branch_name
stringclasses 22
values | content
stringlengths 18
81.8M
| directory_id
stringlengths 40
40
| languages
listlengths 1
36
| num_files
int64 1
7.38k
| repo_language
stringclasses 151
values | repo_name
stringlengths 7
101
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>mail2sandeepd/Ansible<file_sep>/README.md
# Ansible
Install application/rpm using Ansible on single or multiple hosts.
It's all about ansible project and sample files of ansible, by the help of this file you can download and install any package
which you want to install and start and enable the service as well by just replacing few things as below.
<package name>
<service name>
<URL from we have to download package>
|
c5a6e0880b05a3a0adc96c5bc65afd4ad4ea245c
|
[
"Markdown"
] | 1 |
Markdown
|
mail2sandeepd/Ansible
|
e6b9900d64c6a9c0d52e73e74aaa39b0783c6986
|
bc99f420ed69e5cd2e5af76412367761cd6776d6
|
refs/heads/main
|
<repo_name>Alien777/msg<file_sep>/src/main/java/pl/lasota/msg/HazelcastBrokerConfigure.java
package pl.lasota.msg;
import com.hazelcast.topic.ITopic;
public class HazelcastBrokerConfigure<M> implements Configure<M> {
private final ITopic<Message<M>> tr;
public HazelcastBrokerConfigure(ITopic<Message<M>> tr) {
this.tr = tr;
}
@Override
public void onBroker(M m, String from) {
tr.publish(new Message<>(m, from));
}
@Override
public void onBroker(M m, String from, String... to) {
tr.publish(new Message<>(m, from, to));
}
@Override
public void registryLocalBroker(LocalBroker<M> mLocalBroker) {
tr.addMessageListener(message -> {
Message<M> m = message.getMessageObject();
if (m.getTo().length == 0) {
mLocalBroker.onBroker(m.getM(), new User<>(m.getFrom()));
return;
}
mLocalBroker.onBroker(m.getM(), new User<>(m.getFrom()), m.getTo());
});
}
@Override
public void options(Config config) {
}
}
<file_sep>/src/main/java/pl/lasota/msg/SocketBrokerConfigure.java
package pl.lasota.msg;
import com.hazelcast.spi.annotation.Beta;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;
@Beta
public class SocketBrokerConfigure<M> implements Configure<M> {
private LocalBroker<M> mLocalBroker;
private final List<Socket> clients = new LinkedList<>();
public SocketBrokerConfigure(int portServer) throws IOException {
ServerSocket serverSocket = new ServerSocket(portServer);
new Thread(() -> {
try {
Socket accept = serverSocket.accept();
clients.add(accept);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
public void addNode(InetSocketAddress address) throws IOException, ClassNotFoundException {
Socket socket = new Socket(address.getAddress(), address.getPort());
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
while (socket.isConnected()) {
Message<M> m = (Message<M>) objectInputStream.readObject();
if (m.getTo().length == 0) {
mLocalBroker.onBroker(m.getM(), new User<>(m.getFrom()));
continue;
}
mLocalBroker.onBroker(m.getM(), new User<>(m.getFrom()), m.getTo());
}
}
@Override
public void onBroker(M m, String from) {
for (Socket client : clients) {
try {
ObjectOutputStream objectInputStream = new ObjectOutputStream(client.getOutputStream());
objectInputStream.writeObject(new Message<>(m, from));
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onBroker(M m, String from, String... to) {
for (Socket client : clients) {
try {
ObjectOutputStream objectInputStream = new ObjectOutputStream(client.getOutputStream());
objectInputStream.writeObject(new Message<>(m, from, to));
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void registryLocalBroker(LocalBroker<M> mLocalBroker) {
this.mLocalBroker = mLocalBroker;
}
@Override
public void options(Config config) {
config.enableLocalBroker();
}
}
<file_sep>/src/main/java/pl/lasota/msg/Message.java
package pl.lasota.msg;
import java.io.Serializable;
/**
* Online message wrapper
* @param <M>
*/
public class Message<M> implements Serializable {
private M m;
private String from;
private String[] to;
public Message() {
}
public Message(M m, String from) {
this(m, from, new String[0]);
}
public Message(M m, String from, String... to) {
this.m = m;
this.from = from;
this.to = to;
}
public M getM() {
return m;
}
public String getFrom() {
return from;
}
public String[] getTo() {
return to;
}
public void setM(M m) {
this.m = m;
}
public void setFrom(String from) {
this.from = from;
}
public void setTo(String[] to) {
this.to = to;
}
}
<file_sep>/src/main/java/pl/lasota/msg/Main.java
package pl.lasota.msg;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.topic.ITopic;
public class Main {
static User<String> adam;
static User<String> piotrek;
static User<String> kamil;
static User<String> wojtek;
static User<String> sebastian;
static User<String> paulina;
static ReceiverMessageEvent<String> rme = (s, m, f) -> {
System.out.println(m + " od " + f + ": " + s);
};
public static void main(String[] args) {
ITopic<Message<String>> tr = Hazelcast.newHazelcastInstance().getReliableTopic("TR");
serverOne();
serverTwo();
wojtek.sendMessage("WITAJCE");
}
private static void serverTwo() {
ITopic<Message<String>> tr2 = HazelcastClient.newHazelcastClient().getReliableTopic("TR");
HazelcastBrokerConfigure<String> online = new HazelcastBrokerConfigure<>(tr2);
LocalBroker<String> localBroker = new LocalBroker<>();
OnlineBroker<String> onlineBroker = new OnlineBroker<>(localBroker, online);
wojtek = new User<>(onlineBroker, rme, "wojtek");
sebastian = new User<>(onlineBroker, new ReceiverMessageEvent<String>() {
@Override
public void onReceive(String s, User<String> m, String f) {
System.out.println(m + " od " + f + ": " + s);
m.sendMessage("Dostalem wiadomosc od: " + f);
}
}, "sebastian");
paulina = new User<>(onlineBroker, rme, "paulina");
}
private static void serverOne() {
ITopic<Message<String>> tr2 = HazelcastClient.newHazelcastClient().getReliableTopic("TR");
HazelcastBrokerConfigure<String> online = new HazelcastBrokerConfigure<>(tr2);
LocalBroker<String> localBroker = new LocalBroker<>();
OnlineBroker<String> onlineBroker = new OnlineBroker<>(localBroker, online);
adam = new User<>(onlineBroker, rme, "adam");
piotrek = new User<>(onlineBroker, new ReceiverMessageEvent<String>() {
@Override
public void onReceive(String s, User<String> m, String f) {
System.out.println(m + " od " + f + ": " + s);
m.sendMessage("Dostalem wiadomosc od: " + f);
}
}, "piotrek");
kamil = new User<>(onlineBroker, rme, "kamil");
}
}
<file_sep>/src/main/java/pl/lasota/msg/LocalBroker.java
package pl.lasota.msg;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Broker for user registry in single JVM
*
* @param <M>
*/
public class LocalBroker<M> implements Broker<M> {
private final ConcurrentMap<String, User<M>> localUser = new ConcurrentHashMap<>();
@Override
public void onBroker(M m, User<M> from) {
localUser.entrySet().parallelStream()
.filter(us -> !us.getKey().equals(from.id()))
.forEach(us -> us.getValue().receiverMessage(m, from.id()));
}
@Override
public void onBroker(M m, User<M> from, String... to) {
for (String t : to) {
User<M> user = localUser.get(t);
if (user == null) {
break;
}
user.receiverMessage(m, from.id());
}
}
@Override
public void registryUser(User<M> user) throws UserAlreadyRegistryException {
if (localUser.get(user.id()) != null) {
throw new UserAlreadyRegistryException("User is already registered. Please check id.");
}
localUser.put(user.id(), user);
}
@Override
public void removeUser(User<M> id) {
User<M> user = localUser.get(id.id());
localUser.remove(user.id());
}
}
<file_sep>/src/main/java/pl/lasota/msg/User.java
package pl.lasota.msg;
import java.util.Objects;
public class User<M> {
private final Broker<M> broker;
private final ReceiverMessageEvent<M> receiverListener;
private final String id;
public User(String id) {
this.id = id;
this.broker = null;
this.receiverListener = null;
}
public User(Broker<M> broker, ReceiverMessageEvent<M> receiverListener, String id) throws UserAlreadyRegistryException {
this.id = id;
broker.registryUser(this);
this.broker = broker;
this.receiverListener = receiverListener;
}
public void sendMessage(M m) {
if (broker == null) {
return;
}
broker.onBroker(m, this);
}
public void sendMessage(M m, String to) {
if (broker == null) {
return;
}
broker.onBroker(m, this, to);
}
public void sendMessage(M m, String... to) {
if (broker == null) {
return;
}
broker.onBroker(m, this, to);
}
public void receiverMessage(M m, String from) {
if (receiverListener == null) {
return;
}
receiverListener.onReceive(m, this, from);
}
public String id() {
return id;
}
public void logout() {
if (broker == null) {
return;
}
broker.removeUser(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User<?> user = (User<?>) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return id;
}
}
<file_sep>/README.md
# msg
This component provide functionality for distributed message by node or/and user who belong to node.
|
349c7dac8cd81ca7c1cd8c93bdad073ada0b1c32
|
[
"Java",
"Markdown"
] | 7 |
Java
|
Alien777/msg
|
073f66f6ee090adc4f4724812a2d16cdf55374cb
|
9776fde31895068a9f8cbba26250f13dcdb218f9
|
refs/heads/master
|
<repo_name>hannako/Lab_Week<file_sep>/spec/features/booking_a_space_spec.rb
feature "Attempt to book a space" do
before do
sign_in
add_space
click_link "Request to Book"
end
scenario "user can request to book a space" do
fill_in :day, with: "01"
fill_in :month, with: "02"
fill_in :year, with: "03"
click_button "Request"
expect(page).to have_content("Request for Nice Place for 01/02/03 has been sent ")
end
end
<file_sep>/README.md
# Lab Week
## Team:
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>
## Challenge:
Build a mock up of AirBnB.
## Instructions:
Visit https://airbnb99.herokuapp.com/
1. git clone this repository
2. run bundle
3. run rackup to see app on localhost.
# NB: This project is incomplete. Work in Progress.
Project plan:


<file_sep>/app/app.rb
ENV['RACK_ENV'] ||= 'development'
require 'sinatra/base'
require_relative 'data_mapper_setup'
require 'sinatra/flash'
require_relative 'models/request_date'
class AirBnB < Sinatra::Base
use Rack::MethodOverride
register Sinatra::Flash
enable :sessions
set :session_secret, "Harry's Mum"
get '/' do
erb :'index'
end
get '/users/new' do
erb :'users/new'
end
get '/users/sign-in' do
erb :'users/sign-in'
end
post '/sessions' do
user = User.authenticate(params[:username], params[:password])
if user
session[:user_id] = user.id
redirect '/users/spaces'
else
flash.now[:error] = 'Your login details are incorrect'
erb :'users/sign-in'
end
end
post "/users/new" do
user = User.create(username: params[:username],
email: params[:email],
password: params[:password],
password_confirmation: params[:password_confirmation])
if user.save
session[:user_id] = user.id
redirect '/users/spaces'
else
flash.now[:error] = 'User already exists'
erb :'/users/new'
end
end
delete '/sessions' do
session[:user_id] = nil
flash.keep[:notice] = 'goodbye!'
redirect '/'
end
get "/users/spaces" do
@space = Space.all
if Request_date.instance
@request_date = Request_date.instance
# @request_string = @request_date.day + "/" + @request_date.month + "/" + @request_date.year
end
erb :'users/spaces'
end
post "/space/request" do
# space = Space.first(id: params[:id])
# space_name = space.name
space = Space.first(id: params[:id])
name = space.name
day = params[:day]
month = params[:month]
year = params[:year]
date = day + month + year
# requesting = Booking.new(date: date)
# requesting.savelink = Link.new(title: params[:title], url: params[:url])
Request_date.create(day, month, year, name)
redirect 'users/spaces'
end
get "/space/:id" do
space = Space.first(id: params[:id])
@id = params[:id]
@space_name = space.name
@space_description = space.description
@space_price = space.price
erb :space
end
helpers do
def current_user
@current_user ||= User.get(session[:user_id])
end
end
get '/spaces/new' do
erb :create_a_space
end
post '/spaces/temp' do
space = Space.new(name: params[:name],
description: params[:description],
price: params[:price])
space.save
redirect '/users/spaces'
end
# start the server if ruby file executed directly
run! if app_file == $0
end
<file_sep>/tuesday_9_august.md
byte_bnb
[<NAME>, Jess, Francesco, Giancarlo]
# What we learned yesterday:
* CRC
* Waffle
* Setting up a Project
* setting config.ru
# What we are going to do today:
* Diagram
* Feature tests
* Splitting up tasks
* Code classes (afternoon)
# Not looking forward to:
* Diagram
*
<file_sep>/thursday_11_august.md
# byte Thursday
[<NAME>, Jess, Francesco, Giancarlo]
# What we did learned yesterday:
* Sinatra Flash
* Merging Branches with Conflicts
* Rack Overwrite Method (hidden methods)
* Layout page
* Tried Using Ruby code in html
* Implementation Instance Doubles
*
# Continue Implementing User Stories:
* * User Stories
[making a booking, approving a booking]
# Expected problems:
* one to many
* Implementing stories
<file_sep>/monday_8_august.md
## Monday 8 August
[Prashant, Jess, Harry, Francesco, Giancarlo]
# Project Work:
* 9:30-18:00
# Evening Work:
* Personal studies
# Daily Routine:
* Standups 9:30-9:45
* Coding 9:45-12:30
* Retro 12:30-12:45
* Coding 14:00-17:00
* Retro 17:00
# Monday
* CRC
* Waffle
* Learning Goals for the week
# Learning Goals:
* Francesco (attr_readers&accessors, Spies and more Spies,)
* Giancarlo (Consolidating All Material!!!)
* Harry (Databases, Rakefile, Consolidating previous Material, General Ruby definitions, Target attribute in an anchor tab, Diagram Box model, Parameters/Sessions, Ajax )
* Jess (Controllers, Target attribute in an anchor tab, Diagram Box model, 'Sinatra' real world applications vs Heroku, Parameters/Sessions, Interface Segregation Principle, Rakefile, Javascript)
<file_sep>/friday_12_august.md
# Byte Cosa_Nostra
* [Jess,Francesco, Giancarlo, Harry, Prashant]
# What we did yesterday:
* User stories implementations
* Request Booking
# What we are doing today:
* Adding a reservation request date to database
* Box Models
* Request/Booking Model
* Heroku Deployment
# Looking forward to:
* Javascript workshop
<file_sep>/spec/features/listing_spaces_spec.rb
feature "listing spaces" do
scenario "can see spaces" do
visit "/spaces"
expect(page).to_not have_content("Title:")
end
end
<file_sep>/spec/features/user_management_spec.rb
feature 'user sign_up' do
scenario ' user can sign up' do
expect { sign_up }.to change(User, :count).by(1)
expect(page).to have_content('Welcome, user1')
expect(User.first.username).to eq('user1')
end
scenario 'require a matching password' do
expect { sign_up(password_confirmation: 'wrong') }.not_to change(User, :count)
end
scenario 'cannot sign up if email already exists' do
sign_up
expect { sign_up }.not_to change(User, :count)
end
end
feature 'user sign_in' do
let!(:user)do
User.create(email: '<EMAIL>',
username: 'prashant1',
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>')
end
scenario 'with corrent creds' do
sign_in
expect(page).to have_content 'Welcome, prashant1'
end
scenario 'with incorrect creds' do
sign_in(password: '<PASSWORD>')
expect(page).to have_content 'Your login details are incorrect'
end
end
feature 'User signs out' do
before(:each) do
User.create(email: '<EMAIL>',
username: 'prashant1',
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>')
end
scenario 'while being signed in' do
sign_in
click_button 'sign out'
expect(page).to have_content('goodbye!')
expect(page).not_to have_content('Welcome, prashant1')
end
end
<file_sep>/spec/features/create_space_spec.rb
feature "Creation of spaces" do
scenario "creates a space" do
sign_up
click_link "create a space"
fill_in :name, with: "<NAME>"
fill_in :description, with: "Very nice place"
fill_in :price, with: "136.50"
click_button "Create"
expect(page).to have_content("Nice Place")
end
end
<file_sep>/spec/features/web_helper.rb
def sign_up(username: 'user1', email: '<EMAIL>',
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>')
visit '/'
click_button 'sign_up'
fill_in :username, with: username
fill_in :email, with: email
fill_in :password, with: <PASSWORD>
fill_in :password_confirmation, with: <PASSWORD>
click_button 'add_user'
end
def sign_in(username: 'prashant1', password: '<PASSWORD>')
visit '/'
click_button 'sign in'
fill_in :username, with: username
fill_in :password, with: <PASSWORD>
click_button 'submit'
end
def add_space
visit "/users/spaces"
click_link "create a space"
fill_in :name, with: "Nice Place"
fill_in :description, with: "Very nice place"
fill_in :price, with: "136.50"
click_button "Create"
end
<file_sep>/app/models/space.rb
class Space
include DataMapper::Resource
# belongs_to :user, :key => true
property :id, Serial
property :name, String
property :description, String
property :price, Integer
end
<file_sep>/app/models/request_date.rb
class Request_date
attr_reader :day, :month, :year, :name
def initialize(day, month, year, name)
@day = day
@month = month
@year = year
@name = name
end
def self.create(day, month, year, name)
@request_date = Request_date.new(day, month, year, name)
end
def self.instance
@request_date
end
end
<file_sep>/spec/features/reservation_spec.rb
feature "booking a listing" do
scenario "can book for a day" do
sign_up
add_space
click_link "Book"
expect(page).to have_content("Nice Place")
end
end
<file_sep>/app/views/users/spaces.erb
<!DOCTYPE html>
<html>
<h1> Available Rentals </h1>
<head>
</head>
<body>
<a href="/spaces/new">create a space</a>
<!-- <link rel="stylesheet" href="/css/master.css" media="screen" title="no title" charset="utf-8"> -->
<% if Request_date.instance %>
Request for <%= @request_date.name + " for " + @request_date.day + "/" + @request_date.month + "/" + @request_date.year %> has been sent
<% end %>
<dl id='space'>
<% @space.each do |space| %>
<dt>Name: <%= space.name %><br>
<dd>Description: <%= space.description %><br>
<dd>Price: <%= space.price %><br>
<!-- <input type="button" name="name" value="Book" > -->
<a href = "/space/<%= space.id %>" >Request to Book</a>
<% end %>
</dl>
</body>
</html>
<file_sep>/user_stories.md
# landlord Stories BnB
As a user
So that I can use BnB
I would like to be able to sign up
As a landlord with one space
So that I can add a space
I would like to be able to list my space
As a landlord with multiple spaces
So that I can add multiple spaces
I would like to be able to list them all
As a landlord with a space
So that I can add a space
I would like to add a space with a name
As a landlord with a space
So that I can add a space
I would like to add a space with a description
As a landlord with a space
So that I can add a space
I would like to add a space with a price
As a landlord with a space
So that I can rent out a space
I would like to list available dates for rent
As a landlord with a space
So that clients don't double book
I would like to book the space only once
As a landlord with a space
So that i can rent out a space
I would like to authorize the booking
As a landlord with a space
So that I can rent out a space
I would like a space to stay available until booking confirmation
As a signed-up renter
So that I can rent a space
I would like to book for one night
As a signed-up renter
So that I can rent a space
I would like to book for multiple nights
As a signed-up renter
So that I can rent a space
I would like to receive a booking confirmation
<file_sep>/spec/user_spec.rb
describe User do
let!(:user) do
User.create(username: 'prashant1',
email: '<EMAIL>',
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>')
end
it "authenticates when given valid login details" do
authenticated_user = User.authenticate(user.username, user.password)
expect(authenticated_user).to eq user
end
it "does not authenticate when given invalid password" do
bad_user = User.authenticate('prashant1', '<PASSWORD>')
expect(bad_user).to be nil
end
end
|
fbc57488c00ad6f5b3e51671e917fc9a5a6af3a4
|
[
"Markdown",
"Ruby",
"HTML+ERB"
] | 17 |
Markdown
|
hannako/Lab_Week
|
f5ff762811a43f19bf5230b9e086a1b0a3efcaf0
|
731adb2416128e75cfa4130e0de0295c8d97de05
|
refs/heads/master
|
<file_sep>import sys
import os
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from fuel_graphics_scene import *
#MOST COMMENTED OUT FOR DISPLAY PURPOSES
class MainDisplayWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Fuel Price Finder")
self.setInitialLayout()
def setInitialLayout(self):
#create some widgets for a left side test
self.left_label = QLabel("LEFT WIDGET")
self.button_1_left = QPushButton("+")
self.button_2_left = QPushButton("-")
self.left_button = QPushButton("<")
self.up_button = QPushButton("^")
self.right_button = QPushButton(">")
self.down_button = QPushButton("v")
## self.button_3_left = QPushButton("BUTTON3")
## self.button_4_left = QPushButton("BUTTON4")
## #create some widgets for a right side test
## self.right_label = QLabel("RIGHT WIDGET")
## self.button_1_right = QPushButton("BUTTON1")
## self.button_2_right = QPushButton("BUTTON2")
## self.button_3_right = QPushButton("BUTTON3")
## self.button_4_right = QPushButton("BUTTON4")
#add graphics scene
self.middle_graphics = QGraphicsView()
self.graphics_scene = FuelFinderGraphicsScene()
self.middle_graphics.setScene(self.graphics_scene)
self.middle_graphics.setFixedHeight(300)
self.middle_graphics.setFixedWidth(400)
self.middle_graphics.setSceneRect(0,0, 300, 400)
self.middle_graphics.setVerticalScrollBarPolicy(1)
#create layout
self.main_layout = QHBoxLayout()
self.left_layout = QGridLayout()
self.middle_layout = QGridLayout()
self.right_layout = QGridLayout()
#add left test widgets to layout
self.left_layout.addWidget(self.button_1_left, 0, 0)
self.left_layout.addWidget(self.button_2_left, 1, 0)
## self.left_layout.addWidget(self.button_3_left, 1, 0)
## self.left_layout.addWidget(self.button_4_left, 1, 1)
#add right test widgets to layout
## self.right_layout.addWidget(self.button_1_right, 0, 0)
## self.right_layout.addWidget(self.button_2_right, 0, 1)
## self.right_layout.addWidget(self.button_3_right, 1, 0)
## self.right_layout.addWidget(self.button_4_right, 1, 1)
#add graphics to mid
self.middle_layout.addWidget(self.middle_graphics)
#create widgets containing each layout
self.left_widget = QWidget()
self.middle_widget = QWidget()
self.right_widget = QWidget()
#add widgets to corresponding layout
self.left_widget.setLayout(self.left_layout)
self.middle_widget.setLayout(self.middle_layout)
#self.right_widget.setLayout(self.right_layout)
#add widgets to main layout
self.main_layout.addWidget(self.left_widget)
self.main_layout.addWidget(self.middle_widget)
#self.main_layout.addWidget(self.right_widget)
#create main widget and set it as central
self.main_widget = QWidget()
self.main_widget.setLayout(self.main_layout)
self.setCentralWidget(self.main_widget)
def main():
fuel_finder_app = QApplication(sys.argv)
fuel_finder_window = MainDisplayWindow()
fuel_finder_window.show()
fuel_finder_window.raise_()
fuel_finder_app.exec_()
if __name__ == "__main__":
main()
<file_sep>from PyQt4.QtCore import *
from PyQt4.QtGui import *
class FuelFinderGraphicsScene(QGraphicsScene):
def __init__(self):
super().__init__()
self.background_brush = QBrush()
self.background_image = QPixmap("images/background.png")
self.background_brush.setTexture(self.background_image)
self.setBackgroundBrush(self.background_brush)
<file_sep>from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
import sys
import sqlite3
from fuel_finder_interface import *
class FuelDatabase():
def __init__(self):
self.db = QSqlDatabase.addDatabase("QSLITE")
self.db.setDatabaseName("fuel_finder.db")
self.db.open()
def create_tables(self):
sql_list = ["""CREATE TABLE user(userID integer, userName text, password text, userAddress1 text, userAddress2 text, userAddress3 text, userPostcode text, primary key(userID))""",
"""CREATE TABLE owner(ownerID integer, ownerName text, primary key(ownerID))""",
"""CREATE TABLE fuelType(fuelType text, primary key(fuelType))""",
"""CREATE TABLE fuelStation(stationID integer, stationGPS text, stationPostcode text, ownerName text, FOREIGN KEY(ownerName) REFERENCES owner(ownerName), primary key(stationID))""",
"""CREATE TABLE priceTable(priceReading real, userID integer, fuelType text, stationID integer, FOREIGN KEY(userID) REFERENCES user(userID), FOREIGN KEY(fuelType) REFERENCES fuelType(fuelType), FOREIGN KEY(stationID) REFERENCES fuelStation(stationID), primary key(priceReading))"""
]
with sqlite3.connect("fuel_finder.db") as db:
cursor = db.cursor()
for each in sql_list:
cursor.execute(each)
db.commit()
def test_query(self):
sql = """INSERT INTO fuelStation(stationGPS, stationPostcode, ownerName) values("24,24", "CB4 2US", "tesco")"""
with sqlite3.connect("fuel_finder.db") as db:
cursor = db.cursor()
cursor.execute(sql)
db.commit()
if __name__ == "__main__":
app = QApplication(sys.argv)
database = FuelDatabase()
window = MainWindow()
window.show()
window.raise_()
app.exec_()
sql_info = window.get_register_info()
add_user(sql_info)
<file_sep>from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
import sys
import sqlite3
import new_main
from map_interface import *
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
#initialise stacked layout
self.login_layout = QGridLayout()
self.map_layout = QGridLayout()
self.blank = QLabel(" ")
self.register_layout = QGridLayout()
self.set_initial_layout()
self.user_info = {}
def set_initial_layout(self):
self.initial_layout = QHBoxLayout()
self.select_login = QPushButton("\n\n LOGIN \n\n")
self.select_register = QPushButton("\n\n REGISTER \n\n")
#THIS IS TO SKIP THE LOGIN SCREEN BEFORE ITS IMPLEMENTED
self.debug_skip = QPushButton("SKIP - DEBUG")
self.initial_widget = QWidget()
self.initial_layout.addWidget(self.blank)
self.initial_layout.addWidget(self.select_login)
self.initial_layout.addWidget(self.blank)
self.initial_layout.addWidget(self.select_register)
self.initial_layout.addWidget(self.blank)
self.initial_layout.addWidget(self.debug_skip)
self.initial_widget.setLayout(self.initial_layout)
self.setCentralWidget(self.initial_widget)
self.select_login.clicked.connect(self.set_login_layout)
self.select_register.clicked.connect(self.set_register_layout)
self.setFixedSize(600, 480)
self.status = "initial screen"
def set_login_layout(self):
self.submit_button = QPushButton("Login")
self.username_label = QLabel("Username")
self.username_line = QLineEdit()
self.username_line.setMaxLength(10)
self.username_line.setFixedWidth(120)
self.password_label = QLabel("Password")
self.password_line = QLineEdit()
self.password_line.setMaxLength(10)
self.password_line.setFixedWidth(120)
self.password_line.setEchoMode(2)
self.login_layout.addWidget(self.blank, 0 ,0)
self.login_layout.addWidget(self.blank, 1, 0)
self.login_layout.addWidget(self.username_label, 1, 1)
self.login_layout.addWidget(self.username_line, 1, 2)
self.login_layout.addWidget(self.blank, 1, 3)
self.login_layout.addWidget(self.password_label, 3, 1)
self.login_layout.addWidget(self.password_line, 3, 2)
self.login_layout.addWidget(self.blank, 4, 0)
self.login_layout.addWidget(self.submit_button, 4, 1)
self.login_layout.addWidget(self.blank, 4, 2)
self.login_layout.addWidget(self.blank, 5, 0)
self.login_widget = QWidget()
self.login_widget.setLayout(self.login_layout)
self.setCentralWidget(self.login_widget)
self.setFixedSize(600, 480)
self.status = "login screen"
def set_register_layout(self):
self.reg_layout = QGridLayout()
self.setFixedSize(600, 480)
#defining labels
self.username_reg_label = QLabel(" Username")
self.password_reg_label = QLabel(" <PASSWORD>")
self.address1_reg_label = QLabel("Address 1")
self.address2_reg_label = QLabel("Address 2")
self.address3_reg_label = QLabel("Address 3")
self.postcode_reg_label = QLabel(" Postcode")
#defining line edits
self.username_reg_line = QLineEdit()
self.password_reg_line = QLineEdit()
self.address1_reg_line = QLineEdit()
self.address2_reg_line = QLineEdit()
self.address3_reg_line = QLineEdit()
self.postcode_reg_line = QLineEdit()
self.reg_lines_list = [self.username_reg_line, self.password_reg_line, self.address1_reg_line,
self.address2_reg_line, self.address3_reg_line, self.postcode_reg_line]
#buttons
self.register_button = QPushButton("Register")
self.clear_reg_button = QPushButton("Clear")
#validation and formatting
self.username_reg_line.setMaxLength(10)
self.password_reg_line.setMaxLength(10)
self.password_reg_line.setEchoMode(2)
#adding to layout
self.reg_layout.addWidget(self.blank, 0, 0)
self.reg_layout.addWidget(self.username_reg_label, 1, 1)
self.reg_layout.addWidget(self.username_reg_line, 1, 2)
self.reg_layout.addWidget(self.password_reg_label, 2, 1)
self.reg_layout.addWidget(self.password_reg_line, 2, 2)
self.reg_layout.addWidget(self.address1_reg_label, 3, 1)
self.reg_layout.addWidget(self.address1_reg_line, 3, 2)
self.reg_layout.addWidget(self.address2_reg_label, 4, 1)
self.reg_layout.addWidget(self.address2_reg_line, 4, 2)
self.reg_layout.addWidget(self.address3_reg_label, 5, 1)
self.reg_layout.addWidget(self.address3_reg_line, 5, 2)
self.reg_layout.addWidget(self.postcode_reg_label, 6, 1)
self.reg_layout.addWidget(self.postcode_reg_line, 6, 2)
self.reg_layout.addWidget(self.register_button, 8, 2)
self.reg_layout.addWidget(self.clear_reg_button, 8, 3)
self.reg_layout.addWidget(self.blank)
self.register_widget = QWidget()
self.register_widget.setLayout(self.reg_layout)
self.setCentralWidget(self.register_widget)
self.status = "register screen"
#connected to popup for testing
self.register_button.clicked.connect(self.get_register_info)
self.clear_reg_button.clicked.connect(self.clear_register_text)
def get_register_info(self):
#getting info from lineedits for adding to database
username_info = self.username_reg_line.text()
password_info = self.password_reg_line.text()
address1_info = self.address1_reg_line.text()
address2_info = self.address2_reg_line.text()
address3_info = self.address3_reg_line.text()
postcode_info = self.postcode_reg_line.text()
self.user_info = {'username': username_info, 'password': <PASSWORD>, 'address1': address1_info,
'address2': address2_info, 'address3': address3_info, 'postcode': postcode_info}
print(self.user_info['username'])
print(self.user_info['password'])
print(self.user_info['address1'])
print(self.user_info['address2'])
print(self.user_info['address3'])
print(self.user_info['postcode'])
validation_name = len(self.user_info['username'])
validation_pass = len(self.user_info['password'])
if validation_name != 0 and validation_pass != 0:
self.add_user()
else:
print("Not valid, check length of username/password")
self.user_details_popup()
def clear_register_text(self):
for each in self.reg_lines_list:
each.setText("")
def add_user(self):
sql = "INSERT INTO user(userName, password, userAddress1, userAddress2, userAddress3, userPostcode) values(?, ?, ?, ?, ?, ?)"
data = (self.user_info['username'], self.user_info['password'],self.user_info['address1'], self.user_info['address2'],
self.user_info['address3'], self.user_info['postcode'])
with sqlite3.connect("fuel_finder.db") as db:
cursor = db.cursor()
cursor.execute(sql, data)
db.commit()
self.set_initial_layout()
def user_details_popup(self):
popup = DetailsPopup()
popup.show()
popup.raise_()
def set_map_layout(self, map_interface):
self.map_layout = QHBoxLayout()
self.map_layout.addWidget(map_interface)
widget = QWidget()
widget.setLayout(self.map_layout)
self.setFixedSize(800, 600)
self.setCentralWidget(widget)
class DetailsPopup(QDialog):
def __init__(self):
super().__init__()
#dialog box for user seeing their details
self.username_label = QLabel("Username")
self.address1_label = QLabel("Address 1")
self.address2_label = QLabel("Address 2")
self.address3_label = QLabel("Address 3")
self.postcode_label = QLabel("Postcode")
self.password_recover_label = QLabel("<PASSWORD>ten your password?")
self.username_line = QLineEdit()
self.username_line.setText("Test username")
self.address1_line = QLineEdit()
self.address1_line.setText("Test address 1")
self.address2_line = QLineEdit()
self.address2_line.setText("Test address 2")
self.address3_line = QLineEdit()
self.address3_line.setText("Test address 3")
self.postcode_line = QLineEdit()
self.postcode_line.setText("Test Postcode")
self.line_edit_list = [self.username_line, self.address1_line,
self.address2_line, self.address3_line,
self.postcode_line]
self.layout = QGridLayout()
self.layout.addWidget(self.username_label, 0 , 0)
self.layout.addWidget(self.username_line, 0, 1)
self.layout.addWidget(self.address1_label, 1, 0)
self.layout.addWidget(self.address1_line, 1, 1)
self.layout.addWidget(self.address2_label, 2, 0)
self.layout.addWidget(self.address2_line, 2, 1)
self.layout.addWidget(self.address3_label, 3, 0)
self.layout.addWidget(self.address3_line, 3, 1)
self.layout.addWidget(self.postcode_label, 4, 0)
self.layout.addWidget(self.postcode_line, 4, 1)
for each in self.line_edit_list:
each.setReadOnly(True)
self.setLayout(self.layout)
self.exec_()
#handles loading of webpage maps
class MapHTML(QWebView):
def __init__(self, mode):
#constructed with a "mode" parameter to switch between test and final urls
super().__init__()
if mode == "final":
self.url = QUrl("maps.html")
elif mode == "test":
self.url = QUrl("test_maps.html")
else:
print("invalid mode value provided")
self.load_status = self.loadFinished.connect(self.onLoadFinished)
self.load_map()
def load_map(self):
self.load(self.url)
def status(self):
if self.load_status == True:
print("page loaded successfully.")
else:
print("page load failed.")
def onLoadFinished(self):
print("load of {0} finished.".format(self.url.toString()))
self.load_status = True
class LoadingBar(QProgressBar):
def __init__(self):
super().__init__()
self.setRange(1, 1000)
for progress in range(1, 1001):
self.setValue(progress)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
window.raise_()
app.exec_()
<file_sep>import sys
import os
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from fuel_finder_interface import *
from database_handling import *
from map_interface import *
current_user = ""
def load_initial_screen():
print("Current screen: initial")
window.set_initial_layout()
def load_login_screen():
print("Current screen: login")
window.set_login_layout()
def load_register_screen():
print("Current screen: register")
window.set_register_layout()
def load_map_interface(current_user):
map_interface = Map([1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18],[19,20,21],[21,22,23],[24,25,26])
window.set_map_layout(map_interface)
print("༼ ᕤ◕◡◕ ༽ᕤ PUNCH BUGS")
def test_loading_bar():
loadbar = LoadingBar()
window.setCentralWidget(loadbar)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
#window.select_login.clicked.connect(load_map_interface)
window.debug_skip.clicked.connect(load_map_interface)
#window.select_login.clicked.connect(test_loading_bar)
window.raise_()
window.show()
app.exec_()
<file_sep>from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
import sys
class GoogleView(QMainWindow):
def __init__(self):
super().__init__()
self.html_view = QWebView()
url1 = "https://developers.google.com/maps/documentation/javascript/tutorial"
url2 = "file:///U:/A2%20Computing/fuel_finder_1-master/initial_google.html"
url3 = "/Users/natalierobinson/Documents/Luke/fuel_finder_1-master/custom_google_test.html"
#self.url = QUrl("file:///U:/A2%20Computing/fuel_finder_1-master/custom_google_test.html")
self.url = QUrl("custom_google_test.html")
self.html_view.load(self.url)
self.initial_layout = QVBoxLayout()
self.initial_layout.addWidget(self.html_view)
self.main_widget = QWidget()
self.main_widget.setLayout(self.initial_layout)
self.setCentralWidget(self.main_widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = GoogleView()
window.show()
window.raise_()
app.exec_()
<file_sep>from PyQt4.QtWebKit import QWebView
class Map(QWebView):
def __init__(self, station1_list, station2_list, station3_list, station4_list, station5_list, station6_list, station7_list, station8_list, station9_list):
super().__init__()
self.station1_unleaded = 100
self.station1_diesel = 200
self.station1_other = 300
#this may not be a good idea but I'm gonna do it anyway
self.page_html = """<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Custom controls</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
var cambridge = new google.maps.LatLng(52.2204385435938, 0.0995635986328125);
var coords = ''
/**
* The HomeControl adds a control to the map that simply
* returns the user to Chicago. This constructor takes
* the control DIV as an argument.
* @constructor
*/
function HomeControl(controlDiv, map) {
// Set CSS styles for the DIV containing the control
// Setting padding to 5 px will offset the control
// from the edge of the map
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to set the map to Home';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('div');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '12px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = '<b>Home</b>';
controlUI.appendChild(controlText);
// Setup the click event listeners: simply set the map to
// Chicago
google.maps.event.addDomListener(controlUI, 'click', function() {
map.setCenter(cambridge)
});
}
function initialize() {
var mapDiv = document.getElementById('map-canvas');
var mapOptions = {
zoom: 12,
center: cambridge
};
var map = new google.maps.Map(mapDiv, mapOptions);
var stationLatlng = new google.maps.LatLng(52.21328333333334, 0.13665);
var marker1 = new google.maps.Marker({
position: stationLatlng,
map: map,
animation: google.maps.Animation.DROP,
title: 'Elizabeth Way BP',
});
var info1 = new google.maps.InfoWindow({
content: "<h3>Marker1</h3> <p>Unleaded: """ + str(station1_list[0]) + """ </p> <p>Diesel: """ + str(station1_list[1]) + """ </p> <p>other: """ + str(station1_list[2]) + """ </p>"
});
var station2Latlng = new google.maps.LatLng(52.21946247877899, 0.11142432689666748);
var marker2 = new google.maps.Marker({
position : station2Latlng,
map: map,
title: '<NAME>'
});
var info2 = new google.maps.InfoWindow({
content: "<h3>Marker2</h3> <p>Unleaded: """ + str(station2_list[0]) + """ </p> <p>Diesel: """ + str(station2_list[1]) + """ </p> <p>Other: """ + str(station2_list[2]) + """</p>"
});
var station3Latlng = new google.maps.LatLng(52.198414356177594, 0.11321067810058594);
var marker3 = new google.maps.Marker({
position : station3Latlng,
map : map,
title : 'Newnham Rd Station Shell'
});
var info3 = new google.maps.InfoWindow({
content: "<h3>Marker3</h3> <p>Unleaded: """ + str(station3_list[0]) + """ </p> <p>Diesel: """ + str(station3_list[1]) + """ </p> <p>Other: """ + str(station3_list[2]) + """ </p>"
});
var station4Latlng = new google.maps.LatLng(52.20019806415637, 0.15837907791137695);
var marker4 = new google.maps.Marker({
position : station4Latlng,
map : map,
title: "Brooks Rd, Sainsbury's"
});
var info4 = new google.maps.InfoWindow({
content: "<h3>Marker4</h3> <p>Unleaded: """ + str(station4_list[0]) + """ </p> <p>Diesel: """ + str(station4_list[1]) + """ </p> <p>Other: """ + str(station4_list[2]) + """ </p>"
});
var station5Latlng = new google.maps.LatLng(52.21112726046464, 0.18126368522644043);
var marker5 = new google.maps.Marker({
position : station5Latlng,
map : map,
title: "Newmarket Rd, Shell"
});
var info5 = new google.maps.InfoWindow({
content: "<h3>Marker5</h3> <p>Unleaded: """ + str(station5_list[0]) + """ </p> <p>Diesel: """ + str(station5_list[1]) + """ </p> <p>Other: """ + str(station5_list[2]) + """ </p>"
});
var station6Latlng = new google.maps.LatLng(52.17321450649969, 0.11265009641647339);
var marker6 = new google.maps.Marker({
position : station6Latlng,
map : map,
title: "Trumpington, 56 High Street, Shell"
});
var info6 = new google.maps.InfoWindow({
content: "<h3>Marker6</h3> <p>Unleaded: """ + str(station6_list[0]) + """ </p> <p>Diesel: """ + str(station6_list[1]) + """ </p> <p>Other: """ + str(station6_list[2]) + """ </p>"
});
var station7Latlng = new google.maps.LatLng(52.238283272894094, 0.15647470951080322);
var marker7 = new google.maps.Marker({
position : station7Latlng,
map : map,
title: "Tesco Milton, Tesco"
});
var info7 = new google.maps.InfoWindow({
content: "<h3>Marker7</h3> <p>Unleaded: """ + str(station7_list[0]) + """ </p> <p>Diesel: """ + str(station7_list[1]) + """ </p> <p>Other: """ + str(station7_list[2]) + """ </p>"
});
var station8Latlng = new google.maps.LatLng(52.25520301641985, 0.019676685333251953);
var marker8 = new google.maps.Marker({
position : station8Latlng,
map : map,
title: "Tesco Bar Hill, Tesco"
});
var info8 = new google.maps.InfoWindow({
content: "<h3>Marker8</h3> <p>Unleaded: """ + str(station8_list[0]) + """ </p> <p>Diesel: """ + str(station8_list[1]) + """ </p> <p>Other: """ + str(station8_list[2]) + """ </p>"
});
var station9Latlng = new google.maps.LatLng(52.18553665582424, 0.1605302095413208);
var marker9 = new google.maps.Marker({
position : station9Latlng,
map : map,
title: "Cherry Hinton Rd, BP"
});
var info9 = new google.maps.InfoWindow({
content: "<h3>Marker9</h3> <p>Unleaded: """ + str(station9_list[0]) + """ </p> <p>Diesel: """ + str(station9_list[1]) + """ </p> <p>Other: """ + str(station9_list[2]) + """ </p>"
});
// Create the DIV to hold the control and
// call the HomeControl() constructor passing
// in this DIV.
var homeControlDiv = document.createElement('div');
var homeControl = new HomeControl(homeControlDiv, map);
marker1.setAnimation(google.maps.Animation.DROP)
marker1.setAnimation(google.maps.Animation.BOUNCE)
//javascript:void(prompt('',gApplication.getMap().getCenter())); USE THIS TO GET CENTRES OF GOOGLE MAPS PAGES
//http://forums.gpsreview.net/viewtopic.php?t=3632
//MARKER INFOWINDOWS
google.maps.event.addListener(marker1, 'click', function(){
info1.open(map, marker1);
});
google.maps.event.addListener(marker2, 'click', function(){
info2.open(map, marker2)
});
google.maps.event.addListener(marker3, 'click', function(){
info3.open(map, marker3)
});
google.maps.event.addListener(marker4, 'click', function(){
info4.open(map, marker4)
});
google.maps.event.addListener(marker5, 'click', function(){
info5.open(map, marker5)
});
google.maps.event.addListener(marker6, 'click', function(){
info6.open(map, marker6)
});
google.maps.event.addListener(marker7, 'click', function(){
info7.open(map, marker7)
});
google.maps.event.addListener(marker8, 'click', function(){
info8.open(map, marker8)
});
google.maps.event.addListener(marker9, 'click', function(){
info9.open(map, marker9)
});
homeControlDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>"""
#self.page_html.format(str(self.station1_unleaded), str(self.station1_diesel), str(self.station1_other))
self.setHtml(self.page_html)
|
fdb253a609b955edf14d815952650266aff4a3bc
|
[
"Python"
] | 7 |
Python
|
LumenLTE/fuel_finder
|
ae55cf7925cf1288fb5e5570f8a9d8e459c3eef0
|
ede55227b1684bb79cd8e78af7de49d5ee53bdea
|
refs/heads/master
|
<repo_name>ht1121/Chess-Machine-Learning<file_sep>/README.md
# Chess-Machine-Learning
|
6735dbb8bdc3730c296d1dfb0f9a23dce3bbbdb6
|
[
"Markdown"
] | 1 |
Markdown
|
ht1121/Chess-Machine-Learning
|
2497ae4ab9244025e74046b9769b3a1c83787b4c
|
3e24dd6473e738e4407b292695806313d484ba3b
|
refs/heads/master
|
<repo_name>RobinSrimal/cs-module-project-iterative-sorting<file_sep>/src/iterative_sorting/iterative_sorting.py
# TO-DO: Complete the selection_sort() function below
def swapPositions(list, pos1, pos2):
# popping both the elements from list
first_ele = list.pop(pos1)
second_ele = list.pop(pos2-1)
# inserting in each others positions
list.insert(pos1, second_ele)
list.insert(pos2, first_ele)
return list
def selection_sort(arr):
if len(arr) < 2:
return arr
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
for t in range(cur_index, len(arr)):
if arr[t] < arr[smallest_index]:
smallest_index = t
if cur_index == smallest_index:
continue
else:
swapPositions(arr, cur_index, smallest_index)
return arr
# TO-DO: implement the Bubble Sort function below
def swap(arr, pos):
element = arr.pop(pos)
arr.insert(pos + 1, element)
return arr
def bubble_sort(arr):
# Your code here
if len(arr) < 2:
return arr
switch = True
while switch:
counter = 0
for i in range(len(arr) -1):
if arr[i] > arr[i + 1]:
swap(arr, i)
counter += 1
if counter == 0:
switch = False
return arr
'''
STRETCH: implement the Count Sort function below
Counting sort is a sorting algorithm that works on a set of data where
we specifically know the maximum value that can exist in that set of
data. The idea behind this algorithm then is that we can create "buckets"
from 0 up to the max value. This is most easily done by initializing an
array of 0s whose length is the max value + 1 (why do we need this "+ 1"?).
Each buckets[i] then is responsible for keeping track of how many times
we've seen `i` in the input set of data as we iterate through it.
Once we know exactly how many times each piece of data in the input set
showed up, we can construct a sorted set of the input data from the
buckets.
What is the time and space complexity of the counting sort algorithm?
'''
def counting_sort(arr, maximum=None):
# Your code here
return arr
|
a7de8151b06a9cc9a2be4f5b8093f1cc063ccd2c
|
[
"Python"
] | 1 |
Python
|
RobinSrimal/cs-module-project-iterative-sorting
|
c690802c7a57197c398f0c745a56dfcedef00a27
|
ebaed2942ba885ea60f33cc2ab87f1b1d91f7ca4
|
refs/heads/master
|
<file_sep>$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'directors_database'
p directors_database
def directors_totals(nds)
hash = {}
hash
end
def print_first_directors_movie_titles
row_index = 0
while row_index < 1 do
inner_row_index = 0
while inner_row_index < directors_database[row_index][:movies].length do
puts directors_database[row_index][:movies][inner_row_index][:title]
inner_row_index += 1
end
row_index += 1
end
end
<file_sep>$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'directors_database'
def directors_totals(nds)
array = []
row_index = 0
while row_index < directors_database.length do
array << directors_database[row_index][:name]
grosses_per_director = 0
inner_array = []
inner_row_index = 0
while inner_row_index < directors_database[row_index][:movies].length do
grosses_per_director += directors_database[row_index][:movies][inner_row_index][:worldwide_gross]
inner_array << grosses_per_director
inner_row_index += 1
end
array << inner_array.max
row_index += 1
end
new_array = []
string_array = []
integer_array = []
index = 0
while index < array.length do
if array[index].class == String
string_array << array[index]
elsif array[index].class == Integer
integer_array << array[index]
end
new_array << string_array || integer_array
index += 1
end
hash = {
"<NAME>" => 1357566430
}
hash_index = 0
while hash_index < string_array.length do
hash[string_array[hash_index]] = integer_array[hash_index]
hash_index += 1
end
hash
end
p directors_totals(directors_database)
# Remember, it's always OK to pretty print what you get *in* to make sure
# that you know what you're starting with!
#
#
# The Hash result be full of things like "<NAME>" => "222312123123"
result = {
}
#
# Use loops, variables and the accessing method, [], to loop through the NDS
# and total up all the
# ...
# ...
# ...
#
#
# Be sure to return the result at the end!
|
2db64f1a05473e9647633a68f883b02aabd4aa11
|
[
"Ruby"
] | 2 |
Ruby
|
JulianCedric/programming-univbasics-nds-nds-to-insight-raw-brackets-lab-nyc-web-030920
|
fb43f374ad12afed4d91cbd1d868981c65590816
|
9dba9a665b226bbfe29088b8a967c2409d7a31ca
|
refs/heads/master
|
<repo_name>uzimahealth/UzimaHealthAndroidApp<file_sep>/nbproject/project.properties
file.reference.app4-www=www
files.encoding=UTF-8
site.root.folder=${file.reference.app4-www}
source.folder=
<file_sep>/README.md
# Uzima Health Android App
This is the first Open source release of the Uzima Health Android App.<file_sep>/nbproject/private/private.properties
auxiliary.org-netbeans-modules-javascript-karma.enabled=true
browser=Chrome.INTEGRATED
<file_sep>/src/pages/Response/Response.ts
import { Component } from '@angular/core';
import { PopoverController } from 'ionic-angular';
import { PopoverPage } from '../about-popover/about-popover';
import {Headers, Http, RequestOptions} from '@angular/http';
@Component({
selector: 'page-response',
templateUrl: 'Response.html'
})
export class ResponsePage {
public responseitems: any = [];
constructor(public popoverCtrl: PopoverController,private http:Http) {
this.http.get('http://192.168.3.11/ecare/webservice/get/getresponse.php').map(res => res.json()).subscribe(data => {
this.responseitems = data;
});
}
presentPopover(event: Event) {
let popover = this.popoverCtrl.create(PopoverPage);
popover.present({ ev: event });
}
}
<file_sep>/src/pages/Ambulance/Ambulance.ts
import { Component } from '@angular/core';
import { PopoverController } from 'ionic-angular';
import {Headers, Http, RequestOptions} from '@angular/http';
import {Platform, NavController} from 'ionic-angular';
import { PopoverPage } from '../about-popover/about-popover';
import { SpeakerListPage } from '../speaker-list/speaker-list';
import { Storage } from '@ionic/storage';
@Component({
selector: 'page-Ambulance',
templateUrl: 'Ambulance.html'
})
export class AmbulancePage {
public ambulance: any = {};
public nav: NavController;
public userId=0;
constructor(public popoverCtrl: PopoverController, private http:Http, nav: NavController,public storage: Storage) {
this.nav = nav;
this.getUserId();
}
getUserId(): Promise<string> {
return this.storage.get('userId').then((value) => {
this.userId=value;
return value;
});
};
presentPopover(event: Event) {
let popover = this.popoverCtrl.create(PopoverPage);
popover.present({ ev: event });
}
onAmbulance() {
let url = "http://13.58.203.26/ecare/webservice/post/request_ambulance.php";
let body = "patientId="+this.userId;
var headers = new Headers()
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
return this.http.post(url, body,options) .map(res => res.json()).subscribe(
data => {
alert(data.results);
this.nav.push(SpeakerListPage, {});
},
err => {
alert("An error occurred");
this.nav.push(SpeakerListPage, {});
}
);
}
}<file_sep>/src/pages/login/login.ts
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import {Headers, Http, RequestOptions} from '@angular/http';
import { NavController } from 'ionic-angular';
import { UserData } from '../../providers/user-data';
import { UserOptions } from '../../interfaces/user-options';
import { TabsPage } from '../tabs-page/tabs-page';
import { SignupPage } from '../signup/signup';
@Component({
selector: 'page-user',
templateUrl: 'login.html'
})
export class LoginPage {
public login: UserOptions = { username: '', password: '' };
submitted = false;
constructor(public navCtrl: NavController, private http:Http, public userData: UserData) { }
onLogin(form: NgForm) {
this.submitted = true;
if (form.valid) {
let url = "http://13.58.203.26/ecare/webservice/get/login_user.php";
let body = "username=" +this.login.username+"&password="+this.login.password;
var headers = new Headers()
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
return this.http.post(url, body,options) .map(res => res.json()).subscribe(
data => {
if (data === undefined || data.length == 0) {
alert("username and password is wrong");
}
else {
// array empty or does not exist
this.userData.login(this.login.username,data[0].id);
this.navCtrl.push(TabsPage);
}
},
err => {
alert("An error occurred");
}
);
}
}
onSignup() {
this.navCtrl.push(SignupPage);
}
}
<file_sep>/src/pages/Nurse/Nurse.ts
import { Component } from '@angular/core';
import { PopoverController } from 'ionic-angular';
import {Headers, Http, RequestOptions} from '@angular/http';
import {Platform, NavController} from 'ionic-angular';
import { PopoverPage } from '../about-popover/about-popover';
import { SpeakerListPage } from '../speaker-list/speaker-list';
import { Storage } from '@ionic/storage';
@Component({
selector: 'page-Nurse',
templateUrl: 'Nurse.html'
})
export class NursePage {
public nurse: any ={};
public nav: NavController;
public userId=0;
constructor(public popoverCtrl: PopoverController, private http:Http, nav: NavController,public storage: Storage) {
this.nav = nav;
this.getUserId();
}
getUserId(): Promise<string> {
return this.storage.get('userId').then((value) => {
this.userId=value;
return value;
});
};
presentPopover(event: Event) {
let popover = this.popoverCtrl.create(PopoverPage);
popover.present({ ev: event });
}
onNurse()
{
let url = "http://13.58.203.26/ecare/webservice/post/request_nurse.php";
let body = "county="+this.nurse.county+"&town="+this.nurse.town+"&reason="+this.nurse.reason+"&gender="+this.nurse.gender+"&other="+this.nurse.other+"&firstname="+this.nurse.firstname+"&surname="+this.nurse.surname+"&street="+this.nurse.street+"&building="+this.nurse.building+"&landmark="+this.nurse.landmark+"&floor="+this.nurse.floor+
"&phone="+this.nurse.phone+"&date="+this.nurse.date+"&patientId="+this.userId;
var headers = new Headers()
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
return this.http.post(url, body,options) .map(res => res.json()).subscribe(
data => {
alert(data.results);
this.nav.push(SpeakerListPage, {});
},
err => {
alert("An error occurred");
this.nav.push(SpeakerListPage, {});
}
);
}
}<file_sep>/src/pages/tutorial/tutorial.html
<ion-header no-border>
<ion-navbar>
<ion-buttons end *ngIf="showSkip">
<button ion-button (click)="startApp()" color="primary">Skip</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content no-bounce>
<ion-slides #slides (ionSlideWillChange)="onSlideChangeStart($event)" pager>
<ion-slide>
<img src="assets/img/ica-slidebox-img-1.png" class="slide-image"/>
<h2 class="slide-title">
Welcome to <font color ="blue" type="bold">Uzima Health</font>
</h2>
<p>
<b>Your Ultimate Health Care Assistant</b>
</p>
</ion-slide>
<ion-slide>
<img src="assets/img/ica-slidebox-img-2.png" class="slide-image"/>
<h2 class="slide-title" >What is Uzima Health?</h2>
<p><b>Uzima Health</b> enables you to be able to share your health and medical condition history with your Doctor from the comfort of your mobile phone.</p>
</ion-slide>
<ion-slide>
<img src="assets/img/ica-slidebox-img-2.png" class="slide-image"/>
<h2 class="slide-title">How do i use it?</h2>
<p><b>Sign up for your account and register with your hospital </b>Once you have signed up you can edit your profile and be able to select the services you require</p>
</ion-slide>
<ion-slide>
<img src="assets/img/ica-slidebox-img-2.png" class="slide-image"/>
<p><b>How do i contact the hospital using the app?</b></p>
<p>in our contact us page you can be able to find our various contacts for our different branches</p>
</ion-slide>
<ion-slide>
<img src="assets/img/ica-slidebox-img-4.png" class="slide-image"/>
<h2 class="slide-title">Ready to use the app?</h2>
<button ion-button icon-end large clear (click)="startApp()">
Continue
<ion-icon name="arrow-forward"></ion-icon>
</button>
</ion-slide>
</ion-slides>
</ion-content>
<file_sep>/src/pages/signup/signup.ts
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import {Headers, Http, RequestOptions} from '@angular/http';
import { NavController } from 'ionic-angular';
import { UserData } from '../../providers/user-data';
import { UserOptions } from '../../interfaces/user-options';
import { TabsPage } from '../tabs-page/tabs-page';
import { LoginPage } from '../login/login';
@Component({
selector: 'page-user',
templateUrl: 'signup.html'
})
export class SignupPage {
public signup: UserOptions = { username: '', password: '' };
submitted = false;
public signup2: any = {};
constructor(public navCtrl: NavController, public userData: UserData, private http:Http) {}
onSignup(form: NgForm) {
let url = "http://192.168.127.12/ecare/webservice/post/register_user.php";
let body = "county=" +this.signup2.county+"&town="+this.signup2.town+"&firstname="+this.signup2.firstname+"&surname="+this.signup2.surname+"&street="+this.signup2.street+"&building="+this.signup2.building+"&landmark="+this.signup2.landmark+
"&phone="+this.signup2.phone+"&username="+this.signup.username+"&password="+this.signup.password
+"&email="+this.signup2.email;
var headers = new Headers()
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
return this.http.post(url, body,options) .map(res => res.json()).subscribe(
data => {
this.submitted = true;
alert(data.results);
//this.userData.signup(this.signup.username);
//this.navCtrl.push(TabsPage);
this.navCtrl.push(LoginPage);
},
err => {
alert("An error occurred");
}
);
}
}
|
6ba2ec11fb53494914d16f7a212b41560783ab8e
|
[
"Markdown",
"TypeScript",
"HTML",
"INI"
] | 9 |
Markdown
|
uzimahealth/UzimaHealthAndroidApp
|
328631d06ea7e511d666b5a86fae7534aa4736f7
|
a63dc5b0f940408c728cea6eaebe6e66f730f4a9
|
refs/heads/master
|
<file_sep>package sg.edu.rp.c346.id18014854.demoemployeeinfo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView lvEmployee;
ArrayList<Employee> employeeList;
CustomAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvEmployee = findViewById(R.id.listViewEmployee);
employeeList = new ArrayList<>();
Employee person1 = new Employee("John", "Software Technical Leader", 3400.0);
Employee person2 = new Employee("May", "Programmer", 2200.0);
employeeList.add(person1);
employeeList.add(person2);
adapter = new CustomAdapter(this,R.layout.row,employeeList);
lvEmployee.setAdapter(adapter);
}
}
<file_sep>rootProject.name='Demo Employee Info'
include ':app'
|
7e06d72cb4bd56494666e42873c782b26496c162
|
[
"Java",
"Gradle"
] | 2 |
Java
|
18014854/Demo_Employee_Info_PS_2
|
3e306603621690ba17063041459f91a61b7ed5c2
|
1793a3917e8e34efda3a271ce6f84cb90541db5e
|
refs/heads/main
|
<repo_name>Mihail-Makei/Differentiator<file_sep>/Operator.h
#include "Config.h"
#include "MyTree.h"
#define FREELEFT free(node->left);\
node->left = nullptr;
#define FREERIGHT free(node->right);\
node->right = nullptr;
#define CONSTTYPE node->data.type = CONST;
#define OPERATORFILL(a) NodeFill(temp, OPERATORCODE, a);
#define NODETEMP NodeLeft(temp, leftnode);\
NodeRight(temp, rightnode);
#define MEMEPRINT(arg) fprintf(fout, arg);\
fprintf(fout, "\\begin{equation}\n");\
fprintf(fout, "\\[");\
tempone = temp;\
printf("TEMPONE\t%lf\n", tempone->data.data);\
\
while (tempone->parent != nullptr)\
{\
tempcpy = tempone->parent;\
tempone = tempcpy;\
printf("TEMPTWO\t%lf\n", tempone->right->data.data);\
}\
\
\
TeXExport(fout, tempone);\
\
fprintf(fout, "\\]\n");\
fprintf(fout, "\\end{equation}\n\n");
/***********************************************************************************************************************/
OPERATOR(+, PLUS,
{
node->data.data = node->left->data.data + node->right->data.data;
CONSTTYPE;
FREELEFT;
FREERIGHT;
},
{
NodeFill(temp, OPERATORCODE, PLUS);
node_t* leftnode = TreeDiff(node->left);
node_t* rightnode = TreeDiff(node->right);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
return temp;
},
{
OPERATORFILL(PLUS);
node_t* leftnode = NodeCopy(node->left);
node_t* rightnode = NodeCopy(node->right);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
fprintf(fout, "COPY\n");
MEMEPRINT("Let's consider the following part of equation\n\n");
node_t* left = TreeMemes(fout, node->left);
node_t* right = TreeMemes(fout, node->right);
NodeLeft(temp, left);
NodeRight(temp, right);
MEMEPRINT("After, to be honest, pretty difficult transformations we get\n\n");
})
OPERATOR(-, MINUS,
{
node->data.data = node->left->data.data - node->right->data.data;
node->data.type = CONST;
free(node->left);
node->left = nullptr;
free(node->right);
node->right = nullptr;
},
{
NodeFill(temp, OPERATORCODE, MINUS);
node_t* leftnode = TreeDiff(node->left);
node_t* rightnode = TreeDiff(node->right);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
//return temp;
},
{
OPERATORFILL(MINUS);
node_t* leftnode = NodeCopy(node->left);
node_t* rightnode = NodeCopy(node->right);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
fprintf(fout, "COPY\n");
MEMEPRINT("Let's consider the following part of equation\n\n");
node_t* left = TreeMemes(fout, node->left);
node_t* right = TreeMemes(fout, node->right);
NodeLeft(temp, left);
NodeRight(temp, right);
MEMEPRINT("After some not that obvious transformations we get\n\n");
})
///-----------------------------------------------------------------------------------------------------------------------------------------------------------
OPERATOR(*, MUL,
{
node->data.data = node->left->data.data * node->right->data.data;
node->data.type = CONST;
free(node->left);
node->left = nullptr;
free(node->right);
node->right = nullptr;
},
{
OPERATORFILL(PLUS);
node_t* leftnode = NodeCreate(MUL, OPERATORCODE);
node_t* rightnode = NodeCreate(MUL, OPERATORCODE);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
node_t* leftone = TreeDiff(node->left);
node_t* lefttwo = NodeCopy(node->right);
node_t* rightone = NodeCopy(node->left);
node_t* righttwo = TreeDiff(node->right);
NodeLeft(leftnode, leftone);
NodeRight(leftnode, lefttwo);
NodeLeft(rightnode, rightone);
NodeRight(rightnode, righttwo);
//return temp;
},
{
NodeFill(temp, OPERATORCODE, PLUS);
node_t* leftnode = NodeCreate(MUL, OPERATORCODE);
node_t* rightnode = NodeCreate(MUL, OPERATORCODE);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
node_t* leftone = NodeCopy(node->left);
node_t* lefttwo = NodeCopy(node->right);
node_t* rightone = NodeCopy(node->left);
node_t* righttwo = NodeCopy(node->right);
NodeLeft(leftnode, leftone);
NodeRight(leftnode, lefttwo);
NodeLeft(rightnode, rightone);
NodeRight(rightnode, righttwo);
MEMEPRINT("Now let's differentiate the multiplication of two functions\n\n");
leftone = TreeMemes(fout, node->left);
lefttwo = NodeCopy(node->right);
rightone = NodeCopy(node->left);
righttwo = TreeMemes(fout, node->right);
NodeLeft(leftnode, leftone);
NodeRight(leftnode, lefttwo);
NodeLeft(rightnode, rightone);
NodeRight(rightnode, righttwo);
MEMEPRINT("After some very easy transformations we get\n\n");
})
OPERATOR_DIV(/, DIV,
{
node->data.data = node->left->data.data / node->right->data.data;
node->data.type = CONST;
free(node->left);
node->left = nullptr;
free(node->right);
node->right = nullptr;
},
{
NodeFill(temp, OPERATORCODE, DIV);
node_t* leftnode = NodeCreate(MINUS, OPERATORCODE);
node_t* rightnode = NodeCreate(MUL, OPERATORCODE);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
node_t* leftone = NodeCreate(MUL, OPERATORCODE);
node_t* lefttwo = NodeCreate(MUL, OPERATORCODE);
node_t* rightone = NodeCopy(node->right);
node_t* righttwo = NodeCopy(node->right);
NodeLeft(leftnode, leftone);
NodeRight(leftnode, lefttwo);
NodeLeft(rightnode, rightone);
NodeRight(rightnode, righttwo);
node_t* leftoneone = TreeDiff(node->left);
node_t* leftonetwo = NodeCopy(node->right);
node_t* lefttwoone = NodeCopy(node->left);
node_t* lefttwotwo = TreeDiff(node->right);
NodeLeft(leftone, leftoneone);
NodeRight(leftone, leftonetwo);
NodeLeft(lefttwo, lefttwoone);
NodeRight(lefttwo, lefttwotwo);
//return temp;
},
{
OPERATORFILL(DIV);
node_t* leftnode = NodeCreate(MINUS, OPERATORCODE);
node_t* rightnode = NodeCreate(MUL, OPERATORCODE);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
node_t* leftone = NodeCreate(MUL, OPERATORCODE);
node_t* lefttwo = NodeCreate(MUL, OPERATORCODE);
node_t* rightone = NodeCopy(node->right);
node_t* righttwo = NodeCopy(node->right);
NodeLeft(leftnode, leftone);
NodeRight(leftnode, lefttwo);
NodeLeft(rightnode, rightone);
NodeRight(rightnode, righttwo);
node_t* leftoneone = NodeCopy(node->left);
node_t* leftonetwo = NodeCopy(node->right);
node_t* lefttwoone = NodeCopy(node->left);
node_t* lefttwotwo = NodeCopy(node->right);
NodeLeft(leftone, leftoneone);
NodeRight(leftone, leftonetwo);
NodeLeft(lefttwo, lefttwoone);
NodeRight(lefttwo, lefttwotwo);
MEMEPRINT("Now let's differentiate the division\n\n");
leftoneone = TreeMemes(fout, node->left);
leftonetwo = NodeCopy(node->right);
lefttwoone = NodeCopy(node->left);
lefttwotwo = TreeMemes(fout, node->right);
NodeLeft(leftone, leftoneone);
NodeRight(leftone, leftonetwo);
NodeLeft(lefttwo, lefttwoone);
NodeRight(lefttwo, lefttwotwo);
MEMEPRINT("As it can easily be shown, we get\n\n");
})
OPERATOR_ONE(Sin, SINE,
{
node->data.data = sin(node->left->data.data);
node->data.type = CONST;
free(node->left);
node->left = nullptr;
free(node->right);
node->right = nullptr;
},
{
NodeFill(temp, OPERATORCODE, MUL);
node_t* leftnode = NodeCreate(COSINE, OPERATORCODE);
node_t* rightnode = TreeDiff(node->left);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
node_t* leftone = NodeCopy(node->left);
NodeLeft(leftnode, leftone);
//return temp;
},
{
OPERATORFILL(MUL);
node_t* leftnode = NodeCreate(COSINE, OPERATORCODE);
node_t* rightnode = NodeCopy(node->left);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
node_t* leftone = NodeCopy(node->left);
NodeLeft(leftnode, leftone);
MEMEPRINT("Now let's differentiate the sine\n\n");
leftnode = NodeCreate(COSINE, OPERATORCODE);
rightnode = TreeMemes(fout, node->left);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
leftone = NodeCopy(node->left);
NodeLeft(leftnode, leftone);
MEMEPRINT("Now, after two pages of different transformations, we get\n\n");
})
OPERATOR_ONE(Cos, COSINE,
{
node->data.data = cos(node->left->data.data);
node->data.type = CONST;
free(node->left);
node->left = nullptr;
free(node->right);
node->right = nullptr;
},
{
NodeFill(temp, OPERATORCODE, MUL);
node_t* leftnode = NodeCreate(-1, CONST);
node_t* rightnode = NodeCreate(MUL, OPERATORCODE);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
node_t* rightone = NodeCreate(SINE, OPERATORCODE);
node_t* righttwo = TreeDiff(node->left);
NodeLeft(rightnode, rightone);
NodeRight(rightnode, righttwo);
node_t* value = NodeCopy(node->left);
NodeLeft(rightone, value);
},
{
NodeFill(temp, OPERATORCODE, MUL);
node_t* leftnode = NodeCreate(-1, CONST);
node_t* rightnode = NodeCreate(MUL, OPERATORCODE);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
node_t* rightone = NodeCreate(SINE, OPERATORCODE);
node_t* righttwo = NodeCopy(node->left);
NodeLeft(rightnode, rightone);
NodeRight(rightnode, righttwo);
node_t* value = NodeCopy(node->left);
NodeLeft(rightone, value);
MEMEPRINT("Now let's differentiate the cosine\n\n");
righttwo = TreeMemes(fout, node->left);
NodeRight(rightnode, righttwo);
value = NodeCopy(node->left);
NodeLeft(rightone, value);
MEMEPRINT("Now as every spring-2020 army recruit knows\n\n");
})
OPERATOR_ONE(Ln, LN,
{
node->data.data = log(node->left->data.data);
FREELEFT;
CONSTTYPE;
},
{
OPERATORFILL(MUL);
node_t* leftnode = TreeDiff(node->left);
node_t* rightnode = NodeCreate(DIV, OPERATORCODE);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
node_t* left = NodeCreate(1, CONST);
node_t* right = NodeCopy(node->left);
NodeLeft(rightnode, left);
NodeRight(rightnode, right);
},
{
OPERATORFILL(MUL);
node_t* leftnode = NodeCopy(node->left);
node_t* rightnode = NodeCreate(DIV, OPERATORCODE);
NodeLeft(temp, leftnode);
NodeRight(temp, rightnode);
node_t* left = NodeCreate(1, CONST);
node_t* right = NodeCopy(node->left);
NodeLeft(rightnode, left);
NodeRight(rightnode, right);
MEMEPRINT("Now let's differentiate the logarythm\n\n");
leftnode = TreeMemes(fout, node->left);
NodeLeft(temp, leftnode);
MEMEPRINT("Now as every razdolbay knows\n\n");
})
OPERATOR(^, DEG,
{
node->data.data = pow(node->left->data.data, node->right->data.data);
FREELEFT;
FREERIGHT;
CONSTTYPE;
},
{
OPERATORFILL(MUL);
node_t* leftnode = NodeCopy(node);
node_t* rightnode = NodeCreate(PLUS, OPERATORCODE);
NODETEMP;
node_t* left = NodeCreate(MUL, OPERATORCODE);
node_t* right = NodeCreate(MUL, OPERATORCODE);
NodeLeft(rightnode, left);
NodeRight(rightnode, right);
node_t* leftleft = NodeCreate(DIV, OPERATORCODE);
node_t* leftright = TreeDiff(node->left);
NodeLeft(left, leftleft);
NodeRight(left, leftright);
node_t* leftleftone = NodeCopy(node->right);
node_t* leftlefttwo = NodeCopy(node->left);
NodeLeft(leftleft, leftleftone);
NodeRight(leftleft, leftlefttwo);
node_t* rightleft = NodeCreate(LN, OPERATORCODE);
node_t* rightright = TreeDiff(node->right);
NodeLeft(right, rightleft);
NodeRight(right, rightright);
node_t* rightleftleft = NodeCopy(node->left);
NodeLeft(rightleft, rightleftleft);
},
{
OPERATORFILL(MUL);
node_t* leftnode = NodeCopy(node);
node_t* rightnode = NodeCreate(PLUS, OPERATORCODE);
NODETEMP;
node_t* left = NodeCreate(MUL, OPERATORCODE);
node_t* right = NodeCreate(MUL, OPERATORCODE);
NodeLeft(rightnode, left);
NodeRight(rightnode, right);
node_t* leftleft = NodeCreate(DIV, OPERATORCODE);
node_t* leftright = NodeCopy(node->left);
NodeLeft(left, leftleft);
NodeRight(left, leftright);
node_t* leftleftone = NodeCopy(node->right);
node_t* leftlefttwo = NodeCopy(node->left);
NodeLeft(leftleft, leftleftone);
NodeRight(leftleft, leftlefttwo);
node_t* rightleft = NodeCreate(LN, OPERATORCODE);
node_t* rightright = NodeCopy(node->right);
NodeLeft(right, rightleft);
NodeRight(right, rightright);
node_t* rightleftleft = NodeCopy(node->left);
NodeLeft(rightleft, rightleftleft);
MEMEPRINT("Now let's do the transformations you must have learned during your high school studies\n\n");
leftright = TreeMemes(fout, node->left);
rightright = TreeMemes(fout, node->right);
NodeRight(left, leftright);
NodeRight(right, rightright);
MEMEPRINT("Now, after some obvious transformations we get\n\n");
})
<file_sep>/README.md
# Differentiator
A program counting the derivative of one-variable functions and exporting the result to LaTeX. May be quite useful during the calculus course as long as it is able to work with pretty complex functions.
# Supported operations
- sum (+)
- substitution (-)
- multiplication (*)
- division (/)
- sine (sin)
- cosine (cos)
- natural logarithm (ln)
- degree (^)
# Expression format
The expressions and the variables must be taken into brackets with space left between the symbols. i.e.
- ( ( x ) + ( 4 ) );
- ( cos ( ( x ) ^ ( x ) ) );
- ( ln ( ( x ) + ( 100 ) ) ).
<file_sep>/Differentiator.h
//
// Created by User on 17.11.2019.
//
#ifndef DIFFERENTIATOR_DIFFERENTIATOR_H
#define DIFFERENTIATOR_DIFFERENTIATOR_H
#define OPERATOR(name, num, operation, diff, meme)\
if (strcmp(str, #name) == 0)\
{\
NodeFill(temp, OPERATORCODE, num);\
continue;\
}
#define OPERATOR_DIV(name, num, operation, diff, meme)\
if (strcmp(str, #name) == 0)\
{\
NodeFill(temp, OPERATORCODE, num);\
continue;\
}
#define OPERATOR_ONE(name, num, operation, diff, meme)\
if (strcmp(str, #name) == 0)\
{\
NodeFill(temp, OPERATORCODE, num);\
continue;\
}
#include <math.h>
#include "MyTree.h"
#include "Config.h"
void FileRestoreTree (FILE* fin, node_t* node)
{
node_t* temp = node;
node_t* tempcpy = nullptr;
char str[STR_MAX] = "";
fscanf(fin, "%s", str);
while (fscanf(fin, "%s", str) != EOF)
{
if (strcmp(str, "(") == 0)
{
tempcpy = NodeCreate(10, 0);
if (temp->left == nullptr)
{
NodeLeft(temp, tempcpy);
temp = tempcpy;
continue;
}
else if (temp->right == nullptr)
{
NodeRight(temp, tempcpy);
temp = tempcpy;
continue;
}
else
printf("Expression error\n");
}
if (strcmp(str, ")") == 0)
{
tempcpy = temp->parent;
temp = tempcpy;
continue;
}
if ((str[0] >= 'a') && (str[0] <= 'z'))
{
NodeFill(temp, VAR, str[0]);
continue;
}
#include "Operator.h"
double tempnum = 0;
if ((str[0] >= '0') && (str[0] <= '9'))
{
tempnum = std::stod(&str[0]);
NodeFill(temp, CONST, tempnum);
}
}
}
#undef OPERATOR
#undef OPERATOR_ONE
#undef OPERATOR_DIV
node_t* NodeCopy (node_t* node1)
{
if (!node1)
return nullptr;
node_t* node2 = NodeCreate(0, 0);
node2->data.type = node1->data.type;
node2->data.data = node1->data.data;
node2->left = NodeCopy(node1->left);
node2->right = NodeCopy(node1->right);
return node2;
}
#define OPERATOR(name, num, operation, diff, meme)\
case num:\
diff\
break;
#define OPERATOR_DIV(name, num, operation, diff, meme)\
case num:\
diff\
break;
#define OPERATOR_ONE(name, num, operation, diff, meme)\
case num:\
diff\
break;
node_t* TreeDiff (node_t* node)
{
node_t* temp = NodeCreate(0, 0);
if (node->data.type == CONST)
{
NodeFill(temp, CONST, 0);
return temp;
}
if (node->data.type == VAR)
{
NodeFill(temp, CONST, 1);
return temp;
}
if (node->data.type == OPERATORCODE)
{
switch ((int) node->data.data)
{
#include "Operator.h"
}
}
return temp;
}
#undef OPERATOR
#undef OPERATOR_ONE
#undef OPERATOR_DIV
#define OPERATOR(name, num, operation, diff, meme)\
case num:\
operation\
break;
#define OPERATOR_ONE(name, num, operation, diff, meme)\
case num:\
operation\
break;
#define OPERATOR_DIV(name, num, operation, diff, meme)\
case num:\
operation\
break;
void Simplify(node_t* node) {
if (node == nullptr) {
return;
}
int ind = 0;
if ((node->data.type == OPERATORCODE) && (node->left->data.type == CONST) && ((node->right == nullptr) || (node->right->data.type == CONST)))
switch ((int) node->data.data)
{
#include "Operator.h"
}
if (node->data.type == OPERATORCODE && node->data.data == MUL && ((node->left->data.type == CONST && node->left->data.data == 0) || (node->right->data.type == CONST && node->right->data.data == 0)))
{
node->data.type = CONST;
node->data.data = 0;
//BranchDelete(node->left);
node->left = nullptr;
//BranchDelete(node->right);
node->right = nullptr;
}
if (node->data.type == OPERATORCODE && node->data.data == MUL && node->left->data.type == CONST && node->left->data.data == 1)
{
NodeCpy(node, node->right);
}
if (node->data.type == OPERATORCODE && node->data.data == MUL && node->right->data.type == CONST && node->right->data.data == 1)
{
NodeCpy(node, node->left);
}
if (node->data.type == OPERATORCODE && node->data.data == PLUS && node->left->data.type == CONST && node->left->data.data == 0)
{
NodeCpy(node, node->right);
}
if (node->data.type == OPERATORCODE && node->data.data == PLUS && node->right->data.type == CONST && node->right->data.data == 0)
{
NodeCpy(node, node->left);
}
if (node->data.type == OPERATORCODE && node->data.data == MINUS && node->right->data.type == CONST && node->right->data.data == 0)
{
NodeCpy(node, node->left);
}
Simplify(node->left);
Simplify(node->right);
}
#undef OPERATOR
#undef OPERATOR_ONE
#undef OPERATOR_DIV
#define CHECKOPERATOR (node->data.type == OPERATORCODE && node->parent->data.type == OPERATORCODE && (node->data.data == PLUS || node->data.data == MINUS || node->data.data == MUL || node->data.data == DEG) && (node->parent->data.data == MUL || node->parent->data.data == DEG))
#define CHECKPRIORITY (((node->data.data == PLUS || node->data.data == MINUS) && (node->parent->data.data == MUL || node->parent->data.data == DEG)) || (node->data.data == MUL && node->parent->data.data == DEG))
void TeXExport(FILE* fout, node_t* node)
{
if (!node)
return;
int temp = 0;
if (node->parent)
if (CHECKOPERATOR && CHECKPRIORITY)
{
temp = fprintf(fout, "(");
///printf("BAAAAA!\tDATA\t%lf\tPARENT\t%lf\tPARENTRIGHT\t%lf\tTEMP\t%d\n", node->data.data, node->parent->data.data, node->parent->right->data.data, temp);
}
switch(node->data.type)
{
case CONST:
fprintf(fout, "%.3lf", node->data.data);
break;
case VAR:
fprintf(fout, "%c", (char)node->data.data);
break;
case OPERATORCODE:
switch((int)node->data.data)
{
#define OPERATOR_ONE(name, num, operation, diffcode, meme)\
case num:\
fprintf(fout, "%s(", #name);\
break;
#define OPERATOR(name, num, operation, diffcode, meme)\
case num:\
break;
#define OPERATOR_DIV(name, num, operation, diffcode, meme)\
case num:\
fprintf(fout, "\\frac{");\
break;
#include "Operator.h"
#undef OPERATOR
#undef OPERATOR_ONE
#undef OPERATOR_DIV
}
break;
}
TeXExport(fout, node->left);
if (node->data.type == OPERATORCODE)
switch((int) node->data.data)
{
#define OPERATOR_DIV(name, num, operation, diffcode, meme)\
case num:\
fprintf(fout, "}{");\
break;
#define OPERATOR_ONE(name, num, operation, diffcode, meme)\
case num:\
fprintf(fout, ")");\
break;
#define OPERATOR(name, num, operation, diffcode, meme)\
case num:\
fprintf(fout, "%s", #name);\
break;
#include "Operator.h"
#undef OPERATOR
#undef OPERATOR_ONE
#undef OPERATOR_DIV
}
TeXExport(fout, node->right);
if (node->data.type == OPERATORCODE && node->data.data == DIV)
fprintf(fout, "}");
if (node->parent)
if (CHECKOPERATOR && CHECKPRIORITY)
fprintf(fout, ")");
}
#define OPERATOR(name, num, operation, diff, meme)\
case num:\
meme\
break;
#define OPERATOR_DIV(name, num, operation, diff, meme)\
case num:\
meme\
break;
#define OPERATOR_ONE(name, num, operation, diff, meme)\
case num:\
meme\
break;
node_t* TreeMemes (FILE* fout, node_t* node)
{
if (!node->parent)
fprintf(fout, "\\documentclass{article}\n"
"\\usepackage[utf8]{inputenc}\n"
"\\usepackage{amsmath}\n"
"\n"
"\\title{How to count the derivative?}\n"
"\\date{December 2019}\n"
"\n"
"\\begin{document}\n"
"\n"
"\\maketitle\n");
node_t* temp = NodeCreate(0, 0);
node_t* tempone = nullptr;
node_t* tempcpy = nullptr;
if (node->data.type == CONST)
{
NodeFill(temp, CONST, 0);
//return temp;
}
if (node->data.type == VAR)
{
NodeFill(temp, CONST, 1);
//return temp;
}
if (node->data.type == OPERATORCODE)
{
switch ((int) node->data.data)
{
#include "Operator.h"
}
}
if(!node->parent)
{
Simplify(temp);
Simplify(temp);
Simplify(temp);
Simplify(temp);
fprintf(fout, "And finally after conducting several simplifications we get\n");
fprintf(fout, "\\begin{equation}\n");
fprintf(fout, "\\[");
TeXExport(fout, temp);
fprintf(fout, "\\]\n");
fprintf(fout, "\\end{equation}\n\n");
fprintf(fout, "\\end{document}\n");
}
return temp;
}
#undef OPERATOR
#undef OPERATOR_ONE
#undef OPERATOR_DIV
#undef FREELEFT
#undef FREERIGHT
#undef CONSTTYPE
#endif //DIFFERENTIATOR_DIFFERENTIATOR_H
<file_sep>/Config.h
#ifndef DIFFERENTIATOR_CONFIG_H
#define DIFFERENTIATOR_CONFIG_H
const int CONST = 1;
const int VAR = 2;
const int OPERATORCODE = 3;
const int STR_MAX = 10;
enum Operators
{
PLUS = 1,
MINUS,
MUL,
DIV,
SINE,
COSINE,
DEG,
LN,
TG,
CTG,
SH,
CH,
TH,
CTH
};
#endif //DIFFERENTIATOR_CONFIG_H
<file_sep>/MyTree.h
#ifndef TREE_MYTREE_H
#define TREE_MYTREE_H
#include <string.h>
#include "Config.h"
//#include "Errors.h"
typedef char elem_t;
typedef struct NodeData
{
int type;
double data;
} data_t;
typedef struct TreeNode
{
data_t data;
TreeNode* left;
TreeNode* right;
TreeNode* parent;
} node_t;
typedef struct Tree
{
node_t* head;
int err;
} tree_t;
node_t* NodeCreate(double data, int type)
{
node_t* node = (node_t*) calloc(1, sizeof(node_t));
node->data.type = type;
node->data.data = data;
node->left = nullptr;
node->right = nullptr;
node->parent = nullptr;
return node;
}
node_t* TreeCreate(tree_t* tree)
{
tree->err = 0;
tree->head = NodeCreate(0, 0);
return tree->head;
}
node_t* TreeHead(const tree_t* tree)
{
return tree->head;
}
node_t* TreeLeft(const node_t* node)
{
return node->left;
}
node_t* TreeRight(const node_t* node)
{
return node->right;
}
void NodeFill(node_t* node, int type, double data)
{
node->data.type = type;
node->data.data = data;
}
/*void NodePrint(const node_t* node)
{
switch (node->data.type)
{
case CONST:
printf(" %.3lf ", node->data.data);
break;
case VAR:
printf(" %c ", (char) node->data.data);
break;
case OPERATOR:
switch ((int) node->data.data)
{
#define OPERATOR(name, num, operation)\
case num:\
printf(" %s ", #name);\
break;
#include "Operator.h"
#undef OPERATOR
}
}
}*/
void FileNodePrint(FILE* fout, const node_t* node)
{
switch (node->data.type)
{
case CONST:
fprintf(fout, " %.3lf ", node->data.data);
break;
case VAR:
fprintf(fout, " %c ", (char) node->data.data);
break;
case OPERATORCODE:
switch ((int) node->data.data)
{
#define OPERATOR(name, num, operation, diffcode, meme)\
case num:\
fprintf(fout, " %s ", #name);\
break;
#define OPERATOR_DIV(name, num, operation, diffcode, meme)\
case num:\
fprintf(fout, " %s ", #name);\
break;
#define OPERATOR_ONE(name, num, operation, diffcode, meme)\
case num:\
break;
#include "Operator.h"
#undef OPERATOR_ONE
#undef OPERATOR
#undef OPERATOR_DIV
}
}
}
void NodeCpy(node_t* node1, node_t* node2)
{
node_t* temp = node2;
node1->data.type = temp->data.type;
node1->data.data = temp->data.data;
node1->left = temp->left;
node1->right = temp->right;
node1->parent = temp->parent;
}
void FileNodePrintOne(FILE* fout, const node_t* node)
{
switch (node->data.type)
{
case CONST:
break;
case VAR:
break;
case OPERATORCODE:
switch ((int) node->data.data)
{
#define OPERATOR(name, num, operation, diffcode, meme)\
case num:\
break;
#define OPERATOR_DIV(name, num, operation, diffcode, meme)\
case num:\
break;
#define OPERATOR_ONE(name, num, operation, diffcode, meme)\
case num:\
fprintf(fout, " %s ", #name);\
break;
#include "Operator.h"
#undef OPERATOR_ONE
#undef OPERATOR
#undef OPERATOR_DIV
}
}
}
void NodeRight (node_t* parent, node_t* child)
{
parent->right = child;
child->parent = parent;
}
void NodeLeft (node_t* parent, node_t* child)
{
parent->left = child;
child->parent = parent;
}
void NodeDelete(node_t* node)
{
node->parent = nullptr;
free(node);
}
void BranchDelete(node_t* node)
{
if (node->left == nullptr)
NodeDelete(node->left);
else
BranchDelete(node->left);
if (node->right == nullptr)
NodeDelete(node->right);
else
BranchDelete(node->right);
}
void FilePrintTree(FILE* fout, node_t* node)
{
if (!node)
return;
fprintf(fout, " ( ");
FileNodePrintOne(fout, node);
FilePrintTree(fout, node->left);
FileNodePrint(fout, node);
FilePrintTree(fout, node->right);
fprintf(fout, " ) ");
}
/*void TreeGraph(FILE* fout, node_t* node)
{
if (!node)
{
return;
}
if (node->parent != nullptr)
{
//printf("PARENT\t%s\tDATA\t%s\n", node->parent->data, node->data);
fprintf(fout, "\"");
fputs(node->parent->data, fout);
fprintf(fout, "\" -- \"");
fputs(node->data, fout);
fprintf(fout, "\";\n");
}
TreeGraph(fout, node->left);
TreeGraph(fout, node->right);
}*/
#endif //TREE_MYTREE_H
<file_sep>/main.cpp
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include "MyTree.h"
#include "Differentiator.h"
void testdatafprintf();
void test();
void testtree();
void testcopy();
void testdiff();
int main() {
//test();
//testtree();
//testcopy();
testdiff();
return 0;
}
void testdiff()
{
node_t* head = NodeCreate(0, 0);
FILE* fin = fopen("output2.txt", "r");
FileRestoreTree(fin, head);
fclose(fin);
FILE* foutold = fopen("test.tex", "w");
TeXExport(foutold, head);
fclose(foutold);
node_t* headnew = TreeDiff(head);
Simplify(headnew);
Simplify(headnew);
Simplify(headnew);
Simplify(headnew);
FILE* fout = fopen("output5.txt", "w");
FilePrintTree(fout, headnew);
fclose(fout);
FILE* fouttex = fopen("equation.tex", "w");
TeXExport(fouttex, headnew);
fclose(fouttex);
FILE* foutmemes = fopen("memes.tex", "w");
TreeMemes(fout, head);
fclose(foutmemes);
}
void testcopy()
{
node_t* head = NodeCreate(0, 0);
FILE* fin = fopen("output2.txt", "r");
FileRestoreTree(fin, head);
fclose(fin);
node_t* headnew = NodeCopy(head);
FILE* fout = fopen("output4.txt", "w");
FilePrintTree(fout, headnew);
fclose(fout);
}
void testtree()
{
node_t* head = NodeCreate(0, 0);
FILE* fin = fopen("output2.txt", "r");
FileRestoreTree(fin, head);
fclose(fin);
FILE* fout = fopen("output3.txt", "w");
FilePrintTree(fout, head);
fclose(fout);
}
void test()
{
node_t* node2 = NodeCreate(3, CONST);
node_t* head = NodeCreate(3, OPERATORCODE);
node_t* node1 = NodeCreate('x', VAR);
NodeLeft(head, node1);
NodeRight(head, node2);
FILE* fout = fopen("output2.txt", "w");
FilePrintTree(fout, head);
fclose(fout);
}
void testdatafprintf()
{
tree_t tree = {};
FILE* fout = fopen("output.txt", "w");
node_t* head = NodeCreate(10, 1);
FileNodePrint(fout, head);
NodeFill(head, 2, 'x');
FileNodePrint(fout, head);
NodeFill(head, 3, 1);
FileNodePrint(fout, head);
NodeFill(head, 3, 2);
FileNodePrint(fout, head);
NodeFill(head, 3, 3);
FileNodePrint(fout, head);
NodeFill(head, 3, 4);
FileNodePrint(fout, head);
NodeFill(head, 3, 5);
FileNodePrint(fout, head);
fclose(fout);
}
|
a4092879ec74feaaaf77f0beb1e797520074fcde
|
[
"Markdown",
"C++",
"C"
] | 6 |
Markdown
|
Mihail-Makei/Differentiator
|
374e7ba43ce8f28e7c0069963aebff37340d2820
|
5a96eeb59375cfcb2f3c6cb3ead7049df09647a0
|
refs/heads/master
|
<repo_name>mdlefrancois/DataStore_Retrieval<file_sep>/app.py
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
import numpy as np
import pandas as pd
from flask import Flask, jsonify
# Database Setup
engine = create_engine("sqlite:///Resources/hawaii.sqlite")
# reflect an existing database into a new model
Base = automap_base()
# reflect the tables
Base.prepare(engine, reflect=True)
# Save reference to the table
Mea = Base.classes.measurement
Sta = Base.classes.station
# Create our session (link) from Python to the DB
session = Session(engine)
# Flask Setup
app = Flask(__name__)
# Flask Routes
@app.route("/")
def home():
return (
f"Climate Analysis for Honolulu Hawaii. Below are the routes via an API to get information on precipitation, "
f"weather stations and temperature<br/>"
f"Use the address: http://1192.168.3.11:5000 Append with /api/..... to get to the individual API's <br/><br/>"
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/< start ><br/>"
f"/api/v1.0/< start >/< end ><br/>"
f"For < start > or < start >/< end > selections, place yyyy-mm-dd entries during the period between 2016-08-23 and 2017-08-23 as follows:<br/>"
f"http://1192.168.3.11:5000/api/v1.0/2016-08-23/2017-08-23"
)
@app.route("/api/v1.0/precipitation")
def precipitation():
# Query
results = session.query(Mea.date, Mea.prcp).filter(Mea.date > '2016-08-23', Mea.date < '2017-08-23').order_by(Mea.date).all()
all_results = []
for result in results:
result_dict = {}
result_dict["date"] = result.date
result_dict["prcp"] = result.prcp
all_results.append(result_dict)
return jsonify(all_results)
@app.route("/api/v1.0/stations")
def stations():
# Return a json list of stations from the dataset.
# Query
results = session.query(Sta.station, Sta.name).all()
all_stas = []
for result in results:
result_dict = {}
result_dict['station'] = result.station
result_dict['name'] = result.name
all_stas.append(result_dict)
return jsonify(all_stas)
@app.route("/api/v1.0/tobs")
def tobss():
results = session.query(Mea.date, Mea.tobs).filter(Mea.date > '2016-08-23', Mea.date < '2017-08-23').all()
all_tobs = []
for result in results:
result_dict = {}
result_dict['date'] = result.date
result_dict['tobs'] = result.tobs
all_tobs.append(result_dict)
return jsonify(all_tobs)
@app.route("/api/v1.0/<start>")
@app.route("/api/v1.0/<start>/<end>")
def descr(start, end=None):
if end == None: end = session.query(Mea.date).order_by(Mea.date.desc()).first()[0]
tobs = pd.read_sql(session.query(Mea.tobs).filter(Mea.date > start, Mea.date <= end).statement, session.bind)
tobs_dict = {}
tobs_dict["TMIN"] = tobs.describe().loc[tobs.describe().index=='min']['tobs'][0]
tobs_dict["TAVG"] = tobs.describe().loc[tobs.describe().index=='mean']['tobs'][0]
tobs_dict["TMAX"] = tobs.describe().loc[tobs.describe().index=='max']['tobs'][0]
return jsonify(tobs_dict)
if __name__ == "__main__":
app.run(debug=True)
|
c4aaba24edba2999a454f561a104ab1f4805c5d0
|
[
"Python"
] | 1 |
Python
|
mdlefrancois/DataStore_Retrieval
|
b34922927d8337654bc5f1de7cc7dc1407c007e7
|
7a3cc065a888ebddaa8e27a49ecd7142c0e303d8
|
refs/heads/master
|
<file_sep>const states = ["AB", "BC", "MB", "NB", "NL", "NT", "NU", "ON", "PE", "SK", "QC", "YT"];
const regex = {
EMAIL: /^(([^<>()[\]\\.,;:\s@\\"]+(\.[^<>()[\]\\.,;:\s@\\"]+)*)|(\\".+\\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
}
const consts = {
states,
regex
}
export default consts;<file_sep>import styled from 'styled-components';
const Button = styled.button`
display: flex;
align-items: center;
justify-content: center;
height: 54px;
background: #000000;
font-style: normal;
font-weight: bold;
font-size: 20px;
line-height: 24px;
display: flex;
align-items: center;
text-align: center;
color: #FFFFFF;
`;
export default Button;<file_sep>/* eslint-disable no-throw-literal */
import { INotification } from 'components/Notification';
import constants from 'constants/index';
export interface IForm {
firstName: string,
lastName: string,
street: string,
apt?: string,
state: string,
city: string,
email: string
}
export function validate(data:IForm): INotification {
const { firstName, lastName, street, apt, state, city, email} = data;
try {
if(!firstName || !lastName || !street || !state || !city || !email){
throw('All fields except Unit/Apt are required.');
}
if(!constants.regex.EMAIL.test(email)){
throw('Email must be in the correct format.');
}
if(firstName.length > 40){
throw('First Name has a max of 40 characters.');
}
if(lastName.length > 40){
throw('Last Name has a max of 40 characters.');
}
if(street.length > 128){
throw('Street Address has a max of 128 characters.');
}
if(apt && apt.length > 128){
throw('Unit/Apt has a max of 128 characters.');
}
if(email.length > 128){
throw('Email has a max of 128 characters.');
}
if(city.length > 32){
throw('City has a max of 32 characters.');
}
if(state.length > 32){
throw('Province has a max of 32 characters.');
}
return { type: 'success', message: 'Your information has been sent successfully.'}
}catch(err){
const message:string = (err as string);
return { type: 'error', message };
}
}<file_sep>import styled from 'styled-components';
export const Container = styled.datalist`
width: 100%;
height: 38px;
outline: 0;
border: 0;
padding-left: 10px;
border-bottom: 1px solid #EEE;
background: #FaFaFa;
color: #000;
:focus {
border-bottom: 2px solid #969696;
}
::placeholder {
font-style: normal;
font-size: 16px;
display: flex;
color: #a1a1a1;
}
`;
<file_sep>import styled from 'styled-components';
export const Container = styled.div`
position: absolute;
display: flex;
justify-content: center;
z-index: 5;
width: 100%;
height: 100%;
`;
export const Content = styled.div`
display: flex;
flex-direction: column;
margin-top: 80px;
width: 100%;
height:min-content;
max-width: 700px;
background: #FFF;
padding: 40px;
.form-header {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 60px;
margin-bottom: 30px;
h1 {
font-style: normal;
font-weight: bold;
font-size: 32px;
line-height: 31px;
display: flex;
align-items: center;
text-align: center;
color: #000000;
}
}
.form-content {
display: flex;
width: 100%;
flex-direction: column;
.form-content-fields {
display: flex;
gap: 50px;
width: 100%;
margin: 20px 0;
}
button {
margin-top: 35px;
}
}
`;
<file_sep>
import { join } from 'path';
function srcPath(subdir) {
return join(__dirname, 'src', subdir);
}
export const resolve = {
alias: {
'assets': srcPath('src/assets'),
'components': srcPath('src/components'),
'constants': srcPath('src/constants'),
'pages': srcPath('src/pages'),
'services': srcPath('src/services'),
'utils': srcPath('src/utils'),
},
// ...
};<file_sep>It's a challenge created by DeveloPulse which has the main proposal of measure the candidate's technical knowledges around of JS frameworks such as ReactJS and NodeJS.
This challenge contains an implementation of a `Contact Us` webpage, where the user can fill its information in order to contact the DeveloPulse support.
## Introduction
To access and run the project, you need to follow these steps:
**Clone the project using the following command in terminal**
```
git clone https://github.com/wellingtonsa/DeveloPulse-challenge.git
```
**Execute the following commands in order to install all dependencies/libraries**
#### Backend
```
cd server
npm install // or yarn install
```
#### Frontend
```
cd web-application
npm install // or yarn install
```
**Finally, you can run the project using this command:**
- ``` yarn dev ``` (it works to both projects)
## Main utilized tools
### Prototype
- [Figma](https://www.figma.com/file/buNNphLQI2NavxuPmmO9CL/DeveloPulse-Challenge?node-id=0%3A1)
- Material UI
### Backend
- Node.js
**Some technologies, languages and libraries utilized:**
- Typescript
- Express
### Frontend
- React.js
**Some technologies, languages and libraries utilized:**
- Hooks
- Styled Components
- Typescript
- Absolute paths
- ESlint
- Prittier
## Results



<file_sep>import { Router } from 'express';
import Controller from '../controllers';
const routes = Router();
routes.post('/form/submit', Controller.submitForm);
export default routes;
<file_sep>/* eslint-disable no-return-await */
import api from '.';
import { IForm } from '../util/types';
export interface ApiFormResponse {
StatusCode: number,
Status: string
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function sendForm(data:IForm): Promise<any> {
const response = await api.post<ApiFormResponse>(`/Contact/Save`, data);
return response.data;
}
<file_sep>{
"compilerOptions": {
"target": "es2017", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"module": "commonjs",
"allowJs": true,
"esModuleInterop": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include": ["src/**/*.ts"]
}
<file_sep>import styled from 'styled-components';
interface Props {
type: 'success' | 'error'
}
export const Container = styled.div<Props>`
display: flex;
align-items: center;
padding: 10px;
width: 100%;
height: 55px;
border-width: 1px;
border-style: solid;
background: ${({ type }) => type === 'success' ? '#02AD1375' : '#C1000075'};
border-color: ${({ type }) => type === 'success' ? '#02AD1375' : '#C1000075'};
font-style: normal;
font-weight: bold;
font-size: 16px;
line-height: 19px;
display: flex;
align-items: center;
text-align: center;
color: #FFFFFF;
img {
margin-right: 10px;
width: 35px;
height: 35px;
}
`;
<file_sep>import React from 'react';
import path from 'constants/path';
import * as S from './styles';
const TopBar: React.FC = () => (
<S.Container>
<img src={path.images.LOGO} alt="" />
</S.Container>
)
export default TopBar;<file_sep>import { Request, Response } from 'express';
import { sendForm, ApiFormResponse} from '../services/form.services';
import { IForm } from '../util/types';
import { regex } from '../util/constants';
class Controller {
public async submitForm(req:Request, res:Response): Promise<Response<string>>{
const body:IForm = req.body;
const { Name, Address, Address2, City, Email, Province} = body;
if(!Name || !Address || !City || !Email || !Province){
res.status(403).json({type: 'error', message:'One or more information are missing'});
}
if(!regex.EMAIL.test(Email)){
res.status(403).json({type: 'error', message:'Email must be in the correct format.'});
}
if(Name.length > 85){
res.status(403).json({type: 'error', message:'First Name has a max of 85 characters.'});
}
if(Address.length > 128){
res.status(403).json({type: 'error', message:'Address has a max of 128 characters.'});
}
if(Address2 && Address2.length > 128){
res.status(403).json({type: 'error', message:'Address2 has a max of 128 characters.'});
}
if(Email.length > 128){
res.status(403).json({type: 'error', message:'Email has a max of 128 characters.'});
}
if(City.length > 32){
res.status(403).json({type: 'error', message:'City has a max of 32 characters.'});
}
if(Province.length > 32){
res.status(403).json({type: 'error', message:'Province has a max of 32 characters.'});
}
const response:ApiFormResponse = await sendForm(body);
if(response.StatusCode === 200){
return res.status(200).json({type: 'success', message: 'Your information has been sent successfully.'});
}else{
return res.status(response.StatusCode).json({type: 'error', message: response.Status});
}
}
}
export default new Controller();<file_sep>import React from 'react';
import TopBar from 'components/TopBar';
import Form from 'components/Form';
import * as S from './styles';
const Home: React.FC = () => (
<S.Container>
<TopBar/>
<S.Content>
<Form/>
</S.Content>
</S.Container>
)
export default Home;<file_sep>import Logo from 'assets/images/developulse-logo.png';
import ImageBackground from 'assets/images/image-background.jpg';
import Success from 'assets/icons/success.svg';
import Error from 'assets/icons/error.svg';
enum RoutesPath {
HOME = '/',
}
const ImagesPath = {
LOGO: Logo,
IMAGE_BACKGROUND: ImageBackground
}
const IconsPath = {
success: Success,
error: Error
}
const path = {
routes:RoutesPath,
images: ImagesPath,
icons: IconsPath
}
export default path;<file_sep>import styled from 'styled-components';
import path from 'constants/path';
export const Container = styled.div`
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
`;
export const Content = styled.div`
position: relative;
display: flex;
width: 100%;
height: 100%;
background-image: url(${path.images.IMAGE_BACKGROUND});
background-position: center;
background-repeat: no-repeat;
background-size: cover;
::after {
position: absolute;
z-index: 1;
width: 100%;
height: 100%;
content: "";
background: rgba(50, 47, 32, 0.5);
}
`;
<file_sep>/* eslint-disable no-return-await */
import { create, ApisauceInstance } from 'apisauce';
interface ApiCitiesResponse {
Message: string,
Items: string[]
}
const api:ApisauceInstance = create({
baseURL: 'https://imc-hiring-test.azurewebsites.net',
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function getCitiesByState(state:string): Promise<any> {
const response = await api.get<ApiCitiesResponse>(`/Contact/Cities?province=${state}`);
return response.data?.Items;
}
<file_sep>
import { create, ApisauceInstance } from 'apisauce';
const api:ApisauceInstance = create({
baseURL: 'https://imc-hiring-test.azurewebsites.net',
});
export default api;<file_sep>import React from 'react';
import { Switch, BrowserRouter, Route } from 'react-router-dom';
import path from 'constants/path';
import Home from 'pages/Home';
const Routes:React.SFC = () => (
<BrowserRouter>
<Switch>
<Route exact path={path.routes.HOME} component={Home} />
</Switch>
</BrowserRouter>
);
export default Routes;<file_sep>import React from 'react';
import path from 'constants/path';
import * as S from './styles';
export interface INotification {
type: 'success' | 'error',
message: string
}
type Props = INotification;
function Notification({ type, message }:Props): React.ReactElement {
return(
<S.Container type={type}>
<img src={path.icons[type]} alt="" />
{message}
</S.Container>)
}
export default Notification;<file_sep>export interface IForm {
Name: string,
Address: string,
Address2: string,
City: string,
Province: string,
Email: string
}<file_sep>import styled from 'styled-components';
export const Container = styled.div`
display:flex;
align-items: center;
padding: 10px;
width: 100%;
height:60px;
background: #FFFFFF;
box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.2);
img {
height: 36px;
}
`;
<file_sep>import React, { useState, useEffect }from 'react';
import constants from 'constants/index';
import Input from 'common/styled/Input';
import Dropdown from 'common/styled/Dropdown';
import Button from 'common/styled/Button';
import Notification, { INotification } from 'components/Notification';
import { getCitiesByState } from 'services/location.services';
import { submitForm } from 'services/form.services';
import { validate, IForm } from './index.validate';
import * as S from './styles';
const Form: React.FC = () => {
const [cities, setCities] = useState([]);
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [street, setStreet] = useState('');
const [apt, setApt] = useState('');
const [state, setState] = useState('');
const [city, setCity] = useState('');
const [email, setEmail] = useState('');
const [notification, setNotification] = useState<INotification | undefined>(undefined);
useEffect(() => {
if(state){
getCitiesByState(state)
.then(res => {
setCities(res);
setCity('');
})
}
}, [state]);
const handleSubmit = () => {
const data:IForm = {
firstName,
lastName,
street,
apt,
state,
city,
email
}
const response = validate(data);
if(response.type === "success"){
submitForm(data)
.then(res => {
setNotification(res);
handleClearAllFields();
});
}else {
setNotification(response);
}
}
const handleClearAllFields = () => {
setFirstName('');
setLastName('');
setStreet('');
setApt('');
setState('');
setCity('');
setEmail('');
}
return (
<S.Container>
<S.Content>
<div className="form-header">
<h1>Contact Us</h1>
</div>
<div className="form-content">
<div className="form-content-fields">
<Input placeholder="<NAME>" onChange={(e) => setFirstName(e.target.value)} value={firstName}/>
<Input placeholder="<NAME>" onChange={(e) => setLastName(e.target.value)} value={lastName}/>
</div>
<div className="form-content-fields">
<Input placeholder="Street Address" onChange={(e) => setStreet(e.target.value)} value={street}/>
</div>
<div className="form-content-fields">
<Input placeholder="Unit/Apt" onChange={(e) => setApt(e.target.value)} value={apt}/>
</div>
<div className="form-content-fields">
<Dropdown
placeholder="Province/Territory/State"
data={constants.states}
type="state"
onChange={setState}
value={state}/>
<Dropdown
placeholder="City"
data={cities}
type="city"
onChange={setCity} value={city}/>
</div>
<div className="form-content-fields">
<Input placeholder="E-mail" onChange={(e) => setEmail(e.target.value)} value={email}/>
</div>
{notification && (<Notification type={notification.type} message={notification.message}/>)}
<Button onClick={handleSubmit}>Submit</Button>
</div>
</S.Content>
</S.Container>
)
}
export default Form;<file_sep>/* eslint-disable no-return-await */
import { create, ApisauceInstance } from 'apisauce';
import { IForm } from 'components/Form/index.validate';
interface ApiFormResponse {
type: 'success' | 'error',
message: string
}
const api:ApisauceInstance = create({
baseURL: 'http://localhost:3333/',
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function submitForm(form:IForm): Promise<any> {
const data = {
Name: `${form.firstName} ${form.lastName}`,
Address: form.street,
Address2: form.apt ? form.apt : "",
City: form.city,
Province: form.state,
Email: form.email
}
const response = await api.post<ApiFormResponse>(`/form/submit`, data);
return response.data;
}
<file_sep>import React from 'react';
import Input from '../Input';
import * as S from './styles';
interface Props {
data: string[],
type: string,
placeholder: string,
value: string,
onChange: (value:string) => void
}
function Dropdown({ data = [], type, placeholder, value, onChange }:Props): React.ReactElement {
return (
<>
<Input value={value} onChange={(e) => { onChange(e.target.value) }} onFocus={() => onChange('')} placeholder={placeholder} list={`list-${type}`} name={type} id={type}/>
<S.Container id={`list-${type}`}>
{data.map(op => (
<option value={op}>{op}</option>
))}
</S.Container>
</>
)
}
export default Dropdown;
|
a9c3a7ed46f73216cae59e1e2430b58457c1da59
|
[
"TSX",
"JSON with Comments",
"Markdown",
"JavaScript",
"TypeScript"
] | 25 |
TSX
|
wellingtonsa/DeveloPulse-challenge
|
06ee327fa1556152967405329c93bf331c221b46
|
2a6349369b9b3644185397a1c8740dbdea77acac
|
refs/heads/main
|
<repo_name>ajfreedm/KanyeSaidWhat<file_sep>/README.md
# KanyeSaidWhat
### KanyeSaidWhat:
<https://ajfreedm.github.io/KanyeSaidWhat/>
### App Description:
The app will display a randomized quote taken either from kanye.rest API from the famous quote API. The end user will have to answer the question using a button if they think the quote is from Kayne West or a some other famous person.
### API's Used:
Kayne.rest API: https://kanye.rest/
Famous Quotes API: https://type.fit/api/quotes
### API Snippet:
Kayne.rest API Result Snippet:
```
{
"quote": "Keep your nose out the sky, keep your heart to god, and keep your face to the rising sun."
}
```
Type.fit API Result Snippet:
```
{
"text": "Genius is one percent inspiration and ninety-nine percent perspiration.",
"author": "<NAME>"
}
```
### Wireframes:
<https://www.figma.com/file/P6JKDp5DQmXtHlwuGyfTKi/Untitled?node-id=0%3A1>
### MVP:
- Display a random quote to the end user
- User must read the quote and determine if it is a quote from Kayne West or another famous person
- If the user answer correctly he will be displayed another quote
- If the user answers incorrectly, he will be displayed the correct author and will be displayed another quote to try again
### Post-MVP:
- Adding a link to the Wikipedia page of the famous person if the person if the Quote is not Kanyes.
### Project Schedule
| Day | Deliverable | Status |
| ------------- |:-------------:| -----:|
| October 1 | Brainstorming and Wireframe | Complete |
| October 1 | Poject Pitch and Approval | Complete |
| October 4 | HTML Structure | Complete |
| October 5 | Javascript | Complete |
| October 6 | debugging | Complete |
| October 7 | Flexbox / Media Queries | Complete |
### Goals:
I first plan on building on rough website. Second I will fetch the API data and manipulate the DOM accordingly.
### Timeframes
| Component | Time Spent
| ------------- |:-------------:|
| Pseudocode Javascript | 2hr |
| Javascript Code | 8hr |
| Debugging with Console Log | 6hr |
| HTML Stucture | 6hr |
| DOM Manipulation | 6hr |
| CSS Styling | 3hr |
| Media Queries | 1hr |
| Flexbox Implimentation | 3hr |
| Total | 35hr |
### Code Snippet:
While this JavaScript if else and else if statement is simple, it controls main logic of the application.
There are four possible conditions that can be met.
```javascript
if (actualAnswer === "yes" && answer === "yes") {
console.log("win");
result.innerText = "You got that one right! Try this one";
result.style.color = "#258749";
} else if (actualAnswer === "yes" && answer === "no") {
console.log("lose");
result.innerHTML = "You got that one wrong, try again";
result.style.color = "#D23232";
} else if (actualAnswer === "no" && answer === "yes") {
console.log("lose");
result.innerHTML = `You got that one wrong, try again <span><a style="color:#258749; text-decoration: underline;" href="https://en.wikipedia.org/wiki/Special:Search?search=${randomQuoteAuthor}" target="_blank" >${randomQuoteAuthor}</a></span> said ${randomQuoteText}`;
result.style.color = "#D23232";
} else if (actualAnswer === "no" && answer === "no") {
result.innerText = "You got that one right! Try this one";
result.style.color = "#258749";
}
```
|
8966e12f2986c1e0be6b849f99e8892ae846401e
|
[
"Markdown"
] | 1 |
Markdown
|
ajfreedm/KanyeSaidWhat
|
d9f120620694b5d57b61994e83fe323a5958673c
|
92b7d77bb823b2c7dc8b62922e7059653263ae11
|
refs/heads/main
|
<file_sep># Construtores - Exercício
<file_sep>package application;
import java.util.Locale;
import java.util.Scanner;
import util.Account;
public class Main {
public static void main(String[] args) {
Locale.setDefault(Locale.US);
Scanner teclado = new Scanner(System.in);
Account account;
System.out.print("Enter account number: ");
int number = teclado.nextInt();
teclado.nextLine();
System.out.print("Enter account holder: ");
String holder = teclado.nextLine();
System.out.print("Is there an initial deposit (y/n)? ");
char response = teclado.next().charAt(0);
if (response == 'y') {
System.out.print("Enter initial deposit value: ");
double initialDeposit = teclado.nextDouble();
account = new Account(holder, number, initialDeposit);
} else {
account = new Account(holder, number);
}
System.out.println();
System.out.println("Account data:");
System.out.println(account);
System.out.println();
System.out.print("Enter a deposit value: ");
double depositValue = teclado.nextDouble();
account.deposit(depositValue);
System.out.println("Updated account data:");
System.out.println(account);
System.out.println();
System.out.print("Enter a withdraw value: ");
double withdrawValue = teclado.nextDouble();
account.withdraw(withdrawValue);
System.out.println("Updated account data:");
System.out.println(account);
System.out.println();
teclado.close();
}
}
|
dbec1e414ea1e7657ab4be5cd1c0df399a4cdce0
|
[
"Java",
"Markdown"
] | 2 |
Java
|
dantas-barreto/construtores_exercicio
|
3b3474febbf67047cfa32643da14d7bedbee7509
|
3e79663f82662fd802fed10f9fd820040ab0f96e
|
refs/heads/master
|
<file_sep>const chalk = require('chalk');
const log = console.log;
var score=0;
var high = [{
Name:"Sameer",
Score: 2,
},
{
Name: "Sahil",
Score: 4,
}]
var readlineSync = require("readline-sync");
log(chalk.blueBright.bold("Who has awakened the almighty me? State your Name!"));
var name = readlineSync.question();
var choice = properKeyInYN(readlineSync.question(chalk.blue("Welcome "+chalk.red(name)+"! Would you care for a little quiz? [y/n]:")));
function properKeyInYN(answerOfUser){
if(answerOfUser.toUpperCase()==="Y")
return true;
return false;
}
if(!choice)
log(chalk.greenBright("Understandable. Have a great day."));
else
{
ques=["What is the name of my creator?",
"which season is his favorite? ",
"What kind of weather can my creator not stand?",
"Does my creator like chocolates?",
"Does he like milk chocolates over Dark chocolates?",
"Does he like cool things or cute things?",
"What is the powerhouse of the cell?",
"Which Color is my favourite?"
]
ans = ["Sameer",
"Rainy",
"Sunny",
"Yes",
"No",
"Cute",
"Mitochondria",
"Gray"
]
for(var i=0;i<ques.length;i++)
{
var userAns = readlineSync.question(ques[i]);
if(userAns.toUpperCase()===ans[i].toUpperCase())
{
score+=1;
console.log(chalk.greenBright("DING DING DING! Correct answer!!"));
}
else
console.log(chalk.red("OOPS! Wrong answer"));
log(chalk.blueBright("The Correct answer is: ")+chalk.greenBright(ans[i]));
var con=properKeyInYN(readlineSync.question(chalk.blueBright("Would you like to continue? [Y/N]: ")));
if(!con)
break;
}
console.log(chalk.green.bgBlack("Your score is: "+score));
//High Score Evaluation
var max_Score=0;
for (let i = 0; i < high.length; i++) {
if(high[i].Score > max_Score)
{
max_Score=high[i].Score;
}
}
let person = {
Name : name,
Score : score,
};
high.push(person);
if(score>=max_Score)
{
console.log(chalk.greenBright("It is a new high score!!!"));
log("You beat the previous high score by "+chalk.greenBright(score-max_Score)+" points!");
}
else
{
log("Oooh!you missed the high score by "+chalk.red(high-score)+" points!");
}
}
console.log(chalk.bold.black.bgWhite("High Scores: "))
for(let i=0;i<high.length;i++)
{
console.log("\n Name: "+high[i].Name+"\t Score: "+high[i].Score);
}
|
001e5646c222f20742a005fb7c05cde6156ce591
|
[
"JavaScript"
] | 1 |
JavaScript
|
Sameony/SecondQuizButItsOnMeAsWell
|
8ede5623ebb1966ff1bfa7f74380ad96cc7898dc
|
12d77a2d1e8b3b8a29835f8571c11318aa741064
|
refs/heads/master
|
<file_sep>$(document).ready(function(){
//Show loader image
$('$loaderImage').show();
//Show contacts on page load
showContacts();
});
// SHow contacts
function showContacts(){
console.log('Showing Contacts...');
setTimeout("$('#pageContent').load('contacts.php',function(){$('loaderImage').hide();})",1000);
}
|
c240849120abcc7315794379e2356d71f3f050c4
|
[
"JavaScript"
] | 1 |
JavaScript
|
huvii174/Sticky_Note
|
1a28bc7d431ebbc48897454f5ca1aac1399ca463
|
0dd9d929c73c7878287d14e81c3290be5d9e2e2c
|
refs/heads/master
|
<repo_name>chuswang/MyThree<file_sep>/CreateText.ts
import * as THREE from 'three';
export default class CreateText {
private canvas: HTMLCanvasElement;
private ctx: CanvasRenderingContext2D;
constructor() {
this.canvas = document.createElement('canvas')
this.ctx = this.canvas.getContext('2d')
this.sprite = null;
}
drawText(text: string, ctxOptions ? : any) {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
const pat = /[A-z]/;
const pat1 = /\d/;
const textArr = text.split('');
const num = textArr.reduce((pre, str) => {
if (pat.test(str)) {
pre += 45;
} else if (pat1.test(str)) {
pre += 30;
} else {
pre += 30;
}
return pre;
}, 0)
this.canvas.width = THREE.Math.ceilPowerOfTwo(num);
this.canvas.height = 64;
this.ctx.fillStyle = ctxOptions.color || '#000';
// this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.textAlign = 'left';
this.ctx.textBaseline = 'top';
textArr.reduce((pre, str) => {
if (pat.test(str)) {
this.ctx.font = `italic 60px "Times New Roman"`;
this.ctx.fillText(str, pre, 0);
pre += 45;
} else if (pat1.test(str)) {
this.ctx.font = `30px "Times New Roman"`;
this.ctx.fillText(str, pre, 30);
pre += 30;
} else {
this.ctx.font = `60px "Times New Roman"`;
this.ctx.fillText(str, pre, 0);
pre += 30;
}
return pre;
}, 0)
const texture = new THREE.Texture(this.canvas);
texture.magFilter = THREE.NearestFilter
texture.minFilter = THREE.LinearMipMapLinearFilter
texture.needsUpdate = true;
this.sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
}))
this.sprite.scale.set(this.canvas.width / 10, this.canvas.height / 10, 1)
return this.sprite;
}
}<file_sep>/DashLine.ts
/**
*
*@since 2.0
*@author zhiguo
*@Date 2018/5/28 8:45
*/
import {
BrowserInfo
} from '../../../../../src/model/BrowserInfo';
import {
BrowserUtil
} from '../../../../../src/util/BrowserUtil';
import * as THREE from 'three';
import { TimelineLite, Power0, TweenMax } from 'gsap';
import { Mesh, WebGLRenderer } from 'three';
import { PerspectiveCamera } from 'three';
const OBJLoader = require('three-obj-loader');
const MeshLine = require('three.meshline').MeshLine;
const MeshLineMaterial = require('three.meshline').MeshLineMaterial;
const OrbitControls = require('three-orbitcontrols');
OBJLoader(THREE);
export class DashLine {
/*
这个类主要是做一个兼容判定
判断是Ipad时用three自带的虚线
不是Ipad时用我们给的虚线meshLIne
*/
browserInfo: BrowserInfo;
private geometryLine: any;
private dottedLine: any;
private tween: any;
private timeDottedLine: any;
constructor() {
this.browserInfo = BrowserUtil.getBrowserInfo();
}
addLine(pointArr: any, color: any, linewidth: number, dashLine: any) {
/*
startPoint: 起始点
endPoint: 终点
color: 线条颜色
linewidth: 线框
dashLine: 是否是虚线 true是虚线 false是实线
*/
if (this.browserInfo.isIpad) {
if (dashLine) {
this.geometryLine = new THREE.Geometry();
this.geometryLine.vertices = pointArr;
this.dottedLine = new THREE.LineSegments(this.geometryLine, new THREE.LineDashedMaterial({
color: color,
dashSize: 0.1,
gapSize: 0.1,
linewidth: linewidth / 500,
depthTest: false
}));
this.dottedLine.computeLineDistances();
} else {
this.geometryLine = new THREE.Geometry();
this.geometryLine.vertices = pointArr;
this.dottedLine = new THREE.Line(this.geometryLine, new THREE.LineBasicMaterial({
color: color,
linewidth: linewidth / 500,
depthTest: false
}));
}
} else {
this.geometryLine = new THREE.Geometry();
this.geometryLine.vertices = pointArr;
this.dottedLine = this.createLine(this.geometryLine, dashLine, color, linewidth / 1000);
}
// this.tween = {x: startPoint.x, y: startPoint.y, z: startPoint.z};
return this.dottedLine;
}
// 用来画meshLine虚线
createLine(geometry: any, dashLine: boolean, color: any, lineWidth: number) {
const g = new MeshLine();
g.setGeometry(geometry);
const resolution = new THREE.Vector2(window.innerWidth, window.innerHeight);
const material = new MeshLineMaterial({
useMap: false,
color: new THREE.Color(color),
opacity: 1,
dashArray: 0.05,
dashOffset: 0,
dashRatio: 0.5,
resolution: resolution,
// sizeAttenuation: false,
lineWidth: lineWidth,
near: 1,
far: 100,
depthWrite: false,
depthTest: false,
alphaTest: false ? .5 : 0,
side: THREE.DoubleSide,
transparent: dashLine,
});
const mesh = new THREE.Mesh(g.geometry, material);
return mesh;
}
// 虚线动画
animation(startPoint: any, endPoint: any, time: number) {
if (this.browserInfo.isIpad) {
this.timeDottedLine = TweenMax.to(this.tween, time, {
x: endPoint.x,
y: endPoint.y,
z: endPoint.z,
onUpdate: () => {
this.updateDottedLine1(startPoint);
},
paused: true
});
} else {
this.timeDottedLine = TweenMax.to(this.tween, time, {
x: endPoint.x,
y: endPoint.y,
z: endPoint.z,
onUpdate: () => {
this.updateDottedLine2(startPoint);
},
paused: true
});
}
return this.timeDottedLine;
}
// 用于更新苹果机虚线动画
updateDottedLine1(startPoint: any) {
this.geometryLine = new THREE.Geometry();
const endPoint = new THREE.Vector3(this.tween.x, this.tween.y, this.tween.z);
this.geometryLine.vertices = [startPoint, endPoint];
this.dottedLine.geometry.dispose();
this.dottedLine.geometry = this.geometryLine;
this.dottedLine.computeLineDistances();
}
// 用于更新非苹果机虚线动画
updateDottedLine2(startPoint: any) {
this.geometryLine = new THREE.Geometry();
const endPoint = new THREE.Vector3(this.tween.x, this.tween.y, this.tween.z);
this.geometryLine.vertices.push(startPoint);
this.geometryLine.vertices.push(endPoint);
this.dottedLine.geometry.dispose();
const g = new MeshLine();
g.setGeometry(this.geometryLine);
this.dottedLine.geometry = g.geometry;
}
}<file_sep>/CommonForThree.ts
import * as THREE from 'three';
import { DashLine } from './DashLine';
import { SpriteText2D } from 'three-text2d';
import CreateText from './CreateText';
export default class CommonForThree {
private static dashLine = new DashLine();
// 为性能优化,画标准线段进行缩放
static drawUnitLine({
width = 1.2,
color = '#000',
isDash = false,
} = {}) {
const line = CommonForThree.drawDashOrLine([
{ x: -1, y: 0, z: 0 },
{ x: 1, y: 0, z: 0 },
], {
width,
color,
isDash
});
return line;
}
// 缩放线段
static scaleLine(startPos: any, endPos: any, line: THREE.Mesh, proportion: number = 1) {
const [x, y, z] = startPos;
const [x1, y1, z1] = endPos;
// 获取线段长度
const len = Math.hypot(x1 - x, y1 - y, z1 - z);
// 获得中点坐标
const centerPos = [(x + x1) / 2, (y + y1) / 2, (z + z1) / 2];
// 获取弧度
const rad = Math.atan2(y - y1, x - x1);
line.scale.set(len / 2 * proportion, 1, 1);
line.position.set(centerPos[0], centerPos[1], centerPos[2]);
line.rotation.z = rad;
return line;
}
// 画线
static drawDashOrLine(pointArr: any, {
width = 1.2,
color = '#000',
isDash = false,
depthTest = true,
} = {}) {
const line = this.dashLine.addLine(pointArr, color, width * 1000, isDash);
line.material.depthTest = depthTest;
line.material.depthWrite = depthTest;
return line;
}
// 画圆
static drawCircle(radius: number, {
color = '#000',
start = 0,
end = Math.PI * 2,
opacity = 1,
segments = 36,
isLay = false,
position = [0, 0, 0],
depthTest = true
} = {}) {
const CircleM = new THREE.MeshBasicMaterial({
color,
transparent: false,
opacity,
depthTest
});
const CircleG = new THREE.CircleGeometry(radius, segments, start, end);
const Circle = new THREE.Mesh(CircleG, CircleM);
if (isLay) {
Circle.rotation.x = -Math.PI / 2;
}
Circle.position.set(position[0], position[1], position[2]);
return Circle;
}
//画椭圆
static drawEllipseCurve(xRadius: number, yRadius: number, {
color = '#000',
aX = 0,
aY = 0,
aStartAngle = 0,
aEndAngle = 2.0 * Math.PI,
aClockwise = true,
opacity = 1,
depthTest = true,
} = {}) {
const ellipse = new THREE.EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, 0);
const material = new THREE.LineBasicMaterial({
color,
opacity,
transparent: true,
depthTest,
});
const ellipsePath = new THREE.CurvePath();
ellipsePath.add(ellipse);
const ellipseGeometry = ellipsePath.createPointsGeometry(100);
// ellipseGeometry.computeTangents();
const line = new THREE.Line(ellipseGeometry, material);
return line;
}
// 画三角形
static drawTriangle({ color = '#000' } = {}) {
const shape = new THREE.Shape();
shape.moveTo(0.5, 0);
shape.lineTo(-3, 1);
shape.lineTo(-3, -1);
shape.lineTo(0.5, 0);
const trianle = new THREE.Mesh(new THREE.ShapeGeometry(shape, 10), new THREE.MeshBasicMaterial({
color: color,
transparent: true,
depthTest: true,
}))
return trianle;
}
// 图片贴图
static createImg(vertices: any, w: number, h: number, src: any) {
const PlaneG = new THREE.PlaneGeometry(w, h);
const PlaneM = new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load(src),
transparent: true,
overdraw: 0.2,
depthTest: true
});
const Plane = new THREE.Mesh(PlaneG, PlaneM);
Plane.position.set(vertices[0], vertices[1], vertices[2]);
return Plane;
}
// 画直角
static drawRightAngle(length: number, { color = '#000', width = 1 } = {}) {
const line = CommonForThree.drawDashOrLine([
{ x: 0, y: length, z: 0 },
{ x: length, y: length, z: 0 },
{ x: length, y: 0, z: 0 }
], { width, color });
return line;
}
// 画圆线
static createStrokeCircle(radius: number, { color = '#000' } = {}) {
const group = new THREE.Group();
let x, y;
const vertices = [];
for (let i = 0; i < 361; i += 6) {
x = radius * Math.cos(i / 180 * Math.PI);
y = radius * Math.sin(i / 180 * Math.PI);
vertices.push({ x, y, z: 0 });
}
const line = CommonForThree.drawDashOrLine(vertices, { color });
group.add(line);
return group;
}
// 画角度
static drawAngle(startAngle: number, endAngle: number, {
color = '#000',
opacity = 1,
size = 10,
zIndex = 0,
isAngle = true
} = {}) {
const group = new THREE.Group();
const startRad = startAngle / 180 * Math.PI;
const endRad = isAngle ? endAngle / 180 * Math.PI : endAngle;
const angle = CommonForThree.drawCircle(size, { color, opacity, start: startRad, end: endRad });
angle.position.z = zIndex;
group.add(angle);
return group;
}
static createText(text: string, position: Array < number > = [0, 0, 0], { color = '#000', isItalic = true } = {}) {
const str = isItalic ? 'italic' : '';
const textStyle = { font: `${str} 40px "Times New Roman"`, fillStyle: color, antialias: true };
const textMesh = new SpriteText2D(text, textStyle);
textMesh.scale.set(0.15, 0.15, 0.15);
textMesh.position.set(position[0], position[1], position[2]);
textMesh.material.depthTest = false;
return textMesh;
}
// 下标文字的特殊处理
static createText1(text: string, position: Array < number > = [0, 0, 0], { color = '#000', isItalic = true } = {}) {
const textStyle = { color };
const textMesh = new CreateText().drawText(text, textStyle);
textMesh.position.set(position[0], position[1], position[2]);
textMesh.material.depthTest = false;
return textMesh;
}
// 画角度对称扇形
static drawSector(startPos: Array < number > , orginPos: Array < number > , endPos: Array < number > , {
color = '#000'
} = {}) {
const group = new THREE.Group();
// 偏移到原点
const offsetOrginPos = [0, 0, 0]
const offsetStartPos = [0, 0, 0];
offsetStartPos[0] = startPos[0] - orginPos[0];
offsetStartPos[1] = startPos[1] - orginPos[1];
const offsetendPos = {} as any;
offsetendPos[0] = endPos[0] - orginPos[0];
offsetendPos[1] = endPos[1] - orginPos[1];
// 获取需要画扇形五个关键点的坐标
let startAngle = CommonForThree.getLineAngle([0, 0, 0], offsetStartPos);
let endAngle = CommonForThree.getLineAngle([0, 0, 0], offsetendPos);
if (endAngle > 180 && startAngle === 0) {
startAngle = 360;
}
// startAngle = startAngle + 1;
// endAngle = endAngle + 1;
const quarterAngle = (endAngle - startAngle) / 4;
const sectorStartPos = CommonForThree.getCirclePos(startAngle);
const sectorEndPos = CommonForThree.getCirclePos(endAngle);
const sectorCenterPos = CommonForThree.getCirclePos(startAngle + quarterAngle * 2);
const sectorBezierPos1 = CommonForThree.getCirclePos(startAngle + quarterAngle, 11);
const sectorBezierPos2 = CommonForThree.getCirclePos(startAngle + quarterAngle * 3, 11);
group.add(CommonForThree.sectorShape(sectorStartPos, sectorBezierPos1, sectorCenterPos, sectorBezierPos2, sectorEndPos, color))
group.position.set(orginPos[0], orginPos[1], 0);
return group;
}
static getVecPos(startPos: Array < number > , endPos: Array < number > , xishu: Array < number > = [1]) {
const dis = Math.hypot(endPos[0] - startPos[0], endPos[1] - startPos[1]);
let resArr = [] as any;
xishu.forEach(num => {
const vecPos = [0, 0, 0];
vecPos[0] = startPos[0] + (endPos[0] - startPos[0]) * num;
vecPos[1] = startPos[1] + (endPos[1] - startPos[1]) * num;
resArr.push(vecPos);
})
return resArr;
}
static getLineAngle(startPos: Array < number > , endPos: Array < number > , onlyRad ? : boolean) {
let angle = 0;
const rad = Math.atan2(endPos[1] - startPos[1], endPos[0] - startPos[0]);
if (onlyRad) return rad;
angle = rad * 180 / Math.PI;
angle = angle < 0 ? (360 + angle) : angle;
return angle;
}
static sectorShape(pos1: Array < number > , pos2: Array < number > , pos3: Array < number > , pos4: Array < number > , pos5: Array < number > , color ? : String = '#0f0') {
const shape = new THREE.Shape();
shape.moveTo(0, 0);
shape.lineTo(pos1[0], pos1[1]);
shape.quadraticCurveTo(pos2[0], pos2[1], pos3[0], pos3[1]);
shape.quadraticCurveTo(pos4[0], pos4[1], pos5[0], pos5[1]);
shape.lineTo(0, 0);
const G = new THREE.ShapeGeometry(shape, 10);
const M = new THREE.MeshBasicMaterial({
color: color,
transparent: true,
depthTest: true,
})
const setor = new THREE.Mesh(G, M);
G.dispose();
M.dispose();
setor.position.z = -2;
return setor;
}
static getCirclePos(radius: number, len ? : number = 8) {
const pos = [0, 0, 0];
pos[0] = len * Math.cos(radius * Math.PI / 180);
pos[1] = len * Math.sin(radius * Math.PI / 180);
return pos;
}
/**
* @param {起始点位置}
* @param {终点位置}
* @param {需要缩放的线段}
*/
static lineAni(startPos: Array < number > , endPos: Array < number > , line: THREE.Mesh) {
return new Promise((resolve, reject) => {
const dis = Math.hypot(endPos[0] - startPos[0], endPos[1] - startPos[1]);
let num = 0.01;
let timer: any = null;
function ani() {
const vecPos = [0, 0, 0];
vecPos[0] = startPos[0] + (endPos[0] - startPos[0]) * num;
vecPos[1] = startPos[1] + (endPos[1] - startPos[1]) * num;
line = CommonForThree.scaleLine(startPos, vecPos, line);
num += 0.02;
if (num > 1) {
line = CommonForThree.scaleLine(startPos, endPos, line);
cancelAnimationFrame(timer);
resolve(line);
return;
}
timer = requestAnimationFrame(ani);
}
ani();
})
}
// 计算点到直线垂足坐标
static perpendicularPoint(linePoint1: any, linePoint2: any, point: any) {
const rad = Math.atan2(linePoint1[1] - linePoint2[1], linePoint1[0] - linePoint2[0]);
let corssPointPos = [0, 0, -1];
if (rad * 180 / Math.PI !== 90) {
const k = Math.tan(rad);
if (k === 0) {
corssPointPos[0] = point[0];
corssPointPos[1] = linePoint1[1];
} else {
const b = linePoint1[1] - linePoint1[0] * k;
const k1 = -1 / k;
const b1 = point[1] - point[0] * k1;
corssPointPos[0] = (b1 - b) / (k - k1);
corssPointPos[1] = k * corssPointPos[0] + b;
}
} else {
corssPointPos[0] = linePoint1[0];
corssPointPos[1] = point[1];
}
return { rad, pos: corssPointPos };
}
static setPerpendicularPosAndRotate(obj: any, mesh: any, num: number) {
mesh.position.set(...obj.pos);
if (num === 1) {
mesh.rotation.z = obj.rad;
} else if (num === 2) {
mesh.rotation.z = obj.rad;
} else if (num === 3) {
mesh.rotation.z = obj.rad + Math.PI;
} else if (num === 4) {
mesh.rotation.z = obj.rad + Math.PI / 2;
} else if (num === 5) {
mesh.rotation.z = obj.rad - Math.PI / 2;
}
}
static basicTriangleInfo(a: any, b: any, c: any) {
const disA = Math.hypot(b[0] - c[0], b[1] - c[1]);
const disB = Math.hypot(a[0] - c[0], a[1] - c[1]);
const disC = Math.hypot(b[0] - a[0], b[1] - a[1]);
let res = {} as any;
res.a = {} as any;
res.b = {} as any;
res.c = {} as any;
res.a.length = disA;
res.b.length = disB;
res.c.length = disC;
res.a.pos = a;
res.b.pos = b;
res.c.pos = c;
res.a.rad = Math.acos((disB * disB + disC * disC - disA * disA) / 2 / disB / disC);
res.b.rad = Math.acos((disA * disA + disC * disC - disB * disB) / 2 / disA / disC);
res.c.rad = Math.acos((disB * disB + disA * disA - disC * disC) / 2 / disB / disA);
res.a.angle = res.a.rad * 180 / Math.PI;
res.b.angle = res.b.rad * 180 / Math.PI;
res.c.angle = res.c.rad * 180 / Math.PI;
const arr = [Math.round(res.a.angle), Math.round(res.b.angle), Math.round(res.c.angle)];
arr.sort((a, b) => {
return a - b;
});
res.info = (arr[0] === arr[1] && arr[1] === arr[2]) ? '等边三角形' : arr[2] === 90 ? '直角三角形' : arr[2] > 90 ? '钝角三角形' : '锐角三角形';
return res;
}
static twoLineIcon({ color = '#000' } = {}) {
const group = new THREE.Group();
const line1 = CommonForThree.drawUnitLine({ color, width: 1 });
const line2 = line1.clone();
line1.position.y = 0.5;
line2.position.y = -0.5;
group.add(line1, line2);
return group;
}
}
|
c6203d9a1dff8ec10fc4366efe3cce3958562465
|
[
"TypeScript"
] | 3 |
TypeScript
|
chuswang/MyThree
|
fac4642725435d4049e882ab399aebfe505aa6c7
|
5e3bc04969a6f7777ac7a0a47a01ad5199c73fca
|
refs/heads/main
|
<repo_name>ChouKevin/python_for_log<file_sep>/pipline/step.py
from abc import ABC, abstractmethod
class Step(ABC):
@abstractmethod
def handle(self, line: str) -> str :
return NotImplemented
def finish(self):
pass<file_sep>/definitinos.py
import os
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
SRC_LOG_FOLDER = os.path.join(ROOT_DIR, 'log')
DEST_LOG_FOLDER = os.path.join(ROOT_DIR, 'processed')<file_sep>/main.py
from datetime import datetime
from operator import gt, lt
import os
import glob
from pipline import Search, Write, AllStep, AnyStep, Context, Date
from definitinos import *
from typing import Iterable
def load_line_by_line(path: str) -> Iterable[str]:
with open(path) as f:
for line in f.readlines():
yield line
def load_logs(paths: Iterable[str]) -> Iterable[str]:
for path in paths:
for log_info in load_line_by_line(path):
yield log_info
def define_pipline() -> Context:
# any_steps = [
# Search('(?=POST|GET)'),
# ]
# anyContext = AnyStep(any_steps)
final_steps = [
Search(r'(?=POST|GET)'),
Write(os.path.join(DEST_LOG_FOLDER, 'post_get.log')),
Date(DATE_TIME_PATTERN, time=datetime(year=2021, month=9, day=7), cmp=gt),
# Search('response', block_if_match=True),
Write(os.path.join(DEST_LOG_FOLDER, 'after_9_7.log'))
]
final = AllStep(final_steps)
return Context([final])
DATE_TIME_PATTERN = r"(?<=[\[]{1})(?P<day>[\d]{2})[\/]{1}(?P<month>[a-zA-Z]+)[\/]{1}(?P<year>[0-9]+):(?P<hour>[0-9]+):(?P<minute>[0-9]+):(?P<second>[0-9]+) .*(?=[\]])"
if __name__ == '__main__':
log_paths = [path
for path in glob.glob(os.path.join(SRC_LOG_FOLDER, 'fake*.log'))]
pipline = define_pipline()
pipline.exec(load_logs(log_paths))<file_sep>/pipline/date.py
import re
import operator
import calendar
from typing import Mapping
from .step import Step
from datetime import datetime
class Date(Step):
"""
cmp: see `operator` module. using le lt ge gt.
cmp(log_time, given_time).
pattern: named group pattern.
it contains name: `year` `month` `day` `hour` `minute` `second` `microsecond` `tzinfo`.
auto_pass: default=True. because of log is sequential message, if it read the log that
let result of cmp changed, then dont do cmp anymore.
"""
def __init__(self, pattern: str, time: datetime
, cmp: operator, auto_pass: bool=True) -> None:
self.pattern = pattern
self.time = time
self.cmp = cmp
self.auto_pass = auto_pass
self.need_cmp = True
self.prev_cmp_result = None
self.abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num}
def handle(self, line: str) -> str:
if self.need_cmp:
time_info = re.search(self.pattern, line).groupdict()
self._trans_time_info(time_info)
log_time = datetime(**time_info)
cur_cmp_result = self.cmp(log_time, self.time)
self._trigger_cmp(cur_cmp_result)
return line if cur_cmp_result else ""
return line if self.prev_cmp_result else ""
def _trigger_cmp(self, cur_cmp_result: bool):
if not self.auto_pass: return
if self.prev_cmp_result is None:
self.prev_cmp_result = cur_cmp_result
else:
if self.prev_cmp_result != cur_cmp_result:
self.prev_cmp_result = cur_cmp_result
self.need_cmp = False
def _trans_time_info(self, time_info: Mapping[str, str]) :
for k, v in time_info.items():
if k == 'month' and not v.isdigit():
time_info.update({k: self.abbr_to_num[v]})
elif k == 'microsecond':
time_info.update({k: float(v)})
elif k == 'tzinfo':
raise NotImplemented
else:
time_info.update({k: int(v)})<file_sep>/pipline/context.py
from pipline.step import Step
from typing import Iterable
class Context:
def __init__(self, steps: Iterable[Step] = []) -> None:
self.steps = steps
def exec(self, lines: Iterable[Step] = []) -> None:
for line in lines:
for step in self.steps:
line = step.handle(line)
self._finish()
def _finish(self):
for step in self.steps:
step.finish()
<file_sep>/setup.py
from setuptools import find_packages, setup
setup(
name='python_for_log',
version='1.0.0',
packages=find_packages()
)<file_sep>/pipline/__init__.py
from .search import Search
from .write import Write
from .allStep import AllStep
from .anyStep import AnyStep
from .step import Step
from .context import Context
from .replace import Replace
from .date import Date <file_sep>/pipline/write.py
import os
from typing import Optional
from .step import Step
class Write(Step):
def __init__(self, path: str) -> None:
self.path = path
self._preprocess(path)
self.file = open(path, 'a+')
def __str__(self) -> str:
clz_name = self.__class__.__name__
return f'class name : {clz_name}, path: {self.path}'
def _preprocess(self, path: str):
os.makedirs(os.path.dirname(path), exist_ok=True)
if os.path.exists(path):
os.remove(path)
def handle(self, line: str) -> str:
if line and line.strip():
self.file.write(line)
return line
def finish(self):
self.file.close()<file_sep>/pipline/allStep.py
from typing import Iterable, Optional
from .step import Step
class AllStep(Step):
def __init__(self, steps: Iterable[Step] = []) -> None:
self.steps = steps
def __str__(self) -> str:
clz_name = self.__class__.__name__
return f'class name : {clz_name}, ' + ' '.join([str(step) for step in self.steps])
def handle(self, line: str) -> str:
for step in self.steps:
line = step.handle(line)
if not line or line.isspace():
break
return line
def finish(self):
for step in self.steps:
step.finish()<file_sep>/pipline/search.py
import re
from typing import Optional
from .step import Step
class Search(Step):
"""if match(or not) the regex, then pass the line """
def __init__(self, pattern: str, block_if_match: bool = False) -> None:
self.pattern = pattern
self.block_if_match = block_if_match
def __str__(self) -> str:
clz_name = self.__class__.__name__
return f'class name : {clz_name}, regex: {self.pattern}'
def handle(self, line: str) -> str:
match_part = re.search(self.pattern, line)
if self.block_if_match:
return "" if match_part is not None else line
else:
return line if match_part is not None else ""
<file_sep>/README.md
# python_for_log
一個輔助觀察、過濾LOG的小工具,基本上也能用在文字處理上,未來看情況寫個能用web瀏覽和操作的前端。
基本上如果習慣使用grep,或是已經建有ETL,這個東西就沒啥用了
測試資料取自 [flog](https://github.com/mingrammer/flog.git)
<file_sep>/pipline/anyStep.py
from typing import Iterable
from .step import Step
class AnyStep(Step) :
""" if there was one step can handle the log, then return the first result
otherwise return empty
"""
def __init__(self, steps: Iterable[Step] = []) -> None:
self.steps = steps
def __str__(self) -> str:
clz_name = self.__class__.__name__
return f'class name : {clz_name}, ' + ' '.join([str(step) for step in self.steps])
def handle(self, line: str) -> str:
for step in self.steps:
handled = step.handle(line)
if handled and not handled.isspace():
return handled
return ""
def finish(self):
for step in self.steps:
step.finish()<file_sep>/pipline/replace.py
from abc import abstractmethod
from pipline.step import Step
class Replace(Step):
def __init__(self, pattern: str) -> None:
self.pattern = pattern
def __str__(self) -> str:
clz_name = self.__class__.__name__
return f'class name : {clz_name}, regex: {self.pattern}'
@abstractmethod
def replace(line: str) -> str:
return NotImplemented
def handle(self, line: str) -> str:
return self.replace(line)<file_sep>/pipline/fetch.py
class Fetch:
def __init__(self, pattern) -> None:
pass
|
5b5269170bdc3b1556da6157e063637433ee5839
|
[
"Markdown",
"Python"
] | 14 |
Markdown
|
ChouKevin/python_for_log
|
2a5b023cc067cf02acf8de1dfa52f62451468df6
|
8bb51500c4341485bc25ae946eda9f192ae5435b
|
refs/heads/master
|
<file_sep>#if NETCOREAPP3_1
namespace Essensoft.AspNetCore.Payment.WeChatPay
{
public abstract class WeChatPayNotify : WeChatPayObject
{
}
}
#endif
<file_sep>using System.Collections.Concurrent;
using System.Security.Cryptography.X509Certificates;
namespace Essensoft.AspNetCore.Payment.WeChatPay
{
public class WeChatPayCertificateManager
{
private readonly ConcurrentDictionary<string, X509Certificate2> _certificateDictionary = new ConcurrentDictionary<string, X509Certificate2>();
public bool ContainsKey(string hash) => _certificateDictionary.ContainsKey(hash);
public bool TryAdd(string hash, X509Certificate2 certificate) => _certificateDictionary.TryAdd(hash, certificate);
public bool TryGetValue(string hash, out X509Certificate2 certificate) => _certificateDictionary.TryGetValue(hash, out certificate);
}
}
|
4053b766b46ae1f641177983fa90d9c44297a5bb
|
[
"C#"
] | 2 |
C#
|
liangsunxp/payment
|
8a4c64853682d72428fcd3c48f85f9d844301808
|
550f263593f32a626db56bd2d34219f1938b2d01
|
refs/heads/master
|
<repo_name>BOOKSHayley/LSU_CSC1350<file_sep>/CSC1350/src/Movie.java
/**
* This is a movie class which can be used to hold all the information about a movie
*
* CSC 1350 Programming Project 11
* Section 2
*
* @author hrobe39
* @since 2 December 2019
*
*/
public class Movie {
//Step 1: make Movie class
//private variables
private String title;
private int releaseYear;
private String rating;
private String[] acceptableRatings = {"G", "PG", "PG-13", "R", "Not Rated"};
//private helper methods
/**
* checkRatings makes sure the argument is an acceptable rating
* Developed: 2 December 2019
* @author hrobe39
*
* @param rate, String value
* @return boolean whether or not the rating is G, PG, PG-13, R, or Not Rated
*/
private boolean checkRatings(String rate) {
boolean accepted = false;
for(int i = 0; i < acceptableRatings.length; i++) {
if(rate.equals(acceptableRatings[i])) {
accepted = true;
}
}
return accepted;
}
//Constructor
/**
* Constructor
* Developed: 2 December 2019
* @author hrobe39
*
* @param initTitle, String title of movie
* @param initRelYear, int release year of movie
* @param initRating, String movie rating (G, PG, PG-13, R, or Not Rated)
*/
public Movie(String initTitle, int initRelYear, String initRating) {
title = initTitle;
releaseYear = initRelYear;
rating = initRating;
}
//Public Interface:
/**
* setMovieTitle sets the movie title of the object
* Developed:2 December 2019
* @author hrobe39
*
* @param movieTitle, String title of movie
*/
public void setMovieTitle(String movieTitle) {
title = movieTitle;
}
/**
* setReleaseYear sets the release year of the object
* Developed: 2 December 2019
* @author hrobe39
*
* @param newRelYear, int release year of movie
*/
public void setReleaseYear(int newRelYear) {
if(newRelYear > 0) {
releaseYear = newRelYear;
}
}
/**
* setRating sets the rating of the object
* Developed: 2 December 2019
* @author hrobe39
*
* @param newRating, String rating (G, PG, PG-13, R, or Not Rated)
*/
public void setRating(String newRating) {
if(checkRatings(newRating)) {
rating = newRating;
}
}
/**
* movieTitle is the accessor for the movie title
* Developed: 2 December 2019
* @author hrobe39
*
* @return String title of movie
*/
public String movieTitle() {
return title;
}
/**
* releaseYear is the accessor for the release year
* Developed: 2 December 2019
* @author hrobe39
*
* @return int release year of movie
*/
public int releaseYear() {
return releaseYear;
}
/**
* rating is the accessor for the rating
* Developed: 2 December 2019
* @author hrobe39
*
* @return String rating of movie
*/
public String rating() {
return rating;
}
}
<file_sep>/CSC1350/src/Prog11_MovieLibrary.java
import java.util.Scanner;
/**
* This program makes a movie library that the user defines.
*
* CSC 1350 Programming Project 11
* Section 2
*
* @author hrobe39
* @since 2 December 2019
*
*/
public class Prog11_MovieLibrary {
/**
* validInt makes sure the user inputs a valid integer between a max and min
* Developed: 25 November 2019
* @author hrobe39
*
* @param userInput, Scanner object
* @param output, String to prompt user for information
* @param min, int minimum value (inclusive)
* @param max, int maximum value (inclusive)
* @return integer from user that is between a max and min
*/
public static int validInt(Scanner userInput, String output, int min, int max) {
boolean valid = false;
int value = 0;
do {
System.out.println(output);
if(userInput.hasNextInt()){
value = userInput.nextInt();
if(value >= min && value <= max) {
valid = true;
} else {
System.out.printf("Error: %d is not between %d and %d\n", value, min, max);
}
} else {
String badInput = userInput.next();
System.out.printf("Error: %s is not a valid input\n", badInput);
}
} while(!valid);
return value;
}
/**
* validRating makes sure the argument is an acceptable rating
* Developed: 2 December 2019
* @author hrobe39
*
* @param rate, String value
* @return boolean whether or not the rating is G, PG, PG-13, R, or Not Rated
*/
public static boolean validRating(String rate) {
String[] acceptableRatings = {"G", "PG", "PG-13", "R", "Not Rated"};
boolean accepted = false;
for(int i = 0; i < acceptableRatings.length; i++) {
if(rate.equals(acceptableRatings[i])) {
accepted = true;
}
}
return accepted;
}
/**
* getRating asks user for the rating and makes sure the rating is valid
* Developed: 2 December 2019
* @author hrobe39
*
* @param userInput, Scanner object
* @param output, String to prompt user for information
* @return String valid rating
*/
public static String getRating(Scanner userInput, String output) {
boolean valid = false;
String rating = "";
boolean firstTime = true;
do {
System.out.println(output);
if(firstTime) {
userInput.nextLine();
}
firstTime = false;
if(userInput.hasNextLine()) {
rating = userInput.nextLine();
if(validRating(rating)) {
valid = true;
} else {
System.out.printf("%s is not a valid rating.\n", rating);
}
}
} while(!valid);
return rating;
}
/**
* getString takes the nextLine from the user
* Developed: 2 December 2019
* @author hrobe39
*
* @param output, String prompts user for information
* @return String from user
*/
public static String getString(String output) {
Scanner userInput = new Scanner(System.in);
String value = "";
System.out.println(output);
if(userInput.hasNextLine()) {
value = userInput.nextLine();
}
return value;
}
/**
* sortArray sorts an array in alphabetical order
* Developed: 25 November 2019
* Modified: 2 December 2019
* @author hrobe39
*
* @param arr, String array
*/
public static void sortArray(Movie[] arr) {
boolean sorted = false;
int i = 1;
while(!sorted) {
if(i == arr.length) {
sorted = true;
} else {
sorted = true; //assume sorted is true
for(int j = 0; j < arr.length-i; j++) {
if(arr[j].movieTitle().compareTo(arr[j+1].movieTitle()) > 0) {
swapElts(arr, j, j+1);
sorted = false; //if swapped 2 elements, then it is not completely sorted
}
}
}
i++; //make sure to increment i
}
}
/**
* swapElts swaps two elements in an array
* Developed: 25 November 2019
* Modified: 2 December 2019
* @author hrobe39
*
* @param arr, String array
* @param elt1, one element to switch
* @param elt2, second element to switch
*/
public static void swapElts(Movie[] arr, int elt1, int elt2){
Movie temp = arr[elt1];
arr[elt1] = arr[elt2];
arr[elt2] = temp;
}
public static void mainMethod() {
//Step 2: make Scanner object and variables
Scanner userInput = new Scanner(System.in);
//Step 3: ask user for number of movies and make array of that many movies
int numMovies = validInt(userInput, "How many movies are in your personal library?", 1, 100);
Movie[] movieLib = new Movie[numMovies];
//Step 4: fill array with info from user (use methods to help with this)
for(int i = 0; i < movieLib.length; i++) {
String title = getString("Enter the movie title:");
int releaseYear = validInt(userInput, "Enter the year the movie was released:", 1900, 2020);
String rating = getRating(userInput, "Enter the movie rating (G, PG, PG-13, R, or Not Rated):");
movieLib[i] = new Movie(title, releaseYear, rating);
}
//Step 5: sort the array alphabetically by movie title
sortArray(movieLib);
//Step 6: print out the movie library
System.out.println();
System.out.println("Movie Library:");
for(int i = 0; i < movieLib.length; i++) {
System.out.printf("%-13s %s\n", "Movie Title:", movieLib[i].movieTitle());
System.out.printf("%-13s %d\n", "Release Year:", movieLib[i].releaseYear());
System.out.printf("%-13s %s\n", "Rating:", movieLib[i].rating());
System.out.println();
}
//Step 7: Close Scanner object so no resource leak
userInput.close();
}
}
<file_sep>/CSC1350/src/MainClass.java
/**
* This is the main class, where the main methods in each project can be called.
* @author hayle
*
*/
public class MainClass {
public static void main(String[] args) {
//Prog01_ExploringJava.mainMethod();
//Prog02_EasterCalc.mainMethod();
//Prog03_PayCalc.mainMethod();
//Prog04_LoanCalc.mainMethod();
//Prog05_GCD.mainMethod();
//Prog06_Psychic.mainMethod();
//Prog07_Qualify.mainMethod();
//Prog08_Trend.mainMethod();
//Prog09_Minesweep.mainMethod();
//Prog10_MovieLib.mainMethod();
//Prog11_MovieLibrary.mainMethod();
}
}
<file_sep>/CSC1350/src/Prog05_GCD.java
import java.util.Scanner;
/**
* This program is designed o find the Greatest Common Divisor between two positive integers
*
* CSC 1350 Programming project #5
* Section 2
*
* @author hrobe39
* @since October 14, 2019
*/
public class Prog05_GCD {
public static void mainMethod() {
//Step 1 - Create a Scanner and prompt user for 2 numbers
Scanner userInput = new Scanner(System.in);
boolean inputValid = false; //Boolean flag for input validation
//2 numbers from the user. initialization doesn't matter.
int num1 = 0;
int num2 = 0;
int smallestNum = 0; //this is for iteration purposes
int gcd = 1; //Greatest common divisor. Init to 1 bc all numbers are divisible by 1
//input validation for the 2 positive integers
do {
System.out.println("Please enter an integer greater than 0: ");
if(userInput.hasNextInt()) {
num1 = userInput.nextInt();
if(num1 > 0) {
inputValid = true;
} else {
System.out.printf("Error: %d is not greater than 0.\n", num1);
}
} else {
String badInput = userInput.next(); //must take badInput or get an infinite loop
System.out.printf("Error: %s is not an integer.\n", badInput);
}
}while(!inputValid);
inputValid = false; //need to reset boolean for next input validation
do {
System.out.println("Please enter another integer greater than 0: ");
if(userInput.hasNextInt()) {
num2 = userInput.nextInt();
if(num2 > 0) {
inputValid = true;
} else {
System.out.printf("Error: %d is not greater than 0.\n", num2);
}
} else {
String badInput = userInput.next(); //must take badInput or get an infinite loop
System.out.printf("Error: %s is not an integer.\n", badInput);
}
}while(!inputValid);
//Step 2 - find the greatest common divisor through iteration
//find out which number is smallest so don't iterate too far
if(num1 > num2) {
smallestNum = num2;
} else {
smallestNum = num1;
}
//iterate until k is the smallest number (gcd may be smallest number)
for(int k = 1; k <= smallestNum; k++) {
//if the remainder between num and k is 0, num is divisible by k and thus a divisor
if(num1%k == 0 && num2%k == 0) {
gcd = k;
}
}
//tell the user the GCD
System.out.printf("\nThe greatest common divisor of %d and %d is %d\n", num1, num2, gcd);
//Step 3 - print the divisors of each number
System.out.printf("\nDivisors for %d:\n", num1);
//iterate until k is num1 bc num1 is a divisor of itself
for(int k = 1; k <= num1; k++) {
//if the remainder between num1 and k is 0, num1 is divisible by k and thus a divisor
if(num1 % k == 0) {
System.out.println(k);
}
}
System.out.printf("\nDivisors for %d:\n", num2);
//iterate until k is num2 bc num2 is a divisor of itself
for(int k = 1; k <= num2; k++) {
//if the remainder between num2 and k is 0, num2 is divisible by k and thus a divisor
if(num2 % k == 0) {
System.out.println(k);
}
}
//close Scanner so no resource leak
userInput.close();
}
}
<file_sep>/CSC1350/src/Prog06_Psychic.java
import java.util.Scanner;
/**
* This program is designed to test the user's psychic ability
* by seeing if they can guess a randomly-generated whole number
*
* CSC 1350 Programming Project # 6
* Section 2
*
* @author <NAME> (hrobe39)
* @since 21 October 2019
*
*/
public class Prog06_Psychic {
/**
* validInt checks to see if the user entered an integer.
* If a non-integer is entered, the user is prompted until they do.
* Development date: 21 October 2019
* @author <NAME> (hrobe39)
*
* @param scanner, Scanner object to take in user input
* @param output, String that user will see to prompt for integer
* @return valid integer that the user entered
*/
//Step 2: Create method to check for valid integer
public static int validInt(Scanner scanner, String output) {
boolean validInput = false;
int toReturn = 0;
do {
System.out.print(output);
if(scanner.hasNextInt()) {
toReturn = scanner.nextInt();
validInput = true;
} else {
String badInput = scanner.next();
System.out.printf("Error: %s is not a valid input.\n", badInput);
}
} while(!validInput);
return toReturn;
}
/**
* generateRandomNumber makes a random number within a range.
* Development date: 21 October 2019
* @author <NAME> (hrobe39)
*
* @param max, integer that is the upper bound for random number, inclusive
* @param min, integer that is the lower bound for the random number, inclusive
* @return random integer between max and min (inclusive)
*/
//Step 3: create method to return a random number in a range
public static int generateRandomNumber(int max, int min) {
return min + (int)(Math.random() * (max - min + 1));
}
public static void mainMethod() {
//Step 1: create scanner and get upper and lower bounds
Scanner userInput = new Scanner(System.in);
//initialize flag booleans for input validation
boolean validUpperBound = false; //check to see is upperBound is 3 numbers higher than lower bound
boolean sentinelVal = false; //check to see if the sentinel value (q/Q) is entered
//initialize number variables for computations
int upperBound = 0;
int lowerBound = 0;
int randomNumber = 0;
int userNumber = 0;
double correctCounter = 0;
double totalCounter = 0;
double successRate = -1;
System.out.println("So you think you're psychic? Well, let's put that to the test!");
System.out.println("\nI will pick a number in a range, and you have to \"guess\" what the number is.\nI will let you pick the range.");
//get lower and upper bounds
lowerBound = validInt(userInput, "Please enter the whole number lower bound of the range:");
//check to see if upperBound is 3 numbers higher than lowerBound
do {
upperBound = validInt(userInput, "Please enter the whole number upper bound of the range (at least 3 numbers higher than " + lowerBound + "):");
if(upperBound >= lowerBound + 3) {
validUpperBound = true;
} else {
System.out.printf("Error: %d is not 3 numbers higher than %d.\n", upperBound, lowerBound);
}
} while(!validUpperBound);
//Step 4: generate a random number and see if user entered that number
do {
randomNumber = generateRandomNumber(upperBound, lowerBound);
System.out.printf("Enter a whole number between %d and %d or Q to quit:", upperBound, lowerBound);
//if integer is not inputed, might be sentinel
if(userInput.hasNextInt()) {
userNumber = userInput.nextInt();
totalCounter++; //increment here so can get total number of inputs
if(userNumber == randomNumber) {
correctCounter++; //increment here so can get total number of correct inputs
System.out.printf("Well, you must be psychic! You guessed the correct number: %d\n", randomNumber);
} else {
System.out.printf("I am doubting your psychic abilities. You did not guess the right number: %d\n", randomNumber);
}
} else {
String badInput = userInput.next();
if(badInput.equals("Q") || badInput.equals("q")) { //if sentinel (upper or lower case), user finished playing. End loop.
sentinelVal = true;
} else { //if not the sentinel, just a typo. User keeps playing.
System.out.printf("Error: %s is not a valid input.\n", badInput);
}
}
}while(!sentinelVal);
//Step 5: calculate successRate and output to user.
successRate = correctCounter / totalCounter * 100;
System.out.printf("Your success rate is %.5f%%", successRate);
System.out.println("\nThanks for playing!");
//Step 6: close Scanner so no resource leak
userInput.close();
}
}
<file_sep>/CSC1350/src/Prog10_MovieLib.java
import java.util.Scanner;
/**
* This program is a library of movies. The user can enter movies and search for movies they entered
* CSC 1350 Programming Project #10
* Section 2
*
* @author hrobe39
* @since 25 November 2019
*
*/
public class Prog10_MovieLib {
/**
* validInt makes sure the user inputs a valid integer between a max and min
* Developed: 25 November 2019
* @author hrobe39
*
* @param userInput, Scanner object
* @param output, String to prompt user for information
* @param min, int minimum value (inclusive)
* @param max, int maximum value (inclusive)
* @return integer from user that is between a max and min
*/
public static int validInt(Scanner userInput, String output, int min, int max) {
boolean valid = false;
int value = 0;
do {
System.out.println(output);
if(userInput.hasNextInt()){
value = userInput.nextInt();
if(value >= min && value <= max) {
valid = true;
} else {
System.out.printf("Error: %d is not between %d and %d\n", value, min, max);
}
} else {
String badInput = userInput.next();
System.out.printf("Error: %s is not a valid input", badInput);
}
} while(!valid);
return value;
}
/**
* fillArray fills a given array with strings from the user
* Developed: 25 November 2019
* @author hrobe39
*
* @param userInput, Scanner object
* @param arr, empty String array to be filled
* @param output, String to prompt user for information
* @param sentinel, String value that is user enters, the program stops
*/
public static void fillArray(Scanner userInput, String[] arr, String output) {
userInput.hasNextLine();
for(int i = 0; i <arr.length; i++) {
System.out.println(output);
if(i == 0) {
userInput.nextLine(); //do this so first value taken is not the empty string
}
if(userInput.hasNextLine()) {
String value = userInput.nextLine();
arr[i] = value;
}
}
}
/**
* sortArray sorts an array in alphabetical order
* Developed: 25 November 2019
* @author hrobe39
*
* @param arr, String array
*/
public static void sortArray(String[] arr) {
boolean sorted = false;
int i = 1;
while(!sorted) {
if(i == arr.length) {
sorted = true;
} else {
sorted = true; //assume sorted is true
for(int j = 0; j < arr.length-i; j++) {
if(arr[j].compareTo(arr[j+1]) > 0) {
swapElts(arr, j, j+1);
sorted = false; //is swapped 2 elements, then it is not completely sorted
}
}
}
i++; //make sure to increment i
}
}
/**
* searchArray looks through the array for a search value
* Developed: 25 November 2019
* @author hrobe39
*
* @param arr, String array to search through
* @param searchVal, String that user is looking for
* @return int position in array (-1 if not found)
*/
public static int searchArray(String[] arr, String searchVal) {
int position = -1;
boolean found = false;
int i = 0;
while(i < arr.length && !found) {
if(arr[i].equals(searchVal)) {
position = i;
}
i++;
}
return position;
}
/**
* swapElts swaps two elements in an array
* Developed: 25 November 2019
* @author hrobe39
*
* @param arr, String array
* @param elt1, one element to switch
* @param elt2, second element to switch
*/
public static void swapElts(String[] arr, int elt1, int elt2){
String temp = arr[elt1];
arr[elt1] = arr[elt2];
arr[elt2] = temp;
}
public static void mainMethod() {
//Step 1: make Scanner object and variables
Scanner userInput = new Scanner(System.in);
boolean reachedSentinel = false;
String searchVal = "";
int searchValPosition = -1;
//Step 2: ask user for number of movies in lib, and make array with that many movies
int numMovies = validInt(userInput, "How many movies are in your personal library?", 1, 100);
String[] movieLibrary = new String[numMovies];
//Step 3: make method to fill the array
fillArray(userInput, movieLibrary, "Enter Movie Title:");
//Step 4: make a method to sort the array alphabetically
sortArray(movieLibrary);
System.out.println(); //space in console before letting user search
//Step 5: Ask the user what they want to search for
do {
System.out.println("Enter a movie to search or Q to stop:");
if(userInput.hasNextLine()) {
searchVal = userInput.nextLine(); //do this so doesn't take empty string as first val
if(searchVal.equals("Q") || searchVal.equals("q")) { //if user enters q or Q(sentinel), then stop loop
reachedSentinel = true;
} else { //did not reach sentinel, so need to search through array
searchValPosition = searchArray(movieLibrary, searchVal);
if(searchValPosition > -1) { //if position == -1, then the movie was not found
System.out.printf("The %s movie is in the library at position %d.\n", searchVal, searchValPosition);
} else {
System.out.printf("%s is not a movie in the library.\n", searchVal);
}
}
}
} while(!reachedSentinel);
System.out.println(); //space in console before printing the library
//Step 6: print library
System.out.println("Movie Library: ");
for(int i = 0; i < movieLibrary.length; i++) {
System.out.println(movieLibrary[i]);
}
//Step 7: close userInput so no resource leak
userInput.close();
}
}
|
1fc156d447cabf82424f5a3a9792a87ec1177d74
|
[
"Java"
] | 6 |
Java
|
BOOKSHayley/LSU_CSC1350
|
c43a4270d1f429e33825db18a7e733dc9ebdb632
|
7a41671cb1932162bf5be4d1dd15a27d709db2c4
|
refs/heads/master
|
<file_sep>import Alert from 'react';
const api1 = 'https://api.pm.pa.gov.br/';
const api2 = 'http://localhost:3000';
function showError(err) {
Alert.alert('Ops! Ocorreu um problema!', `Mensagem: ${err}`);
}
export {api1, showError, api2};
/*import axios from "axios";
const api = axios.create({
baseURL: "https://api.pm.pa.gov.br/"
//baseURL: "http://127.0.0.1:3333"
});
const api2 = axios.create({
baseURL: "http://localhost:3000"
})
api.interceptors.request.use(async config => {
const token = getToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
export default (api, api2);*/
<file_sep>import styled from "styled-components";
export const Slide = styled.div`
margin-top: 5
`;
<file_sep>import React from "react";
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";
import { isAuthenticated } from "./services/auth";
import SignUp from "./pages/SignUp/Dropdown";
import SignIn from "./pages/SignIn";
import Home from "./pages/Home";
import ListUsers from "./pages/ListUsers/index";
import Apresentation from "./pages/Apresentation/index";
import Report from "./pages/Report"
import DetailReport from"./pages/DetailReport"
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
isAuthenticated() ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: "/", state: { from: props.location } }} />
)
}
/>
);
const Routes = () => (
<BrowserRouter>
<Switch>
<Route exact path="/" component={SignIn} />
<Route path="/signup" component={SignUp} />
<Route path="/apresentation" component={Apresentation} />
<Route path="/home" component={Home} />
<Route path="/listusers" component={ListUsers} />
<Route path="/report" component={Report} />
<Route path="/detailreport" component={DetailReport} />
<PrivateRoute path="/app" component={() => <h1>App</h1>} />
<Route path="*" component={() => <h1>Page not found</h1>} />
</Switch>
</BrowserRouter>
);
export default Routes;
<file_sep>import React, { Component } from "react";
import { withRouter, Link } from "react-router-dom";
import Header from '../../components/Header';
import axios from "axios";
import {api2} from "../../services/api";
import { Form, Container } from "./styles";
import moment from "moment";
import 'moment/locale/pt-br';
class Report extends Component {
state = {
produto: [],
card: false,
eventos: [],
cautelaAb: [],
cautelaClos: [],
titulo: '',
cauthVisible: true,
users: [],
cautelas: '',
viewCautela: [],
};
async componentDidMount() {
const mytoken = localStorage.getItem('token')
console.log(mytoken)
this.loadUsers()
}
loadUsers = async () => {
const token = localStorage.getItem('token');
const header = {
"Authorization" : `Bearer ${token}`
}
// axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}
const res = await axios.get(`${api2}/api/material/all`, {headers: header})
const data = res.data.payload
console.log(data)
this.setState({
produto: data
});
const event = await axios.get(`${api2}/api/evento/all`);
const even = event.data.payload
console.log(even)
this.setState({
eventos: even
})
console.log(even);
const cauth = await axios.get(`${api2}/api/cautela/1`);
const caut = cauth.data.payload
console.log(caut)
this.setState({
cautelaAb: caut
})
console.log(caut);
const cauthOpen = await axios.get(`${api2}/api/cautela/0`);
const cautOpen = cauthOpen.data.payload
console.log(cautOpen)
this.setState({
cautelaClos: cautOpen
})
console.log(cautOpen);
const cautela = await axios.get(`${api2}/api/cautela/1`);
const cautelaDetail = cautela.data.payload;
this.setState({
cautelaAb: cautelaDetail
})
console.log(cautelaDetail);
}
abrirCautela = async e => {
const abrir = await axios.get(`${api2}/api/cautela/${e.id}`)
const abrirEvent = abrir.data.payload;
localStorage.setItem('detail', JSON.stringify(abrir.data))
console.log(abrirEvent)
this.props.history.push("/detailreport", e.id);
};
render() {
const { eventos } = this.state;
return (
<div className="bs-component">
<Header />
<Container className="list-users">
<div className="div" >
<Link>
{eventos.map(evento => (
<Form key={evento.id} onClick={()=>this.abrirCautela(evento)}>
<h5>EVENTO: {evento.nome}</h5>
<p>COMANDANTE: {evento.nomeComandante}</p>
<p>LOCAL: {evento.local}</p>
<p>DATA: {''}
{moment(evento.data).format(
"DD [de] MMMM [de] YYYY [às] HH:mm", "pt", true
)}</p>
</Form>
))}
</Link>
</div>
</Container>
</div>
)
}
}
export default withRouter(Report);
<file_sep>import React, { Component } from "react";
import { Link, withRouter } from "react-router-dom";
import axios from "axios"
import {api2} from "../../services/api";
import Popup from "reactjs-popup"
import { Form, Container } from "./styles";
class Home extends Component {
state = {
descricao: '',
rp: '',
setor: '',
status: 0
};
async componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
const meuId = localStorage.getItem('meuId')
console.log('IF', meuId === "76140881234")
if (meuId === "76140881234") {
await this.setState({
card: true
})
console.log('ta mudando o valor já', this.state.card)
setTimeout(() => {
console.log('timeout', this.state.card)
}, 3000);
}
}
clean() {
localStorage.clear()
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
handleSignUp = e => {
e.preventDefault();
e.target.reset();
alert("Eu vou te registrar");
};
handleSignUp = async e => {
e.preventDefault();
e.target.reset()
const { descricao, rp, setor, status } = this.state;
if (!descricao || !rp || !setor ) {
this.setState({ error: "Preencha todos os CAMPOS para prosseguir!!!" });
} else {
try {
await axios.post(`${api2}/api/material/create`, { descricao, rp, setor, status });
this.props.history.push("/home");
console.log(this.state)
} catch (err) {
console.log(err);
this.setState({ error: "Ocorreu um erro ao salvar os dados." });
}
}
};
render() {
const { descricao, rp, setor } = this.state;
const enabled =
descricao.length > 0 &&
rp.length > 0 &&
setor.length > 0;
return (
<Container>
<Form onSubmit={this.handleSignUp.bind(this)}>
{this.state.error && <p>{this.state.error}</p>}
<h3>Cadastro de HT'S</h3>
<input
type="text"
placeholder="Modelo"
onChange={e => this.setState({ descricao: e.target.value })}
/>
<input
type="text"
placeholder="Nº de Série"
onChange={e => this.setState({ rp: e.target.value })}
/>
<input
type="text"
placeholder="Setor"
onChange={e => this.setState({ setor: e.target.value })}
/>
<input
disabled={true}
type="number"
placeholder="ATENÇÃO, confira os dados antes de salvar."
onChange={e => this.setState({ status: e.target.value })}
/>
<Popup
trigger={<button type="submit" disabled={!enabled}>Salvar</button>} position="center center" >
<div>
O HT:
<br />
Modelo: {this.state.descricao}
<br />
Nº de Série: {this.state.rp}
<br />
Setor: {this.state.setor}
<br />
<div>Foi salvo com sucesso"</div>
</div>
</Popup>
<hr />
<Link to="/apresentation">Voltar</Link>
</Form>
</Container>
);
}
}
export default withRouter(Home);
<file_sep>import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import md5 from "md5";
import Logo from "../../assets/images/logoCitel.png";
import { api1 } from "../../services/api";
import axios from 'axios';
import Background from '../../assets/images/fundo.jpg';
import { Form, Container } from "./styles";
class SignIn extends Component {
state = {
cpf: "",
senha: "",
error: ""
};
handleSignIn = async e => {
e.preventDefault();
const { cpf, senha } = this.state;
console.log('senha', senha);
if (!cpf || !senha) {
this.setState({ error: "Preencha o cpf e Senha para continuar!" });
} else {
try {
await axios.post(`${api1}api/v1/auth/appidentidade`, {
cpf: this.state.cpf,
senha: md5(this.state.senha),
})
.then(res => {
axios.defaults.headers.common['X-Token'] = `${res.data.payload.token}`
console.log(res.data.payload.token)
localStorage.setItem('userData', JSON.stringify(res.data))
localStorage.setItem('token', res.data.payload.token)
let obj = res.data
localStorage.setItem('meuId', cpf)
console.log(obj)
this.props.history.push("/apresentation");
})
}catch (err) {
this.setState({
error:
"Houve um problema com o login, verifique os dados informados"
});
console.log(err)
}
}
};
render() {
return (
<Container style={{backgroundImage: `url(${Background})`}}>
<Form onSubmit={this.handleSignIn}>
<img src={Logo} alt="Airbnb logo" />
{this.state.error && <p>{this.state.error}</p>}
<input
type="text"
placeholder="Digite o CPF"
onChange={e => this.setState({ cpf: e.target.value })}
/>
<input
type="password"
placeholder="Senha"
onChange={e => this.setState({ senha: e.target.value })}
/>
<button type="submit">Entrar</button>
<hr />
</Form>
</Container>
);
}
}
export default withRouter(SignIn);
<file_sep>import React from 'react';
import { withRouter, Link } from "react-router-dom";
import './style.css';
class SignUp extends React.Component {
constructor(){
super();
this.state = {
displayMenu: false,
inform: ''
};
this.showDropdownMenu = this.showDropdownMenu.bind(this);
this.hideDropdownMenu = this.hideDropdownMenu.bind(this);
};
async componentDidMount() {
const dados = localStorage.getItem('userData');
const info = JSON.parse(dados);
console.log(info)
this.setState({
inform: info
})
}
showDropdownMenu(event) {
event.preventDefault();
this.setState({ displayMenu: true }, () => {
document.addEventListener('click', this.hideDropdownMenu);
});
}
hideDropdownMenu() {
this.setState({ displayMenu: false }, () => {
document.removeEventListener('click', this.hideDropdownMenu);
});
}
render() {
return (
<div className="dropdown" style = {{width:"20px"}}>
<div className="button" onClick={this.showDropdownMenu}>CITEL</div>
{ this.state.displayMenu ? (
<ul>
<li>Nome: {this.state.inform.payload.nome_guerra}</li>
<li>Unidade: {this.state.inform.payload.Unidade.sigla_unidade}</li>
<Link to="/" className="link">Sair</Link>
</ul>
):
(
null
)
}
</div>
);
}
}
export default withRouter(SignUp);
<file_sep>import styled from "styled-components";
export const Container = styled.div`
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-around;
align-items: baseline;
align-content: stretch;
padding: 10px;
div {
margin-top: 80px;
background: #fff;
border: 1px solid #ddd;
border-radius: 5px;
padding: 10px;
margin-bottom: 5px;
width: 100%;
}
.buton {
height: 42px;
font-size: 16px;
border: 2px solid #00008B;
background: none;
margin-top: 10px;
color: #da552f;
font-weight: bold;
text-decoration: none;
justify-content: center;
align-items: center;
transition: all 0.2s;
}
`;
export const Header = styled.header`
width: 100%;
height: 100%;
background: blue;
font-size: 20px;
font-weight: robot;
color: white;
display: flex;
justify-content: center;
align-items: center;
padding: 10px;
:hover{
background: #fc6963;
color: #fff
}
`
export const Form = styled.form`
background: #fff;
border: 1px solid #ddd;
border-radius: 5px;
padding: 20px;
margin-bottom: 20px;
cursor: pointer
strong {
color: black;
font-size: 18px
}
p {
}
a {
display: flex;
flex-direction: row;
height: 42px;
font-size: 16px;
border: 2px solid #00008B;
background: none;
margin-top: 10px;
color: #da552f;
font-weight: bold;
text-decoration: none;
display: flex;
justify-content: center;
align-items: center;
transition: all 0.2s;
padding: 10px
}
a:hover {
background: #da552f;
color: #fff
}
h5 {
text-align: center
}
#idMaterial {
margin-left: 50px;
margin-bottom: 1px
}
`;
<file_sep>import React, {useState} from 'react';
import * as ReactDOM from "react-dom";
import {Drawer} from 'react-pretty-drawer';
import Logo from "../../assets/images/logoCitel.png";
import { Link, withRouter } from "react-router-dom";
import { FaEdit, FaList, FaClipboardList } from 'react-icons/fa';
import moment from "moment";
import 'moment/locale/pt-br';
const data = moment().format("DD [de] MMMM [de] YYYY", "pt", true);
const Example = () => {
let [visible, setIsVisible] = useState(false);
const closeDrawer = () => setIsVisible(false);
const openDrawer = () => setIsVisible(true);
return (
<div >
<Drawer
visible={visible}
onClose={closeDrawer}
>
<div style={{ border: 3 }}>
<Link to="/apresentation">
<img src={Logo} alt="Airbnb logo" onClick={"/apresentation"} style={{width: 100, height: 120, marginTop: 120,
marginLeft: 70, marginBlockEnd: 40}} />
</Link>
</div>
<hr style={{borderWidth: 4}} />
<div style={{marginLeft: 35 }}><moment>{data}</moment></div>
<hr style={{borderWidth: 4}} />
<div style={{marginTop: 20}}>
<Link to="/home" style={{fontSize: 20, cursor: 'pointer'}} > <FaEdit color='#00008B' size={30} /> Cadastrar HT's</Link>
</div>
<div style={{marginTop: 20}}>
<Link to="/listusers" style={{fontSize: 20, cursor: 'pointer'}}> <FaList color='#00008B' size={30} /> Listar HT's</Link>
</div>
<div style={{marginTop: 20}}>
<Link to="/report" style={{fontSize: 20, cursor: 'pointer'}}> <FaClipboardList color='#00008B' size={30} /> Relatório</Link>
</div>
</Drawer>
<h3 onClick={openDrawer} style={{color: 'white',
cursor: 'pointer', fontFamily: 'roboto'}}>SISTEMA DE CAUTELA CIRIO DE NAZARÉ</h3>
</div>
);
};
ReactDOM.render(<Example />, document.getElementById("root"));
export default withRouter(Example);
<file_sep>import React, { Component } from "react";
import { withRouter, Link } from "react-router-dom";
import Header from '../../components/Header';
import axios from "axios";
import {api2} from "../../services/api";
import { Form, Container } from "./styles";
import QrCode from 'qrcode.react'
class ListUsers extends Component {
state = {
produto: [],
card: false,
eventos: [],
cautelaAb: [],
cautelaClos: []
};
async componentDidMount() {
const mytoken = localStorage.getItem('token')
const meuId = localStorage.getItem('meuId')
console.log('IF', meuId === "76140881234")
console.log(mytoken)
this.loadUsers();
}
loadUsers = async () => {
const token = localStorage.getItem('token');
const header = {
"Authorization" : `Bearer ${token}`
}
// axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}
const res = await axios.get(`${api2}/api/material/all`, {headers: header})
const data = res.data.payload
console.log(data)
this.setState({
produto: data
});
const event = await axios.get(`${api2}/api/evento/all`);
const even = event.data.payload
console.log(even)
this.setState({
eventos: even
})
console.log(even);
const cauth = await axios.get(`${api2}/api/cautela/1`);
const caut = cauth.data.payload
console.log(caut)
this.setState({
cautelaAb: caut
})
console.log(caut);
const cauthOpen = await axios.get(`${api2}/api/cautela/0`);
const cautOpen = cauthOpen.data.payload
console.log(cautOpen)
this.setState({
cautelaClos: cautOpen
})
console.log(cautOpen)
}
render() {
const { produto } = this.state;
const { eventos } = this.state;
const { cautelaAb } = this.state;
const { cautelaClos } = this.state
return (
<div className="bs-component">
<Header />
<Container className="list-users">
<div className="div">
HT'S: <hr />
TOTAL: {produto.length}
<div className="buton">
<Link>Detalhes</Link>
</div>
</div>
<div className="div">
EVENTOS: <hr />
TOTAL: {eventos.length}
<div className="buton">
<Link>Detalhes</Link>
</div>
</div>
<div className="div">
CAUTELAS EM ABERTO: <hr />
TOTAL: {cautelaAb.length}
<div className="buton">
<Link>Detalhes</Link>
</div>
</div>
<div className="div">
CAUTELAS ENCERRADAS: <hr />
TOTAL: {cautelaClos.length}
<div className="buton">
<Link>Detalhes</Link>
</div>
</div>
{produto.map(prod => (
<Form key={prod.id}>
<strong>Modelo: {prod.descricao}</strong>
<p>Nº de Série: {prod.idMaterial}</p>
<p>Setor: {prod.setor}</p>
<QrCode id="idMaterial"
value={prod.idMaterial.toString()}
size={120}
level={"H"}
includeMargin={true}
/>
</Form>
))}
</Container>
</div>
)
};
}
export default withRouter(ListUsers);
|
7e9fef7dd20372112356dd40dcecbe75bab24301
|
[
"JavaScript"
] | 10 |
JavaScript
|
CHOQUEANO11/SistemaCautela
|
d6ff85d1d5510674afa543d98b60c648334abaa4
|
d2d2b79968044a27b02a86044c33dde0458d57c9
|
refs/heads/master
|
<repo_name>aboosh1313/data_science_repo<file_sep>/README.md
# data_science_repo
# abdullah chaenged this file
# another change
|
476f3f52682cc7395d240a4c6b08a0f944c7cdba
|
[
"Markdown"
] | 1 |
Markdown
|
aboosh1313/data_science_repo
|
0bf1e3b1728a12d17f73397ad5f030aa1a6ac4ed
|
f1c3820fb45f4affce422e0ec13c403a2e662643
|
refs/heads/main
|
<repo_name>Anis662/projet_portfolio_Anis_ElOuahidi<file_sep>/app/Http/Controllers/SkilController.php
<?php
namespace App\Http\Controllers;
use App\Models\Skil;
use Illuminate\Http\Request;
class SkilController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view("skil.create");
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$skil = new Skil();
$request->validate([
"langue" => "required",
"pourcentage" => "required"
]);
$skil->pourcentage = $request->pourcentage;
$skil->langue = $request->langue;
$skil->save();
return redirect()->route("admin");
}
/**
* Display the specified resource.
*
* @param \App\Models\Skil $skil
* @return \Illuminate\Http\Response
*/
public function show(Skil $skil)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Skil $skil
* @return \Illuminate\Http\Response
*/
public function edit(Skil $skil)
{
return view("skil.edit",compact("skil"));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Skil $skil
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Skil $skil)
{
$request->validate([
"langue" => "required",
"pourcentage" => "required"
]);
$skil->pourcentage = $request->pourcentage;
$skil->langue = $request->langue;
$skil->save();
return redirect()->route("admin");
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Skil $skil
* @return \Illuminate\Http\Response
*/
public function destroy(Skil $skil)
{
$skil->delete();
return redirect()->back();
}
}
<file_sep>/resources/views/portfolio/table.blade.php
<a href="{{ route("portfolio.create") }}" class="btn btn-danger">CREATE</a>
<table class="table mt-5">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">IMAGE</th>
<th scope="col">CATEGORIE</th>
<th scope="col">ACTION</th>
</tr>
</thead>
@foreach ($portfolio as $e )
<tbody>
<tr>
<td>{{ $e->id }}</td>
<td><img src="{{ asset("img/$e->image") }}" alt=""></td>
<td>{{ $e->categorie }}</td>
<td class="d-flex">
<a href="/admin/portfolio/{{ $e->id }}/edit" class="btn btn-success">EDIT</a>
<form action="/admin/portfolio/{{ $e->id }}" method="POST">
@csrf
@method("delete")
<button class="btn btn-danger" type="submit">DELETE</button>
</form>
</td>
</tr>
</tbody>
@endforeach
</table>
<file_sep>/resources/views/admin.blade.php
@extends('templates.structure')
@section('content')
<section class="container">
@include('about.table')
@include("fact.table")
@include("skil.table")
@include("portfolio.table")
</section>
@endsection<file_sep>/resources/views/about/table.blade.php
<h1 class="text-center">About</h1>
<a href="{{ route("about.create") }}" class="btn btn-danger">CREATE</a>
<table class="table-responsive table-dark" >
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">PHOTO</th>
<th scope="col">ANNIVERSAIRE</th>
<th scope="col">WEBSITE</th>
<th scope="col">PHONE</th>
<th scope="col">CITY</th>
<th scope="col">AGE</th>
<th scope="col">DEGRE</th>
<th scope="col">MAIL</th>
<th scope="col">FREELANCE</th>
<th scope="col">TEXTE</th>
<th scope="col">ACTION</th>
</tr>
</thead>
@foreach ($about as $e)
<tbody>
<tr>
<td>{{ $e->id }}</td>
<td><img src="{{ asset("img/$e->photo") }}" alt=""></td>
<td>{{ $e->aniversaire }}</td>
<td>{{ $e->website }}</td>
<td>{{ $e->phone }}</td>
<td>{{ $e->city }}</td>
<td>{{ $e->age }}</td>
<td>{{ $e->degre }}</td>
<td>{{ $e->mail }}</td>
<td>{{ $e->freelance }}</td>
<td>{{ $e->texte }}</td>
<td class="d-flex">
<a href="/admin/about/{{ $e->id }}/edit" class="btn btn-success">EDIT</a>
<form action="/admin/about/{{ $e->id }}" method="POST">
@csrf
@method("delete")
<button class="btn btn-danger" type="submit">DELETE</button>
</form>
</td>
</tr>
</tbody>
@endforeach
</table>
<file_sep>/resources/views/about/about.blade.php
<section id="hero" class="d-flex flex-column justify-content-center align-items-center">
<div class="hero-container" data-aos="fade-in">
<h1><NAME></h1>
<p>I'm <span class="typed" data-typed-items="Designer, Developer, Freelancer, Photographer"></span></p>
</div>
</section>
<section id="about" class="about">
<div class="container">
<div class="section-title">
<h2>About</h2>
<p>Magnam dolores commodi suscipit. Necessitatibus eius consequatur ex aliquid fuga eum quidem. Sit sint consectetur velit. Quisquam quos quisquam cupiditate. Et nemo qui impedit suscipit alias ea. Quia fugiat sit in iste officiis commodi quidem hic quas.</p>
</div>
@foreach ($about->take(1) as $e )
<div class="row">
<div class="col-lg-4" data-aos="fade-right">
<img src="{{asset("img/$e->photo")}}" class="img-fluid" alt="">
</div>
<div class="col-lg-8 pt-4 pt-lg-0 content" data-aos="fade-left">
<h3>UI/UX Designer & Web Developer.</h3>
<p class="font-italic">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua.
</p>
<div class="row">
<div class="col-lg-6">
<ul>
<li><i class="icofont-rounded-right"></i> <strong>Birthday:</strong> {{ $e->aniversaire }}</li>
<li><i class="icofont-rounded-right"></i> <strong>Website:</strong>{{ $e->website }}</li>
<li><i class="icofont-rounded-right"></i> <strong>Phone:</strong> {{ $e->phone }}</li>
<li><i class="icofont-rounded-right"></i> <strong>City:</strong> City : {{ $e->city }}</li>
</ul>
</div>
<div class="col-lg-6">
<ul>
<li><i class="icofont-rounded-right"></i> <strong>Age:</strong> {{ $e->age }}</li>
<li><i class="icofont-rounded-right"></i> <strong>Degree:</strong> {{ $e->degre }}</li>
<li><i class="icofont-rounded-right"></i> <strong>PhEmailone:</strong> {{ $e->mail }}</li>
<li><i class="icofont-rounded-right"></i> <strong>Freelance:</strong> {{ $e->freelance }}</li>
</ul>
</div>
</div>
<p>
{{ $e->texte }}
</p>
</div>
</div>
@endforeach
</div>
</section>
<file_sep>/database/seeders/SkilSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class SkilSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table("skils")->insert([
"langue" => "Ruby",
"pourcentage" => 76,
"created_at" => now()
]);
DB::table("skils")->insert([
"langue" => "Python",
"pourcentage" => 50,
"created_at" => now()
]);
DB::table("skils")->insert([
"langue" => "C#",
"pourcentage" => 10,
"created_at" => now()
]);
DB::table("skils")->insert([
"langue" => "C++",
"pourcentage" => 100,
"created_at" => now()
]);
}
}
<file_sep>/resources/views/page1.blade.php
@extends('templates.structure')
@section('content')
@include('about.about')
@include('fact.fact')
@include('skil.skil')
@include('portfolio.portfolio')
@include('contact.contact')
@endsection<file_sep>/database/seeders/FactSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class FactSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table("facts")->insert([
"chiffre" => 30,
"titre" => "lorem ipsum",
"texte" => "Je suis le premier chiffre",
"created_at" => now()
]);
DB::table("facts")->insert([
"chiffre" => 50,
"titre" => "lorem ipsum 2",
"texte" => "Je suis le deuxième chiffre",
"created_at" => now()
]);
DB::table("facts")->insert([
"chiffre" => 70,
"titre" => "lorem ipsum3",
"texte" => "Je suis le troisième chiffre",
"created_at" => now()
]);
}
}
<file_sep>/resources/views/skil/table.blade.php
<a href="{{ route("skil.create") }}" class="btn btn-danger">CREATE</a>
<table class="table mt-5">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">LANGUE</th>
<th scope="col">POURCENTAGE</th>
<th scope="col">ACTION</th>
</tr>
</thead>
@foreach ($skil as $e )
<tbody>
<tr>
<td>{{ $e->id }}</td>
<td>{{ $e->langue }}</td>
<td>{{ $e->pourcentage }}</td>
<td class="d-flex">
<a href="/admin/skil/{{ $e->id }}/edit" class="btn btn-success">EDIT</a>
<form action="/admin/skil/{{ $e->id }}" method="POST">
@csrf
@method("delete")
<button class="btn btn-danger" type="submit">DELETE</button>
</form>
</td>
</tr>
</tbody>
@endforeach
</table>
|
70c490fbd4d078fc41f2ccc9d96fc4c3e59fae1b
|
[
"Blade",
"PHP"
] | 9 |
Blade
|
Anis662/projet_portfolio_Anis_ElOuahidi
|
c782379d8d8c7743d9e3366c4b78dbb54654f1fd
|
66fef9185675336f2e939df7b03a865e4878a2b3
|
refs/heads/master
|
<file_sep>name: splash
layout: true
class: center, middle, inverse
---
count:false
# Kubernetes - Sistema Operacional Distribuido

# by [@famsbh](http://twitter.com/famsbh)
---
layout: true
name: sessao
class: left, center, inverse
#.logo-linux[]
---
layout: true
name: conteudo
class: left, top
.logo-linux[]
---
template: sessao
# Agenda
- Dia 1
- Introdução
- Noções Básicas de Kubernetes
- Arquitetura K8S
- Instalação Minikube
- PODS
- Health Checks
- Labels e Selectors
- Deployments
- Services
- Secrets e ConfigMaps
- Statefull Sets
- Dia 2
- Namespaces e RBAC
- Helm
- Volumes and data
- Security
- Networking
- Ingress
- Arquitetura Kubernetes Avancado
- Dia 3
- Instalando K8s kubeadm
- Logging
- Monitoramento
- CI/CD
- Service MESH
---
template: conteudo
# O Que é o Kubernetes
---
# Cloud Native Computing Foundation
---
# Porque K8S
---
# Arquitetura K8S
---
# Plataformas K8S Gerenciadas
---
# Provedors de infraestrutura
---
# Componentes do K8S
---
# Lab Instalação K8S
---
# Minikube
---
# Kubeadm ()
---
# YAML
---
# PODS
## Componentes
## K8S YAML
## Deployment
## Service Mesh
## Security
|
4dbeaf59c4bc9694c977d8ea43281e57eb39dfca
|
[
"Markdown"
] | 1 |
Markdown
|
gilmarlinux/linuxplace-k8s
|
c71ba4f2525343ad61a0bea9027c990a448173d0
|
9565f8776631b56f6ba270b393a7c2f27b366d7a
|
refs/heads/master
|
<repo_name>raeesaa/mocha-testing<file_sep>/README.md
# mocha-testing
Sample Testing
|
c9ae623e9239a36ec39635eba0f300361f15ce99
|
[
"Markdown"
] | 1 |
Markdown
|
raeesaa/mocha-testing
|
3999f97e6d71cdd910ce2b09030ae1533dce8ddc
|
b53550f5b90c9ff100506ac0ec503ba65c47a339
|
refs/heads/master
|
<repo_name>cancledclient/DiscordjsModMail<file_sep>/README.md
# Discord.JS 12.4.1 Modmail
A modmail with rich features.
- [Features](https://github.com/Cyanic76/discord-modmail/wiki/Features)
- [Get the modmail up and running](https://github.com/Cyanic76/discord-modmail/wiki/Installation)
- [Needed npm modules](https://github.com/Cyanic76/discord-modmail/wiki/Dependencies)
## About
**discord-modmail** by Cyanic76, a JS modmail with rich features.
|
a1bb49801bf9273572b558ad1cb0a02999282291
|
[
"Markdown"
] | 1 |
Markdown
|
cancledclient/DiscordjsModMail
|
38481df26ffdb8bafb3b9514755379e6b29ec150
|
9131fe382899070d5be9874b43928895e6e0b474
|
refs/heads/master
|
<file_sep>#!/bin/sh
git submodule update --init
#git submodule sync
cd pkg/Gauss
export $(grep --max-count=1 ^GAP_DIR* $(which gap) | sed s/'"'//g)
./configure $GAP_DIR
make
|
eca151e5893835375a734159e2760efec61a975e
|
[
"Shell"
] | 1 |
Shell
|
markuslh/SuperRepositoryForHomalg
|
d4fa8c06d3cafa797319e44deb1b12d5031e1a76
|
043c82d3703ada67ad74fbc53c406651ff7c9a30
|
refs/heads/master
|
<file_sep>package mayuri;
import java.util.Scanner;
public class Factorial {
static int factorial(int num) {
if(num == 1) {
return 1;
}
else {
return num * factorial(num-1);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int num = sc.nextInt();
System.out.println(factorial(num));
}
}
<file_sep>package methods;
public class SqareRoot {
static void squareRoot(int number) {
String str="";
for(int index=1;index<= number;index++) {
if(index*index == number) {
System.out.println(index);
break;
}
else if(index > number){
System.out.println("Sqare is not possible");
break;
}
}
}
public static void main(String[] args) {
squareRoot(100);
}
}
<file_sep>package arrays;
import java.util.Scanner;
public class DecimalToBinary {
static String str = "";
static void decimalBinary(int number) {
int remainder = 0;
while(number!=0){
remainder = number%2;
number = number/2;
str+= remainder;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
}
public static void main(String[] args) {
System.out.println("Enter the number");
Scanner sc=new Scanner(System.in);
int number = sc.nextInt();
decimalBinary(number);
sc.close();
}
}
<file_sep>package com.ojas;
import java.util.Scanner;
//Accept the month name using 3 characters in switch statement
public class MonthSwitch {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println(" Enter the month name: ");
String s=sc.next();
String res="";
switch(s){
case "jan":
case "Mar":
case "july":
case "Agust":
case "May":
res = s+ " has 31 days";
break;
case "Feb": res = s+ " has 28 days";
break;
case "Aprial":
case "june": res = s+ " has 30 days";
break;
}
System.out.println(res);
}
}
<file_sep>package com.patterns;
import java.util.LinkedList;
public class LLDemo {
public static void main(String[] args) {
LinkedList<String> ll=new LinkedList<String>();
ll.add("Rashi");
ll.add("vani");
ll.add("Rani");
ll.add("seetha");
ll.addFirst("1");
ll.addLast("harika");
System.out.println();
ll.removeFirst();
ll.removeLast();
System.out.println("after removing="+ll);
ll.remove("vani");
String st=ll.get(0);
System.out.println(st);
System.out.println("After change"+ll);
}
}
<file_sep>package com.moc2;
import java.util.Scanner;
public class OddPalindrome {
static boolean checkPalindrom(int number) {
boolean b = false;
int rem = 0, rev = 0, temp = number;
while (number > 0) {
rem = number % 10;
rev = (rev * 10) + rem;
number = number / 10;
}
if (temp == rev) {
b = true;
}
return b;
}
static boolean isOdd(int number) {
boolean b = false;
if (number % 2 != 0) {
b = true;
}
return b;
}
static String rangePalindrom(int start_value, int end_value) {
String res="";
for (int i = start_value; i <= end_value; i++) {
if (checkPalindrom(i) == true && isOdd(i) == true) {
res += i + " ";
}
}
return res;
}
public static void main(String[] args) {
System.out.println("Enter Range");
Scanner sc = new Scanner(System.in);
int start_value = sc.nextInt();
int end_value = sc.nextInt();
System.out.println(rangePalindrom(start_value, end_value));
}
}<file_sep>package arrays;
import java.util.TreeSet;
public class TreeSetDemo extends NameSorting{
public static void main(String[] args) {
TreeSet<String> t=new TreeSet<String>();
t.add("Rashi");
t.add("Yamini");
t.add("bhanu");
t.add("Rashi");
Collections.sort(t.new)
t.forEach(System.out::println);
}
}
class NameSorting implements
<file_sep>package methods;
public class PrimeNumber {
static boolean primeNumberDisplay(int number,int value) {
if(number<=2) {
return number==2?true:false;
}
if(number%value==0) {
return false;
}
if(value*value>number) {
return true;
}
return primeNumberDisplay(number, value+1);
}
public static void main(String[] args) {
System.out.println(primeNumberDisplay(17,2));
}
}
<file_sep>package com.ojas;
public class PalindromeArgs {
public static void main(String[] args){
int num = 0,rev=0;
num=Integer.parseInt(args[0]);
int num1=num%10;
rev=num/100;
System.out.println(num1==rev);
}
}
<file_sep>package assignment;
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
int number = Integer.parseInt(args[0]);
if(number>0 || )
product = 1;
for(int i = number; i<= number; i++) {
result = * i;
}
}
<file_sep>package arrays;
import java.util.Scanner;
public class Operationsarray {
static void menu() {
String m="Menu choice is\n";
m+="1.Insert\n";
m+="2.display\n";
m+="3.delete\n";
}
static int size=5;
static int array[] = new int[size];
static void insert(int number) {
System.out.println("enter the array elements");
for(int index=1;index<array.length-1;index++) {
System.out.println(array[index]);
}
}
static void display() {
for(int index=0;index<array.length-1;index++) {
System.out.println(array[index]);
}
}
static void delete() {
for(int index=0;index<array.length-1;index++) {
array[index]=array[index+1];
System.out.println(array[index]);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true) {
menu();
int choice = sc.nextInt();
switch(choice) {
case 1:
System.out.println("Enter any value");
insert(sc.nextInt(3));
break;
case 2:
display();
break;
case 3:
delete();
break;
default :
System.out.println("invalid number");
}
}
}
}
<file_sep>package mayuri;
public class NumberOfDigits {
static int noOfDigitsInNumber(int num) {
int count = 0;
while(num > 0) {
count++;
num = num/10;
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(noOfDigitsInNumber(153));
}
}
<file_sep>package com.moc2;
class Test {
static int fact(int num) {
int result;
if (num == 1) {
return 1;
}
return result = fact(num - 1) * num;
}
}
public class Factorial {
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.fact(5));
}
}
<file_sep>package exm1;
public class SomeApp {
public static void main(String[] args) {
byte[] bytes = new byte[256];
// insert code here
}
}<file_sep>package com.patterns;
public class snippet{
public static void main(String[] args) {
int x = 1; int y=0; while(++x<5) y++; System.out.println(y);
}
}
<file_sep>package mayuri;
import java.util.Scanner;
public class BiggestOfArrayElements {
static int BiggestOfArrayElements(int num[]) {
int res = 0;
for(int i = 1;i <= num.length;i++) {
int BiggestOfArrayElements = 0;
if(num[i] > BiggestOfArrayElements) {
BiggestOfArrayElements = num[i];
}
}
return res;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int number[] = new int[5];
Scanner sc = new Scanner(System.in);
System.out.println("Enter 5 elements ?");
for(int i = 0;i < number.length;i++) {
number[i] = sc.nextInt();
}
System.out.println("Biggest value = "+BiggestOfArrayElements(number));
}
}
<file_sep>package com.patterns;
import java.util.ArrayList;
import java.util.Arrays;
public class ConvertToArray {
public static void main(String[] args) {
String strArray[]={"Ramu","sita","vani"};
ArrayList<String> al=new ArrayList<String>(Arrays.asList(strArray));
Object b[]=al.toArray();
for(Object x:b){
System.out.println(x);
}
}
}
<file_sep>package com.patterns;
import java.util.Enumeration;
import java.util.Hashtable;
public class HashExamle {
public static void main(String[] args) {
Hashtable<String,String> ht=new Hashtable<String,String>();
ht.put("<NAME>","Amaravathi");
ht.put("Telangana", "Telangana");
ht.put("Goa", "panaji");
ht.put("Mp", "Mp");
ht.put("America", "Washingtone dc");
Enumeration<String> keys=ht.keys();
while(keys.hasMoreElements()){
String k=(String)keys.nextElement();
String v=ht.get(k);
System.out.println(k+ " "+v);
}
}
}
<file_sep>package mayuri;
public class Smallest {
public static void main(String[] args) {
String res="";
for(int row=1;row<=4; row++) {
for(int col=1; col<=4; col++) {
if(col==1||col==3) {
res+="0";
}
else {
res+="1";
}
}
res+="\n";
}
System.out.println(res);
}
}
<file_sep>package com.patterns;
import java.util.LinkedList;
public class CloneLL {
public static void main(String[] args) {
LinkedList<String> ll=new LinkedList<String>();
ll.add("Rashi");
ll.add("vani");
ll.add("Rani");
ll.add("seetha");
ll.addFirst("1");
ll.addLast("harika");
ll.add(1,"z1");
System.out.println("Actual ll"+ll);
LinkedList<String> copy=(LinkedList<String>l.clone();
System.out.println();
}
}
<file_sep>package com.ojas;
public class TypeCon {
public static void main(String[] args) {
short a = 2, b = 3, c;
c= (short) (a+b);
System.out.println(c);
}
}
<file_sep>package com.discuss;
public class B extends A {
public void show(){
System.out.println("hello");
}
public static void main(String[] args) {
A a=new B();
a.show();
}
}
<file_sep>package com.telusko.OneToMany;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class CollegeAddress {
@Id
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private String clgname,Area,town,city;
private int pincode;
@OneToMany(cascade = CascadeType.ALL)
private List<Students> student;
public CollegeAddress(List<Students> student) {
super();
this.student = student;
}
public CollegeAddress(String clgname, String area, String town, String city, int pincode) {
super();
this.clgname = clgname;
this.Area = area;
this.town = town;
this.city = city;
this.pincode = pincode;
}
public String getClgname() {
return clgname;
}
public void setClgname(String clgname) {
this.clgname = clgname;
}
public String getArea() {
return Area;
}
public void setArea(String area) {
Area = area;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getPincode() {
return pincode;
}
public List<Students> getStudent() {
return student;
}
public void setStudent(List<Students> student) {
this.student = student;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
// @Override
// public String toString() {
// return "CollegeAddress [clgname=" + clgname + ", Area=" + Area + ", town=" + town + ", city=" + city
// + ", pincode=" + pincode + "]";
// }
//
}
<file_sep>package com.moc1;
public class PrimeNumber {
public static void main(String[] args) {
int number = 7;
boolean temp = false;
for (int i = 2; i <= number / 2; ++i) {
if (number % i == 0) {
temp = true;
break;
}
}
if (!temp)
System.out.println(number + " is a prime number");
else
System.out.println(number + " is not a prime number ");
}
}
<file_sep>package exm1;
import static utils.Repetition.twice;
public class Repitition {
public static String twice(String s) { return s + s; }
}
<file_sep>package com.patterns;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Employee2 implements Comparable {
int eno;
String ename;
public Employee2() {
System.out.println("default constructure");
}
public Employee2(int eno, String ename) {
super();
this.eno = eno;
this.ename = ename;
}
public int getEno() {
return eno;
}
public void setEno(int eno) {
this.eno = eno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
@Override
public int compareTo(Object arg0) {
// TODO Auto-generated method stub
return 0;
}
}
public class DemoCompare2 {
public static void main(String[] args) {
List<Employee1> empList=new ArrayList<Employee1>();
Employee1 e=new Employee1(1,"Rashi");
Employee1 e1=new Employee1(5,"Vani");
Employee1 e2=new Employee1(3,"Rani");
Employee1 e3=new Employee1(4,"harika");
Employee1 e4=new Employee1(6,"yaminni");
empList.add(e);
empList.add(e1);
empList.add(e2);
empList.add(e3);
empList.add(e4);
System.out.println("before sorting Emp data");
empList.forEach(x->System.out.println(x.getEno()+" "+x.getEname()));
Collections.sort(empList);
System.out.println("After sorting emp data");
empList.forEach(x->System.out.println(x.getEno()+" "+x.getEname()));
}
}<file_sep>package com.ojas;
public class Sumof2num {
public static void main(String[] args) {
int n=0;
do {
System.out.println("Hii");
n++;
if(n==3){
System.out.println("Rasheeda");
}
if(n==8){
System.out.println(" ");
}
}while(n<=10);
}
}
<file_sep>package exm1;
public class BitUtils {
public static void process(byte[] ) { /* more code here */ }
}
<file_sep>package com.patterns;
import java.util.Comparator;
import java.util.TreeSet;
class MyCompare1 implements Comparator<StringBuffer> {
@Override
public int compare(StringBuffer ss1, StringBuffer ss2) {
String s1 = ss1.toString();
String s2 = ss2.toString();
return -s1.compareTo(s2);
}
}
public class CustomStringBuff {
public static void main(String[] args) {
TreeSet<StringBuffer> t = new TreeSet<StringBuffer>(new MyCompare1());
t.add(new StringBuffer("Rashi"));
t.add(new StringBuffer("Anusha"));
t.add(new StringBuffer("Harika"));
t.forEach(x -> System.out.println(x));
}
}
<file_sep>package javapatterns;
public class MyDBpgm {
}
<file_sep>package com.moc2;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String");
String str=sc.next();
String reverse="";
for(int i=str.length()-1;i>=0;i--){
reverse=reverse+str.charAt(i);
}
if(str.equals(reverse)){
System.out.println("String is palindrome");
}
else{
System.out.println("String is not palindrome");
}
}
}
|
fca77a1f8830add9de4d6fb6fe9e57c7db40bf0a
|
[
"Java"
] | 31 |
Java
|
Rasheeda-Vetapalem/MyJavaCode
|
da514c8717eda14872a78d5873ab0b6de465eccb
|
0a520cfdd7bf57c2e4592cff47d4deda1ee0694c
|
refs/heads/master
|
<file_sep>@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<h3>Message</h3>
<form method="Post">
<p>
<button class="btn btn-primary" type="submit">Send Post request</button>
</p>
</form>
<p>
<a href="/" class="btn btn-primary">Send Get request</a>
</p>
@functions{
public string Message { get; set; }
public void OnGet()
{
Message = "nguyen";
}
public void OnPost()
{
Message = "nguyenPost";
}
}
<file_sep>@using duandautien
@namespace duandautien.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
402bacf10bad12d81bdcfcf91d6c680885488c08
|
[
"HTML+Razor"
] | 2 |
HTML+Razor
|
theplas/duandautien
|
70e74df2bc57e40caef791a5d04488181921499d
|
1450288cedb9ed27980f5eaf88ca9afac7f2b1bb
|
refs/heads/main
|
<file_sep># Annotation-NLP-for-MAUDE
Resource sharing for developing annotation model to implement NLP to analyze device adverse event reports
## Publication
Mao et al. Assessing adverse event reports of hysteroscopic sterilization device removal using natural language processing. Pharmacoepidemiol Drug Saf 2021. PMID: 34919294 \
https://doi.org/10.1002/pds.5402
## Introduction
We have shown that investigators can create an annotation model to implement natural language processing to analyze device adverse event report. We share with the community resources for the creation of such an annotation model and the implementation of customized named entity recognition (NER). See the link above for the full publication. The following resources are shared on this site
- Examples of annotated texts (xml format, can use MAE to open)
- Codes for the implementation of NER
## Contact information
For any questions, please contact <NAME> (<EMAIL>).
<file_sep>#!/usr/bin/env python
# coding: utf-8
## Python codes to read in annotation and implement NER
import glob
import xml.etree.ElementTree as ET
import spacy
import random
import en_core_web_sm
from pathlib import Path
## Read in annotated XML files
## function to collect entities into training data
def load_ent(datafile, filename):
# read in xml file
tree = ET.parse('C:/Project data/'+ datafile + '/' + filename)
root = tree.getroot()
# passing on text
text = root[0].text
# labeled content
entities = []
for child in root[1]:
# do not include link
if child.tag not in ('LINKTAG'):
# get the start and end point of the label
start = int(child.attrib['spans'].split('~')[0])
end = int(child.attrib['spans'].split('~')[1])
entities.append((start, end, child.tag))
#append text and labeled entites, return the list
training_doc = []
training_doc.append((text, {"entities" : entities}))
return training_doc
# extract all training data
train_filelist = glob.glob('C:/Project data/Train_annotate/*')
filenames = []
for filename in train_filelist:
filenames.append((filename.split("\\", 1)[1]))
TRAIN_ENT = []
datafile='Train_annotate'
for filename in filenames:
training_doc = load_ent(datafile, filename)
TRAIN_ENT.extend(training_doc)
# extract all testing data
test_filelist = glob.glob('C:/Project data/Test_annotate/*')
filenames = []
for filename in test_filelist:
filenames.append((filename.split("\\", 1)[1]))
TEST_ENT = []
datafile='Test_annotate'
for filename in filenames:
testing_doc = load_ent(datafile, filename)
TEST_ENT.extend(testing_doc)
## Model training
# set seed
random.seed(123)
# use an established English language model
nlp = en_core_web_sm.load()
# remove original ner
if "ner" in nlp.pipe_names:
nlp.remove_pipe("ner")
ner = nlp.create_pipe('ner')
nlp.add_pipe(ner, last=True)
# add labels
for _, annotations in TRAIN_ENT:
for ent in annotations.get('entities'):
ner.add_label(ent[2])
# get names of other pipes to disable them during training
other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
# updating model
ner = nlp.get_pipe("ner")
# add labels
for _, annotations in TRAIN_ENT:
for ent in annotations.get('entities'):
ner.add_label(ent[2])
# get names of other pipes to disable them during training
other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
# only train NER
with nlp.disable_pipes(*other_pipes):
optimizer = nlp.begin_training()
for itn in range(1000):
print("Starting iteration " + str(itn))
random.shuffle(TRAIN_ENT)
losses = {}
for text, annotations in TRAIN_ENT:
nlp.update(
[text], # batch of texts
[annotations], # batch of annotations
drop=0.2, # dropout - make it harder to memorize data
sgd=optimizer, # callable to update weights
losses=losses)
print(losses)
# save model to output directory
output_dir = Path('C:/Project data/nlp_model')
nlp.to_disk(output_dir)
## Assessing NLP performance
### Exact definition
## define function to assess precision and recall
def ner_eval(ner_model, examples, ent_type):
# set to 0 to begin, fp and fn set to 1e-8 to avoid devision by 0
tp = 0
fp = 1e-8
fn = 1e-8
desire_list = ['SOURCE','TIMING','PROCESS','SYMPTOM','PROCEDURE','COMPLICATION']
for text, annotation in examples:
# get all entities from original labeling and predicted labeling
ents_all = annotation['entities']
pred_all = ner_model(text)
ents_pred_all = []
for ent in pred_all.ents:
ents_pred_all.append((ent.start_char, ent.end_char, ent.label_))
if ent_type == 'ALL':
ents_gold = ents_all
ents_pred = ents_pred_all
elif ent_type == 'DESIRE':
# get six desired entities from original labeling and predicted labeling
ents_gold = [ent for ent in ents_all if ent[2] in desire_list]
ents_pred = [ent for ent in ents_pred_all if ent[2] in desire_list]
else:
# get specific entities from original labeling and predicted labeling
ents_gold = [ent for ent in ents_all if ent[2] == ent_type]
ents_pred = [ent for ent in ents_pred_all if ent[2] == ent_type]
# calculate tru positive, false positive, and false negative
tp += len(set(ents_gold) & set(ents_pred))
fp += len(set(ents_pred) - set(ents_gold))
fn += len(set(ents_gold) - set(ents_pred))
# calculate precision, recall, and fscore
precision = tp / (tp + fp)
recall = tp / (tp + fn)
fscore = 2 * (precision * recall) / (precision + recall + 1e-8)
return({'precision': precision, 'recall': recall, 'fscore': fscore})
# precision and recall on testing data
for ent_type in ['ALL', 'DESIRE', 'SOURCE', 'TIMING', 'PROCESS', 'SYMPTOM', 'PROCEDURE', 'COMPLICATION', 'DEVICE', 'LOCATION', 'CERTAINTY']:
test_eva = ner_eval(nlp, TEST_ENT, ent_type)
print(ent_type, "labels: ", test_eva)
### Lenient defintion: allow overlap
## define function to assess precision and recall
def ner_eval_lenient(ner_model, examples, ent_type):
# set to 0 to begin, fp and fn set to 1e-8 to avoid devision by 0
tp = 0
fp = 1e-8
fn = 1e-8
desire_list = ['SOURCE','TIMING','PROCESS','SYMPTOM','PROCEDURE','COMPLICATION']
for text, annotation in examples:
# get all entities from original labeling and predicted labeling
ents_all = annotation['entities']
pred_all = ner_model(text)
ents_pred_all = []
for ent in pred_all.ents:
ents_pred_all.append((ent.start_char, ent.end_char, ent.label_))
if ent_type == 'ALL':
ents_gold = ents_all
ents_pred = ents_pred_all
elif ent_type == 'DESIRE':
# get six desired entities from original labeling and predicted labeling
ents_gold = [ent for ent in ents_all if ent[2] in desire_list]
ents_pred = [ent for ent in ents_pred_all if ent[2] in desire_list]
else:
# get specific entities from original labeling and predicted labeling
ents_gold = [ent for ent in ents_all if ent[2] == ent_type]
ents_pred = [ent for ent in ents_pred_all if ent[2] == ent_type]
# find overlapped ones
ents_match_gold = []
ents_match_pred = []
for gold in ents_gold:
for pred in ents_pred:
if max(gold[1], pred[1]) - min(gold[0], pred[0]) < (gold[1] - gold[0]) + (pred[1] - pred[0]):
ents_match_gold.append(gold)
ents_match_pred.append(pred)
# calculate tru positive, false positive, and false negative
tp += len(ents_match_gold)
fp += len(set(ents_pred) - set(ents_match_pred))
fn += len(set(ents_gold) - set(ents_match_gold))
# calculate precision, recall, and fscore
precision = tp / (tp + fp)
recall = tp / (tp + fn)
fscore = 2 * (precision * recall) / (precision + recall + 1e-8)
return({'precision': precision, 'recall': recall, 'fscore': fscore})
# precision and recall on testing data
for ent_type in ['ALL', 'DESIRE', 'SOURCE', 'TIMING', 'PROCESS', 'SYMPTOM', 'PROCEDURE', 'COMPLICATION', 'DEVICE', 'LOCATION', 'CERTAINTY']:
test_eva = ner_eval_lenient(nlp, TEST_ENT, ent_type)
print(ent_type, "labels: ", test_eva)
|
fc45c0d1369c8465a3297f230d6b9c26e255228a
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
jialinmaomao/Annotation-NLP-for-MAUDE
|
635393f396b28839d877a93ef8a64e1e28ed3480
|
0dad33e8a4fa06a22387decf26b76a6ab5e5b7fb
|
refs/heads/master
|
<repo_name>saif429/SystemsProject<file_sep>/README.md
Tokenizer For Systems Programming by <NAME>
This is a tokenizer written in C that can discern between words, hexadecimal, octal, floating point, and various things like brackets and other symbols. This is the first Systems Programming assignment in the class. This project uses a linked list implementation which allows easy storage of tokens and allows allows them to be modified later on without issue.
Steps to get it to run
1) Compile the source file and give the executable a name
2) Run the program from the command line with a command such as ./tokenizer "0x4356abdc 0777 [] "
or
tokenizer.exe "0x4356abdc 0777 [] "
Please be sure to wrap the argument in using quotes "" otherwise the program will fail to run correctly. Certain characters such as \ (backslash) will cause the program to fail. Backslashs are an escape character in C and in certain shell environments, please avoid using it in your inputs.
Emojis, and characters that do not appear on a normal keyboard are not supported.
Check the test cases for expected outputs. Most keyboard characters are supported. If our program prints "Malformed Token", you most likely entered a number with a bad format.
<file_sep>/Assignment1.c
/*Tokenizer project using Linked List Structure to hold data*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/*
Token Structure is based off a linked list
This was done so that we could store the tokens easily and then
be able to easily find a token or remove a token if needed
*/
struct Token
{
char *data;
char *tokenType;
struct Token *next;
}
*head;
typedef struct Token Token;
Token *CreateToken(char * ts, char * type)
{
/*if the token linked list is empty*/
if (head==NULL)
{
Token *newToken=(struct Token*)malloc(sizeof(Token));
newToken->data=ts;
newToken->tokenType=type;
newToken->next=NULL;
head=newToken;
return head;
}
/* If the token list has at least 1 or more things in it */
else
{
/*Iterator*/
Token *iter=head;
while (iter->next!=NULL)
{
iter=iter->next;
}
Token *newToken=(struct Token*)malloc(sizeof(Token));
newToken->data=ts;
newToken->tokenType=type;
iter->next=newToken;
newToken->next=NULL;
return newToken;
}
}
/*Destroys the linked list entirely, probably not the right way to do this */
void DestroyToken( Token * tk )
{
Token *iterator=head;
/*In case the linked list is empty*/
if (iterator==NULL)
{
return;
}
/*in case there is only one thing in the linked list*/
else if (iterator->next==NULL)
{
free(tk);
iterator->next=NULL;
}
/*for all other cases*/
else
{
while (iterator->next!=NULL)
{
if (strcmp(iterator->next->data,tk->data)==0)
{
iterator->next=tk->next;
free(tk);
}
iterator=iterator->next;
}
}
}
/*Prints the contens of the token linked list */
void printAllTokens()
{
Token *i=head;
while (i!=NULL)
{
printf("%s",i->tokenType);
printf(" %s\n",i->data);
i=i->next;
}
}
char *GetNextToken( Token * tk )
{
return NULL;
}
/* Creates a new token in the linked list, given a substring location, an input and the token type */
void createNewString (char* input, char* type, int y, int z)
{
/* Gets the start of the token */
int TokenStart = z;
/*Gets the length of the token */
int TokenLength = y-z;
/*Creates a string for just the token */
/*Fixes a null termination bug */
char *NewToken=malloc((TokenLength+1)*sizeof(char*));
/*removing +1 fixes a null termiantion thing*/
NewToken[TokenLength]='\0';
/* Temporary variable simply used to add the token to the NewToken string */
int b = 0;
/*Loops through the input string, and adds the token to the NewToken string*/
for (TokenStart=z; TokenStart<y; TokenStart++)
{
NewToken[b] = input[TokenStart];
b++;
}
if (strcmp(type,"Malformed Token")==0)
{
CreateToken(" ",type);
return;
}
CreateToken(NewToken,type);
}
/* Populates the token list during the initial run */
void populateTokenList(char* input)
{
/* indicates how many times to iterate */
int i = strlen(input);
/*Z keeps track of the beggining index*/
int z = 0;
/* Y keeps track of the ending */
int y = 0;
while (z < i)
{
/*This if statement handles tokens that start with 0 */
/*Hexadecimal eg. 0x */
/*Octal eg. 0532 */
if (input[z]=='0')
{
/*for finding hexadecimal characters*/
if(input[z+1]=='x' || input[z+1] == 'X')
{
/* Y is the stuff after the hexadecimal identifier */
y = z+2;
while (isalnum(input[y]) && input[y]<'g')
{
y++;
if (input[y] == '\0')
{
y++;
break;
}
}
createNewString(input,"Hexadecimal",y,z);
z=y;
continue;
}
/*checks octal */
else if (isdigit(input[z+1]) && (input[z+1]-'0')<=7)
{
int r = 0;
y=z+1;
while (isdigit(input[y]) && input[y]-'0'<=7)
{
/*keeps count of how many indexes have been iterated through*/
y++;
if (input[y] == '.')
{
r++;
}
/* if the end of string is hit, add 1 to y in order to account for the null character index */
else if (input[y] == '\0')
{
y++;
break;
}
}
if (r == 0)
{
createNewString(input,"Octal",y,z);
z=y;
}
else if (r!=0)
{
y = y+1;
while (isdigit(input[y]) || input[y]=='e' || input[y]=='E' || (input[y]=='-' && isdigit(input[y])))
{
/*keeps count of how many indexes have been iterated through*/
y++;
/* if the end of string is hit, add 1 to y in order to account for the null character index */
if (input[y] == '\0')
{
y++;
break;
}
if (input[y] == '0' && (input[y+1] == 'X' || input[y+1] == 'x'))
{
break;
}
}
createNewString(input,"Floating Point",y,z);
z=y;
continue;
}
}
/* added E for floating point stuff" */
else if (isdigit(input[z]) && (input[z+1]=='.' || (input[z+1]=='E' && input[z+2]!='E') || (input[z+1]=='e' && input[z+2]!='e')))
{
y=z+2;
while (isdigit(input[y]) || (input[y]=='E' && input[y+1]!='E') || (input[y]=='e' && input[y+1]!='e') || (input[y]=='-' && isdigit(input[y+1])))
{
/*keeps count of how many indexes have been iterated through*/
y++;
/* if the end of string is hit, add 1 to y in order to account for the null character index */
if (input[y] == '\0')
{
y++;
break;
}
if (input[y] == '0'&& (input[y+1] == 'X' || input[y+1] == 'x'))
{
break;
}
}
createNewString(input,"Floating Point",y,z);
z=y;
continue;
}
else
{
createNewString(input,"Malformed Token",0,0);
z=y;
z+=2;
}
}
/*for words */
else if (isalpha(input[z]))
{
y = z+1;
while (isalpha(input[y]))
{
y++;
if (input[y] == '\0')
{
y++;
break;
}
}
createNewString(input,"word",y,z);
z=y;
continue;
}
/*Does regular digits*/
else if (isdigit(input[z]) && input[z+1]!='.')
{
y = z+1;
int h = 0;
while (isdigit(input[y])) // in this statement we need to have something for floating point
{
if (input[y]=='0' && (input[y+1]=='x' || input[y+1] == 'X'))
{
break;
}
y++;
/*For floating point and floating point with E*/
if (input[y] == '.' || input[y] == 'E' || input[y] == 'e' )
{
h++;
}
else if (input[y] == '\0')
{ // if it hits the end of the string, this adds on the null character index.
y++;
break;
}
}
if (h == 0)
{
createNewString(input,"Decimal",y,z);
z=y;
}
else if (h!=0)
{
y = y+1;
while (isdigit(input[y]) || input[y]=='e' || input[y]=='E' || (input[y]=='-' && isdigit(input[y+1])))
{
/*keeps count of how many indexes have been iterated through*/
y++;
/* if the end of string is hit, add 1 to y in order to account for the null character index */
if (input[y] == '\0')
{
y++;
break;
}
if (input[y] == '0' && (input[y+1] == 'X' || input[y+1] == 'x'))
{
break;
}
}
createNewString(input,"Floating Point",y,z);
z=y;
continue;
}
}
/*added e for floating point*/
else if (isdigit(input[z]) && (input[z+1]=='.' || input[z+1]=='E' || input[z+1]=='e'))
{
y=z+2;
while (isdigit(input[y]) || input[y]=='e' || input[y]=='E' || (input[y]=='-' && isdigit(input[y+1])))
{
/*keeps count of how many indexes have been iterated through*/
y++;
/* if the end of string is hit, add 1 to y in order to account for the null character index */
if (input[y] == '\0')
{
y++;
break;
}
else if (input[y] == '0' && (input[y+1] == 'X' || input[y+1] == 'x'))
{
break;
}
}
createNewString(input,"Floating Point",y,z);
z=y;
continue;
}
/* Switch Statement for other characters */
if (input[z]=='<' && input[z+1]=='<' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Left Shift and Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='>' && input[z+1]=='>' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Right Shift and Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='+' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Plus Equals",y,z);
z=y;
continue;
}
else if (input[z]=='&' && input[z+1]=='&')
{
y=z+2;
createNewString(input,"Logical And",y,z);
z=y;
continue;
}
else if (input[z]=='-' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Minus Equals",y,z);
z=y;
continue;
}
else if (input[z]=='=' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Comparison",y,z);
z=y;
continue;
}
else if (input[z]=='*' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Multiplication Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='/' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Division Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='%' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Remainder Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='&' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Bitwise And Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='^' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Bitwise Exclusive Or Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='|' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Bitwise Inclusive Or Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='|' && input[z+1]=='|')
{
y=z+2;
createNewString(input,"Logical Or",y,z);
z=y;
continue;
}
else if (input[z]=='<' && input[z+1]=='<')
{
y=z+2;
createNewString(input,"Left Shift",y,z);
z=y;
continue;
}
else if (input[z]=='>' && input[z+1]=='>')
{
y=z+2;
createNewString(input,"Right Shift",y,z);
z=y;
continue;
}
else if (input[z]=='-' && input[z+1]=='-')
{
y=z+2;
createNewString(input,"Decrement",y,z);
z=y;
continue;
}
else if (input[z]=='+' && input[z+1]=='+')
{
y=z+2;
createNewString(input,"Increment",y,z);
z=y;
continue;
}
else if (input[z]=='?' && input[z+1]=='-')
{
y=z+2;
createNewString(input,"Conditional Expression",y,z);
z=y;
continue;
}
else if (input[z]=='-' && input[z+1]=='>')
{
y=z+2;
createNewString(input,"Structure Pointer",y,z);
z=y;
continue;
}
switch (input[z])
{
case '+' :
y=z+1;
createNewString(input,"Addition",y,z);
z=y;
break;
case '-' :
y=z+1;
createNewString(input,"Subtraction",y,z);
z=y;
break;
case '*' :
y=z+1;
createNewString(input,"Multiplication",y,z);
z=y;
break;
case '%' :
y=z+1;
createNewString(input,"Modulus",y,z);
z=y;
break;
case '=' :
y=z+1;
createNewString(input,"Assignment",y,z);
z=y;
break;
case '>' :
y=z+1;
createNewString(input,"Greater Than",y,z);
z=y;
break;
case '<' :
y=z+1;
createNewString(input,"Less Than",y,z);
z=y;
break;
case '|' :
y=z+1;
createNewString(input,"Bitwise Inclusive Or / Line",y,z);
z=y;
break;
case '&' :
y=z+1;
createNewString(input,"Bitwise And / Ampersand",y,z);
z=y;
break;
case '^' :
y=z+1;
createNewString(input,"Exclusive Or / Carret",y,z);
z=y;
break;
case '?' :
y=z+1;
createNewString(input,"Question Mark",y,z);
z=y;
break;
case ':' :
y=z+1;
createNewString(input,"Conditional Expression / Colon",y,z);
z=y;
break;
case ',' :
y=z+1;
createNewString(input,"Comma",y,z);
z=y;
break;
case ';' :
y=z+1;
createNewString(input,"End of Expression / Semi Colon",y,z);
z=y;
break;
case '/' :
y=z+1;
createNewString(input,"Slash",y,z);
z=y;
break;
case '\\' :
y=z+1;
createNewString(input,"Backslash",y,z);
z=y;
break;
case '[' :
y=z+1;
createNewString(input,"Left Brace",y,z);
z=y;
break;
case ']' :
y=z+1;
createNewString(input,"Right Brace",y,z);
z=y;
break;
case '{' :
y=z+1;
createNewString(input,"Left Bracket",y,z);
z=y;
break;
case '}' :
y=z+1;
createNewString(input,"Right Bracket",y,z);
z=y;
break;
case '_' :
y=z+1;
createNewString(input,"Underscore",y,z);
z=y;
break;
case '#' :
y=z+1;
createNewString(input,"Hash",y,z);
z=y;
break;
case '!' :
y=z+1;
createNewString(input,"Not / Exclamation",y,z);
z=y;
break;
case '`' :
y=z+1;
createNewString(input,"Tilde",y,z);
z=y;
break;
case '(' :
y=z+1;
createNewString(input,"Left Parenthesis",y,z);
z=y;
break;
case ')' :
y=z+1;
createNewString(input,"Right Parenthesis",y,z);
z=y;
break;
default :
z++;
break;
}
}
}
/* The main function */
int main(int argc, char **argv)
{
if (argv[1]==NULL || strlen(argv[1])==0)
{
printf("%s\n", "No Argument");
return 0;
}
populateTokenList(argv[1]);
printAllTokens();
return 0;
}
|
9524d43dc89fb0b7c60fb353a67da95deaba15a0
|
[
"Markdown",
"C"
] | 2 |
Markdown
|
saif429/SystemsProject
|
d407a2fe516ea944126df2d4be12f0d029aae0b5
|
78f7ffc67ea5b9d49839e587f33a851fc8cafa13
|
refs/heads/master
|
<file_sep>//
// PhotoViewAppDelegate.h
// PhotoView
//
// Created by <NAME> on 3/4/10.
// Copyright Beepscore LLC 2010. All rights reserved.
//
#import <UIKit/UIKit.h>
@class PhotoViewViewController;
@interface PhotoViewAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
PhotoViewViewController *viewController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet PhotoViewViewController *viewController;
@end
<file_sep>//
// PhotoViewViewController.h
// PhotoView
//
// Created by <NAME> on 3/4/10.
// Copyright Beepscore LLC 2010. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface PhotoViewViewController : UIViewController
<UIImagePickerControllerDelegate> {
UIImageView *imageView;
UIImagePickerController *imagePicker;
}
@property(nonatomic,retain)IBOutlet UIImageView *imageView;
@property(nonatomic,retain)IBOutlet UIImagePickerController *imagePicker;
@end
<file_sep>//
// PhotoViewViewController.m
// PhotoView
//
// Created by <NAME> on 3/4/10.
// Copyright Beepscore LLC 2010. All rights reserved.
//
#import "PhotoViewViewController.h"
@implementation PhotoViewViewController
#pragma mark properties
@synthesize imageView;
@synthesize imagePicker;
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
#pragma mark memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)setView:(UIView *)newView {
if (nil == newView) {
self.imageView = nil;
self.imagePicker = nil;
}
[super setView:newView];
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[imageView release], imageView = nil;
[imagePicker release], imagePicker = nil;
[super dealloc];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if ([[touches anyObject] tapCount] > 1) {
// bring up image grabber
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
} else {
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
self.imagePicker.allowsEditing = YES;
[self presentModalViewController:self.imagePicker animated:YES];
}
}
# pragma mark UIImagePickerController delegate methods
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self.imagePicker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
imageView.image = [info objectForKey:UIImagePickerControllerEditedImage];
[self dismissModalViewControllerAnimated:YES];
}
@end
|
ba64d7cb45d54a842dc5c059844f220e2df85676
|
[
"Objective-C"
] | 3 |
Objective-C
|
beepscore/PhotoView
|
bb785bd3e2832bfc80f627fc1def2d763cadc12a
|
d3bc912c4888d23da4d5b05ba4de9cbd70394d3c
|
refs/heads/master
|
<file_sep># Description:
# Just WTF. Fork of https://github.com/jakswa/hubot-reaction
#
# Dependencies:
# "request"
# "cheerio"
#
# Configuration:
# None
#
# Author:
# jakswa
request = require('request')
cheerio = require('cheerio')
format = require('util').format
module.exports = (robot) ->
robot.hear /wtf/i, (msg) ->
getGifs "what-the-fuck", (gifs) ->
if gifs.length > 0
ind = Math.floor(Math.random() * gifs.length)
msg.send gifs.eq(ind).attr('src').replace('thumbnail', 'i')
# simple, in-memory, hour-long cache of requests
# (don't run this for years or anything, not cleaning up unused ones :)
gifSets = {}
getGifs = (tag, callback) ->
gifSet = gifSets[tag]
if gifSet && ((new Date()) - gifSet.date) > 3600000 # 1 hour
gifSet = gifSets[tag] = null # clear old cache item if expired
if gifSet
callback(gifSet.gifs)
return
request format('http://replygif.net/t/%s', tag), (err, resp, body) ->
if err
callback []
return
gifs = cheerio.load(body)('img.gif')
gifSets[tag] = {date: new Date(), gifs: gifs}
callback(gifs)
|
8552f7f4f93bf7b9b658b529f05b529351933d47
|
[
"CoffeeScript"
] | 1 |
CoffeeScript
|
piotrdubiel/hubot-wtf
|
538ad23e88fd3fc31c8f8b3fa797d3b46fdd0119
|
22470e8a76d56f4c7c0e6064f3c67ebda869c7f6
|
refs/heads/main
|
<file_sep>import { ICON } from './icons.js';
function factoryFormElement({ title, fields, button }, { fieldsValues }) {
let newForm = document.createElement('form');
newForm.classList.add('modal-form');
let formHeader = document.createElement('div');
formHeader.classList.add('form-header');
let formClose = document.createElement('div');
formClose.classList.add('form-close', 'btn', 'btn-secondary');
formClose.innerHTML = ICON.cross;
let formTitle = document.createElement('h2');
formTitle.classList.add('form-title');
formTitle.innerText = title;
formHeader.append(formClose);
formHeader.append(formTitle);
newForm.append(formHeader);
let relativeIndx = 0;
for (let field of fields) {
let newField = document.createElement('div');
newField.classList.add('form-field');
let fieldName = document.createElement('label');
fieldName.innerText = field.name;
let fieldInput;
if (field.type !== 'textarea') {
fieldInput = document.createElement('input');
fieldInput.setAttribute('type', field.type);
} else {
fieldInput = document.createElement('textarea');
}
fieldInput.setAttribute('name', field.name);
fieldInput.setAttribute('id', field.id);
if (field.required) fieldInput.setAttribute('required', '');
if (field.type === 'number' || field.type === 'date') {
fieldInput.setAttribute('min', field.minrange);
fieldInput.setAttribute('max', field.maxrange);
}
newField.append(fieldName);
newField.append(fieldInput);
newForm.append(newField);
//Ad values if they exist
if (fieldsValues) fieldInput.value = fieldsValues[relativeIndx];
relativeIndx++;
}
let formSubmit = document.createElement('button');
formSubmit.classList.add('form-submit', 'btn', 'btn-primary', 'btn-long');
formSubmit.innerText = button;
newForm.append(formSubmit);
return newForm;
}
function launchForm(formObj, submitHandler, formValuesObj = {}) {
let formElement = new factoryFormElement(formObj, formValuesObj);
let bg = document.createElement('div');
bg.classList.add('modal-bg');
bg.append(formElement);
let content = document.querySelector('#content');
content.append(bg);
let closeBtn = formElement.querySelector('.form-close');
closeBtn.addEventListener(
'click',
(e) => {
formElement.reset();
content.removeChild(bg);
},
{ once: true }
);
formElement.addEventListener(
'submit',
(e) => {
e.preventDefault();
submitHandler(formElement);
closeBtn.click();
},
{ once: true }
);
}
export { factoryFormElement, launchForm };
<file_sep>import { ICON } from './icons.js';
import {
factoryTask as Task,
factoryProject as Project,
USER_MODULE as USER,
} from './data-logic.js';
import { factoryFormElement as Form, launchForm } from './form-components.js';
import { format, compareAsc, parse, differenceInMinutes } from 'date-fns';
const FORMS = {
addProjectForm: {
title: 'New Project',
fields: [
{
id: 'name',
name: 'Project name',
type: 'text',
required: true,
},
],
button: 'Create project',
},
editProjectForm: {
title: 'Edit Project',
fields: [
{
id: 'name',
name: 'Project name',
type: 'text',
required: true,
},
],
button: 'Update project',
},
deleteProjectForm: {
title: 'Are you sure you want to delete this project?',
fields: [],
button: 'Remove project',
},
addTaskForm: {
title: 'Add new Task',
fields: [
{
id: 'desc',
name: 'Description',
type: 'textarea',
required: true,
},
{
id: 'date',
name: 'Due date',
type: 'date',
required: true,
minrange: format(new Date(), 'yyyy-MM-dd'),
maxrange: '2100-12-31',
},
{
id: 'priority',
name: 'Priority (0 low - 3 max)',
type: 'number',
required: true,
minrange: 0,
maxrange: 3,
},
],
button: 'Submit',
},
editTaskForm: {
title: 'Edit Task',
fields: [
{
id: 'desc',
name: 'Description',
type: 'textarea',
required: true,
},
{
id: 'date',
name: 'Due date',
type: 'date',
required: true,
minrange: format(new Date(), 'yyyy-MM-dd'),
maxrange: '2100-12-31',
},
{
id: 'priority',
name: 'Priority (0 low - 3 max)',
type: 'number',
required: true,
minrange: 0,
maxrange: 3,
},
],
button: 'Update',
},
deleteTaskForm: {
title: 'Delete this task?',
fields: [],
button: 'Remove',
},
};
const DOM_DISPLAY = (() => {
const _projectWrapper = document.querySelector('#project-wrapper');
const _tasksWrapper = document.querySelector('#list-wrapper');
let currentProject = undefined;
const _mobileProjectTitle = document.querySelector('#project-mini-title');
let currentFilter = 0; // 0 - Pending tasks | 1 - Close due dates | 2 - Top Priority | 3 - Done
// For mobiles
_mobileProjectTitle.innerText = getCurrentProject().getName();
const setFilter = (filter) => {
currentFilter = filter;
};
function getCurrentProject() {
return currentProject || new Project(' No project ');
}
const displayProjects = () => {
//Wipe anything before the function call
_projectWrapper.innerHTML = '';
let projects = USER.getProjects();
if (projects.length === 0) {
_projectWrapper.innerText = 'You have no projects.';
}
projects.forEach((project) => {
let projectItem = factoryProjectElement(project.getObjLiteral());
let projectIndex = projects.indexOf(project);
let currentProjectIndex = USER.getProjects().indexOf(getCurrentProject());
//If this is the current project-item, select it
if (projectIndex === currentProjectIndex) {
projectItem.classList.add('project-item-selected');
}
_projectWrapper.appendChild(projectItem);
});
};
const selectProject = (index) => {
updateDisplay();
let project = Array.from(_projectWrapper.childNodes)[index];
//If project doesn't exist. don't even bother (should return error thoe)
if (!project) {
currentProject = undefined;
} else {
currentProject = USER.getProjects()[index];
}
//Update mobile title
_mobileProjectTitle.innerText = getCurrentProject().getName();
updateDisplay();
};
const updateDisplay = () => {
displayProjects();
displayTasks(getCurrentProject().getTasks());
};
const displayTasks = (tasks) => {
//Wipe anything before the function call
_tasksWrapper.innerHTML = '';
let filteredTasks = tasks;
//Apply filter
switch (currentFilter) {
default:
case 0:
filteredTasks = tasks.filter((task) => !task.isDone());
break;
case 1:
filteredTasks = [...tasks]
.sort((a, b) => {
//Get their diferences from today to the due date
let aDiff = differenceInMinutes(
parse(a.getObjLiteral().duedate, 'yyyy-MM-dd', new Date()),
new Date()
);
let bDiff = differenceInMinutes(
parse(b.getObjLiteral().duedate, 'yyyy-MM-dd', new Date()),
new Date()
);
return aDiff > bDiff ? 1 : -1;
})
.filter((task) => !task.isDone());
break;
case 2:
filteredTasks = [...tasks]
.sort((a, b) =>
a.getObjLiteral().priority < b.getObjLiteral().priority ? 1 : -1
)
.filter((task) => !task.isDone());
break;
case 3:
filteredTasks = tasks.filter((task) => task.isDone());
break;
}
if (filteredTasks.length === 0) {
_tasksWrapper.innerText = 'No tasks to show.';
}
filteredTasks.forEach((task) => {
let taskItem = factoryTaskElement(task.getObjLiteral());
_tasksWrapper.appendChild(taskItem);
});
};
function factoryProjectElement({ id, name, tasks }) {
let projectElement = document.createElement('div');
projectElement.classList.add('project-item');
projectElement.setAttribute('data-id', id);
let content = document.createElement('div');
content.classList.add('project-item-content');
// HEADER
let header = document.createElement('div');
header.classList.add('project-item-header');
let icon = document.createElement('div');
icon.classList.add('project-item-icon');
icon.innerHTML = ICON.folder;
let title = document.createElement('p');
title.classList.add('project-item-title');
title.innerText = name;
header.append(icon);
header.append(title);
// BODY
let desc = document.createElement('small');
desc.classList.add('project-item-desc');
desc.innerText =
tasks.length > 1
? `(${tasks.length}) tasks on project.`
: tasks.length > 0
? '(1) task on project.'
: 'No tasks on project.';
content.append(header);
content.append(desc);
let controls = document.createElement('div');
controls.classList.add('project-item-controls');
let editBtn = document.createElement('button');
editBtn.classList.add('btn-edit', 'btn', 'btn-light', 'btn-circle');
editBtn.innerHTML = ICON.pencil;
let deleteBtn = document.createElement('button');
deleteBtn.classList.add('btn-delete', 'btn', 'btn-light', 'btn-circle');
deleteBtn.innerHTML = ICON.trashcan;
controls.append(editBtn);
controls.append(deleteBtn);
projectElement.append(content);
projectElement.append(controls);
// ADD EVENT LISTENERS TO BUTTONS
content.addEventListener('click', (e) => {
displaySelectedProject(projectElement);
});
editBtn.addEventListener('click', (e) => {
editProject(projectElement, name);
});
deleteBtn.addEventListener('click', (e) => {
deleteProject(projectElement);
});
return projectElement;
}
const displaySelectedProject = (projectElement) => {
let projectArr = [..._projectWrapper.children];
let projectIndex = projectArr.indexOf(projectElement);
selectProject(projectIndex);
};
const editProject = (projectElement, ...fields) => {
launchForm(
FORMS.editProjectForm,
(formElement) => {
let projectID = projectElement.getAttribute('data-id');
let projectIndex = USER.getProjectIndexFromProjectID(projectID);
let project = USER.getProjects()[projectIndex];
project.editProject(formElement.querySelector('#name').value);
//Update display
USER.updateData();
DOM_DISPLAY.selectProject(projectIndex);
},
{ fieldsValues: [...fields] }
);
};
const deleteProject = (projectElement) => {
launchForm(FORMS.deleteProjectForm, (formElement) => {
let projectID = projectElement.getAttribute('data-id');
let projectIndex = USER.getProjectIndexFromProjectID(projectID);
USER.removeProjectAtIndex(projectIndex);
//Update display
USER.updateData();
DOM_DISPLAY.selectProject(-1);
});
};
function factoryTaskElement({ id, desc, priority, duedate, done }) {
let taskElement = document.createElement('div');
taskElement.classList.add('list-item');
taskElement.setAttribute('data-id', id);
taskElement.setAttribute('data-done', done);
if (done) {
taskElement.classList.add('list-item-done');
}
// HEADER
let headerElement = document.createElement('div');
headerElement.classList.add('list-item-header');
let infoElement = document.createElement('div');
infoElement.classList.add('list-item-info');
let duedateElement = document.createElement('p');
duedateElement.classList.add('list-item-duedate', 'text-secondary');
duedateElement.innerText = `Due date: ${duedate}`;
let priorityElement = document.createElement('p');
priorityElement.classList.add('list-item-priority', 'text-primary');
priorityElement.innerText =
priority == 3
? 'Urgent'
: priority == 2
? 'Important'
: priority == 1
? 'Should Do'
: 'Optional';
infoElement.append(duedateElement);
infoElement.append(priorityElement);
let controlsElement = document.createElement('div');
controlsElement.classList.add('list-item-controls');
let doneBtn = document.createElement('button');
doneBtn.classList.add('btn-done', 'btn', 'btn-primary', 'btn-circle');
doneBtn.innerHTML = ICON.ribbonCheckmark;
let editBtn = document.createElement('button');
editBtn.classList.add('btn-edit', 'btn', 'btn-secondary', 'btn-circle');
editBtn.innerHTML = ICON.pencil;
let deleteBtn = document.createElement('button');
deleteBtn.classList.add('btn-delete', 'btn', 'btn-secondary', 'btn-circle');
deleteBtn.innerHTML = ICON.trashcan;
controlsElement.append(doneBtn);
controlsElement.append(editBtn);
controlsElement.append(deleteBtn);
headerElement.append(infoElement);
headerElement.append(controlsElement);
// BODY
let bodyElement = document.createElement('div');
bodyElement.classList.add('list-item-body');
let descElement = document.createElement('p');
descElement.classList.add('list-item-desc');
descElement.innerText = desc;
bodyElement.append(descElement);
taskElement.append(headerElement);
taskElement.append(bodyElement);
// ADD EVENT LISTENERS TO BUTTONS
doneBtn.addEventListener(
'click',
(e) => {
markAsDone(taskElement);
},
{ once: true }
);
editBtn.addEventListener('click', (e) => {
//Beware, order of these properties matter, bugs may arise if you move something!
editTask(taskElement, desc, duedate, priority);
});
deleteBtn.addEventListener('click', (e) => {
deleteTask(taskElement);
});
return taskElement;
}
const markAsDone = (taskElement) => {
let taskID = taskElement.getAttribute('data-id');
let project = DOM_DISPLAY.getCurrentProject();
let taskIndex = project.getTaskIndexFromTaskID(taskID);
let currentTask = project.getTasks()[taskIndex];
if (!currentTask.isDone()) currentTask.setDone(true);
else currentTask.setDone(false);
//Update display
USER.updateData();
DOM_DISPLAY.updateDisplay();
};
const editTask = (taskElement, ...fields) => {
launchForm(
FORMS.editTaskForm,
(formElement) => {
let taskID = taskElement.getAttribute('data-id');
let project = DOM_DISPLAY.getCurrentProject();
let taskIndex = project.getTaskIndexFromTaskID(taskID);
let currentTask = project.getTasks()[taskIndex];
currentTask.editTask(
formElement.querySelector('#desc').value,
formElement.querySelector('#priority').value,
formElement.querySelector('#date').value
);
//Update display
USER.updateData();
DOM_DISPLAY.updateDisplay();
},
{ fieldsValues: [...fields] }
);
};
const deleteTask = (taskElement) => {
launchForm(FORMS.deleteTaskForm, (formElement) => {
let taskID = taskElement.getAttribute('data-id');
let project = DOM_DISPLAY.getCurrentProject();
let taskIndex = project.getTaskIndexFromTaskID(taskID);
project.removeTaskAtIndex(taskIndex);
//Update display
USER.updateData();
DOM_DISPLAY.updateDisplay();
});
};
return {
getCurrentProject,
displayProjects,
selectProject,
updateDisplay,
setFilter,
};
})();
// ADD PROJECT BTN
(() => {
let addProjectBtn = document.querySelector('#project-add-btn');
addProjectBtn.addEventListener('click', (e) => {
launchForm(FORMS.addProjectForm, (formElement) => {
let newProject = new Project(formElement.querySelector('#name').value);
USER.addProject(newProject);
//Get index of new project
let projectIndex = USER.getProjects().indexOf(newProject);
//Update display
USER.updateData();
DOM_DISPLAY.selectProject(projectIndex);
});
});
})();
// ADD TASK BTN
(() => {
let addTaskBtn = document.querySelector('#list-add-btn');
addTaskBtn.addEventListener('click', (e) => {
launchForm(FORMS.addTaskForm, (formElement) => {
let newTask = new Task(
formElement.querySelector('#desc').value,
formElement.querySelector('#priority').value,
formElement.querySelector('#date').value
);
let project = DOM_DISPLAY.getCurrentProject();
project.addTask(newTask);
USER.updateData();
DOM_DISPLAY.updateDisplay();
});
});
})();
// DISPLAY TABS
(() => {
const TABS = document.querySelectorAll('.link-nav-item');
TABS.forEach((tab) => {
tab.addEventListener('click', (e) => {
DOM_DISPLAY.setFilter([...TABS].indexOf(tab));
DOM_DISPLAY.updateDisplay();
deselectTabs(TABS);
selectTab(tab);
});
});
function selectTab(tab) {
tab.classList.add('list-nav-item-selected');
}
function deselectTabs(tabs) {
tabs.forEach((tab) => tab.classList.remove('list-nav-item-selected'));
}
})();
export { DOM_DISPLAY };
<file_sep># TODOer
App for storing, displaying and filtering your tasks and projects.
This project was done for the TOP.
## Minor inconveniences
- When deleting a project any project gets unseletected.
- Switching from mobile to PC display breaks the PC layout
|
e79c786d7ec3188ce939b3087e5679b0396141c9
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
Moroundiya/todo-list-app
|
0b62d327e07de532788535e71241f379db7ebf43
|
512ae6ce9c8b95772c44290f3f5675dd2419ffbe
|
refs/heads/master
|
<file_sep># try
This is a try project
|
a54edafafc2acaaedeaf4459f02d42b46dd7c2b7
|
[
"Markdown"
] | 1 |
Markdown
|
mowatermelon/try
|
67aabe593c7e0246cf2033bc70f50f8155630e23
|
55f338cd71a4fb2ddd78bd3363483bb9c58e6710
|
refs/heads/master
|
<file_sep>import 'package:flutter/material.dart';
import 'package:unit_converter/custom_widget/ConverterContainer.dart';
class ConverterPage extends StatefulWidget {
final String unitName;
final Color unitColor;
ConverterPage({@required this.unitName, @required this.unitColor});
@override
_ConverterPageState createState() {
return new _ConverterPageState(
unitName: this.unitName, unitColor: this.unitColor);
}
}
class _ConverterPageState extends State<ConverterPage> {
final String unitName;
final Color unitColor;
_ConverterPageState({@required this.unitName, @required this.unitColor});
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
backgroundColor: unitColor,
title: new Text(unitName),
),
body: _converterBody(),
);
}
Container _converterBody() {
return new Container(
color: Colors.white,
child: new Column(
children: <Widget>[
_input(),
const SizedBox(height: 12.0),
new Icon(Icons.import_export),
const SizedBox(height: 12.0),
_output(),
],
),
);
}
Column _input() {
return new Column(
children: <Widget>[
const SizedBox(height: 24.0),
new ConverterContainer(
hintText: "Enter input value",
labelText: "Input",
),
],
);
}
Column _output() {
return new Column(
children: <Widget>[
new ConverterContainer(
hintText: "Output value",
labelText: "Ouput",
),
],
);
}
}
<file_sep>import 'package:flutter/material.dart';
import 'package:unit_converter/ui/CategoriesPage.dart';
void main(){
runApp(new CategoriesPage());
}<file_sep>import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
class Category {
final String name;
final IconData iconData;
final ColorSwatch colorSwatch;
Category({
@required this.name,
@required this.iconData,
@required this.colorSwatch,
});
}
<file_sep>import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
import 'package:unit_converter/model/Category.dart';
import 'package:unit_converter/ui/ConverterPage.dart';
import 'package:unit_converter/util/Constants.dart';
class CategoryListItem extends StatelessWidget {
final double _itemHeight = 100.0;
final Category category;
CategoryListItem({@required this.category});
@override
Widget build(BuildContext context) {
return Material(
color: Constants.backgroundColor,
child: Container(
height: _itemHeight,
child: InkWell(
splashColor: category.colorSwatch,
highlightColor: category.colorSwatch,
borderRadius: BorderRadius.circular(_itemHeight / 2),
onTap: () {
print("Tapped " + category.name);
_navigateToConverterPage(context);
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: new Container(
child: new Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: new Icon(
category.iconData,
size: 60.0,
),
),
new Text(
category.name,
style: TextStyle(fontSize: 24.0),
),
],
),
),
),
),
),
);
}
void _navigateToConverterPage(BuildContext context) {
Navigator.of(context).push(
new MaterialPageRoute(
builder: (BuildContext context) => new ConverterPage(
unitName: category.name,
unitColor: category.colorSwatch,
),
),
);
}
}
<file_sep># flutter-udacity-course
[Udacity course link](https://classroom.udacity.com/courses/ud905)
<file_sep>import 'package:flutter/material.dart';
import 'package:unit_converter/custom_widget/ConverterOptions.dart';
import 'package:unit_converter/custom_widget/ConverterValue.dart';
import 'package:meta/meta.dart';
class ConverterContainer extends StatelessWidget {
final String labelText;
final String hintText;
ConverterContainer({@required this.labelText, @required this.hintText});
@override
Widget build(BuildContext context) {
return new Container(
child: new Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new ConverterValue(
hintText: hintText,
labelText: labelText,
),
new SizedBox(height: 12.0),
new ConverterOptions(),
],
),
),
);
}
}
<file_sep>import 'package:flutter/material.dart';
import 'package:unit_converter/model/Category.dart';
class Constants {
static final backgroundColor = Colors.green[100];
static const categoryNameList = <String>[
'Length',
'Area',
'Volume',
'Mass',
'Time',
'Digital Storage',
'Energy',
'Currency',
];
static const categoryIconList = <IconData>[
Icons.cake,
Icons.cake,
Icons.cake,
Icons.cake,
Icons.cake,
Icons.cake,
Icons.cake,
Icons.cake,
];
static const categoryColorList = <Color>[
Colors.teal,
Colors.orange,
Colors.pinkAccent,
Colors.blueAccent,
Colors.yellow,
Colors.greenAccent,
Colors.purpleAccent,
Colors.red,
];
static List<Category> getCategoriesList() {
List<Category> list = new List();
for (int i = 0; i < categoryNameList.length; i++) {
list.add(new Category(
name: categoryNameList[i],
iconData: categoryIconList[i],
colorSwatch: categoryColorList[i],
));
}
return list;
}
}
<file_sep>import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class ConverterOptions extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Container(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
),
),
child: DropdownButtonHideUnderline(
child: ButtonTheme(
child: new DropdownButton(items: _inputItems(), onChanged: null),
),
),
);
}
List<DropdownMenuItem<String>> _inputItems() {
List<DropdownMenuItem<String>> list = new List();
list.add(new DropdownMenuItem(child: Text("1")));
list.add(new DropdownMenuItem(child: Text("2")));
list.add(new DropdownMenuItem(child: Text("3")));
list.add(new DropdownMenuItem(child: Text("4")));
list.add(new DropdownMenuItem(child: Text("5")));
list.add(new DropdownMenuItem(child: Text("6")));
list.add(new DropdownMenuItem(child: Text("7")));
list.add(new DropdownMenuItem(child: Text("8")));
list.add(new DropdownMenuItem(child: Text("9")));
list.add(new DropdownMenuItem(child: Text("10")));
return list;
}
}
<file_sep>import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
class ConverterValue extends StatelessWidget {
String _hintText;
String _labelText;
ConverterValue({@required hintText, @required labelText}){
_hintText = hintText;
_labelText = labelText;
}
@override
Widget build(BuildContext context) {
return new TextField(
decoration: new InputDecoration(
border: const OutlineInputBorder(),
hintText: _hintText,
labelText: _labelText,
),
);
}
}<file_sep>import 'package:flutter/material.dart';
import 'package:unit_converter/custom_widget/CategoryListItem.dart';
import 'package:unit_converter/util/Constants.dart';
class CategoriesPage extends StatelessWidget {
final String _appTitle = "UNIT CONVERTER";
@override
Widget build(BuildContext context) {
return new MaterialApp(
debugShowCheckedModeBanner: false,
home: new Scaffold(
appBar: _appBar(),
body: _unitConverterHomePageBody(),
),
);
}
AppBar _appBar() {
return new AppBar(
backgroundColor: Constants.backgroundColor,
elevation: 0.0,
title: Center(
child: new Text(
_appTitle,
style: TextStyle(
color: Colors.black,
fontSize: 22.0,
),
),
),
);
}
Widget _unitConverterHomePageBody() {
return new ListView.builder(
itemCount: Constants.getCategoriesList().length,
itemBuilder: (BuildContext context, int index) => CategoryListItem(
category: Constants.getCategoriesList()[index],
),
);
}
}
|
4f30c40e45c75cc719c3dd834642250c7f4593b1
|
[
"Markdown",
"Dart"
] | 10 |
Markdown
|
rohan20/flutter-udacity-course
|
a985af7d7a8e3ca79baf0a4d517e12d824133eee
|
49ab90b173e8ab8317669dd8b1128bcfd0650722
|
refs/heads/main
|
<file_sep>import React, {useState, useEffect} from 'react'
import {submitForm} from "./apiCalls";
const showSuccess = (responseMessage) => {
return(
alert(responseMessage)
)
}
const WildHabEventForm = () => {
const [formValues, setFormValues] = useState({
eventName: '',
sport: '',
eventDuration: 0
})
const [responseMessage, setResponseMessage] = useState(undefined)
useEffect(() => {
if (responseMessage !== undefined) {
showSuccess(responseMessage)
}
},[responseMessage])
return(
<>
<h1>Create Wild Habitat Event</h1>
<form onSubmit={(event) => submitForm(event, formValues, setResponseMessage)}>
<label>
Event Name:
</label>
<input
name="eventName"
type="text"
value={formValues.eventName}
onChange={e => setFormValues({...formValues, eventName: e.target.value})}
/>
<br />
<label>
Sport:
</label>
<input
name="sport"
type="text"
value={formValues.sport}
onChange={e => setFormValues({...formValues, sport: e.target.value})}
/>
<br />
<label>
Event Duration (hours):
</label>
<input
name="eventDuration"
type="number"
value={formValues.eventDuration}
onChange={e => setFormValues({...formValues, eventDuration: e.target.value})}
/>
<br />
<button type="submit">Submit</button>
</form>
</>
)
}
export default WildHabEventForm
<file_sep>export const submitForm = (event, formValues, setResponseMessage) => {
console.log(formValues)
fetch("https://wildhab-api-a.web.app/events", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formValues),
})
.then(result => result.json())
.then(data => {
data.statusCode < 300 ? setResponseMessage(data.message) : console.log('error')
})
.catch(error => console.log('error', error))
event.preventDefault()
}
// {"status":"success",
// "data":{"updated":{"_seconds":1612553911,"_nanoseconds":864000000},
// "created":{"_seconds":1612553911,"_nanoseconds":864000000},
// "eventName":"Frisbee Event",
// "eventDuration":"1",
// "sport":"Frisbee",
// "id":"Nva5RJDqLM1wz3Rvfc4o"},
// "message":"Events loaded successfully",
// "statusCode":200}
|
bc19affa191d1be6d039019668f2ff6af8d809af
|
[
"JavaScript"
] | 2 |
JavaScript
|
michellebakels/wild-hab-web
|
00c7e7d4cb231562072028a6b05cc55156847c19
|
e2f0abb93cde6429d8cb61df6dec5b21c511469e
|
refs/heads/master
|
<file_sep>/* Scroll Bar Master Styling Starts Here
/* All comments can be freely removed from the css
.scrollgeneric
line-height: 1px
font-size: 1px
position: absolute
top: 0
left: 0
.vscrollerbase
width: 10px
background-color: white
.vscrollerbar
width: 10px
background-color: black
.hscrollerbase
height: 10px
background-color: white
.hscrollerbar
height: 10px
background-color: black
.scrollerjogbox
width: 10px
height: 10px
top: auto
left: auto
bottom: 0px
right: 0px
background-color: gray<file_sep>@import bourbon
@import fonts.sass
@import vars.sass
@import "app/libs/flexcroll/modules/news-ticker/flexcrollstyles.sass"
// =================================== common classes and tags begin ==================================
html
margin-right: 0 !important
overflow: visible !important
body
font-size: 16px
min-width: 320px
position: relative
line-height: 1.6
font-family: "OpenSansRegular", sans-serif
overflow-x: hidden
color: #333
background-image: url("../img/parket_background.jpg")
// set the lengt of site
height: 2600px
//h1 - company name
//h2 - slogan
//h3 - slider headers and section names
//h4 - slider description
//h5 - services section(left navigation panel)
//h6 - text in the content panel
h1, h2, h3, h4, h5, h6,
.h1, .h2, .h3, .h4, .h5, .h6
font-family: "OpenSansLight", sans-serif
font-weight: normal
// section header
h2,
.h2
font-size: 250%
text-align: center
margin-top: 25px //120px
margin-bottom: 25px
// slider frame title
h3,
.h3
font-size: 320%
h4,
.h4
font-family: OpenSansLight, sans-serif
font-weight: normal
font-size: 150%
h5,
.h5
font-family: "OpenSansRegular", sans-serif
font-size: 140%
h6,
.h6
font-size: 100%
margin-top: -8px;
.opacity0
opacity: 0
.nav-background
background-color: $header_color
.white-background
background-color: rgb(255,255,255)
//box-shadow: 0px 14px 14px black
box-shadow: 0px 20px 14px black
.gray-background
background-color: rgb(200,200,200)
box-shadow: 0px 20px 14px black
.black-background
background-color: rgb(0,0,0)
box-shadow: 0px 20px 14px black
.site-end
position: relative
left: 100px;
top: 350px;
.site-content
position: relative
//border: 3px solid #73AD21
z-index: 1
.site-empty-header
display: block
height: 90px
.menu-line
.full-width
padding-left: 0px
padding-right: 0px
.white-section-spacer
height: 110px
background-color: rgb(255,255,255)
box-shadow: 0px 20px 14px black
// =================================== common classes and tags end ===================================
// ================================== logo section begin =============================================
.logo
display: block
width: 80px
margin: 15px 0px
//float: left
img
width: 100%
.logo-company-name
font-family: "ImpactRegular", sans-serif
font-weight: normal
text-align: left
font-size: 30px
color: rgb(255,255,255)
margin: 5px 5px 0px 0px
padding: 5px 10px
line-height: 80%;
.logo-company-slogan
font-family: "ImpactRegular", sans-serif
font-weight: normal
text-align: left
font-size: 18px
color: rgb(255,255,255)
margin: 5px 5px 0px 0px
padding: 0px 10px
line-height: 88%;
.logo-company-phone
font-family: "OpenSansRegular", sans-serif
font-weight: normal
text-align: left
font-size: 14px
color: rgb(255,255,255)
margin: 0px 5px 0px 0px
padding: 15px 10px
line-height: 80%;
// ================================== logo section end =============================================
// ================================== menu section begin ===========================================
.navbar-fixed-top
margin: auto
.hidden-menu-wrapper
padding: 0px
margin: 0px
.main-menu
ul
list-style-type: none
margin: 22px 10px auto 0px
padding: 0px 0px
text-align: right
li
display: inline-block
text-align: center
margin: 0px 0px
padding: 10px 5px
a
font-family: "OpenSansRegular", sans-serif
font-weight: normal
font-size: 125%
//color: rgb(240,190,84)
color: $color_menu_normal
margin: 10px 0px 0px 0px
padding: 0px 0px 0px 5px
+mt($anim_menu_time)
&:hover
text-decoration: none
color: $color_white
&.active
color: $color_golden
text-decoration: none
.hidden-menu
display: none
background-color: $header_color
margin: 0px 0px
padding: 0px 0px
ul
list-style-type: none
padding: 0px 0px 0px 0px
margin: 30px 0% 0px 0%
li
display: block
text-align: center
margin: 0px 0px
padding: 10px 5px
border-bottom: solid $color_menu_normal 1px
a
font-family: "OpenSansRegular", sans-serif
font-weight: normal
font-size: 140%
//color: rgb(240,190,84)
color: $color_menu_normal
margin: 10px 0px 0px 0px
padding: 0px 0px 0px 5px
+mt($anim_menu_time)
&:hover
text-decoration: none
color: $color_white
&.active
color: $color_golden
text-decoration: none
// menu toggle button
.toggle-mnu,
.toggle-mnu-small
display: block
width: 28px
height: 28px
margin-top: 14px
span:after, span:before
content: ""
position: absolute
left: 0
top: 9px
span:after
top: 18px
span
position: relative
display: block
span, span:after, span:before
width: 100%
height: 2px
background-color: #fff
transition: all 0.3s
backface-visibility: hidden
border-radius: 2px
&.on span
background-color: transparent
&.on span:before
transform: rotate(45deg) translate(-1px, 0px)
&.on span:after
transform: rotate(-45deg) translate(6px, -7px)
position: absolute
top: 10px
right: 30px
// ================================== menu section end =============================================
// ================================== slider section begin =============================================
.slider
.carousel
.carousel-caption
padding-bottom: 16%
.h3,
h3,
.h4,
h4
text-shadow: 1px 1px 1px #111
.middle-slider-button
position: absolute
left: 50%
top: $buttons_position_vertical
.info-button
@extend .base-button
.order-button
@extend .base-button
position: absolute
right: 12%
top: $buttons_position_vertical
z-index: 5
.count-button
@extend .base-button
position: absolute
left: 12%
top: $buttons_position_vertical
z-index: 5
// slider buttons for non large resolution end
.hidden-slider-buttons
position: relative
margin: 4px 4px 20px 4px
bottom: -4px
.btn-group
display: block
width: $button_length
margin: auto
z-index: 5
.count-button-hide
@extend .base-button
width: 100%
margin: 5px
.info-button-hide
@extend .base-button
width: 100%
margin: 5px
.order-button-hide
@extend .base-button
width: 100%
margin: 5px
.slider-overlay
position: absolute
top: 0
left: 0;
width: 100%
height: 100%
z-index: 2
background-color: rgba(0,0,0,0.5)
// ================================== slider section end =============================================
<file_sep>@import bourbon
@import vars.sass
//Load Libs SASS
@import "app/libs/animate/animate.sass"
@import "app/libs/font-awesome/css/font-awesome.sass"
@import "app/libs/Magnific-Popup/magnific-popup.sass"
@import "app/libs/owl-carousel/assets/owl.carousel.sass"
@import "app/libs/selectize/dist/css/selectize"
//@import "app/libs/jstree/themes/default/style.sass"
.bootstrap-colomn-padding0
padding-left: 0px
padding-right: 0px
// ================================== galery section begin ===========================================
a.right.carousel-control,
a.left.carousel-control
height: 0px
//chevrons
.carousel-control .icon-prev,
.carousel-control .icon-next
position: absolute
top: -70px
color: $gallery-controls-color
.gallery,
.gallery-small
padding-bottom: 50px
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12
padding-left: 0px;
padding-right: 0px;
.gallery-item
margin: 1px
display: block
overflow: hidden
.img-responsive
margin: auto
+mt($anim_menu_time)
&:hover
.gallery-item-content
//transform: scale(0.9)
opacity: 1
.img-responsive
transform: scale(1.2)
.gallery-item-content
display: block
position: absolute
top: 0%
left: 0%
width: 100%
height: 100%
background-color: rgba(255,255,255,0.70)
transition: all $anim_menu_time ease-in-out
text-align: center
padding-top: 30%
opacity: 0
overflow: hidden
i
color: $gallery-controls-color
font-size: 24px
.carousel-caption
padding-bottom: 7%;
color: $gallery-controls-color
font-size: 16px
line-height: 100%
.gallery-small
.gallery-item
.gallery-item-content
display: block
position: absolute
padding-top: 30%
i
font-size: 20px
.carousel-caption
padding-bottom: 7%;
font-size: 16px
line-height: 100%
// controlls
.carousel-indicators
.active
background-color: $gallery-controls-color
li
border: 1px solid $gallery-controls-color
position: absolute
bottom: -40px
.carousel-control
width: 10%
.icon-prev, .icon-next
font-size: 60px
// dialog
.gallery-popup
position: relative
top: -42px
background-color: #fff
display: block
max-width: 700px
margin: 5% auto
text-align: center
.responsive-img
width: 90%
margin: 0% auto
padding: 1% auto
.h2
font-family: "OpenSansRegular", sans-serif
font-size: 180%
word-wrap: break-word
// popup fade animation
.mfp-fade
&.mfp-bg
opacity: 0
transition: all $gallery_dialog_show_hide_time ease-out
&.mfp-ready
opacity: 0.8
&.mfp-removing
opacity: 0
&.mfp-wrap
.mfp-content
opacity: 0
transition: all $gallery_dialog_show_hide_time ease-out
&.mfp-ready .mfp-content
opacity: 1
&.mfp-removing .mfp-content
opacity: 0
// popup zoom animation
.mfp-with-zoom
.mfp-container, &.mfp-bg
opacity: 0
-webkit-backface-visibility: hidden
/* ideally, transition speed should match zoom duration
-webkit-transition: all 0.3s ease-out
-moz-transition: all 0.3s ease-out
-o-transition: all 0.3s ease-out
transition: all 0.3s ease-out
&.mfp-ready
.mfp-container
opacity: 1
&.mfp-bg
opacity: 0.8
&.mfp-removing
.mfp-container, &.mfp-bg
opacity: 0
// ================================== galery section end ===========================================
// ================================== service section begin ===========================================
// vars
$services-panels_height: 500px
.services
padding-bottom: 25px
//box-shadow: 0px 14px 14px black
//-10px 8px 15px gray, 10px 8px 15px gray
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12
padding-left: 0px;
padding-right: 0px;
.services-panels
height: $services-panels_height
// custom scrollbar
.vscrollerbar
width: 10px
background-color: #b9b9b9
border-radius: 5px
//padding: 0px 15px 0px 0px
.navigation-panel,
.navigation-panel-small
background-color: rgb(241,203,124)
//background-color: rgb(138,138,138)
overflow: auto
height: $services-panels_height
padding: 10px 5px 5px 5px 5px
li
font-size: 22px;
.navigation-panel-small
height: 100%
.content-panel
background-color: rgb(240,240,240)
overflow: auto
height: $services-panels_height
padding: 5px 5px 15px 5px
.h6,
h6
text-align: justify
text-justify: inter-word
.col-xs-1
width: 0%
.jstree-default
.jstree-anchor
height: 34px !important
// side panel
.sidenav
height: $services-panels_height
width: 0
//position: fixed
position: absolute
z-index: 10
top: 0
left: 0
bottom: 0
background-color: #111
overflow-x: hidden
//overflow: auto
transition: 0.5s
padding-top: 0px
> a
padding: 8px 8px 8px 32px
text-decoration: none
font-size: 25px
color: #818181
display: block
transition: 0.3s
> p
padding: 8px 8px 8px 32px
text-decoration: none
font-size: 25px
color: #818181
transition: 0.3s
display: block
a:hover
color: #f1f1f1
.offcanvas a:focus
color: #f1f1f1
.sidenav .closebtn
position: absolute
top: 0
right: 25px
font-size: 36px
margin-left: 50px
@media screen and (max-height: 450px)
.sidenav
padding-top: 15px
a
font-size: 18px
.toggle-mnu-small
position: absolute
top: -50px
left: 0px
.toggle-mnu-small span, .toggle-mnu-small span::after, .toggle-mnu-small span::before
width: 100%;
height: 2px;
background-color: #000
.contacts-buttons
.left-button-wrapper
text-align: center
margin: 6px
.count-button
@extend .base-button
position: absolute
right: 0px
top: 0px
margin: 2px 20px
background-color: $color_orange
&:hover
background-color: $color_orange
.right-button-wrapper
text-align: center
margin: 6px
.order-button
@extend .base-button
position: absolute
left: 0px
top: 0px
margin: 2px 20px
background-color: $color_orange
&:hover
background-color: $color_orange
// ================================== service section end ===========================================
// ================================== comments section begin ===========================================
// vars
$face_radius: 100px
.testimonials
height: 700px + $height_testimonials_adder
.testimonials-item
text-align: center
margin-top: 20px
&:hover
.testimonials-desc
border-bottom: 5px solid $color_orange
.rounded-img-wrap
img
width: $face_radius*1.05
height : $face_radius*1.05
border-radius: $face_radius*1.05
border: 5px solid $color_orange
.testimonials-desc
background-color: $color_light_yellow
margin: 30px 0px 20px 0px
padding: 10px
border-radius: 2px
position: relative
border-bottom: 5px solid $color_white
box-shadow: 0px 14px 14px black
+mt($anim_time)
&::before
content: ''
position: absolute
top: -16px
transform: translateX(-16px)
@include triangle(32px, $color_light_yellow, up)
.rounded-img-wrap
img
+mt($anim_time)
width: $face_radius
height : $face_radius
border-radius: $face_radius
border: 5px solid $color_white
box-shadow: rgba(0,0,0,.25) 0 0 10px
.h5,
h5
text-shadow: 1px 1px 1px #111
.h2,
h2
margin-top: 50px
.leave-testimonial-button-wrapper
text-align: center
height: 150px
.leave-testimonial-button
@extend .base-button
background-color: $color_orange
&:hover
background-color: $color_orange
&:active
background-color: $color_orange
// ================================== comments section end ===========================================
// ================================== contacts section begin ===========================================
//vars
$social_media_icon_size: 45px
.contacts
background-color: $color_light_yellow
h2,
.h2
margin-top: 20px
.contacts-text
padding: 20px
i.fa-phone
padding: 0px 5px
font-size: 34px
i.fa-envelope
font-size: 28px
padding: 0px 3px
i.fa-envelope.first
margin-top: 10px
p
margin: 0px
font-size: 125%
//text-shadow: 1px 1px 4px #333
.social
margin-top: 100px
margin-bottom: 30px
text-align: center
h4,
.h4
font-size: 160%
font-family: "OpenSansRegular", sans-serif
font-weight: normal
margin-bottom: 30px
.social-icons
img
width: $social_media_icon_size
height: $social_media_icon_size
border-radius: $social_media_icon_size
margin: 5px 12px
+mt($anim_menu_time)
opacity: 1.0
a
&:hover
text-decoration: none
img
opacity: 0.8
.contact-form-title
text-align: center
padding: 0px 30px
p
text-align: center
font-size: 120%
font-family: "OpenSansRegular", sans-serif
font-weight: normal
margin-top: 20px
margin-bottom: 20px
line-height: 130%
.contact-form
width: 80%
margin: auto
label
margin: 0px
.form-group
margin: 0px 0px 10px 0px
.submit-button-wrapper
margin: 5px 5px 15px 5px
.submit-button
display: block
margin: auto
.submit-button
@extend .base-button
margin: 10px 0px
background-color: $color_orange
&:hover
background-color: $color_orange
.contacts-dialog
position: relative
top: -42px
background-color: $color_light_yellow
display: block
max-width: 500px
margin: 5% auto
//text-align: center
.contact-form-title
text-align: center
padding: 0px 50px
p
text-align: center
font-size: 120%
font-family: "OpenSansRegular", sans-serif
font-weight: normal
margin-top: 5px
margin-bottom: 10px
line-height: 130%
.contact-form
width: 90%
margin: auto
label
margin: 0px
.form-group
margin: 0px 0px 10px 0px
.submit-button-wrapper
margin: 15px 5px 15px 5px
.submit-button
display: block
margin: auto
.submit-button
@extend .base-button
margin: 10px 0px
background-color: $color_orange
&:hover
background-color: $color_orange
// ================================== contacts section end ===========================================
// ================================== footer section begin ===========================================
.footer
.logo-company-name
margin-top: 10px
.company-phone
text-align: right
margin: 10px auto
color: rgb(200, 200, 200)
.social-header
text-align: center
color: rgb(200, 200, 200)
.copy-rights
text-align: center
color: rgb(100, 100, 100)
.footer-social
text-align: center
margin: 40px 0px 25px 0px
.social-icons
img
width: $social_media_icon_size
height: $social_media_icon_size
border-radius: $social_media_icon_size
margin: 5px 12px
+mt($anim_menu_time)
opacity: 1.0
a
&:hover
text-decoration: none
img
opacity: 0.8
// ================================== footer section end ===========================================
// testimonials dialog begin
.testimonials-dialog
position: relative
top: -10px
background-color: $color_white
display: block
max-width: 700px
margin: 5% auto
.responsive-img
width: 100%
.arrow-up-wrapper
display: block
cursor: pointer
position: fixed
bottom: 50px
right: 50px
z-index: 5
background-color: none
border-radius: 2px
+mt($anim_menu_time)
opacity: .8
&:hover
background-color: $color_golden
i
color: $color_white
i
padding: 10px
color: $color_golden
//ALWAYS END
@import "_media.sass" <file_sep>// ================================== logo begin =========================================
/* Custom, iPhone Retina */
@media only screen and (min-width : 320px)
/**/
.logo
margin: 10px auto
.site-empty-header
margin: 42px
/* Extra Small Devices, Phones */
@media only screen and (min-width : 480px)
/**/
.logo
margin: 10px auto
.site-empty-header
margin: 42px
/* Small Devices, Tablets */
@media only screen and (min-width : 768px)
.site-empty-header
margin: 0px
// ================================== logo end =========================================
// ================================== slider action buttons begin =========================================
@media screen and (min-width: 320px) and (max-width : 650px)
.slider
.hidden-slider-buttons
position: relative
bottom: -18px
margin: 4px 4px 20px 4px
.count-button-hide,
.info-button-hide,
.order-button-hide
margin: 6px
@media screen and (min-width: 651px) and (max-width : 767px)
.slider
.hidden-slider-buttons
position: relative
bottom: -18px
margin: 4px 4px 20px 4px
.count-button-hide,
.info-button-hide,
.order-button-hide
margin: 6px
@media screen and (min-width: 768px) and (max-width : 991px)
.slider
.hidden-slider-buttons
position: relative
bottom: -18px
margin: 4px 4px 20px 4px
.count-button-hide,
.info-button-hide,
.order-button-hide
margin: 6px
@media screen and (min-width: 992px) and (max-width : 1199px)
.slider
.order-button
right: 8%
.count-button
left: 8%
// ================================== slider action buttons end =========================================
@media screen and (min-width: 320px) and (max-width : 350px)
.site-content
.site-empty-header
height: 110px
// ================================== slider text begin ==================================
@media screen and (min-width: 320px) and (max-width : 480px)
.slider
.carousel
.carousel-caption
padding-bottom: 3%
.slider-frame-description
font: 16px OpenSansLight, sans-serif
h3,
.h3
font-size: 200%
h4,
.h4
font-size: 110%
@media screen and (min-width: 481px) and (max-width : 650px)
.slider
.carousel
.carousel-caption
padding-bottom: 3%
@media screen and (min-width: 651px) and (max-width : 991px)
.slider
.carousel
.carousel-caption
padding-bottom: 5%
// ================================== slider text end ==================================
// ================================== gellery controlls begin ==================================
@media only screen and (min-width : 768px)
.gallery
.icon-prev, .icon-next
font-size: 60px
.gallery-small
.icon-prev, .icon-next
font-size: 60px
@media screen and (min-width: 320px) and (max-width : 360px)
.gallery-small
.gallery-item
.gallery-item-content
padding-top: 30%
.carousel-caption
padding-bottom: 0%
bottom: 12px
font-size: 14px
line-height: 100%
@media screen and (min-width: 361px) and (max-width : 410px)
.gallery-small
.gallery-item
.gallery-item-content
padding-top: 30%
.carousel-caption
padding-bottom: 0%
bottom: 20px
font-size: 14px
line-height: 100%
@media screen and (min-width: 768px) and (max-width : 992px)
.gallery
.gallery-item
.gallery-item-content
padding-top: 25%
.carousel-caption
padding-bottom: 3%
font-size: 14px
line-height: 100%
// ================================== gellery controlls end ==================================
// popup text
@media screen and (min-width: 220px) and (max-width : 420px)
.gallery-popup
.h2,
h2
word-wrap: break-word
font-size: 120%
@media screen and (min-width: 421px) and (max-width : 650px)
.gallery-popup
.h2,
h2
word-wrap: break-word
font-size: 150%
// ================================== services begin ==================================
@media screen and (max-width : 768px)
.contacts-buttons
.left-button-wrapper
.count-button
position: static
margin: auto
box-shadow: 0px 5px 5px black
.right-button-wrapper
text-align: center
.order-button
position: static
margin: auto
box-shadow: 0px 5px 5px black
// ================================== services end ==================================
// ================================== testimonials begin ==================================
@media screen and (min-width: 769px) and (max-width : 992px)
.testimonials
height: 800px + $height_testimonials_adder
@media screen and (min-width: 551px) and (max-width : 768px)
.testimonials
height: 1360px + $height_testimonials_adder
@media screen and (min-width: 450px) and (max-width : 550px)
.testimonials
height: 1400px + $height_testimonials_adder
@media screen and (min-width: 380px) and (max-width : 449px)
.testimonials
height: 1500px + $height_testimonials_adder
@media screen and (max-width : 379px)
.testimonials
height: 1600px + $height_testimonials_adder
// ================================== testimonials end ==================================
// ================================== contacts begin ==================================
@media screen and (max-width : 768px)
.contacts
.social
margin-top: 30px
// ================================== contacts end ==================================
// ================================== contacts dialog begin ==================================
@media screen and (max-width : 400px)
.contacts-dialog
top: 0px
.contact-form-title
padding: 0px 30px
.submit-button-wrapper
margin: 15px 5px 5px 5px
@media screen and (min-width : 400px) and (max-width : 992px)
.contacts-dialog
top: -30px
// ================================== contacts dialog end ==================================
// ================================== footer begin ==================================
@media screen and (max-width : 768px)
.footer
.footer-logo
margin: auto
.logo-company-name
margin-top: 10px
text-align: center
.company-phone
text-align: center
// ================================== footer end ==================================
<file_sep>$bootstrap_grid_width: 1170px
$btn: #14B75A
$accent: #ECB124
$blue: #414E5B
$button_length: 250px
$button_border_radius: 2px
// ====================== colors start ========================
$header_color: rgb(0,0,0)
$color_white: rgb(255,255,255)
$color_yellow: rgb(240,190,84)
$color_light_yellow: rgb(241,203,124)
$color_golden: rgb(233,164,15)
$color_orange: rgb(206,95,19)
$color_green: rgb(108, 163, 102)
$color_light_red: rgb(240, 95, 61)
$color_menu_normal: rgb(190,190,190)
$color_slider_buttons_text: rgb(225,225,225)
//
$hidden-menu-hover-background: #ECB124
$gallery-controls-color: #333333
$gallery-caption-color: rgba(65, 78, 91, .6)
// ====================== colors end ========================
// ====================== animation time begin ========================
// standart animation time
$anim_time: .5s
$anim_menu_time: .4s
$gallery_dialog_show_hide_time: .25s
=mt($time)
transition: all $time ease
// ====================== animation time end ========================
.base-button
color: $color_slider_buttons_text
background-color: $color_light_red
border: none
border-radius: $button_border_radius
opacity: .75
font-family: "OpenSansRegular", sans-serif
font-weight: normal
font-size: 22px
margin: 0px 5px
width: $button_length
padding: 5px 5px
box-shadow: 0px 2px 6px black
+mt($anim_menu_time)
&:hover
background-color: $color_light_red
color: $color_slider_buttons_text
opacity: 1
&:active
box-shadow: none
// ====================== slider ========================
$buttons_position_vertical: 75%
// ====================== testimonials begin ========================
// if the testemonials are longer and do not have enough space add some value
$height_testimonials_adder: -90px
// ====================== testimonials end ==========================
|
da38bc02dc6eee608937dfd126ec92f7da57ea63
|
[
"Sass"
] | 5 |
Sass
|
Vladimirvp2/SiteEpic
|
748094c374ec666084ab2dbc01912fa7348399a9
|
8d63911731d3ce998a703b42ac32585d489a49a7
|
refs/heads/master
|
<file_sep>from distutils.core import setup
import os
the_lib_folder = os.path.dirname(os.path.realpath(__file__))
requirement_path = the_lib_folder + '/requirements.txt'
install_requires = []
if os.path.isfile(requirement_path):
with open(requirement_path) as f:
install_requires = f.read().splitlines()
setup(
name='py-parquet-builder',
version='1.0',
packages=['py_parquet_builder'],
url='',
license='',
author='dillonjohnson',
author_email='<EMAIL>',
description='This library creates a parquet from an array of dicts.',
install_requires=install_requires
)
<file_sep>from uuid import uuid4
from schema import Schema, And, Use, Optional
from py_parquet_builder.s3 import upload_file
import pyarrow as pa
import pandas as pd
import pyarrow.parquet as pq
import datetime
import os
from functools import partial
# facebook/facebook-page-insights/2020/04/file.parquet
class FailedToLoadException(Exception):
pass
def validate_input(obj):
schema = Schema([{'processed_timestamp': datetime.datetime,
'effective_timestamp': datetime.datetime,
'month': str,
'year': str,
'json_payload': str,
'social_network_id': str,
'data_type_data': str,
'social_network_type': str}],
ignore_extra_keys=True)
schema.validate(obj)
def validate_output(obj):
schema = Schema([{'processed_timestamp': datetime.datetime,
'effective_timestamp': datetime.datetime,
'month': str,
'year': str,
'json_payload': str,
'social_network_id': str,
'filename': str,
'data_type_data': str,
'social_network_type': str}],
ignore_extra_keys=True)
schema.validate(obj)
def dictarray_to_parquet_table(obj):
df = pd.DataFrame.from_dict(obj)
table = pa.Table.from_pandas(df, preserve_index=False)
return table
def parquet_table_to_file(tab,
filename):
pq.write_table(table=tab,
where=filename)
return filename
def update_filename(row, filename):
row['filename'] = filename
return row
def dictarray_file_to_s3(obj, bucket):
# validate input
validate_input(obj)
# create and append filename
# filename = uuid4() + ".parquet"
subpath = f'{obj[0]["social_network_type"]}/{obj[0]["data_type_data"]}/year={obj[0]["year"]}/month={obj[0]["month"]}/'
filename = f'{uuid4()}.parquet'
# obj['filename'] = filename
obj = list(map(partial(update_filename, filename=filename), obj))
# validate output
validate_output(obj)
# Convert to parquet table
tab = dictarray_to_parquet_table(obj)
# Load parquet to file
filename = parquet_table_to_file(tab, filename)
# Load file to S3
resp = upload_file(filename, bucket, object_name=subpath + filename)
if resp:
os.remove(filename)
else:
# Raise alerts
os.remove(filename)
raise FailedToLoadException(f"The file could not be loaded to bucket. Please retry again later.")
if __name__ == '__main__':
obj = [
{
"processed_timestamp": datetime.datetime.now(),
"effective_timestamp": datetime.datetime.today(),
"year": "2020",
"month": "06",
"test": "test",
"json_payload": "",
"social_network_id": ""
}
]
# validate_input(obj)
# dictarray_to_bytes(obj)
dictarray_file_to_s3(obj)
<file_sep># Py Parquet Builder
## Goal
The goal of this project is to take in a certain format of data and load it into an S3 location ready for consumption by Athena.
### Installing Libraries
```bash
```
### Usage ###
Use this library by passing in an array of dictionaries along with a few partion keys.
This will allow us to <file_sep>from botocore.exceptions import ClientError
import boto3
import logging
def upload_file(filename, bucket, object_name=None):
if object_name is None:
object_name = filename
s3_client = boto3.client('s3')
try:
response = s3_client.upload_file(filename, bucket, object_name)
except ClientError as e:
logging.error(e)
return False
return True
|
9acef670b90727786ac8ec687c768bd6009d06fc
|
[
"Markdown",
"Python"
] | 4 |
Markdown
|
dillonjohnson/py-parquet-builder
|
cd9ce708f94b59df513444643f8a3f5d96e5d7ec
|
750785fe2b4e24b6c4e6a8a5d7da6983a0de920e
|
refs/heads/master
|
<repo_name>AlexeiGitH/KingsPhrases<file_sep>/Privacy Policy.md
# Privacy Policy
This document informs you of our policies regarding the collection, use, and disclosure of personal data when you use our app.
## Information Collection And Use
We don’t collect nor share any personally identifying information.
Our app does not use any third-party services and does not link to any external sites.
This policy is effective as of 26 September 2019.
|
0a89d6c3f2287a36e8bebf4a5f6b2dc2fae69f43
|
[
"Markdown"
] | 1 |
Markdown
|
AlexeiGitH/KingsPhrases
|
0690a12092e84c03680f080e6ff1b7fa904411e1
|
46b0f5b951099aac67496cf28adb9f95e23dae72
|
refs/heads/master
|
<repo_name>totallymike/yafros<file_sep>/Cargo.toml
[package]
name = "mike_os"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
[lib]
crate-type = ["staticlib"]
[dependencies]
spin = "0.3.4"
[dependencies.multiboot2]
git = "https://github.com/phil-opp/multiboot2-elf64"
<file_sep>/src/arch/x86_64/error.asm
GLOBAL error
SECTION .text
BITS 32
error:
mov dword [0xb8000], 0x4f524f45
mov dword [0xb8004], 0x4f3a4f52
mov dword [0xb8008], 0x4f204f20
mov byte [0xb800a], al
hlt
<file_sep>/src/arch/x86_64/long_mode_start.asm
global long_mode_start
section .text
bits 64
long_mode_start:
extern rust_main
call rust_main
; Should never get here,
; but halt if we do
hlt
<file_sep>/src/arch/x86_64/long_mode.asm
SECTION .text
BITS 32
EXTERN error
GLOBAL check_cpuid
GLOBAL check_long_mode
check_cpuid:
;; Try to flip ID bit 21 in FLAGS
;; if it works, we have CPUID
;; Copy flags to EAX via stack
pushfd
pop eax
;; Stash FLAGS to ecx to compare later
mov ecx, eax
xor eax, 1 << 21
push eax
popfd
pushfd
pop eax
push ecx
popfd
cmp eax, ecx
je .no_cpuid
ret
.no_cpuid:
mov al, "1"
jmp error
check_long_mode:
mov eax, 0x80000000
cpuid
cmp eax, 0x80000001
jb .no_long_mode
mov eax, 0x80000001
cpuid
test edx, 1 << 29
jz .no_long_mode
ret
.no_long_mode:
mov al, "2"
jmp error
;; long_mode:
;; mov eax, cr0
;; and eax, 01111111111111111111111111111111b
;; mov cr0, eax
;; mov edi, 0x1000
;; mov cr3, edi
;; xor eax, eax
;; mov ecx, 4096
;; rep stosd
;; mov edi, cr3
;; mov DWORD [edi], 0x2003
;; add edi, 0x1000
;; mov DWORD [edi], 0x3003
;; add edi, 0x1000
;; mov DWORD [edi], 0x4003
;; add edi, 0x1000
;; mov ebx, 0x00000003
;; mov ecx, 512
;; .SetEntry:
;; mov DWORD [edi], ebx
;; add ebx, 0x1000
;; add edi, 8
;; loop .SetEntry
;; mov eax, cr4
;; or eax, 1 << 5
;; mov crx, eax
;; mov ecx, 0xC0000080
;; rdmsr
;; or eax, 1 << 8
;; wrmsr
;; mov eax, cr0
;; or eax, 1 << 31
;; mov cr0, eax
<file_sep>/README.md
# YAFROS
### Yet another Rust OS
##### (Expletive deleted)
## Build instructions
lol
<file_sep>/src/arch/x86_64/boot.asm
EXTERN error
EXTERN check_cpuid
EXTERN check_long_mode
EXTERN long_mode_start
GLOBAL start
SECTION .text
BITS 32
start:
mov esp, stack_top
mov edi, ebx ; Move multiboot info pointer to edi
call check_multiboot
call check_cpuid
call check_long_mode
call disable_paging
call set_up_page_tables
call enable_paging
call set_up_SSE
lgdt [gdt64.pointer]
; Update selectors
mov ax, gdt64.data
mov ss, ax ; Stack selector
mov ds, ax ; Data selector
mov es, ax ; Extra selector
; Magic debug instruction
; gets bochs to pause here, otherwise does nothing
XCHG BX, BX
jmp gdt64.code:long_mode_start
check_multiboot:
cmp eax, 0x36d76289
jne .no_multiboot
ret
.no_multiboot:
mov al, "0"
jmp error
disable_paging:
mov eax, cr0
and eax, 01111111111111111111111111111111b
mov cr0, eax
ret
set_up_page_tables:
; map the first P4 entry to P3 table
mov eax, p3_table
or eax, 0b11 ; Present + writable
mov [p4_table], eax
; Map first P3 entry to P2 table
mov eax, p2_table
or eax, 0b11 ; Present + writable
mov [p3_table], eax
mov ecx, 0 ; Counter variable
.map_p2_table:
; Map ecx-th P2 entry to a huge page that starts at 2MiB*ecx
mov eax, 0x200000 ; 2MiB
mul ecx
or eax, 0b10000011 ; Present, writable, huge
mov [p2_table + ecx * 8], eax ; Map ecx-th entry
inc ecx
cmp ecx, 512
jne .map_p2_table
ret
enable_paging:
; Load P4 to CR3 register (CPU uses this to access the P4 table)
mov eax, p4_table
mov cr3, eax
; Enable PAE-flag in CR4
mov eax, cr4
or eax, 1 << 5
mov cr4, eax
; Set the long-mode bit in the EFER MSR
mov ecx, 0xC0000080
rdmsr
or eax, 1 << 8
wrmsr
; Enable paging in the CR0 register
mov eax, cr0
or eax, 1 << 31
mov cr0, eax
ret
set_up_SSE:
; check for SSE
mov eax, 0x1
cpuid
test edx, 1<<25
jz .no_SSE
; enable SSE
mov eax, cr0
and ax, 0xFFFB
or ax, 0x2
mov cr0, eax
mov eax, cr4
or ax, 3 << 9
mov cr4, eax
ret
.no_SSE:
mov al, "a"
jmp error
SECTION .bss
align 4096
p4_table:
resb 4096
p3_table:
resb 4096
p2_table:
resb 4096
stack_bottom:
resb 4096
stack_top:
SECTION .rodata
gdt64:
dq 0 ; zero entry
.code: equ $ - gdt64
dw 0
dw 0
db 0
db 10011010b
db 00100000b
db 0
.data: equ $ - gdt64
dw 0
dw 0
db 0
db 10010010b
db 00000000b
db 0
.pointer:
dw $ - gdt64 - 1
dq gdt64
|
722de2e953cc4b5f318ce3bf75839d8cbe4acd1f
|
[
"Markdown",
"TOML",
"Assembly"
] | 6 |
Markdown
|
totallymike/yafros
|
edd48f5fc25111ed993ecf0606c5b49f5eabf361
|
70e5580f1ce031edb4505bcad106515b112a2324
|
refs/heads/master
|
<repo_name>shahariaazam/nginx-proxy-test<file_sep>/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
error_log /var/log/nginx/localhost.error_log info;
root /usr/share/nginx/html;
location /api {
proxy_pass http://dev.invoicespring.com:5201/api/v1;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
}<file_sep>/Dockerfile
FROM previewtechs/nginx:proxy
# Bundle app source
COPY . /usr/share/nginx/html
# Remove the default Nginx configuration file
RUN rm -v /etc/nginx/nginx.conf
# Copy a configuration file from the current directory
ADD nginx.conf /etc/nginx/
# Append "daemon off;" to the configuration file
RUN echo "daemon off;" >> /etc/nginx/nginx.conf
# Expose ports
EXPOSE 80
# Set the default command to execute when creating a new container
CMD service nginx start
|
10829b3027daf9402869ceab24e0ab7986cfe01f
|
[
"Nginx",
"Dockerfile"
] | 2 |
Nginx
|
shahariaazam/nginx-proxy-test
|
a51d21db391332cc6e4b52b4bcb2f133e23d683b
|
28a68b7eedd6350f6556c59ad7fb81c4bcd0939e
|
refs/heads/master
|
<repo_name>AndreBClark/WebStudentResources<file_sep>/Readme.md
_**DSCVR**_
===
## Getting Started
### 1. Setting up Accounts
1. Create [github accounts](https://github.com/)
1. send me your usernames so I can add you to the collaborators list
### 2. Github App
1. Download & Install [Github Desktop App](https://desktop.github.com/)
1. set up default cli and editor ``File>Options>Advanced``
### 3. Checking Dependencies
1. Using Your Terminal on mac or git bash on pc
1. check if git is installed ``git --version`` if not install [git](https://git-scm.com/downloads)
1. check if node is installed ``node --version`` or ``npm --version`` Install [node.js](https://nodejs.org/en/)
### 4. Initial Build Process
1. Clone Repository
1. Open CLI at ``dscvr/src/`` or using Github ``cmd + ` `` then ``cd src``
1. enter ``npm install``
1. enter``npm run build --watch``
1. Using Github ``cmd + shift + A`` ``Repository>Open in Editor Name``
_once your editor of choice is open you are ready to work on the project._
### 5. Verify Functionality
Once you've followed the Steps, verify if it worked by **[Viewing the Demo](demo.html)** The result should look colorful and obviously styled.
**Note:** _if either this page or the demo page look un-styled. that means you have not run your build yet or there is an issue preventing the build_
### 6. Working on the project
1. Open github Desktop and open terminal
1. In terminal Enter `cd src` to move to development folder
1. enter `npm run build --watch`
1. leave the terminal open while working
1. `--watch` will auto update your changes to you the assets folder locally
### 7. Checking Out Branches
The `origin/master` branch is the main production branch. with this project we will divide up work as Individual _Features_ or _Tasks_ There Are a few things you need to do, before you begin working on a feature. from this point on Everyone else needs to be working on the Dev Branch.
1. Check the project board for tasks to complete, place your chosen task in the `in progress` stack.
1. move to the dev branch from Github Desktop or from your code editor
1. If Your Feature doesn't have a branch yet create one. You can do so in the Github Desktop Application.
1. switch to your code editor and in the lower corner there should be a line that says the name of the current branch.
1. If it's correct, you're all set.
## Resources
Here is A list of links and Resources for learning more web design stuff. full list repo: [Resource List Repository](https://github.com/AndreBClark/WebStudentResources)
### UI/UX
* **[LearnUI.design](https://learnui.design/blog/)**
* **[King VS Pawn game UI Design](https://learnui.design/blog/king-vs-pawn-game-ui-design.html)**
* **[7 Rules For Creating Gorgeous UI](https://learnui.design/blog/7-rules-for-creating-gorgeous-ui-part-1.html)**
## CSS
* **[BEM](http://getbem.com/)** Block Element Modifier class naming system
* **[Organizing CSS](https://www.youtube.com/watch?v=IKFq2cSbQ4Q)** Video (37:54)
* **[Layout Land](https://www.youtube.com/channel/UC7TizprGknbDalbHplROtag)** Youtube Channel covering CSS Grid and Flexbox
## HTML
* **[Semantic HTML](https://html.com/semantic-markup/)**
* **[Markdown Cheetsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)** simplified rich text formating language that outputs to HTML
* **[Emmet Cheetsheet](https://docs.emmet.io/cheat-sheet/)** html shorthand for writing faster using css selector type notation
* **[100 Days of Code](https://github.com/nas5w/100-days-of-code-frontend)**
## Image Optimization
* [Optimize Images Webpack](https://iamakulov.com/notes/optimize-images-webpack/)
* [webpack for real tasks](https://iamakulov.com/notes/webpack-for-real-tasks-part-1/)
* [images guide](https://images.guide/))
* [imgix](https://www.imgix.com/)
* [fastly Image Optimizer](https://www.fastly.com)
* [Easy Dynamic Image Optimization with React and Webpack](https://www.scientiamobile.com/easy-dynamic-image-optimization-with-react-and-webpack/)
* [Webpack For Everyone -- Automatic Image Optimization](https://laracasts.com/series/webpack-for-everyone/episodes/13)
## Notable Modules in this WebPack
* **[WebPack](https://webpack.js.org/concepts/)**
* **[SASS](https://sass-lang.com/)**
* **[jQuery](https://api.jquery.com/)**
* **[Zurb Foundation](https://foundation.zurb.com/sites/docs/)**
* **[Featherlight](https://github.com/noelboss/featherlight)**
* **[Font Awesome](https://fontawesome.com/icons?d=gallery)**
* **[Slick Carousel](http://kenwheeler.github.io/slick/)**
* **[Babel](https://babeljs.io/docs/en/)**
<file_sep>/imgguidelines.md
# **_DSCVR_**
## Web Image Guidelines
### Initial Considerations
* Tightly crop the images
### Illustrations
* Transparent Background
* White color skin or whatever
* thumbnail and medium size
* Square ratio
* Or 3:2
### Portfolio Pieces
**Ratio**
* Tabloid/letter
* Square
* otherwise keep the ratio but make sure to crop out empty space
### Image resolutions
DPI/PPI: **72**
Colospace: **RGB**
colormode **sRGB**
### File Format
**PNG** Use for flat color images, such as the illustrations
**JPG** for full color complex Raster Images, Especially Photographs
### Naming Convention
lowercase, underscore for separation, hyphens-for-group
`Folder/[file-name]_[width in pixels].[ext]`
example: **characters/med/joe_300.png**
Folders: `branding`, `characters`, `portfolio-items`, `misc`
sized folders: `sm`,`med`,`lg`,`hero`
### File Sizes
**<500KB** is Ideal
no more than **3MB**
_file too big?_ refer to the [Image-Optimization](#Image-Optimization) section
### File Dimensions
image widths:
Thumbnail: **150px**
Medium: **300px**
Large: **1024px**
Full page: **1920px**
_Ask Andre if this is needed first_
### Image Optimization
Be sure to use '**lossless**' compression methods if you want to avoid distortion. Not required but would save us a ton of time and would be greatly appreciated.
It is highly recommended to use this in your own personal workflows for digital/web/social media content as it reduces the file sizes with no noticeable difference.
* On Mac Use [Imageoptim](https://imageoptim.com/mac) it outputs lossless by default.
* [alternatives](https://imageoptim.com/versions)
|
793c140c0e0333b4fe65b319de244fe6794c7343
|
[
"Markdown"
] | 2 |
Markdown
|
AndreBClark/WebStudentResources
|
d71373d9e0070e2926c3f21ef658aa090e159e1c
|
8435d0bf47de9f7b976c5178dbf2f9804426674b
|
refs/heads/master
|
<file_sep>PORTNAME= WebCalendar
DISTVERSIONPREFIX= v
DISTVERSION= 1.9.1-40
DISTVERSIONSUFFIX= -g6183409f
CATEGORIES= www
PKGNAMESUFFIX= ${PHP_PKGNAMESUFFIX}
DISTNAME= webcalendar-${DISTVERSIONPREFIX}${DISTVERSION}${DISTVERSIONSUFFIX}
MAINTAINER= <EMAIL>
COMMENT= Web-based calendar application
WWW= http://www.k5n.us/webcalendar.php
LICENSE= GPLv2
USES= cpe php:web,flavors
USE_GITHUB= yes
GH_ACCOUNT= craigk5n
GH_PROJECT= webcalendar
PORTSCOUT= limit:^1\.2\. skipb:1
USE_PHP= pcre session
NO_BUILD= yes
NO_ARCH= yes
CPE_VENDOR= craig_knudsen
WWWDIR= ${PREFIX}/www/${PORTNAME:tl}
DOCSDIR= ${PREFIX}/share/doc/${PORTNAME:tl}
WITH_PHP_CGI?= /cgi-bin/php
SUB_LIST+= PHPCGI=${WITH_PHP_CGI}
PLIST_SUB+= WWWOWN=${WWWOWN} WWWGRP=${WWWGRP}
PORTDOCS= WebCalendar-SysAdmin.html newwin.gif
OPTIONS_DEFINE= APACHE LDAP GRADIENTBG REMINDERS PALM DOCS EXAMPLES
OPTIONS_DEFAULT= MYSQL REMINDERS
OPTIONS_MULTI= DB
OPTIONS_MULTI_DB= MYSQL PGSQL SQLITE MSSQL DBASE ODBC ORACLE
OPTIONS_SUB= yes
GRADIENTBG_DESC= Gradient background image support
REMINDERS_DESC= Email reminder support
PALM_DESC= Palm export support
DBASE_DESC= Dbase support
APACHE_USE= APACHE_RUN=24+
DBASE_USE= PHP=dbase
GRADIENTBG_USE= PHP=gd
LDAP_USE= PHP=ldap
MSSQL_USE= PHP=mssql
MYSQL_USE= PHP=mysqli
ODBC_USE= PHP=odbc
ORACLE_USE= PHP=oracle
PALM_RUN_DEPENDS= pilot-xfer:${PORTSDIR}/palm/pilot-link
PGSQL_USE= PHP=pgsql
SQLITE_USE= PHP=sqlite3
REMINDERS_USES= php:cli
.include <bsd.port.pre.mk>
.if ${PORT_OPTIONS:MAPACHE}
PLIST_SUB+= CONFDIR=${CONFDIR_REL}
CONFDIR= ${PREFIX}/${CONFDIR_REL}
CONFDIR_REL= ${APACHEETCDIR}/Includes
SUB_FILES= pkg-message
.endif
SUB_FILES+= webcalendar-cgi.conf webcalendar.conf
.if ${PHP_SAPI:Mcgi} == "cgi" && ${PHP_SAPI:Mmod} == ""
CGI_EXT= -cgi
.else
CGI_EXT=
.endif
CONF= webcalendar${CGI_EXT}.conf
PLIST_SUB+= CONFFILE=${CONF}
.if ${PORT_OPTIONS:MDOCS}
SUB_LIST+= HASHMARK=
.else
SUB_LIST+= HASHMARK=\#
.endif
post-extract:
@${RM} -rf ${WRKSRC}/.github ${WRKSRC}/docker
do-install:
@${MKDIR} ${STAGEDIR}${WWWDIR}
(cd ${WRKSRC} && ${COPYTREE_SHARE} . ${STAGEDIR}${WWWDIR})
post-install:
@${MKDIR} ${STAGEDIR}${EXAMPLESDIR}
${INSTALL_DATA} ${WRKDIR}/${CONF} ${STAGEDIR}${EXAMPLESDIR}
@${MKDIR} ${STAGEDIR}${DOCSDIR}
(cd ${WRKSRC}/docs && ${INSTALL_DATA} ${PORTDOCS} ${STAGEDIR}${DOCSDIR})
.include <bsd.port.post.mk>
<file_sep># FreeBSD port for WebCalendar
This repository contains a port skeleton for the PHP WebCalendar application. It's based on the origional PHP 5.x
port [www/webcalendar](https://www.freshports.org/www/webcalendar)
## Using with Portshaker
Create a file `/usr/local/etc/portshaker.d/webcalendar` with the following contents.
```
#!/bin/sh
. /usr/local/share/portshaker/portshaker.subr
method="git"
if [ "$1" != '--' ]; then
err 1 "Extra arguments"
fi
shift
git_clone_uri="https://github.com/tuaris/FreeBSD-WebCalendar.git"
git_branch="master"
sed -i '' '/webcalendar.*2016-01-25.*Has expired/d' ${poudriere_ports_mountpoint}/${default_poudriere_tree}/MOVED
run_portshaker_command $*
```
Then add **webcalendar** to your **_merge_from** line in `/usr/local/etc/portshaker.conf`. For example.
```
#---[ Base directory for mirrored Ports Trees ]---
mirror_base_dir="/var/cache/portshaker"
#---[ Directories where to merge ports ]---
ports_trees="default"
use_zfs="yes"
poudriere_dataset="poudriere/poudriere"
poudriere_ports_mountpoint="/usr/local/poudriere/ports"
default_poudriere_tree="default"
default_merge_from="ports webcalendar"
```
|
2d8c22109c62e795f238c2b4d324ad9f3fad1cca
|
[
"Makefile",
"Markdown"
] | 2 |
Makefile
|
tuaris/FreeBSD-WebCalendar
|
00b3bc75b67018c71a872b56314b6a3030ad8514
|
7bccfe2fb100d4fc045355bcb540bb84615f1296
|
refs/heads/master
|
<file_sep># good-shop
The Good Shop PhoneGap mobile Application
<file_sep>angular.module('starter.controllers', ['ngCordova'])
.controller('MagazineCtrl', function($scope, $state) {
console.log('MagazineCtrl');
})
.controller('CatalogCtrl', function($scope) {})
.controller('ScanCtrl', function($scope, $ionicModal/*, $cordovaBarcodeScanner */) {
$ionicModal.fromTemplateUrl('templates/modal-scan.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal
})
$scope.openModal = function() {
$scope.modal.show()
}
$scope.closeModal = function() {
$scope.modal.hide();
};
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
/*$scope.scanBarcode = function() {
$cordovaBarcodeScanner.scan().then(function(imageData) {
alert(imageData.text);
console.log("Barcode Format -> " + imageData.format);
console.log("Cancelled -> " + imageData.cancelled);
}, function(error) {
console.log("An error happened -> " + error);
});
};
*/
})
.controller('DealersCtrl', function($scope,$ionicLoading, $compile) {
console.log('DealersCtrl');
$scope.init = function() {
console.log('DealersCtrl >> initialize()');
var myLatlng = new google.maps.LatLng(43.07493,-89.381388);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
//Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Uluru (<NAME>)'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
$scope.map = map;
}
$scope.centerOnMe = function() {
if(!$scope.map) {
return;
}
$scope.loading = $ionicLoading.show({
content: 'Getting current location...',
showBackdrop: false
});
navigator.geolocation.getCurrentPosition(function(pos) {
$scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
$scope.loading.hide();
}, function(error) {
alert('Unable to get location: ' + error.message);
});
};
$scope.clickTest = function() {
alert('Example of infowindow with ng-click')
};
})
.controller('WalletCtrl', function($scope, $ionicModal) {
console.log('WalletCtrl');
$scope.contact = {
name: '<NAME>',
info: 'Tap anywhere on the card to open the modal'
}
$ionicModal.fromTemplateUrl('templates/modal-register.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal
})
$scope.openModal = function() {
$scope.modal.show()
}
$scope.closeModal = function() {
$scope.modal.hide();
};
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
});
|
3296e6dfa6ae55b3c0471e4c589c00768e13906b
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
pescarment/good-shop
|
7a1275bb4e7789544b695e44010c89c2cf8496bb
|
405a598e5bc7f7520f5a2d43166d8e48d8e3fbc6
|
refs/heads/main
|
<file_sep>const express = require('express')
const Bookmark = require('../models/bookmark')
const Tag = require('../models/tag')
const router = new express.Router()
//Creating tag
router.post('/tags', async (req, res) => {
const found=await Tag.findOne({title:req.body.title}).exec()
if((found!=null)&&(found.title===req.body.title))
return res.status(400).send({ error: 'same title exists' })
else{
const tag = new Tag(req.body)
try {
await tag.save()
res.status(201).send(tag)
} catch (e) {
res.status(400).send(e)
}
}
})
//Retrieve all tags
router.get('/tags', async (req, res) => {
try {
const tags = await Tag.find({})
res.send(tags)
} catch (e) {
res.status(500).send()
}
})
//Delete tag by id
router.delete('/tags/:id', async (req, res) => {
try {
const bookmark = await Bookmark.findByIdAndDelete(req.params.id)
if (!bookmark) {
res.status(404).send()
}
res.send(bookmark)
} catch (e) {
res.status(500).send()
}
})
module.exports = router
<file_sep>const mongoose = require('mongoose')
const Bookmark = mongoose.model('Bookmark', {
link:{
type:String,
required: true
},
title:{
type:String,
required: true
},
publisher:{
type:String,
required: true
},
createdAt: {
type:Number, default: new Date().getTime()
},
updatedAt:
{type:Number, default: new Date().getTime()
},
tags:[],
})
module.exports = Bookmark<file_sep>const express = require('express')
const bookmarkRouter = require('./routers/bookmark')
const tagRouter = require('./routers/tag')
const config = require('./db/mongoose')
const mongoose = require("mongoose");
mongoose.connect(config.database.url, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on("connected", () => {
console.log("connected to MongoDB Atlas database successfully...");
});
mongoose.connection.on("error", err => {
console.log("error: " + err);
});
const app = express()
const port = process.env.PORT || 3000
app.use(express.json())
app.use(bookmarkRouter)
app.use(tagRouter)
app.listen(port, () => {
console.log('Server is up on port ' + port)
})<file_sep>module.exports = {
database: {
url:
'paste database url string'
}
}
<file_sep>const mongoose = require('mongoose')
const Tag = mongoose.model('Tag', {
title:{
type:String,
required: true
},
createdAt: {type:Number, default: new Date().getTime()},
updatedAt: {type:Number, default: new Date().getTime()}
})
module.exports = Tag<file_sep> Backend API for a Bookmarking Application
Database used MongoDB
API Included:-
Creating Bookmarks
Creating Tags
Retrieving Bookmarks
Retrieving Tags
Deleting Bookmarks
Deleting Tags
Adding Tags to Bookmarks
Removing Tags to Bookmarks
Installation:-
Download node.js latest version
Should have mongodb atlas account(Create an account in mongodb and copy the url string)
On terminal
##npm install
##npm start
Creating Bookmarks:-http://localhost:3000/bookmarks (POST)
Creating tags:-http://localhost:3000/tags (POST)
Retrieving Bookmarks:-http://localhost:3000/bookmarks (GET)
Retrieving Tags:-http://localhost:3000/tags (GET)
Adding tag to bookmark:-http://localhost:3000/bookmarks/add/:id (PATCH)
Removing tag from bookmark:-http://localhost:3000/bookmarks/remove/:id (PATCH)
Delete Bookmarks:-http://localhost:3000/bookmarks/:id (DELETE)
Delete Tags:-http://localhost:3000/tags/:id (DELETE)
|
550212cb4ff84aadd1ef1081e55a12d9edc5210f
|
[
"Markdown",
"JavaScript"
] | 6 |
Markdown
|
ajmalmajeed97/Bookmarks
|
15b1641aa67c700c3ec2e7ee019ddc79b9194a6e
|
fd7f4f1fea1d893a17784fed892ae24415a3fd58
|
refs/heads/master
|
<repo_name>datawowio/posmoni-node<file_sep>/lib/posmoni.js
const Moderations = require('./resources/Moderations');
module.exports = function (config) {
return {
moderations: Moderations(config),
};
};
<file_sep>/README.md
# Posmoni Node.js Library
The Posmoni Node.js library provides convenient access to the Posmoni API from
applications written in server-side JavaScript.
## Installation
Install the package with:
```sh
npm install posmoni --save
# or
yarn add posmoni
```
## Usage
The package needs to be configured with your project's secret key, which is
available in the Posmoni Dashboard. Require it with the key's
value:
<!-- prettier-ignore -->
```js
const posmoni = require('posmoni')({
projectKey: 'project-key',
});
posmoni.moderations.create({
data: 'picture-url',
customId: 'id-1',
})
.then(customer => console.log(customer.id))
.catch(error => console.error(error));
```
Or using ES modules and `async`/`await`:
```js
const posmoni = require('posmoni')({
projectKey: 'project-key',
});
(async() => {
const response = await posmoni.moderations.get({
query: 'moderation-id'
});
console.log(response.data);
})();
```
## Examples
### Create a moderation task to Posmoni
Creating a moderation can be done by using `posmoni.moderations.create` which accepts an required `data` argument and some of optional aguments.
`data` could be text or image's url depends on your project's template.
#### params
| Field | Type | Required | Description |
| ------------- |:-------------:| :-----:| :-----|
| data | string | **Yes** | Image's url or text data |
| postback_url| string | No | URL for answer callback once task has been moderated |
| postback_method| string | No | Callback Configuration HTTP method (`GET`, `POST`, `PUT`, `PATCH`) |
| custom_id | string | No | Custom ID for retrieving moderation task |
| info | json | No | Additional info only for ID card check template |
```js
const posmoni = require('posmoni')({
projectKey: 'project-key',
});
posmoni.moderations
.create({
data: 'picture-url',
customID: 'custom-id'
})
.then((result) => console.log(result.data))
.catch((error) => console.log(error))
```
### List all moderations
After moderations are created, you can list them with `posmoni.moderations.get` and passing
a callback to it. The object returned from a list API will be a `list` object, which you
can access the raw data via `data` attribute:
```javascript
posmoni
.moderations
.get()
.then((result) => console.log(result.data))
.catch((error) => console.log(error))
```
We also support request with pagination. You can pass these arguments into the payload.
#### params
| Field | Type | Required | Description |
| ------------- |:-------------:| :-----:| :-----|
| sortBy | string | No | Specific moderation field for sorting (Default is `id`) |
| sortDirection| string| No | Sorting direction which could be `asc` or `desc` (Default is `desc`) |
| page| integer | No | The number of page (Default is `1`) |
| perPage | integer | No | The number of item per page (Default is `10`) |
### Retrieve a moderation
You can retrieve specific created moderation by using `posmoni.moderations.get` and passing a
customer ID to it, e.g.
```javascript
posmoni.moderations
.get({ query: 'custom-id-1'})
.then((result) => consle.log(result.data))
.catch((error) => console.log(error))
```
<file_sep>/tests/lib/resources/Moderations.test.js
const sinon = require('sinon');
const chai = require('chai');
const axios = require('axios');
const { getModeration, createModeration } = require('../../fixtures/moderations');
sinon.assert.expose(chai.assert, { prefix: '' });
const assert = chai.assert;
const PROJECT_KEY = { projectKey: 'project-key' }
const moderations = require('../../../lib/resources/Moderations')(PROJECT_KEY);
const options = {
data: 'https://assets-cdn.github.com/images/modules/open_graph/github-mark.png',
customId: '1',
query: 1,
};
describe('resources/Moderations', () => {
let sandbox;
beforeEach(() => {
sandbox = sinon.sandbox.create();
});
afterEach(() => {
sandbox.restore();
});
it('should get a moderation', async () => {
sandbox.stub(axios, 'request').resolves(Promise.resolve(getModeration));
const result = await moderations.get({ query } = options);
const parsed = JSON.parse(result);
assert.isObject(parsed.data.attributes);
assert.equal(parsed.meta.code, 200);
});
it('should create a moderation', async () => {
sandbox.stub(axios, 'request').resolves(Promise.resolve(createModeration));
const result = await moderations.create({ data, customId } = options);
const parsed = JSON.parse(result);
assert.isObject(parsed.data.attributes);
assert.equal(parsed.meta.code, 201);
});
});
|
2c0951df0142ef723059d66d8d71af62dbe10887
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
datawowio/posmoni-node
|
c9eed680d0af3db70704b8bd914c3457137b627d
|
a9a7b0e82700b30612328d1a31ad4bc63716435a
|
refs/heads/master
|
<file_sep>import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class SauseLabs {
// public static final String USERNAME = "ahameed";
// public static final String ACCESS_KEY = "<KEY>";
RemoteWebDriver driver;
public static final String USERNAME = "vvasu";
public static final String ACCESS_KEY = "45227988-98e3-4b63-92ed-28bb91835827";
public static final String URL = "https://" + USERNAME + ":" + ACCESS_KEY + "@ondemand.saucelabs.com:443/wd/hub";
@Test
public void browser() throws Exception {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("name", "Facebook_safari_Screenshot");
caps.setCapability("platform", "Windows 10");
caps.setCapability("browserName", "chrome");
caps.setCapability("version", "53.0");
caps.setCapability("build", "Facebook_SauceLabs");
driver = new RemoteWebDriver(new URL(URL), caps);
driver.get("https://www.facebook.com");
System.out.println("title of page is: " + driver.getTitle());
}
@AfterMethod
public void teardown(ITestResult result) throws Exception {
((JavascriptExecutor) driver). executeScript("sauce:job-result=" + (result.isSuccess() ? "passed":"failed"));
driver.quit();
}
}
|
912b1cc198a0786e64a369487de4311f46a82e23
|
[
"Java"
] | 1 |
Java
|
mahe12/IOSAutomation_basik
|
d4ae7984237b6ad9c08554614086e8a463d89361
|
3a0a5764be0f66f211f763d63b6eb76586d09419
|
refs/heads/master
|
<file_sep>const express = require("express");
const route = express.Router();
const User = require("../models/User");
route.post("/register",(req,res)=>{
var userid = req.body.userid;
var pwd = req.body.pwd;
var uname = req.body.uname;
const userObject= new User(userid,pwd,uname);
const userOperations = require("../db/usercrud");
userOperations.register(userObject,res);
});
route.post('/login',(req,res)=>{
var userid = req.body.userid;
var pwd = <PASSWORD>;
const userObject= new User(userid,pwd);
const userOperations = require("../db/usercrud");
userOperations.login(userObject,res);
});
module.exports = route;<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="CSS/welcome.css">
</head>
<body>
<h1>Welcome</h1>
<form class="form-wrapper">
<input type="text" id="search" placeholder="Search for..." required>
<input type="submit" value="go" id="submit">
</form>
</body>
</html><file_sep>const express = require("express");
const bodyParser = require("body-parser");
console.log("type express",typeof express);
const app = express();
app.set('view engine','ejs');
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: false }));
const userroute = require("./routes/userroutes");
app.use("/",userroute);
//app.use(bodyParser.json());
//gmail
const passportGoogleSt = require("./passportgoogle"); // Setup
const passport = require("passport");
app.use(passport.initialize());
app.get('/google',passport.authenticate('google',{
scope : ['profile']
}));
app.get('/google/callback',passport.authenticate('google',
{session: false}),(req,res)=>{
res.render('welcome');
});
//facebook
const passportFacebookSt = require('./passportfacebook');
app.get('/facebook',passport.authenticate('facebook'));
app.get('/callback',passport.authenticate('facebook',
{session: false}),(req,res)=>{
res.render('welcome');
});
var server = app.listen(process.env.port|1234,()=>{
console.log("server start", server.address().port);
});<file_sep>class User{
constructor(userid, pwd, uname){
this.userid = userid;
this.pwd = pwd;
this.uname = uname;
}
}
module.exports = User;<file_sep>const dbConfig = {
"url":"mongodb://localhost:27017/loginregistration"
}
module.exports = dbConfig;
|
765e712e5158759b854d843d8e5c9e81fa656190
|
[
"EJS",
"JavaScript"
] | 5 |
EJS
|
Sharmaash/login-APP
|
2d66f7f0b4dc0d61af8d524348afcc7b7a09d379
|
257527922a08dfc749e09fd2be6e7e476aa9b145
|
refs/heads/main
|
<repo_name>DLLoadandPerformanceTeam/DLLoadandPerformanceTeam<file_sep>/README.md
This repo is created for HRBlock performance engineering team. For evaluation purpose.
|
5e12e394f8c57c4746534a8160f142c0ce961e72
|
[
"Markdown"
] | 1 |
Markdown
|
DLLoadandPerformanceTeam/DLLoadandPerformanceTeam
|
71a2a8296bad27be4ad3e25b719557b9ec94ce5a
|
095fd1a12de4ce04a904d106a02766f20a52fd3f
|
refs/heads/master
|
<file_sep># growassistant
Grass - Your own Hass.io grow assistant
One day i was tired of buying fresh herbs, but unluckily i live in a apartment, where there is not direct sunlight most of the year.
Also i am a lazy guy and i wanted some kind of supervisor of the plant health and status, to track the plants, and automatize as much as possible, while its easy to setup
So i decided to create a tabletop planter which could give enough light to my plants, and also upload some stats and and images to a homeassistant server.
## Main features of first version:
- Smart home integrated (Homeassistant), easy OTA config with ESPHome, Automation throught nodeRED.
- Custom PCB with only thru hole components (easy solder).
- Based on ESP32cam so plenty of projects documentation available.
- Fully 3d printed frame.
- High efficiency and dimmable LED Driver and strips.
- Different light spectrum available.
- Adjustable Height.
- OLED realtime status show.
- Easily hackable (I2C Pins exposed).
### for more info about the project visit my [blog](https://nkmakes.github.io/projects/grow-assistant/)
|
2641cf503070e5e3d20be196b2e7be764adbdf8b
|
[
"Markdown"
] | 1 |
Markdown
|
nkmakes/growassistant
|
0538204e3bef2f645caa2158b7e366f14afcf73f
|
789b526a2f0d0eea47d70424ec98cd717221729c
|
refs/heads/master
|
<repo_name>jaivonmassena/Sprint-Challenge---React<file_sep>/starwars/src/App.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import './App.css';
import PeopleList from './peoplelist.js'
import { Container, Row, Col, Jumbotron, Button } from 'reactstrap';
import Tron from './jumbotron.js'
const styles = {
backgroundColor: ' white',
}
class App extends Component {
constructor() {
super();
this.state = {
starwarsChars: []
};
}
componentDidMount() {
// feel free to research what this code is doing.
// At a high level we are calling an API to fetch some starwars data from the open web.
// We then take that data and resolve it our state.
fetch('https://swapi.co/api/people')
.then(res => {
return res.json();
})
.then(data => {
this.setState({ starwarsChars: data.results });
})
}
render() {
return (
<Container className="App" style={styles}>
<h1 className="Header">React Wars</h1>
<Tron />
<PeopleList {...this.state} />
</Container>
);
}
}
export default App;
<file_sep>/starwars/src/peoplelist.js
import React from 'react';
import { Card, CardImg, CardText, CardBody,
CardTitle, CardSubtitle, Button } from 'reactstrap';
import { Container, Row, Col } from 'reactstrap';
// for(let i = 0; i< props starwars.length; i++)
const PeopleList = props =>{
return(
<Row>
{props.starwarsChars.map((person, i) =>
<Col xs="3">
<Card key = {i + 1}>
<CardImg top width="100%" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=318%C3%97180&w=318&h=180" alt="Card image cap" />
<CardBody>
<CardTitle>{person.name}</CardTitle>
<CardSubtitle>Card subtitle</CardSubtitle>
<CardText>'Some quick example text to build on the card title and make up the bulk of the cards content'.</CardText>
<Button>Button</Button>
</CardBody>
</Card>
</Col>
)
}</Row>)
}
// class PeopleList extends Component {
// constructor(props){
// super(props);
// this.state ={
// people: props.people
// };
// };
// render(){
// return( <div></div>);
// }
// }
export default PeopleList;
|
5cc49d04cca92f5a502d4c4f0ba6aebc203f0c35
|
[
"JavaScript"
] | 2 |
JavaScript
|
jaivonmassena/Sprint-Challenge---React
|
d5174eb09e2535b5ae4dd6514dc485c6737d7681
|
55239fd92fd4f4661544679e92dc851d067fc33e
|
refs/heads/master
|
<repo_name>phleagol/fvwm_2016<file_sep>/.fvwm/lib/UpdateSystemMonitor
#!/usr/bin/perl
use strict ;
use warnings ;
use v5.20 ;
use local::lib ;
use lib `fvwm-perllib dir` ;
use FVWM::Module ;
use POSIX ();
use Sys::Statistics::Linux ;
use Graphics::GnuplotIF ;
use Image::Magick ;
use Data::Dumper ;
#use Data::Dump qw( dump ) ;
## libsys-statistics-linux-perl libgraphics-gnuplotif-perl
## Extra delay at end of each loop.
my $loop_delay = 2 ;
## Step delay between consecutive image update cmnds.
my $step_delay = int($loop_delay*1000/6) ;
## Max data points for the plots.
my $plot_max = 65 ;
## Background color for the plots
my $back = '#171717' ;
## Width/height for the plots
my $width = 139 ;
my $height = 50 ;
## Destination folder for plots
my $dir = "/tmp/fvwm" ;
## Name of fvwmbuttons module that displays plots.
my $fbmodname = "SystemMonitor" ;
## Five hashes to define five gnuplots.
my $cpu = {
plot => [], colorset => 201, id => "cpu",
fore => '#107CBA', shade => '#2C2F33',
outfile => "$dir/cpu.png",
} ;
my $mem = {
plot => [], colorset => 202, id => "mem",
fore => '#8A11AD', shade => '#262226',
outfile => "$dir/mem.png",
} ;
my $disk = {
plot => [], colorset => 203, id => "disk",
fore => '#C99465', shade => '#262321',
outfile => "$dir/disk.png",
} ;
my $iow = {
plot => [], colorset => 204, id => "iow",
fore => '#4CA50B', shade => '#232621',
outfile => "$dir/iow.png",
} ;
my $net = {
plot => [], colorset => 205, id => "net",
fore => '#C9C965', shade => '#262621',
outfile => "$dir/net.png",
} ;
## The plots all start off with zeroes.
foreach my $x ($cpu, $iow, $mem, $disk, $net) {
@{$x->{plot}} = (0) x $plot_max
}
## Start the FVWM module.
my $modname = "UpdateSystemMonitor" ;
my $module = new FVWM::Module(
Name => $modname,
Debug => 0,
) ;
## Start the system stats module.
my $lxs = Sys::Statistics::Linux->new(
cpustats => 1,
memstats => 1,
diskstats => 1,
netstats => 1,
) ;
$lxs->init ;
sleep 1 ;
my $stat = $lxs->get ;
## Get the colorset hash, and obtain the colors for each gnuplot.
my $cs_tracker = $module->track("Colorsets") ;
my $cs_hash = $cs_tracker->data ;
$cs_tracker->stop ;
foreach my $x ($cpu, $iow, $mem, $disk, $net) {
my $cs = $x->{colorset} ;
my $fore = $cs_hash->{$cs}->{fg} ;
my $shade = $cs_hash->{$cs}->{shadow} ;
$x->{fore} = sprintf('#%x',$fore) if $fore ;
$x->{shade} = sprintf('#%x',$shade) if $shade ;
} ;
## Calc the memory total in GB. This remains constant.
my $memtotalGB = nearest(.1, $stat->{memstats}->{memtotal}/1048576) ;
#### MAIN LOOP
while (1) {
## Update system stats and push new data values.
$stat = $lxs->get ;
update_cpustats() ;
update_memstats() ;
update_diskstats() ;
update_netstats() ;
my $delay = 0 ;
foreach my $x ($cpu, $iow, $mem, $disk, $net) {
## Plot the data
simpleplot($x) ;
## Update the image in FvwmButtons.
my $cmd = $delay ? "Schedule $delay " : "" ;
$cmd .= "SendToModule $fbmodname ChangeButton " ;
$cmd .= "$x->{id} Icon $x->{outfile} " ;
$module->send($cmd) ;
$delay += $step_delay ;
} ;
sleep $loop_delay ;
}
#### SUBROUTINES
## Push current cpu usage + iowait to $cpu and $iow hashes.
sub update_cpustats {
my $iowait = nearest(1, $stat->{cpustats}->{cpu}->{iowait}) ;
my $total = nearest(.1, $stat->{cpustats}->{cpu}->{total}) ;
shift @{$cpu->{plot}} ;
push @{$cpu->{plot}}, $total - $iowait ;
shift @{$iow->{plot}} ;
push @{$iow->{plot}}, $iowait ;
}
## Push current memory usage to $mem hash
sub update_memstats {
my $memtotal = $stat->{memstats}->{memtotal} ;
my $himem = $stat->{memstats}->{memused} ;
my $cach = $stat->{memstats}->{cached} ;
my $buff = $stat->{memstats}->{buffers} ;
my $lomem = ($himem - $cach - $buff) * 100/$memtotal ;
shift @{$mem->{plot}} ;
push @{$mem->{plot}}, nearest(.1, $lomem) ;
}
## Push current disk stats to $disk hash (range upto 12MB/s)
sub update_diskstats {
my $ttbyt = $stat->{diskstats}->{sda}->{ttbyt} ;
my $rdbyt = $stat->{diskstats}->{sda}->{rdbyt} ;
my $wrtbyt = $stat->{diskstats}->{sda}->{wrtbyt} ;
shift @{$disk->{plot}} ;
push @{$disk->{plot}}, ceiling($ttbyt, 12582912) ;
}
## Push current network stats to $net hash (range upto 6MB/s)
sub update_netstats {
my $netbyts = my $rxbyts = my $txbyts = 0 ;
foreach my $netdev (keys %{$stat->{netstats}}) {
next if $netdev eq "lo" ;
$rxbyts += $stat->{netstats}->{$netdev}->{rxbyt} ;
$txbyts += $stat->{netstats}->{$netdev}->{txbyt} ;
$netbyts += $rxbyts + $txbyts ;
} ;
shift @{$net->{plot}} ;
push @{$net->{plot}}, ceiling($netbyts, 6291456) ;
}
## Plot the data via gnuplot.
sub simpleplot {
## The hashref of the current plot.
my $ref = shift ;
## Color for the plot and borders.
my $fore = $ref->{fore} ;
## Fill color for under the plot
my $shade = $ref->{shade} ;
## Filename to write image to.
my $outfile = $ref->{outfile} ;
my $plot = Graphics::GnuplotIF->new ;
$plot->gnuplot_set_yrange(0, 101) ;
$plot->gnuplot_cmd(
"set terminal png size $width, " .
"$height background \"$back\" ",
"set output \"$outfile\"",
"unset xtics ; unset ytics ; unset key",
"set border 31 lc rgb \"$fore\" lw 1",
"set lmargin at screen 0.01",
"set rmargin at screen 0.99",
"set tmargin at screen 0.99",
"set bmargin at screen 0.01",
) ;
my @x1 = (1..$plot_max) ;
my %y1 = (
'y_values' => $ref->{plot},
'style_spec' => "filledcurves x1 lc rgb \"$shade\" "
) ;
my %y2 = (
'y_values' => $ref->{plot},
'style_spec' => "lines lw 1 lc rgb \"$fore\" "
) ;
$plot->gnuplot_plot_xy_style(\@x1, \%y1, \%y2) ;
}
#### Mathematical functions
## Pasted and modified from Math::Round
sub nearest {
my $targ = abs(shift);
my $half = 0.50000000000008 ;
my @res = map {
if ($_ >= 0) { $targ * int(($_ + $half * $targ) / $targ); }
else { $targ * POSIX::ceil(($_ - $half * $targ) / $targ); }
} @_ ;
return (wantarray) ? @res : $res[0] ;
}
## Calc and return the list avg.
sub average {
my $tot = 0 ;
my $cnt = scalar @_ ;
foreach (@_) { $tot += $_ }
return nearest(.1, $tot/$cnt ) ;
}
## Sets a max threshold, then normalizes and returns as a percentage.
sub ceiling {
my ($num, $max) = @_ ;
$num = $num > $max ? $max : $num ;
return nearest(.1, $num*100/$max) ;
}
<file_sep>/.fvwm/lib/panelbar/UpdateCalendarPanel
#!/usr/bin/perl
## Useful webpages :-
## http://www.imagemagick.org/script/command-line-processing.php
## http://www.imagemagick.org/script/perl-magick.php
## http://www.imagemagick.org/Usage/draw/#strokewidth
use strict ;
use warnings ;
use utf8 ;
use v5.22 ;
use lib `fvwm-perllib dir` ;
use FVWM::Module ;
use Image::Magick ; ## libimage-magick-perl
use Calendar::Simple ; ## libcalendar-simple-perl
use Astro::MoonPhase ;; ## via CPAN
use Path::Tiny ; ## libpath-tiny-perl
#use Data::Dump qw( dump ) ;
## Name of the FvwmButtons calendar panel.
my $panelmodname = "CalendarPanel" ;
## Image compression setting.
my $quality = 100 ;
## Output image filename.
my $outfile = path("$ENV{FVWM_USERDIR}/images/panel-calendar.png") ;
## Large and small font descriptors.
my $fontdir = "/usr/share/fonts/X11/misc" ;
my $fontsmall = {
file => "$fontdir/ter-u16b_iso-8859-1.pcf.gz",
width => 8, height => 16,
} ;
my $fontlarge = {
file => "$fontdir/ter-u18b_iso-8859-1.pcf.gz",
width => 10, height => 19,
} ;
## Moon-phase icons
my $icondir = "$ENV{FVWM_USERDIR}/images/panelbar/calendar" ;
my @moonicons = qw( new-moon.png first-quarter-moon.png
full-moon.png last-quarter-moon.png ) ;
## Title labels
my @months = ("J A N U A R Y", "F E B R U A R Y", "M A R C H",
"A P R I L", "<NAME>", "<NAME>", "<NAME>", "<NAME>",
"S E P T E M B E R", "O C T O B E R", "N O V E M B E R",
"D E C E M B E R" ) ;
#### Calendar dimensions
## Height of header.
my $header_h = 30 ;
## Width/height of cells.
my $cell_w = 30 ;
my $cell_h = 30 ;
## Start the FVWM module.
my $modname = "UpdateCalendarPanel" ;
my $module = new FVWM::Module(
Name => $modname,
Debug => 0,
) ;
## Get colorset data from FVWM.
my $cs_tracker = $module->track("Colorsets") ;
my $cs_hash = $cs_tracker->data ;
$cs_tracker->stop ;
## Calendar colors
my $title_fg = get_color(310,"fg") ;
my $header_fg = get_color(311,"fg") ;
my $weekday_fg = get_color(312,"fg") ;
my $currentday_fg = get_color(313,"fg") ;
my $dim_text_color = get_color(314,"fg") ;
my $weekend_bg = get_color(315,"bg") ;
my $weekend_fg = get_color(315,"fg") ;
my $grid_color = get_color(316,"fg") ;
#### MAIN
## Create a blank canvas.
my $image = Image::Magick->new ;
$image->Set(size => "245x260") ;
$image->ReadImage("canvas:gray9") ;
## Annotate the main title
my $m = $months[(localtime)[4]] ;
$image = center_justified(116, 25, $title_fg, $fontlarge, $m, $image) ;
## Draw the calendar grid and numbers
my $calendar = get_calendar() ;
$image->Composite(image => $calendar, x => 16, y => 40) ;
## Draw the moon phases legend.
my $moon = get_moonphases() ;
$image->Composite(image => $moon, x => 26, y => 230) ;
## Save the finished calendar.
save_image($image, $outfile) ;
## Update image in the FvwmButtons module.
my $cmd = "SendToModule $panelmodname ChangeButton cicon Icon " ;
$cmd .= $outfile->basename ;
$module->send($cmd) ;
exit ;
#### SUBROUTINES
sub get_color {
my $cs_num = shift ;
my $opt = shift ;
my $color = $cs_hash->{$cs_num}->{$opt} ;
return sprintf('#%x',$color) ;
}
## Draws a calendar, and returns a perlmagick object.
sub get_calendar {
## Calendar width/height
my $cal_w = $cell_w * 7 ;
my $cal_h = $cell_h * 5 + $header_h ;
## Canvas width, height, geometry, color
my $canvas_w = $cal_w + 1 ;
my $canvas_h = $cal_h + 1 ;
my $canvas_geometry = "${canvas_w}x$canvas_h" ;
my $canvas_bg = "gray9" ;
## Create blank calendar canvas.
my $calendar = Image::Magick->new ;
$calendar->Set(size => $canvas_geometry) ;
$calendar->ReadImage("canvas:$canvas_bg") ;
## Annotate labels for the header.
my @days = qw( S M T W T F S ) ;
for (my $idx = 0, my $xx = 19, my $yy = 22 ; $idx <= $#days ; $idx++, $xx += $cell_w) {
$calendar = right_justified(
$xx, $yy, $header_fg, $fontlarge, $days[$idx], $calendar
) ;
}
## Obtain calendar layouts for the current month, and for
## the weeks that immediately precede and follow it.
my $currentday = (localtime)[3] ;
my @thismonth = calendar() ;
my @previousweek = get_previous_week() ;
my @followingweek = get_following_week() ;
## Offsets to position text within the cell.
my $offsetx = 24 ;
my $offsety = 21 ;
## Iterate through the weeks and days of the month.
for (my $yy = $header_h, my $wknum = 0 ; $wknum <= $#thismonth ; $wknum++, $yy += $cell_h ) {
for (my $xx = 0, my $daynum = 0 ; $daynum <= 7 ; $daynum++, $xx += $cell_w ) {
## The actual day of this month for this calendar cell.
my $today = $thismonth[$wknum]->[$daynum] ;
## If this day is undefined, then...
if (not defined $today) {
## get the day number be for the immediately preceding/following week.
$today = $previousweek[$daynum] if $wknum == 0 ;
$today = $followingweek[$daynum] if $wknum == $#thismonth ;
if (defined $today ) {
$calendar = right_justified(
$xx+$offsetx, $yy+$offsety, $dim_text_color, $fontsmall, $today, $calendar
) ;
}
## elsewise,today is already properly defined, so...
} else {
## Set default color for normal week days.
my $color = $weekday_fg ;
## Weekend days or the current day may look different.
if ($daynum =~ /0|6/ or $today == $currentday) {
$color = $weekend_fg ;
$color = $currentday_fg if $today == $currentday ;
my $x2 = $xx + $cell_w ;
my $y2 = $yy + $cell_h ;
$calendar->Draw(
primitive => "rectangle", fill => $weekend_bg, points => "$xx,$yy $x2,$y2",
) ;
}
## Place todays number within the cell.
$calendar = right_justified(
$xx+$offsetx, $yy+$offsety, $color, $fontsmall, $today, $calendar
) ;
}
}
}
## Draw vertical lines.
for (my $x = 0 ; $x <= $cal_w ; $x += $cell_w) {
$calendar = draw_line($calendar, $grid_color,"$x,$header_h $x,$cal_h") ;
}
## Draw horizontal lines.
for (my $y = $header_h ; $y <= $cal_h ; $y += $cell_h) {
$calendar = draw_line($calendar, $grid_color, "0,$y $cal_w,$y") ;
}
## Draw line along top border
$calendar = draw_line($calendar, $grid_color, "0,0 $cal_w,0") ;
## Draw lines along sides of the header.
$calendar = draw_line($calendar, $grid_color, "0,0 0,$header_h") ;
$calendar = draw_line($calendar, $grid_color, "$cal_w,0 $cal_w,$header_h") ;
return $calendar ;
}
## Calculate the moon-phases, and draw it as a legend for below the
## calendar. Returns a perlmagick object.
sub get_moonphases {
## Calculate moon phases for 30 days before/after today.
my $start = time() - 86400 * 30 ;
my $stop = time() + 86400 * 30 ;
(my $phase, my @times) = phaselist($start, $stop) ;
my @moonphases = () ;
my $month = (localtime())[4] ;
## Discard moon-phases not for the current month.
foreach my $time (@times) {
my $d = (localtime($time))[3] ;
my $m = (localtime($time))[4] ;
if ($m == $month) {
my $z = { phase => $phase, day => $d } ;
push @moonphases, $z if $#moonphases < 3 ;
$phase = ++$phase%4 ;
}
}
## Create blank canvas. Calculate width to be a snug fit.
my $moon = Image::Magick->new ;
my $ww = scalar(@moonphases)*55 - 10 ;
$moon->Set(size => "${ww}x20") ;
$moon->ReadImage("canvas:gray9") ;
## Draw an image strip to display the @moonphases info.
my $xx = 0 ;
my $num = 0 ;
foreach my $mphase (@moonphases) {
my $day = $mphase->{day} ;
my $icon = load_image("$icondir/$moonicons[$mphase->{phase}]") ;
$moon->Composite(image => $icon, x => $xx, y => 0) ;
$xx += 20 ;
$moon = left_justified(
$xx, 13, "gray60", $fontsmall, ":$day", $moon
) ;
$xx += 30 ;
last if $num++ > 3 ;
}
return $moon ;
}
sub draw_line {
my $img = shift ;
my $color = shift ;
my $points = shift ;
$img->Draw(
primitive => "line", fill => $color,
points => $points, antialias => "true",
) ;
return $img ;
}
sub get_previous_week {
my $m = (localtime)[4] ;
my $y = (localtime)[5] + 1900 ;
if ($m == 0) { $m = 12 ; $y-- } ;
my @last = calendar($m, $y) ;
my @prevweek = @{ $last[$#last] } ;
return @prevweek ;
}
sub get_following_week {
my $m = (localtime)[4] + 2 ;
my $y = (localtime)[5] + 1900 ;
if ($m == 13) { $m = 1 ; $y++ } ;
my @nextmonth = calendar($m, $y) ;
my @followingweek = @{ $nextmonth[0] } ;
return @followingweek ;
}
sub right_justified {
my $xpos = shift ;
my $ypos = shift ;
my $color = shift ;
my $font = shift ;
my $text = shift ;
my $img = shift ;
$xpos -= $font->{width} * length($text) ;
return 0 if $img->Annotate(
x => $xpos,
y => $ypos,
gravity => "NorthWest",
font => $font->{file},
fill => $color,
text => $text,
) ;
return $img ;
}
sub left_justified {
my $xpos = shift ;
my $ypos = shift ;
my $color = shift ;
my $font = shift ;
my $text = shift ;
my $img = shift ;
return 0 if $img->Annotate(
x => $xpos,
y => $ypos,
gravity => "NorthWest",
font => $font->{file},
fill => $color,
text => $text,
) ;
return $img ;
}
sub center_justified {
my $xpos = shift ;
my $ypos = shift ;
my $color = shift ;
my $font = shift ;
my $text = shift ;
my $img = shift ;
$xpos -= $font->{width} * int(length($text)/2) ;
return 0 if $img->Annotate(
x => $xpos,
y => $ypos,
gravity => "NorthWest",
font => $font->{file},
fill => $color,
text => $text,
) ;
return $img ;
}
sub load_image {
my $err = 1 ;
my $image = Image::Magick->New() ;
my $imgfile = shift ;
open(IMAGE, $imgfile) or return 0 ;
$err = $image->Read(file=>\*IMAGE);
close(IMAGE);
if ($err) { return 0 } else { return $image } ;
}
sub save_image {
my $image = shift ;
my $outfile = shift ;
open(IMAGE, ">$outfile") ;
return 0 if $image->Write(
file => \*IMAGE,
filename => $outfile,
quality => $quality,
) ;
return 1 ;
}
<file_sep>/.fvwm/lib/menus/ClipMenu
#!/usr/bin/perl
## http://www.perl.com/doc/FMTEYEWTK/switch_statements VERYGOOD
## http://perldoc.perl.org/5.8.8/Switch.html
## the "given/when" builtins are much preferred.
##
## https://transfixedbutnotdead.com/2010/08/30/givenwhen-the-perl-switch-statement/
## man perlsyn "Switch Statements"
## Crypt::CBC -
## Digest::Perl::MD5s - libdigest-perl-md5-perl
## A clipboard manager implemented in fvwmperl. Monitors the clipboard
## selection, not the primary. Triggers fvwm submenus for different
## datatypes. Entries are stored as plaintext - not secure !!!
##
## ualarm() is used to periodically poll the clipboard with cb_sync().
## At other times, fvwm events are listened for and acted upon.
##
## libpath-tiny-perl libtext-unidecode-perl libdata-dump-perl
use utf8 ;
use strict ;
use warnings ;
use v5.18 ;
use lib `fvwm-perllib dir`;
use FVWM::Module;
use Path::Tiny ;
use Data::Dump qw( dump ) ;
use Time::HiRes qw( ualarm ) ;
use Text::Unidecode ;
use IPC::Run qw( run timeout ) ;
use Try::Tiny ;
## Array of hashes to store the xsel clip records
my @records = () ;
## maximum number of records in @records - default.
my $max_records = 20 ;
## maximum width for any record label - default.
my $max_chars = 50 ;
## Title name for menu - default
my $menu_title = "ClipMenu" ;
## Name for the clipmenu
my $menu_name = "ClipMenu" ;
## Delay in usecs between xsel polls - default.
my $pollinterval = 1000000 ;
## Timeout period for all xsel commands in seconds.
my $xseltimeout = 2 ;
## md5sum of the last xsel clip added to @record
my $md5last = "" ;
## Setup folder to store entries in.
my $dir = path("$ENV{FVWM_CLIPMENU}") ;
system("rm $dir/* 2>/dev/null") ;
system("mkdir -p $dir 2>/dev/null") ;
## Enable/disable logging
#my $logfile = path("$ENV{FVWM_USERDIR}/log/fvwmclip.log") ;
my $logfile = path("/tmp/clipmenu.log") ;
unlink $logfile ;
#my $logger = "yes" ;
my $logger = "" ;
local $SIG{__WARN__} = sub {
my $message = shift;
logger("warning : $message");
};
## Icons from the fvwm ImagePath for the clipmenu.
my %icons = (
youtube => "cb_youtube-type.png",
torrent => "cb_torrent-type.png",
magnet => "cb_magnet-type.png",
folder => "cb_folder-type.png",
url => "cb_url-type.png",
html => "cb_html-type.png",
video => "cb_video-type.png",
audio => "cb_audio-type.png",
image => "cb_image-type.png",
pdf => "cb_pdf-type.png",
none => "cb_null.png",
clear_history => "cb_clear-history.png",
) ;
## Fvwm cmnds to be triggered by specific datatypes.
my %submenus = () ;
#my %submenus = (
# youtube => "UrlMenu",
# url => "UrlMenu",
# html => "UrlMenu",
# video => "VideoMenu",
# magnet => "AddTorrent",
# torrent => "AddTorrent",
# ) ;
my $module = new FVWM::Module(
Name => 'ClipMenu',
Mask => M_CONFIG_INFO | M_END_CONFIG_INFO | M_STRING,
Debug => 0,
);
my $modname = $module->name ;
## After the config phase, the eventloop listens for SendToModule cmnds.
$module->addHandler(M_CONFIG_INFO, \&read_config);
$module->addHandler(M_END_CONFIG_INFO, sub {
$module->show_message("[$modname] read config finished]") ;
$module->addHandler(M_STRING, \&process_cmd);
clear_history() ;
sleep 1 ;
cb_sync() ;
}) ;
## Using ualarm to trigger a clipboard sync every $pollinterval usecs.
$SIG{ALRM} = \&cb_sync ;
## Using an infinite event_loop to monitor FVWM events.
$module->show_message("starting ".$module->name);
$module->send("Send_ConfigInfo");
$module->event_loop ;
#### SUBROUTINES
## Next two subroutines read and process module config during startup.
##
sub read_config {
my ($module, $event) = @_ ;
return unless $event->_text =~ /^\*$modname(.*)$/;
process_config($1);
}
sub process_config {
my ($s) = @_ ;
my ($option, $args)= $s =~/\s*(\w+)\s*(.*)/;
my %opts = (
Title => sub { $menu_title = $args },
Height => sub { $max_records = $args },
Width => sub { $max_chars = $args },
Period => sub { $pollinterval = $args },
Youtube => sub { $submenus{youtube} = $args },
Torrent => sub { $submenus{torrent} = $args },
Magnet => sub { $submenus{magnet} = $args },
Url => sub { $submenus{url} = $args },
Html => sub { $submenus{html} = $args },
Video => sub { $submenus{video} = $args },
Audio => sub { $submenus{audio} = $args },
Image => sub { $submenus{image} = $args },
Pdf => sub { $submenus{pdf} = $args },
) ;
if (defined $opts{$option}) {
$opts{$option}() ;
} else {
$module->showMessage("Unknown option \"$option\"");
}
}
## Read and act upon SendToModule cmnds sent to this module.
sub process_cmd {
my ($module, $event) = @_ ;
my ($s) = $event->_text ;
my ($command, $arg) = $s =~ /\s*(\w+)\s*(.*)/ ;
my %cmd = (
dump => sub { cb_dump() },
clear => sub { clear_history() },
menu => sub { cb_menu() },
copy => sub { xselcopy($arg) },
) ;
if (defined $cmd{$command}) {
$cmd{$command}() ;
$module->showMessage("debug: $command");
} else {
$module->showMessage("unknown command \"$command\"");
}
}
## Xsel periodically polls the system clipboard via ualarm. If new, then
## a record is stored of extra info about the new entry. If the entry's
## datatype is defined in %submenus, then that cmnd is sent to fvwm.
##
sub cb_sync {
my $md5 = get_xsel_md5() ;
if ($md5 && $md5 ne $md5last) {
## Make a hash of all md5s to indexes in @records
my %md5index = () ;
for (my $idx = $#records ; $idx >= 0 ; $idx--) {
$md5index{$records[$idx]->{md5}} = $idx ;
}
## If this xsel record already exists, ...
if (defined $md5index{$md5}) {
## then move the old record to the top of @records
my $idx = $md5index{$md5} ;
my $oldrecord = $records[$idx] ;
splice @records, $idx, 1 ;
unshift @records, $oldrecord ;
print STDERR "^" ;
} else {
logger('======new clipboard selection======') ;
store_current_xsel($logfile) ;
logger("\n") ;
## else, make a new xsel record.
unlink "$dir/$md5" ;
store_current_xsel("$dir/$md5") ;
my $record = new_record($md5) ;
unshift(@records, $record) if $record ;
print STDERR "+" ;
}
my $menucmd = $records[0]->{menucmd} ;
$module->send($menucmd) if $menucmd ;
## If the num of stored @records now exceeds
## $max_records, then delete the oldest record.
if (exists $records[$max_records]) {
foreach (keys %{ $records[$max_records] } ) {
delete $records[$max_records]->{$_}
}
splice @records, $max_records, 1 ;
}
$md5last = $md5 ;
cb_menu() ;
}
ualarm($pollinterval) ;
return 1 ;
}
## This sub inspects the xsel-file, and determine its type. Then sub
## new_record_typed() builds a hashref with the extra info needed to make
## its clipmenu entry - label, icon, menucmd etc.
##
sub new_record {
my $md5 = shift ;
my $file = $dir->child($md5) ;
my $label = get_label($file) ;
## multiple lines
if ($file->lines > 1) {
$label = substr $label, 0, $max_chars ;
return new_record_typed("other", $md5, $file, $label) ;
## magnet link (single line)
} elsif ($label =~ m{^(magnet[:][?].+)$} ) {
$label = substr $1, 0, $max_chars ;
return new_record_typed("magnet", $md5, $file, $label) ;
## An url (single line)
} elsif ($label =~ m{^http[s]?://(\w.*)$} ) {
## youtube url
if ($label =~ m{://(www[.])?(youtu.*)$}) {
$label = substr $2, 0, $max_chars ;
return new_record_typed("youtube", $md5, $file, $label) ;
## torrent url
} elsif ($label =~ m{://(www[.])?(.+[.]torrent)([?].+)?$} ) {
$label = substr $2, 0, $max_chars ;
return new_record_typed("torrent", $md5, $file, $label) ;
# ## image url
# } elsif ($label =~ m{://(www.)?(.+[.](jpg|gif|png)).*$} ) {
# $label = substr $2, 0, $max_chars ;
# return new_record_typed("image", $md5, $file, $label) ;
## some other kind of url
} else {
$label = substr $1, 0, $max_chars ;
return new_record_typed("url", $md5, $file, $label) ;
}
## A single line, but not a filepath
} elsif ($label !~ m{^/} or not -e $label) {
$label = substr $label, 0, $max_chars ;
return new_record_typed("other", $md5, $file, $label) ;
}
## Either a file or folder path.
my $type = -d $label ? "folder" : "file" ;
my %filetypes = (
"video" => '[.](flv|mkv|mp4|mpe?g|avi|webm|wmv|mov)$',
"audio" => '[.](mp3|m4a|aac|ac3|flac|wav)$',
"image" => '[.](jpg|jpeg|png|gif)$',
"pdf" => '[.]pdf$',
"html" => '[.](html|htm|maff)$',
) ;
if ($type eq "file") {
foreach my $x (keys %filetypes) {
my $pat = $filetypes{$x} ;
if ($label =~ /$pat/ ) { $type = $x }
}
}
## Shorten (abbreviate) the file path.
$label = abbrev_path($label) ;
return new_record_typed($type,, $md5, $file, $label) ;
}
sub new_record_typed {
my $type = shift ;
my $md5 = shift ;
my $file = shift ;
my $label = shift ;
# say STDERR "type : $type" ;
$label = format_label($label) ;
my $icon = exists $icons{$type} ? $icons{$type} : $icons{none} ;
my $menucmd = exists $submenus{$type} ? $submenus{$type} : "" ;
return { md5 => $md5, label => $label,
type => $type, icon => $icon, menucmd => $menucmd } ;
}
## Inspect the xsel-file line by line. The first line found
## with word and/or digit chars is returned as the label.
##
sub get_label {
my $file = shift ;
my $label = "" ;
foreach my $line ($file->lines_utf8) {
if ($line =~ /\w|\d/) {
$label = $line ;
last ;
}
}
$label = "--" if not $label ;
chomp $label ;
unidecode $label ;
return $label ;
}
## Fvwm menus trip up on special chars. This formats a label such
## that menu text prints (almost) correctly.
##
sub format_label {
my $label = shift ;
for ($label) {
tr/$/ / ;
s/([\[\]\#\'\*\?\^`!@;])/\\$1/g ;
s/&/&&/g ;
s/\s+/ /g ;
s/^\s*$/-/ ;
}
return $label ;
}
## If a label is also a filepath, then shorten it via abbreviation.
sub abbrev_path {
my $name = shift ;
while ( length($name) > $max_chars and
$name =~ s!/([^/])[^/]+/!/$1/! ) { }
my $num = length($name) - $max_chars ;
$name = "..." . substr($name, $num+3) if $num > 0 ;
return $name ;
}
## After each new xsel, this sub recreates the clipmenu for fvwm.
sub cb_menu {
## Menu title
sendcmd("DestroyMenu $menu_name") ;
sendcmd("AddToMenu $menu_name \"$menu_title\" Title") ;
## A menu entry for each item in @records.
for (my $idx = 0 ; $idx <= $#records ; $idx++) {
my $rec = $records[$idx] ;
my $icon = $rec->{icon} ? "%$rec->{icon}%" : "" ;
my $cmnd = "+ \'${icon}$rec->{label}\' " ;
$cmnd .= "SendToModule $modname copy $idx" ;
sendcmd($cmnd) ;
}
## Divider line.
sendcmd('+ "" Nop') ;
## Clear history.
my $icon = exists $icons{clear_history} ? $icons{clear_history} : "" ;
my $cmnd = '+ "%' . $icons{clear_history} . "%Clear history" . '" ' ;
$cmnd .= "SendToModule $modname clear " ;
sendcmd($cmnd) ;
}
## Calculate md5sum for the current system clipboard. Xsel cmnds may
## fail, so timeout + exception handler are used for fault-tolerance.
##
sub get_xsel_md5 {
my @cmd1 = ("xsel", "-ob") ;
my @cmd2 = qw( md5sum ) ;
my $out = my $err = "" ;
my $t = timeout($xseltimeout) ;
my $excp = try {
run \@cmd1, '|', \@cmd2, \$out, \$err, $t ;
} catch { "" } ;
if ($err or not $excp) {
print STDERR "~" ;
return 0 ;
}
chomp $out ;
$out =~ s/\s.+$// ;
return $out ;
}
## When the current clipboard has changed, this stores the new xsel
## content to a file.
##
sub store_current_xsel {
my $filex = shift ;
my @cmd = ("xsel", "-ob") ;
my $t = timeout($xseltimeout) ;
my $excp = try {
run \@cmd, ">>", $filex, $t ;
} catch { "" } ;
}
## This sub is triggered via SendToModule. The requested entry is found,
## and pushed to the system clipboard.
##
sub xselcopy {
my $idx = shift ;
my $md5 = $records[$idx]->{md5} ;
my $filex = "$dir/$md5" ;
my $t = timeout($xseltimeout) ;
my @cmd = ("pkill", "xsel") ;
my $excp = try {
run \@cmd, $t ;
} catch { "" } ;
@cmd = ("xsel", "-ib") ;
$excp = try {
run \@cmd, "<", $filex, $t ;
} catch { "" } ;
}
sub clear_history {
@records = () ;
system("rm $dir/* 2>/dev/null") ;
system("mkdir $dir 2>/dev/null") ;
system("echo -- |timeout $xseltimeout xsel -ib") ;
}
sub cb_dump { dump \@records }
sub sendcmd {
foreach (@_) {
$module->send($_) ;
}
}
sub logger {
return 0 unless $logger ;
my $msg = shift ;
$msg .= "\n" ;
$logfile->append_utf8($msg) ;
}
<file_sep>/.fvwm/lib/panelbar/UpdateWeatherPanel
#!/usr/bin/perl
## Useful webpages :-
## http://www.imagemagick.org/script/command-line-processing.php
## http://www.imagemagick.org/script/perl-magick.php
## http://openweathermap.org/weather-conditions
## http://openweathermap.org/forecast5
use strict ;
use warnings ;
use utf8 ;
use v5.22 ;
use lib `fvwm-perllib dir` ;
use FVWM::Module ;
use XML::LibXML::Simple () ;
use Image::Magick ; ## libimage-magick-perl
use IPC::Run qw( run ) ; ## libipc-run-perl
use Path::Tiny ; ## libpath-tiny-perl
use Data::Dump qw( dump ) ;
## Name of the FvwmButtons weather panel.
my $panelmodname = "WeatherPanel" ;
## Output image filepath
my $outfile = path("$ENV{FVWM_USERDIR}/images/panel-weather.png") ;
## Output image size
my $canvas_geom = "300x115" ;
## A file to which the current weather written.
my $weatherfile = path("$ENV{FVWM_USERDIR}/.weather") ;
## Folder path to weather icons.
my $icondir = "$ENV{FVWM_USERDIR}/images/panelbar/weather" ;
## Main weather icon size.
my $iconsize = "80x80" ;
## Canvas background color
my $back = "gray9" ;
## Imagemagick quality setting.
my $quality = 99 ;
## Start the FVWM module.
my $modname = "UpdateWeatherPanel" ;
my $module = new FVWM::Module(
Name => $modname,
Debug => 0,
) ;
## Start up the colorset tracker.
my $cs_tracker = $module->track("Colorsets") ;
my $cs_hash = $cs_tracker->data ;
## Colors for text etc.
my $text_color = get_color(330,"fg") ;
my $bold_color = get_color(331,"fg") ;
## Font descriptors.
my $fontdir = "/usr/share/fonts/X11/misc" ;
my $fontsmall = {
file => "$fontdir/ter-u16b_iso-8859-1.pcf.gz",
width => 8, height => 16,
} ;
my $fontlarge = {
file => "$fontdir/ter-u18b_iso-8859-1.pcf.gz",
width => 10, height => 19,
} ;
## Exit unless internet is available.
exit unless pingtest() ;
#### GET CURRENT WEATHER INFO
## Fetch weather data from openweathermap.com
my $data = get_weather_data() ;
## Weather icon filepath.
my $iconfile = $icondir . "/" . $data->{weather}->{icon} . ".png" ;
## General overview.
my $overview = $data->{weather}->{value} ;
$overview =~ s/([\w']+)/\u\L$1/g ;
## Wind
my $direction = $data->{wind}->{direction}->{code} ;
my $speed = $data->{wind}->{speed}->{value} * 3.6 ;
$speed = nearest(.1, $speed) ;
## Rain
my $rain = 0 ;
my $mode = $data->{precipitation}->{mode} ;
unless ($mode eq "no") {
my $rain = $data->{precipitation}->{value} ;
$rain = nearest(.01, $rain) ;
}
## Temperature
my $celsius = $data->{temperature}->{max} ;
$celsius = nearest(.1, $celsius) ;
## Humidity
my $humid = $data->{humidity}->{value} ;
write_weather_info() ;
#### DRAW PANEL
## Create blank canvas.
my $image = Image::Magick->new ;
$image->Set(size => $canvas_geom) ;
$image->ReadImage("canvas:$back") ;
## Overlay canvas with the weather icon .
my $icon = load_image($iconfile) ;
$icon->AdaptiveResize( geometry => $iconsize) ;
$image->Composite(image => $icon, x => 20, y => 30) ;
## Add the main title - a general weather overview.
my $xx1 = 150 ; my $yy1 = 24 ;
$image = center_justified($xx1, $yy1, $text_color, $fontlarge, $overview, $image) ;
## Calc positions for subtitles
my $yoffset = 19 ;
my $xx2 = 125 ; my $yy2 = 45 ;
my $xx3 = $xx2 ; my $yy3 = $yy2 + $yoffset ;
my $xx4 = $xx3 ; my $yy4 = $yy3 + $yoffset ;
my $xx5 = $xx4 ; my $yy5 = $yy4 + $yoffset ;
## Annotate the subtitles
$image = left_justified($xx2, $yy2, $bold_color, $fontsmall, "TEMP:", $image) ;
$image = left_justified($xx3, $yy3, $bold_color, $fontsmall, "WIND:", $image) ;
$image = left_justified($xx4, $yy4, $bold_color, $fontsmall, "RAIN:", $image) ;
$image = left_justified($xx5, $yy5, $bold_color, $fontsmall, "HUMIDITY:", $image) ;
## 4 annotated value fields for temperature, wind etc.
## Calc positions for value fields.
my $xx6 = 280 ; my $yy6 = 45 ;
my $xx7 = $xx6 ; my $yy7 = $yy6 + $yoffset ;
my $xx8 = $xx7 ; my $yy8 = $yy7 + $yoffset ;
my $xx9 = $xx8 ; my $yy9 = $yy8 + $yoffset ;
## Annotate the value fields.
my $text = "${celsius}°C" ;
$image = right_justified($xx6, $yy6, $text_color, $fontsmall, $text, $image) ;
$text = "${speed}kph $direction" ;
$image = right_justified($xx7, $yy7, $text_color, $fontsmall, $text, $image) ;
$text = $rain ? "${rain}mm/h" : "nil" ;
$image = right_justified($xx8, $yy8, $text_color, $fontsmall, $text, $image) ;
$text = "$humid%" ;
$image = right_justified($xx9, $yy9, $text_color, $fontsmall, $text, $image) ;
## Save the finished thumbnail.
save_image($image, $outfile) ;
## Update image in the FvwmButtons module.
my $cmd = "SendToModule $panelmodname ChangeButton winfo Icon " ;
$cmd .= $outfile->basename ;
$module->send($cmd) ;
## SUBROUTINES
sub get_color {
my $cs_num = shift ;
my $opt = shift ;
my $color = $cs_hash->{$cs_num}->{$opt} ;
return sprintf('#%x',$color) ;
}
sub write_weather_info {
$weatherfile->remove ;
my $info = rounded($data->{temperature}->{max}) . "," . $data->{weather}->{icon} ;
$weatherfile->append($info) ;
}
sub pingtest {
my $cmd = "ping -c1 -W5 8.8.8.8 1>/dev/null 2>&1 " ;
$cmd .= " && echo -n 1 || echo -n 0" ;
return readpipe($cmd) ;
}
sub load_image {
my $err = 1 ;
my $image = Image::Magick->New() ;
my $imgfile = shift ;
open(IMAGE, $imgfile) or return 0 ;
$err = $image->Read(file=>\*IMAGE);
close(IMAGE);
if ($err) { return 0 } else { return $image } ;
}
sub save_image {
my $image = shift ;
my $outfile = shift ;
open(IMAGE, ">$outfile") ;
return 0 if $image->Write(
file => \*IMAGE,
filename => $outfile,
quality => $quality,
) ;
return 1 ;
}
sub right_justified {
my $xpos = shift ;
my $ypos = shift ;
my $color = shift ;
my $font = shift ;
my $text = shift ;
my $img = shift ;
$xpos -= $font->{width} * length($text) ;
return 0 if $img->Annotate(
x => $xpos,
y => $ypos,
gravity => "NorthWest",
font => $font->{file},
fill => $color,
text => $text,
) ;
return $img ;
}
sub left_justified {
my $xpos = shift ;
my $ypos = shift ;
my $color = shift ;
my $font = shift ;
my $text = shift ;
my $img = shift ;
return 0 if $img->Annotate(
x => $xpos,
y => $ypos,
gravity => "NorthWest",
font => $font->{file},
fill => $color,
text => $text,
) ;
return $img ;
}
sub center_justified {
my $xpos = shift ;
my $ypos = shift ;
my $color = shift ;
my $font = shift ;
my $text = shift ;
my $img = shift ;
$xpos -= int($font->{width} * length($text)/2) ;
return 0 if $img->Annotate(
x => $xpos,
y => $ypos,
gravity => "NorthWest",
font => $font->{file},
fill => $color,
text => $text,
) ;
return $img ;
}
sub get_weather_data {
my $key = readpipe("cat $ENV{FVWM_USERDIR}/.weatherkey") ;
my $url = "http://api.openweathermap.org/data/2.5/weather?id=2191562&mode=xml&units=metric&APPID=$key" ;
my $xml = readpipe("timeout 5 curl \"$url\" 2>/dev/null") ;
my $xs = XML::LibXML::Simple->new() ;
my $data = $xs->XMLin($xml,) ;
return $data ;
}
## Cribbed from Math::Round
sub nearest {
my $targ = abs(shift);
my $half = 0.50000000000008 ;
my @res = map {
if ($_ >= 0) { $targ * int(($_ + $half * $targ) / $targ); }
else { $targ * POSIX::ceil(($_ - $half * $targ) / $targ); }
} @_ ;
return (wantarray) ? @res : $res[0] ;
}
## Cribbed from Math::Round
sub rounded {
my $x;
my $half = 0.50000000000008 ;
my @res = map {
if ($_ >= 0) { POSIX::floor($_ + $half); }
else { POSIX::ceil($_ - $half); }
} @_;
return (wantarray) ? @res : $res[0];
}
#my $text = "°C" ;
<file_sep>/.fvwm/lib/panelbar/UpdateVnstatPanel
#!/usr/bin/perl
## Purpose: to build an image that shows vnstat stats for the last week
## as a histogram, and tabulates weekly vnstat summarys below that.
## First, xml data is obtained from vnstat. The stats for rx+tx usage
## are kept, and stored in an array according to date. The stats are
## then written as a data file, which is used to plot a histogram
## with gnuplot. Imagemagick then creates a blank canvas, on which
## the plot is overlayed. More vnstat weekly summaries are annotated
## below the plot. The imagemagick image is finally written to outfile.
## Useful webpages :-
## http://www.imagemagick.org/script/command-line-processing.php
## http://www.imagemagick.org/script/perl-magick.php
use strict ;
use warnings ;
use utf8 ;
use v5.22 ;
use lib `fvwm-perllib dir` ;
use FVWM::Module ;
use Time::Piece ;
use Time::Seconds ;
use IPC::Run qw( run ) ; ## libipc-run-perl
use Path::Tiny ; ## libpath-tiny-perl
use Image::Magick ; ## libimage-magick-perl
use XML::LibXML::Simple () ; ## libxml-libxml-simple-perl
#use Data::Dump qw( dump ) ;
## Name of the FvwmButtons vnstat panel.
my $panelmodname = "VnstatPanel" ;
## Output filename for final imagemagick image.
my $imagemagick_outfile = path("$ENV{FVWM_USERDIR}/images/panel-vnstat.png") ;
## Size of blank canvas used by imagemagick
my $canvas_geometry = "350x145" ;
## Size of graph produced by gnuplot
my $plot_geometry_x = 350 ;
my $plot_geometry_y = 100 ;
## Image compression setting for imagemagick.
my $quality = 100 ;
## Output filename for interim gnuplot image.
my $plot_outfile = Path::Tiny->tempfile(TEMPLATE => 'plot_XXXXXX', suffix => '.png') ;
## Temporary file to store raw vnstat data.
my $datafile = Path::Tiny->tempfile(TEMPLATE => 'vnstat_XXXXXX', suffix => '.dat') ;
## Start the FVWM module.
my $modname = "UpdateVnstatPanel" ;
my $module = new FVWM::Module(
Name => $modname,
Debug => 0,
) ;
## Get FVWM colorset data.
my $cs_tracker = $module->track("Colorsets") ;
my $cs_hash = $cs_tracker->data ;
$cs_tracker->stop ;
## Colors for gnuplot (set via fvwm colorsets)
my $plotcolor_tx = get_color(300,"fg") ;
my $plotcolor_rx = get_color(301,"fg") ;
my $plotcolor_box_border = get_color(302,"fg") ;
my $plotcolor_tics_axes = get_color(303,"fg") ;
## Colors for text, bold and plain.
my $text_bold_color = get_color(304,"fg") ;
my $text_color_1 = get_color(305,"fg") ;
my $text_color_2 = get_color(306,"fg") ;
my $text_color_3 = get_color(307,"fg") ;
## Font descriptor
my $fontdir = "/usr/share/fonts/X11/misc" ;
my $fontsmall = {
file => "$fontdir/ter-u16b_iso-8859-1.pcf.gz",
width => 8, height => 16,
} ;
#### MAIN
## Get data array from vnstat.
my @vnstat = get_vnstat_array() ;
## Write data file for the graph. Also obtain yrange values for the plot.
my ($yrange_max, $yrange_mid) = write_datafile($datafile) ;
## Obtain xrange values for the plot.
my ($xrange_start, $xrange_end) = get_xrange_values() ;
## Plot the vnstat data for the last 7 days
my $plot = define_gnuplot() ;
my @cmd = qw( gnuplot ) ;
my $out = my $err = "" ;
run \@cmd, \$plot, \$out, \$err ;
## Imagemagick - create a blank canvas.
my $image = Image::Magick->new ;
$image->Set(size => $canvas_geometry) ;
$image->ReadImage("canvas:gray9") ;
## Load graph image, and overlay onto the canvas.
my $xx1 = -3 ;
my $yy1 = 20 ;
my $graph = load_image($plot_outfile) ;
$image->Composite(image => $graph, x => $xx1, y => $yy1) ;
## Annotate the main title
my $xx2 = int($plot_geometry_x/2) ;
my $yy2 = 20 ;
my $text = "VNSTAT : LAST 7 DAYS" ;
$image = center_justified($xx2, $yy2, $text_color_1, $fontsmall, $text, $image) ;
## Annotate text for the key
my $xx3 = 100 ;
my $yy3 = $yy1 + $plot_geometry_y + 15 ;
$image = left_justified($xx3, $yy3, $text_color_1, $fontsmall, "TX: ", $image) ;
my $xx4 = $xx3 + 100 ;
my $yy4 = $yy3 ;
$image = left_justified($xx4, $yy4, $text_color_1, $fontsmall, "RX: ", $image) ;
## Draw rectangles for the key
my $xx5 = $xx3 + 30 ;
my $yy5 = $yy3 - 10 ;
my $xx6 = $xx3 + 50 ;
my $yy6 = $yy3 ;
$image->Draw(
primitive => "rectangle",
fill => $plotcolor_tx,
stroke => $plotcolor_box_border,
strokewidth => 1,
points => "$xx5,$yy5 $xx6,$yy6",
) ;
my $xx7 = $xx4 + 30 ;
my $yy7 = $yy4 - 10 ;
my $xx8 = $xx4 + 50 ;
my $yy8 = $yy4 ;
$image->Draw(
primitive => "rectangle",
fill => $plotcolor_rx,
stroke => $plotcolor_box_border,
strokewidth => 1,
points => "$xx7,$yy7 $xx8,$yy8",
) ;
## Save the finished panel.
save_image($image, $imagemagick_outfile) ;
## Update image in the FvwmButtons module.
my $cmd = "SendToModule $panelmodname ChangeButton vicon Icon " ;
$cmd .= $imagemagick_outfile->basename ;
$module->send($cmd) ;
exit ;
#### SUBROUTINES
sub get_color {
my $cs_num = shift ;
my $opt = shift ;
my $color = $cs_hash->{$cs_num}->{$opt} ;
return sprintf('#%x',$color) ;
}
sub get_vnstat_array {
## An empty array to store rx/tx for the last 30 days.
my @net = () ;
for (my $idx = 0, my $t = Time::Piece->new ; $idx <= 29 ; $idx++, $t -= ONE_DAY) {
my $date = $t->strftime("%Y%m%d") ;
$net[$idx] = { rx => 0, tx => 0, date => $date } ;
}
## Update the array with raw data from vnstat
my $raw_vnstat = get_vnstat_data() ;
foreach my $idx (0..29) {
if (defined $raw_vnstat->{interface}->{traffic}->{days}->{day}->{$idx}) {
my $rx = $raw_vnstat->{interface}->{traffic}->{days}->{day}->{$idx}->{rx} ;
my $tx = $raw_vnstat->{interface}->{traffic}->{days}->{day}->{$idx}->{tx} ;
$net[$idx]->{rx} = $rx ;
$net[$idx]->{tx} = $tx ;
}
}
return @net ;
}
sub get_vnstat_data {
my $xml = readpipe("vnstat --xml d 2>/dev/null") ;
my $xs = XML::LibXML::Simple->new() ;
my $data = $xs->XMLin($xml,) ;
return $data ;
}
sub vnstat_summary {
my $first = shift ;
my $last = shift ;
my ($rxtotal, $txtotal, $total) = (0,0,0) ;
## Calc rx/tx totals over the period.
for (my $idx = $first ; $idx < $last ; $idx++) {
my $rx = $vnstat[$idx]->{rx} ;
my $tx = $vnstat[$idx]->{tx} ;
$rxtotal += $rx ;
$txtotal += $tx ;
$total += $rx + $tx ;
}
## Reexpress the totals as Gb (gigabytes) or Mb (megabytes).
foreach ($rxtotal, $txtotal, $total) {
my $num = $_ ;
if ($num >= 1022976) {
$_ = nearest(.1, $num/1048576) . "Gb"
} else {
$_ = nearest(.1,$num/1024) . "Mb"
}
}
return ($rxtotal, $txtotal, $total) ;
}
sub write_datafile {
my $datafile = shift ;
## Initial yrange values for gnuplot
my $yrange_max = 1 ;
my $yrange_mid = .5 ;
## Write a datafile of vnstat for last 7 days.
$datafile->remove ;
foreach my $idx (0..6) {
## rx/tx is already recorded in kilobytes. Change that to gigabytes.
my $rx = nearest(.001, $vnstat[$idx]->{rx}/1048576) ;
my $tx = nearest(.001, $vnstat[$idx]->{tx}/1048576) ;
$yrange_max = int($rx)+1 if $rx > $yrange_max ;
$yrange_max = int($tx)+1 if $tx > $yrange_max ;
$yrange_mid = $yrange_max/2 ;
## append to the data file.
my $data = $vnstat[$idx]->{date} . "00,$tx,$rx\n" ;
$datafile->append($data) ;
}
## return the yrange values.
return ($yrange_max, $yrange_mid) ;
}
## Compute xrange values for the plot
sub get_xrange_values {
my $today = Time::Piece->new->ymd ;
$today = Time::Piece->strptime($today, '%Y-%m-%d');
my $xrange_start = $today ;
$xrange_start -= ONE_DAY * 7 ;
$xrange_start += ONE_HOUR * 9 ;
$xrange_start = $xrange_start->strftime("%Y%m%d%H") ;
my $xrange_end = $today ;
$xrange_end += ONE_HOUR * 12 ;
$xrange_end = $xrange_end->strftime("%Y%m%d%H") ;
return ($xrange_start, $xrange_end) ;
}
sub right_justified {
my $xpos = shift ;
my $ypos = shift ;
my $color = shift ;
my $font = shift ;
my $text = shift ;
my $img = shift ;
$xpos -= $font->{width} * length($text) ;
return 0 if $img->Annotate(
x => $xpos,
y => $ypos,
gravity => "NorthWest",
font => $font->{file},
fill => $color,
text => $text,
) ;
return $img ;
}
sub left_justified {
my $xpos = shift ;
my $ypos = shift ;
my $color = shift ;
my $font = shift ;
my $text = shift ;
my $img = shift ;
return 0 if $img->Annotate(
x => $xpos,
y => $ypos,
gravity => "NorthWest",
font => $font->{file},
fill => $color,
text => $text,
) ;
return $img ;
}
sub center_justified {
my $xpos = shift ;
my $ypos = shift ;
my $color = shift ;
my $font = shift ;
my $text = shift ;
my $img = shift ;
$xpos -= int($font->{width} * length($text)/2) ;
return 0 if $img->Annotate(
x => $xpos,
y => $ypos,
gravity => "NorthWest",
font => $font->{file},
fill => $color,
text => $text,
) ;
return $img ;
}
sub load_image {
my $err = 1 ;
my $image = Image::Magick->New() ;
my $imgfile = shift ;
open(IMAGE, $imgfile) or return 0 ;
$err = $image->Read(file=>\*IMAGE);
close(IMAGE);
if ($err) { return 0 } else { return $image } ;
}
sub save_image {
my $image = shift ;
my $outfile = shift ;
open(IMAGE, ">$outfile") ;
return 0 if $image->Write(
file => \*IMAGE,
filename => $outfile,
quality => $quality,
) ;
return 1 ;
}
## Cribbed from Math::Round
sub nearest {
my $targ = abs(shift);
my $half = 0.50000000000008 ;
my @res = map {
if ($_ >= 0) { $targ * int(($_ + $half * $targ) / $targ); }
else { $targ * POSIX::ceil(($_ - $half * $targ) / $targ); }
} @_ ;
return (wantarray) ? @res : $res[0] ;
}
## It would have been nice to plot the data with one of the gnuplot
## modules for perl. However, those modules are too limited for this
## kind of plot. So it is written as a simple gnuplot script.
sub define_gnuplot {
return qq{
set terminal png size $plot_geometry_x,$plot_geometry_y \\
font "Droid Sans Mono,10" transparent truecolor
set output '$plot_outfile'
set datafile separator ","
set tmargin at screen 0.90
set rmargin at screen 0.96
set lmargin at screen 0.14
set bmargin at screen 0.20
unset key
set border 3 lc rgbcolor "$plotcolor_tics_axes" lw 2
set style data boxes
set boxwidth 0.36 relative
set style fill solid border lc rgbcolor "$plotcolor_box_border"
set timefmt "%Y%m%d%H"
set xdata time
set xtics format "%a"
set xtics nomirror out scale 2,0 offset 0,.5
set ytics nomirror out scale 2,2 offset graph \\
0.03,0 (0, "" $yrange_mid, "${yrange_max}Gb" $yrange_max)
set xrange [\"$xrange_start\":\"$xrange_end\"]
set yrange[0:$yrange_max]
plot '$datafile' \\
using (timecolumn(1)-15550):2 lc rgbcolor "$plotcolor_tx", \\
'' using (timecolumn(1)+15550):3 lc rgbcolor "$plotcolor_rx"
} ; }
<file_sep>/.fvwm/lib/panelbar/UpdateSystemInfoPanel
#!/usr/bin/perl
## Useful webpages :-
## http://www.imagemagick.org/script/command-line-processing.php
## http://www.imagemagick.org/script/perl-magick.php
use strict ;
use warnings ;
use utf8 ;
use v5.22 ;
use lib `fvwm-perllib dir` ;
use FVWM::Module ;
use Image::Magick ; ## libimage-magick-perl
use Data::Dump qw( dump ) ;
use Path::Tiny ; ## libpath-tiny-perl
use POSIX ;
## Name of the FvwmButtons weather panel.
my $panelmodname = "SystemInfoPanel" ;
## Output image filepath
my $outfile = path("$ENV{FVWM_USERDIR}/images/panel-systeminfo.png") ;
## Imagemagick quality setting.
my $quality = 99 ;
## Color and geometry for canvas
my $canvas_geometry = "280x130" ;
my $canvas_bg = "gray9" ;
## Start the FVWM module.
my $modname = "UpdateSystemInfoPanel" ;
my $module = new FVWM::Module(
Name => $modname,
Debug => 0,
) ;
## Get FVWM colorset data.
my $cs_tracker = $module->track("Colorsets") ;
my $cs_hash = $cs_tracker->data ;
$cs_tracker->stop ;
## Colors for text, bold and plain.
my $text_color = get_color(320,"fg") ;
my $text_bold_color = get_color(321,"fg") ;
## Descriptors for large and small fonts.
my $fontdir = "/usr/share/fonts/X11/misc" ;
my $fontsmall = {
file => "$fontdir/ter-u16b_iso-8859-1.pcf.gz", width => 8,
} ;
my $fontlarge = {
file => "$fontdir/ter-u18b_iso-8859-1.pcf.gz", width => 10,
} ;
## Get updated system information.
my ($seconds, $hours, $minutes) = get_uptime() ;
my $loadavg = get_loadavg() ;
my $debs = get_apt_upgradable() ;
my $last_backup = last_backup_days() ;
my $cpu_temp = get_cpu_temperature() ;
#### Draw the panel
## Create blank canvas.
my $image = Image::Magick->new ;
$image->Set(size => $canvas_geometry) ;
$image->ReadImage("canvas:$canvas_bg") ;
## Annotate the main title
my $xx1 = 140 ; my $yy1 = 20 ;
my $text = "SYSTEM INFORMATION" ;
$image = center_justified($xx1, $yy1, $text_color, $fontsmall, $text, $image) ;
## Calculate the subtitles positions.
my $yoffset = 19 ;
my $xx2 = 15 ; my $yy2 = 40 ;
my $xx3 = $xx2 ; my $yy3 = $yy2 + $yoffset ;
my $xx4 = $xx2 ; my $yy4 = $yy3 + $yoffset ;
my $xx5 = $xx2 ; my $yy5 = $yy4 + $yoffset ;
my $xx6 = $xx2 ; my $yy6 = $yy5 + $yoffset ;
## Annotate the subtitles.
$image = left_justified($xx2, $yy2, $text_bold_color, $fontsmall, "UPTIME:", $image) ;
$image = left_justified($xx3, $yy3, $text_bold_color, $fontsmall, "UPGRADES:", $image) ;
$image = left_justified($xx4, $yy4, $text_bold_color, $fontsmall, "LAST BACKUP:", $image) ;
$image = left_justified($xx5, $yy5, $text_bold_color, $fontsmall, "CPU TEMP:", $image) ;
$image = left_justified($xx6, $yy6, $text_bold_color, $fontsmall, "LOAD AVG:", $image) ;
## Calculate the text value positions.
my $xx7 = 265 ; my $yy7 = $yy2 ;
my $xx8 = $xx7 ; my $yy8 = $yy7 + $yoffset ;
my $xx9 = $xx8 ; my $yy9 = $yy8 + $yoffset ;
my $xx10 = $xx9 ; my $yy10 = $yy9 + $yoffset ;
my $xx11 = $xx10 ; my $yy11 = $yy10 + $yoffset ;
## Annotate the text values.
$text = "${hours}hrs, ${minutes}mins" ;
$image = right_justified($xx7, $yy7, $text_color, $fontsmall, $text, $image) ;
$image = right_justified($xx8, $yy8, $text_color, $fontsmall, $debs, $image) ;
$text = "-$last_backup days" ;
$image = right_justified($xx9, $yy9, $text_color, $fontsmall, $text, $image) ;
$text = "${cpu_temp}°C" ;
$image = right_justified($xx10, $yy10, $text_color, $fontsmall, $text, $image) ;
$text = "$loadavg" ;
$image = right_justified($xx11, $yy11, $text_color, $fontsmall, $text, $image) ;
## Save the finished panel.
save_image($image, $outfile) ;
## Update image in the FvwmButtons module.
my $cmd = "SendToModule $panelmodname ChangeButton sicon Icon " ;
$cmd .= $outfile->basename ;
$module->send($cmd) ;
exit ;
#### SUBROUTINES
sub get_color {
my $cs_num = shift ;
my $opt = shift ;
my $color = $cs_hash->{$cs_num}->{$opt} ;
return sprintf('#%x',$color) ;
}
sub get_uptime {
my $seconds = readpipe('sed "s/[.].*//" </proc/uptime') ;
my $hours = int($seconds/3600) ;
my $minutes = int(($seconds%3600)/60) ;
return ($seconds, $hours, $minutes) ;
}
## sub get_meminfo {
## my $used = readpipe 'free -m | awk \'/^Mem:/{print $3}\'' ;
## chomp $used ;
## my $swap = readpipe 'free -m | awk \'/^Swap:/{print $3}\'' ;
## chomp $swap ;
## return ($used, $swap) ;
## }
sub get_loadavg {
my @loadavg = split(/\s+/, readpipe("cat /proc/loadavg")) ;
my $loadavg = join(" ", @loadavg[0..2]) ;
return $loadavg ;
}
sub get_apt_upgradable {
my $apt_file = "/var/log/apt-upgradable" ;
my $total = readpipe("apt list --installed 2>/dev/null|sed 1d|wc -l") ;
chomp $total ;
my $upgradable = 0 ;
if (-r $apt_file) {
$upgradable = readpipe "cat $apt_file" ;
chomp $upgradable ;
}
return "$upgradable of $total" ;
}
sub last_backup_days {
my $atime = 0 ;
my $seconds = time() ;
foreach my $file (</mnt/btrfs/lacipec1?2*>) {
my $cmd = "stat --format=%X " . $file ;
my $num = readpipe($cmd) ;
chomp $num ;
$atime = $num if $num > $atime ;
}
return int(($seconds - $atime)/86400) ;
}
sub get_cpu_temperature {
my $celsius = readpipe("cat /sys/devices/virtual/thermal/thermal_zone0/temp") ;
$celsius = rounded($celsius/1000) ;
return $celsius ;
#$celsius .= "°" ;
}
sub load_image {
my $err = 1 ;
my $image = Image::Magick->New() ;
my $imgfile = shift ;
open(IMAGE, $imgfile) or return 0 ;
$err = $image->Read(file=>\*IMAGE);
close(IMAGE);
if ($err) { return 0 } else { return $image } ;
}
sub save_image {
my $image = shift ;
my $outfile = shift ;
open(IMAGE, ">$outfile") ;
return 0 if $image->Write(
file => \*IMAGE,
filename => $outfile,
quality => $quality,
) ;
return 1 ;
}
sub right_justified {
my $xpos = shift ;
my $ypos = shift ;
my $color = shift ;
my $font = shift ;
my $text = shift ;
my $img = shift ;
$xpos -= $font->{width} * length($text) ;
return 0 if $img->Annotate(
x => $xpos,
y => $ypos,
gravity => "NorthWest",
font => $font->{file},
fill => $color,
text => $text,
) ;
return $img ;
}
sub left_justified {
my $xpos = shift ;
my $ypos = shift ;
my $color = shift ;
my $font = shift ;
my $text = shift ;
my $img = shift ;
return 0 if $img->Annotate(
x => $xpos,
y => $ypos,
gravity => "NorthWest",
font => $font->{file},
fill => $color,
text => $text,
) ;
return $img ;
}
sub center_justified {
my $xpos = shift ;
my $ypos = shift ;
my $color = shift ;
my $font = shift ;
my $text = shift ;
my $img = shift ;
$xpos -= $font->{width} * int(length($text)/2) ;
return 0 if $img->Annotate(
x => $xpos,
y => $ypos,
gravity => "NorthWest",
font => $font->{file},
fill => $color,
text => $text,
) ;
return $img ;
}
## Cribbed from Math::Round
sub rounded {
my $x;
my $half = 0.50000000000008 ;
my @res = map {
if ($_ >= 0) { POSIX::floor($_ + $half); }
else { POSIX::ceil($_ - $half); }
} @_;
return (wantarray) ? @res : $res[0];
}
## Cribbed from Math::Round
sub nearest {
my $targ = abs(shift);
my $half = 0.50000000000008 ;
my @res = map {
if ($_ >= 0) { $targ * int(($_ + $half * $targ) / $targ); }
else { $targ * POSIX::ceil(($_ - $half * $targ) / $targ); }
} @_ ;
return (wantarray) ? @res : $res[0] ;
}
#$text = "PROCESSES:" ;
#$ypos += $offset ;
#$image = left_justified($xpos, $ypos, $text_bold_color, $fontsmall, $text, $image) ;
#$text = "$processes" ;
#$ypos += $offset ;
#$image = right_justified($xpos, $ypos, $text_color, $fontsmall, $text, $image) ;
## sub get_process_count {
## my $processes = readpipe("ps -e | wc -l");
## chomp $processes ;
## return $processes ;
## }
<file_sep>/.fvwm/lib/panelbar/UpdatePanelBar
#!/usr/bin/perl
## Fvwm module to collect system stats, and use them to update
## the various values and fields of the FvwmButtons statusbar.
use strict ;
use warnings ;
use v5.22 ;
use lib `fvwm-perllib dir`;
use FVWM::Module;
use Time::Piece ;
use Time::Seconds ;
use Sys::Statistics::Linux ;
use Path::Tiny ; ## libpath-tiny-perl
use POSIX ;
#use Data::Dump qw( dump ) ;
## Name of the panelbar module.
my $panel_modname = "PanelBar" ;
## Name of the TimeandDate module.
my $timedate_modname = "TimeAndDate" ;
## Name for this fvwmperl module.
my $fvwm_modname = "UpdatePanelBar" ;
## The file from which current weather data is read.
my $weatherfile = path("$ENV{FVWM_USERDIR}/.weather") ;
## Seconds between each panelbar update.
my $pollinterval = 1 ;
## The current time/date.
my $t = Time::Piece->new ;
## Time/date for the last update
my $t_lastupdate = 0 ;
## Time/date for the last memory update
my $t_lastmemory = $t - ONE_HOUR ;
## Time/date for the last weather update
my $t_lastweather = $t - ONE_HOUR ;
## The last known desktop number.
my $lastdesktop = -1 ;
## Colors used to underline desktop numbers
my $underline_off = "gray9" ;
#my $underline_on = "gray70" ;
#my $underline_on = "steelblue4" ;
my $underline_on = "#547A99" ;
## Colorset numbers associated with each numbered desktop.
my %desktop_cs = (
"-1" => 284, "0" => 284, "1" => 275, "2" => 276, "3" => 277,
"4" => 278, "5" => 279, "6" => 280, "7" => 281, "8" => 282,
) ;
## Volume icons for show_volume().
my @volume_icons = (
{ threshold => 20, icon => "pb_volume-zero.png" },
{ threshold => 45, icon => "pb_volume-low.png" },
{ threshold => 70, icon => "pb_volume-medium.png" },
{ threshold => 100, icon => "pb_volume-high.png" },
) ;
## Brightness icons for show_bright().
my @bright_icons = (
{ threshold => 25, icon => "pb_brightness-low.png" },
{ threshold => 50, icon => "pb_brightness-medium.png" },
{ threshold => 75, icon => "pb_brightness-high.png" },
{ threshold => 100, icon => "pb_brightness-full.png" },
) ;
## Obtain initial data from the systems stats module.
my $lxs = Sys::Statistics::Linux->new(
cpustats => 1,
netstats => 1,
) ;
$lxs->init ;
my $lxsdata = $lxs->get ;
## Start periodic updates via the alarm() function.
$SIG{ALRM} = \&polling ;
alarm($pollinterval) ;
## Start the fvwm module, for sending SendToModule cmnds.
my $module = new FVWM::Module(
Name => $fvwm_modname,
Debug => 1,
);
## A tracker to detect and update changes of desktop.
my $page_tracker = $module->track("PageInfo") ;
$page_tracker->observe(sub {
my ($module, $tracker, $info) = @_;
update_desktop($info->{desk_n}) ;
});
## A handler to intercept fvwm cmnds. Triggers an update for
## volume and brightness.
$module->addHandler(M_STRING, sub {
show_volume() ;
show_bright() ;
}) ;
## Listen to fvwm.
$module->event_loop ;
say STDERR "UpdatePanelBar: You shouldn't be here!" ;
#### SUBROUTINES
## To reset the alarm().
sub polling {
alarm(1) ;
update_bar() ;
#update_datetime() ;
return ;
}
sub update_bar {
## Refresh the system stats.
$lxsdata = $lxs->get ;
## Update current date/time.
$t = Time::Piece->new ;
update_datetime() ;
if ($t->epoch%2) {
update_cpustats() ;
update_memstats() if $t->epoch - $t_lastmemory->epoch > 30 ;
update_netstats() ;
update_weather() if $t->epoch - $t_lastweather->epoch > 10 ;
}
$t_lastupdate = $t ;
return 1 ;
}
sub update_weather {
if ($weatherfile->slurp =~ /^(.+)[,](.+)$/) {
my $icon = $2 . "_small.png" ;
sendto_panelbar("wicon Icon \"$icon\"") ;
sendto_panelbar("celsius Title \"${1}C\"") ;
$t_lastweather = $t ;
}
}
sub show_bright {
my $bright_max = 255 ;
my $bl_device="/sys/class/backlight/radeon_bl0/brightness" ;
my $actual = `cat $bl_device` ;
chomp $actual ;
my $bright = ceiling($actual, $bright_max) ;
my $icon ;
foreach my $arg (@bright_icons) {
if ($bright < $arg->{threshold}) {
$icon = $arg->{icon} ;
last ;
}
}
sendto_panelbar("bicon Icon \"$icon\"") if defined($icon) ;
sendto_panelbar("bri Title \"$bright%\"") ;
}
sub show_volume {
my $vol ;
my $icon ;
foreach my $x (`amixer scontents` ) {
if ($x =~ /^\s+Mono:\s+Playback.+\[(\d\d?\d?)%\].+$/) {
$vol = $1 < 100 ? $1 : 99 ;
foreach my $arg (@volume_icons) {
if ($vol < $arg->{threshold}) {
$icon = $arg->{icon} ;
last ;
}
}
sendto_panelbar("vicon Icon \"$icon\"") if defined($icon) ;
sendto_panelbar("vol Title \"$vol%\"") if defined($vol) ;
}
}
}
## It turns out the stats module over-reports memory usage,
## so I'm using free cmnd instead.
sub update_memstats {
my $used = 0 ;
my $total = 1048 ;
my $percent = 0 ;
foreach (`free -m`) {
#if (/^Mem:\s+(\d+)\s+(\d+)\s+\d+\s+\d+\s+\d+\s+(\d+)\s+/) {
if (/^Mem:\s+(\d+)\s+(\d+)\s+/) {
$total = $1 ;
$used = $2 ;
$percent = rounded($used/$total * 99) ;
}
}
#say STDERR "$used :: $total :: $percent" ;
$t_lastmemory = $t ;
sendto_panelbar("hdd Title \"$percent%\"") if $percent ;
}
sub update_netstats {
## Gather disk read/write stats.
my $rxbyts = my $txbyts = 0 ;
foreach my $netdev (keys %{$lxsdata->{netstats}}) {
next if $netdev eq "lo" ;
$rxbyts += $lxsdata->{netstats}->{$netdev}->{rxbyt} ;
$txbyts += $lxsdata->{netstats}->{$netdev}->{txbyt} ;
} ;
if ($rxbyts > $txbyts) {
## Reformat rx to use KB/s or MB/s .
my $netrx = $rxbyts < 1048576 ?
sprintf "%4.0fK", $rxbyts/1024 :
sprintf "%4.1fM", $rxbyts/1048576 ;
$netrx =~ s/(\d.*)$/\+$1/ ;
#say STDERR $netrx ;
## Update the panlebars net field
sendto_panelbar("net Title \"$netrx\"") ;
} else {
## Reformat tx to use KB/s or MB/s .
my $nettx = $txbyts < 1048576 ?
sprintf "%4.0fK", $txbyts/1024 :
sprintf "%4.1fM", $txbyts/1048576 ;
$nettx =~ s/(\d.*)$/\-$1/ ;
#say STDERR $nettx ;
## Update the panlebars net field
sendto_panelbar("net Title \"$nettx\"") ;
} ;
}
sub update_cpustats {
## The cpu equation for Sys::Statistics::Linux::CpuStats is :-
## user + system + iowait = 100 - idle = total
## Here, we are seeking total cpu minus iowait.
my $user = $lxsdata->{cpustats}->{cpu}->{user} ;
my $system = $lxsdata->{cpustats}->{cpu}->{system} ;
my $cpu = rounded($user + $system) ;
$cpu = 99 if $cpu == 100 ;
sendto_panelbar("cpu Title \"$cpu%\"") ;
}
sub update_datetime {
## Get current time + update the seconds field.
my $seconds = sprintf "%02d", $t->sec ;
sendto_panelbar("secs Title $seconds") ;
sendto_timedate("secs Title $seconds") ;
## Update the hours/minutes field.
if ($t_lastupdate and $t->min != $t_lastupdate->min) {
my $minutes = sprintf "%02d:%02d:", $t->hour, $t->min ;
sendto_panelbar("mins Title \"$minutes\"") ;
sendto_timedate("mins Title \"$minutes\"") ;
} ;
## Update the month/day field.
if ($t_lastupdate and $t->mday != $t_lastupdate->mday) {
say STDERR "qqqq" ;
my $date = sprintf "%d %s", $t->mday, $t->monname ;
#say STDERR "::: date == $date" ;
sendto_panelbar("date Title \"$date\"") ;
sendto_timedate("date Title \"$date\"") ;
} ;
## Update all if this is the first time.
if (not $t_lastupdate) {
my $minutes = sprintf "%02d:%02d:", $t->hour, $t->min ;
my $date = sprintf "%d %s", $t->mday, $t->monname ;
#say STDERR "::: date == $date" ;
sendto_panelbar("mins Title \"$minutes\"") ;
sendto_timedate("mins Title \"$minutes\"") ;
sendto_panelbar("date Title \"$date\"") ;
sendto_timedate("date Title \"$date\"") ;
} ;
}
sub update_desktop {
my $currentdesktop = shift ;
return 0 if $currentdesktop == $lastdesktop ;
sendcmd("Colorset $desktop_cs{$currentdesktop} bg $underline_on") ;
sendcmd("Colorset $desktop_cs{$lastdesktop} bg $underline_off") ;
$lastdesktop = $currentdesktop ;
}
sub sendcmd { foreach (@_) { $module->send($_) } }
## To send an fvwm command to the PanelBar module.
sub sendto_panelbar {
foreach (@_) {
my $cmd = "SendToModule $panel_modname ChangeButton " . $_ ;
#say STDERR "::: $cmd" ;
$module->send($cmd) ;
}
return 1 ;
}
## To send an fvwm command to the TimeAndDate module.
sub sendto_timedate {
foreach (@_) {
my $cmd = "SendToModule $timedate_modname ChangeButton " . $_ ;
$module->send($cmd) ;
}
return 1 ;
}
## Cribbed from Math::Round
sub rounded {
my $x;
my $half = 0.50000000000008 ;
my @res = map {
if ($_ >= 0) { POSIX::floor($_ + $half); }
else { POSIX::ceil($_ - $half); }
} @_;
return (wantarray) ? @res : $res[0];
}
## Cribbed from Math::Round
sub nearest {
my $targ = abs(shift);
my $half = 0.50000000000008 ;
my @res = map {
if ($_ >= 0) { $targ * int(($_ + $half * $targ) / $targ); }
else { $targ * POSIX::ceil(($_ - $half * $targ) / $targ); }
} @_ ;
return (wantarray) ? @res : $res[0] ;
}
sub ceiling {
my ($num, $max) = @_ ;
$num = 0 unless defined $num ;
$num = $num > $max ? $max : $num ;
$num = nearest(1, $num*99/$max) ;
return $num ;
}
<file_sep>/.fvwm/lib/Thumbnail
#!/usr/bin/perl
# vim: syntax=perl:
## Useful webpages :-
## http://www.imagemagick.org/script/command-line-processing.php
## http://www.imagemagick.org/script/perl-magick.php
use strict ;
use warnings ;
use v5.18 ;
use lib `fvwm-perllib dir`;
use FVWM::Module;
use Data::Dump qw( dump ) ;
use Image::Magick ; ## libimage-magick-perl
use Path::Tiny ;
use File::stat ;
use Try::Tiny ;
use IPC::Run qw( run timeout ) ;
## Target geometry for thumbnail icons.
my $width = 205 ;
my $height = 120 ;
## Number of times to attempt window capture
my $tries = 3 ;
## Expiration time in seconds for saved thumbnails.
my $expires = 60 ;
## Destination folder for thumbnail icons.
my $folder = "$ENV{FVWM_THUMBS}" ;
## Enable/disable logging
my $logfile = path("/tmp/Thumbnail.log") ;
unlink $logfile ;
my $logger = "yes" ;
#my $logger = "" ;
my $module = new FVWM::Module(
Name => 'Thumbnail',
Debug => 0,
);
my $modname = $module->name ;
## Fvwm module reads config before listening for SendToModule cmnds.
##
$module->add_handler(M_CONFIG_INFO, \&read_config) ;
$module->add_handler(M_END_CONFIG_INFO, sub {
#$module->show_message("[$modname] read config finished]") ;
$module->addHandler(M_STRING, \&process_cmd);
});
#$module->show_message("Starting");
$module->send("Send_ConfigInfo");
$module->event_loop ;
#### SUBROUTINES
## Two functions to read and process entries from the module config
## during startup.
##
sub read_config {
my ($module, $event) = @_ ;
return unless $event->_text =~ /^\*$modname(.*)$/ ;
process_config($1);
}
sub process_config {
my ($s) = @_ ;
my ($option, $args) = $s =~ /\s*(\w+)\s*(.*)/;
my %opts = (
Width => sub { $width = $args },
Height => sub { $height = $args },
Tries => sub { $tries = $args },
Expire => sub { $expires = $args },
) ;
if (defined $opts{$option}) {
$opts{$option}() ;
} else {
$module->showMessage("Unknown option \"$option\"");
}
}
## To process and run commands received via SendToModule cmnds.
##
sub process_cmd {
my ($module, $event) = @_ ;
my ($s) = $event->_text ;
my ($command, $arg) = $s =~ /\s*(\w+)\s*(.*)/ ;
my %cmd = (
capture => sub { thumbnail($arg) },
iconify => sub { iconify($arg) if thumbnail($arg) },
) ;
if (defined $cmd{$command}) {
logger("===========================") ;
logger("$modname: process_cmd() : $command $arg") ;
$cmd{$command}() ;
#$module->showMessage("debug: $command");
#logger("$modname: process_cmd() : $command $arg") ;
} else {
logger("$modname: process_cmd() : unknown : $command $arg") ;
#$module->showMessage("unknown command \"$command $arg\"");
}
}
## To capture, thumbnail and iconify the current window.
##
sub iconify {
## Window id of target window, converted to decimal.
my $widhex = shift ;
my $wid = hex($widhex) ;
## Destination filename for the thumbnail.
my $pngfile = "$folder/$widhex.png" ;
## Tell fvwm to iconify the window.
$module->send("WindowStyle Icon $pngfile", $wid) ;
$module->send("Iconify True", $wid) ;
}
## To thumbnail the current window, if existing icon has not expired.
##
sub thumbnail {
## Window id of target window, converted to decimal.
my $widhex = shift ;
my $wid = hex($widhex) ;
## Destination filename for the thumbnail.
my $pngfile = "$folder/$widhex.png" ;
if ( !-e $pngfile or expired($pngfile)) {
logger("$modname: thumbnail() : new thumb required") ;
## capture image of current window
my $thumb = capture($widhex) ;
logger("$modname: capture() failed ") if not $thumb ;
return 0 if not $thumb ;
logger("$modname: capture() succeeded ") ;
## Reduce to thumbnail size.
return 0 if $thumb->Thumbnail(geometry => "${width}x$height^") ;
logger("$modname: im->thumbnail() succeeded ") ;
## Crop to the correct size
return 0 if $thumb->Crop(geometry => "${width}x$height+0+0") ;
logger("$modname: im->crop() succeeded ") ;
## Save the finished thumbnail.
open(IMAGE, ">$pngfile") ;
return 0 if $thumb->Write(
file => \*IMAGE,
filename => $pngfile,
quality => 100,
) ;
logger("$modname: im->write succeeded") ;
} else {
logger("$modname: current thumb valid") ;
}
return 1 ;
}
## To capture an image of the current window.
sub capture {
## Window id of target window, converted to decimal.
my $widhex = shift ;
my $wid = hex($widhex) ;
## Destination filename for the thumbnail.
my $pngfile = "$folder/$widhex.png" ;
my $xwdfile = "$folder/$widhex.xwd" ;
## IMagick always returns undef unless in error.
my $thumb = Image::Magick->New() ;
my $err ;
foreach (0 .. $tries) {
$err = 1 ;
logger("$modname: begin capture() ") ;
my $t = timeout(2) ;
my $out = my $in = my $stderr = "" ;
unlink $xwdfile ;
my @cmd = ("xwd", "-silent", "-nobdrs", "-id",
$wid, "-out", $xwdfile ) ;
my $excp = try {
run \@cmd, \$in, \$out, \$stderr, $t ;
} catch { "" } ;
## If xwd cmnd produces error, then repeat again.
if ($stderr or not -r $xwdfile) {
logger("$modname: capture() : xwd failed") ;
next ;
}
## If xwd file cannot be opened, then repeat again.
if (not open(IMAGE, $xwdfile)) {
logger("$modname: open() xwdfile failed") ;
next ;
}
unlink $xwdfile ;
## If PerlMagic successfully read the png, then continue.
$err = $thumb->Read(file=>\*IMAGE);
close(IMAGE);
logger("$modname: im->Read() fails for xwdfile") if $err ;
last if not $err ;
}
## Return early if the screenshot operation failed.
if ($err) {
logger("$modname: capture() failed after $tries tries") ;
return 0 ;
} else {
return $thumb
}
}
## Return 1 if $file was modified more that $expired seconds ago.
##
sub expired {
my $file = shift ;
my $diff = time() - stat($file)->mtime ;
if ($diff > $expires) { return 1 } else { return 0 } ;
}
sub logger {
return 0 unless $logger ;
my $msg = shift ;
$msg .= "\n" ;
$logfile->append_utf8($msg) ;
}
<file_sep>/.fvwm/lib/menus/RadioMenu
#!/usr/bin/perl
## Using mpv instead of mpg123 since I also listen to AAC streams.
use utf8 ;
use strict ;
use warnings ;
use v5.20 ;
use lib `fvwm-perllib dir`;
use FVWM::Module;
use Path::Tiny ;
use Data::Dump qw( dump ) ;
## To send commands to fvwm
my $module = new FVWM::Module(
Name => 'RadioMenu',
Debug => 0,
);
## This module's name.
my $modname = $module->name ;
## Action requested by user.
my $command = $ENV{ARG1} ;
## Index number of the selected station
my $index = $ENV{ARG2} || 0 ;
## Config file for radio stations etc.
my $config = path("$ENV{FVWM_USERDIR}/.radiorc") ;
## Name of menus to use for fvwm commands.
my $menuname = "RadioMenu" ;
my $menuname_alt = "RadioMenuTitled" ;
## Equals zero if radio is stopped.
my $status = if_playing() ;
## Tick icon used for station currently playing
my $tickicon = "%mm_tick.png%" ;
## Store radio station info to an array of hashes.
my $num = 0 ;
my @radios = () ;
foreach ($config->lines) {
if (/(^\w.+),(\w.+),(http.+),(http[^\s]+)\s*$/) {
$radios[$num]->{notiflabel} = $1 ;
$radios[$num]->{menulabel} = $2 ;
$radios[$num]->{url} = $3 ;
$radios[$num++]->{stream} = $4 ;
}
}
my $index_max = $num ;
my $index_next = ($index+1)%$index_max ;
my $index_previous = ($index-1)%$index_max ;
#$index_next = 0 if $index_next == $index_max ;
## say STDERR "index : $index" ;
## say STDERR "index_max : $index_max" ;
## say STDERR "index_next : $index_next" ;
## say STDERR "index_previous : $index_previous" ;
#### Processe the input command
my %cmd = (
menu => sub { open_menu() },
stop => sub { kill_radio() },
play => sub { play_radio($index) },
next => sub { play_radio($index_next) },
previous => sub { play_radio($index_previous) },
) ;
if (defined $cmd{$command}) { $cmd{$command}()
} else { $module->showMessage("$modname: unknown command \"$command\"") }
exit ;
#### SUBROUTINES
sub sendcmd {
foreach (@_) {
my $msg = "AddToMenu $menuname $_" ;
$module->send($msg) ;
$msg = "AddToMenu $menuname_alt $_" ;
$module->send($msg) ;
#$module->showMessage("debug: $msg") ;
}
}
## Returns 0 if the mpv radio is not playing.
sub if_playing {
my $pattern = "^mpv --no-ytdl --no-terminal *--cache=auto --cache-initial=0" ;
my $mpv = readpipe("pgrep -f \"$pattern\" | wc -l ") ;
chomp $mpv ;
return $mpv ;
}
sub kill_radio {
my $pattern = "'^mpv --no-ytdl --no-terminal *--cache=auto --cache-initial=0 '" ;
readpipe("pkill -f $pattern 2>&1 1>/dev/null") ;
}
sub play_radio {
my $idx = shift ;
my $lab = $radios[$idx]->{notiflabel} ;
my $url = $radios[$idx]->{stream} ;
my $notif = "$lab" ;
my $notif_cmd = 'FF-Notify 3 Nop "' . $notif . '"' ;
my $mpv_cmd = 'mpv --no-ytdl --no-terminal --cache=auto ' ;
$mpv_cmd .= '--cache-initial=0 "' . $url . '" 2>&1 1>/dev/null' ;
## If the radio is already playing, then stop it.
kill_radio() ;
## Store the index of the selected radio
$module->send("InfoStoreAdd radio_index $idx") ;
## FvwmForm Notify the radio station
$module->send( $notif_cmd ) ;
## mpv command to start the radio
exec("$mpv_cmd ") ;
}
## Build a radio menu for fvwm.
sub open_menu {
## A menu entry for each radio station.
for ($num = 0 ; $num <= $#radios ; $num++) {
my $label = $radios[$num]->{menulabel} ;
## a tick icon for the currently playing station only
my $icon = $status && $num == $index ? $tickicon : "" ;
## this fvwm cmnd to run if the menu entry is selected
sendcmd("\"$icon$label\" PlayRadio $num") ;
}
## Menu separator
sendcmd("\"\" Nop") ;
## if mpv radio is playing, then do this, else...
if ( $status ) {
my $icon = "%mm_information.png%" ;
my $cmd = "OpenFirefoxTab \"$radios[$index]->{url}\"" ;
sendcmd("\"$icon&Now Playing\" $cmd") ;
$icon = "%mm_application-exit.png%" ;
sendcmd("\"${icon}&Stop Radio\" StopTrack") ;
} else {
## if mpv radio not playing
my $icon = "%mm_gvim.png%" ;
sendcmd("\"${icon}&Edit config\" OpenVim $config") ;
}
}
<file_sep>/.fvwm/lib/menus/UrlMenu
#!/usr/bin/perl
use utf8 ;
use strict ;
use warnings ;
use v5.18 ;
use Data::Dump qw( dump ) ;
use lib `fvwm-perllib dir`;
use FVWM::Module;
my $menuname = "UrlMenu" ;
my $menutitle = "Url Menu" ;
## A file where urls are listed for youtube-dl
my $ytlist = $ENV{ARG1} ;
## Num of urls in list.
my $ytnum = 0 ;
if (-r $ytlist) {
$ytnum = readpipe("wc -l <$ytlist") ;
chomp $ytnum ;
}
my $module = new FVWM::Module(
Name => 'UrlMenu',
Debug => 0,
);
my $modname = $module->name ;
## Vars that define which menu apps get included by default.
my ($w3m, $dillo ) = (1) x 2 ;
my ($feh, $sxiv, $mpv, $ytdl, $live) = (0) x 5 ;
## Get the current url from xsel. Exit if not a valid url.
my $url = get_xsel_url() ;
exit if not $url =~ m{^https?://} ;
## get the url's domain
$url =~ m{^https?://(www[.])?([^/]+).*$} ;
my $dom = $2 ;
my $type = "other" ;
## image type
if ($url =~ m{^.+[.](jpg|png)([?].*)?$}) {
#say STDERR "type == image" ;
$type = "image" ;
$w3m = 0 ;
$dillo = 0 ;
$feh = 1 ;
} elsif ($url =~ m{^.+[.]gif([?].*)?$}) {
#say STDERR "type == image" ;
$type = "gif" ;
$w3m = 0 ;
$dillo = 0 ;
$sxiv = 1 ;
## video type
} elsif ($url =~ m{^.+[.](mp4|avi|mkv)([?].*)?$}) {
$type = "video" ;
$w3m = 0 ;
$dillo = 0 ;
$mpv = 1 ;
## reddit domain
} elsif ($dom eq "reddit.com") {
$type = "reddit" ;
$w3m = 0 ;
## youtube domain
} elsif ($dom eq "youtube.com" or $dom eq "youtu.be") {
$type = "youtube" ;
$w3m = 0 ;
$dillo = 0 ;
$ytdl = 1 ;
$mpv = 1 ;
$live = 1 ;
## livestreamer domains
} elsif ($dom eq "chaturbate.com") {
$type = "livestream" ;
$w3m = 0 ;
$dillo = 0 ;
$live = 1 ;
}
## Add entries to the menu.
addentry("\"$menutitle\" Title") ;
addentry("\"%mm_firefox.png%New &Tab\" OpenFirefoxTab") ;
addentry("\"%mm_firefox.png%New &Window\" OpenFirefoxWindow") ;
addentry("\"%mm_firefox.png%&Alt Window\" OpenFirefoxWindowAlt") ;
addentry("\"%mm_dillo.png%&Dillo\" OpenDillo") if $dillo ;
addentry("\"%mm_browser.png%W3&m\" OpenW3m") if $w3m ;
addentry("\"%mm_mpv.png%Play &Video\" MPVPlayVideo") if $mpv ;
addentry("\"%mm_mpv.png%Play A&udio\" MPVPlayAudioOnly") if $mpv ;
addentry("\"%mm_mpv.png%&Livestream\" PlayLivestreamer") if $live ;
addentry("\"%mm_images.png%&View Image\" OpenFeh") if $feh ;
addentry("\"%mm_images.png%&View Image\" OpenSxiv") if $sxiv ;
addentry("\"\" Nop") ;
#addentry("\"\" Nop") if not $ytdl and not $rtv ;
addentry("\"%mm_play.png%To &Ytdl ($ytnum)\" AddYtdl") if $ytdl ;
addentry("\"%mm_urxvt.png%To Hosts\" AddHosts") if not $ytdl ;
#addentry("\"%mm_urxvt.png%To Hosts\" AddHosts") if not $ytdl and not $rtv ;
sub addentry {
foreach (@_) {
my $msg = "AddToMenu $menuname $_" ;
$module->send($msg) ;
}
}
sub get_xsel_url {
my @z = readpipe("timeout 1 xsel -ob") ;
return 0 if not defined $z[0] ;
my $xsel = $z[0] ;
chomp $xsel ;
return $xsel ;
}
<file_sep>/bin/tmux-thepiratebay
#!/bin/bash
tmux kill-session -t piratebay 2>&1 1>/dev/null
tmux new-session -d -s piratebay
sleep 1
tmux new-window -t piratebay:1 -n mvgroup -k "sleep 2 && w3m -cookie https://thepiratebay.org/user/MVGroup/"
tmux new-window -t piratebay:2 -n CenaCme -k "sleep 2 && w3m -cookie https://thepiratebay.org/user/CenaCme/"
tmux new-window -t piratebay:3 -n snowhiter -k "sleep 2 && w3m -cookie https://thepiratebay.org/user/Snowhiter/"
tmux new-window -t piratebay:4 -n tvteam -k "sleep 2 && w3m -cookie https://thepiratebay.org/user/TvTeam/"
tmux new-window -t piratebay:5 -n connor17 -k "sleep 2 && w3m -cookie https://thepiratebay.org/user/connor17/"
#tmux new-window -t piratebay:1 -n stateofmind -k "sleep 2 && w3m -cookie https://thepiratebay.org/user/stateofmind80/"
#tmux new-window -t piratebay:7 -n srigga -k "sleep 2 && w3m -cookie -N +40 https://kat.cr/user/SRIGGA/uploads/"
#tmux new-window -t piratebay:8 -n bubonic -k "sleep 2 && w3m -cookie -N +40 https://kat.cr/user/bubonic420/uploads/"
#tmux new-window -t piratebay:9 -n bullrout -k "sleep 2 && w3m -cookie -N +40 https://kat.cr/user/Bullrout/uploads/"
tmux new-window -t piratebay:6 -n marks -k "sleep 2 && w3m -cookie -B"
tmux select-window -t piratebay:1
tmux attach -t piratebay
# tmux new-window -t piratebay:5 -n redbaron -k "sleep 2 && w3m -cookie https://thepiratebay.org/user/RedBaron58/"
<file_sep>/.fvwm/lib/WallBrowser
#!/usr/bin/perl
## I tried to rewrite this using ->event_loop and ->terminate, to query
## FVWM's configuration database to obtain its settings and vars. But
## it confounded me. It seems that commands were sent to FVWM, but only
## processed by FVWM after the initial wallpaper menu was exited. If
## this module was not part of a MissingSubmenuFunction menu, I doubt
## this problem would occur. So I have now resolved to not obtain this
## module'ssettings from the configuration database.
use utf8 ;
use strict ;
use warnings ;
use v5.20 ;
use lib `fvwm-perllib dir`;
use FVWM::Module;
use Image::Magick ;
#use Data::Dump qw( dump ) ;
my $module = new FVWM::Module(
Name => 'WallBrowser',
Debug => 0,
);
## Read in the current folder for this dynamic menu
my $dir = $ENV{ARG1} ;
## Color for border around thumbnail.
my $wallthumb_border_color = $ENV{ARG2} ;
## Folder in which to store wallpaper thumbnails.
my $thumbdir = $ENV{FVWM_WALLTHUMBS} ;
## Menu icon for folder entries in the menu.
my $icon_dir = "$ENV{HOME}/.icons/AwOken/clear/24x24/places/awoken/awokenclear/folder-photos.png" ;
## Long menu labels get truncated. Maximum length for labels in chars.
my $charmax = 25 ;
## Fvwm menustyle name for this menu.
my $menustyle = "WallpaperMenuStyle" ;
## Cmnd string used to generate the folder menu.
my $menucmd = 'fvwm-menu-directory --icon-file __PIXMAP__ ' ;
$menucmd .= "--icon-dir \"$icon_dir\" --links --dir \"$dir\" " ;
$menucmd .= '--command-file="RootCrop \"%f\"" ' ;
$menucmd .= '--func-name WallBrowser ' ;
## Magick properties to create a nice thumbnail.
my $wallthumb_geom = "80x40!" ;
my $wallthumb_border_width = 2 ;
## my $wallthumb_pad_color = "grey9" ;
## my $wallthumb_pad_geom = "x4" ;
my $quality = 99 ;
## Create thumbs for all images in the current folder.
foreach my $wall (glob("$dir/*.{png,jpg}")) {
## generate a filename for the thumbnail.
my $thumb = $wall ;
$thumb =~ s/^.*\/// ;
$thumb =~ s/[.]\w\w\w$/.png/ ;
$thumb = "$thumbdir/$thumb" ;
## Goto next wally if a good thumb already exists.
if (-e $thumb) {
my @wallstat = stat($wall) ;
my @thumbstat = stat($thumb) ;
next if $wallstat[9] <= $thumbstat[9] ;
unlink $thumb ;
}
## Create a new thumb.
thumbificate($wall, $thumb) ;
say STDERR "WallThumb : $thumb" ;
}
foreach my $line (`$menucmd`) {
chomp $line ;
## Discarding unwanted menu entries
if ($line =~ /Nop$/ or $line =~ /Exec cd/) {
next
## Add a title to the menu.
} elsif ($line =~ /^AddToMenu\s+(\S+)/) {
sendcmd($line) ;
sendcmd("ChangeMenuStyle $menustyle $1") ;
## For each wallpaper entry, substitite in a thumbicon.
} elsif ($line =~ /^.*__PIXMAP__%([^"]*)([.]\w\w\w)["](.*)$/) {
## Make menu entry with thumbicon, and send to fvwm.
my $out = '+ "%' . "$thumbdir/$1.png%\"$3" ;
sendcmd($out) ;
## Add a ">" to all folder entries.
} elsif ($line =~ /^(.*\"%\/[^"]+)(\"\sPopup.*)$/) {
sendcmd("$1\t>$2") ;
} else {
sendcmd($line) ;
}
}
exit ;
#### SUBROUTINES
sub thumbificate {
my $wall = shift ;
my $thumb = shift ;
## Abort thumb if magick cannot read the wallpaper.
my $err = 1 ;
return 0 if not open(WALL, $wall) ;
my $image = Image::Magick->New(quality => $quality) ;
$err = $image->Read(file=>\*WALL) ;
close(WALL) ;
return 0 if $err ;
## Create thumbnail
return 0 if $image->Thumbnail(
geometry => $wallthumb_geom,
) ;
## Add a colored border to the thumb
return 0 if $image->Border(
width => $wallthumb_border_width,
height => $wallthumb_border_width,
bordercolor => $wallthumb_border_color,
) ;
## ## Add another border to top and bottoms sides,
## ## but using the menus background color.
## return 0 if $image->Border(
## bordercolor => $wallthumb_pad_color,
## geometry => $wallthumb_pad_geom,
## ) ;
## Save the thumb into its storage folder.
$err = 1 ;
open(THUMB, ">$thumb") ;
$err = $image->Write(
file => \*THUMB,
filename => $thumb,
quality => $quality,
) ;
close THUMB ;
if ($err) { return 0 } else { return 1 } ;
}
sub sendcmd {
foreach (@_) {
$module->send($_) ;
#$module->showMessage("debug: $_") ;
}
}
<file_sep>/.fvwm/lib/panelbar/UpdateDiskUsagePanel
#!/usr/bin/perl
## CURRENT BEST SCRIPT
## Useful webpages :-
## http://www.imagemagick.org/script/command-line-processing.php
## http://www.imagemagick.org/script/perl-magick.php
## http://www.imagemagick.org/Usage/draw/
use strict ;
use warnings ;
use utf8 ;
use v5.22 ;
use lib `fvwm-perllib dir` ;
use FVWM::Module ;
use Image::Magick ; ## libimage-magick-perl
use Path::Tiny ; ## libpath-tiny-perl
use Data::Dump qw( dump ) ;
## Name of the FvwmButtons weather panel.
my $panelmodname = "DiskUsagePanel" ;
## Output image filepath
my $outfile = path("$ENV{FVWM_USERDIR}/images/panel-disk-usage.png") ;
## Output image size
my $canvas_geometry = "290x150" ;
## Progress bar size.
my $barwidth = 260 ;
my $barheight = 8 ;
## Imagemagick quality setting.
my $quality = 99 ;
## Path to harddrive icon.
my $icondir = "$ENV{FVWM_USERDIR}/images/panelbar/diskusage" ;
my $iconfile = "panel-hdd.png" ;
## Size of hdd icon
my $iconsize = "40x40" ;
## Start the FVWM module.
my $modname = "UpdateDiskUsagePanel" ;
my $module = new FVWM::Module(
Name => $modname,
Debug => 0,
) ;
## Get FVWM colorset data.
my $cs_tracker = $module->track("Colorsets") ;
my $cs_hash = $cs_tracker->data ;
$cs_tracker->stop ;
#### COLORS
## Color for canvas background.
my $canvas_bg = "gray9" ;
## Colors for text, bold and plain.
my $text_color = get_color(325,"fg") ;
my $text_bold_color = get_color(326,"fg") ;
## Colors and geometry of progress bars.
my $bar_fg = get_color(327,"fg") ;
my $bar_bg = get_color(327,"bg") ;
## Descriptors for large and small fonts.
my $fontdir = "/usr/share/fonts/X11/misc" ;
my $fontsmall = {
file => "$fontdir/ter-u16b_iso-8859-1.pcf.gz", width => 8,
} ;
## Store disk usage info for rootfs(btrfs) and data(ext4) partitions.
my $btrfs_max = 1 ;
my $btrfs_alloc = 1 ;
my $btrfs_alloc_perc = 1 ;
my $btrfs_used = 1 ;
my $btrfs_used_perc = 1 ;
my $data_max = 1 ;
my $data_used = 1 ;
my $data_perc = 1 ;
update_disk_usage() ;
## Create blank canvas.
my $image = Image::Magick->new ;
$image->Set(size => $canvas_geometry) ;
$image->ReadImage("canvas:$canvas_bg") ;
#### Draw the rootfs partition (/dev/sda7)
## Overlay canvas with two harddrive icons.
my $icon = load_image("$icondir/$iconfile") ;
$icon->AdaptiveResize( geometry => $iconsize) ;
$image->Composite(image => $icon, x => 15, y => 10) ;
## Annotate with disk usage details.
my $text = "ROOT, /dev/sda7, btrfs" ;
my $xpos = 67 ; my $ypos = 25 ;
$image = left_justified($xpos, $ypos, $text_color, $fontsmall, $text, $image) ;
$text = "${btrfs_used}Gb used of ${btrfs_max}Gb - $btrfs_used_perc%" ;
$xpos = 67 ; $ypos = 42 ;
$image = left_justified($xpos, $ypos, $text_color, $fontsmall, $text, $image) ;
## Add progressbar.
$image = draw_progress(15, 58, $btrfs_used_perc, $image) ;
#### Draw the data partition (/dev/sda9)
## Overlay hdd icon.
$icon = load_image("$icondir/$iconfile") ;
$icon->AdaptiveResize( geometry => $iconsize) ;
$image->Composite(image => $icon, x => 15, y => 80) ;
## Annotate data usage details.
$text = "DATA, /dev/sda9, ext4" ;
$xpos = 67 ; $ypos = 95 ;
$image = left_justified($xpos, $ypos, $text_color, $fontsmall, $text, $image) ;
$text = "${data_used}Gb used of ${data_max}Gb - $data_perc%" ;
$xpos = 67 ; $ypos = 112 ;
$image = left_justified($xpos, $ypos, $text_color, $fontsmall, $text, $image) ;
## Add progressbar
$image = draw_progress(15, 128, $data_perc, $image) ;
## Save the finished thumbnail.
save_image($image, $outfile) ;
## Update image in the FvwmButtons module.
my $cmd = "SendToModule $panelmodname ChangeButton dicon Icon " ;
$cmd .= $outfile->basename ;
$module->send($cmd) ;
exit ;
#### SUBROUTINES
sub get_color {
my $cs_num = shift ;
my $opt = shift ;
my $color = $cs_hash->{$cs_num}->{$opt} ;
return sprintf('#%x',$color) ;
}
sub load_image {
my $err = 1 ;
my $image = Image::Magick->New() ;
my $imgfile = shift ;
open(IMAGE, $imgfile) or return 0 ;
$err = $image->Read(file=>\*IMAGE);
close(IMAGE);
if ($err) { return 0 } else { return $image } ;
}
sub save_image {
my $image = shift ;
my $outfile = shift ;
open(IMAGE, ">$outfile") ;
return 0 if $image->Write(
file => \*IMAGE,
filename => $outfile,
quality => $quality,
) ;
return 1 ;
}
sub draw_progress {
my $xpos = shift ;
my $ypos = shift ;
my $pro1 = shift ;
my $img = shift ;
my $width ;
## Bar background
my $bar = Image::Magick->new ;
$bar->Set(size => "${barwidth}x$barheight") ;
$bar->ReadImage("canvas:$bar_bg") ;
$image->Composite(image => $bar, x => $xpos, y => $ypos) ;
## Progress bar
$width = int($pro1*$barwidth/99 + .5) ;
$bar = Image::Magick->new ;
$bar->Set(size => "${width}x$barheight") ;
$bar->ReadImage("canvas:$bar_fg") ;
$image->Composite(image => $bar, x => $xpos, y => $ypos) ;
return $image ;
}
sub left_justified {
my $xpos = shift ;
my $ypos = shift ;
my $color = shift ;
my $font = shift ;
my $text = shift ;
my $img = shift ;
return 0 if $img->Annotate(
x => $xpos,
y => $ypos,
gravity => "NorthWest",
font => $font->{file},
fill => $color,
text => $text,
) ;
return $img ;
}
sub update_disk_usage {
foreach (`sudo /root/bin/sudo-btrfs-fi-usage`) {
$btrfs_max = nearest(1, $1) if /Device\ssize:\s+([.0-9]+)GiB/ ;
$btrfs_alloc = nearest(.1, $1) if /Device\sallocated:\s+([.0-9]+)GiB/ ;
$btrfs_used = nearest(.1, $1) if /Used:\s+([.0-9]+)GiB/ ;
}
$btrfs_used_perc = nearest(1, $btrfs_used/$btrfs_max*99) ;
$btrfs_alloc_perc = nearest(1, $btrfs_alloc/$btrfs_max*99) ;
foreach (`df -h --output=source,size,used,pcent`) {
if (/sda9\s+(\d+)G\s+(\d+)G\s+(\d+)%$/) {
$data_max = $1 ;
$data_used = $2 ;
$data_perc = $3 ;
}
}
}
## Cribbed from Math::Round
sub nearest {
my $targ = abs(shift);
my $half = 0.50000000000008 ;
my @res = map {
if ($_ >= 0) { $targ * int(($_ + $half * $targ) / $targ); }
else { $targ * POSIX::ceil(($_ - $half * $targ) / $targ); }
} @_ ;
return (wantarray) ? @res : $res[0] ;
}
<file_sep>/bin/addcolor
#!/usr/bin/perl -w
use local::lib ;
use Term::ExtendedColor::Xresources qw( set_xterm_color ) ;
while (<>) {
if (/^\D*color(\d+):?\s+#?(\w+)/) {
set_xterm_color({ $1 => $2}) ;
}
}
# print "color$1: #$2\n" ;
# set_xterm_color({ $1 => $2}) if (/^\D*(\d+)\s+#?(\w+)/)
<file_sep>/.fvwm/lib/RootCrop
#!/usr/bin/perl
## Useful webpages :-
## http://www.imagemagick.org/script/command-line-processing.php
## http://www.imagemagick.org/script/perl-magick.php
use utf8 ;
use strict ;
use warnings ;
use v5.20 ;
use lib `fvwm-perllib dir`;
use FVWM::Module;
use Image::Magick ;
use Data::Dump qw( dump ) ;
## Filename of the uncropped wallpaper.
#my $img = $ARGV[$#ARGV] ;
my $img = $ENV{ARG1} ;
## Output filename for resized wallpaper.
my $out = "/tmp/fvwmwall.png" ;
## To get the width/height of the desktop.
my $module = new FVWM::Module(
Name => 'FvwmWallpaper',
Mask => M_CONFIG_INFO | M_END_CONFIG_INFO | M_STRING,
Debug => 0,
);
my $modname = $module->name ;
my $pg_tracker = $module->track("PageInfo") ;
my $pg_hash = $pg_tracker->data ;
my $vp_height = $pg_hash->{'vp_height'} ;
my $vp_width = $pg_hash->{'vp_width'} ;
my $vp_aspect = $vp_width / $vp_height ;
## Sanity checks
die("$modname filename not found") unless -r $img ;
die("$modname : cannot open image") if not open(IMAGE, $img) ;
## Exit unless perlMagic can read the image.
my $err = 1 ;
my $image = Image::Magick->New(quality => 1) ;
$err = $image->Read(file=>\*IMAGE) ;
close(IMAGE) ;
die("FvwmWall : imgmagick cannot read image") if $err ;
my $img_width = $image->Get('columns') ;
my $img_height = $image->Get('rows') ;
my $img_aspect = $img_width / $img_height ;
## Resize if img width is too small.
if ($vp_width > $img_width) {
my $hh = $vp_width / $img_aspect ;
return 0 if $image->AdaptiveResize(
width => $vp_width,
height => $hh,
) ;
$img_width = $image->Get('columns') ;
$img_height = $image->Get('rows') ;
$img_aspect = $img_width / $img_height ;
}
## Resize only if img height is too small.
if ($vp_height > $img_height) {
my $ww = $img_aspect * $vp_height ;
return 0 if $image->AdaptiveResize(
width => $ww,
height => $vp_height,
) ;
$img_width = $image->Get('columns') ;
$img_height = $image->Get('rows') ;
$img_aspect = $img_width / $img_height ;
}
## Correct the images aspect ratio via postbox cropping.
if ( $img_aspect < $vp_aspect ) {
my $hh = int($img_width/$vp_aspect) ;
my $y = int(($img_height-$hh)/2) ;
return 0 if $image->Crop(
geometry => "${img_width}x$hh+0+$y"
) ;
$img_height = $image->Get('rows') ;
} elsif ( $img_aspect > $vp_aspect ) {
my $ww = int($img_height*$vp_aspect) ;
#my $x = int($ww/2) ;
my $x = int(($img_width-$ww)/2) ;
return 0 if $image->Crop(
geometry => "${ww}x${img_height}+$x+0"
) ;
$img_width = $image->Get('columns') ;
}
$img_aspect = $img_width / $img_height ;
## Lastly, resize the image.
if ($vp_height < $img_height or $vp_width < $img_width) {
return 0 if $image->AdaptiveResize(
width => $vp_width,
height => $vp_height,
) ;
$img_width = $image->Get('columns') ;
$img_height = $image->Get('rows') ;
$img_aspect = $img_width / $img_height ;
}
## Save the finished thumbnail.
open(IMAGE, ">$out") ;
$err = $image->Write(
file=>\*IMAGE,
filename=>$out,
quality => 1
) ;
return 0 if $err ;
close IMAGE ;
#sendcmd("SaveWallInfo") ;
## -r option needed by RootTransparency colorsets.
system("fvwm-root -r $out") ;
sub sendcmd {
foreach (@_) {
$module->send($_) ;
}
}
<file_sep>/bin/tmux-main
#!/bin/sh
ssn=main_tmux
tmux kill-session -t $ssn 1>/dev/null 2>&1
tmux new-session -d -s $ssn 1>/dev/null 2>&1
tmux new-window -t $ssn:1 -k -n root
tmux new-window -t $ssn:2 -n alpha
tmux new-window -t $ssn:3 -n bravo
tmux new-window -t $ssn:4 -n charlie
tmux new-window -t $ssn:5 -n delta
tmux new-window -t $ssn:6 -n gamma
tmux split-window -v -p 40 -t $ssn:6
tmux select-pane -U -t $ssn:6
tmux select-window -t $ssn:1
tmux attach -t $ssn
<file_sep>/.fvwm/lib/UpdateProcesses
#!/usr/bin/perl
## http://stackoverflow.com/questions/3803850/how-do-i-decide-if-a-variable-is-numeric-in-perl
## http://www.perl.com/doc/FMTEYEWTK/is_numeric.html
use strict ;
use warnings ;
use v5.20 ;
use lib `fvwm-perllib dir` ;
use FVWM::Module ;
use List::MoreUtils qw( uniq natatime );
use Data::Dump qw( dump ) ;
use Path::Tiny ;
## Name of fvwmbuttons module that displays plots.
my $fbmodname = "Processes" ;
## Redirect stderr to /dev/null
my $log1 = path("/tmp/pppp1.log") ;
my $log2 = path("/tmp/pppp2.log") ;
#my $log3 = path("/tmp/pppp3.log") ;
#
#*STDERR = $log1 ;
## To send display cmnds to FVWM.
my $modname = "UpdateProcesses" ;
my $module = new FVWM::Module(
Name => $modname,
Debug => 0,
) ;
my @label = (0) x 9 ;
my @value = (0) x 9 ;
## Start conky.
my $conkyrc = "/tmp/fvwm/conkyrc" ;
write_conkyrc() ;
system("pkill -f \"conky.*$conkyrc\"") ;
#open(CONKY, "conky -c $conkyrc 2>/dev/null | ") || die "CONKY failed. \n" ;
open(CONKY, "conky -c $conkyrc 2>/dev/null | tee /tmp/zzzz | ") || die "CONKY failed. \n" ;
my $cnt = 0 ;
while (<CONKY>) {
my $idx = 0 ;
my @labelx = () ;
my @valuex = () ;
## Strip any whitespace padding, and store as array.
$_ =~ s/\s*:::\s*/:::/g ;
my @arx = split(/:::|\n/) ;
## Check for size of arx. If not 0 to 27, then next
# foreach (@arx) {
# #$_ = $1 if $_ =~ /(\S.*\S)/ ;
# $_ =~ s/^\s*// ;
# $_ =~ s/\s*$// ;
# }
my $doublets = natatime 2, @arx ;
while (my ($name, $usage) = $doublets->()) {
if ($name !~ /^\w+/ ) {
say STDERR "name = $name" ;
next ;
}
$usage += 0 ;
if ($usage !~ /^\d+\.?\d*$/) {
say STDERR "usage = :$usage:" ;
next ;
}
}
my @cpux = my @memx = my @iox = () ;
my @cpu_data = @arx[0..5] ;
my @mem_data = @arx[6..11] ;
my @ior = @arx[12..19] ;
my @iow = @arx[20..27] ;
my $msg = "$cnt\t" ;
$msg .= join(':::',@cpu_data, @mem_data, @ior,@iow) ;
$msg .= "\n" ;
$log1->append($msg) ;
## Parse cpu data into formatted strings (@items)
$doublets = natatime 2, @cpu_data ;
while (my ($name, $usage) = $doublets->()) {
$labelx[$idx] = $name ;
$valuex[$idx] = sprintf( '%.1f', nearest(.1, $usage) ) ;
$idx++ ;
}
## Parse memory data into formatted strings (@items)
$doublets = natatime 2, @mem_data ;
while (my ($name, $usage) = $doublets->()) {
$labelx[$idx] = $name ;
$valuex[$idx] = unit_convert($usage) ;
$idx++ ;
}
my %done = () ;
for (1..3) {
my $name ;
my $usage ;
## Remove processes that have appeared once already.
while (defined $done{$iow[0]}) { splice @iow, 0, 2 } ;
while (defined $done{$ior[0]}) { splice @ior, 0, 2 } ;
my $rd = defined($ior[1]) ? $ior[1] : 0 ;
my $wr = defined($iow[1]) ? $iow[1] : 0 ;
if ($wr >= $rd and $wr) {
$name = shift @iow ;
$usage = shift @iow ;
$usage = "+" . unit_convert($usage) ;
} elsif ($rd) {
$name = shift @ior ;
$usage = shift @ior ;
$usage = "-" . unit_convert($usage) ;
} else {
$name = "null" ;
$usage = 0 ;
}
$done{$name} = 1 ;
$labelx[$idx] = $name ;
$valuex[$idx] = $usage ;
$idx++ ;
}
$msg = "$cnt\t" ;
for my $num (0..8) {
$msg .= " [$num] $labelx[$num] : " ;
$msg .= "$valuex[$num]" ;
}
$msg .= "\n" ;
$log2->append($msg) ;
# for (my $num = 0 ; $num <= $#labelx ; $num++ ) {
# if ($labelx[$num] and $labelx[$num] ne $label[$num]) {
# my $cmnd = "SendToModule $fbmodname ChangeButton " ;
# $cmnd .= "label$num Title $labelx[$num]" ;
# my $retvar = $module->send($cmnd) ;
# say STDERR "ERROR" unless $retvar ;
# }
# if ($valuex[$num] and $valuex[$num] ne $value[$num]) {
# my $cmnd = "SendToModule $fbmodname ChangeButton " ;
# $cmnd .= "val$num Title $valuex[$num]" ;
# my $retvar = $module->send($cmnd) ;
# say STDERR "ERROR" unless $retvar ;
# }
# }
my $num = 0 ;
while ($num <= $#labelx && $labelx[$num] ne "null") {
if ($labelx[$num] ne $label[$num]) {
my $cmnd = "SendToModule $fbmodname ChangeButton " ;
$cmnd .= "label$num Title $labelx[$num]" ;
my $retvar = $module->send($cmnd) ;
say STDERR "ERROR" unless $retvar ;
}
if ($valuex[$num] ne $value[$num]) {
my $cmnd = "SendToModule $fbmodname ChangeButton " ;
$cmnd .= "val$num Title $valuex[$num]" ;
my $retvar = $module->send($cmnd) ;
say STDERR "ERROR" unless $retvar ;
}
$num++ ;
}
@label = @labelx ;
@value = @valuex ;
$cnt++ ;
}
sub unit_convert {
my $x = shift ;
my $u = ( $x < 999 ) ? $x :
( $x < 999499 ) ? nearest(1, $x/1000) : nearest(1, $x/1000000) ;
my $v = ( $x < 999 ) ? "B" : ( $x < 999499 ) ? "K" : "M" ;
return $u.$v ;
}
## Pasted and modified from Math::Round
sub nearest {
my $targ = abs(shift);
my $half = 0.50000000000008 ;
my @res = map {
if ($_ >= 0) { $targ * int(($_ + $half * $targ) / $targ); }
else { $targ * POSIX::ceil(($_ - $half * $targ) / $targ); }
} @_ ;
return (wantarray) ? @res : $res[0] ;
}
sub write_conkyrc {
open TXT, ">", $conkyrc || die " open conkyrc failed " ;
print TXT <<'EOF';
background no
out_to_console yes
cpu_avg_samples 1
update_interval 5
total_run_times 0
format_human_readable no
no_buffers yes
uppercase no
use_spacer none
short_units yes
top_cpu_separate false
top_name_width 20
TEXT
${top name 1}:::${top cpu 1}:::\
${top name 2}:::${top cpu 2}:::\
${top name 3}:::${top cpu 3}:::\
${top_mem name 1}:::${top_mem mem_res 1}:::\
${top_mem name 2}:::${top_mem mem_res 2}:::\
${top_mem name 3}:::${top_mem mem_res 3}:::\
${top_io name 1}:::${top_io io_read 1}:::\
${top_io name 2}:::${top_io io_read 2}:::\
${top_io name 3}:::${top_io io_read 3}:::\
${top_io name 4}:::${top_io io_read 4}:::\
${top_io name 1}:::${top_io io_write 1}:::\
${top_io name 2}:::${top_io io_write 2}:::\
${top_io name 3}:::${top_io io_write 3}:::\
${top_io name 4}:::${top_io io_write 4}:::\
EOF
close TXT ;
}
<file_sep>/.fvwm/lib/menus/MountMenu
#!/usr/bin/perl
use utf8 ;
use strict ;
use warnings ;
use v5.20 ;
use lib `fvwm-perllib dir`;
use FVWM::Module;
use List::MoreUtils qw(uniq) ;
#use Data::Dump qw( dump ) ;
my $module = new FVWM::Module(
Name => 'MountMenu',
Debug => 0,
);
## Fvwm menu name
my $menuname = "MountMenu" ;
my $menuname_alt = "MountMenuTitled" ;
## Icons used for yes and no
my $tick = "%mm_tick.png%" ;
my $notick = "%mm_null.png%" ;
## List of vfat devices
my @devs = get_vfat_devices() ;
## Number of tombs found and already mounted
my $tombcount = 0 ;
## Number of vfat found
my $vfatcount = 0 ;
my $cmd = my $item = my $label ;
## Menu entries for any detected vfat devices.
foreach my $device (@devs) {
## More info about the vfat device.
$label = get_device_label($device) ;
my $mnt = get_mountpoint($device) ;
## If device is mounted, then do this, else...
if ($mnt && -d $mnt) {
$cmd = "PUmount /dev/$device" ;
$item = $label ? "$tick$label\t$device"
: "$tick---\t$device" ;
} else {
## If the device is labeled, then do this, else...
if ($label) {
$cmd = "PMount /dev/$device \"$label\"" ;
$item = "$notick$label\t$device" ;
} else {
$cmd = "PMount /dev/$device" ;
$item = "$notick---\t$device" ;
}
}
sendcmd("\"$item\" $cmd") ;
$vfatcount++ ;
}
## Menu separator
if ($vfatcount > 0) { sendcmd("\"\" Nop") }
## Menu entries for files LUKS-encrypted by tomb
foreach my $tombfile ( glob("~/tomb/*.tomb") ) {
## Move to next entry if keyfile not found.
my $keyfile = "$tombfile.key" ;
next unless -e $keyfile ;
$label = $tombfile =~ s/^.*\///r ;
$label =~ s/[.]tomb$// ;
my $mntdir = "/media/$label" ;
## say STDERR "label : $label" ;
## say STDERR "mntdir : $mntdir" ;
## retvar equals 0 if tomb is already mounted
my $retvar = system("lsblk -lno MOUNTPOINT | grep -q \"$mntdir\"") ;
if ($retvar == 0 ) {
$tombcount++ ;
$cmd = "TombUmount \"$label\"" ;
$item = "$tick$label\tluks" ;
} else {
$cmd = "TombMount \"$tombfile\" \"$keyfile\"" ;
$item = "$notick$label\tluks" ;
}
sendcmd("\"$item\" $cmd") ;
}
## Menu separator
sendcmd("\"\" Nop") ;
## THe ethernet is either up or down.
my $ethernet_status = get_ethernet_status() ;
## Number of deb packages to upgrade
my $apt = get_apt_upgradable() ;
if ($ethernet_status eq "up") {
$item = "%mm_ethernet_up.png%Ethernet\tup" ;
$cmd = "Exec exec urxvt -e sudo /root/bin/sudo-ifdown-eth0" ;
} else {
$item = "%mm_ethernet_down.png%Ethernet\tdown" ;
$cmd = "Exec exec urxvt -e sudo /root/bin/sudo-ifup-eth0" ;
}
sendcmd("\"$item\" $cmd") ;
$item = "%mm_apt_update.png%&Apt Update\t$apt" ;
$cmd = "Exec exec urxvt -b 7 -T \"apt update\" -n \"apt update\"" ;
$cmd .= " -g 120x25 -e sudo /root/bin/sudo-apt-update" ;
sendcmd("\"$item\" $cmd") ;
## Only if any luks tombs are already mounted.
if ($tombcount > 0) {
sendcmd("\"\" Nop") ;
sendcmd("\"%mm_tomb.png%Tomb Slam\" TombSlam") ;
}
#### SUBROUTINES
sub get_vfat_devices {
my $cmd = 'lsblk -ln -o FSTYPE,NAME | grep -v sda | sed -rn "s/^vfat\\s+//p"' ;
my @devs = uniq(readpipe($cmd)) ;
chomp @devs ;
return @devs ;
}
sub get_mountpoint {
my $device = shift ;
my $cmd = "lsblk -ln -o NAME,MOUNTPOINT | sed -rn \"s/^$device\\s+//p\"" ;
my $mnt = readpipe($cmd) ;
chomp $mnt ;
return $mnt ;
}
sub get_ethernet_status {
my $ethernet_device = "eth0" ;
my $ethernet_file = "/sys/class/net/$ethernet_device/operstate" ;
my $ethernet_status = readpipe "cat $ethernet_file" ;
chomp $ethernet_status ;
return $ethernet_status ;
}
sub get_apt_upgradable {
my $apt = 0 ;
my $apt_file = "/var/log/apt-upgradable" ;
if (-r $apt_file) {
$apt = readpipe "cat $apt_file" ;
chomp $apt ;
}
return $apt ;
}
sub get_device_label {
my $device = shift ;
my $cmd = "lsblk -ln -o NAME,LABEL | sed -rn \"s/^$device\\s+//p\"" ;
my $label = readpipe($cmd) ;
chomp $label ;
return $label ;
}
sub sendcmd {
foreach (@_) {
my $msg = "AddToMenu $menuname $_" ;
$module->send($msg) ;
$msg = "AddToMenu $menuname_alt $_" ;
$module->send($msg) ;
#$module->showMessage("debug: $msg") ;
}
}
<file_sep>/.vimrc
" URL: http://vim.wikia.com/wiki/Example_vimrc
" Authors: http://vim.wikia.com/wiki/Vim_on_Freenode
" Description: A minimal, but feature rich, example .vimrc. If you are a
" newbie, basing your first .vimrc on this file is a good choice.
" If you're a more advanced user, building your own .vimrc based
" on this file is still a good idea.
"------------------------------------------------------------
" Features {{{1
"
" These options and commands enable some very useful features in Vim, that
" no user should have to live without.
" Set 'nocompatible' to ward off unexpected things that your distro might
" have made, as well as sanely reset options when re-sourcing .vimrc
set nocompatible
" Attempt to determine the type of a file based on its name and possibly its
" contents. Use this to allow intelligent auto-indenting for each filetype,
" and for plugins that are filetype specific.
filetype plugin indent on
" Enable syntax highlighting
syntax on
" Syntax highlighting for *.md files is no markdown, not modula2
au BufRead,BufNewFile *.md set filetype=markdown
"------------------------------------------------------------
" Must have options {{{1
"
" These are highly recommended options.
" Vim with default settings does not allow easy switching between multiple files
" in the same editor window. Users can use multiple split windows or multiple
" tab pages to edit multiple files, but it is still best to enable an option to
" allow easier switching between files.
"
" One such option is the 'hidden' option, which allows you to re-use the same
" window and switch from an unsaved buffer without saving it first. Also allows
" you to keep an undo history for multiple files when re-using the same window
" in this way. Note that using persistent undo also lets you undo in multiple
" files even in the same window, but is less efficient and is actually designed
" for keeping undo history after closing Vim entirely. Vim will complain if you
" try to quit without saving, and swap files will keep you safe if your computer
" crashes.
" set hidden
" Disable swap files and backups - annoying
set nobackup
set nowritebackup
set noswapfile
" Note that not everyone likes working this way (with the hidden option).
" Alternatives include using tabs or split windows instead of re-using the same
" window as mentioned above, and/or either of the following options:
" set confirm
" set autowriteall
" Better command-line completion
set wildmenu
" Show partial commands in the last line of the screen
set showcmd
" Highlight searches (use <C-L> to temporarily turn off highlighting; see the
" mapping of <C-L> below)
set hlsearch
" Modelines have historically been a source of security vulnerabilities. As
" such, it may be a good idea to disable them and use the securemodelines
" script, <http://www.vim.org/scripts/script.php?script_id=1876>.
" set nomodeline
set modeline
set scrolloff=6
"------------------------------------------------------------
" Usability options {{{1
"
" These are options that users frequently set in their .vimrc. Some of them
" change Vim's behaviour in ways which deviate from the true Vi way, but
" which are considered to add usability. Which, if any, of these options to
" use is very much a personal preference, but they are harmless.
" Use case insensitive search, except when using capital letters
set ignorecase
set smartcase
" Allow backspacing over autoindent, line breaks and start of insert action
set backspace=indent,eol,start
" When opening a new line and no filetype-specific indenting is enabled, keep
" the same indent as the line you're currently on. Useful for READMEs, etc.
set autoindent
" Stop certain movements from always going to the first character of a line.
" While this behaviour deviates from that of Vi, it does what most users
" coming from other editors would expect.
set nostartofline
" Display the cursor position on the last line of the screen or in the status
" line of a window
set ruler
" Always display the status line, even if only one window is displayed
set laststatus=2
" Instead of failing a command because of unsaved changes, instead raise a
" dialogue asking if you wish to save changed files.
set confirm
" Use visual bell instead of beeping when doing something wrong
set visualbell
" And reset the terminal code for the visual bell. If visualbell is set, and
" this line is also included, vim will neither flash nor beep. If visualbell
" is unset, this does nothing.
set t_vb=
" Enable use of the mouse for all modes
"set mouse=a
" Set the command window height to 2 lines, to avoid many cases of having to
" "press <Enter> to continue"
set cmdheight=2
" Display line numbers on the left
set number
" Quickly time out on keycodes, but never time out on mappings
set notimeout ttimeout ttimeoutlen=200
" Use <F11> to toggle between 'paste' and 'nopaste'
set pastetoggle=<F11>
"------------------------------------------------------------
" Indentation options {{{1
"
" Indentation settings according to personal preference.
" Indentation settings for using 2 spaces instead of tabs.
" Do not change 'tabstop' from its default value of 8 with this setup.
set shiftwidth=4
set softtabstop=4
set expandtab
" Indentation settings for using hard tabs for indent. Display tabs as
" two characters wide.
"set shiftwidth=2
"set tabstop=2
"------------------------------------------------------------
" Mappings {{{1
"
" Useful mappings
" Use space as your Leader key.
" http://sheerun.net/2014/03/21/how-to-boost-your-vim-productivity/
" :let mapleader = " "
let mapleader = "\<space>"
" Copy & paste to system clipboard with <Space>p and <Space>y
vmap <Leader>y "+y
vmap <Leader>d "+d
nmap <Leader>p "+p
nmap <Leader>P "+P
vmap <Leader>p "+p
vmap <Leader>P "+P
" If you want to keep the cursor in place when you join lines with J,
" you can do this, dropping a mark before the operation to which you
" return afterwards: http://blog.sanctum.geek.nz/vim-annoyances/
nnoremap J mzJ`z
" center the window automatically around the cursor after jumping to
" a location with motions like n (next search pattern occurrence)
" or } (end of next paragraph)
nnoremap n nzz
nnoremap } }zz
" Disable nuisance keys that are default standards in normal mode.
" F1 for help; :help is generally more useful for the experienced user
" Q to start ex mode; annoying when you intended to start recording a macro with q
" K to bring up a man page for the word under the cursor
nnoremap <F1> <nop>
nnoremap Q <nop>
nnoremap K <nop>
" Map Y to act like D and C, i.e. to yank until EOL, rather than act as yy,
" which is the default
map Y y$
" Map <C-L> (redraw screen) to also turn off search highlighting until the
" next search
nnoremap <C-L> :nohl<CR><C-L>
" http://statico.github.io/vim.html
" If I hit j I would expect the cursor to move down a single row on
" the screen, just like every other text editing area in the world.
" The following does just that:
nmap j gj
nmap k gk
nmap <C-Up> gj
nmap <C-Down> gk
" ^^^ Not working yet
"
" http://statico.github.io/vim.html
" make searches case-insensitive except when you include upper-case characters
:set ignorecase
:set smartcase
" highlight the current search. Also set key-binding to clear hilight.
" :set hlsearch
" :nmap \q :nohlsearch<CR>
" http://statico.github.io/vim.html
" two keys to cycle between all open buffers
:nmap <C-n> :bnext<CR>
:nmap <C-p> :bprev<CR>
" Up to section : Yes, My Editor Does That
:setlocal spell spelllang=en_nz
:set nospell
" Folding {{{1
function! MyFoldText() " {{{2
let line = getline(v:foldstart)
let nucolwidth = &fdc + &number * &numberwidth
let windowwidth = winwidth(0) - nucolwidth - 3
let foldedlinecount = v:foldend - v:foldstart
" expand tabs into spaces
let onetab = strpart(' ', 0, &tabstop)
let line = substitute(line, '\t', onetab, 'g')
let line = strpart(line, 0, windowwidth - 2 -len(foldedlinecount))
let fillcharcount = windowwidth - len(line) - len(foldedlinecount)
return line . '…' . repeat(" ",fillcharcount) . foldedlinecount . '…' . ' '
endfunction " }}}
set foldtext=MyFoldText()
set foldmethod=marker
"------------------------------------------------------------
" GnuPG Extensions {{{1
" Set extra file options.
augroup GnuPGExtra
autocmd BufReadCmd,FileReadCmd *.\(gpg\|asc\|pgp\) call SetGPGOptions()
augroup END
function SetGPGOptions()
" Fold at markers.
set foldmethod=marker
" Automatically close all folds.
set foldclose=all
" Only open folds with insert commands.
set foldopen=insert
endfunction
"}}}
" vim-plug {{{1
call plug#begin('~/.vim/plugged')
Plug 'whatyouhide/vim-gotham'
Plug 'jamessan/vim-gnupg'
call plug#end()
"}}}
" Colorscheme {{{1
" Vim uses bright background by default. Set to dark.
set background=dark
" https://github.com/chriskempson/base16-vim
" let g:base16_shell_path='/home/phleagol/.config/base16-shell/'
" let base16colorspace=256
" colorscheme base16-default
:let g:zenburn_high_Contrast=1
colors zenburn
" colorscheme gotham
"}}}
<file_sep>/.fvwm/lib/UpdateBar
#!/usr/bin/perl
## Howto prevent 2 of same script running
use strict ;
use warnings ;
use v5.20 ;
use lib `fvwm-perllib dir`;
use FVWM::Module ;
use POSIX qw( mkfifo ) ;
use Math::Round qw( nearest ) ;
use File::Path qw(make_path remove_tree) ;
use Image::Magick ;
## Name of the associated FvwmButtons module.
my $fbmodname = "NcmpcppGui" ;
## MPD music directory, status etc.
my $music_dir = $ENV{HOME} . "/Music" ;
my $mpd_status = "stopped" ;
my $mpd_file = my $mpd_elapsed = my $mpd_percent = 0 ;
## Coverart geometry + destination.
my $coverart_geom = "256x256!" ;
my $coverart_dir = "/tmp/fvwm/eyed3" ;
my $coverart_dest = "$ENV{FVWM_USERDIR}/images/cover.png" ;
## Define the progress bar/urxvt.
my $colorset = 148 ;
my $barchar = "█" ;
my $barname = "ProgressBar" ;
my $termwidth = 74 ;
my $termfifo = "/tmp/fifo1" ;
#my $termfg = "SteelBlue4" ;
#my $termbg = "gray9" ;
my $termfont = "5x8" ;
my $tup = "\x1b\x4d" ;
## Setup periodic alarm for during playback.
$SIG{ALRM} = \&polling ;
## Start module to communicate with fvwm
my $module = new FVWM::Module(
Name => 'UpdateBar',
Debug => 0,
);
my $modname = $module->name ;
## Tracker object to access info about colorsets
my $cs_tracker = $module->track("Colorsets") ;
#### Obtain progress bar colors.
## Obtain up to date colorset data
my $cs_hash = $cs_tracker->data ;
my $fore = $cs_hash->{$colorset}->{fg} ;
my $back = $cs_hash->{$colorset}->{bg} ;
my $termfg = sprintf('#%x',$fore) if $fore ;
my $termbg = sprintf('#%x',$back) if $back ;
$cs_tracker->stop ;
### SPAWN THE PROGRESS BAR.
## Start the urxvt term.
unlink ($termfifo) ;
mkfifo($termfifo, 0700) or die "mkfifo($termfifo) failed: $!" ;
my $cmd = "urxvt -n $barname -T $barname -g ${termwidth}x1-33300-33300 " ;
$cmd .= "-fn $termfont -fg \"$termfg\" -bg \"$termbg\" -e cat $termfifo &" ;
system($cmd) ;
open(FIFO1, ">$termfifo") ;
## Set FIFO1 as the default buffer - always flush.
select(FIFO1) ;
$| = 1 ;
## make cursor invisible (tput civis)
print "\x1b\x5b\x3f\x32\x35\x6c" ;
sleep 3 ;
update_bar(0) ;
mpd_update() ;
## The fvwm module listens for SendToModule cmnds.
$module->addHandler(M_STRING, \&mpd_update);
#$module->show_message("Starting");
$module->event_loop ;
#### SUBROUTINES
sub mpd_update {
my $new_file ;
my $new_status = "stopped" ;
foreach (`mpc -f ":::%file%:::"`) {
$new_file = "$music_dir/$1" if /^.*:::(.*):::$/ ;
$new_status = $1 if /^\[(\w+)\].*$/ ;
}
## Stop mode
if ($new_status eq "stopped" or not defined($new_file) or not -e $new_file ) {
$mpd_status = "stopped" ;
update_bar(0) ;
set_playback_icon("media-playback-start.png") ;
#$module->showMessage("mpd_update : STOP") ;
return ;
}
## Play or pause mode, yet the file remains the same.
if ($new_file eq $mpd_file) {
$mpd_status = $new_status ;
if ($mpd_status eq "playing") {
#$module->showMessage("mpd_update : PLAYING, SAME") ;
set_playback_icon("media-playback-pause.png") ;
polling()
} else {
#$module->showMessage("mpd_update : PAUSED, SAME") ;
update_elapsed() ;
update_bar($mpd_percent) ;
set_playback_icon("media-playback-start.png") ;
}
## or an entirely new track in play mode.
} else {
$mpd_status = $new_status ;
$mpd_file = $new_file ;
#$module->showMessage("mpd_update : PLAYING, NEW") ;
set_playback_icon("media-playback-pause.png") ;
polling() ;
update_cover() ;
}
}
sub polling {
if ($mpd_status eq "playing") {
update_elapsed() ;
update_bar($mpd_percent) ;
alarm(1) ;
return ;
} else {
alarm 0 ;
return ;
}
}
sub update_elapsed {
foreach (`mpc status`) {
if (/^[[].+#[^ ]+\s+([:\d]+\/[:\d]+)\s\((\d+)%\)\s*$/) {
$mpd_elapsed = $1 ;
$mpd_percent = $2 ;
#$mpd_elapsed =~ s/:/m/ ;
sendtomodule("ChangeButton elapsed Title ${mpd_elapsed}") ;
}
}
}
sub set_playback_icon {
my $icon = shift ;
sendtomodule("ChangeButton playback Icon $icon") ;
}
sub update_bar {
my $num_in = shift ;
my $normal_width = nearest(1, $num_in * $termwidth / 100) ;
$normal_width = $normal_width < 1 ? 1 :
$normal_width > $termwidth ? $termwidth : $normal_width ;
my $out = $barchar x $normal_width ;
$out .= " " x ($termwidth - $normal_width) ;
printf "${tup}\r%s", $out ;
return ;
}
sub open_bar {
## Start the urxvt term.
unlink ($termfifo) ;
mkfifo($termfifo, 0700) or die "mkfifo($termfifo) failed: $!" ;
my $cmd = "urxvt -n $barname -T $barname -g ${termwidth}x1 " ;
$cmd .= "-fn $termfont -fg \"$termfg\" -bg \"$termbg\" -e cat $termfifo &" ;
system($cmd) ;
open(FIFO1, ">$termfifo") ;
## Set FIFO1 as the default buffer - always flush.
select(FIFO1) ;
$| = 1 ;
## make cursor invisible (tput civis)
print "\x1b\x5b\x3f\x32\x35\x6c" ;
}
sub update_cover {
my $coverfile = 0 ;
$coverfile = get_mp3_cover() if $mpd_file =~ /[.]mp3$/ ;
$coverfile = get_flac_cover() if $mpd_file =~ /[.]flac$/ ;
if (not $coverfile) {
my $basename = $mpd_file ;
$basename =~ s/[.]\w\w\w\w?$// ;
## say STDERR "$basename.jpg" ;
## say STDERR "$basename.png" ;
$coverfile = "$basename.jpg" if -r "$basename.jpg" ;
$coverfile = "$basename.png" if -r "$basename.png" ;
}
return 0 unless -r $coverfile ;
## Correctly resize the cover image.
## Read src cover image into imagemagick.
return 0 if not open(IMAGE, $coverfile) ;
my $err = 1 ;
my $image = Image::Magick->New(quality => 1) ;
$err = $image->Read(file=>\*IMAGE) ;
close(IMAGE) ;
return 0 if $err ;
## resize the cover image.
return 0 if $image->AdaptiveResize(geometry => $coverart_geom) ;
## Save the finished cover image..
open(IMAGE, ">$coverart_dest") ;
return 0 if $image->Write(
file => \*IMAGE,
filename => $coverart_dest,
quality => 100,
) ;
sendtomodule("ChangeButton coverart Icon cover.png") ;
return 1 ;
}
sub get_flac_cover {
## Create a tmp folder.
remove_tree($coverart_dir) ;
make_path($coverart_dir) ;
## Dump embedded image from flac.
my $file = "$coverart_dir/zzzz" ;
system("metaflac --export-picture-to=\"$file\" \"$mpd_file\" 1>/dev/null 2>&1") ;
if (-r "$file") { return $file } else { return 0 } ;
}
sub get_mp3_cover {
## Create a tmp folder.
remove_tree($coverart_dir) ;
make_path($coverart_dir) ;
## Dump embedded images from mp3.
system("eyeD3 -i \"$coverart_dir\" \"$mpd_file\" 1>/dev/null 2>&1") ;
my $img = 0 ;
my @names = (
"FRONT_COVER.png", "FRONT_COVER.jpg", "FRONT_COVER.jpeg",
"FRONT_COVER1.png", "FRONT_COVER1.jpg", "FRONT_COVER1.jpeg",
"OTHER.png", "OTHER.jpg", "OTHER.jpeg",
) ;
## Look for a suitably named image.
foreach my $file (@names) {
if (-r "$coverart_dir/$file") {
$img = "$coverart_dir/$file" ;
last ;
}
}
if ($img) { return $img } else { return 0 } ;
}
## For sending commands to the FvwmButtons modules.
sub sendtomodule {
foreach (@_) {
my $cmd = "SendToModule $fbmodname " . $_ ;
$module->send($cmd) ;
}
}
|
6f17118a66d1232128f29bb5b05c4502c332fb53
|
[
"Vim Script",
"Shell",
"Perl"
] | 20 |
Vim Script
|
phleagol/fvwm_2016
|
5950aa27a8be1c8ea159babf5233317d35b7d586
|
dbdfd0680016f15b3c72fc89a21f26ccf47448c8
|
refs/heads/master
|
<file_sep>#include <stdio.h>
int main(void) {
/* new code */
printf("Hello World!\n");
printf("Credintial Helper\n");
printf("Credintial Helper12\n");
return 0;
}
|
5c80ba734fe6d6826627dd36470c589ba14553ec
|
[
"C"
] | 1 |
C
|
xsigmar/hello
|
1112683c83b3bce100b2fa120da7fbc40aaf4f31
|
a279f93c2fd65ff372a8e2fffe0ca7edae3648b4
|
refs/heads/master
|
<repo_name>EmanuelPires/TimeSheet<file_sep>/README.md
# TimeSheet
Group Activity Time Sheet
|
9afcfe5bad785e431862f56ae2d0fc9ce2a95436
|
[
"Markdown"
] | 1 |
Markdown
|
EmanuelPires/TimeSheet
|
849e50efd17137b5cd8d0e801a78d9b8d8c05696
|
82f6c2ef6def73b1f12db25404f48670c155641d
|
refs/heads/main
|
<repo_name>czechoa/Game_of_tanks_JAVA<file_sep>/README.md
# Game_of_tanks_JAVA
<img src="https://github.com/zakrzewskib/Game_of_tanks_JAVA/blob/main/documentation/game.PNG" alt="drawing" width="800px"/>
2020-02-26 - 2020-04-08
|
27e34185aac8ece50b24e336f265e7ed984b1dde
|
[
"Markdown"
] | 1 |
Markdown
|
czechoa/Game_of_tanks_JAVA
|
929bb6cf397c506ce8aeadf8e8ac87cc2098cee2
|
d7b64e120016b26e03e869eaa09ffa31ff7f480a
|
refs/heads/master
|
<file_sep><?php
namespace Demv\Curl\Header;
/**
* Class Content
* @package Client\Header
*/
final class Content extends Header
{
const CHARSET = '%s;charset=%s';
const TYPE = '%s;type=%s';
/**
* Content constructor.
*
* @param string $type
*/
public function __construct(string $type)
{
parent::__construct('Content-Type', $type);
}
/**
* @param string $type
*
* @return $this
*/
public function type(string $type)
{
$this->concat('type=' . $type);
return $this;
}
/**
* @param string $charset
*
* @return $this
*/
public function charset(string $charset)
{
$this->concat('charset=' . $charset);
return $this;
}
}
<file_sep><?php
namespace Demv\Curl\Header;
/**
* Class HeaderProvider
* @package Client\Header
*/
final class HeaderProvider implements HeaderInterface
{
/**
* @var array
*/
private $_header = [];
/**
* @param string $type
*
* @return Content
*/
public function setContent(string $type)
{
$this->_header['content'] = new Content($type);
return $this->_header['content'];
}
/**
* @param string $agent
*
* @return Header
*/
public function setAgent(string $agent)
{
$this->_header['agent'] = new Header('User-Agent', $agent);
return $this->_header['agent'];
}
/**
* @param int $length
*
* @return Header
*/
public function setLength(int $length)
{
$this->_header['length'] = new Header('Content-Length', $length);
return $this->_header['length'];
}
/**
* @param string $header
*
* @return null|Header
*/
public function getHeader(string $header)
{
if (array_key_exists($header, $this->_header)) {
return $this->_header[$header];
}
return null;
}
/**
* @param string $header
* @param string $value
*
* @return Header
*/
public function setHeader(string $header, string $value)
{
$result = $this->getHeader($header);
if ($result !== null) {
$result->setContent($value);
} else {
$result = new Header($header, $value);
$this->_header[$header] = $result;
}
return $result;
}
/**
* @return array
*/
public function provide()
{
$output = [];
foreach ($this->_header as $header) {
$output[] = $header->provide();
}
return $output;
}
}
<file_sep><?php
namespace Demv\Curl;
/**
* Class SoapClient
* @package Client
*/
class SoapClient extends Client
{
/**
* XOP
*/
const XOP = 'application/xop+xml';
/**
* SOAP (Plain XML)
*/
const SOAP = 'application/soap+xml';
/**
* Default User-Agent
*/
const DEFAULT_USER_AGENT = 'Mozilla/1.0N (Windows)';
/**
* SoapClient constructor.
*
* @param string $type
*/
public function __construct( /*string */$type = '') // TODO: PHP 7
{
parent::__construct();
$this->getHeaderProvider()->setContent($type);
}
/**
* @param string $action
* @param string $url
* @param string $data
*
* @return mixed|string
*/
public function submit(string $action, string $url, string $data)
{
$this->getHeaderProvider()->setHeader('SOAPAction', $action);
$this->getHeaderProvider()->setLength(strlen($data));
return $this->usePost(true)->send($url, $data);
}
}
<file_sep><?php
use Demv\Curl\Header\Content;
class ContentTest extends PHPUnit_Framework_TestCase
{
protected $type = 'text/xml';
protected $content = null;
public function setUp()
{
$this->content = new Content($this->type);
}
public function testType()
{
$type = 'application/pdf';
$content = $this->content->type($type)->getContent();
$this->assertCount(2, $content);
$this->assertEquals('type=' . $type, $content[1]);
}
public function testCharset()
{
$charset = 'UTF-8';
$content = $this->content->charset($charset)->getContent();
$this->assertCount(2, $content);
$this->assertEquals('charset=' . $charset, $content[1]);
}
}
<file_sep><?php
use Demv\Curl\Header\Content;
use Demv\Curl\Header\Header;
use Demv\Curl\Header\HeaderProvider;
class HeaderProviderTest extends PHPUnit_Framework_TestCase
{
protected $hp = null;
public function setUp()
{
$this->hp = new HeaderProvider();
}
public function testSetContent()
{
$type = 'text/xml';
$content = $this->hp->setContent($type);
$this->assertInstanceOf(Content::class, $content);
$this->assertCount(1, $content->getContent());
$this->assertEquals($type, $content->getContent()[0]);
}
public function testSetAgent()
{
$agent = 'Apache-HttpClient/4.1.1';
$header = $this->hp->setAgent($agent);
$this->assertInstanceOf(Header::class, $header);
$this->assertCount(1, $header->getContent());
$this->assertEquals($agent, $header->getContent()[0]);
return $this->hp;
}
public function testSetLength()
{
$length = 1512;
$header = $this->hp->setLength($length);
$this->assertInstanceOf(Header::class, $header);
$this->assertCount(1, $header->getContent());
$this->assertEquals($length, $header->getContent()[0]);
}
public function testSetNewHeader()
{
$headerStr = 'Connection';
$value = 'Keep-Alive';
$header = $this->hp->setHeader($headerStr, $value);
$this->assertInstanceOf(Header::class, $header);
$this->assertCount(1, $header->getContent());
$this->assertEquals($value, $header->getContent()[0]);
}
/**
* @depends testSetAgent
*/
public function testOverideExistingHeader(HeaderProvider $hp)
{
$headerStr = 'Agent';
$value = 'Another Agent';
$header = $hp->setHeader($headerStr, $value);
$this->assertInstanceOf(Header::class, $header);
$this->assertCount(1, $header->getContent());
$this->assertEquals($value, $header->getContent()[0]);
}
public function testGetHeaderExisting()
{
$agent = 'Apache-HttpClient/4.1.1';
$this->hp->setAgent($agent);
$header = $this->hp->getHeader('agent');
$this->assertInstanceOf(Header::class, $header);
$this->assertCount(1, $header->getContent());
$this->assertEquals($agent, $header->getContent()[0]);
}
public function testGetHeaderNonExistent()
{
$header = $this->hp->getHeader('none');
$this->assertNull($header);
}
public function testProvide()
{
$agent = 'Apache-HttpClient/4.1.1';
$header = $this->hp->setAgent($agent);
$length = 1024;
$header = $this->hp->setLength($length);
$output = $this->hp->provide();
$this->assertCount(2, $output);
$this->assertEquals('User-Agent: ' . $agent, $output[0]);
$this->assertEquals('Content-Length: ' . $length, $output[1]);
}
}
<file_sep><?php
use Demv\Curl\SoapClient;
class SoapClientTest extends PHPUnit_Framework_TestCase
{
/**
*
*/
public function testConstructSoapClient()
{
$client = new SoapClient();
$this->assertTrue($client !== null);
}
}
<file_sep><?php
namespace Demv\Curl\Header;
/**
* Interface HeaderInterface
* @package Client\Header
*/
interface HeaderInterface
{
/**
* @return string
*/
public function provide();
}
<file_sep><?php
namespace Demv\Curl\Header;
/**
* Class Header
* @package Client\Header
*/
class Header implements HeaderInterface
{
const HEADER = '%s: %s';
/**
* @var null|string
*/
private $_header = null;
/**
* @var array
*/
private $_content = [];
/**
* Header constructor.
*
* @param string $header
* @param string $value
*/
public function __construct(string $header, string $value)
{
$this->_header = $header;
$this->concat($value);
}
/**
* @return null|string
*/
public function getHeader()
{
return $this->_header;
}
/**
* @param $content
*
* @throws \Exception
*/
public final function setContent($content)
{
if (is_array($content)) {
$this->_content = $content;
} else if (is_string($content)) {
$this->_content = explode(';', $content);
} else {
throw new \Exception('Expected array or string');
}
}
/**
* @param string $value
*/
public final function concat(string $value)
{
$this->_content[] = $value;
}
/**
* @return string
*/
public final function getContent()
{
return $this->_content;
}
/**
* @return string
*/
public function provide()
{
return sprintf(self::HEADER, $this->getHeader(), implode(';', $this->getContent()));
}
}
<file_sep><?php
use Demv\Curl\Header\Header;
class HeaderTest extends PHPUnit_Framework_TestCase
{
protected $headerStr = 'Connection';
protected $value = 'Keep-Alive';
protected $header = null;
public function setUp()
{
$this->header = new Header($this->headerStr, $this->value);
}
public function testGetHeader()
{
$this->assertEquals($this->headerStr, $this->header->getHeader());
}
public function testGetContent()
{
$content = $this->header->getContent();
$this->assertCount(1, $content);
$this->assertEquals($this->value, $content[0]);
}
public function testConcat()
{
$anotherValue = 'value';
$this->header->concat($anotherValue);
$content = $this->header->getContent();
$this->assertCount(2, $content);
$this->assertEquals($anotherValue, $content[1]);
}
public function testSetContentWithArray()
{
$newContent = ['value1', 'value2', 'value3'];
$this->header->setContent($newContent);
$content = $this->header->getContent();
$this->assertEquals($newContent, $content);
}
public function testSetContentWithString()
{
$newContent = 'text/xml;charset=UTF-8';
$expectedResult = ['text/xml', 'charset=UTF-8'];
$this->header->setContent($newContent);
$content = $this->header->getContent();
$this->assertEquals($expectedResult, $content);
}
/**
* @expectedException Exception
*/
public function testSetContentWithInvalidInput()
{
$invalidContent = 5;
$this->header->setContent($invalidContent);
}
public function testProvide()
{
$expected = 'Connection: Keep-Alive;Keep-Dead';
$this->header->concat('Keep-Dead');
$this->assertEquals($expected, $this->header->provide());
}
}
<file_sep><?php
namespace Demv\Curl;
use Demv\Curl\Header\HeaderProvider;
/**
* Class Client
* @package Client
*/
class Client
{
/**
* @var array
*/
private static $DefaultOptions = [
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_VERBOSE => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_FAILONERROR => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_TIMEOUT => 600,
CURLOPT_CONNECTTIMEOUT => 180,
CURLOPT_SSLVERSION => CURL_SSLVERSION_DEFAULT,
];
/**
* @var resource
*/
private $_handle = null;
/**
* @var array
*/
private $_options = [];
/**
* @var HeaderProvider|null
*/
private $_headerProvider = null;
/**
* Client constructor.
*/
public function __construct()
{
$this->_handle = curl_init();
}
/**
* Client destructor
*/
public function __destruct()
{
curl_close($this->_handle);
}
/**
* @param int $option
*
* @return mixed
*/
public function getInfo($option = 0)
{
return curl_getinfo($this->_handle, (int) $option);
}
/**
* @param int $option
* @param $value
*
* @return $this
*/
public function setOption(int $option, $value)
{
$this->_options[$option] = true;
curl_setopt($this->_handle, $option, $value);
return $this;
}
/**
* @param array $options
*
* @return $this
*/
public function setOptions(array $options)
{
foreach ($options as $option => $value) {
$this->setOption($option, $value);
}
return $this;
}
/**
* @param bool $host
* @param bool $peer
*
* @return $this
*/
public function verifySSL(bool $host, bool $peer)
{
return $this->setOption(CURLOPT_SSL_VERIFYHOST, $host ? 2 : 0)
->setOption(CURLOPT_SSL_VERIFYPEER, $peer);
}
/**
* @param int $timeout
* @param int $connection_timeout
*
* @return $this
*/
public function setTimeout(int $timeout, int $connection_timeout)
{
return $this->setOption(CURLOPT_TIMEOUT, $timeout)
->setOption(CURLOPT_CONNECTTIMEOUT, $connection_timeout);
}
/**
* @param array $header
*
* @return Client
*/
public function setHeader(array $header)
{
return $this->setOption(CURLOPT_HTTPHEADER, $header);
}
/**
* @return bool
*/
public function hasHeaderProvider()
{
return $this->_headerProvider !== null;
}
/**
* @return HeaderProvider
*/
public function getHeaderProvider()
{
if (!$this->hasHeaderProvider()) {
$this->_headerProvider = new HeaderProvider();
}
return $this->_headerProvider;
}
/**
* @param bool $fetch
*
* @return Client
*/
public function fetchHeader(bool $fetch)
{
return $this->setOption(CURLOPT_HEADER, $fetch);
}
/**
* @param bool $verbose
*
* @return Client
*/
public function verbose(bool $verbose)
{
return $this->setOption(CURLOPT_VERBOSE, $verbose);
}
/**
* @param bool $post
*
* @return Client
*/
public function usePost(bool $post)
{
return $this->setOption(CURLOPT_POST, $post);
}
/**
* @return Client
*/
public function useDefaults()
{
return $this->setOptions(self::$DefaultOptions);
}
/**
* @return $this
*/
public function setDefaults()
{
foreach (self::$DefaultOptions as $option => $value) {
if (!array_key_exists($option, $this->_options)) {
$this->setOption($option, $value);
}
}
return $this;
}
/**
* @param string $url
* @param $data
*
* @return mixed|string
*/
public function send(string $url, $data)
{
$this->setDefaults();
$this->setOption(CURLOPT_URL, $url)
->setOption(CURLOPT_POSTFIELDS, $data);
if ($this->hasHeaderProvider()) {
$this->setOption(CURLOPT_HTTPHEADER, $this->_headerProvider->provide());
}
$result = curl_exec($this->_handle);
if ($result === false) {
return curl_error($this->_handle);
}
return $result;
}
}
|
bb68753832ae2c144a7422e3fd18dae07c757fa1
|
[
"PHP"
] | 10 |
PHP
|
demvsystems/soap-client
|
66aa1701ba4a180fbd2b2eed13fbd976b8662e9b
|
ec1a24e29741f4f11a1650f614c0a5d91d6439e0
|
refs/heads/master
|
<file_sep>---
layout: post_index
title: Blog Articles
permalink: /articles
type: articles
comments: false
pagination:
enabled: true
---
<file_sep>## My Personal Blog
* My personal Jekyll-based static website hosted on GitHub and served with GitHub pages.
* The CNAME file redirects to my custom domain: http://www.johnabraham.me
Features:
* Using Staticman, an external Node.js API for allowing user comments on static sites
* Contact section using FormSpree.io
* Google analytics integration
* Pagination using the jekyll-paginate-v2 plugin/gem
* SEO Considerations
* SSL-enabled
* RSS feed<file_sep># Site wide configuration
title: My Site Title
locale: en_US
port: 4000
baseurl: /
# Jekyll configuration
markdown: kramdown
highlighter: rouge
sass:
sass_dir: assets/css/_sass
style: compressed
plugins:
- jekyll-sitemap
- jekyll-gist
- jekyll-paginate-v2
- jekyll-redirect-from
kramdown:
auto_ids: true
footnote_nr: 1
entity_output: as_char
toc_levels: 1..6
# Site owner
owner:
name: <NAME>
avatar: bio_photo.jpg
bio: "full-stack web developer and open-source enthusiast."
linkedin: john4braham
github: john4braham
email:
name: john.abraham
domain: hotmail
tld: com
google-analytics: UA-118820080-1
# Plugin: Pagination (jekyll-paginate-v2)
pagination:
enabled: true
debug: false
per_page: 6
permalink: "/page/:num/"
title: ":title"
limit: 0
sort_field: "date"
sort_reverse: true
# Plugin: Auto Pages (jekyll-paginate-v2)
autopages:
enabled: true
categories:
enabled: false
collections:
enabled: false
tags:
enabled: true
slugify:
mode: raw
cased: true
layouts:
- "autopage_tags.html"
title: ":tag"
permalink: "/tag/:tag"
# Staticman commenting system configs
staticman:
branch: master
repository: john4braham/john4braham.github.io
unknown_gravatar: ad516503a11cd5ca435acc9bb6523536
notifications:
enabled: false
reCaptcha:
siteKey: <KEY>
secret: <KEY>vgYw7HaDlU9CTO5LJdedt
bvkodMqG16tarJYYtFw9Bl2c1Cd9RZf19k7FmMUn7+GGf84
7kxA/stjiEGWqnMtDAWyiGD8zmtf3p33pM2PrKGFEcj1Fv9
03DsGuAo98qsh5tpus/yBnupoKowhxq/GkmU=
#includes/excludes from jekyll conversion
include: [
".htaccess"
]
exclude: [
"lib",
"config.rb",
"Capfile",
"config",
"log",
"Rakefile",
"Rakefile.rb",
"tmp",
"less",
"*.sublime-project",
"*.sublime-workspace",
"test",
"spec",
"Gruntfile.js",
"package.json",
"node_modules",
"Gemfile",
"Gemfile.lock",
"LICENSE",
"README.md"
]<file_sep>/* ==========================================================================
Page layout
========================================================================== */
html {
height: 100%;
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
outline: 0 !important;
}
body {
color: $text-color;
font-family: $base-font;
background: $body-color;
// for sticky footer
margin: 0;
min-height: 100%;
position: relative;
}
/* Main content */
.site-content {
padding: 0 .5rem 4rem .5rem;
@media #{$large} {
padding: 0 2rem 4rem 2rem;
}
#main {
clear: both;
counter-reset: captions;
@include container(65rem);
@include clearfix;
#index,
.post,
.page {
float: left;
margin: 1rem 0;
background-color: $white;
width: 100%;
h1.page-title {
color: white;
line-height: 1.4;
padding: 0 .5em;
width: max-content;
background-color: black;
-webkit-box-decoration-break: clone;
box-decoration-break: clone;
margin: 1rem 0;
@include font-rem(50);
}
}
.post {
.post-content-wrap {
padding: 1rem 1rem 1rem 1rem;
@media #{$large} {
padding: 0;
.post-content {
width: 75%;
display: inline-block;
}
}
}
}
#index,
.page {
padding: 0 1rem 2rem 1rem;
@media #{$large} {
padding: 0;
}
@media #{$large} {
width: 100%;
}
}
.post-headline-wrap {
height: 375px;
border-bottom: 1px solid #ccc;
.headline-meta {
top: 0;
left: 0;
position: absolute;
padding: .5rem 1.5rem;
margin-top: 2rem;
z-index: 2;
@include grid(12, 12);
@media #{$large} {
@include grid(12, 5);
padding: .5rem 0;
}
// h1.site-name {
// margin-left: 2rem;
// text-transform: uppercase;
// @include font-rem(40);
// i { @include font-rem(35); }
// a {
// color: black;
// }
// }
h1.post-title {
@include font-rem(50);
span {
color: white;
line-height: 1.4;
padding: 0 .5em;
background-color: black;
-webkit-box-decoration-break: clone;
box-decoration-break: clone;
}
}
span.post-author {
a { color: black; }
}
.byline.post-meta {
margin-top: 1rem;
padding: .5rem 0;
a {
color: $orange;
&.comments-preview {
display: inline-block;
.fa-comments {
margin-right: .25rem;
}
}
}
}
}
img {
top: 0;
right: 0;
width: 100%;
position: absolute;
visibility: hidden;
height: -webkit-fill-available;
height: fill-available;
@media #{$large} {
@include grid(12, 8);
}
@media #{$medium} {
visibility: visible;
}
}
span.img-credit {
visibility: hidden;
position: absolute;
right: .5rem;
bottom: .5rem;
color: white;
padding: 0 .5em;
background-color: black;
@include font-rem(20);
a {
color: white;
text-decoration: underline;
}
@media #{$medium} {
visibility: visible;
}
}
}
}
}
/* Index listing specific styling */
/* Layouts: home, blog, and results */
#index {
margin-bottom: 2rem;
h2 {
color: $light-black;
margin-bottom: .5rem;
@include font-rem(30);
}
.articles {
@include grid(12,12);
@media #{$medium} {
@include grid(12,9);
}
}
article {
float:left;
margin-bottom: 2rem;
padding: 1rem .4rem;
@include box-shadow
(-9px 15px 10px -15px #ccc);
@include grid(12,12);
.post-text {
@include grid(12,12);
@media #{$medium} {
@include grid(12,9);
}
h2 { margin-top: 0; }
p+p { @include font-rem(18); }
a.read-more {
font-weight: 700;
@include font-rem(18);
}
}
.post-meta {
clear: inherit;
margin-top: 3.25rem;
padding-left: 2rem;
@include grid(12,3);
display: none !important;
@media #{$medium} {
display: block !important;
}
p { @include font-rem(20); }
i { color: $orange; }
}
.mobile-meta {
margin-bottom: .5rem;
display: block !important;
@media #{$medium} {
display: none !important;
}
}
p+p {
text-indent: 0;
}
}
.topics {
@include grid(12,12);
@media #{$medium} {
padding-left: 2rem;
@include grid(12,3);
}
ol {
margin: 0;
padding: 0;
list-style-type: none;
}
li {
font-weight: 700;
margin-bottom: .3rem;
border-bottom: 1px solid #ccc;
span {
float: right;
color: darken($orange, 10);
}
}
}
}
/* Post byline */
.byline {
clear: both;
color: grey;
font-size: 80%;
}
/* Author sidebar & author/article separator*/
.post-sidebar {
position: -webkit-sticky;
position: sticky;
top: 2rem;
width: 19%;
float: right;
display: none;
padding-left: 1.5rem;
color: $light-black;
@media #{$large} {
display: inline-block;
}
h4 {
margin-top: 0;
margin-bottom: .5rem;
text-transform: uppercase;
@include font-rem(16);
&:before {
content: "\2014";
padding-right: .25rem;
}
}
p {
margin: 0;
color: $light-black;
font-size: 80%;
font-style: italic;
}
a {
color: $light-black;
&:hover {
color: $orange;
}
}
.byline {
color: grey;
}
/* Latest articles list */
.related-posts {
&.side {
a {
display: contents;
font-family: $heading-font;
margin-bottom: .4rem;
&:hover {
text-decoration: underline;
}
}
p {
margin-bottom: 1rem;
}
p:last-child {
margin-bottom: 1.5rem;
}
}
}
}
.related-posts.article,
.about-author-card {
padding: 1rem 1rem 1rem 1rem;
@media #{$large} {
display: none;
}
h4 {
margin-bottom: .5rem;
text-transform: uppercase;
&:before {
content: "\2014";
padding-right: .25rem;
}
}
}
/* Post content wrapper */
.article-wrap {
// Dotted line underlines for links
p > a,
li > a {
text-decoration: underline;
}
}
/* Table of contents */
.toc {
font-size: 95%;
@media #{$large} {
display: block;
@include grid(12,2);
@include prefix(12,0.5);
@include suffix(12,0.5);
position: absolute;
top: 5.5rem;
right: 0;
background-color: $white;
}
header {
background: lighten($black, 10);
}
h3 {
margin: 0;
padding: 5px 10px;
color: $white;
@include font-rem(16);
text-transform: uppercase;
&:hover {
cursor: pointer;
}
}
ul {
margin: 2px 0 0;
padding: 0;
line-height: 1;
}
li {
display: block;
margin: 0 0 1px 0;
padding: 0;
font-family: $heading-font;
list-style-type: none;
&:last-child {
border-bottom-width: 0;
}
a {
padding: 10px;
display: block;
color: $white;
text-decoration: none;
background: lighten($black, 30);
@include opacity(0.7);
@include transition(opacity 0.2s ease-in-out);
&:hover {
@include opacity(1);
}
}
ul {
margin: 1px 0 0;
li a {
padding-left: 20px;
}
}
}
}
/* TOC trigger for collapsing */
#drawer {
max-height: 100%;
overflow: hidden;
&.js-hidden {
max-height: 0;
}
}
/* Social sharing links */
/* Social media brand buttons */
.social-share,
.post-tags {
h4 {
margin-bottom: .5rem;
text-transform: uppercase;
@include font-rem(16);
&:before {
content: "\2014";
padding-right: .25rem;
}
}
ul, li {
margin: 0;
padding: 0;
list-style: none;
}
li {
display: inline-block;
margin: 0 .2rem .4rem 0;
}
i {
padding-right: .25rem;
}
$social:
(twitter, $twitter-color),
(facebook, $facebook-color),
(google-plus, $google-plus-color),
(linkedin, $linkedin-color),
(flickr, $flickr-color),
(foursquare, $foursquare-color),
(instagram, $instagram-color),
(pinterest, $pinterest-color),
(rss, $rss-color),
(tumblr, $tumblr-color),
(vimeo, $vimeo-color),
(youtube, $youtube-color);
@each $socialnetwork, $color in $social {
.#{$socialnetwork} {
background: $color;
}
}
a {
opacity: 0.8;
color: $white;
display: block;
font-weight: 600;
padding: 5px 5px;
border-radius: 3px;
text-transform: uppercase;
text-decoration: none !important;
background-color: $light-black;
font-family: $heading-font;
@include font-rem(14);
&:hover {
color: white;
opacity: .6;
}
}
}
.post-tags {
&.article {
display: block;
@media #{$large} {
display: none;
}
}
&.side {
margin-bottom: 1.25rem;
}
}
/* Footer wrapper */
.footer-wrap {
border-top: .15em solid $orange;
background-color: $footer-color;
padding: 0.5em 0 1em 0;
position: absolute;
right: 0;
bottom: 0;
left: 0;
clear: both;
@include container;
@include clearfix;
a,
a:active,
a:visited,
p,
h4,
h5,
h6,
span {
@include font-rem(18);
}
footer {
text-align: center;
.author-social {
display: inline-block;
}
&, a {
font-weight: 600;
color: $footer-text-color;
}
a {
text-decoration: underline;
&:hover {
@include scale(1.2);
}
}
i:hover {
color: $orange;
}
}
}
/*
Browser upgrade alert
========================================================================== */
.browser-upgrade {
background: #000;
text-align: center;
margin: 0 0 2em 0;
padding: 10px;
text-align: center;
color: $white;
a {
color: $white;
border-bottom: 1px dotted $white;
text-decoration: none;
&:hover {
border-bottom: 1px solid $white;
}
}
}
/*
Google search form
========================================================================== */
#goog-fixurl {
ul {
list-style: none;
margin-left: 0;
padding-left: 0;
li {
list-style-type: none;
}
}
}
#goog-wm-qt {
width: auto;
margin-right: 10px;
margin-bottom: 20px;
padding: 8px 20px;
display: inline-block;
@include font-rem(14);
background-color: $white;
color: $black;
border-width: 2px !important;
border-style: solid !important;
border-color: lighten($black,50);
@include rounded(3px);
}
#goog-wm-sb {
@extend .btn;
}
/*
Reveal animation of site content
========================================================================== */
.fade-in-first {
opacity: 0;
animation: fadeIn 250ms forwards;
}
.fade-in-second {
opacity: 0;
-webkit-animation: fadeIn 500ms forwards;
animation: fadeIn 500ms forwards;
}
.fade-in-third {
opacity: 0;
-webkit-animation: fadeIn 750ms forwards;
animation: fadeIn 750ms forwards;
}
@-webkit-keyframes fadeIn {
0% {
opacity: 0;
transform: translateY(50px);
}
30% {
opacity: 0;
}
100% {
opacity: 1;
transform: translateY(0);
}
}
@keyframes fadeIn {
0% {
opacity: 0;
transform: translateY(50px);
}
30% {
opacity: 0;
}
100% {
opacity: 1;
transform: translateY(0);
}
}
/*
Post footer next/prev pagination
========================================================================== */
.post-navigation {
overflow: hidden;
.article-wrap {
display: inline-block;
&:hover i {
@include scale(1.2);
}
i {
font-size: 2rem;
padding: 5px 0;
}
&.next {
float: left;
margin-top: 1rem;
* { float: none; }
i {
margin-left: 0;
margin-right: .4rem;
}
.text-wrap {
float: right;
}
@media #{$medium} {
float: right;
margin-top: 0;
* { float: right; }
i {
margin-left: .25rem;
margin-right: 0;
}
.text-wrap {
float: left;
}
}
}
&.prev {
width: 100%;
@media #{$medium} {
width: auto;
}
.text-wrap {
display: inline-block;
}
}
}
}
.hr-clearfix {
clear: both;
}
/*
404 page search input styling
========================================================================== */
.search-wrap-404 {
.search-input-icon {
top: 1px;
width: 0;
z-index: 1;
left: -25px;
cursor: pointer;
position: relative;
color: $light-black;
}
}
/*
Contact page form styling
========================================================================== */
#contact-form {
width: 100%;
@media #{$large} {
width: 50%;
float:left;
}
.contact-input-group {
margin-bottom: 1rem;
}
}
.contact-img {
max-width: 512px;
margin: 0 auto;
margin-top: 3rem;
vertical-align: bottom;
@media #{$large} {
float: right;
max-width: 45%;
margin: 0;
}
}
/*
Comments section
========================================================================== */
#comments {
.section-title {
h1 {
margin-bottom: 2rem;
}
}
h3 {
margin-top: 0;
margin-bottom: .25rem;
a {
color: black;
}
}
.comment {
margin-bottom: 2rem;
p {
margin-bottom: .25rem;
}
&.child {
padding: 0;
display: none;
background: white;
margin-left: 4.5rem;
margin-bottom: 0;
margin-top: 0;
.comment-avatar {
width: 2rem;
height: 2rem;
}
p {
margin-bottom: 1rem;
}
}
.comment-avatar {
width: 3rem;
height: 3rem;
margin-right: 1rem;
margin-bottom: 1rem;
vertical-align: top;
display: none;
@media #{$medium} {
display: inline-block;
}
img {
@include rounded(50%);
&:hover {
@include box-shadow(0 0 0 .13em $orange);
}
}
}
.article-text-wrap {
width: 100%;
display: inline-block;
@media #{$medium} {
width: 89%;
}
}
.comment-content {
padding-bottom: .25rem;
}
.comment-reply {
overflow: hidden;
border-radius: 3px;
background: darken($body-color, 10);
a.btn {
margin: 0;
float: right;
height: 1.25rem;
padding: .15rem;
@media screen and (-webkit-min-device-pixel-ratio:0) {
padding: .1rem;
}
@-moz-document url-prefix() {
padding: 0 .25rem 0 0;
}
&.view-comments-btn {
margin-left: .25rem;
}
}
}
.comment-author-name {
a {
color: $orange;
}
}
}
}
.entry-comments {
.leave-comment-btn {
margin-top: 1rem;
margin-bottom: 2rem;
@media #{$large} {
margin-bottom: 0;
}
}
}
/*
Comments form modal content
========================================================================== */
#respond {
.section-title {
h1 {
margin-top: 0 !important;
}
}
}
form#comment-form, {
padding: 1rem;
display: inline-block;
background: darken($body-color, 10);
}
form#comment-form,
form#reply-form {
@include rounded(.4rem);
.hidden {
margin: 0;
}
&.comment-inline > .form-group {
width: 100%;
display: block;
@media #{$small} {
display: inline-block;
@include grid(12,4);
&:first-child {
padding: 0 10px 0 0;
}
&:nth-child(2) {
padding: 0 10px;
}
&:nth-child(3) {
padding: 0 0 0 10px;
}
}
}
.form-group {
.form-controls.reply {
float: right;
}
.btn {
&.clear {
margin-right: .25rem;
}
}
label {
text-align: left;
}
button {
margin: 0;
}
input, textarea, .g-recaptcha {
margin-bottom: 1rem;
}
&.comment-textarea {
width: 100%;
}
input#comment-form-reply {
display: inline;
}
}
}
/*
Toast alert styles
========================================================================== */
.notification {
text-align: center;
margin-bottom: 1rem;
* {
display: table-cell;
vertical-align: middle;
}
}
/*
Paginator
========================================================================== */
.pagination-article {
box-shadow: none !important;
}
.pagination {
text-align: center;
}
.pagination a,
.pagination span {
padding: .35rem .75rem;
display: inline-block;
@include font-rem(18);
}
a.newer {
padding-left: .35rem;
}
a.older {
padding-right: .4rem;
}
.current {
background:
lighten($light-black, 35);
border-color:
lighten($light-black, 35);
}<file_sep>_id: fc1f81d0-6709-11e8-a410-b10b2fe2b059
_parent: /blog/2013/08/16/code-highlighting-post
message: sample comment.
name: User Name
email: <PASSWORD>
url: 'http://johnabraham.me'
replying_to: '1'
date: '2018-06-03T08:42:02.235Z'
timestamp: 1528015322
tags: []
commentDate: '2018-06-03T08:42:02.235Z'
<file_sep>---
permalink: /rss
redirect_to:
- /feed.xml
---
|
923a3894079ecf0effe547200332976981748651
|
[
"Markdown",
"SCSS",
"YAML"
] | 6 |
Markdown
|
jabraham412/john4braham.github.io
|
d7b66cca60658ce1ad3fb341aa3ac01e403d30d8
|
157aedb5986f9737a22e8d6656f28bcf841e59d2
|
refs/heads/master
|
<repo_name>sgentle/sliding-blocks<file_sep>/sliding-blocks.js
// Generated by CoffeeScript 1.10.0
(function() {
var Blocks, El, SvgEl, bind, blocksProto, el, l, len, ref, srcBase;
srcBase = (function() {
var a, src;
src = document.currentScript.src;
a = document.createElement('a');
a.href = src;
a.pathname = a.pathname.split('/').slice(0, -1).join('/') + '/';
return a.href;
})();
El = function(name, attribs, content) {
var el, k, v;
if (attribs == null) {
attribs = {};
}
el = document.createElement(name);
for (k in attribs) {
v = attribs[k];
el.setAttribute(k, v);
}
if (content) {
el.textContent = content;
}
return el;
};
SvgEl = function(name, attribs, content) {
var el, k, v;
if (attribs == null) {
attribs = {};
}
el = document.createElementNS("http://www.w3.org/2000/svg", name);
for (k in attribs) {
v = attribs[k];
el.setAttribute(k, v);
}
if (content) {
el.textContent = content;
}
return el;
};
blocksProto = {
posFor: function(n) {
var x, y;
y = Math.floor(n / this.rows) * this.blockHeight;
x = n % this.rows * this.blockWidth;
return {
x: x,
y: y
};
},
nFor: function(x, y) {
return Math.floor(y / this.blockHeight) * this.cols + Math.floor(x / this.blockWidth);
},
makeBlock: function(n, title) {
var drag, dragState, g, move, rect, ref, startX, startY, startdrag, stopdrag, text, text2, x, y;
g = SvgEl('g', {
fill: 'white'
});
ref = this.posFor(n), x = ref.x, y = ref.y;
rect = SvgEl('rect', {
x: x,
y: y,
width: this.blockWidth,
height: this.blockHeight,
stroke: 'black'
});
text = SvgEl('text', {
x: x + this.blockWidth / 2,
y: y + this.blockHeight * (2 / 3),
fill: '#444',
stroke: '#000',
'font-size': (this.blockHeight / 2) + "px",
'font-family': '"verdana"',
'font-weight': 'bold',
'text-anchor': 'middle',
'pointer-events': 'none'
}, title || n + 1);
move = (function(_this) {
return function(x, y) {
var tx, ty;
rect.setAttribute('x', x);
rect.setAttribute('y', y);
tx = x + _this.blockWidth / 2;
ty = y + _this.blockHeight * (2 / 3);
text.setAttribute('x', tx);
text.setAttribute('y', ty);
if (text2) {
text2.setAttribute('x', tx);
return text2.setAttribute('y', ty);
}
};
})(this);
startX = null;
startY = null;
dragState = null;
startdrag = (function(_this) {
return function(ev) {
var e, l, len, len1, o, ref1, ref2, ref3, ref4, ref5, results;
if (dragState) {
return;
}
ref1 = [Number(rect.getAttribute('x')), Number(rect.getAttribute('y'))], x = ref1[0], y = ref1[1];
n = _this.nFor(x, y);
ev.preventDefault();
console.log("startdrag");
dragState = 'dragging';
startX = (ref2 = ev.pageX) != null ? ref2 : ev.touches[0].pageX;
startY = (ref3 = ev.pageY) != null ? ref3 : ev.touches[0].pageY;
ref4 = ['mousemove', 'touchmove'];
for (l = 0, len = ref4.length; l < len; l++) {
e = ref4[l];
window.addEventListener(e, drag);
}
ref5 = ['mouseup', 'touchend', 'mouseleave', 'touchcancel'];
results = [];
for (o = 0, len1 = ref5.length; o < len1; o++) {
e = ref5[o];
results.push(window.addEventListener(e, stopdrag));
}
return results;
};
})(this);
stopdrag = (function(_this) {
return function(ev) {
var e, l, len, len1, newn, o, ref1, ref2, ref3, results, solved;
if (!dragState) {
return;
}
console.log("stopdrag", dragState);
newn = {
left: n - 1,
right: n + 1,
up: n - _this.cols,
down: n + _this.cols
}[dragState];
dragState = null;
if ((newn != null) && _this.blocks[newn] === null) {
_this.blocks[newn] = g;
_this.blocks[n] = null;
ref1 = _this.posFor(newn), x = ref1.x, y = ref1.y;
move(x, y);
n = newn;
solved = _this.checkSolved();
if (solved && !_this.targets) {
_this.addTargets();
}
if (_this.intercat) {
_this.checkIntercat();
}
} else {
move(x, y);
}
ref2 = ['mousemove', 'touchmove'];
for (l = 0, len = ref2.length; l < len; l++) {
e = ref2[l];
window.removeEventListener(e, drag);
}
ref3 = ['mouseup', 'touchend', 'mouseleave', 'touchcancel'];
results = [];
for (o = 0, len1 = ref3.length; o < len1; o++) {
e = ref3[o];
results.push(window.removeEventListener(e, stopdrag));
}
return results;
};
})(this);
drag = (function(_this) {
return function(ev) {
var diffX, diffY, ref1, ref2;
diffX = ((ref1 = ev.pageX) != null ? ref1 : ev.touches[0].pageX) - startX;
diffY = ((ref2 = ev.pageY) != null ? ref2 : ev.touches[0].pageY) - startY;
dragState = 'dragging';
if (diffX > 0 && _this.blocks[n + 1] === null && ((n + 1) % _this.cols !== 0)) {
if (diffX > _this.blockWidth / 2) {
dragState = 'right';
}
return move(x + Math.min(diffX, _this.blockWidth), y);
} else if (diffX < 0 && _this.blocks[n - 1] === null && (n % _this.cols !== 0)) {
if (diffX < -_this.blockWidth / 2) {
dragState = 'left';
}
return move(x + Math.max(diffX, -_this.blockWidth), y);
} else if (diffY > 0 && _this.blocks[n + _this.cols] === null) {
if (diffY > _this.blockHeight / 2) {
dragState = 'down';
}
return move(x, y + Math.min(diffY, _this.blockHeight));
} else if (diffY < 0 && _this.blocks[n - _this.cols] === null) {
if (diffY < -_this.blockHeight / 2) {
dragState = 'up';
}
return move(x, y + Math.max(diffY, -_this.blockHeight));
} else {
return move(x, y);
}
};
})(this);
rect.addEventListener('mousedown', startdrag);
rect.addEventListener('touchstart', startdrag);
g.appendChild(rect);
g.appendChild(text);
if (title && title[title.length - 1] === '.') {
text2 = text.cloneNode();
text.textContent = title.slice(0, title.length - 1);
text2.textContent = '.';
setTimeout(function() {
return text2.setAttribute('dx', text.getBBox().width / 2 + 'px');
}, 10);
if (text2) {
g.appendChild(text2);
}
}
return g;
},
add: function(title) {
var el;
if (title != null) {
el = this.makeBlock(this.blocks.length, title);
this.el.appendChild(el);
this.blocks.push(el);
return this.origBlocks.push(el);
} else {
this.blocks.push(null);
return this.origBlocks.push(null);
}
},
addColors: function() {
var el, hue, i, l, len, ref, results;
ref = this.blocks;
results = [];
for (i = l = 0, len = ref.length; l < len; i = ++l) {
el = ref[i];
if (!(el)) {
continue;
}
hue = 360 * (i / (this.blocks.length - 1));
results.push(el.setAttribute('fill', "hsl(" + hue + ", 55%, 70%)"));
}
return results;
},
drawTarget: function(n, done) {
var adjWidth, block, blockperm, blx, bly, count, el, i, l, len, oy, ratio, scale, spacing;
oy = this.height + 10;
count = this.blocks.length;
spacing = this.blockWidth / count;
adjWidth = this.width + spacing * count;
scale = adjWidth / count - 10;
ratio = this.height / this.width;
if (this.targets[n]) {
this.targets[n].remove();
}
el = SvgEl('g');
this.targets[n] = el;
el.appendChild(SvgEl('rect', {
x: n * scale,
y: oy,
width: scale - spacing,
height: ratio * scale,
fill: 'white'
}));
blockperm = this.origBlocks.slice().filter(Boolean);
blockperm.splice(n, 0, null);
for (i = l = 0, len = blockperm.length; l < len; i = ++l) {
block = blockperm[i];
if (!(block)) {
continue;
}
blx = i % this.rows;
bly = Math.floor(i / this.rows);
el.appendChild(SvgEl('rect', {
x: n * scale + (blx * (this.blockWidth * (3 / 4) / count)),
y: oy + (bly * (this.blockHeight * (3 / 4) / count)),
width: (this.blockWidth * (3 / 4)) / count,
height: this.blockHeight * (3 / 4) / count,
fill: done ? block != null ? block.getAttribute('fill') : void 0 : '#ddd'
}));
}
return this.el.appendChild(el);
},
addTargets: function() {
var l, n, ref;
this.el.setAttribute('height', this.height + this.height / 4);
this.targets = [];
this.solved = [];
for (n = l = 0, ref = this.blocks.length - 1; 0 <= ref ? l <= ref : l >= ref; n = 0 <= ref ? ++l : --l) {
this.drawTarget(n);
this.solved[n] = false;
}
return this.checkSolved();
},
checkSolved: function() {
var i, j, n;
n = null;
i = 0;
j = 0;
while (i < this.blocks.length) {
if (this.blocks[i] === null) {
n = i++;
continue;
}
if (this.origBlocks[j] === null) {
j++;
continue;
}
if (this.blocks[i] !== this.origBlocks[j]) {
return false;
}
i++;
j++;
}
if (this.targets) {
if (!this.solved[n]) {
this.drawTarget(n, true);
}
this.solved[n] = true;
if (this.solved.filter(Boolean).length === this.blocks.length) {
this.addIntercat();
}
}
return n;
},
addIntercat: function() {
if (this.intercat) {
return;
}
this.intercat = SvgEl('g', {
fill: '#ddd'
});
this.intercat.appendChild(SvgEl('text', {
x: this.width / 2,
y: this.height + this.blockHeight / 2 + 10,
'font-size': (this.blockHeight / 4) + "px",
'font-family': '"verdana"',
'font-weight': 'bold',
'text-anchor': 'middle'
}, "INTERCAT"));
return this.el.appendChild(this.intercat);
},
checkIntercat: function() {
var el, i, l, len, match, ref;
match = "INTERCAT";
ref = this.blocks.filter(Boolean);
for (i = l = 0, len = ref.length; l < len; i = ++l) {
el = ref[i];
if (match[i] !== el.querySelector('text').textContent) {
return false;
}
}
if (!this.finished) {
this.finishIntercat();
}
return true;
},
finishIntercat: function() {
var audio, el, i, l, len, len1, o, ref, ref1;
this.finished = true;
this.intercat.setAttribute('fill', 'url(#rainbow)');
audio = new Audio();
if (audio.canPlayType('audio/mp3')) {
audio.src = srcBase + 'music.mp3';
}
if (audio.canPlayType('audio/ogg')) {
audio.src = srcBase + 'music.ogg';
}
audio.currentTime;
audio.play();
this.intercat.style.transformOrigin = "50% 50%";
this.intercat.style.transformBox = "fill-box";
this.intercat.style.animation = '423ms sb-pulse 0s infinite';
ref = this.blocks.filter(Boolean);
for (i = l = 0, len = ref.length; l < len; i = ++l) {
el = ref[i];
el.style.transformOrigin = '50% 50%';
el.style.transformBox = "fill-box";
el.style.animation = (423 * 8) + "ms sb-spin " + (Math.round(i * 423)) + "ms infinite";
}
ref1 = this.targets;
for (i = o = 0, len1 = ref1.length; o < len1; i = ++o) {
el = ref1[i];
el.style.transformOrigin = '50% 50%';
el.style.transformBox = "fill-box";
el.style.animation = "423ms sb-bounce " + (Math.round(i / 9 * 423)) + "ms infinite";
}
return this.el.querySelector('rect').setAttribute('fill', 'url(#rainbow)');
},
shuffle: function(times) {
var dir, down, i, lastdir, lastswap, left, m, n, results, right, swap, up;
if (times == null) {
times = 50;
}
console.log("shuffle");
i = 0;
n = this.blocks.indexOf(null);
if (n === -1) {
return;
}
lastswap = null;
swap = (function(_this) {
return function(n, m) {
var ref;
console.log("swap", n, m);
lastswap = m;
ref = [_this.blocks[m], _this.blocks[n]], _this.blocks[n] = ref[0], _this.blocks[m] = ref[1];
_this.move(_this.blocks[n], n);
_this.move(_this.blocks[m], m);
return m;
};
})(this);
up = (function(_this) {
return function(n) {
if (n > _this.cols) {
return swap(n, n - _this.cols);
}
};
})(this);
down = (function(_this) {
return function(n) {
if (n < _this.blocks.length - _this.cols) {
return swap(n, n + _this.cols);
}
};
})(this);
left = (function(_this) {
return function(n) {
if (n > 0 && n % _this.cols !== 0) {
return swap(n, n - 1);
}
};
})(this);
right = (function(_this) {
return function(n) {
if (n < _this.blocks.length - 1 && (n + 1) % _this.cols !== 0) {
return swap(n, n + 1);
}
};
})(this);
results = [];
while (i < times || this.checkSolved()) {
m = null;
dir = Math.floor(Math.random() * 4);
while ((m = [up, left, down, right][dir](n)) == null) {
dir = (dir + 1) % 4;
}
lastdir = dir;
if (m != null) {
n = m;
}
results.push(i++);
}
return results;
},
move: function(el, n) {
var rect, ref, ref1, text, text2, tx, ty, x, y;
if (!el) {
return;
}
ref = this.posFor(n), x = ref.x, y = ref.y;
rect = el.querySelector('rect');
ref1 = el.querySelectorAll('text'), text = ref1[0], text2 = ref1[1];
rect.setAttribute('x', x);
rect.setAttribute('y', y);
tx = x + this.blockWidth / 2;
ty = y + this.blockHeight * (2 / 3);
text.setAttribute('x', tx);
text.setAttribute('y', ty);
if (text2) {
text2.setAttribute('x', tx);
return text2.setAttribute('y', ty);
}
}
};
Blocks = function(width, height, rows, cols) {
var blocks, defs, k, rainbow, ref, v;
if (width == null) {
width = 300;
}
if (height == null) {
height = 300;
}
if (rows == null) {
rows = 3;
}
if (cols == null) {
cols = 3;
}
blocks = Object.create(blocksProto);
blocks.blocks = [];
blocks.origBlocks = [];
ref = {
width: width,
height: height,
rows: rows,
cols: cols
};
for (k in ref) {
v = ref[k];
blocks[k] = v;
}
blocks.blockWidth = blocks.width / blocks.cols;
blocks.blockHeight = blocks.height / blocks.rows;
blocks.el = SvgEl('svg', {
xmlns: 'http://www.w3.org/2000/svg',
width: width,
height: height
});
blocks.defs = defs = SvgEl('defs');
blocks.el.appendChild(defs);
rainbow = SvgEl('linearGradient', {
id: 'rainbow',
x1: '0%',
y1: '0%',
x2: '100%',
y2: '100%',
spreadMethod: 'pad'
});
rainbow.appendChild(SvgEl('stop', {
offset: '0%',
'stop-color': '#ff0000'
}));
rainbow.appendChild(SvgEl('stop', {
offset: '17%',
'stop-color': '#ffff00'
}));
rainbow.appendChild(SvgEl('stop', {
offset: '34%',
'stop-color': '#00ff00'
}));
rainbow.appendChild(SvgEl('stop', {
offset: '50%',
'stop-color': '#00ffff'
}));
rainbow.appendChild(SvgEl('stop', {
offset: '66%',
'stop-color': '#0000ff'
}));
rainbow.appendChild(SvgEl('stop', {
offset: '82%',
'stop-color': '#ff00ff'
}));
rainbow.appendChild(SvgEl('stop', {
offset: '100%',
'stop-color': '#ff0000'
}));
defs.appendChild(rainbow);
blocks.el.appendChild(SvgEl('rect', {
x: 0,
y: 0,
width: width,
height: height,
fill: '#555'
}));
return blocks;
};
bind = function(el) {
var blocks, child, l, len, opts, ref, x;
opts = (function() {
var l, len, ref, results;
ref = ['width', 'height', 'rows', 'cols'];
results = [];
for (l = 0, len = ref.length; l < len; l++) {
x = ref[l];
results.push(el.getAttribute(Number(x) || void 0));
}
return results;
})();
blocks = Blocks.apply(null, opts);
ref = el.children;
for (l = 0, len = ref.length; l < len; l++) {
child = ref[l];
switch (child.nodeName) {
case 'S-BLOCK':
blocks.add(child.textContent);
break;
case 'S-BLANK':
blocks.add(null);
break;
default:
console.warn("unknown block type: " + child.nodeName);
}
}
el.innerHTML = "";
blocks.addColors();
if (el.getAttribute('shuffle') != null) {
blocks.shuffle();
}
if (el.getAttribute('targets') != null) {
blocks.withTargets = true;
}
return el.appendChild(blocks.el);
};
ref = document.querySelectorAll('sliding-blocks');
for (l = 0, len = ref.length; l < len; l++) {
el = ref[l];
bind(el);
}
document.body.appendChild(El('style', {}, "@keyframes sb-spin {\n 0% { transform: rotate(0deg) }\n 12.5% { transform: rotate(360deg) }\n 100% { transform: rotate(360deg) }\n}\n@keyframes sb-pulse {\n 0% { transform: scale(1) }\n 50% { transform: scale(1.2) }\n 0% { transform: scale(1) }\n}\n@keyframes sb-bounce {\n 0% { transform: translateY(0px) }\n 33.33% { transform: translateY(-30px) }\n 100% { transform: translateY(0px) }\n}"));
}).call(this);
<file_sep>/sliding-blocks.coffee.md
Sliding Blocks
==============
This is a simple sliding blocks puzzle game. If you're reading this and you
haven't played it, you might want to do that first:
https://demos.samgentle.com/sliding-blocks
Helpers
-------
These are some simple helpers for later on. `srcBase` is the parent of this
file, which is where we look for media.
srcBase = do ->
src = document.currentScript.src
a = document.createElement 'a'
a.href = src
a.pathname = a.pathname.split('/').slice(0, -1).join('/') + '/'
a.href
`El` and `SvgEl` are element creation helpers.
El = (name, attribs={}, content) ->
el = document.createElement name
el.setAttribute k, v for k, v of attribs
el.textContent = content if content
el
SvgEl = (name, attribs={}, content) ->
el = document.createElementNS "http://www.w3.org/2000/svg", name
el.setAttribute k, v for k, v of attribs
el.textContent = content if content
el
Blocks
------
Blocks are represented as an array with a bunch of methods on it.
The Blocks prototype is a big mess. If I were doing this again I would add a
separate `Block` proto and give individual blocks their own methods.
blocksProto =
`posFor` and `nFor` convert back and forth between array indices and x/y coordinates.
posFor: (n) ->
y = n // @rows * @blockHeight
x = n % @rows * @blockWidth
{x, y}
nFor: (x, y) ->
y // @blockHeight * @cols + x // @blockWidth
`makeBlock` is basically our block constructor. It creates the relevant SVG
elements and adds event listeners to move them around.
makeBlock: (n, title) ->
g = SvgEl 'g',
fill: 'white'
{x, y} = @posFor n
rect = SvgEl 'rect',
x: x
y: y
width: @blockWidth
height: @blockHeight
stroke: 'black'
text = SvgEl 'text',
x: x + @blockWidth/2
y: y + @blockHeight * (2/3)
fill: '#444'
stroke: '#000'
'font-size': "#{@blockHeight/2}px"
'font-family': '"verdana"'
'font-weight': 'bold'
'text-anchor': 'middle'
'pointer-events': 'none'
, title || n + 1
move = (x, y) =>
rect.setAttribute 'x', x
rect.setAttribute 'y', y
tx = x + @blockWidth/2
ty = y + @blockHeight * (2/3)
text.setAttribute 'x', tx
text.setAttribute 'y', ty
if text2
text2.setAttribute 'x', tx
text2.setAttribute 'y', ty
Here, we handle dragging. The mousedown/touchstart handler adds event
listeners to `window` and removes them afterwards, so we don't have to bother
filtering move events.
startX = null
startY = null
dragState = null
startdrag = (ev) =>
return if dragState
[x, y] = [Number(rect.getAttribute('x')), Number(rect.getAttribute('y'))]
n = @nFor x, y
ev.preventDefault()
console.log "startdrag"
dragState = 'dragging'
startX = (ev.pageX ? ev.touches[0].pageX)
startY = (ev.pageY ? ev.touches[0].pageY)
window.addEventListener e, drag for e in ['mousemove', 'touchmove']
window.addEventListener e, stopdrag for e in ['mouseup', 'touchend', 'mouseleave', 'touchcancel']
stopdrag = (ev) =>
return unless dragState
console.log "stopdrag", dragState
newn = {left: n - 1, right: n + 1, up: n - @cols, down: n + @cols}[dragState]
dragState = null
if newn? and @blocks[newn] is null
@blocks[newn] = g
@blocks[n] = null
{x, y} = @posFor newn
move(x, y)
n = newn
solved = @checkSolved()
if solved and !@targets
@addTargets()
@checkIntercat() if @intercat
else
move(x, y)
window.removeEventListener e, drag for e in ['mousemove', 'touchmove']
window.removeEventListener e, stopdrag for e in ['mouseup', 'touchend', 'mouseleave', 'touchcancel']
drag = (ev) =>
diffX = (ev.pageX ? ev.touches[0].pageX) - startX
diffY = (ev.pageY ? ev.touches[0].pageY) - startY
dragState = 'dragging'
if diffX > 0 && @blocks[n + 1] is null && ((n + 1) % @cols isnt 0)
dragState = 'right' if diffX > @blockWidth/2
move(x + Math.min(diffX, @blockWidth), y)
else if diffX < 0 && @blocks[n - 1] is null && (n % @cols isnt 0)
dragState = 'left' if diffX < -@blockWidth/2
move(x + Math.max(diffX, -@blockWidth), y)
else if diffY > 0 && @blocks[n + @cols] is null
dragState = 'down' if diffY > @blockHeight/2
move(x, y + Math.min(diffY, @blockHeight))
else if diffY < 0 && @blocks[n - @cols] is null
dragState = 'up' if diffY < -@blockHeight/2
move(x, y + Math.max(diffY, -@blockHeight))
else
move(x, y)
rect.addEventListener 'mousedown', startdrag
rect.addEventListener 'touchstart', startdrag
g.appendChild rect
g.appendChild text
This is a bit of a hack to support distinguishing between "T." and "T", we add
a second text layer and offset it a bit. (If we did things the naive way then
the T. would be positioned differently to the other letters and look weird.
if title and title[title.length-1] == '.'
text2 = text.cloneNode()
text.textContent = title.slice(0, title.length-1)
text2.textContent = '.'
setTimeout ->
text2.setAttribute 'dx', text.getBBox().width / 2 + 'px'
, 10
g.appendChild text2 if text2
g
`add` adds a block to our Blocks. `origBlocks` is kept so we can check whether we have a solution.
add: (title) ->
if title?
el = @makeBlock @blocks.length, title
@el.appendChild el
@blocks.push el
@origBlocks.push el
else
@blocks.push null
@origBlocks.push null
When we're done adding blocks, we can colour them with `addColors`, which does a simple hue cycle.
addColors: ->
for el, i in @blocks when el
hue = 360 * (i / (@blocks.length - 1))
el.setAttribute 'fill', "hsl(#{hue}, 55%, 70%)"
`drawTarget` is responsible for the little targets underneath once you have solved one version of the puzzle
drawTarget: (n, done) ->
oy = @height + 10
count = @blocks.length
spacing = @blockWidth / count
adjWidth = @width + spacing * (count)
scale = adjWidth / count - 10
ratio = @height / @width
if @targets[n]
@targets[n].remove()
el = SvgEl 'g'
@targets[n] = el
el.appendChild SvgEl 'rect',
x: n * scale
y: oy
width: scale - spacing
height: ratio * scale
fill: 'white'
blockperm = @origBlocks.slice().filter(Boolean)
blockperm.splice(n, 0, null)
for block, i in blockperm when block
blx = i % @rows
bly = i // @rows
el.appendChild SvgEl 'rect',
x: n * scale + (blx * (@blockWidth * (3/4) / count))
y: oy + (bly * (@blockHeight * (3/4) / count))
width: (@blockWidth * (3/4)) / count
height: @blockHeight * (3/4) / count
fill: if done then block?.getAttribute('fill') else '#ddd'
@el.appendChild el
`addTargets` just loops through the blocks and calls `drawTarget`. Also makes a bit of extra space in the SVG element.
addTargets: ->
@el.setAttribute 'height', @height + @height/4
@targets = []
@solved = []
for n in [0..@blocks.length-1]
@drawTarget n
@solved[n] = false
@checkSolved()
`checkSolved` is how we know when we've found a solution. To account for
variable blank placement, we skip nulls in blocks and origBlocks
checkSolved: ->
n = null
i = 0
j = 0
while i < @blocks.length
if @blocks[i] is null
n = i++
continue
if @origBlocks[j] is null
j++
continue
return false if @blocks[i] != @origBlocks[j]
i++
j++
if @targets
@drawTarget n, true unless @solved[n]
@solved[n] = true
@addIntercat() if @solved.filter(Boolean).length == @blocks.length
return n
These are Intercat related things
addIntercat: ->
return if @intercat
@intercat = SvgEl 'g',
fill: '#ddd'
@intercat.appendChild SvgEl 'text',
x: @width / 2
y: @height + @blockHeight / 2 + 10
'font-size': "#{@blockHeight/4}px"
'font-family': '"verdana"'
'font-weight': 'bold'
'text-anchor': 'middle'
, "INTERCAT"
@el.appendChild @intercat
checkIntercat: ->
match = "INTERCAT"
for el, i in @blocks.filter(Boolean)
# console.log "check", el.querySelector('text').textContent, match[i]
return false unless match[i] == el.querySelector('text').textContent
@finishIntercat() unless @finished
return true
finishIntercat: ->
@finished = true
@intercat.setAttribute 'fill', 'url(#rainbow)'
audio = new Audio()
audio.src = srcBase + 'music.mp3' if audio.canPlayType('audio/mp3')
audio.src = srcBase + 'music.ogg' if audio.canPlayType('audio/ogg')
audio.currentTime
audio.play()
@intercat.style.transformOrigin = "50% 50%"
@intercat.style.transformBox = "fill-box"
@intercat.style.animation = '423ms sb-pulse 0s infinite'
for el, i in @blocks.filter(Boolean)
el.style.transformOrigin = '50% 50%'
el.style.transformBox = "fill-box"
el.style.animation = "#{423 * 8}ms sb-spin #{Math.round(i * 423)}ms infinite"
for el, i in @targets
el.style.transformOrigin = '50% 50%'
el.style.transformBox = "fill-box"
el.style.animation = "423ms sb-bounce #{Math.round(i/9 * 423)}ms infinite"
@el.querySelector('rect').setAttribute 'fill', 'url(#rainbow)'
This is the code that shuffles the board at the start.
shuffle: (times=50) ->
console.log "shuffle"
i = 0
n = @blocks.indexOf(null)
return if n is -1
lastswap = null
swap = (n, m) =>
console.log("swap", n, m)
lastswap = m
[@blocks[n], @blocks[m]] = [@blocks[m], @blocks[n]]
@move @blocks[n], n
@move @blocks[m], m
m
up = (n) => swap(n, n - @cols) if n > @cols
down = (n) => swap(n, n + @cols) if n < @blocks.length - @cols
left = (n) => swap(n, n - 1) if n > 0 and n % @cols != 0
right = (n) => swap(n, n + 1) if n < @blocks.length - 1 and (n + 1) % @cols != 0
while i < times or @checkSolved()
m = null
dir = Math.floor(Math.random() * 4)
until (m = [up, left, down, right][dir](n))?
dir = (dir + 1) % 4
lastdir = dir
n = m if m?
i++
`move` can't cause a block to move by itself, so we have to just reach in and
fiddle with its properties. This is part of the reason it would be better to
have a separate Block object.
move: (el, n) ->
return unless el
{x, y} = @posFor n
rect = el.querySelector 'rect'
[text, text2] = el.querySelectorAll 'text'
rect.setAttribute 'x', x
rect.setAttribute 'y', y
tx = x + @blockWidth/2
ty = y + @blockHeight * (2/3)
text.setAttribute 'x', tx
text.setAttribute 'y', ty
if text2
text2.setAttribute 'x', tx
text2.setAttribute 'y', ty
This is the constructor for our puzzle. We set up an SVG element and put some
basic things in there, but we expect addBlocks to be called to populate it.
Blocks = (width=300, height=300, rows=3, cols=3) ->
blocks = Object.create blocksProto
blocks.blocks = []
blocks.origBlocks = []
blocks[k] = v for k, v of {width, height, rows, cols}
blocks.blockWidth = blocks.width / blocks.cols
blocks.blockHeight = blocks.height / blocks.rows
blocks.el = SvgEl 'svg',
xmlns: 'http://www.w3.org/2000/svg'
width: width
height: height
blocks.defs = defs = SvgEl 'defs'
blocks.el.appendChild defs
rainbow = SvgEl 'linearGradient',
id: 'rainbow'
x1: '0%', y1: '0%', x2: '100%', y2: '100%'
spreadMethod: 'pad'
rainbow.appendChild SvgEl 'stop', offset: '0%', 'stop-color': '#ff0000'
rainbow.appendChild SvgEl 'stop', offset: '17%', 'stop-color': '#ffff00'
rainbow.appendChild SvgEl 'stop', offset: '34%', 'stop-color': '#00ff00'
rainbow.appendChild SvgEl 'stop', offset: '50%', 'stop-color': '#00ffff'
rainbow.appendChild SvgEl 'stop', offset: '66%', 'stop-color': '#0000ff'
rainbow.appendChild SvgEl 'stop', offset: '82%', 'stop-color': '#ff00ff'
rainbow.appendChild SvgEl 'stop', offset: '100%', 'stop-color': '#ff0000'
defs.appendChild rainbow
blocks.el.appendChild SvgEl 'rect',
x: 0, y: 0, width: width, height: height
fill: '#555'
blocks
This is the glue to connect the `Blocks` instance to a DOM element. We read
the `<s-block>` and `<s-blank>` elements out and then turn them into our own
representation of blocks and blanks.
bind = (el) ->
opts = (el.getAttribute Number(x) or undefined for x in ['width', 'height', 'rows', 'cols'])
blocks = Blocks(opts...)
for child in el.children
switch child.nodeName
when 'S-BLOCK'
blocks.add child.textContent
when 'S-BLANK'
blocks.add null
else
console.warn "unknown block type: #{child.nodeName}"
el.innerHTML = ""
blocks.addColors()
blocks.shuffle() if el.getAttribute('shuffle')?
blocks.withTargets = true if el.getAttribute('targets')?
el.appendChild blocks.el
bind el for el in document.querySelectorAll('sliding-blocks')
Some css animations, because yay globals.
document.body.appendChild El 'style', {}, """
@keyframes sb-spin {
0% { transform: rotate(0deg) }
12.5% { transform: rotate(360deg) }
100% { transform: rotate(360deg) }
}
@keyframes sb-pulse {
0% { transform: scale(1) }
50% { transform: scale(1.2) }
0% { transform: scale(1) }
}
@keyframes sb-bounce {
0% { transform: translateY(0px) }
33.33% { transform: translateY(-30px) }
100% { transform: translateY(0px) }
}
"""
|
3f57950b05ce38c8e6a4da62244102007ec2be18
|
[
"Literate CoffeeScript",
"JavaScript"
] | 2 |
Literate CoffeeScript
|
sgentle/sliding-blocks
|
b9483ed37f8abd16315bbc2e6a7273b3aae70c18
|
6a0b1ca293919e1190e4ae2301636980cbfcede5
|
refs/heads/master
|
<file_sep># Wedding-Invitation
Online wedding invitation mock up
|
220a4e30fdb04a3c2ea7b4b8274935b91f41937e
|
[
"Markdown"
] | 1 |
Markdown
|
MWright87/Wedding-Invitation
|
5961e76b915a4bf926a90c95370d1b862bb1fce1
|
ce9e1306729501c564bf1176c2d5d71119bdb52e
|
refs/heads/master
|
<file_sep><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>board Insert Form</title>
</head>
<body>
<h1> 게시판 글쓰기 </h1>
<br>
<form id="form1" name="form1" method="post" action="./BoardInsert">
title : <input type="text" maxlength="50" size="50" id="title" name="title"/>
<br><br>
writer : <input type="text" maxlength="10" size="10" id="writer" name="writer"/>
<br><br>
contents : <textarea maxlength="1000" rows="5" cols="50" id="contents" name="contents"></textarea>
<br> <br>
<input type="submit" />
</form>
</body>
</html><file_sep>package ch3;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
public class BoardListDAO {
public ArrayList<BoardVO> select(){
ArrayList<BoardVO> blist = new ArrayList<BoardVO>();
BoardVO bVo = null;
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String id = "scott";
String pwd = "<PASSWORD>";
String sql = "select b_no, b_title, b_writer, b_contents"
+ ", reg_date from board"
+ " order by b_no";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, id, pwd);
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
//HashMap<String,String> map = new HashMap<String, String>();
bVo = new BoardVO();
bVo.setB_no(rs.getString("b_no"));
bVo.setB_title(rs.getString("b_title"));
bVo.setB_writer(rs.getString("b_writer"));
bVo.setB_contents(rs.getString("b_contents"));
bVo.setReg_date(rs.getString("reg_date"));
blist.add(bVo);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//System.out.print(blist);
return blist;
}//close select
}
<file_sep>package ch3;
public class MemberVO {
private String m_no;
private String m_nm;
private String m_tel;
private String m_email;
private String reg_date;
private String del_yn;
public String getM_no() {
return m_no;
}
public void setM_no(String m_no) {
this.m_no = m_no;
}
public String getM_nm() {
return m_nm;
}
public void setM_nm(String m_nm) {
this.m_nm = m_nm;
}
public String getM_tel() {
return m_tel;
}
public void setM_tel(String m_tel) {
this.m_tel = m_tel;
}
public String getM_email() {
return m_email;
}
public void setM_email(String m_email) {
this.m_email = m_email;
}
public String getReg_date() {
return reg_date;
}
public void setReg_date(String reg_date) {
this.reg_date = reg_date;
}
public String getDel_yn() {
return del_yn;
}
public void setDel_yn(String del_yn) {
this.del_yn = del_yn;
}
}
<file_sep>package ch3;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
public class BoardInsertDAO {
//HashMap<String, String> map;
/*public BoardInsertDAO() {
// TODO Auto-generated constructor stub
//map = inMap;
}*/
public int insert(HashMap<String, String> map) {
String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
String id = "scott";
String pwd = "<PASSWORD>";
String sql = "insert into board (b_no, b_title, b_writer, b_contents, reg_date)"
+ "values("
+ "board_no_seq.nextval, ?, ?, ?, sysdate)";
int scnt = 0;
Connection conn = null;
PreparedStatement psmt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, id, pwd);
psmt = conn.prepareStatement(sql);
psmt.setString(1, map.get("title"));
psmt.setString(2, map.get("writer"));
psmt.setString(3, map.get("contents"));
scnt = psmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
psmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return scnt;
}//close insert
public ArrayList<HashMap> select(){
ArrayList<HashMap> blist = new ArrayList<HashMap>();
String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
String id = "scott";
String pwd = "<PASSWORD>";
String sql = "select b_no, b_title, b_writer, b_contents"
+ ", reg_date from board"
+ " order by no";
try {
Connection conn = DriverManager.getConnection(url, id, pwd);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
HashMap<String,String> map = new HashMap<String, String>();
map.put("b_no", rs.getString("b_no"));
map.put("b_title", rs.getString("b_title"));
map.put("b_writer", rs.getString("b_writer"));
map.put("b_contents", rs.getString("b_contents"));
map.put("reg_date", rs.getString("reg_date"));
// map.put("clickcnt", rs.getString("clickcnt"));
blist.add(map);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
//System.out.print(blist);
return blist;
}//close select
}
|
55ea549e230163199769f6f3cd5218918f0ea087
|
[
"Java",
"Java Server Pages"
] | 4 |
Java
|
vt0311/servletBoard
|
064e5ced4cc4550267f46e68a7730480184e5c13
|
d888c2d8567511ec2b2694662aff469e8f8f10d3
|
refs/heads/master
|
<repo_name>kayleighkat98/webpack-bookmark<file_sep>/src/index.js
import $ from 'jquery';
import api from './api';
import './index.css';
import store from './STORE';
import bookmarks from './App';
// if (bookmarks.filterValue() == null){
// console.log ('Yes')
// } else {
// console.log('NO')
// }
const main = function () {
api.getMarks()
.then((items) => {
items.forEach((item) => (
store.addItem(item)
));
bookmarks.render();
});
bookmarks.bindEventListeners();
bookmarks.render();
};
$(main)<file_sep>/src/STORE.js
import $ from 'jquery';
const items = [];
let error = null;
let minimumRating= 0;
const addItem = function (item) {
this.items.push(item);
};
const findAndDelete = function (id) {
this.items = this.items.filter(currentItem => currentItem.id !== id);
};
const findAndUpdate = function(id, newData){
const bookmark = this.findById(id);
Object.assign(bookmark, newData);
};
const setError = function (error) {
this.error = error;
};
export default {
items,
error,
minimumRating,
findAndUpdate,
addItem,
findAndDelete,
setError
};
|
a8a93249087badea382de2c9cf302bd42528fc4c
|
[
"JavaScript"
] | 2 |
JavaScript
|
kayleighkat98/webpack-bookmark
|
97f0a708b5e6152938be01cd421a2fe43c685d2b
|
448ee7eaffaef066fd24ea8b891c0c45e2f54917
|
refs/heads/master
|
<repo_name>bartekv2/crud<file_sep>/app/helpers/posts_helper.rb
module PostsHelper
def format_date(date)
date.strftime("%d.%m.%Y")
end
def post_footer(post)
"<cite>#{post.author}, #{format_date(post.created_at)}</cite>".html_safe
end
def current_class?(test_path)
if request.path == test_path
return 'nav-link active'
else
return 'nav-link'
end
''
end
end
|
65250979b40350bed38318bc118eb25451a2c9cf
|
[
"Ruby"
] | 1 |
Ruby
|
bartekv2/crud
|
a4206114e24fba907d508c1fc5151b5d2224f4d6
|
fdfc64ef635931796a3ab54f9c3f66438a295839
|
refs/heads/master
|
<repo_name>silpasusanalex/Onlineexaminationproject<file_sep>/Onlineexamination/ConnectionClass.php
<?php
class ConnectionClass
{
public function __construct()
{
require("config.php");
//echo "<h1>"."Constructed Created"."</h1>";
}
public function operation($qry) //insertion,deletion,updation
{
$response =array();
try
{
$result=mysql_query($qry);
if($result)
$response['Status']="true";
else
throw new Exception(mysql_error());
}
catch(Exception $e)
{
$response['Status']="false";
$response['Message']= $e->getMessage();
}
mysql_close();
return ($response);
}
public function selectdata($qry) //select * from
{
try
{
$result=mysql_query($qry);// or throw new Exception("Error in Query");
if($result)
{
$data = array(); // create a variable to hold the information
while (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false)
{
$data[] = $row; // add the row in to the results (data) array
}
return $data;
}
else
throw new Exception(mysql_error());
}
catch(Exception $e)
{
return $e->getMessage();
}
mysql_close();
}
public function GetSingleData($qry)
{
try
{
$result=mysql_query($qry);// or throw new Exception("Error in Query");
if($result)
{
//$data = array(); // create a variable to hold the information
$row = mysql_fetch_row($result) ;
// $data = $row; // add the row in to the results (data) array
return $row[0];
}
else
throw new Exception(mysql_error());
}
catch(Exception $e)
{
return $e->getMessage();
}
mysql_close($con);
}
public function SendMail($to1,$subject,$body)
{
require_once('SMTPmail/SMTPconfig.php');
require_once('SMTPmail/SMTPClass.php');
$to = $to1;
$from = "<EMAIL>";
$SMTPMail = new SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body);
$SMTPChat = $SMTPMail->SendMail();
}
public function GetSingleRow($qry)
{
try
{
$result=mysql_query($qry);// or throw new Exception("Error in Query");
if($result)
{
//$data = array(); // create a variable to hold the information
$row = mysql_fetch_array($result) ;
// $data = $row; // add the row in to the results (data) array
return $row;
}
else
throw new Exception(mysql_error());
}
catch(Exception $e)
{
return $e->getMessage();
}
mysql_close($con);
}
public function GenerateID($qry,$num)
{
try
{
$result=mysql_query($qry);// or throw new Exception("Error in Query");
if($result)
{
//$data = array(); // create a variable to hold the information
$row = mysql_fetch_row($result) ;
if(empty($row[0]))
{
$maxid=($num+1);
}
else
{
$maxid=$row[0]+1;
}
// $data = $row; // add the row in to the results (data) array
return $maxid;
}
else
throw new Exception(mysql_error());
}
catch(Exception $e)
{
return $e->getMessage();
}
mysql_close();
}
public function FileUpload($path,$filename)
{
if(!is_dir($path))
{
mkdir($path,0777);
}
else
{
echo "ok";
}
}
}
?><file_sep>/Onlineexamination/hod/choosesubject.php
<?php include('hodheader.php');
$exam=$_POST["exam"];
include('../ConnectionClass.php');
$obj1=new ConnectionClass();
$q="select * from questions join faculty on faculty.staff_id=questions.fuc_id and questions.exam_id='$exam' group by questions.fuc_id";
$data=$obj1->selectdata($q);
?>
<?php
if(count($data)>0)
{
?><table width="443" height="186" border="0">
<tr><th>Prepared By</th><th></th></tr>
<?php
foreach($data as $r)
{
?>
<tr>
<td><?php
$f=$r["f_name"];
$l=$r["l_name"];
echo $f." ".$l; ?></td><td><a href="acceptreject.php?examid=<?php echo $r["exam_id"] ?>&fac=<?php echo $r["fuc_id"] ?>">View Questions</a>
<br />
<a href="code/acceptrejectquestion.php?action=accept&qid=<?php echo $r["question_id"] ?>&examid=<?php echo $r["exam_id"] ?>&fac=<?php echo $r["fuc_id"] ?>">Accept</a>
<br />
<a href="code/acceptrejectquestion.php?action=reject&qid=<?php echo $r["question_id"] ?>&examid=<?php echo $r["exam_id"] ?>&fac=<?php echo $r["fuc_id"] ?>">Reject</a>
</td>
</tr>
<?php
}
?>
</table>
<?php
}
else
{
echo "<script>alert('No data');location.href='approve_questions.php'</script>";
}
?>
</form>
<?php include('hodfooter.php'); ?><file_sep>/Onlineexamination/student/studfooter.php
<div class="clr"></div>
</div>
</div>
<div class="sidebar">
<div class="searchform">
</div>
<div class="gadget">
<h2 class="star"></h2>
<div class="clr"></div>
<ul class="sb_menu">
<li><a href="choose exam.php"><span>Attend Exam</</a></span></li>
<li><a href="viewresult.php"><span>View Result</a></span></li>
</ul>
</div>
<div class="gadget">
</div>
</div>
<div class="clr"></div>
</div>
</div>
<div class="fbg">
<div class="fbg_resize">
<div class="clr"></div>
</div>
</div>
<div class="footer">
<div class="footer_resize" align="center">
Copyright (c) websitename. All rights reserved.
<div style="clear:both;"></div>
</div>
</div>
</div>
</body>
</html><file_sep>/Onlineexamination/student/exam.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="../styles.css" rel="stylesheet" type="text/css" media="screen" />
<link rel="stylesheet" href="../nivo-slider.css" type="text/css" media="screen" />
<!-- clock -->
<script src="../js_datepicker/jquery-1.3.1.min.js"></script><!--
<script type="text/javascript" src="../js_datepicker/jquery-1.4.3.min.js"></script>-->
<script type="text/javascript" src="../js_datepicker/jquery.spriteTimer-1.3.6.js"></script>
<script type="text/javascript">
window.history.forward();
</script>
<script type="text/javascript">
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});
//process this function whenever a key is pressed
$(document).keydown(function (event) {
var keyCode = event.keyCode ? event.keyCode : event.charCode;
//window.status = keyCode;
// keyCode for F% on Opera is 57349 ?!
if (keyCode == 116 || keyCode ==15 ) {
return false ;
}
if(event ) {
if(event.ctrlKey ) {
return false;
}
else if(event.MOUSEDOWN)
{
alert("okkk");
}
}
});
</script>
<title>Untitled Page</title>
<style type="text/css">
#mainbody
{
width:900px;
border:2px solid gray;
overflow:auto;
margin:10px auto;
padding:20px;
background: #fff url(../images/white_grey_background_upside_down.jpg) repeat-x;
height:auto;
}
.timerbox
{
height:70px;
position:fixed;
background:#ccf;
right:30px;
margin:0;
padding:5px;
top: -1px;
width:220px;
}
*html .timerbox
{
position:absolute ;
float:right;
}
ul li
{
list-style:none;
display:inline;
padding:5px ;
text-align:right;
}
ul li ul
{
padding-left:40px;
padding-top:20px;
}
ul li ul li
{
padding:10px;
}
.Questions
{
border:1px solid red;
color:Black;
font-size:medium;
padding:20px 30px;
}
</style>
<script type="text/javascript">
//<![CDATA[
var windowHeight=screen.availHeight/4*3+20+"px"
function sniffer() {
var el=document.getElementById("mainbody");
if(screen.width==1280) {
el.style.height= windowHeight;
}
else {
if(screen.width==1024) {
el.style.height= windowHeight;
}
else {
if(screen.width==800) {
el.style.height= windowHeight;
}
}
}
}
onload=sniffer;
//]]>
</script>
<script type="text/javascript">
function runWhenFinished() {
$('.exampleA').css({'background':'#333'});
alert("STOP! Your times Over");
document.forms.form1.submit();
}
$(document).ready(function() {
var a= 900
$('.exampleA .timer').spriteTimer({
'seconds':a,
'isCountDown': true,
'digitImagePath': 'numbers.png',
'callback': runWhenFinished
});
$('.exampleB .timer').spriteTimer({
'digitImagePath': 'numbers.png',
'seconds': 12,
'isCountDown': false
});
});
</script>
<!-- clock -->
</head>
<body>
<div id="bg2"></div>
<div id="wrapper1">
<div id="content_bg_top"></div>
<div id="content_box">
<div id="header">
<div id="wrapper">
<div id="slider-wrapper">
<img src="../images/testb.jpg" width="870" height="241" />
</div>
</div>
</div>
<div id="column_box">
<div class="timerbox">
<div class="example exampleA">
<div class="timer"></div>
</div>
</div>
<p>
<form id="form1" runat="server" method="get" action="code/testdata.php" >
<font color="#FFFFFF" size="+2">
<?php
require_once('../ConnectionClass.php');
$obj1=new ConnectionClass();
$qry="SELECT * FROM questions where status='accepted' and exam_id='1' order by rand()";
$res=$obj1->selectdata($qry);
$i=1;
foreach($res as $row)
{
echo $i.":";
echo $row['title']."<br>";
echo "<font color='#FFFFFF' size='+1'>";
?>
<br />
<input type="radio" name="answer<?php echo $row['question_id']; ?>" value="<?php echo $row['option1']; ?>" />A : <?php echo $row['option1']; ?>
<br />
<input type="radio" name="answer<?php echo $row['question_id']; ?>" value="<?php echo $row['option2']; ?>" />B : <?php echo $row['option2']; ?>
<br />
<input type="radio" name="answer<?php echo $row['question_id']; ?>" value="<?php echo $row['option3']; ?>" />C : <?php echo $row['option3']; ?>
<br />
<input type="radio" name="answer<?php echo $row['question_id']; ?>" value="<?php echo $row['option4']; ?>" />D : <?php echo $row['option4']; ?>
<?php
echo "</font>";
echo "<br>";
echo "<br>";
$i++;
}
?>
</font>
<div align="center"><input type="submit" name="sub" value="Submit" /></div>
</p>
</form>
<p> </p>
<div class="clear"></div>
</div>
</div>
<div id="content_bg_bot"></div>
</div>
</body>
</html>
<file_sep>/Onlineexamination/student/code/testdata.php
<?php
session_start();
$eid=$_SESSION["examid"];
$username=$_SESSION["username"];
require('../../ConnectionClass.php');
$q="select * from questions where status='accept' and exam_id='$eid'";
$obj=new ConnectionClass();
$res=$obj->selectdata($q);
$mark=0;
foreach($res as $row)
{
$pst="answer".$row["question_id"];
$ans=@$_GET[$pst];
if($ans==$row["correct_ans"])
{
$mark=$mark+1;
}
else
{
$mark=$mark+0;
}
}
$obj1=new ConnectionClass();
$qry1="insert into ans_sheet(admn_no,exam_id,mark_obtained) values('$username','$eid','$mark')";
$result=$obj1->operation($qry1);
if($result)
{
?>
<script language="javascript">
alert('Please contact the invigilator for further proceedings THANK YOU!!');
location.href="../student_home.php";
</script>
<?php
}
?><file_sep>/Onlineexamination/admin/viewresult.php
<?php include('adminheader.php'); ?>
<?php include('adminfooter.php'); ?>
<file_sep>/Onlineexamination/student/code/stud_changepw_exe.php
<?php
include('../ConnectionClass.php');
$cp=$_POST["txtcp"];
$np=$_POST["txtnp"];
$cnp=$_POST["txtcop"];
$obj1=new ConnectionClass();
$q="insert into student(student_name,semester,rollnum,admin_num,address,gender,batch,email_id) values('$name','$sem','$rolno','$admsn','$addrss','$gender','$batch','$emlid')";
$obj->opertion($q);
echo "<script>alert('Success');</script>";
?><file_sep>/Onlineexamination/sitefooter.php
<div class="clr"></div>
</div>
</div>
<!-- <div class="sidebar">
<div class="searchform">
</div>
<div class="gadget">
<h2 class="star"><span>Sidebar</span> Menu</h2>
<div class="clr"></div>
<ul class="sb_menu">
<li><a href="#">Home</a></li>
<li><a href="#">TemplateInfo</a></li>
<li><a href="#">Style Demo</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Archives</a></li>
<li><a href="#">Web Templates</a></li>
</ul>
</div>
<div class="gadget">
</div>
</div>-->
<div class="clr"></div>
</div>
</div>
<div class="fbg">
<div class="fbg_resize">
<div class="clr"></div>
</div>
</div>
<div class="footer">
<div class="footer_resize" align="center">
Copyright (c) onlineexamination. All rights reserved.
<div style="clear:both;"></div>
</div>
</div>
</div>
</body>
</html><file_sep>/Onlineexamination/staff/viewstud.php
<?php
include('staffheader.php');
$aa=$_POST["txtadmn"];
include('../ConnectionClass.php');
$obj1=new ConnectionClass();
$q="select * from student join login on student.admin_num=login.username where admin_num='$aa'";
$result=$obj1->selectdata($q);
if(count($result)>0)
{
foreach($result as $t)
{
?>
<table>
<tr><th>Name</th><td><?php echo $t["stud_name"] ?></td></tr>
<tr><th>Semester</th><td><?php echo $t["semester"] ?></td></tr>
<tr><th>Address</th><td><?php echo $t["address"] ?></td></tr>
<tr><th>Batch</th><td><?php echo $t["batch"] ?></td></tr>
<tr><th>Gender</th><td><?php echo $t["gender"] ?></td></tr>
<tr><th>Email</th><td><?php echo $t["email_id"] ?></td></tr>
<tr><th>Status</th><td><?php echo $t["status"] ?></td></tr>
</table>
<?php
}
}
else
{
echo "<script>alert('Invalid admn no');location.href='studentdetails.php'</script>";
}
include('stafffooter.php');
?><file_sep>/Onlineexamination/contact.php
<?php include('siteheader.php');?>
<div align="center">
<p><h4>Contact us...</h4></p>
<p> College of Engineering Chengannur</p>
<p> Alapuzha District , Kerala</p>
<p> PIN 689121 </p>
<p>TEL: +91-479- 2165706, 2454125, 2456046, 2451424</p>
<p> FAX: +91-479-2451424 </p>
<p>E-mail : <EMAIL> </p>
</div>
<?php include('sitefooter.php');?><file_sep>/Onlineexamination/admin/addfaculty.php
<?php include('adminheader.php'); ?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#form1").validate({
});
});
</script>
<script src="../js_datepicker/bootstrap-datepicker.js" type="text/javascript"></script>
<link href="../js_datepicker/bootstrap-datepicker3.css" rel="stylesheet" type="text/css" />
<link href="../js_datepicker/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" >
$(document).ready(function () {
var FromEndDate = new Date();
var myDate = new Date();
myDate.setDate(myDate.getDate() + 30);
$(".datep").datepicker(
{
format: 'yyyy/mm/dd',
autoclose: true,
pickerPosition: "left",
onRender: function (date) {
return (date.valueOf() <= FromEndDate.valueOf()) ? 'disabled' : '';
}
});
});
</script>
<form id="form1" name="form1" method="post" action="code/addfaculty_exe.php">
<table width="638" height="373" border="0" cellpadding="5" cellspacing="1">
<tr>
<td width="169">First Name</td>
<td width="150"><label>
<input type="text" name="fname" id="fname" class="required char" />
</label></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" id="lname" class="required char" /></td>
</tr>
<tr>
<td>Designation</td>
<td><input type="text" name="desig" id="desig" class="required char" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="em" id="em" class="required email" /></td>
</tr>
<tr>
<td>Address</td>
<td><textarea name="adrs" id="adrs" class="required"></textarea></td>
</tr>
<tr>
<td>Qualification</td>
<td><input type="text" name="quali" class="required" id="quali" /></td>
</tr>
<tr>
<td>Type</td>
<td><label>
<select name="type" id="type" class="required">
<option value="select">select</option>
<option value="hod">HOD</option>
<option value="staff">Staff</option>
</select>
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Save" />
</label></td>
</tr>
</table>
</form>
<?php include('adminfooter.php'); ?>
<file_sep>/Onlineexamination/hod/code/scheduling_exe.php
<?php
session_start();
include('../../ConnectionClass.php');
$obj1=new ConnectionClass();
$exam=$_POST["exam"];
$date1=$_POST["d"];
$regf=$_POST["srf4"];
$regto=$_POST["srt5"];
$stime=$_POST["sst7"];
$a="insert into examschedule (date,exam_id,regno_from,regno_to,status,start_time)values('$date1','$exam','$regf','$regto','submitted','$stime')";
$obj1->operation($a);
echo "<script>alert('Successfully Added'); location.href='../examscheduling.php';</script>";
?><file_sep>/Onlineexamination/student/resultview.php
<?php
include('studheader.php');
?>
<?php
//session_start();
$a=$_POST["p"];
$adm=$_SESSION["username"];
include('../ConnectionClass.php');
$obj=new ConnectionClass();
$qry="select * from student join ans_sheet on ans_sheet.exam_id='$a' and ans_sheet.admn_no='$adm' and ans_sheet.admn_no=student.admin_num join exam on exam.exam_id=ans_sheet.exam_id";
$result=$obj->selectdata($qry);
if(count($result)>0)
{
foreach($result as $r)
{
?>
<table>
<tr><th colspan="2" align="center">Online Exam Result </th></tr>
<tr><th>Exam id</th><td><?php echo $r["exam_id"] ?></td></tr>
<tr><th>Exam Name</th><td><?php echo $r["exam_title"] ?></td></tr>
<tr><th>Date</th><td><?php echo $r["exam_date"] ?></td></tr>
<tr><th>Marks Obtailed</th><td><?php echo $r["mark_obtained"] ?></td></tr><!--
<tr><th>Total Mark</th><td><?php echo $r["total_marks"] ?></td></tr>-->
</table>
<?php
}
}
else
{
echo "<script>alert('Not available..Please Try again..');location.href='viewresult.php'</script>";
}
?>
<?php
include('studfooter.php');
?><file_sep>/Onlineexamination/student_reg.php
<?php include('siteheader.php');?>
<script type="text/javascript" src="js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#ww1").validate({
});
});
</script>
<script src="js_datepicker/bootstrap-datepicker.js" type="text/javascript"></script>
<link href="js_datepicker/bootstrap-datepicker3.css" rel="stylesheet" type="text/css" />
<link href="js_datepicker/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" >
$(document).ready(function () {
var FromEndDate = new Date();
var myDate = new Date();
myDate.setDate(myDate.getDate() + 30);
$(".datep").datepicker(
{
format: 'yyyy/mm/dd',
autoclose: true,
pickerPosition: "left",
onRender: function (date) {
return (date.valueOf() <= FromEndDate.valueOf()) ? 'disabled' : '';
}
});
});
</script>
<form id="ww1" name="form1" method="post" action="code/stud_reg_exe.php">
<table width="356" height="388" border="0">
<tr>
<td width="113">Name</td>
<td width="11"> </td>
<td width="62"><label>
<input type="text" name="txtname" id="txtname" class="required char" />
</label></td>
</tr>
<tr>
<td>Semester</td>
<td> </td>
<td><label>
<input type="text" name="txtsem" id="txtsem" class="required number" />
</label></td>
</tr>
<tr>
<td>Roll number</td>
<td> </td>
<td><label>
<input type="text" name="txtrno" id="txtrno" class="required number" />
</label></td>
</tr>
<tr>
<td>Admission Number</td>
<td> </td>
<td><label>
<input type="text" name="txtadmnno" id="txtadmnno" class="required number" />
</label></td>
</tr>
<tr>
<td>Address</td>
<td> </td>
<td><label>
<textarea name="txtadrs" id="txtadrs" class="required "></textarea>
</label></td>
</tr>
<tr>
<td>Gender</td>
<td> </td>
<td><p>
<label>
<input type="radio" name="gender" value="male" id="gender_0" class="required " />
male</label>
<br />
<label>
<input type="radio" name="gender" value="female" id="gender_1" />
female</label>
<br />
</p></td>
</tr>
<tr>
<td>Batch</td>
<td> </td>
<td><label>
<input type="text" name="txtbatch" id="txtbatch" class="required " />
</label></td>
</tr>
<tr>
<td>Email id</td>
<td> </td>
<td><label>
<input type="text" name="txtemail" id="txtemail" class="required email" />
</label></td>
</tr>
<tr>
<td>Password</td>
<td> </td>
<td><label>
<input type="password" name="txtpwd" id="txtpwd" class="required " />
</label></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Submit" />
</label></td>
</tr>
</table>
</form>
<?php include('sitefooter.php');?><file_sep>/Onlineexamination/hod/get_subject.php
<?php
require_once("../ConnectionClass.php");
$obj=new ConnectionClass();
$sem=$_REQUEST["sem"];
$qry="select * from subject where semester='$sem'";
$t=$obj->selectdata($qry);
?>
<?php
foreach($t as $b)
{
?>
<option value="<?php echo $b['sub_id'];?>" ><?php echo $b['sub_name'];?></option>
<?php
}?>
<file_sep>/Onlineexamination/staff/myprofile.php
<?php
include('staffheader.php');
?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#form1").validate({
});
});
</script>
<script src="../js_datepicker/bootstrap-datepicker.js" type="text/javascript"></script>
<link href="../js_datepicker/bootstrap-datepicker3.css" rel="stylesheet" type="text/css" />
<link href="../js_datepicker/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" >
$(document).ready(function () {
var FromEndDate = new Date();
var myDate = new Date();
myDate.setDate(myDate.getDate() + 30);
$(".datep").datepicker(
{
format: 'yyyy/mm/dd',
autoclose: true,
pickerPosition: "left",
onRender: function (date) {
return (date.valueOf() <= FromEndDate.valueOf()) ? 'disabled' : '';
}
});
});
</script>
<?php
//session_start();
include('../ConnectionClass.php');
$obj1=new ConnectionClass();
$username=$_SESSION["username"];
$q="select * from faculty where staff_id='$username'";
$data=$obj1->selectdata($q);
foreach($data as $r)
{
?>
<form id="form1" name="form1" method="post" action="editprofile.php">
<table width="638" height="439" border="0" cellpadding="5" cellspacing="1">
<tr>
<td height="96" colspan="2" align="center"><h2>My Profile</h2></td>
</tr>
<tr>
<td width="169">First Name</td>
<td width="150"><label>
<input type="text" name="fname" id="fname" readonly="readonly" value="<?php echo $r["f_name"] ?>" />
</label></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" id="lname" readonly="readonly" value="<?php echo $r["l_name"] ?>" /></td>
</tr>
<tr>
<td>Designation</td>
<td><input type="text" name="desig" id="desig" readonly="readonly" value="<?php echo $r["designation"] ?>" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="em" id="em" readonly="readonly" value="<?php echo $r["email_id"] ?>"/></td>
</tr>
<tr>
<td>Address</td>
<td><textarea name="adrs" id="adrs" readonly="readonly"><?php echo $r["address"] ?></textarea></td>
</tr>
<tr>
<td>Qualification</td>
<td><input type="text" name="quali" id="quali" readonly="readonly" value="<?php echo $r["qualification"] ?>" /></td>
</tr>
<tr>
<td>Type</td>
<td><label>
<input type="text" id="type" name="type" readonly="readonly" value="<?php echo $r["type"] ?>" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Edit" />
</label></td>
</tr>
</table>
</form>
<?php
}
include('stafffooter.php');
?>
<file_sep>/Onlineexamination/staff/studentdetails.php
<?php include('staffheader.php');
?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#form1").validate({
});
});
</script>
<script src="../js_datepicker/bootstrap-datepicker.js" type="text/javascript"></script>
<link href="../js_datepicker/bootstrap-datepicker3.css" rel="stylesheet" type="text/css" />
<link href="../js_datepicker/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" >
$(document).ready(function () {
var FromEndDate = new Date();
var myDate = new Date();
myDate.setDate(myDate.getDate() + 30);
$(".datep").datepicker(
{
format: 'yyyy/mm/dd',
autoclose: true,
pickerPosition: "left",
onRender: function (date) {
return (date.valueOf() <= FromEndDate.valueOf()) ? 'disabled' : '';
}
});
});
</script>
<form action="viewstud.php" method="post" id="form1">
<table width="400px" border="0">
<tr>
<td>Enter Admission number</td>
<td><label>
<input type="text" name="txtadmn" id="txtadmn" class="required">
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="Submit" name="button" id="button" value="Submit">
</label></td>
</tr>
</table>
</form><?php
include('stafffooter.php');
?><file_sep>/Onlineexamination/admin/code/addfaculty_exe.php
<?php
$fname=$_POST["fname"];
$lname=$_POST["lname"];
$desi=$_POST["desig"];
$em=$_POST["em"];
$quali=$_POST["quali"];
$adrs=$_POST["adrs"];
$type=$_POST["type"];
$staffid=mt_rand();
$pwd=mt_rand();
include('../../ConnectionClass.php');
$obj=new ConnectionClass();
$qq="select count(*) from faculty where email_id='$em'";
$count=$obj->GetSingleData($qq);
if($type!="select")
{
if($count==0)
{
$obj1=new ConnectionClass();
$q="INSERT INTO faculty(staff_id,qualification,designation,f_name,l_name,address,type,email_id) VALUES ('$staffid','$quali', '$desi', '$fname', '$lname', '$adrs', '$type', '$em')";
$obj1->operation($q);
$obj2=new ConnectionClass();
$q2="INSERT INTO login(username,password,usertype,status) VALUES ('$staffid','$pwd','$type','active')";
$obj2->operation($q2);
//send username,password to email
$username=$em;
$sub="Greetings..";
$content="You are added to online examination website..Username:$staffid,Password:$pwd";
$obj3=new ConnectionClass();
$obj3->SendMail($username,$sub,$content);
echo "<script>alert('Successfully Added'); location.href='../addfaculty.php';</script>";
}
else
{
echo "<script>alert('Emailid already added'); location.href='../addfaculty.php';</script>";
}
}
else
{
echo "<script>alert('Please choose staff type'); location.href='../addfaculty.php';</script>";
}
?><file_sep>/Onlineexamination/staff/code/addqu_exe.php
<?php
session_start();
$eid=$_SESSION["examid"];
$ques=$_POST["aq1"];
$ans=$_POST["txtans"];
$op1=$_POST["txtop1"];
$op2=$_POST["txtop2"];
$op3=$_POST["txtop3"];
$op4=$_POST["txtop4"];
$username=$_SESSION["username"];
include('../../ConnectionClass.php');
$obj=new ConnectionClass();
$qq="select count(*) from questions where exam_id='$eid' and title='$ques'";
$count=$obj->GetSingleData($qq);
if($count==0)
{
$obj1=new ConnectionClass();
$q="INSERT INTO questions(title,option1,option2,option3,option4,correct_ans,fuc_id,exam_id,status) VALUES ('$ques','$op1','$op2','$op3','$op4','$ans','$username','$eid','submitted')";
$obj1->operation($q);
echo "<script>alert('Successfully Added'); location.href='../addquestion.php';</script>";
}
else
{
echo "<script>alert('Already added'); location.href='../scheduling.php';</script>";
}
?><file_sep>/Onlineexamination/hod/code/acceptrejectquestion.php
<?php
$ex=$_REQUEST["examid"];
$fid=$_REQUEST["fac"];
$act=$_REQUEST["action"];
$qid=$_REQUEST["qid"];
include('../../ConnectionClass.php');
if($act=="accept")
{
$obj11=new ConnectionClass();
$qq="select * from questions where exam_id='$ex' and status='$act'";
$dd=$obj11->selectdata($qq);
if(count($dd)>0)
{
echo "<script>alert('Already selected a pattern.. '); location.href='../approve_questions.php';</script>";
}
else
{
$obj21=new ConnectionClass();
$q2="update questions set status='$act' where exam_id='$ex' and fuc_id='$fid'";
$data2=$obj21->operation($q2);
}
}
else
{
$obj1=new ConnectionClass();
$q="update questions set status='$act' where exam_id='$ex' and fuc_id='$fid'";
$data=$obj1->operation($q);
}
echo "<script>alert('Success'); location.href='../approve_questions.php';</script>";
?><file_sep>/Onlineexamination/admin/studenview.php
<?php include('adminheader.php'); ?>
<?php
$a=$_POST["p"];
include('../ConnectionClass.php');
$obj=new ConnectionClass();
$qry="select * from student join login on student.admin_num=login.username where admin_num='$a'";
$result=$obj->selectdata($qry);
if(count($result)>0)
{
foreach($result as $r)
{
?>
<table>
<tr><th>Name</th><td><?php echo $r["stud_name"] ?></td></tr>
<tr><th>Semester</th><td><?php echo $r["semester"] ?></td></tr>
<tr><th>Address</th><td><?php echo $r["address"] ?></td></tr>
<tr><th>Batch</th><td><?php echo $r["batch"] ?></td></tr>
<tr><th>Gender</th><td><?php echo $r["gender"] ?></td></tr>
<tr><th>Email</th><td><?php echo $r["email_id"] ?></td></tr>
<tr><th>Status</th><td><?php echo $r["status"] ?></td></tr>
</table>
<?php
}
}
else
{
echo "<script>alert('Invalid Admission Number');location.href='viewstudent.php'</script>";
}
?>
<?php
include('adminfooter.php');
?><file_sep>/Onlineexamination/staff/new.php
<?php include('staffheader.php');
?>
<?php
$aa=$_POST["txtadmn"];
include('ConnectionClass.php');
$obj1=new ConnectionClass();
$q="select * from student";
$result=$obj1->selectdata($q);
if(count($result)>0)
{
?>
<table>
<tr><th>Name</th><th>Semester</th><th>Address</th><th>Batch</th><th>Gender</th><th>Email</th></tr>
<?php
foreach($result as $t)
{
?>
<tr><td><?php echo $t["stud_name"] ?></td><td><?php echo $t["semester"] ?></td><td><?php echo $t["address"] ?></td><td><?php echo $t["batch"] ?></td><td><?php echo $t["gender"] ?></td><td><?php echo $t["email_id"] ?></td></tr>
<?php
}?>
</table>
<?php
}
else
{
echo "<script>alert('No data');location.href='studentdetails.php'</script>";
}
?>
<?php
include('stafffooter.php');
?><file_sep>/Onlineexamination/admin/adminfooter.php
<div class="clr"></div>
</div>
</div>
<div class="sidebar">
<div class="searchform">
</div>
<div class="gadget">
<h2 class="star"></h2>
<div class="clr"></div>
<ul class="sb_menu">
<li><a href="addfaculty.php"><span>Add staff</a></span></li>
<li><a href="viewfaculty.php"><span>View staff</a></span></li>
<li><a href="viewstudent.php"><span>Search Students</a></span></li>
<li><a href="result.php"><span>View Results</a></span></li>
</ul>
</div>
<div class="gadget">
</div>
</div>
<div class="clr"></div>
</div>
</div><br />
<div class="fbg">
<div class="fbg_resize">
<div class="clr"></div>
</div>
</div>
<div class="footer">
<div class="footer_resize" align="center">Copyright (c) onlineexamination. All rights reserved.
<div style="clear:both;"></div>
</div>
</div>
</div>
</body>
</html><file_sep>/Onlineexamination/hod/schedule.php
<?php include('hodheader.php'); ?>
<?php include('hodfooter.php'); ?><file_sep>/Onlineexamination/code/login_exe.php
<?php
session_start();
include('../ConnectionClass.php');
$username=$_POST["txtuname"];
$pwd=$_POST["txtpwd"];
$obj1=new ConnectionClass();
$_SESSION["username"]=$username;
$q="select count(*) from login where username='$username' and password='$pwd' and status='active'";
$count=$obj1->GetSingleData($q);
if($count==0)
{
echo "<script>alert('Invalid');location.href='../login.php'</script>";
}
else
{
$obj21=new ConnectionClass();
$q11="select password from login where username='$username' and password='$pwd'";
$pass=$obj21->GetSingleData($q11);
if($pass==$pwd)
{
$obj2=new ConnectionClass();
$q1="select usertype from login where username='$username' and password='$pwd'";
$utype=$obj2->GetSingleData($q1);
if($utype=="admin")
{
header('location:../admin/admin_home.php');
}
else if($utype=="hod")
{
header('location:../hod/hod_home.php');
}
else if($utype=="staff")
{
header('location:../staff/staff_home.php');
}
else if($utype=="student")
{
header('location:../student/student_home.php');
}
else
{
echo "<script>alert('Invalid');location.href='../login.php';</script>";
}
}
else
{
echo "<script>alert('password incorrect');location.href='../login.php';</script>";
}
}
<file_sep>/Onlineexamination/admin/admin_home.php
<?php include('adminheader.php'); ?>
<style type="text/css">
<!--
.style2 {font-size: 24px}
-->
</style>
<marquee>
<span class="style2">Welcome admin...</span>
</marquee>
<img src="../images/computer.jpg" width="300px" height="200px"/>
<div>Examination online is the first fully customizable software that you can mould as per your requirements. We have a strong, multi-functional base platform from which we create our intuitive, easy-to-use interface: from there we include or exclude the features you require for your own custom online exam creation and reporting functionality needs.</div>
<?php include('adminfooter.php'); ?><file_sep>/Onlineexamination/student/student_home.php
<?php
include('studheader.php');
?>
<marquee>Welcome Student..</marquee>
<img src="../images/computer.jpg" width="300px" height="200px"/>
<div>Examination online is the first fully customizable software that you can mould as per your requirements. We have a strong, multi-functional base platform from which we create our intuitive, easy-to-use interface: from there we include or exclude the features you require for your own custom online exam creation and reporting functionality needs.</div>
<?php
include('studfooter.php');
?><file_sep>/Onlineexamination/hod/viewstaff.php
<?php include('hodheader.php'); ?>
<?php
$aa=$_POST["txtadmn"];
include('../ConnectionClass.php');
$obj1=new ConnectionClass();
$q="select * from faculty where staff_id='$aa'";
$result=$obj1->selectdata($q);
if(count($result)>0)
{
foreach($result as $t)
{
?>
<form name="form1" method="post" action="">
<table>
<tr>
<th width="94">first name</th>
<td width="79"><label>
<input type="text" name="textfield" id="textfield" value=" <?php echo $t["f_name"] ?>">
</label></td>
</tr>
<tr>
<th>last name</th>
<td><?php echo $t["l_name"] ?></td>
</tr>
<tr>
<th>qualification</th>
<td><?php echo $t["qualification"] ?></td>
</tr>
<tr>
<th>designation</th>
<td><?php echo $t["designation"] ?></td>
</tr>
<tr>
<th>date of joining</th>
<td><?php echo $t["date_joining"] ?></td>
</tr>
<tr>
<th>address</th>
<td><?php echo $t["address"] ?></td>
</tr>
<tr>
<th>type</th>
<td><?php echo $t["type"] ?></td>
</tr>
<tr>
<th>email id</th>
<td><?php echo $t["email_id"] ?></td>
</tr>
</table>
</form>
<?php
}
}
else
{
echo "<script>alert('Invalid admn no');location.href='viewstaff.php'</script>";
}
?>
<?php include('hodfooter.php'); ?>
<file_sep>/Onlineexamination/hod/addexam.php
<?php include('hodheader.php'); ?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#form1").validate({
});
});
</script>
<script src="../js_datepicker/bootstrap-datepicker.js" type="text/javascript"></script>
<link href="../js_datepicker/bootstrap-datepicker3.css" rel="stylesheet" type="text/css" />
<link href="../js_datepicker/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" >
$(document).ready(function () {
var FromEndDate = new Date();
var myDate = new Date();
myDate.setDate(myDate.getDate() + 30);
$(".datep").datepicker(
{
format: 'yyyy/mm/dd',
autoclose: true,
pickerPosition: "left",
onRender: function (date) {
return (date.valueOf() <= FromEndDate.valueOf()) ? 'disabled' : '';
}
});
});
</script>
<?php
$sem=$_POST["sem"];
include('../ConnectionClass.php');
$obj1=new ConnectionClass();
$q="select * from subject where semester='$sem'";
$data=$obj1->selectdata($q);
?>
<form id="form1" name="form1" method="post" action="code/addexam_exe.php">
<input type="hidden" id="hid" name="hid" value="<?php echo $sem; ?>" />
<table width="443" height="186" border="0">
<tr>
<td colspan="2"><div align="center"><h4>Add Exam</h4></div></td>
</tr>
<tr>
<td>Choose Suject</td>
<td><label>
<select name="sub" id="sub" class="required">
<option value="select">select</option>
<?php
foreach($data as $r)
{
?>
?>
<option value="<?php echo $r["sub_id"];?>"><?php echo $r["sub_name"];?></option>
<?php
}
?>
</select>
</label></td>
</tr>
<tr>
<td>Title</td>
<td><input type="text" name="etitle" id="etitle" class="required " /></td>
</tr>
<tr>
<td>Date</td>
<td><label>
<input type="date" name="edate" id="edate" class="required datep" placeholder="yyyy-mm-dd" />
</label></td>
</tr>
<tr>
<td>Duration</td>
<td><label>
<input type="text" name="dd" id="dd" value="15mins" readonly="readonly"/>
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="OK" />
</label></td>
</tr>
</table>
</form>
<?php
$obj11=new ConnectionClass();
$q1="select * from subject join exam on subject.sub_id=exam.subject_code and subject.semester='$sem'";
$res1=$obj1->selectdata($q1);
if((count($res1))>0)
{
?>
<table border="1">
<tr><th>Title</th><th>Date</th><th>Subject</th><th>duration</th><th>Action</th></tr>
<?php
foreach($res1 as $row)
{
?>
<tr><td><?php echo $row["exam_title"];?></td><td><?php echo $row["exam_date"];?></td><td><?php echo $row["sub_name"];?></td><td><?php echo $row["duration"];?></td><td><a href="code/delexam.php?id=<?php echo $row["exam_id"];?>" onClick="return(confirm('Are you sure want to delete it?'));">Delete</a></td></tr>
<?php
}
?>
</table>
<?php
}
?>
<?php include('hodfooter.php'); ?><file_sep>/Onlineexamination/student/Changepassword.php
<?php
include('studheader.php');
?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#form1").validate({
rules: {
txtcop: {
required: true,
equalTo: "txtnp"
}
}
});
});
</script>
<script src="../js_datepicker/bootstrap-datepicker.js" type="text/javascript"></script>
<link href="../js_datepicker/bootstrap-datepicker3.css" rel="stylesheet" type="text/css" />
<link href="../js_datepicker/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" >
$(document).ready(function () {
var FromEndDate = new Date();
var myDate = new Date();
myDate.setDate(myDate.getDate() + 30);
$(".datep").datepicker(
{
format: 'yyyy/mm/dd',
autoclose: true,
pickerPosition: "left",
onRender: function (date) {
return (date.valueOf() <= FromEndDate.valueOf()) ? 'disabled' : '';
}
});
});
</script>
<form id="form1" name="form1" method="post" action="code/changepw_exe.php">
<table width="413" height="218" border="0" cellpadding="5" cellspacing="1">
<tr>
<td width="169">Old password</td>
<td width="150"><label>
<input name="txtcp" type="password" id="txtcp" class="required" />
</label></td>
</tr>
<tr>
<td>New password</td>
<td><label>
<input type="password" name="txtnp" id="txtnp" class="required" minlength="6" />
</label></td>
</tr>
<tr>
<td>Confirm password</td>
<td><label>
<input type="password" name="txtcop" id="txtcop" class="required" minlength="6" />
</label></td>
</tr>
<tr>
<td height="34" colspan="2"><label>
<div align="center">
<input type="submit" name="txtsave" id="txtsave" value="Save" />
</div>
</label></td>
</tr>
</table>
</form>
<?php
include('studfooter.php');
?><file_sep>/Onlineexamination/admin/viewfaculty.php
<?php include('adminheader.php');
include('../ConnectionClass.php');
$obj1=new ConnectionClass();
$q="select * from faculty";
$res=$obj1->selectdata($q);
?>
<table border="1">
<tr><th>First Name</th><th>Last Name</th><th>Designation</th><th>Qualification</th><th>Address</th><th>Email</th><th>Faculty Type</th><th>Action</th></tr>
<?php
foreach($res as $row)
{
?>
<tr><td><?php echo $row["f_name"];?></td><td><?php echo $row["l_name"];?></td><td><?php echo $row["designation"];?></td><td><?php echo $row["qualification"];?></td><td><?php echo $row["address"];?></td><td><?php echo $row["email_id"];?></td><td><?php echo $row["type"];?></td><td><a href="code/delfaculty.php?id=<?php echo $row["staff_id"];?>" onclick="return(confirm('Are you sure want to delete it?'));">Delete</a></td></tr>
<?php
}
?>
</table>
<?php include('adminfooter.php'); ?><file_sep>/Onlineexamination/SMTPmail/SMTPconfig.php
<?php
//Server Address
$SmtpServer="mail.v2marry.com";
$SmtpPort="26";
$SmtpUser="admin+v2marry.com";
$SmtpPass="<PASSWORD>";
?><file_sep>/Onlineexamination/hod/sttudntsrch.php
<?php include('hodheader.php');
$ad=$_POST["txtad"];
include('../ConnectionClass.php');
$obj1=new ConnectionClass();
$q="select * from student join login on student.admin_num=login.username where stud_name like '%$ad%'";
$result=$obj1->selectdata($q);
if(count($result)>0)
{
?>
<div style="width:600px;overflow:auto">
<table width="600px">
<tr><th>Admission Number</th><th>Name</th><th>Semester</th><th>Address</th><th>Batch</th><th>Gender</th><th>Email</th><th>Status</th></tr>
<?php
foreach($result as $t)
{
?><tr>
<td><?php echo $t["admin_num"] ?></td>
<td><?php echo $t["stud_name"] ?></td>
<td><?php echo $t["semester"] ?></td>
<td><?php echo $t["address"] ?></td>
<td><?php echo $t["batch"] ?></td>
<td><?php echo $t["gender"] ?></td>
<td><?php echo $t["email_id"] ?></td>
<td><?php echo $t["status"] ?></td></tr>
<?php
}
?>
</table></div>
<?php
}
else
{
echo "<script>alert('Invalid admn no');location.href='Student_Search.php'</script>";
}
include('hodfooter.php');?><file_sep>/Onlineexamination/js_datepicker/jquery.spriteTimer-1.3.6.js
/*
* spriteTimer jQuery plugin v1.3.6
* Copyright (c) 2010 <NAME>
* October 25, 2010
* http://www.spasovski.net/code/spritetimer
* Tested on: jQuery 1.4.2 and jQuery 1.4.3
*
* Dual licensed under the MIT or GPL Version 2 licenses.
*/
(function($) {
$.fn.spriteTimer = function(options) {
var timerElm = this;
var settings = {
//important: the countdown value and height and width of your image sprite
'seconds': 60, //used for countdown functionality
'digitWidth': 42, //you want this set to the width of your numbers image sprite
'digitHeight': 54, //you want this set to the height of your numbers image sprite
'digitImagePath': '../js_datepicker/numbers.png', //the path to your numbers picture containing the numbers 9876543210:. [please see the demo pack for the sample image]
//optional settings to control your timer
'digitElement': 'span', //HTML element to be injected as the digit container [cannot be complex like "span.digit"]
'separatorElement': 'em', //HTML element to be injected as the separator (":" or ".") [cannot be complex like "span.digit"]
'startButton': '', //jQuery selector for your start/stop button [the same button is used, example '#startBtn']
'resetButton': '', //jQuery selector for your reset button [example '#resetBtn']
callback: function(){}, //used for countdown: optional function to call once the timer reaches 0
//optional callbacks in case you want to do run your own functions based on timer events, the current number of seconds is provided as an argument
stopTimerCallback: function(currentSeconds){}, //optional function to call when the start/stop button is clicked to stop the timer
startTimerCallback: function(currentSeconds){}, //optional function to call when the start/stop button is clicked to resume the timer
resetTimerCallback: function(currentSeconds){}, //optional function to call when the reset button is clicked
everySecondCallback: function(currentSeconds){}, //optional function to call every second (useful if you wish to update your own element with the current time)
//important: do you want to count up or count down?
'isCountDown': true //otherwise the timer starts at 0 and counts up
};
if (options) {$.extend(settings, options);}
var timeInterval = null;
var SpriteTimer = {
digits: [],
currentSeconds: settings.seconds,
reInitialized: false,
numDigits: 1,
initialStart: true,
init: function() {
var self = this;
if (settings.isCountDown) {self.numDigits = self.getNumberOfDigits(self.currentSeconds);}
if (!self.reInitialized) {
self.populateTimer();
if (!settings.startButton) {self.initCSS();}
self.updateTime(self.currentSeconds);
} else { //you clicked reset...you bastard!!!
if (settings.isCountDown) {
clearInterval(timeInterval);
self.currentSeconds = settings.seconds;
self.updateTime(self.currentSeconds);
self.digits = [];
self.init();
} else {
clearInterval(timeInterval);
self.currentSeconds = 0;
self.initialStart = true;
self.reInitialized = false;
self.numDigits = 1;
self.digits = [];
timerElm.empty();
self.init();
}
}
if (!settings.isCountDown) {self.currentSeconds = 1;}
if (settings.startButton || settings.resetButton) {
self.initCSS();
self.bindEvents();
} else {
if (settings.isCountDown) {
self.startDownInterval();
} else {
self.initCSS();
self.startUpInterval();
}
}
},
startDownInterval: function() {
var self = this;
timeInterval = setInterval(function() {
if (self.currentSeconds < 1) {
self.updateTime(self.currentSeconds);
clearInterval(timeInterval);
settings.callback();
} else {
self.updateTime(self.currentSeconds);
settings.everySecondCallback(self.currentSeconds--);
}
}, 1000);
},
startUpInterval: function() {
var self = this;
timeInterval = setInterval(function() {
self.updateTime(self.currentSeconds);
self.updateNumDigits(self.isNewDigitNeeded());
settings.everySecondCallback(self.currentSeconds);
self.currentSeconds++;
}, 1000);
},
isNewDigitNeeded: function() {
var s = this.currentSeconds;
if (s == 10 || s == 60 || s == 600 || s == 3600 || s == 36000) {
return true;
}
return false;
},
updateTime: function(seconds) {
var n = timerElm.find(settings.digitElement).size();
var i = 0;
var myVal = 0;
var self = this;
self.numDigits = self.getNumberOfDigits(seconds);
if (self.numDigits == 1) {
for (i = 0; i < (n - 1); i++) {
self.setDigit(self.digits[i], 0);
}
self.setDigit(self.digits[n-1], seconds % 10);
}
if (self.numDigits == 2) {
for (i = 0; i < (n - 2); i++) {
self.setDigit(self.digits[i], 0);
}
self.setDigit(self.digits[n-2], parseInt(String(seconds).charAt(0), 10));
self.setDigit(self.digits[n-1], parseInt(String(seconds).charAt(1), 10));
}
if (self.numDigits == 3) {
if (n == 4) {
self.setDigit(self.digits[0], 0);
}
self.setDigit(self.digits[n-1], Math.floor(seconds % 10));
myVal = seconds % 60;
if (myVal < 10) {
self.setDigit(self.digits[n-2], 0);
} else {
self.setDigit(self.digits[n-2], parseInt(String(myVal).charAt(0), 10));
}
self.setDigit(self.digits[n-3], Math.floor(seconds / 60));
}
if (self.numDigits == 4) {
if (n == 5) {
self.setDigit(self.digits[0], 0);
}
self.setDigit(self.digits[n-1], Math.floor(seconds % 10));
myVal = seconds % 60;
if (myVal < 10) {
self.setDigit(self.digits[n-2], 0);
} else {
self.setDigit(self.digits[n-2], parseInt(String(myVal).charAt(0), 10));
}
var numMins = Math.floor(seconds / 60);
self.setDigit(self.digits[n-3], parseInt(String(numMins).charAt(1), 10));
self.setDigit(self.digits[n-4], parseInt(String(numMins).charAt(0), 10));
}
if (self.numDigits == 5) {
if (n == 6) {
self.setDigit(self.digits[0], 0);
}
self.setDigit(self.digits[n-1], Math.floor(seconds % 10));
myVal = seconds % 60;
if (myVal < 10) {
self.setDigit(self.digits[n-2], 0);
} else {
self.setDigit(self.digits[n-2], parseInt(String(myVal).charAt(0), 10));
}
var numMins = Math.floor(seconds / 60);
var numHours = Math.floor(numMins / 60);
myVal = numMins % 60;
if (myVal > 9) {
self.setDigit(self.digits[n-3], parseInt(String(myVal).charAt(1), 10));
} else {
self.setDigit(self.digits[n-3], parseInt(String(myVal).charAt(0), 10));
}
if (myVal < 10) {
self.setDigit(self.digits[n-4], 0);
} else {
self.setDigit(self.digits[n-4], parseInt(String(myVal).charAt(0), 10));
}
self.setDigit(self.digits[n-5], numHours);
}
if (self.numDigits == 6) {
self.setDigit(self.digits[n-1], Math.floor(seconds % 10));
myVal = seconds % 60;
if (myVal < 10) {
self.setDigit(self.digits[n-2], 0);
} else {
self.setDigit(self.digits[n-2], parseInt(String(myVal).charAt(0), 10));
}
var numMins = Math.floor(seconds / 60);
var numHours = Math.floor(numMins / 60);
myVal = numMins % 60;
if (myVal > 9) {
self.setDigit(self.digits[n-3], parseInt(String(myVal).charAt(1), 10));
} else {
self.setDigit(self.digits[n-3], parseInt(String(myVal).charAt(0), 10));
}
if (myVal < 10) {
self.setDigit(self.digits[n-4], 0);
} else {
self.setDigit(self.digits[n-4], parseInt(String(myVal).charAt(0), 10));
}
self.setDigit(self.digits[n-5], parseInt(String(numHours).charAt(1), 10));
self.setDigit(self.digits[n-6], parseInt(String(numHours).charAt(0), 10));
}
},
initCSS: function(isNewDigit) {
timerElm.find(settings.digitElement + ', ' + settings.separatorElement).css({
'display': 'block',
'float': 'left',
'height': settings.digitHeight + 'px',
'width': settings.digitWidth + 'px',
'background-image': 'url(' + settings.digitImagePath + ')',
'background-repeat': 'no-repeat'
});
timerElm.find('.colon').css({'background-position': '0 -' + (settings.digitHeight * 10) + 'px'});
timerElm.find('.period').css({'background-position': '0 -' + (settings.digitHeight * 11) + 'px'});
if (!settings.isCountDown) {
timerElm.find(settings.digitElement).css({'background-position': '0 -' + (settings.digitHeight * 9) + 'px'});
if (isNewDigit) {
timerElm.find(settings.digitElement + ':first-child').css({'background-position': '0 -' + (settings.digitHeight * 8) + 'px'});
}
}
},
setDigit: function(elm, value) {
var pos = (value === 0) ? 0 - (settings.digitHeight * 9) : 0 - (settings.digitHeight * (10 - value - 1));
$(elm).css({'background-position': '0 ' + pos + 'px'});
},
pauseTimer: function() {
clearInterval(timeInterval);
timeInterval = null;
settings.stopTimerCallback(this.currentSeconds);
},
startTimer: function() {
if (settings.isCountDown) {
this.startDownInterval();
this.initCSS();
this.updateTime(this.currentSeconds);
} else {
this.startUpInterval();
this.initCSS();
if (this.initialStart) {
this.updateTime(0);
this.initialStart = false;
} else {
this.updateTime(this.currentSeconds);
}
}
settings.startTimerCallback(this.currentSeconds);
},
resetTimer: function() {
this.reInitialized = true;
clearInterval(timeInterval);
timeInterval = null;
this.currentSeconds = settings.seconds;
this.init();
settings.resetTimerCallback(this.currentSeconds);
},
setStartStop: function(direction) {
var self = this;
$(settings.startButton).unbind('click');
if (direction == 'stop') {
$(settings.startButton).bind('click', function() {
self.pauseTimer();
self.setStartStop();
if (this.nodeName == 'A') {return false;}
});
} else {
$(settings.startButton).bind('click', function() {
self.startTimer();
self.setStartStop('stop');
if (this.nodeName == 'A') {return false;}
});
}
},
bindEvents: function() {
var self = this;
self.setStartStop();
if (settings.resetButton) {
$(settings.resetButton).bind('click', function() {
self.resetTimer();
if (this.nodeName == 'A') {return false;}
});
}
},
destroy: function() {
clearInterval(timeInterval);
timerElm.empty();
if (settings.isCountDown) {
this.currentSeconds = settings.seconds;
} else {
this.currentSeconds = 0;
}
this.digits = [];
},
populateTimer: function() {
var self = this;
var toInject = '';
for (var i = 0; i < self.numDigits; i++) {
toInject += '<' + settings.digitElement + '></' + settings.digitElement + '>';
if (i === 0 && self.numDigits == 3 || i == 1 && self.numDigits == 4) {
toInject += '<' + settings.separatorElement + ' class="colon"></' + settings.separatorElement + '>';
}
if (self.numDigits == 5 && i == 2 || self.numDigits == 5 && i === 0) {
toInject += '<' + settings.separatorElement + ' class="colon"></' + settings.separatorElement + '>';
}
if (self.numDigits == 6 && i == 3 || self.numDigits == 6 && i === 1) {
toInject += '<' + settings.separatorElement + ' class="colon"></' + settings.separatorElement + '>';
}
}
timerElm.append(toInject);
timerElm.find(settings.digitElement).each(function() {
self.digits.push(this);
});
},
updateNumDigits: function(addAnother) {
var self = this;
var num = self.getNumberOfDigits(self.currentSeconds);
if (num > self.numDigits || addAnother) {
numDigits = num;
timerElm.append('<' + settings.digitElement + '></' + settings.digitElement + '>');
if (num > 2 && num < 5) {
timerElm.find('.colon').remove();
$('<' + settings.separatorElement + ' class="colon"></' + settings.separatorElement + '>').insertBefore(timerElm.find('span:nth-child(' + (num - 1) + ')'));
}
if (num == 5 || num == 6) {
timerElm.find('.colon').remove();
$('<' + settings.separatorElement + ' class="colon"></' + settings.separatorElement + '>').insertBefore(timerElm.find('span:nth-child(' + (num - 1) + ')'));
$('<' + settings.separatorElement + ' class="colon"></' + settings.separatorElement + '>').insertBefore(timerElm.find('span:nth-child(' + (num - 3) + ')'));
}
self.initCSS(true);
timerElm.find(settings.digitElement + ':last-child').each(function() {
self.digits.push(this);
});
}
},
getNumberOfDigits: function(sec) {
if (sec < 10) {
return 1;
} else if (sec > 35999) {
return 6;
} else if (sec > 3599) {
return 5;
} else if (sec > 599) {
return 4;
} else if (sec > 59) {
return 3;
} else {
return 2;
}
}
}; //end SpriteTimer
return this.each(function() {
SpriteTimer.init(); //run boy run!!!
var myself = this;
timerElm.unbind().bind('resetTimer', function() {
SpriteTimer.destroy();
SpriteTimer.init();
}).bind('startTimer', function() {
SpriteTimer.startTimer();
}).bind('stopTimer', function() {
SpriteTimer.pauseTimer();
});
});
};
})(jQuery);
<file_sep>/Onlineexamination/login.php
<?php
include('siteheader.php');
?>
<script type="text/javascript" src="js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#form1").validate({
});
});
</script>
<script src="js_datepicker/bootstrap-datepicker.js" type="text/javascript"></script>
<link href="js_datepicker/bootstrap-datepicker3.css" rel="stylesheet" type="text/css" />
<link href="js_datepicker/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" >
$(document).ready(function () {
var FromEndDate = new Date();
var myDate = new Date();
myDate.setDate(myDate.getDate() + 30);
$(".datep").datepicker(
{
format: 'yyyy/mm/dd',
autoclose: true,
pickerPosition: "left",
onRender: function (date) {
return (date.valueOf() <= FromEndDate.valueOf()) ? 'disabled' : '';
}
});
});
</script>
<form id="form1" name="form1" method="post" action="code/login_exe.php">
<table width="200" border="0">
<tr>
<td width="118">Username</td>
<td width="10"> </td>
<td width="62"><label>
<input type="text" name="txtuname" id="txtuname" class="required" />
</label></td>
</tr>
<tr>
<td>Password</td>
<td> </td>
<td><label>
<input type="password" name="txtpwd" id="txtpwd" class="required" />
</label></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>
<input type="submit" name="button" id="button" value="Save" />
</td>
</tr>
</table>
</form>
<?php
include('sitefooter.php');
?>
<file_sep>/Onlineexamination/code/stud_reg_exe.php
<?php
include('../ConnectionClass.php');
$name=$_POST["txtname"];
$sem=$_POST["txtsem"];
$rolno=$_POST["txtrno"];
$admsn=$_POST["txtadmnno"];
$addrss=$_POST["txtadrs"];
$gender=$_POST["gender"];
$batch=$_POST["txtbatch"];
$emlid=$_POST["txtemail"];
$passwd=$_POST["txtpwd"];
$obj=new ConnectionClass();
$qq="select count(*) from student where admin_num='$admsn' ";
$count=$obj->GetSingleData($qq);
if($count==0)
{
$obj4=new ConnectionClass();
$qq4="select count(*) from student where rollnum='$rolno' ";
$count4=$obj->GetSingleData($qq4);
if($count4==0)
{
$obj5=new ConnectionClass();
$qq5="select count(*) from student where email_id='$emlid' ";
$count5=$obj->GetSingleData($qq5);
if($count5==0)
{
$obj1=new ConnectionClass();
$q="insert into student(stud_name,semester,rollnum,admin_num,address,gender,batch,email_id) values('$name','$sem','$rolno','$admsn','$addrss','$gender','$batch','$emlid')";
$obj1->operation($q);
$obj2=new ConnectionClass();
$s="insert into login(username,password,usertype,status) values('$admsn','$passwd','student','inactive')";
$obj2->operation($s);
echo "<script>alert('Success...Your admission number will be the username to login..');location.href='../login.php'</script>";
}
else
{
echo "<script>alert('email already exist'); location.href='../student_reg.php';</script>";
}
}
else
{
echo "<script>alert('Check your rollnumber'); location.href='../student_reg.php';</script>";
}
}
else
{
echo "<script>alert('Already added'); location.href='../stud_reg_exe.php';</script>";
}
?>
<file_sep>/Onlineexamination/student/code/changepw_exe.php
<?php
session_start();
include('../../ConnectionClass.php');
$cp=$_POST["txtcp"];
$np=$_POST["txtnp"];
$cnp=$_POST["txtcop"];
$obj1=new ConnectionClass();
$username=$_SESSION["username"];
$qry="select password from login where username='$username'";
$res=$obj1->GetSingleData($qry);
if($res==$cp)
{
$oj=new ConnectionClass();
$qry1="update login set password='$np' where username='$username' ";
$t1=$oj->operation($qry1);
echo "<script>alert('Successfully Changed'); location.href='../student_home.php';</script>";
}
else
{
echo "<script>alert('Please enter the correct password');location.href='../changepassword.php';</script>";
}
?><file_sep>/Onlineexamination/test1.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<?php
//Start session
@session_register("user");
@session_register("passwd");
if(!isset($_SESSION['user'])){
header("location:testlogin.php");
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Faith Infosys Aptitude Test</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="styles.css" rel="stylesheet" type="text/css" media="screen" />
<link rel="stylesheet" href="nivo-slider.css" type="text/css" media="screen" />
<!-- clock -->
<script type="text/javascript">
window.history.forward();
</script>
<script src="jquery-1.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});
//process this function whenever a key is pressed
$(document).keydown(function (event) {
var keyCode = event.keyCode ? event.keyCode : event.charCode;
//window.status = keyCode;
// keyCode for F% on Opera is 57349 ?!
if (keyCode == 116 || keyCode ==15 ) {
return false ;
}
if(event ) {
if(event.ctrlKey ) {
return false;
}
else if(event.MOUSEDOWN)
{
alert("okkk");
}
}
});
</script>
<title>Untitled Page</title>
<style type="text/css">
#mainbody
{
width:900px;
border:2px solid gray;
overflow:auto;
margin:10px auto;
padding:20px;
background: #fff url(images/white_grey_background_upside_down.jpg) repeat-x;
height:auto;
}
.timerbox
{
height:70px;
position:fixed;
background:#ccf;
right:30px;
margin:0;
padding:5px;
top: -1px;
width:220px;
}
*html .timerbox
{
position:absolute ;
float:right;
}
ul li
{
list-style:none;
display:inline;
padding:5px ;
text-align:right;
}
ul li ul
{
padding-left:40px;
padding-top:20px;
}
ul li ul li
{
padding:10px;
}
.Questions
{
border:1px solid red;
color:Black;
font-size:medium;
padding:20px 30px;
}
</style>
<script type="text/javascript">
//<![CDATA[
var windowHeight=screen.availHeight/4*3+20+"px"
function sniffer() {
var el=document.getElementById("mainbody");
if(screen.width==1280) {
el.style.height= windowHeight;
}
else {
if(screen.width==1024) {
el.style.height= windowHeight;
}
else {
if(screen.width==800) {
el.style.height= windowHeight;
}
}
}
}
onload=sniffer;
//]]>
</script>
<script type="text/javascript" src="jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="jquery.spriteTimer-1.3.6.js"></script>
<script type="text/javascript">
function runWhenFinished() {
$('.exampleA').css({'background':'#333'});
alert("STOP! Your times Over");
document.forms.form1.submit();
}
$(document).ready(function() {
var a= 900
$('.exampleA .timer').spriteTimer({
'seconds':a,
'isCountDown': true,
'digitImagePath': 'numbers.png',
'callback': runWhenFinished
});
$('.exampleB .timer').spriteTimer({
'digitImagePath': 'numbers.png',
'seconds': 12,
'isCountDown': false
});
});
</script>
<!-- clock -->
</head>
<body>
<div id="bg2"></div>
<div id="wrapper1">
<div id="menu">
<ul>
<li><a href="test.php" class="active">Home</a></li>
<li><a href="logout.php" class="active">Logout</a></li>
</ul>
<div class="clear"></div>
</div>
<div id="logo">
<h1><a href="#">Faith Infosys</a></h1>
<a href="#"><small>Software Development And Training</small></a>
</div>
<div id="content_bg_top"></div>
<div id="content_box">
<div id="header">
<div id="wrapper">
<div id="slider-wrapper">
<img src="images/testb.jpg" width="870" height="241" />
</div>
</div>
</div>
<div id="column_box">
<div class="timerbox">
<div class="example exampleA">
<div class="timer"></div>
</div>
</div>
<p>
<form id="form1" runat="server" method="get" action="testdata.php">
<font color="#FFFFFF" size="+2">
<?php
require_once('config.php');
$con=mysql_connect(dbhost,dbuser,dbpwd);
$db=mysql_select_db(dbdata,$con);
$qry="SELECT * FROM questions where status=1 order by rand()";
$res=mysql_query($qry);
$i=1;
while($row=mysql_fetch_array($res))
{
echo $i.":";
echo $row['question']."<br>";
echo "<font color='#FFFFFF' size='+1'>";
?>
<br />
<input type="radio" name="answer<?php echo $row['qno']; ?>" value="<?php echo $row['op1']; ?>" />A : <?php echo $row['op1']; ?>
<br />
<input type="radio" name="answer<?php echo $row['qno']; ?>" value="<?php echo $row['op2']; ?>" />B : <?php echo $row['op2']; ?>
<br />
<input type="radio" name="answer<?php echo $row['qno']; ?>" value="<?php echo $row['op3']; ?>" />C : <?php echo $row['op3']; ?>
<br />
<input type="radio" name="answer<?php echo $row['qno']; ?>" value="<?php echo $row['op4']; ?>" />D : <?php echo $row['op4']; ?>
<?php
echo "</font>";
echo "<br>";
echo "<br>";
$i++;
}
?>
</font>
<div align="center"><input type="submit" name="sub" value="Submit" /></div>
</p>
</form>
<p> </p>
<div class="clear"></div>
</div>
<div id="footer_top">
<div class="clear"></div>
</div>
</div>
<div id="content_bg_bot"></div>
<div id="footer_bot">
<p>Copyright 2011. <!-- Do not remove -->Designed by <a href="http://www.myfreecsstemplates.com/" title="Free CSS Templates">Faith Infosys </a><!-- end --></p>
<p> </p>
</div>
</div>
</body>
</html>
<file_sep>/Onlineexamination/staff/questions.php
<?php
include('staffheader.php');
include('../ConnectionClass.php');
$obj1=new ConnectionClass();
$q="select * from subject join exam on subject.sub_id=exam.subject_code and exam.exam_date>DATE(NOW())";
$data=$obj1->selectdata($q);
if(count($data)>0)
{
?>
<form id="form1" name="form1" method="post" action="addquestion.php">
<table width="506" border="0" cellspacing="1" cellpadding="5">
<tr>
<td width="111" align="center">choose exam</td>
<td width="110"><label>
<select name="dpexam" id="dpexam">
<?php
foreach($data as $row)
{?>
<option value="<?php echo $row["exam_id"];?>"><?php echo $row["exam_title"]."(Sem:".$row["semester"].",Date:".$row["exam_date"].")";?></option>
<?php
}
?>
</select>
</label></td>
</tr>
<tr>
<td colspan="2"><label>
<div align="center">
<input type="submit" name="button" id="button" value="Next" />
</div>
</label></td>
</tr>
</table>
</form><?php
}
else
{?>
<script>alert('no data found');location.href='staff_home.php'; </script>
<?php
}
include('stafffooter.php');
?><file_sep>/Onlineexamination/hod/resultview.php
<?php include('hodheader.php'); ?>
<?php
$a=$_POST["p"];
$adm=$_POST["ano"];
include('../ConnectionClass.php');
$obj=new ConnectionClass();
echo $qry="select * from student join ans_sheet on ans_sheet.exam_id='$a' and ans_sheet.admn_no='$adm' and ans_sheet.admn_no=student.admin_num join exam on exam.exam_id=ans_sheet.exam_id";
$result=$obj->selectdata($qry);
if(count($result)>0)
{
foreach($result as $r)
{
?>
<table>
<tr><th colspan="2" align="center">Personal Details </th></tr>
<tr><th>Name</th><td><?php echo $r["stud_name"] ?></td></tr>
<tr><th>Semester</th><td><?php echo $r["semester"] ?></td></tr>
<tr><th>Address</th><td><?php echo $r["address"] ?></td></tr>
<tr><th>Batch</th><td><?php echo $r["batch"] ?></td></tr>
<tr><th>Gender</th><td><?php echo $r["gender"] ?></td></tr>
<tr><th>Email</th><td><?php echo $r["email_id"] ?></td></tr>
<tr><th colspan="2" align="center">Accademic Details </th></tr>
<tr><th>Exam id</th><td><?php echo $r["exam_id"] ?></td></tr>
<tr><th>Exam Name</th><td><?php echo $r["exam_title"] ?></td></tr>
<tr><th>Date</th><td><?php echo $r["exam_date"] ?></td></tr>
<tr><th>Marks Obtailed</th><td><?php echo $r["mark_obtained"] ?></td></tr>
</table>
<?php
}
}
else
{
echo "<script>alert('Not available..Please Try again..');location.href='result.php'</script>";
}
?>
<?php
include('hodfooter.php');
?><file_sep>/Onlineexamination/staff/editstud.php
<?php include('staffheader.php');
?>
<?php
$admn=$_REQUEST["id"];
include('../ConnectionClass.php');
$obj1=new ConnectionClass();
$q="select * from student join login on student.admin_num='$admn' and login.username=student.admin_num";
$result=$obj1->selectdata($q);
if(count($result)>0)
{foreach($result as $t)
{
?>
<form action="code/upstatus.php" method="post">
<table>
<tr><th>Name</th><td><input type="text" readonly="readonly" id="sname" name="sname" value="<?php echo $t["stud_name"] ?>" /></td></tr>
<tr><th>Semester</th><td><input type="text" id="sem" name="sem" value="<?php echo $t["semester"] ?>"></td></tr>
<tr><th>Address</th><td><input type="text" readonly="readonly" id="adrs" name="adrs" value="<?php echo $t["address"] ?>" /></td></tr>
<tr><th>Batch</th><td><input type="text" id="b" name="b" value="<?php echo $t["batch"] ?>" /></td></tr>
<tr><th>Gender</th><td><input type="text" readonly="readonly" id="gen" name="gen" value="<?php echo $t["gender"] ?>" /></td></tr>
<tr><th>Email</th><td><input type="text" readonly="readonly" id="em" name="em" value="<?php echo $t["email_id"] ?>" /></td></tr>
<input type="hidden" id="hid" name="hid" value="<?php echo $admn; ?>">
<tr><th>Status</th>
<td><label>
<select name="st" id="st">
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select>
</label></td>
</tr>
<tr><td colspan="2"><input type="submit" value="save" /></td></tr>
</table>
</form>
<?php
}
}
else
{
echo "<script>alert('No data');location.href='studentdetails.php'</script>";
}
?>
<?php
include('stafffooter.php');
?><file_sep>/Onlineexamination/admin/addsubject.php
<?php include('adminheader.php'); ?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#form1").validate({
});
});
</script>
<script src="../js_datepicker/bootstrap-datepicker.js" type="text/javascript"></script>
<link href="../js_datepicker/bootstrap-datepicker3.css" rel="stylesheet" type="text/css" />
<link href="../js_datepicker/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" >
$(document).ready(function () {
var FromEndDate = new Date();
var myDate = new Date();
myDate.setDate(myDate.getDate() + 30);
$(".datep").datepicker(
{
format: 'yyyy/mm/dd',
autoclose: true,
pickerPosition: "left",
onRender: function (date) {
return (date.valueOf() <= FromEndDate.valueOf()) ? 'disabled' : '';
}
});
});
</script>
<form id="form1" name="form1" method="post" action="code/addsubject_exe.php">
<table width="638" height="230" border="0">
<tr>
<td colspan="3" align="center">Add Subject</td>
</tr>
<tr>
<td width="308">Choose Semester</td>
<td width="9"> </td>
<td width="307"><label>
<select name="sem" id="sem">
<option value="select">select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</label></td>
</tr>
<tr>
<td>Enter Subject</td>
<td> </td>
<td><label>
<input type="text" name="sub" id="sub" class="required char" />
</label></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Submit" />
</label></td>
</tr>
</table>
</form>
<?php
include('../ConnectionClass.php');
$obj1=new ConnectionClass();
$q="select * from subject";
$res=$obj1->selectdata($q);
if((count($res))>0)
{
?>
<table border="1">
<tr><th>Semester</th><th>Name</th><th>Action</th></tr>
<?php
foreach($res as $row)
{
?>
<tr><td><?php echo $row["semester"];?></td><td><?php echo $row["sub_name"];?></td><td><a href="code/delsubject.php?id=<?php echo $row["sub_id"];?>" onclick="return(confirm('Are you sure want to delete it?'));">Delete</a></td></tr>
<?php
}
?>
</table>
<?php
}?>
<?php include('adminfooter.php'); ?><file_sep>/Onlineexamination/hod/scheduling.php
<?php include('hodheader.php'); ?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#form1").validate({
});
});
</script>
<script src="../js_datepicker/bootstrap-datepicker.js" type="text/javascript"></script>
<link href="../js_datepicker/bootstrap-datepicker3.css" rel="stylesheet" type="text/css" />
<link href="../js_datepicker/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" >
$(document).ready(function () {
var FromEndDate = new Date();
var myDate = new Date();
myDate.setDate(myDate.getDate() + 30);
$(".datep").datepicker(
{
format: 'yyyy/mm/dd',
autoclose: true,
pickerPosition: "left",
onRender: function (date) {
return (date.valueOf() <= FromEndDate.valueOf()) ? 'disabled' : '';
}
});
});
</script>
<?php
include('../ConnectionClass.php');
$obj1=new ConnectionClass();
$q="select * from subject group by semester";
$data=$obj1->selectdata($q);
?>
<form id="form1" name="form1" method="post" action="addexam.php">
<table width="290" border="0">
<tr>
<td colspan="2"><div align="center">EXAM SCHEDULING</div></td>
</tr>
<tr>
<td width="131">Choose Semester</td>
<td width="149"><label>
<select name="sem" id="sem" class="required">
<option value="select">select</option>
<?php
foreach($data as $r)
{
?>
<option value="<?php echo $r["semester"];?>"><?php echo $r["semester"];?></option>
<?php
}
?>
</select>
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="OK" />
</label></td>
</tr>
</table>
</form><?php include('hodfooter.php'); ?><file_sep>/Onlineexamination/hod/getexam.php
<?php
require_once("../ConnectionClass.php");
$obj=new ConnectionClass();
$sub=$_REQUEST["subject"];
$qry="select * from exam where subject_code='$sub'";
$t=$obj->selectdata($qry);
?>
<?php
foreach($t as $b)
{
?>
<option value="<?php echo $b['exam_id'];?>" ><?php echo $b['exam_title'];?></option>
<?php
}?>
<file_sep>/Onlineexamination/hod/hodfooter.php
<div class="clr"></div>
</div>
</div>
<div class="sidebar">
<div class="searchform">
</div>
<div class="gadget">
<h2 class="star"></h2>
<div class="clr"></div>
<ul class="sb_menu">
<li><a href="scheduling.php"><span>Add Exam</a></span></li>
<li><a href="approve_questions.php"><span>Approve questions</a></span></li>
<li><a href="viewresult.php"><span>View Result</a></span></li>
<li><a href="Student_Search.php"><span>Search student</a></span></li>
</ul>
</div>
<div class="gadget">
</div>
</div>
<div class="clr"></div>
</div>
</div>
<div class="fbg">
<div class="fbg_resize">
<div class="clr"></div>
</div>
</div>
<div class="footer">
<div class="footer_resize" align="center">Copyright (c) websitename. All rights reserved.
<div style="clear:both;"></div>
</div>
</div>
</div>
</body>
</html><file_sep>/Onlineexamination/index.php
<?php include('siteheader.php');?>
<marquee>Welcome..</marquee>
<img src="images/computer.jpg" width="300px" height="200px"/>
<div>Examination online is the first fully customizable software that you can mould as per your requirements. We have a strong, multi-functional base platform from which we create our intuitive, easy-to-use interface: from there we include or exclude the features you require for your own custom online exam creation and reporting functionality needs.</div>
<?php include('sitefooter.php');?>
<file_sep>/Onlineexamination/student/choose exam.php
<?php
include('studheader.php');
?>
<form method="post" action="att_exam.php">
Enter examid:<input name="examid" id="examid" type="text" />
<input value="start" type="submit" />
</form>
<?php
include('studfooter.php');
?><file_sep>/Onlineexamination/admin/code/addsubject_exe.php
<?php
$sem=$_POST["sem"];
$sub=$_POST["sub"];
include('../../ConnectionClass.php');
$obj=new ConnectionClass();
if($sem!="select")
{
$qq="select count(*) from subject where sub_name='$sub' and semester='$sem'";
$count=$obj->GetSingleData($qq);
if($count==0)
{
$obj1=new ConnectionClass();
$q="INSERT INTO subject(sub_name,semester) VALUES ('$sub', '$sem')";
$obj1->operation($q);
echo "<script>alert('Successfully Added'); location.href='../addsubject.php';</script>";
}
else
{
echo "<script>alert('Already added'); location.href='../addsubject.php';</script>";
}
}
else
{
echo "<script>alert('Please choose a subject'); location.href='../addsubject.php';</script>";
}
?><file_sep>/Onlineexamination/hod/change_password.php
<?php include('hodheader.php'); ?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#form1").validate({
rules: {
cp3: {
required: true,
equalTo: "cp2"
}
}
});
});
</script>
<script src="../js_datepicker/bootstrap-datepicker.js" type="text/javascript"></script>
<link href="../js_datepicker/bootstrap-datepicker3.css" rel="stylesheet" type="text/css" />
<link href="../js_datepicker/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" >
$(document).ready(function () {
var FromEndDate = new Date();
var myDate = new Date();
myDate.setDate(myDate.getDate() + 30);
$(".datep").datepicker(
{
format: 'yyyy/mm/dd',
autoclose: true,
pickerPosition: "left",
onRender: function (date) {
return (date.valueOf() <= FromEndDate.valueOf()) ? 'disabled' : '';
}
});
});
</script>
<form id="form1" name="form1" method="post" action="code/change_password_exe.php">
<table width="351" border="0">
<tr>
<td colspan="2"><div align="center">CHANGE PASSWORD</div></td>
</tr>
<tr>
<td width="153">Enter old password</td>
<td width="188"><label>
<input type="password" name="cp1" id="cp1" class="required" />
</label></td>
</tr>
<tr>
<td>Enter new password</td>
<td><label>
<input type="password" name="cp2" id="cp2" class="required" minlength="6" />
</label></td>
</tr>
<tr>
<td>Re-enter new password</td>
<td><label>
<input type="password" name="cp3" id="cp3" class="required" minlength="6" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Save" />
</label></td>
</tr>
</table>
</form><?php include('hodfooter.php'); ?><file_sep>/Onlineexamination/staff/code/my_profile_exe.php
<?php
session_start();
$fname=$_POST["fname"];
$lname=$_POST["lname"];
$des=$_POST["desig"];
$adrs=$_POST["adrs"];
$quali=$_POST["quali"];
include('../../ConnectionClass.php');
$obj1=new ConnectionClass();
$username=$_SESSION["username"];
$qry="update faculty set f_name='$fname',l_name='$lname',designation='$des',address='$adrs',qualification='$quali' where staff_id='$username'";
$res=$obj1->operation($qry);
echo "<script>alert('Successfully Changed'); location.href='../myprofile.php';</script>";
?><file_sep>/Onlineexamination/hod/code/delexam.php
<?php
$sid=$_REQUEST["id"];
include('../../ConnectionClass.php');
$obj=new ConnectionClass();
$qq="delete from exam where exam_id='$sid'";
$count=$obj->operation($qq);
echo "<script>alert('Success..'); location.href='../scheduling.php';</script>";
?><file_sep>/Onlineexamination/staff/staff_home.php
<?php
include('staffheader.php');
?>
<marquee>Welcome Staff...</marquee>
<img src="../images/computer.jpg" width="300px" height="200px"/>
<div>Examination online is the first fully customizable software that you can mould as per your requirements. We have a strong, multi-functional base platform from which we create our intuitive, easy-to-use interface: from there we include or exclude the features you require for your own custom online exam creation and reporting functionality needs.</div>
<?php
include('stafffooter.php');
?><file_sep>/Onlineexamination/hod/acceptreject.php
<?php include('hodheader.php');
$ex=$_REQUEST["examid"];
$fid=$_REQUEST["fac"];
include('../ConnectionClass.php');
$obj1=new ConnectionClass();
$q="select * from questions where exam_id='$ex' and fuc_id='$fid' order by question_id";
$data=$obj1->selectdata($q);
?><a href="approve_questions.php">back</a>
<table>
<tr><th>Question</th><th>Oprion1</th><th>Option2</th><th>Option3</th><th>Option4</th><th>Answer</th></tr>
<?php
foreach($data as $r)
{
?>
<tr><th><?php echo $r["title"]; ?></th><th><?php echo $r["option1"]; ?></th><th><?php echo $r["option2"]; ?></th><th><?php echo $r["option3"]; ?></th><th><?php echo $r["option4"]; ?></th><th><?php echo $r["correct_ans"];?></th></tr>
<?php
}?>
</table>
<?php include('hodfooter.php'); <file_sep>/Onlineexamination/staff/addquestion.php
<?php
include('staffheader.php');
//session_start();
$username=$_SESSION["username"];
if(!(isset($_POST["dpexam"])))
{
$examid=$_SESSION["examid"];
}
else
{
$examid=$_POST["dpexam"];
$_SESSION["examid"]=$examid;
}
?>
<form id="form1" name="form1" method="post" action="code/addqu_exe.php">
<input type="hidden" id="hid" name="hid" value="<?php echo $examid; ?>" />
<table width="596" border="0" cellspacing="1" cellpadding="5">
<tr>
<td> </td>
<td>Add Questions</td>
</tr>
<tr>
<td width="167">Question</td>
<td width="406"><label>
<textarea name="aq1" id="aq1" class="required"></textarea>
</label></td>
</tr>
<tr>
<td>Option 1</td>
<td><label>
<input type="text" name="txtop1" id="txtop1" class="required" />
</label></td>
</tr>
<tr>
<td>Option 2</td>
<td><label>
<input type="text" name="txtop2" id="txtop2" class="required" />
</label></td>
</tr>
<tr>
<td>Option 3</td>
<td><label>
<input type="text" name="txtop3" id="txtop3" class="required" />
</label></td>
</tr>
<tr>
<td>Option 4</td>
<td><label>
<input type="text" name="txtop4" id="txtop4" class="required" />
</label></td>
</tr>
<tr>
<td>Correct answer</td>
<td><label>
<input type="text" name="txtans" id="txtans" class="required" />
</label></td>
</tr>
<tr>
<td colspan="2"><label>
<div align="center">
<input type="submit" name="sav" id="sav" value="Save" />
</div>
</label></td>
</tr>
</table>
</form>
<?php
include('../ConnectionClass.php');
$obj11=new ConnectionClass();
$q1="select * from questions where exam_id='$examid' and fuc_id='$username'";
$data1=$obj11->selectdata($q1);
if(count($data1)>0)
{
?>
<table>
<tr><th>Slno</th><th>Question</th><th>Option1</th><th>Option2</th><th>Option3</th><th>Option4</th><th>Answer</th><th>Action</th></tr>
<?php
$i=1;
foreach($data1 as $r)
{
?>
<tr><td><?php echo $i;$i++; ?></td><td><?php echo $r["title"];?></td><td><?php echo $r["option1"];?></td><td><?php echo $r["option2"];?></td><td><?php echo $r["option3"];?></td><td><?php echo $r["option4"];?></td><td><?php echo $r["correct_ans"];?></td><td><a href="code/delquestion.php?id=<?php echo $r["question_id"];?>" onclick="return(confirm('Are you sure want to delete it?'));">Delete</a></td></tr>
<?php
}
?>
</table>
<?php
}
include('stafffooter.php');
?><file_sep>/Onlineexamination/sitelink.php
<a href="result.php">Check result</a>
<file_sep>/Onlineexamination/student/code/profile_exe.php
<?php
session_start();
$name=$_POST["txtname"];
$sem=$_POST["txtsem"];
$adrs=$_POST["txtadrs"];
include('../../ConnectionClass.php');
$obj1=new ConnectionClass();
$username=$_SESSION["username"];
$qry="update student set stud_name='$name',semester='$sem',address='$adrs' where admin_num='$username'";
$res=$obj1->operation($qry);
echo "<script>alert('Successfully Changed'); location.href='../myprofile.php';</script>";
?><file_sep>/Onlineexamination/admin/code/delfaculty.php
<?php
$sid=$_REQUEST["id"];
include('../../ConnectionClass.php');
$obj=new ConnectionClass();
$qq="delete from faculty where staff_id='$sid'";
$count=$obj->operation($qq);
$obj1=new ConnectionClass();
$qq1="delete from login where username='$sid'";
$count1=$obj1->operation($qq1);
echo "<script>alert('Success..'); location.href='../viewfaculty.php';</script>";
?><file_sep>/Onlineexamination/hod/staff_search.php
<?php include('hodheader.php'); ?>
<form name="form1" method="post" action="viewstaff.php">
<table width="230" border="1">
<tr>
<td width="64">Staff Id</td>
<td width="150"><label>
<input type="text" name="txtadmn" id="textfield">
</label></td>
</tr>
<tr>
<td colspan="2"><label>
<div align="center">
<input type="submit" name="button" id="button" value="Search">
</div>
</label></td>
</tr>
</table>
</form>
<?php include('hodfooter.php'); ?>
<file_sep>/Onlineexamination/admin/adminlinks.php
<a href="admin_home.php">Home</a>
<a href="change_password.php">Change Password</a>
<a href="addfaculty.php">Add Staff</a>
<a href="viewfaculty.php">View Staff</a>
<a href="addsubject.php">Manage Subject</a>
<!--<a href="viewresult.php">View Results</a>-->
<a href="../login.php">Logout</a><file_sep>/Onlineexamination/staff/code/upstatus.php
<?php
$sem=$_POST["sem"];
$status=$_POST["st"];
$admn=$_POST["hid"];
include('../../ConnectionClass.php');
$obj1=new ConnectionClass();
$qry="update student set semester='$sem' where admin_num='$admn'";
$res=$obj1->operation($qry);
$obj11=new ConnectionClass();
$qry1="update login set status='$status' where username='$admn'";
$res1=$obj11->operation($qry1);
echo "<script>alert('Successfully Changed'); location.href='../allstudentdetails.php';</script>";
?><file_sep>/Onlineexamination/hod/code/addexam_exe.php
<?php
session_start();
$sem=$_POST["hid"];
$sub=$_POST["sub"];
$title=$_POST["etitle"];
$edate=$_POST["edate"];
$duration='15';
$username=$_SESSION["username"];
include('../../ConnectionClass.php');
$obj=new ConnectionClass();
$qq="select count(*) from exam where exam_title='$title' and exam_date='$edate' and sem='$sem'";
$count=$obj->GetSingleData($qq);
if($count==0)
{
$obj1=new ConnectionClass();
$q="INSERT INTO exam(exam_date,exam_title,subject_code,staff_id,duration,sem) VALUES ( '$edate','$title','$sub','$username','$duration','$sem')";
$obj1->operation($q);
echo "<script>alert('Successfully Added'); location.href='../scheduling.php';</script>";
}
else
{
echo "<script>alert('Already added'); location.href='../scheduling.php';</script>";
}
?>
|
ad0e8d32cfe8bbf8b53fee25a13017b29474fea4
|
[
"Hack",
"JavaScript",
"PHP"
] | 61 |
Hack
|
silpasusanalex/Onlineexaminationproject
|
a5b0ab3d1116afbd9148253f2b354bb57ece4d29
|
7fa0cf2a8be2224220f56d79d6c53ba5b8d4a6b1
|
refs/heads/master
|
<repo_name>bishengliu/seq_viewer<file_sep>/README.md
This is the js API for viewing plasmid sequence. version 1.0.0. 2016-10-07.
```
var data = {
id: "#displaySeq", //id of the seqViewer div
searchId: "#seqSearch", //search id
sequence: sequence, //sequence
features: features, //feature array
enzymes: enzymes
};
//draw the seqViewer
var sv = new seqViewer();
sv.read(data);
sv.draw();
//redraw the svg when changing the page size
$(window).resize(function (){
sv.redraw();
});
```
|
ebb2c445ed73a4a3af1392fbbfba402d58362e89
|
[
"Markdown"
] | 1 |
Markdown
|
bishengliu/seq_viewer
|
6554b6547b54b479d9c98c7bd51286c812588643
|
06a0ef6a6a2f7238e83feef32cbf06889366cb19
|
refs/heads/master
|
<repo_name>DemonSnake/MakTokenizer<file_sep>/searchEngine.py
"""
Module for searching some query in a database
"""
import os
import shelve
import tokenizer
import indexator
from indexator import Indexator
class ContextWindow():
"""
Class representing a context window
Remembers the boundaries, number and string representation of a line,
filename, positions of target tokens and
string representation of the context
"""
def __init__(self):
"""
Method for initializing of an empty context window
"""
self.lineString = ""
self.targetTokensPositions = []
self.rightBoundary = 0
self.leftBoundary = 0
self.string = ""
self.filename = ""
self.lineNumber = -1
@staticmethod
def initWithData(lineString, tokenPositions, right, left, string, filename, lineNumber):
"""
Method for creating a context window from preproccessored data
@param lineString: string representation of the line
@param tokenPositions: list of positions of target tokens
@param right: the right boundary
@param left: the left boundary
@param string: string representation of the context
@param filename: path to the source file
@param lineNumber: number of the line in the file
@return: ContextWindow
"""
contextWindow = ContextWindow()
contextWindow.lineString = lineString
contextWindow.targetTokensPositions = tokenPositions
contextWindow.rightBoundary = right
contextWindow.leftBoundary = left
contextWindow.string = string
contextWindow.filename = filename
contextWindow.lineNumber = lineNumber
return contextWindow
@staticmethod
def makeWindowGreatAgain(size, filename, position):
"""
Method for creating a context window using the source file and token position
@param size: size of the context window
@param filename: path to the source file
@param position: position of the target token
"""
contextWindow = ContextWindow()
contextWindow.filename = filename
contextWindow.lineNumber = position.posLine
contextWindow.lineString = ""
flag = False
with open(filename, 'r') as f:
for i, l in enumerate(f):
if i+1 == position.posLine:
contextWindow.lineString = l
flag = True
if flag == False:
raise ValueError
contextWindow.targetToken = contextWindow.lineString[position.posBegin:position.posEnd]
contextWindow.targetTokensPositions = []
contextWindow.targetTokensPositions.append(indexator.Position(
position.posBegin, position.posEnd, position.posLine))
right = ""
# rightArray = []
left = ""
# leftArray = []
rawTokens = tokenizer.Tokenizer().genclasstokenize(
contextWindow.lineString[position.posEnd:])
i = 0
temp = "" # buffer against wrong tokens
# tempT = []
for rawToken in rawTokens:
if i < size:
if '\n' in rawToken.string:
break
temp += rawToken.string # buffer updates till alpha/digit token
# tempT.append(rawToken)
# rightArray.append(rawToken)
if (rawToken.category == 'alpha') or (rawToken.category == 'digit'):
right += temp # buffer flushes to other context
temp = ""
# rightArray += tempT
# tempT = []
i += 1
else:
break
contextWindow.rightBoundary = position.posEnd + len(right)
rawTokensLeft = tokenizer.Tokenizer().genclasstokenize(
contextWindow.lineString[position.posBegin - 1::-1])
i = 0
temp = ""
# tempT = []
for rawToken in rawTokensLeft:
if i < size:
if '\n' in rawToken.string:
break
# print("token: '" + rawToken.string + "'")
temp = rawToken.string[::-1] + temp
# tempT.append(tokenizer.ClassifiedToken(
# rawToken.position, rawToken.string[::-1], rawToken.category))
# leftArray.append(tokenizer.ClassifiedToken(
# rawToken.position, rawToken.string[::-1], rawToken.category))
if (rawToken.category == 'alpha') or (rawToken.category == 'digit'):
left = temp + left
temp = ""
# leftArray += tempT
# tempT = []
i += 1
else:
break
# leftArray = leftArray[::-1]
contextWindow.leftBoundary = position.posBegin - len(left)
contextWindow.string = left + contextWindow.targetToken + right
return contextWindow
def __eq__(self, someshit):
"""
Method for comparison of two windows
@param someshit: to what it should compare
@return: True if positions are equel, False otherwise
"""
return (self.targetTokensPositions == someshit.targetTokensPositions
and self.lineString == someshit.lineString
and self.rightBoundary == someshit.rightBoundary
and self.leftBoundary == someshit.leftBoundary
and self.string == someshit.string
and self.filename == someshit.filename
and self.lineNumber == someshit.lineNumber)
def __repr__(self):
"""
Method for representation a context window
@return: string representation
"""
return self.string
def intersectWindows(self, windowB):
"""
Method for intersecting two neighbouring context windows
@param windowB: the right window to be intersected
@return: combined ContextWindow
"""
resultWindow = ContextWindow()
resultWindow.lineString = self.lineString
resultWindow.rightBoundary = windowB.rightBoundary
resultWindow.leftBoundary = self.leftBoundary
resultWindow.lineNumber = self.lineNumber
resultWindow.filename = self.filename
resultWindow.targetTokensPositions = []
resultWindow.targetTokensPositions += self.targetTokensPositions
resultWindow.targetTokensPositions += windowB.targetTokensPositions
resultWindow.string = resultWindow.lineString[self.leftBoundary:windowB.rightBoundary]
return resultWindow
@staticmethod
def unionWindows(windows):
"""
Method for uniting a list of windows if there are some windows that need intersecting
@param windows: the list of windows
@return: list of combined ContextWindows
"""
windowsUnited = []
i = 0
while i < len(windows):
if (i < len(windows) - 1) and (
windows[i].filename == windows[i + 1].filename) and (
windows[i].lineNumber == windows[i + 1].lineNumber) and (((
windows[i].leftBoundary < windows[i + 1].rightBoundary) and (
windows[i + 1].leftBoundary < windows[i].rightBoundary)) or ((
windows[i + 1].leftBoundary == windows[i].rightBoundary) or (
windows[i + 1].leftBoundary == windows[i].rightBoundary + 2) or (
windows[i + 1].leftBoundary == windows[i].rightBoundary - 2))):
windowsUnited.append(windows[i].intersectWindows(windows[i + 1]))
i += 2
else:
windowsUnited.append(windows[i])
i += 1
return windowsUnited
def expandToSentence(self):
"""
Method for expanding a window to match sentence boundaries
"""
i = 0
str = self.lineString[self.rightBoundary:]
while i < len(str):
if ((str[i] == '.') or (str[i] == '?') or (str[i] == '!') and (
str[i + 1] == " ") and (str[i + 2].isupper())):
self.rightBoundary += i + 1
self.string = self.lineString[self.leftBoundary:self.rightBoundary]
break
i += 1
i = self.leftBoundary
str = self.lineString[:self.leftBoundary]
while i > 1:
if ((str[i - 2] == '.') or (str[i - 2] == '?') or (str[i - 2] == '!') and (
str[i - 1] == " ") and (str[i].isupper())):
self.leftBoundary = i
self.string = self.lineString[self.leftBoundary:self.rightBoundary]
break
i -= 1
def markTarget(self):
"""
Method for marking target tokens with bold formatting in a context window
@return: string with bold formatting of target tokens
"""
markedString = self.string
print(markedString)
for pos in self.targetTokensPositions:
targetToken = self.lineString[pos.posBegin:pos.posEnd]
print(targetToken)
markedString = markedString.replace(targetToken, "<b>" + targetToken + "</b>")
print(markedString)
return markedString
class SearchEngine(object):
"""
Tool for searching in a database
"""
def __init__(self, dbName):
"""
Method for initialization a search engine
@param dbName: path of the database
"""
self.db = shelve.open(dbName)
def __del__(self):
"""
Method for the end of the work with the search engine
"""
try:
self.db.close()
except Exception:
return
def search(self, token):
"""
Method for searching one word in the database
@param token: a string (word) to be found
@return: dictionary of filenames as keys and positions of tokens as values
"""
if isinstance(token, str):
return self.db.get(token, {})
else:
raise ValueError
def searchQuery(self, query):
"""
Method for searching a query in the database
Returns dictionary with filenames and positions of all tokens from the query
@param query: a string of tokens to be found
@return: dictionary of filenames as keys and positions of tokens as values
"""
if not(isinstance(query, str)):
raise ValueError
rawTokens = tokenizer.Tokenizer().genclasstokenize(query)
tokens = indexator.Indexator.relevancyFilter(rawTokens)
responds = [] # list of responds of search function for each token in the query
for token in tokens:
responds.append(self.search(token.string))
files = set(responds[0].keys()) # set of filenames from first respond
for d in responds[1:]: # intersection of all filenames in all responds
files.intersection_update(set(d.keys()))
resultDict = {}
for file in files:
resultDict[file] = [] # for every file in intersection of files
for d in responds: # write as values all positions from intersection of files
resultDict[file] += d.get(file, [])
return resultDict
# def searchQueryWindow(self, query, windowSize):
# """
# Method for searching a query in the database which returns windows
# @param query: a string of tokens to be found
# @return: dictionary of filenames as keys and context windows of tokens as values
# """
# positionDict = self.searchQuery(query)
# contextDict = {}
# for k in positionDict.keys():
# print(k)
# contexts = []
# for i in positionDict[k]:
# print(i)
# contexts.append(ContextWindow.makeWindowGreatAgain(
# windowSize, k, i))
# contextDict[k] = ContextWindow().unionWindows(contexts)
# return contextDict
if __name__ == "__main__":
with open('test.txt', 'w') as f:
f.write('All we need is, all we need is, all we need is')
# f.write('And he said yes. All we need is blood. How much pain it is')
with open('testtest.txt', 'w') as f:
f.write('Blood, blood, blood')
with open('testtesttest.txt', 'w') as f:
f.write('All we need is, all we need is,\n all we need is')
with open('test.txt', 'r') as f:
for i, l in enumerate(f):
if i == 0:
lineString = l
targetToken = lineString[20:22]
right = ""
rightArray = []
left = ""
leftArray = []
rawTokens = tokenizer.Tokenizer().genclasstokenize(lineString[22:])
i = 0
for rawToken in rawTokens:
if i < 3:
right += rawToken.string
rightArray.append(rawToken)
if (rawToken.category == 'alpha') or (rawToken.category == 'digit'):
i += 1
rawTokensLeft = tokenizer.Tokenizer().genclasstokenize(lineString[19::-1])
i = 0
for rawToken in rawTokensLeft:
if i < 3:
left = rawToken.string[::-1] + left
leftArray.append(rawToken)
if (rawToken.category == 'alpha') or (rawToken.category == 'digit'):
i += 1
# print(targetToken)
# print(right)
# print(left)
# print(left + targetToken + right)
pos2 = indexator.Position(20, 22, 1)
pos1 = indexator.Position(23, 27, 1)
context1 = ContextWindow.makeWindowGreatAgain(5, 'test.txt', pos1)
context2 = ContextWindow.makeWindowGreatAgain(3, 'test.txt', pos2)
contexts = []
contexts.append(context1)
contexts.append(context2)
unionContexts = ContextWindow().unionWindows(contexts)
# context1.expandToSentence()
# print(context1.string)
# string = "all we need is, all we need is"
print(unionContexts[0].markTarget())
# pos1 = indexator.Position(20, 22, 0)
# pos2 = indexator.Position(32, 35, 0)
# pos3 = indexator.Position(7, 12, 0)
# pos4 = indexator.Position(20, 22, 0)
# pos5 = indexator.Position(28, 30, 0)
# pos6 = indexator.Position(1, 4, 1)
# context1 = ContextWindow.makeWindowGreatAgain(2, 'test.txt', pos1)
# context2 = ContextWindow.makeWindowGreatAgain(2, 'test.txt', pos2)
# context3 = ContextWindow.makeWindowGreatAgain(1, 'testtest.txt', pos3)
# context4 = ContextWindow.makeWindowGreatAgain(8, 'testtesttest.txt', pos4)
# context5 = ContextWindow.makeWindowGreatAgain(2, 'testtesttest.txt', pos5)
# context6 = ContextWindow.makeWindowGreatAgain(2, 'testtesttest.txt', pos6)
# print("'" + context1.string + "'")
# print("'" + context2.string + "'")
# print("'" + context3.string + "'")
# print("'" + context4.string + "'")
# print("'" + context5.string + "'")
# print("'" + context6.string + "'")
# print("=======")
# contexts = []
# contexts.append(context1)
# contexts.append(context2)
# contexts.append(context3)
# contexts.append(context4)
# contexts.append(context5)
# contexts.append(context6)
# unionContexts = ContextWindow().unionWindows(contexts)
# for u in unionContexts:
# print(u)
# print("====================")
# print(context.right)
# print(context.left)
# print(context.targetToken)
# print(context.string)
# print(context.leftBoundary)
# print(context.rightBoundary)
# string = "\n "
# strings = tokenizer.Tokenizer().genclasstokenize(string)
# for s in strings:
# print(s)
files = os.listdir(path=".")
for file in files:
if file.startswith('test'):
os.remove(file)<file_sep>/server.py
"""
Module for web query server
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
class RequestHandler(BaseHTTPRequestHandler):
"""
Class for managing events
"""
def do_GET(self):
"""
Method which runs when webpage is opened
"""
self.send_response(200)
self.send_header("Content-type", "text/html; charset=utf-8")
self.end_headers()
htmlc = """
<html>
<body>
<form method=”post”>
<input type = “text” name = “query”>
<input type = “submit”>
</form>
</body>
</html>
"""
self.wfile.write(bytes(htmlc, encoding="UTF-8"))
if __name__ == "__main__":
server = HTTPServer(('', 80), RequestHandler)
server.serve_forever()<file_sep>/indextest.py
import unittest
import os
import shelve
import indexator
from indexator import Indexator
class Test(unittest.TestCase):
def setUp(self):
self.Indexator = Indexator("TestDatabase")
'''
#unittests for indexize method
def test_input_type_number(self):
with self.assertRaises(ValueError):
self.Indexator.indexize(13)
def test_input_type_not_exists(self):
with self.assertRaises(ValueError):
self.Indexator.indexize('magsorcsareop.txt')
def test_result_one_file_one_word(self):
filename = open('test.txt', 'w')
filename.write('word')
filename.close()
self.Indexator.indexize('test.txt')
flag = False
files = os.listdir(path=".")
if os.name == 'nt':
for file in files:
if file.startswith('TestDatabase.'):
flag = True
else:
for file in files:
if file == 'TestDatabase':
flag = True
self.assertEqual(flag, True)
dbdict = dict(self.Indexator.database)
expected = {'word':{'test.txt': [indexator.Position(0,4)]}}
self.assertEqual(dbdict, expected)
def test_result_one_file_many_words(self):
filename = open('test.txt', 'w')
filename.write('BRP arena is easy')
filename.close()
self.Indexator.indexize('test.txt')
dbdict = dict(self.Indexator.database)
expected = {'BRP': {'test.txt': [indexator.Position(0,3)]},
'arena': {'test.txt': [indexator.Position(4,9)]},
'is': {'test.txt': [indexator.Position(10,12)]},
'easy': {'test.txt': [indexator.Position(13,17)]}}
self.assertEqual(dbdict, expected)
def test_result_two_files_one_word(self):
filename = open('firstrun.txt', 'w')
filename.write('easy')
filename.close()
self.Indexator.indexize('firstrun.txt')
filename = open('secondrun.txt', 'w')
filename.write('easy')
filename.close()
self.Indexator.indexize('secondrun.txt')
dbdict = dict(self.Indexator.database)
expected = {'easy': {'firstrun.txt': [indexator.Position(0,4)],
'secondrun.txt': [indexator.Position(0,4)]}}
self.assertEqual(dbdict, expected)
def test_result_two_files_many_words(self):
filename = open('firstrun.txt', 'w')
filename.write('too easy')
filename.close()
self.Indexator.indexize('firstrun.txt')
filename = open('secondrun.txt', 'w')
filename.write('not so easy')
filename.close()
self.Indexator.indexize('secondrun.txt')
dbdict = dict(self.Indexator.database)
expected = {'too': {'firstrun.txt': [indexator.Position(0,3)]},
'not': {'secondrun.txt': [indexator.Position(0,3)]},
'so': {'secondrun.txt': [indexator.Position(4,6)]},
'easy': {'firstrun.txt': [indexator.Position(4,8)],
'secondrun.txt': [indexator.Position(7,11)]}}
self.assertEqual(dbdict, expected)
'''
#unittests for indexize method with lines
def test_result_one_file_one_line(self):
filename = open('test.txt', 'w')
filename.write('word')
filename.close()
self.Indexator.indexize('test.txt')
flag = False
files = os.listdir(path=".")
if os.name == 'nt':
for file in files:
if file.startswith('TestDatabase.'):
flag = True
else:
for file in files:
if file == 'TestDatabase':
flag = True
self.assertEqual(flag, True)
dbdict = dict(self.Indexator.database)
expected = {'word':{'test.txt': [indexator.Position(0,4,1)]}}
self.assertEqual(dbdict, expected)
def test_result_one_file_two_lines(self):
filename = open('test.txt', 'w')
filename.write('BRP arena\nis easy')
filename.close()
self.Indexator.indexize('test.txt')
dbdict = dict(self.Indexator.database)
expected = {'BRP': {'test.txt': [indexator.Position(0,3,1)]},
'arena': {'test.txt': [indexator.Position(4,9,1)]},
'is': {'test.txt': [indexator.Position(0,2,2)]},
'easy': {'test.txt': [indexator.Position(3,7,2)]}}
self.assertEqual(dbdict, expected)
def test_result_one_file_three_lines(self):
filename = open('test.txt', 'w')
filename.write('BRP arena\nis very\nvery easy')
filename.close()
self.Indexator.indexize('test.txt')
dbdict = dict(self.Indexator.database)
expected = {'BRP': {'test.txt': [indexator.Position(0,3,1)]},
'arena': {'test.txt': [indexator.Position(4,9,1)]},
'is': {'test.txt': [indexator.Position(0,2,2)]},
'easy': {'test.txt': [indexator.Position(5,9,3)]},
'very': {'test.txt': [indexator.Position(3,7,2), indexator.Position(0,4,3)]}}
self.assertEqual(dbdict, expected)
def test_result_two_files_many_words(self):
filename = open('firstrun.txt', 'w')
filename.write('too\neasy')
filename.close()
self.Indexator.indexize('firstrun.txt')
filename = open('secondrun.txt', 'w')
filename.write('not so\neasy')
filename.close()
self.Indexator.indexize('secondrun.txt')
dbdict = dict(self.Indexator.database)
expected = {'too': {'firstrun.txt': [indexator.Position(0,3,1)]},
'not': {'secondrun.txt': [indexator.Position(0,3,1)]},
'so': {'secondrun.txt': [indexator.Position(4,6,1)]},
'easy': {'firstrun.txt': [indexator.Position(0,4,2)],
'secondrun.txt': [indexator.Position(0,4,2)]}}
self.assertEqual(dbdict, expected)
def test_result_two_files_empty_line(self):
filename = open('firstrun.txt', 'w')
filename.write('too\neasy')
filename.close()
self.Indexator.indexize('firstrun.txt')
filename = open('secondrun.txt', 'w')
filename.write('not so\n\neasy')
filename.close()
self.Indexator.indexize('secondrun.txt')
dbdict = dict(self.Indexator.database)
expected = {'too': {'firstrun.txt': [indexator.Position(0,3,1)]},
'not': {'secondrun.txt': [indexator.Position(0,3,1)]},
'so': {'secondrun.txt': [indexator.Position(4,6,1)]},
'easy': {'firstrun.txt': [indexator.Position(0,4,2)],
'secondrun.txt': [indexator.Position(0,4,3)]}}
self.assertEqual(dbdict, expected)
def tearDown(self):
self.Indexator.database.close()
files = os.listdir(path=".")
for file in files:
if file == 'test.txt':
os.remove(file)
if file == 'firstrun.txt':
os.remove(file)
if file == 'secondrun.txt':
os.remove(file)
if file.startswith('TestDatabase.'):
os.remove(file)
if file == 'TestDatabase':
os.remove(file)
if __name__ == '__main__':
unittest.main()
<file_sep>/tokenizer.py
"""
Module for parsing a string to tokens
"""
import unicodedata
class Token(object):
"""
Class representing a word.
Remembers position in the stream and string representation
"""
def __init__(self, position, string):
"""
Method for initialization a simple token
@param position: position of a token in the string
@param string: string representation of a token
"""
self.position = position
self.string = string
def __repr__(self):
"""
Method for representation an instance of the Token class
@return: string representation
"""
return self.string + '_' + str(self.position)
class ClassifiedToken(Token):
"""
Class representing a word.
Remembers position in the stream, string representation
and the type of the token - string/digit/punct/space/other
"""
def __init__(self, position, string, category):
"""
Method for initialization a simple token
@param position: position of a token in the string
@param string: string representation of a token
@param category: type of a token - string/digit/punct/space/other
"""
self.position = position
self.string = string
self.category = category
def __repr__(self):
"""
Method for representation an instance of the Token class
@return: string representation
"""
return self.string + ' ' + str(self.category) + ' ' + str(self.position)
class Tokenizer(object):
"""
Tool for tokenization using methods tokenize/gentokenize/genclasstokenize
"""
@staticmethod
def _categorize(sym):
"""
Method for determining the type of the symbol
@param sym: symbol which type is to be determined
@return: the type of the symbol
"""
if sym.isalpha():
return "alpha"
elif sym.isspace():
return "space"
elif unicodedata.category(sym)[0] == 'P':
return "punct"
elif sym.isdigit():
return "digit"
else:
return "other"
def tokenize(self, stream):
"""
Method for parsing, returns a list of Tokens
@param stream: string that needs parsing
@return: list of tokens
"""
if not type(stream) is str:
raise ValueError
tokens = []
if stream == "":
return tokens
index = -1 # -1 means previous symbol is not alpha
for i, char in enumerate(stream):
if index > -1 and not char.isalpha(): # end of a word
word = Token(index, stream[index:i])
tokens.append(word)
index = -1
if index == -1 and char.isalpha(): # beginning of a word
index = i
if char.isalpha(): # last word in the stream
word = Token(index, stream[index:i+1])
tokens.append(word)
return tokens
def gentokenize(self, stream):
"""
Method for parsing, returns generator
@param stream: string that needs parsing
@return: generator
"""
if not type(stream) is str:
raise ValueError
if stream == "":
return
index = -1 # -1 means previous symbol is not alpha
for i, char in enumerate(stream):
if index > -1 and not char.isalpha(): # end of a word
word = Token(index, stream[index:i])
yield word
index = -1
if index == -1 and char.isalpha(): # beginning of a word
index = i
if char.isalpha(): # last word in the stream
word = Token(index, stream[index:i+1])
yield word
def genclasstokenize(self, stream):
"""
Method for parsing
Returns Tokens of string/digit/punct/space/other classes
@param stream: string that needs parsing
@return: generator
"""
if not type(stream) is str:
raise ValueError
if stream == "":
return
index = 0 # beginning of a token
precat = Tokenizer._categorize(stream[0]) # category of the previous token
for i, char in enumerate(stream[1:len(stream)]):
curcat = Tokenizer._categorize(char)
if curcat != precat:
word = ClassifiedToken(index, stream[index:i+1], precat)
index = i + 1
precat = curcat
yield word
word = ClassifiedToken(index, stream[index:len(stream)+2], precat) # last token
# word = ClassifiedToken(index, stream[index:i+2], precat) # last token
yield word
if __name__ == '__main__':
stream = "some string!"
#print(stream[1:len(stream)])
#stream = " 12мама мыла3 раму!!"
#words = Tokenizer().tokenize(stream)
#print(words)
#words = Tokenizer().gentokenize(stream)
#wordlist = list(words)
#print(wordlist)
wordclasses = Tokenizer().genclasstokenize(stream)
wordclasseslist = list(wordclasses)
print(wordclasseslist)
#print(Tokenizer._categorize(stream[0]))
<file_sep>/searchenginetest.py
import unittest
import os
import shelve
import indexator
import searchEngine
from indexator import Indexator
from searchEngine import SearchEngine
class Test(unittest.TestCase):
def setUp(self):
with open('test0.txt', 'w') as f:
f.write('All we need is,\n all we need is,\n all we need is')
with open('test1.txt', 'w') as f:
f.write('Blood, blood,\n blood')
with open('test2.txt', 'w') as f:
f.write('All we need is, all we need is,\n all we need is')
with open('test.txt', 'w') as f:
f.write('All we need is, all we need is, all we need is')
with open('testtest.txt', 'w') as f:
f.write('Blood, blood, blood')
with open('testtesttest.txt', 'w') as f:
f.write('All we need is, all we need is,\n all we need is')
with open('testSentence.txt', 'w') as f:
f.write('What do we need? All we need is blood. Pain pain pain pain')
indexer = Indexator('TestDatabase')
indexer.indexize('test0.txt')
indexer.indexize('test1.txt')
indexer.indexize('test2.txt')
self.searchEngine = SearchEngine("TestDatabase")
# unittests for search
def test_input_type_number(self):
with self.assertRaises(ValueError):
self.searchEngine.search(13)
def test_input_type_not_exists(self):
self.assertEqual(self.searchEngine.search('вискас'), {})
def test_we(self):
expected = {
'test0.txt': [
indexator.Position(4, 6, 1),
indexator.Position(5, 7, 2),
indexator.Position(5, 7, 3)],
'test2.txt': [
indexator.Position(4, 6, 1),
indexator.Position(20, 22, 1),
indexator.Position(5, 7, 2)]}
self.assertEqual(self.searchEngine.search('we'), expected)
def test_blood(self):
expected = {
'test1.txt': [
indexator.Position(7, 12, 1),
indexator.Position(1, 6, 2)]}
self.assertEqual(self.searchEngine.search("blood"), expected)
# unittests for searchQuery
def test__query_input_type_number(self):
with self.assertRaises(ValueError):
self.searchEngine.searchQuery(13)
def test_query_input_type_not_exists(self):
self.assertEqual(self.searchEngine.searchQuery('вискас'), {})
def test_we_is(self):
expected = {
'test0.txt': [
indexator.Position(4, 6, 1),
indexator.Position(5, 7, 2),
indexator.Position(5, 7, 3),
indexator.Position(12, 14, 1),
indexator.Position(13, 15, 2),
indexator.Position(13, 15, 3)],
'test2.txt': [
indexator.Position(4, 6, 1),
indexator.Position(20, 22, 1),
indexator.Position(5, 7, 2),
indexator.Position(12, 14, 1),
indexator.Position(28, 30, 1),
indexator.Position(13, 15, 2)]}
self.assertEqual(self.searchEngine.searchQuery('we is'), expected)
def test_need(self):
expected = {
'test0.txt': [
indexator.Position(7, 11, 1),
indexator.Position(8, 12, 2),
indexator.Position(8, 12, 3)],
'test2.txt': [
indexator.Position(7, 11, 1),
indexator.Position(23, 27, 1),
indexator.Position(8, 12, 2)]}
self.assertEqual(self.searchEngine.searchQuery('need'), expected)
# unittests for contexts
def test_context(self):
pos = indexator.Position(20, 22, 1)
context = searchEngine.ContextWindow.makeWindowGreatAgain(2, 'test.txt', pos)
self.assertEqual(context.string, "is, all we need is")
def test_context_line_not_exists(self):
pos = indexator.Position(20, 22, 2)
with self.assertRaises(ValueError):
searchEngine.ContextWindow.makeWindowGreatAgain(2, 'test.txt', pos)
def test_context_large_size(self):
pos = indexator.Position(20, 22, 1)
context = searchEngine.ContextWindow.makeWindowGreatAgain(8, 'test.txt', pos)
self.assertEqual(context.string, "All we need is, all we need is, all we need is")
def test_context_zero_size(self):
pos = indexator.Position(20, 22, 1)
context = searchEngine.ContextWindow.makeWindowGreatAgain(0, 'test.txt', pos)
self.assertEqual(context.string, "we")
def test_context_two_windows(self):
poss = [indexator.Position(20, 22, 1),
indexator.Position(32, 35, 1)]
contexts = [searchEngine.ContextWindow.makeWindowGreatAgain(2, 'test.txt', poss[0]),
searchEngine.ContextWindow.makeWindowGreatAgain(2, 'test.txt', poss[1])]
contextUnion = searchEngine.ContextWindow().unionWindows(contexts)
targetTokensPositions = [indexator.Position(20, 22, 1),
indexator.Position(32, 35, 1)]
expected = searchEngine.ContextWindow.initWithData(
"All we need is, all we need is, all we need is",
targetTokensPositions,
43, 12, "is, all we need is, all we need", "test.txt", 1)
expectedList = []
expectedList.append(expected)
self.assertEqual(contextUnion, expectedList)
def test_context_many_windows(self):
poss = [indexator.Position(20, 22, 1),
indexator.Position(32, 35, 1),
indexator.Position(7, 12, 1),
indexator.Position(20, 22, 1),
indexator.Position(28, 30, 1),
indexator.Position(1, 4, 2)]
contexts = [searchEngine.ContextWindow.makeWindowGreatAgain(2, 'test.txt', poss[0]),
searchEngine.ContextWindow.makeWindowGreatAgain(2, 'test.txt', poss[1]),
searchEngine.ContextWindow.makeWindowGreatAgain(1, 'testtest.txt', poss[2]),
searchEngine.ContextWindow.makeWindowGreatAgain(8, 'testtesttest.txt', poss[3]),
searchEngine.ContextWindow.makeWindowGreatAgain(2, 'testtesttest.txt', poss[4]),
searchEngine.ContextWindow.makeWindowGreatAgain(2, 'testtesttest.txt', poss[5])]
contextUnion = searchEngine.ContextWindow().unionWindows(contexts)
targetTokensPositions1 = [indexator.Position(20, 22, 1),
indexator.Position(32, 35, 1)]
expected1 = searchEngine.ContextWindow.initWithData(
"All we need is, all we need is, all we need is",
targetTokensPositions1,
43, 12, "is, all we need is, all we need", "test.txt", 1)
targetTokensPositions2 = [indexator.Position(7, 12, 1)]
expected2 = searchEngine.ContextWindow.initWithData(
"Blood, blood, blood",
targetTokensPositions2,
19, 0, "Blood, blood, blood", "testtest.txt", 1)
targetTokensPositions3 = [indexator.Position(20, 22, 1),
indexator.Position(28, 30, 1)]
expected3 = searchEngine.ContextWindow.initWithData(
"All we need is, all we need is,\n",
targetTokensPositions3,
30, 0, "All we need is, all we need is", "testtesttest.txt", 1)
targetTokensPositions4 = [indexator.Position(1, 4, 2)]
expected4 = searchEngine.ContextWindow.initWithData(
" all we need is",
targetTokensPositions4,
12, 1, "all we need", "testtesttest.txt", 2)
expectedList = []
expectedList.append(expected1)
expectedList.append(expected2)
expectedList.append(expected3)
expectedList.append(expected4)
self.assertEqual(contextUnion, expectedList)
def test_context_expand_to_sentence(self):
pos = indexator.Position(24, 28, 1)
context = searchEngine.ContextWindow.makeWindowGreatAgain(1, 'testSentence.txt', pos)
context.expandToSentence()
targetTokensPositions = [indexator.Position(24, 28, 1)]
expected = searchEngine.ContextWindow.initWithData(
"What do we need? All we need is blood. Pain pain pain pain",
targetTokensPositions,
38, 17, "All we need is blood.", "testSentence.txt", 1)
self.assertEqual(context, expected)
def test_context_expand_to_sentence_two_tokens(self):
poss = [indexator.Position(21, 23, 1),
indexator.Position(24, 28, 1)]
contexts = [searchEngine.ContextWindow.makeWindowGreatAgain(1, 'testSentence.txt', poss[0]),
searchEngine.ContextWindow.makeWindowGreatAgain(1, 'testSentence.txt', poss[1])]
contextUnion = searchEngine.ContextWindow().unionWindows(contexts)
contextUnion[0].expandToSentence()
context = contextUnion[0]
targetTokensPositions = [indexator.Position(21, 23, 1),
indexator.Position(24, 28, 1)]
expected = searchEngine.ContextWindow.initWithData(
"What do we need? All we need is blood. Pain pain pain pain",
targetTokensPositions,
38, 17, "All we need is blood.", "testSentence.txt", 1)
self.assertEqual(context, expected)
# def test_query_context(self):
# expected = {
# 'test.txt': [
# indexator.Position(4, 6, 1),
# indexator.Position(5, 7, 2),
# indexator.Position(5, 7, 3),
# indexator.Position(12, 14, 1),
# indexator.Position(13, 15, 2),
# indexator.Position(13, 15, 3)],
# 'test2.txt': [
# indexator.Position(4, 6, 1),
# indexator.Position(20, 22, 1),
# indexator.Position(5, 7, 2),
# indexator.Position(12, 14, 1),
# indexator.Position(28, 30, 1),
# indexator.Position(13, 15, 2)]}
# print(searchEngine.ContextWindow.makeWindowGreatAgain(
# 3, 'test0.txt', indexator.Position(12, 14, 1),))
# self.assertEqual(self.searchEngine.searchQueryWindow('blood pain', 3), expected)
def tearDown(self):
self.searchEngine.__del__()
files = os.listdir(path=".")
for file in files:
if file.startswith('TestDatabase'):
os.remove(file)
if file.startswith('test'):
os.remove(file)
if __name__ == '__main__':
unittest.main()
<file_sep>/indexator.py
"""
Module for creating a database of tokens from a text file
"""
import os
import shelve
from tokenizer import Tokenizer
class Position(object):
"""
Class for representation of a token's position
Remembers the beginning, the end and the line of a token
"""
# def __init__ (self, posBegin, posEnd):
# self.posBegin = posBegin
# self.posEnd = posEnd
def __init__ (self, posBegin, posEnd, posLine):
"""
Method for initialization position
@param posBegin: position of a token in the string
@param posEnd: string representation of a token
@param posLine: string representation of a token
"""
self.posBegin = posBegin
self.posEnd = posEnd
self.posLine = posLine
# def __eq__(self, someshit):
# return (self.posBegin == someshit.posBegin
# and self.posEnd == someshit.posEnd)
def __eq__(self, someshit):
"""
Method for comparison of two positions
@param someshit: to what it should compare
@return: True if positions are equel, False otherwise
"""
return (self.posBegin == someshit.posBegin
and self.posEnd == someshit.posEnd
and self.posLine == someshit.posLine)
# def __repr__(self):
# return str(self.posBegin) + ', ' + str(self.posEnd)
def __repr__(self):
"""
Method for representation a position of a token
@return: string representation
"""
return '(' + str(self.posBegin) + ', ' + str(self.posEnd) + ', ' + str(self.posLine) + ')'
class Indexator(object):
"""
Tool for indexizing text files
"""
def __init__(self, filename):
"""
Method for initialization an indexator
@param filename: path of the database to be created
"""
self.database = shelve.open(filename, writeback=True)
def __del__(self):
"""
Method for the end of the work with the database
"""
try:
self.database.close()
except Exception:
return
@staticmethod
def relevancyFilter(tokens):
"""
Method for extraction of tokens of type alpha or digit
@param tokens: collection of ClassifiedTokens
@return: generator of tokens of type alpha or digit
"""
for token in tokens:
if token.category == "alpha" or token.category == "digit":
yield token
def indexize(self, filename):
"""
Method for indexizing a file
Modifies the database of the indexator
@param filename: path to a file that needs indexizing
"""
try:
file = open(filename)
except Exception:
raise ValueError
lineNumber = 1
# file0 = [i for i in file]
# file.close()
for line in file:
# print(lineNumber, '/', len(file0))
tokens = Tokenizer().genclasstokenize(line)
usefulTokens = Indexator.relevancyFilter(tokens)
for token in usefulTokens:
self.database.setdefault(
token.string, {}).setdefault(
filename, []).append(
Position(
token.position,
token.position + len(token.string),
lineNumber))
lineNumber = lineNumber + 1
self.database.sync()
file.close()
return
# @classmethod
# def _coveredRetreat(self):
# files = os.listdir(path=".")
# for file in files:
# if file == 'test.txt':
# os.remove(file)
# if file.startswith('TestDatabase.'):
# os.remove(file)
# if file == 'TestDatabase':
# os.remove(file)
# return
if __name__ == "__main__":
""" Indexator._coveredRetreat()
sIndexator = Indexator("TestDatabase")
filename = open('test.txt', 'w')
filename.write('BRP arena\nis very\nvery easy')
filename.close()
sIndexator.indexize('test.txt')
dbdict = dict(sIndexator.database)
expected = {'BRP': {'test.txt': [Position(0,3,1)]},
'arena': {'test.txt': [Position(4,9,1)]},
'is': {'test.txt': [Position(0,2,2)]},
'easy': {'test.txt': [Position(5,9,3)]},
'very': {'test.txt': [Position(3,7,2)],
'test.txt': [Position(0,4,3)]}}
print(dbdict)
print(expected)
Indexator._coveredRetreat() """
""" sIndexator = Indexator("ViMDatabase")
print('1st:')
sIndexator.indexize('tolstoy1.txt')
print('2nd:')
sIndexator.indexize('tolstoy2.txt')
print('3rd:')
sIndexator.indexize('tolstoy3.txt')
print('4th:')
sIndexator.indexize('tolstoy4.txt')
dbdict = dict(sIndexator.database) """
db = shelve.open('ViMDataBase')
print(db['война'])<file_sep>/tokentest.py
import unittest
from tokenizer import Tokenizer
class Test(unittest.TestCase):
def setUp(self):
self.Tokenizer = Tokenizer()
# unittests for tokenize method
def test_list_type_output(self):
result = self.Tokenizer.tokenize('some string')
self.assertIsInstance(result, list)
def test_list_type_number(self):
with self.assertRaises(ValueError):
self.Tokenizer.tokenize(13)
def test_list_type_notlist(self):
with self.assertRaises(ValueError):
self.Tokenizer.tokenize([15, 'abc', 'stream'])
def test_list_result_empty(self):
result = self.Tokenizer.tokenize('')
self.assertEqual(len(result), 0)
def test_list_result_both_alpha(self):
result = self.Tokenizer.tokenize('test !!!111some ,.,. string')
self.assertEqual(len(result), 3)
self.assertEqual(result[0].string, 'test')
self.assertEqual(result[0].position, 0)
self.assertEqual(result[2].string, 'string')
self.assertEqual(result[2].position, 21)
def test_list_result_both_notalpha(self):
result = self.Tokenizer.tokenize(':)test !!!111some ,.,. string**')
self.assertEqual(len(result), 3)
self.assertEqual(result[0].string, 'test')
self.assertEqual(result[0].position, 2)
self.assertEqual(result[2].string, 'string')
self.assertEqual(result[2].position, 23)
def test_list_result_alpha_nonalpha(self):
result = self.Tokenizer.tokenize('test !!!111some ,.,. string$^)')
self.assertEqual(len(result), 3)
self.assertEqual(result[0].string, 'test')
self.assertEqual(result[0].position, 0)
self.assertEqual(result[2].string, 'string')
self.assertEqual(result[2].position, 21)
def test_list_result_nonalpha_alpha(self):
result = self.Tokenizer.tokenize('{test !!!111some ,.,. string')
self.assertEqual(len(result), 3)
self.assertEqual(result[0].string, 'test')
self.assertEqual(result[0].position, 1)
self.assertEqual(result[2].string, 'string')
self.assertEqual(result[2].position, 22)
# unittests for gentokenize method
def test_gen_type_number(self):
with self.assertRaises(ValueError):
result = self.Tokenizer.gentokenize(13)
next(result)
def test_gen_type_notlist(self):
with self.assertRaises(ValueError):
result = self.Tokenizer.gentokenize([15, 'abc', 'stream'])
next(result)
def test_gen_result_empty(self):
result = self.Tokenizer.gentokenize('')
resultlist = list(result)
self.assertEqual(len(resultlist), 0)
def test_gen_result_both_alpha(self):
result = self.Tokenizer.gentokenize('test !!!111some ,.,. string')
resultlist = list(result)
self.assertEqual(len(resultlist), 3)
self.assertEqual(resultlist[0].string, 'test')
self.assertEqual(resultlist[0].position, 0)
self.assertEqual(resultlist[2].string, 'string')
self.assertEqual(resultlist[2].position, 21)
def test_gen_result_both_notalpha(self):
result = self.Tokenizer.gentokenize(':)test !!!111some ,.,. string**')
resultlist = list(result)
self.assertEqual(len(resultlist), 3)
self.assertEqual(resultlist[0].string, 'test')
self.assertEqual(resultlist[0].position, 2)
self.assertEqual(resultlist[2].string, 'string')
self.assertEqual(resultlist[2].position, 23)
def test_gen_result_alpha_nonalpha(self):
result = self.Tokenizer.gentokenize('test !!!111some ,.,. string$^)')
resultlist = list(result)
self.assertEqual(len(resultlist), 3)
self.assertEqual(resultlist[0].string, 'test')
self.assertEqual(resultlist[0].position, 0)
self.assertEqual(resultlist[2].string, 'string')
self.assertEqual(resultlist[2].position, 21)
def test_gen_result_nonalpha_alpha(self):
result = self.Tokenizer.gentokenize('{test !!!111some ,.,. string')
resultlist = list(result)
self.assertEqual(len(resultlist), 3)
self.assertEqual(resultlist[0].string, 'test')
self.assertEqual(resultlist[0].position, 1)
self.assertEqual(resultlist[2].string, 'string')
self.assertEqual(resultlist[2].position, 22)
# unittests for genclasstokenize method
def test_gen_class_type_number(self):
with self.assertRaises(ValueError):
result = self.Tokenizer.genclasstokenize(13)
next(result)
def test_gen_class_type_notlist(self):
with self.assertRaises(ValueError):
result = self.Tokenizer.genclasstokenize([15, 'abc', 'stream'])
next(result)
def test_gen_class_result_empty(self):
result = self.Tokenizer.genclasstokenize('')
resultlist = list(result)
self.assertEqual(len(resultlist), 0)
def test_gen_class_result_one(self):
result = self.Tokenizer.genclasstokenize('some string')
resultlist = list(result)
self.assertEqual(len(resultlist), 3)
self.assertEqual(resultlist[0].string, 'some')
self.assertEqual(resultlist[0].position, 0)
self.assertEqual(resultlist[0].category, "alpha")
self.assertEqual(resultlist[1].string, ' ')
self.assertEqual(resultlist[1].position, 4)
self.assertEqual(resultlist[1].category, "space")
self.assertEqual(resultlist[2].string, 'string')
self.assertEqual(resultlist[2].position, 5)
self.assertEqual(resultlist[2].category, "alpha")
def test_gen_class_result_two(self):
result = self.Tokenizer.genclasstokenize('!!some bloody string 123**')
resultlist = list(result)
self.assertEqual(len(resultlist), 9)
self.assertEqual(resultlist[0].string, '!!')
self.assertEqual(resultlist[0].position, 0)
self.assertEqual(resultlist[0].category, "punct")
self.assertEqual(resultlist[7].string, '123')
self.assertEqual(resultlist[7].position, 21)
self.assertEqual(resultlist[7].category, "digit")
def test_gen_class_result_three(self):
result = self.Tokenizer.genclasstokenize('test™test* *test')
resultlist = list(result)
self.assertEqual(len(resultlist), 7)
self.assertEqual(resultlist[1].string, '™')
self.assertEqual(resultlist[1].position, 4)
self.assertEqual(resultlist[1].category, "other")
if __name__ == '__main__':
unittest.main()
|
63b592716f3218c5594c9f9ca1a655f610bdc1f1
|
[
"Python"
] | 7 |
Python
|
DemonSnake/MakTokenizer
|
38842a4f09bbcb3e82e2d08feb666837787a055c
|
edee1524d8346b30989570d8c168516db2f72ad1
|
refs/heads/master
|
<repo_name>chenmoryosef/compilers-project-2020-public<file_sep>/src/ast/VtableCreator.java
package ast;
import symbolTable.Symbol;
import symbolTable.SymbolTable;
import symbolTable.Type;
import java.util.*;
public class VtableCreator {
StringBuilder vtables = new StringBuilder();
final static String refPointerString = "i8*";
final static String intString = "i32";
final static String intPointerString = "i32*";
final static String boolString = "i1";
public static Map<SymbolTable, String> getSymbolTableClassesMap() {
return symbolTableClassesMap;
}
private static Map<SymbolTable, String> symbolTableClassesMap;
private static Map<String, ObjectStruct> objectStructMap;
public static Map<String, ObjectStruct> getObjectStructMap() {
return objectStructMap;
}
public String createVtableAndObjectsStruct() {
objectStructMap = new HashMap<>();
inverseMap(symbolTable.SymbolTableUtils.getSymbolTableClassMap_real());
StringBuilder stringBuilder = new StringBuilder();
//for each class in the program
for (Map.Entry<String, SymbolTable> entry : symbolTable.SymbolTableUtils.getSymbolTableClassMap_real().entrySet()) {
int countMethods = 0;
String className = entry.getKey();
SymbolTable symbolTable = entry.getValue();
List<MethodeRow> allClassMethods = new ArrayList<MethodeRow>();
List<Field> allFields = new ArrayList<>();
Set<String> methodsNames = new HashSet<>();
//for each methode in this class
int i = 0;
for (Map.Entry<String, Symbol> symbolTableRow : symbolTable.getEntries().entrySet()) {
Symbol symbol = symbolTableRow.getValue();
if (!symbol.getType().equals(Type.METHOD)) {
Field field = new Field();
extractFieldFields(field, symbol, allFields, i++);
} else {
countMethods++;
MethodeRow methodeRow = new MethodeRow();
extractMethodFields(symbol, methodeRow, allClassMethods, methodsNames);
methodeRow.setClassName(className);
}
}
//look for methods the class inherits
countMethods += findAllmethodsAndFields(symbolTable, allClassMethods, methodsNames, allFields);
addToObjectsStructMap(className, allClassMethods, allFields);
//concatenate the vtable of this class
vtableHeader(countMethods, className, stringBuilder);
vtableContent(allClassMethods, stringBuilder);
}
return stringBuilder.toString();
}
private void extractFieldFields(Field field, Symbol symbol, List<Field> allFields, int i) {
field.setType(convertAstTypeToLLVMRepresention(symbol.getDecl().get(0)));
field.setSize(convertAstTypeToSize(symbol.getDecl().get(0)));
field.setFieldName(symbol.getSymbolName());
allFields.add(i, field);
}
public void addToObjectsStructMap(String className, List<MethodeRow> methodeRowList, List<Field> fieldList) {
ObjectStruct objectStruct = new ObjectStruct();
for (MethodeRow methodeRow : methodeRowList) {
methodeRow.createArgsString();
objectStruct.addMethod(methodeRow.getMethodeName(), methodeRow.getArgs(), methodeRow.getRetType());
}
List<Field> inverseFieldList = fieldList.subList(0, fieldList.size());
// Collections.reverse(inverseFieldList);
for (Field field : inverseFieldList) {
objectStruct.addField(field.getFieldName(), field.getType(), field.getSize());
}
objectStructMap.put(className, objectStruct);
}
public void vtableContent(List<MethodeRow> methodeRowList, StringBuilder stringBuilder) {
int i;
for (i = 0; i < methodeRowList.size() - 1; i++) {
stringBuilder.append(methodeRowList.get(i).toString());
stringBuilder.append(",\n");
}
if (methodeRowList.size() > 0) {
stringBuilder.append(methodeRowList.get(methodeRowList.size() - 1).toString());
}
stringBuilder.append("\n]");
}
public void vtableHeader(int funcsNum, String className, StringBuilder stringBuilder) {
stringBuilder.append("\n@." + className + "_vtable = global [" + funcsNum + " x " + refPointerString + "] [\n");
}
public void extractMethodFields(Symbol symbol, MethodeRow methodeRow, List<MethodeRow> methodsList, Set<String> methodsNames) {
extractArgsTypes(symbol, methodeRow);
extractRetType(symbol, methodeRow);
extractMethodeName(symbol, methodeRow);
methodsList.add(methodeRow);
methodsNames.add(symbol.getSymbolName());
}
public void extractMethodeName(Symbol symbol, MethodeRow methodeRow) {
String methodName = symbol.getSymbolName();
methodeRow.setMethodeName(methodName);
}
public void extractRetType(Symbol symbol, MethodeRow row) {
String ret = symbol.getDecl().get(0);
String retType = convertAstTypeToLLVMRepresention(ret);
row.setRetType(retType);
}
public void extractArgsTypes(Symbol symbol, MethodeRow row) {
List<String> decl = symbol.getDecl();
for (int i = 1; i < decl.size(); i++) {
String arg = decl.get(i);
String argType = convertAstTypeToLLVMRepresention(arg);
row.addToArgsType(argType);
}
}
public static String convertAstTypeToLLVMRepresention(String astType) {
switch (astType) {
case "boolean":
return boolString;
case "int":
return intString;
case "intArray":
return intPointerString;
default:
return refPointerString;
}
}
public int convertAstTypeToSize(String astType) {
switch (astType) {
case "boolean":
return 1;
case "int":
return 4;
default:
return 8;
}
}
public class Field {
private String fieldName;
private String type;
private int size;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public class MethodeRow {
String retType;
List<String> argsType;
String className;
String methodeName;
String args;
public MethodeRow() {
this.argsType = new ArrayList<String>();
}
public String getMethodeName() {
return methodeName;
}
public String getArgs() {
return args;
}
public void createArgsString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("(" + refPointerString);
for (String argType : argsType) {
stringBuilder.append(", " + argType);
}
stringBuilder.append(")");
args = stringBuilder.toString();
}
public String getRetType() {
return retType;
}
public void setRetType(String retType) {
this.retType = retType;
}
public void addToArgsType(String arg) {
argsType.add(arg);
}
public void setClassName(String className) {
this.className = className;
}
public void setMethodeName(String methodeName) {
this.methodeName = methodeName;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(refPointerString + " bitcast (" + retType + "(" + refPointerString);
for (String argType : argsType) {
stringBuilder.append(", " + argType);
}
stringBuilder.append(")* @" + className + "." + methodeName + " to " + refPointerString + ")");
return stringBuilder.toString();
}
}
private void moveToTmpList(List<MethodeRow> methodsList, String methodName, List<MethodeRow> tmpMethodsList) {
int i;
for (i = 0; i < methodsList.size(); i++) {
if (methodsList.get(i).getMethodeName().equals(methodName)) {
break;
}
}
MethodeRow tmp = methodsList.get(i);
methodsList.remove(i);
tmpMethodsList.add(tmp);
}
private void addAllFirst(List<MethodeRow> to, List<MethodeRow> from) {
for (int i = 0; i < from.size(); i++) {
to.add(i, from.get(i));
}
}
public int findAllmethodsAndFields(SymbolTable symbolTable, List<MethodeRow> methodsList, Set<String> methodesNames, List<Field> fieldList) {
SymbolTable parentSymbolTable = symbolTable.getParentSymbolTable();
int countMethodes = 0;
List<MethodeRow> orderedMethodLists = new ArrayList<>(methodsList);
methodsList.clear();
while (parentSymbolTable != null) {
List<MethodeRow> tmp = new ArrayList<>();
int i = 0;
for (Map.Entry<String, Symbol> symbolTableRow : parentSymbolTable.getEntries().entrySet()) {
Symbol symbol = symbolTableRow.getValue();
if (!symbol.getType().equals(Type.METHOD)) {
Field field = new Field();
extractFieldFields(field, symbol, fieldList, i++);
} else {
if (methodesNames.contains(symbol.getSymbolName())) {
moveToTmpList(orderedMethodLists, symbol.getSymbolName(), tmp);
continue;
}
countMethodes++;
MethodeRow methodeRow = new MethodeRow();
extractMethodFields(symbol, methodeRow, tmp, methodesNames);
methodeRow.setClassName(symbolTableClassesMap.get(parentSymbolTable));
}
}
addAllFirst(orderedMethodLists, tmp);
// tmp.addAll(orderedMethodLists);
// orderedMethodLists = tmp;
parentSymbolTable = parentSymbolTable.getParentSymbolTable();
}
methodsList.addAll(orderedMethodLists);
return countMethodes;
}
public void inverseMap(Map<String, SymbolTable> map) {
Map<SymbolTable, String> inverseMap = new HashMap<>();
for (String className : map.keySet()) {
inverseMap.put(map.get(className), className);
}
symbolTableClassesMap = inverseMap;
}
}
<file_sep>/src/ast/Visitor.java
package ast;
public interface Visitor {
public void visit(Program program);
public void visit(ClassDecl classDecl);
public void visit(MainClass mainClass);
public void visit(MethodDecl methodDecl);
public void visit(FormalArg formalArg);
public void visit(VarDecl varDecl);
public void visit(BlockStatement blockStatement);
public void visit(IfStatement ifStatement);
public void visit(WhileStatement whileStatement);
public void visit(SysoutStatement sysoutStatement);
public void visit(AssignStatement assignStatement);
public void visit(AssignArrayStatement assignArrayStatement);
public void visit(AndExpr e);
public void visit(LtExpr e);
public void visit(AddExpr e);
public void visit(SubtractExpr e);
public void visit(MultExpr e);
public void visit(ArrayAccessExpr e);
public void visit(ArrayLengthExpr e);
public void visit(MethodCallExpr e);
public void visit(IntegerLiteralExpr e);
public void visit(TrueExpr e);
public void visit(FalseExpr e);
public void visit(IdentifierExpr e);
public void visit(ThisExpr e);
public void visit(NewIntArrayExpr e);
public void visit(NewObjectExpr e);
public void visit(NotExpr e);
public void visit(IntAstType t);
public void visit(BoolAstType t);
public void visit(IntArrayAstType t);
public void visit(RefType t);
}
<file_sep>/src/symbolTable/SymbolTable.java
package symbolTable;
import ast.AstNode;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class SymbolTable {
private Map<String, Symbol> entries;
private SymbolTable parentSymbolTable;
public SymbolTable(SymbolTable parentSymbolTable) {
this.entries = new LinkedHashMap<>();
this.parentSymbolTable = parentSymbolTable;
}
public Map<String, Symbol> getEntries() {
return entries;
}
public SymbolTable getParentSymbolTable() {
return parentSymbolTable;
}
public static String createKey(String name, String name2) {
return name + " " + name2;
}
public static String createKey(String name, Type type) {
return name + type.getName();
}
public Symbol addSymbol(AstNode astNode, String name, Type type, List<String> decl) {
Symbol symbol = new Symbol(name, type, decl, astNode, this);
this.entries.put(createKey(name, type), symbol);
FlowUtils.addSymbolLineNumber(symbol, astNode.lineNumber);
return symbol;
}
private Symbol getKey(String key) {
return this.entries.get(key);
}
public Symbol resolveSymbol(String key) {
Symbol symbol = entries.get(key);
SymbolTable parentSymbolTable = this.parentSymbolTable;
while ((symbol == null && parentSymbolTable != null) ||
(symbol != null && symbol.getType() == Type.METHOD && !symbol.isRootMethod())) {
symbol = parentSymbolTable.getKey(key);
parentSymbolTable = parentSymbolTable.parentSymbolTable;
}
if (symbol == null) {
// error handling
}
return symbol;
}
public boolean checkFieldWasDeclaredBefore(String key) {
Symbol symbol = entries.get(key);
SymbolTable parentSymbolTable = this.parentSymbolTable;
while (symbol == null && parentSymbolTable != null) {
symbol = parentSymbolTable.getKey(key);
parentSymbolTable = parentSymbolTable.parentSymbolTable;
}
if (symbol != null) {
SymbolTableUtils.setERROR(true);
SymbolTableUtils.setERRORReasons("field was declared at least twice in the same class, or in a class and subclass ");
return true;
}
return false;
}
public boolean checkWasAlreadyDeclared(String key) {
Symbol symbol = entries.get(key);
if (symbol != null) {
SymbolTableUtils.setERROR(true);
SymbolTableUtils.setERRORReasons("methode was declared at least twice in the same class or variable declared twice in same method");
return true;
}
return false;
}
}
<file_sep>/tests/ex3/17ifCond/17ifCond.java
class Main {
public static void main(String[] args) {
System.out.println(1);
}
}
class A {
}
class B extends A {
int theVar;
int foo() {
return theVar;
}
}
class C extends A {
int theVar;
int foo() {
return theVar;
}
}
class D extends C {
int bar(int anotherVar) {
int[] max;
max = new int[(theVar) * (anotherVar)];
if (anotherVar)
max[anotherVar] = theVar;
else
max[theVar] = anotherVar;
return (max)[(theVar) * (anotherVar)];
}
}
<file_sep>/src/symbolTable/Symbol.java
package symbolTable;
import ast.AstNode;
import java.util.ArrayList;
import java.util.List;
class Properties {
private List<AstNode> ptrList;
private List<Symbol> symbolList;
// Maybe more ...
public List<Symbol> getSymbolList() {
return symbolList;
}
public Properties(AstNode astNode) {
this.ptrList = new ArrayList<>();
this.ptrList.add(astNode);
this.symbolList = new ArrayList<>();
}
public List<AstNode> getPtrList() {
return ptrList;
}
public void addAstNode(AstNode astNode) {
this.ptrList.add(astNode);
}
public void addSymbol(Symbol symbol) {
this.symbolList.add(symbol);
}
}
public class Symbol {
private String symbolName;
private Type type;
private List<String> decl;
private Properties properties;
private boolean isRootMethod;
private SymbolTable enclosingSymbolTable;
public Symbol(String varName, Type type, List<String> decl, AstNode astNode, SymbolTable enclosingSymbolTable) {
this.symbolName = varName;
this.type = type;
this.decl = decl;
this.properties = new Properties(astNode);
this.isRootMethod = false;
this.enclosingSymbolTable = enclosingSymbolTable;
}
public SymbolTable getEnclosingSymbolTable() {
return enclosingSymbolTable;
}
public void enableRootMethod() {
this.isRootMethod = true;
}
public boolean isRootMethod() {
return isRootMethod;
}
public String getSymbolName() {
return symbolName;
}
public void setSymbolName(String symbolName) {
this.symbolName = symbolName;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public List<String> getDecl() {
return decl;
}
public Properties getProperties() {
return properties;
}
public void addProperty(AstNode astNode) {
this.properties.addAstNode(astNode);
}
public void addProperty(AstNode astNode, Symbol symbol) {
this.properties.addAstNode(astNode);
this.properties.addSymbol(symbol);
}
}
<file_sep>/src/ast/WhileStatement.java
package ast;
import javax.xml.bind.annotation.XmlElement;
public class WhileStatement extends Statement {
@XmlElement(required = true)
private ExprWrapper cond;
@XmlElement(required = true)
private StatementWrapper body;
// for deserialization only!
public WhileStatement() {
}
public WhileStatement(Expr cond, Statement body) {
this.cond = new ExprWrapper(cond);
this.body = new StatementWrapper(body);
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
public Expr cond() {
return cond.e;
}
public Statement body() {
return body.s;
}
}
<file_sep>/tests/ex3/tester.sh
## assumptions:
# 1. in order to reach the compiled jar you need to run ../../mjavac
# 2. tests folder 'Test' has xml and 'Test.res' file (expected result)
## results:
# if the script & your code are working properly
# you should see the names of all of the tests with "Success"
COMMAND="java -jar ../../mjavac.jar unmarshal semantic"
FILEPATH="."
function test()
{
XMLFILE=$1
TESTFOLDER=$2
echo "Running Test:" $TESTFOLDER
result_file=$TESTFOLDER/$TESTFOLDER.our-result
log_file=$TESTFOLDER/$TESTFOLDER.log
if [ -f $result_file ]; then
rm $TESTFOLDER/$TESTFOLDER.our-result
fi
if [ -f $log_file ]; then
rm $TESTFOLDER/$TESTFOLDER.log
fi
$COMMAND $TESTFOLDER/$XMLFILE.xml $result_file > $log_file
diff $result_file $TESTFOLDER/$TESTFOLDER.res
if [ $? -eq 0 ]
then
echo Success
else
echo Fail
fi
}
#ex3:
test AssignmentInvalid.java AssignmentInvalid
test AssignmentValid.java AssignmentValid
test InitVarInvalid.java InitVarInvalid
test InitVarValid.java InitVarValid
test OwnerExprInvalid.java OwnerExprInvalid
test OwnerExprValid.java OwnerExprValid
test MethodInvalid MethodInvalid
test 1orderOfClassesDecls 1orderOfClassesDecls
test 2mainInheritance 2mainInheritance
test 3classesWithSameName 3classesWithSameName
test 4FieldInheritClassSameName 4FieldInheritClassSameName
test 4FieldWithSameDecl 4FieldWithSameDecl
test 5methodsWithSameName 5methodsWithSameName
test 6declOfOverrodeMethodRetVal 6declOfOverrodeMethodRetVal
test 6declOfOverrideMethodFotmalVal 6declOfOverrideMethodFotmalVal
test 6declOfOverrideMethodSubTypeValid 6declOfOverrideMethodSubTypeValid
test 8declareObjectOfUndeclaredClass 8declareObjectOfUndeclaredClass
test 9Invalid 9Invalid
test 9Valid 9Valid
test 10methodCallOnlyFromObject 10methodCallOnlyFromObject
test 11methodCallStaticType 11methodCallStaticType
test 12OwnerExprInvalid 12OwnerExprInvalid
test 12OwnerExprThisValid 12OwnerExprThisValid
test 13LengthValid 13LengthValid
test 13LengthInvalid 13LengthInvalid
test 13LengthValid2 13LengthValid2
test 14notDefined 14notDefined
test 14definedInDiffClass 14definedInDiffClass
test 15IfInitialized 15IfInitialized
test 16assignmentInvalid 16assignmentInvalid
test 16assignmentValid 16assignmentValid
test 17ifCond 17ifCond
test 17whileCond 17whileCond
test 18returnValueInvalid 18returnValueInvalid
test 18returnValueValid 18returnValueValid
test 20printInt 20printInt
test 21multInvalid 21multInvalid
test 21notInvalid 21notInvalid
test 21addInvalid 21addInvalid
test 22arrayInvalid 22arrayInvalid
test 24varsWithSameName 24varsWithSameName
<file_sep>/src/ast/IntegerLiteralExpr.java
package ast;
import javax.xml.bind.annotation.XmlElement;
public class IntegerLiteralExpr extends Expr {
@XmlElement(required = true)
private int num;
// for deserialization only!
public IntegerLiteralExpr() {
}
public IntegerLiteralExpr(int num) {
this.num = num;
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
public int num() {
return num;
}
}
<file_sep>/src/ast/AstVisitor.java
package ast;
import symbolTable.*;
import java.util.*;
public class AstVisitor implements Visitor {
private String mainClassName;
private Set<String> notReferenceTypes = new HashSet<>(Arrays.asList("int","boolean","intArray"));
private List<String> prepareDecl(List<FormalArg> list, AstType returnType) {
ArrayList<String> decl = new ArrayList<>();
decl.add(returnType.id());
for (var formal : list) {
decl.add(formal.type().id());
}
return decl;
}
@Override
public void visit(Program program) {
SymbolTable root = new SymbolTable(null);
SymbolTableUtils.setRoot(root);
mainClassName = program.mainClass().name();
for (ClassDecl classdecl : program.classDecls()) {
if(SymbolTableUtils.isERROR()){return;}
SymbolTableUtils.setCurrSymTable(root);
SymbolTableUtils.setCurrClassID(classdecl.name());
classdecl.accept(this);
}
program.mainClass().accept(this);
}
@Override
public void visit(ClassDecl classDecl) {
if(classDecl.name().equals(mainClassName)){
SymbolTableUtils.setERROR(true);
SymbolTableUtils.setERRORReasons("class inherits from class that hasn't been defined yet. " +
"or, inherits from class main");
return;
}
SymbolTable parentSymbolTable = SymbolTableUtils.getCurrSymTable();
if (classDecl.superName() != null) {
parentSymbolTable = SymbolTableUtils.getSymbolTable(classDecl.superName());
if(parentSymbolTable==null || classDecl.superName().equals(mainClassName)){
SymbolTableUtils.setERROR(true);
SymbolTableUtils.setERRORReasons("class inherits from class that hasn't been defined yet. " +
"or, inherits from class main");
return;
}
}
SymbolTable classSymbolTable = new SymbolTable(parentSymbolTable);
if(SymbolTableUtils.addClassSymbolTable(classDecl.name(), classSymbolTable)){return;}
SymbolTableUtils.addSymbolTable(classDecl.name(), classSymbolTable);
SymbolTableUtils.addClassMethodSymbolTable(classDecl.name(), classSymbolTable);
for (var fieldDecl : classDecl.fields()) {
String type = fieldDecl.type().id();
if(!notReferenceTypes.contains(type)){
if(!SymbolTableUtils.getSymbolTableClassMap_real().containsKey(type)){
SymbolTableUtils.addUnresolvedClasses(type);
}
}
ArrayList<String> decl = new ArrayList<>();
decl.add(fieldDecl.type().id());
String className = fieldDecl.name();
if(classSymbolTable.checkFieldWasDeclaredBefore(SymbolTable.createKey(className,Type.VARIABLE))){return;}
classSymbolTable.addSymbol(fieldDecl, fieldDecl.name(), Type.VARIABLE, decl);
}
for (var methodDecl : classDecl.methoddecls()) {
if(SymbolTableUtils.isERROR()){return;}
List<String> decl = prepareDecl(methodDecl.formals(), methodDecl.returnType());
if(classSymbolTable.checkWasAlreadyDeclared(SymbolTable.createKey(methodDecl.name(),Type.METHOD))){return;}
Symbol methodSymbol = classSymbolTable.addSymbol(methodDecl, methodDecl.name(), Type.METHOD, decl);
Symbol rootMethodSymbol = SymbolTableUtils.getCurrSymTable().resolveSymbol(SymbolTable.createKey(methodDecl.name(), Type.METHOD));
if (rootMethodSymbol != null) {
rootMethodSymbol.addProperty(methodDecl, methodSymbol);
} else {
methodSymbol.enableRootMethod();
}
SymbolTableUtils.setCurrSymTable(classSymbolTable);
methodDecl.accept(this);
}
}
@Override
public void visit(MainClass mainClass) {
if(SymbolTableUtils.isERROR()){return;}
// This is a new scope -> create new symbol table
SymbolTable symbolTable = new SymbolTable(SymbolTableUtils.getRoot());
SymbolTableUtils.addSymbolTable(mainClass.name(), symbolTable);
// MainClass has argsName parameter only - create symbol
ArrayList<String> decl = new ArrayList<>();
decl.add("String[]");
SymbolTableUtils.getCurrSymTable().addSymbol(mainClass, mainClass.argsName(), Type.VARIABLE, decl);
mainClass.mainStatement().accept(this);
}
@Override
public void visit(MethodDecl methodDecl) {
SymbolTable methodSymbolTable = new SymbolTable(SymbolTableUtils.getCurrSymTable());
SymbolTableUtils.addSymbolTable(methodDecl.name(), methodSymbolTable);
SymbolTableUtils.addClassMethodSymbolTable(methodDecl.name() + SymbolTableUtils.getCurrClassId(), methodSymbolTable);
Set<String> formals = new HashSet<>();
for (var formal : methodDecl.formals()) {
String type = formal.type().id();
if(!notReferenceTypes.contains(type)){
if(!SymbolTableUtils.getSymbolTableClassMap_real().containsKey(type)){
SymbolTableUtils.addUnresolvedClasses(type);
}
}
if(formals.contains(formal.name())){
SymbolTableUtils.setERROR(true);
SymbolTableUtils.setERRORReasons("there are at last two formal params with the same name");
return;
}
else{
formals.add(formal.name());
}
ArrayList<String> decl = new ArrayList<>();
decl.add(formal.type().id());
methodSymbolTable.addSymbol(formal, formal.name(), Type.VARIABLE, decl);
}
for (var varDecl : methodDecl.vardecls()) {
String type = varDecl.type().id();
if(!notReferenceTypes.contains(type)){
if(!SymbolTableUtils.getSymbolTableClassMap_real().containsKey(type)){
SymbolTableUtils.addUnresolvedClasses(type);
}
}
ArrayList<String> decl = new ArrayList<>();
decl.add(varDecl.type().id());
String varName = varDecl.name();
if(methodSymbolTable.checkWasAlreadyDeclared(SymbolTable.createKey(varName,Type.VARIABLE))){return;}
methodSymbolTable.addSymbol(varDecl, varDecl.name(), Type.VARIABLE, decl);
}
for (var stmt : methodDecl.body()) {
if(SymbolTableUtils.isERROR()){return;}
stmt.accept(this);
}
if(SymbolTableUtils.isERROR()){return;}
methodDecl.ret().accept(this);
}
@Override
public void visit(FormalArg formalArg) {
// Note - left empty
}
@Override
public void visit(VarDecl varDecl) {
if(SymbolTableUtils.isERROR()){return;}
varDecl.type().accept(this);
}
@Override
public void visit(BlockStatement blockStatement) {
if(SymbolTableUtils.isERROR()){return;}
SymbolTable blockSymbolTable = new SymbolTable(SymbolTableUtils.getCurrSymTable());
SymbolTableUtils.addSymbolTable(String.valueOf(blockStatement.lineNumber), blockSymbolTable);
for (var s : blockStatement.statements()) {
if(SymbolTableUtils.isERROR()){return;}
s.accept(this);
}
}
@Override
public void visit(IfStatement ifStatement) {
if(SymbolTableUtils.isERROR()){return;}
ifStatement.cond().accept(this);
if(SymbolTableUtils.isERROR()){return;}
ifStatement.thencase().accept(this);
if(SymbolTableUtils.isERROR()){return;}
ifStatement.elsecase().accept(this);
}
@Override
public void visit(WhileStatement whileStatement) {
if(SymbolTableUtils.isERROR()){return;}
whileStatement.cond().accept(this);
if(SymbolTableUtils.isERROR()){return;}
whileStatement.body().accept(this);
}
@Override
public void visit(SysoutStatement sysoutStatement) {
if(SymbolTableUtils.isERROR()){return;}
sysoutStatement.arg().accept(this);
}
@Override
public void visit(AssignStatement assignStatement) {
if(SymbolTableUtils.isERROR()){return;}
Symbol rootSymbol = SymbolTableUtils.getCurrSymTable().resolveSymbol(SymbolTable.createKey(assignStatement.lv(), Type.VARIABLE));
if (rootSymbol != null) {
rootSymbol.addProperty(assignStatement);
} else {
SymbolTableUtils.setERROR(true);
SymbolTableUtils.setERRORReasons("reference to object that has not been declared before");
return;
}
assignStatement.rv().accept(this);
}
@Override
public void visit(AssignArrayStatement assignArrayStatement) {
if(SymbolTableUtils.isERROR()){return;}
Symbol rootSymbol = SymbolTableUtils.getCurrSymTable().resolveSymbol(SymbolTable.createKey(assignArrayStatement.lv(), Type.VARIABLE));
if (rootSymbol != null) {
rootSymbol.addProperty(assignArrayStatement);
} else {
SymbolTableUtils.setERROR(true);
SymbolTableUtils.setERRORReasons("reference to object that has not been declared before");
return;
}
assignArrayStatement.index().accept(this);
if(SymbolTableUtils.isERROR()){return;}
assignArrayStatement.rv().accept(this);
}
@Override
public void visit(AndExpr e) {
if(SymbolTableUtils.isERROR()){return;}
e.e1().accept(this);
if(SymbolTableUtils.isERROR()){return;}
e.e2().accept(this);
}
@Override
public void visit(LtExpr e) {
if(SymbolTableUtils.isERROR()){return;}
e.e1().accept(this);
if(SymbolTableUtils.isERROR()){return;}
e.e2().accept(this);
}
@Override
public void visit(AddExpr e) {
if(SymbolTableUtils.isERROR()){return;}
e.e1().accept(this);
if(SymbolTableUtils.isERROR()){return;}
e.e2().accept(this);
}
@Override
public void visit(SubtractExpr e) {
if(SymbolTableUtils.isERROR()){return;}
e.e1().accept(this);
if(SymbolTableUtils.isERROR()){return;}
e.e2().accept(this);
}
@Override
public void visit(MultExpr e) {
if(SymbolTableUtils.isERROR()){return;}
e.e1().accept(this);
if(SymbolTableUtils.isERROR()){return;}
e.e2().accept(this);
}
@Override
public void visit(ArrayAccessExpr e) {
if(SymbolTableUtils.isERROR()){return;}
e.arrayExpr().accept(this);
if(SymbolTableUtils.isERROR()){return;}
e.indexExpr().accept(this);
}
@Override
public void visit(ArrayLengthExpr e) {
if(SymbolTableUtils.isERROR()){return;}
e.arrayExpr().accept(this);
}
@Override
public void visit(MethodCallExpr e) {
if(SymbolTableUtils.isERROR()){return;}
AstNode ownerExp = e.ownerExpr();
Symbol symbol;
String symbolKey = SymbolTable.createKey(e.methodId(), Type.METHOD);
String classId;
SymbolTable symbolTable;
for (Expr arg : e.actuals()) {
arg.accept(this);
}
if (ownerExp instanceof ThisExpr) {
classId = SymbolTableUtils.getCurrClassId();
symbolTable = SymbolTableUtils.getCurrSymTable();
} else if (ownerExp instanceof NewObjectExpr) {
classId = ((NewObjectExpr) ownerExp).classId();
symbolTable = SymbolTableUtils.getSymbolTable(classId);
} else if (ownerExp instanceof IdentifierExpr){
Symbol ownerSymbol = SymbolTableUtils.getCurrSymTable().resolveSymbol(SymbolTable.createKey(((IdentifierExpr) ownerExp).id(), Type.VARIABLE));
if(ownerSymbol == null) {
SymbolTableUtils.setERROR(true);
SymbolTableUtils.setERRORReasons("method call should be invoked with existing variable");
return;
}
classId = ownerSymbol.getDecl().get(0);
if(notReferenceTypes.contains(classId)){
SymbolTableUtils.setERROR(true);
SymbolTableUtils.setERRORReasons("method call should be invoked with this, new or variable");
return;
}
else {
symbolTable = SymbolTableUtils.getSymbolTable(classId);
}
}
else{
SymbolTableUtils.setERROR(true);
SymbolTableUtils.setERRORReasons("method call should be invoked with this, new or variable");
return;
}
if (symbolTable == null) {
if (classId != null) {
SymbolTableUtils.addUnresolvedParam(classId, e.methodId(), e);
return;
}
// handle error why the hell should we get here-
return;
}
symbol = symbolTable.resolveSymbol(symbolKey);
if(symbol == null) {
SymbolTableUtils.addUnresolvedParam(classId, e.methodId(), e);
return;
}
symbol.addProperty(e);
}
@Override
public void visit(IntegerLiteralExpr e) {
}
@Override
public void visit(TrueExpr e) {
}
@Override
public void visit(FalseExpr e) {
}
@Override
public void visit(IdentifierExpr e) {
if(SymbolTableUtils.isERROR()){return;}
Symbol symbol = SymbolTableUtils.getCurrSymTable().resolveSymbol(SymbolTable.createKey(e.id(), Type.VARIABLE));
if(symbol==null){
SymbolTableUtils.setERROR(true);
SymbolTableUtils.setERRORReasons("reference to object that has not been declared before");
return;
}
symbol.addProperty(e);
}
public void visit(ThisExpr e) {
}
@Override
public void visit(NewIntArrayExpr e) {
if(SymbolTableUtils.isERROR()){return;}
e.lengthExpr().accept(this);
}
@Override
public void visit(NewObjectExpr e) {
if(!SymbolTableUtils.getSymbolTableClassMap_real().containsKey(e.classId())){
SymbolTableUtils.addUnresolvedClasses(e.classId());
}
}
@Override
public void visit(NotExpr e) {
if(SymbolTableUtils.isERROR()){return;}
e.e().accept(this);
}
@Override
public void visit(IntAstType t) {
}
@Override
public void visit(BoolAstType t) {
}
@Override
public void visit(IntArrayAstType t) {
}
@Override
public void visit(RefType t) {
Symbol symbol = SymbolTableUtils.getCurrSymTable().resolveSymbol(SymbolTable.createKey(t.id(), Type.VARIABLE));
if (symbol == null) {
SymbolTableUtils.setERROR(true);
SymbolTableUtils.setERRORReasons("reference to object that has not been declared before");
return;
}
symbol.addProperty(t);
}
}
<file_sep>/src/ast/BoolAstType.java
package ast;
public class BoolAstType extends AstType {
final String id = "boolean";
public String id() {
return id;
}
public BoolAstType() {
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
}
<file_sep>/src/ast/FormalArg.java
package ast;
public class FormalArg extends VariableIntroduction {
// for deserialization only!
public FormalArg() {
}
public FormalArg(AstType type, String name, Integer lineNumber) {
// lineNumber = null means it won't be marshaled to the XML
super(type, name, lineNumber);
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
}
<file_sep>/tests/ex4/Invalid/InvalidLexing.java
class Main {
public static void main(String[] a) {
System.out.println(3);
}
}
class Tree {
Tree left;
// Tree right;
public Tree getLeft() {
return left;
}
public int fun() {
int x;
x = 1;
/* x = 0;
return x;
}
}<file_sep>/src/ast/FalseExpr.java
package ast;
public class FalseExpr extends Expr {
public FalseExpr() {
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
}
<file_sep>/build.xml
<project name="MiniJava" default="dist" basedir=".">
<!-- set global properties for this build -->
<property name="src" location="${basedir}/src"/>
<property name="cup" location="${src}/cup"/>
<property name="jflex" location="${src}/jflex"/>
<property name="build" location="${basedir}/build"/>
<property name="tools" location="${basedir}/tools"/>
<taskdef name="jflex" classname="jflex.anttask.JFlexTask" classpath="${tools}/JFlex.jar" />
<taskdef name="cup" classname="java_cup.anttask.CUPTask" classpath="${tools}/java-cup-11b.jar" />
<target name="init">
<!-- Create the time stamp -->
<tstamp/>
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}"/>
</target>
<target name="generate">
<jflex file="${jflex}/Scanner.jflex" destdir="${src}" />
<cup srcfile="${cup}/Parser.cup" destdir="${src}"
parser="Parser" interface="true" locations="false" />
</target>
<target name="compile" depends="init,generate"
description="compile the source">
<!-- Compile the Java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${build}" debug="true">
<classpath>
<fileset dir="${tools}" includes="*.jar"/>
</classpath>
</javac>
</target>
<target name="dist" depends="compile"
description="generate the distribution">
<jar jarfile="mjavac.jar" basedir="${build}">
<manifest>
<attribute name="Main-Class" value="Main"/>
<attribute name="Class-Path" value="${tools}/java-cup-11b-runtime.jar ${tools}/java-cup-11b.jar ${tools}/jakarta.xml.bind-api-2.3.3.jar ${tools}/jaxb-impl-2.3.3.jar ${tools}/jakarta.activation-api-1.2.2.jar ${tools}/jaxb-jxc-2.3.3.jar"/>
</manifest>
</jar>
</target>
<target name="clean"
description="clean up">
<delete file="mjavac.jar"/>
<delete dir="${build}"/>
<delete file="${src}/Lexer.java"/>
<delete file="${src}/Parser.java"/>
<delete file="${src}/sym.java"/>
</target>
</project>
<file_sep>/src/ast/SysoutStatement.java
package ast;
import javax.xml.bind.annotation.XmlElement;
public class SysoutStatement extends Statement {
@XmlElement(required = true)
private ExprWrapper arg;
// for deserialization only!
public SysoutStatement() {
}
public SysoutStatement(Expr arg) {
this.arg = new ExprWrapper(arg);
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
public Expr arg() {
return arg.e;
}
}
<file_sep>/src/ast/ArrayLengthExpr.java
package ast;
import javax.xml.bind.annotation.XmlElement;
public class ArrayLengthExpr extends Expr {
@XmlElement(required = true)
private ExprWrapper arrayExpr;
// for deserialization only!
public ArrayLengthExpr() {
}
public ArrayLengthExpr(Expr arrayExpr) {
this.arrayExpr = new ExprWrapper(arrayExpr);
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
public Expr arrayExpr() {
return arrayExpr.e;
}
}
<file_sep>/src/ast/AssignArrayStatement.java
package ast;
import javax.xml.bind.annotation.XmlElement;
public class AssignArrayStatement extends Statement {
@XmlElement(required = true)
private String lv;
@XmlElement(required = true)
private ExprWrapper index;
@XmlElement(required = true)
private ExprWrapper rv;
// for deserialization only!
public AssignArrayStatement() {
}
public AssignArrayStatement(String lv, Expr index, Expr rv) {
this.lv = lv;
this.index = new ExprWrapper(index);
this.rv = new ExprWrapper(rv);
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
public String lv() {
return lv;
}
public void setLv(String lv) {
this.lv = lv;
}
public Expr index() {
return index.e;
}
public Expr rv() {
return rv.e;
}
}
<file_sep>/tests/ex3-omer/arrays/arraysInvalidLengthNotOnArray.java
class Main {
public static void main(String[] args) {
System.out.println(1);
}
}
class A { }
class B extends A {
int notAnArray;
public int foo() {
return notAnArray.length;
}
}
<file_sep>/src/ast/AssignStatement.java
package ast;
import javax.xml.bind.annotation.XmlElement;
public class AssignStatement extends Statement {
@XmlElement(required = true)
private String lv;
@XmlElement(required = true)
private ExprWrapper rv;
// for deserialization only!
public AssignStatement() {
}
public AssignStatement(String lv, Expr rv) {
this.lv = lv;
this.rv = new ExprWrapper(rv);
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
public String lv() {
return lv;
}
public void setLv(String lv) {
this.lv = lv;
}
public Expr rv() {
return rv.e;
}
}
<file_sep>/src/ast/MethodCallExpr.java
package ast;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import java.util.List;
import java.util.stream.Collectors;
public class MethodCallExpr extends Expr {
@XmlElement(required = true)
private ExprWrapper ownerExpr;
@XmlElement(required = true)
private String methodId;
@XmlElementWrapper(name = "actuals", required = true)
@XmlElement(name = "actual")
private List<ExprWrapper> actuals;
// for deserialization only!
public MethodCallExpr() {
}
public MethodCallExpr(Expr ownerExpr, String methodId, List<Expr> actuals) {
this.ownerExpr = new ExprWrapper(ownerExpr);
this.methodId = methodId;
this.actuals = actuals.stream().map(e -> new ExprWrapper(e)).collect(Collectors.toList());
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
public Expr ownerExpr() {
return ownerExpr.e;
}
public String methodId() {
return methodId;
}
public void setMethodId(String methodId) {
this.methodId = methodId;
}
public List<Expr> actuals() {
return actuals.stream().map(e -> e.e).collect(Collectors.toList());
}
}
<file_sep>/tests/ex3-omer/cyclicInheritance/inheritanceInvalidCyclic.java
class Main {
public static void main(String[] args) {
System.out.println(new Example().run());
}
}
class Example {
int x;
public int run() {
x = 0;
return x + x;
}
public int other() {
int x;
x = 1;
return x - 1;
}
}
class B extends D{
public void test() {
x = 4;
return x+x;
}
}
class C extends B{
public void C_Test() {
x = 7;
return x+x;
}
}
class D extends B{
public void D_Test() {
x = 23;
return x+x;
}
}
class E {
int x;
public void E_Test() {
x = 7;
return x+x;
}
}
<file_sep>/tests/ex3-omer/arrays/arraysValid.java
class Main {
public static void main(String[] args) {
System.out.println(1);
}
}
class A { }
class B extends A {
int[] theVar;
public int foo() {
return theVar.length;
}
}
class C extends A {
int[] theVar;
public int foo() {
theVar = new int[3];
theVar[0] = 5;
theVar[1+0] = 2+2;
return theVar[0];
}
}
class D extends C {
public int bar(int anotherVar) {
System.out.println(theVar[theVar.length] - anotherVar);
return theVar.length - anotherVar;
}
}
<file_sep>/examples/ex1/method.java
class Main {
public static void main(String[] args) {
System.out.println(new Example().run());
}
}
class Example {
public int run() {
Example e;
e = new Example();
return e.run();
}
}
class NonExample {
public int run() {
return new NonExample().run();
}
}<file_sep>/src/ast/VariableIntroduction.java
package ast;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
@XmlSeeAlso({VarDecl.class, FormalArg.class})
public abstract class VariableIntroduction extends AstNode {
@XmlElement(required = true)
private AstTypeWrapper type;
@XmlElement(required = true)
private String name;
// for deserialization only!
public VariableIntroduction() {
}
public VariableIntroduction(AstType type, String name, int lineNumber) {
super(lineNumber);
this.type = new AstTypeWrapper(type);
this.name = name;
}
public AstType type() {
return type.t;
}
public String name() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<file_sep>/src/ast/AstLlvmPrintVisitor.java
package ast;
import symbolTable.Symbol;
import symbolTable.SymbolTable;
import symbolTable.SymbolTableUtils;
import java.util.Map;
public class AstLlvmPrintVisitor implements Visitor {
private StringBuilder builder = new StringBuilder();
private int ifCnt = 0;
private int regCnt = 0;
private String regType;
private String currentClass;
private String currentMethod;
private String currentRegisterToAssign;
private String currentRegisterToStoreTo;
private String currentCallocRegister;
private String printIsOutOfBoundary(AstNode astNode, int labelLegal, int labelIllegal, int lengthRegister, String indexRegister) {
// %_8 = icmp sle i32 %_7, 0
// handle %refId.name separately and int-literal
AstNode exp = null;
if (astNode instanceof ArrayAccessExpr) {
exp = ((ArrayAccessExpr) astNode).indexExpr();
} else if (astNode instanceof AssignArrayStatement) {
exp = ((AssignArrayStatement) astNode).index();
} else {
System.out.println("Errorrrr");
}
String index;
if (exp instanceof IntegerLiteralExpr) {
index = "" + ((IntegerLiteralExpr) exp).num();
} else if (exp instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) exp).id(), currentMethod, true);
index = "%_" + getLastRegisterCount();
} else {
// exp.accept(this);
index = indexRegister;
}
int resultRegister = invokeRegisterCount("i1");
builder.append("%_");
builder.append(resultRegister);
builder.append(" = icmp sle i32 %_");
builder.append(lengthRegister);
builder.append(", ");
builder.append(index);
builder.append("\n");
// br i1 %_0, label %arr_alloc0, label %arr_alloc1
builder.append("br i1 %_");
builder.append(resultRegister);
builder.append(", label %if");
builder.append(labelIllegal);
builder.append(", label %if");
builder.append(labelLegal);
builder.append("\n");
builder.append("if");
builder.append(labelIllegal);
builder.append(":\n");
builder.append("call void @throw_oob()\n");
builder.append("br label %if");
builder.append(labelLegal);
builder.append("\n");
return index;
}
private String printIsNegativeNumberLlvm(AstNode astNode, int labelLegal, int labelIllegal) {
// handle %refId.name separately and int-literal
AstNode exp = null;
if (astNode instanceof NewIntArrayExpr) {
exp = ((NewIntArrayExpr) astNode).lengthExpr();
} else if (astNode instanceof ArrayAccessExpr) {
exp = ((ArrayAccessExpr) astNode).indexExpr();
} else if (astNode instanceof AssignArrayStatement) {
exp = ((AssignArrayStatement) astNode).index();
} else {
System.out.println("Errorrrr");
}
String lengthValue;
if (exp instanceof IntegerLiteralExpr) {
lengthValue = "" + ((IntegerLiteralExpr) exp).num();
} else if (exp instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) exp).id(), currentMethod, true);
lengthValue = "%_" + getLastRegisterCount();
} else {
exp.accept(this);
lengthValue = "%_" + getLastRegisterCount();
}
// %_0 = icmp slt i32 %_2, 0
int resultRegister = invokeRegisterCount("i1");
builder.append("%_");
builder.append(resultRegister);
builder.append(" = icmp slt i32 ");
builder.append(lengthValue);
builder.append(", 0\n");
// br i1 %_0, label %arr_alloc0, label %arr_alloc1
builder.append("br i1 %_");
builder.append(resultRegister);
builder.append(", label %if");
builder.append(labelIllegal);
builder.append(", label %if");
builder.append(labelLegal);
builder.append("\n");
builder.append("if");
builder.append(labelIllegal);
builder.append(":\n");
builder.append("call void @throw_oob()\n");
builder.append("br label %if");
builder.append(labelLegal);
builder.append("\n");
return lengthValue;
}
private String resolveMethodCallVariable(String variableName) {
SymbolTable currentSymbolTable = SymbolTableUtils.getSymbolTableClassWithMethodMap().get(currentMethod + currentClass);
return commonResolveVariable(currentSymbolTable, variableName, true, true);
}
private String commonResolveVariable(SymbolTable currentSymbolTable, String variableName, boolean methodFlag, boolean doLoad) {
String type;
type = isVariableInSymbolTable(variableName, currentSymbolTable);
boolean isField = type == null;
String classId = "";
SymbolTable symbolTable = null;
if (isField) {
SymbolTable parentSymbolTable = currentSymbolTable.getParentSymbolTable();
SymbolTable realParentSymbolTable = currentSymbolTable.getParentSymbolTable();
boolean foundField = false;
while (parentSymbolTable != null && !foundField) {
type = isVariableInSymbolTable(variableName, parentSymbolTable);
foundField = type != null;
symbolTable = parentSymbolTable;
parentSymbolTable = parentSymbolTable.getParentSymbolTable();
}
if (foundField) {
if (methodFlag) {
classId = VtableCreator.getSymbolTableClassesMap().get(symbolTable);
} else {
classId = VtableCreator.getSymbolTableClassesMap().get(realParentSymbolTable);
}
} else {
System.out.println("ERRORRRRRRRR");
}
retrieveField(classId, variableName, doLoad);
if (methodFlag) {
classId = type;
}
} else {
// %_3 = load i32, i32* %e.id()
classId = type;
currentRegisterToStoreTo = "%" + variableName;
type = VtableCreator.convertAstTypeToLLVMRepresention(type);
regType = type;
if (doLoad) {
int register = invokeRegisterCount(type);
builder.append("%_");
builder.append(register);
builder.append(" = load ");
builder.append(type);
builder.append(", ");
builder.append(type);
builder.append("* %");
builder.append(variableName);
builder.append("\n");
currentRegisterToAssign = "%_" + register;
}
}
return classId;
}
private String resolveVariable(String variableName, String methodName, boolean doLoad) {
SymbolTable currentSymbolTable = SymbolTableUtils.getSymbolTableClassWithMethodMap().get(methodName + currentClass);
commonResolveVariable(currentSymbolTable, variableName, false, doLoad);
return currentRegisterToAssign;
}
private String isVariableInSymbolTable(String variableName, SymbolTable currentSymbolTable) {
for (Map.Entry<String, Symbol> entry : currentSymbolTable.getEntries().entrySet()) {
if (entry.getValue().getSymbolName().equals(variableName)) {
return entry.getValue().getDecl().get(0);
}
}
return null;
}
private void retrieveField(String classId, String fieldName, boolean doLoad) {
FieldInfo fieldInfo = VtableCreator.getObjectStructMap().get(classId).getFieldInfoMap().get(fieldName);
int offset = fieldInfo.getOffset();
String type = fieldInfo.getFieldType();
// %_3 = getelementptr i8, i8* %this, i32 8
int registerImplement = invokeRegisterCount("i8");
builder.append("%_");
builder.append(registerImplement);
builder.append(" = getelementptr i8, i8* %this, i32 ");
builder.append(offset);
builder.append("\n");
// %_4 = bitcast i8* %_3 to i32*
int bitcastRegister = invokeRegisterCount("i8*");
builder.append("%_");
builder.append(bitcastRegister);
builder.append(" = bitcast i8* %_");
builder.append(registerImplement);
builder.append(" to ");
builder.append(type);
builder.append("*\n");
currentRegisterToStoreTo = "%_" + bitcastRegister;
if (doLoad) {
// %_5 = load i32, i32* %_4
int loadRegister = invokeRegisterCount(type);
builder.append("%_");
builder.append(loadRegister);
builder.append(" = load ");
builder.append(type);
builder.append(", ");
builder.append(type);
builder.append("* %_");
builder.append(bitcastRegister);
builder.append("\n");
regType = type;
currentRegisterToAssign = "%_" + loadRegister;
}
}
private String astNodeToLlvmType(AstNode node) {
if (node instanceof IntAstType ||
node instanceof SubtractExpr ||
node instanceof AddExpr ||
node instanceof MultExpr || node instanceof IntegerLiteralExpr) {
return "i32";
} else if (node instanceof BoolAstType || node instanceof AndExpr || node instanceof LtExpr) {
return "i1";
} else if (node instanceof IntArrayAstType) {
return "i32*";
} else if (node instanceof RefType) {
return "i8*";
} else {
return "void";
}
}
// functions to keep trace of registers and ifs counts
private int invokeRegisterCount(String type) {
regType = type;
return regCnt++;
}
private int invokeIfRegisterCount() {
return ifCnt++;
}
private int getLastRegisterCount() {
return regCnt - 1;
}
private String getLastRegisterType() {
return regType;
}
private int getLastIfRegisterCount() {
return ifCnt - 1;
}
private void resetRegisterCount() {
regCnt = 0;
}
private void resetIfRegisterCount() {
ifCnt = 0;
}
public String getString() {
return builder.toString();
}
private void visitBinaryExpr(BinaryExpr e, String infixSymbol) {
String firstArg, secondArg;
e.e1().accept(this);
if (e.e1() instanceof IntegerLiteralExpr) {
firstArg = "i32 " + ((IntegerLiteralExpr) e.e1()).num();
} else if (e.e1() instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) e.e1()).id(), currentMethod, true);
firstArg = "i32 %_" + getLastRegisterCount();
} else {
firstArg = "i32 %_" + getLastRegisterCount();
}
e.e2().accept(this);
if (e.e2() instanceof IntegerLiteralExpr) {
secondArg = "" + ((IntegerLiteralExpr) e.e2()).num();
} else if (e.e2() instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) e.e2()).id(), currentMethod, true);
secondArg = "%_" + getLastRegisterCount();
} else {
secondArg = "%_" + getLastRegisterCount();
}
int resultRegister = invokeRegisterCount("i32");
// %_2 = add i32 %_1, 7
builder.append("%_");
builder.append(resultRegister);
builder.append(" = ");
builder.append(infixSymbol);
builder.append(" ");
builder.append(firstArg);
builder.append(", ");
builder.append(secondArg);
builder.append("\n");
}
String verbatim = "declare i8* @calloc(i32, i32)\n" +
"declare i32 @printf(i8*, ...)\n" +
"declare void @exit(i32)\n" +
"\n" +
"@_cint = constant [4 x i8] c\"%d\\0a\\00\"\n" +
"@_cOOB = constant [15 x i8] c\"Out of bounds\\0a\\00\"\n" +
"define void @print_int(i32 %i) {\n" +
"\t%_str = bitcast [4 x i8]* @_cint to i8*\n" +
"\tcall i32 (i8*, ...) @printf(i8* %_str, i32 %i)\n" +
"\tret void\n" +
"}\n" +
"\n" +
"define void @throw_oob() {\n" +
"\t%_str = bitcast [15 x i8]* @_cOOB to i8*\n" +
"\tcall i32 (i8*, ...) @printf(i8* %_str)\n" +
"\tcall void @exit(i32 1)\n" +
"\tret void\n" +
"}\n\n";
@Override
public void visit(Program program) {
// concat mandatory string (@throw_oob, print_int)
builder.append(verbatim);
program.mainClass().accept(this);
for (ClassDecl classdecl : program.classDecls()) {
classdecl.accept(this);
}
}
@Override
public void visit(ClassDecl classDecl) {
currentClass = classDecl.name();
for (var methodDecl : classDecl.methoddecls()) {
currentMethod = methodDecl.name();
methodDecl.accept(this);
builder.append("\n");
}
}
@Override
public void visit(MainClass mainClass) {
// define i32 @main() {
builder.append("define i32 @main() {\n");
// main statements
mainClass.mainStatement().accept(this);
builder.append("ret i32 0\n");
builder.append("}\n\n");
resetIfRegisterCount();
resetRegisterCount();
}
@Override
public void visit(MethodDecl methodDecl) {
MethodInfo methodInfo = VtableCreator.getObjectStructMap().get(currentClass).getMethodeInfoMap().get(currentMethod);
String returntype = methodInfo.getRet();
String formaltype;
String delim = ", ";
// define i32 @Base.set(i8* %this, i32 %.x) {
builder.append("define ");
builder.append(returntype);
builder.append(" @");
builder.append(currentClass);
builder.append(".");
builder.append(methodDecl.name());
builder.append("(i8* %this");
for (FormalArg formal : methodDecl.formals()) {
builder.append(delim);
formaltype = astNodeToLlvmType(formal.type());
builder.append(formaltype);
builder.append(" %.");
builder.append(formal.name());
}
builder.append(") {");
builder.append("\n");
// alloca every formal variable
for (FormalArg formal : methodDecl.formals()) {
formal.accept(this);
}
// alloca every local variable
for (var varDecl : methodDecl.vardecls()) {
varDecl.accept(this);
}
// write method statements
for (var stmt : methodDecl.body()) {
stmt.accept(this);
}
// compute return value
methodDecl.ret().accept(this);
// return value can be:
// ret i1 1
// ret i32 %_3
StringBuilder tmpBuilder = new StringBuilder();
if (methodDecl.ret() instanceof IntegerLiteralExpr) {
tmpBuilder.append(" ");
tmpBuilder.append(((IntegerLiteralExpr) methodDecl.ret()).num());
} else if (methodDecl.ret() instanceof TrueExpr) {
tmpBuilder.append(" 1");
} else if (methodDecl.ret() instanceof FalseExpr) {
tmpBuilder.append(" 0");
} else if (methodDecl.ret() instanceof IdentifierExpr) {
// Resolve Variable Type
// Load that variable into register
this.resolveVariable(((IdentifierExpr) methodDecl.ret()).id(), this.currentMethod, true);
tmpBuilder.append(currentRegisterToAssign);
} else if (methodDecl.ret() instanceof ThisExpr) {
tmpBuilder.append(" %this");
} else if (methodDecl.ret() instanceof NewIntArrayExpr || methodDecl.ret() instanceof NewObjectExpr) {
tmpBuilder.append(currentCallocRegister);
} else {
tmpBuilder.append(" %_");
tmpBuilder.append(getLastRegisterCount());
}
builder.append("ret ");
builder.append(returntype);
builder.append(" ");
builder.append(tmpBuilder);
builder.append("\n}\n");
// Reset ifCnt and regCnt
resetIfRegisterCount();
resetRegisterCount();
}
@Override
public void visit(FormalArg formalArg) {
// %formalArg.name = alloca formalArg.type()
String type = astNodeToLlvmType(formalArg.type());
// %x = alloca i32
builder.append("%");
builder.append(formalArg.name());
builder.append(" = ");
builder.append("alloca ");
builder.append(type);
builder.append("\n");
// store i32 %.x, i32* %x
builder.append("store ");
builder.append(type);
builder.append(" %.");
builder.append(formalArg.name());
builder.append(", ");
builder.append(type);
builder.append("* %");
builder.append(formalArg.name());
builder.append("\n");
}
@Override
public void visit(VarDecl varDecl) {
// %varDecl.name = alloca varDecl.type()
builder.append("%");
builder.append(varDecl.name());
builder.append(" = ");
builder.append("alloca ");
builder.append(astNodeToLlvmType(varDecl.type()));
builder.append("\n");
}
@Override
public void visit(BlockStatement blockStatement) {
for (var statement : blockStatement.statements()) {
statement.accept(this);
}
}
@Override
public void visit(IfStatement ifStatement) {
int trueLabel = invokeIfRegisterCount();
int falseLabel = invokeIfRegisterCount();
// handle True and False Expr
ifStatement.cond().accept(this);
if (ifStatement.cond() instanceof TrueExpr) {
// br label %if1
builder.append("br label %if");
builder.append(trueLabel);
} else if (ifStatement.cond() instanceof FalseExpr) {
// br label %if2
builder.append("br label %if");
builder.append(falseLabel);
} else {
if (ifStatement.cond() instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) ifStatement.cond()).id(), currentMethod, true);
}
// cond accept writes the bool result to the last register
// br i1 %_1, label %if0, label %if1
builder.append("br ");
builder.append("i1 ");
builder.append("%_");
builder.append(getLastRegisterCount());
builder.append(", label %if");
builder.append(trueLabel);
builder.append(", label %if");
builder.append(falseLabel);
}
builder.append("\n");
// if0:
builder.append("if");
builder.append(trueLabel);
builder.append(":\n");
// then statements
ifStatement.thencase().accept(this);
// br label %if2
builder.append("br label ");
int thirdLabel = invokeIfRegisterCount();
builder.append("%if");
builder.append(thirdLabel);
builder.append("\n");
// if1:
builder.append("if");
builder.append(falseLabel);
builder.append(":\n");
// else statement
ifStatement.elsecase().accept(this);
// br label %if2
builder.append("br label ");
builder.append("%if");
builder.append(thirdLabel);
builder.append("\n");
// if2:
builder.append("if");
builder.append(thirdLabel);
builder.append(":\n");
}
private void handleWhileCond(int whileLabel, int outLabel, WhileStatement whileStatement) {
if (whileStatement.cond() instanceof TrueExpr) {
// br label %if1
builder.append("br label %if");
builder.append(whileLabel);
} else if (whileStatement.cond() instanceof FalseExpr) {
// br label %if2
builder.append("br label %if");
builder.append(outLabel);
} else {
// compute cond
if (whileStatement.cond() instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) whileStatement.cond()).id(), currentMethod, true);
} else {
whileStatement.cond().accept(this);
}
// br i1 %_1, label %if1, label %if2
builder.append("br i1 %_");
builder.append(getLastRegisterCount());
builder.append(", label %if");
builder.append(whileLabel);
builder.append(", label %if");
builder.append(outLabel);
}
builder.append("\n");
}
@Override
public void visit(WhileStatement whileStatement) {
// create while and out labels
int condLabel = invokeIfRegisterCount();
int whileLabel = invokeIfRegisterCount();
int outLabel = invokeIfRegisterCount();
// br label %condLabel
builder.append("br label %if");
builder.append(condLabel);
builder.append("\n");
// compute condition and branch over condition value
// if0: (== condLabel)
builder.append("if").append(condLabel).append(":\n");
handleWhileCond(whileLabel, outLabel, whileStatement);
// if1: (== whileLabel)
builder.append("if").append(whileLabel).append(":\n");
// while statements
whileStatement.body().accept(this);
// re-check cond
builder.append("br label %if");
builder.append(condLabel);
builder.append("\n");
// if2: (== outLabel)
builder.append("if").append(outLabel).append(":\n");
}
@Override
public void visit(SysoutStatement sysoutStatement) {
// handle ref-id or int-literal
sysoutStatement.arg().accept(this);
if (sysoutStatement.arg() instanceof IntegerLiteralExpr) {
builder.append("call void (i32) @print_int(i32 ").append(((IntegerLiteralExpr) sysoutStatement.arg()).num()).append(")");
} else if (sysoutStatement.arg() instanceof MethodCallExpr) {
builder.append("call void (i32) @print_int(i32 %_").append(getLastRegisterCount()).append(")");
} else if (sysoutStatement.arg() instanceof IdentifierExpr) {
// Resolve Variable Type
// Load that variable into register
this.resolveVariable(((IdentifierExpr) sysoutStatement.arg()).id(), this.currentMethod, true);
builder.append("call void (i32) @print_int(i32 %_").append(getLastRegisterCount()).append(")");
} else {
builder.append("call void (i32) @print_int(i32 %_").append(getLastRegisterCount()).append(")");
}
builder.append("\n");
}
@Override
public void visit(AssignStatement assignStatement) {
// compute rv
String rvType = "";
String rvRegisterString = "";
int rvRegister = 0;
if (assignStatement.rv() instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) assignStatement.rv()).id(), currentMethod, true);
rvType = getLastRegisterType();
rvRegisterString = currentRegisterToAssign;
} else {
assignStatement.rv().accept(this);
rvRegister = getLastRegisterCount();
rvType = getLastRegisterType();
}
// resolve lv variable
resolveVariable(assignStatement.lv(), currentMethod, false);
String lvReg = currentRegisterToStoreTo;
// handle ref-id or int-literal
if (assignStatement.rv() instanceof AddExpr || assignStatement.rv() instanceof SubtractExpr || assignStatement.rv() instanceof MultExpr || assignStatement.rv() instanceof ArrayAccessExpr) {
// store i32 %_4, i32* %x
builder.append("store i32 %_");
builder.append(rvRegister);
builder.append(", i32* ");
} else if (assignStatement.rv() instanceof IntegerLiteralExpr) {
// store i32 4, i32* %x
builder.append("store i32 ");
builder.append(((IntegerLiteralExpr) assignStatement.rv()).num());
builder.append(", i32* ");
} else if (assignStatement.rv() instanceof LtExpr) {
// store i1 %_4, i1* %x
builder.append("store i1 %_");
builder.append(rvRegister);
builder.append(", i1* ");
} else if (assignStatement.rv() instanceof TrueExpr) {
// store i1 1, i1* %x
builder.append("store i1 1, i1* ");
} else if (assignStatement.rv() instanceof FalseExpr) {
// store i1 0, i1* %x
builder.append("store i1 0, i1* ");
} else if (assignStatement.rv() instanceof NewObjectExpr) {
// store i8* %_0, i8** %b
builder.append("store i8* ");
builder.append(this.currentRegisterToAssign);
builder.append(", i8** ");
} else if (assignStatement.rv() instanceof NewIntArrayExpr) {
// store i32* %_3, i32** %x
builder.append("store i32* ");
builder.append(this.currentRegisterToAssign);
builder.append(", i32** ");
} else if (assignStatement.rv() instanceof IdentifierExpr) {
// store i32 %_3, i32* %x
builder.append("store ");
builder.append(rvType);
builder.append(" ");
builder.append(rvRegisterString);
builder.append(", ");
builder.append(rvType);
builder.append("* ");
} else if (assignStatement.rv() instanceof ThisExpr) {
// store i8* %this, i8** %x
builder.append("store i8* %this, i8** ");
} else {
// store i32 %_3, i32* %x
builder.append("store ");
builder.append(rvType);
builder.append(" %_");
builder.append(rvRegister);
builder.append(", ");
builder.append(rvType);
builder.append("* ");
}
builder.append(lvReg);
// builder.append(assignStatement.lv());
builder.append("\n");
}
@Override
public void visit(AssignArrayStatement assignArrayStatement) {
int legalAccessIndex = invokeIfRegisterCount();
int ilLegalAccessIndex = invokeIfRegisterCount();
int oobLegalAccessIndex = invokeIfRegisterCount();
int oobIlLegalAccessIndex = invokeIfRegisterCount();
String value;
// Load array
String arrayRegister = resolveVariable(assignArrayStatement.lv(), currentMethod, true);
// check len size is not negative
// %_0 = icmp slt i32 %_2, 0
// br i1 %_0, label %arr_alloc0, label %arr_alloc1
// assignArrayStatement.index().accept(this);
value = printIsNegativeNumberLlvm(assignArrayStatement, legalAccessIndex, ilLegalAccessIndex);
// if2:
builder.append("if");
builder.append(legalAccessIndex);
builder.append(":\n");
// Retrieve length of array
int lengthRegister = getLengthOfArray(arrayRegister);
// validate index - make sure it is not OOB
value = printIsOutOfBoundary(assignArrayStatement, oobLegalAccessIndex, oobIlLegalAccessIndex, lengthRegister, value);
// if4:
builder.append("if");
builder.append(oobLegalAccessIndex);
builder.append(":\n");
// compute l value - make sure to add 1 (due to index 0 - size) to index
// %_9 = add i32 0, 1
int indexRegister = invokeRegisterCount("i32");
builder.append("%_");
builder.append(indexRegister);
builder.append(" = add i32 ");
builder.append(value);
builder.append(", 1\n");
// %_10 = getelementptr i32, i32* %_4, i32 %_9
int elementPtrRegister = invokeRegisterCount("i32*");
builder.append("%_");
builder.append(elementPtrRegister);
builder.append(" = getelementptr i32, i32* ");
builder.append(arrayRegister);
builder.append(", i32 %_");
builder.append(indexRegister);
builder.append("\n");
// compute rv
String valueToStore = "i32 ";
assignArrayStatement.rv().accept(this);
if (assignArrayStatement.rv() instanceof IntegerLiteralExpr) {
valueToStore += ((IntegerLiteralExpr) assignArrayStatement.rv()).num();
} else if (assignArrayStatement.rv() instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) assignArrayStatement.rv()).id(), currentMethod, true);
valueToStore += "%_" + getLastRegisterCount();
} else {
valueToStore += "%_" + getLastRegisterCount();
}
// put rv in lv - store value in array
// store i32 1, i32* %_10
builder.append("store ");
builder.append(valueToStore);
builder.append(", i32* %_");
builder.append(elementPtrRegister);
builder.append("\n");
}
@Override
public void visit(AndExpr e) {
int assignedVal;
int andCond0 = invokeIfRegisterCount();
int andCond1 = invokeIfRegisterCount();
int andCond2 = invokeIfRegisterCount();
int andCond3 = invokeIfRegisterCount();
String register = "";
// compute e1
if (e.e1() instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) e.e1()).id(), currentMethod, true);
register = currentRegisterToAssign;
} else {
e.e1().accept(this);
}
// br label %andcond0
builder.append("br label %if");
builder.append(andCond0);
builder.append("\n");
// andcond0:
builder.append("if");
builder.append(andCond0);
builder.append(":\n");
// br i1 %_0, label %andcond1, label %andcond3
if (e.e1() instanceof TrueExpr) {
builder.append("br i1 1, label %if").append(andCond1).append(", label %if").append(andCond3);
} else if (e.e1() instanceof FalseExpr) {
builder.append("br i1 0, label %if").append(andCond1).append(", label %if").append(andCond3);
} else if (e.e1() instanceof IdentifierExpr) {
builder.append("br i1 %_").append(getLastRegisterCount()).append(", label %if").append(andCond1).append(", label %if").append(andCond3);
} else {
builder.append("br i1 %_").append(getLastRegisterCount()).append(", label %if").append(andCond1).append(", label %if").append(andCond3);
}
builder.append("\n");
// andcond1:
builder.append("if").append(andCond1).append(":\n");
// compute e2
e.e2().accept(this);
if (e.e2() instanceof TrueExpr) {
assignedVal = invokeRegisterCount("i1");
builder.append("%_").append(getLastRegisterCount()).append(" = icmp eq i1 1, 1\n");
} else if (e.e2() instanceof FalseExpr) {
assignedVal = invokeRegisterCount("i1");
builder.append("%_").append(getLastRegisterCount()).append(" = = icmp eq i1 1, 0\n");
} else if (e.e2() instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) e.e2()).id(), currentMethod, true);
assignedVal = getLastRegisterCount();
} else {
assignedVal = getLastRegisterCount();
}
// br label %andcond2
builder.append("br label %if").append(andCond2).append("\n");
// andcond2:
builder.append("if").append(andCond2).append(":\n");
// br label %andcond3
builder.append("br label %if").append(andCond3).append("\n");
// andcond3:
builder.append("if").append(andCond3).append(":\n");
invokeRegisterCount("i1");
builder.append("%_").append(getLastRegisterCount()).append(" = phi i1 [0, %if").append(andCond0).append("], [%_").append(assignedVal).append(", %if").append(andCond2).append("]");
builder.append("\n");
}
@Override
public void visit(LtExpr e) {
visitBinaryExpr(e, "icmp slt");
}
@Override
public void visit(AddExpr e) {
visitBinaryExpr(e, "add");
}
@Override
public void visit(SubtractExpr e) {
visitBinaryExpr(e, "sub");
}
@Override
public void visit(MultExpr e) {
visitBinaryExpr(e, "mul");
}
@Override
public void visit(ArrayAccessExpr e) {
// load array
String arrayRegister;
if (e.arrayExpr() instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) e.arrayExpr()).id(), currentMethod, true);
} else {
// if it is new int we handle it inside
e.arrayExpr().accept(this);
}
arrayRegister = currentRegisterToAssign;
// check index is not negative
int labelIllegalIndex = invokeIfRegisterCount();
int labelLegalIndex = invokeIfRegisterCount();
int oobLegalAccessIndex = invokeIfRegisterCount();
int oobIlLegalAccessIndex = invokeIfRegisterCount();
String indexValue;
// %_0 = icmp slt i32 %_2, %_size
//br i1 %_0, label %arr_alloc0, label %arr_alloc1
// e.indexExpr().accept(this);
indexValue = printIsNegativeNumberLlvm(e, labelLegalIndex, labelIllegalIndex);
// if2:
builder.append("if");
builder.append(labelLegalIndex);
builder.append(":\n");
// Retrieve length of array
int lengthRegister = getLengthOfArray(arrayRegister);
// validate index - make sure it is not OOB
indexValue = printIsOutOfBoundary(e, oobLegalAccessIndex, oobIlLegalAccessIndex, lengthRegister, indexValue);
// if2:
builder.append("if");
builder.append(oobLegalAccessIndex);
builder.append(":\n");
// %_9 = add i32 0, 1
int indexRegister = invokeRegisterCount("i32");
builder.append("%_");
builder.append(indexRegister);
builder.append(" = add i32 ");
builder.append(indexValue);
builder.append(", 1\n");
// %_10 = getelementptr i32, i32* %_4, i32 %_9
int valueRegister = invokeRegisterCount("i32*");
builder.append("%_");
builder.append(valueRegister);
builder.append(" = getelementptr i32, i32* ");
builder.append(arrayRegister);
builder.append(", i32 %_");
builder.append(indexRegister);
builder.append("\n");
// %_11 = load i32, i32* %_10
int loadRegister = invokeRegisterCount("i32");
builder.append("%_");
builder.append(loadRegister);
builder.append(" = load i32, i32* %_");
builder.append(valueRegister);
builder.append("\n");
}
@Override
public void visit(ArrayLengthExpr e) {
String lengthValue;
// new int[x].length();
if (e.arrayExpr() instanceof NewIntArrayExpr) {
int lengthRegister = invokeRegisterCount("i32");
AstNode lengthAst = ((NewIntArrayExpr) e.arrayExpr()).lengthExpr();
if (lengthAst instanceof IntegerLiteralExpr) {
lengthValue = "i32 " + ((IntegerLiteralExpr) lengthAst).num();
} else {
lengthAst.accept(this);
if (lengthAst instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) lengthAst).id(), currentMethod, true);
}
lengthValue = "i32 %_" + getLastRegisterCount();
}
// %_1 = i32 7
builder.append("%_");
builder.append(lengthRegister);
builder.append(" = ");
builder.append(lengthValue);
builder.append("\n");
} else if (e.arrayExpr() instanceof IdentifierExpr) {
// %_reg = get element name of array in 0 index
resolveVariable(((IdentifierExpr) e.arrayExpr()).id(), currentMethod, true);
getLengthOfArray(currentRegisterToAssign);
} else {
// the only option is method call?
e.arrayExpr().accept(this);
getLengthOfArray("%_" + getLastRegisterCount());
}
}
private int loadArray(String arrayId) {
// %_4 = load i32*, i32** %x
int arrayRegister = invokeRegisterCount("i32*");
builder.append("%_");
builder.append(arrayRegister);
builder.append(" = ");
builder.append("load i32*, i32** %");
builder.append(arrayId);
builder.append("\n");
return arrayRegister;
}
private int getLengthOfArray(String arrayRegister) {
// %_10 = getelementptr i32, i32* %_4, i32 0
int register = invokeRegisterCount("i32");
builder.append("%_");
builder.append(register);
builder.append(" = ");
builder.append("getelementptr i32, i32* ");
builder.append(arrayRegister);
builder.append(", i32 0");
builder.append("\n");
// %_7 = load i32, i32* %_10
int lengthRegister = invokeRegisterCount("i32");
builder.append("%_");
builder.append(lengthRegister);
builder.append(" = ");
builder.append("load i32, i32* %_");
builder.append(register);
builder.append("\n");
return lengthRegister;
}
@Override
public void visit(MethodCallExpr e) {
AstNode ownerExp = e.ownerExpr();
String classId = "";
// resolve class of owner (this, new, ref-id) -> class
if (ownerExp instanceof ThisExpr) {
currentRegisterToAssign = "%this";
classId = this.currentClass;
} else if (ownerExp instanceof NewObjectExpr) {
classId = ((NewObjectExpr) ownerExp).classId();
} else if (ownerExp instanceof IdentifierExpr) {
classId = resolveMethodCallVariable(((IdentifierExpr) ownerExp).id());
}
// Assume this was done in accept:
// %_6 = load i8*, i8** %b
e.ownerExpr().accept(this);
// %_7 = bitcast i8* %_6 to i8***
String loadedRegister = this.currentRegisterToAssign;
int bitcastRegister = invokeRegisterCount("i8*");
builder.append("%_");
builder.append(bitcastRegister);
builder.append(" = bitcast i8* ");
builder.append(loadedRegister);
builder.append(" to i8***\n");
// %_8 = load i8**, i8*** %_7
int vtableRegister = invokeRegisterCount("i8**");
builder.append("%_");
builder.append(vtableRegister);
builder.append(" = load i8**, i8*** %_");
builder.append(bitcastRegister);
builder.append("\n");
// %_9 = getelementptr i8*, i8** %_8, i32 0
int methodRegister = invokeRegisterCount("i8*");
// Resolve method offset according object struct to map
MethodInfo methodInfo = VtableCreator.getObjectStructMap().get(classId).getMethodeInfoMap().get(e.methodId());
int methodOffset = methodInfo.getOffset();
builder.append("%_");
builder.append(methodRegister);
builder.append(" = getelementptr i8*, i8** %_");
builder.append(vtableRegister);
builder.append(", i32 ");
builder.append(methodOffset);
builder.append("\n");
// %_10 = load i8*, i8** %_9
int actualFunctionPointerRegister = invokeRegisterCount("i8*");
builder.append("%_");
builder.append(actualFunctionPointerRegister);
builder.append(" = load i8*, i8** %_");
builder.append(methodRegister);
builder.append("\n");
// %_11 = bitcast i8* %_10 to i32 (i8*, i32)*
String returnTypeValue = methodInfo.getRet();
String args = methodInfo.getArgs();
bitcastRegister = invokeRegisterCount("i32 ()");
builder.append("%_");
builder.append(bitcastRegister);
builder.append(" = bitcast i8* %_");
builder.append(actualFunctionPointerRegister);
builder.append(" to ");
builder.append(returnTypeValue);
builder.append(args);
builder.append("*\n");
String delim = ", ";
StringBuilder arguments = new StringBuilder();
for (Expr arg : e.actuals()) {
arg.accept(this);
arguments.append(delim);
if (arg instanceof IntegerLiteralExpr) {
arguments.append("i32 ");
arguments.append(((IntegerLiteralExpr) arg).num());
} else if (arg instanceof TrueExpr) {
arguments.append("i1 1");
} else if (arg instanceof FalseExpr) {
arguments.append("i1 0");
} else if (arg instanceof ThisExpr) {
arguments.append("i8* %this");
} else if (arg instanceof NewIntArrayExpr) {
arguments.append("i32* ");
arguments.append(currentCallocRegister);
} else if (arg instanceof NewObjectExpr) {
arguments.append("i8* ");
arguments.append(currentCallocRegister);
} else {
if (arg instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) arg).id(), currentMethod, true);
} else {
arg.accept(this);
}
arguments.append(this.getLastRegisterType());
arguments.append(" ");
arguments.append("%_");
arguments.append(getLastRegisterCount());
}
}
// %_12 = call i32 %_11(i8* %_6, i32 1)
int callRegister = invokeRegisterCount(returnTypeValue);
builder.append("%_");
builder.append(callRegister);
builder.append(" = call ");
builder.append(returnTypeValue);
builder.append(" %_");
builder.append(bitcastRegister);
builder.append("(i8* ");
builder.append(loadedRegister);
builder.append(arguments);
builder.append(")\n");
currentRegisterToAssign = "%_" + callRegister;
}
@Override
public void visit(IntegerLiteralExpr e) {
}
@Override
public void visit(TrueExpr e) {
}
@Override
public void visit(FalseExpr e) {
}
@Override
public void visit(IdentifierExpr e) {
}
public void visit(ThisExpr e) {
}
@Override
public void visit(NewIntArrayExpr e) {
// according to example in class
int labelIllegalLength = invokeIfRegisterCount();
int labelLegalLength = invokeIfRegisterCount();
String lengthValue;
// check len size is not negative
// %_0 = icmp slt i32 %_2, 0
// br i1 %_0, label %arr_alloc0, label %arr_alloc1
// e.lengthExpr().accept(this);
lengthValue = printIsNegativeNumberLlvm(e, labelLegalLength, labelIllegalLength);
// if1:
builder.append("if");
builder.append(labelLegalLength);
builder.append(":\n");
// %_1 = add i32 2, 1
int sizeOfArrayRegister = invokeRegisterCount("i32");
builder.append("%_");
builder.append(sizeOfArrayRegister);
builder.append(" = add i32 ");
builder.append(lengthValue);
builder.append(", 1\n");
// %_2 = call i8* @calloc(i32 4, i32 %_1)
int callocRegister = invokeRegisterCount("i8*");
builder.append("%_");
builder.append(callocRegister);
builder.append(" = call i8* @calloc(i32 4, i32 %_");
builder.append(sizeOfArrayRegister);
builder.append(")\n");
// %_3 = bitcast i8* %_2 to i32*
int bitcastRegister = invokeRegisterCount("i8*");
builder.append("%_");
builder.append(bitcastRegister);
builder.append(" = bitcast i8* %_");
builder.append(callocRegister);
builder.append(" to i32*\n");
// store i32 2, i32* %_3
builder.append("store i32 ");
builder.append(lengthValue);
builder.append(", i32* %_");
builder.append(bitcastRegister);
builder.append("\n");
currentRegisterToAssign = "%_" + bitcastRegister;
currentCallocRegister = "%_" + bitcastRegister;
}
@Override
public void visit(NewObjectExpr e) {
int objectReg = invokeRegisterCount("i8*");
int vTable = invokeRegisterCount("i8**");
int vTableFirstElement = invokeRegisterCount("i8*");
ObjectStruct objectStruct = VtableCreator.getObjectStructMap().get(e.classId());
int sizeOfObject = objectStruct.getSizeInBytes();
int methodsCount = objectStruct.getMethodeInfoMap().size();
// %_0 = call i8* @calloc(i32 1, i32 12)
builder.append("%_");
builder.append(objectReg);
builder.append(" = call i8* @calloc(i32 1, i32 ");
builder.append(sizeOfObject);
builder.append(")\n");
// %_1 = bitcast i8* %_0 to i8***
builder.append("%_");
builder.append(vTable);
builder.append(" = bitcast i8* %_");
builder.append(objectReg);
builder.append(" to i8***\n");
// %_2 = getelementptr [2 x i8*], [2 x i8*]* @.Base_vtable, i32 0, i32 0
builder.append("%_");
builder.append(vTableFirstElement);
builder.append(" = getelementptr [");
builder.append(methodsCount);
builder.append(" x i8*], [");
builder.append(methodsCount);
builder.append(" x i8*]* @.");
builder.append(e.classId());
builder.append("_vtable, i32 0, i32 0\n");
// store i8** %_2, i8*** %_1
builder.append("store i8** %_");
builder.append(vTableFirstElement);
builder.append(", i8*** %_");
builder.append(vTable);
builder.append("\n");
this.currentRegisterToAssign = "%_" + objectReg;
currentCallocRegister = "%_" + objectReg;
}
@Override
public void visit(NotExpr e) {
// %_8 = sub i1 1, %_7
e.e().accept(this);
if (e.e() instanceof TrueExpr || e.e() instanceof FalseExpr) {
builder.append("%_");
builder.append(invokeRegisterCount("i1"));
builder.append(" = sub i1 1, ");
builder.append(e.e() instanceof TrueExpr ? "1" : "0");
builder.append("\n");
} else {
if (e.e() instanceof IdentifierExpr) {
resolveVariable(((IdentifierExpr) e.e()).id(), currentMethod, true);
}
int lastReg = getLastRegisterCount();
builder.append("%_");
builder.append(invokeRegisterCount("i1"));
builder.append(" = sub i1 1, %_");
builder.append(lastReg);
builder.append("\n");
}
}
@Override
public void visit(IntAstType t) {
}
@Override
public void visit(BoolAstType t) {
}
@Override
public void visit(IntArrayAstType t) {
}
@Override
public void visit(RefType t) {
}
}
<file_sep>/tests/ex3-omer/tester.sh
## assumptions:
# 1. in order to reach the compiled jar you need to run ../../mjavac
# 2. tests folder 'Test' has xml and 'Test.res' file (expected result)
## results:
# if the script & your code are working properly
# you should see the names of all of the tests with "Success"
COMMAND="java -jar ../../mjavac.jar unmarshal semantic"
FILEPATH="."
function test()
{
XMLFILE=$1
TESTFOLDER=$2
echo "Running Test:" $TESTFOLDER/$XMLFILE.java.xml
result_file=$TESTFOLDER/$TESTFOLDER.our-result
log_file=$TESTFOLDER/$XMLFILE.log
if [ -f $result_file ]; then
rm $TESTFOLDER/$TESTFOLDER.our-result
fi
if [ -f $log_file ]; then
rm $TESTFOLDER/$XMLFILE.log
fi
$COMMAND $TESTFOLDER/$XMLFILE.java.xml $result_file > $log_file
diff $result_file $TESTFOLDER/$XMLFILE.res
if [ $? -eq 0 ]
then
echo Success
else
echo Fail
fi
}
#ex3 examples in yotam's git:
test arraysValid arrays
test arraysInvalidLengthNotOnArray arrays
test arraysInvalidAccess arrays
test arraysInvalidAssignment arrays
test BinarySearch ast
test BinaryTree ast
test BubbleSort ast
test LinearSearch ast
test LinkedList ast
test QuickSort ast
test TreeVisitor ast
test inheritanceValid cyclicInheritance
test inheritanceInvalidCyclic cyclicInheritance
test inheritanceInvalidClassNotExist cyclicInheritance
test inheritanceInvalidBadClassOrder cyclicInheritance
test IfValid generalTypeChecks
test IfInvalidNonBooleanCond generalTypeChecks
test sysoutValid generalTypeChecks
test sysoutInvalidNonIntCond generalTypeChecks
test whileValid generalTypeChecks
test arrayCallInvalid IdentifierChecks
test booleanCallInvalid IdentifierChecks
test declRefTypeInvalid IdentifierChecks
test declRefTypeValid IdentifierChecks
test intCallInvalid IdentifierChecks
test NewClassInvalid IdentifierChecks
test NewClassValid IdentifierChecks
test initbothifelsinvalid InitializationCheck
test initonlywhileInvalid InitializationCheck
test OwnerExprInvalid methodCall
test OwnerExprValid methodCall
test OwnerExprValidField methodCall
test OwnerExprValidNew methodCall
test OwnerExprValidThis methodCall
test duplicated_formal_args ClassChecks
test duplicated_vars_in_method ClassChecks
test method_ret_type_invalid ClassChecks
test method_same_name_in_inheritance_class ClassChecks
test method_same_name_in_inheritance_class2 ClassChecks
test method_same_name_in_same_class ClassChecks
test several_fields_in_the_inheritance_class ClassChecks
test several_fields_in_the_same_class ClassChecks
test main_name_duplicate ClassChecks
test MethodDoesNotExist methodCallSignature
test MethodOverrideValid methodCallSignature
test MethodOverloadingDiffType methodCallSignature
test MethodOverloadingExtraParam methodCallSignature
test MethodCallWrongActual methodCallSignature
test MethodCallWrongActual2 methodCallSignature
test arrayNameInvalid varDeclarationChecks
test arraysAssignInvalid varDeclarationChecks
test AssignLvInvalid varDeclarationChecks
test AssignRvInvalid varDeclarationChecks
test BinaryAddInvalid varDeclarationChecks
test CallInvalid varDeclarationChecks
test IfInvalid varDeclarationChecks
test IfValid varDeclarationChecks
test OwnerExprNameInvalid varDeclarationChecks
test sysoutInvalid varDeclarationChecks
test whileValid varDeclarationChecks
test AssignmentInvalid yotam
test AssignmentValid yotam
test InitVarInvalid yotam
test InitVarValid yotam
test OwnerExprInvalid yotam
test OwnerExprValid yotam
<file_sep>/src/ast/ArrayAccessExpr.java
package ast;
import javax.xml.bind.annotation.XmlElement;
public class ArrayAccessExpr extends Expr {
@XmlElement(required = true)
private ExprWrapper arrayExpr;
@XmlElement(required = true)
private ExprWrapper indexExpr;
// for deserialization only!
public ArrayAccessExpr() {
}
public ArrayAccessExpr(Expr arrayExpr, Expr indexExpr) {
this.arrayExpr = new ExprWrapper(arrayExpr);
this.indexExpr = new ExprWrapper(indexExpr);
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
public Expr arrayExpr() {
return arrayExpr.e;
}
public Expr indexExpr() {
return indexExpr.e;
}
}
<file_sep>/tests/ex3/16assignmentInvalid/16assignmentInvalid.java
class Main {
public static void main(String[] args) {
System.out.println(1);
}
}
class A {
int what;
}
class B extends A {
int foo() {
return 0;
}
}
class C {
int what;
int poo() {
A a;
B b;
a = new A();
b = new B();
b = a;
return 1;
}
}
<file_sep>/src/ast/MainClass.java
package ast;
import javax.xml.bind.annotation.XmlElement;
public class MainClass extends AstNode {
@XmlElement(required = true)
private String name;
@XmlElement(required = true)
private String argsName;
@XmlElement(required = true)
private StatementWrapper mainStatement;
// for deserialization only!
public MainClass() {
}
public MainClass(String name, String argsName, Statement mainStatement) {
super();
this.name = name;
this.argsName = argsName;
this.mainStatement = new StatementWrapper(mainStatement);
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
public String name() {
return name;
}
public String argsName() {
return argsName;
}
public Statement mainStatement() {
return mainStatement.s;
}
}
<file_sep>/src/ast/AndExpr.java
package ast;
public class AndExpr extends BinaryExpr {
// for deserialization only!
public AndExpr() {
}
public AndExpr(Expr e1, Expr e2) {
super(e1, e2);
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
}
<file_sep>/README.md
Welcome to the compiler project 2020 starter kit!
=== Structure ===
build.xml
(directives for compiling the project using 'ant')
build/
(temp directory created when you build)
examples/
ast/
(examples of AST XMLs representing Java programs)
(more examples to come for each exercise)
schema/
ast.xsd
(XML schema for ASTs)
src/
(where all your stuff is going to go)
ast/*
(Java representation of AST, including XML marshaling & unmarshaling, Visitor interface, and printing to Java. Some files to note:)
AstXMLSerializer.java
(for converting ASTs between XML <-> Java classes)
AstPrintVisitor.java
(printing AST as a Java program)
Visitor.java
(visitor interface)
Program.java
(the root of the AST)
cup/
Parser.cup
(directives for CUP - to be used in ex4)
jflex/
Scanner.jfled
(directives for JFlex - to be used in ex4)
Main.java
(main file, including a skeleton for the command line arguments we will use in the exercises. already does XML marshaling and unarmshaling and printing to Java)
Lexer.java
(generated when you build - to be used in ex4)
Parser.java
(generated when you build - to be used in ex4)
sym.java
(generated when you build - to be used in ex4)
tools/*
(third party JARs for lexing & parsing (ex4) and XML manipulation)
mjava.jar
(*the* build)
README.md
(<-- you are here)
=== All those things with ex4?? ===
Ignore them (for now; you know, Chekhov's gun and the like).
=== Compiling the project ===
ant
=== Cleaning ===
ant clean
=== From AST XML to Java program ===
java -jar mjavac.jar unmarshal print examples/BinaryTree.xml res.java
=== From AST XML to... AST XML ===
java -jar mjavac.jar unmarshal marshal examples/BinaryTree.xml res.xml
(you will use the code for this "marhsal" option when generating ASTs in ex1,ex4)<file_sep>/tests/ex4/class_decls_fail2/class_decls_fail2.java
class BinarySearch {
public static void main(String[] a) {
System.out.println(7);
}
}
class Binary {
public int foo(int x, int z) {
int y;
int bla;
System.out.println(7);
return 17;
}
}
class Mika {
public int foo(int x, int z, int w, boolean t, int) {
int y;
int bla;
int bli;
int blu;
Binary b;
System.out.println(7);
return 17;
}
}
<file_sep>/src/ast/BinaryExpr.java
package ast;
import javax.xml.bind.annotation.XmlElement;
public abstract class BinaryExpr extends Expr {
@XmlElement(required = true)
private ExprWrapper e1;
@XmlElement(required = true)
private ExprWrapper e2;
// for deserialization only!
public BinaryExpr() {
}
public BinaryExpr(Expr e1, Expr e2) {
this.e1 = new ExprWrapper(e1);
this.e2 = new ExprWrapper(e2);
}
public Expr e1() {
return e1.e;
}
public Expr e2() {
return e2.e;
}
}
<file_sep>/tests/ex4/tester.sh
## assumptions:
# 1. in order to reach the compiled jar you need to run ../../mjavac
# 2. tests folder 'Test' has xml and 'Test.res' file (expected result)
## results:
# if the script & your code are working properly
# you should see the names of all of the tests with "Success"
COMMAND="java -jar ../../mjavac.jar parse print"
COMMAND_XML="java -jar ../../mjavac.jar parse marshal"
COMMAND_GOLDEN="java -jar ../../mjavac.jar unmarshal print"
FILEPATH="."
function test()
{
JAVAFILE=$2
TESTFOLDER=$1
echo "Running Test:" $TESTFOLDER / $JAVAFILE
result_file=$TESTFOLDER/$JAVAFILE.java.ours
golden_file=$TESTFOLDER/$JAVAFILE.java
log_file=$TESTFOLDER/$JAVAFILE.log
if [ -f $result_file ]; then
rm $TESTFOLDER/$JAVAFILE.java.ours
fi
if [ -f $log_file ]; then
rm $TESTFOLDER/$JAVAFILE.log
fi
$COMMAND $TESTFOLDER/$JAVAFILE.java $result_file > $log_file
diff -b -w -E -Z -B $result_file $golden_file
if [ $? -eq 0 ]
then
echo Success
else
echo Fail
fi
}
function test_xml()
{
JAVAFILE=$2
TESTFOLDER=$1
echo "Running Test:" $TESTFOLDER / $JAVAFILE
result_file=$TESTFOLDER/$JAVAFILE.java.ours
golden_file=$TESTFOLDER/$JAVAFILE.java.xml
log_file=$TESTFOLDER/$JAVAFILE.log
if [ -f $result_file ]; then
rm $result_file
fi
if [ -f $log_file ]; then
rm $log_file
fi
# create java with out parser
$COMMAND $TESTFOLDER/$JAVAFILE.java $result_file.java > $log_file
# create java with unmarshal - for debug
# $COMMAND_GOLDEN $golden_file $result_file.real.java > $log_file
# create xml with marshal
$COMMAND_XML $TESTFOLDER/$JAVAFILE.java $result_file > $log_file
# ignore spaces, tabs, new lines and lineNumber lines
diff -b -w -E -Z -B -I '^.*<lineNumber>' $result_file $golden_file
if [ $? -eq 0 ]
then
echo Success
else
echo Fail
fi
}
function test_invalid()
{
JAVAFILE=$2
TESTFOLDER=$1
echo "Running Test:" $TESTFOLDER / $JAVAFILE
result_file=$TESTFOLDER/$JAVAFILE.java.ours
golden_file=$TESTFOLDER/$JAVAFILE.err
log_file=$TESTFOLDER/$JAVAFILE.log
if [ -f $result_file ]; then
rm $result_file
fi
if [ -f $log_file ]; then
rm $log_file
fi
# create java with out parser
$COMMAND $TESTFOLDER/$JAVAFILE.java $result_file.java 2>> $log_file
diff -w $log_file $golden_file
if [ $? -eq 0 ]
then
echo Success
else
echo Fail
fi
}
#ex4:
test main-class main-class
test class_decl class_decl
test class_decls class_decls
test_xml ast BubbleSort
test_xml ast LinearSearch
test_xml ast QuickSort
test_xml ast TreeVisitor
test_xml ast Factorial
test_xml ast LinkedList
test_invalid Invalid InvalidLexing
test_invalid Invalid InvalidLexing2
test_invalid Invalid InvalidParsing
test_invalid class_decls_fail2 class_decls_fail2
test_invalid class_decls_fail class_decls_fail
<file_sep>/tests/ex3/4FieldWithSameDecl/4FieldWithSameDecl.java
ERROR
class Main {
public static void main(String[] args) {
System.out.println(1);
}
}
class A {
}
class B extends A {
int theVar;
int foo() {
return theVar;
}
}
class C extends B {
int theVar;
int foo() {
return theVar;
}
}
class D extends C {
int bar(int theVar, int anotherVar) {
return (theVar) + (anotherVar);
}
}
<file_sep>/examples/ex1/README.md
The examples here are structured as follows:
Each example has a name, e.g. local_var, method, etc.
- <name>.java is the original Java source code.
- <name>.java.xml is its AST in XML format.
- <name>.sh is the command line that should perform the renaming you implement.
- <name>_renamed.java.xml is the output of said command.<file_sep>/src/jflex/Scanner.jflex
/***************************/
/* Based on a template by <NAME> */
/***************************/
/*************/
/* USER CODE */
/*************/
import java_cup.runtime.*;
/******************************/
/* DOLAR DOLAR - DON'T TOUCH! */
/******************************/
%%
/************************************/
/* OPTIONS AND DECLARATIONS SECTION */
/************************************/
/*****************************************************/
/* Lexer is the name of the class JFlex will create. */
/* The code will be written to the file Lexer.java. */
/*****************************************************/
%class Lexer
/********************************************************************/
/* The current line number can be accessed with the variable yyline */
/* and the current column number with the variable yycolumn. */
/********************************************************************/
%line
%column
/******************************************************************/
/* CUP compatibility mode interfaces with a CUP generated parser. */
/******************************************************************/
%cup
/****************/
/* DECLARATIONS */
/****************/
/*****************************************************************************/
/* Code between %{ and %}, both of which must be at the beginning of a line, */
/* will be copied verbatim (letter to letter) into the Lexer class code. */
/* Here you declare member variables and functions that are used inside the */
/* scanner actions. */
/*****************************************************************************/
%{
/*********************************************************************************/
/* Create a new java_cup.runtime.Symbol with information about the current token */
/*********************************************************************************/
private Symbol symbol(int type) {return new Symbol(type, yyline, yycolumn);}
private Symbol symbol(int type, Object value) {return new Symbol(type, yyline, yycolumn, value);}
/*******************************************/
/* Enable line number extraction from main */
/*******************************************/
public int getLine() { return yyline + 1; }
public int getCharPos() { return yycolumn; }
%}
/***********************/
/* MACRO DECALARATIONS */
/***********************/
LINETERM = \r|\n|\r\n
WHITESPACE = [\t ] | {LINETERM}
NUMBER = 0 | [1-9][0-9]*
ID = [a-zA-Z\_]+[a-zA-Z0-9\_]*
IN_COMMENT = \/\/[a-zA-Z0-9\(\)\[\]\{\}\?!+\-\*\/\.\,;=\"\_ \t\f]*
MUL_COMMENT = \/\*~"*/"
COMMENTS = {IN_COMMENT}|{MUL_COMMENT}
/******************************/
/* DOLAR DOLAR - DON'T TOUCH! */
/******************************/
%%
/************************************************************/
/* LEXER matches regular expressions to actions (Java code) */
/************************************************************/
/**************************************************************/
/* YYINITIAL is the state at which the lexer begins scanning. */
/* So these regular expressions will only be matched if the */
/* scanner is in the start state YYINITIAL. */
/**************************************************************/
<YYINITIAL> {
<<EOF>> { return symbol(sym.EOF); }
"public" { return symbol(sym.PUBLIC); }
"static" { return symbol(sym.STATIC); }
"class" { return symbol(sym.CLASS); }
"extends" { return symbol(sym.EXTENDS); }
"+" { return symbol(sym.PLUS); }
"-" { return symbol(sym.MINUS); }
"*" { return symbol(sym.MULT); }
"=" { return symbol(sym.ASS); }
"!" { return symbol(sym.NOT); }
"while" { return symbol(sym.WHILE); }
"if" { return symbol(sym.IF); }
"else" { return symbol(sym.ELSE); }
"true" { return symbol(sym.TRUE); }
"false" { return symbol(sym.FALSE); }
"<" { return symbol(sym.LT); }
"&&" { return symbol(sym.AND); }
"," { return symbol(sym.COMMA); }
"(" { return symbol(sym.LPAREN); }
")" { return symbol(sym.RPAREN); }
"{" { return symbol(sym.LBR); }
"}" { return symbol(sym.RBR); }
"[" { return symbol(sym.LSQBR); }
"]" { return symbol(sym.RSQBR); }
";" { return symbol(sym.SEMICOLON); }
"." { return symbol(sym.DOT); }
"this" { return symbol(sym.THIS); }
"return" { return symbol(sym.RET); }
"String[]" { return symbol(sym.STRINGARGS); }
"int[]" { return symbol(sym.TYPEINTARRAY); }
"int" { return symbol(sym.TYPEINT); }
"boolean" { return symbol(sym.TYPEBOOL); }
".length" { return symbol(sym.LENGTH); }
"System.out.println" { return symbol(sym.SYSTEM); }
"new" { return symbol(sym.NEW); }
{NUMBER} { return symbol(sym.NUMBER, Integer.parseInt(yytext())); }
{ID} { return symbol(sym.ID, new String(yytext())); }
{WHITESPACE} { /* do nothing */ }
{COMMENTS} { /* do nothing */ }
}
<file_sep>/tests/ex3/6declOfOverrideMethodSubTypeValid/6declOfOverrideMethodSubTypeValid.java
class Main {
public static void main(String[] args) {
System.out.println(1);
}
}
class Shared {
int theThing;
Shared theThing() {
return new Shared();
}
}
class A extends Shared {
}
class B extends A {
A theThing() {
return new A();
}
}
<file_sep>/src/ast/MethodInfo.java
package ast;
public class MethodInfo {
private String args;
private String ret;
private int offset;
public MethodInfo(String args, String ret, int offset) {
this.args = args;
this.ret = ret;
this.offset = offset;
}
public String getArgs() {
return args;
}
public String getRet() {
return ret;
}
public int getOffset() {
return offset;
}
}
<file_sep>/src/ast/FieldInfo.java
package ast;
public class FieldInfo {
private String fieldType;
private int offset;
public FieldInfo(String fieldType, int offset) {
this.fieldType = fieldType;
this.offset = offset;
}
public String getFieldType() {
return fieldType;
}
public int getOffset() {
return offset;
}
}
<file_sep>/tests/ex3/20printInt/20printInt.java
class Main {
public static void main(String[] a) {
System.out.println(new Simple());
}
}
class Simple {
int fun() {
boolean a;
a = true;
return 0;
}
}
<file_sep>/src/Main.java
import ast.*;
import symbolTable.Symbol;
import symbolTable.FlowUtils;
import symbolTable.SymbolTableUtils;
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
var inputMethod = args[0];
var action = args[1];
var filename = args[args.length - 2];
var outfilename = args[args.length - 1];
Program prog;
if (inputMethod.equals("parse")) {
FileReader fileReader = new FileReader(new File(filename));
Parser p = new Parser(new Lexer(fileReader));
prog = (Program) p.parse().value;
} else if (inputMethod.equals("unmarshal")) {
AstXMLSerializer xmlSerializer = new AstXMLSerializer();
prog = xmlSerializer.deserialize(new File(filename));
} else {
throw new UnsupportedOperationException("unknown input method " + inputMethod);
}
var outFile = new PrintWriter(outfilename);
try {
boolean validToContinue = true;
SymbolTableUtils.buildSymbolTables(prog);
if (action.equals("marshal")) {
AstXMLSerializer xmlSerializer = new AstXMLSerializer();
xmlSerializer.serialize(prog, outfilename);
} else if (action.equals("print")) {
AstPrintVisitor astPrinter = new AstPrintVisitor();
astPrinter.visit(prog);
outFile.write(astPrinter.getString());
} else if (action.equals("semantic")) {
if (SymbolTableUtils.isERROR()) {
// System.out.println(SymbolTableUtils.getERRORReasons());
outFile.write("ERROR\n");
} else {
AstTypesVisitor astTypeVisitor = new AstTypesVisitor();
astTypeVisitor.visit(prog);
if (astTypeVisitor.isError()) {
// System.out.println(astTypeVisitor.getErrorMsg());
outFile.write("ERROR\n");
} else {
AstInitializedVisitor astInitVisitor = new AstInitializedVisitor();
astInitVisitor.visit(prog);
if (astInitVisitor.isError()) {
// System.out.println(astInitVisitor.getErrorMsg());
outFile.write("ERROR\n");
} else {
outFile.write("OK\n");
}
}
}
} else if (action.equals("compile")) {
// VtableCreator - create vtables + Class->data-structure(vtable-method/field -> offset) and probably more...
VtableCreator v = new VtableCreator();
String llvmVtables = v.createVtableAndObjectsStruct();
// LLVM Print Visitor
AstLlvmPrintVisitor astLlvmPrintVisitor = new AstLlvmPrintVisitor();
astLlvmPrintVisitor.visit(prog);
// Concat v tables and visitor's result
String llvmOutput = astLlvmPrintVisitor.getString();
outFile.write(llvmVtables + "\n" + llvmOutput);
} else if (action.equals("rename")) {
var type = args[2];
var originalName = args[3];
var originalLine = args[4];
var newName = args[5];
boolean isMethod;
if (type.equals("var")) {
isMethod = false;
} else if (type.equals("method")) {
isMethod = true;
} else {
throw new IllegalArgumentException("unknown rename type " + type);
}
try {
Symbol symbol = FlowUtils.findSymbolToRename(Integer.parseInt(originalLine), originalName, isMethod);
FlowUtils.rename(symbol.getProperties(), newName);
AstXMLSerializer xmlSerializer = new AstXMLSerializer();
xmlSerializer.serialize(prog, outfilename);
} catch (UnsupportedOperationException e) {
throw new UnsupportedOperationException(e.getMessage());
} catch (Exception e) {
// error handling
throw new UnsupportedOperationException(e.getMessage());
}
} else {
throw new IllegalArgumentException("unknown command line action " + action);
}
} finally {
outFile.flush();
outFile.close();
}
} catch (FileNotFoundException e) {
System.out.println("Error reading file: " + e);
e.printStackTrace();
} catch (Exception e) {
System.out.println("General error: " + e);
e.printStackTrace();
}
}
}
<file_sep>/src/symbolTable/Type.java
package symbolTable;
public enum Type {
METHOD("Method"),
VARIABLE("Variable");
private String name;
Type(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
<file_sep>/src/ast/AstTypesVisitor.java
package ast;
import symbolTable.Symbol;
import symbolTable.SymbolTable;
import symbolTable.SymbolTableUtils;
import symbolTable.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class AstTypesVisitor implements Visitor {
private String errorMsg = "";
private boolean error = false;
private String currentMethod;
private String currentClass;
private String currentType;
List<String> primitiveTypes = Arrays.asList("int", "boolean", "intArray");
// sets error
private void setError(String errorString) {
error = true;
errorMsg += "\nMethod: " + currentMethod + " Class:" + currentClass + "\n" + errorString;
}
public boolean isError() {
return error;
}
public String getErrorMsg() {
return errorMsg;
}
// Checks if a is subtype of b
private boolean isSubTypeOf(String typeA, String typeB) {
boolean bIsPrimitive = false;
for (var type : primitiveTypes) {
if (typeA.equals(type)) {
if (!typeA.equals(typeB)) {
return false;
} else {
return true;
}
}
if (typeB.equals(type)) {
bIsPrimitive = true;
}
}
if(bIsPrimitive) {
return false;
}
SymbolTable typeASymbolTable = SymbolTableUtils.getSymbolTableClassMap_real().get(typeA);
SymbolTable typeBSymbolTable = SymbolTableUtils.getSymbolTableClassMap_real().get(typeB);
SymbolTable symbolTable = typeASymbolTable;
if (symbolTable == typeBSymbolTable) {
return true;
}
while (symbolTable != null) {
symbolTable = symbolTable.getParentSymbolTable();
if (symbolTable != null && symbolTable == typeBSymbolTable) {
return true;
}
}
return false;
}
// Receives ast node and returns its type
private String resolveVariableType(String variableName) {
SymbolTable currentSymbolTable = SymbolTableUtils.getSymbolTableClassWithMethodMap().get(currentMethod + currentClass);
String type;
type = isVariableInSymbolTable(variableName, currentSymbolTable);
boolean isField = type == null;
if (isField) {
SymbolTable parentSymbolTable = currentSymbolTable.getParentSymbolTable();
boolean foundField = false;
while (parentSymbolTable != null && !foundField) {
type = isVariableInSymbolTable(variableName, parentSymbolTable);
foundField = type != null;
parentSymbolTable = parentSymbolTable.getParentSymbolTable();
}
}
return type;
}
private String isVariableInSymbolTable(String variableName, SymbolTable currentSymbolTable) {
for (Map.Entry<String, Symbol> entry : currentSymbolTable.getEntries().entrySet()) {
if (entry.getValue().getSymbolName().equals(variableName)) {
return entry.getValue().getDecl().get(0);
}
}
return null;
}
private Symbol getSymbol(String methodName, SymbolTable currentSymbolTable) {
for (Map.Entry<String, Symbol> entry : currentSymbolTable.getEntries().entrySet()) {
if (entry.getKey().equals(SymbolTable.createKey(methodName, Type.METHOD))) {
return entry.getValue();
}
}
return null;
}
// Returns whether the method is root or not
private boolean isRootMethod(String methodName) {
SymbolTable currentSymbolTable = SymbolTableUtils.getSymbolTableClassMap_real().get(currentClass);
return getSymbol(methodName, currentSymbolTable).isRootMethod();
}
// Returns root method - only when the current class doesn't have it
private Symbol getRootMethod(String methodName) {
SymbolTable currentSymbolTable = SymbolTableUtils.getSymbolTableClassMap_real().get(currentClass);
// currentSymbolTable = currentSymbolTable.getParentSymbolTable();
while (currentSymbolTable != null) {
Symbol symbol = getSymbol(methodName, currentSymbolTable);
if (symbol != null) {
return symbol;
}
currentSymbolTable = currentSymbolTable.getParentSymbolTable();
}
return null;
}
// Returns closet anestor method with the same name- to check override
private Symbol getAncestorMethod(String methodName) {
SymbolTable currentSymbolTable = SymbolTableUtils.getSymbolTableClassMap_real().get(currentClass);
currentSymbolTable = currentSymbolTable.getParentSymbolTable();
while (currentSymbolTable != null) {
Symbol symbol = getSymbol(methodName, currentSymbolTable);
if (symbol != null) {
return symbol;
}
currentSymbolTable = currentSymbolTable.getParentSymbolTable();
}
return null;
}
private Symbol getMethodCallSymbol(String classId, String methodName) {
SymbolTable currentSymbolTable = SymbolTableUtils.getSymbolTableClassMap_real().get(classId);
do {
Symbol symbol = getSymbol(methodName, currentSymbolTable);
if (symbol != null) {
return symbol;
}
currentSymbolTable = currentSymbolTable.getParentSymbolTable();
} while ((currentSymbolTable != null));
return null;
}
@Override
public void visit(Program program) {
program.mainClass().accept(this);
for (ClassDecl classdecl : program.classDecls()) {
if(isError()){return;}
classdecl.accept(this);
}
}
@Override
public void visit(ClassDecl classDecl) {
currentClass = classDecl.name();
for (var methodDecl : classDecl.methoddecls()) {
if(isError()){return;}
currentMethod = methodDecl.name();
methodDecl.accept(this);
}
}
@Override
public void visit(MainClass mainClass) {
mainClass.mainStatement().accept(this);
}
@Override
public void visit(MethodDecl methodDecl) {
// Check if this method is root.
// System.out.println(currentClass);
Symbol rootMethodSymbol;
String rootMethodReturnType;
if(!isRootMethod(methodDecl.name())){
rootMethodSymbol = getAncestorMethod(methodDecl.name());
rootMethodReturnType= rootMethodSymbol.getDecl().get(0);
}
else {
rootMethodSymbol = getRootMethod(methodDecl.name());
rootMethodReturnType = rootMethodSymbol.getDecl().get(0);
// System.out.println("root");
// System.out.println(rootMethodSymbol.getDecl().size());
// System.out.println(rootMethodSymbol.getSymbolName());
}
if (!isRootMethod(methodDecl.name())) {
int i = 1;
// check that the variables are exact type of root
if (methodDecl.formals().size() != rootMethodSymbol.getDecl().size() - 1) {
String exp = "" + (rootMethodSymbol.getDecl().size() - 1);
setError("Incorrect number of formals; expected: " + exp + " got: " + methodDecl.formals().size());
}
for (FormalArg formal : methodDecl.formals()) {
if(isError()){return;}
formal.accept(this);
// resolve upper type
String formalRootMethod = rootMethodSymbol.getDecl().get(i);
// compare upper type and currentType
if (!currentType.equals(formalRootMethod)) {
setError("Formal type incorrect; expected: " + formalRootMethod + " got: " + currentType);
}
i++;
}
// check that the return type is subtype of root return
methodDecl.returnType().accept(this);
if(isError()){return;}
if (!isSubTypeOf(currentType, rootMethodReturnType)) {
setError("Return type incorrect; expected: " + rootMethodReturnType + " got: " + currentType);
}
}
// Do we need this?
for (var varDecl : methodDecl.vardecls()) {
if(isError()){return;}
varDecl.accept(this);
}
if(isError()){return;}
// Only for accept
for (var stmt : methodDecl.body()) {
if(isError()){return;}
stmt.accept(this);
}
// make sure return type is appropriate
if(isError()){return;}
methodDecl.ret().accept(this);
if (!isSubTypeOf(currentType, rootMethodReturnType)) {
setError("Return value incorrect; expected: " + rootMethodReturnType + " got: " + currentType);
}
}
@Override
public void visit(FormalArg formalArg) {
if(isError()){return;}
currentType = resolveVariableType(formalArg.name());
}
@Override
public void visit(VarDecl varDecl) {
if(isError()){return;}
// make sure it needs to be empty
}
@Override
public void visit(BlockStatement blockStatement) {
for (var statement : blockStatement.statements()) {
if(isError()){return;}
statement.accept(this);
}
}
@Override
public void visit(IfStatement ifStatement) {
if(isError()){return;}
// accept cond
ifStatement.cond().accept(this);
if (!currentType.equals("boolean")) {
setError("Expected: boolean, Received: " + currentType);
}
// then statements
ifStatement.thencase().accept(this);
if(isError()){return;}
// else statement
ifStatement.elsecase().accept(this);
}
@Override
public void visit(WhileStatement whileStatement) {
// accept cond
if(isError()){return;}
whileStatement.cond().accept(this);
if (!currentType.equals("boolean")) {
setError("Expected: boolean, Received: " + currentType);
}
if(isError()){return;}
// while statements
whileStatement.body().accept(this);
}
@Override
public void visit(SysoutStatement sysoutStatement) {
// handle ref-id or int-literal
if(isError()){return;}
sysoutStatement.arg().accept(this);
if(isError()){return;}
if (!currentType.equals("int")) {
setError("Expected: int, Received: " + currentType);
}
}
@Override
public void visit(AssignStatement assignStatement) {
if(isError()){return;}
// compute lv
String typeLv = resolveVariableType(assignStatement.lv());
assignStatement.rv().accept(this);
if(isError()){return;}
String typeRv = currentType;
if (!isSubTypeOf(typeRv, typeLv)) {
setError("AssignStatement, expected subtype of: " + typeLv + " Received: " + typeRv);
}
}
@Override
public void visit(AssignArrayStatement assignArrayStatement) {
if(isError()){return;}
// compute lv
String typeLv = resolveVariableType(assignArrayStatement.lv());
if (!typeLv.equals("intArray")) {
setError("Expected: intArray, Received: " + typeLv);
}
assignArrayStatement.index().accept(this);
if(isError()){return;}
if (!currentType.equals("int")) {
setError("Expected: int, Received: " + currentType);
}
if(isError()){return;}
assignArrayStatement.rv().accept(this);
if(isError()){return;}
if (!currentType.equals("int")) {
setError("Expected: int, Received: " + currentType);
}
}
@Override
public void visit(AndExpr e) {
if(isError()){return;}
e.e1().accept(this);
if(isError()){return;}
if (!currentType.equals("boolean")) {
setError("Expected: boolean, Got: " + currentType);
}
e.e2().accept(this);
if(isError()){return;}
if (!currentType.equals("boolean")) {
setError("Expected: boolean, Got: " + currentType);
}
currentType = "boolean";
}
private void visitIntBinaryExpr(BinaryExpr e) {
if(isError()){return;}
e.e1().accept(this);
if(isError()){return;}
if (!currentType.equals("int")) {
setError("Expected: int, Got: " + currentType);
}
e.e2().accept(this);
if(isError()){return;}
if (!currentType.equals("int")) {
setError("Expected: int, Got: " + currentType);
}
currentType = "int";
}
@Override
public void visit(LtExpr e) {
if(isError()){return;}
e.e1().accept(this);
if (!currentType.equals("int")) {
setError("Expected: int, Got: " + currentType);
}
if(isError()){return;}
e.e2().accept(this);
if(isError()){return;}
if (!currentType.equals("int")) {
setError("Expected: int, Got: " + currentType);
}
currentType = "boolean";
}
@Override
public void visit(AddExpr e) {
if(isError()){return;}
visitIntBinaryExpr(e);
}
@Override
public void visit(SubtractExpr e) {
if(isError()){return;}
visitIntBinaryExpr(e);
}
@Override
public void visit(MultExpr e) {
if(isError()){return;}
visitIntBinaryExpr(e);
}
@Override
public void visit(ArrayAccessExpr e) {
if(isError()){return;}
e.arrayExpr().accept(this);
if(isError()){return;}
if (!currentType.equals("intArray")) {
setError("Expected: intArray, Got: " + currentType);
}
if(isError()){return;}
e.indexExpr().accept(this);
if(isError()){return;}
if (!currentType.equals("int")) {
setError("Expected: int, Got: " + currentType);
}
currentType = "int";
}
@Override
public void visit(ArrayLengthExpr e) {
if(isError()){return;}
e.arrayExpr().accept(this);
if(isError()){return;}
if (!currentType.equals("intArray")) {
setError("Expected: intArray, Got: " + currentType);
}
currentType = "int";
}
@Override
public void visit(MethodCallExpr e) {
if(isError()){return;}
// make sure correct owner type
e.ownerExpr().accept(this);
if(isError()){return;}
if (primitiveTypes.contains(currentType)) {
setError("Expected: ref-type, Got: " + currentType);
}
Symbol methodSymbol = getMethodCallSymbol(currentType, e.methodId());
//make sure number of actual params matches the method declaration
if (e.actuals().size()!=methodSymbol.getDecl().size()-1) {
setError("Number of actual params doesn't match the method declaration; expected: " + (methodSymbol.getDecl().size()-1) +
" got: " + e.actuals().size());
}
if(isError()){return;}
// make sure variables are of correct type
int i = 1;
for (Expr arg : e.actuals()) {
if(isError()){return;}
arg.accept(this);
String formalType = methodSymbol.getDecl().get(i);
if (!isSubTypeOf(currentType, formalType)) {
setError("Formal type incorrect; expected: " + formalType + " got: " + currentType);
}
i++;
}
if(isError()){return;}
currentType = methodSymbol.getDecl().get(0);
}
@Override
public void visit(IntegerLiteralExpr e) {
if(isError()){return;}
currentType = "int";
}
@Override
public void visit(TrueExpr e) {
if(isError()){return;}
currentType = "boolean";
}
@Override
public void visit(FalseExpr e) {
if(isError()){return;}
currentType = "boolean";
}
@Override
public void visit(IdentifierExpr e) {
if(isError()){return;}
currentType = resolveVariableType(e.id());
}
public void visit(ThisExpr e) {
if(isError()){return;}
currentType = currentClass;
}
@Override
public void visit(NewIntArrayExpr e) {
if(isError()){return;}
e.lengthExpr().accept(this);
if(isError()){return;}
if (!currentType.equals("int")) {
setError("Expected: int, Got: " + currentType);
}
currentType = "intArray";
}
@Override
public void visit(NewObjectExpr e) {
currentType = e.classId();
}
@Override
public void visit(NotExpr e) {
if(isError()){return;}
// accept
e.e().accept(this);
if(isError()){return;}
if (!currentType.equals("boolean")) {
setError("Expected: boolean, Got: " + currentType);
}
currentType = "boolean";
}
@Override
public void visit(IntAstType t) {
if(isError()){return;}
currentType = t.id;
}
@Override
public void visit(BoolAstType t) {
if(isError()){return;}
currentType = t.id;
}
@Override
public void visit(IntArrayAstType t) {
if(isError()){return;}
currentType = t.id;
}
@Override
public void visit(RefType t) {
if(isError()){return;}
currentType = t.id();
}
}
<file_sep>/tests/ex3-omer/arrays/arraysInvalidAssignment.java
class Main {
public static void main(String[] args) {
System.out.println(1);
}
}
class A { }
class B extends A {
int[] arr;
public int foo() {
arr[0] = new A();
return arr.length;
}
}
<file_sep>/src/ast/ObjectStruct.java
package ast;
import java.util.HashMap;
import java.util.Map;
public class ObjectStruct {
private int sizeInBytes = 8;
//maps between methode name and it's properties
private Map<String, MethodInfo> methodeInfoMap;
//maps between field and it's offset
private Map<String, FieldInfo> fieldInfoMap;
private int lastOffsetFields = 8;
private int lastOffsetMethodes = 0;
public int getSizeInBytes() {
return sizeInBytes;
}
public Map<String, MethodInfo> getMethodeInfoMap() {
return methodeInfoMap;
}
public Map<String, FieldInfo> getFieldInfoMap() {
return fieldInfoMap;
}
public ObjectStruct() {
this.fieldInfoMap = new HashMap<>();
this.methodeInfoMap = new HashMap<>();
}
private int getLastOffsetFields(int fieldSize) {
int result = lastOffsetFields;
lastOffsetFields += fieldSize;
return result;
}
private int getLastOffsetMethods() {
return lastOffsetMethodes++;
}
private void incrementSize(int num) {
sizeInBytes += num;
}
public void addField(String fieldName, String fieldType, int fieldSize) {
FieldInfo fieldInfo = new FieldInfo(fieldType, getLastOffsetFields(fieldSize));
incrementSize(fieldSize);
fieldInfoMap.put(fieldName, fieldInfo);
}
public void addMethod(String methodName, String args, String ret) {
MethodInfo methodInfo = new MethodInfo(args, ret, getLastOffsetMethods());
methodeInfoMap.put(methodName, methodInfo);
}
}
<file_sep>/tests/ex3-omer/methodCall/OwnerExprInvalid.java
class Main {
public static void main(String[] a) {
System.out.println(3);
}
}
class Tree {
Tree left;
Tree right;
public Tree getLeft() {
return left;
}
public Tree getRight() {
return right;
}
public int num() {
return 2;
}
public int fun() {
Tree t;
return new Tree().getLeft().fun();
}
}
<file_sep>/src/ast/IdentifierExpr.java
package ast;
import javax.xml.bind.annotation.XmlElement;
public class IdentifierExpr extends Expr {
@XmlElement(required = true)
private String id;
// for deserialization only!
public IdentifierExpr() {
}
public IdentifierExpr(String id) {
this.id = id;
}
@Override
public void accept(Visitor v) {
v.visit(this);
}
public String id() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
<file_sep>/src/ast/Statement.java
package ast;
public abstract class Statement extends AstNode {
public Statement() {
}
}
|
cf824b9bc8f670790756ea1acf48a41cf16e678d
|
[
"Shell",
"Ant Build System",
"Java",
"Markdown",
"JFlex"
] | 49 |
Shell
|
chenmoryosef/compilers-project-2020-public
|
07fd73d323f1d2067eddc6fd0ec8f8341737b3fa
|
9c895b012f446d7ab26fcd70f5d90dee3a1f686c
|
refs/heads/main
|
<file_sep>const drawBtn = document.querySelector(".jsDrawBtn");
const spans = document.querySelectorAll(".jsNum");
const drawNums = document.getElementById("jsDrawNums");
const draws = drawNums.querySelector("ul");
const navBtn = document.querySelector(".navBtn");
let randomNum = [];
let drawNum = [];
const paintNum = () => {
for (let i = 0; i < spans.length; i++) {
spans[i].innerText = randomNum[i];
if (randomNum[i] <= 10) {
spans[i].classList.add("yellow");
} else if (randomNum[i] <= 20) {
spans[i].classList.add("blue");
} else if (randomNum[i] <= 30) {
spans[i].classList.add("red");
} else if (randomNum[i] <= 40) {
spans[i].classList.add("black");
} else {
spans[i].classList.add("green");
}
}
};
const createNum = () => {
for (let i = randomNum.length; i < 6; i++) {
const min = Math.ceil(1);
const max = Math.floor(45);
const result = Math.floor(Math.random() * (max - min + 1)) + min;
randomNum.push(result);
}
};
const reset = () => {
pass = true;
randomNum = [];
spans.forEach((span) => {
span.classList.remove("yellow", "red", "blue", "black", "green");
});
};
const validation = () => {
let result = [...new Set(randomNum)];
if (result.length !== 6) {
return true;
} else if (result.length === 6) {
return false;
}
};
const handleClick = () => {
reset();
do {
reset();
createNum();
} while (validation());
randomNum.sort((compareCondition = (a, b) => a - b));
drawNum.push(randomNum);
paintDrawNums();
paintNum();
};
const paintDrawNums = () => {
const lastDrawNums = drawNum[drawNum.length - 1];
const item = document.createElement("li");
const items = document.createElement("ul");
lastDrawNums.forEach((num) => {
const number = document.createElement("span");
number.classList.add("jsDrawNum");
if (num <= 10) {
number.classList.add("yellow");
} else if (num <= 20) {
number.classList.add("blue");
} else if (num <= 30) {
number.classList.add("red");
} else if (num <= 40) {
number.classList.add("black");
} else {
number.classList.add("green");
}
number.innerText = num;
item.appendChild(number);
});
draws.appendChild(item);
};
const handleNavClick = () => {
if (drawNums.className === "hide") {
drawNums.className = "appear";
navBtn.innerText = "숨기기";
} else {
drawNums.className = "hide";
navBtn.innerText = "항목 보기";
}
};
const init = () => {
drawBtn.addEventListener("click", handleClick);
navBtn.addEventListener("click", handleNavClick);
};
init();
<file_sep># Lotto
당첨되자 로또,, 간절히 바라며 뽑아봅니다,,
https://seojunhwan.github.io/Lotto/
|
5218487d49680d6c8c8faef74ff7b55cb577ab27
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
Seojunhwan/Lotto
|
f8057bf6198462e40a1d122a0edc579b1c76c003
|
277246042247d6dd52fe1db4a2cad0cb4bc1bc2a
|
refs/heads/master
|
<repo_name>joelchelliah/git-merge-revert-test<file_sep>/README.md
# git-merge-revert-test
|
f7340bf27501480f720c68b5690a907574428c6b
|
[
"Markdown"
] | 1 |
Markdown
|
joelchelliah/git-merge-revert-test
|
32b4d0e3ebff3ecf0d5df7069450572697878ddc
|
c616a47081007b1f257e28ff87a5c8dffcd3a7a8
|
refs/heads/master
|
<repo_name>hyy044101331/mengka<file_sep>/src/main/java/mengka/mail/excelread/ReadExcel_03.java
package mengka.mail.excelread;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import mengka.Util.StringUtil;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class ReadExcel_03 {
/**
* @param args
* @throws Exception
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws Exception {
String path = "src//main//java//mengka//mail//excelread//huodong.xls";
String outPath = "src//main//java//mengka//mail//excelread//activity"
+ getCurrentDate() + ".xls";
String bbpath = "src//main//java//mengka//mail//excelread//article.xls";
String bboutPath = "src//main//java//mengka//mail//excelread//article"
+ getCurrentDate() + ".xls";
String ccpath = "src//main//java//mengka//mail//excelread//shaidan.xls";
String ccoutPath = "src//main//java//mengka//mail//excelread//shaidan"
+ getCurrentDate() + ".xls";
String ddpath = "src//main//java//mengka//mail//excelread//backyard02.xls";
String ddoutPath = "src//main//java//mengka//mail//excelread//backyard"
+ getCurrentDate() + ".xls";
HashMap pathMap = new HashMap();
pathMap.put("huodong", path);
pathMap.put("article", bbpath);
pathMap.put("shaidan", ccpath);
mkBackyardData(ddpath, ddoutPath, pathMap);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void mkBackyardData(String path, String outPath,
HashMap pathMap) throws Exception {
Sheet sheet = getWorkBook(path, 0);
// 表格数据
Sheet hdsheet = getWorkBook((String) pathMap.get("huodong"), 0);
Sheet xbsheet = getWorkBook((String) pathMap.get("article"), 0);
Sheet axsheet = getWorkBook((String) pathMap.get("shaidan"), 0);
HashMap xbMap = getArticleSheet(xbsheet);
HashMap hdMap = getActivitySheet(hdsheet);
HashMap axMap = getArticleSheet(axsheet);
File f = new File(outPath);
FileOutputStream outStream = new FileOutputStream(f, false);
WritableWorkbook workbook = Workbook.createWorkbook(outStream);
WritableSheet sheet1 = workbook.createSheet("店铺后院", 0);
// 表格:设置列的属性
Label label1 = new Label(0, 0, "店铺ID");
Label label2 = new Label(1, 0, "nick");
Label label3 = new Label(2, 0, "用户ID");
Label label4 = new Label(3, 0, "星级");
Label label5 = new Label(4, 0, "站点ID");
Label label6 = new Label(5, 0, "类目");
Label label7 = new Label(6, 0, "小报数量");
Label label8 = new Label(7, 0, "小报喜欢次数");
Label label9 = new Label(8, 0, "小报分享次数");
Label label10 = new Label(9, 0, "小报评论次数");
Label label11 = new Label(10, 0, "活动个数");
Label label12 = new Label(11, 0, "活动参加人数");
Label label13 = new Label(12, 0, "活动喜欢次数");
Label label14 = new Label(13, 0, "活动分享次数");
Label label15 = new Label(14, 0, "活动评论次数");
Label label16 = new Label(15, 0, "晒单数量");
Label label17 = new Label(16, 0, "晒单喜欢次数");
Label label18 = new Label(17, 0, "晒单分享次数");
Label label19 = new Label(18, 0, "晒单评论次数");
Label label20 = new Label(19, 0, "后院喜欢次数");
Label label21 = new Label(20, 0, "用户标记");
sheet1.addCell(label1);
sheet1.addCell(label2);
sheet1.addCell(label3);
sheet1.addCell(label4);
sheet1.addCell(label5);
sheet1.addCell(label6);
sheet1.addCell(label7);
sheet1.addCell(label8);
sheet1.addCell(label9);
sheet1.addCell(label10);
sheet1.addCell(label11);
sheet1.addCell(label12);
sheet1.addCell(label13);
sheet1.addCell(label14);
sheet1.addCell(label15);
sheet1.addCell(label16);
sheet1.addCell(label17);
sheet1.addCell(label18);
sheet1.addCell(label19);
sheet1.addCell(label20);
sheet1.addCell(label21);
/**
* 所有后院的数据
*/
HashMap aaMap = new HashMap();
int excelIndex = 1;
for (int i = 1; i < sheet.getRows(); i++) {
/**
* 单个后院的数据
*/
HashMap data = new HashMap();
// 后院数据
Long shopId = Long
.parseLong(sheet.getCell(0, i).getContents() != null ? sheet
.getCell(0, i).getContents() : "0");
String nick = sheet.getCell(1, i).getContents();
String userId = sheet.getCell(2, i).getContents();
String credit = sheet.getCell(3, i).getContents();
String siteId = sheet.getCell(4, i).getContents();
String cat = sheet.getCell(5, i).getContents();
String favor = sheet.getCell(6, i).getContents();
//String tag5 = sheet.getCell(7, i).getContents();
String siteType="";
if("2".equals(siteId)){
siteType="商城";
}else{
siteType="集市";
}
// step01: 后院基本数据
data.put("shopId", shopId);
data.put("nick", nick);
data.put("userId", userId);
data.put("credit", credit);
data.put("siteId", siteType);
data.put("cat", cat);
data.put("favor", favor);
//data.put("tag5", tag5);
data = getArticleActivityShaidan(shopId, data, xbMap, hdMap, axMap);
aaMap.put(shopId, data);
System.out.println("活动: " + excelIndex);
excelIndex++;
}
int bbIndex = 1;
Iterator aaiterator=aaMap.entrySet().iterator();
while(aaiterator.hasNext()){
Map.Entry entry=(Map.Entry)aaiterator.next();
System.out.println(entry.getKey()+" , "+entry.getValue());
HashMap outMap = (HashMap) entry.getValue();
Label aalabel1 = new Label(0, bbIndex, String.valueOf(entry.getKey()));
Label aalabel2 = new Label(1, bbIndex, String.valueOf(outMap.get("nick")));
Label aalabel3 = new Label(2, bbIndex, String.valueOf(outMap.get("userId")));
Label aalabel4 = new Label(3, bbIndex, String.valueOf(outMap.get("credit")));
Label aalabel5 = new Label(4, bbIndex, String.valueOf(outMap.get("siteId")));
Label aalabel6 = new Label(5, bbIndex, String.valueOf(outMap.get("cat")));
Label aalabel7 = new Label(6, bbIndex, String.valueOf(outMap.get("xbCount")));
Label aalabel8 = new Label(7, bbIndex, String.valueOf(outMap.get("xbFavor")));
Label aalabel9 = new Label(8, bbIndex, String.valueOf(outMap.get("xbShare")));
Label aalabel10 = new Label(9, bbIndex, String.valueOf(outMap.get("xbComment")));
Label aalabel11 = new Label(10, bbIndex, String.valueOf(outMap.get("hdCount")));
Label aalabel12 = new Label(11, bbIndex, String.valueOf(outMap.get("activityCount")));
Label aalabel13 = new Label(12, bbIndex, String.valueOf(outMap.get("hdFavor")));
Label aalabel14 = new Label(13, bbIndex, String.valueOf(outMap.get("hdShare")));
Label aalabel15 = new Label(14, bbIndex, String.valueOf(outMap.get("hdComment")));
Label aalabel16 = new Label(15, bbIndex, String.valueOf(outMap.get("axCount")));
Label aalabel17 = new Label(16, bbIndex, String.valueOf(outMap.get("axFavor")));
Label aalabel18 = new Label(17, bbIndex, String.valueOf(outMap.get("axShare")));
Label aalabel19 = new Label(18, bbIndex, String.valueOf(outMap.get("axComment")));
Label aalabel20 = new Label(19, bbIndex, String.valueOf(outMap.get("favor")));
//Label aalabel21 = new Label(20, bbIndex, String.valueOf(outMap.get("tag5")));
sheet1.addCell(aalabel1);
sheet1.addCell(aalabel2);
sheet1.addCell(aalabel3);
sheet1.addCell(aalabel4);
sheet1.addCell(aalabel5);
sheet1.addCell(aalabel6);
sheet1.addCell(aalabel7);
sheet1.addCell(aalabel8);
sheet1.addCell(aalabel9);
sheet1.addCell(aalabel10);
sheet1.addCell(aalabel11);
sheet1.addCell(aalabel12);
sheet1.addCell(aalabel13);
sheet1.addCell(aalabel14);
sheet1.addCell(aalabel15);
sheet1.addCell(aalabel16);
sheet1.addCell(aalabel17);
sheet1.addCell(aalabel18);
sheet1.addCell(aalabel19);
sheet1.addCell(aalabel20);
//sheet1.addCell(aalabel21);
bbIndex++;
}
// 表格: 将创建的内容写入到输出流之中
workbook.write();
workbook.close();
outStream.close();
}
/**
* 从article.xls、huodong.xls、shaidan.xls三个表中获取这个后院的数据
*
* @param shopId
* @throws Exception
*/
public static HashMap getArticleActivityShaidan(Long shopId, HashMap data,
HashMap xbMap, HashMap hdMap, HashMap axMap)
throws Exception {
Long userId = Long.parseLong((String) data.get("userId"));
HashMap xbData = (HashMap) xbMap.get(userId);
HashMap hdData = (HashMap) hdMap.get(shopId);
HashMap axData = (HashMap) axMap.get(userId);
// step02: 小报数据
data.put("xbCount", xbData!=null&&xbData.get("num")!=null?xbData.get("num"):0);
data.put("xbFavor", xbData!=null&&xbData.get("favor")!=null?xbData.get("favor"):0);
data.put("xbShare", xbData!=null&&xbData.get("share")!=null?xbData.get("share"):0);
data.put("xbComment", xbData!=null&&xbData.get("comment")!=null?xbData.get("comment"):0);
// step03: 活动数据
data.put("hdCount", hdData!=null&&hdData.get("num")!=null?hdData.get("num"):0);
data.put("activityCount", hdData!=null&&hdData.get("activityCount")!=null?hdData.get("activityCount"):0);
data.put("hdFavor", hdData!=null&&hdData.get("favor")!=null?hdData.get("favor"):0);
data.put("hdShare", hdData!=null&&hdData.get("share")!=null?hdData.get("share"):0);
data.put("hdComment", hdData!=null&&hdData.get("comment")!=null?hdData.get("comment"):0);
// step04: 晒单数据
data.put("axCount", axData!=null&&axData.get("num")!=null?axData.get("num"):0);
data.put("axFavor", axData!=null&&axData.get("favor")!=null?axData.get("favor"):0);
data.put("axShare", axData!=null&&axData.get("share")!=null?axData.get("share"):0);
data.put("axComment", axData!=null&&axData.get("comment")!=null?axData.get("comment"):0);
return data;
}
/**
* 一个后院的活动数据
*
* @param sheet
* @return
* @throws IOException
*/
public static HashMap getActivitySheet(Sheet sheet) throws IOException {
HashMap aaMap = new HashMap();
for (int i = 1; i < sheet.getRows(); i++) {
/**
* 表格二
*
*/
HashMap data = new HashMap();
Long shopId = Long
.parseLong(sheet.getCell(0, i).getContents() != null ? sheet
.getCell(0, i).getContents() : "0");
String favorCount = "0";
if (sheet.getCell(3, i).getContents() != null) {
favorCount = ("\\N".equals(sheet.getCell(3, i).getContents())) ? "0"
: sheet.getCell(3, i).getContents();
}
data.put("favor", Integer.parseInt(favorCount));
String shareCount = "0";
if (sheet.getCell(4, i).getContents() != null) {
shareCount = ("\\N".equals(sheet.getCell(4, i).getContents())) ? "0"
: sheet.getCell(4, i).getContents();
}
data.put("share", Integer.parseInt(shareCount));
String commentCount = "0";
if (sheet.getCell(5, i).getContents() != null) {
commentCount = ("\\N".equals(sheet.getCell(5, i).getContents())) ? "0"
: sheet.getCell(5, i).getContents();
}
data.put("comment", Integer.parseInt(commentCount));
HashMap aaaMap = (HashMap) JsonUtil.parseJson(sheet.getCell(6, i)
.getContents(), HashMap.class);
int activityCount = 0;
if (aaaMap.get("activityCount") != null) {
if (aaaMap.get("activityCount") instanceof Integer) {
activityCount = (Integer) aaaMap.get("activityCount");
} else if (StringUtil.isNumeric((String) aaaMap
.get("activityCount"))) {
activityCount = Integer.parseInt((String) aaaMap
.get("activityCount"));
}
}
data.put("activityCount", activityCount);
data.put("num", 1);
if (aaMap.get(shopId) != null) {
HashMap tmpMap = (HashMap) aaMap.get(shopId);
Integer totalFavor = (Integer) data.get("favor")
+ (Integer) tmpMap.get("favor");
Integer totalShare = (Integer) data.get("share")
+ (Integer) tmpMap.get("share");
Integer totalComment = (Integer) data.get("comment")
+ (Integer) tmpMap.get("comment");
Integer totalActivityCount = (Integer) data
.get("activityCount")
+ (Integer) tmpMap.get("activityCount");
Integer totalNum = (Integer) data.get("num")
+ (Integer) tmpMap.get("num");
data.put("favor", totalFavor);
data.put("share", totalShare);
data.put("comment", totalComment);
data.put("activityCount", totalActivityCount);
data.put("num", totalNum);
}
aaMap.put(shopId, data);
}
return aaMap;
}
/**
* 一个后院的小报数据
*
* @param xbsheet
* @param data
* @param aaMap
*/
public static HashMap getArticleSheet(Sheet xbsheet) {
HashMap aaMap = new HashMap();
for (int i = 1; i < xbsheet.getRows(); i++) {
HashMap data = new HashMap();
Long userId = Long
.parseLong(xbsheet.getCell(0, i).getContents() != null ? xbsheet
.getCell(0, i).getContents() : "0");
String favorCount = "0";
if (xbsheet.getCell(3, i).getContents() != null) {
favorCount = ("\\N".equals(xbsheet.getCell(3, i).getContents())) ? "0"
: xbsheet.getCell(3, i).getContents();
}
data.put("favor", Integer.parseInt(favorCount));
String shareCount = "0";
if (xbsheet.getCell(4, i).getContents() != null) {
shareCount = ("\\N".equals(xbsheet.getCell(4, i).getContents())) ? "0"
: xbsheet.getCell(4, i).getContents();
}
data.put("share", Integer.parseInt(shareCount));
String commentCount = "0";
if (xbsheet.getCell(5, i).getContents() != null) {
commentCount = ("\\N".equals(xbsheet.getCell(5, i)
.getContents())) ? "0" : (StringUtil.isNumeric(xbsheet
.getCell(5, i).getContents())) ? xbsheet.getCell(5, i)
.getContents() : "0";
}
data.put("comment", Integer.parseInt(commentCount));
data.put("num", 1);
if (aaMap.get(userId) != null) {
HashMap tmpMap = (HashMap) aaMap.get(userId);
Integer totalFavor = (Integer) data.get("favor")
+ (Integer) tmpMap.get("favor");
Integer totalShare = (Integer) data.get("share")
+ (Integer) tmpMap.get("share");
Integer totalComment = (Integer) data.get("comment")
+ (Integer) tmpMap.get("comment");
Integer totalNum = (Integer) data.get("num")
+ (Integer) tmpMap.get("num");
data.put("favor", totalFavor);
data.put("share", totalShare);
data.put("comment", totalComment);
data.put("num", totalNum);
}
aaMap.put(userId, data);
}
return aaMap;
}
/**
* 根据文件path,读取excel中的数据
*
* @param path
* @param index
* 工作区的index
* @return
* @throws Exception
*/
public static Sheet getWorkBook(String path, Integer index)
throws Exception {
File file = new File(path);
Workbook workbook = Workbook.getWorkbook(file);
if (index == null) {
index = 0;
}
Sheet sheet = workbook.getSheet(index);
return sheet;
}
public static String getCurrentDate() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -1);
DateFormat SIMPLE_DATA_FORMAT = new SimpleDateFormat("yyyyMMdd");
return SIMPLE_DATA_FORMAT.format(cal.getTime());
}
}
<file_sep>/src/main/java/mengka/print/SystemIn.java
package mengka.print;
import java.util.Scanner;
public class SystemIn {
public static void main(String[] args) {
System.out.println("اëتنبë£؛");
Scanner in = new Scanner(System.in);
System.out.print("ؤمتنبëµؤتا£؛"+in.nextLine());
}
}
<file_sep>/src/main/java/mengka/mail/excel/csv/CsvUtil.java
package mengka.mail.excel.csv;
import java.nio.charset.Charset;
import java.util.ArrayList;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
public class CsvUtil {
/**
* 将数据写出到csv文件
*
* @param outPath
* @param list
* @throws Exception
*/
public static void writeCsvFile(String outPath,ArrayList<String[]> list,String charset) throws Exception{
CsvWriter write =new CsvWriter(outPath,',',Charset.forName("gbk"));
for(String[] oneDatas:list){
write.writeRecord(oneDatas);
}
write.close();
}
/**
* 读取csv表格文件
*
* @param path csv文件路径
* @param charset 编码格式
* @return
* @throws Exception
*/
public static ArrayList<String[]> readCSVFile(String path,String charset) throws Exception {
ArrayList<String[]> csvList = new ArrayList<String[]>(); // 用来保存数据
String csvFilePath = path;
CsvReader reader = new CsvReader(csvFilePath, ',',Charset.forName(charset));
reader.readHeaders();
while (reader.readRecord()) {
csvList.add(reader.getValues());
}
reader.close();
return csvList;
}
}
<file_sep>/src/main/java/mengka/random_01/aa.java
package mengka.random_01;
public class aa {
/**
* @param args
*/
public static void main(String[] args) {
int[] indexs = getRanRewardResult(10, 7);
for (int i : indexs) {
System.out.println("i = "+i);
}
}
/**
* 获取随机的中奖结果
*
* @param listNum
* @param count
* 返回结果个数
* @return
*/
public static int[] getRanRewardResult(int listNum, long count) {
int[] aaRan = new int[listNum];
for (int i = 0; i < listNum; i++) {
aaRan[i] = i;
}
int[] resultRan = new int[(int) count];
for (int i = 0; i < count; i++) {
resultRan[i] = (int) (Math.random() * (listNum - i) + 1);
int temp = aaRan[listNum - i - 1];
aaRan[listNum - i - 1] = aaRan[resultRan[i] - 1];
aaRan[resultRan[i] - 1] = temp;
}
for (int i = 0; i < count; i++) {
resultRan[i] = aaRan[listNum - 1 - i];
}
return resultRan;
}
}
<file_sep>/src/main/java/mengka/map2URLQuery/map2URLquery_01.java
package mengka.map2URLQuery;
import java.util.HashMap;
/**
* 将map变成一个URL查询串:<br>
* 【例】:area=1111&id=044101331
*
* @author mengka.hyy
*
*/
public class map2URLquery_01 {
public static HashMap<String, String> aaMap=new HashMap<String, String>();
static{
aaMap.put("id", "044101331");
aaMap.put("area", "1111");
}
/**
* @param args
*/
public static void main(String[] args) {
String aaString = MapUtil.changeMapToQueryString(aaMap, "gbk");
System.out.println(aaString);
}
}
<file_sep>/src/main/java/mengka/sohu_01/Taa.java
package mengka.sohu_01;
import com.mengka.common.StringUtils;
public class Taa {
/**
* @param args
*/
public static void main(String[] args) {
String aaString = "10000001";
String sidString = getSidRoomId(aaString);
System.out.println(sidString);
}
public static String getSidRoomId(String roomId){
if(StringUtils.isBlank(roomId)){
return "00000000";
}
int maxLength = 8;
int length = roomId.length();
int zero = maxLength - length;
if(zero<0){
return "00000000";
}
char[] result = new char[8];
for (int i = 0; i < maxLength; i++) {
if(i<zero){
result[i] = '0';
}else{
char tmp = roomId.charAt(i-zero);
result[i] = tmp;
}
}
return new String(result);
}
}
<file_sep>/src/main/java/mengka/password_01/password_01.java
package mengka.password_01;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha256Hash;
/**
* Created by xiafeng
* on 2015/5/7.
*/
public class password_01 {
private static RandomNumberGenerator rng = new SecureRandomNumberGenerator();
public static void main(String[] args)throws Exception{
String password = "<PASSWORD>";
Object salt = rng.nextBytes();
String hashedPasswordBase64 = new Sha256Hash(password, salt.toString(), 1024).toBase64();
System.out.println("hashedPasswordBase64 = "+hashedPasswordBase64);
}
}
<file_sep>/src/main/java/mengka/json/Mengka.java
package mengka.json;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Mengka implements Serializable{
public Long userId;
public String nick;
public String shopUrl;
public String xuanyan;
public String weibo;
public String bangpai;
public String douban;
public String renren;
public String getRenren() {
return renren;
}
public void setRenren(String renren) {
this.renren = renren;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public String getShopUrl() {
return shopUrl;
}
public void setShopUrl(String shopUrl) {
this.shopUrl = shopUrl;
}
public String getXuanyan() {
return xuanyan;
}
public void setXuanyan(String xuanyan) {
this.xuanyan = xuanyan;
}
public String getWeibo() {
return weibo;
}
public void setWeibo(String weibo) {
this.weibo = weibo;
}
public String getBangpai() {
return bangpai;
}
public void setBangpai(String bangpai) {
this.bangpai = bangpai;
}
public String getDouban() {
return douban;
}
public void setDouban(String douban) {
this.douban = douban;
}
}<file_sep>/src/main/java/mengka/class_01/InnerClass_01.java
package mengka.class_01;
/**
* 匿名内部类:
* <ul>
* <li>是一个特殊的局部内部类,他没有类的名字;【局部内部类:定义在一个方法里面的内部类】</li>
* <li></li>
* </ul>
*
* @author mengka.hyy
*
*/
public class InnerClass_01 {
private String aaString = "test private String";
/**
* @param args
*/
public static void main(String[] args) {
InnerClass_01 innerClass = new InnerClass_01();
innerClass.inner();
}
public void inner(){
final String baicai = "baicai";
String qingcai = "qingcai";
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
System.out.println("匿名内部类。。"+aaString);
/**
* 【匿名内部类访问外部类中的局部变量必须是final属性】
* 因为局部变量的范围被限制在该方法内,当一个方法结束时,栈结构被删除,该变量消失。但是,定义在这个类中的内部类对象仍然存活在堆上,所以内部类对象不能使用局部变量。除非这些局部变量被标识为最终final的就可以。
*/
System.out.println("baicai = "+baicai);
// System.out.println("qingcai = "+qingcai);//编译报错
}});
t1.start();
}
}
<file_sep>/src/main/java/mengka/downloadPic/DownByUrl.java
package mengka.downloadPic;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class DownByUrl {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File f = new File("src\\mengka\\downloadPic\\pic.txt");
InputStream st = null;
try {
st = new FileInputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner in = new Scanner(st);
int n=0;
while (in.hasNext()) {
String[] aaString = in.nextLine().split("\t");
String techanName = aaString[0];
String techanUrl = aaString[1];
try {
// URL url = new URL(
// "http://img02.taobaocdn.com/imgextra/i2/50759571/T24Hp7XXRaXXXXXXXX_!!50759571.jpg");
// File outFile = new File("Y:/newDownload/0001.jpg");
URL url = new URL(techanUrl);
File outFile = new File("D:/newDownload/" + techanName + ".jpg");
//判断文件是否已经存在
boolean b=true;
b=outFile.exists();
if(b){
System.out.println(techanName+"="+b+",已经存在");
continue;
}
OutputStream os = new FileOutputStream(outFile);
InputStream is = url.openStream();
byte[] buff = new byte[1024];
while (true) {
int readed = is.read(buff);
if (readed == -1) {
break;
}
byte[] temp = new byte[readed];
// 复制读取到的图片信息字节
System.arraycopy(buff, 0, temp, 0, readed);
// 写到本地 “outFile”
os.write(temp);
}
System.out.println(techanName);
n++;
is.close();
os.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
System.out.println("下载的图片个数:"+n);
}
}
<file_sep>/README.md
mengka
======<file_sep>/src/main/java/mengka/http/GetHttpByJava.java
package mengka.http;
import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import mengka.noblank.Notblank_langs;
/**
* 用java最原始的方法获取请求中的数据, teach by chengze
*
* @author mengka
*
*/
public class GetHttpByJava {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String pString = "20759";
String vString = "30506";
String catString = "50002766";
boolean kk = get3ProductDoByTbskip(pString, vString, catString);
System.out.println(kk);
/***********************************/
/**
* 返回的商品个数 : psize=3 <br>
* 地域PV对 : pid:vid <br>
* 类目cat : catid <br>
* 是否随机排列:random=1<br>
* 取几天内的数据:period=1<br>
*
*/
/*
* // 类目+地域 String urlString1 =
* "http://tbskip.taobao.com/json/paihangbang.do?show_type=3&period=1&weidu=0&type=0&catid="
* + catString + "&pid=" + pString + "&vid=" + vString +
* "&psize=3&ft=1"; // 类目 String urlString2 =
* "http://tbskip.taobao.com/json/paihangbang.do?show_type=3&period=1&weidu=0&type=0&catid="
* + catString + "&psize=3&ft=1"; // 地域 String CAT_CONSTANT =
* "5000276650016422"; String urlString3 =
* "http://tbskip.taobao.com/json/paihangbang.do?show_type=3&period=1&weidu=0&type=0&catid="
* + CAT_CONSTANT + "&pid=" + pString + "&vid=" + vString +
* "&psize=3&ft=1"; String aaString = getWebContent(urlString1);
* System.out.println(urlString1); System.out.println(aaString);
*
* int aaIndex = aaString.indexOf("msg");
* System.out.println("aaIndex = " + aaIndex); if (aaIndex != -1) {
* String bbString = aaString.substring(aaIndex);
* if(bbString.contains("请求成功")){ String[]
* kkStrings=bbString.split(","); for(String kkString : kkStrings){
* if(kkString.contains("brandid")){ String[]
* ddStrings=kkString.split(":"); String
* slpIdString=ddStrings[ddStrings.length-1];
* System.out.println("slpIdString="+slpIdString); } } } }
*/
/*********************************/
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private static boolean get3ProductDoByTbskip(String pString,
String vString, String catString) {
try {
String urlString = "";
if (null != pString && null != vString && null != catString) {
// 类目+地域
urlString = "http://tbskip.taobao.com/json/paihangbang.do?show_type=3&period=1&weidu=0&type=0&catid="
+ catString
+ "&pid="
+ pString
+ "&vid="
+ vString
+ "&psize=3&ft=1";
} else if (null != catString) {
// 类目
urlString = "http://tbskip.taobao.com/json/paihangbang.do?show_type=3&period=1&weidu=0&type=0&catid="
+ catString + "&psize=3&ft=1";
} else if (null != pString && null != vString) {
// 地域
String CAT_CONSTANT = "5000276650016422";
urlString = "http://tbskip.taobao.com/json/paihangbang.do?show_type=3&period=1&weidu=0&type=0&catid="
+ CAT_CONSTANT
+ "&pid="
+ pString
+ "&vid="
+ vString
+ "&psize=3&ft=1";
}
if (Notblank_langs.isNotBlank(urlString)) {
String aaString = getWebContent(urlString, "gbk", 5000);
int aaIndex = aaString.indexOf("msg");
System.out.println("aaIndex = " + aaIndex);
if (aaIndex != -1) {
String bbString = aaString.substring(aaIndex);
if (bbString.contains("请求成功")) {
String[] kkStrings = bbString.split(",");
for (String kkString : kkStrings) {
if (kkString.contains("brandid")) {
String[] ddStrings = kkString.split(":");
String slpIdString = ddStrings[ddStrings.length - 1];
//log.error("");
System.out
.println("slpIdString=" + slpIdString);
}
}
return true;
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false;
}
/**
*
* 利用java自带的方法,读取URL中的信息
*
*/
public static String getWebContent(String urlString, final String charset,
int timeout) throws IOException {
if (urlString == null || urlString.length() == 0) {
return null;
}
urlString = (urlString.startsWith("http://") || urlString
.startsWith("https://")) ? urlString : ("http://" + urlString)
.intern();
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");// 增加报头,模拟浏览器,防止屏蔽
conn.setRequestProperty("Accept", "text/html");// 只接受text/html类型,当然也可以接受图片,pdf,*/*任意,就是tomcat/conf/web里面定义那些
conn.setConnectTimeout(timeout);
try {
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
} catch (IOException e) {
e.printStackTrace();
// logStringBuilder.append("\n"+e+"\n");
return null;
}
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input,
charset));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\r\n");
}
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
return sb.toString();
}
// public static String getWebContent(String urlString) throws IOException {
// return getWebContent(urlString, "gbk", 5000);
// }
}
<file_sep>/src/main/java/mengka/zhengze_03/zhengze_03.java
package mengka.zhengze_03;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
/**
* 跳出一个页面hyy044101331.htm中的所有的href链接
*
* @author mengka.hyy
*
*/
public class zhengze_03 {
/**
* @param args
*/
public static void main(String[] args) {
String path = "src//main//java//mengka//zhengze_03//hyy044101331.htm";
String aaString = mkFileAllRead(path);
/**
* "\\."用来匹配正则中的小数点
* "."在正则中,代表的是任意的字符
*/
String testString = "href=\"https://www.taobao.com";
Pattern pattern = Pattern
.compile("href=\"([http://|https://].*\\.com)");
Matcher matcher = pattern.matcher(aaString);
int count = 0;
while(matcher.find()){
String bbString = matcher.group(1);
if(StringUtils.isNotBlank(bbString)){
count ++;
System.out.println("["+count+"] = "+bbString);
}
}
}
/**
* 读取整个文件
*
* @param pathString
* 文件的输入路径
*/
public static String mkFileAllRead(String pathString) {
String kkString = "";
StringBuffer stringBuffer = new StringBuffer();
try {
InputStreamReader inputStreamReader = new InputStreamReader(
new FileInputStream(pathString));
BufferedReader brReader = new BufferedReader(inputStreamReader);
stringBuffer = new StringBuffer();
int str;
while ((str = brReader.read()) != -1) {
stringBuffer.append((char) str);
}
kkString = stringBuffer.toString();
} catch (Exception e) {
kkString = e.toString();
}
return kkString;
}
}
<file_sep>/src/main/java/mengka/time_02/Taa.java
package mengka.time_02;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/**
* 世界时间转化成北京时间
*
* 世界时间:2014-06-12T20:00:00.000Z
* 北京时间:2014-06-13 04:00:00
*
* 6月13日,凌晨4点,巴西vs克罗地亚
*
* @author mengka.hyy
*
*/
public class Taa {
/**
* @param args
*/
public static void main(String[] args) {
DateTimeFormatter format = DateTimeFormat .forPattern("yyyy-MM-dd'T'HH:mm:ss.sssZ");
DateTime dateTime = DateTime.parse("2014-06-12T20:00:00.000Z", format);
String aaString = dateTime.toString("yyyy-MM-dd HH:mm:ss");
System.out.println(aaString);
}
}
<file_sep>/src/main/java/mengka/time_02/Tbb.java
package mengka.time_02;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.mengka.common.TimeUtil;
public class Tbb {
private static Log logger = LogFactory.getLog(Tbb.class);
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("date = "+getWeekOfDate(new Date()));
boolean isWorkDay = isWorkDay(new Date());
System.out.println("是不是工作日, isWorkDay = "+isWorkDay);
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(calendar.DATE, 0);
Date time = calendar.getTime();
Date time2 = getDeadLine(time);
System.out.println("time2 = "+TimeUtil.toDate(time2, TimeUtil.format_1));
//当前月的最后一天是几号
Calendar c=Calendar.getInstance();
c.setTime(new Date());
int lastday=c.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("这个月最后一天是:"+lastday+"号");
}
public static boolean isWorkDay(Date date){
boolean isWorkDay = false;
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0){
w = 0;
}
if(1<=w&&w<=5){
isWorkDay = true;
}
return isWorkDay;
}
/**
* 获取当前日期是星期几
*
* @param date
* @return 当前日期是星期几
*/
public static String getWeekOfDate(Date date) {
String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}
/**
* 票据: 到期日期=承兑日期+3个工作日
*
* @return
*/
public static Date getDeadLine(Date acceptDate){
Date deadline = acceptDate;
try{
int count = 0;
while(count<3){
Calendar calendar = Calendar.getInstance();
calendar.setTime(deadline);
calendar.add(calendar.DATE, 1);
deadline = calendar.getTime();
if(isWorkDay(deadline)){
count++;
}
}
}catch (Exception e){
logger.error("getPaymentDate error!",e);
}
return deadline;
}
}
<file_sep>/src/main/java/mengka/zhengze_02/timu_02.java
package mengka.zhengze_02;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* java基础题目②:
* 2. 利用正则表达式,取出商品id; http://item.daily.taobao.net/item.htm?id=1500025776090 (打印出1500025776090)
*
* @author mengka.hyy
*
*/
public class timu_02 {
public static void main(String[] args) {
String url = "http://item.daily.taobao.net/item.htm?id=1500025776090";
String id = getItemFromURL(url);
System.out.println("id = "+id);
}
public static String getItemFromURL(String urlString) {
Pattern pattern = Pattern.compile("[&|?]id=([0-9]+)&?");
Matcher matcher = pattern.matcher(urlString);
if (matcher.find()) {
String auctionId = matcher.group(1);//返回第一个匹配结果
return auctionId;
}
return null;
}
}
<file_sep>/src/main/java/mengka/downloadPic/MysqlDB.java
package mengka.downloadPic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MysqlDB {
static Connection con = null; // 连接对象
static Statement sql = null; // Statement对象(SQL语句)
static ResultSet rs = null; // 结果集对象
/**
* 链接数据库
*/
public static void connect() {
try {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
}
try {
con = DriverManager
.getConnection(
"jdbc:mysql://127.0.0.1:3306/mengka?characterEncoding=GB2312",
"root", "544027354");// 连接数据库的url 用户名和密码
if (!con.isClosed()) {
System.out.println("数据库连接成功");
}
sql = con.createStatement();
// String
// to="Select * From BaiduFood Where productId='"+productName+"'";
} catch (SQLException e) {
System.out.print(e);
}
}
/**
* 20111103 更新 卖家图片链接 到 TFS —— 插入特产数据
*
* @param productId
* @param productName
* @param shengName
* @param shiName
*/
public static void insertToTempaa(String productId, String productName,
String picStr) {
String to = "insert into tempaa(productId,productName,picUrl) VALUES('"
+ productId + "','" + productName + "','" + picStr + "')";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 20111103 更新 卖家图片链接 到 TFS —— 更新链接
*
* @param productName
* @param picStr
*/
public static void updateTFSPicStrByName(String productName, String picStr) {
String to = "UPDATE `tempaa` set picUrl='" + picStr
+ "' WHERE productName='" + productName + "'";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void updateWordsById(long productId, String words) {
String to = "UPDATE `producttable` set words='" + words
+ "' WHERE productId='" + productId + "'";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void updateWordsByName(String productName, String words) {
String to = "UPDATE `producttable` set words='" + words
+ "' WHERE productName='" + productName + "'";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 淘宝网上该特产的个数
*
* @param productName
* @param productNum
*/
public static void updateProductNumByName(String productName,
long productNum) {
String to = "UPDATE `producttable` set productNum='" + productNum
+ "' WHERE productName='" + productName + "'";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 淘宝网上该特产的个数(重载)
*
* @param productName
* @param productNum
*/
public static void updateProductNumByName(String productName,
String productNum) {
String to = "UPDATE `producttable` set productNum='" + productNum
+ "' WHERE productName='" + productName + "'";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 最多特产的类目
*
* @param productName
* @param productNum
*/
public static void updateCatNameByName(String productName, String catName) {
String to = "UPDATE `producttable` set catName='" + catName
+ "' WHERE productName='" + productName + "'";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 最多类目下,的特产个数
*
* @param productName
* @param productNum
*/
public static void updateCatCountByName(String productName, long catCount) {
String to = "UPDATE `producttable` set catCount='" + catCount
+ "' WHERE productName='" + productName + "'";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 最多类目下,的特产个数(重载)
*
* @param productName
* @param productNum
*/
public static void updateCatCountByName(String productName, String catCount) {
String to = "UPDATE `producttable` set catCount='" + catCount
+ "' WHERE productName='" + productName + "'";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void updatePicurlByName(String productName, String picurl) {
String to = "UPDATE `producttable` set picurl='" + picurl
+ "' WHERE productName='" + productName + "'";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void updatePName(long productId, String productName) {
String to = "UPDATE `producttable` set productName='" + productName
+ "' WHERE productId='" + productId + "'";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void updatePName(String productId, String productName) {
String to = "UPDATE `producttable` set productName='" + productName
+ "' WHERE productId='" + productId + "'";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void update(long productId, String productName, String words) {
String to = "UPDATE `producttable` set productName='" + productName
+ "' WHERE productId='" + productId + "';";
to = to + "UPDATE `producttable` set words='" + words
+ "' WHERE productId='" + productId + "'";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void insert(long productId, String productName, String words) {
String to = "insert into producttable(productId,productName,words) VALUES('"
+ productId + "','" + productName + "','" + words + "')";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void insert(String productId, String productName,
String shengName, String shiName) {
String to = "insert into producttable(productId,productName,shengName,shiName) VALUES('"
+ productId
+ "','"
+ productName
+ "','"
+ shengName
+ "','"
+ shiName + "')";
try {
int tt = sql.executeUpdate(to);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 根据特产name,获取特产的词条
*
* @param productName
* 特产name
* @return 特产ID对应的特产的词条
*/
public String getWordsByName(String productName) {
String to = "SELECT * FROM producttable where productName='"
+ productName + "'";
try {
rs = sql.executeQuery(to);
while (rs.next()) {
if (null != rs && null != rs.getString(3)) {
return rs.getString(3);
}
}
} catch (SQLException e) {
e.printStackTrace();
} // 根据所定义的Statement执行生成相应的结果集并存在RS中
return null;
}
/**
* 根据特产ID,获取特产的词条
*
* @param productId
* 特产ID
* @return 特产ID对应的特产的词条
*/
public String getWordsById(String productId) {
String to = "SELECT * FROM producttable where productId='" + productId
+ "'";
try {
rs = sql.executeQuery(to);
while (rs.next()) {
if (null != rs && null != rs.getString(3)) {
return rs.getString(3);
}
}
} catch (SQLException e) {
e.printStackTrace();
} // 根据所定义的Statement执行生成相应的结果集并存在RS中
return null;
}
public String getWordsById(long productId) {
String to = "SELECT * FROM producttable where productId='" + productId
+ "'";
try {
rs = sql.executeQuery(to);
while (rs.next()) {
if (null != rs && null != rs.getString(3)) {
return rs.getString(3);
}
}
} catch (SQLException e) {
e.printStackTrace();
} // 根据所定义的Statement执行生成相应的结果集并存在RS中
return null;
}
/**
* 根据特产ID,获取特产的词条
*
* @param productId
* 特产ID
* @return 特产ID对应的特产的词条
*/
public String getNameById(String productId) {
String to = "SELECT * FROM producttable where productId='" + productId
+ "'";
try {
rs = sql.executeQuery(to);
while (rs.next()) {
if (null != rs && null != rs.getString(2)) {
return rs.getString(2);
}
}
} catch (SQLException e) {
e.printStackTrace();
} // 根据所定义的Statement执行生成相应的结果集并存在RS中
return null;
}
public String getNameById(long productId) {
String to = "SELECT * FROM producttable where productId='" + productId
+ "'";
String pp = "";
try {
rs = sql.executeQuery(to);
while (rs.next()) {
if (null != rs && null != rs.getString(2)) {
return rs.getString(2);
}
}
} catch (SQLException e) {
e.printStackTrace();
} // 根据所定义的Statement执行生成相应的结果集并存在RS中
return null;
}
/**
* 显示数据库中所有的数据
*/
public static void get() {
try {
String to = "SELECT * FROM tempAA";
rs = sql.executeQuery(to);
while (rs.next()) {
System.out.println("productId = " + rs.getString(1));
System.out.println("productName = " + rs.getString(2));
System.out.println("words = " + rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 是否含有该特产
*/
public static boolean haveProductByName(String productName) {
try {
String to = "SELECT productId FROM producttable where productName='"
+ productName + "'";
rs = sql.executeQuery(to);
if (rs.next() && null != rs.getString(1)) {
return true;
} else {
return false;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* 是否含有该特产
*/
public static boolean haveProductById(String productId) {
try {
String to = "SELECT productId FROM producttable where productId='"
+ productId + "'";
rs = sql.executeQuery(to);
if (rs.next() && null != rs.getString(1)) {
return true;
} else {
return false;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* 关闭数据库连接
*/
public static void close() {
try {
if (rs != null) {
rs.close();
}
if (sql != null) {
sql.close();
}
if (con != null) {
con.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
connect();
// updateWords((long)777,"纷纷");
get();
close();
}
}
<file_sep>/src/main/java/mengka/fileList/time_01/showAllFile.java
package mengka.fileList.time_01;
import java.io.File;
import java.util.Date;
import com.mengka.common.TimeUtil;
/**
* 显示所有文件的最后修改时间
*
*
* @author mengka.hyy
*
*/
public class showAllFile {
public static void main(String[] args) {
String path = "/Users/hyy044101331/work_hyy/mengka/src/main/java/mengka/fileList/test";
getAllFileList(path);
}
/**
* 获取路径path下的文件的最后修改时间
*
* @param path
*/
public static void getAllFileList(String path) {
File file = new File(path);
int index = 1;
for (File tmpFile : file.listFiles()) {
if (tmpFile.canRead()) {
String lastModified = TimeUtil.toDate(
new Date(tmpFile.lastModified()), TimeUtil.format_1);
System.out.println("-------, path = "+tmpFile.getAbsolutePath());
System.out.println("--------, n = " + index
+ " , File.getName() = " + tmpFile.getName()
+ " , lastModified = " + lastModified);
index++;
}
}
}
}
<file_sep>/src/main/java/mengka/list/ArrayList_01.java
package mengka.list;
import java.util.Arrays;
import java.util.List;
public class ArrayList_01 {
/**
* @param args
*/
public static void main(String[] args) {
List<String> aaList = (List<String>) Arrays.asList("10.232.12.32", "10.232.10.23", "10.232.102.183", "10.232.102.182");
for(Object aaString:aaList){
System.out.println(aaString);
}
}
}
<file_sep>/src/main/java/mengka/fileclass/MoveFile_01.java
package mengka.fileclass;
import java.io.FileNotFoundException;
import java.io.*;
/**
* 移动文件位置
*
* @author mengka
*
*/
public class MoveFile_01 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String aaString="G:\\yunpan\\work_hyy\\unicode\\src\\mengka\\fileclass\\aa.txt";
String bbString="G:\\yunpan\\work_hyy\\unicode\\src\\mengka\\fileclass\\bb.txt";
mvFile(aaString,bbString);
}
/**
* 移动文件
*
* @param oldPath
* @param newPath
*/
public static void mvFile(String oldPath, String newPath) {
try {
int byteRead = 0;
File oldFile = new File(oldPath);
FileOutputStream fos = new FileOutputStream(new File(newPath));
FileInputStream fis = new FileInputStream(oldFile);
byte[] buffer = new byte[1444];
while ((byteRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, byteRead);
}
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
oldFile.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/mengka/fileclass/File_01.java
package mengka.fileclass;
import java.io.*;
public class File_01 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* File对象 的基本属性信息
*
*/
File aaFile = new File(
"G:\\yunpan\\work_hyy\\unicode\\src\\mengka\\fileclass\\Book1.txt");
System.out.println("File.getName() = " + aaFile.getName());
System.out.println("file.getAbsolutePath() = "
+ aaFile.getAbsolutePath());
/**
* 获取路径下的所有文件
*
*/
File bbFile = new File(
"G:\\yunpan\\work_hyy\\unicode\\src\\mengka\\fileclass\\");
System.out.println("\n\n【当前路径下的文件】:");
int aaIndex=1;
File[] aaFiles = bbFile.listFiles();
if(aaFiles==null){
System.exit(0);
}
for (File file : bbFile.listFiles()) {
if (file.canRead()) {
System.out.println("n = "+aaIndex+" , File.getName() = " + file.getName());
aaIndex++;
}
}
}
}
<file_sep>/src/main/java/mengka/ftp_01/FTPPubUtils.java
package mengka.ftp_01;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.Properties;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
/**
*
* Description: FTP文件上传下载工具类 FTPUtils.java Create on 2014-9-15 下午2:23:46
*
* @author <a href="<EMAIL>" >ding.xin</a>
* @version 1.0 Copyright (c) 2014 T.b.j,Inc. All Rights Reserved.
*/
public class FTPPubUtils {
private static Logger logger = LoggerFactory.getLogger(FTPPubUtils.class);
private static final String FTP_UPLOAD_EXCEPTION = "FTP上传文件失败";
private static final String FTP_BROWSER_EXCEPTION = "FTP浏览文件失败";
private static final String FTP_DOWNLOAD_EXCEPTION = "FTP下载文件失败";
private static final String FTP_DELETE_EXCEPTION = "FTP删除文件失败";
private static final String FTP_DISCONNECT_EXCEPTION = "FTP断开链接失败";
private static final String FTP_READ_FILE_INPUT_EXCEPTION = "FTP读取文件输入流失败";
private static final ClassPathResource FTP_RESOURCE = new ClassPathResource(
"config.properties");
private static Properties FTP_PROPERTIES = null;
private static String url = null;
private static String domain = null;
private static Integer port = null;
private static String username = null;
private static String password = null;
public static String HTTPURL = null;// 对外提供http反向代理的url
static {
try {
FTP_PROPERTIES = new Properties();
FTP_PROPERTIES.load(FTP_RESOURCE.getInputStream());
url = getFtpUrl();
domain = getDomain();
port = getFtpPort();
username = getFtpUsername();
password = getFtpPassword();
HTTPURL = domain + "/" + username;
} catch (IOException e) {
logger.error("", e);
}
}
/**
* Description: 向FTP服务器上传文件
*
* @param url
* FTP服务器hostname
* @param port
* FTP服务器端口,如果默认端口请写-1
* @param username
* FTP登录账号
* @param password
* FTP登录密码
* @param path
* FTP服务器保存目录
* @param filename
* 上传到FTP服务器上的文件名
* @param input
* 输入流
* @return 成功返回true,否则返回false
* @throws IOException
*/
public static boolean uploadFile(InputStream input, String filename,
String path) throws IOException {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
// 获取Ftp链接
getFtpConnection(ftp);
// 创建path制定的目录,若存在,则放回false,若不存在,返回true,并创建目录
boolean ismake = ftp.makeDirectory(path);
if (ismake) {
logger.info("make directory success!");
} else {
logger.warn("make directory fail!");
}
// 转移到FTP服务器目录
boolean isChange = ftp.changeWorkingDirectory(path);
FTPFile[] files = ftp.listFiles();
for (FTPFile ftpFile : files) {
logger.info("********************" + ftpFile.getName()
+ "*******************************************");
}
ftp.storeFile(filename, input);
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
success = false;
logger.error(FTP_UPLOAD_EXCEPTION, e);
} finally {
closeFtpConnection(ftp);
}
return success;
}
/**
* 浏览FTP上的内容
*
* @param remotePath
* @param fileName
* @return
* @throws IOException
*/
public static String browseFile(String remotePath, String fileName)
throws IOException {// 未使用到,只是当测试用
FTPClient ftp = new FTPClient();
String fileString = "";
try {
// 获取Ftp链接
getFtpConnection(ftp);
// 转移到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
FTPFile[] fs = ftp.listFiles();
if (null != fs) {
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
fileString = "ff的内容" + ff.getRawListing();
// File file = ;
}
}
}
} catch (IOException e) {
logger.error(FTP_BROWSER_EXCEPTION, e);
} finally {
closeFtpConnection(ftp);
}
return fileString;
}
/**
* Description: 从FTP服务器下载文件
*
* @Version1.0 Jul 27, 2008 5:32:36 PM by 崔红保(<EMAIL>)创建
* @param remotePath
* FTP服务器上的相对路径
* @param fileName
* 要下载的文件名
* @param localPath
* 下载后保存到本地的路径
* @return
* @throws IOException
*/
public static boolean downloadFile(String remotePath, String fileName,
String localPath) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
// 获取Ftp链接
getFtpConnection(ftp);
// 转移到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}
ftp.logout();
success = true;
} catch (IOException e) {
success = false;
logger.error(FTP_DOWNLOAD_EXCEPTION, e);
} finally {
closeFtpConnection(ftp);
}
return success;
}
/**
* <删除FTP上的文件> <远程删除FTP服务器上的录音文件>
*
* @param url
* FTP服务器IP地址
* @param port
* FTP服务器端口
* @param username
* FTP服务器登录名
* @param password
* FTP服务器密码
* @param remotePath
* 远程文件路径
* @param fileName
* 待删除的文件名
* @return
* @see [类、类#方法、类#成员]
*/
public static boolean deleteFtpFile(String remotePath, String fileName) {
boolean success = false;
FTPClient ftp = new FTPClient();
ftp.setControlEncoding("UTF-8");
try {
// 获取FTP链接并登陆
getFtpConnection(ftp);
// 转移到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
success = ftp.deleteFile(fileName);
ftp.logout();
} catch (IOException e) {
logger.error(FTP_DELETE_EXCEPTION, e);
success = false;
} finally {
closeFtpConnection(ftp);
}
return success;
}
/**
* 获取FTP服务器上文件的输出流
*
* @param remotePath
* @param fileName
* @return
*/
public static InputStream getFileInputStream(String remotePath,
String fileName) {
InputStream is = null;
FTPClient ftp = new FTPClient();
try {
// 获取FTP链接并登陆
boolean isSuccess = getFtpConnection(ftp);
if (isSuccess) {
// 转移到FTP服务器目录
FTPFile[] files = ftp.listFiles();
for (FTPFile ftpFile : files) {
logger.info("********************" + ftpFile.getName()
+ "*******************************************");
}
is = ftp.retrieveFileStream(fileName);
}
} catch (IOException e) {
logger.error(FTP_READ_FILE_INPUT_EXCEPTION, e);
} finally {
closeFtpConnection(ftp);
}
return is;
}
/********************************* 内部方法 ***********************************/
/**
* 获取FTP链接并登陆
*
* @param ftp
* @return
* @throws SocketException
* @throws IOException
*/
private static boolean getFtpConnection(FTPClient ftp)
throws SocketException, IOException {
int reply;
// 连接FTP服务器
if (port > -1) {
ftp.connect(url, port);
} else {
ftp.connect(url);
}
// 登录FTP
ftp.login(username, password);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
logger.warn("getFtpConnection fail, reply:[" + reply + "],url:["
+ url + "],port:[" + port + "],username:[" + username
+ "],password:[" + <PASSWORD> + "])");
return false;
}
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftp.setControlEncoding("GBK");
return true;
}
/**
* 关闭FTP链接
*
* @param ftp
*/
private static void closeFtpConnection(FTPClient ftp) {
try {
ftp.logout();
} catch (Exception e1) {
}
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
logger.error(FTP_DISCONNECT_EXCEPTION, e);
}
}
}
public static String getFtpUrl() {
try {
return FTP_PROPERTIES.getProperty("ftp.pub.url");
} catch (Exception e) {
logger.error("", e);
return null;
}
}
public static String getFtpUsername() {
try {
return FTP_PROPERTIES.getProperty("ftp.pub.username");
} catch (Exception e) {
logger.error("", e);
return null;
}
}
public static String getFtpPassword() {
try {
return FTP_PROPERTIES.getProperty("ftp.pub.password");
} catch (Exception e) {
logger.error("", e);
return null;
}
}
public static Integer getFtpPort() {
try {
return Integer.valueOf(FTP_PROPERTIES.getProperty("ftp.pub.port"));
} catch (Exception e) {
logger.error("", e);
return null;
}
}
public static String getDomain() {
try {
return FTP_PROPERTIES.getProperty("resource.http.url");
} catch (Exception e) {
logger.error("", e);
return null;
}
}
public static void main(String[] args) throws Exception, IOException {
// System.out.println(getFtpPort());
// System.out.println(getFtpPassword());
// System.out.println(getFtpUsername());
// System.out.println(getFtpUrl());
// Properties props = new Properties();
// try {
// InputStream in = new BufferedInputStream (new
// FileInputStream(FTP_PROPERTIES_PATH));
// props.load(in);
// String value = props.getProperty ("ftp.pub.url");
// System.out.println(""+value);
//
// } catch (Exception e) {
// logger.error("",e);
//
// }
System.out.println(getFtpPort());
InputStream input = new FileInputStream("D:\\doc\\icon-80.png");
boolean isSuccess = FTPPubUtils.uploadFile(input, "icon-80.png",
"/KITAS/test/");
if (isSuccess) {
logger.info("file upload success!");
} else {
logger.info("file upload fail!");
}
}
}
<file_sep>/src/main/java/mengka/fileList/createFile.java
package mengka.fileList;
import java.io.File;
public class createFile {
/**
* @param args
*/
public static void main(String[] args) {
String path = "D:/tmp/loan_report";
newFolder(path);
}
public static void newFolder(String folderPath) {
try {
String filePath = folderPath;
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.mkdir();
}
} catch (Exception e) {
System.out.println("newFolder error!");
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/mengka/point_01/timu_04.java
package mengka.point_01;
import java.math.BigDecimal;
/**
* java基础题④:
* 4. 计算公式 "2/3=?” , 只保留小数点后3位;(0.667)
*
* @author mengka.hyy
*
*/
public class timu_04 {
public static void main(String[] args){
double value = 2.0/3;
double remain = pointRemain(value, 3);
System.out.println("remain = "+remain);
}
/**
* 小数点后保留2位
*
* @param data
* @param remain
* @return
*/
public static double pointRemain(double data, int remain) {
BigDecimal bigDecimal = new BigDecimal(String.valueOf(data));
bigDecimal = bigDecimal.setScale(remain,BigDecimal.ROUND_HALF_UP);
return bigDecimal.doubleValue();
}
}
<file_sep>/src/main/java/mengka/isIncUrl/TBIncUrl.java
package mengka.isIncUrl;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import com.mengka.common.StringUtils;
public class TBIncUrl {
/**
* @param args
*/
public static void main(String[] args) {
boolean isTaobao=isIncUrl("http://www.taobao.com/ss");
System.out.println("是不是taobao内部链接: "+isTaobao);
boolean isTaobaoaa=isIncUrl("www.taobaov.com?id=11");
System.out.println("是不是taobao内部链接: "+isTaobaoaa);
boolean isSohuIncUrl = isSohuIncUrl("http://zhibo.m.sohu.com/r/7744/?v=3&_once_=000098_push");
System.out.println("isSohuIncUrl = "+isSohuIncUrl);
boolean isSohuIncUrl2 = isSohuIncUrl("m.sohu.com");
System.out.println("isSohuIncUrl = "+isSohuIncUrl2);
}
/**
* 判断是否安全的集团公司和合作伙伴url
* @param url 绝对url
* @return boolean 默认true
*/
public static final boolean isIncUrl(String url) {
//return true;
try {
String regex="^(http[s]{0,1}://|)([a-z0-9\\-_]+\\.)*(taobao|taobaov|taobaoa|taobaovm|alipay|alibaba|yahoo|3721|yisou|alisoft|alimama|koubei|msn|163|atpanel|allyes|swlc\\.sh)\\.(com|net|cn|org|com\\.cn)(.*)";
PatternCompiler compiler = new Perl5Compiler();
Pattern pattern = null;
try {
pattern = compiler.compile(regex, Perl5Compiler.CASE_INSENSITIVE_MASK);
} catch (Exception e) {
return true;
}
PatternMatcher patternMatcher = new Perl5Matcher();
return patternMatcher.matches(url, pattern);
} catch (Exception ex) {
return true;
}
}
public static final boolean isSohuIncUrl(String url) {
try {
if(StringUtils.isBlank(url)){
return false;
}
String regex="^(http[s]{0,1}://|)([a-z0-9\\-_]+\\.)*(m)\\.(sohu)\\.(com)(.*)";
PatternCompiler compiler = new Perl5Compiler();
Pattern pattern = null;
try {
pattern = compiler.compile(regex, Perl5Compiler.CASE_INSENSITIVE_MASK);
} catch (Exception e) {
return true;
}
PatternMatcher patternMatcher = new Perl5Matcher();
return patternMatcher.matches(url, pattern);
} catch (Exception ex) {
return true;
}
}
}
<file_sep>/src/main/java/mengka/time/CupTime.java
package mengka.time;
import java.text.SimpleDateFormat;
import java.util.Date;
import mengka.Util.StringUtil;
import mengka.noblank.Notblank_langs;
public class CupTime {
/**
* @param args
*/
public static void main(String[] args) {
/**
* Wed May 28 09:57:05 CST 2014
*/
Date date = new Date();
System.out.println(date);
/**
* "hh": 12小时制
*
* 2014-05-29 01:53:46
*/
String aaString = toDate(date, "yyyy-MM-dd hh:mm:ss");
System.out.println(aaString);
/**
* "HH": 24小时制
*
* 2014-05-29 13:53:46
*/
String bbString = toDate(date, "yyyy-MM-dd HH:mm:ss");
System.out.println(bbString);
}
public static java.util.Date toDate(String sDate, String sFmt) {
if (StringUtil.isBlank(sDate) || StringUtil.isBlank(sFmt)) {
return null;
}
SimpleDateFormat sdfFrom = null;
java.util.Date dt = null;
try {
sdfFrom = new SimpleDateFormat(sFmt);
dt = sdfFrom.parse(sDate);
} catch (Exception ex) {
return null;
} finally {
sdfFrom = null;
}
return dt;
}
public static String toDate(java.util.Date dt, String sFmt) {
if (null == dt || StringUtil.isBlank(sFmt)) {
return null;
}
SimpleDateFormat sdfFrom = null;
String sRet = null;
try {
sdfFrom = new SimpleDateFormat(sFmt);
sRet = sdfFrom.format(dt).toString();
} catch (Exception ex) {
return null;
} finally {
sdfFrom = null;
}
return sRet;
}
}
<file_sep>/src/main/java/mengka/time/oneMonth_01.java
package mengka.time;
import java.util.Calendar;
import java.util.Date;
import com.mengka.common.TimeUtil;
public class oneMonth_01 {
/**
* @param args
*/
public static void main(String[] args) {
Date date = TimeUtil.toDate("2015-9-29",TimeUtil.format_3);
String t1 = TimeUtil.toDate(date,"yyyy-MM-01");
System.out.println("t1 = "+t1);
Calendar calendar = Calendar.getInstance();
calendar.setTime(TimeUtil.toDate(t1,TimeUtil.format_3));
calendar.add(calendar.MONTH, 1);
Date endDate = calendar.getTime();
String t2 = TimeUtil.toDate(endDate,TimeUtil.format_3);
System.out.println("t2 = "+t2);
Date nowTime = new Date();
if(nowTime.after(endDate)){
System.out.println("result = true");
}
}
}
<file_sep>/src/main/java/mengka/time/String2Date_01.java
package mengka.time;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import mengka.Util.StringUtil;
public class String2Date_01 {
public static final String DATE_FMT_1 = "yyyy-MM-dd HH:mm:ss";
/**
* @param args
*/
public static void main(String[] args) {
Date aaaDate = new Date();
Date bbbDate = new Date();
if (bbbDate.after(aaaDate)) {
System.out.println("qqqqqq");
}
/**
* 例一:
* 比较时间的先后
*/
Date aaDate = (Date) toDate("2012-10-22 18:24:03", DATE_FMT_1);
Date bbDate = (Date) toDate("2012-10-22 20:24:03", DATE_FMT_1);
if (bbDate.after(aaDate)) {
System.out.println(bbDate);
}
/**
* 例二:
* 7天之后,时间aaDate
*/
Calendar calendar = Calendar.getInstance();
calendar.setTime(aaDate);
calendar.add(calendar.DATE, 7);
Date date = calendar.getTime();
if (date.after(bbDate)) {
System.out.println(date);
}
/**
* 例三:
* 获取一天之前的时间
*/
Calendar bbcalendar = Calendar.getInstance();
bbcalendar.setTime(aaDate);
bbcalendar.add(bbcalendar.DATE, -1);
Date bbdate = bbcalendar.getTime();
System.out.println("bbdate = "+bbdate);
Date ccDate = (Date) toDate("2013-04-03 20:24:03", DATE_FMT_1);
System.out.println("\n"+ccDate.getTime());
}
/**
* 将"yyyy-MM-dd hh:mm:ss"格式的string转变成日期
* <hr>
* 日期格式:
* <ul>
* <li>"yyyy-MM-dd hh:mm:ss"</li>
* <li>"yyyy-MM-dd"</li>
* </ul>
*
* @param sDate
* @param sFmt 日期字符串,"yyyy-MM-dd hh:mm:ss"
* @return
*/
public static java.util.Date toDate(String sDate, String sFmt) {
if (StringUtil.isBlank(sDate) || StringUtil.isBlank(sFmt)) {
return null;
}
SimpleDateFormat sdfFrom = null;
java.util.Date dt = null;
try {
sdfFrom = new SimpleDateFormat(sFmt);
dt = sdfFrom.parse(sDate);
} catch (Exception ex) {
return null;
} finally {
sdfFrom = null;
}
return dt;
}
}
<file_sep>/src/main/java/mengka/danli_04/Taa.java
package mengka.danli_04;
public class Taa {
public static void main(String[] args) {
Mengka.MengkaHolder.MENGKA_HOLDER.read();
Mengka mengka = new Mengka();
mengka.baicai();
}
}
<file_sep>/src/main/java/mengka/zhengze_02/zhengze_02.java
package mengka.zhengze_02;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class zhengze_02 {
/**
* @param args
*/
public static void main(String[] args) {
// String kkString = "hubei.china.taobao.com?id=1111&ali_trackid=00002";
//
// Pattern pattern = Pattern
// .compile("taobao.com");
// Matcher matcher = pattern.matcher(kkString);
//
// while (matcher.find()) {
// String aaString = matcher.group();
// System.out.println(aaString);
// }
String aaString = "<img src=\"qqqq\"/><img src=\"http://m.tv.sohu.com/favicon.ico\" height=\"16\" alt=\"视频\" style=\"vertical-align: middle;padding: 0 5px 2px;\">国安悍将比肩穆勒 曾灌葡国门3球";
Pattern bbpattern = Pattern.compile("<.*>(.*)");
Matcher bbmatcher = bbpattern.matcher(aaString);
if (bbmatcher.find()) {
String auctionId = bbmatcher.group(1);
System.out.println(auctionId);
}
String a = "<B>搜狐网友幻影蚊子</b>:<A href=\"http://quan.sohu.com/pinglun/cyqemw6s1/400748090\" target=_blank>璇璇,好久没见你了,很是想念啊【璇璇:多谢挂念啊!】 <A href=\"http://quan.sohu.com/pinglun/cyqemw6s1/400748090\" target=_blank><FONT color=magenta>[点击与美女主播璇璇互动</FONT></A>]";
Pattern pattern = Pattern.compile("<FONT(.*)>(.*)<\\/FONT>");
Matcher matcher = pattern.matcher(a);
if (matcher.find()) {
String content = matcher.group(2);
System.out.println(content);
StringBuffer buffer = new StringBuffer();
buffer.append("<strong>").append(content).append("</strong>");
System.out.println(buffer.toString());
}
String test = "var assign = require('./Object.assign');var warning = require('fbjs/lib/warning');var abc = require('fbjs/lib/abc');var bcd = require('fbjs/lib/bcd');\n";
Pattern bbbpattern = Pattern.compile("require\\('[^.](.*?)'\\)");
Matcher bbbmatcher = bbbpattern.matcher(test);
while (bbbmatcher.find()) {
String auctionId = bbbmatcher.group(1);
System.out.println(auctionId);
}
}
}
<file_sep>/src/main/java/com/taobao/mengka/antxProperty/PropertyInit.java
package com.taobao.mengka.antxProperty;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class PropertyInit {
private static Properties properties = new Properties();
static {
InputStream in = PropertyInit.class
.getResourceAsStream("/init.properties");
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* /tmp/qs/logs/
* @return
*/
public static String getLogPath() {
return properties.getProperty("logpath");
}
/**
* /tmp/
* @return
*/
public static String getDownloadPath() {
return properties.getProperty("downloadpath");
}
/**
* /tmp/qs/bak/
* @return
*/
public static String getBakPath() {
return properties.getProperty("bakpath");
}
/**
* tair┼ńÍ├ú║<br>
* ${configservers1},${configservers2}
* @return
*/
public static List<String> getConfigServers() {
List<String> list = new ArrayList<String>();
String configServers = properties.getProperty("configservers");
if (configServers != null && configServers.length() > 0) {
String[] configServerArray = configServers.split(",");
if (configServerArray != null && configServerArray.length > 0) {
for (String configServer : configServerArray) {
list.add(configServer);
}
}
}
return list;
}
/**
* tair┼ńÍ├ í░groupNameí▒
* @return
*/
public static String getGroupName() {
return properties.getProperty("groupname");
}
/**
* /tmp/qs/logdata/
* @return
*/
public static String getDataLogPath(){
return properties.getProperty("datalogpath");
}
}
<file_sep>/src/main/java/mengka/zhengze_01/SdkXmlChange.java
package mengka.zhengze_01;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sun.xml.internal.bind.v2.schemagen.episode.Klass;
/**
* 将formType="SELECT"变成formType="select",SDK解析xml的时候,不能区分出大写的参数
* <hr>
* ceshi: "selectaaa" , matcher.group() = "SELECTaaa" <br>
* ceshi: "selectaaa" , matcher.group() = "SELECTAAA" <br>
* ceshi: "mengkaaaa" , matcher.group() = "MENGKAAAA" <br>
* ceshi: "mengmmmka" , matcher.group() = "MENGmmmKA" <br>
* ceshi: "mengkabbb" , matcher.group() = "mengKABBB" <br>
*
* @author Administrator
*
*/
public class SdkXmlChange {
/**
* @param args
*/
public static void main(String[] args) {
String tempString = "src//main//java//mengka//zhengze_01//formParamers.txt";
String kkString = mkFileAllRead(tempString);
Pattern pattern = Pattern
.compile("formType=\"[a-zA-Z]*[A-Z]+[a-zA-Z]*\"");
Matcher matcher = pattern.matcher(kkString);
while (matcher.find()) {
String aaString = matcher.group().toLowerCase().substring(9);
String bbString = matcher.group().substring(9);
kkString = kkString.replaceAll(bbString, aaString);
System.out.println("ceshi: " + aaString + " , matcher.group() = "
+ bbString);
matcher = pattern.matcher(kkString);
}
System.out.println(kkString);
}
/**
* 读取整个文件
*
* @param pathString
* 文件的输入路径
*/
public static String mkFileAllRead(String pathString) {
String kkString = "";
StringBuffer stringBuffer = new StringBuffer();
try {
InputStreamReader inputStreamReader = new InputStreamReader(
new FileInputStream(pathString));
BufferedReader brReader = new BufferedReader(inputStreamReader);
stringBuffer = new StringBuffer();
int str;
while ((str = brReader.read()) != -1) {
stringBuffer.append((char) str);
}
kkString = stringBuffer.toString();
} catch (Exception e) {
kkString = e.toString();
}
return kkString;
}
}
<file_sep>/src/main/java/mengka/mail/excelread/JsonUtil.java
package mengka.mail.excelread;
import java.io.IOException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
/**
* 从tae-common取出来的json常用方法
*
* @author mengka.hyy
*
*/
public class JsonUtil {
private static ObjectMapper mapper = new ObjectMapper().configure(
DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
/**
* 根据json字符串生成javabean的方法
*
* @param json
* @param clazz
* @return
* @throws java.io.IOException
*/
public static Object parseJson(String json, Class<?> clazz) throws IOException {
// 忽略不认识的属性,不报异常
return mapper.readValue(json, clazz);
}
}
<file_sep>/src/main/java/mengka/json/json2Object_01.java
package mengka.json;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.taobao.tae.common.util.JsonUtil;
public class json2Object_01 {
/**
* @param args
*/
public static void main(String[] args) {
/**
* 将json串解析成java对象:
* http://img01.taobaocdn.com/bao/uploaded/i1/T19a2_XhBhXXXXXXXX
*
*/
try {
/**
* step01: 读取文件
*/
String tempString = "src//main//java//mengka//json//neice.txt";
Scanner scanner = mkReadFile(tempString);
int tempIndex = 1;
while (scanner.hasNext()) {
String ccString = scanner.nextLine();
int ccLength = ccString.length();
/**
* step02: 进行元素分解
*/
String shopIdString = "";
String userIdString = "";
String tfsString = "";
int help = 0;
for (int i = 0; i < ccLength; i++) {
if ((Character.isWhitespace(ccString.charAt(i)) == false)
&& help == 0) {
shopIdString += ccString.charAt(i);
}
if ((Character.isWhitespace(ccString.charAt(i)) == false)
&& help == 1) {
userIdString += ccString.charAt(i);
}
if ((Character.isWhitespace(ccString.charAt(i)) == false)
&& help == 2) {
tfsString += ccString.charAt(i);
}
if ((Character.isWhitespace(ccString.charAt(i)) == true)) {
help++;
}
}
String[] aaStrings = ccString.split("\t");
// String tfsString = aaStrings[2];
// System.out.println(shopIdString+","+tfsString);
String urlString = "http://img01.taobaocdn.com/bao/uploaded/i1/"
+ tfsString;
String aaString = getWebContent(urlString, "gbk", 5000);
// System.out.println(aaString);
/****** 出错gson *****/
// GsonBuilder builder = new GsonBuilder();
// builder.excludeFieldsWithoutExposeAnnotation();
// Gson gson = builder.create();
//
// Mengka mengka = gson.fromJson(aaString, Mengka.class);
//
// System.out.println(mengka.getUserId());
/***************/
/**
* step03: json变成对象
*/
Mengka aamengka = (Mengka) JsonUtil.parseJson(aaString,
Mengka.class);
// System.out.println(aamengka.getUserId());
String bbString = "def aa" + tempIndex + " = ['userId':"
+ aamengka.getUserId() + ",'nick':\""
+ aamengka.getNick() + "\",'xuanyan':\""
+ aamengka.getXuanyan() + "\",'shopId':" + shopIdString
+ ",'weibo':\"" + aamengka.getWeibo()
+ "\",'bangpai':\"" + aamengka.getBangpai()
+ "\",'douban':\"" + aamengka.getDouban()
+ "\",'renren':\"" + aamengka.getRenren() + "\"]\n";
System.out.println(bbString);
/**
* step04: 写出文件
*/
String result = "src//main//java//mengka//json//result.txt";
write2FileAdd(result, bbString);
tempIndex++;
}
} catch (Exception e) {
System.out.println(e);
}
}
/**
* 将 inpuString写入到 file中,累加文字
*
* @param file
* 输出的文件路径
* @param inpuString
* 自己输入的内容,写入输出文件file中
*/
public static void write2FileAdd(String file, String inpuString) {
int mkPolice = 0;
try {
if (!file.contains(".")) {
mkPolice = -1;
System.out.println(2 / 0);
}
File f = new File(file);
FileOutputStream fout;
// 替换原来文件中的数据
fout = new FileOutputStream(f, true);
byte[] tempNum = null;
tempNum = inpuString.getBytes();
fout.write(tempNum);
} catch (Exception e) {
if (mkPolice == -1) {
System.out.println("请输入正确的文件路径!");
} else {
e.printStackTrace();
}
}
}
/**
* 按行读取文件内容,返回 Scanner
*
* @param fileString
* 输入文件的存放路径
* @return
*/
public static Scanner mkReadFile(String fileString) {
File f = new File(fileString);
InputStream st = null;
try {
st = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Scanner in = new Scanner(st);
return in;
}
public static String getWebContent(String urlString, final String charset,
int timeout) throws IOException {
if (urlString == null || urlString.length() == 0) {
return null;
}
urlString = (urlString.startsWith("http://") || urlString
.startsWith("https://")) ? urlString : ("http://" + urlString)
.intern();
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");// 增加报头,模拟浏览器,防止屏蔽
conn.setRequestProperty("Accept", "text/html");// 只接受text/html类型,当然也可以接受图片,pdf,*/*任意,就是tomcat/conf/web里面定义那些
conn.setConnectTimeout(timeout);
try {
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
} catch (IOException e) {
e.printStackTrace();
// logStringBuilder.append("\n"+e+"\n");
return null;
}
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input,
charset));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\r\n");
}
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
return sb.toString();
}
}
<file_sep>/src/main/java/mengka/file/duolan/duolan_01.java
package mengka.file.duolan;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Scanner;
public class duolan_01 {
/**
* @param args
*/
public static void main(String[] args) {
String aaString = "src//main//java//mengka//file//duolan//tmall.txt";
String bbString = "src//main//java//mengka//file//duolan//result.txt";
Scanner scanner = mkReadFile(aaString);
String mmString = "def kk = [";
while (scanner.hasNext()) {
String aaaString = scanner.nextLine().trim();
mmString+="'"+aaaString+"',";
}
mmString+="]";
//write2File(bbString,mmString);
System.out.println(mmString);
}
/**
* 将 inpuString写入到 file中
*
* @param file
* 输出的文件路径
* @param inpuString
* 自己输入的内容,写入输出文件file中
*/
public static void write2File(String file, String inpuString) {
int mkPolice = 0;
try {
if (!file.contains(".")) {
mkPolice = -1;
System.out.println(2 / 0);
}
File f = new File(file);
FileOutputStream fout;
// 替换原来文件中的数据
fout = new FileOutputStream(f, false);
byte[] tempNum = null;
tempNum = inpuString.getBytes();
fout.write(tempNum);
} catch (Exception e) {
if (mkPolice == -1) {
System.out.println("请输入正确的文件路径!");
} else {
e.printStackTrace();
}
}
}
/**
* 按行读取文件内容,返回 Scanner
*
* @param fileString 输入文件的存放路径
* @return
*/
public static Scanner mkReadFile(String fileString) {
File f = new File(fileString);
InputStream st = null;
try {
st = new FileInputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner in = new Scanner(st);
return in;
}
}
<file_sep>/src/main/java/mengka/extends_01/BallDO.java
package mengka.extends_01;
public abstract class BallDO {
public String size;//大小
public String weight;//重量
public String name;
public boolean isRound;//是否是圆的
public abstract String getSize();
public BallDO(String name){
this.name = name;
}
}
<file_sep>/src/main/java/mengka/random_01/Tbb.java
package mengka.random_01;
public class Tbb {
/**
* @param args
*/
public static void main(String[] args) {
/**
* ·µ»Ø¡¾1-10¡¿µÄËæ»úÊý
*
*/
for(int i=0;i<30;i++){
int aa = (int) (Math.random() * 10) +1;
System.out.println("aa = "+aa);
}
}
}
<file_sep>/src/main/java/mengka/timeTask_02/ReSendTask.java
package mengka.timeTask_02;
import java.util.TimerTask;
import java.util.concurrent.Semaphore;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ReSendTask extends TimerTask {
private static final Log log = LogFactory.getLog(ReSendTask.class);
private Semaphore semaphore;
public ReSendTask(Semaphore semaphore) {
this.semaphore = semaphore;
}
@Override
public void run() {
try{
//acquire
semaphore.acquire();
//¶¨Ê±ÈÎÎñ
process();
}catch(Exception e){
log.error("ReSendTask run error!",e);
}finally{
semaphore.release();
}
}
public void process(){
log.info("ReSendTask running...");
try{
Thread.sleep(5000);
}catch(Exception e){
}
}
}
<file_sep>/src/main/java/mengka/mail/excel/Excel_01.java
package mengka.mail.excel;
import jxl.write.Label;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Excel_01 {
/*
* 线上: /home/admin/product/buyingNumber/ 表格: 表格的输出路径
*/
private static String excelFile = "src//main//java//mengka//mail//excel//product.xls";
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// 打印到 "1.log"中,的日志信息
System.out.println("####################################");
System.out.println("###" + getCurrentDate() + "###");
System.out.println("####################################");
// 表格:初始化表格数据,设置表格输出路径
File f = new File(excelFile);
FileOutputStream outStream = new FileOutputStream(f, false);
WritableWorkbook workbook = Workbook.createWorkbook(outStream);
// 表格:新创建的一页
/*
* 表格一:所有数据 表格二:没有购买记录的数据 表格三:商品数少于10 个数据
*/
WritableSheet sheet1 = workbook.createSheet("first sheet", 0);
WritableSheet sheet2 = workbook.createSheet("0 购买记录", 1);
WritableSheet sheet3 = workbook.createSheet("商品少于10个", 2);
WritableSheet sheet4 = workbook.createSheet("茶|酒|冲饮", 3);
// 表格:设置列的属性
Label label1 = new Label(0, 0, "特产ID");
Label label2 = new Label(1, 0, "特产名");
Label label3 = new Label(2, 0, "状态");
Label label4 = new Label(3, 0, "购买记录");
Label label5 = new Label(4, 0, "第一页商品个数");
Label label6 = new Label(5, 0, "链接");
Label label7 = new Label(6, 0, "页面商品总数");
Label label8 = new Label(7, 0, "类目ID");
Label label9 = new Label(8, 0, "类目name");
// ====================
Label alabel1 = new Label(0, 0, "特产ID");
Label alabel2 = new Label(1, 0, "特产名");
Label alabel3 = new Label(2, 0, "状态");
Label alabel4 = new Label(3, 0, "购买记录");
Label alabel5 = new Label(4, 0, "第一页商品个数");
Label alabel6 = new Label(5, 0, "链接");
Label alabel7 = new Label(6, 0, "页面商品总数");
Label alabel8 = new Label(7, 0, "类目ID");
Label alabel9 = new Label(8, 0, "类目name");
// ====================
Label blabel1 = new Label(0, 0, "特产ID");
Label blabel2 = new Label(1, 0, "特产名");
Label blabel3 = new Label(2, 0, "状态");
Label blabel4 = new Label(3, 0, "购买记录");
Label blabel5 = new Label(4, 0, "第一页商品个数");
Label blabel6 = new Label(5, 0, "链接");
Label blabel7 = new Label(6, 0, "页面商品总数");
Label blabel8 = new Label(7, 0, "类目ID");
Label blabel9 = new Label(8, 0, "类目name");
// ====================
Label cclabel1 = new Label(0, 0, "特产ID");
Label cclabel2 = new Label(1, 0, "特产名");
Label cclabel3 = new Label(2, 0, "状态");
Label cclabel4 = new Label(3, 0, "购买记录");
Label cclabel5 = new Label(4, 0, "第一页商品个数");
Label cclabel6 = new Label(5, 0, "链接");
Label cclabel7 = new Label(6, 0, "页面商品总数");
Label cclabel8 = new Label(7, 0, "类目ID");
Label cclabel9 = new Label(8, 0, "类目name");
sheet1.addCell(label1);
sheet1.addCell(label2);
sheet1.addCell(label3);
sheet1.addCell(label4);
sheet1.addCell(label5);
sheet1.addCell(label6);
sheet1.addCell(label7);
sheet1.addCell(label8);
sheet1.addCell(label9);
// ====================
sheet2.addCell(alabel1);
sheet2.addCell(alabel2);
sheet2.addCell(alabel3);
sheet2.addCell(alabel4);
sheet2.addCell(alabel5);
sheet2.addCell(alabel6);
sheet2.addCell(alabel7);
sheet2.addCell(alabel8);
sheet2.addCell(alabel9);
// ====================
sheet3.addCell(blabel1);
sheet3.addCell(blabel2);
sheet3.addCell(blabel3);
sheet3.addCell(blabel4);
sheet3.addCell(blabel5);
sheet3.addCell(blabel6);
sheet3.addCell(blabel7);
sheet3.addCell(blabel8);
sheet3.addCell(blabel9);
// ====================
sheet4.addCell(cclabel1);
sheet4.addCell(cclabel2);
sheet4.addCell(cclabel3);
sheet4.addCell(cclabel4);
sheet4.addCell(cclabel5);
sheet4.addCell(cclabel6);
sheet4.addCell(cclabel7);
sheet4.addCell(cclabel8);
sheet4.addCell(cclabel9);
int excelIndex = 1;
for (int i = 1; excelIndex < 100; i++) {
// 表格:写入表格
Label aalabel1 = new Label(0, excelIndex, String.valueOf(i + 10000));
Label aalabel2 = new Label(1, excelIndex, "name" + i);
Label aalabel3 = new Label(2, excelIndex, "状态" + i);
Label aalabel4 = new Label(3, excelIndex, "购买记录");
Label aalabel5 = new Label(4, excelIndex, String.valueOf("aaaa"));
Label aalabel6 = new Label(5, excelIndex, "test-1");
Label aalabel7 = new Label(6, excelIndex, "test-2");
Label aalabel8 = new Label(7, excelIndex, "cat-" + i);
Label aalabel9 = new Label(8, excelIndex, "path-" + i);
sheet1.addCell(aalabel1);
sheet1.addCell(aalabel2);
sheet1.addCell(aalabel3);
sheet1.addCell(aalabel4);
sheet1.addCell(aalabel5);
sheet1.addCell(aalabel6);
sheet1.addCell(aalabel7);
sheet1.addCell(aalabel8);
sheet1.addCell(aalabel9);
excelIndex++;
}
// 表格: 将创建的内容写入到输出流之中
workbook.write();
workbook.close();
outStream.close();
// 打印到 "1.log"中,的日志信息
System.out.println("####################################");
System.out.println("### end " + getCurrentDate() + " ###");
System.out.println("####################################");
}
/**
* 时间取方法 , 例如:"20120117"
*
* @return
*/
public static String getCurrentDate() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 0);
DateFormat SIMPLE_DATA_FORMAT = new SimpleDateFormat("yyyyMMdd");
return SIMPLE_DATA_FORMAT.format(cal.getTime());
}
}
<file_sep>/src/main/java/mengka/split_01/split_01.java
package mengka.split_01;
import java.util.StringTokenizer;
import org.apache.commons.lang.builder.ToStringBuilder;
public class split_01 {
/**
* @param args
*/
public static void main(String[] args) {
String aaString = new String("a,b,c,d");
/**
* 法一:使用正则表达式
*/
String[] aaResult = aaString.split(",");
System.out.println(ToStringBuilder.reflectionToString(aaResult));
/**
* 法二:使用StringTokenizer
*/
StringTokenizer tokenizer = new StringTokenizer(aaString, ",");
String[] bbResult = new String[tokenizer.countTokens()];
int i = 0;
while (tokenizer.hasMoreTokens()) {
bbResult[i] = tokenizer.nextToken();
i++;
}
System.out.println(ToStringBuilder.reflectionToString(bbResult));
}
}
<file_sep>/src/main/java/mengka/decimal/decimal_01.java
package mengka.decimal;
import java.math.BigDecimal;
/**
* 小数点后保留一位数字
*
* @author mengka.hyy
*
*/
public class decimal_01 {
/**
* @param args
*/
public static void main(String[] args) {
BigDecimal b = new BigDecimal((2.0 / 3)*100);
double f = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println("b = "+b+" , f = "+f);
}
}
<file_sep>/src/main/java/mengka/china2taiwan/Taiwan2china_01.java
package mengka.china2taiwan;
/**
* 繁体字变成简体字
*
* @author mengka
*
*/
public class Taiwan2china_01 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String aaString="我是中國人";
String bbString=ChineseUtil.covGBKT2S(aaString);
System.out.println(bbString);
String ccString="人民無民主國家";
String ddString= ChineseUtil.covGBK(ccString,1);
System.out.println(ddString);
}
}
<file_sep>/src/main/java/mengka/extends_02/SchoolService.java
package mengka.extends_02;
/**
* school底层接口
*
* @author mengka.hyy
*
*/
public interface SchoolService {
/**
* 学校名字
* @return
*/
public String getSchoolName();
/**
* 学校地址
* @return
*/
public String getSchoolAddress();
}
<file_sep>/src/main/java/shopcenter/B.java
package shopcenter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
* 【失败】 使用jsoup方法获取不到JS加载之后的html页面
*
* @author mengka.hyy
*
*/
public class B {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
String aaString = "http://ops.jm.taobao.org:9999/dep-center/dependencySearch.html?depId=88872&groupId=com.taobao.shopcenter&artifactId=core-client&extension=jar&version=3.1.11#";
Document doc = Jsoup.connect(aaString).get();
// ElementUrl urlStr=doc.
Element elements = doc.getElementById("searchResults");
String bbString=elements.toString();
System.out.println(bbString);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.taobao.mengka</groupId>
<artifactId>mengka</artifactId>
<name>mengka</name>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<properties>
<spring-version>2.5.6</spring-version>
<ibatis-version>2.3.4.726</ibatis-version>
<java.version>1.6</java.version>
<shiro.version>1.2.3</shiro.version>
</properties>
<dependencies>
<!-- <dependency> <groupId>com.ibatis</groupId> <artifactId>ibatis</artifactId>
<version>2.3.4.726</version> </dependency> -->
<dependency>
<groupId>com.mengka.common</groupId>
<artifactId>mengka-common</artifactId>
<version>1.0.2-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.2</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.4.5-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5-rc1</version>
</dependency>
<!-- ********表格文件处理******* -->
<dependency>
<groupId>jxl</groupId>
<artifactId>jxl</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>net.sourceforge.javacsv</groupId>
<artifactId>javacsv</artifactId>
<version>2.0</version>
</dependency>
<!-- ********end******* -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>1.4.0</version>
</dependency>
<!-- ********抓取网页******* -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.10</version>
</dependency>
<!-- ********end******* -->
<dependency>
<groupId>com.taobao.util</groupId>
<artifactId>util</artifactId>
<version>1.2.3</version>
</dependency>
<!-- <dependency> <groupId>org.apache.oro</groupId> <artifactId>oro</artifactId>
<version>2.0.8</version> </dependency> -->
<!-- ******** file 文件的读写 ******* -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- ********end******* -->
<!-- ******** antx配置文件 ******* -->
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<!-- 为Web工程提供servlet支持 -->
<artifactId>geronimo-servlet_2.5_spec</artifactId>
<version>1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- ********end******* -->
<!-- ********** xml解析依赖 ********* -->
<dependency>
<groupId>com.taobao.commons</groupId>
<artifactId>taobao-commons-utils</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>12.0</version>
</dependency>
<!-- ********end******* -->
<!-- ******** curator是Netflix公司开源的一个Zookeeper client library,用于简化zookeeper客户端编程
******* -->
<dependency>
<groupId>com.netflix.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>1.0.1</version>
</dependency>
<!-- ********end******* -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
<!-- ******** httpclient相关操作 ******* -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- ********end******* -->
<dependency>
<groupId>apache-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.1</version>
</dependency>
<!-- ******** svn相关操作 ******* -->
<dependency>
<groupId>org.tmatesoft.svnkit</groupId>
<artifactId>svnkit</artifactId>
<version>1.3.4</version>
</dependency>
<!-- ********end******* -->
<dependency>
<groupId>com.taobao.tae</groupId>
<artifactId>tae-common-engine</artifactId>
<version>1.0.0-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>com.taobao.logstat</groupId>
<artifactId>logstat-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>com.taobao.hsf.ndi</groupId>
<artifactId>hsf.app.ndi</artifactId>
<version>1.4.9.2-tae</version>
</dependency>
<!-- *** word *** -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.14</version>
</dependency>
<!-- FTP -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>1.4.1</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>dev</id>
<properties>
<props>src/main/filters/dev.properties</props>
<projectName>mengka-daily</projectName>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<props>src/main/filters/prod.properties</props>
<projectName>mengka-online</projectName>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
<build>
<filters>
<filter>${props}</filter>
</filters>
<finalName>${projectName}</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.*</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>GBK</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-5</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>mengka.houseMDTest.Taa</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>/src/main/java/mengka/time_03/Tbb.java
package mengka.time_03;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.mengka.common.TimeUtil;
public class Tbb {
private static Log logger = LogFactory.getLog(Tbb.class);
public static void main(String[] args) {
Date now = new Date();
int i =2;
Date startTime = AverageUtil.getStartTime_realTime(now, i);
Date endTime = AverageUtil.getEndTime_realTime(now, i);
logger.info("--------, startTime = "+TimeUtil.toDate(startTime, TimeUtil.format_1));
logger.info("--------, endTime = "+TimeUtil.toDate(endTime, TimeUtil.format_1));
logger.info("--------, endTime - startTime = "+(endTime.getTime()-startTime.getTime()));
int j =20;
Date startTime2 = AverageUtil.getStartTime_realTime(now, j);
Date endTime2 = AverageUtil.getEndTime_realTime(now, j);
logger.info("--------, startTime = "+TimeUtil.toDate(startTime2, TimeUtil.format_1));
logger.info("--------, endTime = "+TimeUtil.toDate(endTime2, TimeUtil.format_1));
logger.info("--------, endTime - startTime = "+(endTime2.getTime()-startTime2.getTime()));
}
}
<file_sep>/src/main/java/mengka/bigFile_01/Taa.java
package mengka.bigFile_01;
import java.io.*;
/**
* 》》java读取大文件:<br>
* 1.讲究速度的话, 用nio的MappedByteBuffer;<br>
* 2.一般的话, 用BufferedReader就能搞定;<br>
* <br>
* 》》jvm参数:<br>
* -Xms20m -Xmx20m -Xmn10m -XX:+UseSerialGC<br><br>
*
* User: mengka
* Date: 2015/1/12
*/
public class Taa {
public static void main(String[] args) throws Exception {
String path = "D:/test_data.log";
File file = new File(path);
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 1 * 1024 * 1024);// 用5M的缓冲读取文本文件
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
<file_sep>/src/main/java/test/aa.java
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class aa {
/**
* @param args
*/
public static void main(String[] args) {
String ccString = "´ó°×²ËAA°×²ËAAÇà²ËAAA#´ó°×²ËAA°×²ËAAÇà²ËAAA#´ó°×²ËAA°×²ËAAÇà²ËAAA";
ccString = ccString.replace("´ó°×²ËAA", "´ó°×²ËBBB");
System.out.println(ccString);
String aaString = "\u6DD8\u5B9D\u771F";
String bbString = UnicodeToString(aaString);
System.out.println(bbString);
String cc = "HYY044101331";
System.out.println(cc.toLowerCase());
}
public String yilong(String aaString){
aaString+="AAA";
return aaString;
}
public static String UnicodeToString(String str) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(str);
char ch;
while (matcher.find()) {
ch = (char) Integer.parseInt(matcher.group(2), 16);
str = str.replace(matcher.group(1), ch + "");
}
return str;
}
}
<file_sep>/src/main/java/mengka/json_03/Taa.java
package mengka.json_03;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mengka.common.TimeUtil;
import java.util.Date;
/**
* Created by xiafeng
* on 2015/7/6.
*/
public class Taa {
public static void main(String[] args)throws Exception{
String json = "{\"pageStartTime\":1436164882418,\"pageEndTime\":1436164906176,\"pageId\":\"page001\",\"businessInfos\":{\"jinjian\":{\"block001\":[{\"id\":\"btn001\",\"time\":1436164884480}],\"block002\":[{\"id\":\"btn002\",\"time\":1436164885095}]},\"jinjian2\":{\"block003\":[{\"id\":\"btn003\",\"time\":1436164885860}],\"block004\":[{\"id\":\"btn004\",\"time\":1436164886661}]},\"jinjian3\":{\"block005\":[{\"id\":\"btn005\",\"time\":1436164887479},{\"id\":\"btn006\",\"time\":1436164888088},{\"id\":\"btn007\",\"time\":1436164888817},{\"id\":\"btn008\",\"time\":1436164889490}]}}}";
JSONObject jsonObject = JSON.parseObject(json);
Long time = jsonObject.getLong("pageStartTime");
Date date = new Date(time);
System.out.println(TimeUtil.toDate(date,TimeUtil.format_1));
}
}
<file_sep>/src/main/java/mengka/http/GetHttpByJSoup.java
package mengka.http;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
/**
* tiaozi 网页抓取的时候,获取链接的'<'HTML>源代码
*
* @author mengka
*
*/
public class GetHttpByJSoup {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String aaString = "http://zlxy.aqsiq.gov.cn/credit/food_aq/list_food_aq.jsp";
Document doc = Jsoup.connect(aaString).get();
// ElementUrl urlStr=doc.
Elements elements = doc.getElementsByClass("title"); // 文本:
// System.out.println(elements.text());
String urlStr = elements.toString();
System.out.println(elements.text());
System.out.println("\n" + urlStr + "\n\n");
int aaIndex = urlStr.lastIndexOf("</b>");
int bbIndex = urlStr.lastIndexOf("共有");
String bbString = urlStr.substring(bbIndex, aaIndex);
System.out.println(bbString);
int ccIndex = bbString.indexOf("第");
int ddIndex = bbString.indexOf("页");
int kkIndex = bbString.indexOf("/");
String startString = bbString.substring(ccIndex + 1, kkIndex);
String endString = bbString.substring(kkIndex + 1, ddIndex);
System.out.println(startString);
System.out.println(endString);
System.out.println(startString+"=="+endString);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/mengka/date2string/Date2String_01.java
package mengka.date2string;
import java.text.SimpleDateFormat;
import java.util.Date;
import mengka.noblank.Notblank_langs;
public class Date2String_01 {
public static final String DATE_FMT_0 = "yyyy-MM-dd";
/**
* @param args
*/
public static void main(String[] args) {
java.util.Date aaDate = new Date();
String aaString = toDate(aaDate, DATE_FMT_0);
System.out.println(aaDate + " = " + aaString);
}
/**
* 将String类型的日期转成Date类型
*
* @param dt
* date object
* @param sFmt
* the date format
*
* @return the formatted string
*/
public static String toDate(java.util.Date dt, String sFmt) {
if (null == dt || Notblank_langs.isBlank(sFmt)) {
return null;
}
SimpleDateFormat sdfFrom = null;
String sRet = null;
try {
sdfFrom = new SimpleDateFormat(sFmt);
sRet = sdfFrom.format(dt).toString();
} catch (Exception ex) {
return null;
} finally {
sdfFrom = null;
}
return sRet;
}
}
<file_sep>/src/main/java/mengka/mail/excelread/ReadExcel_07.java
package mengka.mail.excelread;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import mengka.noblank.Notblank_langs;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class ReadExcel_07 {
public static final String DATE_FMT_0 = "yyyyMMdd";
public static void main(String[] args) throws Exception {
String aapath = "src//main//java//mengka//mail//excelread//jihuo01.xls";
String aaoutPath = "src//main//java//mengka//mail//excelread//backyard"
+ getCurrentDate() + "_01.xls";
String bbpath = "src//main//java//mengka//mail//excelread//jihuo02.xls";
String bboutPath = "src//main//java//mengka//mail//excelread//backyard"
+ getCurrentDate() + "_02.xls";
String ddpath = "src//main//java//mengka//mail//excelread//jihuo03.xls";
String ddoutPath = "src//main//java//mengka//mail//excelread//backyard"
+ getCurrentDate() + "_03.xls";
// String aapath = "src//main//java//mengka//mail//excelread//backyard01.xls";
// String aaoutPath = "src//main//java//mengka//mail//excelread//backyard"
// + getCurrentDate() + "_01.xls";
// String bbpath = "src//main//java//mengka//mail//excelread//backyard02.xls";
// String bboutPath = "src//main//java//mengka//mail//excelread//backyard"
// + getCurrentDate() + "_02.xls";
//
mkBackyardData(aapath, aaoutPath);
mkBackyardData(bbpath, bboutPath);
mkBackyardData(ddpath, ddoutPath);
}
public static void mkBackyardData(String path, String outPath) throws Exception {
Sheet sheet = getWorkBook(path, 0);
File f = new File(outPath);
FileOutputStream outStream = new FileOutputStream(f, false);
WritableWorkbook workbook = Workbook.createWorkbook(outStream);
WritableSheet sheet1 = workbook.createSheet("店铺后院", 0);
// 表格:设置列的属性
Label label1 = new Label(0, 0, "店铺ID");
Label label2 = new Label(1, 0, "nick");
Label label3 = new Label(2, 0, "用户ID");
Label label4 = new Label(3, 0, "星级");
Label label5 = new Label(4, 0, "站点ID");
Label label6 = new Label(5, 0, "类目");
Label label7 = new Label(6, 0, "后院喜欢次数");
Label label8 = new Label(7, 0, "开始时间");
Label label9 = new Label(8, 0, "结束时间");
Label label10 = new Label(9, 0, "开通时间");
Label label11 = new Label(10, 0, "晒单人数");
Label label12 = new Label(11, 0, "晒单喜欢数");
Label label13 = new Label(12, 0, "晒单评论数");
Label label14 = new Label(13, 0, "指数");
Label label15 = new Label(14, 0, "完成度");
sheet1.addCell(label1);
sheet1.addCell(label2);
sheet1.addCell(label3);
sheet1.addCell(label4);
sheet1.addCell(label5);
sheet1.addCell(label6);
sheet1.addCell(label7);
sheet1.addCell(label8);
sheet1.addCell(label9);
sheet1.addCell(label10);
sheet1.addCell(label11);
sheet1.addCell(label12);
sheet1.addCell(label13);
sheet1.addCell(label14);
sheet1.addCell(label15);
int bbIndex = 1;
for (int i = 1; i < sheet.getRows(); i++) {
Long shopId = Long
.parseLong(sheet.getCell(0, i).getContents() != null ? sheet
.getCell(0, i).getContents() : "0");
try{
String nick = sheet.getCell(1, i).getContents();
String userId = sheet.getCell(2, i).getContents();
String credit = sheet.getCell(3, i).getContents();
String siteId = sheet.getCell(4, i).getContents();
String cat = sheet.getCell(5, i).getContents();
String favor = sheet.getCell(6, i).getContents();
HashMap aaMap = (HashMap) JsonUtil.parseJson(sheet.getCell(7, i)
.getContents(), HashMap.class);
String startTime = (String) aaMap.get("start_time");
String endTime = (String) aaMap.get("end_time");
String stat = (String) aaMap.get("stat");
String[] aaStrings = stat.split(":");
java.util.Date startDate=toDate(startTime,DATE_FMT_0);
java.util.Date endDate=toDate(endTime,DATE_FMT_0);
String distance = distanceTime(endDate,startDate);
System.out.println("shopId = "+shopId);
Label aalabel1 = new Label(0, bbIndex, String.valueOf(shopId));
Label aalabel2 = new Label(1, bbIndex, String.valueOf(nick));
Label aalabel3 = new Label(2, bbIndex, String.valueOf(userId));
Label aalabel4 = new Label(3, bbIndex, String.valueOf(credit));
Label aalabel5 = new Label(4, bbIndex, String.valueOf(siteId));
Label aalabel6 = new Label(5, bbIndex, String.valueOf(cat));
Label aalabel7 = new Label(6, bbIndex, String.valueOf(favor));
Label aalabel8 = new Label(7, bbIndex, String.valueOf(startTime));
Label aalabel9 = new Label(8, bbIndex, String.valueOf(endTime));
Label aalabel10 = new Label(9, bbIndex, String.valueOf(distance));
Label aalabel11 =null;
Label aalabel12 =null;
Label aalabel13 =null;
Label aalabel14 =null;
Label aalabel15 =null;
if(aaStrings!=null&&aaStrings.length>4){
aalabel11 = new Label(10, bbIndex, String.valueOf(aaStrings[3]));
aalabel12 = new Label(11, bbIndex, String.valueOf(aaStrings[4]));
aalabel13 = new Label(12, bbIndex, String.valueOf(aaStrings[5]));
aalabel14 = new Label(13, bbIndex, String.valueOf(aaStrings[0]));
aalabel15 = new Label(14, bbIndex, String.valueOf(aaStrings[2]));
}else{
aalabel11 = new Label(10, bbIndex, "0");
aalabel12 = new Label(11, bbIndex, "0");
aalabel13 = new Label(12, bbIndex, "0");
aalabel14 = new Label(13, bbIndex, "0");
aalabel15 = new Label(14, bbIndex, "0");
}
sheet1.addCell(aalabel1);
sheet1.addCell(aalabel2);
sheet1.addCell(aalabel3);
sheet1.addCell(aalabel4);
sheet1.addCell(aalabel5);
sheet1.addCell(aalabel6);
sheet1.addCell(aalabel7);
sheet1.addCell(aalabel8);
sheet1.addCell(aalabel9);
sheet1.addCell(aalabel10);
sheet1.addCell(aalabel11);
sheet1.addCell(aalabel12);
sheet1.addCell(aalabel13);
sheet1.addCell(aalabel14);
sheet1.addCell(aalabel15);
bbIndex++;
}catch(Exception e){
System.out.print("shopId = "+shopId+" , error = "+e);
}
}
workbook.write();
workbook.close();
outStream.close();
}
/**
* 根据文件path,读取excel中的数据
*
* @param path
* @param index
* 工作区的index
* @return
* @throws Exception
*/
public static Sheet getWorkBook(String path, Integer index)
throws Exception {
File file = new File(path);
Workbook workbook = Workbook.getWorkbook(file);
if (index == null) {
index = 0;
}
Sheet sheet = workbook.getSheet(index);
return sheet;
}
/**
* 计算时间的差额
*
* @param endDate 后面
* @param startDate 前面
* @return
*/
public static String distanceTime(Date endDate, Date startDate) {
if(null == startDate||null == endDate||startDate.after(endDate)){
return "0";
}
long ssDistan = (endDate.getTime() - startDate.getTime()) / 1000;
long mmDistan = (endDate.getTime() - startDate.getTime()) / 1000 / 60;
long hhDistan = (endDate.getTime() - startDate.getTime()) / 1000 / 60 / 60;
long ddDistan = (endDate.getTime() - startDate.getTime()) / 1000/ 60 / 60 / 24;
long monthDistan = (endDate.getTime() - startDate.getTime())/ 1000 / 60 / 60 / 24 / 30;
String buyTimestrString = "";
if (monthDistan != 0) {
buyTimestrString = monthDistan + "个月";
} else {
if (ddDistan != 0) {
buyTimestrString = ddDistan + "天";
} else {
if (hhDistan != 0) {
buyTimestrString = hhDistan + "小时";
} else {
if (mmDistan != 0) {
buyTimestrString = mmDistan + "分钟";
} else {
buyTimestrString = ssDistan + "秒";
}
}
}
}
return buyTimestrString;
}
/**
* change string to date 将String类型的日期转成Date类型
*
* @param sDate
* the date string
* @param sFmt
* the date format
*
* @return Date object
*/
public static java.util.Date toDate(String sDate, String sFmt) {
if (Notblank_langs.isBlank(sDate) || Notblank_langs.isBlank(sFmt)) {
return null;
}
SimpleDateFormat sdfFrom = null;
java.util.Date dt = null;
try {
sdfFrom = new SimpleDateFormat(sFmt);
dt = sdfFrom.parse(sDate);
} catch (Exception ex) {
return null;
} finally {
sdfFrom = null;
}
return dt;
}
public static String getCurrentDate() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -1);
DateFormat SIMPLE_DATA_FORMAT = new SimpleDateFormat("yyyyMMdd");
return SIMPLE_DATA_FORMAT.format(cal.getTime());
}
}
<file_sep>/src/main/java/mengka/china2taiwan/TempUtil.java
package mengka.china2taiwan;
/**
* StringUtil.java中抽取出来的部分,“转化汉字”例子需要的方法
*
* @author mengka
*
*/
public class TempUtil {
/**
* 替换指定的子串,替换所有出现的子串。
*
* <p>
* 如果字符串为<code>null</code>则返回<code>null</code>,如果指定子串为<code>null</code>
* ,则返回原字符串。
*
* <pre>
* StringUtil.replace(null, *, *) = null
* StringUtil.replace("", *, *) = ""
* StringUtil.replace("aba", null, null) = "aba"
* StringUtil.replace("aba", null, null) = "aba"
* StringUtil.replace("aba", "a", null) = "aba"
* StringUtil.replace("aba", "a", "") = "b"
* StringUtil.replace("aba", "a", "z") = "zbz"
* </pre>
*
* </p>
*
* @param text
* 要扫描的字符串
* @param repl
* 要搜索的子串
* @param with
* 替换字符串
*
* @return 被替换后的字符串,如果原始字符串为<code>null</code>,则返回<code>null</code>
*/
public static String replace(String text, String repl, String with) {
return replace(text, repl, with, -1);
}
/**
* 替换指定的子串,替换指定的次数。
*
* <p>
* 如果字符串为<code>null</code>则返回<code>null</code>,如果指定子串为<code>null</code>
* ,则返回原字符串。
*
* <pre>
* StringUtil.replace(null, *, *, *) = null
* StringUtil.replace("", *, *, *) = ""
* StringUtil.replace("abaa", null, null, 1) = "abaa"
* StringUtil.replace("abaa", null, null, 1) = "abaa"
* StringUtil.replace("abaa", "a", null, 1) = "abaa"
* StringUtil.replace("abaa", "a", "", 1) = "baa"
* StringUtil.replace("abaa", "a", "z", 0) = "abaa"
* StringUtil.replace("abaa", "a", "z", 1) = "zbaa"
* StringUtil.replace("abaa", "a", "z", 2) = "zbza"
* StringUtil.replace("abaa", "a", "z", -1) = "zbzz"
* </pre>
*
* </p>
*
* @param text
* 要扫描的字符串
* @param repl
* 要搜索的子串
* @param with
* 替换字符串
* @param max
* maximum number of values to replace, or <code>-1</code> if no
* maximum
*
* @return 被替换后的字符串,如果原始字符串为<code>null</code>,则返回<code>null</code>
*/
public static String replace(String text, String repl, String with, int max) {
if ((text == null) || (repl == null) || (with == null)
|| (repl.length() == 0) || (max == 0)) {
return text;
}
StringBuffer buf = new StringBuffer(text.length());
int start = 0;
int end = 0;
while ((end = text.indexOf(repl, start)) != -1) {
buf.append(text.substring(start, end)).append(with);
start = end + repl.length();
if (--max == 0) {
break;
}
}
buf.append(text.substring(start));
return buf.toString();
}
}
<file_sep>/src/main/java/mengka/downloadPic/Test.java
package mengka.downloadPic;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
MysqlDB mycon=new MysqlDB();
mycon.connect();
mycon.get();
mycon.insertToTempaa("1", "临安玉米", "http://img01.taobaocdn.com/imgextra/i1/317900274/T24nd8XXlXXXXXXXXX_!!317900274.jpg");
System.out.println("插入成功!!");
}
catch(Exception e){
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/mengka/shopcenterhsf/A.java
package mengka.shopcenterhsf;
import java.io.*;
import java.util.HashMap;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.taobao.commons.lang.StringUtil;
/**
* 统计shopcenter里面升级TFS,需要通知的其他应用方<br>
* 前38行是依赖店铺hsf service的,后面的是依赖core-client的其他应用
*
* @author mengka.hyy
*
*/
public class A {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String tempString = "F:\\work_hyy\\mengka\\src\\main\\java\\mengka\\shopcenterhsf\\hsfAndCore.log";
HashMap<String, String> aaMap = new HashMap<String, String>();
Scanner scanner = mkReadFile(tempString);
try {
int tempIndex=1;
while (scanner.hasNext()) {
String aaString = scanner.nextLine().trim();
if (isNotBlank(aaString)) {
if (aaMap.get(aaString)==null) {
if(tempIndex<=38){
aaMap.put(aaString, aaString+":serviceaa");
}else{
aaMap.put(aaString, aaString+":core-client");
}
}else{
aaMap.put(aaString, aaString+":2");
}
// aaMap.put(aaString, aaString);
}
tempIndex++;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
String file = "F:\\work_hyy\\mengka\\result2.log";
Set aaSet=aaMap.entrySet();
Iterator iterator=aaSet.iterator();
StringBuffer aaBuffer=new StringBuffer();
StringBuffer bbBuffer=new StringBuffer();
while(iterator.hasNext()){
Map.Entry entry=(Entry) iterator.next();
System.out.println("<"+entry.getKey()+","+entry.getValue()+">");
if(entry.getValue().toString().contains("serviceaa")){
aaBuffer.append(entry.getKey()+"\n");
}else {
bbBuffer.append(entry.getKey()+"\n");
}
}
write2FileAdd(file,aaBuffer.toString()+"\n");
write2FileAdd(file,bbBuffer.toString());
}
/**
* 检查字符串是否不是空白:<code>null</code>、空字符串<code>""</code>或只有空白字符。
*
* <pre>
* StringUtil.isBlank(null) = false
* StringUtil.isBlank("") = false
* StringUtil.isBlank(" ") = false
* StringUtil.isBlank("bob") = true
* StringUtil.isBlank(" bob ") = true
* </pre>
*
* @param str
* 要检查的字符串
*
* @return 如果为空白, 则返回<code>true</code>
*/
public static boolean isNotBlank(String str) {
int length;
if ((str == null) || ((length = str.length()) == 0)) {
return false;
}
for (int i = 0; i < length; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
/**
* 将 inpuString写入到 file中,累加文字
*
* @param file
* 输出的文件路径
* @param inpuString
* 自己输入的内容,写入输出文件file中
*/
public static void write2FileAdd(String file, String inpuString) {
int mkPolice = 0;
try {
if (!file.contains(".")) {
mkPolice = -1;
System.out.println(2 / 0);
}
File f = new File(file);
FileOutputStream fout;
// 替换原来文件中的数据
fout = new FileOutputStream(f, true);
byte[] tempNum = null;
tempNum = inpuString.getBytes();
fout.write(tempNum);
} catch (Exception e) {
// TODO: handle exception
if (mkPolice == -1) {
System.out.println("请输入正确的文件路径!");
} else {
e.printStackTrace();
}
}
}
/**
* 按行读取文件内容,返回 Scanner
*
* @param fileString
* 输入文件的存放路径
* @return
*/
public static Scanner mkReadFile(String fileString) {
File f = new File(fileString);
InputStream st = null;
try {
st = new FileInputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner in = new Scanner(st);
return in;
}
}
<file_sep>/src/main/java/mengka/time/Time_01.java
package mengka.time;
import java.util.Date;
/**
* 用来计算进程运行消耗的时间:<br>
* Thread.sleep(3000) = 3011
*
* @author mengka.hyy
*
*/
public class Time_01 {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
Date now = new Date();
long start = System.currentTimeMillis();
Thread.sleep(3000);
long endTime = System.currentTimeMillis();
System.out.println(start);
System.out.println(endTime - start);
String dateBegin = "2008-05-22";
String dateEnd = "2008-04-22";
if(java.sql.Date.valueOf(dateBegin).after(java.sql.Date.valueOf(dateEnd))){
System.out.print("aaaaaaaaa");
}
}
}
<file_sep>/src/main/java/mengka/class_02/InnerClass_02.java
package mengka.class_02;
public class InnerClass_02 {
public static class A {
public static void main(String[] args) {
int length = args.length;
System.out.println("length = " + length);
}
}
/**
* @param args
*/
public static void main(String[] args) {
String[] bbStrings = new String[2];
bbStrings[0] = "11";
bbStrings[1] = "22";
A.main(bbStrings);
}
}
<file_sep>/src/main/java/mengka/httpclient/GetTaobaoPage_02.java
package mengka.httpclient;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* 用户登录访问 , 页面: http://mai.taobao.com/welcome.htm
*
* @author mengka.hyy
*
*/
public class GetTaobaoPage_02 {
public static void main(String[] args) throws Exception {
// String urlString = "http://mai.taobao.com/welcome.htm";
// String nameString = "hyy044101331";
// String passwordString = "5***";
String urlString ="http://store.taobao.com/cms_admin.htm";
String nameString = "店铺问题排查";
String passwordString = "***";
// String urlString ="http://design.taobao.com/design.htm?siteId=1&sid=62427758";
// String nameString = "c测试账号27";
// String passwordString = "***";
//
executeHttpPage(urlString, nameString, passwordString);
}
/**
* 用户名和密码,执行页面
* <hr>
* http://baike.baidu.com/cms/s/core/index.html 【或者:baike.baidu.com/cms/s/core/index.html】
* <br>
* lastPageUrl = /cms/s/core/index.html <br>
* domainHost = baike.baidu.com<br> <br>
* 页面返回的状态status: <br>
* 200 正常 , 404 找不到 , 502 500 出错 , 302 重定向
*
* @param pageUrl
* @param username
* @param userpassword
* @throws Exception
*/
public static void executeHttpPage(String pageUrl, String username,
String userpassword) throws Exception {
Pattern pattern = Pattern.compile(".*.com/");
Matcher matcher = pattern.matcher(pageUrl);
/**
* step01:<br>
* 分离URL, lastPageUrl = /cms/s/core/index.html
* <br> domainHost = baike.baidu.com
* <br>
*/
String lastPageUrl = "";
String domainHost = "";
while (matcher.find()) {
if (pageUrl.contains("http")) {
domainHost = matcher.group().substring(7);
int aaIndex = pageUrl.indexOf(domainHost);
domainHost = domainHost.substring(0, domainHost.length()-1);
lastPageUrl = pageUrl.substring(domainHost.length()+7);
} else {
domainHost = matcher.group();
int aaIndex = pageUrl.indexOf(domainHost);
domainHost = domainHost.substring(0, domainHost.length()-1);
lastPageUrl = pageUrl.substring(domainHost.length());
}
}
/**
* step02:
* 设置登录的基本信息
*/
//设置“baike.baidu.com”,如果有port的话
// client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost(domainHost);
//设置登录的用户名和密码
PostMethod post = new PostMethod(lastPageUrl);
NameValuePair name = new NameValuePair("name", username);
NameValuePair pass = new NameValuePair("password", <PASSWORD>);
/**
* step03:
* 设置url后面带的参数
*/
// NameValuePair opt = new NameValuePair("opt", "dealPromotedType");
// NameValuePair opt2 = new NameValuePair("opt2", "add");
// NameValuePair promotedType = new NameValuePair("promotedType", "1073741824");
// NameValuePair userId = new NameValuePair("userId", "902094408");
// NameValuePair wd = new NameValuePair("id", "3779023399");
// post.setRequestBody(new NameValuePair[] { name, pass ,opt,opt2,promotedType,userId });
post.setRequestBody(new NameValuePair[] { name, pass });
/**
* step04:
* 将返回的页面的编码格式变成GBK,并显示
*/
int status = client.executeMethod(post);
System.out.println("status = " + status + "\n"
+ post.getResponseCharSet());
String aaString = post.getResponseBodyAsString();
String bbString = new String(aaString.getBytes("ISO-8859-1"), "gbk");
String outString="";
if(post.getResponseCharSet().equals("GBK")){
outString=aaString;
}else {
outString=bbString;
}
// 打印出页面
System.out.println(outString);
post.releaseConnection();
/**
* step05:
* 打印出client的cookies,这句可以省略
*/
getCookiesByClient(client,domainHost);
}
/**
* 打印出client的cookies,这句可以省略
*
* @param client
* @param domainHost baike.baidu.com
*/
public static void getCookiesByClient(HttpClient client, String domainHost) {
getCookiesByClient(client, domainHost, 8080);
}
/**
* 打印出client的cookies,这句可以省略
*
* @param client
* @param domainHost baike.baidu.com
* @param port 8080
*/
public static void getCookiesByClient(HttpClient client, String domainHost,
int port) {
// 查看cookie信息
CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
Cookie[] cookies = cookiespec.match(domainHost, port, "/", false,
client.getState().getCookies());
if (cookies.length == 0) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.length; i++) {
System.out.println("i = "+i+" , "+cookies[i].toString());
}
}
}
}
<file_sep>/src/main/resources/config.properties
ftp.pub.url=192.168.1.155
ftp.pub.port=21
ftp.pub.username=111
ftp.pub.password=111
resource.http.url=http://192.168.1.155<file_sep>/src/main/java/mengka/extends_02/HduSchoolService.java
package mengka.extends_02;
/**
* HduSchoolService继承了接口SchoolService
*
* @author mengka.hyy
*
*/
public interface HduSchoolService extends SchoolService{
/**
* HDU的校园文化
*
* @return
*/
public String getHduCulture();
}
<file_sep>/src/main/java/mengka/time/Date2String_01.java
package mengka.time;
import java.text.SimpleDateFormat;
import java.util.Date;
import mengka.noblank.Notblank_langs;
public class Date2String_01 {
/**
* @param args
*/
public static void main(String[] args) {
String rewardEndDate = toDate(new Date(),"yyyy-MM-dd HH:mm:ss ");
System.out.println(rewardEndDate);
}
/**
* 将String类型的日期转成Date类型
*
* @param dt
* date object
* @param sFmt
* the date format
*
* @return the formatted string
*/
public static String toDate(java.util.Date dt, String sFmt) {
if (null == dt || Notblank_langs.isBlank(sFmt)) {
return null;
}
SimpleDateFormat sdfFrom = null;
String sRet = null;
try {
sdfFrom = new SimpleDateFormat(sFmt);
sRet = sdfFrom.format(dt).toString();
} catch (Exception ex) {
return null;
} finally {
sdfFrom = null;
}
return sRet;
}
}
<file_sep>/src/main/java/mengka/time/festival_01/Tbb.java
package mengka.time.festival_01;
import java.util.Date;
import com.alibaba.common.lang.StringUtil;
import com.mengka.common.TimeUtil;
/**
* 显示某一个时间的节日
*
* @author mengka.hyy
*
*/
public class Tbb {
public static void main(String[] args) {
/**
* 例一:
* 获取当天的节日
*/
String day = "2014-06-02 00:00:00";
Lunar lunar = new Lunar();
String nongli = lunar.getLunar(day);
System.out.println(nongli);
String festival = FestivalGroup.festivalOfDay(nongli);
System.out.println(day+"-节日:"+festival);
/**
* 农历节日
*
*/
String day2 = "2014-10-02 00:00:00";
String festival2 = getFestival(day2);
System.out.println(day2+"-节日:"+festival2);
/**
* 新历节日
*
*/
String day3 = "2014-10-01 00:00:00";
String festival3 = getFestival(day3);
System.out.println(day3+"-节日:"+festival3);
}
/**
* 获取当天的节日
*
* @param day
* @return
*/
public static String getFestival(String day){
String festival = "";
Lunar lunar = new Lunar();
String nongli = lunar.getLunar(day);
String festival_N = FestivalGroup.festivalOfDay(nongli);
if(StringUtil.isNotBlank(festival_N)){
festival = festival_N;
}
Date date = TimeUtil.toDate(day, TimeUtil.format_1);
String day_X = TimeUtil.toDate(date, "MM月dd日");
String festival_X = FestivalGroup.festivalOfDay(day_X);
if(StringUtil.isNotBlank(festival_X)){
festival = festival_X;
}
return festival;
}
}
<file_sep>/src/main/java/mengka/httpclient_proxy/Taa.java
package mengka.httpclient_proxy;
public class Taa {
public static void main(String[] args) {
ZhiboClientOnlineJob zhiboClientOnlineJob = new ZhiboClientOnlineJob();
zhiboClientOnlineJob.work();
}
}
<file_sep>/src/main/java/mengka/file_java7/file_02.java
package mengka.file_java7;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Éú³ÉÎļþ
*
* @author mengka.hyy
*
*/
public class file_02 {
public static void main(String[] args) throws Exception{
String content = "baicai AAA..\nqingcai AAA..";
String path = "/Users/hyy044101331/work_hyy/mengka/src/main/java/mengka/file_java7/result.txt";
Files.write(Paths.get(path), content.getBytes());
}
}
<file_sep>/src/main/java/mengka/httpWWmessage/sendKeludeWWMessage_01.java
package mengka.httpWWmessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
/**
* 制造http请求,实现用kelude发送消息
*
* @author mengka.hyy
*
*/
public class sendKeludeWWMessage_01 {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//sendKeludeWWMessage(111L,"aaa","bbb");
String encodeNick = URLEncoder.encode("蒙卡", "utf-8");
// URLEncodedUtils.parse(s, charset)
System.out.println(encodeNick);
String aaContent = "您好!<br>由于您是品牌设计师 故为您特别开通<b>后院</b>内测权限!<a href=\"http://siteadmin.taobao.com/outside/page-14007.htm\">立即使用</a>在后院,您可以:阐释品牌背后的故事/与买家深入互动<br>还有更多功能或玩法,不断添加中!<br>不知如何开始,<b><a href=\"http://bbs.taobao.com/catalog/thread/510526-260264093.htm\">看看别人的后院</a></b><br>或者加入旺旺群,与我们聊聊或参加官方活动!<br>(群号:117176071 验证码:后院2013)";
String content = "<br>你好!<br><br>你申请的后院,现已审核通过!<b><a href='http://siteadmin.taobao.com/outside/page-14007.htm'>立即设置</a></b><br><br>在后院,你可以:讲述故事或发起互动<br><br>还有更多功能或玩法,不断添加中!<br><br>不知如何开始,<b><a href='http://bbs.taobao.com/catalog/thread/510526-260264093.htm'>看看别人的后院</a></b><br><br>或者加入旺旺群,与我们聊聊!(群号:117176071 验证码:后院2013)";
HashMap<String, String> queryMap = new HashMap<String, String>();
queryMap.put("auth", "***");
queryMap.put("nick", "蒙卡");
queryMap.put("subject", "aaa");
queryMap.put("context", "bbb");
String queryStr = MapUtil.changeMapToQueryString(queryMap, "utf-8");
String url = "http://kelude.taobao.org/api/admin/notice/wangwang";
postHttpRequest(url,queryStr);
// testPost();
}
/**
* 请求页面
*
* @param preURL
* @param queryStr
* @throws Exception
*/
public static void postHttpRequest(String preURL,String queryStr) throws Exception{
System.out.println(preURL+"?"+queryStr);
URL url = new URL(preURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setDoInput(true);
//connection.connect();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "8859_1");
out.write(queryStr); //向页面传递数据
out.flush();
out.close();
String sCurrentLine= "";
String sTotalString = "";
InputStream urlInputStream = connection.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(
urlInputStream));
while ((sCurrentLine = bf.readLine()) != null) {
sTotalString += sCurrentLine + "/r/n";
}
}
public static void testPost() throws IOException {
/**
* 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。比如: // Using
* java.net.URL and //java.net.URLConnection
*
* 使用页面发送请求的正常流程:在页面http://www.faircanton.com/message/loginlytebox.asp中输入用户名和密码,然后按登录,
* 跳转到页面http://www.faircanton.com/message/check.asp进行验证
* 验证的的结果返回到另一个页面
*
* 使用java程序发送请求的流程:使用URLConnection向http://www.faircanton.com/message/check.asp发送请求
* 并传递两个参数:用户名和密码
* 然后用程序获取验证结果
*/
URL url = new URL("http://kelude.taobao.net/api/admin/notice/wangwang");
URLConnection connection = url.openConnection();
/**
* 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。
* 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做:
*/
connection.setDoOutput(true);
/**
* 最后,为了得到OutputStream,简单起见,把它约束在Writer并且放入POST信息中,例如: ...
*/
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "8859_1");
out.write("nick=%E8%92%99%E5%8D%A1&subject=aaa&context=bbb&auth=***"); //向页面传递数据。post的关键所在!
// remember to clean up
out.flush();
out.close();
/**
* 这样就可以发送一个看起来象这样的POST:
* POST /jobsearch/jobsearch.cgi HTTP 1.0 ACCEPT:
* text/plain Content-type: application/x-www-form-urlencoded
* Content-length: 99 username=bob password=<PASSWORD>
*/
// 一旦发送成功,用以下方法就可以得到服务器的回应:
String sCurrentLine;
String sTotalString;
sCurrentLine = "";
sTotalString = "";
InputStream l_urlStream;
l_urlStream = connection.getInputStream();
// 传说中的三层包装阿!
BufferedReader l_reader = new BufferedReader(new InputStreamReader(
l_urlStream));
while ((sCurrentLine = l_reader.readLine()) != null) {
sTotalString += sCurrentLine + "/r/n";
}
System.out.println(sTotalString);
}
/**
* 发送旺旺消息
*
* @param toUserId
* @param title
* @param content
* @throws IOException
*/
public static void sendKeludeWWMessage(Long toUserId,String title,String content) throws IOException{
if(content==null){
return;
}
String nick="蒙卡";
String url = "http://kelude.taobao.net/api/admin/notice/wangwang?nick="+nick+"&subject="+title+"&context="+content+"&auth=***";
String aa = HttpClientUtil.getWebContent(url, "gbk", 500);
System.out.println(aa);
}
}
<file_sep>/src/main/java/mengka/fileclass/aa.java
package mengka.fileclass;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
public class aa {
/**
* @param args
*/
public static void main(String[] args) {
String tempString = "src//main//java//mengka//fileclass//shangquan.txt";
Scanner scanner = mkReadFile(tempString);
try {
int tempNum=1;
while (scanner.hasNext()) {
String aaString = scanner.nextLine();
System.out.println(aaString.trim());
tempNum++;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* 按行读取文件内容,返回 Scanner
*
* @param fileString 输入文件的存放路径
* @return
*/
public static Scanner mkReadFile(String fileString) {
File f = new File(fileString);
InputStream st = null;
try {
st = new FileInputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner in = new Scanner(st);
return in;
}
}
<file_sep>/src/main/java/mengka/bigFile_02/mkdata.java
package mengka.bigFile_02;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 构造测试数据:<br>
* 日志文件有66132248条记录,文件大小1.8G
* <br><br>
*
* @author mengka.hyy
*
*/
public class mkdata {
private static final Log log = LogFactory.getLog(mkdata.class);
private static FileOutputStream outputStream = null;
public static void main(String[] args) throws Exception {
String path = "/Users/hyy044101331/work_hyy/mengka/src/main/java/mengka/bigFile_02/data.log";
if (outputStream == null) {
File f = new File(path);
// 替换原来文件中的数据
outputStream = new FileOutputStream(f, true);
}
write2FileAdd(path, "gbk");
}
public static void write2FileAdd(String file, String charset)
throws IOException {
try {
for (int i = 0; i < 1000000000; i++) {
StringBuffer buffer = new StringBuffer();
buffer.append(i).append("-").append("00000000000000000000");
buffer.append("\n");
System.out.println("n = " + i);
byte[] temp = null;
temp = buffer.toString().getBytes(charset);
outputStream.write(temp);
}
} catch (Exception e) {
log.error("write2FileAdd error!", e);
}
}
}
<file_sep>/src/main/java/mengka/random_01/Tcc.java
package mengka.random_01;
import java.util.ArrayList;
import java.util.Collections;
public class Tcc {
/**
* @param args
*/
public static void main(String[] args) {
long count = 100000000;
ArrayList<Long> records = getRecords(count);
for(Long tmp:records){
System.out.println(tmp);
}
}
/**
* 获取中奖结果
*
* @param count 是第几个1000区间
* @return
*/
public static ArrayList<Long> getRecords(long count){
long[] data = new long[1000];
for(int i=0;i<1000;i++){
data[i] = i+1+count*1000;
}
ArrayList<Long> records = new ArrayList<Long>();
int[] indexs = getRanRewardResult(1000,50);
for (int i : indexs) {
records.add(data[i]);
}
Collections.sort(records);
return records;
}
public static int[] getRanRewardResult(int listNum, long count) {
int[] aaRan = new int[listNum];
for (int i = 0; i < listNum; i++) {
aaRan[i] = i;
}
int[] resultRan = new int[(int) count];
for (int i = 0; i < count; i++) {
resultRan[i] = (int) (Math.random() * (listNum - i) + 1);
int temp = aaRan[listNum - i - 1];
aaRan[listNum - i - 1] = aaRan[resultRan[i] - 1];
aaRan[resultRan[i] - 1] = temp;
}
for (int i = 0; i < count; i++) {
resultRan[i] = aaRan[listNum - 1 - i];
}
return resultRan;
}
}
<file_sep>/src/main/java/mengka/houseMDTest/Taa.java
package mengka.houseMDTest;
/**
*
* 每3秒打印一段文字,用于houseMD测试
*
* @author mengka.hyy
*
*/
public class Taa {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<10000;i++){
System.out.println("--------------- houseMD test , i = "+i);
Thread.sleep(30000);
}
}
}
<file_sep>/src/main/java/mengka/time/festival_01/Taa.java
package mengka.time.festival_01;
import java.util.Calendar;
import java.util.Date;
import com.mengka.common.TimeUtil;
/**
* 计算某一天是农历那一天
*
* @author mengka.hyy
*
*/
public class Taa {
public static void main(String[] args) {
/**
* 计算农历时间
*
*/
String day = "2012-01-23 00:00:00";
Date date = TimeUtil.toDate(day, TimeUtil.format_1);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Lunar lunar = new Lunar();
lunar.getLunar(calendar);
System.out.print("农历日期:");
System.out.print(lunar.year + "年 ");
System.out.print(lunar.month + "月 ");
System.out.println(lunar.getChinaDayString(lunar.day));
System.out.println("*************");
System.out.println(lunar);
/**
* 约“每三年一闰”
* 19年加7个闰月
*/
String day2 = "2012-06-01 00:00:00";
Lunar lunar2 = new Lunar();
String nongli = lunar2.getLunar(day2);
System.out.println(nongli);
/**
*
*/
String day3 = "2013-10-13 00:00:00";
Lunar lunar3 = new Lunar();
String nongli3 = lunar3.getLunar(day3);
System.out.println(nongli3);
}
}
|
cc6a8c2b00479683b3e6e9621bbdc25d82b1e808
|
[
"Java",
"Markdown",
"INI",
"Maven POM"
] | 70 |
Java
|
hyy044101331/mengka
|
7f360281020c617c2d3f3e7467c013473cd19138
|
ab279c51521f4f7533a0a1c14f0c6aba14ab19da
|
refs/heads/main
|
<file_sep># drumpaint
crossbreed between striped down paint program and drum machine
|
68fdb0f67a9ed8954fb434d2b4a421732abbe937
|
[
"Markdown"
] | 1 |
Markdown
|
mitje-glavanakov/drumpaint
|
eb15ab25f480095c7296dfe403ab50476c1cc949
|
0e970d32abee870d0767b98517db512f2881bb10
|
refs/heads/master
|
<file_sep># test
rohit.repo
<file_sep>---
service:
- docker
dependencies:
pre:
- sudo apt-get -y update
- sudo apt-get -y install awscli
- sudo apt-get -y install mysql-server
- sudo apt-get -y install docker
command: mv /var/lib/docker /var/lib/docker_old
post:
- sudo service docker start
- docker build -t aws .
- docker tag aws:latest $AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/aws:latest
test:
post:
- docker run -d -p 8080:8080 --name aws $AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/aws:latest sleep 10
- docker ps
- eval $(aws ecr get-login --region us-east-1)
- docker push $AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/aws:latest
|
6fdd6414084567607ac5c30367ccba0b6ae73224
|
[
"Markdown",
"YAML"
] | 2 |
Markdown
|
rohit-sri/test
|
986f55c58fee59fd376760405b8969b2deed46f4
|
d85727b6aec06d20c6ae38a6dd0aa48201511246
|
refs/heads/master
|
<file_sep>from ngsolve import *
from netgen.geom2d import SplineGeometry
import matplotlib.pyplot as plt;
import numpy as np
import time
ngsglobals.msg_level = 0
def solve_system(tau, tend, el_order, theta,newton):
# viscosity
nu = 0.001
# timestepping parameters
#tau = 0.04
# simulation time
#tend = 5
# element order
#el_order = 3
# use newton or picard iteration
#newton = True
# theta value for phi scheme
#theta = 0.5
#%% create domain with cylinder
geo = SplineGeometry()
geo.AddRectangle( (0, 0), (2, 0.41), bcs = ("wall", "outlet", "wall", "inlet"))
geo.AddCircle ( (0.2, 0.2), r=0.05, leftdomain=0, rightdomain=1, bc="cyl", maxh=0.009)
mesh = Mesh( geo.GenerateMesh(maxh=0.05) )
mesh.Curve(el_order+1)
#%% define FE spaces
V = VectorH1(mesh,order=el_order, dirichlet="wall|cyl|inlet")
#V.SetOrder(TRIG, 3)
#V.Update()
Q = H1(mesh,order=el_order-1)
X = FESpace([V,Q])
u,p = X.TrialFunction()
v,q = X.TestFunction()
#%% solve stokes eq to init solution
stokes = nu*InnerProduct(grad(u), grad(v))+div(u)*q+div(v)*p - 1e-10*p*q
a = BilinearForm(X)
a += stokes*dx
a.Assemble()
# nothing here ...
f = LinearForm(X)
f.Assemble()
# gridfunction for the solution
gfu = GridFunction(X)
# parabolic inflow at inlet:
uin = CoefficientFunction( (1.5*4*y*(0.41-y)/(0.41*0.41), 0) )
gfu.components[0].Set(uin, definedon=mesh.Boundaries("inlet"))
# solve Stokes problem for initial conditions:
inv_stokes = a.mat.Inverse(X.FreeDofs())
print("number of free DOFS ",np.sum(np.array(X.FreeDofs(), dtype="int")))
res = f.vec.CreateVector()
res.data = f.vec - a.mat*gfu.vec
gfu.vec.data += inv_stokes * res
# plot velocity-mag
Draw (Norm(gfu.components[0]), mesh, "velocity", sd=3)
#%% setup functionals for NS equation
# NS functionals
def a(u, v):
return nu*InnerProduct(grad(u), grad(v))
def b(u,q):
return -(grad(u)[0,0]+grad(u)[1,1])*q
def c(w,u,v):
return InnerProduct(grad(u)*w,v)
# save solution from latest converged time step
gfu0 = GridFunction(X)
gfu0.vec.data = gfu.vec.data
u0 = gfu0.components[0]
p0 = gfu0.components[1]
# define BLF for iterative scheme
A = BilinearForm(X)
A += SymbolicBFI(u*v + tau*theta*( a(u,v) + c(gfu.components[0], u, v) )\
+ tau*( b(v,p) + b(u,q) - 1e-10*p*q ) )
if newton: # add extra term for newton method
A += SymbolicBFI(tau*theta*c(u, gfu.components[0], v) )
# define LF as BLF where u will be given
L = BilinearForm(X)
L += SymbolicBFI( u0*v - u*v\
+ tau*( (1-theta)*( -a(u0,v)-c(u0, u0,v) )\
+ theta*(-a(u,v)-c(u,u,v))\
- b(v,p) - b(u,q) +1e-10*p*q) )
#%% setup integrals for drag and lift coeff. calculation
# get domains normal vectors (correct direction)
n = -specialcf.normal(2)
#n = CoefficientFunction((-n[0],-n[1]))
# get domains tangential vectors
tang = CoefficientFunction((n[1],-n[0]))
# define integrads of drag and lift coeff.
bfv_cd = BoundaryFromVolumeCF(20*( nu*InnerProduct(grad(gfu.components[0])*n,tang)*n[1]-gfu.components[1]*n[0]) )
bfv_cl = BoundaryFromVolumeCF(-20*( nu*InnerProduct(grad(gfu.components[0])*n,tang)*n[0]+gfu.components[1]*n[1]) )
#%% solve NS equation iterative
# init sim.time
t = 0
# save time, drag and lift
time_vals = []
drag = []
lift = []
p1 = []
p2 = []
# save increments of nonlinear solution here
du = GridFunction(X)
# save LHS. of newton/picard iteration here
l = gfu.vec.CreateVector()
sim_time = time.time()
# start solver-loop
with TaskManager(): # enable multi threading
while(t<=tend): # time step loop
print("=====time {:0.6f}=====".format(t))
for it in range(20): # nonlinear-solver iteration
A.Assemble()
L.Apply(gfu.vec, l)
next_inv = A.mat.Inverse(freedofs=X.FreeDofs(), inverse="pardiso")
du.vec.data = next_inv * l
gfu.vec.data += du.vec.data
inc_next = sqrt(InnerProduct(du.vec,du.vec))
err_next = sqrt(InnerProduct(l,du.vec))
print ("\rerr={:0.4E}, increment {:0.4E}".format(err_next, inc_next), end="")
if err_next<1e-10: # check tolerance for iteration
break
Redraw()
# save converged timestep
gfu0.vec.data = gfu.vec.data
u0 = gfu.components[0]
p0 = gfu.components[1]
# increment time
t += tau
time_vals.append(t)
# save drag and lift
lift.append(Integrate(bfv_cl, mesh, definedon=mesh.Boundaries("cyl")))
drag.append(Integrate(bfv_cd, mesh, definedon=mesh.Boundaries("cyl")))
print("\nlift {:0.4f}".format(lift[-1]), "maxminlift {:0.4f}, {:0.4f}".format(np.max(lift),
np.min(lift)))
print("drag {:0.4f}".format(drag[-1]), "maxdrag {:0.4f}".format(np.max(drag)))
# save p1 p2 pressures
p1.append(gfu.components[1](mesh(0.15,0.2)))
p2.append(gfu.components[1](mesh(0.25,0.2)))
sim_time = time.time()-sim_time
time_vals = np.array(time_vals)
drag = np.array(drag)
lift = np.array(lift)
p1 = np.array(p1)
p2 = np.array(p2)
path = "./ex35data/"
filename = path+"solution_{}_{}_{}_{}_{:0.2f}_".format(el_order,tau,newton,theta,sim_time)
np.save(filename, np.array([time_vals,drag,lift,p1,p2]))
#solve_system(tau,tend,el_order,theta,newton=True):
#solve_system(0.001, 1, 2, 0,True)
#solve_system(0.01, 5, 3, 0.5,True)
#solve_system(0.01, 5, 3, 0.75,True)
#solve_system(0.01, 5, 3, 1,True)
#solve_system(0.01, 5, 4, 0.5,True)
solve_system(0.0005, 2, 3, 0,True)
solve_system(0.001, 2, 3, 0.25,True)
solve_system(0.01, 2, 3, 0.5,True)
solve_system(0.01, 2, 3, 0.75,True)
solve_system(0.01, 2, 3, 1,True)
solve_system(0.01, 5, 5, 0.5,True)
solve_system(0.005, 5, 5, 0.5,True)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 19 21:48:35 2020
@author: fabian
"""
import netgen.gui
from ngsolve import *
from netgen.geom2d import unit_square
from netgen.csg import unit_cube
mesh = Mesh(unit_square.GenerateMesh(maxh=0.3))
order=3
fes = H1(mesh, order=order)
gfu = GridFunction(fes)
Draw(gfu, sd=4)
mesh = Mesh(unit_square.GenerateMesh(maxh=0.3))
# basis functions on edge nr:
edge_dofs = fes.GetDofNrs(NodeId(EDGE,10))
print("edge_dofs =", edge_dofs)
SetVisualization(min=-0.05, max=0.05)
gfu.vec[:] = 0
gfu.vec[edge_dofs[0]] = 1
Redraw()<file_sep>from ngsolve import *
import netgen.gui
from netgen.geom2d import unit_square
from netgen.geom2d import SplineGeometry
#import matplotlib.pyplot as plt
import numpy as np
#import scipy.sparse as sp
nu = 1e-5
phi = x**2*(1-x)**2*y**2*(1-y)**2
u_sol = CoefficientFunction((-phi.Diff(y), phi.Diff(x)))
p_sol = x+y-1#x**5+y**5-1/3
# setup strain rate tensor
du = CoefficientFunction( ((u_sol[0].Diff(x), u_sol[0].Diff(y)),
(u_sol[1].Diff(x), u_sol[1].Diff(y)) ),dims=(2,2) )
eps_u = 1/2*(du + du.trans)
f = CoefficientFunction( ( (-2 * nu *(eps_u[0,0].Diff(x) + eps_u[0,1].Diff(y)) + p_sol.Diff(x)),
(-2 * nu *(eps_u[1,0].Diff(x) + eps_u[1,1].Diff(y)) + p_sol.Diff(y))) )
mesh = Mesh(unit_square.GenerateMesh(maxh=0.1))
Draw(mesh)
#P2+c
V = VectorH1(mesh, order=2, dirichlet=".*")
V.SetOrder(TRIG,3)
# P1c
Q = L2(mesh, order=1)
N = NumberSpace(mesh)
X = FESpace([V,Q,N])
(u,p,lam),(v,q,mu) = X.TnT()
eps_u = 1/2*(grad(u)+grad(u).trans)
eps_v = 1/2*(grad(v)+grad(v).trans)
a = BilinearForm(X)
a += (nu*InnerProduct(eps_u,eps_v)-div(v)*p-div(u)*q)*dx
a += (p*mu+q*lam)*dx
a.Assemble()
f_lf = LinearForm(X)
#f_lf += f*v.Operator("divfree_reconstruction")*dx
f_lf += f*v*dx
f_lf.Assemble()
gfu = GridFunction(X)
inv = a.mat.Inverse(freedofs=X.FreeDofs(), inverse="umfpack")
gfu.vec.data = inv*f_lf.vec
Draw(gfu.components[0], mesh, "fem_vel")
Draw(gfu.components[1], mesh, "fem_pres")
res = f_lf.vec.CreateVector()
res.data =f_lf.vec- a.mat*gfu.vec
force = GridFunction(V)
force.Set(f)
Draw(force.components[1], mesh, "force")
exact_sol = GridFunction(X)
exact_sol.components[0].Set((u_sol[0],u_sol[1]))
exact_sol.components[1].Set(p_sol)
delta_du = grad(exact_sol.components[0])-grad(gfu.components[0])
# H1 seminorm
du_norm = Integrate(InnerProduct(delta_du,delta_du),mesh)
print(du_norm)
#Draw(res.vec, mesh, "res")
#err = Integrate(res.data, mesh, VOL, element_wise=True)<file_sep>from ngsolve import *
import netgen.gui
from netgen.geom2d import SplineGeometry
import numpy as np
##Setup Geometry
def MakeGeometry(hmax):
geo = SplineGeometry()
geo.AddRectangle( (0, 0), (1, 1), bcs = ("wall", "wall", "wall", "wall"))
mesh = Mesh( geo.GenerateMesh(maxh=hmax))
Draw(mesh)
return mesh
def calcNorm(gfu,sol,mesh):
#Calc error
delta_u = sol.components[0]-gfu.components[0]
delta_du = grad(sol.components[0])-grad(gfu.components[0])
delta_p = sol.components[2]-gfu.components[2]
##Calculate norms
p_norm = Integrate(delta_p**2,mesh)
u_norm = Integrate(InnerProduct(delta_u,delta_u),mesh)
du_norm = Integrate(InnerProduct(delta_du,delta_du),mesh)
return [np.sqrt(u_norm), np.sqrt(du_norm), np.sqrt(p_norm)]
def tang(arr,n):
return arr-InnerProduct(arr,n)*n
def cust_div(arr):
return CoefficientFunction((arr[0,0]+arr[1,1]))
def cust_grad(arr):
return CoefficientFunction((arr[0].Diff(x),arr[0].Diff(y),arr[1].Diff(x),arr[1].Diff(y)),dims=(2,2))
def SolveSystem(X,psi,pressure,nu,mesh,alpha,k,enable_HDiv=False):
#Test and Trial functions
(u,uhat,p,lam),(v,vhat,q,mu) = X.TnT()
h = specialcf.mesh_size
n = specialcf.normal(2)
#Strain tensor
#eps_u = 0.5*(cust_grad(u)+cust_grad(u).trans)
#eps_v = 0.5*(cust_grad(v)+cust_grad(v).trans)
eps_u = 0.5*(grad(u)+grad(u).trans)
eps_v = 0.5*(grad(v)+grad(v).trans)
#Initializes solution and rhs
u_xe = psi.Diff(y)
u_ye = -psi.Diff(x)
sol_e = GridFunction(X)
sol_e.components[0].Set((u_xe,u_ye))
sol_e.components[2].Set(pressure)
grad_ue = cust_grad((u_xe,u_ye))
eps_nu_ue = -nu*0.5*(grad_ue + grad_ue.trans)
f = CoefficientFunction((eps_nu_ue[0,0].Diff(x)+eps_nu_ue[0,1].Diff(y),eps_nu_ue[1,0].Diff(x)+eps_nu_ue[1,1].Diff(y)))
f+= CoefficientFunction((pressure.Diff(x),pressure.Diff(y)))
#Draw(f, mesh, "f")
#Assemble BLF
a = BilinearForm(X)
if enable_HDiv:
a += (nu*InnerProduct(eps_u,eps_v)-div(u)*q-div(v)*p+lam*q+mu*p)*dx
a += -nu*InnerProduct(eps_u*n,tang(v-vhat,n))*dx(element_boundary=True)
a += -nu*InnerProduct(eps_v*n,tang(u-uhat,n))*dx(element_boundary=True)
a += nu*alpha/h*k**2*InnerProduct(tang(u-uhat,n),tang(v-vhat,n))*dx(element_boundary=True)
else:
a += (nu*InnerProduct(eps_u,eps_v)-cust_div(eps_u)*q-cust_div(eps_v)*p+lam*q+mu*p)*dx
a += -nu*InnerProduct(eps_u*n,v-vhat)*dx(element_boundary=True)
a += -nu*InnerProduct(eps_v*n,u-uhat)*dx(element_boundary=True)
a += nu*alpha*k**2*InnerProduct(u-uhat,v-vhat)/h*dx(element_boundary=True)
a += InnerProduct(u-uhat,n)*q*dx(element_boundary=True)
a += InnerProduct(v-vhat,n)*p*dx(element_boundary=True)
a.Assemble()
#Assemble LF
rhs = LinearForm(X)
rhs += f*v*dx(bonus_intorder=5)
rhs.Assemble()
##Solve System
gfu = GridFunction(X)
inv = a.mat.Inverse(freedofs=X.FreeDofs(), inverse="umfpack")
gfu.vec.data = inv*rhs.vec
return gfu, sol_e
#Set polynomial order, psi, pressure etc.
k = 3
alpha = 1e-2
#Solution and viscosity
psi = (x*(x-1)*y*(y-1))**2
p = x**5+y**5-1/3
#p = x+y-1
offset = 10
nu = np.power(10,(np.arange(-8,offset-8,1,dtype=float)))
#Error
errorHDG = np.zeros((offset,3))
errorHDGDiv = np.zeros((offset,3))
#Generate mesh
mesh = MakeGeometry(0.1)
#HDG Space
V1 = L2(mesh, order=k)
V2 = FacetFESpace(mesh,order=k,dirichlet="wall")
Q = L2(mesh,order=k-1)
N = NumberSpace(mesh)
X = V1**2 * V2**2 * Q * N
for i in range(offset):
gfu, exact = SolveSystem(X,psi,p,nu[i],mesh,alpha,k)
errorHDG[i,:] = calcNorm(gfu,exact,mesh)
Draw(gfu.components[0],mesh,"gfu_HDG")
Draw(exact.components[0],mesh,"exact")
#HDG Div Space
V1 = HDiv(mesh, order=k, dirichlet="wall")
V2 = TangentialFacetFESpace(mesh,order=k,dirichlet="wall")
Q = L2(mesh,order=k-1)
N = NumberSpace(mesh)
X = V1 * V2 * Q * N
for i in range(offset):
gfu, exact = SolveSystem(X,psi,p,nu[i],mesh,alpha,k,True)
errorHDGDiv[i,:] = calcNorm(gfu,exact,mesh)
Draw(gfu.components[0],mesh,"gfu_HDG_div")
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use("GTK3Agg")
plt.figure()
plt.loglog(nu,errorHDG[:,0],marker='o',label=r"$HDG$")
plt.loglog(nu,errorHDGDiv[:,0],marker='o',label=r"$HDG_{Div}$")
plt.grid(True, which="both",linewidth=0.5)
plt.xlabel(r"$\nu$",fontsize=12)
plt.ylabel(r"$|| u - u_h ||_{L^2}$",fontsize=12)
plt.legend()
plt.tick_params(axis='both', which='major', labelsize=12)
plt.figure()
plt.loglog(nu,errorHDG[:,1],marker='o',label=r"$HDG$")
plt.loglog(nu,errorHDGDiv[:,1],marker='o',label=r"$HDG_{Div}$")
plt.grid(True, which="both",linewidth=0.5)
plt.xlabel(r"$\nu$",fontsize=12)
plt.ylabel(r"$\| u - u_h \|_{H^1}$",fontsize=12)
plt.legend()
plt.tick_params(axis='both', which='major', labelsize=12)
plt.figure()
plt.loglog(nu,errorHDG[:,2],marker='o',label=r"$HDG$")
plt.loglog(nu,errorHDGDiv[:,2],marker='o',label=r"$HDG_{Div}$")
plt.grid(True, which="both",linewidth=0.5)
plt.xlabel(r"$\nu$",fontsize=12)
plt.ylabel(r"$|| p - p_h ||_{L^2}$",fontsize=12)
plt.legend()
plt.tick_params(axis='both', which='major', labelsize=12)
plt.show()<file_sep>from ngsolve import *
import netgen.gui
from netgen.geom2d import SplineGeometry
import numpy as np
def MakeGeometry(hmax):
geo = SplineGeometry()
geo.AddRectangle( (0, 0), (1, 1), bcs = ("wall", "wall", "wall", "wall"))
mesh = Mesh( geo.GenerateMesh(maxh=hmax))
return mesh
def SolveSystem(X,psi,pres,nu,mesh,alpha,k,enable_HDiv=False):
(u,u_hat,p,lam),(v,v_hat,q,mu) = X.TnT()
h = specialcf.mesh_size
n = specialcf.normal(2)
# construct exact solution
u_ex = CoefficientFunction( (psi.Diff(y), -psi.Diff(x)) )
sol_ex = GridFunction(X)
sol_ex.components[0].Set(u_ex)
sol_ex.components[2].Set(pres)
# generate a RHS
grad_ue = CoefficientFunction( (u_ex[0].Diff(x),
u_ex[0].Diff(y),
u_ex[1].Diff(x),
u_ex[1].Diff(y)),
dims=(2,2))
eps_nu_uex = -1/2*nu*(grad_ue + grad_ue.trans)
f = CoefficientFunction(( eps_nu_uex[0,0].Diff(x)+eps_nu_uex[0,1].Diff(y),
eps_nu_uex[1,0].Diff(x)+eps_nu_uex[1,1].Diff(y)))
f += CoefficientFunction((pres.Diff(x), pres.Diff(y)))
# generate HDG BLF
def eps(u):
return 1/2*(grad(u)+grad(u).trans)
def my_div(u):
return grad(u)[0,0]+grad(u)[1,1]
a = BilinearForm(X)
a += (nu*InnerProduct(eps(u),eps(v)) + lam*q + mu*p )*dx
a += (-nu*InnerProduct(eps(u)*n, v-v_hat))*dx(element_boundary=True)
a += (-nu*InnerProduct(eps(v)*n, u-u_hat))*dx(element_boundary=True)
a += ((nu*alpha*k*k/h)*InnerProduct(v-v_hat, u-u_hat))*dx(element_boundary=True)
a += (-my_div(u)*q)*dx + (InnerProduct(u-u_hat,n*q))*dx(element_boundary=True)
a += (-my_div(v)*p)*dx + (InnerProduct(v-v_hat,n*p))*dx(element_boundary=True)
a.Assemble()
rhs = LinearForm(X)
rhs += f*v*dx(bonus_intorder=5)
rhs.Assemble()
#Solve System
gfu = GridFunction(X)
inv = a.mat.Inverse(freedofs=X.FreeDofs(), inverse="umfpack")
gfu.vec.data = inv*rhs.vec
return gfu, sol_ex
nu = 100
h = 0.5
k = 3
alpha = 1e-2
psi = (x*(x-1)*y*(y-1))**2
pres = x**5+y**5-1/3
mesh = MakeGeometry(h)
#HDG Space
V = L2(mesh, order=k)
V_hat = FacetFESpace(mesh,order=k,dirichlet="wall")
Q = L2(mesh,order=k-1)
N = NumberSpace(mesh)
X = V**2 * V_hat**2 * Q * N
gfu, exact = SolveSystem(X, psi, pres, nu, mesh, alpha, k)
Draw(gfu.components[0],mesh,"gfu_HDG")
Draw(exact.components[0],mesh,"exact")
<file_sep>recentfile "/home/fabian/Desktop/femcfd/examprep/ex13.py"
<file_sep>from ngsolve import *
from netgen.geom2d import SplineGeometry
import matplotlib.pyplot as plt
import numpy as np
import time
def mesh_rectangle(hmax=0.1):
geo = SplineGeometry()
geo.AddRectangle( (0, 0), (1, 1), bcs = ("wall", "wall", "wall", "wall"))
mesh = Mesh( geo.GenerateMesh(maxh=hmax))
return mesh
def SolveStokes_rec(VxQ, nu=1, k=1, h=1, alpha=1):
X = FESpace(VxQ)
if len(VxQ)==3:
(u,p,lam),(v,q,mu) = X.TnT()
else:
(u,p),(v,q) = X.TnT()
a = BilinearForm(X)
def eps(u):
return 1/2*(grad(u) + grad(u).trans)
a += nu*InnerProduct(eps(u), eps(v))*dx
a += (-div(u)*q - div(v)*p)*dx
uH = u.Operator("hesse")
vH = v.Operator("hesse")
su = -nu*CoefficientFunction((2*uH[0,0] + uH[1,2] + uH[0,3],
2*uH[1,3] + uH[0,1] + uH[1,0]))+ grad(p)
sv = -nu*CoefficientFunction((2*vH[0,0] + vH[1,2] + vH[0,3],
2*vH[1,3] + vH[0,1] + vH[1,0])) +grad(q)
a += (-alpha*h*h*InnerProduct(su,sv) )*dx
if len(VxQ)==3:
a += (lam*q + mu*p)*dx
else:
a+= (-k*p*q)*dx
a.Assemble()
psi = (x*(x-1)*y*(y-1))**2
p_ex = x**5 + y**5 - 1/3
u_ex = CoefficientFunction( (psi.Diff(y), -psi.Diff(x)) )
sol_ex = GridFunction(X)
sol_ex.components[0].Set(u_ex)
sol_ex.components[1].Set(p_ex)
grad_ue = CoefficientFunction( (u_ex[0].Diff(x),
u_ex[0].Diff(y),
u_ex[1].Diff(x),
u_ex[1].Diff(y)),
dims=(2,2))
eps_nu_uex = -1/2*nu*(grad_ue + grad_ue.trans)
f = CoefficientFunction(( eps_nu_uex[0,0].Diff(x)+eps_nu_uex[0,1].Diff(y),
eps_nu_uex[1,0].Diff(x)+eps_nu_uex[1,1].Diff(y)))
f += CoefficientFunction((p_ex.Diff(x), p_ex.Diff(y)))
fstab = alpha*h*h*InnerProduct(f,sv)
#Draw(f, mesh, "f")
rhs = LinearForm(X)
rhs += (f*v - fstab)*dx
rhs.Assemble()
gfu = GridFunction(X)
inv = a.mat.Inverse(freedofs=X.FreeDofs(), inverse="umfpack")
gfu.vec.data = inv * rhs.vec
#Draw(gfu.components[0], mesh, "vel")
#Draw(gfu.components[1], mesh, "pressure")
#Draw(Norm(gfu.components[0]), mesh, "|vel|")
return gfu, sol_ex
def get_FEspace(dir_bc, order=[2,1], conti=[1,1], bubble=0, lag_multi=True):
VxQ = []
V = VectorH1(mesh, order=order[0], dirichlet = dir_bc)
if bubble>0:
V.SetOrder(TRIG, bubble)
V.Update()
VxQ.append(V)
if conti[1]==1:
Q = H1(mesh, order=order[1])
elif conti[1]==0:
Q = L2(mesh, order=order[1])
VxQ.append(Q)
if lag_multi: # lag. multi to enfore zero mean value constraint
N = NumberSpace(mesh)
VxQ.append(N)
return VxQ
def get_norms(gfu, sol_ex):
p_norm = Integrate((sol_ex.components[1]-gfu.components[1])**2,mesh)
delta_u = sol_ex.components[0]-gfu.components[0]
delta_du = grad(sol_ex.components[0])-grad(gfu.components[0])
u_norm = Integrate(InnerProduct(delta_u,delta_u),mesh)
du_norm = Integrate(InnerProduct(delta_du,delta_du),mesh)
p_L2 = p_norm**0.5
u_L2 = u_norm**0.5
u_H1s = du_norm**0.5
return p_L2, u_L2, u_H1s
H_max = np.array([1, 1/2, 1/4, 1/8, 1/16])
P_L2 = []
U_L2 = []
U_H1s = []
for h_max in H_max:
print("hmax = ", h_max)
geom = 1
if geom ==0:
mesh = mesh_cylinder()
dir_bc = "wall|inlet|cyl"
if geom ==1:
mesh = mesh_rectangle(h_max)
dir_bc = "wall"
VxQ = get_FEspace(dir_bc, order=[2,2], conti=[1,1], bubble=0, lag_multi=True)
gfu, sol_ex = SolveStokes_rec(VxQ, 10, 1e-4, h_max, 1e-5)
p_L2, u_L2, u_H1s = get_norms(gfu, sol_ex)
P_L2.append(p_L2)
U_L2.append(u_L2)
U_H1s.append(u_H1s)
print(u_L2)
time.sleep(0.5)
plt.ioff()
fig, ax = plt.subplots()
ax.loglog(H_max, P_L2,".-",label="p L2 ")
ax.loglog(H_max, U_L2,".-",label="u L2 ")
ax.loglog(H_max, U_H1s,".-",label="u H1 sem ")
ax.loglog(H_max, H_max,":",label="O(h)",color="black")
ax.loglog(H_max, H_max**2,":",label="O(h^2)",color="black")
ax.loglog(H_max, H_max**3,":",label="O(h^3)",color="black")
ax.legend(loc='upper left',fontsize=12)
ax.grid(True, which="both",linewidth=0.5)
ax.set_xlabel('$h_{max}$',fontsize=14)
ax.set_ylabel("error",fontsize=14)
plt.savefig("normsP2P2.pdf")
<file_sep>from os import listdir
from os.path import isfile, join
import numpy as np
import matplotlib.pyplot as plt
def get_last_period(time,val):
lift_diff = val[1:]-val[:-1]
lift_diffs = lift_diff[1:]*lift_diff[:-1]
id_extr = np.where(lift_diffs<0)[0]+1
if val[id_extr[1]]<val[id_extr[2]]:
id_min = id_extr[1::2]
id_max = id_extr[::2]
else:
id_min = id_extr[::2]
id_max = id_extr[1::2]
id_last_per = np.arange(id_min[-2], id_min[-1]+1)
return id_min, id_max, id_last_per
def get_period_props(time_per,val_per):
val_max = np.max(val_per)
val_min = np.min(val_per)
val_mean = np.mean(val_per)
per = time_per[-1]-time_per[0]
return val_max, val_min, val_mean, per
def plot_sols(sols):
props_per_sol = []
for sol in sols:
time = sol[0][0,:]
drag = sol[0][1,:]
lift = sol[0][2,:]
p1 = sol[0][3,:]
p2 = sol[0][4,:]
id_min, id_max, id_last_per = get_last_period(time, lift)
time_per = time[id_last_per]
drag_per = drag[id_last_per]
lift_per = lift[id_last_per]
p1p2_per = p1[id_last_per]-p2[id_last_per]
lift_max, lift_min, lift_mean, per = get_period_props(time_per, lift_per)
drag_max, drag_min, drag_mean, per = get_period_props(time_per, drag_per)
props_per_sol.append([time_per, drag_per, lift_per, p1p2_per,
lift_max, lift_min, lift_mean,
drag_max, drag_min, drag_mean, per])
fig0, ax0 = plt.subplots(figsize=(12,6))
fig1, ax1 = plt.subplots(figsize=(12,6))
fig2, ax2 = plt.subplots(figsize=(12,6))
for n, props_sol in enumerate(props_per_sol):
lab = make_name(sols[n][1])
ax0.plot(props_sol[0]-props_sol[0][0], props_sol[2],label=lab)
ax1.plot(props_sol[0]-props_sol[0][0], props_sol[1],label=lab)
ax2.plot(props_sol[0]-props_sol[0][0], props_sol[3],label=lab)
ax0.set_xlabel('time'); ax0.set_ylabel(r'C_L'); ax0.set_title('lift'); ax0.grid(True)
ax0.legend(loc="best")
ax1.set_xlabel('time'); ax1.set_ylabel('C_D'); ax1.set_title('drag'); ax1.grid(True)
ax1.legend(loc="best")
ax2.set_xlabel('time'); ax2.set_ylabel('p1-p2'); ax2.set_title('p1-p2'); ax2.grid(True)
ax2.legend(loc="best")
fig0.savefig("lift.pdf")
fig1.savefig("drag.pdf")
fig2.savefig("p1p2.pdf")
return props_per_sol
def plot_full_sol(sols,sol_ids):
fig0, ax0 = plt.subplots(figsize=(12,6))
fig1, ax1 = plt.subplots(figsize=(12,6))
fig2, ax2 = plt.subplots(figsize=(12,6))
for n in sol_ids:
lab = make_name(sols[n][1])
current_sol = sols[n][0]
ax0.plot(current_sol[0,:], current_sol[2,:],label=lab)
ax1.plot(current_sol[0,:], current_sol[1,:],label=lab)
ax2.plot(current_sol[0,:], current_sol[3,:]-current_sol[4,:],label=lab)
ax0.set_xlabel('time'); ax0.set_ylabel('lift'); ax0.set_title('lift'); ax0.grid(True)
ax0.legend(loc="best")
ax1.set_xlabel('time'); ax1.set_ylabel('drag'); ax1.set_title('drag'); ax1.grid(True)
ax1.legend(loc="best")
ax2.set_xlabel('time'); ax2.set_ylabel('p1-p2'); ax2.set_title('p1-p2'); ax2.grid(True)
ax2.legend(loc="best")
fig0.savefig("lift.pdf")
fig1.savefig("drag.pdf")
fig2.savefig("p1p2.pdf")
def read_references(links, forces):
datas = []
for link in links:
datas.append([np.concatenate((np.genfromtxt(link[0])[:,[1,3,4]].T,
np.genfromtxt(link[1])[:,[6,11]].T)), link[0].split("/")[-1]])
return datas
def make_name(filename):
props = filename.split("_")
if len(props)==4:
name = r"ref o={} {} {}".format(props[1][1], props[3], props[2])
else:
name =r"o={} dt={}, th={}".format(props[1], props[2], props[4])
return name
def plot_soltimes(sols):
sol_times =[]
labels = []
fig, ax = plt.subplots(figsize=(12,6))
for sol in sols:
sol_times.append(float(sol[1].split("_")[-2]))
labels.append(sol[1].split("_")[-3])
id_sorted= np.argsort(np.array(labels,dtype="float"))
ax.barh(np.array(labels)[id_sorted],np.array(sol_times)[id_sorted])
ax.set_xlabel('solve time in s'); ax.set_ylabel('theta'); ax.set_title('solve times'); ax.grid(True)
ax.legend(loc="best")
fig.savefig("solve_times_theta.pdf")
path = "./ex35data/"
my_files = listdir(path)
sols = []
for file in my_files:
sols.append([np.load(path+file), file])
#plot_soltimes(sols)
link_ref_fold = "reference_data/Q21/"
filenames = [("bdforces_q2_lv6_dt3","pointvalues_q2_lv6_dt3")]
#
links = [[link_ref_fold+"drag_lift/"+name[0],link_ref_fold+"press/"+name[1]] for name in filenames]
datas = read_references(links,forces=True)
sols = sols+datas
#plot_full_sol(sols,[0,1,2])
#
props_per_sol = plot_sols(sols)
<file_sep>recentfile "sol_ex3.tex"
<file_sep>
\usepackage[breakable]{tcolorbox}
\tcbset{nobeforeafter} % prevents tcolorboxes being placing in paragraphs
\usepackage{float}
\floatplacement{figure}{H} % forces figures to be placed at the correct location
\usepackage{multicol}
\usepackage[english]{babel}
\usepackage{tabularx}
\usepackage{subfigure}
\usepackage{picture}
\usepackage{amsmath}
\usepackage{hyperref}
\hypersetup{
colorlinks=true,
linkcolor=blue,
filecolor=magenta,
urlcolor=cyan,
}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{adjustbox} % Used to constrain images to a maximum size
\usepackage{xcolor} % Allow colors to be defined
\usepackage{enumerate} % Needed for markdown enumerations to work
\usepackage{geometry} % Used to adjust the document margins
\usepackage{amsmath} % Equations
\usepackage{amssymb} % Equations
\definecolor{urlcolor}{rgb}{0,.145,.698}
\definecolor{linkcolor}{rgb}{.71,0.21,0.01}
\definecolor{citecolor}{rgb}{.12,.54,.11}
% Prevent overflowing lines due to hard-to-break entities
\sloppy
% Setup hyperref package
\hypersetup{
breaklinks=true, % so long urls are correctly broken across lines
colorlinks=true,
urlcolor=urlcolor,
linkcolor=linkcolor,
citecolor=citecolor,
}
% Slightly bigger margins than the latex defaults
\geometry{verbose,tmargin=1in,bmargin=1in,lmargin=0.6in,rmargin=0.6in}
\usepackage{fancyhdr}
\pagestyle{fancy}
\renewcommand{\footrulewidth}{1pt}
\rhead{e12045110 , e12045110, e11921655}
\lhead{VU\,184.702\\ Machine Learning}
\cfoot{\thepage}
\setcounter{secnumdepth}{0}
\setlength\parindent{0pt}
\usepackage{booktabs}
\usepackage{listings}
\usepackage[linesnumbered,ruled,vlined]{algorithm2e}
\newcommand\mycommfont[1]{\footnotesize\ttfamily\textcolor{blue}{#1}}
\SetCommentSty{mycommfont}
\SetKwInput{KwInput}{Input} % Set the Input
\SetKwInput{KwOutput}{Output} % set the Output
<file_sep>from ngsolve import *
import netgen.gui
from netgen.geom2d import unit_square
from netgen.geom2d import SplineGeometry
import matplotlib.pyplot as plt
import numpy as np
import scipy.sparse as sp
k = 2
alpha = 4#1e3
mesh = Mesh(unit_square.GenerateMesh(maxh=0.1))
h = specialcf.mesh_size
V = H1(mesh, order=k)
u = V.TrialFunction()
v = V.TestFunction()
a = BilinearForm(V)
a += grad(u)*grad(v)*dx
a += -grad(u)*specialcf.normal(2)*v*ds(skeleton=True)
a += -grad(v)*specialcf.normal(2)*u*ds(skeleton=True)
a += alpha*k**2/h*u*v*ds(skeleton=True)
c = Preconditioner(a, "local")
f = LinearForm(V)
uD = 1
f += 30*cos(x)*cos(y) *v*dx
f += -grad(v)*specialcf.normal(2)*uD*ds(skeleton=True)
f += alpha*k**2/h*uD*v*ds(skeleton=True)
gfu = GridFunction(V)
V.Update()
a.Assemble()
f.Assemble()
gfu.Update()
## Conjugate gradient solver
inv = CGSolver(a.mat, c.mat, printrates = True, precision = 1e-8, maxsteps = 10000)
gfu.vec.data = inv * f.vec
#gfu.vec.data = a.mat.Inverse(V.FreeDofs(), inverse="sparsecholesky") * f.vec
Draw (gfu)
rows,cols,vals = a.mat.COO()
A = sp.csr_matrix((vals,(rows,cols)))
print("condition number: {}".format(np.linalg.cond(A.todense())))
<file_sep>from ngsolve import *
import netgen.gui
from netgen.geom2d import SplineGeometry
import numpy as np
import ngsolve.meshes as ngm
import matplotlib.pyplot as plt
import time
def MakeGeometry(L):
mesh = ngm.MakeStructured2DMesh(quads=False, nx=2, ny=2)
for i in range(L+1):
mesh.Refine()
return mesh
def solve_system(L=1, eps=0.01, b_wind=(2,1), k=1, plots=False):
mesh = MakeGeometry(L)
b = CoefficientFunction(b_wind)
def my_exp(b,x_coord,eps):
return (exp(b*x_coord/eps)-1)/(exp(b/eps)-1)
f = b[0]*( y - my_exp(b[1],y,eps)) + b[1]*( x - my_exp(b[0],x,eps))
u_exct = ( y - my_exp(b[1],y,eps)) * ( x - my_exp(b[0],x,eps))
V = H1(mesh, order=k, dirichlet="bottom|right|left|top")
u, v = V.TnT()
a = BilinearForm(V)
a += (eps*InnerProduct(grad(u), grad(v)))*dx
a += (InnerProduct(b, grad(u))*v)*dx
a.Assemble()
rhs = LinearForm(V)
rhs += (f*v)*dx
rhs.Assemble()
gfu = GridFunction(V)
try:
inv = a.mat.Inverse(freedofs=V.FreeDofs(), inverse="pardiso")
except:
inv = a.mat.Inverse(freedofs=V.FreeDofs(), inverse="umfpack")
gfu.vec.data = inv*rhs.vec
if plots:
Draw(gfu,mesh,"gfu")
Draw(f, mesh,"f")
Draw(u_exct, mesh,"u_exct")
return u_exct, gfu, mesh
def solve_SUPG(L=1, eps=0.01, b_wind=(2,1), k=1,
plots=False, stabilize=True):
mesh = MakeGeometry(L=L)
b = CoefficientFunction(b_wind)
def my_exp(b,x_coord,eps):
return (exp(b*x_coord/eps)-1)/(exp(b/eps)-1)
f = b[0]*( y - my_exp(b[1],y,eps)) + b[1]*( x - my_exp(b[0],x,eps))
u_exct = ( y - my_exp(b[1],y,eps)) * ( x - my_exp(b[0],x,eps))
#b_abs = InnerProduct(b,b)**0.5
b_abs = (b[0]**2+b[1]**2)**0.5
# get the mesh peclet number
h = specialcf.mesh_size
Ph = b_abs*h/eps
# calc stabilisation parameter
#alpha = IfPos(Ph-1, h/b_abs, 0)
alpha = h/b_abs
V = H1(mesh, order=k, dirichlet="bottom|right|left|top")
u, v = V.TnT()
a = BilinearForm(V)
a += (eps*InnerProduct(grad(u), grad(v)))*dx
a += (InnerProduct(b, grad(u))*v)*dx
if stabilize:
u_H = u.Operator("hesse")
Del_u = u_H[0,0] + u_H[1,1]
rh = -eps*Del_u + InnerProduct(b,grad(u))
a += (alpha*rh*InnerProduct(b, grad(v)))*dx
a.Assemble()
rhs = LinearForm(V)
rhs += (f*v)*dx
if stabilize:
rhs += (alpha*f*InnerProduct(b,grad(v)))*dx
rhs.Assemble()
gfu = GridFunction(V)
try:
inv = a.mat.Inverse(freedofs=V.FreeDofs(), inverse="pardiso")
except:
inv = a.mat.Inverse(freedofs=V.FreeDofs(), inverse="umfpack")
gfu.vec.data = inv*rhs.vec
if plots:
Draw(gfu,mesh,"gfu")
Draw(f, mesh,"f")
Draw(u_exct, mesh,"u_exct")
Draw(Ph, mesh,"Ph")
Draw(alpha, mesh,"alpha")
return u_exct, gfu, mesh
def solve_HDG(L=1, eps=0.01, b_wind=(2,1), k=1, plots=False):
mesh = MakeGeometry(L=L)
b = CoefficientFunction(b_wind)
def my_exp(b,x_coord,eps):
return (exp(b*x_coord/eps)-1)/(exp(b/eps)-1)
f = b[0]*( y - my_exp(b[1],y,eps)) + b[1]*( x - my_exp(b[0],x,eps))
u_exct = ( y - my_exp(b[1],y,eps)) * ( x - my_exp(b[0],x,eps))
n = specialcf.normal(2)
h = specialcf.mesh_size
alpha = 3
kappa = 1
#HDG Space
V = L2(mesh, order=k)
V_hat = FacetFESpace(mesh,order=k,dirichlet="bottom|right|left|top")
X = V * V_hat
(u,u_hat),(v,v_hat) = X.TnT()
a = BilinearForm(X)
# a_HGD, lagrange multiplier
a += (eps*InnerProduct(grad(u),grad(v)) )*dx
a += (-eps*InnerProduct(grad(u), n)*(v-v_hat))*dx(element_boundary=True)
a += (-eps*InnerProduct(grad(v), n)*(u-u_hat))*dx(element_boundary=True)
a += ((eps*alpha*k*k/h)*(v-v_hat)*(u-u_hat))*dx(element_boundary=True)
# c_HDG
u_up = IfPos(b*n, u, u_hat)
c_Tout = IfPos(b*n, b*n*(u_hat-u)*v_hat, 0)
a += ( -InnerProduct(u*b, grad(v)) )*dx
a += ( InnerProduct(b,n)*u_up*v )*dx(element_boundary=True)
a += ( c_Tout )*dx(element_boundary=True)
a.Assemble()
rhs = LinearForm(X)
rhs += (f*v)*dx
rhs.Assemble()
gfu = GridFunction(X)
try:
inv = a.mat.Inverse(freedofs=X.FreeDofs(), inverse="pardiso")
except:
inv = a.mat.Inverse(freedofs=X.FreeDofs(), inverse="umfpack")
gfu.vec.data = inv*rhs.vec
if plots:
Draw(gfu.components[0],mesh,"gfu")
Draw(f, mesh,"f")
Draw(u_exct, mesh,"u_exct")
gfu_out = GridFunction(V)
gfu_out.vec.data = gfu.components[0].vec.data
return u_exct, gfu_out, mesh
def get_err_norm(gfu, u_exct, mesh):
delta_u = u_exct-gfu
u_norm = Integrate(InnerProduct(delta_u,delta_u),mesh)
u_L2 = u_norm**0.5
return u_L2
def run_ex(ex_nr=1):
# refinements
L = [0,1,2,3,4]
# orders
K = [1,2,3]
# L2 error
errs = []
for k in K:
errs.append([])
for l in L:
if(ex_nr==1):
u_exct, gfu , mesh = solve_system(L=l,k=k)
elif(ex_nr==2):
u_exct, gfu , mesh = solve_SUPG(L=l, k=k)
elif(ex_nr==3):
u_exct, gfu , mesh = solve_HDG(L=l, k=k)
u_L2 = get_err_norm(gfu, u_exct, mesh)
errs[-1].append(u_L2)
print(u_L2)
plt.ioff()
fig, ax = plt.subplots()
for err, k in zip(errs,K):
ax.semilogy( L, err,".-",label="order= {}".format(k))
for n in range(1,4):
ax.semilogy(L,(1/2)**(n*np.array(L)),"--",color="black")
ax.legend(loc='best',fontsize=12)
ax.grid(True, which="both",linewidth=0.5)
ax.set_xlabel('L level of refinement',fontsize=14)
ax.set_ylabel("error",fontsize=14)
ax.set_ylim([1e-4,1e-0])
plt.show()
plt.savefig("norms_ex3{}.pdf".format(ex_nr))
def plot_line(px, py=0.5):
plt.ioff()
fig = plt.figure(figsize=(16,8))
gs = fig.add_gridspec(3,4,hspace=0, wspace=0)
ax = gs.subplots(sharex="col", sharey="row")
# refinements
L = [0,1,2,3]
# orders
K = [1,2,3]
for k in K:
for l in L:
u_exct, gfu , mesh = solve_system(L=l,k=k,)
vals = [gfu(mesh(p,py)) for p in px]
ax[k-1,l].plot(px,vals)
u_exct, gfu , mesh = solve_SUPG(L=l, k=k)
vals = [gfu(mesh(p,py)) for p in px]
ax[k-1,l].plot(px,vals)
u_exct, gfu , mesh = solve_HDG(L=l, k=k)
vals = [gfu(mesh(p,py)) for p in px]
ax[k-1,l].plot(px,vals)
#ax[k-1,l].set_ylim([-0.6,0.6])
fig.text(0.5,0.03,"x at y=0.5, left L=0 right L=3",ha="center")
fig.text(0.03,0.5,"fuction value, top k=1 bottom k=3",va="center", rotation="vertical")
plt.show()
#plt.savefig("cut_ex3_123.pdf")
#solve_system(L=3, eps=0.01, k=3, plots=True)
#run_ex(ex_nr=1)
run_ex(ex_nr=2)
#run_ex(ex_nr=3)
#plot_line(np.linspace(0,1,100),py=0.5)
#run_ex32()
#u_exct, gfu , mesh = solve_SUPG(hmax=0.08, k=3,plots=True,
# eps=0.01, stabilize=True)
<file_sep>from ngsolve import *
import netgen.gui
from netgen.geom2d import SplineGeometry
import matplotlib.pyplot as plt
import numpy as np
##Setup Geometry
def MakeGeometry(hmax):
geo = SplineGeometry()
geo.AddRectangle( (0, 0), (1, 1), bcs = ("wall", "wall", "wall", "wall"))
mesh = Mesh( geo.GenerateMesh(maxh=hmax))
Draw(mesh)
return mesh
#SolveStokes
def SolveStokes(X,nu,alpha,h,mesh,consistent=True):
##Test and Trialfunctions
(u,p,lam),(v,q,mu) = X.TnT()
eps_u = 1/2*(grad(u)+grad(u).trans)
eps_v = 1/2*(grad(v)+grad(v).trans)
##Initializes solution and rhs
psi = (x*(x-1)*y*(y-1))**2
pres = x**5 + y**5 - 1/3
u_xe = psi.Diff(y)
u_ye = -psi.Diff(x)
exact_sol = GridFunction(X)
exact_sol.components[0].Set((u_xe,u_ye))
exact_sol.components[1].Set(pres)
grad_ue = CoefficientFunction((u_xe.Diff(x),u_xe.Diff(y),u_ye.Diff(x),u_ye.Diff(y)),dims=(2,2))
eps_nu_ue = -nu*1/2*(grad_ue + grad_ue.trans)
f = CoefficientFunction((eps_nu_ue[0,0].Diff(x)+eps_nu_ue[0,1].Diff(y),eps_nu_ue[1,0].Diff(x)+eps_nu_ue[1,1].Diff(y)))
f+= CoefficientFunction((pres.Diff(x),pres.Diff(y)))
Draw(f, mesh, "f")
Hesse = u.Operator("hesse")
div_eps_u =CoefficientFunction((Hesse[0,0]+0.5*(Hesse[0,2]+Hesse[1,1]),Hesse[1,3]+0.5*(Hesse[1,0]+Hesse[0,1])))
Hesse = v.Operator("hesse")
div_eps_v = CoefficientFunction((Hesse[0,0]+0.5*(Hesse[0,2]+Hesse[1,1]),Hesse[1,3]+0.5*(Hesse[1,0]+Hesse[0,1])))
##Assemble BLF
a = BilinearForm(X)
a += (InnerProduct(eps_u,eps_v)-div(u)*q-div(v)*p+lam*q+mu*p)*dx
##Add Stabilization
a += -alpha*h*h*(InnerProduct(-nu*div_eps_u+grad(p),-nu*div_eps_v+grad(q)))*dx
a.Assemble()
##Assemble LF
rhs = LinearForm(X)
rhs += f*v*dx
##Add consistency term
if consistent:
rhs += -alpha*h*h*InnerProduct(f,-nu*div_eps_v+grad(q))*dx
rhs.Assemble()
##Solve System
gfu = GridFunction(X)
inv = a.mat.Inverse(freedofs=X.FreeDofs(), inverse="sparsecholesky")
gfu.vec.data = inv*rhs.vec
return gfu, exact_sol
## Setup ##
index = 6
alpha = 1e-6
nu = 1
hmax = np.exp2(-np.arange(1,index))
norm_u = np.zeros(index-1)
norm_du = np.zeros(index-1)
norm_p = np.zeros(index-1)
#Mini H1-P1-bubble, H1-P1
#P2P0 H1-P2, L2-const
#P2-bubble H1-P2-bubble, L2-P1
for i in range(index-1):
mesh = MakeGeometry(hmax[i])
V = VectorH1(mesh, order=2, dirichlet="wall")
#V.SetOrder(TRIG,3)
Q = H1(mesh, order=2)
N = NumberSpace(mesh)
X = FESpace([V,Q,N])
##Solve System
gfu, sol = SolveStokes(X,nu,alpha,hmax[i],mesh,True)
delta_u = sol.components[0]-gfu.components[0]
delta_du = grad(sol.components[0])-grad(gfu.components[0])
##Calculate norms
p_norm = Integrate((sol.components[1]-gfu.components[1])**2,mesh)
u_norm = Integrate(InnerProduct(delta_u,delta_u),mesh)
du_norm = Integrate(InnerProduct(delta_du,delta_du),mesh)
norm_p[i] = np.sqrt(p_norm)
norm_u[i] = np.sqrt(u_norm)
norm_du[i] = np.sqrt(du_norm)
## Draw stuff
# Draw(gfu.components[0], mesh, "fem_vel")
# Draw(gfu.components[1], mesh, "fem_pres")
# Draw(sol.components[0], mesh, "exact_vel")
# Draw(sol.components[1], mesh, "exact_pres")
fig, ax = plt.subplots()
ax.loglog(hmax,norm_p,marker='o',label='$||p||_{L_2}$')
ax.loglog(hmax,norm_u,marker='o',label='$||u||_{L_2}$')
ax.loglog(hmax,norm_du,marker='o',label='$|u|_{H_1}$')
ax.loglog(hmax,hmax)
ax.loglog(hmax,np.power(hmax,2))
ax.grid(True, which="both",linewidth=0.5)
ax.set_xlabel('$h_{max}$',fontsize=14)
ax.set_ylabel("error",fontsize=14)
ax.tick_params(axis='both', which='major', labelsize=12)
ax.legend(loc='upper left',fontsize=12)
plt.show()
<file_sep>\documentclass[11pt]{article}
\input{Packages}
\title{Exercise 3}
\author{e11921655 <NAME>}
\date{\today}
\begin{document}
\graphicspath{{./figures/}}
\maketitle
\section{Part1}
\includegraphics[width=0.7\columnwidth]{norms_ex31.pdf}
\section{Part2}
\includegraphics[width=0.7\columnwidth]{norms_ex32.pdf}
\section{Part3}
\includegraphics[width=0.7\columnwidth]{norms_ex33.pdf}
\includegraphics[width=\columnwidth]{cut_ex3_123.pdf}
\section{Part4}
\subsection{solution for $\nu=0.01$ at $L=3$}
\includegraphics[width=\columnwidth]{ex34_001_stream}
\subsection{solution for $\nu=0.002$ at $L=3$}
\includegraphics[width=\columnwidth]{ex34_0002_stream}
\subsection{solution for $\nu=0.001$ at $L=3$}
\includegraphics[width=\columnwidth]{ex34_0001_stream}
\subsection{Iterations needed for convergence}
\begin{tabular}{l| l l l l}
Method, L & 0 &1 &2 &3 \\
\hline
$\nu=0.01$\\
Newton & 5 & 5&5 &5\\
Picard & 15 & 16&16 &16\\
\hline
$\nu=0.002$\\
Newton & - & 10&8 &8\\
Picard & 79 & 32&34 &34\\
\hline
$\nu=0.001$\\
Newton & - & - &- &-\\
Picard & - & 48&37 &38\\
\end{tabular}
\section{Part5}
\subsection{Weak form of NS-equation}
Assume we given the NS-equations in weak form with $(u, p)\in V \times Q=H_0^1(\Omega)^2\times\L_0^2(\Omega)$:
\begin{align}
(\frac{du}{dt}, v) + a(u, v) + c(u,u,v) + b(v,p) + b(u,q) + \epsilon(p,q) = f(v) \quad \forall (v,q)\in V \times Q
\end{align}
\subsection{Time discretisation by $\theta$-scheme}
\begin{align}
(u^{n+1}, v) + \theta \tau a(u^{n+1}, v) +& \theta \tau c(u^{n+1},u^{n+1},v) + \tau b(v,p^{n+1}) + \tau b(u^{n+1},q) \tau (p^{n+1},q) =\notag \\
&\tau f(v) + (u^{n}, v) -(1-\theta) \tau a(u^{n}, v) - (1-\theta) \tau c(u^{n},u^{n},v)
\end{align}
Next assume $u_{i+1}^{n+1}=u_i^{n+1} + \delta u_i^{n+1}$ and $p_{i+1}^{n+1}=p_i^{n+1} + \delta p_i^{n+1}$ where $u^{n+1}_0 = u^{n+1}_K$ and $p^{n+1}_0 = p^{n+1}_K$ for $K\rightarrow \infty$.
Note further:
\begin{align}
c(u^{n+1}_{i+1},u^{n+1}_{i+1},v) = c(u^{n+1}_{i},\delta u^{n+1}_{i},v) + c(\delta u^{n+1}_{i},u^{n+1}_{i},v) +c(u^{n+1}_{i},u^{n+1}_{i},v) +c(\delta u^{n+1}_{i},\delta u^{n+1}_{i},v)
\end{align}
Then for a Newton method we assume $c(\delta u^{n+1}_{i},\delta u^{n+1}_{i},v)$ and for the picard iteration additionally $c(\delta u^{n+1}_{i},u^{n+1}_{i},v)$.
\subsection{Newton iteration}
\begin{align}
&(\delta u^{n+1}_i, v) + \theta \tau \left[ a(\delta u^{n+1}_i, v) + c(\delta u^{n+1}_i,u^{n+1}_i,v)+c(u^{n+1}_i,\delta u^{n+1}_i,v) )\right] + \tau\left[ b(v,\delta p^{n+1}_i) + b(\delta u^{n+1}_i,q) + \epsilon (\delta p^{n+1}_i,q)\right] = \notag \\
&(u^{n+1}_0 -u^{n+1}_i , v) + \tau f(v) + (1-\theta) \tau \left[-a(u^{n+1}_0, v) - c(u^{n+1}_0,u^{n+1}_0,v)\right]
+ \theta \tau\left[- a(u^{n+1}_i, v) - c(u^{n+1}_i,u^{n+1}_i,v)\right]\notag \\
&+ \tau\left[-b(v,p^{n+1}_i) - b(u^{n+1}_i,q) - \epsilon (p^{n+1}_i,q) \right]
\end{align}
\subsection{Picard iteration}
\begin{align}
&(\delta u^{n+1}_i, v) + \theta \tau\left[ c(\delta u^{n+1}_i,u^{n+1}_i,v)+c(u^{n+1}_i,\delta u^{n+1}_i,v) )\right] + \tau\left[ b(v,\delta p^{n+1}_i) + b(\delta u^{n+1}_i,q) + \epsilon (\delta p^{n+1}_i,q)\right] = \notag \\
&(u^{n+1}_0 -u^{n+1}_i , v) + \tau f(v) + (1-\theta) \tau \left[-a(u^{n+1}_0, v) - c(u^{n+1}_0,u^{n+1}_0,v)\right]
+ \theta \tau\left[- a(u^{n+1}_i, v) - c(u^{n+1}_i,u^{n+1}_i,v)\right]\notag \\
&+ \tau\left[-b(v,p^{n+1}_i) - b(u^{n+1}_i,q) - \epsilon (p^{n+1}_i,q) \right]
\end{align}
\subsection{Space discretisation by Tailor-Hood element}
The Taylor-Hood pair of order $k$ is given by:
\begin{align}
& V_h := \{v \in H_0^1(\Omega)^2:\ v|_T\in P^k(T)^2\quad \forall T\in\mathcal{T}_h \} \notag \\
& Q_h := \{q \in L_0^2(\Omega)\cap C(\bar{\Omega}):\ q|_T\in P^k(T)\quad \forall T\in\mathcal{T}_h \} \notag \\
\end{align}
\subsection{Mesh}
We choose a trtraheder mesh with 972 Elements and 550 vertices. The global mesh size is 0.05 where the local redinement at the cylinder wall is choosen to be 0.009. The mesh is shown below:
\includegraphics[width=0.7\columnwidth]{mesh35}
To improve the solution quality p-refinements were conducted for different orders $k$ of the Taylor hood space where in contrast to that h-refinements were choosen for the reference solutions. In the Table below we compare cases where h-refinement of the reference and p-refinements of our solution yield a simillar number of free-dofs.
\begin{tabular}{l l l l}
Lv ref. & order this & free-dofs ref. & free-dofs this\\
2 & 2 & 2704 & 4221\\
3 & 3 & 10608 & 10504\\
- & 4 & - & 19709\\
4 & 5 & 42016 & 31836\\
6 & - & 667264& -
\end{tabular}
\subsection{Investigating influence of $\theta$ values on solution for $t\in[0,2]$}
\includegraphics[width=0.75\columnwidth]{lift_full_theta}
\includegraphics[width=0.75\columnwidth]{lift_theta}
\includegraphics[width=0.75\columnwidth]{drag_theta}
\includegraphics[width=0.75\columnwidth]{p1p2_theta}
\includegraphics[width=0.75\columnwidth]{solve_times_theta}
\subsection{Comparing $\theta\geq 0.5$ methods for $t\in[0,5]$}
\includegraphics[width=0.75\columnwidth]{lift_full_implicit}
\includegraphics[width=0.75\columnwidth]{drag_full_implicit}
\includegraphics[width=0.75\columnwidth]{p1p2_full_implicit}
\includegraphics[width=0.75\columnwidth]{lift_full_implicit_per}
\includegraphics[width=0.75\columnwidth]{drag_full_implicit_per}
\includegraphics[width=0.75\columnwidth]{p1p2_full_implicit_per}
\subsection{p-refinement at $\theta= 0.5$ method for $t\in[0,5]$}
\includegraphics[width=0.75\columnwidth]{lift_final}
\includegraphics[width=0.75\columnwidth]{drag_final}
\includegraphics[width=0.75\columnwidth]{p1p2_final}
%Bibliography
\newpage
\bibliographystyle{plain}
\bibliography{Biblothek}
\end{document}
<file_sep>import numpy as np
import matplotlib.pyplot as plt
from ngsolve import *
from ngsolve.solvers import *
import ngsolve.meshes as ngm
from netgen.geom2d import SplineGeometry
from netgen.geom2d import unit_square
def plot_BD():
x1 = 0.5
x_top = np.linspace(0,1,100)
def u1(x_top, x1):
ux = x_top*0+1
ux[x_top<=x1] = 1 - 1/4 *(1-np.cos( (x1-x_top[x_top<=x1])/x1*np.pi ))**2
ux[x_top>=1-x1] = 1 - 1/4 *(1-np.cos((x_top[x_top>=1-x1]-(1-x1))/x1*np.pi))**2
return ux
plt.ioff()
fig, ax = plt.subplots()
ax.plot(x_top, u1(x_top, 0.2),label="0.2")
ax.plot(x_top, u1(x_top, 0.5),label=0.5)
ax.plot(x_top, u1(x_top, 0.9),label=0.9)
ax.legend(loc="best")
plt.savefig("cavity_BDvel.pdf")
def mesh_rectangle(hmax=0.1):
#geo = SplineGeometry()
#geo.AddRectangle( (0, 0), (1, 1))
#mesh = Mesh( geo.GenerateMesh(maxh=hmax))
mesh = Mesh(unit_square.GenerateMesh(maxh=hmax))
return mesh
def mesh_byrefinement(L=0):
mesh = ngm.MakeStructured2DMesh(quads=False,nx=2,ny=2)
for i in range(L+1):
mesh.Refine()
return mesh
def get_P2bubble(meshi):
V = VectorH1(mesh, order=2, dirichlet = "bottom|right|left|top")
V.SetOrder(TRIG, 3)
V.Update()
Q = L2(mesh, order=1)
return [V,Q]
def Solve_cavity(VxQ, nu=1, x1=0.5, newton=True, show_plots=False):
X = FESpace(VxQ)
(u,p),(v,q) = X.TnT()
def eps(u):
return 1/2*(grad(u) + grad(u).trans)
def a(u,v):
return nu*InnerProduct(grad(u), grad(v))
def b(u,q):
return -(grad(u)[0,0]+grad(u)[1,1])*q
def c(w,u,v):
return InnerProduct(grad(u)*w,v)
# solving stokes
A = BilinearForm(X)
A += a(u,v)*dx
A += ( b(v,p) + b(u,q) - 1e-10*p*q)*dx
A.Assemble()
L = LinearForm(X)
L.Assemble()
gfu = GridFunction(X)
# add u with BC but f=0
#uin = CoefficientFunction( (1.5*4*y*(0.41-y)/(0.41*0.41), 0) )
uin = CoefficientFunction(1)
uin1 = CoefficientFunction(1-1/4*(1-cos( (x1-x)/x1*np.pi ))**2)
uin2 = CoefficientFunction(1-1/4*(1-cos( (x-(1-x1))/x1*np.pi ))**2)
uin = IfPos(x-x1, uin, uin1)
uin = IfPos(x-(1-x1), uin2, uin)
utop = CoefficientFunction((uin,0))
if show_plots:
Draw(utop, mesh, "utop")
gfu.components[0].Set(utop, definedon=mesh.Boundaries("top"))
res = L.vec.CreateVector()
# homogenize solution
res.data = - A.mat * gfu.vec # get residual f-Ax
inv_stokes = A.mat.Inverse(freedofs=X.FreeDofs(), inverse="umfpack")
gfu.vec.data += inv_stokes * res
# residuals for nonlinear iteration
def ruh(uk,pk,v):
return - c(uk,uk,v) - a(uk,v) - b(v,pk)
def rph(uk,q):
return -b(uk,q)
A1 = BilinearForm(X)
# newton
if newton:
A1 += SymbolicBFI(c(gfu.components[0], u, v) + c(u, gfu.components[0], v)\
+a(u,v) + b(v, p) + b(u,q) - 1e-10*p*q)
else: # picard
A1 += SymbolicBFI(c(gfu.components[0], u, v) + a(u,v) + b(v, p) + b(u,q) - 1e-10*p*q )
l_ruh = BilinearForm(X)
l_ruh += ruh(u, p, v)*dx
l_rph = BilinearForm(X)
l_rph += rph(u,q)*dx
L1 = BilinearForm(X)
L1 += ruh(u, p, v)*dx + rph(u,q)*dx + (1e-10*p*q)*dx
l_ruh.Assemble()
l_rph.Assemble()
L1.Assemble()
du = gfu.vec.CreateVector()
gfu_old = gfu.vec.CreateVector()
r_uh = gfu.vec.CreateVector()
r_ph = gfu.vec.CreateVector()
l1 = gfu.vec.CreateVector()
DU = GridFunction(X)
counter=0
for it in range(300):
print("iteration ",it)
A1.Assemble()
L1.Apply(gfu.vec, l1)
next_inv = A1.mat.Inverse(freedofs=X.FreeDofs(), inverse="umfpack")
DU.vec.data = next_inv * l1
gfu.vec.data += DU.vec.data
print(InnerProduct(DU.vec,DU.vec))
l_ruh.Apply(gfu.vec, r_uh)
l_rph.Apply(gfu.vec, r_ph)
error= sqrt(abs(InnerProduct(DU.vec,l1 )))
print(error)
counter +=1
if error<1e-10:
break
elif error>1e10:
counter = -1
break
elif it==299:
counter = -2
if show_plots:
Draw(gfu.components[0], mesh, "vel")
Draw(gfu.components[1], mesh, "pressure")
Draw(Norm(gfu.components[0]), mesh, "|vel|")
SetVisualization(max=2)
return gfu, counter
#iter_counts = []
#
#L = [0,1,2,3]
#Nu = [0.01, 0.002, 0.001]
#
#
#for nu in Nu:
# for l in L:
# mesh = mesh_byrefinement(L=l)
# VxQ = get_P2bubble(mesh)
# gfu, counter = Solve_cavity(VxQ, nu=nu, x1=0.1,newton=True)
# iter_counts.append(counter)
# mesh = mesh_byrefinement(L=l)
# VxQ = get_P2bubble(mesh)
# gfu, counter = Solve_cavity(VxQ, nu=nu, x1=0.1,newton=False)
# iter_counts.append(counter)
#print(iter_counts)
mesh = mesh_byrefinement(L=3)
VxQ = get_P2bubble(mesh)
gfu, counter = Solve_cavity(VxQ, nu=0.001, x1=0.1,newton=False,show_plots=True)
<file_sep>from ngsolve import *
import netgen.gui
from netgen.geom2d import SplineGeometry
import numpy as np
import ngsolve.meshes as ngm
import matplotlib.pyplot as plt
import time
def MakeGeometry(L, hmax=0.1):
if L>=0: # use refinement
mesh = ngm.MakeStructured2DMesh(quads=False, nx=2, ny=2)
for i in range(L+1):
mesh.Refine()
else:
geo = SplineGeometry()
geo.AddRectangle( (0, 0), (1, 1) )
mesh = Mesh( geo.GenerateMesh(maxh=hmax))
return mesh
def solve_system(L=-1,hmax=0.1, eps=0.01, b_wind=(2,1), k=1, plots=False):
mesh = MakeGeometry(L=L,hmax=hmax)
b = CoefficientFunction(b_wind)
def my_exp(b,x_coord,eps):
return (exp(b*x_coord/eps)-1)/(exp(b/eps)-1)
f = b[0]*( y - my_exp(b[1],y,eps)) + b[1]*( x - my_exp(b[0],x,eps))
u_exct = ( y - my_exp(b[1],y,eps)) * ( x - my_exp(b[0],x,eps))
n = specialcf.normal(2)
h = specialcf.mesh_size
alpha = 3
kappa = 1
#HDG Space
V = L2(mesh, order=k)
V_hat = FacetFESpace(mesh,order=k,dirichlet=[1,2,3,4])
X = V * V_hat
(u,u_hat),(v,v_hat) = X.TnT()
a = BilinearForm(X)
# a_HGD, lagrange multiplier
a += (eps*InnerProduct(grad(u),grad(v)) )*dx
a += (-eps*InnerProduct(grad(u), n)*(v-v_hat))*dx(element_boundary=True)
a += (-eps*InnerProduct(grad(v), n)*(u-u_hat))*dx(element_boundary=True)
a += ((eps*alpha*k*k/h)*(v-v_hat)*(u-u_hat))*dx(element_boundary=True)
# c_HDG
u_up = IfPos(b*n, u, u_hat)
c_Tout = IfPos(b*n, b*n*(u_hat-u)*v_hat, 0)
a += ( -InnerProduct(u*b, grad(v)) )*dx
a += ( InnerProduct(b,n)*u_up*v )*dx(element_boundary=True)
a += ( c_Tout )*dx(element_boundary=True)
a.Assemble()
rhs = LinearForm(X)
rhs += (f*v)*dx
rhs.Assemble()
gfu = GridFunction(X)
inv = a.mat.Inverse(freedofs=X.FreeDofs(), inverse="umfpack")
gfu.vec.data = inv*rhs.vec
if plots:
Draw(gfu.components[0],mesh,"gfu")
Draw(f, mesh,"f")
Draw(u_exct, mesh,"u_exct")
return u_exct, gfu, mesh
solve_system(plots=True, k=3, eps=0.01,L=3)
|
80897f2beb602c5e8f4d9a8cca521c13e95c89ab
|
[
"TeX",
"INI",
"Python"
] | 16 |
TeX
|
Holzberger/ngsolve-examples
|
c87f46924daef62399907ca44757eba4796a2dfd
|
2bb23a98a7400de887f606aa6411ac101e820dff
|
refs/heads/master
|
<repo_name>pradeepsundaram/ComponentFramework<file_sep>/src/controls/RadioButton.java
package controls;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import pages.WebPage;
import reports.Report;
import exception.CFException;
public class RadioButton {
private WebElement radioButton;
private By by;
private String rbName;
private String rbDesc;
/**
* Constructor of radio button
*
* @author PSubramani33
* @param rbID
* @param desc
*/
public RadioButton(String rbID,String desc){
rbName=rbID;
rbDesc=desc;
}
/**
* This method will choose the radio button
*
* @author <NAME>
*/
public void choose() {
by=getBy(rbName);
radioButton=ElementUtil.findElement(by);
WebPage.elementList.put(radioButton, rbDesc);
try {
ElementUtil.choose(radioButton);
} catch (CFException e) {
e.printStackTrace();
}
}
/**
* This method will return the By for the Check Box
*
* @author <NAME>
* @return By
*/
public By getBy() {
return by;
}
/**
* This method will return the webelement of the check box
*
* @author <NAME>
* @return WebElement
*/
public WebElement getWebElement(){
radioButton=ElementUtil.findElement(by);
return radioButton;
}
/**
* will return boolean based on the presence of the radio button
*
* @author <NAME>
* @return boolean
*/
public boolean isDisplayed() {
radioButton=ElementUtil.findElement(by);
Report.log("Checking whether the field \"" + WebPage.elementList.get(radioButton)+"\" is displayed.<BR>");
return radioButton.isDisplayed();
}
/**
* will return true when radio button is there in the page, will return true even it is not displayed in the page.
* using java script the radio button may not be visible but radio button may there in the page.
*
* @author <NAME>
* @return boolean
*/
public boolean isEnabled() {
radioButton=ElementUtil.findElement(by);
Report.log("Checking whether the field \"" + WebPage.elementList.get(radioButton)+"\" is enabled.<BR>");
return radioButton.isEnabled();
}
private By getBy(String elementName){
By newBy=null;
if (elementName.startsWith("name")) {
by=ElementUtil.byName(elementName);
} else if (elementName.startsWith("css")) {
by=ElementUtil.byCss(elementName);
} else if (elementName.startsWith("//")) {
by=ElementUtil.byXpath(elementName);
} else if (elementName.startsWith("id")) {
by=ElementUtil.byID(elementName);
} else{
by=ElementUtil.byIDOrName(elementName);
}
return newBy;
}
}
<file_sep>/src/controls/Link.java
package controls;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import pages.WebPage;
import reports.Report;
import exception.CFException;
public class Link {
private WebElement link;
private By by;
private String linkName;
private String linkDesc;
public Link(String linkText,String desc){
linkDesc=desc;
linkName=linkText;
}
public Link(String linkText){
link=ElementUtil.findElementByLinkText(linkText);
WebPage.elementList.put(link, linkText);
}
/**
* This method will click in the link passed as argument
*
* @author <NAME>
*/
public void click(){
by=getBy(linkName);
link=ElementUtil.findElement(by);
WebPage.elementList.put(link, linkDesc);
try {
ElementUtil.click(link);
} catch (CFException e) {
e.printStackTrace();
}
}
/**
* This method will return the By for the button
*
* @author <NAME>
* @return By
*/
public By getBy() {
return by;
}
/**
* This method will return the text displayed in the text
*
* @author <NAME>
* @return String
*/
public String getText(){
by=getBy(linkName);
link=ElementUtil.findElement(by);
WebPage.elementList.put(link, linkDesc);
return link.getText();
}
/**
* This method will return the webelement of the link
* @author <NAME>
* @return WebElement
*/
public WebElement getWebElement(){
by=getBy(linkName);
link=ElementUtil.findElement(by);
WebPage.elementList.put(link, linkDesc);
return link;
}
/**
* will return boolean based on the presence of the link
*
* @author <NAME>
* @return boolean
*/
public boolean isDisplayed() {
link=ElementUtil.findElement(by);
WebPage.elementList.put(link, linkDesc);
Report.log("Checking whether the field \"" + WebPage.elementList.get(link)+"\" is displayed.<BR>");
return link.isDisplayed();
}
private By getBy(String elementName){
By newBy=null;
if (linkName.startsWith("id")) {
newBy = ElementUtil.byID(linkName);
}
else if (linkName.startsWith("css")) {
newBy = ElementUtil.byCss(linkName);
}
else if (linkName.startsWith("//")) {
newBy = ElementUtil.byXpath(linkName);
}
else if (linkName.startsWith("link")) {
newBy = ElementUtil.byLinkText(linkName);
} else {
newBy = ElementUtil.byIDOrName(linkName);
}
return newBy;
}
}
<file_sep>/src/controls/ElementUtil.java
package controls;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import utils.Events;
import exception.CFException;
public class ElementUtil {
static WebDriver driver;
static Events events;
public ElementUtil(WebDriver webDriver) {
driver = webDriver;
events=new Events(driver);
}
public static WebElement findElement(By by) {
return driver.findElement(by);
}
public static WebElement findElementByID(String elementID) {
return driver.findElement(By.id(elementID));
}
public static WebElement findElementByName(String elementID) {
return driver.findElement(By.name(elementID));
}
public static Select findSelect(By by) {
return new Select(driver.findElement(by));
}
public static WebElement findElementByLinkText(String elementLinkText) {
String[] elementID = elementLinkText.split("=");
return driver.findElement(By.linkText(elementID[1]));
}
public static By byXpath(String elementXpath) {
return By.xpath(elementXpath);
}
public static By byID(String elementID) {
String[] eleID = elementID.split("=");
System.out.println("element id is "+eleID[1]);
return By.id(eleID[1]);
}
public static By byIDOrName(String elementID) {
By by=null;
try{
by=By.id(elementID);
driver.findElement(by);
}
catch(NoSuchElementException e){
by=By.name(elementID);
}
return by;
}
public static By byName(String elementName) {
String[] elementID = elementName.split("=");
return By.name(elementID[1]);
}
public static By byNameNew(String elementName) {
return By.name(elementName);
}
public static By byCss(String elementCss) {
String[] elementID = elementCss.split("=");
return By.cssSelector(elementID[1]);
}
public static By byLinkText(String elementLinkText) {
String[] elementID = elementLinkText.split("=");
return By.linkText(elementID[1]);
}
/**
* This method will click the link with its ID
*
* @author <NAME>
* @param elementLinkText
* @return
*/
public static By byLink(String elementLinkText) {
return By.linkText(elementLinkText);
}
public static By selectByXpath(String elementXpath) {
return By.xpath(elementXpath);
}
public static By selectByID(String elementID) {
String[] eleID = elementID.split("=");
return By.id(eleID[1]);
}
public static By selectByName(String elementName) {
String[] elementID = elementName.split("=");
return By.name(elementID[1]);
}
public static By selectByCss(String elementCss) {
String[] elementID = elementCss.split("=");
return By.cssSelector(elementID[1]);
}
public static void click(WebElement webElement) throws CFException {
events.click(webElement);
}
public static void type(WebElement webElement, String text) throws CFException {
events.type(webElement, text);
}
public static void select(Select selectField,
int index) throws CFException {
events.select(selectField, index);
}
public static void selectByValue(Select selectField, String value) throws CFException {
events.selectByValue(selectField, value);
}
public static void selectByText(Select selectField,
String selectString) throws CFException {
events.selectByText(selectField, selectString);
}
public static void check(WebElement webElement) throws CFException {
events.check(webElement);
}
public static void unCheck(WebElement webElement) throws CFException {
events.unCheck(webElement);
}
public static void choose(WebElement webElement) throws CFException {
events.choose(webElement);
}
public static void doubleClick(WebElement webElement) throws CFException {
events.doubleClick(webElement);
}
}
<file_sep>/src/dto/DataObject.java
package dto;
public class DataObject {
public String getQty1() {
return qty1;
}
public void setQty1(String qty1) {
this.qty1 = qty1;
}
public String getQty2() {
return qty2;
}
public void setQty2(String qty2) {
this.qty2 = qty2;
}
String qty;
String qty1;
String qty2;
String itemCode;
String cardNumber;
String cardHolderName;
String cardExpMonth;
String cardExpYear;
String asFrequency;
String asShipdate;
String cardType;
public String getCardType() {
return cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}
public String getAsFrequency() {
return asFrequency;
}
public void setAsFrequency(String asFrequency) {
this.asFrequency = asFrequency;
}
public String getAsShipdate() {
return asShipdate;
}
public void setAsShipdate(String asShipdate) {
this.asShipdate = asShipdate;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
public String getItemCode() {
return itemCode;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getCardHolderName() {
return cardHolderName;
}
public void setCardHolderName(String cardHolderName) {
this.cardHolderName = cardHolderName;
}
public String getCardExpMonth() {
return cardExpMonth;
}
public void setCardExpMonth(String cardExpMonth) {
this.cardExpMonth = cardExpMonth;
}
public String getCardExpYear() {
return cardExpYear;
}
public void setCardExpYear(String cardExpYear) {
this.cardExpYear = cardExpYear;
}
}
<file_sep>/src/dataProviders/.svn/text-base/CSVDataProvider.java.svn-base
package dataProviders;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.testng.ITestContext;
import org.testng.annotations.DataProvider;
import dto.DataObject;
public class CSVDataProvider {
@DataProvider
public static Iterator<Object[]> CSVFileDataProvider(ITestContext context) {
String inputFile = context.getCurrentXmlTest().getParameter(
"CSVFilePath");
List<DataObject> testData = getCSVFileContent(inputFile);
List<Object[]> returnedData = new ArrayList<Object[]>();
for (DataObject userData : testData) {
returnedData.add(new Object[] { userData });
}
return returnedData.iterator();
}
private static List<DataObject> getCSVFileContent(String filenamePath) {
InputStream is;
List<DataObject> lines = new ArrayList<DataObject>();
try {
is = new FileInputStream(new File(filenamePath));
DataInputStream in = new DataInputStream(is);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
DataObject data = new DataObject();
String dataArray[] = strLine.split(",");
// data.setUserName(dataArray[0]);
//data.setPassword(dataArray[1]);
lines.add(data);
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}
}
<file_sep>/src/controls/ElementFinder.java
package controls;
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class ElementFinder {
WebDriver driver;
public ElementFinder(WebDriver webDriver){
driver=webDriver;
}
public WebElement findElementByXpath(String elementXpath){
return driver.findElement(By.xpath(elementXpath));
}
public ArrayList<Object> findElementByXpath1(String elementXpath){
ArrayList<Object> element=new ArrayList<Object>();
element.add(driver.findElement(By.xpath(elementXpath)));
element.add(By.xpath(elementXpath));
return element;
}
public WebElement findElementByID(String elementID){
String []eleID= elementID.split("=");
return driver.findElement(By.id(eleID[1]));
}
public WebElement findElementByName(String elementName){
String []elementID= elementName.split("=");
return driver.findElement(By.name(elementID[1]));
}
public WebElement findElementByCss(String elementCss){
String []elementID= elementCss.split("=");
return driver.findElement(By.cssSelector(elementID[1]));
}
public WebElement findElementByLinkText(String elementLinkText){
String []elementID= elementLinkText.split("=");
return driver.findElement(By.linkText(elementID[1]));
}
public Select findSelectByXpath(String elementXpath){
return new Select(driver.findElement(By.xpath(elementXpath)));
}
public Select findSelectByID(String elementID){
String []eleID= elementID.split("=");
return new Select(driver.findElement(By.id(eleID[1])));
}
public Select findSelectByName(String elementName){
String []elementID= elementName.split("=");
return new Select(driver.findElement(By.name(elementID[1])));
}
public Select findSelectByCss(String elementCss){
String []elementID= elementCss.split("=");
return new Select(driver.findElement(By.cssSelector(elementID[1])));
}
}
<file_sep>/src/reports/Report.java
package reports;
import org.testng.Reporter;
public class Report {
/**
* writes the mesage to report
*
* @author <NAME>
* @param logMessage
*/
public static void log1(String logMessage){
Reporter.log(logMessage+"<BR>");
}
/**
* writes the message to console
*
* @author <NAME>
* @param logMessage
* @param toStandardOutput
*/
public static void log2(String logMessage, boolean toStandardOutput){
Reporter.log(logMessage+"<BR>",toStandardOutput);
}
/**
* writes the mesage to report
*
* @author <NAME>
* @param logMessage
*/
public static void log(String logMessage){
LogHelper.Logger.log(logMessage);
}
/**
* writes the message to console
*
* @author <NAME>
* @param logMessage
* @param toStandardOutput
*/
public static void log(String logMessage, boolean toStandardOutput){
LogHelper.Logger.log(logMessage,toStandardOutput);
}
}
<file_sep>/src/controls/CheckBox.java
package controls;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import pages.WebPage;
import reports.Report;
import exception.CFException;
public class CheckBox {
private WebElement checkBox;
private By by;
String checkBoxID;
String desc;
public CheckBox(String checkBoxName,String description){
checkBoxID=checkBoxName;
desc=description;
}
/**
* This method will check the check box if it is unchecked
*
* @author <NAME>
*/
public void check() {
by=getBy(checkBoxID);
checkBox=ElementUtil.findElement(by);
WebPage.elementList.put(checkBox, desc);
try {
ElementUtil.check(checkBox);
} catch (CFException e) {
e.printStackTrace();
}
}
/**
* this method will uncheck the check box if it is checked, leaves it if the
* check box is not checked
*
* @author <NAME>
*/
public void unCheck() {
by=getBy(checkBoxID);
checkBox=ElementUtil.findElement(by);
WebPage.elementList.put(checkBox, desc);
try {
ElementUtil.unCheck(checkBox);
} catch (CFException e) {
e.printStackTrace();
}
}
/**
* This method will return whether the Check box is checked in the page
* @throws IOException
*/
public boolean isChecked() {
by=getBy(checkBoxID);
checkBox=ElementUtil.findElement(by);
WebPage.elementList.put(checkBox, desc);
return checkBox.isSelected();
}
/**
* This method will return the By for the Check Box
* @author <NAME>
* @param elem
* @return
*/
public By getBy() {
return by;
}
/**
* This method will return the webelement of the check box
*
* @author <NAME>
* @return
*/
public WebElement getWebElement(){
checkBox=ElementUtil.findElement(by);
return checkBox;
}
/**
* will return boolean based on the presence of the check box
*
* @author <NAME>
* @return boolean
*/
public boolean isDisplayed() {
checkBox=ElementUtil.findElement(by);
Report.log("Checking whether the field \"" + WebPage.elementList.get(checkBox)+"\" is displayed.<BR>");
return checkBox.isDisplayed();
}
private By getBy(String elementName){
By newBy=null;
if(checkBoxID.startsWith("name")){
newBy=ElementUtil.byName(checkBoxID);
}
else if(checkBoxID.startsWith("css")){
newBy=ElementUtil.byCss(checkBoxID);
}
else if(checkBoxID.startsWith("//")){
newBy=ElementUtil.byXpath(checkBoxID);
}
else if(checkBoxID.startsWith("id")){
newBy=ElementUtil.byID(checkBoxID);
}
else{
newBy=ElementUtil.byIDOrName(checkBoxID);
}
return newBy;
}
}
<file_sep>/src/utils/EventsUtil.java
package utils;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import pages.WebPage;
import reports.Report;
import events.WindowEvents;
public class EventsUtil implements KeyEvents, WindowEvents {
public Robot robot;
public Actions builder;
/*@Override
public void mouseOver(WebElement webElement) {
builder.moveToElement(webElement).perform();
Report.log("Moving mouse over " + WebPage.elementList.get(webElement)
+ "<BR>");
}*/
public void doubleClick(WebDriver driver, WebElement webElement) {
builder=new Actions(driver);
builder.doubleClick(webElement);
Report.log("Moving mouse over " + WebPage.elementList.get(webElement));
}
public void pressEscKey() {
try{
robot = new Robot();
robot.delay(500);
robot.keyPress(KeyEvent.VK_ESCAPE);
Report.log("Pressing Esc key ");
}
catch(AWTException awte){
awte.printStackTrace();
}
}
public void pressBackSpace() {
try{
robot = new Robot();
robot.delay(500);
robot.keyPress(KeyEvent.VK_BACK_SPACE);
Report.log("Pressing back space key ");
}
catch(AWTException awte){
awte.printStackTrace();
}
}
public void pressTabKey() {
try{
robot = new Robot();
robot.delay(500);
robot.keyPress(KeyEvent.VK_TAB);
Report.log("Pressing TAB key ");
}
catch(AWTException awte){
awte.printStackTrace();
}
}
public void keyDownAlt() {
try{
robot = new Robot();
robot.delay(500);
robot.keyPress(KeyEvent.VK_ALT);
Report.log("key down Alt key ");
}
catch(AWTException awte){
awte.printStackTrace();
}
}
public void pressShiftTabKey(int howManyTimes) {
try{
robot = new Robot();
robot.delay(100);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.delay(500);
this.pressTabKey(howManyTimes);
robot.delay(500);
robot.keyRelease(KeyEvent.VK_SHIFT);
Report.log("Pressing Shift+TAB keys " + howManyTimes + " times ");
}
catch(AWTException awte){
awte.printStackTrace();
}
}
public void pressTabKey(int howManyTimes) {
try{
robot = new Robot();
for (int i = 0; i < howManyTimes; i++) {
robot.delay(500);
robot.keyPress(KeyEvent.VK_TAB);
}
Report.log("Pressing TAB key for " + howManyTimes + " times ");
}
catch(AWTException awte){
awte.printStackTrace();
}
}
public void pressEnterKey() {
try{
robot = new Robot();
robot.delay(500);
robot.keyPress(KeyEvent.VK_ENTER);
Report.log("Pressing ENTER key ");
}
catch(AWTException awte){
awte.printStackTrace();
}
}
public void pressSpaceBar() {
try{
robot = new Robot();
robot.delay(1000);
robot.keyPress(KeyEvent.VK_SPACE);
}
catch(AWTException awte){
awte.printStackTrace();
}
}
public void selectFrame(WebDriver driver, String frameName) {
driver.switchTo().frame(frameName);
}
public void selectWindow(WebDriver driver, String windowName) {
driver.switchTo().window(windowName);
}
public void type(String text) {
try{
robot = new Robot();
robot.delay(500);
String[] textArray = text.split("");
for (int i = 1; i < textArray.length; i++) {
robot.delay(500);
robot.keyPress(TextUtil.getAsciiVal(textArray[i]));
Report.log("Entering " + textArray[i]);
}
}
catch(AWTException awte){
awte.printStackTrace();
}
}
public void pressShiftKey() {
try{
robot = new Robot();
robot.delay(500);
robot.keyPress(KeyEvent.VK_SHIFT);
Report.log("Pressing shift key ");
}
catch(AWTException awte){
awte.printStackTrace();
}
}
public void pressCtrlKey() {
try{
robot = new Robot();
robot.delay(500);
robot.keyPress(KeyEvent.VK_CONTROL);
Report.log("Pressing ctrl key ");
}
catch(AWTException awte){
awte.printStackTrace();
}
}
public void releaseCtrlKey() {
try{
robot = new Robot();
robot.delay(500);
robot.keyRelease(KeyEvent.VK_CONTROL);
Report.log("Releasing ctrl key ");
}
catch(AWTException awte){
awte.printStackTrace();
}
}
public void releaseShiftKey() {
try{
robot = new Robot();
robot.delay(500);
robot.keyRelease(KeyEvent.VK_SHIFT);
Report.log("Pressing shift key ");
}
catch(AWTException awte){
awte.printStackTrace();
}
}
/**
* presses down arrow key
*
* @author <NAME>
*/
public void pressDownKey() {
try{
robot = new Robot();
robot.delay(500);
robot.keyPress(KeyEvent.VK_DOWN);
Report.log("Pressing down arrow key ");
}
catch(AWTException awte){
awte.printStackTrace();
}
}
/**
* Releases down arrow key
*
* @author <NAME>
*/
public void releaseDownKey() {
try{
robot = new Robot();
robot.delay(500);
robot.keyRelease(KeyEvent.VK_DOWN);
Report.log("Releasing down arrow key ");
}
catch(AWTException awte){
awte.printStackTrace();
}
}
public void switchToMainPage(WebDriver driver) {
// TODO Auto-generated method stub
}
}
<file_sep>/src/controls/DateControl.java
package controls;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import pages.WebPage;
import exception.CFException;
public class DateControl {
private WebElement dateControl;
private By by;
String dateName;
String dateDesc;
// private ElementUtil elementUtil;
public DateControl(WebElement date, String desc) {
dateControl = date;
WebPage.elementList.put(dateControl, desc);
}
public DateControl(String dateControl,String description){
dateName=dateControl;
dateDesc=description;
/*if(dateName.startsWith("name")){
by=ElementUtil.byName(dateName);
}
else if(dateName.startsWith("css")){
by=ElementUtil.byCss(dateName);
}
else if(dateName.startsWith("//")){
by=ElementUtil.byXpath(dateName);
}
else if(dateName.startsWith("id")){
by=ElementUtil.byID(dateName);
}
else{
by=ElementUtil.byIDOrName(dateName);
}*/
WebPage.elementList.put(dateControl, description);
}
/**
* This method will select a date in Date controls
*
* @author <NAME>
*/
public void click() {
if(dateName.startsWith("name")){
by=ElementUtil.byName(dateName);
}
else if(dateName.startsWith("css")){
by=ElementUtil.byCss(dateName);
}
else if(dateName.startsWith("//")){
by=ElementUtil.byXpath(dateName);
}
else if(dateName.startsWith("id")){
by=ElementUtil.byID(dateName);
}
else{
by=ElementUtil.byIDOrName(dateName);
}
dateControl=ElementUtil.findElement(by);
try {
ElementUtil.click(dateControl);
} catch (CFException e) {
e.printStackTrace();
}
}
/**
* This method will return By of the dateControl
*
* @author <NAME>
* @return By
*/
public By getBy(){
return by;
}
/**
* This method will return the webelement for date control
* @author <NAME>
* @return WebElement
*/
public WebElement getWebElement(){
dateControl=ElementUtil.findElement(by);
return dateControl;
}
}
<file_sep>/src/controls/TextArea.java
package controls;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import pages.WebPage;
import reports.Report;
import exception.CFException;
public class TextArea {
private WebElement textArea;
private By by;
private String taName;
private String taDesc;
public TextArea(String taID,String desc){
taName=taID;
taDesc=desc;
}
/**
* This method will type the passed text in TextArea
*
* @author <NAME>
* @param text
* @throws IOException
*/
public void type(String text){
by=getBy(taName);
textArea=ElementUtil.findElement(by);
WebPage.elementList.put(textArea, taDesc);
try {
ElementUtil.type(textArea, text);
} catch (CFException e) {
e.printStackTrace();
}
}
/**
* This method will return the By for the Text Area
*
* @author <NAME>
* @return By
*/
public By getBy() {
return by;
}
/**
* This method will return the webelement of the textarea
* @author <NAME>
* @return WebElement
*/
public WebElement getWebElement(){
textArea=ElementUtil.findElement(by);
return textArea;
}
/**
* will return boolean based on the presence of the text area
*
* @author <NAME>
* @return boolean
*/
public boolean isDisplayed() {
textArea=ElementUtil.findElement(by);
Report.log("Checking whether the field \"" + WebPage.elementList.get(textArea)+"\" is displayed.<BR>");
return textArea.isDisplayed();
}
private By getBy(String elementName){
By newBy=null;
if (elementName.startsWith("name")) {
by=ElementUtil.byName(elementName);
} else if (elementName.startsWith("css")) {
by=ElementUtil.byCss(elementName);
} else if (elementName.startsWith("//")) {
by=ElementUtil.byXpath(elementName);
} else if (elementName.startsWith("id")) {
by=ElementUtil.byID(elementName);
} else{
by=ElementUtil.byIDOrName(elementName);
}
return newBy;
}
}
<file_sep>/src/controls/Label.java
package controls;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import pages.WebPage;
import reports.Report;
public class Label {
private By by;
private WebElement lbl;
private String labelName;
private String labelDesc;
// private ElementUtil elementUtil;
public Label(String label,String description){
labelName=label;
labelDesc=description;
}
/**
* This method will return the content in the Label
*
* @author <NAME>
* @return String
*
*/
public String getText() {
by=getBy(labelName);
lbl=ElementUtil.findElement(by);
WebPage.elementList.put(lbl, labelDesc);
return lbl.getText();
}
/**
* This method will return the By of the label
* @author <NAME>
* @return
*/
public By getBy() {
return by;
}
/**
* This method will return the webElement of the label
* @author <NAME>
* @return WebElement
*/
public WebElement getWebElement() {
lbl=ElementUtil.findElement(by);
return lbl;
}
/**
* will return boolean based on the presence of the label
*
* @author <NAME>
* @return boolean
*/
public boolean isDisplayed() {
lbl=ElementUtil.findElement(by);
Report.log("Checking whether the field \"" + WebPage.elementList.get(lbl)+"\" is displayed.<BR>");
return lbl.isDisplayed();
}
private By getBy(String elementName){
By newBy=null;
if (elementName.startsWith("name")) {
by=ElementUtil.byName(elementName);
} else if (elementName.startsWith("css")) {
by=ElementUtil.byCss(elementName);
} else if (elementName.startsWith("//")) {
by=ElementUtil.byXpath(elementName);
} else if (elementName.startsWith("id")) {
by=ElementUtil.byID(elementName);
} else{
by=ElementUtil.byIDOrName(elementName);
}
return newBy;
}
}
|
870ba963edc88cb2ee1e8bfbe44f1d2628ed7151
|
[
"Java"
] | 12 |
Java
|
pradeepsundaram/ComponentFramework
|
676c9812364bac37e8d94f311b760970518a1b1a
|
46ed886b5e08a700f17b74093ffeebdd67eb0ff5
|
refs/heads/main
|
<repo_name>john-manack/apple_ceos_sql<file_sep>/schema.sql
CREATE TABLE apple_ceos (
id serial PRIMARY KEY,
name text NOT NULL,
slug text NOT NULL,
year integer
);<file_sep>/models/conn.js
// THIS IS A HELPER FILE THAT CAN BE USED EACH TIME WE NEED TO IMPLEMENT PGP IN POSTGRESQL
'use strict';
const host = 'localhost',
database = 'apple_ceos';
// You DO NOT want a production-ready server spitting out database queries to the console upon each query (that'd be bad); but for dev purposes, we want to be able to see these outputs in the console
const pgp = require('pg-promise')({
query: function (event) {
console.log('QUERY:', event.query);
}
});
const options = {
host,
database
}
const db = pgp(options);
module.exports = db;<file_sep>/README.md
# Apple CEOs in PostgreSQL
This exercise creates a schema file and seed file to create a table in PostgreSQL.
|
a03517229766ff7b76bc93ad2560646107574f1f
|
[
"Markdown",
"SQL",
"JavaScript"
] | 3 |
Markdown
|
john-manack/apple_ceos_sql
|
3c77291cdfda5372b6f8bf4f580f3f7dccddcbca
|
91cb490a55e666d09dfb6572700b20bede97374e
|
refs/heads/master
|
<repo_name>ollybee/sflowtool-dockerfile<file_sep>/Dockerfile
FROM debian:jessie
MAINTAINER <EMAIL>
EXPOSE 6343/udp
RUN apt-get update\
&& apt-get install -y --no-install-recommends build-essential curl
RUN curl -O http://www.inmon.com/bin/sflowtool-3.22.tar.gz && tar -xvzf sflowtool-3.22.tar.gz
RUN cd sflowtool-3.22 && ./configure && make && make install
RUN apt-get remove --auto-remove --purge -y build-essential curl
ENTRYPOINT ["sflowtool"]
CMD ["--help"]
|
0a7981d2903784f1c03436921f56828d906fa34d
|
[
"Dockerfile"
] | 1 |
Dockerfile
|
ollybee/sflowtool-dockerfile
|
f16ba466ce06cf8ec541126c244b399700bc3ae1
|
0969757be40b7849ce0d04631bd9f503e8306555
|
refs/heads/master
|
<file_sep>#!/bin/bash
if [ $# -ne 1 ]
then
echo "too many or too few arguments"
exit 84
fi
if [ ! -f "$1" ]
then
echo "file doesn't exist"
exit 84
fi
if [ ! -s "$1" ]
then
echo "empty file"
exit 84
fi
MAKE_DIR=$(cat $1 | grep "PROJECT_DIR" | cut -d ';' -f 2)
if [ ! -e $MAKE_DIR ]
then
echo "no project"
exit 84
fi
MAKE_DIR+="/Makefile"
echo 'SOURCES_DIR = ' | tr -d "\n" > $MAKE_DIR
cat $1 | grep "SOURCES_DIR" | cut -d ';' -f 2 | tr -d "\n" | tr -d "//" >> $MAKE_DIR
echo '/' >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
echo 'CC = ' | tr -d "\n" >> $MAKE_DIR
cat $1 | grep "CC" | cut -d ';' -f 2 >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
echo 'SRC = ' | tr -d "\n" >> $MAKE_DIR
printf "\t" | tr -d "\n" >> $MAKE_DIR
cat $1 | grep "\.c" | cut -d ';' -f 1 | sed -re 's/ /\t\\\n\t/g' >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
echo 'OBJ = $(addprefix $(SOURCES_DIR),$(SRC:.c=.o))' >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
echo 'CFLAGS = ' | tr -d "\n" >> $MAKE_DIR
echo "-I./" | tr -d "\n" >> $MAKE_DIR
cat $1 | grep "HEADERS_DIR" | cut -d ';' -f 2 | tr -d "\n" >> $MAKE_DIR
echo '/' | tr -d "\n" >> $MAKE_DIR
echo ' ' | tr -d "\n" >> $MAKE_DIR
cat $1 | grep "CFLAGS" | cut -d ';' -f 2 >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
echo 'LDFLAGS = ' | tr -d "\n" >> $MAKE_DIR
cat $1 | grep "LDFLAGS" | cut -d ';' -f 2 >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
echo 'LIB = ' | tr -d "\n" >> $MAKE_DIR
cat $1 | grep "LIBS_DIR" | cut -d ';' -f 2 >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
echo 'NAME = ' | tr -d "\n" >> $MAKE_DIR
cat $1 | grep "EXEC" | cut -d ';' -f 2 >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
echo 'all:' | tr -d "\n" >> $MAKE_DIR
printf "\t\t" | tr -d "\n" >> $MAKE_DIR
echo '$(NAME)' >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
echo '$(NAME):' | tr -d "\n" >> $MAKE_DIR
printf "\t" | tr -d "\n" >> $MAKE_DIR
echo '$(OBJ)' | tr -d "\n" >> $MAKE_DIR
printf "\n\t\t" >> $MAKE_DIR
echo '$(CC) -o $(NAME) $(OBJ) $(LDFLAGS) $(LIB)' | tr -d "\n" >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
echo 'clean:' >> $MAKE_DIR
printf "\t\t" | tr -d "\n" >> $MAKE_DIR
echo 'rm -rf $(OBJ)' >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
echo 'fclean:' | tr -d "\n" >> $MAKE_DIR
printf "\t\t" | tr -d "\n" >> $MAKE_DIR
echo 'clean' >> $MAKE_DIR
printf "\t\t" | tr -d "\n" >> $MAKE_DIR
echo 'rm -rf $(NAME)' >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
echo 're:' | tr -d "\n" >> $MAKE_DIR
printf "\t\t" | tr -d "\n" >> $MAKE_DIR
echo 'fclean all' >> $MAKE_DIR
printf "\n" >> $MAKE_DIR
echo '.PHONY:' | tr -d "\n" >> $MAKE_DIR
printf "\t\t" | tr -d "\n" >> $MAKE_DIR
echo 'all clean fclean all' >> $MAKE_DIR
|
a3695670f8ad7b9d5d540887eff1d66b024aae9b
|
[
"Shell"
] | 1 |
Shell
|
PruneB/AutoMakefile
|
dbc04ee0247eaab94fd8cf4b8a6dc46fc698bc92
|
5ab49f7f52e09af99ce976b55566d90b51ccc08d
|
refs/heads/master
|
<repo_name>mauwia/hactoberfest2020<file_sep>/README.md
# hactoberfest2020
for hacktoberfest 2020
This Repo created for Hactoberfest 2020, everyone can fork and push PR's.
It is so simple and easy
Long live Open Source!!!
<file_sep>/hello.py
hello = "Hello world!"
print(hello)
b = "hello world!"
print(b)
|
d58e38105936a866094a27c2de8ad0eb8092888f
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
mauwia/hactoberfest2020
|
64ebf8914e818ef1c0c4fb827c8d837ab5d36cf5
|
55ae6cee60f8bd13794915f3188e87daf5d858bd
|
refs/heads/master
|
<repo_name>aoede-pando/emp_track_AR<file_sep>/lib/division.rb
class Division < ActiveRecord::Base
has_many(:employees)
def self.list_by
self.all.each do |div|
puts div.name
end
end
end
<file_sep>/spec/project_spec.rb
require 'spec_helper'
describe Project do
it "has many employees" do
project = Project.create({:name => "water"})
employee1 = Employee.create({:name => "<NAME>"})
employee1.projects << project
employee2 = Employee.create({:name => "<NAME>"})
employee2.projects << project
project.employees.should eq [employee1, employee2]
end
end
<file_sep>/lib/employee.rb
class Employee < ActiveRecord::Base
belongs_to(:division)
has_and_belongs_to_many(:projects)
def self.list_by_name
self.all.each do |emp|
puts emp.name
end
end
def self.list_by_div(div_name)
division = Division.find_by name: div_name
result = division.id
Employee.all.each do |emp|
if emp.division_id == result
puts emp.name
end
end
end
end
<file_sep>/spec/employee_spec.rb
require 'spec_helper'
describe Employee do
it "belongs to a division" do
division = Division.create({:name => "water"})
employee = Employee.create({:name => "<NAME>", :division_id => division.id})
division.employees.should eq [employee]
end
end
<file_sep>/db/migrate/20140818230849_remove_column_project_name.rb
class RemoveColumnProjectName < ActiveRecord::Migration
def change
remove_column :employees, :project_id
end
end
<file_sep>/ui.rb
require 'active_record'
require './lib/division'
require './lib/employee'
require './lib/project'
database_configurations = YAML::load(File.open('./db/config.yml'))
development_configuration = database_configurations['development']
ActiveRecord::Base.establish_connection(development_configuration)
def main_menu
loop do
puts "Press 'a' to add an employee\nPress 'p' to add an employee to a project\nPress 'l' to list employees\nPress 'd' to list all your divisions\nPress 'le' to list all employes in a division\nPress 'x' to exit"
user_input = gets.chomp
if user_input == 'a'
add_emp
elsif user_input == 'l'
list_emp
elsif user_input == 'p'
add_emp_to_proj
elsif user_input == 'd'
list_div
elsif user_input == 'le'
list_employees_in_div
elsif user_input == 'x'
puts 'Goodbye'
exit
else
puts 'Not a valid option'
end
end
end
def add_emp
puts 'What division is human slaving in?'
user_input = gets.chomp
new_div = Division.find_or_create_by(name: user_input)
puts 'What is the human name?'
user_input_two = gets.chomp
new_emp = Employee.create({name: user_input_two, division_id: new_div.id})
puts 'Slave added'
end
def list_emp
puts 'Here are your employees'
Employee.list_by_name
end
def list_div
puts 'Here are your divisions'
Division.list_by
end
def list_employees_in_div
list_div
puts "\n\n"
puts "What division would you like to see?"
puts "\n\n"
user_choice = gets.chomp
Employee.list_by_div(user_choice)
end
def add_emp_to_proj
list_emp
puts "\nWhat human are you referring to?\n"
user_choice = gets.chomp
puts "\nWhat project is this person working on?\n"
user_project = gets.chomp
new_emp = Employee.find_or_create_by(name: user_choice)
new_proj = Project.find_or_create_by(name: user_project)
new_emp.projects << new_proj
end
main_menu
<file_sep>/spec/division_spec.rb
require 'spec_helper'
describe Division do
it "has many employees" do
division = Division.create({:name => "water"})
employee1 = Employee.create({:name => "<NAME>", :division_id => division.id})
employee2 = Employee.create({:name => "<NAME>", :division_id => division.id})
division.employees.should eq [employee1, employee2]
end
end
|
8b21b60655070a8ba42b56c3eb9460d9115f5cd9
|
[
"Ruby"
] | 7 |
Ruby
|
aoede-pando/emp_track_AR
|
17c4b284b4a401112575f913d8152acf03bd57b2
|
ed9b4bb614fc627e04a71e7a551ae972938155b8
|
refs/heads/master
|
<file_sep>#include "vulkan/vulkan.h"
#include "vulkan/vulkan_core.h"
#include "SDL2/SDL.h"
#include "SDL2/SDL_vulkan.h"
#include <iostream>
#include <stdexcept>
#include <functional>
#include <cstdlib>
#include <vector>
#include <cstring>
class HelloTriangleApplication {
public:
void run() {
initWindow();
initVulkan();
mainLoop();
cleanup();
}
private:
SDL_Window* window;
SDL_Renderer* renderer;
SDL_Event event;
VkInstance instance;
const std::vector<const char*> validationLayers = { "VK_LAYER_KHRONOS_validation" };
#ifdef NDEBUG
static constexpr bool enableValidationLayers = false;
#else
static constexpr bool enableValidationLayers = true;
#endif
void initWindow() {
window = SDL_CreateWindow("Triangle", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 400, 400, SDL_WINDOW_VULKAN|SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer(window, -1, 0);
}
void initVulkan() {
createInstance();
}
void mainLoop() {
while(1) {
if(SDL_PollEvent(&event)) {
if(event.type == SDL_QUIT) {
break;
}
}
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
}
}
void cleanup() {
vkDestroyInstance(instance, nullptr);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
}
void createInstance() {
if (enableValidationLayers && !checkValidationLayerSupport()) {
throw std::runtime_error("validation layers requested, but not available!");
}
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Blanco Tower";
appInfo.applicationVersion = VK_MAKE_VERSION(1,0,0);
appInfo.pEngineName = "No Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1,0,0);
appInfo.apiVersion = VK_API_VERSION_1_2;
VkInstanceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
if (enableValidationLayers) {
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
} else {
createInfo.enabledLayerCount = 0;
}
unsigned int count = 0;
if(! SDL_Vulkan_GetInstanceExtensions(window, &count, nullptr))
std::cerr << "Could not retrieve extensions count" << std::endl;
std::vector<const char*> extensions = {
VK_EXT_DEBUG_REPORT_EXTENSION_NAME
};
size_t additional_extension_count = extensions.size();
extensions.resize(additional_extension_count + count);
if (!SDL_Vulkan_GetInstanceExtensions(window, &count, extensions.data() + additional_extension_count))
std::cerr << "Could not retrieve extended instance extensions" << std::endl;
#ifdef DEBUG
// populate supported extensions
uint32_t extensionCount = 0;
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> supportedExtensions(extensionCount);
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, supportedExtensions.data());
// Check for extension support
std::cout << extensions.size() << " extensions needed :" <<std::endl;
for(auto &extension : extensions){
std::cout << "\t" << extension ;
bool found = false;
for(auto &supported : supportedExtensions) {
if(strcmp(extension, supported.extensionName) == 0) {
found = true;
break;
}
}
if(!found) {
std::cout << " -> NOT SUPPORTED";
}
std::cout << std::endl;
}
#endif
createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
createInfo.ppEnabledExtensionNames = extensions.data();
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS)
throw std::runtime_error("failed to create instance!");
}
bool checkValidationLayerSupport() {
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
for (const char* layerName : validationLayers) {
bool layerFound = false;
for (const auto& layerProperties : availableLayers) {
if(strcmp(layerName, layerProperties.layerName) == 0) {
layerFound = true;
break;
}
}
if (!layerFound) {
return false;
}
}
return true;
}
};
int main() {
HelloTriangleApplication app;
try{
app.run();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<file_sep># BT
Experiments with vulkan, sdl2 and premake.
Following : https://vulkan-tutorial.com with some minor adjustments for SDL2
<file_sep>solution "Blanco_Tower"
configurations {"Debug", "Release"}
project "Blanco_Tower"
kind "ConsoleApp"
language "C++"
files { "**.h", "**.cpp" }
includedirs { "./thirdparty/include"}
configuration "Debug"
defines {"DEBUG"}
flags {"Symbols"}
linkoptions{ "`sdl2-config --cflags --libs`"}
links{"vulkan"}
configuration "Release"
defines {"NDEBUG"}
flags {"Optimize"}
linkoptions{ "`sdl2-config --cflags --libs`"}
|
6c223376c974d98f2f194c64ed9a2a414f11bd7a
|
[
"Markdown",
"C++",
"Lua"
] | 3 |
Markdown
|
J-Merle/BT
|
6ca0dcb3076a90c187133b60103045bdca36c41b
|
2287b8c6909662b4f743317a7b5f9a54cef95877
|
refs/heads/master
|
<file_sep>Make a TN map on Ubuntu16.04.1 using D3 and TopoJSON by following [<NAME>'s Merged Choropleth](https://bl.ocks.org/mbostock/670b9fe0577a29c39a1803f59c628769). This project use topomerge to combine census tracts in the same density interval.
### Create the following files in local
index.html # changed height to 700
package.json # changed a few devDependencies to make "npm install" work
prepublish # changed FIPS code from 06 (CA) to 47 (TN), height 700
### Convert data by running "npm install" on package.json
```sh
$ npm install
```
### Load the fillowing files to local server or remote server
index.html
topo.json
### Open index.html in your server to see the map
|
ed1df70600fe629baa729ad1c715f51e28062cef
|
[
"Markdown"
] | 1 |
Markdown
|
youcc/TN-map
|
7940f53b3ea665ebf7cfcb1e47b8f6cd1811163e
|
f7d4fcaa152530db80635eb141d5326940652520
|
refs/heads/master
|
<repo_name>animenotifier/ffxiv<file_sep>/go.mod
module github.com/animenotifier/ffxiv
go 1.12
require (
github.com/PuerkitoBio/goquery v1.5.0
github.com/aerogo/http v1.0.10
github.com/akyoto/assert v0.2.3
github.com/akyoto/stringutils v0.2.4 // indirect
github.com/andybalholm/cascadia v1.1.0 // indirect
golang.org/x/net v0.0.0-20191021144547-ec77196f6094 // indirect
)
<file_sep>/Character_test.go
package ffxiv_test
import (
"testing"
"github.com/akyoto/assert"
"github.com/animenotifier/ffxiv"
)
func TestGetCharacter(t *testing.T) {
id := "9015414"
character, err := ffxiv.GetCharacter(id)
assert.Nil(t, err)
assert.NotNil(t, character)
assert.NotEqual(t, character.Level, 0)
assert.Equal(t, "<NAME>", character.Nick)
assert.Equal(t, "Asura", character.Server)
assert.Equal(t, "Mana", character.DataCenter)
}
func TestGetCharacterFail(t *testing.T) {
id := "404"
character, err := ffxiv.GetCharacter(id)
assert.NotNil(t, err)
assert.Nil(t, character)
}
<file_sep>/Character.go
package ffxiv
import (
"bytes"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"unicode"
"github.com/PuerkitoBio/goquery"
"github.com/aerogo/http/client"
)
var digit = regexp.MustCompile("[0-9]+")
// Character represents a Final Fantasy XIV character.
type Character struct {
Nick string
Server string
DataCenter string
Class string
Level int
ItemLevel int
}
// GetCharacter fetches character data for a given character ID.
func GetCharacter(id string) (*Character, error) {
url := fmt.Sprintf("https://na.finalfantasyxiv.com/lodestone/character/%s", id)
response, err := client.Get(url).End()
if err != nil {
return nil, err
}
page := response.Bytes()
reader := bytes.NewReader(page)
document, err := goquery.NewDocumentFromReader(reader)
if err != nil {
return nil, err
}
characterName := document.Find(".frame__chara__name").Text()
if characterName == "" {
return nil, errors.New("Error parsing character name")
}
// This will look like: "Asura (Mana)"
characterServerAndDataCenter := document.Find(".frame__chara__world").Text()
if characterServerAndDataCenter == "" {
return nil, errors.New("Error parsing character server")
}
// Normalize whitespace characters
characterServerAndDataCenter = strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return ' '
}
return r
}, characterServerAndDataCenter)
// Split the server and data center
serverInfo := strings.Split(characterServerAndDataCenter, " ")
if len(serverInfo) < 2 {
return nil, errors.New("Character server info does not seem to include the data center")
}
characterServer := serverInfo[0]
characterDataCenter := serverInfo[1]
characterDataCenter = strings.TrimPrefix(characterDataCenter, "(")
characterDataCenter = strings.TrimSuffix(characterDataCenter, ")")
if characterDataCenter == "" {
return nil, errors.New("Error parsing character data center")
}
// Level
characterLevel := document.Find(".character__class__data").Text()
if characterLevel == "" {
return nil, errors.New("Error parsing character level")
}
// Weapon
characterWeapon := document.Find(".db-tooltip__item__category").Text()
if characterWeapon == "" {
return nil, errors.New("Error parsing character class")
}
level, err := strconv.Atoi(digit.FindStringSubmatch(characterLevel)[0])
if err != nil {
return nil, err
}
itemLevel := calculateItemLevel(document)
className := getJobName(document)
if className == "" {
// Determine class name using the weapon info
className = strings.Split(characterWeapon, "'")[0]
className = strings.Replace(className, "Two-handed", "", -1)
className = strings.Replace(className, "One-handed", "", -1)
className = strings.TrimSpace(className)
}
character := &Character{
Nick: characterName,
Class: className,
Server: characterServer,
DataCenter: characterDataCenter,
Level: level,
ItemLevel: itemLevel,
}
return character, nil
}
// calculateItemLevel will try to return the average of all item levels.
func calculateItemLevel(document *goquery.Document) int {
items := document.Find(".item_detail_box")
itemCount := 0
itemLevelSum := 0
items.Each(func(i int, item *goquery.Selection) {
itemCategory := strings.ToLower(item.Find(".db-tooltip__item__category").Text())
// Ignore soul crystals
if itemCategory == "soul crystal" {
return
}
// Two-handed weapons are counted twice
weight := 1
if strings.Contains(itemCategory, "two-handed") {
weight = 2
}
// Find item level
itemLevelText := item.Find(".db-tooltip__item__level").Text()
itemLevelText = digit.FindStringSubmatch(itemLevelText)[0]
itemLevel, err := strconv.Atoi(itemLevelText)
if err != nil {
return
}
itemLevelSum += itemLevel * weight
itemCount += weight
})
if itemCount == 0 {
return 0
}
return itemLevelSum / itemCount
}
// getJobName finds the job name by looking at the soul crystal text.
func getJobName(document *goquery.Document) string {
const soulCrystalPrefix = "Soul of the "
jobName := ""
itemNames := document.Find(".db-tooltip__item__name")
itemNames.EachWithBreak(func(i int, item *goquery.Selection) bool {
itemName := item.Text()
if strings.HasPrefix(itemName, soulCrystalPrefix) {
jobName = itemName[len(soulCrystalPrefix):]
return false
}
return true
})
return jobName
}
<file_sep>/CharacterID_test.go
package ffxiv_test
import (
"testing"
"github.com/akyoto/assert"
"github.com/animenotifier/ffxiv"
)
func TestGetCharacterID(t *testing.T) {
id, err := ffxiv.GetCharacterID("A<NAME>", "Asura")
assert.Nil(t, err)
assert.Equal(t, "9015414", id)
}
func TestGetCharacterIDFail(t *testing.T) {
id, err := ffxiv.GetCharacterID("asdfasdfghjklasdf", "Asura")
assert.NotNil(t, err)
assert.Equal(t, id, "")
}
<file_sep>/README.src.md
# {name}
{go:header}
Final Fantasy XIV character data API.
{go:footer}
|
78da3f7e2c350ceaff395e15050bef2c03ca8477
|
[
"Go Module",
"Markdown",
"Go"
] | 5 |
Go Module
|
animenotifier/ffxiv
|
6567402dff18f39790f4bc80c6a5752b28b60075
|
5bc5cb4583170378088885d88cc39bdda2e02be2
|
refs/heads/master
|
<file_sep>// Name: <NAME>
// Berkeley CS 61b - Data Structures
// Description:
// ------------
// Homework 0 - Java syntax
public class HW0 {
// Exercise 2
public static int max(int[] m) {
int i = 0;
int max = m[0];
while(m.length != i) {
if(m[i] >= max) {
max = m[i];
}
i++;
}
return max;
}
// Exercise 3
public static int forMax(int[] m) {
int max = m[0];
for(int i = 0; i < m.length; i++) {
if(m[i] >= max) {
max = m[i];
}
}
return max;
}
// The main method
public static void main(String[] args) {
int[] numbers = new int[]{9, 2, 15, 2, 22, 10, 6};
System.out.println(max(numbers));
System.out.println(forMax(numbers));
}
}
<file_sep># CS-61b Data Structures
|
e48a862f32bfcd21c301a985e2e3174a18572bde
|
[
"Java",
"Markdown"
] | 2 |
Java
|
jpmcb/Berkeley-CS-61b
|
6c904a1f997fa9ebb1af2fc7d4b9292113631f06
|
8c96d7232498aea50be8b027df13acb3df4c9eb0
|
refs/heads/master
|
<file_sep># FingerPrintImageSegmentation
FingerPrint Image Segmentation using Unsupervised Machine Learning
This notebook takes an input fingerprint image and produces a segmented output of the same.
Segmentation includes the use of a vector of kernels. Different kernels with different features help to segment the image more efficiently. Finally the vector arrays are passed through K-clustering (Unsupervised Learning) to produce an output of '0's and '1's to give the final segmented output image. 0s and 1s can sometimes be interchanged depending on the image.
Note: When a pixel is to be viewed as fingerprint, the original pixel value from the image is displayed.
|
05ceee8f8af0bb6b9f35f57dd225c186dab2e610
|
[
"Markdown"
] | 1 |
Markdown
|
chinmaythosar/FingerPrintImageSegmentation
|
f0b3eaa1e85bc1c10ba4cf44cfbe7b2d1ea9aa3e
|
7aed049959c7f291cee89533823f1feaa71297e0
|
refs/heads/master
|
<file_sep>//
// CameraTab.h
// Great of Britain iOS
//
// Created by <NAME> on 15/05/2012.
// Copyright (c) 2012 Me. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface CameraTab : UIViewController
- (void)startCamera;
@end
<file_sep>//
// Great_of_Britain_iOSTests.h
// Great of Britain iOSTests
//
// Created by <NAME> on 15/05/2012.
// Copyright (c) 2012 Me. All rights reserved.
//
#import <SenTestingKit/SenTestingKit.h>
@interface Great_of_Britain_iOSTests : SenTestCase
@end
<file_sep>Great-of-Britain-iOS
====================
Great-of-Britain-iOS<file_sep>//
// IntroLoader.m
// Great of Britain iOS
//
// Created by <NAME> on 15/05/2012.
// Copyright (c) 2012 Me. All rights reserved.
//
#import "IntroLoader.h"
@implementation IntroLoader
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
<file_sep>//
// CustomTabBarController.h
// Great of Britain iOS
//
// Created by <NAME> on 16/05/2012.
// Copyright (c) 2012 Me. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface CustomTabBarController : UITabBarController
@end
<file_sep>//
// HomeTab.h
// Great of Britain iOS
//
// Created by <NAME> on 15/05/2012.
// Copyright (c) 2012 Me. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import "PullRefreshTableViewController.h"
@interface HomeTab : PullRefreshTableViewController <UITableViewDataSource, UITableViewDelegate>
@property (strong, nonatomic) IBOutlet NSMutableArray *streamImages;
@property (strong, nonatomic) IBOutlet UIButton *imageButton;
- (void)customTabBarController;
- (void)loadImages;
- (IBAction)imageButtonAction:(id)sender;
@end
<file_sep>//
// CustomTabBarController.m
// Great of Britain iOS
//
// Created by <NAME> on 16/05/2012.
// Copyright (c) 2012 Me. All rights reserved.
//
#import "CustomTabBarController.h"
@interface CustomTabBarController ()
@end
@implementation CustomTabBarController
- (void)updateTabBarImageForViewControllerIndex:(NSUInteger)index
{
// Determine the image name based on the selected view controller index
}
- (void)drawRect:(CGRect)rect
{
//CGContextDrawImage(UIGraphicsGetCurrentContext(), rect, self.selectedTabBarImage.CGImage);
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
<file_sep>//
// SettingsTab.m
// Great of Britain iOS
//
// Created by <NAME> on 16/05/2012.
// Copyright (c) 2012 Me. All rights reserved.
//
#import "SettingsTab.h"
@implementation SettingsTab
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor clearColor];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
<file_sep>//
// HomeTab.m
// Great of Britain iOS
//
// Created by <NAME> on 15/05/2012.
// Copyright (c) 2012 Me. All rights reserved.
//
#import "HomeTab.h"
@implementation HomeTab
@synthesize streamImages = _streamImages;
@synthesize imageButton = _imageButton;
- (void)viewDidLoad
{
[super viewDidLoad];
[self customTabBarController];
[self loadImages];
self.view.backgroundColor = [UIColor clearColor];
}
- (void)viewDidUnload
{
[self setView:nil];
[super viewDidUnload];
}
- (void)customTabBarController
{
UIImage *barLogoImage = [UIImage imageNamed: @"hp_GOB.png"];
UIImageView *navigationImage = [[UIImageView alloc] initWithImage: barLogoImage];
self.navigationItem.titleView = navigationImage;
UIImage *selectedImage0 = [UIImage imageNamed:@"tb_1_down.png"];
UIImage *unselectedImage0 = [UIImage imageNamed:@"tb_1_up.png"];
UIImage *selectedImage1 = [UIImage imageNamed:@"tb_2_down.png"];
UIImage *unselectedImage1 = [UIImage imageNamed:@"tb_2_up.png"];
UIImage *selectedImage2 = [UIImage imageNamed:@"tb_3_down.png"];
UIImage *unselectedImage2 = [UIImage imageNamed:@"tb_3_up.png"];
UITabBar *tabBar = self.tabBarController.tabBar;
UITabBarItem *item0 = [tabBar.items objectAtIndex:0];
UITabBarItem *item1 = [tabBar.items objectAtIndex:1];
UITabBarItem *item2 = [tabBar.items objectAtIndex:2];
self.tabBarController.tabBar.frame = CGRectMake(0, 430, 320, 50);
[self.tabBarController.tabBar setBackgroundImage:[UIImage imageNamed:@"tb_tabBar_BG.png"]];
[item0 setFinishedSelectedImage:selectedImage0 withFinishedUnselectedImage:unselectedImage0];
[item1 setFinishedSelectedImage:selectedImage1 withFinishedUnselectedImage:unselectedImage1];
[item2 setFinishedSelectedImage:selectedImage2 withFinishedUnselectedImage:unselectedImage2];
}
- (void)loadImages
{
self.streamImages = [[NSMutableArray alloc] init];
for(int r = 0; r < 12; r++){
NSMutableArray *threeImageSet = [[NSMutableArray alloc] init];
for(int t = 0; t < 4; t++){
NSMutableDictionary *singleImageSet = [[NSMutableDictionary alloc] init];
int no = ((r * 4) + t) + 1;
NSString *imageNumber = [NSString stringWithFormat:@"%d", no];
NSString *imageURL = @"http://upload.wikimedia.org/wikipedia/commons/5/58/1NumberOneInCircle.png";
NSString *imageUser = @"Google";
[singleImageSet setValue:imageNumber forKey:@"imageNumber"];
[singleImageSet setValue:imageURL forKey:@"imageURL"];
[singleImageSet setValue:imageUser forKey:@"imageUser"];
[threeImageSet addObject:singleImageSet];
}
[self.streamImages addObject:threeImageSet];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if([self.streamImages count] != 0) return [self.streamImages count] + 1;
else return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == [self.streamImages count]){
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"loadMoreCell"];
return cell;
} else {
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"imageCell"];
NSArray *singleRowArray = [self.streamImages objectAtIndex:indexPath.row];
for(int c = 0; c < [singleRowArray count]; c++){
int gap = (c * 80) + 4;
NSDictionary *singleImageDict = [singleRowArray objectAtIndex:c];
NSString *imageURL = [singleImageDict objectForKey:@"imageURL"];
NSString *imageUser = [singleImageDict objectForKey:@"imageUser"];
NSString *imageNumber = [singleImageDict objectForKey:@"imageNumber"];
self.imageButton = [[UIButton alloc] initWithFrame:CGRectMake(gap, 4, 73, 73)];
self.imageButton.backgroundColor = [UIColor colorWithRed:0.000 green:0.424 blue:0.671 alpha:1];
UILabel *numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
numberLabel.text = [NSString stringWithFormat:@"%@", imageNumber];
numberLabel.textColor = [UIColor colorWithRed:1.000 green:1.000 blue:1.000 alpha:1];
numberLabel.backgroundColor = [UIColor clearColor];
[self.imageButton addSubview:numberLabel];
[self.imageButton addTarget:self action:@selector(imageButtonAction:) forControlEvents:UIControlEventTouchDown];
[self.imageButton setEnabled:YES];
[cell addSubview:self.imageButton];
}
return cell;
}
}
- (IBAction)imageButtonAction:(id)sender
{
NSLog(@"Button Press");
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
|
75db00db924baf67b7aa9085aef05d9c43956f99
|
[
"Markdown",
"Objective-C"
] | 9 |
Markdown
|
fantasticford/Great-of-Britain-iOS
|
82ee2d67f4d69bd5b788c91eb96a1d727c3cd8a2
|
dcfb0c9001e8a911f926c38a2bbae1b7eaa5a973
|
refs/heads/master
|
<file_sep>export type XmlParserOptions = {
/**
* Returns false to exclude a node. Default is true.
*/
filter?: (node: XmlParserNode) => boolean|any;
/**
* True to throw an error when parsing XML document with invalid content like mismatched closing tags.
*/
strictMode?: boolean;
};
export type XmlParserNodeType = 'Comment'|'Text'|'ProcessingInstruction'|'Element'|'DocumentType'|'CDATA';
export type XmlParserNodeWrapper<T extends XmlParserNode> = {
excluded: boolean;
node: T;
}
export type XmlParserNode = {
type: XmlParserNodeType;
}
export type XmlParserAttribute = {
name: string;
value: string;
}
export type XmlParserElementChildNode = XmlParserTextNode|XmlParserElementNode|XmlParserCDATANode|XmlParserCommentNode;
export type XmlParserDocumentChildNode = XmlParserDocumentTypeNode|XmlParserProcessingInstructionNode|XmlParserElementChildNode;
export type XmlParserProcessingInstructionNode = {
type: 'ProcessingInstruction';
name: string;
attributes: Record<string, string>;
}
export type XmlParserElementNode = {
type: 'Element';
name: string;
attributes: Record<string, string>;
children: XmlParserElementChildNode[]|null;
}
export type XmlParserTextNode = {
type: 'Text';
content: string;
}
export type XmlParserCDATANode = {
type: 'CDATA';
content: string;
}
export type XmlParserCommentNode = {
type: 'Comment';
content: string;
}
export type XmlParserDocumentTypeNode = {
type: 'DocumentType';
content: string;
}
export type XmlParserResult = {
declaration?: XmlParserProcessingInstructionNode|null;
root: XmlParserElementNode;
children: XmlParserDocumentChildNode[];
};
export class ParsingError extends Error {
public readonly cause: string;
public constructor(message: string, cause: string) {
super(message);
this.cause = cause;
}
}
let parsingState: {
xml: string;
options: Required<XmlParserOptions>;
};
function nextChild() {
return element(false) || text() || comment() || cdata();
}
function nextRootChild() {
match(/\s*/);
return element(true) || comment() || doctype() || processingInstruction(false);
}
function parseDocument(): XmlParserResult {
const declaration = processingInstruction(true);
const children = [];
let documentRootNode;
let child = nextRootChild();
while (child) {
if (child.node.type === 'Element') {
if (documentRootNode) {
throw new Error('Found multiple root nodes');
}
documentRootNode = child.node;
}
if (!child.excluded) {
children.push(child.node);
}
child = nextRootChild();
}
if (!documentRootNode) {
throw new ParsingError('Failed to parse XML', 'Root Element not found');
}
if (parsingState.xml.length !== 0) {
throw new ParsingError('Failed to parse XML', 'Not Well-Formed XML');
}
return {
declaration: declaration ? declaration.node : null,
root: documentRootNode,
children
};
}
function processingInstruction(matchDeclaration: boolean): XmlParserNodeWrapper<XmlParserProcessingInstructionNode>|undefined {
const m = matchDeclaration ? match(/^<\?(xml)\s*/) : match(/^<\?([\w-:.]+)\s*/);
if (!m) return;
// tag
const node: XmlParserProcessingInstructionNode = {
name: m[1],
type: 'ProcessingInstruction',
attributes: {}
};
// attributes
while (!(eos() || is('?>'))) {
const attr = attribute();
if (attr) {
node.attributes[attr.name] = attr.value;
} else {
return;
}
}
match(/\?>/);
return {
excluded: matchDeclaration ? false : parsingState.options.filter(node) === false,
node
};
}
function element(matchRoot: boolean): XmlParserNodeWrapper<XmlParserElementNode>|undefined {
const m = match(/^<([^?!</>\s]+)\s*/);
if (!m) return;
// name
const node: XmlParserElementNode = {
type: 'Element',
name: m[1],
attributes: {},
children: []
};
const excluded = matchRoot ? false : parsingState.options.filter(node) === false;
// attributes
while (!(eos() || is('>') || is('?>') || is('/>'))) {
const attr = attribute();
if (attr) {
node.attributes[attr.name] = attr.value;
} else {
return;
}
}
// self closing tag
if (match(/^\s*\/>/)) {
node.children = null;
return {
excluded,
node
};
}
match(/\??>/);
// children
let child = nextChild();
while (child) {
if (!child.excluded) {
node.children!.push(child.node);
}
child = nextChild();
}
// closing
if (parsingState.options.strictMode) {
const closingTag = `</${node.name}>`;
if (parsingState.xml.startsWith(closingTag)) {
parsingState.xml = parsingState.xml.slice(closingTag.length);
} else {
throw new ParsingError('Failed to parse XML', `Closing tag not matching "${closingTag}"`);
}
} else {
match(/^<\/\s*[\w-:.\u00C0-\u00FF]+>/);
}
return {
excluded,
node
};
}
function doctype(): XmlParserNodeWrapper<XmlParserDocumentTypeNode>|undefined {
const m =
match(/^<!DOCTYPE\s+\S+\s+SYSTEM[^>]*>/) ||
match(/^<!DOCTYPE\s+\S+\s+PUBLIC[^>]*>/) ||
match(/^<!DOCTYPE\s+\S+\s*\[[^\]]*]>/) ||
match(/^<!DOCTYPE\s+\S+\s*>/);
if (m) {
const node: XmlParserDocumentTypeNode = {
type: 'DocumentType',
content: m[0]
};
return {
excluded: parsingState.options.filter(node) === false,
node
};
}
}
function cdata(): XmlParserNodeWrapper<XmlParserCDATANode>|undefined {
if (parsingState.xml.startsWith('<![CDATA[')) {
const endPositionStart = parsingState.xml.indexOf(']]>');
if (endPositionStart > -1) {
const endPositionFinish = endPositionStart + 3;
const node: XmlParserCDATANode = {
type: 'CDATA',
content: parsingState.xml.substring(0, endPositionFinish)
};
parsingState.xml = parsingState.xml.slice(endPositionFinish);
return {
excluded: parsingState.options.filter(node) === false,
node
};
}
}
}
function comment(): XmlParserNodeWrapper<XmlParserCommentNode>|undefined {
const m = match(/^<!--[\s\S]*?-->/);
if (m) {
const node: XmlParserCommentNode = {
type: 'Comment',
content: m[0]
};
return {
excluded: parsingState.options.filter(node) === false,
node
};
}
}
function text(): XmlParserNodeWrapper<XmlParserTextNode>|undefined {
const m = match(/^([^<]+)/);
if (m) {
const node: XmlParserTextNode = {
type: 'Text',
content: m[1]
};
return {
excluded: parsingState.options.filter(node) === false,
node
};
}
}
function attribute(): XmlParserAttribute|undefined {
const m = match(/([^=]+)\s*=\s*("[^"]*"|'[^']*'|[^>\s]+)\s*/);
if (m) {
return {
name: m[1].trim(),
value: stripQuotes(m[2].trim())
};
}
}
function stripQuotes(val: string): string {
return val.replace(/^['"]|['"]$/g, '');
}
/**
* Match `re` and advance the string.
*/
function match(re: RegExp): RegExpMatchArray|undefined {
const m = parsingState.xml.match(re);
if (m) {
parsingState.xml = parsingState.xml.slice(m[0].length);
return m;
}
}
/**
* End-of-source.
*/
function eos(): boolean {
return 0 === parsingState.xml.length;
}
/**
* Check for `prefix`.
*/
function is(prefix: string): boolean {
return 0 === parsingState.xml.indexOf(prefix);
}
/**
* Parse the given XML string into an object.
*/
function parseXml(xml: string, options: XmlParserOptions = {}): XmlParserResult {
xml = xml.trim();
const filter: XmlParserOptions['filter'] = options.filter || (() => true);
parsingState = {
xml,
options: {
...options,
filter,
strictMode: options.strictMode === true
}
};
return parseDocument();
}
if (typeof module !== 'undefined' && typeof exports === 'object') {
module.exports = parseXml;
}
export default parseXml;
<file_sep>
# xml-parser-xo
An XML parser based on [xml-parser](https://www.npmjs.com/package/xml-parser).
[](https://github.com/chrisbottin/xml-parser/actions/workflows/ci.yml) [](https://npmjs.org/package/xml-parser-xo)
## Installation
```
$ npm install xml-parser-xo
```
## Example
### Usage:
```js
import xmlParser from 'xml-parser-xo';
var xml = `<?xml version="1.0" encoding="utf-8"?>
<!-- Load the stylesheet -->
<?xml-stylesheet href="foo.xsl" type="text/xsl" ?>
<!DOCTYPE foo SYSTEM "foo.dtd">
<foo><![CDATA[some text]]> content</foo>`;
xmlParser(xml);
```
### Output:
```json
{
"declaration": {
"type": "ProcessingInstruction",
"attributes": {"version": "1.0", "encoding": "utf-8"}
},
"root": {
"type": "Element",
"name": "foo",
"attributes": {},
"children": [
{"type": "CDATA", "content": "<![CDATA[some text]]>"},
{"type": "Text", "content": " content"}
]
},
"children": [
{"type": "Comment", "content": "<!-- Load the stylesheet -->"},
{"type": "ProcessingInstruction", "attributes": {"href": "foo.xsl", "type": "text/xsl"}},
{"type": "DocumentType", "content": "<!DOCTYPE foo SYSTEM \"foo.dtd\">"},
{
"type": "Element",
"name": "foo",
"attributes": {},
"children": [
{"type": "CDATA", "content": "<![CDATA[some text]]>"},
{"type": "Text", "content": " content"}
]
}
]
}
```
## Options
- `filter`: Function to filter out unwanted nodes by returning `false`.
- type: `function(node) => boolean`
- default: `() => true`
- `strictMode`: True to throw an error when parsing XML document with invalid content like mismatched closing tags.
- type: `boolean`
- default: `false`
### Usage:
```js
import xmlParser from 'xml-parser-xo';
const xml = `<?xml version="1.0" encoding="utf-8"?>
<!-- Load the stylesheet -->
<?xml-stylesheet href="foo.xsl" type="text/xsl" ?>
<!DOCTYPE foo SYSTEM "foo.dtd">
<foo><![CDATA[some text]]> content</foo>`;
xmlParser(xml, {
filter: (node) => {
return node.type === 'Element' || node.type === 'Text';
}
});
```
### Output:
```json
{
"declaration": {
"type": "ProcessingInstruction",
"attributes": {"version": "1.0", "encoding": "utf-8"}
},
"root": {
"type": "Element",
"name": "foo",
"attributes": {},
"children": [
{"type": "Text", "content": " content"}
]
},
"children": [
{
"type": "Element",
"name": "foo",
"attributes": {},
"children": [
{"type": "Text", "content": " content"}
]
}
]
}
```
## License
MIT
<file_sep>import {assert} from 'chai';
import xmlParser, {ParsingError, XmlParserElementNode} from '../src/index';
describe('XML Parser', function() {
it('should fail to parse blank strings', function() {
try {
xmlParser('');
assert.fail('Should fail');
} catch(err: any) {
assert.equal(err.message, 'Failed to parse XML');
assert.equal((err as ParsingError).cause, 'Root Element not found');
}
});
it('should fail to parse when element attribute is badly formed', function() {
try {
xmlParser('<?xml version="1.0" ?><foo me></foo>');
assert.fail('Should fail');
} catch(err: any) {
assert.equal(err.message, 'Failed to parse XML');
}
});
it('should fail to parse when element is not closed correctly', function() {
try {
xmlParser('<?xml version="1.0" ?><foo>bar<</foo>');
assert.fail('Should fail');
} catch(err: any) {
assert.equal(err.message, 'Failed to parse XML');
assert.equal((err as ParsingError).cause, 'Not Well-Formed XML');
}
});
it('should fail to parse when processing instruction attribute is badly formed', function() {
try {
xmlParser('<?xml version ?><foo></foo>');
assert.fail('Should fail');
} catch(err: any) {
assert.equal(err.message, 'Failed to parse XML');
}
});
context('should honour strictMode option', function() {
it('test 1 - strictMode default', function() {
try {
xmlParser('<root><foo>bar</foo>');
} catch(err: any) {
assert.fail('Should not fail');
}
});
it('test 2 - strictMode OFF', function() {
try {
xmlParser('<root><foo>bar</foo>', {strictMode: false});
} catch(err: any) {
assert.fail('Should not fail');
}
});
it('test 3 - strictMode ON', function() {
try {
xmlParser('<root><foo>bar</foo>', {strictMode: true});
assert.fail('Should not fail');
} catch(err: any) {
assert.equal(err.message, 'Failed to parse XML');
assert.equal((err as ParsingError).cause, 'Closing tag not matching "</root>"');
}
});
it('test 4 - strictMode ON', function() {
try {
xmlParser('<root><content><p xml:space="preserve">This is <b>some</b> content.</contentXX></p>', {strictMode: true});
assert.fail('Should not fail');
} catch(err: any) {
assert.equal(err.message, 'Failed to parse XML');
assert.equal((err as ParsingError).cause, 'Closing tag not matching "</p>"');
}
});
});
it('should support declarations', function() {
const node = xmlParser('<?xml version="1.0" ?><foo></foo>');
const root: XmlParserElementNode = {
type: 'Element',
name: 'foo',
attributes: {},
children: []
};
assert.deepEqual(node, {
declaration: {
name: 'xml',
type: 'ProcessingInstruction',
attributes: {
version: '1.0'
}
},
root: root,
children: [root]
});
});
it('should support comments', function() {
const node = xmlParser('<!-- hello --><foo><!-- content --> hey</foo><!-- world -->');
const root: XmlParserElementNode = {
type: 'Element',
name: 'foo',
attributes: {},
children: [
{type: 'Comment', content: '<!-- content -->'},
{type: 'Text', content: ' hey'}
]
};
assert.deepEqual(node, {
declaration: null,
root: root,
children: [
{type: 'Comment', content: '<!-- hello -->'},
root,
{type: 'Comment', content: '<!-- world -->'}
]
});
});
it('should support tags without text', function() {
const node = xmlParser('<foo></foo>');
assert.deepEqual(node.root, {
type: 'Element',
name: 'foo',
attributes: {},
children: []
});
});
it('should support tags with text', function() {
const node = xmlParser('<foo>hello world</foo>');
assert.deepEqual(node.root, {
type: 'Element',
name: 'foo',
attributes: {},
children: [
{type: 'Text', content: 'hello world'}
]
});
});
it('should support weird whitespace', function() {
const node = xmlParser('<foo \n\n\nbar\n\n= \nbaz>\n\nhello world</\n\nfoo>');
assert.deepEqual(node.root, {
type: 'Element',
name: 'foo',
attributes: {bar: 'baz'},
children: [
{type: 'Text', content: '\n\nhello world'}
]
});
});
it('should support tags with attributes', function() {
const node = xmlParser('<foo bar=baz some="stuff here" a.1="2" whatever=\'whoop\'></foo>');
assert.deepEqual(node.root, {
type: 'Element',
name: 'foo',
attributes: {
bar: 'baz',
some: 'stuff here',
'a.1': '2',
whatever: 'whoop'
},
children: []
});
});
it('should support nested tags', function() {
const node = xmlParser('<a><b><c>hello</c></b></a>');
assert.deepEqual(node.root, {
type: 'Element',
name: 'a',
attributes: {},
children: [
{
type: 'Element',
name: 'b',
attributes: {},
children: [
{
type: 'Element',
name: 'c',
attributes: {},
children: [{type: 'Text', content: 'hello'}]
}
]
}
]
});
});
it('should support nested tags with text', function() {
const node = xmlParser('<a>foo <b>bar <c>baz</c> bad</b></a>');
assert.deepEqual(node.root, {
type: 'Element',
name: 'a',
attributes: {},
children: [
{type: 'Text', content: 'foo '},
{
type: 'Element',
name: 'b',
attributes: {},
children: [
{type: 'Text', content: 'bar '},
{
type: 'Element',
name: 'c',
attributes: {},
children: [{type: 'Text', content: 'baz'}]
},
{type: 'Text', content: ' bad'}
]
}
]
});
});
it('should support self-closing tags', function() {
const node = xmlParser('<a><b>foo</b><b a="bar" /><b>bar</b></a>');
assert.deepEqual(node.root, {
type: 'Element',
name: 'a',
attributes: {},
children: [
{
type: 'Element',
name: 'b',
attributes: {},
children: [{type: 'Text', content: 'foo'}]
},
{
type: 'Element',
name: 'b',
attributes: {
'a': 'bar'
},
children: null
},
{
type: 'Element',
name: 'b',
attributes: {},
children: [{type: 'Text', content: 'bar'}]
}
]
});
});
it('should support self-closing tags without attributes', function() {
const node = xmlParser('<a><b>foo</b><b /> <b>bar</b></a>');
assert.deepEqual(node.root, {
type: 'Element',
name: 'a',
attributes: {},
children: [
{
type: 'Element',
name: 'b',
attributes: {},
children: [{type: 'Text', content: 'foo'}]
},
{
type: 'Element',
name: 'b',
attributes: {},
children: null
},
{type: 'Text', content: ' '},
{
type: 'Element',
name: 'b',
attributes: {},
children: [{type: 'Text', content: 'bar'}]
}
]
});
});
it('should support multi-line comments', function() {
const node = xmlParser('<a><!-- multi-line\n comment\n test -->foo</a>');
assert.deepEqual(node.root, {
type: 'Element',
name: 'a',
attributes: {},
children: [
{
'content': '<!-- multi-line\n comment\n test -->',
'type': 'Comment'
},
{type: 'Text', content: 'foo'}
]
});
});
it('should support attributes with a hyphen and namespaces', function() {
const node = xmlParser('<a data-bar="baz" ns:bar="baz">foo</a>');
assert.deepEqual(node.root, {
type: 'Element',
name: 'a',
attributes: {
'data-bar': 'baz',
'ns:bar': 'baz'
},
children: [{type: 'Text', content: 'foo'}]
});
});
it('should support tags with a dot', function() {
const node = xmlParser('<root><c:Key.Columns><o:Column Ref="ol1"/></c:Key.Columns><c:Key.Columns><o:Column Ref="ol2"/></c:Key.Columns></root>');
assert.deepEqual(node.root, {
type: 'Element',
name: 'root',
attributes: {},
children: [{
type: 'Element',
name: 'c:Key.Columns',
attributes: {},
children: [{
type: 'Element',
name: 'o:Column',
attributes: {
'Ref': 'ol1'
},
children: null
}]
}, {
type: 'Element',
name: 'c:Key.Columns',
attributes: {},
children: [{
type: 'Element',
name: 'o:Column',
attributes: {
'Ref': 'ol2'
},
children: null
}]
}]
});
});
it('should support tags with hyphen and namespaces', function() {
const node = xmlParser(
'<root>' +
'<data-field1>val1</data-field1>' +
'<ns:field2>val2</ns:field2>' +
'</root>'
);
assert.deepEqual(node.root, {
type: 'Element',
name: 'root',
attributes: {},
children: [
{
type: 'Element',
name: 'data-field1',
attributes: {},
children: [{type: 'Text', content: 'val1'}]
},
{
type: 'Element',
name: 'ns:field2',
attributes: {},
children: [{type: 'Text', content: 'val2'}]
}
]
});
});
it('should support unicode characters', function() {
const node = xmlParser(
'<root>' +
'<tåg åttr1="vålue1" åttr2=vålue2>' +
'<tåg>' +
'<tag ąśćłó="vålue1"/>' +
'</tåg>' +
'</tåg></root>');
assert.deepEqual(node.root, {
type: 'Element',
name: 'root',
attributes: {},
children: [
{
type: 'Element',
name: 'tåg',
attributes: {
'åttr1': 'vålue1',
'åttr2': 'vålue2'
},
children: [
{
type: 'Element',
name: 'tåg',
attributes: {},
children: [
{
type: 'Element',
name: 'tag',
attributes: {
'ąśćłó': 'vålue1'
},
children: null
}
]
}
]
}
]
});
});
it('should trim the input', function() {
const node = xmlParser(' <foo></foo> ');
assert.deepEqual(node.root, {
type: 'Element',
name: 'foo',
attributes: {},
children: []
});
});
it('should support CDATA elements', function() {
const node = xmlParser('<?xml version="1.0" ?><foo><![CDATA[some text]]> hello <![CDATA[some more text]]></foo>');
const root: XmlParserElementNode = {
type: 'Element',
name: 'foo',
attributes: {},
children: [
{type: 'CDATA', content: '<![CDATA[some text]]>'},
{type: 'Text', content: ' hello '},
{type: 'CDATA', content: '<![CDATA[some more text]]>'},
]
};
assert.deepEqual(node, {
declaration: {
name: 'xml',
type: 'ProcessingInstruction',
attributes: {
version: '1.0'
}
},
root: root,
children: [root]
});
});
it('should support CDATA elements with XML content', function() {
const node = xmlParser('<?xml version="1.0" ?><foo><![CDATA[<baz/>]]> hello</foo>');
const root: XmlParserElementNode = {
type: 'Element',
name: 'foo',
attributes: {},
children: [
{type: 'CDATA', content: '<![CDATA[<baz/>]]>'},
{type: 'Text', content: ' hello'}
]
};
assert.deepEqual(node, {
declaration: {
name: 'xml',
type: 'ProcessingInstruction',
attributes: {
version: '1.0'
}
},
root: root,
children: [root]
});
});
context('should support DOCTYPE', function() {
function assertParser(doctype: string): void {
const node = xmlParser(`<?xml version="1.0" ?>\n${doctype}\n<foo></foo>`);
const root: XmlParserElementNode = {
type: 'Element',
name: 'foo',
attributes: {},
children: []
};
assert.deepEqual(node, {
declaration: {
name: 'xml',
type: 'ProcessingInstruction',
attributes: {
version: '1.0'
}
},
root: root,
children: [
{type: 'DocumentType', content: doctype},
root
]
});
}
it('DOCTYPE with SYSTEM', function () {
assertParser('<!DOCTYPE foo SYSTEM "foo.dtd">');
});
it('DOCTYPE with PUBLIC', function () {
assertParser('<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN">');
});
it('DOCTYPE with inline entities', function () {
assertParser('<!DOCTYPE foo [ <!ENTITY myentity1 "my entity value" >\n <!ENTITY myentity2 "my entity value" > ]>');
assertParser('<!DOCTYPE foo[<!ENTITY myentity1 "my entity value" >\n <!ENTITY myentity2 "my entity value" >]>');
});
it('DOCTYPE with empty inline entities', function () {
assertParser('<!DOCTYPE foo []>');
assertParser('<!DOCTYPE foo[]>');
assertParser('<!DOCTYPE foo [ ]>');
assertParser('<!DOCTYPE foo>');
});
});
it('should support processing instructions', function() {
const node = xmlParser('<?xml version="1.0" ?><?xml-stylesheet href="style.xsl" type="text/xsl" ?><foo></foo>');
const root: XmlParserElementNode = {
type: 'Element',
name: 'foo',
attributes: {},
children: []
};
assert.deepEqual(node, {
declaration: {
name: 'xml',
type: 'ProcessingInstruction',
attributes: {
version: '1.0'
}
},
root: root,
children: [
{
name: 'xml-stylesheet',
type: 'ProcessingInstruction',
attributes: {
href: 'style.xsl',
type: 'text/xsl'
}
},
root
]
});
});
it('should support complex XML', function() {
const node = xmlParser(`<?xml version="1.0" encoding="utf-8"?>
<!-- Load the stylesheet -->
<?xml-stylesheet href="foo.xsl" type="text/xsl" ?>
<!DOCTYPE foo SYSTEM "foo.dtd">
<foo>
<![CDATA[some text]]> and <bar>some more</bar>
</foo>`);
const root: XmlParserElementNode = {
type: 'Element',
name: 'foo',
attributes: {},
children: [
{type: 'Text', content: '\n'},
{type: 'CDATA', content: '<![CDATA[some text]]>'},
{type: 'Text', content: ' and '},
{
type: 'Element',
name: 'bar',
attributes: {},
children: [
{type: 'Text', content: 'some more'}
]
},
{type: 'Text', content: '\n'}
]
};
assert.deepEqual(node, {
declaration: {
name: 'xml',
type: 'ProcessingInstruction',
attributes: {
version: '1.0',
encoding: 'utf-8'
}
},
root: root,
children: [
{type: 'Comment', content: '<!-- Load the stylesheet -->'},
{
name: 'xml-stylesheet',
type: 'ProcessingInstruction',
attributes: {
href: 'foo.xsl',
type: 'text/xsl'
}
},
{type: 'DocumentType', content: '<!DOCTYPE foo SYSTEM "foo.dtd">'},
root
]
});
});
it('should parse by filtering all nodes', function() {
const node = xmlParser(`<?xml version="1.0" encoding="utf-8"?>
<!-- Load the stylesheet -->
<?xml-stylesheet href="foo.xsl" type="text/xsl" ?>
<!DOCTYPE foo SYSTEM "foo.dtd">
<foo>
<![CDATA[some text]]> and <bar>some more</bar>
</foo>`, {
filter: () => false
});
const root: XmlParserElementNode = {
type: 'Element',
name: 'foo',
attributes: {},
children: []
};
assert.deepEqual(node, {
declaration: {
name: 'xml',
type: 'ProcessingInstruction',
attributes: {
version: '1.0',
encoding: 'utf-8'
}
},
root: root,
children: [
root
]
});
});
it('should parse by filtering some nodes', function() {
const node = xmlParser(`<?xml version="1.0" encoding="utf-8"?>
<!-- Load the stylesheet -->
<?xml-stylesheet href="foo.xsl" type="text/xsl" ?>
<!DOCTYPE foo SYSTEM "foo.dtd">
<foo>
<![CDATA[some text]]> and <bar>some more</bar>
</foo>`, {
filter: (node) => {
return !['Comment', 'CDATA'].includes(node.type);
}
});
const root: XmlParserElementNode = {
type: 'Element',
name: 'foo',
attributes: {},
children: [
{type: 'Text', content: '\n'},
{type: 'Text', content: ' and '},
{
type: 'Element',
name: 'bar',
attributes: {},
children: [
{type: 'Text', content: 'some more'}
]
},
{type: 'Text', content: '\n'}
]
};
assert.deepEqual(node, {
declaration: {
name: 'xml',
type: 'ProcessingInstruction',
attributes: {
version: '1.0',
encoding: 'utf-8'
}
},
root: root,
children: [
{
name: 'xml-stylesheet',
type: 'ProcessingInstruction',
attributes: {
href: 'foo.xsl',
type: 'text/xsl'
}
},
{type: 'DocumentType', content: '<!DOCTYPE foo SYSTEM "foo.dtd">'},
root
]
});
});
});
|
0dc1d720f4cb0197fc6c63b990842aa1b385b396
|
[
"Markdown",
"TypeScript"
] | 3 |
Markdown
|
chrisbottin/xml-parser
|
4119f5e4b5365c1b060245c29d73ebbf2d97f209
|
a7efc3d032b72253e6dc2a4041ecc98ece864cec
|
refs/heads/master
|
<repo_name>danielboucher/javascript-logging-lab-js-intro-000<file_sep>/index.js
console.error("HALP!");
console.log("You have made a mistake!");
console.warn("Danger, this could break something");
|
37653ca8405a24ebed1c953f8df1e93dae9aa77b
|
[
"JavaScript"
] | 1 |
JavaScript
|
danielboucher/javascript-logging-lab-js-intro-000
|
e8ca1e4c6a1e7980f0164cb7ffc88d45d453988e
|
3126f4ab6930bdc3b7cc0123ff7ec84a57956344
|
refs/heads/main
|
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Kolokwium.Models
{
public class ClientsDbContext : DbContext
{
public DbSet<Klient> Klient { get; set; }
public DbSet<Zamowienie> Zamowienie { get; set; }
public DbSet<Pracownik> Pracownik { get; set; }
public DbSet<WyrobCukierniczy> WyrobCukierniczy { get; set; }
public DbSet<Zamowienie_WyrobCukierniczy> Zamowienie_WyrobCukierniczy { get; set; }
public ClientsDbContext()
{
}
public ClientsDbContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Zamowienie_WyrobCukierniczy>()
.HasKey(p => new { p.IdWyrobuCukierniczego, p.IdZamowienia });
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Kolokwium.Models
{
public class Zamowienie
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IdZamowienia { get; set; }
public DateTime DataPrzyjecia { get; set; }
public DateTime? DataRealizacji { get; set; }
[MaxLength(300)]
public string? Uwagi { get; set; }
public int IdKlient { get; set; }
[ForeignKey("IdKlient")]
public virtual Klient Klient { get; set; }
public int IdPracownik { get; set; }
[ForeignKey("IdPracownik")]
public virtual Pracownik Pracownik { get; set; }
public virtual ICollection<Zamowienie_WyrobCukierniczy> Zamowienie_WyrobCukierniczy { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Kolokwium.DTO.Request
{
public class WyrobDtoRequest
{
public int Ilosc { get; set; }
public string Wyrob { get; set; }
public string Uwagi { get; set; }
}
public class CreateOrderDtoRequest
{
public CreateOrderDtoRequest()
{
Wyroby = new HashSet<WyrobDtoRequest>();
}
public DateTime DataPrzyjecia { get; set; }
public string Uwagi { get; set; }
public ICollection<WyrobDtoRequest> Wyroby { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Kolokwium.DTO.Request;
using Kolokwium.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Kolokwium.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class OrdersController : ControllerBase
{
private readonly ClientsDbContext _context;
public OrdersController(ClientsDbContext context)
{
_context = context;
}
[HttpGet]
public IActionResult GetOrders (string Nazwisko)
{
ICollection<Zamowienie> orders;
if (Nazwisko == null)
{
orders = _context.Zamowienie.ToList();
//...
return Ok(orders);
}
else
{
orders = _context.Zamowienie
.Where(z => z.Klient.Nazwisko == Nazwisko)
.ToList();
}
// pobranie dla każdego zamowienia listy wyrobow
return Ok();
}
[HttpPost]
public IActionResult CreateOrder(CreateOrderDtoRequest request)
{
if (request.Wyroby == null || request.Wyroby.Count == 0)
{
return BadRequest("Zamowienie musi miec min 1 wyrob");
}
foreach(var i in request.Wyroby)
{
if (_context.WyrobCukierniczy.Any(s => s.Nazwa == i.Wyrob))
{
return BadRequest("Podano nieistniejacy wyrob");
}
}
var wyroby = _context.WyrobCukierniczy
.Where(w => request.Wyroby.Any(r => r.Wyrob == w.Nazwa));
var newOrder = new Zamowienie
{
DataPrzyjecia = request.DataPrzyjecia,
Uwagi = request.Uwagi
};
var newOrderProduct = request.Wyroby.Select(w => new
Zamowienie_WyrobCukierniczy
{
Ilosc = w.Ilosc,
Uwagi = w.Uwagi,
Zamowienie = newOrder,
WyrobCukierniczy = _context.WyrobCukierniczy.Where(ww => ww.Nazwa == w.Wyrob).First()
}) ;
_context.Zamowienie.Add(newOrder);
//_context.Zamowienie_WyrobCukierniczy.AddRange(newOrderProduct);
_context.SaveChanges();
return Ok();
}
}
}<file_sep>using Kolokwium.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Kolokwium.DTO.Response
{
public class OrderDtoResponse
{
public int IdZamowienia { get; set; }
public DateTime DataPrzyjecia { get; set; }
public DateTime? DataRealizacji { get; set; }
public string? Uwagi { get; set; }
public ICollection<WyrobCukierniczy> WyrobCukierniczy { get; set; }
}
}
|
85bf921dd34f66358e161629671570db7a098865
|
[
"C#"
] | 5 |
C#
|
fongok87/APBD_CW7
|
5412d1229f2767e143ea2cd7676fb758edf9b184
|
d8d8d773857ce66b755322199e47a67bc9c3f134
|
refs/heads/master
|
<repo_name>sim-jihoon/simjihoon<file_sep>/README.md
# simjihoon
## I failed to make new git
|
f46614cdcc602a60a35598ae6515119c5d87f40a
|
[
"Markdown"
] | 1 |
Markdown
|
sim-jihoon/simjihoon
|
346dd6b0aa44a960cc8a5cc76b663eb3f0a5d74f
|
23b3537caffea6a6c3cb1f531036d2023e64cda6
|
refs/heads/main
|
<file_sep># HazeCoinsAPI (Wird noch nicht genutzt)
RushGamez Coinssystem | Version 1.0.0
# API | Erklärung und funktionen werden bei wiki gezeigt
Schau bei der WIKI vorbei
https://github.com/FruitHaze/HazeCoinsAPI/wiki
# Author
FruitHaze
|
250086dc86c2393d63c8e88ee1eb89fdbca2d9ec
|
[
"Markdown"
] | 1 |
Markdown
|
FruitHaze/HazeCoinsAPI
|
8e02f6701c497478a3735f7503fcb73818812ba5
|
5b4db9f04e60a31a962ce14644f195a40c419552
|
refs/heads/master
|
<file_sep>Results/*.Rdata linguist-vendored=false
Results/*.md linguist-vendored=false
Results/*.Rmd linguist-vendored=false
<file_sep>---
title: 'Reproduction of: Automated identification of stratifying signatures in cellular
subpopulations'
author: "<NAME> ( ), <NAME> (16-947-640)"
date: "Januar 7, 2017"
output:
pdf_document: default
html_document:
css: Results/mystyle.css
bibliography: Results/biblio.bib
---
<br\><br\><br/>
<br\><br\><br/>
```{r "setup", echo=FALSE, include=FALSE}
knitr::opts_knit$set(root.dir = "C:/Users/user/Downloads/STA426Project/") # with something else than `getwd()`
library(captioner)
library(citrus)
library(knitr)
library(png)
#this loads environment
load(file="C:/Users/user/Downloads/STA426Project/submitme.RData")
figs <- captioner(prefix="Figure")
tbls <- captioner(prefix="Table")
figs("eventcount_files","Total number of events per file")
capeventcount = figs("eventcount_files")
figs("box","The same data is plotted here as in Table 1. We picked a random patient and looked at the boxplots for the mean marker intensity of 100 trials.", display=FALSE)
capbox = figs("box")
figs("test","add some text here")
test = figs("test")
figs("hiplot","add some text here")
hiplot = figs("hiplot")
figs("img","Estimated Model Error Rate and feature FDRs as a function of model regularization threshold. The threshold at at which final model is constrained is shown by dotted red line.")
capimg = figs("img")
#figs("img2","Estimated Model Error Rate without nFolds")
#capimg2 = figs("img2")
figs("box1","Four features chosen by the FDR threshold that we estimate to be the four most significant features. Applied was a Kolmogorov–Smirnov test to determien the most unlike distributions")
capbox1 = figs("box1")
#figs("box2","Four features chosen by the FDR threshold from median features that we estimat to be the four most significant features. Applied was a Kolmogorov–Smirnov test to determien the most unlike distributions")
#capbox2 = figs("box2")
tbls("dataspread","Each files was downsampled with 5000 samples for 1000 times. Each time the mean marker intensity for the extracellular markers was calculated. Here we show the mean of 1000 means ± s.d.. Patient 1 has s.d. zero because the files contain less than 5000 events.")
capdataspread = tbls("dataspread")
```
##Introduction
Single cell measurements have a clear advantage over whole population measurements. In whole population measurements we measure the average value of a parameter over the total population in the sample. To answer questions that involve the study of specific subpopulation of cells, this is not very helpful. With single cell measurements, we are able to get values for each cell separately. Given single cell data from a sample, we should be able to stratify the cells into its subpopulation and make some prediction towards a disease state, for example.
The most common method to obtain single cell measurements is flow cytometry. For a long time fluorescent flow cytometry was very popular. With this method, in addition to physical properties such as shape though light scattering, one can measure signal strength of a fluorescent marker on and in the cell. This technique is limited by the spectral overlap, i.e. the overlap of the wavelength of the differently colored fluorescent used. This makes it very hard to distinguish a large number of parameters. In resent time flow cytometry has been coupled with mass spectrometry to allow the measurements of >40 inner and outer cellular parameters at the same time. Very briefly, in this method samples are incubated with antibodies carrying rare metals and are then vaporized in a time-of-flight mass spectrometer. The mass of the rare metals and their abundance is measured and replaces the fluorescent measurement of fluorescent flow cytometry.<br>
Bruggner [@Bruggner2014] has proposed a new automated method to detect stratifying signatures in cellular sub populations. They named their method Citrus and it is available as an R package. Citrus combines unsupervised and supervised learning to select significant features within the data. First, a predefined number of samples is randomly selected from each patient and the data is combined. This data is then clustered using hierarchical clustering. From these clusters, citrus tries to extract relevant features. Features are selected by building and testing models for the values of the mean difference of intensity values of the intra cellular markers. These intra cellular markers are tested against the end-point e.g. healthy / diseased.The model is tested via cross-validation and a subset of features chosen accordingly.
In this project work, we set out to explain the workings of citrus in more detail while following the same real world example that is used in the original paper. We want to reproduce the results presented by Bruggner et al, more specifically, we are curious if we are able to find the same top four features in the data set as presented in Figure 2B of the paper.
##Data
Bodenmiller [@Bodenmiller2012] created a dataset with a newly proposed mass-tag cellular barcoding (MCB) method. This method allows for very high dimensional data acquired with mass cytometry. More specifically they set out to measure signaling dynamics and cell-to-cell communication in peripheral blood mononuclear cells (PBMC). To this end 12 different experimental conditions were set up and 14 signaling nodes and 10 cell-surface markers were measured at different time points from 0-4h. Here we focus on one of those conditions mainly the cross-linking of the B-cell receptor (BCR)/Fc receptor (FcR). The data consist of 16 samples of eight healthy donors, one reference and one treated sample per patient.
##Data sampling
The data [@data] was downloaded from cytobank.org. In total 16 .fcs files were downloaded. For each patient there is a different number of events in the FCS files. As Figure 2 shows the number of events ranges from about 3000 in patient 1 to about 17'000 in patient 2. To prevent over representation of any one sample and to reduce computation time Citrus sub samples a user specified number of events per patient and then merges the data before clustering.
<br />
```{r fig.align='center',fig.cap=capeventcount, echo=FALSE}
par(mar=c(6,4,2,2)) #sets the bottom, left, top and right
barplot(eventcount,main="Event distribution",
names.arg=c("p1 BCR-XL","p1 ref","p2 BCR-XL","p2 ref","p3 BCR-XL","p3 ref","p4 BCR-XL",
"p4 ref","p5 BCR-XL","p5 ref","p6 BCR-XL","p6 ref","p7 BCR-XL","p7 ref",
"p8 BCR-XL","p8 ref"),las=2)
```

The function sample() from the R base package is used to select 5000 random data points from each FCS files, if available. As we have tried to reproduce the exact data obtained by Bruggner et al. we found that this is not possible. We suspect this to be the result of sub sampling the date. Each time citrus selects 5000 out of 17'000 events the clustering results are different. Because in hierarchical clustering every data point is seen as a cluster, a significance threshold of 5% was defined. In order words, only clusters containing 5% or more of the total data are seen as significant enough to be considered for further analysis. The original paper represented a clustering containing 31 significant clusters. During our work with citrus and the Bodenmiller data we clustered the data dozens of times and everything from 31 to 37 clusters were obtained, every number multiple times expect 31. We got 31 exactly once. To get an idea how different the sub-samples really are, we decided to sub-sample 5000 data points for each data file 10 times and calculate the mean and standard deviation of the mean of the intensity of the markers. Table 1 below shows the result of this sub-sampling. We sampled 10 times to really get a feeling of range of different types of possible results and not get tricked by the law of large numbers into thinking that there is very low variance. The method proposed by Bruggner et al. uses only one iteration of clustering and feature selection after all. As we can see in Table 1 below the standard deviations of the sample would suggests that few iterations of the clustering process would give a good average representation of the data.
```{r results='asis',echo=FALSE}
kable(data_analysis, caption = "Table1: Each files was downsampled with 5000 samples for 10 times. Each time the mean marker intensity for the extracellular markers was calculated. Here we show the mean of 10 means ± s.d.. Patient 1 has s.d. zero because the files contain less than 5000 events.",format = "html")
```

<br /><br />
It is interesting to look at box plots of one specific patient. Figure 2 below shows the same data as in Table 1 for patient 2. This box plot reveals that for our 10xsampling there are outliers for CD14 and CD45. If, as proposed in the paper, the clustering and feature selection process would only be iterated once, this could have an impact on the result. In other words, our small test has shown that even in 10 sub-sampling it is possible to have datasets containing outliers what could lead to different results in hierarchical clustering.
<br /><br />
```{r results='asis',fig.align='center',fig.cap=capbox, echo=FALSE}
par(mfrow=c(5,2))
marker_names = c("CD3","CD45","CD4","CD20","CD33","CD123","CD14","igM","HLA-DR","CD7")
par(mar=c(2,2,2,2))
par(las = 1) # all axis labels horizontal
for(x in 1:10){
boxplot(as.data.frame(avgintensity_plot[,x]), main = paste("Patient 2 BCR-XL",marker_names[x]),
horizontal = TRUE)
}
```

<br /><br />
##Clustering of data by extracellular markers
One popular method for unsupervised learning is clustering. In clustering one can apply different algorithms to detect structure within a given data set and can build features based on cluster membership. Citrus uses Rclusterpp.hclust() also created by Bruggner et al. This function is an implementation of the Agglomerative Hierarchical Clustering algorithm. In hierarchical clustering smaller clusters are merged into larger clusters following a given distance function and linkage method. In Citrus the distance between markers is specified by the Euclidean distance and Wards linkage used as the agglomerative method. Wards methods minimizes the total within cluster variance.
The Bodenmiller data is clustered by the intensity of the extra cellular markers CD45, CD4, CD20, CD33, CD123, CD14, IgM, HLA-DR, CD7 and CD3.
After clustering it is interesting to look at the topology of the resulting clustering graphs. Figure 3 below shows a graph of clusters containing at least 1% of the total data. A graph is shown for each extra cellular marker and the clusters are color coded according to the relative intensity of the marker in that cluster. This type of graphs reveals subsets of cells in the data. Interesting is the sub graphs which are prominent for CD20 and CD33 but reappears in half of all the graphs. It can be speculated, that this sub graph represents an important subset of the cells because they appear to have several markers differentialy expressed. Notably this clear substructure was not detected in each clustering. In fact, we had to cluster several times to achieve a nice result like this as is presented in the paper (Figure S12 [@Bruggner2014]).
<br /><br /><br />
<figure align="middle">
<img src="Images/submitme_hierarchy.png" alt="-" align="middle">
<figcaption>Figure 3. Hierarchical plot of all clusters containing at least 1% of the total data. The relative intensity of the extra cellular markers are color coded and show the existence of sub graphs which correspond to sub populations of cells.</figcaption>
</figure>
<br /><br />
##Compare clustering with different subsamples
Figure 4 illustrate the diversity of results we obtained. These instances of clustering have a significant number of clusters at 5% in a range of 31 to 40. In neither of them did we find a clear sub graph represented over multiple markers.
<br /><br />
<figure >
<img src="Images/4clusterings.png" alt="-" >
<figcaption>Figure 4. Hierarchy graphs based on four different sub-sampling of the data. Plotted are clusters with more then 1% of the data. Number of clusters for 5% of the data range from 32 to 40 among these four clusterings. </figcaption>
</figure>
<br /><br />
##Feature Extraction
As in [@Bruggner2014] after clustering the data according to the extra cellular markers features are extracted based on intra cellular markers. The markers selected for feature extraction are: pNFkB(Nd142)Dd, pp38(Nd144)Dd, pStat5(Nd150)Dd, pAkt(Sm152)Dd, pStat1(Eu153)Dd, pSHP2(Sm154)Dd, pZap70(Gd156)Dd, pStat3(Gd158)Dd, pSlp76(Dy164)Dd, pBtk(Er166)Dd, pPlcg2(Er167)Dd, pErk(Er168)Dd, pLat(Er170)Dd and pS6(Yb172)Dd. These are all phosphorylated internal signaling nodes. The hope is that the measured values for these signaling nodes are influenced by the B-cell receptor (BCR)/Fc receptor (FcR) cross linking. There two feature types that can be extracted with citrus, abundance and medians. For the given data Bruggner used the median features. For this the median for each marker is calculated on a per-sample base.
##Model Construction
It is necessary to assign each and every sample to one of two or more stimulation groups (i.e 'Reference' and 'BCR-treated' in this case), when we wish to identify features that differ between these groups. After the calculation of descriptive cluster features, regularized classification models are generated, where the cluster features act as independent variables/regressors of the sample groups. However, only a subset of calculated cluster features are used to obtain the differences between the groups. Thus, model generation uses methods such as nearest shrunken centroid (pamr) and lasso-regularized logistic regression (glmnet). These methods generate a series of models based on highly informative subsets of the provided cluster features (the regressors) which are automatically selected. The number of regressors that are included in any given model are restricted by regularization threshold. But, as it not possible to know which subset of features best stratify the groups, instead of a single model at a specified threshold, a set of 'i' models are built using a range of 'i' regularization thresholds. Now, to select an optimal model, cross-validation is perfomed and the simplest one that meets the specified constraints is selected.
The nearest shrunken centroid is derived from the standard nearest centroid classifcation. This method computes a standarized centroid for each class. It shrinks the centroids for every class towards the overall centroid for all classes by a factor of 'threshold'. This shrinkage means moving towards zero by the threshold, and setting it equal to zero when and if it hits zero. After this shrinking, the samples are classifed to their nearest centroid, but uses the shrunken class centroids. One obvious advantage has already been mentioned that it automatically selects the samples/clusters/features and also that it makes the classification more accurate.
##Results Assessment and Selection of a Final Regularization Threshold
The quality of results can be assessed using model error rate plots. A model with small estimated error rate has identified certain subset of cluster features that are strong predictors of sample groups. Building up on this, it means that these subset of features show a behaviour that is novel to that group. Hence, these features are stratifying subset of interest. On the other hand, a model with a high error rate has features that do not differ between sample classes and hence are not useful stratifying features. Thus, interpretation should be done only from models having an acceptable error rate.
When such models with acceptable error rates have been constructed, a regularization threshold is chosen that will be used to constrain the final model. The final model is constructed from all the sample features. A regularization threshold is chosen that results in the simplest model with acceptable error rate. This model would then have a small but informative subset of features differeing between groups. Accordingly, when it is required to identify all of the features that differ between samples, a threshold should be chosen such that, at this value it prodcues a complex model with acceptable error rate and a feature FDR.
##Interpretation of Results
The final constrained model that is generated based on the regularization thresholds and sample features. The non zero features of this final model are the set of features that best differentiate between the sample. The values of these relevant features for each sample are shown in box plots. Related stratifying subsets that have similar behavior may be identified by highlighting relevant subsets in plots of the clustering hierarchy. The plots of clustering hierarchy can be highlighted to identify stratifying subsets that depict similar behaviour.
##Results
The descriptive cluster features were used to train a nearest shrunken centroid classifier (pamr) of the sample's simulation group (reference or BCR-treated) at a range of regularization thresholds that is automatically computed by citrus. Cross-validation and permutation tests are used to estimate and plot classification error rates and feature false discovery rates of each model respectively.
In order to determine all features that differed between the different sample groups, error plot produced above was used to identify the smallest regularization threshold that produced a model with acceptable cross validation accuracy and an estimated feature FDR of < 1%. Using this, Citrus constrained the final classificaiton model from all sample. From the original set of 504 cluster features, a subset of 51 was chosen as which differed between the two simulation conditions. The cutoff line is drawn at the point where the cross validation mean and feature false discovery rate is 0. This line intersects the regularization threshold axis at 2.24805 and the Number of features axis at 51
##Model Error Rate
```{r fig.align='center',fig.cap=capimg, echo=FALSE}
par(mar=c(5,4,4,6)+0.1)
plot(citrus.regressionResult$thresholdCVRates$cvm,
pch=c(1,NA,NA,NA,NA,NA,NA),
axes=FALSE,
ylim = c(0,0.6),
xlab="",ylab="",
type='l', col="black", bg="black")
axis(2, col="red", las = 1)
mtext("Cross Validation Error Rate",side=2,line=2.5)
box()
par(new=TRUE)
plot(citrus.regressionResult$thresholdCVRates$fdr,
pch=c(1,NA,NA,NA,NA,NA,NA),
axes=FALSE,
ylim = c(0,0.6),
xlab="",ylab="",
type='l',col="blue")
axis(4, col="blue", las = 1)
mtext("Feature False Discovery Rate",side=4,line=4)
box()
par(new=TRUE)
axis(1, at=c(1:100),labels=signif(citrus.regressionResult$thresholdCVRates$threshold,2))
mtext("Regularization Thresholds", side=1,line=2.5)
axis(3, at=c(1:100),labels=citrus.regressionResult$finalModel$model$nonzero)
mtext("Number of Features", side=3,line=2.5)
par(new=TRUE)
points(57, citrus.regressionResult$thresholdCVRates$fdr[57],col="red")
for(i in 1:100){
if(citrus.regressionResult$thresholdCVRates$cvm[i] == 0.0){
par(new=TRUE)
points(i, citrus.regressionResult$thresholdCVRates$cvm[i],col="green")
break
}
}
par(new=TRUE)
abline(v=citrus.regressionResult$cvMinima$cv.fdr.constrained.index, col="red", lty=2)
legend("topleft",
inset = c(0,0),
cex = 0.8,
bty = "n",
legend = c("Feature False Discovery Rate", "Cross Validation Error Rate","Threshold for min CV",
"Model for min FDR"),
text.col = c("black"),
col = c("blue", "black","green","red"),
pch = c(20,20,20,20))
```

##Top Features
As discussed in the introduction, the goal was to reproduce the four top features that are shown in Figure 2A [@Bruggner2014]. The citrus endpoint regression function put out a list of features for the two thresholds that are available. It is not clear in what order this list it, nor is it documented anywhere. It is clear though that this list is not ordered in how significant a feature is. In the supplementary material it mentioned in a figure caption depicting top features, that feature are ordered by model weight. Unfortunately we were not able to determine this model weights. As an alternative in order to estimate the for top features we here apply a two sample Kolmogorov–Smirnov test. Unfortunately these are not the features that we hoped to see. In fact, the features that we wanted are not even in the list of all features selected under the model with the FDR threshold.
#Data Transformation
Taking a closer look median feature values, it can be observed that it contains both positive and negative values distributed over a very wide range. Using these values to create a boxplot will yield graphs that have varied scales. Such graphs are not useful when comparison need to be made. For this purpose, it was necessary to transform/normalize the data. Here, the technique of min-max normalization is used and the data values of the medain features are scaled between 0 and 4. The general formula for min-max normalization between [a,b] is:
(b - a)*(x - min(x))
-------------------- + a
max(x) - min(x)
Here, x goes through all the 504 columns of median Features, and thus the data is normalized to obtain more informative plots.
```{r echo=FALSE}
medianFeatures_trans <- matrix(nrow = 16, ncol = 504)
for(i in 1:504){
m <- min(citrus.foldFeatureSet$allFeatures[,i])
maxi <- max(citrus.foldFeatureSet$allFeatures[,i])
for(j in 1:16){
medianFeatures_trans[j,i] <- 4*((citrus.foldFeatureSet$allFeatures[j,i] - m)/(maxi - m))
}
}
rownames(medianFeatures_trans) <- rownames(citrus.foldFeatureSet$allFeatures)
colnames(medianFeatures_trans) <- colnames(citrus.foldFeatureSet$allFeatures)
```
#BoxPlots
```{r fig.align='center',fig.cap=capbox1, echo=FALSE}
#Box plot for the first 4 features.
list_fea <- citrus.regressionResult$differentialFeatures$cv.fdr.constrained$features
p_result = vector(mode="numeric", length =length(list_fea))
#to determine the order of features, i.e. which is the best, we apply a t test to determine the p value for distributions drawn from the same sample. with this we hope to say something about how good the distributions are seperated
for(i in 1:length(list_fea)){
p_result[i] = ks.test(medianFeatures_trans[1:8,list_fea[i]],
medianFeatures_trans[9:16,list_fea[i]])[2]
}
top4 = vector(mode="numeric", length=4)
temp = 0
#some weird way to find 4 top features
for(j in 1:4){
#fidn max in p_result, save it, set to 0, find next
for(i in 1:length(list_fea)){
if(p_result[[i]] > temp)
top4[j] = i
temp = p_result[i]
}
p_result[top4[j]] = 0
}
par(mar=c(2,2,2,2))
par(mfrow=c(2,2))
for(i in top4){
boxplot(medianFeatures_trans[1:8,list_fea[i]],medianFeatures_trans[9:16,list_fea[i]],
horizontal = TRUE, names=c('BCR-XL','Reference'),main=colnames(medianFeatures_trans)[i])
}
```

<br /><br />
<figure >
<img src="Images/TopFeatures2.png" alt="-" align="middle">
<figcaption>Figure 7. Box plots for the Top 4 features obtained after applying KS test. Derived from Citrus </figcaption>
</figure>
<br /><br />
Figure 8 illustrates the hierarchy graph in which all the clusters (highlighted) contain the pNFkB(Nd142)Dd median. It can be seen that the clusters 75573, 75574, 75575 and 75576 are the center of this hierarchical graph. These are the same clusters which were identified as having Top Features through the KS test.
<br /><br />
<figure >
<img src="Images/clusterhighlighted_white.png" alt="-" align="middle" >
<figcaption>Figure 8. Hierarchy Graph showing all the clusters that contain pNFkB(Nd142)Dd median. Derived from Citrus </figcaption>
</figure>
<br /><br />
##Conclusion
We were not able to reproduce the paper, as we set out to do. It is actually not even possible to exactly reproduce it due to the sub sampling as we have shown. Further more, depending on the sub sampling, the regression model can or cannot reach cross validation error rate of zero. In many cases the error rate would drop to zero only after the FDR rate started to rise. Citrus will then automatically select the threshold where the cross validation error rate is zero, while the FDR is already up 20% and in total 90%+ of all features are selected. What has been published is a very nice and clean instance, that we were not able to reproduce. And we tried.
Many important pieces of information are not given in the paper nor the supplementary material. It is not clear as to why clusters are based on extra cellular and features on intra cellular markers. It is not exactly clear how features have been calculated for the publications. The authors claim to have a total of 465 features after taking the mean of each marker for each cluster. With 31 clusters and 14 markers that would be 434 features. Our features where always expected number. Further it is not clear how the top feature are selected.
The package citrus itself is very poorly documented. There is almost no explanation on the functions available and we were not able to access source code itself. We were able to read at least part of the source code on Github which helped us to understand what the different functions do. Citrus comes with a GUI. When one executes the GUI, a different but very similar result to the one published is obtained. It even, most of the times, finds that pS6 median values in a limited number of clusters are the features containing the most amount of information regarding stratification of sub populations. Even though we tried to take citrus apart to fully understand what it does, we were not able to find the difference between what the GUI executes and what we do in R directly. Hence this different result. Funnily enough though, we were able to select a subset of features that citrus deemed to be predictive for stratification. The pNF-kB marker that was found to be a differential feature in several clusters was also found to be significant by the original publication. However, the paper also concluded that pNF-kB is an experimental artifact introduced by the multiplexing protocols.
Despite the apparent failure of this project it nevertheless teached us, again, that we can not relay on publications to be perfect. Once must always assume that what is published is the best possible way that something could have turned out and that there are many sub optimal solutions to the specific problem at hand.
# Appendix
## R Code
### Setup
```{r echo=FALSE, include=FALSE, eval=FALSE}
knitr::opts_knit$set(root.dir = "C:/Users/user/Downloads/STA426Project/") # with something else than `getwd()`
library(captioner)
library(citrus)
library(knitr)
library(png)
#this loads environment
load(file="C:/Users/user/Downloads/STA426Project/submitme.RData")
figs <- captioner(prefix="Figure")
tbls <- captioner(prefix="Table")
figs("eventcount_files","Total number of events per file")
capeventcount = figs("eventcount_files")
figs("box","The same data is plotted here as in Table 1. We picked a random patient and looked at the boxplots for the mean marker intensity of 100 trials.", display=FALSE)
capbox = figs("box")
figs("test","add some text here")
test = figs("test")
figs("test1","add some text here")
test1 = figs("test1")
figs("hiplot","add some text here")
hiplot = figs("hiplot")
figs("img","add camption here")
capimg = figs("img")
figs("box1","Four features chosen by the FDR threshold that we estimat to be the four most significant features. Applyed was a Kolmogorov–Smirnov test to determien the most unlike distributions")
capbox1 = figs("box1")
tbls("dataspread","Each files was downsampled with 5000 samples for 1000 times. Each time the mean marker intensity for the extracellular markers was calculated. Here we show the mean of 1000 means ± s.d.. Patient 1 has s.d. zero because the files contain less than 5000 events.")
capdataspread = tbls("dataspread")
```
### Loading of data
```{r eval=FALSE}
dataDirectory = "C:/Users/user/Downloads/STA426Project/data/"
#all the fcs files are loaded
fileList = data.frame(defaultCondition=
c("PBMC8_30min_patient1_BCR-XL.fcs","PBMC8_30min_patient2_BCR-XL.fcs",
"PBMC8_30min_patient3_BCR-XL.fcs","PBMC8_30min_patient4_BCR-XL.fcs",
"PBMC8_30min_patient5_BCR-XL.fcs","PBMC8_30min_patient6_BCR-XL.fcs",
"PBMC8_30min_patient7_BCR-XL.fcs","PBMC8_30min_patient8_BCR-XL.fcs",
"PBMC8_30min_patient1_Reference.fcs","PBMC8_30min_patient2_Reference.fcs",
"PBMC8_30min_patient3_Reference.fcs","PBMC8_30min_patient4_Reference.fcs",
"PBMC8_30min_patient5_Reference.fcs","PBMC8_30min_patient6_Reference.fcs",
"PBMC8_30min_patient7_Reference.fcs","PBMC8_30min_patient8_Reference.fcs"))
```
### Histogram Figure 1
```{r fig.align='center',fig.cap=capeventcount, eval=FALSE}
eventcount = vector(mode="integer", length=16)
i = 1
#loop each file and count events
for(f in files){
fcsfile = citrus.readFCS(file.path(dataDirectory,f))
eventcount[i] = dim(fcsfile)[1]
i = i +1
#sets the bottom, left, top and right
par(mar=c(6,4,2,2))
barplot(eventcount,main="Event distribution",
names.arg=c("p1 BCR-XL","p1 ref","p2 BCR-XL","p2 ref","p3 BCR-XL","p3 ref","p4 BCR-XL","p4 ref","p5 BCR-XL","p5 ref",
"p6 BCR-XL","p6 ref","p7 BCR-XL","p7 ref","p8 BCR-XL","p8 ref"),las=2)
}
```
### Data analysis for Figure 2 and Table 1
```{r eval=FALSE,echo=FALSE}
marker = c(3, 4, 9, 11, 12, 14, 21, 29, 31, 33)
marker_names = c("CD3","CD45","CD4","CD20","CD33","CD123","CD14","igM","HLA-DR","CD7")
data_analysis = matrix(data=NA, nrow=16, ncol=10)
colnames(data_analysis) = maker_names
rownames(data_analysis) = c("p1 BCR-XL","p1 Ref","p2 BCR-XL","p2 Ref","p3 BCR-XL","p3 Ref","p4 BCR-XL","p4 Ref",
"p5 BCR-XL","p5 Ref","p6 BCR-XL","p6 Ref","p7 BCR-XL","p7 Ref","p8 BCR-XL","p8 Ref")
avgintensity = matrix(data=NA, nrow=10, ncol=10)
colnames(avgintensity) = maker_names
avgintensity_plot = matrix(data=NA, nrow=10, ncol=10)
colnames(avgintensity_plot) = maker_names
k = 1
for(j in 1:8){
#loop all bcr / ref, load files
for(each in c("_BCR-XL.fcs","_Reference.fcs")){
fcsfile = citrus.readFCS(file.path(dataDirectory,paste0("PBMC8_30min_patient",j,each)))
#subsamples 10 times
for(i in 1:10){
#if not patient 1, sample 5k, p1 has only ca. 3k samples
if(j != 1){
sample_fcsfile = fcsfile[sort(sample(1:nrow(fcsfile),5000)),] #1:numberofrowsin(fcsfile)
}else{
sample_fcsfile = fcsfile #1:numberofrowsin(fcsfile)
}
#loop each marker andstore mean
for(h in 1:10){
#avgintensity is 10x10 i.e. 10 subsamples with each 10 means for 10 markers
avgintensity[i,h] = mean(sample_fcsfile@exprs[,marker[h]])
}
}
if(j == 2 && each == "_BCR-XL.fcs"){
avgintensity_plot = avgintensity
}
for(p in 1:10){
data_analysis[k,p] = paste0(signif(mean(avgintensity[,p]), digits = 2),
"±",signif(sd(avgintensity[,p]), digits = 2))
}
k = k +1
}
}
```
### Plot Figure 2
```{r results='asis',fig.align='center',fig.cap=capbox, eval=FALSE}
par(mfrow=c(5,2))
par(mar=c(2,2,2,2))
par(las = 1) # all axis labels horizontal
for(x in 1:10){
boxplot(as.data.frame(avgintensity_plot[,x]), main = paste("Patient 2 BCR-XL",marker_names[x]), horizontal = TRUE)
}
```
### Plot Table 1
```{r results='asis',eval=FALSE}
kable(data_analysis, caption = "Table1: Each files was downsampled with 5000 samples for 1000 times. Each time the mean marker intensity for the extracellular markers was calculated. Here we show the mean of 1000 means ± s.d.. Patient 1 has s.d. zero because the files contain less than 5000 events.",format = "html")
```
### Clustering
```{r eval=FALSE}
#data is clustered according to extracellular markers
clusteringColumns = c("CD3(110:114)Dd","CD45(In115)Dd","CD4(Nd145)Dd","CD20(Sm147)Dd","CD33(Nd148)Dd","CD123(Eu151)Dd",
"CD14(Gd160)Dd","IgM(Yb171)Dd","HLA-DR(Yb174)Dd","CD7(Yb176)Dd")
#vector of endpoints for regression
labels = as.factor(c("BCR-XL","BCR-XL","BCR-XL","BCR-XL","BCR-XL","BCR-XL","BCR-XL","BCR-XL",
"Reference","Reference","Reference","Reference","Reference","Reference","Reference","Reference"))
#data is loaded, sampled and combined
citrus.combinedFCSSet = citrus.readFCSSet(dataDirectory,fileList, fileSampleSize = 5000)
#clustering of folds of sampled data
citrus.foldClustering = citrus.clusterAndMapFolds(citrus.combinedFCSSet,clusteringColumns,labels,nFolds=1)
```
###Hierarchygraphs
```{r eval=FALSE}
citrus.clustering = citrus.cluster(citrus.combinedFCSSet,clusteringColumns,clusteringType = "hierarchical")
#graphs are done with clusters containing >1% of data
largeEnoughClusters1= citrus.selectClusters.minimumClusterSize(citrus.clustering,
minimumClusterSizePercent=0.01)
largeEnoughClusters5= citrus.selectClusters.minimumClusterSize(citrus.clustering,
minimumClusterSizePercent=0.05)
hierarchyGraph = citrus.createHierarchyGraph(citrus.clustering,selectedClusters=largeEnoughClusters1)
clusterMedians = t(sapply(largeEnoughClusters1,citrus:::.getClusterMedians,
clusterAssignments=citrus.clustering$clusterMembership,
data=citrus.combinedFCSSet$data,
clusterCols=clusteringColumns))
rownames(clusterMedians) = largeEnoughClusters1
colnames(clusterMedians) = clusteringColumns
citrus.plotClusteringHierarchy(outputFile="outputdirectory",clusterColors=clusterMedians,
graph=hierarchyGraph$graph,
layout=hierarchyGraph$layout,
plotSize=15,
theme = 'white',singlePDF=T,plotClusterIDs=F,scale=1)
```
###Feature extraction
```{r eval=FALSE}
#the per-sample medians for the following markers are calculated as features
medianColumns=c("pNFkB(Nd142)Dd","pp38(Nd144)Dd","pStat5(Nd150)Dd","pAkt(Sm152)Dd","pStat1(Eu153)Dd","pSHP2(Sm154)Dd",
"pZap70(Gd156)Dd","pStat3(Gd158)Dd","pSlp76(Dy164)Dd","pBtk(Er166)Dd","pPlcg2(Er167)Dd","pErk(Er168)Dd",
"pLat(Er170)Dd","pS6(Yb172)Dd")
#features are calculated on minClustersize >5%, resulting in clusternumber*14 features
citrus.foldFeatureSet = citrus.calculateFoldFeatureSet(citrus.foldClustering=citrus.foldClustering,citrus.combinedFCSSet=citrus.combinedFCSSet,featureType = "medians",medianColumns=medianColumns,minimumClusterSizePercent = 0.05)
```
###Endpoint Regression
```{r eval=FALSE}
#endpoint Regression with the goal to classifiy. labels contains endpoints
citrus.regressionResult = citrus.endpointRegress(modelType="pamr",citrus.foldFeatureSet,labels,family="classification")
```
###Figure 5
```{r eval=FALSE, fig.align='center',fig.cap=capimg}
par(mar=c(5,4,4,6)+0.1)
plot(citrus.regressionResult$thresholdCVRates$cvm,
pch=c(1,NA,NA,NA,NA,NA,NA),
axes=FALSE,
ylim = c(0,0.6),
xlab="",ylab="",
type='l', col="black", bg="black")
axis(2, col="red", las = 1)
mtext("Cross Validation Error Rate",side=2,line=2.5)
box()
par(new=TRUE)
plot(citrus.regressionResult$thresholdCVRates$fdr,
pch=c(1,NA,NA,NA,NA,NA,NA),
axes=FALSE,
ylim = c(0,0.6),
xlab="",ylab="",
type='l',col="blue")
axis(4, col="blue", las = 1)
mtext("Feature False Discovery Rate",side=4,line=4)
box()
par(new=TRUE)
axis(1, at=c(1:100),labels=signif(citrus.regressionResult$thresholdCVRates$threshold,2))
mtext("Regularization Thresholds", side=1,line=2.5)
axis(3, at=c(1:100),labels=citrus.regressionResult$finalModel$model$nonzero)
mtext("Number of Features", side=3,line=2.5)
for(i in 1:100){
if(citrus.regressionResult$thresholdCVRates$fdr[i] != 0){
par(new=TRUE)
print("test")
points(i, citrus.regressionResult$thresholdCVRates$fdr[i],col="red")
break
}
}
for(i in 1:100){
if(citrus.regressionResult$thresholdCVRates$cvm[i] == 0.0625){
par(new=TRUE)
points(i, citrus.regressionResult$thresholdCVRates$cvm[i],col="green")
break
}
}
legend("topleft",
inset = c(0,0),
cex = 0.8,
bty = "n",
legend = c("Feature False Discovery Rate", "Cross Validation Error Rate","Threshold for min CV","Model for min FDR"),
text.col = c("black"),
col = c("blue", "black","green","red"),
pch = c(20,20,20,20))
```
###Figure 6
```{r eval=FALSE, fig.align='center',fig.cap=capbox1}
#Box plot for the first 4 features.
list_fea <- citrus.regressionResult$differentialFeatures$cv.fdr.constrained$features
p_result = vector(mode="numeric", length =length(list_fea))
#to determine the order of features, i.e. which is the best, we apply a t test to determine the p value for distributions drawn from the same sample. with this we hope to say something about how good the distributions are seperated
for(i in 1:length(list_fea)){
p_result[i] = ks.test(citrus.foldFeatureSet$allFeatures[1:8,list_fea[i]],citrus.foldFeatureSet$allFeatures[9:16,list_fea[i]])[2]
}
top4 = vector(mode="numeric", length=4)
temp = 0
#some weird way to find 4 top features
for(j in 1:4){
#fidn max in p_result, save it, set to 0, find next
for(i in 1:length(list_fea)){
if(p_result[[i]] > temp)
top4[j] = i
temp = p_result[i]
}
p_result[top4[j]] = 0
}
par(mar=c(2,2,2,2))
par(mfrow=c(2,2))
for(i in top4){
boxplot(citrus.foldFeatureSet$allFeatures[1:8,list_fea[i]],citrus.foldFeatureSet$allFeatures[9:16,list_fea[i]],
horizontal = TRUE, names=c('BCR-XL','Reference'),main=colnames(citrus.foldFeatureSet$allFeatures)[i])
}
```
###Abundance and Median Feature Calculation
```{r eval=FALSE}
# Build features
abundanceFeatures = citrus.calculateFeatures(citrus.combinedFCSSet,
clusterAssignments=citrus.clustering$clusterMembership,
clusterIds=largeEnoughClusters5)
medianFeatures = citrus.calculateFeatures(citrus.combinedFCSSet,
clusterAssignments=citrus.clustering$clusterMembership,
clusterIds=largeEnoughClusters5,
featureType="medians",
medianColumns=medianColumns)
```
###Calculation of Regularization Thresholds
This function generates a range of regularization thresholds for further model construction.
```{r eval=FALSE}
#labels = factor(rep(c("bcr","ref"),each=8))
regularizationThresholds = citrus.generateRegularizationThresholds(medianFeatures,
labels,
modelType="pamr",
family="classification")
```
###Calculation of Cross Validation Error Rates
This function calculates model error rates at different regularization thresholds. It is a matrix of model error rates, standard error of error estimates and FDRs at supplied thresholds.
```{r eval=FALSE}
thresholdCVRates = citrus.thresholdCVs.quick("pamr",
medianFeatures,
labels,
regularizationThresholds,
family="classification")
```
###Calculation of Cross Validation Minima
This function provides regularization threshold of pre-selected cross validation points and their indices.
```{r eval=FALSE}
cvMinima = citrus.getCVMinima("pamr",thresholdCVRates, fdrRate = 0.01)
```
###Building of Final Model
This function constructs an endpoint model using features calculated by citrus.
```{r eval=FALSE}
finalModel = citrus.buildEndpointModel(medianFeatures,
labels,
family="classification",
type="pamr",
regularizationThresholds)
```
###Extracting Model Features.
This function reports model features ar pre-specific thresholds. For predictive models, it gives non-zero model features at specified regularization thresholds. And, for FDR-constrained models, it reports features which are below the specified FDRs.
```{r eval=FALSE}
modelfeatures = citrus.extractModelFeatures(cvMinima,finalModel,
medianFeatures)
```
```{r fig.align='center',fig.cap=capimg2, echo=FALSE, eval=FALSE}
par(mar=c(5,4,4,6)+0.1)
plot(thresholdCVRates$cvm,
pch=c(1,NA,NA,NA,NA,NA,NA),
axes=FALSE,
ylim = c(0,0.6),
xlab="",ylab="",
type='o',col="red")
axis(2, col="red", las = 1)
mtext("Cross Validation Error Rate",side=2,line=2.5, col='red')
box()
par(new=TRUE)
plot(thresholdCVRates$fdr,
pch=c(1,NA,NA,NA,NA,NA,NA),
axes=FALSE,
ylim = c(0,0.6),
xlab="",ylab="",
type='o',col="blue")
axis(4, col="blue", las = 1)
mtext("Feature False Discovery Rate",side=4,line=4, col='blue')
box()
par(new=TRUE)
axis(1, at=c(1:100),labels=signif(regularizationthresholds,2))
mtext("Regularization Thresholds", side=1, col="green",line=2.5)
axis(3, at=c(1:100),labels=finalModel$model$nonzero)
mtext("Number of Features", side=3, col="magenta",line=2.5)
par(new=TRUE)
points(cvMinima$cv.min$index, thresholdCVRates$fdr[cvMinima$cv.min$index],col="green")
#for(i in 1:100){
# if(thresholdCVRates$cvm[i] == 0.1250){
# abline(v=i, col="orange", lty=2)
# par(new=TRUE)
# points(i, thresholdCVRates$cvm[i], axes=FALSE, xlab="",ylab="", col="green")
# break
# }
#}
```
###Data Transformation
```{r eval=FALSE}
medianFeatures_trans <- matrix(nrow = 16, ncol = 504)
for(i in 1:504){
m <- min(medianFeatures[,i])
maxi <- max(medianFeatures[,i])
for(j in 1:16){
medianFeatures_trans[j,i] <- 4*((medianFeatures[j,i] - m)/(maxi - m))
}
}
rownames(medianFeatures_trans) <- rownames(medianFeatures)
colnames(medianFeatures_trans) <- colnames(medianFeatures)
```
```{r fig.align='center',fig.cap=capbox2, echo=FALSE, eval=FALSE}
#Box plot for the first 4 features.
list_fea_2 <- modelfeatures$cv.fdr.constrained$features
p_result_2 = vector(mode="numeric", length =length(list_fea_2))
#to determine the order of features, i.e. which is the best, we apply a t test to determine the p value for distributions drawn from the same sample. with this we hope to say something about how good the distributions are seperated
for(i in 1:length(list_fea_2)){
p_result_2[i] = ks.test(medianFeatures_trans[1:8,list_fea_2[i]],
medianFeatures_trans[9:16,list_fea_2[i]])[2]
}
top4_2 = vector(mode="numeric", length=4)
temp_2 = 0
#some weird way to find 4 top features
for(j in 1:4){
#find max in p_result, save it, set to 0, find next
for(i in 1:length(list_fea_2)){
if(p_result_2[[i]] > temp_2)
top4_2[j] = i
temp_2 = p_result_2[i]
}
p_result_2[top4[j]] = 0
}
par(mar=c(2,2,2,2))
par(mfrow=c(2,2))
for(i in top4_2){
boxplot(medianFeatures_trans[1:8,list_fea_2[i]],
medianFeatures_trans[9:16,list_fea_2[i]],
horizontal = TRUE,
names=c('BCR-XL','Reference'),
main = colnames(medianFeatures_trans)[i])
}
```
# References
<file_sep># Statistical-Analysis-UZH-Project
This project aims at reproducing the results of published work by Bruggner et. al. on the topic: Automated identification of stratifying signatures in cellular subpopulations. In this work, they have developed Citrus (Cluster Identification, Characterization, and Regression), which aims to identify stratifying sub-populations in flow cytometry datasets. Citrus is available as a R package.
All the materials used during the course of this project are present in this repository.
The original paper, supplementary information, and the fcs data on which this project has been carried out can be found in 'Paper' folder.
The 'Results' folder contain the .Rmd, .md and the .html files, along with other supporting files. It also contains a .Rdata file from which the results presented in this project have been obtained.
|
93b59bb6ba892da2b8bf53b93a37a8b995bc8c5c
|
[
"Git Attributes",
"Markdown"
] | 3 |
Git Attributes
|
saisomesh2594/Statistical-Analysis-UZH-Project
|
cc27f1ef495b735e2c3f63cded3dd0fe2c885179
|
c342d1a97f994872d4470dd8401e8150176dc31f
|
refs/heads/master
|
<file_sep>module ModelSeedDump
VERSION = '0.1.1'
end
<file_sep>require "model_seed_dump/railtie"
module ModelSeedDump
# Your code goes here...
end
|
025bfa86f44a3cb88229e2f27282fa2e68867234
|
[
"Ruby"
] | 2 |
Ruby
|
coffeemk2/model_seed_dump
|
ff07468d4823efc2c830cfecc2e0272227df71af
|
81588fa6cbf1f83501e994104adb98eac208eb0c
|
refs/heads/main
|
<file_sep># weborama_practice
REPO of daily classes of Weborama
|
04e885949ab2c198ea0c8f1b78323435e2309851
|
[
"Markdown"
] | 1 |
Markdown
|
allenbenny419/weborama_practice
|
00943054404b641cd679e0dab3408ec986915f35
|
e97870dffa1dda81a7c9c0409d017401e87b7697
|
refs/heads/master
|
<file_sep><template>
<footer class="footer-distributed">
<div class="footer-left">
<h3>
<img src="./../../assets/logo.png" class="logo">
</h3>
<p class="footer-links">
<router-link tag="a" to="/" class="link">Home</router-link> ·
<router-link tag="a" to="/search" class="link">Search</router-link> ·
<router-link tag="a" to="/contact" class="link">Contact</router-link>
</p>
<p class="footer-company-name">Book7 © 2019</p>
</div>
<div class="footer-center">
<div>
<font-awesome-icon size="xs" :icon="['fa' , 'map-marker-alt']" class="back-color icons-fab"/>
<p>
<span>Las Palmas</span> Gran Canaria, Spain
</p>
</div>
<div>
<font-awesome-icon :icon="['fa' , 'phone']" class="back-color icons-fab"/>
<p>+34 606 837 831</p>
</div>
<div>
<font-awesome-icon :icon="['fa' , 'envelope']" class="back-color icons-fab"/>
<p>
<a href="mailto:<EMAIL>"><EMAIL></a>
</p>
</div>
</div>
<div class="footer-right">
<p class="footer-company-about">
<span>Trabajo para Gestión del Software I</span>
</p>
<div class="footer-icons">
<a href="https://twitter.com">
<font-awesome-icon :icon="['fab' , 'twitter']" class="icon alt" style="color: #1da1f2"/>
</a>
<a href="https://www.facebook.com">
<font-awesome-icon :icon="['fab' , 'facebook-f']" class="icon alt" style="color: #1877f2"/>
</a>
<a href="https://github.com/Apergot/Book7_GS1">
<font-awesome-icon :icon="['fab' , 'github']" class="icon alt" style="color: #000000"/>
</a>
<a href="https://www.linkedin.com">
<font-awesome-icon :icon="['fab' , 'linkedin']" class="icon alt" style="color: #007bb5" />
</a>
</div>
</div>
</footer>
</template>
<script>
</script>
<style scoped>
.back-color{
color: #3e275b;
}
.logo{
width: 130px;
height: 50px;
}
.footer-distributed {
background-color: #f8f9fa;
box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.12);
box-sizing: border-box;
text-align: left;
font: bold 16px sans-serif;
padding: 55px 50px;
margin-top: 80px;
bottom: 0;
width: 100%;
}
.footer-distributed .footer-left,
.footer-distributed .footer-center,
.footer-distributed .footer-right {
display: inline-block;
vertical-align: top;
}
/* Footer left */
.footer-distributed .footer-left {
width: 40%;
}
.footer-distributed h3 {
font: normal 36px "Cookie", cursive;
margin: 0;
}
.footer-distributed h3 span {
color: #5383d3;
}
.footer-distributed .footer-links {
margin: 20px 0 12px;
padding: 0;
}
.footer-distributed .footer-links a {
display: inline-block;
line-height: 1.8;
text-decoration: none;
color: inherit;
}
.footer-distributed .footer-company-name {
color: #8f9296;
font-size: 14px;
font-weight: normal;
margin: 0;
}
.footer-distributed .footer-center {
width: 35%;
}
.footer-distributed .footer-center .icons-fab {
width: 25px;
height: 25px;
text-align: center;
line-height: 42px;
margin: 10px 15px;
vertical-align: middle;
}
.footer-distributed .footer-center p {
display: inline-block;
vertical-align: middle;
margin: 0;
}
.footer-distributed .footer-center p span {
display: block;
font-weight: normal;
font-size: 14px;
line-height: 2;
}
.footer-distributed .footer-center p a {
color: #5383d3;
text-decoration: none;
}
.footer-distributed .footer-right {
width: 20%;
}
.footer-distributed .footer-company-about {
line-height: 20px;
color: #92999f;
font-size: 13px;
font-weight: normal;
margin: 0;
}
.footer-distributed .footer-company-about span {
display: block;
font-size: 14px;
font-weight: bold;
margin-bottom: 20px;
}
.footer-distributed .footer-icons {
margin-top: 25px;
}
.footer-distributed .footer-icons a{
display: inline-block;
width: 35px;
height: 35px;
cursor: pointer;
background-color: #f8f9fa;
border-radius: 2px;
font-size: 20px;
text-align: center;
line-height: 35px;
margin-right: 3px;
margin-bottom: 5px;
}
@media (max-width: 880px) {
.footer-distributed {
font: bold 14px sans-serif;
}
.footer-distributed .footer-left,
.footer-distributed .footer-center,
.footer-distributed .footer-right {
display: block;
width: 100%;
margin-bottom: 40px;
text-align: center;
}
.footer-distributed .footer-center i {
margin-left: 0;
}
}
</style>
<file_sep><template>
<div>
<b-jumbotron class="jumbotron">
</b-jumbotron>
<b-container v-if="gotResults">
<div>
<h1>The Newest</h1>
<app-book-result :books="freshBooks"></app-book-result>
</div>
<div>
<h1>Juvenile fiction</h1>
<app-book-result :books="juvenileFictionBooks"></app-book-result>
</div>
</b-container>
</div>
</template>
<script>
import BookGroup from '../Components/BookResultsGroup'
export default {
data () {
return {
freshBooks: [],
juvenileFictionBooks: [],
gotResults: false
}
},
methods: {
getFreshBooksPresentation: function () {
this.$http.get(`https://www.googleapis.com/books/v1/volumes?q=-term&orderBy=newest&maxResults=20&key=${process.env.VUE_APP_GOOGLE_BOOKS_API_KEY}`)
.then((data) => {
this.freshBooks = data.body.items
})
.catch(err => {
console.log(err)
})
},
getJuvenileFictionBooks: function () {
this.$http.get(`https://www.googleapis.com/books/v1/volumes?q=subject:"JUVENILE+FICTION"&maxResults=20&key=${process.env.VUE_APP_GOOGLE_BOOKS_API_KEY}`)
.then((data) => {
this.juvenileFictionBooks = data.body.items
})
.catch(err => {
console.log(err)
})
}
},
async created () {
this.getFreshBooksPresentation()
this.getJuvenileFictionBooks()
this.gotResults = true
},
components: {
appBookResult: BookGroup
}
}
</script>
<style scope>
.jumbotron{
background-image: linear-gradient(
rgba(0, 0, 0, 0.3),
rgba(0, 0, 0, 0.1)
),url('./../../assets/bibliotheque.jpg');
background-size: cover;
background-position: center bottom;
background-repeat: no-repeat;
height: 20rem;
}
</style>
<file_sep><template>
<div class="contac-form">
<h3>Contact</h3>
<p>For any questions, suggestions or errors on the web,
You can contact us through the following form:</p>
<b-form @submit="onSubmit" @reset="onReset" v-if="show">
<b-form-group
label="Email address:"
description="We'll never share your email with anyone else."
>
<b-form-input
class="input"
v-model="form.email"
type="email"
required
placeholder="Enter email"
></b-form-input>
</b-form-group>
<b-form-group label="Name:" label-for="input-2">
<b-form-input
class="input"
v-model="form.name"
required
placeholder="Enter name"
></b-form-input>
</b-form-group>
<b-form-group label="Subject:" label-for="input-3">
<b-form-input
class="input"
v-model="form.subject"
required
placeholder="Enter subject"
></b-form-input>
</b-form-group>
<b-form-group label="Message:" label-for="input-4">
<b-col sm="10">
<b-form-textarea
class="textarea-default"
placeholder="Write a message"
></b-form-textarea>
</b-col>
</b-form-group>
<b-form-group>
<b-form-checkbox-group v-model="form.checked" class="checkbox">
<b-form-checkbox value="subscribe">Yes! Send me promotions by email</b-form-checkbox>
</b-form-checkbox-group>
</b-form-group>
<b-form-group>
<b-button type="send" variant="primary" class="submit">Send</b-button>
<b-button type="reset" variant="danger" class="submit">Reset</b-button>
</b-form-group>
</b-form>
</div>
</template>
<script>
export default {
data () {
return {
form: {
email: '',
name: '',
subject: '',
checked: []
},
show: true
}
},
methods: {
onSubmit (evt) {
evt.preventDefault()
alert(JSON.stringify(this.form))
},
onReset (evt) {
evt.preventDefault()
this.form.email = ''
this.form.name = ''
this.form.subject = ''
this.form.checked = []
this.show = false
this.$nextTick(() => {
this.show = true
})
}
}
}
</script>
<style scoped>
@media(min-width: 768px) {
.contac-form{
margin-top: 2%;
width: 40%;
margin-left: 30%;
box-sizing: border-box;
box-shadow: 5px 10px 18px #888888;
border-radius: 5px;
border: 1px solid #c0c2c4;
padding: 10px;
}
.submit{
width: 33%;
}
.input{
width: 100%;
}
.checkbox{
margin: 5% 0;
}
}
@media(min-width: 992px) {
.submit{
display: inline-block;
}
.contac-form{
margin-top: 2%;
width: 40%;
margin-left: 30%;
box-sizing: border-box;
box-shadow: 5px 10px 18px #888888;
border-radius: 5px;
border: 1px solid #c0c2c4;
padding: 10px;
}
}
@media(max-width: 768px) {
.checkbox{
margin: 5% 0;
}
}
</style>
<file_sep><template>
<b-container id="signup" class="signup">
<div class="signup-form">
<b-form @submit.prevent="onSubmit">
<h4 class="logo">Sign Up</h4>
<b-form-group
label="Your email address"
description="We'll never share your email with anyone else"
>
<b-form-input
class="input"
type="email"
id="email"
required
v-model="email"
placeholder="Enter mail"
></b-form-input>
</b-form-group>
<b-form-group
label="Password"
description="You'll need it later to log in"
>
<b-form-input
class="input"
type="password"
id="password"
v-model="password"
placeholder="Enter password"
required
></b-form-input>
</b-form-group>
<b-form-group
label="Confirm password"
description="We need to be sure you got it right!"
>
<b-form-input
class="input"
type="password"
id="confirm-password"
v-model="confirmPassword"
placeholder="Enter your password again"
required
></b-form-input>
</b-form-group>
<b-form inline>
<b-form-select
class="input-inline"
id="country"
v-model="country"
:options="countries">
</b-form-select>
<b-input
placeholder="Your age"
class="input-inline"
type="number"
id="age"
v-model.number="age"
></b-input>
</b-form>
<b-form-checkbox
class="checkbox"
id="terms"
v-model="terms"
>Accept Terms of Use</b-form-checkbox>
<div>
<b-button class="submit" type="submit" color="primary">Submit</b-button>
</div>
</b-form>
</div>
</b-container>
</template>
<script>
export default {
data () {
return {
signup: true,
email: '',
age: null,
password: '',
confirmPassword: '',
country: null,
hobbyInputs: [],
terms: false,
countries: [{ text: 'Select your country', value: null }, 'United States', 'United Kingdom', 'Spain', 'Germany', 'France']
}
},
methods: {
onSubmit () {
const formData = {
email: this.email,
age: this.age,
password: <PASSWORD>,
confirmPassword: <PASSWORD>,
country: this.country,
hobbies: this.hobbyInputs.map(hobby => hobby.value),
terms: this.terms
}
console.log(formData)
this.$store.dispatch('signup', formData)
.then(response => {
this.$store.dispatch('login', { email: formData.email, password: <PASSWORD> })
.then(response => {
if (response.status === 200) {
this.$router.push({ name: 'home' })
}
})
.catch(reject => {
console.log('No se ha podido logear')
})
})
}
}
}
</script>
<style scoped>
@media(min-width: 768px) {
.logo{
text-align: center;
}
.signup-form{
margin-top: 2%;
width: 40%;
margin-left: 30%;
box-sizing: border-box;
box-shadow: 5px 10px 18px #888888;
border-radius: 5px;
border: 1px solid #c0c2c4;
padding: 10px;
}
.submit{
width: 33%;
margin-left: 33%;
}
.input{
width: 100%;
}
.input-inline{
width: 46%;
margin: 0 2%;
}
.checkbox{
margin: 5% 0;
}
}
</style>
<file_sep><template>
<b-container class="container searchcont">
<form @submit.prevent="search">
<b-row>
<b-col md="4"></b-col>
<b-col md="4">
<b-form-input type="text" v-model.trim="searchTerm"></b-form-input>
</b-col>
<b-col md="4">
<b-button variant="outline-primary" type="submit" value="search" id="search" @click="show">Search</b-button>
</b-col>
</b-row>
<b-row>
<b-col md="4"></b-col>
<b-col md="4">
<b-form-radio-group v-model="radio" :options="optciones"></b-form-radio-group>
</b-col>
<b-col md="4"></b-col>
</b-row>
</form>
<hr />
<br />
<div v-if="showbuttons">
<b-button pill variant="outline-primary" class="pageButton" @click="previousPage">Previous Page</b-button>
<b-button pill variant="outline-primary" class="pageButton" @click="nextPage">Next Page</b-button>
</div>
<table class="table table-striped">
<tbody>
<tr v-for="book in searchResults" :key="book.id" @click="pushBookToRouter(book)" class="search-result">
<td v-if="book.volumeInfo !== undefined">
<img
:src="'http://books.google.com/books/content?id=' + book.id + '&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api'"
class="search-result--thumbnail"
/>
</td>
<td>
<div>
<h3>{{ book.volumeInfo.title }}</h3>
<h4 v-if="book.volumeInfo.authors">Por {{ bookAuthors(book) }}</h4>
<p v-if="book.volumeInfo.publishedDate">
<span>Publicado en</span>
{{ book.volumeInfo.publishedDate }}
<span
v-if="book.volumeInfo.publisher"
>por Ed. {{ book.volumeInfo.publisher }}</span>
</p>
<span v-if="book.volumeInfo.categories">Categoria: {{ book.volumeInfo.categories }} </span>
</div>
</td>
<div>
</div>
</tr>
</tbody>
</table>
<div v-if="showbuttons">
<b-button class="pageButton" pill variant="outline-primary" @click="previousPage">Previous Page</b-button>
<b-button class="pageButton" pill variant="outline-primary" @click="nextPage">Next Page</b-button>
</div>
</b-container>
</template>
<script>
export default {
name: 'Form',
data () {
return {
showbuttons: false,
radio: '',
texto: '',
searchTerm: '',
searchResults: [],
comp: 0,
startIndex: 0,
seen: false,
optciones: [
{ value: 'intitle', text: 'Título' },
{ value: 'inauthor', text: 'Autor' },
{ value: 'subject', text: 'Categoría' },
{ value: 'isbn', text: 'ISBN' }
]
}
},
methods: {
search () {
this.$http
.get(
`https://www.googleapis.com/books/v1/volumes?q=${this.radio}:${this.searchTerm}&maxResults=10&startIndex=${this.startIndex}`)
.then(response => {
this.searchResults = response.data.items
this.showbuttons = true
})
.catch(e => {
console.log(e)
})
},
bookAuthors (book) {
let authors = book.volumeInfo.authors
if (authors.length < 3) {
authors = authors.join(' and ')
} else if (authors.length > 2) {
let lastAuthor = ' and ' + authors.slice(-1)
authors.pop()
authors = authors.join(', ')
authors += lastAuthor
}
return authors
},
nextPage () {
this.comp = this.startIndex
if ((this.comp += 10) < 100) {
this.startIndex += 10
this.search()
console.log(this.startIndex)
}
this.comp = 0
},
previousPage () {
this.comp = this.startIndex
if ((this.comp -= 10) >= 0) {
this.startIndex -= 10
this.search()
console.log(this.startIndex)
}
this.comp = 0
},
show () {
if (!this.seen) {
this.seen = !this.seen
}
},
pushBookToRouter: function (book) {
this.$router.push({
name: 'bookpage',
params: {
book
}
})
}
}
}
</script>
<style scope>
.container {
margin-top: 3%;
}
.searchcont {
margin-bottom: 25%;
}
.pageButton {
margin: 1rem;
padding: 1rem;
text-align: center;
margin-right: 10px;
}
.search-result {
cursor: pointer;
}
.review-icon {
size: 10%;
}
</style>
<file_sep><template>
<div>
<b-navbar toggleable="lg" class="navbar">
<router-link to="/" tag="b-navbar-brand">
<img src="../../assets/logo.png" alt="" style="width:100px; height:40px;">
</router-link>
<b-navbar-toggle target="nav-collapse"></b-navbar-toggle>
<b-collapse id="nav-collapse" is-nav>
<!-- Right aligned nav items -->
<b-navbar-nav class="ml-auto">
<router-link tag="b-nav-item" to="/search" class="link">Search</router-link>
<router-link tag="b-nav-item" to="/contact" class="link">Contact</router-link>
<div>
<b-button @click="showModal" v-if="!alreadyLoggedIn" id="show-btn">Sign in</b-button>
<b-button disabled v-else>{{ this.$store.getters.user.email }}</b-button>
</div>
</b-navbar-nav>
</b-collapse>
</b-navbar>
<b-modal
ref="signInModal"
hide-footer
hide-header
centered
hide-backdrop
title="Sign into your account"
@show="resetModal"
@hidden="resetModal"
>
<div class="signin-form">
<b-form @submit.prevent="onSubmitSignIn">
<h2 class="title">Sign in</h2>
<b-form-group class="input">
<p v-if="!correctLogIn" class="incorrect"> Incorrect email/password, try again</p>
<b-form-input
type="email"
id="email"
v-model="email"
placeholder="Email"
required
></b-form-input>
</b-form-group>
<b-form-group class="input">
<b-form-input
type="<PASSWORD>"
id="password"
v-model="password"
placeholder="<PASSWORD>"
required
></b-form-input>
</b-form-group>
<div>
<b-button class="submit" type="submit">Submit</b-button>
</div>
<div @click="hideModal">
<router-link tag="a" to="/signup" class="link">
<p class="signinLink">New user? Sign up to create an account!</p>
</router-link>
</div>
</b-form>
</div>
</b-modal>
</div>
</template>
<script>
export default {
data () {
return {
email: '',
password: '',
correctLogIn: false,
alreadyLoggedIn: false
}
},
methods: {
onSubmitSignIn () {
const formData = {
email: this.email,
password: this.password
}
console.log(formData)
this.$store.dispatch('login', { email: formData.email, password: formData.password })
.then(response => {
if (response.status === 200) {
this.correctLogIn = true
this.$store.dispatch('fetchUser')
this.alreadyLoggedIn = true
this.$refs['signInModal'].hide()
}
})
.catch(reject => {
this.resetModal()
this.correctLogIn = false
})
},
resetModal () {
this.email = ''
this.password = ''
this.correctLogIn = true
},
showModal () {
this.$refs['signInModal'].toggle('#toggle-btn')
},
hideModal () {
this.$refs['signInModal'].hide()
}
}
}
</script>
<style scoped>
.logo{
width: 5%;
height: 5%;
}
.navbar{
background-color: #f8f9fa;
}
.link{
font-weight: 700;
}
.submit{
width: 33%;
margin: 5% 33%;
}
.signinLink{
text-align: center;
}
.incorrect{
color: red;
}
.input{
width: 75%;
margin-left: 12.5%;
}
.title{
margin-bottom: 5%;
text-align: center;
}
</style>
<file_sep><template>
<carousel class="slideshow" :navigationEnabled="true" :mouseDrag="false" :perPageCustom="[[240, 2],[480, 3], [768, 5]]">
<slide v-for="book in books" :key="book.id">
<img @slideclick="handleSlideClick"
@click="pushBookToRouter(book)"
v-if="book.volumeInfo.imageLinks !== undefined"
:src=book.volumeInfo.imageLinks.thumbnail img-alt="Card image"
class="slideshow-item bookimg">
<img @slideclick="handleSlideClick"
@click="pushBookToRouter(book)"
v-else
src="./../../assets/no-img.jpg" img-alt="No image"
class="slideshow-item bookimg">
</slide>
</carousel>
</template>
<script>
export default {
props: ['books'],
methods: {
pushBookToRouter: function (book) {
this.$router.push({
name: 'bookpage',
params: {
book
}
})
},
handleSlideClick: (dataset) => {
console.log(dataset.index, dataset.name)
}
}
}
</script>
<style>
.slideshow {
margin: 3% 2%;
padding: 5px;
}
.VueCarousel-pagination{
margin-top: 0!important;
display: none !important;
}
.VueCarousel-dot--active{
color: #c98261 !important;
}
.slideshow-item{
width: 128px;
border-top-width: 1px;
border-right-width: 1px;
border-bottom-width: 1px;
border-left-width: 1px;
border-top-style: solid;
border-bottom-style: solid;
border-left-style: solid;
border-right-style: solid;
padding: 1px;
min-height: 12rem;
max-height: 12rem;
}
.bookimg {
margin-left: 15%;
cursor: pointer;
}
</style>
<file_sep>import Vue from 'vue'
import Vuex from 'vuex'
import axios from '../axios-auth'
import globalAxios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
idToken: null,
userId: null,
user: null
},
mutations: {
authUser (state, userData) {
state.idToken = userData.token
state.userId = userData.userId
},
storeUser (state, user) {
state.user = user
}
},
actions: {
signup ({ commit, dispatch }, authData) {
axios.post(`/accounts:signUp?key=${process.env.VUE_APP_FIREBASE_API_KEY}`, {
email: authData.email,
password: <PASSWORD>,
returnSecureToken: true
})
.then(res => {
console.log(res)
commit('authUser', {
token: res.data.idToken,
userId: res.data.localId
})
dispatch('storeUser', authData)
})
.catch(error => console.log(error))
},
login ({ commit }, authData) {
return new Promise((resolve, reject) => {
axios.post(`/accounts:signInWithPassword?key=${process.env.VUE_APP_FIREBASE_API_KEY}`, {
email: authData.email,
password: <PASSWORD>,
returnSecureToken: true
})
.then(res => {
console.log('id', res)
commit('authUser', {
token: res.data.idToken,
userId: res.data.localId
})
resolve(res)
})
.catch(error => reject(error))
})
},
storeUser ({ commit, state }, userData) {
if (!state.idToken) {
return
}
globalAxios.post('/users.json' + '?auth=' + state.idToken, userData)
.then(res => console.log(res))
.catch(error => console.log(error))
},
fetchUser ({ commit, state }) {
if (!state.idToken) {
return
}
globalAxios.post(`https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=${process.env.VUE_APP_FIREBASE_API_KEY}`, { idToken: state.idToken })
.then(res => {
console.log(res)
commit('storeUser', res.data.users[0])
})
.catch(error => console.log(error))
}
},
getters: {
user (state) {
return state.user
}
}
})
<file_sep><template>
<b-container class="chat chatcont">
<h2 class="text-primary text-center" style="margin-bottom:3%;">{{ bookTitle }}</h2>
<b-card>
<b-card-text>
<p class="text-secondary nomessages" v-if="messages.length == 0">
[No messages yet!]
</p>
<div class="messages" v-chat-scroll="{ always: false, smooth: true }">
<div v-for="message in messages" :key="message.id">
<span class="text-info">[{{ message.email }}]: </span>
<span>{{ message.message }}</span>
<span class="text-secondary time">{{ message.timestamp }}</span>
</div>
</div>
</b-card-text>
<b-card-footer>
<div class="card-action">
<CreateMessage :propCreated="this.propCreated" />
</div>
</b-card-footer>
</b-card>
</b-container>
</template>
<script>
import CreateMessage from './../Components/CreateMessage'
import fb from './../../firebase/init'
import moment from 'moment'
export default {
name: 'Chat',
props: ['email', 'bookId', 'bookTitle'],
components: {
CreateMessage
},
data () {
return {
propCreated: {
email: `${JSON.stringify(this.email)}`,
bookId: `${JSON.stringify(this.bookId)}`
},
messages: []
}
},
created () {
console.log('Esto es lo que quiero pasar', this.propCreated.bookId, this.propCreated.email)
let ref = fb.collection(`messages${this.propCreated.bookId}`).orderBy('timestamp')
ref.onSnapshot(snapshot => {
snapshot.docChanges().forEach(change => {
if (change.type === 'added') {
let doc = change.doc
this.messages.push({
id: doc.id,
email: doc.data().email,
message: doc.data().message,
timestamp: moment(doc.data().timestamp).format('LTS')
})
}
})
})
}
}
</script>
<style>
.chatcont {
margin-bottom: 20%;
}
.chat h2{
font-size: 2.6em;
margin-bottom: 0px;
}
.chat h5{
margin-top: 0px;
margin-bottom: 40px;
}
.chat span{
font-size: 1.2em;
}
.chat .time{
display: block;
font-size: 0.7em;
}
.messages{
max-height: 300px;
overflow: auto;
}
</style>
<file_sep><template>
<div>
<b-container :data="book" class="bookrescont">
<table id="summary_content_table" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td id="bookinfo">
<h1 class="booktitle"><span class="fn"><span dir="ltr">{{ book.volumeInfo.title }}</span></span><span class="subtitle"></span></h1>
<div class="bookcover"><img class="thumbnail" :src="book.volumeInfo.imageLinks.thumbnail" alt="Front Cover" title="Front Cover" width="128" border="1" id="summary-frontcover"></div>
<div class="bookinfo_sectionwrap">
<div v-for="author in book.volumeInfo.authors" :key="author"><span dir="ltr">{{author}}</span></div>
<div><span v-if="book.volumeInfo.publisher !== undefined" dir="ltr">{{ book.volumeInfo.publisher }}</span>, <span v-if="book.volumeInfo.publishedDate !== undefined" dir="ltr">{{ book.volumeInfo.publishedDate }}</span> - <span dir="ltr">{{ book.volumeInfo.categories[0] }}</span> - <span dir="ltr">{{ book.volumeInfo.pageCount }} pages</span></div>
<div class="reviewaggregate hreview-aggregate"><a href="https://books.google.es/books?id=nqRlPwAACAAJ&dq=inauthor:%22J.K.+Rowling%22&sitesec=reviews" aria-label="Average user rating - 18820 stars"><span class="gb-star-on goog-inline-block rating"><span class="value-title" title="4.0"></span></span><span class="gb-star-on goog-inline-block"></span><span class="gb-star-on goog-inline-block"></span><span class="gb-star-on goog-inline-block"></span><span class="gb-star-off goog-inline-block"></span></a> <span class="num-ratings"><a href="https://books.google.es/books?id=nqRlPwAACAAJ&dq=inauthor:%22J.K.+Rowling%22&sitesec=reviews" class="sbs-count secondary"><span class="count"></span></a>
</span>
</div>
</div>
<div id="synopsis">
<div id="synopsis-window" style="height: 5.85em; overflow: hidden;">
<div v-if="book.volumeInfo.description !== undefined" id="synopsistext" dir="ltr" class="sa">{{ book.volumeInfo.description }}</div>
</div><a class="secondary" style="cursor: pointer; padding-top: 6px;"></a></div>
<div class="search_box_wrapper">
<b-button @click="joinBookChat" :disabled="loggedUser" style="rigth:10px;" v-b-tooltip.hover.right title="You need to log in!">Join Book Chat</b-button>
</div>
</td>
</tr>
</tbody>
</table>
</b-container>
</div>
</template>
<script>
export default {
props: ['book'],
data () {
return {
loggedUser: false
}
},
computed: {
email () {
return !this.$store.getters.user ? false : this.$store.getters.user.email
}
},
created () {
this.$store.dispatch('fetchUser')
},
methods: {
joinBookChat () {
if (this.$store.getters.user) {
this.loggedUser = true
this.$router.push({ name: 'chat', params: { email: this.$store.getters.user.email, bookId: this.book.id, bookTitle: this.book.volumeInfo.title } })
}
}
}
}
</script>
<style>
#volume-main {
position: relative;
line-height: 1.2em;
clear: both;
border-top: 1px solid #ebebeb
}
.bookrescont {
margin-bottom: 20%;
}
table {
display: table;
border-collapse: separate;
border-color: grey;
border-style:none;
margin:0;
border-spacing: 2px;
}
tbody {
display: table-row-group;
vertical-align: middle;
border-color: inherit;
}
tr {
display: table-row;
vertical-align: inherit;
border-color: inherit;
}
td {
display: table-cell;
}
#bookinfo {
vertical-align: top;
}
h1 {
display: block;
font-size: 2em;
margin-block-start: 0.67em;
margin-block-end: 0.67em;
margin-inline-start: 0px;
margin-inline-end: 0px;
font-weight: bold;
}
.booktitle{
margin-top: 0;
margin-bottom: 21px;
}
.booktitle .subtitle {
font-size: 60%;
font-weight: normal;
}
div {
display: block;
}
.bookcover {
float: left;
margin-right: 12px;
}
.thumbnail {
width: 128px;
border-top-width: 1px;
border-right-width: 1px;
border-bottom-width: 1px;
border-left-width: 1px;
border-top-style: solid;
border-bottom-style: solid;
border-left-style: solid;
border-right-style: solid;
}
.bookcover img {
padding: 1px;
}
</style>
<file_sep><template>
<div id="app">
<app-header></app-header>
<transition name="slide" mode="out-in">
<router-view></router-view>
</transition>
<app-footer></app-footer>
</div>
</template>
<script>
import Header from './views/Components/Header'
import Footer from './views/Components/Footer'
export default {
components: {
appHeader: Header,
appFooter: Footer
}
}
</script>
<style>
body {
height: 100%;
min-height: 100%;
padding: 0;
margin: 0;
}
body::after {
content: '';
display: block;
height: 100%;
}
.slide-enter-active{
animation: slide-in 350ms ease-out forwards;
}
.slide-leave-active{
animation: slide-out 350ms ease-out forwards;
}
@keyframes slide-in {
from{
transform: translateY(-30px);
opacity: 0;
}
to{
transform: translateY(0);
opacity: 1;
}
}
@keyframes slide-out {
from{
transform: translateY(0);
opacity: 1;
}
to{
transform: translateY(-30px);
opacity: 0;
}
}
</style>
|
acd08df55209675824eda2a094ff0f564465d5dc
|
[
"Vue",
"JavaScript"
] | 11 |
Vue
|
Apergot/Book7_GS1
|
a8bd3df777a711cf1d742c1e184aa1684d583399
|
6035d775bdaeb10b1cb52318b220dd10c5784dc8
|
refs/heads/master
|
<file_sep>import sys
import socket
SSDP_ADDR = "192.168.127.12";
SSDP_PORT = 1900;
SSDP_MX = 1;
SSDP_ST = "urn:schemas-sony-com:service:ScalarWebAPI:1";
NT: urn:schemas-sony-com:service:ScalarWebAPI:1
SSDP_ST = "";
ssdpRequest = "M-SEARCH * HTTP/1.1\r\n" + \
"HOST: %s:%d\r\n" % (SSDP_ADDR, SSDP_PORT) + \
"MAN: \"ssdp:discover\"\r\n" + \
"MX: %d\r\n" % (SSDP_MX, ) + \
"ST: %s\r\n" % (SSDP_ST, ) + "\r\n";
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(ssdpRequest, (SSDP_ADDR, SSDP_PORT))
print "hello"
print sock.recv(1000)
|
ce65d8fd1f74aaf8c0de18671c6134a4f43157d4
|
[
"Python"
] | 1 |
Python
|
chalstrick/sony-api
|
440f96aa58826ae829db00346849c327937722be
|
493dc72d12c518cd675e114147eeb354d79d8a89
|
refs/heads/master
|
<file_sep>using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Common;
using System.Configuration;
using Microsoft.TeamFoundation.Server;
namespace TfsSdk_ConnectToTfsProgrammatically
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static readonly string MyUri = ConfigurationManager.AppSettings["TfsUri"];
private static TfsTeamProjectCollection _tfs;
private static ProjectInfo _selectedTeamProject;
private void InteractiveConnectToTfsClick(object sender, EventArgs e)
{
lblNotes.Text = string.Empty;
try
{
var notes = new StringBuilder();
var tfsPp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false);
tfsPp.ShowDialog();
_tfs = tfsPp.SelectedTeamProjectCollection;
if (tfsPp.SelectedProjects.Any())
{
_selectedTeamProject = tfsPp.SelectedProjects[0];
}
notes.AppendFormat("{0} Team Project : {1} - {2}{0}", Environment.NewLine, _selectedTeamProject.Name, _selectedTeamProject.Uri);
lblNotes.Text = notes.ToString();
}
catch (Exception ex)
{
lblError.Text = " Message : " + ex.Message +
(ex.InnerException != null ? " Inner Exception : " + ex.InnerException : string.Empty);
}
}
private void UnInteractiveConnectToTfsClick(object sender, EventArgs e)
{
lblNotes.Text = string.Empty;
try
{
var notes = new StringBuilder();
var configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(MyUri));
var catalogNode = configurationServer.CatalogNode;
var tpcNodes = catalogNode.QueryChildren(
new Guid[] { CatalogResourceTypes.ProjectCollection },
false, CatalogQueryOptions.None);
foreach (var tpcNode in tpcNodes)
{
var tpcId = new Guid(tpcNode.Resource.Properties["InstanceId"]);
TfsTeamProjectCollection tpc = configurationServer.GetTeamProjectCollection(tpcId);
notes.AppendFormat("{0} Team Project Collection : {1}{0}", Environment.NewLine, tpc.Name);
var tpNodes = tpcNode.QueryChildren(
new Guid[] { CatalogResourceTypes.TeamProject },
false, CatalogQueryOptions.None);
foreach (var p in tpNodes)
{
notes.AppendFormat("{0} Team Project : {1} - {2}{0}", Environment.NewLine,
p.Resource.DisplayName, p.Resource.Description);
}
}
lblNotes.Text = notes.ToString();
}
catch (Exception ex)
{
lblError.Text = " Message : " + ex.Message +
(ex.InnerException != null ? " Inner Exception : " + ex.InnerException : string.Empty);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
|
459af9575f62fcf4ca72ab874dce3f2206572148
|
[
"C#"
] | 1 |
C#
|
MarwanELAdawy/Connect-To-TFS-Programmatically
|
408da205f450b38927c0907ee6312702e2509ade
|
fc14889348afc5e10d0179b6a0f4d679fdd51e0e
|
refs/heads/master
|
<repo_name>pjrt/PlayUnusedImports<file_sep>/build.sbt
lazy val root = (project in file(".")).enablePlugins(PlayScala).settings(
scalaVersion := "2.11.4",
scalacOptions in Compile ++= Seq("-Ywarn-unused-import")
)
<file_sep>/app/controllers/Application.scala
package controllers
import play.api.mvc._
object Application extends Controller {
def ping = Action (_ => Ok("pong"))
}
|
3eb3782bc0ca055373554da28fd30585f0993225
|
[
"Scala"
] | 2 |
Scala
|
pjrt/PlayUnusedImports
|
27edfaf7bbda0598cbe72fc5e9de08bf8127009d
|
505e60527ce5dbdf9d9c2237814203abf8d86445
|
refs/heads/main
|
<repo_name>henk23/nuxt-double-slash-bug<file_sep>/server-middleware/my-server-middleware.js
export default function (req, res, next) {
console.log('my-server-middleware', req.url);
// "Bug" can be fixed by handling double slashes explicitly in this middleware
// const new_url = req.url.replace('//', '/');
//
// if(req.url !== new_url) {
// res.writeHead(301, {
// 'Location': new_url,
// });
// res.end();
// return;
// }
next();
}
<file_sep>/middleware/my-middleware.js
export default function ({ route }) {
console.log('my-middleware', route);
return null;
}
|
18f641e1e746b71506b33e8b6eb74096a86a8105
|
[
"JavaScript"
] | 2 |
JavaScript
|
henk23/nuxt-double-slash-bug
|
2c158483ccfe5a5025b0a0d26f4301170a18c27e
|
5f2c57af052146c242f328a3f1921f7f4f31a1ad
|
refs/heads/master
|
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>TestNG Report</title><style type="text/css">table {margin-bottom:10px;border-collapse:collapse;empty-cells:show}th,td {border:1px solid #009;padding:.25em .5em}th {vertical-align:bottom}td {vertical-align:top}table a {font-weight:bold}.stripe td {background-color: #E6EBF9}.num {text-align:right}.passedodd td {background-color: #3F3}.passedeven td {background-color: #0A0}.skippedodd td {background-color: #DDD}.skippedeven td {background-color: #CCC}.failedodd td,.attn {background-color: #F33}.failedeven td,.stripe .attn {background-color: #D00}.stacktrace {white-space:pre;font-family:monospace}.totop {font-size:85%;text-align:center;border-bottom:2px solid #000}</style></head><body><table><tr><th>Test</th><th># Passed</th><th># Skipped</th><th># Failed</th><th>Time (ms)</th><th>Included Groups</th><th>Excluded Groups</th></tr><tr><th colspan="7">Enrollement_Page_Validation_TestSuite</th></tr><tr><td><a href="#t0">Enrollement_Page_Validation_Testcases</a></td><td class="num">17</td><td class="num">0</td><td class="num">0</td><td class="num">616,292</td><td></td><td></td></tr><tr><th colspan="7">MJN_Enfamil_CA_English_Enrollement_Regression_TestSuite</th></tr><tr><th colspan="7">Enrollement_Submission_TestSuite</th></tr><tr class="stripe"><td><a href="#t1">Enrollement_Submission_Testcases</a></td><td class="num">2</td><td class="num">0</td><td class="num">0</td><td class="num">144,301</td><td>StabilityTest</td><td></td></tr><tr><th>Total</th><th class="num">19</th><th class="num">0</th><th class="num">0</th><th class="num">760,593</th><th colspan="2"></th></tr></table><table><thead><tr><th>Class</th><th>Method</th><th>Start</th><th>Time (ms)</th></tr></thead><tbody><tr><th colspan="4">Enrollement_Page_Validation_TestSuite</th></tr></tbody><tbody id="t0"><tr><th colspan="4">Enrollement_Page_Validation_Testcases — passed</th></tr><tr class="passedeven"><td rowspan="17">testcases.EnrollementPageValidationTest</td><td><a href="#m0">EFB001_validateRedirectedToEnrollmentPage</a></td><td rowspan="1">1485778519360</td><td rowspan="1">35409</td></tr><tr class="passedeven"><td><a href="#m1">EFB002_validateFullWidthBannerContentInEFBForm</a></td><td rowspan="1">1485778554772</td><td rowspan="1">2737</td></tr><tr class="passedeven"><td><a href="#m2">EFB003_validateSocialRegistrationFunctionalityAtEFBForm</a></td><td rowspan="1">1485778557511</td><td rowspan="1">37437</td></tr><tr class="passedeven"><td><a href="#m3">EFB004_validateTabFunctionalityAtEFBForm</a></td><td rowspan="1">1485778594958</td><td rowspan="1">4390</td></tr><tr class="passedeven"><td><a href="#m4">EFB005_verifyErrorMessagesForRequiredFieldsAtEFBForm</a></td><td rowspan="1">1485778599349</td><td rowspan="1">59240</td></tr><tr class="passedeven"><td><a href="#m5">EFB006_verifyFirstNameFieldValidationAtEFBForm</a></td><td rowspan="1">1485778658592</td><td rowspan="1">91791</td></tr><tr class="passedeven"><td><a href="#m6">EFB007_verifyLastNameFieldValidationAtEFBForm</a></td><td rowspan="1">1485778750384</td><td rowspan="1">21173</td></tr><tr class="passedeven"><td><a href="#m7">EFB008_verifyEmailAddressFieldValidationAtEFBForm</a></td><td rowspan="1">1485778771559</td><td rowspan="1">34083</td></tr><tr class="passedeven"><td><a href="#m8">EFB009_verifyPasswordFieldValidationAtEFBForm</a></td><td rowspan="1">1485778805644</td><td rowspan="1">103643</td></tr><tr class="passedeven"><td><a href="#m9">EFB010_verifyBabysDueDateOrBirthDateValidationAtEFBForm</a></td><td rowspan="1">1485778909289</td><td rowspan="1">48386</td></tr><tr class="passedeven"><td><a href="#m10">EFB011_verifyStreetAddressFieldValidationAtEFBForm</a></td><td rowspan="1">1485778957678</td><td rowspan="1">17258</td></tr><tr class="passedeven"><td><a href="#m11">EFB012_verifyCityFieldValidationAtEFBForm</a></td><td rowspan="1">1485778974937</td><td rowspan="1">13839</td></tr><tr class="passedeven"><td><a href="#m12">EFB013_verifyProvinceFieldValidationAtEFBForm</a></td><td rowspan="1">1485778988778</td><td rowspan="1">19471</td></tr><tr class="passedeven"><td><a href="#m13">EFB014_verifyPostalCodeFieldValidationAtEFBForm</a></td><td rowspan="1">1485779008250</td><td rowspan="1">47372</td></tr><tr class="passedeven"><td><a href="#m14">EFB015_verifyTelephoneFieldValidationAtEFBForm</a></td><td rowspan="1">1485779055624</td><td rowspan="1">22060</td></tr><tr class="passedeven"><td><a href="#m15">EFB016_verifyDeliveryPackageTypeAtEFBForm</a></td><td rowspan="1">1485779077686</td><td rowspan="1">32571</td></tr><tr class="passedeven"><td><a href="#m16">EFB017_verifyLeavePopupMessageWindowFunctionalityAtEFBForm</a></td><td rowspan="1">1485779110258</td><td rowspan="1">25358</td></tr></tbody><tbody><tr><th colspan="4">MJN_Enfamil_CA_English_Enrollement_Regression_TestSuite</th></tr></tbody><tbody><tr><th colspan="4">Enrollement_Submission_TestSuite</th></tr></tbody><tbody id="t1"><tr><th colspan="4">Enrollement_Submission_Testcases — passed</th></tr><tr class="passedeven"><td rowspan="2">testcases.EnrollementSubmissionTest</td><td><a href="#m17">EFB017_verifyEnrollementFunctionalityWithEcoFriendlyDeliveryOptionAtEFBForm</a></td><td rowspan="1">1485779141809</td><td rowspan="1">94143</td></tr><tr class="passedeven"><td><a href="#m18">EFB018_verifyEnrollementFunctionalityWithRegularMailOptionAtEFBForm</a></td><td rowspan="1">1485779236018</td><td rowspan="1">49217</td></tr></tbody></table><h2>Enrollement_Page_Validation_Testcases</h2><h3 id="m0">testcases.EnrollementPageValidationTest#EFB001_validateRedirectedToEnrollmentPage</h3><table class="result"></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m1">testcases.EnrollementPageValidationTest#EFB002_validateFullWidthBannerContentInEFBForm</h3><table class="result"></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m2">testcases.EnrollementPageValidationTest#EFB003_validateSocialRegistrationFunctionalityAtEFBForm</h3><table class="result"></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m3">testcases.EnrollementPageValidationTest#EFB004_validateTabFunctionalityAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th></tr><tr class="param stripe"><td>Karthikeyan</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m4">testcases.EnrollementPageValidationTest#EFB005_verifyErrorMessagesForRequiredFieldsAtEFBForm</h3><table class="result"></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m5">testcases.EnrollementPageValidationTest#EFB006_verifyFirstNameFieldValidationAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th><th>Parameter #4</th><th>Parameter #5</th><th>Parameter #6</th><th>Parameter #7</th><th>Parameter #8</th><th>Parameter #9</th><th>Parameter #10</th><th>Parameter #11</th><th>Parameter #12</th></tr><tr class="param stripe"><td>Karthikeyan</td><td>Rajendran</td><td><EMAIL></td><td>Ameexusa@2016</td><td>Feb</td><td>3</td><td>2016</td><td>1353 Queen Street West</td><td>Toronto</td><td>M6K</td><td>1M1</td><td>Ontario</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m6">testcases.EnrollementPageValidationTest#EFB007_verifyLastNameFieldValidationAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th></tr><tr class="param stripe"><td>Rajendran</td><td>Ameexusa@2016</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m7">testcases.EnrollementPageValidationTest#EFB008_verifyEmailAddressFieldValidationAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th><th>Parameter #4</th></tr><tr class="param stripe"><td><EMAIL></td><td>Ameexusa@2016</td><td><EMAIL></td><td>karthi89.infotech</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m8">testcases.EnrollementPageValidationTest#EFB009_verifyPasswordFieldValidationAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th><th>Parameter #4</th><th>Parameter #5</th><th>Parameter #6</th></tr><tr class="param stripe"><td>test</td><td>Ameexusa@2016</td><td>123</td><td>ABCDEF</td><td>abcdefg</td><td><EMAIL></td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m9">testcases.EnrollementPageValidationTest#EFB010_verifyBabysDueDateOrBirthDateValidationAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th><th>Parameter #4</th><th>Parameter #5</th><th>Parameter #6</th><th>Parameter #7</th><th>Parameter #8</th><th>Parameter #9</th><th>Parameter #10</th><th>Parameter #11</th><th>Parameter #12</th><th>Parameter #13</th><th>Parameter #14</th></tr><tr class="param stripe"><td>Karthikeyan</td><td>Rajendran</td><td><EMAIL></td><td>Ameexusa@2016</td><td>Feb</td><td>3</td><td>2016</td><td>1353 Queen Street West</td><td>Toronto</td><td>M6K</td><td>1M1</td><td>Month</td><td>Date</td><td>Year</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m10">testcases.EnrollementPageValidationTest#EFB011_verifyStreetAddressFieldValidationAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th></tr><tr class="param stripe"><td>Ameexusa@2016</td><td>1353 Queen Street West</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m11">testcases.EnrollementPageValidationTest#EFB012_verifyCityFieldValidationAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th></tr><tr class="param stripe"><td>9500433156</td><td>Toronto</td><td>Ameexusa@2016</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m12">testcases.EnrollementPageValidationTest#EFB013_verifyProvinceFieldValidationAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th></tr><tr class="param stripe"><td>Ameexusa@2016</td><td>Ontario</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m13">testcases.EnrollementPageValidationTest#EFB014_verifyPostalCodeFieldValidationAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th><th>Parameter #4</th><th>Parameter #5</th></tr><tr class="param stripe"><td>9500433156</td><td>123</td><td>M6K</td><td>Ameexusa@2016</td><td>1M1</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m14">testcases.EnrollementPageValidationTest#EFB015_verifyTelephoneFieldValidationAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th><th>Parameter #4</th><th>Parameter #5</th></tr><tr class="param stripe"><td>abcdefghij</td><td>1M1</td><td>Ameexusa@2016</td><td>012345678</td><td>9500433156</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m15">testcases.EnrollementPageValidationTest#EFB016_verifyDeliveryPackageTypeAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th><th>Parameter #4</th><th>Parameter #5</th><th>Parameter #6</th><th>Parameter #7</th><th>Parameter #8</th><th>Parameter #9</th><th>Parameter #10</th><th>Parameter #11</th><th>Parameter #12</th></tr><tr class="param stripe"><td>Karthikeyan</td><td>Rajendran</td><td><EMAIL></td><td>Ameexusa@2016</td><td>Feb</td><td>3</td><td>2016</td><td>1353 Queen Street West</td><td>Toronto</td><td>M6K</td><td>1M1</td><td>Ontario</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m16">testcases.EnrollementPageValidationTest#EFB017_verifyLeavePopupMessageWindowFunctionalityAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th></tr><tr class="param stripe"><td>Karthikeyan</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h2>Enrollement_Submission_Testcases</h2><h3 id="m17">testcases.EnrollementSubmissionTest#EFB017_verifyEnrollementFunctionalityWithEcoFriendlyDeliveryOptionAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th><th>Parameter #4</th><th>Parameter #5</th><th>Parameter #6</th><th>Parameter #7</th><th>Parameter #8</th><th>Parameter #9</th></tr><tr class="param stripe"><td>Karthikeyan</td><td>Rajendran</td><td>ame<EMAIL>automationteam+<EMAIL></td><td>Ameexusa@2016</td><td>Jan</td><td>1</td><td>2015</td><td>No</td><td>1353 Queen Street West</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p><h3 id="m18">testcases.EnrollementSubmissionTest#EFB018_verifyEnrollementFunctionalityWithRegularMailOptionAtEFBForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th><th>Parameter #4</th><th>Parameter #5</th><th>Parameter #6</th><th>Parameter #7</th><th>Parameter #8</th><th>Parameter #9</th></tr><tr class="param stripe"><td>Karthikeyan</td><td>Rajendran</td><td><EMAIL>automation<EMAIL></td><td>Ameexusa@2016</td><td>Jan</td><td>1</td><td>2015</td><td>No</td><td>1353 Queen Street West</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p></body></html>
|
f40d621cb2cf4aa449d5284588097d94baa9ca86
|
[
"HTML"
] | 1 |
HTML
|
rajeshamx/MJN_Enfamil_CA_QA_Automation_Report
|
9b112ef2289162eb8e00f82bd62c6946a717cc3f
|
de68b4de67fce23fa31cb746369d0f3e1d8a5bf7
|
refs/heads/master
|
<file_sep>package com.richardevaristo.springJpaTest.OneToOne.dao;
import com.richardevaristo.springJpaTest.OneToOne.model.Profile;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProfileRepository extends JpaRepository<Profile, Integer> {
Profile findProfileById(int id);
Profile findProfileByUserId(int id);
Boolean existsByUserId(int id);
}
<file_sep>package com.richardevaristo.springJpaTest.OneToOne.service;
import com.richardevaristo.springJpaTest.OneToOne.dao.ProfileRepository;
import com.richardevaristo.springJpaTest.OneToOne.message.request.UserProfileRequest;
import com.richardevaristo.springJpaTest.OneToOne.model.Profile;
import com.richardevaristo.springJpaTest.OneToOne.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
@Service
public class ProfileService {
@Autowired
ProfileRepository profileRepository;
public List<Profile> getAllUserProfiles() {
return profileRepository.findAll();
}
public Profile getProfile(int id) {
return profileRepository.findProfileById(id);
}
public Profile getProfileByUserId(int id) {
return profileRepository.findProfileByUserId(id);
}
public Profile updateProfileByUserId(int id, UserProfileRequest request) {
Profile profile = getProfileByUserId(id);
User user = profile.getUser();
user.setFirstName(request.getFirstName())
.setLastName(request.getLastName())
.setEmail(request.getEmail());
profile.setAge(request.getAge())
.setGender(request.getGender())
.setAddress(request.getAddress());
profile.setUser(user);
return profileRepository.save(profile);
}
public String deleteUserProfileById(@PathVariable int id) {
if(profileRepository.existsByUserId(id)) {
profileRepository.deleteById(id);
return "User Deleted!";
}
return "Error processing request -> User does not exist";
}
public Profile createUserProfile(UserProfileRequest request) {
User user = new User();
user.setFirstName(request.getFirstName())
.setLastName(request.getLastName())
.setEmail(request.getEmail());
Profile profile = new Profile();
profile.setAge(request.getAge())
.setGender(request.getGender())
.setAddress(request.getAddress());
profile.setUser(user);
return profileRepository.save(profile);
}
}
<file_sep>package com.richardevaristo.springJpaTest.OneToMany.controller;
import com.richardevaristo.springJpaTest.OneToMany.message.request.BookRequest;
import com.richardevaristo.springJpaTest.OneToMany.model.Book;
import com.richardevaristo.springJpaTest.OneToMany.model.Category;
import com.richardevaristo.springJpaTest.OneToMany.service.BookService;
import com.richardevaristo.springJpaTest.OneToMany.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api")
public class BookController {
@Autowired
BookService bookService;
@Autowired
CategoryService categoryService;
@GetMapping("/books")
public List<Book> getAllBooks() {
return bookService.getAllBooks();
}
@GetMapping("/categories")
public List<Category> getAllCategory() {
return categoryService.getAllCategory();
}
@GetMapping("/books/{id}")
public Book getBookById(@PathVariable int id) {
return bookService.getBookById(id);
}
@GetMapping("/categories/{id}")
public Category getCategoryById(@PathVariable int id) {
return categoryService.getCategoryById(id);
}
@PostMapping("/books/add")
public Book createBook(@RequestBody BookRequest request) {
return null;
}
}
|
4c5572fbce2e79e04c9e91a1e4e00640bad1586f
|
[
"Java"
] | 3 |
Java
|
richardevaristo/jsb-relationships-demo
|
2093699defb85519fe60974a588f32118d5217cc
|
48bc68a87600d071e8933d4ba04d43f9ef0c9e99
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.