code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
"""Games, or Adversarial Search. (Chapters 6)
"""
from utils import infinity, argmax, argmax_random_tie, num_or_str, Dict, update
from utils import if_, Struct
import random
import time
#______________________________________________________________________________
# Minimax Search
def minimax_decision(state, game):
"""Given a state in a game, calculate the best move by searching
forward all the way to the terminal states. [Fig. 6.4]"""
player = game.to_move(state)
def max_value(state):
if game.terminal_test(state):
return game.utility(state, player)
v = -infinity
for (_, s) in game.successors(state):
v = max(v, min_value(s))
return v
def min_value(state):
if game.terminal_test(state):
return game.utility(state, player)
v = infinity
for (_, s) in game.successors(state):
v = min(v, max_value(s))
return v
# Body of minimax_decision starts here:
action, state = argmax(game.successors(state),
lambda ((a, s)): min_value(s))
return action
#______________________________________________________________________________
def alphabeta_full_search(state, game):
"""Search game to determine best action; use alpha-beta pruning.
As in [Fig. 6.7], this version searches all the way to the leaves."""
player = game.to_move(state)
def max_value(state, alpha, beta):
if game.terminal_test(state):
return game.utility(state, player)
v = -infinity
for (a, s) in game.successors(state):
v = max(v, min_value(s, alpha, beta))
if v >= beta:
return v
alpha = max(alpha, v)
return v
def min_value(state, alpha, beta):
if game.terminal_test(state):
return game.utility(state, player)
v = infinity
for (a, s) in game.successors(state):
v = min(v, max_value(s, alpha, beta))
if v <= alpha:
return v
beta = min(beta, v)
return v
# Body of alphabeta_search starts here:
action, state = argmax(game.successors(state),
lambda ((a, s)): min_value(s, -infinity, infinity))
return action
def alphabeta_search(state, game, d=4, cutoff_test=None, eval_fn=None):
"""Search game to determine best action; use alpha-beta pruning.
This version cuts off search and uses an evaluation function."""
player = game.to_move(state)
def max_value(state, alpha, beta, depth):
if cutoff_test(state, depth):
return eval_fn(state)
v = -infinity
succ = game.successors(state)
for (a, s) in succ:
v = max(v, min_value(s, alpha, beta, depth+1))
if v >= beta:
succ.close()
return v
alpha = max(alpha, v)
return v
def min_value(state, alpha, beta, depth):
if cutoff_test(state, depth):
return eval_fn(state)
v = infinity
succ = game.successors(state)
for (a, s) in succ:
v = min(v, max_value(s, alpha, beta, depth+1))
if v <= alpha:
succ.close()
return v
beta = min(beta, v)
return v
# Body of alphabeta_search starts here:
# The default test cuts off at depth d or at a terminal state
cutoff_test = (cutoff_test or
(lambda state,depth: depth>d or game.terminal_test(state)))
eval_fn = eval_fn or (lambda state: game.utility(player, state))
action, state = argmax_random_tie(game.successors(state),
lambda ((a, s)): min_value(s, -infinity,
infinity, 0))
return action
#______________________________________________________________________________
# Players for Games
def query_player(game, state):
"Make a move by querying standard input."
game.display(state)
return num_or_str(raw_input('Your move? '))
def random_player(game, state):
"A player that chooses a legal move at random."
return random.choice(game.legal_moves())
def alphabeta_player(game, state):
return alphabeta_search(state, game)
def play_game(game, *players):
"Play an n-person, move-alternating game."
print game.curr_state
while True:
for player in players:
if game.curr_state.to_move == player.color:
move = player.select_move(game)
print game.make_move(move)
if game.terminal_test():
return game.utility(player.color)
#______________________________________________________________________________
# Some Sample Games
class Game:
"""A game is similar to a problem, but it has a utility for each
state and a terminal test instead of a path cost and a goal
test. To create a game, subclass this class and implement
legal_moves, make_move, utility, and terminal_test. You may
override display and successors or you can inherit their default
methods. You will also need to set the .initial attribute to the
initial state; this can be done in the constructor."""
def legal_moves(self, state):
"Return a list of the allowable moves at this point."
abstract
def make_move(self, move, state):
"Return the state that results from making a move from a state."
abstract
def utility(self, state, player):
"Return the value of this final state to player."
abstract
def terminal_test(self, state):
"Return True if this is a final state for the game."
return not self.legal_moves(state)
def to_move(self, state):
"Return the player whose move it is in this state."
return state.to_move
def display(self, state):
"Print or otherwise display the state."
print state
def successors(self, state):
"Return a list of legal (move, state) pairs."
return [(move, self.make_move(move, state))
for move in self.legal_moves(state)]
def __repr__(self):
return '<%s>' % self.__class__.__name__
class Fig62Game(Game):
"""The game represented in [Fig. 6.2]. Serves as a simple test case.
>>> g = Fig62Game()
>>> minimax_decision('A', g)
'a1'
>>> alphabeta_full_search('A', g)
'a1'
>>> alphabeta_search('A', g)
'a1'
"""
succs = {'A': [('a1', 'B'), ('a2', 'C'), ('a3', 'D')],
'B': [('b1', 'B1'), ('b2', 'B2'), ('b3', 'B3')],
'C': [('c1', 'C1'), ('c2', 'C2'), ('c3', 'C3')],
'D': [('d1', 'D1'), ('d2', 'D2'), ('d3', 'D3')]}
utils = Dict(B1=3, B2=12, B3=8, C1=2, C2=4, C3=6, D1=14, D2=5, D3=2)
initial = 'A'
def successors(self, state):
return self.succs.get(state, [])
def utility(self, state, player):
if player == 'MAX':
return self.utils[state]
else:
return -self.utils[state]
def terminal_test(self, state):
return state not in ('A', 'B', 'C', 'D')
def to_move(self, state):
return if_(state in 'BCD', 'MIN', 'MAX')
class TicTacToe(Game):
"""Play TicTacToe on an h x v board, with Max (first player) playing 'X'.
A state has the player to move, a cached utility, a list of moves in
the form of a list of (x, y) positions, and a board, in the form of
a dict of {(x, y): Player} entries, where Player is 'X' or 'O'."""
def __init__(self, h=3, v=3, k=3):
update(self, h=h, v=v, k=k)
moves = [(x, y) for x in range(1, h+1)
for y in range(1, v+1)]
self.initial = Struct(to_move='X', utility=0, board={}, moves=moves)
def legal_moves(self, state):
"Legal moves are any square not yet taken."
return state.moves
def make_move(self, move, state):
if move not in state.moves:
return state # Illegal move has no effect
board = state.board.copy(); board[move] = state.to_move
moves = list(state.moves); moves.remove(move)
return Struct(to_move=if_(state.to_move == 'X', 'O', 'X'),
utility=self.compute_utility(board, move, state.to_move),
board=board, moves=moves)
def utility(self, state):
"Return the value to X; 1 for win, -1 for loss, 0 otherwise."
return state.utility
def terminal_test(self, state):
"A state is terminal if it is won or there are no empty squares."
return state.utility != 0 or len(state.moves) == 0
def display(self, state):
board = state.board
for x in range(1, self.h+1):
for y in range(1, self.v+1):
print board.get((x, y), '.'),
print
def compute_utility(self, board, move, player):
"If X wins with this move, return 1; if O return -1; else return 0."
if (self.k_in_row(board, move, player, (0, 1)) or
self.k_in_row(board, move, player, (1, 0)) or
self.k_in_row(board, move, player, (1, -1)) or
self.k_in_row(board, move, player, (1, 1))):
return if_(player == 'X', +1, -1)
else:
return 0
def k_in_row(self, board, move, player, (delta_x, delta_y)):
"Return true if there is a line through move on board for player."
x, y = move
n = 0 # n is number of moves in row
while board.get((x, y)) == player:
n += 1
x, y = x + delta_x, y + delta_y
x, y = move
while board.get((x, y)) == player:
n += 1
x, y = x - delta_x, y - delta_y
n -= 1 # Because we counted move itself twice
return n >= self.k
class ConnectFour(TicTacToe):
"""A TicTacToe-like game in which you can only make a move on the bottom
row, or in a square directly above an occupied square. Traditionally
played on a 7x6 board and requiring 4 in a row."""
def __init__(self, h=7, v=6, k=4):
TicTacToe.__init__(self, h, v, k)
def legal_moves(self, state):
"Legal moves are any square not yet taken."
return [(x, y) for (x, y) in state.moves
if y == 0 or (x, y-1) in state.board]
| 00eadeyemi-clone | games.py | Python | mit | 10,347 |
from Tkinter import *
from tkSimpleDialog import Dialog
from globalconst import *
class AboutBox(Dialog):
def body(self, master):
self.canvas = Canvas(self, width=300, height=275)
self.canvas.pack(side=TOP, fill=BOTH, expand=0)
self.canvas.create_text(152,47,text='Raven', fill='black',
font=('Helvetica', 36))
self.canvas.create_text(150,45,text='Raven', fill='white',
font=('Helvetica', 36))
self.canvas.create_text(150,85,text='Version '+ VERSION,
fill='black',
font=('Helvetica', 12))
self.canvas.create_text(150,115,text='An open source checkers program',
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,130,text='by Brandon Corfman',
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,160,text='Evaluation function translated from',
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,175,text="Martin Fierz's Simple Checkers",
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,205,text="Alpha-beta search code written by",
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,220,text="Peter Norvig for the AIMA project;",
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,235,text="adopted for checkers usage",
fill='black',
font=('Helvetica', 10))
self.canvas.create_text(150,250,text="by Brandon Corfman",
fill='black',
font=('Helvetica', 10))
return self.canvas
def cancel(self, event=None):
self.destroy()
def buttonbox(self):
self.button = Button(self, text='OK', padx='5m', command=self.cancel)
self.blank = Canvas(self, width=10, height=20)
self.blank.pack(side=BOTTOM, fill=BOTH, expand=0)
self.button.pack(side=BOTTOM)
self.button.focus_set()
self.bind("<Escape>", self.cancel)
| 00eadeyemi-clone | aboutbox.py | Python | mit | 2,561 |
import copy, textwrap
from globalconst import *
from move import Move
from checkers import Checkers
class SavedGame(object):
def __init__(self):
self._model = Checkers()
self.to_move = None
self.moves = []
self.description = ''
self.black_men = []
self.white_men = []
self.black_kings = []
self.white_kings = []
self.flip_board = False
self.num_players = 1
self._move_check = False
self._bm_check = False
self._bk_check = False
self._wm_check = False
self._wk_check = False
def _write_positions(self, f, prefix, positions):
f.write(prefix + ' ')
for p in sorted(positions):
f.write('%d ' % p)
f.write('\n')
def _write_moves(self, f):
f.write('<moves>\n')
for move in reversed(self.moves):
start = keymap[move.affected_squares[FIRST][0]]
dest = keymap[move.affected_squares[LAST][0]]
movestr = '%d-%d' % (start, dest)
annotation = move.annotation
if annotation.startswith(movestr):
annotation = annotation.replace(movestr, '', 1).rstrip()
f.write('%s;%s\n' % (movestr, annotation))
def write(self, filename):
with open(filename, 'w') as f:
f.write('<description>\n')
for line in self.description.splitlines():
# numbered lists or hyperlinks are not word wrapped.
if line.startswith('# ') or '[[' in line:
f.write(line + '\n')
continue
else:
f.write(textwrap.fill(line, 80) + '\n')
f.write('<setup>\n')
if self.to_move == WHITE:
f.write('white_first\n')
elif self.to_move == BLACK:
f.write('black_first\n')
else:
raise ValueError, "Unknown value for to_move variable"
if self.num_players >=0 and self.num_players <=2:
f.write('%d_player_game\n' % self.num_players)
else:
raise ValueError, "Unknown value for num_players variable"
if self.flip_board:
f.write('flip_board 1\n')
else:
f.write('flip_board 0\n')
self._write_positions(f, 'black_men', self.black_men)
self._write_positions(f, 'black_kings', self.black_kings)
self._write_positions(f, 'white_men', self.white_men)
self._write_positions(f, 'white_kings', self.white_kings)
self._write_moves(f)
def read(self, filename):
with open(filename, 'r') as f:
lines = f.readlines()
linelen = len(lines)
i = 0
while True:
if i >= linelen:
break
line = lines[i].strip()
if line.startswith('<description>'):
self.description = ''
i += 1
while i < linelen and not lines[i].startswith('<setup>'):
self.description += lines[i]
i += 1
elif line.startswith('<setup>'):
i = self._parse_setup(lines, i, linelen)
elif line.startswith('<moves>'):
i = self._parse_moves(lines, i, linelen)
else:
raise IOError, 'Unrecognized section in file, line %d' % (i+1)
def _parse_items(self, line):
men = line.split()[1:]
return map(int, men)
def _add_men_to_board(self, locations, val):
squares = self._model.curr_state.squares
try:
for loc in locations:
idx = squaremap[loc]
squares[idx] = val
except ValueError:
raise IOError, 'Checker location not valid, line %d' % (i+1)
def _parse_setup(self, lines, idx, linelen):
curr_state = self._model.curr_state
curr_state.clear()
idx += 1
while idx < linelen and '<moves>' not in lines[idx]:
line = lines[idx].strip().lower()
if line == 'white_first':
self.to_move = curr_state.to_move = WHITE
self._move_check = True
elif line == 'black_first':
self.to_move = curr_state.to_move = BLACK
self._move_check = True
elif line.endswith('player_game'):
numstr, _ = line.split('_', 1)
self.num_players = int(numstr)
elif line.startswith('flip_board'):
_, setting = line.split()
val = int(setting)
self.flip_board = True if val else False
elif line.startswith('black_men'):
self.black_men = self._parse_items(line)
self._add_men_to_board(self.black_men, BLACK | MAN)
self._bm_check = True
elif line.startswith('white_men'):
self.white_men = self._parse_items(line)
self._add_men_to_board(self.white_men, WHITE | MAN)
self._wm_check = True
elif line.startswith('black_kings'):
self.black_kings = self._parse_items(line)
self._add_men_to_board(self.black_kings, BLACK | KING)
self._bk_check = True
elif line.startswith('white_kings'):
self.white_kings = self._parse_items(line)
self._add_men_to_board(self.white_kings, WHITE | KING)
self._wk_check = True
idx += 1
if (not self._move_check and not self._bm_check and not self._wm_check
and not self._bk_check and not self._wk_check):
raise IOError, 'Error in <setup> section: not all required items found'
return idx
def _is_move(self, delta):
return delta in KING_IDX
def _is_jump(self, delta):
return delta not in KING_IDX
def _try_move(self, idx, start, dest, state_copy, annotation):
legal_moves = self._model.legal_moves(state_copy)
# match move from file with available moves on checkerboard
found = False
startsq, destsq = squaremap[start], squaremap[dest]
for move in legal_moves:
if (startsq == move.affected_squares[FIRST][0] and
destsq == move.affected_squares[LAST][0]):
self._model.make_move(move, state_copy, False, False)
move.annotation = annotation
self.moves.append(move)
found = True
break
if not found:
raise IOError, 'Illegal move found in file, line %d' % (idx+1)
def _try_jump(self, idx, start, dest, state_copy, annotation):
if not self._model.captures_available(state_copy):
return False
legal_moves = self._model.legal_moves(state_copy)
# match jump from file with available jumps on checkerboard
startsq, destsq = squaremap[start], squaremap[dest]
small, large = min(startsq, destsq), max(startsq, destsq)
found = False
for move in legal_moves:
# a valid jump may either have a single jump in it, or
# multiple jumps. In the multiple jump case, startsq is the
# source of the first jump, and destsq is the endpoint of the
# last jump.
if (startsq == move.affected_squares[FIRST][0] and
destsq == move.affected_squares[LAST][0]):
self._model.make_move(move, state_copy, False, False)
move.annotation = annotation
self.moves.append(move)
found = True
break
return found
def _parse_moves(self, lines, idx, linelen):
""" Each move in the file lists the beginning and ending square, along
with an optional annotation string (in Creole format) that describes it.
Since the move listing in the file contains less information than
we need inside our Checkerboard model, I make sure that each move works
on a copy of the model before I commit to using it inside the code. """
state_copy = copy.deepcopy(self._model.curr_state)
idx += 1
while idx < linelen:
line = lines[idx].strip()
if line == "":
idx += 1
continue # ignore blank lines
try:
movestr, annotation = line.split(';', 1)
except ValueError:
raise IOError, 'Unrecognized section in file, line %d' % (idx+1)
# move is always part of the annotation; I just don't want to
# have to repeat it explicitly in the file.
annotation = movestr + annotation
# analyze affected squares to perform a move or jump.
try:
start, dest = [int(x) for x in movestr.split('-')]
except ValueError:
raise IOError, 'Bad move format in file, line %d' % idx
delta = squaremap[start] - squaremap[dest]
if self._is_move(delta):
self._try_move(idx, start, dest, state_copy, annotation)
else:
jumped = self._try_jump(idx, start, dest, state_copy,
annotation)
if not jumped:
raise IOError, 'Bad move format in file, line %d' % idx
idx += 1
self.moves.reverse()
return idx
| 00eadeyemi-clone | gamepersist.py | Python | mit | 9,758 |
from Tkinter import Widget
from controller import Controller
from globalconst import *
class PlayerController(Controller):
def __init__(self, **props):
self._model = props['model']
self._view = props['view']
self._before_turn_event = None
self._end_turn_event = props['end_turn_event']
self._highlights = []
self._move_in_progress = False
def _register_event_handlers(self):
Widget.bind(self._view.canvas, '<Button-1>', self.mouse_click)
def _unregister_event_handlers(self):
Widget.unbind(self._view.canvas, '<Button-1>')
def stop_process(self):
pass
def set_search_time(self, time):
pass
def get_player_type(self):
return HUMAN
def set_before_turn_event(self, evt):
self._before_turn_event = evt
def add_highlights(self):
for h in self._highlights:
self._view.highlight_square(h, OUTLINE_COLOR)
def remove_highlights(self):
for h in self._highlights:
self._view.highlight_square(h, DARK_SQUARES)
def start_turn(self):
self._register_event_handlers()
self._model.curr_state.attach(self._view)
def end_turn(self):
self._unregister_event_handlers()
self._model.curr_state.detach(self._view)
def mouse_click(self, event):
xi, yi = self._view.calc_board_loc(event.x, event.y)
pos = self._view.calc_board_pos(xi, yi)
sq = self._model.curr_state.squares[pos]
if not self._move_in_progress:
player = self._model.curr_state.to_move
self.moves = self._model.legal_moves()
if (sq & player) and self.moves:
self._before_turn_event()
# highlight the start square the user clicked on
self._view.highlight_square(pos, OUTLINE_COLOR)
self._highlights = [pos]
# reduce moves to number matching the positions entered
self.moves = self._filter_moves(pos, self.moves, 0)
self.idx = 2 if self._model.captures_available() else 1
# if only one move available, take it.
if len(self.moves) == 1:
self._make_move()
self._view.canvas.after(100, self._end_turn_event)
return
self._move_in_progress = True
else:
if sq & FREE:
self.moves = self._filter_moves(pos, self.moves, self.idx)
if len(self.moves) == 0: # illegal move
# remove previous square highlights
for h in self._highlights:
self._view.highlight_square(h, DARK_SQUARES)
self._move_in_progress = False
return
else:
self._view.highlight_square(pos, OUTLINE_COLOR)
self._highlights.append(pos)
if len(self.moves) == 1:
self._make_move()
self._view.canvas.after(100, self._end_turn_event)
return
self.idx += 2 if self._model.captures_available() else 1
def _filter_moves(self, pos, moves, idx):
del_list = []
for i, m in enumerate(moves):
if pos != m.affected_squares[idx][0]:
del_list.append(i)
for i in reversed(del_list):
del moves[i]
return moves
def _make_move(self):
move = self.moves[0].affected_squares
step = 2 if len(move) > 2 else 1
# highlight remaining board squares used in move
for m in move[step::step]:
idx = m[0]
self._view.highlight_square(idx, OUTLINE_COLOR)
self._highlights.append(idx)
self._model.make_move(self.moves[0], None, True, True,
self._view.get_annotation())
# a new move obliterates any more redo's along a branch of the game tree
self._model.curr_state.delete_redo_list()
self._move_in_progress = False
| 00eadeyemi-clone | playercontroller.py | Python | mit | 4,232 |
from abc import ABCMeta, abstractmethod
class GoalEvaluator(object):
__metaclass__ = ABCMeta
def __init__(self, bias):
self.bias = bias
@abstractmethod
def calculateDesirability(self, board):
pass
@abstractmethod
def setGoal(self, board):
pass
| 00eadeyemi-clone | goalevaluator.py | Python | mit | 321 |
from Tkinter import *
from time import time, localtime, strftime
class ToolTip( Toplevel ):
"""
Provides a ToolTip widget for Tkinter.
To apply a ToolTip to any Tkinter widget, simply pass the widget to the
ToolTip constructor
"""
def __init__( self, wdgt, msg=None, msgFunc=None, delay=1, follow=True ):
"""
Initialize the ToolTip
Arguments:
wdgt: The widget this ToolTip is assigned to
msg: A static string message assigned to the ToolTip
msgFunc: A function that retrieves a string to use as the ToolTip text
delay: The delay in seconds before the ToolTip appears(may be float)
follow: If True, the ToolTip follows motion, otherwise hides
"""
self.wdgt = wdgt
self.parent = self.wdgt.master # The parent of the ToolTip is the parent of the ToolTips widget
Toplevel.__init__( self, self.parent, bg='black', padx=1, pady=1 ) # Initalise the Toplevel
self.withdraw() # Hide initially
self.overrideredirect( True ) # The ToolTip Toplevel should have no frame or title bar
self.msgVar = StringVar() # The msgVar will contain the text displayed by the ToolTip
if msg == None:
self.msgVar.set( 'No message provided' )
else:
self.msgVar.set( msg )
self.msgFunc = msgFunc
self.delay = delay
self.follow = follow
self.visible = 0
self.lastMotion = 0
Message( self, textvariable=self.msgVar, bg='#FFFFDD',
aspect=1000 ).grid() # The test of the ToolTip is displayed in a Message widget
self.wdgt.bind( '<Enter>', self.spawn, '+' ) # Add bindings to the widget. This will NOT override bindings that the widget already has
self.wdgt.bind( '<Leave>', self.hide, '+' )
self.wdgt.bind( '<Motion>', self.move, '+' )
def spawn( self, event=None ):
"""
Spawn the ToolTip. This simply makes the ToolTip eligible for display.
Usually this is caused by entering the widget
Arguments:
event: The event that called this funciton
"""
self.visible = 1
self.after( int( self.delay * 1000 ), self.show ) # The after function takes a time argument in miliseconds
def show( self ):
"""
Displays the ToolTip if the time delay has been long enough
"""
if self.visible == 1 and time() - self.lastMotion > self.delay:
self.visible = 2
if self.visible == 2:
self.deiconify()
def move( self, event ):
"""
Processes motion within the widget.
Arguments:
event: The event that called this function
"""
self.lastMotion = time()
if self.follow == False: # If the follow flag is not set, motion within the widget will make the ToolTip dissapear
self.withdraw()
self.visible = 1
self.geometry( '+%i+%i' % ( event.x_root+10, event.y_root+10 ) ) # Offset the ToolTip 10x10 pixes southwest of the pointer
try:
self.msgVar.set( self.msgFunc() ) # Try to call the message function. Will not change the message if the message function is None or the message function fails
except:
pass
self.after( int( self.delay * 1000 ), self.show )
def hide( self, event=None ):
"""
Hides the ToolTip. Usually this is caused by leaving the widget
Arguments:
event: The event that called this function
"""
self.visible = 0
self.withdraw()
def xrange2d( n,m ):
"""
Returns a generator of values in a 2d range
Arguments:
n: The number of rows in the 2d range
m: The number of columns in the 2d range
Returns:
A generator of values in a 2d range
"""
return ( (i,j) for i in xrange(n) for j in xrange(m) )
def range2d( n,m ):
"""
Returns a list of values in a 2d range
Arguments:
n: The number of rows in the 2d range
m: The number of columns in the 2d range
Returns:
A list of values in a 2d range
"""
return [(i,j) for i in range(n) for j in range(m) ]
def print_time():
"""
Prints the current time in the following format:
HH:MM:SS.00
"""
t = time()
timeString = 'time='
timeString += strftime( '%H:%M:', localtime(t) )
timeString += '%.2f' % ( t%60, )
return timeString
def main():
root = Tk()
btnList = []
for (i,j) in range2d( 6, 4 ):
text = 'delay=%i\n' % i
delay = i
if j >= 2:
follow=True
text += '+follow\n'
else:
follow = False
text += '-follow\n'
if j % 2 == 0:
msg = None
msgFunc = print_time
text += 'Message Function'
else:
msg = 'Button at %s' % str( (i,j) )
msgFunc = None
text += 'Static Message'
btnList.append( Button( root, text=text ) )
ToolTip( btnList[-1], msg=msg, msgFunc=msgFunc, follow=follow, delay=delay)
btnList[-1].grid( row=i, column=j, sticky=N+S+E+W )
root.mainloop()
if __name__ == '__main__':
main()
| 00eadeyemi-clone | tooltip.py | Python | mit | 5,786 |
class Command(object):
def __init__(self, **props):
self.add = props.get('add') or []
self.remove = props.get('remove') or []
| 00eadeyemi-clone | command.py | Python | mit | 150 |
from globalconst import BLACK, WHITE, KING
import checkers
class Operator(object):
pass
class OneKingAttackOneKing(Operator):
def precondition(self, board):
plr_color = board.to_move
opp_color = board.enemy
return (board.count(plr_color) == 1 and board.count(opp_color) == 1 and
any((x & KING for x in board.get_pieces(opp_color))) and
any((x & KING for x in board.get_pieces(plr_color))) and
board.has_opposition(plr_color))
def postcondition(self, board):
board.make_move()
class PinEnemyKingInCornerWithPlayerKing(Operator):
def __init__(self):
self.pidx = 0
self.eidx = 0
self.goal = 8
def precondition(self, state):
self.pidx, plr = self.plr_lst[0] # only 1 piece per side
self.eidx, enemy = self.enemy_lst[0]
delta = abs(self.pidx - self.eidx)
return ((self.player_total == 1) and (self.enemy_total == 1) and
(plr & KING > 0) and (enemy & KING > 0) and
not (8 <= delta <= 10) and state.have_opposition(plr))
def postcondition(self, state):
new_state = None
old_delta = abs(self.eidx - self.pidx)
goal_delta = abs(self.goal - old_delta)
for move in state.moves:
for m in move:
newidx, _, _ = m[1]
new_delta = abs(self.eidx - newidx)
if abs(goal - new_delta) < goal_delta:
new_state = state.make_move(move)
break
return new_state
# (white)
# 37 38 39 40
# 32 33 34 35
# 28 29 30 31
# 23 24 25 26
# 19 20 21 22
# 14 15 16 17
# 10 11 12 13
# 5 6 7 8
# (black)
class SingleKingFleeToDoubleCorner(Operator):
def __init__(self):
self.pidx = 0
self.eidx = 0
self.dest = [8, 13, 27, 32]
self.goal_delta = 0
def precondition(self, state):
# fail fast
if self.player_total == 1 and self.enemy_total == 1:
return False
self.pidx, _ = self.plr_lst[0]
self.eidx, _ = self.enemy_lst[0]
for sq in self.dest:
if abs(self.pidx - sq) < abs(self.eidx - sq):
self.goal = sq
return True
return False
def postcondition(self, state):
self.goal_delta = abs(self.goal - self.pidx)
for move in state.moves:
for m in move:
newidx, _, _ = m[1]
new_delta = abs(self.goal - newidx)
if new_delta < self.goal_delta:
new_state = state.make_move(move)
break
return new_state
class FormShortDyke(Operator):
def precondition(self):
pass
| 00eadeyemi-clone | predicates.py | Python | mit | 2,954 |
class Controller(object):
def stop_process(self):
pass
| 00eadeyemi-clone | controller.py | Python | mit | 78 |
from abc import ABCMeta, abstractmethod
class Goal:
__metaclass__ = ABCMeta
INACTIVE = 0
ACTIVE = 1
COMPLETED = 2
FAILED = 3
def __init__(self, owner):
self.owner = owner
self.status = self.INACTIVE
@abstractmethod
def activate(self):
pass
@abstractmethod
def process(self):
pass
@abstractmethod
def terminate(self):
pass
def handleMessage(self, msg):
return False
def addSubgoal(self, goal):
raise NotImplementedError('Cannot add goals to atomic goals')
def reactivateIfFailed(self):
if self.status == self.FAILED:
self.status = self.INACTIVE
def activateIfInactive(self):
if self.status == self.INACTIVE:
self.status = self.ACTIVE
| 00eadeyemi-clone | goal.py | Python | mit | 842 |
from Tkinter import *
from ttk import Checkbutton
from tkSimpleDialog import Dialog
from globalconst import *
class SetupBoard(Dialog):
def __init__(self, parent, title, gameManager):
self._master = parent
self._manager = gameManager
self._load_entry_box_vars()
self.result = False
Dialog.__init__(self, parent, title)
def body(self, master):
self._npLFrame = LabelFrame(master, text='No. of players:')
self._npFrameEx1 = Frame(self._npLFrame, width=30)
self._npFrameEx1.pack(side=LEFT, pady=5, expand=1)
self._npButton1 = Radiobutton(self._npLFrame, text='Zero (autoplay)',
value=0, variable=self._num_players,
command=self._disable_player_color)
self._npButton1.pack(side=LEFT, pady=5, expand=1)
self._npButton2 = Radiobutton(self._npLFrame, text='One',
value=1, variable=self._num_players,
command=self._enable_player_color)
self._npButton2.pack(side=LEFT, pady=5, expand=1)
self._npButton3 = Radiobutton(self._npLFrame, text='Two',
value=2, variable=self._num_players,
command=self._disable_player_color)
self._npButton3.pack(side=LEFT, pady=5, expand=1)
self._npFrameEx2 = Frame(self._npLFrame, width=30)
self._npFrameEx2.pack(side=LEFT, pady=5, expand=1)
self._npLFrame.pack(fill=X)
self._playerFrame = LabelFrame(master, text='Player color:')
self._playerFrameEx1 = Frame(self._playerFrame, width=50)
self._playerFrameEx1.pack(side=LEFT, pady=5, expand=1)
self._rbColor1 = Radiobutton(self._playerFrame, text='Black',
value=BLACK, variable=self._player_color)
self._rbColor1.pack(side=LEFT, padx=0, pady=5, expand=1)
self._rbColor2 = Radiobutton(self._playerFrame, text='White',
value=WHITE, variable=self._player_color)
self._rbColor2.pack(side=LEFT, padx=0, pady=5, expand=1)
self._playerFrameEx2 = Frame(self._playerFrame, width=50)
self._playerFrameEx2.pack(side=LEFT, pady=5, expand=1)
self._playerFrame.pack(fill=X)
self._rbFrame = LabelFrame(master, text='Next to move:')
self._rbFrameEx1 = Frame(self._rbFrame, width=50)
self._rbFrameEx1.pack(side=LEFT, pady=5, expand=1)
self._rbTurn1 = Radiobutton(self._rbFrame, text='Black',
value=BLACK, variable=self._player_turn)
self._rbTurn1.pack(side=LEFT, padx=0, pady=5, expand=1)
self._rbTurn2 = Radiobutton(self._rbFrame, text='White',
value=WHITE, variable=self._player_turn)
self._rbTurn2.pack(side=LEFT, padx=0, pady=5, expand=1)
self._rbFrameEx2 = Frame(self._rbFrame, width=50)
self._rbFrameEx2.pack(side=LEFT, pady=5, expand=1)
self._rbFrame.pack(fill=X)
self._bcFrame = LabelFrame(master, text='Board configuration')
self._wmFrame = Frame(self._bcFrame, borderwidth=0)
self._wmLabel = Label(self._wmFrame, text='White men:')
self._wmLabel.pack(side=LEFT, padx=7, pady=10)
self._wmEntry = Entry(self._wmFrame, width=40,
textvariable=self._white_men)
self._wmEntry.pack(side=LEFT, padx=10)
self._wmFrame.pack()
self._wkFrame = Frame(self._bcFrame, borderwidth=0)
self._wkLabel = Label(self._wkFrame, text='White kings:')
self._wkLabel.pack(side=LEFT, padx=5, pady=10)
self._wkEntry = Entry(self._wkFrame, width=40,
textvariable=self._white_kings)
self._wkEntry.pack(side=LEFT, padx=10)
self._wkFrame.pack()
self._bmFrame = Frame(self._bcFrame, borderwidth=0)
self._bmLabel = Label(self._bmFrame, text='Black men:')
self._bmLabel.pack(side=LEFT, padx=7, pady=10)
self._bmEntry = Entry(self._bmFrame, width=40,
textvariable=self._black_men)
self._bmEntry.pack(side=LEFT, padx=10)
self._bmFrame.pack()
self._bkFrame = Frame(self._bcFrame, borderwidth=0)
self._bkLabel = Label(self._bkFrame, text='Black kings:')
self._bkLabel.pack(side=LEFT, padx=5, pady=10)
self._bkEntry = Entry(self._bkFrame, width=40,
textvariable=self._black_kings)
self._bkEntry.pack(side=LEFT, padx=10)
self._bkFrame.pack()
self._bcFrame.pack(fill=X)
self._bsState = IntVar()
self._bsFrame = Frame(master, borderwidth=0)
self._bsCheck = Checkbutton(self._bsFrame, variable=self._bsState,
text='Start new game with the current setup?')
self._bsCheck.pack()
self._bsFrame.pack(fill=X)
if self._num_players.get() == 1:
self._enable_player_color()
else:
self._disable_player_color()
def validate(self):
self.wm_list = self._parse_int_list(self._white_men.get())
self.wk_list = self._parse_int_list(self._white_kings.get())
self.bm_list = self._parse_int_list(self._black_men.get())
self.bk_list = self._parse_int_list(self._black_kings.get())
if (self.wm_list == None or self.wk_list == None
or self.bm_list == None or self.bk_list == None):
return 0 # Error occurred during parsing
if not self._all_unique(self.wm_list, self.wk_list,
self.bm_list, self.bk_list):
return 0 # A repeated index occurred
return 1
def apply(self):
mgr = self._manager
model = mgr.model
view = mgr.view
state = model.curr_state
mgr.player_color = self._player_color.get()
mgr.num_players = self._num_players.get()
mgr.model.curr_state.to_move = self._player_turn.get()
# only reset the BoardView if men or kings have new positions
if (sorted(self.wm_list) != sorted(self._orig_white_men) or
sorted(self.wk_list) != sorted(self._orig_white_kings) or
sorted(self.bm_list) != sorted(self._orig_black_men) or
sorted(self.bk_list) != sorted(self._orig_black_kings) or
self._bsState.get() == 1):
state.clear()
sq = state.squares
for item in self.wm_list:
idx = squaremap[item]
sq[idx] = WHITE | MAN
for item in self.wk_list:
idx = squaremap[item]
sq[idx] = WHITE | KING
for item in self.bm_list:
idx = squaremap[item]
sq[idx] = BLACK | MAN
for item in self.bk_list:
idx = squaremap[item]
sq[idx] = BLACK | KING
state.to_move = self._player_turn.get()
state.reset_undo()
view.reset_view(mgr.model)
if self._bsState.get() == 1:
mgr.filename = None
mgr.parent.set_title_bar_filename()
state.ok_to_move = True
self.result = True
self.destroy()
def cancel(self, event=None):
self.destroy()
def _load_entry_box_vars(self):
self._white_men = StringVar()
self._white_kings = StringVar()
self._black_men = StringVar()
self._black_kings = StringVar()
self._player_color = IntVar()
self._player_turn = IntVar()
self._num_players = IntVar()
self._player_color.set(self._manager.player_color)
self._num_players.set(self._manager.num_players)
model = self._manager.model
self._player_turn.set(model.curr_state.to_move)
view = self._manager.view
self._white_men.set(', '.join(view.get_positions(WHITE | MAN)))
self._white_kings.set(', '.join(view.get_positions(WHITE | KING)))
self._black_men.set(', '.join(view.get_positions(BLACK | MAN)))
self._black_kings.set(', '.join(view.get_positions(BLACK | KING)))
self._orig_white_men = map(int, view.get_positions(WHITE | MAN))
self._orig_white_kings = map(int, view.get_positions(WHITE | KING))
self._orig_black_men = map(int, view.get_positions(BLACK | MAN))
self._orig_black_kings = map(int, view.get_positions(BLACK | KING))
def _disable_player_color(self):
self._rbColor1.configure(state=DISABLED)
self._rbColor2.configure(state=DISABLED)
def _enable_player_color(self):
self._rbColor1.configure(state=NORMAL)
self._rbColor2.configure(state=NORMAL)
def _all_unique(self, *lists):
s = set()
total_list = []
for i in lists:
total_list.extend(i)
s = s.union(i)
return sorted(total_list) == sorted(s)
def _parse_int_list(self, parsestr):
try:
lst = parsestr.split(',')
except AttributeError:
return None
if lst == ['']:
return []
try:
lst = [int(i) for i in lst]
except ValueError:
return None
if not all(((x>=1 and x<=MAX_VALID_SQ) for x in lst)):
return None
return lst
| 00eadeyemi-clone | setupboard.py | Python | mit | 9,624 |
from Tkinter import *
class HyperlinkManager(object):
def __init__(self, textWidget, linkFunc):
self.txt = textWidget
self.linkfunc = linkFunc
self.txt.tag_config('hyper', foreground='blue', underline=1)
self.txt.tag_bind('hyper', '<Enter>', self._enter)
self.txt.tag_bind('hyper', '<Leave>', self._leave)
self.txt.tag_bind('hyper', '<Button-1>', self._click)
self.reset()
def reset(self):
self.filenames = {}
def add(self, filename):
# Add a link with associated filename. The link function returns tags
# to use in the associated text widget.
tag = 'hyper-%d' % len(self.filenames)
self.filenames[tag] = filename
return 'hyper', tag
def _enter(self, event):
self.txt.config(cursor='hand2')
def _leave(self, event):
self.txt.config(cursor='')
def _click(self, event):
for tag in self.txt.tag_names(CURRENT):
if tag.startswith('hyper-'):
self.linkfunc(self.filenames[tag])
return
| 00eadeyemi-clone | hyperlinkmgr.py | Python | mit | 1,115 |
class DocNode(object):
"""
A node in the document.
"""
def __init__(self, kind='', parent=None, content=None):
self.children = []
self.parent = parent
self.kind = kind
self.content = content
if self.parent is not None:
self.parent.children.append(self)
| 00eadeyemi-clone | document.py | Python | mit | 322 |
/**
* SyntaxHighlighterx
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (July 02 2010)
*
* @copyright
* Copyright (C) 2004-2010 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
var funcs = 'abs avg case cast coalesce convert count current_timestamp ' +
'current_user day isnull left lower month nullif replace right ' +
'session_user space substring sum system_user upper user year';
var keywords = 'absolute action add after alter as asc at authorization begin bigint ' +
'binary bit by cascade char character check checkpoint close collate ' +
'column commit committed connect connection constraint contains continue ' +
'create cube current current_date current_time cursor database date ' +
'deallocate dec decimal declare default delete desc distinct double drop ' +
'dynamic else end end-exec escape except exec execute false fetch first ' +
'float for force foreign forward free from full function global goto grant ' +
'group grouping having hour ignore index inner insensitive insert instead ' +
'int integer intersect into is isolation key last level load local max min ' +
'minute modify move name national nchar next no numeric of off on only ' +
'open option order out output partial password precision prepare primary ' +
'prior privileges procedure public read real references relative repeatable ' +
'restrict return returns revoke rollback rollup rows rule schema scroll ' +
'second section select sequence serializable set size smallint static ' +
'statistics table temp temporary then time timestamp to top transaction ' +
'translation trigger true truncate uncommitted union unique update values ' +
'varchar varying view when where with work';
var operators = 'all and any between cross in join like not null or outer some';
this.regexList = [
{ regex: /--(.*)$/gm, css: 'comments' }, // one line and multiline comments
{ regex: SyntaxHighlighter.regexLib.multiLineDoubleQuotedString, css: 'string' }, // double quoted strings
{ regex: SyntaxHighlighter.regexLib.multiLineSingleQuotedString, css: 'string' }, // single quoted strings
{ regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'color2' }, // functions
{ regex: new RegExp(this.getKeywords(operators), 'gmi'), css: 'color1' }, // operators and such
{ regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' } // keyword
];
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['sql'];
SyntaxHighlighter.brushes.Sql = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
| 0x77 | wiki/script/6.js | JavaScript | asf20 | 3,121 |
/**
* SyntaxHighlighterx
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (July 02 2010)
*
* @copyright
* Copyright (C) 2004-2010 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
var keywords = 'AddHandler AddressOf AndAlso Alias And Ansi As Assembly Auto ' +
'Boolean ByRef Byte ByVal Call Case Catch CBool CByte CChar CDate ' +
'CDec CDbl Char CInt Class CLng CObj Const CShort CSng CStr CType ' +
'Date Decimal Declare Default Delegate Dim DirectCast Do Double Each ' +
'Else ElseIf End Enum Erase Error Event Exit False Finally For Friend ' +
'Function Get GetType GoSub GoTo Handles If Implements Imports In ' +
'Inherits Integer Interface Is Let Lib Like Long Loop Me Mod Module ' +
'MustInherit MustOverride MyBase MyClass Namespace New Next Not Nothing ' +
'NotInheritable NotOverridable Object On Option Optional Or OrElse ' +
'Overloads Overridable Overrides ParamArray Preserve Private Property ' +
'Protected Public RaiseEvent ReadOnly ReDim REM RemoveHandler Resume ' +
'Return Select Set Shadows Shared Short Single Static Step Stop String ' +
'Structure Sub SyncLock Then Throw To True Try TypeOf Unicode Until ' +
'Variant When While With WithEvents WriteOnly Xor';
this.regexList = [
{ regex: /'.*$/gm, css: 'comments' }, // one line comments
{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
{ regex: /^\s*#.*$/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion
{ regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // vb keyword
];
this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['vb', 'vbnet'];
SyntaxHighlighter.brushes.Vb = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
| 0x77 | wiki/script/7.js | JavaScript | asf20 | 2,338 |
/**
* SyntaxHighlighterx
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (July 02 2010)
*
* @copyright
* Copyright (C) 2004-2010 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
var funcs = 'abs acos acosh addcslashes addslashes ' +
'array_change_key_case array_chunk array_combine array_count_values array_diff '+
'array_diff_assoc array_diff_key array_diff_uassoc array_diff_ukey array_fill '+
'array_filter array_flip array_intersect array_intersect_assoc array_intersect_key '+
'array_intersect_uassoc array_intersect_ukey array_key_exists array_keys array_map '+
'array_merge array_merge_recursive array_multisort array_pad array_pop array_product '+
'array_push array_rand array_reduce array_reverse array_search array_shift '+
'array_slice array_splice array_sum array_udiff array_udiff_assoc '+
'array_udiff_uassoc array_uintersect array_uintersect_assoc '+
'array_uintersect_uassoc array_unique array_unshift array_values array_walk '+
'array_walk_recursive atan atan2 atanh base64_decode base64_encode base_convert '+
'basename bcadd bccomp bcdiv bcmod bcmul bindec bindtextdomain bzclose bzcompress '+
'bzdecompress bzerrno bzerror bzerrstr bzflush bzopen bzread bzwrite ceil chdir '+
'checkdate checkdnsrr chgrp chmod chop chown chr chroot chunk_split class_exists '+
'closedir closelog copy cos cosh count count_chars date decbin dechex decoct '+
'deg2rad delete ebcdic2ascii echo empty end ereg ereg_replace eregi eregi_replace error_log '+
'error_reporting escapeshellarg escapeshellcmd eval exec exit exp explode extension_loaded '+
'feof fflush fgetc fgetcsv fgets fgetss file_exists file_get_contents file_put_contents '+
'fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype '+
'floatval flock floor flush fmod fnmatch fopen fpassthru fprintf fputcsv fputs fread fscanf '+
'fseek fsockopen fstat ftell ftok getallheaders getcwd getdate getenv gethostbyaddr gethostbyname '+
'gethostbynamel getimagesize getlastmod getmxrr getmygid getmyinode getmypid getmyuid getopt '+
'getprotobyname getprotobynumber getrandmax getrusage getservbyname getservbyport gettext '+
'gettimeofday gettype glob gmdate gmmktime ini_alter ini_get ini_get_all ini_restore ini_set '+
'interface_exists intval ip2long is_a is_array is_bool is_callable is_dir is_double '+
'is_executable is_file is_finite is_float is_infinite is_int is_integer is_link is_long '+
'is_nan is_null is_numeric is_object is_readable is_real is_resource is_scalar is_soap_fault '+
'is_string is_subclass_of is_uploaded_file is_writable is_writeable mkdir mktime nl2br '+
'parse_ini_file parse_str parse_url passthru pathinfo print readlink realpath rewind rewinddir rmdir '+
'round str_ireplace str_pad str_repeat str_replace str_rot13 str_shuffle str_split '+
'str_word_count strcasecmp strchr strcmp strcoll strcspn strftime strip_tags stripcslashes '+
'stripos stripslashes stristr strlen strnatcasecmp strnatcmp strncasecmp strncmp strpbrk '+
'strpos strptime strrchr strrev strripos strrpos strspn strstr strtok strtolower strtotime '+
'strtoupper strtr strval substr substr_compare';
var keywords = 'abstract and array as break case catch cfunction class clone const continue declare default die do ' +
'else elseif enddeclare endfor endforeach endif endswitch endwhile extends final for foreach ' +
'function include include_once global goto if implements interface instanceof namespace new ' +
'old_function or private protected public return require require_once static switch ' +
'throw try use var while xor ';
var constants = '__FILE__ __LINE__ __METHOD__ __FUNCTION__ __CLASS__';
this.regexList = [
{ regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
{ regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
{ regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
{ regex: /\$\w+/g, css: 'variable' }, // variables
{ regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, // common functions
{ regex: new RegExp(this.getKeywords(constants), 'gmi'), css: 'constants' }, // constants
{ regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // keyword
];
this.forHtmlScript(SyntaxHighlighter.regexLib.phpScriptTags);
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['php'];
SyntaxHighlighter.brushes.Php = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
| 0x77 | wiki/script/5.js | JavaScript | asf20 | 5,335 |
/**
* SyntaxHighlighterx
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (July 02 2010)
*
* @copyright
* Copyright (C) 2004-2010 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
var keywords = 'if fi then elif else for do done until while break continue case function return in eq ne ge le';
var commands = 'alias apropos awk basename bash bc bg builtin bzip2 cal cat cd cfdisk chgrp chmod chown chroot' +
'cksum clear cmp comm command cp cron crontab csplit cut date dc dd ddrescue declare df ' +
'diff diff3 dig dir dircolors dirname dirs du echo egrep eject enable env ethtool eval ' +
'exec exit expand export expr false fdformat fdisk fg fgrep file find fmt fold format ' +
'free fsck ftp gawk getopts grep groups gzip hash head history hostname id ifconfig ' +
'import install join kill less let ln local locate logname logout look lpc lpr lprint ' +
'lprintd lprintq lprm ls lsof make man mkdir mkfifo mkisofs mknod more mount mtools ' +
'mv netstat nice nl nohup nslookup open op passwd paste pathchk ping popd pr printcap ' +
'printenv printf ps pushd pwd quota quotacheck quotactl ram rcp read readonly renice ' +
'remsync rm rmdir rsync screen scp sdiff sed select seq set sftp shift shopt shutdown ' +
'sleep sort source split ssh strace su sudo sum symlink sync tail tar tee test time ' +
'times touch top traceroute trap tr true tsort tty type ulimit umask umount unalias ' +
'uname unexpand uniq units unset unshar useradd usermod users uuencode uudecode v vdir ' +
'vi watch wc whereis which who whoami Wget xargs yes'
;
this.regexList = [
{ regex: /^#!.*$/gm, css: 'preprocessor bold' },
{ regex: /\/[\w-\/]+/gm, css: 'plain' },
{ regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, // one line comments
{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
{ regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
{ regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // keywords
{ regex: new RegExp(this.getKeywords(commands), 'gm'), css: 'functions' } // commands
];
}
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['bash', 'shell'];
SyntaxHighlighter.brushes.Bash = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
| 0x77 | wiki/script/2.js | JavaScript | asf20 | 2,895 |
/**
* SyntaxHighlighterx
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (July 02 2010)
*
* @copyright
* Copyright (C) 2004-2010 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
function process(match, regexInfo)
{
var constructor = SyntaxHighlighter.Match,
code = match[0],
tag = new XRegExp('(<|<)[\\s\\/\\?]*(?<name>[:\\w-\\.]+)', 'xg').exec(code),
result = []
;
if (match.attributes != null)
{
var attributes,
regex = new XRegExp('(?<name> [\\w:\\-\\.]+)' +
'\\s*=\\s*' +
'(?<value> ".*?"|\'.*?\'|\\w+)',
'xg');
while ((attributes = regex.exec(code)) != null)
{
result.push(new constructor(attributes.name, match.index + attributes.index, 'color1'));
result.push(new constructor(attributes.value, match.index + attributes.index + attributes[0].indexOf(attributes.value), 'string'));
}
}
if (tag != null)
result.push(
new constructor(tag.name, match.index + tag[0].indexOf(tag.name), 'keyword')
);
return result;
}
this.regexList = [
{ regex: new XRegExp('(\\<|<)\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\](\\>|>)', 'gm'), css: 'color2' }, // <![ ... [ ... ]]>
{ regex: SyntaxHighlighter.regexLib.xmlComments, css: 'comments' }, // <!-- ... -->
{ regex: new XRegExp('(<|<)[\\s\\/\\?]*(\\w+)(?<attributes>.*?)[\\s\\/\\?]*(>|>)', 'sg'), func: process }
];
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['xml', 'xhtml', 'xslt', 'html'];
SyntaxHighlighter.brushes.Xml = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
| 0x77 | wiki/script/8.js | JavaScript | asf20 | 2,068 |
/**
* SyntaxHighlighterx
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (July 02 2010)
*
* @copyright
* Copyright (C) 2004-2010 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
var keywords = 'abstract assert boolean break byte case catch char class const ' +
'continue default do double else enum extends ' +
'false final finally float for goto if implements import ' +
'instanceof int interface long native new null ' +
'package private protected public return ' +
'short static strictfp super switch synchronized this throw throws true ' +
'transient try void volatile while';
this.regexList = [
{ regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
{ regex: /\/\*([^\*][\s\S]*)?\*\//gm, css: 'comments' }, // multiline comments
{ regex: /\/\*(?!\*\/)\*[\s\S]*?\*\//gm, css: 'preprocessor' }, // documentation comments
{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
{ regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
{ regex: /\b([\d]+(\.[\d]+)?|0x[a-f0-9]+)\b/gi, css: 'value' }, // numbers
{ regex: /(?!\@interface\b)\@[\$\w]+\b/g, css: 'color1' }, // annotation @anno
{ regex: /\@interface\b/g, css: 'color2' }, // @interface keyword
{ regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // java keyword
];
this.forHtmlScript({
left : /(<|<)%[@!=]?/g,
right : /%(>|>)/g
});
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['java'];
SyntaxHighlighter.brushes.Java = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
| 0x77 | wiki/script/3.js | JavaScript | asf20 | 2,159 |
/**
* SyntaxHighlighterx
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (July 02 2010)
*
* @copyright
* Copyright (C) 2004-2010 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
// Contributed by David Simmons-Duffin and Marty Kube
var funcs =
'abs accept alarm atan2 bind binmode chdir chmod chomp chop chown chr ' +
'chroot close closedir connect cos crypt defined delete each endgrent ' +
'endhostent endnetent endprotoent endpwent endservent eof exec exists ' +
'exp fcntl fileno flock fork format formline getc getgrent getgrgid ' +
'getgrnam gethostbyaddr gethostbyname gethostent getlogin getnetbyaddr ' +
'getnetbyname getnetent getpeername getpgrp getppid getpriority ' +
'getprotobyname getprotobynumber getprotoent getpwent getpwnam getpwuid ' +
'getservbyname getservbyport getservent getsockname getsockopt glob ' +
'gmtime grep hex index int ioctl join keys kill lc lcfirst length link ' +
'listen localtime lock log lstat map mkdir msgctl msgget msgrcv msgsnd ' +
'oct open opendir ord pack pipe pop pos print printf prototype push ' +
'quotemeta rand read readdir readline readlink readpipe recv rename ' +
'reset reverse rewinddir rindex rmdir scalar seek seekdir select semctl ' +
'semget semop send setgrent sethostent setnetent setpgrp setpriority ' +
'setprotoent setpwent setservent setsockopt shift shmctl shmget shmread ' +
'shmwrite shutdown sin sleep socket socketpair sort splice split sprintf ' +
'sqrt srand stat study substr symlink syscall sysopen sysread sysseek ' +
'system syswrite tell telldir time times tr truncate uc ucfirst umask ' +
'undef unlink unpack unshift utime values vec wait waitpid warn write';
var keywords =
'bless caller continue dbmclose dbmopen die do dump else elsif eval exit ' +
'for foreach goto if import last local my next no our package redo ref ' +
'require return sub tie tied unless untie until use wantarray while';
this.regexList = [
{ regex: new RegExp('#[^!].*$', 'gm'), css: 'comments' },
{ regex: new RegExp('^\\s*#!.*$', 'gm'), css: 'preprocessor' }, // shebang
{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' },
{ regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' },
{ regex: new RegExp('(\\$|@|%)\\w+', 'g'), css: 'variable' },
{ regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' },
{ regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }
];
this.forHtmlScript(SyntaxHighlighter.regexLib.phpScriptTags);
}
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['perl', 'Perl', 'pl'];
SyntaxHighlighter.brushes.Perl = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
| 0x77 | wiki/script/4.js | JavaScript | asf20 | 3,249 |
package foundation.data;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import com.mysport.ui.R;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.DatabaseTableConfig;
import com.j256.ormlite.table.DatabaseTableConfigLoader;
import com.j256.ormlite.table.TableUtils;
/**
*
* @author 福建师范大学软件学院 陈贝、刘大刚
*
*/
public class DataHelper extends OrmLiteSqliteOpenHelper {
private static final int DATABASE_VERSION = 1;
private Context context;
public DataHelper(Context context,String dataFileName) {
super(context, dataFileName, null, DATABASE_VERSION,
R.raw.ormlite_config);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
// create database
this.createTable(db, connectionSource);
}
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int arg2, int arg3) {
// update database
this.updateTable(db, connectionSource);
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
Log.d("DataHelper", "database is opened");
}
@Override
public void close() {
super.close();
Log.d("DataHelper", "database is closed");
}
private void createTable(SQLiteDatabase db,ConnectionSource connectionSource) {
try {
Log.d("DataHelper", "create database");
InputStream is = this.context.getResources().openRawResource(
R.raw.ormlite_config);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr, 4096);
List<DatabaseTableConfig<?>> tableConfigs = DatabaseTableConfigLoader
.loadDatabaseConfigFromReader(reader);
for (DatabaseTableConfig<?> databaseTableConfig : tableConfigs) {
TableUtils.createTableIfNotExists(connectionSource,
databaseTableConfig);
}
is.close();
isr.close();
reader.close();
} catch (Exception e) {
Log.e(DataHelper.class.getName(), "创建数据库失败" + e.getCause());
e.printStackTrace();
}
}
private void updateTable(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.d("DataHelper", "Update Database");
InputStream is = this.context.getResources().openRawResource(
R.raw.ormlite_config);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr, 4096);
List<DatabaseTableConfig<?>> tableConfigs = DatabaseTableConfigLoader
.loadDatabaseConfigFromReader(reader);
for (DatabaseTableConfig<?> databaseTableConfig : tableConfigs) {
TableUtils.dropTable(connectionSource, databaseTableConfig,
true);
}
is.close();
isr.close();
reader.close();
onCreate(db, connectionSource);
} catch (Exception e) {
Log.e(DataHelper.class.getName(), "更新数据库失败" + e.getMessage());
e.printStackTrace();
}
}
} | 10-myclimb | trunk/MyClimb/src/foundation/data/DataHelper.java | Java | asf20 | 3,234 |
package foundation.data;
import java.sql.SQLException;
import java.util.List;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.PreparedDelete;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
/**
*
* @author 福建师范大学软件学院 陈贝、刘大刚
*
*/
public interface IDataContext {
// 增加
public abstract <T, ID> void add(T item, Class<T> dataClass,
Class<ID> idClass) throws SQLException;
// 删除
public abstract <T, ID> void delete(T item, Class<T> dataClass,
Class<ID> idClass) throws SQLException;
//通用删除
public abstract <T,ID> void delete(Class<T> dataClass,
Class<ID> idClass,PreparedDelete<T> preparedDelete) throws SQLException;
// 更新
public abstract <T, ID> void update(T item, Class<T> dataClass,
Class<ID> idClass) throws SQLException;
// 根据ID查询
public abstract <T, ID, K extends ID> T queryById(Class<T> dataClass,
Class<K> idClass, ID id) throws SQLException;
// 查询全部
public abstract <T, ID> List<T> queryForAll(Class<T> dataClass,
Class<ID> idClass) throws SQLException;
// 根据条件查询
public abstract <T, ID> List<String[]> queryBySql(Class<T> dataClass,
Class<ID> idClass, String query) throws SQLException;
// 获取全部记录数
public abstract <T, ID> long countof(Class<T> dataClass, Class<ID> idClass)
throws SQLException;
// 获取符合条件的记录数
public abstract <T, ID> long countof(Class<T> dataClass, Class<ID> idClass,
PreparedQuery<T> query) throws SQLException;
// 按id删除记录
public abstract <T, ID, K extends ID> void deleteById(ID id, Class<T> dataClass,
Class<K> idClass) throws SQLException;
//删除所有记录
public abstract <T, ID> void deleteAll(Class<T> dataClass, Class<ID> idClass)
throws SQLException ;
/**
* 通用查询
*
* @param <T>
* @param <ID>
* @param dataClass
* @param idClass
* @param query
* @return
* @throws SQLException
*/
public abstract <T, ID> List<T> query(Class<T> dataClass,
Class<ID> idClass, PreparedQuery<T> query) throws SQLException;
/**
* 获取QueryBuilder
*
* @param <T>
* @param <ID>
* @param dataClass
* @param idClass
* @return
* @throws SQLException
*/
public abstract <T, ID> QueryBuilder<T, ID> getQueryBuilder(
Class<T> dataClass, Class<ID> idClass) throws SQLException;
/**
* 获取DeleteBuilder
* @param dataClass
* @param idClass
* @return
* @throws SQLException
*/
public abstract <T, ID> DeleteBuilder<T, ID> getDeleteBuilder(
Class<T> dataClass, Class<ID> idClass) throws SQLException;
/**
* 开始事务
*/
public abstract void beginTransaction();
// 提交事务
public abstract void commit();
// 回滚事务
public abstract void rollback();
} | 10-myclimb | trunk/MyClimb/src/foundation/data/IDataContext.java | Java | asf20 | 2,935 |
package foundation.data;
import java.sql.SQLException;
import java.util.List;
import android.database.sqlite.SQLiteDatabase;
import app.MyApplication;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.PreparedDelete;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.support.ConnectionSource;
/**
*
* @author 福建师范大学软件学院 陈贝、刘大刚
*
*/
public class DataContext implements IDataContext {
private ConnectionSource connectionSource;//数据库连接
private SQLiteDatabase db; // 事务管理
public DataContext() {
connectionSource = MyApplication.DATAHELPER.getConnectionSource();
db = MyApplication.DATAHELPER.getWritableDatabase();
}
// 增加
public <T, ID> void add(T item, Class<T> dataClass, Class<ID> idClass)
throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
dao.create(item);
}
// 删除
public <T, ID> void delete(T item, Class<T> dataClass, Class<ID> idClass)
throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
dao.delete(item);
}
//删除所有记录
public <T, ID> void deleteAll(Class<T> dataClass, Class<ID> idClass)
throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
List<T> list=dao.queryForAll();
dao.delete(list);
}
// 按ID删除
public <T, ID, K extends ID> void deleteById(ID id, Class<T> dataClass,
Class<K> idClass) throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
dao.deleteById(id);
}
//删除BUilder
public <T, ID> DeleteBuilder<T, ID> getDeleteBuilder(Class<T> dataClass,
Class<ID> idClass) throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
return dao.deleteBuilder();
}
//通用删除
public <T, ID> void delete(Class<T> dataClass, Class<ID> idClass,
PreparedDelete<T> preparedDelete) throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
dao.delete(preparedDelete);
}
// 更新
public <T, ID> void update(T item, Class<T> dataClass, Class<ID> idClass)
throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
dao.update(item);
}
// 根据ID查询
public <T, ID, K extends ID> T queryById(Class<T> dataClass,
Class<K> idClass, ID id) throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
return dao.queryForId(id);
}
// 查询所有记录
public <T, ID> List<T> queryForAll(Class<T> dataClass, Class<ID> idClass)
throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
return dao.queryForAll();
}
// 根据SQL语句查询
public <T, ID> List<String[]> queryBySql(Class<T> dataClass,
Class<ID> idClass, String sql) throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
GenericRawResults<String[]> rawResults = dao.queryRaw(sql);
List<String[]> list = rawResults.getResults();
return list;
}
// 通用查询
public <T, ID> List<T> query(Class<T> dataClass, Class<ID> idClass,
PreparedQuery<T> query) throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
return dao.query(query);
}
// 获取所有记录数
public <T, ID> long countof(Class<T> dataClass, Class<ID> idClass)
throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
return dao.countOf();
}
// 获取指定条件的记录数
public <T, ID> long countof(Class<T> dataClass, Class<ID> idClass,
PreparedQuery<T> query) throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
return dao.countOf(query);
}
// 获取QueryBuilder
public <T, ID> QueryBuilder<T, ID> getQueryBuilder(Class<T> dataClass,
Class<ID> idClass) throws SQLException {
Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass);
return dao.queryBuilder();
}
// 开始事务
public void beginTransaction() {
db.beginTransaction();
}
// 提交事务
public void commit() {
db.setTransactionSuccessful();
}
// 回滚事务
public void rollback() {
db.endTransaction();
}
}
| 10-myclimb | trunk/MyClimb/src/foundation/data/DataContext.java | Java | asf20 | 4,611 |
package foundation.webservice;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class WeatherService {
//定义Web Service 的命名空间
static final String SERVICE_NS = "http://WebXml.com.cn/";
//定义Web Service提供服务的URL
static final String SERVICE_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";
//调用远程Web Service获取省份列表
public static List<String> getProviceList()
{
//调用的方法
final String methodName = "getRegionProvince";
//创建HttpTransportSE传输对象
final HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);
ht.debug = true;
//使用SOAP1.1协议创建Envelop 对象
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//实例化SoapObject对象
SoapObject soapObject = new SoapObject(SERVICE_NS,methodName);
envelope.bodyOut = soapObject;
//设置与。net提供的Web Service 保持较好的兼容性
envelope.dotNet = true;
FutureTask<List<String>> task = new FutureTask<List<String>>(
new Callable<List<String>>()
{
@Override
public List<String> call() throws Exception
{
//调用Web Service
ht.call(SERVICE_NS + methodName,envelope);
if(envelope.getResponse() != null)
{
//获取服务器响应返回的SOAP消息
SoapObject result = (SoapObject) envelope.bodyIn;
SoapObject detail = (SoapObject) result.getProperty(methodName + "Result");
//解析服务器响应的SOAP消息
return parseProvinceOrCity(detail);
}
return null;
}
});
new Thread(task).start();
try {
return task.get();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
//根据省份获取城市列表
public static List<String> getCityListByProvince(String province)
{
//调用方法
final String methodName = "getSupportCityString";
//创建HttpTransportSE传输对象
final HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);
ht.debug = true;
//实例化SoapObject对象
SoapObject soapObject = new SoapObject(SERVICE_NS,methodName);
//添加一个请求参数
soapObject.addProperty("theRegionCode", province);
//使用SOAP1.1协议创建Envelop对象
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = soapObject;
//设置与。net提供的Web Service 保持较好的兼容性
envelope.dotNet = true;//
FutureTask<List<String>> task = new FutureTask<List<String>>(
new Callable<List<String>>()
{
@Override
public List<String> call() throws Exception
{
//调用Web service
ht.call(SERVICE_NS + methodName, envelope);
if(envelope.getResponse() != null)
{
//获取服务器响应返回的SOAP消息
SoapObject result = (SoapObject) envelope.bodyIn;
SoapObject detail = (SoapObject) result.getProperty(methodName + "Result");
//解析服务器响应的SOAP消息
return parseProvinceOrCity(detail);
}
return null;
}
});
new Thread(task).start();
try {
return task.get();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
private static List<String> parseProvinceOrCity(SoapObject detail) {
// TODO 自动生成的方法存根
ArrayList<String> result = new ArrayList<String>();
for(int i=0; i<detail.getPropertyCount(); i++)
{
//解析出每个省份
result.add(detail.getProperty(i).toString().split(",")[0]);
}
return result;
}
public static SoapObject getWeatherByCity(String cityName)
{
final String methodName = "getWeather";
final HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);
ht.debug = true;
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
SoapObject soapObject = new SoapObject(SERVICE_NS,methodName);
soapObject.addProperty("theCityCode",cityName);
envelope.bodyOut = soapObject;
//设置与。net提供的Web Service保持较好的兼容性
envelope.dotNet = true;
FutureTask<SoapObject> task = new FutureTask<SoapObject>(
new Callable<SoapObject>(){
@Override
public SoapObject call() throws Exception
{
ht.call(SERVICE_NS + methodName, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
SoapObject detail = (SoapObject) result.getProperty(methodName + "Result");
return detail;
}
});
new Thread(task).start();
try {
return task.get();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
}
| 10-myclimb | trunk/MyClimb/src/foundation/webservice/WeatherService.java | Java | asf20 | 5,298 |
package foundation.webservice;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GeocodeService {
public static JSONObject geocodeAddr(double lat, double lng) {
String urlString = "http://maps.google.com/maps/api/geocode/json?latlng="
+ lat + "," + lng + "&sensor=true&language=zh-CN";
StringBuilder sTotalString = new StringBuilder();
try {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
InputStream urlStream = httpConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(urlStream));
String sCurrentLine = "";
while ((sCurrentLine = bufferedReader.readLine()) != null) {
sTotalString.append(sCurrentLine);
System.out.println();
}
//System.out.println(sTotalString);
bufferedReader.close();
httpConnection.disconnect(); // 关闭http连接
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(sTotalString.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
/**
*
* @param lat
* @param lng
* @param i 0街道,1区,2市,3国家
* @return
*/
public static String getAddressByLatLng(double lat, double lng,
int i) {
String address = null;
JSONObject jsonObject = geocodeAddr(lat, lng);
try {
JSONArray placemarks = jsonObject.getJSONArray("results");
JSONObject place = placemarks.getJSONObject(0);
JSONArray detail = place.getJSONArray("address_components");
JSONObject add = detail.getJSONObject(i);
address = add.getString("long_name");
} catch (Exception e) {
e.printStackTrace();
}
return address;
}
}
| 10-myclimb | trunk/MyClimb/src/foundation/webservice/GeocodeService.java | Java | asf20 | 2,150 |
package tool.data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.Bundle;
import domain.businessEntity.gps.ClimbData;
public class ClimbDataUtil {
/**
* @param args
*/
private static final String startAltitude = null;
private static final String stopAltitude = null;
private static final String startTime = null;
private static final String stopTime = null;
private static final String longitude =null;
private static final String latitude =null;
private static Date date1;
private static Date date2;
public static Bundle writeCardtoBundle(ClimbData climbdat){
Bundle bundle = new Bundle();
bundle.putInt("startAltitude", climbdat.getStartAltitude());
bundle.putInt("stopAltitude", climbdat.getStopAltitude());
bundle.putString("startTime", climbdat.getStartTime().toString());
bundle.putString("stopTime", climbdat.getStopTime().toString());
bundle.putDouble("longitude", climbdat.getLongitude());
bundle.putDouble("latitude", climbdat.getLatitude());
return bundle;
}
public static ClimbData readCardFromBundle(Bundle bundle){
ClimbData climbdat = new ClimbData();
climbdat.setStartAltitude(bundle.getInt("startAltitude"));
climbdat.setStopAltitude(bundle.getInt("stopAltitude"));
SimpleDateFormat sdf = new SimpleDateFormat("HH:MI:SS");
try {
date1 = sdf.parse(bundle.getString("startTime"));
date2 = sdf.parse(bundle.getString("stopTime"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
climbdat.setStartTime(date1);
climbdat.setStopTime(date2);
climbdat.setLongitude(bundle.getDouble("longitude"));
climbdat.setLatitude(bundle.getDouble("latitude"));
return climbdat;
}
} | 10-myclimb | trunk/MyClimb/src/tool/data/ClimbDataUtil.java | Java | asf20 | 1,893 |
package tool.data;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import android.os.Environment;
import com.j256.ormlite.android.apptools.OrmLiteConfigUtil;
/**
* 生成ORM映射文件
*
* @author 福建师范大学软件学院 陈贝、刘大刚
* @since 2012-6-8
*
*/
public class DatabaseConfigUtil extends OrmLiteConfigUtil {
public static String BUSINESSENTITYPKGNAME = "domain.businessEntity";
public static void main(String[] args) throws Exception {
Set<Class<?>> clses = getClasses(BUSINESSENTITYPKGNAME);
if (clses == null) {
return;
}
int len = clses.size();
Class<?>[] classes = new Class<?>[len];
int i = 0;
for (Class<?> cls : clses) {
classes[i] = cls;
i++;
}
writeConfigFile("ormlite_config.txt", classes);
}
public static Set<Class<?>> getClasses(String pack) {
// 第一个class类的集合
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
// 是否循环迭代
boolean recursive = true;
// 获取包的名字 并进行替换
String packageName = pack;
String packageDirName = packageName.replace('.', '/');
// 定义一个枚举的集合 并进行循环来处理这个目录下的things
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader()
.getResources(packageDirName);
while (dirs.hasMoreElements()) {
// 获取下一个元素
URL url = dirs.nextElement();
// 得到协议的名称
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
// 获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath,
recursive, classes);
}
}// 循环迭代下去
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* 以文件的形式来获取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
public static void findAndAddClassesInPackageByFile(String packageName,
String packagePath, final boolean recursive, Set<Class<?>> classes) {
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
return;
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(new FileFilter() {
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
public boolean accept(File file) {
return (recursive && file.isDirectory())
|| (file.getName().endsWith(".class"));
}
});
// 循环所有文件
for (File file : dirfiles) {
// 如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(
packageName + "." + file.getName(),
file.getAbsolutePath(), recursive, classes);
} else {
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0,
file.getName().length() - 6);
try {
// 添加到集合中去
classes.add(Thread.currentThread().getContextClassLoader()
.loadClass(packageName + '.' + className));
} catch (ClassNotFoundException e) {
// log.error("添加用户类错误,找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
}
| 10-myclimb | trunk/MyClimb/src/tool/data/DatabaseConfigUtil.java | Java | asf20 | 3,883 |
package tool.SunriseSunset;
/******************************************************************************
*
* SunriseSunset.java
*
*******************************************************************************
*
* Java Class: SunriseSunset
*
* This Java class is part of a collection of classes developed for the
* reading and processing of oceanographic and meterological data collected
* since 1970 by environmental buoys and stations. This dataset is
* maintained by the National Oceanographic Data Center and is publicly
* available. These Java classes were written for the US Environmental
* Protection Agency's National Exposure Research Laboratory under Contract
* No. GS-10F-0073K with Neptune and Company of Los Alamos, New Mexico.
*
* Purpose:
*
* This Java class performs calculations to determine the time of
* sunrise and sunset given lat, long, and date.
*
* Inputs:
*
* Latitude, longitude, date/time, and time zone.
*
* Outputs:
*
* Local time of sunrise and sunset as calculated by the
* program.
* If no sunrise or no sunset occurs, or if the sun is up all day
* or down all day, appropriate boolean values are set.
* A boolean is provided to identify if the time provided is during the day.
*
* The above values are accessed by the following methods:
*
* Date getSunrise() returns date/time of sunrise
* Date getSunset() returns date/time of sunset
* boolean isSunrise() returns true if there was a sunrise, else false
* boolean isSunset() returns true if there was a sunset, else false
* boolean isSunUp() returns true if sun is up all day, else false
* boolean isSunDown() returns true if sun is down all day, else false
* boolean isDaytime() returns true if sun is up at the time
* specified, else false
*
* Required classes from the Java library:
*
* java.util.Date
* java.text.SimpleDateFormat
* java.text.ParseException;
* java.math.BigDecimal;
*
* Package of which this class is a member:
*
* default
*
* Known limitations:
*
* It is assumed that the data provided are within valie ranges
* (i.e. latitude between -90 and +90, longitude between 0 and 360,
* a valid date, and time zone between -14 and +14.
*
* Compatibility:
*
* Java 1.1.8
*
* References:
*
* The mathematical algorithms used in this program are patterned
* after those debveloped by Roger Sinnott in his BASIC program,
* SUNUP.BAS, published in Sky & Telescope magazine:
* Sinnott, Roger W. "Sunrise and Sunset: A Challenge"
* Sky & Telescope, August, 1994 p.84-85
*
* The following is a cross-index of variables used in SUNUP.BAS.
* A single definition from multiple reuse of variable names in
* SUNUP.BAS was clarified with various definitions in this program.
*
* SUNUP.BAS this class
*
* A dfA
* A(2) dfAA1, dfAA2
* A0 dfA0
* A2 dfA2
* A5 dfA5
* AZ Not used
* C dfCosLat
* C0 dfC0
* D iDay
* D(2) dfDD1, dfDD2
* D0 dfD0
* D1 dfD1
* D2 dfD2
* D5 dfD5
* D7 Not used
* DA dfDA
* DD dfDD
* G bGregorian, dfGG
* H dfTimeZone
* H0 dfH0
* H1 dfH1
* H2 dfH2
* H3 dfHourRise, dfHourSet
* H7 Not used
* J dfJ
* J3 dfJ3
* K1 dfK1
* L dfLL
* L0 dfL0
* L2 dfL2
* L5 dfLon
* M iMonth
* M3 dfMinRise, dfMinSet
* N7 Not used
* P dfP
* S iSign, dfSinLat, dfSS
* T dfT
* T0 dfT0
* T3 not used
* TT dfTT
* U dfUU
* V dfVV
* V0 dfV0
* V1 dfV1
* V2 dfV2
* W dfWW
* Y iYear
* Z dfZenith
* Z0 dfTimeZone
*
*
* Author/Company:
*
* JDT: John Tauxe, Neptune and Company
* JMG: Jo Marie Green
*
* Change log:
*
* date ver by description of change
* _________ _____ ___ ______________________________________________
* 5 Jan 01 0.006 JDT Excised from ssapp.java v. 0.005.
* 11 Jan 01 0.007 JDT Minor modifications to comments based on
* material from Sinnott, 1994.
* 7 Feb 01 0.008 JDT Fixed backwards time zone. The standard is that
* local time zone is specified in hours EAST of
* Greenwich, so that EST would be -5, for example.
* For some reason, SUNUP.BAS does this backwards
* (probably an americocentric perspective) and
* SunriseSunset adopted that convention. Oops.
* So the sign in the math is changed.
* 7 Feb 01 0.009 JDT Well, that threw off the azimuth calculation...
* Removed the azimuth calculations.
* 14 Feb 01 0.010 JDT Added ability to accept a time (HH:mm) in
* dateInput, and decide if that time is daytime
* or nighttime.
* 27 Feb 01 0.011 JDT Added accessor methods in place of having public
* variables to get results.
* 28 Feb 01 0.012 JDT Cleaned up list of imported classes.
* 28 Mar 01 1.10 JDT Final version accompanying deliverable 1b.
* 4 Apr 01 1.11 JDT Moved logic supporting .isDaytime into method.
* Moved calculations out of constructor.
* 01 May 01 1.12 JMG Added 'GMT' designation and testing lines.
* 16 May 01 1.13 JDT Added setLenient( false ) and setTimeZone( tz )
* to dfmtDay, dfmtMonth, and dfmtYear in
* doCalculations.
* 27 Jun 01 1.14 JDT Removed reliance on StationConstants (GMT).
* 13 Aug 01 1.20 JDT Final version accompanying deliverable 1c.
* 6 Sep 01 1.21 JDT Thorough code and comment review.
* 21 Sep 01 1.30 JDT Final version accompanying deliverable 2.
* 17 Dec 01 1.40 JDT Version accompanying final deliverable.
*
*----------------------------------------------------------------------------*/
// Import required classes and packages
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.math.BigDecimal;
import java.util.TimeZone;
/******************************************************************************
* class: SunriseSunset class
*******************************************************************************
*
* This Java class performs calculations to determine the time of
* sunrise and sunset given lat, long, and date.
*
* It is assumed that the data provided are within valie ranges
* (i.e. latitude between -90 and +90, longitude between 0 and 360,
* a valid date, and time zone between -14 and +14.
*
*----------------------------------------------------------------------------*/
public class SunriseSunset
{
// Declare and initialize variables
private double dfLat; // latitude from user
private double dfLon; // latitude from user
private Date dateInput; // date/time from user
private double dfTimeZone; // time zone from user
private Date dateSunrise; // date and time of sunrise
private Date dateSunset; // date and time of sunset
private boolean bSunriseToday = false; // flag for sunrise on this date
private boolean bSunsetToday = false; // flag for sunset on this date
private boolean bSunUpAllDay = false; // flag for sun up all day
private boolean bSunDownAllDay = false; // flag for sun down all day
private boolean bDaytime = false; // flag for daytime, given
// hour and min in dateInput
private boolean bSunrise = false; // sunrise during hour checked
private boolean bSunset = false; // sunset during hour checked
private boolean bGregorian = false; // flag for Gregorian calendar
private int iJulian; // Julian day
private int iYear; // year of date of interest
private int iMonth; // month of date of interest
private int iDay; // day of date of interest
private int iCount; // a simple counter
private int iSign; // SUNUP.BAS: S
private double dfHourRise, dfHourSet; // hour of event: SUNUP.BAS H3
private double dfMinRise, dfMinSet; // minute of event: SUNUP.BAS M3
private double dfSinLat, dfCosLat; // sin and cos of latitude
private double dfZenith; // SUNUP.BAS Z: Zenith
private SimpleDateFormat dfmtDate; // formatting for date alone
private SimpleDateFormat dfmtDateTime; // formatting for date and time
private SimpleDateFormat dfmtYear; // formatting for year
private SimpleDateFormat dfmtMonth; // formatting for month
private SimpleDateFormat dfmtDay; // formatting for day
// Many variables in SUNUP.BAS have undocumented meanings,
// and so are translated rather directly to avoid confusion:
private double dfAA1 = 0, dfAA2 = 0; // SUNUP.BAS A(2)
private double dfDD1 = 0, dfDD2 = 0; // SUNUP.BAS D(2)
private double dfC0; // SUNUP.BAS C0
private double dfK1; // SUNUP.BAS K1
private double dfP; // SUNUP.BAS P
private double dfJ; // SUNUP.BAS J
private double dfJ3; // SUNUP.BAS J3
private double dfA; // SUNUP.BAS A
private double dfA0, dfA2, dfA5; // SUNUP.BAS A0, A2, A5
private double dfD0, dfD1, dfD2, dfD5; // SUNUP.BAS D0, D1, D2, D5
private double dfDA, dfDD; // SUNUP.BAS DA, DD
private double dfH0, dfH1, dfH2; // SUNUP.BAS H0, H1, H2
private double dfL0, dfL2; // SUNUP.BAS L0, L2
private double dfT, dfT0, dfTT; // SUNUP.BAS T, T0, TT
private double dfV0, dfV1, dfV2; // SUNUP.BAS V0, V1, V2
private TimeZone tz = TimeZone.getTimeZone( "GMT" );
/******************************************************************************
* method: SunriseSunset
*******************************************************************************
*
* Constructor for SunriseSunset class.
*
*----------------------------------------------------------------------------*/
public SunriseSunset(
double dfLatIn, // latitude
double dfLonIn, // longitude
Date dateInputIn, // date
double dfTimeZoneIn // time zone
)
{
// Copy values supplied as agruments to local variables.
dfLat = dfLatIn;
dfLon = dfLonIn;
dateInput = dateInputIn;
dfTimeZone = dfTimeZoneIn;
// Call the method to do the calculations.
doCalculations();
} // end of class constructor
/******************************************************************************
* method: doCalculations
*******************************************************************************
*
* Method for performing the calculations done in SUNUP.BAS.
*
*----------------------------------------------------------------------------*/
private void doCalculations()
{
try
{
// Break out day, month, and year from date provided.
// (This is necesary for the math algorithms.)
dfmtYear = new SimpleDateFormat( "yyyy" );
dfmtYear.setLenient( false );
dfmtYear.setTimeZone( tz );
dfmtMonth = new SimpleDateFormat( "M" );
dfmtMonth.setLenient( false );
dfmtMonth.setTimeZone( tz );
dfmtDay = new SimpleDateFormat( "d" );
dfmtDay.setLenient( false );
dfmtDay.setTimeZone( tz );
iYear = Integer.parseInt( dfmtYear.format( dateInput ) );
iMonth = Integer.parseInt( dfmtMonth.format( dateInput ) );
iDay = Integer.parseInt( dfmtDay.format( dateInput ) );
// Convert time zone hours to decimal days (SUNUP.BAS line 50)
dfTimeZone = dfTimeZone / 24.0;
// NOTE: (7 Feb 2001) Here is a non-standard part of SUNUP.BAS:
// It (and this algorithm) assumes that the time zone is
// positive west, instead of the standard negative west.
// Classes calling SunriseSunset will be assuming that
// times zones are specified in negative west, so here the
// sign is changed so that the SUNUP algorithm works:
dfTimeZone = -dfTimeZone;
// Convert longitude to fraction (SUNUP.BAS line 50)
dfLon = dfLon / 360.0;
// Convert calendar date to Julian date:
// Check to see if it's later than 1583: Gregorian calendar
// When declared, bGregorian is initialized to false.
// ** Consider making a separate class of this function. **
if( iYear >= 1583 ) bGregorian = true;
// SUNUP.BAS 1210
dfJ = -Math.floor( 7.0 // SUNUP used INT, not floor
* ( Math.floor(
( iMonth + 9.0 )
/ 12.0
) + iYear
) / 4.0
)
// add SUNUP.BAS 1240 and 1250 for G = 0
+ Math.floor( iMonth * 275.0 / 9.0 )
+ iDay
+ 1721027.0
+ iYear * 367.0;
if ( bGregorian )
{
// SUNUP.BAS 1230
if ( ( iMonth - 9.0 ) < 0.0 ) iSign = -1;
else iSign = 1;
dfA = Math.abs( iMonth - 9.0 );
// SUNUP.BAS 1240 and 1250
dfJ3 = -Math.floor(
(
Math.floor(
Math.floor( iYear
+ (double)iSign
* Math.floor( dfA / 7.0 )
)
/ 100.0
) + 1.0
) * 0.75
);
// correct dfJ as in SUNUP.BAS 1240 and 1250 for G = 1
dfJ = dfJ + dfJ3 + 2.0;
}
// SUNUP.BAS 1290
iJulian = (int)dfJ - 1;
// SUNUP.BAS 60 and 70 (see also line 1290)
dfT = (double)iJulian - 2451545.0 + 0.5;
dfTT = dfT / 36525.0 + 1.0; // centuries since 1900
// Calculate local sidereal time at 0h in zone time
// SUNUP.BAS 410 through 460
dfT0 = ( dfT * 8640184.813 / 36525.0
+ 24110.5
+ dfTimeZone * 86636.6
+ dfLon * 86400.0
)
/ 86400.0;
dfT0 = dfT0 - Math.floor( dfT0 ); // NOTE: SUNUP.BAS uses INT()
dfT0 = dfT0 * 2.0 * Math.PI;
// SUNUP.BAS 90
dfT = dfT + dfTimeZone;
// SUNUP.BAS 110: Get Sun's position
for( iCount=0; iCount<=1; iCount++ ) // Loop thru only twice
{
// Calculate Sun's right ascension and declination
// at the start and end of each day.
// SUNUP.BAS 910 - 1160: Fundamental arguments
// from van Flandern and Pulkkinen, 1979
// declare local temporary doubles for calculations
double dfGG; // SUNUP.BAS G
double dfLL; // SUNUP.BAS L
double dfSS; // SUNUP.BAS S
double dfUU; // SUNUP.BAS U
double dfVV; // SUNUP.BAS V
double dfWW; // SUNUP.BAS W
dfLL = 0.779072 + 0.00273790931 * dfT;
dfLL = dfLL - Math.floor( dfLL );
dfLL = dfLL * 2.0 * Math.PI;
dfGG = 0.993126 + 0.0027377785 * dfT;
dfGG = dfGG - Math.floor( dfGG );
dfGG = dfGG * 2.0 * Math.PI;
dfVV = 0.39785 * Math.sin( dfLL )
- 0.01000 * Math.sin( dfLL - dfGG )
+ 0.00333 * Math.sin( dfLL + dfGG )
- 0.00021 * Math.sin( dfLL ) * dfTT;
dfUU = 1
- 0.03349 * Math.cos( dfGG )
- 0.00014 * Math.cos( dfLL * 2.0 )
+ 0.00008 * Math.cos( dfLL );
dfWW = - 0.00010
- 0.04129 * Math.sin( dfLL * 2.0 )
+ 0.03211 * Math.sin( dfGG )
- 0.00104 * Math.sin( 2.0 * dfLL - dfGG )
- 0.00035 * Math.sin( 2.0 * dfLL + dfGG )
- 0.00008 * Math.sin( dfGG ) * dfTT;
// Compute Sun's RA and Dec; SUNUP.BAS 1120 - 1140
dfSS = dfWW / Math.sqrt( dfUU - dfVV * dfVV );
dfA5 = dfLL
+ Math.atan( dfSS / Math.sqrt( 1.0 - dfSS * dfSS ));
dfSS = dfVV / Math.sqrt( dfUU );
dfD5 = Math.atan( dfSS / Math.sqrt( 1 - dfSS * dfSS ));
// Set values and increment t
if ( iCount == 0 ) // SUNUP.BAS 125
{
dfAA1 = dfA5;
dfDD1 = dfD5;
}
else // SUNUP.BAS 145
{
dfAA2 = dfA5;
dfDD2 = dfD5;
}
dfT = dfT + 1.0; // SUNUP.BAS 130
} // end of Get Sun's Position for loop
if ( dfAA2 < dfAA1 ) dfAA2 = dfAA2 + 2.0 * Math.PI;
// SUNUP.BAS 150
dfZenith = Math.PI * 90.833 / 180.0; // SUNUP.BAS 160
dfSinLat = Math.sin( dfLat * Math.PI / 180.0 ); // SUNUP.BAS 170
dfCosLat = Math.cos( dfLat * Math.PI / 180.0 ); // SUNUP.BAS 170
dfA0 = dfAA1; // SUNUP.BAS 190
dfD0 = dfDD1; // SUNUP.BAS 190
dfDA = dfAA2 - dfAA1; // SUNUP.BAS 200
dfDD = dfDD2 - dfDD1; // SUNUP.BAS 200
dfK1 = 15.0 * 1.0027379 * Math.PI / 180.0; // SUNUP.BAS 330
// Initialize sunrise and sunset times, and other variables
// hr and min are set to impossible times to make errors obvious
dfHourRise = 99.0;
dfMinRise = 99.0;
dfHourSet = 99.0;
dfMinSet = 99.0;
dfV0 = 0.0; // initialization implied by absence in SUNUP.BAS
dfV2 = 0.0; // initialization implied by absence in SUNUP.BAS
// Test each hour to see if the Sun crosses the horizon
// and which way it is heading.
for( iCount=0; iCount<24; iCount++ ) // SUNUP.BAS 210
{
double tempA; // SUNUP.BAS A
double tempB; // SUNUP.BAS B
double tempD; // SUNUP.BAS D
double tempE; // SUNUP.BAS E
dfC0 = (double)iCount;
dfP = ( dfC0 + 1.0 ) / 24.0; // SUNUP.BAS 220
dfA2 = dfAA1 + dfP * dfDA; // SUNUP.BAS 230
dfD2 = dfDD1 + dfP * dfDD; // SUNUP.BAS 230
dfL0 = dfT0 + dfC0 * dfK1; // SUNUP.BAS 500
dfL2 = dfL0 + dfK1; // SUNUP.BAS 500
dfH0 = dfL0 - dfA0; // SUNUP.BAS 510
dfH2 = dfL2 - dfA2; // SUNUP.BAS 510
// hour angle at half hour
dfH1 = ( dfH2 + dfH0 ) / 2.0; // SUNUP.BAS 520
// declination at half hour
dfD1 = ( dfD2 + dfD0 ) / 2.0; // SUNUP.BAS 530
// Set value of dfV0 only if this is the first hour,
// otherwise, it will get set to the last dfV2 (SUNUP.BAS 250)
if ( iCount == 0 ) // SUNUP.BAS 550
{
dfV0 = dfSinLat * Math.sin( dfD0 )
+ dfCosLat * Math.cos( dfD0 ) * Math.cos( dfH0 )
- Math.cos( dfZenith ); // SUNUP.BAS 560
}
else
dfV0 = dfV2; // That is, dfV2 from the previous hour.
dfV2 = dfSinLat * Math.sin( dfD2 )
+ dfCosLat * Math.cos( dfD2 ) * Math.cos( dfH2 )
- Math.cos( dfZenith ); // SUNUP.BAS 570
// if dfV0 and dfV2 have the same sign, then proceed to next hr
if (
( dfV0 >= 0.0 && dfV2 >= 0.0 ) // both are positive
|| // or
( dfV0 < 0.0 && dfV2 < 0.0 ) // both are negative
)
{
// Break iteration and proceed to test next hour
dfA0 = dfA2; // SUNUP.BAS 250
dfD0 = dfD2; // SUNUP.BAS 250
continue; // SUNUP.BAS 610
}
dfV1 = dfSinLat * Math.sin( dfD1 )
+ dfCosLat * Math.cos( dfD1 ) * Math.cos( dfH1 )
- Math.cos( dfZenith ); // SUNUP.BAS 590
tempA = 2.0 * dfV2 - 4.0 * dfV1 + 2.0 * dfV0;
// SUNUP.BAS 600
tempB = 4.0 * dfV1 - 3.0 * dfV0 - dfV2; // SUNUP.BAS 600
tempD = tempB * tempB - 4.0 * tempA * dfV0; // SUNUP.BAS 610
if ( tempD < 0.0 )
{
// Break iteration and proceed to test next hour
dfA0 = dfA2; // SUNUP.BAS 250
dfD0 = dfD2; // SUNUP.BAS 250
continue; // SUNUP.BAS 610
}
tempD = Math.sqrt( tempD ); // SUNUP.BAS 620
// Determine occurence of sunrise or sunset.
// Flags to identify occurrence during this day are
// bSunriseToday and bSunsetToday, and are initialized false.
// These are set true only if sunrise or sunset occurs
// at any point in the hourly loop. Never set to false.
// Flags to identify occurrence during this hour:
bSunrise = false; // reset before test
bSunset = false; // reset before test
if ( dfV0 < 0.0 && dfV2 > 0.0 ) // sunrise occurs this hour
{
bSunrise = true; // SUNUP.BAS 640
bSunriseToday = true; // sunrise occurred today
}
if ( dfV0 > 0.0 && dfV2 < 0.0 ) // sunset occurs this hour
{
bSunset = true; // SUNUP.BAS 660
bSunsetToday = true; // sunset occurred today
}
tempE = ( tempD - tempB ) / ( 2.0 * tempA );
if ( tempE > 1.0 || tempE < 0.0 ) // SUNUP.BAS 670, 680
tempE = ( -tempD - tempB ) / ( 2.0 * tempA );
// Set values of hour and minute of sunset or sunrise
// only if sunrise/set occurred this hour.
if ( bSunrise )
{
dfHourRise = Math.floor( dfC0 + tempE + 1.0/120.0 );
dfMinRise = Math.floor(
( dfC0 + tempE + 1.0/120.0
- dfHourRise
)
* 60.0
);
}
if ( bSunset )
{
dfHourSet = Math.floor( dfC0 + tempE + 1.0/120.0 );
dfMinSet = Math.floor(
( dfC0 + tempE + 1.0/120.0
- dfHourSet
)
* 60.0
);
}
// Change settings of variables for next loop
dfA0 = dfA2; // SUNUP.BAS 250
dfD0 = dfD2; // SUNUP.BAS 250
} // end of loop testing each hour for an event
// After having checked all hours, set flags if no rise or set
// bSunUpAllDay and bSundownAllDay are initialized as false
if ( !bSunriseToday && !bSunsetToday )
{
if ( dfV2 < 0.0 )
bSunDownAllDay = true;
else
bSunUpAllDay = true;
}
// Load dateSunrise with data
dfmtDateTime = new SimpleDateFormat( "d M yyyy HH:mm z" );
if( bSunriseToday )
{
dateSunrise = dfmtDateTime.parse( iDay
+ " " + iMonth
+ " " + iYear
+ " " + (int)dfHourRise
+ ":" + (int)dfMinRise
+ " GMT" );
}
// Load dateSunset with data
if( bSunsetToday )
{
dateSunset = dfmtDateTime.parse( iDay
+ " " + iMonth
+ " " + iYear
+ " " + (int)dfHourSet
+ ":" + (int)dfMinSet
+ " GMT" );
}
} // end of try
// Catch errors
catch( ParseException e )
{
System.out.println( "\nCannot parse date" );
System.out.println( e );
System.exit( 1 );
} // end of catch
}
/******************************************************************************
* method: getSunrise()
*******************************************************************************
*
* Gets the date and time of sunrise. If there is no sunrise, returns null.
*
* Member of SunriseSunset class
*
* -------------------------------------------------------------------------- */
public Date getSunrise()
{
if ( bSunriseToday )
return( dateSunrise );
else
return( null );
}
/******************************************************************************
* method: getSunset()
*******************************************************************************
*
* Gets the date and time of sunset. If there is no sunset, returns null.
*
* Member of SunriseSunset class
*
* -------------------------------------------------------------------------- */
public Date getSunset()
{
if ( bSunsetToday )
return( dateSunset );
else
return( null );
}
/******************************************************************************
* method: isSunrise()
*******************************************************************************
*
* Returns a boolean identifying if there was a sunrise.
*
* Member of SunriseSunset class
*
* -------------------------------------------------------------------------- */
public boolean isSunrise()
{
return( bSunriseToday );
}
/******************************************************************************
* method: isSunset()
*******************************************************************************
*
* Returns a boolean identifying if there was a sunset.
*
* Member of SunriseSunset class
*
* -------------------------------------------------------------------------- */
public boolean isSunset()
{
return( bSunsetToday );
}
/******************************************************************************
* method: isSunUp()
*******************************************************************************
*
* Returns a boolean identifying if the sun is up all day.
*
* Member of SunriseSunset class
*
* -------------------------------------------------------------------------- */
public boolean isSunUp()
{
return( bSunUpAllDay );
}
/******************************************************************************
* method: isSunDown()
*******************************************************************************
*
* Returns a boolean identifying if the sun is down all day.
*
* Member of SunriseSunset class
*
* -------------------------------------------------------------------------- */
public boolean isSunDown()
{
return( bSunDownAllDay );
}
/******************************************************************************
* method: isDaytime()
*******************************************************************************
*
* Returns a boolean identifying if it is daytime at the hour contained in
* the Date object passed to SunriseSunset on construction.
*
* Member of SunriseSunset class
*
* -------------------------------------------------------------------------- */
public boolean isDaytime()
{
// Determine if it is daytime (at sunrise or later)
// or nighttime (at sunset or later) at the location of interest
// but expressed in the time zone requested.
if ( bSunriseToday && bSunsetToday ) // sunrise and sunset
{
if ( dateSunrise.before( dateSunset ) ) // sunrise < sunset
{
if (
(
dateInput.after( dateSunrise )
||
dateInput.equals( dateSunrise )
)
&&
dateInput.before( dateSunset )
)
bDaytime = true;
else
bDaytime = false;
}
else // sunrise comes after sunset (in opposite time zones)
{
if (
(
dateInput.after( dateSunrise )
||
dateInput.equals( dateSunrise )
)
|| // use OR rather than AND
dateInput.before( dateSunset )
)
bDaytime = true;
else
bDaytime = false;
}
}
else if ( bSunUpAllDay ) // sun is up all day
bDaytime = true;
else if ( bSunDownAllDay ) // sun is down all day
bDaytime = false;
else if ( bSunriseToday ) // sunrise but no sunset
{
if ( dateInput.before( dateSunrise ) )
bDaytime = false;
else
bDaytime = true;
}
else if ( bSunsetToday ) // sunset but no sunrise
{
if ( dateInput.before( dateSunset ) )
bDaytime = true;
else
bDaytime = false;
}
else bDaytime = false; // this should never execute
return( bDaytime );
}
} // end of class
/*-----------------------------------------------------------------------------
* end of class
*----------------------------------------------------------------------------*/
| 10-myclimb | trunk/MyClimb/src/tool/SunriseSunset/SunriseSunset.java | Java | asf20 | 26,858 |
package app;
import ui.viewModel.ViewModel;
import foundation.data.DataHelper;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
/**
*
* @author 福建师范大学软件学院 倪友聪、赵康
*
*/
public class MyApplication extends Application {
// 数据库助手
public static DataHelper DATAHELPER;
// 数据库名
public static String DATAFILENAME = "myApp.db";
// 登录用户
// Activity跳转广播接收器
public static ViewFwdRcv VWFWDRCV;
@Override
public void onCreate() {
super.onCreate();
// 初始化全局变量
DATAHELPER = new DataHelper(getApplicationContext(), DATAFILENAME);
VWFWDRCV = new ViewFwdRcv();
}
// Activity跳转广播接收器类的定义
public class ViewFwdRcv extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// 获取源源Activity和目标源Activity的名字
String frmActClsNm = arg1.getStringExtra("frmActClsNm");
String toActClsNm = arg1.getStringExtra("toActClsNm");
if (frmActClsNm.equals(toActClsNm) || frmActClsNm == null
|| toActClsNm == null) {
return;
}
// 源Activity的ViewModel对象
ViewModel ObjOfFrmActVM = null;
// 目标Activity的ViewModel对象
ViewModel ObjOfToActVM = null;
// 源Activity中ViewModel对象的打包对象
Bundle bdlOfFrmAct = arg1.getExtras();
// 目标Activity中ViewModel对象的打包对象
Bundle bdlOfToAct = null;
if (bdlOfFrmAct != null) {
// 获取源Activity的ViewModel对象
ObjOfFrmActVM = ViewModel.readFromBundle(bdlOfFrmAct);
}
// 依据源Activity的ViewModel对象,变换生成目标Activity的ViewModel对象
ObjOfToActVM = ViewModelTansformation(frmActClsNm, ObjOfFrmActVM,
toActClsNm);
// 打包目标Activity的ViewModel对象
if (ObjOfToActVM != null) {
bdlOfToAct = ObjOfToActVM.writeToBundle();
}
Class<?> clsOfToAct = null;
try {
clsOfToAct = Class.forName(toActClsNm);
Intent toActIntent = new Intent(MyApplication.this, clsOfToAct);
if (bdlOfToAct != null) {
toActIntent.putExtras(bdlOfToAct);
}
toActIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(toActIntent);
} catch (ClassNotFoundException e) {
Log.e(toActClsNm, "目标Activity的类找不到");
}
}
}
protected ViewModel ViewModelTansformation(String frmActClsNm,
ViewModel objOfFrmActVM, String toActClsNm) {
ViewModel resultVMofToAct = null;
/*
* if (frmActClsNm.equals(Activity1.class.getName()) &&
* toActClsNm.equals(Aoivtity2.class.getName())){ // 强制类型转换 if
* (objOfFrmActVM != null) { ViewModelX objOfVMX = (ViewModelX)
* objOfFrmActVM; ViewModelY objOfVMY = new ViewModelY();
*
* //视图模型变换 objOfVMY.setAge2(objOfVMX.getAge() + 1); resultVMofToAct =
* objOfVMY; } }
*/
return resultVMofToAct;
}
}
| 10-myclimb | trunk/MyClimb/src/app/MyApplication.java | Java | asf20 | 3,127 |
package app;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import com.mysport.ui.R;
/**
*
* @author GreamTeam 沈志鹏 郑运春
*
*/
public class MainActivity extends TabActivity implements OnCheckedChangeListener{
public static final String TAB_GPS = "tabGps";
public static final String TAB_MAP = "tabMap";
public static final String TAB_WEATHER = "tabWeather";
public static final String TAB_TERRAIN = "tabTerrain";
private RadioGroup radioderGroup;
private TabHost tabHost;
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_tab);
tabHost=this.getTabHost();
//添加选项卡
tabHost.addTab(tabHost.newTabSpec("TAB_GPS").setIndicator("TAB_GPS")
.setContent(new Intent(this, ui.activity.gps.GpsObtainActivity.class)));
tabHost.addTab(tabHost.newTabSpec("TAB_MAP").setIndicator("TAB_MAP")
.setContent(new Intent(this,ui.activity.GoogleMap.GMapActivity.class)));
tabHost.addTab(tabHost.newTabSpec("TAB_WEATHER").setIndicator("TAB_WEATHER")
.setContent(new Intent(this,ui.activity.weather.WeatherActivity.class)));
// tabHost.addTab(tabHost.newTabSpec("TAB_TERRAIN").setIndicator("TAB_TERRAIN")
// .setContent(new Intent(this,ui.activity.GoogleMap.GoogleMapActivity.class)));
radioderGroup = (RadioGroup) findViewById(R.id.main_radio);
radioderGroup.setOnCheckedChangeListener(this);
this.tabHost.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
}
});
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch(checkedId){
case R.id.radio_button0:
tabHost.setCurrentTabByTag("TAB_GPS");
break;
case R.id.radio_button1:
tabHost.setCurrentTabByTag("TAB_MAP");
break;
case R.id.radio_button2:
tabHost.setCurrentTabByTag("TAB_WEATHER");
break;
case R.id.radio_button3:
tabHost.setCurrentTabByTag("TAB_TERRAIN");
break;
}
}
}
| 10-myclimb | trunk/MyClimb/src/app/MainActivity.java | Java | asf20 | 2,394 |
/**
* Copyright (c) 2013 Baidu.com, Inc. All Rights Reserved
*/
package socialShare.wxapi;
import android.os.Bundle;
import com.baidu.sharesdk.weixin.WXEventHandlerActivity;
/**
* 处理微信回调
* @author chenhetong(chenhetong@baidu.com)
*
*/
public class WXEntryActivity extends WXEventHandlerActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
finish();
}
}
| 10-myclimb | trunk/MyClimb/src/socialShare/wxapi/WXEntryActivity.java | Java | asf20 | 465 |
package socialShare;
public class SocialShareConfig {
public final static String mbApiKey = "OYt9Ios9cy7vM09e64AIIjFE"; // online
// env
public static final String SINA_SSO_APP_KEY = "319137445";
public static final String QQ_SSO_APP_KEY = "100358052";
public static final String wxApp = "wxa2f5dc38baa66b9d";
}
| 10-myclimb | trunk/MyClimb/src/socialShare/SocialShareConfig.java | Java | asf20 | 355 |
package domain.businessService.gps;
import java.util.List;
import domain.businessEntity.gps.ClimbData;
public interface IClimbDataService {
//添加登山记录
public boolean addClimbData(ClimbData data);
//删除登山记录
public boolean deleteCilmbDataByID(int climbId);
//删除全部记录
public boolean deleteAll();
//获取登山记录
public List<ClimbData> getClimbData();
//根据ID获取登山记录
public ClimbData getClimbDataById(int climbId);
}
| 10-myclimb | trunk/MyClimb/src/domain/businessService/gps/IClimbDataService.java | Java | asf20 | 513 |
package domain.businessService.gps;
import java.util.Date;
import java.util.List;
import domain.businessEntity.gps.LatLngData;
public interface ILatLngDataService {
public boolean addLatLngData(LatLngData data);
public boolean deleteAll();
public boolean deleteByDate(String time);
public List<LatLngData> getLatLngDataByTime(String time);
}
| 10-myclimb | trunk/MyClimb/src/domain/businessService/gps/ILatLngDataService.java | Java | asf20 | 370 |
package domain.businessService.gps;
import java.util.List;
import domain.businessEntity.gps.AltitudeData;
public interface IAltitudeDataService {
public boolean addAltitudeData(AltitudeData data);
public boolean deleteAltitudeData(String time);
public List<AltitudeData> getAltitudeData(String time);
}
| 10-myclimb | trunk/MyClimb/src/domain/businessService/gps/IAltitudeDataService.java | Java | asf20 | 331 |
package domain.businessService.gps;
import java.sql.SQLException;
import java.util.List;
import ui.viewModel.gps.RecDetailViewModel;
import com.j256.ormlite.stmt.QueryBuilder;
import android.util.Log;
import domain.businessEntity.gps.ClimbData;
import foundation.data.DataContext;
import foundation.data.IDataContext;
public class ClimbDataService implements IClimbDataService {
private static String Tag="GpsDataService";
private RecDetailViewModel viewModel;
private IDataContext ctx=null;
public ClimbDataService(){
ctx= new DataContext();
}
//添加数据
@Override
public boolean addClimbData(ClimbData data) {
try {
ctx.add(data, ClimbData.class, int.class);
return true;
} catch (SQLException e) {
Log.e(Tag, e.toString());
}
return false;
}
//根据ID删除数据
@Override
public boolean deleteCilmbDataByID(int climbId) {
// TODO Auto-generated method stub
try {
ctx.deleteById(climbId, ClimbData.class, int.class);
} catch (SQLException e) {
// TODO Auto-generated catch block
Log.e(Tag, e.toString());
}
return false;
}
//删除所有数据
@Override
public boolean deleteAll() {
try {
ctx.deleteAll(ClimbData.class, int.class);
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
Log.e(Tag, e.toString());
}
return false;
}
//获取数据
@Override
public List<ClimbData> getClimbData() {
// TODO Auto-generated method stub
try {
List<ClimbData> dateList=ctx.queryForAll(ClimbData.class, int.class);
return dateList;
} catch (SQLException e) {
// TODO Auto-generated catch block
Log.e(Tag, e.toString());
}
return null;
}
//根据ID获取数据
public ClimbData getClimbDataById(int climbId) {
// TODO Auto-generated method stub
ClimbData climbdata = new ClimbData();
try{
climbdata = ctx.queryById(ClimbData.class, int.class, climbId);
return climbdata;
}catch (Exception e) {
// TODO: handle exception
Log.e(Tag, e.toString());
}
return null;
}
/*
public boolean getClimbDataById(int climbId) {
// TODO Auto-generated method stub
ClimbData climbdata=null;
try{
climbdata = new ClimbData();
climbdata = ctx.queryById(ClimbData.class, int.class, climbId);
viewModel.setClimbdata(climbdata);
// viewModel.fireOnUpdated();
return true;
}catch (Exception e) {
// TODO: handle exception
Log.e(Tag, e.toString());
}
return false;
}
*/
}
| 10-myclimb | trunk/MyClimb/src/domain/businessService/gps/ClimbDataService.java | Java | asf20 | 2,605 |
package domain.businessService.gps;
import java.sql.SQLException;
import java.util.List;
import android.util.Log;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import domain.businessEntity.gps.AltitudeData;
import domain.businessEntity.gps.LatLngData;
import foundation.data.DataContext;
import foundation.data.IDataContext;
public class AltitudeDataService implements IAltitudeDataService {
private static String tag="AltitudeDataService";
private IDataContext ctx = null;
public AltitudeDataService(){
ctx = new DataContext();
}
@Override
public boolean addAltitudeData(AltitudeData data) {
try {
ctx.add(data, AltitudeData.class, Integer.class);
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
@Override
public boolean deleteAltitudeData(String time) {
DeleteBuilder<AltitudeData, Integer> db;
try {
db = ctx.getDeleteBuilder(AltitudeData.class, int.class);
db.where().eq("time", time);
ctx.delete(AltitudeData.class, int.class, db.prepare());
} catch (SQLException e) {
Log.e(tag, e.toString());
}
return false;
}
@Override
public List<AltitudeData> getAltitudeData(String time) {
try {
QueryBuilder<AltitudeData,Integer> qb = ctx.getQueryBuilder(AltitudeData.class, int.class);
qb.where().eq("time", time);
List<AltitudeData> qbDataList = ctx.query(AltitudeData.class, int.class, qb.prepare());
return qbDataList;
} catch (SQLException e) {
Log.e(tag,e.toString());
}
return null;
}
}
| 10-myclimb | trunk/MyClimb/src/domain/businessService/gps/AltitudeDataService.java | Java | asf20 | 1,647 |
package domain.businessService.gps;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import android.util.Log;
import domain.businessEntity.gps.LatLngData;
import foundation.data.DataContext;
import foundation.data.IDataContext;
public class LatLngDataService implements ILatLngDataService{
private static String tag="LatLngDataService";
private IDataContext ctx = null;
public LatLngDataService(){
ctx = new DataContext();
}
@Override
public boolean addLatLngData(LatLngData data) {
try {
ctx.add(data, LatLngData.class, Integer.class);
return true;
} catch (SQLException e) {
Log.e(tag, e.toString());
}
return false;
}
@Override
public boolean deleteAll() {
try {
ctx.deleteAll(LatLngData.class, Integer.class);
return true;
} catch (SQLException e) {
Log.e(tag,e.toString());
}
return false;
}
@Override
public boolean deleteByDate(String time) {
DeleteBuilder<LatLngData, Integer> db;
try {
db = ctx.getDeleteBuilder(LatLngData.class, int.class);
db.where().eq("time", time);
ctx.delete(LatLngData.class, int.class, db.prepare());
} catch (SQLException e) {
Log.e(tag, e.toString());
}
return false;
}
@Override
public List<LatLngData> getLatLngDataByTime(String time) {
try {
QueryBuilder<LatLngData,Integer> qb = ctx.getQueryBuilder(LatLngData.class, int.class);
qb.where().eq("time", time);
List<LatLngData> qbDataList = ctx.query(LatLngData.class, int.class, qb.prepare());
return qbDataList;
} catch (SQLException e) {
Log.e(tag,e.toString());
}
return null;
}
}
| 10-myclimb | trunk/MyClimb/src/domain/businessService/gps/LatLngDataService.java | Java | asf20 | 1,780 |
package domain.businessEntity.gps;
import java.util.Date;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "T_ClimbData")
public class ClimbData {
public ClimbData(){}
//ID号 设置主键
@DatabaseField(generatedId = true)
private int climbID;
//设置登山记录名称
@DatabaseField(canBeNull = false)
private String climbName;
//开始高度
@DatabaseField(canBeNull = true)
private int startAltitude;
//结束高度
@DatabaseField(canBeNull = true)
private int stopAltitude;
//开始时间
@DatabaseField(canBeNull = true)
private Date startTime;
//结束时间
@DatabaseField(canBeNull = true)
private Date stopTime;
//经度
@DatabaseField(canBeNull = true)
private Double longitude;
//纬度
@DatabaseField(canBeNull = true)
private Double latitude;
public int getStartAltitude() {
return startAltitude;
}
public void setStartAltitude(int startAltitude) {
this.startAltitude = startAltitude;
}
public int getStopAltitude() {
return stopAltitude;
}
public void setStopAltitude(int stopAltitude) {
this.stopAltitude = stopAltitude;
}
public int getClimbID() {
return climbID;
}
public void setClimbID(int climbID) {
this.climbID = climbID;
}
public String getClimbName() {
return climbName;
}
public void setClimbName(String climbName) {
this.climbName = climbName;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getStopTime() {
return stopTime;
}
public void setStopTime(Date stopTime) {
this.stopTime = stopTime;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
}
| 10-myclimb | trunk/MyClimb/src/domain/businessEntity/gps/ClimbData.java | Java | asf20 | 2,040 |
package domain.businessEntity.gps;
import java.util.Date;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "T_LatLngData")
public class LatLngData {
public LatLngData(){}
//设置ID为主键
@DatabaseField(generatedId = true)
private int dataID;
//设置开始记录时间作为标识
@DatabaseField(canBeNull = false)
private String time;
//纬度
@DatabaseField(canBeNull = true)
private double lat;
//经度
@DatabaseField(canBeNull = true)
private double lng;
public int getDataID() {
return dataID;
}
public void setDataID(int dataID) {
this.dataID = dataID;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public String getStartTime() {
return time;
}
public void setStartTime(String time) {
this.time = time;
}
}
| 10-myclimb | trunk/MyClimb/src/domain/businessEntity/gps/LatLngData.java | Java | asf20 | 1,023 |
package domain.businessEntity.gps;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "T_AltitudeData")
public class AltitudeData {
@DatabaseField(generatedId = true)
private int dataID;
@DatabaseField(canBeNull = false)
private int Altitude;
@DatabaseField(canBeNull = false)
private String time;
public AltitudeData(){
}
public int getDateID() {
return dataID;
}
public void setDateID(int dataID) {
this.dataID = dataID;
}
public int getAltitude() {
return Altitude;
}
public void setAltitude(int altitude) {
Altitude = altitude;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
| 10-myclimb | trunk/MyClimb/src/domain/businessEntity/gps/AltitudeData.java | Java | asf20 | 793 |
package ui.activity.gps;
import java.io.ByteArrayOutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.R.integer;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.GestureDetector.OnGestureListener;
import android.view.Display;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.sharesdk.BaiduShareException;
import com.baidu.sharesdk.BaiduSocialShare;
import com.baidu.sharesdk.ShareContent;
import com.baidu.sharesdk.ShareListener;
import com.baidu.sharesdk.SocialShareLogger;
import com.baidu.sharesdk.Utility;
import com.baidu.sharesdk.ui.BaiduSocialShareUserInterface;
import com.mysport.ui.R;
import domain.businessEntity.gps.ClimbData;
import domain.businessService.gps.ClimbDataService;
import domain.businessService.gps.IClimbDataService;
import domain.businessService.gps.ILatLngDataService;
import domain.businessService.gps.LatLngDataService;
import socialShare.SocialShareConfig;
import tool.data.ClimbDataUtil;
import ui.activity.ActivityOfAF4Ad;
import ui.activity.GoogleMap.GMapActivity;
import ui.activity.GoogleMap.GoogleMapActivity;
import ui.viewModel.ModelErrorInfo;
import ui.viewModel.ViewModel;
import ui.viewModel.gps.RecDetailViewModel;
public class RecDetailsActivity extends ActivityOfAF4Ad implements
OnTouchListener, OnGestureListener {
private IClimbDataService dateService;
private ILatLngDataService latLngService;
// 记录名
private TextView tv_Name = null;
// 当前日期
private TextView tv_Date = null;
// 开始时间
private TextView tv_startTime = null;
// 结束时间
private TextView tv_stopTime = null;
// 平均海拔
private TextView tv_altitudeDiff = null;
// 经度
private TextView tv_lat = null;
// 纬度
private TextView tv_lon = null;
// 返回上一个界面
private ImageView iv_back = null;
private ImageView iv_delete = null;
private ImageView iv_location;
private int id = -1;
private int maxId = -1;
// 经纬度全局变量方便传值
private double lat;
private double lon;
private String Name;
private String strTime;// 全局变量方便取值
GestureDetector mGestureDetector = null; // 定义手势监听对象
private int verticalMinDistance = 10; // 最小触摸滑动距离
private int minVelocity = 0; // 最小水平移动速度
private RelativeLayout detailLayout;
private ImageView iv_share;
/********************** 社会化分享组件定义 ***********************************/
private BaiduSocialShare socialShare;
private BaiduSocialShareUserInterface socialShareUi;
private final static String appKey = SocialShareConfig.mbApiKey;
private final static String wxAppKey = SocialShareConfig.wxApp;
private ShareContent picContent;
private final Handler handler = new Handler(Looper.getMainLooper());
/*******************************************************************/
/*********************** 图表 *****************************************/
private XYMultipleSeriesDataset ds;
private XYMultipleSeriesRenderer render;
private XYSeries series;
private GraphicalView gv;
private XYSeriesRenderer xyRender;
/*******************************************************************/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
// 初始化社会化主件
socialShare = BaiduSocialShare.getInstance(this, appKey);
// socialShare.supportWeiBoSso(BaiduSocialShareConfig.SINA_SSO_APP_KEY);
socialShare.supportWeixin(wxAppKey);
socialShareUi = socialShare.getSocialShareUserInterfaceInstance();
SocialShareLogger.on();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_rec_details, menu);
return true;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("dataset", ds);
outState.putSerializable("renderer", render);
outState.putSerializable("current_series", series);
outState.putSerializable("current_renderer", xyRender);
}
@Override
protected void onRestoreInstanceState(Bundle savedState) {
super.onRestoreInstanceState(savedState);
ds = (XYMultipleSeriesDataset) savedState.getSerializable("dataset");
render = (XYMultipleSeriesRenderer) savedState
.getSerializable("renderer");
series = (XYSeries) savedState.getSerializable("current_series");
xyRender = (XYSeriesRenderer) savedState
.getSerializable("current_renderer");
}
@Override
protected void onResume() {
super.onResume();
if (ds == null)
getDataset();
if (render == null)
getRenderer();
if (gv == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
gv = ChartFactory.getLineChartView(this, ds, render);
layout.addView(gv, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
} else {
// 绘制图形
gv.repaint();
}
}
private XYMultipleSeriesDataset getDataset() {
ds = new XYMultipleSeriesDataset();
// 新建一个系列(线条)
series = new XYSeries("高度走势");
series.add(10,30);
series.add(20,50);
series.add(30,71);
series.add(40,85);
series.add(50,90);
// 把添加了点的折线放入dataset
ds.addSeries(series);
return ds;
}
public XYMultipleSeriesRenderer getRenderer() {
// 新建一个xymultipleseries
render = new XYMultipleSeriesRenderer();
render.setAxisTitleTextSize(16); // 设置坐标轴标题文本大小
render.setChartTitleTextSize(20); // 设置图表标题文本大小
render.setLabelsTextSize(15); // 设置轴标签文本大小
render.setLegendTextSize(15); // 设置图例文本大小
render.setMargins(new int[] {20, 30, 15,0}); // 设置4边留白
render.setPanEnabled(false, false); // 设置x,y坐标轴不会因用户划动屏幕而移动
// 设置4边留白透明
render.setMarginsColor(Color.argb(0,0xff, 0, 0));
render.setBackgroundColor(Color.TRANSPARENT); // 设置背景色透明
render.setApplyBackgroundColor(true); // 使背景色生效
render.setXTitle("持续时间");
render.setYTitle("海拔高度");
// 设置一个系列的颜色为蓝色
xyRender = new XYSeriesRenderer();
xyRender.setColor(Color.BLUE);
// 往xymultiplerender中增加一个系列
render.addSeriesRenderer(xyRender);
return render;
}
@Override
protected void initControlsAndRegEvent() {
tv_Date = (TextView) findViewById(R.id.tv_Date);
tv_startTime = (TextView) findViewById(R.id.tv_startTime);
tv_stopTime = (TextView) findViewById(R.id.tv_stopTime);
tv_altitudeDiff = (TextView) findViewById(R.id.tv_altitudeDiff);
tv_Name = (TextView) findViewById(R.id.tv_recName);
iv_back = (ImageView) findViewById(R.id.iv_back);
iv_delete = (ImageView) findViewById(R.id.iv_delete);
iv_location = (ImageView) findViewById(R.id.iv_loc);
//iv_back.setOnClickListener(new BackToRecord());
iv_share = (ImageView) findViewById(R.id.iv_share);
mGestureDetector = new GestureDetector((OnGestureListener) this);
detailLayout = (RelativeLayout) findViewById(R.id.detail_layout);
detailLayout.setOnTouchListener(this);
detailLayout.setLongClickable(true);
dateService = new ClimbDataService();
latLngService = new LatLngDataService();
Intent intent = getIntent();
ClimbData climbdata;
if (intent != null) {
Bundle bundle = intent.getExtras();
id = bundle.getInt("id");
maxId = bundle.getInt("count");
climbdata = dateService.getClimbDataById(id);
} else {
throw new RuntimeException("查看信息出错");
}
showActivity(climbdata);
// 设置分享内容
picContent = new ShareContent();
picContent.setContent("MyClimb:我刚刚登上了" + climbdata.getClimbName() + "!"
+ "这是我的行程记录");
picContent.setTitle("MyClimb");
picContent.setUrl("http://weibo.com/lovelss310");
// 设置删除键监听事件
iv_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dateService.deleteCilmbDataByID(id);
latLngService.deleteByDate(strTime);
Intent intent = new Intent(RecDetailsActivity.this,
RecordActivity.class);
startActivity(intent);
RecDetailsActivity.this.finish();
}
});
// 设置定位键监听事件
iv_location.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(RecDetailsActivity.this,
GMapActivity.class);
Bundle bundle = new Bundle();
bundle.putString("time", strTime);
bundle.putString("Marker", Name);
intent.putExtras(bundle);
startActivity(intent);
}
});
iv_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(RecDetailsActivity.this, RecordActivity.class);
RecDetailsActivity.this.startActivity(intent);
RecDetailsActivity.this.finish();
}
});
// 分享按钮监听事件
iv_share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
printscreen_share();
}
});
}
class BackToRecord implements OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent intent = new Intent();
// intent.setClass(RecDetailsActivity.this, RecordActivity.class);
// RecDetailsActivity.this.startActivity(intent);
overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
}
}
//
public void showActivity(ClimbData climbdata) {
if (climbdata != null) {
Name = climbdata.getClimbName();
tv_Name.setText(Name);
Double longitude = climbdata.getLongitude();
Double latitude = climbdata.getLatitude();
lat = longitude;
lon = latitude;
// tv_lat.setText(longitude.toString());
//
// tv_lon.setText(latitude.toString());
Date startTime = climbdata.getStartTime();
Date stopTime = climbdata.getStopTime();
tv_Date.setText(DateFormat.getDateInstance().format(startTime));
SimpleDateFormat tmp = new SimpleDateFormat("yyyy-MM-dd");
strTime = tmp.format(startTime);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
String date1 = sdf.format(startTime);
String date2 = sdf.format(stopTime);
tv_startTime.setText(date1);
tv_stopTime.setText(date2);
int startAltitude = climbdata.getStartAltitude();
int stopAltitude = climbdata.getStopAltitude();
int altitudeDiff = stopAltitude - startAltitude;
tv_altitudeDiff.setText(altitudeDiff + "");
}
}
@Override
protected ViewModel initModel() {
return null;
}
@Override
protected void upDateView(ViewModel aVM) {
// TODO Auto-generated method stub
}
@Override
protected void processViewModelErrorMsg(List<ModelErrorInfo> errsOfVM,
String errMsg) {
// TODO Auto-generated method stub
}
@Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub
if (e2.getX() - e1.getX() > verticalMinDistance
&& Math.abs(velocityX) > minVelocity && (--id) >= 1) {
Animation translateAnimationoOut = AnimationUtils.loadAnimation(
detailLayout.getContext(), R.anim.out_to_right);
detailLayout.startAnimation(translateAnimationoOut);
ClimbData climbdata = dateService.getClimbDataById(id);
showActivity(climbdata);
Animation translateAnimationIn = AnimationUtils.loadAnimation(
detailLayout.getContext(), R.anim.in_from_left);
detailLayout.startAnimation(translateAnimationIn);
}
if (e1.getX() - e2.getX() > verticalMinDistance
&& Math.abs(velocityX) > minVelocity && (++id) <= maxId) {
Toast toast = Toast.makeText(RecDetailsActivity.this, id + "",
Toast.LENGTH_SHORT);
toast.show();
ClimbData climbdata = dateService.getClimbDataById(id);
Animation translateAnimationOut = AnimationUtils.loadAnimation(
detailLayout.getContext(), R.anim.out_to_left);
detailLayout.startAnimation(translateAnimationOut);
showActivity(climbdata);
Animation translateAnimationIn = AnimationUtils.loadAnimation(
detailLayout.getContext(), R.anim.in_from_right);
detailLayout.startAnimation(translateAnimationIn);
}
return false;
}
@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return mGestureDetector.onTouchEvent(event);
}
/*************** 截屏分享 **************/
public void printscreen_share() {
View view1 = getWindow().getDecorView();
Display display = getWindowManager().getDefaultDisplay();
view1.layout(0, 0, display.getWidth(), display.getHeight());
view1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view1.getDrawingCache());
picContent.setImageUrl(null);
picContent.addImageByContent(Bitmap2Bytes(bitmap));
socialShareUi.showShareMenu(this, picContent,
Utility.SHARE_THEME_STYLE, new ShareListener() {
@Override
public void onAuthComplete(Bundle values) {
// TODO Auto-generated method stub
}
@Override
public void onApiComplete(String responses) {
// TODO Auto-generated method stub
handler.post(new Runnable() {
@Override
public void run() {
Utility.showAlert(RecDetailsActivity.this,
"分享成功");
}
});
}
@Override
public void onError(BaiduShareException e) {
handler.post(new Runnable() {
@Override
public void run() {
Utility.showAlert(RecDetailsActivity.this,
"分享失败");
}
});
}
});
}
// 把Bitmap 转成 Byte
public static byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK )
{
Intent intent = new Intent(this, RecordActivity.class);
startActivity(intent);
this.finish();
}
return true;
}
}
| 10-myclimb | trunk/MyClimb/src/ui/activity/gps/RecDetailsActivity.java | Java | asf20 | 16,585 |
package ui.activity.gps;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ui.activity.ActivityOfAF4Ad;
import ui.viewModel.ModelErrorInfo;
import ui.viewModel.ViewModel;
import android.content.Intent;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.mysport.ui.R;
import domain.businessEntity.gps.ClimbData;
import domain.businessService.gps.ClimbDataService;
import domain.businessService.gps.IClimbDataService;
/**
* @uml.annotations
* uml_usage="mmi:///#jsrctype^name=BackToRecord[jsrctype^name=RecDetailsActivity[jcu^name=RecDetailsActivity.java[jpack^name=ui.activity.gps[jsrcroot^srcfolder=src[project^id=MyClimb]]]]]$uml.Class"
* @author DreamTeam 郑宇
*/
public class RecordActivity extends ActivityOfAF4Ad implements OnTouchListener,OnGestureListener {
private IClimbDataService dateService;
private ListView recList;
private TextView tv_id;
private TextView tv_name;
List<Map<String,String>> data;
List<ClimbData> list;
Date date=new Date();
GestureDetector mGestureDetector=null; //定义手势监听对象
private int verticalMinDistance = 10; //最小触摸滑动距离
private int minVelocity = 0; //最小水平移动速度
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
dateService=new ClimbDataService();
list=dateService.getClimbData();
data=convertDateToMap(list);
recList=(ListView)findViewById(R.id.recList);
mGestureDetector=new GestureDetector((OnGestureListener)this);
RelativeLayout recordlayout=(RelativeLayout)findViewById(R.id.record_layout);
recordlayout.setOnTouchListener(this);
recordlayout.setLongClickable(true);
recList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent intent=new Intent(RecordActivity.this, RecDetailsActivity.class);
Bundle bundle=new Bundle();
bundle.putInt("id", list.get(arg2).getClimbID());
bundle.putInt("count", list.size());
intent.putExtras(bundle);
startActivity(intent);
}
});
SimpleAdapter adapter = new SimpleAdapter(this, data,
R.layout.activity_reclist2, new String[] {"name","date"}, new int[]{R.id.recName3,R.id.recDate3});
recList.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_record, menu);
return true;
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
this.finish();
}
@Override
protected void initControlsAndRegEvent() {
}
private List<Map<String, String>> convertDateToMap(List<ClimbData> climbData) {
// TODO Auto-generated method stub
List<Map<String,String>> mapList=new ArrayList<Map<String, String>>();;
if(climbData!=null)
{
int len=climbData.size(),i=0;
for(;i<len;i++)
{
Map<String,String> map=new HashMap<String, String>();
//map.put("id",climbData.get(i).getClimbID()+"");
map.put("name", climbData.get(i).getClimbName());
Date date=climbData.get(i).getStartTime();
map.put("date", DateFormat.getDateInstance().format(date));
mapList.add(map);
}
}
return mapList;
}
@Override
protected ViewModel initModel() {
// TODO Auto-generated method stub
return null;
}
@Override
protected void upDateView(ViewModel aVM) {
// TODO Auto-generated method stub
}
@Override
protected void processViewModelErrorMsg(List<ModelErrorInfo> errsOfVM,
String errMsg) {
// TODO Auto-generated method stub
}
@Override
public boolean onDown(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
if(arg1.getX()-arg0.getX()>verticalMinDistance && Math.abs(arg2)>minVelocity)
{
//Intent intent=new Intent(RecordActivity.this, GpsObtainActivity.class);
//startActivity(intent);
RecordActivity.this.finish();
overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
}
return false;
}
@Override
public void onLongPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onShowPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return mGestureDetector.onTouchEvent(event);
}
}
| 10-myclimb | trunk/MyClimb/src/ui/activity/gps/RecordActivity.java | Java | asf20 | 5,694 |
package ui.activity.gps;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import ui.activity.ActivityOfAF4Ad;
import ui.viewModel.ModelErrorInfo;
import ui.viewModel.ViewModel;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.os.SystemClock;
import android.text.InputType;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.mysport.ui.R;
import domain.businessEntity.gps.ClimbData;
import domain.businessEntity.gps.LatLngData;
import domain.businessService.gps.ClimbDataService;
import domain.businessService.gps.IClimbDataService;
import foundation.webservice.GeocodeService;
/**
* @author DreamTeam 沈志鹏
*/
public class GpsObtainActivity extends ActivityOfAF4Ad implements
OnTouchListener, OnGestureListener {
private TextView tv_altitude;// 高度显示控件
private TextView tv_direction;// 方向显示控件
private TextView tv_speed;// 速度显示控件
private TextView tv_longitude;// 经度显示控件
private TextView tv_latitude;// 纬度显示控件
private ImageButton bt_startAndStop;// 开始结束按钮
private Builder builder;
private EditText editor;// 对话框文本输入控件
private LocationManager locManager;// 定义LocationManager对象
private String cliName;// 行程名称
private Chronometer timer;// 定义计时器
private Date startTime;// 记录开始时间
private Date stopTime;// 记录结束时间
private int startAltitude;// 开始海拔
private int stopAltitude;// 结束海拔
private SimpleDateFormat sDateFormat;
boolean flag = false;// 设置开始结束按钮标志
private int currentAltitude;// 获取当前高度
private SensorManager mSensorManager;// 定义SensorManager对象
private double stopLon;// 结束时经度
private double stopLat;// 结束时纬度
private double currentLon;// 当前经度
private double currentLat;// 当前纬度
private IClimbDataService climbDataService;// 定义登山数据服务对象
GestureDetector mGestureDetector = null; // 定义手势监听对象
private int verticalMinDistance = 10; // 最小触摸滑动距离
private int minVelocity = 0; // 最小水平移动速度
private ImageView iv_compass;
private float predegree = 0f;
private ImageView compassNeedle;//指南针
private String city;
private boolean isExit = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
mGestureDetector = new GestureDetector((OnGestureListener) this);
LinearLayout mainlayout = (LinearLayout) findViewById(R.id.gps_main_layout);
mainlayout.setOnTouchListener(this);
mainlayout.setLongClickable(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_obtain_gps, menu);
return true;
}
@Override
protected void initControlsAndRegEvent() {
// 获取相应控件id
bt_startAndStop = (ImageButton) findViewById(R.id.bt_startAndStop);
tv_altitude = (TextView) findViewById(R.id.tv_altitude);
tv_direction = (TextView) findViewById(R.id.tv_direction);
tv_speed = (TextView) findViewById(R.id.tv_speed);
tv_longitude = (TextView) findViewById(R.id.tv_longitude);
tv_latitude = (TextView) findViewById(R.id.tv_latitude);
timer = (Chronometer) findViewById(R.id.timer);
compassNeedle=(ImageView)findViewById(R.id.iv_compassNeedle);
climbDataService = new ClimbDataService();
// 构建对话框输入控件对象
editor = new EditText(this);
builder = new AlertDialog.Builder(this);
// 设置计时器显示格式
timer.setFormat("%s");
if (flag == true) {
bt_startAndStop.setImageDrawable(getResources().getDrawable(
R.drawable.pause));
} else
bt_startAndStop.setImageDrawable(getResources().getDrawable(
R.drawable.play));
// 启动GPS
startGps();
// 获取方向传感器服务
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// 开始和停止按钮监听事件
bt_startAndStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (flag == false) {
builder.setTitle("请输入行程名称");
builder.setView(editor);
RequireAddressAsyncTask asyncTask = new RequireAddressAsyncTask(
editor);
asyncTask.execute();
// 点击自动EditText自动全选
editor.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
editor.selectAll();
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.showSoftInput(v, 0);
return true;
}
});
builder.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
initControlsAndRegEvent();
}
});
// 设置对话框
builder.setPositiveButton("确认", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 获取输入
cliName = editor.getText().toString();
// 计时器重置
timer.setBase(SystemClock.elapsedRealtime());
// 开始计时
timer.start();
// 获取开始时间
startTime = new java.util.Date();
// 记录开始高度值
startAltitude = currentAltitude;
flag = true;
sendStartStatusToGMap();
initControlsAndRegEvent();
}
});
builder.create().show();
} else {
flag = false;
timer.stop();
// 记录结束是时间
stopTime = new java.util.Date();
// 记录结束时高度
stopAltitude = currentAltitude;
// 记录结束是经度
stopLon = currentLon;
// 记录结束是纬度
stopLat = currentLat;
sendStopStatusToGMap();
writeDataToSqlite();
initControlsAndRegEvent();
}
}
});
}
// 发送开始状态广播给GoogleMap
public void sendStartStatusToGMap() {
Intent intent = new Intent();
intent.setAction("status");
intent.putExtra("status", true);
sendBroadcast(intent);
}
// 发送结束状态广播给GoogleMap
public void sendStopStatusToGMap() {
Intent intent = new Intent();
intent.setAction("status");
intent.putExtra("status", false);
sendBroadcast(intent);
}
// 跳转到记录界面
public void toRecActivity() {
toActivity(this, RecordActivity.class);
}
// 开启GPS功能
public void startGps() {
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Location
// location=locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGpsView(location);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000,
8, new LocationListener() {
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
updateGpsView(locManager.getLastKnownLocation(provider));
}
@Override
public void onProviderDisabled(String provider) {
updateGpsView(null);
}
@Override
public void onLocationChanged(Location location) {
updateGpsView(location);
}
});
}
// 动态更新GPS数据
public void updateGpsView(Location newLocation) {
int altitude;
float speed;
double lat;
double lon;
if (newLocation != null) {
currentAltitude = altitude = (int) newLocation.getAltitude();
speed = newLocation.getSpeed();
currentLat = lat = newLocation.getLatitude();
currentLon = lon = newLocation.getLongitude();
sendBroadcastToWeather();
tv_altitude.setText(Integer.toString(altitude));
tv_speed.setText(new DecimalFormat("#0.0").format(speed));
tv_latitude.setText(Double.toString(lat));
tv_longitude.setText(Double.toString(lon));
} else {
tv_altitude.setText("0");
tv_speed.setText("0");
tv_latitude.setText("0");
tv_longitude.setText("0");
}
}
// 设置方向传感器监听类
SensorEventListener mSersorEventListener = new SensorEventListener() {
// 传感器值改变
@Override
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
if (values[0] >= 0 && values[0] < 30)
tv_direction.setText("北");
if (values[0] >= 30 && values[0] < 60)
tv_direction.setText("东北");
if (values[0] >= 60 && values[0] < 120)
tv_direction.setText("东");
if (values[0] >= 120 && values[0] < 150)
tv_direction.setText("东南");
if (values[0] >= 150 && values[0] < 210)
tv_direction.setText("南");
if (values[0] >= 210 && values[0] < 240)
tv_direction.setText("西南");
if (values[0] >= 240 && values[0] < 300)
tv_direction.setText("西");
if (values[0] >= 300 && values[0] < 330)
tv_direction.setText("西北");
if (values[0] >= 300 && values[0] <= 360)
tv_direction.setText("北");
RotateAnimation animation = new RotateAnimation(predegree, -values[0],
Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
animation.setDuration(200);
compassNeedle.startAnimation(animation);
predegree=-values[0];
}
// 传感器精度改变
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
@Override
protected void onResume() {
super.onResume();
// 方向传感器注册监听器
mSensorManager.registerListener(mSersorEventListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStop() {
// 程序停止时注销监听器
mSensorManager.unregisterListener(mSersorEventListener);
super.onStop();
}
@Override
protected void onPause() {
// 程序暂停时注销监听器
mSensorManager.unregisterListener(mSersorEventListener);
super.onStop();
}
// 数据写入数据库操作
public void writeDataToSqlite() {
ClimbData climbData = new ClimbData();
climbData.setClimbName(cliName);
climbData.setLatitude(stopLat);
climbData.setLongitude(stopLon);
climbData.setStartAltitude(startAltitude);
climbData.setStopAltitude(stopAltitude);
climbData.setStartTime(startTime);
climbData.setStopTime(stopTime);
climbDataService.addClimbData(climbData);
}
@Override
protected ViewModel initModel() {
// TODO Auto-generated method stub
return null;
}
@Override
protected void upDateView(ViewModel aVM) {
// TODO Auto-generated method stub
}
@Override
protected void processViewModelErrorMsg(List<ModelErrorInfo> errsOfVM,
String errMsg) {
// TODO Auto-generated method stub
}
@Override
public boolean onDown(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
if (arg0.getX() - arg1.getX() > verticalMinDistance
&& Math.abs(arg2) > minVelocity) {
Intent intent = new Intent(GpsObtainActivity.this,
RecordActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
}
return false;
}
@Override
public void onLongPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onShowPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return mGestureDetector.onTouchEvent(arg1);
}
/**
*
* 使用多线性异步使用访问网络,进行地址反向解析查询
*
*/
class RequireAddressAsyncTask extends AsyncTask<Void, Void, String> {
private EditText editor;
public RequireAddressAsyncTask(EditText editor) {
this.editor = editor;
}
@Override
protected String doInBackground(Void... params) {
String result = null;
result = GeocodeService.getAddressByLatLng(currentLat, currentLon,
1);
return result;
}
@Override
protected void onPostExecute(String result) {
editor.setText(result);
}
}
public void sendBroadcastToWeather(){
Intent intent = new Intent();
intent.setAction("LatLng");
intent.putExtra("Lat", currentLat);
intent.putExtra("Lng", currentLon);
sendBroadcast(intent);
}
}
| 10-myclimb | trunk/MyClimb/src/ui/activity/gps/GpsObtainActivity.java | Java | asf20 | 14,573 |
package ui.activity.GoogleMap;
/**
* @author DreamTeam 郑运春
*/
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_SATELLITE;
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID;
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_NORMAL;
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_TERRAIN;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.mysport.ui.R;
import domain.businessEntity.gps.LatLngData;
import domain.businessService.gps.ILatLngDataService;
import domain.businessService.gps.LatLngDataService;
public class GMapActivity extends FragmentActivity
implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener{
private Polyline mMutablePolyline;
//经纬度
private double latitude;
private double longitude;
private int flag = 0;
private LatLngData data;
private String strTime;
private LocationClient mLocationClient;
private List<String> titles; //标题栏
private List<List<String>> item_names; //选项名称
private List<List<Integer>> item_images; //选项图标
private MyDefinedMenu myMenu; //弹出菜单
private ILatLngDataService latLngDataService = null;
private List<LatLng> points = new ArrayList<LatLng>();
private List<LatLngData> dataList = new ArrayList<LatLngData>();
private boolean status;//监听第一个界面广播过来的开始或结束的状态 true为开始,false为停止
private boolean traffic_status = false;
private GoogleMap mMap;
private UiSettings mUiSettings;
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(50000) // 50 seconds
.setFastestInterval(20) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_googlemap);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapGoogle);
if (savedInstanceState == null) {
// 第一次得到该 activity.
mapFragment.setRetainInstance(true);
} else {
// 当重启该Activity 时候,不需要要在重新实例化 就可以得到之前的activity
mMap = mapFragment.getMap();
}
latLngDataService = new LatLngDataService();
setUpMapIfNeeded();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(29,113),2));
setRecRoute();
initPopupWindow();
}
public void initPopupWindow(){
//弹出菜单标题栏
titles = addItems(new String[]{"图层菜单"});
//选项图标
item_images = new ArrayList<List<Integer>>();
item_images.add(addItems(new Integer[]{R.drawable.pop_normalmap,
R.drawable.pop_earth,R.drawable.pop_terrin, R.drawable.pop_traffic}));
//选项名称
item_names = new ArrayList<List<String>>();
item_names.add(addItems(new String[]{"平面地图", "卫星地图", "地形", "实时路况"}));
//创建弹出菜单对象
myMenu = new MyDefinedMenu(this, titles, item_names,item_images, new ItemClickEventGmap());
}
//菜单选项点击事件
public class ItemClickEventGmap implements OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(arg2 == 0)
mMap.setMapType(MAP_TYPE_NORMAL);
if(arg2 == 1)
mMap.setMapType(MAP_TYPE_SATELLITE);
if(arg2 == 2)
mMap.setMapType(MAP_TYPE_TERRAIN);
if(arg3 == 3){
mMap.setTrafficEnabled(traffic_status);
setUi();
if(traffic_status)
traffic_status = false;
else
traffic_status = true;
}
myMenu.dismiss(); //菜单消失
myMenu.currentState = 1; //标记状态,已消失
}
}
// 转换为List<String>
private List<String> addItems(String[] values) {
List<String> list = new ArrayList<String>();
for (String var : values) {
list.add(var);
}
return list;
}
//转换为List<Integer>
private List<Integer> addItems(Integer[] values) {
List<Integer> list = new ArrayList<Integer>();
for (Integer var : values) {
list.add(var);
}
return list;
}
public boolean onCreateOptionsMenu(){
return false;
}
public boolean onCreateOptionsMenu(Menu menu){
if(0 == myMenu.currentState && myMenu.isShowing()) {
myMenu.dismiss(); //对话框消失
myMenu.currentState = 1; //标记状态,已消失
} else {
myMenu.showAtLocation(findViewById(R.id.mapGoogle), Gravity.BOTTOM, 0,0);
myMenu.currentState = 0; //标记状态,显示中
}
return false; // true--显示系统自带菜单;false--不显示。
}
@Override
public void closeOptionsMenu() {
// TODO Auto-generated method stub
super.closeOptionsMenu();
}
@Override
public void onOptionsMenuClosed(Menu menu) {
// TODO Auto-generated method stub
super.onOptionsMenuClosed(menu);
}
public void setRecRoute(){
//获取由RecDetailsActivity传过来的位置信息
Bundle bundle = getIntent().getExtras();
if(bundle != null)
{
strTime = bundle.getString("time");
dataList = latLngDataService.getLatLngDataByTime(strTime);
Iterator<LatLngData> it = dataList.iterator();
if(!it.hasNext()){
Toast toast = Toast.makeText(this, "当前记录无轨迹!", Toast.LENGTH_SHORT);
toast.show();
return;
}
PolylineOptions RecOptions = new PolylineOptions();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(it.next().getLat(),it.next().getLng()))
.title("开始"));
//LatLngData data;
while(it.hasNext()){
data = it.next();
RecOptions.add(new LatLng(data.getLat(),data.getLng()));
}
mMap.addMarker(new MarkerOptions()
.position(new LatLng(data.getLat(),data.getLng()))
.title("结束"));
mMutablePolyline = mMap.addPolyline(RecOptions
.color(Color.GREEN)
.width(2)
.geodesic(true));
}
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
if (mMap != null) {
setUi();
mMap.setMapType(MAP_TYPE_SATELLITE);
}
status = StatusReceiver.getStatus();
setUpLocationClientIfNeeded();
mLocationClient.connect();
}
@Override
public void onPause() {
super.onPause();
if (mLocationClient != null) {
mLocationClient.disconnect();
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(
getApplicationContext(),
this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
//添加经纬度点
private void addLatLngPoint(double longitude,double latitude){
double lat = latitude;
double lon = longitude;
points.add(new LatLng(lon,lat));
}
private void setUi(){
mUiSettings.setZoomControlsEnabled(true);
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(true);
mMap.setMyLocationEnabled(true);
mUiSettings.setScrollGesturesEnabled(true);
mUiSettings.setZoomGesturesEnabled(true);
mUiSettings.setTiltGesturesEnabled(true);
mUiSettings.setRotateGesturesEnabled(true);
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapGoogle))
.getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mUiSettings = mMap.getUiSettings();
}
private void drawRouteOnMap(){
if(points.size() >= 2)
{
PolylineOptions options = new PolylineOptions();
options.addAll(points);
mMutablePolyline = mMap.addPolyline(options
.color(Color.RED)
.width(2)
.geodesic(true));
}
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(status){
latitude = location.getLatitude();
longitude = location.getLongitude();
if(flag == 0 ){
mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude,longitude))
.title("开始"));
flag = 1;
}
addLatLngPoint(latitude,longitude);
//划线
drawRouteOnMap();
//将记录下的点存入数据库
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
String time = sf.format(new java.util.Date());
LatLngData data = new LatLngData();
data.setLat(latitude);
data.setLng(longitude);
data.setStartTime(time);
latLngDataService.addLatLngData(data);
}else{
if(flag == 1){
mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude,longitude))
.title("结束"));
flag = 2;
}
}
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub0
}
@Override
public void onConnected(Bundle connectionHint) {
mLocationClient.requestLocationUpdates(
REQUEST,
this); // LocationListener
}
@Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
}
| 10-myclimb | trunk/MyClimb/src/ui/activity/GoogleMap/GMapActivity.java | Java | asf20 | 11,715 |
package ui.activity.GoogleMap;
import java.util.List;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
/**
*
* @author DreamTeam 郑运春
*
*/
public class TitleAdatper extends BaseAdapter {
private List<String> titles;
private Context context;
private final TextView[] tv_titels;
public TitleAdatper(Context context, List<String> titles) {
this.context = context;
this.titles = titles;
tv_titels = new TextView[titles.size()];
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return titles.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public void setFocus(int position) {
for (int i = 0; i < titles.size(); i++) {
tv_titels[i].setBackgroundColor(Color.WHITE);
}
tv_titels[position].setBackgroundColor(Color.BLUE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
tv_titels[position] = new TextView(context);
tv_titels[position].setGravity(Gravity.CENTER);
tv_titels[position].setText(titles.get(position));
tv_titels[position].setTextSize(18);
tv_titels[position].setLayoutParams(new GridView.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
return tv_titels[position];
}
}
| 10-myclimb | trunk/MyClimb/src/ui/activity/GoogleMap/TitleAdatper.java | Java | asf20 | 1,743 |
package ui.activity.GoogleMap;
/**
* @author DreamTeam 郑运春
*/
import java.util.List;
import ui.activity.GoogleMap.GMapActivity.ItemClickEventGmap;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;
public class MyDefinedMenu extends PopupWindow {
private LinearLayout layout;
private GridView gv_title;
private GridView gv_body;
private BodyAdatper[] bodyAdapter;
private TitleAdatper titleAdapter;
private Context context;
private int titleIndex;
public int currentState;
public MyDefinedMenu(Context context, List<String> titles,
List<List<String>> item_names, List<List<Integer>> item_images,
ItemClickEventGmap itemClickEvent) {
super(context);
this.context = context;
currentState = 1;
layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
titleIndex = 0;
gv_title = new GridView(context);
titleAdapter = new TitleAdatper(context, titles);
gv_title.setAdapter(titleAdapter);
gv_title.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
gv_title.setNumColumns(titles.size());
//gv_title.setBackgroundColor(Color.WHITE);
gv_title.setBackgroundColor(Color.GRAY);
bodyAdapter = new BodyAdatper[item_names.size()];
for (int i = 0; i < item_names.size(); i++) {
bodyAdapter[i] = new BodyAdatper(context, item_names.get(i), item_images.get(i));
}
gv_body = new GridView(context);
gv_body.setNumColumns(4);
//设置背景为半透明
//gv_body.setBackgroundColor(Color.TRANSPARENT);
gv_body.setBackgroundColor(Color.WHITE);
gv_body.setAdapter(bodyAdapter[0]);
gv_title.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
titleIndex = arg2;
titleAdapter.setFocus(arg2);
gv_body.setAdapter(bodyAdapter[arg2]);
}
});
gv_body.setOnItemClickListener(itemClickEvent);
layout.addView(gv_title);
layout.addView(gv_body);
this.setContentView(layout);
this.setWidth(LayoutParams.FILL_PARENT);
this.setHeight(LayoutParams.WRAP_CONTENT);
this.setFocusable(true);
}
public int getTitleIndex() {
return titleIndex;
}
}
| 10-myclimb | trunk/MyClimb/src/ui/activity/GoogleMap/MyDefinedMenu.java | Java | asf20 | 2,790 |
package ui.activity.GoogleMap;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class StatusReceiver extends BroadcastReceiver {
private static boolean status;
@Override
public void onReceive(Context context, Intent intent) {
status = intent.getExtras().getBoolean("status");
}
public static boolean getStatus(){
return status;
}
}
| 10-myclimb | trunk/MyClimb/src/ui/activity/GoogleMap/StatusReceiver.java | Java | asf20 | 461 |
package ui.activity.GoogleMap;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Locale;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.CameraPosition;
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.mysport.ui.R;
import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_TERRAIN;
public class GoogleMapActivity extends FragmentActivity {
private GoogleMap mMap;
private UiSettings mUiSettings;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_googlemap);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mMap.setMapType(MAP_TYPE_TERRAIN);
mMap.setMyLocationEnabled(true);
mUiSettings=mMap.getUiSettings();
//设置地图显示指南针
mUiSettings.setCompassEnabled(true);
//倾斜手势操作
mUiSettings.setTiltGesturesEnabled(true);
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapGoogle))
.getMap();
}
}
}
| 10-myclimb | trunk/MyClimb/src/ui/activity/GoogleMap/GoogleMapActivity.java | Java | asf20 | 2,001 |
package ui.activity.GoogleMap;
import java.util.List;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* @author Dreamteam 郑运春
*/
public class BodyAdatper extends BaseAdapter {
private List<String> item_names;
private List<Integer> item_images;
private Context context;
public BodyAdatper(Context context, List<String> item_names,
List<Integer> item_images) {
this.context = context;
this.item_names = item_names;
this.item_images = item_images;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return item_images.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(Gravity.CENTER);
TextView tv_item = new TextView(context);
tv_item.setGravity(Gravity.CENTER);
tv_item.setLayoutParams(new GridView.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tv_item.setText(item_names.get(position));
ImageView img_item = new ImageView(context);
img_item.setLayoutParams(new LayoutParams(50, 50));
img_item.setImageResource(item_images.get(position));
layout.addView(img_item);
layout.addView(tv_item);
return layout;
}
}
| 10-myclimb | trunk/MyClimb/src/ui/activity/GoogleMap/BodyAdatper.java | Java | asf20 | 1,873 |
package ui.activity;
import java.util.List;
import ui.viewModel.IOnViewModelUpated;
import ui.viewModel.ModelErrorInfo;
import ui.viewModel.ViewModel;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import app.MyApplication;
import com.mysport.ui.*;
/**
*
* @author 福建师范大学软件学院 倪友聪、赵康
*
*/
public abstract class ActivityOfAF4Ad extends Activity {
// tag标记,用于输出调试信息
static String tag = "MyApplication";
// 视图模型
protected ViewModel vm;
public ViewModel getVm() {
return vm;
}
public void setVm(ViewModel aVM) {
if (this.vm != aVM) {
this.vm = aVM;
// 触发视图模型更新事件
if (vm != null) {
vm.fireOnUpdted();
}
}
}
// 视图模型更新的监听器
private OnViewModelUpdated listener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 加载视图
setContentView(R.layout.activity_af4ad);
// 初始化视图模型
this.vm = null;
// 考虑Activity跳转时,获取从MyApplication转发过来的ViewModel
Bundle bundle = this.getIntent().getExtras();
if (bundle != null) {
this.vm = ViewModel.readFromBundle(bundle);
}
// 构造监听器
setListener(new OnViewModelUpdated());
Log.d(tag, "in OnCreate...");
}
@Override
protected void onPostCreate(android.os.Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
Log.d(tag, "in onPostCreate...");
// 获取初始视图模型
if (vm == null) {
vm = initModel();
}
Log.d(tag, "vm intialized...");
// 获取操作控件并注册控件事件
initControlsAndRegEvent();
Log.d(tag, "controls obtained....");
// 注册视图模型的监听者
if (vm != null) {
int position = vm.findListener(getListener());
Log.d(tag, "finding listener...");
// 是否已加入过
if (position == -1) {
// 注册视图模型的监听者
vm.addListener(getListener());
Log.d(tag, "listener added");
}
}
// 更新视图
if (vm != null) {
upDateView(vm);
}
}
@Override
protected void onDestroy() {
if (vm != null) {
int position = vm.findListener(getListener());
if (position > -1) {
vm.removeListener(getListener());
}
}
super.onDestroy();
}
// 获取操作控件并注册控件事件
protected abstract void initControlsAndRegEvent();
// 获取初始的视图模型
protected abstract ViewModel initModel();
// 更新视图
protected abstract void upDateView(ViewModel aVM);
/**
* 处理视图模型错误
* @param errsOfVM:第一个参数给出了出错的属性名和出错消息,
* @param errMsg:按每个属性出错误一行的格式给出错误消息
*/
protected abstract void processViewModelErrorMsg(
List<ModelErrorInfo> errsOfVM, String errMsg);
/**
* 视图模型更新的监听器类
**/
/**
*
* @author 福建师范大学软件学院 倪友聪、赵康
*
*/
private class OnViewModelUpdated implements IOnViewModelUpated {
@Override
// 视图模型更新后的回调方法
public void onUpdated(ViewModel vm) {
upDateView(vm);
}
@Override
// 发现视图模型错误时的回调方法
public void onViewModelInError(List<ModelErrorInfo> errsOfVM) {
String errTxt = "";
for (int i = 0; i < errsOfVM.size(); i++) {
errTxt += errsOfVM.get(i).getErrMsg() + "\n";
}
//调用子类的处理视图模型错误方法
processViewModelErrorMsg(errsOfVM, errTxt);
}
}
/**
* 跳转至其它Activity
* @param frmActObj:源Activity对象
* @param toActCls:目标Activity类的描述对象可用ActivityX.class
*/
protected void toActivity(Activity frmActObj, Class<?> toActCls) {
//设定Activity跳转广播
Intent toAppIntent = new Intent("ViewForwardBroadcast");
String frmActClsName=frmActObj.getClass().getName();
String toActClsName=toActCls.getName();
toAppIntent.putExtra("frmActClsNm", frmActClsName);
toAppIntent.putExtra("toActClsNm", toActClsName);
//将源Activity的ViewMode打包
if (this.vm != null) {
Bundle bdlOfFrmAct = new Bundle();
bdlOfFrmAct = vm.writeToBundle();
toAppIntent.putExtras(bdlOfFrmAct);
}
//设定接收广播对象
IntentFilter filter = new IntentFilter("ViewForwardBroadcast");
registerReceiver(MyApplication.VWFWDRCV, filter);
//发送广播
sendBroadcast(toAppIntent);
}
public OnViewModelUpdated getListener() {
return listener;
}
public void setListener(OnViewModelUpdated listener) {
this.listener = listener;
}
}
| 10-myclimb | trunk/MyClimb/src/ui/activity/ActivityOfAF4Ad.java | Java | asf20 | 4,878 |
package ui.activity.weather;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.ksoap2.serialization.SoapObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.GestureDetector.OnGestureListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.mysport.ui.R;
import foundation.webservice.GeocodeService;
import foundation.webservice.WeatherService;
import tool.SunriseSunset.SunriseSunset;
import ui.activity.ActivityOfAF4Ad;
import ui.viewModel.ModelErrorInfo;
import ui.viewModel.ViewModel;
public class WeatherActivity extends ActivityOfAF4Ad {
private ImageView todayWhIcon = null;
private TextView tv_todaydate = null;
private TextView tv_currentTemperature = null;
private TextView tv_today_Temp = null;
private TextView tv_today_windspeed = null;
private ImageView tomorrowWhIcon = null;
private TextView tv_tomorrowdate = null;
private TextView tv_tomorrow_Temp = null;
private TextView tv_tomorrow_windspeed = null;
private TextView today_sunrisetime = null;//
private TextView today_sunsettime = null;//
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
SunriseAndSetAsyncTask calculate = new SunriseAndSetAsyncTask();
RequireWeatherAsyncTask require = new RequireWeatherAsyncTask();
require.execute();
calculate.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_weather, menu);
return true;
}
@Override
protected void initControlsAndRegEvent() {
todayWhIcon = (ImageView) findViewById(R.id.todayWhIcon);
tv_todaydate = (TextView) findViewById(R.id.tv_todaydate);
tv_currentTemperature = (TextView) findViewById(R.id.tv_currentTemperature);
tv_today_Temp = (TextView) findViewById(R.id.tv_today_Temp);
tv_today_windspeed = (TextView) findViewById(R.id.tv_today_windspeed);
tomorrowWhIcon = (ImageView) findViewById(R.id.tomorrowWhIcon);
tv_tomorrowdate = (TextView) findViewById(R.id.tv_tomorrowdate);
// tv_currentTemperature = (TextView)
// findViewById(R.id.tv_currentTemperature);
// tv_tomorrow_Temp = (TextView) findViewById(R.id.tv_tomorrow_Temp);
tv_tomorrow_windspeed = (TextView) findViewById(R.id.tv_tomorrow_windspeed);
tv_tomorrow_Temp = (TextView) findViewById(R.id.tv_tomorrow_Temp);
today_sunrisetime = (TextView) findViewById(R.id.today_sunrisetime);
today_sunsettime = (TextView) findViewById(R.id.today_sunsettime);
}
@Override
protected ViewModel initModel() {
// TODO Auto-generated method stub
return null;
}
@Override
protected void upDateView(ViewModel aVM) {
// TODO Auto-generated method stub
}
@Override
protected void processViewModelErrorMsg(List<ModelErrorInfo> errsOfVM,
String errMsg) {
// TODO Auto-generated method stub
}
// 多线程实现天气查询
class RequireWeatherAsyncTask extends AsyncTask<Void, Void, SoapObject> {
@Override
protected SoapObject doInBackground(Void... arg0) {
String city;
city = GeocodeService.getAddressByLatLng(LatLngReceiver.getLat(),
LatLngReceiver.getLng(), 2);
return WeatherService.getWeatherByCity(city);
}
@Override
protected void onPostExecute(SoapObject detail) {
// TODO Auto-generated method stub
showWeather(detail);
}
}
private void showWeather(SoapObject detail) {
if (detail == null) {
initModel();
return;
}
String weatherToday = null;
String weatherTomorrow = null;
String weatherCurrent = null;
int iconToday;
int iconTomorrow;
// int iconAfterday[] = new int[2];
// 获取天气实况
weatherCurrent = detail.getProperty(4).toString().substring(10, 13);
tv_currentTemperature.setText(weatherCurrent);
// 解析今天的天气情况
String date = detail.getProperty(7).toString();
weatherToday = "今天:" + date.split(" ")[0];
weatherToday = weatherToday + " " + date.split(" ")[1];
tv_todaydate.setText(weatherToday);
weatherToday = detail.getProperty(8).toString();// 今日气温范围
tv_today_Temp.setText(weatherToday);
weatherToday = detail.getProperty(9).toString();
tv_today_windspeed.setText(weatherToday);
iconToday = parseIcon(detail.getProperty(10).toString());
todayWhIcon.setImageResource(iconToday);
// iconToday[1] = parseIcon(detail.getProperty(11).toString());
// 解析明天的天气情况
date = detail.getProperty(12).toString();
weatherTomorrow = "明天:" + date.split(" ")[0];
weatherTomorrow = weatherTomorrow + " " + date.split(" ")[1];
tv_tomorrowdate.setText(weatherTomorrow);
weatherTomorrow = detail.getProperty(13).toString();
tv_tomorrow_Temp.setText(weatherTomorrow);
weatherTomorrow = detail.getProperty(14).toString();
tv_tomorrow_windspeed.setText(weatherTomorrow);
iconTomorrow = parseIcon(detail.getProperty(15).toString());
tomorrowWhIcon.setImageResource(iconTomorrow);
// iconTomorrow[1] = parseIcon(detail.getProperty(16).toString());
}
// 工具方法,该方法负责把返回的天气图标字符串。转换为程序的图片资源ID
private int parseIcon(String strIcon) {
// TODO 自动生成的方法存根
// 根据字符串解析天气图标的代码
if (strIcon == null)
return -1;
if ("0.gif".equals(strIcon))
return R.drawable.a_0;
if ("1.gif".equals(strIcon))
return R.drawable.a_1;
if ("2.gif".equals(strIcon))
return R.drawable.a_2;
if ("3.gif".equals(strIcon))
return R.drawable.a_3;
if ("4.gif".equals(strIcon))
return R.drawable.a_4;
if ("5.gif".equals(strIcon))
return R.drawable.a_5;
if ("6.gif".equals(strIcon))
return R.drawable.a_6;
if ("7.gif".equals(strIcon))
return R.drawable.a_7;
if ("8.gif".equals(strIcon))
return R.drawable.a_8;
if ("9.gif".equals(strIcon))
return R.drawable.a_9;
if ("10.gif".equals(strIcon))
return R.drawable.a_10;
if ("11.gif".equals(strIcon))
return R.drawable.a_11;
if ("12.gif".equals(strIcon))
return R.drawable.a_12;
if ("13.gif".equals(strIcon))
return R.drawable.a_13;
if ("14.gif".equals(strIcon))
return R.drawable.a_14;
if ("15.gif".equals(strIcon))
return R.drawable.a_15;
if ("16.gif".equals(strIcon))
return R.drawable.a_16;
if ("17.gif".equals(strIcon))
return R.drawable.a_17;
if ("18.gif".equals(strIcon))
return R.drawable.a_18;
if ("19.gif".equals(strIcon))
return R.drawable.a_19;
if ("20.gif".equals(strIcon))
return R.drawable.a_20;
if ("21.gif".equals(strIcon))
return R.drawable.a_21;
if ("22.gif".equals(strIcon))
return R.drawable.a_22;
if ("23.gif".equals(strIcon))
return R.drawable.a_23;
if ("24.gif".equals(strIcon))
return R.drawable.a_24;
if ("25.gif".equals(strIcon))
return R.drawable.a_25;
if ("26.gif".equals(strIcon))
return R.drawable.a_26;
if ("27.gif".equals(strIcon))
return R.drawable.a_27;
if ("28.gif".equals(strIcon))
return R.drawable.a_28;
if ("29.gif".equals(strIcon))
return R.drawable.a_29;
if ("30.gif".equals(strIcon))
return R.drawable.a_30;
if ("31.gif".equals(strIcon))
return R.drawable.a_31;
return 0;
}
class SunriseAndSetAsyncTask extends AsyncTask<Void,Void,Date[]>{
private double lat;
private double lng;
@Override
protected Date[] doInBackground(Void... params) {
lat = LatLngReceiver.getLat();
lng = LatLngReceiver.getLng();
Date now = new Date();
Date[] riseSet = new Date[2];
SunriseSunset sunriseSunset = new SunriseSunset(lat, lng, now, 0);
riseSet[0]=sunriseSunset.getSunrise();
riseSet[1]=sunriseSunset.getSunset();
return riseSet;
}
@Override
protected void onPostExecute(Date[] result) {
SimpleDateFormat sf = new SimpleDateFormat("hh:mm:ss");
today_sunrisetime.setText(sf.format(result[0]));
today_sunsettime.setText(sf.format(result[1]));
}
}
}
| 10-myclimb | trunk/MyClimb/src/ui/activity/weather/WeatherActivity.java | Java | asf20 | 8,290 |
package ui.activity.weather;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class LatLngReceiver extends BroadcastReceiver {
private static double lat;
private static double lng;
@Override
public void onReceive(Context context, Intent intent) {
lat = intent.getExtras().getDouble("Lat");
lng = intent.getExtras().getDouble("Lng");
}
public static double getLat(){
return lat;
}
public static double getLng(){
return lng;
}
}
| 10-myclimb | trunk/MyClimb/src/ui/activity/weather/LatLngReceiver.java | Java | asf20 | 535 |
package ui.activity.app;
import com.mysport.ui.R;
import com.mysport.ui.R.layout;
import com.mysport.ui.R.menu;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
//该Activity为测试用,可刪去
public class DefaultActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_default);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_default, menu);
return true;
}
}
| 10-myclimb | trunk/MyClimb/src/ui/activity/app/DefaultActivity.java | Java | asf20 | 678 |
package ui.viewModel;
import java.util.List;
/**
*
* @author 福建师范大学软件学院 倪友聪、赵康
*
*/
public interface IOnViewModelUpated {
//视图模型更新后的回调方法
public void onUpdated(ViewModel vm);
//发现视图模型错误时的回调方法
public void onViewModelInError(List<ModelErrorInfo> errsOfVM);
}
| 10-myclimb | trunk/MyClimb/src/ui/viewModel/IOnViewModelUpated.java | Java | asf20 | 376 |
package ui.viewModel.gps;
import java.util.Date;
import java.util.List;
import ui.viewModel.ModelErrorInfo;
import ui.viewModel.ViewModel;
public class RecordViewModel extends ViewModel {
private String ClimbName;
private Date starTime;
public String getClimbName() {
return ClimbName;
}
public void setClimbName(String climbName) {
ClimbName = climbName;
}
public Date getStarTime() {
return starTime;
}
public void setStarTime(Date starTime) {
this.starTime = starTime;
}
@Override
public List<ModelErrorInfo> verifyModel() {
// TODO Auto-generated method stub
return null;
}
}
| 10-myclimb | trunk/MyClimb/src/ui/viewModel/gps/RecordViewModel.java | Java | asf20 | 642 |
package ui.viewModel.gps;
import java.util.Date;
import java.util.List;
import domain.businessEntity.gps.ClimbData;
import ui.viewModel.ModelErrorInfo;
import ui.viewModel.ViewModel;
public class RecDetailViewModel extends ViewModel {
private String ClimbName;
private int startAltitude;
private int stopAltitude;
private Date startTime;
private Date stopTime;
private String longitude;
private String latitude;
private ClimbData climbdata;
public ClimbData getClimbdata() {
return climbdata;
}
public void setClimbdata(ClimbData climbdata) {
this.climbdata = climbdata;
}
public int getStartAltitude() {
return startAltitude;
}
public void setStartAltitude(int startAltitude) {
this.startAltitude = startAltitude;
}
public int getStopAltitude() {
return stopAltitude;
}
public void setStopAltitude(int stopAltitude) {
this.stopAltitude = stopAltitude;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getStopTime() {
return stopTime;
}
public void setStopTime(Date stopTime) {
this.stopTime = stopTime;
}
public String getClimbName() {
return ClimbName;
}
public void setClimbName(String climbName) {
ClimbName = climbName;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
@Override
public List<ModelErrorInfo> verifyModel() {
// TODO Auto-generated method stub
return null;
}
}
| 10-myclimb | trunk/MyClimb/src/ui/viewModel/gps/RecDetailViewModel.java | Java | asf20 | 1,733 |
package ui.viewModel.attributeReflection;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author 福建师范大学软件学院 倪友聪、赵康
*
*/
public class AttributeReflection {
/**
* Android平台下可以直接打包的类(int,char等可直接打包,如发现遗漏可以再添加)
*/
static String[] CANPARCELABLECALSSNAMES = { "java.lang.String",
"java.util.Date", "Integer", "Float", "Boolean", "Double",
"Character", "Byte", "Short", "Long" };
/**
* 目前只考虑集合类List,后期可再添加其它集合类
*/
static String[] CANPROCESSSETNAMES = { "java.util.List" };
public enum FieldKind {
/**
* 可直接打包的原子类型(其包括CANPARCELABLECALSSNAMES中的类和 Java中的原子类型如int,char等)的属性
*/
ParcelableAtomicField,
/**
* 可直接打包的集合类型(目前仅考虑List)的属性 如List<int>或List<String>
*/
ParcelableCollectionField,
/**
* 不可直接打包的集合类型(目前仅考虑List)的属性
*
*/
CantParceCollectionField,
/**
* 用户自定义类型的属性,不可直接打包
*
*/
ClassUserDefinedField;
}
/**
* 根据给定的对象获取该对象所有属性名称、类型和值, 并存放在AttInfo列表中
*
* @param obj
* :输入的任意一个对象
* @return:输入对象的属性信息列表,空对象则返回null
* @throws ClassNotFoundException
* :该对象对应类定义未发现
* @throws IllegalArgumentException
* :参数异常
* @throws IllegalAccessException
* :私有属性不允许访问
* @throws InstantiationException
* :实例化对象异常
*/
public static List<AttInfo> getAttInfosFromObject(Object obj)
throws ClassNotFoundException, IllegalArgumentException,
IllegalAccessException, InstantiationException {
List<AttInfo> attInfos = null;
if (obj == null)
return attInfos;
Class<?> aClass = Class.forName(obj.getClass().getName());
Field[] flds = aClass.getDeclaredFields();
int len = flds.length;
attInfos = new ArrayList<AttInfo>();
// 根据对象类中每个属性
for (int i = 0; i < len; i++) {
Field fld = flds[i];
fld.setAccessible(true);
String attName = fld.getName();
String typeName = fld.getType().getName();
AttInfo info = new AttInfo();
info.setAttName(attName);
info.setTypeName(typeName);
Object value = fld.get(obj);
FieldKind fldKind = getFieldKind(fld);
// 可打包原子类型或是可打包的集合List类型的属性
if (fldKind == FieldKind.ParcelableAtomicField
|| fldKind == FieldKind.ParcelableCollectionField) {
info.setValue(value);
info.setComplexAtt(null);
} else {
if (fldKind == FieldKind.ClassUserDefinedField) {
// 用户自定义类
info.setValue(null);
// 自定义类中所有子对象的属性信息存放在AttInfosOfDefinedClass
List<AttInfo> AttInfosOfDefinedClass = getAttInfosFromObject(value);
info.setComplexAtt(AttInfosOfDefinedClass);
} else {
info.setValue(null);
List<AttInfo> attInfosInSet = getAttInfosFromCantParceSetField(
fld, value);
info.setComplexAtt(attInfosInSet);
}
}
attInfos.add(info);
}
return attInfos;
}
/**
* 类名和属性信息列表中,构建出对象
*
* @param className
* :类名
* @param attInfos
* :类对象所对应的属性信息
* @return:根据属性信息构造出的对象
* @throws ClassNotFoundException
* :类名对应的类未发现
* @throws InstantiationException
* :实例化异常
* @throws IllegalAccessException
* :私有属性不允许访问
* @throws NoSuchFieldException
* :属性找不到
*/
public static Object getOjectFromAttInfos(String className,
List<AttInfo> attInfos) throws ClassNotFoundException,
InstantiationException, IllegalAccessException,
NoSuchFieldException {
Object obj = null;
if (className == null || attInfos == null) {
return obj;
}
Class<?> cls = Class.forName(className);
obj = cls.newInstance();
int len = attInfos.size();
Class<?> cls2 = obj.getClass();
for (int i = 0; i < len; i++) {
AttInfo att = attInfos.get(i);
String attName = att.getAttName();
String typeName = att.getTypeName();
Object value = att.getValue();
Field fld = cls2.getDeclaredField(attName);
fld.setAccessible(true);
if (value != null) {// 可直接打包类型
fld.set(obj, value);
} else {// 是集合类型或自定义类型
boolean isCollectionType = false;
for (String name : CANPROCESSSETNAMES) {
if (typeName.equals(name)) {
isCollectionType = true;
}
}
if (isCollectionType) {// 是集合类型
List<Object> subObjs = getSubObjectsFormListField(att);
fld.set(obj, subObjs);
} else {// 是自定类型
Object subObj = getOjectFromAttInfos(typeName,
att.getComplexAtt());
fld.set(obj, subObj);
}
}
}
return obj;
}
/**
* 判断一个类的属性Field,在Android下是否可直接打包, 目前只考虑基本类型、自定义类型和List集合三种属性Field
*
* @param Field
* :属性
* @return true:是可直接打包的Field,false:不可直接打包的Field
*/
private static boolean isParcelableBasicTypeField(final Field fld) {
boolean result = false;
Class<?> fldType = fld.getType();
String fldTypeName = fldType.getName();
if (fldType.isPrimitive()) {// 是否是基本类型
result = true;
} else {// 是否是可直接打包类型
for (String typeName : CANPARCELABLECALSSNAMES) {
if (fldTypeName.equals(typeName)) {
result = true;
break;
}
}
}
return result;
}
/**
*
* @param fld
* :属性
* @return:属性的种类(可直接打包的原子类型属性ParcelableAtomicField、
* 不可直接打包的集合类型属性CantParceCollectionField
* 、
* 可直接打包的集合类型属性ParcelableCollectionField
* 、 用户自定义类型的属性
* @throws ClassNotFoundException
* :fld对应类未发现
*/
private static FieldKind getFieldKind(Field fld)
throws ClassNotFoundException {
FieldKind kind = FieldKind.CantParceCollectionField;
boolean isCollectionType = false;
String fldTypeName = fld.getType().getName();
// 判断是否是集合类型
for (String name : CANPROCESSSETNAMES) {
if (fldTypeName.equals(name)) {
isCollectionType = true;
}
}
// 是否集合类型,则判定其kind
if (isCollectionType) {
// 得到参数类名(List<T>中T的名字)
Type fldGenericType = fld.getGenericType();
String parameterizedTypeName = "";
Type[] types = ((ParameterizedType) fldGenericType)
.getActualTypeArguments();
String str = types[0].toString();
int len = str.length();
parameterizedTypeName = str.substring(6, len);
// 获取参数类的属性
Class<?> typeClss;
typeClss = Class.forName(parameterizedTypeName);
Field[] flds = typeClss.getDeclaredFields();
// 判断List<T>中T是不是基本类型,并进一步判断T是否可直接打包,
// 如可则List<T>也可直接打包
if (flds.length == 1) {
if (isParcelableBasicTypeField(flds[0])) {
kind = FieldKind.ParcelableCollectionField;
}
}
} else {// 不考虑其它情况,只剩下基本类型和自定义类型
if (isParcelableBasicTypeField(fld)) {
kind = FieldKind.ParcelableAtomicField;
} else {
kind = FieldKind.ClassUserDefinedField;
}
}
return kind;
}
/**
*
* @param listfld
* :List类型属性
* @param value
* :该属性的值
* @return:该属性下的所有子对象的属性信息列表
* @throws ClassNotFoundException
* :找不到子对象对应的类
* @throws InstantiationException
* :实例化子对象
* @throws IllegalAccessException
* :访问属性异常
*/
public static List<AttInfo> getAttInfosFromCantParceSetField(Field listfld,
Object value) throws ClassNotFoundException,
InstantiationException, IllegalAccessException {
// 不可打包的集合类型
List<AttInfo> AttInfosInSetField = null;
if (value == null) {
return AttInfosInSetField;
}
// 获取参数类的名称
Type fldGenericType = listfld.getGenericType();
String parameterizedTypeName = "";
Type[] types = ((ParameterizedType) fldGenericType)
.getActualTypeArguments();
String str = types[0].toString();
int len2 = str.length();
parameterizedTypeName = str.substring(6, len2);
Class<?> ParameterizedClass = Class.forName(parameterizedTypeName);
List<Object> subObjs = (List<Object>) value;
int numOfSubOj = subObjs.size();
AttInfosInSetField = new ArrayList<AttInfo>();
// 对每个子对象进行递归
for (int k = 0; k < numOfSubOj; k++) {
Object subObj = ParameterizedClass.newInstance();
subObj = subObjs.get(k);
// 一个子象中的属性信息
AttInfo subAttInfo = new AttInfo();
subAttInfo.setAttName(Integer.toString(k));
subAttInfo.setTypeName(parameterizedTypeName);
subAttInfo.setValue(null);
List<AttInfo> AttInfosInSubOject = getAttInfosFromObject(subObj);
subAttInfo.setComplexAtt(AttInfosInSubOject);
AttInfosInSetField.add(subAttInfo);
}
return AttInfosInSetField;
}
public static List<Object> getSubObjectsFormListField(AttInfo att)
throws ClassNotFoundException, InstantiationException,
IllegalAccessException, NoSuchFieldException {
List<Object> subObjs = null;
List<AttInfo> subAttInfos = att.getComplexAtt();
if (subAttInfos == null) {
return subObjs;
}
int numOfSubObjs = subAttInfos.size();
if (numOfSubObjs >= 1) {
subObjs = new ArrayList<Object>();
}
for (int j = 0; j < numOfSubObjs; j++) {
String subClassName = subAttInfos.get(j).getTypeName();
List<AttInfo> AttInfosInThisSubObj = subAttInfos.get(j)
.getComplexAtt();
Object subObj = getOjectFromAttInfos(subClassName,
AttInfosInThisSubObj);
subObjs.add(subObj);
}
return subObjs;
}
}
| 10-myclimb | trunk/MyClimb/src/ui/viewModel/attributeReflection/AttributeReflection.java | Java | asf20 | 10,901 |
package ui.viewModel.attributeReflection;
import java.util.List;
import android.os.Parcel;
import android.os.Parcelable;
/**
*
* @author 福建师范大学软件学院 倪友聪、赵康
*
*/
public class AttInfo implements Parcelable {
// 属性名
private String attName;
// 属性的类型名
private String typeName;
// 属性值,如属性是Android下不可直接打包的类,则此值为空
private Object value;
// 属性信息列表,仅在属性的类型为不可直接打包类时使用
private List<AttInfo> complexAtt;
public String getAttName() {
return attName;
}
public void setAttName(String attName) {
this.attName = attName;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public List<AttInfo> getComplexAtt() {
return complexAtt;
}
public void setComplexAtt(List<AttInfo> complexAtt) {
this.complexAtt = complexAtt;
}
/**
* 将属性信息对象写到Parcel中,实现Parcelable接口中方法
*/
@Override
public int describeContents() {
return 0;
}
/**
* 实现Parcelable接口中Parcel的构造类
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(attName);
dest.writeString(typeName);
if (complexAtt == null) {
dest.writeValue(value);
} else {
dest.writeValue(null);
int len = complexAtt.size();
for (int i = 0; i < len; i++) {
AttInfo subAtt = complexAtt.get(i);
subAtt.writeToParcel(dest, flags);
}
}
}
/**
* 实现Parcelable接口中Parcel的构造类
*/
public static final Parcelable.Creator<AttInfo> CREATOR
= new Parcelable.Creator<AttInfo>() {
// 从Parcel中构造出属性信息对象
public AttInfo createFromParcel(Parcel in) {
AttInfo attInfo = new AttInfo();
attInfo.attName = in.readString();
attInfo.typeName = in.readString();
attInfo.value = in.readValue(null);
if (attInfo.value != null) {// 简单属性
attInfo.complexAtt = null;
} else {// 含子属性列表
Parcel subParcel = (Parcel) in.readValue(null);
createFromParcel(subParcel);
}
return attInfo;
}
/**
* 生成属性信息对象数组,实现Parcelable接口中方法
*/
public AttInfo[] newArray(int size) {
return new AttInfo[size];
}
};
}
| 10-myclimb | trunk/MyClimb/src/ui/viewModel/attributeReflection/AttInfo.java | Java | asf20 | 2,557 |
package ui.viewModel;
import java.util.ArrayList;
import java.util.List;
import ui.viewModel.attributeReflection.AttInfo;
import ui.viewModel.attributeReflection.AttributeReflection;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
/**
*
* @author 福建师范大学软件学院 倪友聪、赵康
*
*/
public abstract class ViewModel {
static String tag = "ViewModel";
/**
* 定义两个常量用ViewModel对象打包使用 CLASSNAME表示类名,FIELDLIST属性列表
*/
public static String CLASSNAME = "ClassName";
public static String FIELDLIST = "FieldList";
// 监听者列表
List<IOnViewModelUpated> listeners = null;
// 触发视图模型更新事件
public void fireOnUpdted() {
List<ModelErrorInfo> errs = verifyModel();
// 检验视图模型是否正确
if (errs == null) {//视图模型正确
// 回调每一个监听者的onUpdated方法
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onUpdated(this);
}
} else {//视图模型不正确;
// 回调每一个监听者的onViewModelInError方法
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onViewModelInError(errs);
}
}
}
/*
*检验模型,将出错属性及对应的错误消息构造ModelErrorInfo对象, 形成列表返回, 如果模型正确则返回null
*/
public abstract List<ModelErrorInfo> verifyModel();
// 增加一个监听者
public void addListener(IOnViewModelUpated aListener) {
listeners.add(aListener);
}
// 删除一个监听者
public Boolean removeListener(IOnViewModelUpated aListener) {
return listeners.remove(aListener);
}
// 查找一个监听者
public int findListener(IOnViewModelUpated aListener) {
return listeners.indexOf(aListener);
}
public ViewModel() {
this.listeners = new ArrayList<IOnViewModelUpated>();
}
/**
* 将ViewMode对象的每个属性,形成attInfo对象(可能含子对象), 写入Bundle进行保存
*
* @return: 返回ViewModel对象的打包,异常时返回null
*/
public Bundle writeToBundle() {
Bundle bdl = null;
List<AttInfo> attInfos = null;
try {
// 获取ViewModel对象对应的属性信息列表
attInfos = AttributeReflection.getAttInfosFromObject(this);
if (attInfos == null) {
return bdl;
}
int len = attInfos.size();
if (len > 0) {
bdl = new Bundle();
AttInfo[] arrayOfAttInfo=new AttInfo[len];
for(int j=0;j<len;j++){
arrayOfAttInfo[j]=attInfos.get(j);
}
bdl.putString(CLASSNAME, this.getClass().getName());
bdl.putParcelableArray(FIELDLIST, arrayOfAttInfo);
}
} catch (InstantiationException e) {
Log.e(tag, e.getMessage());
} catch (IllegalArgumentException e) {
Log.e(tag, e.getMessage());
} catch (ClassNotFoundException e) {
Log.e(tag, e.getMessage());
} catch (IllegalAccessException e) {
Log.e(tag, e.getMessage());
}
return bdl;
}
/**
* 从Pacel创建VieModel对象
*
* @param in
* :ViewModel对象的属性打包对象
* @return:返回解包后的ViewModel对象
*
*/
public static ViewModel readFromBundle(Bundle in) {
ViewModel vm = null;
if(in==null){
return vm;
}
String clsName = in.getString(CLASSNAME);
Parcelable[] arrayOfField = in.getParcelableArray(FIELDLIST);
if (clsName != null && arrayOfField!=null) {
int len = arrayOfField.length;
List<AttInfo> viewModelFields = new ArrayList<AttInfo>();
for (int i = 0; i < len; i++) {
viewModelFields.add((AttInfo) arrayOfField[i]);
}
try {
vm = (ViewModel) AttributeReflection.getOjectFromAttInfos(clsName,
viewModelFields);
} catch (ClassNotFoundException e) {
Log.e(tag, e.getMessage());
} catch (InstantiationException e) {
Log.e(tag, e.getMessage());
} catch (IllegalAccessException e) {
Log.e(tag, e.getMessage());
} catch (NoSuchFieldException e) {
Log.e(tag, e.getMessage());
}
}
return vm;
};
}
| 10-myclimb | trunk/MyClimb/src/ui/viewModel/ViewModel.java | Java | asf20 | 4,136 |
package ui.viewModel;
/**
*
* @author 福建师范大学软件学院 倪友聪、赵康
*
*/
public class ModelErrorInfo {
//错误属性名称
private String errAttName;
//错误消息
private String errMsg;
//获取属性名称
public String getAttName() {
return this.errAttName;
}
//设置属性名称
public void setErrAttName(String aErrAttName){
this.errAttName=aErrAttName;
}
//获取错误消息
public String getErrMsg(){
return this.errMsg;
}
//设置错误消息
public void setErrMsg(String aErrMsg){
this.errMsg=aErrMsg;
}
public ModelErrorInfo(){
}
}
| 10-myclimb | trunk/MyClimb/src/ui/viewModel/ModelErrorInfo.java | Java | asf20 | 659 |
<%@ WebService Language="C#" CodeBehind="iMenu.asmx.cs" Class="iMenuService.iMenu" %>
| 0a9431dc7ba4b01345d07172eb22946f | trunk/public/iMenu.asmx | ASP.NET | asf20 | 90 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="iMenuService._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
| 0a9431dc7ba4b01345d07172eb22946f | trunk/public/Default.aspx | ASP.NET | asf20 | 446 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Caam.Framework.Common;
using System.Data;
using System.Text;
using System.IO;
using System.Configuration;
namespace iMenuService.v2
{
/// <summary>
/// Summary description for iMenuWS
/// </summary>
[WebService(Namespace = "http://codex13.com.vn/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class iMenuWS : System.Web.Services.WebService
{
[WebMethod(Description = "<i>Lấy thông tin menu và thức ăn/nước uống. Kết quả trả về: CSV</i><br/><br/><span style=\"color:gray\">Ví dụ input:</span><br/><input user=\"lbnam\" pass=\"123456\"/>")]
[Obsolete("Version 1.0")]
public string getAll(string input)
{
string result = getCsv(input, "iMenu_usp_Data_GetAllViaXml");
return result;
}
[WebMethod(Description = "<i>Lấy thông tin order sau khi submit. Kết quả trả về: CSV</i><br/><br/><span style=\"color:gray\">Ví dụ input:</span><br/><input user=\"lbnam\" pass=\"123456\"/>")]
[Obsolete("Version 1.0")]
public string getOrderList(string input)
{
string result = getCsv(input, "iMenu_usp_mOrders_GetListByUser");
return result;
}
[WebMethod(Description = "<i>Submit hóa đơn. Kết quả trả về: CSV</i><br/><br/><span style=\"color:gray\">Ví dụ input:</span><br/><input user=\"lbnam\" pass=\"123456\" desc=\"nhanh nhanh\" table=\"1\" parent=\"3\" /><br/>"
+ "<items><br/>"
+ " <item id=\"1\" quantity=\"2\" discount=\"0\" desc=\"\"/><br/>"
+ " <item id=\"2\" quantity=\"3\" discount=\"5000\" desc=\"\"/><br/>"
+ " <item id=\"4\" quantity=\"6\" discount=\"0\" desc=\"it da\"/><br/>"
+ "</items>")]
[Obsolete("Version 1.0")]
public string confirmOrder(string input)
{
string result = getCsvScalar(input, "iMenu_usp_mOrders_Insert");
return result;
}
private string getCsv(string input, string sp)
{
string result = string.Empty;
try
{
DbManager db = new DbManager();
db.CreateParameters(1);
db.AddParameter(0, "@input", input);
DataSet ds = db.ExecuteDataSet(CommandType.StoredProcedure, sp);
db.Close();
if (ds != null)
{
result = ConvertDataSetToCSV(ds);
if (string.IsNullOrEmpty(result))
result = resultToCsv("result", "");
}
else
{
result = resultToCsv("result", "");
}
}
catch (Exception ex)
{
result = resultToCsv("error", ex.Message);
}
return result;
}
private string getCsvScalar(string input, string sp)
{
string result = string.Empty;
try
{
DbManager db = new DbManager();
db.CreateParameters(1);
db.AddParameter(0, "@input", input);
object obj = db.ExecuteScalarV2(CommandType.StoredProcedure, sp);
db.Close();
//if (obj != null)
//{
result = resultToCsv("result", obj);
//}
}
catch (Exception ex)
{
result = resultToCsv("error", ex.Message);
}
return result;
}
[WebMethod(Description = "<i>Lấy url của ảnh trên server. Gọi hàm này xong lấy url ảnh để tải ảnh lưu vào resource. Kết quả trả về: CSV</i><br/><br/><span style=\"color:gray\">Ví dụ input:</span><br/>Coffee-icon.png")]
[Obsolete("Version 1.0")]
public string getImage(string filename)
{
string ret = string.Empty;
if (!string.IsNullOrEmpty(filename))
{
if (File.Exists(Server.MapPath(ConfigurationManager.AppSettings["image_base_path"] + filename)))
{
ret = string.Format("{0}{1}{2}", ConfigurationManager.AppSettings["base_domain"],
ConfigurationManager.AppSettings["image_base_path"], filename);
}
else
ret = "image not found";
}
ret = resultToCsv("url", ret);
return ret;
}
private string resultToCsv(string name, object value)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("\"{0}\"", name);
sb.Append(Environment.NewLine);
sb.Append(value == null ? "0" : value);
return sb.ToString();
}
protected string ExportDataTableToCSV(DataTable dt)
{
//HttpResponse res = HttpContext.Current.Response;
//res.Clear();
//res.ContentType = "text/csv";
//res.AddHeader("content-disposition", "attachment;filename=Categories.csv");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dt.Columns.Count; i++)
{
sb.Append(dt.Columns[i].ColumnName + ',');
}
sb.Append(Environment.NewLine);
for (int j = 0; j < dt.Rows.Count; j++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
sb.Append(dt.Rows[j][k].ToString() + ',');
}
sb.Append(Environment.NewLine);
}
//res.Write(sb.ToString());
return sb.ToString();
//res.End();
}
public static string ConvertDataSetToCSV(DataSet ds)
{
const string LC_COMMA = ",";
const string LC_DBLQUOTE = "\"";
const string LC_DBLQUOTE_ESC = "\"\"";
StringBuilder csv = new StringBuilder();
foreach (DataTable tbl in ds.Tables)
{
// Append the table's column headers.
foreach (DataColumn col in tbl.Columns)
{
csv.Append(LC_DBLQUOTE + col.ColumnName + LC_DBLQUOTE + LC_COMMA);
}
csv.Length -= 1;
csv.Append(Environment.NewLine);
// Append the table's data.
foreach (DataRow row in tbl.Rows)
{
foreach (object val in row.ItemArray)
{
csv.Append(LC_DBLQUOTE + val.ToString().Replace(LC_DBLQUOTE, LC_DBLQUOTE_ESC).Replace(",", ";")
+ LC_DBLQUOTE + LC_COMMA);
}
csv.Length -= 1;
csv.Append(Environment.NewLine);
}
// Add an empty line between this and the next table.
//csv.Append(Environment.NewLine);
csv.Append("###");
csv.Append(Environment.NewLine);
}
return csv.ToString();
}
}
}
| 0a9431dc7ba4b01345d07172eb22946f | trunk/iMenuService/v2/iMenuWS.asmx.cs | C# | asf20 | 7,863 |
<%@ WebService Language="C#" CodeBehind="iMenuWS.asmx.cs" Class="iMenuService.v2.iMenuWS" %>
| 0a9431dc7ba4b01345d07172eb22946f | trunk/iMenuService/v2/iMenuWS.asmx | ASP.NET | asf20 | 97 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Caam.Framework.Common;
using System.Data;
using System.Text;
using System.IO;
using System.Configuration;
namespace iMenuService
{
/// <summary>
/// Summary description for iMenu
/// </summary>
[WebService(Namespace = "http://codex13.com.vn/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class iMenu : System.Web.Services.WebService
{
[WebMethod(Description = "<i>Lấy thông tin menu và thức ăn/nước uống. Kết quả trả về: CSV</i><br/><br/><span style=\"color:gray\">Ví dụ input:</span><br/><input user=\"lbnam\" pass=\"123456\"/>")]
[Obsolete("Version 1.0")]
public string getAll(string input)
{
string result = getCsv(input, "iMenu_usp_Categories_Items_GetAllViaXml");
return result;
}
[WebMethod(Description = "<i>Lấy thông tin order sau khi submit. Kết quả trả về: CSV</i><br/><br/><span style=\"color:gray\">Ví dụ input:</span><br/><input user=\"lbnam\" pass=\"123456\"/>")]
[Obsolete("Version 1.0")]
public string getOrderList(string input)
{
string result = getCsv(input, "iMenu_usp_Orders_GetListByUser");
return result;
}
[WebMethod(Description = "<i>Submit hóa đơn. Kết quả trả về: CSV</i><br/><br/><span style=\"color:gray\">Ví dụ input:</span><br/><input user=\"lbnam\" pass=\"123456\" note=\"nhanh nhanh\" important=\"1\"/><br/>"
+ "<items><br/>"
+ " <item id=\"1\" quantity=\"2\" note=\"\"/><br/>"
+ " <item id=\"2\" quantity=\"3\" note=\"\"/><br/>"
+ " <item id=\"4\" quantity=\"6\" note=\"it da\"/><br/>"
+ "</items>")]
[Obsolete("Version 1.0")]
public string confirmOrder(string input)
{
string result = getCsvScalar(input, "iMenu_usp_Orders_Insert");
return result;
}
private string getCsv(string input, string sp)
{
string result = string.Empty;
try
{
DbManager db = new DbManager();
db.CreateParameters(1);
db.AddParameter(0, "@input", input);
DataSet ds = db.ExecuteDataSet(CommandType.StoredProcedure, sp);
db.Close();
if (ds != null)
{
result = ConvertDataSetToCSV(ds);
if(string.IsNullOrEmpty(result))
result = resultToCsv("result", "");
}
else
{
result = resultToCsv("result", "");
}
}
catch (Exception ex)
{
result = resultToCsv("error", ex.Message);
}
return result;
}
private string getCsvScalar(string input, string sp)
{
string result = string.Empty;
try
{
DbManager db = new DbManager();
db.CreateParameters(1);
db.AddParameter(0, "@input", input);
object obj = db.ExecuteScalarV2(CommandType.StoredProcedure, sp);
db.Close();
//if (obj != null)
//{
result = resultToCsv("result", obj);
//}
}
catch (Exception ex)
{
result = resultToCsv("error", ex.Message);
}
return result;
}
[WebMethod(Description = "<i>Lấy url của ảnh trên server. Gọi hàm này xong lấy url ảnh để tải ảnh lưu vào resource. Kết quả trả về: CSV</i><br/><br/><span style=\"color:gray\">Ví dụ input:</span><br/>Coffee-icon.png")]
[Obsolete("Version 1.0")]
public string getImage(string filename)
{
string ret = string.Format("{0}{1}{2}", ConfigurationManager.AppSettings["base_domain"],
ConfigurationManager.AppSettings["image_base_path"], "no_image.jpg");
if (!string.IsNullOrEmpty(filename))
{
if (File.Exists(Server.MapPath(ConfigurationManager.AppSettings["image_base_path"] + filename)))
{
ret = string.Format("{0}{1}{2}", ConfigurationManager.AppSettings["base_domain"],
ConfigurationManager.AppSettings["image_base_path"], filename);
}
}
ret = resultToCsv("url", ret);
return ret;
}
private string resultToCsv(string name, object value)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("\"{0}\"", name);
sb.Append(Environment.NewLine);
sb.Append(value==null?"0": value);
return sb.ToString();
}
protected string ExportDataTableToCSV(DataTable dt)
{
//HttpResponse res = HttpContext.Current.Response;
//res.Clear();
//res.ContentType = "text/csv";
//res.AddHeader("content-disposition", "attachment;filename=Categories.csv");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dt.Columns.Count; i++)
{
sb.Append(dt.Columns[i].ColumnName + ',');
}
sb.Append(Environment.NewLine);
for (int j = 0; j < dt.Rows.Count; j++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
sb.Append(dt.Rows[j][k].ToString() + ',');
}
sb.Append(Environment.NewLine);
}
//res.Write(sb.ToString());
return sb.ToString();
//res.End();
}
public static string ConvertDataSetToCSV(DataSet ds)
{
const string LC_COMMA = ",";
const string LC_DBLQUOTE = "\"";
const string LC_DBLQUOTE_ESC = "\"\"";
StringBuilder csv = new StringBuilder();
foreach (DataTable tbl in ds.Tables)
{
// Append the table's column headers.
foreach (DataColumn col in tbl.Columns)
{
csv.Append(LC_DBLQUOTE + col.ColumnName + LC_DBLQUOTE + LC_COMMA);
}
csv.Length -= 1;
csv.Append(Environment.NewLine);
// Append the table's data.
foreach (DataRow row in tbl.Rows)
{
foreach (object val in row.ItemArray)
{
csv.Append(LC_DBLQUOTE + val.ToString().Replace(LC_DBLQUOTE, LC_DBLQUOTE_ESC).Replace(",", ";")
+ LC_DBLQUOTE + LC_COMMA);
}
csv.Length -= 1;
csv.Append(Environment.NewLine);
}
// Add an empty line between this and the next table.
//csv.Append(Environment.NewLine);
csv.Append("###");
csv.Append(Environment.NewLine);
}
return csv.ToString();
}
}
}
| 0a9431dc7ba4b01345d07172eb22946f | trunk/iMenuService/iMenu.asmx.cs | C# | asf20 | 7,939 |
<%@ WebService Language="C#" CodeBehind="iMenu.asmx.cs" Class="iMenuService.iMenu" %>
| 0a9431dc7ba4b01345d07172eb22946f | trunk/iMenuService/iMenu.asmx | ASP.NET | asf20 | 90 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("iMenuService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("iMenuService")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b3197157-c62e-4596-9900-318b377d8897")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 0a9431dc7ba4b01345d07172eb22946f | trunk/iMenuService/Properties/AssemblyInfo.cs | C# | asf20 | 1,395 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace iMenuService
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | 0a9431dc7ba4b01345d07172eb22946f | trunk/iMenuService/Default.aspx.cs | C# | asf20 | 334 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="iMenuService._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
| 0a9431dc7ba4b01345d07172eb22946f | trunk/iMenuService/Default.aspx | ASP.NET | asf20 | 446 |
using System.Data.SqlClient;
using System.Configuration;
namespace Caam.Framework.Common
{
public class ConnectionProvider
{
private static ConnectionProvider connProvider = new ConnectionProvider();
private SqlConnection sqlConn = null;//new SqlConnection();
private ConnectionProvider()
{
}
public static ConnectionProvider Get_Instance()
{
if (connProvider == null)
{
connProvider = new ConnectionProvider();
}
return connProvider;
}
public SqlConnection GetSqlConnection()
{
sqlConn = new SqlConnection(this.Get_ConnectionString_FromConfigurationFile(string.Empty));
return sqlConn;
}
public SqlConnection GetSqlConnection(string connectStringKey)
{
sqlConn = new SqlConnection(this.Get_ConnectionString_FromConfigurationFile(connectStringKey));
return sqlConn;
}
private string Get_ConnectionString_FromConfigurationFile(string connectStringKey)
{
string connectionString = this.GetConnString(connectStringKey);
return connectionString;
}
//06/08/2009
public string GetConnString(string connectStringKey)
{
if (string.IsNullOrEmpty(connectStringKey))
connectStringKey = "ConnectionString";
return ConfigurationManager.ConnectionStrings[connectStringKey].ConnectionString;
}
}
}
| 0a9431dc7ba4b01345d07172eb22946f | trunk/iMenuServiceLib/ConnectionProvider.cs | C# | asf20 | 1,641 |
using System.Data;
using System.Data.SqlClient;
//using System.Data.OracleClient;
namespace Caam.Framework.Common
{
public sealed class DbManagerFactory
{
private DbManagerFactory() { }
public static IDbConnection GetConnection(DataProvider providerType)
{
IDbConnection iDbConnection = null;
switch (providerType)
{
case DataProvider.SqlServer:
iDbConnection = new SqlConnection();
break;
//case DataProvider.OleDb:
// iDbConnection = new OleDbConnection();
// break;
//case DataProvider.Odbc:
// iDbConnection = new OdbcConnection();
// break;
case DataProvider.Oracle:
//iDbConnection = new OracleConnection();
break;
default:
return null;
}
return iDbConnection;
}
public static IDbCommand GetCommand(DataProvider providerType)
{
switch (providerType)
{
case DataProvider.SqlServer:
return new SqlCommand();
//case DataProvider.OleDb:
// return new OleDbCommand();
//case DataProvider.Odbc:
// return new OdbcCommand();
case DataProvider.Oracle:
// return new OracleCommand();
default:
return null;
}
}
public static IDbDataAdapter GetDataAdapter(DataProvider providerType)
{
switch (providerType)
{
case DataProvider.SqlServer:
return new SqlDataAdapter();
//case DataProvider.OleDb:
// return new OleDbDataAdapter();
//case DataProvider.Odbc:
// return new OdbcDataAdapter();
case DataProvider.Oracle:
//return new OracleDataAdapter();
default:
return null;
}
}
public static IDbTransaction GetTransaction(DataProvider providerType)
{
IDbConnection iDbConnection = GetConnection(providerType);
IDbTransaction iDbTransaction = iDbConnection.BeginTransaction();
return iDbTransaction;
}
public static IDataParameter GetParameter(DataProvider providerType)
{
IDataParameter iDataParameter = null;
switch (providerType)
{
case DataProvider.SqlServer:
iDataParameter = new SqlParameter();
break;
//case DataProvider.OleDb:
// iDataParameter = new OleDbParameter();
// break;
//case DataProvider.Odbc:
// iDataParameter = new OdbcParameter();
// break;
case DataProvider.Oracle:
// iDataParameter = new OracleParameter();
break;
}
return iDataParameter;
}
public static IDbDataParameter[] GetParameters(DataProvider providerType, int paramsCount)
{
IDbDataParameter[] idbParams = new IDbDataParameter[paramsCount];
switch (providerType)
{
case DataProvider.SqlServer:
for (int i = 0; i < paramsCount; ++i)
{
idbParams[i] = new SqlParameter();
}
break;
//case DataProvider.OleDb:
// for (int i = 0; i < paramsCount; ++i)
// {
// idbParams[i] = new OleDbParameter();
// }
// break;
//case DataProvider.Odbc:
// for (int i = 0; i < paramsCount; ++i)
// {
// idbParams[i] = new OdbcParameter();
// }
// break;
case DataProvider.Oracle:
for (int i = 0; i < paramsCount; ++i)
{
//idbParams[i] = new OracleParameter();
}
break;
default:
idbParams = null;
break;
}
return idbParams;
}
}
}
| 0a9431dc7ba4b01345d07172eb22946f | trunk/iMenuServiceLib/DbManagerFactory.cs | C# | asf20 | 4,732 |
namespace Caam.Framework.Common
{
public enum DataProvider
{
Oracle = 0, SqlServer = 1
}
}
| 0a9431dc7ba4b01345d07172eb22946f | trunk/iMenuServiceLib/enums/DataProvider.cs | C# | asf20 | 118 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("iMenuServiceLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("iMenuServiceLib")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("406c5d3e-8b19-4987-8572-35f0e08460ce")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 0a9431dc7ba4b01345d07172eb22946f | trunk/iMenuServiceLib/Properties/AssemblyInfo.cs | C# | asf20 | 1,442 |
using System;
using System.Data;
using System.Security.Permissions;
namespace Caam.Framework.Common
{
//[StrongNameIdentityPermission(SecurityAction.LinkDemand, PublicKey = PublicKeys.MyCompany)]
public sealed class DbManager : IDbManager, IDisposable
{
private IDbConnection idbConnection;
private IDataReader idataReader;
private IDbCommand idbCommand;
private DataProvider providerType;
private IDbTransaction idbTransaction = null;
private IDbDataParameter[] idbParameters = null;
private string strConnection;
public DbManager():this( DataProvider.SqlServer)
{
}
public DbManager(DataProvider providerType)
{
this.MustDispose = true;
this.providerType = providerType;
this.idbCommand = DbManagerFactory.GetCommand(this.ProviderType);
this.ConnectionString = ConnectionProvider.Get_Instance().GetConnString("");
}
public DbManager(string dataProvider)
{
this.MustDispose = true;
// Return the requested DaoFactory
switch (dataProvider)
{
//case "System.Data.OleDb": return new Access.AccessDaoFactory();
case "System.Data.SqlClient":
//Debug.WriteLine("System.Data.SqlClient");
this.providerType = DataProvider.SqlServer;
break;
case "System.Data.OracleClient":
//Debug.WriteLine("System.Data.OracleClient");
this.providerType = DataProvider.Oracle;
break;
// Just in case: the Design Pattern Framework always has MS Access available.
default:
this.providerType = DataProvider.SqlServer;// new Access.AccessDaoFactory();
break;
}
}
public DbManager(DataProvider providerType, string connectionString)
{
this.MustDispose = true;
this.providerType = providerType;
this.strConnection = connectionString;
}
public IDbConnection Connection
{
get
{
return idbConnection;
}
}
public bool MustDispose { get; set; }
public IDataReader DataReader
{
get
{
return idataReader;
}
set
{
idataReader = value;
}
}
public DataProvider ProviderType
{
get
{
return providerType;
}
set
{
providerType = value;
}
}
public string ConnectionString
{
get
{
return strConnection;
}
set
{
strConnection = value;
}
}
public IDbCommand Command
{
get
{
return idbCommand;
}
}
public IDbTransaction Transaction
{
get
{
return idbTransaction;
}
}
public IDbDataParameter[] Parameters
{
get
{
return idbParameters;
}
}
public void Open()
{
idbConnection = DbManagerFactory.GetConnection(this.providerType);
if (this.ConnectionString == string.Empty)
throw new ArgumentNullException("Connection string is empty");
idbConnection.ConnectionString = this.ConnectionString;
if (idbConnection.State != ConnectionState.Open)
idbConnection.Open();
//this.idbCommand = DbManagerFactory.GetCommand(this.ProviderType);
}
public void Close()
{
if (idbConnection != null && idbConnection.State != ConnectionState.Closed)
idbConnection.Close();
if (idbConnection != null)
((IDisposable)idbConnection).Dispose();
}
public void Dispose()
{
//GC.SuppressFinalize(this);
this.Close();
this.idbCommand = null;
this.idbTransaction = null;
this.idbConnection = null;
//this.idbParameters = null;
this.ConnectionString = null;
//GC.Collect();
//GC.WaitForPendingFinalizers();
}
public void CreateParameters(int paramsCount)
{
idbParameters = new IDbDataParameter[paramsCount];
idbParameters = DbManagerFactory.GetParameters(this.ProviderType, paramsCount);
}
public void AddParameter(int index, string paramName, object objValue)
{
if (index < idbParameters.Length)
{
if (this.providerType == DataProvider.Oracle)
idbParameters[index].ParameterName = paramName.Replace("@", "");
else
idbParameters[index].ParameterName = paramName;
idbParameters[index].Direction = ParameterDirection.Input;
idbParameters[index].Value = objValue;
}
}
public object GetParameterValue(string paramName)
{
if (idbParameters == null)
throw new Exception("idbParameters is null");
int len = idbParameters.Length;
IDbDataParameter param;
for (int i = 0; i < len; i++)
{
param = idbParameters[i];
if (param.ParameterName == paramName)
return param.Value;
}
return null;
}
public void AddParameter(int index, IDbDataParameter param)
{
if (index < idbParameters.Length)
{
idbParameters[index] = param;
}
}
public void AddOutParameter(int index, string paramName, object type)
{
if (index < idbParameters.Length)
{
idbParameters[index].ParameterName = paramName;
idbParameters[index].Direction = ParameterDirection.Output;
idbParameters[index].Size = 8;
}
}
public void BeginTransaction()
{
if (this.idbConnection != null && this.idbConnection.State == ConnectionState.Open)
this.idbTransaction = this.idbConnection.BeginTransaction();
if (this.idbTransaction == null)
idbTransaction = DbManagerFactory.GetTransaction(this.ProviderType);
this.idbCommand.Transaction = idbTransaction;
}
public void CommitTransaction()
{
if (this.idbTransaction != null)
this.idbTransaction.Commit();
idbTransaction = null;
}
public void RollbackTransaction()
{
if (this.idbTransaction != null)
this.idbTransaction.Rollback();
idbTransaction = null;
}
public IDataReader ExecuteReader(CommandType commandType, string commandText)
{
this.idbCommand = DbManagerFactory.GetCommand(this.ProviderType);
idbCommand.Connection = this.Connection;
PrepareCommand(idbCommand, this.Connection, this.Transaction, commandType, commandText, this.Parameters);
this.DataReader = idbCommand.ExecuteReader();
idbCommand.Parameters.Clear();
return this.DataReader;
}
public void CloseReader()
{
if (this.DataReader != null)
this.DataReader.Close();
}
private void AttachParameters(IDbCommand command,
IDbDataParameter[] commandParameters)
{
foreach (IDbDataParameter idbParameter in commandParameters)
{
if ((idbParameter.Direction == ParameterDirection.InputOutput)
&&
(idbParameter.Value == null))
{
idbParameter.Value = DBNull.Value;
}
command.Parameters.Add(idbParameter);
}
}
public void AttachParameters(IDbDataParameter[] commandParameters)
{
CreateParameters(commandParameters.Length);
//foreach (IDbDataParameter idbParameter in commandParameters)
for (int i = 0; i < commandParameters.Length; i++)
{
//if ((idbParameter.Direction == ParameterDirection.InputOutput)
//&&
// (idbParameter.Value == null))
//{
// idbParameter.Value = DBNull.Value;
//}
//this.Command.Parameters.Add(idbParameter);
this.AddParameter(i, commandParameters[i]);
}
}
private void PrepareCommand(IDbCommand command, IDbConnection connection,
IDbTransaction transaction, CommandType commandType, string commandText,
IDbDataParameter[] commandParameters)
{
if (connection == null)
throw new ArgumentNullException("Connection is null");
command.Connection = connection;
if (this.providerType == DataProvider.SqlServer)
command.CommandText = commandText.Substring(commandText.IndexOf(".") + 1);
else
command.CommandText = commandText;
command.CommandType = commandType;
if (transaction != null)
{
command.Transaction = transaction;
}
if (commandParameters != null)
{
AttachParameters(command, commandParameters);
}
}
public int ExecuteNonQuery(CommandType commandType, string commandText)
{
//this.idbCommand = DbManagerFactory.GetCommand(this.ProviderType);
this.Open();
PrepareCommand(idbCommand, this.Connection, this.Transaction,
commandType, commandText, this.Parameters);
int returnValue = idbCommand.ExecuteNonQuery();
idbCommand.Parameters.Clear();
return returnValue;
}
public object ExecuteScalar(CommandType commandType, string commandText)
{
//this.idbCommand = DbManagerFactory.GetCommand(this.ProviderType);
this.Open();
PrepareCommand(idbCommand, this.Connection, this.Transaction, commandType, commandText, this.Parameters);
object returnValue = idbCommand.ExecuteScalar();
idbCommand.Parameters.Clear();
if (this.MustDispose)
this.Dispose();
return returnValue;
}
public DataSet ExecuteDataSet(CommandType commandType, string commandText)
{
//System.Diagnostics.Trace.WriteLine("Begin..dataset"+DateTime.Now.ToString("hhMMss.fff"));
//this.idbCommand = DbManagerFactory.GetCommand(this.ProviderType);
DataSet dataSet = new DataSet();
try
{
this.Open();
PrepareCommand(this.idbCommand, this.Connection, this.Transaction, commandType, commandText, this.Parameters);
IDbDataAdapter dataAdapter = DbManagerFactory.GetDataAdapter(this.ProviderType);
dataAdapter.SelectCommand = this.idbCommand;
dataAdapter.Fill(dataSet);
idbCommand.Parameters.Clear();
//System.Diagnostics.Trace.WriteLine("End..dataset" + DateTime.Now.ToString("hhMMss.fff"));
return dataSet;
}
catch (Exception)
{
throw;
}
finally
{
if (this.MustDispose)
this.Dispose();
}
}
public DataTable ExecuteDataTable(CommandType commandType, string commandText)
{
DataSet ds = ExecuteDataSet(commandType, commandText);
if (ds.Tables.Count > 0)
return ds.Tables[0];
return null;
}
public DataTable ExecuteDataTable(string commandText)
{
return ExecuteDataTable(CommandType.StoredProcedure, commandText);
}
#region version 2
//public DataTable ExecuteDataTableV2(CommandType commandType, string commandText)
//{
// DataSet ds = ExecuteDataSet(commandType, commandText);
// if (ds.Tables.Count > 0)
// return ds.Tables[0];
// return null;
//}
public object ExecuteScalarV2(CommandType commandType, string commandText)
{
try
{
//this.idbCommand = DbManagerFactory.GetCommand(this.ProviderType);
this.Open();
PrepareCommand(idbCommand, this.Connection, this.Transaction, commandType, commandText, this.Parameters);
object returnValue = idbCommand.ExecuteScalar();
return returnValue;
}
catch (Exception)
{
throw;
}
finally
{
if (this.MustDispose)
this.Dispose();
}
}
/// <summary>
/// ExecuteNonQueryV2 - lbnam04
/// </summary>
/// <param name="commandType"></param>
/// <param name="commandText"></param>
/// <returns></returns>
public int ExecuteNonQueryV2(CommandType commandType, string commandText)
{
try
{
//this.idbCommand = DbManagerFactory.GetCommand(this.ProviderType);
this.Open();
PrepareCommand(idbCommand, this.Connection, this.Transaction,
commandType, commandText, this.Parameters);
int returnValue = idbCommand.ExecuteNonQuery();
idbCommand.Parameters.Clear();
return returnValue;
}
catch (Exception)
{
throw;
}
finally
{
if (this.MustDispose)
this.Dispose();
}
}
#endregion
}
}
| 0a9431dc7ba4b01345d07172eb22946f | trunk/iMenuServiceLib/DbManager.cs | C# | asf20 | 15,039 |
using System.Data;
namespace Caam.Framework.Common
{
public interface IDbManager
{
DataProvider ProviderType { get;set;}
string ConnectionString { get;set;}
bool MustDispose { get; set; }
IDbConnection Connection
{
get;
}
IDbTransaction Transaction
{
get;
}
IDataReader DataReader
{
get;
}
IDbCommand Command
{
get;
}
IDbDataParameter[] Parameters
{
get;
}
void Open();
void BeginTransaction();
void CommitTransaction();
void RollbackTransaction(); //16/10/2009 - lbnam04
void CreateParameters(int paramsCount);
void AddParameter(int index, string paramName, object objValue);
void AddParameter(int index, IDbDataParameter param);
void AddOutParameter(int index, string paramName, object dbType);
void AttachParameters(IDbDataParameter[] commandParameters);
IDataReader ExecuteReader(CommandType commandType, string
commandText);
DataSet ExecuteDataSet(CommandType commandType, string
commandText);
DataTable ExecuteDataTable(CommandType commandType, string
commandText);
DataTable ExecuteDataTable(string commandText);
//DataTable ExecuteDataTableV2(CommandType commandType, string commandText);
object ExecuteScalar(CommandType commandType, string commandText);
object ExecuteScalarV2(CommandType commandType, string commandText);
int ExecuteNonQuery(CommandType commandType, string commandText);
int ExecuteNonQueryV2(CommandType commandType, string commandText);
object GetParameterValue(string paramName);
void CloseReader();
void Close();
void Dispose();
}
}
| 0a9431dc7ba4b01345d07172eb22946f | trunk/iMenuServiceLib/IDbManager.cs | C# | asf20 | 1,962 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sv;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author PC-PC
*/
@WebServlet(name = "AddSinhVien", urlPatterns = {"/AddSinhVien"})
public class AddSinhVien extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String username = null;
String password = null;
String firstname = null;
String lastname = null;
String email = null;
username = request.getParameter("username");
password = request.getParameter("passid");
firstname = request.getParameter("firstname");
lastname = request.getParameter("lastname");
email = request.getParameter("email");
//chen vao co so du lieu
if (insertUser(username, password, firstname, lastname, email)) {
session.setAttribute("UserName", username);
session.setAttribute("Access", "member");
//gan sesssion cho UserId
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
} else {
RequestDispatcher rd = request.getRequestDispatcher("registerMember.jsp");
request.setAttribute("addMemberInvalid", false);
rd.forward(request, response);
}
}
public static boolean insertUser(String username, String password, String firstname, String lastname, String email) {
boolean isInsert = false;
//ket noi voi co so du lieu
Connection conn = getConnection();
//chuyen password thanh ma md5
String hashtest = convertMD5(password);
//chuyen du lieu ve kieu ngay
String call = "{call sp_Insert_Member(?,?,?,?,?,?,?,?,?)}";
try {
CallableStatement callbleStatememt = conn.prepareCall(call);
callbleStatememt.setString(1, username);
callbleStatememt.setString(2, password);
callbleStatememt.setString(3, firstname);
callbleStatememt.setString(4, lastname);
callbleStatememt.setString(5, password);
callbleStatememt.executeUpdate();
isInsert = true;
System.out.println("them thanh cong");
} catch (SQLException e) {
System.out.println("loi insert co so du lieu");
e.printStackTrace();
} finally {
System.out.println("dong ket noi");
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return isInsert;
}
public static String convertMD5(String password) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
byte[] digit = md.digest();
BigInteger bigInt = new BigInteger(1, digit);
String hashtext = bigInt.toString(16);
return hashtext;
} catch (NoSuchAlgorithmException e) {
} catch (NullPointerException ex) {
System.out.println(ex);
}
return null;
}
public static Connection getConnection() {
Connection con = null;
try {
// ket noi vs Microsoft sql server
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://PC\\SQLEXPRESSt:1433;" + "databaseName=StudentManagement;";
con = DriverManager.getConnection(url, "sa", "123456");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Loi Ket Noi!");
}
return con;
}
}
| 11cntt3 | AddSinhVien.java | Java | epl | 5,153 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<?php
$db = mysqli_connect("localhost","root","");
mysqli_select_db($db, "thuctap");
mysqli_set_charset($db, "utf8");
print_r($_POST);
$sql="Select *
from sinhvien
";
$result=mysqli_query($db,$sql);
$str="<table >";
$str.="<tr>
<th>Username</th>
<th>Password</th>
<th>Address</th>
<th>Phone number</th>
<th>Email</th>
</tr>";
while($row=mysqli_fetch_array($result))
{
$str.="<tr>";
$str.="<td>".$row['username']."</td>";
$str.="<td>".$row['password']."</td>";
$str.="<td>".$row['address']."</td>";
$str.="<td>".$row['phone']."</td>";
$str.="<td>".$row['email']."</td></tr>";
}
echo $str."</table><br>";
?>
<body>
</body>
</html> | 11cntt3 | xuli.php | PHP | epl | 975 |
<?
$conn=mysql_connect("localhost", "root", "root") or die("can't connect database");
mysql_select_db("it3",$conn);
$sql="select * from user";
$query=mysql_query($sql);
if(mysql_num_rows($query) == 0)
{
echo "Chua co du lieu";
}
else
{
while($row=mysql_fetch_array($query))
{
echo $row[IDSV] ." - ".$row[ho ten]." - ".$row[diachi]. "- ".$row[sdt]." - ".$row[ngaysinh].<br />";
}
}
mysql_close($conn);
?> | 11cntt3 | connectdatabase.php | PHP | epl | 421 |
<form method="post" name="contact" onsubmit="return check_field();">
<fieldset style="border: none;" class="shadow cor">
<div class="bgg_in_spm"></div>
<table width="100%" id="register">
<tr>
<td valign="top">
<table cellpadding="4" cellspacing="0" id="tb_register" style="width: 100%;">
<tr>
<td width="150px">FullName</td>
<td><input type="text" name="name" id="Name" class="boxInput" size="20"/><b style="color: #ff0000;">*</b>
</td>
</tr>
<tr>
<td width="150px">Email</td>
<td><input type="text" name="email" id="Email" class="boxInput" size="20"/><b style="color: #ff0000;">*</b>
</td>
</tr>
<tr>
<td>Phone</td>
<td><input type="number" name="phone" id="phone" class="boxInput" size="20"/> <b style="color: #ff0000;">*</b> <span class="explain"></span></td>
</tr>
<tr>
<td>Website</td>
<td><input type="text" name="website" id="web" class="boxInput" size="20" />
<span class="explain"></span></td>
</tr>
<tr>
<td>Content</td>
<td><input type="text" name="content" id="content" class="boxInput" size="40" value=""/></td>
</tr>
<tr>
<td>Giới tính</td>
<td>
<input type="radio" checked="checked" name="sex" value="male" />Nam <input type="radio" name="sex" value="female" />Nữ
</td>
</tr>
<tr>
<td>Tỉnh/Tp</td>
<td>
<select name="province" id="Province_City">
<option value="1">Hà Nội</option>
<option value="2">TP HCM</option>
<option value="5">Hải Phòng</option>
<option value="4">Đà Nẵng</option>
<option value="6">An Giang</option>
<option value="7">Bà Rịa-Vũng Tàu</option>
<option value="13">Bình Dương</option>
<option value="15">Bình Phước</option>
<option value="16">Bình Thuận</option>
<option value="14">Bình Định</option>
<option value="8">Bạc Liêu</option>
<option value="10">Bắc Giang</option>
<option value="9">Bắc Kạn</option>
<option value="11">Bắc Ninh</option>
<option value="12">Bến Tre</option>
<option value="18">Cao Bằng</option>
<option value="17">Cà Mau</option>
<option value="3">Cần Thơ</option>
<option value="24">Gia Lai</option>
<option value="25">Hà Giang</option>
<option value="26">Hà Nam</option>
<option value="27">Hà Tĩnh</option>
<option value="30">Hòa Bình</option>
<option value="28">Hải Dương</option>
<option value="29">Hậu Giang</option>
<option value="31">Hưng Yên</option>
<option value="32">Khánh Hòa</option>
<option value="33">Kiên Giang</option>
<option value="34">Kon Tum</option>
<option value="35">Lai Châu</option>
<option value="38">Lào Cai</option>
<option value="36">Lâm Đồng</option>
<option value="37">Lạng Sơn</option>
<option value="39">Long An</option>
<option value="40">Nam Định</option>
<option value="41">Nghệ An</option>
<option value="42">Ninh Bình</option>
<option value="43">Ninh Thuận</option>
<option value="44">Phú Thọ</option>
<option value="45">Phú Yên</option>
<option value="46">Quảng Bình</option>
<option value="47">Quảng Nam</option>
<option value="48">Quảng Ngãi</option>
<option value="49">Quảng Ninh</option>
<option value="50">Quảng Trị</option>
<option value="51">Sóc Trăng</option>
<option value="52">Sơn La</option>
<option value="53">Tây Ninh</option>
<option value="56">Thanh Hóa</option>
<option value="54">Thái Bình</option>
<option value="55">Thái Nguyên</option>
<option value="57">Thừa Thiên-Huế</option>
<option value="58">Tiền Giang</option>
<option value="59">Trà Vinh</option>
<option value="60">Tuyên Quang</option>
<option value="61">Vĩnh Long</option>
<option value="62">Vĩnh Phúc</option>
<option value="63">Yên Bái</option>
<option value="19">Đắk Lắk</option>
<option value="22">Đồng Nai</option>
<option value="23">Đồng Tháp</option>
<option value="21">Điện Biên</option>
<option value="20">Đăk Nông</option>
</select><b style="color: #ff0000;">*</b>
</td>
</tr>
<tr>
<td>DateCreate</td>
<td><input type="text" name="date" id="date" class="boxInput" size="50" value=""/></td>
</tr>
<tr>
<td>Địa chỉ</td>
<td><input type="text" name="diachi" id="diachi" class="boxInput" size="50" value=""/><b style="color: #ff0000;">*</b></td>
</tr>
<tr>
<td>
<input type="submit" value="Thêm" class="btn_1" id="note"/>
</td>
</tr>
</table>
</td>
</tr>
</table></fieldset>
</form>
<script type="text/javascript">
function check_field() {
var error = "";
var Email = document.getElementById('Email').value;
if (Email.length <10) error += "- Bạn chưa nhập email\n";
var phone = document.getElementById('phone').value;
if (phone.length <1) error += "- Bạn chưa nhập số điện thoại\n";
var diachi = document.getElementById('diachi').value;
if (diachi.length <1) error += "- Bạn chưa nhập địa chỉ\n";
var Name = document.getElementById('Name').value;
if (Name.length < 3) error += "- Bạn chưa nhập tên";
if (error != "") {
alert(error);
return false;
}
return true;
}
</script>
| 11cntt3 | formAdd.php | Hack | epl | 11,146 |
<html>
<head>
<title>bai3</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href=../style/mystyle.css rel=stylesheet type="text/css"></link>
</head>
<body>
<ul>
<li><a href="trangchu.php">Update</a></li>
</li>
</ul>
<h1>Update Database</h1>
<?php
$con=@mysqli_connect("localhost","root","","it3");
if(!$con) die("Connection failed");
$row = 0;
mysqli_query($con,"set names utf8");
if (($handle = fopen("user.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
if($row >=2){
for ($c=0; $c < $num; $c++) {
$sql="Insert Into user
values( '$data[0]', '$data[1]','$data[2]','$data[3]','$data[4]')";
$rs=@mysqli_query($con,$sql);
}
echo "Update thông tin thành công";
}
}
fclose($handle);
mysqli_close($con);
}
?>
</body>
</html> | 11cntt3 | update.php | PHP | epl | 945 |
<form method="post" name="contact" onsubmit="return check_field();">
<fieldset style="border: none;" class="shadow cor">
<div class="bgg_in_spm"></div>
<table width="100%" id="register">
<tr>
<td valign="top">
<table cellpadding="4" cellspacing="0" id="tb_register" style="width: 100%;">
<tr>
<td width="150px">FullName</td>
<td><input type="text" name="name" id="Name" class="boxInput" size="20"/><b style="color: #ff0000;">*</b>
</td>
</tr>
<tr>
<td width="150px">Email</td>
<td><input type="text" name="email" id="Email" class="boxInput" size="20"/><b style="color: #ff0000;">*</b>
</td>
</tr>
<tr>
<td>Phone</td>
<td><input type="number" name="phone" id="phone" class="boxInput" size="20"/> <b style="color: #ff0000;">*</b> <span class="explain"></span></td>
</tr>
<tr>
<td>Website</td>
<td><input type="text" name="website" id="web" class="boxInput" size="20" />
<span class="explain"></span></td>
</tr>
<tr>
<td>Content</td>
<td><input type="text" name="content" id="content" class="boxInput" size="40" value=""/></td>
</tr>
<tr>
<td>Giới tính</td>
<td>
<input type="radio" checked="checked" name="sex" value="male" />Nam <input type="radio" name="sex" value="female" />Nữ
</td>
</tr>
<tr>
<td>Tỉnh/Tp</td>
<td>
<select name="province" id="Province_City">
<option value="1">Hà Nội</option>
<option value="2">TP HCM</option>
<option value="5">Hải Phòng</option>
<option value="4">Đà Nẵng</option>
<option value="6">An Giang</option>
<option value="7">Bà Rịa-Vũng Tàu</option>
<option value="13">Bình Dương</option>
<option value="15">Bình Phước</option>
<option value="16">Bình Thuận</option>
<option value="14">Bình Định</option>
<option value="8">Bạc Liêu</option>
<option value="10">Bắc Giang</option>
<option value="9">Bắc Kạn</option>
<option value="11">Bắc Ninh</option>
<option value="12">Bến Tre</option>
<option value="18">Cao Bằng</option>
<option value="17">Cà Mau</option>
<option value="3">Cần Thơ</option>
<option value="24">Gia Lai</option>
<option value="25">Hà Giang</option>
<option value="26">Hà Nam</option>
<option value="27">Hà Tĩnh</option>
<option value="30">Hòa Bình</option>
<option value="28">Hải Dương</option>
<option value="29">Hậu Giang</option>
<option value="31">Hưng Yên</option>
<option value="32">Khánh Hòa</option>
<option value="33">Kiên Giang</option>
<option value="34">Kon Tum</option>
<option value="35">Lai Châu</option>
<option value="38">Lào Cai</option>
<option value="36">Lâm Đồng</option>
<option value="37">Lạng Sơn</option>
<option value="39">Long An</option>
<option value="40">Nam Định</option>
<option value="41">Nghệ An</option>
<option value="42">Ninh Bình</option>
<option value="43">Ninh Thuận</option>
<option value="44">Phú Thọ</option>
<option value="45">Phú Yên</option>
<option value="46">Quảng Bình</option>
<option value="47">Quảng Nam</option>
<option value="48">Quảng Ngãi</option>
<option value="49">Quảng Ninh</option>
<option value="50">Quảng Trị</option>
<option value="51">Sóc Trăng</option>
<option value="52">Sơn La</option>
<option value="53">Tây Ninh</option>
<option value="56">Thanh Hóa</option>
<option value="54">Thái Bình</option>
<option value="55">Thái Nguyên</option>
<option value="57">Thừa Thiên-Huế</option>
<option value="58">Tiền Giang</option>
<option value="59">Trà Vinh</option>
<option value="60">Tuyên Quang</option>
<option value="61">Vĩnh Long</option>
<option value="62">Vĩnh Phúc</option>
<option value="63">Yên Bái</option>
<option value="19">Đắk Lắk</option>
<option value="22">Đồng Nai</option>
<option value="23">Đồng Tháp</option>
<option value="21">Điện Biên</option>
<option value="20">Đăk Nông</option>
</select><b style="color: #ff0000;">*</b>
</td>
</tr>
<tr>
<td>DateEdit</td>
<td><input type="text" name="date" id="date" class="boxInput" size="50" value=""/></td>
</tr>
<tr>
<td>Địa chỉ</td>
<td><input type="text" name="diachi" id="diachi" class="boxInput" size="50" value=""/><b style="color: #ff0000;">*</b></td>
</tr>
<tr>
<td>
<input type="submit" value="Sửa" class="btn_1" id="note"/>
</td>
</tr>
</table>
</td>
</tr>
</table></fieldset>
</form>
<script type="text/javascript">
function check_field() {
var error = "";
var Email = document.getElementById('Email').value;
if (Email.length <10) error += "- Bạn chưa nhập email\n";
var phone = document.getElementById('phone').value;
if (phone.length <1) error += "- Bạn chưa nhập số điện thoại\n";
var diachi = document.getElementById('diachi').value;
if (diachi.length <1) error += "- Bạn chưa nhập địa chỉ\n";
var Name = document.getElementById('Name').value;
if (Name.length < 3) error += "- Bạn chưa nhập tên";
if (error != "") {
alert(error);
return false;
}
return true;
}
</script>
| 11cntt3 | formEdit.php | Hack | epl | 11,144 |
$conn=mysql_connect("localhost","root","root") or die(" khong the ket noi");
mysql_select_db("it3"); | 11cntt3 | hàm connectdatabasestudentinformation.php | PHP | epl | 101 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mahoamd5;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
*
* @author PC-PC
*/
public class MahoaMD5 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
public boolean isValidAccount(String userName, String password) {
String hashtext = convertMD5(password);
System.out.println("password MD5: " + hashtext);
// if (checkMember(userName, hashtext) > 0) {
// return true;
// }
return false;
}
public static String convertMD5(String password) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
byte[] digit = md.digest();
BigInteger bigInt = new BigInteger(1, digit);
String hashtext = bigInt.toString(16);
return hashtext;
} catch (NoSuchAlgorithmException e) {
} catch (NullPointerException ex) {
System.out.println(ex);
}
return null;
}
}
| 11cntt3 | MahoaMD5.java | Java | epl | 1,400 |
/*
Copyright 2013 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#include "zlib_container.h"
#include "util.h"
#include <stdio.h>
#include "deflate.h"
/* Calculates the adler32 checksum of the data */
static unsigned adler32(const unsigned char* data, size_t size)
{
static const unsigned sums_overflow = 5550;
unsigned s1 = 1;
unsigned s2 = 1 >> 16;
while (size > 0) {
size_t amount = size > sums_overflow ? sums_overflow : size;
size -= amount;
while (amount > 0) {
s1 += (*data++);
s2 += s1;
amount--;
}
s1 %= 65521;
s2 %= 65521;
}
return (s2 << 16) | s1;
}
void ZopfliZlibCompress(const ZopfliOptions* options,
const unsigned char* in, size_t insize,
unsigned char** out, size_t* outsize) {
unsigned char bitpointer = 0;
unsigned checksum = adler32(in, (unsigned)insize);
unsigned cmf = 120; /* CM 8, CINFO 7. See zlib spec.*/
unsigned flevel = 0;
unsigned fdict = 0;
unsigned cmfflg = 256 * cmf + fdict * 32 + flevel * 64;
unsigned fcheck = 31 - cmfflg % 31;
cmfflg += fcheck;
ZOPFLI_APPEND_DATA(cmfflg / 256, out, outsize);
ZOPFLI_APPEND_DATA(cmfflg % 256, out, outsize);
ZopfliDeflate(options, 2 /* dynamic block */, 1 /* final */,
in, insize, &bitpointer, out, outsize);
ZOPFLI_APPEND_DATA((checksum >> 24) % 256, out, outsize);
ZOPFLI_APPEND_DATA((checksum >> 16) % 256, out, outsize);
ZOPFLI_APPEND_DATA((checksum >> 8) % 256, out, outsize);
ZOPFLI_APPEND_DATA(checksum % 256, out, outsize);
if (options->verbose) {
fprintf(stderr,
"Original Size: %d, Zlib: %d, Compression: %f%% Removed\n",
(int)insize, (int)*outsize,
100.0 * (double)(insize - *outsize) / (double)insize);
}
}
| 06zhangxu-c | zlib_container.c | C | asf20 | 2,415 |
/*
Copyright 2011 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
Zopfli compressor program. It can output gzip-, zlib- or deflate-compatible
data. By default it creates a .gz file. This tool can only compress, not
decompress. Decompression can be done by any standard gzip, zlib or deflate
decompressor.
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "deflate.h"
#include "gzip_container.h"
#include "zlib_container.h"
/*
Loads a file into a memory array.
*/
static void LoadFile(const char* filename,
unsigned char** out, size_t* outsize) {
FILE* file;
*out = 0;
*outsize = 0;
file = fopen(filename, "rb");
if (!file) return;
fseek(file , 0 , SEEK_END);
*outsize = ftell(file);
rewind(file);
*out = (unsigned char*)malloc(*outsize);
if (*outsize && (*out)) {
size_t testsize = fread(*out, 1, *outsize, file);
if (testsize != *outsize) {
/* It could be a directory */
free(*out);
*out = 0;
*outsize = 0;
}
}
assert(!(*outsize) || out); /* If size is not zero, out must be allocated. */
fclose(file);
}
/*
Saves a file from a memory array, overwriting the file if it existed.
*/
static void SaveFile(const char* filename,
const unsigned char* in, size_t insize) {
FILE* file = fopen(filename, "wb" );
assert(file);
fwrite((char*)in, 1, insize, file);
fclose(file);
}
/*
outfilename: filename to write output to, or 0 to write to stdout instead
*/
static void CompressFile(const ZopfliOptions* options,
ZopfliFormat output_type,
const char* infilename,
const char* outfilename) {
unsigned char* in;
size_t insize;
unsigned char* out = 0;
size_t outsize = 0;
LoadFile(infilename, &in, &insize);
if (insize == 0) {
fprintf(stderr, "Invalid filename: %s\n", infilename);
return;
}
ZopfliCompress(options, output_type, in, insize, &out, &outsize);
if (outfilename) {
SaveFile(outfilename, out, outsize);
} else {
size_t i;
for (i = 0; i < outsize; i++) {
/* Works only if terminal does not convert newlines. */
printf("%c", out[i]);
}
}
free(out);
free(in);
}
/*
Add two strings together. Size does not matter. Result must be freed.
*/
static char* AddStrings(const char* str1, const char* str2) {
size_t len = strlen(str1) + strlen(str2);
char* result = (char*)malloc(len + 1);
if (!result) exit(-1); /* Allocation failed. */
strcpy(result, str1);
strcat(result, str2);
return result;
}
static char StringsEqual(const char* str1, const char* str2) {
return strcmp(str1, str2) == 0;
}
int main(int argc, char* argv[]) {
ZopfliOptions options;
ZopfliFormat output_type = ZOPFLI_FORMAT_GZIP;
const char* filename = 0;
int output_to_stdout = 0;
int i;
ZopfliInitOptions(&options);
for (i = 1; i < argc; i++) {
const char* arg = argv[i];
if (StringsEqual(arg, "-v")) options.verbose = 1;
else if (StringsEqual(arg, "-c")) output_to_stdout = 1;
else if (StringsEqual(arg, "--deflate")) {
output_type = ZOPFLI_FORMAT_DEFLATE;
}
else if (StringsEqual(arg, "--zlib")) output_type = ZOPFLI_FORMAT_ZLIB;
else if (StringsEqual(arg, "--gzip")) output_type = ZOPFLI_FORMAT_GZIP;
else if (StringsEqual(arg, "--splitlast")) options.blocksplittinglast = 1;
else if (arg[0] == '-' && arg[1] == '-' && arg[2] == 'i'
&& arg[3] >= '0' && arg[3] <= '9') {
options.numiterations = atoi(arg + 3);
}
else if (StringsEqual(arg, "-h")) {
fprintf(stderr,
"Usage: zopfli [OPTION]... FILE\n"
" -h gives this help\n"
" -c write the result on standard output, instead of disk"
" filename + '.gz'\n"
" -v verbose mode\n"
" --i# perform # iterations (default 15). More gives"
" more compression but is slower."
" Examples: --i10, --i50, --i1000\n");
fprintf(stderr,
" --gzip output to gzip format (default)\n"
" --zlib output to zlib format instead of gzip\n"
" --deflate output to deflate format instead of gzip\n"
" --splitlast do block splitting last instead of first\n");
return 0;
}
}
if (options.numiterations < 1) {
fprintf(stderr, "Error: must have 1 or more iterations");
return 0;
}
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-') {
char* outfilename;
filename = argv[i];
if (output_to_stdout) {
outfilename = 0;
} else if (output_type == ZOPFLI_FORMAT_GZIP) {
outfilename = AddStrings(filename, ".gz");
} else if (output_type == ZOPFLI_FORMAT_ZLIB) {
outfilename = AddStrings(filename, ".zlib");
} else {
assert(output_type == ZOPFLI_FORMAT_DEFLATE);
outfilename = AddStrings(filename, ".deflate");
}
if (options.verbose && outfilename) {
fprintf(stderr, "Saving to: %s\n", outfilename);
}
CompressFile(&options, output_type, filename, outfilename);
free(outfilename);
}
}
if (!filename) {
fprintf(stderr,
"Please provide filename\nFor help, type: %s -h\n", argv[0]);
}
return 0;
}
| 06zhangxu-c | zopfli_bin.c | C | asf20 | 5,933 |
/*
Copyright 2011 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#ifndef ZOPFLI_DEFLATE_H_
#define ZOPFLI_DEFLATE_H_
/*
Functions to compress according to the DEFLATE specification, using the
"squeeze" LZ77 compression backend.
*/
#include "zopfli.h"
/*
Compresses according to the deflate specification and append the compressed
result to the output.
This function will usually output multiple deflate blocks. If final is 1, then
the final bit will be set on the last block.
options: global program options
btype: the deflate block type. Use 2 for best compression.
-0: non compressed blocks (00)
-1: blocks with fixed tree (01)
-2: blocks with dynamic tree (10)
final: whether this is the last section of the input, sets the final bit to the
last deflate block.
in: the input bytes
insize: number of input bytes
bp: bit pointer for the output array. This must initially be 0, and for
consecutive calls must be reused (it can have values from 0-7). This is
because deflate appends blocks as bit-based data, rather than on byte
boundaries.
out: pointer to the dynamic output array to which the result is appended. Must
be freed after use.
outsize: pointer to the dynamic output array size.
*/
void ZopfliDeflate(const ZopfliOptions* options, int btype, int final,
const unsigned char* in, size_t insize,
unsigned char* bp, unsigned char** out, size_t* outsize);
/*
Like ZopfliDeflate, but allows to specify start and end byte with instart and
inend. Only that part is compressed, but earlier bytes are still used for the
back window.
*/
void ZopfliDeflatePart(const ZopfliOptions* options, int btype, int final,
const unsigned char* in, size_t instart, size_t inend,
unsigned char* bp, unsigned char** out,
size_t* outsize);
/*
Calculates block size in bits.
litlens: lz77 lit/lengths
dists: ll77 distances
lstart: start of block
lend: end of block (not inclusive)
*/
double ZopfliCalculateBlockSize(const unsigned short* litlens,
const unsigned short* dists,
size_t lstart, size_t lend, int btype);
#endif /* ZOPFLI_DEFLATE_H_ */
| 06zhangxu-c | deflate.h | C | asf20 | 2,847 |
/*
Copyright 2011 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
Functions for basic LZ77 compression and utilities for the "squeeze" LZ77
compression.
*/
#ifndef ZOPFLI_LZ77_H_
#define ZOPFLI_LZ77_H_
#include <stdlib.h>
#include "cache.h"
#include "hash.h"
#include "zopfli.h"
/*
Stores lit/length and dist pairs for LZ77.
litlens: Contains the literal symbols or length values.
dists: Indicates the distance, or 0 to indicate that there is no distance and
litlens contains a literal instead of a length.
litlens and dists both have the same size.
*/
typedef struct ZopfliLZ77Store {
unsigned short* litlens; /* Lit or len. */
unsigned short* dists; /* If 0: indicates literal in corresponding litlens,
if > 0: length in corresponding litlens, this is the distance. */
size_t size;
} ZopfliLZ77Store;
void ZopfliInitLZ77Store(ZopfliLZ77Store* store);
void ZopfliCleanLZ77Store(ZopfliLZ77Store* store);
void ZopfliCopyLZ77Store(const ZopfliLZ77Store* source, ZopfliLZ77Store* dest);
void ZopfliStoreLitLenDist(unsigned short length, unsigned short dist,
ZopfliLZ77Store* store);
/*
Some state information for compressing a block.
This is currently a bit under-used (with mainly only the longest match cache),
but is kept for easy future expansion.
*/
typedef struct ZopfliBlockState {
const ZopfliOptions* options;
#ifdef ZOPFLI_LONGEST_MATCH_CACHE
/* Cache for length/distance pairs found so far. */
ZopfliLongestMatchCache* lmc;
#endif
/* The start (inclusive) and end (not inclusive) of the current block. */
size_t blockstart;
size_t blockend;
} ZopfliBlockState;
/*
Finds the longest match (length and corresponding distance) for LZ77
compression.
Even when not using "sublen", it can be more efficient to provide an array,
because only then the caching is used.
array: the data
pos: position in the data to find the match for
size: size of the data
limit: limit length to maximum this value (default should be 258). This allows
finding a shorter dist for that length (= less extra bits). Must be
in the range [ZOPFLI_MIN_MATCH, ZOPFLI_MAX_MATCH].
sublen: output array of 259 elements, or null. Has, for each length, the
smallest distance required to reach this length. Only 256 of its 259 values
are used, the first 3 are ignored (the shortest length is 3. It is purely
for convenience that the array is made 3 longer).
*/
void ZopfliFindLongestMatch(
ZopfliBlockState *s, const ZopfliHash* h, const unsigned char* array,
size_t pos, size_t size, size_t limit,
unsigned short* sublen, unsigned short* distance, unsigned short* length);
/*
Verifies if length and dist are indeed valid, only used for assertion.
*/
void ZopfliVerifyLenDist(const unsigned char* data, size_t datasize, size_t pos,
unsigned short dist, unsigned short length);
/*
Counts the number of literal, length and distance symbols in the given lz77
arrays.
litlens: lz77 lit/lengths
dists: ll77 distances
start: where to begin counting in litlens and dists
end: where to stop counting in litlens and dists (not inclusive)
ll_count: count of each lit/len symbol, must have size 288 (see deflate
standard)
d_count: count of each dist symbol, must have size 32 (see deflate standard)
*/
void ZopfliLZ77Counts(const unsigned short* litlens,
const unsigned short* dists,
size_t start, size_t end,
size_t* ll_count, size_t* d_count);
/*
Does LZ77 using an algorithm similar to gzip, with lazy matching, rather than
with the slow but better "squeeze" implementation.
The result is placed in the ZopfliLZ77Store.
If instart is larger than 0, it uses values before instart as starting
dictionary.
*/
void ZopfliLZ77Greedy(ZopfliBlockState* s, const unsigned char* in,
size_t instart, size_t inend,
ZopfliLZ77Store* store);
#endif /* ZOPFLI_LZ77_H_ */
| 06zhangxu-c | lz77.h | C | asf20 | 4,580 |
/*
Copyright 2011 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#include "tree.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "katajainen.h"
#include "util.h"
void ZopfliLengthsToSymbols(const unsigned* lengths, size_t n, unsigned maxbits,
unsigned* symbols) {
size_t* bl_count = (size_t*)malloc(sizeof(size_t) * (maxbits + 1));
size_t* next_code = (size_t*)malloc(sizeof(size_t) * (maxbits + 1));
unsigned bits, i;
unsigned code;
for (i = 0; i < n; i++) {
symbols[i] = 0;
}
/* 1) Count the number of codes for each code length. Let bl_count[N] be the
number of codes of length N, N >= 1. */
for (bits = 0; bits <= maxbits; bits++) {
bl_count[bits] = 0;
}
for (i = 0; i < n; i++) {
assert(lengths[i] <= maxbits);
bl_count[lengths[i]]++;
}
/* 2) Find the numerical value of the smallest code for each code length. */
code = 0;
bl_count[0] = 0;
for (bits = 1; bits <= maxbits; bits++) {
code = (code + bl_count[bits-1]) << 1;
next_code[bits] = code;
}
/* 3) Assign numerical values to all codes, using consecutive values for all
codes of the same length with the base values determined at step 2. */
for (i = 0; i < n; i++) {
unsigned len = lengths[i];
if (len != 0) {
symbols[i] = next_code[len];
next_code[len]++;
}
}
free(bl_count);
free(next_code);
}
void ZopfliCalculateEntropy(const size_t* count, size_t n, double* bitlengths) {
static const double kInvLog2 = 1.4426950408889; /* 1.0 / log(2.0) */
unsigned sum = 0;
unsigned i;
double log2sum;
for (i = 0; i < n; ++i) {
sum += count[i];
}
log2sum = (sum == 0 ? log(n) : log(sum)) * kInvLog2;
for (i = 0; i < n; ++i) {
/* When the count of the symbol is 0, but its cost is requested anyway, it
means the symbol will appear at least once anyway, so give it the cost as if
its count is 1.*/
if (count[i] == 0) bitlengths[i] = log2sum;
else bitlengths[i] = log2sum - log(count[i]) * kInvLog2;
/* Depending on compiler and architecture, the above subtraction of two
floating point numbers may give a negative result very close to zero
instead of zero (e.g. -5.973954e-17 with gcc 4.1.2 on Ubuntu 11.4). Clamp
it to zero. These floating point imprecisions do not affect the cost model
significantly so this is ok. */
if (bitlengths[i] < 0 && bitlengths[i] > -1e-5) bitlengths[i] = 0;
assert(bitlengths[i] >= 0);
}
}
void ZopfliCalculateBitLengths(const size_t* count, size_t n, int maxbits,
unsigned* bitlengths) {
int error = ZopfliLengthLimitedCodeLengths(count, n, maxbits, bitlengths);
(void) error;
assert(!error);
}
| 06zhangxu-c | tree.c | C | asf20 | 3,375 |
/*
Copyright 2011 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#include "cache.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef ZOPFLI_LONGEST_MATCH_CACHE
void ZopfliInitCache(size_t blocksize, ZopfliLongestMatchCache* lmc) {
size_t i;
lmc->length = (unsigned short*)malloc(sizeof(unsigned short) * blocksize);
lmc->dist = (unsigned short*)malloc(sizeof(unsigned short) * blocksize);
/* Rather large amount of memory. */
lmc->sublen = (unsigned char*)malloc(ZOPFLI_CACHE_LENGTH * 3 * blocksize);
/* length > 0 and dist 0 is invalid combination, which indicates on purpose
that this cache value is not filled in yet. */
for (i = 0; i < blocksize; i++) lmc->length[i] = 1;
for (i = 0; i < blocksize; i++) lmc->dist[i] = 0;
for (i = 0; i < ZOPFLI_CACHE_LENGTH * blocksize * 3; i++) lmc->sublen[i] = 0;
}
void ZopfliCleanCache(ZopfliLongestMatchCache* lmc) {
free(lmc->length);
free(lmc->dist);
free(lmc->sublen);
}
void ZopfliSublenToCache(const unsigned short* sublen,
size_t pos, size_t length,
ZopfliLongestMatchCache* lmc) {
size_t i;
size_t j = 0;
unsigned bestlength = 0;
unsigned char* cache;
#if ZOPFLI_CACHE_LENGTH == 0
return;
#endif
cache = &lmc->sublen[ZOPFLI_CACHE_LENGTH * pos * 3];
if (length < 3) return;
for (i = 3; i <= length; i++) {
if (i == length || sublen[i] != sublen[i + 1]) {
cache[j * 3] = i - 3;
cache[j * 3 + 1] = sublen[i] % 256;
cache[j * 3 + 2] = (sublen[i] >> 8) % 256;
bestlength = i;
j++;
if (j >= ZOPFLI_CACHE_LENGTH) break;
}
}
if (j < ZOPFLI_CACHE_LENGTH) {
assert(bestlength == length);
cache[(ZOPFLI_CACHE_LENGTH - 1) * 3] = bestlength - 3;
} else {
assert(bestlength <= length);
}
assert(bestlength == ZopfliMaxCachedSublen(lmc, pos, length));
}
void ZopfliCacheToSublen(const ZopfliLongestMatchCache* lmc,
size_t pos, size_t length,
unsigned short* sublen) {
size_t i, j;
unsigned maxlength = ZopfliMaxCachedSublen(lmc, pos, length);
unsigned prevlength = 0;
unsigned char* cache;
#if ZOPFLI_CACHE_LENGTH == 0
return;
#endif
if (length < 3) return;
cache = &lmc->sublen[ZOPFLI_CACHE_LENGTH * pos * 3];
for (j = 0; j < ZOPFLI_CACHE_LENGTH; j++) {
unsigned length = cache[j * 3] + 3;
unsigned dist = cache[j * 3 + 1] + 256 * cache[j * 3 + 2];
for (i = prevlength; i <= length; i++) {
sublen[i] = dist;
}
if (length == maxlength) break;
prevlength = length + 1;
}
}
/*
Returns the length up to which could be stored in the cache.
*/
unsigned ZopfliMaxCachedSublen(const ZopfliLongestMatchCache* lmc,
size_t pos, size_t length) {
unsigned char* cache;
#if ZOPFLI_CACHE_LENGTH == 0
return 0;
#endif
cache = &lmc->sublen[ZOPFLI_CACHE_LENGTH * pos * 3];
(void)length;
if (cache[1] == 0 && cache[2] == 0) return 0; /* No sublen cached. */
return cache[(ZOPFLI_CACHE_LENGTH - 1) * 3] + 3;
}
#endif /* ZOPFLI_LONGEST_MATCH_CACHE */
| 06zhangxu-c | cache.c | C | asf20 | 3,717 |
/*
Copyright 2011 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
The hash for ZopfliFindLongestMatch of lz77.c.
*/
#ifndef ZOPFLI_HASH_H_
#define ZOPFLI_HASH_H_
#include "util.h"
typedef struct ZopfliHash {
int* head; /* Hash value to index of its most recent occurance. */
unsigned short* prev; /* Index to index of prev. occurance of same hash. */
int* hashval; /* Index to hash value at this index. */
int val; /* Current hash value. */
#ifdef ZOPFLI_HASH_SAME_HASH
/* Fields with similar purpose as the above hash, but for the second hash with
a value that is calculated differently. */
int* head2; /* Hash value to index of its most recent occurance. */
unsigned short* prev2; /* Index to index of prev. occurance of same hash. */
int* hashval2; /* Index to hash value at this index. */
int val2; /* Current hash value. */
#endif
#ifdef ZOPFLI_HASH_SAME
unsigned short* same; /* Amount of repetitions of same byte after this .*/
#endif
} ZopfliHash;
/* Allocates and initializes all fields of ZopfliHash. */
void ZopfliInitHash(size_t window_size, ZopfliHash* h);
/* Frees all fields of ZopfliHash. */
void ZopfliCleanHash(ZopfliHash* h);
/*
Updates the hash values based on the current position in the array. All calls
to this must be made for consecutive bytes.
*/
void ZopfliUpdateHash(const unsigned char* array, size_t pos, size_t end,
ZopfliHash* h);
/*
Prepopulates hash:
Fills in the initial values in the hash, before ZopfliUpdateHash can be used
correctly.
*/
void ZopfliWarmupHash(const unsigned char* array, size_t pos, size_t end,
ZopfliHash* h);
#endif /* ZOPFLI_HASH_H_ */
| 06zhangxu-c | hash.h | C | asf20 | 2,305 |
/*
Copyright 2011 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
The squeeze functions do enhanced LZ77 compression by optimal parsing with a
cost model, rather than greedily choosing the longest length or using a single
step of lazy matching like regular implementations.
Since the cost model is based on the Huffman tree that can only be calculated
after the LZ77 data is generated, there is a chicken and egg problem, and
multiple runs are done with updated cost models to converge to a better
solution.
*/
#ifndef ZOPFLI_SQUEEZE_H_
#define ZOPFLI_SQUEEZE_H_
#include "lz77.h"
/*
Calculates lit/len and dist pairs for given data.
If instart is larger than 0, it uses values before instart as starting
dictionary.
*/
void ZopfliLZ77Optimal(ZopfliBlockState *s,
const unsigned char* in, size_t instart, size_t inend,
ZopfliLZ77Store* store);
/*
Does the same as ZopfliLZ77Optimal, but optimized for the fixed tree of the
deflate standard.
The fixed tree never gives the best compression. But this gives the best
possible LZ77 encoding possible with the fixed tree.
This does not create or output any fixed tree, only LZ77 data optimized for
using with a fixed tree.
If instart is larger than 0, it uses values before instart as starting
dictionary.
*/
void ZopfliLZ77OptimalFixed(ZopfliBlockState *s,
const unsigned char* in,
size_t instart, size_t inend,
ZopfliLZ77Store* store);
#endif /* ZOPFLI_SQUEEZE_H_ */
| 06zhangxu-c | squeeze.h | C | asf20 | 2,175 |
make:
gcc *.c -O2 -W -Wall -Wextra -ansi -pedantic -lm -o zopfli
debug:
gcc *.c -g3 -lm -o zopfli
| 06zhangxu-c | makefile | Makefile | asf20 | 101 |
/*
Copyright 2011 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#ifndef ZOPFLI_ZOPFLI_H_
#define ZOPFLI_ZOPFLI_H_
#include <stdlib.h> /* for size_t */
/*
Options used throughout the program.
*/
typedef struct ZopfliOptions {
/* Whether to print output */
int verbose;
/* Whether to print more detailed output */
int verbose_more;
/*
Maximum amount of times to rerun forward and backward pass to optimize LZ77
compression cost. Good values: 10, 15 for small files, 5 for files over
several MB in size or it will be too slow.
*/
int numiterations;
/*
If true, splits the data in multiple deflate blocks with optimal choice
for the block boundaries. Block splitting gives better compression. Default:
true (1).
*/
int blocksplitting;
/*
If true, chooses the optimal block split points only after doing the iterative
LZ77 compression. If false, chooses the block split points first, then does
iterative LZ77 on each individual block. Depending on the file, either first
or last gives the best compression. Default: false (0).
*/
int blocksplittinglast;
/*
Maximum amount of blocks to split into (0 for unlimited, but this can give
extreme results that hurt compression on some files). Default value: 15.
*/
int blocksplittingmax;
} ZopfliOptions;
/* Initializes options with default values. */
void ZopfliInitOptions(ZopfliOptions* options);
/* Output format */
typedef enum {
ZOPFLI_FORMAT_GZIP,
ZOPFLI_FORMAT_ZLIB,
ZOPFLI_FORMAT_DEFLATE
} ZopfliFormat;
/*
Compresses according to the given output format and appends the result to the
output.
options: global program options
output_type: the output format to use
out: pointer to the dynamic output array to which the result is appended. Must
be freed after use
outsize: pointer to the dynamic output array size
*/
void ZopfliCompress(const ZopfliOptions* options, ZopfliFormat output_type,
const unsigned char* in, size_t insize,
unsigned char** out, size_t* outsize);
#endif /* ZOPFLI_ZOPFLI_H_ */
| 06zhangxu-c | zopfli.h | C | asf20 | 2,686 |
/*
Copyright 2011 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
Utilities for creating and using Huffman trees.
*/
#ifndef ZOPFLI_TREE_H_
#define ZOPFLI_TREE_H_
#include <string.h>
/*
Calculates the bitlengths for the Huffman tree, based on the counts of each
symbol.
*/
void ZopfliCalculateBitLengths(const size_t* count, size_t n, int maxbits,
unsigned *bitlengths);
/*
Converts a series of Huffman tree bitlengths, to the bit values of the symbols.
*/
void ZopfliLengthsToSymbols(const unsigned* lengths, size_t n, unsigned maxbits,
unsigned* symbols);
/*
Calculates the entropy of each symbol, based on the counts of each symbol. The
result is similar to the result of ZopfliCalculateBitLengths, but with the
actual theoritical bit lengths according to the entropy. Since the resulting
values are fractional, they cannot be used to encode the tree specified by
DEFLATE.
*/
void ZopfliCalculateEntropy(const size_t* count, size_t n, double* bitlengths);
#endif /* ZOPFLI_TREE_H_ */
| 06zhangxu-c | tree.h | C | asf20 | 1,677 |
/*
Copyright 2011 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#include "blocksplitter.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "deflate.h"
#include "lz77.h"
#include "squeeze.h"
#include "tree.h"
#include "util.h"
/*
The "f" for the FindMinimum function below.
i: the current parameter of f(i)
context: for your implementation
*/
typedef double FindMinimumFun(size_t i, void* context);
/*
Finds minimum of function f(i) where is is of type size_t, f(i) is of type
double, i is in range start-end (excluding end).
*/
static size_t FindMinimum(FindMinimumFun f, void* context,
size_t start, size_t end) {
if (end - start < 1024) {
double best = ZOPFLI_LARGE_FLOAT;
size_t result = start;
size_t i;
for (i = start; i < end; i++) {
double v = f(i, context);
if (v < best) {
best = v;
result = i;
}
}
return result;
} else {
/* Try to find minimum faster by recursively checking multiple points. */
#define NUM 9 /* Good value: 9. */
size_t i;
size_t p[NUM];
double vp[NUM];
size_t besti;
double best;
double lastbest = ZOPFLI_LARGE_FLOAT;
size_t pos = start;
for (;;) {
if (end - start <= NUM) break;
for (i = 0; i < NUM; i++) {
p[i] = start + (i + 1) * ((end - start) / (NUM + 1));
vp[i] = f(p[i], context);
}
besti = 0;
best = vp[0];
for (i = 1; i < NUM; i++) {
if (vp[i] < best) {
best = vp[i];
besti = i;
}
}
if (best > lastbest) break;
start = besti == 0 ? start : p[besti - 1];
end = besti == NUM - 1 ? end : p[besti + 1];
pos = p[besti];
lastbest = best;
}
return pos;
#undef NUM
}
}
/*
Returns estimated cost of a block in bits. It includes the size to encode the
tree and the size to encode all literal, length and distance symbols and their
extra bits.
litlens: lz77 lit/lengths
dists: ll77 distances
lstart: start of block
lend: end of block (not inclusive)
*/
static double EstimateCost(const unsigned short* litlens,
const unsigned short* dists,
size_t lstart, size_t lend) {
return ZopfliCalculateBlockSize(litlens, dists, lstart, lend, 2);
}
typedef struct SplitCostContext {
const unsigned short* litlens;
const unsigned short* dists;
size_t llsize;
size_t start;
size_t end;
} SplitCostContext;
/*
Gets the cost which is the sum of the cost of the left and the right section
of the data.
type: FindMinimumFun
*/
static double SplitCost(size_t i, void* context) {
SplitCostContext* c = (SplitCostContext*)context;
return EstimateCost(c->litlens, c->dists, c->start, i) +
EstimateCost(c->litlens, c->dists, i, c->end);
}
static void AddSorted(size_t value, size_t** out, size_t* outsize) {
size_t i;
ZOPFLI_APPEND_DATA(value, out, outsize);
if (*outsize > 0) {
for (i = 0; i < *outsize - 1; i++) {
if ((*out)[i] > value) {
size_t j;
for (j = *outsize - 1; j > i; j--) {
(*out)[j] = (*out)[j - 1];
}
(*out)[i] = value;
break;
}
}
}
}
/*
Prints the block split points as decimal and hex values in the terminal.
*/
static void PrintBlockSplitPoints(const unsigned short* litlens,
const unsigned short* dists,
size_t llsize, const size_t* lz77splitpoints,
size_t nlz77points) {
size_t* splitpoints = 0;
size_t npoints = 0;
size_t i;
/* The input is given as lz77 indices, but we want to see the uncompressed
index values. */
size_t pos = 0;
if (nlz77points > 0) {
for (i = 0; i < llsize; i++) {
size_t length = dists[i] == 0 ? 1 : litlens[i];
if (lz77splitpoints[npoints] == i) {
ZOPFLI_APPEND_DATA(pos, &splitpoints, &npoints);
if (npoints == nlz77points) break;
}
pos += length;
}
}
assert(npoints == nlz77points);
fprintf(stderr, "block split points: ");
for (i = 0; i < npoints; i++) {
fprintf(stderr, "%d ", (int)splitpoints[i]);
}
fprintf(stderr, "(hex:");
for (i = 0; i < npoints; i++) {
fprintf(stderr, " %x", (int)splitpoints[i]);
}
fprintf(stderr, ")\n");
free(splitpoints);
}
/*
Finds next block to try to split, the largest of the available ones.
The largest is chosen to make sure that if only a limited amount of blocks is
requested, their sizes are spread evenly.
llsize: the size of the LL77 data, which is the size of the done array here.
done: array indicating which blocks starting at that position are no longer
splittable (splitting them increases rather than decreases cost).
splitpoints: the splitpoints found so far.
npoints: the amount of splitpoints found so far.
lstart: output variable, giving start of block.
lend: output variable, giving end of block.
returns 1 if a block was found, 0 if no block found (all are done).
*/
static int FindLargestSplittableBlock(
size_t llsize, const unsigned char* done,
const size_t* splitpoints, size_t npoints,
size_t* lstart, size_t* lend) {
size_t longest = 0;
int found = 0;
size_t i;
for (i = 0; i <= npoints; i++) {
size_t start = i == 0 ? 0 : splitpoints[i - 1];
size_t end = i == npoints ? llsize - 1 : splitpoints[i];
if (!done[start] && end - start > longest) {
*lstart = start;
*lend = end;
found = 1;
longest = end - start;
}
}
return found;
}
void ZopfliBlockSplitLZ77(const ZopfliOptions* options,
const unsigned short* litlens,
const unsigned short* dists,
size_t llsize, size_t maxblocks,
size_t** splitpoints, size_t* npoints) {
size_t lstart, lend;
size_t i;
size_t llpos = 0;
size_t numblocks = 1;
unsigned char* done;
double splitcost, origcost;
if (llsize < 10) return; /* This code fails on tiny files. */
done = (unsigned char*)malloc(llsize);
if (!done) exit(-1); /* Allocation failed. */
for (i = 0; i < llsize; i++) done[i] = 0;
lstart = 0;
lend = llsize;
for (;;) {
SplitCostContext c;
if (maxblocks > 0 && numblocks >= maxblocks) {
break;
}
c.litlens = litlens;
c.dists = dists;
c.llsize = llsize;
c.start = lstart;
c.end = lend;
assert(lstart < lend);
llpos = FindMinimum(SplitCost, &c, lstart + 1, lend);
assert(llpos > lstart);
assert(llpos < lend);
splitcost = EstimateCost(litlens, dists, lstart, llpos) +
EstimateCost(litlens, dists, llpos, lend);
origcost = EstimateCost(litlens, dists, lstart, lend);
if (splitcost > origcost || llpos == lstart + 1 || llpos == lend) {
done[lstart] = 1;
} else {
AddSorted(llpos, splitpoints, npoints);
numblocks++;
}
if (!FindLargestSplittableBlock(
llsize, done, *splitpoints, *npoints, &lstart, &lend)) {
break; /* No further split will probably reduce compression. */
}
if (lend - lstart < 10) {
break;
}
}
if (options->verbose) {
PrintBlockSplitPoints(litlens, dists, llsize, *splitpoints, *npoints);
}
free(done);
}
void ZopfliBlockSplit(const ZopfliOptions* options,
const unsigned char* in, size_t instart, size_t inend,
size_t maxblocks, size_t** splitpoints, size_t* npoints) {
size_t pos = 0;
size_t i;
ZopfliBlockState s;
size_t* lz77splitpoints = 0;
size_t nlz77points = 0;
ZopfliLZ77Store store;
ZopfliInitLZ77Store(&store);
s.options = options;
s.blockstart = instart;
s.blockend = inend;
#ifdef ZOPFLI_LONGEST_MATCH_CACHE
s.lmc = 0;
#endif
*npoints = 0;
*splitpoints = 0;
/* Unintuitively, Using a simple LZ77 method here instead of ZopfliLZ77Optimal
results in better blocks. */
ZopfliLZ77Greedy(&s, in, instart, inend, &store);
ZopfliBlockSplitLZ77(options,
store.litlens, store.dists, store.size, maxblocks,
&lz77splitpoints, &nlz77points);
/* Convert LZ77 positions to positions in the uncompressed input. */
pos = instart;
if (nlz77points > 0) {
for (i = 0; i < store.size; i++) {
size_t length = store.dists[i] == 0 ? 1 : store.litlens[i];
if (lz77splitpoints[*npoints] == i) {
ZOPFLI_APPEND_DATA(pos, splitpoints, npoints);
if (*npoints == nlz77points) break;
}
pos += length;
}
}
assert(*npoints == nlz77points);
free(lz77splitpoints);
ZopfliCleanLZ77Store(&store);
}
void ZopfliBlockSplitSimple(const unsigned char* in,
size_t instart, size_t inend,
size_t blocksize,
size_t** splitpoints, size_t* npoints) {
size_t i = instart;
while (i < inend) {
ZOPFLI_APPEND_DATA(i, splitpoints, npoints);
i += blocksize;
}
(void)in;
}
| 06zhangxu-c | blocksplitter.c | C | asf20 | 9,625 |
/*
Copyright 2011 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#ifndef ZOPFLI_KATAJAINEN_H_
#define ZOPFLI_KATAJAINEN_H_
#include <string.h>
/*
Outputs minimum-redundancy length-limited code bitlengths for symbols with the
given counts. The bitlengths are limited by maxbits.
The output is tailored for DEFLATE: symbols that never occur, get a bit length
of 0, and if only a single symbol occurs at least once, its bitlength will be 1,
and not 0 as would theoretically be needed for a single symbol.
frequencies: The amount of occurances of each symbol.
n: The amount of symbols.
maxbits: Maximum bit length, inclusive.
bitlengths: Output, the bitlengths for the symbol prefix codes.
return: 0 for OK, non-0 for error.
*/
int ZopfliLengthLimitedCodeLengths(
const size_t* frequencies, int n, int maxbits, unsigned* bitlengths);
#endif /* ZOPFLI_KATAJAINEN_H_ */
| 06zhangxu-c | katajainen.h | C | asf20 | 1,496 |
/*
Copyright 2013 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#ifndef ZOPFLI_ZLIB_H_
#define ZOPFLI_ZLIB_H_
/*
Functions to compress according to the Zlib specification.
*/
#include "zopfli.h"
/*
Compresses according to the zlib specification and append the compressed
result to the output.
options: global program options
out: pointer to the dynamic output array to which the result is appended. Must
be freed after use.
outsize: pointer to the dynamic output array size.
*/
void ZopfliZlibCompress(const ZopfliOptions* options,
const unsigned char* in, size_t insize,
unsigned char** out, size_t* outsize);
#endif /* ZOPFLI_ZLIB_H_ */
| 06zhangxu-c | zlib_container.h | C | asf20 | 1,318 |
/*
Copyright 2011 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
Bounded package merge algorithm, based on the paper
"A Fast and Space-Economical Algorithm for Length-Limited Coding
Jyrki Katajainen, Alistair Moffat, Andrew Turpin".
*/
#include "katajainen.h"
#include <assert.h>
#include <stdlib.h>
typedef struct Node Node;
/*
Nodes forming chains. Also used to represent leaves.
*/
struct Node {
size_t weight; /* Total weight (symbol count) of this chain. */
Node* tail; /* Previous node(s) of this chain, or 0 if none. */
int count; /* Leaf symbol index, or number of leaves before this chain. */
char inuse; /* Tracking for garbage collection. */
};
/*
Memory pool for nodes.
*/
typedef struct NodePool {
Node* nodes; /* The pool. */
Node* next; /* Pointer to a possibly free node in the pool. */
int size; /* Size of the memory pool. */
} NodePool;
/*
Initializes a chain node with the given values and marks it as in use.
*/
static void InitNode(size_t weight, int count, Node* tail, Node* node) {
node->weight = weight;
node->count = count;
node->tail = tail;
node->inuse = 1;
}
/*
Finds a free location in the memory pool. Performs garbage collection if needed.
lists: If given, used to mark in-use nodes during garbage collection.
maxbits: Size of lists.
pool: Memory pool to get free node from.
*/
static Node* GetFreeNode(Node* (*lists)[2], int maxbits, NodePool* pool) {
for (;;) {
if (pool->next >= &pool->nodes[pool->size]) {
/* Garbage collection. */
int i;
for (i = 0; i < pool->size; i++) {
pool->nodes[i].inuse = 0;
}
if (lists) {
for (i = 0; i < maxbits * 2; i++) {
Node* node;
for (node = lists[i / 2][i % 2]; node; node = node->tail) {
node->inuse = 1;
}
}
}
pool->next = &pool->nodes[0];
}
if (!pool->next->inuse) break; /* Found one. */
pool->next++;
}
return pool->next++;
}
/*
Performs a Boundary Package-Merge step. Puts a new chain in the given list. The
new chain is, depending on the weights, a leaf or a combination of two chains
from the previous list.
lists: The lists of chains.
maxbits: Number of lists.
leaves: The leaves, one per symbol.
numsymbols: Number of leaves.
pool: the node memory pool.
index: The index of the list in which a new chain or leaf is required.
final: Whether this is the last time this function is called. If it is then it
is no more needed to recursively call self.
*/
static void BoundaryPM(Node* (*lists)[2], int maxbits,
Node* leaves, int numsymbols, NodePool* pool, int index, char final) {
Node* newchain;
Node* oldchain;
int lastcount = lists[index][1]->count; /* Count of last chain of list. */
if (index == 0 && lastcount >= numsymbols) return;
newchain = GetFreeNode(lists, maxbits, pool);
oldchain = lists[index][1];
/* These are set up before the recursive calls below, so that there is a list
pointing to the new node, to let the garbage collection know it's in use. */
lists[index][0] = oldchain;
lists[index][1] = newchain;
if (index == 0) {
/* New leaf node in list 0. */
InitNode(leaves[lastcount].weight, lastcount + 1, 0, newchain);
} else {
size_t sum = lists[index - 1][0]->weight + lists[index - 1][1]->weight;
if (lastcount < numsymbols && sum > leaves[lastcount].weight) {
/* New leaf inserted in list, so count is incremented. */
InitNode(leaves[lastcount].weight, lastcount + 1, oldchain->tail,
newchain);
} else {
InitNode(sum, lastcount, lists[index - 1][1], newchain);
if (!final) {
/* Two lookahead chains of previous list used up, create new ones. */
BoundaryPM(lists, maxbits, leaves, numsymbols, pool, index - 1, 0);
BoundaryPM(lists, maxbits, leaves, numsymbols, pool, index - 1, 0);
}
}
}
}
/*
Initializes each list with as lookahead chains the two leaves with lowest
weights.
*/
static void InitLists(
NodePool* pool, const Node* leaves, int maxbits, Node* (*lists)[2]) {
int i;
Node* node0 = GetFreeNode(0, maxbits, pool);
Node* node1 = GetFreeNode(0, maxbits, pool);
InitNode(leaves[0].weight, 1, 0, node0);
InitNode(leaves[1].weight, 2, 0, node1);
for (i = 0; i < maxbits; i++) {
lists[i][0] = node0;
lists[i][1] = node1;
}
}
/*
Converts result of boundary package-merge to the bitlengths. The result in the
last chain of the last list contains the amount of active leaves in each list.
chain: Chain to extract the bit length from (last chain from last list).
*/
static void ExtractBitLengths(Node* chain, Node* leaves, unsigned* bitlengths) {
Node* node;
for (node = chain; node; node = node->tail) {
int i;
for (i = 0; i < node->count; i++) {
bitlengths[leaves[i].count]++;
}
}
}
/*
Comparator for sorting the leaves. Has the function signature for qsort.
*/
static int LeafComparator(const void* a, const void* b) {
return ((const Node*)a)->weight - ((const Node*)b)->weight;
}
int ZopfliLengthLimitedCodeLengths(
const size_t* frequencies, int n, int maxbits, unsigned* bitlengths) {
NodePool pool;
int i;
int numsymbols = 0; /* Amount of symbols with frequency > 0. */
int numBoundaryPMRuns;
/* Array of lists of chains. Each list requires only two lookahead chains at
a time, so each list is a array of two Node*'s. */
Node* (*lists)[2];
/* One leaf per symbol. Only numsymbols leaves will be used. */
Node* leaves = (Node*)malloc(n * sizeof(*leaves));
/* Initialize all bitlengths at 0. */
for (i = 0; i < n; i++) {
bitlengths[i] = 0;
}
/* Count used symbols and place them in the leaves. */
for (i = 0; i < n; i++) {
if (frequencies[i]) {
leaves[numsymbols].weight = frequencies[i];
leaves[numsymbols].count = i; /* Index of symbol this leaf represents. */
numsymbols++;
}
}
/* Check special cases and error conditions. */
if ((1 << maxbits) < numsymbols) {
free(leaves);
return 1; /* Error, too few maxbits to represent symbols. */
}
if (numsymbols == 0) {
free(leaves);
return 0; /* No symbols at all. OK. */
}
if (numsymbols == 1) {
bitlengths[leaves[0].count] = 1;
free(leaves);
return 0; /* Only one symbol, give it bitlength 1, not 0. OK. */
}
/* Sort the leaves from lightest to heaviest. */
qsort(leaves, numsymbols, sizeof(Node), LeafComparator);
/* Initialize node memory pool. */
pool.size = 2 * maxbits * (maxbits + 1);
pool.nodes = (Node*)malloc(pool.size * sizeof(*pool.nodes));
pool.next = pool.nodes;
for (i = 0; i < pool.size; i++) {
pool.nodes[i].inuse = 0;
}
lists = (Node* (*)[2])malloc(maxbits * sizeof(*lists));
InitLists(&pool, leaves, maxbits, lists);
/* In the last list, 2 * numsymbols - 2 active chains need to be created. Two
are already created in the initialization. Each BoundaryPM run creates one. */
numBoundaryPMRuns = 2 * numsymbols - 4;
for (i = 0; i < numBoundaryPMRuns; i++) {
char final = i == numBoundaryPMRuns - 1;
BoundaryPM(lists, maxbits, leaves, numsymbols, &pool, maxbits - 1, final);
}
ExtractBitLengths(lists[maxbits - 1][1], leaves, bitlengths);
free(lists);
free(leaves);
free(pool.nodes);
return 0; /* OK. */
}
| 06zhangxu-c | katajainen.c | C | asf20 | 7,919 |
/*
Copyright 2013 Google Inc. All Rights Reserved.
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.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
#include "gzip_container.h"
#include "util.h"
#include <stdio.h>
#include "deflate.h"
/* Table of CRCs of all 8-bit messages. */
static unsigned long crc_table[256];
/* Flag: has the table been computed? Initially false. */
static int crc_table_computed = 0;
/* Makes the table for a fast CRC. */
static void MakeCRCTable() {
unsigned long c;
int n, k;
for (n = 0; n < 256; n++) {
c = (unsigned long) n;
for (k = 0; k < 8; k++) {
if (c & 1) {
c = 0xedb88320L ^ (c >> 1);
} else {
c = c >> 1;
}
}
crc_table[n] = c;
}
crc_table_computed = 1;
}
/*
Updates a running crc with the bytes buf[0..len-1] and returns
the updated crc. The crc should be initialized to zero.
*/
static unsigned long UpdateCRC(unsigned long crc,
const unsigned char *buf, size_t len) {
unsigned long c = crc ^ 0xffffffffL;
unsigned n;
if (!crc_table_computed)
MakeCRCTable();
for (n = 0; n < len; n++) {
c = crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8);
}
return c ^ 0xffffffffL;
}
/* Returns the CRC of the bytes buf[0..len-1]. */
static unsigned long CRC(const unsigned char* buf, int len) {
return UpdateCRC(0L, buf, len);
}
/*
Compresses the data according to the gzip specification.
*/
void ZopfliGzipCompress(const ZopfliOptions* options,
const unsigned char* in, size_t insize,
unsigned char** out, size_t* outsize) {
unsigned long crcvalue = CRC(in, insize);
unsigned char bp = 0;
ZOPFLI_APPEND_DATA(31, out, outsize); /* ID1 */
ZOPFLI_APPEND_DATA(139, out, outsize); /* ID2 */
ZOPFLI_APPEND_DATA(8, out, outsize); /* CM */
ZOPFLI_APPEND_DATA(0, out, outsize); /* FLG */
/* MTIME */
ZOPFLI_APPEND_DATA(0, out, outsize);
ZOPFLI_APPEND_DATA(0, out, outsize);
ZOPFLI_APPEND_DATA(0, out, outsize);
ZOPFLI_APPEND_DATA(0, out, outsize);
ZOPFLI_APPEND_DATA(2, out, outsize); /* XFL, 2 indicates best compression. */
ZOPFLI_APPEND_DATA(3, out, outsize); /* OS follows Unix conventions. */
ZopfliDeflate(options, 2 /* Dynamic block */, 1,
in, insize, &bp, out, outsize);
/* CRC */
ZOPFLI_APPEND_DATA(crcvalue % 256, out, outsize);
ZOPFLI_APPEND_DATA((crcvalue >> 8) % 256, out, outsize);
ZOPFLI_APPEND_DATA((crcvalue >> 16) % 256, out, outsize);
ZOPFLI_APPEND_DATA((crcvalue >> 24) % 256, out, outsize);
/* ISIZE */
ZOPFLI_APPEND_DATA(insize % 256, out, outsize);
ZOPFLI_APPEND_DATA((insize >> 8) % 256, out, outsize);
ZOPFLI_APPEND_DATA((insize >> 16) % 256, out, outsize);
ZOPFLI_APPEND_DATA((insize >> 24) % 256, out, outsize);
if (options->verbose) {
fprintf(stderr,
"Original Size: %d, Gzip: %d, Compression: %f%% Removed\n",
(int)insize, (int)*outsize,
100.0 * (double)(insize - *outsize) / (double)insize);
}
}
| 06zhangxu-c | gzip_container.c | C | asf20 | 3,563 |