repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
VerkhovtsovPavel/BSUIR_Labs | Labs/TI/TI-2/src/keyGenerationAlgorithms/LFSR.java | 665 | package keyGenerationAlgorithms;
public class LFSR implements BaseGenerationAlgorithm{
private int[] polinome;
private int[] currentState;
public LFSR(int[] startState, int[] polinom){
this.currentState = startState;
this.polinome = polinom;
}
@Override
public int generate() {
int newBitKey = currentState[currentState.length];
shiftArray();
return newBitKey;
}
private int newBit(){
int result = 0;
for(Integer rank: polinome){
result^=currentState[rank];
}
return result;
}
private void shiftArray(){
for(int i=currentState.length;i>0; i--){
currentState[i]=currentState[i-1];
}
currentState[0]=newBit();
}
}
| mit |
halsn/mean | modules/farm.recipe/server/routes/device_server.routes.js | 756 | 'use strict';
var adminPolicy = require('../policies/device.server.policy');
var userRecipeController = require('../controllers/user.recipe.controller');
var auth = require('../../../users/server/controllers/users/users.authentication.server.controller');
module.exports = function (app) {
// http://localhost:3000/v1/recipe/5867ba3fbca57512704fa302
app.route('/v1/recipe/:recipe_id')// .all(auth.isAuthenticatedByJWT) // check the user is authenticated through jwt
.get(userRecipeController.getRecipe)
.delete(userRecipeController.removeRecipe)
.put(userRecipeController.updateRecipe);
// http://localhost:3000/v1/recipe
app.route('/v1/recipe').post(userRecipeController.createRecipe)
.get(userRecipeController.searchRecipes);
};
| mit |
jvz/atg-ant-plugin | src/main/java/atg/tools/ant/tasks/RequiredModules.java | 2837 | package atg.tools.ant.tasks;
import atg.tools.ant.types.AtgInstallation;
import atg.tools.ant.types.Module;
import atg.tools.ant.types.ModuleCollection;
import atg.tools.ant.util.StringUtils;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.Reference;
import java.util.Map;
import static atg.tools.ant.util.ModuleUtils.MODULE_NAME_EXTRACTOR;
/**
* Ant task to generate a comma-delimited list of required ATG modules for a given ModuleCollection.
*
* @author msicker
* @version 2.0
*/
public class RequiredModules
extends Task {
private AtgInstallation atg;
private ModuleCollection modules;
private String property;
/**
* Sets the root ATG installation. Not required if using a reference to a module collection.
*
* @param atg root ATG installation.
*/
public void setAtg(final AtgInstallation atg) {
this.atg = atg;
}
/**
* Sets the root ATG installation by reference. Not required if using a reference to a module
* collection.
*
* @param reference reference to root ATG installation.
*/
public void setAtg(final Reference reference) {
setAtg((AtgInstallation) reference.getReferencedObject());
}
/**
* Specifies the module list to use for building the property.
*
* @param modules list of modules to include.
*/
public void setModules(final ModuleCollection modules) {
this.modules = modules;
if (atg != null) {
modules.setAtg(atg);
}
}
/**
* Specifies the module list by reference.
*
* @param reference reference to module list.
*/
public void setModules(final Reference reference) {
setModules((ModuleCollection) reference.getReferencedObject());
}
public ModuleCollection createModules() {
if (atg == null) {
log("No ATG installation was specified for this task.", Project.MSG_ERR);
return null;
}
modules = new ModuleCollection();
modules.setProject(getProject());
modules.setAtg(atg);
return modules;
}
/**
* Specifies the project property to set with a comma-separated list of required modules using
* the configured module collection.
*
* @param property property name to set.
*/
public void setProperty(final String property) {
this.property = property;
}
@Override
public void execute()
throws BuildException {
final String moduleList = StringUtils.join(',', modules.iterator(), MODULE_NAME_EXTRACTOR);
log("Calculated module list: " + moduleList, Project.MSG_DEBUG);
getProject().setProperty(property, moduleList);
}
}
| mit |
Kondou-ger/cobrapress | cobra/generate.py | 2143 | #!/usr/bin/python3
from os import listdir
from shutil import copyfile
class generate(object):
def __init__(self, config):
self.config = config
def generate_html(self):
"""
generate static html
"""
posts = self.generate_post_html()
print(posts)
templates = self.generate_template_html()
for template in templates:
if True: # If theres a post to insert
pass# Somehow merge posts and templates here
# write template to the proper location now
templateoutput = open(self.config['htmldir'] + template[0], 'w')
templateoutput.write(template[1])
templateoutput.close()
def generate_template_html(self):
"""
generate html from templates
returns a list with lists in it - [x][0] is the filename, [x][1] is the html
"""
return [["index.html", "<html></html>"]] # dummy
def generate_post_html(self):
"""
generate html from all posts and return a list with all posts and their metadata
[x][0] is the metadata, [x][1] is the post
"""
files = listdir("posts")
del files[0]
posts = []
print(files)
for post in files:
markdownfile = open("posts/"+post, 'r')
markdowntext = markdownfile.read()
markdownfile.close()
print(markdowntext)
translated = self.translate_markdown(markdowntext)
posts.append(translated)
return posts
def translate_template(self, templatepath, templatename, params):
"""
Translate a template file to html
"""
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader(templatepath))
rendered = env.get_template(templatename).render(params)
return [templatename, rendered]
def translate_markdown(self, markdowntext):
"""
generate a post from given markdown
returns a list, [0] are the infos, [1] is the html
"""
import markdown
import re
regex = re.compile(r"^\+\+\+(.+?)\+\+\+(.+)", re.DOTALL)
matches = regex.match(markdowntext)
try:
html = markdown.markdown(matches.group(2), extensions=self.config["markdown_extensions"])
except AttributeError:
print(markdowntext + "does not look like markdown!")
exit(6)
return [matches.group(1)[1:-1], html]
| mit |
nebrius/commascript | test/tests/functions/15-function_with_switch_missing_return_path.js | 1359 | /*
The MIT License (MIT)
Copyright (c) 2013 Bryan Hughes <bryan@theoreticalideations.com> (http://theoreticalideations.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
'use commascript';
('define(function,foo)', {
returnType: 'string'
});
function foo() {
switch(0) {
case 1:
return 'hello';
case 2:
break;
default:
return 'world';
}
}
| mit |
jonas-p/go-shp | shapefile.go | 18219 | package shp
import (
"encoding/binary"
"io"
"strings"
)
//go:generate stringer -type=ShapeType
// ShapeType is a identifier for the the type of shapes.
type ShapeType int32
// These are the possible shape types.
const (
NULL ShapeType = 0
POINT ShapeType = 1
POLYLINE ShapeType = 3
POLYGON ShapeType = 5
MULTIPOINT ShapeType = 8
POINTZ ShapeType = 11
POLYLINEZ ShapeType = 13
POLYGONZ ShapeType = 15
MULTIPOINTZ ShapeType = 18
POINTM ShapeType = 21
POLYLINEM ShapeType = 23
POLYGONM ShapeType = 25
MULTIPOINTM ShapeType = 28
MULTIPATCH ShapeType = 31
)
// Box structure made up from four coordinates. This type
// is used to represent bounding boxes
type Box struct {
MinX, MinY, MaxX, MaxY float64
}
// Extend extends the box with coordinates from the provided
// box. This method calls Box.ExtendWithPoint twice with
// {MinX, MinY} and {MaxX, MaxY}
func (b *Box) Extend(box Box) {
b.ExtendWithPoint(Point{box.MinX, box.MinY})
b.ExtendWithPoint(Point{box.MaxX, box.MaxY})
}
// ExtendWithPoint extends box with coordinates from point
// if they are outside the range of the current box.
func (b *Box) ExtendWithPoint(p Point) {
if p.X < b.MinX {
b.MinX = p.X
}
if p.Y < b.MinY {
b.MinY = p.Y
}
if p.X > b.MaxX {
b.MaxX = p.X
}
if p.Y > b.MaxY {
b.MaxY = p.Y
}
}
// BBoxFromPoints returns the bounding box calculated
// from points.
func BBoxFromPoints(points []Point) (box Box) {
for k, p := range points {
if k == 0 {
box = Box{p.X, p.Y, p.X, p.Y}
} else {
box.ExtendWithPoint(p)
}
}
return
}
// Shape interface
type Shape interface {
BBox() Box
read(io.Reader)
write(io.Writer)
}
// Null is an empty shape.
type Null struct {
}
// BBox Returns an empty BBox at the geometry origin.
func (n Null) BBox() Box {
return Box{0.0, 0.0, 0.0, 0.0}
}
func (n *Null) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, n)
}
func (n *Null) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, n)
}
// Point is the shape that consists of single a geometry point.
type Point struct {
X, Y float64
}
// BBox returns the bounding box of the Point feature, i.e. an empty area at
// the point location itself.
func (p Point) BBox() Box {
return Box{p.X, p.Y, p.X, p.Y}
}
func (p *Point) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, p)
}
func (p *Point) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, p)
}
func flatten(points [][]Point) []Point {
n, i := 0, 0
for _, v := range points {
n += len(v)
}
r := make([]Point, n)
for _, v := range points {
for _, p := range v {
r[i] = p
i++
}
}
return r
}
// PolyLine is a shape type that consists of an ordered set of vertices that
// consists of one or more parts. A part is a connected sequence of two ore
// more points. Parts may or may not be connected to another and may or may not
// intersect each other.
type PolyLine struct {
Box
NumParts int32
NumPoints int32
Parts []int32
Points []Point
}
// NewPolyLine returns a pointer a new PolyLine created
// with the provided points. The inner slice should be
// the points that the parent part consists of.
func NewPolyLine(parts [][]Point) *PolyLine {
points := flatten(parts)
p := &PolyLine{}
p.NumParts = int32(len(parts))
p.NumPoints = int32(len(points))
p.Parts = make([]int32, len(parts))
var marker int32
for i, part := range parts {
p.Parts[i] = marker
marker += int32(len(part))
}
p.Points = points
p.Box = p.BBox()
return p
}
// BBox returns the bounding box of the PolyLine feature
func (p PolyLine) BBox() Box {
return BBoxFromPoints(p.Points)
}
func (p *PolyLine) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, &p.Box)
binary.Read(file, binary.LittleEndian, &p.NumParts)
binary.Read(file, binary.LittleEndian, &p.NumPoints)
p.Parts = make([]int32, p.NumParts)
p.Points = make([]Point, p.NumPoints)
binary.Read(file, binary.LittleEndian, &p.Parts)
binary.Read(file, binary.LittleEndian, &p.Points)
}
func (p *PolyLine) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, p.Box)
binary.Write(file, binary.LittleEndian, p.NumParts)
binary.Write(file, binary.LittleEndian, p.NumPoints)
binary.Write(file, binary.LittleEndian, p.Parts)
binary.Write(file, binary.LittleEndian, p.Points)
}
// Polygon is identical to the PolyLine struct. However the parts must form
// rings that may not intersect.
type Polygon PolyLine
// BBox returns the bounding box of the Polygon feature
func (p Polygon) BBox() Box {
return BBoxFromPoints(p.Points)
}
func (p *Polygon) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, &p.Box)
binary.Read(file, binary.LittleEndian, &p.NumParts)
binary.Read(file, binary.LittleEndian, &p.NumPoints)
p.Parts = make([]int32, p.NumParts)
p.Points = make([]Point, p.NumPoints)
binary.Read(file, binary.LittleEndian, &p.Parts)
binary.Read(file, binary.LittleEndian, &p.Points)
}
func (p *Polygon) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, p.Box)
binary.Write(file, binary.LittleEndian, p.NumParts)
binary.Write(file, binary.LittleEndian, p.NumPoints)
binary.Write(file, binary.LittleEndian, p.Parts)
binary.Write(file, binary.LittleEndian, p.Points)
}
// MultiPoint is the shape that consists of multiple points.
type MultiPoint struct {
Box Box
NumPoints int32
Points []Point
}
// BBox returns the bounding box of the MultiPoint feature
func (p MultiPoint) BBox() Box {
return BBoxFromPoints(p.Points)
}
func (p *MultiPoint) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, &p.Box)
binary.Read(file, binary.LittleEndian, &p.NumPoints)
p.Points = make([]Point, p.NumPoints)
binary.Read(file, binary.LittleEndian, &p.Points)
}
func (p *MultiPoint) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, p.Box)
binary.Write(file, binary.LittleEndian, p.NumPoints)
binary.Write(file, binary.LittleEndian, p.Points)
}
// PointZ is a triplet of double precision coordinates plus a measure.
type PointZ struct {
X float64
Y float64
Z float64
M float64
}
// BBox eturns the bounding box of the PointZ feature which is an zero-sized area
// at the X and Y coordinates of the feature.
func (p PointZ) BBox() Box {
return Box{p.X, p.Y, p.X, p.Y}
}
func (p *PointZ) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, p)
}
func (p *PointZ) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, p)
}
// PolyLineZ is a shape which consists of one or more parts. A part is a
// connected sequence of two or more points. Parts may or may not be connected
// and may or may not intersect one another.
type PolyLineZ struct {
Box Box
NumParts int32
NumPoints int32
Parts []int32
Points []Point
ZRange [2]float64
ZArray []float64
MRange [2]float64
MArray []float64
}
// BBox eturns the bounding box of the PolyLineZ feature.
func (p PolyLineZ) BBox() Box {
return BBoxFromPoints(p.Points)
}
func (p *PolyLineZ) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, &p.Box)
binary.Read(file, binary.LittleEndian, &p.NumParts)
binary.Read(file, binary.LittleEndian, &p.NumPoints)
p.Parts = make([]int32, p.NumParts)
p.Points = make([]Point, p.NumPoints)
p.ZArray = make([]float64, p.NumPoints)
p.MArray = make([]float64, p.NumPoints)
binary.Read(file, binary.LittleEndian, &p.Parts)
binary.Read(file, binary.LittleEndian, &p.Points)
binary.Read(file, binary.LittleEndian, &p.ZRange)
binary.Read(file, binary.LittleEndian, &p.ZArray)
binary.Read(file, binary.LittleEndian, &p.MRange)
binary.Read(file, binary.LittleEndian, &p.MArray)
}
func (p *PolyLineZ) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, p.Box)
binary.Write(file, binary.LittleEndian, p.NumParts)
binary.Write(file, binary.LittleEndian, p.NumPoints)
binary.Write(file, binary.LittleEndian, p.Parts)
binary.Write(file, binary.LittleEndian, p.Points)
binary.Write(file, binary.LittleEndian, p.ZRange)
binary.Write(file, binary.LittleEndian, p.ZArray)
binary.Write(file, binary.LittleEndian, p.MRange)
binary.Write(file, binary.LittleEndian, p.MArray)
}
// PolygonZ structure is identical to the PolyLineZ structure.
type PolygonZ PolyLineZ
// BBox returns the bounding box of the PolygonZ feature
func (p PolygonZ) BBox() Box {
return BBoxFromPoints(p.Points)
}
func (p *PolygonZ) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, &p.Box)
binary.Read(file, binary.LittleEndian, &p.NumParts)
binary.Read(file, binary.LittleEndian, &p.NumPoints)
p.Parts = make([]int32, p.NumParts)
p.Points = make([]Point, p.NumPoints)
p.ZArray = make([]float64, p.NumPoints)
p.MArray = make([]float64, p.NumPoints)
binary.Read(file, binary.LittleEndian, &p.Parts)
binary.Read(file, binary.LittleEndian, &p.Points)
binary.Read(file, binary.LittleEndian, &p.ZRange)
binary.Read(file, binary.LittleEndian, &p.ZArray)
binary.Read(file, binary.LittleEndian, &p.MRange)
binary.Read(file, binary.LittleEndian, &p.MArray)
}
func (p *PolygonZ) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, p.Box)
binary.Write(file, binary.LittleEndian, p.NumParts)
binary.Write(file, binary.LittleEndian, p.NumPoints)
binary.Write(file, binary.LittleEndian, p.Parts)
binary.Write(file, binary.LittleEndian, p.Points)
binary.Write(file, binary.LittleEndian, p.ZRange)
binary.Write(file, binary.LittleEndian, p.ZArray)
binary.Write(file, binary.LittleEndian, p.MRange)
binary.Write(file, binary.LittleEndian, p.MArray)
}
// MultiPointZ consists of one ore more PointZ.
type MultiPointZ struct {
Box Box
NumPoints int32
Points []Point
ZRange [2]float64
ZArray []float64
MRange [2]float64
MArray []float64
}
// BBox eturns the bounding box of the MultiPointZ feature.
func (p MultiPointZ) BBox() Box {
return BBoxFromPoints(p.Points)
}
func (p *MultiPointZ) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, &p.Box)
binary.Read(file, binary.LittleEndian, &p.NumPoints)
p.Points = make([]Point, p.NumPoints)
p.ZArray = make([]float64, p.NumPoints)
p.MArray = make([]float64, p.NumPoints)
binary.Read(file, binary.LittleEndian, &p.Points)
binary.Read(file, binary.LittleEndian, &p.ZRange)
binary.Read(file, binary.LittleEndian, &p.ZArray)
binary.Read(file, binary.LittleEndian, &p.MRange)
binary.Read(file, binary.LittleEndian, &p.MArray)
}
func (p *MultiPointZ) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, p.Box)
binary.Write(file, binary.LittleEndian, p.NumPoints)
binary.Write(file, binary.LittleEndian, p.Points)
binary.Write(file, binary.LittleEndian, p.ZRange)
binary.Write(file, binary.LittleEndian, p.ZArray)
binary.Write(file, binary.LittleEndian, p.MRange)
binary.Write(file, binary.LittleEndian, p.MArray)
}
// PointM is a point with a measure.
type PointM struct {
X float64
Y float64
M float64
}
// BBox returns the bounding box of the PointM feature which is a zero-sized
// area at the X- and Y-coordinates of the point.
func (p PointM) BBox() Box {
return Box{p.X, p.Y, p.X, p.Y}
}
func (p *PointM) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, p)
}
func (p *PointM) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, p)
}
// PolyLineM is the polyline in which each point also has a measure.
type PolyLineM struct {
Box Box
NumParts int32
NumPoints int32
Parts []int32
Points []Point
MRange [2]float64
MArray []float64
}
// BBox returns the bounding box of the PolyLineM feature.
func (p PolyLineM) BBox() Box {
return BBoxFromPoints(p.Points)
}
func (p *PolyLineM) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, &p.Box)
binary.Read(file, binary.LittleEndian, &p.NumParts)
binary.Read(file, binary.LittleEndian, &p.NumPoints)
p.Parts = make([]int32, p.NumParts)
p.Points = make([]Point, p.NumPoints)
p.MArray = make([]float64, p.NumPoints)
binary.Read(file, binary.LittleEndian, &p.Parts)
binary.Read(file, binary.LittleEndian, &p.Points)
binary.Read(file, binary.LittleEndian, &p.MRange)
binary.Read(file, binary.LittleEndian, &p.MArray)
}
func (p *PolyLineM) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, p.Box)
binary.Write(file, binary.LittleEndian, p.NumParts)
binary.Write(file, binary.LittleEndian, p.NumPoints)
binary.Write(file, binary.LittleEndian, p.Parts)
binary.Write(file, binary.LittleEndian, p.Points)
binary.Write(file, binary.LittleEndian, p.MRange)
binary.Write(file, binary.LittleEndian, p.MArray)
}
// PolygonM structure is identical to the PolyLineZ structure.
type PolygonM PolyLineZ
// BBox returns the bounding box of the PolygonM feature.
func (p PolygonM) BBox() Box {
return BBoxFromPoints(p.Points)
}
func (p *PolygonM) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, &p.Box)
binary.Read(file, binary.LittleEndian, &p.NumParts)
binary.Read(file, binary.LittleEndian, &p.NumPoints)
p.Parts = make([]int32, p.NumParts)
p.Points = make([]Point, p.NumPoints)
p.MArray = make([]float64, p.NumPoints)
binary.Read(file, binary.LittleEndian, &p.Parts)
binary.Read(file, binary.LittleEndian, &p.Points)
binary.Read(file, binary.LittleEndian, &p.MRange)
binary.Read(file, binary.LittleEndian, &p.MArray)
}
func (p *PolygonM) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, p.Box)
binary.Write(file, binary.LittleEndian, p.NumParts)
binary.Write(file, binary.LittleEndian, p.NumPoints)
binary.Write(file, binary.LittleEndian, p.Parts)
binary.Write(file, binary.LittleEndian, p.Points)
binary.Write(file, binary.LittleEndian, p.MRange)
binary.Write(file, binary.LittleEndian, p.MArray)
}
// MultiPointM is the collection of multiple points with measures.
type MultiPointM struct {
Box Box
NumPoints int32
Points []Point
MRange [2]float64
MArray []float64
}
// BBox eturns the bounding box of the MultiPointM feature
func (p MultiPointM) BBox() Box {
return BBoxFromPoints(p.Points)
}
func (p *MultiPointM) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, &p.Box)
binary.Read(file, binary.LittleEndian, &p.NumPoints)
p.Points = make([]Point, p.NumPoints)
p.MArray = make([]float64, p.NumPoints)
binary.Read(file, binary.LittleEndian, &p.Points)
binary.Read(file, binary.LittleEndian, &p.MRange)
binary.Read(file, binary.LittleEndian, &p.MArray)
}
func (p *MultiPointM) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, p.Box)
binary.Write(file, binary.LittleEndian, p.NumPoints)
binary.Write(file, binary.LittleEndian, p.Points)
binary.Write(file, binary.LittleEndian, p.MRange)
binary.Write(file, binary.LittleEndian, p.MArray)
}
// MultiPatch consists of a number of surfaces patches. Each surface path
// descries a surface. The surface patches of a MultiPatch are referred to as
// its parts, and the type of part controls how the order of vertices of an
// MultiPatch part is interpreted.
type MultiPatch struct {
Box Box
NumParts int32
NumPoints int32
Parts []int32
PartTypes []int32
Points []Point
ZRange [2]float64
ZArray []float64
MRange [2]float64
MArray []float64
}
// BBox returns the bounding box of the MultiPatch feature
func (p MultiPatch) BBox() Box {
return BBoxFromPoints(p.Points)
}
func (p *MultiPatch) read(file io.Reader) {
binary.Read(file, binary.LittleEndian, &p.Box)
binary.Read(file, binary.LittleEndian, &p.NumParts)
binary.Read(file, binary.LittleEndian, &p.NumPoints)
p.Parts = make([]int32, p.NumParts)
p.PartTypes = make([]int32, p.NumParts)
p.Points = make([]Point, p.NumPoints)
p.ZArray = make([]float64, p.NumPoints)
p.MArray = make([]float64, p.NumPoints)
binary.Read(file, binary.LittleEndian, &p.Parts)
binary.Read(file, binary.LittleEndian, &p.PartTypes)
binary.Read(file, binary.LittleEndian, &p.Points)
binary.Read(file, binary.LittleEndian, &p.ZRange)
binary.Read(file, binary.LittleEndian, &p.ZArray)
binary.Read(file, binary.LittleEndian, &p.MRange)
binary.Read(file, binary.LittleEndian, &p.MArray)
}
func (p *MultiPatch) write(file io.Writer) {
binary.Write(file, binary.LittleEndian, p.Box)
binary.Write(file, binary.LittleEndian, p.NumParts)
binary.Write(file, binary.LittleEndian, p.NumPoints)
binary.Write(file, binary.LittleEndian, p.Parts)
binary.Write(file, binary.LittleEndian, p.PartTypes)
binary.Write(file, binary.LittleEndian, p.Points)
binary.Write(file, binary.LittleEndian, p.ZRange)
binary.Write(file, binary.LittleEndian, p.ZArray)
binary.Write(file, binary.LittleEndian, p.MRange)
binary.Write(file, binary.LittleEndian, p.MArray)
}
// Field representation of a field object in the DBF file
type Field struct {
Name [11]byte
Fieldtype byte
Addr [4]byte // not used
Size uint8
Precision uint8
Padding [14]byte
}
// Returns a string representation of the Field. Currently
// this only returns field name.
func (f Field) String() string {
return strings.TrimRight(string(f.Name[:]), "\x00")
}
// StringField returns a Field that can be used in SetFields to initialize the
// DBF file.
func StringField(name string, length uint8) Field {
// TODO: Error checking
field := Field{Fieldtype: 'C', Size: length}
copy(field.Name[:], []byte(name))
return field
}
// NumberField returns a Field that can be used in SetFields to initialize the
// DBF file.
func NumberField(name string, length uint8) Field {
field := Field{Fieldtype: 'N', Size: length}
copy(field.Name[:], []byte(name))
return field
}
// FloatField returns a Field that can be used in SetFields to initialize the
// DBF file. Used to store floating points with precision in the DBF.
func FloatField(name string, length uint8, precision uint8) Field {
field := Field{Fieldtype: 'F', Size: length, Precision: precision}
copy(field.Name[:], []byte(name))
return field
}
// DateField feturns a Field that can be used in SetFields to initialize the
// DBF file. Used to store Date strings formatted as YYYYMMDD. Data wise this
// is the same as a StringField with length 8.
func DateField(name string) Field {
field := Field{Fieldtype: 'D', Size: 8}
copy(field.Name[:], []byte(name))
return field
}
| mit |
ozkriff/nergal | src/fs.rs | 1277 | // See LICENSE file for copyright and license details.
use std::path::{Path};
use std::io::{Cursor};
pub fn load_string<P: AsRef<Path>>(path: P) -> String {
String::from_utf8(load(path).into_inner()).unwrap()
}
#[cfg(not(target_os = "android"))]
pub fn load<P: AsRef<Path>>(path: P) -> Cursor<Vec<u8>> {
use std::fs::{File};
use std::io::{Read};
let mut buf = Vec::new();
let fullpath = &Path::new("assets").join(&path);
let mut file = match File::open(&fullpath) {
Ok(file) => file,
Err(err) => {
panic!("Can`t open file '{}' ({})", fullpath.display(), err);
},
};
match file.read_to_end(&mut buf) {
Ok(_) => Cursor::new(buf),
Err(err) => {
panic!("Can`t read file '{}' ({})", fullpath.display(), err);
},
}
}
#[cfg(target_os = "android")]
pub fn load<P: AsRef<Path>>(path: P) -> Cursor<Vec<u8>> {
use android_glue;
let filename = path.as_ref().to_str()
.expect("Can`t convert Path to &str");
match android_glue::load_asset(filename) {
Ok(buf) => Cursor::new(buf),
// TODO: more info about error
Err(_) => panic!("Can`t load asset '{}'", filename),
}
}
// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
| mit |
osoken/sqlite-tensor | doc/conf.py | 1305 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sqlite_tensor import __author__, __version__, __package_name__
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.todo',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
'sphinxcontrib.asyncio',
]
templates_path = ['_templates']
source_suffix = ['.rst', '.md']
master_doc = 'index'
project = __package_name__
copyright = '2017, ' + __author__
author = __author__
version = __version__
release = __version__
language = 'ja'
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
pygments_style = 'sphinx'
todo_include_todos = True
html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']
htmlhelp_basename = __package_name__ + 'doc'
latex_elements = {
}
latex_documents = [
(master_doc, __package_name__ + '.tex',
__package_name__ + ' Documentation',
__author__, 'manual'),
]
man_pages = [
(master_doc, __package_name__, __package_name__ + ' Documentation',
[author], 1)
]
texinfo_documents = [
(master_doc, __package_name__, __package_name__ + ' Documentation',
author, __package_name__, 'One line description of project.',
'Miscellaneous'),
]
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
epub_exclude_files = ['search.html']
| mit |
bakuzan/mylist | public/modules/core/directives/click-pass.directive.js | 478 | (function() {
'use strict';
angular.module('core')
.directive('clickPass', clickPass);
clickPass.$inject = ['$timeout'];
function clickPass($timeout) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function(event) {
$timeout(function() {
event.stopPropagation();
document.getElementById(attrs.clickPass).click();
}, 0);
});
}
};
}
})();
| mit |
AlienIdeology/J-Cord | src/main/java/org/alienideology/jcord/handle/builders/ApplicationBuilder.java | 2667 | package org.alienideology.jcord.handle.builders;
import org.alienideology.jcord.handle.Icon;
import org.alienideology.jcord.handle.client.app.IApplication;
import org.alienideology.jcord.internal.object.client.app.Application;
/**
* ApplicationBuilder - A builder for creating an {@link IApplication}. Used by {@link org.alienideology.jcord.handle.managers.IClientManager}.
*
* @author AlienIdeology
* @since 0.1.4
*/
public final class ApplicationBuilder implements Buildable<ApplicationBuilder, IApplication> {
private String name;
private Icon icon;
private String description;
public ApplicationBuilder() {
clear();
}
/**
* Build an application.
*
* @return The application built, used in {@link org.alienideology.jcord.handle.managers.IClientManager#createApplication(IApplication)}.
*/
@Override
public IApplication build() {
return new Application(null, null)
.setName(name)
.setIcon(icon == null || icon == Icon.DEFAULT_ICON ? null : (String) icon.getData())
.setDescription(description);
}
@Override
public ApplicationBuilder clear() {
name = null;
icon = null;
description = null;
return this;
}
/**
* Set the name of this application.
*
* @exception IllegalArgumentException
* If the name is not valid. See {@link IApplication#isValidName(String)}.
*
* @param name The string name.
* @return ApplicationBuilder for chaining.
*/
public ApplicationBuilder setName(String name) {
if (!IApplication.isValidName(name)) {
throw new IllegalArgumentException("Invalid application name!");
}
this.name = name;
return this;
}
/**
* Set the icon of this application.
*
* @param icon The image file.
* @return ApplicationBuilder for chaining.
*/
public ApplicationBuilder setIcon(Icon icon) {
this.icon = icon;
return this;
}
/**
* Set the description of this application.
*
* @exception IllegalArgumentException
* If the description is not valid. See {@link IApplication#isValidDescription(String)}.
*
* @param description The description.
* @return ApplicationBuilder for chaining.
*/
public ApplicationBuilder setDescription(String description) {
if (!IApplication.isValidDescription(description)) {
throw new IllegalArgumentException("Invalid application description!");
}
this.description = description;
return this;
}
}
| mit |
ActiveState/code | recipes/Python/578692_QGstartscript_Change_display/recipe-578692.py | 7501 | # -*- coding: utf-8; -*-
''' CoordsConf: Configure QGIS coordinate display
Store this script as .qgis2/python/startup.py
Redoute, 19.10.2013 '''
from __future__ import unicode_literals, division
import qgis
QgsPoint = qgis.core.QgsPoint
CoordinateReferenceSystem = qgis.core.QgsCoordinateReferenceSystem
CoordinateTransform = qgis.core.QgsCoordinateTransform
ProjectionSelector = qgis.gui.QgsProjectionSelector
import PyQt4
qActionsContextMenu = PyQt4.QtCore.Qt.ActionsContextMenu
qAlignCenter = PyQt4.QtCore.Qt.AlignCenter
qAlignHCenter = PyQt4.QtCore.Qt.AlignHCenter
qAlignRight = PyQt4.QtCore.Qt.AlignRight
qAlignVCenter = PyQt4.QtCore.Qt.AlignVCenter
qHorizontal = PyQt4.QtCore.Qt.Horizontal
qToolButtonTextOnly = PyQt4.QtCore.Qt.ToolButtonTextOnly
settings = PyQt4.QtCore.QSettings()
Action = PyQt4.QtGui.QAction
ButtonGroup = PyQt4.QtGui.QButtonGroup
Dialog = PyQt4.QtGui.QDialog
DialogButtonBox = PyQt4.QtGui.QDialogButtonBox
GroupBox = PyQt4.QtGui.QGroupBox
Label = PyQt4.QtGui.QLabel
LineEdit = PyQt4.QtGui.QLineEdit
msgBox = PyQt4.QtGui.QMessageBox.information
PushButton = PyQt4.QtGui.QPushButton
RadioButton = PyQt4.QtGui.QRadioButton
TabWidget = PyQt4.QtGui.QTabWidget
ToolButton = PyQt4.QtGui.QToolButton
VBoxLayout = PyQt4.QtGui.QVBoxLayout
Widget = PyQt4.QtGui.QWidget
class Config(object):
# read Options
dstAuthId = settings.value('CoordsConf/dstAuthId', 'EPSG:4326')
dstCrs = CoordinateReferenceSystem(dstAuthId)
rule1 = settings.value('CoordsConf/rule1', 0, type=int)
rule2 = settings.value('CoordsConf/rule2', 0, type=int)
rule3 = settings.value('CoordsConf/rule3', 0, type=int)
rule4 = settings.value('CoordsConf/rule4', 0, type=int)
iface = qgis.utils.iface
mw = iface.mainWindow()
sb = mw.statusBar()
mc = iface.mapCanvas()
mr = mc.mapRenderer()
def makeGroup(parent, odict):
l = VBoxLayout(parent)
g = ButtonGroup(parent)
for id, label in odict.iteritems():
rb = RadioButton(label, parent)
l.addWidget(rb)
g.addButton(rb, id)
return g
# actions of coord display
class Dlg(Dialog):
def __init__(self):
super(Dialog, self).__init__(mw)
self.setWindowTitle('Configure Coords Display')
layout = VBoxLayout(self)
tabs = TabWidget(self)
tabCrs = Widget()
lTabCrs = VBoxLayout(tabCrs)
self.ps = ProjectionSelector(tabCrs)
self.ps.setSelectedAuthId(Config.dstAuthId)
lTabCrs.addWidget(self.ps)
tabs.addTab(tabCrs, '&CRS for coords display')
tabOptions = Widget()
lTabOptions = VBoxLayout(tabOptions)
g1 = GroupBox('&1) When \'on the fly\' CRS transformation is enabled and active layer CRS is available:', tabOptions)
self.o1 = makeGroup(g1,
{0: 'Show display CRS',
2: 'Show project CRS',
3: 'Show active layer CRS',
5: 'Show screen coords'})
lTabOptions.addWidget(g1)
g2 = GroupBox('&2) When \'on the fly\' CRS transformation is enabled and active layer CRS is not available:', tabOptions)
self.o2 = makeGroup(g2,
{0: 'Show display CRS',
2: 'Show project CRS',
5: 'Show screen coords'})
lTabOptions.addWidget(g2)
g3 = GroupBox('&3) When \'on the fly\' CRS transformation is disabled and active layer CRS is available:', tabOptions)
self.o3 = makeGroup(g3,
{1: 'Show display CRS, reprojected via active layer CRS',
0: 'Show display CRS, reprojected via project CRS',
4: 'Show active layer CRS',
2: 'Show project CRS',
5: 'Show screen Coords'})
lTabOptions.addWidget(g3)
g4 = GroupBox('&4) When \'on the fly\' CRS transformation is disabled and active layer CRS is not available:', tabOptions)
self.o4 = makeGroup(g4,
{0: 'Show display CRS, reprojected via project CRS',
2: 'Show project CRS',
5: 'Show screen Coords'})
lTabOptions.addWidget(g4)
lTabOptions.addStretch(1)
tabs.addTab(tabOptions, '&Options')
layout.addWidget(tabs)
bbox = DialogButtonBox(self)
bbox.setOrientation(qHorizontal)
bbox.setStandardButtons(DialogButtonBox.Ok | DialogButtonBox.Cancel)
bbox.accepted.connect(self.accept)
bbox.rejected.connect(self.reject)
layout.addWidget(bbox)
self.adjustSize() ### ???
self.ps.setSelectedAuthId(Config.dstAuthId)
self.o1.button(Config.rule1).setChecked(True)
self.o2.button(Config.rule2).setChecked(True)
self.o3.button(Config.rule3).setChecked(True)
self.o4.button(Config.rule4).setChecked(True)
dlg = Dlg()
def configure():
if dlg.exec_():
Config.dstAuthId = dlg.ps.selectedAuthId()
Config.dstCrs = CoordinateReferenceSystem(Config.dstAuthId)
settings.setValue('CoordsConf/dstAuthId', Config.dstAuthId)
Config.rule1 = dlg.o1.checkedId()
settings.setValue('CoordsConf/rule1', Config.rule1)
Config.rule2 = dlg.o2.checkedId()
settings.setValue('CoordsConf/rule2', Config.rule2)
Config.rule3 = dlg.o3.checkedId()
settings.setValue('CoordsConf/rule3', Config.rule3)
Config.rule4 = dlg.o4.checkedId()
settings.setValue('CoordsConf/rule4', Config.rule4)
# remove builtin statusbar widgetgs
# check extents view button (reduces calculations in QgisApp::showMouseCoordinate)
w = sb.findChild(object, 'mToggleExtentsViewButton')
w.setChecked(True)
sb.removeWidget(w)
sb.removeWidget(sb.findChild(object, 'mCoordsLabel'))
sb.removeWidget(sb.findChild(object, 'mCoordsEdit'))
# create new label widgets for statusbar
crsButton = ToolButton(sb)
crsButton.setToolButtonStyle(qToolButtonTextOnly)
crsButton.setMinimumWidth(20)
crsButton.setMaximumHeight(20)
crsButton.setAutoRaise(True)
crsButton.clicked.connect(configure)
sb.insertPermanentWidget(1, crsButton)
xyButton = ToolButton(sb)
xyButton.setToolButtonStyle(qToolButtonTextOnly)
xyButton.setMinimumWidth(200)
xyButton.setMaximumHeight(20)
xyButton.setAutoRaise(True)
sb.insertPermanentWidget(2, xyButton)
# bind signal
def showCoords(xy):
# Which rule is applicable?
c1 = mr.hasCrsTransformEnabled()
l = iface.activeLayer()
c2 = bool(l and l.crs())
if c1 and c2:
rule = Config.rule1
elif c1:
rule = Config.rule2
elif c2:
rule = Config.rule3
else:
rule = Config.rule4
# transform xy and get auth id according to rule
if rule == 0:
xyCrs = mr.destinationCrs()
xy = CoordinateTransform(xyCrs, Config.dstCrs).transform(xy)
authId = Config.dstAuthId
elif rule == 1:
xyCrs = iface.activeLayer().crs()
xy = CoordinateTransform(xyCrs, Config.dstCrs).transform(xy)
authId = Config.dstAuthId
elif rule == 2:
authId = mr.destinationCrs().authid()
elif rule == 3:
xyCrs = mr.destinationCrs()
layerCrs = iface.activeLayer().crs()
xy = CoordinateTransform(xyCrs, layerCrs).transform(xy)
authId = layerCrs.authid()
elif rule == 4:
authId = iface.activeLayer().crs().authid()
elif rule == 5:
xy = mc.mouseLastXY()
xy = QgsPoint(xy.x(), xy.y())
authId = 'Screen'
# label buttons
crsButton.setText(authId)
xyButton.setText(xy.toString(5))
# init
showCoords(qgis.core.QgsPoint(0, 0))
mc.xyCoordinates.connect(showCoords)
| mit |
tortus/refinerycms-alerts | spec/support/factories/refinery/alerts.rb | 290 | FactoryGirl.define do
factory :alert, :class => Refinery::Alerts::Alert do
sequence(:title) { |n| "RefineryAlert-#{n}" }
live_at { Time.zone.now }
trait :live do
live_at { Time.zone.now }
end
trait :expired do
down_at { Time.zone.now }
end
end
end
| mit |
lucionei/chamadotecnico | chamadosTecnicosFinal-app/node_modules/date-fns/startOfMonth/index.js | 1483 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = startOfMonth;
var _index = require('../toDate/index.js');
var _index2 = _interopRequireDefault(_index);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @name startOfMonth
* @category Month Helpers
* @summary Return the start of a month for the given date.
*
* @description
* Return the start of a month for the given date.
* The result will be in the local timezone.
*
* @param {Date|String|Number} date - the original date
* @param {Options} [options] - the object with options. See [Options]{@link https://date-fns.org/docs/Options}
* @param {0|1|2} [options.additionalDigits=2] - passed to `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
* @returns {Date} the start of a month
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2
*
* @example
* // The start of a month for 2 September 2014 11:55:00:
* var result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0))
* //=> Mon Sep 01 2014 00:00:00
*/
function startOfMonth(dirtyDate, dirtyOptions) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present');
}
var date = (0, _index2.default)(dirtyDate, dirtyOptions);
date.setDate(1);
date.setHours(0, 0, 0, 0);
return date;
}
module.exports = exports['default']; | mit |
LighthouseBlog/Blog | src/app/article-portal/create-article-modal/create-article-modal.component.ts | 2087 | import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { MatDialogRef } from '@angular/material';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { EditorService } from 'app/_services/editor.service';
import { SnackbarMessagingService } from '../../_services/snackbar-messaging.service';
import { CreateArticleFormService } from './create-article-form.service';
@Component({
selector: 'create-article-modal',
templateUrl: './create-article-modal.component.html',
styleUrls: ['./create-article-modal.component.scss']
})
export class CreateArticleModalComponent implements OnInit, OnDestroy {
private destroyed: Subject<boolean> = new Subject<boolean>();
createArticleForm: FormGroup;
constructor(private router: Router,
private dialogRef: MatDialogRef<CreateArticleModalComponent>,
private editorService: EditorService,
private sms: SnackbarMessagingService,
private formService: CreateArticleFormService) {}
ngOnInit() {
this.createArticleForm = this.formService.buildForm();
}
ngOnDestroy() {
this.destroyed.next();
this.destroyed.complete();
}
create(formValue: any, isFormValid: boolean) {
if (isFormValid) {
this.editorService.createArticle(formValue.title, formValue.description)
.pipe(takeUntil(this.destroyed))
.subscribe(results => {
const id = results.id;
if (!Number.isNaN(id)) {
this.dialogRef.close('closed');
this.router.navigateByUrl(`edit/${id}`);
} else {
this.sms.displayErrorMessage(`The article id generated was not a number.
The article was saved but should be deleted and redone.`);
}
}, error => this.sms.displayError(error));
}
}
}
| mit |
envicase/flip | src/Flip/InitExpressionResult.cs | 1773 | namespace Flip
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
internal class InitExpressionResult<TDelegate>
where TDelegate : class
{
public InitExpressionResult(Expression<TDelegate> expression)
{
if (expression == null)
throw new ArgumentNullException(nameof(expression));
Expression = expression;
Function = expression.Compile();
Errors = Enumerable.Empty<InitExpressionError>();
}
private InitExpressionResult(IEnumerable<InitExpressionError> errors)
{
Expression = null;
Function = null;
Errors = new ReadOnlyCollection<InitExpressionError>(
new List<InitExpressionError>(errors));
}
public bool IsSuccess => Expression != null;
public Expression<TDelegate> Expression { get; }
public TDelegate Function { get; }
public IEnumerable<InitExpressionError> Errors { get; }
public static InitExpressionResult<TDelegate> WithErrors(
IEnumerable<InitExpressionError> errors)
{
if (errors == null)
throw new ArgumentNullException(nameof(errors));
return new InitExpressionResult<TDelegate>(errors);
}
public static InitExpressionResult<TDelegate> WithError(
InitExpressionError error)
{
if (error == null)
throw new ArgumentNullException(nameof(error));
return new InitExpressionResult<TDelegate>(new[] { error });
}
}
}
| mit |
ToJans/Nancy | src/Nancy.Tests/Fakes/FakeNancyModuleWithBasePath.cs | 1241 | namespace Nancy.Tests.Fakes
{
using System;
using Nancy;
public class FakeNancyModuleWithBasePath : NancyModule
{
public FakeNancyModuleWithBasePath() : base("/fake")
{
Delete["/"] = x => {
throw new NotImplementedException();
};
Get["/route/with/some/parts"] = x => {
return "FakeNancyModuleWithBasePath";
};
Get["/should/have/conflicting/route/defined"] = x => {
return "FakeNancyModuleWithBasePath";
};
Get["/child/{value}"] = x => {
throw new NotImplementedException();
};
Get["/child/route/{value}"] = x => {
return "test";
};
Get["/"] = x => {
throw new NotImplementedException();
};
Get["/foo/{value}/bar/{capture}"] = x => {
throw new NotImplementedException();
};
Post["/"] = x => {
return "Action result";
};
Put["/"] = x => {
throw new NotImplementedException();
};
}
}
} | mit |
WindSekirun/HannamQRReader | app/src/main/java/windsekirun/hnureader/CaptureActivity.java | 2729 | package windsekirun.hnureader;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.dlazaro66.qrcodereaderview.QRCodeReaderView;
/**
* HNUReader
* Class: CaptureActivity
* Created by WindSekirun on 15. 5. 15..
*/
@SuppressWarnings("ConstantConditions")
public class CaptureActivity extends AppCompatActivity implements QRCodeReaderView.OnQRCodeReadListener {
private QRCodeReaderView qrview;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture);
if (Build.VERSION.SDK_INT >= 20) {
Window w = getWindow();
w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
w.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
w.setStatusBarColor(0xff455a64);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("QR코드 인식");
toolbar.setTitleTextColor(0xffffffff);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
qrview = (QRCodeReaderView) findViewById(R.id.qrdecoderview);
qrview.setOnQRCodeReadListener(this);
}
@Override
public void onQRCodeRead(String s, PointF[] pointFs) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(s));
startActivity(i);
finish();
}
@Override
public void cameraNotFound() {
Toast.makeText(CaptureActivity.this, "사용 가능한 카메라가 없습니다.", Toast.LENGTH_LONG).show();
}
@Override
public void QRCodeNotFoundOnCamImage() {
}
@Override
public void onResume() {
super.onResume();
qrview.getCameraManager().startPreview();
}
@Override
public void onPause() {
super.onPause();
qrview.getCameraManager().stopPreview();
}
@Override
public void onBackPressed() {
qrview.getCameraManager().stopPreview();
finish();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
} | mit |
minio/cli | help.go | 9076 | package cli
import (
"fmt"
"io"
"os"
"strings"
"text/tabwriter"
"text/template"
)
// AppHelpTemplate is the text template for the Default help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
var AppHelpTemplate = `NAME:
{{.Name}}{{if .Usage}} - {{.Usage}}{{end}}
USAGE:
{{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}}
VERSION:
{{.Version}}{{end}}{{end}}{{if .Description}}
DESCRIPTION:
{{.Description}}{{end}}{{if len .Authors}}
AUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}:
{{range $index, $author := .Authors}}{{if $index}}
{{end}}{{$author}}{{end}}{{end}}{{if .VisibleCommands}}
COMMANDS:{{range .VisibleCategories}}{{if .Name}}
{{.Name}}:{{end}}{{range .VisibleCommands}}
{{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}{{if .VisibleFlags}}
GLOBAL FLAGS:
{{range $index, $option := .VisibleFlags}}{{if $index}}
{{end}}{{$option}}{{end}}{{end}}{{if .Copyright}}
COPYRIGHT:
{{.Copyright}}{{end}}
`
// CommandHelpTemplate is the text template for the command help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
var CommandHelpTemplate = `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}}{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{if .Category}}
CATEGORY:
{{.Category}}{{end}}{{if .Description}}
DESCRIPTION:
{{.Description}}{{end}}{{if .VisibleFlags}}
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}{{end}}
`
// SubcommandHelpTemplate is the text template for the subcommand help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
var SubcommandHelpTemplate = `NAME:
{{.HelpName}} - {{if .Description}}{{.Description}}{{else}}{{.Usage}}{{end}}
USAGE:
{{.HelpName}} COMMAND{{if .VisibleFlags}} [COMMAND FLAGS | -h]{{end}} [ARGUMENTS...]
COMMANDS:
{{range .VisibleCommands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
{{end}}{{if .VisibleFlags}}
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}{{end}}
`
var helpCommand = Command{
Name: "help",
Aliases: []string{"h"},
Usage: "Shows a list of commands or help for one command",
ArgsUsage: "[command]",
Action: func(c *Context) error {
args := c.Args()
if args.Present() {
return ShowCommandHelp(c, args.First())
}
ShowAppHelp(c)
return nil
},
}
var helpSubcommand = Command{
Name: "help",
Aliases: []string{"h"},
Usage: "Shows a list of commands or help for one command",
ArgsUsage: "[command]",
Action: func(c *Context) error {
args := c.Args()
if args.Present() {
return ShowCommandHelp(c, args.First())
}
return ShowSubcommandHelp(c)
},
}
// Prints help for the App or Command
type helpPrinter func(w io.Writer, templ string, data interface{})
// Prints help for the App or Command with custom template function.
type helpPrinterCustom func(w io.Writer, templ string, data interface{}, customFunc map[string]interface{})
// HelpPrinter is a function that writes the help output. If not set a default
// is used. The function signature is:
// func(w io.Writer, templ string, data interface{})
var HelpPrinter helpPrinter = printHelp
// HelpPrinterCustom is same as HelpPrinter but
// takes a custom function for template function map.
var HelpPrinterCustom helpPrinterCustom = printHelpCustom
// VersionPrinter prints the version for the App
var VersionPrinter = printVersion
// ShowAppHelpAndExit - Prints the list of subcommands for the app and exits with exit code.
func ShowAppHelpAndExit(c *Context, exitCode int) {
ShowAppHelp(c)
os.Exit(exitCode)
}
// ShowAppHelp is an action that displays the help.
func ShowAppHelp(c *Context) (err error) {
if c.App.CustomAppHelpTemplate == "" {
HelpPrinter(c.App.Writer, AppHelpTemplate, c.App)
return
}
customAppData := func() map[string]interface{} {
if c.App.ExtraInfo == nil {
return nil
}
return map[string]interface{}{
"ExtraInfo": c.App.ExtraInfo,
}
}
HelpPrinterCustom(c.App.Writer, c.App.CustomAppHelpTemplate, c.App, customAppData())
return nil
}
// DefaultAppComplete prints the list of subcommands as the default app completion method
func DefaultAppComplete(c *Context) {
for _, command := range c.App.Commands {
if command.Hidden {
continue
}
for _, name := range command.Names() {
fmt.Fprintln(c.App.Writer, name)
}
}
}
// ShowCommandHelpAndExit - exits with code after showing help
func ShowCommandHelpAndExit(c *Context, command string, code int) {
ShowCommandHelp(c, command)
os.Exit(code)
}
// ShowCommandHelp prints help for the given command
func ShowCommandHelp(ctx *Context, command string) error {
// show the subcommand help for a command with subcommands
if command == "" {
HelpPrinter(ctx.App.Writer, SubcommandHelpTemplate, ctx.App)
return nil
}
for _, c := range ctx.App.Commands {
// If not set, set these values before printing help.
if c.Prompt == "" {
c.Prompt = defaultPrompt
}
if c.EnvVarSetCommand == "" {
c.EnvVarSetCommand = defaultEnvSetCmd
}
if c.AssignmentOperator == "" {
c.AssignmentOperator = defaultAssignmentOperator
}
if c.DisableHistory == "" {
c.DisableHistory = defaultDisableHistory
}
if c.EnableHistory == "" {
c.EnableHistory = defaultEnableHistory
}
if c.HasName(command) {
if c.CustomHelpTemplate != "" {
HelpPrinterCustom(ctx.App.Writer, c.CustomHelpTemplate, c, nil)
} else {
HelpPrinter(ctx.App.Writer, CommandHelpTemplate, c)
}
return nil
}
}
if ctx.App.CommandNotFound == nil {
return NewExitError(fmt.Sprintf("No help topic for '%v'", command), 3)
}
ctx.App.CommandNotFound(ctx, command)
return nil
}
// ShowSubcommandHelp prints help for the given subcommand
func ShowSubcommandHelp(c *Context) error {
return ShowCommandHelp(c, c.Command.Name)
}
// ShowVersion prints the version number of the App
func ShowVersion(c *Context) {
VersionPrinter(c)
}
func printVersion(c *Context) {
fmt.Fprintf(c.App.Writer, "%v version %v\n", c.App.Name, c.App.Version)
}
// ShowCompletions prints the lists of commands within a given context
func ShowCompletions(c *Context) {
a := c.App
if a != nil && a.BashComplete != nil {
a.BashComplete(c)
}
}
// ShowCommandCompletions prints the custom completions for a given command
func ShowCommandCompletions(ctx *Context, command string) {
c := ctx.App.Command(command)
if c != nil && c.BashComplete != nil {
c.BashComplete(ctx)
}
}
func printHelpCustom(out io.Writer, templ string, data interface{}, customFunc map[string]interface{}) {
funcMap := template.FuncMap{
"join": strings.Join,
}
if customFunc != nil {
for key, value := range customFunc {
funcMap[key] = value
}
}
w := tabwriter.NewWriter(out, 1, 8, 2, ' ', 0)
t := template.Must(template.New("help").Funcs(funcMap).Parse(templ))
err := t.Execute(w, data)
if err != nil {
// If the writer is closed, t.Execute will fail, and there's nothing
// we can do to recover.
if os.Getenv("CLI_TEMPLATE_ERROR_DEBUG") != "" {
fmt.Fprintf(ErrWriter, "CLI TEMPLATE ERROR: %#v\n", err)
}
return
}
w.Flush()
}
func printHelp(out io.Writer, templ string, data interface{}) {
printHelpCustom(out, templ, data, nil)
}
func checkVersion(c *Context) bool {
found := false
if VersionFlag.GetName() != "" {
eachName(VersionFlag.GetName(), func(name string) {
if c.GlobalBool(name) || c.Bool(name) {
found = true
}
})
}
return found
}
func checkHelp(c *Context) bool {
found := false
if HelpFlag.GetName() != "" {
eachName(HelpFlag.GetName(), func(name string) {
if c.GlobalBool(name) || c.Bool(name) {
found = true
}
})
}
return found
}
func checkCommandHelp(c *Context, name string) bool {
if c.Bool("h") || c.Bool("help") {
ShowCommandHelp(c, name)
return true
}
return false
}
func checkSubcommandHelp(c *Context) bool {
if c.Bool("h") || c.Bool("help") {
ShowSubcommandHelp(c)
return true
}
return false
}
func checkShellCompleteFlag(a *App, arguments []string) (bool, []string) {
if !a.EnableBashCompletion {
return false, arguments
}
pos := len(arguments) - 1
lastArg := arguments[pos]
if lastArg != "--"+BashCompletionFlag.GetName() {
return false, arguments
}
return true, arguments[:pos]
}
func checkCompletions(c *Context) bool {
if !c.shellComplete {
return false
}
if args := c.Args(); args.Present() {
name := args.First()
if cmd := c.App.Command(name); cmd != nil {
// let the command handle the completion
return false
}
}
ShowCompletions(c)
return true
}
func checkCommandCompletions(c *Context, name string) bool {
if !c.shellComplete {
return false
}
ShowCommandCompletions(c, name)
return true
}
| mit |
testdouble/testdouble.js | src/replace/module/index.browser.js | 141 | export default () => {
throw Error('Sorry, but CommonJS module replacement with td.replace() is only supported under Node.js runtimes.')
}
| mit |
stratedge/wye | tests/Unit/Binding/IsInputOutputTest.php | 1061 | <?php
namespace Tests\Unit\Binding;
use PDO;
use Stratedge\Wye\Binding;
use Stratedge\Wye\Wye;
class IsInputOutputTest extends \Tests\TestCase
{
public function testReturnsTrue()
{
$contants = [
PDO::PARAM_BOOL,
PDO::PARAM_INT,
PDO::PARAM_NULL,
PDO::PARAM_STR,
PDO::PARAM_LOB,
PDO::PARAM_STMT
];
foreach ($contants as $constant) {
$binding = new Binding(new Wye, 'truck', 'Engine', ($constant | PDO::PARAM_INPUT_OUTPUT));
$this->assertTrue($binding->isInputOutput());
}
}
public function testReturnsFalse()
{
$contants = [
PDO::PARAM_BOOL,
PDO::PARAM_INT,
PDO::PARAM_NULL,
PDO::PARAM_STR,
PDO::PARAM_LOB,
PDO::PARAM_STMT
];
foreach ($contants as $constant) {
$binding = new Binding(new Wye, 'truck', 'Engine', $constant);
$this->assertFalse($binding->isInputOutput());
}
}
}
| mit |
Dexesttp/jsbooru | public/js/search.js | 2605 | "use strict";
var Search = Vue.component("main-search", {
template: "#search-template",
props: {
itemsPerPage: {
type: Number,
default: 20,
},
},
data: function () {
return {
currentTags: "",
pos: 0,
count: 0,
images: [],
tags: [],
loaded: false,
};
},
computed: {},
methods: {
init: function () {
this.currentTags = this.$route.query.q || "";
this.pos = +(this.$route.query.s || "");
this.getItems();
},
getItems: function () {
var self = this;
this.$http
.get("image", {
params: {
s: this.pos,
l: this.itemsPerPage,
q: this.currentTags,
},
})
.then(function (response) {
self.count = response.body.count;
self.images = response.body.result.map(function (image) {
return {
id: image._id,
link: "/view/" + image._id,
thumbnail: image.thumbnail || image.url,
tags: image.tags ? image.tags.join(" ") : "",
};
});
self.tags = response.body.tags.sort(function (a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
})
.then(undefined, function (response) {
console.warn("Request failed on image list get");
});
},
selectImage: function (imageID) {
router.push("/view/" + imageID);
},
setRequest: function (request) {
this.currentTags = request.trim();
this.goTo();
},
addTag: function (tag) {
this.currentTags = (this.currentTags + " " + tag).trim();
this.goTo();
},
goTo: function () {
router.push("/search?q=" + this.currentTags);
},
},
created: function (to, from) {
this.init();
},
watch: {
"$route.query.q": function (to, from) {
if (to !== from) this.init();
},
"$route.query.s": function (to, from) {
if (to !== from) this.init();
},
},
});
| mit |
objorke/PropertyTools | Source/Examples/PropertyGrid/PropertyGridDemo/Examples/DataErrorInfoExample.cs | 3506 | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataErrorInfoExample.cs" company="PropertyTools">
// Copyright (c) 2014 PropertyTools contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace ExampleLibrary
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Markup;
using PropertyTools.DataAnnotations;
[PropertyGridExample]
public class DataErrorInfoExample : Example, System.ComponentModel.IDataErrorInfo
{
[AutoUpdateText]
[Description("Should not be empty.")]
public string Name { get; set; }
[AutoUpdateText]
[Description("Should be larger or equal to zero.")]
public int Age { get; set; }
[DependsOn(nameof(Honey))]
[Description("You cannot select both.")]
public bool CondensedMilk { get; set; }
[DependsOn(nameof(CondensedMilk))]
[Description("You cannot select both.")]
public bool Honey { get; set; }
[ItemsSourceProperty(nameof(Countries))]
[Description("Required field.")]
public string Country { get; set; }
[Category("HeaderPlacement = Above")]
[AutoUpdateText]
[Description("Should not be empty.")]
[HeaderPlacement(HeaderPlacement.Above)]
public string Name2 { get; set; }
[Description("This property contains a collection of `Item`s")]
[HeaderPlacement(HeaderPlacement.Above)]
public Collection<Item> Collection1 { get; set; } = new Collection<Item>();
[Browsable(false)]
public IEnumerable<string> Countries => new[] { "Norway", "Sweden", "Denmark", "Finland", string.Empty };
[Browsable(false)]
string System.ComponentModel.IDataErrorInfo.this[string columnName]
{
get
{
switch (columnName)
{
case nameof(Name): return string.IsNullOrEmpty(this.Name) ? "The name should be specified." : null;
case nameof(Name2): return string.IsNullOrEmpty(this.Name2) ? "The name should be specified." : null;
case nameof(Age):
{
if (this.Age > 130) return "The age is probably too large";
if (this.Age < 0) return "The age should not be less than 0.";
return null;
}
case nameof(CondensedMilk):
case nameof(Honey):
return this.CondensedMilk && this.Honey ? "You cannot have both condensed milk and honey!" : null;
case nameof(Country): return string.IsNullOrEmpty(this.Country) ? "The country should be specified." : null;
case nameof(Collection1): return this.Collection1.Count == 0 ? "The collection cannot be empty" : null;
}
return null;
}
}
[Browsable(false)]
string System.ComponentModel.IDataErrorInfo.Error
{
get
{
var o = (System.ComponentModel.IDataErrorInfo)this;
return o[nameof(this.Name)] ?? o[nameof(this.Age)] ?? o[nameof(this.Honey)] ?? o[nameof(this.Country)];
}
}
}
} | mit |
Team-LANS/lepta | src/main/java/com/teamlans/lepta/service/exceptions/LeptaServiceException.java | 335 | package com.teamlans.lepta.service.exceptions;
public class LeptaServiceException extends Exception {
public LeptaServiceException(String message) {
super(message);
}
public LeptaServiceException(Exception e) {
super(e);
}
public LeptaServiceException(String message, Exception e) {
super(message, e);
}
}
| mit |
alanc10n/py-rau | pyrau/commands.py | 2093 | import humanfriendly
from redis import StrictRedis
from six.moves import range
from tabulate import tabulate
class Command:
""" Commands to run against the specified redis instance """
def __init__(self, redis_obj=None):
if redis_obj is None:
self.redis = StrictRedis()
else:
self.redis = redis_obj
def _get_obj_details(self, obj):
""" Given debug data, extract values of interest """
return obj['serializedlength']
def delete(self, key_pattern):
""" Delete keys matching the specified pattern """
for key in self.redis.scan_iter(key_pattern):
print("Deleting key: %s" % key)
self.redis.delete(key)
def get_details(self, key_list):
""" Get debug info for specified keys """
pipe = self.redis.pipeline()
details = []
strides = range(0, len(key_list), self.batch_size)
for i in strides:
for j in key_list[i: i + self.batch_size]:
pipe.debug_object(j)
batch_dets = pipe.execute()
details.extend(map(self._get_obj_details, batch_dets))
return zip(key_list, details)
def keys(self, key_pattern, details=False, sort_by_size=False):
""" List keys matching pattern, optionally with details like size """
key_list = list(self.redis.scan_iter(key_pattern))
if details:
detailed_result = self.get_details(key_list)
if sort_by_size:
detailed_result = sorted(detailed_result, key=lambda x: x[1], reverse=True)
result = []
for r in detailed_result:
#result.append('%s : %s' % (r[0],
# humanfriendly.format_size(r[1])))
result.append((r[0].decode(), humanfriendly.format_size(r[1])))
headers = ['Name', 'Size']
else:
result = [(x.decode(),) for x in key_list]
headers = ['Name',]
print(tabulate(result, headers=headers))
#for value in result:
# print(value)
| mit |
MortalFlesh/MFCollectionsPHP | src/Immutable/IMap.php | 962 | <?php declare(strict_types=1);
namespace MF\Collection\Immutable;
interface IMap extends \MF\Collection\IMap, ICollection
{
/**
* @return IMap
*/
public static function from(array $array, bool $recursive = false);
/**
* @param callable $creator (value:mixed,key:mixed):mixed
* @return IMap
*/
public static function create(iterable $source, callable $creator);
/**
* @return IMap
*/
public function set(mixed $key, mixed $value);
/**
* @return IMap
*/
public function remove(mixed $key);
/** @return IMap */
public function clear();
/** @return IList */
public function keys();
/** @return IList */
public function values();
/**
* @param callable $callback (value:mixed,key:mixed):mixed
* @return IMap
*/
public function map(callable $callback);
/** @return \MF\Collection\Mutable\IMap */
public function asMutable();
}
| mit |
TsvetanKT/BgPeopleWebApi | BgPeopleWebApi.Services/App_Start/BundleConfig.cs | 1331 | namespace BgPeople.Services
{
using System.Web;
using System.Web.Optimization;
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
// Set EnableOptimizations to false for debugging. For more information,
// visit http://go.microsoft.com/fwlink/?LinkId=301862
BundleTable.EnableOptimizations = true;
}
}
}
| mit |
ZLima12/osu | osu.Game/Rulesets/Objects/Legacy/Osu/ConvertHitObjectParser.cs | 2727 | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osuTK;
using osu.Game.Rulesets.Objects.Types;
using System.Collections.Generic;
using osu.Game.Audio;
namespace osu.Game.Rulesets.Objects.Legacy.Osu
{
/// <summary>
/// A HitObjectParser to parse legacy osu! Beatmaps.
/// </summary>
public class ConvertHitObjectParser : Legacy.ConvertHitObjectParser
{
public ConvertHitObjectParser(double offset, int formatVersion)
: base(offset, formatVersion)
{
}
private bool forceNewCombo;
private int extraComboOffset;
protected override HitObject CreateHit(Vector2 position, bool newCombo, int comboOffset)
{
newCombo |= forceNewCombo;
comboOffset += extraComboOffset;
forceNewCombo = false;
extraComboOffset = 0;
return new ConvertHit
{
Position = position,
NewCombo = FirstObject || newCombo,
ComboOffset = comboOffset
};
}
protected override HitObject CreateSlider(Vector2 position, bool newCombo, int comboOffset, Vector2[] controlPoints, double? length, PathType pathType, int repeatCount,
List<List<HitSampleInfo>> nodeSamples)
{
newCombo |= forceNewCombo;
comboOffset += extraComboOffset;
forceNewCombo = false;
extraComboOffset = 0;
return new ConvertSlider
{
Position = position,
NewCombo = FirstObject || newCombo,
ComboOffset = comboOffset,
Path = new SliderPath(pathType, controlPoints, length),
NodeSamples = nodeSamples,
RepeatCount = repeatCount
};
}
protected override HitObject CreateSpinner(Vector2 position, bool newCombo, int comboOffset, double endTime)
{
// Convert spinners don't create the new combo themselves, but force the next non-spinner hitobject to create a new combo
// Their combo offset is still added to that next hitobject's combo index
forceNewCombo |= FormatVersion <= 8 || newCombo;
extraComboOffset += comboOffset;
return new ConvertSpinner
{
Position = position,
EndTime = endTime
};
}
protected override HitObject CreateHold(Vector2 position, bool newCombo, int comboOffset, double endTime)
{
return null;
}
}
}
| mit |
hoaaah/smdspr | console/migrations/m171016_141123_create_table_ta_periode.php | 1056 | <?php
use yii\db\Migration;
class m171016_141123_create_table_ta_periode extends Migration
{
public function safeUp()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable('{{%ta_periode}}', [
'ID_Tahun' => $this->smallInteger(6)->notNull(),
'Kd_Prov' => $this->smallInteger(4)->notNull(),
'Kd_Kab_Kota' => $this->smallInteger(4)->notNull(),
'Tahun1' => $this->smallInteger(6),
'Tahun2' => $this->smallInteger(6),
'Tahun3' => $this->smallInteger(6),
'Tahun4' => $this->smallInteger(6),
'Tahun5' => $this->smallInteger(6),
'Aktive' => $this->smallInteger(4),
], $tableOptions);
$this->addPrimaryKey('primary_key', '{{%ta_periode}}', ['ID_Tahun','Kd_Prov','Kd_Kab_Kota']);
}
public function safeDown()
{
$this->dropTable('{{%ta_periode}}');
}
}
| mit |
mattweldon/indie-ui | addon/services/indie-toaster.js | 401 | import Ember from "ember";
export default Ember.Service.extend({
message: null,
setMessage(text, type) {
if (type == undefined) {
type = 'default';
}
this.set('type', type);
this.set('message', text);
Ember.run.later(() => {
this.set('type', null);
this.set('message', null);
}, 3000);
},
getMessage() {
return this.get('message');
}
});
| mit |
table-tennis-analytics/table-tennis-api | app/controllers/v1/games_controller.rb | 442 | module V1
class GamesController < ApplicationController
def index
respond_with Game.ordered.send(params[:scope])
end
def create
respond_with Game.create(game_params), location: nil
end
def update
game.update game_params
head :no_content
end
private
def game
game ||= Game.find params[:id]
end
def game_params
params.require(:game).permit!
end
end
end | mit |
iavanish/CollegePal | CollegePal/app/src/main/java/iavanish/collegepal/DiscussionForum/DeleteDiscussion.java | 583 |
package iavanish.collegepal.DiscussionForum;
import iavanish.collegepal.CommonClasses.DataBaseWrite;
import iavanish.collegepal.CommonClasses.Student;
/**
*
* @author deependra
*/
/**
*
* Delete a discussion
*/
public class DeleteDiscussion {
public Discussion discussion;
public Student student;
private DataBaseWrite dataBaseWrite;
public DeleteDiscussion(Discussion discussion, Student student) {
this.discussion = discussion;
this.student = student;
}
public void deleteDiscussion() {
}
}
| mit |
znerol75/anime-organizer | AnimeOrganizer/Library/Settings.cs | 7212 | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace AnimeOrganizer.Library
{
class Settings
{
// Default Stats
private string DEFAULT_WORKING_DIRECTORY = Directory.GetCurrentDirectory() + @"\";
private string[] DEFAULT_FORMATS = { ".mkv", ".avi", ".flv", ".mp4" };
private string[] DEFAULT_TAGS = { "-- none --", "Finished", "Unfinished", "Complete", "Incomplete" };
private string[] ARGUMENTS_NAMES = { "name" };
private string SETTINGS_NAME = "settings.xml";
// Editable Stats
public string current_source_directory { get; set; }
public string current_destination_directory { get; set; }
public string current_source_name { get; set; }
public string current_destination_name { get; set; }
public List<string> tags { get; set; } = new List<string>();
public List<string> formats { get; set; } = new List<string>();
public List<string> formats_active { get; set; } = new List<string>();
public Dictionary<string, string> directories { get; set; } = new Dictionary<string, string>();
public char[] delimiters { get; set; } = { '-' };
public char[] ignoredChars { get; set; } = { '_' };
// XML Original
private XmlWriterSettings xmlsettings = new XmlWriterSettings();
// Script
private Dictionary<string, XMLAction> Node2Script { get; set; }
delegate void XMLAction(XmlTextReader reader, Dictionary<string, string> argumentDictionary);
public Settings()
{
Node2Script = new Dictionary<string, XMLAction>
{
["tag"] = (x, argD) => tags.Add(x.Value),
["format"] = (x, argD) => formats.Add(x.Value),
["format_active"] = (x, argD) => formats_active.Add(x.Value),
["directory"] = (x, argD) => directories.Add(argD["name"], x.Value),
["source"] = (x, argD) =>
{
if (!string.IsNullOrEmpty(x.Value))
{
current_source_name = x.Value;
current_source_directory = directories[x.Value];
}
},
["destination"] = (x, argD) =>
{
if (!string.IsNullOrEmpty(x.Value))
{
current_destination_name = x.Value;
current_destination_directory = directories[x.Value];
}
}
};
xmlsettings.Indent = true;
xmlsettings.IndentChars = ("\t");
xmlsettings.OmitXmlDeclaration = true;
}
internal void Refresh(Main main)
{
main.cmbUnsortedCrrntDir.Items.AddRange(directories.Keys.ToArray());
main.cmbSortedCrrntDir.Items.AddRange(directories.Keys.ToArray());
main.cmbUnsortedCrrntDir.SelectedItem = current_source_name;
main.cmbSortedCrrntDir.SelectedItem = current_destination_name;
main.lblSourceDirectory.Text = current_source_directory;
main.lblDestinationDirectory.Text = current_destination_directory;
}
public void Load ()
{
if (!File.Exists(DEFAULT_WORKING_DIRECTORY + "\\" + SETTINGS_NAME))
LoadDefault();
else
using (XmlTextReader reader = new XmlTextReader(SETTINGS_NAME))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
try
{
Dictionary<string, string> arguments = new Dictionary<string, string>();
string name = reader.Name;
foreach (string argument in ARGUMENTS_NAMES) arguments[argument] = reader[argument];
reader.Read();
Node2Script[name](reader, arguments);
}
catch (Exception e)
{
MessageBox.Show(reader.Name + "\n" + reader.Value + "\n" + e.ToString());
Debug.WriteLine(e);
}
}
}
}
}
public void Save ()
{
using (XmlWriter xwriter = XmlWriter.Create(SETTINGS_NAME, xmlsettings))
{
xwriter.WriteStartDocument();
xwriter.WriteStartElement("settings");
xwriter.WriteStartElement("directories");
foreach (string key in directories.Keys)
{
xwriter.WriteStartElement("directory");
xwriter.WriteAttributeString("name", key);
xwriter.WriteString(directories[key]);
xwriter.WriteEndElement();
}
xwriter.WriteEndElement();
xwriter.WriteStartElement("source");
xwriter.WriteString(current_source_name);
xwriter.WriteEndElement();
xwriter.WriteStartElement("destination");
xwriter.WriteString(current_destination_name);
xwriter.WriteEndElement();
xwriter.WriteStartElement("tags");
for (int i = 0; i < tags.Count; i++)
{
xwriter.WriteStartElement("tag");
xwriter.WriteString(tags[i]);
xwriter.WriteEndElement();
}
xwriter.WriteEndElement();
xwriter.WriteStartElement("formats");
for (int j = 0; j < formats.Count; j++)
{
xwriter.WriteStartElement("format");
xwriter.WriteString(formats[j]);
xwriter.WriteEndElement();
}
for (int k = 0; k < formats_active.Count; k++)
{
xwriter.WriteStartElement("format_active");
xwriter.WriteString(formats_active[k]);
xwriter.WriteEndElement();
}
xwriter.WriteEndElement();
xwriter.WriteEndElement();
xwriter.WriteEndDocument();
}
}
private void LoadDefault ()
{
current_source_name = "Default";
current_destination_name = "Default";
tags.AddRange(DEFAULT_TAGS);
formats_active.AddRange(DEFAULT_FORMATS);
directories.Add("Default", DEFAULT_WORKING_DIRECTORY);
Save();
}
}
}
| mit |
6bee/Remote.Linq | src/Remote.Linq/ExpressionExecution/ExpressionExecutionContext`1.cs | 1140 | // Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.
namespace Remote.Linq.ExpressionExecution
{
using Remote.Linq.Expressions;
using System.Linq;
public class ExpressionExecutionContext<TDataTranferObject> : ExpressionExecutionDecoratorBase<TDataTranferObject>
{
private readonly Expression _expression;
public ExpressionExecutionContext(ExpressionExecutionContext<TDataTranferObject> parent)
: this(parent.CheckNotNull(nameof(parent)), parent._expression)
{
}
public ExpressionExecutionContext(ExpressionExecutor<IQueryable, TDataTranferObject> parent, Expression expression)
: this((IExpressionExecutionDecorator<TDataTranferObject>)parent, expression)
{
}
internal ExpressionExecutionContext(IExpressionExecutionDecorator<TDataTranferObject> parent, Expression expression)
: base(parent)
=> _expression = expression.CheckNotNull(nameof(expression));
public TDataTranferObject Execute()
=> Execute(_expression);
}
} | mit |
InSilicoLabs/texture | lib/jats/article-meta/ArticleMeta.js | 258 | import { DocumentNode } from 'substance'
class ArticleMeta extends DocumentNode {}
ArticleMeta.type = 'article-meta'
ArticleMeta.define({
attributes: { type: 'object', default: {} },
nodes: { type: ['id'], default: [] }
})
export default ArticleMeta
| mit |
otto-torino/gino | ckeditor/plugins/print/lang/sq.js | 240 | /*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'print', 'sq', {
toolbar: 'Shtype'
} );
| mit |
nicole-a-tesla/Scrapples | app/assets/javascripts/games_show.js | 1281 | $( document ).ready(function() {
// Games page wlil auto-refresh
var $timestampDiv = $('#game-timestamp');
var gameTimestamp = $timestampDiv.attr('gameTimestamp')
var roundTimestamp = $timestampDiv.attr('roundTimestamp')
var gameId = $timestampDiv.attr('game-id')
console.log(gameTimestamp)
console.log(roundTimestamp)
var interval = 2000; // 1000 = 1 second, 3000 = 3 seconds
function checkForGameChanges() {
$.ajax({
type: 'PATCH',
url: '/games/' + gameId,
data: { },
dataType: 'json',
success: function (data) {
console.log("Success!")
console.log(data)
// Do NOT user !== here; the data types are not the same
if ((gameTimestamp != data.gameTimestamp) || (roundTimestamp != data.roundTimestamp)) {
location.reload()
}
},
complete: function (data) {
setTimeout(checkForGameChanges, interval);
}
});
}
// initial checkForGameChanges, don't remove this condition (it checks that the route is actually games#show)
if (gameTimestamp && roundTimestamp) {
setTimeout(checkForGameChanges, interval);
}
}); | mit |
GuitarmonYz/AutoKnowledge | vue_front_end/node_modules/element-ui/lib/radio-button.js | 7030 | module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(243);
/***/ },
/***/ 3:
/***/ function(module, exports) {
/* globals __VUE_SSR_CONTEXT__ */
// this module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle
module.exports = function normalizeComponent (
rawScriptExports,
compiledTemplate,
injectStyles,
scopeId,
moduleIdentifier /* server only */
) {
var esModule
var scriptExports = rawScriptExports = rawScriptExports || {}
// ES6 modules interop
var type = typeof rawScriptExports.default
if (type === 'object' || type === 'function') {
esModule = rawScriptExports
scriptExports = rawScriptExports.default
}
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (compiledTemplate) {
options.render = compiledTemplate.render
options.staticRenderFns = compiledTemplate.staticRenderFns
}
// scopedId
if (scopeId) {
options._scopeId = scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context = context || (this.$vnode && this.$vnode.ssrContext)
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = injectStyles
}
if (hook) {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
}
return {
esModule: esModule,
exports: scriptExports,
options: options
}
}
/***/ },
/***/ 243:
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _radioButton = __webpack_require__(244);
var _radioButton2 = _interopRequireDefault(_radioButton);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* istanbul ignore next */
_radioButton2.default.install = function (Vue) {
Vue.component(_radioButton2.default.name, _radioButton2.default);
};
exports.default = _radioButton2.default;
/***/ },
/***/ 244:
/***/ function(module, exports, __webpack_require__) {
var Component = __webpack_require__(3)(
/* script */
__webpack_require__(245),
/* template */
__webpack_require__(246),
/* styles */
null,
/* scopeId */
null,
/* moduleIdentifier (server only) */
null
)
module.exports = Component.exports
/***/ },
/***/ 245:
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
exports.default = {
name: 'ElRadioButton',
props: {
label: {},
disabled: Boolean,
name: String
},
computed: {
value: {
get: function get() {
return this._radioGroup.value;
},
set: function set(value) {
this._radioGroup.$emit('input', value);
}
},
_radioGroup: function _radioGroup() {
var parent = this.$parent;
while (parent) {
if (parent.$options.componentName !== 'ElRadioGroup') {
parent = parent.$parent;
} else {
return parent;
}
}
return false;
},
activeStyle: function activeStyle() {
return {
backgroundColor: this._radioGroup.fill || '',
borderColor: this._radioGroup.fill || '',
boxShadow: this._radioGroup.fill ? '-1px 0 0 0 ' + this._radioGroup.fill : '',
color: this._radioGroup.textColor || ''
};
},
size: function size() {
return this._radioGroup.size;
},
isDisabled: function isDisabled() {
return this.disabled || this._radioGroup.disabled;
}
}
};
/***/ },
/***/ 246:
/***/ function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('label', {
staticClass: "el-radio-button",
class: [
_vm.size ? 'el-radio-button--' + _vm.size : '', {
'is-active': _vm.value === _vm.label
}, {
'is-disabled': _vm.isDisabled
}
]
}, [_c('input', {
directives: [{
name: "model",
rawName: "v-model",
value: (_vm.value),
expression: "value"
}],
staticClass: "el-radio-button__orig-radio",
attrs: {
"type": "radio",
"name": _vm.name,
"disabled": _vm.isDisabled
},
domProps: {
"value": _vm.label,
"checked": _vm._q(_vm.value, _vm.label)
},
on: {
"__c": function($event) {
_vm.value = _vm.label
}
}
}), _c('span', {
staticClass: "el-radio-button__inner",
style: (_vm.value === _vm.label ? _vm.activeStyle : null)
}, [_vm._t("default"), (!_vm.$slots.default) ? [_vm._v(_vm._s(_vm.label))] : _vm._e()], 2)])
},staticRenderFns: []}
/***/ }
/******/ }); | mit |
rakeshsojitra/test | web/js/coolbaby.js | 59153 |
var $j = jQuery.noConflict();
jQuery(function ($) {
"use strict";
var iOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);
if (iOS) {
$j('body').addClass('ios');
}
})
jQuery(function ($) {
"use strict";
var usualmenu = $j("ul.sf-menu");
if (usualmenu.length != 0)
usualmenu.supersubs({
minWidth: 18,
maxWidth: 27,
extraWidth: 1
}).superfish({
delay: 0,
speed: 0,
speedOut: 0,
onBeforeShow: function () {
if ($j(this).parents("ul").length > 1) {
var w = $j(window).width();
var ul_offset = $j(this).parents("ul").offset();
var ul_width = $j(this).parents("ul").outerWidth();
ul_width = ul_width + 50;
if ((ul_offset.left + ul_width > w - (ul_width / 2)) && (ul_offset.left - ul_width > 0)) {
$j(this).addClass('offscreen_fix');
} else {
$j(this).removeClass('offscreen_fix');
}
}
;
}
})
});
jQuery(function ($) {
"use strict";
// countdown ini
if ($j("#countdown1").length > 0) {
$j('#countdown1').countdown({
until: new Date() + 100000
});
}
// customize selects
if ($j(".selectpicker").length > 0) {
$j('.selectpicker').selectpicker({});
}
});
jQuery(function ($) {
"use strict";
if ($j(".chart").length > 0) {
$j('.chart').easyPieChart({
barColor: '#c69c6d',
lineWidth: 4,
size: 93,
scaleColor: false,
easing: 'easeOutBounce',
onStep: function (from, to, percent) {
$j(this.el).find('.percent').text(Math.round(percent));
}
});
}
});
jQuery(function ($) {
"use strict";
if ($j('.video-popup').length > 0) {
$j('.video-popup').magnificPopup({
disableOn: 700,
type: 'iframe',
mainClass: 'mfp-fade',
removalDelay: 160,
preloader: false,
fixedContentPos: false
});
}
if ($j('.image-thumbnail a.gallery-group').length > 0) {
$j('.image-thumbnail a.gallery-group').magnificPopup({
type: 'image',
gallery: {
enabled: true
}
});
}
});
jQuery(function ($) {
"use strict";
$j(document).bind('cbox_open', function () {
$j('html').css({
overflow: 'hidden'
});
}).bind('cbox_closed', function () {
$j('html').css({
overflow: ''
});
});
// check if RTL mode
var colorBoxMenuPosL = ($j("body").hasClass('rtl')) ? 'none' : '0';
var colorBoxMenuPosR = ($j("body").hasClass('rtl')) ? '0' : 'none';
$j("#off-canvas-menu-toggle").colorbox({
inline: true,
opacity: 0.55,
transition: "none",
arrowKey: false,
width: "300",
height: "100%",
fixed: true,
className: 'canvas-menu',
top: 0,
right: colorBoxMenuPosR,
left: colorBoxMenuPosL,
colorBoxCartPos: 0
})
// check if RTL mode
var colorBoxCartPosL = ($j("body").hasClass('rtl')) ? '0' : 'none';
var colorBoxCartPosR = ($j("body").hasClass('rtl')) ? 'none' : '0';
$j(".open-cart").colorbox({
inline: true,
opacity: 0.55,
transition: "fade",
speed: 300,
arrowKey: false,
width: "320",
height: "100%",
fixed: true,
top: 0,
right: colorBoxCartPosR,
left: colorBoxCartPosL,
onComplete: function () {
$j("#cboxClose, #cboxOverlay").on("click", function (e) {
e.preventDefault();
$j("#drop-shopcart").find('.animated').removeClass('animated');
})
}
});
var addToCart = function (button) {
var $link = button.closest('.product-preview').find('.preview-image').clone();
var $title = button.closest('.product-preview').find('.title a').clone();
var $price = button.closest('.product-preview').find('span.price:first').clone();
var $template = $j("#liTemplate > div").clone().appendTo('#drop-shopcart .list');
$link.find("img.img-second").remove().end().appendTo('#drop-shopcart .list > div:last .image');
$title.appendTo('#drop-shopcart .list > div:last .description .product-name');
$price.appendTo('#drop-shopcart .list > div:last .description .price');
$j('#drop-shopcart .list > div:last .description .price').removeClass('new');
$j('.remove-from-cart').on("click", function () {
$j(this).closest('.item').fadeIn().remove();
if ($j("#drop-shopcart .list > div").length == 0) {
$j("#drop-shopcart .total").hide();
$j("#drop-shopcart .empty").show();
}
})
var checkAnimated = function () {
if ($j("#drop-shopcart .list > div:last").prev("li").hasClass("animated")) {
$j('#drop-shopcart .list > div:last').addClass('animated');
clearTimeout(intrvl);
}
}
var intrvl = setInterval(checkAnimated, 300);
}
$j(".add-to-cart").on("click", function (e) {
addToCart($j(this))
if (!$j("#drop-shopcart .total").is(':visible')) {
$j("#drop-shopcart .total").show();
$j("#drop-shopcart .empty").hide();
}
});
$j('.remove-from-cart').on("click", function (e) {
e.preventDefault();
$j(this).closest('.item').fadeIn().remove();
if ($j("#drop-shopcart .list > div").length == 0) {
$j("#drop-shopcart .total").hide();
$j("#drop-shopcart .empty").show();
}
})
});
jQuery(function ($) {
"use strict";
var brandsImg = $j(".brands-carousel img");
$j(".brands-carousel a").append('<div class="after"></div>');
});
jQuery(function ($) {
"use strict";
$j('.navbar-main-menu dt.item').doubleTapToGo();
});
jQuery(function ($) {
"use strict";
$j(".anim-icon").hover(
function () {
var newimg = $j(this).find('img').attr('data-hover');
var oldimg = $j(this).find('img').attr('src');
$j(this).find('img').attr('src', newimg).attr('data-hover', oldimg)
},
function () {
var newimg = $j(this).find('img').attr('data-hover');
var oldimg = $j(this).find('img').attr('src');
$j(this).find('img').attr('src', newimg).attr('data-hover', oldimg)
}
)
});
jQuery(function ($j) {
"use strict";
var windowWidth = window.innerWidth || document.documentElement.clientWidth;
if (windowWidth > 991 || $j('body').hasClass('noresponsive')) {
footerIni()
}
$j(window).resize(function () {
var windowWidthR = window.innerWidth || document.documentElement.clientWidth;
if (windowWidthR != windowWidth) {
var footerCollapsed = $j('#footer-collapsed');
if (windowWidthR > 991 || $j('body').hasClass('noresponsive')) {
if (!footerCollapsed.hasClass('ini')) {
footerIni();
} else {
var footerStartHeight = 74;
footerCollapsed.find('.collapsed-block').css({
'width': ''
});
footerCollapsed.stop().css({
'height': footerStartHeight
});
}
} else {
footerCollapsed.css({
'height': 'auto'
});
footerCollapsed.find('.collapsed-block').css({
'width': ''
});
}
windowWidth = windowWidthR;
}
});
})
function footerIni() {
"use strict";
var footerCollapsed = $j('#footer-collapsed');
var footerHeight = footerCollapsed.prop('scrollHeight'),
footerStartHeight = 74,
collapsedBlockN = footerCollapsed.find('.collapsed-block:visible').length,
collapsedBlockW = 100 / collapsedBlockN - 1 + '%',
slideSpeed = 500;
if (footerCollapsed.hasClass('no-popup')) {
footerCollapsed.css({
'height': footerStartHeight
});
footerCollapsed.find('.collapsed-block').css({
'width': ''
});
footerCollapsed.addClass('open').removeClass('closed');
footerCollapsed.find('.collapsed-block').animate({
width: collapsedBlockW
}, slideSpeed);
footerHeight = footerCollapsed.prop('scrollHeight');
setTimeout(function () {
footerHeight = footerCollapsed.prop('scrollHeight');
footerCollapsed.stop().animate({
height: footerHeight
}, slideSpeed, function () {
});
}, 0)
} else {
footerCollapsed.css({
'height': footerStartHeight
}).removeClass('open').addClass('closed ini');
footerCollapsed.find('.collapsed-block').css({
'width': ''
});
footerCollapsed.find('.link').click(function (e) {
footerCollapsed.addClass('blockHeader');
e.preventDefault();
if (footerCollapsed.hasClass('closed')) {
footerCollapsed.addClass('open').removeClass('closed');
footerCollapsed.find('.collapsed-block').animate({
width: collapsedBlockW
}, slideSpeed);
footerHeight = footerCollapsed.prop('scrollHeight');
setTimeout(function () {
footerHeight = footerCollapsed.prop('scrollHeight');
footerCollapsed.stop().animate({
height: footerHeight
}, slideSpeed, function () {
});
$j("html, body").animate({
scrollTop: $j(document).height()
}, slideSpeed);
}, slideSpeed + 200)
} else {
footerCollapsed.removeClass('open').addClass('closed');
footerCollapsed.find('.collapsed-block').each(function () {
$j(this).stop(true, false).animate({
'width': $j(this).find('.inside').prop('scrollWidth')
}, slideSpeed);
})
footerCollapsed.stop().animate({
height: footerStartHeight
}, slideSpeed, function () {
});
}
setTimeout(function () {
footerCollapsed.removeClass('blockHeader');
}, slideSpeed * 4)
})
}
}
function footerStick() {
"use strict";
var windowH = $j(window).outerHeight();
var contentH = $j('#outer').outerHeight();
if (windowH > contentH) {
$j('footer').css({
'paddingTop': windowH - contentH + 'px'
});
} else {
$j('footer').css({
'paddingTop': 0
});
}
}
function slideHoverWidth() {
"use strict";
var windowWidth = document.documentElement.clientWidth || document.body.clientWidth,
w = $j(".container").outerWidth(),
padLR = (windowWidth - w) / 2;
$j('#hover-left').css({
width: padLR,
left: -padLR
});
$j('#hover-right').css({
width: padLR + w * 2 / 3 + 1,
right: -padLR
});
}
function equalHeight(container) {
"use strict";
var currentTallest = 0,
currentRowStart = 0,
currentDiv = 0,
rowDivs = new Array(),
el,
topPosition = 0;
$j(container).each(function () {
el = $j(this);
el.height('auto');
topPosition = el.position().top;
if (currentRowStart != topPosition) {
for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
rowDivs.length = 0; // empty the array
currentRowStart = topPosition;
currentTallest = el.height();
rowDivs.push(el);
} else {
rowDivs.push(el);
currentTallest = (currentTallest < el.height()) ? (el.height()) : (currentTallest);
}
for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
});
}
function carouselProductNoSpace() {
"use strict";
var windowWidth = window.innerWidth || document.documentElement.clientWidth,
containerWidth = $j(".container").width(),
productInContainer = 5,
productInRow = Math.ceil(windowWidth * productInContainer / containerWidth),
productRowWidth = productInRow * 100 / productInContainer,
productRowLeft = (productInRow - productInContainer) * 0.5 * 100 / productInContainer;
var $showArrowMulti = false;
$j('section.content .products-nospace-outer .products-nospace .slides').each(function () {
jQuery(this).parent().parent().parent('section.content').hide();
})
$j('.products-nospace .slides').each(function () {
var $jthis = jQuery(this);
var countProduct = $jthis.find(".carousel-item").length;
$jthis.unslick();
if (countProduct > 0) {
$jthis.parent().parent().parent('section.content').show();
}
if (countProduct <= 5) {
productRowLeft = 0
}
if (!$j('body').hasClass('boxed')) {
$jthis.parent('.products-nospace').css({
width: productRowWidth + '%',
marginLeft: -productRowLeft + '%'
});
}
if (countProduct > 5) {
$showArrowMulti = true;
var cloneCount = Math.ceil((productInRow + 1) / countProduct) - 1;
var productsToClone = $jthis.children();
for (var i = 0; i < cloneCount; i++)
productsToClone.clone().prependTo($jthis);
}
if ($j('body').hasClass('responsive')) {
$jthis.slick({
dots: false,
infinite: true,
arrows: false,
speed: 300,
slidesToShow: productInRow, // important, don't change
slidesToScroll: 2,
centerMode: false,
responsive: [{
breakpoint: 992,
settings: {
slidesToShow: 4,
slidesToScroll: 4,
centerMode: false
}
}, {
breakpoint: 769,
settings: {
slidesToShow: 3,
slidesToScroll: 3,
centerMode: true
}
}, {
breakpoint: 481,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
centerMode: true
}
}, {
breakpoint: 321,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: true
}
}]
});
} else {
$jthis.slick({
dots: false,
infinite: true,
arrows: false,
speed: 300,
slidesToShow: productInRow, // important, don't change
slidesToScroll: 2,
centerMode: false,
});
}
})
if ($showArrowMulti) {
$j('#nextSlick').click(function (e) {
$j(".products-nospace .slides").slickNext();
e.preventDefault();
})
$j('#prevSlick').click(function (e) {
$j(".products-nospace .slides").slickPrev();
e.preventDefault();
})
} else {
$j('.slick-arrows').hide().prev('.subtitle.right-space').removeClass('right-space')
}
}
function carouselAccordionIni() {
"use strict";
$j('.products-widget.vertical .slides').slick({
dots: false,
infinite: true,
vertical: true,
arrows: true,
autoplay: false,
autoplaySpeed: 2000,
speed: 500,
slidesToShow: 2,
slidesToScroll: 2,
touchMove: false
});
$j('.blog-widget-small.vertical .slides').slick({
dots: false,
infinite: true,
vertical: true,
arrows: true,
autoplay: false,
autoplaySpeed: 2000,
speed: 500,
slidesToShow: 2,
slidesToScroll: 2,
touchMove: false
});
}
function horisontalAccordion() {
"use strict";
var w = $j('#mobileAccord').width(),
panelW = 35,
slideSpeed = 300,
panel = $j('#mobileAccord .accord-panel'),
panelBut = $j("#mobileAccord .vertical_title_outer"),
panelN = panel.length,
openPanelW = w - (panelN - 1) * panelW;
panelBut.unbind("click");
panelBut.click(function () {
$j('#mobileAccord').addClass('historyOpened');
if ($j(this).parent().hasClass('open')) {
$j(this).parent().removeClass('open').removeClass('historyOpen').addClass('closed').stop().animate({
width: panelW
}, slideSpeed);
} else {
$j('#mobileAccord .accord-panel').removeClass('open').removeClass('historyOpen').addClass('closed').stop().animate({
width: panelW
}, slideSpeed);
$j(this).parent().removeClass('closed').addClass('open').addClass('historyOpen').stop().animate({
width: openPanelW
}, slideSpeed);
}
});
panel.addClass('open').removeAttr("style");
carouselAccordionIni()
setTimeout(function () {
panel.removeClass('open').addClass('closed').animate({
width: panelW
}, 0);
panel.each(function () {
if ($j(this).hasClass('historyOpen')) {
$j(this).removeClass('historyOpen').removeClass('closed').addClass('open').animate({
width: openPanelW
}, 0);
}
});
if (!$j('#mobileAccord').hasClass('historyOpened')) {
$j('#mobileAccord .accord-panel:first-child').removeClass('closed').addClass('open').animate({
width: openPanelW
}, 0);
}
}, 100)
}
jQuery(function ($j) {
"use strict";
var footerExpander = $j('.expander');
footerExpander.click(function (e) {
var top = $j(this).offset().top - 50;
$j("html, body").animate({
scrollTop: top
}, 500);
});
});
jQuery(function ($j) {
"use strict";
// Android doesn't support autoplay
var video = $j('.video-autoplay');
var isAndroid = /(android)/i.test(navigator.userAgent);
if (isAndroid) {
video.hide();
}
});
jQuery(function ($j) {
"use strict";
function backgroundScroll(el, width, speed) {
el.animate({
'background-position': '-' + width + 'px'
}, speed, 'linear', function () {
el.css('background-position', '0');
backgroundScroll(el, width, speed);
});
}
var isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/);
var scrollSpeed;
if (!isSafari) {
var scrollImageWidth = 1378;
scrollSpeed = 4;
backgroundScroll($j('.no-touch .animate-bg'), scrollImageWidth, scrollSpeed * 10000);
}
});
jQuery(function ($j) {
"use strict";
var windowWidth = window.innerWidth || document.documentElement.clientWidth;
if (windowWidth < 481) {
horisontalAccordion();
} else
carouselAccordionIni();
$j(window).resize(function () {
var windowWidthR = window.innerWidth || document.documentElement.clientWidth;
if (windowWidthR != windowWidth) {
clearTimeout(window.resizeEvt);
window.resizeEvt = setTimeout(function () {
var windowWidth = window.innerWidth || document.documentElement.clientWidth,
panel = $j('#mobileAccord .accord-panel')
if (windowWidth < 481) {
horisontalAccordion();
} else {
panel.addClass('open').removeClass('close').removeClass('historyOpen').removeAttr("style");
$j('#mobileAccord').removeClass('historyOpened');
}
}, 500);
windowWidth = windowWidthR;
}
});
});
jQuery(function ($j) {
"use strict";
var duration = {
searchShow: 200,
searchHide: 200
}
$j('header .btn-search').click(function (e) {
e.preventDefault();
$j(this).fadeOut(duration.searchShow);
if (!$j("#openSearch").hasClass('open')) {
$j("#openSearch").stop(true, false).addClass('open').animate({
height: 48
}, duration.searchShow);
} else {
$j("#openSearch").stop(true, false).removeClass('open').animate({
height: 0
}, duration.searchHide);
}
})
$j('#openSearch .search-close').click(function (e) {
$j('header .btn-search').fadeIn(duration.searchHide);
$j("#openSearch").stop(true, false).removeClass('open').animate({
height: 0
}, duration.searchHide);
})
var hiddenBut = $j('header .btn-group .dropdown-toggle')
hiddenBut.click(function (e) {
e.preventDefault();
e.stopPropagation();
});
});
(function () {
"use strict";
var viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]'),
ua = navigator.userAgent,
gestureStart = function () {
viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6"
},
scaleFix = function () {
if (viewportmeta && (/iPhone|iPad/.test(ua) && !/Opera Mini/.test(ua))) {
viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0";
document.addEventListener("gesturestart", gestureStart, false)
}
};
scaleFix()
})();
jQuery(function ($j) {
"use strict";
var viewGrid = $j(".view-grid"),
viewList = $j(".view-list"),
productList = $j(".products-list");
viewGrid.click(function (e) {
viewGrid.addClass('active');
viewList.removeClass('active');
productList.removeClass("products-list-in-row").addClass("products-list-in-column");
e.preventDefault()
});
viewList.click(function (e) {
viewList.addClass('active');
viewGrid.removeClass('active');
productList.removeClass("products-list-in-column").addClass("products-list-in-row");
e.preventDefault()
})
});
jQuery(function ($j) {
"use strict";
var calculateProductsInRow = function (row) {
$j(".product-view-ajax-container.temp").each(function () {
$j(this).remove()
});
var productsInRow = 0;
$j(row).children(".product-preview-outer").each(function () {
if ($j(this).prev().length > 0) {
if ($j(this).position().top != $j(this).prev().position().top)
return false;
productsInRow++
} else
productsInRow++
});
$j(row).children(":nth-child(" + productsInRow + "n)").after('<div class="product-view-ajax-container temp"></div>')
};
$j(".products-list").each(function () {
calculateProductsInRow(this)
});
var windowWidth = window.innerWidth || document.documentElement.clientWidth;
$j(window).resize(function () {
var windowWidthR = window.innerWidth || document.documentElement.clientWidth;
if (windowWidthR != windowWidth) {
$j(".products-list").each(function () {
calculateProductsInRow(this)
})
windowWidth = windowWidthR;
}
});
});
/* MENU
jQuery(function($j) {
"use strict";
var duration = {
menuShow: 400,
menuCompactShow: 800,
menuShowShort: 700,
menuSlide: 400,
headerTransform: 400,
switcherFade: 400
},
$jheader = $j("header .navbar"),
$jwindow = $j(window),
$jbackToTop = $j("header .back-to-top"),
$jbody = $j("body"),
$jswitcher = $j(".navbar-switcher", $jheader),
$jmenu = $j(".navbar-main-menu", $jheader),
$jmenuItems = $j(".item", $jmenu),
$jmenuContainer = $j("<div id='menuScrollerWrapper'></div>"),
$jmenuScrollerOuter = $j("<div class='container' style='overflow: hidden;'></div>"),
$jmenuScroller = $j("<div style='overflow: hidden;' id='menuScroller'></div>"),
$jmenuHeight = $j("header .navbar-compact"),
menuHeightInner = $j("header .navbar-height-inner"),
menuInner = $j("header .navbar-height-inner").length,
$jmenuForSlide =
$jmenuContainer.add($jmenuHeight),
menuWidth = 0,
menuActive = false,
headerHeight = $jheader.outerHeight(),
latent = $jwindow.scrollTop() >= headerHeight,
positionHeader = false,
active = false,
activeDropHeight = false;
var reculcPosHeader = function() {
var headerCompact = false,
menuShow = false;
if (menuActive) {
menuShow = true
}
if ($jheader.hasClass("navbar-compact")) {
headerCompact = true;
$jheader.removeClass("navbar-compact");
}
headerHeight = $jheader.outerHeight();
positionHeader = 0;
if (headerCompact) {
$jheader.addClass("navbar-compact");
}
if (menuShow) $jmenuForSlide.show();
if (parseInt($jheader.css("top")) < -1) {
$jheader.animate({
top: positionHeader + "px"
}, duration.menuCompactShow, 'easeOutBack');
$jbody.animate({
'marginTop': headerHeight + "px"
}, 0);
if ($j('body').is(':hover')) {
$j('html, body').animate({
scrollTop: $jwindow.scrollTop() + headerHeight
}, 0);
}
}
};
if (latent) {
$jheader.addClass("navbar-compact").animate({
top: positionHeader + "px"
}, duration.menuCompactShow, 'easeOutBack');
$jbody.css({
'marginTop': headerHeight + "px"
});
}
$j(window).load(function() {
reculcPosHeader();
})
$jbackToTop.click(function() {
$j("html, body").animate({
scrollTop: 0
}, 400)
});
$j(window).resize(function() {
reculcPosHeader();
});
var menuTimer;
$jmenuItems.each(function() {
var $jthis = $j(this),
$jdropdown = $jthis.next("dd.item-content");
if ($jdropdown.length) {
var pos = menuWidth;
menuWidth += 100;
if ($jdropdown.hasClass('content-small')) {
$jdropdown = $j("<div style='width: 50%; float: left;' class='dropdown-small dropdown dropdown" + pos * 0.01 + "'></div>").append($jdropdown.html());
} else $jdropdown = $j("<div style='width: 50%; float: left;' class='dropdown dropdown" + pos * 0.01 + "'></div>").append($jdropdown.html());
$jmenuScroller.append($jdropdown);
$jthis.addClass("with-sub").mouseenter(function(e) {
e.preventDefault();
if (menuTimer) {
clearTimeout(menuTimer);
}
if (menuActive || menuActive === 0) {
if (menuActive !== pos) {
var posN = pos / 100;
menuActive = pos;
if (menuTimer) {
clearTimeout(menuTimer);
}
menuTimer = setTimeout(function() {
$jmenuItems.removeClass("active");
$jthis.addClass("active");
var posClass = '.dropdown' + posN;
$jmenuScroller.find('.dropdown').removeClass("active");
$jmenuScroller.find(posClass).addClass("active");
activeDropHeight = $jmenuScroller.find(posClass).height();
$jmenuScroller.css({
marginLeft: -pos + "%"
});
if ($jmenuScroller.find(posClass).hasClass('dropdown-small')) {
$j("#menuScrollerWrapper").addClass('color');
$j("#menuScrollerWrapper").stop().animate({
height: activeDropHeight
}, duration.menuShowShort, function() {
reculcPosHeader();
})
} else {
$j("#menuScrollerWrapper").removeClass('color');
$j("#menuScrollerWrapper").stop().animate({
height: activeDropHeight
}, duration.menuShow, function() {
reculcPosHeader();
})
}
}, 300);
}
} else {
if (menuTimer) {
clearTimeout(menuTimer);
}
menuTimer = setTimeout(function() {
$jmenuScroller.css({
marginLeft: -pos + "%"
});
menuActive = pos;
$jmenuItems.removeClass("active");
$jthis.addClass("active");
var posN = pos / 100;
$j("#menuScrollerWrapper").css({
display: 'block'
});
$j("#menuScrollerWrapper").css({
"height": '0'
});
var posClass = '.dropdown' + posN;
$jmenuScroller.find('.dropdown').removeClass("active");
$jmenuScroller.find(posClass).addClass("active");
activeDropHeight = $jmenuScroller.find(posClass).height();
if (activeDropHeight == 0) {
activeDropHeight = $jmenuScroller.parent().css({
display: 'block'
}).find(posClass).height();
$jmenuScroller.parent().css({
display: 'none'
});
}
if ($jmenuScroller.find(posClass).hasClass('dropdown-small')) {
$j("#menuScrollerWrapper").addClass('color')
} else $j("#menuScrollerWrapper").removeClass('color');
$j("#menuScrollerWrapper").stop(false, false).animate({
height: activeDropHeight
}, duration.menuShow, function() {
reculcPosHeader();
});
}, 300);
}
}).mouseleave(function(e) {
if (menuTimer) {
clearTimeout(menuTimer);
}
menuTimer = setTimeout(function() {
$jmenuItems.removeClass("active");
$jmenuScroller.find('.dropdown').removeClass("active");
$j("#menuScrollerWrapper").stop(false, false).animate({
height: 0
}, duration.menuShow, function() {
reculcPosHeader();
});
menuActive = false;
}, 300);
});
}
});
$jmenuScroller.mouseenter(function(e) {
if (menuTimer) {
clearTimeout(menuTimer);
}
})
.mouseleave(function(e) {
if (menuTimer) {
clearTimeout(menuTimer);
}
menuTimer = setTimeout(function() {
$jmenuItems.removeClass("active");
$j("#menuScrollerWrapper").stop().animate({
height: 0
}, duration.menuShow, function() {
reculcPosHeader();
});
menuActive = false;
}, 300);
});
$jmenuScroller.css("width", menuWidth + "%");
$jmenuScroller.children("div").css("width", 100 / (menuWidth / 100) + "%");
$j('.navbar .background').append($jmenuContainer.append($jmenuScrollerOuter.append($jmenuScroller)));
$jmenuHeight.css({
height: $jmenuContainer.height() + (menuInner ? 0 : headerHeight - 14) + "px",
display: "none"
});
$jwindow.scroll(function() {
if (!latent && $jwindow.scrollTop() >= headerHeight) {
if (!$j('#footer-collapsed').hasClass('blockHeader')) {
menuActive = false;
$jbackToTop.stop().fadeIn(300);
if ($j('html').hasClass('no-touch')) {
$jheader.addClass("navbar-compact");
reculcPosHeader();
$jheader.stop().animate({
top: positionHeader + "px"
}, duration.menuCompactShow, 'easeOutBack');
}
latent = true;
}
} else if (latent && $jwindow.scrollTop() < headerHeight) {
if ($j('html').hasClass('no-touch')) {
$jheader.stop().css("top", "").removeClass("navbar-compact");
$jbody.css("marginTop", "")
}
$jbackToTop.stop().fadeOut(300);
active = false;
latent = false;
}
});
var $jmenuClose = $j('.megamenuClose');
$jmenuClose.on("click", function(e) {
if (menuTimer) {
clearTimeout(menuTimer);
}
menuTimer = setTimeout(function() {
$jmenuItems.removeClass("active");
$j("#menuScrollerWrapper").stop().animate({
height: 0
}, duration.menuShow, function() {
reculcPosHeader();
});
menuActive = false;
}, 300);
})
}); */
jQuery(function ($j) {
"use strict";
$j(".social-widgets .item").each(function () {
var $jthis = $j(this),
timer;
$jthis.on("mouseenter", function () {
var $jthis = $j(this);
if (timer)
clearTimeout(timer);
timer = setTimeout(function () {
$jthis.addClass("active")
}, 200)
}).on("mouseleave", function () {
var $jthis = $j(this);
if (timer)
clearTimeout(timer);
timer = setTimeout(function () {
$jthis.removeClass("active")
}, 100)
}).on("click", function (e) {
e.preventDefault()
})
})
});
jQuery(function ($j) {
"use strict";
$j(".live-chat").each(function () {
var $jthis = $j(this),
timer;
$jthis.on("mouseenter", function () {
var $jthis = $j(this);
if (timer)
clearTimeout(timer);
timer = setTimeout(function () {
$jthis.addClass("active")
}, 200)
}).on("mouseleave", function () {
var $jthis = $j(this);
if (timer)
clearTimeout(timer);
timer = setTimeout(function () {
$jthis.removeClass("active")
}, 100)
}).on("click", function (e) {
e.preventDefault()
})
})
});
jQuery(function ($j) {
$j(".slider-range").each(function () {
$j(this).noUiSlider({
start: [0, 320],
connect: true,
range: {
'min': 0,
'max': 400
}
});
var lower = $j(this).find('.value-lower');
var lvalue = $j(this).find('.lvalue');
var upper = $j(this).find('.value-upper');
var uvalue = $j(this).find('.uvalue');
$j(this).Link('lower').to(lower);
$j(this).Link('upper').to(upper);
$j(this).on('slide', function(event, values) {
lvalue.val(values[0]).trigger('input');
uvalue.val(values[1]).trigger('input');
});
});
});
jQuery(function ($j) {
"use strict";
$j(".expander-list").find("ul").hide().end().find(" .expander").text("+").end().find(".active").each(function () {
$j(this).parents("li ").each(function () {
var $jthis = $j(this),
$jul = $jthis.find("> ul"),
$jname = $jthis.find("> .name a"),
$jexpander = $jthis.find("> .name .expander");
$jul.show();
$jname.css("font-weight", "bold");
$jexpander.html("−")
})
}).end().find(" .expander").each(function () {
var $jthis = $j(this),
hide = $jthis.text() === "+",
$jul = $jthis.parent(".name").next("ul"),
$jname = $jthis.next("a");
$jthis.click(function () {
if ($jul.css("display") ==
"block")
$jul.slideUp("slow");
else
$jul.slideDown("slow");
$j(this).html(hide ? "−" : "+");
$jname.css("font-weight", hide ? "bold" : "normal");
hide = !hide
})
})
});
jQuery(function ($j) {
"use strict";
$j(".collapsed-block .expander").click(function (e) {
var collapse_content_selector = $j(this).attr("href");
var expander = $j(this);
if (!$j(collapse_content_selector).hasClass("open"))
expander.addClass("open").html("−");
else
expander.removeClass("open").html("+");
if (!$j(collapse_content_selector).hasClass("open"))
$j(collapse_content_selector).addClass("open").slideDown("normal");
else
$j(collapse_content_selector).removeClass("open").slideUp("normal");
e.preventDefault()
})
});
jQuery(function ($j) {
"use strict";
if ($j(".no-touch .cloudzoom").length) {
CloudZoom.quickStart();
}
});
jQuery(function ($j) {
"use strict";
carouselProductNoSpace();
var $jmainContainer = $j(".container"),
$jsection = $j(".products-list"),
$jlinks = $j(".quick-view:not(.fancybox)"),
$jview = $j(".product-view-ajax"),
$jcontainer = $j(".product-view-container", $jview),
$jloader = $j(".ajax-loader", $jview),
$jlayar = $j(".layar", $jview),
$jslider;
var initProductView = function ($jproductView) {
var $jclose = $j(".close-view", $jproductView);
$jclose.click(function (e) {
e.preventDefault();
$jcontainer.slideUp(500, function () {
$jcontainer.empty();
$jview.hide();
$jcontainer.show()
})
setTimeout(function () {
$j('html, body').animate({
scrollTop: $j(".product-preview.active").offset().top - 70
}, 500, function () {
$j(".product-preview.active").removeClass('active');
});
}, 500)
})
};
$jlinks.click(function (e) {
if ($j(".hidden-xs").is(":visible")) {
e.preventDefault();
var $jthis = $j(this),
url = $jthis.attr("href");
$jthis.closest(".product-preview").addClass('active');
if ($jthis.closest(".product-carousel").length > 0) {
$jthis.closest(".product-carousel").next(".product-view-ajax-container").first().append($jview);
} else if ($jthis.closest(".products-nospace-outer.products-list").length > 0) {
$jthis.closest(".listing-row").nextAll('.product-view-ajax-container:first').append($jview);
} else if ($jthis.closest(".products-list").length > 0) {
$jthis.closest(".product-preview-outer").nextAll('.product-view-ajax-container:first').append($jview);
} else if ($jthis.closest(".products-nospace-outer").length > 0) {
$jthis.closest(".products-nospace-outer").nextAll('.product-view-ajax-container:first').append($jview);
} else {
$jthis.parent().parent().nextAll('.product-view-ajax-container:first').append($jview);
}
$jview.show();
$jlayar.show();
$jloader.show();
$j('html, body').animate({
scrollTop: $jthis.closest(".product-preview").offset().top
}, 500);
setTimeout(function () {
$j.ajax({
url: url,
cache: false,
success: function (data) {
var $jdata = $j(data);
initProductView($jdata);
$jloader.hide();
$jlayar.hide();
if (!$jcontainer.text()) {
$jdata.hide();
$jcontainer.empty().append($jdata);
$jdata.slideDown(500)
} else
$jcontainer.empty().append($jdata)
},
complete: function () {
console.log("ajax complete");
$j('html, body').animate({
scrollTop: $jview.offset().top - 100
}, 500);
},
error: function (jqXHR, textStatus, errorThrown) {
$jloader.hide();
$jcontainer.html(textStatus)
}
})
}, 1000);
}
});
$j(".responsive .product-carousel").slick({
dots: false,
infinite: false,
speed: 500,
slidesToShow: 6,
slidesToScroll: 6,
responsive: [{
breakpoint: 1199,
settings: {
slidesToShow: 5,
slidesToScroll: 5
}
}, {
breakpoint: 992,
settings: {
slidesToShow: 4,
slidesToScroll: 4
}
}, {
breakpoint: 769,
settings: {
slidesToShow: 3,
slidesToScroll: 3
}
}, {
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
}, {
breakpoint: 481,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}, {
breakpoint: 321,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}]
});
$j(".noresponsive .product-carousel").slick({
dots: false,
infinite: false,
speed: 500,
slidesToShow: 6,
slidesToScroll: 6
});
initProductView();
$j(".responsive .single-product-carousel").slick({
dots: false,
infinite: true,
speed: 300,
slidesToShow: 4,
slidesToScroll: 1,
asNavFor: '.slider-nav',
responsive: [{
breakpoint: 481,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: false
}
}, {
breakpoint: 321,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: false
}
}]
})
$j(".noresponsive .single-product-carousel").slick({
dots: false,
infinite: true,
speed: 300,
slidesToShow: 4,
slidesToScroll: 1,
asNavFor: '.slider-nav'
})
if ($j('.slider-nav').length) {
var slidernavItem = 3;
if (!$j('.slider-nav').parent().find('.video-link').length) {
slidernavItem = 4;
$j('.slider-nav').css({
'width': '100%'
})
}
$j('.responsive .slider-nav').slick({
slidesToShow: slidernavItem,
slidesToScroll: 1,
asNavFor: '.single-product-carousel',
speed: 300,
dots: false,
arrows: false,
centerMode: false,
focusOnSelect: true,
responsive: [{
breakpoint: 992,
settings: {
slidesToShow: slidernavItem,
slidesToScroll: 1,
centerMode: false
}
}]
});
$j('.noresponsive .slider-nav').slick({
slidesToShow: slidernavItem,
slidesToScroll: 1,
asNavFor: '.single-product-carousel',
speed: 300,
dots: false,
arrows: false,
centerMode: false,
focusOnSelect: true
});
}
$j(".responsive .single-product").slick({
dots: false,
infinite: true,
speed: 300,
fade: true,
arrows: false,
slidesToShow: 1,
slidesToScroll: 1,
asNavFor: '.slider-nav-simple',
responsive: [{
breakpoint: 481,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: false
}
}, {
breakpoint: 321,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: false
}
}]
})
$j(".noresponsive .single-product").slick({
dots: false,
infinite: true,
speed: 300,
fade: true,
arrows: false,
slidesToShow: 1,
slidesToScroll: 1,
asNavFor: '.slider-nav-simple'
})
if ($j('.slider-nav-simple').length) {
var slidernavItem = 3;
if (!$j('.slider-nav-simple').parent().find('.video-link').length) {
slidernavItem = 4;
$j('.slider-nav-simple').css({
'width': '100%'
})
}
$j('.slider-nav-simple').slick({
slidesToShow: slidernavItem,
slidesToScroll: 1,
asNavFor: '.single-product',
speed: 300,
dots: false,
arrows: false,
centerMode: false,
focusOnSelect: true,
responsive: [{
breakpoint: 992,
settings: {
slidesToShow: slidernavItem,
slidesToScroll: 1,
centerMode: false
}
}]
});
}
$j('.testimonials-widget .slides').slick({
dots: false,
infinite: false,
vertical: true,
arrows: true,
autoplay: false,
speed: 500,
slidesToScroll: 1,
slidesToShow: 1,
touchMove: false
//variableWidth: true
});
$j(".responsive .circle_banners .row").slick({
dots: false,
infinite: false,
draggable: false,
speed: 300,
slidesToShow: 3,
slidesToScroll: 1,
responsive: [{
breakpoint: 992,
settings: {
slidesToShow: 3,
slidesToScroll: 1
}
}, {
breakpoint: 769,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
arrows: false,
draggable: true
}
}]
});
$j(".noresponsive .circle_banners .row").slick({
dots: false,
infinite: false,
draggable: false,
speed: 300,
slidesToShow: 3,
slidesToScroll: 1
});
$j(".responsive .blog-widget .slides").slick({
dots: false,
infinite: false,
draggable: false,
speed: 300,
slidesToShow: 5,
slidesToScroll: 1,
responsive: [{
breakpoint: 992,
settings: {
slidesToShow: 4,
slidesToScroll: 1
}
}, {
breakpoint: 769,
settings: {
slidesToShow: 3,
slidesToScroll: 1
}
}, {
breakpoint: 681,
settings: {
slidesToShow: 2,
slidesToScroll: 1
}
}, {
breakpoint: 321,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}]
});
$j(".noresponsive .blog-widget .slides").slick({
dots: false,
infinite: false,
draggable: false,
speed: 300,
slidesToShow: 5,
slidesToScroll: 1
});
// category banner carousel
var categoryCarousel = $j('.category-slider');
categoryCarousel.slick({
dots: false,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1
});
// news carousel
var newsCarousel = $j('#newsCarousel');
newsCarousel.slick({
dots: false,
infinite: false,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1
});
setTimeout(function () {
newsCarousel.css({
visibility: 'visible'
});
}, 1000)
// news marquee
$j('#newsCarousel .marquee').liMarquee();
$j(".blog-widget .slides button").hover(function () {
$j(this).parent().find(".slick-list").toggleClass('nav-hover')
});
$j(".responsive .brands-carousel .slides").slick({
dots: false,
infinite: true,
autoplay: false,
autoplaySpeed: 2000,
speed: 500,
slidesToShow: 7,
slidesToScroll: 1,
responsive: [{
breakpoint: 992,
settings: {
slidesToShow: 5,
slidesToScroll: 4
}
}, {
breakpoint: 768,
settings: {
slidesToShow: 4,
slidesToScroll: 3
}
}, {
breakpoint: 480,
settings: {
slidesToShow: 3,
slidesToScroll: 2
}
}]
});
$j(".noresponsive .brands-carousel .slides").slick({
dots: false,
infinite: true,
autoplay: false,
autoplaySpeed: 2000,
speed: 500,
slidesToShow: 7,
slidesToScroll: 1
});
$j('.slick-slider').each(function () {
var $jthis = $j(this);
if (!$jthis.find('button').length) {
$jthis.parent().prev('.right-space').addClass('no-right-space');
$jthis.parent().prev().prev('.right-space').addClass('no-right-space');
}
})
var windowWidth = window.innerWidth || document.documentElement.clientWidth;
$j(window).resize(function () {
var windowWidthR = window.innerWidth || document.documentElement.clientWidth;
if (windowWidthR != windowWidth) {
clearTimeout(window.resizeEvt);
window.resizeEvt = setTimeout(function () {
$j('.slick-slider').each(function () {
var $jthis = $j(this);
if (!$jthis.find('button').length) {
$jthis.parent().prev('.right-space').addClass('no-right-space');
$jthis.parent().prev().prev('.right-space').addClass('no-right-space');
} else {
$jthis.parent().prev('.right-space').removeClass('no-right-space');
$jthis.parent().prev().prev('.right-space').removeClass('no-right-space');
}
})
}, 500);
windowWidth = windowWidthR;
}
});
});
$j(window).load(function () {
"use strict";
var loadcontainer = $j('.facebook-widget').find(".loading");
$j.ajax({
url: $j('.facebook-widget a').attr("href"),
cache: false,
success: function (data) {
setTimeout(function () {
loadcontainer.html(data)
}, 1000)
}
});
slideHoverWidth();
equalHeight('.rect-equal-height');
setTimeout(function () {
if ($j('#popup-box').length) {
$j.magnificPopup.open({
items: {
src: '#popup-box'
},
mainClass: 'mfp-fade',
closeBtnInside: true,
closeMarkup: '<button title="%title%" class="mfp-close">×</button>',
type: 'inline'
});
}
}, 1000);
$j('#menuScrollerWrapper').css({
display: 'block'
});
$j('.header-product-carousel').slick({
dots: false,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1
});
$j('#menuScrollerWrapper').css({
display: 'none'
});
$j("body").width($j("body").width() + 1).width("auto");
var windowWidth = window.innerWidth || document.documentElement.clientWidth;
var animate = $j(".animate");
var animateDelay = $j(".animate-delay-outer");
var animateDelayItem = $j(".animate-delay");
if (windowWidth > 767) {
animate.bind("inview", function (event, visible) {
if (visible && !$j(this).hasClass("animated"))
$j(this).addClass("animated")
});
animateDelay.bind("inview", function (event, visible) {
if (visible && !$j(this).hasClass("animated")) {
var j = -1;
var $jthis = $j(this).find(".animate-delay");
$jthis.each(function () {
var $jthis = jQuery(this);
j++;
setTimeout(function () {
$jthis.addClass("animated")
}, 200 * j)
});
$j(this).addClass("animated")
}
})
} else {
animate.each(function () {
$j(this).removeClass("animate")
});
animateDelayItem.each(function () {
$j(this).removeClass("animate-delay")
})
}
var counter = $j(".counter")
if (counter.length > 0) {
$j('.counter').countTo();
}
var tabsLeftTabs = $j(".responsive .tabs-left .nav-tabs"),
tabsLeftContent = $j('.responsive .tabs-left .tab-content');
if (tabsLeftContent.length > 0) {
tabsLeftContent.css({
'min-height': tabsLeftTabs.height() - 3
});
}
$j(".preview.hover-slide .preview-image").each(function () {
var imageHeight = $j(this).find("img").height();
$j(this).css({
"height": imageHeight
})
});
$j("body > .loader").fadeOut("slow");
if ($j(".no-touch .parallax").length > 0)
$j(".no-touch .parallax").parallax({
speed: 0,
axis: "y"
});
var $jisotop = $j(".products-isotope")
if ($jisotop.length) {
if ($jisotop.children().length == 0) {
$jisotop.parent().parent('section.content').hide();
} else {
// add columnWidth function to Masonry
var MasonryMode = Isotope.LayoutMode.modes.masonry;
MasonryMode.prototype._getMeasurement = function (measurement, size) {
var option = this.options[measurement];
var elem;
if (!option) {
// default to 0
this[measurement] = 0;
} else if (typeof option === 'function') {
this[measurement] = option.call(this);
} else {
// use option as an element
if (typeof option === 'string') {
elem = this.element.querySelector(option);
} else if (isElement(option)) {
elem = option;
}
// use size of element, if element
this[measurement] = elem ? getSize(elem)[size] : option;
}
};
$jisotop.isotope({
itemSelector: ".product-preview,.banner,.item",
masonry: {
columnWidth: function () {
return this.size.innerWidth / 60;
}
}
});
var $optionSets = $j(".filters-by-category .option-set"),
$optionLinks = $optionSets.find("a");
$optionLinks.click(function () {
var $this = $j(this);
if ($this.hasClass("selected"))
return false;
var $optionSet = $this.parents(".option-set");
$optionSet.find(".selected").removeClass("selected");
$this.addClass("selected");
var options = {},
key = $optionSet.attr("data-option-key"),
value = $this.attr("data-option-value");
value = value === "false" ? false : value;
options[key] = value;
if (key === "layoutMode" && typeof changeLayoutMode === "function")
changeLayoutMode($this, options);
else
$jisotop.isotope(options);
return false
})
}
}
var $jisotopPost = $j(".blog-posts")
if ($jisotopPost.length) {
$jisotopPost.isotope({
itemSelector: ".blog-post"
});
var $optionSets = $j(".filters-by-category .option-set"),
$optionLinks = $optionSets.find("a");
$optionLinks.click(function () {
var $this = $j(this);
if ($this.hasClass("selected"))
return false;
var $optionSet = $this.parents(".option-set");
$optionSet.find(".selected").removeClass("selected");
$this.addClass("selected");
var options = {},
key = $optionSet.attr("data-option-key"),
value = $this.attr("data-option-value");
value = value === "false" ? false : value;
options[key] = value;
if (key === "layoutMode" && typeof changeLayoutMode === "function")
changeLayoutMode($this, options);
else
$jisotopPost.isotope(options);
return false
})
}
$j('.marina .product-preview .preview-image, .marina .products-widget .preview-image, .marina .blog-widget-small .preview-image, .marina .single-product-wrapper, .marina .elevatezoom-gallery, .marina .video-link .img-outer').each(function () {
$j(this).height($j(this).width());
});
footerStick();
if ($j(".product-images-cell").length) {
var productViewHeight = $j(".product-images-cell").height();
$j(".product-view").css({
'min-height': productViewHeight + 'px'
});
}
var windowWidth = window.innerWidth || document.documentElement.clientWidth;
$j(window).resize(function () {
footerStick();
var windowWidthR = window.innerWidth || document.documentElement.clientWidth;
if (windowWidthR != windowWidth) {
$j('.marina .product-preview .preview-image, .marina .products-widget .preview-image, .marina .blog-widget-small .preview-image, .marina .single-product-wrapper, .marina .elevatezoom-gallery, .marina .video-link .img-outer').each(function () {
$j(this).height($j(this).width());
});
carouselProductNoSpace();
slideHoverWidth();
if ($j("#popup-box").length > 0 && $j("#colorbox").is(":visible")) {
$j.colorbox({
inline: true,
href: "#popup-box",
preloading: false,
fixed: true,
opacity: 0.75
});
}
setTimeout(function () {
if ($j(".product-images-cell").length) {
$j(".product-view").css({
'min-height': 0
});
var productViewHeight = $j(".product-images-cell").height();
$j(".product-view").css({
'min-height': productViewHeight + 'px'
});
}
}, 500)
windowWidth = windowWidthR;
}
});
}); | mit |
jshint/jshint | tests/unit/options.js | 162101 | /**
* Tests for all non-environmental options. Non-environmental options are
* options that change how JSHint behaves instead of just pre-defining a set
* of global variables.
*/
"use strict";
var JSHINT = require("../..").JSHINT;
var fs = require('fs');
var TestRun = require('../helpers/testhelper').setup.testRun;
var fixture = require('../helpers/fixture').fixture;
/**
* Option `shadow` allows you to re-define variables later in code.
*
* E.g.:
* var a = 1;
* if (cond == true)
* var a = 2; // Variable a has been already defined on line 1.
*
* More often than not it is a typo, but sometimes people use it.
*/
exports.shadow = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/redef.js", "utf8");
// Do not tolerate variable shadowing by default
TestRun(test)
.addError(5, 13, "'a' is already defined.")
.addError(10, 9, "'foo' is already defined.")
.test(src, {es3: true});
TestRun(test)
.addError(5, 13, "'a' is already defined.")
.addError(10, 9, "'foo' is already defined.")
.test(src, {es3: true, shadow: false });
TestRun(test)
.addError(5, 13, "'a' is already defined.")
.addError(10, 9, "'foo' is already defined.")
.test(src, {es3: true, shadow: "inner" });
// Allow variable shadowing when shadow is true
TestRun(test)
.test(src, { es3: true, shadow: true });
src = [
"function f() {",
" function inner() {}",
"}"
];
TestRun(test, "nested functions - 'shadowed' `arguments` - true")
.test(src, { shadow: true });
TestRun(test, "nested functions - 'shadowed' `arguments` - false")
.test(src, { shadow: false });
TestRun(test, "nested functions - 'shadowed' `arguments` - 'inner'")
.test(src, { shadow: "inner" });
test.done();
};
/**
* Option `shadow:outer` allows you to re-define variables later in inner scopes.
*
* E.g.:
* var a = 1;
* function foo() {
* var a = 2;
* }
*/
exports.shadowouter = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/scope-redef.js", "utf8");
// Do not tolarate inner scope variable shadowing by default
TestRun(test)
.addError(5, 13, "'a' is already defined in outer scope.")
.addError(12, 18, "'b' is already defined in outer scope.")
.addError(20, 18, "'bar' is already defined in outer scope.")
.addError(26, 14, "'foo' is already defined.")
.test(src, { es3: true, shadow: "outer" });
test.done();
};
exports.shadowInline = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/shadow-inline.js", "utf8");
TestRun(test)
.addError(6, 18, "'a' is already defined in outer scope.")
.addError(7, 13, "'a' is already defined.")
.addError(7, 13, "'a' is already defined in outer scope.")
.addError(17, 13, "'a' is already defined.")
.addError(27, 13, "'a' is already defined.")
.addError(42, 5, "Bad option value.")
.addError(47, 13, "'a' is already defined.")
.test(src);
test.done();
};
exports.shadowEs6 = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/redef-es6.js", "utf8");
var commonErrors = [
[2, 5, "'ga' has already been declared."],
[5, 7, "'gb' has already been declared."],
[14, 9, "'gd' has already been declared."],
[24, 9, "'gf' has already been declared."],
[110, 5, "'gx' has already been declared."],
[113, 7, "'gy' has already been declared."],
[116, 7, "'gz' has already been declared."],
[119, 5, "'gza' has already been declared."],
[122, 5, "'gzb' has already been declared."],
[132, 5, "'gzd' has already been declared."],
[147, 7, "'gzf' has already been declared."],
[156, 9, "'a' has already been declared."],
[159, 11, "'b' has already been declared."],
[168, 13, "'d' has already been declared."],
[178, 13, "'f' has already been declared."],
[264, 9, "'x' has already been declared."],
[267, 11, "'y' has already been declared."],
[270, 11, "'z' has already been declared."],
[273, 9, "'za' has already been declared."],
[276, 9, "'zb' has already been declared."],
[286, 9, "'zd' has already been declared."],
[301, 11, "'zf' has already been declared."],
[317, 11, "'zi' has already been declared."],
[344, 9, "'zzi' has already been declared."],
[345, 11, "'zzj' has already been declared."],
[349, 24, "'zzl' has already been declared."],
[349, 30, "'zzl' was used before it was declared, which is illegal for 'const' variables."],
[350, 22, "'zzm' has already been declared."],
[350, 28, "'zzm' was used before it was declared, which is illegal for 'let' variables."],
[364, 7, "'zj' has already been declared."]
];
var innerErrors = [
[343, 9, "'zzh' is already defined."],
[348, 22, "'zzk' is already defined."]
];
var outerErrors = [
/* block scope variables shadowing out of scope */
[9, 9, "'gc' is already defined."],
[19, 11, "'ge' is already defined."],
[28, 9, "'gg' is already defined in outer scope."],
[32, 11, "'gh' is already defined in outer scope."],
[36, 9, "'gi' is already defined in outer scope."],
[40, 3, "'gj' is already defined."],
[44, 3, "'gk' is already defined."],
[48, 3, "'gl' is already defined."],
[53, 7, "'gm' is already defined."],
[59, 7, "'gn' is already defined."],
[65, 7, "'go' is already defined."],
[71, 9, "'gp' is already defined."],
[76, 9, "'gq' is already defined."],
[81, 11, "'gr' is already defined."],
[86, 11, "'gs' is already defined."],
[163, 13, "'c' is already defined."],
[173, 15, "'e' is already defined."],
[182, 13, "'g' is already defined in outer scope."],
[186, 15, "'h' is already defined in outer scope."],
[190, 13, "'i' is already defined in outer scope."],
[194, 6, "'j' is already defined."],
[198, 6, "'k' is already defined."],
[202, 6, "'l' is already defined."],
[207, 10, "'m' is already defined."],
[213, 10, "'n' is already defined."],
[219, 10, "'o' is already defined."],
[225, 13, "'p' is already defined."],
[230, 13, "'q' is already defined."],
[235, 15, "'r' is already defined."],
[240, 15, "'s' is already defined."],
/* variables shadowing outside of function scope */
[91, 9, "'gt' is already defined in outer scope."],
[96, 9, "'gu' is already defined in outer scope."],
[101, 11, "'gv' is already defined in outer scope."],
[106, 9, "'gw' is already defined in outer scope."],
[245, 13, "'t' is already defined in outer scope."],
[250, 13, "'u' is already defined in outer scope."],
[255, 15, "'v' is already defined in outer scope."],
[260, 13, "'w' is already defined in outer scope."],
/* variables shadowing outside multiple function scopes */
[332, 17, "'zza' is already defined in outer scope."],
[333, 17, "'zzb' is already defined in outer scope."],
[334, 17, "'zzc' is already defined in outer scope."],
[335, 17, "'zzd' is already defined in outer scope."],
[336, 17, "'zze' is already defined in outer scope."],
[337, 17, "'zzf' is already defined in outer scope."],
[358, 9, "'zzn' is already defined in outer scope."]
];
var testRun = TestRun(test);
commonErrors.forEach(function(error) { testRun.addError.apply(testRun, error); });
testRun.test(src, {esnext: true, shadow: true});
var testRun = TestRun(test);
commonErrors.concat(innerErrors).forEach(function(error) { testRun.addError.apply(testRun, error); });
testRun.test(src, {esnext: true, shadow: "inner", maxerr: 100 });
var testRun = TestRun(test);
commonErrors.concat(innerErrors, outerErrors).forEach(function(error) { testRun.addError.apply(testRun, error); });
testRun.test(src, {esnext: true, shadow: "outer", maxerr: 100});
test.done();
};
/**
* Option `latedef` allows you to prohibit the use of variable before their
* definitions.
*
* E.g.:
* fn(); // fn will be defined later in code
* function fn() {};
*
* Since JavaScript has function-scope only, you can define variables and
* functions wherever you want. But if you want to be more strict, use
* this option.
*/
exports.latedef = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/latedef.js', 'utf8'),
src1 = fs.readFileSync(__dirname + '/fixtures/redef.js', 'utf8'),
esnextSrc = fs.readFileSync(__dirname + '/fixtures/latedef-esnext.js', 'utf8');
// By default, tolerate the use of variable before its definition
TestRun(test)
.test(src, {es3: true, funcscope: true});
TestRun(test)
.addError(10, 5, "'i' was used before it was declared, which is illegal for 'let' variables.")
.test(esnextSrc, {esnext: true});
// However, JSHint must complain if variable is actually missing
TestRun(test)
.addError(1, 1, "'fn' is not defined.")
.test('fn();', { es3: true, undef: true });
// And it also must complain about the redefinition (see option `shadow`)
TestRun(test)
.addError(5, 13, "'a' is already defined.")
.addError(10, 9, "'foo' is already defined.")
.test(src1, { es3: true });
// When latedef is true, JSHint must not tolerate the use before definition
TestRun(test)
.addError(10, 9, "'vr' was used before it was defined.")
.test(src, { es3: true, latedef: "nofunc" });
// when latedef is true, jshint must not warn if variable is defined.
TestRun(test)
.test([
"if(true) { var a; }",
"if (a) { a(); }",
"var a;"], { es3: true, latedef: true});
// When latedef_func is true, JSHint must not tolerate the use before definition for functions
TestRun(test)
.addError(2, 10, "'fn' was used before it was defined.")
.addError(6, 14, "'fn1' was used before it was defined.")
.addError(10, 9, "'vr' was used before it was defined.")
.addError(18, 12, "'bar' was used before it was defined.")
.addError(18, 3, "Inner functions should be listed at the top of the outer function.")
.test(src, { es3: true, latedef: true });
var es2015Errors = TestRun(test)
.addError(4, 5, "'c' was used before it was defined.")
.addError(6, 7, "'e' was used before it was defined.")
.addError(8, 5, "'h' was used before it was defined.")
.addError(10, 5, "'i' was used before it was declared, which is illegal for 'let' variables.")
.addError(15, 9, "'ai' was used before it was defined.")
.addError(20, 13, "'ai' was used before it was defined.")
.addError(31, 9, "'bi' was used before it was defined.")
.addError(48, 13, "'ci' was used before it was defined.")
.addError(75, 10, "'importedName' was used before it was defined.")
.addError(76, 8, "'importedModule' was used before it was defined.")
.addError(77, 13, "'importedNamespace' was used before it was defined.");
es2015Errors
.test(esnextSrc, {esversion: 2015, latedef: true});
es2015Errors
.test(esnextSrc, {esversion: 2015, latedef: "nofunc"});
TestRun(test, "shouldn't warn when marking a var as exported")
.test("var a;", { exported: ["a"], latedef: true });
test.done();
};
exports.latedefInline = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/latedef-inline.js', 'utf8');
TestRun(test)
.addError(4, 14, "'foo' was used before it was defined.")
.addError(6, 9, "'a' was used before it was defined.")
.addError(22, 9, "'a' was used before it was defined.")
.addError(26, 5, "Bad option value.")
.test(src);
TestRun(test, "shouldn't warn when marking a var as exported")
.test("/*exported a*/var a;", { latedef: true });
test.done();
};
exports.notypeof = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/typeofcomp.js', 'utf8');
TestRun(test)
.addError(1, 17, "Invalid typeof value 'funtion'")
.addError(2, 14, "Invalid typeof value 'double'")
.addError(3, 17, "Invalid typeof value 'bool'")
.addError(4, 11, "Invalid typeof value 'obj'")
.addError(13, 17, "Invalid typeof value 'symbol'")
.addError(14, 21, "'BigInt' is only available in ES11 (use 'esversion: 11').")
.test(src);
TestRun(test)
.addError(1, 17, "Invalid typeof value 'funtion'")
.addError(2, 14, "Invalid typeof value 'double'")
.addError(3, 17, "Invalid typeof value 'bool'")
.addError(4, 11, "Invalid typeof value 'obj'")
.addError(14, 21, "'BigInt' is only available in ES11 (use 'esversion: 11').")
.test(src, { esnext: true });
TestRun(test)
.addError(1, 17, "Invalid typeof value 'funtion'")
.addError(2, 14, "Invalid typeof value 'double'")
.addError(3, 17, "Invalid typeof value 'bool'")
.addError(4, 11, "Invalid typeof value 'obj'")
.test(src, { esversion: 11 });
TestRun(test)
.test(src, { notypeof: true });
TestRun(test)
.test(src, { notypeof: true, esnext: true });
test.done();
}
exports['combination of latedef and undef'] = function (test) {
var src = fixture('latedefundef.js');
// Assures that when `undef` is set to true, it'll report undefined variables
// and late definitions won't be reported as `latedef` is set to false.
TestRun(test)
.addError(29, 1, "'hello' is not defined.")
.addError(35, 5, "'world' is not defined.")
.test(src, { es3: true, latedef: false, undef: true });
// When we suppress `latedef` and `undef` then we get no warnings.
TestRun(test)
.test(src, { es3: true, latedef: false, undef: false });
// If we warn on `latedef` but suppress `undef` we only get the
// late definition warnings.
TestRun(test)
.addError(5, 10, "'func2' was used before it was defined.")
.addError(12, 10, "'foo' was used before it was defined.")
.addError(18, 14, "'fn1' was used before it was defined.")
.addError(26, 10, "'baz' was used before it was defined.")
.addError(34, 14, "'fn' was used before it was defined.")
.addError(41, 9, "'q' was used before it was defined.")
.addError(46, 5, "'h' was used before it was defined.")
.test(src, { es3: true, latedef: true, undef: false });
// But we get all the functions warning if we disable latedef func
TestRun(test)
.addError(41, 9, "'q' was used before it was defined.")
.addError(46, 5, "'h' was used before it was defined.")
.test(src, { es3: true, latedef: "nofunc", undef: false });
// If we warn on both options we get all the warnings.
TestRun(test)
.addError(5, 10, "'func2' was used before it was defined.")
.addError(12, 10, "'foo' was used before it was defined.")
.addError(18, 14, "'fn1' was used before it was defined.")
.addError(26, 10, "'baz' was used before it was defined.")
.addError(29, 1, "'hello' is not defined.")
.addError(34, 14, "'fn' was used before it was defined.")
.addError(35, 5, "'world' is not defined.")
.addError(41, 9, "'q' was used before it was defined.")
.addError(46, 5, "'h' was used before it was defined.")
.test(src, { es3: true, latedef: true, undef: true });
// If we remove latedef_func, we don't get the functions warning
TestRun(test)
.addError(29, 1, "'hello' is not defined.")
.addError(35, 5, "'world' is not defined.")
.addError(41, 9, "'q' was used before it was defined.")
.addError(46, 5, "'h' was used before it was defined.")
.test(src, { es3: true, latedef: "nofunc", undef: true });
test.done();
};
exports.undefwstrict = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/undefstrict.js', 'utf8');
TestRun(test).test(src, { es3: true, undef: false });
test.done();
};
// Regression test for GH-431
exports["implied and unused should respect hoisting"] = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/gh431.js', 'utf8');
TestRun(test)
.addError(14, 5, "'fun4' is not defined.")
.test(src, { undef: true }); // es5
JSHINT(src, { undef: true });
var report = JSHINT.data();
test.equal(report.implieds.length, 1);
test.equal(report.implieds[0].name, 'fun4');
test.deepEqual(report.implieds[0].line, [14]);
test.equal(report.unused.length, 3);
test.done();
};
/**
* The `proto` and `iterator` options allow you to prohibit the use of the
* special `__proto__` and `__iterator__` properties, respectively.
*/
exports.testProtoAndIterator = function (test) {
var source = fs.readFileSync(__dirname + '/fixtures/protoiterator.js', 'utf8');
var json = '{"__proto__": true, "__iterator__": false, "_identifier": null, "property": 123}';
// JSHint should not allow the `__proto__` and
// `__iterator__` properties by default
TestRun(test)
.addError(7, 34, "The '__proto__' property is deprecated.")
.addError(8, 19, "The '__proto__' property is deprecated.")
.addError(10, 19, "The '__proto__' property is deprecated.")
.addError(27, 29, "The '__iterator__' property is deprecated.")
.addError(27, 53, "The '__iterator__' property is deprecated.")
.addError(33, 19, "The '__proto__' property is deprecated.")
.addError(37, 29, "The '__proto__' property is deprecated.")
.test(source, {es3: true});
TestRun(test)
.addError(1, 2, "The '__proto__' key may produce unexpected results.")
.addError(1, 21, "The '__iterator__' key may produce unexpected results.")
.test(json, {es3: true});
// Should not report any errors when proto and iterator
// options are on
TestRun("source").test(source, { es3: true, proto: true, iterator: true });
TestRun("json").test(json, { es3: true, proto: true, iterator: true });
test.done();
};
/**
* The `camelcase` option allows you to enforce use of the camel case convention.
*/
exports.testCamelcase = function (test) {
var source = fs.readFileSync(__dirname + '/fixtures/camelcase.js', 'utf8');
// By default, tolerate arbitrary identifiers
TestRun(test)
.test(source, {es3: true});
// Require identifiers in camel case if camelcase is true
TestRun(test)
.addError(5, 17, "Identifier 'Foo_bar' is not in camel case.")
.addError(5, 25, "Identifier 'test_me' is not in camel case.")
.addError(6, 15, "Identifier 'test_me' is not in camel case.")
.addError(6, 25, "Identifier 'test_me' is not in camel case.")
.addError(13, 26, "Identifier 'test_1' is not in camel case.")
.test(source, { es3: true, camelcase: true });
test.done();
};
/**
* Option `curly` allows you to enforce the use of curly braces around
* control blocks. JavaScript allows one-line blocks to go without curly
* braces but some people like to always use curly bracse. This option is
* for them.
*
* E.g.:
* if (cond) return;
* vs.
* if (cond) { return; }
*/
exports.curly = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/curly.js', 'utf8'),
src1 = fs.readFileSync(__dirname + '/fixtures/curly2.js', 'utf8');
// By default, tolerate one-line blocks since they are valid JavaScript
TestRun(test).test(src, {es3: true});
TestRun(test).test(src1, {es3: true});
// Require all blocks to be wrapped with curly braces if curly is true
TestRun(test)
.addError(2, 5, "Expected '{' and instead saw 'return'.")
.addError(5, 5, "Expected '{' and instead saw 'doSomething'.")
.addError(8, 5, "Expected '{' and instead saw 'doSomething'.")
.addError(11, 5, "Expected '{' and instead saw 'doSomething'.")
.test(src, { es3: true, curly: true });
TestRun(test).test(src1, { es3: true, curly: true });
test.done();
};
/** Option `noempty` prohibits the use of empty blocks. */
exports.noempty = function (test) {
var code = [
"for (;;) {}",
"if (true) {",
"}",
"foo();"
];
// By default, tolerate empty blocks since they are valid JavaScript
TestRun(test).test(code, { es3: true });
// Do not tolerate, when noempty is true
TestRun(test)
.addError(1, 10, "Empty block.")
.addError(2, 11, "Empty block.")
.test(code, { es3: true, noempty: true });
test.done();
};
/**
* Option `noarg` prohibits the use of arguments.callee and arguments.caller.
* JSHint allows them by default but you have to know what you are doing since:
* - They are not supported by all JavaScript implementations
* - They might prevent an interpreter from doing some optimization tricks
* - They are prohibited in the strict mode
*/
exports.noarg = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/noarg.js', 'utf8');
// By default, tolerate both arguments.callee and arguments.caller
TestRun(test).test(src, { es3: true });
// Do not tolerate both .callee and .caller when noarg is true
TestRun(test)
.addError(2, 12, 'Avoid arguments.callee.')
.addError(6, 12, 'Avoid arguments.caller.')
.test(src, { es3: true, noarg: true });
test.done();
};
/** Option `nonew` prohibits the use of constructors for side-effects */
exports.nonew = function (test) {
var code = "new Thing();",
code1 = "var obj = new Thing();";
TestRun(test).test(code, { es3: true });
TestRun(test).test(code1, { es3: true });
TestRun(test)
.addError(1, 1, "Do not use 'new' for side effects.")
.test(code, { es3: true, nonew: true });
test.done();
};
// Option `asi` allows you to use automatic-semicolon insertion
exports.asi = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/asi.js', 'utf8');
TestRun(test, 1)
.addError(2, 13, "Missing semicolon.")
.addError(4, 21, "Missing semicolon.")
.addError(5, 14, "Missing semicolon.")
.addError(9, 26, "Missing semicolon.")
.addError(10, 14, "Missing semicolon.")
.addError(11, 23, "Missing semicolon.")
.addError(12, 14, "Missing semicolon.")
.addError(16, 23, "Missing semicolon.")
.addError(17, 19, "Missing semicolon.")
.addError(19, 18, "Missing semicolon.")
.addError(21, 18, "Missing semicolon.")
.addError(25, 6, "Missing semicolon.")
.addError(26, 10, "Missing semicolon.")
.addError(27, 12, "Missing semicolon.")
.addError(28, 12, "Missing semicolon.")
.test(src, { es3: true });
TestRun(test, 2)
.test(src, { es3: true, asi: true });
var code = [
"function a() { 'code' }",
"function b() { 'code'; 'code' }",
"function c() { 'code', 'code' }",
"function d() {",
" 'code' }",
"function e() { 'code' 'code' }"
];
TestRun(test, "gh-2714")
.addError(2, 24, "Unnecessary directive \"code\".")
.addError(3, 24, "Expected an assignment or function call and instead saw an expression.")
.addError(6, 22, "Missing semicolon.", { code: "E058" })
.addError(6, 16, "Expected an assignment or function call and instead saw an expression.")
.addError(6, 23, "Expected an assignment or function call and instead saw an expression.")
.test(code, { asi: true });
test.done();
};
// Option `asi` extended for safety -- warn in scenarios that would be unsafe when using asi.
exports.safeasi = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/safeasi.js', 'utf8');
TestRun(test, 1)
// TOOD consider setting an option to suppress these errors so that
// the tests don't become tightly interdependent
.addError(10, 5, "Misleading line break before '/'; readers may interpret this as an expression boundary.")
.addError(10, 8, "Expected an identifier and instead saw '.'.")
.addError(10, 8, "Expected an assignment or function call and instead saw an expression.")
.addError(10, 9, "Missing semicolon.")
.addError(10, 30, "Missing semicolon.")
.addError(11, 5, "Missing semicolon.")
.addError(21, 2, "Missing semicolon.")
.test(src, {});
TestRun(test, 2)
.addError(5, 1, "Misleading line break before '('; readers may interpret this as an expression boundary.")
.addError(8, 5, "Misleading line break before '('; readers may interpret this as an expression boundary.")
.addError(10, 5, "Misleading line break before '/'; readers may interpret this as an expression boundary.")
.addError(10, 8, "Expected an identifier and instead saw '.'.")
.addError(10, 8, "Expected an assignment or function call and instead saw an expression.")
.addError(10, 9, "Missing semicolon.")
.test(src, { asi: true });
var afterBracket = [
'x = []',
'[1];',
'x[0]',
'(2);'
];
TestRun(test, 'following bracket (asi: false)')
.test(afterBracket);
TestRun(test, 'following bracket (asi: true)')
.addError(2, 1, "Misleading line break before '['; readers may interpret this as an expression boundary.")
.addError(4, 1, "Misleading line break before '('; readers may interpret this as an expression boundary.")
.test(afterBracket, { asi: true });
var asClause = [
'if (true)',
' ({x} = {});',
'if (true)',
' [x] = [0];',
'while (false)',
' ({x} = {});',
'while (false)',
' [x] = [0];'
];
// Regression tests for gh-3304
TestRun(test, 'as clause (asi: false)')
.test(asClause, { esversion: 6 });
TestRun(test, 'as clause (asi: true)')
.test(asClause, { esversion: 6, asi: true });
test.done();
};
exports["missing semicolons not influenced by asi"] = function (test) {
// These tests are taken from
// http://www.ecma-international.org/ecma-262/6.0/index.html#sec-11.9.2
var code = [
"void 0;", // Not JSON
"{ 1 2 } 3"
];
TestRun(test)
.addError(2, 4, "Missing semicolon.", { code: "E058" })
.test(code, { expr: true, asi: true });
code = [
"void 0;",
"{ 1",
"2 } 3"
];
TestRun(test).test(code, { expr: true, asi: true });
code = "do {} while (false) var a;";
TestRun(test, "do-while as es5")
.addError(1, 20, "Missing semicolon.", { code: "E058" })
.test(code);
TestRun(test, "do-while as es5+moz")
.addError(1, 20, "Missing semicolon.", { code: "E058" })
.test(code, { moz: true });
TestRun(test, "do-while as es6")
.addError(1, 20, "Missing semicolon.", { code: "W033" })
.test(code, { esversion: 6 });
TestRun(test, "do-while as es6 with asi")
.test(code, { esversion: 6, asi: true });
TestRun(test, "do-while false positive")
.addError(1, 5, "Missing semicolon.", { code: "E058" })
.test("'do' var x;", { esversion: 6, expr: true });
test.done();
};
/** Option `lastsemic` allows you to skip the semicolon after last statement in a block,
* if that statement is followed by the closing brace on the same line. */
exports.lastsemic = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/lastsemic.js', 'utf8');
// without lastsemic
TestRun(test)
.addError(2, 11, "Missing semicolon.") // missing semicolon in the middle of a block
.addError(4, 45, "Missing semicolon.") // missing semicolon in a one-liner function
.addError(5, 12, "Missing semicolon.") // missing semicolon at the end of a block
.test(src, {es3: true});
// with lastsemic
TestRun(test)
.addError(2, 11, "Missing semicolon.")
.addError(5, 12, "Missing semicolon.")
.test(src, { es3: true, lastsemic: true });
// this line is valid now: [1, 2, 3].forEach(function(i) { print(i) });
// line 5 isn't, because the block doesn't close on the same line
test.done();
};
/**
* Option `expr` allows you to use ExpressionStatement as a Program code.
*
* Even though ExpressionStatement as a Program (i.e. without assingment
* of its result) is a valid JavaScript, more often than not it is a typo.
* That's why by default JSHint complains about it. But if you know what
* are you doing, there is nothing wrong with it.
*/
exports.expr = function (test) {
var exps = [
{ character: 33, src: "obj && obj.method && obj.method();" },
{ character: 20, src: "myvar && func(myvar);" },
{ character: 1, src: "1;" },
{ character: 1, src: "true;" },
{ character: 19, src: "+function (test) {};" }
];
for (var i = 0, exp; exp = exps[i]; i += 1) {
TestRun(test)
.addError(1, exp.character, 'Expected an assignment or function call and instead saw an expression.')
.test(exp.src, { es3: true });
}
for (i = 0, exp = null; exp = exps[i]; i += 1) {
TestRun(test).test(exp.src, { es3: true, expr: true });
}
test.done();
};
// Option `undef` requires you to always define variables you use.
exports.undef = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/undef.js', 'utf8');
// Make sure there are no other errors
TestRun(test).test(src, { es3: true });
// Make sure it fails when undef is true
TestRun(test)
.addError(1, 1, "'undef' is not defined.")
.addError(5, 12, "'undef' is not defined.")
.addError(6, 12, "'undef' is not defined.")
.addError(8, 12, "'undef' is not defined.")
.addError(9, 12, "'undef' is not defined.")
.addError(13, 5, "'localUndef' is not defined.")
.addError(18, 16, "'localUndef' is not defined.")
.addError(19, 16, "'localUndef' is not defined.")
.addError(21, 16, "'localUndef' is not defined.")
.addError(22, 16, "'localUndef' is not defined.")
.addError(32, 12, "'undef' is not defined.")
.addError(33, 13, "'undef' is not defined.")
.addError(34, 12, "'undef' is not defined.")
.test(src, { es3: true, undef: true });
// block scope cannot use themselves in the declaration
TestRun(test)
.addError(1, 9, "'a' was used before it was declared, which is illegal for 'let' variables.")
.addError(2, 11, "'b' was used before it was declared, which is illegal for 'const' variables.")
.addError(5, 7, "'e' is already defined.")
.test([
'let a = a;',
'const b = b;',
'var c = c;',
'function f(e) {',
' var e;', // the var does not overwrite the param, the param is used
' e = e || 2;',
' return e;',
'}'
], { esnext: true, undef: true });
// Regression test for GH-668.
src = fs.readFileSync(__dirname + "/fixtures/gh668.js", "utf8");
test.ok(JSHINT(src, { undef: true }));
test.ok(!JSHINT.data().implieds);
test.ok(JSHINT(src));
test.ok(!JSHINT.data().implieds);
JSHINT("if (typeof foobar) {}", { undef: true });
test.strictEqual(JSHINT.data().implieds, undefined);
// See gh-3055 "Labels Break JSHint"
TestRun(test, "following labeled block")
.addError(4, 6, "'x' is not defined.")
.test([
"label: {",
" let x;",
"}",
"void x;"
], { esversion: 6, undef: true });
TestRun(test)
.addError(1, 1, "'foo' is not defined.")
.test(['foo.call();',
'/* exported foo, bar */'],
{undef: true});
TestRun(test, "arguments - ES5")
.addError(6, 6, "'arguments' is not defined.")
.test([
"function f() { return arguments; }",
"void function() { return arguments; };",
"void function f() { return arguments; };",
"void { get g() { return arguments; } };",
"void { get g() {}, set g(_) { return arguments; } };",
"void arguments;"
], { undef: true });
TestRun(test, "arguments - ES2015")
.addError(47, 11, "'arguments' is not defined.")
.addError(48, 21, "'arguments' is not defined.")
.addError(49, 12, "'arguments' is not defined.")
.test([
"function f(_ = arguments) {}",
"void function (_ = arguments) {};",
"void function f(_ = arguments) {};",
"function* g(_ = arguments) { yield; }",
"void function* (_ = arguments) { yield; };",
"void function* g(_ = arguments) { yield; };",
"function* g() { yield arguments; }",
"void function* () { yield arguments; };",
"void function* g() { yield arguments; };",
"void { method(_ = arguments) {} };",
"void { method() { return arguments; } };",
"void { *method(_ = arguments) { yield; } };",
"void { *method() { yield arguments; } };",
"class C0 { constructor(_ = arguments) {} }",
"class C1 { constructor() { return arguments; } }",
"class C2 { method(_ = arguments) {} }",
"class C3 { method() { return arguments; } }",
"class C4 { *method(_ = arguments) { yield; } }",
"class C5 { *method() { yield arguments; } }",
"class C6 { static method(_ = arguments) {} }",
"class C7 { static method() { return arguments; } }",
"class C8 { static *method(_ = arguments) { yield; } }",
"class C9 { static *method() { yield arguments; } }",
"void class { constructor(_ = arguments) {} };",
"void class { constructor() { return arguments; } };",
"void class { method(_ = arguments) {} };",
"void class { method() { return arguments; } };",
"void class { *method(_ = arguments) { yield; } };",
"void class { *method() { yield arguments; } };",
"void class { static method(_ = arguments) {} };",
"void class { static method() { return arguments; } };",
"void class { static *method(_ = arguments) { yield; } };",
"void class { static *method() { yield arguments; } };",
"void class C { constructor(_ = arguments) {} };",
"void class C { constructor() { return arguments; } };",
"void class C { method(_ = arguments) {} };",
"void class C { method() { return arguments; } };",
"void class C { *method(_ = arguments) { yield; } };",
"void class C { *method() { yield arguments; } };",
"void class C { static method(_ = arguments) {} };",
"void class C { static method() { return arguments; } };",
"void class C { static *method(_ = arguments) { yield; } };",
"void class C { static *method() { yield arguments; } };",
"void function() { void (_ = arguments) => _; };",
"void function() { void () => { return arguments; }; };",
"void function() { void () => arguments; };",
"void (_ = arguments) => _;",
"void () => { return arguments; };",
"void () => arguments;"
], { undef: true, esversion: 6 });
test.done();
};
exports.undefToOpMethods = function (test) {
TestRun(test)
.addError(2, 12, "'undef' is not defined.")
.addError(3, 12, "'undef' is not defined.")
.test([
"var obj;",
"obj.delete(undef);",
"obj.typeof(undef);"
], { undef: true });
test.done();
};
/**
* In strict mode, the `delete` operator does not accept unresolvable
* references:
*
* http://es5.github.io/#x11.4.1
*
* This will only be apparent in cases where the user has suppressed warnings
* about deleting variables.
*/
exports.undefDeleteStrict = function (test) {
TestRun(test)
.addError(3, 10, "'aNullReference' is not defined.")
.test([
"(function() {",
" 'use strict';",
" delete aNullReference;",
"}());"
], { undef: true, "-W051": false });
test.done();
};
exports.unused = {};
exports.unused.basic = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/unused.js', 'utf8');
var allErrors = [
[22, 7, "'i' is defined but never used."],
[101, 5, "'inTry2' used out of scope."],
[117, 13, "'inTry9' was used before it was declared, which is illegal for 'let' variables."],
[118, 15, "'inTry10' was used before it was declared, which is illegal for 'const' variables."]
];
var testRun = TestRun(test);
allErrors.forEach(function (e) {
testRun.addError.apply(testRun, e);
});
testRun.test(src, { esnext: true });
var var_errors = allErrors.concat([
[1, 5, "'a' is defined but never used."],
[7, 9, "'c' is defined but never used."],
[15, 10, "'foo' is defined but never used."],
[20, 10, "'bar' is defined but never used."],
[36, 7, "'cc' is defined but never used."],
[39, 9, "'dd' is defined but never used."],
[58, 11, "'constUsed' is defined but never used."],
[62, 9, "'letUsed' is defined but never used."],
[63, 9, "'anotherUnused' is defined but never used."],
[91, 9, "'inTry6' is defined but never used."],
[94, 9, "'inTry9' is defined but never used."],
[95, 11, "'inTry10' is defined but never used."],
[99, 13, "'inTry4' is defined but never used."],
[122, 10, "'unusedRecurringFunc' is defined but never used."]
]);
var last_param_errors = [
[6, 18, "'f' is defined but never used."],
[28, 14, "'a' is defined but never used."],
[28, 17, "'b' is defined but never used."],
[28, 20, "'c' is defined but never used."],
[68, 5, "'y' is defined but never used."],
[69, 6, "'y' is defined but never used."],
[70, 9, "'z' is defined but never used."]
];
var all_param_errors = [
[15, 14, "'err' is defined but never used."],
[71, 6, "'y' is defined but never used."]
];
var true_run = TestRun(test, {esnext: true});
var_errors.slice().concat(last_param_errors).forEach(function (e) {
true_run.addError.apply(true_run, e);
});
true_run.test(src, { esnext: true, unused: true });
test.ok(!JSHINT(src, { esnext: true, unused: true }));
// Test checking all function params via unused="strict"
var all_run = TestRun(test);
var_errors.slice().concat(last_param_errors, all_param_errors).forEach(function (e) {
all_run.addError.apply(true_run, e);
});
all_run.test(src, { esnext: true, unused: "strict"});
// Test checking everything except function params
var vars_run = TestRun(test);
var_errors.forEach(function (e) { vars_run.addError.apply(vars_run, e); });
vars_run.test(src, { esnext: true, unused: "vars"});
var unused = JSHINT.data().unused;
test.equal(24, unused.length);
test.ok(unused.some(function (err) { return err.line === 1 && err.character == 5 && err.name === "a"; }));
test.ok(unused.some(function (err) { return err.line === 6 && err.character == 18 && err.name === "f"; }));
test.ok(unused.some(function (err) { return err.line === 7 && err.character == 9 && err.name === "c"; }));
test.ok(unused.some(function (err) { return err.line === 15 && err.character == 10 && err.name === "foo"; }));
test.ok(unused.some(function (err) { return err.line === 68 && err.character == 5 && err.name === "y"; }));
test.done();
};
// Regression test for gh-3362
exports.unused.es3Reserved = function (test) {
TestRun(test)
.addError(1, 5, "'abstract' is defined but never used.")
.addError(1, 15, "'boolean' is defined but never used.")
.addError(1, 24, "'byte' is defined but never used.")
.addError(1, 30, "'char' is defined but never used.")
.addError(1, 36, "'double' is defined but never used.")
.addError(1, 44, "'final' is defined but never used.")
.addError(1, 51, "'float' is defined but never used.")
.addError(1, 58, "'goto' is defined but never used.")
.addError(1, 64, "'int' is defined but never used.")
.addError(2, 5, "'long' is defined but never used.")
.addError(2, 11, "'native' is defined but never used.")
.addError(2, 19, "'short' is defined but never used.")
.addError(2, 26, "'synchronized' is defined but never used.")
.addError(2, 40, "'transient' is defined but never used.")
.addError(2, 51, "'volatile' is defined but never used.")
.test([
"var abstract, boolean, byte, char, double, final, float, goto, int;",
"var long, native, short, synchronized, transient, volatile;",
], {unused: true});
TestRun(test)
.test([
"var abstract, boolean, byte, char, double, final, float, goto, int;",
"var long, native, short, synchronized, transient, volatile;",
"void (abstract + boolean + byte + char + double + final + float + loat + goto + int);",
"void (long + native + short + synchronized + transient + volatile);"
], {unused: true});
test.done();
};
// Regression test for gh-2784
exports.unused.usedThroughShadowedDeclaration = function (test) {
var code = [
"(function() {",
" var x;",
" {",
" var x;",
" void x;",
" }",
"}());"
];
TestRun(test)
.addError(4, 9, "'x' is already defined.")
.test(code, { unused: true });
test.done();
};
exports.unused.unusedThroughShadowedDeclaration = function (test) {
var code = [
"(function() {",
" {",
" var x;",
" void x;",
" }",
" {",
" var x;",
" }",
"})();"
];
TestRun(test)
.addError(7, 11, "'x' is already defined.")
.test(code, { unused: true });
test.done();
};
exports.unused.hoisted = function (test) {
var code = [
"(function() {",
" {",
" var x;",
" }",
" {",
" var x;",
" }",
" void x;",
"}());"
];
TestRun(test)
.addError(6, 9, "'x' is already defined.")
.addError(8, 8, "'x' used out of scope.")
.test(code, { unused: true });
test.done();
};
exports.unused.crossBlocks = function (test) {
var code = fs.readFileSync(__dirname + '/fixtures/unused-cross-blocks.js', 'utf8');
TestRun(test)
.addError(15, 9, "'func4' is already defined.")
.addError(18, 9, "'func5' is already defined.")
.addError(41, 11, "'topBlock6' is already defined.")
.addError(44, 11, "'topBlock7' is already defined.")
.addError(56, 13, "'topBlock3' is already defined.")
.addError(59, 13, "'topBlock4' is already defined.")
.addError(9, 7, "'unusedFunc' is defined but never used.")
.addError(27, 9, "'unusedTopBlock' is defined but never used.")
.addError(52, 11, "'unusedNestedBlock' is defined but never used.")
.test(code, { unused: true });
TestRun(test)
.addError(15, 9, "'func4' is already defined.")
.addError(18, 9, "'func5' is already defined.")
.addError(41, 11, "'topBlock6' is already defined.")
.addError(44, 11, "'topBlock7' is already defined.")
.addError(56, 13, "'topBlock3' is already defined.")
.addError(59, 13, "'topBlock4' is already defined.")
.test(code);
test.done();
};
// Regression test for gh-3354
exports.unused.methodNames = function (test) {
TestRun(test, "object methods - ES5")
.test([
"var p;",
"void {",
" get p() { void p; },",
" set p(_) { void p; void _; }",
"};"
], { unused: true, esversion: 5 });
TestRun(test, "object methods - ES6")
.test([
"var m, g;",
"void {",
" m() { void m; },",
" *g() { yield g; }",
"};"
], { unused: true, esversion: 6 });
TestRun(test, "object methods - ES8")
.test([
"var m;",
"void {",
" async m() { void m; }",
"};"
], { unused: true, esversion: 8 });
TestRun(test, "object methods - ES9")
.test([
"var m;",
"void {",
" async * m() { yield m; }",
"};"
], { unused: true, esversion: 9 });
TestRun(test, "class methods - ES6")
.test([
"var m, g, p, s;",
"void class {",
" m() { void m; }",
" *g() { yield g; }",
" get p() { void p; }",
" set p() { void p; }",
" static s() { void s; }",
"};"
], { unused: true, esversion: 6 });
TestRun(test, "class methods - ES8")
.test([
"var m;",
"void class {",
" async m() { void m; }",
"};"
], { unused: true, esversion: 8 });
TestRun(test, "class methods - ES9")
.test([
"var m;",
"void class {",
" async * m() { yield m; }",
"};"
], { unused: true, esversion: 9 });
test.done();
};
exports['param overrides function name expression'] = function (test) {
TestRun(test)
.test([
"var A = function B(B) {",
" return B;",
"};",
"A();"
], { undef: true, unused: "strict" });
test.done();
};
exports['let can re-use function and class name'] = function (test) {
TestRun(test)
.test([
"var A = function B(C) {",
" let B = C;",
" return B;",
"};",
"A();",
"var D = class E { constructor(F) { let E = F; return E; }};",
"D();"
], { undef: true, unused: "strict", esnext: true });
test.done();
};
exports['unused with param destructuring'] = function(test) {
var code = [
"let b = ([...args], a) => a;",
"b = args => true;",
"b = function([...args], a) { return a; };",
"b = function([args], a) { return a; };",
"b = function({ args }, a) { return a; };",
"b = function({ a: args }, a) { return a; };",
"b = function({ a: [args] }, a) { return a; };",
"b = function({ a: [args] }, a) { return a; };"
];
TestRun(test)
.addError(2, 5, "'args' is defined but never used.")
.test(code, { esnext: true, unused: true });
TestRun(test)
.addError(1, 14, "'args' is defined but never used.")
.addError(2, 5, "'args' is defined but never used.")
.addError(3, 18, "'args' is defined but never used.")
.addError(4, 15, "'args' is defined but never used.")
.addError(5, 16, "'args' is defined but never used.")
.addError(6, 19, "'args' is defined but never used.")
.addError(7, 20, "'args' is defined but never used.")
.addError(8, 20, "'args' is defined but never used.")
.test(code, { esnext: true, unused: "strict" });
test.done();
};
exports['unused data with options'] = function (test) {
// see gh-1894 for discussion on this test
var code = [
"function func(placeHolder1, placeHolder2, used, param) {",
" used = 1;",
"}"
];
var expectedVarUnused = [{ name: 'func', line: 1, character: 10 }];
var expectedParamUnused = [{ name: 'param', line: 1, character: 49 }];
var expectedPlaceholderUnused = [{ name: 'placeHolder2', line: 1, character: 29 },
{ name: 'placeHolder1', line: 1, character: 15 }];
var expectedAllUnused = expectedParamUnused.concat(expectedPlaceholderUnused, expectedVarUnused);
var expectedVarAndParamUnused = expectedParamUnused.concat(expectedVarUnused);
// true
TestRun(test)
.addError(1, 10, "'func' is defined but never used.")
.addError(1, 49, "'param' is defined but never used.")
.test(code, { unused: true });
var unused = JSHINT.data().unused;
test.deepEqual(expectedVarAndParamUnused, unused);
// false
TestRun(test)
.test(code, { unused: false });
unused = JSHINT.data().unused;
test.deepEqual(expectedVarUnused, unused);
// strict
TestRun(test)
.addError(1, 10, "'func' is defined but never used.")
.addError(1, 15, "'placeHolder1' is defined but never used.")
.addError(1, 29, "'placeHolder2' is defined but never used.")
.addError(1, 49, "'param' is defined but never used.")
.test(code, { unused: "strict" });
unused = JSHINT.data().unused;
test.deepEqual(expectedAllUnused, unused);
// vars
TestRun(test)
.addError(1, 10, "'func' is defined but never used.")
.test(code, { unused: "vars" });
unused = JSHINT.data().unused;
test.deepEqual(expectedAllUnused, unused);
test.done();
};
exports['unused with global override'] = function (test) {
var code;
code = [
"alert();",
"function alert() {}"
];
TestRun(test)
.test(code, { unused: true, undef: true, devel: true, latedef: false });
test.done();
};
// Regressions for "unused" getting overwritten via comment (GH-778)
exports['unused overrides'] = function (test) {
var code;
code = ['function foo(a) {', '/*jshint unused:false */', '}', 'foo();'];
TestRun(test).test(code, {es3: true, unused: true});
code = ['function foo(a, b, c) {', '/*jshint unused:vars */', 'var i = b;', '}', 'foo();'];
TestRun(test)
.addError(3, 5, "'i' is defined but never used.")
.test(code, {es3: true, unused: true});
code = ['function foo(a, b, c) {', '/*jshint unused:true */', 'var i = b;', '}', 'foo();'];
TestRun(test)
.addError(1, 20, "'c' is defined but never used.")
.addError(3, 5, "'i' is defined but never used.")
.test(code, {es3: true, unused: "strict"});
code = ['function foo(a, b, c) {', '/*jshint unused:strict */', 'var i = b;', '}', 'foo();'];
TestRun(test)
.addError(1, 14, "'a' is defined but never used.")
.addError(1, 20, "'c' is defined but never used.")
.addError(3, 5, "'i' is defined but never used.")
.test(code, {es3: true, unused: true});
code = ['/*jshint unused:vars */', 'function foo(a, b) {}', 'foo();'];
TestRun(test).test(code, {es3: true, unused: "strict"});
code = ['/*jshint unused:vars */', 'function foo(a, b) {', 'var i = 3;', '}', 'foo();'];
TestRun(test)
.addError(3, 5, "'i' is defined but never used.")
.test(code, {es3: true, unused: "strict"});
code = ['/*jshint unused:badoption */', 'function foo(a, b) {', 'var i = 3;', '}', 'foo();'];
TestRun(test)
.addError(1, 1, "Bad option value.")
.addError(2, 17, "'b' is defined but never used.")
.addError(2, 14, "'a' is defined but never used.")
.addError(3, 5, "'i' is defined but never used.")
.test(code, {es3: true, unused: "strict"});
test.done();
};
exports['unused overrides esnext'] = function (test) {
var code;
code = ['function foo(a) {', '/*jshint unused:false */', '}', 'foo();'];
TestRun(test).test(code, {esnext: true, unused: true});
code = ['function foo(a, b, c) {', '/*jshint unused:vars */', 'let i = b;', '}', 'foo();'];
TestRun(test)
.addError(3, 5, "'i' is defined but never used.")
.test(code, {esnext: true, unused: true});
code = ['function foo(a, b, c) {', '/*jshint unused:true */', 'let i = b;', '}', 'foo();'];
TestRun(test)
.addError(1, 20, "'c' is defined but never used.")
.addError(3, 5, "'i' is defined but never used.")
.test(code, {esnext: true, unused: "strict"});
code = ['function foo(a, b, c) {', '/*jshint unused:strict */', 'let i = b;', '}', 'foo();'];
TestRun(test)
.addError(1, 14, "'a' is defined but never used.")
.addError(1, 20, "'c' is defined but never used.")
.addError(3, 5, "'i' is defined but never used.")
.test(code, {esnext: true, unused: true});
code = ['/*jshint unused:vars */', 'function foo(a, b) {', 'let i = 3;', '}', 'foo();'];
TestRun(test)
.addError(3, 5, "'i' is defined but never used.")
.test(code, {esnext: true, unused: "strict"});
code = ['/*jshint unused:badoption */', 'function foo(a, b) {', 'let i = 3;', '}', 'foo();'];
TestRun(test)
.addError(1, 1, "Bad option value.")
.addError(2, 17, "'b' is defined but never used.")
.addError(2, 14, "'a' is defined but never used.")
.addError(3, 5, "'i' is defined but never used.")
.test(code, {esnext: true, unused: "strict"});
test.done();
};
exports['unused with latedef function'] = function (test) {
var code;
// Regression for gh-2363, gh-2282, gh-2191
code = ['exports.a = a;',
'function a() {}',
'exports.b = function() { b(); };',
'function b() {}',
'(function() {',
' function c() { d(); }',
' window.c = c;',
' function d() {}',
'})();',
'var e;',
'(function() {',
' e();',
' function e(){}',
'})();',
''];
TestRun(test)
.addError(10, 5, "'e' is defined but never used.")
.test(code, {undef: false, unused: true, node: true});
test.done();
};
// Regression test for `undef` to make sure that ...
exports['undef in a function scope'] = function (test) {
var src = fixture('undef_func.js');
// Make sure that the lint is clean with and without undef.
TestRun(test).test(src, {es3: true});
TestRun(test).test(src, {es3: true, undef: true });
test.done();
};
/** Option `scripturl` allows the use of javascript-type URLs */
exports.scripturl = function (test) {
var code = [
"var foo = { 'count': 12, 'href': 'javascript:' };",
"foo = 'javascript:' + 'xyz';"
],
src = fs.readFileSync(__dirname + '/fixtures/scripturl.js', 'utf8');
// Make sure there is an error
TestRun(test)
.addError(1, 47, "Script URL.")
.addError(2, 20, "Script URL.") // 2 times?
.addError(2, 7, "JavaScript URL.")
.test(code, {es3: true});
// Make sure the error goes away when javascript URLs are tolerated
TestRun(test).test(code, { es3: true, scripturl: true });
// Make sure an error does not exist for labels that look like URLs (GH-1013)
TestRun(test)
.test(src, {es3: true});
test.done();
};
/**
* Option `forin` disallows the use of for in loops without hasOwnProperty.
*
* The for in statement is used to loop through the names of properties
* of an object, including those inherited through the prototype chain.
* The method hasOwnPropery is used to check if the property belongs to
* an object or was inherited through the prototype chain.
*/
exports.forin = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/forin.js', 'utf8');
var msg = 'The body of a for in should be wrapped in an if statement to filter unwanted ' +
'properties from the prototype.';
// Make sure there are no other errors
TestRun(test).test(src, {es3: true});
// Make sure it fails when forin is true
TestRun(test)
.addError(15, 1, msg)
.addError(23, 1, msg)
.addError(37, 3, msg)
.addError(43, 9, msg)
.addError(73, 1, msg)
.test(src, { es3: true, forin: true });
test.done();
};
/**
* Option `loopfunc` allows you to use function expression in the loop.
* E.g.:
* while (true) x = function (test) {};
*
* This is generally a bad idea since it is too easy to make a
* closure-related mistake.
*/
exports.loopfunc = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/loopfunc.js', 'utf8');
// By default, not functions are allowed inside loops
TestRun(test)
.addError(4, 13, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (v)")
.addError(8, 13, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (v)")
.addError(20, 11, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (nonExistent)")
.addError(25, 13, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (p)")
.addError(12, 5, "Function declarations should not be placed in blocks. Use a function " +
"expression or move the statement to the top of the outer function.")
.addError(42, 7, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (i)")
.test(src, {es3: true});
// When loopfunc is true, only function declaration should fail.
// Expressions are okay.
TestRun(test)
.addError(12, 5, "Function declarations should not be placed in blocks. Use a function " +
"expression or move the statement to the top of the outer function.")
.test(src, { es3: true, loopfunc: true });
var es6LoopFuncSrc = [
"for (var i = 0; i < 5; i++) {",
" var y = w => i;",
"}",
"for (i = 0; i < 5; i++) {",
" var z = () => i;",
"}",
"for (i = 0; i < 5; i++) {",
" y = i => i;", // not capturing
"}",
"for (i = 0; i < 5; i++) {",
" y = { a() { return i; } };",
"}",
"for (i = 0; i < 5; i++) {",
" y = class { constructor() { this.i = i; }};",
"}",
"for (i = 0; i < 5; i++) {",
" y = { a() { return () => i; } };",
"}"
];
TestRun(test)
.addError(2, 13, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (i)")
.addError(5, 11, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (i)")
.addError(11, 9, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (i)")
.addError(14, 15, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (i)")
.addError(17, 9, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (i)")
.test(es6LoopFuncSrc, {esnext: true});
// functions declared in the expressions that loop should warn
var src2 = [
"for(var i = 0; function a(){return i;}; i++) { break; }",
"var j;",
"while(function b(){return j;}){}",
"for(var c = function(){return j;};;){c();}"];
TestRun(test)
.addError(1, 25, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (i)")
.addError(3, 16, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (j)")
.test(src2, { es3: true, loopfunc: false, boss: true });
TestRun(test, "Allows closing over immutable bindings (ES5)")
.addError(6, 8, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (outerVar)")
.addError(7, 8, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (innerVar)")
.test([
"var outerVar;",
"",
"while (false) {",
" var innerVar;",
"",
" void function() { var localVar; return outerVar; };",
" void function() { var localVar; return innerVar; };",
" void function() { var localVar; return localVar; };",
"",
"}",
]);
TestRun(test, "Allows closing over immutable bindings (globals)")
.addError(8, 8, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (mutableGlobal)")
.addError(15, 10, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (immutableGlobal)")
.test([
"/* globals immutableGlobal: false, mutableGlobal: true */",
"while (false) {",
" void function() { return eval; };",
" void function() { return Infinity; };",
" void function() { return NaN; };",
" void function() { return undefined; };",
" void function() { return immutableGlobal; };",
" void function() { return mutableGlobal; };",
"}",
"",
"// Should recognize shadowing",
"(function() {",
" var immutableGlobal;",
" while (false) {",
" void function() { return immutableGlobal; };",
" }",
"}());"
]);
TestRun(test, "Allows closing over immutable bindings (ES2015)")
.addError(10, 8, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (outerLet)")
.addError(11, 8, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (innerLet)")
.addError(18, 8, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (OuterClass)")
.addError(19, 8, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (InnerClass)")
.test([
"let outerLet;",
"const outerConst = 0;",
"class OuterClass {}",
"",
"while (false) {",
" let innerLet;",
" const innerConst = 0;",
" class InnerClass {}",
"",
" void function() { let localLet; return outerLet; };",
" void function() { let localLet; return innerLet; };",
" void function() { let localLet; return localLet; };",
"",
" void function() { const localConst = 0; return outerConst; };",
" void function() { const localConst = 0; return innerConst; };",
" void function() { const localConst = 0; return localConst; };",
"",
" void function() { class LocalClass {} return OuterClass; };",
" void function() { class LocalClass {} return InnerClass; };",
" void function() { class LocalClass {} return LocalClass; };",
"}"
], { esversion: 2015 });
TestRun(test, "W083 lists multiple outer scope variables")
.addError(3, 11, "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (a, b)")
.test([
"var a, b;",
"for (;;) {",
" var f = function() {",
" return a + b;",
" };",
"}"
]);
test.done();
};
/** Option `boss` unlocks some useful but unsafe features of JavaScript. */
exports.boss = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/boss.js', 'utf8');
// By default, warn about suspicious assignments
TestRun(test)
.addError(1, 7, 'Expected a conditional expression and instead saw an assignment.')
.addError(4, 12, 'Expected a conditional expression and instead saw an assignment.')
.addError(7, 15, 'Expected a conditional expression and instead saw an assignment.')
.addError(12, 12, 'Expected a conditional expression and instead saw an assignment.')
// GH-657
.addError(14, 7, 'Expected a conditional expression and instead saw an assignment.')
.addError(17, 12, 'Expected a conditional expression and instead saw an assignment.')
.addError(20, 15, 'Expected a conditional expression and instead saw an assignment.')
.addError(25, 12, 'Expected a conditional expression and instead saw an assignment.')
// GH-670
.addError(28, 12, "Did you mean to return a conditional instead of an assignment?")
.addError(32, 14, "Did you mean to return a conditional instead of an assignment?")
.test(src, {es3: true});
// But if you are the boss, all is good
TestRun(test).test(src, { es3: true, boss: true });
test.done();
};
/**
* Options `eqnull` allows you to use '== null' comparisons.
* It is useful when you want to check if value is null _or_ undefined.
*/
exports.eqnull = function (test) {
var code = [
'if (e == null) doSomething();',
'if (null == e) doSomething();',
'if (e != null) doSomething();',
'if (null != e) doSomething();',
];
// By default, warn about `== null` comparison
/**
* This test previously asserted the issuance of warning W041.
* W041 has since been removed, but the test is maintained in
* order to discourage regressions.
*/
TestRun(test)
.test(code, {es3: true});
// But when `eqnull` is true, no questions asked
TestRun(test).test(code, { es3: true, eqnull: true });
// Make sure that `eqnull` has precedence over `eqeqeq`
TestRun(test).test(code, { es3: true, eqeqeq: true, eqnull: true });
test.done();
};
/**
* Option `supernew` allows you to use operator `new` with anonymous functions
* and objects without invocation.
*
* Ex.:
* new function (test) { ... };
* new Date;
*/
exports.supernew = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/supernew.js', 'utf8');
TestRun(test)
.addError(1, 9, "Weird construction. Is 'new' necessary?")
.addError(9, 1, "Missing '()' invoking a constructor.")
.addError(11, 13, "Missing '()' invoking a constructor.")
.test(src, {es3: true});
TestRun(test).test(src, { es3: true, supernew: true });
test.done();
};
/** Option `bitwise` disallows the use of bitwise operators. */
exports.bitwise = function (test) {
var unOps = [ "~" ];
var binOps = [ "&", "|", "^", "<<", ">>", ">>>" ];
var modOps = [ "&=", "|=", "^=", "<<=", ">>=", ">>>=" ];
var i, op;
for (i = 0; i < unOps.length; i += 1) {
op = unOps[i];
TestRun(test)
.test("var b = " + op + "a;", {es3: true});
TestRun(test)
.addError(1, 9, "Unexpected use of '" + op + "'.")
.test("var b = " + op + "a;", {es3: true, bitwise: true});
}
for (i = 0; i < binOps.length; i += 1) {
op = binOps[i];
TestRun(test)
.test("var c = a " + op + " b;", {es3: true});
TestRun(test)
.addError(1, 11, "Unexpected use of '" + op + "'.")
.test("var c = a " + op + " b;", {es3: true, bitwise: true});
}
for (i = 0; i < modOps.length; i += 1) {
op = modOps[i];
TestRun(test)
.test("b " + op + " a;", {es3: true});
TestRun(test)
.addError(1, 3, "Unexpected use of '" + op + "'.")
.test("b " + op + " a;", {es3: true, bitwise: true});
}
test.done();
};
/** Option `debug` allows the use of debugger statements. */
exports.debug = function (test) {
var code = 'function test () { debugger; return true; }';
// By default disallow debugger statements.
TestRun(test)
.addError(1, 20, "Forgotten 'debugger' statement?")
.test(code, {es3: true});
// But allow them if debug is true.
TestRun(test).test(code, { es3: true, debug: true });
test.done();
};
/** `debugger` statements without semicolons are found on the correct line */
exports.debuggerWithoutSemicolons = function (test) {
var src = [
"function test () {",
"debugger",
"return true; }"
];
// Ensure we mark the correct line when finding debugger statements
TestRun(test)
.addError(2, 1, "Forgotten 'debugger' statement?")
.test(src, {es3: true, asi: true});
test.done();
};
/** Option `eqeqeq` requires you to use === all the time. */
exports.eqeqeq = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/eqeqeq.js', 'utf8');
/**
* This test previously asserted the issuance of warning W041.
* W041 has since been removed, but the test is maintained in
* order to discourage regressions.
*/
TestRun(test)
.test(src, {es3: true});
TestRun(test)
.addError(2, 13, "Expected '===' and instead saw '=='.")
.addError(5, 13, "Expected '!==' and instead saw '!='.")
.addError(8, 13, "Expected '===' and instead saw '=='.")
.test(src, { es3: true, eqeqeq: true });
test.done();
};
/** Option `evil` allows the use of eval. */
exports.evil = function (test) {
var src = [
"eval('hey();');",
"document.write('');",
"document.writeln('');",
"window.execScript('xyz');",
"new Function('xyz();');",
"setTimeout('xyz();', 2);",
"setInterval('xyz();', 2);",
"var t = document['eval']('xyz');"
];
TestRun(test)
.addError(1, 1, "eval can be harmful.")
.addError(2, 1, "document.write can be a form of eval.")
.addError(3, 1, "document.write can be a form of eval.")
.addError(4, 18, "eval can be harmful.")
.addError(5, 13, "The Function constructor is a form of eval.")
.addError(6, 1, "Implied eval. Consider passing a function instead of a string.")
.addError(7, 1, "Implied eval. Consider passing a function instead of a string.")
.addError(8, 24, "eval can be harmful.")
.test(src, { es3: true, browser: true });
TestRun(test).test(src, { es3: true, evil: true, browser: true });
test.done();
};
/**
* Option `immed` forces you to wrap immediate invocations in parens.
*
* Functions in JavaScript can be immediately invoce but that can confuse
* readers of your code. To make it less confusing, wrap the invocations in
* parens.
*
* E.g. (note the parens):
* var a = (function (test) {
* return 'a';
* }());
* console.log(a); // --> 'a'
*/
exports.immed = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/immed.js', 'utf8');
TestRun(test).test(src, {es3: true});
TestRun(test)
.addError(3, 3, "Wrap an immediate function invocation in parens " +
"to assist the reader in understanding that the expression " +
"is the result of a function, and not the function itself.")
.addError(13, 9, "Wrapping non-IIFE function literals in parens is unnecessary.")
.test(src, { es3: true, immed: true });
// Regression for GH-900
TestRun(test)
//.addError(1, 23232323, "Expected an assignment or function call and instead saw an expression.")
.addError(1, 31, "Expected an identifier and instead saw ')'.")
.addError(1, 30, "Expected an assignment or function call and instead saw an expression.")
.addError(1, 14, "Unmatched '{'.")
.addError(1, 31, "Expected an assignment or function call and instead saw an expression.")
.addError(1, 31, "Missing semicolon.")
.addError(1, 32, "Unrecoverable syntax error. (100% scanned).")
.test("(function () { if (true) { }());", { es3: true, immed: true });
test.done();
};
/** Option `plusplus` prohibits the use of increments/decrements. */
exports.plusplus = function (test) {
var ops = [ '++', '--' ];
for (var i = 0, op; op = ops[i]; i += 1) {
TestRun(test).test('var i = j' + op + ';', {es3: true});
TestRun(test).test('var i = ' + op + 'j;', {es3: true});
}
for (i = 0, op = null; op = ops[i]; i += 1) {
TestRun(test)
.addError(1, 10, "Unexpected use of '" + op + "'.")
.test('var i = j' + op + ';', { es3: true, plusplus: true });
TestRun(test)
.addError(1, 9, "Unexpected use of '" + op + "'.")
.test('var i = ' + op + 'j;', { es3: true, plusplus: true });
}
test.done();
};
/**
* Option `newcap` requires constructors to be capitalized.
*
* Constructors are functions that are designed to be used with the `new` statement.
* `new` creates a new object and binds it to the implied this parameter.
* A constructor executed without new will have its this assigned to a global object,
* leading to errors.
*
* Unfortunately, JavaScript gives us absolutely no way of telling if a function is a
* constructor. There is a convention to capitalize all constructor names to prevent
* those mistakes. This option enforces that convention.
*/
exports.newcap = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/newcap.js', 'utf8');
TestRun(test).test(src, {es3: true}); // By default, everything is fine
// When newcap is true, enforce the conventions
TestRun(test)
.addError(1, 15, 'A constructor name should start with an uppercase letter.')
.addError(5, 7, "Missing 'new' prefix when invoking a constructor.")
.addError(10, 15, "A constructor name should start with an uppercase letter.")
.addError(14, 13, "A constructor name should start with an uppercase letter.")
.test(src, { es3: true, newcap: true });
test.done();
};
/** Option `sub` allows all forms of subscription. */
exports.sub = function (test) {
TestRun(test)
.addError(1, 17, "['prop'] is better written in dot notation.")
.test("window.obj = obj['prop'];", {es3: true});
TestRun(test).test("window.obj = obj['prop'];", { es3: true, sub: true });
test.done();
};
/** Option `strict` requires you to use "use strict"; */
exports.strict = function (test) {
var code = "(function (test) { return; }());";
var code1 = '(function (test) { "use strict"; return; }());';
var code2 = "var obj = Object({ foo: 'bar' });";
var code3 = "'use strict'; \n function hello() { return; }";
var src = fs.readFileSync(__dirname + '/fixtures/strict_violations.js', 'utf8');
var src2 = fs.readFileSync(__dirname + '/fixtures/strict_incorrect.js', 'utf8');
var src3 = fs.readFileSync(__dirname + '/fixtures/strict_newcap.js', 'utf8');
TestRun(test).test(code, {es3: true});
TestRun(test).test(code1, {es3: true});
var run = TestRun(test)
.addError(1, 20, 'Missing "use strict" statement.');
run.test(code, { es3: true, strict: true });
run
.addError(1, 26, 'Missing "use strict" statement.')
.test(code, { es3: true, strict: "global" });
TestRun(test).test(code, { es3: true, strict: "implied" });
TestRun(test).test(code1, { es3: true, strict: true });
TestRun(test).test(code1, { es3: true, strict: "global" });
TestRun(test)
.addError(1, 20, 'Unnecessary directive "use strict".')
.test(code1, { es3: true, strict: "implied" });
// Test for strict mode violations
run = TestRun(test)
.addError(4, 36, "If a strict mode function is executed using function invocation, its 'this' value will be undefined.")
.addError(7, 52, 'Strict violation.')
.addError(8, 52, 'Strict violation.');
run.test(src, { es3: true, strict: true });
run.test(src, { es3: true, strict: "global" });
run = TestRun(test)
.addError(4, 5, 'Expected an assignment or function call and instead saw an expression.')
.addError(9, 17, 'Missing semicolon.')
.addError(28, 9, 'Expected an assignment or function call and instead saw an expression.')
.addError(53, 9, 'Expected an assignment or function call and instead saw an expression.');
run.test(src2, { es3: true, strict: false });
TestRun(test)
.test(src3, {es3 : true});
TestRun(test).test(code2, { es3: true, strict: true });
TestRun(test)
.addError(1, 33, 'Missing "use strict" statement.')
.test(code2, { es3: true, strict: "global" });
TestRun(test).test(code3, { strict: "global"});
run = TestRun(test)
.addError(1, 1, 'Use the function form of "use strict".');
run.test(code3, { strict: true });
run.addError(1, 1, 'Unnecessary directive "use strict".')
.test(code3, { strict: "implied" });
[ true, false, "global", "implied" ].forEach(function(val) {
JSHINT("/*jshint strict: " + val + " */");
test.strictEqual(JSHINT.data().options.strict, val);
});
TestRun(test)
.addError(1, 1, "Bad option value.")
.test("/*jshint strict: foo */");
TestRun(test, "environments have precedence over 'strict: true'")
.test(code3, { strict: true, node: true });
TestRun(test, "gh-2668")
.addError(1, 6, "Missing \"use strict\" statement.")
.test("a = 2;", { strict: "global" });
TestRun(test, "Warning location, missing semicolon (gh-3528)")
.addError(1, 1, "Use the function form of \"use strict\".")
.addError(1, 13, "Missing semicolon.")
.test("'use strict'\n");
TestRun(test, "Warning location among other directives")
.addError(2, 1, "Use the function form of \"use strict\".")
.test([
"'use another-directive';",
"'use strict';",
"'use a-third-directive';"
]);
test.done();
};
/**
* This test asserts sub-optimal behavior.
*
* In the "browserify", "node" and "phantomjs" environments, user code is not
* executed in the global scope directly. This means that top-level `use
* strict` directives, although seemingly global, do *not* enable ES5 strict
* mode for other scripts executed in the same environment. Because of this,
* the `strict` option should enforce a top-level `use strict` directive in
* those environments.
*
* The `strict` option was implemented without consideration for these
* environments, so the sub-optimal behavior must be preserved for backwards
* compatability.
*
* TODO: Interpret `strict: true` as `strict: global` in the Browserify,
* Node.js, and PhantomJS environments, and remove this test in JSHint 3
*/
exports.strictEnvs = function (test) {
var partialStrict = [
"void 0;",
"(function() { void 0; }());",
"(function() { 'use strict'; void 0; }());"
];
TestRun(test, "")
.addError(2, 15, "Missing \"use strict\" statement.")
.test(partialStrict, { strict: true, browserify: true });
TestRun(test, "")
.addError(2, 15, "Missing \"use strict\" statement.")
.test(partialStrict, { strict: true, node: true });
TestRun(test, "")
.addError(2, 15, "Missing \"use strict\" statement.")
.test(partialStrict, { strict: true, phantom: true });
partialStrict = [
'(() =>',
' void 0',
')();',
]
TestRun(test, "Block-less arrow functions in the Browserify env")
.addError(3, 1, "Missing \"use strict\" statement.")
.test(partialStrict, { esversion: 6, strict: true, browserify: true });
TestRun(test, "Block-less arrow function in the Node.js environment")
.addError(3, 1, "Missing \"use strict\" statement.")
.test(partialStrict, { esversion: 6, strict: true, node: true });
TestRun(test, "Block-less arrow function in the PhantomJS environment")
.addError(3, 1, "Missing \"use strict\" statement.")
.test(partialStrict, { esversion: 6, strict: true, phantom: true });
test.done();
};
/**
* The following test asserts sub-optimal behavior.
*
* Through the `strict` and `globalstrict` options, JSHint can be configured to
* issue warnings when code is not in strict mode. Historically, JSHint has
* issued these warnings on a per-statement basis in global code, leading to
* "noisy" output through the repeated reporting of the missing directive.
*/
exports.strictNoise = function (test) {
TestRun(test, "global scope")
.addError(1, 7, "Missing \"use strict\" statement.")
.addError(2, 7, "Missing \"use strict\" statement.")
.test([
"void 0;",
"void 0;",
], { strict: true, globalstrict: true });
TestRun(test, "function scope")
.addError(2, 3, "Missing \"use strict\" statement.")
.test([
"(function() {",
" void 0;",
" void 0;",
"}());",
], { strict: true });
TestRun(test, "function scope")
.addError(2, 3, "Missing \"use strict\" statement.")
.test([
"(function() {",
" (function() {",
" void 0;",
" void 0;",
" }());",
"}());",
], { strict: true });
test.done();
};
/** Option `globalstrict` allows you to use global "use strict"; */
exports.globalstrict = function (test) {
var code = [
'"use strict";',
'function hello() { return; }'
];
TestRun(test)
.addError(1, 1, 'Use the function form of "use strict".')
.test(code, { es3: true, strict: true });
TestRun(test).test(code, { es3: true, globalstrict: true });
// Check that globalstrict also enabled strict
TestRun(test)
.addError(1, 26, 'Missing "use strict" statement.')
.test(code[1], { es3: true, globalstrict: true });
// Don't enforce "use strict"; if strict has been explicitly set to false
TestRun(test).test(code[1], { es3: true, globalstrict: true, strict: false });
TestRun(test, "co-occurence with 'strict: global' (via configuration)")
.addError(0, 0, "Incompatible values for the 'strict' and 'globalstrict' linting options. (0% scanned).")
.test("this is not JavaScript", { strict: "global", globalstrict: false });
TestRun(test, "co-occurence with 'strict: global' (via configuration)")
.addError(0, 0, "Incompatible values for the 'strict' and 'globalstrict' linting options. (0% scanned).")
.test("this is not JavaScript", { strict: "global", globalstrict: true });
TestRun(test, "co-occurence with 'strict: global' (via in-line directive")
.addError(2, 1, "Incompatible values for the 'strict' and 'globalstrict' linting options. (66% scanned).")
.test([
"",
"// jshint globalstrict: true",
"this is not JavaScript"
], { strict: "global" });
TestRun(test, "co-occurence with 'strict: global' (via in-line directive")
.addError(2, 1, "Incompatible values for the 'strict' and 'globalstrict' linting options. (66% scanned).")
.test([
"",
"// jshint globalstrict: false",
"this is not JavaScript"
], { strict: "global" });
TestRun(test, "co-occurence with 'strict: global' (via in-line directive")
.addError(2, 1, "Incompatible values for the 'strict' and 'globalstrict' linting options. (66% scanned).")
.test([
"",
"// jshint strict: global",
"this is not JavaScript"
], { globalstrict: true });
TestRun(test, "co-occurence with 'strict: global' (via in-line directive")
.addError(2, 1, "Incompatible values for the 'strict' and 'globalstrict' linting options. (66% scanned).")
.test([
"",
"// jshint strict: global",
"this is not JavaScript"
], { globalstrict: false });
TestRun(test, "co-occurence with internally-set 'strict: gobal' (module code)")
.test(code, { strict: true, globalstrict: false, esnext: true, module: true });
TestRun(test, "co-occurence with internally-set 'strict: gobal' (Node.js code)")
.test(code, { strict: true, globalstrict: false, node: true });
TestRun(test, "co-occurence with internally-set 'strict: gobal' (Phantom.js code)")
.test(code, { strict: true, globalstrict: false, phantom: true });
TestRun(test, "co-occurence with internally-set 'strict: gobal' (Browserify code)")
.test(code, { strict: true, globalstrict: false, browserify: true });
// Check that we can detect missing "use strict"; statement for code that is
// not inside a function
code = [
"var a = 1;",
"a += 1;",
"function func() {}"
];
TestRun(test)
.addError(1, 10, 'Missing "use strict" statement.')
.addError(2, 7, 'Missing "use strict" statement.')
.test(code, { globalstrict: true, strict: true });
// globalscript does not prevent you from using only the function-mode
// "use strict";
code = '(function (test) { "use strict"; return; }());';
TestRun(test).test(code, { globalstrict: true, strict: true });
TestRun(test, "gh-2661")
.test("'use strict';", { strict: false, globalstrict: true });
TestRun(test, "gh-2836 (1)")
.test([
"// jshint globalstrict: true",
// The specific option set by the following directive is not relevant.
// Any option set by another directive will trigger the regression.
"// jshint undef: true"
]);
TestRun(test, "gh-2836 (2)")
.test([
"// jshint strict: true, globalstrict: true",
// The specific option set by the following directive is not relevant.
// Any option set by another directive will trigger the regression.
"// jshint undef: true"
]);
test.done();
};
/** Option `laxbreak` allows you to insert newlines before some operators. */
exports.laxbreak = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/laxbreak.js', 'utf8');
TestRun(test)
.addError(2, 5, "Misleading line break before ','; readers may interpret this as an expression boundary.")
.addError(3, 3, "Comma warnings can be turned off with 'laxcomma'.")
.addError(12, 10, "Misleading line break before ','; readers may interpret this as an expression boundary.")
.test(src, { es3: true });
var ops = [ '||', '&&', '*', '/', '%', '+', '-', '>=',
'==', '===', '!=', '!==', '>', '<', '<=', 'instanceof' ];
for (var i = 0, op, code; op = ops[i]; i += 1) {
code = ['var a = b ', op + ' c;'];
TestRun(test)
.addError(2, 1, "Misleading line break before '" + op + "'; readers may interpret this as an expression boundary.")
.test(code, { es3: true });
TestRun(test).test(code, { es3: true, laxbreak: true });
}
code = [ 'var a = b ', '? c : d;' ];
TestRun(test)
.addError(2, 1, "Misleading line break before '?'; readers may interpret this as an expression boundary.")
.test(code, { es3: true });
TestRun(test).test(code, { es3: true, laxbreak: true });
test.done();
};
exports.validthis = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/strict_this.js', 'utf8');
TestRun(test)
.addError(8, 9, "If a strict mode function is executed using function invocation, its 'this' value will be undefined.")
.addError(9, 19, "If a strict mode function is executed using function invocation, its 'this' value will be undefined.")
.addError(11, 19, "If a strict mode function is executed using function invocation, its 'this' value will be undefined.")
.test(src, {es3: true});
src = fs.readFileSync(__dirname + '/fixtures/strict_this2.js', 'utf8');
TestRun(test).test(src, {es3: true});
// Test for erroneus use of validthis
var code = ['/*jshint validthis:true */', 'hello();'];
TestRun(test)
.addError(1, 1, "Option 'validthis' can't be used in a global scope.")
.test(code, {es3: true});
code = ['function x() {', '/*jshint validthis:heya */', 'hello();', '}'];
TestRun(test)
.addError(2, 1, "Bad option value.")
.test(code, {es3: true});
test.done();
};
/*
* Test string relevant options
* multistr allows multiline strings
*/
exports.strings = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/strings.js', 'utf8');
TestRun(test)
.addError(9, 20, "Unclosed string.")
.addError(10, 1, "Unclosed string.")
.addError(15, 1, "Unclosed string.")
.addError(25, 16, "Octal literals are not allowed in strict mode.")
.test(src, { es3: true, multistr: true });
TestRun(test)
.addError(3, 21, "Bad escaping of EOL. Use option multistr if needed.")
.addError(4, 2, "Bad escaping of EOL. Use option multistr if needed.")
.addError(9, 20, "Unclosed string.")
.addError(10, 1, "Unclosed string.")
.addError(14, 21, "Bad escaping of EOL. Use option multistr if needed.")
.addError(15, 1, "Unclosed string.")
.addError(25, 16, "Octal literals are not allowed in strict mode.")
.addError(29, 36, "Bad escaping of EOL. Use option multistr if needed.")
.test(src, { es3: true });
test.done();
};
/*
* Test the `quotmark` option
* quotmark quotation mark or true (=ensure consistency)
*/
exports.quotes = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/quotes.js', 'utf8');
var src2 = fs.readFileSync(__dirname + '/fixtures/quotes2.js', 'utf8');
TestRun(test)
.test(src, { es3: true });
TestRun(test)
.addError(3, 21, "Mixed double and single quotes.")
.test(src, { es3: true, quotmark: true });
TestRun(test)
.addError(3, 21, "Strings must use singlequote.")
.test(src, { es3: true, quotmark: 'single' });
TestRun(test)
.addError(2, 21, "Strings must use doublequote.")
.test(src, { es3: true, quotmark: 'double' });
// test multiple runs (must have the same result)
TestRun(test)
.addError(3, 21, "Mixed double and single quotes.")
.test(src, { es3: true, quotmark: true });
TestRun(test)
.addError(3, 21, "Mixed double and single quotes.")
.test(src2, { es3: true, quotmark: true });
test.done();
};
// Test the `quotmark` option when defined as a JSHint comment.
exports.quotesInline = function (test) {
TestRun(test)
.addError(6, 24, "Strings must use doublequote.")
.addError(14, 24, "Strings must use singlequote.")
.addError(21, 24, "Mixed double and single quotes.")
.addError(32, 5, "Bad option value.")
.test(fs.readFileSync(__dirname + "/fixtures/quotes3.js", "utf8"));
test.done();
};
// Test the `quotmark` option along with TemplateLiterals.
exports.quotesAndTemplateLiterals = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/quotes4.js', 'utf8');
// Without esnext
TestRun(test)
.addError(2, 13, "'template literal syntax' is only available in ES6 (use 'esversion: 6').")
.test(src);
// With esnext
TestRun(test)
.test(src, {esnext: true});
// With esnext and single quotemark
TestRun(test)
.test(src, {esnext: true, quotmark: 'single'});
// With esnext and double quotemark
TestRun(test)
.addError(1, 21, "Strings must use doublequote.")
.test(src, {esnext: true, quotmark: 'double'});
test.done();
};
exports.scope = {};
exports.scope.basic = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/scope.js', 'utf8');
TestRun(test, 1)
.addError(11, 14, "'j' used out of scope.")
.addError(11, 21, "'j' used out of scope.")
.addError(11, 28, "'j' used out of scope.")
.addError(12, 13, "'x' used out of scope.")
.addError(20, 9, "'aa' used out of scope.")
.addError(27, 9, "'bb' used out of scope.")
.addError(37, 9, "'cc' is not defined.")
.addError(42, 5, "'bb' is not defined.")
.addError(53, 5, "'xx' used out of scope.")
.addError(54, 5, "'yy' used out of scope.")
.test(src, {es3: true});
TestRun(test, 2)
.addError(37, 9, "'cc' is not defined.")
.addError(42, 5, "'bb' is not defined.")
.test(src, { es3: true, funcscope: true });
test.done();
};
exports.scope.crossBlocks = function (test) {
var code = fs.readFileSync(__dirname + '/fixtures/scope-cross-blocks.js', 'utf8');
TestRun(test)
.addError(3, 8, "'topBlockBefore' used out of scope.")
.addError(4, 8, "'nestedBlockBefore' used out of scope.")
.addError(11, 10, "'nestedBlockBefore' used out of scope.")
.addError(27, 10, "'nestedBlockAfter' used out of scope.")
.addError(32, 8, "'nestedBlockAfter' used out of scope.")
.addError(33, 8, "'topBlockAfter' used out of scope.")
.test(code);
TestRun(test)
.test(code, { funcscope: true });
test.done();
};
/*
* Tests `esnext` and `moz` options.
*
* This test simply makes sure that options are recognizable
* and do not reset ES5 mode (see GH-1068)
*
*/
exports.esnext = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/const.js', 'utf8');
var code = [
'const myConst = true;',
'const foo = 9;',
'var myConst = function (test) { };',
'foo = "hello world";',
'var a = { get x() {} };'
];
TestRun(test)
.addError(21, 7, "const 'immutable4' is initialized to 'undefined'.")
.test(src, { esnext: true });
TestRun(test)
.addError(21, 7, "const 'immutable4' is initialized to 'undefined'.")
.test(src, { moz: true });
TestRun(test)
.addError(3, 5, "'myConst' has already been declared.")
.addError(4, 1, "Attempting to override 'foo' which is a constant.")
.test(code, { esnext: true });
TestRun(test)
.addError(3, 5, "'myConst' has already been declared.")
.addError(4, 1, "Attempting to override 'foo' which is a constant.")
.test(code, { moz: true });
test.done();
};
// The `moz` option should not preclude ES6
exports.mozAndEs6 = function (test) {
var src = [
"var x = () => {};",
"function* toArray(...rest) {",
" void new.target;",
" yield rest;",
"}",
"var y = [...x];"
];
TestRun(test)
.test(src, { esversion: 6 });
TestRun(test)
.test(src, { esversion: 6, moz: true });
test.done();
};
/*
* Tests the `maxlen` option
*/
exports.maxlen = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/maxlen.js', 'utf8');
TestRun(test)
.addError(3, 24, "Line is too long.")
.addError(4, 29, "Line is too long.")
.addError(5, 40, "Line is too long.")
.addError(6, 46, "Line is too long.")
// line 7 and more are exceptions and won't trigger the error
.test(src, { es3: true, maxlen: 23 });
test.done();
};
/*
* Tests the `laxcomma` option
*/
exports.laxcomma = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/laxcomma.js', 'utf8');
// All errors.
TestRun(test)
.addError(1, 9, "Misleading line break before ','; readers may interpret this as an expression boundary.")
.addError(2, 3, "Comma warnings can be turned off with 'laxcomma'.")
.addError(2, 9, "Misleading line break before ','; readers may interpret this as an expression boundary.")
.addError(6, 10, "Misleading line break before ','; readers may interpret this as an expression boundary.")
.addError(10, 3, "Misleading line break before '&&'; readers may interpret this as an expression boundary.")
.addError(15, 9, "Misleading line break before '?'; readers may interpret this as an expression boundary.")
.test(src, {es3: true});
// Allows bad line breaking, but not on commas.
TestRun(test)
.addError(1, 9, "Misleading line break before ','; readers may interpret this as an expression boundary.")
.addError(2, 3, "Comma warnings can be turned off with 'laxcomma'.")
.addError(2, 9, "Misleading line break before ','; readers may interpret this as an expression boundary.")
.addError(6, 10, "Misleading line break before ','; readers may interpret this as an expression boundary.")
.test(src, {es3: true, laxbreak: true });
// Allows comma-first style but warns on bad line breaking
TestRun(test)
.addError(10, 3, "Misleading line break before '&&'; readers may interpret this as an expression boundary.")
.addError(15, 9, "Misleading line break before '?'; readers may interpret this as an expression boundary.")
.test(src, {es3: true, laxcomma: true });
// No errors if both laxbreak and laxcomma are turned on
TestRun(test).test(src, {es3: true, laxbreak: true, laxcomma: true });
test.done();
};
exports.unnecessarysemicolon = function (test) {
var code = [
"function foo() {",
" var a;;",
"}"
];
TestRun(test)
.addError(2, 11, "Unnecessary semicolon.")
.test(code, {es3: true});
test.done();
};
exports.blacklist = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/browser.js', 'utf8');
var code = [
'/*jshint browser: true */',
'/*global -event, bar, -btoa */',
'var a = event.hello();',
'var c = foo();',
'var b = btoa(1);',
'var d = bar();'
];
// make sure everything is ok
TestRun(test).test(src, { es3: true, undef: true, browser: true });
// disallow Node in a predef Object
TestRun(test)
.addError(15, 19, "'Node' is not defined.")
.test(src, {
undef: true,
browser: true,
predef: { '-Node': false }
});
// disallow Node and NodeFilter in a predef Array
TestRun(test)
.addError(14, 20, "'NodeFilter' is not defined.")
.addError(15, 19, "'Node' is not defined.")
.test(src, {
undef: true,
browser: true,
predef: ['-Node', '-NodeFilter']
});
TestRun(test)
.addError(3, 9, "'event' is not defined.")
.addError(4, 9, "'foo' is not defined.")
.addError(5, 9, "'btoa' is not defined.")
.test(code, { es3: true, undef: true });
test.done();
};
/*
* Tests the `maxstatements` option
*/
exports.maxstatements = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/max-statements-per-function.js', 'utf8');
TestRun(test)
.addError(1, 33, "This function has too many statements. (8)")
.test(src, { es3: true, maxstatements: 7 });
TestRun(test)
.test(src, { es3: true, maxstatements: 8 });
TestRun(test)
.test(src, { es3: true });
test.done();
};
/*
* Tests the `maxdepth` option
*/
exports.maxdepth = function (test) {
var fixture = '/fixtures/max-nested-block-depth-per-function.js';
var src = fs.readFileSync(__dirname + fixture, 'utf8');
TestRun(test)
.addError(5, 27, "Blocks are nested too deeply. (2)")
.addError(14, 26, "Blocks are nested too deeply. (2)")
.test(src, { es3: true, maxdepth: 1 });
TestRun(test)
.addError(9, 28, "Blocks are nested too deeply. (3)")
.test(src, { es3: true, maxdepth: 2 });
TestRun(test)
.test(src, { es3: true, maxdepth: 3 });
TestRun(test)
.test(src, { es3: true });
test.done();
};
/*
* Tests the `maxparams` option
*/
exports.maxparams = function (test) {
var fixture = '/fixtures/max-parameters-per-function.js';
var src = fs.readFileSync(__dirname + fixture, 'utf8');
TestRun(test)
.addError(4, 33, "This function has too many parameters. (3)")
.addError(10, 10, "This function has too many parameters. (3)")
.addError(16, 11, "This function has too many parameters. (3)")
.test(src, { esnext: true, maxparams: 2 });
TestRun(test)
.test(src, { esnext: true, maxparams: 3 });
TestRun(test)
.addError(4, 33, "This function has too many parameters. (3)")
.addError(8, 10, "This function has too many parameters. (1)")
.addError(9, 14, "This function has too many parameters. (1)")
.addError(10, 10, "This function has too many parameters. (3)")
.addError(11, 10, "This function has too many parameters. (1)")
.addError(13, 11, "This function has too many parameters. (2)")
.addError(16, 11, "This function has too many parameters. (3)")
.test(src, {esnext: true, maxparams: 0 });
TestRun(test)
.test(src, { esnext: true });
var functions = JSHINT.data().functions;
test.equal(functions.length, 9);
test.equal(functions[0].metrics.parameters, 0);
test.equal(functions[1].metrics.parameters, 3);
test.equal(functions[2].metrics.parameters, 0);
test.equal(functions[3].metrics.parameters, 1);
test.equal(functions[4].metrics.parameters, 1);
test.equal(functions[5].metrics.parameters, 3);
test.equal(functions[6].metrics.parameters, 1);
test.equal(functions[7].metrics.parameters, 2);
test.equal(functions[8].metrics.parameters, 3);
test.done();
};
/*
* Tests the `maxcomplexity` option
*/
exports.maxcomplexity = function (test) {
var fixture = '/fixtures/max-cyclomatic-complexity-per-function.js';
var src = fs.readFileSync(__dirname + fixture, 'utf8');
TestRun(test)
.addError(8, 44, "This function's cyclomatic complexity is too high. (2)")
.addError(15, 44, "This function's cyclomatic complexity is too high. (2)")
.addError(25, 54, "This function's cyclomatic complexity is too high. (2)")
.addError(47, 44, "This function's cyclomatic complexity is too high. (8)")
.addError(76, 66, "This function's cyclomatic complexity is too high. (2)")
.addError(80, 60, "This function's cyclomatic complexity is too high. (2)")
.addError(84, 61, "This function's cyclomatic complexity is too high. (2)")
.addError(88, 68, "This function's cyclomatic complexity is too high. (2)")
.test(src, { es3: true, maxcomplexity: 1 });
TestRun(test)
.test(src, { es3: true, maxcomplexity: 8 });
TestRun(test)
.test(src, { es3: true });
TestRun(test, "nullish coalescing operator")
.addError(1, 11, "This function's cyclomatic complexity is too high. (2)")
.test([
"function f() { 0 ?? 0; }"
], { esversion: 11, expr: true, maxcomplexity: 1 });
test.done();
};
// Metrics output per function.
exports.fnmetrics = function (test) {
JSHINT([
"function foo(a, b) { if (a) return b; }",
"function bar() { var a = 0; a += 1; return a; }",
"function hasTryCatch() { try { } catch(e) { }}",
"try { throw e; } catch(e) {}"
]);
test.equal(JSHINT.data().functions.length, 3);
test.deepEqual(JSHINT.data().functions[0].metrics, {
complexity: 2,
parameters: 2,
statements: 1
});
test.deepEqual(JSHINT.data().functions[1].metrics, {
complexity: 1,
parameters: 0,
statements: 3
});
test.deepEqual(JSHINT.data().functions[2].metrics, {
complexity: 2,
parameters: 0,
statements: 1
});
test.done();
};
/*
* Tests ignored warnings.
*/
exports.ignored = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/ignored.js", "utf-8");
TestRun(test)
.addError(4, 12, "A trailing decimal point can be confused with a dot: '12.'.")
.addError(12, 11, "Missing semicolon.")
.test(src, { es3: true });
TestRun(test)
.addError(12, 11, "Missing semicolon.")
.test(src, { es3: true, "-W047": true });
test.done();
};
/*
* Tests ignored warnings being unignored.
*/
exports.unignored = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/unignored.js", "utf-8");
TestRun(test)
.addError(5, 12, "A leading decimal point can be confused with a dot: '.12'.")
.test(src, { es3: true });
test.done();
};
/*
* Tests that the W117 and undef can be toggled per line.
*/
exports['per-line undef / -W117'] = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/ignore-w117.js", "utf-8");
TestRun(test)
.addError(5, 3, "'c' is not defined.")
.addError(11, 3, "'c' is not defined.")
.addError(15, 3, "'c' is not defined.")
.test(src, { undef:true });
test.done();
};
/*
* Tests the `freeze` option -- Warn if native object prototype is assigned to.
*/
exports.freeze = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/nativeobject.js", "utf-8");
TestRun(test)
.addError(3, 16, "Extending prototype of native object: 'Array'.")
.addError(13, 8, "Extending prototype of native object: 'Boolean'.")
.test(src, { freeze: true, esversion: 6 });
TestRun(test)
.test(src, { esversion: 6 });
test.done();
};
exports.nonbsp = function (test) {
var src = fs.readFileSync(__dirname + '/fixtures/nbsp.js', 'utf8');
TestRun(test)
.test(src, { sub: true });
TestRun(test)
.addError(1, 19, "This line contains non-breaking spaces: http://jshint.com/docs/options/#nonbsp")
.test(src, { nonbsp: true, sub: true });
test.done();
};
/** Option `nocomma` disallows the use of comma operator. */
exports.nocomma = function (test) {
// By default allow comma operator
TestRun(test, "nocomma off by default")
.test("return 2, 5;", {});
TestRun(test, "nocomma main case")
.addError(1, 9, "Unexpected use of a comma operator.")
.test("return 2, 5;", { nocomma: true });
TestRun(test, "nocomma in an expression")
.addError(1, 3, "Unexpected use of a comma operator.")
.test("(2, 5);", { expr: true, nocomma: true });
TestRun(test, "avoid nocomma false positives in value literals")
.test("return { a: 2, b: [1, 2] };", { nocomma: true });
TestRun(test, "avoid nocomma false positives in for statements")
.test("for(;;) { return; }", { nocomma: true });
TestRun(test, "avoid nocomma false positives in function expressions")
.test("return function(a, b) {};", { nocomma: true });
TestRun(test, "avoid nocomma false positives in arrow function expressions")
.test("return (a, b) => a;", { esnext: true, nocomma: true });
TestRun(test, "avoid nocomma false positives in destructuring arrays")
.test("var [a, b] = [1, 2];", { esnext: true, nocomma: true });
TestRun(test, "avoid nocomma false positives in destructuring objects")
.test("var {a, b} = {a:1, b:2};", { esnext: true, nocomma: true });
test.done();
};
exports.enforceall = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/enforceall.js", "utf8");
// Throws errors not normally on be default
TestRun(test)
.addError(1, 19, "This line contains non-breaking spaces: http://jshint.com/docs/options/#nonbsp")
.addError(1, 18, "['key'] is better written in dot notation.")
.addError(1, 15, "'obj' is not defined.")
.addError(1, 32, "Missing semicolon.")
.test(src, { enforceall: true });
// Can override default hard
TestRun(test)
.test(src, { enforceall: true, nonbsp: false, bitwise: false, sub: true, undef: false, unused: false, asi:true });
TestRun(test, "Does not enable 'regexpu'.")
.test('void /./;', { enforceall: true });
test.done();
};
exports.removeglobal = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/removeglobals.js", "utf8");
TestRun(test)
.addError(1, 1, "'JSON' is not defined.")
.test(src, { undef: true, predef: ["-JSON", "myglobal"] });
test.done();
};
exports.ignoreDelimiters = function (test) {
var src = fs.readFileSync(__dirname + "/fixtures/ignoreDelimiters.js", "utf8");
TestRun(test)
// make sure line/column are still reported properly
.addError(6, 37, "Missing semicolon.")
.test(src, {
ignoreDelimiters: [
{ start: "<%=", end: "%>" },
{ start: "<%", end: "%>" },
{ start: "<?php", end: "?>" },
// make sure single tokens are ignored
{ start: "foo" },
{ end: "bar" }
]
});
test.done();
};
exports.esnextPredefs = function (test) {
var code = [
'/* global alert: true */',
'var mySym = Symbol("name");',
'var myBadSym = new Symbol("name");',
'alert(Reflect);'
];
TestRun(test)
.addError(3, 16, "Do not use Symbol as a constructor.")
.test(code, { esnext: true, undef: true });
test.done();
};
var singleGroups = exports.singleGroups = {};
singleGroups.loneIdentifier = function (test) {
var code = [
"if ((a)) {}",
"if ((a) + b + c) {}",
"if (a + (b) + c) {}",
"if (a + b + (c)) {}",
];
TestRun(test)
.addError(1, 5, "Unnecessary grouping operator.")
.addError(2, 5, "Unnecessary grouping operator.")
.addError(3, 9, "Unnecessary grouping operator.")
.addError(4, 13, "Unnecessary grouping operator.")
.test(code, { singleGroups: true });
test.done();
};
singleGroups.neighborless = function (test) {
var code = [
"if ((a instanceof b)) {}",
"if ((a in b)) {}",
"if ((a + b)) {}"
];
TestRun(test)
.addError(1, 5, "Unnecessary grouping operator.")
.addError(2, 5, "Unnecessary grouping operator.")
.addError(3, 5, "Unnecessary grouping operator.")
.test(code, { singleGroups: true });
test.done();
};
singleGroups.bindingPower = {};
singleGroups.bindingPower.singleExpr = function (test) {
var code = [
"var a = !(a instanceof b);",
"var b = !(a in b);",
"var c = !!(a && a.b);",
"var d = (1 - 2) * 3;",
"var e = 3 * (1 - 2);",
"var f = a && (b || c);",
"var g = ~(a * b);",
"var h = void (a || b);",
"var i = 2 * (3 - 4 - 5) * 6;",
"var j = (a = 1) + 2;",
"var j = (a += 1) / 2;",
"var k = 'foo' + ('bar' ? 'baz' : 'qux');",
"var l = 1 + (0 || 3);",
"var u = a / (b * c);",
"var v = a % (b / c);",
"var w = a * (b * c);",
"var x = z === (b === c);",
"x = typeof (a + b);",
// Invalid forms:
"var j = 2 * ((3 - 4) - 5) * 6;",
"var l = 2 * ((3 - 4 - 5)) * 6;",
"var m = typeof(a.b);",
"var n = 1 - (2 * 3);",
"var o = (3 * 1) - 2;",
"var p = ~(Math.abs(a));",
"var q = -(a[b]);",
"var r = +(a.b);",
"var s = --(a.b);",
"var t = ++(a[b]);",
"if (a in c || (b in c)) {}",
"if ((a in c) || b in c) {}",
"if ((a in c) || (b in c)) {}",
"if ((a * b) * c) {}",
"if (a + (b * c)) {}",
"(a ? a : (a=[])).push(b);",
"if (a || (1 / 0 == 1 / 0)) {}",
];
TestRun(test)
.addError(19, 14, "Unnecessary grouping operator.")
.addError(20, 14, "Unnecessary grouping operator.")
.addError(21, 15, "Unnecessary grouping operator.")
.addError(22, 13, "Unnecessary grouping operator.")
.addError(23, 9, "Unnecessary grouping operator.")
.addError(24, 10, "Unnecessary grouping operator.")
.addError(25, 10, "Unnecessary grouping operator.")
.addError(26, 10, "Unnecessary grouping operator.")
.addError(27, 11, "Unnecessary grouping operator.")
.addError(28, 11, "Unnecessary grouping operator.")
.addError(29, 15, "Unnecessary grouping operator.")
.addError(30, 5, "Unnecessary grouping operator.")
.addError(31, 5, "Unnecessary grouping operator.")
.addError(31, 17, "Unnecessary grouping operator.")
.addError(32, 5, "Unnecessary grouping operator.")
.addError(33, 9, "Unnecessary grouping operator.")
.addError(34, 10, "Unnecessary grouping operator.")
.addError(35, 10, "Unnecessary grouping operator.")
.test(code, { singleGroups: true });
code = [
"var x;",
"x = (printA || printB)``;",
"x = (printA || printB)`${}`;",
"x = (new X)``;",
"x = (new X)`${}`;",
// Should warn:
"x = (x.y)``;",
"x = (x.y)`${}`;",
"x = (x[x])``;",
"x = (x[x])`${}`;",
"x = (x())``;",
"x = (x())`${}`;"
];
TestRun(test)
.addError(6, 5, "Unnecessary grouping operator.")
.addError(7, 5, "Unnecessary grouping operator.")
.addError(8, 5, "Unnecessary grouping operator.")
.addError(9, 5, "Unnecessary grouping operator.")
.addError(10, 5, "Unnecessary grouping operator.")
.addError(11, 5, "Unnecessary grouping operator.")
.test(code, { singleGroups: true, esversion: 6, supernew: true });
test.done();
};
singleGroups.bindingPower.multiExpr = function (test) {
var code = [
"var j = (a, b);",
"var k = -(a, b);",
"var i = (1, a = 1) + 2;",
"var k = a ? (b, c) : (d, e);",
"var j = (a, b + c) * d;",
"if (a, (b * c)) {}",
"if ((a * b), c) {}",
"if ((a, b, c)) {}",
"if ((a + 1)) {}"
];
TestRun(test)
.addError(6, 8, "Unnecessary grouping operator.")
.addError(7, 5, "Unnecessary grouping operator.")
.addError(8, 5, "Unnecessary grouping operator.")
.addError(9, 5, "Unnecessary grouping operator.")
.test(code, { singleGroups: true });
test.done();
};
singleGroups.multiExpr = function (test) {
var code = [
"var a = (1, 2);",
"var b = (true, false) ? 1 : 2;",
"var c = true ? (1, 2) : false;",
"var d = true ? false : (1, 2);",
"foo((1, 2));"
];
TestRun(test)
.test(code, { singleGroups: true });
test.done();
};
// Although the following form is redundant in purely mathematical terms, type
// coercion semantics in JavaScript make it impossible to statically determine
// whether the grouping operator is necessary. JSHint should err on the side of
// caution and allow this form.
singleGroups.concatenation = function (test) {
var code = [
"var a = b + (c + d);",
"var e = (f + g) + h;"
];
TestRun(test)
.addError(2, 9, "Unnecessary grouping operator.")
.test(code, { singleGroups: true });
test.done();
};
singleGroups.functionExpression = function (test) {
var code = [
"(function() {})();",
"(function() {}).call();",
"(function() {}());",
"(function() {}.call());",
"if (true) {} (function() {}());",
"(function() {}());",
// These usages are not technically necessary, but parenthesis are commonly
// used to signal that a function expression is going to be invoked
// immediately.
"var a = (function() {})();",
"var b = (function() {}).call();",
"var c = (function() {}());",
"var d = (function() {}.call());",
"var e = { e: (function() {})() };",
"var f = { f: (function() {}).call() };",
"var g = { g: (function() {}()) };",
"var h = { h: (function() {}.call()) };",
"if ((function() {})()) {}",
"if ((function() {}).call()) {}",
"if ((function() {}())) {}",
"if ((function() {}.call())) {}",
// Invalid forms:
"var i = (function() {});"
];
TestRun(test)
.addError(19, 9, "Unnecessary grouping operator.")
.test(code, { singleGroups: true, asi: true });
test.done();
};
singleGroups.generatorExpression = function (test) {
var code = [
"(function*() { yield; })();",
"(function*() { yield; }).call();",
"(function*() { yield; }());",
"(function*() { yield; }.call());",
"if (true) {} (function*() { yield; }());",
"(function*() { yield; }());",
// These usages are not technically necessary, but parenthesis are commonly
// used to signal that a function expression is going to be invoked
// immediately.
"var a = (function*() { yield; })();",
"var b = (function*() { yield; }).call();",
"var c = (function*() { yield; }());",
"var d = (function*() { yield; }.call());",
"var e = { e: (function*() { yield; })() };",
"var f = { f: (function*() { yield; }).call() };",
"var g = { g: (function*() { yield; }()) };",
"var h = { h: (function*() { yield; }.call()) };",
"if ((function*() { yield; })()) {}",
"if ((function*() { yield; }).call()) {}",
"if ((function*() { yield; }())) {}",
"if ((function*() { yield; }.call())) {}",
// Invalid forms:
"var i = (function*() { yield; });"
];
TestRun(test)
.addError(19, 9, "Unnecessary grouping operator.")
.test(code, { singleGroups: true, asi: true, esnext: true });
test.done();
};
singleGroups.yield = function (test) {
TestRun(test, "otherwise-invalid position")
.test([
"function* g() {",
" var x;",
" x = 0 || (yield);",
" x = 0 || (yield 0);",
" x = 0 && (yield);",
" x = 0 && (yield 0);",
" x = !(yield);",
" x = !(yield 0);",
" x = !!(yield);",
" x = !!(yield 0);",
" x = 0 + (yield);",
" x = 0 + (yield 0);",
" x = 0 - (yield);",
" x = 0 - (yield 0);",
"}"
], { singleGroups: true, esversion: 6 });
TestRun(test, "operand delineation")
.test([
"function* g() {",
" (yield).x = 0;",
" x = (yield) ? 0 : 0;",
" x = (yield 0) ? 0 : 0;",
" x = (yield) / 0;",
"}"
], { singleGroups: true, esversion: 6 });
TestRun(test)
.addError(2, 3, "Unnecessary grouping operator.")
.addError(3, 3, "Unnecessary grouping operator.")
.addError(4, 11, "Unnecessary grouping operator.")
.addError(5, 11, "Unnecessary grouping operator.")
.addError(6, 7, "Unnecessary grouping operator.")
.addError(7, 7, "Unnecessary grouping operator.")
.addError(8, 8, "Unnecessary grouping operator.")
.addError(9, 8, "Unnecessary grouping operator.")
.addError(10, 8, "Unnecessary grouping operator.")
.addError(11, 8, "Unnecessary grouping operator.")
.addError(12, 8, "Unnecessary grouping operator.")
.addError(13, 8, "Unnecessary grouping operator.")
.addError(14, 8, "Unnecessary grouping operator.")
.addError(15, 8, "Unnecessary grouping operator.")
.addError(16, 8, "Unnecessary grouping operator.")
.addError(17, 8, "Unnecessary grouping operator.")
.addError(18, 9, "Unnecessary grouping operator.")
.addError(19, 9, "Unnecessary grouping operator.")
.addError(20, 9, "Unnecessary grouping operator.")
.addError(21, 9, "Unnecessary grouping operator.")
.addError(22, 10, "Unnecessary grouping operator.")
.addError(23, 10, "Unnecessary grouping operator.")
.addError(24, 8, "Unnecessary grouping operator.")
.addError(25, 8, "Unnecessary grouping operator.")
.addError(26, 8, "Unnecessary grouping operator.")
.addError(27, 8, "Unnecessary grouping operator.")
.addError(28, 8, "Unnecessary grouping operator.")
.addError(29, 8, "Unnecessary grouping operator.")
.addError(30, 11, "Unnecessary grouping operator.")
.addError(31, 11, "Unnecessary grouping operator.")
.addError(32, 15, "Unnecessary grouping operator.")
.addError(33, 15, "Unnecessary grouping operator.")
.addError(34, 9, "Unnecessary grouping operator.")
.test([
"function* g() {",
" (yield);",
" (yield 0);",
" var x = (yield);",
" var y = (yield 0);",
" x = (yield);",
" x = (yield 0);",
" x += (yield);",
" x += (yield 0);",
" x -= (yield);",
" x -= (yield 0);",
" x *= (yield);",
" x *= (yield 0);",
" x /= (yield);",
" x /= (yield 0);",
" x %= (yield);",
" x %= (yield 0);",
" x <<= (yield 0);",
" x <<= (yield);",
" x >>= (yield);",
" x >>= (yield 0);",
" x >>>= (yield);",
" x >>>= (yield 0);",
" x &= (yield);",
" x &= (yield 0);",
" x ^= (yield);",
" x ^= (yield 0);",
" x |= (yield);",
" x |= (yield 0);",
" x = 0 ? (yield) : 0;",
" x = 0 ? (yield 0) : 0;",
" x = 0 ? 0 : (yield);",
" x = 0 ? 0 : (yield 0);",
" yield (yield);",
"}"
], { singleGroups: true, esversion: 6 });
test.done();
};
singleGroups.arrowFunctions = function (test) {
var code = [
"var a = () => ({});",
"var b = (c) => {};",
"var g = (() => 3)();",
"var h = (() => ({}))();",
"var i = (() => 3).length;",
"var j = (() => ({})).length;",
"var k = (() => 3)[prop];",
"var l = (() => ({}))[prop];",
"var m = (() => 3) || 3;",
"var n = (() => ({})) || 3;",
"var o = (() => {})();",
"var p = (() => {})[prop];",
"var q = (() => {}) || 3;",
"(() => {})();",
// Invalid forms:
"var d = () => (e);",
"var f = () => (3);",
"var r = (() => 3);",
"var s = (() => {});"
];
TestRun(test)
.addError(15, 15, "Unnecessary grouping operator.")
.addError(16, 15, "Unnecessary grouping operator.")
.addError(17, 9, "Unnecessary grouping operator.")
.addError(18, 9, "Unnecessary grouping operator.")
.test(code, { singleGroups: true, esnext: true });
test.done();
};
singleGroups.exponentiation = function (test) {
TestRun(test)
.addError(1, 1, "Unnecessary grouping operator.")
.addError(2, 6, "Unnecessary grouping operator.")
.test([
"(2) ** 2;",
"2 ** (2);",
], { singleGroups: true, expr: true, esversion: 7 });
TestRun(test, "UpdateExpression")
.addError(2, 1, "Unnecessary grouping operator.")
.addError(3, 1, "Unnecessary grouping operator.")
.addError(4, 1, "Unnecessary grouping operator.")
.addError(5, 1, "Unnecessary grouping operator.")
.addError(6, 6, "Unnecessary grouping operator.")
.addError(7, 6, "Unnecessary grouping operator.")
.addError(8, 6, "Unnecessary grouping operator.")
.addError(9, 6, "Unnecessary grouping operator.")
.test([
"var x;",
"(++x) ** 2;",
"(x++) ** 2;",
"(--x) ** 2;",
"(x--) ** 2;",
"2 ** (++x);",
"2 ** (x++);",
"2 ** (--x);",
"2 ** (x--);"
], { singleGroups: true, expr: true, esversion: 7 });
TestRun(test, "UnaryExpression")
.addError(1, 16, "Variables should not be deleted.")
.addError(8, 10, "Variables should not be deleted.")
.test([
"delete (2 ** 3);",
"void (2 ** 3);",
"typeof (2 ** 3);",
"+(2 ** 3);",
"-(2 ** 3);",
"~(2 ** 3);",
"!(2 ** 3);",
"(delete 2) ** 3;",
"(void 2) ** 3;",
"(typeof 2) ** 3;",
"(+2) ** 3;",
"(-2) ** 3;",
"(~2) ** 3;",
"(!2) ** 3;"
], { singleGroups: true, expr: true, esversion: 7 });
TestRun(test, "MultiplicativeExpression")
.addError(2, 5, "Unnecessary grouping operator.")
.addError(4, 1, "Unnecessary grouping operator.")
.addError(6, 5, "Unnecessary grouping operator.")
.addError(8, 1, "Unnecessary grouping operator.")
.addError(10, 5, "Unnecessary grouping operator.")
.addError(12, 1, "Unnecessary grouping operator.")
.test([
"(2 * 3) ** 4;",
"2 * (3 ** 4);",
"2 ** (3 * 4);",
"(2 ** 3) * 4;",
"(2 / 3) ** 4;",
"2 / (3 ** 4);",
"2 ** (3 / 4);",
"(2 ** 3) / 4;",
"(2 % 3) ** 4;",
"2 % (3 ** 4);",
"2 ** (3 % 4);",
"(2 ** 3) % 4;"
], { singleGroups: true, expr: true, esversion: 7 });
TestRun(test, "AdditiveExpression")
.addError(2, 5, "Unnecessary grouping operator.")
.addError(4, 1, "Unnecessary grouping operator.")
.addError(6, 5, "Unnecessary grouping operator.")
.addError(8, 1, "Unnecessary grouping operator.")
.test([
"(2 + 3) ** 4;",
"2 + (3 ** 4);",
"2 ** (3 + 4);",
"(2 ** 3) + 4;",
"(2 - 3) ** 4;",
"2 - (3 ** 4);",
"2 ** (3 - 4);",
"(2 ** 3) - 4;"
], { singleGroups: true, expr: true, esversion: 7 });
TestRun(test, "Exponentiation")
.addError(2, 6, "Unnecessary grouping operator.")
.test([
"(2 ** 3) ** 4;",
"2 ** (3 ** 4);"
], { singleGroups: true, expr: true, esversion: 7 });
test.done();
};
singleGroups.asyncFunction = function (test) {
TestRun(test, "Async Function Expression")
.test([
"(async function() {})();",
"(async function a() {})();"
], { singleGroups: true, esversion: 8 });
TestRun(test, "Async Generator Function Expression")
.test([
"(async function * () { yield; })();",
"(async function * a() { yield; })();"
], { singleGroups: true, esversion: 9 });
TestRun(test, "Async Arrow Function")
.test([
"(async () => {})();",
"(async x => x)();"
], { singleGroups: true, esversion: 8 });
TestRun(test, "async identifier")
.addError(1, 1, "Unnecessary grouping operator.")
.addError(2, 1, "Unnecessary grouping operator.")
.test([
"(async());",
"(async(x, y, z));"
], { singleGroups: true, esversion: 8 });
test.done();
};
singleGroups.await = function (test) {
TestRun(test, "MultiplicativeExpression")
.addError(2, 3, "Unnecessary grouping operator.")
.test([
"(async function() {",
" (await 2) * 3;",
"})();"
], { singleGroups: true, expr: true, esversion: 8 });
TestRun(test, "ExponentiationExpression")
.addError(2, 3, "Unnecessary grouping operator.")
.test([
"(async function() {",
" (await 2) ** 3;",
"})();"
], { singleGroups: true, expr: true, esversion: 8 });
TestRun(test, "CallExpression")
.test([
"(async function() {",
" (await 2)();",
"})();"
], { singleGroups: true, expr: true, esversion: 8 });
TestRun(test, "EqualityExpression")
.addError(2, 3, "Unnecessary grouping operator.")
.addError(3, 3, "Unnecessary grouping operator.")
.addError(4, 3, "Unnecessary grouping operator.")
.addError(5, 3, "Unnecessary grouping operator.")
.test([
"(async function() {",
" (await 2) == 2;",
" (await 2) != 2;",
" (await 2) === 2;",
" (await 2) !== 2;",
"})();"
], { singleGroups: true, expr: true, esversion: 8 });
TestRun(test, "Expression")
.addError(2, 3, "Unnecessary grouping operator.")
.test([
"(async function() {",
" (await 0), 0;",
"})();"
], { singleGroups: true, expr: true, esversion: 8 });
test.done();
};
singleGroups.objectLiterals = function (test) {
var code = [
"({}).method();",
"if(true) {} ({}).method();",
"g(); ({}).method();",
// Invalid forms
"var a = ({}).method();",
"if (({}).method()) {}",
"var b = { a: ({}).method() };",
"for (({}); ;) {}",
"for (; ;({})) {}"
];
TestRun(test, "grouping operator not required")
.addError(4, 9, "Unnecessary grouping operator.")
.addError(5, 5, "Unnecessary grouping operator.")
.addError(6, 14, "Unnecessary grouping operator.")
.addError(7, 6, "Unnecessary grouping operator.")
.addError(8, 9, "Unnecessary grouping operator.")
.test(code, { singleGroups: true });
test.done();
};
singleGroups.newLine = function(test) {
var code = [
"function x() {",
" return f",
" ();",
"}",
"x({ f: null });"
];
TestRun(test)
.test(code, { singleGroups: true });
test.done();
};
singleGroups.lineNumber = function (test) {
var code = [
"var x = (",
" 1",
")",
";"
];
TestRun(test)
.addError(1, 9, "Unnecessary grouping operator.")
.test(code, { singleGroups: true });
test.done();
};
singleGroups.unary = function (test) {
var code = [
"(-3).toString();",
"(+3)[methodName]();",
"(!3).toString();",
"(~3).toString();",
"(typeof x).toString();",
"(new x).method();",
// Unnecessary:
"x = (-3) + 5;",
"x = (+3) - 5;",
"x = (!3) / 5;",
"x = (~3) << 5;",
"x = (typeof x) === 'undefined';",
"x = (new x) + 4;",
];
TestRun(test)
.addError(6, 6, "Missing '()' invoking a constructor.")
.addError(7, 5, "Unnecessary grouping operator.")
.addError(8, 5, "Unnecessary grouping operator.")
.addError(9, 5, "Unnecessary grouping operator.")
.addError(10, 5, "Unnecessary grouping operator.")
.addError(11, 5, "Unnecessary grouping operator.")
.addError(12, 5, "Unnecessary grouping operator.")
.addError(12, 10, "Missing '()' invoking a constructor.")
.test(code, { singleGroups: true });
test.done();
};
singleGroups.numberLiterals = function (test) {
var code = [
"(3).toString();",
"(3.1).toString();",
"(.3).toString();",
"(3.).toString();",
"(1e3).toString();",
"(1e-3).toString();",
"(1.1e3).toString();",
"(1.1e-3).toString();",
"(3)[methodName]();",
"var x = (3) + 3;",
"('3').toString();"
];
TestRun(test)
.addError(2, 1, "Unnecessary grouping operator.")
.addError(3, 1, "Unnecessary grouping operator.")
.addError(3, 4, "A leading decimal point can be confused with a dot: '.3'.")
.addError(4, 1, "Unnecessary grouping operator.")
.addError(4, 4, "A trailing decimal point can be confused with a dot: '3.'.")
.addError(5, 1, "Unnecessary grouping operator.")
.addError(6, 1, "Unnecessary grouping operator.")
.addError(7, 1, "Unnecessary grouping operator.")
.addError(8, 1, "Unnecessary grouping operator.")
.addError(9, 1, "Unnecessary grouping operator.")
.addError(10, 9, "Unnecessary grouping operator.")
.addError(11, 1, "Unnecessary grouping operator.")
.test(code, { singleGroups: true });
test.done();
};
singleGroups.postfix = function (test) {
var code = [
"var x;",
"(x++).toString();",
"(x--).toString();"
];
TestRun(test)
.test(code, { singleGroups: true });
test.done();
};
singleGroups.destructuringAssign = function (test) {
var code = [
// statements
"({ x } = { x : 1 });",
"([ x ] = [ 1 ]);",
// expressions
"1, ({ x } = { x : 1 });",
"1, ([ x ] = [ 1 ]);",
"for (({ x } = { X: 1 }); ;) {}",
"for (; ;({ x } = { X: 1 })) {}"
];
TestRun(test)
.addError(2, 1, "Unnecessary grouping operator.")
.addError(3, 4, "Unnecessary grouping operator.")
.addError(4, 4, "Unnecessary grouping operator.")
.addError(5, 6, "Unnecessary grouping operator.")
.addError(6, 9, "Unnecessary grouping operator.")
.test(code, { esversion: 6, singleGroups: true, expr: true });
test.done();
};
singleGroups.nullishCoalescing = function (test) {
TestRun(test)
.addError(1, 1, "Unnecessary grouping operator.")
.addError(2, 6, "Unnecessary grouping operator.")
.test([
"(0) ?? 0;",
"0 ?? (0);"
], { singleGroups: true, expr: true, esversion: 11 });
TestRun(test)
.test([
"0 ?? (0 || 0);",
"(0 ?? 0) || 0;",
"0 ?? (0 && 0);",
"(0 ?? 0) && 0;"
], { singleGroups: true, expr: true, esversion: 11 });
test.done();
};
singleGroups.optionalChaining = function (test) {
var code = [
"new ({}?.constructor)();",
"({}?.toString)``;",
// Invalid forms:
"([])?.x;",
"([]?.x).x;",
"([]?.x)?.x;"
];
TestRun(test)
.addError(1, 21, "Bad constructor.")
.addError(2, 15, "Expected an assignment or function call and instead saw an expression.")
.addError(3, 1, "Unnecessary grouping operator.")
.addError(3, 7, "Expected an assignment or function call and instead saw an expression.")
.addError(4, 1, "Unnecessary grouping operator.")
.addError(4, 9, "Expected an assignment or function call and instead saw an expression.")
.addError(5, 1, "Unnecessary grouping operator.")
.addError(5, 10, "Expected an assignment or function call and instead saw an expression.")
.test(code, { singleGroups: true, esversion: 11 });
test.done();
};
exports.elision = function (test) {
var code = [
"var a = [1,,2];",
"var b = [1,,,,2];",
"var c = [1,2,];",
"var d = [,1,2];",
"var e = [,,1,2];",
];
TestRun(test, "elision=false ES5")
.addError(1, 12, "Empty array elements require elision=true.")
.addError(2, 12, "Empty array elements require elision=true.")
.addError(4, 10, "Empty array elements require elision=true.")
.addError(5, 10, "Empty array elements require elision=true.")
.test(code, { elision: false, es3: false });
TestRun(test, "elision=false ES3")
.addError(1, 12, "Extra comma. (it breaks older versions of IE)")
.addError(2, 12, "Extra comma. (it breaks older versions of IE)")
.addError(2, 13, "Extra comma. (it breaks older versions of IE)")
.addError(2, 14, "Extra comma. (it breaks older versions of IE)")
.addError(3, 13, "Extra comma. (it breaks older versions of IE)")
.addError(4, 10, "Extra comma. (it breaks older versions of IE)")
.addError(5, 10, "Extra comma. (it breaks older versions of IE)")
.addError(5, 11, "Extra comma. (it breaks older versions of IE)")
.test(code, { elision: false, es3: true });
TestRun(test, "elision=true ES5")
.test(code, { elision: true, es3: false });
TestRun(test, "elision=true ES3")
.addError(3, 13, "Extra comma. (it breaks older versions of IE)")
.test(code, { elision: true, es3: true });
test.done();
};
exports.badInlineOptionValue = function (test) {
var src = [ "/* jshint bitwise:batcrazy */" ];
TestRun(test)
.addError(1, 1, "Bad option value.")
.test(src);
test.done();
};
exports.futureHostile = function (test) {
var code = [
"var JSON = {};",
"var Map = function() {};",
"var Promise = function() {};",
"var Proxy = function() {};",
"var Reflect = function() {};",
"var Set = function() {};",
"var Symbol = function() {};",
"var WeakMap = function() {};",
"var WeakSet = function() {};",
"var ArrayBuffer = function() {};",
"var DataView = function() {};",
"var Int8Array = function() {};",
"var Int16Array = function() {};",
"var Int32Array = function() {};",
"var Uint8Array = function() {};",
"var Uint16Array = function() {};",
"var Uint32Array = function() {};",
"var Uint8ClampedArray = function() {};",
"var Float32Array = function() {};",
"var Float64Array = function() {};"
];
TestRun(test, "ES3 without option")
.addError(1, 5, "'JSON' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(2, 5, "'Map' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(3, 5, "'Promise' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(4, 5, "'Proxy' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(5, 5, "'Reflect' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(6, 5, "'Set' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(7, 5, "'Symbol' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(8, 5, "'WeakMap' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(9, 5, "'WeakSet' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(10, 5, "'ArrayBuffer' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(11, 5, "'DataView' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(12, 5, "'Int8Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(13, 5, "'Int16Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(14, 5, "'Int32Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(15, 5, "'Uint8Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(16, 5, "'Uint16Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(17, 5, "'Uint32Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(18, 5, "'Uint8ClampedArray' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(19, 5, "'Float32Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(20, 5, "'Float64Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.test(code, { es3: true, es5: false, futurehostile: false });
TestRun(test, "ES3 with option")
.test(code, { es3: true, es5: false });
TestRun(test, "ES5 without option")
.addError(1, 5, "Redefinition of 'JSON'.")
.addError(2, 5, "'Map' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(3, 5, "'Promise' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(4, 5, "'Proxy' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(5, 5, "'Reflect' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(6, 5, "'Set' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(7, 5, "'Symbol' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(8, 5, "'WeakMap' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(9, 5, "'WeakSet' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(10, 5, "'ArrayBuffer' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(11, 5, "'DataView' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(12, 5, "'Int8Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(13, 5, "'Int16Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(14, 5, "'Int32Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(15, 5, "'Uint8Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(16, 5, "'Uint16Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(17, 5, "'Uint32Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(18, 5, "'Uint8ClampedArray' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(19, 5, "'Float32Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.addError(20, 5, "'Float64Array' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.")
.test(code, { futurehostile: false });
TestRun(test, "ES5 with option")
.addError(1, 5, "Redefinition of 'JSON'.")
.test(code, {});
TestRun(test, "ES5 with opt-out")
.test(code, {
predef: ["-JSON"]
});
TestRun(test, "ESNext without option")
.addError(1, 5, "Redefinition of 'JSON'.")
.addError(2, 5, "Redefinition of 'Map'.")
.addError(3, 5, "Redefinition of 'Promise'.")
.addError(4, 5, "Redefinition of 'Proxy'.")
.addError(5, 5, "Redefinition of 'Reflect'.")
.addError(6, 5, "Redefinition of 'Set'.")
.addError(7, 5, "Redefinition of 'Symbol'.")
.addError(8, 5, "Redefinition of 'WeakMap'.")
.addError(9, 5, "Redefinition of 'WeakSet'.")
.addError(10, 5, "Redefinition of 'ArrayBuffer'.")
.addError(11, 5, "Redefinition of 'DataView'.")
.addError(12, 5, "Redefinition of 'Int8Array'.")
.addError(13, 5, "Redefinition of 'Int16Array'.")
.addError(14, 5, "Redefinition of 'Int32Array'.")
.addError(15, 5, "Redefinition of 'Uint8Array'.")
.addError(16, 5, "Redefinition of 'Uint16Array'.")
.addError(17, 5, "Redefinition of 'Uint32Array'.")
.addError(18, 5, "Redefinition of 'Uint8ClampedArray'.")
.addError(19, 5, "Redefinition of 'Float32Array'.")
.addError(20, 5, "Redefinition of 'Float64Array'.")
.test(code, { esnext: true, futurehostile: false });
TestRun(test, "ESNext with option")
.addError(1, 5, "Redefinition of 'JSON'.")
.addError(2, 5, "Redefinition of 'Map'.")
.addError(3, 5, "Redefinition of 'Promise'.")
.addError(4, 5, "Redefinition of 'Proxy'.")
.addError(5, 5, "Redefinition of 'Reflect'.")
.addError(6, 5, "Redefinition of 'Set'.")
.addError(7, 5, "Redefinition of 'Symbol'.")
.addError(8, 5, "Redefinition of 'WeakMap'.")
.addError(9, 5, "Redefinition of 'WeakSet'.")
.addError(10, 5, "Redefinition of 'ArrayBuffer'.")
.addError(11, 5, "Redefinition of 'DataView'.")
.addError(12, 5, "Redefinition of 'Int8Array'.")
.addError(13, 5, "Redefinition of 'Int16Array'.")
.addError(14, 5, "Redefinition of 'Int32Array'.")
.addError(15, 5, "Redefinition of 'Uint8Array'.")
.addError(16, 5, "Redefinition of 'Uint16Array'.")
.addError(17, 5, "Redefinition of 'Uint32Array'.")
.addError(18, 5, "Redefinition of 'Uint8ClampedArray'.")
.addError(19, 5, "Redefinition of 'Float32Array'.")
.addError(20, 5, "Redefinition of 'Float64Array'.")
.test(code, { esnext: true });
TestRun(test, "ESNext with opt-out")
.test(code, {
esnext: true,
futurehostile: false,
predef: [
"-JSON",
"-Map",
"-Promise",
"-Proxy",
"-Reflect",
"-Set",
"-Symbol",
"-WeakMap",
"-WeakSet",
"-ArrayBuffer",
"-DataView",
"-Int8Array",
"-Int16Array",
"-Int32Array",
"-Uint8Array",
"-Uint16Array",
"-Uint32Array",
"-Uint8ClampedArray",
"-Float32Array",
"-Float64Array"
]
});
code = [
"let JSON = {};",
"let Map = function() {};",
"let Promise = function() {};",
"let Proxy = function() {};",
"let Reflect = function() {};",
"let Set = function() {};",
"let Symbol = function() {};",
"let WeakMap = function() {};",
"let WeakSet = function() {};",
"let ArrayBuffer = function() {};",
"let DataView = function() {};",
"let Int8Array = function() {};",
"let Int16Array = function() {};",
"let Int32Array = function() {};",
"let Uint8Array = function() {};",
"let Uint16Array = function() {};",
"let Uint32Array = function() {};",
"let Uint8ClampedArray = function() {};",
"let Float32Array = function() {};",
"let Float64Array = function() {};"
];
TestRun(test, "ESNext with option")
.addError(1, 5, "Redefinition of 'JSON'.")
.addError(2, 5, "Redefinition of 'Map'.")
.addError(3, 5, "Redefinition of 'Promise'.")
.addError(4, 5, "Redefinition of 'Proxy'.")
.addError(5, 5, "Redefinition of 'Reflect'.")
.addError(6, 5, "Redefinition of 'Set'.")
.addError(7, 5, "Redefinition of 'Symbol'.")
.addError(8, 5, "Redefinition of 'WeakMap'.")
.addError(9, 5, "Redefinition of 'WeakSet'.")
.addError(10, 5, "Redefinition of 'ArrayBuffer'.")
.addError(11, 5, "Redefinition of 'DataView'.")
.addError(12, 5, "Redefinition of 'Int8Array'.")
.addError(13, 5, "Redefinition of 'Int16Array'.")
.addError(14, 5, "Redefinition of 'Int32Array'.")
.addError(15, 5, "Redefinition of 'Uint8Array'.")
.addError(16, 5, "Redefinition of 'Uint16Array'.")
.addError(17, 5, "Redefinition of 'Uint32Array'.")
.addError(18, 5, "Redefinition of 'Uint8ClampedArray'.")
.addError(19, 5, "Redefinition of 'Float32Array'.")
.addError(20, 5, "Redefinition of 'Float64Array'.")
.test(code, { esnext: true });
TestRun(test, "ESNext with opt-out")
.test(code, {
esnext: true,
futurehostile: false,
predef: [
"-JSON",
"-Map",
"-Promise",
"-Proxy",
"-Reflect",
"-Set",
"-Symbol",
"-WeakMap",
"-WeakSet",
"-ArrayBuffer",
"-DataView",
"-Int8Array",
"-Int16Array",
"-Int32Array",
"-Uint8Array",
"-Uint16Array",
"-Uint32Array",
"-Uint8ClampedArray",
"-Float32Array",
"-Float64Array"
]
});
code = [
"const JSON = {};",
"const Map = function() {};",
"const Promise = function() {};",
"const Proxy = function() {};",
"const Reflect = function() {};",
"const Set = function() {};",
"const Symbol = function() {};",
"const WeakMap = function() {};",
"const WeakSet = function() {};",
"const ArrayBuffer = function() {};",
"const DataView = function() {};",
"const Int8Array = function() {};",
"const Int16Array = function() {};",
"const Int32Array = function() {};",
"const Uint8Array = function() {};",
"const Uint16Array = function() {};",
"const Uint32Array = function() {};",
"const Uint8ClampedArray = function() {};",
"const Float32Array = function() {};",
"const Float64Array = function() {};"
];
TestRun(test, "ESNext with option")
.addError(1, 7, "Redefinition of 'JSON'.")
.addError(2, 7, "Redefinition of 'Map'.")
.addError(3, 7, "Redefinition of 'Promise'.")
.addError(4, 7, "Redefinition of 'Proxy'.")
.addError(5, 7, "Redefinition of 'Reflect'.")
.addError(6, 7, "Redefinition of 'Set'.")
.addError(7, 7, "Redefinition of 'Symbol'.")
.addError(8, 7, "Redefinition of 'WeakMap'.")
.addError(9, 7, "Redefinition of 'WeakSet'.")
.addError(10, 7, "Redefinition of 'ArrayBuffer'.")
.addError(11, 7, "Redefinition of 'DataView'.")
.addError(12, 7, "Redefinition of 'Int8Array'.")
.addError(13, 7, "Redefinition of 'Int16Array'.")
.addError(14, 7, "Redefinition of 'Int32Array'.")
.addError(15, 7, "Redefinition of 'Uint8Array'.")
.addError(16, 7, "Redefinition of 'Uint16Array'.")
.addError(17, 7, "Redefinition of 'Uint32Array'.")
.addError(18, 7, "Redefinition of 'Uint8ClampedArray'.")
.addError(19, 7, "Redefinition of 'Float32Array'.")
.addError(20, 7, "Redefinition of 'Float64Array'.")
.test(code, { esnext: true });
TestRun(test, "ESNext with opt-out")
.test(code, {
esnext: true,
futurehostile: false,
predef: [
"-JSON",
"-Map",
"-Promise",
"-Proxy",
"-Reflect",
"-Set",
"-Symbol",
"-WeakMap",
"-WeakSet",
"-ArrayBuffer",
"-DataView",
"-Int8Array",
"-Int16Array",
"-Int32Array",
"-Uint8Array",
"-Uint16Array",
"-Uint32Array",
"-Uint8ClampedArray",
"-Float32Array",
"-Float64Array"
]
});
test.done();
};
exports.varstmt = function (test) {
var code = [
"var x;",
"var y = 5;",
"var fn = function() {",
" var x;",
" var y = 5;",
"};",
"for (var a in x);"
];
TestRun(test)
.addError(1, 1, "`var` declarations are forbidden. Use `let` or `const` instead.")
.addError(2, 1, "`var` declarations are forbidden. Use `let` or `const` instead.")
.addError(3, 1, "`var` declarations are forbidden. Use `let` or `const` instead.")
.addError(4, 3, "`var` declarations are forbidden. Use `let` or `const` instead.")
.addError(5, 3, "`var` declarations are forbidden. Use `let` or `const` instead.")
.addError(7, 6, "`var` declarations are forbidden. Use `let` or `const` instead.")
.test(code, { varstmt: true });
test.done();
};
exports.module = {};
exports.module.behavior = function(test) {
var code = [
"var package = 3;",
"function f() { return this; }"
];
TestRun(test)
.test(code, {});
TestRun(test)
.addError(0, 0, "The 'module' option is only available when linting ECMAScript 6 code.")
.addError(1, 5, "Expected an identifier and instead saw 'package' (a reserved word).")
.addError(2, 23, "If a strict mode function is executed using function invocation, its 'this' value will be undefined.")
.test(code, { module: true });
TestRun(test)
.addError(1, 5, "Expected an identifier and instead saw 'package' (a reserved word).")
.addError(2, 23, "If a strict mode function is executed using function invocation, its 'this' value will be undefined.")
.test(code, { module: true, esnext: true });
code = [
"/* jshint module: true */",
"var package = 3;",
"function f() { return this; }"
];
TestRun(test)
.addError(1, 1, "The 'module' option is only available when linting ECMAScript 6 code.")
.addError(2, 5, "Expected an identifier and instead saw 'package' (a reserved word).")
.addError(3, 23, "If a strict mode function is executed using function invocation, its 'this' value will be undefined.")
.test(code);
code[0] = "/* jshint module: true, esnext: true */";
TestRun(test)
.addError(2, 5, "Expected an identifier and instead saw 'package' (a reserved word).")
.addError(3, 23, "If a strict mode function is executed using function invocation, its 'this' value will be undefined.")
.test(code);
test.done();
};
exports.module.declarationRestrictions = function( test ) {
TestRun(test)
.addError(2, 3, "The 'module' option cannot be set after any executable code.")
.test([
"(function() {",
" /* jshint module: true */",
"})();"
], { esnext: true });
TestRun(test)
.addError(2, 1, "The 'module' option cannot be set after any executable code.")
.test([
"void 0;",
"/* jshint module: true */"
], { esnext: true });
TestRun(test)
.addError(3, 1, "The 'module' option cannot be set after any executable code.")
.test([
"void 0;",
"// hide",
"/* jshint module: true */"
], { esnext: true });
TestRun(test, "First line (following statement)")
.addError(1, 20, "The 'module' option cannot be set after any executable code.")
.test([
"(function() {})(); /* jshint module: true */"
], { esnext: true });
TestRun(test, "First line (within statement)")
.addError(1, 15, "The 'module' option cannot be set after any executable code.")
.test([
"(function() { /* jshint module: true */",
"})();"
], { esnext: true });
TestRun(test, "First line (before statement)")
.test([
"/* jshint module: true */ (function() {",
"})();"
], { esnext: true });
TestRun(test, "First line (within expression)")
.addError(1, 10, "The 'module' option cannot be set after any executable code.")
.test("Math.abs(/*jshint module: true */4);", { esnext: true });
TestRun(test, "Following single-line comment")
.test([
"// License boilerplate",
"/* jshint module: true */"
], { esnext: true });
TestRun(test, "Following multi-line comment")
.test([
"/**",
" * License boilerplate",
" */",
" /* jshint module: true */"
], { esnext: true });
TestRun(test, "Following shebang")
.test([
"#!/usr/bin/env node",
"/* jshint module: true */"
], { esnext: true });
TestRun(test, "Not re-applied with every directive (gh-2560)")
.test([
"/* jshint module:true */",
"function bar() {",
" /* jshint validthis:true */",
"}"
], { esnext: true });
test.done();
};
exports.module.newcap = function(test) {
var code = [
"var ctor = function() {};",
"var Ctor = function() {};",
"var c1 = new ctor();",
"var c2 = Ctor();"
];
TestRun(test, "The `newcap` option is not automatically enabled for module code.")
.test(code, { esversion: 6, module: true });
test.done();
};
exports.module.await = function(test) {
var allPositions = [
"var await;",
"function await() {}",
"await: while (false) {}",
"void { await: null };",
"void {}.await;"
];
TestRun(test)
.test(allPositions, { esversion: 3 });
TestRun(test)
.test(allPositions);
TestRun(test)
.test(allPositions, { esversion: 6 });
TestRun(test)
.addError(1, 5, "Expected an identifier and instead saw 'await' (a reserved word).")
.test("var await;", { esversion: 6, module: true });
TestRun(test)
.addError(1, 10, "Expected an identifier and instead saw 'await' (a reserved word).")
.test("function await() {}", { esversion: 6, module: true });
TestRun(test)
.addError(1, 1, "Expected an assignment or function call and instead saw an expression.")
.addError(1, 1, "Expected an identifier and instead saw 'await' (a reserved word).")
.addError(1, 6, "Missing semicolon.")
.addError(1, 1, "Unrecoverable syntax error. (100% scanned).")
.test("await: while (false) {}", { esversion: 6, module: true });
TestRun(test)
.test([
"void { await: null };",
"void {}.await;"
], { esversion: 6, module: true });
test.done();
};
exports.esversion = function(test) {
var code = [
"// jshint esversion: 3",
"// jshint esversion: 4",
"// jshint esversion: 5",
"// jshint esversion: 6",
"// jshint esversion: 2015",
"// jshint esversion: 7",
"// jshint esversion: 2016",
"// jshint esversion: 8",
"// jshint esversion: 2017",
"// jshint esversion: 9",
"// jshint esversion: 2018",
"// jshint esversion: 10",
"// jshint esversion: 2019",
"// jshint esversion: 11",
"// jshint esversion: 2020",
"// jshint esversion: 12",
"// jshint esversion: 2021"
];
TestRun(test, "Value")
.addError(2, 1, "Bad option value.")
.addError(16, 1, "Bad option value.")
.addError(17, 1, "Bad option value.")
.test(code);
var es5code = [
"var a = {",
" get b() {}",
"};"
];
TestRun(test, "ES5 syntax as ES3")
.addError(2, 7, "get/set are ES5 features.")
.test(es5code, { esversion: 3 });
TestRun(test, "ES5 syntax as ES5")
.test(es5code); // esversion: 5 (default)
TestRun(test, "ES5 syntax as ES6")
.test(es5code, { esversion: 6 });
var es6code = [
"var a = {",
" ['b']: 1",
"};",
"var b = () => {};"
];
TestRun(test, "ES6 syntax as ES3")
.addError(2, 3, "'computed property names' is only available in ES6 (use 'esversion: 6').")
.addError(4, 10, "'arrow function syntax (=>)' is only available in ES6 (use 'esversion: 6').")
.test(es6code, { esversion: 3 });
TestRun(test, "ES6 syntax as ES5")
.addError(2, 3, "'computed property names' is only available in ES6 (use 'esversion: 6').")
.addError(4, 10, "'arrow function syntax (=>)' is only available in ES6 (use 'esversion: 6').")
.test(es6code); // esversion: 5 (default)
TestRun(test, "ES6 syntax as ES6")
.test(es6code, { esversion: 6 });
TestRun(test, "ES6 syntax as ES6 (via option value `2015`)")
.test(es5code, { esversion: 2015 });
TestRun(test, "ES6 syntax as ES7")
.test(es6code, { esversion: 7 });
TestRun(test, "ES6 syntax as ES8")
.test(es6code, { esversion: 8 });
// Array comprehensions aren't defined in ECMAScript 6,
// but they can be enabled using the `esnext` option
var arrayComprehension = [
"var a = [ 1, 2, 3 ];",
"var b = [ for (i of a) i ];"
];
TestRun(test, "array comprehensions - esversion: 6")
.addError(2, 9, "'array comprehension' is only available in Mozilla JavaScript extensions " +
"(use moz option).")
.test(arrayComprehension, { esversion: 6 });
TestRun(test, "array comprehensions - esversion: 7")
.addError(2, 9, "'array comprehension' is only available in Mozilla JavaScript extensions " +
"(use moz option).")
.test(arrayComprehension, { esversion: 7 });
TestRun(test, "array comprehensions - esversion: 8")
.addError(2, 9, "'array comprehension' is only available in Mozilla JavaScript extensions " +
"(use moz option).")
.test(arrayComprehension, { esversion: 8 });
TestRun(test, "array comprehensions - esnext: true")
.test(arrayComprehension, { esnext: true });
TestRun(test, "incompatibility with `es3`") // TODO: Remove in JSHint 3
.addError(0, 0, "Incompatible values for the 'esversion' and 'es3' linting options. (0% scanned).")
.test(es6code, { esversion: 6, es3: true });
TestRun(test, "incompatibility with `es5`") // TODO: Remove in JSHint 3
.addError(0, 0, "Incompatible values for the 'esversion' and 'es5' linting options. (0% scanned).")
.test(es6code, { esversion: 6, es5: true });
TestRun(test, "incompatibility with `esnext`") // TODO: Remove in JSHint 3
.addError(0, 0, "Incompatible values for the 'esversion' and 'esnext' linting options. (0% scanned).")
.test(es6code, { esversion: 3, esnext: true });
TestRun(test, "imcompatible option specified in-line")
.addError(2, 1, "Incompatible values for the 'esversion' and 'es3' linting options. (66% scanned).")
.test(["", "// jshint esversion: 3", ""], { es3: true });
TestRun(test, "incompatible option specified in-line")
.addError(2, 1, "Incompatible values for the 'esversion' and 'es3' linting options. (66% scanned).")
.test(["", "// jshint es3: true", ""], { esversion: 3 });
TestRun(test, "compatible option specified in-line")
.addError(3, 1, "'class' is available in ES6 (use 'esversion: 6') or Mozilla JS extensions (use moz).")
.test(["", "// jshint esversion: 3", "class A {}"], { esversion: 3 });
TestRun(test, "compatible option specified in-line")
.addError(3, 1, "'class' is available in ES6 (use 'esversion: 6') or Mozilla JS extensions (use moz).")
.test(["", "// jshint esversion: 3", "class A {}"], { esversion: 6 });
TestRun(test, "compatible option specified in-line")
.test(["", "// jshint esversion: 6", "class A {}"], { esversion: 3 });
var code2 = [ // TODO: Remove in JSHint 3
"/* jshint esversion: 3, esnext: true */"
].concat(es6code);
TestRun(test, "incompatible options specified in-line") // TODO: Remove in JSHint 3
.addError(1, 1, "Incompatible values for the 'esversion' and 'esnext' linting options. (20% scanned).")
.test(code2);
var code3 = [
"var someCode;",
"// jshint esversion: 3"
];
TestRun(test, "cannot be set after any executable code")
.addError(2, 1, "The 'esversion' option cannot be set after any executable code.")
.test(code3);
var code4 = [
"#!/usr/bin/env node",
"/**",
" * License",
" */",
"// jshint esversion: 3",
"// jshint esversion: 6"
];
TestRun(test, "can follow shebang or comments")
.test(code4);
var code5 = [
"// jshint moz: true",
"// jshint esversion: 3",
"var x = {",
" get a() {}",
"};",
"// jshint moz: true",
"var x = {",
" get a() {}",
"};"
];
TestRun(test, "correctly swap between moz and esversion")
.addError(4, 7, "get/set are ES5 features.")
.test(code5);
test.done();
};
// Option `trailingcomma` requires a comma after each element in an array or
// object literal.
exports.trailingcomma = function (test) {
var code = [
"var a = [];",
"var b = [1];",
"var c = [1,];",
"var d = [1,2];",
"var e = [1,2,];",
"var f = {};",
"var g = {a: 1};",
"var h = {a: 1,};",
"var i = {a: 1, b: 2};",
"var j = {a: 1, b: 2,};"
];
TestRun(test, "trailingcomma=true ES6")
.addError(2, 11, "Missing comma.")
.addError(4, 13, "Missing comma.")
.addError(7, 14, "Missing comma.")
.addError(9, 20, "Missing comma.")
.test(code, { trailingcomma: true, esversion: 6 });
TestRun(test, "trailingcomma=true ES5")
.addError(2, 11, "Missing comma.")
.addError(4, 13, "Missing comma.")
.addError(7, 14, "Missing comma.")
.addError(9, 20, "Missing comma.")
.test(code, { trailingcomma: true });
TestRun(test, "trailingcomma=true ES3")
.addError(3, 11, "Extra comma. (it breaks older versions of IE)")
.addError(5, 13, "Extra comma. (it breaks older versions of IE)")
.addError(8, 14, "Extra comma. (it breaks older versions of IE)")
.addError(10, 20, "Extra comma. (it breaks older versions of IE)")
.test(code, { trailingcomma: true, es3: true });
test.done();
};
exports.unstable = function (test) {
TestRun(test, "Accepts programmatic configuration.")
.test("", { unstable: {} });
TestRun(test, "Accepts empty in-line directive (single-line comment).")
.test("// jshint.unstable");
TestRun(test, "Rejects empty in-line directive (multi-line comment).")
.addError(1, 1, "Bad unstable option: ''.")
.test("/* jshint.unstable */");
TestRun(test, "Rejects non-existent names specified via programmatic configuration.")
.addError(0, 0, "Bad unstable option: 'nonExistentOptionName'.")
.test("", { unstable: { nonExistentOptionName: true } });
TestRun(test, "Rejects non-existent names specified via in-line directive (single-line comment).")
.addError(1, 1, "Bad unstable option: 'nonExistentOptionName'.")
.test("// jshint.unstable nonExistentOptionName: true");
TestRun(test, "Rejects non-existent names specified via in-line directive (multi-line comment).")
.addError(1, 1, "Bad unstable option: 'nonExistentOptionName'.")
.test("/* jshint.unstable nonExistentOptionName: true */");
TestRun(test, "Rejects stable names specified via programmatic configuration.")
.addError(0, 0, "Bad unstable option: 'undef'.")
.test("", { unstable: { undef: true } });
TestRun(test, "Rejects stable names specified via in-line directive (single-line comment).")
.addError(1, 1, "Bad unstable option: 'undef'.")
.test("// jshint.unstable undef: true");
TestRun(test, "Rejects stable names specified via in-line directive (multi-line comment).")
.addError(1, 1, "Bad unstable option: 'undef'.")
.test("/* jshint.unstable undef: true */");
test.done();
};
exports.leanswitch = function (test) {
var code = [
"switch (0) {",
" case 0:",
" default:",
" break;",
"}"
];
TestRun(test, "empty case clause followed by default")
.test(code);
TestRun(test, "empty case clause followed by default")
.addError(2, 9, "Superfluous 'case' clause.")
.test(code, { leanswitch: true });
code = [
"switch (0) {",
" case 0:",
" case 1:",
" break;",
"}"
];
TestRun(test, "empty case clause followed by case")
.test(code);
TestRun(test, "empty case clause followed by case")
.test(code, { leanswitch: true });
code = [
"switch (0) {",
" default:",
" case 0:",
" break;",
"}"
];
TestRun(test, "empty default clause followed by case")
.test(code);
TestRun(test, "empty default clause followed by case")
.addError(3, 3, "Superfluous 'case' clause.")
.test(code, { leanswitch: true });
code = [
"switch (0) {",
" case 0:",
" void 0;",
" default:",
" break;",
"}"
];
TestRun(test, "non-empty case clause followed by default")
.addError(3, 11, "Expected a 'break' statement before 'default'.")
.test(code);
TestRun(test, "non-empty case clause followed by default")
.addError(3, 11, "Expected a 'break' statement before 'default'.")
.test(code, { leanswitch: true });
code = [
"switch (0) {",
" case 0:",
" void 0;",
" case 1:",
" break;",
"}"
];
TestRun(test, "non-empty case clause followed by case")
.addError(3, 11, "Expected a 'break' statement before 'case'.")
.test(code);
TestRun(test, "non-empty case clause followed by case")
.addError(3, 11, "Expected a 'break' statement before 'case'.")
.test(code, { leanswitch: true });
code = [
"switch (0) {",
" default:",
" void 0;",
" case 0:",
" break;",
"}"
];
TestRun(test, "non-empty default clause followed by case")
.addError(3, 11, "Expected a 'break' statement before 'case'.")
.test(code);
TestRun(test, "non-empty default clause followed by case")
.addError(3, 11, "Expected a 'break' statement before 'case'.")
.test(code, { leanswitch: true });
test.done();
};
exports.noreturnawait = function(test) {
var code = [
"void function() {",
" return await;",
"};",
"void function() {",
" return await(null);",
"};",
"void async function() {",
" return null;",
"};",
"void async function() {",
" return 'await';",
"};",
"void async function() {",
" try {",
" return await null;",
" } catch (err) {}",
"};",
"void async function() {",
" try {",
" void async function() {",
" return await null;",
" };",
" } catch (err) {}",
"};",
"void async function() {",
" return await null;",
"};"
];
TestRun(test, "function expression (disabled)")
.test(code, { esversion: 8 });
TestRun(test, "function expression (enabled)")
.addError(21, 14, "Unnecessary `await` expression.")
.addError(26, 10, "Unnecessary `await` expression.")
.test(code, { esversion: 8, noreturnawait: true });
code = [
"void (() => await);",
"void (() => await(null));",
"void (async () => null);",
"void (async () => 'await');",
"void (async () => await null);",
"void (async () => { await null; });"
];
TestRun(test, "arrow function (disabled)")
.test(code, { esversion: 8 });
TestRun(test, "arrow function (enabled)")
.addError(5, 19, "Unnecessary `await` expression.")
.test(code, { esversion: 8, noreturnawait: true });
test.done();
};
exports.regexpu = function (test) {
TestRun(test, "restricted outside of ES6 - via API")
.addError(0, 0, "The 'regexpu' option is only available when linting ECMAScript 6 code.")
.test("void 0;", { regexpu: true })
TestRun(test, "restricted outside of ES6 - via directive")
.addError(1, 1, "The 'regexpu' option is only available when linting ECMAScript 6 code.")
.test([
"// jshint regexpu: true",
"void 0;"
]);
TestRun(test, "missing")
.addError(1, 6, "Regular expressions should include the 'u' flag.")
.addError(2, 6, "Regular expressions should include the 'u' flag.")
.addError(3, 6, "Regular expressions should include the 'u' flag.")
.test([
"void /./;",
"void /./g;",
"void /./giym;",
], { regexpu: true, esversion: 6 });
TestRun(test, "in use")
.test([
"void /./u;",
"void /./ugiym;",
"void /./guiym;",
"void /./giuym;",
"void /./giyum;",
"void /./giymu;"
], { esversion: 6 });
TestRun(test, "missing - option set when parsing precedes option enablement")
.addError(3, 8, "Regular expressions should include the 'u' flag.")
.test([
"(function() {",
" // jshint regexpu: true",
" void /./;",
"}());"
], { esversion: 6 });
test.done();
};
| mit |
ddtraceweb/socool | src/Core/Controller/CoreResponse.php | 1950 | <?php
/**
* Created by JetBrains PhpStorm.
* User: daviddjian
* Date: 10/08/13
* Time: 11:02
* To change this template use File | Settings | File Templates.
*/
namespace Core\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Templating\Helper\SlotsHelper;
use Symfony\Component\Templating\PhpEngine;
Trait CoreResponse{
/**
* @var \Symfony\Component\Templating\PhpEngine
*/
public $view;
/**
* @param \Symfony\Component\Templating\PhpEngine $view
*/
public function setView(PhpEngine $view)
{
$this->view = $view;
}
/**
* @param $name
* @param array $parameters
*
* @return string
*/
public function render($name, array $parameters = array())
{
$arrayMerge = array();
$arrayMerge["context"] = $this->getContext();
$arrayMerge["request"] = $this->getRequest();
$arrayMerge["router"] = $this->getRouter();
$arrayMerge["session"] = $this->getSession();
$arrayMerge["date"] = new \DateTime();
$arrayMerge["translator"] = $this->getTranslator();
$arrayMerge['seo'] = $this->getSeoArray();
$parameters = array_merge($arrayMerge, $parameters);
$this->getView()->set(new SlotsHelper());
$response = new Response();
$response->setContent($this->getView()->render($name, $parameters));
$response->headers->set('Content-Type', 'text/html');
$response->setCharset('UTF-8');
return $response;
}
/**
* @return \Symfony\Component\Templating\PhpEngine
*/
public function getView()
{
return $this->view;
}
public function renderJson($json)
{
$response = new Response();
$response->setContent($json);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
} | mit |
CallFire/callfire-api-client-java | src/main/java/com/callfire/api/client/api/contacts/model/Contact.java | 847 | package com.callfire.api.client.api.contacts.model;
import java.util.HashMap;
import java.util.Map;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* Represents contact information in Callfire system
*/
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Contact extends CallfireModel {
private Long id;
private String firstName;
private String lastName;
private String zipcode;
private String homePhone;
private String workPhone;
private String mobilePhone;
private String externalId;
private String externalSystem;
private Boolean deleted;
@Builder.Default private Map<String, String> properties = new HashMap<>();
}
| mit |
nfl/react-metrics | src/core/useTrackBindingPlugin.js | 2858 | import EventListener from "fbjs/lib/EventListener";
import attr2obj from "./utils/attr2obj";
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
export class TrackBindingPlugin {
constructor(
{attributePrefix = "data-metrics", traverseParent = false} = {}
) {
this._attributePrefix = attributePrefix;
this._traverseParent = traverseParent;
}
listen(callback, rootElement = document.body) {
if (typeof callback !== "function") {
throw new Error("callback needs to be a function.");
}
if (rootElement && rootElement.nodeType !== 1) {
throw new Error("rootElement needs to be a valid node element.");
}
if (this._clickHandler) {
this.remove();
}
this._rootElement = rootElement;
this._clickHandler = EventListener.listen(
rootElement,
"click",
this._handleClick.bind(this, callback)
);
return {
target: this,
remove: this.remove.bind(this)
};
}
remove() {
if (this._clickHandler) {
this._clickHandler.remove();
this._clickHandler = null;
}
}
/**
* A click handler to perform custom link tracking, any element with 'metrics-*' attribute will be tracked.
*
* @method _handleClick
* @param {Object} event
* @private
*/
_handleClick(callback, event) {
if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
return;
}
let elem = event.target || event.srcElement;
let dataset = this._getData(elem);
if (this._traverseParent) {
const rootElement = this._rootElement;
while (elem !== rootElement) {
elem = elem.parentElement || elem.parentNode;
dataset = {...this._getData(elem), ...dataset};
}
}
if (!Object.keys(dataset).length) {
return;
}
const eventName = dataset && dataset.eventName;
const mergePagedefaults = dataset && dataset.mergePagedefaults;
delete dataset.mergePagedefaults;
if (eventName) {
delete dataset.eventName;
callback(eventName, dataset, mergePagedefaults === "true");
}
}
_getData(elem) {
return attr2obj(elem, this._attributePrefix);
}
}
export default function useTrackBindingPlugin({
callback,
rootElement,
attributePrefix,
traverseParent
}) {
const trackBindingPlugin = new TrackBindingPlugin({
attributePrefix,
traverseParent
});
return trackBindingPlugin.listen(callback, rootElement);
}
| mit |
ac9831/StudyProject-Asp.Net | DevDataControl/DevDataControl/FrmObjectDataSource.aspx.designer.cs | 1651 | //------------------------------------------------------------------------------
// <자동 생성됨>
// 이 코드는 도구를 사용하여 생성되었습니다.
//
// 파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면
// 이러한 변경 내용이 손실됩니다.
// </자동 생성됨>
//------------------------------------------------------------------------------
namespace DevDataControl {
public partial class FrmObjectDataSource1 {
/// <summary>
/// form1 컨트롤입니다.
/// </summary>
/// <remarks>
/// 자동 생성 필드입니다.
/// 수정하려면 디자이너 파일에서 코드 숨김 파일로 필드 선언을 이동하세요.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// ctlMemoList 컨트롤입니다.
/// </summary>
/// <remarks>
/// 자동 생성 필드입니다.
/// 수정하려면 디자이너 파일에서 코드 숨김 파일로 필드 선언을 이동하세요.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView ctlMemoList;
/// <summary>
/// odsMemoList 컨트롤입니다.
/// </summary>
/// <remarks>
/// 자동 생성 필드입니다.
/// 수정하려면 디자이너 파일에서 코드 숨김 파일로 필드 선언을 이동하세요.
/// </remarks>
protected global::System.Web.UI.WebControls.ObjectDataSource odsMemoList;
}
}
| mit |
paine1690/cdp4j | src/main/java/io/webfolder/cdp/annotation/EventName.java | 1461 | /**
* The MIT License
* Copyright © 2017 WebFolder OÜ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.webfolder.cdp.annotation;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target({TYPE})
public @interface EventName {
public String value();
}
| mit |
lytics/jstag | src/rollup/dom/location.js | 98 | /** @module jstag/dom/location */
import window from './window';
export default window.location;
| mit |
jsor/doctrine-postgis | src/Functions/ST_TransScale.php | 1410 | <?php
declare(strict_types=1);
/* This file is auto-generated. Don't edit directly! */
namespace Jsor\Doctrine\PostGIS\Functions;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\AST\Node;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
final class ST_TransScale extends FunctionNode
{
protected array $expressions = [];
public function parse(Parser $parser): void
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->expressions[] = $parser->ArithmeticFactor();
$parser->match(Lexer::T_COMMA);
$this->expressions[] = $parser->ArithmeticFactor();
$parser->match(Lexer::T_COMMA);
$this->expressions[] = $parser->ArithmeticFactor();
$parser->match(Lexer::T_COMMA);
$this->expressions[] = $parser->ArithmeticFactor();
$parser->match(Lexer::T_COMMA);
$this->expressions[] = $parser->ArithmeticFactor();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql(SqlWalker $sqlWalker): string
{
$arguments = [];
/** @var Node $expression */
foreach ($this->expressions as $expression) {
$arguments[] = $expression->dispatch($sqlWalker);
}
return 'ST_TransScale(' . implode(', ', $arguments) . ')';
}
}
| mit |
iandees/all-the-places | locations/spiders/hannaford.py | 5049 | import scrapy
from locations.items import GeojsonPointItem
import re
regex = r"(\D+,\s\D+-\d{5}).*" # city, state, zip
regex_am = r"\s?([Aa][Mm])"
regex_pm = r"\s?([Pp][Mm])"
regex_lat = r"(lat = \d+\.\d+)"
regex_lon = r"(lng = -\d+\.\d+)"
regex_id = r"(t\.id = \"\d+\")"
class HannafordSpider(scrapy.Spider):
name = 'hannaford'
allowed_domains = ['www.hannaford.com']
start_urls = [
'https://www.hannaford.com/custserv/locate_store.cmd?form_state=locateStoreForm&latitude=&longitude=&formId=locateStoreForm&radius=500&cityStateZip=maine&submitBtn.x=37&submitBtn.y=10']
def parse(self, response):
base_url = "https://www.hannaford.com"
script = response.xpath(
'//script[contains(., "t.lat")]/text()')[0].extract()
lat = re.findall(regex_lat, script)
lat = [x.strip('lat = ') for x in lat]
lon = re.findall(regex_lon, script)
lon = [x.strip('lng = ') for x in lon]
storeid = re.findall(regex_id, script)
storeid = [x.strip('t.id = "').strip('"') for x in storeid]
lat_lon = list(zip(storeid, lat, lon))
stores = response.xpath(
'//*[@id="pageContentWrapperInner"]//descendant::*/a[2]/@href') \
.extract()
for store in stores:
store = base_url + store
yield scrapy.Request(
store, callback=self.parse_store, meta={'lat_lon': lat_lon})
def combine_hours(self, hours):
days = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
hours = self.convert_hours(hours)
converted_hours = ''.join('{} {} '.format(*t)
for t in zip(days, hours))
return converted_hours
def convert_hours(self, hours):
for i in range(len(hours)):
cleaned_times = ''
if ':' in hours[i]:
hours_to = hours[i].split('-')
for ampm in hours_to:
if re.search(regex_pm, ampm):
ampm = re.sub(regex_pm, '', ampm)
hour_min = ampm.split(':')
if int(hour_min[0]) < 12:
hour_min[0] = str(12 + int(hour_min[0]))
cleaned_times += (":".join(hour_min))
if re.search(regex_am, ampm):
ampm = re.sub(regex_am, '', ampm)
hour_min = ampm.split(':')
if len(hour_min[0]) < 2:
hour_min[0] = hour_min[0].zfill(2)
if ampm[0]:
cleaned_times += (":".join(hour_min)) + '-'
else:
cleaned_times += (":".join(hour_min))
else:
if ampm[0]:
cleaned_times += (":".join(hour_min)) + '-'
else:
cleaned_times += (":".join(hour_min))
else:
cleaned_times += 'off'
hours[i] = cleaned_times
return hours
def parse_store(self, response):
storeid = response.url.split('=')[1]
for i in response.meta['lat_lon']:
if i[0] == storeid:
lat = i[1]
lon = i[2]
addr = response.xpath(
'//div[@class="storeContact"]/p[1]/text()').extract()
addr = [x.strip().replace('\xa0', '-') for x in addr]
street = ''
cty_st_zip = ''
for i in addr:
search = re.search(regex, i)
if not search:
street += i + ' '
else:
cty_st_zip += i
city = cty_st_zip.split(',')[0]
state = cty_st_zip.split('-')[0].split(',')[1]
postcode = cty_st_zip.split('-')[1]
addr_full = "{}{},{} {}".format(street, city, state, postcode)
phone = response.xpath(
'//div[@class="storeContact"]/p[2]/text()'
).extract_first().split('\xa0')[1]
name = response.xpath(
'//h1[@style="display:block;"]/text()').extract_first().split(
' to ')[1]
website = response.xpath(
'//div[@class="storeContact"]/descendant::*/a/@href') \
.extract_first()
if not website:
website = response.url
hours = response.xpath(
'//div[@class="storeHours"]/div/p/descendant::*/text()').extract()
opening_hours = self.combine_hours(hours)
yield GeojsonPointItem(
ref=response.url,
name=name,
lat=lat,
lon=lon,
addr_full=addr_full,
street=street,
city=city,
state=state,
postcode=postcode,
phone=phone,
website=website,
opening_hours=opening_hours
)
| mit |
SponsorPay/events_emitter | lib/events_emitter/pixel.rb | 801 | require "net/http"
module EventsEmitter
class Pixel
def record(fragment, _)
pixel_url = URI.parse("http:#{url(fragment)}")
http = Net::HTTP.new(pixel_url.host, pixel_url.port)
http.read_timeout = timeout
request = Net::HTTP::Get.new(pixel_url.request_uri)
response = http.request(request)
return true
rescue Timeout::Error => e
notifier = self.class.config[:exception_notifier]
if notifier
notifier.notify(e, pixel_url)
return false
else
raise e
end
end
def url(fragment)
"#{self.class.config[:url]}?#{fragment}"
end
def timeout
self.class.config[:timeout]
end
def self.config
@config ||= { url: "//example.com/pixel.gif", timeout: 1 }
end
end
end
| mit |
spyder-ide/spyder-terminal | spyder_terminal/server/tests/test_server.py | 5329 |
"""
Tornado server-side tests.
Note: This uses tornado.testing unittest style tests
"""
import os
import sys
import os.path as osp
from urllib.parse import urlencode
import pytest
from flaky import flaky
from tornado import testing, websocket, gen
from tornado.concurrent import Future
from spyder.utils.programs import find_program
sys.path.append(osp.realpath(osp.dirname(__file__) + "/.."))
from spyder_terminal.server.common import create_app
LOCATION = os.path.realpath(os.path.join(os.getcwd(),
os.path.dirname(__file__)))
LOCATION_SLASH = LOCATION.replace('\\', '/')
LINE_END = '\n'
SHELL = 'bash'
WINDOWS = os.name == 'nt'
if WINDOWS:
LINE_END = '\r\n'
SHELL = 'cmd'
class TerminalServerTests(testing.AsyncHTTPTestCase):
"""Main server tests."""
def get_app(self):
"""Return HTTP/WS server."""
self.close_future = Future()
return create_app(SHELL, self.close_future)
def _mk_connection(self, pid):
return websocket.websocket_connect(
'ws://127.0.0.1:{0}/terminals/{1}'.format(
self.get_http_port(), pid)
)
@gen.coroutine
def close(self, ws):
"""
Close a websocket connection and wait for the server side.
If we don't wait here, there are sometimes leak warnings in the
tests.
"""
ws.close()
yield self.close_future
@testing.gen_test
def test_main_get(self):
"""Test if HTML source is rendered."""
response = yield self.http_client.fetch(
self.get_url('/'),
method="GET"
)
self.assertEqual(response.code, 200)
@testing.gen_test
def test_main_post(self):
"""Test that POST requests to root are forbidden."""
try:
yield self.http_client.fetch(
self.get_url('/'),
method="POST",
body=''
)
except Exception:
pass
@testing.gen_test
def test_create_terminal(self):
"""Test terminal creation."""
data = {'rows': '25', 'cols': '80'}
response = yield self.http_client.fetch(
self.get_url('/api/terminals'),
method="POST",
body=urlencode(data)
)
self.assertEqual(response.code, 200)
@flaky(max_runs=3)
@testing.gen_test
def test_terminal_communication(self):
"""Test terminal creation."""
data = {'rows': '25', 'cols': '100'}
response = yield self.http_client.fetch(
self.get_url('/api/terminals'),
method="POST",
body=urlencode(data)
)
pid = response.body.decode('utf-8')
sock = yield self._mk_connection(pid)
msg = yield sock.read_message()
print(msg)
test_msg = 'pwd'
sock.write_message(' ' + test_msg)
msg = ''
while test_msg not in msg:
msg += yield sock.read_message()
print(msg)
msg = ''.join(msg.rstrip())
self.assertTrue(test_msg in msg)
yield self.close(sock)
@testing.gen_test
def test_terminal_closing(self):
"""Test terminal destruction."""
data = {'rows': '25', 'cols': '80'}
response = yield self.http_client.fetch(
self.get_url('/api/terminals'),
method="POST",
body=urlencode(data)
)
pid = response.body.decode('utf-8')
sock = yield self._mk_connection(pid)
_ = yield sock.read_message()
yield self.close(sock)
try:
sock.write_message(' This shall not work')
except AttributeError:
pass
yield self.close(sock)
@flaky(max_runs=3)
@pytest.mark.timeout(10)
@testing.gen_test
@pytest.mark.skipif(os.name == 'nt', reason="Doesn't work on Windows")
def test_terminal_resize(self):
"""Test terminal resizing."""
data = {'rows': '25', 'cols': '80'}
response = yield self.http_client.fetch(
self.get_url('/api/terminals'),
method="POST",
body=urlencode(data)
)
pid = response.body.decode('utf-8')
sock = yield self._mk_connection(pid)
_ = yield sock.read_message()
data = {'rows': '23', 'cols': '73'}
response = yield self.http_client.fetch(
self.get_url('/api/terminals/{0}/size'.format(pid)),
method="POST",
body=urlencode(data)
)
sock.write_message('cd {0}{1}'.format(LOCATION_SLASH, LINE_END))
# Use the current python interpreter to execute print_size.py if it
# can be determined by sys.executable. Otherwise just hope that there
# is a `python` in the shell's path which works with the script.
python_bin = sys.executable or "python"
python_exec = python_bin + ' print_size.py' + LINE_END
sock.write_message(python_exec)
expected_size = '(73, 23)'
msg = ''
fail_retry = 50
tries = 0
while expected_size not in msg:
if tries == fail_retry:
break
msg = yield sock.read_message()
tries += 1
self.assertIn(expected_size, msg)
yield self.close(sock)
| mit |
fernandolozer/CursoAspNetCore1 | ViewComponent1/src/ViewComponent1/Migrations/ApplicationDbContextModelSnapshot.cs | 6445 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using ViewComponent1.Models;
namespace ViewComponent1.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-beta8")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId");
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId");
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("ViewComponent1.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("ViewComponent1.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("ViewComponent1.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("ViewComponent1.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| mit |
wizardone/mongoid_search | lib/mongoid_search/util.rb | 1712 | # encoding: utf-8
module Mongoid::Search::Util
def self.keywords(klass, fields)
if fields.is_a?(Array)
fields.map do |field|
self.keywords(klass, field)
end
elsif fields.is_a?(Hash)
fields.keys.map do |field|
attribute = klass.send(field)
unless attribute.blank?
if attribute.is_a?(Array)
attribute.map{ |a| self.keywords(a, fields[field]) }
else
self.keywords(attribute, fields[field])
end
end
end
else
value = if klass.respond_to?(fields.to_s + "_translations")
klass.send(fields.to_s + "_translations").values
elsif klass.respond_to?(fields)
klass.send(fields)
else
value = klass[fields];
end
value = value.join(' ') if value.respond_to?(:join)
normalize_keywords(value) if value
end
end
def self.normalize_keywords(text)
ligatures = Mongoid::Search.ligatures
ignore_list = Mongoid::Search.ignore_list
stem_keywords = Mongoid::Search.stem_keywords
stem_proc = Mongoid::Search.stem_proc
return [] if text.blank?
text = text.to_s.
mb_chars.
normalize(:kd).
downcase.
to_s.
gsub(/[._:;'"`,?|={}()!@#%^&*<>~\$\-\\\/\[\]]/, ' '). # strip punctuation
gsub(/[^\s\p{Alnum}]/,''). # strip accents
gsub(/[#{ligatures.keys.join("")}]/) {|c| ligatures[c]}.
split(' ').
reject { |word| word.size < Mongoid::Search.minimum_word_size }
text = text.reject { |word| ignore_list.include?(word) } unless ignore_list.blank?
text = text.map(&stem_proc) if stem_keywords
text
end
end
| mit |
zlx/fetch_meizi | lib/fetch_meizi/version.rb | 42 | module FetchMeizi
VERSION = "0.2.1"
end
| mit |
metodiobetsanov/Tech-Module-CSharp | Entry Module/CSharp/01. First Steps in Coding/02. Expression/Properties/AssemblyInfo.cs | 1404 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("02. Expression")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02. Expression")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b63e196a-5bdd-411e-a888-5c2f6d9138c0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
johnson/shadowgraph | vendor/plugins/authlogic/test/session_test/id_test.rb | 385 | require File.dirname(__FILE__) + '/../test_helper.rb'
module SessionTest
class IdTest < ActiveSupport::TestCase
def test_credentials
session = UserSession.new
session.credentials = [:my_id]
assert_equal :my_id, session.id
end
def test_id
session = UserSession.new
session.id = :my_id
assert_equal :my_id, session.id
end
end
end | mit |
Microsoft/MIEngine | src/WindowsDebugLauncher/DebugLauncher.cs | 10194 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WindowsDebugLauncher
{
internal class DebugLauncher : IDisposable
{
private static readonly int BUFFER_SIZE = 1024 * 4;
internal class LaunchParameters
{
public string PipeServer { get; set; }
public string StdInPipeName { get; set; }
public string StdOutPipeName { get; set; }
public string StdErrPipeName { get; set; }
public string PidPipeName { get; set; }
public string DbgExe { get; set; }
public List<string> DbgExeArgs { get; set; }
public LaunchParameters()
{
DbgExeArgs = new List<string>();
}
/// <summary>
/// Ensures all parameters have been set
/// </summary>
/// <returns></returns>
public bool ValidateParameters()
{
return !(string.IsNullOrEmpty(PipeServer)
|| string.IsNullOrEmpty(StdInPipeName)
|| string.IsNullOrEmpty(StdOutPipeName)
|| string.IsNullOrEmpty(StdErrPipeName)
|| string.IsNullOrEmpty(PidPipeName)
|| string.IsNullOrEmpty(DbgExe));
}
public string ParametersAsString()
{
StringBuilder argString = new StringBuilder();
foreach (var arg in DbgExeArgs.ToList())
{
if (arg.Contains(' '))
{
argString.Append("\"" + arg + "\"");
}
else
{
argString.Append(arg);
}
argString.Append(' ');
}
return argString.ToString();
}
}
private LaunchParameters _parameters;
private bool _isRunning = true;
private StreamWriter _debuggerCommandStream;
private StreamReader _debuggerOutputStream;
private StreamReader _debuggerErrorStream;
private StreamReader _npCommandStream;
private StreamWriter _npErrorStream;
private StreamWriter _npOutputStream;
private StreamWriter _npPidStream;
private Process _dbgProcess;
CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
public DebugLauncher(LaunchParameters parameters)
{
_parameters = parameters;
}
public void StartPipeConnection()
{
NamedPipeClientStream inputStream = new NamedPipeClientStream(_parameters.PipeServer, _parameters.StdInPipeName, PipeDirection.In, PipeOptions.None, TokenImpersonationLevel.Impersonation);
NamedPipeClientStream outputStream = new NamedPipeClientStream(_parameters.PipeServer, _parameters.StdOutPipeName, PipeDirection.Out, PipeOptions.None, TokenImpersonationLevel.Impersonation);
NamedPipeClientStream errorStream = new NamedPipeClientStream(_parameters.PipeServer, _parameters.StdErrPipeName, PipeDirection.Out, PipeOptions.None, TokenImpersonationLevel.Impersonation);
NamedPipeClientStream pidStream = new NamedPipeClientStream(_parameters.PipeServer, _parameters.PidPipeName, PipeDirection.Out, PipeOptions.None, TokenImpersonationLevel.Impersonation);
try
{
// Connect as soon as possible
inputStream.Connect();
outputStream.Connect();
errorStream.Connect();
pidStream.Connect();
Encoding encNoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
_npCommandStream = new StreamReader(inputStream, encNoBom, false, BUFFER_SIZE);
_npOutputStream = new StreamWriter(outputStream, encNoBom, BUFFER_SIZE) { AutoFlush = true };
_npErrorStream = new StreamWriter(errorStream, encNoBom, BUFFER_SIZE) { AutoFlush = true };
_npPidStream = new StreamWriter(pidStream, encNoBom, 5000) { AutoFlush = true };
ProcessStartInfo info = new ProcessStartInfo();
if (Path.IsPathRooted(_parameters.DbgExe))
{
info.WorkingDirectory = Path.GetDirectoryName(_parameters.DbgExe);
}
info.FileName = _parameters.DbgExe;
info.Arguments = _parameters.ParametersAsString();
info.UseShellExecute = false;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
_dbgProcess = new Process();
_dbgProcess.StartInfo = info;
_dbgProcess.EnableRaisingEvents = true;
_dbgProcess.Exited += OnProcessExited;
_dbgProcess.Start();
_debuggerCommandStream = new StreamWriter(_dbgProcess.StandardInput.BaseStream, encNoBom) { AutoFlush = true };
_debuggerOutputStream = _dbgProcess.StandardOutput;
_debuggerErrorStream = _dbgProcess.StandardError;
Thread readThread = new Thread(() => ReadWriteLoop(_npCommandStream, _debuggerCommandStream, _cancellationTokenSource.Token));
readThread.Name = "MIEngine.DbgInputThread";
readThread.Start();
Thread outputThread = new Thread(() => ReadWriteLoop(_debuggerOutputStream, _npOutputStream, _cancellationTokenSource.Token));
outputThread.Name = "MIEngine.DbgOutputThread";
outputThread.Start();
Thread errThread = new Thread(() => ReadWriteLoop(_debuggerErrorStream, _npErrorStream, _cancellationTokenSource.Token));
errThread.Name = "MIEngine.DbgErrorThread";
errThread.Start();
_npPidStream.WriteLine(Process.GetCurrentProcess().Id.ToString(CultureInfo.CurrentCulture));
_npPidStream.WriteLine(_dbgProcess.Id.ToString(CultureInfo.CurrentCulture));
}
catch (Exception e)
{
Debug.Fail($"Exception caught in StartPipeConnection. Message: {e.Message}");
ReportExceptionAndShutdown(e);
}
}
private void OnProcessExited(object c, EventArgs e)
{
Shutdown();
}
private void Shutdown()
{
if (_isRunning)
{
_isRunning = false;
_cancellationTokenSource.Cancel();
_dbgProcess?.Close();
_dbgProcess = null;
}
}
private void ReadWriteLoop(StreamReader reader, StreamWriter writer, CancellationToken token)
{
try
{
while (_isRunning)
{
string line = ReadLine(reader, token);
{
//Console.Error.WriteLine(symbol + line);
if (line != null)
{
writer.WriteLine(line);
writer.Flush();
}
}
}
}
catch (Exception e)
{
Debug.Fail($"Exception caught in ReadWriteLoop. Message: {e.Message}");
ReportExceptionAndShutdown(e);
}
}
private void ReportExceptionAndShutdown(Exception e)
{
try
{
_npErrorStream.WriteLine(FormattableString.Invariant($"Exception while debugging. {e.Message}. Shutting down."));
}
catch (Exception) { } // Eat any exceptions
finally
{
Shutdown();
}
}
private string ReadLine(StreamReader reader, CancellationToken token)
{
try
{
//return reader.ReadLine();
Task<string> task = reader.ReadLineAsync();
task.Wait(token);
return task.Result;
}
catch (Exception e)
{
// We will get some exceptions we expect. Assert only on the ones we don't expect
Debug.Assert(
e is OperationCanceledException
|| e is IOException
|| e is ObjectDisposedException
|| (e is AggregateException && ((AggregateException)e).InnerException is ArgumentException), // we get this when the host side is closed
"Exception throw from ReadLine when we haven't quit yet");
Shutdown();
return null;
}
}
#region IDisposable Support
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_isRunning)
{
Shutdown();
}
try
{
_npCommandStream?.Dispose();
_npOutputStream?.Dispose();
_npErrorStream?.Dispose();
_npPidStream?.Dispose();
_cancellationTokenSource?.Dispose();
_debuggerCommandStream?.Dispose();
_debuggerOutputStream?.Dispose();
_debuggerErrorStream?.Dispose();
}
// catch all exceptions
catch
{ }
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| mit |
nosplashurinal/order-management | app/components/AddTeam.js | 4316 | import React from 'react';
import PropTypes from 'prop-types';
import styles from '../styles/addTeam.scss';
import classNames from 'classnames';
import TeamMembers from './TeamMembers';
import TeamRoles from './TeamRoles';
import Input from '../components/Input';
import Select from '../components/Select';
import { Motion, spring } from 'react-motion';
const inActiveStyles = {
borderColor: 'rgba(0,0,0,.2)',
color: '#434343',
opacity: 0.9
};
const activeStyles = {
borderColor: 'rgba(0,0,0,.2)',
color: '#434343',
opacity: 1
};
const activeTabStyle = {
};
const inactiveTabStyle = {
};
const inActiveInput = {
...inActiveStyles
};
const activeInput = {
...activeStyles
};
const labelPos = {
inActive: '17px',
active: '-13px'
};
const AddTeam = ({ onToggleTeamTab, handleChange, activeTab, values, onToggleInput, activeField, onToggleSelect, onFocusSelect, options }) =>
<section id={styles.admin_team}>
<header>
<div>
<span>Add / Edit Team</span>
<button type="button" id={styles.add_team}>Add Team</button>
</div>
<form id={styles.form} name="form">
<div className={styles.custom_select}>
<Select
id={'team'}
tabIndex={2}
name={'Team'}
height={'48px'}
padding={'0 12px 14px 12px'}
type={{
boxType: 'checkBox',
styles: {border: '1px solid #CCCCCC'}
}}
items={options.team}
isOpen={activeField === 'team' ? true : false}
onToggleSelect={onToggleSelect}
onFocusSelect={onFocusSelect}
style={activeField === 'team' ? activeStyles : inActiveStyles} />
</div>
<div className={styles.input}><Input id={'email'} type={'text'} tabIndex={1} top={labelPos} left={'12px'} bottom={'0px'} placeholder={'Email'} onToggleInput={onToggleInput} value={values.email} handleChange={handleChange} isActive={(activeField === 'email')} style={activeField === 'email' ? activeInput : inActiveInput} fontSize={values.email.length === 0 && activeField !== 'email' ? 16 : 14} /></div>
<div className={styles.btn_group}>
<button className={classNames(styles.btn, styles.btn__medium, styles.btn__secondary)}>Edit</button>
<button className={classNames(styles.btn, styles.btn__medium, styles.btn__primary)}>Save</button>
</div>
</form>
</header>
<div id={styles.body}>
<div className={styles.header}>
<div className={styles.tabs}>
<button style={activeTab === 'teamRoles' ? activeTabStyle : inactiveTabStyle} onClick={() => activeTab === 'teamRoles' || onToggleTeamTab('teamRoles')}>Team Roles</button>
<button style={activeTab === 'teamMembers' ? activeTabStyle : inactiveTabStyle} onClick={() => activeTab === 'teamMembers' || onToggleTeamTab('teamMembers')}>Team Members</button>
<Motion defaultStyle={{x: 0}} style={{x: spring(activeTab === 'teamMembers' ? 100 : 0, {spring: 30, damping: 30})}}>
{intStyle => <i style={{transform: 'translate(' + intStyle.x + '%, 0)'}}></i>}
</Motion>
</div>
<input type="text" name="teamsearch" placeholder="search" />
</div>
{activeTab === 'teamRoles' ?
<div className={styles.team_data}>
<TeamRoles />
</div> : <div className={styles.team_data}>
<TeamMembers />
</div>}
</div>
</section>;
AddTeam.propTypes = {
activeField: PropTypes.string,
values: PropTypes.object,
options: PropTypes.object,
onToggleSelect: PropTypes.func,
onFocusSelect: PropTypes.func,
onToggleInput: PropTypes.func,
handleChange: PropTypes.func,
activeTab: PropTypes.string,
onToggleTeamTab: PropTypes.func
};
export default AddTeam;
| mit |
Aldarov/StudentEmployment | Client/src/modules/_global/components/RenderList.js | 349 | import React from 'react';
import PropTypes from 'prop-types';
import List from './List';
export default function renderList ({
fields,
...custom
}) {
const data = fields.getAll() || [];
return (
<List
data={data}
{...custom}
/>
);
}
renderList.propTypes = {
fields: PropTypes.object,
meta: PropTypes.object,
};
| mit |
DungntVccorp/hoc_Java | EP9_SOCKET/src/ep9_socket/EP9_MAIN_SERVER.java | 2428 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ep9_socket;
import java.io.*;
import java.net.*;
/**
*
* @author nguyendung
*/
public class EP9_MAIN_SERVER implements Runnable {
private Socket socket = null;
private PrintWriter out = null;
private BufferedReader in = null;
private boolean online = true;
EP9_MAIN_SERVER(Socket accept) throws IOException {
System.out.println("Create New Socket Client");
socket = accept;
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
@Override
public void run() {
try {
while (online) {
String inputLine = in.readLine();
//int length = dIn.readInt();
if (inputLine != null) {
System.out.println("String " + inputLine);
switch (inputLine) {
case "GG":
this.out.println("COUNT " + EP9_APP_SHARE_DATASOURCE.getInstance().CountClient());
break;
case "MESSAGE":
this.sendMessageToAllUser();
break;
case "END":
online = false;
break;
default:
this.out.println("HIHI " + inputLine);
break;
}
}
}
if (!online) {
try {
in.close();
out.close();
socket.close();
} catch (Exception e) {
} finally {
System.out.println("End Thread " + +EP9_APP_SHARE_DATASOURCE.getInstance().CountClient());
}
}
} catch (IOException ex) {
System.out.println("End Thread " + +EP9_APP_SHARE_DATASOURCE.getInstance().CountClient());
}
}
public void sendMessage(String message) {
this.out.println(message);
}
public void stop() {
}
public void sendMessageToAllUser() {
}
}
| mit |
UIUXEngineering/ix-material | libs/fn/src/lib/_common/uniqueId.ts | 465 | import { toString } from './toString';
/** Used to generate unique IDs. */
let idCounter = 0;
/**
* Generates a unique ID. If `prefix` is given, the ID is appended to it.
*
* @category Util
* @param [prefix=''] The value to prefix the ID with.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
*/
export function uniqueId(prefix: string): string {
const id = ++idCounter;
return toString(prefix) + id;
}
| mit |
bang88/ant-console | src/constants/DashboardConstants.js | 267 | /**
* SunEee
* @date Created on 11/16/15
* @author YuHui(语晖)<yuhui@suneee.com>
*/
import keyMirror from 'fbjs/lib/keyMirror';
export default keyMirror({
REQUEST_DASHBOARD: null,
REQUEST_DASHBOARD_SUCCESS: null,
REQUEST_DASHBOARD_ERROR: null
})
| mit |
tparisi/Vizi | engine/src/lights/pointLight.js | 1242 | goog.provide('Vizi.PointLight');
goog.require('Vizi.Light');
Vizi.PointLight = function(param)
{
param = param || {};
Vizi.Light.call(this, param);
this.positionVec = new THREE.Vector3;
if (param.object) {
this.object = param.object;
}
else {
var distance = ( param.distance !== undefined ) ? param.distance : Vizi.PointLight.DEFAULT_DISTANCE;
this.object = new THREE.PointLight(param.color, param.intensity, distance);
}
// Create accessors for all properties... just pass-throughs to Three.js
Object.defineProperties(this, {
distance: {
get: function() {
return this.object.distance;
},
set: function(v) {
this.object.distance = v;
}
},
});
}
goog.inherits(Vizi.PointLight, Vizi.Light);
Vizi.PointLight.prototype.realize = function()
{
Vizi.Light.prototype.realize.call(this);
}
Vizi.PointLight.prototype.update = function()
{
if (this.object)
{
this.positionVec.set(0, 0, 0);
var worldmat = this.object.parent.matrixWorld;
this.positionVec.applyMatrix4(worldmat);
this.position.copy(this.positionVec);
}
// Update the rest
Vizi.Light.prototype.update.call(this);
}
Vizi.PointLight.DEFAULT_DISTANCE = 0;
| mit |
madkom/docker-registry-client | tests/spec/DockerRegistryApi/Authorization/TokenAuthorizationSpec.php | 2929 | <?php
namespace spec\Madkom\DockerRegistryApi\Authorization;
use Http\Client\HttpClient;
use Madkom\DockerRegistryApi\Authorization\TokenAuthorization;
use Madkom\DockerRegistryApi\AuthorizationService;
use Madkom\DockerRegistryApi\DockerRegistryException;
use Madkom\DockerRegistryApi\PsrHttpRequestFactory;
use Madkom\DockerRegistryApi\Request;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
/**
* Class TokenAuthorizationSpec
* @package spec\Madkom\DockerRegistryApi\Authorization
* @author Dariusz Gafka <d.gafka@madkom.pl>
* @mixin TokenAuthorization
*/
class TokenAuthorizationSpec extends ObjectBehavior
{
/** @var PsrHttpRequestFactory */
private $authorizationRequestFactory;
function let(PsrHttpRequestFactory $authorizationRequestFactory)
{
$this->authorizationRequestFactory = $authorizationRequestFactory;
$this->beConstructedWith('login', 'password', 'registryServiceName', $authorizationRequestFactory);
}
function it_is_initializable()
{
$this->shouldHaveType(AuthorizationService::class);
}
function it_should_return_authorization_string(HttpClient $client, Request $request, ResponseInterface $responseInterface, StreamInterface $streamInterface, RequestInterface $authorizationPsrRequest)
{
$this->authorizationRequestFactory->host()->willReturn('https://portus.com');
$this->authorizationRequestFactory->toPsrRequest(Argument::type(Request\Authorization::class))->willReturn($authorizationPsrRequest);
$client->sendRequest($authorizationPsrRequest)->willReturn($responseInterface);
$responseInterface->getStatusCode()->willReturn(200);
$responseInterface->getBody()->willReturn($streamInterface);
$streamInterface->getContents()->willReturn(json_encode(['token' => 'someGeneratedToken']));
$this->authorizationHeader($client, $request)->shouldReturn('Bearer someGeneratedToken');
}
function it_should_throw_exception_if_no_authorized(HttpClient $client, Request $request, ResponseInterface $responseInterface, StreamInterface $streamInterface, RequestInterface $authorizationPsrRequest)
{
$this->authorizationRequestFactory->host()->willReturn('https://portus.com');
$this->authorizationRequestFactory->toPsrRequest(Argument::type(Request\Authorization::class))->willReturn($authorizationPsrRequest);
$client->sendRequest($authorizationPsrRequest)->willReturn($responseInterface);
$responseInterface->getStatusCode()->willReturn(403);
$responseInterface->getBody()->willReturn($streamInterface);
$streamInterface->getContents()->willReturn('not authorized');
$this->shouldThrow(DockerRegistryException::class)->during('authorizationHeader', [$client, $request]);
}
}
| mit |
michelfernandes/crescer-2016-1 | src/modulo-01-java-OO/projeto-lotr-bluej/SindarinParaInglesTest.java | 352 |
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class SindarinParaInglesTest
{
@Test
public void traduzirNaurParaIngles(){
//naur
TradutorSindarin tradutorIngles = new SindarinParaIngles();
assertEquals("fire",tradutorIngles.traduzir("naur"));
}
}
| mit |
born2net/ng2-minimal | src/app/heroes/hero-detail.component.ts | 1665 | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Hero, HeroService } from './hero.service';
@Component({
template: `
<h2>HEROES</h2>
<div *ngIf="hero">
<h3>"{{hero.name}}"</h3>
<div>
<label>Id: </label>{{hero.id}}</div>
<div>
<label>Name: </label>
<input [(ngModel)]="hero.name" placeholder="name"/>
</div>
<p>
<button (click)="gotoHeroes()">Back</button>
</p>
</div>
`,
})
export class HeroDetailComponent implements OnInit, OnDestroy {
hero: Hero;
sub: any;
constructor(
private router: Router,
private route: ActivatedRoute,
private service: HeroService) {}
ngOnInit() {
this.sub = this.route
.params
.subscribe(params => {
let id = +params['id'];
this.service.getHero(id)
.then(hero => this.hero = hero);
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
gotoHeroes() {
let heroId = this.hero ? this.hero.id : null;
// Pass along the hero id if available
// so that the HeroList component can select that hero.
// Add a totally useless `foo` parameter for kicks.
this.router.navigate(['/heroes'], { queryParams: { id: `${heroId}`, foo: 'foo' } });
}
}
/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/ | mit |
gclusters/gclusters | biblio_all.php | 4808 | <?php
include 'conn.php';
include 'inte2.php';
include 'columns.php';
// define queries ...
$page= $_GET['page'];
$pgn = $page * 25;
$query_auth = "SELECT * FROM biblioclusters ORDER BY biblio_date DESC LIMIT $pgn,25";
$result = mysql_query($query_auth) or die("Sorry, not a valid query!");
$numres = mysql_num_rows($result);
?>
<HTML>
<HEAD>
<TITLE>Gclusters :: Selected bibliography</TITLE>
<meta name="author" content="Marco Castellani">
<meta name="Keywords" content="astronomy, Milky Way, globular clusters">
</HEAD>
<body background="backgr2.jpg">
<div style="text-align: center;">
<table border=3>
<tr><td><b>
Selected bibliography and CMDs
</b></td></tr>
</table>
<p>
</div>
<?php
if (!$page) {
echo '<h2><i>Most recent 25 papers added to Gclusters</i><p>';
} else {
echo '<h3>...Browsing selected bibliography...</h3></i><p>';
}
$pagen=$page-1;
$pagep=$page+1;
echo "<table border=2><tr>";
if ($page!=0) {
echo "<td><a href=\"biblio_all.php?page=$pagen\">Previous page</a></td>";
echo "<td><b><a href=\"biblio_all.php?page=0\">Top</a></b></td>";
}
echo "<td><a href=\"biblio_all.php?page=$pagep\">Next page</a></td>";
echo "</tr></table><p>";
$iiref=0;
// $line cicla su tutti i papers
while ($line = mysql_fetch_row($result)) {
$iiref++;
// cerco tutti i tag disponibili per il dato paper.
// $line[4] è "ID" del paper
$query_names = "SELECT tag FROM bibliotags WHERE paper = '$line[4]'";
$res_names = mysql_query($query_names) or die ("query_names failed");
$num_paper= mysql_num_rows($res_names);
// Provo intanto ad aprire il CMD come un link...
// $line[9] è "linkima" del paper in "biblioclusters"
$ggc_cmd_web=$line[9];
@ $fpweb = fopen ($ggc_cmd_web, "r");
if ($fpweb) {
$ggc_cmd=$ggc_cmd_web; // la variabile è una URL valida
} else {
// Individuo il nome corretto per il file con il CMD...
// $line[7] è "cmdiagrams" in "bibliocusters"
$ggc_cmd_new="ima/".$line[7]; // associo il path
$ggc_cmd_png=$ggc_cmd_new.'.png'; // estensione png
$ggc_cmd_gif=$ggc_cmd_new.'.gif'; // estensione gif
$ggc_cmd_jpg=$ggc_cmd_new.'.jpg'; // estensione jpg
// Provo ad aprire i files con le differenti estesioni...
@ $fpp_new = fopen ($ggc_cmd_new, "r"); // no aggiunte
@ $fpp_png = fopen ($ggc_cmd_png, "r"); // png
@ $fpp_gif = fopen ($ggc_cmd_gif, "r"); // gif
@ $fpp_jpg = fopen ($ggc_cmd_jpg, "r"); // jpg
// Scelgo il file che "si apre"...
if($fpp_new) {
$ggc_cmd=$ggc_cmd_new; // already ok
} else if ($fpp_png) {
$ggc_cmd=$ggc_cmd_png; // PNG is ok
} else if ($fpp_gif) { // GIF is ok
} else if ($fpp_jpg) {
$ggc_cmd=$ggc_cmd_jpg; // JPG is ok
}
}
?>
<table width="90%" border=2>
<tr>
<td colspan=2 align=CENTER BGCOLOR="#99CCFF"><b>
<?php
$iaref=$pgn+$iiref;
echo 'Paper n. '.$iaref;
?>
</td>
</tr>
<?php
// Author
echo '<tr>';
echo '<td width="20%"> ';
echo 'Author';
echo '</td><td>';
echo $line[0];
echo "</td></tr>\n";
// Title & Link
echo "<tr><td>\n";
echo 'Title';
echo "</td><td>\n";
echo '<a href=';
echo "article.php?idart=$line[4]";
echo ">";
echo $line[1];
echo "</a>";
echo "</td></tr>\n";
// Journal
echo "<tr><td>\n";
echo 'Journal';
echo "</td><td>\n";
echo $line[2];
echo "</td></tr>\n";
// Year
if ($line[6]!="0")
{
echo "<tr><td>\n";
echo 'Year';
echo '</td><td>';
echo $line[6];
echo "</td></tr>\n";
}
// Color-magnitude diagram
if ($line[7]!="" or $line[9]!="")
{
echo "<tr><td>\n";
echo 'CM diagram';
echo '</td><td>';
echo '<img src='.$ggc_cmd.' width="400">';
echo "</td></tr>\n";
}
// ***************** blocco A2 *****************
echo '<tr><td>';
echo 'Tags';
echo "</td><td>\n";
for ($nnp=0; $nnp < $num_paper; $nnp++)
{
$ntag = mysql_fetch_row($res_names);
echo "<b>".$ntag[0]."</b>";
if ($nnp < $num_paper-1)
{
echo ", ";
}
}
echo "</td></tr>\n";
// **********************************************
// data di inserimento nel database
if ($line[8]!="0000-00-00")
{
echo '<tr><td>';
echo '<i>Added on:</i>';
echo '</td><td><i>';
echo $line[8];
echo "</i></td></tr>\n";
}
echo "</table><p>\n";
}
// Closing connection
mysql_close($link);
echo "<p>Query processed at ";
echo date("H:i, jS F");
echo "<br>";
include 'coda.html';
echo'</p>';
?>
</body>
</html>
| mit |
glapointe7/CryptoGL | src/Skipjack.cpp | 3246 | #include "Skipjack.hpp"
using namespace CryptoGL;
constexpr std::array<uint8_t, 256> Skipjack::f_table;
void Skipjack::setKey(const BytesVector &key)
{
const uint8_t key_len = key.size();
if (key_len != 10)
{
throw BadKeyLength("Your key has to be 10 bytes length.", key_len);
}
this->key = key;
}
void Skipjack::generateSubkeys()
{
subkeys = key;
}
uint8_t Skipjack::F(const uint8_t half_block, const uint8_t round) const
{
return f_table[half_block ^ subkeys[round]];
}
void Skipjack::encodeFeistelRounds(uint8_t& L, uint8_t& R, const uint8_t round) const
{
L ^= F(R, round % 10);
R ^= F(L, (round + 1) % 10);
L ^= F(R, (round + 2) % 10);
R ^= F(L, (round + 3) % 10);
}
void Skipjack::decodeFeistelRounds(uint8_t& L, uint8_t& R, const uint8_t round) const
{
L ^= F(R, (round + 3) % 10);
R ^= F(L, (round + 2) % 10);
L ^= F(R, (round + 1) % 10);
R ^= F(L, round % 10);
}
void Skipjack::applyRuleAOnBlock(const uint8_t round)
{
const uint16_t tmp = current_block[3];
current_block[3] = current_block[2];
current_block[2] = current_block[1];
uint8_t L = current_block[0] >> 8;
uint8_t R = current_block[0] & 0xFF;
encodeFeistelRounds(L, R, round * 4);
current_block[1] = (L << 8) | R;
current_block[0] = tmp ^ current_block[1] ^ (round + 1);
}
void Skipjack::applyRuleBOnBlock(const uint8_t round)
{
const uint16_t tmp = current_block[3];
current_block[3] = current_block[2];
current_block[2] = current_block[0] ^ current_block[1] ^ (round + 1);
uint8_t L = current_block[0] >> 8;
uint8_t R = current_block[0] & 0xFF;
encodeFeistelRounds(L, R, round * 4);
current_block[1] = (L << 8) | R;
current_block[0] = tmp;
}
void Skipjack::applyInverseRuleAOnBlock(const uint8_t round)
{
const uint16_t tmp = current_block[0] ^ current_block[1] ^ (round + 1);
uint8_t R = current_block[1] >> 8;
uint8_t L = current_block[1] & 0xFF;
decodeFeistelRounds(L, R, round * 4);
current_block[0] = (R << 8) | L;
current_block[1] = current_block[2];
current_block[2] = current_block[3];
current_block[3] = tmp;
}
void Skipjack::applyInverseRuleBOnBlock(const uint8_t round)
{
const uint16_t tmp = current_block[0];
uint8_t R = current_block[1] >> 8;
uint8_t L = current_block[1] & 0xFF;
decodeFeistelRounds(L, R, round * 4);
current_block[0] = (R << 8) | L;
current_block[1] = current_block[0] ^ current_block[2] ^ (round + 1);
current_block[2] = current_block[3];
current_block[3] = tmp;
}
void Skipjack::processEncodingCurrentBlock()
{
for (uint8_t i = 0; i < 8; ++i)
applyRuleAOnBlock(i);
for (uint8_t i = 8; i < 16; ++i)
applyRuleBOnBlock(i);
for (uint8_t i = 16; i < 24; ++i)
applyRuleAOnBlock(i);
for (uint8_t i = 24; i < 32; ++i)
applyRuleBOnBlock(i);
}
void Skipjack::processDecodingCurrentBlock()
{
for (uint8_t i = 31; i >= 24; --i)
applyInverseRuleBOnBlock(i);
for (uint8_t i = 23; i >= 16; --i)
applyInverseRuleAOnBlock(i);
for (uint8_t i = 15; i >= 8; --i)
applyInverseRuleBOnBlock(i);
for (int8_t i = 7; i >= 0; --i)
applyInverseRuleAOnBlock(i);
} | mit |
graphology/graphology-layout-forceatlas2 | helpers.js | 5396 | /**
* Graphology ForceAtlas2 Helpers
* ===============================
*
* Miscellaneous helper functions.
*/
/**
* Constants.
*/
var PPN = 10,
PPE = 3;
/**
* Very simple Object.assign-like function.
*
* @param {object} target - First object.
* @param {object} [...objects] - Objects to merge.
* @return {object}
*/
exports.assign = function(target) {
target = target || {};
var objects = Array.prototype.slice.call(arguments).slice(1),
i,
k,
l;
for (i = 0, l = objects.length; i < l; i++) {
if (!objects[i])
continue;
for (k in objects[i])
target[k] = objects[i][k];
}
return target;
};
/**
* Function used to validate the given settings.
*
* @param {object} settings - Settings to validate.
* @return {object|null}
*/
exports.validateSettings = function(settings) {
if ('linLogMode' in settings &&
typeof settings.linLogMode !== 'boolean')
return {message: 'the `linLogMode` setting should be a boolean.'};
if ('outboundAttractionDistribution' in settings &&
typeof settings.outboundAttractionDistribution !== 'boolean')
return {message: 'the `outboundAttractionDistribution` setting should be a boolean.'};
if ('adjustSizes' in settings &&
typeof settings.adjustSizes !== 'boolean')
return {message: 'the `adjustSizes` setting should be a boolean.'};
if ('edgeWeightInfluence' in settings &&
typeof settings.edgeWeightInfluence !== 'number' &&
settings.edgeWeightInfluence < 0)
return {message: 'the `edgeWeightInfluence` setting should be a number >= 0.'};
if ('scalingRatio' in settings &&
typeof settings.scalingRatio !== 'number' &&
settings.scalingRatio < 0)
return {message: 'the `scalingRatio` setting should be a number >= 0.'};
if ('strongGravityMode' in settings &&
typeof settings.strongGravityMode !== 'boolean')
return {message: 'the `strongGravityMode` setting should be a boolean.'};
if ('gravity' in settings &&
typeof settings.gravity !== 'number' &&
settings.gravity < 0)
return {message: 'the `gravity` setting should be a number >= 0.'};
if ('slowDown' in settings &&
typeof settings.slowDown !== 'number' &&
settings.slowDown < 0)
return {message: 'the `slowDown` setting should be a number >= 0.'};
if ('barnesHutOptimize' in settings &&
typeof settings.barnesHutOptimize !== 'boolean')
return {message: 'the `barnesHutOptimize` setting should be a boolean.'};
if ('barnesHutTheta' in settings &&
typeof settings.barnesHutTheta !== 'number' &&
settings.barnesHutTheta < 0)
return {message: 'the `barnesHutTheta` setting should be a number >= 0.'};
return null;
};
/**
* Function generating a flat matrix for both nodes & edges of the given graph.
*
* @param {Graph} graph - Target graph.
* @return {object} - Both matrices.
*/
exports.graphToByteArrays = function(graph) {
var order = graph.order,
size = graph.size,
index = {},
j;
var NodeMatrix = new Float32Array(order * PPN),
EdgeMatrix = new Float32Array(size * PPE);
// Iterate through nodes
j = 0;
graph.forEachNode(function(node, attr) {
// Node index
index[node] = j;
// Populating byte array
NodeMatrix[j] = attr.x;
NodeMatrix[j + 1] = attr.y;
NodeMatrix[j + 2] = 0;
NodeMatrix[j + 3] = 0;
NodeMatrix[j + 4] = 0;
NodeMatrix[j + 5] = 0;
NodeMatrix[j + 6] = 1 + graph.degree(node);
NodeMatrix[j + 7] = 1;
NodeMatrix[j + 8] = attr.size || 1;
NodeMatrix[j + 9] = attr.fixed ? 1 : 0;
j += PPN;
});
// Iterate through edges
j = 0;
graph.forEachEdge(function(edge, attr, source, target) {
// Populating byte array
EdgeMatrix[j] = index[source];
EdgeMatrix[j + 1] = index[target];
EdgeMatrix[j + 2] = attr.weight || 0;
j += PPE;
});
return {
nodes: NodeMatrix,
edges: EdgeMatrix
};
};
/**
* Function applying the layout back to the graph.
*
* @param {Graph} graph - Target graph.
* @param {Float32Array} NodeMatrix - Node matrix.
*/
exports.assignLayoutChanges = function(graph, NodeMatrix) {
var i = 0;
graph.updateEachNodeAttributes(function(node, attr) {
attr.x = NodeMatrix[i];
attr.y = NodeMatrix[i + 1];
i += PPN;
return attr;
}, {attributes: ['x', 'y']});
};
/**
* Function collecting the layout positions.
*
* @param {Graph} graph - Target graph.
* @param {Float32Array} NodeMatrix - Node matrix.
* @return {object} - Map to node positions.
*/
exports.collectLayoutChanges = function(graph, NodeMatrix) {
var nodes = graph.nodes(),
positions = {};
for (var i = 0, j = 0, l = NodeMatrix.length; i < l; i += PPN) {
positions[nodes[j]] = {
x: NodeMatrix[i],
y: NodeMatrix[i + 1]
};
j++;
}
return positions;
};
/**
* Function returning a web worker from the given function.
*
* @param {function} fn - Function for the worker.
* @return {DOMString}
*/
exports.createWorker = function createWorker(fn) {
var xURL = window.URL || window.webkitURL;
var code = fn.toString();
var objectUrl = xURL.createObjectURL(new Blob(['(' + code + ').call(this);'], {type: 'text/javascript'}));
var worker = new Worker(objectUrl);
xURL.revokeObjectURL(objectUrl);
return worker;
};
| mit |
victorrentea/training | jee7/src/main/java/victor/training/jee7/jms20/MessageReceiverSync.java | 547 | package victor.training.jee7.jms20;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.jms.JMSContext;
import javax.jms.Queue;
@Stateless
public class MessageReceiverSync {
@Inject
private JMSContext context;
@Resource(mappedName = "java:global/jms/myResponseQueue")
Queue responseQueue;
public String receiveMessage() {
MyJavaMessage message = context
.createConsumer(responseQueue)
.receiveBody(MyJavaMessage.class);
return "MessageReceiverSync:Received " + message;
}
} | mit |
ValmirJ/Projeto-Integrado-3-Bingo | Bingo/src/bingo/interactions/ConnectWithRa.java | 1154 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bingo.interactions;
import bingo.FormManager;
import bingo.TelaInicial;
import bingo.TelaSalas;
import org.json.simple.JSONObject;
/**
*
* @author valmir
*/
public class ConnectWithRa extends Interactor{
private TelaInicial telaInicial;
private TelaSalas telaSalas;
public ConnectWithRa() {
super();
}
public void perform(JSONObject params ) throws Exception {
telaInicial = this.getFormManager().getTelaInicial();
String typeReturned = (String) params.get("type");
if(typeReturned.equals("ra-em-uso"))
telaInicial.showRaAlreadyUsed();
else {
if(typeReturned.equals("ra-invalido"))
telaInicial.showInvalidRa();
else {
getFormManager().hideCurrent();
this.telaSalas = this.getFormManager().getTelaSalas();
this.telaSalas.setVisible(true);
}
}
}
}
| mit |
ClubObsidian/ObsidianEngine | src/com/clubobsidian/obsidianengine/asm/commons/RemappingSignatureAdapter.java | 4716 | /***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.clubobsidian.obsidianengine.asm.commons;
import com.clubobsidian.obsidianengine.asm.Opcodes;
import com.clubobsidian.obsidianengine.asm.signature.SignatureVisitor;
/**
* A {@link SignatureVisitor} adapter for type mapping.
*
* @deprecated use {@link SignatureRemapper} instead.
* @author Eugene Kuleshov
*/
@Deprecated
public class RemappingSignatureAdapter extends SignatureVisitor {
private final SignatureVisitor v;
private final Remapper remapper;
private String className;
public RemappingSignatureAdapter(final SignatureVisitor v,
final Remapper remapper) {
this(Opcodes.ASM5, v, remapper);
}
protected RemappingSignatureAdapter(final int api,
final SignatureVisitor v, final Remapper remapper) {
super(api);
this.v = v;
this.remapper = remapper;
}
@Override
public void visitClassType(String name) {
className = name;
v.visitClassType(remapper.mapType(name));
}
@Override
public void visitInnerClassType(String name) {
String remappedOuter = remapper.mapType(className) + '$';
className = className + '$' + name;
String remappedName = remapper.mapType(className);
int index = remappedName.startsWith(remappedOuter) ? remappedOuter
.length() : remappedName.lastIndexOf('$') + 1;
v.visitInnerClassType(remappedName.substring(index));
}
@Override
public void visitFormalTypeParameter(String name) {
v.visitFormalTypeParameter(name);
}
@Override
public void visitTypeVariable(String name) {
v.visitTypeVariable(name);
}
@Override
public SignatureVisitor visitArrayType() {
v.visitArrayType();
return this;
}
@Override
public void visitBaseType(char descriptor) {
v.visitBaseType(descriptor);
}
@Override
public SignatureVisitor visitClassBound() {
v.visitClassBound();
return this;
}
@Override
public SignatureVisitor visitExceptionType() {
v.visitExceptionType();
return this;
}
@Override
public SignatureVisitor visitInterface() {
v.visitInterface();
return this;
}
@Override
public SignatureVisitor visitInterfaceBound() {
v.visitInterfaceBound();
return this;
}
@Override
public SignatureVisitor visitParameterType() {
v.visitParameterType();
return this;
}
@Override
public SignatureVisitor visitReturnType() {
v.visitReturnType();
return this;
}
@Override
public SignatureVisitor visitSuperclass() {
v.visitSuperclass();
return this;
}
@Override
public void visitTypeArgument() {
v.visitTypeArgument();
}
@Override
public SignatureVisitor visitTypeArgument(char wildcard) {
v.visitTypeArgument(wildcard);
return this;
}
@Override
public void visitEnd() {
v.visitEnd();
}
}
| mit |
joelghill/PocketRockets | PocketRocket/Assets/ModularRocket/ModularRocket2DBounds.cs | 1958 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PocketRockets;
using System;
namespace PocketRockets.ModularRocket
{
public class ModularRocket2DBounds : MonoBehaviour, IBoundingBox2d {
public Bounds RocketBounds;
private ModularRocketPart rocketPart;
// Use this for initialization
void Start()
{
this.rocketPart = this.gameObject.GetComponent<ModularRocketPart>();
}
private void CalculateLocalBounds()
{
this.RocketBounds = new Bounds(transform.position, Vector3.one);
foreach (var rocketPart in this.rocketPart.GetAttachedModularParts())
{
var renderer = rocketPart.gameObject.GetComponent<Renderer>();
this.RocketBounds.Encapsulate(renderer.bounds);
}
}
// Update is called once per frame
void Update()
{
this.CalculateLocalBounds();
}
public float GetBottomEdge()
{
return this.RocketBounds.center.y - this.RocketBounds.extents.y;
}
public float GetLeftEdge()
{
return this.RocketBounds.center.x - this.RocketBounds.extents.x;
}
public float GetRightEdge()
{
return this.RocketBounds.center.x + this.RocketBounds.extents.x;
}
public float GetTopEdge()
{
return this.RocketBounds.center.y + this.RocketBounds.extents.y;
}
public BoundingEdges GetBoundingEdges()
{
return new BoundingEdges()
{
Left = this.GetLeftEdge(),
Right = this.GetRightEdge(),
Top = this.GetTopEdge(),
Bottom = this.GetBottomEdge()
};
}
public Vector3 GetPosition()
{
return this.RocketBounds.center;
}
}
}
| mit |
sigaind/cupon | vendor/sonata-project/admin-bundle/Sonata/AdminBundle/Controller/HelperController.php | 8863 | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\Util\PropertyPath;
use Symfony\Component\HttpFoundation\Request;
use Sonata\AdminBundle\Admin\Pool;
use Sonata\AdminBundle\Admin\AdminHelper;
class HelperController
{
/**
* @var \Twig_Environment
*/
protected $twig;
/**
* @var \Sonata\AdminBundle\Admin\AdminHelper
*/
protected $helper;
/**
* @var \Sonata\AdminBundle\Admin\Pool
*/
protected $pool;
/**
* @param \Twig_Environment $twig
* @param \Sonata\AdminBundle\Admin\Pool $pool
* @param \Sonata\AdminBundle\Admin\AdminHelper $helper
*/
public function __construct(\Twig_Environment $twig, Pool $pool, AdminHelper $helper)
{
$this->twig = $twig;
$this->pool = $pool;
$this->helper = $helper;
}
/**
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*
* @param \Symfony\Component\HttpFoundation\Request $request
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function appendFormFieldElementAction(Request $request)
{
$code = $request->get('code');
$elementId = $request->get('elementId');
$objectId = $request->get('objectId');
$uniqid = $request->get('uniqid');
$admin = $this->pool->getInstance($code);
$admin->setRequest($request);
if ($uniqid) {
$admin->setUniqid($uniqid);
}
$subject = $admin->getModelManager()->find($admin->getClass(), $objectId);
if ($objectId && !$subject) {
throw new NotFoundHttpException;
}
if (!$subject) {
$subject = $admin->getNewInstance();
}
$admin->setSubject($subject);
list($fieldDescription, $form) = $this->helper->appendFormFieldElement($admin, $subject, $elementId);
/** @var $form \Symfony\Component\Form\Form */
$view = $this->helper->getChildFormView($form->createView(), $elementId);
// render the widget
// todo : fix this, the twig environment variable is not set inside the extension ...
$extension = $this->twig->getExtension('form');
$extension->initRuntime($this->twig);
$extension->renderer->setTheme($view, $admin->getFormTheme());
return new Response($extension->renderer->searchAndRenderBlock($view, 'widget'));
}
/**
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*
* @param \Symfony\Component\HttpFoundation\Request $request
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function retrieveFormFieldElementAction(Request $request)
{
$code = $request->get('code');
$elementId = $request->get('elementId');
$objectId = $request->get('objectId');
$uniqid = $request->get('uniqid');
$admin = $this->pool->getInstance($code);
if ($uniqid) {
$admin->setUniqid($uniqid);
}
if ($objectId) {
$subject = $admin->getModelManager()->find($admin->getClass(), $objectId);
if (!$subject) {
throw new NotFoundHttpException(sprintf('Unable to find the object id: %s, class: %s', $objectId, $admin->getClass()));
}
} else {
$subject = $admin->getNewInstance();
}
$admin->setSubject($subject);
$formBuilder = $admin->getFormBuilder($subject);
$form = $formBuilder->getForm();
$form->bindRequest($request);
$view = $this->helper->getChildFormView($form->createView(), $elementId);
// render the widget
// todo : fix this, the twig environment variable is not set inside the extension ...
$extension = $this->twig->getExtension('form');
$extension->initRuntime($this->twig);
$extension->renderer->setTheme($view, $admin->getFormTheme());
return new Response($extension->renderer->searchAndRenderBlock($view, 'widget'));
}
/**
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*
* @param \Symfony\Component\HttpFoundation\Request $request
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function getShortObjectDescriptionAction(Request $request)
{
$code = $request->get('code');
$objectId = $request->get('objectId');
$uniqid = $request->get('uniqid');
$admin = $this->pool->getInstance($code);
if (!$admin) {
throw new NotFoundHttpException();
}
if ($uniqid) {
$admin->setUniqid($uniqid);
}
$object = $admin->getObject($objectId);
if (!$object) {
return new Response();
}
$description = 'no description available';
foreach (array('getAdminTitle', 'getTitle', 'getName', '__toString') as $method) {
if (method_exists($object, $method)) {
$description = call_user_func(array($object, $method));
break;
}
}
$url = $admin->generateUrl('edit', array('id' => $objectId));
$htmlOutput = $this->twig->render($admin->getTemplate('short_object_description'),
array(
'description' => $description,
'object' => $object,
'url' => $url
)
);
return new Response($htmlOutput);
}
/**
* @param \Symfony\Component\HttpFoundation\Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function setObjectFieldValueAction(Request $request)
{
$field = $request->get('field');
$code = $request->get('code');
$objectId = $request->get('objectId');
$value = $request->get('value');
$context = $request->get('context');
$admin = $this->pool->getInstance($code);
// alter should be done by using a post method
if ($request->getMethod() != 'POST') {
return new Response(json_encode(array('status' => 'KO', 'message' => 'Expected a POST Request')), 200, array(
'Content-Type' => 'application/json'
));
}
$object = $admin->getObject($objectId);
if (!$object) {
return new Response(json_encode(array('status' => 'KO', 'message' => 'Object does not exist')), 200, array(
'Content-Type' => 'application/json'
));
}
// check user permission
if (false === $admin->isGranted('EDIT', $object)) {
return new Response(json_encode(array('status' => 'KO', 'message' => 'Invalid permissions')), 200, array(
'Content-Type' => 'application/json'
));
}
if ($context == 'list') {
$fieldDescription = $admin->getListFieldDescription($field);
} else {
return new Response(json_encode(array('status' => 'KO', 'message' => 'Invalid context')), 200, array(
'Content-Type' => 'application/json'
));
}
if (!$fieldDescription) {
return new Response(json_encode(array('status' => 'KO', 'message' => 'The field does not exist')), 200, array(
'Content-Type' => 'application/json'
));
}
if (!$fieldDescription->getOption('editable')) {
return new Response(json_encode(array('status' => 'KO', 'message' => 'The field cannot be edit, editable option must be set to true')), 200, array(
'Content-Type' => 'application/json'
));
}
// TODO : call the validator component ...
$propertyPath = new PropertyPath($field);
$propertyPath->setValue($object, $value);
$admin->update($object);
// render the widget
// todo : fix this, the twig environment variable is not set inside the extension ...
$extension = $this->twig->getExtension('sonata_admin');
$extension->initRuntime($this->twig);
$content = $extension->renderListElement($object, $fieldDescription);
return new Response(json_encode(array('status' => 'OK', 'content' => $content)), 200, array(
'Content-Type' => 'application/json'
));
}
} | mit |
jeck5895/jfo-master | assets/js/admin/report.js | 939 | $(function() {
var ctx = $("#yearly-chart").get(0).getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July","August","September","October","November","December"],
datasets:
[
{
label: 'Employers',
backgroundColor: '#F44336',
data: [12, 19, 10, 17, 28, 52, 4, 13, 11, 31, 23, 41], //to populate from database
},
{
label: 'Applicants',
backgroundColor: '#803690',
data: [17, 22, 5, 5, 23, 33, 5, 3, 53, 32, 12, 23, 12], //to populate from database
},
{
label: 'Job Posts',
backgroundColor: '#46BFBD',
data: [20, 21, 12, 5, 31, 13, 20, 12, 43, 53, 87, 91], //to populate from database
},
{
label: 'Applications',
backgroundColor: '#FDB45C',
data: [30, 29, 15, 5, 20, 35, 10, 23, 12, 31, 13, 31], //to populate from database
}
]
}
});
}); | mit |
hellofresh/rx.php-examples | src/Client/Memory/Converter/UserConverter.php | 568 | <?php
namespace Client\Memory\Converter;
use HelloFresh\Repository\UserRepositoryInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class UserConverter
{
/** @var UserRepositoryInterface */
private $repo;
public function __construct(UserRepositoryInterface $repo)
{
$this->repo = $repo;
}
public function convert($id)
{
if (null === $user = $this->repo->find($id)) {
throw new NotFoundHttpException(sprintf('User %d does not exist', $id));
}
return $user;
}
} | mit |
linyows/h2o-cookbook | recipes/source.rb | 897 | # Cookbook Name:: h2o
# Recipe:: source
build_essential 'install_build_packages'
case node['platform_family']
when 'rhel', 'fedora'
package %w[curl unzip cmake openssl-devel libyaml-devel]
when 'debian'
package %w[curl unzip cmake pkg-config libssl-dev zlib1g-dev]
end
version = node['h2o']['download_version']
cache_path = Chef::Config[:file_cache_path]
remote_file "#{cache_path}/h2o-#{version}.zip" do
source node['h2o']['download_url']
checksum node['h2o']['download_checksum']
action :create_if_missing
end
bash "expand h2o-#{version}" do
not_if "test -d #{cache_path}/h2o-#{version}"
code <<-CODE
cd #{cache_path}
unzip h2o-#{version}.zip
CODE
end
bash "install h2o-#{version}" do
code <<-CODE
cd #{cache_path}/h2o-#{version}
cmake -DWITH_BUNDLED_SSL=on .
make && make install
CODE
not_if "/usr/local/bin/h2o -v 2>&1 | grep -q #{version}"
end
| mit |
lucasmichot/PHP-CS-Fixer | tests/Fixer/ReturnNotation/SimplifiedNullReturnFixerTest.php | 1691 | <?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Tests\Fixer\ReturnNotation;
use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
/**
* @author Graham Campbell <graham@alt-three.com>
*
* @internal
*
* @covers \PhpCsFixer\Fixer\ReturnNotation\SimplifiedNullReturnFixer
*/
final class SimplifiedNullReturnFixerTest extends AbstractFixerTestCase
{
/**
* @param string $expected
* @param null|string $input
*
* @dataProvider provideExamples
*/
public function testFix($expected, $input = null)
{
$this->doTest($expected, $input);
}
public function provideExamples()
{
return [
// check correct statements aren't changed
['<?php return ;'],
['<?php return \'null\';'],
['<?php return false;'],
['<?php return (false );'],
['<?php return null === foo();'],
['<?php return array() == null ;'],
// check we modified those that can be changed
['<?php return;', '<?php return null;'],
['<?php return;', '<?php return (null);'],
['<?php return;', '<?php return ( null );'],
['<?php return;', '<?php return ( (( null)));'],
['<?php return /* hello */;', '<?php return /* hello */ null ;'],
['<?php return;', '<?php return NULL;'],
['<?php return;', "<?php return\n(\nnull\n)\n;"],
];
}
}
| mit |
rwl/PyCIM | CIM15/IEC61970/Informative/InfLocations/Zone.py | 2259 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from CIM15.IEC61968.Common.Location import Location
class Zone(Location):
"""Area divided off from other areas. It may be part of the electrical network, a land area where special restrictions apply, weather areas, etc. For weather, it is an area where a set of relatively homogenous weather measurements apply.Area divided off from other areas. It may be part of the electrical network, a land area where special restrictions apply, weather areas, etc. For weather, it is an area where a set of relatively homogenous weather measurements apply.
"""
def __init__(self, kind="weatherZone", *args, **kw_args):
"""Initialises a new 'Zone' instance.
@param kind: Kind of this zone. Values are: "weatherZone", "other", "specialRestrictionLand", "electricalNetwork"
"""
#: Kind of this zone. Values are: "weatherZone", "other", "specialRestrictionLand", "electricalNetwork"
self.kind = kind
super(Zone, self).__init__(*args, **kw_args)
_attrs = ["kind"]
_attr_types = {"kind": str}
_defaults = {"kind": "weatherZone"}
_enums = {"kind": "ZoneKind"}
_refs = []
_many_refs = []
| mit |
ActiveState/code | recipes/Python/52216_a_Python_daemon/recipe-52216.py | 228 | import sys
import os
if os.fork()==0:
os.setsid()
sys.stdout=open("/dev/null", 'w')
sys.stdin=open("/dev/null", 'r')
while(1):
# Daemon's main code goes here
pass
sys.exit(0)
| mit |
TylerK/ctci | 1. Strings/check-permutation.spec.js | 429 | const expect = require('chai').expect
const checkPermutation = require('./check-permutation')
describe('Check Permutation', () => {
it('Should return true if string A is a permutation of string B', () => {
expect(checkPermutation('abcdefg', 'gbefacd')).to.equal(true)
})
it('Should return false if the two strings are not the same length', () => {
expect(checkPermutation('abc', 'abcdef')).to.equal(false)
})
})
| mit |
FrenchYeti/ufo | framework/src/Db/Statement.php | 2784 | <?php
namespace Ufo\Db;
/**
* DatabaseStatementModel class.
* Intended as parent for all database prepared statement classes.
*/
class Statement
{
/**
* Object of type DatabaseModel
* @var \phpsec\DatabaseModel
*/
protected $db;
/**
* The query to be executed
* @var string
*/
protected $query;
/**
* Parameters to the query to be executed
* @var array
*/
protected $params;
/**
* PDOStatement object.
* @var \PDOStatement
*/
protected $statement;
/**
* Constructor of the class to set DB connection, query and statement
* @param \phpsec\DatabaseModel $db
* @param string $query
*/
public function __construct( Connexion $db, $query)
{
$this->db = $db;
$this->query = $query;
$this->statement = $db->getHandler()->prepare($query);
}
/**
* Destructor of the class
*/
public function __destruct ()
{
if (isset($this->statement))
{
$this->db = NULL;
$this->query = NULL;
$this->params = NULL;
$this->statement = NULL;
}
}
/**
* Fetches a row from a result set associated with a PDOStatement object.
* @return \PDO::FETCH_ASSOC The fetch_style parameter determines how PDO returns the row.
*/
public function fetch ()
{
return $this->statement->fetch (\PDO::FETCH_ASSOC);
}
/**
* Fetches all rows from a result set associated with a PDOStatement object.
* @return \PDO::FETCH_ASSOC The fetch_style parameter determines how PDO returns the row.
*/
public function fetchAll()
{
return $this->statement->fetchAll (\PDO::FETCH_ASSOC);
}
/**
* Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement.
*/
public function bindAll ()
{
$params = func_get_args ();
$this->params = $params;
$i = 0;
foreach ($params as &$param) {
$this->statement->bindValue (++$i, $param); //call the PDO's bindValue method to bind the value
}
}
/**
* Execute the prepared statement.
* @return boolean Returns TRUE on success or FALSE on failure.
*/
public function execute ()
{
$args = func_get_args (); //get all user arguments
if (!empty ($args[0]) && is_array ($args[0])) //If the argument contains an array that contains all the parameters, then execute the statement with all those parameters
return $this->statement->execute ($args[0]);
else
return $this->statement->execute (); //If the argument does not contain any parameter, then execute the statement without any parameters
}
/**
* Returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
* @return int Number of rows affected
*/
public function rowCount ()
{
return $this->statement->rowCount ();
}
}
?> | mit |
sanketbajoria/galaxy | src/app/views/download/downloadQueue.js | 258 | class DownloadQueue{
constructor(){
this.queue = [];
}
getAll(){
return this.queue;
}
push(item){
this.queue.push(item);
}
clear(){
this.queue = [];
}
}
module.exports = new DownloadQueue(); | mit |
TwilioDevEd/api-snippets | rest/transcription/list-get-example-1/list-get-example-1.5.x.rb | 500 | # Get twilio-ruby from twilio.com/docs/ruby/install
require 'twilio-ruby'
# Get your Account SID and Auth Token from twilio.com/console
# To set up environmental variables, see http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)
# Loop over transcriptions and print out a property for each one
@client.transcriptions.list.each do |transcription|
puts transcription.transcription_text
end
| mit |
theinbetweens/spread | lib/spread/version.rb | 38 | module Spread
VERSION = "0.0.1"
end
| mit |
cowboyd/ember-microstates | tests/unit/macros/state-test.js | 2771 | /* jshint expr:true */
import { expect } from 'chai';
import { describe, it } from 'mocha';
import { state, create } from '@microstates/ember';
import Object from '@ember/object';
describe('Unit: Macro | state', function() {
describe('with a value', function() {
let Container = Object.extend({
n: state(42)
});
it('allows to create a number type using state(42)', function() {
expect(Container.create().get('n.state')).to.equal(42);
});
it('allows to increment', function() {
let c = Container.create();
c.get('n').increment();
expect(c.n.state).to.equal(43);
});
it('does not share state between multiple instances', function() {
let c1 = Container.create();
let c2 = Container.create();
c1.get('n').increment();
expect(c1.get('n.state')).to.equal(43);
expect(c2.get('n.state')).to.equal(42);
});
});
describe('without arguments', function() {
let Container = Object.extend({
n: state()
});
it('allows to create a value without a Type', function() {
expect(Container.create().get('n.state')).to.equal(undefined);
});
it('allows to set', function() {
let c = Container.create();
c.get('n').set('hello world');
expect(c.n.state).to.equal('hello world');
});
});
describe('with a microstate as an argument', function() {
let Container = Object.extend({
n: state(create(Number, 42))
});
it('allows to create a number type using use(create(Number, 42))', function() {
expect(Container.create().get('n.state')).to.equal(42);
});
it('allows to increment', function() {
let c = Container.create();
c.get('n').increment();
expect(c.n.state).to.equal(43);
});
it('does not share state between multiple instances', function() {
let c1 = Container.create();
let c2 = Container.create();
c1.get('n').increment();
expect(c1.get('n.state')).to.equal(43);
expect(c2.get('n.state')).to.equal(42);
});
});
describe('with a type as an argument', function() {
let Container = Object.extend({
n: state(Number, 42)
});
it('allows to create a number type using useType(Number, 42)', function() {
expect(Container.create().get('n.state')).to.equal(42);
});
it('allows to increment', function() {
let c = Container.create();
c.get('n').increment();
expect(c.n.state).to.equal(43);
});
it('does not share state between multiple instances', function() {
let c1 = Container.create();
let c2 = Container.create();
c1.get('n').increment();
expect(c1.get('n.state')).to.equal(43);
expect(c2.get('n.state')).to.equal(42);
});
});
});
| mit |
begeekmyfriend/leetcode | 0297_serialize_and_deserialize_binary_tree/tree_serdes.cc | 1746 | #include <bits/stdc++.h>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res;
ser(root, res);
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int len = data.length();
return des(data.c_str(), &len);
}
private:
void ser(TreeNode* root, string& res) {
if (root == nullptr) {
res.push_back((char) 0x80);
res.push_back((char) 0x00);
res.push_back((char) 0x00);
res.push_back((char) 0x00);
return;
}
ser(root->left, res);
ser(root->right, res);
for (int i = sizeof(int) - 1; i >= 0; i--) {
res.push_back(((char *)&root->val)[i]);
}
}
TreeNode* des(const char *data, int *len) {
if (*len == 0) {
return nullptr;
}
int value;
const char *s = data + *len - 1;
for (int i = 0; i < sizeof(int); i++) {
((char *)&value)[i] = *s--;
}
if (value == INT_MIN) {
(*len) -= sizeof(int);
return nullptr;
}
(*len) -= sizeof(int);
TreeNode *root = new TreeNode(value);
root->right = des(data, len);
root->left = des(data, len);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));
| mit |
thinkingmik/ideman-cli | bin/scripts/dropTables.js | 3318 | var Promise = require('bluebird');
var Configuration = require('../configuration');
var dropsIdemanTables = function() {
return new Promise(function(resolve, reject) {
var config = Configuration.getConfig();
var tables = config.tables.entities;
var prefix = config.tables.prefix;
var knex = require('knex')(config.database);
return knex.schema.hasTable(prefix + tables.policy.table)
.then(function(exists) {
if (exists) {
console.log('[DROP] drop ' + tables.policy.table + ' table');
return knex.schema.dropTable(prefix + tables.policy.table);
}
})
.then(function() {
return knex.schema.hasTable(prefix + tables.permission.table)
.then(function(exists) {
if (exists) {
console.log('[DROP] drop ' + tables.permission.table + ' table');
return knex.schema.dropTableIfExists(prefix + tables.permission.table);
}
});
})
.then(function() {
return knex.schema.hasTable(prefix + tables.resource.table)
.then(function(exists) {
if (exists) {
console.log('[DROP] drop ' + tables.resource.table + ' table');
return knex.schema.dropTableIfExists(prefix + tables.resource.table);
}
});
})
.then(function() {
return knex.schema.hasTable(prefix + tables.code.table)
.then(function(exists) {
if (exists) {
console.log('[DROP] drop ' + tables.code.table + ' table');
return knex.schema.dropTableIfExists(prefix + tables.code.table);
}
});
})
.then(function() {
return knex.schema.hasTable(prefix + tables.token.table)
.then(function(exists) {
if (exists) {
console.log('[DROP] drop ' + tables.token.table + ' table');
return knex.schema.dropTableIfExists(prefix + tables.token.table);
}
});
})
.then(function() {
return knex.schema.hasTable(prefix + tables.client.table)
.then(function(exists) {
if (exists) {
console.log('[DROP] drop ' + tables.client.table + ' table');
return knex.schema.dropTableIfExists(prefix + tables.client.table);
}
});
})
.then(function() {
return knex.schema.hasTable(prefix + tables.userRole.table)
.then(function(exists) {
if (exists) {
console.log('[DROP] drop ' + tables.userRole.table + ' table');
return knex.schema.dropTableIfExists(prefix + tables.userRole.table);
}
});
})
.then(function() {
return knex.schema.hasTable(prefix + tables.role.table)
.then(function(exists) {
if (exists) {
console.log('[DROP] drop ' + tables.role.table + ' table');
return knex.schema.dropTableIfExists(prefix + tables.role.table);
}
});
})
.then(function() {
return knex.schema.hasTable(prefix + tables.user.table)
.then(function(exists) {
if (exists) {
console.log('[DROP] drop ' + tables.user.table + ' table');
return knex.schema.dropTableIfExists(prefix + tables.user.table);
}
});
})
.then(function() {
return resolve(true);
})
.catch(function(err) {
return reject(err);
});
});
}
exports.idemanTables = dropsIdemanTables;
| mit |
dbishoponline/superdashboard | kendo/source/js/cultures/kendo.culture.ms-MY.js | 2451 | /*
* Kendo UI Web v2012.2.710 (http://kendoui.com)
* Copyright 2012 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at http://kendoui.com/web-license
* If you do not own a commercial license, this file shall be governed by the
* GNU General Public License (GPL) version 3.
* For GPL requirements, please review: http://www.gnu.org/copyleft/gpl.html
*/
(function( window, undefined ) {
kendo.cultures["ms-MY"] = {
name: "ms-MY",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["($n)","$n"],
decimals: 0,
",": ",",
".": ".",
groupSize: [3],
symbol: "RM"
}
},
calendars: {
standard: {
days: {
names: ["Ahad","Isnin","Selasa","Rabu","Khamis","Jumaat","Sabtu"],
namesAbbr: ["Ahad","Isnin","Sel","Rabu","Khamis","Jumaat","Sabtu"],
namesShort: ["A","I","S","R","K","J","S"]
},
months: {
names: ["Januari","Februari","Mac","April","Mei","Jun","Julai","Ogos","September","Oktober","November","Disember",""],
namesAbbr: ["Jan","Feb","Mac","Apr","Mei","Jun","Jul","Ogos","Sept","Okt","Nov","Dis",""]
},
AM: [""],
PM: [""],
patterns: {
d: "dd/MM/yyyy",
D: "dd MMMM yyyy",
F: "dd MMMM yyyy H:mm:ss",
g: "dd/MM/yyyy H:mm",
G: "dd/MM/yyyy H:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "H:mm",
T: "H:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "/",
":": ":",
firstDay: 1
}
}
}
})(this);
; | mit |
wcang/pytekcap | tekcap.py | 870 | def nl_str(value):
return ns_str((value & 0xffff0000) >> 16) + ns_str(value)
def ns_str(value):
return chr((value & 0xff00) >> 8) + chr((value & 0xff))
def nc_str(value):
return chr(value & 0xff)
class tekcap:
def __setattr__(self, attr, value):
for index, field in enumerate(self.fields):
if field == attr:
self.__dict__[attr] = self.validator[index](value)
break
else:
raise AttributeError, attr
def __getattr__(self, attr):
if attr not in self.fields:
raise AttributeError, attr
return self.__dict__[attr]
def join(*args):
checking = []
buf = ''
prev_pkt = None
for pkt in args:
if hasattr(pkt, 'need_csum') and pkt.need_csum():
checking.append((prev_pkt, pkt, len(buf)))
buf = buf + str(pkt)
prev_pkt = pkt
for (prev_pkt, pkt, offset) in checking:
buf = pkt.perform_checksum(prev_pkt, buf, offset)
return buf
| mit |
palmerev/react-pomodoro | constants.js | 217 | export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'
export const statuses = {
INACTIVE: 'INACTIVE',
BREAK: 'BREAK',
WORK: 'WORK'
}
export default {
INCREMENT,
DECREMENT,
statuses
}
| mit |
leagueofcake/Project-Resistance | src/client/main/conversation/components/MessageHistory.stories.js | 603 | import React from 'react';
import { withKnobs, object } from '@storybook/addon-knobs';
import MessageHistory from './MessageHistory';
import { messageData } from './Message.stories';
export default {
component: MessageHistory,
title: 'MainPanel/Conversation/Components/MessageHistory',
decorators: [withKnobs],
excludeStories: /.*Data$/,
};
const WrappedMessageHistory = ({ messages }) => (
<div className="container">
<MessageHistory
messages={object('messages', [...messages])}
/>
</div>
);
export const Default = () => <WrappedMessageHistory messages={messageData} />; | mit |
nodkz/graphql-compose-elasticsearch | src/elasticDSL/Query/Compound/FunctionScore.js | 2562 | /* @flow */
import { InputTypeComposer } from 'graphql-compose';
import { getQueryITC, prepareQueryInResolve } from '../Query';
import { getTypeName, type CommonOpts, desc } from '../../../utils';
export function getFunctionScoreITC<TContext>(
opts: CommonOpts<TContext>
): InputTypeComposer<TContext> {
const name = getTypeName('QueryFunctionScore', opts);
const description = desc(
`
The function_score allows you to modify the score of documents that
are retrieved by a query. This can be useful if, for example,
a score function is computationally expensive and it is sufficient
to compute the score on a filtered set of documents.
[Documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html)
`
);
const RandomScoreType = opts.schemaComposer.createInputTC({
name: getTypeName('QueryFunctionScoreRandom', opts),
fields: {
seed: 'Float',
},
});
return opts.getOrCreateITC(name, () => ({
name,
description,
fields: {
query: (): InputTypeComposer<TContext> => getQueryITC(opts),
boost: 'String',
boost_mode: {
type: 'String',
description: 'Can be: `multiply`, `replace`, `sum`, `avg`, `max`, `min`.',
},
random_score: RandomScoreType,
functions: [
opts.schemaComposer.createInputTC({
name: getTypeName('QueryFunctionScoreFunction', opts),
fields: {
filter: (): InputTypeComposer<TContext> => getQueryITC(opts),
random_score: RandomScoreType,
weight: 'Float',
script_score: 'JSON',
field_value_factor: 'JSON',
gauss: 'JSON',
linear: 'JSON',
exp: 'JSON',
},
}),
],
max_boost: 'Float',
score_mode: {
type: 'String',
description: 'Can be: `multiply`, `sum`, `avg`, `first`, `max`, `min`.',
},
min_score: 'Float',
},
}));
}
/* eslint-disable no-param-reassign, camelcase */
export function prepareFunctionScoreInResolve(
function_score: any,
fieldMap: mixed
): { [argName: string]: any } {
if (function_score.query) {
function_score.query = prepareQueryInResolve(function_score.query, fieldMap);
}
if (Array.isArray(function_score.functions)) {
function_score.functions = function_score.functions.map(func => {
if (func.filter) {
func.filter = prepareQueryInResolve(func.filter, fieldMap);
}
return func;
});
}
return function_score;
}
| mit |
grom358/zemscript | src/net/zeminvaders/lang/ast/TrueNode.java | 1721 | /*
* Copyright (c) 2008 Cameron Zemek
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
package net.zeminvaders.lang.ast;
import net.zeminvaders.lang.Interpreter;
import net.zeminvaders.lang.SourcePosition;
import net.zeminvaders.lang.runtime.ZemBoolean;
import net.zeminvaders.lang.runtime.ZemObject;
/**
* The boolean true.
*
* @author <a href="mailto:grom@zeminvaders.net">Cameron Zemek</a>
*/
public class TrueNode extends Node {
public TrueNode(SourcePosition pos) {
super(pos);
}
@Override
public ZemObject eval(Interpreter interpreter) {
return ZemBoolean.TRUE;
}
@Override
public String toString() {
return "true";
}
}
| mit |
skn9x/Freja | src/freja/sql/Getter.java | 60 | package freja.sql;
public abstract class Getter {
}
| mit |
TheOdinProject/theodinproject | spec/support/cuprite.rb | 698 | require 'capybara/cuprite'
Capybara.register_driver(:cuprite) do |app|
Capybara::Cuprite::Driver.new(
app,
**{
window_size: [1200, 1200],
browser_options: {},
process_timeout: 30,
timeout: 60,
inspector: true,
headless: !ENV['HEADLESS'].in?(%w[n 0 no false]),
js_errors: true
}
)
end
Capybara.default_driver = :cuprite
Capybara.javascript_driver = :cuprite
module CupriteHelpers
def pause
page.driver.pause
end
def debug(*args)
page.driver.debug(*args)
end
end
RSpec.configure do |config|
config.prepend_before(:each, type: :system) do
driven_by :cuprite
end
config.include CupriteHelpers, type: :system
end
| mit |
mpi77/cpdn-api | app/models/Background/Task.php | 3256 | <?php
namespace CpdnAPI\Models\Background;
use Phalcon\Mvc\Model;
use CpdnAPI\Utils\Common;
use CpdnAPI\Utils\MetaGenerator as MG;
class Task extends Model
{
const STATUS_PREPARING = "preparing";
const STATUS_NEW = "new";
const STATUS_WORKING = "working";
const STATUS_COMPLETE = "complete";
/**
* @var integer
*
*/
public $id;
/**
* @var string
*
*/
public $executorId;
/**
* @var integer
*
*/
public $schemeId;
/**
* @var integer
*
*/
public $profileId;
/**
* @var string
*
*/
public $status;
/**
* @var integer
*
*/
public $priority;
/**
* @var string
*
*/
public $command;
/**
* @var string
*
*/
public $result;
/**
* @var string
*
*/
public $tsCreate;
/**
* @var string
*
*/
public $tsUpdate;
/**
* @var string
*
*/
public $tsReceive;
/**
* @var string
*
*/
public $tsExecute;
public function initialize() {
$this->setConnectionService ( 'backgroundDb' );
$this->belongsTo ( "executorId", "CpdnAPI\Models\Background\Executor", "id", array (
'alias' => 'executor'
) );
$this->belongsTo ( "schemeId", "CpdnAPI\Models\Network\Scheme", "id", array (
'alias' => 'scheme'
) );
$this->belongsTo ( "profileId", "CpdnAPI\Models\IdentityProvider\Profile", "id", array (
'alias' => 'profile'
) );
}
public function beforeValidationOnCreate() {
$this->tsCreate = date ( "Y-m-d H:i:s" );
$this->tsUpdate = date ( "Y-m-d H:i:s" );
}
public function beforeValidationOnUpdate() {
$this->tsUpdate = date ( "Y-m-d H:i:s" );
}
public function columnMap() {
return array (
'id' => 'id',
'executor_id' => 'executorId',
'scheme_id' => 'schemeId',
'profile_id' => 'profileId',
'status' => 'status',
'priority' => 'priority',
'command' => 'command',
'result' => 'result',
'ts_create' => 'tsCreate',
'ts_update' => 'tsUpdate',
'ts_receive' => 'tsReceive',
'ts_execute' => 'tsExecute'
);
}
/**
* Get task in defined output structure.
*
* @param Task $task
* @return array
*/
public static function getTask(Task $task) {
return array (
"executor" => array (
MG::KEY_META => MG::generate ( sprintf ( "/%s/executors/%s/", Common::API_VERSION_V1, $task->executorId ), array (
MG::KEY_ID => $task->executorId
) )
),
"user" => array (
MG::KEY_META => MG::generate ( sprintf ( "/%s/users/%s/", Common::API_VERSION_V1, $task->profileId ), array (
MG::KEY_ID => $task->profileId
) )
),
"scheme" => array (
MG::KEY_META => MG::generate ( sprintf ( "/%s/schemes/%s/", Common::API_VERSION_V1, $task->schemeId ), array (
MG::KEY_ID => $task->schemeId
) )
),
"status" => $task->status,
"priority" => $task->priority,
"command" => $task->command,
"result" => $task->result
);
}
}
| mit |
be-pongit/confac-front | src/components/invoice/spec/InvoiceListModel.spec.ts | 2240 | import moment from 'moment';
import InvoiceListModel from '../models/InvoiceListModel';
import InvoiceModel from '../models/InvoiceModel';
import {InvoiceFilters} from '../../../models';
describe('InvoiceListModel', () => {
it('filters with last x days', () => {
const filters: InvoiceFilters = {
search: [{value: 'last 1 days', label: 'last 1 days', type: 'manual_input'}],
groupedByMonth: false,
} as InvoiceFilters;
const today = () => moment().startOf('day');
const invoices = [
{date: today(), verified: true} as InvoiceModel,
{date: today().subtract(1, 'days'), verified: true} as InvoiceModel,
{date: today().subtract(2, 'days'), verified: true} as InvoiceModel,
{date: today().subtract(3, 'days'), verified: true} as InvoiceModel,
];
const vm = new InvoiceListModel(invoices, [], [], filters, false);
const result = vm.getFilteredInvoices();
expect(result.length).toBe(2);
});
it('filters with last x days no longer shows unverified too', () => {
const filters: InvoiceFilters = {
search: [{value: 'last 1 days', label: 'last 1 days', type: 'manual_input'}],
groupedByMonth: false,
} as InvoiceFilters;
const invoices = [
{date: moment().subtract(3, 'days'), verified: false} as InvoiceModel,
];
const vm = new InvoiceListModel(invoices, [], [], filters, true);
const result = vm.getFilteredInvoices();
expect(result.length).toBe(0);
});
it('filters with free text in invoice lines', () => {
const filters: InvoiceFilters = {
search: [{value: 'koen', label: 'koen', type: 'manual_input'}],
groupedByMonth: false,
} as InvoiceFilters;
const emptyClient = {
city: '',
address: '',
};
const invoices = [
{_id: '', lines: [{desc: 'Prestaties Koen'}], client: emptyClient, orderNr: '', number: 5, date: moment(), money: {}} as InvoiceModel,
{_id: '', lines: [{desc: 'Prestaties Ilse'}], client: emptyClient, orderNr: '', number: 6, date: moment(), money: {}} as InvoiceModel,
];
const vm = new InvoiceListModel(invoices, [], [], filters, true);
const result = vm.getFilteredInvoices();
expect(result.length).toBe(1);
});
});
| mit |
akshaykumar90/sparkling-water | chapter9/inordertraversalwithparent.go | 1070 | // Problem 9.5
package chapter9
type TreeNodeWithParent struct {
Value int
Left *TreeNodeWithParent
Right *TreeNodeWithParent
Parent *TreeNodeWithParent
}
const (
left = iota
right = iota
parent = iota
)
func InorderTraversalWithParent(root *TreeNodeWithParent) []int {
result := make([]int, 0)
getNextNode := func(node *TreeNodeWithParent, nodeType int) *TreeNodeWithParent {
switch nodeType {
case left:
if node.Left != nil {
return node.Left
}
fallthrough
case right:
if node.Right != nil {
return node.Right
}
fallthrough
default:
return node.Parent
}
}
var curr, prev *TreeNodeWithParent = root, nil
for curr != nil {
var nextNodeType int
switch prev {
case nil:
fallthrough
case curr.Parent:
if curr.Left == nil {
result = append(result, curr.Value)
}
nextNodeType = left
case curr.Left:
result = append(result, curr.Value)
nextNodeType = right
case curr.Right:
nextNodeType = parent
}
prev, curr = curr, getNextNode(curr, nextNodeType)
}
return result
}
| mit |
lingtalfi/bee | bee/modules/Bee/Notation/File/IndentedLines/MultiLineCompiler/MultiLineCompilerInterface.php | 512 | <?php
/*
* This file is part of the Bee package.
*
* (c) Ling Talfi <lingtalfi@bee-framework.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Bee\Notation\File\IndentedLines\MultiLineCompiler;
/**
* MultiLineCompilerInterface
* @author Lingtalfi
* 2015-02-27
*
*/
interface MultiLineCompilerInterface
{
/**
* @return string
*/
public function getValue(array $lines, $nodeLevel);
}
| mit |
surla/bookmark-list | app/models/bookmark.rb | 134 | class Bookmark < ActiveRecord::Base
belongs_to :user
belongs_to :category
validates_presence_of :url, :title, :description
end
| mit |
craftworkgames/Astrid.Framework | Astrid.Framework/Gui/Screen.cs | 2119 | using System.Collections.Generic;
using Astrid.Animations;
using Astrid.Core;
namespace Astrid.Gui
{
public interface IScreenContext : IDeviceManager
{
Camera Camera { get; }
Viewport Viewport { get; }
AssetManager AssetManager { get; }
void SetScreen(Screen screen);
}
public abstract class Screen : IDeviceManager
{
protected Screen(IScreenContext game)
{
_layers = new List<ScreenLayer>();
Game = game;
ClearColor = Color.CornflowerBlue;
Animations = new AnimationSystem();
}
protected IScreenContext Game { get; private set; }
public Color ClearColor { get; set; }
public AnimationSystem Animations { get; private set; }
private readonly List<ScreenLayer> _layers;
public IList<ScreenLayer> Layers
{
get { return _layers; }
}
public AssetManager AssetManager
{
get { return Game.AssetManager; }
}
public GraphicsDevice GraphicsDevice
{
get { return Game.GraphicsDevice; }
}
public InputDevice InputDevice
{
get { return Game.InputDevice; }
}
public AudioDevice AudioDevice
{
get { return Game.AudioDevice; }
}
public void SetScreen(Screen screen)
{
Game.SetScreen(screen);
}
public virtual void Show() { }
public virtual void Hide() { }
public virtual void Resize(int width, int height) { }
public virtual void Pause() { }
public virtual void Resume() { }
public virtual void Update(float deltaTime)
{
Animations.Update(deltaTime);
foreach (var layer in Layers)
layer.Update(deltaTime, InputDevice);
}
public virtual void Render(float deltaTime)
{
GraphicsDevice.Clear(ClearColor);
foreach (var layer in _layers)
layer.Render(deltaTime);
}
}
}
| mit |