language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 5,891 | 2.359375 | 2 |
[
"MIT"
] |
permissive
|
package spacesurvival.view.game.utilities;
import spacesurvival.model.World;
import spacesurvival.model.collision.bounding.CircleBoundingBox;
import spacesurvival.model.common.Pair;
import spacesurvival.model.gameobject.GameObject;
import spacesurvival.model.gameobject.fireable.Boss;
import spacesurvival.model.gameobject.fireable.SpaceShipSingleton;
import spacesurvival.model.gameobject.main.MainObject;
import spacesurvival.model.gameobject.takeable.TakeableGameObject;
import spacesurvival.utilities.ThreadUtils;
import spacesurvival.view.game.utilities.commandlife.CallerLife;
import spacesurvival.view.game.utilities.logiccolor.LogicColorShip;
import spacesurvival.view.utilities.GraphicsLayoutUtils;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.swing.JPanel;
/**
* Implements a panel to graph game objects, through a support structure.
*/
public class PanelEntityGame extends JPanel {
private static final long serialVersionUID = -6158413043296871948L;
/**
* Anchor life bar.
*/
public static final int ANCHOR_X_LIFE_BAR = 0;
/**
* Height life bar ledge.
*/
public static final int HEIGHT_LIFE_BAR = 6;
/**
* Height life.
*/
public static final int HEIGHT_LIFE = 5;
/**
* Difference height life bar e life.
*/
public static final int DIFFERENCE_HEIGHT_LIFE_BAR = Math.abs(HEIGHT_LIFE_BAR - HEIGHT_LIFE);
private volatile Map<GameObject, Pair<Image, Image>> gameObjects;
private final CallerLife callerLife;
private Optional<World> world;
/**
* Initialize and create all graphics components.
*/
public PanelEntityGame() {
super();
super.setOpaque(true);
super.setBackground(GraphicsLayoutUtils.BACKGROUND_GAME_COLOR);
this.gameObjects = new HashMap<>();
this.world = Optional.empty();
this.callerLife = new CallerLife(new LogicColorShip());
new Thread(PanelEntityGame.this::runUpdateGameObjects).start();
}
/**
* Set world for panel.
* @param world
*/
public void setWorld(final World world) {
this.world = Optional.of(world);
}
/**
* Repaint all game component.
*/
@Override
@SuppressWarnings("PMD.EmptyCatchBlock")
public final void paintComponent(final Graphics g) {
super.paintComponent(g);
final Graphics2D g2d = (Graphics2D) g;
try {
this.world.get().getAllBullets().forEach(bullet -> {
g2d.setTransform(bullet.getTransform());
g2d.drawImage(bullet.getImgBody(), 0, 0, null);
});
this.gameObjects.entrySet().forEach(entity -> {
g2d.setTransform(getCorrectAffineTransformFromBoundingBox(entity.getKey()));
g2d.drawImage(entity.getValue().getX(), 0, 0, null);
g2d.drawImage(entity.getValue().getY(), 0, 0, null);
this.assignLifeBar(entity.getKey(), g2d);
});
} catch (ConcurrentModificationException e) { }
}
private void drawLifeBar(final Graphics2D g2d, final GameObject gameObject) {
this.drawBar(g2d, gameObject);
this.drawLife(g2d, gameObject);
}
private void drawBar(final Graphics2D g2d, final GameObject gameObject) {
g2d.setColor(Color.WHITE);
g2d.drawRect(ANCHOR_X_LIFE_BAR, (int) gameObject.getSize().getHeight(), (int) gameObject.getSize().getWidth(), HEIGHT_LIFE_BAR);
}
private void drawLife(final Graphics2D g2d, final GameObject gameObject) {
this.callerLife.executeDrawLife((MainObject) gameObject, g2d);
}
private boolean isTargetLife(final GameObject obj) {
return !(obj instanceof SpaceShipSingleton || obj instanceof TakeableGameObject || obj instanceof Boss);
}
private void assignLifeBar(final GameObject gameObject, final Graphics2D g2d) {
if (this.isTargetLife(gameObject)) {
this.drawLifeBar(g2d, gameObject);
}
}
private AffineTransform getCorrectAffineTransformFromBoundingBox(final GameObject gameObject) {
if (gameObject.getBoundingBox() instanceof CircleBoundingBox) {
final CircleBoundingBox cbb = (CircleBoundingBox) gameObject.getBoundingBox();
final AffineTransform transform = new AffineTransform();
transform.setTransform(gameObject.getTransform());
transform.translate(-cbb.getRadius(), -cbb.getRadius());
return transform;
} else {
return gameObject.getTransform();
}
}
private void updateGameObjects() {
this.putObjectFromWorld();
this.deletGameObject();
}
private void putObjectFromWorld() {
this.world.get().getAllObjectsExceptBullets().forEach(obj -> {
final Pair<Image, Image> pair = new Pair<>(obj.getImgBody(), obj.getImgEffect());
this.gameObjects.put(obj, pair);
});
}
private void deletGameObject() {
final Set<GameObject> objDelet = new HashSet<>();
this.gameObjects.forEach((key, value) -> {
if (!this.world.get().getAllObjectsExceptBullets().contains(key)) {
objDelet.add(key);
}
});
objDelet.forEach(this.gameObjects::remove);
}
/**
* Method for filling the support structure.
*/
public final void runUpdateGameObjects() {
while (true) {
if (this.world.isPresent()) {
this.updateGameObjects();
}
ThreadUtils.sleep(ThreadUtils.MEDIUM_SLEEP);
}
}
}
|
Ruby
|
UTF-8
| 3,491 | 3.109375 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
# vi: fenc=utf-8:expandtab:ts=2:sw=2:sts=2
#
# Author:: Petr Kovar (mailto:pejuko@gmail.com)
# Copyright:: Copyright (c) 2011 Petr Kovář
# License:: Distributes under the same terms as Ruby
module ScanEnhancer
class Box
STROKE = "#f00f"
FILL = "#fff0"
attr_accessor :left, :top, :right, :bottom
def initialize(left, top, right, bottom)
@left, @top, @right, @bottom = [left, top, right, bottom]
end
def +(box)
self.class.new(*plus(box))
end
alias :join :+
def join!(box)
@left, @top, @right, @bottom = plus(box)
end
def plus(box)
left = [@left, box.left].min
top = [@top, box.top].min
right = [@right, box.right].max
bottom = [@bottom, box.bottom].max
[left, top, right, bottom]
end
def width; @right - @left + 1; end
def height; @bottom - @top + 1; end
def middle; [(@right+@left)/2, (@bottom+@top)/2]; end
def dist(b)
x, y = [0,0]
if @right < b.left
x = b.left - @right
elsif @left > b.right
x = @left - b.right
end
if @bottom < b.top
y = b.top - @bottom
elsif @top > b.bottom
y = @top - b.bottom
end
[x,y]
end
def intersect?(b)
return false if (@right<b.left) or (@left>b.right) or (@top>b.bottom) or (@bottom<b.top)
true
end
def include?(x, y)
(x >= @left) and (x <= @right) and (y >= @top) and (y <= @bottom)
end
# Draw rectangle to the img using STOKE and FILL colors
def highlight(img, msg=nil)
context = drawContext.rectangle(@left, @top, @right, @bottom)
context.draw(img)
if msg
x = (@left + @right) / 2
y = (@top + @bottom) / 2
context = textContext.text_align(Magick::CenterAlign).text(x, y, msg)
context.draw(img)
end
img
end
def invert(max_x, max_y)
boxes = []
boxes << Box.new(0, 0, @left-1, max_y-1) if @left > 0
boxes << Box.new(0, 0, max_x-1, @top-1) if @top > 0
boxes << Box.new(@right+1, 0, max_x-1, max_y-1) if @right < max_x
boxes << Box.new(0, @bottom+1, max_x-1, max_y-1) if @bottom < max_y
boxes
end
def fill(img, color = 255, max_x, max_y)
if img.kind_of? Array
(@left..@right).each do |x|
(@top..@bottom).each do |y|
img[y*max_x + x] = color
end
end
else
draw = Magick::Draw.new
draw.fill = "#ffff"
draw.stroke = "#ffff"
draw.rectangle(@left, @top, @right, @bottom)
draw.draw(img)
end
end
def to_a
[@left, @top, @right, @bottom]
end
def to_f(iw,ih,w=1.0,h=1.0)
[[0,((@left-1).to_f/iw)*w].max, [0,((@top-1).to_f/ih)*h].max, [w,((@right+1).to_f/iw)*w].min, [h,((@bottom+1).to_f/ih)*h].min]
# [[0,(@left.to_f/iw)*w].max, [0,(@top.to_f/ih)*h].max, [w,(@right.to_f/iw)*w].min, [h,(@bottom.to_f/ih)*h].min]
end
private
def drawContext
draw = Magick::Draw.new
color = %w(#f00 #0f0 #00f #ff0 #0ff #f0f).sort_by{rand}.first
draw.fill = color + '8'
draw.stroke = color + 'f'
draw
end
def textContext
draw = Magick::Draw.new
draw.fill = '#00ff'
draw.stroke = '#00ff'
draw.font_weight = Magick::NormalWeight
draw.font_stretch = Magick::NormalStretch
draw.font_style= Magick::NormalStyle
draw.text_undercolor '#ccca'
draw
end
end
end
|
Shell
|
UTF-8
| 43,156 | 2.53125 | 3 |
[] |
no_license
|
#!/bin/bash
# edit by hackjackyer
#因为这个程序基于py的,所以需要安装py环境
rpm -qa |grep python 1>/etc/null 2>&1 && echo "python has already installed" || yum -y install python
sleep 3
#将py指令输出到speedtest.py文件
echo "#!/usr/bin/env python" >>speedtest.py
echo "# -*- coding: utf-8 -*-" >>speedtest.py
echo "# Copyright 2012-2015 Matt Martz" >>speedtest.py
echo "# All Rights Reserved." >>speedtest.py
echo "#" >>speedtest.py
echo "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may" >>speedtest.py
echo "# not use this file except in compliance with the License. You may obtain" >>speedtest.py
echo "# a copy of the License at" >>speedtest.py
echo "#" >>speedtest.py
echo "# http://www.apache.org/licenses/LICENSE-2.0" >>speedtest.py
echo "#" >>speedtest.py
echo "# Unless required by applicable law or agreed to in writing, software" >>speedtest.py
echo "# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT" >>speedtest.py
echo "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the" >>speedtest.py
echo "# License for the specific language governing permissions and limitations" >>speedtest.py
echo "# under the License." >>speedtest.py
echo "" >>speedtest.py
echo "import os" >>speedtest.py
echo "import re" >>speedtest.py
echo "import sys" >>speedtest.py
echo "import math" >>speedtest.py
echo "import signal" >>speedtest.py
echo "import socket" >>speedtest.py
echo "import timeit" >>speedtest.py
echo "import platform" >>speedtest.py
echo "import threading" >>speedtest.py
echo "" >>speedtest.py
echo "__version__ = '0.3.4'" >>speedtest.py
echo "" >>speedtest.py
echo "# Some global variables we use" >>speedtest.py
echo "user_agent = None" >>speedtest.py
echo "source = None" >>speedtest.py
echo "shutdown_event = None" >>speedtest.py
echo "scheme = 'http'" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "# Used for bound_interface" >>speedtest.py
echo "socket_socket = socket.socket" >>speedtest.py
echo "" >>speedtest.py
echo "try:" >>speedtest.py
echo " import xml.etree.cElementTree as ET" >>speedtest.py
echo "except ImportError:" >>speedtest.py
echo " try:" >>speedtest.py
echo " import xml.etree.ElementTree as ET" >>speedtest.py
echo " except ImportError:" >>speedtest.py
echo " from xml.dom import minidom as DOM" >>speedtest.py
echo " ET = None" >>speedtest.py
echo "" >>speedtest.py
echo "# Begin import game to handle Python 2 and Python 3" >>speedtest.py
echo "try:" >>speedtest.py
echo " from urllib2 import urlopen, Request, HTTPError, URLError" >>speedtest.py
echo "except ImportError:" >>speedtest.py
echo " from urllib.request import urlopen, Request, HTTPError, URLError" >>speedtest.py
echo "" >>speedtest.py
echo "try:" >>speedtest.py
echo " from httplib import HTTPConnection, HTTPSConnection" >>speedtest.py
echo "except ImportError:" >>speedtest.py
echo " e_http_py2 = sys.exc_info()" >>speedtest.py
echo " try:" >>speedtest.py
echo " from http.client import HTTPConnection, HTTPSConnection" >>speedtest.py
echo " except ImportError:" >>speedtest.py
echo " e_http_py3 = sys.exc_info()" >>speedtest.py
echo " raise SystemExit('Your python installation is missing required HTTP '" >>speedtest.py
echo " 'client classes:\n\n'" >>speedtest.py
echo " 'Python 2: %s\n'" >>speedtest.py
echo " 'Python 3: %s' % (e_http_py2[1], e_http_py3[1]))" >>speedtest.py
echo "" >>speedtest.py
echo "try:" >>speedtest.py
echo " from Queue import Queue" >>speedtest.py
echo "except ImportError:" >>speedtest.py
echo " from queue import Queue" >>speedtest.py
echo "" >>speedtest.py
echo "try:" >>speedtest.py
echo " from urlparse import urlparse" >>speedtest.py
echo "except ImportError:" >>speedtest.py
echo " from urllib.parse import urlparse" >>speedtest.py
echo "" >>speedtest.py
echo "try:" >>speedtest.py
echo " from urlparse import parse_qs" >>speedtest.py
echo "except ImportError:" >>speedtest.py
echo " try:" >>speedtest.py
echo " from urllib.parse import parse_qs" >>speedtest.py
echo " except ImportError:" >>speedtest.py
echo " from cgi import parse_qs" >>speedtest.py
echo "" >>speedtest.py
echo "try:" >>speedtest.py
echo " from hashlib import md5" >>speedtest.py
echo "except ImportError:" >>speedtest.py
echo " from md5 import md5" >>speedtest.py
echo "" >>speedtest.py
echo "try:" >>speedtest.py
echo " from argparse import ArgumentParser as ArgParser" >>speedtest.py
echo "except ImportError:" >>speedtest.py
echo " from optparse import OptionParser as ArgParser" >>speedtest.py
echo "" >>speedtest.py
echo "try:" >>speedtest.py
echo " import builtins" >>speedtest.py
echo "except ImportError:" >>speedtest.py
echo " def print_(*args, **kwargs):" >>speedtest.py
echo " \"\"\"The new-style print function taken from" >>speedtest.py
echo " https://pypi.python.org/pypi/six/" >>speedtest.py
echo "" >>speedtest.py
echo " \"\"\"" >>speedtest.py
echo " fp = kwargs.pop(\"file\", sys.stdout)" >>speedtest.py
echo " if fp is None:" >>speedtest.py
echo " return" >>speedtest.py
echo "" >>speedtest.py
echo " def write(data):" >>speedtest.py
echo " if not isinstance(data, basestring):" >>speedtest.py
echo " data = str(data)" >>speedtest.py
echo " fp.write(data)" >>speedtest.py
echo "" >>speedtest.py
echo " want_unicode = False" >>speedtest.py
echo " sep = kwargs.pop(\"sep\", None)" >>speedtest.py
echo " if sep is not None:" >>speedtest.py
echo " if isinstance(sep, unicode):" >>speedtest.py
echo " want_unicode = True" >>speedtest.py
echo " elif not isinstance(sep, str):" >>speedtest.py
echo " raise TypeError(\"sep must be None or a string\")" >>speedtest.py
echo " end = kwargs.pop(\"end\", None)" >>speedtest.py
echo " if end is not None:" >>speedtest.py
echo " if isinstance(end, unicode):" >>speedtest.py
echo " want_unicode = True" >>speedtest.py
echo " elif not isinstance(end, str):" >>speedtest.py
echo " raise TypeError(\"end must be None or a string\")" >>speedtest.py
echo " if kwargs:" >>speedtest.py
echo " raise TypeError(\"invalid keyword arguments to print()\")" >>speedtest.py
echo " if not want_unicode:" >>speedtest.py
echo " for arg in args:" >>speedtest.py
echo " if isinstance(arg, unicode):" >>speedtest.py
echo " want_unicode = True" >>speedtest.py
echo " break" >>speedtest.py
echo " if want_unicode:" >>speedtest.py
echo " newline = unicode(\"\n\")" >>speedtest.py
echo " space = unicode(\" \")" >>speedtest.py
echo " else:" >>speedtest.py
echo " newline = \"\n\"" >>speedtest.py
echo " space = \" \"" >>speedtest.py
echo " if sep is None:" >>speedtest.py
echo " sep = space" >>speedtest.py
echo " if end is None:" >>speedtest.py
echo " end = newline" >>speedtest.py
echo " for i, arg in enumerate(args):" >>speedtest.py
echo " if i:" >>speedtest.py
echo " write(sep)" >>speedtest.py
echo " write(arg)" >>speedtest.py
echo " write(end)" >>speedtest.py
echo "else:" >>speedtest.py
echo " print_ = getattr(builtins, 'print')" >>speedtest.py
echo " del builtins" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "class SpeedtestCliServerListError(Exception):" >>speedtest.py
echo " \"\"\"Internal Exception class used to indicate to move on to the next" >>speedtest.py
echo " URL for retrieving speedtest.net server details" >>speedtest.py
echo "" >>speedtest.py
echo " \"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def bound_socket(*args, **kwargs):" >>speedtest.py
echo " \"\"\"Bind socket to a specified source IP address\"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " global source" >>speedtest.py
echo " sock = socket_socket(*args, **kwargs)" >>speedtest.py
echo " sock.bind((source, 0))" >>speedtest.py
echo " return sock" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def distance(origin, destination):" >>speedtest.py
echo " \"\"\"Determine distance between 2 sets of [lat,lon] in km\"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " lat1, lon1 = origin" >>speedtest.py
echo " lat2, lon2 = destination" >>speedtest.py
echo " radius = 6371 # km" >>speedtest.py
echo "" >>speedtest.py
echo " dlat = math.radians(lat2 - lat1)" >>speedtest.py
echo " dlon = math.radians(lon2 - lon1)" >>speedtest.py
echo " a = (math.sin(dlat / 2) * math.sin(dlat / 2) +" >>speedtest.py
echo " math.cos(math.radians(lat1)) *" >>speedtest.py
echo " math.cos(math.radians(lat2)) * math.sin(dlon / 2) *" >>speedtest.py
echo " math.sin(dlon / 2))" >>speedtest.py
echo " c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))" >>speedtest.py
echo " d = radius * c" >>speedtest.py
echo "" >>speedtest.py
echo " return d" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def build_user_agent():" >>speedtest.py
echo " \"\"\"Build a Mozilla/5.0 compatible User-Agent string\"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " global user_agent" >>speedtest.py
echo " if user_agent:" >>speedtest.py
echo " return user_agent" >>speedtest.py
echo "" >>speedtest.py
echo " ua_tuple = (" >>speedtest.py
echo " 'Mozilla/5.0'," >>speedtest.py
echo " '(%s; U; %s; en-us)' % (platform.system(), platform.architecture()[0])," >>speedtest.py
echo " 'Python/%s' % platform.python_version()," >>speedtest.py
echo " '(KHTML, like Gecko)'," >>speedtest.py
echo " 'speedtest-cli/%s' % __version__" >>speedtest.py
echo " )" >>speedtest.py
echo " user_agent = ' '.join(ua_tuple)" >>speedtest.py
echo " return user_agent" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def build_request(url, data=None, headers={}):" >>speedtest.py
echo " \"\"\"Build a urllib2 request object" >>speedtest.py
echo "" >>speedtest.py
echo " This function automatically adds a User-Agent header to all requests" >>speedtest.py
echo "" >>speedtest.py
echo " \"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " if url[0] == ':':" >>speedtest.py
echo " schemed_url = '%s%s' % (scheme, url)" >>speedtest.py
echo " else:" >>speedtest.py
echo " schemed_url = url" >>speedtest.py
echo "" >>speedtest.py
echo " headers['User-Agent'] = user_agent" >>speedtest.py
echo " return Request(schemed_url, data=data, headers=headers)" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def catch_request(request):" >>speedtest.py
echo " \"\"\"Helper function to catch common exceptions encountered when" >>speedtest.py
echo " establishing a connection with a HTTP/HTTPS request" >>speedtest.py
echo "" >>speedtest.py
echo " \"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " try:" >>speedtest.py
echo " uh = urlopen(request)" >>speedtest.py
echo " return uh, False" >>speedtest.py
echo " except (HTTPError, URLError, socket.error):" >>speedtest.py
echo " e = sys.exc_info()[1]" >>speedtest.py
echo " return None, e" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "class FileGetter(threading.Thread):" >>speedtest.py
echo " \"\"\"Thread class for retrieving a URL\"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " def __init__(self, url, start):" >>speedtest.py
echo " self.url = url" >>speedtest.py
echo " self.result = None" >>speedtest.py
echo " self.starttime = start" >>speedtest.py
echo " threading.Thread.__init__(self)" >>speedtest.py
echo "" >>speedtest.py
echo " def run(self):" >>speedtest.py
echo " self.result = [0]" >>speedtest.py
echo " try:" >>speedtest.py
echo " if (timeit.default_timer() - self.starttime) <= 10:" >>speedtest.py
echo " request = build_request(self.url)" >>speedtest.py
echo " f = urlopen(request)" >>speedtest.py
echo " while 1 and not shutdown_event.isSet():" >>speedtest.py
echo " self.result.append(len(f.read(10240)))" >>speedtest.py
echo " if self.result[-1] == 0:" >>speedtest.py
echo " break" >>speedtest.py
echo " f.close()" >>speedtest.py
echo " except IOError:" >>speedtest.py
echo " pass" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def downloadSpeed(files, quiet=False):" >>speedtest.py
echo " \"\"\"Function to launch FileGetter threads and calculate download speeds\"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " start = timeit.default_timer()" >>speedtest.py
echo "" >>speedtest.py
echo " def producer(q, files):" >>speedtest.py
echo " for file in files:" >>speedtest.py
echo " thread = FileGetter(file, start)" >>speedtest.py
echo " thread.start()" >>speedtest.py
echo " q.put(thread, True)" >>speedtest.py
echo " if not quiet and not shutdown_event.isSet():" >>speedtest.py
echo " sys.stdout.write('.')" >>speedtest.py
echo " sys.stdout.flush()" >>speedtest.py
echo "" >>speedtest.py
echo " finished = []" >>speedtest.py
echo "" >>speedtest.py
echo " def consumer(q, total_files):" >>speedtest.py
echo " while len(finished) < total_files:" >>speedtest.py
echo " thread = q.get(True)" >>speedtest.py
echo " while thread.isAlive():" >>speedtest.py
echo " thread.join(timeout=0.1)" >>speedtest.py
echo " finished.append(sum(thread.result))" >>speedtest.py
echo " del thread" >>speedtest.py
echo "" >>speedtest.py
echo " q = Queue(6)" >>speedtest.py
echo " prod_thread = threading.Thread(target=producer, args=(q, files))" >>speedtest.py
echo " cons_thread = threading.Thread(target=consumer, args=(q, len(files)))" >>speedtest.py
echo " start = timeit.default_timer()" >>speedtest.py
echo " prod_thread.start()" >>speedtest.py
echo " cons_thread.start()" >>speedtest.py
echo " while prod_thread.isAlive():" >>speedtest.py
echo " prod_thread.join(timeout=0.1)" >>speedtest.py
echo " while cons_thread.isAlive():" >>speedtest.py
echo " cons_thread.join(timeout=0.1)" >>speedtest.py
echo " return (sum(finished) / (timeit.default_timer() - start))" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "class FilePutter(threading.Thread):" >>speedtest.py
echo " \"\"\"Thread class for putting a URL\"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " def __init__(self, url, start, size):" >>speedtest.py
echo " self.url = url" >>speedtest.py
echo " chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'" >>speedtest.py
echo " data = chars * (int(round(int(size) / 36.0)))" >>speedtest.py
echo " self.data = ('content1=%s' % data[0:int(size) - 9]).encode()" >>speedtest.py
echo " del data" >>speedtest.py
echo " self.result = None" >>speedtest.py
echo " self.starttime = start" >>speedtest.py
echo " threading.Thread.__init__(self)" >>speedtest.py
echo "" >>speedtest.py
echo " def run(self):" >>speedtest.py
echo " try:" >>speedtest.py
echo " if ((timeit.default_timer() - self.starttime) <= 10 and" >>speedtest.py
echo " not shutdown_event.isSet()):" >>speedtest.py
echo " request = build_request(self.url, data=self.data)" >>speedtest.py
echo " f = urlopen(request)" >>speedtest.py
echo " f.read(11)" >>speedtest.py
echo " f.close()" >>speedtest.py
echo " self.result = len(self.data)" >>speedtest.py
echo " else:" >>speedtest.py
echo " self.result = 0" >>speedtest.py
echo " except IOError:" >>speedtest.py
echo " self.result = 0" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def uploadSpeed(url, sizes, quiet=False):" >>speedtest.py
echo " \"\"\"Function to launch FilePutter threads and calculate upload speeds\"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " start = timeit.default_timer()" >>speedtest.py
echo "" >>speedtest.py
echo " def producer(q, sizes):" >>speedtest.py
echo " for size in sizes:" >>speedtest.py
echo " thread = FilePutter(url, start, size)" >>speedtest.py
echo " thread.start()" >>speedtest.py
echo " q.put(thread, True)" >>speedtest.py
echo " if not quiet and not shutdown_event.isSet():" >>speedtest.py
echo " sys.stdout.write('.')" >>speedtest.py
echo " sys.stdout.flush()" >>speedtest.py
echo "" >>speedtest.py
echo " finished = []" >>speedtest.py
echo "" >>speedtest.py
echo " def consumer(q, total_sizes):" >>speedtest.py
echo " while len(finished) < total_sizes:" >>speedtest.py
echo " thread = q.get(True)" >>speedtest.py
echo " while thread.isAlive():" >>speedtest.py
echo " thread.join(timeout=0.1)" >>speedtest.py
echo " finished.append(thread.result)" >>speedtest.py
echo " del thread" >>speedtest.py
echo "" >>speedtest.py
echo " q = Queue(6)" >>speedtest.py
echo " prod_thread = threading.Thread(target=producer, args=(q, sizes))" >>speedtest.py
echo " cons_thread = threading.Thread(target=consumer, args=(q, len(sizes)))" >>speedtest.py
echo " start = timeit.default_timer()" >>speedtest.py
echo " prod_thread.start()" >>speedtest.py
echo " cons_thread.start()" >>speedtest.py
echo " while prod_thread.isAlive():" >>speedtest.py
echo " prod_thread.join(timeout=0.1)" >>speedtest.py
echo " while cons_thread.isAlive():" >>speedtest.py
echo " cons_thread.join(timeout=0.1)" >>speedtest.py
echo " return (sum(finished) / (timeit.default_timer() - start))" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def getAttributesByTagName(dom, tagName):" >>speedtest.py
echo " \"\"\"Retrieve an attribute from an XML document and return it in a" >>speedtest.py
echo " consistent format" >>speedtest.py
echo "" >>speedtest.py
echo " Only used with xml.dom.minidom, which is likely only to be used" >>speedtest.py
echo " with python versions older than 2.5" >>speedtest.py
echo " \"\"\"" >>speedtest.py
echo " elem = dom.getElementsByTagName(tagName)[0]" >>speedtest.py
echo " return dict(list(elem.attributes.items()))" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def getConfig():" >>speedtest.py
echo " \"\"\"Download the speedtest.net configuration and return only the data" >>speedtest.py
echo " we are interested in" >>speedtest.py
echo " \"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " request = build_request('://www.speedtest.net/speedtest-config.php')" >>speedtest.py
echo " uh, e = catch_request(request)" >>speedtest.py
echo " if e:" >>speedtest.py
echo " print_('Could not retrieve speedtest.net configuration: %s' % e)" >>speedtest.py
echo " sys.exit(1)" >>speedtest.py
echo " configxml = []" >>speedtest.py
echo " while 1:" >>speedtest.py
echo " configxml.append(uh.read(10240))" >>speedtest.py
echo " if len(configxml[-1]) == 0:" >>speedtest.py
echo " break" >>speedtest.py
echo " if int(uh.code) != 200:" >>speedtest.py
echo " return None" >>speedtest.py
echo " uh.close()" >>speedtest.py
echo " try:" >>speedtest.py
echo " try:" >>speedtest.py
echo " root = ET.fromstring(''.encode().join(configxml))" >>speedtest.py
echo " config = {" >>speedtest.py
echo " 'client': root.find('client').attrib," >>speedtest.py
echo " 'times': root.find('times').attrib," >>speedtest.py
echo " 'download': root.find('download').attrib," >>speedtest.py
echo " 'upload': root.find('upload').attrib}" >>speedtest.py
echo " except AttributeError: # Python3 branch" >>speedtest.py
echo " root = DOM.parseString(''.join(configxml))" >>speedtest.py
echo " config = {" >>speedtest.py
echo " 'client': getAttributesByTagName(root, 'client')," >>speedtest.py
echo " 'times': getAttributesByTagName(root, 'times')," >>speedtest.py
echo " 'download': getAttributesByTagName(root, 'download')," >>speedtest.py
echo " 'upload': getAttributesByTagName(root, 'upload')}" >>speedtest.py
echo " except SyntaxError:" >>speedtest.py
echo " print_('Failed to parse speedtest.net configuration')" >>speedtest.py
echo " sys.exit(1)" >>speedtest.py
echo " del root" >>speedtest.py
echo " del configxml" >>speedtest.py
echo " return config" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def closestServers(client, all=False):" >>speedtest.py
echo " \"\"\"Determine the 5 closest speedtest.net servers based on geographic" >>speedtest.py
echo " distance" >>speedtest.py
echo " \"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " urls = [" >>speedtest.py
echo " '://www.speedtest.net/speedtest-servers-static.php'," >>speedtest.py
echo " '://c.speedtest.net/speedtest-servers-static.php'," >>speedtest.py
echo " '://www.speedtest.net/speedtest-servers.php'," >>speedtest.py
echo " '://c.speedtest.net/speedtest-servers.php'," >>speedtest.py
echo " ]" >>speedtest.py
echo " errors = []" >>speedtest.py
echo " servers = {}" >>speedtest.py
echo " for url in urls:" >>speedtest.py
echo " try:" >>speedtest.py
echo " request = build_request(url)" >>speedtest.py
echo " uh, e = catch_request(request)" >>speedtest.py
echo " if e:" >>speedtest.py
echo " errors.append('%s' % e)" >>speedtest.py
echo " raise SpeedtestCliServerListError" >>speedtest.py
echo " serversxml = []" >>speedtest.py
echo " while 1:" >>speedtest.py
echo " serversxml.append(uh.read(10240))" >>speedtest.py
echo " if len(serversxml[-1]) == 0:" >>speedtest.py
echo " break" >>speedtest.py
echo " if int(uh.code) != 200:" >>speedtest.py
echo " uh.close()" >>speedtest.py
echo " raise SpeedtestCliServerListError" >>speedtest.py
echo " uh.close()" >>speedtest.py
echo " try:" >>speedtest.py
echo " try:" >>speedtest.py
echo " root = ET.fromstring(''.encode().join(serversxml))" >>speedtest.py
echo " elements = root.getiterator('server')" >>speedtest.py
echo " except AttributeError: # Python3 branch" >>speedtest.py
echo " root = DOM.parseString(''.join(serversxml))" >>speedtest.py
echo " elements = root.getElementsByTagName('server')" >>speedtest.py
echo " except SyntaxError:" >>speedtest.py
echo " raise SpeedtestCliServerListError" >>speedtest.py
echo " for server in elements:" >>speedtest.py
echo " try:" >>speedtest.py
echo " attrib = server.attrib" >>speedtest.py
echo " except AttributeError:" >>speedtest.py
echo " attrib = dict(list(server.attributes.items()))" >>speedtest.py
echo " d = distance([float(client['lat'])," >>speedtest.py
echo " float(client['lon'])]," >>speedtest.py
echo " [float(attrib.get('lat'))," >>speedtest.py
echo " float(attrib.get('lon'))])" >>speedtest.py
echo " attrib['d'] = d" >>speedtest.py
echo " if d not in servers:" >>speedtest.py
echo " servers[d] = [attrib]" >>speedtest.py
echo " else:" >>speedtest.py
echo " servers[d].append(attrib)" >>speedtest.py
echo " del root" >>speedtest.py
echo " del serversxml" >>speedtest.py
echo " del elements" >>speedtest.py
echo " except SpeedtestCliServerListError:" >>speedtest.py
echo " continue" >>speedtest.py
echo "" >>speedtest.py
echo " # We were able to fetch and parse the list of speedtest.net servers" >>speedtest.py
echo " if servers:" >>speedtest.py
echo " break" >>speedtest.py
echo "" >>speedtest.py
echo " if not servers:" >>speedtest.py
echo " print_('Failed to retrieve list of speedtest.net servers:\n\n %s' %" >>speedtest.py
echo " '\n'.join(errors))" >>speedtest.py
echo " sys.exit(1)" >>speedtest.py
echo "" >>speedtest.py
echo " closest = []" >>speedtest.py
echo " for d in sorted(servers.keys()):" >>speedtest.py
echo " for s in servers[d]:" >>speedtest.py
echo " closest.append(s)" >>speedtest.py
echo " if len(closest) == 5 and not all:" >>speedtest.py
echo " break" >>speedtest.py
echo " else:" >>speedtest.py
echo " continue" >>speedtest.py
echo " break" >>speedtest.py
echo "" >>speedtest.py
echo " del servers" >>speedtest.py
echo " return closest" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def getBestServer(servers):" >>speedtest.py
echo " \"\"\"Perform a speedtest.net latency request to determine which" >>speedtest.py
echo " speedtest.net server has the lowest latency" >>speedtest.py
echo " \"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " results = {}" >>speedtest.py
echo " for server in servers:" >>speedtest.py
echo " cum = []" >>speedtest.py
echo " url = '%s/latency.txt' % os.path.dirname(server['url'])" >>speedtest.py
echo " urlparts = urlparse(url)" >>speedtest.py
echo " for i in range(0, 3):" >>speedtest.py
echo " try:" >>speedtest.py
echo " if urlparts[0] == 'https':" >>speedtest.py
echo " h = HTTPSConnection(urlparts[1])" >>speedtest.py
echo " else:" >>speedtest.py
echo " h = HTTPConnection(urlparts[1])" >>speedtest.py
echo " headers = {'User-Agent': user_agent}" >>speedtest.py
echo " start = timeit.default_timer()" >>speedtest.py
echo " h.request(\"GET\", urlparts[2], headers=headers)" >>speedtest.py
echo " r = h.getresponse()" >>speedtest.py
echo " total = (timeit.default_timer() - start)" >>speedtest.py
echo " except (HTTPError, URLError, socket.error):" >>speedtest.py
echo " cum.append(3600)" >>speedtest.py
echo " continue" >>speedtest.py
echo " text = r.read(9)" >>speedtest.py
echo " if int(r.status) == 200 and text == 'test=test'.encode():" >>speedtest.py
echo " cum.append(total)" >>speedtest.py
echo " else:" >>speedtest.py
echo " cum.append(3600)" >>speedtest.py
echo " h.close()" >>speedtest.py
echo " avg = round((sum(cum) / 6) * 1000, 3)" >>speedtest.py
echo " results[avg] = server" >>speedtest.py
echo " fastest = sorted(results.keys())[0]" >>speedtest.py
echo " best = results[fastest]" >>speedtest.py
echo " best['latency'] = fastest" >>speedtest.py
echo "" >>speedtest.py
echo " return best" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def ctrl_c(signum, frame):" >>speedtest.py
echo " \"\"\"Catch Ctrl-C key sequence and set a shutdown_event for our threaded" >>speedtest.py
echo " operations" >>speedtest.py
echo " \"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " global shutdown_event" >>speedtest.py
echo " shutdown_event.set()" >>speedtest.py
echo " raise SystemExit('\nCancelling...')" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def version():" >>speedtest.py
echo " \"\"\"Print the version\"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " raise SystemExit(__version__)" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def speedtest():" >>speedtest.py
echo " \"\"\"Run the full speedtest.net test\"\"\"" >>speedtest.py
echo "" >>speedtest.py
echo " global shutdown_event, source, scheme" >>speedtest.py
echo " shutdown_event = threading.Event()" >>speedtest.py
echo "" >>speedtest.py
echo " signal.signal(signal.SIGINT, ctrl_c)" >>speedtest.py
echo "" >>speedtest.py
echo " description = (" >>speedtest.py
echo " 'Command line interface for testing internet bandwidth using '" >>speedtest.py
echo " 'speedtest.net.\n'" >>speedtest.py
echo " '------------------------------------------------------------'" >>speedtest.py
echo " '--------------\n'" >>speedtest.py
echo " 'https://github.com/sivel/speedtest-cli')" >>speedtest.py
echo "" >>speedtest.py
echo " parser = ArgParser(description=description)" >>speedtest.py
echo " # Give optparse.OptionParser an \`add_argument\` method for" >>speedtest.py
echo " # compatibility with argparse.ArgumentParser" >>speedtest.py
echo " try:" >>speedtest.py
echo " parser.add_argument = parser.add_option" >>speedtest.py
echo " except AttributeError:" >>speedtest.py
echo " pass" >>speedtest.py
echo " parser.add_argument('--bytes', dest='units', action='store_const'," >>speedtest.py
echo " const=('byte', 1), default=('bit', 8)," >>speedtest.py
echo " help='Display values in bytes instead of bits. Does '" >>speedtest.py
echo " 'not affect the image generated by --share')" >>speedtest.py
echo " parser.add_argument('--share', action='store_true'," >>speedtest.py
echo " help='Generate and provide a URL to the speedtest.net '" >>speedtest.py
echo " 'share results image')" >>speedtest.py
echo " parser.add_argument('--simple', action='store_true'," >>speedtest.py
echo " help='Suppress verbose output, only show basic '" >>speedtest.py
echo " 'information')" >>speedtest.py
echo " parser.add_argument('--list', action='store_true'," >>speedtest.py
echo " help='Display a list of speedtest.net servers '" >>speedtest.py
echo " 'sorted by distance')" >>speedtest.py
echo " parser.add_argument('--server', help='Specify a server ID to test against')" >>speedtest.py
echo " parser.add_argument('--mini', help='URL of the Speedtest Mini server')" >>speedtest.py
echo " parser.add_argument('--source', help='Source IP address to bind to')" >>speedtest.py
echo " parser.add_argument('--timeout', default=10, type=int," >>speedtest.py
echo " help='HTTP timeout in seconds. Default 10')" >>speedtest.py
echo " parser.add_argument('--secure', action='store_true'," >>speedtest.py
echo " help='Use HTTPS instead of HTTP when communicating '" >>speedtest.py
echo " 'with speedtest.net operated servers')" >>speedtest.py
echo " parser.add_argument('--version', action='store_true'," >>speedtest.py
echo " help='Show the version number and exit')" >>speedtest.py
echo "" >>speedtest.py
echo " options = parser.parse_args()" >>speedtest.py
echo " if isinstance(options, tuple):" >>speedtest.py
echo " args = options[0]" >>speedtest.py
echo " else:" >>speedtest.py
echo " args = options" >>speedtest.py
echo " del options" >>speedtest.py
echo "" >>speedtest.py
echo " # Print the version and exit" >>speedtest.py
echo " if args.version:" >>speedtest.py
echo " version()" >>speedtest.py
echo "" >>speedtest.py
echo " socket.setdefaulttimeout(args.timeout)" >>speedtest.py
echo "" >>speedtest.py
echo " # Pre-cache the user agent string" >>speedtest.py
echo " build_user_agent()" >>speedtest.py
echo "" >>speedtest.py
echo " # If specified bind to a specific IP address" >>speedtest.py
echo " if args.source:" >>speedtest.py
echo " source = args.source" >>speedtest.py
echo " socket.socket = bound_socket" >>speedtest.py
echo "" >>speedtest.py
echo " if args.secure:" >>speedtest.py
echo " scheme = 'https'" >>speedtest.py
echo "" >>speedtest.py
echo " if not args.simple:" >>speedtest.py
echo " print_('Retrieving speedtest.net configuration...')" >>speedtest.py
echo " try:" >>speedtest.py
echo " config = getConfig()" >>speedtest.py
echo " except URLError:" >>speedtest.py
echo " print_('Cannot retrieve speedtest configuration')" >>speedtest.py
echo " sys.exit(1)" >>speedtest.py
echo "" >>speedtest.py
echo " if not args.simple:" >>speedtest.py
echo " print_('Retrieving speedtest.net server list...')" >>speedtest.py
echo " if args.list or args.server:" >>speedtest.py
echo " servers = closestServers(config['client'], True)" >>speedtest.py
echo " if args.list:" >>speedtest.py
echo " serverList = []" >>speedtest.py
echo " for server in servers:" >>speedtest.py
echo " line = ('%(id)4s) %(sponsor)s (%(name)s, %(country)s) '" >>speedtest.py
echo " '[%(d)0.2f km]' % server)" >>speedtest.py
echo " serverList.append(line)" >>speedtest.py
echo " print_('\n'.join(serverList).encode('utf-8', 'ignore'))" >>speedtest.py
echo " sys.exit(0)" >>speedtest.py
echo " else:" >>speedtest.py
echo " servers = closestServers(config['client'])" >>speedtest.py
echo "" >>speedtest.py
echo " if not args.simple:" >>speedtest.py
echo " print_('Testing from %(isp)s (%(ip)s)...' % config['client'])" >>speedtest.py
echo "" >>speedtest.py
echo " if args.server:" >>speedtest.py
echo " try:" >>speedtest.py
echo " best = getBestServer(filter(lambda x: x['id'] == args.server," >>speedtest.py
echo " servers))" >>speedtest.py
echo " except IndexError:" >>speedtest.py
echo " print_('Invalid server ID')" >>speedtest.py
echo " sys.exit(1)" >>speedtest.py
echo " elif args.mini:" >>speedtest.py
echo " name, ext = os.path.splitext(args.mini)" >>speedtest.py
echo " if ext:" >>speedtest.py
echo " url = os.path.dirname(args.mini)" >>speedtest.py
echo " else:" >>speedtest.py
echo " url = args.mini" >>speedtest.py
echo " urlparts = urlparse(url)" >>speedtest.py
echo " try:" >>speedtest.py
echo " request = build_request(args.mini)" >>speedtest.py
echo " f = urlopen(request)" >>speedtest.py
echo " except:" >>speedtest.py
echo " print_('Invalid Speedtest Mini URL')" >>speedtest.py
echo " sys.exit(1)" >>speedtest.py
echo " else:" >>speedtest.py
echo " text = f.read()" >>speedtest.py
echo " f.close()" >>speedtest.py
echo " extension = re.findall('upload_extension: \"([^\"]+)\"', text.decode())" >>speedtest.py
echo " if not extension:" >>speedtest.py
echo " for ext in ['php', 'asp', 'aspx', 'jsp']:" >>speedtest.py
echo " try:" >>speedtest.py
echo " request = build_request('%s/speedtest/upload.%s' %" >>speedtest.py
echo " (args.mini, ext))" >>speedtest.py
echo " f = urlopen(request)" >>speedtest.py
echo " except:" >>speedtest.py
echo " pass" >>speedtest.py
echo " else:" >>speedtest.py
echo " data = f.read().strip()" >>speedtest.py
echo " if (f.code == 200 and" >>speedtest.py
echo " len(data.splitlines()) == 1 and" >>speedtest.py
echo " re.match('size=[0-9]', data)):" >>speedtest.py
echo " extension = [ext]" >>speedtest.py
echo " break" >>speedtest.py
echo " if not urlparts or not extension:" >>speedtest.py
echo " print_('Please provide the full URL of your Speedtest Mini server')" >>speedtest.py
echo " sys.exit(1)" >>speedtest.py
echo " servers = [{" >>speedtest.py
echo " 'sponsor': 'Speedtest Mini'," >>speedtest.py
echo " 'name': urlparts[1]," >>speedtest.py
echo " 'd': 0," >>speedtest.py
echo " 'url': '%s/speedtest/upload.%s' % (url.rstrip('/'), extension[0])," >>speedtest.py
echo " 'latency': 0," >>speedtest.py
echo " 'id': 0" >>speedtest.py
echo " }]" >>speedtest.py
echo " try:" >>speedtest.py
echo " best = getBestServer(servers)" >>speedtest.py
echo " except:" >>speedtest.py
echo " best = servers[0]" >>speedtest.py
echo " else:" >>speedtest.py
echo " if not args.simple:" >>speedtest.py
echo " print_('Selecting best server based on latency...')" >>speedtest.py
echo " best = getBestServer(servers)" >>speedtest.py
echo "" >>speedtest.py
echo " if not args.simple:" >>speedtest.py
echo " print_(('Hosted by %(sponsor)s (%(name)s) [%(d)0.2f km]: '" >>speedtest.py
echo " '%(latency)s ms' % best).encode('utf-8', 'ignore'))" >>speedtest.py
echo " else:" >>speedtest.py
echo " print_('Ping: %(latency)s ms' % best)" >>speedtest.py
echo "" >>speedtest.py
echo " sizes = [350, 500, 750, 1000, 1500, 2000, 2500, 3000, 3500, 4000]" >>speedtest.py
echo " urls = []" >>speedtest.py
echo " for size in sizes:" >>speedtest.py
echo " for i in range(0, 4):" >>speedtest.py
echo " urls.append('%s/random%sx%s.jpg' %" >>speedtest.py
echo " (os.path.dirname(best['url']), size, size))" >>speedtest.py
echo " if not args.simple:" >>speedtest.py
echo " print_('Testing download speed', end='')" >>speedtest.py
echo " dlspeed = downloadSpeed(urls, args.simple)" >>speedtest.py
echo " if not args.simple:" >>speedtest.py
echo " print_()" >>speedtest.py
echo " print_('Download: %0.2f M%s/s' %" >>speedtest.py
echo " ((dlspeed / 1000 / 1000) * args.units[1], args.units[0]))" >>speedtest.py
echo "" >>speedtest.py
echo " sizesizes = [int(.25 * 1000 * 1000), int(.5 * 1000 * 1000)]" >>speedtest.py
echo " sizes = []" >>speedtest.py
echo " for size in sizesizes:" >>speedtest.py
echo " for i in range(0, 25):" >>speedtest.py
echo " sizes.append(size)" >>speedtest.py
echo " if not args.simple:" >>speedtest.py
echo " print_('Testing upload speed', end='')" >>speedtest.py
echo " ulspeed = uploadSpeed(best['url'], sizes, args.simple)" >>speedtest.py
echo " if not args.simple:" >>speedtest.py
echo " print_()" >>speedtest.py
echo " print_('Upload: %0.2f M%s/s' %" >>speedtest.py
echo " ((ulspeed / 1000 / 1000) * args.units[1], args.units[0]))" >>speedtest.py
echo "" >>speedtest.py
echo " if args.share and args.mini:" >>speedtest.py
echo " print_('Cannot generate a speedtest.net share results image while '" >>speedtest.py
echo " 'testing against a Speedtest Mini server')" >>speedtest.py
echo " elif args.share:" >>speedtest.py
echo " dlspeedk = int(round((dlspeed / 1000) * 8, 0))" >>speedtest.py
echo " ping = int(round(best['latency'], 0))" >>speedtest.py
echo " ulspeedk = int(round((ulspeed / 1000) * 8, 0))" >>speedtest.py
echo "" >>speedtest.py
echo " # Build the request to send results back to speedtest.net" >>speedtest.py
echo " # We use a list instead of a dict because the API expects parameters" >>speedtest.py
echo " # in a certain order" >>speedtest.py
echo " apiData = [" >>speedtest.py
echo " 'download=%s' % dlspeedk," >>speedtest.py
echo " 'ping=%s' % ping," >>speedtest.py
echo " 'upload=%s' % ulspeedk," >>speedtest.py
echo " 'promo='," >>speedtest.py
echo " 'startmode=%s' % 'pingselect'," >>speedtest.py
echo " 'recommendedserverid=%s' % best['id']," >>speedtest.py
echo " 'accuracy=%s' % 1," >>speedtest.py
echo " 'serverid=%s' % best['id']," >>speedtest.py
echo " 'hash=%s' % md5(('%s-%s-%s-%s' %" >>speedtest.py
echo " (ping, ulspeedk, dlspeedk, '297aae72'))" >>speedtest.py
echo " .encode()).hexdigest()]" >>speedtest.py
echo "" >>speedtest.py
echo " headers = {'Referer': 'http://c.speedtest.net/flash/speedtest.swf'}" >>speedtest.py
echo " request = build_request('://www.speedtest.net/api/api.php'," >>speedtest.py
echo " data='&'.join(apiData).encode()," >>speedtest.py
echo " headers=headers)" >>speedtest.py
echo " f, e = catch_request(request)" >>speedtest.py
echo " if e:" >>speedtest.py
echo " print_('Could not submit results to speedtest.net: %s' % e)" >>speedtest.py
echo " sys.exit(1)" >>speedtest.py
echo " response = f.read()" >>speedtest.py
echo " code = f.code" >>speedtest.py
echo " f.close()" >>speedtest.py
echo "" >>speedtest.py
echo " if int(code) != 200:" >>speedtest.py
echo " print_('Could not submit results to speedtest.net')" >>speedtest.py
echo " sys.exit(1)" >>speedtest.py
echo "" >>speedtest.py
echo " qsargs = parse_qs(response.decode())" >>speedtest.py
echo " resultid = qsargs.get('resultid')" >>speedtest.py
echo " if not resultid or len(resultid) != 1:" >>speedtest.py
echo " print_('Could not submit results to speedtest.net')" >>speedtest.py
echo " sys.exit(1)" >>speedtest.py
echo "" >>speedtest.py
echo " print_('Share results: %s://www.speedtest.net/result/%s.png' %" >>speedtest.py
echo " (scheme, resultid[0]))" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "def main():" >>speedtest.py
echo " try:" >>speedtest.py
echo " speedtest()" >>speedtest.py
echo " except KeyboardInterrupt:" >>speedtest.py
echo " print_('\nCancelling...')" >>speedtest.py
echo "" >>speedtest.py
echo "" >>speedtest.py
echo "if __name__ == '__main__':" >>speedtest.py
echo " main()" >>speedtest.py
echo "" >>speedtest.py
echo "# vim:ts=4:sw=4:expandtab" >>speedtest.py
#然后执行刚才生成的文件,--server是固定以那个服务器来测速服务器来实验的,可以不用加--server参数。
python speedtest.py --server=5081
sleep 3
#删除生成的py文件。
rm -f speedtest.py
|
C#
|
UTF-8
| 1,411 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Linq;
using System.Threading;
using System.Timers;
using channelbot_2.Interfaces;
using channelbot_2.Models;
using Microsoft.EntityFrameworkCore;
namespace channelbot_2
{
public class RedditPostMaker : IPoller
{
// Post messages every 30m, check for it (incase the reddit request failed from the events)
public int PollInterval { get; set; } = 1800000 ; // 120000
/// <summary>
/// On setup
/// </summary>
public void OnSetup()
{
}
/// <summary>
/// On poll, currently every 30m
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
public void OnPoll(object source, ElapsedEventArgs e)
{
using (var db = new ModelDbContext())
{
var yts = db.YoutubeNotifications.Where(x => x.PostedToReddit == false)
.ToList();
foreach (var youtubeNotification in yts)
{
if (youtubeNotification == null) continue;
youtubeNotification.Channel =
db.Channels.FirstOrDefault(y => y.Id == youtubeNotification.ChannelId);
Program.reddit.PostInSubreddit(new {}, youtubeNotification);
Thread.Sleep(1000);
}
}
}
}
}
|
PHP
|
UTF-8
| 3,569 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Commercetools\Core\Builder\Update;
use Commercetools\Core\Error\InvalidArgumentException;
use Commercetools\Core\Request\AbstractAction;
use Commercetools\Core\Request\Extensions\Command\ExtensionChangeDestinationAction;
use Commercetools\Core\Request\Extensions\Command\ExtensionChangeTriggersAction;
use Commercetools\Core\Request\Extensions\Command\ExtensionSetKeyAction;
use Commercetools\Core\Request\Extensions\Command\ExtensionSetTimeoutInMsAction;
class ExtensionsActionBuilder
{
private $actions = [];
/**
* @link https://docs.commercetools.com/http-api-projects-api-extensions.html#change-destination
* @param ExtensionChangeDestinationAction|callable $action
* @return $this
*/
public function changeDestination($action = null)
{
$this->addAction($this->resolveAction(ExtensionChangeDestinationAction::class, $action));
return $this;
}
/**
* @link https://docs.commercetools.com/http-api-projects-api-extensions.html#change-triggers
* @param ExtensionChangeTriggersAction|callable $action
* @return $this
*/
public function changeTriggers($action = null)
{
$this->addAction($this->resolveAction(ExtensionChangeTriggersAction::class, $action));
return $this;
}
/**
* @link https://docs.commercetools.com/http-api-projects-api-extensions.html#set-key
* @param ExtensionSetKeyAction|callable $action
* @return $this
*/
public function setKey($action = null)
{
$this->addAction($this->resolveAction(ExtensionSetKeyAction::class, $action));
return $this;
}
/**
* @link https://docs.commercetools.com/http-api-projects-api-extensions.html#set-timeoutinms
* @param ExtensionSetTimeoutInMsAction|callable $action
* @return $this
*/
public function setTimeoutInMs($action = null)
{
$this->addAction($this->resolveAction(ExtensionSetTimeoutInMsAction::class, $action));
return $this;
}
/**
* @return ExtensionsActionBuilder
*/
public static function of()
{
return new self();
}
/**
* @param $class
* @param $action
* @return AbstractAction
* @throws InvalidArgumentException
*/
private function resolveAction($class, $action = null)
{
if (is_null($action) || is_callable($action)) {
$callback = $action;
$emptyAction = $class::of();
$action = $this->callback($emptyAction, $callback);
}
if ($action instanceof $class) {
return $action;
}
throw new InvalidArgumentException(
sprintf('Expected method to be called with or callable to return %s', $class)
);
}
/**
* @param $action
* @param callable $callback
* @return AbstractAction
*/
private function callback($action, callable $callback = null)
{
if (!is_null($callback)) {
$action = $callback($action);
}
return $action;
}
/**
* @param AbstractAction $action
* @return $this;
*/
public function addAction(AbstractAction $action)
{
$this->actions[] = $action;
return $this;
}
/**
* @return array
*/
public function getActions()
{
return $this->actions;
}
/**
* @param array $actions
* @return $this
*/
public function setActions(array $actions)
{
$this->actions = $actions;
return $this;
}
}
|
Shell
|
UTF-8
| 5,637 | 3.671875 | 4 |
[] |
permissive
|
#!/usr/bin/env bash
#
# NOTE:
# - $! is tested in background.test.sh
# - $- is tested in sh-options
#
# TODO: It would be nice to make a table, like:
#
# $$ $BASHPID $PPID $SHLVL $BASH_SUBSHELL
# X
# (Subshell, Command Sub, Pipeline, Spawn $0)
#
# And see whether the variable changed.
#### $PWD is set
# Just test that it has a slash for now.
echo $PWD | grep /
## status: 0
#### $PWD is not only set, but exported
env | grep PWD
## status: 0
## BUG mksh status: 1
#### $HOME is NOT set
case $SH in *zsh) echo 'zsh sets HOME'; exit ;; esac
home=$(echo $HOME)
test "$home" = ""
echo status=$?
env | grep HOME
echo status=$?
# not in interactive shell either
$SH -i -c 'echo $HOME' | grep /
echo status=$?
## STDOUT:
status=0
status=1
status=1
## END
## BUG zsh STDOUT:
zsh sets HOME
## END
#### $1 .. $9 are scoped, while $0 is not
fun() { echo $0 $1 $2 | sed -e 's/.*sh/sh/'; }
fun a b
## stdout: sh a b
## BUG zsh stdout: fun a b
#### $?
echo $? # starts out as 0
sh -c 'exit 33'
echo $?
## STDOUT:
0
33
## END
## status: 0
#### $#
set -- 1 2 3 4
echo $#
## stdout: 4
## status: 0
#### $_
# This is bash-specific.
echo hi
echo $_
## stdout-json: "hi\nhi\n"
## N-I dash/mksh stdout-json: "hi\n\n"
#### $$ looks like a PID
# Just test that it has decimal digits
echo $$ | egrep '[0-9]+'
## status: 0
#### $$ doesn't change with subshell or command sub
# Just test that it has decimal digits
set -o errexit
die() {
echo 1>&2 "$@"; exit 1
}
parent=$$
test -n "$parent" || die "empty PID in parent"
( child=$$
test -n "$child" || die "empty PID in subshell"
test "$parent" = "$child" || die "should be equal: $parent != $child"
echo 'subshell OK'
)
echo $( child=$$
test -n "$child" || die "empty PID in command sub"
test "$parent" = "$child" || die "should be equal: $parent != $child"
echo 'command sub OK'
)
exit 3 # make sure we got here
## status: 3
## STDOUT:
subshell OK
command sub OK
## END
#### $BASHPID DOES change with subshell and command sub
set -o errexit
die() {
echo 1>&2 "$@"; exit 1
}
parent=$BASHPID
test -n "$parent" || die "empty BASHPID in parent"
( child=$BASHPID
test -n "$child" || die "empty BASHPID in subshell"
test "$parent" != "$child" || die "should not be equal: $parent = $child"
echo 'subshell OK'
)
echo $( child=$BASHPID
test -n "$child" || die "empty BASHPID in command sub"
test "$parent" != "$child" ||
die "should not be equal: $parent = $child"
echo 'command sub OK'
)
exit 3 # make sure we got here
## status: 3
## STDOUT:
subshell OK
command sub OK
## END
## N-I dash/zsh status: 1
## N-I dash/zsh stdout-json: ""
#### Background PID $! looks like a PID
sleep 0.01 &
pid=$!
wait
echo $pid | egrep '[0-9]+' >/dev/null
echo status=$?
## stdout: status=0
#### $PPID
echo $PPID | egrep '[0-9]+'
## status: 0
# NOTE: There is also $BASHPID
#### $PIPESTATUS
echo hi | sh -c 'cat; exit 33' | wc -l >/dev/null
argv.py "${PIPESTATUS[@]}"
## status: 0
## STDOUT:
['0', '33', '0']
## END
## N-I dash stdout-json: ""
## N-I dash status: 2
## N-I zsh STDOUT:
['']
## END
#### $RANDOM
expr $0 : '.*/osh$' && exit 99 # Disabled because of spec-runner.sh issue
echo $RANDOM | egrep '[0-9]+'
## status: 0
## N-I dash status: 1
#### $UID and $EUID
# These are both bash-specific.
set -o errexit
echo $UID | egrep -o '[0-9]+' >/dev/null
echo $EUID | egrep -o '[0-9]+' >/dev/null
echo status=$?
## stdout: status=0
## N-I dash/mksh stdout-json: ""
## N-I dash/mksh status: 1
#### $OSTYPE is non-empty
test -n "$OSTYPE"
echo status=$?
## STDOUT:
status=0
## END
## N-I dash/mksh STDOUT:
status=1
## END
#### $HOSTNAME
test "$HOSTNAME" = "$(hostname)"
echo status=$?
## STDOUT:
status=0
## END
## N-I dash/mksh/zsh STDOUT:
status=1
## END
#### $LINENO is the current line, not line of function call
echo $LINENO # first line
g() {
argv.py $LINENO # line 3
}
f() {
argv.py $LINENO # line 6
g
argv.py $LINENO # line 8
}
f
## STDOUT:
1
['6']
['3']
['8']
## END
## BUG zsh STDOUT:
1
['1']
['1']
['3']
## END
## BUG dash STDOUT:
1
['2']
['2']
['4']
## END
#### $LINENO in "bare" redirect arg (bug regression)
filename=$TMP/bare3
rm -f $filename
> $TMP/bare$LINENO
test -f $filename && echo written
echo $LINENO
## STDOUT:
written
5
## END
## BUG zsh STDOUT:
## END
#### $LINENO in redirect arg (bug regression)
filename=$TMP/lineno_regression3
rm -f $filename
echo x > $TMP/lineno_regression$LINENO
test -f $filename && echo written
echo $LINENO
## STDOUT:
written
5
## END
#### $LINENO for [[
echo one
[[ $LINENO -eq 2 ]] && echo OK
## STDOUT:
one
OK
## END
## N-I dash status: 127
## N-I dash stdout: one
## N-I mksh status: 1
## N-I mksh stdout: one
#### $LINENO for ((
echo one
(( x = LINENO ))
echo $x
## STDOUT:
one
2
## END
## N-I dash stdout-json: "one\n\n"
#### $LINENO in for loop
# hm bash doesn't take into account the word break. That's OK; we won't either.
echo one
for x in \
$LINENO zzz; do
echo $x
done
## STDOUT:
one
2
zzz
## END
## OK mksh STDOUT:
one
1
zzz
## END
#### $LINENO in other for loops
set -- a b c
for x; do
echo $LINENO $x
done
## STDOUT:
3 a
3 b
3 c
## END
#### $LINENO in for (( loop
# This is a real edge case that I'm not sure we care about. We would have to
# change the span ID inside the loop to make it really correct.
echo one
for (( i = 0; i < $LINENO; i++ )); do
echo $i
done
## STDOUT:
one
0
1
## END
## N-I dash stdout: one
## N-I dash status: 2
## BUG mksh stdout: one
## BUG mksh status: 1
#### $LINENO for assignment
a1=$LINENO a2=$LINENO
b1=$LINENO b2=$LINENO
echo $a1 $a2
echo $b1 $b2
## STDOUT:
1 1
2 2
## END
|
Java
|
UTF-8
| 748 | 2.25 | 2 |
[] |
no_license
|
package com.yutai.audio.model.dao.user;
import java.util.List;
import com.yutai.audio.model.beans.user.User;
public interface IUserDAO {
//注册
public abstract boolean addUser(User user);
//根据ID查找用户
public abstract User selectUserByID(int user_id);
//根据手机号查找用户
public abstract User selectUserByPhone(String user_phone);
//查询所有的用户
public abstract List<User> selectAllUser();
//修改用户
public abstract boolean updateUserByID(User user,int user_id);
//查找用户密码是否一致
public abstract boolean selectUserOKPasswordByID(String user_password_old,int user_id);
//修改用户密码
public abstract boolean updateUserPasswordByID(String user_password_new,int user_id);
}
|
PHP
|
UTF-8
| 1,668 | 2.796875 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
include_once("../config.inc.php");
include_once("../db.inc.php");
include_once("../utils.inc.php");
$input = json_decode(file_get_contents('php://input'),true);
$uploadOk = true;
// Verify parameter of the song.
if(empty($input['trackName']) || empty($input['artist']) || !is_int($input['genre']))
{
logError("empty parameter: the name : " . $input['trackName'] . ' or the artist : ' . $input['artist'] . ' or the genre : ' . $input['genre']);
$uploadOk = false;
}
do //Generate name file
{
$outputFileName = bin2hex(random_bytes(8));
$target_file = $relativeMusicDirectory . $outputFileName;
} while(file_exists($target_file));
// Check file size
if (filesize($_FILES['fileToUpload']['tmp_name']) == $_FILES['fileToUpload']['size'] && $_FILES['fileToUpload']['size'] > 500000)
{
logError("Upload failed, size inconsistent : " . filesize($_FILES['fileToUpload']['tmp_name']) . " != " . $_FILES['fileToUpload']['size'] . " || > 500 000");
$uploadOk = false;
}
//Move file and register song
if ($uploadOk)
{
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file))
{
logError("The file ". $_FILES['fileToUpload']['tmp_name']. " has been uploaded and renamed to $target_file.");
if(hasGenre($input['genre']))
{
registerSong($outputFileName, $input['artist'], $input['trackName'], $input['genre']);
}
}
else
{
logError("There was an error moving file ". $_FILES['fileToUpload']['tmp_name'] . " to " . $target_file);
}
}
if($uploadOk)
echo '{"status":"success"}';
else
echo '{"status":"error", "error":"upload failed, or invalid file"}';
|
Java
|
UTF-8
| 1,945 | 2.296875 | 2 |
[] |
no_license
|
package com.movie.pitang.models.results;
import java.util.Set;
public abstract class ProgramaResult {
private String poster_path;
private String overview;
private Set<Integer> genre_ids;
private long id;
private String original_language;
private String backdrop_path;
private double popularity;
private Integer vote_count;
private double vote_average;
public ProgramaResult() {
}
public String getPoster_path() {
return poster_path;
}
public void setPoster_path(String poster_path) {
this.poster_path = poster_path;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public Set<Integer> getGenre_ids() {
return genre_ids;
}
public void setGenre_ids(Set<Integer> genre_ids) {
this.genre_ids = genre_ids;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getOriginal_language() {
return original_language;
}
public void setOriginal_language(String original_language) {
this.original_language = original_language;
}
public String getBackdrop_path() {
return backdrop_path;
}
public void setBackdrop_path(String backdrop_path) {
this.backdrop_path = backdrop_path;
}
public double getPopularity() {
return popularity;
}
public void setPopularity(double popularity) {
this.popularity = popularity;
}
public Integer getVote_count() {
return vote_count;
}
public void setVote_count(Integer vote_count) {
this.vote_count = vote_count;
}
public double getVote_average() {
return vote_average;
}
public void setVote_average(double vote_average) {
this.vote_average = vote_average;
}
}
|
Java
|
UTF-8
| 18,287 | 2.40625 | 2 |
[] |
no_license
|
package an.xacml.policy.function;
import static an.xacml.policy.AttributeValue.FALSE;
import static an.xacml.policy.AttributeValue.TRUE;
import java.math.BigInteger;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import an.xacml.Constants;
import an.xacml.IndeterminateException;
import an.xacml.engine.EvaluationContext;
import an.xacml.policy.AttributeValue;
@XACMLFunctionProvider
public abstract class CommonFunctions {
public static void checkArguments(Object[] params, int expectedNumber) throws IndeterminateException {
// check null
checkNull(params);
// check parameters number
if (expectedNumber > 0 && params.length != expectedNumber) {
throw new IndeterminateException("Expected " + expectedNumber +
" parameters, but got " + params.length + ".");
}
// check parameters type
for (Object param : params) {
if (param != null && !(param instanceof AttributeValue) && !(param instanceof AttributeValue[])) {
throw new IndeterminateException("Expected 'AttributeValue' type, but got '" +
param.getClass().getSimpleName() + "' type.");
}
}
}
public static void checkNull(Object[] params) throws IndeterminateException {
for (Object param : params) {
checkNull(param);
}
}
public static void checkNull(Object arg) throws IndeterminateException {
if (arg == null) {
throw new IndeterminateException("The argument is null.");
}
}
public static void checkArgumentType(AttributeValue attrVal, URI expectedType)
throws IndeterminateException {
URI actualType = attrVal.getDataType();
if (!actualType.equals(expectedType)) {
throw new IndeterminateException("Expected '" + expectedType.toString() +
"', but got '" + actualType.toString() + "'");
}
}
@EquivalentFunction
@XACMLFunction({
"urn:oasis:names:tc:xacml:1.0:function:string-equal",
"urn:oasis:names:tc:xacml:1.0:function:boolean-equal",
"urn:oasis:names:tc:xacml:1.0:function:integer-equal",
"urn:oasis:names:tc:xacml:1.0:function:date-equal",
"urn:oasis:names:tc:xacml:1.0:function:time-equal",
"urn:oasis:names:tc:xacml:1.0:function:dateTime-equal",
"urn:oasis:names:tc:xacml:1.0:function:dayTimeDuration-equal",
"urn:oasis:names:tc:xacml:1.0:function:yearMonthDuration-equal",
"urn:oasis:names:tc:xacml:1.0:function:anyURI-equal",
"urn:oasis:names:tc:xacml:1.0:function:x500Name-equal",
"urn:oasis:names:tc:xacml:1.0:function:rfc822Name-equal",
"urn:oasis:names:tc:xacml:1.0:function:hexBinary-equal",
"urn:oasis:names:tc:xacml:1.0:function:base64Binary-equal"
})
public static AttributeValue equals(EvaluationContext ctx, Object[] params) throws IndeterminateException {
checkArguments(params, 2);
params = checkArrayArguments(params);
AttributeValue o1 = (AttributeValue)params[0];
AttributeValue o2 = (AttributeValue)params[1];
// System.out.println( o1.getValue() + " = " + o2.getValue());
if (o1 != null && o2 != null) {
if (o1 == o2) {
return TRUE;
}
return o1.equals(o2) ? TRUE : FALSE;
}
return FALSE;
}
public static Object[] checkArrayArguments(Object[] params) throws IndeterminateException {
for (int i=0; i < params.length; i++) {
if (params[i] instanceof Object[]) {
Object[] temp = (Object[]) params[i];
if (temp.length == 1) {
params[i] = temp[0];
} else {
throw new IndeterminateException("Array is to long. Please check your policy.");
}
}
}
return params;
}
@XACMLFunction({
"urn:oasis:names:tc:xacml:1.0:function:string-one-and-only",
"urn:oasis:names:tc:xacml:1.0:function:boolean-one-and-only",
"urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only",
"urn:oasis:names:tc:xacml:1.0:function:double-one-and-only",
"urn:oasis:names:tc:xacml:1.0:function:time-one-and-only",
"urn:oasis:names:tc:xacml:1.0:function:date-one-and-only",
"urn:oasis:names:tc:xacml:1.0:function:dateTime-one-and-only",
"urn:oasis:names:tc:xacml:1.0:function:anyURI-one-and-only",
"urn:oasis:names:tc:xacml:1.0:function:hexBinary-one-and-only",
"urn:oasis:names:tc:xacml:1.0:function:base64Binary-one-and-only",
"urn:oasis:names:tc:xacml:1.0:function:dayTimeDuration-one-and-only",
"urn:oasis:names:tc:xacml:1.0:function:yearMonthDuration-one-and-only",
"urn:oasis:names:tc:xacml:1.0:function:x500Name-one-and-only",
"urn:oasis:names:tc:xacml:1.0:function:rfc822Name-one-and-only"
})
public static AttributeValue bagOneAndOnly(EvaluationContext ctx, Object[] params)
throws IndeterminateException {
checkArguments(params, 1);
AttributeValue[] bag = (AttributeValue[])params[0];
if (bag != null && bag.length == 1) {
return bag[0];
}
throw new IndeterminateException("Expected 1 and only 1 element in bag, but we got " +
(bag == null ? "'null'" : bag.length));
}
@XACMLFunction({
"urn:oasis:names:tc:xacml:1.0:function:string-bag-size",
"urn:oasis:names:tc:xacml:1.0:function:boolean-bag-size",
"urn:oasis:names:tc:xacml:1.0:function:integer-bag-size",
"urn:oasis:names:tc:xacml:1.0:function:double-bag-size",
"urn:oasis:names:tc:xacml:1.0:function:time-bag-size",
"urn:oasis:names:tc:xacml:1.0:function:date-bag-size",
"urn:oasis:names:tc:xacml:1.0:function:dateTime-bag-size",
"urn:oasis:names:tc:xacml:1.0:function:anyURI-bag-size",
"urn:oasis:names:tc:xacml:1.0:function:hexBinary-bag-size",
"urn:oasis:names:tc:xacml:1.0:function:base64Binary-bag-size",
"urn:oasis:names:tc:xacml:1.0:function:dayTimeDuration-bag-size",
"urn:oasis:names:tc:xacml:1.0:function:yearMonthDuration-bag-size",
"urn:oasis:names:tc:xacml:1.0:function:x500Name-bag-size",
"urn:oasis:names:tc:xacml:1.0:function:rfc822Name-bag-size"
})
public static AttributeValue bagSize(EvaluationContext ctx, Object[] params)
throws IndeterminateException {
checkArguments(params, 1);
AttributeValue[] bag = (AttributeValue[])params[0];
try {
return AttributeValue.getInstance(Constants.TYPE_INTEGER, BigInteger.valueOf(bag.length));
}
catch (Exception ex) {
throw new IndeterminateException("Error occurs while evaluating function bagSize.", ex);
}
}
@XACMLFunction({
"urn:oasis:names:tc:xacml:1.0:function:string-is-in",
"urn:oasis:names:tc:xacml:1.0:function:boolean-is-in",
"urn:oasis:names:tc:xacml:1.0:function:integer-is-in",
"urn:oasis:names:tc:xacml:1.0:function:double-is-in",
"urn:oasis:names:tc:xacml:1.0:function:time-is-in",
"urn:oasis:names:tc:xacml:1.0:function:date-is-in",
"urn:oasis:names:tc:xacml:1.0:function:dateTime-is-in",
"urn:oasis:names:tc:xacml:1.0:function:anyURI-is-in",
"urn:oasis:names:tc:xacml:1.0:function:hexBinary-is-in",
"urn:oasis:names:tc:xacml:1.0:function:base64Binary-is-in",
"urn:oasis:names:tc:xacml:1.0:function:dayTimeDuration-is-in",
"urn:oasis:names:tc:xacml:1.0:function:yearMonthDuration-is-in",
"urn:oasis:names:tc:xacml:1.0:function:x500Name-is-in",
"urn:oasis:names:tc:xacml:1.0:function:rfc822Name-is-in"
})
public static AttributeValue bagIsIn(EvaluationContext ctx, Object[] params)
throws IndeterminateException {
checkArguments(params, 2);
checkNull(params);
AttributeValue o = (AttributeValue)params[0];
AttributeValue[] bag = (AttributeValue[])params[1];
for (AttributeValue each : bag) {
if (equals(ctx, new AttributeValue[] {o, each}) == TRUE) {
return TRUE;
}
}
return FALSE;
}
@XACMLFunction({
"urn:oasis:names:tc:xacml:1.0:function:string-bag",
"urn:oasis:names:tc:xacml:1.0:function:boolean-bag",
"urn:oasis:names:tc:xacml:1.0:function:integer-bag",
"urn:oasis:names:tc:xacml:1.0:function:double-bag",
"urn:oasis:names:tc:xacml:1.0:function:time-bag",
"urn:oasis:names:tc:xacml:1.0:function:date-bag",
"urn:oasis:names:tc:xacml:1.0:function:dateTime-bag",
"urn:oasis:names:tc:xacml:1.0:function:anyURI-bag",
"urn:oasis:names:tc:xacml:1.0:function:hexBinary-bag",
"urn:oasis:names:tc:xacml:1.0:function:base64Binary-bag",
"urn:oasis:names:tc:xacml:1.0:function:dayTimeDuration-bag",
"urn:oasis:names:tc:xacml:1.0:function:yearMonthDuration-bag",
"urn:oasis:names:tc:xacml:1.0:function:x500Name-bag",
"urn:oasis:names:tc:xacml:1.0:function:rfc822Name-bag"
})
public static AttributeValue[] bagBag(EvaluationContext ctx, Object[] params)
throws IndeterminateException {
for (Object param : params) {
if (param != null && !(param instanceof AttributeValue)) {
throw new IndeterminateException("Expected 'AttributeValue' type, but got '" +
param.getClass().getSimpleName() + "' type.");
}
}
AttributeValue[] result = new AttributeValue[params.length];
System.arraycopy(params, 0, result, 0, params.length);
return result;
}
@XACMLFunction({
"urn:oasis:names:tc:xacml:1.0:function:string-intersection",
"urn:oasis:names:tc:xacml:1.0:function:boolean-intersection",
"urn:oasis:names:tc:xacml:1.0:function:integer-intersection",
"urn:oasis:names:tc:xacml:1.0:function:double-intersection",
"urn:oasis:names:tc:xacml:1.0:function:time-intersection",
"urn:oasis:names:tc:xacml:1.0:function:date-intersection",
"urn:oasis:names:tc:xacml:1.0:function:dateTime-intersection",
"urn:oasis:names:tc:xacml:1.0:function:anyURI-intersection",
"urn:oasis:names:tc:xacml:1.0:function:hexBinary-intersection",
"urn:oasis:names:tc:xacml:1.0:function:base64Binary-intersection",
"urn:oasis:names:tc:xacml:1.0:function:dayTimeDuration-intersection",
"urn:oasis:names:tc:xacml:1.0:function:yearMonthDuration-intersection",
"urn:oasis:names:tc:xacml:1.0:function:x500Name-intersection",
"urn:oasis:names:tc:xacml:1.0:function:rfc822Name-intersection"
})
public static AttributeValue[] setIntersection(EvaluationContext ctx, Object[] params)
throws IndeterminateException {
checkArguments(params, 2);
AttributeValue[] bag1 = (AttributeValue[])params[0];
AttributeValue[] bag2 = (AttributeValue[])params[0];
Set<AttributeValue> result = new HashSet<AttributeValue>();
for (AttributeValue each1 : bag1) {
for (AttributeValue each2 : bag2) {
if (equals(ctx, new AttributeValue[] {each1, each2}) == TRUE) {
result.add(each1);
}
}
}
return result.toArray(bag1);
}
@XACMLFunction({
"urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of",
"urn:oasis:names:tc:xacml:1.0:function:boolean-at-least-one-member-of",
"urn:oasis:names:tc:xacml:1.0:function:integer-at-least-one-member-of",
"urn:oasis:names:tc:xacml:1.0:function:double-at-least-one-member-of",
"urn:oasis:names:tc:xacml:1.0:function:time-at-least-one-member-of",
"urn:oasis:names:tc:xacml:1.0:function:date-at-least-one-member-of",
"urn:oasis:names:tc:xacml:1.0:function:dateTime-at-least-one-member-of",
"urn:oasis:names:tc:xacml:1.0:function:anyURI-at-least-one-member-of",
"urn:oasis:names:tc:xacml:1.0:function:hexBinary-at-least-one-member-of",
"urn:oasis:names:tc:xacml:1.0:function:base64Binary-at-least-one-member-of",
"urn:oasis:names:tc:xacml:1.0:function:dayTimeDuration-at-least-one-member-of",
"urn:oasis:names:tc:xacml:1.0:function:yearMonthDuration-at-least-one-member-of",
"urn:oasis:names:tc:xacml:1.0:function:x500Name-at-least-one-member-of",
"urn:oasis:names:tc:xacml:1.0:function:rfc822Name-at-least-one-member-of"
})
public static AttributeValue setAtLeastOneMemberOf(EvaluationContext ctx, Object[] params)
throws IndeterminateException {
checkArguments(params, 2);
AttributeValue[] bag1 = (AttributeValue[])params[0];
AttributeValue[] bag2 = (AttributeValue[])params[1];
for (AttributeValue each : bag1) {
if (bagIsIn(ctx, new Object[] {each, bag2}) == TRUE) {
return TRUE;
}
}
return FALSE;
}
@XACMLFunction({
"urn:oasis:names:tc:xacml:1.0:function:string-union",
"urn:oasis:names:tc:xacml:1.0:function:boolean-union",
"urn:oasis:names:tc:xacml:1.0:function:integer-union",
"urn:oasis:names:tc:xacml:1.0:function:double-union",
"urn:oasis:names:tc:xacml:1.0:function:time-union",
"urn:oasis:names:tc:xacml:1.0:function:date-union",
"urn:oasis:names:tc:xacml:1.0:function:dateTime-union",
"urn:oasis:names:tc:xacml:1.0:function:anyURI-union",
"urn:oasis:names:tc:xacml:1.0:function:hexBinary-union",
"urn:oasis:names:tc:xacml:1.0:function:base64Binary-union",
"urn:oasis:names:tc:xacml:1.0:function:dayTimeDuration-union",
"urn:oasis:names:tc:xacml:1.0:function:yearMonthDuration-union",
"urn:oasis:names:tc:xacml:1.0:function:x500Name-union",
"urn:oasis:names:tc:xacml:1.0:function:rfc822Name-union"
})
public static AttributeValue[] setUnion(EvaluationContext ctx, Object[] params)
throws IndeterminateException {
checkArguments(params, 2);
AttributeValue[] bag1 = (AttributeValue[])params[0];
AttributeValue[] bag2 = (AttributeValue[])params[0];
Set<AttributeValue> result = new HashSet<AttributeValue>();
for (AttributeValue each : bag1) {
result.add(each);
}
for (AttributeValue each : bag2) {
result.add(each);
}
return result.toArray(bag1);
}
@XACMLFunction({
"urn:oasis:names:tc:xacml:1.0:function:string-subset",
"urn:oasis:names:tc:xacml:1.0:function:boolean-subset",
"urn:oasis:names:tc:xacml:1.0:function:integer-subset",
"urn:oasis:names:tc:xacml:1.0:function:double-subset",
"urn:oasis:names:tc:xacml:1.0:function:time-subset",
"urn:oasis:names:tc:xacml:1.0:function:date-subset",
"urn:oasis:names:tc:xacml:1.0:function:dateTime-subset",
"urn:oasis:names:tc:xacml:1.0:function:anyURI-subset",
"urn:oasis:names:tc:xacml:1.0:function:hexBinary-subset",
"urn:oasis:names:tc:xacml:1.0:function:base64Binary-subset",
"urn:oasis:names:tc:xacml:1.0:function:dayTimeDuration-subset",
"urn:oasis:names:tc:xacml:1.0:function:yearMonthDuration-subset",
"urn:oasis:names:tc:xacml:1.0:function:x500Name-subset",
"urn:oasis:names:tc:xacml:1.0:function:rfc822Name-subset"
})
public static AttributeValue setSubset(EvaluationContext ctx, Object[] params)
throws IndeterminateException {
checkArguments(params, 2);
AttributeValue[] bag1 = (AttributeValue[])params[0];
AttributeValue[] bag2 = (AttributeValue[])params[0];
Set<AttributeValue> set1 = new HashSet<AttributeValue>();
for (AttributeValue each : bag1) {
set1.add(each);
}
Set<AttributeValue> set2 = new HashSet<AttributeValue>();
for (AttributeValue each : bag2) {
set2.add(each);
}
return set2.containsAll(set1) ? TRUE : FALSE;
}
@EquivalentFunction
@XACMLFunction({
"urn:oasis:names:tc:xacml:1.0:function:string-set-equals",
"urn:oasis:names:tc:xacml:1.0:function:boolean-set-equals",
"urn:oasis:names:tc:xacml:1.0:function:integer-set-equals",
"urn:oasis:names:tc:xacml:1.0:function:double-set-equals",
"urn:oasis:names:tc:xacml:1.0:function:time-set-equals",
"urn:oasis:names:tc:xacml:1.0:function:date-set-equals",
"urn:oasis:names:tc:xacml:1.0:function:dateTime-set-equals",
"urn:oasis:names:tc:xacml:1.0:function:anyURI-set-equals",
"urn:oasis:names:tc:xacml:1.0:function:hexBinary-set-equals",
"urn:oasis:names:tc:xacml:1.0:function:base64Binary-set-equals",
"urn:oasis:names:tc:xacml:1.0:function:dayTimeDuration-set-equals",
"urn:oasis:names:tc:xacml:1.0:function:yearMonthDuration-set-equals",
"urn:oasis:names:tc:xacml:1.0:function:x500Name-set-equals",
"urn:oasis:names:tc:xacml:1.0:function:rfc822Name-set-equals"
})
public static AttributeValue setEquals(EvaluationContext ctx, Object[] params)
throws IndeterminateException {
checkArguments(params, 2);
AttributeValue[] bag1 = (AttributeValue[])params[0];
AttributeValue[] bag2 = (AttributeValue[])params[0];
// FIXME - I didn't follow the specification here.
Set<AttributeValue> set1 = new HashSet<AttributeValue>();
for (AttributeValue each : bag1) {
set1.add(each);
}
Set<AttributeValue> set2 = new HashSet<AttributeValue>();
for (AttributeValue each : bag2) {
set2.add(each);
}
return (set1.size() == set2.size() && set1.containsAll(set2)) ? TRUE : FALSE;
}
}
|
Java
|
UTF-8
| 170 | 1.796875 | 2 |
[] |
no_license
|
package com.jajahome.service;
import com.jajahome.po.User;
public interface UserService {
User selectUserByUserAndPass(User user);
int insert(User record);
}
|
Java
|
UTF-8
| 9,174 | 2.109375 | 2 |
[] |
no_license
|
package ru.zzsdeo.mymoneybalance;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.TextView;
public class MainFragment extends Fragment implements LoaderCallbacks<Cursor> {
//<vars
private TextView warningText;
private MySimpleCursorAdapter scAdapter;
private static final int CM_DELETE_ID = 1;
private static final int CM_EDIT_ID = 2;
//vars>
//<functions
private void myBalance (View v) {
TextView cardInfo = (TextView) v.findViewById(R.id.cardInfo);
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
Cursor c = db.query("mytable", null, "card = 'Cash'", null, null, null, "datetime desc, _id desc");
if (c.moveToFirst()) {
cardInfo.setText("Наличные: " + Double.toString(c.getDouble(c.getColumnIndex("calculatedbalance"))) + "\n");
}
c = db.query("mytable", null, "card = 'Card2485'", null, null, null, "datetime desc, _id desc");
if (c.moveToFirst()) {
cardInfo.append("Зарплатная: " + Double.toString(c.getDouble(c.getColumnIndex("calculatedbalance"))) + "\n");
}
c = db.query("mytable", null, "card = 'Card0115'", null, null, null, "datetime desc, _id desc");
if (c.moveToFirst()) {
cardInfo.append("Кредитная: " + Double.toString(c.getDouble(c.getColumnIndex("calculatedbalance"))));
}
}
//functions>
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_item:
DialogFragment addDialog = new AddDialog();
addDialog.show(getFragmentManager(), "addDialog");
return true;
default:
return false;
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
// получаем из пункта контекстного меню данные по пункту списка
AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case CM_DELETE_ID:
// извлекаем id записи и удаляем соответствующую запись в БД
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
Cursor c = db.query("mytable", null, "_id = " + acmi.id, null, null, null, null);
c.moveToFirst();
String card = c.getString(c.getColumnIndex("card"));
db.delete("mytable", "_id = " + acmi.id, null);
//обновляем баланс
ContentValues cv = new ContentValues();
c = db.query("mytable", null, "card = " + '"' + card + '"', null, null, null, "datetime asc");
if (c.moveToFirst()) {
double balance = 0;
do {
double am;
if (c.getString(c.getColumnIndex("expenceincome")).equals("Rashod")) {
am = -c.getDouble(c.getColumnIndex("amount"));
} else {
am = c.getDouble(c.getColumnIndex("amount"));
}
balance = balance + am - c.getDouble(c.getColumnIndex("comission"));
Log.d("myLogs", "Удаление " + Double.toString(balance));
cv.put("calculatedbalance", Round.roundedDouble(balance));
db.update("mytable", cv, "_id = " + '"' + c.getInt(c.getColumnIndex("_id")) + '"', null);
cv.clear();
} while (c.moveToNext());
}
// получаем новый курсор с данными
getLoaderManager().getLoader(0).forceLoad();
myBalance(getView());
return true;
case CM_EDIT_ID:
Log.d("myLogs", "edit "+acmi.id);
Bundle args = new Bundle();
args.putLong("id", acmi.id);
DialogFragment editDialog = new EditDialog();
editDialog.setArguments(args);
editDialog.show(getFragmentManager(), "editDialog");
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, CM_DELETE_ID, 0, R.string.delete_record);
menu.add(0, CM_EDIT_ID, 1, R.string.edit);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main, parent, false);
DatabaseManager.initializeInstance(new DBHelper(getActivity()));
warningText = (TextView) v.findViewById(R.id.warningTextView);
myBalance(v);
//<list view
ListView transactionsListView = (ListView) v.findViewById(R.id.transactionsListView);
String[] from = new String[]{"datetime", "paymentdetails", "card", "amount", "calculatedbalance"};
int[] to = new int[]{R.id.lvDateTime, R.id.lvDetails, R.id.lvCard, R.id.lvAmount, R.id.lvBalance};
scAdapter = new MySimpleCursorAdapter(getActivity(), R.layout.list_item, null, from, to, 0);
transactionsListView.setAdapter(scAdapter);
registerForContextMenu(transactionsListView);
getLoaderManager().initLoader(0, null, this);
transactionsListView.setOnItemClickListener( new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra("position", i);
startActivity(intent);
}
});
//list view>
return v;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), null, null, null, null, null) {
@Override
public Cursor loadInBackground() {
// You better know how to get your database.
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
// You can use any query that returns a cursor.
return db.query("mytable", null, null, null, null, null, "datetime desc, _id desc");
}
};
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
scAdapter.swapCursor(arg1);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
}
@Override
public void onDestroy() {
super.onDestroy();
DatabaseManager.getInstance().closeDatabase();
}
@Override
public void onResume() {
super.onResume();
getLoaderManager().getLoader(0).forceLoad();
//<warning + start stop service
PackageManager pm = getActivity().getPackageManager();
ComponentName component = new ComponentName(getActivity(), SmsReceiver.class);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
warningText.setTextColor(Color.RED);
if (!settings.getBoolean("start_service", true)) {
pm.setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
warningText.setText("Перехват SMS от банка отключен");
}
if ((settings.getBoolean("start_service", true)) & (pm.getComponentEnabledSetting(component) != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)) {
pm.setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, PackageManager.DONT_KILL_APP);
warningText.setText("");
}
//warning + start stop service>
}
}
|
Java
|
UTF-8
| 2,159 | 3.296875 | 3 |
[] |
no_license
|
public class Solution {
public String minWindow(String S, String T) {
int cnt = 0; // Used for finding the first window
int len = 0; // Length of current window
int min = 0;
boolean found = false;
String result = "";
Map<Character, Integer> needToFind = new HashMap<Character, Integer>();
Map<Character, Integer> hasFound = new HashMap<Character, Integer>();
for (int i = 0; i < T.length(); i++) {
char c = T.charAt(i);
if (!needToFind.containsKey(c)) {
needToFind.put(c, 1);
}
else {
needToFind.put(c, needToFind.get(c) + 1);
}
}
// Find first window
int i = 0;
while (i < S.length()) {
char c = S.charAt(i);
if (!hasFound.containsKey(c)) {
hasFound.put(c, 1);
}
else {
hasFound.put(c, hasFound.get(c) + 1);
}
len++;
if (needToFind.containsKey(c) && (needToFind.get(c) >= hasFound.get(c))) {
cnt++;
}
if (cnt == T.length()) {
if (!found) {
found = true;
min = len;
result = S.substring(0, i + 1);
}
// Try to move left
int j = i - len + 1;
char temp = S.charAt(j);
while (!needToFind.containsKey(temp) || needToFind.get(temp) < hasFound.get(temp)) {
hasFound.put(temp, hasFound.get(temp) - 1);
len--;
if (len < min) {
min = len;
result = S.substring(j + 1, i + 1);
}
j++;
temp = S.charAt(j);
}
}
i++;
}
return result;
}
}
|
Java
|
UTF-8
| 3,703 | 2.40625 | 2 |
[] |
no_license
|
package com.zealot.boss.base.service.authorize.impl;
import java.util.*;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.zealot.boss.base.dao.authorize.DepartmentDao;
import com.zealot.boss.base.entity.authorize.Department;
import com.zealot.boss.base.service.authorize.DepartmentService;
import com.zealot.exception.AppException;
import com.zealot.exception.ResultException;
import com.zealot.exception.message.MessageCode;
@Service("departmentService")
public class DepartmentServiceImpl implements DepartmentService {
@Resource
private DepartmentDao departmentDAO;
/**
* 查找单个部门信息
*/
public Department findById(Integer id) throws AppException {
return departmentDAO.findDepartmentById(id);
}
/**
* 查找所有子菜單
*/
public List <Department> getChildrenDepartmentList(Integer parentId) throws AppException
{
List <Department> departmentList = departmentDAO.findByParentId( parentId );
return departmentList;
}
/**
* 根据路径查询路径菜單
*/
public List <Department> getDepartmentListByPath(String path) throws AppException
{
Department dep = new Department();
dep.setPath(path);
List <Department> departmentList = departmentDAO.findByPath(path);
return departmentList;
}
/**
* 查找所有根部门
*/
public List<Department> findRootDepartmentList() throws AppException {
List<Department> departmentList = this.getChildrenDepartmentList(0);
return departmentList;
}
/**
* 查找所有部门
*/
public List<Department> findAll() throws AppException {
return departmentDAO.findAll();
}
/**
*從所有菜單中找子菜單
*/
public List<Department> findChildList(Department department, List<Department> allDepartmentList){
List<Department> tmpList = new LinkedList<Department>();
for( Department childDepartment : allDepartmentList){
if( childDepartment.getParentId().intValue() == department.getId().intValue() ){
tmpList.add( childDepartment );
}
}
return tmpList;
}
/**
* 添加department
* @param department
* @throws AppException
*/
public void add(Department department) throws AppException {
Date date = new Date();
department.setCreateTime(date);
department.setUpdateTime(date);
List<Department> existDepartment = this.getChildrenDepartmentList(department.getParentId());
department.setIorder(existDepartment.size() + 1);
departmentDAO.saveDepartment(department);
}
/**
* 更新department
* @param department
* @throws AppException
*/
public void update(Department department) throws AppException {
//String[] ignoreArray = { "id", "createTime" };
Department persistent = findById(department.getId());
//BeanUtils.copyProperties(department, persistent, ignoreArray);
persistent.setName(department.getName());
persistent.setIorder(department.getIorder());
persistent.setUpdateTime(new Date());
persistent.setUpdatedBy(department.getUpdatedBy());
departmentDAO.updateDepartment(persistent);
}
/**
* 删除department
* @param department
* @throws AppException
*/
public void delete(Department department) throws AppException,ResultException {
List<Department> childList = this.getChildrenDepartmentList(department.getId());
if (childList.size() > 0) {
throw new ResultException(MessageCode.DEP_CHILD_EXITS);
}
Long count = departmentDAO.countUserByDepartment(department.getId());
if (count > 0) {
throw new ResultException(MessageCode.DEP_USER_EXITS);
}
departmentDAO.deleteDepartment(department);
}
}
|
Python
|
UTF-8
| 369 | 2.75 | 3 |
[] |
no_license
|
from microbit import *
def display_acc_data():
my_send = accelerometer.get_values()
display.scroll("x")
display.scroll(str(my_send[0]))
display.scroll("y")
display.scroll(str(my_send[1]))
display.scroll("z")
display.scroll(str(my_send[2]))
sleep(800)
while True:
if button_a.was_pressed():
display_acc_data()
|
C++
|
UTF-8
| 1,272 | 2.578125 | 3 |
[] |
no_license
|
#include <utilities/config.h>
using namespace utilities;
Config::Config(std::string package_name) : package_name(package_name)
{
}
void Config::loadParam(ros::NodeHandle *nh, std::string name, std::string ¶m, std::string default_param)
{
nh->param<std::string>(name, param, default_param);
ROS_INFO("[%s::Config::loadParam::%s]: %s = %s", package_name.c_str(), nh->getNamespace().c_str(), name.c_str(), param.c_str());
}
void Config::loadParam(ros::NodeHandle *nh, std::string name, int ¶m, int default_param)
{
nh->param<int>(name, param, default_param);
ROS_INFO("[%s::Config::loadParam]: %s = %i", package_name.c_str(), name.c_str(), param);
}
void Config::loadParam(ros::NodeHandle *nh, std::string name, double ¶m, double default_param)
{
nh->param<double>(name, param, default_param);
ROS_INFO("[%s::Config::loadParam]: %s = %f", package_name.c_str(), name.c_str(), param);
}
void Config::loadParam(ros::NodeHandle *nh, std::string name, bool ¶m, bool default_param)
{
nh->param<bool>(name, param, default_param);
if (param)
{
ROS_INFO("[%s::Config::loadParam]: %s = true", package_name.c_str(), name.c_str());
}
else
{
ROS_INFO("[%s::Config::loadParam]: %s = false", package_name.c_str(), name.c_str());
}
}
|
C++
|
UTF-8
| 1,946 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
/************************************************************************
STM32F746 Discovery show SD-card directory on TFT
Required libraries: GFX, Adafruit
Installation Instructions:
1. Import the Adadruit library in the menue
Sketch=>Include Libraries=>Manage Libraries => Adafruit ILI9341
2. Import the Adadruit GFX-Library
Sketch=>Include Libraries=>Manage Libraries => Adafruit GFX Library
This code is mainly derived fron the "OpenNext" example from the
SdFat examples.
June 2017, ChrisMicro
************************************************************************/
#include "SdFat.h"
#include "LTDC_F746_Discovery.h"
SdFatSdio sd;
SdFile file;
LTDC_F746_Discovery tft;
void setup()
{
// The buffer is memory mapped
// You can directly draw on the display by writing to the buffer
uint16_t *buffer = (uint16_t *)malloc(2*LTDC_F746_ROKOTECH.width * LTDC_F746_ROKOTECH.height);
tft.begin((uint16_t *)buffer);
tft.fillScreen(LTDC_BLACK);
//tft.setRotation(0);
tft.setCursor(0, 0);
tft.setTextColor(LTDC_GREEN); tft.setTextSize(2);
tft.println("STM32F746 Discovery SD-card directory");
tft.setTextColor(LTDC_YELLOW); tft.setTextSize(1);
if (!sd.begin())
{
tft.setTextColor(LTDC_RED); tft.print("error SD-card not detected");
sd.initErrorHalt();
}
// Open next file in root. The volume working directory, vwd, is root.
// Warning, openNext starts at the current position of sd.vwd() so a
// rewind may be neccessary in your application.
sd.vwd()->rewind();
while (file.openNext(sd.vwd(), O_READ))
{
file.printFileSize(&tft);
tft.write(' ');
file.printModifyDateTime(&tft);
tft.write(' ');
file.printName(&tft);
if (file.isDir())
{
// Indicate a directory.
tft.write('/');
}
tft.println();
delay(1000);
file.close();
}
tft.setTextColor(LTDC_BLUE);
tft.println("Done!");
}
void loop()
{
}
|
Go
|
UTF-8
| 2,362 | 3.078125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
package ast
// superGlobalScope represents the scope containing superglobals such as $_GET
type SuperGlobalScope struct {
Identifiers []Variable
}
// globalScope represents the global scope on which functions and classes are
// defined. This is always within a namespace, but in many cases that may just
// be the default global namespace ("\")
type GlobalScope struct {
*Namespace
*Scope
}
// scope represents a particular local scope (such as within a function).
type Scope struct {
Identifiers map[string][]*Variable
DynamicVariables []*Variable
EnclosingScope *Scope
GlobalScope *GlobalScope
SuperGlobalScope *SuperGlobalScope
}
func (s *Scope) Variable(v *Variable) {
switch i := v.Name.(type) {
case Identifier:
s.Identifiers[i.Value] = append(s.Identifiers[i.Value], v)
default:
s.DynamicVariables = append(s.DynamicVariables, v)
}
}
type File struct {
Name string
Namespace Namespace
Nodes []Node
}
type FileSet struct {
Files map[string]*File
Namespaces map[string]*Namespace
GlobalNamespace *Namespace
*Scope
}
func NewFileSet() *FileSet {
return &FileSet{
Files: make(map[string]*File),
Namespaces: make(map[string]*Namespace),
GlobalNamespace: NewNamespace("/"),
Scope: NewScope(nil, &GlobalScope{}, &SuperGlobalScope{}),
}
}
func (f *FileSet) Namespace(name string) *Namespace {
_, ok := f.Namespaces[name]
if !ok {
f.Namespaces[name] = NewNamespace(name)
}
return f.Namespaces[name]
}
type Namespace struct {
Name string
ClassesAndInterfaces map[string]Statement
Constants map[string][]*Variable
Functions map[string]*FunctionStmt
}
func NewNamespace(name string) *Namespace {
return &Namespace{
Name: name,
ClassesAndInterfaces: map[string]Statement{},
Constants: map[string][]*Variable{},
Functions: map[string]*FunctionStmt{},
}
}
type Classer interface {
Node
ClassName() string
}
func (c Class) ClassName() string { return c.Name }
func (i Interface) ClassName() string { return i.Name }
func NewScope(parent *Scope, global *GlobalScope, superGlobal *SuperGlobalScope) *Scope {
return &Scope{
Identifiers: map[string][]*Variable{},
EnclosingScope: parent,
GlobalScope: global,
SuperGlobalScope: superGlobal,
}
}
|
JavaScript
|
UTF-8
| 2,586 | 2.90625 | 3 |
[] |
no_license
|
const MoveState = cc.Enum({
NONE : -1,
IDLE : -1,
UP : -1,
RIGHT : -1,
LEFT : -1,
DOWN : -1
});
cc.Class({
extends : cc.Component,
properties: {
moveSpeed : 0,
},
statics : {
MoveState : MoveState
},
//use node on to react with event
onLoad : function () {
this.moveState = MoveState.IDLE;
this.node.on("stand", this.idle, this);
this.node.on("freeze", this.stop, this);
this.node.on("update-dir", this.updateDir, this);
},
updateDir : function (event) {
this.moveDir = event.detail.dir;
},
// move state change functions
idle : function () {
if(this.moveState !== MoveState.IDLE){
this.moveState = MoveState.IDLE;
cc.log("MoveStateChange :: IDLE");
}
},
stop : function () {
this.moveState = MoveState.NONE;
this.moveDir = null;
cc.log("MoveStateChange :: STOP");
},
moveUp : function () {
if(this.moveState !== MoveState.UP){
this.moveState = MoveState.UP;
cc.log("MoveStateChange :: UP");
}
},
moveDown : function () {
if(this.moveState !== MoveState.DOWN){
this.moveState = MoveState.DOWN;
cc.log("MoveStateChange :: DOWN");
}
},
moveLeft : function () {
if(this.moveState !== MoveState.LEFT){
this.moveState = MoveState.LEFT;
// this.node.scaleX = -1;
cc.log("MoveStateChange :: LEFT");
}
},
moveRight : function () {
if(this.moveState !== MoveState.RIGHT){
this.moveState = MoveState.RIGHT;
// this.node.scaleX = 1;
cc.log("MoveStateChange :: RIGHT");
}
},
update : function (dt) {
if (this.moveDir) {
this.node.x += this.moveSpeed * this.moveDir.x * dt;
this.node.y += this.moveSpeed * this.moveDir.y * dt;
let deg = cc.radiansToDegrees(cc.pToAngle(this.moveDir));
// pay attention radiansToDegrees will provide a degree between (-180,180)
if (deg >= 45 && deg < 135){
this.moveUp();
}else if (deg >= 135 || deg < -135){
this.moveLeft();
}else if (deg >= -135 && deg < -45){
this.moveDown();
}else {
this.moveRight();
}
} else if (this.moveState !== MoveState.NONE) {
this.idle();
}
},
});
|
Java
|
UTF-8
| 349 | 1.695313 | 2 |
[
"MIT"
] |
permissive
|
package de.rieckpil.learning.codingchallenges;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CodingChallengesApplication {
public static void main(String[] args) {
SpringApplication.run(CodingChallengesApplication.class, args);
}
}
|
C++
|
UHC
| 4,077 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
// ***************************************************************
// UIRectString version: 1.0 ? date: 08/01/2008
// -------------------------------------------------------------
// Ͽ ؽƮ ϴ ƾ
// -------------------------------------------------------------
// Copyright (C) 2008 - All Rights Reserved
// ***************************************************************
//
// ***************************************************************
#ifndef UIRECTSTRING_H_
#define UIRECTSTRING_H_
#ifdef PRAGMA_ONCE
#pragma once
#endif
// #include <Engine/Interface/UIWindow.h>
// #include <vector>
//////////////////////////////////////////////////////////////////////////
// ؽƮ !!
enum eTextAlign
{
ALIGN_LEFT = 0,
ALIGN_CENTER,
ALIGN_RIGHT,
};
class CRectStringData
{
private:
UIRect m_rcStrRect;
COLOR m_Color;
CTString m_strData;
void CalculateRect();
public:
CRectStringData()
{
m_rcStrRect.SetRect(0,0,0,0);
m_Color = 0xFFFFFFFF;
m_strData = CTString("");
}
~CRectStringData()
{
}
CTString& GetString(){ return m_strData; }
void SetString(CTString& strInput, COLOR color = 0xFFFFFFFF);
void SetPos(int nPosX, int nPosY)
{
int nWidth = m_rcStrRect.GetWidth();
int nHeight = m_rcStrRect.GetHeight();
m_rcStrRect.SetRect(nPosX, nPosY, nPosX + nWidth, nPosY + nHeight);
}
void SetColor(COLOR color){ m_Color = color;}
void ClearString()
{
m_strData.Clear();
m_Color = 0xFFFFFFFF;
m_rcStrRect.SetRect(0,0,0,0);
}
int GetPosX(){ return m_rcStrRect.Left; }
int GetPosY(){ return m_rcStrRect.Top; }
int GetWidth(){ return m_rcStrRect.GetWidth(); }
int GetHeight(){ return m_rcStrRect.GetHeight(); }
COLOR GetColor(){ return m_Color; }
UIRect GetRect(){ return m_rcStrRect; }
};
class CUIRectString : public CUIWindow
{
private:
std::vector<CRectStringData> m_vecRcStringData;
std::vector<CTString> m_vecStringList; // ؽƮ( ..)
std::vector<COLOR> m_vecColor; // Į
int m_nAlign;
int CheckSplitPos(CTString& strInput, int nWidth);
void AddCRectStringData(CTString& strInput, COLOR color);
public:
CUIRectString() : m_nAlign(ALIGN_LEFT)
{
}
~CUIRectString()
{
}
void SetAlign(int nAlign);
void Create( CUIWindow *pParentWnd, int nX, int nY, int nWidth, int nHeight );
void Create( CUIWindow *pParentWnd, UIRect rcRect);
void SetSize(int nWidth, int nHeight);
void SetWidth( int nWidth );
void SetHeight( int nHeight );
void SetPos(int nPosX, int nPosY);
void SetPosX( int nX );
void SetPosY( int nY );
void Move( int ndX, int ndY );
int GetMaxStrWidth();
int GetMaxStrHeight();
void AddString(CTString& strInput, COLOR color = 0xFFFFFFFF);
void ClearString();
void Render();
BOOL IsEmpty() { return m_vecStringList.size() > 0 ? FALSE : TRUE; }
};
class CUIRectStringList : public CUIWindow
{
private:
std::vector<CUIRectString> m_vecRectString;
UIRect m_RectSeparate;
int m_nRowMax;
int m_nColMax;
int CalcRowColNum(int nRow, int nCol) {return ((nCol - 1) * m_nRowMax) + (nRow - 1);}
public:
CUIRectStringList() : m_nRowMax(0), m_nColMax(0)
{
}
~CUIRectStringList()
{
}
void Create( CUIWindow *pParentWnd, int nX, int nY, int nWidth, int nHeight );
void Create( CUIWindow *pParentWnd, UIRect rcRect);
void SetAlignAll(int nAlign);
void SetAlignRow(int nRow, int nAlign);
void SetAlignCol(int nCol, int nAlign);
void SetAlign(int nRow, int nCol, int nAlign);
void AddString(int nRow, int nCol, CTString& strInput, COLOR color = 0xFFFFFFFF);
void SetPos(int nPosX, int nPosY);
void SetPosX( int nX );
void SetPosY( int nY );
void Move( int ndX, int ndY );
void SetSize(int nWidth, int nHeight);
void SetWidth( int nWidth );
void SetHeight( int nHeight );
void SetRowCol(int nRow, int nCol);
void ClearStringAll();
void ClearString(int nRow, int nCol);
void Render();
};
#endif
//////////////////////////////////////////////////////////////////////////
|
Markdown
|
UTF-8
| 1,370 | 2.53125 | 3 |
[] |
no_license
|
---
layout: post
title: laravel5.2で検索結果の詳細表示
date: 2016-03-29 05:52:14
categories: laravel laravel-5
---
<p>お世話になります。<br>
<a href="http://qiita.com/zaburo/items/9fefa3f6834b2e79b734" rel="nofollow">http://qiita.com/zaburo/items/9fefa3f6834b2e79b734</a><br>
こちらを参考にし、laravelで検索を実装することができました。</p>
<p>しかしながら検索の詳細表示ができず困っています。<br>
routes.php</p>
```
Route::get('/detail/{id}', 'SearchController@detail');
```
<p>SearchController.php</p>
```
public function detail($id) {
$query = DB::table('item_master')->where('id',$id);
return view('layouts.detail.index')->with('query',$query);
}
```
<p>layouts.detail.index.blade.php</p>
```
<div>{{$query->id}}</div>
<div>{{$query->item_name}}</div>
```
<p>こちらで取得することができません。<br>
おそらく$queryでvar_dumpすると意図しないものがでてくる(無限ループ?)のでおそらくそこなのですが<br>
何が間違っているのかわかりません。<br>
ちなみにitem_masterテーブルには一意のidとitem_nameが入っています。</p>
<p>大変低レベルな質問で申し訳ないのですが<br>
ご教授のほどお願いいたします。</p>
|
SQL
|
UTF-8
| 2,201 | 3.90625 | 4 |
[] |
no_license
|
create table user
(id int not null primary key auto_increment,
name char(20) not null ,
age tinyint not null default 20,
sex enum('m','w') default 'm'
);
create table friend_circle
(id int not null primary key auto_increment,
uid int not null,
content text default null,
place char(20) default null,
posted_time datetime default now(),
picture text,
constraint user_fk foreign key(uid) references user(id)
);
create table comment_like(
id int not null primary key auto_increment,
uid int not null,
fid int not null,
dz enum('1','0') default '0',
comment text default null,
constraint use_fk foreign key(uid) references user(id),
constraint friend_fk foreign key(fid) references friend_circle(id)
);
create table stu
(
sid int primary key auto_increment,
name varchar(20),
age tinyint,
sex enum('m','w'),
native_place varchar(30)
);
create table teacher
(tid int primary key auto_increment,
name varchar(20),
age tinyint,
rank enum('讲师','副教授','教授')
);
create table course
(cid int primary key auto_increment,
name varchar(20),
credit decimal(2,1),
tid int,
constraint teacher_fk foreign key(tid) references teacher(tid)
);
create table chose_course
(id int primary key auto_increment,
sid int,
cid int,
socre decimal(3,1),
constraint student_fk foreign key(sid) references stu(sid),
constraint course_fk foreign key (cid) references course(cid)
);
--对book表进行重组
--分为 书籍表 作者表 和出版社表
--1. 通过ER模型规划三个表的内容和关系
--2. 设计三者之间的关系
--3. 根据你的设计创建三个表完善表关系
create table press
(pid int primary key auto_increment,
pname varchar(20),
address varchar(30),
phone char(11)
);
create table book
(bid int primary key auto_increment,
bname varchar(30),
publication_number smallint,
edition cahr(6),
publication_time date,
content text
);
create table writer
(wid int primary key auto_increment,
wname char(20),
age tinyint,
sex enum('m','w'),
country char(10),
phone char(11)
);
create table write
(bid int,
wid int,
write_time date ,
primary key(bid,wid),
constraint book_fk foreign key(bid) references book(bid),
constraint writer_fk foreign key(wid) references writer(wid)
);
|
Java
|
UTF-8
| 10,243 | 2.015625 | 2 |
[] |
no_license
|
/**
BamSeqChksum
Copyright (C) 2009-2014 German Tischler
Copyright (C) 2011-2014 Genome Research Limited
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
public class BamHeaderParser
{
public static class ReferenceSequenceInfo
{
String name;
int length;
ReferenceSequenceInfo(String name, int length)
{
this.name = name;
this.length = length;
}
}
enum state_enum {
readmagic,
readtextlength,
readtext,
readnumref,
readrefnamelen,
readrefnametext,
readreflen,
done
};
state_enum state;
byte magic[];
int magicread;
int textlen;
int textlenread;
byte text[];
int textread;
int numref;
int numrefread;
int numrefparsed;
int refnamelengthread;
int refnamelength;
int refnameread;
byte refname[];
int reflengthread;
int reflen;
public ReferenceSequenceInfo refseqs[];
public ReadGroup readgroups[];
int rgmask;
int rghashcnt[];
int rghashids[];
public BamHeaderParser()
{
state = state_enum.readmagic;
magicread = 0;
magic = new byte[4];
textlen = 0;
textlenread = 0;
textread = 0;
numref = 0;
numrefread = 0;
numrefparsed = 0;
rgmask = 0;
}
public int getNumReadGroups()
{
return readgroups.length;
}
public String getReadGroupId(int id)
{
if ( id < 0 || id >= readgroups.length )
return new String();
else
return readgroups[id].getId();
}
public static class AddBlockResult
{
boolean finished;
int offset;
AddBlockResult(boolean finished, int offset)
{
this.finished = finished;
this.offset = offset;
}
}
public static class ReadGroupKeyValuePair
{
byte ida;
byte idb;
int vallow;
int valhigh;
ReadGroupKeyValuePair(byte ida, byte idb, int vallow, int valhigh)
{
this.ida = ida;
this.idb = idb;
this.vallow = vallow;
this.valhigh = valhigh;
}
}
public static final long FNV_prime = 0x100000001b3l;
public static final long FNV_basis = 0xcbf29ce484222325l;
public class ReadGroup
{
int idlow;
int idhigh;
ReadGroupKeyValuePair [] items;
public int hashKey()
{
long h = FNV_basis;
for ( int i = idlow; i < idhigh; ++i )
{
h = h ^ ((long)text[i]);
h *= FNV_prime;
}
return (int)(h & 0x7FFFFFFFl);
}
ReadGroup(java.util.Vector<ReadGroupKeyValuePair> vitems)
{
boolean haveid = false;
idlow = -1;
idhigh = -1;
for ( ReadGroupKeyValuePair item : vitems )
if ( item.ida == 'I' && item.idb == 'D' )
{
haveid = true;
idlow = item.vallow;
idhigh = item.valhigh;
}
items = haveid ? new ReadGroupKeyValuePair[vitems.size()-1] : new ReadGroupKeyValuePair[vitems.size()];
int i = 0;
for ( ReadGroupKeyValuePair item : vitems )
if ( item.ida != 'I' || item.idb != 'D' )
items[i++] = item;
}
public String getId()
{
return new String(text,idlow,idhigh-idlow);
}
public String toString()
{
StringBuffer SB = new StringBuffer();
SB.append('@');
SB.append('R');
SB.append('G');
if ( idlow != -1 )
{
SB.append('\t');
SB.append('I');
SB.append('D');
SB.append(':');
SB.append(new String(text,idlow,idhigh-idlow));
}
for ( int i = 0; i < items.length; ++i )
{
SB.append('\t');
SB.append((char)items[i].ida);
SB.append((char)items[i].idb);
SB.append(':');
SB.append(new String(text,items[i].vallow,items[i].valhigh-items[i].vallow));
}
return SB.toString();
}
}
public static int hashKey(byte [] B, int off, int len)
{
long h = FNV_basis;
for ( int i = off; i < off+len; ++i )
{
h = h ^ ((long)B[i]);
h *= FNV_prime;
}
return (int)(h & 0x7FFFFFFFl);
}
public int getReadGroupId(byte [] B, int off, int len)
{
int h = hashKey(B,off,len) & rgmask;
int c = rghashcnt[h+1]-rghashcnt[h];
for ( int i = 0; i < c; ++i )
{
ReadGroup rg = readgroups[rghashids[rghashcnt[h]+i]];
if ( len == rg.idhigh-rg.idlow )
{
boolean ok = true;
for ( int j = 0; j < len; ++j )
if ( text[rg.idlow+j] != B[off+j] )
{
ok = false;
break;
}
if ( ok )
return rghashids[rghashcnt[h]+i];
}
}
return -1;
}
public void extractReadGroups() throws Exception
{
int offset = 0;
java.util.Vector<ReadGroup> lreadgroups = new java.util.Vector<ReadGroup>();
while ( offset != textlen )
{
int sol = offset;
while ( offset < textlen && text[offset] != '\n' )
++offset;
int eol = offset;
if ( eol-sol >= 4 && text[sol] == '@' && text[sol+1] == 'R' && text[sol+2] == 'G' && text[sol+3] == '\t' )
{
// System.err.println(new String(text,sol,eol-sol));
int low = sol+4;
java.util.Vector<ReadGroupKeyValuePair> items = new java.util.Vector<ReadGroupKeyValuePair>();
while ( low != eol )
{
int high = low;
while ( high != eol && text[high] != '\t' )
++high;
if (
high-low >= 3 && text[low+2] == ':'
)
{
byte ida = text[low];
byte idb = text[low+1];
int vallow = low+3;
int valhigh = high;
items.add(
new ReadGroupKeyValuePair(ida,idb,vallow,valhigh)
);
/*
System.err.println(
"" + (char)ida + (char)idb + "\t" + new String(text,vallow,valhigh-vallow));
*/
}
if ( high != eol )
++high;
low = high;
}
ReadGroup rg = new ReadGroup(items);
if ( rg.idlow < 0 )
throw new Exception("invalid read group line "+new String(text,sol,eol-sol));
lreadgroups.add(rg);
}
// skip over newline
if ( offset < textlen )
++offset;
}
readgroups = new ReadGroup[lreadgroups.size()];
int s = 1;
int shift = 0;
while ( s < readgroups.length )
{
s <<= 1;
shift += 1;
}
s <<= 2;
shift += 2;
rgmask = s-1;
rghashcnt = new int[s+1];
int o = 0;
for ( ReadGroup rg : lreadgroups )
{
readgroups[o++] = rg;
int hash = rg.hashKey() & rgmask;
rghashcnt[hash]++;
// System.err.println(rg.getId() + " " + hash );
}
// compute prefix sums over rghashcnt
int sum = 0;
int [] rghashcntcopy = new int[rghashcnt.length];
for ( int i = 0; i < rghashcnt.length; ++i )
{
int t = rghashcnt[i];
rghashcnt[i] = sum;
sum += t;
rghashcntcopy[i] = rghashcnt[i];
}
rghashids = new int[readgroups.length];
for ( int i = 0; i < readgroups.length; ++i )
{
int hash = readgroups[i].hashKey() & rgmask;
rghashids[rghashcntcopy[hash]++] = i;
}
/*
for ( int i = 0; i+1 < rghashcnt.length; ++i )
{
int off = rghashcnt[i];
int len = rghashcnt[i+1]-off;
for ( int j = 0; j < len; ++j )
{
System.err.println("*" + rghashids[off+j]);
}
}
*/
}
public boolean addBlock(byte [] B, int len, AddBlockResult result) throws Exception
{
int offset = 0;
while ( offset < len && state != state_enum.done )
{
switch ( state )
{
case readmagic:
{
while ( magicread < 4 && offset < len )
magic[magicread++] = B[offset++];
if ( magicread == 4 )
{
if (
magic[0] == 'B' &&
magic[1] == 'A' &&
magic[2] == 'M' &&
magic[3] == '\1'
)
{
state = state_enum.readtextlength;
}
else
{
throw new Exception("Got wrong BAM magic");
}
}
break;
}
case readtextlength:
{
while ( textlenread < 4 && offset < len )
textlen |= (B[offset++]&0xFF) << ((textlenread++)*8);
if ( textlenread == 4 )
{
state = state_enum.readtext;
text = new byte[textlen];
}
break;
}
case readtext:
{
while ( textread < textlen && offset < len )
text[textread++] = B[offset++];
if ( textread == textlen )
state = state_enum.readnumref;
break;
}
case readnumref:
{
while ( numrefread < 4 && offset < len )
numref |= (B[offset++]&0xFF) << ((numrefread++)*8);
if ( numrefread == 4 )
{
refseqs = new ReferenceSequenceInfo[numref];
if ( numref == 0 )
state = state_enum.done;
else
{
state = state_enum.readrefnamelen;
refnamelengthread = 0;
refnamelength = 0;
}
}
break;
}
case readrefnamelen:
{
while ( refnamelengthread < 4 && offset < len )
refnamelength |= (B[offset++]&0xFF) << (refnamelengthread++ *8);
if ( refnamelengthread == 4 )
{
state = state_enum.readrefnametext;
refnameread = 0;
if ( refname == null || refnamelength > refname.length )
refname = new byte[refnamelength];
}
break;
}
case readrefnametext:
{
while ( refnameread < refnamelength && offset < len )
refname[refnameread++] = B[offset++];
if ( refnameread == refnamelength )
{
state = state_enum.readreflen;
reflengthread = 0;
reflen = 0;
}
break;
}
case readreflen:
{
while ( reflengthread < 4 && offset < len )
reflen |= (B[offset++]&0xFF) << (8*(reflengthread++));
if ( reflengthread == 4 )
{
refseqs[numrefparsed] = new ReferenceSequenceInfo(new String(refname,0,refnamelength-1),reflen);
if ( ++numrefparsed == numref )
{
state = state_enum.done;
}
else
{
state = state_enum.readrefnamelen;
refnamelengthread = 0;
refnamelength = 0;
}
}
}
}
}
result.finished = (state == state_enum.done);
result.offset = offset;
return result.finished;
}
}
|
Shell
|
UTF-8
| 1,505 | 3.40625 | 3 |
[] |
no_license
|
#!/bin/sh
exec >/dev/null
__devroot() {
[ ! -e /dev/root ] || return 0
export $(tr " " "\n" < /proc/cmdline | grep root=)
[ -n "$root" ] || root=/dev/mmcblk0p2
[ $root = /dev/nfs ] || ln -s $root /dev/root 2>/dev/null| :
}
__devroot
t="$2"
b=$1
remount=no
tp=""
[ "$b" = /dev/root ] && export $(tr " " "\n" < /proc/cmdline | grep rootfstype=)
[ -z "$rootfstype" ] && export rootfstype=$(blkid $b -o value -s TYPE)
echo $@ | grep -q remount && remount=yes
set -- $(echo $@|sed s/nobootwait//g)
if /bin/mountpoint -q "$t" && [ $remount = yes ]; then
while test $1 != '-o'; do shift ; done
shift
/bin/mount -i --no-canonicalize -o remount,$(echo $@) $b $t || :
elif ! /bin/mountpoint -q "$t"; then
[ "$UPSTART_JOB" = mountall -a "$PROCESS" = main ] || \
trap "initctl emit -n mounted MOUNTPOINT='$2'" TERM EXIT KILL
[ $rootfstype != nfs ] || exit 0
[ $rootfstype != btrfs ] && findmnt -S $b && exit 0
[ "$UPSTART_JOB" = mountall -a "$PROCESS" = main ] || \
grep -w $b /etc/fstab | grep -w $t | \
while read sa sb sc sd se sf; do
[ "$sf" -eq 1 ] || continue
[ -x "/sbin/fsck.$rootfstype" ] || continue
[ -e "$b" ] || exit 1
if [ "$rootfstype" = vfat ]; then
"/sbin/fsck.$rootfstype" -aw $b ||:
else
"/sbin/fsck.$rootfstype" -fy $b 2>/dev/null ||:
fi
done
/bin/mount -i -t $rootfstype --no-canonicalize $@ || :
fi
exit 0
|
Java
|
UTF-8
| 5,178 | 2.484375 | 2 |
[] |
permissive
|
/* Copyright (C) 2005-2011 Fabio Riccardi */
package com.lightcrafts.ui.editor;
import com.lightcrafts.image.BadImageFileException;
import com.lightcrafts.image.ImageInfo;
import com.lightcrafts.image.UnknownImageTypeException;
import com.lightcrafts.image.types.ImageType;
import com.lightcrafts.image.types.LZNDocumentProvider;
import com.lightcrafts.image.types.LZNImageType;
import com.lightcrafts.utils.LightCraftsException;
import com.lightcrafts.utils.xml.XmlDocument;
import com.lightcrafts.utils.xml.XmlNode;
import org.w3c.dom.Document;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Encapsulates the cumbersome procedures to extract LZN data and an image
* file pointer, if any are defined, from a file.
*/
public class DocumentReader {
/**
* The output from reading a file is a triplet: and XML document holding
* the LZN data; an ImageInfo, in case the file is also an image; and a
* file where the original image is supposed to be located.
*/
public static class Interpretation {
public XmlDocument xml;
public File imageFile;
public ImageInfo info;
}
/**
* Tell quickly if the given file has any LZN data in it.
*/
public static boolean isReadable(File file) {
ImageInfo info = ImageInfo.getInstanceFor(file);
try {
return info.getImageType() instanceof LZNDocumentProvider;
}
catch ( Throwable t ) {
return false;
}
}
/**
* Identify the LZN content and image file pointer contained in the given
* file, or return null if no LZN data can be identified.
* <p>
* It is possible that LZN data exists but no image file can be found.
* This is typical in "LZT" (template) files, for instance.
*/
public static Interpretation read(File file) {
XmlDocument xmlDoc = null;
File imageFile = null;
ImageInfo info = ImageInfo.getInstanceFor(file);
ImageType type;
try {
type = info.getImageType();
}
catch (IOException e) {
return null;
}
catch (LightCraftsException e) {
if (file.getName().endsWith(".lzt")) {
// This is a symptom of a template file, which does have an
// Interpretation. So we continue.
type = LZNImageType.INSTANCE;
}
else {
return null;
}
}
if (type == LZNImageType.INSTANCE) {
try {
InputStream in = new FileInputStream(file);
xmlDoc = new XmlDocument(in);
LightweightDocument lwDoc = new LightweightDocument(file);
imageFile = lwDoc.getImageFile();
}
catch (IOException e) {
// Fall back to the embedded document test.
}
}
// Second try as an image with embedded document metadata:
if (xmlDoc == null) {
try {
if (type instanceof LZNDocumentProvider) {
final LZNDocumentProvider p = (LZNDocumentProvider)type;
Document lznDoc = p.getLZNDocument(info);
if (lznDoc != null) {
xmlDoc = new XmlDocument(lznDoc.getDocumentElement());
if (xmlDoc != null) {
// The original image may be in the same file,
// or referenced through a path pointer:
XmlNode root = xmlDoc.getRoot();
// (tag copied from ui.editor.Document)
XmlNode imageNode = root.getChild("Image");
// (tag written in export())
if ( imageNode.hasAttribute("self")) {
imageFile = file;
}
else {
LightweightDocument lwDoc =
new LightweightDocument(file, xmlDoc);
imageFile = lwDoc.getImageFile();
}
}
}
}
}
catch (BadImageFileException e) {
return null;
}
catch (IOException e) {
return null;
}
catch (UnknownImageTypeException e) {
return null;
}
catch (Throwable t) {
System.out.println("Unexpected error in DocumentReader.read()");
System.out.println(
t.getClass().getName() + ": " + t.getMessage()
);
return null;
}
}
if (xmlDoc != null) {
Interpretation interp = new Interpretation();
interp.xml = xmlDoc;
interp.imageFile = imageFile;
interp.info = info;
return interp;
}
else {
return null;
}
}
}
|
Go
|
UTF-8
| 780 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
package main
import (
"bytes"
"github.com/bcmk/go-smtpd/smtpd"
"github.com/jhillyerd/enmime"
)
type env struct {
*smtpd.BasicEnvelope
from smtpd.MailAddress
data []byte
mime *enmime.Envelope
rcpts []smtpd.MailAddress
ch chan<- *env
}
// Close implements smtpd.Envelope.Close
func (e *env) Close() error {
mime, err := enmime.ReadEnvelope(bytes.NewReader(e.data))
if err != nil {
return err
}
e.mime = mime
e.ch <- e
return nil
}
// Write implements smtpd.Envelope.Write
func (e *env) Write(line []byte) error {
e.data = append(e.data, line...)
return nil
}
// AddRecipient implements smtpd.Envelope.AddRecipient
func (e *env) AddRecipient(rcpt smtpd.MailAddress) error {
e.rcpts = append(e.rcpts, rcpt)
return e.BasicEnvelope.AddRecipient(rcpt)
}
|
Python
|
UTF-8
| 13,047 | 3.515625 | 4 |
[] |
no_license
|
import json
import numpy
import utils
from math import exp
from random import random
"""
######################### DIMENSIONS ################################
Here are the different matrices:
self.matrix_weights1 -> INPUT_SIZE * HIDDEN_LAYER_SIZE (takes in input, outputs input for hidden layer)
self.matrix_weights2 -> HIDDEN_LAYER_SIZE * OUTPUT_SIZE (takes in hidden layer input, output 10 values)
Input data: the squares of the images (0=not painted, 1=painted)
To get the result of the first layer, we apply the weights and add the bias.
Therefore, res = input * matrix_weights1 + bias1
input * matrix_weights1 -> (1 x INPUT_SIZE) * (INPUT_SIZE x HIDDEN_LAYER_SIZE) = 1 x HIDDEN_LAYER_SIZE
If we want to add the bias, it must have the right dimensions -> 1 x HIDDEN_LAYER_SIZE
Then, we apply the sigmoid function on every element.
Similarly, for the second layer, res = output * matrix_weights2 + bias2
output * matrix_weights2 -> (1 x HIDDEN_LAYER_SIZE) * (HIDDEN_LAYER_SIZE x OUTPUT_SIZE) = 1 x OUTPUT_SIZE
If we want to add the bias, it must have the right dimensions -> 1 x OUTPUT_SIZE
################### BACK PROPAGATION ###################################
Here we have first to compute the errors. Since the dimensions of the output are 1 x OUTPUT_SIZE, then
the errors for the last layer too (1 x OUTPUT_SIZE)
To add the weight corrections, the output must have the same dimensions as the weight matrix, because
correction is done by adding the output (multiplied by a learning rate) to the weight matrix.
Therefore, the 2 weight correction matrices must have as dimensions
corrections_mat2 = HIDDEN_LAYER_SIZE x OUTPUT_SIZE
corrections_mat1 = INPUT_SIZE x HIDDEN_LAYER_SIZE
The bias have as dimensions, 1 x HIDDEN_SIZE, 1 x OUTPUT_SIZE, like the errors, so the correction
is simple (just multiply by the learning rate and add to the bias)
Errors: 1 x OUTPUT_SIZE
Input for the 2nd layer: 1 x HIDDEN_LAYER_SIZE
corrections_mat2 -> (HIDDEN_LAYER_SIZE x 1) * (1 x OUTPUT_SIZE) = HIDDEN_LAYER_SIZE x OUTPUT_SIZE
Therefore, corrections_mat2 = input.T * errors
We then need to add the sigmoid prime factor, which applies for each node in the result.
The number of nodes in that layer is OUTPUT_SIZE, and the correction matrix is
HIDDEN_LAYER_SIZE x OUTPUT_SIZE, therefore we must correct each column by sigmoid_prime(z_i).
Therefore, it should be (input.T * errors) x (sigmoid) for the last layer.
In the first layer, the only difference is how we compute the errors, which is more complicated.
To compute the errors, we must see how the node affects the cost. Since we can't do this directly, we
need to use a trick.
The idea is to see how the node affects the nodes in the next layer, and how those nodes affect the
cost (in a recursive fashion). By combining the two (via the chain rule), we can compute the cost accurately.
The maths is the following:
dCost_i/dWeight = sum(dCost_i/dOutput_f * dOutput_f/dTotal_input_f * dTotal_input_f/dOutput_node)
for all nodes f in the following layer.
In other words, dCost_i/dWeight = sum(output_errors_f * sigmoid_prime(f) * weight_f)
Again, this must have the appropriate dimensions (similar to the other error matrix): 1 x HIDDEN_LAYER_SIZE
Weights: HIDDEN_LAYER_SIZE x OUTPUT_SIZE
Output errors: 1 x OUTPUT_SIZE
Therefore, res = (1 x OUTPUT_SIZE) * (OUTPUT_SIZE x HIDDEN_LAYER_SIZE) = 1 x HIDDEN_LAYER_SIZE
res = output_errors * weights.T
Afterwards, we need to apply the sigmoid prime function, in the same fashion. Again, we must
multiply by the sigmoid_prime(input_f) element_by_element.
Therefore, hidden_errors = (output_errors * weights.T) x sigmoid_prime(output_layer_2)
"""
class GeneralNeuralNet:
MAX_LAYER_SIZE = 100
def __init__(self, restore_from_file=False, filename=None,
layer_sizes=None, learning_rate=0.4, momentum=0.3, data=None):
self.FILE_PATH = filename or "data.txt"
self.LEARNING_RATE = learning_rate
self.MOMENTUM = momentum
self.layer_sizes = layer_sizes
self.num_matrices = len(layer_sizes) - 1
self.weights_changes = []
self.bias_changes = []
self.inputs = []
self.net_inputs = []
self.outputs = []
self.errors = []
self.grad_weights = []
self.grad_bias = []
self.set_up_matrices(data, restore_from_file)
self.sigmoid = numpy.vectorize(self._sigmoid_scalar)
self.sigmoid_prime = numpy.vectorize(self._sigmoid_prime_scalar)
def set_up_matrices(self, data, restore_from_file):
if self.layer_sizes is None or len(self.layer_sizes) == 0:
raise Exception("The list of sizes must not be empty or None.")
are_sizes_invalid = any([not (0 < size < self.MAX_LAYER_SIZE) for size in self.layer_sizes])
if are_sizes_invalid:
raise Exception("The sizes must be between 1 and %s" % self.MAX_LAYER_SIZE)
self._initialize_matrices(data, restore_from_file)
def _initialize_matrices(self, data, restore_from_file):
if restore_from_file:
file_data = self.retrieve_data()
if file_data is not None:
self._set_matrices(file_data)
return
if data is None:
self._initialize_weights_randomly()
else:
self._set_matrices(data)
def _set_matrices(self, file_data):
bias_list = file_data["bias"]
matrix_weight_list = file_data["weights"]
num_layers_in_file_data = len(matrix_weight_list) + 1
if self.get_num_layers() != num_layers_in_file_data:
raise Exception("The number of layers in the file is different from the number of layers you specified.")
self.bias_list = []
self.matrix_weights_list = []
for i in range(self.get_num_layers() - 1):
input_size, output_size = self.layer_sizes[i], self.layer_sizes[i + 1]
bias = bias_list[i]
matrix_weights = matrix_weight_list[i]
bias_size = len(bias)
if bias_size != output_size:
raise Exception("The bias for layer %d should have %d elements but has %d (on file)" % (i, output_size,
bias_size))
num_rows = len(matrix_weights)
if num_rows != input_size:
raise Exception("The weights matrix %d should have %d rows but has %d rown on file" % (i, input_size,
num_rows))
num_columns = len(matrix_weights[0])
if num_columns != output_size:
raise Exception(
"The weights matrix %d should have %d rows but has %d rows on file" % (i, output_size, num_columns))
numpy_matrix_weights = numpy.mat([numpy.array(li) for li in matrix_weights])
numpy_bias = numpy.mat([numpy.array(bias)])
self.bias_list.append(numpy_matrix_weights)
self.matrix_weights_list.append(numpy_bias)
def _sigmoid_scalar(self, x):
return 1 / (1 + exp(-x))
def _sigmoid_prime_scalar(self, x):
sigmoid_val = self._sigmoid_scalar(x)
return sigmoid_val * (1 - sigmoid_val)
def _initialize_weights_randomly(self):
self.bias_list = []
self.matrix_weights_list = []
for i in range(self.num_matrices):
input_size, output_size = self.layer_sizes[i], self.layer_sizes[i + 1]
self.bias_list.append(self._make_random_matrix_with_small_numbers(1, output_size))
self.matrix_weights_list.append(self._make_random_matrix_with_small_numbers(input_size, output_size))
def get_num_layers(self):
return len(self.layer_sizes)
def _make_random_matrix_with_small_numbers(self, size_in, size_out):
matrix = [[-0.06 + 0.12 * random() for i in range(size_out)] for j in range(size_in)]
return numpy.mat(matrix)
def predict(self, input_data):
"""
Makes a prediction from the given input data.
:param input_data: the input data
:return: number: the recognized number
"""
input_data = numpy.mat(input_data)
# If we're at layer X, there's no need to keep track of the result of the previous layers
# so we simply replace the current state each time we go to the next layer
current_state = input_data
for (weights_matrix, bias) in zip(self.matrix_weights_list, self.bias_list):
current_state = numpy.dot(current_state, weights_matrix)
current_state += bias
current_state = self.sigmoid(current_state)
return current_state.tolist()[0]
def train_samples(self, data):
"""
Trains the neural network given a series of inputs and the correct results.
:param data: a list of tuples containing the input_data and the result the neural net should predict
:return: None
"""
for input_data, result in data:
self.train(input_data, result)
def train(self, input_data, result):
"""
Uses the backpropagation algorithm to improve the weights on the network.
:param input_data: the input of the training example
:param result: the output of the training example
"""
input_data = numpy.mat(input_data)
# Step 1: use our current neural network to predict an outcome
self.inputs = []
self.net_inputs = []
self.outputs = []
current_layer = input_data
for (weights_matrix, bias) in zip(self.matrix_weights_list, self.bias_list):
self.inputs.append(current_layer)
net_input_next_layer = numpy.dot(current_layer, weights_matrix) + bias
self.net_inputs.append(net_input_next_layer)
current_layer = output = self.sigmoid(net_input_next_layer)
self.outputs.append(output)
# Step 2: compute the error term (dE/dOuput) for each layer
output_layer_errors = self.outputs[-1] - numpy.mat(result)
self.errors = [output_layer_errors]
for i in range(self.num_matrices - 1, 0, -1):
error_next_layer = self.errors[0]
net_input_next_layer = self.net_inputs[i]
weights_next_layer = self.matrix_weights_list[i]
sigmoid_prime_next_layer = self.sigmoid_prime(net_input_next_layer)
adjusted_next_layer_errors = numpy.multiply(error_next_layer, sigmoid_prime_next_layer)
error_current_layer = numpy.dot(adjusted_next_layer_errors, weights_next_layer.T)
self.errors.insert(0, error_current_layer)
# Step 3: compute the gradient of the weights (and bias) on the error
self.grad_weights = []
self.grad_bias = []
for i in range(self.num_matrices - 1, -1, -1):
errors = self.errors[i]
net_input = self.net_inputs[i]
input = self.inputs[i]
grad_weights = numpy.dot(input.T, errors)
sigmoid_prime_layer = self.sigmoid_prime(net_input)
gradient_weights = numpy.multiply(grad_weights, sigmoid_prime_layer)
gradient_bias = numpy.multiply(sigmoid_prime_layer, errors)
self.grad_bias.insert(0, gradient_bias)
self.grad_weights.insert(0, gradient_weights)
# Step 4: update the weights
for i in range(self.num_matrices):
self.matrix_weights_list[i] -= self.LEARNING_RATE * self.grad_weights[i]
self.bias_list[i] -= self.LEARNING_RATE * self.grad_bias[i]
# Step 5: Add momentum
if self.weights_changes:
for i in range(self.num_matrices):
self.matrix_weights_list[i] -= self.MOMENTUM * self.weights_changes[i]
self.bias_list[i] -= self.MOMENTUM * self.bias_changes[i]
self.weights_changes = self.grad_weights
self.bias_changes = self.grad_bias
def save_data(self):
data = {
"bias": [],
"weights": []
}
for i in range(len(self.matrix_weights_list)):
weight_matrix = [np_mat.tolist()[0] for np_mat in self.matrix_weights_list[i]]
bias = self.bias_list[i].tolist()[0]
data["bias"].append(bias)
data["weights"].append(weight_matrix)
# data = {
# "matrix_weights1": ,
# "matrix_weights2": [np_mat.tolist()[0] for np_mat in self.matrix_weights2],
# "bias1": self.bias1[0].tolist()[0],
# "bias2": self.bias2[0].tolist()[0]
# }
with open(self.FILE_PATH, 'w') as f:
f.write(json.dumps(data))
def retrieve_data(self):
if utils.file_exists(self.FILE_PATH):
with open(self.FILE_PATH) as f:
try:
return json.load(f)
except (ValueError, KeyError):
return None
|
Markdown
|
UTF-8
| 485 | 2.703125 | 3 |
[] |
no_license
|
# Catch-the-monkey 🐒
Minigame idealized for me while I was creating a sliding ad. The object of the game is to catch the crazy monkey that appears randomly on the screen.
## Starting
There is no need to install anything, as this game was created with HTML, CSS and pure JS. You can access the [game link](https://lucasnovais182.github.io/Catch-the-monkey/) and have fun or download the zip and run it on your machine and, if you want / can,
to contribute to this repository 😍.
|
Java
|
UTF-8
| 565 | 1.671875 | 2 |
[] |
no_license
|
package com.yiban.yiban_application.web.service.empl;
import com.yiban.yiban_application.javabean.Wall_trends;
import com.yiban.yiban_application.web.service.IndexServiceInterface;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class IndexService implements IndexServiceInterface {
@Override
public List<Wall_trends> getWall_trendsList(int pageNum, int pageSize) {
return null;
}
@Override
public List<Wall_trends> getWall_trendsListBySearch(String search_info) {
return null;
}
}
|
Markdown
|
UTF-8
| 7,448 | 3.421875 | 3 |
[] |
no_license
|
## [Biology Meets Programming: Bioinformatics for Beginners](https://www.coursera.org/learn/bioinformatics?)
<b>Course description:</b><br>
This course will cover algorithms for solving various biological problems along with a handful of programming challenges helping you implement these algorithms in Python. It offers a gently-paced introduction to our Bioinformatics Specialization (https://www.coursera.org/specializations/bioinformatics), preparing learners to take the first course in the Specialization, "Finding Hidden Messages in DNA" (https://www.coursera.org/learn/dna-analysis).
Each of the four weeks in the course will consist of two required components. First, an interactive textbook provides Python programming challenges that arise from real biological problems. Second, each week will culminate in a summary quiz.
All algorithms must be optimised to run in under five minutes per problem, which more often than not means that the first and/or most simple algorithm you try won't work efficiently enough to pass the course.
Code is not hosted here to comply with course guidelines. I may post my study notes which helped me get through the course at a later date.
Verify this certificate at: [coursera.org/verify/C32WZCCD9STR](https://www.coursera.org/verify/C32WZCCD9STR)

---
### Week 01: Where in the Genome Does Replication Begin? (Part 1)
* Determine the length of the <i>Vibrio cholera</i> genome.
* Write a function called PatternCount which finds the number of times a DNA motif is
found within a DNA sequence (exact match).
* Write a function called FrequencyMap with which you can specify a motif length k, and the
algorithm will store all possible k-mers that appear in a DNA sequence in a Python dictionary
as keys and the number of times each k-mer appears as its corresponding value.
* Write a function called FrequentWords which makes use of the FrequencyMap function to
return a list of k-mers of specified length k which occur the most often within a DNA sequence
* Write a function called Reverse which takes a string and reverses them.
* Write a function called Complement which takes a string of DNA nucleotides and
returns the complementary DNA strand.
* Write a function called ReverseComplement which accepts a string of DNA nucleotides and
uses the Reverse and Complement functions to return the reverse complement DNA sequence.
* Write a function called PatternMatching which accepts a DNA genome string and short
DNA pattern string and returns the indices at which the pattern occurs as an exact match
in the genome.
* Pass a quiz making use of the above algorithms on provided datasets.
---
### Week 02: Where in the Genome Does Replication Begin? (Part 2)
* Write a function called SymbolArray which returns a symbol array from a DNA genome string and single
nucleotide of choice (A, T, G, or C).
* Write a function called FasterSymbolArray, with an improved algorithm of SymbolArray.
* Write a function called SkewArray, an array used to keep track of the difference between the total number of occurrences of G and the total number of occurrences of C at every point in the genome.
* Write a function called MinimumSkew which uses SkewArray to return the index at which the minimum skew value occurs.
* Write a function called HammingDistance, which returns the number of different bases when comparing two DNA sequences.
* Write a function called ApproximatePatternMatching, which uses HammingDistance and accepts a DNA pattern, a long DNA sequence, and an integer d to return indices in the long DNA sequence at which the DNA pattern appears with at most d mismatched bases.
* Write a function called ApproximatePatternCount which is like ApproximatePatternMatching, but returns the number of approximate matches.
* Pass a quiz making use of the above algorithms on provided datasets, as well as
some related biology theory.
---
### Week 03: Which DNA Patterns Play the Role of Molecular Clocks? (Part 1)
* Write a function called Count, which takes a list of strings Motifs as input and returns the count matrix of Motifs (as a dictionary of lists).
* Write a function called Profile which uses Count and takes Motifs as input and returns their profile matrix as a dictionary of lists.
* Write a function called Consensus which uses Count and takes a list of strings Motifs as input and returns the consensus string of Motifs.
* Write a function called Pr which computes a profile matrix for a DNA sequence.
* Write a function called ProfileMostProbablePattern which accepts a string Text, an integer k, and a 4 x k matrix Profile, and returns a Profile-most probable k-mer in Text.
* Write a function called Score which allows us to calculate a score for motifs in GreedyMotifSearch.
* Write a function called GreedyMotifSearch, which uses many of the above functions in a complex algorithm to find the set of motifs across a number of DNA sequences that match each other most closely.
* Pass a quiz making use of the above algorithms on provided datasets, as well as
some related biology theory.
---
### Week 04: Which DNA Patterns Play the Role of Molecular Clocks? (Part 4)
* Write a function CountWithPseudocounts, which takes a list of strings Motifs as input and returns the count matrix of Motifs with pseudocounts as a dictionary of lists.
* Write a function ProfileWithPseudocounts that uses CountWithPseudocounts to that take a list of strings Motifs as input and returns the profile matrix of Motifs with pseudocounts as a dictionary of lists.
* Write a function GreedyMotifSearchWithPseudocounts which takes a list of strings Dna followed by integers k and t and returns the result of running GreedyMotifSearch, where each profile matrix is generated with pseudocounts
* Write a function Motifs that takes a profile matrix Profile corresponding to a list of strings Dna as input and returns a list of the Profile-most probable k-mers in each string from Dna. Then add this function to Motifs.py.
* Write a function RandomMotifs(Dna, k, t) that uses random.randint to choose a random k-mer from each of t different strings Dna, and returns a list of t strings.
* Write a function Normalize(Probabilities) which takes a dictionary Probabilities whose keys are k-mers and whose values are the probabilities of these k-mers (which do not necessarily sum to 1). The function should divide each value in Probabilities by the sum of all values in Probabilities, then return the resulting dictionary.
* Write a function WeightedDie(Probabilities). This function takes a dictionary Probabilities whose keys are k-mers and whose values are the probabilities of these k-mers. The function should return a randomly chosen k-mer key with respect to the values in Probabilities.
* Write a function ProfileGeneratedString(Text, profile, k) that takes a string Text, a profile matrix profile, and an integer k as input. It should then return a randomly generated k-mer from Text whose probabilities are generated from profile, as described above.
* Write a function GibbsSampler which is a more cautious version of RandomizedMotifSearch, and utilises many of the above functions. It takes a parameter N corresponding to the number of iterations that we plan to run the program. The algorithm discards a single k-mer from the current set of motifs at each iteration and decides to either keep it or replace it with a new one.
|
TypeScript
|
UTF-8
| 2,053 | 3.671875 | 4 |
[
"MIT"
] |
permissive
|
/**
* Take input from [0, n] and return it as [0, 1]
* @hidden
*/
export function bound01(n: any, max: number) {
if (isOnePointZero(n)) {
n = '100%';
}
const processPercent = isPercentage(n);
n = max === 360 ? n : Math.min(max, Math.max(0, parseFloat(n)));
// Automatically convert percentage into number
if (processPercent) {
n = parseInt(String(n * max), 10) / 100;
}
// Handle floating point rounding errors
if (Math.abs(n - max) < 0.000001) {
return 1;
}
// Convert into [0, 1] range if it isn't already
if (max === 360) {
// If n is a hue given in degrees,
// wrap around out-of-range values into [0, 360] range
// then convert into [0, 1].
n = (n < 0 ? (n % max) + max : n % max) / parseFloat(String(max));
} else {
// If n not a hue given in degrees
// Convert into [0, 1] range if it isn't already.
n = (n % max) / parseFloat(String(max));
}
return n;
}
/**
* Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
* <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
* @hidden
*/
export function isOnePointZero(n: string | number) {
return typeof n === 'string' && n.includes('.') && parseFloat(n) === 1;
}
/**
* Check to see if string passed in is a percentage
* @hidden
*/
export function isPercentage(n: string | number) {
return typeof n === 'string' && n.includes('%');
}
/**
* Return a valid alpha value [0,1] with all invalid values being set to 1
* @hidden
*/
export function boundAlpha(a?: number | string) {
a = parseFloat(a as string);
if (isNaN(a) || a < 0 || a > 1) {
a = 1;
}
return a;
}
/**
* Replace a decimal with it's percentage value
* @hidden
*/
export function convertToPercentage(n: number | string) {
if (n <= 1) {
return `${Number(n) * 100}%`;
}
return n;
}
/**
* Force a hex value to have 2 characters
* @hidden
*/
export function pad2(c: string) {
return c.length === 1 ? '0' + c : String(c);
}
|
Java
|
UTF-8
| 2,147 | 2.3125 | 2 |
[] |
no_license
|
package mgplugin.generator.entity;
/**
* <pre>
* @programName : 프로그램명
* @description : 프로그램_처리내용
* @history
* ---------- --------------- ------------------------------------------------------------------
* 수정일 수정자 수정내용
* ---------- --------------- ------------------------------------------------------------------
* 2019.12.03 김도진 최초생성
*
* </pre>
*/
public class SourceTemplate {
// 묶음 처리
private String packageName = "";
private String typeName = "";
private String baseTypeName = "";
private String tableComment = "";
private String source = "";
/**
* @return the baseTypeName
*/
public String getBaseTypeName() {
return baseTypeName;
}
/**
* @param baseTypeName the baseTypeName to set
*/
public void setBaseTypeName(String baseTypeName) {
this.baseTypeName = baseTypeName;
}
/**
* @return the packageName
*/
public String getPackageName() {
return packageName;
}
/**
* @param packageName the packageName to set
*/
public void setPackageName(String packageName) {
this.packageName = packageName;
}
/**
* @return the typeName
*/
public String getTypeName() {
return typeName;
}
/**
* @param typeName the typeName to set
*/
public void setTypeName(String typeName) {
this.typeName = typeName;
}
/**
* @return the tableComment
*/
public String getTableComment() {
return tableComment;
}
/**
* @param tableComment the tableComment to set
*/
public void setTableComment(String tableComment) {
this.tableComment = tableComment;
}
/**
* @return the source
*/
public String getSource() {
return source;
}
/**
* @param source the source to set
*/
public void setSource(String source) {
this.source = source;
}
}
|
Python
|
UTF-8
| 651 | 4.1875 | 4 |
[] |
no_license
|
#!/usr/bin/python
print("You find yourself in a room with eight doors.")
print("Each door is numbered starting at 1.")
print("")
myDoor = input("Select a door 1-8: ")
# Example use of in as a condition
# The list used here is a predefined list; but could be a variable instead
if myDoor in (1,3,6,8):
print("You enter door %d and emerge on a sandy beach..." % (myDoor) )
elif myDoor in (2,4):
print("You enter door %d and are confronted by a giant troll!" % (myDoor) )
elif myDoor in (5,7):
print("You attempt to open door %d, but it will not open..." % (myDoor) )
else:
print("Umm... that does not appear to be a valid door number")
|
Java
|
UTF-8
| 1,137 | 2.296875 | 2 |
[] |
no_license
|
package com.stfl.service;
import com.stfl.user.ApplicationUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class SecurityService {
@Autowired
ApplicationUserService applicationUserService;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
public ApplicationUser getUserFromSession(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return applicationUserService.findByUserName(auth.getName());
}
public ApplicationUser saveUser(ApplicationUser user) {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
return applicationUserService.saveUser(user);
}
public String getUserNameFromSession() {
ApplicationUser user = getUserFromSession();
String name = user.getUsername();
return name;
}
}
|
Markdown
|
UTF-8
| 435 | 3.296875 | 3 |
[
"MIT"
] |
permissive
|
# thread-first
Like the thread first macro in clojure https://clojure.org/guides/threading_macros
# install
`npm install thread-first`
# usage
```javascript
var threadFirst = require('thread-first')
function head (array) {
return Array.isArray(array) && array[0]
}
var text = 'abcd'
var X = threadFirst(text, [
['replace', 'a', 'x'],
'toUpperCase',
['split', ''],
head
])
console.log(X) // 'X'
```
|
Java
|
UTF-8
| 308 | 1.835938 | 2 |
[] |
no_license
|
package org.gradle.test.performancenull_134;
import static org.junit.Assert.*;
public class Testnull_13303 {
private final Productionnull_13303 production = new Productionnull_13303("value");
@org.junit.Test
public void test() {
assertEquals(production.getProperty(), "value");
}
}
|
Swift
|
UTF-8
| 7,234 | 2.859375 | 3 |
[] |
no_license
|
//
// ViewController.swift
// SearchRank
//
// Created by hanwe on 2021/07/19.
//
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("1: \(solution(["java backend junior pizza 150","python frontend senior chicken 210","python frontend senior chicken 150","cpp backend senior pizza 260","java backend junior chicken 80","python backend senior chicken 50"], ["java and backend and junior and pizza 100","python and frontend and senior and chicken 200","cpp and - and senior and pizza 250","- and backend and senior and - 150","- and - and - and chicken 100","- and - and - and - 150"]))") // [1,1,1,1,2,4]
}
// enum Lan: String, CaseIterable {
// case java = "java"
// case python = "python"
// case cpp = "cpp"
//
// static func getEnum(_ inputed: String) -> Lan {
// var returnValue: Lan = .cpp
// for item in Lan.allCases {
// if inputed == item.rawValue {
// returnValue = item
// break
// }
// }
// return returnValue
// }
// }
//
// enum Position: String, CaseIterable {
// case frontend = "frontend"
// case backend = "backend"
// static func getEnum(_ inputed: String) -> Position {
// var returnValue: Position = .backend
// for item in Position.allCases {
// if inputed == item.rawValue {
// returnValue = item
// break
// }
// }
// return returnValue
// }
// }
//
// enum Level: String, CaseIterable {
// case junior = "junior"
// case senior = "senior"
// static func getEnum(_ inputed: String) -> Level {
// var returnValue: Level = .junior
// for item in Level.allCases {
// if inputed == item.rawValue {
// returnValue = item
// break
// }
// }
// return returnValue
// }
// }
//
// enum Food: String, CaseIterable {
// case chicken = "chicken"
// case pizza = "pizza"
// static func getEnum(_ inputed: String) -> Food {
// var returnValue: Food = .chicken
// for item in Food.allCases {
// if inputed == item.rawValue {
// returnValue = item
// break
// }
// }
// return returnValue
// }
// }
//
// struct User {
// let lan: Lan
// let position: Position
// let level: Level
// let food: Food
// let score: Int
// }
//
// func solution(_ info:[String], _ query:[String]) -> [Int] {
// var userPool: [User] = []
// for item in info {
// let splited = item.split(separator: " ")
// let lan = Lan.getEnum(String(splited[0]))
// let position = Position.getEnum(String(splited[1]))
// let level = Level.getEnum(String(splited[2]))
// let food = Food.getEnum(String(splited[3]))
// userPool.append(User(lan: lan, position: position, level: level, food: food, score: Int(splited[4])!))
// }
//
// var result: [Int] = []
//
// for item in query {
// result.append(getQueryCnt(query: item, pool: userPool))
// }
//
//
// return result
// }
//
// func getQueryCnt(query: String, pool: [User]) -> Int {
// var copyPool = pool
//
// let splited = query.split(separator: " ").filter({ $0 != "and" })
// var lan: Lan?
// if String(splited[0]) != "-" {
// lan = Lan.getEnum(String(splited[0]))
// }
// if lan != nil {
// copyPool = copyPool.filter({ $0.lan == lan! })
// if copyPool.count == 0 {
// return 0
// }
// }
//
// var position: Position?
// if String(splited[1]) != "-" {
// position = Position.getEnum(String(splited[1]))
// }
// if position != nil {
// copyPool = copyPool.filter({ $0.position == position! })
// if copyPool.count == 0 {
// return 0
// }
// }
//
// var level: Level?
// if String(splited[2]) != "-" {
// level = Level.getEnum(String(splited[2]))
// }
// if level != nil {
// copyPool = copyPool.filter({ $0.level == level! })
// if copyPool.count == 0 {
// return 0
// }
// }
//
// var food: Food?
// if String(splited[3]) != "-" {
// food = Food.getEnum(String(splited[3]))
// }
// if food != nil {
// copyPool = copyPool.filter({ $0.food == food! })
// if copyPool.count == 0 {
// return 0
// }
// }
//
// var score: Int?
// if String(splited[4]) != "-" {
// score = Int(String(splited[4]))
// }
// if score != nil {
// copyPool = copyPool.filter({ $0.score >= score! })
// }
//
// return copyPool.count
// }
func solution(_ info:[String], _ query:[String]) -> [Int] {
var dict = [String:[Int]]()
var answer = [Int]()
for item in info {
let array = item.components(separatedBy: " ")
let languages = [array[0], "-"]
let jobs = [array[1], "-"]
let careers = [array[2], "-"]
let foods = [array[3], "-"]
let score = Int(array[4])!
for language in languages {
for job in jobs {
for career in careers {
for food in foods {
let key = "\(language)\(job)\(career)\(food)"
if dict[key] == nil {
dict[key] = [score]
} else {
dict[key]?.append(score)
}
}
}
}
}
}
for item in dict {
let sorted = item.value.sorted()
dict[item.key] = sorted
}
for item in query {
let array = item.components(separatedBy: " ")
let arr = array.filter {$0 != "and"}
let key = "\(arr[0])\(arr[1])\(arr[2])\(arr[3])"
let score = Int(arr[4])!
if let scoreArr = dict[key] {
var low = 0
var high = scoreArr.count - 1
var mid = 0
while low <= high {
mid = (low+high) / 2
if scoreArr[mid] < score {
low = mid + 1
} else {
high = mid - 1
}
}
answer.append(scoreArr.count - low)
} else {
answer.append(0)
}
}
return answer
}
}
|
Python
|
UTF-8
| 4,799 | 3.296875 | 3 |
[] |
no_license
|
# /usr/bin/env python
# __author__ = 'P0WER1ISA'
# __homepage__ = 'https://github.com/P0WER1ISA'
# __builddate__:2017/8/9 12:44
# 6.1 读写CSV数据
import csv
from collections import namedtuple
with open('data/stocks.csv') as f:
f_csv = csv.reader(f)
headings = next(f_csv) # 读取成元组序列
print(headings)
Row = namedtuple('Row', headings) # 生成csv的列表名称来访问元素内容的tuple子类
for r in f_csv: # row是一个元组,包含了一行的列元素(csv文件每列数据用逗号分割)
row = Row(*r)
print(row)
print(r)
with open('data/stocks.csv') as f:
f_csv = csv.DictReader(f) # 读取成字典序列
for row in f_csv:
print(row)
print(row['Symbo']) # 通过行标头来访问每个元素
headers = ['Symbo', 'Price', 'Date', 'Time', 'Chage', 'Volume']
rows = [
('AA', '39.48', '6/11/2007', '9:36am', '-0.18', '181800'),
('AA', '39.48', '6/11/2007', '9:36am', '-0.18', '181800'),
('AA', '39.48', '6/11/2007', '9:36am', '-0.18', '181800'),
('AA', '39.48', '6/11/2007', '9:36am', '-0.18', '181800'),
]
with open('data/stocks_w.csv', 'w') as f: # 写入csv文件
f_csv = csv.writer(f)
f_csv.writerow(headers)
f_csv.writerow(rows)
# 6.2 读写JSON数据
import json
data = {'name': 'ACME', 'shares': 100, 'price': 524.31}
json_str = json.dumps(data) # JSON序列化
print(json_str)
print(json.loads(json_str)) # JSON反序列化
# 6.3 解析简单的XML文档 (xml.etree.ElementTree)
from urllib.request import urlopen
from xml.etree.ElementTree import parse
u = urlopen('http://planet.python.org/rss20.xml')
doc = parse(u)
for item in doc.iterfind('channel/item'):
title = item.findtext('title')
date = item.findtext('pubDate')
link = item.findtext('link')
print(title)
print(date)
print(link)
# 6.4 以增量方式解析大型XML文件 (考虑使用迭代器和生成器)
from xml.etree.ElementTree import iterparse
def parse_and_remove(filename, path):
path_parts = path.split('/')
doc = iterparse(filename, ('start', 'end'))
next(doc)
tag_stack = []
elem_stack = []
for event, elem in doc:
if event == 'statr':
tag_stack.append(elem.tag)
elem_stack.append(elem)
elif event == 'end':
if tag_stack == path_parts:
yield elem
elem_stack[-2].remove(elem)
try:
tag_stack.pop()
elem_stack.pop()
except IndexError:
pass
# 6.5 将字典转换为XML
from xml.etree.ElementTree import Element
def dict_to_xml(tag, d):
elem = Element(tag)
for key, val in d.items():
child = Element(key)
child.text = str(val)
elem.append(child)
return elem
s = {'name': 'GOOG', 'shares': 100, 'price': 490.1}
e = dict_to_xml('stock', s)
print(e)
from xml.etree.ElementTree import tostring # 使用tostring函数将其转换为字符串
print(tostring(e))
e.set('_id', '1234') # 增加属性
print(tostring(e))
# 6.6 解析、修改和重写XML
from xml.etree.ElementTree import parse, Element # 使用ElementTree来读取这个文档,并对其结构作出修改
doc = parse('pred.xml')
root = doc.getroot()
print(root)
root.remove(root.find('sri'))
root.remove(root.find('cr'))
root.getchildren().index(root.find('nm'))
e = Element('spam')
e.text = 'This is a test'
root.insert(2, e)
# 6.7 用命名空间来解析XML文档
# 6.8 同关系型数据库进行交互
import sqlite3
db = sqlite3.connect('data/databas.db')
c = db.cursor()
c.execute('CREATE TABLE portfolio (symbol TEXT, shares INTEGER, price REAL)')
db.commit()
# 6.9 编码与解码十六进制数字
s = b'Hello'
import binascii
h = binascii.b2a_hex(s) # 二进制转十六进制(每个字节的数据转成相应的2位十六进制标识)
print(h)
a = binascii.a2b_hex(h) # 与b2a_hex函数相反,把买个2位十六进制转成一个2进制字节
print(a)
import base64
s = b'Hello'
h = base64.b16encode(s) # 同binascii.b2a_hex ,输出大写形式
print(h)
print(base64.b16decode(h)) # 同b2a_hex函数
# Base64编码和解码
import base64
s = b'Hello'
print(s)
a = base64.b64encode(s) # base64编码
print(a)
print(base64.b64decode(a)) # base64解码
# 6.11 读写二进制结构的数组
from struct import Struct
def write_records(records, format, f):
records_struct = Struct(format)
for r in records:
f.write(records_struct.pack(*r))
records = [(1, 2.3, 4.5), (6, 7.8, 9.0), (12, 13.4, 56.7)]
with open('data/data.b', 'wb') as f:
write_records(records, '<idd', f) # '<':采用小端存储,'i':int,'d':double
# 6.12 读取嵌套性和大小可变的二进制结构
# 6.13 数据汇总和统计
|
Python
|
UTF-8
| 382 | 4.3125 | 4 |
[] |
no_license
|
# -*- encoding=utf8 -*-
# 提示用户输入分数,获取用户输入内容,并保存到变量 data
data = input('请输入分数:')
# 将用户输入分数从字符串转成整数数值,并保存到变量 score
score = int(data)
if score >= 90:
print('优秀')
elif score >= 70:
print('良好')
elif score >= 60:
print('及格')
else:
print('不及格')
|
SQL
|
UTF-8
| 2,312 | 4.09375 | 4 |
[] |
no_license
|
#achar todos os contatos de todas as listas de contatos de um usuario COM VIEW
SELECT DISTINCT LDC.NOME, U.* FROM USUARIO_SIMPLES DONO
JOIN LISTA_DE_CONTATOS LDC ON DONO.USUARIO_ID = DONO
JOIN USUARIO_SIMPLES U ON U.USUARIO_ID = LDC.USUARIO_ID
WHERE DONO.USUARIO_ID = 1
ORDER BY LDC.NOME;
#achar todas as mensagens de um chat e quem as mandou
SELECT U.NOME, CONTEUDO, A.*, DATA_DE_ENVIO FROM MENSAGEM M
JOIN CHAT C ON C.CHAT_ID = M.CHAT_ID
JOIN USUARIO U ON M.USUARIO_ID = U.USUARIO_ID
LEFT JOIN ARQUIVO A USING (ARQUIVO_ID)
WHERE C.CHAT_ID = 2
AND M.USUARIO_ID = C.USUARIO_ID
ORDER BY DATA_DE_ENVIO;
#olhar o calendario do usuario 1
SELECT U.NOME, C.* FROM USUARIO U
JOIN CALENDARIO CAL USING(USUARIO_ID)
JOIN COMPROMISSO_REUNIAO C USING(COMPROMISSO_ID)
WHERE U.USUARIO_ID = 1;
#Todas as chamadas do usuario 1
SELECT U.*, CH.* FROM USUARIO_SIMPLES U
JOIN CHAT C ON C.USUARIO_ID = U.USUARIO_ID
JOIN CHAMADA CH ON C.CHAT_ID = CH.CHAT_ID
WHERE U.USUARIO_ID = 1;
#Todos os arquivos enviados pelo usuario 1
SELECT U.*, A.* FROM USUARIO_SIMPLES U
JOIN MENSAGEM M USING(USUARIO_ID)
JOIN ARQUIVO A USING(ARQUIVO_ID)
WHERE USUARIO_ID = 1;
#Usuarios que tem mais de um compromisso
select * from usuario_simples
join calendario using(usuario_id)
join compromisso using(compromisso_id)
group by usuario_id
having count(compromisso_id) > 1;
#achar todos os chats de um usuario X
SELECT DISTINCT CHAT_ID, U.NOME AS PARTICIPANTE FROM CHAT
JOIN USUARIO U USING(USUARIO_ID)
WHERE U.NOME <> 1
AND CHAT_ID IN (SELECT DISTINCT CHAT_ID FROM CHAT
WHERE USUARIO_ID = 1)
ORDER BY CHAT_ID;
#O numero de compromissos do usuario 1
SELECT DISTINCT U.USUARIO_ID, U.NOME, COUNT(C.COMPROMISSO_ID) FROM USUARIO DONO
JOIN LISTA_DE_CONTATOS LDC ON DONO.USUARIO_ID = DONO
JOIN USUARIO U ON U.USUARIO_ID = LDC.USUARIO_ID
LEFT JOIN CALENDARIO C ON C.USUARIO_ID = U.USUARIO_ID
WHERE DONO.USUARIO_ID = 1
GROUP BY U.USUARIO_ID;
#TODOS OS USUARIOS QUE NAO TEM CHAT COM O USUARIO 2 E SEUS METODOS DE PAGAMENTO
SELECT DISTINCT U1.USUARIO_ID, NOME, UP.METODO_DE_PAGAMENTO FROM USUARIO U1
LEFT JOIN USUARIO_PREMIUM UP ON U1.USUARIO_PREMIUM_ID = UP.USUARIO_PREMIUM_ID
WHERE NOT EXISTS (SELECT * FROM CHAT
WHERE USUARIO_ID = U1.USUARIO_ID
AND CHAT_ID IN (SELECT DISTINCT CHAT_ID FROM CHAT
JOIN USUARIO USING(USUARIO_ID)
WHERE USUARIO_ID = 2))
|
Python
|
UTF-8
| 2,278 | 4.21875 | 4 |
[] |
no_license
|
##################
# Built-in Lists #
##################
# Initialize
peoples = ["Mao", "Chou", "Liu"]
print peoples
print peoples[0] # >> First Element: "Mao"
print peoples[-1] # >> Last Element: "Liu"
print len(peoples) # >> 3
# Everything fits
jianguo = [1949, "Beijing", "China", peoples]
print jianguo
# Add Element
peoples.append("Lin")
print peoples
jianguo.insert(0, "TianAnMen")
print jianguo
# Change Element
for i in range(0,4):
peoples[i] = "Famous - " + peoples[i]
print peoples
print jianguo
# Remove Element
del peoples[2]
print peoples # >> ['Famous - Mao', 'Famous - Chou', 'Famous - Lin']
peoples.remove("Famous - Lin")
print peoples # >> ['Famous - Mao', 'Famous - Chou']
jianguo.remove(peoples)
print jianguo
# Concatenate Lists
jianguo.extend(peoples)
print jianguo # >> ['TianAnMen', 1949, 'Beijing', 'China', 'Famous - Mao', 'Famous - Chou']
# Slicing List
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
firstTwo = squares[0:2]
print firstTwo # >> [0, 1]
lastTwo = squares[-2:]
print lastTwo # >> [0, 1]
exceptFirst = squares[1:]
print exceptFirst
exceptLast = squares[:-1]
print exceptLast
# enumerate() for index
days = ["Mon", "Tues", "Wed", "Thr", "Fri", "Sat", "Sun"]
for i, d in enumerate(days):
print i, d
#########################
# Built-in Dictionaries #
#########################
# Initialize and Access
capitals = {'Peru':'Lima', 'China': 'Beijing', 'US':'Washington', 'Italy':'Rome', 'Germany':'Berlin', 'India':'Dehli'}
print capitals['China'] # >> Beijing
print 'Italy' in capitals # >> True
# Concatenating without Collision
moreCapitals = {'Japan': 'Tokyo', 'Korea': 'Seoul', 'India':'Delhi'}
capitals.update(moreCapitals)
print capitals['India'] # >> Delhi
# Iterations
for key in capitals.keys():
key = "Capital of " + key
print capitals
for value in capitals.values():
value = value + " 2017"
print capitals
for key, value in capitals.items():
print key + " - " + value
##################
# Comprehensions #
##################
# For Lists
square3 = [i**2 for i in range(30) if i % 3 == 0]
print square3
# For Dictionaries
square4 = {i: i**2 for i in range(30) if i % 4 == 0}
print square4
# Transform Dictionary
capitalsByCap = {capitals[key]: key for key in capitals}
print capitalsByCap
|
C++
|
UTF-8
| 322 | 2.796875 | 3 |
[] |
no_license
|
/*
*
***
*****
*******
*********
*/
#include<iostream>
using namespace std;
int main(){
int i,j,k;
int s =1;
for (i=4; i >= 0 ; i--){
for (j=0; j <= i ; j++){
cout << " ";
}
for (k=0; k<s ; k++){
cout << "*";
}
s = s+ 2;
cout <<endl;
}
return 0;
}
|
Java
|
UTF-8
| 9,086 | 2.078125 | 2 |
[] |
no_license
|
package top.leonx.vanity.data;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.EncoderException;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.crash.ReportedException;
import net.minecraft.entity.Entity;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.network.datasync.IDataSerializer;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.leonx.vanity.entity.OutsiderIncorporeal;
import top.leonx.vanity.util.DummyLivingEntityHolder;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class IncorporealDataManager extends EntityDataManager {
private final Map<Integer, EntityDataManager.DataEntry<?>> entries = Maps.newHashMap();
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private boolean empty = true;
private boolean dirty;
private final OutsiderIncorporeal outsider;
public IncorporealDataManager(OutsiderIncorporeal outsider) {
super(null);
this.outsider=outsider;
}
public <T> void register(DataParameter<T> key, T value) {
int i = key.getId();
if (i > 254) {
throw new IllegalArgumentException("Data value id is too big with " + i + "! (Max is " + 254 + ")");
} else if (this.entries.containsKey(i)) {
throw new IllegalArgumentException("Duplicate id value for " + i + "!");
} else if (DataSerializers.getSerializerId(key.getSerializer()) < 0) {
throw new IllegalArgumentException("Unregistered serializer " + key.getSerializer() + " for " + i + "!");
} else {
this.setEntry(key, value);
}
}
public <T> boolean hasKey(DataParameter<T> key)
{
return this.entries.containsKey(key.getId());
}
private <T> void setEntry(DataParameter<T> key, T value) {
EntityDataManager.DataEntry<T> dataEntry = new EntityDataManager.DataEntry<>(key, value);
this.lock.writeLock().lock();
this.entries.put(key.getId(), dataEntry);
this.empty = false;
this.lock.writeLock().unlock();
}
private <T> EntityDataManager.DataEntry<T> getEntry(DataParameter<T> key) {
this.lock.readLock().lock();
EntityDataManager.DataEntry<T> dataEntry;
try {
dataEntry = (EntityDataManager.DataEntry<T>) this.entries.get(key.getId());
} catch (Throwable throwable) {
CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Getting synched entity data");
CrashReportCategory crashreportcategory = crashreport.makeCategory("Synched entity data");
crashreportcategory.addDetail("Data ID", key);
throw new ReportedException(crashreport);
} finally {
this.lock.readLock().unlock();
}
return dataEntry;
}
public <T> T get(DataParameter<T> key) {
return this.getEntry(key).getValue();
}
public <T> void set(DataParameter<T> key, T value) {
EntityDataManager.DataEntry<T> dataEntry = this.getEntry(key);
if (ObjectUtils.notEqual(value, dataEntry.getValue())) {
dataEntry.setValue(value);
this.outsider.notifyDataManagerChange(key);
dataEntry.setDirty(true);
this.dirty = true;
}
}
public <T> void setWithNotify(DataParameter<T> key, T value)
{
EntityDataManager.DataEntry<T> dataEntry = this.getEntry(key);
if (ObjectUtils.notEqual(value, dataEntry.getValue())) {
dataEntry.setValue(value);
dataEntry.setDirty(true);
this.dirty = true;
}
}
public boolean isDirty() {
return this.dirty;
}
public static void writeEntries(List<EntityDataManager.DataEntry<?>> entriesIn, PacketBuffer buf) throws IOException {
if (entriesIn != null) {
int i = 0;
for(int j = entriesIn.size(); i < j; ++i) {
writeEntry(buf, entriesIn.get(i));
}
}
buf.writeByte(255);
}
@Nullable
public List<EntityDataManager.DataEntry<?>> getDirty() {
List<EntityDataManager.DataEntry<?>> list = null;
if (this.dirty) {
this.lock.readLock().lock();
for(EntityDataManager.DataEntry<?> dataEntry : this.entries.values()) {
if (dataEntry.isDirty()) {
dataEntry.setDirty(false);
if (list == null) {
list = Lists.newArrayList();
}
list.add(dataEntry.copy());
}
}
this.lock.readLock().unlock();
}
this.dirty = false;
return list;
}
@Nullable
public List<EntityDataManager.DataEntry<?>> getAll() {
List<EntityDataManager.DataEntry<?>> list = null;
this.lock.readLock().lock();
for(EntityDataManager.DataEntry<?> dataEntry : this.entries.values()) {
if (list == null) {
list = Lists.newArrayList();
}
list.add(dataEntry.copy());
}
this.lock.readLock().unlock();
return list;
}
private static <T> void writeEntry(PacketBuffer buf, EntityDataManager.DataEntry<T> entry) throws IOException {
DataParameter<T> dataParameter = entry.getKey();
int i = DataSerializers.getSerializerId(dataParameter.getSerializer());
if (i < 0) {
throw new EncoderException("Unknown serializer type " + dataParameter.getSerializer());
} else {
buf.writeByte(dataParameter.getId());
buf.writeVarInt(i);
dataParameter.getSerializer().write(buf, entry.getValue());
}
}
@Nullable
public static List<EntityDataManager.DataEntry<?>> readEntries(PacketBuffer buf) throws IOException {
List<EntityDataManager.DataEntry<?>> list = null;
int i;
while((i = buf.readUnsignedByte()) != 255) {
if (list == null) {
list = Lists.newArrayList();
}
int j = buf.readVarInt();
IDataSerializer<?> iDataSerializer = DataSerializers.getSerializer(j);
if (iDataSerializer == null) {
throw new DecoderException("Unknown serializer type " + j);
}
list.add(makeDataEntry(buf, i, iDataSerializer));
}
return list;
}
private static <T> EntityDataManager.DataEntry<T> makeDataEntry(PacketBuffer bufferIn, int idIn, IDataSerializer<T> serializerIn) {
return new EntityDataManager.DataEntry<>(serializerIn.createKey(idIn), serializerIn.read(bufferIn));
}
@OnlyIn(Dist.CLIENT)
public void setEntryValues(List<EntityDataManager.DataEntry<?>> entriesIn) {
this.lock.writeLock().lock();
for(EntityDataManager.DataEntry<?> dataEntry : entriesIn) {
EntityDataManager.DataEntry<?> dataEntry1 = this.entries.get(dataEntry.getKey().getId());
if (dataEntry1 != null) {
this.setEntryValue(dataEntry1, dataEntry);
this.outsider.notifyDataManagerChange(dataEntry.getKey());
}
}
this.lock.writeLock().unlock();
this.dirty = true;
}
@OnlyIn(Dist.CLIENT)
private <T> void setEntryValue(EntityDataManager.DataEntry<T> target, EntityDataManager.DataEntry<?> source) {
if (!Objects.equals(source.getKey().getSerializer(), target.getKey().getSerializer())) {
throw new IllegalStateException(String.format("Invalid entity data item type for field %d on entity %s: old=%s(%s), new=%s(%s)", target.getKey().getId(), this.outsider, target.getValue(),
target.getValue().getClass(), source.getValue(), source.getValue().getClass()));
} else {
target.setValue((T)source.getValue());
}
}
public boolean isEmpty() {
return this.empty;
}
public void setClean() {
this.dirty = false;
this.lock.readLock().lock();
for(EntityDataManager.DataEntry<?> dataEntry : this.entries.values()) {
dataEntry.setDirty(false);
}
this.lock.readLock().unlock();
}
}
|
Markdown
|
UTF-8
| 398 | 3.109375 | 3 |
[] |
no_license
|
# My Movie List
This mini project is a vanilla JavaScript movie list in which you will be able to add movies (title, director and genre) and delete them.
# Motivation
* Implementing ES6 classes.
* Interacting with local storage.
* Dealing with Events.
# Screenshot
Check out the end result :point_right: [MyMovieList](https://nainiayoub.github.io/Hands-on-JavaScript-projects/MyMovieList/)
|
C#
|
UTF-8
| 298 | 2.953125 | 3 |
[] |
no_license
|
public Employee(Person person)
{
// clone property values
foreach (var property in person.GetType().GetProperties().Where(property => property.CanRead && property.CanWrite))
{
property.SetValue(this, property.GetValue(user, null), null);
}
}
|
Python
|
UTF-8
| 2,284 | 3.4375 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
class Node(object):
def __init__(self,data=0,which_T=None):
self.leaf = []
self.data=data
self.which_T=[]
class SuffixTree(object):
def __init__(self):
self.root = Node()
def add(self,s,which_T):
s+="$"
for i in range(0,len(s)):
current=self.root
for sub in s[i:]:
if len(current.leaf)!=0:
havechoose=0
for leafs in current.leaf:
if sub == leafs.data:
current=leafs
leafs.which_T.append(which_T)
havechoose=1
break
if havechoose==0:
newleaf=Node()
newleaf.data=sub
newleaf.which_T.append(which_T)
print newleaf.data
print newleaf.which_T
current.leaf.append(newleaf)
current=newleaf
else:
newleaf=Node()
newleaf.data=sub
newleaf.which_T.append(which_T)
print newleaf.data
print newleaf.which_T
current.leaf.append(newleaf)
current=newleaf
def main():
tree = SuffixTree()
with open('t2.txt','r') as f:
for line in f.readlines():
print line.strip()
s=line.strip().split(':')
tree.add(s[1].split(','),s[0])
while (True):
x = raw_input("Search for: ")
x=x.split(',')
now=tree.root
stop=0
result=0
for i in x:
stop+=1
for leafs in now.leaf:
if i == leafs.data:
now=leafs
break
if stop==len(x):
for each in now.leaf:
print "find in "
print each.which_T
result+=len(each.which_T)
print result
if __name__ == '__main__':
main()
|
Java
|
UTF-8
| 614 | 1.96875 | 2 |
[] |
no_license
|
package com.sb.demo.security1.domain;
import java.io.Serializable;
/**
* security 权限demo第一套
*
* @date 2020年3月27日 下午11:11:36
* @author jdr
*/
public class SysUserRole1 implements Serializable {
private static final long serialVersionUID = 1L;
private Integer userId;
private Integer roleId;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
}
|
JavaScript
|
UTF-8
| 1,334 | 2.953125 | 3 |
[] |
no_license
|
const $ = document.querySelector.bind(document)
const $$ = document.querySelectorAll.bind(document)
/*
1. Next/Prev
2. Auto next
3. Nav Active
4. Click Nav Active
*/
const IMAGE_WIDTH = 980
const silderContent = $('.slider-content')
const sliderItem = $$('.slider-item')
const nextBtn = $('.control.next')
const prevBtn = $('.control.prev')
const navs = $$('.nav')
let currentIndex = 0
let nextTime
// Xử lý action slider
function slideToIndex(index) {
silderContent.style.transform = `translateX(-${IMAGE_WIDTH * index}px)`
}
// Xử lý next
function next() {
currentIndex++
if (currentIndex >= sliderItem.length) {
currentIndex = 0
}
slideToIndex(currentIndex)
startAutoPlay()
handleNavActive()
}
// Xử lý click next
nextBtn.onclick = next
// Xử lý prev
function prev() {
currentIndex--
if (currentIndex < 0) {
currentIndex = sliderItem.length - 1
}
slideToIndex(currentIndex)
startAutoPlay()
handleNavActive()
}
// Xử lý click prev
prevBtn.onclick = prev
// Auto play
startAutoPlay()
function startAutoPlay() {
clearInterval(nextTime)
nextTime = setInterval(next, 3000)
}
// Active Nav
function handleNavActive() {
$('.nav.curent').classList.remove('current')
navs[currentIndex].classList.add('current')
}
|
C++
|
UTF-8
| 986 | 3 | 3 |
[] |
no_license
|
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
int len = candidates.size();
vector<vector<int>> res;
if(!len)
return res;
vector<int> comb;
sort(candidates.begin(), candidates.end());
comb_target(candidates, res, comb, target);
}
void comb_target(vector<int> candidates, vector<vector<int>> &res, vector<int> comb, int target)
{
if(target ==0)
{
res.push_back(comb);
return;
}
if(!candidates.size())
return;
int small = candidates[0];
int num = target/small;
vector<int> sub(candidates.begin()+1, candidates.end());
comb_target(sub, res, comb, target);
for(int i=0; i<num; i++)
{
target -=small;
comb.push_back(small);
comb_target(sub, res, comb, target);
}
}
};
|
Python
|
UTF-8
| 526 | 4.25 | 4 |
[] |
no_license
|
# Faça um Programa que leia três números e mostre-os em ordem decrescente.
n = int(input("Informe um numero: "))
n1 = int(input("Informe um numero: "))
n2 = int(input("Informe um numero: "))
if n > n1 and n > n2 and n1 > n2:
ordem = n, n1, n2
elif n > n2 and n > n1 and n1 < n2:
ordem = n, n2, n1
elif n1 > n2 and n1 > n and n > n2:
ordem = n1, n, n2
elif n1 > n and n1 > n2 and n < n2:
ordem = n1, n2, n
elif n2 > n1 and n2 > n and n > n1:
ordem = n2, n, n1
else:
ordem = n2, n1, n
print(ordem)
|
Swift
|
UTF-8
| 1,488 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
//
// PacketSpec.swift
// TunnelPacketKit
//
// Created by Zhuhao Wang on 16/1/20.
// Copyright © 2016年 Zhuhao Wang. All rights reserved.
//
import Foundation
import Nimble
import Quick
@testable import TunnelPacketKit
class IPPacketSpec: QuickSpec {
override func spec() {
var packetData: NSData!
var packet: IPPacket!
beforeEach {
let bundle = NSBundle(forClass: self.dynamicType)
let file = bundle.pathForResource("Packet_1", ofType: "bin")!
let data = NSData(contentsOfFile: file)!
packetData = data.subdataWithRange(NSMakeRange(14, data.length - 14))
packet = IPPacket(packetData)
}
describe("The IPPacket") {
it("Can parse the data") {
expect(packet.parsePacket()) == true
expect(packet.version) == IPVersion.IPv4
expect(packet.headerLength) == 20
expect(packet.totalLength) == 713
expect(packet.TTL) == 64
expect(packet.packetType) == PacketType.TCP
expect(packet.sourceAddress.equalTo(IPv4Address(192, 168, 1, 230))) == true
expect(packet.destinationAddress.equalTo(IPv4Address(17, 172, 233, 92))) == true
expect(packet.tcpPacket).toNot(beNil())
}
it("Can validate packet") {
packet.parsePacket()
expect(packet.validate()) == true
}
}
}
}
|
TypeScript
|
UTF-8
| 343 | 3.5625 | 4 |
[] |
no_license
|
/**
* 647. 回文子串
* https://leetcode-cn.com/problems/palindromic-substrings/
*/
export default function PalindromicSubstrings() {
}
PalindromicSubstrings();
/**
* 计算这个字符串中有多少个回文子串
* @param {string} s
* @return {number} {number}
*/
function countSubstrings(s: string): number {
return 0;
}
|
Python
|
UTF-8
| 986 | 3.375 | 3 |
[] |
no_license
|
# Uses python3
import numpy
def edit_distance(s1, s2):
len_1 = len(s1)
len_2 = len(s2)
dpresult = numpy.zeros((len_1+1 , len_2+1)) # a martix
for i in range(len_2+1): # edit distance for a null string and another string is just length of string
dpresult[0][i] = i
for i in range(len_1+1):
dpresult[i][0] = i
# Filling remaining matrix
for i in range(1, len_1+1):
for j in range(1, len_2+1):
insertion = dpresult[i][j-1] + 1
deletion = dpresult[i-1][j] + 1
mismatch = dpresult[i-1][j-1] + 1
match = dpresult[i-1][j-1]
if s1[i-1] == s2[j-1]: #when it matches
dpresult[i][j] = min(insertion, deletion, match)
if s1[i-1] != s2[j-1]: #when it doesn't match
dpresult[i][j] = min(insertion, deletion, mismatch)
return (int(dpresult[len_1][len_2]))
if __name__ == "__main__":
print(edit_distance(input(), input()))
|
JavaScript
|
UTF-8
| 1,056 | 2.6875 | 3 |
[] |
no_license
|
import React, { Component } from 'react'
import axios from "axios";
class Person extends Component {
constructor() {
super();
this.state = {
person: {}
}
}
componentDidMount() {
axios.get(`https://swapi.co/api/people/${this.props.match.params.id}`)
.then(response => {
this.setState({
person: response.data
})
});
}
componentWillReceiveProps(nextProps) {
if (nextProps.match.params.id !== this.props.match.params.id) {
axios.get(`https://swapi.co/api/people/${nextProps.match.params.id}`)
.then(response => {
this.setState({
person: response.data
})
});
}
}
render() {
return (
<div>
<h1>{this.state.person.name}</h1>
<h2>{this.state.person.eye_color}</h2>
</div>
)
}
}
export default Person
|
JavaScript
|
UTF-8
| 369 | 2.734375 | 3 |
[] |
no_license
|
var BulletMixin = Base => class extends Base {
shooted() {
var bullet = this;
this.interval_id = setInterval(function() { bullet.pattern(); }, 1000 / _fps);
}
pattern() {
// some pattern
this.move_next();
}
move_next() {
this.x += this.vector.x;
this.y += this.vector.y;
}
destroy() {
clearInterval(this.interval_id);
}
}
|
Java
|
UTF-8
| 1,355 | 2.1875 | 2 |
[] |
no_license
|
package com.lover.service.imp;
import com.lover.dao.MessageDao;
import com.lover.entity.Constant;
import com.lover.entity.Feedback;
import com.lover.entity.Message;
import com.lover.entity.Result;
import com.lover.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
@Service
public class MessageServiceImp implements MessageService {
@Autowired
private MessageDao messageDao;
@Override
public List<Message> messageList(int page) {
HashMap hashMap = new HashMap();
hashMap.put("start", page * Constant.MESSAGE_PAGE_NUMBER);
hashMap.put("length", Constant.MESSAGE_PAGE_NUMBER);
return messageDao.messageList(hashMap);
}
@Override
public Integer messageNum() {
return messageDao.messageNum();
}
@Override
public Result messageAdd(Message message) {
message.init();
message.format();
System.out.println(message.toString());
messageDao.messageAdd(message);
return Result.resultFactory(Feedback.FEEDBACK_SUCCESS);
}
@Override
public Result messageDel(Message message) {
messageDao.messageDel(message.getMid());
return Result.resultFactory(Feedback.FEEDBACK_SUCCESS);
}
}
|
TypeScript
|
UTF-8
| 1,135 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
import { Injectable } from '@angular/core';
@Injectable()
export class IDialogService {
alert(message: string): void { return void (0); };
error(error: any): string { return ''; };
prompt(message: string): string { return ''; };
}
@Injectable()
export class DialogService implements IDialogService {
alert(message: string): void {
window.alert(message);
}
error(error: any): string {
let message = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
window.alert(message);
return message;
}
prompt(message: string): string {
return window.prompt(message);
}
}
@Injectable()
export class MockDialogService implements IDialogService {
alert(message: string): void {
console.log(`alert called with ${message}`);
}
error(error: any): string {
console.log(`error called with ${error.message}`);
return error.message;
}
prompt(message: string): string {
console.log(`prompt called with message ${message}`);
return message;
}
}
|
Ruby
|
UTF-8
| 669 | 3.5625 | 4 |
[] |
no_license
|
# Random sorted arrays
class Random
class << self
def int_array(size: 0, max: 0, sort: true)
arr = []
while arr.size < size
elem = rand(max)
arr << elem unless arr.include?(elem)
end
return arr unless sort
arr.sort
end
def str_array(size: 0, str_len: 0, sort: true)
arr = size.times.map.each_with_object([]) do |_t, memo|
memo << random_str(str_len: str_len)
end
return arr unless sort
arr.sort
end
private
def random_str(str_len: 0)
str_len.times.map.each_with_object('') do |_t, memo|
memo << ('a'..'z').to_a.sample
end
end
end
end
|
Python
|
UTF-8
| 9,856 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
from libsaas.services import base
from libsaas import http, parsers
class Link(base.Resource):
path = 'link'
def __init__(self, parent, link):
self.parent = parent
self.object_id = link
def get_url(self):
return '{0}/{1}'.format(self.parent.get_url(), self.path)
def _get(self, path, params):
params['link'] = self.object_id
url = '{0}/{1}'.format(self.get_url(), path)
request = http.Request('GET', url, params)
return request, parsers.parse_json
@base.apimethod
def info(self):
"""
Returns metadata about a single bitly link.
"""
return self._get('info', {})
@base.apimethod
def content(self, content_type=None):
"""
Returns the "main article" from the linked page,
as determined by the content extractor, in either HTML
or plain text format.
:var content_type: specifies whether to return the content
as html or plain text. if` not indicated, defaults to 'html'.
:vartype content_type: str
"""
params = base.get_params(None, locals())
return self._get('content', params)
@base.apimethod
def category(self):
"""
Returns the detected categories for a document,
in descending order of confidence.
"""
return self._get('category', {})
@base.apimethod
def social(self):
"""
Returns the "social score" for a specified bitly link.
"""
return self._get('social', {})
@base.apimethod
def location(self):
"""
Returns the significant locations for the bitly link
or None if locations do not exist.
"""
return self._get('location', {})
@base.apimethod
def language(self):
"""
Returns the significant languages for the bitly link.
"""
return self._get('language', {})
@base.apimethod
def clicks(self, unit=None, units=None, timezone=None,
rollup=None, limit=None, unit_reference_ts=None):
"""
Returns the number of clicks on a single bitly link.
:var unit: timspan: minute, hour, day, week or month.
When unit is minute the maximum value for units is 60.
if` not indicated, defaults to day.
:vartype unit: str
:var units: an integer representing the time units to query data for.
If -1 is passed, it will return all units of time.
:vartype units: int
:var timezone: an integer hour offset from UTC (-14..14) or a timezone
string. If not indicated, defaults to America/New_York.
:vartype timezone: str
:var rollup: returns data for multiple units rolled up to a single
result instead of a separate value for each period of time.
:vartype rollup: bool
:var limit: the number of rows it will return. Default is 100.
:vartype limit: int
:var unit_reference_ts: an epoch timestamp, indicating the most recent
time for which to pull metrics.
If not indicated, it defaults to now.
:vartype unit_reference_ts: int
"""
params = base.get_params(None, locals())
return self._get('clicks', params)
@base.apimethod
def countries(self, unit=None, units=None, timezone=None,
limit=None, unit_reference_ts=None):
"""
Returns metrics about the countries referring click traffic
to a single bitly link.
:var unit: timspan: minute, hour, day, week or month.
When unit is minute the maximum value for units is 60.
if` not indicated, defaults to day.
:vartype unit: str
:var units: an integer representing the time units to query data for.
If -1 is passed, it will return all units of time.
:vartype units: int
:var timezone: an integer hour offset from UTC (-14..14) or a timezone
string. If not indicated, defaults to America/New_York.
:vartype timezone: str
:var limit: the number of rows it will return. Default is 100.
:vartype limit: int
:var unit_reference_ts: an epoch timestamp, indicating the most recent
time for which to pull metrics.
If not indicated, it defaults to now.
:vartype unit_reference_ts: int
"""
params = base.get_params(None, locals())
return self._get('countries', params)
@base.apimethod
def encoders_count(self):
"""
Returns the number of users who have shortened a single bitly link.
"""
return self._get('encoders_count', {})
@base.apimethod
def referrers(self, unit=None, units=None, timezone=None,
limit=None, unit_reference_ts=None):
"""
Returns metrics about the pages referring click traffic
to a single bitly link.
:var unit: timspan: minute, hour, day, week or month.
When unit is minute the maximum value for units is 60.
if` not indicated, defaults to day.
:vartype unit: str
:var units: an integer representing the time units to query data for.
If -1 is passed, it will return all units of time.
:vartype units: int
:var timezone: an integer hour offset from UTC (-14..14) or a timezone
string. If not indicated, defaults to America/New_York.
:vartype timezone: str
:var limit: the number of rows it will return. Default is 100.
:vartype limit: int
:var unit_reference_ts: an epoch timestamp, indicating the most recent
time for which to pull metrics.
If not indicated, it defaults to now.
:vartype unit_reference_ts: int
"""
params = base.get_params(None, locals())
return self._get('referrers', params)
@base.apimethod
def referrers_by_domain(self, unit=None, units=None, timezone=None,
limit=None, unit_reference_ts=None):
"""
Returns metrics about the pages referring click traffic
to a single bitly link, grouped by referring domain.
:var unit: timspan: minute, hour, day, week or month.
When unit is minute the maximum value for units is 60.
if` not indicated, defaults to day.
:vartype unit: str
:var units: an integer representing the time units to query data for.
If -1 is passed, it will return all units of time.
:vartype units: int
:var timezone: an integer hour offset from UTC (-14..14) or a timezone
string. If not indicated, defaults to America/New_York.
:vartype timezone: str
:var limit: the number of rows it will return. Default is 100.
:vartype limit: int
:var unit_reference_ts: an epoch timestamp, indicating the most recent
time for which to pull metrics.
If not indicated, it defaults to now.
:vartype unit_reference_ts: int
"""
params = base.get_params(None, locals())
return self._get('referrers_by_domain', params)
@base.apimethod
def referring_domains(self, unit=None, units=None, timezone=None,
limit=None, unit_reference_ts=None):
"""
Returns metrics about the domains referring click traffic
to a single bitly link.
:var unit: timspan: minute, hour, day, week or month.
When unit is minute the maximum value for units is 60.
if` not indicated, defaults to day.
:vartype unit: str
:var units: an integer representing the time units to query data for.
If -1 is passed, it will return all units of time.
:vartype units: int
:var timezone: an integer hour offset from UTC (-14..14) or a timezone
string. If not indicated, defaults to America/New_York.
:vartype timezone: str
:var limit: the number of rows it will return. Default is 100.
:vartype limit: int
:var unit_reference_ts: an epoch timestamp, indicating the most recent
time for which to pull metrics.
If not indicated, it defaults to now.
:vartype unit_reference_ts: int
"""
params = base.get_params(None, locals())
return self._get('referring_domains', params)
@base.apimethod
def shares(self, unit=None, units=None, timezone=None,
rollup=None, limit=None, unit_reference_ts=None):
"""
Returns metrics about a shares of a single link.
:var unit: timspan: minute, hour, day, week or month.
When unit is minute the maximum value for units is 60.
if` not indicated, defaults to day.
:vartype unit: str
:var units: an integer representing the time units to query data for.
If -1 is passed, it will return all units of time.
:vartype units: int
:var timezone: an integer hour offset from UTC (-14..14) or a timezone
string. If not indicated, defaults to America/New_York.
:vartype timezone: str
:var rollup: returns data for multiple units rolled up to a single
result instead of a separate value for each period of time.
:vartype rollup: bool
:var limit: the number of rows it will return. Default is 100.
:vartype limit: int
:var unit_reference_ts: an epoch timestamp, indicating the most recent
time for which to pull metrics.
If not indicated, it defaults to now.
:vartype unit_reference_ts: int
"""
params = base.get_params(None, locals())
return self._get('shares', params)
|
Markdown
|
UTF-8
| 10,179 | 3.15625 | 3 |
[] |
no_license
|
# MVVM-Sample-Android-App
** MVVM with Data Binding on Android has the benefits of easier testing and modularity, while also reducing the amount of glue code that we have to write to connect the view + model.
Let’s examine the parts of MVVM.
## Model
The model is the Data + State + Business logic of our Tic-Tac-Toe application. It’s the brains of our application so to speak. It is not tied to the view or controller, and because of this, it is reusable in many contexts.
## View
The view binds to observable variables and actions exposed by the viewModel in a flexible way. More on that in minute.
## ViewModel
The ViewModel is responsible for wrapping the model and preparing observable data needed by the view. It also provides hooks for the view to pass events to the model. The ViewModel is not tied to the view however.
## Evaluation
Unit testing is even easier now, because you really have no dependency on the view. When testing, you only need to verify that the observable variables are set appropriately when the model changes. There is no need to mock out the view for testing as there was with the MVP pattern.
## MVVM Concerns
Maintenance - Since views can bind to both variables and expressions, extraneous presentation logic can creep in over time, effectively adding code to our XML. To avoid this, always get values directly from the ViewModel rather than attempt to compute or derive them in the views binding expression. This way the computation can be unit tested appropriately.
# The library used in this are :
## LiveData
--> LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
--> LiveData considers an observer, which is represented by the Observer class, to be in an active state if its lifecycle is in the STARTED or RESUMED state. LiveData only notifies active observers about updates. Inactive observers registered to watch LiveData objects aren't notified about changes.
--> You can register an observer paired with an object that implements the LifecycleOwner interface. This relationship allows the observer to be removed when the state of the corresponding Lifecycle object changes to DESTROYED. This is especially useful for activities and fragments because they can safely observe LiveData objects and not worry about leaks—activities and fragments are instantly unsubscribed when their lifecycles are destroyed.
### The advantages of using LiveData
Using LiveData provides the following advantages:
#### Ensures your UI matches your data state
--> LiveData follows the observer pattern. LiveData notifies Observer objects when the lifecycle state changes. You can consolidate your code to update the UI in these Observer objects. Instead of updating the UI every time the app data changes, your observer can update the UI every time there's a change.
#### No memory leaks
--> Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed.
#### No crashes due to stopped activities
--> If the observer's lifecycle is inactive, such as in the case of an activity in the back stack, then it doesn’t receive any LiveData events.
#### No more manual lifecycle handling
--> UI components just observe relevant data and don’t stop or resume observation. LiveData automatically manages all of this since it’s aware of the relevant lifecycle status changes while observing.
#### Always up to date data
--> If a lifecycle becomes inactive, it receives the latest data upon becoming active again. For example, an activity that was in the background receives the latest data right after it returns to the foreground.
#### Proper configuration changes
--> If an activity or fragment is recreated due to a configuration change, like device rotation, it immediately receives the latest available data.
#### Sharing resources
--> You can extend a LiveData object using the singleton pattern to wrap system services so that they can be shared in your app. The LiveData object connects to the system service once, and then any observer that needs the resource can just watch the LiveData object. For more information, see Extend LiveData.
## ViewModel
--> The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.
--> The Android framework manages the lifecycles of UI controllers, such as activities and fragments. The framework may decide to destroy or re-create a UI controller in response to certain user actions or device events that are completely out of your control.
--> If the system destroys or re-creates a UI controller, any transient UI-related data you store in them is lost. For example, your app may include a list of users in one of its activities. When the activity is re-created for a configuration change, the new activity has to re-fetch the list of users. For simple data, the activity can use the onSaveInstanceState() method and restore its data from the bundle in onCreate(), but this approach is only suitable for small amounts of data that can be serialized then deserialized, not for potentially large amounts of data like a list of users or bitmaps.
--> Another problem is that UI controllers frequently need to make asynchronous calls that may take some time to return. The UI controller needs to manage these calls and ensure the system cleans them up after it's destroyed to avoid potential memory leaks. This management requires a lot of maintenance, and in the case where the object is re-created for a configuration change, it's a waste of resources since the object may have to reissue calls it has already made.
--> UI controllers such as activities and fragments are primarily intended to display UI data, react to user actions, or handle operating system communication, such as permission requests. Requiring UI controllers to also be responsible for loading data from a database or network adds bloat to the class. Assigning excessive responsibility to UI controllers can result in a single class that tries to handle all of an app's work by itself, instead of delegating work to other classes. Assigning excessive responsibility to the UI controllers in this way also makes testing a lot harder.
--> It's easier and more efficient to separate out view data ownership from UI controller logic.
### Implement a ViewModel
--> Architecture Components provides ViewModel helper class for the UI controller that is responsible for preparing data for the UI. ViewModel objects are automatically retained during configuration changes so that data they hold is immediately available to the next activity or fragment instance. For example, if you need to display a list of users in your app, make sure to assign responsibility to acquire and keep the list of users to a ViewModel, instead of an activity or fragment, as illustrated by the following sample code:
public class MyViewModel extends ViewModel {
private MutableLiveData<List<User>> users;
public LiveData<List<User>> getUsers() {
if (users == null) {
users = new MutableLiveData<List<User>>();
loadUsers();
}
return users;
}
private void loadUsers() {
// Do an asynchronous operation to fetch users.
}
}
--> You can then access the list from an activity as follows:
public class MyActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
// Create a ViewModel the first time the system calls an activity's onCreate() method.
// Re-created activities receive the same MyViewModel instance created by the first activity.
MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
model.getUsers().observe(this, users -> {
// update UI
});
}
}
---> If the activity is re-created, it receives the same MyViewModel instance that was created by the first activity. When the owner activity is finished, the framework calls the ViewModel objects's onCleared() method so that it can clean up resources.
---> ViewModel objects are designed to outlive specific instantiations of views or LifecycleOwners. This design also means you can write tests to cover a ViewModel more easily as it doesn't know about view and Lifecycle objects. ViewModel objects can contain LifecycleObservers, such as LiveData objects. However ViewModel objects must never observe changes to lifecycle-aware observables, such as LiveData objects. If the ViewModel needs the Application context, for example to find a system service, it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor, since Application class extends Context.
## Data binding
--> The Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically.
--> Layouts are often defined in activities with code that calls UI framework methods. For example, the code below calls findViewById() to find a TextView widget and bind it to the userName property of the viewModel variable:
TextView textView = findViewById(R.id.sample_text);
textView.setText(viewModel.getUserName());
--> The following example shows how to use the Data Binding Library to assign text to the widget directly in the layout file. This removes the need to call any of the Java code shown above. Note the use of @{} syntax in the assignment expression:
<TextView
android:text="@{viewmodel.userName}" />
--> Binding components in the layout file lets you remove many UI framework calls in your activities, making them simpler and easier to maintain. This can also improve your app's performance and help prevent memory leaks and null pointer exceptions.
|
Markdown
|
UTF-8
| 4,977 | 2.546875 | 3 |
[] |
no_license
|
---
author:
name: Hildebrant
picture: 110392
body: 'Hello to all... it's been some while since I had much opportunity to contribute.
Good to have a free moment to get back in the community. <BR> <BR>I'm looking
for some ideas, along the lines of type suggestions for an identity I (we)
are developing. <BR> <BR> <BR>I would love to post the design briefs, but that are
anything but brief, near 6 pages of 10 point type. <BR> <BR>So here are the basics:
<BR> <BR>Company: Blume Custom Homes <BR>Type of Company: Custom home builder, 1.5+
<BR>They are on of the top ten custom home builders around. Building mainly in the
southwest region. <BR>We have finished the mark and color systems and are now moving
on to a type system. I am looking for two famlies. <BR> <BR>The feeling is custom,
artistic, one-of-a-kind, unique, southwestern, arizona, new mexico. <BR> <BR>We
are using a slightly modified Mantinia for the name in the mark, the subline of
text (custom homes) is set in Quadratta Sans (sp) <BR> <BR>(1)
for headlines and use at large point sizes, 24+ point sizes. Im thinking a serif,
possibly even a script. This has to be mature, and challenging, if that makes sense.
<BR> <BR>(2) A family for body copy, needing SC, text figures and lining
figures. Im thinking sans, something along the lines of scala, possibly something
like a semiserif, or wedge even? <BR> <BR>Just looking for some suggestions, I seem
to be in a bit of a rut. I would like to keep the total for font purchase to aroun
$300 USD, if possile. <BR> <BR>Love to hear your thoughts. <BR> <BR>Cheers! <BR>
<BR><!--attachment: Blume_CustomHomes_Mark-64269.pdf*mime_pdf.gif*application/pdf*26.3*Mark+and+Grid+for+mark*Blume_CustomHomes_Mark%2epdf
--><center><table border=1><tr><td><img src="http://www.typophile.com/forums/icons/mime_pdf.gif"
align=left alt="application/pdf">Mark and Grid for mark<br><a href="http://www.typophile.com/forums/messages/4100/Blume_CustomHomes_Mark-64269.pdf"
target="_blank"><b>Blume_CustomHomes_Mark.pdf</b></a> (26.3 k)</td></tr></table></center><!--/attachment-->'
comments:
- author:
name: Hildebrant
picture: 110392
body: 'Did not seem to attatch!?!?<!--attachment: Blume_CustomHomes_Mark-64272.pdf*mime_pdf.gif*application/pdf*26.3*Blume+Custom+Homes*Blume_CustomHomes_Mark%2epdf
--><center><table border=1><tr><td><img src="http://www.typophile.com/forums/icons/mime_pdf.gif"
align=left alt="application/pdf">Blume Custom Homes<br><a href="http://www.typophile.com/forums/messages/4100/Blume_CustomHomes_Mark-64272.pdf"
target="_blank"><b>Blume_CustomHomes_Mark.pdf</b></a> (26.3 k)</td></tr></table></center><!--/attachment-->'
created: '2005-01-31 05:39:23'
- author:
name: Stefan H
picture: 109742
body: Kyle, <BR> <BR>Cool logotype! Brave usage of colurs as well, and always nice
to be able to take advantage of the "Golden section". I guess you're
already familiar with the book "Geometry of Design" by Kimberly Elam?
(ISBN 1-56898-249-6). Great book about this subject. <BR> <BR>Anyway,
regarding according typefaces, you might find some of mine appealing? <BR> <BR>1)
Delicato, Remontoire, Luminance or even Oxtail? <BR> <BR>2) Sophisto or Delicato
<BR> <BR>See for yourself at; <a href="http://www.macrhino.com" target="_blank">http://www.macrhino.com</a>
<BR> <BR>Cheers/SH
created: '2005-01-31 08:48:08'
- author:
name: Hildebrant
picture: 110392
body: Thanks stephan, I like oxtail. The others are great faces, but dont seem appropriate
for this project. <BR> <BR>Anyone else have any suggestions?
created: '2005-02-01 15:52:11'
- author:
name: hrant
picture: 110403
body: What about one/some of these? <BR>Adobe Penumbra <BR>Meridien <BR>Perpetua
<BR> <BR>hhp
created: '2005-02-02 19:21:57'
- author:
name: Miss Tiffany
picture: 110563
body: How about <a href="http://www.secretonix.pt/ftf/catalogue/FTFgarda03.htm"
target="_blank">FTF Garda Titling No.3</a>?
created: '2005-02-02 19:47:09'
- author:
name: Hildebrant
picture: 110392
body: Tiffany -- <BR>Thats perfect. It really has the contrast wee need, and just
a touch of that Frank Lloyd Wright vibe. <BR> <BR>We bought it! <BR> <BR>Mario
was very helpful -- and even sent the typeface over so we could test it out with
a few things. The client loves it. <BR> <BR>Thanks for the hlep guys (and
gals). <BR> <BR>Hildebrant.
created: '2005-02-08 21:39:35'
- author:
name: Miss Tiffany
picture: 110563
body: Kyle, no problemo. I had actually just looked through the FTF library before
reading your posts. Kinda cool to see more "trajan-esque" titling fonts
that aren't Trajan. :^)
created: '2005-02-08 22:20:15'
date: '2005-01-31 05:35:52'
node_type: forum
title: Blume Custom Homes Identity
---
|
Java
|
UTF-8
| 1,589 | 3.359375 | 3 |
[] |
no_license
|
package com.apisero;
import java.util.Date;
public class Example2 {
public static int add(int a, int b) {
return a + b;
}
protected static int subtract(int a, int b) {
return a - b;
}
static int multiply(int a, int b) {
return a * b;
}
private static float divide(int a, int b) {
return (float) a / b;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(Math.round(1.238));
System.out.println(Math.min(100, 200));
System.out.println(Math.max(100, 200));
System.out.println(Math.multiplyHigh(2, 5));
System.out.println(Math.pow(2, 5));
System.out.println(Character.toUpperCase('a'));
System.out.println(Character.toLowerCase('B'));
System.out.println(Character.isDigit('9'));
System.out.println(Character.isAlphabetic('@'));
System.out.println(Character.toString('8'));
System.out.println("xyz".indexOf("yz"));
System.out.println("my my my my".replace("my", "Delhi"));
System.out.println("my my my my".replaceFirst(" ", "_"));
System.out.println();
System.out.println("This is fun".toUpperCase());
String[] test = "my my my my".split(" ");
for(int i = 0; i < test.length; i++) {
System.out.print(test[i] + " ");
}
int[] m = new int[7];
int j = 0;
for(int i = 35; i <= 66; i += 5) {
m[j] = i;
j++;
}
for(int i = 0; i < m.length; i++) {
System.out.print(m[i] + " ");
}
int a = 5, b = 3;
System.out.println();
System.out.println(add(a, b));
System.out.println(subtract(a, b));
System.out.println(multiply(a, b));
System.out.println(divide(a, b));
}
}
|
C
|
UTF-8
| 1,734 | 2.515625 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_conversion_format_check.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adconsta <adconsta@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/08 18:24:13 by adconsta #+# #+# */
/* Updated: 2020/12/14 11:26:53 by adconsta ### ########.fr */
/* */
/* ************************************************************************** */
#include "header_printf.h"
unsigned int ft_flag_format(const char *str)
{
unsigned int i;
i = 0;
if (str[i] == '%')
i++;
if (ft_isbase(FLAG, str[i]))
i++;
if (ft_isbase(FLAG, str[i]))
i++;
while (ft_isbase(FLAG, str[i]))
i++;
return (i);
}
unsigned int ft_width_format(const char *str)
{
unsigned int i;
i = 0;
if (str[i] == '*')
i++;
else
{
while (ft_isbase(DIGIT, str[i]))
i++;
}
return (i);
}
unsigned int ft_precision_format(const char *str)
{
unsigned int i;
i = 0;
if (str[i] == '.')
i++;
else
return (0);
if (str[i] == '*')
i++;
else
{
while (ft_isbase(DIGIT, str[i]))
i++;
}
return (i);
}
int ft_check_conversion_format(const char *str)
{
str += ft_flag_format(str);
str += ft_width_format(str);
str += ft_precision_format(str);
if (!ft_isbase(TYPE, *str))
return (1);
return (0);
}
|
SQL
|
UTF-8
| 718 | 3.84375 | 4 |
[] |
no_license
|
DELIMITER ;;
DROP PROCEDURE IF EXISTS most_expensive_products;;
CREATE PROCEDURE most_expensive_products()
BEGIN
DECLARE parameter INT;
SELECT value INTO parameter FROM ad.parameter WHERE name = 'MOST_EXPENSIVE';
SELECT pc.name, top5.price FROM productcategory AS pc
INNER JOIN (
SELECT price, category_id FROM product
ORDER BY price DESC
LIMIT parameter
INNER JOIN productcategory
ON cart
) AS top5
ON pc.id = top5.category_id
GROUP BY pc.name;
END;;
-- Procedure to get most expensive product on each category
-- Returns ID, name, price and category
call most_expensive_products()
|
JavaScript
|
UTF-8
| 1,351 | 2.671875 | 3 |
[] |
no_license
|
import React, { Component } from "react";
class ValidatingForm extends Component {
state = { user: '' }
handleChange = event => {
this.setState({
user: event.target.value
})
}
handleSubmit = event => {
let a = 'a';
event.preventDefault();
alert(`this user is ${this.state.user}`);
}
render() {
//Nedan tar vi in validation, vilken valdiation som helst och i andra index-filen skapar vi valideringen
//Det vill säga att denna render vet aldrig vilken validering som kommer skickas in.
const { user } = this.state;
const error = this.props.getError(user);
return (
<form onSubmit={this.handleSubmit}>
<label>
User:
<input
type="text"
onChange={this.handleChange}
/>
</label>
{error ? <p style={{ color: 'red' }}>{error}</p> : null}
<div>
<button
disabled={Boolean(user.length === 0 || error)}
type="submit">
Submit
</button>
</div>
</form>
);
}
}
export { ValidatingForm };
|
JavaScript
|
UTF-8
| 8,124 | 2.6875 | 3 |
[] |
no_license
|
/**
* @file 轮播
* @author musicode
*/
define(function (require, exports, module) {
'use strict';
var toNumber = require('../function/toNumber');
var Switchable = require('../helper/Switchable');
var Iterator = require('../helper/Iterator');
var lifeUtil = require('../util/life');
/**
* 轮播
*
* @constructor
* @param {Object} options
* @property {jQuery} options.mainElement 主元素
*
* @property {number} options.index 从第几个开始播放
* @property {number} options.minIndex index 的最小值,不传默认是 0
* @property {number} options.maxIndex index 的最大值,不传默认从 DOM 读取切换项的数量
*
* @property {number} options.step 每次滚动几项,通常取决于一屏展现的数量
*
* @property {number} options.timeout 自动播放时,启动的时间间隔,单位是毫秒
* @property {number} options.interval 自动播放时,切换的时间间隔,单位是毫秒
* @property {boolean=} options.loop 是否循环播放
* @property {boolean=} options.reverse 是否反向,正向是从左到右,反向是从右到左
* @property {boolean=} options.autoPlay 是否自动播放
* @property {boolean=} options.pauseOnHover 鼠标 hover item 时是否暂停播放,从用户体验来看,为 true 比较好
*
* @property {string=} options.navTrigger 有导航按钮时,触发切换的方式,可选值有 enter click
* @property {number=} options.navDelay 当 navTrigger 是 enter 时,可以设置延时,单位是毫秒
* @property {Function} options.navAnimation 切换动画
*
* @property {string=} options.navSelector 导航按钮选择器(一般会写序号的小按钮)
* @property {string=} options.navActiveClass 当前 index 对应的导航按钮的 className
*
* @property {string} options.itemSelector 切换项选择器
* @property {string=} options.itemActiveClass 当前 index 对应的切换项的 className
* @property {Function} options.itemAnimation 切换动画
*
* @property {string=} options.prevSelector 上一个按钮的选择器
* @property {string=} options.nextSelector 下一个按钮的选择器
*
*/
function Carousel(options) {
lifeUtil.init(this, options);
}
var proto = Carousel.prototype;
proto.type = 'Carousel';
proto.init = function () {
var me = this;
me.initStruct();
var mainElement = me.option('mainElement');
var namespace = me.namespace();
var clickType = 'click' + namespace;
var prevSelector = me.option('prevSelector');
if (prevSelector) {
mainElement.on(
clickType,
prevSelector,
$.proxy(me.prev, me)
);
}
var nextSelector = me.option('nextSelector');
if (nextSelector) {
mainElement.on(
clickType,
nextSelector,
$.proxy(me.next, me)
);
}
var itemSelector = me.option('itemSelector');
if (me.option('autoPlay')
&& me.option('pauseOnHover')
) {
mainElement
.on(
'mouseenter' + namespace,
itemSelector,
$.proxy(me.pause, me)
)
.on(
'mouseleave' + namespace,
itemSelector,
$.proxy(me.play, me)
);
}
var navTrigger = me.option('navTrigger');
var navSelector = me.option('navSelector');
var navActiveClass = me.option('navActiveClass');
var switcher;
if (navTrigger && navSelector) {
switcher = new Switchable({
mainElement: mainElement,
switchTrigger: navTrigger,
switchDelay: me.option('navDelay'),
itemSelector: navSelector,
itemActiveClass: navActiveClass,
watchSync: {
index: function (index) {
me.set('index', index);
}
}
});
}
var iterator = new Iterator({
timeout: me.option('timeout'),
interval: me.option('interval'),
step: me.option('step'),
loop: me.option('loop'),
watchSync: {
index: function (index) {
me.set('index', index);
},
minIndex: function (minIndex) {
me.set('minIndex', minIndex);
},
maxIndex: function (maxIndex) {
me.set('maxIndex', maxIndex);
}
}
});
var dispatchEvent = function (e, data) {
me.emit(e, data);
};
$.each(exclude, function (index, name) {
iterator
.before(name, dispatchEvent)
.after(name, dispatchEvent);
});
me.inner({
main: mainElement,
switcher: switcher,
iterator: iterator
});
me.set({
index: me.option('index'),
minIndex: me.option('minIndex'),
maxIndex: me.option('maxIndex')
});
};
proto.prev = function () {
this.inner('iterator').prev();
};
proto.next = function () {
this.inner('iterator').next();
};
proto.play = function () {
this.inner('iterator').start(
this.option('reverse')
);
};
proto.pause = function () {
this.inner('iterator').pause();
};
proto.stop = function () {
this.inner('iterator').stop();
};
proto.dispose = function () {
var me = this;
lifeUtil.dispose(me);
me.inner('iterator').dispose();
var switcher = me.inner('switcher');
if (switcher) {
switcher.dispose();
}
};
var exclude = [ 'prev', 'next', 'play', 'pause', 'stop' ];
lifeUtil.extend(proto, exclude);
Carousel.propertyUpdater = {
index: function (index, oldIndex) {
var me = this;
var mainElement = me.inner('main');
me.inner('iterator').set('index', index);
var switcher = me.inner('switcher');
if (switcher) {
switcher.set('index', index);
me.execute('navAnimation', {
mainElement: mainElement,
navSelector: me.option('navSelector'),
navActiveClass: me.option('navActiveClass'),
fromIndex: oldIndex,
toIndex: index
});
}
me.execute('itemAnimation', {
mainElement: mainElement,
itemSelector: me.option('itemSelector'),
itemActiveClass: me.option('itemActiveClass'),
fromIndex: oldIndex,
toIndex: index
});
if (me.option('autoPlay')) {
me.play();
}
},
minIndex: function (minIndex) {
var iterator = this.inner('iterator');
iterator.set('minIndex', minIndex);
iterator.option('defaultIndex', minIndex);
},
maxIndex: function (maxIndex) {
this.inner('iterator').set('maxIndex', maxIndex);
}
};
Carousel.propertyValidator = {
minIndex: function (minIndex) {
return toNumber(minIndex, 0);
},
maxIndex: function (maxIndex) {
maxIndex = toNumber(maxIndex, null);
if (maxIndex == null) {
var items = this.inner('main').find(
this.option('itemSelector')
);
maxIndex = items.length - 1;
}
return maxIndex;
}
};
return Carousel;
});
|
Java
|
UTF-8
| 968 | 2.765625 | 3 |
[
"Apache-2.0"
] |
permissive
|
package bit.operations;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class BitsCountTest extends TestCase {
/**
* Create the test case
*
* @param testName
* name of the test case
*/
public BitsCountTest(String testName) {
super(testName);
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(BitsCountTest.class);
}
/**
* Rigourous Test :-)
*/
public void testNaiveCounter() {
NaiveCounter nc = new NaiveCounter();
assertEquals(3, nc.bitsCount(7));
assertEquals(1, nc.bitsCount(4));
}
public void testKernighan() {
Kernighan kh = new Kernighan();
assertEquals(3, kh.bitsCount(7));
assertEquals(1, kh.bitsCount(4));
}
public void testLookUp() {
LookupTable lt = new LookupTable();
assertEquals(3, lt.bitsCount(7));
assertEquals(1, lt.bitsCount(4));
}
}
|
Java
|
UTF-8
| 1,402 | 2.375 | 2 |
[] |
no_license
|
package com.google.firebase.codelab.friendlychat;
import android.util.Log;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import static android.R.attr.id;
/**
* Created by user on 2016/12/9.
*/
public class FirebaseData {
public DatabaseReference mDatabase;
public FirebaseData(){
mDatabase = FirebaseDatabase.getInstance().getReference();
}
//用callback interface
public interface Callback {
//這個是找完firebase後才會做的函式
void getProfile(UserProfile userProfile);
}
public void getProfileById(String id ,final Callback callback) {
mDatabase.child("UserProfile").orderByChild("userid").equalTo(id).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
UserProfile profile = dataSnapshot.getValue(UserProfile.class);
callback.getProfile(profile);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
}
}
|
C
|
GB18030
| 988 | 4.03125 | 4 |
[] |
no_license
|
// дһû֣ȻҪûϡ
// һдӡһдӡÿеĸĸ
// ĸӦֵĽβ룬ʾ
// Melissa Honeybee
// 7 8
// ȻӡͬϢĸӦʵĿʼ롣
// Melissa Honeybee
// 7 8
#include <stdio.h>
#include <string.h>
int main()
{
char first_name[21];
char last_name[21];
int count_first;
int count_last;
printf("type your first name : ");
scanf("%s", first_name);
printf("type your last name : ");
scanf("%s", last_name);
count_first = strlen(first_name);
count_last = strlen(last_name);
printf("%s %s\n", first_name, last_name);
printf("%*d %*d\n", count_first, count_first, count_last, count_last);
printf("%s %s\n", first_name, last_name);
printf("%-*d %-*d\n", count_first, count_first, count_last, count_last);
return 0;
}
|
Python
|
UTF-8
| 8,504 | 2.859375 | 3 |
[] |
no_license
|
# import the necessary packages
#import four_point_transform function from transform_new.py file
from four import *
from crop_test import *
from ellipse import *
import numpy as np
import cv2
################################################################################
## The following code is strongly derived from the following link: http://www.
## pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example
## code performs edge detection to find contour of object, then uses contour
## to find four cornors of object, and then calls four_point_transform function
## to get rid of excess background behind object and display straigtened object
################################################################################
THRESH_DEF = 120
def find_sorted_contours(image,threshold_value):
# convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
(height,width,foo) = image.shape
# edged = cv2.Canny(gray, 75, 200)
(foo,threshold_image) = cv2.threshold(gray,threshold_value,255,cv2.THRESH_BINARY)
# cv2.imshow("threshold_image", qwertyuiop)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# find the contours in the edged image, keeping only the
# largest ones, and initialize the screen contour
(cnts, _) = cv2.findContours(threshold_image.copy(),
cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)
box = []
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
(x,y,w,h) = cv2.boundingRect(c)
(v,foo) = isIn((x + w/2,y + h/2),box,epsilon,50)
if (0.45 < float(h)/float(w) < 0.55 or 1.3 < float(h)/float(w) < 1.7) and 0.00125 * height * width < cv2.contourArea(approx) < 0.3 * height * width:
if not v:
box.append((x + w/2,y + h/2))
cv2.drawContours(image,[approx],-1,(0,255,0),2)
box = sorted(box, key=lambda (x,y): y)
# image = cv2.resize(image,(0,0),fx = 0.3,fy = 0.3,interpolation = cv2.INTER_LANCZOS4)
# cv2.imshow("f",image)
# cv2.waitKey(0)
return (cnts,box)
def find_long_box_contour(contours, width, below_first_long_box):
long_boxes_contours = []
for c in contours:
# approximate the contour
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
# if our approximated contour has four points, then we
# can assume that we have found our screen
rightmostpoint = tuple(approx[approx[:,:,0].argmax()][0])
leftmostpoint = tuple(approx[approx[:,:,0].argmin()][0])
if len(approx)==2 and leftmostpoint[0]<width/4 and rightmostpoint[0]>3*width/4 and rightmostpoint[1]>below_first_long_box: #and rightmostpoint[1]<height/2:
long_box = approx
long_boxes_contours.append(long_box)
return long_boxes_contours
#sort contours by max y values (from min to max)
def sort_long_box_contours_key(contours):
return contours[contours[:,:,1].argmax()][0][1]
def find_left_right_points(contour):
return (tuple(contour[contour[:,:,0].argmin()][0]),tuple(contour[contour[:,:,0].argmax()][0]))
def find_test_border(sorted_long_boxes_contours, previous_border):
for x in sorted_long_boxes_contours:
rightmostpoint = tuple(x[x[:,:,0].argmax()][0])
leftmostpoint = tuple(x[x[:,:,0].argmin()][0])
if leftmostpoint[1]>previous_border + 50:
test_border = x
break
return test_border
def isVert(h,w):
return h > w
def rotate(img,deg):
(h, w) = img.shape[:2]
M = cv2.getRotationMatrix2D((w/2,h/2),deg,1)
dst = cv2.warpAffine(img,M,(w,h))
return dst
def find_tests(filename):
image = cv2.imread(filename)
# image = resize(image, height = 3264)
(height, width) = image.shape[:2]
if not(isVert(height,width)):
b = int((width - height)/2)
image_r = cv2.copyMakeBorder(image,b,b,0,0,cv2.BORDER_CONSTANT)
image_r = rotate(image_r,-90)
image = image_r
cnts,long_boxes_contours,sorted_long_boxes_contours, box = [],[],[],[]
cond = True
i = 100
img_copy = image.copy()
while cond and i < 200:
(cnts,box) = find_sorted_contours(img_copy,i)
long_boxes_contours = find_long_box_contour(cnts, width, int(height*0.14))
sorted_long_boxes_contours = sorted(long_boxes_contours, key = sort_long_box_contours_key)
cond = len(sorted_long_boxes_contours) < 5
i += 1
print i, len(box)
img_copy = image.copy()
if cond:
raise Exception("Image parse failed!")
sorted_long_boxes_contours = filter(lambda x: box[0][1] < x[0][0][1] < box[1][1],sorted_long_boxes_contours)
print sorted_long_boxes_contours
print box
# cv2.drawContours(image,sorted_long_boxes_contours,-1,(0,255,0),2)
# cv2.imshow(',',image)
# cv2.waitKey(0)
test1_border = sorted_long_boxes_contours[0]
(left_t1_point, right_t1_point) = find_left_right_points(test1_border)
# display_image_with_line(image, left_t1_point, right_t1_point)
test2_border = find_test_border(sorted_long_boxes_contours, left_t1_point[1])
(left_t2_point, right_t2_point) = find_left_right_points(test2_border)
test3_border = find_test_border(sorted_long_boxes_contours, left_t2_point[1])
(left_t3_point, right_t3_point) = find_left_right_points(test3_border)
test4_border = find_test_border(sorted_long_boxes_contours, left_t3_point[1])
(left_t4_point, right_t4_point) = find_left_right_points(test4_border)
test5_border = find_test_border(sorted_long_boxes_contours, left_t4_point[1])
(left_t5_point, right_t5_point) = find_left_right_points(test5_border)
#####################################################
### TEST 1 Section ###
#####################################################
t1_points = [left_t1_point, right_t1_point, left_t2_point , right_t2_point]
test1section = four_point_transform(image, t1_points)
#####################################################
### TEST 2 Section ###
#####################################################
t2_points = [left_t2_point, right_t2_point, left_t3_point , right_t3_point]
test2section = four_point_transform(image, t2_points)
#####################################################
### TEST 3 Section ###
#####################################################
t3_points = [left_t3_point, right_t3_point, left_t4_point, right_t4_point]
test3section = four_point_transform(image, t3_points)
#####################################################
### TEST 4 Section ###
#####################################################
t4_points = [left_t4_point, right_t4_point, left_t5_point , right_t5_point]
test4section = four_point_transform(image, t4_points)
return [test1section,test2section,test3section,test4section]
# filename = "mine.jpg"
# ###################################
# ### draw ACT_box + student box ###
# ###################################
# # cv2.imshow("image123", image123)
# image123 = cv2.imread(filename)
# gray = cv2.cvtColor(image123, cv2.COLOR_BGR2GRAY)
# edged = cv2.Canny(gray, 75, 200)
# edged = cv2.cvtColor(edged, cv2.COLOR_GRAY2BGR)
# (foo,threshold_image) = cv2.threshold(gray,120,255,cv2.THRESH_BINARY)
# img = cv2.cvtColor(threshold_image, cv2.COLOR_GRAY2BGR)
# (height, width) = image123.shape[:2]
# cnts = find_sorted_contours(img)
# long_boxes_contours= find_long_box_contour(cnts, width, int(height*0.14))
# sorted_long_boxes_contours = sorted(long_boxes_contours, key = sort_long_box_contours_key)# reverse = True)#[:5]
# # show edge detected image123
# print "STEP 1: Edge Detection"
# print len(sorted_long_boxes_contours)
# test = edged
# for xxxxx in long_boxes_contours: #sorted_long_boxes_contours:
# # if cv2.contourArea(xxxxx) > 10000:
# cv2.drawContours(test, [xxxxx], -1, (0, 255, 0), 2)
# # ttttt = resize(test, height = 750)
# # print xxxxx[xxxxx[:,:,1].argmin()][0][1]
# # cv2.imshow("Edged", ttttt)
# # cv2.waitKey(0)
# # cv2.destroyAllWindows()
# ttttt = resize(test, height = 750)
# print xxxxx[xxxxx[:,:,1].argmin()][0][1]
# cv2.imshow("Edged", ttttt)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
|
Java
|
UTF-8
| 859 | 2.109375 | 2 |
[] |
no_license
|
package com.appium.screen.flows;
import com.appium.config.CommonAppiumTest;
import com.appium.config.DeviceInterface;
import com.appium.page.objects.HomePageObject;
import com.appium.pages.Login;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import java.io.IOException;
public class AndroidFlow extends CommonAppiumTest implements DeviceInterface {
public AndroidFlow(AppiumDriver<MobileElement> driver) {
super(driver);
}
@Override
public void login(Login loginPage, String emailId, String phoneNumber) throws IOException, InterruptedException {
if(isAndroid()){
loginPage.loginWithEmaildId(emailId);
// loginPage.loginWithPhoneNumber(phoneNumber);
}
}
@Override
public void waitForHomePage(HomePageObject homePageObject) {
}
}
|
JavaScript
|
UTF-8
| 517 | 3.6875 | 4 |
[] |
no_license
|
function solution(people, limit) {
people.sort((a, b) => a - b); // 그냥 sort하면 2자리 이상일 때 정렬안됨
let count = 0;
let l = 0;
let r = people.length - 1;
while (l <= r) {
if (people[l] + people[r] <= limit) l++;
count++;
r--; //최소값과 최댓값이 limit보다 크면 최댓값을 보트태워보낸다
}
return count;
}
console.log(solution([40, 50, 60, 90], 90));
// console.log(solution([70, 50, 80, 50], 100));
// console.log(solution([50, 50, 50, 50], 100));
|
Java
|
UTF-8
| 3,446 | 2.328125 | 2 |
[] |
no_license
|
package test;
import static materialkomponente.BauteilNr.bauteilNr;
import materialkomponente.BauteilNr;
import materialkomponente.IMaterialServicesFuerFertigung;
import materialkomponente.MaterialKomponente;
import persistenz.DatabaseConnection;
import persistenz.IPersistenzService;
import utilities.KeineInventurAtomarerBauteileException;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class MaterialKomponenteTest extends TestCase {
@Rule
public ExpectedException thrown= ExpectedException.none();
IPersistenzService pServ;
IMaterialServicesFuerFertigung mServ;
int b1 = 0;
int b2 = 0;
int bKomplex = 0;
@Before
public void setUp() throws Exception {
pServ = new DatabaseConnection();
mServ = new MaterialKomponente(pServ);
b1 = pServ.create(DatabaseConnection.BAUTEIL, "false,-1");
b2 = pServ.create(DatabaseConnection.BAUTEIL, "false,-1");
// das komplexe Bauteil besteht aus zwei mal b1 und einmal b2
String s = String.format( "true,5,%d,%d,%d",b1,b1,b2);
// true,5,0,0,1
bKomplex = pServ.create(DatabaseConnection.BAUTEIL,s);
}
@After
public void tearDown() throws Exception {
pServ = null;
mServ = null;
b1 = b2 = bKomplex = 0;
}
@Test
public void testZeigeInventar() throws Exception {
int anz = mServ.zeigeInventar(bauteilNr(bKomplex));
assertEquals(anz, 5);
}
@Test
public void testZeigeInventarAtomareBauteile() {
try {
mServ.zeigeInventar(bauteilNr(b1));
}
catch (KeineInventurAtomarerBauteileException e) {
}
catch (Exception e) {
fail();
}
}
@Test
public void testIstKomplexesBauteil() throws Exception {
assertFalse(mServ.istKomplexesBauteil(bauteilNr(b1)));
assertFalse(mServ.istKomplexesBauteil(bauteilNr(b2)));
assertTrue(mServ.istKomplexesBauteil(bauteilNr(bKomplex)));
}
@Test
public void testBestandTeilevon() throws Exception {
List<BauteilNr> bauteile = mServ.bestandTeilevon(bauteilNr(bKomplex));
assertEquals(new HashSet<>(bauteile),
new HashSet<BauteilNr>(Arrays.asList(bauteilNr(b1), bauteilNr(b1), bauteilNr(b2))));
}
@Test
public void testErzeuge() throws Exception {
int dazu = 6;
BauteilNr btn = bauteilNr(bKomplex);
int vorher = mServ.zeigeInventar(btn);
mServ.erzeuge(btn, dazu);
int nachher = mServ.zeigeInventar(btn);
assertEquals(nachher, vorher + dazu);
}
@Test
public void testErzeugeAtomareBauteile() throws Exception {
try {
BauteilNr btn = bauteilNr(b1);
mServ.erzeuge(btn, 1);
}
catch (KeineInventurAtomarerBauteileException e) {
}
catch (Exception e) {
fail();
}
}
@Test
public void testVerbrauche() throws Exception {
int genommen = 2;
BauteilNr btn = bauteilNr(bKomplex);
int vorher = mServ.zeigeInventar(btn);
mServ.verbrauche(btn, genommen);
int nachher = mServ.zeigeInventar(btn);
assertEquals(nachher, vorher - genommen);
}
}
|
C++
|
UTF-8
| 969 | 3.109375 | 3 |
[] |
no_license
|
#ifndef SCREEN_H
#define SCREEN_H
#include <string>
#include <vector>
#include <iostream>
#include "Window_mgr.h"
class Screen {
public:
typedef std::string::size_type pos;
typedef std::vector<Screen>::size_type ScreenIndex;
public:
friend class Window_mgr;
friend void Window_mgr::clear(ScreenIndex);
public:
Screen() = default;
Screen(pos h, pos w) : height(h), width(w), contents(h*w, ' ') {}
Screen(pos h, pos w, char c) : height(h), width(w), contents(h*w,c) {}
public:
char get() const {
return contents[cursor];
}
char get(pos, pos) const;
Screen& move(pos, pos);
Screen& set(char);
Screen& set(pos, pos, char);
Screen& display(std::ostream&);
const Screen& display (std::ostream&) const;
private:
pos cursor = 0;
pos height = 0;
pos width = 0;
std::string contents;
private:
void do_display(std::ostream& os) const {
os << contents;
}
};
#endif
|
Python
|
UTF-8
| 2,204 | 3.09375 | 3 |
[] |
no_license
|
import pygame
from math import sin, cos, atan, pi
from settings import *
class Bullet:
def __init__(self, x, y, tilesize, direction, t_bullet=False, destination=None):
self.speed = 10
self.center = [x, y]
self.startpos = self.center[:]
self.radius = 4
self.hitbox = pygame.Rect([x-self.radius, y-self.radius, 2*self.radius, 2*self.radius])
self.tilesize = tilesize
self.direction = direction
self.t_bullet = t_bullet
if t_bullet is True:
self.destination = destination
self.dx = self.destination[0] - self.center[0]
self.dy = self.destination[1] - self.center[1]
if self.dx != 0:
self.angle = atan(self.dy/self.dx)
def drawBullet(self, screen, player):
pygame.draw.circle(screen, [237, 14, 14], [self.center[0] - player.x + 416, self.center[1]], self.radius)
def bulletUpdate(self, Maps, mapnr, player=None):
if self.t_bullet is False:
self.hitbox = pygame.Rect([self.center[0] - self.radius, self.center[1] - self.radius, 2 * self.radius, 2 * self.radius])
if self.direction == "Right":
self.center[0] += self.speed
elif self.direction == "Left":
self.center[0] -= self.speed
else:
if self.startpos[0] < self.destination[0]:
self.center[0] += int(cos(self.angle) * self.speed)
self.center[1] += int(sin(self.angle) * self.speed)
else:
self.center[0] -= int(cos(self.angle) * self.speed)
self.center[1] -= int(sin(self.angle) * self.speed)
tulpP = int((self.center[0] + self.radius) / self.tilesize)
ridaA = int((self.center[1] + self.radius) / self.tilesize)
tulpV = int((self.center[0] - self.radius) / self.tilesize)
ridaY = int((self.center[1] - self.radius) / self.tilesize)
try:
if Maps.maps[mapnr][ridaA][tulpP] > 0 or Maps.maps[mapnr][ridaA][tulpV] > 0 or Maps.maps[mapnr][ridaY][tulpP] > 0 or Maps.maps[mapnr][ridaY][tulpV] > 0:
return True
except IndexError:
return True
|
C++
|
UTF-8
| 404 | 3.0625 | 3 |
[
"CC0-1.0"
] |
permissive
|
#include "iostream"
#include "vector"
#include "string"
using namespace std;
int main()
{
int num1, num2;
while (cin >> num1 >> num2) {
try {
if (!num2) throw range_error("invalid == 0");
cout << num1 / num2 << endl;
} catch (range_error err) {
cout << err.what() << "\nplease in put the numbers again." << endl;
}
}
return 0;
}
|
Python
|
UTF-8
| 1,755 | 2.53125 | 3 |
[] |
no_license
|
from django.test import TestCase
from django.contrib.auth import get_user_model
class EmployeeManagerTestCase(TestCase):
"""
CommonUser model tests.
"""
def setUp(self):
self.User = get_user_model()
def test_create_user_ok(self):
user = self.User.objects.create_user(
email="user@selin.com.ru", password="testuser")
self.assertEqual(user.email, "user@selin.com.ru")
self.assertTrue(user.is_active)
self.assertFalse(user.is_staff)
self.assertFalse(user.is_superuser)
self.assertIsNone(user.username)
def test_create_user_nok(self):
with self.assertRaises(TypeError):
self.User.objects.create_user(username="user")
with self.assertRaises(TypeError):
self.User.objects.create_user(email="")
with self.assertRaises(ValueError):
self.User.objects.create_user(email="", password="testuser")
def test_create_superuser_ok(self):
super_user = self.User.objects.create_superuser(
email="superuser@selin.com.ru", password="testsuperuser")
self.assertEqual(super_user.email, "superuser@selin.com.ru")
self.assertTrue(super_user.is_active)
self.assertTrue(super_user.is_staff)
self.assertTrue(super_user.is_superuser)
self.assertIsNone(super_user.username)
def test_create_superuser_nok(self):
with self.assertRaises(ValueError):
self.User.objects.create_superuser(
email="superuser@selin.com.ru",
password="testsuperuser",
is_superuser=False)
with self.assertRaises(ValueError):
self.User.objects.create_superuser(
email="superuser@selin.com.ru",
password="testsuperuser",
is_staff=False)
|
Go
|
UTF-8
| 1,736 | 2.9375 | 3 |
[] |
no_license
|
package controller
import (
"encoding/json"
"net/http"
"site/backend/model"
)
type ProdutoController struct {
}
func NewProdutoController() *ProdutoController {
return &ProdutoController{}
}
func (produtoC *ProdutoController) BuscarCategorias(w http.ResponseWriter, r *http.Request) {
categoria1 := model.Categoria{"Livros", 56}
categoria2 := model.Categoria{"Revistas", 1034}
categoria3 := model.Categoria{"Quadrinhos", 548}
categoria4 := model.Categoria{"Albuns", 47}
categoria5 := model.Categoria{"Figurinhas", 738}
categorias := []model.Categoria{categoria1, categoria2, categoria3, categoria4, categoria5}
json.NewEncoder(w).Encode(categorias)
}
func (produtoC *ProdutoController) BuscarProdutos(w http.ResponseWriter, r *http.Request) {
produto1 := model.Produto{"1º Produto", "public/fonts/image/320x150.png", 24.99, 3, "Este é o 1º produto"}
produto2 := model.Produto{"2º Produto", "public/fonts/image/320x150.png", 54.00, 5, "Este é o 2º produto"}
produto3 := model.Produto{"3º Produto", "public/fonts/image/320x150.png", 3.90, 4, "Este é o 3º produto"}
produto4 := model.Produto{"4º Produto", "public/fonts/image/320x150.png", 17.80, 2, "Este é o 4º produto"}
produto5 := model.Produto{"5º Produto", "public/fonts/image/320x150.png", 97.00, 0, "Este é o 5º produto"}
produtos := []model.Produto{produto1, produto2, produto3, produto4, produto5}
json.NewEncoder(w).Encode(produtos)
}
func (produtoC *ProdutoController) BuscarDetalheProduto(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
nome := ps.ByName("id")
produto := model.Produto{nome, "public/fonts/image/320x150.png", 54.00, 5, "Descrição completa do produto"}
json.NewEncoder(w).Encode(produto)
}
|
Go
|
UTF-8
| 3,409 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
package server
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"github.com/ActiveState/tail"
)
var tempBuild = path.Join(os.TempDir(), "build")
const maxQueue = 20
//Server is an HTTP server accepting requests
//for cross-compilation
type Server struct {
Port string
count int
q chan *Compilation
curr *Compilation
doneCount int
done []*Compilation
logger *Logger
files http.Handler
}
//NewServer creates a new Server
func NewServer(port string) (*Server, error) {
if BINTRAY_API_KEY == "" {
return nil, errors.New("BINTRAY_API_KEY variable not set")
}
dir := ""
localPath := "static/"
goPath := os.Getenv("GOPATH") + "/src/github.com/jpillora/cloud-gox/static/"
if _, err := os.Stat(localPath); err == nil {
dir = localPath
} else if _, err := os.Stat(goPath); err == nil {
dir = goPath
} else {
return nil, errors.New("static files directory not found")
}
return &Server{
Port: port,
q: make(chan *Compilation, maxQueue),
logger: NewLogger(),
files: http.FileServer(http.Dir(dir)),
}, nil
}
func (s *Server) Start() error {
//service queue
go s.dequeue()
//tail -f the log for the toolchain build
go s.tailToolchain()
//initial empty status update
s.statusUpdate()
http.Handle("/", s.files)
http.Handle("/log", s.logger.stream)
http.HandleFunc("/compile", s.enqueueReq)
http.HandleFunc("/hook", s.hookReq)
return http.ListenAndServe(":"+s.Port, nil)
}
func (s *Server) tailToolchain() {
t, err := tail.TailFile("toolchain.log", tail.Config{
Follow: true,
Logger: tail.DiscardingLogger,
})
if err != nil {
return
}
for line := range t.Lines {
s.Printf("%s\n", line.Text)
}
}
func (s *Server) enqueueReq(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(400)
w.Write([]byte("missing body"))
return
}
c := &Compilation{}
err = json.Unmarshal(b, c)
if err != nil {
w.WriteHeader(400)
w.Write([]byte("invalid json: " + err.Error()))
return
}
//all "compile" requests go to a public bintray
c.Dest = "bintray"
err = s.enqueue(c)
if err != nil {
w.WriteHeader(400)
w.Write([]byte(err.Error()))
}
}
func (s *Server) enqueue(c *Compilation) error {
if err := c.verify(); err != nil {
return err
}
if len(s.q) == maxQueue {
return errors.New("Queue is full")
}
s.count++
c.ID = s.count
c.Completed = false
c.Queued = true
c.Error = ""
//default pkg root
if len(c.Targets) == 0 {
c.Targets = []string{"."}
}
s.q <- c
s.statusUpdate()
return nil
}
func (s *Server) dequeue() {
for c := range s.q {
c.Queued = false
s.curr = c
s.statusUpdate()
s.Printf("compiling '%s'...\n", c.Package)
if err := s.compile(c); err != nil {
s.Printf("compile error '%s': %s\n", c.Package, err)
c.Error = err.Error()
} else {
s.Printf("compiled '%s'\n", c.Package)
}
//clean up
os.RemoveAll(tempBuild)
c.Completed = true
s.curr = nil
s.done = append(s.done, c)
s.doneCount++
s.statusUpdate()
}
}
func (s *Server) statusUpdate() {
//limit to latest 10
d := s.done
if len(d) > 10 {
d = d[len(d)-10:]
}
s.logger.statusUpdate(&statusEvent{
Current: s.curr,
NumQueued: len(s.q),
NumDone: s.doneCount,
Done: d,
})
}
func (s *Server) Printf(f string, args ...interface{}) {
fmt.Fprintf(s.logger, f, args...)
}
|
JavaScript
|
UTF-8
| 1,331 | 2.703125 | 3 |
[] |
no_license
|
'use strict';
var request = require("request");
const http = require('http');
const agent = new http.Agent({maxSockets: 30}); // 5 concurrent connections per origin
//Promessify la lib request, pour garder le style de codage
function request_promise(url, options){
return new Promise( (resolve, reject)=>{
request(url, options, (err, response, body)=>{
if(err) reject(err);
else resolve(body);
});
})
}
/**
* Free Google API implementation
* Normaly for debugging purpose
* @param {string} text text to translate
* @param {string} apiKey user api key to use for translation (if needed)
*/
module.exports = (text,config)=>{
let from = config.from || 'fr';
let to = config.to[0] || 'en'; // only one for now....
let url = "http://translate.googleapis.com/translate_a/single?client=gtx&sl="
+ from + "&tl=" + to + "&dt=t&q=" + encodeURI(text);
return request_promise(url,{agent: agent})
.then ( (trs)=>{
/*
[
[
["Internal","Interne",null,null,2]
],null,"fr"
]
*/
let sent = JSON.parse(trs)[0][0][0];
return sent;
});
}
|
PHP
|
UTF-8
| 4,056 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$name = filter_input(INPUT_POST, 'formName', FILTER_SANITIZE_SPECIAL_CHARS);
$tel = filter_input(INPUT_POST, 'formTel', FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_input(INPUT_POST, 'formEmail', FILTER_SANITIZE_SPECIAL_CHARS);
$url = filter_input(INPUT_POST, 'formUrl', FILTER_SANITIZE_SPECIAL_CHARS);
$gender = filter_input(INPUT_POST, 'formGender', FILTER_SANITIZE_SPECIAL_CHARS);
$hobbieRead = filter_input(INPUT_POST, 'formRead', FILTER_SANITIZE_SPECIAL_CHARS);
$hobbieSwim = filter_input(INPUT_POST, 'formSwim', FILTER_SANITIZE_SPECIAL_CHARS);
$hobbieRun = filter_input(INPUT_POST, 'formRun', FILTER_SANITIZE_SPECIAL_CHARS);
$nationality = filter_input(INPUT_POST, 'formNationality', FILTER_SANITIZE_SPECIAL_CHARS);
$message = filter_input(INPUT_POST, 'formMessage', FILTER_SANITIZE_SPECIAL_CHARS);
$isHobbieRead = $hobbieRead ? 'Si' : 'No';
$isHobbieSwim = $hobbieSwim ? 'Si' : 'No';
$isHobbieRun = $hobbieRun ? 'Si' : 'No';
$comments = '<div> Nombre: ' . $name
. '<br /> Teléfono: ' . $tel
. '<br /> Correo electrónico: ' . $email
. '<br /> Sitio web: ' . $url
. '<br /> Sexo: ' . $gender
. '<br /> Leer: ' . $isHobbieRead
. '<br /> Nadar: ' . $isHobbieSwim
. '<br /> Correr: ' . $isHobbieRun
. '<br /> Nacionalidad: ' . $nationality
. '<br /> Mensaje: ' . $message
. '</div>';
require_once 'PHPMailerAutoload.php';
$phpmailer = new PHPMailer();
$phpmailer->IsHTML( TRUE );
$phpmailer->ClearAddresses();
$phpmailer->AddAddress( 'aanayaluna@gmail.com', 'Alexandra Anaya Luna' ); // Correo del destinatario y nombre
$phpmailer->addBCC( '' ); // Correo CC
//$phpmailer->IsSMTP();
$phpmailer->SMTPDebug = 0;
$phpmailer->CharSet = 'UTF-8';
$phpmailer->SMTPAuth = true;
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->Host = 'smtp.gmail.com'; // Servidor de correo saliente SMTP
$phpmailer->Port = 465; // Puerto de correo saliente SMTP
$phpmailer->Username = 'nayelli.sangenis@gmail.com'; // Usuario del correo electrónico
$phpmailer->Password = '$eduMac_1010*'; // Contraseña del correo electrónico
$phpmailer->From = 'nayelli.sangenis@gmail.com'; // From
$phpmailer->FromName = 'Formulario Web'; // From Name
$phpmailer->Subject = 'Contacto'; // Subject
$phpmailer->MsgHTML( $comments );
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Formularios Web</title>
<link rel="stylesheet" href="../css/main.css" />
</head>
<body>
<div class="wrapper">
<header class="header-page">
<div class="container">
<h1>Formularios</h1>
</div>
</header>
<main class="main-page">
<div class="container">
<section class="section-page">
<?php if ( $phpmailer->Send() ): ?>
<p>El correo electrónico se ha enviado</p><!-- HTML que se mostrará cuando el correo se envíe correctamente. -->
<?php else: ?>
<p class="error">Ocurrio un error al enviar los datos</p><!-- HTML en caso de error de envío. -->
<?php endif; ?>
</div>
</section>
</main>
<footer class="footer-page">
<div class="container">
<p>Todos los derechos reservados | Alexandra Anaya Luna | eduMac 2017</p>
</div>
</footer>
</div>
</body>
</html>
|
C#
|
UTF-8
| 5,267 | 2.703125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Linq.Expressions;
using System.Reflection;
using System.Configuration;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
namespace MealsToGo.Repository
{
}
// public class DataRepository<TContext> : IDataRepository<TContext> where TContext : ObjectContext
//{
// // Cached ObjectSets so changes persist
// protected Dictionary<string, object> CachedObjects = new Dictionary<string, object>();
// protected ObjectSet<TEntity> GetObjectSet<TEntity>() where TEntity : EntityObject
// {
// var fulltypename = typeof (TEntity).AssemblyQualifiedName;
// if (fulltypename == null)
// throw new ArgumentException("Invalid Type passed to GetObjectSet!");
// if (!CachedObjects.ContainsKey(fulltypename))
// {
// var objectset = _context.CreateObjectSet<TEntity>();
// CachedObjects.Add(fulltypename, objectset);
// }
// return CachedObjects[fulltypename] as ObjectSet<TEntity>;
// }
// protected TContext _context;
// /// <summary>
// /// Constructor that takes a context
// /// </summary>
// /// <param name="context">An established data context</param>
// public DataRepository(TContext context)
// {
// _context = context;
// }
// /// <summary>
// /// Constructor that takes a connection string and an EDMX name
// /// </summary>
// /// <param name="connectionString">The connection string</param>
// /// <param name="edmxName">The name of the EDMX so we can build an Entity Connection string</param>
// public DataRepository(string connectionString, string edmxName)
// {
// var entityConnection =
// String.Format(
// "metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl;provider=System.Data.SqlClient;provider connection string=",
// edmxName);
// // append the database connection string and save
// entityConnection = entityConnection + "\"" + connectionString + "\"";
// var targetType = typeof (TContext);
// var ctx = Activator.CreateInstance(targetType, entityConnection);
// _context = (TContext) ctx;
// }
// public IQueryable<TEntity> Fetch<TEntity>() where TEntity : EntityObject
// {
// return GetObjectSet<TEntity>();
// }
// public IEnumerable<TEntity> GetAll<TEntity>() where TEntity : EntityObject
// {
// return GetObjectSet<TEntity>().AsEnumerable();
// }
// public IEnumerable<TEntity> Find<TEntity>(Func<TEntity, bool> predicate) where TEntity : EntityObject
// {
// return GetObjectSet<TEntity>().Where(predicate);
// }
// public TEntity GetSingle<TEntity>(Func<TEntity, bool> predicate) where TEntity : EntityObject
// {
// return GetObjectSet<TEntity>().Single(predicate);
// }
// public TEntity GetFirst<TEntity>(Func<TEntity, bool> predicate) where TEntity : EntityObject
// {
// return GetObjectSet<TEntity>().First(predicate);
// }
// public IEnumerable<TEntity> GetLookup<TEntity>() where TEntity : EntityObject
// {
// return GetObjectSet<TEntity>().ToList();
// }
// public void Add<TEntity>(TEntity entity) where TEntity : EntityObject
// {
// if (entity == null)
// throw new ArgumentException("Cannot add a null entity");
// GetObjectSet<TEntity>().AddObject(entity);
// }
// public void Delete<TEntity>(TEntity entity) where TEntity : EntityObject
// {
// if (entity == null)
// throw new ArgumentException("Cannot delete a null entity");
// GetObjectSet<TEntity>().DeleteObject(entity);
// }
// public void Attach<TEntity>(TEntity entity) where TEntity : EntityObject
// {
// if (entity == null)
// throw new ArgumentException("Cannot attach a null entity");
// GetObjectSet<TEntity>().Attach(entity);
// }
// public void SaveChanges()
// {
// SaveChanges(SaveOptions.None);
// }
// public void SaveChanges(SaveOptions options)
// {
// _context.SaveChanges(options);
// }
// public void Refresh<TEntity>(TEntity entity) where TEntity : EntityObject
// {
// _context.Refresh(RefreshMode.StoreWins, entity);
// }
// public void Refresh<TEntity>(IEnumerable<TEntity> entities) where TEntity : EntityObject
// {
// _context.Refresh(RefreshMode.StoreWins, entities);
// }
// #region IDisposable implementation
// private bool disposedValue;
// protected void Dispose(bool disposing)
// {
// if (!this.disposedValue)
// {
// if (disposing)
// {
// // dispose managed state here if required
// }
// // dispose unmanaged objects and set large fields to null
// }
// this.disposedValue = true;
// }
// public void Dispose()
// {
// Dispose(true);
// GC.SuppressFinalize(this);
// }
// #endregion
//}
// }
|
Markdown
|
UTF-8
| 1,056 | 3.203125 | 3 |
[] |
no_license
|
# Verlet Integration
This repo uses verlet integration to simulate a world with:
- Points
- Sticks connecting points
- A cloth
- A (swinging) block
It was mostly inspired by [this paper by Thomas
Jakobsen](http://graphics.cs.cmu.edu/nsp/course/15-869/2006/papers/jakobsen.htm).
I [wrote a blog](https://040code.github.io/2018/03/04/verlet-integration/)
explaining this code.
## Installation
Prerequisites:
- [JVM](http://www.oracle.com/technetwork/java/javase/downloads/index.html)
installed
- [Leiningen](https://leiningen.org) installed
`git clone <this repo>`
Tested on java8.
## Usage
Running `lein run` in the root of this project will start an applet where you
can interact with mouse and keyboard.
Keybindings:
- `b` (re)start block simulation
- `c` (re)start cloth simulation
- `p` (re)start point simulation
- `s` (re)start stick simulation
- `i` to show info screen
- `q` to quit
Mouse interactions:
- Click and drag any point
- Unpin a pinned point
## License
Use the code the way you want it at your own risk. It is not copyrighted.
|
JavaScript
|
UTF-8
| 673 | 2.578125 | 3 |
[] |
no_license
|
const message = '<div>Hi {{candidate.name}} !</div><div><br></div><div>Thank you for applying! We have received your application and will keep you updated on the process as soon as your application status changes.</div><div><a href="http://Happo">Happo</a></div><div><br></div><div><a href="http://Happo">Happo</a></div><div><br></div><div>Have a nice day!</div><div><br></div><div>Sincerely, </div><div><br></div><div>{{name}} at {{companyName}}</div>';
const preProcessMessage = (m) => {
if (m.indexOf('<a') < 0) {
return m;
}
return m.split('<a').join('<a style="color: #009fe2;text-decoration: none;"');
}
console.log(preProcessMessage(message));
|
PHP
|
UTF-8
| 193 | 2.625 | 3 |
[] |
no_license
|
<?php
namespace RonteLtd\Zmq;
interface Client
{
/**
* Send message to Queue.
*
* @return bool Success/Unsuccess
*/
public function send(string $message): bool;
}
|
JavaScript
|
UTF-8
| 1,090 | 3.703125 | 4 |
[
"MIT"
] |
permissive
|
/**
* what
*
* @author GuoBin on
*/
'use strict';
function log(param) {
console.log(param);
}
log(parseInt('2'));
// [1, NaN, NaN]
log(['1', '2', '3'].map(parseInt));
log(['1', '2', '3'].map((val, index, arr) => {
console.log(index);
// console.log(arr);
return parseInt(val, 10);
}));
// 'object', false
log([typeof null, null instanceof Object]);
// 81
const res = [[3, 2, 2].reduce(Math.pow)];
log(res);
const END = Math.pow(2, 53);
log(END);
const a = 0.2;
const b = 0.1;
const c = 0.8;
const d = 0.6;
const bool1 = a - b === b;
console.log(a - b); // 0.1
console.log(c - d); // 0.20000000000007
const bool2 = c - d === 1;
log(bool1);
log(bool2);
console.log(String('a'));
function isOdd(num) {
return num % 2 === 1;
}
function isEven(num) {
return num % 2 === 0;
}
function isSane(num) {
return isEven(num) || isOdd(num);
}
console.log(true || false);
console.log(isSane(7));
// true
console.log(Array.isArray(Array.prototype));
console.log(Array);
console.log(Array.prototype);
console.log('5' + 3);
console.log('5' - 3);
// 2
console.log(1 + - + + + - + 1);
|
C++
|
UTF-8
| 683 | 2.59375 | 3 |
[] |
no_license
|
#include "Icon.hpp"
#include <cstdlib>
Icon::Icon(std::string pathToFile) : pathToFile(pathToFile) {
WORD pWord;
ICONINFO iconinfo;
HICON hIcon = ExtractAssociatedIcon(GetModuleHandle(NULL), pathToFile.c_str(), &pWord);
GetIconInfo(hIcon, &iconinfo);
hBitmap = iconinfo.hbmColor;
if (!hBitmap) exit(1);
}
Icon::~Icon() {
}
std::string Icon::GetPathToFile() const {
return pathToFile;
}
HBITMAP Icon::GetHBitmap() const {
return hBitmap;
}
int Icon::GetHeight() const {
return height;
}
int Icon::GetWidth() const {
return width;
}
void Icon::SetHeight(int newHeight) {
height = newHeight;
}
void Icon::SetWidth(int newWidth) {
width = newWidth;
}
|
Markdown
|
UTF-8
| 2,628 | 2.71875 | 3 |
[] |
no_license
|
### Resources
### Parameters (can be referenced via Fn::Ref or !Ref)
Example define parameter:
```
Parameters:
SecurityGroupDescription:
Description: Security Group Description
Type: String
```
Example use parameter:
```
ServerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: !Ref SecurityGroupDescription
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
```
### Mappings (can be referenced via Fn::FindInMap or !FindInMap)
FindInMap [ MapName, TopLevelKey, SecondLevelKey ]
Example:
```
Mappings:
RegionMap:
us-east-1:
"32": "ami-3231312"
"64": "ami-5454545"
us-west-1:
"32": "ami-78787"
"64": "ami-98988"
Resources:
MyEc2Instance:
Type: AWS::EC2:Instance
Properties:
ImageId: !FindInMap [RegionMap, !Ref "AWS:Region", 32]
InstanceType: t2.micro
```
### Outputs (can be imported via Fn::ImportValue or !ImportValue)
Define output example:
```
Outputs:
StackSSHSecurityGroup:
Description: The SSH Security Group for our Company
Value: !Ref MyCompanyWideSSHSecurityGroup
Export:
Name: SSHSecurityGroup
```
Import output example:
```
Resources:
MySecureInstance:
Type: AWS::EC2::Instance
Properties:
AvailabilityZone: us-east-1a
ImageId: ami-a4c7edb2
InstanceType: t2.micro
SecurityGroups:
- !ImportValue SSHSecurityGroup
```
### Conditions
Create a condition example:
```
Conditions:
CreateProdResources: !Equals [ !Ref EnvType, prod ]
```
Functions:
- And
- Equals
- If
- Not
- Or
Use the condition example:
```
Resources:
MountPoint:
Type: "AWS::EC2::VolumeAttachment"
Condition: CreateProdResources
```
### Intrinsic Functions
- Ref
- Fn::GetAtt
- Fn::FindInMap
- Fn::ImportValue
- Fn::Join
- Fn::Sub
- Condition functions (If, Equals, And, Or, Not)
### GetAtt Example (get AZ from EC2)
```
Resources:
EC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-123456
InstanceType: t2.micro
NewVolume:
Type: AWS::ECS::Volume
Condition: CreateProdResources
Properties:
Size: 100
AvailabilityZone:
!GetAtt: EC2Instance.AvailabilityZone
```
### Join demo
### e.g. create "a:b:c"
!Join [ ":", [a, b, c] ]
### CloudFormation Rollbacks
### CloudFormation ChangeSets
### CloudFormation Nested Stacks VS Cross Stacks
### CloudFormation StackSet
|
Java
|
UTF-8
| 2,330 | 2.734375 | 3 |
[] |
no_license
|
package com.ada.proyectoFinal.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table (name= "Producto")
public class Producto {
// ATRIBUTOS
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private int id;
private String productName;
private String category;
private String description;
private String ingredients;
private String preparation;
private float weight;
private float price;
private int stock;
// CONSTRUCTOR
public Producto () {
}
public Producto (int id, String productName, String category, String description, String ingredients, String preparation, float weight, float price, int stock) {
this.id = id;
this.productName = productName;
this.category = category;
this.description = description;
this.ingredients = ingredients;
this.preparation = preparation;
this.weight = weight;
this.price = price;
this.stock = stock;
}
// GETTERS Y SETTERS
public int getId() {
return id;
}
public String getProductName() {
return productName;
}
public String getCategory() {
return category;
}
public String getDescription() {
return description;
}
public String getIngredients() {
return ingredients;
}
public String getPreparation() {
return preparation;
}
public float getWeight() {
return weight;
}
public float getPrice() {
return price;
}
public int getStock() {
return stock;
}
public void setId(int id) {
this.id = id;
}
public void setProductName(String productName) {
this.productName = productName;
}
public void setCategory(String category) {
this.category = category;
}
public void setDescription(String description) {
this.description = description;
}
public void setIngredients(String ingredients) {
this.ingredients = ingredients;
}
public void setPreparation(String preparation) {
this.preparation = preparation;
}
public void setWeight(float weight) {
this.weight = weight;
}
public void setPrice(float price) {
this.price = price;
}
public void setStock(int stock) {
this.stock = stock;
}
}
|
Ruby
|
UTF-8
| 947 | 3.484375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def roll_call_dwarves(dwarfs)
# takes an array of dwarfs and prints out a numbered list of dwarfs
dwarfs.each_with_index {|dwarf, index| puts "#{index + 1} #{dwarf}"}
end
def summon_captain_planet(planeteer_calls)
# takes an array of planeteer calls and returns an array of each planeteer_call
# capitalized with a bang attached
planeteer_calls.map {|planeteer_call| planeteer_call.capitalize << "!"}
end
def long_planeteer_calls(planeteer_calls)
# takes an array of planeteer_calls and returns true if any planeteer_call(s)
# are 5-lettered or more and false otherwise
planeteer_calls.any? {|planeteer_call| planeteer_call.length > 4}
end
def find_the_cheese(ingredients)
# takes an array of food ingredients an returns the first ingredient is also
# in the array of cheeses, cheese_types
cheese_types = ["cheddar", "gouda", "camembert"]
ingredients.find do |ingredient|
cheese_types.include?(ingredient)
end
end
|
Java
|
UTF-8
| 2,180 | 2.140625 | 2 |
[] |
no_license
|
package com.pnp;
import java.util.ArrayList;
import java.util.List;
import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.activity.BaseActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.pnp.adapter.CircleAdapter;
import com.pnp.model.CircleImgs;
import com.pnp.model.CircleInfo;
public class CircleActivity extends BaseActivity {
@BindView(id = R.id.circle_list)
private ListView mListView;
@Override
public void setRootView() {
setContentView(R.layout.activity_circle);
}
@Override
protected void initWidget() {
super.initWidget();
final TextView titleView = (TextView) findViewById(R.id.actionbar_title);
titleView.setText("朋友圈");
final Button backButton = (Button) findViewById(R.id.actionbar_back);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
mListView.addHeaderView(getheadView());
// mListView.setDividerHeight(0);
setData();
}
private void setData() {
List<CircleInfo> mList = new ArrayList<CircleInfo>();
CircleInfo mUserInfo = new CircleInfo();
CircleImgs m = new CircleImgs();
m.setUrls("http://m1.img.srcdd.com/farm2/d/2011/0817/01/5A461954F44D8DC67A17838AA356FE4B_S64_64_64.JPEG");
mUserInfo.getUi().add(m);
mList.add(mUserInfo);
// ---------------------------------------------
CircleInfo mUserInfo2 = new CircleInfo();
CircleImgs m2 = new CircleImgs();
m2.setUrls("http://m1.img.srcdd.com/farm2/d/2011/0817/01/5A461954F44D8DC67A17838AA356FE4B_S64_64_64.JPEG");
mUserInfo2.getUi().add(m2);
CircleImgs m21 = new CircleImgs();
m21.setUrls("http://m1.img.srcdd.com/farm2/d/2011/0817/01/5A461954F44D8DC67A17838AA356FE4B_S64_64_64.JPEG");
mUserInfo2.getUi().add(m21);
mList.add(mUserInfo2);
CircleAdapter mWeChatAdapter = new CircleAdapter(this);
mWeChatAdapter.setData(mList);
mListView.setAdapter(mWeChatAdapter);
}
private View getheadView() {
View view = LayoutInflater.from(CircleActivity.this).inflate(
R.layout.circle_header, null);
return view;
}
}
|
C#
|
UTF-8
| 1,393 | 2.71875 | 3 |
[] |
no_license
|
using CarWebApplication.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CarWebApplication.Services
{
public interface IUserData
{
LoginViewModel UserViewModel { get; set; }
IDataSource DataSource { get; set; }
bool CheckLoginUser();
}
public class UserData : IUserData
{
public LoginViewModel UserViewModel { get; set ; }
public IDataSource DataSource { get; set; }
public bool CheckLoginUser()
{
var user = DataSource.GetUserInfo();
if(user!=null && !string.IsNullOrWhiteSpace(user.Email))
return true;
return false;
}
}
public interface IDataSource
{
LoginViewModel UserViewModel { get; set; }
LoginViewModel GetUserInfo();
}
public class JsonDataSource : IDataSource
{
public LoginViewModel UserViewModel { get; set ; }
public LoginViewModel GetUserInfo()
{
var userVm = new LoginViewModel();
return userVm;
}
}
public class XmlDataSource : IDataSource
{
public LoginViewModel UserViewModel { get; set; }
public LoginViewModel GetUserInfo()
{
var userVm = new LoginViewModel();
return userVm;
}
}
}
|
Java
|
UTF-8
| 41,540 | 1.640625 | 2 |
[
"Apache-2.0"
] |
permissive
|
// Generated from KafkaSql.g4 by ANTLR 4.7.2
package com.looboo.kafkasql.parser;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.*;
import org.antlr.v4.runtime.tree.*;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class KafkaSqlParser extends Parser {
static { RuntimeMetaData.checkVersion("4.7.2", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
T__0=1, T__1=2, T__2=3, T__3=4, WS=5, SELECT=6, FROM=7, IN=8, WHERE=9,
BETWEEN=10, PARTITION=11, TIMESTAMP=12, OFFSET=13, TOPICS=14, OFFSETS=15,
PARTITIONS=16, CONSUMERS=17, CONSUMER_OFFSET=18, COUNT=19, BYTE=20, STR=21,
STAR=22, EQUAL=23, SEMICOLON=24, ID=25, SPACE=26, NUMBER=27, CHARS=28;
public static final int
RULE_selectStatement = 0, RULE_topicStatement = 1, RULE_offsetStatement = 2,
RULE_partitionsStatement = 3, RULE_consumersStatement = 4, RULE_consumerOffsetStatement = 5,
RULE_countStatement = 6, RULE_querySpecification = 7, RULE_value = 8,
RULE_whereClause = 9, RULE_inCluase = 10, RULE_betweenCluase = 11, RULE_equationClause = 12,
RULE_partitionsEquslCluase = 13, RULE_timestampEquslCluase = 14, RULE_valueEqualClause = 15,
RULE_byteFunction = 16, RULE_strFunction = 17, RULE_numberList = 18, RULE_charsList = 19;
private static String[] makeRuleNames() {
return new String[] {
"selectStatement", "topicStatement", "offsetStatement", "partitionsStatement",
"consumersStatement", "consumerOffsetStatement", "countStatement", "querySpecification",
"value", "whereClause", "inCluase", "betweenCluase", "equationClause",
"partitionsEquslCluase", "timestampEquslCluase", "valueEqualClause",
"byteFunction", "strFunction", "numberList", "charsList"
};
}
public static final String[] ruleNames = makeRuleNames();
private static String[] makeLiteralNames() {
return new String[] {
null, "'('", "'.'", "','", "')'", null, "'SELECT'", "'FROM'", "'IN'",
"'WHERE'", "'BETWEEN'", "'PARTITION'", "'TIMESTAMP'", "'OFFSET'", "'TOPICS'",
"'OFFSETS'", "'PARTITIONS'", "'CONSUMERS'", "'CONSUMER_OFFSET'", "'COUNT'",
"'BYTE'", "'STR'", "'*'", "'='", "';'", null, "' '"
};
}
private static final String[] _LITERAL_NAMES = makeLiteralNames();
private static String[] makeSymbolicNames() {
return new String[] {
null, null, null, null, null, "WS", "SELECT", "FROM", "IN", "WHERE",
"BETWEEN", "PARTITION", "TIMESTAMP", "OFFSET", "TOPICS", "OFFSETS", "PARTITIONS",
"CONSUMERS", "CONSUMER_OFFSET", "COUNT", "BYTE", "STR", "STAR", "EQUAL",
"SEMICOLON", "ID", "SPACE", "NUMBER", "CHARS"
};
}
private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames();
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
@Override
public String getGrammarFileName() { return "KafkaSql.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public ATN getATN() { return _ATN; }
public KafkaSqlParser(TokenStream input) {
super(input);
_interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
public static class SelectStatementContext extends ParserRuleContext {
public TerminalNode SELECT() { return getToken(KafkaSqlParser.SELECT, 0); }
public TopicStatementContext topicStatement() {
return getRuleContext(TopicStatementContext.class,0);
}
public OffsetStatementContext offsetStatement() {
return getRuleContext(OffsetStatementContext.class,0);
}
public PartitionsStatementContext partitionsStatement() {
return getRuleContext(PartitionsStatementContext.class,0);
}
public ConsumersStatementContext consumersStatement() {
return getRuleContext(ConsumersStatementContext.class,0);
}
public ConsumerOffsetStatementContext consumerOffsetStatement() {
return getRuleContext(ConsumerOffsetStatementContext.class,0);
}
public QuerySpecificationContext querySpecification() {
return getRuleContext(QuerySpecificationContext.class,0);
}
public CountStatementContext countStatement() {
return getRuleContext(CountStatementContext.class,0);
}
public SelectStatementContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_selectStatement; }
}
public final SelectStatementContext selectStatement() throws RecognitionException {
SelectStatementContext _localctx = new SelectStatementContext(_ctx, getState());
enterRule(_localctx, 0, RULE_selectStatement);
try {
setState(54);
_errHandler.sync(this);
switch ( getInterpreter().adaptivePredict(_input,0,_ctx) ) {
case 1:
enterOuterAlt(_localctx, 1);
{
setState(40);
match(SELECT);
setState(41);
topicStatement();
}
break;
case 2:
enterOuterAlt(_localctx, 2);
{
setState(42);
match(SELECT);
setState(43);
offsetStatement();
}
break;
case 3:
enterOuterAlt(_localctx, 3);
{
setState(44);
match(SELECT);
setState(45);
partitionsStatement();
}
break;
case 4:
enterOuterAlt(_localctx, 4);
{
setState(46);
match(SELECT);
setState(47);
consumersStatement();
}
break;
case 5:
enterOuterAlt(_localctx, 5);
{
setState(48);
match(SELECT);
setState(49);
consumerOffsetStatement();
}
break;
case 6:
enterOuterAlt(_localctx, 6);
{
setState(50);
match(SELECT);
setState(51);
querySpecification();
}
break;
case 7:
enterOuterAlt(_localctx, 7);
{
setState(52);
match(SELECT);
setState(53);
countStatement();
}
break;
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class TopicStatementContext extends ParserRuleContext {
public TerminalNode TOPICS() { return getToken(KafkaSqlParser.TOPICS, 0); }
public TopicStatementContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_topicStatement; }
}
public final TopicStatementContext topicStatement() throws RecognitionException {
TopicStatementContext _localctx = new TopicStatementContext(_ctx, getState());
enterRule(_localctx, 2, RULE_topicStatement);
try {
enterOuterAlt(_localctx, 1);
{
setState(56);
match(TOPICS);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class OffsetStatementContext extends ParserRuleContext {
public TerminalNode OFFSETS() { return getToken(KafkaSqlParser.OFFSETS, 0); }
public TerminalNode ID() { return getToken(KafkaSqlParser.ID, 0); }
public List<TerminalNode> NUMBER() { return getTokens(KafkaSqlParser.NUMBER); }
public TerminalNode NUMBER(int i) {
return getToken(KafkaSqlParser.NUMBER, i);
}
public List<TerminalNode> SPACE() { return getTokens(KafkaSqlParser.SPACE); }
public TerminalNode SPACE(int i) {
return getToken(KafkaSqlParser.SPACE, i);
}
public OffsetStatementContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_offsetStatement; }
}
public final OffsetStatementContext offsetStatement() throws RecognitionException {
OffsetStatementContext _localctx = new OffsetStatementContext(_ctx, getState());
enterRule(_localctx, 4, RULE_offsetStatement);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(58);
match(OFFSETS);
setState(59);
match(T__0);
setState(60);
match(ID);
setState(76);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==T__1) {
{
setState(61);
match(T__1);
setState(62);
match(NUMBER);
setState(73);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==T__2) {
{
{
setState(63);
match(T__2);
setState(67);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==SPACE) {
{
{
setState(64);
match(SPACE);
}
}
setState(69);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(70);
match(NUMBER);
}
}
setState(75);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
setState(78);
match(T__3);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class PartitionsStatementContext extends ParserRuleContext {
public TerminalNode PARTITIONS() { return getToken(KafkaSqlParser.PARTITIONS, 0); }
public TerminalNode ID() { return getToken(KafkaSqlParser.ID, 0); }
public PartitionsStatementContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_partitionsStatement; }
}
public final PartitionsStatementContext partitionsStatement() throws RecognitionException {
PartitionsStatementContext _localctx = new PartitionsStatementContext(_ctx, getState());
enterRule(_localctx, 6, RULE_partitionsStatement);
try {
enterOuterAlt(_localctx, 1);
{
setState(80);
match(PARTITIONS);
setState(81);
match(T__0);
setState(82);
match(ID);
setState(83);
match(T__3);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ConsumersStatementContext extends ParserRuleContext {
public TerminalNode CONSUMERS() { return getToken(KafkaSqlParser.CONSUMERS, 0); }
public TerminalNode STAR() { return getToken(KafkaSqlParser.STAR, 0); }
public TerminalNode ID() { return getToken(KafkaSqlParser.ID, 0); }
public ConsumersStatementContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_consumersStatement; }
}
public final ConsumersStatementContext consumersStatement() throws RecognitionException {
ConsumersStatementContext _localctx = new ConsumersStatementContext(_ctx, getState());
enterRule(_localctx, 8, RULE_consumersStatement);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(85);
match(CONSUMERS);
setState(86);
match(T__0);
setState(87);
_la = _input.LA(1);
if ( !(_la==STAR || _la==ID) ) {
_errHandler.recoverInline(this);
}
else {
if ( _input.LA(1)==Token.EOF ) matchedEOF = true;
_errHandler.reportMatch(this);
consume();
}
setState(88);
match(T__3);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ConsumerOffsetStatementContext extends ParserRuleContext {
public TerminalNode CONSUMER_OFFSET() { return getToken(KafkaSqlParser.CONSUMER_OFFSET, 0); }
public TerminalNode ID() { return getToken(KafkaSqlParser.ID, 0); }
public ConsumerOffsetStatementContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_consumerOffsetStatement; }
}
public final ConsumerOffsetStatementContext consumerOffsetStatement() throws RecognitionException {
ConsumerOffsetStatementContext _localctx = new ConsumerOffsetStatementContext(_ctx, getState());
enterRule(_localctx, 10, RULE_consumerOffsetStatement);
try {
enterOuterAlt(_localctx, 1);
{
setState(90);
match(CONSUMER_OFFSET);
setState(91);
match(T__0);
setState(92);
match(ID);
setState(93);
match(T__3);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class CountStatementContext extends ParserRuleContext {
public TerminalNode COUNT() { return getToken(KafkaSqlParser.COUNT, 0); }
public TerminalNode ID() { return getToken(KafkaSqlParser.ID, 0); }
public List<TerminalNode> NUMBER() { return getTokens(KafkaSqlParser.NUMBER); }
public TerminalNode NUMBER(int i) {
return getToken(KafkaSqlParser.NUMBER, i);
}
public List<TerminalNode> SPACE() { return getTokens(KafkaSqlParser.SPACE); }
public TerminalNode SPACE(int i) {
return getToken(KafkaSqlParser.SPACE, i);
}
public CountStatementContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_countStatement; }
}
public final CountStatementContext countStatement() throws RecognitionException {
CountStatementContext _localctx = new CountStatementContext(_ctx, getState());
enterRule(_localctx, 12, RULE_countStatement);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(95);
match(COUNT);
setState(96);
match(T__0);
setState(97);
match(ID);
setState(113);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==T__1) {
{
setState(98);
match(T__1);
setState(99);
match(NUMBER);
setState(110);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==T__2) {
{
{
setState(100);
match(T__2);
setState(104);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==SPACE) {
{
{
setState(101);
match(SPACE);
}
}
setState(106);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(107);
match(NUMBER);
}
}
setState(112);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
setState(115);
match(T__3);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class QuerySpecificationContext extends ParserRuleContext {
public TerminalNode FROM() { return getToken(KafkaSqlParser.FROM, 0); }
public TerminalNode ID() { return getToken(KafkaSqlParser.ID, 0); }
public TerminalNode STAR() { return getToken(KafkaSqlParser.STAR, 0); }
public List<ValueContext> value() {
return getRuleContexts(ValueContext.class);
}
public ValueContext value(int i) {
return getRuleContext(ValueContext.class,i);
}
public WhereClauseContext whereClause() {
return getRuleContext(WhereClauseContext.class,0);
}
public QuerySpecificationContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_querySpecification; }
}
public final QuerySpecificationContext querySpecification() throws RecognitionException {
QuerySpecificationContext _localctx = new QuerySpecificationContext(_ctx, getState());
enterRule(_localctx, 14, RULE_querySpecification);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(126);
_errHandler.sync(this);
switch (_input.LA(1)) {
case STAR:
{
setState(117);
match(STAR);
}
break;
case BYTE:
case STR:
{
setState(118);
value();
setState(123);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==T__2) {
{
{
setState(119);
match(T__2);
setState(120);
value();
}
}
setState(125);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
break;
default:
throw new NoViableAltException(this);
}
setState(128);
match(FROM);
setState(129);
match(ID);
setState(131);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==WHERE) {
{
setState(130);
whereClause();
}
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ValueContext extends ParserRuleContext {
public ByteFunctionContext byteFunction() {
return getRuleContext(ByteFunctionContext.class,0);
}
public StrFunctionContext strFunction() {
return getRuleContext(StrFunctionContext.class,0);
}
public ValueContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_value; }
}
public final ValueContext value() throws RecognitionException {
ValueContext _localctx = new ValueContext(_ctx, getState());
enterRule(_localctx, 16, RULE_value);
try {
enterOuterAlt(_localctx, 1);
{
setState(135);
_errHandler.sync(this);
switch (_input.LA(1)) {
case BYTE:
{
setState(133);
byteFunction();
}
break;
case STR:
{
setState(134);
strFunction();
}
break;
default:
throw new NoViableAltException(this);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class WhereClauseContext extends ParserRuleContext {
public TerminalNode WHERE() { return getToken(KafkaSqlParser.WHERE, 0); }
public EquationClauseContext equationClause() {
return getRuleContext(EquationClauseContext.class,0);
}
public InCluaseContext inCluase() {
return getRuleContext(InCluaseContext.class,0);
}
public BetweenCluaseContext betweenCluase() {
return getRuleContext(BetweenCluaseContext.class,0);
}
public WhereClauseContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_whereClause; }
}
public final WhereClauseContext whereClause() throws RecognitionException {
WhereClauseContext _localctx = new WhereClauseContext(_ctx, getState());
enterRule(_localctx, 18, RULE_whereClause);
try {
enterOuterAlt(_localctx, 1);
{
setState(137);
match(WHERE);
setState(141);
_errHandler.sync(this);
switch ( getInterpreter().adaptivePredict(_input,11,_ctx) ) {
case 1:
{
setState(138);
equationClause();
}
break;
case 2:
{
setState(139);
inCluase();
}
break;
case 3:
{
setState(140);
betweenCluase();
}
break;
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class InCluaseContext extends ParserRuleContext {
public TerminalNode IN() { return getToken(KafkaSqlParser.IN, 0); }
public TerminalNode PARTITION() { return getToken(KafkaSqlParser.PARTITION, 0); }
public TerminalNode TIMESTAMP() { return getToken(KafkaSqlParser.TIMESTAMP, 0); }
public ValueContext value() {
return getRuleContext(ValueContext.class,0);
}
public List<TerminalNode> NUMBER() { return getTokens(KafkaSqlParser.NUMBER); }
public TerminalNode NUMBER(int i) {
return getToken(KafkaSqlParser.NUMBER, i);
}
public List<TerminalNode> CHARS() { return getTokens(KafkaSqlParser.CHARS); }
public TerminalNode CHARS(int i) {
return getToken(KafkaSqlParser.CHARS, i);
}
public List<TerminalNode> SPACE() { return getTokens(KafkaSqlParser.SPACE); }
public TerminalNode SPACE(int i) {
return getToken(KafkaSqlParser.SPACE, i);
}
public InCluaseContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_inCluase; }
}
public final InCluaseContext inCluase() throws RecognitionException {
InCluaseContext _localctx = new InCluaseContext(_ctx, getState());
enterRule(_localctx, 20, RULE_inCluase);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(146);
_errHandler.sync(this);
switch (_input.LA(1)) {
case PARTITION:
{
setState(143);
match(PARTITION);
}
break;
case TIMESTAMP:
{
setState(144);
match(TIMESTAMP);
}
break;
case BYTE:
case STR:
{
setState(145);
value();
}
break;
default:
throw new NoViableAltException(this);
}
setState(148);
match(IN);
setState(149);
match(T__0);
setState(178);
_errHandler.sync(this);
switch (_input.LA(1)) {
case NUMBER:
{
setState(150);
match(NUMBER);
setState(161);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==T__2) {
{
{
setState(151);
match(T__2);
setState(155);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==SPACE) {
{
{
setState(152);
match(SPACE);
}
}
setState(157);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(158);
match(NUMBER);
}
}
setState(163);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
break;
case CHARS:
{
setState(164);
match(CHARS);
setState(175);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==T__2) {
{
{
setState(165);
match(T__2);
setState(169);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==SPACE) {
{
{
setState(166);
match(SPACE);
}
}
setState(171);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(172);
match(CHARS);
}
}
setState(177);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
break;
default:
throw new NoViableAltException(this);
}
setState(180);
match(T__3);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class BetweenCluaseContext extends ParserRuleContext {
public TerminalNode BETWEEN() { return getToken(KafkaSqlParser.BETWEEN, 0); }
public List<TerminalNode> NUMBER() { return getTokens(KafkaSqlParser.NUMBER); }
public TerminalNode NUMBER(int i) {
return getToken(KafkaSqlParser.NUMBER, i);
}
public TerminalNode PARTITION() { return getToken(KafkaSqlParser.PARTITION, 0); }
public TerminalNode TIMESTAMP() { return getToken(KafkaSqlParser.TIMESTAMP, 0); }
public BetweenCluaseContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_betweenCluase; }
}
public final BetweenCluaseContext betweenCluase() throws RecognitionException {
BetweenCluaseContext _localctx = new BetweenCluaseContext(_ctx, getState());
enterRule(_localctx, 22, RULE_betweenCluase);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(182);
_la = _input.LA(1);
if ( !(_la==PARTITION || _la==TIMESTAMP) ) {
_errHandler.recoverInline(this);
}
else {
if ( _input.LA(1)==Token.EOF ) matchedEOF = true;
_errHandler.reportMatch(this);
consume();
}
setState(183);
match(BETWEEN);
setState(184);
match(T__0);
setState(185);
match(NUMBER);
setState(186);
match(T__2);
setState(187);
match(NUMBER);
setState(188);
match(T__3);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class EquationClauseContext extends ParserRuleContext {
public PartitionsEquslCluaseContext partitionsEquslCluase() {
return getRuleContext(PartitionsEquslCluaseContext.class,0);
}
public TimestampEquslCluaseContext timestampEquslCluase() {
return getRuleContext(TimestampEquslCluaseContext.class,0);
}
public ValueEqualClauseContext valueEqualClause() {
return getRuleContext(ValueEqualClauseContext.class,0);
}
public EquationClauseContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_equationClause; }
}
public final EquationClauseContext equationClause() throws RecognitionException {
EquationClauseContext _localctx = new EquationClauseContext(_ctx, getState());
enterRule(_localctx, 24, RULE_equationClause);
try {
setState(193);
_errHandler.sync(this);
switch (_input.LA(1)) {
case PARTITION:
enterOuterAlt(_localctx, 1);
{
setState(190);
partitionsEquslCluase();
}
break;
case TIMESTAMP:
enterOuterAlt(_localctx, 2);
{
setState(191);
timestampEquslCluase();
}
break;
case BYTE:
case STR:
enterOuterAlt(_localctx, 3);
{
setState(192);
valueEqualClause();
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class PartitionsEquslCluaseContext extends ParserRuleContext {
public TerminalNode PARTITION() { return getToken(KafkaSqlParser.PARTITION, 0); }
public TerminalNode EQUAL() { return getToken(KafkaSqlParser.EQUAL, 0); }
public TerminalNode NUMBER() { return getToken(KafkaSqlParser.NUMBER, 0); }
public PartitionsEquslCluaseContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_partitionsEquslCluase; }
}
public final PartitionsEquslCluaseContext partitionsEquslCluase() throws RecognitionException {
PartitionsEquslCluaseContext _localctx = new PartitionsEquslCluaseContext(_ctx, getState());
enterRule(_localctx, 26, RULE_partitionsEquslCluase);
try {
enterOuterAlt(_localctx, 1);
{
setState(195);
match(PARTITION);
setState(196);
match(EQUAL);
setState(197);
match(NUMBER);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class TimestampEquslCluaseContext extends ParserRuleContext {
public TerminalNode TIMESTAMP() { return getToken(KafkaSqlParser.TIMESTAMP, 0); }
public TerminalNode EQUAL() { return getToken(KafkaSqlParser.EQUAL, 0); }
public TerminalNode NUMBER() { return getToken(KafkaSqlParser.NUMBER, 0); }
public TimestampEquslCluaseContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_timestampEquslCluase; }
}
public final TimestampEquslCluaseContext timestampEquslCluase() throws RecognitionException {
TimestampEquslCluaseContext _localctx = new TimestampEquslCluaseContext(_ctx, getState());
enterRule(_localctx, 28, RULE_timestampEquslCluase);
try {
enterOuterAlt(_localctx, 1);
{
setState(199);
match(TIMESTAMP);
setState(200);
match(EQUAL);
setState(201);
match(NUMBER);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ValueEqualClauseContext extends ParserRuleContext {
public ValueContext value() {
return getRuleContext(ValueContext.class,0);
}
public TerminalNode EQUAL() { return getToken(KafkaSqlParser.EQUAL, 0); }
public TerminalNode CHARS() { return getToken(KafkaSqlParser.CHARS, 0); }
public TerminalNode NUMBER() { return getToken(KafkaSqlParser.NUMBER, 0); }
public ValueEqualClauseContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_valueEqualClause; }
}
public final ValueEqualClauseContext valueEqualClause() throws RecognitionException {
ValueEqualClauseContext _localctx = new ValueEqualClauseContext(_ctx, getState());
enterRule(_localctx, 30, RULE_valueEqualClause);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(203);
value();
setState(204);
match(EQUAL);
setState(205);
_la = _input.LA(1);
if ( !(_la==NUMBER || _la==CHARS) ) {
_errHandler.recoverInline(this);
}
else {
if ( _input.LA(1)==Token.EOF ) matchedEOF = true;
_errHandler.reportMatch(this);
consume();
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ByteFunctionContext extends ParserRuleContext {
public TerminalNode BYTE() { return getToken(KafkaSqlParser.BYTE, 0); }
public TerminalNode ID() { return getToken(KafkaSqlParser.ID, 0); }
public ByteFunctionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_byteFunction; }
}
public final ByteFunctionContext byteFunction() throws RecognitionException {
ByteFunctionContext _localctx = new ByteFunctionContext(_ctx, getState());
enterRule(_localctx, 32, RULE_byteFunction);
try {
enterOuterAlt(_localctx, 1);
{
setState(207);
match(BYTE);
setState(208);
match(T__0);
setState(209);
match(ID);
setState(210);
match(T__3);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class StrFunctionContext extends ParserRuleContext {
public TerminalNode STR() { return getToken(KafkaSqlParser.STR, 0); }
public TerminalNode ID() { return getToken(KafkaSqlParser.ID, 0); }
public StrFunctionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_strFunction; }
}
public final StrFunctionContext strFunction() throws RecognitionException {
StrFunctionContext _localctx = new StrFunctionContext(_ctx, getState());
enterRule(_localctx, 34, RULE_strFunction);
try {
enterOuterAlt(_localctx, 1);
{
setState(212);
match(STR);
setState(213);
match(T__0);
setState(214);
match(ID);
setState(215);
match(T__3);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class NumberListContext extends ParserRuleContext {
public List<TerminalNode> NUMBER() { return getTokens(KafkaSqlParser.NUMBER); }
public TerminalNode NUMBER(int i) {
return getToken(KafkaSqlParser.NUMBER, i);
}
public List<TerminalNode> SPACE() { return getTokens(KafkaSqlParser.SPACE); }
public TerminalNode SPACE(int i) {
return getToken(KafkaSqlParser.SPACE, i);
}
public NumberListContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_numberList; }
}
public final NumberListContext numberList() throws RecognitionException {
NumberListContext _localctx = new NumberListContext(_ctx, getState());
enterRule(_localctx, 36, RULE_numberList);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(217);
match(NUMBER);
setState(228);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==T__2) {
{
{
setState(218);
match(T__2);
setState(222);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==SPACE) {
{
{
setState(219);
match(SPACE);
}
}
setState(224);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(225);
match(NUMBER);
}
}
setState(230);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class CharsListContext extends ParserRuleContext {
public List<TerminalNode> CHARS() { return getTokens(KafkaSqlParser.CHARS); }
public TerminalNode CHARS(int i) {
return getToken(KafkaSqlParser.CHARS, i);
}
public List<TerminalNode> SPACE() { return getTokens(KafkaSqlParser.SPACE); }
public TerminalNode SPACE(int i) {
return getToken(KafkaSqlParser.SPACE, i);
}
public CharsListContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_charsList; }
}
public final CharsListContext charsList() throws RecognitionException {
CharsListContext _localctx = new CharsListContext(_ctx, getState());
enterRule(_localctx, 38, RULE_charsList);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(231);
match(CHARS);
setState(242);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==T__2) {
{
{
setState(232);
match(T__2);
setState(236);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==SPACE) {
{
{
setState(233);
match(SPACE);
}
}
setState(238);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(239);
match(CHARS);
}
}
setState(244);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static final String _serializedATN =
"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\36\u00f8\4\2\t\2"+
"\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13"+
"\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22"+
"\4\23\t\23\4\24\t\24\4\25\t\25\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2"+
"\3\2\3\2\3\2\3\2\5\29\n\2\3\3\3\3\3\4\3\4\3\4\3\4\3\4\3\4\3\4\7\4D\n\4"+
"\f\4\16\4G\13\4\3\4\7\4J\n\4\f\4\16\4M\13\4\5\4O\n\4\3\4\3\4\3\5\3\5\3"+
"\5\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3\b\3\b\3\b"+
"\3\b\3\b\7\bi\n\b\f\b\16\bl\13\b\3\b\7\bo\n\b\f\b\16\br\13\b\5\bt\n\b"+
"\3\b\3\b\3\t\3\t\3\t\3\t\7\t|\n\t\f\t\16\t\177\13\t\5\t\u0081\n\t\3\t"+
"\3\t\3\t\5\t\u0086\n\t\3\n\3\n\5\n\u008a\n\n\3\13\3\13\3\13\3\13\5\13"+
"\u0090\n\13\3\f\3\f\3\f\5\f\u0095\n\f\3\f\3\f\3\f\3\f\3\f\7\f\u009c\n"+
"\f\f\f\16\f\u009f\13\f\3\f\7\f\u00a2\n\f\f\f\16\f\u00a5\13\f\3\f\3\f\3"+
"\f\7\f\u00aa\n\f\f\f\16\f\u00ad\13\f\3\f\7\f\u00b0\n\f\f\f\16\f\u00b3"+
"\13\f\5\f\u00b5\n\f\3\f\3\f\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\16\3\16"+
"\3\16\5\16\u00c4\n\16\3\17\3\17\3\17\3\17\3\20\3\20\3\20\3\20\3\21\3\21"+
"\3\21\3\21\3\22\3\22\3\22\3\22\3\22\3\23\3\23\3\23\3\23\3\23\3\24\3\24"+
"\3\24\7\24\u00df\n\24\f\24\16\24\u00e2\13\24\3\24\7\24\u00e5\n\24\f\24"+
"\16\24\u00e8\13\24\3\25\3\25\3\25\7\25\u00ed\n\25\f\25\16\25\u00f0\13"+
"\25\3\25\7\25\u00f3\n\25\f\25\16\25\u00f6\13\25\3\25\2\2\26\2\4\6\b\n"+
"\f\16\20\22\24\26\30\32\34\36 \"$&(\2\5\4\2\30\30\33\33\3\2\r\16\3\2\35"+
"\36\2\u0102\28\3\2\2\2\4:\3\2\2\2\6<\3\2\2\2\bR\3\2\2\2\nW\3\2\2\2\f\\"+
"\3\2\2\2\16a\3\2\2\2\20\u0080\3\2\2\2\22\u0089\3\2\2\2\24\u008b\3\2\2"+
"\2\26\u0094\3\2\2\2\30\u00b8\3\2\2\2\32\u00c3\3\2\2\2\34\u00c5\3\2\2\2"+
"\36\u00c9\3\2\2\2 \u00cd\3\2\2\2\"\u00d1\3\2\2\2$\u00d6\3\2\2\2&\u00db"+
"\3\2\2\2(\u00e9\3\2\2\2*+\7\b\2\2+9\5\4\3\2,-\7\b\2\2-9\5\6\4\2./\7\b"+
"\2\2/9\5\b\5\2\60\61\7\b\2\2\619\5\n\6\2\62\63\7\b\2\2\639\5\f\7\2\64"+
"\65\7\b\2\2\659\5\20\t\2\66\67\7\b\2\2\679\5\16\b\28*\3\2\2\28,\3\2\2"+
"\28.\3\2\2\28\60\3\2\2\28\62\3\2\2\28\64\3\2\2\28\66\3\2\2\29\3\3\2\2"+
"\2:;\7\20\2\2;\5\3\2\2\2<=\7\21\2\2=>\7\3\2\2>N\7\33\2\2?@\7\4\2\2@K\7"+
"\35\2\2AE\7\5\2\2BD\7\34\2\2CB\3\2\2\2DG\3\2\2\2EC\3\2\2\2EF\3\2\2\2F"+
"H\3\2\2\2GE\3\2\2\2HJ\7\35\2\2IA\3\2\2\2JM\3\2\2\2KI\3\2\2\2KL\3\2\2\2"+
"LO\3\2\2\2MK\3\2\2\2N?\3\2\2\2NO\3\2\2\2OP\3\2\2\2PQ\7\6\2\2Q\7\3\2\2"+
"\2RS\7\22\2\2ST\7\3\2\2TU\7\33\2\2UV\7\6\2\2V\t\3\2\2\2WX\7\23\2\2XY\7"+
"\3\2\2YZ\t\2\2\2Z[\7\6\2\2[\13\3\2\2\2\\]\7\24\2\2]^\7\3\2\2^_\7\33\2"+
"\2_`\7\6\2\2`\r\3\2\2\2ab\7\25\2\2bc\7\3\2\2cs\7\33\2\2de\7\4\2\2ep\7"+
"\35\2\2fj\7\5\2\2gi\7\34\2\2hg\3\2\2\2il\3\2\2\2jh\3\2\2\2jk\3\2\2\2k"+
"m\3\2\2\2lj\3\2\2\2mo\7\35\2\2nf\3\2\2\2or\3\2\2\2pn\3\2\2\2pq\3\2\2\2"+
"qt\3\2\2\2rp\3\2\2\2sd\3\2\2\2st\3\2\2\2tu\3\2\2\2uv\7\6\2\2v\17\3\2\2"+
"\2w\u0081\7\30\2\2x}\5\22\n\2yz\7\5\2\2z|\5\22\n\2{y\3\2\2\2|\177\3\2"+
"\2\2}{\3\2\2\2}~\3\2\2\2~\u0081\3\2\2\2\177}\3\2\2\2\u0080w\3\2\2\2\u0080"+
"x\3\2\2\2\u0081\u0082\3\2\2\2\u0082\u0083\7\t\2\2\u0083\u0085\7\33\2\2"+
"\u0084\u0086\5\24\13\2\u0085\u0084\3\2\2\2\u0085\u0086\3\2\2\2\u0086\21"+
"\3\2\2\2\u0087\u008a\5\"\22\2\u0088\u008a\5$\23\2\u0089\u0087\3\2\2\2"+
"\u0089\u0088\3\2\2\2\u008a\23\3\2\2\2\u008b\u008f\7\13\2\2\u008c\u0090"+
"\5\32\16\2\u008d\u0090\5\26\f\2\u008e\u0090\5\30\r\2\u008f\u008c\3\2\2"+
"\2\u008f\u008d\3\2\2\2\u008f\u008e\3\2\2\2\u0090\25\3\2\2\2\u0091\u0095"+
"\7\r\2\2\u0092\u0095\7\16\2\2\u0093\u0095\5\22\n\2\u0094\u0091\3\2\2\2"+
"\u0094\u0092\3\2\2\2\u0094\u0093\3\2\2\2\u0095\u0096\3\2\2\2\u0096\u0097"+
"\7\n\2\2\u0097\u00b4\7\3\2\2\u0098\u00a3\7\35\2\2\u0099\u009d\7\5\2\2"+
"\u009a\u009c\7\34\2\2\u009b\u009a\3\2\2\2\u009c\u009f\3\2\2\2\u009d\u009b"+
"\3\2\2\2\u009d\u009e\3\2\2\2\u009e\u00a0\3\2\2\2\u009f\u009d\3\2\2\2\u00a0"+
"\u00a2\7\35\2\2\u00a1\u0099\3\2\2\2\u00a2\u00a5\3\2\2\2\u00a3\u00a1\3"+
"\2\2\2\u00a3\u00a4\3\2\2\2\u00a4\u00b5\3\2\2\2\u00a5\u00a3\3\2\2\2\u00a6"+
"\u00b1\7\36\2\2\u00a7\u00ab\7\5\2\2\u00a8\u00aa\7\34\2\2\u00a9\u00a8\3"+
"\2\2\2\u00aa\u00ad\3\2\2\2\u00ab\u00a9\3\2\2\2\u00ab\u00ac\3\2\2\2\u00ac"+
"\u00ae\3\2\2\2\u00ad\u00ab\3\2\2\2\u00ae\u00b0\7\36\2\2\u00af\u00a7\3"+
"\2\2\2\u00b0\u00b3\3\2\2\2\u00b1\u00af\3\2\2\2\u00b1\u00b2\3\2\2\2\u00b2"+
"\u00b5\3\2\2\2\u00b3\u00b1\3\2\2\2\u00b4\u0098\3\2\2\2\u00b4\u00a6\3\2"+
"\2\2\u00b5\u00b6\3\2\2\2\u00b6\u00b7\7\6\2\2\u00b7\27\3\2\2\2\u00b8\u00b9"+
"\t\3\2\2\u00b9\u00ba\7\f\2\2\u00ba\u00bb\7\3\2\2\u00bb\u00bc\7\35\2\2"+
"\u00bc\u00bd\7\5\2\2\u00bd\u00be\7\35\2\2\u00be\u00bf\7\6\2\2\u00bf\31"+
"\3\2\2\2\u00c0\u00c4\5\34\17\2\u00c1\u00c4\5\36\20\2\u00c2\u00c4\5 \21"+
"\2\u00c3\u00c0\3\2\2\2\u00c3\u00c1\3\2\2\2\u00c3\u00c2\3\2\2\2\u00c4\33"+
"\3\2\2\2\u00c5\u00c6\7\r\2\2\u00c6\u00c7\7\31\2\2\u00c7\u00c8\7\35\2\2"+
"\u00c8\35\3\2\2\2\u00c9\u00ca\7\16\2\2\u00ca\u00cb\7\31\2\2\u00cb\u00cc"+
"\7\35\2\2\u00cc\37\3\2\2\2\u00cd\u00ce\5\22\n\2\u00ce\u00cf\7\31\2\2\u00cf"+
"\u00d0\t\4\2\2\u00d0!\3\2\2\2\u00d1\u00d2\7\26\2\2\u00d2\u00d3\7\3\2\2"+
"\u00d3\u00d4\7\33\2\2\u00d4\u00d5\7\6\2\2\u00d5#\3\2\2\2\u00d6\u00d7\7"+
"\27\2\2\u00d7\u00d8\7\3\2\2\u00d8\u00d9\7\33\2\2\u00d9\u00da\7\6\2\2\u00da"+
"%\3\2\2\2\u00db\u00e6\7\35\2\2\u00dc\u00e0\7\5\2\2\u00dd\u00df\7\34\2"+
"\2\u00de\u00dd\3\2\2\2\u00df\u00e2\3\2\2\2\u00e0\u00de\3\2\2\2\u00e0\u00e1"+
"\3\2\2\2\u00e1\u00e3\3\2\2\2\u00e2\u00e0\3\2\2\2\u00e3\u00e5\7\35\2\2"+
"\u00e4\u00dc\3\2\2\2\u00e5\u00e8\3\2\2\2\u00e6\u00e4\3\2\2\2\u00e6\u00e7"+
"\3\2\2\2\u00e7\'\3\2\2\2\u00e8\u00e6\3\2\2\2\u00e9\u00f4\7\36\2\2\u00ea"+
"\u00ee\7\5\2\2\u00eb\u00ed\7\34\2\2\u00ec\u00eb\3\2\2\2\u00ed\u00f0\3"+
"\2\2\2\u00ee\u00ec\3\2\2\2\u00ee\u00ef\3\2\2\2\u00ef\u00f1\3\2\2\2\u00f0"+
"\u00ee\3\2\2\2\u00f1\u00f3\7\36\2\2\u00f2\u00ea\3\2\2\2\u00f3\u00f6\3"+
"\2\2\2\u00f4\u00f2\3\2\2\2\u00f4\u00f5\3\2\2\2\u00f5)\3\2\2\2\u00f6\u00f4"+
"\3\2\2\2\318EKNjps}\u0080\u0085\u0089\u008f\u0094\u009d\u00a3\u00ab\u00b1"+
"\u00b4\u00c3\u00e0\u00e6\u00ee\u00f4";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
}
|
Python
|
UTF-8
| 430 | 2.796875 | 3 |
[] |
no_license
|
import psycopg2
class DAO:
def __init__(self):
self.c = None
self.connection = None
def connect(self):
try:
self.c = psycopg2.connect\
("dbname='simple_blog' user='postgres' host='localhost' password='123456' port='5432'")
self.connection = self.c.cursor()
except Exception as error:
print("Error connecting to the Database", error)
|
Swift
|
UTF-8
| 1,197 | 3.0625 | 3 |
[] |
no_license
|
//
// Bruker.swift
// MemoFrame
//
// Created by Christopher Reyes on 22.03.2017.
// Copyright © 2017 Christopher Reyes. All rights reserved.
//
import Foundation
struct Bruker {
/*init (epost: String, alder: Int, kjonn: String, land: String, passord: String) {
self.epost = epost
self.alder = alder
self.kjonn = kjonn
self.land = land
self.passord = passord
init fungerer bare i en klasse... kan ikke bruke både init og setters getters sammen i en klasse?
}*/
private var epost: String {
get {
return self.epost
}
set {
self.epost = (newValue)
}
}
private var alder: Int
private var kjonn: String
private var land: String {
get {
return self.land
}
set {
self.land = (newValue)
}
}
private var passord: String {
get {
return self.passord
}
set {
self.passord = (newValue)
}
}
}
|
Markdown
|
UTF-8
| 2,813 | 2.515625 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: Guia de programação (LINQ to DataSet)
ms.date: 03/30/2017
ms.assetid: 977aedd7-0084-46a0-b56f-345787a55da1
ms.openlocfilehash: dc13af06cf6c439d739d76904f206ebc50ba3187
ms.sourcegitcommit: 7bc6887ab658550baa78f1520ea735838249345e
ms.translationtype: MT
ms.contentlocale: pt-BR
ms.lasthandoff: 01/03/2020
ms.locfileid: "75634801"
---
# <a name="programming-guide-linq-to-dataset"></a>Guia de programação (LINQ to DataSet)
Esta seção fornece informações conceituais e exemplos de programação com LINQ to DataSet.
## <a name="in-this-section"></a>Nesta seção
[Consultas no LINQ to DataSet](queries-in-linq-to-dataset.md)
Fornece informações sobre como escrever LINQ to DataSet consultas.
[Consultando DataSets](querying-datasets-linq-to-dataset.md)
Descreve como consultar objetos <xref:System.Data.DataSet>.
[Comparando DataRows](comparing-datarows-linq-to-dataset.md)
Descreve como usar o objeto <xref:System.Data.DataRowComparer> para comparar linhas de dados.
[Criando um DataTable de uma consulta](creating-a-datatable-from-a-query-linq-to-dataset.md)
Fornece informações sobre como criar um <xref:System.Data.DataTable> de uma consulta LINQ to DataSet usando o método <xref:System.Data.DataTableExtensions.CopyToDataTable%2A>.
[Como: implementar CopyToDataTable\<T > em que o tipo genérico T não é uma DataRow](implement-copytodatatable-where-type-not-a-datarow.md)
Descreve como implementar um método `CopyToDataTable<T>` personalizado, onde o parâmetro genérico T não é do tipo <xref:System.Data.DataRow>.
[Campo genérico e métodos de SetField](generic-field-and-setfield-methods-linq-to-dataset.md)
Fornece informações sobre os métodos genéricos <xref:System.Data.DataRowExtensions.Field%2A> e <xref:System.Data.DataRowExtensions.SetField%2A>.
[Associação de dados e LINQ to DataSet](data-binding-and-linq-to-dataset.md)
Descreve a vinculação de dados usando o objeto <xref:System.Data.DataView>.
[Depuração de consultas LINQ to DataSet](debugging-linq-to-dataset-queries.md)
Fornece informações sobre depuração e solução de problemas LINQ to DataSet consultas.
[Security](security-linq-to-dataset.md)
Descreve problemas de segurança no LINQ to DataSet.
[Exemplos de LINQ to DataSet](linq-to-dataset-examples.md)
Fornece exemplos de consulta que usam os operadores LINQ.
## <a name="reference"></a>Referência
<xref:System.Data.DataRowComparer>
<xref:System.Data.DataRowExtensions>
<xref:System.Data.DataTableExtensions>
<xref:System.Data.DataView>
## <a name="see-also"></a>Veja também
- [LINQ e ADO.NET](linq-and-ado-net.md)
- [LINQ (Consulta Integrada à Linguagem)](../../../csharp/programming-guide/concepts/linq/index.md)
|
Python
|
UTF-8
| 831 | 2.53125 | 3 |
[] |
no_license
|
import dynamixel, time
portName = "/dev/ttyUSB0"
baudRate = 9600
serial = dynamixel.SerialStream(port = portName, baudrate = baudRate, timeout = 1)
print "connect"
net = dynamixel.DynamixelNetwork(serial)
net.scan(1, 1)
myActuators = list()
pos = 0
print "Scanning for Dynamixels..."
#print net.get_dynamixels()
for dyn in net.get_dynamixels():
print dyn.id
myActuators.append(net[dyn.id])
print "...Done"
for ac in myActuators:
ac.moving_speed = 175
ac.synchronized = True
ac.torque_enable = True
ac.torque_limit = 800
ac.max_torque = 800
while (1):
for ac in myActuators:
ac.goal_position = pos
net.synchronize()
# for ac in myActuators:
# ac.read_all()
# time.sleep(0.01)
time.sleep(2)
if pos > 4095:
pos = 0
else:
pos += 511
|
Python
|
UTF-8
| 458 | 2.625 | 3 |
[] |
no_license
|
H,W=map(int,input().split())
s=[list(map(int, list(input().replace('#','1').replace('.','0')))) for _ in range(H)]
padded = [[0 for i in range(W+2)] for j in range(H+2)]
for i in range(H):
for j in range(W):
padded[i+1][j+1] = s[i][j]
for i in range(1,H+1):
for j in range(1,W+1):
if padded[i][j]==1:
if padded[i+1][j]==0 and padded[i-1][j]==0 and padded[i][j+1]==0 and padded[i][j-1]==0:
print('No')
exit()
print('Yes')
|
C#
|
UTF-8
| 10,621 | 2.515625 | 3 |
[] |
no_license
|
using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using EmaTours.DAL.Factory;
using System.Data.Entity.Validation;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using EmaTours.Entities;
using System.Data.Entity.Migrations;
namespace EmaTours.DAL.Repositories
{
public class Repository<TT> : ContainerContextFactory, IDisposable, IRepository<TT> where TT : class
{
#region Properties
/// <summary>
/// Generic Table from Context
/// </summary>
public DbSet<TT> Table { get; set; }
#endregion
#region Constractors
/// <summary>
/// Empty Constructor
/// </summary>
public Repository(EMAToursEntities Context)
{
context = Context;
Table = context.Set<TT>();
}
#endregion
#region Funcss
/// <summary>
/// Add Data
/// </summary>
/// <param name="t"> object from table</param>
/// <returns>Return Row Added</returns>
public virtual void Add(TT t)
{
try
{
//context.Set<TT>().AddOrUpdate(t);
context.Set<TT>().Add(t);
}
catch (DbEntityValidationException e)
{
}
catch (Exception ex)
{
}
}
/// <summary>
/// Detete Rows (For Tables that Haven't IsActive Column
/// </summary>
/// <param name="t"> Table object</param>
/// <returns></returns>
public virtual void Delete(TT t)
{
try
{
Table.Remove(t);
}
catch (Exception ex)
{
}
}
/// <summary>
/// Detete Rows Async(For Tables that Haven't IsActive Column
/// </summary>
/// <param name="t"> Table object</param>
/// <returns></returns>
/// <summary>
/// Return single row
/// </summary>
/// <param name="id"> table id params object for more customization </param>
/// <returns>Db Row</returns>
//public virtual TT GetById(params object[] id)
//{
// try
// {
// return Table.Find(id);
// }
// catch (Exception ex)
// {
// return null;
// }
//}
/// <summary>
/// Return single row Async
/// </summary>
/// <param name="id"> table id params object for more customization </param>
/// <returns>Db Row</returns>
///
public async Task<TT> GetByIdAsync(params object[] id)
{
try
{
return await Table.FindAsync(id);
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// Edit Table Row
/// </summary>
/// <param name="t">Table object</param>
/// <param name="excludedProperties"></param>
/// mo
/// <returns> true or false (updated or not) </returns>
public virtual void Edit(TT t)
{
try
{
context.Set<TT>().AddOrUpdate(t);
}
catch (Exception ex)
{
}
}
/// <summary>
/// Edit Table Row
/// </summary>
/// <param name="t">Table object</param>
/// <param name="excludedProperties"></param>
/// mo
/// <returns> true or false (updated or not) </returns>
public virtual void SaveExcluded(TT t, params string[] excludedProperties)
{
try
{
if (excludedProperties.Any())
{
Table.Attach(t);
context.Configuration.ValidateOnSaveEnabled = false;
foreach (var name in excludedProperties)
{
context.Entry(t).Property(name).IsModified = false;
}
var takenProp = context.Entry<TT>(t).CurrentValues.PropertyNames.Except(excludedProperties);
foreach (var name in takenProp)
{
context.Entry(t).Property(name).IsModified = true;
}
}
else
{
context.Entry<TT>(t).State = EntityState.Modified;
}
}
catch (Exception ex)
{
}
}
/// <summary>
/// Edit Table Row
/// </summary>
/// <param name="t">Table object</param>
/// <param name="included"></param>
/// mo
/// <returns> true or false (updated or not) </returns>
public virtual void SaveIncluded(TT t, params string[] included)
{
try
{
if (included.Any())
{
Table.Attach(t);
context.Configuration.ValidateOnSaveEnabled = false;
foreach (var name in included)
{
context.Entry(t).Property(name).IsModified = true;
}
var excludedProps = context.Entry<TT>(t).CurrentValues.PropertyNames.Except(included);
foreach (var name in excludedProps)
{
context.Entry(t).Property(name).IsModified = false;
}
}
else
{
context.Entry<TT>(t).State = EntityState.Modified;
}
}
catch (Exception ex)
{
}
}
/// <summary>
/// Edit Table Row Async
/// </summary>
/// <param name="t">Table object</param>mo
/// <returns> true or false (updated or not) </returns>
public async Task EditAsync(TT t)
{
try
{
context.Entry<TT>(t).State = EntityState.Modified;
}
catch (Exception ex)
{
}
}
/// <summary>
/// Get All Data with linq IQueryable
/// </summary>
/// <returns>All Data</returns>
public virtual IQueryable<TT> GetAll()
{
try
{
return Table.AsNoTracking();
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// Get All Data with linq IQueryable Async
/// </summary>
/// <returns>All Data</returns>
public async Task<IQueryable<TT>> GetAllAsync()
{
try
{
// return await Task.Run(() => Table );
var items = await Table.AsNoTracking().ToListAsync();
return items.AsQueryable();
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// Get Table Count
/// </summary>
/// <returns></returns>
public virtual int GetTableCount()
{
try
{
return Table.Count();
}
catch (Exception ex)
{
return -1;
}
}
/// <summary>
/// Get All where statment
/// </summary>
/// <param name="where"> linq statement</param>
/// <returns></returns>
public virtual IQueryable<TT> Find(Expression<Func<TT, bool>> @where)
{
return Table.AsNoTracking().Where(@where);
}
/// <summary>
/// Get All where statment Async
/// </summary>
/// <param name="where"> linq statement</param>
/// <returns></returns>
public async Task<IQueryable<TT>> FindAsync(Expression<Func<TT, bool>> where)
{
var items = await Table.Where(@where).ToListAsync();
return items.AsQueryable();
}
/// <summary>
/// Get Single Row where statment
/// </summary>
/// <param name="where"> linq statement</param>
/// <returns></returns>
public virtual TT Single(Expression<Func<TT, bool>> @where)
{
return Table.Single(where) ?? Table?.SingleOrDefault(@where); ;
}
/// <summary>
/// Get First Element of data
/// </summary>
/// <param name="where"> linq statement</param>
/// <returns></returns>
public virtual TT First(Expression<Func<TT, bool>> @where)
{
return Table?.First(@where) ?? Table?.FirstOrDefault(@where);
}
public virtual void EditRange(IEnumerable<TT> list)
{
try
{
foreach (var item in list)
{
context.Entry<TT>(item).State = EntityState.Modified;
}
}
catch (Exception ex)
{
}
}
public virtual void RemoveRange(IEnumerable<TT> list)
{
try
{
Table.RemoveRange(list);
}
catch (Exception ex)
{
}
}
public virtual void AddRange(IEnumerable<TT> list)
{
try
{
Table.AddRange(list);
}
catch (Exception ex)
{
}
}
/// <summary>
/// order , skip and take no of rows
/// </summary>
/// <param name="order"> asscending or descending</param>
/// <param name="skipRows">rows to skip</param>
/// <param name="takenRows">rows to take</param>
/// <returns></returns>
public virtual IQueryable<TT> Skip(Expression<Func<TT, bool>> order, int skipRows, int? takenRows)
{
return takenRows == null ? Table.OrderBy(order).Skip(skipRows) :
Table.OrderBy(order).Skip(skipRows).Take(takenRows.Value);
}
#endregion
#region DisopseDbObject
public new void Dispose()
{
context?.Dispose();
GC.SuppressFinalize(this);
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.