branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/main
|
<repo_name>Ashokskhot/react-redux-example<file_sep>/src/redux/counter/increment-counter-action.js
import { createAction } from "redux-actions";
export const IncrementCounterRdxConst = "Counter/IncrementCounter";
export const IncrementCounterAction = createAction(
IncrementCounterRdxConst,
(payload) => payload
);
export const IncrementCounterReducer = (state, action) => {
return state + 1;
};
<file_sep>/src/redux/counter/decrement-counter-action.js
import { createAction } from "redux-actions";
export const DecrementCounterRdxConst = "Counter/DecrementCounter";
export const DecrementCounterAction = createAction(DecrementCounterRdxConst);
export const DecrementCounterReducer = (state, action) => {
return state - 1;
};
<file_sep>/README.md
# react-redux-example
Created with CodeSandbox
|
898617f81af08a35348893c5981e4cd065cc5573
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
Ashokskhot/react-redux-example
|
eda5699628733a19f9f680944a325b6371ddbfce
|
5541040fe843199bdda918c0fb4cb6873d71f0cd
|
refs/heads/master
|
<file_sep>local verse = require "verse";
local uuid = require "util.uuid".generate;
local xmlns_auth = "jabber:iq:auth";
function verse.plugins.legacy(stream)
local function handle_auth_form(result)
local query = result:get_child("query", xmlns_auth);
if result.attr.type ~= "result" or not query then
local type, cond, text = result:get_error();
stream:debug("warn", "%s %s: %s", type, cond, text);
--stream:event("authentication-failure", { condition = cond });
-- COMPAT continue anyways
end
local auth_data = {
username = stream.username;
password = <PASSWORD>;
resource = stream.resource or uuid();
digest = false, sequence = false, token = false;
};
local request = verse.iq({ to = stream.host, type = "set" })
:tag("query", { xmlns = xmlns_auth });
if #query > 0 then
for tag in query:childtags() do
local field = tag.name;
local value = auth_data[field];
if value then
request:tag(field):text(auth_data[field]):up();
elseif value == nil then
local cond = "feature-not-implemented";
stream:event("authentication-failure", { condition = cond });
return false;
end
end
else -- COMPAT for servers not following XEP 78
for field, value in pairs(auth_data) do
if value then
request:tag(field):text(value):up();
end
end
end
stream:send_iq(request, function (response)
if response.attr.type == "result" then
stream.resource = auth_data.resource;
stream.jid = auth_data.username.."@"..stream.host.."/"..auth_data.resource;
stream:event("authentication-success");
stream:event("bind-success", stream.jid);
else
local type, cond, text = response:get_error();
stream:event("authentication-failure", { condition = cond });
end
end);
end
local function handle_opened(attr)
if not attr.version then
stream:send_iq(verse.iq({type="get"})
:tag("query", { xmlns = "jabber:iq:auth" })
:tag("username"):text(stream.username),
handle_auth_form);
end
end
stream:hook("opened", handle_opened);
end
<file_sep>local function not_impl()
error("Function not implemented");
end
local mime = require "mime";
module "encodings"
stringprep = {};
base64 = { encode = mime.b64, decode = mime.unb64 };
return _M;
<file_sep>local verse = require "verse";
local xmlns_blocking = "urn:xmpp:blocking";
function verse.plugins.blocking(stream)
-- FIXME: Disco
stream.blocking = {};
function stream.blocking:block_jid(jid, callback)
stream:send_iq(verse.iq{type="set"}
:tag("block", { xmlns = xmlns_blocking })
:tag("item", { jid = jid })
, function () return callback and callback(true); end
, function () return callback and callback(false); end
);
end
function stream.blocking:unblock_jid(jid, callback)
stream:send_iq(verse.iq{type="set"}
:tag("unblock", { xmlns = xmlns_blocking })
:tag("item", { jid = jid })
, function () return callback and callback(true); end
, function () return callback and callback(false); end
);
end
function stream.blocking:unblock_all_jids(callback)
stream:send_iq(verse.iq{type="set"}
:tag("unblock", { xmlns = xmlns_blocking })
, function () return callback and callback(true); end
, function () return callback and callback(false); end
);
end
function stream.blocking:get_blocked_jids(callback)
stream:send_iq(verse.iq{type="get"}
:tag("blocklist", { xmlns = xmlns_blocking })
, function (result)
local list = result:get_child("blocklist", xmlns_blocking);
if not list then return callback and callback(false); end
local jids = {};
for item in list:childtags() do
jids[#jids+1] = item.attr.jid;
end
return callback and callback(jids);
end
, function (result) return callback and callback(false); end
);
end
end
<file_sep>local stanza_mt = getmetatable(require "util.stanza".stanza());
local xmlns_stanzas = "urn:ietf:params:xml:ns:xmpp-stanzas";
function stanza_mt:get_error()
local type, condition, text;
local error_tag = self:get_child("error");
if not error_tag then
return nil, nil;
end
type = error_tag.attr.type;
for child in error_tag:children() do
if child.attr.xmlns == xmlns_stanzas then
if child.name == "text" then
text = child:get_text();
else
condition = child.name;
end
if condition and text then
break;
end
end
end
return type, condition, text;
end
<file_sep>local verse = require "verse";
local jid = require "util.jid";
local xmlns_bind = "urn:ietf:params:xml:ns:xmpp-bind";
function verse.plugins.bind(stream)
local function handle_features(features)
if stream.bound then return; end
stream:debug("Binding resource...");
stream:send_iq(verse.iq({ type = "set" }):tag("bind", {xmlns=xmlns_bind}):tag("resource"):text(stream.resource),
function (reply)
if reply.attr.type == "result" then
local result_jid = reply
:get_child("bind", xmlns_bind)
:get_child_text("jid");
stream.username, stream.host, stream.resource = jid.split(result_jid);
stream.jid, stream.bound = result_jid, true;
stream:event("bind-success", { jid = result_jid });
elseif reply.attr.type == "error" then
local err = reply:child_with_name("error");
local type, condition, text = reply:get_error();
stream:event("bind-failure", { error = condition, text = text, type = type });
end
end);
end
stream:hook("stream-features", handle_features, 200);
return true;
end
<file_sep>local verse = require "verse";
local adhoc = require "lib.adhoc";
local xmlns_commands = "http://jabber.org/protocol/commands";
local xmlns_data = "jabber:x:data";
local command_mt = {};
command_mt.__index = command_mt;
-- Table of commands we provide
local commands = {};
function verse.plugins.adhoc(stream)
stream:add_plugin("disco");
stream:add_disco_feature(xmlns_commands);
function stream:query_commands(jid, callback)
stream:disco_items(jid, xmlns_commands, function (items)
stream:debug("adhoc list returned")
local command_list = {};
for _, item in ipairs(items) do
command_list[item.node] = item.name;
end
stream:debug("adhoc calling callback")
return callback(command_list);
end);
end
function stream:execute_command(jid, command, callback)
local cmd = setmetatable({
stream = stream, jid = jid,
command = command, callback = callback
}, command_mt);
return cmd:execute();
end
-- ACL checker for commands we provide
local function has_affiliation(jid, aff)
if not(aff) or aff == "user" then return true; end
if type(aff) == "function" then
return aff(jid);
end
-- TODO: Support 'roster', etc.
end
function stream:add_adhoc_command(name, node, handler, permission)
commands[node] = adhoc.new(name, node, handler, permission);
stream:add_disco_item({ jid = stream.jid, node = node, name = name }, xmlns_commands);
return commands[node];
end
local function handle_command(stanza)
local command_tag = stanza.tags[1];
local node = command_tag.attr.node;
local handler = commands[node];
if not handler then return; end
if not has_affiliation(stanza.attr.from, handler.permission) then
stream:send(verse.error_reply(stanza, "auth", "forbidden", "You don't have permission to execute this command"):up()
:add_child(handler:cmdtag("canceled")
:tag("note", {type="error"}):text("You don't have permission to execute this command")));
return true
end
-- User has permission now execute the command
return adhoc.handle_cmd(handler, { send = function (d) return stream:send(d) end }, stanza);
end
stream:hook("iq/"..xmlns_commands, function (stanza)
local type = stanza.attr.type;
local name = stanza.tags[1].name;
if type == "set" and name == "command" then
return handle_command(stanza);
end
end);
end
function command_mt:_process_response(result)
if result.attr.type == "error" then
self.status = "canceled";
self.callback(self, {});
return;
end
local command = result:get_child("command", xmlns_commands);
self.status = command.attr.status;
self.sessionid = command.attr.sessionid;
self.form = command:get_child("x", xmlns_data);
self.note = command:get_child("note"); --FIXME handle multiple <note/>s
self.callback(self);
end
-- Initial execution of a command
function command_mt:execute()
local iq = verse.iq({ to = self.jid, type = "set" })
:tag("command", { xmlns = xmlns_commands, node = self.command });
self.stream:send_iq(iq, function (result)
self:_process_response(result);
end);
end
function command_mt:next(form)
local iq = verse.iq({ to = self.jid, type = "set" })
:tag("command", {
xmlns = xmlns_commands,
node = self.command,
sessionid = self.sessionid
});
if form then iq:add_child(form); end
self.stream:send_iq(iq, function (result)
self:_process_response(result);
end);
end
<file_sep>
return function (stream, name)
if name == "PLAIN" and stream.username and stream.password then
return function (stream)
return "success" == coroutine.yield("\0"..stream.username.."\0"..stream.password);
end, 5;
end
end
<file_sep>-- Copyright (C) 2009-2010 <NAME>
-- Copyright (C) 2009-2010 <NAME>
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local verse = require "verse";
local zlib = require "zlib";
local xmlns_compression_feature = "http://jabber.org/features/compress"
local xmlns_compression_protocol = "http://jabber.org/protocol/compress"
local xmlns_stream = "http://etherx.jabber.org/streams";
local compression_level = 9;
-- returns either nil or a fully functional ready to use inflate stream
local function get_deflate_stream(session)
local status, deflate_stream = pcall(zlib.deflate, compression_level);
if status == false then
local error_st = verse.stanza("failure", {xmlns=xmlns_compression_protocol}):tag("setup-failed");
session:send(error_st);
session:error("Failed to create zlib.deflate filter: %s", tostring(deflate_stream));
return
end
return deflate_stream
end
-- returns either nil or a fully functional ready to use inflate stream
local function get_inflate_stream(session)
local status, inflate_stream = pcall(zlib.inflate);
if status == false then
local error_st = verse.stanza("failure", {xmlns=xmlns_compression_protocol}):tag("setup-failed");
session:send(error_st);
session:error("Failed to create zlib.inflate filter: %s", tostring(inflate_stream));
return
end
return inflate_stream
end
-- setup compression for a stream
local function setup_compression(session, deflate_stream)
function session:send(t)
--TODO: Better code injection in the sending process
local status, compressed, eof = pcall(deflate_stream, tostring(t), 'sync');
if status == false then
session:close({
condition = "undefined-condition";
text = compressed;
extra = verse.stanza("failure", {xmlns=xmlns_compression_protocol}):tag("processing-failed");
});
session:warn("Compressed send failed: %s", tostring(compressed));
return;
end
session.conn:write(compressed);
end;
end
-- setup decompression for a stream
local function setup_decompression(session, inflate_stream)
local old_data = session.data
session.data = function(conn, data)
session:debug("Decompressing data...");
local status, decompressed, eof = pcall(inflate_stream, data);
if status == false then
session:close({
condition = "undefined-condition";
text = decompressed;
extra = verse.stanza("failure", {xmlns=xmlns_compression_protocol}):tag("processing-failed");
});
stream:warn("%s", tostring(decompressed));
return;
end
return old_data(conn, decompressed);
end;
end
function verse.plugins.compression(stream)
local function handle_features(features)
if not stream.compressed then
-- does remote server support compression?
local comp_st = features:child_with_name("compression");
if comp_st then
-- do we support the mechanism
for a in comp_st:children() do
local algorithm = a[1]
if algorithm == "zlib" then
stream:send(verse.stanza("compress", {xmlns=xmlns_compression_protocol}):tag("method"):text("zlib"))
stream:debug("Enabled compression using zlib.")
return true;
end
end
session:debug("Remote server supports no compression algorithm we support.")
end
end
end
local function handle_compressed(stanza)
if stanza.name == "compressed" then
stream:debug("Activating compression...")
-- create deflate and inflate streams
local deflate_stream = get_deflate_stream(stream);
if not deflate_stream then return end
local inflate_stream = get_inflate_stream(stream);
if not inflate_stream then return end
-- setup compression for stream.w
setup_compression(stream, deflate_stream);
-- setup decompression for stream.data
setup_decompression(stream, inflate_stream);
stream.compressed = true;
stream:reopen();
elseif stanza.name == "failure" then
stream:warn("Failed to establish compression");
end
end
stream:hook("stream-features", handle_features, 250);
stream:hook("stream/"..xmlns_compression_protocol, handle_compressed);
end
<file_sep>local verse = require "verse";
local xmlns_s5b = "urn:xmpp:jingle:transports:s5b:1";
local xmlns_bytestreams = "http://jabber.org/protocol/bytestreams";
local sha1 = require "util.hashes".sha1;
local uuid_generate = require "util.uuid".generate;
local function negotiate_socks5(conn, hash)
local function suppress_connected()
conn:unhook("connected", suppress_connected);
return true;
end
local function receive_connection_response(data)
conn:unhook("incoming-raw", receive_connection_response);
if data:sub(1, 2) ~= "\005\000" then
return conn:event("error", "connection-failure");
end
conn:event("connected");
return true;
end
local function receive_auth_response(data)
conn:unhook("incoming-raw", receive_auth_response);
if data ~= "\005\000" then -- SOCKSv5; "NO AUTHENTICATION"
-- Server is not SOCKSv5, or does not allow no auth
local err = "version-mismatch";
if data:sub(1,1) == "\005" then
err = "authentication-failure";
end
return conn:event("error", err);
end
-- Request SOCKS5 connection
conn:send(string.char(0x05, 0x01, 0x00, 0x03, #hash)..hash.."\0\0"); --FIXME: Move to "connected"?
conn:hook("incoming-raw", receive_connection_response, 100);
return true;
end
conn:hook("connected", suppress_connected, 200);
conn:hook("incoming-raw", receive_auth_response, 100);
conn:send("\005\001\000"); -- SOCKSv5; 1 mechanism; "NO AUTHENTICATION"
end
local function connect_to_usable_streamhost(callback, streamhosts, auth_token)
local conn = verse.new(nil, {
streamhosts = streamhosts,
current_host = 0;
});
--Attempt to connect to the next host
local function attempt_next_streamhost(event)
if event then
return callback(nil, event.reason);
end
-- First connect, or the last connect failed
if conn.current_host < #conn.streamhosts then
conn.current_host = conn.current_host + 1;
conn:debug("Attempting to connect to "..conn.streamhosts[conn.current_host].host..":"..conn.streamhosts[conn.current_host].port.."...");
local ok, err = conn:connect(
conn.streamhosts[conn.current_host].host,
conn.streamhosts[conn.current_host].port
);
if not ok then
conn:debug("Error connecting to proxy (%s:%s): %s",
conn.streamhosts[conn.current_host].host,
conn.streamhosts[conn.current_host].port,
err
);
else
conn:debug("Connecting...");
end
negotiate_socks5(conn, auth_token);
return true; -- Halt processing of disconnected event
end
-- All streamhosts tried, none successful
conn:unhook("disconnected", attempt_next_streamhost);
return callback(nil);
-- Let disconnected event fall through to user handlers...
end
conn:hook("disconnected", attempt_next_streamhost, 100);
-- When this event fires, we're connected to a streamhost
conn:hook("connected", function ()
conn:unhook("disconnected", attempt_next_streamhost);
callback(conn.streamhosts[conn.current_host], conn);
end, 100);
attempt_next_streamhost(); -- Set it in motion
return conn;
end
function verse.plugins.jingle_s5b(stream)
stream:hook("ready", function ()
stream:add_disco_feature(xmlns_s5b);
end, 10);
local s5b = {};
function s5b:generate_initiate()
self.s5b_sid = uuid_generate();
local transport = verse.stanza("transport", { xmlns = xmlns_s5b,
mode = "tcp", sid = self.s5b_sid });
local p = 0;
for jid, streamhost in pairs(stream.proxy65.available_streamhosts) do
p = p + 1;
transport:tag("candidate", { jid = jid, host = streamhost.host,
port = streamhost.port, cid=jid, priority = p, type = "proxy" }):up();
end
stream:debug("Have %d proxies", p)
return transport;
end
function s5b:generate_accept(initiate_transport)
local candidates = {};
self.s5b_peer_candidates = candidates;
self.s5b_mode = initiate_transport.attr.mode or "tcp";
self.s5b_sid = initiate_transport.attr.sid or self.jingle.sid;
-- Import the list of candidates the initiator offered us
for candidate in initiate_transport:childtags() do
--if candidate.attr.jid == "<EMAIL>/Gajim"
--and candidate.attr.host == "172.16.17.32" then
candidates[candidate.attr.cid] = {
type = candidate.attr.type;
jid = candidate.attr.jid;
host = candidate.attr.host;
port = tonumber(candidate.attr.port) or 0;
priority = tonumber(candidate.attr.priority) or 0;
cid = candidate.attr.cid;
};
--end
end
-- Import our own candidates
-- TODO ^
local transport = verse.stanza("transport", { xmlns = xmlns_s5b });
return transport;
end
function s5b:connect(callback)
stream:warn("Connecting!");
local streamhost_array = {};
for cid, streamhost in pairs(self.s5b_peer_candidates or {}) do
streamhost_array[#streamhost_array+1] = streamhost;
end
if #streamhost_array > 0 then
self.connecting_peer_candidates = true;
local function onconnect(streamhost, conn)
self.jingle:send_command("transport-info", verse.stanza("content", { creator = self.creator, name = self.name })
:tag("transport", { xmlns = xmlns_s5b, sid = self.s5b_sid })
:tag("candidate-used", { cid = streamhost.cid }));
self.onconnect_callback = callback;
self.conn = conn;
end
local auth_token = <PASSWORD>(self.s5b_sid..self.peer..stream.jid, true);
connect_to_usable_streamhost(onconnect, streamhost_array, auth_token);
else
stream:warn("Actually, I'm going to wait for my peer to tell me its streamhost...");
self.onconnect_callback = callback;
end
end
function s5b:info_received(jingle_tag)
stream:warn("Info received");
local content_tag = jingle_tag:child_with_name("content");
local transport_tag = content_tag:child_with_name("transport");
if transport_tag:get_child("candidate-used") and not self.connecting_peer_candidates then
local candidate_used = transport_tag:child_with_name("candidate-used");
if candidate_used then
-- Connect straight away to candidate used, we weren't trying any anyway
local function onconnect(streamhost, conn)
if self.jingle.role == "initiator" then -- More correct would be - "is this a candidate we offered?"
-- Activate the stream
self.jingle.stream:send_iq(verse.iq({ to = streamhost.jid, type = "set" })
:tag("query", { xmlns = xmlns_bytestreams, sid = self.s5b_sid })
:tag("activate"):text(self.jingle.peer), function (result)
if result.attr.type == "result" then
self.jingle:send_command("transport-info", verse.stanza("content", content_tag.attr)
:tag("transport", { xmlns = xmlns_s5b, sid = self.s5b_sid })
:tag("activated", { cid = candidate_used.attr.cid }));
self.conn = conn;
self.onconnect_callback(conn);
else
self.jingle.stream:error("Failed to activate bytestream");
end
end);
end
end
-- FIXME: Another assumption that cid==jid, and that it was our candidate
self.jingle.stream:debug("CID: %s", self.jingle.stream.proxy65.available_streamhosts[candidate_used.attr.cid]);
local streamhost_array = {
self.jingle.stream.proxy65.available_streamhosts[candidate_used.attr.cid];
};
local auth_token = sha1(self.s5b_sid..stream.jid..self.peer, true);
connect_to_usable_streamhost(onconnect, streamhost_array, auth_token);
end
elseif transport_tag:get_child("activated") then
self.onconnect_callback(self.conn);
end
end
function s5b:disconnect()
if self.conn then
self.conn:close();
end
end
function s5b:handle_accepted(jingle_tag)
end
local s5b_mt = { __index = s5b };
stream:hook("jingle/transport/"..xmlns_s5b, function (jingle)
return setmetatable({
role = jingle.role,
peer = jingle.peer,
stream = jingle.stream,
jingle = jingle,
}, s5b_mt);
end);
end
<file_sep>-- This implements XEP-0313: Message Archive Management
-- http://xmpp.org/extensions/xep-0313.html
-- (ie not XEP-0136)
local verse = require "verse";
local st = require "util.stanza";
local xmlns_mam = "urn:xmpp:mam:2"
local xmlns_forward = "urn:xmpp:forward:0";
local xmlns_delay = "urn:xmpp:delay";
local uuid = require "util.uuid".generate;
local parse_datetime = require "util.datetime".parse;
local datetime = require "util.datetime".datetime;
local dataform = require"util.dataforms".new;
local rsm = require "util.rsm";
local NULL = {};
local query_form = dataform {
{ name = "FORM_TYPE"; type = "hidden"; value = xmlns_mam; };
{ name = "with"; type = "jid-single"; };
{ name = "start"; type = "text-single" };
{ name = "end"; type = "text-single"; };
};
function verse.plugins.archive(stream)
function stream:query_archive(where, query_params, callback)
local queryid = uuid();
local query_st = st.iq{ type="set", to = where }
:tag("query", { xmlns = xmlns_mam, queryid = queryid });
local qstart, qend = tonumber(query_params["start"]), tonumber(query_params["end"]);
query_params["start"] = qstart and datetime(qstart);
query_params["end"] = qend and datetime(qend);
query_st:add_child(query_form:form(query_params, "submit"));
-- query_st:up();
query_st:add_child(rsm.generate(query_params));
local results = {};
local function handle_archived_message(message)
local result_tag = message:get_child("result", xmlns_mam);
if result_tag and result_tag.attr.queryid == queryid then
local forwarded = result_tag:get_child("forwarded", xmlns_forward);
forwarded = forwarded or message:get_child("forwarded", xmlns_forward); -- COMPAT XEP-0313 pre 2013-05-31
local id = result_tag.attr.id;
local delay = forwarded:get_child("delay", xmlns_delay);
local stamp = delay and parse_datetime(delay.attr.stamp) or nil;
local message = forwarded:get_child("message", "jabber:client")
results[#results+1] = { id = id, stamp = stamp, message = message };
return true
end
end
self:hook("message", handle_archived_message, 1);
self:send_iq(query_st, function(reply)
self:unhook("message", handle_archived_message);
if reply.attr.type == "error" then
self:warn(table.concat({reply:get_error()}, " "))
callback(false, reply:get_error())
return true;
end
local finnished = reply:get_child("fin", xmlns_mam)
if finnished then
local rset = rsm.get(finnished);
for k,v in pairs(rset or NULL) do results[k]=v; end
end
callback(results);
return true
end);
end
local default_attrs = {
always = true, [true] = "always",
never = false, [false] = "never",
roster = "roster",
}
local function prefs_decode(stanza) -- from XML
local prefs = {};
local default = stanza.attr.default;
if default then
prefs[false] = default_attrs[default];
end
local always = stanza:get_child("always");
if always then
for rule in always:childtags("jid") do
local jid = rule:get_text();
prefs[jid] = true;
end
end
local never = stanza:get_child("never");
if never then
for rule in never:childtags("jid") do
local jid = rule:get_text();
prefs[jid] = false;
end
end
return prefs;
end
local function prefs_encode(prefs) -- into XML
local default
default, prefs[false] = prefs[false], nil;
if default ~= nil then
default = default_attrs[default];
end
local reply = st.stanza("prefs", { xmlns = xmlns_mam, default = default })
local always = st.stanza("always");
local never = st.stanza("never");
for k,v in pairs(prefs) do
(v and always or never):tag("jid"):text(k):up();
end
return reply:add_child(always):add_child(never);
end
function stream:archive_prefs_get(callback)
self:send_iq(st.iq{ type="get" }:tag("prefs", { xmlns = xmlns_mam }),
function(result)
if result and result.attr.type == "result" and result.tags[1] then
local prefs = prefs_decode(result.tags[1]);
callback(prefs, result);
else
callback(nil, result);
end
end);
end
function stream:archive_prefs_set(prefs, callback)
self:send_iq(st.iq{ type="set" }:add_child(prefs_encode(prefs)), callback);
end
end
<file_sep>local verse = require "verse";
local uuid = require "util.uuid";
local sha1 = require "util.hashes".sha1;
local proxy65_mt = {};
proxy65_mt.__index = proxy65_mt;
local xmlns_bytestreams = "http://jabber.org/protocol/bytestreams";
local negotiate_socks5;
function verse.plugins.proxy65(stream)
stream.proxy65 = setmetatable({ stream = stream }, proxy65_mt);
stream.proxy65.available_streamhosts = {};
local outstanding_proxies = 0;
stream:hook("disco/service-discovered/proxy", function (service)
-- Fill list with available proxies
if service.type == "bytestreams" then
outstanding_proxies = outstanding_proxies + 1;
stream:send_iq(verse.iq({ to = service.jid, type = "get" })
:tag("query", { xmlns = xmlns_bytestreams }), function (result)
outstanding_proxies = outstanding_proxies - 1;
if result.attr.type == "result" then
local streamhost = result:get_child("query", xmlns_bytestreams)
:get_child("streamhost").attr;
stream.proxy65.available_streamhosts[streamhost.jid] = {
jid = streamhost.jid;
host = streamhost.host;
port = tonumber(streamhost.port);
};
end
if outstanding_proxies == 0 then
stream:event("proxy65/discovered-proxies", stream.proxy65.available_streamhosts);
end
end);
end
end);
stream:hook("iq/"..xmlns_bytestreams, function (request)
local conn = verse.new(nil, {
initiator_jid = request.attr.from,
streamhosts = {},
current_host = 0;
});
-- Parse hosts from request
for tag in request.tags[1]:childtags() do
if tag.name == "streamhost" then
table.insert(conn.streamhosts, tag.attr);
end
end
--Attempt to connect to the next host
local function attempt_next_streamhost()
-- First connect, or the last connect failed
if conn.current_host < #conn.streamhosts then
conn.current_host = conn.current_host + 1;
conn:connect(
conn.streamhosts[conn.current_host].host,
conn.streamhosts[conn.current_host].port
);
negotiate_socks5(stream, conn, request.tags[1].attr.sid, request.attr.from, stream.jid);
return true; -- Halt processing of disconnected event
end
-- All streamhosts tried, none successful
conn:unhook("disconnected", attempt_next_streamhost);
stream:send(verse.error_reply(request, "cancel", "item-not-found"));
-- Let disconnected event fall through to user handlers...
end
function conn:accept()
conn:hook("disconnected", attempt_next_streamhost, 100);
-- When this event fires, we're connected to a streamhost
conn:hook("connected", function ()
conn:unhook("disconnected", attempt_next_streamhost);
-- Send XMPP success notification
local reply = verse.reply(request)
:tag("query", request.tags[1].attr)
:tag("streamhost-used", { jid = conn.streamhosts[conn.current_host].jid });
stream:send(reply);
end, 100);
attempt_next_streamhost();
end
function conn:refuse()
-- FIXME: XMPP refused reply
end
stream:event("proxy65/request", conn);
end);
end
function proxy65_mt:new(target_jid, proxies)
local conn = verse.new(nil, {
target_jid = target_jid;
bytestream_sid = uuid.generate();
});
local request = verse.iq{type="set", to = target_jid}
:tag("query", { xmlns = xmlns_bytestreams, mode = "tcp", sid = conn.bytestream_sid });
for _, proxy in ipairs(proxies or self.proxies) do
request:tag("streamhost", proxy):up();
end
self.stream:send_iq(request, function (reply)
if reply.attr.type == "error" then
local type, condition, text = reply:get_error();
conn:event("connection-failed", { conn = conn, type = type, condition = condition, text = text });
else
-- Target connected to streamhost, connect ourselves
local streamhost_used = reply.tags[1]:get_child("streamhost-used");
-- if not streamhost_used then
--FIXME: Emit error
-- end
conn.streamhost_jid = streamhost_used.attr.jid;
local host, port;
for _, proxy in ipairs(proxies or self.proxies) do
if proxy.jid == conn.streamhost_jid then
host, port = proxy.host, proxy.port;
break;
end
end
-- if not (host and port) then
--FIXME: Emit error
-- end
conn:connect(host, port);
local function handle_proxy_connected()
conn:unhook("connected", handle_proxy_connected);
-- Both of us connected, tell proxy to activate connection
local activate_request = verse.iq{to = conn.streamhost_jid, type="set"}
:tag("query", { xmlns = xmlns_bytestreams, sid = conn.bytestream_sid })
:tag("activate"):text(target_jid);
self.stream:send_iq(activate_request, function (activated)
if activated.attr.type == "result" then
-- Connection activated, ready to use
conn:event("connected", conn);
-- else --FIXME: Emit error
end
end);
return true;
end
conn:hook("connected", handle_proxy_connected, 100);
negotiate_socks5(self.stream, conn, conn.bytestream_sid, self.stream.jid, target_jid);
end
end);
return conn;
end
function negotiate_socks5(stream, conn, sid, requester_jid, target_jid)
local hash = sha1(sid..requester_jid..target_jid);
local function suppress_connected()
conn:unhook("connected", suppress_connected);
return true;
end
local function receive_connection_response(data)
conn:unhook("incoming-raw", receive_connection_response);
if data:sub(1, 2) ~= "\005\000" then
return conn:event("error", "connection-failure");
end
conn:event("connected");
return true;
end
local function receive_auth_response(data)
conn:unhook("incoming-raw", receive_auth_response);
if data ~= "\005\000" then -- SOCKSv5; "NO AUTHENTICATION"
-- Server is not SOCKSv5, or does not allow no auth
local err = "version-mismatch";
if data:sub(1,1) == "\005" then
err = "authentication-failure";
end
return conn:event("error", err);
end
-- Request SOCKS5 connection
conn:send(string.char(0x05, 0x01, 0x00, 0x03, #hash)..hash.."\0\0"); --FIXME: Move to "connected"?
conn:hook("incoming-raw", receive_connection_response, 100);
return true;
end
conn:hook("connected", suppress_connected, 200);
conn:hook("incoming-raw", receive_auth_response, 100);
conn:send("\005\001\000"); -- SOCKSv5; 1 mechanism; "NO AUTHENTICATION"
end
<file_sep>-- Change these:
local jid, password = "<EMAIL>", "<PASSWORD>";
-- This line squishes verse each time you run,
-- handy if you're hacking on Verse itself
--os.execute("squish --minify-level=none");
require "verse".init("client");
c = verse.new();
c:add_plugin("version");
c:add_plugin("pep");
-- Add some hooks for debugging
c:hook("opened", function () print("Stream opened!") end);
c:hook("closed", function () print("Stream closed!") end);
c:hook("stanza", function (stanza) print("Stanza:", stanza) end);
-- This one prints all received data
c:hook("incoming-raw", print, 1000);
-- Print a message after authentication
c:hook("authentication-success", function () print("Logged in!"); end);
c:hook("authentication-failure", function (err) print("Failed to log in! Error: "..tostring(err.condition)); end);
-- Print a message and exit when disconnected
c:hook("disconnected", function () print("Disconnected!"); os.exit(); end);
-- Now, actually start the connection:
c:connect_client(jid, password);
-- Catch the "ready" event to know when the stream is ready to use
c:hook("ready", function ()
print("Stream ready!");
c.version:set{ name = "verse example client" };
c:hook_pep("http://jabber.org/protocol/mood", function (event)
print(event.from.." is "..event.item.tags[1].name);
end);
c:hook_pep("http://jabber.org/protocol/tune", function (event)
print(event.from.." is listening to "..event.item:get_child_text("title"));
end);
c:send(verse.presence());
c:publish_pep(verse.stanza("tune", { xmlns = "http://jabber.org/protocol/tune" })
:tag("title"):text("Beautiful Cedars"):up()
:tag("artist"):text("The Spinners"):up()
:tag("source"):text("Not Quite Folk"):up()
:tag("track"):text("4"):up()
);
end);
print("Starting loop...")
verse.loop()
<file_sep>
local base64, unbase64 = require "mime".b64, require"mime".unb64;
local hashes = require"util.hashes";
local bit = require"bit";
local random = require"util.random";
local tonumber = tonumber;
local char, byte = string.char, string.byte;
local gsub = string.gsub;
local xor = bit.bxor;
local function XOR(a, b)
return (gsub(a, "()(.)", function(i, c)
return char(xor(byte(c), byte(b, i)))
end));
end
local H, HMAC = hashes.sha1, hashes.hmac_sha1;
local function Hi(str, salt, i)
local U = HMAC(str, salt .. "\0\0\0\1");
local ret = U;
for _ = 2, i do
U = HMAC(str, U);
ret = XOR(ret, U);
end
return ret;
end
local function Normalize(str)
return str; -- TODO
end
local function value_safe(str)
return (gsub(str, "[,=]", { [","] = "=2C", ["="] = "=3D" }));
end
local function scram(stream, name)
local username = "n=" .. value_safe(stream.username);
local c_nonce = base64(random.bytes(15));
local our_nonce = "r=" .. c_nonce;
local client_first_message_bare = username .. "," .. our_nonce;
local cbind_data = "";
local gs2_cbind_flag = stream.conn:ssl() and "y" or "n";
if name == "SCRAM-SHA-1-PLUS" then
cbind_data = stream.conn:socket():getfinished();
gs2_cbind_flag = "p=tls-unique";
end
local gs2_header = gs2_cbind_flag .. ",,";
local client_first_message = gs2_header .. client_first_message_bare;
local cont, server_first_message = coroutine.yield(client_first_message);
if cont ~= "challenge" then return false end
local nonce, salt, iteration_count = server_first_message:match("(r=[^,]+),s=([^,]*),i=(%d+)");
local i = tonumber(iteration_count);
salt = unbase64(salt);
if not nonce or not salt or not i then
return false, "Could not parse server_first_message";
elseif nonce:find(c_nonce, 3, true) ~= 3 then
return false, "nonce sent by server does not match our nonce";
elseif nonce == our_nonce then
return false, "server did not append s-nonce to nonce";
end
local cbind_input = gs2_header .. cbind_data;
local channel_binding = "c=" .. base64(cbind_input);
local client_final_message_without_proof = channel_binding .. "," .. nonce;
local SaltedPassword;
local ClientKey;
local ServerKey;
if stream.client_key and stream.server_key then
ClientKey = stream.client_key;
ServerKey = stream.server_key;
else
if stream.salted_password then
SaltedPassword = stream.salted_password;
elseif stream.password then
SaltedPassword = Hi(Normalize(stream.password), salt, i);
end
ServerKey = HMAC(SaltedPassword, "Server Key");
ClientKey = HMAC(SaltedPassword, "Client Key");
end
local StoredKey = H(ClientKey);
local AuthMessage = client_first_message_bare .. "," .. server_first_message .. "," .. client_final_message_without_proof;
local ClientSignature = HMAC(StoredKey, AuthMessage);
local ClientProof = XOR(ClientKey, ClientSignature);
local ServerSignature = HMAC(ServerKey, AuthMessage);
local proof = "p=" .. base64(ClientProof);
local client_final_message = client_final_message_without_proof .. "," .. proof;
local ok, server_final_message = coroutine.yield(client_final_message);
if ok ~= "success" then return false, "success-expected" end
local verifier = server_final_message:match("v=([^,]+)");
if unbase64(verifier) ~= ServerSignature then
return false, "server signature did not match";
end
return true;
end
return function (stream, name)
if stream.username and (stream.password or (stream.client_key or stream.server_key)) then
if name == "SCRAM-SHA-1" then
return scram, 99;
elseif name == "SCRAM-SHA-1-PLUS" then
local sock = stream.conn:ssl() and stream.conn:socket();
if sock and sock.getfinished then
return scram, 100;
end
end
end
end
<file_sep>local verse = require "verse";
local t_insert = table.insert;
local xmlns_pubsub = "http://jabber.org/protocol/pubsub";
local xmlns_pubsub_owner = "http://jabber.org/protocol/pubsub#owner";
local xmlns_pubsub_event = "http://jabber.org/protocol/pubsub#event";
-- local xmlns_pubsub_errors = "http://jabber.org/protocol/pubsub#errors";
local pubsub = {};
local pubsub_mt = { __index = pubsub };
function verse.plugins.pubsub(stream)
stream.pubsub = setmetatable({ stream = stream }, pubsub_mt);
stream:hook("message", function (message)
local m_from = message.attr.from;
for pubsub_event in message:childtags("event", xmlns_pubsub_event) do
local items = pubsub_event:get_child("items");
if items then
local node = items.attr.node;
for item in items:childtags("item") do
stream:event("pubsub/event", {
from = m_from;
node = node;
item = item;
});
end
end
end
end);
return true;
end
-- COMPAT
function pubsub:create(server, node, callback)
return self:service(server):node(node):create(nil, callback);
end
function pubsub:subscribe(server, node, jid, callback)
return self:service(server):node(node):subscribe(jid, nil, callback);
end
function pubsub:publish(server, node, id, item, callback)
return self:service(server):node(node):publish(id, nil, item, callback);
end
--------------------------------------------------------------------------
---------------------New and improved PubSub interface--------------------
--------------------------------------------------------------------------
local pubsub_service = {};
local pubsub_service_mt = { __index = pubsub_service };
-- TODO should the property be named 'jid' instead?
function pubsub:service(service)
return setmetatable({ stream = self.stream, service = service }, pubsub_service_mt)
end
-- Helper function for iq+pubsub tags
local function pubsub_iq(iq_type, to, ns, op, node, jid, item_id)
local st = verse.iq{ type = iq_type or "get", to = to }
:tag("pubsub", { xmlns = ns or xmlns_pubsub }) -- ns would be ..#owner
if op then st:tag(op, { node = node, jid = jid }); end
if item_id then st:tag("item", { id = item_id ~= true and item_id or nil }); end
return st;
end
-- http://xmpp.org/extensions/xep-0060.html#entity-subscriptions
function pubsub_service:subscriptions(callback)
self.stream:send_iq(pubsub_iq(nil, self.service, nil, "subscriptions")
, callback and function (result)
if result.attr.type == "result" then
local ps = result:get_child("pubsub", xmlns_pubsub);
local subs = ps and ps:get_child("subscriptions");
local nodes = {};
if subs then
for sub in subs:childtags("subscription") do
local node = self:node(sub.attr.node)
node.subscription = sub;
node.subscribed_jid = sub.attr.jid;
t_insert(nodes, node);
-- FIXME Good enough?
-- Or how about:
-- nodes[node] = sub;
end
end
callback(nodes);
else
callback(false, result:get_error());
end
end or nil);
end
-- http://xmpp.org/extensions/xep-0060.html#entity-affiliations
function pubsub_service:affiliations(callback)
self.stream:send_iq(pubsub_iq(nil, self.service, nil, "affiliations")
, callback and function (result)
if result.attr.type == "result" then
local ps = result:get_child("pubsub", xmlns_pubsub);
local affils = ps and ps:get_child("affiliations") or {};
local nodes = {};
if affils then
for affil in affils:childtags("affiliation") do
local node = self:node(affil.attr.node)
node.affiliation = affil;
t_insert(nodes, node);
-- nodes[node] = affil;
end
end
callback(nodes);
else
callback(false, result:get_error());
end
end or nil);
end
function pubsub_service:nodes(callback)
self.stream:disco_items(self.service, nil, function(items, ...)
if items then
for i=1,#items do
items[i] = self:node(items[i].node);
end
end
callback(items, ...)
end);
end
local pubsub_node = {};
local pubsub_node_mt = { __index = pubsub_node };
function pubsub_service:node(node)
return setmetatable({ stream = self.stream, service = self.service, node = node }, pubsub_node_mt)
end
function pubsub_mt:__call(service, node)
local s = self:service(service);
return node and s:node(node) or s;
end
function pubsub_node:hook(callback, prio)
self._hooks = self._hooks or setmetatable({}, { __mode = 'kv' });
local function hook(event)
-- FIXME service == nil would mean anyone,
-- publishing would be go to your bare jid.
-- So if you're only interestied in your own
-- events, hook your own bare jid.
if (not event.service or event.from == self.service) and event.node == self.node then
return callback(event)
end
end
self._hooks[callback] = hook;
self.stream:hook("pubsub/event", hook, prio);
return hook;
end
function pubsub_node:unhook(callback)
if callback then
local hook = self._hooks[callback];
self.stream:unhook("pubsub/event", hook);
elseif self._hooks then
for hook in pairs(self._hooks) do
self.stream:unhook("pubsub/event", hook);
end
end
end
function pubsub_node:create(config, callback)
if config ~= nil then
error("Not implemented yet.");
else
self.stream:send_iq(pubsub_iq("set", self.service, nil, "create", self.node), callback);
end
end
-- <configure/> and <default/> rolled into one
function pubsub_node:configure(config, callback)
if config ~= nil then
error("Not implemented yet.");
--[[
if config == true then
self.stream:send_iq(pubsub_iq("get", self.service, nil, "configure", self.node)
, function(reply)
local form = reply:get_child("pubsub"):get_child("configure"):get_cild("x");
local config = callback(require"util.dataforms".something(form))
self.stream:send_iq(pubsub_iq("set", config, ...))
end);
end
--]]
-- fetch form and pass it to the callback
-- which would process it and pass it back
-- and then we submit it
-- elseif type(config) == "table" then
-- it's a form or stanza that we submit
-- end
-- this would be done for everything that needs a config
end
self.stream:send_iq(pubsub_iq("set", self.service, nil, config == nil and "default" or "configure", self.node), callback);
end
function pubsub_node:publish(id, options, node, callback)
if options ~= nil then
error("Node configuration is not implemented yet.");
end
self.stream:send_iq(pubsub_iq("set", self.service, nil, "publish", self.node, nil, id or true)
:add_child(node)
, callback);
end
function pubsub_node:subscribe(jid, options, callback)
jid = jid or self.stream.jid;
if options ~= nil then
error("Subscription configuration is not implemented yet.");
end
self.stream:send_iq(pubsub_iq("set", self.service, nil, "subscribe", self.node, jid)
, callback);
end
function pubsub_node:subscription(callback)
error("Not implemented yet.");
end
function pubsub_node:affiliation(callback)
error("Not implemented yet.");
end
function pubsub_node:unsubscribe(jid, callback)
jid = jid or self.subscribed_jid or self.stream.jid;
self.stream:send_iq(pubsub_iq("set", self.service, nil, "unsubscribe", self.node, jid)
, callback);
end
function pubsub_node:configure_subscription(options, callback)
error("Not implemented yet.");
end
function pubsub_node:items(full, callback)
if full then
self.stream:send_iq(pubsub_iq("get", self.service, nil, "items", self.node)
, callback);
else
self.stream:disco_items(self.service, self.node, callback);
end
end
function pubsub_node:item(id, callback)
self.stream:send_iq(pubsub_iq("get", self.service, nil, "items", self.node, nil, id)
, callback);
end
function pubsub_node:retract(id, callback)
self.stream:send_iq(pubsub_iq("set", self.service, nil, "retract", self.node, nil, id)
, callback);
end
function pubsub_node:purge(notify, callback)
assert(not notify, "Not implemented yet.");
self.stream:send_iq(pubsub_iq("set", self.service, xmlns_pubsub_owner, "purge", self.node)
, callback);
end
function pubsub_node:delete(redirect_uri, callback)
assert(not redirect_uri, "Not implemented yet.");
self.stream:send_iq(pubsub_iq("set", self.service, xmlns_pubsub_owner, "delete", self.node)
, callback);
end
<file_sep>local verse = require "verse";
function verse.plugins.presence(stream)
stream.last_presence = nil;
stream:hook("presence-out", function (presence)
if not presence.attr.to then
stream.last_presence = presence; -- Cache non-directed presence
end
end, 1);
function stream:resend_presence()
if self.last_presence then
stream:send(self.last_presence);
end
end
function stream:set_status(opts)
local p = verse.presence();
if type(opts) == "table" then
if opts.show then
p:tag("show"):text(opts.show):up();
end
if opts.priority or opts.prio then
p:tag("priority"):text(tostring(opts.priority or opts.prio)):up();
end
if opts.status or opts.msg then
p:tag("status"):text(opts.status or opts.msg):up();
end
elseif type(opts) == "string" then
p:tag("status"):text(opts):up();
end
stream:send(p);
end
end
<file_sep>-- Change these:
local jid, password = "<EMAIL>", "<PASSWORD>";
-- This line squishes verse each time you run,
-- handy if you're hacking on Verse itself
--os.execute("squish --minify-level=none");
require "verse".init("client");
c = verse.new(verse.logger());
c:add_plugin("version");
c:add_plugin("disco");
c:add_plugin("adhoc");
-- Add some hooks for debugging
c:hook("opened", function () print("Stream opened!") end);
c:hook("closed", function () print("Stream closed!") end);
c:hook("stanza", function (stanza) print("Stanza:", stanza) end);
-- This one prints all received data
c:hook("incoming-raw", print, 1000);
-- Print a message after authentication
c:hook("authentication-success", function () print("Logged in!"); end);
c:hook("authentication-failure", function (err) print("Failed to log in! Error: "..tostring(err.condition)); end);
-- Print a message and exit when disconnected
c:hook("disconnected", function () print("Disconnected!"); os.exit(); end);
-- Now, actually start the connection:
c:connect_client(jid, password);
-- Catch the "ready" event to know when the stream is ready to use
c:hook("ready", function ()
print("Stream ready!");
c.version:set{ name = "verse example client" };
local function random_handler()
return { info = tostring(math.random(1,100)), status = "completed" };
end
c:add_adhoc_command("Get random number", "random", random_handler);
c:send(verse.presence():add_child(c:caps()));
end);
print("Starting loop...")
verse.loop()
<file_sep>local verse = require "verse";
local xmlns_carbons = "urn:xmpp:carbons:2";
local xmlns_forward = "urn:xmpp:forward:0";
local os_time = os.time;
local parse_datetime = require "util.datetime".parse;
local bare_jid = require "util.jid".bare;
-- TODO Check disco for support
function verse.plugins.carbons(stream)
local carbons = {};
carbons.enabled = false;
stream.carbons = carbons;
function carbons:enable(callback)
stream:send_iq(verse.iq{type="set"}
:tag("enable", { xmlns = xmlns_carbons })
, function(result)
local success = result.attr.type == "result";
if success then
carbons.enabled = true;
end
if callback then
callback(success);
end
end or nil);
end
function carbons:disable(callback)
stream:send_iq(verse.iq{type="set"}
:tag("disable", { xmlns = xmlns_carbons })
, function(result)
local success = result.attr.type == "result";
if success then
carbons.enabled = false;
end
if callback then
callback(success);
end
end or nil);
end
local my_bare;
stream:hook("bind-success", function()
my_bare = bare_jid(stream.jid);
end);
stream:hook("message", function(stanza)
local carbon = stanza:get_child(nil, xmlns_carbons);
if stanza.attr.from == my_bare and carbon then
local carbon_dir = carbon.name;
local fwd = carbon:get_child("forwarded", xmlns_forward);
local fwd_stanza = fwd and fwd:get_child("message", "jabber:client");
local delay = fwd:get_child("delay", "urn:xmpp:delay");
local stamp = delay and delay.attr.stamp;
stamp = stamp and parse_datetime(stamp);
if fwd_stanza then
return stream:event("carbon", {
dir = carbon_dir,
stanza = fwd_stanza,
timestamp = stamp or os_time(),
});
end
end
end, 1);
end
<file_sep>local verse = require "verse";
local events = require "util.events";
local jid = require "util.jid";
local room_mt = {};
room_mt.__index = room_mt;
local xmlns_delay = "urn:xmpp:delay";
local xmlns_muc = "http://jabber.org/protocol/muc";
function verse.plugins.groupchat(stream)
stream:add_plugin("presence")
stream.rooms = {};
stream:hook("stanza", function (stanza)
local room_jid = jid.bare(stanza.attr.from);
if not room_jid then return end
local room = stream.rooms[room_jid]
if not room and stanza.attr.to and room_jid then
room = stream.rooms[stanza.attr.to.." "..room_jid]
end
if room and room.opts.source and stanza.attr.to ~= room.opts.source then return end
if room then
local nick = select(3, jid.split(stanza.attr.from));
local body = stanza:get_child_text("body");
local delay = stanza:get_child("delay", xmlns_delay);
local event = {
room_jid = room_jid;
room = room;
sender = room.occupants[nick];
nick = nick;
body = body;
stanza = stanza;
delay = (delay and delay.attr.stamp);
};
local ret = room:event(stanza.name, event);
return ret or (stanza.name == "message") or nil;
end
end, 500);
function stream:join_room(jid, nick, opts)
if not nick then
return false, "no nickname supplied"
end
opts = opts or {};
local room = setmetatable(verse.eventable{
stream = stream, jid = jid, nick = nick,
subject = nil,
occupants = {},
opts = opts,
}, room_mt);
if opts.source then
self.rooms[opts.source.." "..jid] = room;
else
self.rooms[jid] = room;
end
local occupants = room.occupants;
room:hook("presence", function (presence)
local nick = presence.nick or nick;
if not occupants[nick] and presence.stanza.attr.type ~= "unavailable" then
occupants[nick] = {
nick = nick;
jid = presence.stanza.attr.from;
presence = presence.stanza;
};
local x = presence.stanza:get_child("x", xmlns_muc .. "#user");
if x then
local x_item = x:get_child("item");
if x_item and x_item.attr then
occupants[nick].real_jid = x_item.attr.jid;
occupants[nick].affiliation = x_item.attr.affiliation;
occupants[nick].role = x_item.attr.role;
end
--TODO Check for status 100?
end
if nick == room.nick then
room.stream:event("groupchat/joined", room);
else
room:event("occupant-joined", occupants[nick]);
end
elseif occupants[nick] and presence.stanza.attr.type == "unavailable" then
if nick == room.nick then
room.stream:event("groupchat/left", room);
if room.opts.source then
self.rooms[room.opts.source.." "..jid] = nil;
else
self.rooms[jid] = nil;
end
else
occupants[nick].presence = presence.stanza;
room:event("occupant-left", occupants[nick]);
occupants[nick] = nil;
end
end
end);
room:hook("message", function(event)
local subject = event.stanza:get_child_text("subject");
if not subject then return end
subject = #subject > 0 and subject or nil;
if subject ~= room.subject then
local old_subject = room.subject;
room.subject = subject;
return room:event("subject-changed", { from = old_subject, to = subject, by = event.sender, event = event });
end
end, 2000);
local join_st = verse.presence():tag("x",{xmlns = xmlns_muc}):reset();
self:event("pre-groupchat/joining", join_st);
room:send(join_st)
self:event("groupchat/joining", room);
return room;
end
stream:hook("presence-out", function(presence)
if not presence.attr.to then
for _, room in pairs(stream.rooms) do
room:send(presence);
end
presence.attr.to = nil;
end
end);
end
function room_mt:send(stanza)
if stanza.name == "message" and not stanza.attr.type then
stanza.attr.type = "groupchat";
end
if stanza.name == "presence" then
stanza.attr.to = self.jid .."/"..self.nick;
end
if stanza.attr.type == "groupchat" or not stanza.attr.to then
stanza.attr.to = self.jid;
end
if self.opts.source then
stanza.attr.from = self.opts.source
end
self.stream:send(stanza);
end
function room_mt:send_message(text)
self:send(verse.message():tag("body"):text(text));
end
function room_mt:set_subject(text)
self:send(verse.message():tag("subject"):text(text));
end
function room_mt:leave(message)
self.stream:event("groupchat/leaving", self);
local presence = verse.presence({type="unavailable"});
if message then
presence:tag("status"):text(message);
end
self:send(presence);
end
function room_mt:admin_set(nick, what, value, reason)
self:send(verse.iq({type="set"})
:query(xmlns_muc .. "#admin")
:tag("item", {nick = nick, [what] = value})
:tag("reason"):text(reason or ""));
end
function room_mt:set_role(nick, role, reason)
self:admin_set(nick, "role", role, reason);
end
function room_mt:set_affiliation(nick, affiliation, reason)
self:admin_set(nick, "affiliation", affiliation, reason);
end
function room_mt:kick(nick, reason)
self:set_role(nick, "none", reason);
end
function room_mt:ban(nick, reason)
self:set_affiliation(nick, "outcast", reason);
end
<file_sep>local verse = require "verse";
local base64 = require "util.encodings".base64;
local uuid_generate = require "util.uuid".generate;
local xmlns_jingle_ibb = "urn:xmpp:jingle:transports:ibb:1";
local xmlns_ibb = "http://jabber.org/protocol/ibb";
assert(base64.encode("This is a test.") == "VGhpcyBpcyBhIHRlc3Qu", "Base64 encoding failed");
assert(base64.decode("VGhpcyBpcyBhIHRlc3Qu") == "This is a test.", "Base64 decoding failed");
local t_concat = table.concat
local ibb_conn = {};
local ibb_conn_mt = { __index = ibb_conn };
local function new_ibb(stream)
local conn = setmetatable({ stream = stream }, ibb_conn_mt)
conn = verse.eventable(conn);
return conn;
end
function ibb_conn:initiate(peer, sid, stanza)
self.block = 2048; -- ignored for now
self.stanza = stanza or 'iq';
self.peer = peer;
self.sid = sid or tostring(self):match("%x+$");
self.iseq = 0;
self.oseq = 0;
local feeder = function(stanza)
return self:feed(stanza)
end
self.feeder = feeder;
print("Hooking incomming IQs");
local stream = self.stream;
stream:hook("iq/".. xmlns_ibb, feeder)
if stanza == "message" then
stream:hook("message", feeder)
end
end
function ibb_conn:open(callback)
self.stream:send_iq(verse.iq{ to = self.peer, type = "set" }
:tag("open", {
xmlns = xmlns_ibb,
["block-size"] = self.block,
sid = self.sid,
stanza = self.stanza
})
, function(reply)
if callback then
if reply.attr.type ~= "error" then
callback(true)
else
callback(false, reply:get_error())
end
end
end);
end
function ibb_conn:send(data)
local stanza = self.stanza;
local st;
if stanza == "iq" then
st = verse.iq{ type = "set", to = self.peer }
elseif stanza == "message" then
st = verse.message{ to = self.peer }
end
local seq = self.oseq;
self.oseq = seq + 1;
st:tag("data", { xmlns = xmlns_ibb, sid = self.sid, seq = seq })
:text(base64.encode(data));
if stanza == "iq" then
self.stream:send_iq(st, function(reply)
self:event(reply.attr.type == "result" and "drained" or "error");
end)
else
stream:send(st)
self:event("drained");
end
end
function ibb_conn:feed(stanza)
if stanza.attr.from ~= self.peer then return end
local child = stanza[1];
if child.attr.sid ~= self.sid then return end
local ok;
if child.name == "open" then
self:event("connected");
self.stream:send(verse.reply(stanza))
return true
elseif child.name == "data" then
local bdata = stanza:get_child_text("data", xmlns_ibb);
local seq = tonumber(child.attr.seq);
local expected_seq = self.iseq;
if bdata and seq then
if seq ~= expected_seq then
self.stream:send(verse.error_reply(stanza, "cancel", "not-acceptable", "Wrong sequence. Packet lost?"))
self:close();
self:event("error");
return true;
end
self.iseq = seq + 1;
local data = base64.decode(bdata);
if self.stanza == "iq" then
self.stream:send(verse.reply(stanza))
end
self:event("incoming-raw", data);
return true;
end
elseif child.name == "close" then
self.stream:send(verse.reply(stanza))
self:close();
return true
end
end
--[[ FIXME some day
function ibb_conn:receive(patt)
-- is this even used?
print("ibb_conn:receive("..tostring(patt)..")");
assert(patt == "*a" or tonumber(patt));
local data = t_concat(self.ibuffer):sub(self.pos, tonumber(patt) or nil);
self.pos = self.pos + #data;
return data
end
function ibb_conn:dirty()
print("ibb_conn:dirty()");
return false -- ????
end
function ibb_conn:getfd()
return 0
end
function ibb_conn:settimeout(n)
-- ignore?
end
-]]
function ibb_conn:close()
self.stream:unhook("iq/".. xmlns_ibb, self.feeder)
self:event("disconnected");
end
function verse.plugins.jingle_ibb(stream)
stream:hook("ready", function ()
stream:add_disco_feature(xmlns_jingle_ibb);
end, 10);
local ibb = {};
function ibb:_setup()
local conn = new_ibb(self.stream);
conn.sid = self.sid or conn.sid;
conn.stanza = self.stanza or conn.stanza;
conn.block = self.block or conn.block;
conn:initiate(self.peer, self.sid, self.stanza);
self.conn = conn;
end
function ibb:generate_initiate()
print("ibb:generate_initiate() as ".. self.role);
local sid = uuid_generate();
self.sid = sid;
self.stanza = 'iq';
self.block = 2048;
local transport = verse.stanza("transport", { xmlns = xmlns_jingle_ibb,
sid = self.sid, stanza = self.stanza, ["block-size"] = self.block });
return transport;
end
function ibb:generate_accept(initiate_transport)
print("ibb:generate_accept() as ".. self.role);
local attr = initiate_transport.attr;
self.sid = attr.sid or self.sid;
self.stanza = attr.stanza or self.stanza;
self.block = attr["block-size"] or self.block;
self:_setup();
return initiate_transport;
end
function ibb:connect(callback)
if not self.conn then
self:_setup();
end
local conn = self.conn;
print("ibb:connect() as ".. self.role);
if self.role == "initiator" then
conn:open(function(ok, ...)
assert(ok, table.concat({...}, ", "));
callback(conn);
end);
else
callback(conn);
end
end
function ibb:info_received(jingle_tag)
print("ibb:info_received()");
-- TODO, what exactly?
end
function ibb:disconnect()
if self.conn then
self.conn:close()
end
end
function ibb:handle_accepted(jingle_tag) end
local ibb_mt = { __index = ibb };
stream:hook("jingle/transport/"..xmlns_jingle_ibb, function (jingle)
return setmetatable({
role = jingle.role,
peer = jingle.peer,
stream = jingle.stream,
jingle = jingle,
}, ibb_mt);
end);
end
<file_sep>#!/bin/sh
SQUISH=./buildscripts/squish
PROSODY_URL=https://hg.prosody.im/0.10/raw-file/tip/
PREFIX="/usr/local"
LUA_VERSION=5.1
LUA_INTERPRETER=lua$LUA_VERSION
if which $LUA_INTERPRETER>/dev/null; then
LUA_DIR=$($LUA_INTERPRETER -e 'print((package.path:match("'"${PREFIX}"'[^;]+%?%.lua"):gsub("/%?%.lua$", "")))')
else
LUA_DIR="$PREFIX/share/lua/$LUA_VERSION"
fi
# Help
show_help() {
cat <<EOF
Configure Prosody prior to building.
--help This help.
--prefix Installation path prefix (used when installing)
Default: $PREFIX
--lua-lib-dir=DIR You can also specify Lua's libraries dir.
Default: $LUA_DIR
--squish Path to squish utility (used for building)
Default: $SQUISH
--prosody-rev Prosody revision to pull files from
Default: tip
--prosody-url URL to pull Prosody files from (not compatible with --prosody-rev)
Default: $PROSODY_URL
EOF
}
while [ "$1" ]
do
value="`echo $1 | sed 's/[^=]*=\(.*\)/\1/'`"
if echo "$value" | grep -q "~"
then
echo
echo '*WARNING*: the "~" sign is not expanded in flags.'
echo 'If you mean the home directory, use $HOME instead.'
echo
fi
case "$1" in
--help)
show_help
exit 0
;;
--lua-lib-dir=*)
LUA_LIBDIR="$value"
;;
--with-squish=*)
SQUISH="$value"
;;
--prosody-rev=*)
PROSODY_REV="$value"
PROSODY_REV_SET=yes
;;
--prosody-url=*)
PROSODY_URL="$value"
PROSODY_URL_SET=yes
;;
*)
echo "Error: Unknown flag: $1"
exit 1
;;
esac
shift
done
# Sanity-check options
if ! test -x "$SQUISH"; then
echo "FATAL: Unable to find/use squish: $SQUISH";
exit 1;
fi
if [ "$PROSODY_URL_SET" = "yes" -a "$PROSODY_REV_SET" = "yes" ]; then
echo "FATAL: You can only specify one of --prosody-rev and --prosody-url, not both"
exit 1;
fi
if [ "$PROSODY_REV_SET" = "yes" ]; then
PROSODY_URL="https://hg.prosody.im/trunk/raw-file/${PROSODY_REV}/"
fi
cat <<EOF >config.unix
# This file was automatically generated by the configure script.
# Run "./configure --help" for details.
SQUISH=./buildscripts/squish
PROSODY_URL=$PROSODY_URL
LUA_DIR=$LUA_DIR
EOF
echo
echo "Using squish from: $SQUISH"
echo "Installing verse.lua to: $LUA_DIR"
echo "Fetching Prosody files from: $PROSODY_URL"
echo
echo "Configured successfully. Please run 'make' to proceed."
<file_sep>-- Change these:
local jid, password = "<EMAIL>", "<PASSWORD>";
-- This line squishes verse each time you run,
-- handy if you're hacking on Verse itself
--os.execute("squish --minify-level=none");
require "verse".init("client");
c = verse.new();
c:add_plugin("pubsub");
-- Add some hooks for debugging
c:hook("opened", function () print("Stream opened!") end);
c:hook("closed", function () print("Stream closed!") end);
c:hook("stanza", function (stanza) print("Stanza:", stanza) end);
-- This one prints all received data
c:hook("incoming-raw", print, 1000);
-- Print a message after authentication
c:hook("authentication-success", function () print("Logged in!"); end);
c:hook("authentication-failure", function (err) print("Failed to log in! Error: "..tostring(err.condition)); end);
-- Print a message and exit when disconnected
c:hook("disconnected", function () print("Disconnected!"); os.exit(); end);
-- Now, actually start the connection:
c:connect_client(jid, password);
-- Catch the "ready" event to know when the stream is ready to use
c:hook("ready", function ()
print("Stream ready!");
-- Create a reference to a node
local node = c.pubsub("pubsub.shakespeare.lit", "princely_musings");
-- Callback for when something is published to the node
node:hook(function(event)
print(event.item)
end);
node:subscribe() -- so we actually get the notifications that above callback would get
node:publish(
nil, -- no id, so the service should give us one
nil, -- no options (not supported at the time of this writing)
verse.stanza("something", { xmlns = "http://example.com/pubsub-thingy" }) -- the actual payload, would turn up in event.item above
:tag("foobar"),
function(success) -- callback
print("publish", success and "success" or "failure")
end)
end);
print("Starting loop...")
verse.loop()
<file_sep>-- Change these:
local jid, password = "<EMAIL>/receiver", "<PASSWORD>";
-- This line squishes verse each time you run,
-- handy if you're hacking on Verse itself
--os.execute("squish --minify-level=none");
require "verse".init("client");
c = verse.new(verse.logger())
c:add_plugin("version");
c:add_plugin("disco");
c:add_plugin("proxy65");
c:add_plugin("jingle");
c:add_plugin("jingle_ft");
c:add_plugin("jingle_s5b");
-- Add some hooks for debugging
c:hook("opened", function () print("Stream opened!") end);
c:hook("closed", function () print("Stream closed!") end);
c:hook("stanza", function (stanza) print("Stanza:", stanza) end, 15);
-- This one prints all received data
--c:hook("incoming-raw", function (...) print("<<", ...) end, 1000);
-- Print a message after authentication
c:hook("authentication-success", function () print("Logged in!"); end);
c:hook("authentication-failure", function (err) print("Failed to log in! Error: "..tostring(err.condition)); end);
-- Print a message and exit when disconnected
c:hook("disconnected", function () print("Disconnected!"); os.exit(); end);
-- Now, actually start the connection:
c:connect_client(jid, password);
-- Catch the "ready" event to know when the stream is ready to use
c:hook("ready", function ()
print("Stream ready!");
-- Handle incoming Jingle requests
c:hook("jingle", function (jingle)
if jingle.content.type == "file" then
print("File offer from "..jingle.peer.."!");
print("Filename: "..jingle.content.file.name.." Size: "..jingle.content.file.size);
jingle:accept({ save_file = jingle.content.file.name..".received" });
end
end);
c:send(verse.presence()
:tag("status"):text("Send me a file!"):up()
:add_child(c:caps())
);
end);
print("Starting loop...")
verse.loop()
<file_sep>local verse = require "verse";
function verse.plugins.keepalive(stream)
stream.keepalive_timeout = stream.keepalive_timeout or 300;
verse.add_task(stream.keepalive_timeout, function ()
stream.conn:write(" ");
return stream.keepalive_timeout;
end);
end
<file_sep>local verse = require "verse";
local vcard = require "util.vcard";
local xmlns_vcard = "vcard-temp";
function verse.plugins.vcard(stream)
function stream:get_vcard(jid, callback) --jid = nil for self
stream:send_iq(verse.iq({to = jid, type="get"})
:tag("vCard", {xmlns=xmlns_vcard}), callback and function(stanza)
local vCard = stanza:get_child("vCard", xmlns_vcard);
if stanza.attr.type == "result" and vCard then
vCard = vcard.from_xep54(vCard)
callback(vCard)
else
callback(false) -- FIXME add error
end
end or nil);
end
function stream:set_vcard(aCard, callback)
local xCard;
if type(aCard) == "table" and aCard.name then
xCard = aCard;
elseif type(aCard) == "string" then
xCard = vcard.to_xep54(vcard.from_text(aCard)[1]);
elseif type(aCard) == "table" then
xCard = vcard.to_xep54(aCard);
error("Converting a table to vCard not implemented")
end
if not xCard then return false end
stream:debug("setting vcard to %s", tostring(xCard));
stream:send_iq(verse.iq({type="set"})
:add_child(xCard), callback);
end
end
<file_sep>local verse = require "verse";
local xmlns_browsing = "urn:xmpp:browsing:0";
function verse.plugins.browsing(stream)
stream:add_plugin("pep");
function stream:browsing(infos, callback)
if type(infos) == "string" then
infos = { uri = infos; };
end
local link = verse.stanza("page", {xmlns=xmlns_browsing})
for info, value in pairs(infos) do
link:tag(info):text(value):up();
end
return stream:publish_pep(link, callback);
end
stream:hook_pep(xmlns_browsing, function(event)
local item = event.item;
return stream:event("browsing", {
from = event.from;
description = item:get_child_text"description";
keywords = item:get_child_text"keywords";
title = item:get_child_text"title";
uri = item:get_child_text"uri";
});
end);
end
<file_sep>-- Prosody IM
-- Copyright (C) 2008-2014 <NAME>
-- Copyright (C) 2008-2014 <NAME>
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local urandom = io.open("/dev/urandom", "r");
if urandom then
return {
seed = function () end;
bytes = function (n) return urandom:read(n); end
};
end
local crypto = require "crypto"
return crypto.rand;
<file_sep>local xmlns_carbons = "urn:xmpp:carbons:1";
local xmlns_forward = "urn:xmpp:forward:0";
local function datetime(t) return os_date("!%Y-%m-%dT%H:%M:%SZ", t); end
-- This line squishes verse each time you run,
-- handy if you're hacking on Verse itself
--os.execute("squish --minify-level=none verse");
require "verse".init("client");
c = verse.new();--verse.logger());
c:add_plugin "carbons"
c:hook("disconnected", verse.quit);
local jid, password = unpack(arg);
assert(jid and password, "You need to supply JID and password as arguments");
c:connect_client(jid, password);
-- Print a message after authentication
c:hook("authentication-success", function () c:debug("Logged in!"); end);
c:hook("authentication-failure", function (err)
c:error("Failed to log in! Error: "..tostring(err.condition));
c:close();
end);
c:hook("carbon", function(carbon)
local dir, ts, st = carbon.dir, carbon.timestamp, carbon.stanza;
print("", datetime(ts), dir:upper());
print(st);
end);
-- Catch the "ready" event to know when the stream is ready to use
c:hook("ready", function ()
c:debug("Connected");
c.carbons:enable(function(ok)
if ok then
c:debug("Carbons enabled")
else
c:error("Could not enable carbons, aborting");
c:close();
end
end);
end);
verse.loop()
<file_sep>local verse = require "verse";
local timer = require "util.timer";
local uuid_generate = require "util.uuid".generate;
local xmlns_jingle = "urn:xmpp:jingle:1";
local xmlns_jingle_errors = "urn:xmpp:jingle:errors:1";
local jingle_mt = {};
jingle_mt.__index = jingle_mt;
local registered_transports = {};
local registered_content_types = {};
function verse.plugins.jingle(stream)
stream:hook("ready", function ()
stream:add_disco_feature(xmlns_jingle);
end, 10);
function stream:jingle(to)
return verse.eventable(setmetatable(base or {
role = "initiator";
peer = to;
sid = uuid_generate();
stream = stream;
}, jingle_mt));
end
function stream:register_jingle_transport(transport)
-- transport is a function that receives a
-- <transport> element, and returns a connection
-- We wait for 'connected' on that connection,
-- and use :send() and 'incoming-raw'.
end
function stream:register_jingle_content_type(content)
-- Call content() for every 'incoming-raw'?
-- I think content() returns the object we return
-- on jingle:accept()
end
local function handle_incoming_jingle(stanza)
local jingle_tag = stanza:get_child("jingle", xmlns_jingle);
local sid = jingle_tag.attr.sid;
local action = jingle_tag.attr.action;
local result = stream:event("jingle/"..sid, stanza);
if result == true then
-- Ack
stream:send(verse.reply(stanza));
return true;
end
-- No existing Jingle object handled this action, our turn...
if action ~= "session-initiate" then
-- Trying to send a command to a session we don't know
local reply = verse.error_reply(stanza, "cancel", "item-not-found")
:tag("unknown-session", { xmlns = xmlns_jingle_errors }):up();
stream:send(reply);
return;
end
-- Ok, session-initiate, new session
-- Create new Jingle object
local sid = jingle_tag.attr.sid;
local jingle = verse.eventable{
role = "receiver";
peer = stanza.attr.from;
sid = sid;
stream = stream;
};
setmetatable(jingle, jingle_mt);
local content_tag;
local content, transport;
for tag in jingle_tag:childtags() do
if tag.name == "content" and tag.attr.xmlns == xmlns_jingle then
local description_tag = tag:child_with_name("description");
local description_xmlns = description_tag.attr.xmlns;
if description_xmlns then
local desc_handler = stream:event("jingle/content/"..description_xmlns, jingle, description_tag);
if desc_handler then
content = desc_handler;
end
end
local transport_tag = tag:child_with_name("transport");
local transport_xmlns = transport_tag.attr.xmlns;
transport = stream:event("jingle/transport/"..transport_xmlns, jingle, transport_tag);
if content and transport then
content_tag = tag;
break;
end
end
end
if not content then
-- FIXME: Fail, no content
stream:send(verse.error_reply(stanza, "cancel", "feature-not-implemented", "The specified content is not supported"));
return true;
end
if not transport then
-- FIXME: Refuse session, no transport
stream:send(verse.error_reply(stanza, "cancel", "feature-not-implemented", "The specified transport is not supported"));
return true;
end
stream:send(verse.reply(stanza));
jingle.content_tag = content_tag;
jingle.creator, jingle.name = content_tag.attr.creator, content_tag.attr.name;
jingle.content, jingle.transport = content, transport;
function jingle:decline()
-- FIXME: Decline session
end
stream:hook("jingle/"..sid, function (stanza)
if stanza.attr.from ~= jingle.peer then
return false;
end
local jingle_tag = stanza:get_child("jingle", xmlns_jingle);
return jingle:handle_command(jingle_tag);
end);
stream:event("jingle", jingle);
return true;
end
function jingle_mt:handle_command(jingle_tag)
local action = jingle_tag.attr.action;
stream:debug("Handling Jingle command: %s", action);
if action == "session-terminate" then
self:destroy();
elseif action == "session-accept" then
-- Yay!
self:handle_accepted(jingle_tag);
elseif action == "transport-info" then
stream:debug("Handling transport-info");
self.transport:info_received(jingle_tag);
elseif action == "transport-replace" then
-- FIXME: Used for IBB fallback
stream:error("Peer wanted to swap transport, not implemented");
else
-- FIXME: Reply unhandled command
stream:warn("Unhandled Jingle command: %s", action);
return nil;
end
return true;
end
function jingle_mt:send_command(command, element, callback)
local stanza = verse.iq({ to = self.peer, type = "set" })
:tag("jingle", {
xmlns = xmlns_jingle,
sid = self.sid,
action = command,
initiator = self.role == "initiator" and self.stream.jid or nil,
responder = self.role == "responder" and self.jid or nil,
}):add_child(element);
if not callback then
self.stream:send(stanza);
else
self.stream:send_iq(stanza, callback);
end
end
function jingle_mt:accept(options)
local accept_stanza = verse.iq({ to = self.peer, type = "set" })
:tag("jingle", {
xmlns = xmlns_jingle,
sid = self.sid,
action = "session-accept",
responder = stream.jid,
})
:tag("content", { creator = self.creator, name = self.name });
local content_accept_tag = self.content:generate_accept(self.content_tag:child_with_name("description"), options);
accept_stanza:add_child(content_accept_tag);
local transport_accept_tag = self.transport:generate_accept(self.content_tag:child_with_name("transport"), options);
accept_stanza:add_child(transport_accept_tag);
local jingle = self;
stream:send_iq(accept_stanza, function (result)
if result.attr.type == "error" then
local type, condition, text = result:get_error();
stream:error("session-accept rejected: %s", condition); -- FIXME: Notify
return false;
end
jingle.transport:connect(function (conn)
stream:warn("CONNECTED (receiver)!!!");
jingle.state = "active";
jingle:event("connected", conn);
end);
end);
end
stream:hook("iq/"..xmlns_jingle, handle_incoming_jingle);
return true;
end
function jingle_mt:offer(name, content)
local session_initiate = verse.iq({ to = self.peer, type = "set" })
:tag("jingle", { xmlns = xmlns_jingle, action = "session-initiate",
initiator = self.stream.jid, sid = self.sid });
-- Content tag
session_initiate:tag("content", { creator = self.role, name = name });
-- Need description element from someone who can turn 'content' into XML
local description = self.stream:event("jingle/describe/"..name, content);
if not description then
return false, "Unknown content type";
end
session_initiate:add_child(description);
-- FIXME: Sort transports by 1) recipient caps 2) priority (SOCKS vs IBB, etc.)
-- Fixed to s5b in the meantime
local transport = self.stream:event("jingle/transport/".."urn:xmpp:jingle:transports:s5b:1", self);
self.transport = transport;
session_initiate:add_child(transport:generate_initiate());
self.stream:debug("Hooking %s", "jingle/"..self.sid);
self.stream:hook("jingle/"..self.sid, function (stanza)
if stanza.attr.from ~= self.peer then
return false;
end
local jingle_tag = stanza:get_child("jingle", xmlns_jingle);
return self:handle_command(jingle_tag)
end);
self.stream:send_iq(session_initiate, function (result)
if result.attr.type == "error" then
self.state = "terminated";
local type, condition, text = result:get_error();
return self:event("error", { type = type, condition = condition, text = text });
end
end);
self.state = "pending";
end
function jingle_mt:terminate(reason)
local reason_tag = verse.stanza("reason"):tag(reason or "success");
self:send_command("session-terminate", reason_tag, function (result)
self.state = "terminated";
self.transport:disconnect();
self:destroy();
end);
end
function jingle_mt:destroy()
self:event("terminated");
self.stream:unhook("jingle/"..self.sid, self.handle_command);
end
function jingle_mt:handle_accepted(jingle_tag)
local transport_tag = jingle_tag:child_with_name("transport");
self.transport:handle_accepted(transport_tag);
self.transport:connect(function (conn)
self.stream:debug("CONNECTED (initiator)!")
-- Connected, send file
self.state = "active";
self:event("connected", conn);
end);
end
function jingle_mt:set_source(source, auto_close)
local function pump()
local chunk, err = source();
if chunk and chunk ~= "" then
self.transport.conn:send(chunk);
elseif chunk == "" then
return pump(); -- We need some data!
elseif chunk == nil then
if auto_close then
self:terminate();
end
self.transport.conn:unhook("drained", pump);
source = nil;
end
end
self.transport.conn:hook("drained", pump);
pump();
end
function jingle_mt:set_sink(sink)
self.transport.conn:hook("incoming-raw", sink);
self.transport.conn:hook("disconnected", function (event)
self.stream:debug("Closing sink...");
local reason = event.reason;
if reason == "closed" then reason = nil; end
sink(nil, reason);
end);
end
<file_sep>include config.unix
ifndef SQUISH
$(error Please run ./configure first)
endif
SOURCE_FILES=$(shell $(SQUISH) --list-files)
MISSING_FILES=$(shell $(SQUISH) --list-missing-files)
all: verse.lua
verse.lua: $(SOURCE_FILES)
$(SQUISH)
install: verse.lua
install -t $(LUA_DIR) -m 644 $^
clean:
rm verse.lua
$(MISSING_FILES):
mkdir -p "$(@D)"
wget "$(PROSODY_URL)$@" -O "$@"
rsm.lib.lua:
wget https://hg.prosody.im/prosody-0.10/raw-file/0.10.1/util/rsm.lua -O rsm.lib.lua
release: $(MISSING_FILES)
rm config.unix
.PHONY: all release clean install
<file_sep>local verse = require "verse";
local bare_jid = require "util.jid".bare;
local xmlns_roster = "jabber:iq:roster";
local xmlns_rosterver = "urn:xmpp:features:rosterver";
local t_insert = table.insert;
function verse.plugins.roster(stream)
local ver_supported = false;
local roster = {
items = {};
ver = "";
-- TODO:
-- groups = {};
};
stream.roster = roster;
stream:hook("stream-features", function(features_stanza)
if features_stanza:get_child("ver", xmlns_rosterver) then
ver_supported = true;
end
end);
local function item_lua2xml(item_table)
local xml_item = verse.stanza("item", { xmlns = xmlns_roster });
for k, v in pairs(item_table) do
if k ~= "groups" then
xml_item.attr[k] = v;
else
for i = 1,#v do
xml_item:tag("group"):text(v[i]):up();
end
end
end
return xml_item;
end
local function item_xml2lua(xml_item)
local item_table = { };
local groups = {};
item_table.groups = groups;
for k, v in pairs(xml_item.attr) do
if k ~= "xmlns" then
item_table[k] = v
end
end
for group in xml_item:childtags("group") do
t_insert(groups, group:get_text())
end
return item_table;
end
function roster:load(r)
roster.ver, roster.items = r.ver, r.items;
end
function roster:dump()
return {
ver = roster.ver,
items = roster.items,
};
end
-- should this be add_contact(item, callback) instead?
function roster:add_contact(jid, name, groups, callback)
local item = { jid = jid, name = name, groups = groups };
local stanza = verse.iq({ type = "set" })
:tag("query", { xmlns = xmlns_roster })
:add_child(item_lua2xml(item));
stream:send_iq(stanza, function (reply)
if not callback then return end
if reply.attr.type == "result" then
callback(true);
else
callback(nil, reply);
end
end);
end
-- What about subscriptions?
function roster:delete_contact(jid, callback)
jid = (type(jid) == "table" and jid.jid) or jid;
local item = { jid = jid, subscription = "remove" }
if not roster.items[jid] then return false, "item-not-found"; end
stream:send_iq(verse.iq({ type = "set" })
:tag("query", { xmlns = xmlns_roster })
:add_child(item_lua2xml(item)),
function (reply)
if not callback then return end
if reply.attr.type == "result" then
callback(true);
else
callback(nil, reply);
end
end);
end
local function add_item(item) -- Takes one roster <item/>
local roster_item = item_xml2lua(item);
roster.items[roster_item.jid] = roster_item;
end
-- Private low level
local function delete_item(jid)
local deleted_item = roster.items[jid];
roster.items[jid] = nil;
return deleted_item;
end
function roster:fetch(callback)
stream:send_iq(verse.iq({type="get"}):tag("query", { xmlns = xmlns_roster, ver = ver_supported and roster.ver or nil }),
function (result)
if result.attr.type == "result" then
local query = result:get_child("query", xmlns_roster);
if query then
roster.items = {};
for item in query:childtags("item") do
add_item(item)
end
roster.ver = query.attr.ver or "";
end
callback(roster);
else
callback(nil, result);
end
end);
end
stream:hook("iq/"..xmlns_roster, function(stanza)
local type, from = stanza.attr.type, stanza.attr.from;
if type == "set" and (not from or from == bare_jid(stream.jid)) then
local query = stanza:get_child("query", xmlns_roster);
local item = query and query:get_child("item");
if item then
local event, target;
local jid = item.attr.jid;
if item.attr.subscription == "remove" then
event = "removed"
target = delete_item(jid);
else
event = roster.items[jid] and "changed" or "added";
add_item(item)
target = roster.items[jid];
end
roster.ver = query.attr.ver;
if target then
stream:event("roster/item-"..event, target);
end
-- TODO else return error? Events?
end
stream:send(verse.reply(stanza))
return true;
end
end);
end
<file_sep>local verse = require "verse";
local stream = verse.stream_mt;
local jid_split = require "util.jid".split;
local lxp = require "lxp";
local st = require "util.stanza";
local sha1 = require "util.hashes".sha1;
-- Shortcuts to save having to load util.stanza
verse.message, verse.presence, verse.iq, verse.stanza, verse.reply, verse.error_reply =
st.message, st.presence, st.iq, st.stanza, st.reply, st.error_reply;
local new_xmpp_stream = require "util.xmppstream".new;
local xmlns_stream = "http://etherx.jabber.org/streams";
local xmlns_component = "jabber:component:accept";
local stream_callbacks = {
stream_ns = xmlns_stream,
stream_tag = "stream",
default_ns = xmlns_component };
function stream_callbacks.streamopened(stream, attr)
stream.stream_id = attr.id;
if not stream:event("opened", attr) then
stream.notopen = nil;
end
return true;
end
function stream_callbacks.streamclosed(stream)
return stream:event("closed");
end
function stream_callbacks.handlestanza(stream, stanza)
if stanza.attr.xmlns == xmlns_stream then
return stream:event("stream-"..stanza.name, stanza);
elseif stanza.attr.xmlns or stanza.name == "handshake" then
return stream:event("stream/"..(stanza.attr.xmlns or xmlns_component), stanza);
end
return stream:event("stanza", stanza);
end
function stream:reset()
if self.stream then
self.stream:reset();
else
self.stream = new_xmpp_stream(self, stream_callbacks);
end
self.notopen = true;
return true;
end
function stream:connect_component(jid, pass)
self.jid, self.password = jid, pass;
self.username, self.host, self.resource = jid_split(jid);
function self.data(conn, data)
local ok, err = self.stream:feed(data);
if ok then return; end
stream:debug("Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "));
stream:close("xml-not-well-formed");
end
self:hook("incoming-raw", function (data) return self.data(self.conn, data); end);
self.curr_id = 0;
self.tracked_iqs = {};
self:hook("stanza", function (stanza)
local id, type = stanza.attr.id, stanza.attr.type;
if id and stanza.name == "iq" and (type == "result" or type == "error") and self.tracked_iqs[id] then
self.tracked_iqs[id](stanza);
self.tracked_iqs[id] = nil;
return true;
end
end);
self:hook("stanza", function (stanza)
local ret;
if stanza.attr.xmlns == nil or stanza.attr.xmlns == "jabber:client" then
if stanza.name == "iq" and (stanza.attr.type == "get" or stanza.attr.type == "set") then
local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
if xmlns then
ret = self:event("iq/"..xmlns, stanza);
if not ret then
ret = self:event("iq", stanza);
end
end
if ret == nil then
self:send(verse.error_reply(stanza, "cancel", "service-unavailable"));
return true;
end
else
ret = self:event(stanza.name, stanza);
end
end
return ret;
end, -1);
self:hook("opened", function (attr)
print(self.jid, self.stream_id, attr.id);
local token = sha1(self.stream_id..pass, true);
self:send(st.stanza("handshake", { xmlns = xmlns_component }):text(token));
self:hook("stream/"..xmlns_component, function (stanza)
if stanza.name == "handshake" then
self:event("authentication-success");
end
end);
end);
local function stream_ready()
self:event("ready");
end
self:hook("authentication-success", stream_ready, -1);
-- Initialise connection
self:connect(self.connect_host or self.host, self.connect_port or 5347);
self:reopen();
end
function stream:reopen()
self:reset();
self:send(st.stanza("stream:stream", { to = self.jid, ["xmlns:stream"]='http://etherx.jabber.org/streams',
xmlns = xmlns_component, version = "1.0" }):top_tag());
end
function stream:close(reason)
if not self.notopen then
self:send("</stream:stream>");
end
local on_disconnect = self.conn.disconnect();
self.conn:close();
on_disconnect(conn, reason);
end
function stream:send_iq(iq, callback)
local id = self:new_id();
self.tracked_iqs[id] = callback;
iq.attr.id = id;
self:send(iq);
end
function stream:new_id()
self.curr_id = self.curr_id + 1;
return tostring(self.curr_id);
end
<file_sep>
return function (stream, name)
if name == "ANONYMOUS" then
return function ()
return coroutine.yield() == "success";
end, 0;
end
end
<file_sep>local verse = require "verse";
local now = require"socket".gettime;
local xmlns_sm = "urn:xmpp:sm:3";
function verse.plugins.smacks(stream)
-- State for outgoing stanzas
local outgoing_queue = {};
local last_ack = 0;
local last_stanza_time = now();
local timer_active;
-- State for incoming stanzas
local handled_stanza_count = 0;
-- Catch incoming stanzas
local function incoming_stanza(stanza)
if stanza.attr.xmlns == "jabber:client" or not stanza.attr.xmlns then
handled_stanza_count = handled_stanza_count + 1;
stream:debug("Increasing handled stanzas to %d for %s", handled_stanza_count, stanza:top_tag());
end
end
-- Catch outgoing stanzas
local function outgoing_stanza(stanza)
-- NOTE: This will not behave nice if stanzas are serialized before this point
if stanza.name and not stanza.attr.xmlns then
-- serialize stanzas in order to bypass this on resumption
outgoing_queue[#outgoing_queue+1] = tostring(stanza);
last_stanza_time = now();
if not timer_active then
timer_active = true;
stream:debug("Waiting to send ack request...");
verse.add_task(1, function()
if #outgoing_queue == 0 then
timer_active = false;
return;
end
local time_since_last_stanza = now() - last_stanza_time;
if time_since_last_stanza < 1 and #outgoing_queue < 10 then
return 1 - time_since_last_stanza;
end
stream:debug("Time up, sending <r>...");
timer_active = false;
stream:send(verse.stanza("r", { xmlns = xmlns_sm }));
end);
end
end
end
local function on_disconnect()
stream:debug("smacks: connection lost");
stream.stream_management_supported = nil;
if stream.resumption_token then
stream:debug("smacks: have resumption token, reconnecting in 1s...");
stream.authenticated = nil;
verse.add_task(1, function ()
stream:connect(stream.connect_host or stream.host, stream.connect_port or 5222);
end);
return true;
end
end
-- Graceful shutdown
local function on_close()
stream.resumption_token = nil;
stream:unhook("disconnected", on_disconnect);
end
local function handle_sm_command(stanza)
if stanza.name == "r" then -- Request for acks for stanzas we received
stream:debug("Ack requested... acking %d handled stanzas", handled_stanza_count);
stream:send(verse.stanza("a", { xmlns = xmlns_sm, h = tostring(handled_stanza_count) }));
elseif stanza.name == "a" then -- Ack for stanzas we sent
local new_ack = tonumber(stanza.attr.h);
if new_ack > last_ack then
local old_unacked = #outgoing_queue;
for i=last_ack+1,new_ack do
table.remove(outgoing_queue, 1);
end
stream:debug("Received ack: New ack: "..new_ack.." Last ack: "..last_ack.." Unacked stanzas now: "..#outgoing_queue.." (was "..old_unacked..")");
last_ack = new_ack;
else
stream:warn("Received bad ack for "..new_ack.." when last ack was "..last_ack);
end
elseif stanza.name == "enabled" then
if stanza.attr.id then
stream.resumption_token = stanza.attr.id;
stream:hook("closed", on_close, 100);
stream:hook("disconnected", on_disconnect, 100);
end
elseif stanza.name == "resumed" then
local new_ack = tonumber(stanza.attr.h);
if new_ack > last_ack then
local old_unacked = #outgoing_queue;
for i=last_ack+1,new_ack do
table.remove(outgoing_queue, 1);
end
stream:debug("Received ack: New ack: "..new_ack.." Last ack: "..last_ack.." Unacked stanzas now: "..#outgoing_queue.." (was "..old_unacked..")");
last_ack = new_ack;
end
for i=1,#outgoing_queue do
stream:send(outgoing_queue[i]);
end
outgoing_queue = {};
stream:debug("Resumed successfully");
stream:event("resumed");
else
stream:warn("Don't know how to handle "..xmlns_sm.."/"..stanza.name);
end
end
local function on_bind_success()
if not stream.smacks then
--stream:unhook("bind-success", on_bind_success);
stream:debug("smacks: sending enable");
stream:send(verse.stanza("enable", { xmlns = xmlns_sm, resume = "true" }));
stream.smacks = true;
-- Catch stanzas
stream:hook("stanza", incoming_stanza);
stream:hook("outgoing", outgoing_stanza);
end
end
local function on_features(features)
if features:get_child("sm", xmlns_sm) then
stream.stream_management_supported = true;
if stream.smacks and stream.bound then -- Already enabled in a previous session - resume
stream:debug("Resuming stream with %d handled stanzas", handled_stanza_count);
stream:send(verse.stanza("resume", { xmlns = xmlns_sm,
h = handled_stanza_count, previd = stream.resumption_token }));
return true;
else
stream:hook("bind-success", on_bind_success, 1);
end
end
end
stream:hook("stream-features", on_features, 250);
stream:hook("stream/"..xmlns_sm, handle_sm_command);
--stream:hook("ready", on_stream_ready, 500);
end
<file_sep>local verse = require "verse";
local ltn12 = require "ltn12";
local dirsep = package.config:sub(1,1);
local xmlns_jingle_ft = "urn:xmpp:jingle:apps:file-transfer:4";
function verse.plugins.jingle_ft(stream)
stream:hook("ready", function ()
stream:add_disco_feature(xmlns_jingle_ft);
end, 10);
local ft_content = { type = "file" };
function ft_content:generate_accept(description, options)
if options and options.save_file then
self.jingle:hook("connected", function ()
local sink = ltn12.sink.file(io.open(options.save_file, "w+"));
self.jingle:set_sink(sink);
end);
end
return description;
end
local ft_mt = { __index = ft_content };
stream:hook("jingle/content/"..xmlns_jingle_ft, function (jingle, description_tag)
local file_tag = description_tag:get_child("file");
local file = {
name = file_tag:get_child_text("name");
size = tonumber(file_tag:get_child_text("size"));
desc = file_tag:get_child_text("desc");
date = file_tag:get_child_text("date");
};
return setmetatable({ jingle = jingle, file = file }, ft_mt);
end);
stream:hook("jingle/describe/file", function (file_info)
-- Return <description/>
local date;
if file_info.timestamp then
date = os.date("!%Y-%m-%dT%H:%M:%SZ", file_info.timestamp);
end
return verse.stanza("description", { xmlns = xmlns_jingle_ft })
:tag("file")
:tag("name"):text(file_info.filename):up()
:tag("size"):text(tostring(file_info.size)):up()
:tag("date"):text(date):up()
:tag("desc"):text(file_info.description):up()
:up();
end);
function stream:send_file(to, filename)
local file, err = io.open(filename);
if not file then return file, err; end
local file_size = file:seek("end", 0);
file:seek("set", 0);
local source = ltn12.source.file(file);
local jingle = self:jingle(to);
jingle:offer("file", {
filename = filename:match("[^"..dirsep.."]+$");
size = file_size;
});
jingle:hook("connected", function ()
jingle:set_source(source, true);
end);
return jingle;
end
end
<file_sep>local verse = require "verse";
-- local xmlns_vcard = "vcard-temp";
local xmlns_vcard_update = "vcard-temp:x:update";
local sha1 = require("util.hashes").sha1;
local ok, fun = pcall(function()
local unb64 = require("util.encodings").base64.decode;
assert(unb64("SGVsbG8=") == "Hello")
return unb64;
end);
if not ok then
ok, fun = pcall(function() return require("mime").unb64; end);
if not ok then
error("Could not find a base64 decoder")
end
end
local unb64 = fun;
function verse.plugins.vcard_update(stream)
stream:add_plugin("vcard");
stream:add_plugin("presence");
local x_vcard_update;
local function update_vcard_photo(vCard)
local data;
for i=1,#vCard do
if vCard[i].name == "PHOTO" then
data = vCard[i][1];
break
end
end
if data then
local hash = sha1(unb64(data), true);
x_vcard_update = verse.stanza("x", { xmlns = xmlns_vcard_update })
:tag("photo"):text(hash);
stream:resend_presence()
else
x_vcard_update = nil;
end
end
--[[ TODO Complete this, it's probably broken.
-- Maybe better to hook outgoing stanza?
local _set_vcard = stream.set_vcard;
function stream:set_vcard(vCard, callback)
_set_vcard(vCard, function(event, ...)
if event.attr.type == "result" then
local vCard_ = response:get_child("vCard", xmlns_vcard);
if vCard_ then
update_vcard_photo(vCard_);
end -- Or fetch it again? Seems wasteful, but if the server overrides stuff? :/
end
if callback then
return callback(event, ...);
end
end);
end
--]]
local initial_vcard_fetch_started;
stream:hook("ready", function()
if initial_vcard_fetch_started then return; end
initial_vcard_fetch_started = true;
-- if stream:jid_supports(nil, xmlns_vcard) then TODO this, correctly
stream:get_vcard(nil, function(response)
if response then
update_vcard_photo(response)
end
stream:event("ready");
end);
return true;
end, 3);
stream:hook("presence-out", function(presence)
if x_vcard_update and not presence:get_child("x", xmlns_vcard_update) then
presence:add_child(x_vcard_update);
end
end, 10);
--[[
stream:hook("presence", function(presence)
local x_vcard_update = presence:get_child("x", xmlns_vcard_update);
local photo_hash = x_vcard_update and x_vcard_update:get_child("photo");
:get_child_text("photo");
if x_vcard_update then
-- TODO Cache peoples avatars here
end
end);
--]]
end
<file_sep>
local new_xmpp_stream = require "util.xmppstream".new;
local st = require "util.stanza";
require "net.httpclient_listener"; -- Required for net.http to work
local http = require "net.http";
local stream_mt = setmetatable({}, { __index = verse.stream_mt });
stream_mt.__index = stream_mt;
local xmlns_stream = "http://etherx.jabber.org/streams";
local xmlns_bosh = "http://jabber.org/protocol/httpbind";
local reconnect_timeout = 5;
function verse.new_bosh(logger, url)
local stream = {
bosh_conn_pool = {};
bosh_waiting_requests = {};
bosh_rid = math.random(1,999999);
bosh_outgoing_buffer = {};
bosh_url = url;
conn = {};
};
function stream:reopen()
self.bosh_need_restart = true;
self:flush();
end
local conn = verse.new(logger, stream);
return setmetatable(conn, stream_mt);
end
function stream_mt:connect()
self:_send_session_request();
end
function stream_mt:send(data)
self:debug("Putting into BOSH send buffer: %s", tostring(data));
self.bosh_outgoing_buffer[#self.bosh_outgoing_buffer+1] = st.clone(data);
self:flush(); --TODO: Optimize by doing this on next tick (give a chance for data to buffer)
end
function stream_mt:flush()
if self.connected
and #self.bosh_waiting_requests < self.bosh_max_requests
and (#self.bosh_waiting_requests == 0
or #self.bosh_outgoing_buffer > 0
or self.bosh_need_restart) then
self:debug("Flushing...");
local payload = self:_make_body();
local buffer = self.bosh_outgoing_buffer;
for i, stanza in ipairs(buffer) do
payload:add_child(stanza);
buffer[i] = nil;
end
self:_make_request(payload);
else
self:debug("Decided not to flush.");
end
end
function stream_mt:_make_request(payload)
local request, err = http.request(self.bosh_url, { body = tostring(payload) }, function (response, code, request)
if code ~= 0 then
self.inactive_since = nil;
return self:_handle_response(response, code, request);
end
-- Connection issues, we need to retry this request
local time = os.time();
if not self.inactive_since then
self.inactive_since = time; -- So we know when it is time to give up
elseif time - self.inactive_since > self.bosh_max_inactivity then
return self:_disconnected();
else
self:debug("%d seconds left to reconnect, retrying in %d seconds...",
self.bosh_max_inactivity - (time - self.inactive_since), reconnect_timeout);
end
-- Set up reconnect timer
timer.add_task(reconnect_timeout, function ()
self:debug("Retrying request...");
-- Remove old request
for i, waiting_request in ipairs(self.bosh_waiting_requests) do
if waiting_request == request then
table.remove(self.bosh_waiting_requests, i);
break;
end
end
self:_make_request(payload);
end);
end);
if request then
table.insert(self.bosh_waiting_requests, request);
else
self:warn("Request failed instantly: %s", err);
end
end
function stream_mt:_disconnected()
self.connected = nil;
self:event("disconnected");
end
function stream_mt:_send_session_request()
local body = self:_make_body();
-- XEP-0124
body.attr.hold = "1";
body.attr.wait = "60";
body.attr["xml:lang"] = "en";
body.attr.ver = "1.6";
-- XEP-0206
body.attr.from = self.jid;
body.attr.to = self.host;
body.attr.secure = 'true';
http.request(self.bosh_url, { body = tostring(body) }, function (response, code)
if code == 0 then
-- Failed to connect
return self:_disconnected();
end
-- Handle session creation response
local payload = self:_parse_response(response)
if not payload then
self:warn("Invalid session creation response");
self:_disconnected();
return;
end
self.bosh_sid = payload.attr.sid; -- Session id
self.bosh_wait = tonumber(payload.attr.wait); -- How long the server may hold connections for
self.bosh_hold = tonumber(payload.attr.hold); -- How many connections the server may hold
self.bosh_max_inactivity = tonumber(payload.attr.inactivity); -- Max amount of time with no connections
self.bosh_max_requests = tonumber(payload.attr.requests) or self.bosh_hold; -- Max simultaneous requests we can make
self.connected = true;
self:event("connected");
self:_handle_response_payload(payload);
end);
end
function stream_mt:_handle_response(response, code, request)
if self.bosh_waiting_requests[1] ~= request then
self:warn("Server replied to request that wasn't the oldest");
for i, waiting_request in ipairs(self.bosh_waiting_requests) do
if waiting_request == request then
self.bosh_waiting_requests[i] = nil;
break;
end
end
else
table.remove(self.bosh_waiting_requests, 1);
end
local payload = self:_parse_response(response);
if payload then
self:_handle_response_payload(payload);
end
self:flush();
end
function stream_mt:_handle_response_payload(payload)
local stanzas = payload.tags;
for i = 1, #stanzas do
local stanza = stanzas[i];
if stanza.attr.xmlns == xmlns_stream then
self:event("stream-"..stanza.name, stanza);
elseif stanza.attr.xmlns then
self:event("stream/"..stanza.attr.xmlns, stanza);
else
self:event("stanza", stanza);
end
end
if payload.attr.type == "terminate" then
self:_disconnected({reason = payload.attr.condition});
end
end
local stream_callbacks = {
stream_ns = "http://jabber.org/protocol/httpbind", stream_tag = "body",
default_ns = "jabber:client",
streamopened = function (session, attr) session.notopen = nil; session.payload = verse.stanza("body", attr); return true; end;
handlestanza = function (session, stanza) session.payload:add_child(stanza); end;
};
function stream_mt:_parse_response(response)
self:debug("Parsing response: %s", response);
if response == nil then
self:debug("%s", debug.traceback());
self:_disconnected();
return;
end
local session = { notopen = true, stream = self };
local stream = new_xmpp_stream(session, stream_callbacks);
stream:feed(response);
return session.payload;
end
function stream_mt:_make_body()
self.bosh_rid = self.bosh_rid + 1;
local body = verse.stanza("body", {
xmlns = xmlns_bosh;
content = "text/xml; charset=utf-8";
sid = self.bosh_sid;
rid = self.bosh_rid;
});
if self.bosh_need_restart then
self.bosh_need_restart = nil;
body.attr.restart = 'true';
end
return body;
end
<file_sep>local verse = require "verse";
local gettime = require"socket".gettime;
local xmlns_ping = "urn:xmpp:ping";
function verse.plugins.ping(stream)
function stream:ping(jid, callback)
local t = gettime();
stream:send_iq(verse.iq{ to = jid, type = "get" }:tag("ping", { xmlns = xmlns_ping }),
function (reply)
if reply.attr.type == "error" then
local type, condition, text = reply:get_error();
if condition ~= "service-unavailable" and condition ~= "feature-not-implemented" then
callback(nil, jid, { type = type, condition = condition, text = text });
return;
end
end
callback(gettime()-t, jid);
end);
end
stream:hook("iq/"..xmlns_ping, function(stanza)
return stream:send(verse.reply(stanza));
end);
return true;
end
<file_sep>local verse = require "verse";
local xmlns_version = "jabber:iq:version";
local function set_version(self, version_info)
self.name = version_info.name;
self.version = version_info.version;
self.platform = version_info.platform;
end
function verse.plugins.version(stream)
stream.version = { set = set_version };
stream:hook("iq/"..xmlns_version, function (stanza)
if stanza.attr.type ~= "get" then return; end
local reply = verse.reply(stanza)
:tag("query", { xmlns = xmlns_version });
if stream.version.name then
reply:tag("name"):text(tostring(stream.version.name)):up();
end
if stream.version.version then
reply:tag("version"):text(tostring(stream.version.version)):up()
end
if stream.version.platform then
reply:tag("os"):text(stream.version.platform);
end
stream:send(reply);
return true;
end);
function stream:query_version(target_jid, callback)
callback = callback or function (version) return self:event("version/response", version); end
self:send_iq(verse.iq({ type = "get", to = target_jid })
:tag("query", { xmlns = xmlns_version }),
function (reply)
if reply.attr.type == "result" then
local query = reply:get_child("query", xmlns_version);
local name = query and query:get_child_text("name");
local version = query and query:get_child_text("version");
local os = query and query:get_child_text("os");
callback({
name = name;
version = version;
platform = os;
});
else
local type, condition, text = reply:get_error();
callback({
error = true;
condition = condition;
text = text;
type = type;
});
end
end);
end
return true;
end
<file_sep>
local function not_available(_, method_name)
error("Hash method "..method_name.." not available", 2);
end
local _M = setmetatable({}, { __index = not_available });
local function with(mod, f)
local ok, pkg = pcall(require, mod);
if ok then f(pkg); end
end
with("bgcrypto.md5", function (md5)
_M.md5 = md5.digest;
_M.hmac_md5 = md5.hmac.digest;
end);
with("bgcrypto.sha1", function (sha1)
_M.sha1 = sha1.digest;
_M.hmac_sha1 = sha1.hmac.digest;
_M.scram_Hi_sha1 = function (p, s, i) return sha1.pbkdf2(p, s, i, 20); end;
end);
with("bgcrypto.sha256", function (sha256)
_M.sha256 = sha256.digest;
_M.hmac_sha256 = sha256.hmac.digest;
end);
with("bgcrypto.sha512", function (sha512)
_M.sha512 = sha512.digest;
_M.hmac_sha512 = sha512.hmac.digest;
end);
with("sha1", function (sha1)
_M.sha1 = function (data, hex)
if hex then
return sha1.sha1(data);
else
return (sha1.binary(data));
end
end;
end);
return _M;
<file_sep>local verse = require "verse";
local xmlns_register = "jabber:iq:register";
function verse.plugins.register(stream)
local function handle_features(features_stanza)
if features_stanza:get_child("register", "http://jabber.org/features/iq-register") then
local request = verse.iq({ to = stream.host_, type = "set" })
:tag("query", { xmlns = xmlns_register })
:tag("username"):text(stream.username):up()
:tag("password"):text(stream.password):up();
if stream.register_email then
request:tag("email"):text(stream.register_email):up();
end
stream:send_iq(request, function (result)
if result.attr.type == "result" then
stream:event("registration-success");
else
local type, condition, text = result:get_error();
stream:debug("Registration failed: %s", condition);
stream:event("registration-failure", { type = type, condition = condition, text = text });
end
end);
else
stream:debug("In-band registration not offered by server");
stream:event("registration-failure", { condition = "service-unavailable" });
end
stream:unhook("stream-features", handle_features);
return true;
end
stream:hook("stream-features", handle_features, 310);
end
<file_sep>local verse = require "verse";
local xmlns_pubsub = "http://jabber.org/protocol/pubsub";
local xmlns_pubsub_event = xmlns_pubsub.."#event";
function verse.plugins.pep(stream)
stream:add_plugin("disco");
stream:add_plugin("pubsub");
stream.pep = {};
stream:hook("pubsub/event", function(event)
return stream:event("pep/"..event.node, { from = event.from, item = event.item.tags[1] } );
end);
function stream:hook_pep(node, callback, priority)
local handlers = stream.events._handlers["pep/"..node];
if not(handlers) or #handlers == 0 then
stream:add_disco_feature(node.."+notify");
end
stream:hook("pep/"..node, callback, priority);
end
function stream:unhook_pep(node, callback)
stream:unhook("pep/"..node, callback);
local handlers = stream.events._handlers["pep/"..node];
if not(handlers) or #handlers == 0 then
stream:remove_disco_feature(node.."+notify");
end
end
function stream:publish_pep(item, node, id)
return stream.pubsub:service(nil):node(node or item.attr.xmlns):publish(id or "current", nil, item)
end
end
<file_sep>local verse = require "verse";
local xmlns_session = "urn:ietf:params:xml:ns:xmpp-session";
function verse.plugins.session(stream)
local function handle_features(features)
local session_feature = features:get_child("session", xmlns_session);
if session_feature and not session_feature:get_child("optional") then
local function handle_binding(jid)
stream:debug("Establishing Session...");
stream:send_iq(verse.iq({ type = "set" }):tag("session", {xmlns=xmlns_session}),
function (reply)
if reply.attr.type == "result" then
stream:event("session-success");
elseif reply.attr.type == "error" then
local type, condition, text = reply:get_error();
stream:event("session-failure", { error = condition, text = text, type = type });
end
end);
return true;
end
stream:hook("bind-success", handle_binding);
end
end
stream:hook("stream-features", handle_features);
return true;
end
<file_sep>local verse = require "verse";
-- Implements XEP-0049: Private XML Storage
local xmlns_private = "jabber:iq:private";
function verse.plugins.private(stream)
function stream:private_set(name, xmlns, data, callback)
local iq = verse.iq({ type = "set" })
:tag("query", { xmlns = xmlns_private });
if data then
if data.name == name and data.attr and data.attr.xmlns == xmlns then
iq:add_child(data);
else
iq:tag(name, { xmlns = xmlns })
:add_child(data);
end
end
self:send_iq(iq, callback);
end
function stream:private_get(name, xmlns, callback)
self:send_iq(verse.iq({type="get"})
:tag("query", { xmlns = xmlns_private })
:tag(name, { xmlns = xmlns }),
function (reply)
if reply.attr.type == "result" then
local query = reply:get_child("query", xmlns_private);
local result = query:get_child(name, xmlns);
callback(result);
end
end);
end
end
<file_sep>-- Verse XMPP Library
-- Copyright (C) 2010 <NAME> <<EMAIL>>
-- Copyright (C) 2010 <NAME> <<EMAIL>>
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local verse = require "verse";
local b64 = require("mime").b64;
local sha1 = require("util.hashes").sha1;
local calculate_hash = require "util.caps".calculate_hash;
local xmlns_caps = "http://jabber.org/protocol/caps";
local xmlns_disco = "http://jabber.org/protocol/disco";
local xmlns_disco_info = xmlns_disco.."#info";
local xmlns_disco_items = xmlns_disco.."#items";
function verse.plugins.disco(stream)
stream:add_plugin("presence");
local disco_info_mt = {
__index = function(t, k)
local node = { identities = {}, features = {} };
if k == "identities" or k == "features" then
return t[false][k]
end
t[k] = node;
return node;
end,
};
local disco_items_mt = {
__index = function(t, k)
local node = { };
t[k] = node;
return node;
end,
};
stream.disco = {
cache = {},
info = setmetatable({
[false] = {
identities = {
{category = 'client', type='pc', name='Verse'},
},
features = {
[xmlns_caps] = true,
[xmlns_disco_info] = true,
[xmlns_disco_items] = true,
},
},
}, disco_info_mt);
items = setmetatable({[false]={}}, disco_items_mt);
};
stream.caps = {}
stream.caps.node = 'http://code.matthewwild.co.uk/verse/'
local function build_self_disco_info_stanza(query_node)
local node = stream.disco.info[query_node or false];
if query_node and query_node == stream.caps.node .. "#" .. stream.caps.hash then
node = stream.disco.info[false];
end
local identities, features = node.identities, node.features
-- construct the response
local result = verse.stanza("query", {
xmlns = xmlns_disco_info,
node = query_node,
});
for _,identity in pairs(identities) do
result:tag('identity', identity):up()
end
for feature in pairs(features) do
result:tag('feature', { var = feature }):up()
end
return result;
end
setmetatable(stream.caps, {
__call = function (...) -- vararg: allow calling as function or member
-- retrieve the c stanza to insert into the
-- presence stanza
local hash = calculate_hash(build_self_disco_info_stanza())
stream.caps.hash = hash;
-- TODO proper caching.... some day
return verse.stanza('c', {
xmlns = xmlns_caps,
hash = 'sha-1',
node = stream.caps.node,
ver = hash
})
end
})
function stream:set_identity(identity, node)
self.disco.info[node or false].identities = { identity };
stream:resend_presence();
end
function stream:add_identity(identity, node)
local identities = self.disco.info[node or false].identities;
identities[#identities + 1] = identity;
stream:resend_presence();
end
function stream:add_disco_feature(feature, node)
local feature = feature.var or feature;
self.disco.info[node or false].features[feature] = true;
stream:resend_presence();
end
function stream:remove_disco_feature(feature, node)
local feature = feature.var or feature;
self.disco.info[node or false].features[feature] = nil;
stream:resend_presence();
end
function stream:add_disco_item(item, node)
local items = self.disco.items[node or false];
items[#items +1] = item;
end
function stream:remove_disco_item(item, node)
local items = self.disco.items[node or false];
for i=#items,1,-1 do
if items[i] == item then
table.remove(items, i);
end
end
end
-- TODO Node?
function stream:jid_has_identity(jid, category, type)
local cached_disco = self.disco.cache[jid];
if not cached_disco then
return nil, "no-cache";
end
local identities = self.disco.cache[jid].identities;
if type then
return identities[category.."/"..type] or false;
end
-- Check whether we have any identities with this category instead
for identity in pairs(identities) do
if identity:match("^(.*)/") == category then
return true;
end
end
end
function stream:jid_supports(jid, feature)
local cached_disco = self.disco.cache[jid];
if not cached_disco or not cached_disco.features then
return nil, "no-cache";
end
return cached_disco.features[feature] or false;
end
function stream:get_local_services(category, type)
local host_disco = self.disco.cache[self.host];
if not(host_disco) or not(host_disco.items) then
return nil, "no-cache";
end
local results = {};
for _, service in ipairs(host_disco.items) do
if self:jid_has_identity(service.jid, category, type) then
table.insert(results, service.jid);
end
end
return results;
end
function stream:disco_local_services(callback)
self:disco_items(self.host, nil, function (items)
if not items then
return callback({});
end
local n_items = 0;
local function item_callback()
n_items = n_items - 1;
if n_items == 0 then
return callback(items);
end
end
for _, item in ipairs(items) do
if item.jid then
n_items = n_items + 1;
self:disco_info(item.jid, nil, item_callback);
end
end
if n_items == 0 then
return callback(items);
end
end);
end
function stream:disco_info(jid, node, callback)
local disco_request = verse.iq({ to = jid, type = "get" })
:tag("query", { xmlns = xmlns_disco_info, node = node });
self:send_iq(disco_request, function (result)
if result.attr.type == "error" then
return callback(nil, result:get_error());
end
local identities, features = {}, {};
for tag in result:get_child("query", xmlns_disco_info):childtags() do
if tag.name == "identity" then
identities[tag.attr.category.."/"..tag.attr.type] = tag.attr.name or true;
elseif tag.name == "feature" then
features[tag.attr.var] = true;
end
end
if not self.disco.cache[jid] then
self.disco.cache[jid] = { nodes = {} };
end
if node then
if not self.disco.cache[jid].nodes[node] then
self.disco.cache[jid].nodes[node] = { nodes = {} };
end
self.disco.cache[jid].nodes[node].identities = identities;
self.disco.cache[jid].nodes[node].features = features;
else
self.disco.cache[jid].identities = identities;
self.disco.cache[jid].features = features;
end
return callback(self.disco.cache[jid]);
end);
end
function stream:disco_items(jid, node, callback)
local disco_request = verse.iq({ to = jid, type = "get" })
:tag("query", { xmlns = xmlns_disco_items, node = node });
self:send_iq(disco_request, function (result)
if result.attr.type == "error" then
return callback(nil, result:get_error());
end
local disco_items = { };
for tag in result:get_child("query", xmlns_disco_items):childtags() do
if tag.name == "item" then
table.insert(disco_items, {
name = tag.attr.name;
jid = tag.attr.jid;
node = tag.attr.node;
});
end
end
if not self.disco.cache[jid] then
self.disco.cache[jid] = { nodes = {} };
end
if node then
if not self.disco.cache[jid].nodes[node] then
self.disco.cache[jid].nodes[node] = { nodes = {} };
end
self.disco.cache[jid].nodes[node].items = disco_items;
else
self.disco.cache[jid].items = disco_items;
end
return callback(disco_items);
end);
end
stream:hook("iq/"..xmlns_disco_info, function (stanza)
local query = stanza.tags[1];
if stanza.attr.type == 'get' and query.name == "query" then
local query_tag = build_self_disco_info_stanza(query.attr.node);
local result = verse.reply(stanza):add_child(query_tag);
stream:send(result);
return true
end
end);
stream:hook("iq/"..xmlns_disco_items, function (stanza)
local query = stanza.tags[1];
if stanza.attr.type == 'get' and query.name == "query" then
-- figure out what items to send
local items = stream.disco.items[query.attr.node or false];
-- construct the response
local result = verse.reply(stanza):tag('query',{
xmlns = xmlns_disco_items,
node = query.attr.node
})
for i=1,#items do
result:tag('item', items[i]):up()
end
stream:send(result);
return true
end
end);
local initial_disco_started;
stream:hook("ready", function ()
if initial_disco_started then return; end
initial_disco_started = true;
-- Using the disco cache, fires events for each identity of a given JID
local function scan_identities_for_service(service_jid)
local service_disco_info = stream.disco.cache[service_jid];
if service_disco_info then
for identity in pairs(service_disco_info.identities) do
local category, type = identity:match("^(.*)/(.*)$");
print(service_jid, category, type)
stream:event("disco/service-discovered/"..category, {
type = type, jid = service_jid;
});
end
end
end
stream:disco_info(stream.host, nil, function ()
scan_identities_for_service(stream.host);
end);
stream:disco_local_services(function (services)
for _, service in ipairs(services) do
scan_identities_for_service(service.jid);
end
stream:event("ready");
end);
return true;
end, 50);
stream:hook("presence-out", function (presence)
if not presence:get_child("c", xmlns_caps) then
presence:reset():add_child(stream:caps()):reset();
end
end, 10);
end
-- end of disco.lua
<file_sep>local verse = require "verse";
local xmlns_last = "jabber:iq:last";
local function set_uptime(self, uptime_info)
self.starttime = uptime_info.starttime;
end
function verse.plugins.uptime(stream)
stream.uptime = { set = set_uptime };
stream:hook("iq/"..xmlns_last, function (stanza)
if stanza.attr.type ~= "get" then return; end
local reply = verse.reply(stanza)
:tag("query", { seconds = tostring(os.difftime(os.time(), stream.uptime.starttime)), xmlns = xmlns_last });
stream:send(reply);
return true;
end);
function stream:query_uptime(target_jid, callback)
callback = callback or function (uptime) return stream:event("uptime/response", uptime); end
stream:send_iq(verse.iq({ type = "get", to = target_jid })
:tag("query", { xmlns = xmlns_last }),
function (reply)
local query = reply:get_child("query", xmlns_last);
if reply.attr.type == "result" then
local seconds = tonumber(query.attr.seconds);
callback({
seconds = seconds or nil;
});
else
local type, condition, text = reply:get_error();
callback({
error = true;
condition = condition;
text = text;
type = type;
});
end
end);
end
return true;
end
<file_sep>local jid, password = "<PASSWORD>", "<PASSWORD>";
--os.execute("squish --minify-level=none verse");
require "verse".init("component");
c = verse.new(verse.logger())
c:add_plugin("version");
c:add_plugin("ping");
-- Add some hooks for debugging
c:hook("opened", function () print("Stream opened!") end);
c:hook("closed", function () print("Stream closed!") end);
c:hook("stanza", function (stanza) print("Stanza:", stanza) end);
-- This one prints all received data
c:hook("incoming-raw", print, 1000);
-- Print a message after authentication
c:hook("authentication-success", function () print("Logged in!"); end);
c:hook("authentication-failure", function (err) print("Failed to log in! Error: "..tostring(err.condition)); end);
-- Print a message and exit when disconnected
c:hook("disconnected", function () print("Disconnected!"); os.exit(); end);
-- Now, actually start the connection:
c.connect_host = "127.0.0.1"
c:connect_component(jid, password);
-- Catch binding-success which is (currently) how you know when a stream is ready
c:hook("ready", function ()
print("Stream ready!");
c.version:set{ name = "verse example component" };
end);
-- Echo, echo, echo, echo...
c:hook("stanza", function (stanza)
stanza.attr.from, stanza.attr.to = stanza.attr.to, stanza.attr.from;
c:send(stanza);
end)
print("Starting loop...")
verse.loop()
<file_sep>local verse = require"verse";
local base64, unbase64 = require "mime".b64, require"mime".unb64;
local xmlns_sasl = "urn:ietf:params:xml:ns:xmpp-sasl";
function verse.plugins.sasl(stream)
local function handle_features(features_stanza)
if stream.authenticated then return; end
stream:debug("Authenticating with SASL...");
local sasl_mechanisms = features_stanza:get_child("mechanisms", xmlns_sasl);
if not sasl_mechanisms then return end
local mechanisms = {};
local preference = {};
for mech in sasl_mechanisms:childtags("mechanism") do
mech = mech:get_text();
stream:debug("Server offers %s", mech);
if not mechanisms[mech] then
local name = mech:match("[^-]+");
local ok, impl = pcall(require, "util.sasl."..name:lower());
if ok then
stream:debug("Loaded SASL %s module", name);
mechanisms[mech], preference[mech] = impl(stream, mech);
elseif not tostring(impl):match("not found") then
stream:debug("Loading failed: %s", tostring(impl));
end
end
end
local supported = {}; -- by the server
for mech in pairs(mechanisms) do
table.insert(supported, mech);
end
if not supported[1] then
stream:event("authentication-failure", { condition = "no-supported-sasl-mechanisms" });
stream:close();
return;
end
table.sort(supported, function (a, b) return preference[a] > preference[b]; end);
local mechanism, initial_data = supported[1];
stream:debug("Selecting %s mechanism...", mechanism);
stream.sasl_mechanism = coroutine.wrap(mechanisms[mechanism]);
initial_data = stream:sasl_mechanism(mechanism);
local auth_stanza = verse.stanza("auth", { xmlns = xmlns_sasl, mechanism = mechanism });
if initial_data then
auth_stanza:text(base64(initial_data));
end
stream:send(auth_stanza);
return true;
end
local function handle_sasl(sasl_stanza)
if sasl_stanza.name == "failure" then
local err = sasl_stanza.tags[1];
local text = sasl_stanza:get_child_text("text");
stream:event("authentication-failure", { condition = err.name, text = text });
stream:close();
return false;
end
local ok, err = stream.sasl_mechanism(sasl_stanza.name, unbase64(sasl_stanza:get_text()));
if not ok then
stream:event("authentication-failure", { condition = err });
stream:close();
return false;
elseif ok == true then
stream:event("authentication-success");
stream.authenticated = true
stream:reopen();
else
stream:send(verse.stanza("response", { xmlns = xmlns_sasl }):text(base64(ok)));
end
return true;
end
stream:hook("stream-features", handle_features, 300);
stream:hook("stream/"..xmlns_sasl, handle_sasl);
return true;
end
<file_sep>local verse = require"verse";
local xmlns_receipts = "urn:xmpp:receipts";
function verse.plugins.receipts(stream)
stream:add_plugin("disco");
local function send_receipt(stanza)
if stanza:get_child("request", xmlns_receipts) then
stream:send(verse.reply(stanza)
:tag("received", { xmlns = xmlns_receipts, id = stanza.attr.id }));
end
end
stream:add_disco_feature(xmlns_receipts);
stream:hook("message", send_receipt, 1000);
end
|
d269cb7d9d5606da284e00e64c6eea8463289a54
|
[
"Makefile",
"Shell",
"Lua"
] | 48
|
Lua
|
andrewvmail/verse
|
cfea346869af4e53a4dba4d6843f3a5088cd975f
|
38a18ca0ffec91179b98541e58ba412a1cb6c08f
|
refs/heads/master
|
<file_sep>from typing import Any
import discord
from redbot.core import Config, commands, checks
from redbot.core.bot import Red
Cog: Any = getattr(commands, "Cog", object)
listener = getattr(commands.Cog, "listener", None) # Trusty + Sinbad
if listener is None:
def listener(name=None):
return lambda x: x
class InfoChannel(Cog):
"""
Create a channel with updating server info
Less important information about the cog
"""
def __init__(self, bot: Red):
self.bot = bot
self.config = Config.get_conf(
self, identifier=731101021116710497110110101108, force_registration=True
)
default_guild = {
"channel_id": None,
"category_id": None,
"member_count": True,
"channel_count": True,
}
self.config.register_guild(**default_guild)
@commands.command()
@checks.admin()
async def infochannel(self, ctx: commands.Context):
"""
Toggle info channel for this server
"""
def check(m):
return (
m.content.upper() in ["Y", "YES", "N", "NO"]
and m.channel == ctx.channel
and m.author == ctx.author
)
guild: discord.Guild = ctx.guild
channel_id = await self.config.guild(guild).channel_id()
if channel_id is not None:
channel: discord.VoiceChannel = guild.get_channel(channel_id)
else:
channel: discord.VoiceChannel = None
if channel_id is not None and channel is None:
await ctx.send("Info channel has been deleted, recreate it?")
elif channel_id is None:
await ctx.send("Enable info channel on this server?")
else:
await ctx.send("Info channel is {}. Delete it?".format(channel.mention))
msg = await self.bot.wait_for("message", check=check)
if msg.content.upper() in ["N", "NO"]:
await ctx.send("Cancelled")
return
if channel is None:
await self.make_infochannel(guild)
else:
await self.delete_infochannel(guild, channel)
if not await ctx.tick():
await ctx.send("Done!")
async def make_infochannel(self, guild: discord.Guild):
overwrites = {guild.default_role: discord.PermissionOverwrite(connect=False),
guild.me: discord.PermissionOverwrite(manage_channels=True, connect=True)}
category: discord.CategoryChannel = await guild.create_category("──────ZEVENBEEK──────", overwrites=overwrites)
channel = await guild.create_voice_channel(
"Placeholder", category=category, reason="InfoChannel make", overwrites=overwrites
)
await self.config.guild(guild).channel_id.set(channel.id)
await self.config.guild(guild).category_id.set(category.id)
await self.update_infochannel(guild)
async def delete_infochannel(self, guild: discord.Guild, channel: discord.VoiceChannel):
await channel.category.delete(reason="InfoChannel delete")
await channel.delete(reason="InfoChannel delete")
await self.config.guild(guild).clear()
async def update_infochannel(self, guild: discord.Guild):
guild_data = await self.config.guild(guild).all()
channel_id = guild_data["channel_id"]
if channel_id is None:
return
channel: discord.VoiceChannel = guild.get_channel(channel_id)
if channel is None:
return
name = ""
if guild_data["member_count"]:
name += "Spelers: 60/128 "
if guild_data["channel_count"]:
name += "+ 0"
if name == "":
name = "Stats not enabled"
await channel.edit(reason="InfoChannel update", name=name)
@listener()
async def on_member_join(self, member: discord.Member):
await self.update_infochannel(member.guild)
@listener()
async def on_member_remove(self, member: discord.Member):
await self.update_infochannel(member.guild)
|
1f2ad41d8fcaf6cb3c3f062deded17a766beb51c
|
[
"Python"
] | 1
|
Python
|
Smiling2death/serverinfo
|
2dd19899938097fef1c2f62098a6c58cf171c917
|
a379c7f8d573f1d1c59c218da0cac70f4883d3ac
|
refs/heads/master
|
<file_sep>'''
Created on 2013-4-20
@author: baritono
'''
from collections import deque
import re
from datetime import datetime
from threading import Thread
import subprocess
import signal
main_tags = {"fuse":set(['', 'write', 'read', 'readdir', 'flush']),
"re_meepo":set(['', 'mkfile', 'listdir', 'eread', 'ewrite', 'lock', 'move', 'mkdir', 'unlock', 'getattr', 'commit_sha1', 'commit', 'rmfile']),
"fs_lobby":set(['']),
"callback":set(['']),
"main":set(['']),
"metacache":set(['invalidate']),
"GET":set(['']),
"PUT":set(['']),
"sync":set([''])}
class MeepoLogEntry:
TIME_PATTERN = re.compile(r'\[((\d{1,2}):(\d{1,2}):(\d{1,2}))\]')
TAG_PATTERN = re.compile(r'\[([a-zA-Z_]+)\]')
CURL_TRANSPORT_FAILURE_SIGNATURE = "Xmlrpc-c Curl transport is now in an unknown state and may not be able to continue functioning."
XML_RPC_FAILURE_SIGNATURE = "XML-RPC Fault:"
RPC_FAILURE_ID_PATTERN = re.compile(r"\((-?\d+)\)$")
def __init__(self, line):
self.line = line
self.is_curl_failure = MeepoLogEntry.CURL_TRANSPORT_FAILURE_SIGNATURE in line
self.is_xml_rpc_failure = MeepoLogEntry.XML_RPC_FAILURE_SIGNATURE in line
if self.is_xml_rpc_failure:
match = MeepoLogEntry.RPC_FAILURE_ID_PATTERN.search(line)
if match != None:
self.xml_rpc_failure_code = match.group(1)
else:
self.xml_rpc_failure_code = None
else:
self.xml_rpc_failure_code = None
time_match = MeepoLogEntry.TIME_PATTERN.match(line)
if time_match != None:
today = datetime.today()
self.time = datetime(today.year, today.month, today.day,
int(time_match.group(2)),
int(time_match.group(3)),
int(time_match.group(4)))
tag_list = []
start_pos = len(time_match.group())
while True:
tag_match = MeepoLogEntry.TAG_PATTERN.match(line, start_pos)
if tag_match == None:
break
tag_list.append(tag_match.group(1))
start_pos += len(tag_match.group())
self.tags = tag_list
self.content = line[start_pos:]
if len(tag_list) == 1 or len(tag_list) == 2:
maintag = tag_list[0]
subtag = ""
if len(tag_list) == 2:
subtag = tag_list[1]
if maintag not in main_tags:
main_tags[maintag] = set()
print "[new] main tag added:", main_tags.keys()
print "[example]", line
if subtag not in main_tags[maintag]:
main_tags[maintag].add(subtag)
print "[new]", maintag, "sub-tag added:", main_tags[maintag]
print "[example]", line
else:
print "[unknown]", time_match.group(1), tag_list, line[start_pos:]
else:
self.time = None
self.tags = None
self.content = line
class MeepoMonitorThread(Thread):
INITIAL_STATE = 0
DISCONNECTED_STATE = 1
CONNECTED_STATE = 2
UNKNOWN_STATE = 3
EXITED_STATE = 4
ACCOUNT_WAITING_STATE = 5
PASSWORD_WAITING_STATE = 6
EXIT_SUCCESS = 0
EXIT_LOGIN_FAILURE = 1
EXIT_ANOTHER_INSTANCE = 2
EXIT_UNKNOWN_ACCOUNT = 3
XML_RPC_ERROR_NOT_RUNNING = "0" # filesystem not running
XML_RPC_ERROR_LOGIN_FAILURE = "1004" # log-in failure
XML_RPC_ERROR_NON_EXIST = "1017" # the file or directory does not exist
XML_RPC_ERROR_NO_ELEMENT = "-503" # no element found
LOG_BUFFER_SIZE = 1024
def __init__(self, binary_path, state_change_callback, new_log_entry_callback):
super(MeepoMonitorThread, self).__init__(name="meepo-monitor")
self.log_buffer = deque()
self.important_log_buffer = deque()
self.state = MeepoMonitorThread.INITIAL_STATE
self.exit_status = MeepoMonitorThread.EXIT_SUCCESS
self.binary_path = binary_path
self.state_change_callback = state_change_callback
self.new_log_entry_callback = new_log_entry_callback
# TODO: handle subprocess launch failure
self.subprocess = subprocess.Popen([binary_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self._meepo_ouput = self.subprocess.stdout
def make_state_transition(self, new_state, log_entry = None):
self.state = new_state
if log_entry != None:
self.important_log_buffer.append(log_entry)
while len(self.important_log_buffer) > MeepoMonitorThread.LOG_BUFFER_SIZE:
self.important_log_buffer.popleft()
self.new_log_entry_callback(log_entry, True)
self.state_change_callback()
def run(self):
self._meepo_output = self.subprocess.stdout
self.state = MeepoMonitorThread.DISCONNECTED_STATE
while True:
line = self._meepo_output.readline()
if len(line) == 0:
break
log_entry = MeepoLogEntry(line.rstrip("\r\n"))
self.log_buffer.append(log_entry)
while len(self.log_buffer) > MeepoMonitorThread.LOG_BUFFER_SIZE:
self.log_buffer.popleft()
self.new_log_entry_callback(log_entry, False)
if "Meepo Account(E-mail):" in log_entry.line:
self.exit_status = MeepoMonitorThread.EXIT_UNKNOWN_ACCOUNT
self.quit()
# TODO: handle first-time login
elif "Another meepo_client is running!" in log_entry.line:
self.exit_status = MeepoMonitorThread.EXIT_ANOTHER_INSTANCE
self.quit()
elif "Login success" in log_entry.line:
self.make_state_transition(MeepoMonitorThread.CONNECTED_STATE, log_entry)
elif "Mount terminated: Success" in log_entry.line >= 0:
self.make_state_transition(MeepoMonitorThread.DISCONNECTED_STATE, log_entry)
elif log_entry.is_curl_failure:
self.make_state_transition(MeepoMonitorThread.UNKNOWN_STATE, log_entry)
# TODO: move back to CONNECTED_STATE when a following read/write operation is completed successfully
elif log_entry.is_xml_rpc_failure:
error_id = log_entry.xml_rpc_failure_code
if error_id == MeepoMonitorThread.XML_RPC_ERROR_LOGIN_FAILURE:
self.exit_status = MeepoMonitorThread.EXIT_LOGIN_FAILURE
elif error_id == MeepoMonitorThread.XML_RPC_ERROR_NOT_RUNNING:
self.make_state_transition(MeepoMonitorThread.UNKNOWN_STATE, log_entry)
self.subprocess.wait()
self.make_state_transition(MeepoMonitorThread.EXITED_STATE)
def quit(self):
if self.subprocess.returncode == None:
self.subprocess.send_signal(signal.SIGINT)
<file_sep>#!/usr/bin/env python
import os.path
import stat
import gobject
import gconf
import gtk
import appindicator
from meepo_wrapper import MeepoMonitorThread
import meepo_wrapper
global main_indicator, monitor_thread
global log_dialog_builder
global meepo_binary_path
log_dialog_builder = None
CONNECTED_LOGO_PATH = "/home/baritono/bin/meepo-connected-32.png"
DISCONNECTED_LOGO_PATH = "/home/baritono/bin/meepo-disconnected-32.png"
GCONF_DIR = "/apps/indicator-meepo"
MEEPO_BINARY_PATH_GCONF_ENTRY = "meepo-binary-path"
EXPECTED_BINARY_MIME_TYPE = "application/x-executable"
user_request_quit = False
def is_executable_file(entry_path):
EXE_MOD_BITS = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
return entry_path != None and os.path.isfile(entry_path) and (stat.S_IMODE(os.stat(entry_path).st_mode) & EXE_MOD_BITS)
def search_meepo_binary():
if 'PATH' not in os.environ:
return None
path_env = os.environ['PATH']
for path in path_env.split(':'):
if not path:
path = os.getcwd()
path = os.path.abspath(os.path.expanduser(path))
if os.path.isdir(path):
for entry in os.listdir(path):
entry_path = os.path.join(path, entry)
if is_executable_file(entry_path) and entry.startswith("meepo"):
return entry_path
return None
def quit_meepo(w):
global monitor_thread
global user_request_quit
user_request_quit = True
monitor_thread.quit()
def get_log_dialog(log_dialog_builder):
if log_dialog_builder != None:
return log_dialog_builder.get_object("meepo_log_dialog")
else:
return None
def get_log_textview(log_dialog_builder):
if log_dialog_builder != None:
return log_dialog_builder.get_object("log_textview")
else:
return None
def get_important_log_textview(log_dialog_builder):
if log_dialog_builder != None:
return log_dialog_builder.get_object("important_log_textview")
else:
return None
def log_dialog_hidden(w):
global log_dialog_builder
get_log_dialog(log_dialog_builder).destroy()
log_dialog_builder = None
def hide_log_dialog(w):
global log_dialog_builder
log_dialog = get_log_dialog(log_dialog_builder)
if log_dialog == None:
return
log_dialog.hide()
def reload_log_textviews():
global log_dialog_builder
if log_dialog_builder == None:
return
log_textview = get_log_textview(log_dialog_builder)
important_log_textview = get_important_log_textview(log_dialog_builder)
text = ""
for log_entry in monitor_thread.log_buffer:
text += log_entry.line + "\n"
textbuffer = log_textview.get_buffer()
textbuffer.set_text("")
textbuffer.create_tag("default", family="Monospace")
beginning = textbuffer.get_start_iter()
textbuffer.insert_with_tags_by_name(beginning, text, "default")
log_textview.scroll_to_iter(textbuffer.get_end_iter(), 0)
text = ""
for log_entry in monitor_thread.important_log_buffer:
text += log_entry.line + "\n"
textbuffer = important_log_textview.get_buffer()
textbuffer.set_text("")
textbuffer.create_tag("default", family="Monospace")
beginning = textbuffer.get_start_iter()
textbuffer.insert_with_tags_by_name(beginning, text, "default")
important_log_textview.scroll_to_iter(textbuffer.get_end_iter(), 0)
def insert_new_log_entry(entry, is_important):
global log_dialog_builder
if log_dialog_builder == None:
return
if not is_important:
log_textview = get_log_textview(log_dialog_builder)
else:
log_textview = get_important_log_textview(log_dialog_builder)
text = entry.line + "\n"
textbuffer = log_textview.get_buffer()
end = textbuffer.get_end_iter()
textbuffer.insert_with_tags_by_name(end, text, "default")
log_textview.scroll_to_iter(textbuffer.get_end_iter(), 0)
number_of_stale_lines = textbuffer.get_line_count() - meepo_wrapper.MeepoMonitorThread.LOG_BUFFER_SIZE
if number_of_stale_lines > 0:
end_of_stale_lines = textbuffer.get_iter_at_line(number_of_stale_lines)
textbuffer.delete(textbuffer.get_start_iter(), end_of_stale_lines)
def new_log_entry_callback(entry, is_important):
gobject.idle_add(insert_new_log_entry, entry, is_important)
def show_log_dialog(w):
global log_dialog_builder
if log_dialog_builder != None:
return
glade = os.path.join(os.path.dirname(__file__), "log_dialog.glade")
if not os.path.isfile(glade):
glade = os.path.join(os.path.dirname(__file__), "../data/ui/log_dialog.glade")
log_dialog_builder = gtk.Builder()
log_dialog_builder.add_from_file(glade)
log_dialog = get_log_dialog(log_dialog_builder)
signals_map = { "ok_button_clicked" : hide_log_dialog, "dialog_hidden" : log_dialog_hidden }
log_dialog_builder.connect_signals(signals_map)
reload_log_textviews()
log_dialog.show()
def ui_check_state_change():
global monitor_thread
if monitor_thread.state == MeepoMonitorThread.EXITED_STATE:
if user_request_quit:
gtk.main_quit()
elif monitor_thread.exit_status == MeepoMonitorThread.EXIT_SUCCESS:
message = gtk.MessageDialog(flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_ERROR,
buttons = gtk.BUTTONS_YES_NO)
message.set_markup("The subprocess aborted unexpectedly, should we try to restart it?")
message.set_title("Meepo Error")
result = message.run()
message.destroy()
if result == gtk.RESPONSE_YES:
start_new_monitor_thread()
else:
gtk.main_quit()
elif monitor_thread.exit_status == MeepoMonitorThread.EXIT_ANOTHER_INSTANCE:
message = gtk.MessageDialog(flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_ERROR,
buttons = gtk.BUTTONS_OK)
message.set_markup("It seems that another meepo process is already running, we will now quit.")
message.set_title("Meepo Error")
message.run()
message.destroy()
gtk.main_quit()
elif monitor_thread.exit_status == MeepoMonitorThread.EXIT_LOGIN_FAILURE:
# TODO: handle login failure
pass
elif monitor_thread.exit_status == MeepoMonitorThread.EXIT_UNKNOWN_ACCOUNT:
# TODO: handle first-time login
pass
elif monitor_thread.state == MeepoMonitorThread.CONNECTED_STATE:
main_indicator.set_icon(CONNECTED_LOGO_PATH)
else:
main_indicator.set_icon(DISCONNECTED_LOGO_PATH)
def ui_check_state_change_callback():
gobject.idle_add(ui_check_state_change)
def start_new_monitor_thread():
global monitor_thread
global meepo_binary_path
while True:
try:
monitor_thread = MeepoMonitorThread(meepo_binary_path, ui_check_state_change_callback,
new_log_entry_callback)
except BaseException as e:
message = gtk.MessageDialog(flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_ERROR,
buttons = gtk.BUTTONS_OK_CANCEL)
message.set_markup("Failed to launch meepo process.\n"
+ "Failure detail: " + str(e) + "\n"
+ "Press \"OK\" to retry.\n"
+ "Press \"Cancel\" to quit.\n")
message.set_title("Meepo Error")
response = message.run()
message.destroy()
if response != gtk.RESPONSE_OK:
quit()
else:
break
monitor_thread.start()
def get_meepo_executable_path():
gconf_client = gconf.client_get_default()
if not gconf_client.dir_exists(GCONF_DIR):
gconf_client.add_dir(GCONF_DIR, preload = False)
binary_path_gconf_path = GCONF_DIR + "/" + MEEPO_BINARY_PATH_GCONF_ENTRY
binary_path = gconf_client.get_string(binary_path_gconf_path)
if is_executable_file(binary_path):
return binary_path
message = gtk.MessageDialog(flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_INFO,
buttons = gtk.BUTTONS_OK)
message.set_markup("No valid meepo executable is configured, please choose one.")
message.set_title("Meepo Information")
message.run()
message.destroy()
found_meepo_binary = search_meepo_binary()
assert found_meepo_binary == None or is_executable_file(found_meepo_binary)
while True:
file_filter = gtk.FileFilter()
file_filter.add_mime_type(EXPECTED_BINARY_MIME_TYPE)
file_chooser = gtk.FileChooserDialog(title = "Choose Meepo executable",
action = gtk.FILE_CHOOSER_ACTION_OPEN,
buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
file_chooser.set_filter(file_filter)
if found_meepo_binary != None:
file_chooser.set_filename(found_meepo_binary)
response = file_chooser.run()
binary_path = file_chooser.get_filename()
file_chooser.destroy()
if response != gtk.RESPONSE_OK:
quit()
if is_executable_file(binary_path):
gconf_client.set_string(binary_path_gconf_path, binary_path)
break
else:
message = gtk.MessageDialog(flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_ERROR,
buttons = gtk.BUTTONS_OK)
message.set_markup("The selected file is not a valid meepo executable, please choose another one.")
message.set_title("Meepo Error")
message.run()
message.destroy()
return binary_path
if __name__ == "__main__":
meepo_binary_path = get_meepo_executable_path()
main_indicator = appindicator.Indicator ("indicator-meepo",
DISCONNECTED_LOGO_PATH,
appindicator.CATEGORY_APPLICATION_STATUS)
main_indicator.set_status (appindicator.STATUS_ACTIVE)
menu = gtk.Menu()
log_menu_item = gtk.MenuItem("view log")
log_menu_item.connect("activate", show_log_dialog)
menu.append(log_menu_item)
log_menu_item.show()
quit_menu_item = gtk.MenuItem("quit")
quit_menu_item.connect("activate", quit_meepo)
menu.append(quit_menu_item)
quit_menu_item.show()
main_indicator.set_menu(menu)
gobject.threads_init() # @UndefinedVariable
start_new_monitor_thread()
gtk.main()
<file_sep>indicator-meepo
===============
Unity indicator for Meepo cloud storage service
|
76da13bcbb0b3d8e1d57da8f2bee90155772d469
|
[
"Markdown",
"Python"
] | 3
|
Python
|
baritono/indicator-meepo
|
7f1867b251518fb8f58eba1ae36eca083f4e0538
|
f8d5d2daa39f89320ac8dac1b7951e85b3d3d0ee
|
refs/heads/master
|
<file_sep>package hw;
import java.util.*;
public class hw02_105021031 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner src=new Scanner(System.in);
int n=src.nextInt();
Random ran=new Random(n);
System.out.print(ran.nextInt(n)+1);
}
}
|
2f7113654bc1f8f5dadb3d56f2248b28c8768f37
|
[
"Java"
] | 1
|
Java
|
csie-asia/week01-20160919-hukepasta0425
|
a5f4e7c2c2f588228b2d8883b5b52e2e393ec9e7
|
9c18918455f59cfa580c1e7f282fd0b5240ae266
|
refs/heads/master
|
<file_sep>const discord = require('discord.js');
const client = new discord.Client();
const sql = require('sqlite');
const _ = require('lodash');
sql.open('./score.sqlite');
const config = require('./config.json');
prefix = config.prefix;
token = config.token;
client.on('ready', () => {
console.log('Bot is running!');
});
client.on('message', async message => {
if (message.content.startsWith(prefix)) {
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
prefixedCommand(message, command, args);
}
if (message.author.bot) return;
scoreUpdate(message);
});
function prefixedCommand(message, command, args) {
if (command === "score") {
sql.get(`SELECT * FROM scores WHERE userId = "${message.author.id}"`).then(row => {
if (!row) return message.reply("You have 0 points");
message.reply(`You have ${row.points} points`);
});
} else if (command === "rps") {
if (args.length != 1) {
message.reply("Invalid choice, try again.");
}
let choices = ['r', 'p', 's'];
let choice = args[0].charAt(0).toLowerCase();
computerChoice = _.sample(choices);
console.log(choice, choices, computerChoice);
if (choices.indexOf(choice) === -1) {
message.reply("Invalid choice, try again.");
} else if (choice === computerChoice) {
message.reply("We tied.");
} else if ((choice === 'r' && computerChoice === 'p') ||
(choice === 'p' && computerChoice === 's') ||
(choice === 's' && computerChoice === 'r')) {
message.reply("You lost.");
} else {
message.reply("You won!");
}
} else if (command === "flip") {
let outcome = ['Heads', 'Tails'];
message.reply(_.sample(outcome));
}
}
function scoreUpdate(message) {
sql.get(`SELECT * FROM scores WHERE userID = "${message.author.id}"`).then(row => {
if (!row) {
sql.run("INSERT INTO scores (userId, points, level) VALUES (?, ?, ?)", [message.author.id, 1, 0]);
} else {
sql.run(`UPDATE scores SET points = ${row.points + 1} WHERE userID = ${message.author.id}`);
}
}).catch(() => {
console.error;
sql.run("CREATE TABLE IF NOT EXISTS scores (userId TEXT, points INTEGER, level INTEGER)").then(() => {
sql.run("INSERT INTO scores (userId, points, level) VALUES (?, ?, ?)", [message.author.id, 1, 0]);
});
});
}
client.login(token);
|
f0f04580383d34e1d094d1847528e50900de10bd
|
[
"JavaScript"
] | 1
|
JavaScript
|
joshuapondrom/Geoff-Bot
|
c054e92c4ac7602364775ecbf53c6c155313cfb0
|
9c5411f97e54816212b546a6eea955a0fc15ebf4
|
refs/heads/master
|
<repo_name>john-grillo/d2lminusminus<file_sep>/bot.bash
#!/bin/bash
mkfifo .botfile
chan=$1
if [ $2 != '' ] && [ -f $2 ] ; then
key=`cat $2`
fi
tail -f .botfile | openssl s_client -connect irc.cat.pdx.edu:6697 | while true; do
if [[ -z $started ]] ; then
echo "USER d2lbot d2lbot d2lbot :d2lbot" >> .botfile
echo "NICK d2lminusminus" >> .botfile
echo "JOIN #$chan $key" >> .botfile
started="yes"
fi
read irc
echo $irc
if `echo $irc | cut -d ' ' -f 1 | grep PING > /dev/null`; then
echo "PONG" >> .botfile
elif `echo $irc | grep PRIVMSG | grep -i d2l > /dev/null` ; then
nick="${irc%%!*}"; nick="${nick#:}"
if [[ $nick != 'd2lminusminus' ]] ; then
chan=`echo $irc | cut -d ' ' -f 3`
echo "PRIVMSG $chan :d2l--" >> .botfile
fi
fi
done
|
45535bd2bde838b5fcdbe06a6fc68b54c7f0e5be
|
[
"Shell"
] | 1
|
Shell
|
john-grillo/d2lminusminus
|
1e5e106ab04b542848924c319382d104301a2737
|
727563753137423c0c2a23b9b8cebf87c7db65f8
|
refs/heads/master
|
<repo_name>Meepnix/ImgReady<file_sep>/examples/example1.js
/**
* @fileoverview Function, containing example code how to intialise and use ImgReady.
* @Author <NAME>
* @preserve Copyright 2011 <NAME>.
* See LICENCE for details.
*/
/** Function that implements a canvas and its resources.
*/
function render()
{
//Setting up canvas
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');
var interLoad;
//Set Canvas size
var width = 1000;
var height = 500;
var percent = 0;
canvas.width = width;
canvas.height = height;
//Setup ImgReady class from ImgReady Module
var imgStor = new ImgReady();
//Cache resources
var boomAud = imgStor.addAudio("sounds/boom.ogg");
var pewAud = imgStor.addAudio9"sounds/pew.ogg");
var rocketImg = imgStor.addImage("images/rocket.png");
var pikeImg = imgStor.addImage("images/pike.png");
//Every second checks the status of resources loading
var interLoad = setInterval(loading, 1000);
/** Function Closure that renders resource load status and runs the main render
* once all the resources have loaded.
*/
var loading = function()
{
percent = imgStor.getPercent();
clear();
context.fillStyle = "black";
context.font = "20px sans-serif";
context.fillText( "loading "+percent+" %", 300, 300 );
if (percent == 100)
{
clearInterval(interLoad);
start();
}
};
/** Function Closure that runs the successfully cached resources.
*/
var start = function()
{
//Play sounds
boomAud.play();
pewAud.play();
//Render images
context.drawImage(rocketImg, 50, 50);
context.drawImage(pikeImg, 100, 100);
};
/** Function Closure that clears the canvas.
*/
var clear = function()
{
context.clearRect(0, 0, width, height);
};
}
//Engage!!!
window.onload = function(){
render();
};
|
06b8a936a850c592520c076353e2c10d19c7eb33
|
[
"JavaScript"
] | 1
|
JavaScript
|
Meepnix/ImgReady
|
93d0fbbc13031e7af93981c77e61aa493175a817
|
25f28d63e9c16676a5a127d643c1b0738f936818
|
refs/heads/master
|
<file_sep>#CS3030Homework8
<NAME>
<NAME>
<NAME>
Python/MySQL/Bash report generator
**Module 1** - config.ini file containing database credentials. Obviously this has been omitted from the repository for security reasons.
The required format for the config.ini file is as follows:
[mysql]
host = localhost
database = DATABASE NAME
user = USERNAME
password = <PASSWORD>
The config.ini file is parsed by the included dbconfig.py module and passed to mysql\_connect.py for use in Module 2
**Module 2** - create\_report.py
Requires two arguments (*beg\_date*, *end\_date*) in the format <YYYYMMDD>
Connects to the database using config.ini parsed by dbconfig.py and generates a fixed length report using *beg\_date* and *end\_date* as delimiters for the data.
Exit codes:
**-1:** Improper date format
**-2:** No data for given date range
**0:** Successful execution
**Script 1** - run\_report.sh
Shell wrapper script that runs create\_report.py, generates a zipped copy of the report, uploads it to the given FTP server, and emails the status of the FTP upload.
Required paramters:
**-f** <BegDate>
**-t** <EndDate>
**-e** <email>
**-u** <user>
**-p** <passwd>
<file_sep>#!/bin/bash -
#===============================================================================
#
# FILE: run_report.sh
#
# USAGE: ./run_report.sh
#
# DESCRIPTION:
#
# AUTHOR: <NAME> (), <EMAIL>
# CREATED: 12/03/2016 05:19
#===============================================================================
#set -o nounset # Treat unset variables as an error
showHelp() {
echo "This file will run the create_report.py file with the specified dates and ftp the results to the FTP server using the supplied credentials. Errors will be reported to the email"
echo "Usage: $0 -f <beginDate> -t <endDate> -e <email> -u <user> -p <password>"
exit -5
}
while getopts ":f:t:e:u:p:" opt
do
case $opt in
f) begin=$OPTARG
;;
t) end=$OPTARG
;;
e) email=$OPTARG
;;
u) user=$OPTARG
;;
p) password=$OPTARG
;;
h) showHelp
;;
\?) showHelp
;;
esac
done
if [[ $begin == "" || $end == "" || $email == "" || $user == "" || $password == "" ]]
then
showHelp
fi
fileDate=`date +%Y_%m_%d-%H:%m`
file="report-$fileDate.txt"
python3 create_report.py $begin $end > $file
result=$?
sed -i '1,3d' $file
if [[ $result -eq 255 ]] # For some reaseon, if python exits with a negative number, it is just taken away from 256
then
echo "Exited with -1. Sending an email..."
mail -s "The create_report program exited with code -1" -r "<EMAIL>" $email << EOF
The create_report could not run due to invalid date params. Please review it's documentation.
EOF
elif [[ $result -eq 254 ]]
then
echo "Exited with -2. Sending an email..."
mail -s "The create_report program exited with code -2" -r "<EMAIL>" $email << EOF
The create_report program ran, but no transactions were found within the specified date range
EOF
else
echo "All good. Zipping and sending now"
zipFile="report-$fileDate.zip"
zip $zipFile $file
ftpAddress=192.168.127.12
echo "Attempting to ftp..."
ftp -inv $ftpAddress << COMMS
user $user $password
put $zipFile
bye
COMMS
rm $zipFile
mail -s "run_report.sh ran successfully to $ftpaddress" -r "<EMAIL>" $email << EOF
Successfully created a transaction report from $begin to $end
EOF
fi
rm $file
exit 0
<file_sep>#!/usr/bin/python3
import time
import os, sys
import datetime
from optparse import OptionParser
from datetime import datetime
From mysql.connector import (connection)
#from mysql.connector import error
#import MySQLdb.connector
parser = OptionParser()
if sys.argv[1] == "-u" and sys.argv[3] == "-d" and sys.argv[5] == "-p" and sys.argv[7] == "-b" and sys.argv[9] == "-b" :
parser.add_option("-u", "--username", type="string",
help="insert the the",
dest="user")
parser.add_option("-d", "--databaseName", type="string",
help="this is the name of database",
dest="data")
parser.add_option("-p", "--password", type="string",
help="this is the login password",
dest="passw")
parser.add_option("-e", "--enddate", type="string",
help="End Date with the following format: YYYYMMDD ",
dest="Enddate")
parser.add_option("-b", "--begindate", type="string",
help="Begin Date with the following format: YYYYMMDD ",
dest="begin")
(options, args) = parser.parse_args()
def beginFormatted():
date = (options.begin + " 00:00:00")
datetimeobject = datetime.strptime(date,'%Y%m%d %H:%M:%S')
print(datetimeobject)
def endFormatted():
date2 = (options.Enddate + " 23:59:00")
datetimeobject2 = datetime.strptime(date2, '%Y%m%d %H:%M:%S')
print(datetimeobject2)
def sqlquary():
mysql -u (options.user) -p (options.passw) -d (option.data)
def main():
beginFormatted()
endFormatted()
sqlquary()
#def dateChange():
#testr = SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
main()
<file_sep>#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright é 2016 Jonathan <<EMAIL>>
#
# Distributed under terms of the MIT license.
import sys
from configparser import ConfigParser
from dbconfig import read_db_config
from mysql_connect import connect
from pprint import pprint as pp
def convDate(beg_date, end_date):
"""
Takes beginning date and end date as parameters to query the database.
Converts the inputs to proper format YYYY-MM-DD hh:mm
Args:
beg_date: date in YYYYMMDD format
end_date: date in YYYYMMDD format
Returns:
"""
db = read_db_config()
if(len(str(beg_date)) != 8 or len(str(end_date)) != 8):
print("Improper date format. Please use the format <YYYYMMDD>")
#Exit code 255 in Bash
exit(-1)
#Convert to list to add elements
convB_date = list(str(beg_date))
convE_date = list(str(end_date))
#Add dashes, whitespace, and time
#Year
convB_date.insert(4, "-")
convE_date.insert(4, "-")
#Month
convB_date.insert(7, "-")
convE_date.insert(7, "-")
#Time (whitespace)
convB_date.insert(11, " ")
convE_date.insert(11, " ")
#Time (value)
convB_date.insert(12, "00:00")
convE_date.insert(12, "23:59")
#Assign to new variables for database query
bDate = "".join(convB_date)
eDate = "".join(convE_date)
#Connect to database and retrieve contents for display
contents = connect(bDate, eDate)
if not contents:
print("No data for given date range")
#Exit code 254 in Bash
exit(-2)
#The fun part, making the fixed length record.
#Should always be 47 characters long
#Index, Name, Size, Type
#[0], Transaction ID, 5, int
#[1], Transaction date, 12, int
#[2], Card number, 6, int
#[3], Prod qty, 2, int
#[4], Prod amt, 6, int
#[5], Prod desc, 10, str
#[6], Prod total, 6, int
for entry in contents:
print('{0:05d}{1:012d}{2:06d}{3:02d}{4:06d}{5:10}{6:06d}'.format(int(entry[0]), int(entry[1]), int(entry[2]), int(entry[3]), int(entry[4]), entry[5], int(entry[6])))
# Main function
def main(beg_date, end_date):
convDate(beg_date, end_date)
return
if __name__ == "__main__":
# Call Main
beg_date = 20001018
end_date = 20161231
if len(sys.argv) == 1:
main(beg_date, end_date)
#Exit code 0 in Bash
exit(0)
else:
main(sys.argv[1], sys.argv[2])
#Exit code 0 in Bash
exit(0)
|
6a4e9560b7ff880a41bcc1397e85dee3d2fc96e7
|
[
"Markdown",
"Python",
"Shell"
] | 4
|
Markdown
|
BrashFlea/CS3030Homework8
|
50dab0dc54dbdd8b142cb5cada1f43ac907ded6f
|
395b34fe0604b92d1b94fc200ccd7842e4fce255
|
refs/heads/master
|
<repo_name>danhixon/translate<file_sep>/lib/edit_in_place.rb
#
module EditInPlace
def translate(msgid)
return msgid if msgid.start_with?("<span")
if $translate_in_same_window
"<span class=\"translate\" onClick=\"javascript:top.document.location.href='/#{I18n.locale}/translate/edit?key=#{CGI::escape(msgid)}';\">" + I18n.translate(msgid) + '</span>'
else
"<span class=\"translate\" onClick=\"window.open('/#{I18n.locale}/translate/edit?key=#{CGI::escape(msgid)}','mywin','width=480,height=600,scrollbars=1,toolbar=0,resizable=1');\">" + I18n.translate(msgid) + '</span>'
end
end
alias :t :translate
module_function :translate, :t
end
module ApplicationHelper
include EditInPlace
end
module Controller
include EditInPlace
end
module ActiveRecord
class Base
include EditInPlace
end
end
#end
|
3f28c208971ef3c18c89ee33102f5875ecd4b49d
|
[
"Ruby"
] | 1
|
Ruby
|
danhixon/translate
|
0a6bba509c959d929d3a10070ae89286476290ff
|
87fc5186d100e55b1aedf707dde5392f3e01be84
|
refs/heads/master
|
<file_sep>python compress.py folder quality
e.g.
python compress.py ~/Downloads/img/ 80
但现在的脚本是有问题的…
不好用
结尾一定要带 /<file_sep>#!/bin/bash
pipreqs .<file_sep>#!/usr/bin/python
#coding:utf-8
from PIL import Image
import os
import sys
import glob
import shutil
import time
from colorama import Fore, Back, Style
print("正在初始化")
time.sleep(1)
#记录程序开始执行的时间
start = time.clock()
#读取参数
#第一个参数为输入文件夹路径
source_dir = sys.argv[1]
#第二个参数为压缩质量
thequality = int(sys.argv[2])
print (thequality)
print ('参数列表:', str(sys.argv))
#print(source_dir)
#目标文件夹上级父目录
hjx = os.path.abspath(os.path.join(os.path.dirname(source_dir),os.path.pardir))
print ("父目录")
print (hjx)
#源目录最后一段
hw = os.path.basename(os.path.normpath(source_dir))
print ("源目录最后一段")
print (hw)
#新目录
desdir = hjx + "/lsh_" + hw
print (desdir)
#唔,先,复制个文件夹出来再说 2333
shutil.copytree(source_dir,desdir)
#读取文件列表
def dirlist(path, allfile):
#filelist = os.listdir(path)
#下面这句用 glob 排除掉了 . 开头的隐藏文件
filelist = glob.glob(os.path.join(path, '*'))
for filename in filelist:
filepath = os.path.join(path, filename)
if os.path.isdir(filepath):
dirlist(filepath, allfile)
else:
allfile.append(filepath)
return allfile
#计算压缩前的文件夹大小
folder_size = 0
for (path, dirs, files) in os.walk(source_dir):
for file in files:
filename = os.path.join(path, file)
folder_size += os.path.getsize(filename)
pre_size = "%0.1f MB" % (folder_size/(1024*1024.0))
# 默认压缩jpeg
def default_compress_jpeg(path,extname):
lsh_jpeg = Image.open(path)
lsh_jpeg.save(newpath,'JPEG',quality= thequality )
# 默认压缩 png
def default_compress_png(path,newpath):
lsh_png = Image.open(path)
lsh_png.save(newpath,'PNG',quality= thequality )
#列出目标文件夹下所有文件
list = dirlist(desdir,[])
print("待处理文件列表")
print(list)
print("开始压缩")
i = 0
for x in list:
image_types = [".jpg",".png",".jpeg"]
fullpath = os.path.abspath(x)
path = os.path.split(x)[0]
filename = os.path.split(x)[1]
extname = os.path.splitext(x)[1]
if extname in image_types:
#print(fullpath)
i = i+1
newpath = fullpath
if extname == ".png":
default_compress_png(fullpath,newpath)
print(Fore.GREEN + "正在压缩 " + fullpath)
elif extname == ".jpg":
default_compress_jpeg(fullpath,newpath)
print(Fore.GREEN + "正在压缩 " + fullpath)
elif extname ==".jpeg":
default_compress_jpeg(fullpath,newpath)
print(Fore.GREEN + "正在压缩 " + fullpath)
else:
print(filename + "不是受支持的图片文件类型")
#print(filename)
# print(path)
#print(extname)
else:
print("incorrect type")
# 计算压缩后的文件夹大小
folder_size = 0
for (path, dirs, files) in os.walk(desdir):
for file in files:
filename = os.path.join(path, file)
folder_size += os.path.getsize(filename)
post_size = "%0.1f MB" % (folder_size / (1024 * 1024.0))
#计算程序运行时间
elapsed = (time.clock() - start)
print(Fore.BLUE + "所有图片压缩完成,一共压缩了" + str(i) + "张图片")
print (Fore.RED + "图片压缩完成,耗时:" + str(elapsed) + "秒")
print("所有图片已从" + pre_size + "压缩到了" + post_size)<file_sep>colorama==0.4.1
Pillow==5.4.1
|
f645216013dc56d0ff093d7d54d08c00e66007eb
|
[
"Markdown",
"Python",
"Text",
"Shell"
] | 4
|
Markdown
|
ibegyourpardon/lsh_compress
|
e6eb362d2eceff13b1e56fdee98f14dc5cdf6526
|
fda0919d2efa0bdcbefdd8e10b8ebab49835f335
|
refs/heads/master
|
<file_sep>import React from "react";
import styled from "styled-components";
import Typography from "@material-ui/core/Typography";
const StyledText = styled(Typography)`
color: #7c795d;
font-family: "Trocchi";
font-size: 2.5em;
font-weight: normal;
`;
const Title = ({ text }) => {
return (
<div
style={{
display: "flex",
justifyContent: "center",
width: "100%",
margin: "1.5rem 0",
}}
>
<StyledText nowrap={true}>{text}</StyledText>
</div>
);
};
export default Title;
<file_sep>import React, { Component } from "react";
import styled from "styled-components";
import Header from "../components/header";
import Title from "../components/status/title";
import WaterControl from "../components/status/waterControl";
import HistoryArea from "../components/status/historyArea";
import {
FlexRow,
CenterDivider,
RotateRefreshIcon,
} from "../components/sharedComponents";
import { currentStatus } from "../services/api";
import StatusComponent from "../components/status/statusComponent";
const ContentBox = styled.div`
display: flex;
flex-direction: column;
`;
const StatusBlock = styled(FlexRow)`
justify-content: space-around;
padding: 1.5rem 10rem 1rem 10rem;
@media (max-width: 1400px) {
padding: 1rem 4rem 1rem 4rem;
}
@media (max-width: 1025px) {
flex-direction: column;
align-items: center;
}
`;
class Main extends Component {
state = {
openDialog: false,
refresh: false,
isLoggedIn: false,
currentStatus: { humidity: "-", temp: "-", light: "-" },
};
constructor(props) {
super(props);
document.getElementById("body").className = "whiteTheme";
}
componentDidMount() {
this.getData();
}
getData = () => {
this.setState({ refresh: true });
currentStatus(
({ data }) => {
const currentStatus = { ...this.state.currentStatus };
const avg_temp = (data.data.temp1 + data.data.temp2) / 2;
const avg_light = (data.data.light1 + data.data.light2) / 2;
currentStatus.humidity = data.data.humid_arv.toFixed(2);
currentStatus.temp = avg_temp.toFixed(2);
currentStatus.light = avg_light.toFixed(2);
this.setState({ currentStatus, refresh: false });
},
(err) => {
console.log("getValue error.");
}
);
};
handleCloseDialog = () => {
this.setState({ openDialog: false });
};
handleAlert = (type) => {
this.setState({ openDialog: !this.state.openDialog });
console.log("ALERT", type);
};
handleWater = () => {
console.log("WATER !");
};
handleRefreshData = () => {
this.getData();
};
componentWillReceiveProps({ isLoggedIn }) {
this.setState({ isLoggedIn });
}
render() {
const { refresh, openDialog, isLoggedIn } = this.state;
return (
<div>
<Header isLoggedIn={isLoggedIn} {...this.props} />
<ContentBox>
<Title text="Environments Status"></Title>
<div
style={{
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
marginBottom: "1rem",
}}
>
<RotateRefreshIcon
onClick={this.handleRefreshData}
rotate={refresh}
/>
{refresh ? (
<p> Getting Data From Server ...</p>
) : (
<p> Click for Refresh Data</p>
)}
</div>
<StatusBlock>
<StatusComponent
type={"fresh"}
text={"HUMIDITY"}
value={this.state.currentStatus.humidity}
unit={"humidity unit"}
onAlert={() => this.handleAlert("humid")}
alertText={"HUMIDITY WARNING !"}
onOpenDialog={openDialog}
onCloseDialog={this.handleCloseDialog}
onWater={this.handleWater}
/>
<StatusComponent
type={"moderate"}
text={"TEMPERATURE"}
value={this.state.currentStatus.temp}
unit={"Celcius"}
onAlert={() => this.handleAlert("temp")}
alertText={"TEMPERATURE WARNING !"}
onOpenDialog={openDialog}
onCloseDialog={this.handleCloseDialog}
onWater={this.handleWater}
/>
<StatusComponent
type={"danger"}
text={"LIGHT"}
value={this.state.currentStatus.light}
unit={"light unit"}
onAlert={() => this.handleAlert("light")}
alertText={"LIGHT WARNING !"}
onOpenDialog={openDialog}
onCloseDialog={this.handleCloseDialog}
onWater={this.handleWater}
/>
</StatusBlock>
<CenterDivider margin="2rem 0 0 0" />
<div>
<Title text="Configure Water ON/OFF" />
<WaterControl status="loading" />
</div>
<CenterDivider margin="2rem 0" />
<HistoryArea {...this.props} />
<CenterDivider margin="2rem 0 4rem 0" />
</ContentBox>
</div>
);
}
}
export default Main;
<file_sep>import React from "react";
import styled, { keyframes } from "styled-components";
import Divider from "@material-ui/core/Divider";
import CachedIcon from "@material-ui/icons/Cached";
import CancelIcon from "@material-ui/icons/Cancel";
import ErrorOutlineOutlinedIcon from "@material-ui/icons/ErrorOutlineOutlined";
import CheckCircleOutlineIcon from "@material-ui/icons/CheckCircleOutline";
import RefreshIcon from "@material-ui/icons/Refresh";
export const FlexRow = styled.div`
display: flex;
flex-direction: row;
`;
const rotate360 = keyframes`
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
`;
export const shake = keyframes`
0% { transform: translate(1px, 1px) rotate(0deg); }
25% { transform: translate(-1px, -2px) rotate(-1deg); }
`;
export const WarningIcon = styled(ErrorOutlineOutlinedIcon)`
color: orangered;
cursor: pointer;
animation: ${shake} 0.5s infinite;
`;
export const ProgressIcon = styled(CachedIcon)`
animation: ${rotate360} 1.5s linear infinite;
`;
export const RotateRefreshIcon = styled(RefreshIcon)`
width: 3rem;
height: 3rem;
color: ${(props) => (props.rotate ? "#6c5ce7" : "#636e72")};
cursor: pointer;
transition: 0.75s;
animation: ${rotate360} ${(props) => (props.rotate ? "1.5s" : "0s")} linear
infinite;
:hover {
transform: scale(0.9);
}
`;
export const OffIcon = styled(CancelIcon)`
animation: ${shake} 1.5s infinite;
color: red;
`;
export const OnIcon = styled(CheckCircleOutlineIcon)`
color: #fff;
animation: ${shake} 1s infinite;
`;
export const Spinner = styled.div`
animation: ${rotate360} 1s linear infinite;
border-bottom: 2px solid blue;
border-top: 2px solid greenyellow;
border-left: 2px solid green;
background: transparent;
width: 1.5rem;
height: 1.5rem;
border-radius: 50%;
`;
export const BackGround = styled.div`
display: flex;
flex-direction: column;
position: relative;
width: 100vw;
height: 100vh;
background: ${(props) =>
props.fresh
? `radial-gradient(
ellipse farthest-corner at 100% 0,
#01ff70 5%,
#ffffff 95%
)`
: props.moderate
? `radial-gradient(
ellipse farthest-corner at 100% 0,
#FFDC00 5%,
#ffffff 95%
)`
: props.danger
? `radial-gradient(
ellipse farthest-corner at 100% 0,
#FF4136 5%,
#ffffff 95%
)`
: null};
`;
export const BackGroundStatus = styled.div`
background: ${(props) =>
props.fresh
? `radial-gradient(
ellipse farthest-corner at 100% 0,
#01ff70 5%,
#ffffff 95%
)`
: props.moderate
? `radial-gradient(
ellipse farthest-corner at 100% 0,
#FFDC00 5%,
#ffffff 95%
)`
: props.danger
? `radial-gradient(
ellipse farthest-corner at 100% 0,
#FF4136 5%,
#ffffff 95%
)`
: null};
border-radius: 10px;
transition: all 0.2s ease-in-out;
:hover {
transform: scale(1.05);
}
`;
const StyledDivider = styled(Divider)`
width: 90%;
margin: ${(props) => props.margin};
`;
export function CenterDivider({ margin }) {
return (
<FlexRow style={{ justifyContent: "center" }}>
<StyledDivider margin={margin} />
</FlexRow>
);
}
<file_sep>import React from "react";
import Button from "@material-ui/core/Button";
import HistoryIcon from "@material-ui/icons/History";
const HistoryArea = (props) => {
return (
<div
style={{
display: "flex",
justifyContent: "center",
}}
>
<div
style={{
width: "80%",
display: "flex",
justifyContent: "center",
}}
>
<Button
color="primary"
variant="contained"
startIcon={<HistoryIcon />}
onClick={() => {
window.location = "./history";
}}
>
HISTORY
</Button>
</div>
</div>
);
};
export default HistoryArea;
<file_sep>import React from "react";
import styled, { keyframes } from "styled-components";
import Alert from "../../components/alert";
import TitleStatus from "./titleStatus";
import ValueStatus from "./valueStatus";
import { BackGroundStatus, shake } from "../../components/sharedComponents";
const DetailsBox = styled(BackGroundStatus)`
width: 25%;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 1rem;
background: linear-gradient(#341f97 95%, rgba(127, 113, 248, 1) 100%);
box-shadow: 0px 0px 10px #0abde3;
overflow: hidden;
animation: ${shake} 1.5s;
@media (max-width: 1185px) {
width: 30%;
}
@media (max-width: 1025px) {
width: 45%;
margin: ${(props) => (props.text === "TEMPERATURE" ? "2rem" : null)};
}
@media (max-width: 750px) {
width: 70%;
margin: ${(props) => (props.text === "TEMPERATURE" ? "2rem" : null)};
}
@media (max-width: 600px) {
width: 85%;
margin: ${(props) => (props.text === "TEMPERATURE" ? "2rem" : null)};
}
`;
const StatusComponent = ({
type,
text,
onAlert,
alertText,
value,
unit,
onOpenDialog,
onCloseDialog,
onWater,
}) => {
return (
<DetailsBox
// fresh={type === "fresh"}
// moderate={type === "moderate"}
// danger={type === "danger"}
text={text}
>
<TitleStatus text={text} />
<ValueStatus value={value} unit={unit} />
{/* <Alert
onAlert={onAlert}
text={alertText}
onOpenDialog={onOpenDialog}
onCloseDialog={onCloseDialog}
onWater={onWater}
/> */}
</DetailsBox>
);
};
export default StatusComponent;
<file_sep>import React, { Component } from "react";
import styled from "styled-components";
import PaginationComponent from "./paginationComponent";
import { paginate } from "../../utils/paginate";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableContainer from "@material-ui/core/TableContainer";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
const StyledTableRow = styled(TableRow)`
background-color: ${(props) =>
props.data.indexOf(props.row) === 0 ? "greenyellow" : "none"};
cursor: pointer;
transition: all 0.2s ease-in-out;
:hover {
}
`;
class TableComponent extends Component {
state = {
currentPage: 1,
rowPerPage: 4,
data: [
{
name: "Date 1",
humidity: 159,
light: 6.0,
temperature: 24,
blabla: 4.0,
},
{
name: "Date 2",
humidity: 237,
light: 9.0,
temperature: 37,
blabla: 4.3,
},
{
name: "Date 3",
humidity: 262,
light: 16.0,
temperature: 24,
blabla: 6.0,
},
{
name: "Date 4",
humidity: 305,
light: 3.7,
temperature: 67,
blabla: 4.3,
},
{
name: "Date 5",
humidity: 356,
light: 16.0,
temperature: 49,
blabla: 3.9,
},
{
name: "Date 6",
humidity: 356,
light: 16.0,
temperature: 49,
blabla: 3.9,
},
{
name: "Date 7",
humidity: 356,
light: 16.0,
temperature: 49,
blabla: 3.9,
},
{
name: "Date 8",
humidity: 356,
light: 16.0,
temperature: 49,
blabla: 3.9,
},
{
name: "Date 9",
humidity: 356,
light: 16.0,
temperature: 49,
blabla: 3.9,
},
{
name: "Date 10",
humidity: 356,
light: 16.0,
temperature: 49,
blabla: 3.9,
},
],
};
handlePageChange = (page) => {
this.setState({ currentPage: page });
};
render() {
const { data, currentPage, rowPerPage } = this.state;
const test = [1, 2, 3];
let showedData = paginate(data, currentPage, rowPerPage);
return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
}}
>
<TableContainer style={{ width: "90%" }}>
<Table>
<TableHead>
<TableRow>
<TableCell>Date</TableCell>
<TableCell align="right">Avg. Humidity (unit) </TableCell>
<TableCell align="right">Avg. Light (unit) </TableCell>
<TableCell align="right">
Avg. Temperature (unit)
</TableCell>
<TableCell align="right">Avg. blabla (unit) </TableCell>
</TableRow>
</TableHead>
<TableBody>
{showedData.map((row) => (
<StyledTableRow data={this.state.data} row={row} key={row.name}>
<TableCell component="th" scope="row">
{row.name}
</TableCell>
<TableCell align="right">{row.humidity}</TableCell>
<TableCell align="right">{row.light}</TableCell>
<TableCell align="right">{row.temperature}</TableCell>
<TableCell align="right">{row.blabla}</TableCell>
</StyledTableRow>
))}
</TableBody>
</Table>
</TableContainer>
<PaginationComponent
rowPerPage={this.state.rowPerPage}
totalRow={this.state.data.length}
onPageChange={this.handlePageChange}
currentPage={this.state.currentPage}
/>
</div>
);
}
}
export default TableComponent;
<file_sep>import React, { Component } from "react";
import { signIn } from "../../services/api";
import { Spinner } from "../sharedComponents";
import { Button, Input } from "@material-ui/core";
import VpnKeyIcon from "@material-ui/icons/VpnKey";
class LoginForm extends Component {
state = {
account: { username: "", password: "" },
required: {
username: false,
password: <PASSWORD>,
},
errorMessage: "",
isLoading: false,
};
handleSubmit = (e) => {
e.preventDefault();
if (this.validateRequiredField()) {
this.setState({ isLoading: !this.state.isLoading });
signIn(
this.state.account,
({ data }) => {
console.log("success", data);
localStorage.setItem("token", data.token);
this.setState({ isLoading: !this.state.isLoading });
window.location = "./main";
},
(response) => {
this.setState({
isLoading: !this.state.isLoading,
errorMessage: response.data.note,
});
}
);
}
};
handleChange = (e) => {
const account = { ...this.state.account };
account[e.currentTarget.id] = e.currentTarget.value;
this.setState({ account });
};
validateRequiredField = () => {
const requiredList = Object.keys({ ...this.state.account });
const toSet = { ...this.state.required };
requiredList.map((v) => {
if (this.state.account[v]) {
toSet[v] = false;
} else {
toSet[v] = true;
}
});
this.setState({ required: toSet });
const requiredStatus = Object.values({ ...toSet });
if (requiredStatus.includes(true)) {
this.setState({ errorMessage: "Please complete the required field." });
return false;
} else {
this.setState({ errorMessage: "" });
return true;
}
};
render() {
return (
<form
onSubmit={this.handleSubmit}
style={{
display: "flex",
flexDirection: "column",
marginTop: "2rem",
}}
>
<Input
autoFocus
value={this.state.account.username}
onChange={this.handleChange}
placeholder="Username"
id="username"
/>
<Input
value={this.state.account.password}
onChange={this.handleChange}
placeholder="<PASSWORD>"
id="password"
type="password"
style={{ margin: "1rem 0 0" }}
/>
{this.state.errorMessage ? (
<p style={{ color: "red" }}>* {this.state.errorMessage}</p>
) : (
<p style={{ display: "none" }}></p>
)}
{this.state.isLoading ? (
<Button
type="submit"
color="primary"
variant="contained"
style={{
margin: "2rem 0 0",
width: "50%",
height: "2.3rem",
alignSelf: "center",
}}
>
<Spinner
style={{
borderBottom: "2px solid white",
borderTop: "transparent",
borderLeft: "2px solid white",
width: "1.2rem",
height: "1.2rem",
}}
/>
</Button>
) : (
<Button
type="submit"
startIcon={<VpnKeyIcon />}
color="primary"
variant="contained"
style={{
margin: "2rem 0 0",
width: "50%",
height: "2.3rem",
alignSelf: "center",
}}
>
LOGIN
</Button>
)}
</form>
);
}
}
export default LoginForm;
<file_sep>import React from "react";
import styled from "styled-components";
import { FlexRow } from "../sharedComponents";
import Button from "@material-ui/core/Button";
const StyledInst = styled(Button)`
color: #ffffff;
border: solid 2px whitesmoke;
padding: 0.5rem 1rem;
border-radius: 1rem;
@media (max-width: 915px) {
font-size: 0.75em;
padding: 0.5rem;
}
`;
const StyledToMainPage = styled(Button)`
color: #ffffff;
margin-left: 1rem;
@media (max-width: 915px) {
font-size: 0.9em;
}
`;
const StyledBar = styled.div`
width: 100%;
display: flex;
flex-direction: row;
justify-content: space-between;
background: #130f40;
padding: 0.5rem 0rem;
`;
const AppBarComponent = ({ isLoggedIn, history }) => {
return (
<StyledBar>
<StyledToMainPage
onClick={() => {
window.location = "./main";
}}
>
STATUS PAGE
</StyledToMainPage>
<FlexRow>
<StyledInst style={{ marginLeft: "1.5rem" }}>
WATER STATUS : PROGRESSING...
</StyledInst>
<StyledInst
style={{ margin: "0rem 1rem" }}
onClick={() => {
history.push("./history");
}}
>
HISTORY
</StyledInst>
{isLoggedIn ? (
<FlexRow>
<StyledInst
onClick={() => {
window.location = "./control";
}}
>
WATER CONTROLLER
</StyledInst>
<StyledInst
style={{
border: "solid 3px #ff7979",
color: "#ff7979",
margin: "0rem 1.5rem",
}}
onClick={() => {
localStorage.removeItem("token");
window.location = "./login";
}}
>
LOGOUT
</StyledInst>
</FlexRow>
) : (
<StyledInst
style={{ margin: "0rem 1.5rem 0rem 0rem" }}
onClick={() => {
window.location = "./login";
}}
>
Login
</StyledInst>
)}
</FlexRow>
</StyledBar>
);
};
export default AppBarComponent;
<file_sep>import React, { Component } from "react";
import Header from "../components/header";
import TableComponent from "../components/common/tableComponent";
import ChartComponent from "../components/common/chartComponent";
class History extends Component {
state = { isLoggedIn: false };
constructor(props) {
super(props);
document.getElementById("body").className = "whiteTheme";
}
componentWillReceiveProps({ isLoggedIn }) {
this.setState({ isLoggedIn });
}
render() {
return (
<div>
<Header isLoggedIn={this.state.isLoggedIn} {...this.props} />
<div>
<ChartComponent />
<TableComponent />
</div>
</div>
);
}
}
export default History;
<file_sep>import React from "react";
import styled from "styled-components";
const ValueStatusBox = styled.div`
display: flex;
flex-direction: row;
justify-content: flex-end;
align-items: center;
border-radius: 10px;
background: whitesmoke;
position: relative;
margin: 2rem 0;
overflow: hidden;
`;
const ValueBox = styled.div`
font-size: 1.5em;
margin: 0rem 0.5rem;
`;
const UnitBox = styled.div`
font-size: 2em;
margin-right: 2rem;
text-align: right;
font-weight: bold;
@media (max-width: 650px) {
font-size: 1.5em;
}
`;
const valueStatus = ({ value, unit }) => {
return (
<ValueStatusBox>
<div
style={{
width: "100%",
display: "flex",
justifyContent: "center",
position: "absolute",
}}
>
<ValueBox>{value}</ValueBox>
</div>
<UnitBox>Unit</UnitBox>
</ValueStatusBox>
);
};
export default valueStatus;
<file_sep>import React from "react";
import styled from "styled-components";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
import NotFoundIcon from "../assets/icons/notfound.svg";
const OutSideBox = styled.div`
display: flex;
justify-content: center;
align-items: center;
width: 100vw;
height: 100vh;
`;
const ContentBox = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
`;
const NotFound = (props) => {
return (
<OutSideBox>
<ContentBox>
<img src={NotFoundIcon} style={{ width: "20vmax" }} />
<Typography style={{ fontSize: "3vmax", margin: "2rem" }}>
404 PAGE NOT FOUND
</Typography>
<Button
color="default"
variant="contained"
onClick={() => {
window.location = "./main";
}}
>
BACK TO MAIN PAGE
</Button>
</ContentBox>
</OutSideBox>
);
};
export default NotFound;
<file_sep>import React, { Component } from "react";
import { Route, Redirect, Switch } from "react-router-dom";
import Control from "./pages/control";
import Main from "./pages/main";
import NotFound from "./pages/notFound";
import Login from "./pages/login";
import History from "./pages/history";
import "./index.css";
class App extends Component {
state = {
isLoggedIn: false,
};
componentDidMount() {
const isLoggedIn = localStorage.getItem("token");
if (isLoggedIn) this.setState({ isLoggedIn: true });
}
render() {
return (
<React.Fragment>
<Switch>
<Route
path="/iot-mushroom-web/main"
render={(props) => (
<Main {...props} isLoggedIn={this.state.isLoggedIn} />
)}
/>
<Route
path="/iot-mushroom-web/login"
render={(props) => (
<Login {...props} isLoggedIn={this.state.isLoggedIn} />
)}
/>
<Route
path="/iot-mushroom-web/history"
render={(props) => (
<History {...props} isLoggedIn={this.state.isLoggedIn} />
)}
/>
<Route
path="/iot-mushroom-web/control"
render={(props) => (
<Control {...props} isLoggedIn={this.state.isLoggedIn} />
)}
/>
<Route path="/iot-mushroom-web/not-found" component={NotFound} />
<Redirect
from="/iot-mushroom-web"
exact
to="/iot-mushroom-web/main"
/>
<Redirect to="/iot-mushroom-web/not-found" />
</Switch>
</React.Fragment>
);
}
}
export default App;
<file_sep>import React, { Component } from "react";
import styled from "styled-components";
import LoginForm from "../components/common/loginForm";
import Mushroom from "../assets/images/mushroom.svg";
import Grass from "../assets/images/grass.svg";
import Button from "@material-ui/core/Button";
import { Typography } from "@material-ui/core";
import PageviewIcon from "@material-ui/icons/Pageview";
import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
const StyledBackGround = styled.div`
display: flex;
margin: 7rem 0;
align-items: center;
justify-content: center;
`;
const StyledContentBox = styled.div`
display: flex;
flex-direction: column;
background: whitesmoke;
align-items: center;
justify-content: center;
padding: 4rem 5rem;
border: #ffff solid 2px;
border-radius: 20px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.5);
`;
const StyledMushroomImg = styled.img`
width: 75px;
height: 75px;
`;
class Login extends Component {
state = { isLoggedIn: false };
componentWillReceiveProps({ isLoggedIn }) {
this.setState({ isLoggedIn });
}
redirectToStatusPage = () => {
window.location = "./main";
};
render() {
return !this.state.isLoggedIn ? (
<StyledBackGround>
<StyledContentBox>
<div style={{ display: "flex" }}>
<StyledMushroomImg src={Mushroom} />
<StyledMushroomImg
src={Grass}
style={{
width: "20px",
paddingTop: "1rem",
}}
/>
</div>
<Typography style={{ fontSize: "1.5em" }}>Sign In</Typography>
<LoginForm />
<Typography style={{ margin: "1rem 0" }}>OR</Typography>
<Button
variant="contained"
color="secondary"
startIcon={<PageviewIcon />}
onClick={() => {
window.location = "./main";
}}
>
GO TO STATUS PAGE
</Button>
</StyledContentBox>
</StyledBackGround>
) : (
this.redirectToStatusPage()
);
}
}
export default Login;
|
f4e90af0c5359108e7648b4ea9165cfbb8a5082e
|
[
"JavaScript"
] | 13
|
JavaScript
|
WisTiCeJEnT/iot-mushroom-web
|
5287c4142b4c0f3e83e0f714b023929c1a00cea1
|
a9ed54635a640ecd485c1cce21aaedce611e7ab9
|
refs/heads/master
|
<file_sep>/**
*
*/
/**
* Tests para DAOs.
*
* @author Equipo 1
*
*/
package com.ipartek.formacion.repository;<file_sep># Proyecto Dado
Proyecto web 2.5 desarrollado con Java6 y Spring3.
i18n Euskera, Castellano e Ingles.

## Requisitos:
Es necesario tener instalado el siguiente entorno para poder ejecutar la app
-Java JDK 6 o superior
-SGBD mysql 5.0.8 o superior
-Servidor de aplicaciones tomcat 6 o superior.
## Instalacion:
-Importar scrip de la carpeta deploy/install.sql
-Desplegar deploy/dado/.war en tomcat
-Acceder mediante la url "http://localhost:8080/dado"
Si desea cambiar las credenciales de la base de datos, modificar el fichero src/main/resources/database.properties y volver a generar el .war.
<file_sep>package com.ipartek.formacion.domain;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class HistorialTest {
static final Date fecha = new Date();
static Usuario usuario = null;
static Historial historial = null;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
usuario = new Usuario();
usuario.setId(1);
usuario.setNombre("Aaron");
historial = new Historial();
}
@AfterClass()
public static void tearDownAfterClass() throws Exception {
historial = null;
usuario = null;
}
@Before()
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testConstructor() {
assertEquals(null, historial.getFecha());
assertEquals(null, historial.getU());
}
@Test
public void testSetterGetter() {
historial.setFecha(fecha);
assertEquals(fecha, historial.getFecha());
historial.setU(usuario);
assertEquals(usuario, historial.getU());
}
}
<file_sep>package com.ipartek.formacion.domain;
import java.util.Date;
/**
*
* @author Equipo 1
*
*/
public class Historial {
private Usuario usuario;
private Date fecha;
public Usuario getU() {
return this.usuario;
}
public void setU(Usuario usuario) {
this.usuario = usuario;
}
public Date getFecha() {
return this.fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
@Override()
public String toString() {
return "Historial [u=" + this.usuario.getNombre() + ", fecha=" + this.fecha + "]";
}
}
<file_sep>package com.ipartek.formacion.domain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Date;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class DadoTest {
static final int idDado = 1;
static final int numero = 2;
static final Date fecha = new Date();
static final int max = 10;
static final int min = 1;
static final int maxUsuarios = 10;
static Dado dado = null;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
dado = new Dado();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
dado = null;
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testConstructor() {
assertEquals(-1, dado.getId());
assertEquals(0, dado.getNumero());
assertEquals(null, dado.getFecha());
}
@Test
public void testSetterGetter() {
dado.setId(idDado);
assertEquals(idDado, dado.getId());
dado.setNumero(numero);
assertEquals(numero, dado.getNumero());
dado.setFecha(fecha);
assertEquals(fecha, dado.getFecha());
}
@Test
public void testLanzar() {
dado.lanzar(maxUsuarios);
assertTrue(max >= dado.getNumero());
assertTrue(min <= dado.getNumero());
}
}
<file_sep>package com.ipartek.formacion.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ipartek.formacion.domain.Historial;
import com.ipartek.formacion.repository.DadoDAO;
@Service(value="dadoService")
public class DadoServiceImpl implements DadoService {
@Autowired()
private DadoDAO dadoDAO;
@Override()
public List<Historial> getHistorial() {
return this.dadoDAO.getHistorial();
}
@Override()
public boolean addTirada(int idUsuario) {
return this.dadoDAO.addTirada(idUsuario);
}
}
|
5ce8cdbcc2941e97544411dc280c47c880206910
|
[
"Markdown",
"Java"
] | 6
|
Java
|
Eneko-Aaron/dado_eq1
|
afd148df19fdef6ba6bf4f0c22f44a762199de4e
|
c2ad630849fcdce529073480b573973471c3a76a
|
refs/heads/main
|
<file_sep>#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define SUCCESS_STATUS (0)
#define PUTENV_ERROR (1)
#define PUTENV_ERROR_VALUE (-1)
int main() {
// Создание переменной типа time_t (числовой тип из библотеки time.h)
time_t now;
// Создание структуры для последущего хранения времени
struct tm *sp;
// Установка переменной окружения TZ для последующего опеределения
// времени в этом часовом поясе
int putenvRes = putenv("TZ=America/Los_Angeles");
if (putenvRes == PUTENV_ERROR_VALUE) {
perror("Error while setting Time Zone");
return PUTENV_ERROR;
}
// Запись текущего времени в переменную now - значение в секундах, считая
// от timestamp (01.01.1970 00:00)
time(&now);
// Вывод текущего времени в формате (Month Week Day H:M:S Year).
// Функция ctime как раз преобразует время в секундах из переменной now
// в строку с учетом часового пояса из перменной TZ
printf("%s", ctime(&now));
// Функция localtime возвращает указатель на структуру, в которой время
// хранится в полях (т.е. tm_mday - день, tm_min - минута). Время
// представляется как локальное (т.е для текущего часового пояса)
sp = localtime(&now);
// Вывод времени на основе полей полученной структуры
printf(
"%d/%d/%02d %d:%02d %s\n",
sp->tm_mon + 1,
sp->tm_mday,
sp->tm_year + 1900,
sp->tm_hour,
sp->tm_min,
tzname[sp->tm_isdst]
);
return SUCCESS_STATUS;
}
<file_sep>#include <signal.h>
#include <stdio.h>
static int a = 0;
static int flag = 1;
static int fd;
void beep(int sig){
a++;
write(fd, '\a', 1);
}
void leave(int sig){
flag = 0;
}
int main(){
fd = open("/dev/tty", O_RDWR);
if(signal(SIGINT, beep) == SIG_ERR){
perror("error signal");
return 0;
}
if(signal(SIGQUIT, leave) == SIG_ERR){
perror("error leave signal");
return 0;
}
do{
} while(flag);
printf("%d", a);
}<file_sep>#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#define FAIL -1
#define SUCCESS 0
#define CHECK_INIT 0
#define OPEN_ERROR -1
#define FCNTL_ERROR -1
#define LOCK_ERROR -1
#define PRINTF_ERROR 0
#define CLOSE_ERROR -1
#define OPEN_EDITOR_ERROR -1
#define SYSTEM_ERROR -1
#define ALLOC_ERROR NULL
const char* editor_format_str = "vim %s";
int try_open_editor(const char* file_name)
{
int length = snprintf(NULL, 0, editor_format_str, file_name);
if (length < PRINTF_ERROR)
{
perror("Can't get result length");
return OPEN_EDITOR_ERROR;
}
length += 1;
char* command = (char*)malloc(length * sizeof(*command));
if (command == ALLOC_ERROR)
{
perror("Can't allocate memory for command");
return OPEN_EDITOR_ERROR;
}
length = snprintf(command, length, editor_format_str, file_name);
if (length < PRINTF_ERROR)
{
free(command);
return OPEN_EDITOR_ERROR;
}
int system_check = CHECK_INIT;
system_check = system(command);
if (system_check == SYSTEM_ERROR)
{
perror("System executed with error");
free(command);
return OPEN_EDITOR_ERROR;
}
free(command);
return SUCCESS;
}
int set_remove_lock(struct flock* lock, int file_descriptor, char* file_name)
{
int fcntl_check = CHECK_INIT;
lock->l_type = F_WRLCK;
printf("Setting lock\n");
fcntl_check = fcntl(file_descriptor, F_SETLK, lock);
if (fcntl_check == FCNTL_ERROR)
{
perror("fcntl() lock error");
}
printf("Press Enter to open edtior\n");
char enter_symbol = getchar();
int check = CHECK_INIT;
check = try_open_editor(file_name);
if (check == OPEN_EDITOR_ERROR)
{
printf("Error while calling editor\n");
return LOCK_ERROR;
}
lock->l_type = F_UNLCK;
printf("Removing lock\n");
fcntl_check = fcntl(file_descriptor, F_SETLK, lock);
if (fcntl_check == FCNTL_ERROR)
{
perror("fcntl() unlock error");
return LOCK_ERROR;
}
return SUCCESS;
}
int main(int argc, char *argv[])
{
struct flock lock;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
int file_descriptor = CHECK_INIT;
int lock_check = CHECK_INIT;
int close_check = CHECK_INIT;
if (argc != 2)
{
printf("Usage: a.out f1\n");
return FAIL;
}
file_descriptor = open(argv[1], O_RDWR);
if (file_descriptor == OPEN_ERROR)
{
perror("Can't open file");
return FAIL;
}
lock_check = set_remove_lock(&lock, file_descriptor, argv[1]);
if (lock_check == LOCK_ERROR)
{
printf("Error while setting lock\n");
close_check = close(file_descriptor);
if (close_check == CLOSE_ERROR)
{
perror("Error with closing the file");
return FAIL;
}
return FAIL;
}
close_check = close(file_descriptor);
if (close_check == CLOSE_ERROR)
{
perror("Error with closing the file");
return FAIL;
}
return SUCCESS;
}
<file_sep>#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdbool.h>
#define SUCCESS_STATUS (0)
#define MEMORY_ALLOCATION_ERROR (1)
#define MEMORY_REALLOCATION_ERROR (2)
#define EOF_STATUS (3)
#define LINE_END_SYMBOL ('\n')
#define TERMINAL_ZERO ('\0')
#define EXIT_SYMBOL ('.')
#define BUF_SIZE (100)
typedef struct ListNode {
char *value;
struct ListNode *next;
struct ListNode *prev;
} ListNode;
int initList(ListNode **head, ListNode **tail) {
*head = (ListNode*) malloc(sizeof(ListNode));
if (*head == NULL) {
perror("Error on head node creation");
return MEMORY_ALLOCATION_ERROR;
}
(*head)->value = NULL;
(*head)->next = NULL;
(*head)->prev = NULL;
*tail = *head;
return SUCCESS_STATUS;
}
int addNode(ListNode **head, char *value, int valueLen) {
ListNode *node = (ListNode*) malloc(sizeof(ListNode));
if (node == NULL) {
perror("Error on node creation");
return MEMORY_ALLOCATION_ERROR;
}
node->value = (char*) malloc(sizeof(char) * (valueLen + 1));
if (node->value == NULL) {
perror("Error on line copy creation");
return MEMORY_ALLOCATION_ERROR;
}
// Копирование значения из введённой строки
strncpy(node->value, value, valueLen);
node->value[valueLen] = TERMINAL_ZERO;
// Переопределение указателей
node->next = *head;
node->prev = NULL;
(*head)->prev = node;
*head = node;
return SUCCESS_STATUS;
}
void freeList(ListNode *head) {
ListNode *tmpNode;
while (head != NULL) {
tmpNode = head;
head = head->next;
free(tmpNode);
}
}
int readLine(char **line, int *lineLen) {
int idx = 0;
while (true) {
// Чтение строки из входного потока
char *fgetsRes = fgets(&(*line)[idx], BUF_SIZE, stdin);
if (fgetsRes == NULL) {
fprintf(stderr, "Unexpected file end\n");
return EOF_STATUS;
}
// Запись в переменную текущего размера строки
idx = (int) strnlen(*line, idx + BUF_SIZE);
// Проверка на конец строки
if ((*line)[idx - 1] == LINE_END_SYMBOL) {
break;
}
// Перевыделение памяти под строку
char *tmp = (char*) realloc(*line, sizeof(char) * (idx + BUF_SIZE));
if (tmp == NULL) {
perror("Error on line realloc");
return MEMORY_REALLOCATION_ERROR;
}
*line = tmp;
}
*lineLen = idx;
return SUCCESS_STATUS;
}
int main() {
// Выделение пямяти под строку, в которую будут
// записываться данные из входного потока
char *line = (char*) malloc(sizeof(char) * BUF_SIZE);
if (line == NULL) {
perror("Error on line initialization");
return MEMORY_ALLOCATION_ERROR;
}
int lineLen;
// Создание указателей на начало и конец списка
ListNode *head, *tail;
int initListRes = initList(&head, &tail);
if (initListRes != SUCCESS_STATUS) {
free(line);
return initListRes;
}
// Построчное чтение из входного потока, пока не дойдём до символа '.'
while (true) {
int readLineRes = readLine(&line, &lineLen);
if (readLineRes != SUCCESS_STATUS) {
freeList(head);
free(line);
return readLineRes;
}
if (line[0] == EXIT_SYMBOL) {
break;
}
int addNodeRes = addNode(&head, line, lineLen);
if (addNodeRes != SUCCESS_STATUS) {
freeList(head);
free(line);
return addNodeRes;
}
}
// Вывод списка
for (ListNode *node = tail->prev; node != NULL; node = node->prev) {
printf("%s", node->value);
}
// Очистка памяти
freeList(head);
free(line);
return SUCCESS_STATUS;
}<file_sep>#include <unistd.h>
#include <stdio.h>
#define SUCCESS_STATUS (0)
#define WRONG_ARGUMENTS_NUMBER_ERROR (1)
#define FILE_OPEN_ERROR (2)
#define SETUID_ERROR (3)
#define SETUID_ERROR_VALUE (-1)
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Wrong arguments number");
return WRONG_ARGUMENTS_NUMBER_ERROR;
}
// Создание указателя на файл
FILE *file;
// Вывод действительного и эффективного идентификаторов процесса
printf("Real user id: %d\nEffective user id: %d\n", getuid(), geteuid());
// Первая попытка чтения файла
file = fopen(argv[1], "r");
if (file == NULL) {
perror("Error on first file open");
return FILE_OPEN_ERROR;
}
fclose(file);
// Установка эффективого индентификатора равным действительному
int setuidRes = setuid(getuid());
if (setuidRes == SETUID_ERROR_VALUE) {
perror("Error on setuid");
return SETUID_ERROR;
}
// Вывод идентификаторов после использования функции setuid
printf("New real user id: %d\nNew effective user id: %d\n", getuid(), geteuid());
// Вторая попытка чтения файла
file = fopen(argv[1], "r");
if (file == NULL) {
perror("Error on second file open");
return FILE_OPEN_ERROR;
}
fclose(file);
return SUCCESS_STATUS;
}
<file_sep>#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
struct termios orig_termios;
static int fd;
void disableRawMode(){
int set_check = 0;
set_check = tcsetattr(fd, TCSAFLUSH, &orig_termios);
if(set_check == -1){
perror("Error setting flags");
return 0;
}
}
void enableRawMode() {
int set_check = 0;
int get_check = 0;
get_check = tcgetattr(fd, &orig_termios);
if(get_check == -1){
perror("Error getting attributes");
return 0;
}
struct termios raw = orig_termios;
raw.c_lflag &= ~(ISIG | ICANON);
raw.c_cc[VMIN] = 1;
set_check = tcsetattr(fd, TCSAFLUSH, &raw);
if(set_check == -1){
perror("Error setting attributes");
return 0;
}
}
int main(){
fd = open("/dev/tty", O_RDWR);
enableRawMode();
int a = 0;
printf("2*2=");
int scan_check = 0;
scan_check = read
if(scan_check == NULL)
{
perror("Error reading");
return 0;
}
disableRawMode();
}<file_sep>#include<stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#define FORK_ERROR -1
#define EXEC_ERROR -1
#define WAIT_ERROR -1
#define CHECK_INIT 0
#define CHILD_PROCESS 0
#define PARENT_PROCESS 1
#define END_OF_ARGS NULL
int main(int argc, char* argv[])
{
pid_t fork_check = CHECK_INIT;
int status = 0;
pid_t wait_check = CHECK_INIT;
// if (argc != 2)
// {
// printf("Usage: a.out f1\n");
// return EXIT_FAILURE;
// }
fork_check = fork();
if (fork_check == FORK_ERROR)
{
perror("Error while creating process");
return EXIT_FAILURE;
}
if (fork_check == CHILD_PROCESS)
{
//printf("\nI am a new process\nMy PID: %d\nMy PPID:%d\n",getpid(),getppid());
int execl_check = CHECK_INIT;
execl_check = execl("/bin/cat", "cat", argv[1], END_OF_ARGS);
if(execl_check == EXEC_ERROR)
{
perror("Error while openning cat");
return EXIT_FAILURE;
}
}
if (fork_check >= PARENT_PROCESS)
{
printf("I am parent\nMy child's PID: %d\nMy PID: %d\n", fork_check, getpid());
}
wait_check = wait(&status);
if (wait_check == WAIT_ERROR)
{
perror("Error while waiting child determination");
return EXIT_FAILURE;
}
printf("\nWait ended.\n");
return EXIT_SUCCESS;
}
|
16e209eeafb39befd01d03d5b836d819b454830e
|
[
"C"
] | 7
|
C
|
maaaaango11/OS
|
fe3b374bcb252c918569929d5db947aebc4184e8
|
1511ac5122a65c73ace101223f2c475c23949c60
|
refs/heads/master
|
<repo_name>pom421/redux-counter-global<file_sep>/README.md
This is another redux counter example.
But this time, the purpose is to have potentially multiple counters. And a global one which sums up all the little ones.
The code shows how to add state dynamically and to mix N instances of the same component with an id props.
<file_sep>/src/ducks.js
export const increment = id => ({
type: "INC",
id
});
export const decrement = id => ({
type: "DEC",
id
});
export const initCounter = (id, defaultValue) => ({
type: "INIT",
id,
defaultValue
});
export const reset = (id, defaultValue) => ({
type: "RESET",
id,
defaultValue
});
// crée un nouvel état en assurant l'immutabilité
const buildNewState = ({ counters }, { id }, cb) => {
const newCounters = counters.map(elt => {
if (elt.id === id) {
return {
id: elt.id,
count: cb(elt.count)
};
} else {
return elt;
}
});
const newCount = newCounters.reduce((prev, curr) => {
return curr.count + prev;
}, 0);
return { newCounters, newCount };
};
export const counterReducer = (state = { count: 0, counters: [] }, action) => {
const { id } = action;
let res;
switch (action.type) {
case "INC":
res = buildNewState(state, action, elt => elt + 1);
return {
count: res.newCount,
counters: res.newCounters
};
case "DEC":
res = buildNewState(state, action, elt => elt - 1);
return {
count: res.newCount,
counters: res.newCounters
};
case "RESET":
res = buildNewState(state, action, () => action.defaultValue);
return {
count: res.newCount,
counters: res.newCounters
};
case "INIT":
let newCounters = state.counters.concat({
id,
count: action.defaultValue
});
res = buildNewState(
{ counters: newCounters },
action,
() => action.defaultValue
);
return {
count: res.newCount,
counters: res.newCounters
};
default:
return state;
}
};
<file_sep>/src/components/Counter.js
import React from "react";
import { connect } from "react-redux";
import { increment, decrement, initCounter, reset } from "../ducks";
class Counter extends React.Component {
componentDidMount() {
this.props.initCounter(
this.props.id,
this.props.defaultValue ? this.props.defaultValue : 0
);
}
render() {
const { id, count, defaultValue, decrement, increment, reset } = this.props;
return (
<div>
<h2>
Compteur{" "}
<span style={{ fontSize: 14 }}>
<button onClick={() => reset(id, defaultValue ? defaultValue : 0)}>
reset
</button>
</span>
</h2>
<button onClick={() => decrement(id)}>-</button>
<span style={{ margin: "0 10px" }}>{count}</span>
<button onClick={() => increment(id)}>+</button>
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
let subState = state.counters.filter(elt => elt.id === ownProps.id);
//return subState.length === 1 ? subState[0] : {};
return subState[0];
};
// auto wrap with dispatch
const mapDispatchToProp = {
increment,
decrement,
initCounter,
reset
};
export default connect(
mapStateToProps,
mapDispatchToProp
)(Counter);
|
63f86ab5cf87572efeefef86382260f63a9d61f3
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
pom421/redux-counter-global
|
93f6d5aa360a0e53fbaef76f149fe98ec7a69936
|
034a4473e7b871a5c0b1ac4e04a5aae5d4c2675d
|
refs/heads/master
|
<repo_name>woshare/qipai_server<file_sep>/Doudizhu-sever-master/Doudizhu-sever-master/socket/msgHandler.js
/*消息发送类*/
// var loginHandler = require('../game/login/loginHandler');
var gameSever = require('../game/game/gameSever');
var commands = require('./commands');
var events = require('events');
var emitter = new events.EventEmitter();
// addEvent(commands.REGISTER, loginHandler);
// addEvent(commands.LOGIN, loginHandler);
addEvent(commands.MATCH_PLAYER, gameSever);
addEvent(commands.PLAY_GAME, gameSever);
addEvent(commands.PLAYER_PLAYCARD, gameSever);
addEvent(commands.PLAYER_WANTDIZHU, gameSever);
addEvent(commands.WS_CLOSE, gameSever);
function addEvent(command, handler) {
emitter.on(command, function (ws, data) {
handler.handMsg(ws, data);
})
}
exports.dispatch = function (command, ws, data) {
emitter.emit(command, ws, data);
};
<file_sep>/Doudizhu-sever-master/Doudizhu-sever-master/game/game/roomServer.js
/**
* 单个房间管理
* */
var wss = require('../../socket/websocket');
var commands = require('../../socket/commands');
var RoomServer = function () {
};
var p = RoomServer.prototype;
//房间信息
p.roomId = 0;
//玩家信息
p.players = [];
p.p1Cards = [];
p.p2Cards = [];
p.p3Cards = [];
p.dzCards = [];
//当前信息
p.curPlayerIndex = 1; //暂时初始为1,游戏进程中为1,2,3
p.addCurIndex = function () {
this.curPlayerIndex++;
if(this.curPlayerIndex > 3)
{
this.curPlayerIndex = 1; //每次到4就变回1
}
};
/** 关于正在出的牌
* 初步想法是记录牌型:
* 单,对,三带一,顺子,连对,飞机,四带二,炸弹
* 顺子连队飞机的话必须数量对上(除开炸弹,毕竟炸弹不讲道理的)
* 然后按照斗地主的规则,记录最小的一张(头子)
* 特例:4443,记录4 ; 666654,记录6
* */
//先定义可能出现的牌型
const CARD_TYPE = {
//各种牌型的对应数字
NO_CARDS : -1, //前面没有牌(每次开始出牌)
ERROR_CARDS : 0, //错误牌型
SINGLE_CARD : 1, //单牌
DOUBLE_CARD : 2, //对子
THREE_CARD : 3,//3不带
THREE_ONE_CARD : 4,//3带1
THREE_TWO_CARD : 5, //3带2
BOMB_TWO_CARD : 6, //四个带2张单牌
BOMB_FOUR_CARD : 7, //四个带2对
CONNECT_CARD : 8, //连牌
COMPANY_CARD : 9, //连队
AIRCRAFT_CARD : 10, //飞机不带
AIRCRAFT_WING : 11, //飞机带单牌或对子
BOMB_CARD : 12, //炸弹
KINGBOMB_CARD : 13//王炸
};
//只记录最小的一张,特例比如4443,要记录4,注意这里的index是跟curPlayerIndex不一样
p.curCards = {type: CARD_TYPE.NO_CARDS, header:0, cards:[]};
p.initGame = function () {
var cards = getNewCards54();
this.p1Cards = cards.slice(0,17);
this.p2Cards = cards.slice(17,34);
this.p3Cards = cards.slice(34,51);
this.dzCards = cards.slice(51,54);
this.sendToOnePlayers(1, {command:commands.PLAY_GAME, content:{ state: 0, roomId: this.roomId, cards:this.p1Cards}});
this.sendToOnePlayers(2, {command:commands.PLAY_GAME, content:{ state: 0, roomId: this.roomId, cards:this.p2Cards}});
this.sendToOnePlayers(3, {command:commands.PLAY_GAME, content:{ state: 0, roomId: this.roomId, cards:this.p3Cards}});
this.changeState(3);
};
//当前状态 2是结算,1是游戏中, 3是抢地主
p.changeState = function (state) {
switch (state){
case 1:
this.sendToRoomPlayers({command:commands.PLAY_GAME, content:{ state:1, curPlayerIndex:this.curPlayerIndex, curCard:this.curCards }});
break;
case 2:
this.sendToRoomPlayers({command:commands.PLAY_GAME, content:{state:2, scores:this.scores}});
break;
case 3:
this.curPlayerIndex = Math.ceil(Math.random() * 3);
this.sendToRoomPlayers({command:commands.PLAYER_WANTDIZHU, content:{ state:3, curPlayerIndex:this.curPlayerIndex, nowScore:0}});
break;
}
};
//处理玩家请求
p.handlePlayersQuest = function (index, data) {
var quest = data.command;
var seq = data.seq;
console.log('玩家的请求' + quest);
switch(quest)
{
case commands.PLAYER_PLAYCARD:
this.playCard(index, data.content.curCards, seq);
break;
case commands.PLAYER_WANTDIZHU:
this.wantDizhu(index, data.content, seq);
break;
}
};
p.nowBigger = 0; //这个数据用来记录当前牌最大的那个人
p.passNum = 0; //这个数据用来记录有几个人点了pass,如果有2个,说明要重新出牌了。
p.playCard = function (index, curCards, seq) {
//前后端都需要判断出牌是否符合规则
// if(cardPlayAble(this["p"+index+"Cards"], content.cards))
// {
//
// }
if(curCards.cards.length !== 0)
{
if(!this.removeCards(index ,curCards.cards))
{
console.log('有人出了一张他没有的牌?!')
}
}
console.log('告知玩家出牌成功');
this.sendToOnePlayers(index, {command:commands.PLAYER_PLAYCARD, seq:seq, code:0});
//如果出了牌,就替换最新的当前牌
if(curCards.type !== -2)
{
this.curCards = curCards;
this.passNum = 0; //每次有人出了牌,都要重新计算不要次数
}else//有人点击了过牌
{
this.passNum++;
if(this.passNum === 1) //第一次点击的时候记录,第二次因为curindex已经变了所以不记录
{
this.nowBigger = this.curPlayerIndex - 1 < 1 ? 3 : this.curPlayerIndex - 1;
console.log('有一个玩家点击了过牌现在牌最大的玩家是'+this.nowBigger);
this.curCards.type = -2;
}else if(this.passNum === 2) //连续两个人点击了过,说明要重新发起出牌流程,而起始就是之前最大的那个人
{
console.log('有两个玩家点击了过牌');
this.passNum = 0;
this.curPlayerIndex = this.nowBigger;
this.sendToRoomPlayers({command:commands.PLAY_GAME, content:{ state:1, curPlayerIndex:this.curPlayerIndex, curCard:{type: CARD_TYPE.NO_CARDS, header:0, cards:[]}}});
this.nowBigger = 0;
return;
}
}
//通知下一个玩家和出的牌
this.addCurIndex();
this.sendToRoomPlayers({command:commands.PLAY_GAME, content:{ state:1, curPlayerIndex:this.curPlayerIndex, curCard:this.curCards}});
};
p.removeCards = function (index, cards) {
var cardGroup = this['p'+index+'Cards'];
console.log('cards',cards);
console.log('cardGroup',cardGroup);
var havaThisCard;
for(var i = 0; i < cards.length; i++)
{
havaThisCard = false;
for(var j = 0; j < cardGroup.length; j++)
{
if(cards[i] === cardGroup[j])
{
havaThisCard = true;
console.log('zhixing');
cardGroup.splice(j,1);
//某个玩家出完牌了
if(cardGroup.length === 0)
{
this.countScore(index); //算分
this.changeState(2);
}
break;
}
}
if(!havaThisCard) return false;
}
return true;
};
p.zhaTimes = 0; //用来记录翻倍次数
p.scores = {}; //本局得分
p.countScore = function (index) {
var score = this.nowScore;
for(var i = 0; i < this.zhaTimes; i++)
{
score = score * 2;
}
var other1 = index - 1 < 1 ? 3 : index - 1;
var other2 = index + 1 > 3 ? 1 : index + 1;
var dizhu = this.dizhu;
var obj = {};
if(index === dizhu)
{
obj[other1] = -1 * score;
obj[other2] = -1 * score;
obj[dizhu] = 2 * score;
}else
{
obj[other1] = score;
obj[other2] = score;
obj[dizhu] = -2 * score;
}
this.scores = obj;
};
p.nowScore = 0; //记录当前抢地主到几分了
p.dizhu = 0; //记录几号玩家是地主
p.wantDizhuTimes = 0; //记录是第几个玩家开始抢
p.wantDizhu = function (index, content, seq) {
var score = content.score;
this.wantDizhuTimes++;
console.log('告知玩家叫分成功');
this.sendToOnePlayers(index, {command:commands.PLAYER_WANTDIZHU, seq:seq, code:0});
//到3分了说明有人已经抢到地主
if(score ===3)
{
this.nowScore = score;
this['p'+index+'Cards'] = this['p'+index+'Cards'].concat(this.dzCards);
this.sendToRoomPlayers({command:commands.PLAYER_WANTDIZHU, content:{ state:3, dizhu:this.curPlayerIndex, dizhuCards:this.dzCards, nowScore:this.nowScore}});
this.dizhu = index;
this.curPlayerIndex = index;
this.changeState(1);
return;
}else if(score > this.nowScore)
{
this.nowScore = score;
this.dizhu = index;
}
if(this.wantDizhuTimes === 3)
{
this['p'+index+'Cards'] = this['p'+index+'Cards'].concat(this.dzCards);
this.sendToRoomPlayers({command:commands.PLAYER_WANTDIZHU, content:{ state:3, dizhu:this.dizhu, dizhuCards:this.dzCards, nowScore:this.nowScore}});
this.curPlayerIndex = this.dizhu;
this.changeState(1);
console.log();
}else
{
this.addCurIndex();
this.sendToRoomPlayers({command:commands.PLAYER_WANTDIZHU, content:{ state:3, curPlayerIndex:this.curPlayerIndex, nowScore:this.nowScore}});
}
};
//向房间的所有玩家发送信息
p.sendToRoomPlayers = function (data) {
for(var i = 0; i < this.players.length; i++)
{
this.players[i].ws.send(JSON.stringify(data));
}
};
//向房间的某一个玩家发送信息
p.sendToOnePlayers = function (index, data) {
this.players[index - 1].ws.send(JSON.stringify(data));
};
//取得一组打乱的牌(开局时)
function getNewCards54() {
var arr = [];
for( var i = 1; i < 55; i++)
{
arr.push(i);
}
arr = arr.shuffle();
return arr;
}
//打乱算法
if (!Array.prototype.shuffle) {
Array.prototype.shuffle = function() {
for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
return this;
};
}
module.exports = RoomServer;<file_sep>/Doudizhu-sever-master/Doudizhu-sever-master/app.js
var express =require('express');
var app = express();
var wss = require('./socket/websocket');
app.listen(3000);
console.log('sever start');<file_sep>/Doudizhu-sever-master/Doudizhu-sever-master/socket/commands.js
/**
* Created by WinAsia on 2017/6/15.
*/
/*消息码*/
const commands = {
SYSTEM_MSG:1,
REGISTER:2,
LOGIN:3,
MATCH_PLAYER:4,
PLAY_GAME:5,
ROOM_NOTIFY:6,
PLAYER_PLAYCARD:7,
PLAYER_WANTDIZHU:8,
WS_CLOSE:9
};
module.exports = commands;<file_sep>/Doudizhu-sever-master/Doudizhu-sever-master/game/game/gameSever.js
/**
* Created by wqy on 2017/6/15.
*/
var commands = require('../../socket/commands');
var RoomServer = require('./roomServer');
exports.handMsg = function (ws, data) {
var command = data.command;
console.log('匹配',data.content.name);
switch (command)
{
case commands.MATCH_PLAYER:
matchPlayer(ws, data.content.name, data.seq, function (err, seq, players, roomId) {
if(err)
{
console.log('匹配失败');
}else
{
var resp = {command:commands.MATCH_PLAYER, code:0, seq:seq, content:{players:players, roomId:roomId}};
ws.send(JSON.stringify(resp));
}
});
break;
case commands.PLAY_GAME:
case commands.PLAYER_PLAYCARD:
case commands.PLAYER_WANTDIZHU:
playGame(ws, data);
break;
case commands.WS_CLOSE:
/**如果他还在排队就移除排队队列*/
if (queue.indexOf(ws) !== -1)
{
queue.splice(queue.indexOf(ws),1);
}
break;
}
};
var queue = []; //当前匹配队列
var rooms = {}; //所有房间
var roomIndex = 1; //房间编号
function matchPlayer(ws, name, seq, callBack) {
queue.push({ws:ws, name:name, seq:seq, callback:callBack});
console.log('当前玩家数:' + queue.length);
//队列每到3人就分配一个房间
if(queue.length === 3)
{
var names = [queue[0].name, queue[1].name,queue[2].name];
var players = [queue[0], queue[1], queue[2]];
var roomPlayers = [];
for(var i = 0; i < 3; i++)
{
players[i].callback(null, queue[i].seq, names, roomIndex);
roomPlayers.push({ws:players[i].ws, name:players[i].name});
}
var room = new RoomServer();
room.roomId = roomIndex;
roomIndex++;
rooms[room.roomId] = room;
room.players = roomPlayers;
room.initGame();
queue = [];//每匹配到一次玩家就清空一次排队队列
}
}
function playGame(ws, data) {
console.log('收到玩家关于游戏内的消息' + JSON.stringify(data));
var roomId = data.content.roomId;
var index = data.content.index;
var name = data.content.name;
//如果发出的请求和接收的链接不同则不执行
if(name !== ws.name)
{
console.log( name + '玩家发送了不对的信息');
return;
}
var room = rooms[roomId];
if(room)
{
console.log("房间" + roomId + '的' + index + '号位玩家发出请求' + JSON.stringify(data));
room.handlePlayersQuest(index, data);
}
}
/*玩家退出队列,要将其移除*/
function userExit(name) {
for(var i = 0; i < queue.length; i++)
{
if(queue[i].name === name)
{
queue.splice(i,1);
break;
}
}
}
|
39885967fd90660c9780a248acee65965f79a8bd
|
[
"JavaScript"
] | 5
|
JavaScript
|
woshare/qipai_server
|
82b63807292e9791d9b515332afc87549fac6ddb
|
66cf0bf6a56603fa3a48bf1137f93302379bb38c
|
refs/heads/master
|
<repo_name>brad10/brad10<file_sep>/covid19/article.php
<?php
include("php/config.php");
$titrePage = "Article";
include("view/view.php");
?>
|
ab11166502fd58c98c7d920c7e6ba9c50e26a11a
|
[
"PHP"
] | 1
|
PHP
|
brad10/brad10
|
d1b244e3d6ab3be81c057cb996a1a973941ff36b
|
581d9bc0abd8fcc65c69fb3aa98f3c0865cf2507
|
refs/heads/master
|
<repo_name>GanjelaMJ98/learnSQL<file_sep>/modelStreet.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'modelStreet.ui'
#
# Created by: PyQt5 UI code generator 5.11.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(310, 363)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.Table = QtWidgets.QTableWidget(self.centralwidget)
self.Table.setGeometry(QtCore.QRect(20, 40, 271, 221))
self.Table.setRowCount(10)
self.Table.setColumnCount(2)
self.Table.setObjectName("Table")
item = QtWidgets.QTableWidgetItem()
self.Table.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.Table.setHorizontalHeaderItem(1, item)
self.Load_but = QtWidgets.QPushButton(self.centralwidget)
self.Load_but.setGeometry(QtCore.QRect(20, 310, 75, 23))
self.Load_but.setObjectName("Load_but")
self.Delete_but = QtWidgets.QPushButton(self.centralwidget)
self.Delete_but.setGeometry(QtCore.QRect(140, 310, 75, 23))
self.Delete_but.setObjectName("Delete_but")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(130, 10, 111, 21))
self.label.setObjectName("label")
self.Update_but = QtWidgets.QPushButton(self.centralwidget)
self.Update_but.setGeometry(QtCore.QRect(210, 310, 75, 23))
self.Update_but.setObjectName("Update_but")
self.Search_t = QtWidgets.QLineEdit(self.centralwidget)
self.Search_t.setGeometry(QtCore.QRect(20, 280, 191, 20))
self.Search_t.setObjectName("Search_t")
self.Search_but = QtWidgets.QPushButton(self.centralwidget)
self.Search_but.setGeometry(QtCore.QRect(210, 280, 75, 23))
self.Search_but.setObjectName("Search_but")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Street" ))
item = self.Table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "street_id"))
item = self.Table.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Street"))
self.Load_but.setText(_translate("MainWindow", "Load"))
self.Delete_but.setText(_translate("MainWindow", "Delete"))
self.label.setText(_translate("MainWindow", "STREETS"))
self.Update_but.setText(_translate("MainWindow", "Update"))
self.Search_but.setText(_translate("MainWindow", "Search"))
<file_sep>/Street.py
import sys
from PyQt5 import QtWidgets
import modelStreet
import api
import sqlite3
conn = sqlite3.connect('PhoneBookDB.db')
cursor = conn.cursor()
class ExampleName(QtWidgets.QMainWindow, modelStreet.Ui_MainWindow):
currentItemRow = None
currentItemColumn = None
currentItemText = None
deleteIndex = None
searchText = None
updateFlag = 0
newItemText = None
def __init__(self):
super().__init__()
self.setupUi(self)
self.Load_but.clicked.connect(self.loadData)
self.Delete_but.clicked.connect(self.Delete)
self.Search_but.clicked.connect(self.Search)
self.Update_but.clicked.connect(self.Update)
self.Table.clicked.connect(self.onClickTable)
self.Search_t.textChanged.connect(self.onTextSearch)
self.Table.itemChanged.connect(self.cellChangedTable)
def cellChangedTable(self, item):
if self.updateFlag == 1:
self.updateFlag = 0
self.newItemText = item.text()
id = str(self.SearchIndexInTable(item.row()))
api.windowStreetUpdate(self.newItemText,id)
else:
return
def onClickTable(self, item):
self.currentItemRow = item.row()
self.currentItemColumn = item.column()
self.deleteIndex = self.SearchIndexInTable(item.row(), item.column())
self.currentItemText = self.Table.item(item.row(),item.column()).text()
def SearchIndexInTable(self,row,column = None):
index_row = row
index_column = 0
return(self.Table.item(index_row, index_column).text())
def Delete(self):
api.windowStreetDelete(self.deleteIndex)
def Update(self):
self.updateFlag = 1
def loadData(self,name = False):
if name is not False:
sql = api.windowStreetLoadTable(name)
res = conn.execute(sql)
else:
sql = api.windowStreetLoadTable()
res = conn.execute(sql)
self.Table.setRowCount(0)
for row_number, row_data in enumerate(res):
self.Table.insertRow(row_number)
for colum_number , data in enumerate(row_data):
self.Table.setItem(row_number,colum_number,QtWidgets.QTableWidgetItem(str(data)))
def onTextSearch(self, text):
self.searchText = text
def Search(self):
self.loadData(self.searchText)
def main():
app = QtWidgets.QApplication(sys.argv)
Street = ExampleName()
Street.show()
Street.loadData()
app.exec_()
if __name__ == '__main__':
main()<file_sep>/model.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'model.ui'
#
# Created by: PyQt5 UI code generator 5.11.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(937, 725)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.Sur_ok = QtWidgets.QPushButton(self.centralwidget)
self.Sur_ok.setGeometry(QtCore.QRect(260, 80, 61, 31))
self.Sur_ok.setObjectName("Sur_ok")
self.Name_ok = QtWidgets.QPushButton(self.centralwidget)
self.Name_ok.setGeometry(QtCore.QRect(530, 80, 61, 31))
self.Name_ok.setObjectName("Name_ok")
self.Patron_ok = QtWidgets.QPushButton(self.centralwidget)
self.Patron_ok.setGeometry(QtCore.QRect(820, 80, 61, 31))
self.Patron_ok.setObjectName("Patron_ok")
self.Street_ok = QtWidgets.QPushButton(self.centralwidget)
self.Street_ok.setGeometry(QtCore.QRect(260, 160, 61, 31))
self.Street_ok.setObjectName("Street_ok")
self.Surname_l = QtWidgets.QLabel(self.centralwidget)
self.Surname_l.setGeometry(QtCore.QRect(70, 60, 47, 13))
self.Surname_l.setObjectName("Surname_l")
self.Name_l = QtWidgets.QLabel(self.centralwidget)
self.Name_l.setGeometry(QtCore.QRect(340, 60, 47, 13))
self.Name_l.setObjectName("Name_l")
self.Patron_l = QtWidgets.QLabel(self.centralwidget)
self.Patron_l.setGeometry(QtCore.QRect(630, 60, 47, 13))
self.Patron_l.setObjectName("Patron_l")
self.Street_l = QtWidgets.QLabel(self.centralwidget)
self.Street_l.setGeometry(QtCore.QRect(70, 140, 47, 13))
self.Street_l.setObjectName("Street_l")
self.Table = QtWidgets.QTableWidget(self.centralwidget)
self.Table.setGeometry(QtCore.QRect(70, 290, 811, 411))
self.Table.setRowCount(15)
self.Table.setColumnCount(9)
self.Table.setObjectName("Table")
item = QtWidgets.QTableWidgetItem()
self.Table.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.Table.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.Table.setHorizontalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.Table.setHorizontalHeaderItem(3, item)
item = QtWidgets.QTableWidgetItem()
self.Table.setHorizontalHeaderItem(4, item)
item = QtWidgets.QTableWidgetItem()
self.Table.setHorizontalHeaderItem(5, item)
item = QtWidgets.QTableWidgetItem()
self.Table.setHorizontalHeaderItem(6, item)
item = QtWidgets.QTableWidgetItem()
self.Table.setHorizontalHeaderItem(7, item)
item = QtWidgets.QTableWidgetItem()
self.Table.setHorizontalHeaderItem(8, item)
self.Bild_l = QtWidgets.QLabel(self.centralwidget)
self.Bild_l.setGeometry(QtCore.QRect(340, 140, 47, 13))
self.Bild_l.setObjectName("Bild_l")
self.Block_l = QtWidgets.QLabel(self.centralwidget)
self.Block_l.setGeometry(QtCore.QRect(470, 140, 47, 13))
self.Block_l.setObjectName("Block_l")
self.Appr_l = QtWidgets.QLabel(self.centralwidget)
self.Appr_l.setGeometry(QtCore.QRect(580, 140, 47, 13))
self.Appr_l.setObjectName("Appr_l")
self.Number_l = QtWidgets.QLabel(self.centralwidget)
self.Number_l.setGeometry(QtCore.QRect(690, 140, 47, 13))
self.Number_l.setObjectName("Number_l")
self.comboSurname = QtWidgets.QComboBox(self.centralwidget)
self.comboSurname.setGeometry(QtCore.QRect(70, 110, 191, 22))
self.comboSurname.setObjectName("comboSurname")
self.comboName = QtWidgets.QComboBox(self.centralwidget)
self.comboName.setGeometry(QtCore.QRect(340, 110, 191, 22))
self.comboName.setObjectName("comboName")
self.comboPatron = QtWidgets.QComboBox(self.centralwidget)
self.comboPatron.setGeometry(QtCore.QRect(630, 110, 191, 22))
self.comboPatron.setObjectName("comboPatron")
self.comboStreet = QtWidgets.QComboBox(self.centralwidget)
self.comboStreet.setGeometry(QtCore.QRect(70, 190, 191, 22))
self.comboStreet.setObjectName("comboStreet")
self.Surname_t = QtWidgets.QLineEdit(self.centralwidget)
self.Surname_t.setGeometry(QtCore.QRect(70, 80, 191, 31))
self.Surname_t.setObjectName("Surname_t")
self.Name_t = QtWidgets.QLineEdit(self.centralwidget)
self.Name_t.setGeometry(QtCore.QRect(340, 80, 191, 31))
self.Name_t.setObjectName("Name_t")
self.Patron_t = QtWidgets.QLineEdit(self.centralwidget)
self.Patron_t.setGeometry(QtCore.QRect(630, 80, 191, 31))
self.Patron_t.setObjectName("Patron_t")
self.Street_t = QtWidgets.QLineEdit(self.centralwidget)
self.Street_t.setGeometry(QtCore.QRect(70, 160, 191, 31))
self.Street_t.setObjectName("Street_t")
self.Bild_t = QtWidgets.QLineEdit(self.centralwidget)
self.Bild_t.setGeometry(QtCore.QRect(340, 160, 111, 31))
self.Bild_t.setObjectName("Bild_t")
self.Block_t = QtWidgets.QLineEdit(self.centralwidget)
self.Block_t.setGeometry(QtCore.QRect(470, 160, 81, 31))
self.Block_t.setObjectName("Block_t")
self.Appr_t = QtWidgets.QLineEdit(self.centralwidget)
self.Appr_t.setGeometry(QtCore.QRect(580, 160, 61, 31))
self.Appr_t.setObjectName("Appr_t")
self.Number_t = QtWidgets.QLineEdit(self.centralwidget)
self.Number_t.setGeometry(QtCore.QRect(690, 160, 171, 31))
self.Number_t.setObjectName("Number_t")
self.LoadDB_but = QtWidgets.QPushButton(self.centralwidget)
self.LoadDB_but.setGeometry(QtCore.QRect(70, 250, 91, 31))
self.LoadDB_but.setObjectName("LoadDB_but")
self.Search_but = QtWidgets.QPushButton(self.centralwidget)
self.Search_but.setGeometry(QtCore.QRect(250, 250, 151, 31))
self.Search_but.setObjectName("Search_but")
self.Add_but = QtWidgets.QPushButton(self.centralwidget)
self.Add_but.setGeometry(QtCore.QRect(690, 250, 91, 31))
self.Add_but.setObjectName("Add_but")
self.Delete_but = QtWidgets.QPushButton(self.centralwidget)
self.Delete_but.setGeometry(QtCore.QRect(550, 250, 91, 31))
self.Delete_but.setObjectName("Delete_but")
self.Update_but = QtWidgets.QPushButton(self.centralwidget)
self.Update_but.setGeometry(QtCore.QRect(790, 250, 91, 31))
self.Update_but.setObjectName("Update_but")
self.ID_t = QtWidgets.QLineEdit(self.centralwidget)
self.ID_t.setGeometry(QtCore.QRect(510, 250, 31, 31))
self.ID_t.setObjectName("ID_t")
self.id_l = QtWidgets.QLabel(self.centralwidget)
self.id_l.setGeometry(QtCore.QRect(490, 252, 16, 21))
self.id_l.setObjectName("id_l")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "PhoneBook"))
self.Sur_ok.setText(_translate("MainWindow", "OK"))
self.Name_ok.setText(_translate("MainWindow", "OK"))
self.Patron_ok.setText(_translate("MainWindow", "OK"))
self.Street_ok.setText(_translate("MainWindow", "OK"))
self.Surname_l.setText(_translate("MainWindow", "Surname"))
self.Name_l.setText(_translate("MainWindow", "Name"))
self.Patron_l.setText(_translate("MainWindow", "Patron"))
self.Street_l.setText(_translate("MainWindow", "Street"))
item = self.Table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "id"))
item = self.Table.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Surname"))
item = self.Table.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Name"))
item = self.Table.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "Patron"))
item = self.Table.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", "Street"))
item = self.Table.horizontalHeaderItem(5)
item.setText(_translate("MainWindow", "Bild"))
item = self.Table.horizontalHeaderItem(6)
item.setText(_translate("MainWindow", "Block"))
item = self.Table.horizontalHeaderItem(7)
item.setText(_translate("MainWindow", "Appr"))
item = self.Table.horizontalHeaderItem(8)
item.setText(_translate("MainWindow", "Numper"))
self.Bild_l.setText(_translate("MainWindow", "Bild"))
self.Block_l.setText(_translate("MainWindow", "Block"))
self.Appr_l.setText(_translate("MainWindow", "Appr"))
self.Number_l.setText(_translate("MainWindow", "Number"))
self.LoadDB_but.setText(_translate("MainWindow", "Load DB"))
self.Search_but.setText(_translate("MainWindow", "Search"))
self.Add_but.setText(_translate("MainWindow", "ADD"))
self.Delete_but.setText(_translate("MainWindow", "DELETE"))
self.Update_but.setText(_translate("MainWindow", "UPDATE"))
self.id_l.setText(_translate("MainWindow", "ID"))
<file_sep>/CreateDB.py
import sqlite3
conn = sqlite3.connect('PhoneBook.sqlite')
cursor = conn.cursor()
cursor.execute("""CREATE TABLE `name_t` (
`name_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL
) """)
cursor.execute("""CREATE TABLE `surname_t` (
`surname_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`surname` TEXT NOT NULL
) """)
cursor.execute("""CREATE TABLE `patron_t` (
`patron_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`patron` TEXT NOT NULL
)""")
cursor.execute("""CREATE TABLE `street_t` (
`street_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`street` TEXT NOT NULL
)""")
cursor.execute("""CREATE TABLE `main` (
`main_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`surname_id` INTEGER,
`name_id` INTEGER,
`patron_id` INTEGER,
`street_id` INTEGER,
`bild` INTEGER,
`block` INTEGER,
`appr` INTEGER,
`number` TEXT,
FOREIGN KEY(`street_id`) REFERENCES `street_t`(`street_id`),
FOREIGN KEY(`name_id`) REFERENCES `name_t`(`name_id`),
FOREIGN KEY(`surname_id`) REFERENCES `surname_t`(`surname_id`),
FOREIGN KEY(`patron_id`) REFERENCES `patron_t`(`patron_id`)
)""")
conn.close()<file_sep>/api.py
import sqlite3
conn = sqlite3.connect('PhoneBookDB.db')
cursor = conn.cursor()
def addName(name):
n = False
for row in cursor.execute("SELECT * from name_t"):
if row[1] == name:
n = True
if n == False:
cursor.execute("INSERT INTO name_t VALUES (NULL,?) ", [name] )
print("Added name ", name)
return 1
else:
print("Name already exists")
return 0
def addSurname(surname):
n = False
for row in cursor.execute("SELECT * from surname_t"):
if row[1] == surname:
n = True
if n == False:
cursor.execute("INSERT INTO surname_t VALUES (NULL,?) ", [surname] )
print("Added surname ", surname)
return 1
else:
print("Surname already exists")
return 0
def addStreet(street):
n = False
for row in cursor.execute("SELECT * from street_t"):
if row[1] == street:
n = True
if n == False:
cursor.execute("INSERT INTO street_t VALUES (NULL,?) ", [street] )
print("Added street ", street)
return 1
else:
print("Street already exists")
return 0
def addPatron(patron):
n = False
for row in cursor.execute("SELECT * from patron_t"):
if row[1] == patron:
n = True
if n == False:
cursor.execute("INSERT INTO patron_t VALUES (NULL,?) ", [patron])
print("Added patron ", patron)
return 1
else:
print("Patron already exists")
return 0
def addMain(surname = None,name = None, patron = None, street = None, bild = None,block = None,appr = None,number = None):
addSurname(surname)
addName(name)
addPatron(patron)
addStreet(street)
surname_sql = "(SELECT surname_id FROM surname_t WHERE surname = '{0}')".format(surname)
name_sql = "(SELECT name_id FROM name_t WHERE name = '{0}')".format(name)
patron_sql = "(SELECT patron_id FROM patron_t WHERE patron = '{0}')".format(patron)
street_sql = "(SELECT street_id FROM street_t WHERE street = '{0}')".format(street)
if bild == "":
bild = "NULL"
if block == "":
block = "NULL"
if appr == "":
appr = "NULL"
if number == "":
number = "NULL"
sql = "INSERT INTO main VALUES (NULL, {0},{1},{2},{3},{4},{5},{6},{7})".format(surname_sql,name_sql,patron_sql,street_sql,bild,block,appr,number)
#print(sql)
cursor.execute(sql)
conn.commit()
def DeleteByID(id):
sql = "DELETE FROM main WHERE `main_id` = '{}'".format(id)
cursor.execute(sql)
conn.commit()
print("delete id ", id)
def searchMain(surname = None,name = None, patron = None, street = None, bild = None,block = None,appr = None,number = None):
sql = '''SELECT m.main_id,
s.surname,
n.name,
p.patron,
st.street,
m.bild,
m.block,
m.appr,
m.number
FROM surname_t s, name_t n, patron_t p ,street_t st NATURAL JOIN main m '''
if surname is not None and name is not None and patron is not None and street is not None:
sql = sql + "WHERE s.surname = '{0}' and n.name = '{1}' and p.patron = '{2}' and st.street = '{3}'".format(surname,name,patron, street)
#for row in cursor.execute(sql):
#print(row)
return sql
def NEWsearchMain(surname = None,name = None, patron = None, street = None, bild = None,block = None,appr = None,number = None):
sql = """SELECT m.main_id,
s.surname,
n.name,
p.patron,
st.street,
m.bild,
m.block,
m.appr,
m.number
FROM surname_t s, name_t n, patron_t p ,street_t st NATURAL JOIN main m """
sql = sql + "WHERE 1 = 1 "
if surname != "":
sql += "AND s.surname = '{0}' ".format(surname)
if name != "":
sql += "AND n.name = '{0}' ".format(name)
if patron != "":
sql += "AND p.patron = '{0}' ".format(patron)
if street != "":
sql += "AND st.street = '{0}' ".format(street)
if bild != "":
sql += "AND m.bild = '{0}' ".format(bild)
if block != "":
sql += "AND m.block = '{0}' ".format(block)
if appr != "":
sql += "AND m.appr = '{0}' ".format(appr)
if number != "":
sql += "AND m.number = '{0}' ".format(number)
#print(sql)
#for row in cursor.execute(sql):
#print(row)
return sql
def updateMain(NewName,CurrentName, column,main_id):
if CurrentName == "None":
CurrentName = "NULL"
if column == 0:
print("ERROR UPDATE ID")
return
elif column == 1:
#addName(NewName)
#sql = "update main SET surname_id = (select surname_id from surname_t where surname = '{1}' ) where main_id = '{1}'".format(NewName, main_id)
sql = "update surname_t SET surname = '{0}' where surname_id = (select surname_id from surname_t where surname = '{1}')".format(NewName,CurrentName)
elif column == 2:
#addSurname(NewName)
#sql = "update main SET name_id = (select name_id from name_t where name = '{1}' ) where main_id = '{1}'".format(NewName, main_id)
sql = "update name_t SET name = '{0}' where name_id = (select name_id from name_t where name = '{1}')".format(NewName, CurrentName)
elif column == 3:
#addPatron(NewName)
#sql = "update main SET patron_id = (select patron_id from patron_t where patron = '{1}' ) where main_id = '{1}'".format(NewName, main_id)
sql = "update patron_t SET patron = '{0}' where patron_id = (select patron_id from patron_t where patron = '{1}')".format(NewName, CurrentName)
elif column == 4:
#addStreet(NewName)
#sql = "update main SET street_id = (select street_id from street_t where street = '{1}' ) where main_id = '{1}'".format(NewName, main_id)
sql = "update street_t SET street = '{0}' where street_id = (select street_id from street_t where street = '{1}')".format(NewName, CurrentName)
elif column == 5:
sql = "update main SET bild = '{0}' where main_id = '{1}'".format(NewName, main_id)
elif column == 6:
sql = "update main SET block = '{0}' where main_id = '{1}'".format(NewName, main_id)
elif column == 7:
sql = "update main SET appr = '{0}' where main_id = '{1}'".format(NewName, main_id)
elif column == 1:
sql = "update main SET number = '{0}' where main_id = '{1}'".format(NewName, main_id)
cursor.execute(sql)
conn.commit()
print("update {0} >> {1} in index {2}".format(CurrentName,NewName,main_id))
#sql = "update name_t SET name = 'Petro' where name_id = (select name_id from name_t where name = 'Petr')"
def searchOnlySurname():
list = []
sql = """SELECT surname FROM surname_t """
for row in cursor.execute(sql):
list.append(row[0])
#print(list)
return tuple(list)
def searchOnlyName():
list = []
sql = """SELECT name FROM name_t"""
for row in cursor.execute(sql):
list.append(row[0])
#print(list)
return tuple(list)
def searchOnlyPatron():
list = []
sql = """SELECT patron FROM patron_t"""
for row in cursor.execute(sql):
list.append(row[0])
#print(list)
return tuple(list)
def searchOnlyStreet():
list = []
sql = """SELECT street FROM street_t"""
for row in cursor.execute(sql):
list.append(row[0])
#print(list)
return tuple(list)
def searchSurname(surname):
sql = """SELECT m.main_id,
s.surname,
n.name,
p.patron,
st.street,
m.bild,
m.block,
m.appr,
m.number
FROM surname_t s, name_t n, patron_t p ,street_t st NATURAL JOIN main m WHERE s.surname = '{0}'""".format(surname)
#print(sql)
for row in cursor.execute(sql):
print(row)
return sql
def searchName(name):
sql = """SELECT m.main_id,
s.surname,
n.name,
p.patron,
st.street,
m.bild,
m.block,
m.appr,
m.number
FROM surname_t s, name_t n, patron_t p ,street_t st NATURAL JOIN main m WHERE n.name = '{0}'""".format(name)
#print(sql)
for row in cursor.execute(sql):
print(row)
return sql
def searchPatron(patron):
sql = """SELECT m.main_id,
s.surname,
n.name,
p.patron,
st.street,
m.bild,
m.block,
m.appr,
m.number
FROM surname_t s, name_t n, patron_t p ,street_t st NATURAL JOIN main m WHERE p.patron = '{0}'""".format(patron)
#print(sql)
for row in cursor.execute(sql):
print(row)
return sql
def searchStreet(street):
sql = """SELECT m.main_id,
s.surname,
n.name,
p.patron,
st.street,
m.bild,
m.block,
m.appr,
m.number
FROM surname_t s, name_t n, patron_t p ,street_t st NATURAL JOIN main m WHERE st.street = '{0}'""".format(street)
#print(sql)
for row in cursor.execute(sql):
print(row)
return sql
######NAME
def windowNameLoadTable(name = None):
list = []
sql = """SELECT * FROM name_t"""
if name is not None:
sql += " WHERE name = '{0}'".format(str(name))
for row in cursor.execute(sql):
list.append(row[0])
return sql
def windowNameIdInMain(id):
list = []
sql = "select name_id from main"
cursor.execute(sql)
for row in cursor.execute(sql):
list.append(row[0])
if list.count(id) == 0:
return False
else:
return True
def windowNameDelete(id):
sql = "DELETE FROM name_t WHERE `name_id` = '{0}'".format(id)
if windowNameIdInMain(int(id)) == True:
print("FOREIGN KEY constraint failed: {0}".format(sql))
return
else:
cursor.execute(sql)
conn.commit()
print("windowName: delete id ", id)
def windowNameUpdate(NewName,id):
sql = "update name_t set name = '{0}' where name_id = '{1}'".format(NewName,id)
cursor.execute(sql)
conn.commit()
print("windowName: update id {0}: {1}".format(id,NewName))
######SURNAME
def windowSurnameLoadTable(surname = None):
list = []
sql = """SELECT * FROM surname_t"""
if surname is not None:
sql += " WHERE surname = '{0}'".format(str(surname))
for row in cursor.execute(sql):
list.append(row[0])
return sql
def windowSurnameIdInMain(id):
list = []
sql = "select surname_id from main"
cursor.execute(sql)
for row in cursor.execute(sql):
list.append(row[0])
if list.count(id) == 0:
return False
else:
return True
def windowSurnameDelete(id):
sql = "DELETE FROM surname_t WHERE `surname_id` = '{0}'".format(id)
if windowSurnameIdInMain(int(id)) == True:
print("FOREIGN KEY constraint failed: {0}".format(sql))
return
else:
cursor.execute(sql)
conn.commit()
print("windowSurname: delete id ", id)
def windowSurnameUpdate(NewName,id):
sql = "update surname_t set surname = '{0}' where surname_id = '{1}'".format(NewName,id)
cursor.execute(sql)
conn.commit()
print("windowSurname: update id {0}: {1}".format(id,NewName))
######PATRON
def windowPatronLoadTable(patron = None):
list = []
sql = """SELECT * FROM patron_t"""
if patron is not None:
sql += " WHERE patron = '{0}'".format(str(patron))
for row in cursor.execute(sql):
list.append(row[0])
return sql
def windowPatronIdInMain(id):
list = []
sql = "select patron_id from main"
cursor.execute(sql)
for row in cursor.execute(sql):
list.append(row[0])
if list.count(id) == 0:
return False
else:
return True
def windowPatronDelete(id):
sql = "DELETE FROM patron_t WHERE `patron_id` = '{0}'".format(id)
if windowPatronIdInMain(int(id)) == True:
print("FOREIGN KEY constraint failed: {0}".format(sql))
return
else:
cursor.execute(sql)
conn.commit()
print("windowPatron: delete id ", id)
def windowPatronUpdate(NewName,id):
sql = "update patron_t set patron = '{0}' where patron_id = '{1}'".format(NewName,id)
cursor.execute(sql)
conn.commit()
print("windowPatron: update id {0}: {1}".format(id,NewName))
######STREET
def windowStreetLoadTable(street = None):
list = []
sql = """SELECT * FROM street_t"""
if street is not None:
sql += " WHERE street = '{0}'".format(str(street))
for row in cursor.execute(sql):
list.append(row[0])
return sql
def windowStreetIdInMain(id):
list = []
sql = "select street_id from main"
cursor.execute(sql)
for row in cursor.execute(sql):
list.append(row[0])
if list.count(id) == 0:
return False
else:
return True
def windowStreetDelete(id):
sql = "DELETE FROM street_t WHERE `street_id` = '{0}'".format(id)
if windowStreetIdInMain(int(id)) == True:
print("FOREIGN KEY constraint failed: {0}".format(sql))
return
else:
cursor.execute(sql)
conn.commit()
print("windowStreet: delete id ", id)
def windowStreetUpdate(NewName,id):
sql = "update street_t set street = '{0}' where street_id = '{1}'".format(NewName,id)
cursor.execute(sql)
conn.commit()
print("windowStreet: update id {0}: {1}".format(id,NewName))
if __name__ == "__main__":
#updateMain("Sidorenko","Sidoenko",1)
#addSurname("Ganjela")
#addStreet("Dubosekovskaya")
#addPatron("Andreevich")
#addName("Vlad")
#addMain("Zvezdin","Tema","Olegovich","Balashiha",66,6,666,6666666666)
conn.commit()<file_sep>/main.py
import sys
from PyQt5 import QtWidgets
import subprocess
import model #файл дизайна
import api
import sqlite3
conn = sqlite3.connect('PhoneBookDB.db')
cursor = conn.cursor()
#TODO: Убрать глобальные переменные
textID = list()
textSurname = list()
textName = list()
textPatron = list()
textStreet = list()
textBild = list()
textBlock = list()
textAppr = list()
textNumber = list()
currentID = str()
currentSurname = str()
currentName = str()
currentPatron = str()
currentStreet = str()
currentBild = str()
currentBlock = str()
currentAppr = str()
currentNumber = str()
class ExampleApp(QtWidgets.QMainWindow, model.Ui_MainWindow):
currentItemRow = None
currentItemColumn = None
currentItemText = None
newItemText = None
deleteIndex = None
updateFlag = 0
def __init__(self):
# Это здесь нужно для доступа к переменным, методам
# и т.д. в файле model.py
super().__init__()
self.setupUi(self) # Это нужно для инициализации нашего дизайна
self.LoadDB_but.clicked.connect(self.loadData) #обработчик кнопки
self.updateComboBox()
# Основные кнопки
self.Search_but.clicked.connect(self.Search_data)
self.Add_but.clicked.connect(self.Add_data)
self.Update_but.clicked.connect(self.Update)
self.Delete_but.clicked.connect(self.Delete)
# Ввод текста
self.ID_t.textChanged.connect(self.onTextID)
self.Surname_t.textChanged.connect(self.onTextSurname)
self.Name_t.textChanged.connect(self.onTextName)
self.Patron_t.textChanged.connect(self.onTextPatron)
self.Street_t.textChanged.connect(self.onTextStreet)
self.Bild_t.textChanged.connect(self.onTextBild)
self.Block_t.textChanged.connect(self.onTextBlock)
self.Appr_t.textChanged.connect(self.onTextAppr)
self.Number_t.textChanged.connect(self.onTextNumber)
# Запуск диалоговых окон
self.Sur_ok.clicked.connect(self.Surname)
self.Name_ok.clicked.connect(self.Name)
self.Patron_ok.clicked.connect(self.Patron)
self.Street_ok.clicked.connect(self.Street)
# Действия с таблицей
self.Table.clicked.connect(self.onClickTable)
self.Table.itemChanged.connect(self.cellChangedTable)
def Surname(self):
subprocess.run(["python", "Surname.py"])
def Name(self):
subprocess.run(["python", "Name.py"])
def Patron(self):
subprocess.run(["python", "Patron.py"])
def Street(self):
subprocess.run(["python", "Street.py"])
def loadData(self,sql):
sql = api.searchMain()
res = conn.execute(sql)
self.Table.setRowCount(0)
for row_number, row_data in enumerate(res):
self.Table.insertRow(row_number)
for colum_number , data in enumerate(row_data):
self.Table.setItem(row_number,colum_number,QtWidgets.QTableWidgetItem(str(data)))
def Search_data(self):
sql = api.NEWsearchMain(currentSurname,currentName,currentPatron,currentStreet,currentBild,currentBlock,currentAppr,currentNumber)
res = conn.execute(sql)
self.Table.setRowCount(0)
for row_number, row_data in enumerate(res):
self.Table.insertRow(row_number)
for colum_number, data in enumerate(row_data):
self.Table.setItem(row_number, colum_number, QtWidgets.QTableWidgetItem(str(data)))
def Add_data(self):
api.addMain(surname = currentSurname,name = currentName, patron = currentPatron,street = currentStreet, bild =currentBild, block = currentBlock, appr = currentAppr, number = currentNumber)
self.Update_all()
def Delete(self):
api.DeleteByID(self.deleteIndex)
#api.DeleteByID(currentID)
def Update(self):
self.updateFlag = 1
def cellChangedTable(self,item):
if self.updateFlag == 1:
self.updateFlag = 0
self.newItemText = item.text()
api.updateMain(self.newItemText,self.currentItemText,self.currentItemColumn,self.SearchIndexInTable(item.row(),item.column()))
self.Update_all()
else:
return
#_________Обновление выпадающих списков_______
def onClickTable(self, item):
self.currentItemRow = item.row()
self.currentItemColumn = item.column()
self.deleteIndex = self.SearchIndexInTable(item.row(), item.column())
self.currentItemText = self.Table.item(item.row(),item.column()).text()
def SearchIndexInTable(self, row, column):
index_row = row
index_column = 0
return (self.Table.item(index_row, index_column).text())
def Update_all(self):
self.updateComboBox()
def updateComboBox(self):
self.comboSurname.clear()
self.comboName.clear()
self.comboPatron.clear()
self.comboStreet.clear()
surnames = api.searchOnlySurname()
self.comboSurname.addItems(surnames)
self.comboSurname.activated[str].connect(self.TextUpdateSurname)
names = api.searchOnlyName()
self.comboName.addItems(names)
self.comboName.activated[str].connect(self.TextUpdateName)
patrons = api.searchOnlyPatron()
self.comboPatron.addItems(patrons)
self.comboPatron.activated[str].connect(self.TextUpdatePatron)
streets = api.searchOnlyStreet()
self.comboStreet.addItems(streets)
self.comboStreet.activated[str].connect(self.TextUpdateStreet)
def onTextID(self, text):
textID.append(text)
global currentID
currentID = textID[-1]
self.deleteIndex = textID[-1]
def onTextSurname(self, text):
textSurname.append(text)
global currentSurname
currentSurname = textSurname[-1]
def onTextName(self, text):
textName.append(text)
global currentName
currentName = textName[-1]
def onTextPatron(self, text):
textPatron.append(text)
global currentPatron
currentPatron = textPatron[-1]
def onTextStreet(self, text):
textStreet.append(text)
global currentStreet
currentStreet = textStreet[-1]
def onTextBild(self, text):
textBild.append(text)
global currentBild
currentBild = textBild[-1]
def onTextBlock(self, text):
textBlock.append(text)
global currentBlock
currentBlock = textBlock[-1]
def onTextAppr(self, text):
textAppr.append(text)
global currentAppr
currentAppr = textAppr[-1]
def onTextNumber(self, text):
textNumber.append(text)
global currentNumber
currentNumber = textNumber[-1]
def TextUpdateSurname(self, text):
self.Surname_t.setText(text)
def TextUpdateName(self, text):
self.Name_t.setText(text)
def TextUpdatePatron(self, text):
self.Patron_t.setText(text)
def TextUpdateStreet(self, text):
self.Street_t.setText(text)
def main():
app = QtWidgets.QApplication(sys.argv) # Новый экземпляр QApplication
window = ExampleApp() # Создаём объект класса ExampleApp
window.show() # Показываем окно
app.exec_() # и запускаем приложение
if __name__ == '__main__':
main()
|
f806cb20138072df0c6d749c0d7e4b69703b543c
|
[
"Python"
] | 6
|
Python
|
GanjelaMJ98/learnSQL
|
791839feacd89a81115c512489e7af3c613642bf
|
500cf05f8d2d47674b35614ea6f3e004b56b8f72
|
refs/heads/master
|
<repo_name>killerluiz/Simulador_chao_fabrica<file_sep>/mainFinal.c
#include "biblio.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
int main(){
srand(time(NULL));
double Tempo = 0 , menorTempo, tempoTotal, estadia ; // verificador de tempo
int i, pos=0, ver_E;
int verMaq = 0; // verificador para ver se tem maquina para ser liberada.
double vetProdutos[3] = {chegadaPedido(21.5), chegadaPedido(19.1), chegadaPedido(8.0)}; //chegada dos 3 pedidos de tempo random
double tempoSaida[4] = {-1,-1,-1,-1}; // tempo das maquinas finalizar o estagio do rolamento [Torno,Torno,Fresa,Mandril]
int *score = malloc(sizeof(int)*4);
double *rolamentoTempoProcesso = malloc(sizeof(double)*4);
// contador de produtos feitos [conico,cilindrico,aco,titanico]
for(i=0;i<4;i++){
score[i] = 0;
rolamentoTempoProcesso[i] = 0;
}
// tempo total de processamento para cada rolamento [conico,cilindrico,aco,titanio]
machine *processTorno1 = cria_machine(), *processTorno2 = cria_machine(), *processFresa = cria_machine(), *processMandril = cria_machine();
rolamento *rolamentoAux;
Fila *filaTorno = criafila(), *filaFresa = criafila(), *filaMandril = criafila();
printf("O tempo desejado de funcionamento? \n");
scanf("%lf", &tempoTotal);
while (Tempo <= tempoTotal) {
menorTempo = vetProdutos[0];
pos = 0;
verMaq = 0;
//verifica menor tempo para pegar o primeiro pedido
for(i=0; i<3; i++){ //verificando o menor
if(menorTempo > vetProdutos[i]){
menorTempo = vetProdutos[i];
pos = i;
verMaq = 0;
}
}
for (i=0;i<4;i++){ //verificando se alguma maquina vai liberar mais cedo do que criar um novo rolamento
if(tempoSaida[i] != -1){
if(menorTempo > tempoSaida[i]){ // verificando o menor tempo caso seja uma maquina querendo liberar
menorTempo = tempoSaida[i];
pos = i;
verMaq = 1;
}
}
}
// criando rolamentos.
if (verMaq == 0){ // se nenhuma maquina liberou um produto.
if(pos == 0){
rolamentoAux = cria_rolamento_conico(menorTempo);
insere_fila(filaTorno,rolamentoAux); // insere na fila torno 2
vetProdutos[0] = menorTempo + chegadaPedido(21.5);
}
if(pos == 1){
rolamentoAux = cria_rolamento_cilindrico(menorTempo);
insere_fila(filaTorno,rolamentoAux); // insere na fila torno
vetProdutos[1] = menorTempo + chegadaPedido(19.1);
}
if(pos == 2){
ver_E = esferico_verifica(); //verifica qual o esferico
if(ver_E == 0){
rolamentoAux = cria_rolamento_aco(menorTempo);
}
if(ver_E == 1){
rolamentoAux = cria_rolamento_titanico(menorTempo);
}
insere_fila(filaFresa,rolamentoAux);
vetProdutos[2] = menorTempo + chegadaPedido(8.0);
}
}else{ // se tiver maquina para liberar em vez de criar rolamento
if(pos == 0){ // maquina Torno 1 acabou o processamento
processTorno1->tempo = -1;
tempoSaida[0] = -1; // indicador de maquina vazia
rolamentoAux = processTorno1->rolamento; // auxiliar segura o ponteiro do rolamento que estava na maquina
}
if(pos == 1){ // maquina Torno 2 acabou o processamento
processTorno2->tempo = -1;
tempoSaida[1] = -1; // indicador de maquina vazia
rolamentoAux = processTorno2->rolamento; // auxiliar segura o ponteiro do rolamento atual
}
if(pos == 2){ // maquina Fresa acabou o processamento
processFresa->tempo = -1;
tempoSaida[2] = -1; // indicador de maquina vazia
}
if(pos == 3){ // maquina Mandril acabou o processamento
processMandril->tempo = -1;
tempoSaida[3] = -1; // indicador de maquina vazia
}
rolamentoAux->pos = rolamentoAux->pos + 1; // andando para proxima maquina.
if (verifica_prox_maquina(rolamentoAux) == 1){ //se a proxima posição for Torno, joga na fila
insere_fila(filaTorno,rolamentoAux); // insere na fila torno
}else{
if (verifica_prox_maquina(rolamentoAux) == 2){ // se a proxima posição for Fresa, joga na fila
insere_fila(filaFresa,rolamentoAux);
}else{
if (verifica_prox_maquina(rolamentoAux) == 3){ // se a proxima posição for Mandril, joga na fila
insere_fila(filaMandril,rolamentoAux);
}else{ // significa que chegou no fim e o rolamento foi feito.
if(verifica_prox_maquina(rolamentoAux) == 4){ // acho q não precisava pq é oq sobra.
score = rolamento_construido(rolamentoAux->nome,score); // incrementa o placar para marcar qnts foram feitos
rolamentoAux->tempoSaida = menorTempo;
rolamentoTempoProcesso = rolamento_processo(rolamentoAux,rolamentoTempoProcesso); // incrementa o placar com o tempo de processo do rolamento
}
}
}
}
}
if(tempoSaida[0] == -1){ // Se a maquina Torno1 tiver livre.
if(filaTorno->tam != 0){
rolamentoAux = obter_fila(filaTorno);
processTorno1->rolamento = rolamentoAux;
estadia = verifica_estadia(rolamentoAux);
processTorno1->tempo = menorTempo + tempoMaquina(estadia); // tempo maquina vai gerar o tempo de processo
tempoSaida[0] = processTorno1->tempo;
}
}
if(tempoSaida[1] == -1){ // Se a maquina Torno2 tiver livre.
if(filaTorno->tam != 0){
rolamentoAux = obter_fila(filaTorno);
processTorno2->rolamento = rolamentoAux;
estadia = verifica_estadia(rolamentoAux);
processTorno2->tempo = menorTempo + tempoMaquina(estadia); // tempo maquina vai gerar o tempo de processo
tempoSaida[1] = processTorno2->tempo;
}
}
if(tempoSaida[2] == -1){ // Se a maquina Fresa tiver livre.
if(filaFresa->tam != 0){
rolamentoAux = obter_fila(filaFresa);
processFresa->rolamento = rolamentoAux;
estadia = verifica_estadia(rolamentoAux);
processFresa->tempo = menorTempo + tempoMaquina(estadia); // tempo maquina vai gerar o tempo de processo
tempoSaida[2] = processFresa->tempo;
}
}
if(tempoSaida[3] == -1){ // Se a maquina Mandril tiver livre.
if(filaMandril->tam != 0){
rolamentoAux = obter_fila(filaMandril);
processMandril->rolamento = rolamentoAux;
estadia = verifica_estadia(rolamentoAux);
processMandril->tempo = menorTempo + tempoMaquina(estadia); // tempo maquina vai gerar o tempo de processo
tempoSaida[3] = processMandril->tempo;
}
}
Tempo = menorTempo; // tempo RECEBE o tempo que foi usado.
// explicação: O tempo é incrementado na chegada junto com o random da chegada
// mesma coisa para saida do produto (saida definida na entrada da maquina)
}
printf("Quantidade de rolamentos construidos: \n Conico: %d \n Cilindrico: %d \n Aco: %d \n Titanio: %d \n \n ", score[0], score[1], score[2], score[3]);
printf("Tempo total de processamento: \n Conico: %lf \n Cilindrico: %lf \n Aco: %lf \n Titanio: %lf \n \n",rolamentoTempoProcesso[0],rolamentoTempoProcesso[1],rolamentoTempoProcesso[2],rolamentoTempoProcesso[3]);
printf("Tempo medio de cada rolamento: \n Conico: %lf \n Cilindrico: %lf \n Aco: %lf \n Titanio: %lf \n \n", rolamentoTempoProcesso[0]/score[0],rolamentoTempoProcesso[1]/score[1],rolamentoTempoProcesso[2]/score[2],rolamentoTempoProcesso[3]/score[3]);
destruirFila(filaTorno);
destruirFila(filaMandril);
destruirFila(filaFresa);
free(processTorno1);
free(processTorno2);
free(processMandril);
free(processFresa);
return 0;
}<file_sep>/fila.c
#include "biblio.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
no *criaNo(rolamento *p, int prior){
no *N = malloc(sizeof(no));
N->rolamento = p;
N->prox = N->ant = NULL;
N->prior = prior;
return N;
}
Fila *criafila(){
Fila *Fila;
Fila = malloc(sizeof(Fila));
Fila->ini = Fila->fim = NULL;
Fila->tam = 0;
return Fila;
}
rolamento *obter_fila(Fila *Fil){
no *k = Fil->ini;
rolamento *rola = k->rolamento;
Fil->ini = Fil->ini->prox;
Fil->tam--;
return rola;
}
void imprimeFila(Fila *Fila){
int i=0;
no *N = Fila->ini;
//printf("Fila Tamanho: %d \n", Fila->tam);
while (N!=NULL && i< Fila->tam){
printf("Impressora rolamento:%s\n", N->rolamento->nome);
printf("Impressora Tempo:%lf\n", N->rolamento->tempo);
N = N->prox;
i++;
}
}
void insere_fila(Fila *fila, rolamento *rola){
double tempon = rola->tempo;
no *N = criaNo(rola,rola->prioridade);
N->rolamento->tempo = tempon;
if(fila->ini == NULL) { //se nao tiver nenhum na fila
fila->ini = fila->fim = N;
}else{
if(fila->ini->prior < rola->prioridade) { //se tiver maior prioridade
N->prox = fila->ini;
fila->ini = N;
}else{
if(fila->fim->prior >= rola->prioridade) { //se tiver menor prioridade
fila->fim->prox = N;
fila->fim = N;
}else {
no *k = fila->ini; //se tiver com prioridade no meio
while(k->prox->prior >= rola->prioridade) {
k = k->prox;
}
N->prox = k->prox;
k->prox = N;
}
}
}
fila->tam++;
}
void destruirFila(Fila *Fila){
no *k, *N = Fila->ini;
while(N != NULL){
k = N->prox;
free(N);
N = k;
}
Fila->tam = 0;
Fila->ini = Fila->fim = NULL;
}
<file_sep>/funcoes.c
#include "biblio.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
machine *cria_machine(){
machine *maq = malloc(sizeof(machine));
maq->rolamento = NULL;
maq->tempo = 0;
return maq;
}
rolamento *cria_rolamento_conico(double tempo){
rolamento *rolamento = malloc(sizeof(rolamento));
rolamento->nome = "conico"; //ctz q isso vai dar merda. Tem q ser seta
rolamento->pos = 0;
rolamento->tempo = tempo;
rolamento->prioridade = 1;
return rolamento;
}
rolamento *cria_rolamento_cilindrico(double tempo){
rolamento *rolamento = malloc(sizeof(rolamento));
rolamento->nome = "cilindrico" ;
rolamento->pos = 0;
rolamento->tempo = tempo;
rolamento->prioridade = 2;
return rolamento;
}
rolamento *cria_rolamento_aco(double tempo){
rolamento *rolamento = malloc(sizeof(rolamento));
rolamento->nome = "aco" ;
rolamento->pos = 0;
rolamento->tempo = tempo;
rolamento->prioridade = 1;
return rolamento;
}
rolamento *cria_rolamento_titanico(double tempo){
rolamento *rolamento = malloc(sizeof(rolamento));
rolamento->nome = "titanico" ;
rolamento->pos = 0;
rolamento->tempo = tempo;
rolamento->prioridade = 1;
return rolamento;
}
int esferico_verifica(){
int v;
v = (rand()%100);
if(v <= 10){
return 1;
}else{
return 0;
}
}
double chegadaPedido(double param){
double u=0;
do {
u = (double) (rand()%RAND_MAX) / RAND_MAX;
} while ((u==0) || (u==1));
return (double) (-param * log (u));
}
double tempoMaquina(double estadia){
return 2.0 * estadia * rand() / (RAND_MAX + 1.0);
}
int *rolamento_construido(char *nome_rolamento, int *score){ //recebe o placar de produtos feitos e incrementa o que acabou.
int num;
if(strcmp(nome_rolamento,"conico") == 0){
num = score[0];
num++;
score[0]=num;
}
if(strcmp(nome_rolamento,"cilindrico") == 0){
num = score[1];
num++;
score[1]=num;
}
if(strcmp(nome_rolamento,"aco") == 0){
num = score[2];
num++;
score[2]=num;
}
if(strcmp(nome_rolamento,"titanico") == 0){
num = score[3];
num++;
score[3]=num;
}
return score;
}
double *rolamento_processo(rolamento *rola, double *placar){ //recebe o placar de produtos feitos e incrementa o que acabou.
if(strcmp(rola->nome,"conico") == 0){
placar[0] = placar[0] + (rola->tempoSaida - rola->tempo);
}
if(strcmp(rola->nome,"cilindrico") == 0){
placar[1] = placar[1] + (rola->tempoSaida - rola->tempo);
}
if(strcmp(rola->nome,"aco") == 0){
placar[2] = placar[2] + (rola->tempoSaida - rola->tempo);
}
if(strcmp(rola->nome,"titanico") == 0){
placar[3] = placar[3] + (rola->tempoSaida - rola->tempo);
}
return placar;
}
double verifica_estadia(rolamento *rola){
double estadia;
if(strcmp(rola->nome,"conico") == 0){
double vet_conico[4] = {1.8,2.1,1.8,0};
estadia = vet_conico[rola->pos];
}
if(strcmp(rola->nome,"cilindrico") == 0){
double vet_cilin[5] = {0.8,0.5,0.8,1.2,0};
estadia = vet_cilin[rola->pos];
}
if(strcmp(rola->nome,"aco") == 0){
double vet_aco[4] = {0.5,1.4,1.0,0};
estadia = vet_aco[rola->pos];
}
if(strcmp(rola->nome,"titanico") == 0){
double vet_titanico[6] = {0.6,1.5,1.6,0.6,1.6,0};
estadia = vet_titanico[rola->pos];
}
return estadia;
}
int verifica_prox_maquina(rolamento *rola){
int maquina;
// 1 - TORNO
// 2 - FRESA
// 3 - MANDRIL
// 4 - END
if(strcmp(rola->nome,"conico") == 0){
int vet_conico[4] = {1,3,1,4};
maquina = vet_conico[rola->pos];
}
if(strcmp(rola->nome,"cilindrico") == 0){
int vet_cilin[5] = {1,2,1,3,4};
maquina = vet_cilin[rola->pos];
}
if(strcmp(rola->nome,"aco") == 0){
int vet_aco[4] = {2,3,1,4};
maquina = vet_aco[rola->pos];
}
if(strcmp(rola->nome,"titanico") == 0){
int vet_titanico[6] = {2,3,1,2,1,4};
maquina = vet_titanico[rola->pos];
}
return maquina;
}<file_sep>/biblio.h
#ifndef __biblio_h_
#define __biblio_h_
typedef struct rolamento {
char *nome;
int prioridade;
int pos;
double tempo;
double tempoSaida;
} rolamento;
typedef struct no {
struct no *prox, *ant;
rolamento *rolamento;
int prior;
} no;
typedef struct Fila {
no *ini, *fim;
int tam;
}Fila;
typedef struct machine{
rolamento *rolamento;
double tempo;
}machine;
no *criaNo(rolamento *p, int prior);
Fila *criafila();
rolamento *obter_fila(Fila *Fil);
void imprimeFila(Fila *Fila);
void insere_fila(Fila *fila, rolamento *rola);
void destruirFila(Fila *Fila);
machine *cria_machine();
rolamento *cria_rolamento_conico(double tempo);
rolamento *cria_rolamento_cilindrico(double tempo);
rolamento *cria_rolamento_aco(double tempo);
rolamento *cria_rolamento_titanico(double tempo);
double chegadaPedido(double param);
double tempoMaquina(double estadia);
int *rolamento_construido(char *nome_rolamento, int *score);
double *rolamento_processo(rolamento *rola, double *placar);
int esferico_verifica();
double verifica_estadia(rolamento *rola);
int verifica_prox_maquina(rolamento *rola);
#endif<file_sep>/README.md
# Simulador_chao_fabrica
Trabalho de Estrutura de Dados.
para rodar no gcc utilize:
gcc -Wall -pedantic -o main.exe main.c mainFinal.c fila.c funcoes.c biblio.h
o "main.c" serve para apenas mostrar o funcionamento do algoritmo.
<file_sep>/main.c
#include "biblio.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <windows.h>
int main(){
srand(time(NULL));
double Tempo = 0 , menorTempo, tempoTotal, estadia ; // verificador de tempo
int i, pos=0, ver_E;
int verMaq = 0; // verificador para ver se tem maquina para ser liberada.
double vetProdutos[3] = {chegadaPedido(21.5), chegadaPedido(19.1), chegadaPedido(8.0)}; //chegada dos 3 pedidos de tempo random
double tempoSaida[4] = {-1,-1,-1,-1}; // tempo das maquinas finalizar o estagio do rolamento [Torno,Torno,Fresa,Mandril]
int *score = malloc(sizeof(int)*4);
double *rolamentoTempoProcesso = malloc(sizeof(double)*4);
// contador de produtos feitos [conico,cilindrico,aco,titanico]
for(i=0;i<4;i++){
score[i] = 0;
rolamentoTempoProcesso[i] = 0;
}
// tempo total de processamento para cada rolamento [conico,cilindrico,aco,titanio]
machine *processTorno1 = cria_machine(), *processTorno2 = cria_machine(), *processFresa = cria_machine(), *processMandril = cria_machine();
rolamento *rolamentoAux;
Fila *filaTorno = criafila(), *filaFresa = criafila(), *filaMandril = criafila();
printf("O tempo desejado de funcionamento? \n");
scanf("%lf", &tempoTotal);
while (Tempo <= tempoTotal) {
menorTempo = vetProdutos[0];
pos = 0;
verMaq = 0;
//verifica menor tempo para pegar o primeiro pedido
for(i=0; i<3; i++){ //verificando o menor
printf("Tempo em que vai chegar: %lf \n",vetProdutos[i]);
if(menorTempo > vetProdutos[i]){
menorTempo = vetProdutos[i];
pos = i;
verMaq = 0;
}
}
for (i=0;i<4;i++){ //verificando se alguma maquina vai liberar mais cedo do que criar um novo rolamento
printf("Tempo em que vai sair: %lf \n", tempoSaida[i]);
if(tempoSaida[i] != -1){
if(menorTempo > tempoSaida[i]){ // verificando o menor tempo caso seja uma maquina querendo liberar
menorTempo = tempoSaida[i];
pos = i;
verMaq = 1;
}
}
}
printf("Menor Tempo: %lf \n",menorTempo);
// criando rolamentos.
if (verMaq == 0){ // se nenhuma maquina liberou um produto.
printf("Chegou um produto.\n");
printf("pos: %d \n",pos);
printf("[Conico,Cilindrico,Esferico]\n");
if(pos == 0){
rolamentoAux = cria_rolamento_conico(menorTempo);
insere_fila(filaTorno,rolamentoAux); // insere na fila torno 2
vetProdutos[0] = menorTempo + chegadaPedido(21.5);
printf("Criou o rolamento conico e inseriu na fila Torno.\n");
}
if(pos == 1){
rolamentoAux = cria_rolamento_cilindrico(menorTempo);
insere_fila(filaTorno,rolamentoAux); // insere na fila torno
vetProdutos[1] = menorTempo + chegadaPedido(19.1);
printf("Criou o rolamento cilindrico e inseriu na fila Torno.\n");
}
if(pos == 2){
ver_E = esferico_verifica();
if(ver_E == 0){
rolamentoAux = cria_rolamento_aco(menorTempo);
printf("criou esferico de aco.\n");
}
if(ver_E == 1){
rolamentoAux = cria_rolamento_titanico(menorTempo);
printf("criou esferico de titanico.\n");
}
insere_fila(filaFresa,rolamentoAux);
vetProdutos[2] = menorTempo + chegadaPedido(8.0);
}
printf("-----------------------\n");
imprimeFila(filaTorno);
printf("Fila de Torno Impressa.\n");
printf("-----------------------\n");
imprimeFila(filaFresa);
printf("Fila de Fresa Impressa.\n");
printf("-----------------------\n");
imprimeFila(filaMandril);
printf("Fila de Mandril Impressa.\n");
printf ("Placar de saida dos produtos das maquinas.\n");
printf("Tempo de Saida do rolamento do Torno 1: %lf \n",tempoSaida[0]);
printf("Tempo de Saida do rolamento do Torno 2: %lf \n",tempoSaida[1]);
printf("Tempo de Saida do rolamento do Fresa: %lf \n",tempoSaida[2]);
printf("Tempo de Saida do rolamento do Mandril: %lf \n",tempoSaida[3]);
}else{ // se tiver maquina para liberar em vez de criar rolamento
printf("pos: %d \n",pos);
printf("[T1,T2,F,M]\n");
printf("Liberando maquina para proximo estagio.\n");
if(pos == 0){ // maquina Torno 1 acabou o processamento
processTorno1->tempo = -1;
tempoSaida[0] = -1; // indicador de maquina vazia
rolamentoAux = processTorno1->rolamento; // auxiliar segura o ponteiro do rolamento que estava na maquina
printf("Rolamento extraido da maquina Torno 1: %s\n", rolamentoAux->nome);
rolamentoAux->pos = rolamentoAux->pos + 1; // andando para proxima maquina.
printf("andou proxima maquina.\n");
if (verifica_prox_maquina(rolamentoAux) == 1){ //se a proxima posição for Torno, joga na fila
printf("proxima maquina é Torno\n");
insere_fila(filaTorno,rolamentoAux); // insere na fila torno
printf("Entra na fila de torno\n");
}else{
if (verifica_prox_maquina(rolamentoAux) == 2){ // se a proxima posição for Fresa, joga na fila
printf("Proxima maquina é Fresa\n");
insere_fila(filaFresa,rolamentoAux);
printf("Entra na fila de Fresa\n");
}else{
if (verifica_prox_maquina(rolamentoAux) == 3){ // se a proxima posição for Mandril, joga na fila
printf("Proxima maquina é Mandril\n");
insere_fila(filaMandril,rolamentoAux);
printf("Entra na fila de Mandril\n");
}else{ // significa que chegou no fim e o rolamento foi feito.
if(verifica_prox_maquina(rolamentoAux) == 4){ // acho q não precisava pq é oq sobra.
printf("Finalizou o rolamento\n");
score = rolamento_construido(rolamentoAux->nome,score); // incrementa o placar para marcar qnts foram feitos
rolamentoAux->tempoSaida = menorTempo;
rolamentoTempoProcesso = rolamento_processo(rolamentoAux,rolamentoTempoProcesso); // incrementa o placar com o tempo de processo do rolamento
printf("Pontos contabilizados.\n");
//free(rolamentoAux);
}
}
}
}
}
if(pos == 1){ // maquina Torno 2 acabou o processamento
processTorno2->tempo = -1;
tempoSaida[1] = -1; // indicador de maquina vazia
rolamentoAux = processTorno2->rolamento; // auxiliar segura o ponteiro do rolamento atual
printf("Rolamento extraido da maquina Torno 2: %s\n", rolamentoAux->nome);
rolamentoAux->pos = rolamentoAux->pos + 1; // andando para proxima maquina.
printf("andou proxima maquina.\n");
if (verifica_prox_maquina(rolamentoAux) == 1){ //se a proxima posição for Torno, joga na fila
printf("proxima maquina é Torno\n");
insere_fila(filaTorno,rolamentoAux); // insere na fila torno
printf("Entra na fila de torno\n");
}else{
if (verifica_prox_maquina(rolamentoAux) == 2){ // se a proxima posição for Fresa, joga na fila
printf("Proxima maquina é Fresa\n");
insere_fila(filaFresa,rolamentoAux);
printf("Entra na fila de Fresa\n");
}else{
if (verifica_prox_maquina(rolamentoAux) == 3){ // se a proxima posição for Mandril, joga na fila
printf("Proxima maquina é Mandril\n");
insere_fila(filaMandril,rolamentoAux);
printf("Entra na fila de Mandril\n");
}else{ // significa que chegou no fim e o rolamento foi feito.
if(verifica_prox_maquina(rolamentoAux) == 4){ // acho q não precisava pq é oq sobra.
printf("Finalizou o rolamento\n");
score = rolamento_construido(rolamentoAux->nome,score); // incrementa o placar para marcar qnts foram feitos
rolamentoAux->tempoSaida = menorTempo;
rolamentoTempoProcesso = rolamento_processo(rolamentoAux,rolamentoTempoProcesso); // incrementa o placar com o tempo de processo do rolamento
printf("Pontos contabilizados.\n");
//free(rolamentoAux);
}
}
}
}
}
if(pos == 2){ // maquina Fresa acabou o processamento
processFresa->tempo = -1;
tempoSaida[2] = -1; // indicador de maquina vazia
rolamentoAux = processFresa->rolamento; // auxiliar segura o ponteiro do rolamento atual
printf("Rolamento extraido da maquina Fresa: %s\n", rolamentoAux->nome);
rolamentoAux->pos = rolamentoAux->pos + 1; // andando para proxima maquina.
printf("andou proxima maquina.\n");
if (verifica_prox_maquina(rolamentoAux) == 1){ //se a proxima posição for Torno, joga na fila
printf("proxima maquina é Torno\n");
insere_fila(filaTorno,rolamentoAux); // insere na fila torno
printf("Entra na fila de torno\n");
}else{
if (verifica_prox_maquina(rolamentoAux) == 2){ // se a proxima posição for Fresa, joga na fila
printf("Proxima maquina é Fresa\n");
insere_fila(filaFresa,rolamentoAux);
printf("Entra na fila de Fresa\n");
}else{
if (verifica_prox_maquina(rolamentoAux) == 3){ // se a proxima posição for Mandril, joga na fila
printf("Proxima maquina é Mandril\n");
insere_fila(filaMandril,rolamentoAux);
printf("Entra na fila de Mandril\n");
}else{ // significa que chegou no fim e o rolamento foi feito.
if(verifica_prox_maquina(rolamentoAux) == 4){ // acho q não precisava pq é oq sobra.
printf("Finalizou o rolamento\n");
score = rolamento_construido(rolamentoAux->nome,score); // incrementa o placar para marcar qnts foram feitos
rolamentoAux->tempoSaida = menorTempo;
rolamentoTempoProcesso = rolamento_processo(rolamentoAux,rolamentoTempoProcesso); // incrementa o placar com o tempo de processo do rolamento
printf("Pontos contabilizados.\n");
//free(rolamentoAux);
}
}
}
}
}
if(pos == 3){ // maquina Mandril acabou o processamento
processMandril->tempo = -1;
tempoSaida[3] = -1; // indicador de maquina vazia
rolamentoAux = processMandril->rolamento; // auxiliar segura o ponteiro do rolamento atual
printf("Rolamento extraido da maquina Mandril: %s\n", rolamentoAux->nome);
rolamentoAux->pos = rolamentoAux->pos + 1; // andando para proxima maquina.
printf("andou proxima maquina.\n");
if (verifica_prox_maquina(rolamentoAux) == 1){ //se a proxima posição for Torno, joga na fila
printf("proxima maquina é Torno\n");
insere_fila(filaTorno,rolamentoAux); // insere na fila torno
printf("Entra na fila de torno\n");
}else{
if (verifica_prox_maquina(rolamentoAux) == 2){ // se a proxima posição for Fresa, joga na fila
printf("Proxima maquina é Fresa\n");
insere_fila(filaFresa,rolamentoAux);
printf("Entra na fila de Fresa\n");
}else{
if (verifica_prox_maquina(rolamentoAux) == 3){ // se a proxima posição for Mandril, joga na fila
printf("Proxima maquina é Mandril\n");
insere_fila(filaMandril,rolamentoAux);
printf("Entra na fila de Mandril\n");
}else{ // significa que chegou no fim e o rolamento foi feito.
if(verifica_prox_maquina(rolamentoAux) == 4){ // acho q não precisava pq é oq sobra.
printf("Finalizou o rolamento\n");
score = rolamento_construido(rolamentoAux->nome,score); // incrementa o placar para marcar qnts foram feitos
rolamentoAux->tempoSaida = menorTempo;
rolamentoTempoProcesso = rolamento_processo(rolamentoAux,rolamentoTempoProcesso); // incrementa o placar com o tempo de processo do rolamento
printf("Pontos contabilizados.\n");
//free(rolamentoAux);
}
}
}
}
}
}
printf("Imprimindo denovo para verificação das Saidas.\n");
printf("Placar de saida dos produtos das maquinas.\n");
printf("Tempo de Saida do rolamento do Torno 1: %lf \n",tempoSaida[0]);
printf("Tempo de Saida do rolamento do Torno 2: %lf \n",tempoSaida[1]);
printf("Tempo de Saida do rolamento do Fresa: %lf \n",tempoSaida[2]);
printf("Tempo de Saida do rolamento do Mandril: %lf \n",tempoSaida[3]);
if(tempoSaida[0] == -1){ // Se a maquina Torno1 tiver livre.
if(filaTorno->tam != 0){
rolamentoAux = obter_fila(filaTorno);
processTorno1->rolamento = rolamentoAux;
estadia = verifica_estadia(rolamentoAux);
processTorno1->tempo = menorTempo + tempoMaquina(estadia); // tempo maquina vai gerar o tempo de processo
tempoSaida[0] = processTorno1->tempo;
}
}
if(tempoSaida[1] == -1){ // Se a maquina Torno2 tiver livre.
if(filaTorno->tam != 0){
rolamentoAux = obter_fila(filaTorno);
processTorno2->rolamento = rolamentoAux;
estadia = verifica_estadia(rolamentoAux);
processTorno2->tempo = menorTempo + tempoMaquina(estadia); // tempo maquina vai gerar o tempo de processo
tempoSaida[1] = processTorno2->tempo;
}
}
if(tempoSaida[2] == -1){ // Se a maquina Fresa tiver livre.
if(filaFresa->tam != 0){
rolamentoAux = obter_fila(filaFresa);
processFresa->rolamento = rolamentoAux;
estadia = verifica_estadia(rolamentoAux);
processFresa->tempo = menorTempo + tempoMaquina(estadia); // tempo maquina vai gerar o tempo de processo
tempoSaida[2] = processFresa->tempo;
}
}
if(tempoSaida[3] == -1){ // Se a maquina Mandril tiver livre.
if(filaMandril->tam != 0){
rolamentoAux = obter_fila(filaMandril);
processMandril->rolamento = rolamentoAux;
estadia = verifica_estadia(rolamentoAux);
processMandril->tempo = menorTempo + tempoMaquina(estadia); // tempo maquina vai gerar o tempo de processo
tempoSaida[3] = processMandril->tempo;
}
}
Tempo = menorTempo; // tempo RECEBE o tempo que foi usado.
/*printf("Delay de 0,25 sec. \n");
Sleep(250);
printf("End of delay\n");*/
printf("Tempo: %lf ************************************ \n", Tempo);
// explicação: O tempo é incrementado na chegada junto com o random da chegada
// mesma coisa para saida do produto (saida definida na entrada da maquina)
}
printf("Quantidade de rolamentos construidos: \n Conico: %d \n Cilindrico: %d \n Aco: %d \n Titanio: %d \n \n ", score[0], score[1], score[2], score[3]);
printf("Tempo total de processamento: \n Conico: %lf \n Cilindrico: %lf \n Aco: %lf \n Titanio: %lf \n \n",rolamentoTempoProcesso[0],rolamentoTempoProcesso[1],rolamentoTempoProcesso[2],rolamentoTempoProcesso[3]);
printf("Tempo medio de cada rolamento: \n Conico: %lf \n Cilindrico: %lf \n Aco: %lf \n Titanio: %lf \n \n", rolamentoTempoProcesso[0]/score[0],rolamentoTempoProcesso[1]/score[1],rolamentoTempoProcesso[2]/score[2],rolamentoTempoProcesso[3]/score[3]);
destruirFila(filaTorno);
destruirFila(filaMandril);
destruirFila(filaFresa);
free(processTorno1);
free(processTorno2);
free(processMandril);
free(processFresa);
}
/* falta ainda:
> se precisa carregar o tempo de espera na fila e de processamento de cada rolamento nós precisamos de:
atribuir uma variavel no rolamento de tempo de inicio e o tempo final (quando ela finalizar) e pegar a diferença.
>tirar o apagar_rolamento e colocar free no lugar.
>printar os resultados
> a identificar..
FEITOS:
> após pegar um rolamento um novo tempo random deve ser atribuido ao tempo pego
> a tabela oferecida para o tempo de processamento de cada maquina, deveria conter juntamente no rolamento, pois a cada
posição andada para mostrar qual é a proxima maquina, deveria ter um outro vetor mostrando o tempo de processamento da
proxima maquina.
> criar um placar de tempo total de processamento para cada rolamento.
*/
|
ba4544e9d18cd30b83f2e352d31ba073ddadad04
|
[
"Markdown",
"C"
] | 6
|
C
|
killerluiz/Simulador_chao_fabrica
|
a4d0943ea4b51a4209dd03a8b8f99690cf925caf
|
2b64253c355b20a92b79ca004b395e8bce38e731
|
refs/heads/master
|
<repo_name>vishnudk/web_scrapper<file_sep>/webScrapper.py
#https://www.linkedin.com/pulse/how-easy-scraping-data-from-linkedin-profiles-david-craven
import requests as res
import bs4
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
def loginFunction():
driver = webdriver.Chrome('D:\downloads\chromedriver')
driver.get('https://www.linkedin.com')
userName = driver.find_element_by_id('session_key')
userName.send_keys('################')
password = driver.find_element_by_id('session_password')
password.send_keys('#############')
# sleep(0.5)
log_in_button = driver.find_element_by_class_name('sign-in-form__submit-button')
log_in_button.click()
# article = driver.find_elements_by_id('ember755')
article = driver.find_elements_by_class_name('break-words')
article = [i.text for i in article]
for ar in article:
print(ar)
print("===============================")
time.sleep(2000)
def main_function():
# print("Enter the specification")
# query=input()
driver2=webdriver.Chrome('D:\downloads\chromedriver')
driver2.get('https://www.google.com')
search_query = driver2.find_element_by_name('q')
search_query.send_keys('site:linkedin.com/in/ AND "python developer" AND "London"')
search_query.send_keys(Keys.RETURN)
# profileUrls=driver2.find_element_by_tag_name('a')
# profileUrls = driver2.find_elements_by_xpath("//*[@href]")
# profileUrls = driver2.find_elements_by_partial_link_text('')
profileUrls = driver2.find_elements_by_class_name('r')
# profileUrls = [url.text for url in profileUrls]
time.sleep(1)
if __name__ == "__main__":
# main_function()
loginFunction()
|
4fe65cea20c79ddb64d3e0b58cceeea5578400f8
|
[
"Python"
] | 1
|
Python
|
vishnudk/web_scrapper
|
4a8f2bd77949533eab5639cc82c7329d118b3a05
|
16ee856cc25b24493bc87abab2842380830349c7
|
refs/heads/main
|
<file_sep># Test_Submodule
modified readme
<file_sep>const lib = require('./math-library/basic-library');
const result = lib.add(3,88);
console.log(result);
//more examples
const resultSub = lib.sub(3,88);
console.log(resultSub);
|
bf8f57ebf180bbc437ac875cd4a5640a182ec855
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
TeoLj/Test_Submodule
|
d75b2b2505c45175e0e2643a29348e6f5350ee6b
|
66b230dbaa4852d377f7fe18b2ad0e20f57f1690
|
refs/heads/master
|
<file_sep>#!/bin/bash
echo "Ashlesha"
echo "added new code from london"
|
3f1c5b608edabd5abf135efd81fc0a8058e06c32
|
[
"Shell"
] | 1
|
Shell
|
ashlesha26/website1
|
f22bfbafe7fef7f915c2b85de54271b2b5d315ca
|
da8741543394de9b6a1c96395796d83b73377880
|
refs/heads/master
|
<repo_name>gmjdev/gm-tel-input<file_sep>/projects/gm-tel-input/src/lib/gm-tel-input.directive.ts
import { AbstractControl, ValidatorFn } from '@angular/forms';
import * as googlePhoneLib from 'google-libphonenumber';
const phoneUtil = googlePhoneLib.PhoneNumberUtil.getInstance();
const PNF = googlePhoneLib.PhoneNumberFormat;
/** A hero's name can't match the given regular expression */
export function phoneNumberValidatorFn(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
const value = control.value;
if (value) {
const telNumberPattern = /^\+([0-9]+\s)*[0-9]+$/;
if (!telNumberPattern.test(value)) {
return { 'invalidFormat': { value: control.value } };
}
try {
const number = phoneUtil.parseAndKeepRawInput(value.replace(' ', ''));
return phoneUtil.isValidNumber(number) ? null :
{ 'invalidTel': { value: control.value } };
} catch (e) {
return { 'invalidTel': { value: control.value } };
}
}
return null;
};
}
export function formatInputAsInternational( country: string, number: string ): string {
try {
const parseNbr = phoneUtil.parseAndKeepRawInput( number, country.toUpperCase());
return phoneUtil.format(parseNbr, PNF.NATIONAL);
} catch (e) {
return '';
}
}
<file_sep>/projects/gm-tel-input/src/lib/gm-tel-input.component.ts
import { Component, Output, Input, OnInit, EventEmitter } from '@angular/core';
import { CountryCode } from './modal/country-code.modal';
import { Country } from './modal/country.modal';
import { FormControl } from '@angular/forms';
import { map } from 'rxjs/operators';
import {formatInputAsInternational} from './gm-tel-input.directive';
@Component({
selector: 'gm-tel-input',
templateUrl: './gm-tel-input.component.html',
styleUrls: ['./gm-tel-input.component.scss'],
providers: [CountryCode]
})
export class GmTelInputComponent implements OnInit {
@Input() value;
@Output() valueChange: EventEmitter<any> = new EventEmitter<any>();
@Input() id: String = 'contactNbr';
@Input() separateCountry = false;
@Input() formControlSrc: FormControl;
_invalidFormatMsg: string;
_invalidTelMsg: string;
allCountries: Array<Country> = [];
selectedCountry: Country = new Country();
constructor(
private countryCodeData: CountryCode
) { }
get f() {
return this.formControlSrc;
}
get invalidFormatMsg(): string {
return this._invalidFormatMsg;
}
get invalidTelMsg(): string {
return this._invalidTelMsg;
}
@Input('invalidFormatMsg')
set invalidFormatMsg(value: string) {
this._invalidFormatMsg = value;
}
@Input('invalidTelMsg')
set invalidTelMsg(value: string) {
this._invalidTelMsg = value;
}
ngOnInit() {
if (!this.value) {
this.value = {
countryCode: '',
mobileNumber: ''
};
}
this.fetchCountryData();
this.selectedCountry = this.allCountries[0];
this.onChanges();
}
private onChanges(): void {
if (!this.formControlSrc) {
return;
}
this.formControlSrc.valueChanges.subscribe(val =>
this.updateModalValue(val.trim()));
}
private updateModalValue(val: string): void {
this.value.countryCode = this.getDialCodeOnly().trim();
this.value.mobileNumber = this.getMobileNumberOnly(val).trim();
const countryNbr = this.value.countryCode.concat(this.value.mobileNumber);
this.value.formatted = formatInputAsInternational(this.selectedCountry.iso2, countryNbr);
this.valueChange.emit(this.value);
}
private updateFormControlValue(val): void {
this.formControlSrc.setValue(val);
}
private setCountryCode(element): void {
const dialCode = this.getDialCodeOnly();
let contactNbr = this.formControlSrc.value;
if (contactNbr.indexOf(dialCode) !== -1) {
return;
}
const tokens: string[] = contactNbr.split(' ') || [];
if (tokens.length === 2 && tokens[1].length > 0) {
const val = !this.separateCountry ? dialCode.concat(tokens[1]) : contactNbr;
this.updateFormControlValue(val);
return;
}
contactNbr = this.separateCountry ? contactNbr : dialCode;
element.focus();
const currentLength = dialCode.length + 1;
if (element.setSelectionRange) {
element.setSelectionRange(currentLength, currentLength);
} else if (element.createTextRange) {
const range = element.createTextRange();
range.collapse(true);
range.moveEnd('character', currentLength);
range.moveStart('character', currentLength);
range.select();
}
this.updateFormControlValue(contactNbr);
}
public onFocus(evt): void {
this.setCountryCode(evt.currentTarget);
}
public onCountrySelect(country: Country, el): void {
this.selectedCountry = country;
this.setCountryCode(el);
}
public onInputKeyPress(event): void {
const pattern = /[0-9\+\-\ ]/;
const inputChar = String.fromCharCode(event.charCode);
if (!pattern.test(inputChar)) {
event.preventDefault();
}
}
protected fetchCountryData(): void {
this.countryCodeData.allCountries.forEach(c => {
const country = new Country();
country.name = c[0].toString();
country.iso2 = c[1].toString();
country.dialCode = c[2].toString();
country.priority = +c[3] || 0;
country.areaCode = +c[4] || null;
country.flagClass = 'flag-icon-' + country.iso2.toLocaleLowerCase();
country.placeHolder = this.separateCountry ? 'XXXXXXXXXX' : '+' + c[2].toString().concat(' ').concat('XXXXXXXXXX');
this.allCountries.push(country);
});
}
private getMobileNumberOnly(value: string): string {
return value ? value.replace(this.getDialCodeOnly().trim(), '') : '';
}
private getDialCodeOnly(): string {
return this.selectedCountry ? '+' + this.selectedCountry.dialCode + ' ' : '';
}
}
<file_sep>/projects/gm-tel-input-tester/src/app/app.component.ts
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { phoneNumberValidator } from 'gm-tel-input';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'gm-tel-input-tester';
telNumberCtrl: FormControl = new FormControl('', [phoneNumberValidator()]);
telNumber = {};
telNumberCtrl1: FormControl = new FormControl('', [phoneNumberValidator()]);
telNumber1 = {};
}
<file_sep>/projects/gm-tel-input/src/lib/gm-tel-input.module.ts
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import { GmTelInputComponent } from './gm-tel-input.component';
@NgModule({
declarations: [
GmTelInputComponent
],
imports: [
CommonModule,
ReactiveFormsModule
],
exports: [
GmTelInputComponent
],
providers: [],
})
export class GmTelInputModule {
static forRoot(): ModuleWithProviders<GmTelInputModule> {
return {
ngModule: GmTelInputModule,
providers: [],
};
}
}
<file_sep>/Changelog.md
## Changelog
### [1.0.4] - 2020-11-29
- Added Support for rendering Country Code and Mobile number input as separate fields<file_sep>/projects/gm-tel-input/src/lib/gm-tel-input.validator.ts
import { AbstractControl, ValidatorFn } from '@angular/forms';
import * as googlePhoneLib from 'google-libphonenumber';
const phoneUtil = googlePhoneLib.PhoneNumberUtil.getInstance();
export function phoneNumberValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
const value = control.value;
if (value) {
const telNumberPattern = /^[\+]{0,1}([0-9]+\s)*[0-9]+/g;
if (!telNumberPattern.test(value)) {
return { 'invalidFormat': { value: control.value } };
}
try {
const number = phoneUtil.parseAndKeepRawInput(value.replace(' ', ''));
return phoneUtil.isValidNumber(number) ? null :
{ 'invalidTel': { value: control.value } };
} catch (e) {
return { 'invalidTel': { value: control.value } };
}
}
return null;
};
}
<file_sep>/README.md
# gm-tel-input
An Angular based module providing support for international mobile number input along with validation support using [google-libphonenumber](https://www.npmjs.com/package/google-libphonenumber). Component styling is based on [Bootstrap](https://github.com/twbs/bootstrap).


## Installation
#### Install the package via `npm`:
```sh
npm install --save gm-tel-input
```
Install library dependencies
```sh
npm install --save jquery
npm install --save bootstrap
npm install --save flag-icon-css
npm install --save google-libphonenumber
```
## Usage
Add and import ```GmTelInputModule``` module into application
```javascript
import { GmTelInputModule } from 'gm-tel-input';
imports: [
GmTelInputModule.forRoot()
]
```
Add following code snippet required to render element in your HTML file
```html
<gm-tel-input [value]="telNumber" [invalidFormatMsg]="'Invalid Contact number format'"
[invalidTelMsg]="'Invalid Contact number'" [formControlSrc]="telNumberCtrl" [id]="contactNbr">
</gm-tel-input>
```
Initialized Form Control and value to be used by component
```javascript
telNumberCtrl: FormControl = new FormControl('', []);
telNumber = {};
```
If you are interested to have basic phone number validation based on [google-libphonenumber](https://www.npmjs.com/package/google-libphonenumber), kindly import `phoneNumberValidator` from `gm-tel-input` library and update ```FormControl``` initialization definition as below :
```javascript
telNumberCtrl: FormControl = new FormControl('', [phoneNumberValidator()]);
```
Add following CSS and Script files to your **`angular.json`** file
```json
"styles": [
"node_modules/flag-icon-css/css/flag-icon.min.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.bundle.js"
]
```
## Options
| Options | Type | Default | Description |
| ---------------- | ----------------- | -------------------------------------------- | ---------------------------------------------------------- |
| value | ```object``` | {<br>countryCode:'',<br>mobileNumber:''<br>formatted:'' <br>} | Object containing selected country code and mobile number. |
| invalidFormatMsg | ```string``` | ```''``` | Validation error message for invalid input format. |
| invalidTelMsg | ```string``` | ```''``` | Validation error message for incorrect input number. |
| formControlSrc | ```FormControl``` | | Instance of ```FormControl``` to be used |
| id | ```string``` | contactNbr | Id to be used in native HTML input element |
| separateCountry | ```boolean``` | false | Flag which renders country coomponent as separate component|
## Tests
Coming up
## Changelog
Below are few latest change logs.
### [1.0.4] - 2020-11-29
- Added Support for rendering Country Code and Mobile number input as separate fields
## Acknowledgments / Attributions
- Country & Flag images from [flag-icon-css](https://github.com/lipis/flag-icon-css)
- Contact Number validation from [google-libphonenumber](https://www.npmjs.com/package/google-libphonenumber)
- Theme and Styling with help of [Bootstrap](https://github.com/twbs/bootstrap)
## Support
If you like this library consider to add star on [GitHub Repository](https://github.com/gmjdev/gm-tel-input).
Thank you!
## Licenses
Copyright 2019 <EMAIL>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.<file_sep>/projects/gm-tel-input/src/public_api.ts
export * from './lib/gm-tel-input.component';
export * from './lib/gm-tel-input.validator';
export * from './lib/gm-tel-input.module';
<file_sep>/projects/gm-tel-input/src/lib/modal/country.modal.ts
export class Country {
name: string;
iso2: string;
dialCode: string;
priority: number;
areaCode: number;
flagClass: string;
placeHolder: string;
constructor() {
this.name = '';
this.iso2 = '';
this.dialCode = '';
this.priority = 0;
this.areaCode = null;
this.flagClass = '';
this.placeHolder = '';
}
}
|
717388fafdc6fce5bc858de549d2ba4901968278
|
[
"Markdown",
"TypeScript"
] | 9
|
TypeScript
|
gmjdev/gm-tel-input
|
7fb2607e957fc16144cb9e64524eb3d4e4250c1b
|
a1edd4bb5cef6f3055c4fbd0313d96b7ce201d50
|
refs/heads/master
|
<file_sep>import { Component } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';
/**
* App Component
*
* @export
* @class AppComponent
*/
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
/**
* Array for spinner size
*
* @type {Array<string>}
* @memberof AppComponent
*/
sizeArray: Array<string> = ['small', 'default', 'medium', 'large'];
/**
* Loading Text for spinner
*
* @type {string}
* @memberof AppComponent
*/
loadingText = 'Loading...';
/**
* Spinner configuration
*
* @type {object}
* @memberof AppComponent
*/
spinnerConfig: object = {
bdColor: 'rgba(0, 0, 0, 1)',
size: 'medium',
color: '#fff',
type: 'ball-8bits',
fullScreen: true,
template: '<img src="https://media.giphy.com/media/o8igknyuKs6aY/giphy.gif" />',
};
/**
* Array of loaders
*
* @type {Array<string>}
* @memberof AppComponent
*/
loaders: Array<string> = [
'ball-8bits',
'ball-atom',
'ball-beat',
'ball-circus',
'ball-climbing-dot',
'ball-clip-rotate',
'ball-clip-rotate-multiple',
'ball-clip-rotate-pulse',
'ball-elastic-dots',
'ball-fall',
'ball-fussion',
'ball-grid-beat',
'ball-grid-pulse',
'ball-newton-cradle',
'ball-pulse',
'ball-pulse-rise',
'ball-pulse-sync',
'ball-rotate',
'ball-running-dots',
'ball-scale',
'ball-scale-multiple',
'ball-scale-pulse',
'ball-scale-ripple',
'ball-scale-ripple-multiple',
'ball-spin',
'ball-spin-clockwise',
'ball-spin-clockwise-fade',
'ball-spin-clockwise-fade-rotating',
'ball-spin-fade',
'ball-spin-fade-rotating',
'ball-spin-rotate',
'ball-square-clockwise-spin',
'ball-square-spin',
'ball-triangle-path',
'ball-zig-zag',
'ball-zig-zag-deflect',
'cube-transition',
'fire',
'line-scale',
'line-scale-party',
'line-scale-pulse-out',
'line-scale-pulse-out-rapid',
'line-spin-clockwise-fade',
'line-spin-clockwise-fade-rotating',
'line-spin-fade',
'line-spin-fade-rotating',
'pacman',
'square-jelly-box',
'square-loader',
'square-spin',
'timer',
'triangle-skew-spin'
];
/**
* Creates an instance of AppComponent.
* @param {NgxSpinnerService} spinner Spinner service
* @memberof AppComponent
*/
constructor(private spinner: NgxSpinnerService) { }
/**
* To show/hide spinner
*
* @memberof AppComponent
*/
showSpinner(name: string) {
this.spinner.show(name);
this.spinner.hide(name, 3000);
}
}
|
68438066dc329eb8be2450ba24bbff3c7ec73f59
|
[
"TypeScript"
] | 1
|
TypeScript
|
shakibuz-zaman/ngx-spinner
|
344e6b074f5a3eb2841aed976a7a48d4f7a8fb5d
|
6e0e7144afe30b8b13af14e264bf0eba1a320e78
|
refs/heads/master
|
<file_sep>package my.spitterP.mainP;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import my.spitterP.mainP.Spitter;
//@Table(name = "spittle")
@Entity
public class Spittle {
private Long id;
private Spitter spitter;
private String text;
private Date when;
public Spittle() {
this.spitter = new Spitter(); // HARD-CODED FOR NOW
this.spitter.setId((long)1);
}
@Id
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getSpittleText() {
return this.text;
}
public void setSpittleText(String text) {
this.text = text;
}
public Date getPostedTime() {
return this.when;
}
public void setPostedTime(Date when) {
this.when = when;
}
@ManyToOne
@JoinColumn(name = "SPITTER_ID")
public Spitter getSpitter_id() {
return this.spitter;
}
public void setSpitter_id(Spitter spitter) {
this.spitter = spitter;
}
}
|
60eff893f5e7d0dab230b61e31a8864679e2bcbb
|
[
"Java"
] | 1
|
Java
|
tomekl007/springHibernateProject
|
ec5bd32a7c72390ece238b3da41f95373d0e4b93
|
6cdfcb7b7fe654be39525ce8c4645d56ddd0a7ae
|
refs/heads/master
|
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jul 15, 2019 at 09:00 AM
-- Server version: 10.3.16-MariaDB
-- PHP Version: 7.3.6
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `cr10_amber_cameron_biglibrary`
--
-- --------------------------------------------------------
--
-- Table structure for table `artist`
--
CREATE TABLE `artist` (
`artist_id` smallint(6) NOT NULL,
`artist_name` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `artist`
--
INSERT INTO `artist` (`artist_id`, `artist_name`) VALUES
(0, '<NAME>'),
(1, '<NAME>'),
(2, 'Black Keys');
-- --------------------------------------------------------
--
-- Table structure for table `author`
--
CREATE TABLE `author` (
`author_id` smallint(6) NOT NULL,
`author_name` varchar(20) NOT NULL,
`author_surname` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `author`
--
INSERT INTO `author` (`author_id`, `author_name`, `author_surname`) VALUES
(1, 'David', 'Nicholls'),
(2, 'Liane', 'Moriarty'),
(3, 'Heather', 'Morris'),
(4, '<NAME>', 'Martin'),
(5, 'John', 'Grisham');
-- --------------------------------------------------------
--
-- Table structure for table `book`
--
CREATE TABLE `book` (
`book_id` smallint(6) NOT NULL,
`title` varchar(100) NOT NULL,
`img` varchar(200) NOT NULL,
`author_id` smallint(6) NOT NULL,
`ISBN` bigint(13) NOT NULL,
`description` varchar(500) NOT NULL,
`publish_date` date NOT NULL,
`publisher_id` smallint(6) NOT NULL,
`status` smallint(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `book`
--
INSERT INTO `book` (`book_id`, `title`, `img`, `author_id`, `ISBN`, `description`, `publish_date`, `publisher_id`, `status`) VALUES
(2, 'Nine Perfect Strangers', 'https://assets.whsmith.co.uk/product-image/extra-large/9781405919463-10-000_1.jpg', 2, 9781405919463, 'The number one Sunday Times bestseller from the author of Big Little Lies', '2019-03-07', 1, 0),
(3, 'The Tattooist of Auschwitz', 'https://assets.whsmith.co.uk/product-image/extra-large/9781785763670-10-000_1.jpg', 3, 9781785763670, 'The heart breaking and unforgettable international bestseller', '2018-10-04', 2, 0),
(17, 'The Reckoning', 'https://assets.whsmith.co.uk/product-image/extra-large/9781473684423-10-000_1.jpg', 5, 9781444715408, 'The electrifying new novel from bestseller <NAME>', '2019-07-11', 4, 0),
(21, 'A Game of Thrones', 'https://images-na.ssl-images-amazon.com/images/I/91dSMhdIzTL.jpg', 4, 9780553588484, 'The first book in the Game of Thrones series', '1996-08-01', 3, 0),
(22, 'A Clash of Kings', 'https://images-na.ssl-images-amazon.com/images/I/91Nl6NuijHL.jpg', 4, 9780553579901, 'The Second Novel in A Song of Ice and Fire', '1999-11-16', 3, 0);
-- --------------------------------------------------------
--
-- Table structure for table `cd`
--
CREATE TABLE `cd` (
`cd_id` smallint(6) NOT NULL,
`title` varchar(100) NOT NULL,
`img` varchar(100) NOT NULL,
`artist_id` smallint(6) NOT NULL,
`ISRC` varchar(12) NOT NULL,
`description` varchar(500) NOT NULL,
`release_date` date NOT NULL,
`studio_id` smallint(6) NOT NULL,
`status` smallint(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `cd`
--
INSERT INTO `cd` (`cd_id`, `title`, `img`, `artist_id`, `ISRC`, `description`, `release_date`, `studio_id`, `status`) VALUES
(1, 'Divinely Uninspired To A Hellish Extent', 'https://ichef.bbci.co.uk/images/ic/320xn/p07b7bsq.jpg', 1, 'B07NPSN19M', 'Divinely Uninspired To A Hellish Extent', '2019-06-14', 1, 0),
(2, 'Lets Rock', 'https://ichef.bbci.co.uk/images/ic/320xn/p07g3xj6.jpg', 2, 'B07R4WPYS5', 'The ninth studio album by American rock duo the Black Keys.', '2019-06-28', 2, 0),
(4, 'Step Back In Time - The Definitive', 'https://ichef.bbci.co.uk/images/ic/320xn/p07g3xbv.jpg', 0, 'B07R44LR62', 'The Career album contains 41 of your biggest hits plus bonus track New York City', '2019-06-28', 0, 1);
-- --------------------------------------------------------
--
-- Table structure for table `director`
--
CREATE TABLE `director` (
`director_id` smallint(6) NOT NULL,
`director_name` varchar(20) NOT NULL,
`director_surname` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `director`
--
INSERT INTO `director` (`director_id`, `director_name`, `director_surname`) VALUES
(1, 'Frank', 'Darabont'),
(2, '<NAME>', 'Coppola'),
(3, 'Christopher', 'Nolan');
-- --------------------------------------------------------
--
-- Table structure for table `dvd`
--
CREATE TABLE `dvd` (
`dvd_id` smallint(6) NOT NULL,
`dvd_title` varchar(100) NOT NULL,
`img` varchar(200) NOT NULL,
`director_id` smallint(6) NOT NULL,
`ASIN` varchar(10) NOT NULL,
`description` varchar(500) NOT NULL,
`release_date` date NOT NULL,
`production_id` smallint(6) NOT NULL,
`status` smallint(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `dvd`
--
INSERT INTO `dvd` (`dvd_id`, `dvd_title`, `img`, `director_id`, `ASIN`, `description`, `release_date`, `production_id`, `status`) VALUES
(1, 'The Shawshank Redemption', 'https://m.media-amazon.com/images/M/MV5BMDFkYTc0MGEtZmNhMC00ZDIzLWFmNTEtODM1ZmRlYWMwMWFmXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_.jpg', 1, 'B07R8BPB6V', 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', '1994-01-01', 1, 0),
(2, 'The Godfather', 'https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_UY268_CR3', 2, 'B001CFAXOA', 'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.', '1972-01-01', 2, 0),
(3, 'The Dark Knight', 'https://m.media-amazon.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_UX182_CR0,0,182,268_AL_.jpg', 3, 'B001G73S50', 'When the menace known as The Joker emerges from his mysterious past, he wreaks havoc and chaos on the people of Gotham.', '2008-01-01', 3, 0);
-- --------------------------------------------------------
--
-- Table structure for table `production_studio`
--
CREATE TABLE `production_studio` (
`production_id` smallint(6) NOT NULL,
`production_name` varchar(50) NOT NULL,
`production_address` varchar(100) NOT NULL,
`production_size` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `production_studio`
--
INSERT INTO `production_studio` (`production_id`, `production_name`, `production_address`, `production_size`) VALUES
(1, 'Castle Rock Entertainment', 'New York City', 'Small'),
(2, 'Paramount Pictures', 'Hollywood', 'Large'),
(3, '<NAME>', 'Burbank', 'Large');
-- --------------------------------------------------------
--
-- Table structure for table `publisher`
--
CREATE TABLE `publisher` (
`publisher_id` smallint(6) NOT NULL,
`publisher_name` varchar(50) NOT NULL,
`publisher_address` varchar(100) NOT NULL,
`publisher_size` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `publisher`
--
INSERT INTO `publisher` (`publisher_id`, `publisher_name`, `publisher_address`, `publisher_size`) VALUES
(1, 'Penguin', 'City of Westminster', 'Large'),
(2, 'Zaffre', 'Wimpole Street', 'Small'),
(3, 'Bantam Books', 'New Tork City', 'Medium'),
(4, 'Hodder & Stoughton', 'London', 'Large');
-- --------------------------------------------------------
--
-- Table structure for table `record_studio`
--
CREATE TABLE `record_studio` (
`record_studio_id` smallint(6) NOT NULL,
`studio_name` varchar(50) NOT NULL,
`studio_address` varchar(100) NOT NULL,
`studio_size` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `record_studio`
--
INSERT INTO `record_studio` (`record_studio_id`, `studio_name`, `studio_address`, `studio_size`) VALUES
(0, 'Various', 'Various', 'Large'),
(1, 'Vertigo', 'Berlin', 'Medium'),
(2, 'Easy Eye Sound', 'Nashville Tennessee', 'Small');
-- --------------------------------------------------------
--
-- Table structure for table `status`
--
CREATE TABLE `status` (
`status_id` smallint(1) NOT NULL,
`status` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `status`
--
INSERT INTO `status` (`status_id`, `status`) VALUES
(0, 'Available'),
(1, 'Reserved');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `artist`
--
ALTER TABLE `artist`
ADD PRIMARY KEY (`artist_id`);
--
-- Indexes for table `author`
--
ALTER TABLE `author`
ADD PRIMARY KEY (`author_id`);
--
-- Indexes for table `book`
--
ALTER TABLE `book`
ADD PRIMARY KEY (`book_id`),
ADD KEY `author_id` (`author_id`,`publisher_id`),
ADD KEY `publisher_id` (`publisher_id`),
ADD KEY `status` (`status`);
--
-- Indexes for table `cd`
--
ALTER TABLE `cd`
ADD PRIMARY KEY (`cd_id`),
ADD KEY `studio_id` (`studio_id`),
ADD KEY `artist_id` (`artist_id`),
ADD KEY `status` (`status`);
--
-- Indexes for table `director`
--
ALTER TABLE `director`
ADD PRIMARY KEY (`director_id`);
--
-- Indexes for table `dvd`
--
ALTER TABLE `dvd`
ADD PRIMARY KEY (`dvd_id`),
ADD KEY `director_id` (`director_id`),
ADD KEY `production_id` (`production_id`),
ADD KEY `status` (`status`);
--
-- Indexes for table `production_studio`
--
ALTER TABLE `production_studio`
ADD PRIMARY KEY (`production_id`);
--
-- Indexes for table `publisher`
--
ALTER TABLE `publisher`
ADD PRIMARY KEY (`publisher_id`);
--
-- Indexes for table `record_studio`
--
ALTER TABLE `record_studio`
ADD PRIMARY KEY (`record_studio_id`);
--
-- Indexes for table `status`
--
ALTER TABLE `status`
ADD PRIMARY KEY (`status_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `author`
--
ALTER TABLE `author`
MODIFY `author_id` smallint(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `book`
--
ALTER TABLE `book`
MODIFY `book_id` smallint(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=39;
--
-- AUTO_INCREMENT for table `cd`
--
ALTER TABLE `cd`
MODIFY `cd_id` smallint(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `dvd`
--
ALTER TABLE `dvd`
MODIFY `dvd_id` smallint(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `publisher`
--
ALTER TABLE `publisher`
MODIFY `publisher_id` smallint(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `book`
--
ALTER TABLE `book`
ADD CONSTRAINT `book_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `author` (`author_id`),
ADD CONSTRAINT `book_ibfk_2` FOREIGN KEY (`publisher_id`) REFERENCES `publisher` (`publisher_id`),
ADD CONSTRAINT `book_ibfk_3` FOREIGN KEY (`status`) REFERENCES `status` (`status_id`);
--
-- Constraints for table `cd`
--
ALTER TABLE `cd`
ADD CONSTRAINT `cd_ibfk_1` FOREIGN KEY (`status`) REFERENCES `status` (`status_id`),
ADD CONSTRAINT `cd_ibfk_2` FOREIGN KEY (`artist_id`) REFERENCES `artist` (`artist_id`),
ADD CONSTRAINT `cd_ibfk_3` FOREIGN KEY (`studio_id`) REFERENCES `record_studio` (`record_studio_id`);
--
-- Constraints for table `dvd`
--
ALTER TABLE `dvd`
ADD CONSTRAINT `dvd_ibfk_1` FOREIGN KEY (`status`) REFERENCES `status` (`status_id`),
ADD CONSTRAINT `dvd_ibfk_2` FOREIGN KEY (`production_id`) REFERENCES `production_studio` (`production_id`),
ADD CONSTRAINT `dvd_ibfk_3` FOREIGN KEY (`director_id`) REFERENCES `director` (`director_id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
require_once 'db_connect.php';
?>
<!DOCTYPE html>
<html>
<head>
<title >Update Book Book</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<?php
if ($_POST) {
$dvd_title = $_POST['dvd_title'];
$img = $_POST['img'];
$director_id = $_POST[ 'director_id'];
$ASIN = $_POST[ 'ASIN'];
$description = $_POST['description'];
$release_date = $_POST['release_date'];
$production_id = $_POST['production_id'];
$status = $_POST['status'];
$id = $_POST['id'];
$sql = "UPDATE dvd SET dvd_title = '$dvd_title', img = '$img', director_id = '$director_id', ASIN = '$ASIN', description = '$description', release_date = '$release_date', production_id = '$production_id', status = '$status' WHERE dvd_id = '$id'" ;
if($connect->query($sql) === TRUE) {
echo "<p>Successfully Updated</p>";
echo "<a href='../dvd_update.php?book_id=" .$id."'><button type='button' class='btn btn-success'>Back</button></a>";
echo "<a href='../index.php'><button type='button' class='btn btn-success'>Home</button></a>";
} else {
echo "Error while updating record : ". $connect->error;
}
$connect->close();
}
?>
</body>
</html><file_sep><?php require_once 'actions/db_connect.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>Code Review 10</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<br>
<div>
<div class="container">
<div class="row">
<div class="col">
<h2>Books</h2>
</div>
<div class="col">
<a href= "create.php"><button type="button" class="btn btn-success" >Add Book</button></a>
</div>
</div>
</div>
<table class="table table-striped table-success">
<thead>
<tr>
<th scope="col">Title</th>
<th scope="col">Author</th>
<th scope="col">Availability</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT book_id, title, author_name, author_surname, status.status from book\n". "INNER JOIN author ON author.author_id = book.author_id\n". "INNER JOIN status ON status.status_id = book.status";
$result = $connect->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" .$row['title']."</td>
<td>" .$row['author_name']." " .$row['author_surname']."</td>
<td>" .$row['status']."
<td>
<a href='list.php?book_id=" .$row['book_id']."'><button type='button' class='btn btn-success' >Show Media</button></a>
<a href='update.php?book_id=" .$row['book_id']."'><button type='button' class='btn btn-success'>Edit</button></a>
<a href='delete.php?book_id=" .$row['book_id']."'><button type='button' class='btn btn-success'>Delete</button></a>
</td>
</tr>" ;
}
} else {
echo "<tr><td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
?>
</tbody>
</table>
</div>
<br>
<div>
<div class="container">
<div class="row">
<div class="col">
<h2>CDs</h2>
</div>
<div class="col">
<a href= "cd_create.php"><button type="button" class="btn btn-success">Add CD</button></a>
</div>
</div>
</div>
<table class="table table-striped table-success">
<thead>
<tr>
<th>Title</th>
<th>Artist</th>
<th>Availability</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT cd_id, title, artist_name, status.status from cd INNER JOIN artist ON artist.artist_id = cd.artist_id INNER JOIN status ON status.status_id = cd.status";
$result = $connect->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" .$row['title']."</td>
<td>" .$row['artist_name']."</td>
<td>" .$row['status']."
<td>
<a href='cd_list.php?cd_id=" .$row['cd_id']."'><button type='button' class='btn btn-success'>Show Media</button></a>
<a href='cd_update.php?cd_id=" .$row['cd_id']."'><button type='button' class='btn btn-success'>Edit</button></a>
<a href='cd_delete.php?cd_id=" .$row['cd_id']."'><button type='button' class='btn btn-success'>Delete</button></a>
</td>
</tr>" ;
}
} else {
echo "<tr><td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
?>
</tbody>
</table>
</div>
<br>
<div>
<div class="container">
<div class="row">
<div class="col">
<h2>DVDs</h2>
</div>
<div class="col">
<a href= "dvd_create.php"><button type="button" class="btn btn-success" >Add DVD</button></a>
</div>
</div>
</div>
<table class="table table-striped table-success">
<thead>
<tr>
<th>Title</th>
<th>Director</th>
<th>Availability</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT dvd_id, dvd_title, director_name, director_surname, status.status from dvd INNER JOIN director ON director.director_id = dvd.director_id INNER JOIN status ON status.status_id = dvd.status";
$result = $connect->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" .$row['dvd_title']."</td>
<td>" .$row['director_name']. " " .$row['director_surname']."</td>
<td>" .$row['status']."
<td>
<a href='dvd_list.php?dvd_id=" .$row['dvd_id']."'><button type='button' class='btn btn-success'>Show Media</button></a>
<a href='dvd_update.php?dvd_id=" .$row['dvd_id']."'><button type='button' class='btn btn-success'>Edit</button></a>
<a href='dvd_delete.php?dvd_id=" .$row['dvd_id']."'><button type='button' class='btn btn-success'>Delete</button></a>
</td>
</tr>" ;
}
} else {
echo "<tr><td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
?>
</tbody>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep><?php
require_once 'db_connect.php';
?>
<html>
<head>
<title>Code Review 10 | Add Book</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<?php
if ($_POST) {
$book_name = $_POST['book_name'];
$img = $_POST['img'];
$author_id = $_POST[ 'author_id'];
$ISBN = $_POST[ 'ISBN'];
$description = $_POST['description'];
$publish_date = $_POST['publish_date'];
$publisher_id = $_POST['publisher_id'];
$status = $_POST['status'];
$sql = "INSERT INTO book (title, img, author_id, ISBN, description, publish_date, publisher_id, status) VALUES ('$book_name', '$img', '$author_id', '$ISBN', '$description', '$publish_date', '$publisher_id', '$status')";
if($connect->query($sql) === TRUE) {
echo "<div class='container'><div class='alert alert-success' role='alert'><h4 class='alert-heading'>Success!!!</h4><p>New Record Added to Library</p><hr>" ;
echo "<a href='../create.php'><button type='button' class='btn btn-success'>Back</button></a>";
echo "<a href='../index.php'><button type='button' class='btn btn-success'>Home</button></a></div></div>";
} else {
echo "<div class='container'><div class='alert alert-danger'><h4 class='alert-heading'>Error<h4><p> " . $sql . " " . $connect->connect_error . "</p></div></div>";
}
$connect->close();
}
?>
</body>
</html><file_sep><?php
require_once 'db_connect.php';
?>
<!DOCTYPE html>
<html>
<head>
<title >Update Book</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<?php
if ($_POST) {
$title = $_POST['title'];
$img = $_POST['img'];
$author_id = $_POST[ 'author_id'];
$ISBN = $_POST[ 'ISBN'];
$description = $_POST['description'];
$publish_date = $_POST['publish_date'];
$publisher_id = $_POST['publisher_id'];
$status = $_POST['status'];
$id = $_POST['id'];
$sql = "UPDATE book SET title = '$title', img = '$img', author_id = '$author_id', ISBN = '$ISBN', description = '$description', publish_date = '$publish_date', publisher_id = '$publisher_id', status = '$status' WHERE book_id = '$id'" ;
if($connect->query($sql) === TRUE) {
echo "<p>Successfully Updated</p>";
echo "<a href='../update.php?book_id=" .$id."'><button type='button' class='btn btn-success'>Back</button></a>";
echo "<a href='../index.php'><button type='button' class='btn btn-success'>Home</button></a>";
} else {
echo "Error while updating record : ". $connect->error;
}
$connect->close();
}
?>
</body>
</html><file_sep><?php
require_once 'db_connect.php';
?>
<html>
<head>
<title>Code Review 10 | Add CD</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<?php
if ($_POST) {
$cd_name = $_POST['cd_name'];
$img = $_POST['img'];
$artist_id = $_POST[ 'artist_id'];
$ISRC = $_POST[ 'ISRC'];
$description = $_POST['description'];
$release_date = $_POST['release_date'];
$studio_id = $_POST['studio_id'];
$status = $_POST['status'];
$sql = "INSERT INTO cd (title, img, artist_id, ISRC, description, release_date, studio_id, status) VALUES ('$cd_name', '$img', '$artist_id', '$ISRC', '$description', '$release_date', '$studio_id', '$status')";
if($connect->query($sql) === TRUE) {
echo "<div class='container'><div class='alert alert-success' role='alert'><h4 class='alert-heading'>Success!!!</h4><p>New Record Added to Library</p><hr>" ;
echo "<a href='../cd_create.php'><button type='button' class='btn btn-success'>Back</button></a>";
echo "<a href='../index.php'><button type='button' class='btn btn-success'>Home</button></a></div></div>";
} else {
echo "<div class='container'><div class='alert alert-danger'><h4 class='alert-heading'>Error<h4><p> " . $sql . " " . $connect->connect_error . "</p></div></div>";
}
$connect->close();
}
?>
</body>
</html><file_sep><?php
require_once 'db_connect.php';
?>
<!DOCTYPE html>
<html>
<head>
<title >Delete DVD</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<?php
if ($_POST) {
$id = $_POST['dvd_id'];
$sql = "DELETE FROM dvd WHERE dvd_id = $id";
if($connect->query($sql) === TRUE) {
echo "<p>Successfully deleted!!</p>" ;
echo "<a href='../index.php'><button type='button' class='btn btn-success'>Back</button></a>";
} else {
echo "Error updating record : " . $connect->error;
}
$connect->close();
}
?>
</body>
</html><file_sep><?php
require_once 'actions/db_connect.php';
if ($_GET['cd_id']) {
$id = $_GET['cd_id'];
$sql = "SELECT * FROM cd WHERE cd_id = $id" ;
$result = $connect->query($sql);
$data = $result->fetch_assoc();
$connect->close();
?>
<!DOCTYPE html>
<html>
<head>
<title >Delete CD</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="alert alert-danger">
<h3 class="alert-heading">Do you really want to delete this CD?</h3><hr>
<form action ="actions/cd_a_delete.php" method="post">
<input type="hidden" name= "cd_id" value="<?php echo $data['cd_id'] ?>" />
<button type="submit" class="btn btn-danger">Yes, delete it!</button >
<a href="index.php"><button type="button" class="btn btn-danger">No, go back!</button ></a>
</form>
</div>
</div>
</body>
</html>
<?php
}
?><file_sep><?php
require_once 'actions/db_connect.php';
?>
<html>
<head>
<title>Code Review 10</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<?php
if ($_GET['cd_id']) {
$id = $_GET['cd_id'];
$sql = "SELECT title,img,ISRC,description,release_date,artist_name, studio_name, status.status FROM cd
INNER JOIN artist ON cd.artist_id = artist.artist_id
INNER JOIN record_studio ON record_studio_id = studio_id
INNER JOIN status ON status.status_id = cd.status
WHERE cd_id = $id" ;
$result = $connect->query($sql);
$data = $result->fetch_assoc();
$connect->close();
?>
<div class="container">
<div class="card" style="width: 18rem;">
<img src="<?php echo $data['img'] ?>" class="card-img-top">
<div class="card-body">
<h5 class="card-title"><?php echo $data['title'] ?></h5>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item"><b>Artist </b><?php echo $data['artist_name'] ?></li>
<li class="list-group-item"><b>ISRC </b>
<?php echo $data['ISRC'] ?></li>
<li class="list-group-item"><b>Description </b>
<?php echo $data['description'] ?></li>
<li class="list-group-item"><b>Release Date </b><?php echo $data['release_date'] ?></li>
<li class="list-group-item"><b>Recording Studio </b><?php echo $data['studio_name'] ?></li>
<li class="list-group-item"><b>Availability </b>
<?php echo $data['status'] ?></li>
</ul>
<div class="card-body">
<a href= "index.php"><button class="btn btn-success" type="button" >Back</button ></a>
</div>
</div>
</div>
<?php
}
?>
</body>
</html><file_sep><html>
<head>
<title>Code Review 10 | Add Book</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>Add Book</h2>
<form action="actions/a_create.php" method= "post">
<div class="form-group">
<label>Book Name</label>
<input class="form-control" class="form-control" type="text" name="book_name" placeholder="Book Name" />
</div>
<div class="form-group">
<label>Image Link</label>
<input class="form-control"
type="text" name= "img" placeholder="URL" />
</div>
<div class="form-group">
<label>Author ID</label>
<input class="form-control" type="text" name="author_id" placeholder ="See reference below" />
</div>
<div class="form-group">
<label>ISBN</label>
<input class="form-control" type="text" name="ISBN" placeholder ="ISBN" />
</div>
<div class="form-group">
<label>Short Description</label>
<input class="form-control" type="text" name="description" placeholder ="Description" />
</div>
<div class="form-group">
<label>First Published Date</label>
<input class="form-control" type="date" name="publish_date" placeholder ="0000-00-00" />
</div>
<div class="form-group">
<label>Publisher ID</label>
<input class="form-control" type="text" name="publisher_id" placeholder ="See reference below" />
</div>
<div class="form-group">
<label>Status</label>
<input class="form-control" type="text" name="status" placeholder ="Status" />
<small id="statusHelp" class="form-text text-muted">0=Available, 1=Reserved</small>
</div>
<div class="form-group">
<button type='submit' class='btn btn-success'>Add Book</button>
<a href= "index.php"><button type='button' class='btn btn-success'>Back</button></a>
</div>
</form>
</div>
<div class="container">
<div class="row">
<div class="col">
<table class="table table-striped table-success">
<h2>Author Reference</h2>
<thead>
<tr>
<th>Author ID</th>
<th>First Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<?php
require_once 'actions/db_connect.php';
$sql = "SELECT * from artist";
$result = $connect->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" .$row['author_id']."</td>
<td>" .$row['author_name']."</td>
<td>" .$row['author_surname']."</td>
</tr>" ;
}
} else {
echo "<tr><td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
?>
</tbody>
</table>
</div>
<div class="col">
<table class="table table-striped table-success">
<h2>Publisher Reference</h2>
<thead>
<tr>
<th>Publisher ID</th>
<th>Name</th>
<th>Address</th>
<th>Size</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * from publisher";
$result = $connect->query($sql);
$connect->close();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" .$row['publisher_id']."</td>
<td>" .$row['publisher_name']."</td>
<td>" .$row['publisher_address']."</td>
<td>" .$row['publisher_size']."</td>
<td>
<a href='plist.php?publisher_id=" .$row['publisher_id']."'><button type='button' class='btn btn-success'>Show All Media</button></a>
</td>
</tr>" ;
}
} else {
echo "<tr><td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html><file_sep><?php
require_once 'actions/db_connect.php';
if ($_GET['dvd_id']) {
$id = $_GET['dvd_id'];
$sql = "SELECT * FROM dvd WHERE dvd_id =
$id" ;
$result = $connect->query($sql);
$data = $result->fetch_assoc();
?>
<!DOCTYPE html>
<html>
<head>
<title>Update DVD</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<div class='container'>
<h2>Update DVD</h2>
<form action="actions/dvd_a_update.php" method="post">
<div class="form-group">
<label>DVD Name</label>
<input class="form-control" type="text" name="dvd_title" placeholder="dvd Name" value="<?php echo $data['dvd_title'] ?>" />
</div>
<div class="form-group">
<label>Image Link</label>
<input class="form-control" type="text" name= "img" placeholder="URL" value ="<?php echo $data['img'] ?>" /></td >
</div>
<div class="form-group">
<label>Director ID</label>
<input class="form-control" type="text" name="director_id" placeholder ="See reference below" value= "<?php echo $data['director_id'] ?>" />
</div>
<div class="form-group">
<label>ASIN</label>
<input class="form-control" type="text" name="ASIN" placeholder ="ASIN" value= "<?php echo $data['ASIN'] ?>" />
</div>
<div class="form-group">
<label>Description</label>
<input class="form-control" type="text" name="description" placeholder ="Description" value= "<?php echo $data['description'] ?>" />
</div>
<div class="form-group">
<label>Release Date</label>
<input class="form-control" type="date" name="release_date" placeholder ="00-00-0000" value= "<?php echo $data['release_date'] ?>" />
</div>
<div class="form-group">
<label>Production_id ID</label>
<input class="form-control" type="text" name="production_id" placeholder ="See reference below" value= "<?php echo $data['production_id'] ?>" />
</div>
<div class="form-group">
<label>Availability</label>
<input class="form-control" type="text" name="status" placeholder ="status" value= "<?php echo $data['status'] ?>" />
<small id="statusHelp" class="form-text text-muted">0=Available, 1=Reserved</small>
</div>
<div class="form-group">
<input class="form-control" type= "hidden" name= "id" value= "<?php echo $data['dvd_id']?>" />
<button class="btn btn-success" type= "submit">Save Changes</button>
<a href= "index.php"><button class="btn btn-success" type="button" >Back</button ></a>
</div>
</form>
</div>
<div class="container">
<div class="row">
<div class="col">
<table class="table table-striped table-success">
<h2>Director Reference</h2>
<thead>
<tr>
<th>director ID</th>
<th>First Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * from director";
$result = $connect->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" .$row['director_id']."</td>
<td>" .$row['director_name']."</td>
<td>" .$row['director_surname']."</td>
</tr>" ;
}
} else {
echo "<tr><td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
?>
</tbody>
</table>
<table>
<h2>Production Studio Reference</h2>
<thead>
<tr>
<th>Production Studio ID</th>
<th>Name</th>
<th>Address</th>
<th>Size</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * from production_studio";
$result = $connect->query($sql);
$connect->close();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" .$row['production_id']."</td>
<td>" .$row['production_name']."</td>
<td>" .$row['production_address']."</td>
<td>" .$row['production_size']."</td>
<td>
<a href='dvdplist.php?production_id=" .$row['production_id']."'><button type='button' class='btn btn-success'>Show All Media</button></a>
</td>
</tr>" ;
}
} else {
echo "<tr><td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body >
</html >
<?php
}
?><file_sep><?php
require_once 'actions/db_connect.php';
?>
<html>
<head>
<title>Code Review 10</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<?php
if ($_GET['book_id']) {
$id = $_GET['book_id'];
$sql = "SELECT title,img,ISBN,description,publish_date,author_name,author_surname, publisher_name, status.status FROM book
INNER JOIN author ON book.author_id = author.author_id
INNER JOIN publisher ON book.publisher_id = publisher.publisher_id
INNER JOIN status ON status.status_id = book.status
WHERE book_id = $id" ;
$result = $connect->query($sql);
$data = $result->fetch_assoc();
$connect->close();
?>
<div class="container">
<div class="card" style="width: 18rem;">
<img src="<?php echo $data['img'] ?>" class="card-img-top">
<div class="card-body">
<h5 class="card-title"><?php echo $data['title'] ?></h5>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item"><b>Author </b><?php echo $data['author_name'], ' ', $data['author_surname'] ?></li>
<li class="list-group-item"><b>ISBN </b>
<?php echo $data['ISBN'] ?></li>
<li class="list-group-item"><b>Description </b>
<?php echo $data['description'] ?></li>
<li class="list-group-item"><b>First Published Date </b><?php echo $data['publish_date'] ?></li>
<li class="list-group-item"><b>Publisher </b><?php echo $data['publisher_name'] ?></li>
<li class="list-group-item"><b>Availability </b>
<?php echo $data['status'] ?></li>
</ul>
<div class="card-body">
<a href= "index.php"><button class="btn btn-success" type="button" >Back</button ></a>
</div>
</div>
</div>
<?php
}
?>
</body>
</html><file_sep><?php
require_once 'actions/db_connect.php';
?>
<html>
<head>
<title>Code Review 10 | Media List</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<table class="table table-striped table-success">
<tbody>
<?php
if ($_GET['publisher_id']) {
$id = $_GET['publisher_id'];
$sql = "SELECT title FROM book
WHERE publisher_id = $id" ;
$result = $connect->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row['title']. "</td></tr>";
}
} else {
echo "<tr><td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
$connect->close();
}
?>
</tbody>
</table>
</body>
</html><file_sep><?php
require_once 'actions/db_connect.php';
?>
<html>
<head>
<title>Code Review 10</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<?php
if ($_GET['dvd_id']) {
$id = $_GET['dvd_id'];
$sql = "SELECT dvd_title,img,ASIN,description,release_date,director_name,director_surname, production_name, status.status FROM dvd
INNER JOIN director ON dvd.director_id = director.director_id
INNER JOIN production_studio ON dvd.production_id = production_studio.production_id
INNER JOIN status ON status.status_id = dvd.status
WHERE dvd_id = $id" ;
$result = $connect->query($sql);
$data = $result->fetch_assoc();
$connect->close();
?>
<div class="container">
<div class="card" style="width: 18rem;">
<img src="<?php echo $data['img'] ?>" class="card-img-top">
<div class="card-body">
<h5 class="card-title"><?php echo $data['dvd_title'] ?></h5>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item"><b>Director </b><?php echo $data['director_name'], ' ', $data['director_surname'] ?></li>
<li class="list-group-item"><b>ASIN </b>
<?php echo $data['ASIN'] ?></li>
<li class="list-group-item"><b>Description </b>
<?php echo $data['description'] ?></li>
<li class="list-group-item"><b>Release Date </b><?php echo $data['release_date'] ?></li>
<li class="list-group-item"><b>Production Studio </b><?php echo $data['production_name'] ?></li>
<li class="list-group-item"><b>Availability </b>
<?php echo $data['status'] ?></li>
</ul>
<div class="card-body">
<a href= "index.php"><button class="btn btn-success" type="button" >Back</button ></a>
</div>
</div>
</div>
<?php
}
?>
</body>
</html><file_sep><html>
<head>
<title>Code Review 10 | Add CD</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>Add CD</h2>
<form action="actions/cd_a_create.php" method= "post">
<div class="form-group">
<label>CD Name</label>
<input class="form-control" class="form-control" type="text" name="cd_name" placeholder="CD Name" />
</div>
<div class="form-group">
<label>Image Link</label>
<input class="form-control"
type="text" name= "img" placeholder="URL" />
</div>
<div class="form-group">
<label>Artist ID</label>
<input class="form-control" type="text" name="artist_id" placeholder ="See reference below" />
</div>
<div class="form-group">
<label>ISRC</label>
<input class="form-control" type="text" name="ISRC" placeholder ="ISRC" />
</div>
<div class="form-group">
<label>Short Description</label>
<input class="form-control" type="text" name="description" placeholder ="Description" />
</div>
<div class="form-group">
<label>First Released Date</label>
<input class="form-control" type="date" name="release_date" placeholder ="0000-00-00" />
</div>
<div class="form-group">
<label>Studio ID</label>
<input class="form-control" type="text" name="studio_id" placeholder ="See reference below" />
</div>
<div class="form-group">
<label>Status</label>
<input class="form-control" type="text" name="status" placeholder ="Status" />
<small id="statusHelp" class="form-text text-muted">0=Available, 1=Reserved</small>
</div>
<div class="form-group">
<button type='submit' class='btn btn-success'>Add CD</button>
<a href= "index.php"><button type='button' class='btn btn-success'>Back</button></a>
</div>
</form>
</div>
<div class="container">
<div class="row">
<div class="col">
<table class="table table-striped table-success">
<h2>Artist Reference</h2>
<thead>
<tr>
<th>Artist ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php
require_once 'actions/db_connect.php';
$sql = "SELECT * from artist";
$result = $connect->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" .$row['artist_id']."</td>
<td>" .$row['artist_name']."</td>
</tr>" ;
}
} else {
echo "<tr><td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
?>
</tbody>
</table>
</div>
<div class="col">
<table class="table table-striped table-success">
<h2>Studio Reference</h2>
<thead>
<tr>
<th>Studio ID</th>
<th>Name</th>
<th>Address</th>
<th>Size</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * from record_studio";
$result = $connect->query($sql);
$connect->close();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" .$row['record_studio_id']."</td>
<td>" .$row['studio_name']."</td>
<td>" .$row['studio_address']."</td>
<td>" .$row['studio_size']."</td>
<td>
<a href='cdplist.php?record_studio_id=" .$row['record_studio_id']."'><button type='button' class='btn btn-success'>Show All Media</button></a>
</td>
</tr>" ;
}
} else {
echo "<tr><td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html><file_sep><?php
require_once 'actions/db_connect.php';
if ($_GET['book_id']) {
$id = $_GET['book_id'];
$sql = "SELECT * FROM book WHERE book_id =
$id" ;
$result = $connect->query($sql);
$data = $result->fetch_assoc();
?>
<!DOCTYPE html>
<html>
<head>
<title>Update Book</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class='container'>
<h2>Update Book</h2>
<form action="actions/a_update.php" method="post">
<div class="form-group">
<label>Book Name</label>
<input class="form-control" type="text" name="title" placeholder="Book Name" value="<?php echo $data['title'] ?>" />
</div>
<div class="form-group">
<label>Image Link</label>
<input class="form-control" type="text" name= "img" placeholder="URL" value ="<?php echo $data['img'] ?>" />
</div>
<div class="form-group">
<label>Author ID</label>
<input class="form-control" type="text" name="author_id" placeholder ="See reference below" value= "<?php echo $data['author_id'] ?>" />
</div>
<div class="form-group">
<label>ISBN</label>
<input class="form-control" type="text" name="ISBN" placeholder ="ISBN" value= "<?php echo $data['ISBN'] ?>" />
</div>
<div class="form-group">
<label>Description</label>
<input class="form-control" type="text" name="description" placeholder ="Description" value= "<?php echo $data['description'] ?>" />
</div>
<div class="form-group">
<label>First Publish Date</label>
<input class="form-control" type="date" name="publish_date" placeholder ="00-00-0000" value= "<?php echo $data['publish_date'] ?>" />
</div>
<div class="form-group">
<label>Publisher ID</label>
<input class="form-control" type="text" name="publisher_id" placeholder ="See reference below" value= "<?php echo $data['publisher_id'] ?>" />
</div>
<div class="form-group">
<label>Availability</label>
<input class="form-control" type="text" name="status" placeholder ="Status" value= "<?php echo $data['status'] ?>" />
<small id="statusHelp" class="form-text text-muted">0=Available, 1=Reserved</small>
</div>
<div class="form-group">
<input type= "hidden" name= "id" value= "<?php echo $data['book_id']?>" />
<button type= "submit" class="btn btn-success">Save Changes</button>
<a href= "index.php"><button type="button" class="btn btn-success">Back</button ></a>
</div>
</form>
</div>
<div class="container">
<div class="row">
<div class="col">
<table class="table table-striped table-success">
<h2>Author Reference</h2>
<thead>
<th>Author ID</th>
<th>First Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * from author";
$result = $connect->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" .$row['author_id']."</td>
<td>" .$row['author_name']."</td>
<td>" .$row['author_surname']."</td>
</tr>" ;
}
} else {
echo "<td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
?>
</tbody>
</table>
</div>
<div class="col">
<table class="table table-striped table-success">
<h2>Publisher Reference</h2>
<thead>
<th>Publisher ID</th>
<th>Name</th>
<th>Address</th>
<th>Size</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * from publisher";
$result = $connect->query($sql);
$connect->close();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" .$row['publisher_id']."</td>
<td>" .$row['publisher_name']."</td>
<td>" .$row['publisher_address']."</td>
<td>" .$row['publisher_size']."</td>
<td>
<a href='plist.php?publisher_id=" .$row['publisher_id']."'><button type='button' class='btn btn-success'>Show All Media</button></a>
</td>
</tr>" ;
}
} else {
echo "<td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body >
</html >
<?php
}
?><file_sep><?php
require_once 'actions/db_connect.php';
if ($_GET['cd_id']) {
$id = $_GET['cd_id'];
$sql = "SELECT * FROM cd WHERE cd_id =
$id" ;
$result = $connect->query($sql);
$data = $result->fetch_assoc();
?>
<!DOCTYPE html>
<html>
<head>
<title>Update CD</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<div class='container'>
<h2>Update CD</h2>
<form action="actions/cd_a_update.php" method="post">
<div class="form-group">
<label>CD Name</label>
<input class="form-control" type="text" name="title" placeholder="CD Name" value="<?php echo $data['title'] ?>" />
</div>
<div class="form-group">
<label>Image Link</label>
<input class="form-control" type="text" name= "img" placeholder="URL" value ="<?php echo $data['img'] ?>" />
</div>
<div class="form-group">
<label>Artist ID</label>
<input class="form-control" type="text" name="artist_id" placeholder ="See reference below" value= "<?php echo $data['artist_id'] ?>" />
</div>
<div class="form-group">
<label>ISRC</label>
<input class="form-control" type="text" name="ISRC" placeholder ="ISRC" value= "<?php echo $data['ISRC'] ?>" />
</div>
<div class="form-group">
<label>Description</label>
<input class="form-control" type="text" name="description" placeholder ="Description" value= "<?php echo $data['description'] ?>" />
</div>
<div class="form-group">
<label>First Release Date</label>
<input class="form-control" type="date" name="release_date" placeholder ="00-00-0000" value= "<?php echo $data['release_date'] ?>" />
</div>
<div class="form-group">
<label>Studio ID</label>
<input class="form-control" type="text" name="studio_id" placeholder ="See reference below" value= "<?php echo $data['studio_id'] ?>" />
</div>
<div class="form-group">
<label>Availability</label>
<input class="form-control" type="text" name="status" placeholder ="Status" value= "<?php echo $data['status'] ?>" />
<small id="statusHelp" class="form-text text-muted">0=Available, 1=Reserved</small>
</div>
<div class="form-group">
<input type= "hidden" name= "id" value= "<?php echo $data['cd_id']?>" />
<button type= "submit" class="btn btn-success">Save Changes</button>
<a href= "index.php"><button type="button" class="btn btn-success">Back</button ></a>
</div>
</form>
</div>
<div class="container">
<div class="row">
<div class="col">
<table class="table table-striped table-success">
<h2>Artist Reference</h2>
<thead>
<th>Artist ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * from artist";
$result = $connect->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" .$row['artist_id']."</td>
<td>" .$row['artist_name']."</td>
</tr>" ;
}
} else {
echo "<td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
?>
</tbody>
</table>
</div>
<div class="col">
<table class="table table-striped table-success">
<h2>Studio Reference</h2>
<thead>
<th>Studio ID</th>
<th>Name</th>
<th>Address</th>
<th>Size</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * from record_studio";
$result = $connect->query($sql);
$connect->close();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" .$row['record_studio_id']."</td>
<td>" .$row['studio_name']."</td>
<td>" .$row['studio_address']."</td>
<td>" .$row['studio_size']."</td>
<td>
<a href='cdplist.php?record_studio_id=" .$row['record_studio_id']."'><button type='button' class='btn btn-success'>Show All Media</button></a>
</td>
</tr>" ;
}
} else {
echo "<td colspan='5'><center>No Data Avaliable</center></td></tr>";
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body >
</html >
<?php
}
?>
|
182429cc9803eb79879e113baab8cdbe8e4036a4
|
[
"SQL",
"PHP"
] | 17
|
SQL
|
ambercameron/FSWD70-CodeReview10-AmberCameron
|
ef12e4bdb7eba68ba28dac2cba4b41e4d55ea879
|
5621351f7fe564d2965cb6835d8eac33370a9c23
|
refs/heads/master
|
<file_sep># webRTC-Multi-person-video-conference-room
multi-person video conference room
<file_sep>package com.scbd.bdpl.controller.multimedia;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* websocket服务
* @author Ivan
*
*/
@ServerEndpoint("/websocket/{username}")
public class SocketServer {
private static Map<String, Session> userOnlineMap = new HashMap<String,Session>();
//连接时
@OnOpen
public void open(Session session,@PathParam("username")String username) {
for (String onlineUsername : userOnlineMap.keySet()) {
if(onlineUsername.equals(username)) {//用户已存在
System.out.println("用户已存在,或用户名重复");
return;
}
}
//转发给其他人上线消息
JSONObject json=new JSONObject();
json.put("type", "userConnection");
json.put("data", username);
forwardMessageExceptMe(session, json.toString());
System.out.println(username + "open");
userOnlineMap.put(username,session);//添加用户进入在线列表
}
//收到消息
@OnMessage
public void OnMessage(String message, Session session,@PathParam("username")String username) {
//获得消息并转为JSON
JSONObject json=JSON.parseObject(message);
String type=(String) json.get("type");
//判断消息
switch (type) {
//查询在线用户
case "getOnlineUserName":
replyOnlineUserName(session);
break;
//转发消息给sendTo
default:
String sendBy=(String) json.get("sendBy");
String sendTo=(String) json.get("sendTo");
if(sendBy!=null&&sendTo!=null) {
forwardMessage(userOnlineMap.get(sendTo), message);
}
break;
}
}
@OnClose
public void close(Session session,@PathParam("username")String username) {
System.out.println(username + "close");
try {
userOnlineMap.remove(username, session);
session.close();
//转发给其他人下线消息
JSONObject json=new JSONObject();
json.put("type", "userClose");
json.put("data", username);
forwardMessageExceptMe(session, json.toString());
} catch (IOException e) {
// e.printStackTrace();
}
}
//回复在线用户
private void replyOnlineUserName(Session session) {
Set<String> OnlineUserNames=userOnlineMap.keySet();
JSONObject json=new JSONObject();
json.put("type", "userOnlineList");
json.put("data", OnlineUserNames);
forwardMessage(session,json.toString());
}
//转发消息特定目标
private void forwardMessage(Session session,String message) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
// e.printStackTrace();
}
}
//转发消息给所有人
private void forwardMessage(Collection<Session> sessions,String message) {
for (Session session : sessions) {
forwardMessage(session,message);
}
}
//转发消息给除自己以外的所有人
private void forwardMessageExceptMe(Session session,String message) {
for (Session sessions : userOnlineMap.values()) {
if(!sessions.equals(session)) {
forwardMessage(sessions,message);
}
}
}
}
|
63a4a607574a7b74a93289599bdc67ac120f0904
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
EricTop3/webRTC-Multi-person-video-conference-room
|
e401f7a6117512076f12d9ca64116fb53ee130cf
|
3be45d73791b80c7abbbb943b4db233a2746a577
|
refs/heads/master
|
<repo_name>ludowica-fernando/GoogleMaps<file_sep>/app/src/main/java/com/shenal/googlemaps/TemperatureLineChart.java
package com.shenal.googlemaps;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class TemperatureLineChart extends AppCompatActivity {
LineChart lineChart;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;//database
LineDataSet lineDataSet = new LineDataSet(null, null);
ArrayList<ILineDataSet> iLineDataSets = new ArrayList<>();
LineData lineData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temperature_line_chart);
lineChart = findViewById(R.id.line_chart);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("masterSheet");
retrieveData();
Button btnList = findViewById(R.id.btnList);
btnList.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goToList();
}
});
}
private void retrieveData() {
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ArrayList<Entry> dataVals = new ArrayList<Entry>();
if (dataSnapshot.hasChildren()) {
for (DataSnapshot myDataSnapshot : dataSnapshot.getChildren()) {
DataPoint dataPoint = myDataSnapshot.getValue(DataPoint.class);
dataVals.add(new Entry(dataPoint.getDay(), dataPoint.getTemperature()));
}
showChart(dataVals);
} else {
lineChart.invalidate();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void showChart(ArrayList<Entry> dataVals) {
lineDataSet.setValues(dataVals);
lineDataSet.setLabel("Temperature");
iLineDataSets.clear();
iLineDataSets.add(lineDataSet);
lineData = new LineData(iLineDataSets);
lineChart.clear();
lineChart.setData(lineData);
lineChart.invalidate();
}
private void goToList() {
Intent intent = new Intent(this, Temp_Data.class);
startActivity(intent);
}
}
<file_sep>/app/src/main/java/com/shenal/googlemaps/MapsActivity.java
package com.shenal.googlemaps;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.github.mikephil.charting.data.Entry;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener, LocationListener {
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_maps);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("masterSheet");
// Get the SupportMapFragment and request notification
// when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
googleMap.setOnMarkerClickListener(this);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot s : dataSnapshot.getChildren()) {
MapData mapData = s.getValue(MapData.class);
DataPoint dataPoint = s.getValue(DataPoint.class);
LatLng location = new LatLng(mapData.latitude, mapData.longitude);
mMap.addMarker(new MarkerOptions().position(location).title("Date: " + dataPoint.getDay() + "Temperature : " + dataPoint.getTemperature())).setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public boolean onMarkerClick(Marker marker) {
return false;
}
}<file_sep>/app/src/main/java/com/shenal/googlemaps/DODataPoint.java
package com.shenal.googlemaps;
public class DODataPoint {
int day;
int dissolvedoxygen;
public DODataPoint(int day, int dissolvedoxygen) {
this.day = day;
this.dissolvedoxygen = dissolvedoxygen;
}
public DODataPoint() {
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getDissolvedoxygen() {
return dissolvedoxygen;
}
public void setDissolvedoxygen(int dissolvedoxygen) {
this.dissolvedoxygen = dissolvedoxygen;
}
}
<file_sep>/app/src/main/java/com/shenal/googlemaps/Oxy_fetch.java
package com.shenal.googlemaps;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Oxy_fetch extends AsyncTask<Void, Void, Void> {
String data = "";
String singleParsed = "";
String dataParsed = "";
@Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://script.googleusercontent.com/macros/echo?user_content_key=<KEY>&lib=MnrE7b2I2PjfH799VodkCPiQjIVyBAxva"); //get from which website
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); //check connection
InputStream inputStream = httpURLConnection.getInputStream(); //this is input
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((inputStream)));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
data = data.substring(10);//delete first 11 character = sheet1
JSONArray JA = new JSONArray(data);
for (int i = 0; i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "Day: " + JO.get("Day") + "/" + JO.get("Month") + "/" + JO.get("Year") + "\n" +
"Dissolved Oxygen: " + JO.get("DissolvedOxygen") + "\n";
dataParsed = dataParsed + singleParsed + "\n";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Oxy_Data.oxydata.setText(this.dataParsed);
}
}
<file_sep>/app/src/main/java/com/shenal/googlemaps/Humidity_Data.java
package com.shenal.googlemaps;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.os.Bundle;
import android.widget.TextView;
public class Humidity_Data extends AppCompatActivity {
public static TextView oxydata;
public static SwipeRefreshLayout pullToRefresh;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_humidity__data);
oxydata = findViewById(R.id.data);
pullToRefresh = findViewById(R.id.refresh);
Humidity_fetch process = new Humidity_fetch();
process.execute();
pullToRefresh.setRefreshing(false);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
Humidity_fetch process = new Humidity_fetch();
process.execute();
pullToRefresh.setRefreshing(false);
}
});
}
}
|
71f9b027575de84e56c381191c30e408e0e0dc3d
|
[
"Java"
] | 5
|
Java
|
ludowica-fernando/GoogleMaps
|
145ab9d6d9426b0c75ff2656ce01c7d610973f15
|
74fb13a13e87f8f07626758d7de11936ce7c7762
|
refs/heads/master
|
<repo_name>rafi16jan/micropython<file_sep>/ports/javascript/js.c
#include "py/nlr.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "py/binary.h"
#include <stdio.h>
#include <string.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
STATIC mp_obj_t js_exec(mp_obj_t code) {
char * result = emscripten_run_script_string(mp_obj_str_get_str(code));
return mp_obj_new_str(result, strlen(result));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(js_exec_obj, js_exec);
STATIC mp_obj_t js_sleep(mp_obj_t milliseconds) {
emscripten_sleep_with_yield(mp_obj_get_int(milliseconds));
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(js_sleep_obj, js_sleep);
STATIC const mp_map_elem_t js_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_js) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_exec), (mp_obj_t)&js_exec_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_sleep), (mp_obj_t)&js_sleep_obj },
};
STATIC MP_DEFINE_CONST_DICT (
mp_module_js_globals,
js_globals_table
);
const mp_obj_module_t mp_module_js = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_js_globals,
};
|
b2961be92b062ba22e06afd72acef80084789351
|
[
"C"
] | 1
|
C
|
rafi16jan/micropython
|
21bf511f93dd94a5ac05626b5a94c70d7492d427
|
82ad6602ff5c551bf04dc0a5c37d7e4f5debf591
|
refs/heads/master
|
<file_sep>package hello;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HelloController {
@RequestMapping(value="/greeting", method=RequestMethod.GET)
public String index(Model model) {
return "hello";
}
@RequestMapping(value="/", method=RequestMethod.GET)
public String sales(Model model) {
return "sales";
}
}<file_sep><?xml version="1.0" encoding="UTF-8"?>
<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>org.springframework</groupId>
<artifactId>gs-rest-service</artifactId>
<version>0.1.0</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-http</artifactId>
<version>2.8</version>
</dependency>
<!-- Drools -->
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>6.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>6.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-internal</artifactId>
<version>6.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-ci</artifactId>
<version>6.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-api</artifactId>
<version>6.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-templates</artifactId>
<version>6.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.mvel</groupId>
<artifactId>mvel2</artifactId>
<version>2.2.1.Final</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr-runtime</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-decisiontables</artifactId>
<version>6.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.eclipse.jdt</groupId>
<artifactId>org.eclipse.jdt.core</artifactId>
<version>3.7.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.3</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.5.0</version>
</dependency>
</dependencies>
<properties>
<start-class>hello.Application</start-class>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project><file_sep>package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.drools.compiler.kproject.ReleaseIdImpl;
import org.drools.core.io.impl.UrlResource;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.api.builder.KieScanner;
import org.kie.api.builder.KieModule;
import org.kie.internal.io.ResourceFactory;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
@RestController
public class GreetingController {
private KieScanner scanner = null;
private KieContainer kieContainer = null;
private void loadKie(String urlBase) {
if (kieContainer == null) {
String url = urlBase + "/workbench/maven2/com/sep/test/greeting/1.0/greeting-1.0.jar";
KieServices ks = KieServices.Factory.get();
UrlResource urlResource = (UrlResource) ks.getResources().newUrlResource(url);
try {
InputStream is = urlResource.getInputStream();
KieModule kModule = ks.getRepository().addKieModule(ks.getResources().newInputStreamResource(is));
System.out.println(kModule.getReleaseId());
kieContainer = ks.newKieContainer(new ReleaseIdImpl("com.sep.test", "greeting", "LATEST"));
scanner = ks.newKieScanner(kieContainer);
} catch(Exception e) {
System.out.println("Exception thrown while constructing InputStream");
System.out.println(e.getMessage());
}
}
}
private void runRules(Greeting g, String baseUrl) {
loadKie(baseUrl);
scanner.scanNow(); // update resource
StatelessKieSession kieSession = kieContainer.newStatelessKieSession();
kieSession.execute(g);
}
private String getBaseURL(HttpServletRequest request) {
String url = request.getRequestURL().toString();
return url.substring(0, url.length() - request.getRequestURI().length());
}
@RequestMapping("/greeting/data")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name,
@RequestParam(value="language", defaultValue="english") String language,
HttpServletRequest request) {
Greeting g = new Greeting(1, name, language);
runRules(g, getBaseURL(request));
return g;
}
}<file_sep>package hello;
public class Sales {
public String role = "";
public String channel = "";
public boolean isActive = true;
public boolean showAllProducts = false;
public boolean showOasActivity = false;
public boolean showNewBusiness = false;
public boolean showUserList = false;
public boolean showCsProducts = false;
public boolean showCommissionInfo = false;
public Sales(String role, String channel, boolean isActive) {
this.role = role;
this.channel = channel;
this.isActive = isActive;
}
public void setShowAllProducts(boolean val) {
this.showAllProducts = val;
}
public void setShowOasActivity(boolean val) {
this.showOasActivity = val;
}
public void setShowNewBusiness(boolean val) {
this.showNewBusiness = val;
}
public void setShowUserList(boolean val) {
this.showUserList = val;
}
public void setShowCsProducts(boolean val) {
this.showCsProducts = val;
}
public void setShowCommissionInfo(boolean val) {
this.showCommissionInfo = val;
}
}
|
b812e021fa574f4a211461d1e61fb75d6fcb4895
|
[
"Java",
"Maven POM"
] | 4
|
Java
|
larryprice/rules-engine-experiment-drools
|
e3aaaec7663e575a61a38d7059e2f34aa7446ba6
|
127217662ca4daf88ce1b7ee3a348815f16c57d2
|
refs/heads/master
|
<file_sep># Searchable Directory App
[](https://opensource.org/licenses/MIT)
### Table of Contents
1. [Description](#description)
2. [Usage](#usage)
3. [License](#license)
4. [Contributing](#contribution)
5. [Tests](#testing)
6. [Questions](#questions)
### Description
-The user will be able to see their entire directory of soccer players and search for individual soccer players by name.
#### User Story
- AS a coach
I WANT to be able to see my roster of players and quickly check their statistics.
### Usage
-When preparing to win.
### License
- MIT
### Contributing
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
### Tests
- See deployed app on
[Heroku ](https://still-plateau-25675.herokuapp.com/)
and
[GitHub ](https://github.com/camrynnesullivan/Employee-Directory-1)
to test features.
#### Questions
- GitHub Profile: (https://github.com/camrynnesullivan)
- Email: <EMAIL>
<file_sep>import React, { useState } from "react";
import players from "../Table/players.json";
const style = {
textAlign: "center",
display: "block",
margin: "0 auto",
};
function Search({ setResults }) {
const [search, setSearch] = useState("");
const handleInputChange = (event) => {
setSearch(event.target.value);
if (event.target.value === "") {
setResults(players);
} else {
var filteredPlayers = players.filter((player) => {
return player.name.toLowerCase().includes(search);
});
console.log(filteredPlayers);
setResults(filteredPlayers);
}
};
return (
<div className="search" style={style}>
<h3>Search for a player here!</h3>
<input
placeholder="search here"
className="user-type"
style={style}
value={search}
onChange={handleInputChange}
></input>
</div>
);
}
export default Search;
|
d8c8dc8c8f1079fc4e88f8d3d05cd4597c86e02d
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
camrynnesullivan/Employee-Directory-1
|
4aa7f7daedf68cac8cd5ae2530e4ad69f3a97f43
|
76c6904a601934432838c1a0f1066f05d63f7efc
|
refs/heads/master
|
<repo_name>lujdong/boty-design<file_sep>/dumi/docs/Button.md
<!--
* @Author: Cookie
* @Date: 2021-03-03 13:15:56
* @LastEditors: Cookie
* @LastEditTime: 2021-03-03 20:42:37
* @Description:
-->
---
Button
---
```jsx
/**
* title: 普通配置
* desc: 参考 antd
*/
import React from 'react';
import { Button } from "boty";
export default () => <Button>按钮</Button>
```
```jsx
/**
* title: loading
* desc: 单loading属性存在时,会将点击方法视为异步,用 await 承接
*/
import React from 'react';
import { Button } from "boty";
const handlerSyncClick = () => {
return new Promise((resolve) => {
setTimeout(() => {
alert('回调结束')
resolve(true);
}, 1000);
});
};
export default () => <Button onClick={handlerSyncClick} loading>异步回调</Button>
```
<API src="../../src/components/Button/index.tsx"></API><file_sep>/dumi/.umi-production/core/routes.ts
// @ts-nocheck
import React from 'react';
import { ApplyPluginsType } from 'D:/self_git/vite-react-boty-desing/node_modules/umi/node_modules/@umijs/runtime';
import * as umiExports from './umiExports';
import { plugin } from './plugin';
export function getRoutes() {
const routes = [
{
"path": "/~demos/:uuid",
"layout": false,
"wrappers": [require('D:/self_git/vite-react-boty-desing/node_modules/@umijs/preset-dumi/lib/theme/layout').default],
"component": (props) => {
const React = require('react');
const renderArgs = require('../../../node_modules/@umijs/preset-dumi/lib/plugins/features/demo/getDemoRenderArgs').default(props);
switch (renderArgs.length) {
case 1:
// render demo directly
return renderArgs[0];
case 2:
// render demo with previewer
return React.createElement(
require('dumi-theme-default/src/builtins/Previewer.tsx').default,
renderArgs[0],
renderArgs[1],
);
default:
return `Demo ${uuid} not found :(`;
}
}
},
{
"path": "/_demos/:uuid",
"redirect": "/~demos/:uuid"
},
{
"__dumiRoot": true,
"layout": false,
"path": "/",
"wrappers": [require('D:/self_git/vite-react-boty-desing/node_modules/@umijs/preset-dumi/lib/theme/layout').default, require('D:/self_git/vite-react-boty-desing/node_modules/dumi-theme-default/src/layout.tsx').default],
"routes": [
{
"path": "/button",
"component": require('D:/self_git/vite-react-boty-desing/dumi/docs/Button.md').default,
"exact": true,
"meta": {
"filePath": "docs/Button.md",
"updatedTime": null,
"slugs": [
{
"depth": 2,
"value": "Button",
"heading": "button"
},
{
"depth": 2,
"value": "API",
"heading": "api"
}
],
"title": "Button"
},
"title": "Button"
},
{
"path": "/",
"component": require('D:/self_git/vite-react-boty-desing/dumi/docs/index.md').default,
"exact": true,
"meta": {
"filePath": "docs/index.md",
"updatedTime": null,
"slugs": [
{
"depth": 2,
"value": "首页",
"heading": "首页"
}
],
"title": "首页"
},
"title": "首页"
}
],
"title": "boty-design",
"component": (props) => props.children
}
];
// allow user to extend routes
plugin.applyPlugins({
key: 'patchRoutes',
type: ApplyPluginsType.event,
args: { routes },
});
return routes;
}
<file_sep>/dumi/docs/index.md
<!--
* @Author: Cookie
* @Date: 2021-03-03 13:15:56
* @LastEditors: Cookie
* @LastEditTime: 2021-03-03 14:42:07
* @Description:
-->
---
首页
---
欢乐造轮子团队启航
|
bd3dffe196def0c01db72c9002158e9a985163d4
|
[
"Markdown",
"TypeScript"
] | 3
|
Markdown
|
lujdong/boty-design
|
d7815675b9222b6e0a20e364c2de184d7ab7afec
|
8268d51d3b7fa7458565d730dd9a0c7481df969b
|
refs/heads/master
|
<file_sep># sequence2sequence-chatbot
a chatbot which is implemented via seq2seq LSTM model.
how to train
run 'data.py' to produce some files we needed.
run 'train.py' to train the model.
run 'test_model.py' to predict.
requirements
python3.5
tensorflow1.3
<file_sep>import tensorflow as tf
import numpy as np
batch_size = 27
sequence_length = 10
hidden_size = 256
num_layers = 2
num_encoder_symbols = 1004 # 'UNK' and '<go>' and '<eos>' and '<pad>'
num_decoder_symbols = 1004
embedding_size = 256
learning_rate = 0.001
model_dir = './model'
encoder_inputs = tf.placeholder(dtype=tf.int32, shape=[batch_size, sequence_length])
decoder_inputs = tf.placeholder(dtype=tf.int32, shape=[batch_size, sequence_length])
targets = tf.placeholder(dtype=tf.int32, shape=[batch_size, sequence_length])
weights = tf.placeholder(dtype=tf.float32, shape=[batch_size, sequence_length])
cell = tf.nn.rnn_cell.BasicLSTMCell(hidden_size)
cell = tf.nn.rnn_cell.MultiRNNCell([cell] * num_layers)
def loadQA():
train_x = np.load('./data/idx_q.npy', mmap_mode='r')
train_y = np.load('./data/idx_a.npy', mmap_mode='r')
train_target = np.load('./data/idx_o.npy', mmap_mode='r')
return train_x, train_y, train_target
results, states = tf.contrib.legacy_seq2seq.embedding_rnn_seq2seq(
tf.unstack(encoder_inputs, axis=1),
tf.unstack(decoder_inputs, axis=1),
cell,
num_encoder_symbols,
num_decoder_symbols,
embedding_size,
feed_previous=False
)
logits = tf.stack(results, axis=1)
print("sssss: ", logits)
loss = tf.contrib.seq2seq.sequence_loss(logits, targets=targets, weights=weights)
pred = tf.argmax(logits, axis=2)
train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
saver = tf.train.Saver()
train_weights = np.ones(shape=[batch_size, sequence_length], dtype=np.float32)
with tf.Session() as sess:
ckpt = tf.train.get_checkpoint_state(model_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
else:
sess.run(tf.global_variables_initializer())
epoch = 0
while epoch < 5000000:
epoch = epoch + 1
print("epoch:", epoch)
for step in range(0, 1):
print("step:", step)
train_x, train_y, train_target = loadQA()
train_encoder_inputs = train_x[step * batch_size:step * batch_size + batch_size, :]
train_decoder_inputs = train_y[step * batch_size:step * batch_size + batch_size, :]
train_targets = train_target[step * batch_size:step * batch_size + batch_size, :]
op = sess.run(train_op, feed_dict={encoder_inputs: train_encoder_inputs, targets: train_targets,
weights: train_weights, decoder_inputs: train_decoder_inputs})
cost = sess.run(loss, feed_dict={encoder_inputs: train_encoder_inputs, targets: train_targets,
weights: train_weights, decoder_inputs: train_decoder_inputs})
print(cost)
step = step + 1
if epoch % 100 == 0:
saver.save(sess, model_dir + '/model.ckpt', global_step=epoch + 1)
|
bdbaba79b2d2c0bc320535a9d537965b93b3b57e
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
amlolex50/sequence2sequence-chatbot
|
0fe97e308a383fd28b1c818c6488b1d7bb3507b9
|
498b9575362fd12af0cd92b7816d74591c0bba90
|
refs/heads/master
|
<repo_name>copypasteearth/FuelStore<file_sep>/fuel/app/tasks/tables/category-sqlite.sql
create table `category` (
id integer primary key not null,
name text unique not null collate nocase
);
<file_sep>/fuel/app/tasks/tables/selection-mysql.sql
create table `selection` (
id integer auto_increment primary key not null,
product_id integer not null,
order_id integer not null,
quantity integer not null,
purchase_price real not null,
foreign key(order_id) references `order`(id),
foreign key(product_id) references product(id),
unique(order_id,product_id)
);
<file_sep>/fuel/app/classes/model/category.php
<?php
class Model_Category extends \Orm\Model {
protected static $_table_name = 'category';
protected static $_properties = [
'id',
'name',
];
// use $category->products to get the products with this category
protected static $_has_many = [
'products' => [
'model_to' => 'Model_Product',
]
];
}
<file_sep>/fuel/app/tmp/Smarty/templates_c/faccc4a106138e0b6f873504275f6057391ac9d0_0.file.index.tpl.php
<?php
/* Smarty version 3.1.33, created on 2019-04-18 20:01:41
from 'C:\Users\copyp\OneDrive\Documents\NetBeansProjects\FuelStore\fuel\app\views\home\index.tpl' */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.33',
'unifunc' => 'content_5cb90fe5d34906_50565153',
'has_nocache_code' => false,
'file_dependency' =>
array (
'faccc4a106138e0b6f873504275f6057391ac9d0' =>
array (
0 => 'C:\\Users\\copyp\\OneDrive\\Documents\\NetBeansProjects\\FuelStore\\fuel\\app\\views\\home\\index.tpl',
1 => 1555631874,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_5cb90fe5d34906_50565153 (Smarty_Internal_Template $_smarty_tpl) {
$_smarty_tpl->_loadInheritance();
$_smarty_tpl->inheritance->init($_smarty_tpl, true);
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_11994313265cb90fe593a9d1_54517756', "localstyle");
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_67368345cb90fe593bfa5_60817670', "content");
?>
<?php $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl");
}
/* {block "localstyle"} */
class Block_11994313265cb90fe593a9d1_54517756 extends Smarty_Internal_Block
{
public $subBlocks = array (
'localstyle' =>
array (
0 => 'Block_11994313265cb90fe593a9d1_54517756',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<style type="text/css">
</style>
<?php
}
}
/* {/block "localstyle"} */
/* {block "content"} */
class Block_67368345cb90fe593bfa5_60817670 extends Smarty_Internal_Block
{
public $subBlocks = array (
'content' =>
array (
0 => 'Block_67368345cb90fe593bfa5_60817670',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
$_smarty_tpl->_checkPlugins(array(0=>array('file'=>'C:\\Users\\copyp\\OneDrive\\Documents\\NetBeansProjects\\FuelStore\\fuel\\vendor\\smarty\\smarty\\libs\\plugins\\function.html_options.php','function'=>'smarty_function_html_options',),));
?>
<h2>Products</h2>
<?php $_block_plugin1 = isset($_smarty_tpl->smarty->registered_plugins['block']['form'][0][0]) ? $_smarty_tpl->smarty->registered_plugins['block']['form'][0][0] : null;
if (!is_callable(array($_block_plugin1, 'form'))) {
throw new SmartyException('block tag \'form\' not callable or registered');
}
$_smarty_tpl->smarty->_cache['_tag_stack'][] = array('form', array('attrs'=>array('method'=>'GET','action'=>'home/something')));
$_block_repeat=true;
echo $_block_plugin1->form(array('attrs'=>array('method'=>'GET','action'=>'home/something')), null, $_smarty_tpl, $_block_repeat);
while ($_block_repeat) {
ob_start();?>
<button type="submit">Choose category:</button>
<select name='category_id'>
<?php echo smarty_function_html_options(array('options'=>$_smarty_tpl->tpl_vars['categories']->value,'selected'=>$_smarty_tpl->tpl_vars['category_id']->value),$_smarty_tpl);?>
</select>
<?php $_block_repeat=false;
echo $_block_plugin1->form(array('attrs'=>array('method'=>'GET','action'=>'home/something')), ob_get_clean(), $_smarty_tpl, $_block_repeat);
}
array_pop($_smarty_tpl->smarty->_cache['_tag_stack']);?>
<p></p>
<table class="table table-hover table-sm">
<tr>
<th>
<?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>"/home/something",'text'=>"name"),$_smarty_tpl ) );?>
</th>
<th class="price">
<?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>"/home/something",'text'=>"price"),$_smarty_tpl ) );?>
</th>
<th>category</th>
</tr>
<?php
$_from = $_smarty_tpl->smarty->ext->_foreach->init($_smarty_tpl, $_smarty_tpl->tpl_vars['products']->value, 'product');
if ($_from !== null) {
foreach ($_from as $_smarty_tpl->tpl_vars['product']->value) {
?>
<tr>
<td>
<?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>"/cart/show/".((string)$_smarty_tpl->tpl_vars['product']->value->id),'text'=>((string)$_smarty_tpl->tpl_vars['product']->value->name)),$_smarty_tpl ) );?>
</td>
<td class="price">$<?php echo number_format($_smarty_tpl->tpl_vars['product']->value->price,2);?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['product']->value->category->name;?>
</td>
</tr>
<?php
}
}
$_smarty_tpl->smarty->ext->_foreach->restore($_smarty_tpl, 1);?>
</table>
<?php
}
}
/* {/block "content"} */
}
<file_sep>/fuel/app/config/parser.php
<?php
return [
'extensions' => [
'tpl' => 'View_Smarty',
],
'View_Smarty' => [
'extensions' => [
'MyExtensions',
],
],
];
<file_sep>/fuel/app/tasks/descriptions/ti-84-calc.html
Features:
<ul>
<li>16-character, 8-line display </li>
<li>480KB flash memory, 24KB RAM </li>
<li>Fully compatible with the TI-83 Plus </li>
<li>Use TI presentation tools (adapter sold separately) to connect
with the rest of the class </li>
<li>7 different graphing styles help to differentiate graphs drawn </li>
<li>Advanced statistics functions, including hypothesis testing and
calculation of confidence intervals </li>
<li>Complex number calculations </li>
<li>Financial functions, including time value of money, cash flow and amortization </li>
<li>USB (cable included) and unit-to-unit connectivity (cable included) </li>
<li>Powered by 4 AAA batteries (included) </li>
</ul>
<file_sep>/fuel/app/tasks/descriptions/toshiba-canvio-3.0-portable-usb-hard-drive.html
Features:
<ul>
<li> Fast, simple computer backups </li>
<li> USB 3.0 connectivity for blazing-fast data transfers. Provides transfer rates
up to 10 times faster than USB 2.0. Fully compatible with USB 2.0 systems. </li>
<li> Preloaded Windows-compatible software makes backup fast and simple. NTI Backup
Now EZTM software gives you useful backup options, letting you choose between
backing up to your Canvio portable hard drive, to the cloud, or to both
(cloud storage is especially useful if drive is ever lost or damaged). You can
back up specific files and folders, or back up everything stored on your computer. </li>
<li> Lets you easily recover lost files. Begin retrieving a file or folder by simply
clicking the restore button. Booting from the Canvio drive will restore to your
computer all your backed-up files. Also includes a utility to let you create a
bootable CD/DVD. </li>
<li> Encryption support for greater backup security. Password-protected data encryption
(up to 256-bit) helps keep your data safe from unauthorized access. </li>
<li> Drive Space Alert monitor lets you know when disk is getting full. </li>
</ul>
<file_sep>/fuel/app/classes/controller/admin.php
<?php
/**
* author: <NAME>
* class: csc 417 User Interfaces MW 5:45-7pm
*/
class Controller_admin extends Controller_Base {
/**
*
* description: this is the initial entry for creating a new category
*/
public function action_addCategory(){
$categories = Model_Category::find('all');
$data = [
'categories' => $categories,
'cat' => null
];
$validator = Validators::categoryValidator();
$view = View::forge("user/addcategory.tpl",$data);
$view->set_safe('validator', $validator);
return $view;
}
/**
*
* description: this function is for the reentrant of the add category page
*/
public function action_addCategoryReenterant(){
$cancel = Input::param('cancel');
if(!is_null($cancel)){
return Response::redirect("/");
}
$validator = Validators::categoryValidator();
$validated = $validator->run(Input::post());
if($validated){
$validData = $validator->validated();
$category = Model_Category::forge();
$category->name = $validData['cat'];
$category->save();
return Response::redirect("/");
}
$categories = Model_Category::find('all');
$data = [
'categories' => $categories,
'cat' => Input::param('cat')
];
$view = View::forge("user/addcategory.tpl",$data);
$view->set_safe('validator', $validator);
return $view;
}
/**
*
* description:this is the initial entry of the add product page
*/
public function action_addProduct(){
$category_recs = Model_Category::find('all');
$categories = [];
$photo_id = null;
foreach($category_recs as $rec) {
$categories[$rec->id] = $rec->name;
}
$photos_dir = "assets/img/products/";
$photoFiles = array_diff(scandir($photos_dir),[".",".."]);
foreach($photoFiles as $key => $value){
$product1 = Model_Product::find('first',['where' => ['photo_file' => $value]]);
if(!is_null($product1)){
unset($photoFiles[$key]);
}
}
$data = [
'categories' => $categories,
'photos' => $photoFiles,
'textarea' => null,
'name' => null,
'price' => null,
'photo_id' => null,
'category_id' => null
];
$validator = Validators::addProductValidator();
$view = View::forge("user/addproduct.tpl",$data);
$view->set_safe('validator', $validator);
return $view;
}
/**
*
* description: the reentrant action for adding a product
*/
public function action_addProductReenterant(){
$cancel = Input::param('cancel');
$add = Input::param('add');
$validator = Validators::addProductValidator();
$photos_dir = DOCROOT."assets/img/products/";
$photoFiles = array_diff(scandir($photos_dir),[".",".."]);
if(!is_null($cancel)){
return Response::redirect("/");
}
if(!is_null($add)){
$validated = $validator->run(Input::post());
if($validated){
$validData = $validator->validated();
$product = Model_Product::forge();
$product->name = $validData['name'];
$product->price = $validData['price'];
$product->description = $validData['textarea'];
$product->photo_file = $photoFiles[$validData['photo_id']];
$product->category_id = $validData['category_id'];
$product->save();
$prod_id = $product->id;
return Response::redirect("/cart/show/$prod_id");
}
}
$category_recs = Model_Category::find('all');
$categories = [];
$photo_id = null;
foreach($category_recs as $rec) {
$categories[$rec->id] = $rec->name;
}
foreach($photoFiles as $key => $value){
$product1 = Model_Product::find('first',['where' => ['photo_file' => $value]]);
if(!is_null($product1)){
unset($photoFiles[$key]);
}
}
$data = [
'categories' => $categories,
'photos' => $photoFiles,
'textarea' => Input::param('textarea'),
'name' => Input::param('name'),
'price' => Input::param('price'),
'photo_id' => Input::param('photo_id'),
'category_id' => Input::param('category_id')
];
$view = View::forge("user/addproduct.tpl",$data);
$view->set_safe('validator', $validator);
return $view;
}
}
<file_sep>/fuel/app/tmp/Smarty/templates_c/7219061e02d16985e3d58f748d732c89461b81b5_0.file.links.tpl.php
<?php
/* Smarty version 3.1.33, created on 2019-04-19 16:15:18
from 'C:\Users\copyp\OneDrive\Documents\NetBeansProjects\FuelStore_JRowan\fuel\app\views\links.tpl' */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.33',
'unifunc' => 'content_5cba2c564f2190_62129380',
'has_nocache_code' => false,
'file_dependency' =>
array (
'7219061e02d16985e3d58f748d732c89461b81b5' =>
array (
0 => 'C:\\Users\\copyp\\OneDrive\\Documents\\NetBeansProjects\\FuelStore_JRowan\\fuel\\app\\views\\links.tpl',
1 => 1555704854,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_5cba2c564f2190_62129380 (Smarty_Internal_Template $_smarty_tpl) {
if (!$_smarty_tpl->tpl_vars['session']->value->get('login') || !$_smarty_tpl->tpl_vars['session']->value->get('login')->is_admin) {?>
<li class="nav-link"><?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>"/cart",'text'=>"Cart"),$_smarty_tpl ) );?>
</li>
<?php }?>
<?php if ($_smarty_tpl->tpl_vars['session']->value->get('login') && !$_smarty_tpl->tpl_vars['session']->value->get('login')->is_admin) {?>
<li class="nav-link"><?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>'/user/myOrders','text'=>'My Orders'),$_smarty_tpl ) );?>
</li>
<?php }?>
<?php if ($_smarty_tpl->tpl_vars['session']->value->get('login') && $_smarty_tpl->tpl_vars['session']->value->get('login')->is_admin) {?>
<li class="nav-link"><?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>'/adminOrder/allOrders','text'=>'All Orders'),$_smarty_tpl ) );?>
</li>
<li class="nav-link"><?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>'/admin/addProduct','text'=>'Add Product'),$_smarty_tpl ) );?>
</li>
<li class="nav-link"><?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>'/admin/addCategory','text'=>'Add Category'),$_smarty_tpl ) );?>
</li>
<?php }?>
<?php if ($_smarty_tpl->tpl_vars['session']->value->get('login')) {?>
<li class="nav-link"><?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>'/authenticate/logout','text'=>'Logout'),$_smarty_tpl ) );?>
</li>
<?php } else { ?>
<li class="nav-link"><?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>'/authenticate/login','text'=>'Login'),$_smarty_tpl ) );?>
</li>
<li class="nav-link"><?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>'/newuser/createUser','text'=>'Create Account'),$_smarty_tpl ) );?>
</li>
<?php }?>
<?php }
}
<file_sep>/fuel/app/tasks/product_data.php
<?php
$product_data = [
/*
[
'name' => '',
'category' => '',
'price' => '',
'photo_file' => '',
'description_file' => '',
],
*/
[
'name' => 'Texas Instruments TI-84 Graphing Calculator',
'category' => 'calculator',
'price' => '109',
'photo_file' => 'ti-84-calc.jpg',
'description_file' => 'ti-84-calc.html',
],
[
'name' => 'Olympus WS-210S Digital Voice Recorder',
'category' => 'voice',
'price' => '52.9',
'photo_file' => 'olympus-ws-210s-voicerec.jpg',
'description_file' => 'olympus-ws-210s-voicerec.html',
],
[
'name' => 'Sony M470 Microcassette Recorder',
'category' => 'voice',
'price' => '29.95',
'photo_file' => 'sony-m470-macrorec.jpg',
'description_file' => 'sony-m470-macrorec.html',
],
[
'name' => 'Aluratek USB Internet Radio Jukebox',
'category' => 'video-audio',
'price' => '19.95',
'photo_file' => 'aluratek-usb-jukebox.jpg',
'description_file' => 'aluratek-usb-jukebox.html',
],
[
'name' => 'Netgear Wireless-N Gigabit Router',
'category' => 'network',
'price' => '99.9',
'photo_file' => 'netgear-n-gigrouter.jpg',
'description_file' => 'netgear-n-gigrouter.html',
],
[
'name' => 'Linksys Wireless-G Access Point',
'category' => 'network',
'price' => '79.9',
'photo_file' => 'linksys-wireless-g-ap.jpg',
'description_file' => 'linksys-wireless-g-ap.html',
],
[
'name' => 'Epson Stylus C88+ Inkjet Printer',
'category' => 'printer',
'price' => '111.95',
'photo_file' => 'epson-stylus-c88-printer.jpg',
'description_file' => 'epson-stylus-c88-printer.html',
],
[
'name' => 'HP 10bII+ Financial Calculator',
'category' => 'calculator',
'price' => '38.49',
'photo_file' => 'hp-10bII+-financial-calculator.jpg',
'description_file' => 'hp-10bII+-financial-calculator.html',
],
[
'name' => 'HP Officejet Pro 6100 ePrinter',
'category' => 'printer',
'price' => '99.99',
'photo_file' => 'hp-officejet-pro-6100-eprinter.jpg',
'description_file' => 'hp-officejet-pro-6100-eprinter.html',
],
[
'name' => 'VuPoint Magic Wand Portable Scanner',
'category' => 'copy-scan',
'price' => '69.99',
'photo_file' => 'vupoint-magic-wand-scanner.jpg',
'description_file' => 'vupoint-magic-wand-scanner.html',
],
[
'name' => 'Victor 12-Digit Executive Desktop Financial Calculator',
'category' => 'calculator',
'price' => '24.99',
'photo_file' => 'victor-executive-desktop-calculator.jpg',
'description_file' => 'victor-executive-desktop-calculator.html',
],
[
'name' => 'UltraTab Jazz C925 9" Tablet',
'category' => 'computer',
'price' => '99.99',
'photo_file' => 'ultratab-jazz-c925-9in-tablet.jpg',
'description_file' => 'ultratab-jazz-c925-9in-tablet.html',
],
[
'name' => 'Toshiba Canvio 3.0 Portable USB 3.0 Hard Drive 500GB',
'category' => 'storage',
'price' => '69.99',
'photo_file' => 'toshiba-canvio-3.0-portable-usb-hard-drive.jpg',
'description_file' => 'toshiba-canvio-3.0-portable-usb-hard-drive.html',
],
[
'name' => 'Seagate Backup Plus 500GB External USB 3.0 Portable Hard Drive',
'category' => 'storage',
'price' => '69.99',
'photo_file' => 'seagate-500gb-external-usb-hard-drive.jpg',
'description_file' => 'seagate-500gb-external-usb-hard-drive.html',
],
[
'name' => 'Cyber Acoustics CA-2880 USB-Powered Speaker',
'category' => 'video-audio',
'price' => '16.79',
'photo_file' => 'cyber-acoustics-2880-usb-speaker.jpg',
'description_file' => 'cyber-acoustics-2880-usb-speaker.html',
],
[
'name' => 'SanDisk Cruzer 8GB USB 2.0 Flash Drive',
'category' => 'storage',
'price' => '5.99',
'photo_file' => 'sandisk-cruzer-8gb-usb-flash-drive.jpg',
'description_file' => 'sandisk-cruzer-8gb-usb-flash-drive.html',
],
[
'name' => 'Samsung Smart Wi-Fi Built-In Blu-ray Player',
'category' => 'video-audio',
'price' => '89.99',
'photo_file' => 'samsung-smart-wi-fi-blu-ray-player.jpg',
'description_file' => 'samsung-smart-wi-fi-blu-ray-player.html',
],
];
/*
accessory | Allsop Monitor Stand Jr., Pewter | 22.29 | allsop-monitor-stand.jpg
video-audio | Ativa Mobil-IT Stereo Speaker Set | 19.99 | ativa-mobil-it-stereo-speaker-set.jpg
voice | AT&T TL7600 DECT 6.0 Digital Cordless Headset | 69.99 | att-tl7600-digital-cordless-headset.jpg
printer | Brother HL-2240 Monochrome Laser Printer | 79.99 | brother-hl-2240-laser-printer.jpg
voice | Sony Digital Voice Recorder | 49.99 | sony-digital-voice-recorder.jpg
calculator | Sharp EL-738C Financial Calculator | 29.99 | sharp-el-738c-financial-calculator.jpg
accessory | Safco Underdesk Printer/Fax Stand | 69.99 | safco-underdesk-printer-fax-stand.jpg
voice | Olympus Digital Voice Recorder | 39.99 | olympus-digital-voice-recorder.jpg
accessory | Fellowes Standard Monitor Riser | 19.99 | fellowes-standard-monitor-riser.jpg
storage | SanDisk microSDHCTM 16GB Memory Card | 44.99 | sandisk-micro-sdhctm-16gb-card.jpg
copy-scan | Canon Flatbed Color Image Scanner with Z-Lid Expansion Top | 54.98 | canon-flatbed-image-scanner-expansion-top.jpg
video-audio | Logitech Z130 2-Piece Speaker System | 31.99 | logitech-z130-speaker-system.jpg
computer | Logitech MK520 Wireless Keyboard and Mouse | 39.99 | logitech-mk520-wireless-keyboard-mouse.jpg
computer | HP W2072a 20" LED-Backlit LCD Monitor | 119.99 | hp-W2072a-20in-lcd-monitor.jpg
video-audio | SanDisk - Sansa Clip+ 4GB* MP3 Player | 29.99 | sandisk-sansa-clip-4gb-mp3-player.jpg
camera | Canon PowerShot A4000 IS 16.0-Megapixel Digital Camera | 109.99 | canon-powershot-a400-camera.jpg
camera | Sony DSCW650/B 16.1Megapixel Digital Camera | 79.99 | sony-dscw650-digital-camera.jpg
video-audio | Mach Speed Eclipse 180G2 Series 4GB* Video MP3 Player | 29.99 | mach-speed-eclipse-180gw-video-mp3-player.jpg
accessory | Targus APA31US 90-Watt AC Laptop Charger | 54.99 | targus-apa31US-laptop-charger.jpg
*/
<file_sep>/fuel/app/tmp/Smarty/templates_c/2c86c0905c6ee24ed47a699c974cbb4e22face6a_0.file.index.tpl.php
<?php
/* Smarty version 3.1.33, created on 2019-04-19 08:42:35
from 'C:\Users\copyp\OneDrive\Documents\NetBeansProjects\FuelStore_JRowan\fuel\app\views\cart\index.tpl' */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.33',
'unifunc' => 'content_5cb9c23be2e395_59007854',
'has_nocache_code' => false,
'file_dependency' =>
array (
'2c86c0905c6ee24ed47a699c974cbb4e22face6a' =>
array (
0 => 'C:\\Users\\copyp\\OneDrive\\Documents\\NetBeansProjects\\FuelStore_JRowan\\fuel\\app\\views\\cart\\index.tpl',
1 => 1555631874,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_5cb9c23be2e395_59007854 (Smarty_Internal_Template $_smarty_tpl) {
$_smarty_tpl->_loadInheritance();
$_smarty_tpl->inheritance->init($_smarty_tpl, true);
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_6689061955cb9c23be0e424_95641172', "content");
?>
<?php $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl");
}
/* {block "content"} */
class Block_6689061955cb9c23be0e424_95641172 extends Smarty_Internal_Block
{
public $subBlocks = array (
'content' =>
array (
0 => 'Block_6689061955cb9c23be0e424_95641172',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<h2>My Cart</h2>
<table class='table table-borderless table-sm'>
<tr>
<th>name</th>
<th>id</th>
<th>category</th>
<th>price</th>
<th>quantity</th>
<th>subtotal</th>
</tr>
<?php
$_from = $_smarty_tpl->smarty->ext->_foreach->init($_smarty_tpl, $_smarty_tpl->tpl_vars['cart_info']->value, 'data', false, 'product_id');
if ($_from !== null) {
foreach ($_from as $_smarty_tpl->tpl_vars['product_id']->value => $_smarty_tpl->tpl_vars['data']->value) {
?>
<tr>
<td>
<?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>"cart/show/".((string)$_smarty_tpl->tpl_vars['product_id']->value),'text'=>((string)$_smarty_tpl->tpl_vars['data']->value['name'])),$_smarty_tpl ) );?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['product_id']->value;?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['data']->value['category'];?>
</td>
<td>$<?php echo number_format($_smarty_tpl->tpl_vars['data']->value['price'],2);?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['data']->value['amount'];?>
</td>
<td>$<?php echo number_format($_smarty_tpl->tpl_vars['data']->value['subtotal'],2);?>
</td>
</tr>
<?php
}
}
$_smarty_tpl->smarty->ext->_foreach->restore($_smarty_tpl, 1);?>
<tr>
<th>Total: <b>$<?php echo sprintf("%.2f",$_smarty_tpl->tpl_vars['total_price']->value);?>
</b></th>
</tr>
</table>
<?php if ($_smarty_tpl->tpl_vars['session']->value->get('login') && $_smarty_tpl->tpl_vars['session']->value->get('cart')) {?>
<?php $_block_plugin1 = isset($_smarty_tpl->smarty->registered_plugins['block']['form'][0][0]) ? $_smarty_tpl->smarty->registered_plugins['block']['form'][0][0] : null;
if (!is_callable(array($_block_plugin1, 'form'))) {
throw new SmartyException('block tag \'form\' not callable or registered');
}
$_smarty_tpl->smarty->_cache['_tag_stack'][] = array('form', array('attrs'=>array('action'=>'/user/makeOrder','method'=>"GET")));
$_block_repeat=true;
echo $_block_plugin1->form(array('attrs'=>array('action'=>'/user/makeOrder','method'=>"GET")), null, $_smarty_tpl, $_block_repeat);
while ($_block_repeat) {
ob_start();?>
<button type='submit'>Make an Order from Cart</button>
<?php $_block_repeat=false;
echo $_block_plugin1->form(array('attrs'=>array('action'=>'/user/makeOrder','method'=>"GET")), ob_get_clean(), $_smarty_tpl, $_block_repeat);
}
array_pop($_smarty_tpl->smarty->_cache['_tag_stack']);?>
<?php }?>
<?php
}
}
/* {/block "content"} */
}
<file_sep>/fuel/app/tmp/Smarty/templates_c/025ee92f9a1a6ee3f0891a24283de9a14e82fcb8_0.file.addcategory.tpl.php
<?php
/* Smarty version 3.1.33, created on 2019-04-19 16:01:07
from 'C:\Users\copyp\OneDrive\Documents\NetBeansProjects\FuelStore_JRowan\fuel\app\views\user\addcategory.tpl' */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.33',
'unifunc' => 'content_5cba2903625328_69912368',
'has_nocache_code' => false,
'file_dependency' =>
array (
'025ee92f9a1a6ee3f0891a24283de9a14e82fcb8' =>
array (
0 => 'C:\\Users\\copyp\\OneDrive\\Documents\\NetBeansProjects\\FuelStore_JRowan\\fuel\\app\\views\\user\\addcategory.tpl',
1 => 1555704061,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_5cba2903625328_69912368 (Smarty_Internal_Template $_smarty_tpl) {
$_smarty_tpl->_loadInheritance();
$_smarty_tpl->inheritance->init($_smarty_tpl, true);
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_9352245005cba29035fc886_42171776', "localstyle");
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_4947180985cba29035fd7c4_57316976', "content");
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_5876284485cba2903624ba9_45013733', "localscript");
$_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl");
}
/* {block "localstyle"} */
class Block_9352245005cba29035fc886_42171776 extends Smarty_Internal_Block
{
public $subBlocks = array (
'localstyle' =>
array (
0 => 'Block_9352245005cba29035fc886_42171776',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<style type="text/css">
td:first-child, th:first-child {
width: 10px;
white-space: nowrap;
}
.error {
color: red; font-size: 80%; font-weight:bold;
}
</style>
<?php
}
}
/* {/block "localstyle"} */
/* {block "content"} */
class Block_4947180985cba29035fd7c4_57316976 extends Smarty_Internal_Block
{
public $subBlocks = array (
'content' =>
array (
0 => 'Block_4947180985cba29035fd7c4_57316976',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<h2>Add Category</h2>
<h5><b>Current Categories:</b></h5>
<ul>
<?php
$_from = $_smarty_tpl->smarty->ext->_foreach->init($_smarty_tpl, $_smarty_tpl->tpl_vars['categories']->value, 'category');
if ($_from !== null) {
foreach ($_from as $_smarty_tpl->tpl_vars['category']->value) {
?>
<li><?php echo $_smarty_tpl->tpl_vars['category']->value->name;?>
</li>
<?php
}
}
$_smarty_tpl->smarty->ext->_foreach->restore($_smarty_tpl, 1);?>
</ul>
<?php $_block_plugin1 = isset($_smarty_tpl->smarty->registered_plugins['block']['form'][0][0]) ? $_smarty_tpl->smarty->registered_plugins['block']['form'][0][0] : null;
if (!is_callable(array($_block_plugin1, 'form'))) {
throw new SmartyException('block tag \'form\' not callable or registered');
}
$_smarty_tpl->smarty->_cache['_tag_stack'][] = array('form', array('attrs'=>array('action'=>'/admin/addCategoryReenterant')));
$_block_repeat=true;
echo $_block_plugin1->form(array('attrs'=>array('action'=>'/admin/addCategoryReenterant')), null, $_smarty_tpl, $_block_repeat);
while ($_block_repeat) {
ob_start();?>
<table class="table table-sm table-borderless">
<tr>
<th>category name:</th>
<td><input class="form-control" type="text" name="cat" value="<?php echo $_smarty_tpl->tpl_vars['cat']->value;?>
" required />
<span class="error"><?php echo $_smarty_tpl->tpl_vars['validator']->value->error_message('cat');?>
</span></td>
</tr>
<tr>
<td></td>
<td>
<button type="submit" name="add">Add</button>
<button type="submit" name="cancel">Cancel</button>
</td>
</tr>
</table>
<?php $_block_repeat=false;
echo $_block_plugin1->form(array('attrs'=>array('action'=>'/admin/addCategoryReenterant')), ob_get_clean(), $_smarty_tpl, $_block_repeat);
}
array_pop($_smarty_tpl->smarty->_cache['_tag_stack']);?>
<h4 class="message"><?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['session_get_flash'][0], array( array('var'=>'message'),$_smarty_tpl ) );?>
</h4>
<?php
}
}
/* {/block "content"} */
/* {block "localscript"} */
class Block_5876284485cba2903624ba9_45013733 extends Smarty_Internal_Block
{
public $subBlocks = array (
'localscript' =>
array (
0 => 'Block_5876284485cba2903624ba9_45013733',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<?php echo '<script'; ?>
type="text/javascript">
$("button[name='cancel']").click(function () {
$("input[name='cat']").prop('disabled', true);
});
<?php echo '</script'; ?>
>
<?php
}
}
/* {/block "localscript"} */
}
<file_sep>/fuel/app/tasks/descriptions/hp-officejet-pro-6100-eprinter.html
Features:
<ul>
<li> ePrint technology lets you print from anywhere with your mobile device </li>
<li> Stay productive on the go with HP ePrint! </li>
<li> Print professional color documents for a low cost per page. </li>
<li> Prints up to 16 pages per minute in black, 9 in color (ISO standard). </li>
<li> Built-in wireless (and wired) connectivity lets you share with multiple computers.
250-sheet paper tray can handle your larger, more complex print jobs. </li>
<li> Energy STAR® qualified. </li>
</ul>
<file_sep>/fuel/app/classes/validators.php
<?php
class Validators {
/**
*
* @return type validator
* description: this function returns a category validator
*/
public static function categoryValidator(){
$validator = Validation::forge();
$isUnique = function($title) {
$bookWithTitle = Model_Category::find('first', [
'where' => [
[ 'name', $title ]
]
]);
return is_null($bookWithTitle);
};
$validator->add('cat', 'cat')
->add_rule('trim')
->add_rule('required')
->add_rule(['unique' => $isUnique])
;
return $validator;
}
/**
*
* description: this function returns a validator for the add product page
*/
public static function addProductValidator(){
require_once PKGPATH . "htmLawed.php";
$check_valid_html = function($text) {
$out_text = htmLawed($text);
return ($out_text === $text);
};
$isUnique = function($title) {
$bookWithTitle = Model_Product::find('first', [
'where' => [
[ 'name', $title ]
]
]);
return is_null($bookWithTitle);
};
$validator = Validation::forge();
$validator->add('name', 'name') // field, label
->add_rule('trim')
->add_rule('required')
->add_rule('min_length', 3)
->add_rule(['unique' => $isUnique])
;
$validator->add('textarea', 'textarea')
->add_rule(['valid_html' => $check_valid_html])
;
$validator->add('price','price');
$validator->add('photo_id','photo_id');
$validator->add('category_id','category_id');
$validator
->set_message('valid_html', 'html is invalid')
;
return $validator;
}
/**
*
* description: this returns a validator for validating the modify product fields
*/
public static function modifyProductValidator() {
require_once PKGPATH . "htmLawed.php";
$check_valid_html = function($text) {
$out_text = htmLawed($text);
return ($out_text === $text);
};
$validator = Validation::forge();
$validator->add('textarea', 'textarea')
->add_rule(['valid_html' => $check_valid_html])
;
$validator
->set_message('valid_html', 'html is invalid')
;
$validator->add('category_id','category_id');
$validator->add('price','price');
$validator->add('photo_id','photo_id');
$validator->add('id','id');
$validator->add('add','add');
$validator->add('cancel','cancel');
return $validator;
}
/**
*
* description: this function returns a validator for the form in creating a user
*/
public static function userValidator(){
$validator = Validation::forge();
$isUnique = function($title) {
$bookWithTitle = Model_User::find('first', [
'where' => [
[ 'name', $title ]
]
]);
return is_null($bookWithTitle);
};
$validator->add('username', 'username') // field, label
->add_rule('trim')
->add_rule('required')
->add_rule(['unique' => $isUnique])
->add_rule('min_length', 3)
;
$validator->add('password', '<PASSWORD>')
->add_rule('trim')
->add_rule('required')
->add_rule('min_length', 3)
;
$validator->add('confirmpassword', '<PASSWORD>assword')
->add_rule('required')
->add_rule('match_field', 'password') // nust match the pwd field
;
$validator->add('email','email');
$validator->add('create','create');
$validator->add('cancel','cancel');
return $validator;
}
}
<file_sep>/fuel/app/classes/controller/adminorder.php
<?php
/**
* author: <NAME>
* class: csc 417 User Interfaces MW 5:45-7pm
*/
class Controller_adminOrder extends Controller_Base {
/**
*
* description: this is the initial entry for the all orders page
*/
public function action_allOrders(){
$orders = Model_Order::find('all');
$data = [
'orders' => $orders
];
return View::forge('user/allorders.tpl', $data);
}
/**
*
* description: this is the reenterant function for modify product
*/
public function action_modify(){
$validator = Validators::modifyProductValidator();
$add = Input::param('add');
$cancel = Input::param('cancel');
if(!is_null($cancel)){
return Response::redirect("/");
}
if(!is_null($add)){
$validated = $validator->run(Input::post());
if ($validated) {
$validData = $validator->validated();
$id = $validData['id'];//Input::param('id');
$product = Model_Product::find($id);
$category_id = $validData['category_id'];//Input::param('category_id');
$price = $validData['price'];//Input::param('price');
$textarea = $validData['textarea'];//Input::param('textarea');
$photos_dir = DOCROOT."assets/img/products/";
$photoFiles = array_diff(scandir($photos_dir),[".",".."]);
$photo_id = $validData['photo_id'];//Input::param('photo_id');
$product->price = $price;
$product->description = $textarea;
$product->photo_file = $photoFiles[$photo_id];
$product->category_id = $category_id;
$product->save();
return Response::redirect("/cart/show/$id");
}
}
$id = Input::param('id');
$product = Model_Product::find($id);
$name = $product->name;
$category_id = Input::param('category_id');
$price = Input::param('price');
$textarea = Input::param('textarea');
$category_recs = Model_Category::find('all');
$categories = [];
$photo_id = null;
foreach($category_recs as $rec) {
$categories[$rec->id] = $rec->name;
}
$photos_dir = DOCROOT."assets/img/products/";
$photoFiles = array_diff(scandir($photos_dir),[".",".."]);
foreach($photoFiles as $key => $value){
$product1 = Model_Product::find('first',['where' => ['photo_file' => $value]]);
if(!is_null($product1)){
if(!($product->photo_file == $value)){
unset($photoFiles[$key]);
}else{
$photo_id = $key;
}
}else{
if(is_null($photo_id) && $product->photo_file == $value){
$photo_id = $key;
}
}
}
$photo_id = Input::param('photo_id');
$data = [
'id' => $id,
'categories' => $categories,
'name' => $product->name,
'category_id' => $category_id,
'price' => $price,
'textarea' => $textarea,
'photo_id' => $photo_id,
'photos' => $photoFiles
//'selected_photo' => $selectedPhoto
];
$view = View::forge('user/modifyproduct.tpl', $data);
$view->set_safe('validator', $validator);
return $view;
}
/**
*
* description: this is the initial entry for modify product
*/
public function action_modifyProduct(){
$validator = Validators::modifyProductValidator();
$id = Input::param('id');
$product = Model_Product::find($id);
$category_id = $product->category_id;
$category_recs = Model_Category::find('all');
$categories = [];
$photo_id = null;
foreach($category_recs as $rec) {
if(is_null($category_id)){
$category_id = $product->category_id;
}
$categories[$rec->id] = $rec->name;
}
$textarea = $product->description;
$price = $product->price;
$photos_dir = DOCROOT."assets/img/products/";
$photoFiles = array_diff(scandir($photos_dir),[".",".."]);
//return var_dump($photoFiles);
foreach($photoFiles as $key => $value){
$product1 = Model_Product::find('first',['where' => ['photo_file' => $value]]);
if(!is_null($product1)){
if(!($product->photo_file == $value)){
unset($photoFiles[$key]);
}else{
$photo_id = $key;
}
}else{
if(is_null($photo_id) && $product->photo_file == $value){
$photo_id = $key;
}
}
}
$data = [
'id' => $id,
'categories' => $categories,
'name' => $product->name,
'category_id' => $category_id,
'price' => $price,
'textarea' => $textarea,
'photo_id' => $photo_id,
'photos' => $photoFiles
//'selected_photo' => $selectedPhoto
];
$view = View::forge('user/modifyproduct.tpl', $data);
$view->set_safe('validator', $validator);
return $view;
}
}
<file_sep>/fuel/app/tmp/Smarty/templates_c/e8deffb66b0fa0b7dbbf3ed0bf4029ee2ca5577e_0.file.layout.tpl.php
<?php
/* Smarty version 3.1.33, created on 2019-04-18 20:01:42
from 'C:\Users\copyp\OneDrive\Documents\NetBeansProjects\FuelStore\fuel\app\views\layout.tpl' */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.33',
'unifunc' => 'content_5cb90fe63e7043_36068724',
'has_nocache_code' => false,
'file_dependency' =>
array (
'e8deffb66b0fa0b7dbbf3ed0bf4029ee2ca5577e' =>
array (
0 => 'C:\\Users\\copyp\\OneDrive\\Documents\\NetBeansProjects\\FuelStore\\fuel\\app\\views\\layout.tpl',
1 => 1555631874,
2 => 'file',
),
),
'includes' =>
array (
'file:links.tpl' => 1,
),
),false)) {
function content_5cb90fe63e7043_36068724 (Smarty_Internal_Template $_smarty_tpl) {
$_smarty_tpl->_loadInheritance();
$_smarty_tpl->inheritance->init($_smarty_tpl, false);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>
<?php ob_start();
echo basename(dirname(call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['base_url'][0], array( array(),$_smarty_tpl ) )));
$_prefixVariable1 = ob_get_clean();
echo (($tmp = @$_smarty_tpl->tpl_vars['page_title']->value)===null||$tmp==='' ? $_prefixVariable1 : $tmp);?>
</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
crossorigin="anonymous" />
<?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['asset_css'][0], array( array('refs'=>array("layout.css")),$_smarty_tpl ) );?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_15244376755cb90fe6334d26_52150509', "localstyle");
?>
<?php echo '<script'; ?>
type="text/javascript">
// for Safari browser, deal with back button
window.onpageshow = function (event) {
if (event.persisted) {
window.location.reload();
}
};
<?php echo '</script'; ?>
>
</head>
<body>
<header>
<div>
<?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['asset_img'][0], array( array('refs'=>"header.png",'attrs'=>array('class'=>'img-responsive')),$_smarty_tpl ) );?>
<span class='login'><?php echo (($tmp = @$_smarty_tpl->tpl_vars['session']->value->get('login')->name)===null||$tmp==='' ? '' : $tmp);?>
</span>
</div>
<nav class="navbar navbar-dark bg-info navbar-expand-sm">
<?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>'/','text'=>'Home','attrs'=>array('class'=>"navbar-brand")),$_smarty_tpl ) );?>
<button class="navbar-toggler navbar-toggler-icon" type="button"
data-toggle="collapse" data-target="#navbar1">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbar1">
<ul class="navbar-nav mr-auto">
<?php $_smarty_tpl->_subTemplateRender('file:links.tpl', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false);
?>
</ul>
</div>
</nav>
</header>
<section class="container-fluid"><?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_7630276695cb90fe63e5db6_18602596', "content");
?>
</section>
<?php echo '<script'; ?>
src="https://code.jquery.com/jquery-1.12.4.min.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"><?php echo '</script'; ?>
>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_16672131165cb90fe63e68d4_21877258', "localscript");
?>
</body>
</html>
<?php }
/* {block "localstyle"} */
class Block_15244376755cb90fe6334d26_52150509 extends Smarty_Internal_Block
{
public $subBlocks = array (
'localstyle' =>
array (
0 => 'Block_15244376755cb90fe6334d26_52150509',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
}
}
/* {/block "localstyle"} */
/* {block "content"} */
class Block_7630276695cb90fe63e5db6_18602596 extends Smarty_Internal_Block
{
public $subBlocks = array (
'content' =>
array (
0 => 'Block_7630276695cb90fe63e5db6_18602596',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
}
}
/* {/block "content"} */
/* {block "localscript"} */
class Block_16672131165cb90fe63e68d4_21877258 extends Smarty_Internal_Block
{
public $subBlocks = array (
'localscript' =>
array (
0 => 'Block_16672131165cb90fe63e68d4_21877258',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
}
}
/* {/block "localscript"} */
}
<file_sep>/fuel/app/tmp/Smarty/templates_c/3ebc0ee83dd8fcd6080534161b4121fa04732e6a_0.file.modifyproduct.tpl.php
<?php
/* Smarty version 3.1.33, created on 2019-04-19 13:01:43
from 'C:\Users\copyp\OneDrive\Documents\NetBeansProjects\FuelStore_JRowan\fuel\app\views\user\modifyproduct.tpl' */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.33',
'unifunc' => 'content_5cb9fef79c7056_44789123',
'has_nocache_code' => false,
'file_dependency' =>
array (
'3ebc0ee83dd8fcd6080534161b4121fa04732e6a' =>
array (
0 => 'C:\\Users\\copyp\\OneDrive\\Documents\\NetBeansProjects\\FuelStore_JRowan\\fuel\\app\\views\\user\\modifyproduct.tpl',
1 => 1555693296,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_5cb9fef79c7056_44789123 (Smarty_Internal_Template $_smarty_tpl) {
$_smarty_tpl->_loadInheritance();
$_smarty_tpl->inheritance->init($_smarty_tpl, true);
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_17344595885cb9fef79afb24_59304766', "localstyle");
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_4658201115cb9fef79b09a0_77199348', "content");
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_9467898775cb9fef79c68f5_40438455', "localscript");
$_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl");
}
/* {block "localstyle"} */
class Block_17344595885cb9fef79afb24_59304766 extends Smarty_Internal_Block
{
public $subBlocks = array (
'localstyle' =>
array (
0 => 'Block_17344595885cb9fef79afb24_59304766',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<style type="text/css">
td:first-child, th:first-child {
width: 10px;
white-space: nowrap;
}
.error {
color: red; font-size: 80%; font-weight:bold;
}
</style>
<?php
}
}
/* {/block "localstyle"} */
/* {block "content"} */
class Block_4658201115cb9fef79b09a0_77199348 extends Smarty_Internal_Block
{
public $subBlocks = array (
'content' =>
array (
0 => 'Block_4658201115cb9fef79b09a0_77199348',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
$_smarty_tpl->_checkPlugins(array(0=>array('file'=>'C:\\Users\\copyp\\OneDrive\\Documents\\NetBeansProjects\\FuelStore_JRowan\\fuel\\vendor\\smarty\\smarty\\libs\\plugins\\function.html_options.php','function'=>'smarty_function_html_options',),));
?>
<h2>Modify Product</h2>
<?php $_block_plugin1 = isset($_smarty_tpl->smarty->registered_plugins['block']['form'][0][0]) ? $_smarty_tpl->smarty->registered_plugins['block']['form'][0][0] : null;
if (!is_callable(array($_block_plugin1, 'form'))) {
throw new SmartyException('block tag \'form\' not callable or registered');
}
$_smarty_tpl->smarty->_cache['_tag_stack'][] = array('form', array('attrs'=>array('action'=>'adminOrder/modify')));
$_block_repeat=true;
echo $_block_plugin1->form(array('attrs'=>array('action'=>'adminOrder/modify')), null, $_smarty_tpl, $_block_repeat);
while ($_block_repeat) {
ob_start();?>
<input type="hidden" name='id' value='<?php echo $_smarty_tpl->tpl_vars['id']->value;?>
' />
<table class="table table-sm table-borderless">
<tr>
<th>name:</th>
<td><?php echo $_smarty_tpl->tpl_vars['name']->value;?>
</td>
</tr>
<tr>
<th>category:</th>
<td>
<select name="category_id">
<?php echo smarty_function_html_options(array('options'=>$_smarty_tpl->tpl_vars['categories']->value,'selected'=>$_smarty_tpl->tpl_vars['category_id']->value),$_smarty_tpl);?>
</select>
</td>
</tr>
<tr>
<th>price ($):</th>
<td><input class="form-control" type="number" name="price" min="0.00" step="0.01" value='<?php echo $_smarty_tpl->tpl_vars['price']->value;?>
' required /></td>
</tr>
<tr>
<th>desctiption:</th>
<td><textarea class="form-control" name='textarea' rows='10' ><?php echo $_smarty_tpl->tpl_vars['textarea']->value;?>
</textarea>
<span class="error"><?php echo $_smarty_tpl->tpl_vars['validator']->value->error_message('textarea');?>
</span></td>
</tr>
<tr>
<th>photo:</th>
<td>
<select name="photo_id">
<?php echo smarty_function_html_options(array('options'=>$_smarty_tpl->tpl_vars['photos']->value,'selected'=>$_smarty_tpl->tpl_vars['photo_id']->value),$_smarty_tpl);?>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<button type="submit" name="add">Modify</button>
<button type="submit" name="cancel">Cancel</button>
</td>
</tr>
</table>
<?php $_block_repeat=false;
echo $_block_plugin1->form(array('attrs'=>array('action'=>'adminOrder/modify')), ob_get_clean(), $_smarty_tpl, $_block_repeat);
}
array_pop($_smarty_tpl->smarty->_cache['_tag_stack']);?>
<h4 class="message"><?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['session_get_flash'][0], array( array('var'=>'message'),$_smarty_tpl ) );?>
</h4>
<?php
}
}
/* {/block "content"} */
/* {block "localscript"} */
class Block_9467898775cb9fef79c68f5_40438455 extends Smarty_Internal_Block
{
public $subBlocks = array (
'localscript' =>
array (
0 => 'Block_9467898775cb9fef79c68f5_40438455',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<?php echo '<script'; ?>
type="text/javascript">
$("button[name='cancel']").click(function () {
$("input[name='name']").prop('disabled', true);
$("input[name='price']").prop('disabled', true);
$("input[name='textarea']").prop('disabled', true);
});
<?php echo '</script'; ?>
>
<?php
}
}
/* {/block "localscript"} */
}
<file_sep>/fuel/app/tmp/Smarty/templates_c/1ca3e2e28ce05ab46672ac810c79a954a38557f7_0.file.orderdetails.tpl.php
<?php
/* Smarty version 3.1.33, created on 2019-04-19 11:06:09
from 'C:\Users\copyp\OneDrive\Documents\NetBeansProjects\FuelStore_JRowan\fuel\app\views\user\orderdetails.tpl' */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.33',
'unifunc' => 'content_5cb9e3e1047e08_84907753',
'has_nocache_code' => false,
'file_dependency' =>
array (
'1ca3e2e28ce05ab46672ac810c79a954a38557f7' =>
array (
0 => 'C:\\Users\\copyp\\OneDrive\\Documents\\NetBeansProjects\\FuelStore_JRowan\\fuel\\app\\views\\user\\orderdetails.tpl',
1 => 1555686365,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_5cb9e3e1047e08_84907753 (Smarty_Internal_Template $_smarty_tpl) {
$_smarty_tpl->_loadInheritance();
$_smarty_tpl->inheritance->init($_smarty_tpl, true);
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_7745073265cb9e3e10163a2_11535335', "localstyle");
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_1338259795cb9e3e1017a75_76370105', "content");
$_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl");
}
/* {block "localstyle"} */
class Block_7745073265cb9e3e10163a2_11535335 extends Smarty_Internal_Block
{
public $subBlocks = array (
'localstyle' =>
array (
0 => 'Block_7745073265cb9e3e10163a2_11535335',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<style>
</style>
<?php
}
}
/* {/block "localstyle"} */
/* {block "content"} */
class Block_1338259795cb9e3e1017a75_76370105 extends Smarty_Internal_Block
{
public $subBlocks = array (
'content' =>
array (
0 => 'Block_1338259795cb9e3e1017a75_76370105',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<h2>Order #<?php echo $_smarty_tpl->tpl_vars['order']->value->id;?>
</h2>
<?php if ($_smarty_tpl->tpl_vars['session']->value->get('login') && $_smarty_tpl->tpl_vars['session']->value->get('login')->is_admin) {?>
<pre>
User: <?php echo $_smarty_tpl->tpl_vars['order']->value->user->name;?>
Email: <?php echo $_smarty_tpl->tpl_vars['order']->value->user->email;?>
</pre>
<?php }?>
<table class="table table-hover table-sm">
<tr>
<th>product name</th>
<th>id</th>
<th>category</th>
<th>purchase price</th>
<th>quantity</th>
<th>subtotal</th>
</tr>
<?php
$_from = $_smarty_tpl->smarty->ext->_foreach->init($_smarty_tpl, $_smarty_tpl->tpl_vars['order']->value->selections, 'info');
if ($_from !== null) {
foreach ($_from as $_smarty_tpl->tpl_vars['info']->value) {
?>
<tr>
<td><?php echo $_smarty_tpl->tpl_vars['info']->value->product->name;?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['info']->value->product->id;?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['info']->value->product->category->name;?>
</td>
<td class="price">$<?php echo number_format($_smarty_tpl->tpl_vars['info']->value->purchase_price,2);?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['info']->value->quantity;?>
</td>
<td>$<?php echo number_format($_smarty_tpl->tpl_vars['info']->value->purchase_price*$_smarty_tpl->tpl_vars['info']->value->quantity,2);?>
</td>
</tr>
<?php
}
}
$_smarty_tpl->smarty->ext->_foreach->restore($_smarty_tpl, 1);?>
</table>
<pre>
<b>Total = $<?php echo number_format($_smarty_tpl->tpl_vars['total_price']->value,2);?>
</b>
</pre>
<?php if ($_smarty_tpl->tpl_vars['session']->value->get('login') && $_smarty_tpl->tpl_vars['session']->value->get('login')->is_admin) {?>
<?php ob_start();
echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['session_get_flash'][0], array( array('var'=>'confirm'),$_smarty_tpl ) );
$_prefixVariable1 = ob_get_clean();
if ($_prefixVariable1) {?>
<?php $_block_plugin1 = isset($_smarty_tpl->smarty->registered_plugins['block']['form'][0][0]) ? $_smarty_tpl->smarty->registered_plugins['block']['form'][0][0] : null;
if (!is_callable(array($_block_plugin1, 'form'))) {
throw new SmartyException('block tag \'form\' not callable or registered');
}
$_smarty_tpl->smarty->_cache['_tag_stack'][] = array('form', array('attrs'=>array('action'=>'user/deleteOrder')));
$_block_repeat=true;
echo $_block_plugin1->form(array('attrs'=>array('action'=>'user/deleteOrder')), null, $_smarty_tpl, $_block_repeat);
while ($_block_repeat) {
ob_start();?>
<input type="hidden" name="idhid" value=<?php echo $_smarty_tpl->tpl_vars['order']->value->id;?>
/>
<input type='hidden' name='confirm' value='confirm' />
<button type="submit" >Process</button>
<button type="submit" name="cancel">Cancel</button>
<h4 class="message"><?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['session_get_flash'][0], array( array('var'=>'message'),$_smarty_tpl ) );?>
</h4>
<?php $_block_repeat=false;
echo $_block_plugin1->form(array('attrs'=>array('action'=>'user/deleteOrder')), ob_get_clean(), $_smarty_tpl, $_block_repeat);
}
array_pop($_smarty_tpl->smarty->_cache['_tag_stack']);?>
<?php } else { ?>
<?php $_block_plugin2 = isset($_smarty_tpl->smarty->registered_plugins['block']['form'][0][0]) ? $_smarty_tpl->smarty->registered_plugins['block']['form'][0][0] : null;
if (!is_callable(array($_block_plugin2, 'form'))) {
throw new SmartyException('block tag \'form\' not callable or registered');
}
$_smarty_tpl->smarty->_cache['_tag_stack'][] = array('form', array('attrs'=>array('action'=>'user/deleteOrder')));
$_block_repeat=true;
echo $_block_plugin2->form(array('attrs'=>array('action'=>'user/deleteOrder')), null, $_smarty_tpl, $_block_repeat);
while ($_block_repeat) {
ob_start();?>
<input type="hidden" name="idhid" value=<?php echo $_smarty_tpl->tpl_vars['order']->value->id;?>
/>
<button type="submit" >Process</button>
<h4 class="message"><?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['session_get_flash'][0], array( array('var'=>'message'),$_smarty_tpl ) );?>
</h4>
<?php $_block_repeat=false;
echo $_block_plugin2->form(array('attrs'=>array('action'=>'user/deleteOrder')), ob_get_clean(), $_smarty_tpl, $_block_repeat);
}
array_pop($_smarty_tpl->smarty->_cache['_tag_stack']);?>
<?php }?>
<?php }?>
<?php
}
}
/* {/block "content"} */
}
<file_sep>/fuel/app/tasks/tables/product-sqlite.sql
create table `product` (
id integer primary key not null,
name text unique not null collate nocase,
description text not null,
price real not null,
category_id integer not null,
photo_file text not null collate nocase,
foreign key(category_id) references category(id)
);
<file_sep>/fuel/app/classes/controller/user.php
<?php
/**
* author: <NAME>
* class: csc 417 User Interfaces MW 5:45-7pm
*/
class Controller_User extends Controller_Base {
/**
*
* description: this is the initial entry for my orders
*/
public function action_myOrders(){
$login = Session::get('login');
$user_id = $login->id;
$orders = Model_Order::find('all',['where' => ['user_id' => $user_id]]);
$data = [
'orders' => $orders
];
return View::forge('user/myorders.tpl', $data);
}
/**
*
* @param type $order_id : id of order
* description: this is an action to take the user to order details
*/
public function action_orderDetails($order_id){
$order = Model_Order::find($order_id);
$selections = $order->selections;
$total_price = 0;
foreach($selections as $select){
$total_price += $select->quantity * $select->purchase_price;
}
$data = [
'order' => $order,
'total_price' => $total_price
];
return View::forge('user/orderdetails.tpl', $data);
}
/**
*
* description: called when admin user clickes process order
*/
public function action_deleteOrder(){
$id = Input::param('idhid');
$order = Model_Order::find($id);
$confirm = Input::param('confirm');
$cancel = Input::param('cancel');
if(!is_null($cancel)){
return Response::redirect("/adminOrder/allOrders");
exit();
}
if(!is_null($confirm)){
foreach($order->selections as $sel){
$sel->delete();
}
$order->delete();
Session::set_flash('message', "Order $id Successfully Processed");
return Response::redirect("/adminOrder/allOrders");
}else{
Session::set_flash('message', 'Press Process again');
Session::set_flash('confirm', 'confirm');
return Response::redirect("/user/orderDetails/$id");
}
$selections = $order->selections;
$total_price = 0;
foreach($selections as $select){
$total_price += $select->quantity * $select->purchase_price;
}
$data = [
'order' => $order,
'total_price' => $total_price
];
return View::forge('user/orderdetails.tpl', $data);
}
/**
*
* description: this action is called when the user makes and order from cart
*/
public function action_makeOrder(){
$user_id = Session::get('login')->id;
$date = date("Y-m-d H:i:s", time());
$order = Model_Order::forge();
$order->user_id = $user_id;
$order->created_at = $date;
$order->save();
$order_id = $order->id;
$cart = Session::get('cart');
foreach($cart as $key => $value){
$product = Model_Product::find($key);
$selection = Model_Selection::forge();
$selection->product_id = $product->id;
$selection->order_id = $order_id;
$selection->quantity = $value;
$selection->purchase_price = $product->price;
$selection->save();
}
//unset($cart);
//Session::set('cart',$cart);
Session::delete('cart');
return Response::redirect("/user/myOrders");
}
}
<file_sep>/fuel/app/classes/model/order.php
<?php
class Model_Order extends \Orm\Model {
protected static $_table_name = 'order';
protected static $_properties = [
'id',
'user_id',
'created_at',
];
// use $order->products to get the products of the order
protected static $_many_many = [
'products' => [
'model_to' => 'Model_Product',
'table_through' => 'selection',
],
];
// use $order->user to get the user of the order
protected static $_belongs_to = [
'user' => [
'model_to' => 'Model_User',
]
];
// use $order->selections to get the selections
// the cascade_delete is there to prevent an error message
// on deleting the selections of an order
protected static $_has_many = [
'selections' => [
'model_to' => 'Model_Selection',
'cascade_delete'=> true,
]
];
// sets the created_at field to current timestamp, unless set manually
protected static $_observers = [
'Orm\Observer_CreatedAt' => [
'events' => ['before_insert'],
'mysql_timestamp' => true,
'property' => 'created_at',
'overwrite' => false,
],
];
}
<file_sep>/fuel/app/tasks/populatetables.php
<?php
namespace Fuel\Tasks;
use Model_Category;
use Model_Order;
use Model_User;
use Model_Selection;
use Model_Product;
use Exception;
class PopulateTables {
public static function run() {
echo "\n---- users\n";
$user_data = [
["john", "<EMAIL>", "john"],
["kirsten", "<EMAIL>", "kirsten"],
["bill", "<EMAIL>", "bill"],
["mary", "<EMAIL>", "mary"],
["joan", "<EMAIL>", "joan"],
["alice", "<EMAIL>", "alice"],
["carla", "<EMAIL>", "carla"],
["dave", "<EMAIL>", "dave"],
];
foreach ($user_data as $data) {
list($name, $email, $password) = $data;
$user = Model_User::forge();
$user->name = $name;
$user->email = $email;
$user->password = hash('sha256', $password);
$user->save();
echo "user $user->id: $name\n";
}
echo "\n---- admins\n";
foreach (['dave', 'carla'] as $name) {
$user = Model_User::find('first', [
'where' => ['name' => $name],
]);
$user->is_admin = true;
$user->save();
echo "admin: $name\n";
}
require_once __DIR__ . "/product_data.php";
echo "\n---- categories\n";
$category_names = [];
foreach ($product_data as $data) {
$category_names[$data['category']] = 1;
}
foreach (array_keys($category_names) as $name) {
$category = Model_Category::forge();
$category->name = $name;
$category->save();
echo "$category->id: $name\n";
}
$photos_dir = DOCROOT . "public/assets/img/products";
$descriptions_dir = __DIR__ . "/descriptions";
echo "\n---- products\n\n";
$products = [];
foreach ($product_data as $data) {
$name = $data['name'];
$category_name = $data['category'];
$price = $data['price'];
$photo_file = $data['photo_file'];
$description_file = $data['description_file'];
//$category = R::findOne('category', 'name = ?', [$category_name]);
$category = Model_Category::find('first', [
'where' => [['name', $category_name]],
]);
echo "product name: $name\n";
$file = "$photos_dir/$photo_file";
if (!file_exists($file)) {
throw new Exception("missing photo file: $file");
}
$file = "$descriptions_dir/$description_file";
if (file_exists($file)) {
$description = file_get_contents($file);
}
else {
echo "---- missing description, set to empty\n";
$description = "";
}
$product = Model_Product::forge();
$product->photo_file = $photo_file;
$product->name = $name;
$product->category_id = $category->id;
$product->price = $price;
$product->description = $description;
$product->save();
echo "---- product added with id: $product->id\n";
$products[$product->id] = $product;
}
echo "\n---- orders\n";
define("SECONDS_PER_DAY", 3600 * 24);
function randTimeNdaysPast($days) {
$timestamp = time() - $days * SECONDS_PER_DAY + rand(0, SECONDS_PER_DAY);
return date("Y-m-d H:i:s", $timestamp);
}
function makeOrder($user, $ndays, $productQuant) {
$order = Model_Order::forge();
$order->user_id = $user->id;
$order->created_at = randTimeNdaysPast($ndays);
$order->save();
echo "\nby $user->name on $order->created_at\n";
foreach ($productQuant as $arr) {
list($product, $quantity) = $arr;
echo " #$product->id: $product->name ($quantity)\n";
$item = Model_Selection::forge();
$item->order = $order;
$item->product = $product;
$item->quantity = $quantity;
$item->purchase_price = $product->price;
$item->save();
}
}
$alice = Model_User::find('first', [
'where' => [['name', 'alice']],
]);
$john = Model_User::find('first', [
'where' => [['name', 'john']],
]);
$bill = Model_User::find('first', [
'where' => [['name', 'bill']],
]);
$ndays = 7;
makeOrder($alice, $ndays--, [
[$products[1], 2],
[$products[5], 3],
]);
makeOrder($alice, $ndays--, [
[$products[12], 1],
[$products[8], 4],
]);
makeOrder($bill, $ndays--, [
[$products[2], 5],
[$products[6], 2],
]);
makeOrder($alice, $ndays--, [
[$products[3], 3],
[$products[11], 1],
]);
makeOrder($bill, $ndays--, [
[$products[1], 3],
[$products[3], 3],
[$products[5], 1],
[$products[6], 2],
]);
}
}
<file_sep>/fuel/app/tasks/tables/order-sqlite.sql
create table `order` (
id integer primary key not null,
user_id integer not null,
created_at datetime not null,
foreign key(user_id) references user(id)
);
<file_sep>/fuel/app/tasks/descriptions/sony-m470-macrorec.html
Features:
<ul>
<li>Voice Operated Recording (VOR) using "Clear Voice" recording system </li>
<li>One Touch Recording thru the built-In microphone </li>
<li>2-Speed Record/Playback </li>
<li>Cue And Review With Slide Control </li>
<li>30 Hour Battery Life </li>
<li>LED Battery Level Indicator </li>
<li>Automatic Shut Off At End Of Tape </li>
<li>DC-In Jack </li>
<li>Battery LED </li>
<li>L/R Monaural Earphone Jack Hinged </li>
<li>Automatic Recording Level Control </li>
</ul>
<file_sep>/README.md
"# FuelStore"
<file_sep>/fuel/app/tmp/Smarty/templates_c/3252b9d88af32f58ecf9544e19a3390c852120bf_0.file.showProduct.tpl.php
<?php
/* Smarty version 3.1.33, created on 2019-04-19 11:44:49
from 'C:\Users\copyp\OneDrive\Documents\NetBeansProjects\FuelStore_JRowan\fuel\app\views\home\showProduct.tpl' */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.33',
'unifunc' => 'content_5cb9ecf1e795e6_43103217',
'has_nocache_code' => false,
'file_dependency' =>
array (
'3252b9d88af32f58ecf9544e19a3390c852120bf' =>
array (
0 => 'C:\\Users\\copyp\\OneDrive\\Documents\\NetBeansProjects\\FuelStore_JRowan\\fuel\\app\\views\\home\\showProduct.tpl',
1 => 1555688686,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_5cb9ecf1e795e6_43103217 (Smarty_Internal_Template $_smarty_tpl) {
$_smarty_tpl->_loadInheritance();
$_smarty_tpl->inheritance->init($_smarty_tpl, true);
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_15764582355cb9ecf1e629d4_33824758', "localstyle");
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_17805939245cb9ecf1e63845_43688827', "content");
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_16920485995cb9ecf1e78dc9_41756635', "localscript");
?>
<?php $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl");
}
/* {block "localstyle"} */
class Block_15764582355cb9ecf1e629d4_33824758 extends Smarty_Internal_Block
{
public $subBlocks = array (
'localstyle' =>
array (
0 => 'Block_15764582355cb9ecf1e629d4_33824758',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<style type="text/css">
table.info td:first-child, table.info th:first-child {
white-space: nowrap;
width: 10px;
}
table.info th, table.info td {
line-height: 10px;
}
input {
width: 5em;
}
</style>
<?php
}
}
/* {/block "localstyle"} */
/* {block "content"} */
class Block_17805939245cb9ecf1e63845_43688827 extends Smarty_Internal_Block
{
public $subBlocks = array (
'content' =>
array (
0 => 'Block_17805939245cb9ecf1e63845_43688827',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<h2>Show Product</h2>
<table class='info table table-sm table-borderless'>
<tr>
<th colspan="2"><?php echo $_smarty_tpl->tpl_vars['product']->value->name;?>
</th>
</tr>
<tr>
<td>product id:</td>
<td><?php echo $_smarty_tpl->tpl_vars['product']->value->id;?>
</td>
</tr>
<tr>
<td>price:</td>
<td>$<?php echo number_format($_smarty_tpl->tpl_vars['product']->value->price,2);?>
</td>
</tr>
<tr>
<td>category:</td>
<td><?php echo $_smarty_tpl->tpl_vars['product']->value->category->name;?>
</td>
</tr>
</table>
<table class='table-sm'>
<tr>
<td>
<?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['asset_img'][0], array( array('refs'=>$_smarty_tpl->tpl_vars['image_src']->value,'attrs'=>array('class'=>'img-fluid')),$_smarty_tpl ) );?>
</td>
<td>
<?php if ($_smarty_tpl->tpl_vars['session']->value->get('login') && $_smarty_tpl->tpl_vars['session']->value->get('login')->is_admin) {?>
<?php $_block_plugin1 = isset($_smarty_tpl->smarty->registered_plugins['block']['form'][0][0]) ? $_smarty_tpl->smarty->registered_plugins['block']['form'][0][0] : null;
if (!is_callable(array($_block_plugin1, 'form'))) {
throw new SmartyException('block tag \'form\' not callable or registered');
}
$_smarty_tpl->smarty->_cache['_tag_stack'][] = array('form', array('attrs'=>array('action'=>'/adminOrder/modifyProduct')));
$_block_repeat=true;
echo $_block_plugin1->form(array('attrs'=>array('action'=>'/adminOrder/modifyProduct')), null, $_smarty_tpl, $_block_repeat);
while ($_block_repeat) {
ob_start();?>
<button type="submit" name='modify'>Modify</button>
<input type="hidden" name='id' value=<?php echo $_smarty_tpl->tpl_vars['product']->value->id;?>
/>
<?php $_block_repeat=false;
echo $_block_plugin1->form(array('attrs'=>array('action'=>'/adminOrder/modifyProduct')), ob_get_clean(), $_smarty_tpl, $_block_repeat);
}
array_pop($_smarty_tpl->smarty->_cache['_tag_stack']);?>
<?php } else { ?>
<?php $_block_plugin2 = isset($_smarty_tpl->smarty->registered_plugins['block']['form'][0][0]) ? $_smarty_tpl->smarty->registered_plugins['block']['form'][0][0] : null;
if (!is_callable(array($_block_plugin2, 'form'))) {
throw new SmartyException('block tag \'form\' not callable or registered');
}
$_smarty_tpl->smarty->_cache['_tag_stack'][] = array('form', array('attrs'=>array('action'=>"cart/setCart",'method'=>"get")));
$_block_repeat=true;
echo $_block_plugin2->form(array('attrs'=>array('action'=>"cart/setCart",'method'=>"get")), null, $_smarty_tpl, $_block_repeat);
while ($_block_repeat) {
ob_start();?>
<b>Quantity:</b>
<input name="quantity" type="number" min="1" value="<?php echo $_smarty_tpl->tpl_vars['quantity']->value;?>
" required />
<input name="id" type="hidden" value="<?php echo $_smarty_tpl->tpl_vars['product']->value->id;?>
" />
<p></p>
<button type="submit" name='set'>Set Quantity</button>
<button type="submit" name='cancel'>Cancel</button>
<button type="submit" name='remove'>Remove From Cart</button>
<?php $_block_repeat=false;
echo $_block_plugin2->form(array('attrs'=>array('action'=>"cart/setCart",'method'=>"get")), ob_get_clean(), $_smarty_tpl, $_block_repeat);
}
array_pop($_smarty_tpl->smarty->_cache['_tag_stack']);
}?>
</td>
</tr>
</table>
<p>
<?php echo $_smarty_tpl->tpl_vars['description']->value;?>
</p>
<?php
}
}
/* {/block "content"} */
/* {block "localscript"} */
class Block_16920485995cb9ecf1e78dc9_41756635 extends Smarty_Internal_Block
{
public $subBlocks = array (
'localscript' =>
array (
0 => 'Block_16920485995cb9ecf1e78dc9_41756635',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<?php echo '<script'; ?>
type="text/javascript">
$("button[name='cancel']").click(function () {
$("input[name='quantity']").prop('disabled', true);
});
$("button[name='remove']").click(function () {
$("input[name='quantity']").prop('disabled', true);
});
<?php echo '</script'; ?>
>
<?php
}
}
/* {/block "localscript"} */
}
<file_sep>/fuel/app/tasks/tables/user-sqlite.sql
create table `user` (
id integer primary key not null,
name text unique not null collate nocase,
email text not null collate nocase,
password text not null,
is_admin bool not null
)
<file_sep>/fuel/app/classes/model/product.php
<?php
class Model_Product extends \Orm\Model {
protected static $_properties = [
'id',
'name',
'price',
'description',
'photo_file',
'category_id',
];
protected static $_table_name = 'product';
// use $product->category to get the category
protected static $_belongs_to = [
'category' => [
'model_to' => 'Model_Category',
],
];
// use $product->orders to get the orders of a product
protected static $_many_many = [
'orders' => [
'model_to' => 'Model_Order',
'table_through' => 'selection',
],
];
// use $product->selections to the selections of a product
protected static $_has_many = [
'selections' => [
'model_to' => 'Model_Selection',
]
];
}
<file_sep>/fuel/app/classes/model/selection.php
<?php
class Model_Selection extends \Orm\Model {
protected static $_table_name = 'selection';
protected static $_properties = [
'id',
'product_id',
'order_id',
'quantity',
'purchase_price',
];
// use $selection->product to get the product that owns this selection
// use $selection->order to get the order that owns this selection
protected static $_belongs_to = [
'product' => [
'model_to' => 'Model_Product',
],
'order' => [
'model_to' => 'Model_Order',
]
];
}
<file_sep>/fuel/app/tmp/Smarty/templates_c/12b1140c91aafe1aa5d26800cc13eeb93888c679_0.file.allorders.tpl.php
<?php
/* Smarty version 3.1.33, created on 2019-04-19 11:36:40
from 'C:\Users\copyp\OneDrive\Documents\NetBeansProjects\FuelStore_JRowan\fuel\app\views\user\allorders.tpl' */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.33',
'unifunc' => 'content_5cb9eb087905a2_98634120',
'has_nocache_code' => false,
'file_dependency' =>
array (
'12b1140c91aafe1aa5d26800cc13eeb93888c679' =>
array (
0 => 'C:\\Users\\copyp\\OneDrive\\Documents\\NetBeansProjects\\FuelStore_JRowan\\fuel\\app\\views\\user\\allorders.tpl',
1 => 1555688196,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_5cb9eb087905a2_98634120 (Smarty_Internal_Template $_smarty_tpl) {
$_smarty_tpl->_loadInheritance();
$_smarty_tpl->inheritance->init($_smarty_tpl, true);
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_710331915cb9eb0877e354_68743481', "localstyle");
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_7183619435cb9eb0877f035_95210076', "content");
$_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl");
}
/* {block "localstyle"} */
class Block_710331915cb9eb0877e354_68743481 extends Smarty_Internal_Block
{
public $subBlocks = array (
'localstyle' =>
array (
0 => 'Block_710331915cb9eb0877e354_68743481',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<style type="text/css">
td:first-child, th:first-child {
width: 10px;
white-space: nowrap;
}
</style>
<?php
}
}
/* {/block "localstyle"} */
/* {block "content"} */
class Block_7183619435cb9eb0877f035_95210076 extends Smarty_Internal_Block
{
public $subBlocks = array (
'content' =>
array (
0 => 'Block_7183619435cb9eb0877f035_95210076',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<h2>All Orders</h2>
<table class="table table-sm table-borderless">
<tr>
<th>Order Id</th>
<th>User</th>
<th>Date/Time</th>
</tr>
<?php
$_from = $_smarty_tpl->smarty->ext->_foreach->init($_smarty_tpl, $_smarty_tpl->tpl_vars['orders']->value, 'order');
if ($_from !== null) {
foreach ($_from as $_smarty_tpl->tpl_vars['order']->value) {
?>
<tr>
<td>
<?php echo $_smarty_tpl->tpl_vars['order']->value->id;?>
<?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['html_anchor'][0], array( array('href'=>"/user/orderDetails/".((string)$_smarty_tpl->tpl_vars['order']->value->id),'text'=>"(details)"),$_smarty_tpl ) );?>
</a>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['order']->value->user->name;?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['order']->value->created_at;?>
</td>
</tr>
<?php
}
}
$_smarty_tpl->smarty->ext->_foreach->restore($_smarty_tpl, 1);?>
</table>
<h4 class="message"><?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['session_get_flash'][0], array( array('var'=>'message'),$_smarty_tpl ) );?>
</h4>
<?php
}
}
/* {/block "content"} */
}
<file_sep>/fuel/app/classes/controller/home.php
<?php
/**
* author: <NAME>
* class: csc 417 User Interfaces MW 5:45-7pm
*/
class Controller_Home extends Controller_Base {
public function before() {
parent::before();
if (is_null(Session::get('field'))) {
Session::set('field','name');
}
if (is_null(Session::get('category'))) {
Session::set('category',0);
}
}
/**
*
* @param type $name : 'name'
* description: called when the user clicks on the name link in the home page
* to set the ordering of products to name
*/
public function action_name($name){
Session::set('field',$name);
return Response::redirect("/");
}
/**
*
* @param type $price
* description: called when the user clicks on the price link in the home page
* to set the ordering of products by price
*/
public function action_price($price){
Session::set('field',$price);
return Response::redirect("/");
}
public function action_something() {
return "home/something";
}
/**
*
* description: called when the user sets a category in the home page
*/
public function action_setCategory(){
$category_id = Input::param('category_id');
if(is_null($category_id)){
$category_id = 0;
}
Session::set('category',$category_id);
return Response::redirect("/");
}
/**
*
* description: this is the initial entry to the home page
*/
public function action_index() {
$categories[0] = "-- ALL --";
foreach (Model_Category::find('all') as $rec) {
$categories[$rec->id] = $rec->name;
}
$category_id = Session::get('category');
$field = Session::get('field');
if($category_id == 0){
$products = Model_Product::find('all',['order_by' => [$field]]);
}else{
$products = Model_Product::find('all',['where' => ['category_id' => $category_id],'order_by' => [$field]]);
}
$data = [
'products' => $products,
'categories' => $categories,
'category_id' => $category_id,
];
return View::forge('home/index.tpl', $data);
}
}
<file_sep>/fuel/app/tasks/tables/order-mysql.sql
create table `order` (
id integer auto_increment primary key not null,
user_id integer not null,
created_at datetime not null,
foreign key(user_id) references user(id)
);
<file_sep>/fuel/app/tasks/descriptions/mach-speed-eclipse-180gw-video-mp3-player.html
Features:
<ul>
<li> Compact size. Measures just 0.5" thin and weighs only 3.2 oz.,
so you can take your music with you on the go. </li>
<li> 4GB* built-in flash memory offers spacious storage for songs, videos and photos.
The microSD slot supports up to a 16GB microSDHC card for expanded storage
options (card not included). </li>
<li> Built-in camera and camcorder let you capture still photos and record video.
Digital photo viewer makes it easy to navigate through your pictures. </li>
<li> Supported formats include MP3, WMA (nonencrypted), OGG, APE, FLAC, WAV and
AAC to accommodate your media collection. </li>
<li> 1.8" color LCD screen showcases your photos and videos in clear display. </li>
<li> Built-in speaker Along with bass boost creates rich, robust sound. </li>
<li> Built-in FM tuner with 30 station presets, so you can enjoy your favorite
radio channels. Voice recorder allows you to record notes, lectures,
conversations and more for later review. </li>
<li> Supports Apple iTunes so you can easily download your
favorite songs and videos (additional fees may apply). </li>
<li> Bass boost delivers rich, textured sound. </li>
<li> High-speed USB 2.0 interface
for blazing-fast transfer speeds (USB 2.0 cable included). </li>
<li> Skip-free playback ensures a quality listening experience. </li>
<li> Up to 8 hours playback with the built-in rechargeable lithium-ion battery. </li>
<li> PC and Mac compatible
for multifunctional use with Windows 2000 or later and Mac OS X 10.4 or later. </li>
</ul>
<file_sep>/fuel/app/tasks/tables/product-mysql.sql
create table `product` (
id integer auto_increment primary key not null,
name varchar(255) unique not null,
description text not null,
price real not null,
photo_file varchar(255) not null,
category_id integer not null,
foreign key(category_id) references category(id)
);
<file_sep>/fuel/app/tmp/Smarty/templates_c/6e3ea55ea9b10aee00275d4cac348b5d0ebdff31_0.file.showProduct.tpl.php
<?php
/* Smarty version 3.1.33, created on 2019-04-18 20:02:45
from 'C:\Users\copyp\OneDrive\Documents\NetBeansProjects\FuelStore\fuel\app\views\home\showProduct.tpl' */
/* @var Smarty_Internal_Template $_smarty_tpl */
if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array (
'version' => '3.1.33',
'unifunc' => 'content_5cb91025dbd574_35190617',
'has_nocache_code' => false,
'file_dependency' =>
array (
'6e3ea55ea9b10aee00275d4cac348b5d0ebdff31' =>
array (
0 => 'C:\\Users\\copyp\\OneDrive\\Documents\\NetBeansProjects\\FuelStore\\fuel\\app\\views\\home\\showProduct.tpl',
1 => 1555631874,
2 => 'file',
),
),
'includes' =>
array (
),
),false)) {
function content_5cb91025dbd574_35190617 (Smarty_Internal_Template $_smarty_tpl) {
$_smarty_tpl->_loadInheritance();
$_smarty_tpl->inheritance->init($_smarty_tpl, true);
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_14594207625cb91025dadc45_36165541', "localstyle");
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_11750195315cb91025daeb11_03873055', "content");
?>
<?php
$_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_14371468075cb91025dbcd56_04788785', "localscript");
?>
<?php $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl");
}
/* {block "localstyle"} */
class Block_14594207625cb91025dadc45_36165541 extends Smarty_Internal_Block
{
public $subBlocks = array (
'localstyle' =>
array (
0 => 'Block_14594207625cb91025dadc45_36165541',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<style type="text/css">
table.info td:first-child, table.info th:first-child {
white-space: nowrap;
width: 10px;
}
table.info th, table.info td {
line-height: 10px;
}
input {
width: 5em;
}
</style>
<?php
}
}
/* {/block "localstyle"} */
/* {block "content"} */
class Block_11750195315cb91025daeb11_03873055 extends Smarty_Internal_Block
{
public $subBlocks = array (
'content' =>
array (
0 => 'Block_11750195315cb91025daeb11_03873055',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<h2>Show Product</h2>
<table class='info table table-sm table-borderless'>
<tr>
<th colspan="2"><?php echo $_smarty_tpl->tpl_vars['product']->value->name;?>
</th>
</tr>
<tr>
<td>product id:</td>
<td><?php echo $_smarty_tpl->tpl_vars['product']->value->id;?>
</td>
</tr>
<tr>
<td>price:</td>
<td>$<?php echo number_format($_smarty_tpl->tpl_vars['product']->value->price,2);?>
</td>
</tr>
<tr>
<td>category:</td>
<td><?php echo $_smarty_tpl->tpl_vars['product']->value->category->name;?>
</td>
</tr>
</table>
<table class='table-sm'>
<tr>
<td>
<?php echo call_user_func_array( $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['asset_img'][0], array( array('refs'=>$_smarty_tpl->tpl_vars['image_src']->value,'attrs'=>array('class'=>'img-fluid')),$_smarty_tpl ) );?>
</td>
<td>
<?php $_block_plugin1 = isset($_smarty_tpl->smarty->registered_plugins['block']['form'][0][0]) ? $_smarty_tpl->smarty->registered_plugins['block']['form'][0][0] : null;
if (!is_callable(array($_block_plugin1, 'form'))) {
throw new SmartyException('block tag \'form\' not callable or registered');
}
$_smarty_tpl->smarty->_cache['_tag_stack'][] = array('form', array('attrs'=>array('action'=>"cart/something",'method'=>"get")));
$_block_repeat=true;
echo $_block_plugin1->form(array('attrs'=>array('action'=>"cart/something",'method'=>"get")), null, $_smarty_tpl, $_block_repeat);
while ($_block_repeat) {
ob_start();?>
<b>Quantity:</b>
<input name="quantity" type="number" min="1" required />
<p></p>
<button type="submit" name='set'>Set Quantity</button>
<button type="submit" name='cancel'>Cancel</button>
<button type="submit" name='remove'>Remove From Cart</button>
<?php $_block_repeat=false;
echo $_block_plugin1->form(array('attrs'=>array('action'=>"cart/something",'method'=>"get")), ob_get_clean(), $_smarty_tpl, $_block_repeat);
}
array_pop($_smarty_tpl->smarty->_cache['_tag_stack']);?>
</td>
</tr>
</table>
<p>
<?php echo $_smarty_tpl->tpl_vars['description']->value;?>
</p>
<?php
}
}
/* {/block "content"} */
/* {block "localscript"} */
class Block_14371468075cb91025dbcd56_04788785 extends Smarty_Internal_Block
{
public $subBlocks = array (
'localscript' =>
array (
0 => 'Block_14371468075cb91025dbcd56_04788785',
),
);
public function callBlock(Smarty_Internal_Template $_smarty_tpl) {
?>
<?php echo '<script'; ?>
type="text/javascript">
$("button[name='cancel']").click(function () {
$("input[name='quantity']").prop('disabled', true);
});
$("button[name='remove']").click(function () {
$("input[name='quantity']").prop('disabled', true);
});
<?php echo '</script'; ?>
>
<?php
}
}
/* {/block "localscript"} */
}
<file_sep>/fuel/app/classes/controller/newuser.php
<?php
/**
* author: <NAME>
* class: csc 417 User Interfaces MW 5:45-7pm
*/
class Controller_newuser extends Controller_Base {
/**
*
* description: this is the initial entry to create a user page
*/
public function action_createUser(){
$data = [
'username' => null,
'email' => null,
];
$validator = Validators::userValidator();
$view = View::forge("authenticate/newuser.tpl",$data);
$view->set_safe('validator', $validator);
return $view;
}
/**
*
* description: this is the reentrand action for creating a user
*/
public function action_userValidate(){
$cancel = Input::param('cancel');
if(!is_null($cancel)){
return Response::redirect("/");
}
$validator = Validators::userValidator();
$validated = $validator->run(Input::post());
if($validated){
$validData = $validator->validated();
$user = Model_User::forge();
$user->name = $validData['username'];
$user->email = $validData['email'];
$user->password = hash('<PASSWORD>', $valid<PASSWORD>['<PASSWORD>']);
$user->save();
return Response::redirect("authenticate/login");
}
$data = [
'username' => Input::param('username'),
'email' => Input::param('email')
];
$view = View::forge("authenticate/newuser.tpl",$data);
$view->set_safe('validator', $validator);
return $view;
}
}
<file_sep>/fuel/app/tasks/descriptions/hp-10bII+-financial-calculator.html
Features:
<ul>
<li> Fast financial calculations for professionals and students </li>
<li> Features powerful finance, business and statistical functions.
Makes it easy to solve financial and other calculations accurately and quickly. </li>
<li> Dedicated keys provide fast access to common financial and statistical functions.
Lets you do trigonometry, hyperbolics, permutations and combinations, date
calculations and probability distributions. Amortization and time value of
money functions enable quick calculations of loans and mortgages. You can
also calculate cash flow (IRR, NPV and NFV) with up to 45 data points,
as well as break-even quantity. Lets you choose from 6 regression options, plus Best Fit. </li>
<li> Clear, easy-to-read 12-character LCD features adjustable contrast. Lets
you view answers with up to 12 digits of accuracy. On-screen labels provide useful context. </li>
<li> Allows you to store up to 22 numbers in memory registers for later use. </li>
<li> Provides a choice of entry-system logic: algebraic and chain algebraic. </li>
</ul>
<file_sep>/fuel/app/classes/controller/cart.php
<?php
/**
* author: <NAME>
* class: csc 417 User Interfaces MW 5:45-7pm
*/
class Controller_Cart extends Controller_Base {
public function before() {
parent::before();
if (is_null(Session::get('cart'))) {
Session::set('cart', []);
}
}
/**
*
* description: action when setting,removing,or cancelling show product page
*/
public function action_setCart(){
$set = Input::param('set');
$cancel = Input::param('cancel');
$remove = Input::param('remove');
$quantity = Input::param('quantity');
$id = Input::param('id');
if(!is_null($set)){
$cart = Session::get('cart');
$cart[$id] = $quantity;
Session::set('cart',$cart);
return Response::redirect("/Cart/index");
}
if(!is_null($cancel)){
return Response::redirect("/");
}
if(!is_null($remove)){
$cart = Session::get('cart');
unset($cart[$id]);
Session::set('cart',$cart);
return Response::redirect("/Cart/index");
}
}
/**
*
* @param type $product_id : id of product to be shown
* description: this is called when the user selects a product to be shown
*/
public function action_show($product_id) {
$quantity = null;
if(isset(Session::get('cart')[$product_id])){
$quantity = Session::get('cart')[$product_id];
}
$product = Model_Product::find($product_id);
$image_src = "products/$product->photo_file";
$data = [
'product' => $product,
'image_src' => $image_src,
'quantity' => $quantity
];
$view = View::forge('home/showProduct.tpl', $data);
$view->set_safe('description', $product->description);
return $view;
}
/**
*
* description: called as the initial entry to cart page
*/
public function action_index() {
//total price, adds up all products in cart
$total_price = 0;
//cart info stores all of the products and details returned to view
$cart_info = [];
foreach (Session::get('cart') as $key => $value) {
$id = $key;
$product = Model_Product::find($key);//R::findOne("product", "id=?",[$key]);
//$category = //R::findOne("category", "id=?",[$product->category_id]);
$cat_name = $product->category->name;//$category->name;
$quantity = $value;
$name = $product->name;
$price = $product->price;
$subtotal = $quantity * $price;
$cart_info[$id] = [
'name' => $name,
'category' => $cat_name,
'price' => $price,
'amount' => $quantity,
'subtotal' => $subtotal
];
$total_price += $price * $quantity;
//echo "<script>console.log( 'Debug Objects: " . $product . "' );</script>";
}
$data = [
'cart_info' => $cart_info,
'total_price' => $total_price,
];
$view = View::forge('cart/index.tpl', $data);
return $view;
}
public function action_something() {
return "cart/something";
}
}
<file_sep>/fuel/app/tasks/descriptions/canon-powershot-a400-camera.html
Features:
<ul>
<li> 8x optical zoom with 28mm wide-angle lens for stunning images </li>
<li> 16.0-megapixel sensor delivers detailed shots ready to be enlarged. </li>
<li> Optical Image Stabilizer helps you avoid blurry shots.
Specially developed for fast-moving action shots and to help
counteract the effects of shaky hands — keeps your images in focus. </li>
<li> Large, clear 3.0-inch LCD makes taking and viewing images a breeze. </li>
<li> Smart AUTO mode takes the guesswork out of shooting.
The camera will do the work for you by intelligently selecting the proper
settings for your shot based on 32 predefined shooting situations. </li>
<li> Shoot brilliant 720p HD video with a dedicated movie button. </li>
<li> Face detection technology helps you take better portraits. </li>
</ul>
|
bf9a7edf4d2517bea4e5c9effb1291dac5ad8a56
|
[
"Markdown",
"SQL",
"HTML",
"PHP"
] | 39
|
SQL
|
copypasteearth/FuelStore
|
542438bda39c15147620c7a5c9419231c1f23be0
|
96d92a6c941e283c9119cebb1e2a6d10f73ef9d3
|
refs/heads/master
|
<repo_name>kissjacky/qycms<file_sep>/backend/models/Product.php
<?php
namespace backend\models;
use Yii;
use yii\web\UploadedFile;
/**
* This is the model class for table "qycms_product".
*
* @property integer $id
* @property string $name
* @property integer $cid
* @property string $pics
* @property string $fields
* @property string $content
* @property integer $status
* @property integer $ctime
* @property integer $mtime
* @property string $lang
*/
class Product extends \common\models\Product
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'qycms_product';
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[
'status',
'default',
'value' => self::STATUS_ACTIVE
],
]);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'id',
'name' => '名称',
'cid' => '分类',
'pics' => '产品图片',
'fields' => '附加字段',
'content' => '内容',
'status' => '状态',
'ctime' => '创建时间',
'mtime' => '修改时间',
'lang' => '语种',
];
}
}
<file_sep>/backend/widgets/Quill.php
<?php
/**
* @author <EMAIL>
* @date 15/10/2017
*/
namespace backend\widgets;
use yii\base\Widget;
class Quill extends Widget {
public $name;
public $form_id;
public $contents;
public function run() {
$view = $this->getView();
QuillAsset::register($view);
$view->registerJs('var hiddenInput = $("input[name=\'' . $this->name . '\']");
var editor = new Quill("#editor", {
modules: { toolbar: [
["bold", "italic"],
["link", "blockquote", "code-block", "image"],
[{ list: "ordered" }, { list: "bullet" }]
] },
placeholder: "请填写内容",
theme: "snow"
//,contents: JSON.parse(hiddenInput.val())
});
//editor.setContents(JSON.parse(hiddenInput.val()).ops);
$("#editor").children().first().html(hiddenInput.val());
$("#' . $this->form_id . '").submit(function(){
//hiddenInput.val(JSON.stringify(editor.getContents()));
hiddenInput.val($(\'#editor\').children().first().html());
});');
echo '
<!-- the editor container -->
<div id="editor">
</div>';
}
}
<file_sep>/backend/logic/Nested.php
<?php
/**
* @author <EMAIL>
* @date 08/10/2017
*/
namespace backend\logic;
/**
* Class Nested
* 要求:数据list的每一行,含id、pid、pids字段
* @package common\models
*/
class Nested extends \common\logic\Nested {
protected static $_with_pre = true;
public static function dataList($data) {
$res = [];
$tmp = self::childrenWithTree($data);
unset($data);
if (!empty($tmp['tree'])) {
self::dataPrefix($tmp['tree'], $tmp['items'], $res);
}
return $res;
}
private static function dataPrefix($tree, &$items, &$res) {
foreach ($tree as $k => $v) {
$level = $items[$k]['pids'] == '0' ? 1 : count(explode(',', $items[$k]['pids'])) + 1;
if($level == 1){
$pre = '';
}elseif($level == 2){
$pre = '– ';
}else{
$pre = str_repeat('<span style="color: #999;">┊ </span>', $level - 2) . '– ';
}
$items[$k]['name'] = $pre . $items[$k]['name'];
$items[$k]['nested_level'] = $level;
$res[$items[$k]['id']] = $items[$k];
if (!empty($v)) {
self::dataPrefix($v, $items, $res);
}
}
}
}
<file_sep>/backend/views/site/index.php
<?php
use yii\helpers\Url;
/* @var $this yii\web\View */
$this->title = '青鱼CMS 后台';
?>
<div class="site-index">
<div class="jumbotron">
<h1>恭喜!</h1>
<p class="lead">您已成功拥有青鱼CMS应用.</p>
<p><a class="btn btn-lg btn-success" href="<?=Url::to(['config/index'])?>">Get started</a></p>
</div>
<div class="body-content">
<div class="row">
<div class="col-lg-4">
<h2>简单可靠</h2>
<p>青鱼CMS 基于简单、强大、优雅的Yii框架实现,提供CMS的核心模块,运营人员可凭直觉轻松丰富您的站点。<br>分类、文章管理、产品管理、单页面管理、菜单配置……<br>一切都是那么自然、简单!</p>
<p><a class="btn btn-default" href="<?=Url::to(['config/index'])?>">全局配置 »</a></p>
</div>
<div class="col-lg-4">
<h2>分类嵌套</h2>
<p>青鱼CMS 支持无限嵌套的分类,并支持分类的嵌套排序,无疑支持了您的产品、文档的组织和展示需求。</p>
<p><a class="btn btn-default" href="<?=Url::to(['procate/index'])?>">文章分类 »</a></p>
</div>
<div class="col-lg-4">
<h2>多语种 & SEO</h2>
<p>青鱼CMS 设计之初,就注重多语种、SEO优化。<br>只要在站点创立之初,配置多语种信息,即可在编辑内容时选择语种。<br>您将得到一个内容井然的多语种站点!</p>
<p><a class="btn btn-default" href="<?=Url::to(['config/index'])?>">全局配置 »</a></p>
</div>
</div>
</div>
</div>
<file_sep>/frontend/models/Article.php
<?php
namespace frontend\models;
use Yii;
/**
* This is the model class for table "qycms_article".
* @property integer $id
* @property string $name
* @property integer $cid
* @property string $summary
* @property string $content
* @property integer $status
* @property integer $ctime
* @property integer $mtime
* @property integer $lang_id
*/
class Article extends \common\models\Article {
public static function getHot($num = 5) {
$data = self::find()->where([
'=',
'lang',
Yii::$app->language
])->orderBy('hits DESC')->offset(0)->limit($num)->asArray()->all();
return $data;
}
public static function getLatest($num = 5) {
$data = self::find()->where([
'=',
'lang',
Yii::$app->language
])->orderBy('mtime DESC')->offset(0)->limit($num)->asArray()->all();
return $data;
}
}
<file_sep>/backend/models/Page.php
<?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "qycms_page".
*
* @property integer $id
* @property string $name
* @property string $summary
* @property string $content
* @property integer $status
* @property integer $ctime
* @property integer $mtime
* @property string $lang
*/
class Page extends \common\models\Page
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'qycms_page';
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[
'status',
'default',
'value' => self::STATUS_ACTIVE
],
]);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'id',
'name' => '名称',
'summary' => '摘要',
'content' => '内容',
'status' => '状态',
'ctime' => '创建时间',
'mtime' => '修改时间',
'lang' => '语种',
];
}
public static function options(){
$data = Page::find()->asArray()->all();
$res = [];
foreach ($data as $v){
$res[$v['id']] = $v['name'];
}
return $res;
}
}
<file_sep>/backend/widgets/DatetimepickerInput.php
<?php
/**
* @author <EMAIL>
* @date 29/09/2017
*/
namespace backend\widgets;
use yii\widgets\InputWidget;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
/**
* MaskedInput generates a masked text input.
*
* MaskedInput is similar to [[Html::textInput()]] except that an input mask will be used to force users to enter
* properly formatted data, such as phone numbers, social security numbers.
*
* To use MaskedInput, you must set the [[mask]] property. The following example
* shows how to use MaskedInput to collect phone numbers:
*
* ```php
* echo MaskedInput::widget([
* 'name' => 'phone',
* 'mask' => '999-999-9999',
* ]);
* ```
*
* You can also use this widget in an [[yii\widgets\ActiveForm|ActiveForm]] using the [[yii\widgets\ActiveField::widget()|widget()]]
* method, for example like this:
*
* ```php
* <?= $form->field($model, 'from_date')->widget(\yii\widgets\MaskedInput::className(), [
* 'mask' => '999-999-9999',
* ]) ?>
* ```
*
* The masked text field is implemented based on the
* [jQuery input masked plugin](https://github.com/RobinHerbots/jquery.inputmask).
*
* @author <NAME> <<EMAIL>>
* @since 2.0
*/
class DatetimepickerInput extends InputWidget
{
/**
* The name of the jQuery plugin to use for this widget.
*/
const PLUGIN_NAME = 'datetimepicker';
/**
* @var array the HTML attributes for the input tag.
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $options = ['class' => 'form-control'];
/**
* @var string the type of the input tag. Currently only 'text' and 'tel' are supported.
* @see https://github.com/RobinHerbots/jquery.inputmask
* @since 2.0.6
*/
public $type = 'text';
/**
* Initializes the widget.
*
* @throws InvalidConfigException if the "mask" property is not set.
*/
public function init()
{
parent::init();
}
/**
* @inheritdoc
*/
public function run()
{
$this->registerClientScript();
if ($this->hasModel()) {
echo Html::activeInput($this->type, $this->model, $this->attribute, $this->options);
} else {
echo Html::input($this->type, $this->name, $this->value, $this->options);
}
}
/**
* Registers the needed client script and options.
*/
public function registerClientScript()
{
$js = '';
$view = $this->getView();
$id = $this->options['id'];
$js .= '$("#' . $id . '").' . self::PLUGIN_NAME . '({format: "Y-m-d H:i:s",lang:"ch"});';
DatetimepickerInputAsset::register($view);
$view->registerJs($js);
}
}
<file_sep>/backend/controllers/ArtcateController.php
<?php
namespace backend\controllers;
use backend\logic\Nested;
use backend\models\Article;
use Yii;
use backend\models\Artcate;
use yii\data\ActiveDataProvider;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\Lang;
/**
* ArtcateController implements the CRUD actions for Artcate model.
*/
class ArtcateController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Artcate models.
* @return mixed
*/
public function actionIndex()
{
$data = Nested::dataList(Artcate::find()->orderBy('display_order DESC')->asArray()->all());
return $this->render('index', [
'data' => $data,
]);
}
public function actionOrder(){
$ids = Yii::$app->request->post('ids');
$order = array_reverse(explode(',', trim($ids, ', ')));
foreach ($order as $k=>$id){
Artcate::updateAll(['display_order' => $k], 'id = '.$id);
}
var_dump($order);
}
/**
* Displays a single Artcate model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Artcate model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Artcate();
$post = Yii::$app->request->post();
if(!empty($post[$model->formName()])){
$data = $post[$model->formName()];
$post[$model->formName()]['pids'] = Nested::getPids(Artcate::findOne($data['pid']));
$post[$model->formName()]['ctime'] = $post[$model->formName()]['mtime'] = time();
if ($post['save-to-hide'] == 'yes') {
$post[$model->formName()]['status'] = Artcate::STATUS_HIDE;
}
}
if ($model->load($post) && $model->save()) {
if ($post['save-then-new'] == 'yes') {
return $this->render('create', [
'model' => new Artcate(),
]);
}
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Artcate model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$post = Yii::$app->request->post();
if(!empty($post[$model->formName()])){
$data = $post[$model->formName()];
$post[$model->formName()]['pids'] = Nested::getPids(Artcate::findOne($data['pid']));
$post[$model->formName()]['mtime'] = time();
if ($post['save-to-hide'] == 'yes') {
$post[$model->formName()]['status'] = Artcate::STATUS_HIDE;
}
}
if ($model->load($post) && $model->save()) {
if ($post['save-then-new'] == 'yes') {
return $this->render('create', [
'model' => new Artcate(),
]);
}
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Artcate model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
public function actionHide(){
$id = Yii::$app->request->get('id');
$model = $this->findModel($id);
$status = $model->status;
$model->status = $status == Artcate::STATUS_HIDE ? Artcate::STATUS_ACTIVE : Artcate::STATUS_HIDE;
$model->save();
return $this->redirect(['index']);
}
/**
* Finds the Artcate model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Artcate the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Artcate::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
<file_sep>/README.md
# qycms
yet another cms
<file_sep>/common/logic/Lang.php
<?php
/**
* @author <EMAIL>
* @date 08/10/2017
*/
namespace common\logic;
use yii;
use yii\helpers\ArrayHelper;
class Lang {
public static function items(){
$res = [];
foreach (Yii::$app->params['lang'] as $v) {
$res[$v['code']] = $v['title_native'];
}
return $res;
}
}
<file_sep>/frontend/messages/zh-CN/article.php
<?php
/**
* @author <EMAIL>
* @date 14/10/2017
*/
return [
'Artcates' => '文章',
'Create Artcate' => '添加文章',
];
<file_sep>/frontend/logic/Base.php
<?php
/**
* @author <EMAIL>
* @date 22/10/2017
*/
namespace frontend\logic;
class Base {
}
<file_sep>/backend/models/Menu.php
<?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "qycms_menu".
*
* @property integer $id
* @property integer $pid
* @property string $name
* @property string $content_type
* @property string $content
* @property integer $ctime
* @property integer $mtime
* @property string $lang
*/
class Menu extends \common\models\Menu
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'qycms_menu';
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), []);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'id',
'pid' => '上级菜单',
'pids' => '祖先id链',
'name' => '名称',
'content_type' => '内容类型',
'content' => '内容',
'ctime' => '创建时间',
'mtime' => '修改时间',
'lang' => '语种',
];
}
}
<file_sep>/frontend/models/Procate.php
<?php
namespace frontend\models;
use Yii;
use frontend\logic\Nested;
/**
* This is the model class for table "qycms_procate".
*
* @property integer $id
* @property string $name
* @property integer $pid
* @property string $pids
* @property integer $status
* @property integer $display_order
* @property integer $ctime
* @property integer $mtime
* @property integer $lang_id
*/
class Procate extends \common\models\Procate
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'qycms_procate';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['pid', 'status', 'display_order', 'ctime', 'mtime', 'lang_id'], 'integer'],
[['name'], 'string', 'max' => 64],
[['pids'], 'string', 'max' => 32],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app\common', 'id'),
'name' => Yii::t('app\common', '名称'),
'pid' => Yii::t('app\common', '父分类id'),
'pids' => Yii::t('app\common', '祖先id链,逗号分隔'),
'status' => Yii::t('app\common', '状态 0编辑 1发布 2隐藏'),
'display_order' => Yii::t('app\common', '显示顺序'),
'ctime' => Yii::t('app\common', '创建时间'),
'mtime' => Yii::t('app\common', '修改时间'),
'lang_id' => Yii::t('app\common', '语言id'),
];
}
public static function firstLevel(){
$data = self::find()->where(['=', 'pid', 0])->andWhere(['=', 'status', self::STATUS_ACTIVE])->andWhere(['=', 'lang', Yii::$app->language])->orderBy('display_order DESC')->asArray()->all();
return $data;
}
public static function nestedItems() {
$data = self::find()->where(['=', 'status', self::STATUS_ACTIVE])->andWhere(['=', 'lang', Yii::$app->language])->orderBy('display_order DESC')->asArray()->all();
$data = Nested::childrenWithTree($data);
foreach ($data['items'] as $k => $v) {
}
return $data;
}
}
<file_sep>/common/logic/Nested.php
<?php
/**
* @author <EMAIL>
* @date 08/10/2017
*/
namespace common\logic;
use yii\helpers\ArrayHelper;
/**
* Class Nested
* 多级
* 要求:数据list的每一行,含id、pid、pids、display_order字段
* @package common\models
*/
class Nested {
protected static $_with_pre;
/**
* @param $data
* @return array $ct ['items'=>[],'tree'=>[]]
*/
public static function childrenWithTree($data) {
$tree = [];
$items = [];
foreach ($data as $v) {
$items[$v['id']] = $v;
$now = &$tree;
$pids = empty($v['pids']) ? [] : explode(',', $v['pids']);
array_push($pids, $v['id']);
foreach ($pids as $pid) {
if (!array_key_exists($pid, $now)) {
$now[$pid] = [];
}
$now = &$now[$pid];
}
}
return [
'items' => $items,
'tree' => $tree
];
}
public static function getFirstLevel(&$ct){
return ArrayHelper::filter($ct['items'], array_keys($ct['tree']));
}
public static function getAncestors(&$ct, $id = null){
if(empty($id)){
return false;
}
$item = $ct['items'][$id];
$ks = explode(',', $item['pids']);
return ArrayHelper::filter($ct['items'], $ks);
}
public static function getSiblings(&$ct, $id){
if(empty($id)){
return false;
}
$item = $ct['items'][$id];
$ks = $item['pids'] == 0 ? '' : '[' . str_replace(',', '][', $item['pids']) . ']';
eval('$ids = $ct["tree"]' . $ks . ';');
return ArrayHelper::filter($ct['items'], array_keys($ids));
}
public static function getChildren(&$ct, $id){
if(empty($id)){
return false;
}
$item = $ct['items'][$id];
$ks = $item['pids'] == 0 ? '[' . $id . ']' : '[' . str_replace(',', '][', $item['pids']) . '][' . $id . ']';
eval('$ids = $ct["tree"]' . $ks . ';');
return ArrayHelper::filter($ct['items'], array_keys($ids));
}
public static function options($data = [], $filter_id = null, $with_root = true) {
$options = [];
$with_root && $options[] = '根/';
$tmp = self::childrenWithTree($data);
if (!empty($tmp['tree'])) {
self::fe($tmp['tree'], $tmp['items'], $options, $filter_id);
}
return $options;
}
public static function getPids($model) {
if (empty($model)) {
return '0';
}
$pids = empty($model->pids) ? '' : $model->pids . ',';
return $pids . $model->id;
}
private static function fe($tree, &$items, &$options, $filter_id) {
foreach ($tree as $k => $v) {
$pre = '';
if (static::$_with_pre) {
$level = $items[$k]['pids'] == '0' ? 1 : count(explode(',', $items[$k]['pids'])) + 1;
$pre = str_repeat('-', $level);
}
if (empty($filter_id) || $filter_id != $items[$k]['id']) {
$options[$items[$k]['id']] = $pre . $items[$k]['name'];
if (!empty($v)) {
self::fe($v, $items, $options, $filter_id);
}
}
}
}
}
<file_sep>/backend/views/artcate/_form.php
<?php
use yii\helpers\Html;
//use yii\widgets\ActiveForm;
use yii\bootstrap\ActiveForm;
use backend\widgets\DatetimepickerInput;
use common\logic\Lang;
use backend\models\Artcate;
use backend\logic\Nested;
/* @var $this yii\web\View */
/* @var $model backend\models\Artcate */
/* @var $lang_items array backend\models\Artcate */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="artcate-form">
<?php $form = ActiveForm::begin([]); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pid')->dropDownList(Nested::options(Artcate::find()->asArray()->all(), $model->id)) ?>
<!-- --><?//= $form->field($model, 'status')->textInput() ?>
<!-- --><?//= $form->field($model, 'ctime')->widget(DatetimepickerInput::className()) ?>
<?php if (count(Yii::$app->params['lang']) > 1) {
echo $form->field($model, 'lang')->dropDownList(Lang::items(), ['data-lang-switch' => $model->isNewRecord ? 'yes' : 'no']);
} ?>
<?=\backend\widgets\FooterBtn::widget()?>
<?php ActiveForm::end(); ?>
</div>
<file_sep>/backend/views/banner/_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use common\logic\Lang;
/* @var $this yii\web\View */
/* @var $model backend\models\Banner */
/* @var $form yii\widgets\ActiveForm */
$name_pic = Html::getInputName($model, 'pic');
if (!empty($model->pic)) {
$this->registerJs('$("<div><img style=\'width:300px;height:auto;\' src=\'/upload/image/' . $model->pic . '\'></div>").insertAfter(\'input[name="' . $name_pic . '"]\');');
}
?>
<script>
</script>
<div class="banner-form">
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($model, 'pic')->hiddenInput()->label('Banner图')?>
<?=$form->field($model, 'imageFile')->fileInput()->label($model->isNewRecord ? '图片上传' : '重新上传')?>
<?=$form->field($model, 'url')->textInput(['maxlength' => true, 'placeholder' => '以http(s):// 或 /(站内链接) 开头'])?>
<?=$form->field($model, 'title')->textInput(['maxlength' => true])?>
<?=$form->field($model, 'text')->textInput(['maxlength' => true])?>
<?=$form->field($model, 'code')->textInput(['maxlength' => true])?>
<?php if (count(Yii::$app->params['lang']) > 1) {
echo $form->field($model, 'lang')->dropDownList(Lang::items(), ['data-lang-switch' => $model->isNewRecord ? 'yes' : 'no']);
} ?>
<?=\backend\widgets\FooterBtn::widget(['btn_save_to_hide' => false])?>
<?php ActiveForm::end(); ?>
</div>
<file_sep>/backend/views/page/_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use common\logic\Lang;
/* @var $this yii\web\View */
/* @var $model backend\models\Page */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="page-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?php echo $form->field($model, 'summary')->textInput(['maxlength' => true, 'placeholder' => '留空则自动从<内容>字段获取']) ?>
<?=$form->field($model, 'content')->widget('kucha\ueditor\UEditor', ['clientOptions' => ['initialFrameHeight' => '300',]]);?>
<?php if (count(Yii::$app->params['lang']) > 1) {
echo $form->field($model, 'lang')->dropDownList(Lang::items(), ['data-lang-switch' => $model->isNewRecord ? 'yes' : 'no']);
} ?>
<?=\backend\widgets\FooterBtn::widget()?>
<?php ActiveForm::end(); ?>
</div>
<?php
$summaryName = Html::getInputName($model, 'summary');
$this->registerJs('
$("button.save,button.save-then-new,button.save-to-hide").click(function(){
var summaryInput = $("input[name=\'' . $summaryName . '\']");
if(!summaryInput.val()){
summaryInput.val(ueditor.getContentTxt().substr(0,100).trim());
}
});
');
?><file_sep>/backend/widgets/FooterBtn.php
<?php
/**
* @author <EMAIL>
* @date 21/10/2017
*/
namespace backend\widgets;
use yii\base\Widget;
use yii\helpers\Html;
use yii\helpers\Url;
class FooterBtn extends Widget {
public $btn_save = true;
public $btn_save_then_new = true;
public $btn_save_to_hide = true;
public $btn_cancel = true;
public function run() {
$this->getView()->registerJs('
var saveThenNew = $(".save-then-new");
if(saveThenNew.length > 0){
saveThenNew.click(function(){
$("input[name=save-then-new]").val("yes");
});}
var saveToHide = $(".save-to-hide");
if(saveToHide.length > 0){
saveToHide.click(function(){
$("input[name=save-to-hide]").val("yes");
});}');
$btns = '<div class="form-group footer-btns-div">';
$this->btn_save && $btns .= Html::submitButton('<i class="fa fa-fw fa-check"></i>保存', ['class' => 'btn btn-success save']);
$this->btn_save_then_new && $btns .= '<input type="hidden" name="save-then-new" value="no">' . Html::submitButton('<i class="fa fa-fw fa-plus text-success"></i>保存并新建', ['class' => 'btn btn-default save-then-new']);
$this->btn_save_to_hide && $btns .= '<input type="hidden" name="save-to-hide" value="no">' . Html::submitButton('<i class="fa fa-fw fa-file-text-o text-success"></i>存为草稿', ['class' => 'btn btn-default save-to-hide']);
$this->btn_cancel && $btns .= '<a href="' . Url::to(["index"]) . '" class="btn btn-default"><i class="fa fa-fw fa-close text-danger"></i>取消</a>';
$btns .= '</div>';
echo $btns;
}
}<file_sep>/backend/views/artcate/index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use common\models\Artcate;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = '文章分类';
$this->params['breadcrumbs'][] = $this->title;
\backend\widgets\NestViewAsset::register($this);
$js = 'jQuery(document).ready(function ($){
var sortableList = new $.JSortableList("#sortable", "asc" , "'.\yii\helpers\Url::to(['order']).'","","1");
});';
$this->registerJs($js);
?>
<div class="artcate-index">
<p>
<?=Html::a('<i class="fa fa-fw fa-plus"></i>添加'.$this->title, ['create'], ['class' => 'btn btn-success'])?>
</p>
<table class="table table-striped">
<thead>
<tr>
<th>排序</th>
<th>名称</th>
<th>状态</th>
<th>修改时间</th>
<th>语种</th>
<th>操作</th>
</tr>
</thead>
<tbody id="sortable">
<?php $langs = Yii::$app->params['lang'];
foreach ($data as $v) { ?>
<tr level="<?=$v['nested_level']?>" sortable-group-id="<?=$v['pid']?>" item-id="<?=$v['id']?>" parents="<?=str_replace(',', ' ', $v['pids'])?>">
<td><i class="fa fa-fw fa-arrows-v sortable-handler" style="cursor: move;"></i></td>
<td><?=$v['name']?></td>
<td><?=$v['status'] == Artcate::STATUS_ACTIVE ? '<span class="text-green">发布</span>' : ($v['status'] == Artcate::STATUS_EDIT ? '<span class="">编辑中</span>' : ($v['status'] == Artcate::STATUS_HIDE ? '<span class="text-muted">隐藏</span>' : ''))?></td>
<td><?=date('Y-m-d H:i', $v['mtime'])?></td>
<td><?='<img src="/images/' . $langs[$v['lang']]['image'] . '.gif">'?></td>
<td class="action-btn-td"><?=Html::a('<i class="fa fa-pencil-square-o"></i>', [
'update',
'id' => $v['id']
], [
'class' => 'btn btn-sm btn-default modify-btn',
'aria-label' => '修改',
]) . Html::a($v['status'] == Artcate::STATUS_HIDE ? '<i class="fa fa-fw fa-toggle-off text-muted"></i>' : '<i class="fa fa-fw fa-toggle-on text-green"></i>', [
'hide',
'id' => $v['id']
], [
'class' => 'btn btn-sm btn-default hide-btn',
'aria-label' => '隐藏切换',
'data-pjax' => '0',
]) . Html::a('<span class="fa fa-trash"></span>', [
'delete',
'id' => $v['id']
], [
'title' => Yii::t('yii', 'Delete'),
'aria-label' => Yii::t('yii', 'Delete'),
'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
'data-method' => 'post',
'data-pjax' => '0',
'class' => 'btn btn-sm btn-default',
]);?></td>
</tr><?php } ?>
</tbody>
</table>
</div>
<file_sep>/backend/views/config/index.php
<?php
use backend\widgets\DatetimepickerInputAsset;
use yii\helpers\Url;
/* @var $this yii\web\View */
DatetimepickerInputAsset::register($this);
$this->title = '全局配置';
$js = '$("input[name=site_maintain_time]").datetimepicker({format: "Y-m-d H:i:s",lang:"ch"});
$("#langSwitch").find("option[value=\'' . $lang_code . '\']").prop("selected", true);$("#langSwitch").change(function(){location.href = \''.Url::to(['index']).'&lang_code=\'+$(this).val();});
';
$this->registerJs($js);
?>
<form class="form-horizontal" method="post" enctype="multipart/form-data">
<input name="_csrf-backend" type="hidden" id="_csrf" value="<?=Yii::$app->request->csrfToken?>">
<div class="box-body">
<div class="form-group">
<label class="col-sm-2 control-label">站点维护</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="site_maintain_time" value="<?=$config['site_maintain_time']?>" placeholder="开始时间">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">按语言配置</label>
<div class="col-sm-10">
<select class="form-control" name="lang_code" id="langSwitch">
<?php foreach ($config['lang'] as $k=>$v){?>
<option value="<?=$v['code']?>"><?=$v['title_native']?></option>
<?php }?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">站点名称</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="lang[<?=$lang_code?>][site_name]" value="<?=$config['lang'][$lang_code]['site_name']?>" placeholder="">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">站点Logo</label>
<div class="col-sm-10">
<img src="/upload/image/<?=$config['lang'][$lang_code]['site_logo']?>" style="width: 300px;height: auto;">
<input type="hidden" name="lang[<?=$lang_code?>][site_logo]" value="<?=$config['lang'][$lang_code]['site_logo']?>" placeholder="">
<input type="file" name="site_logo_file">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">首页#关于我们#标题</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="lang[<?=$lang_code?>][about_us_title]" value="<?=isset($config['lang'][$lang_code]['about_us_title'])?$config['lang'][$lang_code]['about_us_title']:''?>" placeholder="例:关于我们 (留空则不显示)">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">首页#关于我们#内容</label>
<div class="col-sm-10">
<textarea class="form-control" name="lang[<?=$lang_code?>][about_us_text]" placeholder="留空则不显示"><?=isset($config['lang'][$lang_code]['about_us_text'])?$config['lang'][$lang_code]['about_us_text']:''?></textarea>
</div>
</div>
<div class="form-group hidden">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox"> Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-2">
<button type="submit" class="btn btn-success"><i class="fa fa-fw fa-check"></i>保存</button>
<a href="<?=Url::to(['site/index'])?>" class="btn btn-default" style="margin-left: 5px;"><i class="fa fa-fw fa-close text-danger"></i>取消</a>
</div>
</div>
</div>
</form><file_sep>/backend/logic/Upload.php
<?php
/**
* @author <EMAIL>
* @date 21/10/2017
*/
namespace backend\logic;
use yii\web\UploadedFile;
/**
* Class Nested
* 要求:数据list的每一行,含id、pid、pids字段
* @package common\models
*/
class Upload {
public static function img($name) {
$file = UploadedFile::getInstanceByName($name);
if(empty($file)){
return null;
}
$sub = date('Ymd') . '/';
$dir = $_SERVER['DOCUMENT_ROOT'] . '/upload/image/' . $sub;
if (!file_exists($dir) && !mkdir($dir, 0777, true)) {
return false;
} else if (!is_writeable($dir)) {
return false;
}
$fileName = time() . mt_rand(100000, 999999) . '.' . $file->extension;
$file->saveAs($dir . $fileName);
return $sub . $fileName;
}
}
<file_sep>/backend/widgets/DatetimepickerInputAsset.php
<?php
/**
* @author <EMAIL>
* @date 29/09/2017
*/
namespace backend\widgets;
use yii\web\AssetBundle;
/**
* The asset bundle for the [[DatetimepickerInput]] widget.
*
* Includes client assets of [jQuery input mask plugin](https://github.com/RobinHerbots/jquery.inputmask).
*
*/
class DatetimepickerInputAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $js = [
'js/jquery.datetimepicker.js',
];
public $css = [
'css/jquery.datetimepicker.css',
];
public $depends = [
'yii\web\JqueryAsset',
'yii\bootstrap\BootstrapAsset',
];
}
<file_sep>/common/models/Menu.php
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "qycms_menu".
*
* @property integer $id
* @property integer $pid
* @property string $pids
* @property string $name
* @property string $content_type
* @property string $content
* @property integer $ctime
* @property integer $mtime
* @property string $lang
*/
class Menu extends \yii\db\ActiveRecord
{
const CONTENT_TYPE = [
'URL'=>'外部链接',
'ARTCATE'=>'文章分类',
//'ARTICLE'=>'文章',
'PROCATE'=>'产品分类',
//'PRODUCT'=>'产品',
'PAGE'=>'单页',
];
/**
* @inheritdoc
*/
public static function tableName()
{
return 'qycms_menu';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['pid', 'ctime', 'mtime'], 'integer'],
[['name', 'content', 'ctime', 'mtime'], 'required'],
[['content'], 'string'],
[['name'], 'string', 'max' => 64],
[['content_type'], 'string', 'max' => 32],
[['pids'], 'string', 'max' => 32],
[['lang'], 'string', 'max' => 7],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('common', 'id'),
'pid' => Yii::t('common', '父菜单'),
'pids' => Yii::t('common', '祖先id链'),
'name' => Yii::t('common', '名称'),
'content_type' => Yii::t('common', '内容类型'),
'content' => Yii::t('common', '内容'),
'ctime' => Yii::t('common', '创建时间'),
'mtime' => Yii::t('common', '修改时间'),
'lang_id' => Yii::t('common', '语言'),
];
}
}
<file_sep>/backend/controllers/ConfigController.php
<?php
namespace backend\controllers;
use yii;
use yii\helpers\ArrayHelper;
use backend\logic\Upload;
class ConfigController extends \yii\web\Controller
{
public function actionIndex()
{
$lang_code = Yii::$app->request->get('lang_code', 'zh-CN');
$post = Yii::$app->request->post();
$path = Yii::$app->basePath . '/../common/config/params-local.php';
$config = require $path;
if (!empty($post)) {
unset($post['_csrf-backend']);
$lang_code = ArrayHelper::remove($post, 'lang_code');
$filepath = Upload::img('site_logo_file');
if($filepath){
$post['lang'][$lang_code]['site_logo'] = $filepath;
}
$config = ArrayHelper::merge($config, $post);
file_put_contents($path, '<?php return ' . var_export($config, true) . ';');
}
return $this->render('index', [
'config' => $config,
'lang_code' => $lang_code,
]);
}
}
<file_sep>/backend/views/product/_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use common\logic\Lang;
use backend\logic\Nested;
use backend\models\Procate;
/* @var $this yii\web\View */
/* @var $model backend\models\Product */
/* @var $form yii\widgets\ActiveForm */
\backend\widgets\AjaxfileAsset::register($this);
$upload_url = \yii\helpers\Url::to(['site/upload']);
empty($model->pics) && $model->pics = '[]';
$picsName = Html::getInputName($model, 'pics');
$this->registerJs('
var pics = ' . $model->pics . ';
var picsWrapper = $("#product-pic-wrapper");
var picTemplate = $("#pic-template");
$("input[type=file]").ajaxfileupload({
action: "' . $upload_url . '",
params: {
"_csrf-backend": "' . Yii::$app->request->getCsrfToken() . '"
},
onComplete: function(res) {
console.log(res);
if(res.errno==0){
pics.push(res.filepath);
renderPics();
}
},
onCancel: function() {
console.log("no file selected");
}
});
renderPics();
function renderPics(){
console.log(pics);
picsWrapper.empty();
pics.forEach(function(v,i){
picTemplate.children().first().clone().appendTo(picsWrapper).find(".product-pic").attr("src","/upload/image/"+v);
});
$(\'input[name="'.$picsName.'"]\').val(pics.join(","));
}
');
?>
<div class="product-form">
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($model, 'name')->textInput(['maxlength' => true])?>
<?=$form->field($model, 'cid')->dropDownList(Nested::options(Procate::find()->asArray()->all(), null, false))?>
<?=$form->field($model, 'pics')->hiddenInput()?>
<div id="product-pic-wrapper"></div>
<input type="file" id="pic-file" name="pic_file">
<?php //echo $form->field($model, 'fields')->textInput(['maxlength' => true])?>
<?=$form->field($model, 'content')->widget('kucha\ueditor\UEditor', ['clientOptions' => ['initialFrameHeight' => '300',]]);?>
<?php if (count(Yii::$app->params['lang']) > 1) {
echo $form->field($model, 'lang')->dropDownList(Lang::items(), ['data-lang-switch' => $model->isNewRecord ? 'yes' : 'no']);
} ?>
<?=\backend\widgets\FooterBtn::widget()?>
<?php ActiveForm::end(); ?>
</div>
<div id="pic-template"><div style="display: inline-block;"><img class="product-pic" src="" style="width: 80px;max-height: 100%;"></div></div><file_sep>/frontend/messages/zh-CN/product.php
<?php
/**
* @author <EMAIL>
* @date 14/10/2017
*/
return [
'Procates' => '产品',
'Create Procate' => '添加产品',
];
<file_sep>/backend/widgets/NestViewAsset.php
<?php
/**
* @author <EMAIL>
* @date 29/09/2017
*/
namespace backend\widgets;
use yii\web\AssetBundle;
/**
* The asset bundle for the [[DatetimepickerInput]] widget.
*
* Includes client assets of [jQuery input mask plugin](https://github.com/RobinHerbots/jquery.inputmask).
*
*/
class NestViewAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $js = [
'js/jquery-ui.min.js',
'js/sortablelist.js',
];
public $css = [
'css/jquery-ui.css',
'css/sortablelist.css',
];
public $depends = [
'yii\web\JqueryAsset',
'yii\bootstrap\BootstrapAsset',
];
}
<file_sep>/frontend/views/products/index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\Url;
use frontend\logic\Nested;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
$firstLevel = Nested::getFirstLevel($ct);
$ancestors = Nested::getAncestors($ct, $id);
$siblings = Nested::getSiblings($ct, $id);
$children = Nested::getChildren($ct, $id);
if(empty($procate)){
$this->title = Yii::t('app/product', 'Procates');
$this->params['breadcrumbs'][] = $this->title;
}else{
$this->title = $procate['name'];
$this->params['breadcrumbs'][] = ['label' => Yii::t('app/product', 'Procates'), 'url' => ['index'],];
foreach ($ancestors as $v){
$this->params['breadcrumbs'][] = ['label' => $v['name'], 'url' => ['index', 'id'=>$v['id']]];
}
$this->params['breadcrumbs'][] = $procate['name'];
}
$this->registerCss('.chip{border-radius: 0;}');
$this->registerJs('
$("#cate_switch_div > select").material_select();
$("#cate_switch_div select").change(function(){location.href=$(this).val();});');
?>
<div class="procate-index">
<div class="row">
<div class="col l3 s12">
<?php if (Yii::$app->devicedetect->isMobile()) { ?>
<div class="input-field" id="cate_switch_div">
<select style="color: blue;">
<?php if(empty($procate)){?>
<option value="<?=Url::to(['index'])?>">全部</option>
<?php foreach ($firstLevel as $v){?>
<option value="<?=Url::to(['index', 'id'=>$v['id']])?>"><?=$v['name']?></option>
<?php } ?>
<?php }else{ ?>
<?php foreach ($siblings as $v){?>
<option value="<?=Url::to(['index', 'id'=>$v['id']])?>"<?=$procate['id'] == $v['id'] ? ' selected' : ''?>><?=$v['name']?></option>
<?php } ?>
<?php }?>
</select>
</div>
<?php } else { ?>
<div class="collection">
<?php if(empty($procate)){?>
<?php foreach ($firstLevel as $v){?>
<a href="<?=Url::to(['index', 'id'=>$v['id']])?>" class="collection-item"><?=$v['name']?></a>
<?php } ?>
<?php }else{ ?>
<?php foreach ($siblings as $v){?>
<a href="<?=Url::to(['index', 'id'=>$v['id']])?>" class="collection-item<?=$procate['id'] == $v['id'] ? ' active' : ''?>"><?=$v['name']?></a>
<?php } ?>
<?php }?>
</div>
<?php } ?>
</div>
<div class="col l9 s12">
<?php if(!empty($children)){?>
<div>
<?php foreach ($children as $v){?>
<div class="chip">
<a href="<?=Url::to(['index', 'id'=>$v['id']])?>" class="collection-item"><?=$v['name']?></a>
</div>
<?php } ?>
</div>
<?php }?>
<?php foreach ($items as $v){?>
<div class="card card-product">
<p>
<a class="teal-text" href="<?=Url::to(['view', 'id'=>$v['id']])?>"><?=$v['name']?></a>
<span class="secondary-content grey-text"><?=date('Y-m-d', $v['mtime'])?></span></p>
</div>
<?php }?>
</div>
</div>
</div>
<file_sep>/backend/views/procate/_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use common\logic\Lang;
use backend\models\Procate;
use backend\logic\Nested;
/* @var $this yii\web\View */
/* @var $model backend\models\Procate */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="procate-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pid')->dropDownList(Nested::options(Procate::find()->asArray()->all(), $model->id)) ?>
<?php if (count(Yii::$app->params['lang']) > 1) {
echo $form->field($model, 'lang')->dropDownList(Lang::items(), ['data-lang-switch' => $model->isNewRecord ? 'yes' : 'no']);
} ?>
<?=\backend\widgets\FooterBtn::widget()?>
<?php ActiveForm::end(); ?>
</div>
<file_sep>/frontend/assets/AppAsset.php
<?php
namespace frontend\assets;
use yii\web\AssetBundle;
/**
* Main frontend application asset bundle.
*/
class AppAsset extends AssetBundle {
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
// 'css/site.css',
//'css/materialize.font.css', append into materialize.min.css by qingyu
[
'css/materialize.min.css',
'media' => 'screen,projection'
],
[
'css/style.css',
'media' => 'screen,projection'
],
];
public $js = [
'js/materialize.min.js',
];
public $depends = [
'yii\web\JqueryAsset',
// 'yii\web\YiiAsset',
// 'yii\bootstrap\BootstrapAsset',
];
}
<file_sep>/backend/models/Banner.php
<?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "qycms_banner".
*
* @property integer $id
* @property string $pic
* @property string $url
* @property string $title
* @property string $text
* @property string $code
* @property integer $display_order
* @property string $lang
*/
class Banner extends \common\models\Banner
{
/**
* @var \yii\web\UploadedFile
*/
public $imageFile;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'qycms_banner';
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), []);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'id',
'pic' => '路径',
'url' => '跳转地址',
'title' => '标题文字',
'text' => '副标题',
'code' => '嵌入代码',
'display_order' => '显示顺序',
'lang' => '语种',
];
}
}
<file_sep>/frontend/controllers/ProductsController.php
<?php
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use frontend\models\Procate;
use frontend\models\Product;
/**
* ProductsController implements the CRUD actions for Procate model.
*/
class ProductsController extends Controller {
/**
* @inheritdoc
*/
public function behaviors() {
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
public function actionIndex($id = null) {
$ct = Procate::nestedItems();
if ($id) {
$procate = $ct['items'][$id];
//var_dump($procate);exit;
if (empty($procate) || $procate['status'] != Procate::STATUS_ACTIVE) {
throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
}
$items = Product::find()->where(['=', 'cid', $id])->andWhere(['=', 'status', Product::STATUS_ACTIVE])->andWhere(['=', 'lang', Yii::$app->language])->asArray()->offset(0)->limit(20)->all();
} else {
$procate = [];
$items = Product::find()->where(['=', 'status', Product::STATUS_ACTIVE])->andWhere(['=', 'lang', Yii::$app->language])->asArray()->offset(0)->limit(20)->all();
}
return $this->render('index', [
'ct' => $ct,
'id' => $id,
'procate' => $procate,
'items' => $items,
]);
}
public function actionView($id) {
$product = $this->findOne($id);
$ct = Procate::nestedItems();
return $this->render('view', [
'model' => $product,
'ct' => $ct,
]);
}
protected function findModel($id) {
$model = Procate::findOne($id);
if ($model == null || $model->status != Procate::STATUS_ACTIVE) {
throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
}
return $model;
}
protected function findOne($id) {
$model = Product::findOne($id);
if ($model == null || $model->status != Product::STATUS_ACTIVE) {
throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
}
return $model;
}
}
<file_sep>/backend/views/menu/_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use common\logic\Lang;
use backend\models\Menu;
use backend\models\Artcate;
use backend\logic\Nested;
use backend\models\Page;
use yii\helpers\Url;
use backend\models\Procate;
/* @var $this yii\web\View */
/* @var $model backend\models\Menu */
/* @var $form yii\widgets\ActiveForm */
$js = '$(document).ready(function () {
var editPageUrl = "'. Url::to(['page/update', 'id'=>'1']) .'";
$(".type").appendTo($("#form-tmp"));
$(\'select[name="Menu[content_type]"]\').change(function () {
$(".menu-form .type").appendTo($("#form-tmp"));
$("#TYPE-"+$(this).val()).insertAfter($(this).parent());
}).change();
$(\'select[name="Menu[content][page]"]\').change(function(){
$("#type-page-edit").attr("href", editPageUrl.replace(/id=\d+/,"id="+$(this).val()));
}).change();
});';
$this->registerJs($js);
?>
<div class="menu-form" style="width: 60%;">
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($model, 'name')->textInput(['maxlength' => true])?>
<?=$form->field($model, 'pid')->dropDownList(Nested::options(Menu::find()->orderBy('display_order DESC')->asArray()->all(), $model->id))?>
<?=$form->field($model, 'content_type')->dropDownList(Menu::CONTENT_TYPE)?>
<div class="type" id="TYPE-URL">
<?php $urlDefault = $model->isNewRecord ? ['value' => 'https://qingyu.me/'] : [] ?>
<?=$form->field($model, 'content[url]')->textInput(array_merge([
'maxlength' => true,
'name' => 'Menu[content][url]',
], $urlDefault))->label('链接地址')?>
</div>
<div class="type" id="TYPE-ARTCATE">
<?=$form->field($model, 'content[artcate]')->dropDownList(Nested::options(Artcate::find()->orderBy('display_order DESC')->asArray()->all(), null, false))->label('分类选择')?>
</div>
<div class="type" id="TYPE-PROCATE">
<?=$form->field($model, 'content[procate]')->dropDownList(['根'] + Nested::options(Procate::find()->orderBy('display_order DESC')->asArray()->all(), null, false))->label('分类选择')?>
</div>
<div class="type" id="TYPE-PAGE" style="position: relative;">
<?=$form->field($model, 'content[page]')->dropDownList(Page::options())->label('单页选择')?>
<?=Html::a('编辑单页', '',['target'=>'_blank',
'id' => 'type-page-edit',
'class'=> 'btn btn-default',
'style'=>'position: absolute; top: 40%;left: 102%;'])?>
</div>
<?php if (count(Yii::$app->params['lang']) > 1) {
echo $form->field($model, 'lang')->dropDownList(Lang::items(), ['data-lang-switch' => $model->isNewRecord ? 'yes' : 'no']);
} ?>
<?=\backend\widgets\FooterBtn::widget(['btn_save_to_hide' => false])?>
<?php ActiveForm::end(); ?>
</div>
<div id="form-tmp" style="display: none;"></div>
<file_sep>/frontend/views/layouts/main.php
<?php
/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use frontend\assets\AppAsset;
use common\widgets\Alert;
use frontend\models\Menu;
use yii\helpers\Url;
$menu = Menu::nestedItems();
$lang = Yii::$app->params['lang'];
$clang = Yii::$app->language;
$artcates = \frontend\models\Artcate::firstLevel();
$procates = \frontend\models\Procate::firstLevel();
$this->registerCss('
#main-content{margin-top:15px;}
#logo-container{max-width: 30%;}
#logo-container>img{width:100%; max-height: 100%; vertical-align: middle;}
#main-content img{max-width: 100%; height: auto;}
.ueditor-content img{}
@media only screen and (max-width: 600px) {
#logo-container{max-width: 80%;}
#lang_switch_div .select-wrapper input.select-dropdown {
width: 80px;
}
#breadcrumbs_nav{height:auto;}
#breadcrumbs_nav li{float:none;display:inline-block;}
}
.card-article{padding: 0.05rem 0.75rem;}
.card-article > p{line-height: 1rem;}
.footer-ul>li>a{display:block;padding:5px 0;}
');
AppAsset::register($this);
$this->registerJs('
$(function(){
$(".button-collapse").sideNav();
$(".parallax").parallax();
$(".dropdown-button").dropdown({ hover: true,belowOrigin:true });
var minHeight = window.innerHeight - $("nav").css("height").slice(0,-2) - $("footer").css("height").slice(0,-2) - 30 + "px";
$("#main-content").css("minHeight", minHeight);
$("#lang_switch").material_select();
$("#lang_switch").change(function(){location.href="/"+$(this).val();});
});
');
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?=Yii::$app->language?>">
<head>
<meta charset="<?=Yii::$app->charset?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?=Html::csrfMetaTags()?>
<title><?=Html::encode($this->title)?></title>
<?php $this->head() ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<?php $this->beginBody() ?>
<nav class="white" role="navigation">
<div class="nav-wrapper container">
<a id="logo-container" href="/" class="brand-logo"><img src="/upload/image/<?=$lang[$clang]['site_logo']?>"></a>
<?php if (count(Yii::$app->params['lang']) > 1) { ?>
<div class="input-field right" id="lang_switch_div">
<img src="/images/<?=$lang[$clang]['image']?>.gif">
<select id="lang_switch" style="color: blue;">
<?php foreach ($lang as $k => $v) { ?>
<option value="<?=$v['code']?>"<?=$clang == $k ? ' selected' : ''?>><?=$v['title_native']?></option>
<?php } ?>
</select>
</div>
<?php } ?>
<?php if (Yii::$app->devicedetect->isMobile()) { ?>
<ul id="nav-mobile" class="side-nav">
<?php foreach ($menu['tree'] as $id => $v) { ?>
<?php if(empty($v)){?>
<li><a href="<?=$menu['items'][$id]['url']?>"><?=$menu['items'][$id]['name']?></a></li>
<?php }else { ?>
<li><a href="<?=$menu['items'][$id]['url']?>"><?=$menu['items'][$id]['name']?></a></li>
<?php foreach ($v as $id2 => $v2) { ?>
<li style="line-height: 38px;height: 38px;"><a href="<?=$menu['items'][$id2]['url']?>">——<?=$menu['items'][$id2]['name']?></a></li>
<?php }?>
<?php }?>
<?php } ?>
</ul>
<a href="#" data-activates="nav-mobile" class="button-collapse"><i class="material-icons">menu</i></a>
<?php } else { ?>
<ul class="right hide-on-med-and-down">
<?php foreach ($menu['tree'] as $id => $v) { ?>
<?php if(empty($v)){?>
<li><a href="<?=$menu['items'][$id]['url']?>"><?=$menu['items'][$id]['name']?></a></li>
<?php }else { ?>
<li><a class="dropdown-button" data-activates="dropdown-<?=$id?>" href="<?=$menu['items'][$id]['url']?>"><?=$menu['items'][$id]['name']?></a></li>
<ul id="dropdown-<?=$id?>" class="dropdown-content">
<?php foreach ($v as $id2 => $v2) { ?>
<li><a href="<?=$menu['items'][$id2]['url']?>"><?=$menu['items'][$id2]['name']?></a></li>
<?php }?>
</ul>
<?php }?>
<?php } ?>
</ul>
<?php } ?>
</div>
</nav>
<?php if (!empty($this->params['breadcrumbs'])) { ?>
<nav id="breadcrumbs_nav">
<div class="container"><?=Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
])?></div>
</nav>
<?php } ?>
<div id="main-content" class="container"><?=$content?></div>
<footer class="page-footer teal">
<div class="container">
<div class="row">
<?php if(!empty($lang[$clang]['about_us_title'])){ ?>
<div class="col l6 s12">
<h5 class="white-text"><?=$lang[$clang]['about_us_title']?></h5>
<p class="grey-text text-lighten-4"><?=$lang[$clang]['about_us_text']?></p>
</div>
<?php }?>
<?php if(!empty($artcates)){?>
<div class="col l3 s12">
<h5 class="white-text"><?=Yii::t('app/article', 'Artcates')?></h5>
<ul class="footer-ul">
<?php foreach ($artcates as $v){?>
<li><a class="white-text" href="<?=Url::to(['articles/index','id'=>$v['id']])?>"><?=$v['name']?></a></li>
<?php }?>
</ul>
</div>
<?php }?>
<?php if(!empty($procates)){?>
<div class="col l3 s12">
<h5 class="white-text"><?=Yii::t('app/common', 'Procates')?></h5>
<ul class="footer-ul">
<?php foreach ($procates as $v){?>
<li><a class="white-text" href="<?=Url::to(['products/index','id'=>$v['id']])?>"><?=$v['name']?></a></li>
<?php }?>
</ul>
</div>
<?php }?>
</div>
</div>
<div class="footer-copyright">
<div class="container">
© <?=date('Y')?> <a class="brown-text text-lighten-3" href="/"><?=$lang[$clang]['site_name']?></a>
</div>
</div>
</footer>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
<file_sep>/common/models/Product.php
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "qycms_product".
*
* @property integer $id
* @property string $name
* @property integer $cid
* @property string $pics
* @property string $fields
* @property string $content
* @property integer $status
* @property integer $ctime
* @property integer $mtime
* @property string $lang
*/
class Product extends \yii\db\ActiveRecord
{
const STATUS_ACTIVE = 1;
const STATUS_EDIT = 2;
const STATUS_HIDE = 3;
const STATUS_DELETED = 4;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'qycms_product';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['cid', 'status', 'ctime', 'mtime', 'hits'], 'integer'],
[['content', 'name'], 'required'],
[['name'], 'string', 'max' => 64],
[['pics', 'fields'], 'string', 'max' => 2000],
[['lang'], 'string', 'max' => 7],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('common', 'id'),
'name' => Yii::t('common', '名称'),
'cid' => Yii::t('common', '分类id'),
'pics' => Yii::t('common', '图片,json格式'),
'fields' => Yii::t('common', '附件字段,json格式'),
'content' => Yii::t('common', '内容'),
'status' => Yii::t('common', '状态'),
'ctime' => Yii::t('common', '创建时间'),
'mtime' => Yii::t('common', '修改时间'),
'hits' => Yii::t('common', '浏览数'),
'lang_id' => Yii::t('common', '语言'),
];
}
}
<file_sep>/frontend/views/articles/home.php
<?php
/**
* @author <EMAIL>
* @date 25/10/2017
*/
/* @var $this yii\web\View */
?>
<div>
<?=$this->defaultExtension?>
<p>article-home</p>
</div>
<file_sep>/backend/models/Article.php
<?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "qycms_article".
*
* @property integer $id
* @property string $name
* @property integer $cid
* @property string $summary
* @property string $content
* @property integer $status
* @property integer $ctime
* @property integer $mtime
* @property string $lang
*/
class Article extends \common\models\Article
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'qycms_article';
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[
'status',
'default',
'value' => self::STATUS_ACTIVE
],
]);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'id',
'name' => '名称',
'cid' => '分类',
'summary' => '摘要',
'content' => '内容',
'status' => '状态',
'ctime' => '创建时间',
'mtime' => '修改时间',
'lang' => '语种',
];
}
/**
* @inheritdoc
* @return ArticleQuery the active query used by this AR class.
*/
public static function find()
{
return new ArticleQuery(get_called_class());
}
}
<file_sep>/frontend/views/page/view.php
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model frontend\models\Page */
$this->title = $model->name;
$this->params['breadcrumbs'][] = $this->title;
$this->registerJsFile('/js/ueditor.parse.js');
$this->registerJs('uParse(".page-view", {
rootPath: "../"
});');
?>
<div class="page-view ueditor-content">
<?=$model->content?>
</div>
<file_sep>/frontend/views/site/index.php
<?php
use frontend\models\Banner;
/* @var $this yii\web\View */
$banner = Banner::find()->where(['=', 'lang', Yii::$app->language])->orderBy('display_order DESC')->asArray()->all();
$this->title = 'My Yii Application';
$this->registerCssFile('/css/swiper.min.css');
$this->registerJsFile('/js/swiper.min.js');
$this->registerCss('
.swiper-slide>a{display:block;}
.swiper-slide>a>img{width:100%;height:30%;}
.swiper-slide>span{position:absolute;left:50%;top:70%;}
');
$this->registerJs('
var mySwiper = new Swiper (".swiper-container", {
loop: true
});
');
?>
<div class="site-index">
<?php if(!empty($banner)){?>
<div class="swiper-container">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
<?php foreach ($banner as $item) { ?>
<div class="swiper-slide">
<a href="<?=$item['url']?>"><img src="/upload/image/<?=$item['pic']?>"></a>
<span><?=$item['title']?></span>
</div>
<?php }?>
</div>
<div class="swiper-pagination"></div>
<!-- <div class="swiper-scrollbar"></div>-->
</div>
<?php }?>
<div id="index-banner" class="parallax-container">
<div class="section no-pad-bot">
<div class="container">
<br><br>
<h1 class="header center teal-text text-lighten-2">Parallax Template</h1>
<div class="row center">
<h5 class="header col s12 light">A modern responsive front-end framework based on Material Design</h5>
</div>
<div class="row center">
<a href="http://materializecss.com/getting-started.html" id="download-button" class="btn-large waves-effect waves-light teal lighten-1">Get Started</a>
</div>
<br><br>
</div>
</div>
<div class="parallax"><img src="/img/background1.jpg" alt="Unsplashed background img 1"></div>
</div>
<div class="container">
<div class="section">
<!-- Icon Section -->
<div class="row">
<div class="col s12 m4">
<div class="icon-block">
<h2 class="center brown-text"><i class="material-icons">flash_on</i></h2>
<h5 class="center">Speeds up development</h5>
<p class="light">We did most of the heavy lifting for you to provide a default stylings that incorporate our custom components. Additionally, we refined animations and transitions to provide a smoother experience for developers.</p>
</div>
</div>
<div class="col s12 m4">
<div class="icon-block">
<h2 class="center brown-text"><i class="material-icons">group</i></h2>
<h5 class="center">User Experience Focused</h5>
<p class="light">By utilizing elements and principles of Material Design, we were able to create a framework that incorporates components and animations that provide more feedback to users. Additionally, a single underlying responsive system across all platforms allow for a more unified user experience.</p>
</div>
</div>
<div class="col s12 m4">
<div class="icon-block">
<h2 class="center brown-text"><i class="material-icons">settings</i></h2>
<h5 class="center">Easy to work with</h5>
<p class="light">We have provided detailed documentation as well as specific code examples to help new users get started. We are also always open to feedback and can answer any questions a user may have about Materialize.</p>
</div>
</div>
</div>
</div>
</div>
<div class="parallax-container valign-wrapper">
<div class="section no-pad-bot">
<div class="container">
<div class="row center">
<h5 class="header col s12 light">A modern responsive front-end framework based on Material Design</h5>
</div>
</div>
</div>
<div class="parallax"><img src="/img/background2.jpg" alt="Unsplashed background img 2"></div>
</div>
<div class="container">
<div class="section">
<div class="row">
<div class="col s12 center">
<h3><i class="mdi-content-send brown-text"></i></h3>
<h4>Contact Us</h4>
<p class="left-align light">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam scelerisque id nunc nec volutpat. Etiam pellentesque tristique arcu, non consequat magna fermentum ac. Cras ut ultricies eros. Maecenas eros justo, ullamcorper a sapien id, viverra ultrices eros. Morbi sem neque, posuere et pretium eget, bibendum sollicitudin lacus. Aliquam eleifend sollicitudin diam, eu mattis nisl maximus sed. Nulla imperdiet semper molestie. Morbi massa odio, condimentum sed ipsum ac, gravida ultrices erat. Nullam eget dignissim mauris, non tristique erat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;</p>
</div>
</div>
</div>
</div>
<div class="parallax-container valign-wrapper">
<div class="section no-pad-bot">
<div class="container">
<div class="row center">
<h5 class="header col s12 light">A modern responsive front-end framework based on Material Design</h5>
</div>
</div>
</div>
<div class="parallax"><img src="/img/background3.jpg" alt="Unsplashed background img 3"></div>
</div>
</div>
<file_sep>/frontend/views/articles/view.php
<?php
use yii\helpers\Html;
use frontend\logic\Nested;
/* @var $this yii\web\View */
/* @var $model frontend\models\Artcate */
$ancestors = Nested::getAncestors($ct, $model->cid);
$cates = $ancestors;
$cates[] = $ct['items'][$model->cid];
$this->title = $model->name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app/article', 'Artcates'), 'url' => ['index']];
foreach ($cates as $v){
$this->params['breadcrumbs'][] = ['label' => $v['name'], 'url' => ['index', 'id'=>$v['id']]];
}
$this->params['breadcrumbs'][] = $this->title;
$this->registerJsFile('/js/ueditor.parse.js');
$this->registerJs('uParse(".artcate-view", {
rootPath: "../"
});');
?>
<h1><?=Html::encode($this->title)?></h1>
<div class="artcate-view">
<?=$model->content?>
</div>
<file_sep>/environments/dev/common/config/params-local.php
<?php
return [
'lang' => [
/**
* array format, key refers to the language tag, value is about its configurations
* @see http://en.wikipedia.org/wiki/IETF_language_tag
*/
'zh-CN' => [
'code' => 'zh-CN',
'title' => '中文',
'title_native' => '中文',
'image' => 'zh_cn',
'site_name' => '青鱼工作室',
'order' => 0,
'site_logo' => 'abc',
],
/*
'en-US' => [
'code' => 'en-US',
'title' => '英文',
'title_native' => 'English',
'image' => 'en_us',
'site_name' => 'Qingyu Co. Ltd.',
'order' => 1,
'site_logo' => 'abc',
],
*/
],
'site_maintain_time' => '',
];
<file_sep>/frontend/models/Banner.php
<?php
namespace frontend\models;
use Yii;
/**
* This is the model class for table "qycms_banner".
*
* @property integer $id
* @property string $pic
* @property string $url
* @property string $title
* @property string $text
* @property string $code
* @property integer $display_order
* @property integer $lang_id
*/
class Banner extends \common\models\Banner
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'qycms_banner';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['display_order', 'lang_id'], 'integer'],
[['pic', 'url', 'title', 'text'], 'string', 'max' => 255],
[['code'], 'string', 'max' => 2000],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app/common', 'id'),
'pic' => Yii::t('app/common', 'path'),
'url' => Yii::t('app/common', 'url'),
'title' => Yii::t('app/common', 'title'),
'text' => Yii::t('app/common', 'text'),
'code' => Yii::t('app/common', 'code'),
'display_order' => Yii::t('app/common', '显示顺序'),
'lang_id' => Yii::t('app/common', '语言id'),
];
}
}
<file_sep>/frontend/logic/Articles.php
<?php
/**
* @author <EMAIL>
* @date 22/10/2017
*/
namespace frontend\logic;
use frontend\models\Artcate;
class Articles extends Base {
public static function nestedCates(){
return Artcate::nestedItems();
}
public static function getItems($cid){
}
public static function getItem($id){
}
}
<file_sep>/common/models/Lang.php
<?php
namespace common\models;
use Yii;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "qycms_lang".
* @property integer $id
* @property string $lang_code
* @property string $title
* @property string $title_native
* @property string $sef
* @property string $image
* @property string $description
* @property string $metakey
* @property string $metadesc
* @property string $sitename
* @property integer $published
* @property integer $ordering
*/
class Lang extends \yii\db\ActiveRecord {
const PUBLISH_ON = 1;
const PUBLISH_OFF = 0;
private static $show = [];
public static function show($only_published = true) {
if (!isset(self::$show[intval($only_published)])) {
$tmp = self::find()->asArray();
if ($only_published) {
$tmp->where(['published' => $only_published]);
}
$tmp = $tmp->orderBy('ordering')->all();
$res = [];
foreach ($tmp as $v) {
$res[$v['id']] = $v;
}
self::$show[intval($only_published)] = $res;
}
return self::$show[intval($only_published)];
}
public static function items() {
$tmp = self::find()->asArray()->where(['published' => self::PUBLISH_ON])->orderBy('ordering')->all();
$res = [];
foreach ($tmp as $v) {
$res[$v['id']] = $v['title_native'];
}
return $res;
}
public static function id($lang_code) {
return (new \yii\db\Query())->from('qycms_lang')->where(['=', 'lang_code', $lang_code])->scalar();
}
/**
* @inheritdoc
*/
public static function tableName() {
return 'qycms_lang';
}
/**
* @inheritdoc
*/
public function rules() {
return [
[
[
'lang_code',
'title',
'title_native',
'sef',
'image',
'description',
'metakey',
'metadesc'
],
'required'
],
[
[
'metakey',
'metadesc'
],
'string'
],
[
[
'published',
'ordering'
],
'integer'
],
[
['lang_code'],
'string',
'max' => 7
],
[
[
'title',
'title_native',
'sef',
'image'
],
'string',
'max' => 50
],
[
['description'],
'string',
'max' => 512
],
[
['sitename'],
'string',
'max' => 1024
],
[
['sef'],
'unique'
],
[
['image'],
'unique'
],
[
['lang_code'],
'unique'
],
];
}
/**
* @inheritdoc
*/
public function attributeLabels() {
return [
'id' => Yii::t('common', 'ID'),
'lang_code' => Yii::t('common', 'Lang Code'),
'title' => Yii::t('common', 'Title'),
'title_native' => Yii::t('common', 'Title Native'),
'sef' => Yii::t('common', 'Sef'),
'image' => Yii::t('common', 'Image'),
'description' => Yii::t('common', 'Description'),
'metakey' => Yii::t('common', 'Metakey'),
'metadesc' => Yii::t('common', 'Metadesc'),
'sitename' => Yii::t('common', 'Sitename'),
'published' => Yii::t('common', 'Published'),
'ordering' => Yii::t('common', 'Ordering'),
];
}
}
<file_sep>/frontend/models/Menu.php
<?php
namespace frontend\models;
use common\logic\Nested;
use common\logic\Lang;
use Yii;
use yii\helpers\Url;
/**
* This is the model class for table "qycms_menu".
* @property integer $id
* @property integer $pid
* @property string $name
* @property string $content_type
* @property string $content
* @property integer $ctime
* @property integer $mtime
* @property integer $lang_id
*/
class Menu extends \common\models\Menu {
/**
* @inheritdoc
*/
public static function tableName() {
return 'qycms_menu';
}
/**
* @inheritdoc
*/
public function rules() {
return [
[
[
'pid',
'ctime',
'mtime',
'lang_id'
],
'integer'
],
[
[
'content',
'ctime',
'mtime'
],
'required'
],
[
['content'],
'string'
],
[
['name'],
'string',
'max' => 64
],
[
['content_type'],
'string',
'max' => 32
],
];
}
/**
* @inheritdoc
*/
public function attributeLabels() {
return [
'id' => Yii::t('common', 'id'),
'pid' => Yii::t('common', '父菜单'),
'name' => Yii::t('common', '名称'),
'content_type' => Yii::t('common', '内容类型'),
'content' => Yii::t('common', '内容'),
'ctime' => Yii::t('common', '创建时间'),
'mtime' => Yii::t('common', '修改时间'),
'lang_id' => Yii::t('common', '语言id'),
];
}
public static function nestedItems() {
$menu = Menu::find()->where(['=', 'lang', Yii::$app->language])->orderBy('display_order DESC')->asArray()->all();
$menu = Nested::childrenWithTree($menu);
foreach ($menu['items'] as $k => $v) {
$menu['items'][$k]['content'] = json_decode($v['content'], true);
$menu['items'][$k]['url'] = self::determineUrl($v['content_type'], $menu['items'][$k]['content']);
}
return $menu;
}
public static function determineUrl($type, $content) {
switch ($type) {
case 'URL':
return $content['url'];
break;
case 'PAGE':
return Url::to([
'page/view',
'id' => $content['page']
]);
break;
case 'ARTCATE':
return Url::to([
'articles/index',
'id' => $content['artcate']
]);
break;
case 'PROCATE':
$url = ['products/index',];
!empty($content['procate']) && $url['id'] = $content['procate'];
return Url::to($url);
break;
case 'ARTICLE':
return Url::to([
'articles/view',
'id' => $content['article']
]);
break;
default:
return '';
}
}
}
<file_sep>/backend/views/article/index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use common\models\Article;
use backend\models\Artcate;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = '文章';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="article-index">
<p>
<?=Html::a('<i class="fa fa-fw fa-plus"></i>添加'.$this->title, ['create'], ['class' => 'btn btn-success'])?>
</p>
<?=GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'options' => ['class' => 'table-responsive'],
'filterUrl' => $filterUrl,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
'name',
[
'attribute' => 'cid',
'content' => function($model, $key, $index, $column) {
$items = Artcate::items();
return $items[$model->cid]['name'];
},
'filter' => Artcate::options(),
],
//'summary',
[
'attribute' => 'status',
'content' => function($model, $key, $index, $column) {
switch ($model->status) {
case Article::STATUS_ACTIVE:
return '<span class="text-green">发布</span>';
break;
case Article::STATUS_EDIT:
return '<span class="">编辑中</span>';
break;
case Article::STATUS_HIDE:
return '<span class="text-muted">隐藏</span>';
break;
default:
return '';
}
},
'filter' => [
Article::STATUS_ACTIVE => '发布',
Article::STATUS_EDIT => '编辑中',
Article::STATUS_HIDE => '隐藏',
],
],
// 'ctime:datetime',
[
'attribute' => 'mtime',
'content' => function($model, $key, $index, $column) {
return date('Y-m-d H:i', $model->mtime);
},
'filter' => false,
],
[
'attribute' => 'lang',
'content' => function($model, $key, $index, $column) {
$langs = Yii::$app->params['lang'];
return '<img src="/images/' . $langs[$model->lang]['image'] . '.gif">';
},
'filter' => \common\logic\Lang::items(),
],
[
'class' => 'yii\grid\ActionColumn',
'header' => '操作',
'contentOptions' => ['class' => 'action-btn-td'],
'buttons' => [
'update' => function($url, $model, $key) {
$options = [
'class' => 'btn btn-sm btn-default modify-btn',
'aria-label' => '修改',
];
return Html::a('<i class="fa fa-pencil-square-o"></i>', $url, $options);
},
'hide' => function($url, $model, $key) {
$options = [
'class' => 'btn btn-sm btn-default hide-btn',
'aria-label' => '隐藏切换',
'data-pjax' => '0',
];
return Html::a($model->status == Article::STATUS_HIDE ? '<i class="fa fa-fw fa-toggle-off text-muted"></i>' : '<i class="fa fa-fw fa-toggle-on text-green"></i>', $url, $options);
},
'delete' => function($url, $model, $key) {
$options = [
'class' => 'btn btn-sm btn-default',
'aria-label' => Yii::t('yii', 'Delete'),
'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
'data-method' => 'post',
'data-pjax' => '0',
];
return Html::a('<span class="fa fa-trash"></span>', $url, $options);
},
],
'template' => ' {update} {hide} {delete}',
],
],
]);?>
</div>
<file_sep>/vendor_my_fix.php
#!/usr/bin/env php
<?php
/**
* @author <EMAIL>
* @date 23/10/2017
*/
$params = getParams();
$root = str_replace('\\', '/', __DIR__);
echo "QyCMS vendor my Fix Tool v1.0\n\n";
$map = [
'vendor_my_fix/BootstrapAsset.php'=>'vendor/yiisoft/yii2-bootstrap/BootstrapAsset.php',
'vendor_my_fix/BootstrapPluginAsset.php'=>'vendor/yiisoft/yii2-bootstrap/BootstrapPluginAsset.php',
'vendor_my_fix/JqueryAsset.php'=>'vendor/yiisoft/yii2/web/JqueryAsset.php',
'vendor_my_fix/vendor_my_fix/UEditor.php'=>'vendor/kucha/ueditor/UEditor.php',
'vendor_my_fix/UEditorAsset.php'=>'vendor/kucha/ueditor/UEditorAsset.php',
'vendor_my_fix/ZeroClipboard.js' =>'vendor/kucha/ueditor/assets/third-party/zeroclipboard/ZeroClipboard.js',
];
$all = false;
foreach ($map as $s=>$t){
$diff_cmd = "diff $s $t";
echo "Command: $diff_cmd\n";
echo "Result: " . shell_exec($diff_cmd);
if (!copyFile($root, $s, $t, $all, $params)) {
break;
}
}
function copyFile($root, $source, $target, &$all, $params)
{
if (!is_file($root . '/' . $source)) {
echo " skip $target ($source not exist)\n";
return true;
}
if (is_file($root . '/' . $target)) {
if (file_get_contents($root . '/' . $source) === file_get_contents($root . '/' . $target)) {
echo " unchanged $target\n";
return true;
}
if ($all) {
echo " overwrite $target\n";
} else {
echo " exist $target\n";
echo " ...overwrite? [Yes|No|All|Quit] ";
$answer = !empty($params['overwrite']) ? $params['overwrite'] : trim(fgets(STDIN));
if (!strncasecmp($answer, 'q', 1)) {
return false;
} else {
if (!strncasecmp($answer, 'y', 1)) {
echo " overwrite $target\n";
} else {
if (!strncasecmp($answer, 'a', 1)) {
echo " overwrite $target\n";
$all = true;
} else {
echo " skip $target\n";
return true;
}
}
}
}
file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
return true;
}
echo " generate $target\n";
@mkdir(dirname($root . '/' . $target), 0777, true);
file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
return true;
}
function getParams()
{
$rawParams = [];
if (isset($_SERVER['argv'])) {
$rawParams = $_SERVER['argv'];
array_shift($rawParams);
}
$params = [];
foreach ($rawParams as $param) {
if (preg_match('/^--(\w+)(=(.*))?$/', $param, $matches)) {
$name = $matches[1];
$params[$name] = isset($matches[3]) ? $matches[3] : true;
} else {
$params[] = $param;
}
}
return $params;
}<file_sep>/backend/widgets/LangselectAsset.php
<?php
/**
* @author <EMAIL>
* @date 29/09/2017
*/
namespace backend\widgets;
use yii\web\AssetBundle;
/**
* The asset bundle for the [[DatetimepickerInput]] widget.
*
* Includes client assets of [jQuery input mask plugin](https://github.com/RobinHerbots/jquery.inputmask).
*
*/
class LangselectAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $js = [
'js/js.cookie.js',
];
public $depends = [
'yii\web\JqueryAsset',
];
}
<file_sep>/frontend/logic/Nested.php
<?php
/**
* @author <EMAIL>
* @date 08/10/2017
*/
namespace frontend\logic;
/**
* Class Nested
* 要求:数据list的每一行,含id、pid、pids字段
* @package common\models
*/
class Nested extends \common\logic\Nested {
}
<file_sep>/common/models/Tag.php
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "qycms_tag".
*
* @property integer $id
* @property string $tag
* @property string $type
* @property integer $spec_id
* @property string $lang
*/
class Tag extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'qycms_tag';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['spec_id'], 'integer'],
[['tag'], 'string', 'max' => 64],
[['type'], 'string', 'max' => 32],
[['lang'], 'string', 'max' => 7],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('common', 'id'),
'tag' => Yii::t('common', '标签名'),
'type' => Yii::t('common', '类型'),
'spec_id' => Yii::t('common', '具体id'),
'lang_id' => Yii::t('common', '语言'),
];
}
/**
* @inheritdoc
* @return TagQuery the active query used by this AR class.
*/
public static function find()
{
return new TagQuery(get_called_class());
}
}
<file_sep>/frontend/web/backend/js/sortablelist.js
/**
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
(function ($) {
$.JSortableList = function (tableWrapper, sortDir, saveOrderingUrl, options, nestedList) {
var root = this;
var disabledOrderingElements = '';
var sortableGroupId = '';
var sortableRange;
var childrenNodes;
var sameLevelNodes;
if (sortDir != 'desc') {
sortDir = 'asc';
}
var ops = $.extend({
orderingIcon: 'add-on', //class name of order icon
orderingWrapper: 'input-prepend', //ordering control wrapper class name
orderingGroup: 'sortable-group-id', //sortable-group-id
sortableClassName: 'dndlist-sortable',
placeHolderClassName: 'dnd-list-highlight dndlist-place-holder',
sortableHandle: '.sortable-handler'
}, options);
$('tr', tableWrapper).removeClass(ops.sortableClassName).addClass(ops.sortableClassName);
//make wrapper table position be relative, to fix y-axis drag problem on Safari
$(tableWrapper).parents('table').css('position', 'relative');
$(ops.sortableHandle, tableWrapper).css('cursor', 'move');
var _handle = $(ops.sortableHandle, $(tableWrapper)).length > 0 ? ops.sortableHandle : '';
$(tableWrapper).sortable({
axis: 'y',
cursor: 'move',
handle: _handle,
items: 'tr.' + ops.sortableClassName,
placeholder: ops.placeHolderClassName,
helper: function (e, ui) {
//hard set left position to fix y-axis drag problem on Safari
$(ui).css({'left': '0px'});
ui.children().each(function () {
$(this).width($(this).width());
});
$(ui).children('td').addClass('dndlist-dragged-row');
return ui;
},
start: function (e, ui) {
root.sortableGroupId = ui.item.attr(ops.orderingGroup);
if (root.sortableGroupId) {
root.sortableRange = $('tr[' + ops.orderingGroup + '=' + root.sortableGroupId + ']');
} else {
root.sortableRange = $('.' + ops.sortableClassName);
}
//Disable sortable for other group's records
root.disableOtherGroupSort(e, ui);
//Proceed nested list
if (nestedList) {
root.hideChildrenNodes(ui.item.attr('item-id'));
root.hideSameLevelChildrenNodes(ui.item.attr('level'));
$(tableWrapper).sortable('refresh');
}
},
stop: function (e, ui) {
$('td', $(this)).removeClass('dndlist-dragged-row');
$(ui.item).css({opacity: 0});
$(ui.item).animate({
opacity: 1
}, 800, function () {
$(ui.item).css('opacity', '');
});
root.enableOtherGroupSort(e, ui);
root.rearrangeOrderingValues(root.sortableGroupId, ui);
root.disabledOrderingElements = '';
//Proceed nested list
if (nestedList) {
root.showChildrenNodes(ui.item);
root.showSameLevelChildrenNodes(ui.item);
$(tableWrapper).sortable('refresh');
}
if (saveOrderingUrl) {
//serialize form then post to callback url
var ids = '';
$(tableWrapper).children().each(function (i, v) {
ids += $(v).attr('item-id') + ',';
});
console.log(ids);
$.post(saveOrderingUrl, 'ids=' + ids);
}
}
});
this.hideChildrenNodes = function (itemId) {
root.childrenNodes = root.getChildrenNodes(itemId);
root.childrenNodes.hide();
};
this.showChildrenNodes = function (item) {
item.after(root.childrenNodes);
root.childrenNodes.show();
root.childrenNodes = "";
};
this.hideSameLevelChildrenNodes = function (level) {
root.sameLevelNodes = root.getSameLevelNodes(level);
root.sameLevelNodes.each(function () {
_childrenNodes = root.getChildrenNodes($(this).attr('item-id'));
_childrenNodes.addClass('child-nodes-tmp-hide');
_childrenNodes.hide();
});
};
this.showSameLevelChildrenNodes = function (item) {
prevItem = item.prev();
prevItemChildrenNodes = root.getChildrenNodes(prevItem.attr('item-id'));
prevItem.after(prevItemChildrenNodes);
$('tr.child-nodes-tmp-hide').show().removeClass('child-nodes-tmp-hide');
root.sameLevelNodes = "";
};
this.disableOtherGroupSort = function (e, ui) {
if (root.sortableGroupId) {
var _tr = $('tr[' + ops.orderingGroup + '!=' + root.sortableGroupId + ']', $(tableWrapper));
_tr.removeClass(ops.sortableClassName).addClass('dndlist-group-disabled');
$(tableWrapper).sortable('refresh');
}
};
this.enableOtherGroupSort = function (e, ui) {
var _tr = $('tr', $(tableWrapper)).removeClass(ops.sortableClassName);
_tr.addClass(ops.sortableClassName)
.removeClass('dndlist-group-disabled');
$(tableWrapper).sortable('refresh');
};
this.disableOrderingControl = function () {
$('.' + ops.orderingWrapper + ' .add-on a', root.sortableRange).hide();
};
this.enableOrderingControl = function () {
$('.' + ops.orderingWrapper + ' .add-on a', root.disabledOrderingElements).show();
};
this.rearrangeOrderingControl = function (sortableGroupId, ui) {
var range;
if (sortableGroupId) {
root.sortableRange = $('tr[' + ops.orderingGroup + '=' + sortableGroupId + ']');
} else {
root.sortableRange = $('.' + ops.sortableClassName);
}
range = root.sortableRange;
var count = range.length;
var i = 0;
if (count > 1) {
range.each(function () {
//firstible, add both ordering icons for missing-icon item
var upIcon = $('.' + ops.orderingWrapper + ' .add-on:first a', $(this)); //get orderup icon of current dropped item
var downIcon = $('.' + ops.orderingWrapper + ' .add-on:last a', $(this)); //get orderup icon of current dropped item
if (upIcon.get(0) && downIcon.get(0)) {
//do nothing
} else if (upIcon.get(0)) {
upIcon.removeAttr('title');
upIcon = $('.' + ops.orderingWrapper + ' .add-on:first', $(this)).html();
downIcon = upIcon.replace('icon-uparrow', 'icon-downarrow');
downIcon = downIcon.replace('.orderup', '.orderdown');
$('.' + ops.orderingWrapper + ' .add-on:last', $(this)).html(downIcon);
} else if (downIcon.get(0)) {
downIcon.removeAttr('title');
downIcon = $('.' + ops.orderingWrapper + ' .add-on:last', $(this)).html();
upIcon = downIcon.replace('icon-downarrow', 'icon-uparrow');
upIcon = upIcon.replace('.orderdown', '.orderup');
$('.' + ops.orderingWrapper + ' .add-on:first', $(this)).html(upIcon);
}
});
//remove orderup icon for first record
$('.' + ops.orderingWrapper + ' .add-on:first a', range[0]).remove();
//remove order down icon for last record
$('.' + ops.orderingWrapper + ' .add-on:last a', range[(count - 1)]).remove();
}
};
this.rearrangeOrderingValues = function (sortableGroupId, ui) {
var range;
if (sortableGroupId) {
root.sortableRange = $('tr[' + ops.orderingGroup + '=' + sortableGroupId + ']');
} else {
root.sortableRange = $('.' + ops.sortableClassName);
}
};
this.getChildrenNodes = function (parentId) {
return $('tr[parents~="' + parentId + '"]');
};
this.getSameLevelNodes = function (level) {
return $('tr[level=' + level + ']');
}
}
})(jQuery);
<file_sep>/backend/models/Artcate.php
<?php
namespace backend\models;
use Yii;
/**
* This is the model class for table "qycms_artcate".
*
* @property integer $id
* @property string $name
* @property integer $pid
* @property integer $status
* @property integer $ctime
* @property integer $mtime
* @property string $lang
*/
class Artcate extends \common\models\Artcate
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'qycms_artcate';
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[
'status',
'default',
'value' => self::STATUS_ACTIVE
],
[
'display_order',
'default',
'value' => 0
],
]);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'id',
'name' => '名称',
'pid' => '上级分类',
'pids' => '祖先id链',
'status' => '状态',
'display_order' => '显示顺序',
'ctime' => '创建时间',
'mtime' => '修改时间',
'lang' => '语种',
];
}
public static function options(){
$data = self::find()->asArray()->all();
$res = [];
foreach ($data as $v){
$res[$v['id']] = $v['name'];
}
return $res;
}
}
<file_sep>/frontend/messages/zh-CN/common.php
<?php
/**
* @author <EMAIL>
* @date 14/10/2017
*/
return [
'name'=>'名称',
'Parent Category'=>'父分类',
'Pages' => '单页',
'Procates'=>'产品',
];
<file_sep>/vendor_my_fix/UEditor.php
<?php
/**
* @link https://github.com/BigKuCha/yii2-ueditor-widget
* @link http://ueditor.baidu.com/website/index.html
*/
namespace kucha\ueditor;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\View;
use yii\widgets\InputWidget;
class UEditor extends InputWidget
{
//配置选项,参阅Ueditor官网文档(定制菜单等)
public $clientOptions = [];
//默认配置
protected $_options;
/**
* @throws \yii\base\InvalidConfigException
*/
public function init()
{
if (isset($this->options['id'])) {
$this->id = $this->options['id'];
} else {
$this->id = $this->hasModel() ? Html::getInputId($this->model,
$this->attribute) : $this->id;
}
$this->_options = [
//'serverUrl' => Url::to(['site/upload']),
'serverUrl' => '/zh-cn/site/upload',
'initialFrameWidth' => '100%',
'initialFrameHeight' => '300',
'lang' => (strtolower(Yii::$app->language) == 'en-us') ? 'en' : 'zh-cn',
'toolbars' => [
[
'fullscreen',
'source',
'|',
'undo',
'redo',
'|',
'bold',
'italic',
'underline',
'fontborder',
'strikethrough',
'superscript',
'subscript',
'removeformat',
'autotypeset',
'blockquote',
'pasteplain',
'|',
'forecolor',
'backcolor',
'insertorderedlist',
'insertunorderedlist',
'|',
'rowspacingtop',
'rowspacingbottom',
'lineheight',
'|',
'customstyle',
'paragraph',
'fontfamily',
'fontsize',
'|',
'indent',
'|',
'justifyleft',
'justifycenter',
'justifyright',
'justifyjustify',
'|',
'link',
'unlink',
'|',
'imagenone',
'imageleft',
'imageright',
'imagecenter',
'|',
'simpleupload',
'insertimage',
'insertvideo',
'attachment',
'map',
'gmap',
'insertframe',
'template',
'|',
'horizontal',
'spechars',
'|',
'inserttable',
'deletetable',
'insertrow',
'deleterow',
'insertcol',
'deletecol',
'mergecells',
'mergeright',
'mergedown',
'splittocells',
'splittorows',
'splittocols',
'|',
'print',
'searchreplace'
]
],
];
$this->clientOptions = ArrayHelper::merge($this->_options, $this->clientOptions);
parent::init();
}
public function run()
{
$this->registerClientScript();
if ($this->hasModel()) {
$name = Html::getInputName($this->model, $this->attribute);
$value = Html::getAttributeValue($this->model, $this->attribute);
return '<script id="' . $this->id . '" name="' . $name . '" type="text/plain">'.$value.'</script>';
//return Html::activeTextarea($this->model, $this->attribute, ['id' => $this->id]);
} else {
return Html::textarea($this->id, $this->value, ['id' => $this->id]);
}
}
/**
* 注册客户端脚本
*/
protected function registerClientScript()
{
UEditorAsset::register($this->view);
$clientOptions = Json::encode($this->clientOptions);
$script = "var ueditor = UE.getEditor('" . $this->id . "', " . $clientOptions . ");";
$this->view->registerJs($script, View::POS_READY);
}
}
<file_sep>/backend/controllers/MenuController.php
<?php
namespace backend\controllers;
use backend\logic\Nested;
use backend\models\Artcate;
use Yii;
use backend\models\Menu;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* MenuController implements the CRUD actions for Menu model.
*/
class MenuController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Menu models.
* @return mixed
*/
public function actionIndex()
{
$data = Nested::dataList(Menu::find()->orderBy('display_order DESC')->asArray()->all());
return $this->render('index', [
'data' => $data,
]);
}
public function actionOrder(){
$ids = Yii::$app->request->post('ids');
$order = array_reverse(explode(',', trim($ids, ', ')));
foreach ($order as $k=>$id){
Menu::updateAll(['display_order' => $k], 'id = '.$id);
}
var_dump($order);
}
/**
* Displays a single Menu model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Menu model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Menu();
$post = Yii::$app->request->post();
if(!empty($post[$model->formName()])){
$data = $post[$model->formName()];
$post[$model->formName()]['pids'] = Nested::getPids(Menu::findOne($data['pid']));
$post[$model->formName()]['ctime'] = $post[$model->formName()]['mtime'] = time();
if($data['content_type'] == 'URL'){
if(empty($data['content']['url'])){
}
}elseif ($data['content_type'] == 'ARTCATE'){
}elseif ($data['content_type'] == 'PROCATE'){
}else{
}
$post[$model->formName()]['content'] = json_encode($data['content']);
}
if ($model->load($post) && $model->save()) {
if ($post['save-then-new'] == 'yes') {
return $this->render('create', [
'model' => new Menu(),
]);
}
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Menu model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$post = Yii::$app->request->post();
if(!empty($post[$model->formName()])){
$data = $post[$model->formName()];
$post[$model->formName()]['pids'] = Nested::getPids(Menu::findOne($data['pid']));
$post[$model->formName()]['mtime'] = time();
if($data['content_type'] == 'URL'){
if(empty($data['content']['url'])){
}
}elseif ($data['content_type'] == 'ARTCATE'){
}elseif ($data['content_type'] == 'PROCATE'){
}else{
}
$post[$model->formName()]['content'] = json_encode($data['content']);
}
$model->content = json_decode($model->content, true);
if ($model->load($post) && $model->save()) {
if ($post['save-then-new'] == 'yes') {
return $this->render('create', [
'model' => new Menu(),
]);
}
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Menu model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Menu model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Menu the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Menu::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
<file_sep>/common/models/Procate.php
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "qycms_procate".
*
* @property integer $id
* @property string $name
* @property integer $pid
* @property string $pids
* @property integer $status
* @property integer $display_order
* @property integer $ctime
* @property integer $mtime
* @property string $lang
*/
class Procate extends \yii\db\ActiveRecord
{
const STATUS_ACTIVE = 1;
const STATUS_EDIT = 2;
const STATUS_HIDE = 3;
const STATUS_DELETED = 4;
private static $items = [];
/**
* @inheritdoc
*/
public static function tableName()
{
return 'qycms_procate';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['pid', 'status', 'display_order', 'ctime', 'mtime'], 'integer'],
['name', 'required'],
[['name'], 'string', 'max' => 64],
[['pids'], 'string', 'max' => 32],
[['lang'], 'string', 'max' => 7],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('common', 'id'),
'name' => Yii::t('common', '名称'),
'pid' => Yii::t('common', '父分类id'),
'pids' => Yii::t('common', '祖先id链,逗号分隔'),
'status' => Yii::t('common', '状态 0编辑 1发布 2隐藏'),
'display_order' => Yii::t('common', '显示顺序'),
'ctime' => Yii::t('common', '创建时间'),
'mtime' => Yii::t('common', '修改时间'),
'lang_id' => Yii::t('common', '语言'),
];
}
public static function items(){
if(empty(self::$items)){
$data = self::find()->asArray()->all();
$res = [];
foreach ($data as $v){
$res[$v['id']] = $v;
}
self::$items = $res;
}
return self::$items;
}
}
<file_sep>/frontend/models/Page.php
<?php
namespace frontend\models;
use Yii;
/**
* This is the model class for table "qycms_page".
*
* @property integer $id
* @property string $name
* @property string $summary
* @property string $content
* @property integer $status
* @property integer $ctime
* @property integer $mtime
* @property integer $lang_id
*/
class Page extends \common\models\Page
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'qycms_page';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['content'], 'required'],
[['content'], 'string'],
[['status', 'ctime', 'mtime', 'lang_id'], 'integer'],
[['name'], 'string', 'max' => 64],
[['summary'], 'string', 'max' => 2000],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app/common', 'id'),
'name' => Yii::t('app/common', '名称'),
'summary' => Yii::t('app/common', '摘要'),
'content' => Yii::t('app/common', '内容'),
'status' => Yii::t('app/common', '状态 1发布 2编辑 3隐藏 4删除'),
'ctime' => Yii::t('app/common', '创建时间'),
'mtime' => Yii::t('app/common', '修改时间'),
'lang_id' => Yii::t('app/common', '语言id'),
];
}
}
|
eb3136468fe13a7913551b35f57826c15b80a0be
|
[
"Markdown",
"JavaScript",
"PHP"
] | 58
|
PHP
|
kissjacky/qycms
|
92bbe67632bc49538d596c3ec065a6d2f25e1c56
|
1f027adfece7e4468c3c129359b1dd48d64f73b9
|
refs/heads/master
|
<repo_name>lucashigor/graphql-net-core-3<file_sep>/Mutations/PropertyMutation.cs
using Dominio;
using ExternalServices;
using GraphQL.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Types;
namespace graphql_with_external_services.Mutations
{
public class PropertyMutation : ObjectGraphType
{
public PropertyMutation(IMicroregiaoExternalService service)
{
Field<MicroregiaoType>(
"addMicroregia",
arguments: new QueryArguments(
new QueryArgument<NonNullGraphType<MicroregiaoInputType>> { Name = "microregiao" }),
resolve: context =>
{
var entity = context.GetArgument<Microregiao>("microregiao");
return service.AddAsync(entity);
});
}
}
}
<file_sep>/Queries/MicroregiaoQuery.cs
using ExternalServices;
using GraphQL.Types;
using Types;
namespace graphql_with_external_services.Queries
{
public class MicroregiaoQuery : ObjectGraphType
{
public MicroregiaoQuery(IMicroregiaoExternalService service)
{
Field<ListGraphType<MicroregiaoType>>(
"microregiao",
arguments: new QueryArguments(new QueryArgument<IntGraphType> { Name = "id"}),
resolve: context => {
var id = context.GetArgument<int?>("id");
return id != null ? service.GetById(id.Value)
: service.GetAllAsync();
}) ;
}
}
}
<file_sep>/api/Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
namespace api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseInMemoryDatabase("InMemoryDatabase"));
services.AddTransient<UsuarioService>();
services.AddTransient<ProdutoService>();
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env
, UsuarioService usrService, ProdutoService produtoService)
{
usrService.Incluir(
new Usuario() { ID = "usuario01", ChaveAcesso = "94be650011cf412ca906fc335f615cdc" });
usrService.Incluir(
new Usuario() { ID = "usuario02", ChaveAcesso = "531fd5b19d58438da0fd9afface43b3c" });
produtoService.Incluir(
new Produto { CodigoBarras = "11111111111", Nome = "Produto01", Preco = 579 }
);
produtoService.Incluir(
new Produto { CodigoBarras = "2222222222", Nome = "Produto02", Preco = 579 }
);
produtoService.Incluir(
new Produto { CodigoBarras = "333333333333", Nome = "Produto03", Preco = 579 }
);
produtoService.Incluir(
new Produto { CodigoBarras = "4444444444", Nome = "Produto04", Preco = 579 }
);
produtoService.Incluir(
new Produto { CodigoBarras = "5555555555", Nome = "Produto05", Preco = 579 }
);
produtoService.Incluir(
new Produto { CodigoBarras = "66666666666", Nome = "Produto06", Preco = 579 }
);
produtoService.Incluir(
new Produto { CodigoBarras = "77777777777", Nome = "Produto07", Preco = 579 }
);
produtoService.Incluir(
new Produto { CodigoBarras = "888888888888", Nome = "Produto08", Preco = 579 }
);
produtoService.Incluir(
new Produto { CodigoBarras = "99999999999", Nome = "Produto09", Preco = 579 }
);
produtoService.Incluir(
new Produto { CodigoBarras = "10101010101010101010", Nome = "Produto10", Preco = 579 }
);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
<file_sep>/api/EatMoreQuery.cs
using System;
using GraphQL.Types;
namespace api
{
public class EatMoreQuery : ObjectGraphType
{
public EatMoreQuery(ApplicationDbContext db)
{
Field<ListGraphType<ProdutoType>>(
"produtos",
resolve: context =>
{
var produtos = db
.Produtos;
return produtos;
});
}
}
}
<file_sep>/Startup.cs
using ExternalServices;
using GraphiQl;
using GraphQL;
using GraphQL.Types;
using graphql_with_external_services.Mutations;
using graphql_with_external_services.Queries;
using graphql_with_external_services.Schema;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Types;
namespace graphql_with_external_services
{
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMvc()
.AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
services.AddHttpClient<IMicroregiaoExternalService, MicroregiaoExternalService>();
services.AddSingleton<IDocumentExecuter, DocumentExecuter>();
services.AddSingleton<MicroregiaoQuery>();
services.AddSingleton<MicroregiaoType>();
services.AddSingleton<MesorregiaoType>();
services.AddSingleton<UFType>();
services.AddSingleton<RegiaoType>();
services.AddSingleton<PropertyMutation>();
services.AddSingleton<MicroregiaoInputType>();
var sp = services.BuildServiceProvider();
services.AddSingleton<ISchema>(new RealEstateSchema(new FuncDependencyResolver(type => sp.GetService(type))));
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader();
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseGraphiQl();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseCors(MyAllowSpecificOrigins);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
<file_sep>/api/Controllers/WeatherForecastController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GraphQL;
using GraphQL.Types;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace api.Controllers
{
[ApiController]
[Route("[controller]")]
public class GraphQLController : ControllerBase
{
private readonly ApplicationDbContext _db;
public GraphQLController(ApplicationDbContext db)
{
_db = db;
_db.Produtos.Add(new Produto() {
CodigoBarras = "asdasasdasd",
Nome = "Nome 1",
Preco = 122
});
_db.Produtos.Add(new Produto()
{
CodigoBarras = "asdasasdasd",
Nome = "Nome 2",
Preco = 123
});
_db.Produtos.Add(new Produto()
{
CodigoBarras = "asdasasdasd",
Nome = "Nome 3",
Preco = 124
});
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]GraphQLQuery query)
{
var inputs = query.Variables.ToInputs();
var schema = new Schema()
{
Query = new EatMoreQuery(_db)
};
var result = await new DocumentExecuter().ExecuteAsync(_ =>
{
_.Schema = schema;
_.Query = query.Query;
_.OperationName = query.OperationName;
_.Inputs = inputs;
}).ConfigureAwait(false);
if (result.Errors?.Count > 0)
{
return BadRequest();
}
return Ok(result);
}
}
}
<file_sep>/api/models/Produto.cs
using System;
namespace api
{
public class Produto
{
private string _codigoBarras;
public string CodigoBarras
{
get => _codigoBarras;
set => _codigoBarras = value?.Trim().ToUpper();
}
private string _nome;
public string Nome
{
get => _nome;
set => _nome = value?.Trim();
}
public double Preco { get; set; }
}
}
<file_sep>/Schema/RealEstateSchema.cs
using GraphQL;
using graphql_with_external_services.Mutations;
using graphql_with_external_services.Queries;
namespace graphql_with_external_services.Schema
{
public class RealEstateSchema : GraphQL.Types.Schema
{
public RealEstateSchema(IDependencyResolver resolver) :base(resolver)
{
Query = resolver.Resolve<MicroregiaoQuery>();
Mutation = resolver.Resolve<PropertyMutation>();
}
}
}
<file_sep>/api/ProdutoType.cs
using System;
using GraphQL.Types;
namespace api
{
public class ProdutoType : ObjectGraphType<Produto>
{
public ProdutoType()
{
Name = "Produto";
Field(x => x.CodigoBarras).Description("Código de Barras");
Field(x => x.Nome).Description("Nome do produto");
Field(x => x.Preco).Description("Preço");
}
}
}
|
c88857594e67ee0ebec85a6ecc5f5bbd06dfccf7
|
[
"C#"
] | 9
|
C#
|
lucashigor/graphql-net-core-3
|
79bb03d8dd6f68baa08e3a08ae1178cc5012fe80
|
7da153c22ceb753dfc0b0f88919a9d25a337fcc8
|
refs/heads/master
|
<file_sep>import org.newdawn.slick.SlickException;
public class Bike extends Vehicle{
Bike(String imageSrc, float x, float y, float spd, boolean solid, int dir) throws SlickException {
super(imageSrc, x,y,spd,solid,dir);
}
public void update(int delta) {
if(this.getX() >= 1000 || this.getX() <= 24) {
setSpeed(-1);
}
this.setSpriteX(this.getX() + getSpeed()*delta);
//x += this.getSpeed();
if(this.getX() < 0 - this.getWidth() && this.getDirection() < 0) {
this.setSpriteX(App.SCREEN_WIDTH + this.getWidth()/2);
}
if(this.getX()> App.SCREEN_WIDTH + this.getWidth() && this.getDirection() > 0) {
this.setSpriteX(0 - this.getWidth()/2);
}
/* update boundbox for vehicle */
setX(this.getX());
setY(this.getY());
}
}
<file_sep>import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
public class Lives{
private String image_path = "assets/lives.png";
private Image image;
private float x,y;
Lives(float x, float y) throws SlickException{
this.x = x;
this.y = y;
image = new Image(image_path);
}
void render(Graphics g){
image.drawCentered(x, y);
}
}<file_sep>import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
public class Turtle extends Vehicle{
private Image image;
Turtle(String imageSrc, float x, float y, float spd, boolean solid, int dir) throws SlickException {
super(imageSrc, x, y, spd, solid, dir);
image = new Image(imageSrc);
this.setX(x);
this.setY(y);
}
public void render(Graphics g) {
if((World.map_time % 9000.0) <= 7000) {
image.drawCentered(getX(), getY());
}
}
public boolean getUnderWater() {
if((World.map_time % 9000.0) <= 7000) {
return false;
}
return true;
}
}<file_sep>import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Random;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
public class World {
private String[] levels = {"assets/levels/0.lvl", "assets/levels/1.lvl"} ;
private int curr_level = 0;
private int current_rnum;
public static final int TILE_SIZE = 48;
public static final int GOAL_SIZE = TILE_SIZE*2;
private final int E_WAIT = 14;
private int num_starting_lives = 3;
private int targets_filled;
private int ex_timer;
static Random rand = new Random();
@SuppressWarnings("unused")
private boolean death_flag;
private ArrayList<Tile> tiles = new ArrayList<Tile>();
private ArrayList<Vehicle> rideable = new ArrayList<Vehicle>();
private ArrayList<Vehicle> kot_vehicles = new ArrayList<Vehicle>();
private ArrayList<Lives> lives = new ArrayList<Lives>();
private ArrayList<Vehicle> logs = new ArrayList<Vehicle>();
private ArrayList<Sprite> targets = new ArrayList<Sprite>();
private ExtraLife ex;
private Player sprite;
private int PLAYER_START_X = 512; // 512,720 : 512, 384 :93.6111
private int PLAYER_START_Y = 720;
public static long map_time = 0;
public long ex_alive_time = 0;
public World() throws SlickException {
/* Performs initialization of all objects and tiles */
createMap();
createLives();
createGates();
sprite = new Player("assets/frog.png",PLAYER_START_X, PLAYER_START_Y);
}
public void kill() {
/* Remove a single life from the player and ends the game
* when the life count is zero */
lives.remove(lives.size() -1);
if(lives.isEmpty()) {
System.exit(0);
}
else {
reset();
}
}
public void reset() {
/* Resets players position to values in the specification */
sprite.setSpriteX(PLAYER_START_X);
sprite.setSpriteY(PLAYER_START_Y);
}
public void render(Graphics g) {
/* Renders all objects that kill the player on contact/ or are tiles*/
for(Vehicle k: kot_vehicles) {
k.render(g);
}
for(Tile tile: tiles) {
tile.render(g);
}
/* renders objects that the player can "attach" to (turtle, log, bulldozer") */
for(Vehicle r: rideable) {
r.render(g);
}
int count = 0;
for(Vehicle log: logs) {
log.render(g);
g.drawString("" + count, log.getX(),log.getY());
count++;
}
/* renders all of the frog sprites */
for(Lives life: lives){
life.render(g);
}
for(Sprite goal: targets) {
goal.render(g);
}
if(ex != null) {
ex.render(g);
}
sprite.render(g);
g.drawString("TIME: " + map_time/1000.1f, 512, 720);
g.drawString("ex_timer" + ex_timer, 0, 384);
}
public void update(Input input, int delta) throws SlickException {
boolean death_flag = false;
boolean riding = false;
map_time += delta;
/* After a random period of time an ExtraLife is made */
// if(map_time % (ex_timer*1000) == 0) {
// createExtraLife();
// ex.setUnderWater(true);
// }
if(map_time == rand.nextInt(10)*1000) {
createExtraLife();
ex.setUnderWater(true);
}
/* Goes to the next level if all the holes are filled */
if(targets_filled == targets.size()) {
targets_filled = 0;
ex = null;
curr_level = (curr_level + 1) % levels.length;
createMap();
createGates();
createExtraLife(); // have a look
reset();
}
/* allows extra life sprite to ride on the log*/
if(ex != null) {
ex.attach(logs.get(current_rnum).getSpeed(), delta);
ex.update();
ex_alive_time += delta;
}
/* Check for collision with kill on touch vehicles and updates these vehicles */
for( Vehicle object: kot_vehicles) {
object.update(delta);
if(sprite.intersects(object)) {
death_flag = true;
}
}
/*Update all rideable objects and attach player to above water objects */
for(Vehicle w_object: rideable) {
w_object.update(delta);
/* wont let player move through solid vehicles */
if(sprite.intersects(w_object) && w_object.getSolid()) {
sprite.moveBack();
}
/* Causes player to ride with the vehicle */
if(sprite.intersects(w_object) && !w_object.getUnderWater()){
riding = true;
sprite.attach(w_object.getSpeed(), delta);
/* kills player if they are "squished" against the out of bounds area */
if(w_object.getSolid() && sprite.getX() >= App.SCREEN_WIDTH - TILE_SIZE) {
death_flag = true;
}
}
}
/* moves the logs and attaches the sprite if on them */
for (Vehicle log: logs) {
log.update(delta);
if(sprite.intersects(log) && !log.getUnderWater()){
riding = true;
sprite.attach(log.getSpeed(), delta);
}
}
/* Extralife follows log off screen and onto the other side */
if(ex != null && logs.get(current_rnum).getOffScreen()) {
if (logs.get(current_rnum).getDirection() == 1) {
ex.setSpriteX(0- logs.get(current_rnum).getWidth()/2 + ex.getX() - logs.get(current_rnum).getPrevX() );
}
else {
System.out.println("TRIPPED");
ex.setSpriteX(App.SCREEN_WIDTH + logs.get(current_rnum).getWidth()/2 + ex.getX() - logs.get(current_rnum).getPrevX() );
}
}
/* kills player if they "fall" in water/KOT tile and also doesn't allow them to move through
* solid tiles */
for( Tile tile: tiles) {
if(sprite.intersects(tile) && tile.touchable == 0 && riding == false) {
death_flag = true;
}
else if(sprite.intersects(tile) && tile.touchable == 2) {
sprite.moveBack();
}
}
/* kills player if they are supposed to die */
if(death_flag == true) {
kill();
}
/* Checks to see if the sprite reached a goal which is located in the last row of tiles */
for(Sprite target: targets) {
if(sprite.intersects(target) && target.getUnderWater()) {
target.setUnderWater(false);
targets_filled++;
reset();
}
else if(sprite.intersects(target)) {
kill();
}
}
/* increases lives if extraLife is touched */
if(ex != null && sprite.intersects(ex)) {
ex = null;
int remainingLives = lives.size();
lives.add(new Lives(24 + 32*(remainingLives), 744));
createExtraLife();
}
/* Move player */
sprite.update(input, delta);
}
public void createMap() throws SlickException {
/* sets initial direction to left */
int dir = 1;
map_time = 0;
ex_timer = rand.nextInt(10) + 1;// + 25;
targets_filled = 0;
/* clears all objects and tiles on map */
rideable.clear();
kot_vehicles.clear();
logs.clear();
tiles.clear();
targets.clear();
ex = null;
/* reads the level file and adds each object to their appropriate ArrayList */
try (BufferedReader br = new BufferedReader(new FileReader(levels[curr_level]))) {
String text;
while ((text = br.readLine()) != null) {
String[] words = text.split(",");
int x = Integer.parseInt(words[1]);
int y = Integer.parseInt(words[2]);
/* if not a tile then check if the direction needs to be switch to right */
if(words.length > 3) {
if (words[3].equals("false")) {
dir = -1;
}
}
/* Initialize tiles */
if(words[0].equals("water")) {
tiles.add(new Tile("assets/water.png", x, y, 0));
}
else if(words[0].equals("grass")) {
tiles.add(new Tile("assets/grass.png", x, y, 1));
}
else if(words[0].equals("tree")) {
tiles.add(new Tile("assets/tree.png", x, y, 2));
}
/* Initialize every obstacle/ vehicle */
else if(words[0].equals("bus")) {
kot_vehicles.add(new Vehicle("assets/bus.png", x, y, 0.15f, false, dir));
}
else if(words[0].equals("bulldozer")) {
rideable.add(new Vehicle("assets/bulldozer.png", x, y, 0.05f, true, dir));
}
else if(words[0].equals("bike")) {
kot_vehicles.add(new Bike("assets/bike.png", x, y, 0.2f, false, dir));
}
else if(words[0].equals("log")) {
logs.add(new Vehicle("assets/log.png", x, y, 0.1f, false, dir));
}
else if(words[0].equals("longLog")) {
logs.add(new Vehicle("assets/longlog.png", x, y, 0.07f, false, dir));
}
else if(words[0].equals("racecar")) {
kot_vehicles.add(new Vehicle("assets/racecar.png", x, y, 0.5f, false, dir));
}
else if(words[0].equals("turtle")) {
rideable.add(new Turtle("assets/turtles.png", x, y, 0.1f, false, dir));
}
dir = 1;
}
} catch (Exception e) {
e.printStackTrace();
}
}
/* Finds the holes in the top 2nd row of tiles and puts sprites in them */
public void createGates() throws SlickException {
float curr_x = 0;
float prev_x = 0;
for(Tile tile: tiles) {
if(tile.getY() == TILE_SIZE) {
curr_x = tile.getX();
/* Finds the gap and puts a hidden sprite in the middle */
if(curr_x - prev_x > TILE_SIZE) {
targets.add(new Sprite("assets/frog.png", (float) (prev_x+ 0.5*(curr_x - prev_x)), TILE_SIZE, true));
}
prev_x = curr_x;
}
}
}
public void createLives() throws SlickException {
/* Creates the number of starting lives */
for( int i = 0; i< num_starting_lives; i++) {
lives.add(new Lives(24 + 32*i, 744));
}
}
public void createExtraLife() throws SlickException {
current_rnum = createRnd(logs.size());
System.out.println(ex_alive_time);
ex = new ExtraLife("assets/extralife.png", logs.get(current_rnum).getX(), logs.get(current_rnum).getY(), logs.get(current_rnum).getWidth());
ex_alive_time = 0;
}
public int createRnd(int max) {
return rand.nextInt(max);
}
}
|
c6525d99089372ffed3f4d4b94362398acf69646
|
[
"Java"
] | 4
|
Java
|
nmontorio98/Frogger
|
01029dca02c6d5c5f7a9a3561f41365948f0767a
|
429ef18b6a30fdfeda1d9a5d7e095d9cb14d858e
|
refs/heads/master
|
<file_sep>cask 'dymo-label' do
version '8.7'
sha256 'a0c69c47be728c2e835fa92110457c56ddc32e6941db95f7c783826a10f14ba9'
url "http://download.dymo.com/dymo/Software/Mac/DLS#{version.major}Setup.#{version}.dmg"
name 'Dymo Label'
homepage 'https://www.dymo.com/en-US/online-support'
pkg "DYMO Label v.#{version.major}.pkg", choices: [
{
'choiceIdentifier' => 'application',
'choiceAttribute' => 'selected',
'attributeSetting' => 1,
},
{
'choiceIdentifier' => 'appsupport',
'choiceAttribute' => 'selected',
'attributeSetting' => 1,
},
{
'choiceIdentifier' => 'frameworks',
'choiceAttribute' => 'selected',
'attributeSetting' => 1,
},
{
'choiceIdentifier' => 'documents',
'choiceAttribute' => 'selected',
'attributeSetting' => 1,
},
{
'choiceIdentifier' => 'officeaddins',
'choiceAttribute' => 'selected',
'attributeSetting' => 0,
},
{
'choiceIdentifier' => 'safariaddin',
'choiceAttribute' => 'selected',
'attributeSetting' => 0,
},
{
'choiceIdentifier' => 'addressbookaddin',
'choiceAttribute' => 'selected',
'attributeSetting' => 0,
},
{
'choiceIdentifier' => 'npapiaddin',
'choiceAttribute' => 'selected',
'attributeSetting' => 0,
},
{
'choiceIdentifier' => 'cups',
'choiceAttribute' => 'selected',
'attributeSetting' => 1,
},
{
'choiceIdentifier' => 'uninstall',
'choiceAttribute' => 'selected',
'attributeSetting' => 0,
},
{
'choiceIdentifier' => 'webservice',
'choiceAttribute' => 'selected',
'attributeSetting' => 0,
}
]
uninstall launchctl: 'com.dymo.pnpd', pkgutil: [
'com.dymo.cups',
'com.dymo.dls.addressbook.addin',
'com.dymo.dls.application',
'com.dymo.dls.appsupport',
'com.dymo.dls.documents',
'com.dymo.dls.frameworks',
'com.dymo.dls.npapi.addin',
'com.dymo.dls.office.addins',
'com.dymo.dls.safari.addin',
]
zap delete: [
'~/Library/Preferences/com.dymo.dls.plist',
'~/Library/Caches/com.dymo.dls',
]
end
|
2138d8ca8eb18b3996546945935fbec20061e242
|
[
"Ruby"
] | 1
|
Ruby
|
breckwagner/microbrew
|
b17d5736f3f96c42f966d7ecf2ddc43cd025706b
|
867d68bb4949d62a5ce0500d2c0aaccde6d8bc38
|
refs/heads/master
|
<file_sep>package com.example.rish.listviewexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);
ArrayList<ListItem> listItems = new ArrayList<ListItem>();
ListItem obj1= new ListItem("Orange","50000",R.drawable.orange);
listItems.add(obj1);
listItems.add(new ListItem("Orange","50000",R.drawable.orange));
ListItem obj2= new ListItem();
obj2.setName("Mango");
obj2.setQuantity("60000");
obj2.setImage(R.drawable.ic_launcher_background);
listItems.add(obj2);
final MyListAdapter adapter = new MyListAdapter(MainActivity.this,listItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListItem obj= adapter.getItem(position);
Toast.makeText(MainActivity.this,obj.getImage(),Toast.LENGTH_SHORT).show();
}
});
}
}
|
47b477e0f88bd1d023b7083cf758777491396436
|
[
"Java"
] | 1
|
Java
|
RishabhAwasthi/W2class1-Listview
|
d9bfea328393dee9bea2eafe5427cdabe1e6efad
|
da4e31231161a137916c99d658aa5c7a6d83f66f
|
refs/heads/master
|
<repo_name>kduraiswami/algorithmpractice<file_sep>/sherlock.rb
def sherlock_sum(array)
if array.empty?
return "NO"
end
i = 1
left_array = []
right_array = []
if array[1..-1].inject{ |sum, x| sum + x } == 0
return "YES"
end
while i < array.length
left_array = array[0..(i-1)]
right_array = array[i+1..-1]
if left_array.inject{ |sum, x| sum + x} == right_array.inject{ |sum, x| sum + x }
return "YES"
end
i += 1
end
if array[0..-2].inject{ |sum, x| sum + x } == 0
return "YES"
end
return "NO"
end
p sherlock_sum([]) == "NO"
p sherlock_sum([1,2,3]) == "NO"
p sherlock_sum([-1,1,0,2]) == "YES"
p sherlock_sum([-5,-4,-3,-2,-1,5,4,3,2,1,0,-1,-2,-3,-4,-5,1,2,3,4,5]) == "YES"
p sherlock_sum([1,2,3,3]) == "YES"
p sherlock_sum([1,0,-2,2]) == "YES"
<file_sep>/lexicographic.rb
def lexicographic_finder(string)
string_array = string.split('')
lexicographic_minimum = string_array.sort!
p lexicographic_minimum
until lexicographic_minimum.join('') < string_array.join('')
lexicographic_minimum
end
if lexicographic_minimum == string_array
lexicographic_minimum = ["n","o", " ", "a","n","s","w","e","r"]
end
return lexicographic_minimum.join('')
end
# if we start from the right side of the word we can switch the [-1]
# with the "closest" value
# I want to compare the right letter to the next, if right is "greater" then switch,
# if the right letter is
# if the right letter is right next to the
# the placement of the letter itself matters as well as
# the value of the letter itself
p lexicographic_finder("ab") == "ba"
p lexicographic_finder("bb") == "no answer"
p lexicographic_finder("hefg") == "hegf"
p lexicographic_finder("dhck") == "dhkc"
p lexicographic_finder("dkhc") == "hcdk"
p lexicographic_finder("abcd") == "abdc"
p lexicographic_finder("dcba") == "dcab"<file_sep>/newpractice/practice.rb
def repeat_letter?(name)
chars = name.split('')
frequency = Hash.new(0)
chars.each do |letter|
frequency[letter] += 1
end
chars.length != frequency.keys.length ? true : false
end
p repeat_letter?("kailash") == true
p repeat_letter?("tony") == false
p repeat_letter?("slik") == false
p repeat_letter?("anjali") == true<file_sep>/panagram.rb
def pangram(sentence)
if is_pangram?(sentence)
puts "pangram"
else
puts "not pangram"
end
end
def is_pangram?(sentence)
sentence_array = sentence.split('')
letter_frequency_hash = Hash.new(0)
sentence_array.each do |letter|
letter_frequency_hash[letter] += 1
end
if letter_frequency_hash.keys.length > 26
return true
else
return false
end
end
pangram("the quick brown fox jumps over the lazy dog")
pangram("We promptly judged antique ivory buckles for the next prize")
pangram("We promptly judged antique ivory buckles for the prize") <file_sep>/findpairs.rb
test_1 = [0, 1, 2, 98, 99, 100, 101] #[1,98], [2,98]
test_2 = [95,5,95] #[95,5]
test_3 = [95,5,5,95] #[95,5],[5,95]
def find_pairs(sum, array)
array.sort!
pairs = []
i = 0
j = array.length - 1
while (i < j)
lower_bound = array[i]
upper_bound = array[j]
if (lower_bound + upper_bound == sum)
pairs.push([lower_bound,upper_bound])
i += 1
j -= 1
elsif (lower_bound + upper_bound < sum)
i += 1
else
j -= 1
end
end
return pairs
end
p find_pairs(100, test_1)
p find_pairs(100, test_2)
p find_pairs(100, test_3)
<file_sep>/maximumsum.rb
def maximum_sum(array, modulo_number)
possible_sums = subarray_sum_creator(array)
maximum_sum = sum_modulo_creator(possible_sums, modulo_number)
return maximum_sum.max
end
def subarray_sum_creator(array)
possible_sums = []
array.each_with_index do |anchor_position, index|
i = index
j = i + 1
while j < array.length
possible_sums << array[index..j].inject{ |sum, x| sum + x}
j += 1
end
end
return possible_sums
end
def sum_modulo_creator(possible_sums, modulo_number)
modulo_sums = []
possible_sums.each do |individual_sum|
modulo_sums << individual_sum % modulo_number
end
return modulo_sums
end
# I calculated every possible sum which is larger than the original array
# I calculated every possible modulo value which is equal to the above array
# I then do a search over the entire array for the max which is at worst the entire array
p maximum_sum([3,3,5,9,9],7) == 6
p maximum_sum([1,2,3],7) == 6
p maximum_sum([1,2,5],5) == 3
p maximum_sum([1,3,2],6) == 5
p maximum_sum([1,4,6,3,2],3) == 2
p maximum_sum([2,4,6,8],2) == 0
<file_sep>/gameofthrones.rb
def possible_palindrone?(string)
hash_of_letter_frequency = Hash.new(0)
string_array = string.split('')
string_array.each do |letter|
hash_of_letter_frequency[letter] += 1
end
unless hash_of_letter_frequency.keys.length % string_array.length <= 1
return true
else
return false
end
end
p possible_palindrone?('abcddabc') == true
p possible_palindrone?('abcd') == false
p possible_palindrone?('aaabbbb') == true
p possible_palindrone?('abcccba') == true
p possible_palindrone?('ccddeeffeeccdd') == true
p possible_palindrone?('cdcdcdcdeeeef') == true
p possible_palindrone?('cdefghmnopqrstuvw') == false
p possible_palindrone?('obb') == true
p possible_palindrone?('a') == false
<file_sep>/gemstones.rb
def gem_element_counter(*rocks)
first_rock = rocks[0].split('')
gem_elements = []
first_rock.each do |individual_element|
if gem_element?(individual_element,rocks[1..-1])
gem_elements << individual_element
end
end
return gem_elements.length
end
def gem_element?(individual_element, rocks_in_question)
if detect_element_frequency(individual_element, rocks_in_question) == rocks_in_question.length
true
else
false
end
end
def detect_element_frequency(individual_element, rocks_in_question)
individual_element_frequency = 0
rocks_in_question.each do |individual_rocks|
if individual_rocks.include?(individual_element)
individual_element_frequency += 1
end
end
return individual_element_frequency
end
p gem_element_counter('abcdde','baccd','eeabg') == 2
p gem_element_counter('abcd','abc') == 3
p gem_element_counter('abcd','efgh') == 0
<file_sep>/permutations.rb
def permutation_detector(number)
split_digits = number.to_s.split('')
all_possible_permutations = split_digits.permutation.map(&:join)
all_possible_permutations.each do |individual_permutation|
return "YES" if individual_permutation.to_i % 8 == 0
end
return "NO"
end
p permutation_detector(123) == "YES"
p permutation_detector(61) == "YES"
p permutation_detector(75) == "NO"
p permutation_detector(8) == "YES"
p permutation_detector(7) == "NO"
<file_sep>/commonstring.rb
def common_string(string1, string2)
string1_array = string1.split('')
string1_letter_frequency = Hash.new(0)
string1_array.each do |individual_letter|
string1_letter_frequency[individual_letter] += 1
end
string2_array = string2.split('')
string2_letter_frequency = Hash.new(0)
string2_array.each do |individual_letter|
string2_letter_frequency[individual_letter] += 1
end
all_unique_letters = []
all_unique_letters_frequency = Hash.new(0)
all_unique_letters = string1_letter_frequency.keys + string2_letter_frequency.keys
all_unique_letters.each do |individual_letter|
all_unique_letters_frequency[individual_letter] += 1
if all_unique_letters_frequency[individual_letter] > 1
return "YES"
end
end
return "NO"
end
# this solution goes over the entire dataset at worst 4 times and at least 3 times each- ouch
# I like that I can escape immediately when creating hash
# I wish I had a more efficient way of getting the unique characters of the inputs
p common_string("hello","world") == "YES"
p common_string("poly", "morphic") == "YES"
p common_string("santa", "claus") == "YES"
p common_string("hi", "world") == "NO"
p common_string("polly", "mer") == "NO"
p common_string("pool", "guy") == "NO"<file_sep>/hunnet.rb
numbers = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51]
#write an algorithm that will find pairs of numbers in the above array that add up to 100
def find_pairs_for_sum(sum,array)
pairs = []
array.each do |potential_number|
if array.include?(sum-potential_number)
unless pairs.include?([potential_number, sum-potential_number].reverse)
pairs << [potential_number, sum-potential_number]
end
end
end
return pairs
end
p find_pairs_for_sum(100, numbers)
# tests
=begin
before each do
array = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51]
find_pairs_for_sum(100, array)
end
it should choose only two numbers per pair
expect pair.length to be(2)
it should choose two numbers that equal the correct sum
expect results[0][0] + results[0][1] to be(100)
=end<file_sep>/hashsort.rb
def hashsort(unsorted_hash)
# the output of this will be an array of the keys sorted by length
output_array = []
max_length = 0
unsorted_hash.each do |key, value|
output_array << key.to_s
end
output_array.sort_by { |hash_key| hash_key.length }
end
unsorted_hash = { abc: 'hello', 'another_key' => 123, 4567 => 'third'}
p hashsort(unsorted_hash)<file_sep>/rotate.rb
=begin
Do you think a simple Java array question can be a challenge?
Let's use the following problem to test.
Problem: Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3,
the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
How many different ways do you know to solve this problem?
=end
def rotate!(array,steps)
new_array = []
n = array.size
i = 1
while i <= n
new_array << array[(i + steps)%n]
i += 1
end
return new_array
end
p rotate!([1,2,3,4,5,6,7], 3)
p rotate!([1,2,3], 2)
#tests
=begin
before do
array = [1,2,3,4,5]
steps = 2
new_array = rotate(array,steps)
end
"it should not change the length of the array"
expect array.length to eq(new_array.length)
end
"it should contain the same elements"
expect array.uniq.sort to eq(new_array.uniq.sort)
end
"it should move the first element two indices"
expect array[0] to eq(new_array[2])
end
"it should return the same array if steps are equal to length"
expect array to contain?(new_array)
end
=end<file_sep>/alternate.rb
def alternate_count(string)
string_letters = string.split('')
letter_removal_count = 0
i = 0
j = 1
while j <= string_letters.length
if string_letters[i] == string_letters[j]
letter_removal_count += 1
end
i += 1
j += 1
end
return letter_removal_count
end
#need to test if a string has alternating characters
#a string with alternating characters will return the value 0
#a string with all the same characters will return a value one less than the length
p alternate_count("AAAA") == 3
p alternate_count("BBBBB") == 4
p alternate_count("ABABABAB") == 0
p alternate_count("BABABAB") == 0
p alternate_count("AAABBB") == 4<file_sep>/sort.rb
=begin
write an algorithm that will sort an array from lowest to highest value
=end
def merge_sort(lst)
if lst.length <= 1
lst
else
mid = (lst.length / 2).floor
left = merge_sort(lst[0..mid - 1])
right = merge_sort(lst[mid..lst.length])
merge(left, right)
end
end
def merge(left, right)
if left.empty?
right
elsif right.empty?
left
elsif left.first < right.first
[left.first] + merge(left[1..left.length], right)
else
[right.first] + merge(left, right[1..right.length])
end
end
p sort([4,3,2,1])
p sort([4,3,2,1]) == [1,2,3,4]
p sort([-1,-2,3,2]) == [-2,-1,2,3]
# tests
=begin
"it should return a sorted array duh" do
expect sort([4,3,2,1]).to be([1,2,3,4])
end
"it should not get confused by negative numbers" do
expect sort(negative_array).to be([-4,-2,1,2])
end
=end<file_sep>/README.md
This is a repo of various algorithm challenges I complete :)
<file_sep>/alice.rb
def anagram_maker(string1, string2)
string1_array = string1.split('')
string2_array = string2.split('')
combined_characters = string1_array << string2_array
combined_characters.flatten!
character_frequencies = Hash.new(0)
combined_characters.each do |individual_letter|
character_frequencies[individual_letter] += 1
end
p combined_characters
p character_frequencies
p character_frequencies.keys.length
p combined_characters.length
end
#anagrams have the same character set and length
p anagram_maker('cde', 'abc') == 4
p anagram_maker('abbddc', 'abbddcc') == 1
p anagram_maker('efght', 'tfgeh') == 0
p anagram_maker('poito', 'ppoito') == 1
p anagram_maker('vvvvvxyz', 'xyzp') == 6<file_sep>/isomorphic.rb
=begin
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character
while preserving the order of characters. No two characters may map
to the same character but a character may map to itself.
For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
=end
def isomorphic?(string1, string2)
string1_unique_letters = Hash.new(0)
string2_unique_letters = Hash.new(0)
string1.split('').each do |letter|
string1_unique_letters[letter] += 1
end
string2.split('').each do |letter|
string2_unique_letters[letter] += 1
end
string1_unique_letters_count = string1_unique_letters.keys.length
string2_unique_letters_count = string2_unique_letters.keys.length
if string1_unique_letters_count == string2_unique_letters_count
true
else
false
end
end
p isomorphic?('egg', 'add')
p isomorphic?('paper', 'title')
p isomorphic?('wood', 'food')
p isomorphic?('foo', 'bar')
#tests
=begin
"it should yield true for one letter to one letter map"
isomorphic("a","b").to be(truthy)
end
"it should yield true for "
=end<file_sep>/pascal.rb
def pascal_triangle(rows)
if rows <= 0
return "must have at least one row!"
end
pascal_triangle_top = [[1],[1,1]]
return [pascal_triangle_top[0]] if rows == 1
return pascal_triangle_top if rows == 2
return pascal_triangle_top << create_new_row
end
def create_new_row(rows)
additional_rows = []
additional_rows[0] = 1
additional_rows[-1] = 1
return additional_rows
end
p pascal_triangle(0) == "must have at least one row!"
p pascal_triangle(1) == [[1]]
p pascal_triangle(2) == [[1],[1,1]]
p pascal_triangle(4) == [[1],[1,1],[1,2,1],[1,3,3,1]]<file_sep>/klargest.rb
=begin
Find the kth largest element in an unsorted array.
Note that it is the kth largest element in the sorted order,
not the kth distinct element.
For example, given [3,2,1,5,6,4] and k = 2, return 5.
Note: You may assume k is always valid, 1 ≤ k ≤ array's length.
=end
def klargest(array, klargest)
if klargest > array.length
"error"
else
array.sort!
return array[klargest*-1]
end
end
p klargest([1,2,3,4],1) == 4
p klargest([1,2,3,4],2) == 3
p klargest([1],1) == 1
p klargest([1,2],3) == "error"
=begin
#tests
before each do
array = [1,4,3,2]
end
"it should return the largest number if k = 1"
expect klargest(array, 1).to be(4)
end
"it should return 3 if k = 2"
expect klargest(array, 2).to be(3)
end
=end<file_sep>/median.rb
=begin
There are two sorted arrays A and B of size m and n respectively.
Find the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Analysis
If we see log(n), we should think about using binary something.
This problem can be converted to the problem of finding kth element,
k is (A's length + B' Length)/2.
If any of the two arrays is empty,
then the kth element is the non-empty array's kth element.
If k == 0, the kth element is the first element of A or B.
For normal cases(all other cases),
we need to move the pointer at the pace of half of an array length
to get log(n) time.
=end
def median_finder(arrayA, arrayB)
union_array = arrayA.push(*arrayB)
union_array.sort!
total_length = union_array.length
if total_length % 2 == 0
(union_array[(total_length/2)-1] + union_array[(total_length/2)+1])/2
else
union_array[total_length/2]
end
end
p median_finder([1,2,3],[5,6,7]) == 4
p median_finder([1,2,8,5], [29,20,33]) == 8
p median_finder([1,2,3,4],[6,7,8,9]) == 5
#tests
=begin
before do
a = [1,2,3]
b = [4,5,6]
median_finder(a,b)
end
"it should return number inside the range"
expect ((a[0]..b[-1]) === median_finder(a,b)).to be(true)
end
"it should "
=end<file_sep>/gcd.rb
def sherlock_gcd(array)
all_possible_combinations = (2..array.length).flat_map{|size| array.combination(size).to_a }
all_possible_combinations.each do |single_combination|
return "YES" if single_combination[0].gcd(single_combination[1]) == 1
end
return "NO"
end
p sherlock_gcd([1, 2, 3]) == "YES"
p sherlock_gcd([2, 4]) == "NO"
p sherlock_gcd([5, 5, 5]) == "NO"<file_sep>/fibonacci.rb
def create_fibonacci(sequence_length)
p (1...(sequence_length).to_i).inject( [0, 1] ) { | fibonacci | fibonacci << fibonacci.last(2).inject(:+) }
end
create_fibonacci(7)<file_sep>/funnystring.rb
def is_funny?(string1,string2)
end
|
d2f03e844d8ab2c2b5370f4cef7a3dc4ccbcdf4e
|
[
"Markdown",
"Ruby"
] | 24
|
Ruby
|
kduraiswami/algorithmpractice
|
a89281ed1229ab55502c94ee4c643ca211a2e001
|
7cdfb55f8fd4c9a5246f29ad13fe3f27c0040792
|
refs/heads/master
|
<file_sep>import java.util.Scanner; //IMPORTING PACKAGES
import java.io.*;
class Hospital
{
public static void main(String[] args) throws Exception //DECLARING EXCEPTION USING THROWS
{ Appointments a[]=new Appointments[10]; //ARRAY OBJECT CREATION
Medicine m[]=new Medicine[10]; //ARRAY OBJECT CREATION
Medicine o[]=new Medicine[10]; //ARRAY OBJECT CREATION
AppointmentsFile AppointmentsFile;
int booking_number=0;
int order_number=0;
do
{
System.out.println("\n\n\t\tWELCOME TO THE CITY GENERAL HOSPITAL\n");
System.out.println("\t\t1. Doctor Appointment");
System.out.println("\t\t2. Medical Store");
System.out.println("\t\t9. Exit");
System.out.println("Enter the choice number from above and press the ENTER key:");
Scanner sc=new Scanner(System.in);
int choice = Integer.parseInt(sc.nextLine());
switch (choice)
{
case 1:
{
System.out.println("\t\t\t1. Book a new appointment");
System.out.println("\t\t\t2. View all appointments (View your number)");
int choice_appointment = Integer.parseInt(sc.nextLine());
switch (choice_appointment) //NESTED SWITCH
{
case 1:
{
System.out.println("Enter your name: ");
String name=sc.nextLine();
System.out.println("Enter your gender (M/F/O)");
char gender=sc.next().charAt(0);
sc.nextLine();
System.out.println("Enter your age");
int age=Integer.parseInt(sc.nextLine());
try //EXCEPTION HANDLING USING TRY-CATCH
{
if(age>13&&age<32767)
System.out.println("Age vaidated.");
else
{
sc.close();
throw new InvalidAgeException("Invalid age input. It must be beween 13-120"+age);
}
}catch(InvalidAgeException z){System.out.println("Exception occured: "+z);}
a[booking_number]=new Appointments(booking_number+1, name, age, gender);
a[booking_number].start(); // THREAD START
a[booking_number].interrupt(); //THREAD INTERRUPT
AppointmentsFile=new AppointmentsFile(booking_number+1, name, age, gender);
a[booking_number].display_appointment_info();
AppointmentsFile.save_file();
booking_number++;
break;
}
case 2:
{
AppointmentsFile=new AppointmentsFile();
AppointmentsFile.show_file();
break;
}
default:
{
System.out.println("Invalid choice, please enter a valid choice");
}
}
break;
}
case 2:
{
m[0]=new Medicine(101, "Crocin", 20);
m[1]=new Medicine(102, "Betadin", 60);
m[2]=new Medicine(103, "Amoxicillin", 100);
m[3]=new Medicine(104, "Nexium", 150);
m[4]=new Medicine(105, "Aspirin", 200);
m[5]=new Medicine(106, "Combiflam", 30);
m[6]=new Medicine(107, "Azithromycin", 40);
m[7]=new Medicine(108, "<NAME>", 15);
m[8]=new Medicine(109, "Cetirizine", 25);
m[9]=new Medicine(110, "Actos", 70);
System.out.println("\t\tWELCOME TO CITY GENERAL MEDICAL STORE");
System.out.println("\t\t\t1. Check medicine catalogue (Medicine Codes)");
System.out.println("\t\t\t2. Place a new order");
System.out.println("\t\t\t3. Check order details");
int choice_appointment = Integer.parseInt(sc.nextLine());
switch (choice_appointment)
{
case 1:
{
for(int i=0;i<10;i++)
{
m[i].display_medicine_info();
}
break;
}
case 2:
{
for(int r=0;r<10;r++)
{
m[r].display_medicine_info();
}
System.out.println("Enter your name: ");
String name=sc.nextLine();
int code;
String m_name;
int m_price;
int quantity;
int j;
System.out.println("Enter medicine code");
for(;;)
{
code=Integer.parseInt(sc.nextLine());
if(code>=101&&code<=110)
{
break;
}
else
{
System.out.println("Inavlid code, enter the correct code: ");
}
}
for(j=0;j<9;j++)
{
if(code==m[j].medicine_code)
{
m_price=m[j].medicine_price;
m_name=m[j].medicine_name;
System.out.println("Enter quantity");
quantity=Integer.parseInt(sc.nextLine());
o[order_number]=new Medicine();
o[order_number].info(order_number+1, name, quantity, m_price, m_name);
o[order_number].order_print();
o[order_number].info();
order_number++;
break;
}
}
break;
}
case 3:
{
int flag=0;
System.out.println("Enter Order ID you want to search");
int id=Integer.parseInt(sc.nextLine());
for(int l=0;l<10;l++)
{
if(id==o[l].order_id)
{
o[l].info();
flag=1;
break;
}
}
if(flag==0)
{
System.out.println("Order not found");
}
break;
}
default:
{
System.out.println("Invalid choice, please enter a valid choice");
}
}
break;
}
case 9:
{
sc.close();
System.exit(0);
}
default:
{
System.out.println("Invalid choice, please enter a valid choice");
}
}
}while(true);
}
}
class InvalidAgeException extends Exception //CUSTOM EXCEPTION DECLARATION
{
private static final long serialVersionUID = 1L;
InvalidAgeException(String s)
{
super(s);
}
}
interface Printable2 //INTERFACE
{
void display_appointment_info();
}
class Appointments extends Thread implements Printable2 //THREADING AND IMPLEMENTING
{
public int patient_booking_id;
public String patient_name;
public int patient_age;
public char patient_gender;
Appointments() //INITIALIZING CONSTRUCTOR
{
}
Appointments(int _booking_id, String _name, int _age, char _gender) //PARAMETERIZED CONSTRUCTOR AND CONSTRUCTOR OVERLOADING
{
this.patient_booking_id=_booking_id;
this.patient_name=_name;
this.patient_age=_age;
this.patient_gender=_gender;
}
public void display_appointment_info()
{
System.out.println("Booking ID: "+patient_booking_id);
System.out.println("Name: "+patient_name);
System.out.println("Age: "+patient_age);
System.out.println("Gender: "+patient_gender);
}
// public void appointment_print() //METHOD USING ABSTRACT CLASS
public void run() //THREAD RUN METHOD
{
System.out.println("-----APPOINTMENT BOOKED SUCCESSFULLY-----");
}
}
class AppointmentsFile extends Appointments //INHERITANCE
{
AppointmentsFile()
{
}
AppointmentsFile(int _booking_id, String _name, int _age, char _gender)
{
super(_booking_id, _name, _age, _gender);
}
public void save_file() throws Exception //DECLARING EXCEPTION USING THROWS
{
if (patient_booking_id==1)
{
FileWriter fw=new FileWriter("appointments.txt"); //FILE HANDLING
fw.write("Booking ID: "+patient_booking_id+", ");
fw.write("Name: "+patient_name+", ");
fw.write("Age: "+patient_age+", ");
fw.write("Gender: "+patient_gender+"\n");
fw.close();
}
else
{
FileWriter fw=new FileWriter("appointments.txt", true); //FILE HANDLING
fw.write("Booking ID: "+patient_booking_id+", ");
fw.write("Name: "+patient_name+", ");
fw.write("Age: "+patient_age+", ");
fw.write("Gender: "+patient_gender+"\n");
fw.close();
}
}
public void show_file() throws Exception //DECLARING EXCEPTION USING THROWS
{
FileReader fr=new FileReader("appointments.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
System.out.println(" ");
fr.close();
}
}
abstract class Printable //ABSTRACT CLASS
{
abstract void order_print();
abstract void display_medicine_info();
abstract void info();
}
class Medicine extends Printable //INTERFACE IMPLEMENTATION
{
int order_id;
String customer_name;
int medicine_quantity;
int total_bill;
int medicine_code;
String medicine_name;
int medicine_price;
Medicine() //INITIALIZING DEFAULT CONSTRUCTOR
{
medicine_code=0;
medicine_name=null;
medicine_price=0;
}
Medicine(int medicine_code, String medicine_name, int medicine_price) //PARAMETERIZED CONSTRUCTOR
{
this.medicine_code=medicine_code;
this.medicine_name=medicine_name;
this.medicine_price=medicine_price;
}
public void display_medicine_info()
{
System.out.println("Code: "+medicine_code+", Medicine Name: "+medicine_name+", Price: "+medicine_price);
}
public void info(int order_id, String customer_name, int medicine_quantity, int m_price, String m_name) //METHOD OVERLOADING
{
this.order_id=order_id;
this.customer_name=customer_name;
this.medicine_quantity=medicine_quantity;
this.medicine_price=m_price;
this.medicine_name=m_name;
this.total_bill=(medicine_price*medicine_quantity);
}
public void info() //METHOD OVERLOADING
{
System.out.println("Order ID: "+order_id);
System.out.println("Name: "+customer_name);
System.out.println("Medicine Name: "+medicine_name);
System.out.println("Price: "+medicine_price);
System.out.println("Quantity: "+medicine_quantity);
System.out.println("Total Bill: "+total_bill);
}
public void order_print() //METHOD USING INTERFACE
{
System.out.println("-----ORDER PLACED SUCCESSFULLY-----");
}
}
|
326f5cbe4873f642ddac2120351ea1bfff5835c8
|
[
"Java"
] | 1
|
Java
|
GarvMaggu/Java-Project
|
6290284064a464ca82c0dba4f7c6d7c3e46eb732
|
0442163731ff8cc9397d815719d8702965f4f97f
|
refs/heads/master
|
<file_sep>require_relative '../nakamoto_institute_scrapper'
class NakamotoInstituteScrapper::Document
attr_accessor :name, :author, :date, :url
@@all =[]
def self.all
@@all
end
def save
@@all << self
end
def self.reset
@@all = []
end
end
<file_sep>require_relative '../nakamoto_institute_scrapper'
class NakamotoInstituteScrapper::CLI
def call
make_a_search = true
puts "Welcome to Nakamoto Institute Scrapper"
while make_a_search == true
NakamotoInstituteScrapper::Scrapper.new
menu_list_of_documents
make_a_search = new_request?
end
end
def menu_list_of_documents
puts "The documents available are:"
display_documents
puts "What document do you want more info on?"
input = get_user_input
if input.to_i > 0 && input.to_i <= NakamotoInstituteScrapper::Document.all.size
document = NakamotoInstituteScrapper::Document.all[input.to_i - 1]
display_documents_info(document)
else
puts "Selection unclear - please type the number of the document you want to check."
sleep 3
menu_list_of_documents
end
end
def display_documents
NakamotoInstituteScrapper::Document.all.each_with_index do |document, index|
puts "#{index +1} - #{document.name}"
end
end
def display_documents_info(document_object)
puts "#{document_object.name} has been written by #{document_object.author} on #{document_object.date}\nYou can access the document here:#{document_object.url}"
end
def new_request?
puts "Do you want to check another document? (Y/N)"
user_input = get_user_input.downcase
case user_input
when "y"
NakamotoInstituteScrapper::Document.reset
true
when "n"
false
else puts "selection_unclear - please type Y or N"
new_request?
end
end
def get_user_input
gets.to_s.strip
end
end
<file_sep>require_relative '../nakamoto_institute_scrapper'
class NakamotoInstituteScrapper::Scrapper
def initialize
self.scrap_website
end
def scrap_website
@doc = Nokogiri::HTML(open("http://nakamotoinstitute.org/literature/"))
puts "scrapping website"
# binding.pry
scrap_table
#binding.pry
end
def scrap_table
table = @doc.at('table').css('tbody')
table.search('tr').each do |tr|
#binding.pry
column_count = 0
document = NakamotoInstituteScrapper::Document.new
tr.search('td').each do |td|
case (column_count % 4)
when 0
document.name = td.text.strip.tr('"', '')
document.url = td.css("a").attr("href").value.prepend("http://nakamotoinstitute.org")
#when 1 - not used as we don't collect formats
when 2
document.author = td.text.strip.gsub(/\s\s+/,' ')
when 3
document.date = td.text.strip
end
column_count +=1
end
document.save
end
end
end
<file_sep>require_relative "./nakamoto_institute_scrapper/version"
require_relative "./nakamoto_institute_scrapper/cli"
require_relative "./nakamoto_institute_scrapper/document"
require_relative "./nakamoto_institute_scrapper/scrapper"
require 'pry'
require 'nokogiri'
require 'open-uri'
module NakamotoInstituteScrapper
# Your code goes here...
end
|
4d376c441bbbf2c5a913548a0d73bb98d416deac
|
[
"Ruby"
] | 4
|
Ruby
|
smartcontrart/Nakamoto_Institute_Scrapper
|
4f6b2b3dfeab277f9158fdcdc198ffe9ae72a49e
|
22264ece4d5093b793b47e17136efcbc555fbd40
|
refs/heads/master
|
<file_sep>using Microsoft.ServiceBus;
using PrintServiceHost;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace PrintServiceClient
{
class Program
{
static void Main(string[] args)
{
ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Https;
var cf = new ChannelFactory<IPrintChannel>(
new NetTcpRelayBinding { IsDynamic = true },
new EndpointAddress(ServiceBusEnvironment.CreateServiceUri("sb", "[Servicebusnamespace]", "printservice"))); //add Servicebusnamespace
cf.Endpoint.Behaviors.Add(new TransportClientEndpointBehavior
{ TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider("[KeyName]", "[Key]") });//add SAS keyname and key
IPrintChannel channel = cf.CreateChannel();
channel.Open();
Console.WriteLine(channel.SendToPrintQueue(new PrintInfo { DocumentName = "sample.pdf", ContainerName = "documents", PrintQueueName = "queue1" })); // update document name and container name as applicable.
channel.Close();
cf.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace PrintServiceHost
{
[ServiceContract(Name = "IPrintContract", Namespace = "urn:ps")]
public interface IPrintContract
{
[OperationContract]
string SendToPrintQueue(PrintInfo printInfo);
}
public interface IPrintChannel : IPrintContract, IClientChannel { }
}
<file_sep># Cloudprintsample
This is a simple cloud print sample using azure service bus relay.
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Printing;
using System.IO;
namespace PrintServiceHost
{
[ServiceBehavior(Name = "PrintService", Namespace = "urn:ps")]
public class PrintService : IPrintContract
{
/// <summary>
/// gets the print info from the request , downloads the document and sends it to print queue.
/// </summary>
/// <param name="printInfo"></param>
/// <returns>status string</returns>
public string SendToPrintQueue(PrintInfo printInfo)
{
try
{
DownloadDocumentfromCloudStorage(printInfo);
return "success";
}
catch (Exception exp)
{
return "failure :"+exp.Message;
}
}
private void DownloadDocumentfromCloudStorage(PrintInfo printInfo)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve a reference to a container.
CloudBlobContainer container = blobClient.GetContainerReference(printInfo.ContainerName);
CloudBlockBlob blockBlob2 = container.GetBlockBlobReference(printInfo.DocumentName);
using (var memoryStream = new MemoryStream())
{
blockBlob2.DownloadToStream(memoryStream);
// Create the printer server and print queue objects
LocalPrintServer localPrintServer2 = new LocalPrintServer();
PrintQueue defaultPrintQueue2 = LocalPrintServer.GetDefaultPrintQueue();
// Call AddJob
PrintSystemJobInfo anotherPrintJob = defaultPrintQueue2.AddJob("MyJob");
// Write a Byte buffer to the JobStream and close the stream
Stream anotherStream = anotherPrintJob.JobStream;
Byte[] anotherByteBuffer = memoryStream.ToArray();
anotherStream.Write(anotherByteBuffer, 0, anotherByteBuffer.Length);
anotherStream.Close();
}
}
}
}
<file_sep>using System.ServiceModel;
namespace PrintServiceHost
{
[ServiceContract(Name ="IPrintContract", Namespace = "urn:ps")]
public interface IPrintContract
{
[OperationContract]
string SendToPrintQueue(PrintInfo printInfo);
}
public interface IPrintChannel : IPrintContract, IClientChannel { }
}
<file_sep>using Microsoft.ServiceBus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace PrintServiceHost
{
class Program
{
static void Main(string[] args)
{
ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Https;
ServiceHost sh = new ServiceHost(typeof(PrintService));
sh.Open();
Console.WriteLine("Press ENTER to close");
Console.ReadLine();
sh.Close();
}
}
}
<file_sep>using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace PrintServiceHost
{
[DataContract]
public class PrintInfo
{
[DataMember]
public string DocumentName { get; set; }
[DataMember]
public string ContainerName { get; set; }
[DataMember]
public string PrintQueueName { get; set; }
}
}
|
1f94996306963a95634e4be152f87f083124ab35
|
[
"Markdown",
"C#"
] | 7
|
C#
|
vkaravind/Cloudprintsample
|
314a4ead42c2b44e9f8a13fb8d6a59cde976a695
|
8da2f7bbd2705883f36fd72650523992d807c605
|
refs/heads/main
|
<repo_name>Adeliyaaa/oop_5th_sem<file_sep>/3rd_lab/src/com/company/Main.java
package com.company;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
PhoneBook test = new PhoneBook();
test.addNewContact("Maria", "Lugovaya", TypeOfContact.HOME_PHONE, "88559552806");
test.addNumber("Maria", "Lugovaya", TypeOfContact.WORK, "837894479");
test.addNumber("Maria", "Lugovaya", TypeOfContact.MOBILE_PHONE, "8989898655");
test.addNewContact("Rufina", "Talalaeva", TypeOfContact.MOBILE_PHONE, "89238393892");
test.addNewContact("Regina", "Tavabilova", TypeOfContact.WORK, "8928394223");
test.editName("Rufina", "Talalaeva", "Rufina", "Rizatdinova");
test.deleteContact("Regina", "Tavabilova");
test.addNewContact("Olga", "Chernuhina", TypeOfContact.MOBILE_PHONE, "8989239883");
test.deleteNumber("837894479");
test.findNumbers("80909090");
test.addNewContact("Anastasia", "Zhukova", TypeOfContact.TG_ALIAS, "@helloworld");
test.addNewContact("Kristina", "Vedenskaya", TypeOfContact.VK_ALIAS, "@kristina_super");
}
}
<file_sep>/Course project/src/main/java/FileSource.java
import java.io.IOException;
import java.util.List;
public interface FileSource {
void toFile(List<Student> list) throws IOException;
List<Student> fromFile() throws IOException;
}<file_sep>/6th_lab/src/main/java/AddSquare.java
import shapesPackage.addedListener;
import shapesPackage.Square;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AddSquare extends JDialog {
private JTextField textField1;
private JButton addFigureButton;
private JButton cancelButton;
private JPanel contentPane;
private JLabel sideMustBeGreaterLabel;
public AddSquare(addedListener listener) {
setModal(true);
setContentPane(contentPane);
sideMustBeGreaterLabel.setForeground(Color.RED);
sideMustBeGreaterLabel.setVisible(false);
setSize(300, 200);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
addFigureButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double side;
side = Double.parseDouble(textField1.getText());
if (side <= 0)
sideMustBeGreaterLabel.setVisible(true);
else {
listener.onAdded(new Square(side));
dispose();
}
}
});
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPane = new JPanel();
contentPane.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(3, 1, new Insets(10, 10, 10, 10), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(3, 2, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel1, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
addFigureButton = new JButton();
addFigureButton.setText("Add Square");
panel1.add(addFigureButton, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
cancelButton = new JButton();
cancelButton.setText("Cancel");
panel1.add(cancelButton, new com.intellij.uiDesigner.core.GridConstraints(2, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
textField1 = new JTextField();
panel1.add(textField1, new com.intellij.uiDesigner.core.GridConstraints(2, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("Put side size here");
panel1.add(label1, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
sideMustBeGreaterLabel = new JLabel();
sideMustBeGreaterLabel.setText("Side must be greater than zero");
panel1.add(sideMustBeGreaterLabel, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final com.intellij.uiDesigner.core.Spacer spacer1 = new com.intellij.uiDesigner.core.Spacer();
contentPane.add(spacer1, new com.intellij.uiDesigner.core.GridConstraints(2, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final com.intellij.uiDesigner.core.Spacer spacer2 = new com.intellij.uiDesigner.core.Spacer();
contentPane.add(spacer2, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPane;
}
}
<file_sep>/5th_labb/src/main/java/shapeConverter.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.*;
import java.lang.reflect.Type;
import java.util.List;
public class shapeConverter {
private final String fileName;
public shapeConverter(String fileName) {
this.fileName = fileName;
}
public void convertToJson(List<Shape> shapes) throws IOException {
try (Writer writer = new FileWriter(fileName, false)) {
Type type = new TypeToken<List<Shape>>() {}.getType();
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(Shape.class, new shapeSerializer())
.create();
gson.toJson(shapes, type, writer);
} catch (IOException e) {
throw new IOException("Error! check the file");
}
}
public List<Shape> convertFromJson () throws IOException {
try (FileReader reader = new FileReader(fileName)) {
Type type = new TypeToken<List<Shape>>() {}.getType();
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(Shape.class, new shapeSerializer())
.create();
List<Shape> listOfShapes = gson.fromJson(reader, type);
return listOfShapes;
} catch (IOException e) {
throw new IOException("Error! check the file");
}
}
}
<file_sep>/Course project/src/main/java/ReportSource.java
import java.io.IOException;
import java.util.List;
public interface ReportSource {
void toFile(Report report) throws IOException;
Report fromFile() throws IOException;
}<file_sep>/4th_lab/src/com/company/Shape.java
package com.company;
interface Shape {
double calcArea();
double calcPerimeter();
}
<file_sep>/4th_lab/src/com/company/ShapeAccumulator.java
package com.company;
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import static java.lang.System.out;
public class ShapeAccumulator {
List <Shape> ShapesList;
public ShapeAccumulator(){
ShapesList = new ArrayList<>();
}
public <T extends Shape> void add (T shape){
ShapesList.add(shape);
}
public void addAll (Collection<? extends Shape> allFigures){
ShapesList.addAll(allFigures);
}
public Shape getMaxAreaShape(){
ShapesList.sort(Comparator.comparingDouble(Shape::calcArea));
return ShapesList.get(ShapesList.size()-1);
}
public Shape getMinAreaShape(){
ShapesList.sort(Comparator.comparingDouble(Shape::calcArea));
return ShapesList.get(0);
}
public Shape getMaxPerimeterShape(){
ShapesList.sort(Comparator.comparingDouble(Shape::calcPerimeter));
return ShapesList.get(ShapesList.size()-1);
}
public Shape getMinPerimeterShape(){
ShapesList.sort(Comparator.comparingDouble(Shape::calcPerimeter));
return ShapesList.get(0);
}
public double getTotalArea(){
return ShapesList.stream().mapToDouble(Shape::calcArea).sum();
}
public double getTotalPerimeter(){
return ShapesList.stream().mapToDouble(Shape::calcPerimeter).sum();
}
}
<file_sep>/1st_lab/src/com/company/Main.java
package com.company;
import static java.lang.System.out;
public class Main {
public static void main(String[] args) {
Matrix A = new Matrix(3, 3);
A.set_value(1, 0, 0);
A.set_value(2, 0, 1);
A.set_value(3, 1, 0);
A.set_value(4, 1, 1);
A.set_value(5, 0, 2);
A.set_value(6, 1, 2);
A.set_value(7, 2, 2);
A.set_value(8, 2, 0);
A.set_value(9, 2, 1);
out.println(A);
Matrix B = A.transpose();
out.println(B);
Matrix C = A.times(B);
out.println(C);
Matrix D = C.multiply(2);
out.println(D);
D = C.plus(A);
out.println(D);
D = D.minus(B);
out.println(D);
out.println(D.determinant());
out.println(A.equals(B));
}
}
<file_sep>/Course project/src/main/java/ReportConverter.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.*;
import java.lang.reflect.Type;
import java.util.List;
public class ReportConverter {
private final String fileName;
public ReportConverter(String fileName) {
this.fileName = fileName;
}
public void convertToJson(Report report) throws IOException {
try (Writer writer = new FileWriter(fileName, false)) {
Type type = new TypeToken<Report>() {}.getType();
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(Report.class, new ReportSerializer())
.create();
gson.toJson(report, type, writer);
} catch (IOException e) {
throw new IOException("Error! check the file");
}
}
public Report convertFromJson () throws IOException {
try (FileReader reader = new FileReader(fileName)) {
Type type = new TypeToken<Report>() {}.getType();
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(Report.class, new ReportSerializer())
.create();
Report report = gson.fromJson(reader, type);
return report;
} catch (IOException e) {
throw new IOException("Error! check the file");
}
}
}<file_sep>/2nd_lab/src/com/company/Main.java
package com.company;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import static java.lang.System.out;
public class Main {
public static void main(String[] args) {
List <Shape> ShapesList = new ArrayList<>();
ShapesList.add(new Circles(7));
ShapesList.add(new Triangle(3, 4, 5));
ShapesList.add(new Rect(5, 8));
ShapesList.add(new Square(15));
ShapesList.add(new Triangle(12, 17, 14));
ShapesList.add(new Circles(14));
ShapesList.add(new Rect(9, 15));
out.println("The list of shapes we have:");
ShapesList.forEach(shape -> out.println(shape.toString()));
//sorting by perimeter
ShapesList.sort(Comparator.comparingDouble(Shape::calcPerimeter));
out.println("The shape with the largest perimeter is:");
out.println(ShapesList.get(ShapesList.size()-1).toString());
out.println("The shape with the smallest perimeter is:");
out.println(ShapesList.get(0).toString());
//sorting by area
ShapesList.sort(Comparator.comparingDouble(Shape::calcArea));
out.println("The shape with the largest area is:");
out.println(ShapesList.get(ShapesList.size()-1).toString());
out.println("The shape with the smallest area is:");
out.println(ShapesList.get(0).toString());
//calculating total area
double Area = ShapesList.stream().mapToDouble(Shape::calcArea).sum();
out.println("Total area of the shapes is " + Area);
}
}
<file_sep>/Course project/src/main/java/ReportMenu.java
import javax.swing.*;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import java.awt.*;
import java.awt.event.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.io.FileOutputStream;
import org.apache.poi.*;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
//import org.apache.poi.hssf.usermodel.XSSFWorkbook;
//import org.apache.poi.ss.usermodel.*;
//import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
//import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReportMenu extends JDialog {
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JButton addStudentButton;
private JButton removeStudentButton;
private JList studentsList;
private JComboBox comboBox1;
private JButton confirmButton;
private JButton setProfessorButton;
private JButton saveToFileButton;
private JLabel group;
private JLabel subject;
private JLabel prof;
private JButton setGroupButton;
private JComboBox comboBox2;
private JComboBox comboBox3;
private JButton setSubjectButton;
private JComboBox comboBox4;
private JRadioButton a2RadioButton;
private JRadioButton a3RadioButton;
private JRadioButton a4RadioButton;
private JRadioButton a5RadioButton;
private JLabel groupLabel;
private JLabel errorLabel;
public ReportMenu() {
setBounds(300, 100, 800, 300);
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
errorLabel.setForeground(Color.red);
errorLabel.setVisible(false);
Report report;
ReportConverter converter = new ReportConverter("report.json");
DefaultListModel<Student> listModel = new DefaultListModel<>();
try {
report = converter.convertFromJson();
for (Student temp : report.getStudents()) {
listModel.addElement(temp);
group.setText(String.valueOf((int) report.getGroupNumber()));
subject.setText(report.getSubject());
prof.setText(report.getFullname());
}
} catch (IOException e) {
JOptionPane.showMessageDialog(ReportMenu.this, "Error! Couldn't upload the file");
e.printStackTrace();
}
studentsList.setListData(listModel.toArray());
ButtonGroup groupGrades = new ButtonGroup();
groupGrades.add(a2RadioButton);
groupGrades.add(a3RadioButton);
groupGrades.add(a4RadioButton);
groupGrades.add(a5RadioButton);
listModel.addListDataListener(new ListDataListener() {
@Override
public void intervalAdded(ListDataEvent e) {
studentsList.setListData(listModel.toArray());
}
@Override
public void intervalRemoved(ListDataEvent e) {
studentsList.setListData(listModel.toArray());
}
@Override
public void contentsChanged(ListDataEvent e) {
studentsList.setListData(listModel.toArray());
}
});
buttonCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
});
// call onCancel() when cross is clicked
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
onCancel();
}
});
// call onCancel() on ESCAPE
contentPane.registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
addStudentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AddStudent addStudent = new AddStudent(listModel::addElement);
addStudent.setVisible(true);
}
});
removeStudentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (studentsList.isSelectionEmpty()) {
errorLabel.setText("Select student first");
errorLabel.setVisible(true);
} else {
listModel.remove(studentsList.getSelectedIndex());
errorLabel.setVisible(false);
}
}
});
confirmButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (studentsList.isSelectionEmpty()) {
errorLabel.setText("Select student first");
errorLabel.setVisible(true);
} else if (!a2RadioButton.isSelected() && !a3RadioButton.isSelected() &&
!a4RadioButton.isSelected() && !a5RadioButton.isSelected()) {
errorLabel.setText("Select grade value first");
errorLabel.setVisible(true);
} else {
int selectedIndex = studentsList.getSelectedIndex();
if (a2RadioButton.isSelected())
listModel.getElementAt(selectedIndex).addGrade(2);
else if (a3RadioButton.isSelected())
listModel.getElementAt(selectedIndex).addGrade(3);
else if (a4RadioButton.isSelected())
listModel.getElementAt(selectedIndex).addGrade(4);
else
listModel.getElementAt(selectedIndex).addGrade(5);
errorLabel.setVisible(false);
}
}
});
setGroupButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Report anotherReport;
//now you can add new group
if (comboBox2.getSelectedItem().equals("Add new...")) {
String result = JOptionPane.showInputDialog(
ReportMenu.this,
"Fill in new group's number");
comboBox2.addItem(result);
anotherReport = new Report(Integer.parseInt(result), subject.getText());
String fileName = result + ".json";
ReportConverter newConverter = new ReportConverter(fileName);
try {
newConverter.convertToJson(anotherReport);
} catch (IOException x) {
JOptionPane.showMessageDialog(ReportMenu.this, "Error! Couldn't save to the file");
x.printStackTrace();
}
} else {
String fileName = comboBox2.getSelectedItem().toString() + ".json";
ReportConverter anotherConverter = new ReportConverter(fileName);
try {
anotherReport = anotherConverter.convertFromJson();
listModel.removeAllElements();
for (Student temp : anotherReport.getStudents()) {
listModel.addElement(temp);
group.setText(String.valueOf((int) anotherReport.getGroupNumber()));
subject.setText(anotherReport.getSubject());
prof.setText(anotherReport.getFullname());
}
} catch (IOException x) {
JOptionPane.showMessageDialog(ReportMenu.this, "Error! Couldn't upload the group list");
x.printStackTrace();
}
group.setText(comboBox2.getSelectedItem().toString());
studentsList.setListData(listModel.toArray());
errorLabel.setVisible(false);
}
}
});
setSubjectButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//now you can add new subject
if (comboBox4.getSelectedItem().equals("Add new...")) {
String result = JOptionPane.showInputDialog(
ReportMenu.this,
"Fill in new subject's name");
comboBox4.addItem(result);
}
else if (comboBox4.getSelectedIndex() > -1) {
subject.setText(comboBox4.getSelectedItem().toString());
errorLabel.setVisible(false);
}
//now you can add new subject
else {
errorLabel.setText("Select subject first");
errorLabel.setVisible(true);
}
}
});
setProfessorButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (comboBox3.getSelectedItem().equals("Add new...")) {
//now you can add new prof
String result = JOptionPane.showInputDialog(
ReportMenu.this,
"Fill in new professor's surname, name and lastname");
comboBox3.addItem(result);
}
else if (comboBox3.getSelectedIndex() > -1) {
prof.setText(comboBox3.getSelectedItem().toString());
errorLabel.setVisible(false);
} else {
errorLabel.setText("Select professor first");
errorLabel.setVisible(true);
}
}
});
saveToFileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Report newReport = new Report(Integer.parseInt(group.getText()), subject.getText());
String[] arrSplit = prof.getText().split(" ");
newReport.setProfessor(arrSplit[0], arrSplit[1], arrSplit[2]);
List<Student> newstuds = new ArrayList<>();
for (int i = 0; i < listModel.getSize(); i++) {
newstuds.add(listModel.elementAt(i));
}
newReport.setStudents(newstuds);
String fileName;
//Changed to fileName instead of writing all the groups
fileName = comboBox2.getSelectedItem().toString() + ".json";
ReportConverter newConverter = new ReportConverter(fileName);
try {
newConverter.convertToJson(newReport);
} catch (IOException x) {
JOptionPane.showMessageDialog(ReportMenu.this, "Error! Couldn't save to the file");
x.printStackTrace();
}
}
});
buttonOK.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String filename = "Report.xls";
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
Row headerRow = sheet.createRow(0);
Cell cell = headerRow.createCell(0);
cell.setCellValue("Group: " + group.getText());
cell = headerRow.createCell(1);
cell.setCellValue("Subject: " + subject.getText());
cell = headerRow.createCell(2);
cell.setCellValue("Professor: " + prof.getText());
cell = headerRow.createCell(3);
headerRow = sheet.createRow(1);
cell = headerRow.createCell(0);
cell.setCellValue("Surname");
cell = headerRow.createCell(1);
cell.setCellValue("Name");
cell = headerRow.createCell(2);
cell.setCellValue("Lastname");
cell = headerRow.createCell(3);
cell.setCellValue("Grade");
int rowNum = 2;
List<Student> newstuds = new ArrayList<>();
for (int i = 0; i < listModel.getSize(); i++) {
newstuds.add(listModel.elementAt(i));
}
for (Student stud : newstuds) {
Row row = sheet.createRow(rowNum++);
row.createCell(0)
.setCellValue(stud.getSurname());
row.createCell(1)
.setCellValue(stud.getName());
row.createCell(2)
.setCellValue(stud.getLastname());
row.createCell(3)
.setCellValue(stud.getGrade());
}
for (int i = 0; i < 4; i++) {
sheet.autoSizeColumn(i);
}
String Filename;
Filename = group.getText() + ' ' + subject.getText() + ".xlsx";
FileOutputStream fileOut = new FileOutputStream(Filename);
workbook.write(fileOut);
fileOut.close();
// Closing the workbook
workbook.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(ReportMenu.this, "Error! Couldn't save to the file");
ex.printStackTrace();
}
}
});
}
private void onOK() {
// add your code here
dispose();
}
private void onCancel() {
// add your code here if necessary
dispose();
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPane = new JPanel();
contentPane.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(3, 1, new Insets(10, 10, 10, 10), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel1, new com.intellij.uiDesigner.core.GridConstraints(2, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false));
panel1.add(panel2, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
buttonOK = new JButton();
buttonOK.setText("Save to Excel");
panel2.add(buttonOK, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
buttonCancel = new JButton();
buttonCancel.setText("Exit");
panel2.add(buttonCancel, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
saveToFileButton = new JButton();
saveToFileButton.setText("Save to File");
panel1.add(saveToFileButton, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(4, 3, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel3, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JPanel panel4 = new JPanel();
panel4.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(4, 1, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(panel4, new com.intellij.uiDesigner.core.GridConstraints(0, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
addStudentButton = new JButton();
addStudentButton.setText("Add Student");
panel4.add(addStudentButton, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
removeStudentButton = new JButton();
removeStudentButton.setText("Remove Student");
panel4.add(removeStudentButton, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("Set Grade");
panel4.add(label1, new com.intellij.uiDesigner.core.GridConstraints(2, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel5 = new JPanel();
panel5.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
panel4.add(panel5, new com.intellij.uiDesigner.core.GridConstraints(3, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JPanel panel6 = new JPanel();
panel6.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 4, new Insets(0, 0, 0, 0), -1, -1));
panel5.add(panel6, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
a2RadioButton = new JRadioButton();
a2RadioButton.setText("2");
panel6.add(a2RadioButton, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
a4RadioButton = new JRadioButton();
a4RadioButton.setText("4");
panel6.add(a4RadioButton, new com.intellij.uiDesigner.core.GridConstraints(0, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
a5RadioButton = new JRadioButton();
a5RadioButton.setText("5");
panel6.add(a5RadioButton, new com.intellij.uiDesigner.core.GridConstraints(0, 3, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
a3RadioButton = new JRadioButton();
a3RadioButton.setText("3");
panel6.add(a3RadioButton, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel7 = new JPanel();
panel7.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
panel5.add(panel7, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
confirmButton = new JButton();
confirmButton.setText("Confirm");
panel7.add(confirmButton, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
group = new JLabel();
Font groupFont = this.$$$getFont$$$("Lora", -1, -1, group.getFont());
if (groupFont != null) group.setFont(groupFont);
group.setText("Label");
panel3.add(group, new com.intellij.uiDesigner.core.GridConstraints(1, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
groupLabel = new JLabel();
Font groupLabelFont = this.$$$getFont$$$(null, -1, -1, groupLabel.getFont());
if (groupLabelFont != null) groupLabel.setFont(groupLabelFont);
groupLabel.setText("Group:");
panel3.add(groupLabel, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
subject = new JLabel();
Font subjectFont = this.$$$getFont$$$("Lora", -1, -1, subject.getFont());
if (subjectFont != null) subject.setFont(subjectFont);
subject.setText("Label");
panel3.add(subject, new com.intellij.uiDesigner.core.GridConstraints(2, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label2 = new JLabel();
label2.setText("Subject:");
panel3.add(label2, new com.intellij.uiDesigner.core.GridConstraints(2, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
prof = new JLabel();
Font profFont = this.$$$getFont$$$("Lora", -1, -1, prof.getFont());
if (profFont != null) prof.setFont(profFont);
prof.setText("Label");
panel3.add(prof, new com.intellij.uiDesigner.core.GridConstraints(3, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("Professor:");
panel3.add(label3, new com.intellij.uiDesigner.core.GridConstraints(3, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel8 = new JPanel();
panel8.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(panel8, new com.intellij.uiDesigner.core.GridConstraints(1, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
setGroupButton = new JButton();
setGroupButton.setText("Set Group");
panel8.add(setGroupButton, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
comboBox2 = new JComboBox();
final DefaultComboBoxModel defaultComboBoxModel1 = new DefaultComboBoxModel();
defaultComboBoxModel1.addElement("Add new...");
defaultComboBoxModel1.addElement("8301");
defaultComboBoxModel1.addElement("8302");
defaultComboBoxModel1.addElement("8309");
comboBox2.setModel(defaultComboBoxModel1);
panel8.add(comboBox2, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel9 = new JPanel();
panel9.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(panel9, new com.intellij.uiDesigner.core.GridConstraints(2, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
setSubjectButton = new JButton();
setSubjectButton.setText("Set Subject");
panel9.add(setSubjectButton, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
comboBox4 = new JComboBox();
final DefaultComboBoxModel defaultComboBoxModel2 = new DefaultComboBoxModel();
defaultComboBoxModel2.addElement("Add new...");
defaultComboBoxModel2.addElement("Data Bases");
defaultComboBoxModel2.addElement("Economics");
defaultComboBoxModel2.addElement("Operation Systems");
defaultComboBoxModel2.addElement("OOP");
defaultComboBoxModel2.addElement("Methods of Optimization");
defaultComboBoxModel2.addElement("Metrology");
defaultComboBoxModel2.addElement("Schematics");
defaultComboBoxModel2.addElement("Foreign Language");
comboBox4.setModel(defaultComboBoxModel2);
panel9.add(comboBox4, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel10 = new JPanel();
panel10.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(panel10, new com.intellij.uiDesigner.core.GridConstraints(3, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
setProfessorButton = new JButton();
setProfessorButton.setText("Set Professor");
panel10.add(setProfessorButton, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
comboBox3 = new JComboBox();
final DefaultComboBoxModel defaultComboBoxModel3 = new DefaultComboBoxModel();
defaultComboBoxModel3.addElement("Add new...");
defaultComboBoxModel3.addElement("<NAME>");
defaultComboBoxModel3.addElement("<NAME>");
defaultComboBoxModel3.addElement("<NAME>");
defaultComboBoxModel3.addElement("<NAME>");
defaultComboBoxModel3.addElement("<NAME>");
defaultComboBoxModel3.addElement("<NAME>");
defaultComboBoxModel3.addElement("<NAME>");
comboBox3.setModel(defaultComboBoxModel3);
panel10.add(comboBox3, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
studentsList = new JList();
Font studentsListFont = this.$$$getFont$$$("Lora", -1, -1, studentsList.getFont());
if (studentsListFont != null) studentsList.setFont(studentsListFont);
final DefaultListModel defaultListModel1 = new DefaultListModel();
studentsList.setModel(defaultListModel1);
panel3.add(studentsList, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 2, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, null, new Dimension(150, 50), null, 0, false));
errorLabel = new JLabel();
errorLabel.setText("Label");
contentPane.add(errorLabel, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
private Font $$$getFont$$$(String fontName, int style, int size, Font currentFont) {
if (currentFont == null) return null;
String resultName;
if (fontName == null) {
resultName = currentFont.getName();
} else {
Font testFont = new Font(fontName, Font.PLAIN, 10);
if (testFont.canDisplay('a') && testFont.canDisplay('1')) {
resultName = fontName;
} else {
resultName = currentFont.getName();
}
}
return new Font(resultName, style >= 0 ? style : currentFont.getStyle(), size >= 0 ? size : currentFont.getSize());
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPane;
}
}
<file_sep>/3rd_lab/src/com/company/Contact.java
package com.company;
import java.util.List;
import java.util.ArrayList;
public class Contact {
private String name;
private String surname;
List <info> ListOfContactInfo;
public Contact(String name, String surname, TypeOfContact type, String num) {
this.name = name;
this.surname = surname;
this.ListOfContactInfo = new ArrayList<>();
info data = new info(type, num);
ListOfContactInfo.add(data);
}
public Contact (String name, String surname, List <info> ListOfContactInfo){
this.name = name;
this.surname = surname;
this.ListOfContactInfo = new ArrayList<>(ListOfContactInfo);
}
public String getName() {
return name;
}
public String getSurname(){
return surname;
}
public void setName(String newName, String newSurname) {
name = newName;
surname = newSurname;
}
public void addNumber(TypeOfContact type, String num) {
info data = new info(type, num);
ListOfContactInfo.add(data);
}
public Contact find (String part){
List <info> found = new ArrayList<>();
found = findNumber(part);
Contact temporary;
if (found.size() > 0){
temporary = new Contact(name, surname, found);
return temporary;
}
else
return null;
}
public info findOne (String number) {
for (info temp : ListOfContactInfo)
if (temp.getNumber().equals(number))
return temp;
return null;
}
public List <info> findNumber(String part){
List <info> found = new ArrayList<>();
for (info looking : ListOfContactInfo){
if (looking.getNumber().contains(part)){
found.add(looking);
}
}
return found;
}
public boolean deleteNumber(String num){
info deleting = findOne(num);
if (deleting != null){
ListOfContactInfo.remove(deleting);
return true;
}
else
return false;
}
public void editNumber(String oldNumber, String newNumber){
info temp = findOne(oldNumber);
if (temp != null){
temp.setNumber(newNumber);
}
else
throw new IllegalArgumentException("Contact with this number does not exist");
}
@Override
public String toString() {
return name + ' ' + surname + ' ' + ListOfContactInfo.toString();
}
}
class info {
private final TypeOfContact type;
private String number;
info(TypeOfContact type, String number) {
this.type = type;
if ((type == TypeOfContact.TG_ALIAS || type == TypeOfContact.VK_ALIAS) && number.charAt(0) != '@')
throw new IllegalArgumentException("An undeclared contact type was entered");
if (type == TypeOfContact.EMAIL && !number.contains("@"))
throw new IllegalArgumentException("An undeclared contact type was entered");
this.number = number;
}
public String getNumber() {
return number;
}
public void setNumber(String newNumber){
this.number = newNumber;
}
@Override
public String toString() {
return ("Info: " + number + " Type: " + type);
}
}
enum TypeOfContact{
HOME_PHONE,
MOBILE_PHONE,
WORK,
EMAIL,
TG_ALIAS,
VK_ALIAS
}<file_sep>/6th_lab/src/main/java/ShapeMenu.java
import shapesPackage.shapeConverter;
import shapesPackage.shapeSerializer;
import shapesPackage.Shape;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListDataEvent;
import static java.lang.System.out;
public class ShapeMenu extends JDialog {
private JPanel contentPane;
private JList shapeList;
private JButton buttonOK;
private JButton buttonCancel;
private JButton addCircleButton;
private JButton removeFigureButton;
private JButton addSquareButton;
private JButton addRectangleButton;
private JButton addTriangleButton;
private JButton moveDownButton;
private JButton moveUpButton;
private JLabel pleaseSelectItemFirstLabel;
public ShapeMenu() {
setTitle("Menu of Shapes");
setContentPane(contentPane);
setModal(true);
setSize(700, 300);
removeFigureButton.setBackground(Color.pink);
pleaseSelectItemFirstLabel.setForeground(Color.RED);
pleaseSelectItemFirstLabel.setVisible(false);
getRootPane().setDefaultButton(buttonOK);
shapeConverter converter = new shapeConverter("shapeList.json");
DefaultListModel<Shape> listModel = new DefaultListModel<>();
try {
listModel.addAll(converter.convertFromJson());
} catch (IOException e) {
JOptionPane.showMessageDialog(ShapeMenu.this, "Error! Couldn't upload the file");
e.printStackTrace();
}
shapeList.setListData(listModel.toArray());
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
List<Shape> newShapesList = new ArrayList<>();
Arrays.stream(listModel.toArray()).forEach(element -> newShapesList.add((Shape) element));
shapeConverter newconverter = new shapeConverter("shapeList.json");
try {
newconverter.convertToJson(newShapesList);
} catch (IOException x) {
x.printStackTrace();
JOptionPane.showMessageDialog(ShapeMenu.this, "Error! Couldn't save to the file");
}
}
});
buttonCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
});
listModel.addListDataListener(new ListDataListener() {
@Override
public void intervalAdded(ListDataEvent e) {
shapeList.setListData(listModel.toArray());
}
@Override
public void intervalRemoved(ListDataEvent e) {
shapeList.setListData(listModel.toArray());
}
@Override
public void contentsChanged(ListDataEvent e) {
shapeList.setListData(listModel.toArray());
}
});
addCircleButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddCircle addCircle = new AddCircle(listModel::addElement);
addCircle.setVisible(true);
}
});
// call onCancel() when cross is clicked
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
onCancel();
}
});
// call onCancel() on ESCAPE
contentPane.registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
addSquareButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AddSquare addSquare = new AddSquare(listModel::addElement);
addSquare.setVisible(true);
}
});
addRectangleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AddRect addRect = new AddRect(listModel::addElement);
addRect.setVisible(true);
}
});
addTriangleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AddTriangle addTriangle = new AddTriangle(listModel::addElement);
addTriangle.setVisible(true);
}
});
removeFigureButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (shapeList.isSelectionEmpty())
pleaseSelectItemFirstLabel.setVisible(true);
else {
listModel.remove(shapeList.getSelectedIndex());
pleaseSelectItemFirstLabel.setVisible(false);
}
}
});
moveDownButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (shapeList.isSelectionEmpty())
pleaseSelectItemFirstLabel.setVisible(true);
else {
int selectedIndex = shapeList.getSelectedIndex();
if (selectedIndex == listModel.getSize() - 1)
throw new IllegalArgumentException();
Shape changethis = listModel.set(selectedIndex + 1, listModel.get(selectedIndex));
listModel.set(selectedIndex, changethis);
pleaseSelectItemFirstLabel.setVisible(false);
}
}
});
moveUpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (shapeList.isSelectionEmpty())
pleaseSelectItemFirstLabel.setVisible(true);
else {
int selectedIndex = shapeList.getSelectedIndex();
if (selectedIndex < 1)
throw new IllegalArgumentException();
Shape changethis = listModel.set(selectedIndex - 1, listModel.get(selectedIndex));
listModel.set(selectedIndex, changethis);
pleaseSelectItemFirstLabel.setVisible(false);
}
}
});
}
private void onCancel() {
// add your code here if necessary
dispose();
}
public static void main(String[] args) {
ShapeMenu dialog = new ShapeMenu();
dialog.pack();
dialog.setVisible(true);
System.exit(0);
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPane = new JPanel();
contentPane.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(4, 2, new Insets(10, 10, 10, 10), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel1, new com.intellij.uiDesigner.core.GridConstraints(2, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
final com.intellij.uiDesigner.core.Spacer spacer1 = new com.intellij.uiDesigner.core.Spacer();
panel1.add(spacer1, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false));
panel1.add(panel2, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
buttonOK = new JButton();
buttonOK.setText("Save changes");
panel2.add(buttonOK, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
buttonCancel = new JButton();
buttonCancel.setText("Exit");
panel2.add(buttonCancel, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(8, 3, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel3, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final com.intellij.uiDesigner.core.Spacer spacer2 = new com.intellij.uiDesigner.core.Spacer();
panel3.add(spacer2, new com.intellij.uiDesigner.core.GridConstraints(1, 1, 5, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_VERTICAL, 1, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
removeFigureButton = new JButton();
removeFigureButton.setText("Remove Figure");
panel3.add(removeFigureButton, new com.intellij.uiDesigner.core.GridConstraints(5, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
shapeList = new JList();
final DefaultListModel defaultListModel1 = new DefaultListModel();
shapeList.setModel(defaultListModel1);
panel3.add(shapeList, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 5, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, null, new Dimension(150, 50), null, 0, false));
addSquareButton = new JButton();
addSquareButton.setText("Add Square");
panel3.add(addSquareButton, new com.intellij.uiDesigner.core.GridConstraints(2, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
addRectangleButton = new JButton();
addRectangleButton.setText("Add Rectangle");
panel3.add(addRectangleButton, new com.intellij.uiDesigner.core.GridConstraints(3, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
addCircleButton = new JButton();
addCircleButton.setText("Add Circle");
panel3.add(addCircleButton, new com.intellij.uiDesigner.core.GridConstraints(1, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
addTriangleButton = new JButton();
addTriangleButton.setText("Add Triangle");
panel3.add(addTriangleButton, new com.intellij.uiDesigner.core.GridConstraints(4, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel4 = new JPanel();
panel4.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(panel4, new com.intellij.uiDesigner.core.GridConstraints(7, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
moveDownButton = new JButton();
moveDownButton.setText("Move Down");
panel4.add(moveDownButton, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
moveUpButton = new JButton();
moveUpButton.setText("Move Up");
panel4.add(moveUpButton, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
pleaseSelectItemFirstLabel = new JLabel();
pleaseSelectItemFirstLabel.setText("Please select item first");
panel3.add(pleaseSelectItemFirstLabel, new com.intellij.uiDesigner.core.GridConstraints(6, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_WEST, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final com.intellij.uiDesigner.core.Spacer spacer3 = new com.intellij.uiDesigner.core.Spacer();
contentPane.add(spacer3, new com.intellij.uiDesigner.core.GridConstraints(1, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_VERTICAL, 1, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
final com.intellij.uiDesigner.core.Spacer spacer4 = new com.intellij.uiDesigner.core.Spacer();
contentPane.add(spacer4, new com.intellij.uiDesigner.core.GridConstraints(3, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final com.intellij.uiDesigner.core.Spacer spacer5 = new com.intellij.uiDesigner.core.Spacer();
contentPane.add(spacer5, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 2, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPane;
}
}
<file_sep>/5th_labb/src/main/java/Main.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static java.lang.System.out;
public class Main {
public static void main(String[] args) {
List<Shape> listOfShapes = new ArrayList<>();
listOfShapes.add(new Circles(5));
listOfShapes.add(new Triangle(3, 4, 5 ));
listOfShapes.add(new Square(6));
listOfShapes.add(new Square (4));
listOfShapes.add(new Rect (4, 8));
shapeConverter converter = new shapeConverter("shapeList.json");
try {converter.convertToJson(listOfShapes);}
catch (IOException e) {e.printStackTrace();}
try {
List<Shape> readShapes = converter.convertFromJson();
readShapes.forEach(shape -> out.println(shape.toString()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>/4th_lab/src/com/company/Triangle.java
package com.company;
public class Triangle implements Shape {
public final double side_one;
public final double side_two;
public final double side_three;
public Triangle(double side_one, double side_two, double side_three) {
if (side_one <= 0 || side_two <= 0 || side_three <= 0)
throw new IllegalArgumentException("Sides of a triangle cannot be less or equal to zero");
if (side_one + side_two <= side_three || side_one + side_three <= side_two || side_two + side_three <= side_one)
throw new IllegalArgumentException("Triangles with these sides cannot exist");
this.side_one = side_one;
this.side_two = side_two;
this.side_three = side_three;
}
@Override
public double calcArea() {
//p is semiperimeter
double p = (side_one + side_two + side_three) / 2;
return Math.sqrt(p * (p - side_one) * (p - side_two) * (p - side_three));
}
@Override
public double calcPerimeter() {
return side_one + side_two + side_three;
}
public double getSide_one() {
return side_one;
}
public double getSide_two() {
return side_two;
}
public double getSide_three() {
return side_three;
}
@Override
public String toString() {
return "Triangle (a = " + side_one + ", b = " + side_two + ", c = " + side_three + "):" +
"\n area = " + calcArea() +
"\n perimeter = " + calcPerimeter() + "\n";
}
}
<file_sep>/Course project/src/main/java/addedListener.java
public interface addedListener {
void onAdded(Student student);
}
|
beffe4190169df5fc5a462756c76650619e402b7
|
[
"Java"
] | 16
|
Java
|
Adeliyaaa/oop_5th_sem
|
ddecf45cd2645502d0e3d2de9a17677ee117476a
|
3039589315fb219652af6ec8a569fb98fb2e5a38
|
refs/heads/master
|
<file_sep>export {nameCheck} from './validator'
<file_sep>const axios = require ('axios');
const cheerio = require('cheerio');
var bodyParser = require('body-parser');
const path = require('path')
var express = require('express');
var app = express();
app.use(bodyParser.json());
app.use((req, res, next)=>{
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type')
res.setHeader('Access-Control-Allow-Credentials', true)
next()
})
app.use(express.static(path.resolve(__dirname + '/front/build')));
app.listen(process.env.PORT || 3000, function() {
console.log(`Server is running on ${process.env.PORT || 3000}`);
});
app.get('/bandcamp/name/:nameID', (req, res) => {
let name = req.params.nameID;
bandcamp(name, res);
});
app.get('/facebook/name/:nameID', (req, res) => {
let name = req.params.nameID;
facebook(name, res);
});
app.get('/soundcloud/name/:nameID', (req, res) => {
let name = req.params.nameID;
soundcloud(name, res);
});
app.get('/youtube/name/:nameID', (req, res) => {
let name = req.params.nameID;
youtube(name, res);
});
app.get('/home', (req, res) => {
res.sendFile(path.resolve(__dirname + '/front/build/index.html'));
});
// Band camp
function bandcamp (name, res) {
let scrapeURL = 'https://' + name + '.bandcamp.com';
axios.get(scrapeURL)
.then(result => {
let $ = cheerio.load(result.data);
let b = $('#signupform h3');
let btext = b.text();
let btest = btext.includes('sign up');
let results = {};
if (btest) {
// If the B test includes sign up, return false. It's not available.
console.log('bandCamp: false');
results = false;
res.send(results)
}
else {
// If the B test does NOT include.
console.log('bandCamp: true');
results = true;
res.send(results)
}
}).catch(error => {
console.log('An error has occured in bandcamp');
});
}
//soundcloud
function soundcloud(name, res, results) {
let scrapeURL= 'https://soundcloud.com/' + name;
axios.get(scrapeURL)
.then(result => {
console.log('soundcloud: true');
results = true;
res.send(results);
})
.catch(error => {
if (error.request.res.statusCode) {
console.log('soundcloud: false');
results = false;
res.send(results);
}
else {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
});
}
//youtube
function youtube (name, res, results){
let scrapeURL= 'https://www.youtube.com/user/' + name;
axios.get(scrapeURL).then(result => {
console.log('youtube: true')
result = true;
res.send(result);
})
.catch(error => {
if (error.request.res.statusCode){
console.log('youtube: false');
result = false;
res.send(result)
} else {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
});
}
//facebook
function facebook (name, res, results){
let facebookNameUrl = 'http://graph.facebook.com/' + name;
axios.get(facebookNameUrl)
.then(result => {
}).catch ((error) =>{
let response = error.response.data.error.message;
let responseResult = response.includes('exist');
if (responseResult) {
console.log('facebok: ' + false);
result = false;
res.send(result)
}
else {
console.log('facebook: ' + true);
result = true;
res.send(result);
}
});
}
<file_sep>export {BigInput} from './BigInput'
<file_sep>export const nameCheck = (name) => {
let nameArr = name.toLowerCase().split('');
for (let i = 0; i < nameArr.length; i++) {
if (nameArr[i] === '&') {
nameArr.splice(i, 1, 'a', 'n', 'd')
}
if(nameArr[i] === ' ') {
nameArr.splice(i, 1)
}
}
let result = nameArr.join('');
if (result.length < 5) {
return false
}
return result;
}
<file_sep>import request from 'axios';
export const youtubeHelper = async (bandname, responseHandler) => {
let response = await request.get(`/youtube/name/${bandname}`)
let responseObject = {youtube: response.data};
return responseObject;
}
export const facebookHelper = async (bandname, responseHandler) => {
let response = await request.get(`/facebook/name/${bandname}`)
let responseObject = {facebook: response.data};
return responseObject;
}
export const soundcloudHelper = async (bandname, responseHandler) => {
let response = await request.get(`/soundcloud/name/${bandname}`)
let responseObject = {soundcloud: response.data};
return responseObject;
}
export const bandcampHelper = async (bandname, responseHandler) => {
let response = await request.get(`/bandcamp/name/${bandname}`)
let responseObject = {bandcamp: response.data};
return responseObject;
}
<file_sep>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import {BigInput} from './components';
import {Sign, TrafficLight} from './svg';
import {nameCheck} from './lib';
import {youtubeHelper, facebookHelper, bandcampHelper, soundcloudHelper} from './lib/searchHelper';
class App extends Component {
state = {
currentText: '',
bands: {
youtube: 'unknown',
bandcamp: 'unknown',
facebook: 'unknown',
soundcloud: 'unknown'
},
finalBand: undefined,
};
handleInputChange = (evt) => {
this.setState({
currentText: evt.target.value,
errorMessage: '',
bands: {
youtube: 'unknown',
bandcamp: 'unknown',
facebook: 'unknown',
soundcloud: 'unknown'
}
})
}
handleSubmit = async (evt) => {
evt.preventDefault();
let result = nameCheck(this.state.currentText);
if (!result) {
this.setState({
errorMessage: "Make sure your submission has at least 5 letters!"
})
}
else {
this.setState({
finalBand: result
})
this.handleResponse(await facebookHelper(result));
this.handleResponse(await soundcloudHelper(result))
this.handleResponse(await bandcampHelper(result))
this.handleResponse(await youtubeHelper(result))
}
}
handleEmptySubmit = (evt) => {
evt.preventDefault();
if (this.state.finalBand) {
this.setState({
finalBand: ''
})
}
else {
this.setState({
errorMessage: 'Please supply a band name',
});
}
}
handleResponse = (responseObject) => {
let bands = {...this.state.bands, ...responseObject}
this.setState({
bands: bands
})
}
render() {
const submitHandler = this.state.currentText ? this.handleSubmit : this.handleEmptySubmit;
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">What's in a name?</h1>
<h3>Search to see if your band's name username's available on four major music sites.</h3>
</header>
<div className="App">
<BigInput handleSubmit={submitHandler} handleInputChange={this.handleInputChange} currentText={this.state.currentText} errorMessage={this.state.errorMessage} placeHolder='Type Band Name Here' />
<Sign className="sign" finalBand={this.state.finalBand}/>
<TrafficLight className='light' bands={this.state.bands}/>
</div>
</div>
);
}
}
export default App;
|
2800207f7337e03931e26ba36d681efcdfb193b8
|
[
"JavaScript"
] | 6
|
JavaScript
|
IAmNatch/What-s-in-a-Name-V2
|
59c4ebbf4ce1a609ec18a6b636f71c7f3c1a950a
|
b3d675fc1a9eb955caac352bec148dafc118ad31
|
refs/heads/master
|
<repo_name>ahmedkawsar21/MobileAutomationPractice<file_sep>/EspnCricinfo/src/test/java/testCases/TestAccountPage.java
package testCases;
import base.MobileAPI2;
public class TestAccountPage extends MobileAPI2 {
}
|
0b191ca7b8076251ee455b713ebcebad0f0416a8
|
[
"Java"
] | 1
|
Java
|
ahmedkawsar21/MobileAutomationPractice
|
bd6f82294c9b47f5d61944cdf90dc092225132ea
|
1a4407e8d423a0e5adaef2de3a6b37151301c514
|
refs/heads/master
|
<repo_name>GreenFaith/v2ex_scrapy<file_sep>/v2ex_scrapy/spiders/topic.py
import scrapy
import json
from v2ex_scrapy.items import TopicItem
from v2ex_scrapy.utils import topic_max, maxid_local
from scrapy import log
class topicSpider(scrapy.Spider):
name = "topic"
_url = 'http://www.v2ex.com/api/topics/show.json?id=%d'
MAX = topic_max()
RANGE = range(MAX-200, MAX)
#: the latest 200 topics
start_urls = [ _url%i for i in RANGE ]
def parse(self, response):
res = json.loads(response.body)
if not res or not isinstance(res, list):
return
try:
res = res[0]
res['_id'] = res['id']
del res['id']
item = TopicItem(res)
except Exception, e:
self.log(str(e), level=log.ERROR)
return
yield item
<file_sep>/v2ex_scrapy/spiders/reply.py
import scrapy
import json
import re
from v2ex_scrapy.items import ReplyItem
from v2ex_scrapy.utils import topic_max, maxid_local
from scrapy import log
class replySpider(scrapy.Spider):
name = 'reply'
_url = 'http://www.v2ex.com/api/replies/show.json?topic_id=%d'
MAX = topic_max()
RANGE = range(MAX-200, MAX)
start_urls = [ _url%i for i in RANGE]
def parse(self, response):
res = json.loads(response.body)
if not res or not isinstance(res, list):
return
for r in res:
try:
r['_id'] = r['id']
del r['id']
r['topic_id'] = int(re.search('\=(\d+)', response.url).group(1))
item = ReplyItem(r)
except Exception, e:
self.log("%s"% response.url, level=log.ERROR)
self.log(str(e), level=log.DEBUG)
return
yield item
<file_sep>/README.md
V2EX_Scrapy
===========
`V2EX_Scrapy` 是一只基于 V2EX API 的异步 IO 爬虫
</br>
</br>
正努力地为 [V2EX 第三方社区搜索](http://shixiz.com) 抓取索引数据
开始使用前,请确保了解:
[V2EX 关于 API 公平使用方面的规则](https://www.v2ex.com/p/7v9TEc53)
环境准备
--------
* [Scrapy] (http://scrapy.org/)
* [Mongodb] (http://www.mongodb.org/)
快速开始
--------
#: 安装必要 python 库
sudo pip install scrapy
sudo pip install pymongo
#: 抓取社区最新数据
scrapy crawl topic
scrapy crawl reply
定时运行
--------
参见 run.sh 中的 `cron` 注释
更多
-----
* [scrapy 文档] (http://doc.scrapy.org/en/latest/)
* [V友整理的 V2EX API] (https://gist.github.com/dbbbit/16a8fdbb73e627e00864)
欢迎提交 Pull Request 来改进爬虫
--------------------------------
* [提交建议,需求,Bug报告](https://github.com/dbbbit/v2ex_scrapy/issues/new)
* [Fork Me](https://github.com/dbbbit/v2ex_scrapy/fork)
|
6ca6459e5f4d44a5b4ab8cc49f50148b7c07c9aa
|
[
"Markdown",
"Python"
] | 3
|
Python
|
GreenFaith/v2ex_scrapy
|
0e8d6e3b1dce8d4c80ea9abfc13aa6bb2041ebac
|
8593eaa4cbf0c3e1df5bd79ef45853bee3497da4
|
refs/heads/master
|
<repo_name>Josizzle/API-Calls<file_sep>/README.md
# API-Calls
How to make restful API calls
<file_sep>/js/main.js
// Web Storage API session storage
if (window.sessionstorage) {
var txtUsername = document.getElementById('InputEmail1');
var txtAnswer = document.getElementById('InputPassword1');
txtUsername.value = sessionStorage.getItem('InputEmail1');
txtAnswer.value = sessionStorage.getItem('InputPassword1');
txtUsername.addEventListener('input', function() {
sessionStorage.setItem('InputEmail1', txtUsername.value);
}, false);
console.log('Email')
txtAnswer.addEventListener('input', function() {
sessionStorage.setItem('InputPassword1', txtAnswer.value);
}, false);
console.log('Password')
}
|
1fedaa98f8746e6fe32e03119217c74c15d26cfc
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Josizzle/API-Calls
|
4bfeed5f1a971b510285eb0776f5c9dd3ee128a9
|
b340352387a36486ac76daa5b9da7b8de7861a6a
|
refs/heads/master
|
<repo_name>bvasko/React-Require-Backbone<file_sep>/README.md
Todo MVC with Backbone / React / Require
=========================================
[Todo MVC](https://github.com/tastejs/todomvc?source=cc) updated for require / react / backbone to serve pre-compiled jsx templates
Based on:
[github.com/seiffert](https://github.com/seiffert/blog-articles/tree/master/pimp-my-backbone.view/examples/todolist-reactive-backbone)
and:
[github.com/Havelaer/](https://github.com/philix/jsx-requirejs-plugin)
Optimizer
--------------
Added app.build.js for r.js optimizer
```
r.js -o build/app.build.js
```
Dependencies
----------------
Pre-compile templates
```
npm install jsx
```
Run Require optimizer
```
npm install requirejs
```
Getting Started
----------------
Run to watch and compile jsx files
```
jsx --watch app/jsx/ app/views/ -x js
```
TODO
--------------
Move JSX watch to gruntfile
#### Update:
Removed --no-cache-dir directive, jsx compiler not updating modules with it in<file_sep>/build/app.build.js
({
appDir: '../app',
baseUrl: './',
dir: '../dist',
optimize: 'uglify',
paths: {
'main': 'main',
'text':'vendor/js/text',
'views': 'jsx',
'jsx':'vendor/js/jsx',
'JSXTransformer': 'vendor/js/JSXTransformer-0.8.0'
},
mainConfigFile: '../app/main.js',
modules: [
{
name: 'main',
exclude: ['react','jsx']
}
]
})<file_sep>/app/main.js
require.config({
'baseUrl': '/app',
paths: {
'jquery': 'vendor/js/jquery.min',
'lodash': 'vendor/js/lodash.min',
'backbone': 'vendor/js/backbone-min',
'react': 'vendor/js/react-with-addons.min',
'localStore': 'vendor/js/backbone.localStorage-min',
'JSXTransformer': 'vendor/js/JSXTransformer-0.8.0',
'jsx': 'vendor/js/jsx',
'text':'vendor/js/text'
}
});
require(['backbone',
'react',
'collections/TodoList',
'jsx!views/TodoApp'],
function(Backbone, React, TodoList, TodoApp){
var list = new TodoList();
React.renderComponent(
TodoApp( {todos: list} ),
document.getElementById('container'));
});<file_sep>/app/views/TodoItem.js
/** @jsx React.DOM */
define(['jquery',
'lodash',
'backbone',
'localStore',
'react',
'utils/utils'],
function ($,_,Backbone,localStore,React,Utils) {
// Begin React stuff
var TodoItem = React.createClass({displayName: 'TodoItem',
handleSubmit: function(event) {
var val = this.refs.editField.getDOMNode().value.trim();
if (val) {
this.props.onSave(val);
} else {
this.props.onDestroy();
}
return false;
},
onEdit: function() {
this.props.onEdit();
this.refs.editField.getDOMNode().focus();
},
render: function() {
var classes = Utils.stringifyObjKeys({
completed: this.props.todo.get('completed'), editing: this.props.editing
});
return (
React.DOM.li( {className:classes},
React.DOM.div( {className:"view"},
React.DOM.input(
{className:"toggle",
type:"checkbox",
checked:this.props.todo.get('completed'),
onChange:this.props.onToggle,
key:this.props.key}
),
React.DOM.label( {onDoubleClick:this.onEdit},
this.props.todo.get('title')
),
React.DOM.button( {className:"destroy", onClick:this.props.onDestroy} )
),
React.DOM.form( {onSubmit:this.handleSubmit},
React.DOM.input(
{ref:"editField",
className:"edit",
defaultValue:this.props.todo.get('title'),
onBlur:this.handleSubmit,
autoFocus:"autofocus"}
)
)
)
);
}
});
return TodoItem;
});<file_sep>/app/jsx/TodoApp.js
/** @jsx React.DOM */
define(['jquery',
'lodash',
'backbone',
'react',
'utils/mixin',
'jsx!views/TodoItem',
'jsx!views/TodoFooter'],
function ($,_,Backbone,React,BackboneMixin,TodoItem,TodoFooter) {
// Begin React stuff
var TodoApp = React.createClass({
mixins: [BackboneMixin],
getInitialState: function() {
return {editing: null};
},
componentDidMount: function() {
// Additional functionality for todomvc: fetch() the collection on init
this.props.todos.fetch();
this.refs.newField.getDOMNode().focus();
},
componentDidUpdate: function() {
// If saving were expensive we'd listen for mutation events on Backbone and
// do this manually. however, since saving isn't expensive this is an
// elegant way to keep it reactively up-to-date.
this.props.todos.forEach(function(todo) {
todo.save();
});
},
getBackboneModels: function() {
return [this.props.todos];
},
handleSubmit: function(event) {
event.preventDefault();
var val = this.refs.newField.getDOMNode().value.trim();
if (val) {
this.props.todos.create({
title: val,
completed: false,
order: this.props.todos.nextOrder()
});
this.refs.newField.getDOMNode().value = '';
}
},
toggleAll: function(event) {
var checked = event.nativeEvent.target.checked;
this.props.todos.forEach(function(todo) {
todo.set('completed', checked);
});
},
edit: function(todo) {
this.setState({editing: todo.get('id')});
},
save: function(todo, text) {
todo.set('title', text);
this.setState({editing: null});
},
clearCompleted: function() {
this.props.todos.completed().forEach(function(todo) {
todo.destroy();
});
},
render: function() {
var footer = null;
var main = null;
var todoItems = this.props.todos.map(function(todo) {
return (
<TodoItem
key={todo.cid}
todo={todo}
onToggle={todo.toggle.bind(todo)}
onDestroy={todo.destroy.bind(todo)}
onEdit={this.edit.bind(this, todo)}
editing={this.state.editing === todo.get('id')}
onSave={this.save.bind(this, todo)}
/>
);
}, this);
var activeTodoCount = this.props.todos.remaining().length;
var completedCount = todoItems.length - activeTodoCount;
if (activeTodoCount || completedCount) {
footer = <TodoFooter
count={activeTodoCount}
completedCount={completedCount}
onClearCompleted={this.clearCompleted} />;
}
if (todoItems.length) {
main = ( <section id="main">
<input id="toggle-all" type="checkbox" onChange={this.toggleAll} />
<ul id="todo-list">
{todoItems}
</ul>
</section> );
}
return (
<div>
<section id="todoapp">
<header id="header">
<h1>todos</h1>
<form onSubmit={this.handleSubmit}>
<input ref="newField" id="new-todo" placeholder="What needs to be done?" />
</form>
</header>
{main}
{footer}
</section>
<footer id="info">
<p>Double-click to edit a todo</p>
<p>
Created by{' '}
<a href="http://github.com/petehunt/">petehunt;</a>
</p>
<p>Forked from {' '}<a href="http://todomvc.com">TodoMVC</a></p>
</footer>
</div>
);
}
});
return TodoApp;
}
);<file_sep>/app/views/TodoFooter.js
/** @jsx React.DOM */
define(['jquery',
'lodash',
'backbone',
'react',
'utils/utils'],
function ($,_,Backbone,React,Utils) {
var TodoFooter = React.createClass({displayName: 'TodoFooter',
render: function() {
var activeTodoWord = Utils.pluralize(this.props.count, 'todo');
var clearButton = null;
if (this.props.completedCount > 0) {
clearButton = (
React.DOM.button( {id:"clear-completed", onClick:this.props.onClearCompleted},
" Clear completed (",this.props.completedCount,") "
)
);
}
return (
React.DOM.footer( {id:"footer"},
React.DOM.span( {id:"todo-count"},
React.DOM.strong(null, this.props.count),' ',
activeTodoWord,' ',"left "
),
clearButton
)
);
}
});
return TodoFooter;
});
|
3c559fea0d088928e3f7deaf9643f121ef04fc04
|
[
"Markdown",
"JavaScript"
] | 6
|
Markdown
|
bvasko/React-Require-Backbone
|
fc029c8616cc3c896e82bb61fc28654a8a09dbd4
|
1ba81b143125cd0f77c05818cd11c47d0aa04981
|
refs/heads/master
|
<file_sep>rootProject.name='Image Loading'
include ':app'
<file_sep>package br.com.gabriel.imageloading
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private val SELECT_PICTURE = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btLoadImage.setOnClickListener { pickImage() }
}
/**
* Acionar o carregamento de imagem utilizando a técnica que desejamos testar (i.e. Glide ou Picasso).
* */
private fun loadImage() {
// Image Loading content here ...
val url = "https://media1.giphy.com/media/zGnnFpOB1OjMQ/giphy.gif"// LOTR Gif
// Glide: recomendada pelo Google na própria documentação do Android.
Glide.with(this)// inicializa a biblioteca e informa o contexto da aplicação
.load(url)// URL da imagem
.into(ivMain)// referência do ImageView
/*A declaração é semelhante à do Glide, a única diferença é que não precisamos mais
referenciar o contexto da aplicação, pois isso será obtido a partir do imageView que foi
declarado.*/
/*
Picasso.get()// inicialização da biblioteca e obtemos sua instância
.load(url)// carregamos a URL de uma imagem
.into(ivMain)// inserimos a imagem carregada em um imageView
*/
}
/**
* CARREGA IMAGEM DA GALERIA OU TIRANDO UMA NOVA.
* */
fun pickImage() {
// Pick Intent
val pickIntent = Intent(Intent.ACTION_GET_CONTENT)// Acessar conteúdo nos documentos.
/*Para que o Android entenda que essa ação estará relacionada apenas com imagens*/
pickIntent.type = "image/*"
// Take Picture Intent
// Intenção que permite o usuário tirar uma foto nova
// NOTE: Precisamos declarar o uso desse hardware no AndroidManifest.
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
// Pick Gallery Image
/*Intenção de acessar conteúdos direto na galeria. Passando também a URI correspondente à
galeria, disponibilizada através da declaração MediaStore.Images.Media.EXTERNAL_CONTENT_URI.*/
val pickGalleryImageIntent =
Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
// Choose Intent
// Para exibir o menu de opções de Intents
val pickTitle = "Select or take a new Picture"
val chooserIntent = Intent.createChooser(pickIntent, pickTitle)
chooserIntent.putExtra(
Intent.EXTRA_INITIAL_INTENTS, arrayOf(
takePictureIntent, pickGalleryImageIntent
)// Unindo todas as declarações anteriores
)
// Send Intent
// checamos se o dispositivo possui aplicativos capazes de executar as ações desejadas,
if (chooserIntent.resolveActivity(packageManager) != null) {
startActivityForResult(chooserIntent, SELECT_PICTURE)
}
}
/**
* Dispatch incoming result to the correct fragment.
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// validamos o requestCode e o resultCode
if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK)
if (data?.extras != null)
/*o bitmap inteiro da imagem está dentro de uma propriedade chamada data dentro do
objeto extras .*/ ivMain.setImageBitmap(data.extras.get("data") as Bitmap)
else if (data?.data != null) Picasso.get().load(data.data).into(ivMain)
}
}
|
198c8104ad431572ec60e69a26561b4c52db0869
|
[
"Kotlin",
"Gradle"
] | 2
|
Gradle
|
Gabriel-D-S-Magalhaes/Image_Loading
|
c5d675c198b6675c68a41e47d02134d4c01f9339
|
157eb67763114f85b97adb7cb15d363c8ec4538e
|
refs/heads/main
|
<repo_name>fatmaoz/ticketing-project-security<file_sep>/src/main/java/com/cydeo/controller/ProjectController.java
package com.cydeo.controller;
import com.cydeo.dto.ProjectDTO;
import com.cydeo.dto.UserDTO;
import com.cydeo.service.ProjectService;
import com.cydeo.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@Controller
@RequestMapping("/project")
public class ProjectController {
private final ProjectService projectService;
private final UserService userService;
public ProjectController(ProjectService projectService, UserService userService) {
this.projectService = projectService;
this.userService = userService;
}
@GetMapping("/create")
public String createProject(Model model) {
model.addAttribute("project", new ProjectDTO());
model.addAttribute("projects", projectService.listAllProjectDetails());
model.addAttribute("managers", userService.listAllByRole("manager"));
return "project/create";
}
@PostMapping("/create")
public String insertProject(@ModelAttribute("project") ProjectDTO project, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("projects", projectService.listAllProjectDetails());
model.addAttribute("managers", userService.listAllByRole("manager"));
return "project/create";
}
projectService.save(project);
return "redirect:/project/create";
}
@GetMapping("/delete/{projectcode}")
public String deleteProject(@PathVariable("projectcode") String projectcode) {
projectService.delete(projectcode);
return "redirect:/project/create";
}
@GetMapping("/complete/{projectcode}")
public String completeProject(@PathVariable("projectcode") String projectcode) {
projectService.complete(projectcode);
return "redirect:/project/create";
}
@GetMapping("/update/{projectcode}")
public String editProject(@PathVariable("projectcode") String projectcode, Model model) {
model.addAttribute("project", projectService.getByProjectCode(projectcode));
model.addAttribute("projects", projectService.listAllProjectDetails());
model.addAttribute("managers", userService.listAllByRole("manager"));
return "/project/update";
}
@PostMapping("/update")
public String updateProject(@ModelAttribute("project") ProjectDTO project, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("projects", projectService.listAllProjectDetails());
model.addAttribute("managers", userService.listAllByRole("manager"));
return "/project/update";
}
projectService.update(project);
return "redirect:/project/create";
}
@GetMapping("/manager/project-status")
public String getProjectByManager(Model model) {
List<ProjectDTO> projects = projectService.listAllProjectDetails();
model.addAttribute("projects", projects);
return "/manager/project-status";
}
@GetMapping("/manager/complete/{projectCode}")
public String managerCompleteProject(@PathVariable("projectCode") String projectCode) {
projectService.complete(projectCode);
return "redirect:/project/manager/project-status";
}
}
<file_sep>/src/main/java/com/cydeo/entity/User.java
package com.cydeo.entity;
import com.cydeo.enums.Gender;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Where;
import javax.persistence.*;
import java.time.LocalDateTime;
@NoArgsConstructor
@Data
@Entity
@Table(name = "users")
@Where(clause = "is_deleted=false")
public class User extends BaseEntity {
private String firstName;
private String lastName;
@Column(unique = true, nullable = false)
private String userName;
private String passWord;
private boolean enabled;
private String phone;
@ManyToOne
@JoinColumn(name = "role_id")
private Role role;
@Enumerated(EnumType.STRING)
private Gender gender;
}
<file_sep>/src/main/java/com/cydeo/repository/ProjectRepository.java
package com.cydeo.repository;
import com.cydeo.entity.Project;
import com.cydeo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ProjectRepository extends JpaRepository<Project,Long> {
Project findByProjectCode(String code);
List<Project> findAllByAssignedManager(User manager);
}
<file_sep>/target/classes/application.properties
spring.datasource.url=jdbc:postgresql://ticketingdb.cuv7phep6qnd.eu-west-2.rds.amazonaws.com:5432/ticketingdb
spring.datasource.username=postgres
spring.datasource.password=<PASSWORD>
spring.jpa.show-sql=false
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=create
spring.sql.init.mode=always
spring.jpa.defer-datasource-initialization=true
<file_sep>/Dockerfile
FROM amd64/maven:3.8.6-openjdk-11
WORKDIR usr/app
COPY . .
ENTRYPOINT ["mvn","spring-boot:run"]<file_sep>/src/main/java/com/cydeo/service/impl/UserServiceImpl.java
package com.cydeo.service.impl;
import com.cydeo.dto.ProjectDTO;
import com.cydeo.dto.TaskDTO;
import com.cydeo.dto.UserDTO;
import com.cydeo.entity.Project;
import com.cydeo.entity.Task;
import com.cydeo.entity.User;
import com.cydeo.mapper.UserMapper;
import com.cydeo.repository.UserRepository;
import com.cydeo.service.ProjectService;
import com.cydeo.service.TaskService;
import com.cydeo.service.UserService;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Sort;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final UserMapper userMapper;
private final ProjectService projectService;
private final TaskService taskService;
private final PasswordEncoder passwordEncoder;
public UserServiceImpl(UserRepository userRepository, UserMapper userMapper, ProjectService projectService, TaskService taskService, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.userMapper = userMapper;
this.projectService = projectService;
this.taskService = taskService;
this.passwordEncoder = passwordEncoder;
}
@Override
public List<UserDTO> listAllUsers() {
List<User> userList = userRepository.findAll(Sort.by("firstName"));
return userList.stream().map(userMapper::convertToDTO).collect(Collectors.toList());
}
@Override
public UserDTO findByUserName(String username) {
User user = userRepository.findByUserName(username);
return userMapper.convertToDTO(user);
}
@Override
public void save(UserDTO dto) {
dto.setEnabled(true);
User obj = userMapper.convertToEntity(dto);
obj.setPassWord(passwordEncoder.encode(obj.getPassWord()));
userRepository.save(obj);
}
@Override
public UserDTO update(UserDTO dto) {
//Find current user
User user = userRepository.findByUserName(dto.getUserName());
//Map updated user dto to entity object
User convertedUser = userMapper.convertToEntity(dto);
//set id to converted object
convertedUser.setId(user.getId());
//save updated user
userRepository.save(convertedUser);
return findByUserName(dto.getUserName());
}
@Override
public void deleteByUserName(String username) {
userRepository.deleteByUserName(username);
}
@Override
public void delete(String username) {
User user = userRepository.findByUserName(username);
if (checkIfUserCanBeDeleted(user)) {
user.setIsDeleted(true);
user.setUserName(user.getUserName() + "-" + user.getId());
userRepository.save(user);
}
}
private boolean checkIfUserCanBeDeleted(User user) {
switch (user.getRole().getDescription()) {
case "Manager":
List<ProjectDTO> projectDTOList = projectService.readAllByAssignedManager(user);
return projectDTOList.size() == 0;
case "Employee":
List<TaskDTO> taskDTOList = taskService.readAllByAssignedEmployee(user);
return taskDTOList.size() == 0;
default:
return true;
}
}
@Override
public List<UserDTO> listAllByRole(String role) {
List<User> users = userRepository.findAllByRoleDescriptionIgnoreCase(role);
return users.stream().map(userMapper::convertToDTO).collect(Collectors.toList());
}
}
<file_sep>/src/main/java/com/cydeo/service/ProjectService.java
package com.cydeo.service;
import com.cydeo.dto.ProjectDTO;
import com.cydeo.entity.User;
import java.util.List;
public interface ProjectService {
ProjectDTO getByProjectCode(String code);
List<ProjectDTO> listAllProjects();
void save(ProjectDTO dto);
void update(ProjectDTO dto);
void delete(String code);
void complete(String projectCode);
List<ProjectDTO> listAllProjectDetails();
List<ProjectDTO> readAllByAssignedManager(User assignedManager);
}
<file_sep>/docker-compose.yaml
version: "3.7"
services:
mypostgres:
image: postgres
container_name: mypostgres
ports:
- "5435:5432"
restart: always
environment:
POSTGRES_USER: "postgres"
POSTGRES_PASSWORD: "admin"
POSTGRES_DB: "ticketing-app"
networks:
- webnet
volumes:
- initdb:/var/lib/postgres/data
ticketing-app:
build: .
container_name: ticketingapp
ports:
- "8080:8080"
depends_on:
- mypostgres
networks:
- webnet
volumes:
initdb:
networks:
webnet:
driver: bridge
<file_sep>/src/main/java/com/cydeo/service/impl/ProjectServiceImpl.java
package com.cydeo.service.impl;
import com.cydeo.dto.ProjectDTO;
import com.cydeo.dto.UserDTO;
import com.cydeo.entity.Project;
import com.cydeo.entity.User;
import com.cydeo.enums.Status;
import com.cydeo.mapper.ProjectMapper;
import com.cydeo.mapper.UserMapper;
import com.cydeo.repository.ProjectRepository;
import com.cydeo.repository.TaskRepository;
import com.cydeo.service.ProjectService;
import com.cydeo.service.TaskService;
import com.cydeo.service.UserService;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class ProjectServiceImpl implements ProjectService {
private final ProjectRepository projectRepository;
private final ProjectMapper projectMapper;
private final UserService userService;
private final UserMapper userMapper;
private final TaskService taskService;
public ProjectServiceImpl(ProjectRepository projectRepository, ProjectMapper projectMapper, @Lazy UserService userService, UserMapper userMapper, TaskService taskService) {
this.projectRepository = projectRepository;
this.projectMapper = projectMapper;
this.userService = userService;
this.userMapper = userMapper;
this.taskService = taskService;
}
@Override
public ProjectDTO getByProjectCode(String code) {
Project project = projectRepository.findByProjectCode(code);
return projectMapper.convertToDto(project);
}
@Override
public List<ProjectDTO> listAllProjects() {
List<Project> list = projectRepository.findAll();
return list.stream().map(projectMapper::convertToDto).collect(Collectors.toList());
}
@Override
public void save(ProjectDTO dto) {
dto.setProjectStatus(Status.OPEN);
Project project = projectMapper.convertToEntity(dto);
projectRepository.save(project);
}
@Override
public void update(ProjectDTO dto) {
Project project = projectRepository.findByProjectCode(dto.getProjectCode());
Project convertedProject = projectMapper.convertToEntity(dto);
convertedProject.setId(project.getId());
convertedProject.setProjectStatus(project.getProjectStatus());
projectRepository.save(convertedProject);
}
@Override
public void delete(String code) {
Project project = projectRepository.findByProjectCode(code);
project.setIsDeleted(true);
project.setProjectCode(project.getProjectCode() + "-" + project.getId());
projectRepository.save(project);
taskService.deleteByProject(projectMapper.convertToDto(project));
}
@Override
public void complete(String projectCode) {
Project project = projectRepository.findByProjectCode(projectCode);
project.setProjectStatus(Status.COMPLETE);
projectRepository.save(project);
taskService.completeByProject(projectMapper.convertToDto(project));
}
@Override
public List<ProjectDTO> listAllProjectDetails() {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
UserDTO currentUserDTO = userService.findByUserName(username);
User user = userMapper.convertToEntity(currentUserDTO);
List<Project> list = projectRepository.findAllByAssignedManager(user);
return list.stream().map(project -> {
ProjectDTO obj = projectMapper.convertToDto(project);
obj.setUnfinishedTaskCounts(taskService.totalNonCompletedTask(project.getProjectCode()));
obj.setCompleteTaskCounts(taskService.totalCompletedTask(project.getProjectCode()));
return obj;
}).collect(Collectors.toList());
}
@Override
public List<ProjectDTO> readAllByAssignedManager(User assignedManager) {
List<Project> list = projectRepository.findAllByAssignedManager(assignedManager);
return list.stream().map(projectMapper::convertToDto).collect(Collectors.toList());
}
}
<file_sep>/src/main/java/com/cydeo/controller/TaskController.java
package com.cydeo.controller;
import com.cydeo.dto.TaskDTO;
import com.cydeo.enums.Status;
import com.cydeo.service.ProjectService;
import com.cydeo.service.TaskService;
import com.cydeo.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@Controller
@RequestMapping("/task")
public class TaskController {
private final TaskService taskService;
private final ProjectService projectService;
private final UserService userService;
public TaskController(TaskService taskService, ProjectService projectService, UserService userService) {
this.taskService = taskService;
this.projectService = projectService;
this.userService = userService;
}
@GetMapping("/create")
public String createTask(Model model) {
model.addAttribute("task", new TaskDTO());
model.addAttribute("projects", projectService.listAllProjects());
model.addAttribute("employees", userService.listAllByRole("employee"));
model.addAttribute("tasks", taskService.listAllTasks());
return "task/create";
}
@PostMapping("/create")
public String insertTask(@ModelAttribute("task") TaskDTO task, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("projects", projectService.listAllProjects());
model.addAttribute("employees", userService.listAllByRole("employee"));
model.addAttribute("tasks", taskService.listAllTasks());
return "task/create";
}
taskService.save(task);
return "redirect:/task/create";
}
@GetMapping("/delete/{taskId}")
public String deleteTask(@PathVariable("taskId") Long taskId) {
taskService.delete(taskId);
return "redirect:/task/create";
}
@GetMapping("/update/{taskId}")
public String editTask(@PathVariable("taskId") Long taskId, Model model) {
model.addAttribute("task", taskService.findById(taskId));
model.addAttribute("projects", projectService.listAllProjects());
model.addAttribute("employees", userService.listAllByRole("employee"));
model.addAttribute("tasks", taskService.listAllTasks());
return "task/update";
}
// @PostMapping("/update/{taskId}")
// public String updateTask(@PathVariable("taskId") Long taskId, TaskDTO task) {
// task.setId(taskId);
// taskService.update(task);
// return "redirect:/task/create";
// }
//
@PostMapping("/update/{id}")
public String updateTask(@ModelAttribute("task") TaskDTO task, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("projects", projectService.listAllProjects());
model.addAttribute("employees", userService.listAllByRole("employee"));
model.addAttribute("tasks", taskService.listAllTasks());
return "task/update";
}
taskService.update(task);
return "redirect:/task/create";
}
@GetMapping("/employee/pending-tasks")
public String employeePendingTasks(Model model) {
model.addAttribute("tasks", taskService.listAllTasksByStatusIsNot(Status.COMPLETE));
return "task/pending-tasks";
}
@GetMapping("/employee/edit/{id}")
public String employeeEditTask(@PathVariable("id") Long id, Model model) {
model.addAttribute("task", taskService.findById(id));
model.addAttribute("tasks", taskService.listAllTasksByStatusIsNot(Status.COMPLETE));
model.addAttribute("statuses", Status.values());
return "task/status-update";
}
@PostMapping("/employee/update/{id}")
public String employeeUpdateTask(@ModelAttribute("task") TaskDTO task, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("tasks", taskService.listAllTasksByStatusIsNot(Status.COMPLETE));
model.addAttribute("statuses", Status.values());
return "task/status-update";
}
taskService.updateStatus(task);
return "redirect:/task/employee/pending-tasks";
}
@GetMapping("/employee/archive")
public String employeeArchivedTasks(Model model) {
model.addAttribute("tasks", taskService.listAllTasksByStatus(Status.COMPLETE));
return "task/archive";
}
}
<file_sep>/src/main/java/com/cydeo/mapper/UserMapper.java
package com.cydeo.mapper;
import com.cydeo.dto.UserDTO;
import com.cydeo.entity.User;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Component;
@Component
public class UserMapper {
private final ModelMapper modelMapper;
public UserMapper(ModelMapper modelMapper) {
this.modelMapper = modelMapper;
}
public User convertToEntity(UserDTO dto){
return modelMapper.map(dto,User.class);
}
public UserDTO convertToDTO(User entity){
return modelMapper.map(entity,UserDTO.class);
}
}
|
f13c79e0bb361a1827731a48b5d6dc9c23bcac3b
|
[
"Java",
"Dockerfile",
"YAML",
"INI"
] | 11
|
Java
|
fatmaoz/ticketing-project-security
|
ca91448edecf2d65140faf7b92d42a64102ef0df
|
1e30aab0cbfac229f95c907ccbfe4e514a7a4d31
|
refs/heads/master
|
<repo_name>bernatangg/waplant-kotlin<file_sep>/app/src/main/java/com/bernatangg/waplant/onBoarding/OnBoardingViewPager.kt
package com.bernatangg.waplant.onBoarding
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.PagerAdapter
class OnBoardingViewPager(private val mLayoutInflater: LayoutInflater, private val mLayouts: Array<Int>) : PagerAdapter() {
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val view: View = mLayoutInflater.inflate(mLayouts[position], container, false)
container.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
super.destroyItem(container, position, `object`)
}
override fun getCount(): Int {
return mLayouts.size
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view == `object`
}
}<file_sep>/settings.gradle
rootProject.name='Waplant'
include ':app'
|
d03f24801085a980b9b9a69870b65cb26e273493
|
[
"Kotlin",
"Gradle"
] | 2
|
Kotlin
|
bernatangg/waplant-kotlin
|
88035ea65a41994a866e33db3b3c549a340433a9
|
ea529c2685c2e79b577fa4b1b11de21958285e44
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Jan 19 17:19:58 2015
@author: 3200982
"""
from soccersimulator import pyglet
from soccersimulator import Vector2D, SoccerBattle, SoccerPlayer, SoccerTeam, SoccerStrategy, SoccerAction
from soccersimulator import PygletObserver,ConsoleListener,LogListener
class RandomStrategy(SoccerStrategy):
def __init__(self):
self.name="Random"
def start_battle(self,state):
pass
def finish_battle(self,won):
pass
def compute_strategy(self,state,player,teamid):
shoot=Vector2D.create_random(-1,1)
acceleration=Vector2D.create_random(-1,1)
action = SoccerAction(acceleration,shoot)
return action
def copy(self):
return RandomStrategy()
def create_strategy(self):
return RandomStrategy()
class FonceurStrategy(SoccerStrategy):
def __init__(self):
self.name="Fonceur"
def start_battle(self,state):
pass
def finish_battle(self,won):
pass
def idteamadverse(self,teamid) :
if(teamid == 1) :
return 2
else :
return 1
def compute_strategy(self,state,player,teamid):
acceleration=state.ball.position - player.position
shoot= state.get_goal_center(self.idteamadverse(teamid)) - player.position
action = SoccerAction(acceleration,shoot)
return action
def copy(self):
return FonceurStrategy()
def create_strategy(self):
return FonceurStrategy()
<file_sep>
from monequipe import teams
name = "<NAME>"<file_sep># -*- coding: utf-8 -*-
from soccersimulator import pyglet
from soccersimulator import Vector2D, SoccerBattle, SoccerPlayer, SoccerTeam, SoccerStrategy, SoccerAction, GAME_WIDTH, GAME_HEIGHT, BALL_RADIUS, PLAYER_RADIUS
from soccersimulator import PygletObserver,ConsoleListener,LogListener
from ToolBox import *
import math
# Le joueur fonce vers un point donné
class StrategieAvecUtilitaire(SoccerStrategy) :
def compute_strategy (self, state, player, teamid) :
u = Utilitaire(state, player, teamid)
return self.compute_strategy_utilitaire(u)
class AllerVersPoint(StrategieAvecUtilitaire) :
def __init__ (self, direction) :
self.direction = direction
self.nom = "AllerVersPointStrat"
def compute_strategy_utilitaire (self, u) :
return u.bouger(u.versUnPoint())
# Le joueur fonce vers le ballon
class AllerVersBallon(StrategieAvecUtilitaire):
def __init__(self):
self.name="AllerVersBallonStrat"
def compute_strategy_utilitaire (self, u) :
return u.bouger(u.versLaBalle())
# Le joueur Tire vers les buts
class Tirer(StrategieAvecUtilitaire) :
def __init__ (self) :
SoccerStrategy.__init__(self,"TirerStrat")
def compute_strategy_utilitaire (self, u) :
if u.aLaBalle():
return u.tirer(u.versLesButsAdverses())
return u.rienDuTout()
# Le joueur Dégage le ballon avec un angle prédéfini
class Degagement(SoccerStrategy):
def __init__(self):
self.name="DegagementStrat"
def compute_strategy_utilitaire (self, u) :
shoot = Vector2D.create_polar(u.player.angle + 3.5, 100)
return u.tirer(shoot)
# Le joueur tire autour de l'adversaire en face de lui
# Composition de deux stratègies, l'une basée sur le placement, l'autre sur le tir
class ComposeStrategy(StrategieAvecUtilitaire) :
def __init__(self,acceleration,shoot) :
self.acceleration = acceleration
self.shoot = shoot
def compute_strategy_utilitaire (self, u) :
return SoccerAction(self.acceleration.compute_strategy_utilitaire(u).acceleration, self.shoot.compute_strategy_utilitaire(u).shoot)
# Stratégie de placement en tant que defenseur
class PlacementDefenseur(StrategieAvecUtilitaire) :
def __init__(self) :
SoccerStrategy.__init__(self,"PlacementDefenseurStrat")
def compute_strategy_utilitaire (self, u) :
if u.distanceBallonMesButs().norm > 45 :
acceleration = u.entreBalleEtBut()
else :
acceleration = u.versLaBalle()
return u.bouger(acceleration)
# Stratégie de temporisation : attend l'acte du joueur a 9/10eme de la distance entre ses buts et le milieu du terrain
class Temporisation(StrategieAvecUtilitaire) :
def __init__(self) :
slef.name="TemporisationStrat"
def compute_strategy_utilitaire (self, u) :
milieuter = u.state.get_goal_center(u.teamid)
position = Vector2D(milieuter.x*0.1 + u.state.ball.position.x*0.9, milieuter.y*0.1 + u.state.ball.position.y*0.9)
return u.bouger(position)
# Stratégie de passe vers le joueur allié le plus proche
class Passe(StrategieAvecUtilitaire) :
def __init__(self) :
SoccerStrategy.__init__(self, "PasseStrat")
def compute_strategy_utilitaire (self, u) :
joueurLePlusProche = u.versJoueurLePlusProche()
if u.state.get_goal_center(u.adversaire())-u.player.position > u.state.get_goal_center(u.adversaire()) - u.joueurLePlusProche().position:
if (u.aLaBalle()) :
shoot = u.versJoueurLePlusProche()
return u.tirer(shoot)
return u.tirer(u.versLesButsAdverses())
return u.rienDuTout()
# Stratégie de placement de goal :
class PlacementGoal(StrategieAvecUtilitaire):
def __init__(self):
self.name="PlacementGoalStrat"
def compute_strategy_utilitaire (self, u) :
if u.distanceBallonMesButs().norm > 5 :
return u.bouger(u.entreBalleEtBut())
return u.bouger(u.versLaBalle())
# Stratégie de fonceur : combinaison AllerVersBallon + Tirer
class FonceurStrategy(StrategieAvecUtilitaire):
def __init__(self):
self.fonceurstrategy = ComposeStrategy(AllerVersBallon(), Tirer())
def compute_strategy_utilitaire (self, u) :
return self.fonceurstrategy.compute_strategy_utilitaire(u)
# Stratégie de défenseur 2v2 : combinaison PlacementDefenseur + passe
class DefenseurStrategy(StrategieAvecUtilitaire):
def __init__(self):
self.defenseurstrategy = ComposeStrategy(PlacementDefenseur(), Degagement())
def compute_strategy_utilitaire (self, u) :
return self.defenseurstrategy.compute_strategy_utilitaire(u)
# Stratégie de gardien de but 1v1 qui intercepte et fonce au but : Combinaison GoalStrategy + FonceurStrategy
class Goal1v1Strategy(StrategieAvecUtilitaire):
def __init__(self):
self.name="Goal1v1Strat"
def compute_strategy_utilitaire (self, u) :
if u.versLaBalle().norm > 10 :
return u.bouger(u.entreBalleEtBut())
else :
return SoccerAction(u.versLaBalle(), u.versLesButsAdverses())
# Stratégie de goal 2v2 : combinaison PlacementGoal + Passe
# Strtégie de dribleur : Combinaison AllerVersBallon + Drible(contournement)
class DribleStrategy(StrategieAvecUtilitaire):
def __init__(self):
self.dribleStrategy = ComposeStrategy(AllerVersBallon(), Contournement())
def compute_strategy_utilitaire (self, u) :
return self.dribleStrategy.compute_strategy_utilitaire(u)
<file_sep>from soccersimulator import SoccerBattle, SoccerPlayer, SoccerTeam
from soccersimulator import PygletObserver,ConsoleListener,LogListener
from soccersimulator import pyglet
from base_strategie import *
from ToolBox import *
team1=SoccerTeam("Minute Maid Tropical")
team1.add_player(SoccerPlayer("t1j1",Goal1v1Strategy()))
team2=SoccerTeam("Minute Maid Orange")
team2.add_player(SoccerPlayer("t2j1",DefenseurStrategy()))
team2.add_player(SoccerPlayer("t2j2",FonceurStrategy()))
team3=SoccerTeam("Minute Maid Pomme")
team3.add_player(SoccerPlayer("t1j1",FonceurStrategy()))
team3.add_player(SoccerPlayer("t1j4",DefenseurStrategy()))
team3.add_player(SoccerPlayer("t1j3",Goal1v1Strategy()))
team3.add_player(SoccerPlayer("t1j2",FonceurStrategy()))
teams =[team1, team2, team3]
<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Jan 26 18:27:50 2015
@author: 3200982
"""
from soccersimulator import pyglet
from soccersimulator import Vector2D, SoccerBattle, SoccerPlayer, SoccerTeam, SoccerStrategy, SoccerAction
from soccersimulator import PygletObserver,ConsoleListener,LogListener
class GoalStrategy(SoccerStrategy):
def __init__(self):
self.name="Goal"
def start_battle(self,state):
pass
def finish_battle(self,won):
pass
def idteamadverse(self,teamid) :
if(teamid == 1) :
return 2
else :
return 1
def compute_strategy(self,state,player,teamid):
diff = state.ball.position - player.position
if diff.norm > 5 :
vitesse = state.ball.position + state.get_goal_center(teamid) - player.position - player.position
shoot= state.get_goal_center(self.idteamadverse(teamid)) - player.position
else :
vitesse = state.ball.position - player.position
shoot= state.get_goal_center(self.idteamadverse(teamid)) - player.position
action = SoccerAction(vitesse,shoot)
return action
def copy(self):
return GoalStrategy()
def create_strategy(self):
return GoalStrategy()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Jan 26 18:48:43 2015
@author: 3200982
"""
#Test
from soccersimulator import pyglet
from soccersimulator import Vector2D, SoccerBattle, SoccerPlayer, SoccerTeam, SoccerStrategy, SoccerAction, GAME_WIDTH, GAME_HEIGHT
from soccersimulator import PygletObserver,ConsoleListener,LogListener
from base_strategie import *
team1=SoccerTeam("team1")
team2=SoccerTeam("team2")
team1.add_player(SoccerPlayer("t1j1",Goal1v1Strategy()))
team1.add_player(SoccerPlayer("t1j2",DefenseurStrategy()))
team2.add_player(SoccerPlayer("t2j1",FonceurStrategy()))
team2.add_player(SoccerPlayer("t2j2",FonceurStrategy()))
battle=SoccerBattle(team1,team2)
obs=PygletObserver()
obs.set_soccer_battle(battle)
pyglet.app.run()<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Feb 16 18:27:33 2015
@author: 3200982
"""
#encoding=utf8
from soccersimulator import pyglet
from soccersimulator import Vector2D, SoccerBattle, SoccerPlayer, SoccerTeam, SoccerStrategy, SoccerAction, GAME_WIDTH, GAME_HEIGHT, BALL_RADIUS, PLAYER_RADIUS
from soccersimulator import PygletObserver,ConsoleListener,LogListener
import math
class Utilitaire :
def __init__ (self, state, player, teamid) :
self.state = state
self.player = player
self.teamid = teamid
# ID team Adverse
def adversaire(self) :
if(self.teamid == 1) :
return 2
else :
return 1
# Mon joueur est à portée pour tirer la balle, "il a la balle"
def aLaBalle(self) :
return self.player.position.distance(self.state.ball.position)<=(PLAYER_RADIUS+BALL_RADIUS)
# Vecteur vers un point
def versUnPoint(self, direction) :
return direction - self.player.position
# Vecteur en direction de la Balle
def versLaBalle(self) :
return self.state.ball.position-self.player.position
# Vecteur en direction des buts adverses
def versLesButsAdverses(self) :
return self.state.get_goal_center(self.adversaire()) - self.player.position
# Vecteur de la distance entre mes buts et le ballon
def distanceBallonMesButs(self) :
return self.state.ball.position - self.state.get_goal_center(self.teamid)
# Vecteur de la distance entre le ballon et le joueur adverse
def distanceBallonAdversaire(self) :
return self.state.ball.position - self.player.adversaire().position
# Vecteur de la distance entre mon joueur et les buts adverses
def distanceJoueurButAdverse(self) :
return self.state.get_goal_center(adversaire()) - self.player.position
# Mon joueur ne fait rien
def rienDuTout(self) :
return SoccerAction(Vector2D(0,0), Vector2D(0,0))
# Mon joueur bouge vers un endroit (sans tirer)
def bouger(self, acceleration) :
return SoccerAction(acceleration, Vector2D(0,0))
# Mon joueur tire vers un endroit (sans bouger)
def tirer(self, shoot) :
return SoccerAction(Vector2D(0,0), shoot)
# Mon joueur bouge et tire vers un endroit
def bougertirer(self, acceleration, shoot) :
return SoccerAction(acceleration, shoot)
# Mon joueur se place entre la balle est ses buts
def entreBalleEtBut(self) :
return self.state.ball.position + self.state.get_goal_center(self.teamid) - self.player.position - self.player.position
# Id du joueur le plus proche du joueur ami avec le ballon hormis le joueur avec le ballon
def joueurLePlusProche(self) :
if (self.teamid == 1) :
res = [self.state.ball.position.distance(p.position) for p in self.state.team1.players if p!= self.player]
m = min(res)
return self.state.team1.players[res.index(m)]
else :
res = [self.state.ball.position.distance(p.position) for p in self.state.team2.players if p!= self.player]
m=min(res)
return self. state.team2.players[res.index(m)]
# Vecteur vers joueur le plus proche du joueur ami avec le ballon hormis le joueur avec le ballon
def versJoueurLePlusProche(self) :
return self.joueurLePlusProche().position - self.player.position
# Indique si mon équipe possède le ballon ou non
def onALaBalle(self):
x = 12345
for p in self.state.team1 :
distanceDuBallon = self.state.ball.position - p.position
if(distanceDuBallon.norm < x):
x = distanceDuBallon.norm
y = 12345
for q in self.state.team2 :
distanceDuBallon2 = self.state.ball.position - q.position
if(distanceDuBallon.norm < x):
y = distanceDuBallon2.norm
if(((x < y and self.team == 1) or (x > y and self.team == 2)) and y < GAME_WIDTH * 0.2):
return True
else:
return False
|
ccd0a17cac82a9979f814e0b49c9d0aa519708a8
|
[
"Python"
] | 7
|
Python
|
ArezkiSky/Projet-soccer-2I013
|
a9bacf43d77822416d9bd5cc8292c9e01c30fab6
|
e65c277d3f60a2df655021ef4b7526fa2887c178
|
refs/heads/master
|
<repo_name>spandanpal22/Tic-Tac-Toe<file_sep>/README.md
# Tic-Tac-Toe
This is a classic Tic-Tac-Toe game that can be played by two persons. Download and run the .exe file to play it. And if you want to
modify, you can as I have also provided the .cpp file.
<file_sep>/TICTACTO.CPP
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
void display();
int main()
{
system("CLS");
char ch,j='1',c[9],np1[20],np2[20];
int sp1=0,sp2=0,i,choice;
cout<<"\t\t\t\tTic-tac-toe\n\t\t\t\t-----------";
cout<<"\nEnter player 1 name : ";
cin.getline(np1,20);
cout<<"\nEnter player 2 name : ";
cin.getline(np2,20);
system("CLS");
again:
for(i=0,j;i<=8;i++,j++)
{
c[i]=j;
}
cout<<"\t\t\t\tTic-tac-toe\n\t\t\t\t-----------";
cout<<"\n"<<np1<<" is X (Score : "<<sp1<<")\t\t\t\t"<<np2<<" is o(Score : "<<sp2<<")";
cout<<"\n\t\t\t\t"<<c[0]<<" | "<<c[1]<<" | "<<c[2]<<endl;
cout<<"\t\t\t\t---|-----|---"<<endl;
cout<<"\t\t\t\t"<<c[3]<<" | "<<c[4]<<" | "<<c[5]<<endl;
cout<<"\t\t\t\t---|-----|---"<<endl;
cout<<"\t\t\t\t"<<c[6]<<" | "<<c[7]<<" | "<<c[8]<<endl;
for(i=1;i<=5;i++)
{
cout<<np1<<"'s turn.Select your choice : ";
cin>>choice;
if(choice<1||choice>9)
{
cout<<"Incorrect Choice!!! Try Again";
goto temp1;
}
if(c[choice-1]=='o'||c[choice-1]=='X')
{
cout<<"\nThis place is already occupied.Choose another place.";
temp1:
cout<<endl<<np1<<" Select your choice : ";
cin>>choice;
}
c[choice-1]='X';
system("CLS");
cout<<"\t\t\t\tTic-tac-toe\n\t\t\t\t-----------";
cout<<"\n"<<np1<<" is X (Score : "<<sp1<<")\t\t\t\t"<<np2<<" is o(Score : "<<sp2<<")";
cout<<"\n\t\t\t\t"<<c[0]<<" | "<<c[1]<<" | "<<c[2]<<endl;
cout<<"\t\t\t\t---|-----|---"<<endl;
cout<<"\t\t\t\t"<<c[3]<<" | "<<c[4]<<" | "<<c[5]<<endl;
cout<<"\t\t\t\t---|-----|---"<<endl;
cout<<"\t\t\t\t"<<c[6]<<" | "<<c[7]<<" | "<<c[8]<<endl;
if((c[0]=='X'&&c[1]=='X'&&c[2]=='X')||(c[3]=='X'&&c[4]=='X'&&c[5]=='X')||(c[6]=='X'&&c[7]=='X'&&c[8]=='X')||(c[0]=='X'&&c[3]=='X'&&c[6]=='X')||(c[1]=='X'&&c[4]=='X'&&c[7]=='X')||(c[2]=='X'&&c[5]=='X'&&c[8]=='X')||(c[0]=='X'&&c[4]=='X'&&c[8]=='X')||(c[6]=='X'&&c[4]=='X'&&c[2]=='X'))
{
cout<<"\n\t\t\t Congratuations!!!\n\t\t\t "<<endl;
display();
cout<<"\n\t\t\t "<<np1<<" has won the match.";
sp1++;
break;
}
else if((c[0]=='o'&&c[1]=='o'&&c[2]=='o')||(c[3]=='o'&&c[4]=='o'&&c[5]=='o')||(c[6]=='o'&&c[7]=='o'&&c[8]=='o')||(c[0]=='o'&&c[3]=='o'&&c[6]=='o')||(c[1]=='o'&&c[4]=='o'&&c[7]=='o')||(c[2]=='o'&&c[5]=='o'&&c[8]=='o')||(c[0]=='o'&&c[4]=='o'&&c[8]=='o')||(c[6]=='o'&&c[4]=='o'&&c[2]=='o'))
{
cout<<"\n\t\t\t Congratuations!!!\n\t\t\t "<<endl;
display();
cout<<"\n\t\t\t "<<np2<<" has won the match.";
sp2++;
break;
}
if(i==5)
{
cout<<"It's a draw.";
sp1++;
sp2++;
}
if(i<=4)
{
cout<<np2<<"'s turn.Select your choice : ";
cin>>choice;
if(choice<1||choice>9)
{
cout<<"Incorrect Choice!!! Try Again";
goto temp2;
}
if(c[choice-1]=='o'||c[choice-1]=='X')
{
cout<<"\nThis place is already occupied.Choose another place.";
temp2:
cout<<endl<<np2<<" Select your choice : ";
cin>>choice;
}
c[choice-1]='o';
system("CLS");
cout<<"\t\t\t\tTic-tac-toe\n\t\t\t\t-----------";
cout<<"\n"<<np1<<" is X (Score : "<<sp1<<")\t\t\t\t"<<np2<<" is o(Score : "<<sp2<<")";
cout<<"\n\t\t\t\t"<<c[0]<<" | "<<c[1]<<" | "<<c[2]<<endl;
cout<<"\t\t\t\t---|-----|---"<<endl;
cout<<"\t\t\t\t"<<c[3]<<" | "<<c[4]<<" | "<<c[5]<<endl;
cout<<"\t\t\t\t---|-----|---"<<endl;
cout<<"\t\t\t\t"<<c[6]<<" | "<<c[7]<<" | "<<c[8]<<endl;
if((c[0]=='X'&&c[1]=='X'&&c[2]=='X')||(c[3]=='X'&&c[4]=='X'&&c[5]=='X')||(c[6]=='X'&&c[7]=='X'&&c[8]=='X')||(c[0]=='X'&&c[3]=='X'&&c[6]=='X')||(c[1]=='X'&&c[4]=='X'&&c[7]=='X')||(c[2]=='X'&&c[5]=='X'&&c[8]=='X')||(c[0]=='X'&&c[4]=='X'&&c[8]=='X')||(c[6]=='X'&&c[4]=='X'&&c[2]=='X'))
{
cout<<"\n\t\t\t Congratuations!!!\n\t\t\t "<<endl;
display();
cout<<"\n\t\t\t "<<np1<<" has won the match.";
sp1++;
break;
}
else if((c[0]=='o'&&c[1]=='o'&&c[2]=='o')||(c[3]=='o'&&c[4]=='o'&&c[5]=='o')||(c[6]=='o'&&c[7]=='o'&&c[8]=='o')||(c[0]=='o'&&c[3]=='o'&&c[6]=='o')||(c[1]=='o'&&c[4]=='o'&&c[7]=='o')||(c[2]=='o'&&c[5]=='o'&&c[8]=='o')||(c[0]=='o'&&c[4]=='o'&&c[8]=='o')||(c[6]=='o'&&c[4]=='o'&&c[2]=='o'))
{
cout<<"\n\t\t\t Congratuations!!!\n\t\t\t "<<endl;
display();
cout<<"\n\t\t\t "<<np2<<" has won the match.";
sp2++;
break;
}
}
}
cout<<"\nDo you want to play again ?(Y/N) ";
cin>>ch;
j='1';
if(ch=='y'||ch=='Y')
{
system("CLS");
goto again;
}
cout<<"Final scores are :\n\t"<<np1<<" has scored "<<sp1<<"\n\t"<<np2<<" has scored "<<sp2;
if(sp1>sp2)
cout<<"\nFinal winner is "<<np1;
else if(sp1<sp2)
cout<<"\nFinal winner is "<<np2;
else
cout<<"\nThe match is draw.";
getch();
return 0;
}
void display()
{
cout<<"\t\t\t\t*\n\t\t\t * * *\n\t\t\t * * * * * *\n\t\t * * * * * * * * *\n\t\t\t * * * * * *\n\t\t\t * * *\n\t\t\t\t*";
}
|
cb51f690c845f6ab1c8dd13759ac6713759cd3c6
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
spandanpal22/Tic-Tac-Toe
|
9961fba77fd0a5baf56d012a340669acf1f9acd8
|
024ff39becf4f2db176c0f5b5c5352a5e26c75f1
|
refs/heads/master
|
<repo_name>varun-king/FoodDeliveryAPP<file_sep>/Order+CoreDataClass.swift
//
// Order+CoreDataClass.swift
// foodDelivery
//
// Created by apple on 5/30/20.
// Copyright © 2020 varun. All rights reserved.
//
//
import Foundation
import CoreData
@objc(Order)
public class Order: NSManagedObject {
}
<file_sep>/Reward+CoreDataProperties.swift
//
// Reward+CoreDataProperties.swift
// foodDelivery
//
// Created by apple on 5/30/20.
// Copyright © 2020 varun. All rights reserved.
//
//
import Foundation
import CoreData
extension Reward {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Reward> {
return NSFetchRequest<Reward>(entityName: "Reward")
}
@NSManaged public var user_email: String?
@NSManaged public var isUsed: Bool
@NSManaged public var coupon: String?
@NSManaged public var per_off: Int16
}
<file_sep>/foodDelivery/MenuStruct.swift
//
// MenuStruct.swift
// foodDelivery
//
// Created by apple on 5/30/20.
// Copyright © 2020 varun. All rights reserved.
//
import Foundation
struct MenuStruct:Codable {
var sku:String = ""
var name:String = ""
var description:String = ""
var photo:String = ""
var price:Double = 0.0
var calorie:Int = 0
init() {}
}
<file_sep>/foodDelivery/View/OrderViewController.swift
//
// OrderViewController.swift
// foodDelivery
//
// Created by apple on 5/30/20.
// Copyright © 2020 varun. All rights reserved.
//
import UIKit
class OrderViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
var username = ""
var password = ""
var price = 0.0
var defaults:UserDefaults!
var tip = 0
var percentageOff = 0
var sku = ""
var selectedDay = ""
//MARK: Outlets
@IBOutlet weak var foodImg: UIImageView!
@IBOutlet weak var txtFoodName: UILabel!
@IBOutlet weak var txtFoodPrice: UILabel!
@IBOutlet weak var txtFoodDesc: UITextView!
@IBOutlet weak var txtCouponMessage: UILabel!
@IBOutlet weak var txtCoupon: UITextField!
@IBOutlet weak var txtTip: UITextField!
var couponArry:[String] = [String]()
let couponTypePikerView = UIPickerView()
override func viewDidLoad() {
super.viewDidLoad()
self.defaults = UserDefaults.standard
let name = self.defaults.string(forKey: "foodName")
let desc = self.defaults.string(forKey: "foodDesc")
let photo = self.defaults.string(forKey: "foodImg")
sku = self.defaults.string(forKey: "foodSku")!
price = self.defaults.double(forKey: "foodPrice")
let calorie = self.defaults.integer(forKey: "foodCalorie")
username = self.defaults.string(forKey: "username")!
password = self.defaults.string(forKey: "password")!
// get the age
foodImg.image = UIImage(named: "\(photo!).jpg")
txtFoodName.text = name!
txtFoodDesc.text = desc!
txtFoodPrice.text = String(price)
couponArry = DatabaseController.instance.getAllUnUsedCoupon(user: username)
self.couponTypePikerView.delegate = self
txtCoupon.inputView = couponTypePikerView
self.couponTypePikerView.reloadAllComponents()
createToolbar()
print("name: \(name!) \n desc: \(desc!) \n photo: \(photo!) \n sku: \(sku) \n price: \(price) \n calorie: \(calorie) \n username: \(username) \n password: <PASSWORD>) \n")
}
func createToolbar() {
let toolbar = UIToolbar()
toolbar.sizeToFit()
self.couponTypePikerView.reloadAllComponents()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(dismissKeyboard
))
toolbar.setItems([doneButton], animated: false)
toolbar.isUserInteractionEnabled = true
txtCoupon.inputAccessoryView = toolbar
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return couponArry.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return couponArry[row]
}
// To hidePikerView
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedDay = couponArry[row]
txtCoupon.text = selectedDay
}
@IBAction func addTipButtonPressed(_ sender: Any) {
tip = Int(txtTip.text!) ?? 0
}
@IBAction func tip10(_ sender: Any) {
tip = 10
txtTip.text = "10%"
}
@IBAction func tip15(_ sender: Any) {
tip = 15
txtTip.text = "15%"
}
@IBAction func tip20(_ sender: Any) {
tip = 20
txtTip.text = "20%"
}
@IBAction func applyButtonPressed(_ sender: Any) {
let user = username
let coupon = txtCoupon.text!
if(coupon != "" || user != ""){
let check = DatabaseController.instance.validateCoupon(user: user, coupon: coupon )
txtCouponMessage.text = "\(check.message)"
self.percentageOff = check.off
DatabaseController.instance.updateRewardCouponForthisUser(user: user, coupon: coupon)
}
}
@IBAction func placeOrderButtonPreesed(_ sender: Any) {
let date = NSDate()
var tipMoney = 0.0
var discount = 0.0
print("Tip \(tip)")
if(tip != 0){
tipMoney = price * (Double(tip)/100.0)
print("Tip \(tipMoney)")
}
if(self.percentageOff != 0){
discount = price * Double(self.percentageOff) / 100.0
}
let tax = (price + tipMoney + discount) * 0.13
let subtotal = price + tipMoney - discount + tax
self.defaults.set(subtotal, forKey: "ordSubtotal")
self.defaults.set(discount, forKey: "ordDiscont")
self.defaults.set(tax, forKey: "ordTax")
self.defaults.set(tipMoney, forKey: "ordTip")
self.defaults.set(date, forKey: "ordDate")
var customerInfo = DatabaseController.instance.checkLogin(email: username, password: <PASSWORD>)
var foodObje = DatabaseController.instance.foodObject(sku: sku)
DatabaseController.instance.saveOrderToDatabase(date: date as Date, subtotal: subtotal, taxD: tax, tipD: tipMoney, discountD: discount, food_menu: foodObje[0], customerData: customerInfo[0])
performSegue(withIdentifier: "receiptViewController", sender: self)
}
}
<file_sep>/foodDelivery/Database Controler/DatabaseController.swift
//
// DatabaseController.swift
// foodDelivery
//
// Created by apple on 5/30/20.
// Copyright © 2020 varun. All rights reserved.
//
import Foundation
import CoreData
import UIKit
class DatabaseController{
static let instance = DatabaseController()
let database = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// let database = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
func signUp(password:String, email:String, phone:String, image:NSData) -> String {
var message = ""
let customer = Customer(context:database)
customer.customer_password = <PASSWORD>
customer.customer_email = email
customer.customer_phone = phone
customer.customer_image = image
// save to the database
do {
try database.save()
message = "User Create Successfully"
}
catch {
// print("error!")
message = "\(error)"
}
return message
}
func checkLogin(email:String, password:String) -> [Customer]{
var customer:[Customer] = [Customer]()
let request : NSFetchRequest<Customer> = Customer.fetchRequest()
let query = NSPredicate(format: "customer_email == %@", "\(email)")
request.predicate = query
do {
let results = try database.fetch(request)
if results.count == 0 {
print("no results found")
}
else {
customer = results
// print each user
print("sign IN")
for user in results {
print(user.customer_email!)
}
}
}catch{
//message = "\(error)"
print("Error in signIn : \(error)")
}
return customer
}
func checkUserExist(email:String) -> [Customer]{
var customer:[Customer] = [Customer]()
let request : NSFetchRequest<Customer> = Customer.fetchRequest()
let query = NSPredicate(format: "customer_email == %@", "\(email)")
request.predicate = query
do {
let results = try database.fetch(request)
customer = results
print("Hey you are here")
}catch{
//message = "\(error)"
print("Error in signIn : \(error)")
}
return customer
}
func saveFoodMenuToCoreData(sku:String, name:String, desc:String, img:String, price:Double, caloie:Int) -> String{
var message = ""
let food_menu = FoodMenu(context:database)
food_menu.meal_name = name
food_menu.meal_sku = sku
food_menu.meal_description = desc
food_menu.meal_photo = img
food_menu.meal_price = price
food_menu.meal_calorie = Int16(caloie)
// save to the database
do {
try database.save()
message = "Save Successfully"
}
catch {
print("error!")
message = "\(error)"
}
return message
}
func foodDatabaseCheck() -> Int {
var food:[FoodMenu] = [FoodMenu]()
var value = 0
let request : NSFetchRequest<FoodMenu> = FoodMenu.fetchRequest()
// let query = NSPredicate(format: "customer_email == %@", "\(email)")
// request.predicate = query
do {
let results = try database.fetch(request)
if results.count == 0 {
print("no results found")
value = 0
}
else {
// print each user
print("sign IN")
for user in results {
print(user.meal_photo!)
}
value = results.count
}
}catch{
//message = "\(error)"
print("Error in Finding Food : \(error)")
}
return value
}
func giveDataBackTo() -> [FoodMenu] {
print("We are in func giveDataBackTo ")
var food:[FoodMenu] = [FoodMenu]()
let request : NSFetchRequest<FoodMenu> = FoodMenu.fetchRequest()
// let query = NSPredicate(format: "customer_email == %@", "\(email)")
// request.predicate = query
do {
let results = try database.fetch(request)
if results.count == 0 {
print("no results found")
}
else {
food = results
// print each user
// print("sign IN")
print("IN else Found Result \(food)")
}
}catch{
//message = "\(error)"
print("Error in Finding Food : \(error)")
}
return food
}
//MARK: Add Coupon
func addCoupon(coupon:String, mail:String, used:Bool, percentage:Int) -> String{
var message = ""
let reward_coupon = Reward(context:database)
reward_coupon.coupon = coupon
reward_coupon.user_email = mail
reward_coupon.per_off = Int16(percentage)
reward_coupon.isUsed = false
// save to the database
do {
try database.save()
message = "You won Coupon"
}
catch {
print("error!")
message = "\(error)"
}
return message
}
//Display all Unused Coupon to user
func getAllUnUsedCoupon(user:String) -> [String]{
var couponArray:[String] = [String]()
couponArray.append(" ")
let request : NSFetchRequest<Reward> = Reward.fetchRequest()
let query = NSPredicate(format: "user_email == %@", "\(user)")
request.predicate = query
do {
let results = try database.fetch(request)
if results.count == 0 {
// print("no results found")
// message = "In Validate Coupon"
}
else {
for user in results {
if(user.isUsed == false){
couponArray.append(user.coupon!)
}else {
print("No Coupon")
}
}
}
}catch{
//message = "\(error)"
print("Error in Finding Coupon : \(error)")
}
return couponArray
}
//MARK: ValidationOfCoupon
func validateCoupon(user:String, coupon:String) -> (off:Int,message:String) {
var message = ""
var off = 0
print("We are in func validateCoupon ")
var validaCop:[Reward] = [Reward]()
let request : NSFetchRequest<Reward> = Reward.fetchRequest()
let query = NSPredicate(format: "user_email == %@", "\(user)")
request.predicate = query
do {
let results = try database.fetch(request)
if results.count == 0 {
// print("no results found")
message = "In Validate Coupon"
}
else {
validaCop = results
for user in results {
if(user.isUsed == false && user.coupon == coupon){
print("Is Used: \(user.isUsed)")
print("Coupon is \(coupon)")
message = "Successfully Applied"
off = Int(user.per_off)
print("Coupon Value: \(Int(user.per_off))")
} else if(user.isUsed == true && user.coupon == coupon){
print("Coupon is \(coupon)")
message = "Already Applied"
off = 0
}
}
}
}catch{
//message = "\(error)"
print("Error in Finding Coupon : \(error)")
}
return (off,message)
}
//Update Coupon Usage
func updateRewardCouponForthisUser(user:String, coupon:String){
var validaCop:[Reward] = [Reward]()
let request : NSFetchRequest<Reward> = Reward.fetchRequest()
let query = NSPredicate(format: "user_email == %@", "\(user)")
request.predicate = query
let query2 = NSPredicate(format: "coupon == %@", "\(coupon)")
request.predicate = query2
do {
let results = try database.fetch(request)
if results.count == 0 {
// print("no results found")
//message = "In Validate Coupon"
}
else {
validaCop = results
let people = validaCop[0] as NSManagedObject
//let person = NSManagedObject(entity: entity, insertInto: managedContext)
people.setValue(true, forKeyPath: "isUsed")
//save the context
do {
try database.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
}catch{
//message = "\(error)"
print("Error in Finding Coupon : \(error)")
}
}
func saveOrderToDatabase(date:Date, subtotal:Double, taxD:Double, tipD:Double, discountD:Double, food_menu:FoodMenu, customerData:Customer){
var message = ""
let orderData = OrderData(context:database)
orderData.date = date as NSDate
orderData.discount = discountD
orderData.tax = taxD
orderData.tip = tipD
orderData.subtotal = subtotal
orderData.foodOtions = food_menu
orderData.orderCutomer = customerData
// save to the database
do {
try database.save()
message = "You won Coupon"
print("Order Data Added to Data Base")
}
catch {
print("error!")
message = "\(error)"
}
}
func foodObject(sku:String) -> [FoodMenu]{
var foodOBJ:[FoodMenu] = [FoodMenu]()
let request : NSFetchRequest<FoodMenu> = FoodMenu.fetchRequest()
let query = NSPredicate(format: "meal_sku == %@", "\(sku)")
request.predicate = query
do {
let results = try database.fetch(request)
if results.count == 0 {
print("no results found")
}
else {
foodOBJ = results
// print each user
// print("sign IN")
// print("IN else Found Result \(food)")
}
}catch{
//message = "\(error)"
print("Error in Finding Food : \(error)")
}
return foodOBJ
}
func getOrderHistory(userEmail:String) -> [OrderData] {
var returnType:[OrderData] = [OrderData]()
let request : NSFetchRequest<OrderData> = OrderData.fetchRequest()
do {
let results = try database.fetch(request)
if results.count == 0 {
print("no results found")
}
else {
// returnType = results
for order in results{
if(order.orderCutomer?.customer_email == userEmail){
returnType.append(order)
}
}
// print each user
// print("sign IN")
// print("IN else Found Result \(food)")
}
}catch{
//message = "\(error)"
print("Error in Finding Food : \(error)")
}
return returnType
}
//FInal CLose
}
<file_sep>/OrderData+CoreDataClass.swift
//
// OrderData+CoreDataClass.swift
// foodDelivery
//
// Created by apple on 5/30/20.
// Copyright © 2020 varun. All rights reserved.
//
//
import Foundation
import CoreData
@objc(OrderData)
public class OrderData: NSManagedObject {
}
<file_sep>/foodDelivery/View/signUpViewController.swift
//
// signUpViewController.swift
// foodDelivery
//
// Created by apple on 5/29/20.
// Copyright © 2020 varun. All rights reserved.
//
import UIKit
class signUpViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARKS: Outlets
@IBOutlet weak var txtEmail: UITextField!
@IBOutlet weak var txtPassword: UITextField!
@IBOutlet weak var txtPhone: UITextField!
@IBOutlet weak var saveImage: UIImageView!
//MARK: Variebles
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
let tapGuesture = UITapGestureRecognizer(target: self, action: #selector(self.selectImage(gesture:)))
self.saveImage.isUserInteractionEnabled = true
self.saveImage.addGestureRecognizer(tapGuesture)
}
@objc func selectImage(gesture: UITapGestureRecognizer){
if(UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum)){
imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}
}
// MARKS: Actions
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
self.imagePicker.dismiss(animated: true, completion: nil)
let img = info[.originalImage] as? UIImage
self.saveImage.image = img
}
@IBAction func takePhotoFromCamara(_ sender: Any) {
print("Camara Button Pressed")
if(UIImagePickerController.isSourceTypeAvailable(.camera)){
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}else{
showAlertboax(title: "No Camara", message: "This device does not have camara. You have to choose from galary by clicking on image section")
print("this device does not have camara. You have choose from galary by clicking on image section")
}
}
func showAlertboax(title:String, message:String){
let box = UIAlertController(
title: "\(title)",
message: "\(message)",
preferredStyle: .alert
)
box.addAction(
UIAlertAction(title: "OK", style: .default, handler: {action in
// self.performSegue(withIdentifier: "signInPage", sender: self)
})
)
self.present(box, animated: true)
}
@IBAction func signUpButtonPressed(_ sender: Any) {
print("SignUp Button Pressed")
var message = ""
var count = 0
if(txtEmail.text! != ""){
var userExe = DatabaseController.instance.checkUserExist(email: txtEmail.text!)
count = userExe.count
}
if(txtPassword.text! == "" || txtEmail.text! == "" || txtPhone.text! == ""){
showAlertboax(title: "Error", message: "Every Field Must be filled")
}else if(txtEmail.text! != "" && count != 0){
showAlertboax(title: "Error", message: "User already exists")
return
}else{
let jpg = self.saveImage.image?.jpegData(compressionQuality: 0.75)
message = DatabaseController.instance.signUp(password: <PASSWORD>!, email: txtEmail.text!, phone: txtPhone.text!, image: jpg as! NSData)
showAlertboax(title: "Successful", message: "\(message)")
txtEmail.text = ""
txtPhone.text = ""
txtPassword.text = ""
print(message)
}
}
}
<file_sep>/foodDelivery/CustomTableViewCell.swift
//
// CustomTableViewCell.swift
// foodDelivery
//
// Created by apple on 5/30/20.
// Copyright © 2020 varun. All rights reserved.
//
import UIKit
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var cellView: UIView!
@IBOutlet weak var txtFoodImage: UIImageView!
@IBOutlet weak var txtFoodName: UILabel!
@IBOutlet weak var txtFoodCalorie: UILabel!
@IBOutlet weak var txtFoodPrice: UILabel!
@IBOutlet weak var txtFoodDescr: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
<file_sep>/foodDelivery/View/receiptViewController.swift
//
// receiptViewController.swift
// foodDelivery
//
// Created by apple on 5/29/20.
// Copyright © 2020 varun. All rights reserved.
//
import UIKit
import UserNotifications
import MapKit
import CoreLocation
class receiptViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
var locationManager:CLLocationManager?
var count = 20
var timer:Timer?
//Outlets
var defaults:UserDefaults!
@IBOutlet weak var txtOrderDate: UILabel!
@IBOutlet weak var txtOrderSku: UILabel!
@IBOutlet weak var txtOrderName: UILabel!
@IBOutlet weak var imgOrderImg: UIImageView!
@IBOutlet weak var txtOrderPrice: UILabel!
@IBOutlet weak var txtOrderDisnt: UILabel!
@IBOutlet weak var txtOrderTip: UILabel!
@IBOutlet weak var txtOrderTax: UILabel!
@IBOutlet weak var txtOrderSubtotal: UILabel!
var orderInfo:[OrderData] = []
override func viewDidLoad() {
super.viewDidLoad()
self.defaults = UserDefaults.standard
// let date = self.defaults.data(forKey: "ordDate")!
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss a"
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
// let dateString = formatter.string(from: (date as!Date) as Date)
txtOrderName.text = self.defaults.string(forKey: "foodName")!
// txtOrderDate.text = dateString
imgOrderImg.image = UIImage(named: "\(self.defaults.string(forKey: "foodImg")!).jpg")
txtOrderSku.text = self.defaults.string(forKey: "foodSku")!
txtOrderPrice.text = String(self.defaults.double(forKey: "foodPrice"))
//let calorie = self.defaults.integer(forKey: "foodCalorie")
txtOrderSubtotal.text = String(self.defaults.double(forKey: "ordSubtotal"))
txtOrderTax.text = String(self.defaults.double(forKey: "ordTax"))
txtOrderTip.text = String(self.defaults.double(forKey: "ordTip"))
txtOrderDisnt.text = String(self.defaults.double(forKey: "ordDiscont"))
// For Order Notification
locationManager = CLLocationManager()
locationManager?.delegate = self
// self.mapView.delegate = self
// self.mapView.delegate = self
let storeLocation = CLLocationCoordinate2D(latitude: 43.774710, longitude: -79.695090)
let zoomLavel = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
let region = MKCoordinateRegion(center: storeLocation, span: zoomLavel)
/*mapView.setRegion(region, animated: true)
let storePin = MKPointAnnotation()
storePin.coordinate = storeLocation
storePin.title = "Store"
mapView.addAnnotation(storePin)
*/
locationManager?.requestWhenInUseAuthorization()
locationManager?.startUpdatingLocation()
// mapView.showsUserLocation = true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
// userloca = CLLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let lat = location.coordinate.latitude
let long = location.coordinate.longitude
let someOtherLocation: CLLocation = CLLocation(latitude: 43.774710, longitude: -79.695090)
let usersCurrentLocation: CLLocation = CLLocation(latitude: lat, longitude: long)
let distanceInMeters: CLLocationDistance = usersCurrentLocation.distance(from: someOtherLocation)
if distanceInMeters < 100 {
print("\(distanceInMeters)")
print("He is near you")
callNatifiation()
let box = UIAlertController(
title: "Start Preparing Order",
message: "Your Order has been prepared.",
preferredStyle: .alert
)
box.addAction(
UIAlertAction(title: "OK", style: .default, handler: nil)
)
self.present(box, animated: true)
guard timer == nil else { return }
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
self.count = self.count - 1
print("Count is \( self.count)")
if(self.count == 0){
let box = UIAlertController(
title: "Order ready",
message: "Your Order is ready",
preferredStyle: .alert
)
box.addAction(
UIAlertAction(title: "OK", style: .default, handler: {action in
inavlidate()
})
)
self.present(box, animated: true)
}
})
func inavlidate() {
self.timer?.invalidate()
print("you are here")
count = 30
}
} else {
print("\(distanceInMeters)")
print("He is very Dooooor")
// this user is at least over 100 meters outside the otherLocation
}
}
func callNatifiation(){
print("Notifucation Function")
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Reminder"
content.body = "Your Oder is redy"
content.sound = .default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 15, repeats: false)
let request = UNNotificationRequest(identifier: "Reminder", content: content, trigger: trigger)
center.add(request) { (error) in
if error != nil{
print("Error = \(error?.localizedDescription ?? "Local notification ")")
}
}
}
@IBAction func continueButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "continue_shopping", sender: self)
}
}
<file_sep>/foodDelivery/View/orderHistoryViewController.swift
//
// orderHistoryViewController.swift
// foodDelivery
//
// Created by apple on 5/29/20.
// Copyright © 2020 varun. All rights reserved.
//
import UIKit
class orderHistoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var historyTableView: UITableView!
var orderHistory:[OrderData] = [OrderData]()
var defaults:UserDefaults!
override func viewDidLoad() {
super.viewDidLoad()
self.defaults = UserDefaults.standard
print("You are in History")
orderHistory = DatabaseController.instance.getOrderHistory(userEmail: "\(self.defaults.string(forKey: "username")!)")
print("\(orderHistory)")
for order in orderHistory{
print("Food Name: \((order.foodOtions?.meal_name!)!)")
print("Customer Name: \((order.orderCutomer?.customer_email!)!)")
}
self.historyTableView.delegate = self
self.historyTableView.dataSource = self
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return orderHistory.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = historyTableView.dequeueReusableCell(withIdentifier: "myCell") as! HistoryTableViewCell
let date_time = orderHistory[indexPath.row].date
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss a"
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
let dateString = formatter.string(from: date_time! as Date)
cell.txtName.text = "\((orderHistory[indexPath.row].foodOtions?.meal_name!)!)"
cell.txtImage.image = UIImage(named: "\((orderHistory[indexPath.row].foodOtions?.meal_photo!)!)")
cell.txtDate.text = "\(dateString)"
return cell
}
}
<file_sep>/OrderData+CoreDataProperties.swift
//
// OrderData+CoreDataProperties.swift
// foodDelivery
//
// Created by apple on 5/30/20.
// Copyright © 2020 varun. All rights reserved.
//
//
import Foundation
import CoreData
extension OrderData {
@nonobjc public class func fetchRequest() -> NSFetchRequest<OrderData> {
return NSFetchRequest<OrderData>(entityName: "OrderData")
}
@NSManaged public var date: NSDate?
@NSManaged public var subtotal: Double
@NSManaged public var tax: Double
@NSManaged public var tip: Double
@NSManaged public var discount: Double
@NSManaged public var foodOtions: FoodMenu?
@NSManaged public var orderCutomer: Customer?
}
<file_sep>/FoodMenu+CoreDataClass.swift
//
// FoodMenu+CoreDataClass.swift
// foodDelivery
//
// Created by apple on 5/30/20.
// Copyright © 2020 varun. All rights reserved.
//
//
import Foundation
import CoreData
@objc(FoodMenu)
public class FoodMenu: NSManagedObject {
}
<file_sep>/foodDelivery/mealPackageViewController.swift
//
// mealPackageViewController.swift
// foodDelivery
//
// Created by apple on 5/29/20.
// Copyright © 2020 varun. All rights reserved.
//
import UIKit
import CoreData
class mealPackageViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: Outlets
@IBOutlet weak var foodTabelView: UITableView!
// MARK: Variables
var menuData:[MenuStruct] = []
var foodOptions:[FoodMenu] = []
override func viewDidLoad() {
foodTabelView.delegate = self
foodTabelView.dataSource = self
// load the json file here
guard let file = openFile() else { return }
// load words from file into data source
menuData = self.getData(from: file)!
//Check for blank Database
let resultConts = DatabaseController.instance.foodDatabaseCheck()
if(resultConts != 5){
for i in 0 ..< menuData.count{
let message = DatabaseController.instance.saveFoodMenuToCoreData(sku: menuData[i].sku, name: menuData[i].name, desc: menuData[i].description, img: menuData[i].photo, price: menuData[i].price, caloie: menuData[i].calorie)
print("Menu Item Stored in Data : \(message)")
}
}
foodOptions = DatabaseController.instance.giveDataBackTo()
super.viewDidLoad()
}
func openDefaultFile()-> String? {
guard let file = Bundle.main.path(forResource:"MenuDetail", ofType:"json") else {
print("Cannot find file")
return nil;
}
print("File found: \(file.description)")
return file
}
func openFile() -> String? {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let finalPath = paths[0]
let filename = finalPath.appendingPathComponent("MenuDetail.json")
// check if file exists
let fileExists = FileManager().fileExists(atPath: filename.path)
if (fileExists == true) {
// load words from saved file
return filename.path;
}
else {
// open words from default file
return self.openDefaultFile()
}
return nil
}
func getData(from file:String?) -> [MenuStruct]? {
if (file == nil) {
print("File path is null")
return nil
}
do {
// open the file
let jsonData = try String(contentsOfFile: file!).data(using: .utf8)
print(jsonData) // outputs: Optional(749Bytes)
// get content of file
let decodedData =
try JSONDecoder().decode([MenuStruct].self, from: jsonData!)
// DEBUG: print file contents to screen
dump(decodedData)
return decodedData
} catch {
print("Error while parsing file")
print(error.localizedDescription)
}
return nil
}
// MARK: Table View
// Table View Functions
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return foodOptions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = foodTabelView.dequeueReusableCell(withIdentifier: "customCell") as! CustomTableViewCell
cell.txtFoodName.text = foodOptions[indexPath.row].meal_name!
cell.txtFoodDescr.text = foodOptions[indexPath.row].meal_name!
cell.txtFoodPrice.text = foodOptions[indexPath.row].meal_name!
cell.txtFoodCalorie.text = foodOptions[indexPath.row].meal_name!
cell.txtFoodImage.image = UIImage(named: "\(foodOptions[indexPath.row].meal_name!).jpg")
return cell
}
}
<file_sep>/foodDelivery/View/foodTableViewController.swift
//
// foodTableViewController.swift
// foodDelivery
//
// Created by apple on 5/30/20.
// Copyright © 2020 varun. All rights reserved.
//
import UIKit
extension String {
static func random(length: Int = 6) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: String = ""
for _ in 0..<length {
let randomValue = arc4random_uniform(UInt32(base.count))
randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
}
return randomString
}
}
class foodTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
var defaults:UserDefaults!
// MARK: Outlets
@IBOutlet weak var foodTabelView: UITableView!
// MARK: Variables
var menuData:[MenuStruct] = []
var foodOptions:[FoodMenu] = []
var reward_point = 0
var reward:[String] = []
var off = 0
override func viewDidLoad() {
reward_point = 0
self.defaults = UserDefaults.standard
foodTabelView.delegate = self
foodTabelView.dataSource = self
// load the json file here
guard let file = openFile() else { return }
// load words from file into data source
menuData = self.getData(from: file)!
//Check for blank Database
let resultConts = DatabaseController.instance.foodDatabaseCheck()
// var resultCounts = DatabaseController.instance.giveDataBackTo()
if(resultConts < 5){
for i in 0 ..< menuData.count{
let message = DatabaseController.instance.saveFoodMenuToCoreData(sku: menuData[i].sku, name: menuData[i].name, desc: menuData[i].description, img: menuData[i].photo, price: menuData[i].price, caloie: menuData[i].calorie)
print("Menu Item Stored in Data : \(message)")
}
}
foodOptions = DatabaseController.instance.giveDataBackTo()
super.viewDidLoad()
}
func openDefaultFile()-> String? {
guard let file = Bundle.main.path(forResource:"MenuDetail", ofType:"json") else {
print("Cannot find file")
return nil;
}
print("File found: \(file.description)")
return file
}
func openFile() -> String? {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let finalPath = paths[0]
let filename = finalPath.appendingPathComponent("MenuDetail.json")
// check if file exists
let fileExists = FileManager().fileExists(atPath: filename.path)
if (fileExists == true) {
// load words from saved file
return filename.path;
}
else {
// open words from default file
return self.openDefaultFile()
}
return nil
}
func getData(from file:String?) -> [MenuStruct]? {
if (file == nil) {
print("File path is null")
return nil
}
do {
// open the file
let jsonData = try String(contentsOfFile: file!).data(using: .utf8)
print(jsonData) // outputs: Optional(749Bytes)
// get content of file
let decodedData =
try JSONDecoder().decode([MenuStruct].self, from: jsonData!)
// DEBUG: print file contents to screen
dump(decodedData)
return decodedData
} catch {
print("Error while parsing file")
print(error.localizedDescription)
}
return nil
}
//Get Reward FUnction
@IBAction func getRewardButtonPressed(_ sender: Any) {
let box = UIAlertController(
title: "Want Reward",
message: "To get Reward you have to shake your device three times",
preferredStyle: .alert
)
box.addAction(
UIAlertAction(title: "No", style: .default, handler: nil)
)
box.addAction(
UIAlertAction(title: "Yes", style: .default, handler: nil)
)
// show alert box
self.present(box, animated: true)
}
@IBAction func orderHistoryButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "orderHistoryController", sender: self)
}
//orderHistoryController
override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
print("Device is shaking")
// result.text = result.text + "Device is Shaking \n"
//
self.reward_point = self.reward_point + 1
var randomString = ""
if(self.reward_point == 3){
repeat{
randomString = String.random()
} while(self.reward.contains(randomString))
func randomNumber(probabilities: [Double]) -> Int {
// Sum of all probabilities (so that we don't have to require that the sum is 1.0):
let sum = probabilities.reduce(0, +)
// Random number in the range 0.0 <= rnd < sum :
let rnd = Double.random(in: 0.0 ..< sum)
// Find the first interval of accumulated probabilities into which `rnd` falls:
var accum = 0.0
for (i, p) in probabilities.enumerated() {
accum += p
if rnd < accum {
return i
}
}
// This point might be reached due to floating point inaccuracies:
return (probabilities.count - 1)
}
var message = ""
let x = randomNumber(probabilities: [0.65, 0.3, 0.05])
print("x is \(x)")
if(x == 2){
off = 10
message = "Congrats, you won 10 % off"
}
else if(x == 3){
off = 50
message = "Congrats, you won 50 % off"
}else{
off = 0
message = "Sorry you don't win reward"
}
// addCoupon
let box = UIAlertController(
title: "Coupon",
message: "\(message)",
preferredStyle: .alert
)
/* box.addAction(
UIAlertAction(title: "No", style: .default, handler:
{
action in
self.reward_point = 0
})
)*/
box.addAction(
UIAlertAction(title: "OK", style: .default, handler: {
action in
self.reward_point = 0
self.reward.append(randomString)
let username = self.defaults.string(forKey: "username")
print("Random \(randomString) \n mail \( username!) \n off \(self.off) \n ")
if(self.off > 0){
DatabaseController.instance.addCoupon(coupon: randomString, mail: username!, used: false, percentage: self.off)
}
})
)
// show alert box
self.present(box, animated: true)
}
// let color = [UIColor.white, UIColor.red, UIColor.green, UIColor.yellow, UIColor.cyan, UIColor.magenta, UIColor.purple]
// let number = Int.random(in: 0 ..< color.count)
// self.view.backgroundColor = color[number]
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
print("Device stop shaking")
// self.view.backgroundColor = UIColor.white
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return foodOptions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = foodTabelView.dequeueReusableCell(withIdentifier: "customCell") as! CustomTableViewCell
cell.txtFoodName.text = foodOptions[indexPath.row].meal_name!
cell.txtFoodDescr.text = foodOptions[indexPath.row].meal_description!
cell.txtFoodPrice.text = String(foodOptions[indexPath.row].meal_price)
cell.txtFoodCalorie.text = String(foodOptions[indexPath.row].meal_calorie)
cell.txtFoodImage.image = UIImage(named: "\(foodOptions[indexPath.row].meal_photo!).jpg")
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.defaults.set(foodOptions[indexPath.row].meal_name!, forKey: "foodName")
self.defaults.set(foodOptions[indexPath.row].meal_description!, forKey: "foodDesc")
self.defaults.set(foodOptions[indexPath.row].meal_photo!, forKey: "foodImg")
self.defaults.set(foodOptions[indexPath.row].meal_price, forKey: "foodPrice")
self.defaults.set(foodOptions[indexPath.row].meal_calorie, forKey: "foodCalorie")
self.defaults.set(foodOptions[indexPath.row].meal_sku!, forKey: "foodSku")
// self.navigationController?.pushViewController(PatientNumber_priority, animated: true)
performSegue(withIdentifier: "OrderViewController", sender: self)
}
}
<file_sep>/Customer+CoreDataProperties.swift
//
// Customer+CoreDataProperties.swift
// foodDelivery
//
// Created by apple on 5/30/20.
// Copyright © 2020 varun. All rights reserved.
//
//
import Foundation
import CoreData
extension Customer {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Customer> {
return NSFetchRequest<Customer>(entityName: "Customer")
}
@NSManaged public var customer_email: String?
@NSManaged public var customer_image: NSData?
@NSManaged public var customer_password: String?
@NSManaged public var customer_phone: String?
@NSManaged public var cutomerHasOrder: NSSet?
}
// MARK: Generated accessors for cutomerHasOrder
extension Customer {
@objc(addCutomerHasOrderObject:)
@NSManaged public func addToCutomerHasOrder(_ value: OrderData)
@objc(removeCutomerHasOrderObject:)
@NSManaged public func removeFromCutomerHasOrder(_ value: OrderData)
@objc(addCutomerHasOrder:)
@NSManaged public func addToCutomerHasOrder(_ values: NSSet)
@objc(removeCutomerHasOrder:)
@NSManaged public func removeFromCutomerHasOrder(_ values: NSSet)
}
<file_sep>/FoodMenu+CoreDataProperties.swift
//
// FoodMenu+CoreDataProperties.swift
// foodDelivery
//
// Created by apple on 5/30/20.
// Copyright © 2020 varun. All rights reserved.
//
//
import Foundation
import CoreData
extension FoodMenu {
@nonobjc public class func fetchRequest() -> NSFetchRequest<FoodMenu> {
return NSFetchRequest<FoodMenu>(entityName: "FoodMenu")
}
@NSManaged public var meal_calorie: Int16
@NSManaged public var meal_description: String?
@NSManaged public var meal_name: String?
@NSManaged public var meal_photo: String?
@NSManaged public var meal_price: Double
@NSManaged public var meal_sku: String?
@NSManaged public var orderIn: NSSet?
}
// MARK: Generated accessors for orderIn
extension FoodMenu {
@objc(addOrderInObject:)
@NSManaged public func addToOrderIn(_ value: OrderData)
@objc(removeOrderInObject:)
@NSManaged public func removeFromOrderIn(_ value: OrderData)
@objc(addOrderIn:)
@NSManaged public func addToOrderIn(_ values: NSSet)
@objc(removeOrderIn:)
@NSManaged public func removeFromOrderIn(_ values: NSSet)
}
<file_sep>/Order+CoreDataProperties.swift
//
// Order+CoreDataProperties.swift
// foodDelivery
//
// Created by apple on 5/30/20.
// Copyright © 2020 varun. All rights reserved.
//
//
import Foundation
import CoreData
extension Order {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Order> {
return NSFetchRequest<Order>(entityName: "Order")
}
@NSManaged public var subtotal: Double
@NSManaged public var total: Double
@NSManaged public var tax: Double
@NSManaged public var discount: Double
@NSManaged public var tip: Double
}
<file_sep>/foodDelivery/View/ViewController.swift
//
// ViewController.swift
// foodDelivery
//
// Created by apple on 5/29/20.
// Copyright © 2020 varun. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
@IBOutlet weak var txtEmail: UITextField!
@IBOutlet weak var txtPassword: UITextField!
var defaults:UserDefaults!
override func viewDidLoad() {
self.defaults = UserDefaults.standard
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//MARK: ACTIONS
@IBAction func signInButtonPressed(_ sender: Any) {
var message = ""
// testing
if(txtEmail.text! == "" || txtPassword.text! == ""){
message = "Please fill required information"
showAlertboax(title: "Error", message: "Please fill required information")
}else{
var customer = DatabaseController.instance.checkLogin(email: txtEmail.text!, password: txtPassword.text!)
if(customer.count != 0){
for customerData in customer{
if(customerData.customer_email == txtEmail.text! && customerData.customer_password == txtPassword.text!){
print("Customer Found On Sign iN and Good to go")
self.defaults.set(txtEmail.text!, forKey: "username")
self.defaults.set(txtPassword.text!, forKey: "<PASSWORD>")
txtEmail.text = ""
txtPassword.text = ""
performSegue(withIdentifier: "mealPackageViewController", sender: self)
}
}
}
else{
showAlertboax(title: "Error", message: "User does not exists")
print("We Dont have that customer")
}
}
}
@IBAction func createButtonPressed(_ sender: Any) {
print("Create Button Pressed")
performSegue(withIdentifier: "signUpViewController", sender: self)
}
func showAlertboax(title:String, message:String){
let box = UIAlertController(
title: "\(title)",
message: "\(message)",
preferredStyle: .alert
)
box.addAction(
UIAlertAction(title: "OK", style: .default, handler: {action in
// self.performSegue(withIdentifier: "signInPage", sender: self)
})
)
self.present(box, animated: true)
txtEmail.text = ""
txtPassword.text = ""
}
}
|
300050bc62813c5196eda94acff703c28ae2b2ae
|
[
"Swift"
] | 18
|
Swift
|
varun-king/FoodDeliveryAPP
|
0753f4c6986c526c7cd0d8ac761f3f287c47cc28
|
78ed2fe1575e041baaafd9e39ec5d95fadf18e88
|
refs/heads/master
|
<file_sep>typedef struct Skill
{
char*name;
uint8_t mark_count;
} Skill;
Skill g_skills[] = { { "Academics" }, { "Brawling" }, { "Climbing" }, { "Craft" }, { "Deceit" },
{ "Digging" }, { "Dodge" }, { "Endurance" }, { "Gossip" }, { "Inquiry" }, { "Jumping" },
{ "Leadership" }, { "Mle Combat" }, { "Negotiation" }, { "Observation" }, { "Presence" },
{ "Ranged Combat" }, { "Riding" }, { "Searching" }, { "Stealth" }, { "Supernatural" },
{ "Swimming" }, { "Tactics" }, { "Throwing" }, { "Vehicles" }, { "Weather Sense" } };
#define DIE_DENOMINATIONS(macro)\
macro(DENOMINATION_D4, ("D4"))\
macro(DENOMINATION_D6, ("D6"))\
macro(DENOMINATION_D8, ("D8"))\
macro(DENOMINATION_D10, ("D10"))\
macro(DENOMINATION_D12, ("D12"))
enum DieDenominationIndex
{
DIE_DENOMINATIONS(MAKE_ENUM)
};
char*g_die_denominations[] = { DIE_DENOMINATIONS(MAKE_VALUE) };
typedef struct Trait
{
char*name;
uint8_t dice[ARRAY_COUNT(g_unallocated_dice)];
} Trait;
#define TRAITS(macro)\
macro(TRAIT_BODY, ({ "Body" }))\
macro(TRAIT_SPEED, ({ "Speed" }))\
macro(TRAIT_MIND, ({ "Mind" }))\
macro(TRAIT_WILL, ({ "Will" }))\
macro(TRAIT_SPECIES, ({ "Species" }))\
macro(TRAIT_CAREER, ({ "Career" }))
enum TraitIndex
{
TRAITS(MAKE_ENUM)
};
Trait g_traits[] = { TRAITS(MAKE_VALUE) };
enum GiftDescriptor
{
DESCRIPTOR_INFLUENCE = 0b1,
DESCRIPTOR_MULTIPLE = 0b10
};
enum RequirementIndex
{
REQUIREMENT_TEXT_JUSTIFICATION,
REQUIREMENT_GIFT,
REQUIREMENT_NO_GIFT_WITH_DESCRIPTOR,
REQUIREMENT_TRAIT,
REQUIREMENT_CAREER_GIFTS,
REQUIREMENT_FAVORITE_USE,
REQUIREMENT_HOST_PERMISSION
};
typedef struct Requirement
{
union
{
char*justification;
uint16_t descriptor_flags;
uint8_t gift_index;
struct
{
uint8_t trait_index;
uint8_t minimum_denomination;
};
};
uint8_t requirement_type;
} Requirement;
typedef struct Gift
{
char*name;
Requirement*requirements;
uint16_t descriptor_flags;
uint8_t requirement_count;
} Gift;
#define GIFTS(macro)\
macro(GIFT_ACROBAT, ({ "Acrobat" }))\
macro(GIFT_BRAWLING_FIGHTER, ({ "Brawling Fighter" }))\
macro(GIFT_CHARGING_STRIKE, ({ "Charging Strike" }))\
macro(GIFT_CONTORTIONIST, ({ "Contortionist" }))\
macro(GIFT_COWARD, ({ "Coward" }))\
macro(GIFT_FAST_CLIMBER, ({ "Fast Climber" }))\
macro(GIFT_FAST_JUMPER, ({ "Fast Jumper" }))\
macro(GIFT_FAST_SWIMMER, ({ "Fast Swimmer" }))\
macro(GIFT_FRENZY, ({ "Frenzy" }))\
macro(GIFT_GIANT,\
({\
"Giant",\
(Requirement[])\
{\
{\
.trait_index = TRAIT_BODY,\
.minimum_denomination = DENOMINATION_D12,\
.requirement_type = REQUIREMENT_TRAIT\
}\
},\
DESCRIPTOR_INFLUENCE, 1\
}))\
macro(GIFT_HIKING, ({ "Hiking" }))\
macro(GIFT_KEEN_EARS, ({ "Keen Ears" }))\
macro(GIFT_KEEN_EYES, ({ "Keen Eyes" }))\
macro(GIFT_KEEN_NOSE, ({ "Keen Nose" }))\
macro(GIFT_LEGERDEMAIN, ({ "Legerdemain" }))\
macro(GIFT_MELEE_FINESSE, ({ "Melee Finesse" }))\
macro(GIFT_MOUNTED_FIGHTER, ({ "Mounted Fighter" }))\
macro(GIFT_NIGHT_VISION, ({ "Night Vision" }))\
macro(GIFT_PACIFIST, ({ "Pacifist" }))\
macro(GIFT_PARKOUR,\
({\
"Parkour",\
(Requirement[])\
{\
{\
.gift_index = GIFT_FAST_CLIMBER,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_SPRINGING_STRIKE, ({ "Springing Strike" }))\
macro(GIFT_SURE_FOOTED, ({ "Sure-Footed" }))\
macro(GIFT_ANIMAL_HANDLING, ({ "Animal Handling" }))\
macro(GIFT_ARTIST, ({ "Artist" }))\
macro(GIFT_CLEAR_HEADED, ({ "Clear-Headed" }))\
macro(GIFT_CRAFT_SPECIALTY, ({ "Craft Specialty" }))\
macro(GIFT_DEAD_RECKONING, ({ "Dead Reckoning" }))\
macro(GIFT_EXTRA_FAVORITE, ({ "Extra Favorite" }))\
macro(GIFT_FIRST_AID, ({ "First Aid" }))\
macro(GIFT_GAMBLING, ({ "Gambling" }))\
macro(GIFT_GEOGRAPHY, ({ "Geography" }))\
macro(GIFT_HERALDRY, ({ "Heraldry" }))\
macro(GIFT_HISTORY, ({ "History" }))\
macro(GIFT_JUNK_EXPERT, ({ "Junk Expert" }))\
macro(GIFT_LANGUAGE, ({ "Language" }))\
macro(GIFT_MEDICINE, ({ "Medicine" }))\
macro(GIFT_MELEE_FERVOR, ({ "Melee Fervor" }))\
macro(GIFT_MELEE_GUILE, ({ "Melee Guile" }))\
macro(GIFT_MYSTIC, ({ "Mystic" }))\
macro(GIFT_OVERCONFIDENCE, ({ "Overconfidence" }))\
macro(GIFT_PACK_TACTICS, ({ "Pack Tactics" }))\
macro(GIFT_PIETY, ({ "Piety" }))\
macro(GIFT_SAILING, ({ "Sailing" }))\
macro(GIFT_SPELUNKING, ({ "Spelunking" }))\
macro(GIFT_TEAMSTER, ({ "Teamster" }))\
macro(GIFT_TRACKING, ({ "Tracking" }))\
macro(GIFT_UNSHAKEABLE_FIGHTER, ({ "Unshakeable Fighter" }))\
macro(GIFT_VENGEFUL_FIGHTER, ({ "Vengeful Fighter" }))\
macro(GIFT_BRIBERY, ({ "Bribery" }))\
macro(GIFT_CAROUSING, ({ "Carousing" }))\
macro(GIFT_COSMOPOLITAN, ({ "Cosmopolitan" }))\
macro(GIFT_DIPLOMACY, ({ "Diplomacy" }))\
macro(GIFT_DISGUISE, ({ "Disguise" }))\
macro(GIFT_ETIQUETTE, ({ "Etiquette" }))\
macro(GIFT_FAST_TALK, ({ "Fast-Talk" }))\
macro(GIFT_HAGGLING, ({ "Haggling" }))\
macro(GIFT_HONOR, ({ "Honor" }))\
macro(GIFT_INSIDER, ({ "Insider" }))\
macro(GIFT_LAW, ({ "Law" }))\
macro(GIFT_LEGAL_AUTHORITY,\
({\
"Legal Authority",\
(Requirement[])\
{\
{\
.justification = "Authorization from a recognized legal authority.",\
.requirement_type = REQUIREMENT_TEXT_JUSTIFICATION\
}\
},\
DESCRIPTOR_INFLUENCE, 1\
}))\
macro(GIFT_LOCAL_KNOWLEDGE, ({ "Local Knowledge" }))\
macro(GIFT_LOW_PROFILE, ({ "Low Profile" }))\
macro(GIFT_NOBILITY,\
({\
"Nobility",\
(Requirement[])\
{\
{\
.justification = "A noble bloodline or parent of nobility, traceable to a Great House or Minor House.",\
.requirement_type = REQUIREMENT_TEXT_JUSTIFICATION\
}\
},\
DESCRIPTOR_INFLUENCE | DESCRIPTOR_MULTIPLE, 1\
}))\
macro(GIFT_ORATORY, ({ "Oratory" }))\
macro(GIFT_ORDAINMENT,\
({\
"Ordainment",\
(Requirement[])\
{\
{\
.justification = "An endorsement from a religious organization.",\
.requirement_type = REQUIREMENT_TEXT_JUSTIFICATION\
}\
},\
DESCRIPTOR_INFLUENCE | DESCRIPTOR_MULTIPLE, 1\
}))\
macro(GIFT_PERFORMANCE, ({ "Performance" }))\
macro(GIFT_SEDUCTION, ({ "Seduction" }))\
macro(GIFT_SHADOWING, ({ "Shadowing" }))\
macro(GIFT_SURVIVAL, ({ "Survival" }))\
macro(GIFT_TEAM_PLAYER, ({ "Team Player" }))\
macro(GIFT_WEALTH,\
({\
"Wealth",\
(Requirement[])\
{\
{\
.justification = "An appropriate background and career.",\
.requirement_type = REQUIREMENT_TEXT_JUSTIFICATION\
}\
},\
DESCRIPTOR_INFLUENCE | DESCRIPTOR_MULTIPLE, 1\
}))\
macro(GIFT_ARCHERS_TRAPPINGS, ({ "Archer's Trappings" }))\
macro(GIFT_CLERICS_TRAPPINGS, ({ "Cleric's Trappings" }))\
macro(GIFT_COGNOSCENTES_TRAPPINGS, ({ "Cognoscente's Trappings" }))\
macro(GIFT_DILETTANTES_TRAPPINGS, ({ "Dilettante's Trappings" }))\
macro(GIFT_ELEMENTALISTS_TRAPPINGS, ({ "Elementalist's Trappings" }))\
macro(GIFT_FUSILEERS_TRAPPINGS, ({ "Fusileer's Trappings" }))\
macro(GIFT_KNIGHTS_TRAPPINGS, ({ "Knight's Trappings" }))\
macro(GIFT_MUSKETEERS_TRAPPINGS, ({ "Musketeer's Trappings" }))\
macro(GIFT_RIDERS_TRAPPINGS, ({ "Rider's Trappings" }))\
macro(GIFT_SCHOLARS_TRAPPINGS, ({ "Scholar's Trappings" }))\
macro(GIFT_SIGNATURE_ITEM, ({ "Signature Item" }))\
macro(GIFT_SPYS_TRAPPINGS, ({ "Spy's Trappings" }))\
macro(GIFT_THAUMATURGES_TRAPPINGS, ({ "Thaumaturge's Trappings" }))\
macro(GIFT_COMBAT_EDGE, ({ "Combat Edge" }))\
macro(GIFT_COMBAT_SAVE, ({ "Combat Save" }))\
macro(GIFT_DIEHARD,\
({\
"Diehard",\
(Requirement[])\
{\
{\
.gift_index = GIFT_TOUGHNESS,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_DISARMING_SAVE,\
({\
"Disarming Save",\
(Requirement[])\
{\
{\
.trait_index = TRAIT_BODY,\
.minimum_denomination = DENOMINATION_D8,\
.requirement_type = REQUIREMENT_TRAIT\
}\
},\
0, 1\
}))\
macro(GIFT_DRAMATIC_DISHEVELING,\
({\
"Dramatic Disheveling",\
(Requirement[])\
{\
{\
.trait_index = TRAIT_WILL,\
.minimum_denomination = DENOMINATION_D8,\
.requirement_type = REQUIREMENT_TRAIT\
}\
},\
0, 1\
}))\
macro(GIFT_MAGIC_SAVE,\
({\
"Magic Save",\
(Requirement[])\
{\
{\
.gift_index = GIFT_MYSTIC,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_REPLAY_FOR_DESTINY,\
({\
"Replay for Destiny",\
(Requirement[])\
{\
{\
.trait_index = TRAIT_BODY,\
.minimum_denomination = DENOMINATION_D8,\
},\
{\
.trait_index = TRAIT_SPEED,\
.minimum_denomination = DENOMINATION_D8,\
},\
{\
.trait_index = TRAIT_MIND,\
.minimum_denomination = DENOMINATION_D8,\
},\
{\
.trait_index = TRAIT_WILL,\
.minimum_denomination = DENOMINATION_D8,\
}\
},\
0, 4\
}))\
macro(GIFT_RETREATING_SAVE,\
({\
"Retreating Save",\
(Requirement[])\
{\
{\
.trait_index = TRAIT_SPEED,\
.minimum_denomination = DENOMINATION_D8,\
}\
},\
0, 1\
}))\
macro(GIFT_SHIELD_SAVE,\
({\
"Shield Save",\
(Requirement[])\
{\
{\
.gift_index = GIFT_RESOLVE,\
.requirement_type = REQUIREMENT_GIFT\
},\
{\
.gift_index = GIFT_VETERAN,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 2\
}))\
macro(GIFT_TOUGHNESS, ({ "Toughness", 0, DESCRIPTOR_MULTIPLE }))\
macro(GIFT_EXTRA_CAREER,\
({\
"Extra Career",\
(Requirement[])\
{\
{\
.requirement_type = REQUIREMENT_CAREER_GIFTS\
}\
},\
0, 1\
}))\
macro(GIFT_FAVOR_BONUS,\
({\
"Favor Bonus",\
(Requirement[])\
{\
{\
.requirement_type = REQUIREMENT_FAVORITE_USE\
}\
},\
0, 1\
}))\
macro(GIFT_INCREASED_TRAIT, ({ "Increased Trait", 0, DESCRIPTOR_MULTIPLE }))\
macro(GIFT_KNACK, ({ "Knack" }))\
macro(GIFT_LUCK, ({ "Luck", 0, DESCRIPTOR_MULTIPLE }))\
macro(GIFT_PERSONALITY, ({ "Personality" }))\
macro(GIFT_DEEP_DIVING, ({ "Deep Diving" }))\
macro(GIFT_ECHOLOCATION, ({ "Echolocation" }))\
macro(GIFT_FLIGHT, ({ "Flight" }))\
macro(GIFT_HOWLING, ({ "Howling" }))\
macro(GIFT_NATURAL_ARMOR, ({ "Natural Armor" }))\
macro(GIFT_PREHENSILE_FEET, ({ "Prehensile Feet" }))\
macro(GIFT_PREHENSILE_TAIL, ({ "Prehensile Tail" }))\
macro(GIFT_QUILLS, ({ "Quills" }))\
macro(GIFT_SPRAY, ({ "Spray" }))\
macro(GIFT_VENEMOUS_BITE, ({ "Venemous Bite" }))\
macro(GIFT_ALLY, ({ "Ally" }))\
macro(GIFT_GANG_OF_IRREGULARS,\
({\
"Gang of Irregulars",\
(Requirement[])\
{\
{\
.gift_index = GIFT_ALLY,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_IMPROVED_ALLY,\
({\
"Improved Ally",\
(Requirement[])\
{\
{\
.gift_index = GIFT_ALLY,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
DESCRIPTOR_MULTIPLE, 1\
}))\
macro(GIFT_AMBIDEXTERITY, ({ "Ambidexterity" }))\
macro(GIFT_AKIMBO_FIGHTER,\
({\
"Akimbo Fighter",\
(Requirement[])\
{\
{\
.gift_index = GIFT_AMBIDEXTERITY,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_TANDEM_REPLAY,\
({\
"Tandem Replay",\
(Requirement[])\
{\
{\
.gift_index = GIFT_AMBIDEXTERITY,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_TANDEM_STRIKE,\
({\
"Tandem Strike",\
(Requirement[])\
{\
{\
.gift_index = GIFT_AMBIDEXTERITY,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_COUNTER_TACTICS, ({ "Counter-Tactics" }))\
macro(GIFT_ALL_OUT_ATTACK,\
({\
"All-Out Attack",\
(Requirement[])\
{\
{\
.gift_index = GIFT_COUNTER_TACTICS,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_GUARD_BREAKER,\
({\
"Guard Breaker",\
(Requirement[])\
{\
{\
.gift_index = GIFT_COUNTER_TACTICS,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_KNOCKDOWN_STRIKE,\
({\
"Knockdown Strike",\
(Requirement[])\
{\
{\
.gift_index = GIFT_COUNTER_TACTICS,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_MOB_FIGHTER,\
({\
"Mob Fighter",\
(Requirement[])\
{\
{\
.gift_index = GIFT_COUNTER_TACTICS,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_THREATENING_FIGHTER,\
({\
"Threatening Fighter",\
(Requirement[])\
{\
{\
.gift_index = GIFT_COUNTER_TACTICS,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_DANGER_SENSE, ({ "Danger Sense" }))\
macro(GIFT_BODYGUARD,\
({\
"Bodyguard",\
(Requirement[])\
{\
{\
.gift_index = GIFT_DANGER_SENSE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_BLIND_FIGHTING,\
({\
"Blind-Fighting",\
(Requirement[])\
{\
{\
.gift_index = GIFT_DANGER_SENSE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_PRUDENCE,\
({\
"Prudence",\
(Requirement[])\
{\
{\
.gift_index = GIFT_DANGER_SENSE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_SIXTH_SENSE,\
({\
"Sixth Sense",\
(Requirement[])\
{\
{\
.gift_index = GIFT_DANGER_SENSE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_STITCH_IN_TIME,\
({\
"Stitch in Time",\
(Requirement[])\
{\
{\
.gift_index = GIFT_DANGER_SENSE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_FAST_MOVER, ({ "Fast Mover" }))\
macro(GIFT_ARTFUL_DODGER,\
({\
"Artful Dodger",\
(Requirement[])\
{\
{\
.gift_index = GIFT_FAST_MOVER,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_MAD_SPRINT,\
({\
"Mad Sprint",\
(Requirement[])\
{\
{\
.gift_index = GIFT_FAST_MOVER,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_RAPID_DASH,\
({\
"Rapid Dash",\
(Requirement[])\
{\
{\
.gift_index = GIFT_FAST_MOVER,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_RAPID_SPRINT,\
({\
"Rapid Sprint",\
(Requirement[])\
{\
{\
.gift_index = GIFT_FAST_MOVER,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_FENCING, ({ "Fencing" }))\
macro(GIFT_DISARMING_STRIKE,\
({\
"Disarming Strike",\
(Requirement[])\
{\
{\
.gift_index = GIFT_FENCING,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_FENCING_REPLAY,\
({\
"Fencing Replay",\
(Requirement[])\
{\
{\
.gift_index = GIFT_FENCING,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_RAPIER_LUNGE,\
({\
"Rapier Lunge",\
(Requirement[])\
{\
{\
.gift_index = GIFT_FENCING,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_LITERACY, ({ "Literacy" }))\
macro(GIFT_ADMINISTRATION,\
({\
"Administration",\
(Requirement[])\
{\
{\
.gift_index = GIFT_LITERACY,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_ASTROLOGY,\
({\
"Astrology",\
(Requirement[])\
{\
{\
.gift_index = GIFT_LITERACY,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_CARTOGRAPHY,\
({\
"Cartography",\
(Requirement[])\
{\
{\
.gift_index = GIFT_LITERACY,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_DOCTOR,\
({\
"Doctor",\
(Requirement[])\
{\
{\
.gift_index = GIFT_LITERACY,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_MATHEMATICS,\
({\
"Mathematics",\
(Requirement[])\
{\
{\
.gift_index = GIFT_LITERACY,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_RESEARCH,\
({\
"Research",\
(Requirement[])\
{\
{\
.gift_index = GIFT_LITERACY,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_TRADEWINDS_NAVIGATION,\
({\
"Tradewinds Navigation",\
(Requirement[])\
{\
{\
.gift_index = GIFT_LITERACY,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_QUICK_DRAW, ({ "Quick Draw" }))\
macro(GIFT_QUICK_SHEATHE,\
({\
"Quick Sheathe",\
(Requirement[])\
{\
{\
.gift_index = GIFT_QUICK_DRAW,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_SECOND_THROW,\
({\
"Second Throw",\
(Requirement[])\
{\
{\
.gift_index = GIFT_QUICK_DRAW,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_SUDDEN_DRAW,\
({\
"Sudden Draw",\
(Requirement[])\
{\
{\
.gift_index = GIFT_QUICK_DRAW,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_RESOLVE, ({ "Resolve" }))\
macro(GIFT_ARMORED_FIGHTER,\
({\
"Armored Fighter",\
(Requirement[])\
{\
{\
.gift_index = GIFT_RESOLVE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_GUARD_SOAK,\
({\
"Guard Soak",\
(Requirement[])\
{\
{\
.gift_index = GIFT_RESOLVE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_RELENTLESSNESS,\
({\
"Relentlessness",\
(Requirement[])\
{\
{\
.gift_index = GIFT_RESOLVE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_SCARY_FIGHTER,\
({\
"Scary Fighter",\
(Requirement[])\
{\
{\
.gift_index = GIFT_RESOLVE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_SHIELD_SOAK,\
({\
"Shield Soak",\
(Requirement[])\
{\
{\
.gift_index = GIFT_RESOLVE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_SHARPSHOOTER, ({ "Sharpshooter" }))\
macro(GIFT_AIMING_ON_THE_DRAW,\
({\
"Aiming on the Draw",\
(Requirement[])\
{\
{\
.gift_index = GIFT_SHARPSHOOTER,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_COUNTER_SHOT,\
({\
"Counter Shot",\
(Requirement[])\
{\
{\
.gift_index = GIFT_SHARPSHOOTER,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_INSTINCTIVE_SHOT,\
({\
"Instinctive Shot",\
(Requirement[])\
{\
{\
.gift_index = GIFT_SHARPSHOOTER,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_SNIPERS_SHOT,\
({\
"Sniper's Shot",\
(Requirement[])\
{\
{\
.gift_index = GIFT_SHARPSHOOTER,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_STREETWISE, ({ "Streetwise" }))\
macro(GIFT_FORGERY,\
({\
"Forgery",\
(Requirement[])\
{\
{\
.gift_index = GIFT_STREETWISE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
DESCRIPTOR_MULTIPLE, 1\
}))\
macro(GIFT_SABOTAGE,\
({\
"Sabotage",\
(Requirement[])\
{\
{\
.gift_index = GIFT_STREETWISE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_SNEAKY_FIGHTER,\
({\
"Sneaky Fighter",\
(Requirement[])\
{\
{\
.gift_index = GIFT_STREETWISE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_SKULKING,\
({\
"Skulking",\
(Requirement[])\
{\
{\
.gift_index = GIFT_STREETWISE,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_STRENGTH, ({ "Strength" }))\
macro(GIFT_IMPROVED_STRENGTH,\
({\
"Improved Strength",\
(Requirement[])\
{\
{\
.gift_index = GIFT_STRENGTH,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_INDOMITABLE_FIGHTER,\
({\
"Indomitable Fighter",\
(Requirement[])\
{\
{\
.gift_index = GIFT_STRENGTH,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_LINE_BREAKER,\
({\
"Line Breaker",\
(Requirement[])\
{\
{\
.gift_index = GIFT_STRENGTH,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_MIGHTY_GRIP,\
({\
"Mighty Grip",\
(Requirement[])\
{\
{\
.gift_index = GIFT_STRENGTH,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_MIGHTY_STRIKE,\
({\
"Mighty Strike",\
(Requirement[])\
{\
{\
.gift_index = GIFT_STRENGTH,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_TRUE_LEADER, ({ "True Leader" }))\
macro(GIFT_COMMANDING_LEADER,\
({\
"Commanding Leader",\
(Requirement[])\
{\
{\
.gift_index = GIFT_TRUE_LEADER,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_MILITIA_LEADER,\
({\
"Militia Leader",\
(Requirement[])\
{\
{\
.gift_index = GIFT_TRUE_LEADER,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_TROOP_LEADER,\
({\
"Troop Leader",\
(Requirement[])\
{\
{\
.gift_index = GIFT_TRUE_LEADER,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_WATCHFUL_LEADER,\
({\
"Watchful Leader",\
(Requirement[])\
{\
{\
.gift_index = GIFT_TRUE_LEADER,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_VETERAN, ({ "Veteran" }))\
macro(GIFT_BRAVERY,\
({\
"Bravery",\
(Requirement[])\
{\
{\
.gift_index = GIFT_VETERAN,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_FOCUSED_FIGHTER,\
({\
"Focused Fighter",\
(Requirement[])\
{\
{\
.gift_index = GIFT_VETERAN,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_KNOCKOUT_STRIKE,\
({\
"Knockout Strike",\
(Requirement[])\
{\
{\
.gift_index = GIFT_VETERAN,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_RAPID_AIM,\
({\
"Rapid Aim",\
(Requirement[])\
{\
{\
.gift_index = GIFT_VETERAN,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_RAPID_GUARD,\
({\
"Rapid Guard",\
(Requirement[])\
{\
{\
.gift_index = GIFT_VETERAN,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_SHIELD_FIGHTER,\
({\
"Shield Fighter",\
(Requirement[])\
{\
{\
.gift_index = GIFT_VETERAN,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 1\
}))\
macro(GIFT_ANONYMOUS,\
({\
"Anonymous",\
(Requirement[])\
{\
{\
.descriptor_flags = DESCRIPTOR_INFLUENCE,\
.requirement_type = REQUIREMENT_NO_GIFT_WITH_DESCRIPTOR\
},\
{\
.requirement_type = REQUIREMENT_HOST_PERMISSION\
}\
},\
0, 2\
}))\
macro(GIFT_ELEMENTAL_APPRENTICE,\
({\
"Elemental Apprentice",\
(Requirement[])\
{\
{\
.gift_index = GIFT_LITERACY,\
.requirement_type = REQUIREMENT_GIFT\
},\
{\
.gift_index = GIFT_ELEMENTALISTS_TRAPPINGS,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 2\
}))\
macro(GIFT_GREEN_AND_PURPLE_MAGIC_APPRENTICE,\
({\
"Green & Purple Magic Apprentice",\
(Requirement[])\
{\
{\
.gift_index = GIFT_LITERACY, \
.requirement_type = REQUIREMENT_GIFT\
},\
{\
.gift_index = GIFT_COGNOSCENTES_TRAPPINGS, \
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 2\
}))\
macro(GIFT_THAUMATURGY_APPRENTICE,\
({\
"Thaumaturgy Apprentice",\
(Requirement[])\
{\
{\
.gift_index = GIFT_LITERACY,\
.requirement_type = REQUIREMENT_GIFT\
},\
{\
.gift_index = GIFT_THAUMATURGES_TRAPPINGS,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 2\
}))\
macro(GIFT_WHITE_MAGIC_APPRENTICE,\
({ "White Magic Apprentice",\
(Requirement[])\
{\
{\
.gift_index = GIFT_LITERACY,\
.requirement_type = REQUIREMENT_GIFT\
},\
{\
.gift_index = GIFT_CLERICS_TRAPPINGS,\
.requirement_type = REQUIREMENT_GIFT\
}\
},\
0, 2\
}))
enum GiftIndex
{
GIFTS(MAKE_ENUM)
};
Gift g_gifts[] = { GIFTS(MAKE_VALUE) };<file_sep>#include "ironclaw.c"
#define TABS(macro)\
macro(TAB_ALLOCATE_DICE, ("Allocate Trait Dice"))\
macro(TAB_ALLOCATE_MARKS, ("Allocate Marks"))\
macro(TAB_CHOOSE_GIFTS, ("Choose Gifts"))
enum TabIndex
{
TABS(MAKE_ENUM)
};
char*g_tab_names[] = { TABS(MAKE_VALUE) };
enum WindowControlID
{
SKILL_TABLE_SCROLL_ID = 1,
ALLOCATE_BUTTON_ID,
DEALLOCATE_BUTTON_ID,
TAB_0_ID,
WINDOW_VERTCAL_SCROLL_ID = TAB_0_ID + ARRAY_COUNT(g_tab_names),
WINDOW_HORIZONTAL_SCROLL_ID,
SKILL_TABLE_ROW_0_ID,
MAX_WINDOW_CONTROL_ID
};
ScrollBar g_window_horizontal_scroll;
ScrollBar g_vertical_scrolls[3];
#define WINDOW_VERTICAL_SCROLL g_vertical_scrolls[0]
#define SKILL_TABLE_SCROLL g_vertical_scrolls[1]
#define GIFT_LIST_SCROLL g_vertical_scrolls[2]
Grid g_skill_table;
Grid g_skill_table_dice_header;
int32_t g_skill_table_column_min_x_values[3 + ARRAY_COUNT(g_die_denominations)];
int32_t g_skill_table_frame_min_y;
uint32_t g_skill_column_width;
uint32_t g_die_column_width;
int32_t g_allocate_button_min_x;
int32_t g_allocate_button_min_y;
Rasterization*g_allocate_button_arrow;
int32_t g_deallocate_button_min_x;
int32_t g_deallocate_button_min_y;
Rasterization*g_deallocate_button_arrow;
int32_t g_tab_min_x;
uint32_t g_tab_width;
size_t g_selected_tab_index = 0;
typedef union TabLayout
{
Grid unallocated_dice_table;
struct
{
int32_t unallocated_marks_display_min_x;
int32_t unallocated_marks_display_min_y;
uint32_t unallocated_marks_display_width;
};
struct
{
Grid species_gifts;
Grid gift_list;
int32_t gift_list_frame_min_y;
int32_t species_gift_column_min_x_values[2];
int32_t gift_list_column_min_x_values[2];
};
} TabLayout;
TabLayout g_layout;
enum AllocateTraitDiceTabID
{
UNALLOCATED_DICE_TABLE_COLUMN_0_ID = SKILL_TABLE_ROW_0_ID,
TRAIT_TABLE_ROW_0_ID = UNALLOCATED_DICE_TABLE_COLUMN_0_ID + ARRAY_COUNT(g_unallocated_dice)
};
int32_t g_trait_table_column_min_x_values[2 + ARRAY_COUNT(g_unallocated_dice)];
Grid g_trait_table;
size_t g_selected_die_denomination_index = ARRAY_COUNT(g_unallocated_dice);
size_t g_selected_trait_index = ARRAY_COUNT(g_traits);
uint32_t g_trait_column_width;
#define UNALLOCATED_MARKS_ID MAX_WINDOW_CONTROL_ID
size_t g_selected_skill_index = ARRAY_COUNT(g_skills);
uint8_t g_unallocated_marks = 13;
enum ChooseGiftsTabID
{
GIFT_LIST_SCROLL_ID = MAX_WINDOW_CONTROL_ID,
GIFT_LIST_ROW_0_ID
};
#define GIFT_LIST_ROW_0_ID MAX_WINDOW_CONTROL_ID
uint8_t g_free_gifts_chosen_count;
uint8_t g_free_gift_indices[3];
uint32_t g_gift_list_width;
size_t g_selected_gift_index = ARRAY_COUNT(g_gifts);
void scale_graphics_to_dpi(void*font_data, size_t font_data_size, uint16_t dpi)
{
FT_New_Memory_Face(g_freetype_library, font_data, font_data_size, 0, &g_face);
FT_Set_Char_Size(g_face, 0, g_message_font_height, 0, dpi);
for (FT_ULong codepoint = FIRST_RASTERIZED_GLYPH; codepoint <= LAST_RASTERIZED_GLYPH;
++codepoint)
{
rasterize_glyph(codepoint, get_rasterization(codepoint));
}
rasterize_glyph(0x25b2, &g_up_arrowhead_rasterization);
rasterize_glyph(0x25ba, &g_right_arrowhead_rasterization);
rasterize_glyph(0x25bc, &g_down_arrowhead_rasterization);
rasterize_glyph(0x25c4, &g_left_arrowhead_rasterization);
g_line_thickness = get_rasterization('|')->bitmap.width;
g_table_row_height =
round26_6to_pixel(g_face->size->metrics.ascender - 2 * g_face->size->metrics.descender);
g_text_padding = (g_table_row_height - get_rasterization('M')->bitmap.rows) / 2;
g_table_row_height += g_line_thickness;
WINDOW_VERTICAL_SCROLL.viewport_extent_along_thickness.min = g_table_row_height;
SKILL_TABLE_SCROLL.content_length =
g_table_row_height * ARRAY_COUNT(g_skills) - g_line_thickness;
g_skill_column_width = get_string_width("Skills");
for (size_t i = 0; i < ARRAY_COUNT(g_skills); ++i)
{
g_skill_column_width = max32(g_skill_column_width, get_string_width(g_skills[i].name));
}
g_skill_column_width += g_line_thickness + 2 * g_text_padding;
g_die_column_width = g_line_thickness + get_string_width("D12") + 2 * g_text_padding;
g_trait_column_width = get_string_width("Traits");
for (size_t i = 0; i < ARRAY_COUNT(g_traits); ++i)
{
g_trait_column_width = max32(g_trait_column_width, get_string_width(g_traits[i].name));
}
g_trait_column_width += g_line_thickness + 2 * g_text_padding;
GIFT_LIST_SCROLL.content_length = g_table_row_height * ARRAY_COUNT(g_gifts) - g_line_thickness;
g_gift_list_width = 0;
for (size_t i = 0; i < ARRAY_COUNT(g_gifts); ++i)
{
g_gift_list_width = max32(g_gift_list_width, get_string_width(g_gifts[i].name));
}
g_gift_list_width += g_line_thickness + 2 * g_text_padding;
g_tab_width = 0;
for (size_t i = 0; i < ARRAY_COUNT(g_tab_names); ++i)
{
g_tab_width = max32(g_tab_width, get_string_width(g_tab_names[i]));
}
g_tab_width += g_line_thickness + 2 * g_text_padding;
}
void reset_widget_x_positions(void)
{
uint32_t cell_height = g_table_row_height - g_line_thickness;
switch (g_selected_tab_index)
{
case TAB_ALLOCATE_DICE:
{
g_trait_table.column_min_x_values[0] =
cell_height - g_window_horizontal_scroll.content_offset;
if (WINDOW_VERTICAL_SCROLL.is_active)
{
g_trait_table.column_min_x_values[0] += cell_height;
}
g_trait_table.column_min_x_values[1] =
g_trait_table.column_min_x_values[0] + g_trait_column_width;
for (size_t i = 2; i <= g_trait_table.column_count; ++i)
{
g_trait_table.column_min_x_values[i] =
g_trait_table.column_min_x_values[i - 1] + g_die_column_width;
}
g_deallocate_button_min_x = g_layout.unallocated_dice_table.column_min_x_values[0] +
(get_grid_width(&g_layout.unallocated_dice_table) + g_line_thickness) / 2;
g_allocate_button_min_x = g_deallocate_button_min_x - g_table_row_height;
g_skill_table.column_min_x_values[0] =
get_rightmost_column_x(&g_trait_table) + g_table_row_height;
break;
}
case TAB_ALLOCATE_MARKS:
{
g_layout.unallocated_marks_display_min_x =
cell_height - g_window_horizontal_scroll.content_offset;
if (WINDOW_VERTICAL_SCROLL.is_active)
{
g_layout.unallocated_marks_display_min_x += cell_height;
}
g_allocate_button_min_x = g_layout.unallocated_marks_display_min_x +
g_layout.unallocated_marks_display_width + g_table_row_height;
g_deallocate_button_min_x = g_allocate_button_min_x;
g_skill_table.column_min_x_values[0] = g_allocate_button_min_x + 2 * g_table_row_height;
break;
}
case TAB_CHOOSE_GIFTS:
{
g_layout.species_gifts.column_min_x_values[0] =
cell_height - g_window_horizontal_scroll.content_offset;
if (WINDOW_VERTICAL_SCROLL.is_active)
{
g_layout.species_gifts.column_min_x_values[0] += cell_height;
}
g_layout.species_gifts.column_min_x_values[1] =
g_layout.species_gifts.column_min_x_values[0] + g_gift_list_width;
g_allocate_button_min_x =
g_layout.species_gifts.column_min_x_values[1] + g_table_row_height;
g_deallocate_button_min_x = g_allocate_button_min_x;
g_layout.gift_list_column_min_x_values[0] =
g_deallocate_button_min_x + 2 * g_table_row_height;
if (GIFT_LIST_SCROLL.is_active)
{
GIFT_LIST_SCROLL.min_along_thickness = g_layout.gift_list_column_min_x_values[0];
g_layout.gift_list_column_min_x_values[0] += cell_height;
}
GIFT_LIST_SCROLL.viewport_extent_along_thickness.min =
g_layout.gift_list_column_min_x_values[0] + g_line_thickness;
g_layout.gift_list_column_min_x_values[1] =
g_layout.gift_list_column_min_x_values[0] + g_gift_list_width;
g_skill_table.column_min_x_values[0] =
g_layout.gift_list_column_min_x_values[1] + g_table_row_height;
}
}
if (SKILL_TABLE_SCROLL.is_active)
{
SKILL_TABLE_SCROLL.min_along_thickness = g_skill_table.column_min_x_values[0];
g_skill_table.column_min_x_values[0] += cell_height;
}
g_skill_table.column_min_x_values[1] =
g_skill_table.column_min_x_values[0] + g_skill_column_width;
g_skill_table.column_min_x_values[2] = g_skill_table.column_min_x_values[1] +
g_line_thickness + get_string_width("Marks") + 2 * g_text_padding;
for (size_t i = 2; i < g_skill_table.column_count; ++i)
{
g_skill_table.column_min_x_values[i + 1] =
g_skill_table.column_min_x_values[i] + g_die_column_width;
}
SKILL_TABLE_SCROLL.viewport_extent_along_thickness.min =
g_skill_table.column_min_x_values[0] + g_line_thickness;
if (g_window_horizontal_scroll.is_active)
{
g_tab_min_x = get_rightmost_column_x(&g_skill_table) + g_table_row_height;
}
else
{
g_tab_min_x = g_window_x_extent.length - (g_tab_width + g_line_thickness);
}
}
void reset_widget_y_positions(void)
{
uint32_t cell_height = g_table_row_height - g_line_thickness;
g_skill_table_dice_header.min_y = cell_height - WINDOW_VERTICAL_SCROLL.content_offset;
g_skill_table_frame_min_y = g_skill_table_dice_header.min_y + g_table_row_height;
if (SKILL_TABLE_SCROLL.is_active)
{
SKILL_TABLE_SCROLL.min_along_length = g_skill_table_frame_min_y;
}
SKILL_TABLE_SCROLL.viewport_extent_along_length.min =
g_skill_table_frame_min_y + g_line_thickness;
g_skill_table.min_y = g_skill_table_frame_min_y - SKILL_TABLE_SCROLL.content_offset;
switch (g_selected_tab_index)
{
case TAB_ALLOCATE_DICE:
{
g_layout.unallocated_dice_table.min_y = g_skill_table_frame_min_y;
g_allocate_button_min_y = g_skill_table_frame_min_y + 3 * g_table_row_height;
g_deallocate_button_min_y = g_allocate_button_min_y;
g_trait_table.min_y = g_allocate_button_min_y + 3 * g_table_row_height;
break;
}
case TAB_ALLOCATE_MARKS:
{
g_allocate_button_min_y = g_skill_table_frame_min_y;
g_deallocate_button_min_y = g_allocate_button_min_y + g_table_row_height;
g_layout.unallocated_marks_display_min_y = g_deallocate_button_min_y;
break;
}
case TAB_CHOOSE_GIFTS:
{
g_allocate_button_min_y =
g_skill_table_dice_header.min_y + 8 * g_table_row_height + g_table_row_height / 2;
g_deallocate_button_min_y = g_allocate_button_min_y + g_table_row_height;
g_layout.species_gifts.min_y = g_skill_table_dice_header.min_y;
g_layout.gift_list_frame_min_y = g_skill_table_dice_header.min_y;
g_layout.gift_list.min_y = g_layout.gift_list_frame_min_y - GIFT_LIST_SCROLL.content_offset;
GIFT_LIST_SCROLL.min_along_length = g_layout.gift_list_frame_min_y;
GIFT_LIST_SCROLL.viewport_extent_along_length.min =
GIFT_LIST_SCROLL.min_along_length + g_line_thickness;
}
}
}
void reset_widget_positions(void)
{
reset_widget_x_positions();
reset_widget_y_positions();
}
void reformat_widgets_on_window_resize()
{
uint32_t cell_height = g_table_row_height - g_line_thickness;
size_t vertical_scroll_count;
uint32_t window_scroll_viewport_heights_at_which_vertical_scrolls_activate
[ARRAY_COUNT(g_vertical_scrolls)];
size_t scroll_activation_order[ARRAY_COUNT(g_vertical_scrolls)];
int32_t unscrolled_skill_table_frame_min_y = cell_height + g_table_row_height;
window_scroll_viewport_heights_at_which_vertical_scrolls_activate[1] =
unscrolled_skill_table_frame_min_y + (1 + g_skill_table.row_count) * g_table_row_height;
switch (g_selected_tab_index)
{
case TAB_ALLOCATE_DICE:
{
vertical_scroll_count = 2;
g_window_horizontal_scroll.content_length = get_grid_width(&g_trait_table) +
get_grid_width(&g_skill_table) + 3 * g_table_row_height + g_tab_width;
scroll_activation_order[0] = 1;
scroll_activation_order[1] = 0;
WINDOW_VERTICAL_SCROLL.content_length =
cell_height + (g_trait_table.row_count + 8) * g_table_row_height;
break;
}
case TAB_ALLOCATE_MARKS:
{
vertical_scroll_count = 2;
g_window_horizontal_scroll.content_length = g_layout.unallocated_marks_display_width +
5 * g_table_row_height + get_grid_width(&g_skill_table) + g_tab_width;
scroll_activation_order[0] = 1;
scroll_activation_order[1] = 0;
WINDOW_VERTICAL_SCROLL.content_length = cell_height + 4 * g_table_row_height;
break;
}
case TAB_CHOOSE_GIFTS:
{
vertical_scroll_count = 3;
g_window_horizontal_scroll.content_length = 6 * g_table_row_height + 2 * g_gift_list_width +
get_grid_width(&g_skill_table) + g_tab_width;
scroll_activation_order[0] = 2;
scroll_activation_order[1] = 1;
scroll_activation_order[2] = 0;
window_scroll_viewport_heights_at_which_vertical_scrolls_activate[2] =
cell_height + g_table_row_height * (ARRAY_COUNT(g_gifts) + 1);
WINDOW_VERTICAL_SCROLL.content_length = cell_height + 12 * g_table_row_height;
}
}
window_scroll_viewport_heights_at_which_vertical_scrolls_activate[0] =
WINDOW_VERTICAL_SCROLL.content_length;
for (size_t i = 0; i < vertical_scroll_count; ++i)
{
g_vertical_scrolls[i].is_active = false;
}
g_window_horizontal_scroll.is_active = false;
uint32_t window_content_width = g_window_horizontal_scroll.content_length;
uint32_t window_scroll_viewport_height = g_window_y_extent.length;
size_t scroll_activation_index = 0;
while (true)
{
while (true)
{
if (scroll_activation_index == vertical_scroll_count)
{
if (window_content_width > g_window_x_extent.length)
{
g_window_horizontal_scroll.is_active = true;
}
goto scroll_activity_states_are_set;
}
if (window_scroll_viewport_heights_at_which_vertical_scrolls_activate
[scroll_activation_order[scroll_activation_index]] > window_scroll_viewport_height)
{
g_vertical_scrolls[scroll_activation_order[scroll_activation_index]].is_active =
true;
window_content_width += cell_height;
++scroll_activation_index;
}
else
{
break;
}
}
if (g_window_horizontal_scroll.is_active)
{
goto scroll_activity_states_are_set;
}
else if (window_content_width > g_window_x_extent.length)
{
g_window_horizontal_scroll.is_active = true;
window_scroll_viewport_height -= cell_height;
}
else
{
++scroll_activation_index;
}
}
scroll_activity_states_are_set:
g_window_horizontal_scroll.length = g_window_x_extent.length;
g_window_horizontal_scroll.viewport_extent_along_thickness.length = g_window_y_extent.length;
if (g_window_horizontal_scroll.is_active)
{
g_window_horizontal_scroll.min_along_thickness = g_window_y_extent.length - cell_height;
g_window_horizontal_scroll.viewport_extent_along_thickness.length -= cell_height;
}
else
{
g_window_horizontal_scroll.content_offset = 0;
}
if (WINDOW_VERTICAL_SCROLL.is_active)
{
g_window_horizontal_scroll.min_along_length = cell_height;
g_window_horizontal_scroll.length -= cell_height;
WINDOW_VERTICAL_SCROLL.length =
g_window_horizontal_scroll.viewport_extent_along_thickness.length;
WINDOW_VERTICAL_SCROLL.viewport_extent_along_length.length = WINDOW_VERTICAL_SCROLL.length;
}
else
{
g_window_horizontal_scroll.min_along_length = 0;
WINDOW_VERTICAL_SCROLL.content_offset = 0;
}
if (SKILL_TABLE_SCROLL.is_active)
{
g_window_horizontal_scroll.content_length += cell_height;
SKILL_TABLE_SCROLL.viewport_extent_along_length.length =
max32(g_window_horizontal_scroll.viewport_extent_along_thickness.length -
g_table_row_height, WINDOW_VERTICAL_SCROLL.content_length - g_table_row_height) -
(unscrolled_skill_table_frame_min_y + g_line_thickness);
SKILL_TABLE_SCROLL.length =
SKILL_TABLE_SCROLL.viewport_extent_along_length.length + 2 * g_line_thickness;
}
else
{
SKILL_TABLE_SCROLL.content_offset = 0;
SKILL_TABLE_SCROLL.viewport_extent_along_length.length = SKILL_TABLE_SCROLL.content_length;
}
GIFT_LIST_SCROLL.viewport_extent_along_thickness.length = g_gift_list_width - g_line_thickness;
GIFT_LIST_SCROLL.viewport_extent_along_length.length =
max32(g_window_horizontal_scroll.viewport_extent_along_thickness.length -
g_table_row_height, WINDOW_VERTICAL_SCROLL.content_length - g_table_row_height) -
g_table_row_height;
if (GIFT_LIST_SCROLL.is_active)
{
g_window_horizontal_scroll.content_length += cell_height;
GIFT_LIST_SCROLL.length =
GIFT_LIST_SCROLL.viewport_extent_along_length.length + 2 * g_line_thickness;
}
else
{
GIFT_LIST_SCROLL.content_offset = 0;
}
g_window_horizontal_scroll.viewport_extent_along_length.min =
g_window_horizontal_scroll.min_along_length;
g_window_horizontal_scroll.viewport_extent_along_length.length =
g_window_horizontal_scroll.length;
WINDOW_VERTICAL_SCROLL.viewport_extent_along_thickness.length =
g_window_horizontal_scroll.viewport_extent_along_length.length;
reset_widget_positions();
}
void select_allocate_trait_dice_tab(void)
{
g_allocate_button_arrow = &g_down_arrowhead_rasterization;
g_deallocate_button_arrow = &g_up_arrowhead_rasterization;
g_layout.unallocated_dice_table.column_count = ARRAY_COUNT(g_unallocated_dice);
g_layout.unallocated_dice_table.row_count = 2;
g_layout.unallocated_dice_table.column_min_x_values = g_trait_table_column_min_x_values + 1;
g_trait_table.column_count = ARRAY_COUNT(g_trait_table_column_min_x_values) - 1;
g_trait_table.row_count = ARRAY_COUNT(g_traits);
g_trait_table.column_min_x_values = g_trait_table_column_min_x_values;
reformat_widgets_on_window_resize();
}
#define INIT(copy_font_data_param, dpi)\
{\
SET_MESSAGE_FONT_SIZE(dpi);\
SET_PAGE_SIZE();\
g_stack.start = RESERVE_MEMORY(UINT32_MAX);\
g_stack.end = (uint8_t*)g_stack.start + UINT32_MAX;\
g_stack.cursor = g_stack.start;\
g_stack.cursor_max = g_stack.start;\
g_skill_table_dice_header.column_count = ARRAY_COUNT(g_die_denominations);\
g_skill_table_dice_header.row_count = 1;\
g_skill_table_dice_header.column_min_x_values = g_skill_table_column_min_x_values + 2;\
g_skill_table.column_count = ARRAY_COUNT(g_skill_table_column_min_x_values) - 1;\
g_skill_table.row_count = ARRAY_COUNT(g_skills);\
g_skill_table.column_min_x_values = g_skill_table_column_min_x_values;\
FT_Init_FreeType(&g_freetype_library);\
scale_graphics_to_dpi(g_stack.start, COPY_FONT_DATA_TO_STACK_CURSOR(copy_font_data_param, dpi),\
dpi);\
select_allocate_trait_dice_tab();\
SKILL_TABLE_SCROLL.viewport_extent_along_thickness.length =\
get_grid_width(&g_skill_table) - g_line_thickness;\
SET_INITIAL_CURSOR_POSITION();\
}
void handle_message(void)
{
for (size_t i = 0; i < g_window_x_extent.length * g_window_y_extent.length; ++i)
{
g_pixels[i].value = g_dark_gray.value;
}
uint32_t cell_height = g_table_row_height - g_line_thickness;
if (update_vertical_scroll_bar_offset(&SKILL_TABLE_SCROLL, SKILL_TABLE_SCROLL_ID))
{
g_skill_table.min_y = g_skill_table_frame_min_y - SKILL_TABLE_SCROLL.content_offset;
}
if (g_selected_tab_index == TAB_CHOOSE_GIFTS &&
update_vertical_scroll_bar_offset(&GIFT_LIST_SCROLL, GIFT_LIST_SCROLL_ID))
{
g_layout.gift_list.min_y = g_layout.gift_list_frame_min_y - GIFT_LIST_SCROLL.content_offset;
}
if (update_scroll_bar_offset(&g_window_horizontal_scroll, g_cursor_y, g_cursor_x,
WINDOW_HORIZONTAL_SCROLL_ID, g_shift_is_down))
{
reset_widget_x_positions();
}
if (update_vertical_scroll_bar_offset(&WINDOW_VERTICAL_SCROLL, WINDOW_VERTCAL_SCROLL_ID))
{
reset_widget_y_positions();
}
draw_vertical_scroll_bar(g_window_x_extent, g_window_y_extent, &WINDOW_VERTICAL_SCROLL);
if (g_window_horizontal_scroll.is_active)
{
ScrollGeometryData data = get_scroll_geometry_data(&g_window_horizontal_scroll);
draw_filled_rectangle(g_window_x_extent, g_window_y_extent,
g_window_horizontal_scroll.min_along_length,
g_window_horizontal_scroll.min_along_thickness, g_window_horizontal_scroll.length,
data.trough_thickness, g_light_gray);
draw_filled_rectangle(g_window_x_extent, g_window_y_extent,
g_window_horizontal_scroll.min_along_length + g_line_thickness +
get_thumb_offset(&g_window_horizontal_scroll, &data),
g_window_horizontal_scroll.min_along_thickness + g_line_thickness, data.thumb_length,
data.thumb_thickness, g_dark_gray);
}
if (g_selected_tab_index == TAB_CHOOSE_GIFTS)
{
draw_vertical_scroll_bar(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, &GIFT_LIST_SCROLL);
}
draw_vertical_scroll_bar(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, &SKILL_TABLE_SCROLL);
int32_t tab_cell_min_x = g_tab_min_x + g_line_thickness;
uint32_t tab_cell_width = g_tab_width - g_line_thickness;
int32_t tab_min_y = -(g_line_thickness + WINDOW_VERTICAL_SCROLL.content_offset);
if (select_table_row(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, &g_selected_tab_index,
ARRAY_COUNT(g_tab_names), g_tab_min_x, tab_min_y, g_tab_width, TAB_0_ID))
{
switch (g_selected_tab_index)
{
case TAB_ALLOCATE_DICE:
{
select_allocate_trait_dice_tab();
break;
}
case TAB_ALLOCATE_MARKS:
{
g_allocate_button_arrow = &g_right_arrowhead_rasterization;
g_deallocate_button_arrow = &g_left_arrowhead_rasterization;
g_layout.unallocated_marks_display_width =
g_line_thickness + get_string_width("Unallocated Marks") + 2 * g_text_padding;
reformat_widgets_on_window_resize();
break;
}
case TAB_CHOOSE_GIFTS:
{
g_allocate_button_arrow = &g_left_arrowhead_rasterization;
g_deallocate_button_arrow = &g_right_arrowhead_rasterization;
g_layout.species_gifts.row_count = 3;
g_layout.species_gifts.column_count = 1;
g_layout.species_gifts.column_min_x_values = g_layout.species_gift_column_min_x_values;
g_layout.gift_list.row_count = ARRAY_COUNT(g_gifts);
g_layout.gift_list.column_count = 1;
g_layout.gift_list.column_min_x_values = g_layout.gift_list_column_min_x_values;
reformat_widgets_on_window_resize();
}
}
}
for (size_t i = 0; i < ARRAY_COUNT(g_tab_names); ++i)
{
tab_min_y += g_table_row_height;
draw_horizontally_centered_string(g_tab_names[i],
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, tab_cell_min_x,
tab_min_y - g_text_padding, tab_cell_width);
draw_filled_rectangle(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, tab_cell_min_x, tab_min_y,
tab_cell_width, g_line_thickness, g_black);
}
draw_filled_rectangle(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, g_tab_min_x, 0,
g_line_thickness, g_window_y_extent.length, g_black);
draw_filled_rectangle(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, g_tab_min_x,
g_selected_tab_index * g_table_row_height -
WINDOW_VERTICAL_SCROLL.content_offset,
g_line_thickness, cell_height, g_dark_gray);
draw_filled_rectangle(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, g_tab_min_x + g_tab_width,
-WINDOW_VERTICAL_SCROLL.content_offset, g_line_thickness,
ARRAY_COUNT(g_tab_names) * g_table_row_height, g_black);
uint32_t skill_table_width = get_grid_width(&g_skill_table);
Color allocate_button_border_color = g_light_gray;
Color deallocate_button_border_color = g_light_gray;
uint32_t unallocated_dice_table_height = 2 * g_table_row_height;
Interval clipped_skill_table_viewport_x_extent;
Interval clipped_skill_table_viewport_y_extent;
intersect_viewports(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
SKILL_TABLE_SCROLL.viewport_extent_along_thickness,
SKILL_TABLE_SCROLL.viewport_extent_along_length, &clipped_skill_table_viewport_x_extent,
&clipped_skill_table_viewport_y_extent);
switch (g_selected_tab_index)
{
case TAB_ALLOCATE_DICE:
{
int32_t unallocated_dice_table_cell_min_x =
g_layout.unallocated_dice_table.column_min_x_values[0] + g_line_thickness;
if (g_cursor_x >= unallocated_dice_table_cell_min_x)
{
size_t die_index =
(g_cursor_x - unallocated_dice_table_cell_min_x) / g_die_column_width;
if (die_index < g_layout.unallocated_dice_table.column_count)
{
if (do_button_action(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_layout.unallocated_dice_table.column_min_x_values[die_index],
g_skill_table_frame_min_y, g_die_column_width, unallocated_dice_table_height,
UNALLOCATED_DICE_TABLE_COLUMN_0_ID + die_index))
{
g_selected_die_denomination_index = die_index;
}
}
if (g_clicked_control_id >= UNALLOCATED_DICE_TABLE_COLUMN_0_ID &&
g_clicked_control_id < UNALLOCATED_DICE_TABLE_COLUMN_0_ID +
ARRAY_COUNT(g_unallocated_dice))
{
do_button_action(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_layout.unallocated_dice_table.column_min_x_values[
g_clicked_control_id - UNALLOCATED_DICE_TABLE_COLUMN_0_ID],
g_skill_table_frame_min_y, g_die_column_width, unallocated_dice_table_height,
g_clicked_control_id);
}
}
uint32_t die_cell_width = g_die_column_width - g_line_thickness;
if (g_selected_die_denomination_index < g_layout.unallocated_dice_table.column_count)
{
draw_filled_rectangle(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_layout.unallocated_dice_table.
column_min_x_values[g_selected_die_denomination_index] + g_line_thickness,
g_skill_table_frame_min_y + g_line_thickness + g_table_row_height, die_cell_width,
cell_height, g_white);
}
select_table_row(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, &g_selected_trait_index,
ARRAY_COUNT(g_traits), g_trait_table.column_min_x_values[0], g_trait_table.min_y,
get_grid_width(&g_trait_table), TRAIT_TABLE_ROW_0_ID);
if (g_selected_trait_index < ARRAY_COUNT(g_traits))
{
draw_filled_rectangle(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_trait_table.column_min_x_values[1],
g_line_thickness + g_trait_table.min_y +
g_selected_trait_index * g_table_row_height,
g_trait_table.column_min_x_values[g_trait_table.column_count] -
g_trait_table.column_min_x_values[1],
cell_height, g_white);
if (g_selected_die_denomination_index < 3)
{
uint8_t*selected_trait_dice =
g_traits[g_selected_trait_index].dice + g_selected_die_denomination_index;
if (g_unallocated_dice[g_selected_die_denomination_index])
{
if (do_button_action(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_allocate_button_min_x, g_allocate_button_min_y, g_table_row_height,
g_table_row_height, ALLOCATE_BUTTON_ID))
{
++*selected_trait_dice;
--g_unallocated_dice[g_selected_die_denomination_index];
}
allocate_button_border_color = g_black;
}
if (*selected_trait_dice)
{
if (do_button_action(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_deallocate_button_min_x, g_deallocate_button_min_y, g_table_row_height,
g_table_row_height, DEALLOCATE_BUTTON_ID))
{
--*selected_trait_dice;
++g_unallocated_dice[g_selected_die_denomination_index];
}
deallocate_button_border_color = g_black;
}
}
}
draw_grid(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
&g_layout.unallocated_dice_table);
int32_t cell_x = g_layout.unallocated_dice_table.column_min_x_values[0] + g_line_thickness;
int32_t text_y = g_skill_table_frame_min_y - g_text_padding;
uint32_t unallocated_dice_cells_width =
get_grid_width(&g_layout.unallocated_dice_table) - g_line_thickness;
draw_horizontally_centered_string("Unallocated Dice",
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, cell_x, text_y,
unallocated_dice_cells_width);
text_y += g_table_row_height;
for (size_t i = 0; i < g_layout.unallocated_dice_table.column_count; ++i)
{
draw_horizontally_centered_string(g_die_denominations[i],
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, cell_x, text_y,
die_cell_width);
draw_uint8(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, g_unallocated_dice[i],
cell_x + g_text_padding, text_y + g_table_row_height);
cell_x += g_die_column_width;
}
draw_grid(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, &g_trait_table);
draw_grid(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
&(Grid) { 3, 1, g_layout.unallocated_dice_table.column_min_x_values,
g_trait_table.min_y - g_table_row_height });
text_y = g_trait_table.min_y - g_text_padding;
draw_horizontally_centered_string("Traits",
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_trait_table.column_min_x_values[0], text_y, g_trait_column_width + g_line_thickness);
draw_horizontally_centered_string("Dice",
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_layout.unallocated_dice_table.column_min_x_values[0] + g_line_thickness,
text_y - g_table_row_height, unallocated_dice_cells_width);
for (size_t i = 0; i < 3; ++i)
{
draw_horizontally_centered_string(g_die_denominations[i],
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_layout.unallocated_dice_table.column_min_x_values[i] + g_line_thickness, text_y,
die_cell_width);
}
for (size_t i = 0; i < g_trait_table.row_count; ++i)
{
text_y += g_table_row_height;
Trait*trait = g_traits + i;
draw_string(trait->name, g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_trait_table.column_min_x_values[0] + g_line_thickness + g_text_padding, text_y);
for (size_t die_index = 0; die_index < ARRAY_COUNT(trait->dice); ++die_index)
{
draw_uint8(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
trait->dice[die_index],
g_layout.unallocated_dice_table.column_min_x_values[die_index] +
g_line_thickness + g_text_padding, text_y);
}
}
break;
}
case TAB_ALLOCATE_MARKS:
{
select_table_row(clipped_skill_table_viewport_x_extent,
clipped_skill_table_viewport_y_extent, &g_selected_skill_index, ARRAY_COUNT(g_skills),
g_skill_table.column_min_x_values[0], g_skill_table.min_y, skill_table_width,
SKILL_TABLE_ROW_0_ID);
if (g_selected_skill_index < ARRAY_COUNT(g_skills))
{
draw_filled_rectangle(clipped_skill_table_viewport_x_extent,
clipped_skill_table_viewport_y_extent,
g_line_thickness + g_skill_table.column_min_x_values[1],
g_line_thickness + g_skill_table.min_y +
g_selected_skill_index * g_table_row_height,
g_skill_table.column_min_x_values[2] -
(g_skill_table.column_min_x_values[1] + g_line_thickness),
cell_height, g_white);
Skill*selected_skill = g_skills + g_selected_skill_index;
if (g_unallocated_marks && selected_skill->mark_count < 3)
{
if (do_button_action(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_allocate_button_min_x, g_allocate_button_min_y, g_table_row_height,
g_table_row_height, ALLOCATE_BUTTON_ID))
{
++selected_skill->mark_count;
--g_unallocated_marks;
}
allocate_button_border_color = g_black;
}
if (selected_skill->mark_count)
{
if (do_button_action(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_deallocate_button_min_x, g_deallocate_button_min_y, g_table_row_height,
g_table_row_height, DEALLOCATE_BUTTON_ID))
{
--selected_skill->mark_count;
++g_unallocated_marks;
}
deallocate_button_border_color = g_black;
}
}
draw_rectangle_outline(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_layout.unallocated_marks_display_min_x, g_layout.unallocated_marks_display_min_y,
g_layout.unallocated_marks_display_width, g_table_row_height, g_black);
int32_t text_x =
g_layout.unallocated_marks_display_min_x + g_line_thickness + g_text_padding;
int32_t text_y = g_deallocate_button_min_y - g_text_padding;
draw_string("Unallocated Marks", g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, text_x, text_y);
draw_uint8(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, g_unallocated_marks, text_x,
text_y + g_table_row_height);
break;
}
case TAB_CHOOSE_GIFTS:
{
draw_horizontally_centered_string("Species Gifts",
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_layout.species_gift_column_min_x_values[0],
g_layout.species_gifts.min_y - g_text_padding, g_gift_list_width + g_line_thickness);
draw_grid(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, &g_layout.species_gifts);
Grid chosen_gifts = g_layout.species_gifts;
chosen_gifts.min_y += 4 * g_table_row_height;
draw_horizontally_centered_string("Career Gifts",
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_layout.species_gift_column_min_x_values[0], chosen_gifts.min_y - g_text_padding,
g_gift_list_width + g_line_thickness);
draw_grid(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, &chosen_gifts);
chosen_gifts.min_y += 4 * g_table_row_height;
int32_t text_y = chosen_gifts.min_y - g_text_padding;
draw_horizontally_centered_string("Free Gifts",
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_layout.species_gift_column_min_x_values[0], text_y,
g_gift_list_width + g_line_thickness);
Interval clipped_gift_list_viewport_x_extent;
Interval clipped_gift_list_viewport_y_extent;
intersect_viewports(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
GIFT_LIST_SCROLL.viewport_extent_along_thickness,
GIFT_LIST_SCROLL.viewport_extent_along_length, &clipped_gift_list_viewport_x_extent,
&clipped_gift_list_viewport_y_extent);
select_table_row(clipped_gift_list_viewport_x_extent, clipped_gift_list_viewport_y_extent,
&g_selected_gift_index, ARRAY_COUNT(g_gifts), g_layout.gift_list.column_min_x_values[0],
g_layout.gift_list.min_y, g_gift_list_width, GIFT_LIST_ROW_0_ID);
if (g_selected_gift_index < ARRAY_COUNT(g_gifts))
{
draw_filled_rectangle(clipped_gift_list_viewport_x_extent,
clipped_gift_list_viewport_y_extent,
g_line_thickness + g_layout.gift_list.column_min_x_values[0],
g_line_thickness + g_layout.gift_list.min_y +
g_selected_gift_index * g_table_row_height,
g_gift_list_width - g_line_thickness, cell_height, g_white);
if (g_free_gifts_chosen_count < ARRAY_COUNT(g_free_gift_indices))
{
for (size_t i = 0; i < g_free_gifts_chosen_count; ++i)
{
if (g_free_gift_indices[i] == g_selected_gift_index &&
!(g_gifts[g_selected_gift_index].descriptor_flags & DESCRIPTOR_MULTIPLE))
{
goto requirement_not_satisfied;
}
}
Gift*selected_gift = g_gifts + g_selected_gift_index;
for (size_t i = 0; i < selected_gift->requirement_count; ++i)
{
Requirement*requirement = selected_gift->requirements + i;
switch (requirement->requirement_type)
{
case REQUIREMENT_GIFT:
{
for (size_t j = 0; j < g_free_gifts_chosen_count; ++j)
{
if (g_free_gift_indices[j] == requirement->gift_index)
{
goto requirement_satisfied;
}
}
goto requirement_not_satisfied;
}
case REQUIREMENT_NO_GIFT_WITH_DESCRIPTOR:
{
for (size_t j = 0; j < g_free_gifts_chosen_count; ++j)
{
if (g_gifts[g_free_gift_indices[j]].descriptor_flags &
requirement->descriptor_flags)
{
goto requirement_not_satisfied;
}
}
goto requirement_satisfied;
}
case REQUIREMENT_TRAIT:
{
Trait*trait = g_traits + requirement->trait_index;
for (size_t j = DENOMINATION_D8; j-- > requirement->minimum_denomination;)
{
if (trait->dice[j] > 0)
{
goto requirement_satisfied;
}
}
goto requirement_not_satisfied;
}
}
requirement_satisfied:;
}
if (do_button_action(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_allocate_button_min_x, g_allocate_button_min_y, g_table_row_height,
g_table_row_height, ALLOCATE_BUTTON_ID))
{
g_free_gift_indices[g_free_gifts_chosen_count] = g_selected_gift_index;
++g_free_gifts_chosen_count;
}
requirement_not_satisfied:
allocate_button_border_color = g_black;
}
}
draw_grid(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, &chosen_gifts);
int32_t text_x = chosen_gifts.column_min_x_values[0] + g_line_thickness + g_text_padding;
for (size_t i = 0; i < g_free_gifts_chosen_count; ++i)
{
text_y += g_table_row_height;
draw_string(g_gifts[g_free_gift_indices[i]].name,
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, text_x, text_y);
}
draw_grid_dividers(clipped_gift_list_viewport_x_extent, clipped_gift_list_viewport_y_extent,
&g_layout.gift_list);
draw_rectangle_outline(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_layout.gift_list_column_min_x_values[0], g_layout.gift_list_frame_min_y,
g_gift_list_width,
GIFT_LIST_SCROLL.viewport_extent_along_length.length + g_line_thickness, g_black);
draw_horizontally_centered_string("Gifts",
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_layout.gift_list_column_min_x_values[0],
g_layout.gift_list_frame_min_y - g_text_padding, g_gift_list_width + g_line_thickness);
text_x = g_layout.gift_list_column_min_x_values[0] + g_line_thickness + g_text_padding;
text_y = g_layout.gift_list.min_y - g_text_padding;
for (size_t i = 0; i < ARRAY_COUNT(g_gifts); ++i)
{
text_y += g_table_row_height;
draw_string(g_gifts[i].name, clipped_gift_list_viewport_x_extent,
clipped_gift_list_viewport_y_extent, text_x, text_y);
}
}
}
draw_grid(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, &g_skill_table_dice_header);
draw_horizontally_centered_string("Dice",
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_skill_table.column_min_x_values[2] + g_line_thickness,
g_skill_table_dice_header.min_y - g_text_padding,
get_grid_width(&g_skill_table_dice_header) - g_line_thickness);
uint32_t die_column_width_with_both_borders = g_die_column_width + g_line_thickness;
int32_t text_y = g_skill_table_frame_min_y - g_text_padding;
for (size_t i = 2; i < g_skill_table.column_count; ++i)
{
draw_horizontally_centered_string(g_die_denominations[i - 2],
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_skill_table.column_min_x_values[i], text_y, die_column_width_with_both_borders);
}
draw_grid_dividers(clipped_skill_table_viewport_x_extent, clipped_skill_table_viewport_y_extent,
&g_skill_table);
draw_rectangle_outline(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_skill_table.column_min_x_values[0], g_skill_table_frame_min_y, skill_table_width,
SKILL_TABLE_SCROLL.viewport_extent_along_length.length + g_line_thickness, g_black);
draw_horizontally_centered_string("Skills",
g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_skill_table.column_min_x_values[0], text_y,
g_skill_table.column_min_x_values[1] + g_line_thickness -
g_skill_table.column_min_x_values[0]);
draw_string("Marks", g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness,
g_skill_table.column_min_x_values[1] + g_line_thickness + g_text_padding, text_y);
int32_t skill_text_x = g_skill_table.column_min_x_values[0] + g_line_thickness + g_text_padding;
text_y = g_skill_table.min_y - g_text_padding;
for (size_t i = 0; i < ARRAY_COUNT(g_skills); ++i)
{
text_y += g_table_row_height;
Skill*skill = g_skills + i;
draw_string(skill->name, clipped_skill_table_viewport_x_extent,
clipped_skill_table_viewport_y_extent, skill_text_x, text_y);
draw_uint8(clipped_skill_table_viewport_x_extent, clipped_skill_table_viewport_y_extent,
skill->mark_count,
g_skill_table.column_min_x_values[1] + g_line_thickness + g_text_padding, text_y);
uint8_t die_counts[ARRAY_COUNT(g_die_denominations)] = { 0 };
if (skill->mark_count)
{
++die_counts[skill->mark_count - 1];
}
for (size_t die_index = 0; die_index < ARRAY_COUNT(g_die_denominations); ++die_index)
{
draw_uint8(clipped_skill_table_viewport_x_extent, clipped_skill_table_viewport_y_extent,
die_counts[die_index],
g_skill_table.column_min_x_values[2 + die_index] + g_line_thickness +
g_text_padding,
text_y);
}
}
if (allocate_button_border_color.value == g_black.value)
{
draw_rectangle_outline(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, g_deallocate_button_min_x,
g_deallocate_button_min_y, g_table_row_height, g_table_row_height,
deallocate_button_border_color);
draw_rectangle_outline(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, g_allocate_button_min_x,
g_allocate_button_min_y, g_table_row_height, g_table_row_height,
allocate_button_border_color);
}
else
{
draw_rectangle_outline(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, g_allocate_button_min_x,
g_allocate_button_min_y, g_table_row_height, g_table_row_height,
allocate_button_border_color);
draw_rectangle_outline(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, g_deallocate_button_min_x,
g_deallocate_button_min_y, g_table_row_height, g_table_row_height,
deallocate_button_border_color);
}
draw_rasterization(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, g_deallocate_button_arrow,
g_deallocate_button_min_x + (g_table_row_height + g_line_thickness -
g_right_arrowhead_rasterization.bitmap.width) / 2,
g_deallocate_button_min_y + (g_table_row_height + g_line_thickness -
g_right_arrowhead_rasterization.bitmap.rows) / 2, deallocate_button_border_color);
draw_rasterization(g_window_horizontal_scroll.viewport_extent_along_length,
g_window_horizontal_scroll.viewport_extent_along_thickness, g_allocate_button_arrow,
g_allocate_button_min_x + (g_table_row_height + g_line_thickness -
g_left_arrowhead_rasterization.bitmap.width) / 2,
g_allocate_button_min_y + (g_table_row_height + g_line_thickness -
g_left_arrowhead_rasterization.bitmap.rows) / 2, allocate_button_border_color);
g_left_mouse_button_changed_state = false;
g_120ths_of_mouse_wheel_notches_turned = 0;
if (!g_left_mouse_button_is_down)
{
g_clicked_control_id = 0;
}
}<file_sep>#include <ft2build.h>
#include FT_FREETYPE_H
#include <stdbool.h>
#include <stdint.h>
#ifdef _DEBUG
#define ASSERT(condition) if (!(condition)) { *(int*)0 = 0; }
#else
#define ASSERT(condition)
#endif
#define ARRAY_COUNT(arr) (sizeof(arr) / sizeof(arr[0]))
#define UNPAREN(...) __VA_ARGS__
#define MAKE_ENUM(name, value) name,
#define MAKE_VALUE(name, value) UNPAREN value,
uint8_t g_unallocated_dice[] = { 1, 3, 2 };
#include "rulebook_data.c"
int32_t min32(int32_t a, int32_t b)
{
if (a < b)
{
return a;
}
return b;
}
int32_t max32(int32_t a, int32_t b)
{
if (a > b)
{
return a;
}
return b;
}
typedef struct Stack
{
void*start;
void*end;
void*cursor;
void*cursor_max;
} Stack;
size_t g_page_size;
Stack g_stack;
void*align_cursor(Stack*output_stack, size_t alignment)
{
output_stack->cursor =
(void*)(((uintptr_t)output_stack->cursor + alignment - 1) & -(uintptr_t)alignment);
return output_stack->cursor;
}
void allocate_unaligned_stack_slot(Stack*output_stack, size_t slot_size)
{
output_stack->cursor = (uint8_t*)output_stack->cursor + slot_size;
while (output_stack->cursor > output_stack->cursor_max)
{
COMMIT_PAGE(output_stack->cursor_max);
output_stack->cursor_max = (uint8_t*)output_stack->cursor_max + g_page_size;
}
}
void*allocate_stack_slot(Stack*output_stack, size_t slot_size, size_t alignment)
{
void*slot = align_cursor(output_stack, alignment);
allocate_unaligned_stack_slot(output_stack, slot_size);
return slot;
}
typedef struct Interval
{
int32_t min;
int32_t length;
} Interval;
typedef union Color
{
struct
{
uint8_t blue;
uint8_t green;
uint8_t red;
uint8_t alpha;
};
uint32_t value;
} Color;
size_t g_pixel_buffer_capacity;
Color*g_pixels;
Interval g_window_x_extent;
Interval g_window_y_extent;
uint32_t g_line_thickness;
uint32_t g_table_row_height;
Color g_black = { .value = 0xff000000 };
Color g_dark_gray = { .value = 0xffb0b0b0 };
Color g_light_gray = { .value = 0xffd0d0d0 };
Color g_white = { .value = 0xffffffff };
void draw_filled_rectangle(Interval clip_x_extent, Interval clip_y_extent, int32_t min_x,
int32_t min_y, uint32_t width, uint32_t height, Color color)
{
int32_t max_x = min32(min_x + width, clip_x_extent.min + clip_x_extent.length);
min_x = max32(min_x, clip_x_extent.min);
int32_t max_y = min32(min_y + height, clip_y_extent.min + clip_y_extent.length);
min_y = max32(min_y, clip_y_extent.min);
for (int32_t y = min_y; y < max_y; ++y)
{
Color*row = g_pixels + y * g_window_x_extent.length;
for (int32_t x = min_x; x < max_x; ++x)
{
row[x].value = color.value;
}
}
}
void draw_rectangle_outline(Interval clip_x_extent, Interval clip_y_extent, int32_t min_x,
int32_t min_y, uint32_t width, uint32_t height, Color color)
{
draw_filled_rectangle(clip_x_extent, clip_y_extent, min_x, min_y, width, g_line_thickness,
color);
draw_filled_rectangle(clip_x_extent, clip_y_extent, min_x + g_line_thickness, min_y + height,
width, g_line_thickness, color);
draw_filled_rectangle(clip_x_extent, clip_y_extent, min_x, min_y + g_line_thickness,
g_line_thickness, height, color);
draw_filled_rectangle(clip_x_extent, clip_y_extent, min_x + width, min_y, g_line_thickness,
height, color);
}
typedef struct Grid
{
size_t column_count;
size_t row_count;
int32_t*column_min_x_values;
int32_t min_y;
} Grid;
int32_t get_rightmost_column_x(Grid*grid)
{
return grid->column_min_x_values[grid->column_count];
}
uint32_t get_grid_width(Grid*grid)
{
return get_rightmost_column_x(grid) - grid->column_min_x_values[0];
}
void draw_grid_dividers(Interval clip_x_extent, Interval clip_y_extent, Grid*grid)
{
int32_t cell_min_y = grid->min_y + g_line_thickness;
uint32_t height = g_table_row_height * grid->row_count - g_line_thickness;
for (size_t column_index = 1; column_index < grid->column_count; ++column_index)
{
draw_filled_rectangle(clip_x_extent, clip_y_extent, grid->column_min_x_values[column_index],
cell_min_y, g_line_thickness, height, g_black);
}
int32_t cell_min_x = grid->column_min_x_values[0] + g_line_thickness;
int32_t row_min_y = grid->min_y;
uint32_t cells_width = grid->column_min_x_values[grid->column_count] - cell_min_x;
for (size_t row_index = 1; row_index < grid->row_count; ++row_index)
{
row_min_y += g_table_row_height;
draw_filled_rectangle(clip_x_extent, clip_y_extent, cell_min_x, row_min_y, cells_width,
g_line_thickness, g_black);
}
}
void draw_grid(Interval clip_x_extent, Interval clip_y_extent, Grid*grid)
{
draw_rectangle_outline(clip_x_extent, clip_y_extent, grid->column_min_x_values[0], grid->min_y,
get_grid_width(grid), g_table_row_height * grid->row_count, g_black);
draw_grid_dividers(clip_x_extent, clip_y_extent, grid);
}
typedef struct Rasterization
{
FT_Bitmap bitmap;
FT_Int left_bearing;
FT_Int top_bearing;
FT_Pos advance;
} Rasterization;
#define FIRST_RASTERIZED_GLYPH ' '
#define LAST_RASTERIZED_GLYPH '~'
FT_Library g_freetype_library;
FT_Face g_face;
Rasterization g_glyph_rasterizations[1 + LAST_RASTERIZED_GLYPH - FIRST_RASTERIZED_GLYPH];
Rasterization g_up_arrowhead_rasterization;
Rasterization g_right_arrowhead_rasterization;
Rasterization g_down_arrowhead_rasterization;
Rasterization g_left_arrowhead_rasterization;
FT_F26Dot6 g_message_font_height;
uint32_t g_text_padding;
uint32_t round26_6to_pixel(uint32_t subpixel)
{
return (subpixel + 32) >> 6;
}
Rasterization*get_rasterization(char codepoint)
{
return g_glyph_rasterizations + codepoint - FIRST_RASTERIZED_GLYPH;
}
void rasterize_glyph(FT_ULong codepoint, Rasterization*rasterization_slot)
{
FT_Load_Glyph(g_face, FT_Get_Char_Index(g_face, codepoint), FT_LOAD_DEFAULT);
FT_Render_Glyph(g_face->glyph, FT_RENDER_MODE_NORMAL);
rasterization_slot->bitmap = g_face->glyph->bitmap;
rasterization_slot->bitmap.buffer = g_stack.cursor;
size_t rasterization_size = g_face->glyph->bitmap.rows * g_face->glyph->bitmap.pitch;
allocate_unaligned_stack_slot(&g_stack, rasterization_size);
memcpy(rasterization_slot->bitmap.buffer, g_face->glyph->bitmap.buffer, rasterization_size);
rasterization_slot->left_bearing = g_face->glyph->bitmap_left;
rasterization_slot->top_bearing = g_face->glyph->bitmap_top;
rasterization_slot->advance = g_face->glyph->metrics.horiAdvance;
}
void draw_rasterization(Interval clip_x_extent, Interval clip_y_extent, Rasterization*rasterization,
int32_t min_x, int32_t min_y, Color color)
{
int32_t max_x_in_bitmap = min32(rasterization->bitmap.width,
clip_x_extent.min + clip_x_extent.length - min_x);
int32_t max_y_in_bitmap =
min32(rasterization->bitmap.rows, clip_y_extent.min + clip_y_extent.length - min_y);
Color*bitmap_top_left_in_window_buffer = g_pixels + min_y * g_window_x_extent.length + min_x;
for (int32_t bitmap_y = max32(0, clip_y_extent.min - min_y); bitmap_y < max_y_in_bitmap;
++bitmap_y)
{
Color*bitmap_row_left_end_in_window_buffer =
bitmap_top_left_in_window_buffer + bitmap_y * g_window_x_extent.length;
for (int32_t bitmap_x = max32(0, clip_x_extent.min - min_x); bitmap_x < max_x_in_bitmap;
++bitmap_x)
{
Color*pixel = bitmap_row_left_end_in_window_buffer + bitmap_x;
uint32_t alpha =
rasterization->bitmap.buffer[bitmap_y * rasterization->bitmap.pitch + bitmap_x];
uint32_t lerp_term = (255 - alpha) * pixel->alpha;
pixel->red = (color.red * alpha) / 255 + (lerp_term * pixel->red) / 65025;
pixel->green = (color.green * alpha) / 255 + (lerp_term * pixel->green) / 65025;
pixel->blue = (color.blue * alpha) / 255 + (lerp_term * pixel->blue) / 65025;
pixel->alpha = alpha + lerp_term / 255;
}
}
}
FT_Pos draw_string(char*string, Interval clip_x_extent, Interval clip_y_extent, int32_t origin_x,
int32_t origin_y)
{
FT_Pos advance = origin_x << 6;
FT_UInt previous_glyph_index = FT_Get_Char_Index(g_face, string[0]);
FT_Vector kerning_with_previous_glyph = { 0, 0 };
for (char*character = string; *character; ++character)
{
advance += kerning_with_previous_glyph.x;
Rasterization*rasterization = get_rasterization(*character);
draw_rasterization(clip_x_extent, clip_y_extent, rasterization,
round26_6to_pixel(advance) + rasterization->left_bearing,
origin_y - rasterization->top_bearing, g_black);
advance += g_glyph_rasterizations[*character - FIRST_RASTERIZED_GLYPH].advance;
FT_UInt glyph_index = FT_Get_Char_Index(g_face, character[1]);
FT_Get_Kerning(g_face, previous_glyph_index, glyph_index, FT_KERNING_DEFAULT,
&kerning_with_previous_glyph);
}
return advance;
}
uint32_t get_string_width(char*string)
{
FT_Pos out = 0;
FT_UInt previous_glyph_index = FT_Get_Char_Index(g_face, string[0]);
FT_Vector kerning_with_previous_glyph = { 0, 0 };
for (char*character = string; *character; ++character)
{
out += kerning_with_previous_glyph.x + get_rasterization(*character)->advance;
FT_Get_Kerning(g_face, previous_glyph_index, FT_Get_Char_Index(g_face, character[1]),
FT_KERNING_DEFAULT, &kerning_with_previous_glyph);
}
return round26_6to_pixel(out);
}
void draw_horizontally_centered_string(char*string, Interval clip_x_extent, Interval clip_y_extent,
int32_t cell_min_x, int32_t text_origin_y, uint32_t cell_width)
{
draw_string(string, clip_x_extent, clip_y_extent,
cell_min_x + (cell_width - get_string_width(string)) / 2, text_origin_y);
}
void draw_uint8(Interval clip_x_extent, Interval clip_y_extent, uint8_t value, int32_t origin_x,
int32_t origin_y)
{
char buffer[4];
char*string;
if (value)
{
string = buffer + 3;
*string = 0;
while (value)
{
--string;
*string = value % 10 + '0';
value /= 10;
}
}
else
{
string = buffer;
string[0] = '0';
string[1] = 0;
}
draw_string(string, clip_x_extent, clip_y_extent, origin_x, origin_y);
}
uint32_t g_text_lines_per_mouse_wheel_notch;
uint8_t g_clicked_control_id;
int32_t g_cursor_x;
int32_t g_cursor_y;
bool g_left_mouse_button_is_down;
bool g_left_mouse_button_changed_state;
bool g_shift_is_down;
int16_t g_120ths_of_mouse_wheel_notches_turned;
bool do_button_action(Interval clip_x_extent, Interval clip_y_extent, int32_t min_x, int32_t min_y,
uint32_t width, uint32_t height, uint8_t control_id)
{
int32_t cell_min_x = min_x + g_line_thickness;
int32_t cell_min_y = min_y + g_line_thickness;
if (g_cursor_x >= cell_min_x && g_cursor_x < min_x + width && g_cursor_y >= cell_min_y &&
g_cursor_y < min_y + height)
{
if (g_left_mouse_button_is_down)
{
if (g_left_mouse_button_changed_state)
{
g_clicked_control_id = control_id;
}
if (g_clicked_control_id == control_id)
{
draw_filled_rectangle(clip_x_extent, clip_y_extent, cell_min_x, cell_min_y,
width - g_line_thickness, height - g_line_thickness, g_white);
}
}
else
{
draw_filled_rectangle(clip_x_extent, clip_y_extent, cell_min_x, cell_min_y,
width - g_line_thickness, height - g_line_thickness, g_light_gray);
if (g_left_mouse_button_changed_state && g_clicked_control_id == control_id)
{
g_clicked_control_id = 0;
return true;
}
}
}
else if (g_clicked_control_id == control_id)
{
if (g_left_mouse_button_is_down)
{
uint32_t interior_dimension = g_table_row_height - g_line_thickness;
draw_filled_rectangle(clip_x_extent, clip_y_extent, cell_min_x, cell_min_y,
width - g_line_thickness, height - g_line_thickness, g_light_gray);
}
else if (g_left_mouse_button_changed_state)
{
g_clicked_control_id = 0;
}
}
return false;
}
bool select_table_row(Interval clip_x_extent, Interval clip_y_extent, size_t*selected_row_index,
size_t table_row_count, int32_t table_min_x, int32_t table_min_y, uint32_t table_width,
uint8_t table_row_0_id)
{
bool selection_changed = false;
if (g_cursor_y >= clip_y_extent.min && g_cursor_y < clip_y_extent.min + clip_y_extent.length &&
g_cursor_y >= table_min_y)
{
size_t row_index = (g_cursor_y - table_min_y) / g_table_row_height;
if (row_index < table_row_count &&
do_button_action(clip_x_extent, clip_y_extent, table_min_x,
table_min_y + row_index * g_table_row_height, table_width, g_table_row_height,
table_row_0_id + row_index))
{
*selected_row_index = row_index;
selection_changed = true;
}
if (g_clicked_control_id >= table_row_0_id &&
g_clicked_control_id < table_row_0_id + table_row_count)
{
do_button_action(clip_x_extent, clip_y_extent, table_min_x,
table_min_y + (g_clicked_control_id - table_row_0_id) * g_table_row_height,
table_width, g_table_row_height, g_clicked_control_id);
}
}
return selection_changed;
}
typedef struct ScrollBar
{
int32_t min_along_thickness;
int32_t min_along_length;
uint32_t length;
uint32_t content_length;
uint32_t content_offset;
Interval viewport_extent_along_thickness;
Interval viewport_extent_along_length;
int32_t previous_cursor_lengthwise_coord;
bool is_active;
} ScrollBar;
typedef struct ScrollGeometryData
{
uint32_t trough_thickness;
uint32_t thumb_thickness;
uint32_t thumb_length;
uint32_t max_thumb_offset;
uint32_t max_viewport_offset;
} ScrollGeometryData;
ScrollGeometryData get_scroll_geometry_data(ScrollBar*scroll)
{
ScrollGeometryData out;
out.trough_thickness = g_table_row_height - g_line_thickness;
uint32_t trough_length_without_border = scroll->length - 2 * g_line_thickness;
out.thumb_thickness = out.trough_thickness - 2 * g_line_thickness;
out.thumb_length = (trough_length_without_border *
scroll->viewport_extent_along_length.length) / scroll->content_length;
out.max_thumb_offset = trough_length_without_border - out.thumb_length;
out.max_viewport_offset = scroll->content_length - scroll->viewport_extent_along_length.length;
return out;
}
uint32_t get_thumb_offset(ScrollBar*scroll, ScrollGeometryData*data)
{
return (data->max_thumb_offset * scroll->content_offset + data->max_viewport_offset / 2) /
data->max_viewport_offset;
}
bool update_scroll_bar_offset(ScrollBar*scroll, int32_t cursor_coord_along_thickness,
int32_t cursor_coord_along_length, uint32_t scroll_id, bool scroll_wheel_applies)
{
if (scroll->is_active)
{
ASSERT(scroll->content_length >= scroll->viewport_extent_along_length.length);
uint32_t old_content_offset = scroll->content_offset;
ScrollGeometryData data = get_scroll_geometry_data(scroll);
int32_t thumb_min_along_thickness = scroll->min_along_thickness + g_line_thickness;
int32_t thumb_min_along_length = scroll->min_along_length + g_line_thickness;
if (scroll_wheel_applies &&
cursor_coord_along_thickness >= scroll->viewport_extent_along_thickness.min &&
cursor_coord_along_thickness < scroll->viewport_extent_along_thickness.min +
scroll->viewport_extent_along_thickness.length &&
cursor_coord_along_length >= scroll->viewport_extent_along_length.min &&
cursor_coord_along_length < scroll->viewport_extent_along_length.min +
scroll->viewport_extent_along_length.length)
{
scroll->content_offset = max32(0,
scroll->content_offset - (g_120ths_of_mouse_wheel_notches_turned *
(int32_t)(g_text_lines_per_mouse_wheel_notch * g_table_row_height)) / 120);
g_120ths_of_mouse_wheel_notches_turned = 0;
}
if (g_left_mouse_button_is_down && g_clicked_control_id == scroll_id)
{
int32_t thumb_offset = get_thumb_offset(scroll, &data) + cursor_coord_along_length -
scroll->previous_cursor_lengthwise_coord;
if (thumb_offset > 0)
{
thumb_offset = min32(thumb_offset, data.max_thumb_offset);
}
else
{
thumb_offset = 0;
}
thumb_min_along_length += thumb_offset;
scroll->content_offset = (data.max_viewport_offset * thumb_offset +
data.max_thumb_offset / 2) / data.max_thumb_offset;
scroll->previous_cursor_lengthwise_coord = cursor_coord_along_length;
}
else
{
scroll->content_offset = min32(scroll->content_offset, data.max_viewport_offset);
thumb_min_along_length += get_thumb_offset(scroll, &data);
if (g_left_mouse_button_is_down && g_left_mouse_button_changed_state &&
cursor_coord_along_thickness >= thumb_min_along_thickness &&
cursor_coord_along_thickness < thumb_min_along_thickness + data.thumb_thickness &&
cursor_coord_along_length >= thumb_min_along_length &&
cursor_coord_along_length < thumb_min_along_length + data.thumb_length)
{
g_clicked_control_id = scroll_id;
scroll->previous_cursor_lengthwise_coord = cursor_coord_along_length;
}
}
return old_content_offset != scroll->content_offset;
}
return false;
}
bool update_vertical_scroll_bar_offset(ScrollBar*scroll, uint32_t scroll_id)
{
return update_scroll_bar_offset(scroll, g_cursor_x, g_cursor_y, scroll_id, !g_shift_is_down);
}
void draw_vertical_scroll_bar(Interval clip_x_extent, Interval clip_y_extent, ScrollBar*scroll)
{
if (scroll->is_active)
{
ScrollGeometryData data = get_scroll_geometry_data(scroll);
draw_filled_rectangle(clip_x_extent, clip_y_extent, scroll->min_along_thickness,
scroll->min_along_length, data.trough_thickness, scroll->length, g_light_gray);
draw_filled_rectangle(clip_x_extent, clip_y_extent,
scroll->min_along_thickness + g_line_thickness,
scroll->min_along_length + g_line_thickness + get_thumb_offset(scroll, &data),
data.thumb_thickness, data.thumb_length, g_dark_gray);
}
}
Interval intersect_intervals(Interval a, Interval b)
{
Interval out;
out.min = max32(a.min, b.min);
out.length = min32(a.min + a.length, b.min + b.length) - out.min;
return out;
}
void intersect_viewports(Interval x_extent_a, Interval y_extent_a, Interval x_extent_b,
Interval y_extent_b, Interval*x_extent_out, Interval*y_extent_out)
{
*x_extent_out = intersect_intervals(x_extent_a, x_extent_b);
*y_extent_out = intersect_intervals(y_extent_a, y_extent_b);
}<file_sep>#include <windows.h>
#include <windowsx.h>
size_t copy_font_data_to_stack_cursor(HWND window_handle, WORD dpi);
#define SET_MESSAGE_FONT_SIZE(dpi)\
{\
NONCLIENTMETRICSW non_client_metrics;\
non_client_metrics.cbSize = sizeof(NONCLIENTMETRICSW);\
SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, non_client_metrics.cbSize, &non_client_metrics,\
0);\
g_message_font_height = ((-non_client_metrics.lfMessageFont.lfHeight * 72) << 6) / dpi;\
}
#define COPY_FONT_DATA_TO_STACK_CURSOR(param, dpi) copy_font_data_to_stack_cursor(param, dpi)
#define SET_INITIAL_CURSOR_POSITION()\
{\
POINT cursor_position;\
GetCursorPos(&cursor_position);\
g_cursor_x = cursor_position.x;\
g_cursor_y = cursor_position.y;\
}
#define SET_PAGE_SIZE()\
{\
SYSTEM_INFO system_info;\
GetSystemInfo(&system_info);\
g_page_size = max(system_info.dwAllocationGranularity, system_info.dwPageSize);\
}
#define RESERVE_MEMORY(size) VirtualAlloc(0, size, MEM_RESERVE, PAGE_READWRITE)
#define COMMIT_PAGE(address) VirtualAlloc(address, g_page_size, MEM_COMMIT, PAGE_READWRITE)
#include "create_character_window.c"
size_t copy_font_data_to_stack_cursor(HWND window_handle, WORD dpi)
{
HFONT win_font = CreateFont(0, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, ANSI_CHARSET,
OUT_TT_ONLY_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, 0, "Ariel");
HDC device_context = GetDC(window_handle);
SelectFont(device_context, win_font);
DWORD font_file_size = GetFontData(device_context, 0, 0, 0, 0);
void*font_data = g_stack.cursor;
allocate_unaligned_stack_slot(&g_stack, font_file_size);
GetFontData(device_context, 0, 0, font_data, font_file_size);
DeleteObject(win_font);
ReleaseDC(window_handle, device_context);
return font_file_size;
}
HDC g_device_context;
BITMAPINFO g_pixel_buffer_info;
LRESULT CALLBACK create_character_proc(HWND window_handle, UINT message, WPARAM w_param,
LPARAM l_param)
{
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_DPICHANGED:
FT_Done_Face(g_face);
WORD dpi = HIWORD(w_param);
g_stack.cursor = g_stack.start;
scale_graphics_to_dpi(g_stack.start, copy_font_data_to_stack_cursor(window_handle, dpi),
dpi);
reset_widget_positions();
RECT*client_rect = (RECT*)l_param;
SetWindowPos(window_handle, 0, client_rect->left, client_rect->top,
client_rect->right - client_rect->left, client_rect->bottom - client_rect->top,
SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOZORDER);
return 0;
case WM_LBUTTONDOWN:
SetCapture(window_handle);
g_left_mouse_button_is_down = true;
g_left_mouse_button_changed_state = true;
return 0;
case WM_LBUTTONUP:
ReleaseCapture();
g_left_mouse_button_is_down = false;
g_left_mouse_button_changed_state = true;
return 0;
case WM_MOUSEMOVE:
g_cursor_x = GET_X_LPARAM(l_param);
g_cursor_y = GET_Y_LPARAM(l_param);
return 0;
case WM_MOUSEWHEEL:
g_120ths_of_mouse_wheel_notches_turned = GET_WHEEL_DELTA_WPARAM(w_param);
return 0;
case WM_SIZE:
g_window_x_extent.length = LOWORD(l_param);
g_window_y_extent.length = HIWORD(l_param);
g_pixel_buffer_info.bmiHeader.biWidth = g_window_x_extent.length;
g_pixel_buffer_info.bmiHeader.biHeight = -(int32_t)g_window_y_extent.length;
size_t new_pixel_buffer_capacity =
GetSystemMetrics(SM_CXVIRTUALSCREEN) * GetSystemMetrics(SM_CXVIRTUALSCREEN);
if (new_pixel_buffer_capacity > g_pixel_buffer_capacity)
{
VirtualFree(g_pixels, 0, MEM_RELEASE);
g_pixels = VirtualAlloc(0, sizeof(Color) * new_pixel_buffer_capacity, MEM_COMMIT,
PAGE_READWRITE);
g_pixel_buffer_capacity = new_pixel_buffer_capacity;
}
reformat_widgets_on_window_resize();
handle_message();
StretchDIBits(g_device_context, 0, 0, g_window_x_extent.length, g_window_y_extent.length, 0,
0, g_window_x_extent.length, g_window_y_extent.length, g_pixels, &g_pixel_buffer_info,
DIB_RGB_COLORS, SRCCOPY);
return 0;
case WM_KEYDOWN:
if (w_param = VK_SHIFT)
{
g_shift_is_down = true;
return 0;
}
break;
case WM_KEYUP:
if (w_param = VK_SHIFT)
{
g_shift_is_down = false;
return 0;
}
}
return DefWindowProc(window_handle, message, w_param, l_param);
}
HWND init(HINSTANCE instance_handle)
{
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE);
SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &g_text_lines_per_mouse_wheel_notch, 0);
g_pixel_buffer_info.bmiHeader.biSize = sizeof(g_pixel_buffer_info.bmiHeader);
g_pixel_buffer_info.bmiHeader.biPlanes = 1;
g_pixel_buffer_info.bmiHeader.biBitCount = 8 * sizeof(Color);
g_pixel_buffer_info.bmiHeader.biCompression = BI_RGB;
WNDCLASSEX wc = { 0 };
wc.cbSize = sizeof(WNDCLASSEX);
wc.lpfnWndProc = create_character_proc;
wc.hInstance = instance_handle;
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.lpszClassName = "Create Character";
RegisterClassEx(&wc);
HWND window_handle = CreateWindow(wc.lpszClassName, "Create Character", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, instance_handle, 0);
WORD dpi = GetDpiForWindow(window_handle);
INIT(window_handle, dpi);
ShowWindow(window_handle, SW_MAXIMIZE);
return window_handle;
}
int WINAPI wWinMain(HINSTANCE instance_handle, HINSTANCE previous_instance_handle,
PWSTR command_line, int show)
{
g_device_context = GetDC(init(instance_handle));
MSG msg;
while (GetMessage(&msg, 0, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
handle_message();
StretchDIBits(g_device_context, 0, 0, g_window_x_extent.length, g_window_y_extent.length, 0,
0, g_window_x_extent.length, g_window_y_extent.length, g_pixels, &g_pixel_buffer_info,
DIB_RGB_COLORS, SRCCOPY);
}
return 0;
}
|
8877279fcd630f613f7436ba8a0f2832b3fc3193
|
[
"C"
] | 4
|
C
|
AlexanderKindel/ironclaw
|
1c8249225a048c3dd7fc8aadf35bb19e8e21f3d6
|
103ce98d263a5f31db3f68cffa417ce5bd63e370
|
refs/heads/master
|
<file_sep>package hostess
import (
"flag"
"io/ioutil"
"os"
"testing"
"github.com/codegangsta/cli"
"github.com/stretchr/testify/assert"
)
func TestStrPadRight(t *testing.T) {
assert.Equal(t, "", StrPadRight("", 0), "Zero-length no padding")
assert.Equal(t, " ", StrPadRight("", 10), "Zero-length 10 padding")
assert.Equal(t, "string", StrPadRight("string", 0), "6-length 0 padding")
}
func captureOutput(f func()) string {
rescueStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
f()
w.Close()
out, _ := ioutil.ReadAll(r)
os.Stdout = rescueStdout
return string(out[:])
}
func TestLs(t *testing.T) {
os.Setenv("HOSTESS_PATH", "test-fixtures/hostfile1")
defer os.Setenv("HOSTESS_PATH", "")
app := cli.NewApp()
context := cli.NewContext(app, &flag.FlagSet{}, nil)
Ls(context)
// Test on/off arguments functionality
os.Setenv("HOSTESS_PATH", "test-fixtures/ls_on_off")
set := flag.NewFlagSet("test", 0)
set.Parse([]string{"list", "on"})
context = cli.NewContext(app, set, nil)
command := cli.Command{
Name: "list",
Aliases: []string{"ls"},
Usage: "Testing Ls",
Description: "Testing Ls",
Action: Ls,
}
output := captureOutput(func() {
command.Run(context)
})
assert.Equal(t, "chocolate.pie.example.com -> fc00:e968:6179::de52:7100 (On)\n", output)
}
|
e7619f6f749f4aac282b45e3b78f8d2f2deecffc
|
[
"Go"
] | 1
|
Go
|
taylon/hostess
|
8bc3c83b095f469119e850763171b302831f1500
|
e2ea2728457cd07c01a203e35d144df4834a7e41
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace MobileApp.Views.Pages.Extenders
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class AddItemPage : ContentPage
{
public AddItemPage()
{
InitializeComponent();
}
private async void AddBut_Clicked(object sender, EventArgs e)
{
await Navigation.PopAsync();
}
private async void AddItemCancel_Clicked(object sender, EventArgs e)
{
await Navigation.PopAsync();
//await Navigation.PopToRootAsync();
}
private void AddItemSave_Clicked(object sender, EventArgs e)
{
}
}
}<file_sep># Host: localhost (Version 5.6.37)
# Date: 2019-04-23 10:02:37
# Generator: MySQL-Front 6.1 (Build 1.26)
#
# Structure for table "category"
#
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`desc` varchar(255) DEFAULT NULL,
`categoryid` int(11) DEFAULT NULL,
PRIMARY KEY (`Id`),
KEY `categoryid` (`categoryid`),
CONSTRAINT `category_ibfk_1` FOREIGN KEY (`categoryid`) REFERENCES `category` (`Id`) ON DELETE SET NULL ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
#
# Data for table "category"
#
#
# Structure for table "users"
#
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`Id` varchar(255) NOT NULL DEFAULT '',
`fname` varchar(255) DEFAULT NULL,
`lname` varchar(255) DEFAULT NULL,
`uname` varchar(255) DEFAULT NULL,
`email` varchar(1024) DEFAULT NULL,
`password` varchar(1024) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
#
# Data for table "users"
#
#
# Structure for table "items"
#
DROP TABLE IF EXISTS `items`;
CREATE TABLE `items` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`suject` varchar(1024) DEFAULT NULL,
`body` varchar(4000) DEFAULT NULL,
`categoryid` int(11) DEFAULT NULL,
`userid` varchar(255) DEFAULT NULL,
PRIMARY KEY (`Id`),
KEY `userid` (`userid`),
KEY `categoryid` (`categoryid`),
CONSTRAINT `items_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `users` (`Id`) ON DELETE SET NULL ON UPDATE NO ACTION,
CONSTRAINT `items_ibfk_2` FOREIGN KEY (`categoryid`) REFERENCES `category` (`Id`) ON DELETE SET NULL ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
#
# Data for table "items"
#
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using MobileApp.Views.Pages;
namespace MobileApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
public LoginPage()
{
InitializeComponent();
}
private async void LoginButton_Clicked(object sender, EventArgs e)
{
bool LgnUsername = string.IsNullOrEmpty(LoginUsername.Text);
bool LgnPassword = string.IsNullOrEmpty(LoginPassword.Text);
if (LgnPassword || LgnUsername)
{
await DisplayAlert("Sign in Error", "Sign failed check Username or Password", "Ok");
}
else
{
Application.Current.MainPage = (new LandingPage ());
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace MobileApp.Views.Pages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LandingPage : Shell
{
public LandingPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
Navigation.PopAsync();
base.OnAppearing();
}
}
}
|
7a37ba47a86b3285cad53527ae96d57459be353a
|
[
"C#",
"SQL"
] | 4
|
C#
|
gpproton/DotNetTemplate1
|
f39c5e8dea1be8867d29190426dfdf6413400487
|
4563c8a2e9a4d9c6cd01934102ea0193845a7ee1
|
refs/heads/main
|
<file_sep>var express = require('express');
var router = express.Router();
var path = require('path');
var db = require('../configuration/dbConnection.js');
router.get('/:id', (req, res) => {
var query = `UPDATE users SET status='verified' WHERE id='${req.params.id}';`;
function status(){
res.redirect('/signin');
}
db.query(query, (err, res) => {
if (err) {
console.error(err);
return;
}
else{
status();
}
});
});
module.exports = router;<file_sep>var express = require('express');
var router = express.Router();
var path = require('path');
var db = require('../configuration/dbConnection.js');
var fs = require('fs');
router.get('/:username', (req, res) => {
var cityExist = false;
var stateExist = false;
var countryExist = false;
var mobileNumberExist = false;
if(req.params.username == req.cookies.user){
function status(userDetails){
if(userDetails.city != null){
cityExist = true;
}
if(userDetails.state != null){
stateExist = true;
}
if(userDetails.country != null){
countryExist = true;
}
if(userDetails.mobilenumber != null){
mobileNumberExist = true;
}
res.render('user',{
username: req.cookies.user,
user: userDetails,
mobileNumberExist: mobileNumberExist,
cityExist: cityExist,
stateExist: stateExist,
countryExist: countryExist
});
}
var query = `SELECT * FROM users WHERE username='${req.cookies.user}';`
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
else{
status(res.rows[0]);
}
});
}
else{
res.send(`<html><body><h1>You are not authorized to access this page</h1></body></html>`);
}
});
router.post('/:username', (req, res) => {
var name = req.body.name;
var email = req.body.email;
var queryCount = 1;
if(req.body.mobileNumber){
var mobileNumber = req.body.mobileNumber;
}
else{
var mobileNumber = null;
queryCount++;
}
if(req.body.city){
var city = req.body.city;
}
else{
var city = null;
queryCount++;
}
if(req.body.state){
var state = req.body.state;
}
else{
var state = null;
queryCount++;
}
if(req.body.country){
var country = req.body.country;
}
else{
var country = null;
queryCount++;
}
function status(){
queryCount--;
if(queryCount == 0){
res.redirect(`/user/${req.cookies.user}`);
}
}
var query = `UPDATE users SET name='${name}',email='${email}',mobilenumber='${mobileNumber}',city='${city}',state='${state}',country='${country}' WHERE username='${req.cookies.user}';`;
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
status();
});
if(!mobileNumber){
var query1 = `UPDATE users SET mobilenumber=null WHERE username='${req.cookies.user}';`;
db.query(query1, (err, res) => {
if(err){
console.error(err);
return;
}
status();
});
}
if(!city){
var query2 = `UPDATE users SET city=null WHERE username='${req.cookies.user}';`;
db.query(query2, (err, res) => {
if(err){
console.error(err);
return;
}
status();
});
}
if(!state){
var query3 = `UPDATE users SET state=null WHERE username='${req.cookies.user}';`;
db.query(query3, (err, res) => {
if(err){
console.error(err);
return;
}
status();
});
}
if(!country){
var query4 = `UPDATE users SET country=null WHERE username='${req.cookies.user}';`;
db.query(query4, (err, res) => {
if(err){
console.error(err);
return;
}
status();
});
}
});
router.get('/:username/classifieds', (req, res) => {
if(req.params.username == req.cookies.user){
var activeList;
var closedList;
var count = 0;
function status(classifiedsStatus, classifiedList){
count++;
if(classifiedsStatus == 'active'){
activeList = classifiedList;
}
if(classifiedsStatus == 'closed'){
closedList = classifiedList;
}
if(count == 2){
res.render('userClassifieds',{
username: req.cookies.user,
activeList: activeList,
closedList: closedList
});
}
}
var query1 = `SELECT * FROM classified WHERE status='active' and owner='${req.cookies.user}';`;
db.query(query1, (err, res) => {
if(err){
console.error(err);
return;
}
status('active',res.rows);
});
var query2 = `SELECT * FROM classified WHERE status='closed' and owner='${req.cookies.user}';`;
db.query(query2, (err, res) => {
if(err){
console.error(err);
return;
}
status('closed',res.rows);
});
}
else{
res.send(`<html><body><h1>You are not authorized to access this page</h1></body></html>`);
}
});
router.get('/:username/classifieds/:id', (req, res) => {
if(req.params.username == req.cookies.user){
var query = `SELECT *,EXTRACT(DAY FROM now() - postingdate) AS timedifference FROM classified WHERE id='${req.params.id}';`;
function status(isClassifiedExist, classified){
if(!isClassifiedExist){
res.redirect('/classifiedDoesNotExist');
}
else{
var classifiedAge;
if(classified.timedifference == 0){
classifiedAge = 'today';
}
else if(classified.timedifference == 1){
classifiedAge = 'yesterday';
}
else if(classified.timedifference < 30){
classifiedAge = `${classified.timedifference} days ago`;
}
else if(classified.timedifference < 365){
classifiedAge = `${classified.timedifference/30} months ago`
}
else{
classifiedAge = `${classified.timedifference/365} years ago`
}
res.render('userClassified',{
username: req.cookies.user,
classified: classified,
classifiedAge: classifiedAge
});
}
}
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
else{
if(!res.rows.length){
status(false,null);
}
else{
status(true,res.rows[0]);
}
}
});
}
else{
res.send(`<html><body><h1>You are not authorized to access this page</h1></body></html>`);
}
});
router.get('/:username/classifieds/:id/:action', (req, res) => {
if(req.params.username == req.cookies.user){
if(req.params.action == 'close'){
function status(){
res.redirect(`/user/${req.cookies.user}/classifieds`)
}
var query = `UPDATE classified SET status='closed' WHERE id='${req.params.id}';`;
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
status();
});
}
else if(req.params.action == 'reopen'){
function status(){
res.redirect(`/user/${req.cookies.user}/classifieds`)
}
var query = `UPDATE classified SET status='active' WHERE id='${req.params.id}';`;
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
status();
});
}
else if(req.params.action == 'delete'){
var imagename;
function status(){
res.redirect(`/user/${req.cookies.user}/classifieds`);
fs.unlink(`./public/classifiedImages/${imagename}`,(err) => {
if(err) console.log(err);
});
}
var query1 = `SELECT imagename from classified WHERE id='${req.params.id}';`;
db.query(query1, (err, res) => {
if(err){
console.error(err);
return;
}
imagename = res.rows[0].imagename;
});
var query2 = `DELETE FROM classified WHERE id='${req.params.id}';`;
db.query(query2, (err, res) => {
if(err){
console.error(err);
return;
}
status();
});
}
else if(req.params.action == 'modify'){
function status(classified){
res.render('classifiedModification', {
username: req.cookies.user,
classified: classified
});
}
query = `SELECT * FROM classified WHERE id='${req.params.id}';`;
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
status(res.rows[0]);
});
}
}
else{
res.send(`<html><body><h1>You are not authorized to access this page</h1></body></html>`);
}
});
router.post('/:username/classifieds/:id/modify', (req, res) => {
if(req.params.username == req.cookies.user){
var title = req.body.title;
var price = req.body.price;
var description = req.body.description;
var id = req.params.id;
var ownerName = req.body.ownerName;
var category = req.body.category;
var mobileNumber = req.body.mobileNumber;
var city = req.body.city;
var state = req.body.state;
var country = req.body.country;
function status(){
res.redirect(`/user/${req.cookies.user}/classifieds/${req.params.id}`);
}
query = `UPDATE classified SET title='${title}',price='${price}',description='${description}',ownername='${ownerName}',category='${category}',mobilenumber='${mobileNumber}',city='${city}',state='${state}',country='${country}' WHERE id='${id}';`;
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
else{
status();
}
});
}
else{
res.send(`<html><body><h1>You are not authorized to access this page</h1></body></html>`);
}
});
router.get('/:username/settings', (req, res) => {
if(req.params.username == req.cookies.user){
res.render('userSettings',{
username: req.cookies.user,
});
}
else{
res.send(`<html><body><h1>You are not authorized to access this page</h1></body></html>`);
}
});
router.post('/:username/settings', (req, res) => {
if(req.params.username == req.cookies.user){
var oldPassword = req.body.oldPassword;
var newPassword = req.body.newPassword;
var confirmPassword = req.body.confirmPassword;
function status(requestStatus,wrongPassword){
if(requestStatus){
res.redirect('/');
}
else{
if(wrongPassword){
res.render('userSettings',{
username: req.cookies.user,
wrongPassword: true
});
}
else{
res.render('userSettings',{
username: req.cookies.user,
requestFailed: true
});
}
}
}
var query = `SELECT * FROM users WHERE username='${req.cookies.user}' AND password=crypt('${<PASSWORD>}', password);`;
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
else{
if(res.rows.length == 1){
if(newPassword != confirmPassword){
status(false, false);
}
else{
var query = `UPDATE users SET password=crypt('${<PASSWORD>}',gen_salt('bf')) WHERE username='${req.cookies.user}';`;
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
else{
status(true, true);
}
});
}
}
else{
status(false, true);
}
}
});
}
else{
res.send(`<html><body><h1>You are not authorized to access this page</h1></body></html>`);
}
});
module.exports = router;<file_sep>var express = require('express');
var router = express.Router();
var path = require('path');
var db = require('../configuration/dbConnection.js');
router.get('/', (req, res) => {
var searchItem = req.query.searchItem.toLowerCase();
function status(classifiedList){
res.render('search',{
username: req.cookies.user,
searchItem: searchItem,
classifiedList: classifiedList
});
}
var query = `SELECT * FROM classified WHERE status='active' AND (LOWER(title) LIKE '%${searchItem}%' OR LOWER(category) LIKE '%${searchItem}%') ORDER BY postingdate DESC;`;
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
else{
status(res.rows);
}
});
})
router.post('/', (req, res) => {
var searchItem = req.query.searchItem.toLowerCase();
var city = req.body.city.toLowerCase();
var state = req.body.state.toLowerCase();
var country = req.body.country.toLowerCase();
var minPrice;
if(req.body.minprice){
minPrice = parseInt(req.body.minprice);
}
var maxPrice;
if(req.body.maxprice){
maxPrice = parseInt(req.body.maxprice);
}
if(minPrice && maxPrice && minPrice > maxPrice){
var temp = minPrice;
minPrice = maxPrice;
maxPrice = temp;
}
function status(classifiedList){
res.render('search',{
username: req.cookies.user,
searchItem: searchItem,
classifiedList: classifiedList
});
}
var query = `SELECT * FROM classified WHERE status='active' AND (LOWER(title) LIKE '%${searchItem}%' OR LOWER(category) LIKE '%${searchItem}%')`;
if(city){
query = query + ` AND LOWER(city)='${city}'`;
}
if(state){
query = query + ` AND LOWER(state)='${state}'`;
}
if(country){
query = query + ` AND LOWER(country)='${country}'`;
}
if(minPrice){
query = query + ` AND price>='${minPrice}'`;
}
if(maxPrice){
query = query + ` AND price<='${maxPrice}'`;
}
query = query + ` ORDER BY postingdate DESC;`;
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
else{
status(res.rows);
}
});
});
module.exports = router;<file_sep>var express = require('express');
var router = express.Router();
var path = require('path');
var db = require('../configuration/dbConnection.js');
router.get('/:id', (req, res) => {
var query = `SELECT *,EXTRACT(DAY FROM now() - postingdate) AS timedifference FROM classified WHERE id='${req.params.id}' and status='active';`
function status(isClassifiedExist, classified){
if(!isClassifiedExist){
res.redirect('/classifiedDoesNotExist');
}
else{
var classifiedAge;
if(classified.timedifference == 0){
classifiedAge = 'today';
}
else if(classified.timedifference == 1){
classifiedAge = 'yesterday';
}
else if(classified.timedifference < 30){
classifiedAge = `${classified.timedifference} days ago`;
}
else if(classified.timedifference < 365){
classifiedAge = `${classified.timedifference/30} months ago`
}
else{
classifiedAge = `${classified.timedifference/365} years ago`
}
res.render('classified',{
username: req.cookies.user,
classified: classified,
classifiedAge: classifiedAge
});
}
}
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
else{
if(!res.rows.length){
status(false,null);
}
else{
status(true,res.rows[0]);
}
}
});
});
module.exports = router;<file_sep>const express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var home = require('./routes/home.js');
var signin = require('./routes/signin.js');
var signup = require('./routes/signup.js');
var logout = require('./routes/logout.js');
var user = require('./routes/user.js');
var sell = require('./routes/sell.js');
var classified = require('./routes/classified.js');
var category = require('./routes/category.js');
var search = require('./routes/search.js');
var userVerification = require('./routes/userVerification.js');
var app = express();
app.set('view engine', 'pug');
app.set('views','./views');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret: 'ssshhhhh'}));
app.use(express.static('public/classifiedImages'));
app.use('/', home);
app.use('/signin', signin);
app.use('/signup', signup);
app.use('/logout', logout);
app.use('/user/', user);
app.use('/sell', sell);
app.use('/classified/',classified);
app.use('/category/',category);
app.use('/search', search);
app.use('/userVerification/',userVerification);
app.get('/db', async (req, res) => {
try {
const client = await pool.connect();
const result = await client.query('SELECT * FROM test_table');
const results = { 'results': (result) ? result.rows : null};
res.render('pages/db', results );
client.release();
} catch (err) {
console.error(err);
res.send("Error " + err);
}
});
app.listen(process.env.PORT || 5000);<file_sep>var express = require('express');
var router = express.Router();
var path = require('path');
var db = require('../configuration/dbConnection.js');
const { v4: uuidv4 } = require('uuid');
var multer = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/classifiedImages');
},
filename: function (req, file, cb) {
cb(null, 'classified-' + uuidv4() + '.' + file.mimetype.substring(file.mimetype.indexOf('/') + 1));
}
})
var upload = multer({ storage: storage })
router.get('/', (req, res) => {
if(req.cookies.user){
function status(user){
res.render('sell',{
username: req.cookies.user,
user : user
});
}
var query = `SELECT * FROM users WHERE username='${req.cookies.user}';`
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
else{
status(res.rows[0]);
}
});
}
else{
res.redirect('/signin');
}
});
router.post('/', upload.single('classifiedPhoto'),(req, res) => {
var title = req.body.title;
var price = req.body.price;
var description = req.body.description;
var id = req.file.filename.substr(req.file.filename.indexOf('-') + 1, 36);
var ownerName = req.body.ownerName;
var category = req.body.category;
var mobileNumber = req.body.mobileNumber;
var city = req.body.city;
var state = req.body.state;
var country = req.body.country;
function status(isPosted){
if(isPosted){
res.redirect('/');
}
}
if(!req.cookies.user){
res.redirect('/signin');
}
else{
var query = `INSERT INTO classified(title,price,description,owner,id,imagename,ownername,category,mobilenumber,city,state,country) VALUES('${title}','${price}','${description}','${req.cookies.user}','${id}','${req.file.filename}','${ownerName}','${category}','${mobileNumber}','${city}','${state}','${country}');`;
db.query(query, (err, res) => {
if(err){
console.error(err);
return;
}
else{
status(true);
}
});
}
});
module.exports = router;<file_sep>var express = require('express');
var router = express.Router();
var path = require('path');
var db = require('../configuration/dbConnection.js');
router.get('/', (req, res) => {
res.render('signin',{
username: req.cookies.user
});
});
router.post('/', (req, res) => {
var email = req.body.siemail;
var password = <PASSWORD>;
var username;
var query = `SELECT username FROM users WHERE email='${email}' and password=crypt('${password}', password) and status='verified';`;
function status(userExist){
if(userExist){
req.cookies.user = username;
res.cookie('user', username);
res.redirect('/');
}
else{
res.render('signin',{
username: req.cookies.user,
loginFailed : true
})
}
}
db.query(query, (err, res) => {
if (err) {
console.error(err);
return;
}
else{
if(res.rows.length){
username = res.rows[0].username;
status(true);
}
else{
status(false);
}
}
});
});
module.exports = router;
|
1ddbf9dc0f07f5a9e0b37675ac88e01bbfc49f2b
|
[
"JavaScript"
] | 7
|
JavaScript
|
amitrajakalidindi/afternoon-hallows
|
38a6c64434e1fca995cd1af0db317bd50863a272
|
4b531fb6321917aafda3e90bf25ecdef34e05d02
|
refs/heads/master
|
<file_sep>package cn.loaol.note02.service.impl;
public class ApplicationExection extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public ApplicationExection() {
}
public ApplicationExection(String message) {
super(message);
}
public ApplicationExection(Throwable cause) {
super(cause);
}
public ApplicationExection(String message, Throwable cause) {
super(message, cause);
}
public ApplicationExection(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
<file_sep>package cn.loaol.note02.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.loaol.note02.entity.Note;
import cn.loaol.note02.service.impl.NoteServiceImpl;
@Controller
@RequestMapping("note")
public class NoteController {
@Resource
NoteServiceImpl noteservice;
@RequestMapping("/getnotelist.do")
@ResponseBody
public Object getnotelist(String notebookid) {
return noteservice.notelist(notebookid);
}
@RequestMapping("/updatenote.do")
@ResponseBody
public Object updatenote(String noteid,String notetitle,String notebody) {
Note note=noteservice.noteone(noteid);
note.setNotetitle(notetitle);
note.setNotebody(notebody);
noteservice.updatenote(note);
return noteservice.updatenote(note);
}
@RequestMapping("/addnote.do")
@ResponseBody
public Object addnote(String userid,String notebookid,String notetitle) {
return noteservice.insternote(userid, notebookid, notetitle);
}
}
<file_sep>package cn.loaol.note02.service.impl;
import java.sql.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.loaol.note02.dao.NoteBookDao;
import cn.loaol.note02.entity.NoteBook;
import cn.loaol.note02.service.NoteBookService;
@Service
public class NoteBookServiceImpl implements NoteBookService{
@Resource
NoteBookDao notebookdao;
public List<NoteBook> notebooklist(String userid) {
List<NoteBook> notebooklist=notebookdao.noteBookList(userid);
return notebooklist;
}
public NoteBook notebookone(String notebookid) {
return notebookdao.notebookone(notebookid);
}
public int updatenotebook(NoteBook notebook) {
return notebookdao.updatenotebook(notebook);
}
public int insertnotebook(String userid, String notebookname) {
NoteBook notebook=new NoteBook();
notebook.setNotebookId(UUID.randomUUID().toString());
notebook.setNotebookName(notebookname);
notebook.setUserId(userid);
notebook.setNotebookTypeId("5");
notebook.setNotbookCreatetime(new Date(System.currentTimeMillis()));
return notebookdao.insertnotebook(notebook);
}
}
<file_sep>package cn.loaol.note02.dao;
import java.util.List;
import cn.loaol.note02.entity.NoteBook;
public interface NoteBookDao {
List<NoteBook> noteBookList(String userid);
NoteBook notebookone(String notebookid);
int insertnotebook(NoteBook notebook);
int updatenotebook(NoteBook notebook);
}<file_sep>driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/cloud_note?useUnicode=true&characterEncoding=UTF-8
user=root
pwd=<PASSWORD>
maxActive=20
salt=<PASSWORD><file_sep>package cn.loaol.note02.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.loaol.note02.entity.User;
import cn.loaol.note02.service.UserService;
import cn.loaol.note02.util.JsonResult;
@Controller
@RequestMapping("/user")
public class LoginController {
@Resource
UserService uservice;
@RequestMapping("/login.do")
@ResponseBody
public Object login(String name,String password) {
User user=uservice.login(name, password);
return new JsonResult(0,"登陆成功!",user);
}
@ExceptionHandler(Exception.class)
@ResponseBody
public Object exHandler(Throwable e) {
String eMsg=e.getMessage();
String[] eMsgs=eMsg.split("-");
String[] eMsgs1=eMsg.split("\\.");
int state=Integer.parseInt(eMsgs1[0]);
String messge=eMsgs[1];
return new JsonResult(state,messge,null);
}
}
<file_sep>package cn.loaol.note02.service;
import java.util.List;
import cn.loaol.note02.entity.NoteBook;
public interface NoteBookService {
List<NoteBook> notebooklist(String userid);
NoteBook notebookone(String notebookid);
int insertnotebook(String userid,String notebookname);
int updatenotebook(NoteBook notebook);
}
<file_sep>package cn.loaol.note02.test;
import java.util.List;
import java.util.UUID;
import org.junit.Test;
import cn.loaol.note02.dao.NoteDao;
import cn.loaol.note02.entity.Note;
public class TestNoteDao extends BaseTest {
@Test
public void testnotelist() {
NoteDao notedao=ctx.getBean("noteDao", NoteDao.class);
List<Note> list=notedao.notelist("6d763ac9-dca3-42d7-a2a7-a08053095c08");
System.out.println(list);
}
@Test
public void testnoteone() {
NoteDao notedao=ctx.getBean("noteDao", NoteDao.class);
Note noteone=notedao.noteone("c784305e-66fe-4356-b855-a35c15ae5383");
System.out.println(noteone);
}
@Test
public void testinsternote() {
NoteDao notedao=ctx.getBean("noteDao", NoteDao.class);
Note noteone=notedao.noteone("01da5d69-89d5-4140-9585-b559a97f9cb0");
System.out.println(noteone);
String newid=UUID.randomUUID().toString();
noteone.setNoteid(newid);
noteone.setNotetitle("更新测试1111");
noteone.setNotebody("更新测试内容11!");
noteone.setNotelastmodifytime(System.currentTimeMillis());
noteone.setNotecreatetime(System.currentTimeMillis());
System.out.println(noteone);
int rs=notedao.insertnote(noteone);
noteone=notedao.noteone(newid);
System.out.println(noteone);
}
@Test
public void testupdatenote() {
NoteDao notedao=ctx.getBean("noteDao", NoteDao.class);
Note noteone=notedao.noteone("01da5d69-89d5-4140-9585-b559a97f9cb0");
System.out.println(noteone);
noteone.setNotetitle("更新测试1111");
noteone.setNotebody("更新测试内容11!");
noteone.setNotestatusid("1");
noteone.setNotelastmodifytime(System.currentTimeMillis());
noteone.setNotecreatetime(System.currentTimeMillis());
System.out.println(noteone);
int rs=notedao.updatenote(noteone);
noteone=notedao.noteone("01da5d69-89d5-4140-9585-b559a97f9cb0");
System.out.println(noteone);
}
}<file_sep>package cn.loaol.note02.service;
import cn.loaol.note02.entity.User;
public interface UserService {
User login(String name,String password);
int regist(String name,String nick,String password,String comfirm);
}
|
2ae0e8e9ec4282bbcebadb6fbff4f51ae87d2dfd
|
[
"Java",
"INI"
] | 9
|
Java
|
gongmingshi/note02
|
1a1e713649bf4ff9be8f8ef167c356e025cd71e6
|
2590eadfe4e69d8ae090e5631c273abe88050433
|
refs/heads/master
|
<file_sep>using Plugin.Media.Abstractions;
using Rootedfuture.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Rootedfuture.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class PhotoPreview : ContentPage
{
public MediaFile PhotoPrev;
public int TreeId = 0;
private bool TaskRunning = false;
private int treeReserve;
public PhotoPreview(MediaFile photoPreview, int treeId, int reserve = 0)
{
InitializeComponent();
PhotoPrev = photoPreview;
takenPhoto.Source = ImageSource.FromStream(() => {
var stream = photoPreview.GetStream();
return stream;
});
TreeId = treeId;
treeReserve = reserve;
ButtonRetakePhoto.Clicked += ButtonRetakePhoto_Clicked;
ButtonAcceptPhoto.Clicked += ButtonAcceptPhoto_Clicked;
}
private async void ButtonAcceptPhoto_Clicked(object sender, EventArgs e)
{
if (IsAlreadyBusy())
{
await Navigation.PushModalAsync(new Loader());
var content = new MultipartFormDataContent();
content.Add(new StreamContent(PhotoPrev.GetStream()), "\"imageFile\"", $"\"{PhotoPrev.Path}\"");
content.Add(new StringContent(TreeId.ToString()), "treeId");
content.Add(new StringContent(treeReserve.ToString()), "reserve");
await ApiService.SendImageToServer(content);
if (treeReserve == 1)
{
MessagingCenter.Send<PhotoPreview>(this, "ReloadPhotoNotPlanted");
}
else
{
MessagingCenter.Send<PhotoPreview>(this, "ReloadPhoto");
}
TaskDone();
}
}
private void ButtonRetakePhoto_Clicked(object sender, EventArgs e)
{
if (treeReserve==1)
{
MessagingCenter.Send<PhotoPreview>(this, "RetakePhotoNotPlanted");
}
else
{
MessagingCenter.Send<PhotoPreview>(this, "RetakePhoto");
}
}
private bool IsAlreadyBusy()
{
if (TaskRunning)
{
return false;
}
else
{
TaskRunning = true;
return true;
}
}
private void TaskDone()
{
TaskRunning = false;
}
}
}<file_sep>using System.Collections.Generic;
using System.ComponentModel;
namespace Rootedfuture.Models
{
public class GalleryPhotoModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
List<GalleryItem> galleryItems = new List<GalleryItem>();
private bool _galleryDataLoaded = false;
public bool galleryIsEmpty = false;
public bool GalleryIsEmpty
{
get => galleryIsEmpty;
set
{
galleryIsEmpty = value;
OnPropertyChanged(nameof(GalleryIsEmpty));
}
}
public bool GalleryDataLoaded
{
get => _galleryDataLoaded;
set
{
_galleryDataLoaded = value;
OnPropertyChanged(nameof(GalleryDataLoaded));
}
}
public List<GalleryItem> GalleryPhotoList
{
get => galleryItems;
set
{
galleryItems = value;
OnPropertyChanged(nameof(GalleryPhotoList));
}
}
private void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
<file_sep>using Rootedfuture.Models;
using Rootedfuture.Services;
using Rootedfuture.Views;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using ZXing;
using ZXing.Mobile;
using ZXing.Net.Mobile.Forms;
namespace Rootedfuture
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ScanPage : ContentPage
{
ZXingScannerPage scanPage;
private ErrorModel errorModel;
private bool TaskRunning = false;
private async void RunQrScanningTask() {
if (IsAlreadyBusy())
{
await runQrScanner();
TaskDone();
}
}
public ScanPage()
{
errorModel = new ErrorModel();
InitializeComponent();
ButtonScanQrCode.Clicked += ButtonScanQrCode_Clicked;
BindingContext = errorModel;
errorModel.Status = "Please scan QR code";
MessagingCenter.Subscribe<TreeDetails>(this, "ScanAnotherOne", (sender) =>
{
Navigation.PopAsync();
RunQrScanningTask();
});
}
private void ButtonScanQrCode_Clicked(object sender, EventArgs e)
{
RunQrScanningTask();
}
private async Task runQrScanner()
{
List<BarcodeFormat> formats = new List<BarcodeFormat>();
formats.Add(BarcodeFormat.QR_CODE);
var options = new MobileBarcodeScanningOptions
{
AutoRotate = false,
UseFrontCameraIfAvailable = true,
TryHarder = true,
PossibleFormats = formats
};
scanPage = new ZXingScannerPage();
scanPage.OnScanResult += (result) =>
{
scanPage.IsScanning = false;
Device.BeginInvokeOnMainThread(async () =>
{
await Navigation.PopModalAsync();
await Navigation.PushModalAsync(new Loader());
TreeData treeData = await ApiService.GetTreeInfoAsync(result.Text);
if (treeData != null && !treeData.error)
{
//for some reson here you have to make this lines in MainThread , you did it above but the below working on Task so to update UI you should implment
//in UI MainThread
if (treeData.treeNotSold)
{
Device.BeginInvokeOnMainThread(async () =>
{
errorModel.Status = "Please scan QR code";
await Navigation.PushAsync(new NotSoldTreeView(treeData));
});
}
else
{
Device.BeginInvokeOnMainThread(async () =>
{
errorModel.Status = "Please scan QR code";
await Navigation.PushAsync(new TreeDetails(treeData));
});
//Will work ^_^
}
await Navigation.PopModalAsync();
}
else
{
await Navigation.PopModalAsync();
errorModel.Status = "Invalid code, please scan an other one";
}
});
};
await Navigation.PushModalAsync(scanPage);
}
private bool IsAlreadyBusy()
{
if (TaskRunning)
{
return false;
}
else
{
TaskRunning = true;
return true;
}
}
private void TaskDone()
{
TaskRunning = false;
}
}
}
<file_sep>using Plugin.Media;
using Plugin.Media.Abstractions;
using Rootedfuture.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Rootedfuture.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TreeDetails : ContentPage
{
private int activeTreeId = 0;
private MediaFile capturedPhoto;
private bool TaskRunning = false;
private void RunCamera() {
if (IsAlreadyBusy())
{
Navigation.PopModalAsync();
TakePicture();
}
}
public TreeDetails(TreeData treeData)
{
InitializeComponent();
MessagingCenter.Subscribe<PhotoPreview>(this, "RetakePhoto", (sender) =>
{
RunCamera();
});
MessagingCenter.Subscribe<PhotoPreview>(this, "ReloadPhoto", (sender) =>
{
Navigation.PopModalAsync();
Navigation.PopModalAsync();
});
MessagingCenter.Subscribe<DistanceNotice>(this, "DistanceAccepted", (sender) =>
{
RunCamera();
});
ButtonShowGallery.Clicked += ButtonShowGallery_Clicked;
ButtonScanAnotherTree.Clicked += ButtonScanAnotherTree_Clicked;
ButtonTakePicture.Clicked += ButtonTakePicture_Clicked;
BindingContext = treeData;
activeTreeId = treeData.id;
}
private async void TakePicture()
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("Camera", "Camera not available", "OK");
return;
}
capturedPhoto = await CrossMedia.Current.TakePhotoAsync(
new StoreCameraMediaOptions
{
PhotoSize = PhotoSize.Medium,
CompressionQuality = 75
}
);
if (capturedPhoto != null)
{
await Navigation.PushModalAsync(new PhotoPreview(capturedPhoto, activeTreeId));
}
TaskDone();
}
private async void ButtonTakePicture_Clicked(object sender, EventArgs e)
{
if (IsAlreadyBusy())
{
await Navigation.PushModalAsync(new DistanceNotice(true));
TaskDone();
}
}
private void ButtonScanAnotherTree_Clicked(object sender, EventArgs e)
{
MessagingCenter.Send<TreeDetails>(this, "ScanAnotherOne");
}
private async void ButtonShowGallery_Clicked(object sender, EventArgs e)
{
if (IsAlreadyBusy())
{
await Navigation.PushModalAsync(new Loader());
await Navigation.PushAsync(new Gallery(activeTreeId));
TaskDone();
}
}
private bool IsAlreadyBusy() {
if (TaskRunning)
{
return false;
}
else
{
TaskRunning = true;
return true;
}
}
private void TaskDone() {
TaskRunning = false;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Rootedfuture.Models
{
public class TreeData
{
public int id { get; set; }
public string productName { get; set; }
public bool error { get; set; }
public bool treeNotSold { get; set; }
public string treePhoto { get; set; }
public string projectName { get; set; }
public string treePhotoPath
{
get { return "http://rootedfutu.re/images/trees/" + treePhoto; }
set { treePhoto = value; }
}
public string treeTypeName { get; set; }
public string treeTypeDesc { get; set; }
public IList<TreeDonationList> treeDonationList { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Rootedfuture.Models
{
public class GalleryItem
{
public string file_name { get; set; }
public string treePhotoPath
{
get { return "http://rootedfutu.re/images/trees/" + file_name; }
set { file_name = value; }
}
public string created_at { get; set; }
public int daysAgo { get; set; }
public string DaysAgo
{
get {
string daysCounter = string.Empty;
switch (daysAgo)
{
case 0:
daysCounter = "Today";
break;
case 1:
daysCounter = "1 Day ago";
break;
default:
daysCounter = daysAgo.ToString() + " Days ago";
break;
}
return daysCounter;
}
set { daysAgo = Int32.Parse(value); }
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Rootedfuture.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class DistanceNotice : ContentPage
{
private bool sendToMain = true;
public DistanceNotice(bool sendType)
{
InitializeComponent();
sendToMain = sendType;
TakePictureButton.Clicked += TakePictureButton_Clicked;
}
private void TakePictureButton_Clicked(object sender, EventArgs e)
{
if (sendToMain)
{
MessagingCenter.Send<DistanceNotice>(this, "DistanceAccepted");
}
else
{
MessagingCenter.Send<DistanceNotice>(this, "DistanceAcceptedNotPlanted");
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace Rootedfuture.Models
{
public class ErrorModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string status;
public string Status
{
get => status;
set
{
if (status == value)
{
return;
}
status = value;
OnPropertyChanged(nameof(Status));
}
}
void OnPropertyChanged(string name)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
<file_sep>using Rootedfuture.Models;
using Rootedfuture.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Rootedfuture.Views
{
public partial class Gallery : ContentPage
{
private GalleryPhotoModel GalleryPhotoModel = new GalleryPhotoModel();
public Gallery(int Id)
{
InitializeComponent();
ButtonBackToInfoTop.Clicked+= ButtonBackToInfoBtm_Clicked;
ButtonBackToInfoBtm.Clicked += ButtonBackToInfoBtm_Clicked;
BindingContext = GalleryPhotoModel;
GalleryPhotoModel.GalleryDataLoaded = false;
imagesList.ItemTapped += ImagesList_ItemTapped;
LoadTreeGallery(Id);
}
private void ImagesList_ItemTapped(object sender, ItemTappedEventArgs e)
{
return;
}
private void ButtonBackToInfoBtm_Clicked(object sender, EventArgs e)
{
Navigation.PopAsync();
GalleryPhotoModel.GalleryDataLoaded = false;
}
private async void LoadTreeGallery(int Id)
{
var resultData = await ApiService.GetTreeGallery(Id);
if (resultData != null)
{
if (!resultData.Any()) {
GalleryPhotoModel.GalleryIsEmpty = true;
}
else
{
GalleryPhotoModel.GalleryDataLoaded = true;
GalleryPhotoModel.GalleryIsEmpty = false;
GalleryPhotoModel.GalleryPhotoList = resultData;
}
await Navigation.PopModalAsync();
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Rootedfuture.Models
{
public class TreePhoto
{
public string result { get; set; }
}
}
<file_sep>using Plugin.Media;
using Rootedfuture.Models;
using Plugin.Media.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Rootedfuture.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NotSoldTreeView : ContentPage
{
private bool TaskRunning = false;
private MediaFile capturedPhoto;
private int activeTreeId;
public NotSoldTreeView(TreeData treeData)
{
InitializeComponent();
BindingContext = treeData;
activeTreeId = treeData.id;
Button_GoBackToScanPage.Clicked += Button_GoBackToScanPage_Clicked;
ButtonTakePicture.Clicked += ButtonTakePicture_Clicked;
MessagingCenter.Subscribe<DistanceNotice>(this, "DistanceAcceptedNotPlanted", (sender) =>
{
RunCamera();
});
MessagingCenter.Subscribe<PhotoPreview>(this, "RetakePhotoNotPlanted", (sender) =>
{
RunCamera();
});
MessagingCenter.Subscribe<PhotoPreview>(this, "ReloadPhotoNotPlanted", (sender) =>
{
Navigation.PopModalAsync();
Navigation.PopModalAsync();
});
}
private void RunCamera()
{
if (IsAlreadyBusy())
{
Navigation.PopModalAsync();
TakePicture();
}
}
private async void TakePicture()
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("Camera", "Camera not available", "OK");
return;
}
capturedPhoto = await CrossMedia.Current.TakePhotoAsync(
new StoreCameraMediaOptions
{
PhotoSize = PhotoSize.Medium,
CompressionQuality = 75
}
);
if (capturedPhoto != null)
{
await Navigation.PushModalAsync(new PhotoPreview(capturedPhoto, activeTreeId, 1));
}
TaskDone();
}
private async void ButtonTakePicture_Clicked(object sender, EventArgs e)
{
if (IsAlreadyBusy())
{
await Navigation.PushModalAsync(new DistanceNotice(false));
TaskDone();
}
}
private void Button_GoBackToScanPage_Clicked(object sender, EventArgs e)
{
Navigation.PopAsync();
}
private bool IsAlreadyBusy()
{
if (TaskRunning)
{
return false;
}
else
{
TaskRunning = true;
return true;
}
}
private void TaskDone()
{
TaskRunning = false;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Rootedfuture.Models
{
public class TreeDonationList
{
public string Fname { get; set; }
public string Lname { get; set; }
public int donate { get; set; }
public string FullName
{
get { return $"{Fname} {Lname}"; }
}
public string Donate
{
get { return donate.ToString()+"$" ; }
set { donate = Int32.Parse(value); }
}
}
}
<file_sep>using Newtonsoft.Json;
using Rootedfuture.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Essentials;
namespace Rootedfuture.Services
{
class ApiService
{
readonly static HttpClient _httpClient = new HttpClient();
private static JsonSerializer _serializer = new JsonSerializer();
private static string apiURL = "https://rootedfutu.re/api/";
private static async Task<JsonTextReader> SendRequest(string requestURL)
{
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = new HttpResponseMessage();
if (Connectivity.NetworkAccess == NetworkAccess.Internet)
{
response = await _httpClient.GetAsync(apiURL + requestURL);
if (!response.IsSuccessStatusCode)
{
return null;
}
}
else
{
return null;
}
var reader = new StreamReader(await response.Content.ReadAsStreamAsync());
var str = new JsonTextReader(reader);
return str;
}
public static async Task<JsonTextReader> SendMultipartRequest(string requestURL, MultipartFormDataContent requestData = null)
{
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = new HttpResponseMessage();
HttpContent content = requestData;
if (Connectivity.NetworkAccess == NetworkAccess.Internet)
{
try
{
response = await _httpClient.PostAsync(apiURL + requestURL, content);
}
catch (Exception)
{
return null;
}
}
else
{
return null;
}
var reader = new StreamReader(await response.Content.ReadAsStreamAsync());
var str = new JsonTextReader(reader);
return str;
}
public static async Task<TreeData> GetTreeInfoAsync(string qrCodeNum)
{
var responseData = await SendRequest("retrieve-tree/qr/" + qrCodeNum);
if (responseData == null)
{
return null;
}
return _serializer.Deserialize<TreeData>(responseData);
}
public static async Task<List<GalleryItem>> GetTreeGallery(int id)
{
var responseData = await SendRequest("get-tree-gallery/id/" + id);
if (responseData == null)
{
return null;
}
return _serializer.Deserialize<List<GalleryItem>>(responseData);
}
public static async Task<TreePhoto> SendImageToServer(MultipartFormDataContent content)
{
var responseData = await SendMultipartRequest("update-tree", content);
if (responseData == null)
{
return null;
}
return _serializer.Deserialize<TreePhoto>(responseData);
}
}
}
|
f7ea7a361ca1dc55beaa49f640f0930474948d40
|
[
"C#"
] | 13
|
C#
|
DevStar365/Rootedfuture_Xamarin
|
5395b439ae17e36fdf2235a23217c06a76f31b4f
|
bcd2f66cb8c08951fd878851583d77cffd3aa84f
|
refs/heads/main
|
<file_sep>// first
function foo(arr) {
for (var k of arr) {
if (typeof k == 'object') {
return foo(arr.flat())
}
}
return arr
}
console.log(foo([14, [1, [
[
[3],
[4, [54, 'sdfg', [
[],
[5]
], 'oiyy']]
], 1
], 0]]))
// second
function foo(num) {
let sum = 0
if (num.toString().split('').length == 1) {
console.log(num)
} else {
num.toString().split('').forEach((val) => sum += +val)
return foo(sum)
}
}
console.log(foo(539))
// third
function foo(arr, num) {
return (num == 0) ? arr : foo(arr.concat(arr.splice(0, 1)), --num)
}
console.log(foo([1, 2, 3, 4, 5, 6], 5))
// forth
function foo(obj) {
let obj3 = new Map()
let arrvalues = [...new Set(Object.values(obj))]
for (var k of arrvalues) {
obj3.set(k, [])
for (var h in obj) {
if (obj[h] == k) {
obj3.get(k).push(h)
}
}
}
return Object.fromEntries(obj3)
}
console.log(foo({ z: '1', a: '1', b: '2', n: '1', c: '2', h: '1', d: '2', e: '1', k: '3', po: '1' }))
// fivth
// first type
function foo(arr) {
return arr.filter((val) => val.readStatus == true).sort(function(a, b) { return a.percent - b.percent });
}
console.log(foo([
{ book: 'Catcher in the Rye', readStatus: true, percent: 40 },
{ book: 'Animal Farm', readStatus: true, percent: 20 },
{ book: 'Solaris', readStatus: false, percent: 90 },
{ book: 'The Fall', readStatus: true, percent: 50 },
{ book: 'White Nights', readStatus: false, percent: 60 },
{ book: 'After Dark', readStatus: true, percent: 70 },
]))
// second type
function foo(arr) {
let arr1 = []
let arr2 = []
let arr3 = new Map()
arr.filter((val, ind) => (val.readStatus) ? arr1.push(ind) : arr2.push(ind))
let arr5 = arr.filter((val) => val.readStatus).sort(function(a, b) { return a.percent - b.percent });
let arr4 = arr.filter((val) => !val.readStatus)
for (var i = 0; i < arr.length; i++) {
arr3.set(arr1[i], arr5[i])
arr3.set(arr2[i], arr4[i])
}
return Object.fromEntries(Object.entries(Object.fromEntries(arr3)).splice(0, arr.length))
}
console.log(foo([
{ book: 'Catcher in the Rye', readStatus: true, percent: 40 },
{ book: 'zzx', readStatus: false, percent: 60 },
{ book: 'poiuyh', readStatus: true, percent: 100 },
{ book: 'Solaris', readStatus: false, percent: 90 },
{ book: 'Animal Farm', readStatus: true, percent: 20 },
{ book: 'The Fall', readStatus: true, percent: 50 },
{ book: 'White Nights', readStatus: false, percent: 60 },
{ book: 'After Dark', readStatus: true, percent: 70 },
{ book: 'hutr', readStatus: true, percent: 120 },
{ book: 'Nights', readStatus: false, percent: 150 },
{ book: 'Nigh', readStatus: false, percent: 200 },
{ book: 'oioi', readStatus: true, percent: 55 },
]))
|
abba222109a80edce55fee34c35274e32330cf6a
|
[
"JavaScript"
] | 1
|
JavaScript
|
vachhhh/homework4
|
e42282b60decec12a0bd81e212e1e32f18888c62
|
1cfa5f63a0077b31dd0b847c8aaa54749355fdef
|
refs/heads/master
|
<repo_name>lichangjin/tech_servlet<file_sep>/src/main/java/cn/tech/servlet/handler/ServletHandler.java
package cn.tech.servlet.handler;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.management.RuntimeErrorException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.tech.common.exception.TechErrorCode;
import cn.tech.common.exception.TechException;
import cn.tech.common.util.TechUtil;
import cn.tech.servlet.model.MethodType;
public class ServletHandler {
private static final Log logger = LogFactory.getLog(ServletHandler.class);
private static final byte[] syncRoot = new byte[0];
private List<UrlRewrite> mapping = new ArrayList<UrlRewrite>();
private Map<Class<?>, Object> handlers = new HashMap<>();
public ServletHandler(String config) throws TechException {
List<UrlRewrite> temp = new ArrayList<UrlRewrite>();
String file = TechUtil.getConfigFile(config);
try {
File f = new File(file);
InputStreamReader insReader = new InputStreamReader(new FileInputStream(f), "UTF-8");
@SuppressWarnings("resource")
BufferedReader in = new BufferedReader(insReader);
String line = null;
while ((line = in.readLine()) != null) {
if (!TechUtil.stringIsNullOrEmpty(line) && !line.startsWith("#")) {
String[] s = line.split("=");
if (s == null || s.length != 2)
throw new RuntimeErrorException(null, line + " is error(=).");
UrlRewrite item = new UrlRewrite();
item.setPattern(Pattern.compile(s[0]));
String[] cm = s[1].split(":");
if (cm == null || cm.length < 2)
throw new RuntimeErrorException(null, line + " is error(=).");
Class<?> clazz = Class.forName(cm[0]);
item.setClazz(clazz);
Method[] methods = clazz.getMethods();
for (Method m : methods) {
if (TechUtil.stringCompare(m.getName(), cm[1]))
item.addMethod(m);
}
temp.add(item);
if (cm.length > 2)
item.setCache_switch(TechUtil.toInt(cm[2], 0) > 0);
if (cm.length > 3)
item.setCache_time(TechUtil.toInt(cm[3], 0));
if (cm.length > 4)
item.setCheck_login(TechUtil.toInt(cm[4], 0) > 0);
if (item.getMethods().isEmpty())
throw new RuntimeErrorException(null, line + " is error(=).");
}
}
mapping = temp;
} catch (IOException e) {
throw new TechException(TechErrorCode.UNDEFINED_ERROR, e);
} catch (ClassNotFoundException e) {
throw new TechException(TechErrorCode.UNDEFINED_ERROR, e);
}
}
public Object handler(HttpServletRequest req, HttpServletResponse resp, MethodType methodType, String ext) throws TechException {
try {
String url = req.getRequestURI();
if (ext == null)
ext = TechUtil.getFileExtName(url);
String[] paths = null;
String u = null;
if (!TechUtil.stringIsNullOrEmpty(url)) {
while (url.indexOf("//") > 0)
url = url.replaceAll("//", "/");
u = methodType.name() + " " + url;
while (url.startsWith("/"))
url = url.substring(1);
if (url.endsWith(ext))
url = url.substring(0, url.length() - ext.length());
paths = url.toLowerCase().split("/");
} else
u = methodType.name() + " /";
for (UrlRewrite item : mapping) {
Matcher m = item.getPattern().matcher(u);
if (m.find()) {
for (Method method : item.getMethods()) {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length != 5)
continue;
if (!paramTypes[0].getName().equals(TechServletRequest.class.getName()))
continue;
if (!paramTypes[1].getName().equals(HttpServletResponse.class.getName()))
continue;
if (!paramTypes[2].getName().equals(methodType.getClass().getName()))
continue;
if (!paramTypes[3].getName().equals(paths.getClass().getName()))
continue;
if (!paramTypes[4].getName().equals(ext.getClass().getName()))
continue;
return method.invoke(getHandler(item.getClazz()), new Object[] { TechServletRequest.build(req), resp, methodType, paths, ext });
}
}
}
throw new TechException(TechErrorCode.UNDEFINED_ERROR, "url_write(" + u + ") is out of the config.");
} catch (TechException e) {
throw e;
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof TechException)
throw (TechException) t;
logger.error(null, e);
throw new TechException(TechErrorCode.UNDEFINED_ERROR);
} catch (Exception e) {
logger.error(null, e);
throw new TechException(TechErrorCode.UNDEFINED_ERROR);
}
}
public Object handler(String url, MethodType methodType, String ext) {
try {
boolean is_run = false;
if (ext == null)
ext = TechUtil.getFileExtName(url);
String[] paths = null;
String u = null;
if (!TechUtil.stringIsNullOrEmpty(url)) {
while (url.indexOf("//") > 0)
url = url.replaceAll("//", "/");
u = methodType.name() + " " + url;
while (url.startsWith("/"))
url = url.substring(1);
if (url.endsWith(ext))
url = url.substring(0, url.length() - ext.length());
paths = url.toLowerCase().split("/");
} else
u = methodType.name() + " /";
for (UrlRewrite item : mapping) {
Matcher m = item.getPattern().matcher(u);
if (m.find()) {
is_run = true;
// return item.getMethod().invoke(null, new Object[] { null,
// null, method, paths, ext });
for (Method method : item.getMethods()) {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length != 3)
continue;
if (!paramTypes[0].getName().equals(methodType.getClass().getName()))
continue;
if (!paramTypes[1].getName().equals(paths.getClass().getName()))
continue;
if (!paramTypes[2].getName().equals(ext.getClass().getName()))
continue;
return method.invoke(getHandler(item.getClazz()), new Object[] { methodType, paths, ext });
}
is_run = false;
}
}
if (!is_run)
throw new TechException(TechErrorCode.UNDEFINED_ERROR, "url_write(" + u + ") is out of the config.");
} catch (Exception e) {
logger.error(null, e);
}
return null;
}
private Object getHandler(Class<?> clazz) throws TechException {
Object handler = handlers.get(clazz);
if (handler == null) {
synchronized (syncRoot) {
if (handler == null) {
try {
handler = clazz.newInstance();
handlers.put(clazz, handler);
} catch (InstantiationException e) {
throw TechException.throwTechException(e);
} catch (IllegalAccessException e) {
throw TechException.throwTechException(e);
}
}
}
}
return handler;
}
class UrlRewrite {
private Pattern pattern;
private List<Method> methods = new ArrayList<Method>();
private Class<?> clazz;
private int cache_time = 60;
private boolean cache_switch = false;
private boolean check_login = false;
public boolean isCheck_login() {
return check_login;
}
public void setCheck_login(boolean check_login) {
this.check_login = check_login;
}
public boolean getCache_switch() {
return cache_switch && cache_time > 0;
}
public void setCache_switch(boolean cache_switch) {
this.cache_switch = cache_switch;
}
public int getCache_time() {
return cache_time;
}
public void setCache_time(int sec) {
this.cache_time = sec;
}
public Pattern getPattern() {
return pattern;
}
public void setPattern(Pattern pattern) {
this.pattern = pattern;
}
public List<Method> getMethods() {
return methods;
}
public void setMethods(List<Method> methods) {
this.methods = methods;
}
public void addMethod(Method method) {
if (methods == null)
methods = new ArrayList<>();
this.methods.add(method);
}
public Class<?> getClazz() {
return clazz;
}
public void setClazz(Class<?> clazz) {
this.clazz = clazz;
}
}
}<file_sep>/src/main/java/cn/tech/servlet/filter/CharacterEncodingFilter.java
package cn.tech.servlet.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class CharacterEncodingFilter implements Filter {
protected String encoding = "utf-8";
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
protected String selectEncoding(ServletRequest request) {
return this.encoding;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig config) throws ServletException {
this.filterConfig = config;
this.encoding = filterConfig.getInitParameter("encoding");
}
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
}
<file_sep>/src/main/java/cn/tech/servlet/handler/OpenHandler.java
package cn.tech.servlet.handler;
import cn.tech.common.exception.TechException;
public class OpenHandler extends ServletHandler {
private static final byte[] syncRoot = new byte[0];
private static OpenHandler instance;
public OpenHandler(String config) throws TechException {
super(config);
}
public static OpenHandler getInstance() throws TechException {
if (instance == null) {
synchronized (syncRoot) {
if (instance == null)
instance = new OpenHandler("url_rewrite.properties");
}
}
return instance;
}
}
|
4a9c158b67b4930dbea7fa3e7f59a40c5d056db3
|
[
"Java"
] | 3
|
Java
|
lichangjin/tech_servlet
|
7118c1b9880297cb3ed4753dc648ff481dd81ff5
|
362eba4c9292c072a3973d5170ce3c7f772725a2
|
refs/heads/master
|
<file_sep><!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>glumptio.us</title>
<meta name="description" content="">
<meta name="author" content="galumptious" >
<meta name="viewport" content="width=device-width">
<meta property="og:title" content="Glumptious" />
<meta property="og:type" content="company" />
<meta property="og:url" content="http://www.glumptio.us" />
<meta property="og:image" content="http://www.glumptio.us/img/fbsq.png" />
<meta property="og:site_name" content="Glumptious" />
<meta property="fb:admins" content="1267800034" />
<link rel="stylesheet/less" href="less/style.less?v2.1">
<script src="js/libs/less-1.3.0.min.js"></script>
<!-- Use SimpLESS (Win/Linux/Mac) or LESS.app (Mac) to compile your .less files
to style.css, and replace the 2 lines above by this one:
<link rel="stylesheet" href="less/style.css">
-->
<script src="js/libs/modernizr-2.5.3-respond-1.1.0.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.min.js"><\/script>')</script>
</head>
<body>
<?php require('blog/wp-load.php'); ?>
<?php include_once('analytics.php') ?>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<!--[if lt IE 7]><p class=chromeframe>Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</p><![endif]-->
<div class="container">
<h1 class="glumptious">GLUMPTIOUS</h1>
<div class="tabbable">
<ul class="nav nav-tabs"><div class="nav-tabs-bg"></div>
<li id="nav1" class="active"><a href="#home" data-toggle="tab" border="0">home</a></li>
<li id="nav2"><a href="#about" data-toggle="tab" border="0">about</a></li>
<li id="nav3"><a href="#work" data-toggle="tab" border="0">work</a></li>
<li id="nav4"><a class="opposite" href="#blog" data-toggle="tab" border="0">blog</a></li>
<li id="nav5"><a class="opposite" href="mailto:<EMAIL>.us" border="0">mailio</a></li>
<li id="nav6"><a class="opposite" href="#socio" data-toggle="tab" border="0">socio</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade active in" id="home">
<?php include_once('home.php') ?>
</div>
<div class="tab-pane fade" id="about">
<?php include_once('about.php') ?>
</div>
<div class="tab-pane fade" id="work">
<?php include_once('work.php') ?>
</div>
<div class="tab-pane fade" id="blog">
<div class="hero-unit"><span class="w_background"></span>
<?php
$posts = get_posts('numberposts=3');
foreach ($posts as $post) : start_wp(); ?>
<section style="padding: 0 20px;">
<h2 class="hero-head slideHook slide"><?php the_title(); echo "<br>" ?></h2>
<h4 class="tLine"><?php the_date(); ?></h4>
<span class="tLine" style="text-align:left;"><?php the_content(); ?></span>
</section>
<?php
endforeach;
?>
</div>
<img class="bg" src="img/bg1.gif">
</div>
<div class="tab-pane fade" id="socio">
<?php include_once('socio.php') ?>
</div>
</div>
</div>
</div>
<!-- /container -->
<script src="js/libs/bootstrap/bootstrap.min.js"></script>
<script src="js/script.js"></script>
<script src="js/bootstrap-datepicker.js"></script>
<script src="js/bootstrap-tabs.js"></script>
</body>
</html>
<file_sep>glumptio.us
===========
da site<file_sep><?php
$posts = get_posts('numberposts=3');
foreach ($posts as $post) : start_wp(); ?>
<section>
<h3><?php the_title(); echo "<br>" ?></h3>
<h4><?php the_date(); ?></h4>
<?php the_excerpt(); ?>
</section>
<?php
endforeach;
?>
<img class="bg" src="img/bg1.gif"><file_sep>!#/bin/bash
sass --watch css/sass/style.sass:css/style.css -r css/sass/bourbon/lib/bourbon.rb
|
6cec80d78173c6c77b2c87d65f8badcc24970f5c
|
[
"Markdown",
"PHP",
"Shell"
] | 4
|
PHP
|
zjr/glumptio.us
|
9f95bb6f039954e16d6b86e9366416ec71f996f8
|
3147b8a1eb7736b71990c4782fd18d4c11d79698
|
refs/heads/master
|
<repo_name>dtqdv/seminario<file_sep>/database/migrations/2016_06_19_212431_create_equipos.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEquipos extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('equipos', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('nombre' , 30);
$table->string('escudo' , 45)->nullable();
$table->integer('torneos_id')->unsigned();
$table->foreign('torneos_id')->references('id')->on('torneos');
$table->smallInteger('saldo')->nullable();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('equipos');
}
}
|
6dad286fcba82b6fe53636c1f4c988bb8ae0a4e9
|
[
"PHP"
] | 1
|
PHP
|
dtqdv/seminario
|
df1027f5bf1a97a18337c02af4ecb0b5c2c6d482
|
5dc600b6e63fc1315f6b52904ad7bfe753cd7a0e
|
refs/heads/master
|
<file_sep><?php
/**
* Created by PhpStorm.
* User: neoweb
* Date: 2016/11/29
* Time: 10:32
*/
namespace app\user\controller;
use think\Controller;
use app\user\model\Profile;
use app\user\model\Book;
use app\user\model\Role;
use app\user\model\User as UserModel;
class User extends Controller
{
// 关联插入(一对一)
public function add()
{
$user = new UserModel();
$user->name = 'thinkphp';
$user->password = '<PASSWORD>';
$user->nickname = '流年';
if ($user->save()) {
// 写入关联数据
$profile['truename'] = '刘晨';
$profile['birthday'] = '1995-03-05';
$profile['address'] = '中国上海';
$profile['email'] = '<EMAIL>';
$user->profile()->save($profile);
return '用户[ ' . $user->name . ' ]新增成功';
} else {
return $user->getError();
}
}
// 关联新增book(一对多)
public function addBook()
{
$user = UserModel::get(1);
// $book = new Book;
$book['title'] = 'ThinkPHP5快速入门';
$book['publish_time'] = '2016-05-06';
if ($user->books()->save($book)) {
return '添加Book成功';
} else {
return $user->getError();
}
}
// 关联批量新增book(一对多)
public function addBooks()
{
$user = UserModel::get(1);
$books = [
['title' => 'ThinkPHP5完全开发', 'publish_time' => '2016-05-06'],
['title' => 'ThinkPHP5开发手册', 'publish_time' => '2016-03-06'],
];
$user->books()->saveAll($books);
return '添加Book成功';
}
// 关联新增数据(多对多,角色不存在)
public function addUser()
{
$user = UserModel::getByNickname('张三');
// 新增用户角色 并自动写入枢纽表
$result = $user->roles()->save(['name' => 'editor', 'title' => '运营']);
if ($result) {
return '用户角色新增成功';
} else {
return '用户角色新增失败';
}
}
// 关联新增数据(多对多,角色不存在)
public function addUsers()
{
$user = UserModel::getByNickname('张三');
// 给当前用户新增多个用户角色
$result = $user->roles()->saveAll([
['name' => 'leader', 'title' => '领导'],
['name' => 'admin', 'title' => '管理员'],
]);
if ($result) {
return '用户角色新增成功';
} else {
return '用户角色新增失败';
}
}
// 关联新增数据(多对多,角色已存在)
public function addAttach()
{
/*
* 使用角色名关联
$user = UserModel::getByNickname('张三');
$role = Role::getByName('editor');
// 添加枢纽表数据
$user->roles()->attach($role);
return '用户角色添加成功';
*/
//使用角色id关联
$user = UserModel::getByNickname('李四');
$result = $user->roles()->attach(1);
if ($result) {
return '用户角色新增成功';
} else {
return '用户角色新增失败';
}
}
// 关联查询(一对一)
public function read($id = '')
{
$user = UserModel::get($id, 'profile');
/**
* 模型输出
*/
echo "输出数组:<br>";
dump($user->toArray());
echo "输出数组(隐藏属性):<br>";
dump($user->hidden(['create_time', 'update_time'])->toArray());
echo "输出数组(指定属性):<br>";
dump($user->visible(['id', 'nickname', 'name'])->toArray());
echo "输出数组(追加属性):<br>";
dump($user->append(['user_status'])->toArray());
echo "输出JSON:<br>";
// echo $user->toJson();
echo UserModel::get($id);
}
// 关联查询(一对多)
public function bookList()
{
$user = UserModel::get(1, 'books');
$books = $user->books;
foreach ($books as $book) {
echo $book->id . '<br>';
echo $book->title . '<br>';
echo $book->publish_time . '<br>';
echo $book->create_time . '<br>';
echo $book->update_time . '<br>';
echo $book->status . '<br>';
echo $book->user_id . '<br>';
echo '------------------------------------<br>';
}
}
// 关联查询(一对多)
public function readBook()
{
$user = UserModel::get(1);
// 获取状态为1的关联数据
$books = $user->books()->where('status', 1)->select();
dump('获取状态为1的关联数据:' . count($books));
// 获取作者写的某本书
$book = $user->books()->getByTitle('ThinkPHP5完全开发');
dump('获取作者写的某本书:' . count($book));
// 查询有写过书的作者列表
$user = UserModel::has('books')->select();
dump('查询有写过书的作者列表:' . count($user));
// 查询写过三本书以上的作者
$user = UserModel::has('books', '>=', 3)->select();
dump('查询写过三本书以上的作者:' . count($user));
// 查询写过ThinkPHP5快速入门的作者
$user = UserModel::hasWhere('books', ['title' => 'ThinkPHP5快速入门'])->distinct(true)->select();
dump('查询写过ThinkPHP5快速入门的作者(去除重复数据 ):' . count($user));
$user = UserModel::hasWhere('books', ['title' => 'ThinkPHP5快速入门'])->group(true)->select();
dump('查询写过ThinkPHP5快速入门的作者(合并重复字段 ):' . count($user));
}
// 关联查询(多对多)
public function readUser()
{
/*
$user = UserModel::getByNickname('张三');
dump($user->roles);
*/
// 预载入查询
$user = UserModel::get(1, 'roles');
dump($user->roles);
}
// 关联更新(一对一)
public function update($id)
{
$user = UserModel::get($id);
$user->name = 'framework';
if ($user->save()) {
// 更新关联数据
$user->profile->email = '<EMAIL>';
$user->profile->save();
return '用户[ ' . $user->name . ' ]更新成功';
} else {
return $user->getError();
}
/*
// 关联更新(一对多)
$user = UserModel::get($id);
$user->books()->where('title', 'ThinkPHP5快速入门')->update(['title' => 'ThinkPHP5开发手册']);
*/
}
// 关联删除
public function delete($id)
{
/*
//一对一
$user = UserModel::get($id);
if ($user->delete()) {
// 删除关联数据
$user->profile->delete();
return '用户[ ' . $user->name . ' ]删除成功';
} else {
return $user->getError();
}
//一对多
$user = UserModel::get($id);
if ($user->delete()) {
// 删除所有的关联数据
$user->books()->delete();
}
*/
//多对多(删除关联的枢纽表数据,但不会删除关联模型数据)
/*
$user = UserModel::get($id);
$role = Role::getByName('editor');
// 删除关联数据 但不删除关联模型数据
$user->roles()->detach($role);
return '用户角色删除成功';
*/
//多对多(删除用户的编辑角色并且同时删除编辑这个角色身份)
$user = UserModel::getByNickname('李四');
$role = Role::getByName('editor');
// 删除关联数据 并同时删除关联模型数据
$user->roles()->detach($role, true);
return '用户角色删除成功';
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: neoweb
* Date: 2016/12/6
* Time: 10:38
*/
namespace app\api\model;
use think\Model;
class Profile extends Model
{
protected $type = [
'birthday' => 'timestamp:Y-m-d',
];
}
|
d22e64811dba76bcf1d999b14f12f76b9abb7216
|
[
"PHP"
] | 2
|
PHP
|
nagi736933735/api
|
a21d695ea495edda73b311058324519b7c1ca016
|
1ffe0e3bb26f35a215dc146f2ae1576db1ab2795
|
refs/heads/master
|
<file_sep>
import { Terminal } from 'xterm';
import * as fullscreen from 'xterm/lib/addons/fullscreen/fullscreen';
import fromUTF8Array from './TextConvertor';
import 'xterm/dist/addons/fullscreen/fullscreen.css';
import 'xterm/dist/xterm.css';
Terminal.applyAddon(fullscreen);
function createLogWindow(wsUrl) {
const term = new Terminal({
cols: 200,
cursorBlink: false,
useStyle: true,
fontSize: 12,
});
term.open(document.getElementById('container-shell'));
const ws = new WebSocket(wsUrl);
ws.binaryType = 'arraybuffer';
ws.onmessage = (event) => {
if (typeof (event.data) === 'string') {
console.log(event.data);
return;
}
const str = fromUTF8Array(new Uint8Array(event.data));
term.write(str.replace(/\n/g, '\r\n'));
};
window.term = term;
term.setOption('disableStdin', true);
term.focus();
}
export default createLogWindow;
<file_sep>
import createTerminalWindow from './TerminalWindow';
import createLogWindow from './LogWindow';
import './index.css';
// generate websocket url
const loc = window.location;
const protocal = (loc.protocol === 'https:' ? 'wss:' : 'ws:');
const {
project, env, name, isLog,
} = window.wsArgs;
let { host } = window.wsArgs;
host = host || loc.host;
const path = isLog ? 'pods-log' : 'pods-terminal';
const wsUrl = `${protocal}//${host}/api/ws/${path}?project=${project}&env=${env}&name=${name}`;
console.log(wsUrl);
if (isLog) {
createLogWindow(wsUrl);
} else {
createTerminalWindow(wsUrl);
}
<file_sep>
// import 'zmodem.js/dist/zmodem.devel';
// import * as zmodem from 'xterm/lib/addons/zmodem/zmodem';
// import Zmodem from 'zmodem.js';
// import * as fit from 'xterm/lib/addons/fit/fit';
// import React from 'react';
// import {
// render,
// } from 'react-dom';
// import App from './App';
import Zmodem from 'zmodem.js/src/zmodem_browser';
import { Terminal } from 'xterm';
import * as fullscreen from 'xterm/lib/addons/fullscreen/fullscreen';
import fromUTF8Array from './TextConvertor';
import 'xterm/dist/addons/fullscreen/fullscreen.css';
import 'xterm/dist/xterm.css';
// https://xtermjs.org/docs/api/addons/fullscreen/
Terminal.applyAddon(fullscreen);
// Terminal.applyAddon(zmodem);
// https://xtermjs.org/docs/api/addons/fit/
// Terminal.applyAddon(fit);
function createTerminalWindow(wsUrl) {
const term = new Terminal({
// cols: 30,
// lines: 50
cursorBlink: true,
useStyle: true,
fontSize: 14,
});
term.open(document.getElementById('container-shell'));
let zsentry;
const ws = new WebSocket(wsUrl);
ws.binaryType = 'arraybuffer';
ws.onmessage = (event) => {
if (typeof (event.data) === 'string') {
console.log(event.data);
return;
}
// const rawData = window.atob(message.data); // base64 to raw
// const bin = [];
// for (let i = 0; i < rawData.length; i++) {
// bin.push(rawData.charCodeAt(i));
// }
// const utf8Array = new Uint8Array(bin);
// zsentry.consume(utf8Array);
zsentry.consume(new Uint8Array(event.data));
// term.write(String.fromCharCode(...rawData));
};
const encoder = new TextEncoder();
term.on('data', (data) => {
let binArr = data;
if (typeof (data) === 'string') {
binArr = encoder.encode(data);
}
ws.send(binArr);
});
window.term = term;
// term.toggleFullScreen(true);
// term.fit();
term.focus();
function handleReceive(zsession) {
zsession.on('offer', (offer) => {
const fileBuffer = [];
let size = 0;
const printSendedSize = () => {
term.write(`already send: ${(size / 1024 / 1024).toFixed(3)}MB\r`);
};
term.write('\r\n start download \r\n');
let last = Date.now();
offer.on('input', (payload) => {
const newPayload = new Uint8Array(payload);
fileBuffer.push(newPayload);
size += newPayload.length;
const now = Date.now();
if (now - last > 200) {
last = now;
printSendedSize();
}
});
offer.accept().then(() => {
printSendedSize();
// download (ref: zmodem_browser.save_to_disk)
const blob = new Blob(fileBuffer, { type: 'application/octet-stream' });
const url = URL.createObjectURL(blob);
const el = document.createElement('a');
el.style.display = 'none';
el.href = url;
el.download = offer.get_details().name;
document.body.appendChild(el);
el.click();
document.body.removeChild(el);
term.write('\r\ncomplate \r\n');
}, console.error.bind(console));
});
const promise = new Promise(((res) => {
zsession.on('session_end', () => {
res();
});
}));
zsession.start();
return promise;
}
function handleSend(zsession) {
return new Promise(((res) => {
const fileInput = document.getElementById('fileInput');
fileInput.click();
window.fileInput = fileInput;
fileInput.onchange = () => {
const files = fileInput.files;
Zmodem.Browser.send_files(
zsession,
files,
{
on_progress(obj, xfer) {
console.log(xfer);
},
on_file_complete(obj) {
console.log(obj);
term.write('\r\n complete \r\n');
},
},
).then(
zsession.close.bind(zsession),
console.error.bind(console),
).then(() => {
res();
});
};
}));
}
// ---------
zsentry = new Zmodem.Sentry({
to_terminal: (octets) => {
term.write(fromUTF8Array(new Uint8Array(octets)));
},
sender: (octets) => {
ws.send(new Uint8Array(octets));
},
on_retract: () => {
console.log('on_retract');
},
on_detect: (detection) => {
console.log(detection);
term.setOption('disableStdin', true);
const zsession = detection.confirm();
let promise;
if (zsession.type === 'send') {
promise = handleSend(zsession);
} else {
// receive
promise = handleReceive(zsession);
}
promise.catch(console.error.bind(console)).then(() => {
term.setOption('disableStdin', false);
});
term.setOption('disableStdin', false);
},
});
}
export default createTerminalWindow;
|
1ff51a6d9f710f2da7814a58cea07f4c80521064
|
[
"JavaScript"
] | 3
|
JavaScript
|
skywe-tang/webpack-demo
|
fc2885ba79d72efaee47ee73149bc012ff9928c9
|
ebd0def46d82c6fac7984dbe607e45e817a856cd
|
refs/heads/master
|
<repo_name>warrenwong798/news<file_sep>/handleListDisplay.php
<?php
// Here gets differnt info requested from db and send back to client side
$conn=mysqli_connect('sophia.cs.hku.hk','cywong','303519Cy') or die ('Failed to Connect '.mysqli_error($conn));
mysqli_select_db($conn,'cywong') or die ('Failed to Access DB'.mysqli_error($conn));
$query = "select * from news where headline like '%".$_GET["searchString"]."%' order by SUBSTRING_INDEX(time, ' ', -1) DESC";
$result = mysqli_query($conn, $query) or die ('Failed to query '.mysqli_error($conn));
$totalNo = mysqli_num_rows($result);
$news = array();
// while($row=mysqli_fetch_array($result)) {
// $news[]=array('newsID'=>$row['newsID'],'headline'=>$row['headline'], 'time'=>$row['time'], 'content'=>array_slice(explode(" ", $row['content']), 0, 10));
// }
//
// print json_encode(array('news' => $news ));
$loginStatus = 0;
if (isset($_COOKIE['userID'])){
$loginStatus = 1;
}
while($row=mysqli_fetch_array($result)) {
$news[]=array('newsID'=>$row['newsID'],'headline'=>$row['headline'], 'time'=>$row['time'], 'content'=>array_slice(explode(" ", $row['content']), 0, 10));
}
print json_encode(array('totalNo'=>$totalNo,'news'=>$news, 'loginStatus'=>$loginStatus));
?>
<file_sep>/handleLogin.php
<?php
// It finds record matching username th verify it first, then find record match both username and pw
// This can distinguish the user inputting incorrect pw or username
// also setcookie and return success or err msg
$conn=mysqli_connect('sophia.cs.hku.hk','cywong','303519Cy') or die ('Failed to Connect '.mysqli_error($conn));
mysqli_select_db($conn,'cywong') or die ('Failed to Access DB'.mysqli_error($conn));
$query = "select * from users where name = '".$_GET['username']."'";
$result = mysqli_query($conn, $query) or die ('Failed to query '.mysqli_error($conn));
if (mysqli_num_rows($result) == 0){
print "Username is incorrect";
}
else{
$query2 = "select * from users where name = '".$_GET['username']."' and password = '".$_GET['password']."'";
$result2 = mysqli_query($conn, $query2) or die ('Failed to query '.mysqli_error($conn));
// print "ok";
if (mysqli_num_rows($result2) == 0){
print "Password is incorrect";
}
else{
$users = array();
while($row=mysqli_fetch_array($result2)) {
$users[]=array('userID'=>$row['userID'],'name'=>$row['name'], 'password'=>$row['password'], 'icon'=>$row['icon']);
}
setcookie("userID", $users[0]['userID'], time() + (3600),"/");
print "login success";
}
}
?>
<file_sep>/readme.txt
A small part of codes in this assignment is not written by me,
including jquery-3.1.1.min.js, bootstrap.min.js and font-awesome.min.js(including font style files linking inside)
Credit to framework, library, template, icons providers of all related materials in this project
The above-mentioned materials provides free license for developers to use them
Also,
credit to Freepik providing free icon online (http://www.flaticon.com/free-icon/lace_254068), the icons are taken
from the link for testing purpose of this assignment
Apart from the above-mentioned parts, all codes in this project is done by me.
For the basic functions of this project, I use jQuery for sending ajax, changing, adding or deleting elements in the html page.
php is used for server-client interactions.
For the layout, I use grid system of bootstrap for basic styling that enable simple responsive features.
The accurate design of layout is written by me in style.css
This project perform sorting for all comments or news according to their time, with the latest one at the top.
This project provides function to browse news and search news from db
Together with login, logout and comment functions
At the top of each page will have comment to introduce the basic algorithm of the page of code.
<file_sep>/login.php
<!DOCTYPE html>
<head>
<!-- This page responsible to retrieving login info and send to server for authentication -->
<link href="bootstrap.min.css" rel="stylesheet">
<link href="style.css" rel="stylesheet">
<script src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function login(){
var userName = $("#userName").val();
var password = $("#password").val();
if ((userName == "") || (password == "")){
alert("Please enter username and password");
return;
}
$.ajax({
url: 'handleLogin.php?username=' + userName + '&password=' + password,
type: 'get',
dataType: 'text',
success: function(responseText){
if (responseText == "login success"){
$("#heading").html("You have successfully logged in");
$("#loginData").hide();
}
else{
$("#heading").html(responseText);
}
}
});
}
</script>
</head>
<body>
<div class="conatiner">
<div class="col-xs-12 text-center">
<h3 id="heading">You can log in here</h3>
</div>
<div id="loginData">
<div class="col-xs-8 col-xs-offset-4 input-field input-field-name">
<div class="col-xs-2">
User Name:
</div>
<div class="col-xs-10">
<input type="text" value="" id = "userName"/>
</div>
</div>
<div class="col-xs-8 col-xs-offset-4 input-field input-field-pw">
<div class="col-xs-2">
Password:
</div>
<div class="col-xs-10">
<input type="text" value="" id = "password"/>
</div>
</div>
<div class="col-xs-12 text-center">
<button id="submit" onclick="login()">Submit</button>
</div>
</div>
<div id="goBack" class="col-xs-12">
</div>
</div>
<script>
var goBack = <?php if ($_GET['newsID'] != "0"){
echo "'displayNewsEntry.php?newsID=".$_GET['newsID']."'";
}
else{
$html = "'index.html'";
echo $html;
} ?>;
$("#goBack").html("<a href = '" + goBack + "'> Go Back</a>");
</script>
</body>
<file_sep>/handlePostComment.php
<?php
// It post new comment to db and retrieve all new comments to client side
$conn=mysqli_connect('sophia.cs.hku.hk','cywong','303519Cy') or die ('Failed to Connect '.mysqli_error($conn));
mysqli_select_db($conn,'cywong') or die ('Failed to Access DB'.mysqli_error($conn));
$query = "select * from comments";
$result = mysqli_query($conn, $query) or die ('Failed to query '.mysqli_error($conn));
$totalNo = mysqli_num_rows($result);
$totalNo = $totalNo + 1;
$time = $_POST['month']." ".$_POST['date']." ".$_POST['year'];
$query2 = "insert into comments (commentID, newsID , userID, content, time) values ('".$totalNo."', '".$_POST['newsID']."','".$_COOKIE['userID']."','".$_POST['comment']."','".$time."')";
$result2 = mysqli_query($conn, $query2) or die ('Failed to query '.mysqli_error($conn));
$query3 = "select * from comments where commentID > ".$_POST['commentID']." and newsID = '".$_POST['newsID']."'";
$result3 = mysqli_query($conn, $query3) or die ('Failed to query '.mysqli_error($conn));
$newComments = array();
while($row = mysqli_fetch_assoc($result3)) {
$query4 = "select * from users where userID = '".$row['userID']."'";
$result4 = mysqli_query($conn, $query4) or die ('Failed to query '.mysqli_error($conn));
$icon = "";
$name = "";
while($row2 = mysqli_fetch_assoc($result4)){
$icon = $row2['icon'];
$name = $row2['name'];
}
$newComments[] = array('commentID'=>$row['commentID'], 'newsID'=>$row['newsID'],'userID'=>$row['userID'], 'time'=>$row['time'], 'content'=>$row['content'], 'icon'=>$icon, 'name'=>$name);
}
print json_encode(array('newComments'=>$newComments));
?>
<file_sep>/displayNewsEntry.php
<?php
// This obtain detail info of news and allow user post cm after login
$conn=mysqli_connect('sophia.cs.hku.hk','cywong','303519Cy') or die ('Failed to Connect '.mysqli_error($conn));
mysqli_select_db($conn,'cywong') or die ('Failed to Access DB'.mysqli_error($conn));
$query = "select * from news where newsID = ".$_GET["newsID"];
$result = mysqli_query($conn, $query) or die ('Failed to query '.mysqli_error($conn));
$news = array();
while($row = mysqli_fetch_assoc($result)) {
$news[] = array('newsID'=>$row['newsID'],'headline'=>$row['headline'], 'time'=>$row['time'], 'content'=>$row['content']);
}
// $news = json_encode($news);
?>
<!DOCTYPE html>
<head>
<link href='bootstrap.min.css' rel='stylesheet'>
<link href='font-awesome.min.css' rel='stylesheet'>
<link href='style.css' rel='stylesheet'>
<script src='jquery-3.1.1.min.js'></script>
</head>
<body>
<div class='col-xs-12'>
<div class="col-xs-12 text-center">
<!-- <div class="text-left" style="max-width:100px;"> -->
<a class="arrow" href="index.html"><i class="fa fa-arrow-left fa-4x" aria-hidden="true"></i></a>
<!-- </div> -->
<?php
print "<h2>".$news[0]['headline']."</h2>".$news[0]['time'];
?>
</div>
<div class="col-xs-12">
<?php
print "<h4 class='newsContent'>".$news[0]['content']."</h4>";
?>
</div>
<div class="col-xs-12" id="comments">
<?php
$query2 = "select * from comments where newsID = ".$_GET["newsID"]." order by SUBSTRING_INDEX(time, ' ', -1) DESC";
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$results = mysqli_query($conn, $query2) or die ('Failed to query '.mysqli_error($conn));
$comments = array();
$i = 0;
while($row3 = mysqli_fetch_assoc($results)) {
// $comments[] = array('commentID'=>$row3['commentID'], 'newsID'=>$row3['newsID'],'userID'=>$row3['userID'], 'time'=>$row3['time'], 'content'=>$row3['content']);
// $query3 = "select * from users where userID =".$comments[$i]['userID'];
$query3 = "select * from users where userID =".$row3['userID'];
$userResults = mysqli_query($conn, $query3) or die ('Failed to query '.mysqli_error($conn));
$users = array();
$j = 0;
$name ="";
$icon="";
while($row2 = mysqli_fetch_assoc($userResults)){
$users[] = array('userID'=>$row2['userID'], 'name'=>$row2['name'], 'password'=>$<PASSWORD>['<PASSWORD>'], 'icon'=>$row2['icon']);
// print "<div class='col-xs-12 comment'><div class='col-xs-2'><img src='".$users[$j]['icon']."'/></div><div class='col-xs-2'><h4>".$users[$j]['name']."</h4></div><div class='col-xs-8 text-center'>".$comments[$i]['time']."<br/>".$comments[$i]['content']."</div></div>";
// $j = $j + 1;
// $users[] = array('userID'=>$row2['userID'], 'name'=>$row2['name'], 'icon'=>$row2['icon'],'commentID'=>$row3['commentID'], 'newsID'=>$row3['newsID'], 'time'=>$row3['time'], 'content'=>$row3['content']);
$name = $row2['name'];
$icon = $row2['icon'];
}
$comments[] = array('commentID'=>$row3['commentID'],'userID'=>$row3['userID'], 'time'=>$row3['time'],'content'=>$row3['content'], 'name'=>$name,'icon'=>$icon);
$i = $i + 1;
}
?>
<script>
var cm = <?php print json_encode(array('cm'=>$comments)); ?>;
cm.cm.sort(function(x,y){
var xDate = new Date(x.time);
var yDate = new Date(y.time);
if (xDate > yDate){
return -1;
}
if (xDate < yDate){
return 1;
}
return 0;
});
for (var i = 0; i < cm.cm.length; i++){
$("#comments").append("<div class='col-xs-12 comment'><div class='col-xs-2'><img src='" + cm.cm[i]['icon'] + "'/></div><div class='col-xs-2'><h4>" + cm.cm[i]['name'] + "</h4></div><div class='col-xs-8 text-center'>" + cm.cm[i]['time'] + "<br/>" + cm.cm[i]['content'] + "</div></div>");
}
</script>
</div>
<div id="commentArea" class="col-xs-12">
<div class='col-xs-6 col-xs-offset-2'>
<input class="col-xs-12" type='text' id='commentBox'/>
</div>
<div class='col-xs-4'>
<a id='loginButton' href="login.php?newsID=<?php echo $_GET['newsID']?>"><button>Login to Comment</button></a>
<button id='commentButton' onclick="postComment()">Post Comment</button>
</div>
</div>
</div>
<script>
function postComment(){
if ($("#commentBox").val() == ""){
alert("No comment has been entered");
}
else{
var monthName = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var time = new Date();
var month = monthName[time.getMonth()];
var day = time.getDate();
var year = time.getFullYear();
var newsID = <?php echo $_GET['newsID']; ?>;
if (cm.cm.length == 0){
var commentID = 0;
}
else{
var commentID = cm.cm[0]['commentID'];
}
$.ajax({
type: "post",
url: "handlePostComment.php",
dataType: "json",
data: {comment: $("#commentBox").val(), newsID: newsID, commentID: commentID, date: day, month: month, year: year},
success: function (responseText){
$("#commentBox").val("");
responseText.newComments.sort(function(x,y){
var xDate = new Date(x.time);
var yDate = new Date(y.time);
if (xDate > yDate){
return -1;
}
if (xDate < yDate){
return 1;
}
return 0;
});
for (var i = 0; i < responseText.newComments.length; i++){
$("#comments").prepend("<div class='col-xs-12 comment'><div class='col-xs-2'><img src='" + responseText.newComments[i]['icon'] + "'/></div><div class='col-xs-2'><h4>" + responseText.newComments[i]['name'] + "</h4></div><div class='col-xs-8 text-center'>" + responseText.newComments[i]['time'] + "<br/>" + responseText.newComments[i]['content'] + "</div></div>");
}
}
});
}
}
function getCookie(cname, callback) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
callback(c.substring(name.length,c.length));
return;
}
}
callback("");
}
function init(cookie){
var userID = cookie;
if (userID != ""){
$("#loginButton").hide();
$("#commentButton").show();
$("#commentBox").prop('disabled', false);
// console.log("1");
}
else{
$("#loginButton").show();
$("#commentButton").hide();
$("#commentBox").prop('disabled', true);
// console.log("2");
}
}
$(document).ready(getCookie("userID", init));
</script>
</body>
<file_sep>/handleLogout.php
<?php
// It removes cookies to logout
if (isset($_COOKIE['userID'])){
unset($_COOKIE['userID']);
setcookie('userID', null, -1, '/');
print "logout success";
}
else{
print "User is not logged in yet";
}
?>
|
a931d22414614ead6eb5610c337741f1c0da71b3
|
[
"Text",
"PHP"
] | 7
|
PHP
|
warrenwong798/news
|
052d6514a24c757f42a7df04ee2ca18c91dc936d
|
9105e57ab01000bbd57a47b87fe8a2860c4b1125
|
refs/heads/master
|
<file_sep>require('./bootstrap');
let checkbox = document.querySelectorAll('.flag');
function checkedRecord(event) {
let el = event.target;
let type = el.getAttribute('data-type');
let record_id = el.getAttribute('data-id');
let value = el.checked;
axios.post('/expenses/checked', {
type, record_id, value
}).then((response) => {
console.log(response.data);
})
}
if (checkbox) {
checkbox.forEach(function (item) {
item.addEventListener('click', checkedRecord);
});
}<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Models\Receipt;
class ReceiptController extends Controller
{
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Receipt $receipt)
{
$url = Storage::url($receipt->path);
return "<img src='$url'>";
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\Models\Project;
class ProjectsSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
if(Project::count() < 1) {
Project::insert([
['project_name' => 'Project #1'],
['project_name' => 'Project #2'],
['project_name' => 'Project #3'],
['project_name' => 'Project #4'],
['project_name' => 'Project #5'],
]);
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Http\Requests\ExpenseCreateRequest;
use Illuminate\Http\Request;
use League\Flysystem\Exception;
use App\Models\Category;
use App\Models\Company;
use App\Models\Employee;
use App\Models\Expense;
use App\Models\Project;
use App\Models\Type;
use App\Models\Receipt;
use App\Models\Reimbursement;
class ExpenseController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$expenses = Expense::orderBy('date', 'DESC')->get();
return view('expenses.index', compact('expenses'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$categories = Category::orderBy('category_name')->get();
$companies = Company::orderBy('company_name')->get();
$employees = Employee::orderBy('first_name')->get();
$projects = Project::orderBy('project_name')->get();
$types = Type::orderBy('type_name')->get();
return view('expenses.create', compact('categories', 'companies', 'employees', 'projects', 'types'));
}
/**
* Store a newly created resource in storage.
*
* @param ExpenseCreateRequest $request
* @return \Illuminate\Http\Response
*/
public function store(ExpenseCreateRequest $request)
{
$expense = Expense::create($request->all());
if ($request->receipt && $expense) {
foreach ($request->receipt as $key => $receipt) {
$path = $receipt->store('public/expenses_receipts');
$filename = $receipt->getClientOriginalName();
$receipt = new Receipt();
$receipt->expense_id = $expense->id;
$receipt->path = $path;
$receipt->original_name = $filename;
$receipt->save();
}
}
return redirect()->route('expenses.index');
}
/**
* Display the specified resource.
*
* @param \App\Expense $expense
* @return \Illuminate\Http\Response
*/
public function show(Expense $expense)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Expense $expense
* @return \Illuminate\Http\Response
*/
public function edit(Expense $expense)
{
$categories = Category::orderBy('category_name')->get();
$companies = Company::orderBy('company_name')->get();
$employees = Employee::orderBy('first_name')->get();
$projects = Project::orderBy('project_name')->get();
$types = Type::orderBy('type_name')->get();
return view('expenses.create', compact('categories', 'companies', 'employees', 'projects', 'types', 'expense'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Expense $expense
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Expense $expense)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Expense $expense
* @return \Illuminate\Http\Response
*/
public function destroy(Expense $expense)
{
//
}
public function checked(Request $request)
{
$receipts = Receipt::where($request->type . '_id', $request->record_id)->get();
$expense = Expense::find($request->record_id);
$expense_amount = $expense->amount;
$reimbursements = Reimbursement::where('expense_id', $expense->id)->get();
$reimbursement_amount = 0;
foreach ($reimbursements as $reimbursement) {
$reimbursement_amount += $reimbursement->amount;
}
// return response()->json($reimbursement_amount >= $expense_amount);
$expense->checked = (int) $request->value;
if (!$receipts->count() || $reimbursement_amount < $expense_amount) {
$expense->save();
return response()->json(true);
}
return response()->json(false);
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Receipt extends Model
{
public function expense()
{
return $this->belongsTo(Expense::class);
}
public function reimbursement()
{
return $this->belongsTo(Reimbursement::class);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\Models\Employee;
class EmployeesSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
if(Employee::count() < 1) {
Employee::insert([
['first_name' => '<NAME>', 'last_name' => '<NAME>', 'email' => '<EMAIL>'],
['first_name' => '<NAME>', 'last_name' => '<NAME>', 'email' => '<EMAIL>'],
['first_name' => '<NAME>', 'last_name' => '<NAME>', 'email' => '<EMAIL>'],
]);
}
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Reimbursement extends Model
{
protected $fillable = [
'expense_id',
'date',
'amount',
'comment'
];
public function receipts()
{
return $this->hasMany(Receipt::class);
}
public function expense()
{
return $this->belongsTo(Expense::class);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\Models\Category;
class CategoriesSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
if(Category::count() < 1) {
Category::insert([
['category_name' => 'Category #1'],
['category_name' => 'Category #2'],
['category_name' => 'Category #3'],
['category_name' => 'Category #4'],
['category_name' => 'Category #5'],
]);
}
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'ExpenseController@index');
Route::resources([
'expenses' => 'ExpenseController',
'reimbursements' => 'ReimbursementController',
]);
Route::post('/expenses/checked', 'ExpenseController@checked');
Route::get('/receipts/{receipt}', 'ReceiptController@show')->name('receipts.show');<file_sep><?php
use Illuminate\Database\Seeder;
use App\Models\Company;
class CompaniesSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
if(Company::count() < 1) {
Company::insert([
['company_name' => 'Company #1'],
['company_name' => 'Company #2'],
['company_name' => 'Company #3'],
['company_name' => 'Company #4'],
['company_name' => 'Company #5'],
]);
}
}
}
<file_sep>
## Installation
###### Please, read official documentation before the installation process
https://laravel.com/docs/6.x/installation
#### 1. Clone the project
`git clone https://github.com/den1ohar`
#### 2. Install dependencies via Composer
`composer install`
#### 3. Create `.env` file and set the following credentials
```angular2html
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=mysql_user_name
DB_PASSWORD=<PASSWORD>
```
###### Pay attention to `DB_DATABASE`, `DB_USERNAME`, `DB_PASSWORD`
#### 4. Run the following command:
```angular2html
php artisan key:generate
php artisan migrate
php artisan db:seed
```<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Expense;
use App\Models\Reimbursement;
use App\Models\Receipt;
use App\Http\Requests\ReimbursementCreateRequest;
class ReimbursementController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$reimbursements = Reimbursement::orderBy('date', 'DESC')->get();
return view('reimbursements.index', compact('reimbursements'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$expenses = Expense::orderBy('date', 'DESC')->get();
return view('reimbursements.create', compact('expenses'));
}
/**
* Store a newly created resource in storage.
*
* @param ReimbursementCreateRequest $request
* @return \Illuminate\Http\Response
*/
public function store(ReimbursementCreateRequest $request)
{
$reimbursement = Reimbursement::create($request->all());
if ($request->receipt && $reimbursement) {
foreach ($request->receipt as $key => $receipt) {
$path = $receipt->store('public/reimbursement');
$filename = $receipt->getClientOriginalName();
$receipt = new Receipt();
$receipt->reimbursement_id = $reimbursement->id;
$receipt->path = $path;
$receipt->original_name = $filename;
$receipt->save();
}
}
return redirect()->route('reimbursements.index');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Reimbursement $reimbursement)
{
$expenses = Expense::orderBy('date', 'DESC')->get();
return view('expenses.create', compact('expenses', 'reimbursement'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ExpenseCreateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
"date" => "required|date",
"type_id" => "nullable|exists:types,id",
"category_id" => "nullable|exists:categories,id",
"amount" => "required|numeric",
"comment" => "nullable|string|max:3000",
"company_id" => "required|exists:companies,id",
"project_id" => "nullable|exists:projects,id",
"employee_id" => "nullable|exists:employees,id",
"note" => "nullable|string|max:250",
"receipt" => "nullable",
];
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\Models\Type;
class TypesSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
if(Type::count() < 1) {
Type::insert([
['type_name' => 'Type #1'],
['type_name' => 'Type #2'],
['type_name' => 'Type #3'],
['type_name' => 'Type #4'],
['type_name' => 'Type #5'],
]);
}
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Expense extends Model
{
protected $fillable = [
'date',
'type_id',
'category_id',
'amount',
'comment',
'company_id',
'project_id',
'employee_id',
'note'
];
public function receipts()
{
return $this->hasMany(Receipt::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function company()
{
return $this->belongsTo(Company::class);
}
public function employee()
{
return $this->belongsTo(Employee::class);
}
public function project()
{
return $this->belongsTo(Project::class);
}
public function type()
{
return $this->belongsTo(Type::class);
}
public function reimbursement()
{
return $this->belongsTo(Reimbursement::class);
}
}
|
f7eb11660efca79fa42ee564ce9c148604752b19
|
[
"JavaScript",
"Markdown",
"PHP"
] | 15
|
JavaScript
|
den1ohar/laravel6
|
082aa03d73fcae44dd7f3eedbe9cf25e63e2636d
|
f908ce97b6636febe4efcdb252fb8f340bba6eea
|
refs/heads/master
|
<repo_name>suzukaze/dotfiles<file_sep>/bin/gitbrd
#!/usr/bin/env ruby
branch = `git br | peco`
branch.chop!
system("git br -D #{branch}")
<file_sep>/makefile
DOTFILES_GITHUB := "https://github.com/suzukaze/dotfiles"
DOTFILES_EXCLUDES := .DS_Store .git .gitmodules .travis.yml
DOTFILES_TARGET := $(wildcard .??*) bin
DOTFILES_DIR := $(PWD)
DOTFILES_FILES := $(filter-out $(DOTFILES_EXCLUDES), $(DOTFILES_TARGET))
all: install
test:
@prove $(PROVE_OPT) $(wildcard ./etc/test/*_test.pl)
help:
@echo "make list #=> List the files"
@echo "make update #=> Fetch changes"
@echo "make deploy #=> Create symlink"
@echo "make init #=> Setup environment"
@echo "make install #=> Updating, deploying and initializng"
@echo "make clean #=> Remove the dotfiles"
@echo "make brew #=> Update brew packages"
@echo "make cask #=> Update cask packages"
list:
@$(foreach val, $(DOTFILES_FILES), ls -dF $(val);)
update:
git pull origin master
git submodule init
git submodule update
git submodule foreach git pull origin master
deploy:
@echo 'Start deploy dotfiles current directory.'
@echo 'If this is "dotdir", curretly it is ignored and copy your hand.'
@echo ''
@$(foreach val, $(DOTFILES_FILES), ln -sfnv $(abspath $(val)) $(HOME)/$(val);)
init:
@$(foreach val, $(wildcard ./etc/init/*.sh), bash $(val);)
ifeq ($(shell uname), Darwin)
@$(foreach val, $(wildcard ./etc/init/osx/*.sh), bash $(val);)
homebrew:
@bash $(DOTFILES_DIR)/etc/init/osx/install_homebrew.sh
brew: homebrew
@bash $(DOTFILES_DIR)/etc/init/osx/Brewfile
endif
install: update deploy init
@exec $$SHELL
clean:
@echo 'Remove dot files in your home directory...'
@-$(foreach val, $(DOTFILES_FILES), rm -vrf $(HOME)/$(val);)
-rm -rf $(DOTFILES_DIR)
<file_sep>/bin/delete_link_row
#!/usr/bin/env ruby
#
# httpを含む行を削除
#
contents = ""
if ARGV.length == 1
filename = ARGV[0]
File.open(filename) do |file|
file.each_line do |line|
next if line =~ /http/
contents << line
end
end
else
IO.popen('pbpaste', 'r') do |f|
f.each_line do |line|
next if line =~ /http/
contents << line
end
end
end
puts contents
IO.popen('pbcopy', 'w') {|f| f << contents} # クリップボードにコピーします
<file_sep>/etc/init/osx/install_brew_packages.sh
#!/bin/bash
trap 'echo Error: $0: stopped; exit 1' ERR INT
set -u
set -e
#
# A system that judge if this script is necessary or not
#
# Testing the judgement system
echo -n 'Install Homebrew packages? (y/N) '
read
if [[ "$REPLY" =~ ^[Yy]$ ]]; then
bash "$(dirname "${BASH_SOURCE}")"/Brewfile
fi
# vim:fdm=marker
<file_sep>/bin/mou
#!/bin/bash
if test $# -eq 0; then
`open -a Mou`
elif test $# -eq 1; then
`touch ${1}`
`open -a Mou ${1}`
fi
<file_sep>/bin/rm_node_modules
#!/bin/bash
rm -rf node_modules
cd client && rm -rf node_modules
<file_sep>/bin/make_dir_with_date
#!/usr/bin/env ruby
require 'date'
require 'fileutils'
def format_date(date)
str = "#{date.strftime("%Y_%m%d")}"
end
if ARGV.size < 1
puts <<"EOS"
usage: make_dir_with_date [prefix_dir] [diff day(option)]
ex : make_dir_with_date image
$ ls
image_2015_0227
EOS
exit
end
prefixdir = ARGV[0]
base_date = Date.today
# 第1引数から今日の日付をたす
if ARGV.length >= 2
base_date += ARGV[0].to_i
end
date = format_date(base_date)
dir = "#{prefixdir}_#{date}"
FileUtils.mkdir_p(dir) unless FileTest.exist?(dir)
puts dir
IO.popen('pbcopy', 'w') {|f| f << dir} # クリップボードにコピーします
<file_sep>/bin/cpwd
#!/usr/bin/env ruby
#
# pwdの結果をクリップボードに入れる
#
#
path = `pwd`
path.chomp! # 改行コードを削除
puts path
IO.popen('pbcopy', 'w') {|f| f << path} # クリップボードにコピーします
<file_sep>/bin/rgbconverter
#! /usr/bin/env ruby
require 'rubygems'
require 'thor'
class RgbConverter < Thor
desc "hex r g b", "convert to hex"
def hex(r, g, b)
hex_r = r.to_i.to_s(16)
hex_g = g.to_i.to_s(16)
hex_b = b.to_i.to_s(16)
hex_argb = "#ff#{hex_r}#{hex_g}#{hex_b}"
IO.popen('pbcopy', 'w') {|f| f << hex_argb} # クリップボードにコピーします
puts hex_argb
end
desc "hex_rgb rgb [delimiter]", "convert to hex"
def hex_rgb(rgb, delimiter='.')
split_rgb = rgb.split(delimiter)
red = green = blue = 0
split_rgb.each do |val|
case val[0]
when 'R', 'r'
red = val[1..-1].to_i
when 'G', 'g'
green = val[1..-1].to_i
when 'B', 'b'
blue = val[1..-1].to_i
end
end
hex(red.to_s, green.to_s, blue.to_s)
end
end
RgbConverter.start
<file_sep>/bin/write_clip
#!/usr/bin/env ruby
#
# クリップボードに書き込みます
#
if ARGV.length == 0
puts "write_clip [to_clip_command]"
end
to_clip_command = ARGV.join(" ")
puts to_clip_command
IO.popen('pbcopy', 'w') {|f| f << to_clip_command} # クリップボードにコピーします
<file_sep>/bin/datef
#!/usr/bin/env ruby
require 'date'
date = Date.today.strftime("%Y%m%d")
puts date
IO.popen('pbcopy', 'w') {|f| f << date} # クリップボードにコピーします
<file_sep>/etc/init/install
#!/bin/sh
# This shell script conforms to POSIX.
# An interrupt (typically ^C) has the effect of aborting the current command
trap 'e_error "Abort the command that is in progress"; exit 1' INT
trap 'e_error "Some error has occurred"; exit 1' ERR
#set -e
set -u
# Pilot of dotfiles
# It shows the use of dotfiles and describe what is inside
# regardless of execution or non-execution
#
cat <<-'EOT'
| | | | / _(_) |
__| | ___ | |_| |_ _| | ___ ___
/ _` |/ _ \| __| _| | |/ _ \/ __|
| (_| | (_) | |_| | | | | __/\__ \
\__,_|\___/ \__|_| |_|_|\___||___/
*** WHAT'S INSIDE? ***
1. Download https://github.com/b4b4r07/dotfiles.git
2. Symlinking dot files to your home directory
3. Execute all sh files within 'etc/init/` (optional)
See the README for documentation.
https://github.com/b4b4r07/dotfiles
Copyright (c) 2014 "BABAROT" aka @b4b4r07
Licensed under the MIT license.
EOT
# Insert newline
e_newline() { printf "\n"; }
# Normal style of writing
#e_header() { printf "\n\033[1m%s\033[0m\n" "$*"; }
e_header() { printf "\033[1m%s\033[0m\n" "$*"; }
# Success
e_success() { printf " \033[1;32m✔\033[0m %s\n" "$*"; }
# Failure
e_error() { printf " \033[1;31m✖\033[0m %s\n" "$*" 1>&2; }
# Result
e_arrow() { printf " \033[1;34m➜\033[0m %s\n" "$*"; }
# Check if exists
#is_exist() { which "$1" >/dev/null 2>&1; return $?; }
is_exist() { [ -x "$(which "$1")" ]; }
# Set dotfiles environment valuable
DOTFILES=~/.dotfiles; export DOTFILES
# This is a make install, which is functionize
# To execute all sh files within etc/init/.
# Also, this initialize function has interactive system and works as a selector
initialize()
{
prompt_menu() {
local prompt nums
e_header "Run the following init scripts."
if _prompt_menu_draws "To edit this list, press any key except ENTER. " -1 && read -rp "Enter to Go> " && [ -n "$REPLY" ]; then
prompt="Press number to toggle, r/R to reverse (Separate options with spaces): "
while _prompt_menu_draws "$1" 1 && read -rp "$prompt" nums && [ "$nums" != '' ]; do
_prompt_menu_adds "$nums"
done
fi
_prompt_menu_adds
}
_prompt_menu_iter() {
local fn i sel state c=0
local fn=$1; shift
for i in $menu_options; do
state=0
for sel in $menu_selects; do
[ "$sel" = "$i" ] && state=1 && break
done
$fn $state "$c" "$i" "$@"
c=$((c+1))
done
}
_prompt_menu_draws() {
# carriage return printf
printf "\r\033[1m%s\033[0m\n" "$1"
_prompt_menu_iter _prompt_menu_draw "$2"
}
_prompt_menu_draw()
{
local method
document() { toupper | sed 's/\.sh//g' | sed 's/_/ /g'; }
if [ "$1" -eq 0 ]; then method=e_error; fi
if [ "$1" -eq 1 ]; then method=e_success; fi
if [ -n "$4" ]; then
if [ "$4" = '-1' ]; then
e_arrow "$(printf "%2d) %s\n" $(($2+1)) "$(basename "$3" | document)")"
else
$method "$(printf "%2d) %s\n" $(($2+1)) "$(basename "$3" | document)")"
fi
else
$method "$(basename "$2" | document)"
fi
}
_prompt_menu_adds() {
_prompt_menu_result=""
_prompt_menu_iter _prompt_menu_add "$@"
menu_selects="${_prompt_menu_result}"
}
_prompt_menu_add() {
local state c file nums n keep match
state=$1; shift
c=$1; shift
file=$1; shift
IFS=' '
nums="$*"
for n in $nums; do
if [ "$n" = 'r' -o "$n" = 'R' ]; then
match=1; [ "$state" = 0 ] && keep=1
elif expr "$n" : "^[0-9][0-9]*$" >/dev/null && [ $((n-1)) = "$c" ]; then
match=1; [ "$state" = 0 ] && keep=1
fi
done
[ ! "$match" -a "$state" = 1 -o "$keep" ] || return
_prompt_menu_result="$_prompt_menu_result $file"
}
# Capitalization based on the POSIX standards
toupper() { awk '{ print toupper(substr($0, 1, 1)) substr($0, 2, length($0) - 1) }'; }
tolower() { awk '{ print tolower(substr($0, 1, 1)) substr($0, 2, length($0) - 1) }'; }
# main function in initialize
init_files() {
local f files i
f=""
files=$(echo $DOTFILES/etc/init/*.sh $DOTFILES/etc/init/osx/*.sh)
for i in $files
do
f="$f $(DEBUG=1 bash "$i")"
done
menu_options=""
menu_selects=""
for i in $f
do
menu_selects="$menu_selects $i"
menu_options="$menu_options $i"
done
[ -n "$f" ] && prompt_menu "Press ENTER to run checked files"
for i in $menu_selects
do
bash "$i"
done
}
init_files "$@"
}
installing_dotfiles()
{
# If $DOTFILES already exists, removing the directory
if [ -d $DOTFILES ]; then
e_header "$DOTFILES: already exists, removing..."
rm -rf "$DOTFILES"
#mv -f $DOTFILES ${DOTFILES}.old
fi
# 1. Download the repository
# ==> downloading
# Priority: git > curl > wget
e_newline
e_header 'Downloading dotfiles...'
if is_exist 'git'; then
# --recursive equals to ...
# git submodule init
# git submodule update
git clone --recursive https://github.com/suzukaze/dotfiles.git "$DOTFILES"
else
local zip_url='https://github.com/suzukaze/dotfiles/archive/master.zip'
# Ensure the workplace
mkdir -p /tmp/$$ && cd /tmp/$$
if is_exist 'curl'; then
curl -L -o dotfiles.zip "$zip_url"
elif is_exist 'wget'; then
wget -O dotfiles.zip "$zip_url"
else
e_error 'git,curl,wget: not found'
return 1
fi
# Expand the zip to dotfiles directory
# and move to $DOTFILES
unzip dotfiles.zip
mv dotfiles-master "$DOTFILES"
fi && e_success 'done'
# 2. Deploy dotfiles to your home directory
# ==> deploying
cd "$DOTFILES"
e_newline
e_header 'Deploying dotfiles...'
if make deploy; then
e_success 'done'
fi
# 3. Execute all sh files within etc/init/
# ==> initializing
if [ "${1:-}" = 'init' ]; then
e_header 'Initializing...'
if [ -t 0 ]; then
initialize "$@"
else
cd "$DOTFILES"
make init
fi && e_success 'done'
fi
e_newline
if [ -t 0 ]; then
# Restart shell if specified "bash -c $(curl -L {URL})"
# not restart:
# curl -L {URL} | bash
e_arrow 'Restarting your shell...'
exec "${SHELL:-/bin/zsh}"
else
e_arrow 'Restart your shell, manually'
fi
}
# Main
#
# Check if run from a command line only bash
# python-like "if __name__ == '__main__':"
#
# A SAFETY system
# Note: This script is designed to be run from a command line shell.
if [ "$0" = "${BASH_SOURCE:-}" ]; then
e_error 'WARNING!!'
e_error 'You should NOT run directly from the command line'
e_error 'For more info, see https://github.com/suzukaze/dotfiles'
e_newline
# Push off the safety catch
if [ "${1:-}" != 'directly' ]; then
exit 1
fi
fi
installing_dotfiles "$@"
e_success 'All done'
# vim:fdm=marker
<file_sep>/bin/gitco
#!/usr/bin/env ruby
branch = `git br | peco`
branch.chop!
system("git checkout #{branch}")
<file_sep>/bin/showlsdir
#!/usr/bin/env ruby
#
# ディレクトリのファイル一覧をクリップボードに入れる
#
#
if ARGV.length < 1
puts "usage: ruby dir"
puts "dir is for (ls)"
end
dir = ARGV[0]
list = `ls #{dir}`
puts list
IO.popen('pbcopy', 'w') {|f| f << list} # クリップボードにコピーします
<file_sep>/bin/makeweek
#!/usr/bin/env ruby
#
# 前日はから一週間を表示します
# さらにクリップボードに一週間をコピーします
#
require 'date'
def format_date(date)
str_weeks = ['日', '月', '火', '水', '木', '金', '土']
str = "#{date.strftime("%Y/%m/%d")}(#{str_weeks[date.strftime("%w").to_i]})"
#str = "#{date.strftime("%Y/%m/%d")}"
#str = "a"
str
end
base_date = Date.today
# 第1引数から今日の日付をたす
if ARGV.length >= 1
base_date += ARGV[0].to_i
end
option_str = ""
if ARGV.length == 2
option_str = "週報 : "
end
end_date = base_date - 1
start_date = end_date - 6
str_start_date = format_date(start_date)
str_end_date = format_date(end_date)
from_to_dates = "#{option_str}#{str_start_date}〜#{str_end_date}"
puts from_to_dates
IO.popen('pbcopy', 'w') {|f| f << from_to_dates} # クリップボードにコピーします
<file_sep>/.zshrc
########################################
# 環境変数
export LANG=ja_JP.UTF-8
# rmでゴミ箱へ
#alias rm='rmtrash'
# コマンドの候補
autoload -U compinit
compinit
# プロンプト 現在のディレクトリ表示
# 複数行の入力や制御構文入力の場合に構文名がプロンプトに表示されている
#PROMPT="%/%% "
#PROMPT2="%_%% "
#SPROMPT="%r is correct? [n,y,a,e]: "
PROMPT="$ "
# 履歴
HISTFILE=$HOME/.zsh-history # 履歴をファイルに保存する
HISTSIZE=100000 # メモリ内の履歴の数
SAVEHIST=100000 # 保存される履歴の数
setopt extended_history # 履歴ファイルに時刻を記録
function history-all { history -E 1 } # 全履歴の一覧を出力する
setopt hist_ignore_all_dups # ヒストリに追加されるコマンド行が古いものと同じなら古いものを削除
# iTerm2のタブ名を変更する
function title {
echo -ne "\033]0;"$*"\007"
}
##################
# http://kitak.hatenablog.jp/entry/2013/05/25/103059
# format解説 http://mollifier.hatenablog.com/entry/20090814/p1
#
# VCSの情報を取得するzshの便利関数 vcs_infoを使う
autoload -Uz vcs_info
# 表示フォーマットの指定
# %b ブランチ情報
# %a アクション名(mergeなど)
zstyle ':vcs_info:*' formats '[%r:%b]'
zstyle ':vcs_info:*' actionformats '[%r:%b|%a]'
precmd () {
psvar=()
#LANG=en_US.UTF-8 vcs_info
LANG=UTF-8 vcs_info
[[ -n "$vcs_info_msg_0_" ]] && psvar[1]="$vcs_info_msg_0_"
}
# バージョン管理されているディレクトリにいれば表示,そうでなければ非表示
RPROMPT="%1(v|%F{green}%1v%f|)"
#######################################
# peco hitory
#######################################
# http://www.absolute-keitarou.net/blog/?p=1337
function peco-select-history() {
local tac
if which tac > /dev/null; then
tac="tac";
else
tac="tail -r"
fi
BUFFER=$(history -n 1 | \
eval $tac | \
peco --query "$LBUFFER")
CURSOR=$#BUFFER
zle clear-screen
}
zle -N peco-select-history
bindkey '^r' peco-select-history
#######################################
# ghq + peco
#######################################
# http://weblog.bulknews.net/post/89635306479/ghq-peco-percol
function peco-src () {
local selected_dir=$(ghq list --full-path | peco --query "$LBUFFER")
if [ -n "$selected_dir" ]; then
BUFFER="cd ${selected_dir}"
zle accept-line
fi
zle clear-screen
}
zle -N peco-src
bindkey '^]' peco-src
########################################
# pcd
########################################
function pcd() {
local PCD_FILE=$HOME/.peco/.peco-cd
local PCD_RETURN
if [ $1 ] && [ $1 = "add" ]; then
if [ $2 ]; then
ADD_DIR=$2
if [ $2 = "." ]; then
ADD_DIR=$(pwd)
fi
echo "add $ADD_DIR to $PCD_FILE"
echo $ADD_DIR >> $PCD_FILE
fi
elif [ $1 ] && [ $1 = "edit" ]; then
if [ $EDITOR ]; then
$EDITOR $PCD_FILE
fi
elif [ $1 ] && [ $1 = "." ]; then
PCD_RETURN=$(/bin/ls -F | grep /$ | sort | peco)
else
PCD_RETURN=$(cat $PCD_FILE | sort | peco)
fi
if [ $PCD_RETURN ]; then
cd $PCD_RETURN
fi
}
propen() {
local current_branch_name=$(git symbolic-ref --short HEAD | xargs perl -MURI::Escape -e 'print uri_escape($ARGV[0]);')
git config --get remote.origin.url | sed -e "s/^.*[:\/]\(.*\/.*\).git$/https:\/\/github.com\/\1\//" | sed -e "s/$/pull\/${current_branch_name}/" | xargs open
}
alias s='cd ..'
alias t='tig'
alias gl='git lga'
alias g='cd $(ghq root)/$(ghq list | peco)'
alias gh='hub browse $(ghq list | peco | cut -d "/" -f 2,3)'
export PATH="$HOME/mysql-build/bin:$PATH"
export MRUBY=~/repo/src/github.com/suzukaze/mruby
export PATH=$MRUBY/bin:$PATH:
export GOROOT=/usr/local/opt/go/libexec
export PATH=$PATH:$GOROOT/bin
export GOPATH=$HOME/repo
export PATH=$PATH:$GOPATH/bin
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"
export MRUBY_HOME=~/repo/src/github.com/suzukaze/mruby
export PATH="/usr/bin/xiki":$PATH
### Added by the Heroku Toolbelt
export PATH="/usr/local/heroku/bin:$PATH"
export PATH="/Applications/MacVim.app/Contents/MacOS":$PATH
# MacVimのctagsではなく/usr/local/bin/ctagsを優先する
# brew
export PATH=/usr/local/bin:$PATH
#export BREW=~/brew
#export PATH=$BREW/bin:$PATH
# ctags -R -f .tags # .ctagsを作成するコマンド
# ctags --langmap=RUBY:.rb --exclude="*.js" --exclude=".git*" -R .
#alias ctags="`brew --prefix`/bin/ctags"
export COFFEE_SCRIPT=~/.npm/coffee-script/1.7.1/package
export PATH=$COFFEE_SCRIPT/bin:$PATH
export PGDATA=/usr/local/var/postgres
export STREEM_HOME=~/repo/src/github.com/suzukaze/streem
export PATH=$STREEM_HOME/bin:$PATH
# JAVA_HOME バージョン切替 1.6, 1.7, 1.8
export JAVA_HOME=`/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java_home -v "1.8"`
export PATH=${JAVA_HOME}/bin:${PATH}
export JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8
export PATH=$HOME/bin:$PATH
# Android
export ADB_PECO_HOME=~/repo/src/github.com/tomorrowkey/adb-peco/
export PATH=$ADB_PECO_HOME/bin:$PATH
alias restart-adb='adb kill-server; adb start-server'
alias uninstallapp='adbp shell pm list package | sed -e s/package:// | peco | xargs adbp uninstall'
alias installapp='find ./ -name *.apk | peco | xargs adb install -r'
# Androidのメソッド数を数える
alias dex-method-counts=~/repo/src/github.com/mihaip/dex-method-counts/dex-method-counts
# cocos2d ダウンロード
# Add environment variable COCOS_CONSOLE_ROOT for cocos2d-x
export COCOS_CONSOLE_ROOT=~/work/cocos2d-x-3.3/tools/cocos2d-console/bin
export PATH=$COCOS_CONSOLE_ROOT:$PATH
# Add environment variable COCOS_X_ROOT for cocos2d-x
export COCOS_X_ROOT=~/work/cocos2d-x-3.3
export PATH=$COCOS_X_ROOT:$PATH
# cocos2d git
# Add environment variable COCOS_CONSOLE_ROOT for cocos2d-x
#export COCOS_CONSOLE_ROOT=~/repo/src/github.com/suzukaze/cocos2d-x/tools/cocos2d-console/bin
#export PATH=$COCOS_CONSOLE_ROOT:$PATH
# Add environment variable COCOS_TEMPLATES_ROOT for cocos2d-x
#export COCOS_TEMPLATES_ROOT=~/repo/src/github.com/suzukaze/cocos2d-x/templates
#export PATH=$COCOS_TEMPLATES_ROOT:$PATH
# Add environment variable COCOS_TEMPLATES_ROOT for cocos2d-x
export COCOS_TEMPLATES_ROOT=~/work/cocos2d-x-3.3/templates
export PATH=$COCOS_TEMPLATES_ROOT:$PATH
# Add environment variable NDK_ROOT for cocos2d-x
export NDK_ROOT=~/work/android/android-ndk-r9d
export PATH=$NDK_ROOT:$PATH
# Add environment variable ANDROID_SDK_ROOT for cocos2d-x
export ANDROID_SDK_ROOT=~/work/android/sdk
export PATH=$ANDROID_SDK_ROOT:$PATH
export PATH=$ANDROID_SDK_ROOT/tools:$ANDROID_SDK_ROOT/platform-tools:$PATH
export ANT_ROOT=~/work/ant/apache-ant-1.9.4/bin
export PATH=$ANT_ROOT:$PATH
export APPENGINE_SDK_HOME=/usr/local/opt/app-engine-java/libexec
#todo
export TODO_DB_PATH=$HOME/Dropbox/todo.json
export PATH=$HOME/.nodebrew/current/bin:$PATH
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
export PATH="/usr/local/opt/openssl/bin:$PATH"
<file_sep>/bin/replace_tabs_with_spaces
#!/usr/bin/env ruby
require 'FileUtils'
require 'tempfile'
if ARGV.size == 0
puts "usage:ruby [filename]"
exit
end
filename = ARGV[0]
puts filename
temp_filename = 'temp.txt'
temp_file = Tempfile.new(temp_filename)
File::open(filename) do |f|
f.each do |line|
temp_line = line.gsub(/\t/, " "*4)
temp_file.write(temp_line)
end
end
File::delete(filename)
FileUtils.mv(temp_file.path, filename)
temp_file.close
<file_sep>/etc/init/osx/Brewfile
#!/bin/bash
# vim: ft=sh
trap 'echo Error: $0: stopped; exit 1' ERR
set -u
set -e
if ! type brew >/dev/null 2>&1; then
echo 'Requirement: brew' 1>&2
exit 1
fi
echo 'brew updating...'
brew update
outdated=$(brew outdated)
if [ -n "$outdated" ]; then
echo 'The following package(s) will upgrade.'
echo ''
echo "$outdated"
echo 'Are you sure?'
echo 'If you do not want to upgrade, please type Ctrl-c now.'
echo ''
# Wait Ctrl-c
read dummy
brew upgrade
fi
declare -a BREW_PACKAGES=(
"autoconf"
"cmake"
"fish"
"gibo"
"git"
"go"
"graphviz"
"hiredis"
"libgd"
"libuv"
"lzlib"
"node"
"nvm"
"mycli"
"mysql"
"openssl"
"pcre"
"peco"
"postgresql"
"readline"
"redis"
"ruby-build"
"tig"
"tree"
"sbt"
"qt4"
"wget"
"wslay"
)
for package in "${BREW_PACKAGES[@]}"
do
if brew list -1 | grep -q "^$(basename $package)"; then
echo "Skip: brew install ${package}"
else
brew install $package
fi
done
<file_sep>/README.md
## dofiles
## Install
```sh
bash -c "$(curl -L https://raw.githubusercontent.com/suzukaze/dotfiles/master/etc/init/install)"
```
## Memo
### Unistall brew packages
rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup
## Licence
[](./doc/LICENSE-MIT.txt "License")
Copyright (c) 2014 "BABAROT" b4b4r07
Copyright (c) 2015 <NAME>
Licensed under the [MIT license](./doc/LICENSE-MIT.txt).
Unless attributed otherwise, everything is under the MIT licence. Some stuff is not from me, and without attribution, and I no longer remember where I got it from. I apologize for that.
<file_sep>/bin/add_date_to_file
#!/usr/bin/env ruby
require 'fileutils'
require 'date'
if ARGV.length == 0
puts <<EOS
usage: ruby add_date_to_file.rb <filename>
or
ruby add_date_to_file.rb <filename> <sub_day>
EOS
exit
end
date = Date.today
path = ARGV[0]
if ARGV.length == 2
suby_day = ARGV[1].to_i
date -= suby_day
end
filename = File.basename(path, ".zip")
dir = File.dirname(path)
new_path = "#{dir}/#{filename}_#{date.strftime("%Y%m%d")}.zip"
FileUtils.mv(path, new_path)
<file_sep>/bin/makedate
#!/usr/bin/env ruby
require 'date'
def format_date(date)
str_weeks = ['日', '月', '火', '水', '木', '金', '土']
str = "#{date.strftime("%Y/%m/%d")}(#{str_weeks[date.strftime("%w").to_i]})"
end
base_date = Date.today
# 第1引数から今日の日付をたす
if ARGV.length >= 1
base_date += ARGV[0].to_i
end
date = format_date(base_date)
puts date
IO.popen('pbcopy', 'w') {|f| f << date} # クリップボードにコピーします
<file_sep>/.pryrc
begin
require 'awesome_print'
rescue LoadError
else
AwesomePrint.pry!
end
<file_sep>/etc/init/osx/install_homebrew.sh
#!/bin/bash
trap 'echo Error: $0: stopped; exit 1' ERR INT
set -u
set -e
# A system that judge if this script is necessary or not
#
# Testing the judgement system
echo 'brew: command not found' 1>&2
echo -n 'Install now? (y/N) '
read
if [[ "$REPLY" =~ ^[Yy]$ ]]; then
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
fi
# vim:fdm=marker
<file_sep>/bin/work_time_maker
#!/usr/bin/env ruby
# It is end time maker.
# It add end time and break time to start time.
#
WORK_TIME = 8 # 8 hours
BREAK_TIME = 60 # 60 miniutes
if ARGV.size != 1
puts <<"EOS"
usage: ruby aker [start time]
ex: ruby_work_time_maker 10:00
EOS
exit
end
start_time_str = ARGV[0]
start_times = start_time_str.split(":")
start_time_hour = start_times[0].to_i
start_time_minute = start_times[1].to_i
start_time = start_time_hour * 60 + start_time_minute
end_time = start_time + WORK_TIME * 60 + BREAK_TIME
end_time_hour = end_time / 60
end_time_minute = end_time - end_time_hour * 60
end_time_hour_str = "#{end_time_hour}:#{end_time_minute}"
end_time_hour_str = sprintf("%02d:%02d", end_time_hour, end_time_minute)
result = "#{start_time_str}〜#{end_time_hour_str}"
puts result
IO.popen('pbcopy', 'w') {|f| f << result} # クリップボードにコピーします
|
584cfa3e1f1f8386287db3429b3aed5f13eb1d04
|
[
"Makefile",
"Ruby",
"Markdown",
"Shell"
] | 24
|
Ruby
|
suzukaze/dotfiles
|
38aff3d6cafab6960057a015a303cbe44fa2f7b5
|
54280c96951a0649e7ca1c52ae2f8f0a578cae92
|
refs/heads/master
|
<file_sep>//
// MovieResStoreStore.swift
// MovieList
//
// Created by <NAME> on 3/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
import Foundation
import Alamofire
class MovieRestStore: MovieStoreProtocol {
let urlDetail = "https://api.themoviedb.org/3/movie/%@?api_key=<KEY>"
func getMovieList(page: Int, sort: SortData, _ completion: @escaping (Result<MovieList>) -> Void) {
let sort = sort == .DESC ? "release_date.desc" : "release_date.asc"
AF.request(URL(string: "http://api.themoviedb.org/3/discover/movie?api_key=<KEY>&primary_release_date.lte=2016-12-31&sort_by=\(sort)&page=\(page)")!, method: .get).responseJSON { response in
switch response.result {
case .success:
do {
// print("suscess feed movie list")
let decoder = JSONDecoder()
let result = try decoder.decode(MovieList.self, from: response.data!)
completion(.success(result))
// print(result)
} catch let error {
print("error case success movie list")
print(error)
}
case let .failure(error):
print("error case failure movie list")
print(error)
}
}
}
func getMovieDetail(id: String, _ completion: @escaping (Result<DetailModel>) -> Void) {
AF.request(URL(string: String(format: urlDetail, id))!, method: .get).responseJSON { (response) in
switch response.result {
case .success:
do {
// print("suscess feed movie data")
let decoder = JSONDecoder()
let result = try decoder.decode(DetailModel.self, from: response.data!)
completion(.success(result))
} catch let error {
print("error case success movie data")
print(error)
}
case let .failure(error):
print("error case failure movie data")
print(error)
}
}
}
}
<file_sep>//
// Additional.swift
// MobileBuyer
//
// Created by <NAME> on 27/8/2562 BE.
// Copyright © 2562 <NAME>. All rights reserved.
//
import Foundation
import UIKit
import AlamofireImage
enum Result<T> {
case success(T)
case failure(Error)
}
enum SortData {
case ASC
case DESC
}
extension UIImageView {
func loadImageUrl(_ urlString:String) {
guard let url = URL(string: urlString) else {
return
}
af_setImage(withURL: url)
}
}
<file_sep>//
// DetailPresenter.swift
// MovieList
//
// Created by <NAME> on 2/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
import UIKit
protocol DetailPresenterInterface {
func presentMovieData(response: Detail.GetMovieData.Response)
}
class DetailPresenter: DetailPresenterInterface {
weak var viewController: DetailViewControllerInterface!
// MARK: - Presentation logic
func presentMovieData(response: Detail.GetMovieData.Response) {
var model: Detail.GetMovieData.ViewModel?
switch response.movie {
case .success(let data):
// join list of Category
var categoryArray : Array<String> = []
for i in data.genres {
categoryArray.append(i.name)
}
if categoryArray.isEmpty {
categoryArray.append("None")
}
let categoryList = categoryArray.joined(separator: ", ")
let lastVote = UserDefaults.standard.object(forKey: "lastVoteByUser") as? [String: Int]
let voteUser = lastVote?["\(data.id)"] ?? 0
let displayDetail = Detail.GetMovieData.ViewModel.DisplayDetail(title: data.title,
overview: data.overview,
popularity: "Popularity: \(data.popularity)",
imageURL: "https://image.tmdb.org/t/p/original\(data.posterPath ?? "")",
category: "Category: \(categoryList)",
language: "Language: \(data.originalLanguage.uppercased())",
vote: voteUser)
model = Detail.GetMovieData.ViewModel(content: Result<Detail.GetMovieData.ViewModel.DisplayDetail>.success(displayDetail))
case .failure(let error):
print(error)
model = Detail.GetMovieData.ViewModel(content: Result<Detail.GetMovieData.ViewModel.DisplayDetail>.failure(error))
}
guard let viewModel = model else {
return
}
viewController.displayMovieData(viewModel: viewModel)
}
}
<file_sep>//
// MovieWorker.swift
// MovieList
//
// Created by <NAME> on 3/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
import UIKit
protocol MovieStoreProtocol {
func getMovieList(page: Int,sort: SortData , _ completion: @escaping (Result<MovieList>) -> Void)
func getMovieDetail(id: String, _ completion: @escaping (Result<DetailModel>) -> Void)
}
class MovieWorker {
var store: MovieStoreProtocol
init(store: MovieStoreProtocol) {
self.store = store
}
// MARK: - Business Logic
func getMovieList(page: Int,sort: SortData , _ completion: @escaping (Result<MovieList>) -> Void) {
store.getMovieList(page: page, sort: sort) {
completion($0)
}
}
func getMovieDetail(id: String, _ completion: @escaping (Result<DetailModel>) -> Void) {
store.getMovieDetail(id: id) {
completion($0)
}
}
}
<file_sep>//
// DetailPresenterTests.swift
// MovieList
//
// Created by <NAME> on 13/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
@testable import MovieList
import XCTest
class DetailPresenterTests: XCTestCase {
class SpyDetailView: DetailViewControllerInterface {
var displayMovieDataCalled = false
func displayMovieData(viewModel: Detail.GetMovieData.ViewModel) {
displayMovieDataCalled = true
}
}
// MARK: - Subject under test
var sut: DetailPresenter!
// MARK: - Test lifecycle
override func setUp() {
super.setUp()
setupDetailPresenter()
}
override func tearDown() {
super.tearDown()
}
// MARK: - Test setup
func setupDetailPresenter() {
sut = DetailPresenter()
}
// MARK: - Test doubles
// MARK: - Tests
func testGetMovieDataSuccess() {
// Given
let spyDetailView = SpyDetailView()
sut.viewController = spyDetailView
// When
sut.presentMovieData(response: Detail.GetMovieData.Response(movie: Result<DetailModel>.success(DetailModel(adult: false, backdropPath: "", belongsToCollection: nil, budget: 0, genres: [Genre(id: 1, name: "Comedy")], homepage: "", id: 11, imdbID: "", originalLanguage: "", originalTitle: "Discolocos", overview: "The high energy movement in Mexico", popularity: 2.0, posterPath: "", productionCompanies: nil, productionCountries: nil, releaseDate: "2016-12-31", revenue: 0, runtime: 101, spokenLanguages: [SpokenLanguage(iso639_1: "EN", name: "English")], status: "Released", tagline: "", title: "Discolocos", video: false, voteAverage: 4.5, voteCount: 5))))
// Then
XCTAssertTrue(spyDetailView.displayMovieDataCalled)
}
func testGetMovieDataFailure() {
// Given
let spyDetailView = SpyDetailView()
sut.viewController = spyDetailView
// When
sut.presentMovieData(response: Detail.GetMovieData.Response(movie: Result<DetailModel>.failure(NSError(domain: "", code: 0, userInfo: nil))))
// Then
XCTAssertTrue(spyDetailView.displayMovieDataCalled)
}
func testGetMovieDataIfCategoryArrayIsNil() {
// Given
let spyDetailView = SpyDetailView()
sut.viewController = spyDetailView
// When
sut.presentMovieData(response: Detail.GetMovieData.Response(movie: Result<DetailModel>.success(DetailModel(adult: false, backdropPath: "", belongsToCollection: nil, budget: 0, genres: [], homepage: "", id: 11, imdbID: "", originalLanguage: "", originalTitle: "Discolocos", overview: "The high energy movement in Mexico", popularity: 2.0, posterPath: "", productionCompanies: nil, productionCountries: nil, releaseDate: "2016-12-31", revenue: 0, runtime: 101, spokenLanguages: [SpokenLanguage(iso639_1: "EN", name: "English")], status: "Released", tagline: "", title: "Discolocos", video: false, voteAverage: 4.5, voteCount: 5))))
// Then
XCTAssertTrue(spyDetailView.displayMovieDataCalled)
}
}
<file_sep>//
// DetailInteractor.swift
// MovieList
//
// Created by <NAME> on 2/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
import UIKit
protocol DetailInteractorInterface {
func getMovieData(request: Detail.GetMovieData.Request)
func calculateVote(request: Detail.SetVote.Request)
var model: DetailModel? { get }
var id: String? { get set }
}
class DetailInteractor: DetailInteractorInterface {
var selectedStar: Int?
var selectedMovie: DetailModel?
var voteCount: Int?
var voteAvg: Double?
var newVote: Double?
var id: String?
var presenter: DetailPresenterInterface!
var worker: MovieWorker?
var model: DetailModel?
// MARK: - Business logic
func getMovieData(request: Detail.GetMovieData.Request) {
guard let movieId = id else {
return
}
worker?.getMovieDetail(id: movieId, { [weak self] result in
var response: Detail.GetMovieData.Response
switch result {
case .success(let data):
self?.selectedMovie = data
print(data)
response = Detail.GetMovieData.Response(movie: Result<DetailModel>.success(data))
case .failure(let error):
response = Detail.GetMovieData.Response(movie: Result<DetailModel>.failure(error))
print(error)
}
self?.presenter.presentMovieData(response: response)
})
}
func calculateVote(request: Detail.SetVote.Request) {
guard let id = id else {
return
}
voteCount = selectedMovie?.voteCount
let count = Double(voteCount ?? 0)
voteAvg = selectedMovie?.voteAverage
let avg = voteAvg ?? 0.0
newVote = ((( (avg*count) + (request.voteUser * 2) ) / (count+1) ) / 2)
selectedStar = Int(request.voteUser)
var voteResult = UserDefaults.standard.object(forKey: "voteByUser") as? [String: Double] ?? [:]
voteResult[id] = newVote
UserDefaults.standard.set(voteResult, forKey: "voteByUser")
var lastVote = UserDefaults.standard.object(forKey: "lastVoteByUser") as? [String: Int] ?? [:]
lastVote[id] = selectedStar
UserDefaults.standard.set(lastVote, forKey: "lastVoteByUser")
}
}
<file_sep>//
// MainPresenter.swift
// MovieList
//
// Created by <NAME> on 2/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
import UIKit
protocol MainPresenterInterface {
func presentMovieList(response: Main.GetMovieList.Response)
}
class MainPresenter: MainPresenterInterface {
weak var viewController: MainViewControllerInterface!
// MARK: - Presentation logic
func presentMovieList(response: Main.GetMovieList.Response) {
var viewModel: [Main.GetMovieList.ViewModel] = []
switch response.result {
case .success(let data):
let voteResult = UserDefaults.standard.object(forKey: "voteByUser") as? [String: Double]
viewModel = data.map {
var voteAvg = $0.voteAverage / 2
if let vote = voteResult?["\($0.id)"] {
voteAvg = vote
}
return Main.GetMovieList.ViewModel(title: $0.title,
popularity: "Popularity: \($0.popularity)",
rating: voteAvg,
imageURL: "https://image.tmdb.org/t/p/original\($0.posterPath ?? "" )" ,
backdropURL: "https://image.tmdb.org/t/p/original\($0.backdropPath ?? "")" )
}
case .failure(let error):
print("error")
print(error)
}
viewController.displayMovieList(viewModel: viewModel)
}
}
<file_sep>//
// DetailInteractorTests.swift
// MovieList
//
// Created by <NAME> on 13/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
@testable import MovieList
import XCTest
class DetailInteractorTests: XCTestCase {
class SpyDetailPresenter: DetailPresenterInterface {
var presentMovieDataCelled = false
func presentMovieData(response: Detail.GetMovieData.Response) {
presentMovieDataCelled = true
}
}
class SpyDetailWorker: MovieWorker {
var isFailure = false
override func getMovieDetail(id: String, _ completion: @escaping (Result<DetailModel>) -> Void) {
if isFailure {
completion(Result.failure(NSError(domain: "", code: 0, userInfo: nil)))
} else {
completion(Result<DetailModel>.success(DetailModel(adult: false, backdropPath: "", belongsToCollection: nil, budget: 0, genres: [Genre(id: 1, name: "Comedy")], homepage: "", id: 11, imdbID: "", originalLanguage: "", originalTitle: "Discolocos", overview: "The high energy movement in Mexico", popularity: 2.0, posterPath: "", productionCompanies: nil, productionCountries: nil, releaseDate: "2016-12-31", revenue: 0, runtime: 101, spokenLanguages: [SpokenLanguage(iso639_1: "EN", name: "English")], status: "Released", tagline: "", title: "Discolocos", video: false, voteAverage: 4, voteCount: 1)))
}
// (( ((4*1)+(5*2)) /2) /2)
}
}
// MARK: - Subject under test
var sut: DetailInteractor!
// MARK: - Test lifecycle
override func setUp() {
super.setUp()
setupDetailInteractor()
}
override func tearDown() {
super.tearDown()
}
// MARK: - Test setup
func setupDetailInteractor() {
sut = DetailInteractor()
}
// MARK: - Test doubles
// MARK: - Tests
func testDisplayMovieDataSuccess() {
// Given
let spyPresenter = SpyDetailPresenter()
sut.presenter = spyPresenter
let spyWorker = SpyDetailWorker(store: MovieRestStore())
sut.worker = spyWorker
let request = Detail.GetMovieData.Request()
sut.id = "\(11)"
// When
sut.getMovieData(request: request)
// Then
XCTAssertTrue(spyPresenter.presentMovieDataCelled)
}
func testDisplayMovieDataFailure() {
// Given
let spyPresenter = SpyDetailPresenter()
sut.presenter = spyPresenter
let spyWorker = SpyDetailWorker(store: MovieRestStore())
sut.worker = spyWorker
let request = Detail.GetMovieData.Request()
sut.id = "\(11)"
spyWorker.isFailure = true
// When
sut.getMovieData(request: request)
// Then
XCTAssertTrue(spyPresenter.presentMovieDataCelled)
}
func testDisplayMovieDataIdIsNil() {
// Given
let spyPresenter = SpyDetailPresenter()
sut.presenter = spyPresenter
let spyWorker = SpyDetailWorker(store: MovieRestStore())
sut.worker = spyWorker
let request = Detail.GetMovieData.Request()
sut.id = nil
// When
sut.getMovieData(request: request)
// Then
XCTAssertFalse(spyPresenter.presentMovieDataCelled)
}
func testCalculateVoteSuccess() {
// Given
let spyPresenter = SpyDetailPresenter()
sut.presenter = spyPresenter
let spyWorker = SpyDetailWorker(store: MovieRestStore())
sut.worker = spyWorker
sut.selectedMovie = DetailModel(adult: false, backdropPath: "", belongsToCollection: nil, budget: 0, genres: [Genre(id: 1, name: "Comedy")], homepage: "", id: 11, imdbID: "", originalLanguage: "", originalTitle: "Discolocos", overview: "The high energy movement in Mexico", popularity: 2.0, posterPath: "", productionCompanies: nil, productionCountries: nil, releaseDate: "2016-12-31", revenue: 0, runtime: 101, spokenLanguages: [SpokenLanguage(iso639_1: "EN", name: "English")], status: "Released", tagline: "", title: "Discolocos", video: false, voteAverage: 4, voteCount: 1)
sut.id = "\(String(describing: sut.selectedMovie?.id))"
let request = Detail.SetVote.Request(voteUser: 5)
// When
sut.calculateVote(request: request)
// Then
XCTAssertEqual(sut.selectedStar, 5)
XCTAssertEqual(sut.newVote, 3.5)
}
func testCalculateVoteIfIdIsNil() {
// Given
let spyPresenter = SpyDetailPresenter()
sut.presenter = spyPresenter
let spyWorker = SpyDetailWorker(store: MovieRestStore())
sut.worker = spyWorker
sut.id = nil
let request = Detail.SetVote.Request(voteUser: 5)
// When
sut.calculateVote(request: request)
// print(sut.selectedMovie?)
// Then
XCTAssertEqual(sut.voteCount, nil)
XCTAssertEqual(sut.voteAvg, nil)
}
}
<file_sep>//
// MainPresenterTests.swift
// MovieList
//
// Created by <NAME> on 12/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
@testable import MovieList
import XCTest
class MainPresenterTests: XCTestCase {
class SpyMainView: MainViewControllerInterface {
var displayMovieListCalled = false
var data:[Main.GetMovieList.ViewModel] = [] // capture data
func displayMovieList(viewModel: [Main.GetMovieList.ViewModel]) {
data = viewModel
displayMovieListCalled = true
}
}
// MARK: - Subject under test
var sut: MainPresenter!
// MARK: - Test lifecycle
override func setUp() {
super.setUp()
setupMainPresenter()
}
override func tearDown() {
super.tearDown()
}
// MARK: - Test setup
func setupMainPresenter() {
sut = MainPresenter()
}
// MARK: - Test doubles
// MARK: - Tests
func testDisplayMovieListCallSuccess() {
// Given
let spy = SpyMainView()
sut.viewController = spy
// When
sut.presentMovieList(response: Main.GetMovieList.Response(result: .success([MovieModel(popularity: 0.6, id: 1, video: false, voteCount: 1, voteAverage: 10.0, title: "Dawn French Live", releaseDate: "2016-12-31", originalLanguage: "en", originalTitle: "Dawn French Live", genreIDS: [], backdropPath: "", adult: false, overview: "Dawn French stars in her acclaimed one-woman show", posterPath: "")])))
// Then
XCTAssertTrue(spy.displayMovieListCalled)
// print(spy.displayMovieListCalled)
// print("data: \(spy.data)")
// XCTAssert(spy.data.isEmpty)
// let data = 5
// XCTAssertEqual(data, 5, "Data must be 5")
}
func testDisplayMovieListCallFailure() {
// Given
let spy = SpyMainView()
sut.viewController = spy
// When
sut.presentMovieList(response: Main.GetMovieList.Response(result: .failure(NSError(domain: "", code: 0, userInfo: nil))))
// Then
XCTAssertEqual(spy.displayMovieListCalled, true)
}
// func testData() {
// // Given
// let spy = Spy()
// sut.viewController = spy
// let model1:MovieModel = MovieModel(popularity: 0.0, id: 1, video: false, voteCount: 1, voteAverage: 1, title: "Oat", releaseDate: "", originalLanguage: "", originalTitle: "", genreIDS: [], backdropPath: "", adult: false, overview: "", posterPath: "")
// let model2:MovieModel = MovieModel(popularity: 1.0, id: 2, video: false, voteCount: 2, voteAverage: 2, title: "Nick", releaseDate: "", originalLanguage: "", originalTitle: "", genreIDS: [], backdropPath: "", adult: false, overview: "", posterPath: "")
// let model3:MovieModel = MovieModel(popularity: 1.0, id: 3, video: false, voteCount: 2, voteAverage: 2, title: "Ying", releaseDate: "", originalLanguage: "", originalTitle: "", genreIDS: [], backdropPath: "", adult: false, overview: "", posterPath: "")
// let dataArray:[MovieModel] = [model1, model2, model3]
// When
// let result = Result<[MovieModel]>.success(dataArray)
// let data = Main.GetMovieList.Response(result: result)
// sut.presentMovieList(response: data)
// sut.presentMovieList(response: Main.GetMovieList.Response(result: Result<[MovieModel]>.success(dataArray)))
// sut.presentMovieList(response: Main.GetMovieList.Response(result: Result<[MovieModel]>.success([MovieModel(popularity: 1.0, id: 1, video: false, voteCount: 1, voteAverage: 1, title: "Oat", releaseDate: "", originalLanguage: "", originalTitle: "", genreIDS: [], backdropPath: "", adult: false, overview: "", posterPath: "")])))
//
//// Then
// print(spy.data[1])
// XCTAssertEqual(spy.data[1].popularity, "Popularity: 1.0")
// }
}
<file_sep>//
// MainRouter.swift
// MovieList
//
// Created by <NAME> on 2/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
import UIKit
protocol MainRouterInput {
func navigateToDetail(withID: String)
}
class MainRouter: MainRouterInput {
weak var viewController: MainViewController!
// MARK: - Navigation
func navigateToDetail(withID: String) {
if let detailViewController = UIStoryboard(name: "Detail", bundle: nil).instantiateInitialViewController() as? DetailViewController {
detailViewController.interactor.id = withID
// school = student, Main = Cell
detailViewController.mainViewDelegate = viewController
viewController.navigationController?.pushViewController(detailViewController, animated: true)
print(withID)
}
}
// MARK: - Communication
func passDataToNextScene(segue: UIStoryboardSegue) {
if segue.identifier == "ShowSomewhereScene" {
passDataToSomewhereScene(segue: segue)
}
}
func passDataToSomewhereScene(segue: UIStoryboardSegue) {
// let someWhereViewController = segue.destinationViewController as! SomeWhereViewController
// someWhereViewController.interactor.model = viewController.interactor.model
}
}
<file_sep>//
// MainModels.swift
// MovieList
//
// Created by <NAME> on 2/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
import UIKit
import Alamofire
struct Main {
/// This structure represents a use case
struct GetMovieList {
/// Data struct sent to Interactor
struct Request {
let needLoadMore: Bool
let sortType: SortData?
}
/// Data struct sent to Presenter
struct Response {
let result: Result<[MovieModel]>
}
/// Data struct sent to ViewController
struct ViewModel {
let title: String
let popularity: String
let rating: Double
let imageURL: String
let backdropURL: String
}
}
struct SetLoadMore {
/// Data struct sent to Interactor
struct Request {
}
/// Data struct sent to Presenter
struct Response {
let totalPage: Int
let currentPage: Int
}
/// Data struct sent to ViewController
struct ViewModel {
}
}
}
<file_sep>//
// DetailModels.swift
// MovieList
//
// Created by <NAME> on 2/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
import UIKit
struct Detail {
/// This structure represents a use case
struct GetMovieData {
/// Data struct sent to Interactor
struct Request {}
/// Data struct sent to Presenter
struct Response {
let movie: Result<DetailModel>
}
/// Data struct sent to ViewController
struct ViewModel {
let content: Result<DisplayDetail>
struct DisplayDetail {
let title: String
let overview: String
let popularity: String
let imageURL: String
let category: String
let language: String
let vote: Int
}
}
}
struct SetVote {
struct Request {
let voteUser: Double
}
/// Data struct sent to Presenter
struct Response {
let voteResult: Double
}
/// Data struct sent to ViewController
struct ViewModel {
let popularity: String
}
}
}
<file_sep>//
// MainInteractor.swift
// MovieList
//
// Created by <NAME> on 2/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
import UIKit
protocol MainInteractorInterface {
func getMovieList (request: Main.GetMovieList.Request)
func loadmorePage(request: Main.SetLoadMore.Request)
func updateVote(request: Main.GetMovieList.Request)
var movieList: [MovieModel] { get }
}
class MainInteractor: MainInteractorInterface {
var view: MainViewController!
var presenter: MainPresenterInterface!
var worker: MovieWorker?
var moviePage: MovieList?
var movieList: [MovieModel] = []
var currentPage: Int = 1
var totalPage: Int = 0
var currentSort: SortData?
// MARK: - Business logic
func getMovieList(request: Main.GetMovieList.Request) {
var page = currentPage
let sort = request.sortType ?? currentSort
if currentSort != sort {
page = 1
currentPage = 1
currentSort = sort
} else if currentSort == sort && !request.needLoadMore {
return
}
// print("\(page) \(sort)")
// needLoadMore
if request.needLoadMore {
worker?.getMovieList(page: page, sort: sort ?? .DESC) { [weak self] result in
var response: Main.GetMovieList.Response
switch result {
case .success(let data):
if let movieList = self?.movieList {
self?.movieList = movieList + data.results
}
guard let result = self?.movieList else { return }
response = Main.GetMovieList.Response(result: Result<[MovieModel]>.success(result))
case .failure(let error):
response = Main.GetMovieList.Response(result: Result<[MovieModel]>.failure(error))
}
self?.presenter.presentMovieList(response: response)
}
} else {
// print("feed data normal")
worker?.getMovieList(page: page, sort: sort ?? .DESC) { [weak self] result in
var response: Main.GetMovieList.Response
switch result {
case .success(let data):
self?.totalPage = data.totalPages
self?.movieList = data.results
response = Main.GetMovieList.Response(result: Result<[MovieModel]>.success(data.results))
case .failure(let error):
response = Main.GetMovieList.Response(result: Result<[MovieModel]>.failure(error))
print(error)
}
self?.presenter.presentMovieList(response: response)
}
}
}
func loadmorePage(request: Main.SetLoadMore.Request) {
currentPage += 1
// print("page: \(currentPage)")
if currentPage <= totalPage {
let request = Main.GetMovieList.Request(needLoadMore: true, sortType: nil)
getMovieList(request: request)
}
}
func updateVote(request: Main.GetMovieList.Request) {
var response: Main.GetMovieList.Response
response = Main.GetMovieList.Response(result: Result<[MovieModel]>.success(movieList))
presenter.presentMovieList(response: response)
}
}
<file_sep>//
// MainViewController.swift
// MovieList
//
// Created by <NAME> on 2/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
import UIKit
import MJRefresh
protocol MainViewControllerInterface: class {
func displayMovieList(viewModel: [Main.GetMovieList.ViewModel])
}
protocol UpdatePopDelegate: class {
func updatePopularity()
}
class MainViewController: UIViewController, MainViewControllerInterface, UpdatePopDelegate {
var interactor: MainInteractorInterface!
var router: MainRouter!
var viewData : [Main.GetMovieList.ViewModel]?
@IBOutlet weak var tableView: UITableView!
// MARK: - Object lifecycle
override func awakeFromNib() {
super.awakeFromNib()
configure(viewController: self)
}
// MARK: - Configuration
private func configure(viewController: MainViewController) {
let router = MainRouter()
router.viewController = viewController
let presenter = MainPresenter()
presenter.viewController = viewController
let interactor = MainInteractor()
interactor.presenter = presenter
interactor.worker = MovieWorker(store: MovieRestStore())
viewController.interactor = interactor
viewController.router = router
}
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupMovieList()
getMovieList()
}
// MARK: - Event handling
func setupMovieList() {
tableView.register(UINib(nibName: "MovieCell", bundle: nil), forCellReuseIdentifier: "MovieCell")
tableView.mj_footer = MJRefreshAutoNormalFooter()
tableView.mj_footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh))
}
@IBAction func sortButton(_ sender: Any) {
showSortingAlert()
}
func getMovieList() {
let request = Main.GetMovieList.Request(needLoadMore: false, sortType: .DESC)
interactor.getMovieList(request: request)
}
@objc
func footerRefresh() {
// print("Loadmore..")
let request = Main.SetLoadMore.Request()
interactor.loadmorePage(request: request)
}
func pushGetMovieListToInteractor(request: Main.GetMovieList.Request) {
interactor.getMovieList(request: request)
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: UITableView.ScrollPosition.top, animated: false)
}
func showSortingAlert() {
let alert = UIAlertController(title: "Sort", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Old to New (ASC)", style: .default, handler: { [weak self] _ in
let request = Main.GetMovieList.Request(needLoadMore: false, sortType: .ASC)
self?.pushGetMovieListToInteractor(request: request)
}))
alert.addAction(UIAlertAction(title: "New to Old (DESC)", style: .default, handler: { [weak self] _ in
let request = Main.GetMovieList.Request(needLoadMore: false, sortType: .DESC)
self?.pushGetMovieListToInteractor(request: request)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in
}))
present(alert, animated: true, completion: nil)
}
// MARK: - Display logic
func displayMovieList(viewModel: [Main.GetMovieList.ViewModel]) {
// print(viewModel)
viewData = viewModel
tableView.mj_footer.endRefreshing()
tableView.reloadData()
}
func updatePopularity() {
// เรียก userdefault เพื่อที่จะ get ค่า id กับ rating มา
// หา id ที่เท่ากันใน interactor เพื่อที่จะ update ค่า rating
let request = Main.GetMovieList.Request(needLoadMore: false, sortType: .DESC)
interactor.updateVote(request: request)
}
}
extension MainViewController : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewData?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell") as? MovieCell, let viewData = viewData else {
return UITableViewCell()
}
cell.updateUI(viewData[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// print("Selected Row: \(indexPath.row)")
let id = "\(interactor.movieList[indexPath.row].id)"
router.navigateToDetail(withID: id)
}
}
<file_sep>//
// DetailViewController.swift
// MovieList
//
// Created by <NAME> on 2/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
import UIKit
protocol DetailViewControllerInterface: class {
func displayMovieData(viewModel: Detail.GetMovieData.ViewModel)
}
class DetailViewController: UIViewController, DetailViewControllerInterface {
@IBOutlet weak var posterImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var languageLabel: UILabel!
@IBOutlet weak var popularityLabel: UILabel!
@IBOutlet weak var stackView: UIStackView!
@IBOutlet var starButton: [UIButton]!
var interactor: DetailInteractorInterface!
var router: DetailRouter!
var viewDetail: Detail.GetMovieData.ViewModel?
// remove
var updatePopularity: Detail.SetVote.ViewModel?
weak var mainViewDelegate: UpdatePopDelegate?
// MARK: - Object lifecycle
override func awakeFromNib() {
super.awakeFromNib()
configure(viewController: self)
}
// MARK: - Configuration
private func configure(viewController: DetailViewController) {
let router = DetailRouter()
router.viewController = viewController
let presenter = DetailPresenter()
presenter.viewController = viewController
let interactor = DetailInteractor()
interactor.presenter = presenter
interactor.worker = MovieWorker(store: MovieRestStore())
viewController.interactor = interactor
viewController.router = router
}
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
getMovieData()
}
// MARK: - Event handling
func getMovieData() {
let request = Detail.GetMovieData.Request()
interactor.getMovieData(request: request)
}
@IBAction func buttonTapped(_ sender: UIButton) {
setStar(tag: sender.tag)
calculateVote(vote: Double(sender.tag))
mainViewDelegate?.updatePopularity()
}
func setStar(tag: Int) {
// print("Rated \(tag) stars.")
for button in starButton {
if button.tag > tag {
button.setBackgroundImage(UIImage.init(named: "star.png"), for: .normal)
} else {
button.setBackgroundImage(UIImage.init(named: "star-tap.png"), for: .normal)
}
}
}
// MARK: - Display logic
func displayMovieData(viewModel: Detail.GetMovieData.ViewModel) {
viewDetail = viewModel
updateDetail(viewDetail!)
}
func updateDetail(_ viewDetail: Detail.GetMovieData.ViewModel) {
switch viewDetail.content {
case .success(let data):
titleLabel.text = data.title
overviewLabel.text = data.overview
popularityLabel.text = data.popularity
languageLabel.text = data.language
categoryLabel.text = data.category
posterImageView.loadImageUrl(data.imageURL)
setStar(tag: data.vote)
case .failure(let error):
print(error)
}
}
// User-Defaults Vote
func calculateVote(vote: Double){
let request = Detail.SetVote.Request(voteUser: vote)
interactor.calculateVote(request: request)
}
}
<file_sep>//
// MovieCell.swift
// MovieList
//
// Created by <NAME> on 2/9/2562 BE.
// Copyright © 2562 <NAME>. All rights reserved.
//
import UIKit
class MovieCell: UITableViewCell {
@IBOutlet weak var posterImageView: UIImageView!
@IBOutlet weak var backdropImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var popularityLabel: UILabel!
@IBOutlet weak var ratingLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func updateUI(_ displayedMovie: Main.GetMovieList.ViewModel) {
nameLabel.text = displayedMovie.title
popularityLabel.text = "\(displayedMovie.popularity)"
ratingLabel.text = "\(displayedMovie.rating)"
posterImageView.loadImageUrl(displayedMovie.imageURL)
backdropImageView.loadImageUrl(displayedMovie.backdropURL)
}
override func prepareForReuse() {
super.prepareForReuse()
posterImageView.image = nil
backdropImageView.image = nil
}
}
<file_sep>//
// MainInteractorTests.swift
// MovieList
//
// Created by <NAME> on 12/9/2562 BE.
// Copyright (c) 2562 <NAME>. All rights reserved.
//
@testable import MovieList
import XCTest
class MainInteractorTests: XCTestCase {
class SpyPresenter: MainPresenterInterface {
var presentMovieListCalled = false
func presentMovieList(response: Main.GetMovieList.Response) {
presentMovieListCalled = true
}
}
class SpyWorker: MovieWorker {
var workerCalled = false
var isFailure = false
override func getMovieList(page: Int, sort: SortData, _ completion: @escaping (Result<MovieList>) -> Void) {
if isFailure {
completion(Result.failure(NSError(domain: "", code: 0, userInfo: nil)))
} else {
completion(Result.success(MovieList(page: 1, totalResults: 10000, totalPages: 500, results: [MovieModel(popularity: 0.6, id: 1, video: false, voteCount: 1, voteAverage: 10.0, title: "Dawn French Live", releaseDate: "2016-12-31", originalLanguage: "en", originalTitle: "Dawn French Live", genreIDS: [], backdropPath: "", adult: false, overview: "Dawn French stars in her acclaimed one-woman show", posterPath: "")])))
}
}
}
// MARK: - Subject under test
var sut: MainInteractor!
// MARK: - Test lifecycle
override func setUp() {
super.setUp()
setupMainInteractor()
}
override func tearDown() {
super.tearDown()
}
// MARK: - Test setup
func setupMainInteractor() {
sut = MainInteractor()
}
// MARK: - Test doubles
// MARK: - Tests
func testGetMovieListCalledSuccess() {
// Given
let spyPresenter = SpyPresenter()
sut.presenter = spyPresenter
let spyWorker = SpyWorker(store: MovieRestStore())
sut.worker = spyWorker
spyWorker.workerCalled = true
let request = Main.GetMovieList.Request(needLoadMore: false, sortType: .DESC)
// When
sut.getMovieList(request: request)
// Then
XCTAssertTrue(spyPresenter.presentMovieListCalled)
XCTAssertEqual(sut.currentSort, .DESC)
XCTAssertTrue(spyWorker.workerCalled)
}
func testGetMovieListCalledFailure() {
// Given
let spyPresenter = SpyPresenter()
sut.presenter = spyPresenter
let spyWorker = SpyWorker(store: MovieRestStore())
sut.worker = spyWorker
spyWorker.isFailure = true
let request = Main.GetMovieList.Request(needLoadMore: false, sortType: .DESC)
// When
sut.getMovieList(request: request)
// Then
XCTAssertTrue(spyPresenter.presentMovieListCalled)
}
func testLoadMoreSuccess() {
// Given
let spyPresenter = SpyPresenter()
sut.presenter = spyPresenter
let spyWorker = SpyWorker(store: MovieRestStore())
sut.worker = spyWorker
let request = Main.SetLoadMore.Request()
sut.currentPage = 1
sut.totalPage = 500
// When
sut.loadmorePage(request: request)
// Then
XCTAssertTrue(spyPresenter.presentMovieListCalled)
}
func testLoadMoreFailure() {
// Given
let spyPresenter = SpyPresenter()
sut.presenter = spyPresenter
let spyWorker = SpyWorker(store: MovieRestStore())
sut.worker = spyWorker
spyWorker.isFailure = true
let request = Main.SetLoadMore.Request()
sut.currentPage = 1
sut.totalPage = 500
// When
sut.loadmorePage(request: request)
// Then
XCTAssertTrue(spyPresenter.presentMovieListCalled)
}
func testLoadMoreWhenCurrentPageMoreThanTotalPage() {
// Given
let spyPresenter = SpyPresenter()
sut.presenter = spyPresenter
let spyWorker = SpyWorker(store: MovieRestStore())
sut.worker = spyWorker
// spyWorker.isFailure = true
let request = Main.SetLoadMore.Request()
sut.currentPage = 501
sut.totalPage = 500
// When
sut.loadmorePage(request: request)
// Then
XCTAssertFalse(spyPresenter.presentMovieListCalled)
}
func testUpdateVote() {
// Given
let spyPresenter = SpyPresenter()
sut.presenter = spyPresenter
let request = Main.GetMovieList.Request(needLoadMore: false, sortType: .DESC)
// When
sut.updateVote(request: request)
// Then
XCTAssertTrue(spyPresenter.presentMovieListCalled)
}
}
|
80ba5d3005f17d524d1f4c281a59a674fdadafb9
|
[
"Swift"
] | 17
|
Swift
|
yingntck/MovieList
|
3ce63cfae68b1126199b6267ec10b4d0e5767893
|
787cf2cc47a1846a9fa6f87fd0e94d4e77c4b567
|
refs/heads/master
|
<file_sep>package com.appsheet.adityabansal.appsheet;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/*
Custom Adaper for the ListView
*/
class UserAdapter extends ArrayAdapter<User> {
public UserAdapter(Context context, ArrayList<User> users) {
super(context, 0, users);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
User user = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.user_item, parent, false);
}
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvAge = (TextView) convertView.findViewById(R.id.tvAge);
TextView tvNum = (TextView) convertView.findViewById(R.id.tvNum);
tvName.setText(user.name + " ");
tvAge.setText(user.age + " ");
tvNum.setText(user.number + " ");
return convertView;
}
}
|
04ec288512a08f274f6ece8541ecff21163f9201
|
[
"Java"
] | 1
|
Java
|
maddymanu/AppSheet
|
c440668dcb786fe0854964543371e3e174560617
|
7e91dff6e116e7d16dbbb0ab3caa53f2e8470e2c
|
refs/heads/master
|
<file_sep># fuck-anticon
for Ng Zorro or Antd(React) font-icon Local Deployment.
## Feature
1. No more request ali server;
2. Use Webpack for bundle fonts;
3. No less.
## Install
1.
```
npm install --save-dev @hjin/fuck-anticon
# or
yarn add --dev @hjin/fuck-anticon
```
2. Add PostInstall to your package.json
```
"scripts": {
"postinstall": "fuck-anticon"
},
```
3. (Optional) Add fonts to your global style Only for NgZorro 0.6 or lower.
```
@font-face {
font-family: 'anticon';
src: url('../node_modules/ng-zorro-antd/src/assets/fonts/iconfont.eot'); /* IE9*/
src:
/* IE6-IE8 */
url('../node_modules/ng-zorro-antd/src/assets/fonts/iconfont.eot?#iefix') format('embedded-opentype'),
/* chrome、firefox */
url('../node_modules/ng-zorro-antd/src/assets/fonts/iconfont.woff') format('woff'),
/* chrome、firefox、opera、Safari, Android, iOS 4.2+*/
url('../node_modules/ng-zorro-antd/src/assets/fonts/iconfont.ttf') format('truetype'),
/* iOS 4.1- */
url('../node_modules/ng-zorro-antd/src/assets/fonts/iconfont.svg#iconfont') format('svg');
}
```
自己动手丰衣足食 NG-ZORRO/ng-zorro-antd#158<file_sep>const fs = require("fs");
const path = require("path");
const cpFile = require("cp-file");
const find = require("find");
describe("remove ng-zorro font-face", () => {
let toBeReplaceFile = [];
let tmpFile = [];
beforeEach(done => {
new Promise((resolve, reject) => {
find
.file(
/.js$/,
path.join(__dirname, "../node_modules/ng-zorro-antd"),
files => {
const result = [];
for (let f of files) {
const content = fs.readFileSync(f);
if (
content.indexOf("@font-face") > -1 &&
content.indexOf("anticon") > -1
) {
result.push(f);
}
}
resolve(result);
}
)
.error(function(err) {
reject(err);
});
})
.then(result => {
toBeReplaceFile = Array.from(result);
tmpFile = toBeReplaceFile.map(s => s + ".tmp");
return Promise.all(
toBeReplaceFile.map((s, index) => {
return cpFile(s, tmpFile[index]);
})
);
})
.then(() => {
done();
})
.catch(err => done.fail(err));
});
afterEach(done => {
Promise.all(
toBeReplaceFile.map((s, index) => {
return cpFile(tmpFile[index], s);
})
)
.then(done)
.catch(done.fail);
});
it("should contain anticon font face", () => {
toBeReplaceFile.map(s => {
const content = fs.readFileSync(s);
expect(content.indexOf("'anticon'")).toBeGreaterThan(-1);
});
});
it("should remove anticon font face", done => {
const replace = require("../src/ng");
replace
.then(() => {
return Promise.all(
toBeReplaceFile.map(s => {
const content = fs.readFileSync(s);
expect(content.indexOf("/at.alicdn.com/")).toBe(-1, s);
return Promise.resolve();
})
);
})
.then(done)
.catch(done.fail);
});
});
describe("remove antd font-face", () => {
it("should remove anticon remote url", done => {
done();
});
});
<file_sep>const fs = require("fs");
const path = require("path");
const https = require("https");
const url = require("url");
const replace = require("replace-in-file");
module.exports = () => {
let cssPath = path.join(process.cwd(), "./node_modules/antd/dist/antd.css");
const options = {
files: ["node_modules/antd/dist/*.css"],
from: /https:\/\/at\.alicdn\.com\/t\//g,
to: "./"
};
console.log("download antd's font file...");
let cssContent = fs.readFileSync(cssPath, {
encoding: "utf8"
});
const distDir = path.join(process.cwd(), "./node_modules/antd/dist");
let urlRegex = /https:\/\/at\.alicdn\.com\/t\/font_[_a-zA-Z0-9]+\.(eot|woff|ttf|svg)\b/g;
let fonts = new Set(cssContent.match(urlRegex));
let downloadAll = [];
for (let f of fonts) {
downloadAll.push(
new Promise((resolve, reject) => {
download(
f,
path.join(distDir, path.parse(url.parse(f).path).base),
err => {
if (err) {
reject(err);
}
resolve();
}
);
})
);
}
return Promise.all(downloadAll)
.then(() => replace(options))
.then(changedfiles => {
console.log("modified files:", changedfiles.join(", "));
})
.catch(err => {
console.error(err);
throw err;
});
};
function download(url, dist, callback) {
let file = fs.createWriteStream(dist);
https
.get(url, function(response) {
response.pipe(file);
file.on("finish", function() {
file.close(); // close() is async, call cb after close completes.
callback();
});
})
.on("error", function(err) {
// Handle errors
fs.unlink(dist); // Delete the file async. (But we don't check the result)
if (callback) callback(err);
});
}
<file_sep>#!/usr/bin/env node
"use strict";
const path = require("path");
const semver = require("semver");
const ngReplace = require("./ng_gte_0_7");
const ngOldReplace = require("./ng_lte_0_6");
const reactReplace = require("./react");
const pkg = require(path.join(process.cwd(), "./package.json"));
if (pkgContain(pkg, "antd")) {
reactReplace();
}
if (pkgContain(pkg, "ng-zorro-antd", "<0.7.0")) {
ngOldReplace();
}
if (pkgContain(pkg, "ng-zorro-antd", ">=0.7.0")) {
ngReplace();
}
function pkgContain(pkg, search, ver) {
const inPkg =
Object.keys(pkg.dependencies).indexOf(search) > -1 ||
Object.keys(pkg.devDependencies).indexOf(search) > -1;
if (!inPkg) {
return false;
}
if (!ver) {
return inPkg;
}
const targetPkg = path.join(
process.cwd(),
"node_modules",
search,
"package.json"
);
return semver.satisfies(require(targetPkg).version, ver);
}
<file_sep>"use strict";
const replace = require("replace-in-file");
const options = {
files: ["node_modules/ng-zorro-antd/**/*.js"],
from: /@font-face {[^{}]*?anticon[^{}]*?}/gi,
to: ""
};
module.exports = () =>
new Promise((resolve, reject) => {
replace(options)
.then(changedfiles => {
console.log("modified files:", changedfiles.join(", "));
resolve();
})
.catch(error => {
console.error("error occurred:", error);
reject();
});
});
|
4535bf7ff47db4441d93a5ad96d0e059b8884f25
|
[
"Markdown",
"JavaScript"
] | 5
|
Markdown
|
hjin-me/fuck-anticon
|
d8eaa1fb9e5721a24e1a22fea93f4f8962668b7f
|
a765111cccbedb108e1537b823c9600a5b0184fc
|
refs/heads/master
|
<file_sep>from django.db import models
from django_mysql.models import ListCharField
class Lexico(models.Model):
name = models.CharField(max_length=100)
lista = ListCharField(
base_field=models.CharField(max_length=10),
size=6,
max_length=(6 * 11), # 6 * 10 character nominals, plus commas
default=None
)
# Create your models here.
<file_sep>from django.conf.urls import url
from .views import searchlex
urlpatterns = [
url(r'^search/$',searchlex, name = 'searchlex')
]<file_sep>from django.contrib import admin
from .models import Lexico
admin.site.register(Lexico)
# Register your models here.
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2019-01-04 19:38
from __future__ import unicode_literals
from django.db import migrations, models
import django_mysql.models
class Migration(migrations.Migration):
dependencies = [
('search', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='lexico',
name='lista',
field=django_mysql.models.ListCharField(models.CharField(max_length=10), default=None, max_length=66, size=6),
),
]
<file_sep>from django.shortcuts import render
from .models import Lexico
from django.http import HttpResponse
def searchlex(request):
hola = Lexico.objects.all().order_by('id')
return render(request,'search.html', {'hola':hola})
# Create your views here.
|
f57d2d8ff772c2d6509247bf418d3277fabeb360
|
[
"Python"
] | 5
|
Python
|
juliamendoim/GeneradorDj
|
5bc80b31953fe001eb0c4c88c76787223c45d4ff
|
b65fab0cb419bcf4164d9998eca289535b05e621
|
refs/heads/master
|
<repo_name>BilalHRDY/EpreuveAngular<file_sep>/src/app/add-joueur/add-joueur.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
// import { ToastrService } from 'ngx-toastr';
import { Joueur } from '../class/joueur';
import { JoueurService } from '../service/joueur.service';
@Component({
selector: 'app-add-joueur',
templateUrl: './add-joueur.component.html',
styleUrls: ['./add-joueur.component.css']
})
export class AddJoueurComponent implements OnInit {
joueurFormulaire= new Joueur();
joueurPoste = ['gardien', 'attaquant', 'milieu', 'defenseur'];
isLoading = false;
constructor(private router: Router, private joueurService: JoueurService) { }
ngOnInit(): void {
}
joueurSubmit(){
this.isLoading = true
this.joueurService.add(this.joueurFormulaire).subscribe(data => {
this.router.navigate(['/']);
// this.notifier.success(this.joueurFormulaire.nom +' ajouté', 'Félicitations, vous avez ajouter un joueur')
})
}
}
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AddJoueurComponent } from './add-joueur/add-joueur.component';
import { DetailJoueurComponent } from './detail-joueur/detail-joueur.component';
import { HomePageComponent } from './home-page/home-page.component';
const routes : Routes = [
{path:'', component: HomePageComponent},
{path:'joueur/add', component: AddJoueurComponent},
{path:'joueur/:id', component: DetailJoueurComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
48a421b38bc90ca22def7303dae08595388c68d9
|
[
"TypeScript"
] | 2
|
TypeScript
|
BilalHRDY/EpreuveAngular
|
79791c4442ffa0260b4af45dbf0aad08472c0a24
|
25016b585a9beb1d559b1ef5e64080bc526596c5
|
refs/heads/master
|
<repo_name>Juantorresma/os-labs<file_sep>/lab5.2/README.md
From the attached document, implement your own Virtual Memory Manager.
Skip the Statistrics and Modifications sections.
Required and testing files are also in the below links.
All code must be located at your os-labs repository in a new directory lab5.2
Add the README.md file with description and how to compile and run your code.
The lab can be done in teams of maximum 3 members.
Team:
<NAME>
<NAME>
how to run
python memorymanager.py
<file_sep>/lab7.1/server1.c
/* Make the necessary includes and set up the variables. */
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdlib.h>
typedef struct {
char oper;
int values[10];
} pack;
int main()
{
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_un server_address;
struct sockaddr_un client_address;
/* Remove any old socket and create an unnamed socket for the server. */
unlink("server_socket");
server_sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
/* Name the socket. */
server_address.sun_family = AF_UNIX;
strcpy(server_address.sun_path, "server_socket");
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
/* Create a connection queue and wait for clients. */
listen(server_sockfd, 5);
while (1) {
char ch;
printf("server waiting\n");
/* Accept a connection. */
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd,
(struct sockaddr *)&client_address, &client_len);
/* We can now read/write to client on client_sockfd. */
pack p;
read(client_sockfd, &p, sizeof(pack));
int resta = 0;
int i = 0;
if (p.oper == '+') {
for (i = 0;i<10;i++) {
resta = resta + p.values[i];
}
}
else if (p.oper == '-') {
resta=p.values[0];
for (i = 1;i<10;i++) {
resta = resta - p.values[i];
}
}
else if (p.oper == '*') {
resta = 1;
for (i = 0;i<10;i++) {
resta = resta * p.values[i];
}
}
else {
printf("Server: Invalid Operation \n");
}
printf("Server - Result: %d \n", resta);
close(client_sockfd);
}
}
<file_sep>/lab1.6/lab16.c
/**
* Simple shell interface program.
*
* Operating System Concepts - Ninth Edition
* Copyright <NAME> - 2013
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#define MAX_LINE 80 /* 80 chars per line, per command */
int main(void)
{
char buf[MAX_LINE/2 + 1]; /* command line (of 80) has max of 40 arguments */
int should_run = 1;
pid_t baby_pid;
int i=0, upper=0;
while (should_run){
printf("osh>");
fflush(stdout);
fgets(buf,MAX_LINE,stdin);
baby_pid = fork();
if(baby_pid<0){
printf("Not a child or a parent\n");
return 1;
}
else if(baby_pid==0){
char * x[MAX_LINE]={"/bin/bash","-c",buf};
execvp(x[0],x);
return 0;
}
else if (baby_pid > 0){
wait(NULL);
return 0;
}
}
return 0;
}
<file_sep>/lab5.2/memorymanager.py
from numpy import roll, array
def Buscar(numPagina):
for n in TLB:
if n["page"] == numPagina:
return n["frame"]
return None
def push(TLB, numPagina, numFrame):
TLB = roll(TLB, 1)
TLB[0]["Pagina"] = numPagina
TLB[0]["Frame"] = numFrame
return TLB
def leerStorage (numPagina):
añadirStorage = numPagina*256
with open("BACKING_STORE.bin", "rb") as archivo:
archivo.seek(añadirStorage)
for i in range(256):
data = archivo.read(1)
memFisica[Frame*tamañoPag+i] = data
def leerAddressVirtual(filename):
with open(filename) as archivo:
addressVirtual = archivo.readlines()
return [int(x.strip()) for x in addressVirtual]
def ordenar(byte):
un = ord(byte)
return un - 256 if un > 127 else un
if __name__ == "__main__":
filename = "addresses.txt"
tamañoPag = 256
numPaginas = 256
tamaño = 16
numPagMask = 65280
pagTabla = [None]*numPaginas
memFisica = [None]*numPaginas*tamañoPag
frame = 0
cont = 0
TLB = []
for i in range(tamaño):
TLB.append({"page":-1, "frame": -1})
TLB = array(TLB)
with open("test.txt", "w") as myfile:
addressesVirtuales = leerAddressVirtual(filename)
for añadirVirt in addressesVirtuales:
numPagina = añadirVirt&numPagMask
numPagina = numPagina>>8
offset = añadirVirt&255
Frame = Buscar(numPagina)
if Frame:
adressesFis = Frame*256 + offset
cont = cont + 1
elif not pagTabla[numPagina]:
leerStorage(numPagina)
pagTabla[numPagina] = frame
TLB = push(TLB, numPagina, frame)
frame = frame + 1
adressesFis = pagTabla[numPagina]*256 + offset
else:
TLB = push(TLB, numPagina, pagTabla[numPagina])
adressesFis = pagTabla[numPagina]*256 + offset
value = memFisica[adressesFis]
myfile.write("Virtual address: {} Physical address: {} Value: {}\n".format(añadirVirt, adressesFis, ordenar(value)))
<file_sep>/lab1.9/Readme.txt
gcc multipliplication.c -o multiplication -lpthread
./multiplication
<file_sep>/lab1.7/main.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
int n=10;
int bt[10];
int wt[10];
int rt[10];
int avwt=0;
int i;
int j;
int total=0;
int pos;
int temp;
int count;
int time;
int remain;
int flag=0;
int time_quantum;
wt[0]=0;
void FCFS (void){
printf("\Write Burst Time of processes\n");
for(i=0;i<n;i++)
{
printf("P[%d]:",i+1);
scanf("%d",&bt[i]);
}
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
}
printf("\nProcess\t\tBurst Time");
avwt/=i;
printf("\n\nAverage Waiting Time:%d",avwt);
return 0;
}
void PSA (void){
printf("\nMeter Burst time and priority\n");
for(i=0;i<n;i++)
{
printf("\nP[%d]\n",i+1);
printf("Burst Time:");
scanf("%d",&bt[i]);
printf("Priority:");
scanf("%d",&pr[i]);
p[i]=i+1;
}
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(pr[j]<pr[pos])
pos=j;
}
tem=pr[i];
pr[i]=pr[pos];
pr[pos]=tem;
tem=bt[i];
bt[i]=bt[pos];
bt[pos]=tem;
tem=p[i];
p[i]=p[pos];
p[pos]=tem;
}
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
total+=wt[i];
}
avwt/=i;
printf("\n\nAverage Waiting Time=%d",avwt);
}
void SJF (void){
printf("\nEnter Burst Time:\n");
for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1;
}
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])
pos=j;
}
tem=bt[i];
bt[i]=bt[pos];
bt[pos]=tem;
tem=p[i];
p[i]=p[pos];
p[pos]=tem;
}
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
}
avwt/=i;
printf("\nProcess\t Burst Time \tWaiting Time");
printf("\n\nAverage Waiting Time=%f",avwt);
}
int main(void){
srand(time(NULL));
unsigned char x=1;
while(x){
char select;
printf("Select:\n1) PSA\n2) SJF\n3) FCFS\n> ");
scanf("%c",&num);
if(num==1){
PSA();
}
else if (num==2){
SJF();
}
else if (num==3){
FCFS();
}
}
return 0;
}
<file_sep>/lab7.2/README.md
gcc client3.c -o client3
gcc server3.c -o server3
./server3 &
./client3 ID<file_sep>/lab1.8/helloToMany.c
#include <pthread.h>
#include <stdio.h>
/* the thread runs in this function */
void *runner(void *param);
main(int argc, char *argv[])
{
int i, policy;
int ThreadsNumber;
int valor, j;
printf("Number of Threads you wish to enter: ");
fflush(stdout);
scanf("%d",&ThreadsNumber);
args args_array[ThreadsNumber];
pthread_t tid[ThreadsNumber];
pthread_attr_t attr;
pthread_attr_init(&attr);
if (pthread_attr_getschedpolicy(&attr,&policy) != 0)
fprintf(stderr, "Unable to get policy.\n");
else {
if (policy == SCHED_OTHER)
printf("SCHED_OTHER\n");
else if (policy == SCHED_RR)
printf("SCHED_OTHER\n");
else if (policy == SCHED_FIFO)
printf("SCHED_FIFO\n");
}
if (pthread_attr_setschedpolicy(&attr, SCHED_OTHER) != 0)
printf("unable to set scheduling policy to SCHED_OTHER \n");
for (i = 0; i < ThreadsNumber; i++)
args_array[i]=;
args_array[i].valor=i;
pthread_create(&tid[i],&attr,runner,(void *) &args_array[i]);
printf("I am thread 1. Created new thread (%ld) in iteration %d\n",(void *)args_array[i].j,args_array[i].valor);
}
for (i = 0; i < NUM_THREADS; i++)
pthread_join(tid[i], NULL);
}
void *runner(void *param)
{
printf("Hello from thread %d - I was created in iteration %ld\n",a->id,a->iteration);
pthread_exit(0);
}
<file_sep>/lab1.9/multiplication.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_BUFFERS 40
long **buffers[NUM_BUFFERS];
pthread_mutex_t mutexes[NUM_BUFFERS];
pthread_t threads[200];
long *result;
long *matA;
long *matB;
struct MatStruct {
long row;
long *matA_pt;
long *matB_pt;
long *result;
};
long *readMatrix(char *filename);
void printMatrix(long *mat_pt);
long *getColumn(int col, long *matrix);
void printColumn(long *col);
void printRow(long *row);
long *getRow(int row, long *matrix);
int getLock(void);
int releaseLock(int lock);
long dotProduct(long *vec1, long *vec2);
int saveResultMatrix(long *result);
long *multiply(long* matA, long* matB);
void *row_mul(void *args);
long *test(void);
int main(void) {
matA = readMatrix("matA.dat");
matB = readMatrix("matB.dat");
long *result;
result = multiply(matA, matB);
saveResultMatrix(result);
return EXIT_SUCCESS;
}
long *multiply(long *matA, long *matB) {
int i;
int j;
int index;
int rv;
static long *result;
long *row_result_pt;
result = malloc(SIZE * sizeof(long));
for (i = 0; i < 200; i++) {
rv = pthread_create(&threads[i], NULL, &row_mul, (void *) i);
if (rv != 0) {
perror("error");
return 0;
}
}
for (j = 0; j < 200; j++) {
pthread_join(threads[j], (long *) &row_result_pt);
for (index = 0; index < 200; index++) {
*(result + ((j * 200) + index)) = *(row_result_pt + index);
}
}
return result;
}
void *row_mul(void *args) {
long *row;
long *col;
long *result_vec;
int row_n = (int) args;
int lock;
int i;
result_vec = malloc(200 * sizeof(long));
row = getRow(row_n, matA);
lock = getLock();
while (lock == -1) {
lock = getLock();
}
buffers[lock] = &result_vec;
for (i = 0; i < 200; i++) {
col = getColumn(i, matB);
*(*buffers[lock] + i) = dotProduct(row, col);
}
buffers[lock] = 0;
releaseLock(lock);
return (void *) result_vec;
}
long *test(void) {
long *row;
long *col;
int i;
long *pt;
pt = malloc(200 * sizeof(long));
buffers[0] = &pt;
row = getRow(0, matA);
for (i = 0; i < 200; i++) {
col = getColumn(i, matB);
*(*buffers[0] + i) = dotProduct(row, col);
}
return pt;
}
void printMatrix(long *mat_pt) {
int i;
int j;
for (i = 0; i < 200; i++) {
for (j = 0; j < 200; j++) {
printf("[%d][%d] = %ld\n", i, j, *(mat_pt + (i * 200) + j));
}
}
}
void printColumn(long *col) {
int j;
printf("[");
for (j = 0; j < COL; j++) {
printf("%d:%ld, ", j, *(col + j));
}
printf("]\n");
}
void printRow(long *row) {
int j;
printf("[");
for (j = 0; j < 200; j++) {
printf("%d:%ld, ", j, *(row + j));
}
printf("]\n");
}
long *readMatrix(char *filename) {
FILE *file;
int i;
long *matrix;
matrix = malloc(40000 * sizeof(long));
file = fopen(filename, "r");
if (file) {
for (i = 0; i < 40000; i++) {
fscanf(file, "%ld\n", &matrix[i]);
}
fclose(file);
} else {
return 0;
}
return matrix;
}
long *getColumn(int col, long *matrix) {
static long *column;
column = malloc(COL * sizeof(long));
int j;
for (j = 0; j < 200; j++) {
column[j] = matrix[(j * 200) + col];
}
return column;
}
long *getRow(int row, long *matrix) {
long *row_list;
row_list = malloc(200 * sizeof(long));
int i;
for (i = 0; i < 200; i++) {
row_list[i] = matrix[(row * 200) + i];
}
return row_list;
}
int getLock(void) {
int lock;
int i;
for (i = 0; i < NUM_BUFFERS; i++) {
lock = pthread_mutex_trylock(&mutexes[i]);
if (lock == 0) {
return i;
}
}
return -1;
}
int releaseLock(int lock) {
return pthread_mutex_unlock(&mutexes[lock]);
}
long dotProduct(long *vec1, long *vec2) {
int i;
int result;
result = 0;
for (i = 0; i < 200; i++) {
result += vec1[i] * vec2[i];
}
return result;
}
int saveResultMatrix(long *result) {
FILE *f = fopen("resultado.dat", "w+");
for (int i = 0; i < 40000; i++) {
fprintf(f, "%ld\n", *(result + i));
}
fclose(f);
return 0;
}
<file_sep>/lab7.1/README.md
gcc client1.c -o client1
gcc server1.c -o server1
./server1 &
./client1 ID
|
253ddfc15eb4df9559daeccd699c729d91190a18
|
[
"Markdown",
"C",
"Python",
"Text"
] | 10
|
Markdown
|
Juantorresma/os-labs
|
3cb15e3ea229f1a02c4b43c7bce1d467831ff4a6
|
7bbc7d581f9107c0e7eae3908cbd32ccc41bda58
|
refs/heads/master
|
<file_sep># NLP100本ノック
#
# 62. KVS内の反復処理
# 60で構築したデータベースを用い,活動場所が「Japan」となっているアーティスト数を求めよ.
import redis
import time
def count_by_area(r, area):
cnt = 0
keys = r.keys()
for key in keys:
data = r.hgetall(key)
for key, value in data.items():
if value == area:
cnt += 1
return cnt
if __name__ == '__main__':
r = redis.StrictRedis(host="localhost", port=6379, db=1)
area = b"Japan"
cnt = count_by_area(r, area)
print(cnt)
<file_sep># NLP100本ノック
#
# 夏目漱石の小説『吾輩は猫である』の文章(neko.txt)をMeCabを使って形態素解析し,
# その結果をneko.txt.mecabというファイルに保存せよ.このファイルを用いて,以下の問に対応するプログラムを実装せよ.
# なお,問題37, 38, 39はmatplotlibもしくはGnuplotを用いるとよい.
# 30. 形態素解析結果の読み込み
# 形態素解析結果(neko.txt.mecab)を読み込むプログラムを実装せよ.
# ただし,各形態素は表層形(surface),基本形(base),品詞(pos),品詞細分類1(pos1)を
# キーとするマッピング型に格納し,1文を形態素(マッピング型)のリストとして表現せよ.
# 第4章の残りの問題では,ここで作ったプログラムを活用せよ.
# neko.txtの解析
# $ mecab neko.txt -o neko.txt.mecab
def mecab_to_dic(mecab_text):
"""
MeCabの解析結果(MeCabの出力形式)1行から、形態素の
表層形(surface), 基本(base), 品(pos), 品詞細分類1(pos1)を
keyとする辞書型を作成する
args:
file_name: str, MeCabの解析結果の1行分
return:
morph_list: list, 形態素の辞書
"""
mecab_text = mecab_text.replace("\n", "")
tab_split = mecab_text.split("\t")
element_list = tab_split[1].split(",")
morph_dic = {"surface": tab_split[0],
"base": element_list[6],
"pos": element_list[0],
"pos1": element_list[1]}
return morph_dic
def read_mecab(file_name):
"""
MeCabの解析結果から1行ごとに読み込んで、mecab_to_dicに渡す.
返ってきた辞書は元のテキスト1行分(EOSが現れる)ごとにリストに格納.
今回元のテキストneko.txtは1行1文になっているのでEOSで区切れば,
1文ごとに形態素をリストに格納できる.
各文のリストはさらにリストにネストする
args:
file_neme: str, MeCabの解析結果のファイル名
return:
all_sentences: list, 1文ごとの形態素のリストを要素としたリスト
"""
morph_list = []
all_sentences = []
with open(file_name, "r", encoding="utf-8") as f:
for line in f:
if line == "EOS\n":
if morph_list:
all_sentences.append(morph_list)
morph_list = []
continue
morph_dic = mecab_to_dic(line)
morph_list.append(morph_dic)
return all_sentences
if __name__ == '__main__':
file_name = "neko.txt.mecab"
all_sentences = read_mecab(file_name)
for sentence in all_sentences[::100]:
print(sentence)
print('\n')
<file_sep># NLP100本ノック
#
# 24. ファイル参照の抽出
# 記事から参照されているメディアファイルをすべて抜き出せ.
# File:で始まってるやつを抜き出せばよいのかな?
import re
pattern = re.compile(r"File:([^|]+)\|")
with open("jawiki-britain.txt", "r", encoding="utf-8") as f:
for line in f:
match = re.search(pattern, line)
if match:
print(match.group(1))
<file_sep># NLP100本ノック
#
# 09. Typoglycemia
# スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,
# それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.
# ただし,長さが4以下の単語は並び替えないこととする.
# 適当な英語の文(例えば"I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .")
# を与え,その実行結果を確認せよ.
import random
def Typoglycemia(text):
word_list = text.split()
new_word_list = []
for i in word_list:
if len(i) > 4:
temp = ""
temp += i[0]
# random.shuffle()は文字列に直接使えないのでrandom.sampleを使ってみる
temp += "".join(random.sample(i[1:-1], len(i[1:-1])))
temp += i[-1]
new_word_list.append(temp)
else:
new_word_list.append(i)
return " ".join(new_word_list)
if __name__ == '__main__':
text = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."
print(Typoglycemia(text))
<file_sep># NLP100本ノック
#
# 25. テンプレートの抽出
# 記事中に含まれる「基礎情報」テンプレートのフィールド名と値を抽出し,
# 辞書オブジェクトとして格納せよ.
# 公式国名が複数行にまたがっているので面倒そう
import re
# のちの問題でも使ったので関数化
def parse_info(text):
# いったん基礎情報の部分を抜き出す
pattern_f = re.compile(r"{{基礎情報.+^}}", re.MULTILINE | re.DOTALL)
text = re.search(pattern_f, text).group()
# re.split()で各情報ごとに切り取ってから処理したほうがやりやすい
# が、あえて正規表現を使って一発で取り出すと
pattern_g = re.compile(r"^\|([^ ]+) = (.+?)(\n(?=\|)|\n(?=}}))", re.M | re.S)
match_list_temp = re.findall(pattern_g, text)
match_list = [[i[0], i[1]] for i in match_list_temp]
return match_list
if __name__ == '__main__':
with open("jawiki-britain.txt", "r", encoding="utf-8") as f:
text = f.read()
info_list = parse_info(text)
for info in info_list:
print("{}: \n{}\n".format(info[0], info[1]))
<file_sep># NLP100本ノック
#
# 34. 「AのB」
# 2つの名詞が「の」で連結されている名詞句を抽出せよ.
from nlp030 import read_mecab
file_name = "neko.txt.mecab"
all_sentences = read_mecab(file_name)
for sentence in all_sentences:
if len(sentence) < 3:
continue
for i in range(len(sentence)-2):
if sentence[i]["pos"] == sentence[i+2]["pos"] == "名詞":
if sentence[i+1]["surface"] == "の":
l = [s["surface"] for s in sentence[i:i+3]]
print("".join(l))
<file_sep># NLP100本ノック
#
# 08. 暗号文
# 与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.
# 英小文字ならば(219 - 文字コード)の文字に置換
# その他の文字はそのまま出力
# この関数を用い,英語のメッセージを暗号化・復号化せよ.
def cipher(raw_str):
cipher_str = ""
for i in raw_str:
if i.islower():
cipher_str += chr(219 - ord(i))
else:
cipher_str += i
return cipher_str
if __name__ == '__main__':
strings = "I am an NLPer"
print(strings)
print(cipher(strings))
print(cipher(cipher(strings)))
<file_sep># NLP100本ノック
#
# 56. 共参照解析
# Stanford Core NLPの共参照解析の結果に基づき,
# 文中の参照表現(mention)を代表参照表現(representative mention)に置換せよ.
# ただし,置換するときは,「代表参照表現(参照表現)」のように,
# 元の参照表現が分かるように配慮せよ.
import re
import xml.etree.ElementTree as ET
def get_coreferences(elem):
"""
coreferenceの関係を使いやすい形で抜き出しておく関数
args:
elem: nlp.txt.xmlを読み込んだETオブジェクト
return:
{
s_id:[(s_id, e_id, mention, rep_mention), ...],
...
}
sentence_idをkeyとする辞書型、要素はタプルのリスト
各タプル()は(開始id, 終端id, mention, rep_mention)
"""
cf_list = elem.find(".//coreference")
cf_dic = {}
for cf in cf_list:
for m in cf.findall("mention"):
if m.get("representative") == "true":
rep_mention = m.findtext("text")
else:
s_id = m.findtext("sentence")
m_tuple = (m.findtext("start"), m.findtext("end"),
m.findtext("text"), rep_mention)
cf_dic[s_id] = cf_dic.get(s_id, [])
cf_dic[s_id].append(m_tuple)
return cf_dic
def replace_mention(elem):
"""
参照表現を代表参照表現に置換しながら出力する関数
args:
elem: nlp.txt.xmlを読み込んだETオブジェクト
"""
cf_dic = get_coreferences(elem)
for sentence in elem.find(".//sentences"):
if sentence.get("id") in cf_dic:
for rep in cf_dic[sentence.get("id")]:
for token in sentence.findall(".//token"):
if token.get("id") == rep[0]:
token.find("word").text = "{}({})".format(rep[3], rep[2])
elif int(rep[0]) < int(token.get("id")) < int(rep[1]):
token.find("word").text = ""
word_list = [token.findtext("word") for token in sentence.findall(".//token") \
if token.findtext("word") != ""]
else:
word_list = [token.findtext("word") for token in sentence.findall(".//token")]
print(" ".join(word_list))
if __name__ == '__main__':
tree = ET.parse("nlp.txt.xml")
elem = tree.getroot()
replace_mention(elem)
<file_sep># NLP100本ノック
#
# 49. 名詞間の係り受けパスの抽出
# 文中のすべての名詞句のペアを結ぶ最短係り受けパスを抽出せよ.
# ただし,名詞句ペアの文節番号がiとj(i<j)のとき,
# 係り受けパスは以下の仕様を満たすものとする.
# 問題48と同様に,パスは開始文節から終了文節に至るまでの
# 各文節の表現(表層形の形態素列)を"->"で連結して表現する
# 文節iとjに含まれる名詞句はそれぞれ,XとYに置換する
# また,係り受けパスの形状は,以下の2通りが考えられる.
# 文節iから構文木の根に至る経路上に文節jが存在する場合:
# 文節iから文節jのパスを表示
# 上記以外で,文節iと文節jから構文木の根に至る経路上で共通の文節kで交わる場合:
# 文節iから文節kに至る直前のパスと文節jから文節kに至る直前までのパス,
# 文節kの内容を"|"で連結して表示
# 例えば,「吾輩はここで始めて人間というものを見た。」という文(neko.txt.cabochaの8文目)から,次のような出力が得られるはずである.
# Xは | Yで -> 始めて -> 人間という -> ものを | 見た
# Xは | Yという -> ものを | 見た
# Xは | Yを | 見た
# Xで -> 始めて -> Y
# Xで -> 始めて -> 人間という -> Y
# Xという -> Y
from nlp041 import read_cabocha
def noun_path(chunk_list):
path_list = []
for chunk in chunk_list:
if "名詞" in chunk.get_pos_list():
for r_chunk in chunk_list[chunk.num+1:]:
if "名詞" in r_chunk.get_pos_list():
path = get_toward_path(chunk_list, chunk.num, r_chunk.num)
if path:
path_list.append(path)
return path_list
def get_toward_path(chunk_list, chunk_num_start, chunk_num_end):
"""
与えられた文のChunkリストから,
指定された文節番号(文節i)から、指定された文節番号(文節j)までの係り受けのパスを返す。
係り受けパスが通っていない場合、
文節iと文節jから構文木の根に至るまでの共通の文節kをさがし、
文節iから文節kに至る直前のパスと文節jから文節kに至る直前までのパス,文節kの内容を返す.
"""
path = [chunk_list[chunk_num_start]]
i_path = [replace_noun(chunk_list[chunk_num_start], "X")]
dst = chunk_list[chunk_num_start].dst
while dst != -1:
if dst == chunk_num_end:
i_path.append(replace_noun(chunk_list[dst], "Y"))
return [i_path]
path.append(chunk_list[dst])
i_path.append(chunk_list[dst].get_surf())
dst = chunk_list[dst].dst
else:
j_dst = chunk_num_end
j_path = [replace_noun(chunk_list[j_dst], "Y")]
while j_dst != -1:
for cnt, i_path_chunk in enumerate(path):
if chunk_list[j_dst].dst == i_path_chunk.dst:
return [i_path[:cnt+1], j_path, [chunk_list[i_path_chunk.dst].get_surf()]]
j_dst = chunk_list[j_dst].dst
j_path.append(chunk_list[j_dst].get_surf())
return None
def replace_noun(chunk, re_noun):
"""
文節から名詞句をre_nounに変換した文字列を返す
"""
re_str = ""
flag = 0
morphs = chunk.get_morphs()
for morph in morphs:
if morph.pos == "名詞":
if flag == 0:
flag = 1
re_str += re_noun
elif morph.pos != "記号":
re_str += morph.surface
return re_str
if __name__ == '__main__':
all_sentences = read_cabocha("neko.txt.cabocha")
for sentence in all_sentences:
path_list = noun_path(sentence)
for path in path_list:
path_str = " | ".join([" -> ".join(x_path) for x_path in path])
print(path_str)
print("-------------------------------------")
<file_sep># NLP100本ノック
#
<file_sep># NLP100本ノック
#
# 54. 品詞タグ付け
# Stanford Core NLPの解析結果XMLを読み込み,単語,レンマ,品詞をタブ区切り形式で出力せよ.
# xmltodictというパッケージを使ってみる
import re
pattern_token = re.compile(r"<token(.+?)</token>", re.DOTALL)
pattern_word = re.compile(r"<word>(.+?)</word>")
pattern_lemma = re.compile(r"<lemma>(.+?)</lemma>")
pattern_pos = re.compile(r"<POS>(.+?)</POS>")
with open("nlp.txt.xml", "r", encoding="utf-8") as f:
text = f.read()
tokens = re.findall(pattern_token, text)
for token in tokens:
word = re.search(pattern_word, token).group(1)
lemma = re.search(pattern_lemma, token).group(1)
pos = re.search(pattern_pos, token).group(1)
print("{}, {}, {}".format(word, lemma, pos))
# xmltodictというパッケージを使って見る単語、練磨,瀕死をタブ区切り形式で出力してい
<file_sep>## 64. MongoDBの構築
アーティスト情報(artist.json.gz)をデータベースに登録せよ.
さらに,次のフィールドでインデックスを作成せよ: name, aliases.name, tags.value, rating.value
* データベースへの登録
```
$ mongoimport --db test_db --collection test_coll --type json --file artist.json
```
* インデックスの作成
```
# 最初の状態
> db.test_coll.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test_db.test_coll"
}
]
# インデックスの作成: name
> db.test_coll.createIndex({name: 1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
# インデックスの作成: alieses.name
> db.test_coll.createIndex({"aliases.name": 1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
# インデックスの作成: tags.value
> db.test_coll.createIndex({"tags.value": 1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 3,
"numIndexesAfter" : 4,
"ok" : 1
}
# インデックスの作成: rating.value
> db.test_coll.createIndex({"rating.value": 1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 4,
"numIndexesAfter" : 5,
"ok" : 1
}
# 作成したインデックスの確認
> db.test_coll.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test_db.test_coll"
},
{
"v" : 1,
"key" : {
"name" : 1
},
"name" : "name_1",
"ns" : "test_db.test_coll"
},
{
"v" : 1,
"key" : {
"aliases.name" : 1
},
"name" : "aliases.name_1",
"ns" : "test_db.test_coll"
},
{
"v" : 1,
"key" : {
"tags.value" : 1
},
"name" : "tags.value_1",
"ns" : "test_db.test_coll"
},
{
"v" : 1,
"key" : {
"rating.value" : 1
},
"name" : "rating.value_1",
"ns" : "test_db.test_coll"
}
]
```
<file_sep># NLP100本ノック
#
# 32. 動詞の原形
# 動詞の原形をすべて抽出せよ.
from nlp030 import read_mecab
file_name = "neko.txt.mecab"
all_sentences = read_mecab(file_name)
for sentence in all_sentences:
for morph in sentence:
if morph["pos"] == "動詞":
print(morph["base"])
<file_sep># NLP100本ノック
#
# Wikipediaの記事を以下のフォーマットで書き出したファイルjawiki-country.json.gzがある.
# 1行に1記事の情報がJSON形式で格納される
# 各行には記事名が"title"キーに,記事本文が"text"キーの辞書オブジェクトに格納され,
# そのオブジェクトがJSON形式で書き出される
# ファイル全体はgzipで圧縮される
# 以下の処理を行うプログラムを作成せよ.
# 20. JSONデータの読み込み
# Wikipedia記事のJSONファイルを読み込み,
# 「イギリス」に関する記事本文を表示せよ.
# 問題21-29では,ここで抽出した記事本文に対して実行せよ.
import json
with open("jawiki-country.json", "r", encoding="utf-8") as f:
for line in f:
data = json.loads(line)
if data["title"] == "イギリス":
print(data["text"])
with open("jawiki-britain.txt", "w", encoding="utf-8") as f2:
f2.write(data["text"])
# WindowsだとたぶんUnicodeEncodeErrorになるので以下をつかう
# print(data["text"].encode("sjis", "ignore").decode("sjis"))
"""
めも
与えられたjsonファイルをファイルオブジェクトからjson.load()で一度に読み込もうとすると,
In [1]: f = open("jawiki-country.json", "r", encoding="utf-8")
In [2]: s = json.load(f)
JSONDecodeError: Extra data: line 2 column 1 (char 27837)
と怒られた.
与えられたjsonファイルは次のような形式
{"text": "本文1", "title": "国名1"}
{"text": "本文2", "title": "国名2"}
{"text": "本文3", "title": "国名3"}
...略
これは辞書型を羅列した形になっていて, pythonのデータ構造として一度に読み込めない.
つまり、たぶんjson.load()で読み込めない. (オプションを指定すれば解決できる?)
json.load()で読み込むには,
[
{"text": "本文1", "title": "国名1"},
{"text": "本文2", "title": "国名2"},
{"text": "本文3", "title": "国名3"}
]
みたいに、各辞書が配列の要素となるような構造となってる必要がある.
"""<file_sep># NLP100本ノック
#
# 14. 先頭からN行を出力
# 自然数Nをコマンドライン引数などの手段で受け取り,
# 入力のうち先頭のN行だけを表示せよ.確認にはheadコマンドを用いよ.
print("行数:")
N = int(input())
with open("hightemp.txt", "r", encoding="utf-8") as f:
for i in range(N):
print(f.readline())<file_sep># NLP100本ノック
#
# 31. 動詞
# 動詞の表層形をすべて抽出せよ
from nlp030 import read_mecab
file_name = "neko.txt.mecab"
all_sentences = read_mecab(file_name)
for sentence in all_sentences:
for morph in sentence:
if morph["pos"] == "動詞":
print(morph["surface"])
<file_sep># NLP100本ノック
#
# 57. 係り受け解析
# Stanford Core NLPの係り受け解析の結果(collapsed-dependencies)を有向グラフとして可視化せよ.
# 可視化には,係り受け木をDOT言語に変換し,Graphvizを用いるとよい.
# また,Pythonから有向グラフを直接的に可視化するには,pydotを使うとよい.
import xml.etree.ElementTree as ET
from graphviz import Digraph
def dep_to_graph(elem, s_id):
"""
Stanford Core NLPの解析結果xmlから係り受け関係のグラフを作成する関数
args:
elem: ETオブジェクト, Stanford Core NLPの解析結果xmlのETパーザオブジェクト
s_id: int, グラフ化するセンテンスid
"""
g = Digraph(format="png")
sentence = elem.findall(".//sentence")[s_id - 1]
coll_dep = sentence.find("dependencies[@type='collapsed-dependencies']")
dep_list = coll_dep.findall("dep")
for dep in dep_list:
gov_idx = dep.find("governor").get("idx")
gov_text = dep.find("governor").text
dep_idx = dep.find("dependent").get("idx")
dep_text = dep.find("dependent").text
# ROOTは出力しない
if gov_text == "ROOT":
continue
# グラフにノードとエッジを追加
g.node(gov_idx, gov_text)
g.node(dep_idx, dep_text)
g.edge(dep_idx, gov_idx)
print(g)
g.render("nlp057_result")
if __name__ == '__main__':
tree = ET.parse("nlp.txt.xml")
elem = tree.getroot()
print("sentences id: ") #標準入力でグラフ化するsentence idを指定
s_id = int(input())
dep_to_graph(elem, s_id)
<file_sep># NLP100本ノック
#
# 29. 国旗画像のURLを取得する
# テンプレートの内容を利用し,国旗画像のURLを取得せよ.
# (ヒント: MediaWiki APIのimageinfoを呼び出して,ファイル参照をURLに変換すればよい)
import requests
import re
# API:Imageinfoのページの例をほとんどそのまま
payload = {"action":"query",
"titles":"File:Flag of the United Kingdom.svg",
"prop":"imageinfo",
"iiprop":"url",
"format":"json"}
r = requests.get("https://ja.wikipedia.org/w/api.php", params=payload)
# jsonに直すと(辞書のkeyがページidになっていて)参照するのが面倒になるので正規表現で抽出
url = re.search(r'"url":"([^"]+)",', r.text).group(1)
print(url)
# urllibはモダンじゃないから使わないとインターン先ですごい人が言ってました.
# requestsを使っているので、入っていない場合は
# $ pip install requests
<file_sep># NLP100本ノック
#
# 48. 名詞から根へのパスの抽出
# 文中のすべての名詞を含む文節に対し,その文節から構文木の根に至るパスを抽出せよ.
# ただし,構文木上のパスは以下の仕様を満たすものとする.
# 各文節は(表層形の)形態素列で表現する
# パスの開始文節から終了文節に至るまで,各文節の表現を"->"で連結する
# 「吾輩はここで始めて人間というものを見た」という文(neko.txt.cabochaの8文目)から,
# 次のような出力が得られるはずである.
# 吾輩は -> 見た
# ここで -> 始めて -> 人間という -> ものを -> 見た
# 人間という -> ものを -> 見た
# ものを -> 見た
from nlp041 import read_cabocha
def chunk_path(chunk_list, leaf_pos="名詞"):
"""
指定した品詞を持つ文節から構文木の根に至るパスを返す
args:
chunk_list, list, Chunkオブジェクトのリスト
dst_pos: str, 品詞
return:
path_list, list, パスのリスト. パスはChunkのリストとして表現
"""
path_list = []
for chunk in chunk_list:
if leaf_pos in chunk.get_pos_list():
path = [chunk]
dst = chunk.dst
while dst != -1:
path.append(chunk_list[dst])
dst = chunk_list[dst].dst
path_list.append(path)
return path_list
if __name__ == '__main__':
all_sentences = read_cabocha("neko.txt.cabocha")
for sentence in all_sentences:
path_list = chunk_path(sentence)
for path in path_list:
print(" -> ".join([chunk.get_surf() for chunk in path]))
print("------------------------------------")<file_sep># mongodbクライアント
import pymongo
from pymongo import MongoClient
class ArtistsDataBase():
def __init__(self, db, collection, hostname="localhost", port=27017):
self.client = MongoClient(hostname, port)
self.coll = self.client[db][collection]
def generate_query(self, elem):
"""
pymongoの検索条件のリストを生成するメソッド
"""
query = []
for field in ["name", "area"]:
if elem.get(field, ""):
query.append({field: elem[field]})
if elem.get("aliase", ""):
query.append({"aliase":{"$elemMatch": {"name": elem["aliase"]}}})
if elem.get("tag", ""):
query.append({"tags":{"$elemMatch": {"value": elem["tag"]}}})
return query
def search_artists(self, query):
"""
検索条件のリストからand検索した結果をratingでソートして返すメソッド
"""
data = self.coll.find({"$and": query})
data = data.sort("rating.count", pymongo.DESCENDING).limit(50)
results = []
for doc in data:
art_dic = {}
art_dic["name"] = doc.get("name", "")
art_dic["aliases"] = ", ".join([i["name"] for i in doc.get("aliases", [{"name": ""}])])
art_dic["area"] = doc.get("area", "")
art_dic["tags"] = ", ".join([i["value"] for i in doc.get("tags", [{"value": ""}])])
art_dic["rating"] = doc.get("rating", {"count": ""})["count"]
results.append(art_dic)
return results
if __name__ == '__main__':
DATABASE = "test_db"
COLLECTION = "test_coll"
art_db = ArtistsDataBase(db=DATABASE, collection=COLLECTION)
elem_dic = {}
elem_dic.update({"name":"", "area": "", "tag": "dance"})
results = art_db.search_artists(art_db.generate_query(elem_dic))
print(results)
fields = ["name", "aliases", "area", "tags", "rating"]
for artist in results:
for field in fields:
print(artist[field])
print("---------------------")
<file_sep># NLP100本ノック
#
# hightemp.txtは,日本の最高気温の記録を「都道府県」「地点」「℃」「日」の
# タブ区切り形式で格納したファイルである.以下の処理を行うプログラムを作成し,
# hightemp.txtを入力ファイルとして実行せよ.
# さらに,同様の処理をUNIXコマンドでも実行し,プログラムの実行結果を確認せよ.
#
# 10. 行数のカウント
# 行数をカウントせよ.確認にはwcコマンドを用いよ
with open("hightemp.txt", "r", encoding="utf-8") as f:
print(len(f.readlines()))
# UNIXコマンド
# あとで<file_sep># NLP100本ノック
#
# 33. サ変名詞
# サ変接続の名詞をすべて抽出せよ.
from nlp030 import read_mecab
file_name = "neko.txt.mecab"
all_sentences = read_mecab(file_name)
for sentence in all_sentences:
for morph in sentence:
if morph["pos1"] == "サ変接続":
print(morph["surface"])
<file_sep># NLP100本ノック
#
# 39. Zipfの法則
# 単語の出現頻度順位を横軸,その出現頻度を縦軸として,両対数グラフをプロットせよ.
import matplotlib.pyplot as plt
from nlp030 import read_mecab
from nlp036 import word_freq
# 日本語フォント読み込み
from matplotlib.font_manager import FontProperties
fp = FontProperties(fname=r'/usr/local/share/fonts/TakaoPGothic.ttf', size=10)
# nlp036の関数から頻度取得
file_name = "neko.txt.mecab"
all_sentences = read_mecab(file_name)
freq_list_desc = word_freq(all_sentences)
# グラフ描写
# すべてのデータだと値の範囲が広すぎてうまく表示されない
# data = [i[1] for i in freq_list_desc]
# 頻度上位200~1000を表示するとそれなりに見えるグラフになる
X = [i for i in range(len(freq_list_desc))]
Y = [i[1] for i in freq_list_desc]
plt.plot(X,Y)
plt.xscale("log") # y軸を対数目盛に
plt.yscale("log") # y軸を対数目盛に
plt.title("Zipfの法則", fontproperties=fp)
plt.xlabel("単語の出現頻度順位",fontproperties=fp)
plt.ylabel("出現頻度",fontproperties=fp)
plt.show()
<file_sep># NLP100本ノック
#
# 43. 名詞を含む文節が動詞を含む文節に係るものを抽出
# 名詞を含む文節が,動詞を含む文節に係るとき,これらをタブ区切り形式で抽出せよ.
# ただし,句読点などの記号は出力しないようにせよ.
# set_chunk_depをテキスト返すのではなく、Chunkオブジェクトとして返すように
# 修正したものを作成した(nlp43_2.py)
from nlp041 import read_cabocha
def set_chunk_pos(chunk_list, src_pos="名詞", dst_pos="動詞"):
"""
1文のchunkリストから
指定した品詞を含む文節->指定した品詞を含む文節の係り受けを見つけ、
(係り元の文節のテキスト, 係り先の文節のテキスト)という
タプルのリストとして返す関数
"""
chunk_dep_list = []
for chunk in chunk_list:
if chunk.dst == -1:
continue
elif src_pos in chunk.get_pos_list() and dst_pos in chunk_list[chunk.dst].get_pos_list():
src_surf = chunk.get_surf()
dst_surf = chunk_list[chunk.dst].get_surf()
chunk_dep_list.append((src_surf, dst_surf))
return chunk_dep_list
if __name__ == '__main__':
all_sentences = read_cabocha("neko.txt.cabocha")
for sentence in all_sentences:
chunk_dep_list = set_chunk_pos(sentence)
for chunk_dep in chunk_dep_list:
print("{}\t{}".format(chunk_dep[0], chunk_dep[1]))
print("\n")
<file_sep># NLP100本ノック
#
# 15. 末尾のN行を出力
# 自然数Nをコマンドライン引数などの手段で受け取り,
# 入力のうち末尾のN行だけを表示せよ.
# 確認にはtailコマンドを用いよ.
print("行数:")
N = int(input())
with open("hightemp.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
for i in range(N):
print(lines[-N+i])<file_sep># NLP100本ノック
#
# 07. テンプレートによる文生成
# 引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.
# さらに,x=12, y="気温", z=22.4として,実行結果を確認せよ
def foo(x, y, z):
return "{}時の{}は{}".format(x, y, z)
if __name__ == '__main__':
x=12
y="気温"
z=22.4
print(foo(x, y, z))<file_sep># NLP100本ノック
#
# 47. 機能動詞構文のマイニング
# 動詞のヲ格にサ変接続名詞が入っている場合のみに着目したい.
# 46のプログラムを以下の仕様を満たすように改変せよ.
# 「サ変接続名詞+を(助詞)」で構成される文節が動詞に係る場合のみを対象とする
# 述語は「サ変接続名詞+を+動詞の基本形」とし,文節中に複数の動詞があるときは,最左の動詞を用いる
# 述語に係る助詞(文節)が複数あるときは,すべての助詞をスペース区切りで辞書順に並べる
# 述語に係る文節が複数ある場合は,すべての項をスペース区切りで並べる(助詞の並び順と揃えよ)
# 例えば「別段くるにも及ばんさと、主人は手紙に返事をする。」という文から,
# 以下の出力が得られるはずである.
# 返事をする と に は 及ばんさと 手紙に 主人は
# このプログラムの出力をファイルに保存し,以下の事項をUNIXコマンドを用いて確認せよ.
# コーパス中で頻出する述語(サ変接続名詞+を+動詞)
# コーパス中で頻出する述語と助詞パターン
from nlp041 import read_cabocha
def case_pattern(chunk_list, dst_pos):
"""
指定した品詞に掛かる格(助詞)を調べる関数
args:
chunk_list, list, Chunkオブジェクトのリスト
dst_pos: str, 品詞
return:
[(サ変名Chunk, 動詞のMorph, (助詞のMorph, ...), (助詞を含むChunk, ...)), ...]
"""
case_list = []
chunk_dep_list = set_src_chunk(chunk_list)
for chunk_dep in chunk_dep_list:
if dst_pos in chunk_dep[0].get_pos_list():
sahen_chunk = None
particles = []
chunks_contain_part = []
verbs = chunk_dep[0].get_morphs(dst_pos)
for chunk in chunk_dep[1]:
morphs = chunk.get_morphs()
if len(morphs) == 2:
if morphs[0].pos1 == "サ変接続" and morphs[1].surface == "を":
sahen_chunk = chunk
continue
if chunk.get_morphs("助詞"):
particles.extend(chunk.get_morphs("助詞"))
chunks_contain_part.append(chunk)
if sahen_chunk:
case_list.append((sahen_chunk, verbs[0], tuple(particles), tuple(chunks_contain_part)))
return case_list
def set_src_chunk(chunk_list):
"""
(chunk, chunkに係るchunkのタプル)のリストを返す関数
"""
chunk_dep_list = []
for chunk in chunk_list:
src_chunk_list = tuple([chunk_list[i] for i in chunk.srcs])
chunk_dep_list.append((chunk, src_chunk_list))
return chunk_dep_list
if __name__ == '__main__':
all_sentences = read_cabocha("neko.txt.cabocha")
for sentence in all_sentences:
case_list = case_pattern(sentence, "動詞")
for case in case_list:
particles = " ".join([morph.surface for morph in case[2]])
chunk_surf = " ".join([chunk.get_surf() for chunk in case[3]])
print("{}{}\t{}\t{}".format(case[0].get_surf(), case[1].base, particles, chunk_surf))
"""
メモ
助詞の係り受けがない動詞句も出力している.
動詞句の係り元の文節に助詞が複数含まれていた場合、それをすべて抽出していたが、
問題文中の出力例をみると、最後の助詞だけでよいらしい.
入力:別段くるにも及ばんさと、主人は手紙に返事をする。
公式の出力例
返事をする と に は 及ばんさと 手紙に 主人は
本プログラムの出力
返事をする さ と は に 及ばんさと 主人は 手紙に
46行目を
- particles.extend(chunk.get_morphs("助詞"))
+ particles.append(chunk.get_morphs("助詞")[-1])
と修正すれば公式通りになる
"""
<file_sep># NLP100本ノック
#
# 06. 集合
# "paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,
# それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.
# さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ.
from nlp005 import ngram
text1 = "paraparaparadise"
text2 = "paragraph"
X = set(ngram(text1, 2, "char"))
Y = set(ngram(text2, 2, "char"))
print("Xの集合: {}".format(X))
print("Yの集合: {}".format(Y))
print("XとYの和集合: {}".format(X | Y))
print("XとYの積集合: {}".format(X & Y))
print("XとYの差集合: {}".format(X - Y))
print("'se' in X: {}".format(('s', 'e') in X))
print("'se' in Y: {}".format(('s', 'e') in Y))
<file_sep># NLP100本ノック
#
# 42. 係り元と係り先の文節の表示
# 係り元の文節と係り先の文節のテキストをタブ区切り形式ですべて抽出せよ.
# ただし,句読点などの記号は出力しないようにせよ.
# set_chunk_depをテキスト返すのではなく、
# Chunkオブジェクトとして返すように修正した
# 係り先のない文節は出力しないよう修正
from nlp041 import read_cabocha
def set_chunk_dep(chunk_list):
"""
1文のchunkリストから(係り元の文節のChunk, 係り先の文節のChunk)という
タプルのリストとして返す関数
"""
chunk_dep_list = []
for chunk in chunk_list:
src_surf = chunk.get_surf()
if src_surf == "":
continue
elif chunk.dst == -1:
continue
else:
dst_chunk = chunk_list[chunk.dst]
chunk_dep_list.append((chunk, dst_chunk))
return chunk_dep_list
if __name__ == '__main__':
all_sentences = read_cabocha("neko.txt.cabocha")
for sentence in all_sentences:
chunk_dep_list = set_chunk_dep(sentence)
for chunk_dep in chunk_dep_list:
print("{}\t{}".format(chunk_dep[0].get_surf()
, chunk_dep[1].get_surf()))
print("\n")
<file_sep># NLP100本ノック
#
# 61. KVSの検索
# 60で構築したデータベースを用い,特定の(指定された)アーティストの活動場所を取得せよ
# 名前から検索できるよう修正
import redis
def get_area(r, name):
area = r.hgetall(name) if r.hgetall(name) else None
return area
if __name__ == '__main__':
r = redis.StrictRedis(host="localhost", port=6379, db=1) # 修正版のdbは1番
print("artist name:", end="")
name = input()
area = get_area(r, name)
if area:
for key, item in area.items():
print("id:{}, area:{}".format(key.decode(), item.decode()))
else:
print("該当なし")
<file_sep># NLP100本ノック
#
# 23. セクション構造
# 記事中に含まれるセクション名とそのレベル(例えば"== セクション名 =="なら1)を表示せよ.
import re
pattern = re.compile(r"(={2,})([^=]+)(={2,})")
with open("jawiki-britain.txt", "r", encoding="utf-8") as f:
for line in f:
match = re.search(pattern, line)
if match:
print(match.group())
print("セクション名:{}, レベル:{}".format(match.group(2), len(match.group(1))-1))
<file_sep># NLP100本ノック
#
# 63. オブジェクトを値に格納したKVS
# KVSを用い,アーティスト名(name)からタグと被タグ数(タグ付けされた回数)のリストを検索するためのデータベースを構築せよ.
# さらに,ここで構築したデータベースを用い,アーティスト名からタグと被タグ数を検索せよ.
import json
import redis
import sys
def set_db_tag(r, file_name):
with open(file_name, "r", encoding="utf-8") as f:
with r.pipeline() as pipe:
pipe.multi()
for line in f:
data = json.loads(line)
# hash型:keyをname, valueはid:area
if "tags" in data.keys():
value = {data["id"]:str(data.get("tags")).encode("utf-8")}
pipe.hmset(data["name"].encode("utf-8"), value)
pipe.execute()
def get_tags(r, name):
area = r.hgetall(name) if r.hgetall(name) else None
return area
if __name__ == '__main__':
args = sys.argv
r = redis.StrictRedis(host="localhost", port=6379, db=2)
if "d" in args:
file_name = "artist.json"
set_db_tag(r, file_name)
print("artist name:", end="")
name = input()
area = get_tags(r, name)
if area:
for key, item in area.items():
print("id:{}, tags:{}".format(key.decode(), item.decode()))
else:
print("該当なし")
"""
メモ
問題の要件がいまいち曖昧でつかみにくい
実行するときコマンドライン引数でdを指定するとデータベースに書き込む
検索のみの場合はオプションなし
"""
<file_sep># NLP100本ノック
#
# 16. ファイルをN分割する
# 自然数Nをコマンドライン引数などの手段で受け取り,
# 入力のファイルを行単位でN分割せよ.同様の処理をsplitコマンドで実現せよ.
print("何分割:")
N = int(input())
with open("hightemp.txt", "r", encoding="utf-8") as f
lines = f.readlines()
n = len(lines) // N
a = len(lines) % N
# 割り切れないときどうするか指定がないので適当
if n < 1:
print("無理")
else:
for i in range(N):
if i < N-1:
new_lines = lines[i*n:i*n+n]
elif i == N-1:
new_lines = lines[i*n:i*n+n+a]
print("".join(new_lines))
print("-----------------------------------------")<file_sep># NLP100本ノック
#
# 60. KVSの構築
# Key-Value-Store (KVS) を用い,アーティスト名(name)から活動場所(area)を検索するためのデータベースを構築せよ.
# 要件を満たすよう修正
import json
import redis
def set_db(r, file_name):
with open(file_name, "r", encoding="utf-8") as f:
with r.pipeline() as pipe:
pipe.multi()
for line in f:
data = json.loads(line)
# hash型:keyをname, valueはid:area
value = {data["id"]:data.get("area", "unknown").encode("utf-8")}
pipe.hmset(data["name"].encode("utf-8"), value)
pipe.execute()
if __name__ == '__main__':
file_name = "artist.json"
r = redis.StrictRedis(host="localhost", port=6379, db=1)
set_db(r, file_name)
"""
nameが重複するので,
nameをkey, idをhash値, areaをvalueとして記録
例えば宇宙人というnameは2人いるので,
宇宙人{1009652:Japan, 662905:Taiwan}
といったデータ構造になる
"""<file_sep># NLP100本ノック
#
# 18. 各行を3コラム目の数値の降順にソート
# 各行を3コラム目の数値の逆順で整列せよ(注意: 各行の内容は変更せずに並び替えよ).
# 確認にはsortコマンドを用いよ(この問題はコマンドで実行した時の結果と合わなくてもよい).
with open("hightemp.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
lines.sort(key = lambda line: line.split()[2])
print(''.join(lines))<file_sep># NLP100本ノック
#
# 27. 内部リンクの除去
# 26の処理に加えて,テンプレートの値からMediaWikiの内部リンクマークアップを除去し,
# テキストに変換せよ(参考: マークアップ早見表).
# 内部リンクとは[[]]で囲まれている部分らしい.
# とくに指定がないので, [[記事名|表示文字]]となっているものは表示文字を残すことにする
import re
from nlp025 import parse_info
from nlp026 import remove_emphasis
def remove_link(info_list):
pattern = re.compile(r"\[{2}(?:[^\|\[\]]+\|)?([^\]]+)\]{2}")
for info in info_list:
info[1] = re.sub(pattern, "\g<1>", info[1])
return info_list
if __name__ == '__main__':
with open("jawiki-britain.txt", "r", encoding="utf-8") as f:
text = f.read()
info_list = parse_info(text)
info_list = remove_emphasis(info_list)
info_list = remove_link(info_list)
for info in info_list:
print("{}: \n{}\n".format(info[0], info[1]))<file_sep>## 66. 検索件数の取得
MongoDBのインタラクティブシェルを用いて,
活動場所が「Japan」となっているアーティスト数を求めよ.
```
> db.test_coll.find({area: "Japan"}).count()
22821
```<file_sep># NLP100本ノック
#
# 52. ステミング
# 51の出力を入力として受け取り,Porterのステミングアルゴリズムを適用し,
# 単語と語幹をタブ区切り形式で出力せよ.
# Pythonでは,Porterのステミングアルゴリズムの実装としてstemmingモジュールを利用するとよい.
# NLTKのstemパッケージを使用
# http://www.nltk.org/api/nltk.stem.html
from nltk.stem.porter import PorterStemmer
ps = PorterStemmer()
with open("nlp051_result.txt", "r", encoding="utf-8") as f:
for line in f:
word = line.strip()
stem_word = ps.stem(word)
print("{}\t{}".format(word, stem_word))
<file_sep># NLP100本ノック
#
# ユーザから入力された検索条件に合致するアーティストの情報を表示するWebアプリケーションを作成せよ.
# アーティスト名,アーティストの別名,タグ等で検索条件を指定し,
# アーティスト情報のリストをレーティングの高い順などで整列して表示せよ.
from flask import Flask, render_template, request, redirect, url_for
from artists_db import ArtistsDataBase
# 接続するmongodbのdb名とcollectionm名を設定
DATABASE = "test_db"
COLLECTION = "test_coll"
app = Flask(__name__)
art_db = ArtistsDataBase(db=DATABASE, collection=COLLECTION)
@app.route("/")
def hello():
return render_template("index.html")
@app.route("/send", methods=["GET"])
def search_db():
elem_dic = {}
for elem in ["name", "aliase", "area", "tag"]:
elem_dic[elem] = request.args.get(elem, default="")
results = art_db.search_artists(art_db.generate_query(elem_dic))
fields = ["name", "aliases", "area", "tags", "rating"]
return render_template("result.html", results=results, fields=fields)
if __name__ == "__main__":
app.debug = True
app.run()<file_sep># NLP100本ノック
#
# 02. 「パトカー」+「タクシー」=「パタトクカシーー」
# 「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.
# 普通にfor分で連結
s1 = "パトカー"
s2 = "タクシー"
s = ""
for i, j in zip(s1, s2):
s = s + i + j
print(s)
# 処理速度的にはリスト作成からjoinメソッドで連結という方法が早いらしい
s = ""
s = "".join([i + j for i, j in zip(s1, s2)])
print(s)<file_sep># NLP100本ノック
#
# 38. ヒストグラム
# 単語の出現頻度のヒストグラム
# (横軸に出現頻度,縦軸に出現頻度をとる単語の種類数を棒グラフで表したもの)
# を描け.
import matplotlib.pyplot as plt
from nlp030 import read_mecab
from nlp036 import word_freq
# 日本語フォント読み込み
from matplotlib.font_manager import FontProperties
fp = FontProperties(fname=r'/usr/local/share/fonts/TakaoPGothic.ttf', size=10)
# nlp036の関数から頻度取得
file_name = "neko.txt.mecab"
all_sentences = read_mecab(file_name)
freq_list_desc = word_freq(all_sentences)
# グラフ描写
# すべてのデータだと値の範囲が広すぎてうまく表示されない
# data = [i[1] for i in freq_list_desc]
# 頻度上位200~1000を表示するとそれなりに見えるグラフになる
data = [i[1] for i in freq_list_desc[200:1001]]
plt.hist(data, bins=30)
plt.title("出現頻度ヒストグラム", fontproperties=fp)
plt.xlabel("出現頻度",fontproperties=fp)
plt.ylabel("単語の種類数",fontproperties=fp)
plt.show()
<file_sep># NLP100本ノック
#
# 17. 1列目の文字列の異なり
# 1列目の文字列の種類(異なる文字列の集合)を求めよ.確認にはsort, uniqコマンドを用いよ.
word_set = set()
with open("hightemp.txt", "r", encoding="utf-8") as f:
for line in f:
word_set.add(line.split()[0])
print(word_set)<file_sep># nock069
## Flask
* Webアプリケーションのフレームワークとして[Flask](http://flask.pocoo.org/)を使っています.
```
$ pip install Flask
```
## Run
* mongodbサーバの起動
```
$ sudo mongod
```
* webサーバの起動
```
$ python app.py
```
* urlにアクセス
[http://127.0.0.1:5000/](http://127.0.0.1:5000/)
<file_sep># NLP100本ノック
#
# 21. カテゴリ名を含む行を抽出
# 記事中でカテゴリ名を宣言している行を抽出せよ.
with open("jawiki-britain.txt", "r", encoding="utf-8") as f:
for line in f:
if "Category:" in line:
print(line)
<file_sep># NLP100本ノック
#
# 41. 係り受け解析結果の読み込み(文節・係り受け)
# 40に加えて,文節を表すクラスChunkを実装せよ.
# このクラスは形態素(Morphオブジェクト)のリスト(morphs),
# 係り先文節インデックス番号(dst),
# 係り元文節インデックス番号のリスト(srcs)
# をメンバ変数に持つこととする.
# さらに,入力テキストのCaboChaの解析結果を読み込み,
# 1文をChunkオブジェクトのリストとして表現し,8文目の文節の文字列と係り先を表示せよ.
# 第5章の残りの問題では,ここで作ったプログラムを活用せよ.
import re
class Morph(object):
"""
表層形(surface), 基本形(base),品詞(pos),品詞細分類1(pos1)
をアトリビュートに持つだけのクラス
atr:
self.surface: str, 表層形
self.base: str, 基本形
self.pos: str, 品詞
self.pos1: str, 品詞細分類1
"""
def __init__(self, surface, base, pos, pos1):
self.surface = surface
self.base = base
self.pos = pos
self.pos1 = pos1
def __str__(self):
return "surface: {}, base:{}, pos:{}, pos1:{}".format(self.surface,
self.base, self.pos, self.pos1)
class Chunk(object):
"""
文節の
形態素(Morphオブジェクト)のリスト(morphs), 係り先文節インデックス番号(dst),
係り元文節インデックス番号のリスト(srcs)をアトリビュートとして持つクラス
atr:
self.morphs: list, Morphモブジェクトのリスト
self.num: int, 要件にないけど追加, 自身の文節番号
self.dst: int, 掛かり先のインデックス番号
self.srcs: list, 掛かり元のインデックス番号(int)のリスト
"""
def __init__(self, morphs, num, dst, srcs):
self.morphs = morphs
self.num = num
self.dst = dst
self.srcs = srcs
def __str__(self):
surface = " ".join([morph.surface for morph in self.morphs])
return "{}, num:{}, dst:{}, srcs:{}".format(surface,
self.num, self.dst, self.srcs)
def get_surf(self, rm_symbol=True):
if rm_symbol:
return "".join([morph.surface for morph in self.morphs if morph.pos != "記号"])
return "".join([morph.surface for morph in self.morphs])
def get_pos_list(self):
return [morph.pos for morph in self.morphs]
def get_morphs(self, pos="all"):
if pos == "all":
return [morph for morph in self.morphs]
else:
return [morph for morph in self.morphs if morph.pos == pos]
def mecab_to_morph(mecab_text):
"""
MeCabの解析結果(MeCabの出力形式)1行から、
Morphオブジェクトを生成する
args:
file_name: str, MeCabの解析結果の1行分
return:
morph: Morph
"""
mecab_text = mecab_text.replace("\n", "")
tab_split = mecab_text.split("\t")
elem_list = tab_split[1].split(",")
morph = Morph(tab_split[0], elem_list[6], elem_list[0], elem_list[1])
return morph
def read_cabocha(file_name):
"""
複数行のCaboChaの解析結果から、1行ごとに切り出して処理を行い、
各行をChunkオブジェクトのリストとする関数
args:
file_neme: str, MeCabの解析結果のファイル名
return:
all_sentences: list, 各行のchunkリストを格納したリスト
"""
all_sentences = []
with open(file_name, "r", encoding="utf-8") as f:
text_list = f.read().split("EOS\n")
for text in text_list:
if text != "":
all_sentences.append(parse_chunk(text + "EOS"))
return all_sentences
def parse_chunk(cabocha_text):
"""
1行分のCaboChaの解析結果から、各分節のChunkオブジェクトを生成し、
1行をChunkオブジェクトのリストとして返す関数
args:
cabocha_text: str, 1行分のCaboChaの解析結果
return:
chunk_list: list, Chunkオブジェクトのリスト
"""
lines = cabocha_text.split('\n')
pattern = re.compile(r"^\*\s([0-9]+)\s([^D]+)D")
morph_list = []
chunk_list = []
srcs_list = [[] for i in range(len(lines))] # 掛かり元を記録しておくためのリスト
for line in lines:
if re.search(r"^\*\s[0-9]+", line):
if morph_list:
chunk_list.append(Chunk(morph_list, num, dst, srcs))
morph_list = []
match = re.search(pattern, line)
num = int(match.group(1))
dst = int(match.group(2))
srcs_list[dst].append(num)
srcs = srcs_list[num]
elif line == "EOS":
if morph_list:
chunk_list.append(Chunk(morph_list, num, dst, srcs))
break
else:
morph_list.append(mecab_to_morph(line))
return chunk_list
if __name__ == '__main__':
all_sentences = read_cabocha("neko.txt.cabocha")
for cnt, chunk in enumerate(all_sentences[7]):
print("chunk{}:{}".format(cnt, chunk))
# for sentence in all_sentences:
# for cnt, chunk in enumerate(sentence):
# print("chunk{}:{}".format(cnt, chunk))
# print("\n")
"""
メモ
後々使いやすくなるかなと思い
全文をループする関数と1文をパーズする関数を分けた
parse_chunk()について
掛かり元のリストsrcsの扱いに少し迷った
先人のコードを見ると、各分節のChunkオブジェクトを一通り生成した後、
EOSが来たときに、係り受け関係をsrcsアトリビュートに追加していた.
045のために修正.Chunkのアトリビュートにnumを追加
"""
<file_sep># NLP100本ノック
#
# 60. KVSの構築
# Key-Value-Store (KVS) を用い,アーティスト名(name)から活動場所(area)を検索するためのデータベースを構築せよ.
import json
import redis
def set_db(r, file_name):
with open(file_name, "r", encoding="utf-8") as f:
with r.pipeline() as pipe:
pipe.multi()
for line in f:
data = json.loads(line)
value = {"name":data["name"].encode("utf-8"), "area":data.get("area", "unknown").encode("utf-8")}
pipe.hmset(data["id"], value)
pipe.execute()
if __name__ == '__main__':
file_name = "artist.json"
r = redis.StrictRedis(host="localhost", port=6379, db=0)
set_db(r, file_name)
"""
メモ
データベースはあんまり触れてこなかったのでよく分かってないかもしれません.
redisはpipeline処理というのでトランザクションっぽいことが可能らしい
とりあえず, 排他とか整合性は考えずに, multiとexecでまとめて処理
multi()とexecute()の間にエラーが発生したら何も実行しないようにした...つもりだけど本当になってる?
RDB, NoSQL
追記
よく問題文を見ると,
nameからareaを検索できるようなDB設計じゃないといけないらしいです
修正版 -> nlp060_2.py
"""
<file_sep># NLP100本ノック
#
# 59. S式の解析
# Stanford Core NLPの句構造解析の結果(S式)を読み込み,文中のすべての名詞句(NP)を表示せよ.
# 入れ子になっている名詞句もすべて表示すること.
import xml.etree.ElementTree as ET
import re
def parse_exp(text, exp_list):
"""
S式をパーザする関数. 与えられたテキスト中のすべてのS式をリストとして返す.
一対の()で閉じている式を{}に置換し、置換後のテキストを入力として再帰的に処理.
式として確定した部分は()が{}になった状態でリストに格納される
args:
text: str, S式のテキスト
exp_list, list, {}に置換したS式のリスト
return:
exp_list, list, {}に置換したS式のリスト
"""
pattern = re.compile(r"\(([^()]+)\)")
if re.search(pattern, text):
exp_list.extend(["{"+s+"}" for s in re.findall(pattern, text)])
rep_text = re.sub(pattern, "{\g<1>}", text)
exp_list = parse_exp(rep_text, exp_list)
return exp_list
def extract_np(elem):
"""
Stanford Core NLPの解析結果xmlのS式から名詞句(NP)を出力する関数
args:
elem: ETオブジェクト, Stanford Core NLPの解析結果xmlのETパーザオブジェクト
"""
pattern_w = re.compile(r"{[A-Z]+ ([^{}]+)}")
for sentence in elem.find(".//sentences"):
s_exp = sentence.find("parse").text
exp_list = parse_exp(s_exp, [])
print("--------sentence id :{}--------".format(sentence.get("id")))
for exp in exp_list:
if exp[0:3] == "{NP":
# print(exp)
print(" ".join(re.findall(pattern_w, exp)))
if __name__ == '__main__':
tree = ET.parse("nlp.txt.xml")
elem = tree.getroot()
extract_np(elem)
"""
めも
parse_exp()は簡潔さを優先で記述
再帰処理+置換で処理速度はいまいちかもしれない
"""
<file_sep># NLP100本ノック
#
# 51. 単語の切り出し
# 空白を単語の区切りとみなし,50の出力を入力として受け取り,1行1単語の形式で出力せよ.
# ただし,文の終端では空行を出力せよ.
import re
import sys
def split_space(text):
word_list = text.split()
for word in word_list:
print(word)
#nlp050
pattern = re.compile(r"([\.;:?!])\s([A-Z])")
with open("nlp.txt", "r", encoding="utf-8") as f:
for line in f:
if line != "\n":
sentences = re.sub(pattern, r"\1\n\2", line)
split_space(sentences)
<file_sep># NLP100本ノック
#
# 55. 固有表現抽出
# 入力文中の人名をすべて抜き出せ.
import re
pattern_token = re.compile(r"<token(.+?)</token>", re.DOTALL)
pattern_word = re.compile(r"<word>(.+?)</word>")
pattern_ner = re.compile(r"<NER>(.+?)</NER>")
with open("nlp.txt.xml", "r", encoding="utf-8") as f:
text = f.read()
tokens = re.findall(pattern_token, text)
for token in tokens:
ner = re.search(pattern_ner, token).group(1)
if ner == "PERSON":
print(re.search(pattern_word, token).group(1))
<file_sep># NLP100本ノック
#
# 11. タブをスペースに置換
# タブ1文字につきスペース1文字に置換せよ.
# 確認にはsedコマンド,trコマンド,もしくはexpandコマンドを用いよ.
with open("hightemp.txt", "r", encoding="utf-8") as f:
text = f.read().replace("\t", " ")
print(text)<file_sep># NLP100本ノック
#
# 65. MongoDBの検索
# MongoDBのインタラクティブシェルを用いて,"Queen"というアーティストに関する情報を取得せよ.
# さらに,これと同様の処理を行うプログラムを実装せよ
# Mongoシェル
# > db.test_coll.find({name: "Queen"})
from pymongo import MongoClient
if __name__ == '__main__':
client = MongoClient('localhost', 27017)
coll = client.test_db.test_coll
name = "Queen"
for artist in coll.find({"name": name}):
print(artist)
client.close()
<file_sep># NLP100本ノック
#
# 28. MediaWikiマークアップの除去
# 27の処理に加えて,テンプレートの値からMediaWikiマークアップを可能な限り除去し,
# 国の基本情報を整形せよ.
# <>で囲まれたタグと{{}}を消せばよい?
import re
from nlp025 import parse_info
from nlp026 import remove_emphasis
from nlp027 import remove_link
def remove_markup(info_list):
pattern = re.compile(r"<[^>]+>|\**\{{2}|\}{2}")
for info in info_list:
info[1] = re.sub(pattern, "", info[1])
return info_list
if __name__ == '__main__':
with open("jawiki-britain.txt", "r", encoding="utf-8") as f:
text = f.read()
info_list = parse_info(text)
info_list = remove_emphasis(info_list)
info_list = remove_link(info_list)
info_list = remove_markup(info_list)
for info in info_list:
print("{}: \n{}\n".format(info[0], info[1]))<file_sep># NLP100本ノック
#
# 62. KVS内の反復処理
# 60で構築したデータベースを用い,活動場所が「Japan」となっているアーティスト数を求めよ.
import redis
import time
def count_by_area(r, area):
cnt = 0
keys = r.keys()
for key in keys:
if r.hget(key, "area") == area:
cnt += 1
return cnt
if __name__ == '__main__':
start = time.time()
r = redis.StrictRedis(host="localhost", port=6379, db=0)
area = b"Japan"
cnt = count_by_area(r, area)
print(cnt)
elapsed_time = time.time() - start
print("elapsed_time:{} [sec]".format(elapsed_time))
# elapsed_time:29.450867891311646 [sec]
"""
メモ
29.450867891311646 [sec]
全データを走査するので, けっこう時間が掛かります.
何か良い方法があるんでしょうか...
redisのdocumentationには
>>キー・バリュー・ストアの本質は、キーに対して、値と呼ばれるどんなデータでも格納できるという点にあります。
>>このデータは、保存時に使用した正確なキーを知っている場合にのみ、後からアクセスができます。値の側から検索する方法はありません。
http://redis.shibu.jp/tutorial/
修正版 -> nlp062_2.py
"""<file_sep># NLP100本ノック
#
# 13. col1.txtとcol2.txtをマージ
# 12で作ったcol1.txtとcol2.txtを結合し,
# 元のファイルの1列目と2列目をタブ区切りで並べたテキストファイルを作成せよ.
# 確認にはpasteコマンドを用いよ.
f_col1 = open("col1.txt", "r", encoding="utf-8")
f_col2 = open("col2.txt", "r", encoding="utf-8")
f_col3 = open("col3.txt", "w", encoding="utf-8")
with f_col1, f_col2, f_col3:
for line1, line2 in zip(f_col1, f_col2):
line1 = line1.replace("\n", "")
f_col3.write(line1 + "\t" + line2)
<file_sep># NLP100本ノック
#
# 61. KVSの検索
# 60で構築したデータベースを用い,特定の(指定された)アーティストの活動場所を取得せよ
import redis
def get_area(r, art_id):
area = r.hget(art_id, "area").decode("utf-8") if r.hget(art_id, "area") else "該当なし"
return area
if __name__ == '__main__':
r = redis.StrictRedis(host="localhost", port=6379, db=0)
print("artist id:", end="")
art_id = input()
area = get_area(r, art_id)
print(area)
"""
修正版 -> nlp061_2.py
"""
<file_sep># NLP100本ノック
#
# 05. n-gram
# 与えられたシーケンス(文字列やリストなど)からn-gramを作る関数を作成せよ.
# この関数を用い,"I am an NLPer"という文から単語bi-gram,文字bi-gramを得よ.
# 文字ngram
def char_ngram(text, n):
ngram_dic = {}
text = text.replace(" ", "")
for i in range(len(text)-n+1):
ngram_dic[text[i:i+n]] = ngram_dic.get(text[i:i+n], 0) + 1
# dict.get()メソッドはkeyを渡して、その対応する要素を取り出す.
# 第2引数を指定するとkeyが存在していなかったときに返すデフォルト値を設定できる
return ngram_dic
# 単語ngram
def word_ngram(text, n):
ngram_dic = {}
word_list = text.split()
word_tuple = tuple(word_list)
for i in range(len(word_list)-n+1):
ngram_dic[word_tuple[i:i+n]] = ngram_dic.get(word_tuple[i:i+n], 0) + 1
return ngram_dic
# 以上は頻度を求める関数だけど、
# 巷の回答を見ると、頻度は不要で、共起関係のリストを出力すればよいらしい
# 関数も一つにまとめた単語&文字ngram
def ngram(text, n, mode="char"):
ngram_list = []
if mode == "char":
text = text.replace(" ", "")
unit_list = text
elif mode == "word":
unit_list = tuple(text.split())
for i in range(len(unit_list)-n+1):
ngram_list.append(unit_list[i:i+n])
# 文字ngramは文字列のリスト, 単語ngramはタプルのリストで返す.
return ngram_list
if __name__ == '__main__':
print("string:")
text = input()
print("n:")
n = int(input())
print(char_ngram(text, n))
print(word_ngram(text, n))
print(ngram(text, n))
print(ngram(text, n, "word"))<file_sep># NLP100本ノック
# #
# 26. 強調マークアップの除去
# 25の処理時に,テンプレートの値からMediaWikiの
# 強調マークアップ(弱い強調,強調,強い強調のすべて)
# を除去してテキストに変換せよ(参考: マークアップ早見表).
# おそらく2,3,5連シングルクォーテーションを除去しろということ?
import re
from nlp025 import parse_info
def remove_emphasis(info_list):
for info in info_list:
info[1] = re.sub(r"'{2,5}", "", info[1])
return info_list
if __name__ == '__main__':
with open("jawiki-britain.txt", "r", encoding="utf-8") as f:
text = f.read()
info_list = parse_info(text)
info_list = remove_emphasis(info_list)
for info in info_list:
print("{}: \n{}\n".format(info[0], info[1]))
<file_sep># NLP100本ノック
#
# 03. 円周率
# "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
# という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.
# ,と.の除去
s = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
s = s.replace(",", "").replace(".", "")
# 正規表現なら
# import re
# s = re.sub("[,.]", "", s)
word_list = s.split(" ")
l = []
for i in word_list:
l.append(len(i))
print(l)<file_sep># NLP100本ノック
#
# 58. タプルの抽出
# Stanford Core NLPの係り受け解析の結果(collapsed-dependencies)に基づき,
# 「主語 述語 目的語」の組をタブ区切り形式で出力せよ.
# ただし,主語,述語,目的語の定義は以下を参考にせよ.
# 述語: nsubj関係とdobj関係の子(dependant)を持つ単語
# 主語: 述語からnsubj関係にある子(dependent)
# 目的語: 述語からdobj関係にある子(dependent)
import xml.etree.ElementTree as ET
def extract_tuple(elem):
"""
Stanford Core NLPの解析結果xmlから主語述語目的語の係り受け関係を出力する関数
args:
elem: ETオブジェクト, Stanford Core NLPの解析結果xmlのETパーザオブジェクト
"""
print("{:4}\t{:15}\t{:15}\t{:15}".format("s_id", "nsubj", "sub", "dobj"))
for sentence in elem.find(".//sentences"):
coll_dep = sentence.find("dependencies[@type='collapsed-dependencies']")
dep_list = coll_dep.findall("dep")
dep_dic = {}
for dep in dep_list:
gov_idx = dep.find("governor").get("idx")
gov_text = dep.find("governor").text
dep_idx = dep.find("dependent").get("idx")
dep_text = dep.find("dependent").text
dep_type = dep.get("type")
if dep_type == "nsubj" or dep_type == "dobj":
dep_dic.setdefault((gov_idx, gov_text), {}).update({dep_type:dep_text})
for key, value in dep_dic.items():
if "nsubj" in value.keys() and "dobj" in value.keys():
print("{:4}\t{:15}\t{:15}\t{:15}".format(sentence.get("id"),
value["nsubj"], key[1], value["dobj"]))
if __name__ == '__main__':
tree = ET.parse("nlp.txt.xml")
elem = tree.getroot()
extract_tuple(elem)
<file_sep># NLP100本ノック
#
# 42. 係り元と係り先の文節の表示
# 係り元の文節と係り先の文節のテキストをタブ区切り形式ですべて抽出せよ.
# ただし,句読点などの記号は出力しないようにせよ.
# set_chunk_depをテキスト返すのではなく、Chunkオブジェクトとして返すように
# 修正したものを作成した(nlp42_2.py)
from nlp041 import read_cabocha
def set_chunk_dep(chunk_list):
"""
1文のchunkリストから(係り元の文節のテキスト, 係り先の文節のテキスト)という
タプルのリストとして返す関数
"""
chunk_dep_list = []
for chunk in chunk_list:
src_surf = chunk.get_surf()
if src_surf == "":
continue
elif chunk.dst == -1:
dst_surf = ""
else:
dst_surf = chunk_list[chunk.dst].get_surf()
chunk_dep_list.append((src_surf, dst_surf))
return chunk_dep_list
if __name__ == '__main__':
all_sentences = read_cabocha("neko.txt.cabocha")
for sentence in all_sentences:
chunk_dep_list = set_chunk_dep(sentence)
for chunk_dep in chunk_dep_list:
print("{}\t{}".format(chunk_dep[0], chunk_dep[1]))
print("\n")
<file_sep># NLP100本ノック
#
# 50. 文区切り
# (. or ; or : or ? or !) → 空白文字 → 英大文字というパターンを文の区切りと見なし,
# 入力された文書を1行1文の形式で出力せよ.
# 改行も文の区切りとみなす
import re
import sys
pattern = re.compile(r"([\.;:?!])\s([A-Z])")
with open("nlp.txt", "r", encoding="utf-8") as f:
for line in f:
if line != "\n":
sentences = re.sub(pattern, r"\1\n\2", line)
# print(sentences),
sys.stdout.write(sentences)<file_sep># NLP100本ノック
#
# 35. 名詞の連接
# 名詞の連接(連続して出現する名詞)を最長一致で抽出せよ.
from nlp030 import read_mecab
file_name = "neko.txt.mecab"
all_sentences = read_mecab(file_name)
for sentence in all_sentences:
noun_list = []
for cnt, morph in enumerate(sentence):
if morph["pos"] == "名詞":
noun_list.append(morph["surface"])
if cnt == len(sentence)-1 and len(noun_list) > 1:
print("".join(noun_list))
noun_list = []
elif len(noun_list) > 1:
print("".join(noun_list))
noun_list = []
else:
noun_list = []
<file_sep># NLP100本ノック
#
# 68. ソート
# "dance"というタグを付与されたアーティストの中で
# レーティングの投票数が多いアーティスト・トップ10を求めよ.
# Mongoシェル
# db.test_coll.find({tags: {$elemMatch: {value: "dance"}}}, {name: true, tags: true, rating:true}).sort({"rating.count": -1}).limit(10)
import pymongo
from pymongo import MongoClient
if __name__ == '__main__':
client = MongoClient('localhost', 27017)
coll = client.test_db.test_coll
data = coll.find({"tags":{"$elemMatch": {"value": "dance"}}})
data = data.sort("rating.count", pymongo.DESCENDING)[0:10]
for art in data:
print(art["name"], art["rating"]["count"])
client.close()
<file_sep># NLP100本ノック
#
# 44. 係り受け木の可視化
# 与えられた文の係り受け木を有向グラフとして可視化せよ.
# 可視化には,係り受け木をDOT言語に変換し,Graphvizを用いるとよい.
# また,Pythonから有向グラフを直接的に可視化するには,pydotを使うとよい
# pythonからGraphvizを利用するパッケージはいくつかあるみたい.
# 問題文中で言っているpydotよりもgraphvizの方が公式ドキュメントがしっかりしてたので,
# こちらを使うことにする.
# Graphvizをpythonから利用するパッケージgraphviz ややこしい.
# http://graphviz.readthedocs.io/en/latest/index.html
# $ sudo apt-get install graphviz
# $ pip install graphviz
from graphviz import Digraph
from nlp041 import read_cabocha
from nlp042_2 import set_chunk_dep
def dep_to_graph(chunk_dep_list):
"""
chunkの係り関係のタプルからグラフを作成する関数
"""
g = Digraph(format="png")
# 日本語表示のためのフォントを設定
g.attr("node", fontname="TakaoPGothic")
for chunk_dep in chunk_dep_list:
g.edge(chunk_dep[0].get_surf(),
chunk_dep[1].get_surf())
print(g)
g.render("nlp044")
if __name__ == '__main__':
all_sentences = read_cabocha("neko.txt.cabocha")
chunk_dep_list = set_chunk_dep(all_sentences[6])
dep_to_graph(chunk_dep_list)
<file_sep># NLP100本ノック
#
# 67. 複数のドキュメントの取得
# 特定の(指定した)別名を持つアーティストを検索せよ.
# Mongoシェル
# > db.test_coll.find({aliases: {$exists: true}}).count()
# 82644
from pymongo import MongoClient
if __name__ == '__main__':
client = MongoClient('localhost', 27017)
coll = client.test_db.test_coll
print(coll.find({"aliases": {"$exists": True}}).count())
client.close()<file_sep># NLP100本ノック
#
# 46. 動詞の格フレーム情報の抽出
# 45のプログラムを改変し,述語と格パターンに続けて項(述語に係っている文節そのもの)をタブ区切り形式で出力せよ.45の仕様に加えて,以下の仕様を満たすようにせよ.
# 項は述語に係っている文節の単語列とする(末尾の助詞を取り除く必要はない)
# 述語に係る文節が複数あるときは,助詞と同一の基準・順序でスペース区切りで並べる
# 「吾輩はここで始めて人間というものを見た」という例文(neko.txt.cabochaの8文目)を考える.
# この文は「始める」と「見る」の2つの動詞を含み,「始める」に係る文節は「ここで」,
# 「見る」に係る文節は「吾輩は」と「ものを」と解析された場合は,次のような出力になるはずである.
# 始める で ここで
# 見る は を 吾輩は ものを
from nlp041 import read_cabocha
def case_pattern(chunk_list, dst_pos):
"""
指定した品詞に掛かる格(助詞)を調べる関数
args:
dst_pos: str, 品詞
return:
[((動詞のMorph, (助詞のMorph, ...), (助詞を含むChunk, ...)), ...]
"""
case_list = []
chunk_dep_list = set_src_chunk(chunk_list)
for chunk_dep in chunk_dep_list:
if dst_pos in chunk_dep[0].get_pos_list():
particles = []
chunks_contain_part = []
verbs = chunk_dep[0].get_morphs(dst_pos)
for chunk in chunk_dep[1]:
if chunk.get_morphs("助詞"):
particles.extend(chunk.get_morphs("助詞"))
chunks_contain_part.append(chunk)
case_list.append((verbs[0], tuple(particles), tuple(chunks_contain_part)))
return case_list
def set_src_chunk(chunk_list):
"""
(chunk, chunkに係るchunkのタプル)のリストを返す関数
"""
chunk_dep_list = []
for chunk in chunk_list:
src_chunk_list = tuple([chunk_list[i] for i in chunk.srcs])
chunk_dep_list.append((chunk, src_chunk_list))
return chunk_dep_list
if __name__ == '__main__':
all_sentences = read_cabocha("neko.txt.cabocha")
for sentence in all_sentences:
case_list = case_pattern(sentence, "動詞")
for case in case_list:
particles = " ".join([morph.surface for morph in case[1]])
chunk_surf = " ".join([chunk.get_surf() for chunk in case[2]])
print("{}\t{}\t{}".format(case[0].base, particles, chunk_surf))
<file_sep># NLP100本ノック
#
# 45. 動詞の格パターンの抽出
# 今回用いている文章をコーパスと見なし,日本語の述語が取りうる格を調査したい.
# 動詞を述語,動詞に係っている文節の助詞を格と考え,述語と格をタブ区切り形式で出力せよ.
# ただし,出力は以下の仕様を満たすようにせよ.
# ・動詞を含む文節において,最左の動詞の基本形を述語とする
# ・述語に係る助詞を格とする
# ・述語に係る助詞(文節)が複数あるときは,すべての助詞をスペース区切りで辞書順に並べる
# 「吾輩はここで始めて人間というものを見た」という例文(neko.txt.cabochaの8文目)を考える.
# この文は「始める」と「見る」の2つの動詞を含み,「始める」に係る文節は「ここで」,
# 「見る」に係る文節は「吾輩は」と「ものを」と解析された場合は,次のような出力になるはずである.
# 始める で
# 見る は を
# このプログラムの出力をファイルに保存し,以下の事項をUNIXコマンドを用いて確認せよ.
# コーパス中で頻出する述語と格パターンの組み合わせ
# 「する」「見る」「与える」という動詞の格パターン(コーパス中で出現頻度の高い順に並べよ
from nlp041 import read_cabocha
def case_pattern(chunk_list, dst_pos):
"""
指定した品詞に掛かる格(助詞)を調べる関数
args:
dst_pos: str, 品詞
return:
[(動詞のMorph, (助詞のMorph, 助詞のMorph, ...)), ...]
"""
case_list = []
chunk_dep_list = set_src_chunk(chunk_list)
for chunk_dep in chunk_dep_list:
if dst_pos in chunk_dep[0].get_pos_list():
particles = []
verbs = chunk_dep[0].get_morphs(dst_pos)
for chunk in chunk_dep[1]:
particles.extend(chunk.get_morphs("助詞"))
case_list.append((verbs[0], tuple(particles)))
return case_list
def set_src_chunk(chunk_list):
"""
(chunk, chunkに係るchunkのタプル)のリストを返す関数
"""
chunk_dep_list = []
for chunk in chunk_list:
src_chunk_list = tuple([chunk_list[i] for i in chunk.srcs])
chunk_dep_list.append((chunk, src_chunk_list))
return chunk_dep_list
if __name__ == '__main__':
all_sentences = read_cabocha("neko.txt.cabocha")
for sentence in all_sentences:
case_list = case_pattern(sentence, "動詞")
for case in case_list:
particles = " ".join([morph.surface for morph in case[1]])
print("{}\t{}".format(case[0].base, particles))
"""
メモ
for文でlistにappend()するか内包表記にするかいつも迷う.
可読性を取るならfor文?速度を取るなら内包表記?
"""
<file_sep># NLP100本ノック
#
# 12. 1列目をcol1.txtに,2列目をcol2.txtに保存
# 各行の1列目だけを抜き出したものをcol1.txtに,
# 2列目だけを抜き出したものをcol2.txtとしてファイルに保存せよ.
# 確認にはcutコマンドを用いよ.
f = open("hightemp.txt", "r", encoding="utf-8")
f_col1 = open("col1.txt", "w", encoding="utf-8")
f_col2 = open("col2.txt", "w", encoding="utf-8")
with f, f_col1, f_col2:
for line in f:
f_col1.write(line.split()[0] + "\n")
f_col2.write(line.split()[1] + "\n")
<file_sep># NLP100本ノック
#
# 19. 各行の1コラム目の文字列の出現頻度を求め,出現頻度の高い順に並べる
# 各行の1列目の文字列の出現頻度を求め,その高い順に並べて表示せよ.
# 確認にはcut, uniq, sortコマンドを用いよ.
word_list=[]
with open("hightemp.txt", "r", encoding="utf-8") as f:
for line in f:
word_list.append(line.split()[0])
freq_dic = {}
for word in word_list:
freq_dic[word] = freq_dic.get(word, 0) + 1
freq_list = list(freq_dic.items())
freq_list.sort(key=lambda i: i[1], reverse=True)
print(freq_list)
<file_sep># NLP100本ノック
#
# 36. 単語の出現頻度
# 文章中に出現する単語とその出現頻度を求め,出現頻度の高い順に並べよ.
from nlp030 import read_mecab
file_name = "neko.txt.mecab"
all_sentences = read_mecab(file_name)
def word_freq(all_sentences):
"""
read_mecab()の出力から、単語の頻度を求める
辞書に記録してから, 頻度の降順にタプルのリストに変換して返す.
args:
all_sentences: list, read_mecab()で出力される形式のリスト
return:
freq_list_desc: list, タプル(単語, 頻度)のリスト(頻度の降順)
"""
freq_dic = {}
for sentence in all_sentences:
for morph in sentence:
freq_dic[morph["surface"]] = freq_dic.get(morph["surface"], 0) + 1
freq_list_desc = sorted(freq_dic.items(), key=lambda x :x[1], reverse=True)
# return freq_dic
return freq_list_desc
if __name__ == '__main__':
file_name = "neko.txt.mecab"
all_sentences = read_mecab(file_name)
freq_list_desc = word_freq(all_sentences)
for i in freq_list_desc:
print("{}:{}".format(i[0], i[1]))
<file_sep># NLP100本ノック
#
# 37. 頻度上位10語
# 出現頻度が高い10語とその出現頻度をグラフ(例えば棒グラフなど)で表示せよ.
import matplotlib.pyplot as plt
from nlp030 import read_mecab
from nlp036 import word_freq
# 日本語フォント読み込み
from matplotlib.font_manager import FontProperties
fp = FontProperties(fname=r'/usr/local/share/fonts/TakaoPGothic.ttf', size=10)
# nlp036の関数から頻度取得
file_name = "neko.txt.mecab"
all_sentences = read_mecab(file_name)
freq_list_desc = word_freq(all_sentences)
# グラフ描写
X = [i for i in range(1, 11)]
Y = [i[1] for i in freq_list_desc[:10]]
plt.bar(X,Y, align="center")
plt.xticks(X, [i[0] for i in freq_list_desc[:10]], fontproperties=fp)
plt.title("出現頻度上位10単語", fontproperties=fp)
plt.xlabel("単語",fontproperties=fp)
plt.ylabel("出現回数",fontproperties=fp)
plt.show()
<file_sep># NLP100本ノック
#
# 夏目漱石の小説『吾輩は猫である』の文章(neko.txt)を
# CaboChaを使って係り受け解析し,その結果をneko.txt.cabochaというファイルに保存せよ.
# このファイルを用いて,以下の問に対応するプログラムを実装せよ.
# $ cabocha -f1 neko.txt -o neko.txt.cabocha
# 40. 係り受け解析結果の読み込み(形態素)
# 形態素を表すクラスMorphを実装せよ.
# このクラスは表層形(surface), 基本形(base),品詞(pos),品詞細分類1(pos1)
# をメンバ変数に持つこととする. さらに, CaboChaの解析結果(neko.txt.cabocha)を読み込み,
# 各文をMorphオブジェクトのリストとして表現し, 3文目の形態素列を表示せよ.
import re
class Morph(object):
"""
表層形(surface), 基本形(base),品詞(pos),品詞細分類1(pos1)
をアトリビュートに持つだけのクラス
"""
def __init__(self, surface, base, pos, pos1):
self.surface = surface
self.base = base
self.pos = pos
self.pos1 = pos1
def __str__(self):
return "surface: {}, base:{}, pos:{}, pos1:{}".format(self.surface,
self.base, self.pos, self.pos1)
# CaboChaは各形態素の情報をMeCab形式で出力するので流用
def mecab_to_morph(mecab_text):
"""
MeCabの解析結果(MeCabの出力形式)1行から、
Morphオブジェクトを生成する
args:
file_name: str, MeCabの解析結果の1行分
return:
morph: Morph
"""
mecab_text = mecab_text.replace("\n", "")
tab_split = mecab_text.split("\t")
elem_list = tab_split[1].split(",")
morph = Morph(tab_split[0], elem_list[6], elem_list[0], elem_list[1])
return morph
def read_cabocha(file_name):
"""
CaboChaの解析結果から1行ごとに読み込んで、形態素の情報をmecab_to_morphに渡す.
返ってきたMorphオブジェクトは元のテキスト1行分(EOSが現れる)ごとにリストに格納.
各文のリストはさらにリストにネストする
args:
file_neme: str, MeCabの解析結果のファイル名
return:
all_sentences: list, 1文ごとの形態素のリストを要素としたリスト
"""
morph_list = []
all_sentences = []
with open(file_name, "r", encoding="utf-8") as f:
for line in f:
if line == "EOS\n":
if morph_list:
all_sentences.append(morph_list)
morph_list = []
continue
if re.search(r"^\*\s[0-9]+", line):
continue
morph = mecab_to_morph(line)
morph_list.append(morph)
return all_sentences
if __name__ == '__main__':
all_sentences = read_cabocha("neko.txt.cabocha")
for morph in all_sentences[2]:
print(morph)
<file_sep># NLP100本ノック
#
# 53. Tokenization
# Stanford Core NLPを用い,入力テキストの解析結果をXML形式で得よ.
# また,このXMLファイルを読み込み,入力テキストを1行1単語の形式で出力せよ.
# java -Xmx5g -cp stanford-corenlp-3.6.0.jar:stanford-corenlp-3.6.0-models.jar:* edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators tokenize,ssplit,pos,lemma,ner,parse,mention,coref -file nlp050_result.txt -outputFormat xml
import re
pattern = re.compile(r"<word>([^<]+)</word>")
with open("nlp.txt.xml", "r", encoding="utf-8") as f:
for line in f:
match = re.search(pattern, line)
if match:
print(match.group(1))
<file_sep># NLP100本ノック
#
# 04. 元素記号
# "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
# という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,
# それ以外の単語は先頭に2文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への
# 連想配列(辞書型もしくはマップ型)を作成せよ.
s = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
s = s.replace(".", "")
word_list = s.split()
dic = {}
l = [1, 5, 6, 7, 8, 9, 15, 16, 19]
for cnt, word in enumerate(word_list):
if cnt+1 in l:
dic.update({word[0]:cnt+1})
else:
dic.update({word[0:2]:cnt+1})
print(dic)
# {'H': 1, 'B': 5, 'S': 16, 'Li': 3, 'Ar': 18,
# 'O': 8, 'He': 2, 'Mi': 12, 'Na': 11, 'Cl': 17,
# 'C': 6, 'Ne': 10, 'Be': 4, 'F': 9, 'Si': 14,
# 'P': 15, 'Al': 13, 'N': 7, 'K': 19, 'Ca': 20}<file_sep># NLP100本ノック
#
# 22. カテゴリ名の抽出
# 記事のカテゴリ名を(行単位ではなく名前で)抽出せよ.
import re
with open("jawiki-britain.txt", "r", encoding="utf-8") as f:
for line in f:
if "Category:" in line:
match = re.search(r"Category:([^]]+)]", line)
print(match.group(1))
|
c166f77ecf7257b51489ad547f40eef8a0e88971
|
[
"Markdown",
"Python"
] | 75
|
Python
|
IchWale/NLP100
|
f25092b1250b17fb6c66b6f1e5e7a89801e90d89
|
46aaa57d82441c7d2dc7a1bc96b0fd72adf0cb07
|
refs/heads/master
|
<file_sep>rootProject.name = 'cheese-mvc'
<file_sep>package com.muteas.Bilgi;
import com.muteas.Entity.Ogrenci;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@Repository
public class OgrenciBilgi {
private static Map<Integer, Ogrenci> sinif;
static {
sinif= new HashMap<Integer, Ogrenci>(){
{
put(1,new Ogrenci(1,"James","Granger"));
put(2,new Ogrenci(2,"Hakeem","Bradley"));
put(3,new Ogrenci(3,"Jean","Rainbow"));
}
};
}
private OgrenciBilgi ogrenciBilgi;
public Collection<Ogrenci> SinifiAl(){
return sinif.values();
}
public Ogrenci idOgrenciAl(int id){
return sinif.get(id);
}
public void idOgrenciSil(int id) {
sinif.remove(id);
}
public void idOgrenciGuncelleme(Ogrenci ogrenci){
Ogrenci s=sinif.get(ogrenci.getId());
s.setSoyisim(ogrenci.getSoyisim());
s.setIsim(ogrenci.getIsim());
sinif.put(ogrenci.getId(),ogrenci);
}
public void idOgrenciEkleme(Ogrenci ogrenci) {
sinif.put(ogrenci.getId(),ogrenci);
}
}
<file_sep> package com.muteas.Service;
import com.muteas.Bilgi.OgrenciBilgi;
import com.muteas.Entity.Ogrenci;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collection;
@Service
public class OgrenciServis {
@Autowired
private OgrenciBilgi ogrenciBilgi;
public Collection<Ogrenci> SinifiAl(){
return this.ogrenciBilgi.SinifiAl();
}
public Ogrenci idOgrenciAl(int id){
return this.ogrenciBilgi.idOgrenciAl(id);
}
public void idOgrenciSil(int id) {
this.ogrenciBilgi.idOgrenciSil(id);
}
public void idOgrenciGuncelleme(Ogrenci ogrenci){
this.ogrenciBilgi.idOgrenciGuncelleme(ogrenci);
}
public void idOgrenciEkleme(Ogrenci ogrenci) {
this.ogrenciBilgi.idOgrenciEkleme(ogrenci);
}
}
|
8f6ea4615a8ffbda8eb8efacbbe55340d155d92f
|
[
"Java",
"Gradle"
] | 3
|
Gradle
|
mucahidyilmaz/-KayitEklemeSpringBoot
|
b48488605f529a405ee8b548771526320a18aff3
|
70490894d797eb88c88435e3eec9944521dd8141
|
refs/heads/master
|
<repo_name>pawan-subudhi/Wordpress<file_sep>/wp-content/themes/fictional-university-theme/inc/like-route.php
<?php
add_action('rest_api_init', 'universityLikeRoutes');//used whenever we want to add new custom route or new field to the route
function universityLikeRoutes(){
//register 2 new routes
//this is for post method i.e this is responsible for POST https type request
register_rest_route('university/v1', 'manageLike', array(
'methods' => 'POST',
'callback' => 'createLike'
));
//this is for delete method i.e this is responsible for DELETE https type request
register_rest_route('university/v1', 'manageLike', array(
'methods' => 'DELETE',
'callback' => 'deleteLike'
));
}
function createLike($data){
if(is_user_logged_in()){
$professor = sanitize_text_field( $data['professorID'] );
$existQuery = new WP_Query(array(
'author' => get_current_user_id(),
'post_type' => 'like',
'meta_query' => array(
array(
'key' => 'liked_professor_id',//name of custom field
'compare' => '=',
'value' => $professor
)
),
));
if($existQuery->found_posts == 0 AND get_post_type($professor) == 'professor'){
//wp_insert_post returns a id of newly created post id if it successfull
return wp_insert_post(array(
'post_type' => 'like',
'post_status' => 'publish',
'post_title' => 'Our PHP Create Post Test',
'meta_input' => array(
'liked_professor_id' => $professor
),
));//will let us programatically create a new post right from our php code
} else {
die("Invalid professor id");
}
} else {
die("Only logged in users can create a like.");
}
}
function deleteLike($data){
$likeId = sanitize_text_field( $data['like'] );
if(get_current_user_id() == get_post_field('post_author', $likeId) AND get_post_type($likeId) == 'like') {
wp_delete_post($likeId, true);//takes 2 args .. 1st is the id and 2nd is wether we want to move it to the trash or skip the trash and completely delete. if true then we are trying to skip the trash
return"Congrats, like deleted.";
} else {
die("You do not have the permission to delete that.");
}
}<file_sep>/README.md
# Wordpress
This is fictional university website built using wordpress
<file_sep>/wp-content/themes/fictional-university-theme/js/modules/Like.js
import $ from 'jquery';
class Like {
constructor(){
this.events();//this adds our event listeners as soon as the page loads
}
events(){
$(".like-box").on("click", this.ourClickDispatcher.bind(this));
}
//methods
ourClickDispatcher(e){
var currentLikeBox = $(e.target).closest(".like-box");//whatever element got clicked on find its closest ancistor that matches this selector
// the js .data function only looks at the data-attribute only once when the page loads so if we want our user to toggle back and forth b/w liking anf unliking so this method wont work fine so we need to use the attr function
if(currentLikeBox.attr('data-exists') == 'yes') {
this.deleteLike(currentLikeBox);
} else {
this.createLike(currentLikeBox);
}
}
createLike(currentLikeBox){
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', universityData.nonce);
},
url: universityData.root_url + '/wp-json/university/v1/manageLike',
type: 'POST',
data: {'professorID': currentLikeBox.data('professor')},
success: (response) => {
currentLikeBox.attr('data-exists','yes');
var likeCount = parseInt(currentLikeBox.find('.like-count').html(),10);
likeCount++;
currentLikeBox.find('.like-count').html(likeCount);
currentLikeBox.attr('data-like',response);
console.log(response);
},
error: (response) => {
console.log(response);
}
});
}
deleteLike(currentLikeBox){
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', universityData.nonce);
},
url: universityData.root_url + '/wp-json/university/v1/manageLike',
data: {
'like' : currentLikeBox.attr('data-like')
},
type: 'DELETE',
success: (response) => {
currentLikeBox.attr('data-exists','no');
var likeCount = parseInt(currentLikeBox.find('.like-count').html(),10);
likeCount--;
currentLikeBox.find('.like-count').html(likeCount);
currentLikeBox.attr('data-like','');
console.log(response);
},
error: (response) => {
console.log(response);
}
});
}
}
export default Like;<file_sep>/wp-content/mu-plugins/university-post-types.php
<?php
//to register/create a post type
//Event Post Type
function university_post_types(){
register_post_type('event', array(
'capability_type' => 'event',
'map_meta_cap' => true,
'supports' => array('title', 'editor', 'excerpt'),
'rewrite' => array(
'slug' => 'events'
),
'has_archive' => true,//so it could support archive mode
'public' => true, //this make sthe post type visible to editors and viewers over the website
'labels' => array(
'name' => 'Events',//gives name in the dasboard events like any other sections
'add_new_item' => 'Add New Event',//when clicked onto the events it will show at the top add new eventin this scene
'edit_item' => 'Edit Event',
'all_items' => 'All Events',//whenever we hiver on the event ssection it will show this
'singular_name' => 'Event',//name for one object of this post type
),
'menu_icon' => 'dashicons-calendar'
));
//Program Post Type
register_post_type('program', array(
'supports' => array('title'),
'rewrite' => array(
'slug' => 'programs'
),
'has_archive' => true,//so it could support archive mode
'public' => true, //this make sthe post type visible to editors and viewers over the website
'labels' => array(
'name' => 'Programs',//gives name in the dasboard events like any other sections
'add_new_item' => 'Add New Program',//when clicked onto the events it will show at the top add new eventin this scene
'edit_item' => 'Edit Program',
'all_items' => 'All Programs',//whenever we hiver on the event ssection it will show this
'singular_name' => 'Program',//name for one object of this post type
),
'menu_icon' => 'dashicons-awards'
));
//Professor Post Type
register_post_type('professor', array(
'show_in_rest' =>true,//to enable raw json data for custom post types created we need to make this field true
'supports' => array('title', 'editor','thumbnail'),
'public' => true, //this make sthe post type visible to editors and viewers over the website
'labels' => array(
'name' => 'Professors',//gives name in the dasboard events like any other sections
'add_new_item' => 'Add New Professor',//when clicked onto the events it will show at the top add new eventin this scene
'edit_item' => 'Edit Professor',
'all_items' => 'All Professors',//whenever we hiver on the event ssection it will show this
'singular_name' => 'Professor',//name for one object of this post type
),
'menu_icon' => 'dashicons-welcome-learn-more'
));
//Campus Post Type
register_post_type('campus', array(
'capability_type' => 'campus',
'map_meta_cap' => true,
'supports' => array('title', 'editor', 'excerpt'),
// archive URL
'rewrite' => array(
'slug' => 'campuses'
),
'has_archive' => true,//so it could support archive mode
'public' => true, //this make sthe post type visible to editors and viewers over the website
'labels' => array(
'name' => 'Campuses',//gives name in the dasboard events like any other sections
'add_new_item' => 'Add New Campus',//when clicked onto the events it will show at the top add new eventin this scene
'edit_item' => 'Edit Campus',
'all_items' => 'All Campuses',//whenever we hiver on the event ssection it will show this
'singular_name' => 'Campus',//name for one object of this post type
),
'menu_icon' => 'dashicons-location-alt'
));
//Note Post Type
register_post_type('note', array(
'capability_type' => 'note',
'map_meta_cap' => true,
'show_in_rest' => true,//to enable raw json data for custom post types created we need to make this field true. It enables the built-in rest api end points
'supports' => array('title', 'editor'),
'public' => false, //because we want notes to be private and sepecific to each user account not want our note to display in our public query or in search results and this false will hide it from admin dashboard
'show_ui' => true,//this will enable the post type show in dashboard
'labels' => array(
'name' => 'Notes',//gives name in the dasboard events like any other sections
'add_new_item' => 'Add New Note',//when clicked onto the events it will show at the top add new eventin this scene
'edit_item' => 'Edit Note',
'all_items' => 'All Notes',//whenever we hiver on the event ssection it will show this
'singular_name' => 'Note',//name for one object of this post type
),
'menu_icon' => 'dashicons-welcome-write-blog'
));
//Like Post Type
register_post_type('like', array(
'supports' => array('title'),
'public' => false, //because we want notes to be private and sepecific to each user account not want our note to display in our public query or in search results and this false will hide it from admin dashboard
'show_ui' => true,//this will enable the post type show in dashboard
'labels' => array(
'name' => 'Likes',//gives name in the dasboard events like any other sections
'add_new_item' => 'Add New Like',//when clicked onto the events it will show at the top add new eventin this scene
'edit_item' => 'Edit Like',
'all_items' => 'All Likes',//whenever we hiver on the event ssection it will show this
'singular_name' => 'Like',//name for one object of this post type
),
'menu_icon' => 'dashicons-heart'
));
}
add_action('init','university_post_types');
<file_sep>/wp-content/themes/fictional-university-theme/functions.php
<?php
require get_theme_file_path('/inc/search-route.php');
require get_theme_file_path('/inc/like-route.php');
//to add a custom field to the raw json data that wp sends back to us while rest api we call for live search i.e add author name to the posts data we fetch
function university_custom_rest(){
//takes 3 args. 1st is the post type we wan to cutomize, 2nd is the name to field u want to add, 3rd is array how we want to manage this field
//here the return value of get_callback is assigned to the authorName
register_rest_field('post', 'authorName', array(
'get_callback' => function(){return get_the_author();}
));
register_rest_field('note', 'userNoteCount', array(
'get_callback' => function(){return count_user_posts(get_current_user_id(), 'note');}
));
}
//takes 2 args. 1st is wp event we want to hook onto and 2nd is the func we want to call during this event hook
add_action('rest_api_init','university_custom_rest');
function pageBanner($args = NULL) {
//php logic
if (!$args['title']) {
$args['title'] = get_the_title();
}
if (!$args['subtitle']) {
$args['subtitle'] = get_field('page_banner_subtitle');
}
if (!$args['photo']) {
if (get_field('page_banner_background_image')) {
$args['photo'] = get_field('page_banner_background_image')['sizes']['pageBanner'];
} else {
$args['photo'] = get_theme_file_uri('/images/ocean.jpg');
}
}
?>
<div class="page-banner">
<div class="page-banner__bg-image" style="background-image: url(<?php echo $args['photo']; ?>);"></div>
<div class="page-banner__content container container--narrow">
<h1 class="page-banner__title"><?php echo $args['title'] ?></h1>
<div class="page-banner__intro">
<p><?php echo $args['subtitle']; ?></p>
</div>
</div>
</div>
<?php }
function university_files() {
// alias name, file path, this script/file is dependednt on any other script, version number can give any or to avoid caching use a little trick of microtime which gives uniques value evrytime loaded, do u want to load this file right before the closing body tag
wp_enqueue_script('main-university-js', get_theme_file_uri('/js/scripts-bundled.js'), NULL, microtime(), true);
wp_enqueue_style('custom-google-fonts', '//fonts.googleapis.com/css?family=Roboto+Condensed:300,300i,400,400i,700,700i|Roboto:100,300,400,400i,700,700i');
wp_enqueue_style('font-awesome', '//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');
wp_enqueue_style('university_main_styles', get_stylesheet_uri(), NULL, microtime());
//take 3 args for 1st include name/handle js file which u want to make flexible
//2nd arg is make u a variable name
//3rd is array of data we want to make it available in js file
wp_localize_script('main-university-js','universityData',array(
'root_url' => get_site_url(),
'nonce' => wp_create_nonce('wp_rest'),
));
}
add_action('wp_enqueue_scripts', 'university_files');
function university_features() {
add_theme_support('title-tag');
add_theme_support('post-thumbnails');
add_image_size('professorLandscape', 400, 260, true);//nickname, width, height, do u want to crop the image or not
//if set to true the cropping will be done towards the center
//if want more control provide array with direction 1st parameter either left,right and center , 2nd param will be top, center, bottom
add_image_size('professorPortrait', 480, 650, true);
add_image_size('pageBanner', 1500, 350, true);
}
add_action('after_setup_theme', 'university_features');
function university_adjust_queries($query) {
if (!is_admin() AND is_post_type_archive('campus') AND $query->is_main_query()) {
$query->set('posts_per_page', -1);
}
if (!is_admin() AND is_post_type_archive('program') AND $query->is_main_query()) {
$query->set('orderby', 'title');
$query->set('order', 'ASC');
$query->set('posts_per_page', -1);
}
if (!is_admin() AND is_post_type_archive('event') AND $query->is_main_query()) {
$today = date('Ymd');
$query->set('meta_key', 'event_date');
$query->set('orderby', 'meta_value_num');
$query->set('order', 'ASC');
$query->set('meta_query', array(
array(
'key' => 'event_date',
'compare' => '>=',
'value' => $today,
'type' => 'numeric'
)
));
}
}
add_action('pre_get_posts', 'university_adjust_queries');
//Reedirect Subuscriber account out of admin and onto homepage
add_action('admin_init','redirectSubsToFrontend');
function redirectSubsToFrontend(){
$ourCurrentUser = wp_get_current_user();
if(count($ourCurrentUser->roles) == 1 AND $ourCurrentUser->roles[0] == 'subscriber'){
wp_redirect(site_url('/'));
exit;
}
}
add_action('wp_loaded','noSubsAdminBar');
function noSubsAdminBar(){
$ourCurrentUser = wp_get_current_user();
if(count($ourCurrentUser->roles) == 1 AND $ourCurrentUser->roles[0] == 'subscriber'){
show_admin_bar(false);
}
}
//Customizing login screen
add_filter('login_headerurl', 'ourHeaderUrl');
function ourHeaderUrl(){
return esc_url(site_url('/'));
}
add_action('login_enqueue_scripts', 'ourLoginCSS');
function ourLoginCSS(){
wp_enqueue_style('university_main_styles', get_stylesheet_uri(), NULL, microtime());
wp_enqueue_style('custom-google-fonts', '//fonts.googleapis.com/css?family=Roboto+Condensed:300,300i,400,400i,700,700i|Roboto:100,300,400,400i,700,700i');
}
add_filter('login_headertitle', 'ourLoginTitle');
function ourLoginTitle(){
return get_bloginfo('name');
}
//Force note posts to be private
add_filter('wp_insert_post_data', 'makeNotePrivate', 10, 2);//this hooks intercepts the request right before the data could save into wp database
function makeNotePrivate($data, $postarr){
if($data['post_type'] == 'note'){
if(count_user_posts(get_current_user_id(), 'note') > 4 AND !$postarr['ID']){
die("You have reached your note limit.");
}
$data['post_title'] = sanitize_text_field($data['post_title']);
$data['post_content'] = sanitize_textarea_field($data['post_content']);
}
if($data['post_type'] == 'note' AND $data['post_status'] != 'trash'){
$data['post_status'] = "private";
}
return $data;
}
|
8c4e422b69e8671249cfeb21221b418130f0b4d0
|
[
"Markdown",
"JavaScript",
"PHP"
] | 5
|
PHP
|
pawan-subudhi/Wordpress
|
e5a451cb86964e87810bd7b86d1689205d95477f
|
cddf0b801f987be48e69577358bba486e33819f3
|
refs/heads/master
|
<file_sep>### Set up the variables required to read and piece together
### the test and training data
## all files are in the UCI HAR Dataset directory in the working directory
## read the features.txt file to get the all column names
the_headers <- read.csv("UCI HAR Dataset/features.txt", header = FALSE, sep = " ")
## get the columns of interest
# For the purposes of this project, only the basic mean and standard deviations
# will be part of the tidy data set. The measurements which have been
# calculated by meanFreq() and gravityMean() will not be part of this project
the_cols <-
unname(
unlist(
lapply(
subset(
the_headers,
select = c(2)),
function(x) grep("\\bmean()\\b|std()", x)
)
)
)
## activity labels for the tidy data set later in this script
activity_labels <- read.csv("UCI HAR Dataset/activity_labels.txt",
header = FALSE,
sep = " ")
## The test and training data are fixed width format files. Each column of
## data is 16 characters and there are 561 columns of data. The number of
## columns can be discovered with:
## length(the_headers[,1])
# reading all the columms is slow, so take advantage of the ability to skip
# columns when using read.fwf()
# create a vector with 561 elements; set them all to -16 to skip each column
col_widths <- rep(c(-16), each = 561)
# now set the columns we actually want to a positive sixteen
col_widths[the_cols] <- 16
# the file has a leading space
col_widths[1] <- 17
# to double check, each line in the file is 8977 characters.
# (8977 - 1)/16 = 561 Perfect. Let's go read some data....
### Get the data for test, activities, and subjects
## Test data
test_x <- read.fwf("UCI HAR Dataset/test/X_test.txt",
header = FALSE,
widths = col_widths)
# rename the columns
names(test_x) <- as.vector(the_headers[the_cols,2])
## Test activities
test_y_activity <- read.csv("UCI HAR Dataset/test/y_test.txt", header = FALSE)
## Subjects
subject_test <- read.csv("UCI HAR Dataset/test/subject_test.txt", header = FALSE)
## Use column binding to place the subjects and their activites with their
## corresponding data
test <- cbind(subject_test, test_y_activity, test_x)
## add names to these two new columns
names(test)[1:2] <- c("Subject", "Activity")
## clean up some memory space; like when I'm cooking, I try to clean as I go
rm(test_x)
rm(test_y_activity)
rm(subject_test)
### Get the data for training
train_x <- read.fwf("UCI HAR Dataset/train/X_train.txt",
header = FALSE,
widths = col_widths)
# The rbind() call to merge the data sets will fail if the column names don't
# match so go ahead and name them.
names(train_x) <- as.vector(the_headers[the_cols,2])
train_y_activity <- read.csv("UCI HAR Dataset/train/y_train.txt", header = FALSE)
subject_train <- read.csv("UCI HAR Dataset/train/subject_train.txt", header = FALSE)
train <- cbind(subject_train, train_y_activity, train_x)
names(train)[1:2] <- c("Subject", "Activity")
rm(train_x)
rm(train_y_activity)
rm(subject_train)
### Combine test and train
## use row binding to stack the two data sets together
merged_data <- rbind(test, train)
rm(test)
rm(train)
rm(the_headers)
rm(col_widths)
rm(the_cols)
### Create the tidy data set
## unique(merged_data[, 1:2]) tells me I have 180 unique combinations of
## subject and activity
tidy_data <- aggregate(merged_data[, 3:68],
list(merged_data$Subject, merged_data$Activity),
mean)
### never assume anything; do a few spot checks to ensure the tidy data
### is correct
# double_check <- subset(merged_data,
# Subject == 2 & Activity == 5,
# select = c(3))
# mean(double_check[,1])
# tidied_data <- tidy_data[which(
# tidy_data$Group.1 == 2 & tidy_data$Group.2 == 5),]
names(tidy_data)[1:2] <- c("Subject", "Activity")
# change the activity codes to meaningful labels
tidy_data$Activity <- activity_labels$V2[match(tidy_data$Activity,
activity_labels$V1)]
write.table(tidy_data, file = "tidy_data.txt", row.names = FALSE, sep = ",")
rm(activity_labels)
rm(merged_data)
rm(tidy_data)
|
1a2d346d1c96f0cb460f514138a013ccb20dd0e8
|
[
"R"
] | 1
|
R
|
David-Carnes/G_and_C_Data_Course_Project
|
6e0317fb5dc328cb6ccd247653aabfee3429b621
|
3e6579f8c51248e49c327006116cbf4d942cfa97
|
refs/heads/main
|
<repo_name>fabianpena90/widgets<file_sep>/src/components/Convert.js
import React, { useState, useEffect } from 'react';
import axios from 'axios'
function Convert(props) {
const [translated, setTranslated] = useState('')
// const [otherText, setOtherText] = useEffect(props.text)
// useEffect(() => {
// const timerId = setTimeout(() =>{
// setOtherText(props.text)
// }, 500);
// return () => {
// clearTimeout(timerId)
// }
// },[props.text])
useEffect(() => {
async function translate() {
let res = await axios.post('https://translation.googleapis.com/language/translate/v2', {}, {
params: {
q: props.text,
target: props?.language?.value,
key: '<KEY>'
}
})
setTranslated(res?.data.data?.translations[0]?.translatedText)
// setTranslated(res.data.translations.translatedText)
}
translate()
},[props.language, props.text])
return (
<div>
<h1 className="ui header">{translated}</h1>
</div>
);
}
export default Convert;<file_sep>/src/components/ColorSelector.js
import React, { useState, useEffect, useRef } from 'react';
import 'semantic-ui-css/semantic.min.css'
function ColorSelector(props) {
const [open, setOpen] = useState(false);
const ref = useRef(); // to give reference of what element is
useEffect(() => {
document.body.addEventListener('click', (e) => {
if(ref.current?.contains(e.target)){
return;
}
setOpen(false)
})
},[])
const colorOptions = props.options?.map(option =>{
if(option.value === props.selected.value) {
return null
}
return (
<div onClick={() => props.onSelectedChange(option)} key={props.options.value} className="item">
{option.label}
</div>
)
})
return (
<div ref={ref} className="ui form">
<div className="field">
<label className="label">{props.label}</label>
<div
onClick={() => setOpen(!open)}
className={`ui selection dropdown ${open ? 'visible active' : ''}`}>
<i className="dropdown icon"></i>
<div className="text">{props?.selected?.label}</div>
<div className={`menu ${open ? 'visible transition': ''}`}>
{colorOptions}
</div>
</div>
</div>
</div>
);
}
export default ColorSelector;<file_sep>/src/components/App.js
import React, { useState, useEffect }from 'react';
import Accordion from './Accordion'
import Search from './Search'
import ColorSelector from './ColorSelector'
import Translate from './Translate'
import Route from './Route'
import Header from './Header'
const items = [
{
title: "What is Full Stack Developer?",
content: "A full stack developer is a web developer or engineer who works with both the front and back ends of a website or application—meaning they can tackle projects that involve databases, building user-facing websites, or even work with clients during the planning phase of projects."
},
{
title: "What is Frontend Developer?",
content: "Front-end web development is the practice of converting data to a graphical interface, through the use of HTML, CSS, and JavaScript, so that users can view and interact with that data"
},
{
title: "What is Backend Developer?",
content: "A back-end web developer is responsible for server-side web application logic and integration of the work front-end developers do. Back-end developers are usually write the web services and APIs used by front-end developers and mobile application developers"
}
];
const options = [
{
label: 'The Color Red',
value: 'red'
},
{
label: 'The Color Blue',
value: 'blue'
},
{
label: 'The Color Green',
value: 'green'
},
]
function App() {
const [selected, setSelected] = useState(options[0]);
// const [showColorSelector, setShowColorSelector] = useState(true)
// function showAccordion(){
// if(window.location.pathname === '/'){
// return <Accordion items={items}/>
// }
// }
// function showSearch(){
// if(window.location.pathname === '/list'){
// return <Search />
// }
// }
// function showColorSelector(){
// if(window.location.pathname === '/colorSelector'){
// return <ColorSelector />
// }
// }
// function showTranslate(){
// if(window.location.pathname === '/translate'){
// return <Translate />
// }
// }
return (
<div className='ui container'>
{/* <Search /> */}
{/* <Accordion items={items} /> */}
{/* <button onClick={() => setShowColorSelector(!showColorSelector)}>Toggle Dropdown</button>
{showColorSelector ? */}
{/* <ColorSelector
selected={selected}
options={options}
onSelectedChange={setSelected}
/> */}
{/* : null
} */}
<Header />
<Route path="/">
<Accordion items={items} />
</Route>
<Route path="/list">
<Search />
</Route>
<Route path="/colorSelector">
<ColorSelector
label="Select a color"
options={options}
selected={selected}
onSelectedChange={setSelected}
/>
</Route>
<Route path="/translate">
<Translate />
</Route>
</div>
);
}
export default App;
<file_sep>/src/components/Accordion.js
import React, { useState } from 'react';
import 'semantic-ui-css/semantic.min.css'
function Accordion({items}) {
const [title, setTitle] = useState(null)
function titleClick(index){
// console.log('Title was clicked', index);
setTitle(index)
}
const fullContent = items.map((item, index) =>{
const active = index === title ? "active" : ""
return (
<React.Fragment key={item.title}>
<div
onClick={() => titleClick(index)}
className={`title ${active}`}>
<i className="dropdown icon"></i>
{item.title}
</div>
<div className={`content ${active}`}>
<p>{item.content}</p>
</div>
</React.Fragment>
)
})
return (
<div className="ui styled accordion">
{fullContent}
</div>
);
}
export default Accordion;
|
1924bb1c8781c02d8cae0f6d2afb4c4f7782516e
|
[
"JavaScript"
] | 4
|
JavaScript
|
fabianpena90/widgets
|
c500c8e887ce73b100df01591cd07dd067ae3a15
|
7f543806038e87ba07d9aa644b93e45c4e9afe81
|
refs/heads/main
|
<repo_name>Venjora/Project02<file_sep>/js/script.js
const listQuery = document.querySelectorAll('li');
listQuery.innerHTML = "";
//putting nodeList into an Array
const contacts = Array.from(listQuery);
var current_page = 1;
const rows = 10;
//to get the extra 4contacts as a whole numbers
var page_no = Math.ceil(contacts.length/rows);
console.log(page_no);
//number of contacts
console.log(contacts.length);
//creating id to ul
const element = document.getElementsByTagName('ul')[0];
element.id = "contactList";
var contactID = document.getElementById('contactList');
function DisplayContacts(items, wrapper, rows_per_page, page){
// wrapper.innerHTML = "";
page--;
//start = 0;
let start = rows_per_page * page;
// end = 10;
let end = start + rows_per_page;
let paginatedItems = items.slice(start, end);
//emptying the ul
wrapper.innerHTML = "";
for(let i = 0; i < paginatedItems.length; i++){
let item = paginatedItems[i];
contactID.innerHTML +='<li class = "contact-item cf">'+ item.innerHTML + '</li>';
}
}
const div = document.createElement('div');
div.id = 'pagination';
div.className = 'pagination';
document.getElementsByClassName('page')[0].id = "page";
document.getElementById('page').appendChild(div);
const pages = document.getElementById('pagination');
DisplayContacts(contacts, contactID, rows, current_page);
// const link = document.createElement('a');
// console.log(link.innerHTML);
// document.getElementById('btn').appendChild(link);
function SetupPages (wrapper){
wrapper.innerHTML = "";
let list = document.createElement('li');
list.id = 'list';
let button = document.createElement('button');
button.id ='btn';
button.className = 'btn';
button.style.cssText ='border: none; padding: 0; background: none'
document.getElementById('pagination').appendChild(list);
document.getElementById('list').appendChild(button);
for(i = 1; i <page_no+1; i++){
DisplayButtons(i);
}
}
function DisplayButtons(page){
const link = document.createElement('a');
console.log(link.innerHTML);
document.getElementById('btn').appendChild(link);
link.innerText = page;
if(current_page == page) {link.classList.add('active')};
link.addEventListener('click', function(){
if(current_page == page) {link.classList.add('active')};
current_page = page;
DisplayContacts(contacts, contactID, rows, current_page);
let current_btn = document.querySelector('li a.active');
current_btn.classList.remove('active');
link.classList.add('active');
});
return link;
}
SetupPages(pages);
|
1306619f8c1e0d56d4af421e905854756c1310f4
|
[
"JavaScript"
] | 1
|
JavaScript
|
Venjora/Project02
|
b7fc192d93b4ac9627c2a73ffd81fdffc5487f32
|
d17783abd22a44a2a3f9bb62730e2e15aa38dded
|
refs/heads/master
|
<repo_name>puerdon/falcon_for_ptt_word<file_sep>/Dockerfile
FROM python:3.8.0-alpine3.10
ENV PYTHONUNBUFFERED 1
COPY requirements.txt /tmp/
RUN pip install -r /tmp/requirements.txt
EXPOSE 80
WORKDIR /data
COPY ./api /app
WORKDIR /app
CMD ["gunicorn", "-b", "0.0.0.0:80", "app:api"]
<file_sep>/api/app.py
import falcon
from ptt_word import PTTWordResource, AvailableBoardsResource
api = application = falcon.API()
ptt_word_resource = PTTWordResource()
api.add_route('/query', ptt_word_resource)
available_boards_resource = AvailableBoardsResource()
api.add_route('/available_boards', available_boards_resource)<file_sep>/api/ptt_word.py
import json
import falcon
import logging
import os
class AvailableBoardsResource(object):
def on_get(self, req, resp):
boards = [b.split('.json')[0] for b in os.listdir("/data")]
resp.body = json.dumps(boards, ensure_ascii=False)
class PTTWordResource(object):
def __init__(self):
self.logger = logging.getLogger('x.' + __name__)
def on_get(self, req, resp):
lemma = req.get_param("lemma", required=True)
pos = req.get_param("pos")
board = req.get_param("board", required=True)
year = req.get_param("year", required=True)
# step 1: 檢查是否有該版資料
if not os.path.isfile(f"/data/{board}.json"):
result = {
"result": 0,
"error": f"no data for board: <{board}>"
}
resp.body = json.dumps(result, ensure_ascii=False)
return
with open(f"/data/{board}.json", "r") as f:
d = json.load(f)
# step 2: 確認有該版資料後,檢查是否有年份資料
try:
result = d[year]
except KeyError:
result = {
"result": 0,
"error": f"no data for year: <{year}> in board: <{board}>"
}
resp.body = json.dumps(result, ensure_ascii=False)
return
# step 3: 確認有該版與該年份資料後,檢查是否有該lemma資料
try:
result = result[lemma]
except KeyError:
result = {
"result": 0,
"error": f"no data for lemma: <{lemma}> in board: <{board}> in year <{year}>"
}
resp.body = json.dumps(result, ensure_ascii=False)
return
else:
# 確認有該lemma資料後,檢查client是否有query特定pos
if pos is None: # client沒有輸入pos
result = {
"result": 1,
"freq": {k: v / get_year_total_freq(year=year) for k, v in result.items()}
}
resp.body = json.dumps(result, ensure_ascii=False)
else: # cline有輸入pos
try: # 檢查該pos是否存在
result = {
"result": 1,
"freq": result[pos] / get_year_total_freq(year=year)
}
except KeyError:
available_pos = [f"<{p}>" for p in result.keys()]
result = {
"result": 0,
"error": f"no data for lemma: <{lemma}> with pos: <{pos}>, please try pos: {', '.join(available_pos)}"
}
finally:
resp.body = json.dumps(result, ensure_ascii=False)
def get_year_total_freq(year=None):
with open(f"/data/sum_by_year.json", "r") as f:
d = json.load(f)
return d[year]
<file_sep>/README.md
# falcon_for_ptt_word
用來查詢ptt各版當中詞彙於各年份的頻率
- Step 1: build docker image
`$ docker-compose up --build`
- Step 2: 將各版的json複製到`board_data`資料夾
<版名>.json
json 格式:
```
{
"2004" <str: 年份>: {
"打" <str: lemma>: {
"NN" <str: pos>: 70 <int: freq>,
"Va" <str: pos>: 100 <int: freq>,
...
},
...
},
...
}
- Step 3: `board_dadta/` 資料夾中也需要放入 `sum_by_year.json` ,紀錄每年的總詞頻
json 格式:
```
{
"2004": <int>,
"2005": <int>,
...
}
```
```
|
1ce0859ca268785224e95417fc09ca0817c2acab
|
[
"Markdown",
"Python",
"Dockerfile"
] | 4
|
Dockerfile
|
puerdon/falcon_for_ptt_word
|
4a91c2a7455826afda4258afa545cdb883e89a16
|
b98fb154230fba19c7614b97ddf2bff624556d3a
|
refs/heads/master
|
<file_sep>
import React, { Component } from 'react';
import {
View,
StyleSheet,
PermissionsAndroid,
Platform,
AsyncStorage
} from 'react-native';
import { Container, Header, Content, Button, Text } from 'native-base';
class LandingScreen extends Component {
async componentDidMount() {
var userID = await AsyncStorage.getItem('userID')
if (userID != null) {
console.log(userID)
globalUserID = userID
}
try {
const granted = await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
PermissionsAndroid.PERMISSIONS.CAMERA,
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
])
} catch (err) {
console.warn(err)
}
}
render() {
return (
<Container style={{ backgroundColor: "#262626", alignItems: 'center' }}>
<Content>
<Button style={{ marginTop: 100 }} large rounded block
onPress={() => this.props.navigation.navigate('Signup')}>
<Text>Signup</Text>
</Button>
<Text style={styles.Text}>-----Already a member?-----</Text>
<Button style={{ width: "100%" }} rounded large block success
onPress={() => this.props.navigation.navigate('Login')}>
<Text>Login</Text>
</Button>
</Content>
</Container>
// <Button
// style={styles.Button}
// contentStyle={{ height: 80, width: 300 }}
// color="#2E75B5" mode="contained"
// onPress={() => this.props.navigation.navigate('Signup')}>
// <Text style={styles.Text2}>Sign Up</Text>
// </Button>
// <Text style={styles.Text}>-----Already a member?-----</Text>
// <Button
// style={styles.Button}
// contentStyle={{ height: 80, width: 300 }}
// color="#00AF50" mode="contained"
// onPress={() => this.props.navigation.navigate('Signup')}>
// <Text style={styles.Text2}>Login</Text>
// </Button>
)
}
}
export default LandingScreen
const styles = StyleSheet.create({
Container: {
flex: 1,
backgroundColor: '#262626'
},
btnContainer: {
marginTop: 100,
alignItems: 'center',
marginRight: 10,
marginLeft: 10
},
Text: {
marginTop: 100,
marginBottom: 30,
color: 'white',
alignSelf: 'center'
},
Text2: {
fontSize: 20
},
Button: {
borderRadius: 20
},
})<file_sep>import React,{ Component } from 'react';
import { Container, Header, Content, Button, Text, Icon, Left, Right, Body, Item, Input } from 'native-base';
class Notifications extends Component{
render(){
return(
<Container>
<Content>
</Content>
</Container>
)
}
}
export default Notifications<file_sep>
import React, { Component } from 'react';
import {
View,
StyleSheet,
} from 'react-native';
var message = ""
import { Container, Header, Content, Button, Text, Icon, Left, Right, Body, Item, Input } from 'native-base';
import firebase, { storage } from 'firebase'
import { config } from '../../../Firebase/index'
if (!firebase.apps.length) {
firebase.initializeApp(config())
}
class SignUp extends Component {
constructor(props) {
super(props);
this.state = {
text: {
username: '',
firstname: '',
lastname: '',
age: '',
team: '',
password: '',
confirmPassword: ''
},
};
}
textChangedHandler = (igKey, value) => {
var text = { ...this.state.text }
text[igKey] = value
this.setState({ text: text })
}
test() {
alert(this.state.text.username + " " + this.state.text.firstname + " " + this.state.text.lastname)
}
componentDidMount() {
}
onSubmitHandler = () => {
var values = []
var users = []
Object.keys(this.state.text)
.map(igKey => values.push(this.state.text[igKey]))
var users = []
firebase.database().ref('Users/').once('value', function (snapshot) {
users = snapshot.val()
}).then(() => {
var userExist = false
Object.keys(users)
.map(igKey => {
if (this.state.text.username == users[igKey]['username']) {
userExist = true
return
}
})
if (userExist) {
alert('Username already exists')
} else {
if (values.indexOf('') >= 0) {
if (values[5] == values[6]) {
alert("Please fill up all fields!")
}
}
else {
var datas = firebase.database().ref('/Users')
datas.push(this.state.text);
}
}
});
}
// checkIfUsernameExists(){
// var users =
// }
render() {
const placeholder = ['Username', 'Firstname', 'Lastname', 'Age', 'Team', '<PASSWORD>', '<PASSWORD>']
const TextInputs = Object.keys(this.state.text)
.map((igKey, index) => {
return (
<Item style={styles.item}>
<Input style={styles.input} placeholder={placeholder[index]}
value={this.state.text.igKey}
onChangeText={value => this.textChangedHandler(igKey, value)} />
</Item>)
})
return (
<Container style={{ backgroundColor: "#262626" }}>
<Content>
<Button transparent style={{ position: 'absolute', left: 0, right: 0 }}
onPress={() => this.props.navigation.goBack()}>
<Icon name='arrow-back' style={{ fontSize: 35, color: 'white' }} />
</Button>
<View style={{ alignItems: 'center', marginTop: 60, marginRight: 30, marginLeft: 30 }}>
{TextInputs}
<Button
success
onPress={() => this.onSubmitHandler()}
style={styles.button} block>
<Text>Login</Text>
</Button>
</View>
</Content>
</Container>
)
}
}
export default SignUp
const styles = StyleSheet.create({
Container: {
flex: 1,
backgroundColor: '#262626'
},
item: {
margin: 5,
backgroundColor: '#ADB8CA',
borderRadius: 10,
borderColor: 'transparent'
}, input: {
marginLeft: 5
}, button: {
borderRadius: 10,
marginTop: 30
}
})
<file_sep>/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow
*/
import React, { Component } from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
} from 'react-native';
import Home from './Screens/Home/Home'
import BikeShop from './Screens/BikeShop/BikeShop'
import LandingScreen from './Screens/LandingScreen/LandingScreen'
import Login from './Screens/LandingScreen/Login/Login'
import Signup from './Screens/LandingScreen/Signup/Signup'
import Record from './Screens/Record/Record'
import Profile from './Screens/Profile/Profile'
import Notifications from './Screens/Notifications/Notifications'
import SaveActivity from './Screens/SaveActivity/SaveActivity'
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import {Icon} from 'native-base';
const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();
global.globalUserID =""
function Tabs() {
return (
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName;
if (route.name === 'Home') {
iconName = focused ? 'ios-home' :'ios-home';
} else if (route.name === 'Record') {
iconName = focused ? 'ios-add-circle' : 'ios-add-circle-outline';
} else if (route.name === 'BikeShop'){
iconName = focused ? 'md-bicycle' : 'md-bicycle';
}else if (route.name === 'Profile'){
iconName = focused ? 'ios-contact': 'ios-contact';
}
// You can return any component that you like here!
return <Icon name={iconName} size={size} style={{color:color}} />;
},
})}
tabBarOptions={{
activeTintColor: 'tomato',
inactiveTintColor: 'gray',
}}
>
<Tab.Screen name="Home" component={Home} />
<Tab.Screen name="Record" component={Record} />
<Tab.Screen name="BikeShop" component={BikeShop} />
<Tab.Screen name="Profile" component={Profile} />
</Tab.Navigator>
)
}
function Stacks() {
return (
<Stack.Navigator screenOptions={{
headerShown: false}}>
<Stack.Screen name="LandingScreen" component={LandingScreen} />
<Stack.Screen name="Tabs" component={Tabs} />
<Stack.Screen name="Login" component={Login} />
<Stack.Screen name="Signup" component={Signup} />
<Stack.Screen name="Notifications" component={Notifications} />
<Tab.Screen name="SaveActivity" component={SaveActivity} />
</Stack.Navigator>
)
}
export default function App() {
return (
<NavigationContainer>
<Stacks />
</NavigationContainer>
);
}
<file_sep>import React, { Component } from 'react';
import { Container, Header, Content, Button, Text, Icon, Left, Right, Body, Badge, Item, Input } from 'native-base';
import { TouchableOpacity } from 'react-native-gesture-handler';
class SaveActivityHeader extends Component {
render() {
return (
<Header style={{ backgroundColor: 'white' }}>
<Left>
<TouchableOpacity
onPress={() => this.props.navigation.goBack()}>
<Icon name='arrow-back' style={{ fontSize: 30, color: 'black' }} />
</TouchableOpacity>
</Left>
<Body>
</Body>
<Right>
<TouchableOpacity onPress={()=>this.props.onSave(this.props.trailTitle)}>
<Text>Save</Text>
</TouchableOpacity>
</Right>
</Header>
)
}
}
export default SaveActivityHeader<file_sep>
import React, { Component } from 'react';
import {
View,
StyleSheet,
AsyncStorage
} from 'react-native';
import firebase, { storage } from 'firebase'
import { config } from '../../../Firebase/index'
if (!firebase.apps.length) {
firebase.initializeApp(config())
}
import { Container, Header, Content, Button, Text, Icon, Left, Right, Body, Item, Input } from 'native-base';
import { TextInput } from 'react-native-gesture-handler';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
text: {
username: 'r',
password: 'rg'
}
};
}
textChangedHandler = (igKey, value) => {
var text = { ...this.state.text }
text[igKey] = value
this.setState({ text: text })
}
checkUser(){
}
onSubmitHander=()=>{
var ids=[]
var users=[]
var bool = false
var userID=''
firebase.database().ref('Users/').once('value', function (snapshot) {
users = snapshot.val()
console.log(users)
}).then(() => {
Object.keys(users)
.map((igKey)=>{
if (this.state.text.username == users[igKey]['username'] && this.state.text.password == users[igKey]['password']) {
userID=igKey
bool = true
}
})
if (bool == true){
globalUserID = userID
AsyncStorage.setItem('userID', userID)
this.props.navigation.navigate('Tabs')
}
else{
alert("Wrong Username Password")
}
})
}
render() {
const placeholder = ['Username', 'Password']
const TextInputs = Object.keys(this.state.text)
.map((igKey, index) => {
return (
<Item style={styles.item}>
<Input style={styles.input} placeholder={placeholder[index]}
value={this.state.text.igKey}
onChangeText={value => this.textChangedHandler(igKey, value)} />
</Item>)
})
return (
<Container style={{ backgroundColor: "#262626" }}>
<Content>
<Button transparent style={{ position: 'absolute', left: 0, right: 0 }}
onPress={() => this.props.navigation.goBack()}>
<Icon name='arrow-back' style={{ fontSize: 35, color: 'white' }} />
</Button>
<View style={{ alignItems: 'center', marginTop: 60, marginRight: 30, marginLeft: 30 }}>
{TextInputs}
<Button
success
onPress={() => this.onSubmitHander()}
style={styles.button} block>
<Text>Login</Text>
</Button>
</View>
</Content>
</Container>
)
}
}
export default Login
const styles = StyleSheet.create({
Container: {
flex: 1,
backgroundColor: '#262626'
},
item: {
margin: 5,
backgroundColor: '#ADB8CA',
borderRadius: 10,
borderColor: 'transparent'
}, input: {
marginLeft: 5
}, button: {
borderRadius: 10,
marginTop: 30
}
})
<file_sep>
import React, { Component } from 'react';
import {
View,
StyleSheet,
PermissionsAndroid,
Platform,
Image
} from 'react-native';
import { Container, Header, Content, Button, Text, Icon, Left, Right, Body, Item, Input } from 'native-base';
import MapView, { Marker, Polyline, AnimatedRegion, PROVIDER_GOOGLE } from 'react-native-maps';
import Geolocation from '@react-native-community/geolocation';
import haversine from "haversine";
import { ScrollView } from 'react-native-gesture-handler';
import Geocoder from 'react-native-geocoding';
const LATITUDE_DELTA = 0.009;
const LONGITUDE_DELTA = 0.009;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
Geocoder.init("AIzaSyANqV6leq3SUf6UTIlNQiPEoNAMPU5yAgA")
class Record extends Component {
constructor(props) {
super(props);
this.state = {
latitude: LATITUDE,
longitude: LONGITUDE,
routeCoordinates: [],
distanceTravelled: 0,
prevLatLng: {},
coordinate: new AnimatedRegion({
latitude: LATITUDE,
longitude: LONGITUDE
}),
recording: false,
recordText: 'RECORD',
address: '',
};
}
async componentDidMount() {
Geolocation.watchPosition(position => {
const { routeCoordinates, distanceTravelled } = this.state;
const { latitude, longitude } = position.coords
const newCoordinate = {
latitude,
longitude
}
this.setState({
latitude,
longitude,
distanceTravelled:
distanceTravelled + this.calcDistance(newCoordinate),
prevLatLng: newCoordinate
})
this.isRecording(routeCoordinates, newCoordinate)
},
error => console.log(error),
{
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 1000,
distanceFilter: 10
});
}
// componentWillUnmount() {
// Geolocation.clearWatch(this.watchID)
// }
takeSnapshot() {
// 'takeSnapshot' takes a config object with the
// following options
const snapshot = this.map.takeSnapshot({
// width: 300, // optional, when omitted the view-width is used
// height: 300, // optional, when omitted the view-height is used
// region: {
// latitude: this.state.latitude,
// longitude: this.state.longitude,
// latitudeDelta: 0.0922,
// longitudeDelta: 0.0421,
// }, // iOS only, optional region to render
format: 'jpg', // image formats: 'png', 'jpg' (default: 'png')
quality: 0.8, // image quality: 0..1 (only relevant for jpg, default: 1)
result: 'file' // result types: 'file', 'base64' (default: 'file')
});
snapshot.then((uri) => {
this.setState({ mapSnapshot: uri });
});
}
calcDistance = newLatLng => {
const { prevLatLng } = this.state;
console.log( (this.state.distanceTravelled)+ haversine(newLatLng,prevLatLng,{unit: 'mile'}) || 0)
return haversine(prevLatLng, newLatLng) || 0;
};
isRecording = (routeCoordinates, newCoordinate) => {
if (this.state.recording) {
this.setState({ routeCoordinates: routeCoordinates.concat([newCoordinate]) })
}
}
async geoCode() {
try {
Geocoder.from(this.state.routeCoordinates[0].latitude, this.state.routeCoordinates[0].longitude)
.then(json => {
var addressComponent = json.results[0].address_components[0];
console.log(addressComponent)
this.setState({ address: addressComponent.long_name })
return
})
} catch (err) {
alert(err); // TypeError: failed to fetch
}
}
btnOnpress = () => {
var text = (this.state.recordText == 'RECORD') ? 'STOP' : 'RECORD'
if (text == 'RECORD') {
const snapshot = this.map.takeSnapshot({
// width: 300, // optional, when omitted the view-width is used
// height: 300, // optional, when omitted the view-height is used
// region: {
latitude: this.state.latitude,
longitude: this.state.longitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
// }, // iOS only, optional region to render
format: 'jpg', // image formats: 'png', 'jpg' (default: 'png')
quality: 0.8, // image quality: 0..1 (only relevant for jpg, default: 1)
result: 'file' // result types: 'file', 'base64' (default: 'file')
});
snapshot.then((uri) => {
this.setState({ mapSnapshot: uri });
Geocoder.from(this.state.routeCoordinates[0].latitude, this.state.routeCoordinates[0].longitude)
.then(json => {
var addressComponent = json.results[0].formatted_address;
console.log(addressComponent)
this.props.navigation.navigate('SaveActivity', { snapshoturi: uri, routeCoordinates: this.state.routeCoordinates, distance: this.state.distanceTravelled, address: addressComponent })
})
});
}
this.setState({ recordText: text, recording: !this.state.recording })
}
render() {
return (
<View style={styles.container}>
<MapView
provider={PROVIDER_GOOGLE} // remove if not using Google Maps
style={styles.map}
showsUserLocation
followsUserLocation
loadingEnabled
ref={map => { this.map = map }}
region={{
latitude: this.state.latitude,
longitude: this.state.longitude,
latitudeDelta: 0.009,
longitudeDelta: 0.009,
}}
>
<Polyline coordinates={this.state.routeCoordinates} strokeWidth={5} />
</MapView>
<Button
onPress={() => this.btnOnpress()}
style={styles.button}><Text>{this.state.recordText}</Text></Button>
{/* <Button
onPress={() => this.geoCode()}
style={{position:"absolute",bottom:0}}><Text>{this.state.recordText}</Text></Button> */}
</View>
)
}
}
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
button: {
position: 'absolute',
bottom: 500
}
});
export default Record<file_sep># Enduro-trail-app<file_sep>
import React, { Component } from 'react';
import {
View,
StatusBar,
AsyncStorage,
StyleSheet,
Image
} from 'react-native';
import HomeHeader from '../../Headers/HomeHeader'
import { Container, Header, Content, Card, CardItem, Thumbnail, Text, Button, Icon, Left, Body, Right } from 'native-base';
import firebase, { storage } from 'firebase'
import { config } from '../../Firebase/index'
import CardPosts from './CardPosts';
if (!firebase.apps.length) {
firebase.initializeApp(config())
}
class Home extends Component {
constructor(props) {
super(props);
this.state = {
url: '',
races: [
{ id: 1, race_title: "", race_type: "", race_category_open: "", race_address: "", race_no_of_stage: "", race_info: "", race_no_of_rider_limit: "" }
]
};
}
read() {
}
readUserData() {
firebase.database().ref('Trails/').once('value', function (snapshot) {
console.log(snapshot.val())
});
}
async componentDidMount() {
var userID = await AsyncStorage.getItem('userID')
if (userID != null) {
console.log(userID)
}
// const storage = firebase.storage()
// const ref = storage.ref('images/image_name');
// const url = await ref.getDownloadURL();
// console.log(url)
//this.readUserData()
}
render() {
return (
<CardPosts />
)
}
}
export default Home
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
box: {
width: 50,
height: 50,
backgroundColor: 'blue',
shadowColor: "#000",
elevation: 24,
}
})
|
a20b4196f99abafbe61280d9eede15f2b4397b04
|
[
"JavaScript",
"Markdown"
] | 9
|
JavaScript
|
yocyo357/Enduro-trail-app
|
8b8447da9e64cefe08993ebab00a86484381661c
|
0e1762910136bdeca346b4ca46689f863295d974
|
refs/heads/main
|
<file_sep>const express = require("express");
const fetch = require("node-fetch");
const app = express();
const port = process.env.PORT || 8000;
const url = "https://testapi.donatekart.com/api/campaign ";
// LIST OF CAMPAIGN WITH SORTED DATA
app.get("/", async (req, res) => {
try {
const data = await fetch(url);
const dataJson = await data.json();
const sorted = dataJson.sort((a, b) => b.totalAmount - a.totalAmount);
const ress = sorted.map((item) => {
const { title, totalAmount, backersCount, endDate } = item;
return {
title: title,
totalAmount: totalAmount,
backersCount: backersCount,
endDate: endDate
};
});
res.send(ress);
} catch (error) {
console.log(error);
}
});
// LIST OF ACTIVE CAMPAIGN
app.get("/active", async (req, res) => {
try {
const data = await fetch(url);
const dataJson = await data.json();
let today = new Date().toISOString().slice(0, 10);
let lastDate = "2021-05-24";
const activecamp = dataJson.filter(
(item) => item.endDate >= today && item.created > lastDate
);
res.send(activecamp);
} catch (error) {
console.log(error);
}
});
// LIST OF CLOSED CAMPAING
app.get("/closed", async (req, res) => {
try {
const data = await fetch(url);
const dataJson = await data.json();
let today = new Date().toISOString().slice(0, 10);
const closedCamp = dataJson.filter((item) => {
return item.endDate < today && item.procuredAmount > item.totalAmount;
});
` `;
res.send(closedCamp);
} catch (error) {
console.log(error);
}
});
app.listen(port, () => {
console.log(`connetion is is live from ${port}`);
});
<file_sep># donatekar_backend
Created with CodeSandbox
|
14c1c3186a25efe769dbbf33b9b5f0b53a9386f8
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
amityadav06/donatekar_backend
|
250c96fc939a26ac9f607dbeb6f6e1ec02d21f26
|
c6cd1f7c2a5dd74178bf0b8d434bc4d8140b657c
|
refs/heads/master
|
<repo_name>cgvarela/actor-ios-old<file_sep>/ActorClient/ActorClient/CocoaLogProvider.swift
//
// CocoaLogProvider.swift
// ActorClient
//
// Created by <NAME> on 15.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
@objc class CocoaLogProvider : NSObject, AMLogProvider {
func w(tag: String!, withMessage message: String!) {
NSLog("⚠️ %@: %@", tag, message);
}
func v(tag: String!, withError throwable: JavaLangThrowable!) {
NSLog("🔴 %@: %@", tag, throwable);
}
func v(tag: String!, withMessage message: String!) {
NSLog("[V] %@: %@", tag, message);
}
func d(tag: String!, withMessage message: String!) {
NSLog("[D] %@: %@", tag, message);
}
}<file_sep>/ActorClient/ActorClient/BubbleCell.swift
//
// BubbleView.swift
// ActorClient
//
// Created by <NAME> on 11.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
import UIKit;
class BubbleCell: UITableViewCell {
class func measureHeight(message: AMMessage) -> CGFloat {
var content = message.getContent()!;
if (content is AMTextContent){
return BubbleTextCell.measureTextHeight(message)
} else if (content is AMPhotoContent) {
return BubbleMediaCell.measureMediaHeight(message)
} else if (content is AMVideoContent) {
return BubbleMediaCell.measureMediaHeight(message)
} else if (content is AMServiceContent){
return BubbleServiceCell.measureServiceHeight(message);
} else {
return BubbleUnsupportedCell.measureUnsupportedHeight(message)
}
}
let bubblePadding:CGFloat = 6;
var bindedMessage: AMMessage? = nil
init(reuseId: String){
super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseId);
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func performBind(message: AMMessage) {
var reuse = false
if (bindedMessage != nil && bindedMessage?.getRid() == message.getRid()) {
reuse = true
}
bindedMessage = message
bind(message, reuse: reuse)
}
func bind(message: AMMessage, reuse: Bool){
fatalError("bind(message:) has not been implemented")
}
func formatDate(date:Int64) -> String {
var dateFormatter = NSDateFormatter();
dateFormatter.dateFormat = "HH:mm";
return dateFormatter.stringFromDate(NSDate(timeIntervalSince1970: NSTimeInterval(Double(date) / 1000.0)));
}
}
<file_sep>/ActorClient/ActorClient/UIButtonTable.swift
//
// UIButtonTable.swift
// ActorClient
//
// Created by <NAME> on 22.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
class UIButtonTable : UIButton {
override var highlighted: Bool {
get {
return super.highlighted
}
set (val) {
if (val) {
backgroundColor = Resources.SelectorColor
} else {
backgroundColor = UIColor.clearColor()
}
super.highlighted = val
}
}
}<file_sep>/ActorClient/ActorClient/BubbleMediaCell.swift
//
// BubbleMediaCell.swift
// ActorClient
//
// Created by <NAME> on 17.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
class BubbleMediaCell : BubbleCell {
private class func measureMedia(w: Int, h: Int) -> CGSize {
var screenScale = UIScreen.mainScreen().scale;
var scaleW = 240 / CGFloat(w)
var scaleH = 340 / CGFloat(h)
var scale = min(scaleW, scaleH)
return CGSize(width: scale * CGFloat(w), height: scale * CGFloat(h))
}
class func measureMediaHeight(message: AMMessage) -> CGFloat {
var content = message.getContent() as! AMDocumentContent;
if (message.getContent() is AMPhotoContent){
var photo = message.getContent() as! AMPhotoContent;
return measureMedia(Int(photo.getW()), h: Int(photo.getH())).height + 8;
}
fatalError("???")
}
let bubble = UIImageView();
let preview = UIImageView();
let circullarNode = CircullarNode()
var isOut:Bool = false;
var contentWidth = 0
var contentHeight = 0
var thumb : AMFastThumb? = nil
var contentViewSize: CGSize? = nil
var thumbLoaded = false
var contentLoaded = false
var bindedDownloadFile: jlong? = nil
var bindedDownloadCallback: CocoaDownloadCallback? = nil
var bindedUploadFile: jlong? = nil
var bindedUploadCallback: CocoaUploadCallback? = nil
var generation = 0;
override init(reuseId: String) {
super.init(reuseId: reuseId)
bubble.image = UIImage(named: "conv_media_bg")
contentView.addSubview(bubble)
contentView.addSubview(preview)
contentView.addSubview(circullarNode.view)
self.backgroundColor = UIColor.clearColor();
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func bind(message: AMMessage, reuse: Bool) {
if (!reuse) {
self.isOut = message.getSenderId() == MSG.myUid()
if (message.getContent() is AMPhotoContent) {
var photo = message.getContent() as! AMPhotoContent;
thumb = photo.getFastThumb()
contentWidth = Int(photo.getW())
contentHeight = Int(photo.getH())
} else if (message.getContent() is AMVideoContent) {
var video = message.getContent() as! AMVideoContent;
thumb = video.getFastThumb()
contentWidth = Int(video.getW())
contentHeight = Int(video.getH())
} else {
fatalError("Unsupported content")
}
preview.image = nil
thumbLoaded = false
contentLoaded = false
contentViewSize = BubbleMediaCell.measureMedia(contentWidth, h: contentHeight)
circullarNode.setProgress(0, animated: false)
UIView.animateWithDuration(0, animations: { () -> Void in
self.circullarNode.alpha = 0
self.preview.alpha = 0
})
}
var document = message.getContent() as! AMDocumentContent;
var rebindRequired = !reuse;
if (!rebindRequired) {
// Force rebind if source is changed from local to remote
if (document.getSource() is AMFileRemoteSource) {
// TODO: check rebind need
}
}
if (rebindRequired) {
// Increase cell generation for any new bind
generation++;
clearBindings()
var selfGeneration = generation;
if (document.getSource() is AMFileRemoteSource) {
var fileReference = (document.getSource() as! AMFileRemoteSource).getFileReference();
bindedDownloadFile = fileReference.getFileId()
bindedDownloadCallback = CocoaDownloadCallback(notDownloaded: { () -> () in
self.loadThumb(selfGeneration)
self.hideProgress(selfGeneration)
}, onDownloading: { (progress) -> () in
self.loadThumb(selfGeneration)
self.showProgress(progress, selfGeneration: selfGeneration)
}, onDownloaded: { (reference) -> () in
self.loadReference(reference, selfGeneration: selfGeneration)
self.hideProgress(selfGeneration)
})
// TODO: Better logic for autodownload
MSG.bindRawFileWith(fileReference, withAutoStart: true, withCallback: bindedDownloadCallback)
} else if (document.getSource() is AMFileLocalSource) {
var fileReference = (document.getSource() as! AMFileLocalSource).getFileDescriptor();
bindedUploadFile = message.getRid();
bindedUploadCallback = CocoaUploadCallback(notUploaded: { () -> () in
self.loadReference(fileReference, selfGeneration: selfGeneration)
self.hideProgress(selfGeneration)
}, onUploading: { (progress) -> () in
self.loadReference(fileReference, selfGeneration: selfGeneration)
self.showProgress(progress, selfGeneration: selfGeneration)
}, onUploadedClosure: { () -> () in
self.loadReference(fileReference, selfGeneration: selfGeneration)
self.hideProgress(selfGeneration)
});
MSG.bindRawUploadFile(message.getRid(), withCallback: bindedUploadCallback)
} else {
fatalError("Unsupported file source")
}
}
}
func loadThumb(selfGeneration: Int) {
if (selfGeneration != generation) {
return
}
if (thumbLoaded) {
return
}
thumbLoaded = true
if (thumb != nil) {
var loadedThumb = UIImage(data: self.thumb!.getImage().toNSData()!)?.roundCorners(contentViewSize!.width - 2, h: contentViewSize!.height - 2, roundSize: 14)
runOnUiThread(selfGeneration,closure: { ()->() in
self.setPreviewImage(loadedThumb!, fast: true)
});
}
}
func loadReference(reference: String, selfGeneration: Int) {
if (selfGeneration != generation) {
return
}
if (contentLoaded) {
return
}
contentLoaded = true
var loadedContent = UIImage(contentsOfFile: CocoaFiles.pathFromDescriptor(reference))?.roundCorners(contentViewSize!.width - 2, h: contentViewSize!.height - 2, roundSize: 14)
if (loadedContent == nil) {
return
}
runOnUiThread(selfGeneration, closure: { () -> () in
self.setPreviewImage(loadedContent!, fast: false)
})
}
func setPreviewImage(img: UIImage, fast: Bool){
if ((fast && self.preview.image == nil) || !fast) {
self.preview.image = img;
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.preview.alpha = 1
})
}
}
func hideProgress(selfGeneration: Int) {
self.runOnUiThread(selfGeneration, closure: { () -> () in
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.circullarNode.alpha = 0
})
})
}
func showProgress(value: Double, selfGeneration: Int) {
self.circullarNode.postProgress(value, animated: true)
self.runOnUiThread(selfGeneration, closure: { () -> () in
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.circullarNode.alpha = 1
})
})
}
func clearBindings() {
if (bindedDownloadFile != nil && bindedDownloadCallback != nil) {
MSG.unbindRawFile(bindedDownloadFile!, withAutoCancel: false, withCallback: bindedDownloadCallback!)
bindedDownloadFile = nil
bindedDownloadCallback = nil
}
if (bindedUploadFile != nil && bindedUploadCallback != nil) {
MSG.unbindRawUploadFile(bindedUploadFile!, withCallback: bindedUploadCallback!)
bindedUploadFile = nil
bindedUploadCallback = nil
}
}
func runOnUiThread(selfGeneration: Int, closure: ()->()){
dispatch_async(dispatch_get_main_queue(), {
if (selfGeneration != self.generation) {
return
}
closure()
})
}
override func layoutSubviews() {
super.layoutSubviews()
let padding = CGFloat(10)
var width = contentView.frame.width
var height = contentView.frame.height
var bubbleHeight = height - 8
var bubbleWidth = bubbleHeight * CGFloat(contentWidth) / CGFloat(contentHeight)
if (self.isOut) {
self.bubble.frame = CGRectMake(width - bubbleWidth - padding, 4, bubbleWidth, bubbleHeight)
} else {
self.bubble.frame = CGRectMake(padding, 4, bubbleWidth, bubbleHeight)
}
preview.frame = CGRectMake(bubble.frame.origin.x + 1, bubble.frame.origin.y + 1, bubble.frame.width - 2, bubble.frame.height - 2);
circullarNode.frame = CGRectMake(
preview.frame.origin.x + preview.frame.width/2 - 32,
preview.frame.origin.y + preview.frame.height/2 - 32,
64, 64)
}
}<file_sep>/ActorClient/ActorClient/BubbleTextCell.swift
//
// BubbleTextCell.swift
// ActorClient
//
// Created by <NAME> on 11.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
import UIKit
// Using padding for proper date align.
// One space + 16 non-breakable spases for out messages
private let stringOutPadding = " \u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}";
// One space + 6 non-breakable spaces for in messages
private let stringInPadding = " \u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}\u{00A0}";
//private let bubbleFont = UIFont(name: "Roboto", size: 16)!
private let bubbleFont = UIFont(name: "HelveticaNeue", size: 16)!
private let maxTextWidth = 240
private func measureText(message: String, isOut: Bool) -> CGRect {
var style = NSMutableParagraphStyle();
style.lineBreakMode = NSLineBreakMode.ByWordWrapping;
var text = (message + (isOut ? stringOutPadding : stringInPadding)) as NSString;
var size = CGSize(width: maxTextWidth, height: 0);
var rect = text.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: bubbleFont, NSParagraphStyleAttributeName: style], context: nil);
return CGRectMake(0, 0, round(rect.width), round(rect.height))
}
class BubbleTextCell : BubbleCell {
class func measureTextHeight(message: AMMessage) -> CGFloat {
var content = message.getContent() as! AMTextContent!;
return round(measureText(content.getText(), message.getSenderId() == MSG.myUid()).height) + 14
}
let textPaddingStart:CGFloat = 10.0;
let textPaddingEnd:CGFloat = 8.0;
let datePaddingOut:CGFloat = 66.0;
let datePaddingIn:CGFloat = 20.0;
// let dateColorOut = UIColor(red: 45/255.0, green: 163/255.0, blue: 47/255.0, alpha: 1.0);
let dateColorOut = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.27);
let dateColorIn = UIColor(red: 151/255.0, green: 151/255.0, blue: 151/255.0, alpha: 1.0);
let messageTextColor = UIColor(red: 20/255.0, green: 22/255.0, blue: 23/255.0, alpha: 1.0);
let statusActive = UIColor(red: 52/255.0, green: 151/255.0, blue: 249/255.0, alpha: 1.0);
let statusPassive = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.27);
let bubble = UIImageView();
let messageText = UILabel();
let dateText = UILabel();
let statusView = UIImageView();
var isOut:Bool = false;
var messageState: UInt = AMMessageState.UNKNOWN.rawValue;
var needRelayout = true
override init(reuseId: String) {
super.init(reuseId: reuseId)
messageText.font = bubbleFont;
messageText.lineBreakMode = .ByWordWrapping;
messageText.numberOfLines = 0;
messageText.textColor = messageTextColor;
dateText.font = UIFont(name: "HelveticaNeue-Italic", size: 11);
dateText.lineBreakMode = .ByClipping;
dateText.numberOfLines = 1;
dateText.contentMode = UIViewContentMode.TopLeft
dateText.textAlignment = NSTextAlignment.Right;
statusView.contentMode = UIViewContentMode.Center;
contentView.addSubview(bubble);
contentView.addSubview(messageText);
contentView.addSubview(dateText);
contentView.addSubview(statusView);
self.backgroundColor = UIColor.clearColor();
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func bind(message: AMMessage, reuse: Bool) {
if (!reuse) {
needRelayout = true
messageText.text = (message.getContent() as! AMTextContent).getText();
isOut = message.getSenderId() == MSG.myUid();
if (isOut) {
bubble.image = UIImage(named: "BubbleOutgoingFull");
} else {
bubble.image = UIImage(named: "BubbleIncomingFull");
}
}
// Always update date and state
dateText.text = formatDate(message.getDate());
messageState = UInt(message.getMessageState().ordinal());
}
override func layoutSubviews() {
super.layoutSubviews();
UIView.performWithoutAnimation { () -> Void in
var realRect = measureText(self.messageText.text!, self.isOut);
self.messageText.frame = realRect;
self.messageText.sizeToFit()
var w = round(realRect.width);
var h = round(realRect.height);
if (self.isOut) {
self.messageText.frame.origin = CGPoint(x: self.frame.width - w - self.textPaddingEnd - self.bubblePadding, y: 8);
self.dateText.textColor = self.dateColorOut;
} else {
self.messageText.frame.origin = CGPoint(x: self.bubblePadding + self.textPaddingStart, y: 8)
self.dateText.textColor = self.dateColorIn;
}
let x = round(self.messageText.frame.origin.x);
let y = round(self.messageText.frame.origin.y);
if (self.isOut) {
self.bubble.frame = CGRectMake(x - self.textPaddingEnd, y - 4, w + self.textPaddingStart+self.textPaddingEnd, h + 8);
self.dateText.frame = CGRectMake(x + w - 68, self.bubble.frame.maxY - 24, 46, 26);
} else {
self.bubble.frame = CGRectMake(x - self.textPaddingStart, y - 4, w + self.textPaddingStart+self.textPaddingEnd + self.datePaddingIn, h + 8);
self.dateText.frame = CGRectMake(x + w - 32, self.bubble.frame.maxY - 24, 46, 26);
}
if (self.isOut) {
self.statusView.frame = CGRectMake(x + w - 22, y + h - 20, 20, 26);
self.statusView.hidden = false;
switch(self.messageState) {
case AMMessageState.UNKNOWN.rawValue:
self.statusView.image = Resources.iconClock;
self.statusView.tintColor = self.statusPassive;
case AMMessageState.PENDING.rawValue:
self.statusView.image = Resources.iconClock;
self.statusView.tintColor = self.statusPassive;
break;
case AMMessageState.SENT.rawValue:
self.statusView.image = Resources.iconCheck1;
self.statusView.tintColor = self.statusPassive;
break;
case AMMessageState.RECEIVED.rawValue:
self.statusView.image = Resources.iconCheck2;
self.statusView.tintColor = self.statusPassive;
break;
case AMMessageState.READ.rawValue:
self.statusView.image = Resources.iconCheck2;
self.statusView.tintColor = self.statusActive;
break;
default:
self.statusView.image = Resources.iconClock;
self.statusView.tintColor = self.statusPassive;
break;
}
} else {
self.statusView.hidden = true;
}
}
}
}<file_sep>/ActorClient/ActorClient/MainTabController.swift
//
// MainTabController.swift
// ActorClient
//
// Created by <NAME> on 10.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
import UIKit
class MainTabController : UITabBarController, UITabBarDelegate, ABActionShitDelegate {
var centerButton:UIButton? = nil;
var isInited = false;
required init(coder aDecoder: NSCoder) {
fatalError("Not implemented")
}
init(){
super.init(nibName: nil, bundle: nil);
initControllers()
}
func initControllers() {
// centerButton = UIButton(frame: CGRect(x: 0, y: 0, width: 66, height: 58));
// centerButton!.setBackgroundImage(UIImage(named: "ic_round_button_red"), forState: UIControlState.Normal);
// centerButton!.setImage(UIImage(named: "ic_add_white_24"), forState: UIControlState.Normal);
// centerButton!.imageEdgeInsets = UIEdgeInsetsMake(4, 0, -4, 0);
// centerButton!.addTarget(self, action: "centerButtonTap", forControlEvents: UIControlEvents.TouchUpInside)
// self.view.addSubview(centerButton!);
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
}
func centerButtonTap() {
var actionShit = ABActionShit()
actionShit.buttonTitles = ["Add Contact", "Create group", "Write to..."];
actionShit.delegate = self
actionShit.showWithCompletion(nil)
}
func actionShit(actionShit: ABActionShit!, clickedButtonAtIndex buttonIndex: Int) {
if (buttonIndex == 0) {
doAddContact()
} else if (buttonIndex == 1) {
navigationController?.pushViewController(GroupMembersController(), animated: true)
} else if (buttonIndex == 2) {
doCompose()
}
}
func doCompose() {
navigationController?.pushViewController(ComposeController(), animated: true)
}
func doAddContact() {
var alertView = UIAlertView(title: "Add Contact", message: "Please, specify phone number", delegate: nil, cancelButtonTitle: "Cancel")
alertView.alertViewStyle = UIAlertViewStyle.PlainTextInput
alertView.show()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if (!isInited) {
if (MSG.isLoggedIn()) {
isInited = true
viewControllers = [ContactsViewController(),
DialogsViewController(),
SettingsViewController()];
selectedIndex = 1;
applyTitle(1);
}
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// centerButton!.frame = CGRectMake(view.center.x-31, view.frame.height-58, 66, 58)
}
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!) {
var item = (tabBar.items! as NSArray).indexOfObject(item);
applyTitle(item);
}
func applyTitle(item: Int){
switch(item){
case 0:
navigationItem.title = "People";
navigationItem.leftBarButtonItem = nil;
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "doAddContact")
break;
case 1:
navigationItem.title = "Chats";
if ((self.viewControllers![1] as! DialogsViewController).isTableEditing()) {
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "editDialogs");
navigationItem.rightBarButtonItem = nil
} else {
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Edit, target: self, action: "editDialogs");
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "doCompose")
}
case 2:
navigationItem.title = "You";
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Edit, target: self, action: "editProfile");
navigationItem.rightBarButtonItem = nil;
break;
default:
navigationItem.leftBarButtonItem = nil;
navigationItem.rightBarButtonItem = nil;
navigationItem.title = "";
break;
}
}
func editDialogs() {
(self.viewControllers![1] as! DialogsViewController).toggleEdit();
applyTitle(1)
}
func editProfile() {
}
}<file_sep>/ActorClient/ActorClient/ContactCell.swift
//
// ContactCell.swift
// ActorClient
//
// Created by <NAME> on 12.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
import UIKit
class ContactCell : UITableViewCell {
let avatarView = AvatarView(frameSize: 40);
let shortNameView = UILabel();
let titleView = UILabel();
let separatorView = TableViewSeparator(color: Resources.SeparatorColor)
init(reuseIdentifier:String) {
super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier)
titleView.font = UIFont(name: "HelveticaNeue", size: 18);
shortNameView.font = UIFont(name: "HelveticaNeue-Bold", size: 18);
shortNameView.textAlignment = NSTextAlignment.Center
self.contentView.addSubview(avatarView);
self.contentView.addSubview(shortNameView);
self.contentView.addSubview(titleView);
self.contentView.addSubview(separatorView);
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bindContact(contact: AMContact, shortValue: String?, isLast: Bool) {
avatarView.bind(contact.getName(), id: contact.getUid(), avatar: contact.getAvatar());
titleView.text = contact.getName();
if (shortValue == nil){
shortNameView.hidden = true;
} else {
shortNameView.text = shortValue!;
shortNameView.hidden = false;
}
separatorView.hidden = isLast
}
override func layoutSubviews() {
super.layoutSubviews()
var width = self.contentView.frame.width;
shortNameView.frame = CGRectMake(0, 8, 30, 40);
avatarView.frame = CGRectMake(30, 8, 40, 40);
titleView.frame = CGRectMake(80, 8, width - 80 - 14, 40);
separatorView.frame = CGRectMake(80, 55.5, width - 80, 0.5);
}
}<file_sep>/ActorClient/ActorClient/UDPreferencesStorage.swift
//
// UDPreferencesStorage.swift
// ActorClient
//
// Created by <NAME> on 15.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
class UDPreferencesStorage: NSObject, DKPreferencesStorage {
let prefs = NSUserDefaults.standardUserDefaults()
func putLong(key: String!, withValue v: jlong) {
prefs.setObject(NSNumber(longLong: v), forKey: key)
prefs.synchronize()
}
func getLong(key: String!, withDefault def: jlong) -> jlong {
var val: AnyObject? = prefs.objectForKey(key)
if (val == nil || !(val is NSNumber)) {
return def;
} else {
return (val as! NSNumber).longLongValue
}
}
func putInt(key: String!, withValue v: jint) {
prefs.setInteger(Int(v), forKey: key)
prefs.synchronize()
}
func getInt(key: String!, withDefault def: jint) -> jint {
var val: AnyObject? = prefs.objectForKey(key)
if (val == nil || !(val is NSNumber)) {
return def;
} else {
return (val as! NSNumber).intValue
}
}
func putBool(key: String!, withValue v: Bool) {
prefs.setBool(v, forKey: key)
prefs.synchronize()
}
func getBool(key: String!, withDefault def: Bool) -> Bool {
var val: AnyObject? = prefs.objectForKey(key);
if (val == nil || (!(val is Bool))) {
return def;
} else {
return val as! Bool;
}
}
func putBytes(key: String!, withValue v: IOSByteArray!) {
prefs.setObject(v.toNSData(), forKey: key)
prefs.synchronize()
}
func getBytes(key: String!) -> IOSByteArray! {
var val: AnyObject? = prefs.objectForKey(key);
if (val == nil || !(val is NSData)){
return nil
} else {
return (val as! NSData).toJavaBytes()
}
}
func putString(key: String!, withValue v: String!) {
prefs.setObject(v, forKey: key)
prefs.synchronize()
}
func getString(key: String!) -> String! {
var val: AnyObject? = prefs.objectForKey(key);
if (val == nil || !(val is String)) {
return nil
} else {
return val as! String
}
}
}<file_sep>/ActorClient/ActorClient/CocoaMainThreadProvider.swift
//
// CocoaMainThreadProvider.swift
// ActorClient
//
// Created by <NAME> on 15.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
class CocoaMainThreadProvider:NSObject, AMMainThreadProvider {
func runOnUiThread(runnable: JavaLangRunnable!) {
dispatch_async(dispatch_get_main_queue(), {
runnable.run()
});
}
func isMainThread() -> Bool {
return NSThread.currentThread().isMainThread
}
func isSingleThread() -> Bool {
return false
}
}<file_sep>/ActorClient/ActorClient/CocoaExecution.swift
//
// CocoaExecution.swift
// ActorClient
//
// Created by <NAME> on 22.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
extension UIViewController {
func execute(command: AMCommand) {
MBProgressHUD.showHUDAddedTo(UIApplication.sharedApplication().keyWindow, animated: true)
command.startWithAMCommandCallback(CocoaCallback(result: { (val:Any?) -> () in
MBProgressHUD.hideAllHUDsForView(UIApplication.sharedApplication().keyWindow, animated: true)
}, error: { (val) -> () in
MBProgressHUD.hideAllHUDsForView(UIApplication.sharedApplication().keyWindow, animated: true)
}))
}
}<file_sep>/ActorClient/ActorClient/SettingsViewController.swift
//
// SettingsViewController.swift
// ActorClient
//
// Created by <NAME> on 12.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let binder: Binder = Binder();
var user: AMUserVM? = nil
@IBOutlet weak var tableView: UITableView!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
initCommon();
}
init() {
super.init(nibName: "SettingsViewController", bundle: nil)
initCommon();
}
func initCommon(){
var icon = UIImage(named: "ic_settings_blue_24")!;
tabBarItem = UITabBarItem(title: nil,
image: icon.tintImage(Resources.BarTintUnselectedColor)
.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal),
selectedImage: icon);
tabBarItem.imageInsets=UIEdgeInsetsMake(6, 0, -6, 0);
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = Resources.BackyardColor
tableView.registerNib(UINib(nibName: "AvatarCell", bundle: nil), forCellReuseIdentifier: "cell_avatar")
tableView.registerNib(UINib(nibName: "ContactRecordCell", bundle: nil), forCellReuseIdentifier: "cell_contact")
tableView.registerNib(UINib(nibName: "MenuItemCell", bundle: nil), forCellReuseIdentifier: "cell_menu")
tableView.delegate = self
tableView.dataSource = self
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
user = MSG.getUsers().getWithLong(jlong(MSG.myUid())) as! AMUserVM;
binder.bind(user!.getAvatar(), closure: { (avatar: AMAvatar?) -> () in
self.tableView.reloadData()
})
binder.bind(user!.getName(), closure: { (name: NSString?) -> () in
self.tableView.reloadData()
})
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 0) {
return 1
} else if (section == 1) {
var phones = user!.getPhones().get() as! JavaUtilArrayList;
return Int(phones.size())
} else if (section == 2) {
return 4
}
fatalError("??")
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (indexPath.section == 0) {
// Avatar
return 160
} else if (indexPath.section == 1) {
// Contacts
return 66
} else if (indexPath.section == 2) {
return 44
}
fatalError("??")
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.section == 0) {
var res = tableView.dequeueReusableCellWithIdentifier("cell_avatar") as! AvatarCell;
res.bind(user!)
return res
} else if (indexPath.section == 1) {
var res = tableView.dequeueReusableCellWithIdentifier("cell_contact") as! ContactRecordCell;
var phones = user!.getPhones().get() as! JavaUtilArrayList;
var phone = phones.getWithInt(jint(indexPath.row)) as! AMUserPhone;
res.bind(phone)
return res
} else if (indexPath.section == 2) {
var res = tableView.dequeueReusableCellWithIdentifier("cell_menu") as! MenuItemCell;
res.setData("ic_profile_help",title: "Help")
return res
}
fatalError("??")
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if (section == 0){
return 0
} else {
return 48
}
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if (section == 0) {
return nil
} else {
var res = UIView(frame: CGRectMake(0, 0, 320, 36))
var bg = UIView(frame: CGRectMake(0, 12, 320, 36))
bg.backgroundColor = UIColor.whiteColor()
res.addSubview(bg)
var shadow = UIImageView(frame: CGRectMake(0, 8, 320, 4))
shadow.contentMode = UIViewContentMode.ScaleToFill
shadow.image = UIImage(named: "CardTop2")
res.addSubview(shadow)
var title = UILabel()
title.text = section == 1 ? "Contacts" : "Help";
title.textColor = Resources.TintColor
title.font = UIFont(name: "HelveticaNeue-Medium", size: 14)
title.frame = CGRectMake(60, 12, 320 - 60, 36)
res.addSubview(title)
return res
}
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
var res = UIView(frame: CGRectMake(0, 0, 320, 10))
res.backgroundColor = Resources.BackyardColor
var shadow = UIImageView(image: UIImage(named: "CardBottom2"))
shadow.contentMode = UIViewContentMode.ScaleToFill
shadow.frame = CGRectMake(0, 0, 320, 4)
res.addSubview(shadow)
return res
}
}<file_sep>/ActorClient/ActorClient/Binder.swift
//
// Binder.swift
// ActorClient
//
// Created by <NAME> on 12.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
class Binder {
var bindings : [BindHolder] = [];
func bind<T1,T2,T3>(valueModel1:AMValueModel, valueModel2:AMValueModel, valueModel3:AMValueModel, closure: (value1:T1?, value2:T2?, value3:T3?) -> ()) {
var listener1 = BindListener { (_value1) -> () in
closure(value1: _value1 as? T1, value2: valueModel2.get() as? T2, value3: valueModel2.get() as? T3)
};
var listener2 = BindListener { (_value2) -> () in
closure(value1: valueModel1.get() as? T1, value2: _value2 as? T2, value3: valueModel2.get() as? T3)
};
var listener3 = BindListener { (_value3) -> () in
closure(value1: valueModel1.get() as? T1, value2: valueModel2.get() as? T2, value3: _value3 as? T3)
};
bindings.append(BindHolder(valueModel: valueModel1, listener: listener1))
bindings.append(BindHolder(valueModel: valueModel2, listener: listener2))
bindings.append(BindHolder(valueModel: valueModel3, listener: listener3))
valueModel1.subscribeWithAMValueChangedListener(listener1, withBoolean: false)
valueModel2.subscribeWithAMValueChangedListener(listener2, withBoolean: false)
valueModel3.subscribeWithAMValueChangedListener(listener3, withBoolean: false)
closure(value1: valueModel1.get() as? T1, value2: valueModel2.get() as? T2, value3: valueModel3.get() as? T3)
}
func bind<T1,T2>(valueModel1:AMValueModel, valueModel2:AMValueModel, closure: (value1:T1?, value2:T2?) -> ()) {
var listener1 = BindListener { (_value1) -> () in
closure(value1: _value1 as? T1, value2: valueModel2.get() as? T2)
};
var listener2 = BindListener { (_value2) -> () in
closure(value1: valueModel1.get() as? T1, value2: _value2 as? T2)
};
bindings.append(BindHolder(valueModel: valueModel1, listener: listener1))
bindings.append(BindHolder(valueModel: valueModel2, listener: listener2))
valueModel1.subscribeWithAMValueChangedListener(listener1, withBoolean: false)
valueModel2.subscribeWithAMValueChangedListener(listener2, withBoolean: false)
closure(value1: valueModel1.get() as? T1, value2: valueModel2.get() as? T2)
}
func bind<T>(value:AMValueModel, closure: (value: T?)->()) {
var listener = BindListener { (value2) -> () in
closure(value: value2 as? T);
};
var holder = BindHolder(valueModel: value, listener: listener);
bindings.append(holder);
value.subscribeWithAMValueChangedListener(listener);
}
func unbindAll() {
for holder in bindings {
holder.valueModel.unsubscribeWithAMValueChangedListener(holder.listener);
}
bindings.removeAll(keepCapacity: true);
}
}
class BindListener: NSObject, JavaObject, AMValueChangedListener {
var closure: (value: AnyObject?)->();
init(closure: (value: AnyObject?)->()){
self.closure = closure;
}
@objc func onChangedWithId(val: AnyObject!, withAMValueModel valueModel: AMValueModel!) {
closure(value: val);
}
}
class BindHolder {
var listener: BindListener;
var valueModel: AMValueModel;
init(valueModel: AMValueModel, listener: BindListener) {
self.valueModel = valueModel;
self.listener = listener;
}
}<file_sep>/ActorClient/ActorClient/ContactRecordCell.swift
//
// ContactRecordCell.swift
// ActorClient
//
// Created by <NAME> on 17.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import UIKit
class ContactRecordCell: UITableViewCell {
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var value: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func bind(phone: AMUserPhone) {
icon.image = UIImage(named: "ic_profile_phone")?.tintImage(Resources.TintColor)
title.text = phone.getTitle();
title.textColor = Resources.TintColor
value.text = "+\(phone.getPhone())";
}
}
<file_sep>/ActorClient/ActorClient/ProfileController.swift
//
// ProfileController.swift
// ActorClient
//
// Created by <NAME> on 22.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import UIKit
class ProfileController: UIViewController, UIAlertViewDelegate {
let uid: Int
var userVm: AMUserVM?
var binder = Binder()
@IBOutlet weak var contentScroll: UIScrollView!
@IBOutlet weak var avatarView: AvatarView!
@IBOutlet weak var nameView: UILabel!
@IBOutlet weak var settingsLabel: UILabel!
@IBOutlet weak var notificationsIcon: UIImageView!
@IBOutlet weak var onlineLabel: UILabel!
@IBOutlet weak var notificationsSwitch: UISwitch!
@IBOutlet weak var addToContactButton: UIButtonTable!
@IBOutlet weak var writeMessageButton: UIButtonTable!
@IBOutlet weak var footerView: UIView!
@IBOutlet weak var contactsView: UIView!
init(uid:Int) {
self.uid = uid
super.init(nibName: "ProfileController", bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Navigation bar
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Edit, target: self, action: "editName")
// Name
self.nameView.textColor = Resources.TextPrimaryColor
self.onlineLabel.textColor = Resources.TextSecondaryColor
// Actions
self.addToContactButton.setTitleColor(Resources.TintColor, forState: UIControlState.Normal)
self.addToContactButton.setImage(UIImage(named: "ic_profile_notification")?.tintImage(Resources.SecondaryTint), forState: UIControlState.Normal)
self.addToContactButton.addTarget(self, action: "addContact", forControlEvents: UIControlEvents.TouchUpInside)
self.writeMessageButton.setTitleColor(Resources.TintColor, forState: UIControlState.Normal)
self.writeMessageButton.setImage(UIImage(named: "ic_profile_notification")?.tintImage(Resources.SecondaryTint), forState: UIControlState.Normal)
self.writeMessageButton.addTarget(self, action: "compose", forControlEvents: UIControlEvents.TouchUpInside)
// Settings
self.settingsLabel.textColor = Resources.TintColor
self.notificationsIcon.image = UIImage(named: "ic_profile_notification")?.tintImage(Resources.SecondaryTint)
self.notificationsSwitch.onTintColor = Resources.TintColor
self.userVm = MSG.getUsers().getWithLong(jlong(uid)) as! AMUserVM
binder.bind(userVm!.getName()!, closure: { (value: NSString?) -> () in
self.navigationItem.title = value! as String
self.nameView.text = value! as String
})
binder.bind(userVm!.getAvatar(), closure: { (value: AMAvatar?)-> () in
self.avatarView.bind(self.userVm!.getName().get() as! String, id: jint(self.uid), avatar: value)
})
binder.bind(userVm!.isContact(), closure: { (value:JavaLangBoolean?) -> () in
if (value!.booleanValue()) {
self.addToContactButton.setTitle("Remove from Contacts", forState: UIControlState.Normal)
} else {
self.addToContactButton.setTitle("Add to Contacts", forState: UIControlState.Normal)
}
})
binder.bind(userVm!.getPresence(), closure: { (presence: AMUserPresence?) -> () in
var stateText = MSG.getFormatter().formatPresenceWithAMUserPresence(presence, withAMSexEnum: self.userVm!.getSex())
self.onlineLabel.text = stateText;
var state = UInt(presence!.getState().ordinal())
if (state == AMUserPresence_State.ONLINE.rawValue) {
self.onlineLabel.textColor = Resources.TintColor
} else {
self.onlineLabel.textColor = Resources.TextSecondaryColor
}
})
binder.bind(userVm!.getPhones(), closure: { (value:JavaUtilArrayList?) -> () in
self.updateLayout(value!);
})
contentScroll.contentSize = CGSize(width: 0, height: contentScroll.frame.height + 1.0)
}
func updateLayout(phones: JavaUtilArrayList) {
while(contactsView.subviews.count > 0){
(contactsView.subviews[0] as! UIView).removeFromSuperview()
}
for i in 0..<phones.size() {
var phone = phones.getWithInt(i) as! AMUserPhone;
if (i == 0) {
var iconView = UIImageView(frame: CGRectMake(0, CGFloat(i*48), 66, 48))
iconView.image = UIImage(named: "ic_profile_phone")?.tintImage(Resources.TintColor)
iconView.contentMode = UIViewContentMode.Center
contactsView.addSubview(iconView)
}
var phoneView = UILabel(frame: CGRectMake(66, CGFloat(i*48 + 22), 320 - 66, 22))
phoneView.textColor = Resources.TextPrimaryColor
phoneView.font = UIFont.systemFontOfSize(18)
phoneView.text = "+\(phone.getPhone())";
var titleView = UILabel(frame: CGRectMake(66, CGFloat(i*48), 320 - 66, 22))
titleView.textColor = Resources.TintColor
titleView.font = UIFont.systemFontOfSize(14)
titleView.text = phone.getTitle();
contactsView.addSubview(titleView)
contactsView.addSubview(phoneView)
}
}
func addContact() {
if ((self.userVm!.isContact().get() as! JavaLangBoolean).booleanValue()) {
execute(MSG.removeContactWithInt(jint(uid)))
} else {
execute(MSG.addContactWithInt(jint(uid)))
}
}
func compose() {
self.navigationController?.pushViewController(MessagesViewController(peer: AMPeer.userWithInt(jint(self.uid))), animated: true);
}
func editName() {
var alertView = UIAlertView(title: "Edit Name", message: "<NAME>", delegate: self, cancelButtonTitle: "Cancel")
alertView.addButtonWithTitle("Edit")
alertView.alertViewStyle = UIAlertViewStyle.PlainTextInput
alertView.textFieldAtIndex(0)?.text = self.userVm!.getName().get() as! String;
alertView.textFieldAtIndex(0)?.autocapitalizationType = UITextAutocapitalizationType.Sentences
alertView.show()
}
func alertView(alertView: UIAlertView, willDismissWithButtonIndex buttonIndex: Int) {
if (buttonIndex == 1) {
execute(MSG.editNameWithInt(jint(self.uid), withNSString: alertView.textFieldAtIndex(0)!.text!))
}
}
}
<file_sep>/ActorClient/ActorClient/EngineListController.swift
//
// EngineListController.swift
// ActorClient
//
// Created by <NAME> on 10.03.15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class EngineListController: UIViewController, UITableViewDelegate, UITableViewDataSource, AMDisplayList_Listener {
private var engineTableView: UITableView!;
private var displayList: AMBindedDisplayList!;
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil);
}
init(){
super.init(nibName: nil, bundle: nil);
}
func bindTable(table: UITableView){
self.engineTableView = table;
self.engineTableView!.dataSource = self;
self.engineTableView!.delegate = self;
}
override func viewDidLoad() {
if (self.displayList == nil) {
self.displayList = buildDisplayList()
self.displayList.addListenerWithAMDisplayList_Listener(self)
self.engineTableView.reloadData()
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if (self.engineTableView != nil) {
var selected = self.engineTableView.indexPathForSelectedRow();
if (selected != nil){
self.engineTableView.deselectRowAtIndexPath(selected!, animated: animated);
}
}
}
func filter(val: String) {
if (val.size() == 0) {
self.displayList.initTopWithBoolean(false)
} else {
self.displayList.initSearchWithNSString(val, withBoolean: false)
}
}
// Table Data Source
func onCollectionChanged() {
if (self.engineTableView != nil){
self.engineTableView.reloadData()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (displayList == nil) {
return 0;
}
if (section != 0) {
return 0;
}
return Int(displayList.getSize());
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var item: AnyObject? = objectAtIndexPath(indexPath)
var cell = buildCell(tableView, cellForRowAtIndexPath:indexPath, item:item);
bindCell(tableView, cellForRowAtIndexPath: indexPath, item: item, cell: cell);
displayList.touchWithInt(jint(indexPath.row))
return cell;
}
func objectAtIndexPath(indexPath: NSIndexPath) -> AnyObject? {
if (displayList == nil) {
return nil
}
return displayList.getItemWithInt(jint(indexPath.row));
}
// Abstract methods
func buildDisplayList() -> AMBindedDisplayList {
fatalError("Not implemented");
}
func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell {
fatalError("Not implemented");
}
func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) {
fatalError("Not implemented");
}
}<file_sep>/ActorClient/ActorClient/CocoaNetworking.swift
//
// CocoaNetworking.swift
// ActorClient
//
// Created by <NAME> on 20.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
class SwiftCocoaNetworkProvider : NSObject, AMNetworkProvider {
// TODO: Check thread-safe correctness
let syncObject = NSObject()
var pendingConnection: Array<AnyObject> = []
func createConnection(connectionId: jint, withEndpoint endpoint: AMConnectionEndpoint!, withCallback callback: AMConnectionCallback!, withCreateCallback createCallback: AMCreateConnectionCallback!) {
// var connection = SwiftCocoaConnection(connectionId: connectionId, withEndpoint: endpoint!, withCallback: callback!, connectionCreated: { (connection) -> () in
// createCallback.onConnectionCreated(connection)
// objc_sync_enter(self.syncObject)
// self.pendingConnection.removeAtIndex(find(self.pendingConnection, connection)!)
// objc_sync_exit(self.syncObject)
// }) { (connection) -> () in
// createCallback.onConnectionCreateError()
// objc_sync_enter(self.syncObject)
// self.pendingConnection.removeAtIndex(find(self.pendingConnection, connection)!)
// objc_sync_exit(self.syncObject)
// }
var connection = CocoaTcpConnection(connectionId: connectionId, connectionEndpoint: endpoint, connectionCallback: callback, createCallback: createCallback)
objc_sync_enter(syncObject)
pendingConnection.append(connection)
objc_sync_exit(syncObject)
// connection.start()
}
}
class SwiftCocoaConnection: NSObject, AMConnection, GCDAsyncSocketDelegate {
let connectionTimeout = 5.0
var isSocketOpen = false
var isSocketClosed = false
var gcdSocket:GCDAsyncSocket? = nil;
var outPackageIndex:UInt32 = 0
var inPackageIndex:UInt32 = 0
let connectionId:Int;
let endpoint: AMConnectionEndpoint;
let connectionCreated: (connection: SwiftCocoaConnection)->()
let connectionFailure: (connection: SwiftCocoaConnection)->()
let callback: AMConnectionCallback;
init(connectionId: jint, withEndpoint endpoint: AMConnectionEndpoint, withCallback callback: AMConnectionCallback, connectionCreated: (connection: SwiftCocoaConnection)->(), connectionFailure: (connection: SwiftCocoaConnection)->()) {
self.connectionId = Int(connectionId)
self.endpoint = endpoint;
self.connectionCreated = connectionCreated
self.connectionFailure = connectionFailure
self.callback = callback
}
func start() {
NSLog("🎍#\(connectionId) Connecting...")
gcdSocket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0))
gcdSocket!.connectToHost(endpoint.getHost()!, onPort: UInt16(endpoint.getPort()), withTimeout: connectionTimeout, error: nil)
}
func socket(sock: GCDAsyncSocket!, didConnectToHost host: String!, port: UInt16) {
NSLog("🎍#\(connectionId) Connected...")
if (UInt(self.endpoint.getType().ordinal()) == AMConnectionEndpoint_Type.TCP_TLS.rawValue) {
NSLog("🎍#\(self.connectionId) Starring TLS Session...")
// TODO: Check TLS
sock.startTLS([//(id)kCFStreamSSLAllowsExpiredCertificates:@NO,
//(id)kCFStreamSSLAllowsExpiredRoots:@NO,
//(id)kCFStreamSSLAllowsAnyRoot:@YES,
//(id)kCFStreamSSLValidatesCertificateChain:@YES,
kCFStreamSSLPeerName:"actor.im"
//(id)kCFStreamSSLLevel:(id)kCFStreamSocketSecurityLevelNegotiatedSSL,
])
} else {
if (self.isSocketOpen) {
return
}
self.isSocketOpen = true
self.requestReadHeader()
self.connectionCreated(connection: self)
}
}
func socketDidSecure(sock: GCDAsyncSocket!) {
NSLog("🎍#\(connectionId) TLS connection established...")
if (isSocketOpen) {
return
}
isSocketOpen = true
self.requestReadHeader()
self.connectionCreated(connection: self)
}
func socketDidDisconnect(sock: GCDAsyncSocket!, withError err: NSError!) {
if (isSocketOpen) {
isSocketClosed = true
NSLog("🎍#\(connectionId) Connection die")
callback.onConnectionDie()
} else {
if (isSocketClosed) {
return
}
isSocketClosed = true
NSLog("🎍#\(connectionId) Connection failured")
connectionFailure(connection: self)
}
}
func requestReadHeader() {
NSLog("🎍#\(connectionId) Request reading header...")
gcdSocket?.readDataToLength(4, withTimeout: -1, tag: 0)
// gcdSocket?.readDataWithTimeout(-1, tag: 0)
}
func requestReadBody(bodySize: UInt) {
NSLog("🎍#\(connectionId) Request reading body \(bodySize)...")
gcdSocket?.readDataToLength(bodySize, withTimeout: -1, tag: 1)
}
func socket(sock: GCDAsyncSocket!, didReadPartialDataOfLength partialLength: UInt, tag: Int) {
NSLog("🎍#\(connectionId) didReadPartialDataOfLength \(partialLength)...")
}
func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) {
if (tag == 0) {
// Header
if (data.length != 4) {
fatalError("🎍#\(connectionId) Unknown header size");
}
var len = data.readUInt32();
if (len == 0) {
crashConnection()
return
} else if (len > 1024 * 1024 * 1024) {
crashConnection()
return
}
NSLog("🎍#\(connectionId) Received header \(len)...")
requestReadBody(UInt(len));
} else if (tag == 1) {
// Body
NSLog("🎍#\(connectionId) Received body \(data.length)...")
var packageIndex = data.readUInt32();
var package = data.subdataWithRange(NSMakeRange(4, Int(data.length - 8)))
var crc32 = data.readUInt32(data.length - 4)
// TODO: Add packageIndex and crc32 checks
NSLog("🎍#\(connectionId) Loaded body #\(packageIndex)...")
callback.onMessage(package.toJavaBytes(), withOffset: jint(0), withLen: jint(package.length))
requestReadHeader()
} else {
fatalError("🎍#\(connectionId) Unknown tag");
}
}
func socket(sock: GCDAsyncSocket!, didWriteDataWithTag tag: Int) {
NSLog("🎍#\(connectionId) didWriteDataWithTag...")
}
func socket(sock: GCDAsyncSocket!, didWritePartialDataOfLength partialLength: UInt, tag: Int) {
NSLog("🎍#\(connectionId) didWritePartialDataOfLength \(partialLength)...")
}
func post(data: IOSByteArray!, withOffset offset: jint, withLen len: jint) {
if (isSocketClosed) {
NSLog("🎍#\(connectionId) isSocketClosed...")
return
}
// Prepare Transport package
var dataToWrite = NSMutableData(capacity: Int(data.length() + 12))!
dataToWrite.appendUInt32(UInt32(8 + data.length()))
dataToWrite.appendUInt32(UInt32(self.outPackageIndex++))
dataToWrite.appendData(data.toNSData().subdataWithRange(NSMakeRange(Int(offset), Int(len))))
dataToWrite.appendData(CRC32.crc32(dataToWrite as NSData))
// TODO: Propper timeout??
NSLog("🎍#\(self.connectionId) Data posted to socket...")
self.gcdSocket?.writeData(dataToWrite, withTimeout: -1, tag: 0)
}
func crashConnection() {
if (isSocketClosed) {
return
}
isSocketClosed = true
gcdSocket?.disconnect()
}
func isClosed() -> Bool {
return isSocketClosed
}
func close() {
if (isSocketClosed) {
return
}
isSocketClosed = true
crashConnection()
}
}<file_sep>/ActorClient/ActorClient/GroupMembersController.swift
//
// GroupMembersController.swift
// ActorClient
//
// Created by <NAME> on 23.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import UIKit
class GroupMembersController: ContactsBaseController, VENTokenFieldDataSource, VENTokenFieldDelegate {
@IBOutlet weak var tokenField: UIView!
@IBOutlet weak var contactsTable: UITableView!
var tokenFieldView: VENTokenField?;
var selectedNames: Array<AMContact> = []
override init() {
super.init(nibName: "GroupMembersController", bundle: nil)
navigationItem.title = "Group Members";
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: UIBarButtonItemStyle.Done, target: self, action: "doNext")
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
tokenFieldView = VENTokenField(frame: CGRectMake(0, 0, tokenField.frame.width, tokenField.frame.height))
tokenFieldView!.delegate = self
tokenFieldView!.dataSource = self
tokenFieldView!.maxHeight = 96
view.addSubview(tokenFieldView!)
bindTable(contactsTable)
super.viewDidLoad()
}
func doNext() {
}
func tokenField(tokenField: VENTokenField!, didChangeText text: String!) {
filter(text)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var contact = objectAtIndexPath(indexPath) as! AMContact
selectedNames.append(contact)
tokenFieldView?.reloadData()
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func tokenField(tokenField: VENTokenField!, didDeleteTokenAtIndex index: UInt) {
self.selectedNames.removeAtIndex(Int(index))
tokenFieldView?.reloadData()
}
func tokenField(tokenField: VENTokenField!, titleForTokenAtIndex index: UInt) -> String! {
return self.selectedNames[Int(index)].getName()
}
func tokenFieldCollapsedText(tokenField: VENTokenField!) -> String! {
return "selected \(self.selectedNames.count)"
}
func numberOfTokensInTokenField(tokenField: VENTokenField!) -> UInt {
return UInt(self.selectedNames.count)
}
}
<file_sep>/ActorClient/ActorClient/FMDBKeyValue.swift
//
// FMDBKeyValue.swift
// ActorClient
//
// Created by <NAME> on 14.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
@objc class FMDBKeyValue: NSObject, DKKeyValueStorage {
var db :FMDatabase?;
let databasePath: String;
let tableName: String;
let queryCreate: String;
let queryItem: String;
let queryAdd: String;
let queryDelete: String;
let queryDeleteAll: String;
var isTableChecked: Bool = false;
init(databasePath: String, tableName: String) {
self.databasePath = databasePath
self.tableName = tableName
// Queries
self.queryCreate = "CREATE TABLE IF NOT EXISTS " + tableName + " (" +
"\"ID\" INTEGER NOT NULL, " +
"\"BYTES\" BLOB NOT NULL, " +
"PRIMARY KEY (\"ID\"));";
self.queryItem = "SELECT \"BYTES\" FROM " + tableName + " WHERE \"ID\" = ?;";
self.queryAdd = "REPLACE INTO " + tableName + " (\"ID\", \"BYTES\") VALUES (?, ?);";
self.queryDelete = "DELETE FROM " + tableName + " WHERE \"ID\" = ?;";
self.queryDeleteAll = "DELETE FROM " + tableName + ";";
super.init()
}
private func checkTable() {
if (isTableChecked) {
return
}
isTableChecked = true;
self.db = FMDatabase(path: databasePath)
self.db!.open()
if (!db!.tableExists(tableName)) {
db!.executeUpdate(queryCreate)
}
}
func addOrUpdateItemsWithJavaUtilList(values: JavaUtilList!) {
checkTable();
db!.beginTransaction()
for i in 0..<values.size() {
let record = values.getWithInt(i) as! DKKeyValueRecord;
db!.executeUpdate(queryAdd, record.getId().toNSNumber(),record.getData()!.toNSData())
}
db!.commit()
}
func addOrUpdateItemWithLong(id_: jlong, withByteArray data: IOSByteArray!) {
checkTable();
db!.beginTransaction()
db!.executeUpdate(queryAdd, id_.toNSNumber(), data!.toNSData())
db!.commit()
}
func removeItemsWithLongArray(ids: IOSLongArray!) {
checkTable();
db!.beginTransaction()
for i in 0..<ids.length() {
var id_ = ids.longAtIndex(UInt(i));
db!.executeUpdate(queryDelete, id_.toNSNumber())
}
db!.commit()
}
func removeItemWithLong(id_: jlong) {
checkTable();
db!.beginTransaction()
db!.executeUpdate(queryDelete, id_.toNSNumber())
db!.commit()
}
func clear() {
checkTable();
db!.beginTransaction()
db!.executeUpdate(queryDeleteAll);
db!.commit()
}
func getValueWithLong(id_: jlong) -> IOSByteArray! {
checkTable();
var result = db!.dataForQuery(queryItem, id_.toNSNumber());
if (result == nil) {
return nil;
}
return result.toJavaBytes();
}
}<file_sep>/ActorClient/ActorClient/ComposeController.swift
//
// ComposeController.swift
// ActorClient
//
// Created by <NAME> on 23.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import UIKit
class ComposeController: ContactsBaseController, UISearchBarDelegate, UISearchDisplayDelegate {
@IBOutlet weak var tableView: UITableView!
var searchView: UISearchBar?
var searchDisplay: UISearchDisplayController?
var searchSource: ContactsSource?
override init() {
super.init(nibName: "ComposeController", bundle: nil)
self.navigationItem.title = "New Message";
self.extendedLayoutIncludesOpaqueBars = true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
bindTable(tableView)
searchView = UISearchBar()
searchView!.searchBarStyle = UISearchBarStyle.Default
searchView!.barStyle = UIBarStyle.Default
searchView!.translucent = false
searchView?.setSearchFieldBackgroundImage(Imaging.imageWithColor(Resources.SearchBgColor, size: CGSize(width: 1, height: 28)), forState: UIControlState.Normal)
// Enabled color
searchView!.barTintColor = UIColor.whiteColor()
// Disabled color
searchView!.backgroundImage = Imaging.imageWithColor(UIColor.whiteColor(), size: CGSize(width: 1, height: 1))
searchView!.backgroundColor = UIColor.whiteColor()
// Enabled Cancel button color
searchView!.tintColor = Resources.TintColor
searchView!.placeholder = "";
searchView!.delegate = self
searchView!.frame = CGRectMake(0, 0, 0, 44)
searchDisplay = UISearchDisplayController(searchBar: searchView, contentsController: self)
searchDisplay?.searchResultsDelegate = self
searchDisplay?.searchResultsTableView.rowHeight = 56
searchDisplay?.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyle.None
searchDisplay?.searchResultsTableView.backgroundColor = Resources.BackyardColor
searchDisplay?.searchResultsTableView.frame = tableView.frame
tableView.tableHeaderView = searchView
searchSource = ContactsSource(searchDisplay: searchDisplay!)
super.viewDidLoad()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (tableView == self.tableView) {
var contact = objectAtIndexPath(indexPath) as! AMContact
var controllers = NSMutableArray(array: navigationController!.viewControllers)
controllers.removeLastObject()
controllers.addObject(MessagesViewController(peer: AMPeer.userWithInt(contact.getUid())))
navigationController!.setViewControllers(controllers as [AnyObject], animated: true)
} else {
var contact = searchSource!.objectAtIndexPath(indexPath) as! AMContact
var controllers = NSMutableArray(array: navigationController!.viewControllers)
controllers.removeLastObject()
controllers.addObject(MessagesViewController(peer: AMPeer.userWithInt(contact.getUid())))
navigationController!.setViewControllers(controllers as [AnyObject], animated: true)
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
}
}<file_sep>/ActorClient/ActorClient/ContactsViewController.swift
//
// ContactsViewController.swift
// ActorClient
//
// Created by <NAME> on 10.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import UIKit
class ContactsViewController: ContactsBaseController {
@IBOutlet var rootView: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var emptyView: UIView!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
initCommon();
}
override init() {
super.init(nibName: "ContactsViewController", bundle: nil)
initCommon();
}
func initCommon(){
var icon = UIImage(named: "ic_users_blue_24")!;
tabBarItem = UITabBarItem(title: nil,
image: icon.tintImage(Resources.BarTintUnselectedColor)
.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal),
selectedImage: icon);
tabBarItem.imageInsets=UIEdgeInsetsMake(6, 0, -6, 0);
}
override func viewDidLoad() {
bindTable(tableView);
emptyView.hidden = true;
super.viewDidLoad();
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
var selected = tableView.indexPathForSelectedRow();
if (selected != nil){
tableView.deselectRowAtIndexPath(selected!, animated: animated);
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var contact = objectAtIndexPath(indexPath) as! AMContact;
self.navigationController?.pushViewController(MessagesViewController(peer: AMPeer.userWithInt(contact.getUid())), animated: true);
}
}
<file_sep>/ActorClient/ActorClient/Resouces.swift
//
// Resouces.swift
// ActorClient
//
// Created by <NAME> on 11.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
@objc class Resources {
init(){
fatalError("Unable to instantinate Resources");
}
private static var _iconCheck1:UIImage? = nil;
private static var _iconCheck2:UIImage? = nil;
private static var _iconError:UIImage? = nil;
private static var _iconWarring:UIImage? = nil;
private static var _iconClock:UIImage? = nil;
static var iconCheck1:UIImage {
get {
if (_iconCheck1 == nil){
_iconCheck1 = UIImage(named: "msg_check_1")?
.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
}
return _iconCheck1!;
}
}
static var iconCheck2:UIImage {
get {
if (_iconCheck2 == nil){
_iconCheck2 = UIImage(named: "msg_check_2")?
.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
}
return _iconCheck2!;
}
}
static var iconError:UIImage {
get {
if (_iconError == nil){
_iconError = UIImage(named: "msg_error")?
.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
}
return _iconError!;
}
}
static var iconWarring:UIImage {
get {
if (_iconWarring == nil){
_iconWarring = UIImage(named: "msg_warring")?
.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
}
return _iconWarring!;
}
}
static var iconClock:UIImage {
get {
if (_iconClock == nil){
_iconClock = UIImage(named: "msg_clock")?
.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
}
return _iconClock!;
}
}
static let TintDarkColor = UIColor(red: 38/255.0, green: 109/255.0, blue: 204/255.0, alpha: 1.0);
static let TintColor = UIColor(red: 80/255.0, green: 133/255.0, blue: 204/255.0, alpha: 1.0);
static let BarTintColor = TintColor;
static let BarTintUnselectedColor = UIColor(red: 171/255.0, green: 182/255.0, blue: 202/255.0, alpha: 1);
static let SearchBgColor = UIColor(red: 217/255.0, green: 218/255.0, blue: 220/255.0, alpha: 1)
static let placeHolderColors : [UIColor] = [
UIColor(red: 0x59/255.0, green: 0xa2/255.0, blue: 0xbe/255.0, alpha: 1),
UIColor(red: 0x20/255.0, green: 0x93/255.0, blue: 0xcd/255.0, alpha: 1),
UIColor(red: 0xad/255.0, green: 0x62/255.0, blue: 0xa7/255.0, alpha: 1),
UIColor(red: 0xf1/255.0, green: 0x63/255.0, blue: 0x64/255.0, alpha: 1),
UIColor(red: 0xf9/255.0, green: 0xa4/255.0, blue: 0x3e/255.0, alpha: 1),
UIColor(red: 0xe4/255.0, green: 0xc6/255.0, blue: 0x2e/255.0, alpha: 1),
UIColor(red: 0x67/255.0, green: 0xbf/255.0, blue: 0x74/255.0, alpha: 1)];
static let TextPrimaryColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0);
static let TextSecondaryColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0x8A/255.0);
static let SeparatorColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0x1e/255.0)
static let BackyardColor = UIColor(red: 238/255.0, green: 238/255.0, blue: 238/255.0, alpha: 1)
static let SecondaryTint = UIColor(red: 0xb5/255.0, green: 0xb6/255.0, blue: 0xb7/255.0, alpha: 1)
static let SecondaryLightText = UIColor(red: 1, green: 1, blue: 1, alpha: 128/255.0)
static let PrimaryLightText = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
static let SelectorColor = UIColor(red: 0, green: 0, blue: 0, alpha: 60/255.0)
}
<file_sep>/ActorClient/ActorClient/AppDelegate.swift
//
// AppDelegate.swift
// ActorClient
//
// Created by <NAME> on 10.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
@objc class AppDelegate : UIResponder, UIApplicationDelegate {
private var window : UIWindow?;
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
application.statusBarStyle = UIStatusBarStyle.LightContent
var navAppearance = UINavigationBar.appearance();
navAppearance.tintColor = UIColor.whiteColor();
navAppearance.barTintColor = UIColor.whiteColor();
navAppearance.backgroundColor = Resources.TintColor;
navAppearance.setBackgroundImage(Imaging.imageWithColor(Resources.TintColor, size: CGSize(width: 1, height: 46)), forBarMetrics: UIBarMetrics.Default)
navAppearance.shadowImage = UIImage(named: "CardBottom2")
navAppearance.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()];
navAppearance.translucent = false;
var textFieldAppearance = UITextField.appearance();
textFieldAppearance.tintColor = Resources.TintColor;
//var searchBarAppearance = UISearchBar.appearance();
//searchBarAppearance.tintColor = Resources.TintColor;
UITabBar.appearance().translucent = false
UITabBar.appearance().tintColor = Resources.BarTintColor;
UITabBar.appearance().backgroundImage = Imaging.imageWithColor(UIColor.whiteColor(), size: CGSize(width: 1, height: 46))
UITabBar.appearance().shadowImage = UIImage(named: "CardTop2");
UITabBar.appearance().selectionIndicatorImage = Imaging.imageWithColor(UIColor(red: 0xeb/255.0, green: 0xed/255.0, blue: 0xf2/255.0, alpha: 1), size: CGSize(width: 1, height: 46)).resizableImageWithCapInsets(UIEdgeInsetsZero);
// setTitleTextAttributes(NSForegroundColorAttributeName, );
// var barButtonItemAppearance = UIBarButtonItem.appearance();
// barButtonItemAppearance
// [UINavigationBar appearance].tintColor = [UIColor whiteColor];
// [UINavigationBar appearance].barTintColor = BAR_COLOR;
// [UINavigationBar appearance].backgroundColor = BAR_COLOR;
// [UINavigationBar appearance].titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
// [UITextField appearance].tintColor = BAR_COLOR;
// [UISearchBar appearance].tintColor = BAR_COLOR;
// //[UISearchBar appearance].backgroundImage = [UIImage new];
// [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class],nil]
// setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];
//
// [UITableViewCell appearance].tintColor = BAR_COLOR;
// [UITableView appearance].sectionIndexColor = BAR_COLOR;
// [UITabBar appearance].tintColor = BAR_COLOR;
//
// [MagicalRecord setupAutoMigratingCoreDataStack];
//
// [CocoaMessenger messenger];
// Starting app
var rootController = UINavigationController(rootViewController: MainTabController());
window = UIWindow(frame: UIScreen.mainScreen().bounds);
// window?.tintColor = TintColor;
window?.rootViewController = rootController;
window?.makeKeyAndVisible();
if (!MSG.isLoggedIn()){
var controller = UIStoryboard(name: "Auth", bundle: nil).instantiateInitialViewController() as! UIViewController;
rootController.presentViewController(controller, animated: false, completion: nil)
}
return true;
}
func applicationWillEnterForeground(application: UIApplication) {
MSG.onAppVisible();
}
func applicationDidEnterBackground(application: UIApplication) {
MSG.onAppHidden();
}
}<file_sep>/ActorClient/ActorClient/DiscoverViewController.swift
//
// DiscoverViewController.swift
// ActorClient
//
// Created by <NAME> on 12.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import UIKit
class DiscoverViewController: UIViewController {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
initCommon();
}
init() {
super.init(nibName: "DiscoverViewController", bundle: nil)
initCommon();
}
func initCommon(){
var icon = UIImage(named: "ic_search_blue_24")!;
tabBarItem = UITabBarItem(title: nil,
image: icon.tintImage(Resources.BarTintUnselectedColor)
.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal),
selectedImage: icon);
tabBarItem.imageInsets=UIEdgeInsetsMake(6, 0, -6, 0);
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/ActorClient/ActorClient/MenuItemCell.swift
//
// MenuItemCell.swift
// ActorClient
//
// Created by <NAME> on 18.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import UIKit
class MenuItemCell: UITableViewCell {
@IBOutlet weak var titleView: UILabel!
@IBOutlet weak var iconView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setData(image: String, title: String){
iconView.image = UIImage(named: image)!.tintImage(Resources.SecondaryTint)
titleView.text = title
}
}
<file_sep>/ActorClient/ActorClient/Strings.swift
//
// Strings.swift
// ActorClient
//
// Created by <NAME> on 14.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
extension String {
func trim() -> String {
return stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet());
}
func size() -> Int {
return count(self);
}
subscript (i: Int) -> Character {
return self[advance(self.startIndex, i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
func first(count: Int) -> String {
let realCount = min(count, size());
return substringToIndex(advance(startIndex, realCount));
}
func smallValue() -> String {
let trimmed = trim();
if (trimmed.isEmpty){
return "#";
}
let letters = NSCharacterSet.letterCharacterSet()
var res: String = self[0];
if (res.rangeOfCharacterFromSet(letters) != nil) {
return res.uppercaseString;
} else {
return "#";
}
}
}<file_sep>/ActorClient/ActorClient/EngineSlackListController.swift
//
// EngineSlackListController.swift
// ActorClient
//
// Created by <NAME> on 11.03.15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Foundation
import UIKit;
class EngineSlackListController: SLKTextViewController, UITableViewDelegate, UITableViewDataSource, AMDisplayList_Listener {
private var displayList: AMBindedDisplayList!;
private var emptyLock: Bool = true;
init(isInverted:Bool) {
super.init(tableViewStyle: UITableViewStyle.Plain);
self.inverted = isInverted;
self.tableView.contentInset = UIEdgeInsetsZero;
}
required init!(coder decoder: NSCoder!) {
fatalError("Not implemented");
}
override func viewDidLoad() {
if (self.displayList == nil) {
self.displayList = getDisplayList()
self.displayList.addListenerWithAMDisplayList_Listener(self)
}
dispatch_async(dispatch_get_main_queue(),{
self.emptyLock = false
self.tableView.reloadData()
});
}
func onCollectionChanged() {
NSLog("🇯🇵 onCollcetionChanged")
if (self.emptyLock) {
return
}
if (self.tableView != nil){
self.tableView.reloadData()
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (emptyLock) {
return 0
}
if (displayList == nil) {
return 0;
}
if (section != 0) {
return 0;
}
return Int(displayList.getSize());
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var item: AnyObject? = objectAtIndexPath(indexPath)
var cell = buildCell(tableView, cellForRowAtIndexPath:indexPath, item:item);
bindCell(tableView, cellForRowAtIndexPath: indexPath, item: item, cell: cell);
displayList.touchWithInt(jint(indexPath.row))
cell.transform = tableView.transform
return cell;
}
func objectAtIndexPath(indexPath: NSIndexPath) -> AnyObject? {
if (displayList == nil) {
return nil
}
return displayList.getItemWithInt(jint(indexPath.row));
}
// Abstract methods
func getDisplayList() -> AMBindedDisplayList {
fatalError("Not implemented");
}
func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell {
fatalError("Not implemented");
}
func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) {
fatalError("Not implemented");
}
}<file_sep>/ActorClient/ActorClient/FMDBList.swift
//
// FMDBList.swift
// ActorClient
//
// Created by <NAME> on 15.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
class FMDBList : NSObject, DKListStorage {
var db :FMDatabase? = nil;
var isTableChecked: Bool = false;
let databasePath: String;
let tableName: String;
let queryCreate: String;
let queryCreateIndex: String;
let queryCreateFilter: String;
let queryAdd: String;
let queryItem: String;
let queryDelete: String;
let queryDeleteAll: String;
let queryForwardFirst: String;
let queryForwardMore: String;
let queryForwardFilterFirst: String;
let queryForwardFilterMore: String;
init (databasePath: String, tableName: String){
self.databasePath = databasePath
self.tableName = tableName;
self.queryCreate = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + //
"\"ID\" INTEGER NOT NULL," + // 0: id
"\"SORT_KEY\" INTEGER NOT NULL," + // 1: sortKey
"\"QUERY\" TEXT," + // 2: query
"\"BYTES\" BLOB NOT NULL," + // 3: bytes
"PRIMARY KEY(\"ID\"));";
self.queryCreateIndex = "CREATE INDEX IF NOT EXISTS IDX_ID_SORT ON " + tableName + " (\"SORT_KEY\");"
self.queryCreateFilter = "CREATE INDEX IF NOT EXISTS IDX_ID_QUERY_SORT ON " + tableName + " (\"QUERY\", \"SORT_KEY\");"
self.queryAdd = "REPLACE INTO " + tableName + " (\"ID\",\"QUERY\",\"SORT_KEY\",\"BYTES\") VALUES (?,?,?,?)";
self.queryItem = "SELECT \"ID\",\"QUERY\",\"SORT_KEY\",\"BYTES\" FROM " + tableName + " WHERE \"ID\" = ?;";
self.queryDeleteAll = "DELETE FROM " + tableName + ";";
self.queryDelete = "DELETE FROM " + tableName + " WHERE \"ID\"= ?;";
self.queryForwardFirst = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " ORDER BY SORT_KEY DESC LIMIT ?";
self.queryForwardMore = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE \"SORT_KEY\" < ? ORDER BY SORT_KEY DESC LIMIT ?";
self.queryForwardFilterFirst = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE \"QUERY\" LIKE ? OR \"QUERY\" LIKE ? ORDER BY SORT_KEY DESC LIMIT ?";
self.queryForwardFilterMore = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE (\"QUERY\" LIKE ? OR \"QUERY\" LIKE ?) AND \"SORT_KEY\" < ? ORDER BY SORT_KEY DESC LIMIT ?";
}
func checkTable() {
if (isTableChecked) {
return
}
isTableChecked = true;
self.db = FMDatabase(path: databasePath)
self.db!.open()
if (!db!.tableExists(tableName)) {
db!.executeUpdate(queryCreate)
db!.executeUpdate(queryCreateIndex)
db!.executeUpdate(queryCreateFilter)
}
}
func updateOrAddWithDKListEngineRecord(valueContainer: DKListEngineRecord!) {
checkTable();
db!.beginTransaction()
db!.executeUpdate(queryAdd, withArgumentsInArray: [valueContainer.getKey().toNSNumber(), valueContainer.dbQuery(), valueContainer.getOrder().toNSNumber(),
valueContainer.getData().toNSData()])
db!.commit()
}
func updateOrAddWithJavaUtilList(items: JavaUtilList!) {
checkTable();
db!.beginTransaction()
for i in 0..<items.size() {
let record = items.getWithInt(i) as! DKListEngineRecord;
db!.executeUpdate(queryAdd, record.getKey().toNSNumber(), record.dbQuery(), record.getOrder().toNSNumber(),
record.getData().toNSData())
}
db!.commit()
}
func delete__WithLong(key: jlong) {
checkTable();
db!.beginTransaction()
db!.executeUpdate(queryDelete, key.toNSNumber());
db!.commit()
}
func delete__WithLongArray(keys: IOSLongArray!) {
checkTable();
db!.beginTransaction()
for i in 0..<keys.length() {
var k = keys.longAtIndex(UInt(i));
db!.executeUpdate(queryDelete, k.toNSNumber());
}
db!.commit()
}
func getCount() -> jint {
checkTable();
fatalError("Not implemented")
}
func clear() {
checkTable();
db!.beginTransaction()
db!.executeUpdate(queryDeleteAll);
db!.commit()
}
func loadItemWithLong(key: jlong) -> DKListEngineRecord! {
checkTable();
var result = db!.executeQuery(queryItem, key.toNSNumber());
if (result == nil) {
return nil
}
if (result!.next()) {
var query: AnyObject! = result!.objectForColumnName("QUERY");
if (query is NSNull){
query = nil
}
var res = DKListEngineRecord(long: jlong(result!.longForColumn("ID")), withLong: jlong(result!.longForColumn("SORT_KEY")), withNSString: query as! String?, withByteArray: result!.dataForColumn("BYTES").toJavaBytes())
result?.close()
return res;
} else {
result?.close()
return nil
}
}
func loadForwardWithJavaLangLong(sortingKey: JavaLangLong!, withInt limit: jint) -> JavaUtilList! {
checkTable();
var result : FMResultSet? = nil;
if (sortingKey == nil) {
result = db!.executeQuery(queryForwardFirst, limit.toNSNumber());
} else {
result = db!.executeQuery(queryForwardMore, sortingKey!.longValue, limit.toNSNumber());
}
if (result == nil) {
NSLog(db!.lastErrorMessage())
return nil
}
var res: JavaUtilArrayList = JavaUtilArrayList();
while(result!.next()) {
var query: AnyObject! = result!.objectForColumnName("QUERY");
if (query is NSNull) {
query = nil
}
res.addWithId(DKListEngineRecord(long: jlong(result!.longForColumn("ID")), withLong: jlong(result!.longForColumn("SORT_KEY")), withNSString: query as! String?, withByteArray: result!.dataForColumn("BYTES").toJavaBytes()))
}
result!.close()
return res;
}
func loadForwardWithNSString(query: String!, withJavaLangLong sortingKey: JavaLangLong!, withInt limit: jint) -> JavaUtilList! {
checkTable();
checkTable();
var result : FMResultSet? = nil;
if (sortingKey == nil) {
result = db!.executeQuery(queryForwardFilterFirst, query + "%", "% " + query + "%", limit.toNSNumber());
} else {
result = db!.executeQuery(queryForwardFilterMore, query + "%", "% " + query + "%", sortingKey!.longValue, limit.toNSNumber());
}
if (result == nil) {
NSLog(db!.lastErrorMessage())
return nil
}
var res: JavaUtilArrayList = JavaUtilArrayList();
while(result!.next()) {
var query: AnyObject! = result!.objectForColumnName("QUERY");
if (query is NSNull) {
query = nil
}
res.addWithId(DKListEngineRecord(long: jlong(result!.longForColumn("ID")), withLong: jlong(result!.longForColumn("SORT_KEY")), withNSString: query as! String?, withByteArray: result!.dataForColumn("BYTES").toJavaBytes()))
}
result!.close()
return res;
}
func loadBackwardWithJavaLangLong(sortingKey: JavaLangLong!, withInt limit: jint) -> JavaUtilList! {
checkTable();
fatalError("Not implemented")
}
func loadBackwardWithNSString(query: String!, withJavaLangLong sortingKey: JavaLangLong!, withInt limit: jint) -> JavaUtilList! {
checkTable();
fatalError("Not implemented")
}
}<file_sep>/ActorClient/ActorClient/DialogCell.swift
//
// DialogCell.swift
// ActorClient
//
// Created by <NAME> on 12.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import UIKit;
class DialogCell: UITableViewCell {
let avatarView: AvatarView = AvatarView(frameSize: 48);
let titleView: UILabel = UILabel();
let messageView: UILabel = UILabel();
let dateView: UILabel = UILabel();
let statusView: UIImageView = UIImageView();
let separatorView = TableViewSeparator(color: Resources.SeparatorColor);
var bindedFile: jlong? = nil;
var avatarCallback: CocoaDownloadCallback? = nil;
init(reuseIdentifier:String) {
super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier)
titleView.font = UIFont(name: "Roboto-Medium", size: 19);
titleView.textColor = Resources.TextPrimaryColor;
messageView.font = UIFont(name: "HelveticaNeue", size: 16);
messageView.textColor = Resources.TextSecondaryColor;
dateView.font = UIFont(name: "HelveticaNeue", size: 14);
dateView.textColor = Resources.TextSecondaryColor
dateView.textAlignment = NSTextAlignment.Right;
statusView.contentMode = UIViewContentMode.Center;
self.contentView.addSubview(avatarView)
self.contentView.addSubview(titleView)
self.contentView.addSubview(messageView)
self.contentView.addSubview(dateView)
self.contentView.addSubview(statusView)
self.contentView.addSubview(separatorView)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bindDialog(dialog: AMDialog, isLast:Bool) {
avatarView.bind(dialog.getDialogTitle(), id: dialog.getPeer().getPeerId(), avatar: dialog.getDialogAvatar());
titleView.text = dialog.getDialogTitle();
var text = MSG.getFormatter().formatContentDialogTextWithInt(dialog.getSenderId(), withAMContentTypeEnum: dialog.getMessageType(), withNSString: dialog.getText(), withInt: dialog.getRelatedUid());
if (UInt(dialog.getPeer().getPeerType().ordinal()) == AMPeerType.GROUP.rawValue){
if (MSG.getFormatter().isLargeDialogMessageWithAMContentTypeEnum(dialog.getMessageType())) {
self.messageView.text = text
} else {
self.messageView.text = MSG.getFormatter().formatPerformerNameWithInt(dialog.getSenderId()) + ": " + text
}
} else {
self.messageView.text = text
}
if (dialog.getDate() > 0) {
self.dateView.text = MSG.getFormatter().formatShortDateWithLong(dialog.getDate());
self.dateView.hidden = false;
} else {
self.dateView.hidden = true;
}
var messageState = UInt(dialog.getStatus().ordinal());
if (messageState == AMMessageState.PENDING.rawValue) {
self.statusView.tintColor = UIColor(red: 0, green: 0, blue: 0, alpha: 64/255.0)
self.statusView.image = Resources.iconClock;
self.statusView.hidden = false;
} else if (messageState == AMMessageState.READ.rawValue) {
self.statusView.tintColor = UIColor(red: 126/255.0, green: 168/255.0, blue: 239/255.0, alpha: 1.0)
self.statusView.image = Resources.iconCheck2;
self.statusView.hidden = false;
} else if (messageState == AMMessageState.RECEIVED.rawValue) {
self.statusView.tintColor = UIColor(red: 0, green: 0, blue: 0, alpha: 64/255.0)
self.statusView.image = Resources.iconCheck2;
self.statusView.hidden = false;
} else if (messageState == AMMessageState.SENT.rawValue) {
self.statusView.tintColor = UIColor(red: 0, green: 0, blue: 0, alpha: 64/255.0)
self.statusView.image = Resources.iconCheck1;
self.statusView.hidden = false;
} else if (messageState == AMMessageState.ERROR.rawValue) {
self.statusView.tintColor = UIColor(red: 210/255.0, green: 74/255.0, blue: 67/255.0, alpha: 64/255.0)
self.statusView.image = Resources.iconError;
self.statusView.hidden = false;
} else {
self.statusView.hidden = true;
}
self.separatorView.hidden = isLast;
}
override func layoutSubviews() {
super.layoutSubviews();
// We expect height == 76;
let width = self.contentView.frame.width;
let leftPadding = CGFloat(76);
let padding = CGFloat(14);
avatarView.frame = CGRectMake(padding, padding, 48, 48);
titleView.frame = CGRectMake(leftPadding, 18, width - leftPadding - /*paddingRight*/(padding + 50), 18);
var messagePadding:CGFloat = 0;
if (!self.statusView.hidden) {
messagePadding = 22;
statusView.frame = CGRectMake(leftPadding, 44, 20, 18);
}
messageView.frame = CGRectMake(leftPadding+messagePadding, 44, width - leftPadding - /*paddingRight*/padding - messagePadding, 18);
dateView.frame = CGRectMake(width - /*width*/60 - /*paddingRight*/padding , 18, 60, 18);
separatorView.frame = CGRectMake(leftPadding, 75.5, width, 0.5);
}
}<file_sep>/ActorClient/ActorClient/AvatarView.swift
//
// AvatarView.swift
// ActorClient
//
// Created by <NAME> on 13.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
import UIKit
// Cache
private let cacheSize = 10;
private let loadingPool = SThreadPool()
private var avatarCache = Dictionary<Int, SwiftlyLRU<Int64, UIImage>>()
private func checkCache(size: Int, id:Int64) -> UIImage? {
if let cache = avatarCache[size] {
if let img = cache[id] {
return img
}
}
return nil
}
private func putToCache(size: Int, id: Int64, image: UIImage) {
if let cache = avatarCache[size] {
cache[id] = image
} else {
var cache = SwiftlyLRU<jlong, UIImage>(capacity: cacheSize);
cache[id] = image
avatarCache.updateValue(cache, forKey: size)
}
}
class AvatarView : UIImageView {
var frameSize: Int = 0;
// Request
var bindedFileId: jlong! = nil;
var bindedTitle: String! = nil;
var bindedId: jint! = nil;
var requestId: Int = 0;
var callback: CocoaDownloadCallback? = nil;
init(frameSize: Int) {
self.frameSize = frameSize;
super.init(image: nil);
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
self.frameSize = Int(min(frame.width, frame.height))
}
func bind(title: String, id:jint, avatar: AMAvatar!) {
var fileLocation = avatar?.getSmallImage()?.getFileReference();
if (bindedId != nil && bindedId == id) {
var notChanged = true;
// Is Preview changed
notChanged = notChanged && bindedTitle.smallValue() == title.smallValue()
// Is avatar changed
if (fileLocation == nil) {
if (bindedFileId != nil) {
notChanged = false
}
} else if (bindedFileId == nil) {
if (fileLocation != nil) {
notChanged = false
}
} else {
if (bindedFileId != fileLocation?.getFileId()) {
notChanged = false
}
}
if (notChanged) {
return
}
}
unbind()
self.bindedId = id
self.bindedTitle = title
if (fileLocation == nil) {
// No avatar: Apply placeholder
self.image = Imaging.avatarPlaceholder(bindedId, size: frameSize, title: title.smallValue());
return
}
// Load avatar
var cached = checkCache(frameSize, Int64(fileLocation!.getFileId()))
if (cached != nil) {
self.image = cached
return
}
requestId++
var callbackRequestId = requestId
self.bindedFileId = fileLocation?.getFileId()
self.callback = CocoaDownloadCallback(onDownloaded: { (reference) -> () in
if (callbackRequestId != self.requestId) {
return;
}
var image = UIImage(contentsOfFile: CocoaFiles.pathFromDescriptor(reference));
if (image == nil) {
return
}
image = image!.roundImage(self.frameSize);
dispatch_async(dispatch_get_main_queue(), {
if (callbackRequestId != self.requestId) {
return;
}
putToCache(self.frameSize, Int64(self.bindedFileId!), image!)
self.image = image;
});
});
MSG.bindRawFileWith(fileLocation, withAutoStart: true, withCallback: self.callback)
}
func unbind() {
self.image = nil
self.bindedId = nil
self.bindedTitle = nil
if (bindedFileId != nil) {
MSG.unbindRawFile(bindedFileId!, withAutoCancel: false, withCallback: callback)
bindedFileId = nil
callback = nil
requestId++;
}
}
}<file_sep>/ActorClient/ActorClient/AvatarCell.swift
//
// AvatarCell.swift
// ActorClient
//
// Created by <NAME> on 17.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import UIKit
class AvatarCell: UITableViewCell {
@IBOutlet weak var avatarView: AvatarView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var subTitle: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func bind(user: AMUserVM) {
avatarView.bind(user.getName().get() as! String, id: user.getId(), avatar: user.getAvatar().get() as? AMAvatar)
title.text = user.getName().get() as! String
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>/ActorClient/ActorClient/GroupController.swift
//
// GroupControllerViewController.swift
// ActorClient
//
// Created by <NAME> on 23.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import UIKit
class GroupController: UIViewController {
let gid: Int
var group: AMGroupVM?;
var binder = Binder()
init(gid:Int) {
self.gid = gid
super.init(nibName: "GroupController", bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
group = MSG.getGroups().getWithLong(jlong(gid)) as! AMGroupVM;
binder.bind(group!.getName()!, closure: { (value:String?) -> () in
self.navigationItem.title = value
})
}
}
<file_sep>/ActorClient/ActorClient/Wrappers.swift
//
// Wrappers.swift
// ActorClient
//
// Created by <NAME> on 12.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
class CocoaCallback: NSObject, AMCommandCallback {
var resultClosure: ((val: AnyObject!) -> ())?;
var errorClosure: ((val:JavaLangException!) -> ())?;
init<T>(result: ((val:T?) -> ())?, error: ((val:JavaLangException!) -> ())?) {
super.init()
self.resultClosure = { (val: AnyObject!) -> () in
result?(val: val as? T)
}
self.errorClosure = error
}
func onResultWithId(res: AnyObject!) {
resultClosure?(val: res)
}
func onErrorWithJavaLangException(e: JavaLangException!) {
errorClosure?(val: e)
}
}
class CocoaDownloadCallback : NSObject, AMDownloadCallback {
let notDownloaded: (()->())?
let onDownloading: ((progress: Double) -> ())?
let onDownloaded: ((fileName: String) -> ())?
init(notDownloaded: (()->())?, onDownloading: ((progress: Double) -> ())?, onDownloaded: ((reference: String) -> ())?) {
self.notDownloaded = notDownloaded;
self.onDownloading = onDownloading;
self.onDownloaded = onDownloaded;
}
init(onDownloaded: (reference: String) -> ()) {
self.notDownloaded = nil;
self.onDownloading = nil;
self.onDownloaded = onDownloaded;
}
func onNotDownloaded() {
self.notDownloaded?();
}
func onDownloadingWithFloat(progress: jfloat) {
self.onDownloading?(progress: Double(progress));
}
func onDownloadedWithAMFileSystemReference(reference: AMFileSystemReference!) {
self.onDownloaded?(fileName: reference!.getDescriptor());
}
}
class CocoaUploadCallback : NSObject, AMUploadCallback {
let notUploaded: (()->())?
let onUploading: ((progress: Double) -> ())?
let onUploadedClosure: (() -> ())?
init(notUploaded: (()->())?, onUploading: ((progress: Double) -> ())?, onUploadedClosure: (() -> ())?) {
self.onUploading = onUploading
self.notUploaded = notUploaded
self.onUploadedClosure = onUploadedClosure;
}
func onNotUploading() {
notUploaded?();
}
func onUploaded() {
onUploadedClosure?()
}
func onUploadingWithFloat(progress: jfloat) {
onUploading?(progress: Double(progress))
}
}<file_sep>/ActorClient/ActorClient/CocoaMessenger.swift
//
// CocoaMessenger.swift
// ActorClient
//
// Created by <NAME> on 10.03.15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Foundation
private var holder:CocoaMessenger?;
var MSG : CocoaMessenger {
get{
if (holder == nil){
var dbPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
.UserDomainMask, true)[0].stringByAppendingPathComponent("actor.db");
// var db = FMDatabase(path: dbPath);
// db.open()
var builder = AMConfigurationBuilder();
// Providers
builder.setLogProvider(CocoaLogProvider())
builder.setNetworkProvider(SwiftCocoaNetworkProvider())
builder.setThreadingProvider(AMCocoaThreadingProvider())
builder.setStorageProvider(CocoaStorage(dbPath: dbPath))
builder.setMainThreadProvider(CocoaMainThreadProvider())
builder.setLocaleProvider(CocoaLocale())
builder.setPhoneBookProvider(CocoaPhoneBookProvider())
builder.setCryptoProvider(BCBouncyCastleProvider())
builder.setFileSystemProvider(CocoaFileSystem())
builder.setNotificationProvider(iOSNotificationProvider())
builder.setEnableNetworkLogging(true)
// Connection
builder.addEndpoint("tcp://mtproto-api.actor.im:8080");
var value: UInt8 = 0xFF
var convHash = IOSByteArray.newArrayWithLength(32)
var buf = UnsafeMutablePointer<UInt8>(convHash.buffer());
for i in 1..<32 {
buf.memory = UInt8(arc4random_uniform(255));
buf++;
// convHash.buffer()[i] = jbyte(0xFF);
}
builder.setApiConfiguration(AMApiConfiguration(NSString: "Actor iOS", withInt: 1, withNSString: "???", withNSString: "My Device", withByteArray: convHash))
holder = CocoaMessenger(AMConfiguration: builder.build());
}
return holder!;
}
}
@objc class CocoaMessenger : AMMessenger {
class func messenger() -> CocoaMessenger { return MSG }
func sendUIImage(image: UIImage, peer: AMPeer) {
var thumb = image.resizeSquare(90, maxH: 90);
var resized = image.resizeOptimize(1200 * 1200);
var thumbData = UIImageJPEGRepresentation(thumb, 0.55);
NSLog("Thumb size \(thumbData.length), \(thumb.size.width * thumb.scale)x\(thumb.size.height * thumb.scale)");
var descriptor = "/tmp/"+NSUUID().UUIDString
var path = CocoaFiles.pathFromDescriptor(descriptor);
UIImageJPEGRepresentation(resized, 0.80).writeToFile(path, atomically: true)
MSG.sendPhotoWithAMPeer(peer, withNSString: "image.jpg", withInt: jint(resized.size.width), withInt: jint(resized.size.height), withAMFastThumb: AMFastThumb(int: jint(thumb.size.width), withInt: jint(thumb.size.height), withByteArray: thumbData.toJavaBytes()), withAMFileSystemReference: CocoaFile(path: descriptor))
}
}<file_sep>/ActorClient/ActorClient/BubbleUnsupportedCell.swift
//
// BubbleUnsupportedContent.swift
// ActorClient
//
// Created by <NAME> on 22.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
class BubbleUnsupportedCell : BubbleCell {
class func measureUnsupportedHeight(message: AMMessage) -> CGFloat {
return 100+8;
}
let bubble = UIImageView()
let unsupportedLabel = UILabel()
var isOut = true
override init(reuseId: String) {
super.init(reuseId: reuseId)
bubble.image = UIImage(named: "conv_media_bg")
unsupportedLabel.text = "Unsupported content"
unsupportedLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
unsupportedLabel.textAlignment = NSTextAlignment.Center
contentView.addSubview(bubble)
contentView.addSubview(unsupportedLabel)
self.backgroundColor = UIColor.clearColor();
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func bind(message: AMMessage, reuse: Bool) {
self.isOut = message.getSenderId() == MSG.myUid()
}
override func layoutSubviews() {
super.layoutSubviews()
let padding = CGFloat(10)
var width = contentView.frame.width
var height = contentView.frame.height
if (self.isOut) {
self.bubble.frame = CGRectMake(width - 180 - padding, 4, 180, 100)
} else {
self.bubble.frame = CGRectMake(padding, 4, 180, 100)
}
self.unsupportedLabel.frame = self.bubble.frame
}
}<file_sep>/ActorClient/ActorClient/BubbleServiceCell.swift
//
// BubbleServiceCell.swift
// ActorClient
//
// Created by <NAME> on 19.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
private let maxServiceTextWidth = 260
private let serviceBubbleFont = UIFont(name: "HelveticaNeue-Medium", size: 12)!
private func measureText(message: String) -> CGRect {
var messageValue = message as NSString;
var style = NSMutableParagraphStyle();
style.lineBreakMode = NSLineBreakMode.ByWordWrapping;
var size = CGSize(width: maxServiceTextWidth, height: 0);
var rect = messageValue.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: serviceBubbleFont, NSParagraphStyleAttributeName: style], context: nil);
return CGRectMake(0, 0, round(rect.width), round(rect.height))
}
class BubbleServiceCell : BubbleCell {
class func measureServiceHeight(message: AMMessage) -> CGFloat {
var text = MSG.getFormatter().formatFullServiceMessageWithInt(message.getSenderId(), withAMServiceContent: message.getContent() as! AMServiceContent);
return measureText(text).height + 16
}
var serviceText = UILabel()
var serviceBg = UIImageView()
override init(reuseId: String) {
super.init(reuseId: reuseId)
serviceText.lineBreakMode = .ByWordWrapping;
serviceText.numberOfLines = 0;
serviceText.textColor = UIColor.whiteColor()
serviceText.contentMode = UIViewContentMode.Center
serviceText.textAlignment = NSTextAlignment.Center
serviceText.font = serviceBubbleFont;
serviceBg.image = UIImage(named: "bubble_service_bg");
self.contentView.addSubview(serviceBg)
self.contentView.addSubview(serviceText)
self.backgroundColor = UIColor.clearColor();
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func bind(message: AMMessage, reuse: Bool) {
serviceText.text = MSG.getFormatter().formatFullServiceMessageWithInt(message.getSenderId(), withAMServiceContent: message.getContent() as! AMServiceContent)
}
override func layoutSubviews() {
serviceText.frame = CGRectMake((self.contentView.frame.width - CGFloat(maxServiceTextWidth)) / 2.0, 0.0, CGFloat(maxServiceTextWidth), self.contentView.frame.height);
serviceText.sizeToFit()
serviceText.frame = CGRectMake( (self.contentView.frame.width - serviceText.frame.width) / 2, (self.contentView.frame.height - serviceText.frame.height) / 2, serviceText.frame.width, serviceText.frame.height)
serviceBg.frame = CGRectMake(serviceText.frame.origin.x - 8, serviceText.frame.origin.y - 3,
serviceText.frame.width + 16, serviceText.frame.height + 6)
}
}<file_sep>/ActorClient/ActorClient/PlaceHolderController.swift
//
// PlaceHolderController.swift
// ActorClient
//
// Created by <NAME> on 12.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
import UIKit;
class PlaceHolderController : UIViewController {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
initCommon();
}
init() {
super.init(nibName: "DiscoverViewController", bundle: nil)
initCommon();
}
func initCommon(){
tabBarItem = UITabBarItem(title: nil,
image: nil,
selectedImage: nil);
tabBarItem.enabled = false;
}
}<file_sep>/ActorClient/ActorClient/SearchSource.swift
//
// SearchSource.swift
// ActorClient
//
// Created by <NAME> on 23.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
class SearchSource: NSObject, UISearchBarDelegate, UISearchDisplayDelegate, UITableViewDataSource, AMDisplayList_Listener {
private var displayList: AMBindedDisplayList!;
private let searchDisplay: UISearchDisplayController
init(searchDisplay: UISearchDisplayController){
self.searchDisplay = searchDisplay;
super.init()
self.displayList = buildDisplayList()
self.displayList.addListenerWithAMDisplayList_Listener(self)
searchDisplay.searchBar.delegate = self
searchDisplay.searchResultsDataSource = self
searchDisplay.delegate = self
}
func close() {
self.displayList.removeListenerWithAMDisplayList_Listener(self)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section != 0) {
return 0;
}
return Int(displayList.getSize());
}
func onCollectionChanged() {
searchDisplay.searchResultsTableView.reloadData()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var item: AnyObject? = objectAtIndexPath(indexPath)
var cell = buildCell(tableView, cellForRowAtIndexPath:indexPath, item:item);
bindCell(tableView, cellForRowAtIndexPath: indexPath, item: item, cell: cell);
displayList.touchWithInt(jint(indexPath.row))
return cell;
}
func buildDisplayList() -> AMBindedDisplayList {
fatalError("Not implemented");
}
func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell {
fatalError("Not implemented");
}
func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) {
fatalError("Not implemented");
}
func objectAtIndexPath(indexPath: NSIndexPath) -> AnyObject? {
return displayList.getItemWithInt(jint(indexPath.row));
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
var normalized = searchText.trim()
if (normalized.size() > 0) {
displayList.initSearchWithNSString(normalized, withBoolean: false)
} else {
displayList.initTopWithBoolean(false)
}
}
func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController) {
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true)
}
func searchDisplayControllerWillEndSearch(controller: UISearchDisplayController) {
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
}
func searchDisplayController(controller: UISearchDisplayController, didShowSearchResultsTableView tableView: UITableView) {
for v in tableView.subviews {
if (v is UIImageView) {
(v as! UIImageView).alpha = 0;
}
}
}
}<file_sep>/ActorClient/ActorClient/MessagesViewController.swift
//
// MessagesViewController.swift
// ActorClient
//
// Created by <NAME> on 11.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
import UIKit
import MobileCoreServices
class MessagesViewController: EngineSlackListController, UIDocumentPickerDelegate, ABActionShitDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var peer: AMPeer!;
let binder: Binder = Binder();
let titleView: UILabel = UILabel();
let subtitleView: UILabel = UILabel();
let navigationView: UIView = UIView();
let avatarView = BarAvatarView(frameSize: 36)
init(peer: AMPeer) {
super.init(isInverted: true);
// Hack for fixing top offsets
self.edgesForExtendedLayout = UIRectEdge.All ^ UIRectEdge.Top;
self.peer = peer;
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None;
self.tableView.backgroundColor = UIColor.clearColor();
self.tableView.allowsSelection = false;
self.tableView.tableHeaderView = UIView(frame:CGRectMake(0, 0, 100, 6));
self.textInputbar.backgroundColor = UIColor.whiteColor();
self.textInputbar.autoHideRightButton = false;
self.textView.placeholder = "Message";
self.rightButton.titleLabel?.text = "Send"
self.keyboardPanningEnabled = true;
self.leftButton.setImage(UIImage(named: "conv_attach"), forState: UIControlState.Normal)
// Title
navigationView.frame = CGRectMake(0, 0, 190, 44);
navigationView.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
titleView.frame = CGRectMake(0, 4, 190, 20)
titleView.font = UIFont(name: "HelveticaNeue-Medium", size: 17)!
titleView.adjustsFontSizeToFitWidth = false;
titleView.textColor = UIColor.whiteColor();
titleView.textAlignment = NSTextAlignment.Center;
titleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail;
titleView.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
subtitleView.frame = CGRectMake(0, 22, 190, 20);
subtitleView.font = UIFont.systemFontOfSize(13);
subtitleView.adjustsFontSizeToFitWidth=false;
subtitleView.textColor = Resources.SecondaryLightText
subtitleView.textAlignment = NSTextAlignment.Center;
subtitleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail;
subtitleView.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
navigationView.addSubview(titleView);
navigationView.addSubview(subtitleView);
self.navigationItem.titleView = navigationView;
// Avatar
avatarView.frame = CGRectMake(0, 0, 36, 36)
var tapGesture = UITapGestureRecognizer(target: self, action: "onAvatarTap");
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
avatarView.addGestureRecognizer(tapGesture)
var barItem = UIBarButtonItem(customView: avatarView)
self.navigationItem.rightBarButtonItem = barItem
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated);
textView.text = MSG.loadDraft(peer);
var image = UIImage(named: "ChatBackground");
var bg = UIImageView(image: UIImage(named: "ChatBackground"));
view.insertSubview(bg, atIndex: 0);
// Installing bindings
if (UInt(peer.getPeerType().ordinal()) == AMPeerType.PRIVATE.rawValue) {
let user = MSG.getUsers().getWithLong(jlong(peer.getPeerId())) as! AMUserVM;
var nameModel = user.getName() as AMValueModel;
binder.bind(nameModel, closure: { (value: NSString?) -> () in
self.titleView.text = String(value!);
self.navigationView.sizeToFit();
})
binder.bind(user.getAvatar(), closure: { (value: AMAvatar?) -> () in
self.avatarView.bind(user.getName().get() as! String, id: user.getId(), avatar: value)
})
binder.bind(MSG.getTyping(peer.getPeerId())!.getTyping(), valueModel2: user.getPresence()!, closure:{ (typing:JavaLangBoolean?, presence:AMUserPresence?) -> () in
if (typing != nil && typing!.booleanValue()) {
self.subtitleView.text = MSG.getFormatter().formatTyping();
self.subtitleView.textColor = Resources.PrimaryLightText
} else {
var stateText = MSG.getFormatter().formatPresenceWithAMUserPresence(presence, withAMSexEnum: user.getSex())
self.subtitleView.text = stateText;
var state = UInt(presence!.getState().ordinal())
if (state == AMUserPresence_State.ONLINE.rawValue) {
self.subtitleView.textColor = Resources.PrimaryLightText
} else {
self.subtitleView.textColor = Resources.SecondaryLightText
}
}
})
} else if (UInt(peer.getPeerType().ordinal()) == AMPeerType.GROUP.rawValue) {
let group = MSG.getGroups().getWithLong(jlong(peer.getPeerId())) as! AMGroupVM;
var nameModel = group.getName() as AMValueModel;
binder.bind(nameModel, closure: { (value: NSString?) -> () in
self.titleView.text = String(value!);
self.navigationView.sizeToFit();
})
binder.bind(group.getAvatar(), closure: { (value: AMAvatar?) -> () in
self.avatarView.bind(group.getName().get() as! String, id: group.getId(), avatar: value)
})
binder.bind(MSG.getGroupTyping(group.getId()).getActive()!, valueModel2: group.getMembers(), valueModel3: group.getPresence(), closure: { (value1:IOSIntArray?, value2:JavaUtilHashSet?, value3:JavaLangInteger?) -> () in
if (value1!.length() > 0) {
self.subtitleView.textColor = Resources.PrimaryLightText
if (value1!.length() == 1) {
var uid = value1!.intAtIndex(0);
var user = MSG.getUsers().getWithLong(jlong(uid)) as! AMUserVM;
self.subtitleView.text = MSG.getFormatter().formatTypingWithNSString(user.getName().get() as!String)
} else {
self.subtitleView.text = MSG.getFormatter().formatTypingWithInt(value1!.length());
}
} else {
var membersString = MSG.getFormatter().formatGroupMembersWithInt(value2!.size())
if (value3 == nil || value3!.integerValue == 0) {
self.subtitleView.textColor = Resources.SecondaryLightText
self.subtitleView.text = membersString;
} else {
membersString = membersString + ", ";
var onlineString = MSG.getFormatter().formatGroupOnlineWithInt(value3!.intValue());
var attributedString = NSMutableAttributedString(string: (membersString + onlineString))
attributedString.addAttribute(NSForegroundColorAttributeName, value: Resources.PrimaryLightText, range: NSMakeRange(membersString.size(), onlineString.size()))
self.subtitleView.attributedText = attributedString
}
}
})
}
MSG.onConversationOpen(peer)
}
func onAvatarTap() {
if (UInt(peer.getPeerType().ordinal()) == AMPeerType.PRIVATE.rawValue) {
self.navigationController?.pushViewController(ProfileController(uid: Int(peer.getPeerId())), animated: true)
} else if (UInt(peer.getPeerType().ordinal()) == AMPeerType.GROUP.rawValue) {
self.navigationController?.pushViewController(GroupController(gid: Int(peer.getPeerId())), animated: true)
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
MSG.onConversationClosed(peer)
}
override func textWillUpdate() {
super.textWillUpdate();
MSG.onTyping(peer);
}
override func didPressRightButton(sender: AnyObject!) {
// Perform auto correct
textView.refreshFirstResponder();
MSG.sendMessage(peer, withText: textView.text);
super.didPressRightButton(sender);
}
override func didPressLeftButton(sender: AnyObject!) {
super.didPressLeftButton(sender)
var actionShit = ABActionShit()
actionShit.buttonTitles = ["Take Photo","Record Video", "Media Library", "Document"]
actionShit.cancelButtonTitle = "Cancel"
actionShit.delegate = self
actionShit.showWithCompletion(nil)
}
func actionShit(actionShit: ABActionShit!, clickedButtonAtIndex buttonIndex: Int) {
if (buttonIndex == 0) {
var pickerController = UIImagePickerController()
pickerController.sourceType = UIImagePickerControllerSourceType.Camera
pickerController.mediaTypes = [kUTTypeImage]
pickerController.view.backgroundColor = UIColor.blackColor()
pickerController.navigationBar.tintColor = Resources.TintColor
pickerController.delegate = self
pickerController.navigationBar.tintColor = UIColor.whiteColor()
pickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()];
self.presentViewController(pickerController, animated: true, completion: nil)
} else if (buttonIndex == 1) {
var pickerController = UIImagePickerController()
pickerController.sourceType = UIImagePickerControllerSourceType.Camera
pickerController.mediaTypes = [kUTTypeVideo, kUTTypeMovie]
pickerController.view.backgroundColor = UIColor.blackColor()
pickerController.navigationBar.tintColor = Resources.TintColor
pickerController.delegate = self
pickerController.navigationBar.tintColor = UIColor.whiteColor()
pickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()];
self.presentViewController(pickerController, animated: true, completion: nil)
} else if (buttonIndex == 2) {
var pickerController = UIImagePickerController()
pickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
pickerController.mediaTypes = [kUTTypeImage, kUTTypeVideo, kUTTypeMovie]
pickerController.view.backgroundColor = UIColor.blackColor()
pickerController.navigationBar.tintColor = Resources.TintColor
pickerController.delegate = self
pickerController.navigationBar.tintColor = UIColor.whiteColor()
pickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()];
self.presentViewController(pickerController, animated: true, completion: nil)
} else if (buttonIndex == 3) {
var documentView = UIDocumentPickerViewController(documentTypes: [kUTTypeText as NSString, "com.apple.iwork.pages.pages", "com.apple.iwork.numbers.numbers", "com.apple.iwork.keynote.key"], inMode: UIDocumentPickerMode.Import)
documentView.delegate = self
documentView.view.backgroundColor = UIColor.whiteColor()
self.presentViewController(documentView, animated: true, completion: nil)
}
}
// Image picker
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
picker.dismissViewControllerAnimated(true, completion: nil)
MSG.sendUIImage(image, peer: peer!)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
picker.dismissViewControllerAnimated(true, completion: nil)
MSG.sendUIImage(info[UIImagePickerControllerOriginalImage] as! UIImage, peer: peer!)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true, completion: nil)
}
// Document picker
func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
var path = url.path;
// TODO: Implement
}
override func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell {
var message = (item as! AMMessage);
if (message.getSenderId() != MSG.myUid()){
MSG.onInMessageShown(peer, withRid: message.getRid(), withDate: message.getDate(), withEncrypted: false);
}
if (message.getContent() is AMTextContent){
var cell = tableView.dequeueReusableCellWithIdentifier("bubble_text") as! BubbleTextCell?
if (cell == nil) {
cell = BubbleTextCell(reuseId: "bubble_text")
}
return cell!
} else if (message.getContent() is AMPhotoContent || message.getContent() is AMVideoContent) {
var cell = tableView.dequeueReusableCellWithIdentifier("bubble_media") as! BubbleMediaCell?
if (cell == nil) {
cell = BubbleMediaCell(reuseId: "bubble_media")
}
return cell!
} else if (message.getContent() is AMServiceContent){
var cell = tableView.dequeueReusableCellWithIdentifier("bubble_service") as! BubbleServiceCell?
if (cell == nil) {
cell = BubbleServiceCell(reuseId: "bubble_service")
}
return cell!
} else {
var cell = tableView.dequeueReusableCellWithIdentifier("bubble_unsupported") as! BubbleUnsupportedCell?
if (cell == nil) {
cell = BubbleUnsupportedCell(reuseId: "bubble_unsupported")
}
return cell!
}
}
override func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) {
(cell as! BubbleCell).performBind(item as! AMMessage);
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var item = objectAtIndexPath(indexPath) as! AMMessage;
return BubbleCell.measureHeight(item);
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated);
MSG.saveDraft(peer, withText: textView.text);
}
override func getDisplayList() -> AMBindedDisplayList {
return MSG.getMessagesGlobalListWithAMPeer(peer)
}
}
class BarAvatarView : AvatarView {
override init(frameSize: Int) {
super.init(frameSize: frameSize)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func alignmentRectInsets() -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 36, bottom: 0, right: 8)
}
}<file_sep>/ActorClient/Podfile
platform :ios, '7.0'
target 'ActorClient' do
# ABPhoneField dependency
pod 'RMPhoneFormat', :git => 'https://github.com/actorapp/RMPhoneFormat'
#pod 'SHSPhoneComponent'
# Model
pod 'MMMutableMethods', :git => 'https://github.com/k06a/MMMutableMethods', :branch => 'dev', :tag => '0.0.7'
pod 'J2ObjC', :git => 'https://github.com/actorapp/j2objc'
pod 'RegexKitLite', :inhibit_warnings => true
pod 'CocoaAsyncSocket'
pod 'FMDB'
# UI
pod 'VENTokenField'
pod 'AsyncDisplayKit'
pod 'SVProgressHUD'
pod 'MBProgressHUD'
pod 'PSTAlertController'
pod 'PHFComposeBarView'
pod 'DZNPhotoPickerController'
pod 'HockeySDK'
pod 'SlackTextViewController', :git => 'https://github.com/actorapp/SlackTextViewController'
end
target 'ActorClientTests' do
end
<file_sep>/ActorClient/ActorClient/CocoaStorage.swift
//
// CocoaStorage.swift
// ActorClient
//
// Created by <NAME> on 14.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
@objc class CocoaStorage : AMBaseStorageProvider {
let dbPath: String;
init(dbPath: String) {
self.dbPath = dbPath;
}
override func createPreferencesStorage() -> DKPreferencesStorage! {
return UDPreferencesStorage();
}
override func createKeyValue(name: String!) -> DKKeyValueStorage! {
return FMDBKeyValue(databasePath: dbPath, tableName: name);
}
override func createList(name: String!) -> DKListStorage! {
return FMDBList(databasePath: dbPath, tableName: name);
}
}<file_sep>/ActorClient/ActorClient/iOSNotificationProvider.swift
//
// iOSNotificationProvider.swift
// ActorClient
//
// Created by <NAME> on 17.03.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
import AVFoundation
@objc class iOSNotificationProvider: NSObject, AMNotificationProvider {
var internalMessage:SystemSoundID = 0
override init() {
super.init()
var path = NSBundle.mainBundle().URLForResource("notification", withExtension: "aiff");
AudioServicesCreateSystemSoundID(path, &internalMessage)
}
func onMessageArriveInApp() {
AudioServicesPlaySystemSound(internalMessage)
}
func onDialogsOpen() {
}
func onChatOpenWithAMPeer(peer: AMPeer!) {
}
func onNotificationWithJavaUtilList(topNotifications: JavaUtilList!, withInt messagesCount: jint, withInt conversationsCount: jint) {
}
}
<file_sep>/ActorClient/ActorClient/DialogsViewController.swift
//
// DialogsViewController.swift
// ActorClient
//
// Created by <NAME> on 10.03.15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class DialogsViewController: EngineListController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var loadingView: UIView!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
initCommon();
}
override init() {
super.init(nibName: "DialogsViewController", bundle: nil)
initCommon();
}
func initCommon(){
var icon = UIImage(named: "ic_letter_blue_24")!;
tabBarItem = UITabBarItem(title: nil,
image: icon.tintImage(Resources.BarTintUnselectedColor)
.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal),
selectedImage: icon);
tabBarItem.imageInsets=UIEdgeInsetsMake(6, 0, -6, 0);
}
override func buildDisplayList() -> AMBindedDisplayList {
return MSG.getDialogsGlobalList()
}
func toggleEdit() {
self.tableView.setEditing(!self.tableView.editing, animated: true);
}
func isTableEditing() -> Bool {
return self.tableView.editing;
}
override func viewDidLoad() {
tableView.backgroundColor = Resources.BackyardColor
// Footer
var footer = UIView(frame: CGRectMake(0, 0, 320, 80));
var footerHint = UILabel(frame: CGRectMake(0, 0, 320, 60));
footerHint.textAlignment = NSTextAlignment.Center;
footerHint.font = UIFont.systemFontOfSize(16);
footerHint.textColor = UIColor(red: 164/255.0, green: 164/255.0, blue: 164/255.0, alpha: 1)
footerHint.text = "Swipe for more options";
footer.addSubview(footerHint);
var shadow = UIImageView(image: UIImage(named: "CardBottom2"));
shadow.frame = CGRectMake(0, 0, 320, 4);
shadow.contentMode = UIViewContentMode.ScaleToFill;
footer.addSubview(shadow);
self.tableView.tableFooterView = footer;
var header = UIView(frame: CGRectMake(0, 0, 320, 0))
var headerShadow = UIImageView(frame: CGRectMake(0, -4, 320, 4));
headerShadow.image = UIImage(named: "CardTop2");
headerShadow.contentMode = UIViewContentMode.ScaleToFill;
header.addSubview(headerShadow);
self.tableView.tableHeaderView = header;
loadingView.hidden = true;
bindTable(tableView);
super.viewDidLoad();
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
MSG.onDialogsOpen();
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
var dialog = objectAtIndexPath(indexPath) as! AMDialog
execute(MSG.deleteChatWithAMPeer(dialog.getPeer()));
}
}
override func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell {
let reuseKey = "cell_dialog";
var cell = tableView.dequeueReusableCellWithIdentifier(reuseKey) as! DialogCell?;
if (cell == nil){
cell = DialogCell(reuseIdentifier: reuseKey);
cell?.awakeFromNib();
}
return cell!;
}
override func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) {
var dialog = item as! AMDialog;
let isLast = indexPath.row == tableView.numberOfRowsInSection(indexPath.section)-1;
(cell as! DialogCell).bindDialog(dialog, isLast: isLast);
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var dialog = objectAtIndexPath(indexPath) as! AMDialog;
self.navigationController?.pushViewController(MessagesViewController(peer: dialog.getPeer()), animated: true);
}
override func viewDidDisappear(animated: Bool) {
MSG.onDialogsClosed();
}
}
|
d15e82ff33d270a1ca3e3c6f88e331b69c127819
|
[
"Swift",
"Ruby"
] | 42
|
Swift
|
cgvarela/actor-ios-old
|
abce3b6e31e3e0c4c48cbe60eca10292c662b9b4
|
3fa8aabb91339c53bb7f23e32fdeb699ad5bf8bc
|
refs/heads/master
|
<repo_name>SAGAR-KALAL/warehouse<file_sep>/README.md
# warehouse
Team :-3Designers
1.<NAME> 2GI16CS119
2.<NAME> 2GI16CS120
3.<NAME> 2GI16CS169
<file_sep>/src/tempproj/Tempproj.java
package tempproj;
import java.util.Scanner;
/**
*
* @author <NAME>
*/
class FinishedProduct{
int productID;
String[] size={"LARGE","MEDIUM","SMALL"};
int quantity[]=new int[3];
int emplCount;
Scanner inp=new Scanner(System.in);
void addProduct(int pid,int s){
productID=pid;
//size[s]=s;
System.out.println("Enter the no.of products : ");
int data=0;
do{
data=inp.nextInt();
if(data<=0)
System.out.println("Quantity need to be more than 0");
}
while(data<=0);
quantity[s]+=data;
}
void removeProduct(int pid,int s){
int data=0;
int flag=0;
do{
System.out.println("Enter the no.of products to be removed: ");
data=inp.nextInt();
if(data<=0)
System.out.println("Quantity need to be more than 0");
else if(data>quantity[s]){
System.out.println("Insufficient no. of products in the warehouse");
displayInfo();
System.out.println("Willing to unload less no. of products");
System.out.println("Press\n 1:YES \n 0:NO");
boolean choice=true;
int value=inp.nextInt();
if(quantity[s]==0 && value==1){
System.out.println("There are no products in the storage location");
break;
}
if(value==0){
choice=false;
flag=1;
}
if(!choice)
break;
}
}
while(data<0 || data>quantity[s]);
if(quantity[s]!=0 && flag==0)
quantity[s]-=data;
}
void allotEmployee(){
int eval;
int extra;
int i;
for(i=0;i<=2;i++){
eval=quantity[i]/100;
extra=quantity[i]%100;
switch(i){
case 0:eval=eval*4;
if(extra!=0 && extra<50)
extra=2;
else if(extra>=50)
extra=4;
break;
case 1:eval=eval*3;
if(extra!=0 && extra<50)
extra=2;
else if(extra>=50)
extra=3;
break;
case 2:eval=eval*2;
if(extra!=0 && extra<50)
extra=1;
else if(extra>=50)
extra=2;
break;
}
System.out.println("Eval="+eval);
System.out.println("Extra="+extra);
emplCount+=eval+extra;
}
}
void displayInfo(){
System.out.println("Product ID is: "+productID);
System.out.println("Product Details are:");
System.out.println("SIZE\t QUANTITY\t");
System.out.println("------------------------");
for(int i=0;i<=2;i++){
System.out.println(size[i]+"\t"+quantity[i]);
}
allotEmployee();
System.out.println("Employees count is: "+emplCount );
}
}
public class Tempproj {
public static void main(String[] args) {
int choice;
Scanner inp=new Scanner(System.in);
for(;;){
System.out.println("THE WAREHOUSE CONTAINS\n1.Basic Materials\n"
+ "2.Fabricated parts\n3.Finished Products\n4.Exit Enter your choice:");
choice=inp.nextInt();
switch(choice){
case 1:
//TODO Basic material code is to be fixed!!
break;
case 2:
//TODO Fabricated parts code is to be fixed!!
break;
case 3:
int i;
FinishedProduct fp[]=new FinishedProduct[10];
for(i=0;i<fp.length;i++){
fp[i]=new FinishedProduct();
}
for(;;){
System.out.println("\nYou are dealing with Storage area of Finished Products!!!");
System.out.println("Permitted product IDs are 100-109");
System.out.println("Available choices to deal with particular product are \n"
+ " 1.Add/update any product\n"
+ " 2.Remove the product\n"
+ " 3.Employee Count \n"
+ " 4.Display product details\n"
+ " 5.Go back to main menu\n"
+ "Choose your option :");
choice=inp.nextInt();
int proID,pos;
int size;
switch(choice){
case 1:
proID=acceptPID();
System.out.println("Size Menu Includes: \n 0.Large\n 1.Medium\n 2.Small\n"
+ "Choose the size of the product to be added(0,1,2 only permitted) :");
size=inp.nextInt();
pos=proID%100;
for(i=0;i<fp.length;i++){
if(i==pos){
fp[i].addProduct(proID, size);
fp[i].allotEmployee();
break;
}
}
break;
case 2:
proID=acceptPID();
System.out.println("Size Menu Includes: \n 0.Large\n 1.Medium\n 2.Small\n"
+ "Choose the size of the product to be removed(0-2) :");
size=inp.nextInt();
pos=proID%100;
for(i=0;i<fp.length;i++){
if(i==pos){
fp[i].removeProduct(proID, size);
fp[i].allotEmployee();
break;
}
}
break;
case 3:
int ecount=0;
for(i=0;i<fp.length;i++){
ecount+=fp[i].emplCount;
}
System.out.println("Total number of employees in the warehouse=" +ecount);
break;
case 4:
proID=acceptPID();
pos=proID%100;
fp[pos].displayInfo();
break;
}
if(choice==5)
break;
}
break;
case 4:System.exit(0);
}
}
}
static int acceptPID(){
int proID;
Scanner inp=new Scanner(System.in);
System.out.println("Enter the product ID :");
do{
proID=inp.nextInt();
if(proID>109 || proID<100){
System.out.println("Enter a valid product ID (100-109)");
}
}while(proID>109 || proID<100);
return proID;
}
}
|
06c4bf62e2dedff0b2bdd1e7a4dd545ae57d1b57
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
SAGAR-KALAL/warehouse
|
9a6a63b44558875ef600bf6279fb93d269dc6f0e
|
af1cd13f86767a95a14999066be25e0285241240
|
refs/heads/main
|
<file_sep># Niconicoment
display comment on browser like niconico video
|
7626b94167d112da088b33195f26881d78133b0d
|
[
"Markdown"
] | 1
|
Markdown
|
rinoguchi/niconicoment
|
996754322a3dc3efaf6ca6eb48fd2dc33afeac88
|
17dd9ec1ba48c9ab65e4d4e37978ba09256604ad
|
refs/heads/master
|
<file_sep>#pragma once
#include "Publication.h"
class Magazine : public Publication{
public:
Magazine() = default;
virtual std::string DOI(){
return _m + _DOINumber;
}
protected:
std::string _m = "M";
};<file_sep>#pragma once
#include "Page.h"
class TitlePage : public Page {
public:
TitlePage(std::string text, std::string header, std::string author, std::string subTitle) : Page(text, header), _author(author), _subTitle(subTitle) {}
TitlePage(): Page("empty", "empty"), _author("empty"), _subTitle("empty"){}
void SetAuthor(std::string author){
_author = author;
}
void SetSubTitle(std::string subTitle){
_subTitle = subTitle;
}
std::string getAuthor()const {
return _author;
}
std::string getSubTitle()const {
return _subTitle;
}
private:
std::string _author;
std::string _subTitle;
};<file_sep>#pragma once
#include "Main.h"
class Gps : public Coordinate{
public:
Gps() : Coordinate(0, 0){}
Gps(float longitude, float latitude): Coordinate(longitude, latitude) {}
Coordinate Location(float longitude, float latitude){
Latitude(latitude);
Longitude(longitude);
return Coordinate(longitude, latitude);
};
Coordinate LocationInfo(){
return Coordinate(m_longitude, m_latitude);
}
private:
};<file_sep>#pragma once
#include "Gps.h"
#include "TrackingSystem.h"
class TrackingUnit: public Gps, public TrackingSystem{
public:
TrackingUnit(std::string dir = "South") : Compass(dir) {}
std::string CompassDirection()const {
return "TUnit/" + _dir;
}
void Start(){
_start = _coordinates;
}
float Distance()const{
return _distance;
}
void Location(const Coordinate& location){
_coordinates.Longitude(location.Longitude());
_coordinates.Latitude(location.Latitude());
}
std::string LocationInfo()const{
return "Longitude: " + std::to_string(_coordinates.Longitude()) + " Latitude: " + std::to_string(_coordinates.Latitude());
}
void Go(float distance, std::string dir){
_coordinates.MoveInDirection(distance, dir);
_distance = Haversine(_start.Longitude(),_start.Latitude(), _coordinates.Longitude(), _coordinates.Latitude());;
}
private:
float _distance = 0;
Coordinate _start;
};
<file_sep>#pragma once
#include "Haversine.h"
#include <string>
class Compass{
public:
Compass(std::string dir ="West") : _dir(dir) {}
virtual std::string CompassDirection()const{
return "C/" + _dir;
}
static std::string West(){
return "West";
}
static std::string East(){
return "East";
}
static std::string South(){
return "South";
}
static std::string North(){
return "North";
}
protected:
std::string _dir;
};
<file_sep>#pragma once
#include <iostream>
#include <string>
class Samochod{
public:
Samochod(std::string marka = "", std::string model = "") : _marka(marka), _model(model) {}
void print() const{
std::cout << _marka << " : " << _model << std::endl;
}
private:
std::string _marka;
std::string _model;
};<file_sep>#pragma once
#include <string>
#include <iostream>
//Klasa reprezentująca pmieszczenie
class Pomieszczenie{
public:
//Konstruktor przyjmujący nazwę pomieszczenia
//Konstruktor jest głośny, tzn wypisuje informacje o
//tworzeniu obiektu
Pomieszczenie(std::string name) : _name(name) {
std::cout << "Tworze pomieszczenie: " << _name << std::endl;
}
//Metoda zetrzyj_kurze
//Wypisuje tekst oraz nazwę pomieszczenia
//w którym ściera kurze
void zetrzyj_kurze() const {
std::cout << "Scieram kurze w pomieszczeniu: " << _name << std::endl;
}
//Metoda umyj_podloge
//Wypisuje tekst oraz nazwę pomieszczenia
//w którym myje podłogę
void umyj_podloge() const{
std::cout << "Myje podlogew pomieszczeniu: " << _name << std::endl;
}
//Metoda okurz
//Wypisuje tekst oraz nazwę pomieszczenia
//w którym odkurza
void odkurz() const{
std::cout << "Odkurzam pomieszczenie: " << _name << std::endl;
}
//Metoda szablonowa wstaw
//wstawia wartość typu T do pomieszczenia
template<typename T>
void wstaw(T wartosc){
std::cout << "Wtawiam " << wartosc << " do pomieszczenia: " << _name << std::endl;
}
private:
std::string _name;
};
/*
ogólny wskaźnik na medotę void która nie przyjmuje argumentów i jest const!! w klasie pomieszczeni
Lokaj przyjmuje obiekt na którym chcemy wywołać tę funkcję
lokaj przyjmuje obiekt który jest const
*/
template<void (Pomieszczenie::*T)() const>
void Lokaj(const Pomieszczenie &room){
std::cout << "Pomieszczenie jest zamkniete\n";
}
template<int>
void Lokaj(const Pomieszczenie &room){
std::cout << "Nic nie robie" << std::endl;
}
//Rozni sie tylko tym ze lokaj przyjmuje obiekt nie const
template<void (Pomieszczenie::*T)() const>
void Lokaj(Pomieszczenie &room){
(room.*T)();
}<file_sep>#pragma once
#include "Publication.h"
class Book : public Publication{
public:
Book() = default;
virtual std::string DOI(){
return _b + _DOINumber;
}
protected:
std::string _b= "B";
};<file_sep>#pragma once
#include "Page.h"
class A4Page: public Page{
public:
A4Page(std::string title): Page(title) {}
A4Page(): Page("empty") {}
};
<file_sep>#pragma once
#include "B5Page.h"
#include "TitlePage.h"
#include <vector>
#include "A4Page.h"
#include "Publication.h"
class Book : public Publication{
public:
friend std::ostream& operator<<(std::ostream& stream, const Book& book);
Book(std::string title, int numpages, std::string format): _title(title), _numberpages(numpages), _format(format) {
_pages.push_back(new TitlePage());
for(int i =0; i < _numberpages - 1; i++ ){
if(format == "B5")
_pages.push_back(new B5Page());
if(format == "A4")
_pages.push_back(new A4Page());
}
}
~Book(){
for(auto i : _pages){
delete i; //zawsze wywola odpowidni bo zrobilismy wirtualny destruktor
}
}
TitlePage* TitlePagePtr(){
return static_cast<TitlePage*>(_pages.at(0)); //statiic cast bo zapewniam ze titlepage jest na pierwszym miejscu
}
void operator++(){
_pages.push_back(new B5Page());
}
const Book& operator=(const Book& K){
if( this != &K){
if(_format != K._format)
std::cout << "[ERROR]:: Trying to assign different formats!" << std::endl;
else
_numberpages = K._numberpages;
}
return *this;
}
int NPages() const override{
return _pages.size();
}
private:
std::string _title;
int _numberpages;
std::string _format;
std::vector <Page*> _pages;
};
<file_sep>#pragma once
#include "Page.h"
class TitlePage : public Page {
public:
TitlePage(std::string title) : Page(title) {}
TitlePage(): Page("empty") {}
};<file_sep>CXX=g++
CPPFLAGS=-Wall $(GXX_FLAGS)
CPPFLAGS+=-g
DEP_FLAGS=-MMD
DEP_FLAGS+=-MP
SRC=$(wildcard *.cpp)
H=$(SRC:.cpp=.h)
OBJ=$(SRC:.cpp=.o)
DEP=$(SRC:.cpp=.d)
CPPFLAGS+=$(DEP_FLAGS)
HEAD=$(filter-out main.h, $(H))
EXE_NAME=Gps
all: program
# compile all files
program: $(OBJ)
$(CXX) $(LFLAGS) $(OBJ) -o $(EXE_NAME)
.PHONY: clean run debug
# clean trash files
clean:
@rm -f $(EXE_NAME) $(OBJ) $(DEP)
# run app
run: program
./$(EXE_NAME)
# run gdb debuger
debug: program
gdb $(EXE_NAME)
val: program
valgrind ./$(EXE_NAME)
-include $(DEP)
<file_sep>#pragma once
#include "Main.h"
class Distance {
public:
Distance(Coordinate& city1, Coordinate& city2): Distance (city1.Longitude(), city1.Latitude(), city2.Longitude(), city2.Latitude()){}
Distance(float x1, float y1, float x2, float y2){
_distance=Haversine(x1, y1, x2, y2);
}
~Distance()=default;
float Value(){return _distance;}
private:
float _distance;
};<file_sep>#pragma once
#include "Compass.h"
class TrackingSystem: public virtual Compass {
public:
TrackingSystem(std::string dir="North") :Compass(dir) {}
std::string CompassDirection()const {
return "TS/" + _dir;
}
};
<file_sep>#pragma once
#include "Page.h"
class B5Page: public Page{
public:
B5Page(std::string title): Page(title) {}
B5Page(): Page("empty") {}
};
<file_sep>#pragma once
#include <iostream>
//Klasa reprezentująca punkt na płaszczyznie 2d
class Punkt{
public:
//Konstruktor obiektu klasy punkt
//x- pierwsza współrzędna punktu
//y - druga współrzędna punktu
Punkt(int x, int y) : m_x(x), m_y(y) {}
//Metoda szablonowa wsp
//W przypadku a = 0 zwraca pierwszą współrzędną punktu
//W przypasku a = 1 zwraca drugą współrzędną punktu
template<int a> int wsp() const;
//Metoda szablonowa min
//Zwraca minimalny element z dwóch porównywanych a lub b
template<typename T> static T min(const T& a,const T& b);
//Metoda szablonowa max
//Zwraca maksymalny element z dwoch porównywanych a lub b
template<typename T> static T max(const T& a,const T& b);
//Operator <
//Sprawdza czy wpółrzędne punktu są mniejsze od parametru other
bool operator < (const Punkt& other) const;
private:
int m_x;
int m_y;
};
template<int a>
int Punkt::wsp() const{
if(a == 0)
return m_x;
else return m_y;
}
bool Punkt::operator < (const Punkt& other) const{
if(m_x > other.m_x)
return false;
else if(m_x == other.m_x)
if(m_y >= other.m_y)
return false;
return true;
}
template<typename T>
T Punkt::min(const T& a,const T& b){
return (a < b) ? a : b;
}
template<typename T>
T Punkt::max(const T& a,const T& b){
return (a < b) ? b : a;
}<file_sep>#include "Publication.h"
#include <iostream>
#include "Book.h"
Publication* Publication::Create(std::string type, int num, std::string format){
return new Book(type, num, format);
}
<file_sep>#pragma once
#include "Samochod.h"
//Klasa reprezentująca fabrykę
class Fabryka{
public:
//Metoda szablonowa prototyp
//Zwraca statyczną zmienną Typu T
template<typename T> T prototyp(T value, bool czyZmieniac = true);
template<typename T> T produkuj();
};
template<typename T>
T Fabryka::prototyp(T value, bool czyZmieniac){
static T zmienna;
if(czyZmieniac)
zmienna = value;
return zmienna;
}
template<typename T>
T Fabryka::produkuj(){
return prototyp(T(), false);
}
<file_sep>#pragma once
#include "Page.h"
class A4Page: public Page{
public:
A4Page(std::string text, std::string header): Page(text, header) {}
A4Page(): Page("empty", "empty") {}
};
<file_sep>#pragma once
#include <iostream>
#include <string>
class Page{
public:
Page(std::string text, std::string header): _text(text), _header(header) {}
virtual ~Page() = default;
virtual std::string Text()const {return _text;}
void SetHeader(std::string header){
_header = header;
}
virtual void Text(std::string text){
_text = text;
}
protected:
std::string _text;
std::string _header;
};<file_sep>#pragma once
#include <iostream>
#include <string>
class Page{
public:
Page(std::string title): _title(title) {}
virtual ~Page() = default;
virtual std::string GetTitle() const{
return _title;
}
virtual void SetTitle(std::string title){
_title = title;
}
protected:
std::string _title;
};<file_sep>#pragma once
#include "Haversine.h"
#include "Compass.h"
#include <string>
class Gps: public virtual Compass{
public:
Gps (std::string city ="East", float longitude = 0, float latitude = 0) : _city(city) {
_coordinates.Longitude(longitude);
_coordinates.Latitude(latitude);
}
std::string GetCity()const{
return _city;
}
void SetCity(std::string& city){
_city = city;
}
void UpdateLocation(float longitude, float latitude){
_coordinates.Longitude(longitude);
_coordinates.Latitude(latitude);
}
Coordinate& Coordintes(){
return _coordinates;
}
std::string GpsLoc()const{
return "Longitude: " + std::to_string(_coordinates.Longitude()) + " Latitude: " + std::to_string(_coordinates.Latitude());
}
std::string CompassDirection()const {
return "G/" + _dir;
}
Coordinate Location()const{
return _coordinates;
}
protected:
std::string _city;
Coordinate _coordinates;
};
<file_sep>#pragma once
#include <iostream>
#include <string>
class Publication{
public:
Publication(){
}
virtual ~Publication() = default;
static Publication* Create(std::string type, int num, std::string format);
virtual int NPages() const= 0;
protected:
};
<file_sep>#include "Publication.h"
#include <iostream>
#include "Magazine.h"
#include "Book.h"
Publication* Publication::Create(std::string type, int num, std::string format){
if(type == "Book"){return new Book();}
else if( type == "Magazine") { return new Magazine();}
else return 0;
}
<file_sep>#pragma once
#include <iostream>
#include <string>
class Page{
public:
Page(std::string text, std::string header): _text(text), _header(header) {}
virtual ~Page() = default;
inline std::string getHeader()const {return _header;}
inline std::string getText()const {return _text;}
void SetHeader(std::string header){
_header = header;
}
void setText(std::string text){
_text = text;
}
protected:
std::string _text;
std::string _header;
};<file_sep>#pragma once
#include <iostream>
#include <string>
class Publication{
public:
Publication(){
_DOINumber = "/00.0000/000";
}
virtual ~Publication() = default;
static Publication* Create(std::string type, int num, std::string format);
virtual std::string DOI() = 0;
protected:
std::string _DOINumber;
};
<file_sep>#pragma once
#include "Pomieszczenie.h"<file_sep>#pragma once
#include "B5Page.h"
#include "TitlePage.h"
#include <vector>
class Book{
public:
friend std::ostream& operator<<(std::ostream& stream, const Book& book);
Book(std::string title, int numpages, std::string format): _title(title), _numberpages(numpages), _format(format) {
_pages.push_back(new TitlePage());
for(int i =0; i < _numberpages; i++ ){
_pages.push_back(new B5Page());
}
}
~Book(){
for(auto i : _pages){
delete i; //zawsze wywola odpowidni bo zrobilismy wirtualny destruktor
}
}
int size(){
return _numberpages +1;
}
TitlePage* TitlePagePtr(){
return static_cast<TitlePage*>(_pages.at(0)); //statiic cast bo zapewniam ze titlepage jest na pierwszym miejscu
}
Page* operator[](int i){
return _pages.at(i-1);
}
private:
std::string _title;
int _numberpages;
std::string _format;
std::vector <Page*> _pages;
};
std::ostream &operator<<(std::ostream &stream, const Book &book)
{
stream << "[Book::Title] " << book._title << "(" << dynamic_cast<TitlePage*>(book._pages.at(0))->getSubTitle() << ")" <<std::endl;
stream << "[Book::Author] "<< dynamic_cast<TitlePage*>(book._pages.at(0))->getAuthor()<< std::endl;
for(int i = 0; i < (int)book._pages.size()-1; i++){
if(book._pages[i]->getHeader() != "empty"){
stream <<"[Page(" << i << ")::header] " <<book._pages[i]->getHeader() << std::endl;
}
stream << "[Page(" << i << ")::text] " << book._pages[i]->getText() << std::endl;
}
return stream;
}
|
0de7d22f5b477a25504412f68626fc74cf0faa35
|
[
"C",
"Makefile",
"C++"
] | 28
|
C++
|
przemyslawmarkiewicz/PO1LAB
|
e0d7704201d7361101f8f5c149b0e2779f5c67ab
|
47879c6e6a88c37fb471d9eec3d8c82e2dc78451
|
refs/heads/master
|
<file_sep>//
// MySwiftSecond.swift
// SwfitTest
//
// Created by kingcode on 15/9/26.
// Copyright (c) 2015年 kingcode. All rights reserved.
//
import Foundation
// 函数
// 函数嵌套
func chosseSetp(backWard:Bool)->(Int)->Int{
func setpForward(input:Int)->Int{
return input + 1
}
func setpBack(input:Int)->Int{
return input - 1
}
// 这里注意严格的空格
return backWard ? setpForward:setpBack
}
// 函数的类型 (Int,Int)->Int
func addTwo(a:Int,b:Int)->Int{
return a + b
}
func mutpleTwo(a:Int,b:Int)->Int{
return a * b
}
func funcTypeTest(){
var fadd:(Int,Int)->Int = addTwo
var fmutple:(Int,Int)->Int = mutpleTwo
var addresult = fadd(3,3)
var mutpleresult = fmutple(3,3)
//printMathResult(3, 3, fadd(3,3)
printMathResult(3, 3, fadd)
}
func printMathResult(a:Int,b:Int,fadd:(Int,Int)->Int)->Int{
return fadd(3,3)
}
// 输入输出参数
// 输入输出参数相当于直接操作实参 swap1(&x, &y),用的地址
func swap1(inout a:Int,inout b:Int){
let t = a
a = b
b = t
}
// 参数传尽量就是常量了,变量参数用var
func fa(testx x:Int){
var x = 1
var y = 2
swap1(&x, &y)
// x++
}
func fa1(var testx x:Int){
x++
}
//默认值
//带默认值的参数名自动是外部名
func getString(a:[Int],b:String = "",f:Bool = false)->String{
return ""
}
// 内部明,外部名一样的情况
func sayHi(#usermm:String,#age:Int){
// 居然是常量
// usermm = "wang"
getString([3,3])
getString([2,3], b: "", f: true)
}
// username 外部名 name 内部名 外部名提高程序的可读性,
func sayHello(username name:String){
sayHi(usermm:"", age:3)
}
// 返回多个参数,其实就是元组
func count(mystring:String)->(rstring1:String,rstring2:String){
sayHello(username: "wang")
return (mystring,mystring)
}
// 注意返回空 V是大写
func sayHellop(name:String,otherName:String)->Void{
println("\(name) \(otherName)")
}
func sayHello(){
sayHellop("wan", "li")
println("hello")
}
func sayHello(name:String)->String{
return "hello \(name)"
}
func AFuncYuanzu(){
var name:String = sayHello("wangxiaolong")
sayHello()
var genres:Set = ["wang","xiao","long"]
var genres1:Set = ["yao","chun","ping"]
for temp in genres{
// 变量
}
// 并集
var bingji = sorted(genres.union(genres1))
var jiaoji = genres.intersect(genres1)
// 去掉交际,剩下,genres的
var quchujiaoji = genres.subtract(genres1)
var qudiaojiaoji = genres.exclusiveOr(genres1)
var issub = genres.isSubsetOf(genres1)
var buxiangjiaojihe = genres.isDisjointWith(genres1)
// 集合类型,无需
// 需要有初始值
var Aset = Set("dd")
Aset.insert("d")
// 清空
Aset = []
////6.数组是值类型的
var Aaarray = [String]()
var Aarray:Array = ["wnag","wang"]
var Aarrayt1 = ["wang","wag"]
var Aarry3 = Array<String>()
Aarray.append("wang")
// 加记得是同一类型才能
Aarray += [" "]
Aarray.insert("dd", atIndex: 0)
Aarray.removeAll(keepCapacity: true)
Aarray.removeAtIndex(1)
///包括2但不包括4,删除2不删除4
Aarray.removeRange(Range(start: 2, end: 4))
Aarray[0] = "dd"
Aarray[3...4] = ["d","d"]
// 清空
Aarray = []
//where子句,用于switch中
let yetPoint = (1, 1)
switch yetPoint {
case let(x, y) where x == y:
println("点(\(x),\(y))在x==y这条线上")
case let(x, y) where x == -y:
println("点(\(x),\(y))在x==-y这条线上")
case let(x, y):
println("点(\(x),\(y))不在这两条斜线上")
}
/*
var shoppingList : [String] = ["Watch", "iPhone6+", "牙刷", "牙膏"]
//1.查
shoppingList.count
shoppingList.isEmpty
//遍历数组
for shopping in shoppingList {
println("\(shopping)")
}
//遍历数组并获取每个元素的下标
for (index, shopping) in enumerate(shoppingList) {
println("\(index) : \(shopping)")
}
//使用下标运算获取元素
for var i = 0; i < shoppingList.count; i++ {
println("\(i) : \(shoppingList[i])")
}
//2.增
shoppingList.append("面包")
shoppingList.count
shoppingList += ["牛奶"]
shoppingList.count
shoppingList += ["笔", "纸"]
shoppingList.insert("Mac", atIndex: 0)
//3.删
shoppingList.removeAtIndex(0)
shoppingList.removeLast()
//shoppingList.removeAll(keepCapacity: true)
println(shoppingList)
//包括2但不包括4,删除2不删除4
shoppingList.removeRange(Range(start:2, end:4))
println(shoppingList)
//4.改
shoppingList[0] = "Apple Watch"
println(shoppingList)
shoppingList[1 ..< 3] = ["饺子", "馄饨"]
println(shoppingList)
//5.空数组的创建
//空数组
var someInts = [Int]()//Array()
var otherInts : [Int] = []//[]相当于空数组
someInts.append(1)
otherInts.append(1)
var anotherInts = Array() //本质
//有初始值的数组
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
//类型推断出数组是[Double]类型的
var anotherDoubles = Array(count: 3, repeatedValue: 0.0)
let sixDoubles = threeDoubles + anotherDoubles
//6.数组是值类型的
var arr1 = [100, 200, 300]
var arr2 = arr1
arr1[0] = 1111
arr1[1] = 2222
println("\(arr2)")
//OC中的数组是引用类型的
var arr3 : NSMutableArray = ["aaa", "bbb", "ccc"]
var arr4 = arr3
arr3[0] = "AAA"
arr3[1] = "BBB"
println(arr4)
13.//集合Set
import UIKit
var names = Set()
names.count
names.insert("Daniel")
names.insert("ShaSha")
names.insert("ShanShan")
names.insert("Daniel")
//集合无序,元素不可重复
println("\(names)")
//清空set
names = []
//使用数组字面值构建一个set
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop", "Hip hop", "Rock"]
println("\(favoriteGenres)")
//类型推断
var favoriteGenres2: Set = ["Rock", "Classical", "Hip hop", "Rock"]
println("\(favoriteGenres2)")
//访问和修改
favoriteGenres.count
favoriteGenres.isEmpty
//遍历
for genres in favoriteGenres {
println("\(genres)")
}
//不要在程序中依赖set的顺序
for (index, genres) in enumerate(favoriteGenres){
println("\(index) : \(genres)")
}
//删除
if let removeGenre = favoriteGenres.remove("Hip hop") {
println("成功删除:\(removeGenre)")
}else{
println("Set中没有你要删除的元素")
}
println("\(favoriteGenres)")
//判断某一个元素是否存在
if favoriteGenres.contains("Rock") {
println("有这种风格")
}else{
println("没有这种风格")
}
//遍历
for genres in favoriteGenres {
println("\(genres)")
}
//排序遍历
var genres : Set = ["Jazz", "Classes", "Rock", "Funk"]
for genre in sorted(genres) {
println("\(genre)")
}
//集合运算
let oddDigits : Set = [1, 3, 5, 7, 9]//奇数
let evenDigits : Set = [0, 2, 4, 6, 8]//偶数
//并集
sorted(oddDigits.union(evenDigits))
//交集
oddDigits.intersect(evenDigits)
let primes : Set = [2,3,5,7]//素数
//把交集去掉,只留下oddDigits剩余的
oddDigits.subtract(primes)
//把交集去掉,留下两类中所有剩下的
oddDigits.exclusiveOr(primes)
let hourseAnimals : Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐷", "🐔", "🐑", "🐱", "🐶"]
let cityAnimals :Set = ["🐨", "🐭"]
//是不是子集
hourseAnimals.isSubsetOf(farmAnimals)
//是不是超集
farmAnimals.isSupersetOf(hourseAnimals)
//不相交的集合
hourseAnimals.isDisjointWith(cityAnimals)
14.数组
import UIKit
let a = [1, 2, 3]//a是Int数组
var shoppingList : [String] = ["Watch", "iPhone6+", "牙刷", "牙膏"]
//1.查
shoppingList.count
shoppingList.isEmpty
//遍历数组
for shopping in shoppingList {
println("\(shopping)")
}
//遍历数组并获取每个元素的下标
for (index, shopping) in enumerate(shoppingList) {
println("\(index) : \(shopping)")
}
//使用下标运算获取元素
for var i = 0; i < shoppingList.count; i++ {
println("\(i) : \(shoppingList[i])")
}
//2.增
shoppingList.append("面包")
shoppingList.count
shoppingList += ["牛奶"]
shoppingList.count
shoppingList += ["笔", "纸"]
shoppingList.insert("Mac", atIndex: 0)
//3.删
shoppingList.removeAtIndex(0)
shoppingList.removeLast()
//shoppingList.removeAll(keepCapacity: true)
println(shoppingList)
//包括2但不包括4,删除2不删除4
shoppingList.removeRange(Range(start:2, end:4))
println(shoppingList)
//4.改
shoppingList[0] = "Apple Watch"
println(shoppingList)
shoppingList[1 ..< 3] = ["饺子", "馄饨"]
println(shoppingList)
//5.数组的创建
//空数组
var someInts = [Int]()//Array()
var otherInts : [Int] = []//[]相当于空数组
someInts.append(1)
otherInts.append(1)
var anotherInts = Array() //本质
//有初始值的数组
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
//类型推断出数组是[Double]类型的
var anotherDoubles = Array(count: 3
*/
}
func AFuncLiuCheng(){
// true or false
if 1 > 2 {
}else{
}
/* //条件的结果必须是true或false
//if a {} //ERROR
var x : Int? = nil
if x != nil { //不能写成!x
println("x不为空")
}*/
var Aa:Int? = nil
if Aa != nil{
}
// if !Aa{
//
// }
// Switch
/*
/**
1.完备性(exhaustive),不论表达式的值是多少,switch都应该有一个分支来处理,如果缺少分支,语法错误
2.没有隐式贯穿(NO Implicit Fallthrough),如果一个分支结束,switch语句就结束,(而OC中必须看见break才跳出分支)不会继续向下一个分支执行,除非特殊申请
3.一个case可以有多个匹配模式
4.在case中也可以使用break提前结束switch语句
*/
*/
var Aab = 4
// 这里不能用可选类型
// 记得没有括号
switch Aab{
case 1:
println("")
case 2:
println("")
// 可以贯穿式
case 4,5,678,8:
println("")
default:
println("")
}
//switch 类型不限
var AaS:String = ""
switch AaS{
case "wang":
//必须有个处理的
println("")
default:
println("")
}
// for while
for inde in 1...6{
}
for index in 1..<7{
}
for temp in "wangxiaolong"{
}
var Avalue = 100
for _ in 1...Avalue{// _占位符
}
while Avalue < 100{
}
// FIXME
// 可选类型
var AKa:Int
// 没有赋值的的变量,不能使用,
AKa = 2
println("\(AKa)")
// 非可选变量不可以为空
//AKa = nil
var AKav:Int? //默认未nil
println(" \(AKav)")
AKav = nil
// 可选不能直接和非科学之间运算
let Aadd = AKav! + AKa
var a : Int = 10
var b : Double = 20
//Int和Double不是一个类型,Swift不会自动将a提升为一个Double,所以编译错误,不能一起运算,而oc中会自动将int(小)提升为Double(大)类型,临时进行运算
//let c = a + b
let c = Double(a) + b
let Adouble:Double = 23.34
let Ainta:Int = 23
// 注意括号的位置
let Aaddadou = Adouble + Double(Ainta)
// 对包强制解包
var ANameString:String? = "1234"
let ANameCon = ANameString?.toInt()
let AAge = "212"
// 会自动转为可选
var AnameAd:Int? = AAge.toInt()
if ANameString != nil{
}
var An:String?
// 对空解包依然未空
let test = An!
// 可选值绑定
if let test = AnameAd{
//test不是可选只
}else{
}
// 隐式解包
let Ayinshi:Int!
Ayinshi = 3
let Anumber = Ayinshi + 3
}
// TODO
func AFunc(){
var name1 = "wang"
let age = 13
var erjinzhi = 0b10101010
var bajinzhi = 0o1234
var shiniujinzhi = 0xf
// Swift语言是强类型语言,变量需要明确的类型
// 常量和变量必须在使用前声明,用let来声明常量,用var来声明变量
// 类型推断
var myage = 34
// 可以在一行中声明多个常量或者多个变量,用逗号隔开
var a = 1,b = 2,c = 3
// 类型标注,需要写在方法里面
var Aname:String
Aname = "wang"
var Aage: Int
Aage = 1
// 类型转换
// 字符串可以直接相加
let AnameAge = Aname + Aname
let ANameAge = Aname + String(Aage)
let AStringShot = "\(Aname), age \(Aage)"
// 基本数据类型
var Aint:Int?
var ADouble:Double?
var AFloat:Float32
var ABool:Bool?
var Aint64:Int64
var AFloat64: Float64
// 获取再内存中的大小
sizeof(Int64)
sizeof(Double)
sizeof(Bool)
sizeof(Float64)
// 运算符+-*\
var Aadd = 1 + 2
//-9 % -4 //结果正负就看%左边的值除数本身正负
////支持浮点数
//%左边的值 = 右边的值 X 倍数 + 余数
// 余数 = 左边的值 - 右边的值 X 倍数
3.14 % 2.99 //3.14 - 2.99 X 1
8.15 % 2.34 //8.15 - 2.34 X 3
/*
//单目 ++,--和C语言相同
//比较 >, >=, <, <=, ==, !=和C语言相同
//三目运算符 ? : 和C语言一样
//瑞吉运算符 && || ! & | 和C语言一样
//以下是不同*********************************\\
//1.Swift支持===运算符,专门用于比较两个引用是否指向了同一个对象(在对象部分讲)
//2.新的运算符 ??
可选类型
var x : Int?
x = nil
let r = (x != nil ? x : 0)
let r2 = x ?? 0 //如果想不为空,结果为想本身;如果为空,结果为0
//3.新运算符 ...(闭区间运算符)
for index in 1...5 {
println("\(index)")
}
//4.半闭区间运算符 ..<包括前者不包括后者
for index in 1 ..< 5 {//包括1但不包括5
println("\(index)")
}
*/
for index in 1..<5{
}
for index in 1...5{
}
// 字符串
var AString = ""
var AString1 = String()
//类型标注
var AString2:String?
AString.isEmpty
//SWift中的String类型完全兼容OC中的NSString类的所有方法
AString.hasPrefix("w")
AString.hasSuffix("e")
var Achar = Character("d")
Achar = "d"
//Achar = "AB"
Achar = "\\"
Achar = " "// 空格也是字符,多了报错
//注意类型推断,推断出的类型默认是String
var ch2 = "T"
ch2 = "ABCDEF"//String
var tiger : Character = "🐯"
let dog : Character = "🐶"
// swift unicode 支持中国编码
var 你妈:String
你妈 = "woman"
}
<file_sep>//
// MySwiftThird.swift
// SwfitTest
//
// Created by kingcode on 15/9/27.
// Copyright (c) 2015年 kingcode. All rights reserved.
//
import Foundation
/*
9.结构体的构造器代理Initializer Delegation
构造器代理:
在构造器中调用另外一个构造器来完成初始化工作
为了方便构造实例
*/
// 构造器
/**
/*语法:
1.当创建一个实例时,实例的构造器一定会被调用
2.一个类型中至少会有一个构造器,如果没有,编译器会帮我们自动生成一个
3.构造器方法中的每一个参数名都默认为既是内部名,也是外部名
4. 一个类型的构造器可以有多个,多个构造器之间形成重载(overload)关系
5. 构造器是自动调用的,不允许程序员主动调用
*/
*/
class Teacher {
// 类中的属性要么是饿可选择
var name:String?
// 要么是默认值
var age = 2
var isman:Bool = true
// 要么再init进行初始化
init(name:String,age:Int,isman:Bool){
self.name = name
self.age = age
self.isman = isman
}
}
func studentTest(){
var student = Student(name: "", age: 2)
var s = Student("",3)
}
struct Student {
var name:String?
var age:Int?
init(name:String,age:Int){
self.name = name
self.age = age
}
// _隐藏外部
init(_ name:String,_ age:Int){
self.name = name
self.age = age
}
}
/**
将具体的实现隐藏起来,只给外界公开访问接口
@interface Sample : NSObject
@property(nonatomic, strong, readonly) NSString *name;
@end
@interface Sample ()
//在.m中,将属性name重新声明为可读可写
@property(nonatomic, strong, readwrite) NSString *name;
@end
*/
// 继承重写
/**
子类(Sub class) 父类(Super class) 基类(Base class)
Swift中,继承是单继承的。但是,Swift中的类并不一定非得有父类。Swift没有类似NSObject的根类,没有父类的类叫基类。
*/
class A{
// 存储属性
var name = ""
// 计算属性
var age:String{
return ""
}
func A(){
}
}
class B:A {
// 方法覆盖
override func A(){
}
// 存储属性不能重写
// override var name = "dd"
// 重写计算属性
override var age:String{
return "edd"
}
// 结合继承给存储属性添加监视器,必须加上overide
override var name:String{
willSet{
}
didSet{
}
}
}
func jichengtest(){
var jia:A = B()
// 存储属性不能重写
}
// 私有,公有类不能写在方法里
private class pricateclass{
}
public class publicclass{
// 再任何位置都可以访问,
public var propA:Int = 0
// 再本模块,本项目内部访问缺省internal
var propB:Int = 0
// 私有属性,只能再本类中访问
private var propC:Int = 0
public func MethodA(){
}
private func MehtodB(){
}
//新语法:
//属性count的set是私有的,而get是公开的(这个属性只有我自己能改,但大家不能修改,只可读)
public private(set) var count : Int = 0
}
func fangwenkongzhi(){
// 私有类
// 公有类
}
func juzheng(){
struct Metrix{
var grid:[Double]
let rows:Int
let cols:Int
// 初始化方法
init(rows:Int,cols:Int){
self.rows = rows
self.cols = cols
self.grid = Array<Double>(count: rows * cols, repeatedValue:0.0)
}
subscript(row:Int,col:Int)->Double{
set{
//assert(true, "")
grid[rows * cols + cols] = newValue
}
get{
return grid[rows * cols + cols]
}
}
}
var m = Metrix(rows: 3, cols: 3)
m[0,2] = 39
m[0,1] = 33
}
func SubscriptyTest(){
// 下标运算
class MyArray{
var array = [Int]()
func add(x:Int){
array.append(x)
}
var size:Int{
return array.count
}
// 类就支持下标运算了
subscript(index:Int)->Int{
get{
return array[index]
}
set{
array[index] = newValue
}
}
}
var array = MyArray()
array.add(3)
array.size
array[3] = 3
array[1] = 1
}
func StructTest(){
struct Point{
var x = 0.0,y = 0.0
//struct中的方法默认为只读方法,只能读取当前实例的属性的值,不能修改属性的值
//但是,如果方法前加了关键字mutating,那么方法就可以修改属性的值了,加了mutating method的方法就是变异方法
// 变异方法 只用于值类型(struct,enum)
mutating func moveByX(_x:Double, y _y:Double) {
x += _x
y += _y
}
static func TypeMethod(){
println("结构体静态方法")
}
}
}
// 方法
class Counter{
var count = 0
var x = "",y = ""
func setX(x:String,y:String){
self.x = x
self.y = y
}
// 类方法 同OC+
class func functest() {
println("leifangfa")
}
// 实例方法可访问实例变量
func increment(){
count++
}
// #内部名
func incrementBy(#amount:Int){
count += amount
}
// 方法重载
func incrementBy(amout:Int,numberOfTimes:Int){
count += amout * numberOfTimes
}
func incrementyBy(testint amout:String,testint2 amount2:String){
x = amout
y = amount2
}
}
func classTest(){
var count = Counter()
count.increment()
count.incrementBy(amount: 2)
count.incrementBy(2, numberOfTimes: 4)
count.incrementyBy(testint: "", testint2: "")
}
// 实例属性和类型属性,类结构体通用
//不加static的是实例属性,加static的是类型属性。实例属性只能通过实例来访问,不能通过类型来访问。同样,类型属性只能通过类型来访问,不能通过实例来访问
class testclass{
// 实例属性
var name:String = "wag"
// 类型属性
static var age:Int = 0
// 是计算类型属性
static var jisuanleixngshxing:Int{
return 199
}
}
// 属性监视器,属性发生改变,也就是必须哟值父给他
func jububianliang(){
//
var jububianliang:Int = 9{
willSet{
println("\(newValue)")
}
didSet{
println("\(oldValue)")
}
}
}
// 全局=变量也可以添加监视器
var globe:Int = 0{
willSet{
println("\(newValue)")
}
didSet{
println("\(oldValue)")
}
}
// 属性监视器 观察器
var indicator:Int = -1999
class StepCounter {
// 一个属性租多可以有两个属性观察其,一个willset,一个didset
var totalStep:Int = 0{
willSet{
//属性变化前调用
println("属性马上变成 \(newValue)")
indicator = newValue
}
didSet{
// 属性发生变化后调用
println("属性变化前的值\(oldValue)")
indicator = oldValue
}
}
}
// 延迟属性
class DataImporter{
var mucnFiles = "data.Text"
}
class DataManager {
////这是一个延迟加载属性,只有当读取这个属性的值时才会加载到内存。这个属性加载时太慢了,且会占用大量的内存,所以,能不加载就不加载
lazy var importer = DataImporter()
}
func temp(){
let manger = DataManager()
var test:DataImporter = manger.importer//此时必须加载属性的内容
}
// 存储属性和计算属性
struct SHUXING{
var firstValue:Int //存储属性,再内存中有控件保留值
let length:Int // 常量属性
}
func SHUXING1(){
var shxing = SHUXING(firstValue: 0, length: 4)
//shxing.length = 3
}
func JietouTI(){
struct Point{
var X:Float
var Y:Float
}
struct Size{
var Width:Float
var Height:Float
}
struct MFrame{
var point:Point
var size:Size
// center 计算属性
var center:Point{
get{
let centerX = point.X + size.Height / 2
let centerY = point.Y + size.Width / 2
return Point(X: centerX, Y: centerY)
}
set(p){
let originX = p.X - size.Width / 2
let originY = p.Y - size.Height / 2
point = Point(X: originX, Y: originY)
}
}
}
let frame = MFrame(point: Point(X: 3, Y: 3), size: Size(Width: 3, Height: 3))
}
//结构体的逐一构造器
struct Point {
var x : Float
var y : Float
}
//Swift要确保实例中的属性都有初始值
let point = Point(x:10, y:20)
// 类和结构
// 基础数据都是结构体类型
/*
var i : Int
var f : Float
var s : String
var a : Array
var d : Dictionary
var set : Set
*/
//结构体是值类型
struct Resolution {
var width = 0 // 属性
var height = 0
}
//类是引用类型
class VideoMode {
var resolution = Resolution()// 属性
var inerloaced = false // 逐行
var name:String? //可选值属性
}
//专门用于判断两个引用是否指向了同一个对象的运算符:===
//不可以使用==来判断两个引用是否指向同一个对象
//==是用来判断两个对象的内容是否相等(相当于OC中的isEqual方法),要使用==,必须重写==运算符函数
func Bfunc(){
var someReso = Resolution()
someReso.width = 1024
someReso.height = 748
var someVie = VideoMode()
someVie.resolution = someReso
var otherMode = VideoMode()
if someVie === otherMode {
println("这两引用指向了同一个对象")
}
}
// 枚举
enum Myenum{
case North
case South
case East
case West
}
func Fenum(){
// 原始值,(Raw Value),裸值
enum Week:Int{
case SUN = 0
case MON = 1,THE,WED,THU,FRI,SAT
}
var w : Week
w = .SUN
// 枚举值 -》原始值
let sunValue:Int = w.rawValue
println("\(sunValue)")
w = .WED
w.rawValue
// 原始值 -》 枚举值
let week = Week(rawValue: 5)// 可选值
if week == .FRI{
}
var direction:Myenum
// 不能推断时需要写全
direction = Myenum.North
// 自动类型判断
direction = .North
switch direction{
case .North:
println("")
case .South:
println("")
case .East:
println("")
default:
println("")
}
//时机开发中使用枚举, .System是一个枚举值
// var button: UIButton = UIButton.buttonWithType(.System) as! UIButton
}
// 闭包本质就是函数,凡事函数的地方哪个都可以用闭包
func Closures(){
var a = [4,1,2,5,3,9,0,6,8,7];
//闭包的本质是函数,凡是要函数的地方都可以给闭包
myclosure(wang:{(a:Int,b:Int)->Int in
return 1
}
)
myclosure(wang:{
(a:Int,b:Int)->Int in
return 1
})
myclosu({(a:Int,b:String)->String in
return ""})
}
func myclosure(wang myf:(Int,Int)->Int){
}
func myclosu(mycloo:(Int,String)->String){
}
/*
闭包表达式的语法如下:
{
(parameters)->returnType in
语句...
return xxx
}
OC中的Block:
^returnType(parameters){
//…
return xxx;
}
1.闭包1
import UIKit
func rule(a:Int, b:Int)->Bool {
return a > b
}
f: {(a:Int,b:Int)->Bool in
return a > b
}
func sortInts(inout data:[Int], f:(Int,Int)->Bool = rule ){
for var i=0; i
for var j=0; j
if f(data[j],data[j+1]) {
swap(&data[j], &data[j+1])
}
}
println("\(data)")
}
}
var a = [4,1,2,5,3,9,0,6,8,7];
//闭包的本质是函数,凡是要函数的地方都可以给闭包
sortInts(&a, f: {(a:Int,b:Int)->Bool in
return a > b
})
println("\(a)")
//Swift的类型推断功能可以推断出闭包中的参数和返回值类型,所以可以不用提供
sortInts(&a, f: {(a,b) in return a > b})
//当闭包中只是一条语句时,return可以省略不写
sortInts(&a, f: {(a,b) in a > b})
//闭包中的参数可以直接使用$0,$1,$2...来代替
sortInts(&a, f: {$0 > $1})
//如果只有两个参数,可以将参数直接省略
sortInts(&a, f: <)
println("\(a)")
2.闭包2
import UIKit
var a = [3,2,1,4,9,8,0,5,7,6]
sort(&a, {(x, y) in return x%3 < y%3})
println("\(a)")
sort(&a, {$0 < $1})
println("\(a)")
sort(&a, >)
println("\(a)")
let r1 = sorted(a, {$0 < $1})
println("\(r1)")
var names = ["aaa","bbb","ccc"]
sort(&names, <)
println("\(names)")
//拖尾闭包(Trailing Closures)
//最后一个参数
sort(&a) {
(x, y)->Bool in return x%3 < y%3
}
*/
/*
闭包:
Swift ==> Closures
Smalltalk Ruby OC ==> Block
Python C++(11) Lisp ==> Lambda
Javascript (JS) ==> Anonymous Function(匿名函数)
Swift中的闭包本质上是一个函数,一般将闭包函数称为闭包表达式。
*/<file_sep>//
// MySwfit.swift
// SwfitTest
//
// Created by kingcode on 15/9/25.
// Copyright (c) 2015年 kingcode. All rights reserved.
//
import Foundation
typealias myfloat = Float32
/**
协议protocol
1.Swift使用protocol定义协议
2.Protocol(协议)用于统一方法和属性的名称,而不实现任何功能。协议能够被类,枚举,结构体实现,满足协议要求的类,枚举,结构体被称为协议的遵循者
3.属性要求
通常前置var关键字将属性声明为变量。在属性声明后写上{ get set }表示属性为可读写的。{ get }用来表示属性为可读的。即使你为可读的属性实现了setter方法,它也不会出错。
protocol SomeProtocol {
var musBeSettable : Int { get set }
var doesNotNeedToBeSettable: Int { get }
}
4.方法要求
协议能够要求其遵循者必备某些特定的实例方法和类方法。协议方法的声明与普通方法声明相似,但它不需要方法内容.
协议方法支持变长参数(variadic parameter),不支持默认参数(default parameter)。
5.突变方法要求
能在方法或函数内部改变实例类型的方法称为突变方法。在值类型(Value Type)(译者注:特指结构体和枚举)中的的函数前缀加上mutating关键字来表示该函数允许改变该实例和其属性的类型
类中的成员为引用类型(Reference Type),可以方便的修改实例及其属性的值而无需改变类型;而结构体和枚举中的成员均为值类型(Value Type),修改变量的值就相当于修改变量的类型,而Swift默认不允许修改类型,因此需要前置mutating关键字用来表示该函数中能够修改类型
用class实现协议中的mutating方法时,不用写mutating关键字;用结构体,枚举实现协议中的mutating方法时,必须写mutating关键字
6.协议类型
协议本身不实现任何功能,但你可以将它当做类型来使用
使用场景:
作为函数,方法或构造器中的参数类型,返回值类型
作为常量,变量,属性的类型
作为数组,字典或其他容器中的元素类型
7.委托(代理)模式
8.在扩展中添加协议成员
9.通过扩展补充协议声明:当一个类型已经实现了协议中的所有要求,却没有声明时,可以通过扩展来补充协议声明
10.集合中的协议类型:协议类型可以被集合使用,表示集合中的元素均为协议类型
11.协议的继承:协议能够继承一到多个其他协议。语法与类的继承相似,多个协议间用逗号,分隔
12.协议合成:一个协议可由多个协议采用protocol<oneProtocol,twoProtocol>这样的格式进行组合,称为协议合成(protocol composition)。
13.检验协议的一致性
使用is检验协议一致性,使用as将协议类型向下转换(downcast)为的其他协议类型
is操作符用来检查实例是否遵循了某个协议。
as?返回一个可选值,当实例遵循协议时,返回该协议类型;否则返回nil
as用以强制向下转换型。
@objc用来表示协议是可选的,也可以用来表示暴露给Objective-C的代码,此外,@objc型 协议只对类有效,因此只能在类中检查协议的一致性。
14.可选协议要求
在协议中使用@optional关键字作为前缀来定义可选成员。
可选协议在调用时使用可选链
可选协议只能在含有@objc前缀的协议中生效。且@objc的协议只能被类遵循。
15.Swift 标准库中定义了一个Equatable协议,该协议要求任何遵循的类型实现等式符(==)和不等符(!=)对任何两个该类型进行比较。所有的 Swift 标准类型自动支持Equatable协议
扩展extension
1.Swift使用extension声明扩展
2.Swift 中的扩展可以:
(1)添加计算型属性和计算静态属性: 扩展可以添加新的计算属性,但是不可以添加存储属性,也不可以向已有属性添加属性观测器(property observers)。
(2)定义实例方法和类型方法 :扩展可以向已有类型添加新的实例方法和类型方法.通过扩展添加的实例方法也可以修改该实例本身。结构体和枚举类型中修改self或其属性的方法必须将该实例方法标注为mutating,正如来自原始实现的修改方法一样。
(3)提供新的构造器:扩展能向类中添加新的便利构造器,但是它们不能向类中添加新的指定构造器或析构函数。指定构造器和析构函数必须总是由原始的类实现来提供。
(4)定义下标:扩展可以向一个已有类型添加新下标
(5)定义和使用新的嵌套类型:扩展可以向已有的类、结构体和枚举添加新的嵌套类型
(6)使一个已有类型符合某个协议 :一个扩展可以扩展一个已有类型,使其能够适配一个或多个协议(protocol)
范型<>
1.Swift使用<>来声明泛型函数或泛型类型。
2.Swift支持在类、枚举和结构中使用泛型
3.泛型代码可以让你写出根据自我需求定义、适用于任何类型的,灵活且可重用的函数和类型。它的可以让你避免重复的代码,用一种清晰和抽象的方式来表达代码的意图。
4.泛型函数
func swapTwoValues (inout a: T, inout b: T) {}
占位类型T是一种类型参数的示例。类型参数指定并命名为一个占位类型,并且紧随在函数名后面,使用一对尖括号括起来.可支持多个类型参数,命名在尖括号中,用逗号分开。
类型别名 typealias
1.Swift 使用typealias关键字定义类型别名
2. typealias AudioSample = UInt16
断言assert
1.Swift中用全局函数assert来断言调试2.assert函数接受一个布尔表达式和一个断言失败时显示的消息。如:
let age = -3;
assert(age >= 0, " age cannot < zero")
取余运算符 %
1.Swift允许对浮点数执行取余运算
2. a % b => a = (b × 最多倍数) + 余数.
b为负值时的b的符号被忽略,这意味着%b和%-b的结果是一样的.
8 % 2.5 = 0.5 ; => (8 = 2.5*3+0.5)
赋值运算符 =
*/
enum myenmu{
func test(){
}
case enmu1,e,e1,e2,e3
//case enmu2
}
func test(){
var menmu:myenmu
//let temp = myenmu.e1.rowValue
}
/**
枚举enum
1.枚举可以关联方法
2.使用toRaw和fromRaw在原始数值和枚举值之间进行转换
结构体Struct
1.支持构造器和方法
2.结构和类的最大区别在于:结构的实例按值传递(passed by value),而类的实例按引用传递(passed by reference)
3.结构类型有一种成员逐一完成初始化的构造器,类不存在成员逐一构造器
类 class
1.重写一个由继承而来的方法需要在方法定义前标注override关键词。
2.@final 用来标记一个类不被继承或者一个方法不被重写
3.类型方法
在类结构体里面用class func开头 ,对于枚举和结构来说,类型方法是用static func开头。
4. 便捷初始化.
convenience init() { self.init(name: "[Unnamed]") }
5.weak:弱引用必须声明为变量 及 可选类型
6.unowned:无主引用不能为可选类型
*/
// 输入,输出参数inout
// 由函数修改后,从函数返回替换原来的值,类似于传递的引用
func printAndCont(inout stringToPrint:String)->Int{
return 3;
}
// 函数,可变参数函数
func matableFunc(names:String...){
for name in names{
println(name)
}
}
/*
*/
func BaseDataTypeTrain(){
matableFunc()
matableFunc("wang","xiao","long")
var myyuzu = (name:"wang",age:9)
println(myyuzu.name)
// var (one:Int,_) = yuzu
// println(yuzu)
var tuple = ("1",1,33)
println(tuple.0)
var tu = (1,"ee")
// 元组
var (one:Int, two:String) = tu
for temp in 1...4{
}
for temp in 1...3{
println(temp)
}
/**
区间
..生成 [ ) 的区间,而…生成 [ ] 的区间
元组(Tuple)
元组类型可以将一些不同的数据类型组装成一个元素
var yuZu = ( 404 , "error" )
println( yuZu )
var ( one:Int , two:String ) = yuZu
println( one )
println( two )
2.使用 _ 来忽略不需要的值
var ( one:Int , _ ) = yuZu
println( one )
3.使用元素序号来选择元组中的值,从0开始
var tuple = ( 404 , "error" )
println( tuple.0 )
4.使用 元组名.元素名 访问
var tuple = ( eN:404 , eT:"error" )
println( tuple.eN )
*/
// 字典只有一种创建形式
var dict1 = Dictionary<String,Int>()
var keys = Array<String>()
keys = Array(dict1.keys)
let values = Array(dict1.values)
for (key , value) in dict1{
println("key: \(key) value: \(value)")
}
//dict1.removeAll("one")
dict1.removeAll()
dict1["zero"] = nil
let oldvalue = dict1.removeValueForKey("wang")
dict1["am"] = 1
//dict1["zeor"] = 0
if let oldValue = dict1.updateValue(1, forKey: "zeor"){
}
// 确定长度
var array1 = [Double](count: 3, repeatedValue: 0.0)
var array2 = Array<String>()
var array0 = [String]()
for (index,value) in enumerate(array0){
println("item \(index):\(value)")
}
array0.removeAtIndex(0)
array0[0...2] = []
array0.insert("zeero", atIndex: 0)
// Bool isEmpty = array0.isEmpty();
var count = array0.count
array0.append("")
// array0 += "two"
array0 += ["two","three"]
// 创建数组
var myarray = [String]();
var myarray2:[String] = []
// 1、还是用这种吧
var myarray1 = Array<String>()
let mydictionary = Dictionary<String,Int>()
let myarray3 = Array([])
var emptyarra = []
/*
字典和数组
1.都用[]
2.空数组 和 空字典
var emptyArray = String[]() (或者 Array<String>() )
let emptyDictionary = Dictionary<String,Int>()
或者
var emptyArr:String[] = []
或者
var emptyArray = Array([]) //用数组创建数组
对于已知类型的字典可用[:]置空
var arr = [] //直接这样写arr是个空的NSArray
3.确定长度和默认值的数组
var threeDoubles = Double[](count: 3, repeatedValue: 0.0)
4.用只读属性count来读取数组和字典的长度
5.用属性isEmpty检查数组的长度是否为0
6.往数组追加元素
emptyArray.append("one")
emptyArray += "two"
emptyArray += [ "three" , "four" ]
emptyArray.insert("zero" , atIndex:0)
7.从数组中删除元素
let lastElement = emptyArray.removeLast() //删除最后一个
let indexElement = emptyArray.removeAtIndex(3) //按索引删除
emptyArray[0...2] = [] //区间元素替换
8. 遍历数组
for (index, value) in enumerate(emptyArray) {
println("Item \(index): \(value)")
}
9. 给字典增加元素
emptyDictionary["zero"] = 0
if let oldValue = emptyDictionary.updateValue(1, forKey: "one") {
println("The old value for key:one was \(oldValue).")
} //增加或更新元素
10.移除字典元素
emptyDictionary["zero"] = nil
let oldValue = emptyDictionary.removeValueForKey("one")
emptyDictionary.removeAll()
11.遍历字典
for (key, value) in dic {
println("\(key): \(value)")
}
12.获取字典的keys和values
let keys = Array(dic.keys)
let values = Array(dic.values)
13.数组的copy方法
通过调用数组的copy方法来完成强制拷贝。这个方法将会完整复制一个数组到新的数组中。
14.数组的unshare方法
如果多个变量引用了同一个数组,可以使用unshare方法来完成一次“独立”
区间
..生成 [ ) 的区间,而…生成 [ ] 的区间
*/
}
//enum MyEnum{
// MyEnum1,
// MyEnum2,
// MyEnum3
//}
//struct Dog {
// var name:String?
// var hoster:String?
//
//}
/**
Swift数据类型
1.基础数据类型:整形Int、浮点数Double和Float、布尔类型Bool,字符串类型String。
2.集合数据类型,Array和Dictionary
3.元组类型
4.结构体struct,枚举enum,类:class
5.数值类型 和 引用类型
(1)数值类型是说当它被赋值给一个常量或者变量,或者作为参数传递给函数时,是完整地复制了一个新的数值,而不是仅仅改变了引用对象。
(2)所有Swift中的基础类型-整型,浮点型,布尔类型,字符串,数组和字典都是数值类型。它们也都是由结构来实现的。
(3)在Swift中所有的结构和枚举类型都是数值类型。这意味这你实例化的每个结构和枚举,其包含的所有属性,都会在代码中传递的时候被完整复制。
(4)类 和 函数 闭包 是引用类型
(5)当一个值类型实例作为常量而存在,它的所有属性也作为常量而存在。类是引用类型。如果你将引用类型的实例赋值给常量,依然能够改变实例的变量属性。
?和 !
参见博文:http://joeyio.com/ios/2014/06/04/swift---/
字典和数组
1.都用[]
*/
var name:String?
func setname(){
// let score:Dictionary<"","">
// let arms:Array<"">
name = "wangxiaolong"
print(name);
let age:Int
let height:Double
let isMan:Bool
let address:String
}
<file_sep>
//
// MySwiftFourth.swift
// SwfitTest
//
// Created by kingcode on 15/9/27.
// Copyright (c) 2015年 kingcode. All rights reserved.
//
import Foundation
/**
二:便利构造器:
1) 是次要的,辅助性的构造器.
2) 一个类可能没有便利构造器,但不能没有指定构造器
3) 便利构造器不会调用父类的构造器,而会调用同类中的构造器
三原则 四检查:
三大原则: 1)指定向上调, 2)便利调自己, 3)便利最终会调用到指定
安全检查:
1. 必须先初始本类的所有属性之后,才能向上调用父类的指定构造器(初始化父类中的属性)
2. 必须调用完了父类的指定构造器后,才能给继承下来的属性赋值(如果需要的话)
3. 在便利构造器中,如果需要直接给属性赋值,则赋值语句一定要写在调用另一个构造器的语句之后
4. 构造器中要调用其他构造器之前,不能调用任何实例方法。只有在调用其他构造器之后才可以调用实例方法。
构造器的继承问题:
一般情况下,构造器是不能被子类继承的,子类中如果需要父类的构造器,可以重写(覆盖)父类中已有构造器。但有如下特殊规则:
1. 如果子类没有任何指定构造器,那么子类就继承所有的指定构造器
2. 如果子类提供了父类中所有的指定构造器(可以是继承来的或都是覆盖的),那么,父类中所有的便利构造器也会被子类继承
*/
class Person {
var name:String
/*
//编译器写的构造器
override init(){
//在调用父类的指定构造器之前,必须相处是否本类中的所有属性
numberOfPassengers = 1
super.init()
//必须先调用父类的指定构造器,再给从父类继承来的属性赋值,否则有可能导致你赋的值无效(被覆盖)
numberOfWheels = 2
}
*/
// 一个类一定有构造器
// 如果没有自定义的,系统会默认创建一个
// init(name:String){
// self.name = name
// }
init(){
name = ""
}
}
class PersonA: Person {
var age:Int
override init(){
age = 2
super.init()
}
// override init(age:Int){
// age = 2
// super.init(name: "")
// name = 33
// }
}
/*
10.指定构造器
有两种:
指定构造器(Designated Initializer)
便利构造器(Convenience Initializer)
一:指定构造器:
1) 最重要的构造器
2) 初始化所有的属性,并且向上调用父类的指定构造器来初始从父类中继承的属性
3) 类中至少有一个指定构造器(可以是自己写的,也可以是从父类中继承来的)
*/
|
74b5cd5d1bd898574babafc9dcdaf12585a542de
|
[
"Swift"
] | 4
|
Swift
|
kingcodexl/Demo
|
f0717b75d12a0e2be2eb417801515a141ee973b5
|
3ce4e317fec9beea8e720762bb0ed40dcceb226f
|
refs/heads/master
|
<file_sep>use libc::size_t;
use std::str;
use std::ffi::{CString, CStr};
use proton_sys;
mod encoder;
pub enum Trace {
OFF,
DRV,
FRM,
RAW
}
struct Condition<'cond> {
name: &'cond str,
description: &'cond str
}
enum State {
UNINIT,
CLOSED,
ACTIVE
}
/**
* (LocalState, RemoteState)
*/
struct EndpointState(State, State);
impl EndpointState {
fn from_bits(bits: i32) -> EndpointState {
EndpointState::from_flags(&proton_sys::StateFlags::from_bits(bits).unwrap())
}
fn from_flags(flags: &proton_sys::StateFlags) -> EndpointState {
let local = match flags.local_state() {
proton_sys::LOCAL_ACTIVE => State::ACTIVE,
proton_sys::LOCAL_CLOSED => State::CLOSED,
_ => State::UNINIT, // need to handle error case7
};
let remote = match flags.local_state() {
proton_sys::REMOTE_ACTIVE => State::ACTIVE,
proton_sys::REMOTE_CLOSED => State::CLOSED,
_ => State::UNINIT,
};
EndpointState(local, remote)
}
fn as_bits(&self) -> i32 {
self.as_flags().bits()
}
fn as_flags(&self) -> proton_sys::StateFlags {
let local = match self.0 {
State::ACTIVE => proton_sys::LOCAL_ACTIVE,
State::CLOSED => proton_sys::LOCAL_CLOSED,
State::UNINIT => proton_sys::LOCAL_UNINIT
};
let remote = match self.1 {
State::ACTIVE => proton_sys::REMOTE_ACTIVE,
State::CLOSED => proton_sys::REMOTE_CLOSED,
State::UNINIT => proton_sys::REMOTE_UNINIT
};
local & remote
}
}
trait Endpoint {
fn condition(&self) -> (Condition, Condition);
}
// implement endpoint
struct Session(*mut proton_sys::pn_session_t);
impl Session {
fn from_ptr(ptr: *mut proton_sys::pn_session_t) -> Session {
Session(ptr)
}
fn open(&mut self) {
unsafe { proton_sys::pn_session_open(&mut *self.0); }
}
fn close(&mut self) {
// update condition
unsafe { proton_sys::pn_session_close(&mut *self.0); }
}
fn state(&mut self) -> EndpointState {
unsafe {
let state = proton_sys::pn_session_state(&mut *self.0);
EndpointState::from_bits(state)
}
}
fn next(&mut self, state: &EndpointState) -> Session {
Session(unsafe{proton_sys::pn_session_next(&mut *self.0, state.as_bits())})
}
fn connection(&mut self) -> Connection {
Connection::from_ptr(unsafe{proton_sys::pn_session_connection(&mut *self.0)})
}
fn get_incoming_capacity(&mut self) -> u64 {
unsafe { proton_sys::pn_session_get_incoming_capacity(&mut *self.0) }
}
fn set_incoming_capacity(&mut self, capacity: u64) {
unsafe { proton_sys::pn_session_set_incoming_capacity(&mut *self.0, capacity); }
}
fn incoming_bytes(&mut self) -> u64 {
unsafe { proton_sys::pn_session_incoming_bytes(&mut *self.0) }
}
fn outgoing_bytes(&mut self) -> u64 {
unsafe { proton_sys::pn_session_outgoing_bytes(&mut *self.0) }
}
fn sender(&mut self, name: &str) -> Link {
let unique = unsafe{
let n = CString::new(name).unwrap();
proton_sys::pn_sender(&mut *self.0, n.as_ptr())
};
Link::Sender(Sender(unique))
}
fn receiver(&mut self, name: &str) -> Link {
let unique = unsafe{
let n = CString::new(name).unwrap();
proton_sys::pn_receiver(&mut *self.0, n.as_ptr())
};
Link::Receiver(Receiver(unique))
}
// move to dtor
fn free(&mut self) {
unsafe { proton_sys::pn_session_free(&mut *self.0); }
}
}
struct Sender(*mut proton_sys::pn_link_t);
struct Receiver(*mut proton_sys::pn_link_t);
// Implement endpoint
enum Link {
Sender(Sender),
Receiver(Receiver),
}
impl Link {
fn get_mut(&mut self) -> &mut proton_sys::pn_link_t {
match *self {
Link::Sender(Sender(ref mut p)) |
Link::Receiver(Receiver(ref mut p)) => unsafe{&mut **p}
}
}
fn open(&mut self) {
unsafe {proton_sys::pn_link_open(self.get_mut());}
}
fn close(&mut self) {
// update condition missing
unsafe {proton_sys::pn_link_close(self.get_mut());}
}
fn state(&mut self) -> EndpointState {
unsafe {
let state = proton_sys::pn_link_state(self.get_mut());
EndpointState::from_bits(state)
}
}
// Missing source, target, remote_source, remote_target, session
// delivery, current
fn session(&mut self) -> Session {
match *self {
Link::Sender(Sender(ref mut p)) |
Link::Receiver(Receiver(ref mut p)) => {
Session::from_ptr(unsafe{proton_sys::pn_link_session(*p)})
}
}
}
// FIXME: Is this really needed?
fn connection(&mut self) -> Connection {
self.session().connection()
}
fn advance(&mut self) -> bool{
unsafe {proton_sys::pn_link_advance(self.get_mut()) == 0}
}
fn unsettled(&mut self) -> i32 {
unsafe {proton_sys::pn_link_unsettled(self.get_mut())}
}
fn credit(&mut self) -> i32 {
unsafe {proton_sys::pn_link_credit(self.get_mut())}
}
fn available(&mut self) {
unsafe {proton_sys::pn_link_available(self.get_mut());}
}
fn queued(&mut self) -> i32 {
unsafe {proton_sys::pn_link_queued(self.get_mut())}
}
// missing next
fn name(&mut self) -> &str {
unsafe {
let name = CStr::from_ptr(proton_sys::pn_link_name(self.get_mut()));
str::from_utf8(name.to_bytes()).unwrap()
}
}
// is_sender, is_receiver (use enum?)
fn remote_snd_settle_mode(&mut self) {
unsafe {proton_sys::pn_link_remote_snd_settle_mode(self.get_mut());}
}
fn remote_rcv_settle_mode(&mut self) {
unsafe {proton_sys::pn_link_remote_rcv_settle_mode(self.get_mut());}
}
// get_drain, set_drain
fn drained(&mut self) -> i32 {
unsafe {proton_sys::pn_link_drained(self.get_mut())}
}
fn detach(&mut self) {
unsafe {proton_sys::pn_link_detach(self.get_mut());}
}
fn free(&mut self) {
unsafe {proton_sys::pn_link_free(self.get_mut());}
}
}
impl Sender {
fn offered(&mut self, credits: i32) {
unsafe {proton_sys::pn_link_offered(&mut *self.0, credits);}
}
fn send(&mut self, bytes: &[u8]) {
let s = CString::new(bytes).unwrap();
unsafe{
let sent = proton_sys::pn_link_send(&mut *self.0,
s.as_ptr(),
bytes.len() as proton_sys::size_t);
assert_eq!(bytes.len(), sent as usize);
}
}
}
impl Sender {
fn flow(&mut self, credits: i32) {
unsafe {proton_sys::pn_link_flow(&mut *self.0, credits);}
}
fn recv(&mut self, limit: u32) -> Vec<i8> {
let mut dst = Vec::with_capacity(limit as usize);
unsafe{
let sent = proton_sys::pn_link_send(&mut *self.0,
dst.as_mut_ptr(),
limit as proton_sys::size_t);
assert_eq!(limit as usize, sent as usize);
}
dst
}
}
pub struct Message {
ptr: *mut proton_sys::pn_message_t
}
impl Message {
pub fn new() -> Message {
let message = unsafe {proton_sys::pn_message()};
Message {
ptr: message
}
}
}
// implement endpoint
pub struct Connection {
ptr: *mut proton_sys::pn_connection_t
}
impl Connection {
pub fn new() -> Connection {
Connection::from_ptr(unsafe {proton_sys::pn_connection()})
}
fn from_ptr(ptr: *mut proton_sys::pn_connection_t) -> Connection {
Connection {
ptr: ptr
}
}
pub fn transport(&mut self) -> Transport {
Transport::from_ptr(unsafe {proton_sys::pn_connection_transport(self.ptr)})
}
// collect, (get|set)_container
}
//impl Endpoint for Connection {
// fn condition(&self) -> (Condition, Condition) {
// unsafe{(proton_sys::pn_connection_condition(self.connection.0),
// proton_sys::pn_connection_remote_condition(self.connection.0))}
// }
//}
pub struct Container;
impl Container {
pub fn new() -> Container {
Container
}
}
pub struct Transport {
ptr: *mut proton_sys::pn_transport_t
}
impl Transport {
pub fn new() -> Transport {
let transport;
unsafe {
transport = proton_sys::pn_transport();
proton_sys::pn_transport_set_server(transport);
};
Transport::from_ptr(transport)
}
pub fn from_ptr(ptr: *mut proton_sys::pn_transport_t) -> Transport {
Transport {
ptr: ptr
}
}
pub fn bind(&mut self, conn: &mut Connection) {
unsafe {proton_sys::pn_transport_bind(self.ptr, conn.ptr)};
}
pub fn unbind(&mut self) {
unsafe {proton_sys::pn_transport_unbind(self.ptr)};
}
pub fn close_head(&mut self) {
unsafe {proton_sys::pn_transport_close_head(self.ptr)};
}
pub fn close_tail(&mut self) {
unsafe {proton_sys::pn_transport_close_tail(self.ptr)};
}
pub fn has_capacity(&mut self) -> bool {
debug!("CAPACITY: {}", self.capacity());
self.capacity() > 0
}
pub fn capacity(&mut self) -> i64 {
unsafe {proton_sys::pn_transport_capacity(self.ptr)}
}
pub fn pending(&mut self) -> i8 {
let pending = unsafe {proton_sys::pn_transport_pending(self.ptr) as i8};
if pending >= proton_sys::PN_EOS {
pending
} else {
// needs check for errors instead of returning pending
pending
}
}
pub fn push(&mut self, bytes: &[u8]) {
let s = CString::new(bytes).unwrap();
//debug!("len: {}", s.len() as proton_sys::size_t);
unsafe {
let size = bytes.len() as proton_sys::size_t;
let res = proton_sys::pn_transport_push(self.ptr, s.as_ptr(), size);
debug!("RESULT: {}", res);
if res != size as i64{
// this shouldn't panic
panic!("OVERFLOW");
} else if res < 0 {
panic!("ERRROR");
}
};
}
}
<file_sep>[package]
name = "rust-proton"
version = "0.0.1"
authors = ["<NAME> <<EMAIL>>"]
[dependencies.proton-sys]
path = "proton-sys"
[dependencies]
mio = "0.3.*"
libc = "0.1.*"
log = "0.3"
env_logger = "0.3"
rustc-serialize = "0.3"
<file_sep>#include <proton/cid.h>
#include <proton/codec.h>
#include <proton/condition.h>
#include <proton/connection.h>
#include <proton/container.h>
#include <proton/delivery.h>
#include <proton/disposition.h>
#include <proton/engine.h>
#include <proton/error.h>
#include <proton/event.h>
#include <proton/handlers.h>
#include <proton/import_export.h>
#include <proton/io.h>
#include <proton/link.h>
#include <proton/log.h>
#include <proton/message.h>
#include <proton/messenger.h>
#include <proton/object.h>
#include <proton/parser.h>
#include <proton/reactor.h>
#include <proton/sasl.h>
#include <proton/scanner.h>
#include <proton/selectable.h>
#include <proton/selector.h>
#include <proton/session.h>
#include <proton/ssl.h>
#include <proton/terminus.h>
#include <proton/transport.h>
#include <proton/type_compat.h>
#include <proton/types.h>
#include <proton/url.h>
<file_sep>[package]
name = "proton-sys"
version = "0.0.1"
authors = ["<NAME> <<EMAIL>>"]
[dependencies]
libc = "0.1.7"
bitflags = "0.1.1"<file_sep>#[macro_use] extern crate log;
extern crate env_logger;
extern crate mio;
extern crate rust_proton as proton;
use proton::{AmqpHandler};
use mio::*;
use mio::tcp::*;
pub fn main() {
env_logger::init().unwrap();
let mut event_loop = EventLoop::new().unwrap();
info!("listen for connections");
let mut hdlr = AmqpHandler::new(&"127.0.0.1:5672");
event_loop.register_opt(hdlr.sock(), Token(0),
Interest::readable(),
PollOpt::edge() | PollOpt::oneshot()).unwrap();
// Start the event loop
event_loop.run(&mut hdlr).unwrap();
}
<file_sep>#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
extern crate libc;
#[macro_use] extern crate bitflags;
type __builtin_va_list = libc::c_void;
pub const PN_EOS: i8 = -1;
pub const PN_ERR: i8 = -2;
pub const PN_OVERFLOW: i8 = -3;
pub const PN_UNDERFLOW: i8 = -4;
pub const PN_STATE_ERR: i8 = -5;
pub const PN_ARG_ERR: i8 = -6;
pub const PN_TIMEOUT: i8 = -7;
pub const PN_INTR: i8 = -8;
pub const PN_INPROGRESS: i8 = -9;
bitflags! {
flags StateFlags: i32 {
const LOCAL_UNINIT = 0b00000001,
const LOCAL_ACTIVE = 0b00000010,
const LOCAL_CLOSED = 0b00000100,
const REMOTE_UNINIT = 0b00001000,
const REMOTE_ACTIVE = 0b00010000,
const REMOTE_CLOSED = 0b00100000,
const LOCAL_MASK = LOCAL_UNINIT.bits
| LOCAL_ACTIVE.bits
| LOCAL_CLOSED.bits,
const REMOTE_MASK = REMOTE_UNINIT.bits
| REMOTE_ACTIVE.bits
| REMOTE_CLOSED.bits,
}
}
impl StateFlags {
pub fn local_state(&self) -> StateFlags {
*self & LOCAL_MASK
}
pub fn remote_state(&self) -> StateFlags {
*self & REMOTE_MASK
}
}
include!("ffi.rs");
<file_sep>use std::string;
use std::{char, f64, fmt, io, num, str, mem};
use std::ffi::CString;
use rustc_serialize as serialize;
use std::marker::PhantomData;
use proton_sys;
/*
Marshal encodes a Rust value as AMQP data in buffer based on its type.
If buffer is nil, or is not large enough, a new buffer is created.
Returns the buffer used for encoding with len() adjusted to the actual size of data.
Rust types are encoded as follows
+-------------------------------------+--------------------------------------------+
|Rust type |AMQP type |
+-------------------------------------+--------------------------------------------+
|bool |bool |
+-------------------------------------+--------------------------------------------+
|int8, int16, int32, int64 (int) |byte, short, int, long (int or long) |
+-------------------------------------+--------------------------------------------+
|uint8, uint16, uint32, uint64 (uint) |ubyte, ushort, uint, ulong (uint or ulong) |
+-------------------------------------+--------------------------------------------+
|float32, float64 |float, double. |
+-------------------------------------+--------------------------------------------+
|string |string |
+-------------------------------------+--------------------------------------------+
|[]byte, Binary |binary |
+-------------------------------------+--------------------------------------------+
|Symbol |symbol |
+-------------------------------------+--------------------------------------------+
|interface{} |the contained type |
+-------------------------------------+--------------------------------------------+
|nil |null |
+-------------------------------------+--------------------------------------------+
|map[K]T |map with K and T converted as above |
+-------------------------------------+--------------------------------------------+
|Map |map, may have mixed types for keys, values |
+-------------------------------------+--------------------------------------------+
|[]T |list with T converted as above |
+-------------------------------------+--------------------------------------------+
|List |list, may have mixed types values |
+-------------------------------------+--------------------------------------------+
TODO: Update the table to match rust types
TODO Rust types: array, slice, struct
Rust types that cannot be marshaled: complex64/128, uintptr, function, interface, channel
*/
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum ErrorCode {
// ADD SOMETHING HERE
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum ParserError {
/// msg, line, col
SyntaxError(ErrorCode, usize, usize),
IoError(io::ErrorKind, &'static str),
}
// Builder and Parser have the same errors.
pub type BuilderError = ParserError;
#[derive(Clone, PartialEq, Debug)]
pub enum DecoderError {
ParseError(ParserError),
ExpectedError(string::String, string::String),
MissingFieldError(string::String),
UnknownVariantError(string::String),
ApplicationError(string::String)
}
#[derive(Clone, Copy, Debug)]
pub enum EncoderError {
FmtError(fmt::Error),
BadHashmapKey,
}
pub type EncodeResult = Result<(), EncoderError>;
pub type DecodeResult<T> = Result<T, DecoderError>;
pub struct Encoder<'e> {
data: *mut proton_sys::pn_data_t,
__phantom: PhantomData<&'e ()>
}
impl<'e> Encoder<'e> {
fn new() -> Encoder<'e> {
Encoder::with_capacity(16)
}
fn with_capacity(capacity: ::libc::size_t) -> Encoder<'e> {
let data = unsafe{proton_sys::pn_data(capacity)};
Encoder {data: data, __phantom: PhantomData}
}
}
impl<'a> serialize::Encoder for Encoder<'a> {
type Error = EncoderError;
fn emit_nil(&mut self) -> EncodeResult {
Ok(unsafe{proton_sys::pn_data_put_null(&mut *self.data);})
}
fn emit_usize(&mut self, v: usize) -> EncodeResult {
Ok(unsafe{proton_sys::pn_data_put_uint(&mut *self.data, v as u32);})
}
fn emit_u64(&mut self, v: u64) -> EncodeResult {
// NOTE(flaper87): check word size
Ok(unsafe{proton_sys::pn_data_put_ulong(&mut *self.data, v);})
}
fn emit_u32(&mut self, v: u32) -> EncodeResult {
Ok(unsafe{proton_sys::pn_data_put_uint(&mut *self.data, v);})
}
fn emit_u16(&mut self, v: u16) -> EncodeResult {
Ok(unsafe{proton_sys::pn_data_put_ushort(&mut *self.data, v);})
}
fn emit_u8(&mut self, v: u8) -> EncodeResult {
Ok(unsafe{proton_sys::pn_data_put_ubyte(&mut *self.data, v);})
}
fn emit_isize(&mut self, v: isize) -> EncodeResult {
// NOTE(flaper87): check word size
Ok(unsafe{proton_sys::pn_data_put_int(&mut *self.data, v as i32);})
}
fn emit_i64(&mut self, v: i64) -> EncodeResult {
Ok(unsafe{proton_sys::pn_data_put_long(&mut *self.data, v);})
}
fn emit_i32(&mut self, v: i32) -> EncodeResult {
Ok(unsafe{proton_sys::pn_data_put_int(&mut *self.data, v);})
}
fn emit_i16(&mut self, v: i16) -> EncodeResult {
Ok(unsafe{proton_sys::pn_data_put_short(&mut *self.data, v);})
}
fn emit_i8(&mut self, v: i8) -> EncodeResult {
Ok(unsafe{proton_sys::pn_data_put_byte(&mut *self.data, v);})
}
fn emit_bool(&mut self, v: bool) -> EncodeResult {
Ok(unsafe{proton_sys::pn_data_put_bool(&mut *self.data, v as u8);})
}
fn emit_f64(&mut self, v: f64) -> EncodeResult {
Ok(unsafe{proton_sys::pn_data_put_float(&mut *self.data, v as f32);})
}
fn emit_f32(&mut self, v: f32) -> EncodeResult {
Ok(unsafe{proton_sys::pn_data_put_float(&mut *self.data, v);})
}
fn emit_char(&mut self, v: char) -> EncodeResult {
Ok(unsafe{proton_sys::pn_data_put_char(&mut *self.data, v as u32);})
}
fn emit_str(&mut self, slice: &str) -> EncodeResult {
Ok(unsafe{
let s = CString::new(slice).unwrap();
let bytes = proton_sys::pn_bytes(slice.len() as proton_sys::size_t, s.as_ptr());
proton_sys::pn_data_put_string(&mut *self.data, bytes);})
}
fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
f(self)
}
fn emit_enum_variant<F>(&mut self,
name: &str,
_id: usize,
cnt: usize,
f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
Ok(())
}
fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
f(self)
}
fn emit_enum_struct_variant<F>(&mut self,
name: &str,
id: usize,
cnt: usize,
f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_enum_variant(name, id, cnt, f)
}
fn emit_enum_struct_variant_field<F>(&mut self,
_: &str,
idx: usize,
f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_enum_variant_arg(idx, f)
}
fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
Ok(())
}
fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
f(self)
}
fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_seq(len, f)
}
fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_seq_elt(idx, f)
}
fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_seq(len, f)
}
fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_seq_elt(idx, f)
}
fn emit_option<F>(&mut self, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
f(self)
}
fn emit_option_none(&mut self) -> EncodeResult {
self.emit_nil()
}
fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
f(self)
}
fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
Ok(())
}
fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
f(self)
}
fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
Ok(())
}
fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
Ok(())
}
fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
f(self)
}
}
/// Shortcut function to encode a `T` into a JSON `String`
pub fn encode<T: serialize::Encodable>(object: &T) -> Result<Vec<i8>, EncoderError> {
let mut encoder = Encoder::new();
try!(object.encode(&mut encoder));
let mut size = 1024;
let mut bytes = Vec::with_capacity(size);
let mut result = proton_sys::PN_OVERFLOW;
while result == proton_sys::PN_OVERFLOW {
result = unsafe{proton_sys::pn_data_encode(encoder.data,
bytes.as_mut_ptr(),
size as u64) as i8};
if result > 0 {
unsafe {bytes.set_len(result as usize);}
break;
} else if result <= 0 {
// not ok
println!("ERROR");
break;
}
size *= 2;
bytes = Vec::with_capacity(size);
}
bytes.shrink_to_fit();
Ok(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::CStr;
use std::slice;
use std::str;
use proton_sys;
macro_rules! create_test {
($func:ident, $get_data:ident, $value:expr) => (
#[test]
fn $func() {
let value = $value;
let encoded = encode(&value).unwrap();
let data;
unsafe {
data = proton_sys::pn_data(1024);
let err = proton_sys::pn_data_decode(data,
encoded.as_ptr(),
encoded.len() as u64);
}
assert_eq!(1, unsafe{proton_sys::pn_data_size(data)});
assert_eq!(format!("pn_{:}", stringify!($func)),
get_type_name(data).to_lowercase());
let data_content = unsafe {
//concat_idents!(proton_sys::pn_data_get_, $func)(data)
proton_sys::$get_data(data)
};
assert_eq!(value, data_content);
}
)
}
fn get_type_name<'a>(data: *mut proton_sys::pn_data_t) -> &'a str {
unsafe{
let t = proton_sys::pn_data_type(data);
let name = proton_sys::pn_type_name(t);
CStr::from_ptr(name).to_str().unwrap()
}
}
#[test]
fn test_string_encoding() {
let value = "testing";
let encoded = encode(&value).unwrap();
let data;
unsafe {
data = proton_sys::pn_data(1024);
let err = proton_sys::pn_data_decode(data,
encoded.as_ptr(),
encoded.len() as u64);
}
assert_eq!(1, unsafe{proton_sys::pn_data_size(data)});
assert_eq!("PN_STRING", get_type_name(data));
let data_content = unsafe {
let pn_bytes = proton_sys::pn_data_get_string(data);
let data: &[u8] = slice::from_raw_parts(pn_bytes.start as *const u8,
pn_bytes.size as usize);
str::from_utf8(data).unwrap()
};
assert_eq!(value, data_content);
}
create_test!(ubyte, pn_data_get_ubyte, 1u8);
create_test!(ushort, pn_data_get_ushort, 1u16);
create_test!(uint, pn_data_get_uint, 1u32);
create_test!(ulong, pn_data_get_ulong, 1u64);
create_test!(byte, pn_data_get_byte, 1i8);
create_test!(short, pn_data_get_short, 1i16);
create_test!(int, pn_data_get_int, 1i32);
create_test!(long, pn_data_get_long, 1i64);
create_test!(float, pn_data_get_float, 1f32);
}
<file_sep>// TODO: remove these when everything is implemented
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_imports)]
extern crate mio;
extern crate libc;
extern crate rustc_serialize;
extern crate proton_sys;
#[macro_use] extern crate log;
pub use proton::{
Transport
};
mod io;
mod proton;
pub use io::{
AmqpHandler
};
<file_sep>use mio::*;
use mio::tcp::*;
use mio::buf::{ByteBuf, MutByteBuf, SliceBuf};
use mio::util::Slab;
use std::io;
use proton;
type AmqpEventLoop = EventLoop<AmqpHandler>;
struct AmqpSocket {
sock: NonBlock<TcpStream>,
buf: Option<ByteBuf>,
mut_buf: Option<MutByteBuf>,
token: Option<Token>,
interest: Interest,
connection: proton::Connection,
transport: proton::Transport,
}
impl AmqpSocket {
fn new(sock: NonBlock<TcpStream>) -> AmqpSocket {
let mut transport = proton::Transport::new();
let mut connection = proton::Connection::new();
transport.bind(&mut connection);
AmqpSocket {
sock: sock,
buf: None,
mut_buf:Some(ByteBuf::mut_with_capacity(2048)),
token: None,
interest: Interest::hup(),
connection: connection,
transport: transport
}
}
fn writable(&mut self, event_loop: &mut AmqpEventLoop) -> io::Result<()> {
let mut buf = self.buf.take().unwrap();
debug!("CON : writing buf = {:?}", buf.bytes());
match self.sock.write(&mut buf) {
Ok(None) => {
debug!("client flushing buf; WOULDBLOCK");
self.buf = Some(buf);
self.interest.insert(Interest::writable());
}
Ok(Some(r)) => {
debug!("CONN : we wrote {} bytes!", r);
self.mut_buf = Some(buf.flip());
self.interest.insert(Interest::readable());
self.interest.remove(Interest::writable());
}
Err(e) => debug!("not implemented; client err={:?}", e),
}
event_loop.reregister(&self.sock, self.token.unwrap(), self.interest, PollOpt::edge() | PollOpt::oneshot())
}
fn readable(&mut self, event_loop: &mut AmqpEventLoop) -> io::Result<()> {
let mut buf = self.mut_buf.take().unwrap();
match self.sock.read(&mut buf) {
Ok(None) => {
panic!("We just got readable, but were unable to read from the socket?");
}
Ok(Some(r)) => {
println!("CONN : we read {} bytes!", r);
//self.transport.push(buf.mut_bytes());
if !self.transport.has_capacity() {
debug!("No capacity. Turning to writable");
//self.interest.remove(Interest::readable());
//self.interest.insert(Interest::writable());
}
self.interest.remove(Interest::readable());
self.interest.insert(Interest::writable());
}
Err(e) => {
debug!("not implemented; client err={:?}", e);
self.interest.remove(Interest::readable());
}
};
self.buf = Some(buf.flip());
event_loop.reregister(&self.sock,
self.token.unwrap(),
self.interest,
PollOpt::edge())
}
}
struct AmqpAcceptor {
sock: NonBlock<TcpListener>,
conns: Slab<AmqpSocket>
}
impl AmqpAcceptor {
fn accept(&mut self, event_loop: &mut AmqpEventLoop) -> io::Result<()> {
debug!("server accepting socket");
let sock = self.sock.accept().unwrap().unwrap();
let conn = AmqpSocket::new(sock);
let tok = self.conns.insert(conn)
.ok().expect("could not add connectiont o slab");
// Register the connection
self.conns[tok].token = Some(tok);
event_loop.register_opt(&self.conns[tok].sock, tok, Interest::readable(), PollOpt::edge() | PollOpt::oneshot())
.ok().expect("could not register socket with event loop");
Ok(())
}
fn conn_readable(&mut self, event_loop: &mut AmqpEventLoop, tok: Token) -> io::Result<()> {
debug!("server conn readable; tok={:?}", tok);
self.conn(tok).readable(event_loop)
}
fn conn_writable(&mut self, event_loop: &mut AmqpEventLoop, tok: Token) -> io::Result<()> {
debug!("server conn writable; tok={:?}", tok);
self.conn(tok).writable(event_loop)
}
fn conn<'a>(&'a mut self, tok: Token) -> &'a mut AmqpSocket {
&mut self.conns[tok]
}
}
pub struct AmqpHandler {
sock: AmqpAcceptor
}
impl AmqpHandler {
pub fn new(address: &str) -> AmqpHandler {
let addr = address.parse().unwrap();
let srv = tcp::v4().unwrap();
info!("setting re-use addr");
srv.set_reuseaddr(true).unwrap();
srv.bind(&addr).unwrap();
let srv = srv.listen(256usize).unwrap();
AmqpHandler::with_acceptor(srv)
}
pub fn sock(&self) -> &TcpListener {
&self.sock.sock
}
pub fn with_acceptor(acceptor: NonBlock<TcpListener>) -> AmqpHandler {
AmqpHandler{
sock: AmqpAcceptor {
sock: acceptor,
conns: Slab::new_starting_at(Token(1), 128)
}
}
}
}
impl Handler for AmqpHandler {
type Timeout = usize;
type Message = ();
fn writable(&mut self, event_loop: &mut AmqpEventLoop, token: Token) {
println!("writable");
match token {
Token(0) => panic!("received writable for token 0"),
//CLIENT => self.client.writable(event_loop).unwrap(),
_ => self.sock.conn_writable(event_loop, token).unwrap()
};
}
fn readable(&mut self, event_loop: &mut AmqpEventLoop, token: Token, hint: ReadHint) {
assert!(hint.is_data());
match token {
Token(0) => self.sock.accept(event_loop).unwrap(),
//CLIENT => self.client.readable(event_loop).unwrap(),
i => self.sock.conn_readable(event_loop, i).unwrap()
};
}
}
|
d798ea1dbee0c991d07a4347c69b5609ead0cc36
|
[
"TOML",
"Rust",
"C"
] | 9
|
Rust
|
FlaPer87/rust-proton
|
1832cc0526d94604846b58754b62c9ff2086e122
|
21d2c883fcfa27245456119029f057247e350cb9
|
refs/heads/master
|
<repo_name>PR72510/AsyncTaskProject<file_sep>/app/src/main/java/com/example/asynctaskproject/MainActivity.java
package com.example.asynctaskproject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.Image;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
public class MainActivity extends AppCompatActivity {
MyBroadcastReciever reciever;
static MainActivity activity;
private static final String TAG = "MainActivity";
ProgressBar mProgressBar;
String src = "https://i.redd.it/efcrd1vc4ql21.jpg";
Button btn_dwld, btn_dwld_ser;
ImageView image;
// public static final int progress_bar_type = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reciever = new MyBroadcastReciever();
activity = this;
btn_dwld = (Button) findViewById(R.id.btn_dwld);
btn_dwld_ser = (Button) findViewById(R.id.btn_dwld_ser);
image = (ImageView) findViewById(R.id.image);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
// pDialog = new ProgressDialog(this);
btn_dwld.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "onClick: ");
new DownloadTask(MainActivity.this).execute(src);
}
});
btn_dwld_ser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MyServices.class);
intent.putExtra("URL", src);
Log.i(TAG, "onClick: Service");
startService(intent);
}
});
}
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(reciever, filter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(reciever);
}
public static MainActivity getInstance() {
return activity;
}
}<file_sep>/app/src/main/java/com/example/asynctaskproject/MyServices.java
package com.example.asynctaskproject;
import android.app.IntentService;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MyServices extends IntentService {
Bitmap bmImg = null;
MainActivity activity = MainActivity.getInstance();
private static final String TAG = "MyServices";
public MyServices() {
super("MyServices");
}
@Override
public IBinder onBind(Intent intent) {
return super.onBind(intent);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
String url = intent.getStringExtra("URL");
Log.i(TAG, "onHandleIntent: " + url);
try {
Log.i(TAG, "onHandleIntent: 1st");
int count;
URL url1 = new URL(url);
URLConnection urlConnection = url1.openConnection();
urlConnection.connect();
InputStream inputStream = new BufferedInputStream(url1.openStream());
byte[] data1 = new byte[1024];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Log.i(TAG, "onHandleIntent: 2nd");
/*returns int in the range of 0 to 255. If no byte is
available because the end of the stream has been reached, the returned value is -1.
*/
while((count = inputStream.read(data1)) != -1){ // Reads some number of bytes from the input stream and stores them into the buffer array b
outputStream.write(data1, 0 , count); // Writes len bytes from the specified byte array starting at offset off to this output stream
}
byte[] imageData = outputStream.toByteArray();
bmImg = BitmapFactory.decodeByteArray(imageData, 0,imageData.length);
Log.i(TAG, "onHandleIntent: 3rd" + bmImg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onDestroy() {
activity.image.setImageBitmap(bmImg);
Log.i(TAG, "onDestroy: ");
}
}
|
78ed1299232622ce8e0bd5c94b34e54832e9b63f
|
[
"Java"
] | 2
|
Java
|
PR72510/AsyncTaskProject
|
691709da21c5e4ec1d674ec378e05ff30e902045
|
e9fa16dc59e46261263af4ab3ab3d2771f8048bb
|
refs/heads/master
|
<file_sep>document.write("hello world");
var myname="Saurabh";
var age:number=22;
var canvote:boolean=true;
document.write(" Hello!!");
//document.getElementById("a").innerHTML="I am"+age;
document.write("<br><br>"+"type of name is "+typeof(name));
document.write("<br><br>"+"type of age is "+typeof(age));
document.write("<br><br>"+"type of canvote is "+typeof(canvote));
const pi=3.14;
//pi=22;
document.write("<br>PI is a "+typeof(pi)+" "+pi);
var randomarr=[5,6,55,6,5];
for(var val in randomarr){
document.write("<br>"+val)
}
var mappedarr=randomarr.map(Math.sqrt);
for(var i in mappedarr)
{
document.write("<br>"+i)
}
var addone=(x)=>
{
return x+1;
}
console.log(addone(1));
var addone=(x)=>x+2;
console.log(addone(1));
var getsum=function(num1:number,num2:number):number
{
return num1+num2;
}
var ans:number=getsum(2,2);
console.log(getsum(2,2));
console.log(ans);
var total=[2,3,5].reduce(
function(a,b)
{
return a+b;
}
);
console.log(total);
var sumall = function(...nums:number[]):void
{
var sum=nums.reduce((a,b)=>a+b);
document.write("<br>"+sum);
}
sumall(2,3);
sumall(2,3,4);<file_sep>namespace Mobile{
export class MobileDetails{
mobileId:number;
mobileName:string;
mobileCost:number;
printMobileDetail(){
console.log(this.mobileId+","+this.mobileName+","+this.mobileCost);
}
}
}<file_sep>///<reference path="mobile.ts"/>
///<reference path="BasicPhone.ts"/>
///<reference path="SmartPhone.ts"/>
var data = [
{
"mobileId":1000,
"mobileName":"Note 8",
"mobileCost":67000,
"mobileType":"Android"
},
{
"mobileId":1001,
"mobileName":"IPhone X",
"mobileCost":89000,
"mobileType":"iOS"
}
]
function printDetails(phone){
phone.printMobileDetail();
}
var bobj=new Mobile.BasicPhone();
bobj.mobileId=data[1].mobileId;
bobj.mobileName=data[1].mobileName;
bobj.mobileCost=data[1].mobileCost;
bobj.mobileType=data[1].mobileType;
printDetails(bobj);
var sobj=new Mobile.SmartPhone();
sobj.mobileId=data[0].mobileId;
sobj.mobileName=data[0].mobileName;
sobj.mobileCost=data[0].mobileCost;
sobj.mobileType=data[0].mobileType;
printDetails(sobj);<file_sep>///<reference path="mobile.ts"/>
namespace Mobile{
export class SmartPhone extends MobileDetails{
mobileType:string;
printMobileDetail(){
console.log(this.mobileId+","+this.mobileName+","+this.mobileCost+","+this.mobileType);
}
}
}
|
4847f50482fa804cc7d688febe3acfd278c7d402
|
[
"TypeScript"
] | 4
|
TypeScript
|
saurabhgupta8196/Typescript
|
fe62b291b0eae19f13db8e2bc8d25cb81d01d0b3
|
591a2c405a8b47c000220dbfd64f4e3a5cee6fdc
|
refs/heads/master
|
<file_sep>######################################################################################################
# saumya's personal development boot strap configuration
######################################################################################################
# git config
export PATH="/usr/local/git/bin:$PATH"
# ant
export PATH="/Users/saumya/1_devhome/1_toolkits/apache-ant-1.9.4/bin/:$PATH"
# Gradle
export PATH="/Users/saumya/1_devhome/1_toolkits/gradle/gradle-2.10/bin/:$PATH"
######################################################################################################
# android SDK
export PATH="$PATH:/Users/saumya/1_devhome/1_toolkits/android/android-sdk-macosx/tools"
export PATH="$PATH:/Users/saumya/1_devhome/1_toolkits/android/android-sdk-macosx/platform-tools"
# android NDK
export PATH="$PATH:/Users/saumya/1_devhome/1_toolkits/android/android-ndk-r9b"
#################################### N M E ##########################################################
##### setup for Android
# export ANDROID_HOME=/Users/saumya/1_devhome/1_toolkits/android/android-sdk-macosx
export ANDROID_SDK="/Users/saumya/1_devhome/1_toolkits/android/android-sdk-macosx"
export ANDROID_NDK_ROOT="/Users/saumya/1_devhome/1_toolkits/android/android-ndk-r9b"
export ANDROID_NDK_DIR="/Users/saumya/1_devhome/1_toolkits/android/android-ndk-r9b"
######################################################################################################
# XAMP : mySql
export PATH="$PATH:/Applications/XAMPP/xamppfiles/bin"
### Added by the Heroku Toolbelt
export PATH="/usr/local/heroku/bin:$PATH"
<file_sep>Configuration files of a development machine
============================================
For MAC users :
Generally as a MAC user, its easier to configure teh whole system with the help of some entries in particular files. Thisrepo consists of the configuration files of my own machine.
### Details of the different settings :
#### Linux(Ubuntu) environment :
- `.bashrc` is for Ubuntu
#### Windows environment :
TODO
#### MAC environment
- `.bash_profile` : used for setting PATH for the whole system
- The entries of this file is generally used for system wide settings
- present in ~/ , in a MAC this is the location of user root; ie; the logged in user's root directory
#### Sublime Text 3
- Preferences.sublime-settings : used to configure SublimeText
- Configures SublimeText
- Location of this file is at
~/Library/Application Support/Sublime Text 3/Packages/User
- TODO
|
dbecbcd8e24edde71d5758ebcb639827d6a15cff
|
[
"Markdown",
"Shell"
] | 2
|
Shell
|
saumya/ConfigFiles
|
5c7c33ae367f7e5b63b5aaef120d78995a23ab40
|
47074cf3fd8cad2777f4bb86e0332d9fc538b798
|
refs/heads/master
|
<repo_name>hansolasus/LINE-BOT-PHP-Starter<file_sep>/bot.php
<?php
$access_token = '<KEY>';
// Get POST body content
$content = file_get_contents('php://input');
// Parse JSON
$events = json_decode($content, true);
// Validate parsed JSON data
if (!is_null($events['events'])) {
// Loop through each event
foreach ($events['events'] as $event) {
// Reply only when message sent is in 'text' format
if ($event['type'] == 'message' && $event['message']['type'] == 'text') {
// Get text sent
$text = $event['message']['text'];
$msgCount = strlen($text);
if (strpos($text, 'สุดา') !== false) { // note: three equal signs
$text = 'สุดาแก่มาก!!!!';
}else if(strpos($text, 'แบงค์') !== false){
$text = 'แบงค์หน้าตาดีมาก!!!!';
}else if(strpos($text, 'เก่ง') !== false){
$text = 'เก่งขี้เหล้าจัง!!!!';
}else if(strpos($text, 'แจง') !== false){
$text = 'แจงไม่สวยเลย!!!!';
}else if(strpos($text, 'ตุ้ย') !== false){
$text = 'ครางชื่อตุ้ยหน่อย!!!!';
}else if(strpos($text, 'มด') !== false){
if($msgCount % 2 == 0){
$text = 'มดดำเป็นตอตะโก!!!!';
}else{
$text = 'มดดำตับเป็ด!!!!';
}
}else if(strpos($text, 'ต้อม') !== false){
$text = 'พี่ต้อมผู้ใหญ่ใจดี ชอบเลี้ยงน้องๆ';
}else{
$text = '';
}
if($text != ''){
// Get replyToken
$replyToken = $event['replyToken'];
// Build message to reply back
$messages = [
'type' => 'text',
'text' => $text
];
// Make a POST Request to Messaging API to reply to sender
$url = 'https://api.line.me/v2/bot/message/reply';
$data = [
'replyToken' => $replyToken,
'messages' => [$messages],
];
$post = json_encode($data);
$headers = array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);
echo $result . "\r\n";
}
}
}
}
echo "OK";
?><file_sep>/testWebservice.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$client = new SoapClient("http://www.scadachaopraya.com/CPYProvider.asmx?wsdl",
array(
"trace" => 1, // enable trace to view what is happening
"exceptions" => 0, // disable exceptions
"cache_wsdl" => 0) // disable any caching on the wsdl, encase you alter the wsdl server
);
$params = array(
'stn_id' => "1"
);
$data = $client->LastDataByID($params);
print_r($data);
echo "<hr>";
echo $data->LastDataByIDResult;
echo "<hr>";
// display what was sent to the server (the request)
echo "<p>Request :".htmlspecialchars($client->__getLastRequest()) ."</p>";
echo "<hr>";
// display the response from the server
echo "<p>Response:".htmlspecialchars($client->__getLastResponse())."</p>";
?>
|
2366d29641c60f431acc7915b8beee5000b78164
|
[
"PHP"
] | 2
|
PHP
|
hansolasus/LINE-BOT-PHP-Starter
|
288d397f9638bce074fd4e3fc02fbd7d19dc93c8
|
1e45c33793ac69721f21126b2f30dd3348c34549
|
refs/heads/master
|
<repo_name>sardarasifjahan/DockerTesting<file_sep>/src/main/java/com/payment/repositiory/ProductRepositiory.java
package com.payment.repositiory;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.payment.pojo.Product;
@Repository
public interface ProductRepositiory extends CrudRepository<Product,Integer>{
}
|
5f839caae2cf84b341c85bd979f320647ef94879
|
[
"Java"
] | 1
|
Java
|
sardarasifjahan/DockerTesting
|
d258e963d59217ab391f651f73a0b7ccaa0b381e
|
0a8b8f661cc51ece8137de019c4a057a816b36cc
|
refs/heads/master
|
<file_sep>'use strict';
/**
* @ngdoc function
* @name basicoangularApp.controller:Vt5Ctrl
* @description
* # Vt5Ctrl
* Controller of the basicoangularApp
*/
var aplicacion = angular.module('basicoangularApp');
aplicacion.factory('factory',function(){
return {mensaje:'saludo desde la fabrica'};
});
aplicacion.controller('ControladorUno', function ($scope, factory) {
$scope.dato = factory;
});
<file_sep>'use strict';
/**
* @ngdoc function
* @name basicoangularApp.controller:Vt4Ctrl
* @description
* # Vt4Ctrl
* Controller of the basicoangularApp
*/
angular.module('basicoangularApp')
.controller('Vt4Ctrl', function ($scope) {
$scope.clientes = [
{codigo:'1',razonSocial:'Marta', direccion:'<NAME> 10980', telefono:'0342-4592354',saldo:'135.85',dia: new Date()},
{codigo:'2',razonSocial:'<NAME>',direccion:'Francia 3100',telefono:'0342-4520981',saldo:'245.00',dia: new Date()},
{codigo:'3',razonSocial:'<NAME>',direccion:'cochabamba 1589',telefono:'0342-4589654',saldo:'0',dia: new Date()},
{codigo:'4',razonSocial:'Elias',direccion:'Pte Pero 1256',telefono:'0342-4586235',saldo:'1009.50',dia: new Date()},
{codigo:'5',razonSocial:'Jara',direccion:'J D Solis 2953',telefono:'0342-4589632',saldo:'0.00',dia: new Date()},
{codigo:'6',razonSocial:'<NAME>',direccion:'Avellaneda 3541',telefono:'0342-4512365',saldo:'890.4',dia: new Date()},
{codigo:'7',razonSocial:'Ministerio',direccion:'Bv Pellegrini 3100',telefono:'0342-4536582', saldo:'10000.85',dia: new Date()}
];
$scope.ordenarPor= function(orden){
$scope.ordenSeleccionado= orden;
};
});
<file_sep>'use strict';
/**
* @ngdoc function
* @name basicoangularApp.controller:Vt2Ctrl
* @description
* # Vt2Ctrl
* Controller of the basicoangularApp
*/
angular.module('basicoangularApp')
.controller('Vt2Ctrl', function ($scope) {
$scope.tareas = [
{texto: 'Estudiar', hecho:true},
{texto: 'Rendir', hecho:true},
{texto: 'Salir', hecho:false},
];
});
<file_sep>'use strict';
/**
* @ngdoc function
* @name basicoangularApp.controller:Vt2Ctrl
* @description
* # Vt2Ctrl
* Controller of the basicoangularApp
*/
angular.module('basicoangularApp')
.controller('Vt3Ctrl', function ($scope) {
$scope.tareas = [
{texto: 'Estudiar', hecho:true},
{texto: 'Rendir', hecho:true},
{texto: 'Salir', hecho:false},
];
$scope.agregarTarea= function(){
$scope.tareas.push({texto: $scope.txtnuevaTarea, hecho:false});
$scope.txtnuevaTarea= '';
};
$scope.restantes=function (){
var cuenta=0;
angular.forEach($scope.tareas, function(tarea) {
cuenta+= tarea.hecho ? 0 : 1;
});
return cuenta;
};
$scope.eliminarTarea= function(){
var tareasViejas= $scope.tareas;
$scope.tareas=[];
angular.forEach(tareasViejas, function(tarea){
if(!tarea.hecho) {$scope.tareas.push(tarea);}
});
};
});
|
924928a12fb55dced498e2654c2e8620fee1e784
|
[
"JavaScript"
] | 4
|
JavaScript
|
agespinosa/app
|
1d69217919fb93c46fe75ba669a1aea85bfc4898
|
1622b0b855b7c5820779a7a3187d4f3fd9c86575
|
refs/heads/master
|
<repo_name>franktranvantu/java-8<file_sep>/README.md
Contains examples about Java 8<file_sep>/convert-iterator-to-stream/iterable-to-stream/src/com/frank/Main.java
package com.frank;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public class Main {
public static void main(String[] args) {
Iterable<String> list = Arrays.asList("mkyong", "java", "kotlin", "spring boot", "android");
List<Integer> result = StreamSupport.stream(list.spliterator(), false)
.map(x -> x.length())
.collect(Collectors.toList());
result.forEach(System.out::println);
}
}
|
ec9c810e0efab5ae7c965ed24f6b31c10672c69f
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
franktranvantu/java-8
|
eecf643ffdf1f058e9f4644a093bff34f3f7289f
|
aa7eee6325c7f41ba1f2de0be2283047c3fe9d94
|
refs/heads/master
|
<repo_name>HttPaul/project1<file_sep>/project1.js
/**
* Created by Paul on 5/20/2016.
*/
var testing = "Timothy's Test";
for(var i = 0; i < 100; i++){
console.log(testing);
}
|
b1871a239f7b68292d19826a72cdca1cee30a87d
|
[
"JavaScript"
] | 1
|
JavaScript
|
HttPaul/project1
|
a1f37eb45d461bb2720de219eda70f8d885dce2f
|
2099c082791e4b15eb4552f420d66c06a09390f5
|
refs/heads/master
|
<repo_name>ArrangementMaker/django-twittercard<file_sep>/twittercard/templatetags/twittercard.py
from django import template
from django.conf import settings
register = template.Library()
def twittercard_summary(context, *args, **kwargs):
card = get_twittercard_attributes(kwargs)
card['card'] = 'summary'
request = context['request']
card['url'] = kwargs.get('url', request.build_absolute_uri())
return card
register.inclusion_tag('twittercard/summary.html', takes_context=True)(twittercard_summary)
def twittercard_photo(context, *args, **kwargs):
card = get_twittercard_attributes(kwargs)
card['card'] = 'photo'
card['image_width'] = kwargs.get('image_width', None)
card['image_height'] = kwargs.get('image_height', None)
return card
register.inclusion_tag('twittercard/photo.html', takes_context=True)(twittercard_photo)
def get_twittercard_attributes(kwargs):
card = {}
card['title'] = kwargs.get('title', None)
card['description'] = kwargs.get('description', None)
card['image'] = kwargs.get('image', None)
config = getattr(settings, 'TWITTERCARD_CONFIG', None)
if config is not None:
card['site'] = kwargs.get('site', config.get('SITE', None))
card['site_id'] = kwargs.get('site_id', config.get('SITE_ID', None))
card['creator'] = kwargs.get('creator', config.get('CREATOR', None))
card['creator_id'] = kwargs.get('creator_id', config.get('CREATOR_ID', None))
return card
|
841b92e9e18d0b045bcf2b73040636bc973d4807
|
[
"Python"
] | 1
|
Python
|
ArrangementMaker/django-twittercard
|
e17cd6cdf4769f1d90f7b30fef6cc297119fd73a
|
ab3514656dc501669c4fad482e1f946bd84a2077
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.