max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
3,402 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kylin.rest.controller;
import java.io.IOException;
import java.util.Locale;
import org.apache.kylin.common.util.HadoopUtil;
import org.apache.kylin.common.util.JsonUtil;
import org.apache.kylin.metadata.model.TableDesc;
import org.junit.Assert;
import org.junit.Test;
public class StreamingControllerTest {
@Test
public void testReadTableDesc() throws IOException {
String requestTableData = "{\"name\":\"my_table_name\",\"source_type\":1,\"columns\":[{\"id\":1,\"name\":"
+ "\"amount\",\"datatype\":\"decimal\"},{\"id\":2,\"name\":\"category\",\"datatype\":\"varchar(256)\"},"
+ "{\"id\":3,\"name\":\"order_time\",\"datatype\":\"timestamp\"},{\"id\":4,\"name\":\"device\","
+ "\"datatype\":\"varchar(256)\"},{\"id\":5,\"name\":\"qty\",\"datatype\":\"int\"},{\"id\":6,\"name\":"
+ "\"user_id\",\"datatype\":\"varchar(256)\"},{\"id\":7,\"name\":\"user_age\",\"datatype\":\"int\"},"
+ "{\"id\":8,\"name\":\"user_gender\",\"datatype\":\"varchar(256)\"},{\"id\":9,\"name\":\"currency\","
+ "\"datatype\":\"varchar(256)\"},{\"id\":10,\"name\":\"country\",\"datatype\":\"varchar(256)\"},"
+ "{\"id\":11,\"name\":\"year_start\",\"datatype\":\"date\"},{\"id\":12,\"name\":\"quarter_start\","
+ "\"datatype\":\"date\"},{\"id\":13,\"name\":\"month_start\",\"datatype\":\"date\"},{\"id\":14,"
+ "\"name\":\"week_start\",\"datatype\":\"date\"},{\"id\":15,\"name\":\"day_start\",\"datatype\":"
+ "\"date\"},{\"id\":16,\"name\":\"hour_start\",\"datatype\":\"timestamp\"},{\"id\":17,\"name\":"
+ "\"minute_start\",\"datatype\":\"timestamp\"}],\"database\":\"my_database_name\"}";
TableDesc desc = JsonUtil.readValue(requestTableData, TableDesc.class);
String[] dbTable = HadoopUtil.parseHiveTableName(desc.getIdentity());
desc.setName(dbTable[1]);
desc.setDatabase(dbTable[0]);
Assert.assertEquals("my_table_name".toUpperCase(Locale.ROOT), desc.getName());
Assert.assertEquals("my_database_name".toUpperCase(Locale.ROOT), desc.getDatabase());
}
}
| 1,172 |
782 | /*
* Copyright (c) 2021, <NAME>. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.abst.fiducial;
import boofcv.abst.fiducial.calib.ConfigECoCheckMarkers.MarkerShape;
import boofcv.abst.geo.Estimate1ofEpipolar;
import boofcv.alg.fiducial.calib.ecocheck.ECoCheckDetector;
import boofcv.alg.fiducial.calib.ecocheck.ECoCheckFound;
import boofcv.alg.fiducial.calib.ecocheck.ECoCheckUtils;
import boofcv.factory.geo.FactoryMultiView;
import boofcv.struct.geo.AssociatedPair;
import boofcv.struct.geo.Point2D3D;
import boofcv.struct.geo.PointIndex2D_F64;
import boofcv.struct.image.ImageGray;
import boofcv.struct.image.ImageType;
import georegression.struct.homography.Homography2D_F64;
import georegression.struct.point.Point2D_F64;
import georegression.struct.point.Point3D_F64;
import georegression.struct.shapes.Polygon2D_F64;
import georegression.transform.homography.HomographyPointOps_F64;
import lombok.Getter;
import org.ddogleg.struct.DogArray;
import org.ddogleg.struct.DogArray_I32;
import org.ddogleg.struct.FastArray;
import org.ejml.data.DMatrixRMaj;
import org.ejml.dense.fixed.CommonOps_DDF3;
import org.ejml.ops.DConvertMatrixStruct;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* Wrapper around {@link ECoCheckDetector} for {@link FiducialDetector}.
*
* @author <NAME>
*/
public class ECoCheck_to_FiducialDetector<T extends ImageGray<T>> extends FiducialDetectorPnP<T> {
/** The wrapped detector */
@Getter ECoCheckDetector<T> detector;
// workspace for estimating pose. observation is in normalized image coordinates
private final DogArray<Point2D3D> points2D3D = new DogArray<>(Point2D3D::new);
// homographies from corner-marker coordinate system to image pixels
private final DogArray<Homography2D_F64> listMarkerToPixels = new DogArray<>(Homography2D_F64::new);
// workspace for computing homography
DMatrixRMaj tmp = new DMatrixRMaj(3, 3);
private final DogArray<AssociatedPair> pairs = new DogArray<>(AssociatedPair::new);
// used to retrieve grid shape and marker's physical size
final FastArray<MarkerShape> markerShapes;
// list of known detections with known markers
DogArray_I32 foundToDetection = new DogArray_I32();
final Point3D_F64 point3 = new Point3D_F64();
public ECoCheck_to_FiducialDetector( ECoCheckDetector<T> detector, FastArray<MarkerShape> markerShapes ) {
this.detector = detector;
this.markerShapes = markerShapes;
}
@Override public void detect( T input ) {
detector.process(input);
// Find all the known detections
foundToDetection.reset();
for (int detectionID = 0; detectionID < detector.getFound().size; detectionID++) {
ECoCheckFound found = detector.found.get(detectionID);
if (found.markerID < 0)
continue;
foundToDetection.add(detectionID);
}
ECoCheckUtils utils = detector.getUtils();
Estimate1ofEpipolar computeHomography = FactoryMultiView.homographyTLS();
// Compute homographies for each marker
listMarkerToPixels.reset();
for (int knownIdx = 0; knownIdx < foundToDetection.size; knownIdx++) {
int detectionID = foundToDetection.get(knownIdx);
ECoCheckFound found = detector.found.get(detectionID);
int markerID = found.markerID;
// create a list of pairs from marker coordinates to pixels
pairs.resetResize(found.corners.size);
for (int i = 0; i < found.corners.size; i++) {
PointIndex2D_F64 foundCorner = found.corners.get(i);
// Get location of corner on marker in marker units
utils.cornerToMarker3D(markerID, foundCorner.index, point3);
// Observed pixel coordinate of corner
Point2D_F64 p = found.corners.get(i).p;
pairs.get(i).setTo(point3.x, point3.y, p.x, p.y);
}
// Find the homography that relates the coordinate systems
Homography2D_F64 h = listMarkerToPixels.grow();
if (!computeHomography.process(pairs.toList(), tmp)) {
// well this is unexpected. Let's just silently fail.
CommonOps_DDF3.fill(h, 0);
} else {
DConvertMatrixStruct.convert(tmp, h);
}
}
}
@Override public int totalFound() {return foundToDetection.size;}
@Override public void getCenter( int which, Point2D_F64 location ) {
HomographyPointOps_F64.transform(listMarkerToPixels.get(which), 0.0, 0.0, location);
}
@Override public Polygon2D_F64 getBounds( int which, @Nullable Polygon2D_F64 storage ) {
if (storage == null)
storage = new Polygon2D_F64(4);
else
storage.vertexes.resize(4);
HomographyPointOps_F64.transform(listMarkerToPixels.get(which), -0.5, -0.5, storage.get(0));
HomographyPointOps_F64.transform(listMarkerToPixels.get(which), -0.5, 0.5, storage.get(1));
HomographyPointOps_F64.transform(listMarkerToPixels.get(which), 0.5, 0.5, storage.get(2));
HomographyPointOps_F64.transform(listMarkerToPixels.get(which), 0.5, -0.5, storage.get(3));
return storage;
}
@Override public long getId( int which ) {return foundIndexToFound(which).markerID;}
@Override public String getMessage( int which ) {return getId(which) + "";}
@Override public double getWidth( int which ) {
int markerID = foundIndexToFound(which).markerID;
MarkerShape marker = markerShapes.get(markerID);
return (marker.getWidth() + marker.getHeight())/2.0;
}
@Override public boolean hasID() {return true;}
@Override public boolean hasMessage() {return false;}
@Override public ImageType<T> getInputType() {return detector.getImageType();}
@Override public double getSideWidth( int which ) {
int markerID = foundIndexToFound(which).markerID;
return markerShapes.get(markerID).getWidth();
}
@Override public double getSideHeight( int which ) {
int markerID = foundIndexToFound(which).markerID;
return markerShapes.get(markerID).getHeight();
}
@Override public List<PointIndex2D_F64> getDetectedControl( int which ) {
return foundIndexToFound(which).corners.toList();
}
@Override protected List<Point2D3D> getControl3D( int which ) {
ECoCheckFound found = foundIndexToFound(which);
MarkerShape marker = markerShapes.get(found.markerID);
points2D3D.resetResize(found.corners.size);
ECoCheckUtils utils = detector.getUtils();
// length of longest side on the marker
double markerLength = Math.max(marker.getWidth(), marker.getHeight());
for (int i = 0; i < found.corners.size; i++) {
PointIndex2D_F64 corner = found.corners.get(i);
Point2D3D p23 = points2D3D.get(i);
utils.cornerToMarker3D(found.markerID, corner.index, p23.location);
pixelToNorm.compute(corner.p.x, corner.p.y, p23.observation);
// Convert the units
p23.location.scale(markerLength);
}
return points2D3D.toList();
}
private ECoCheckFound foundIndexToFound( int which ) {
return detector.getFound().get(foundToDetection.get(which));
}
}
| 2,591 |
964 | # -*- coding: utf-8 -*-
# Copyright (c) 2010-2016, MIT Probabilistic Computing Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""SQLite3 utilities."""
import apsw
import binascii
import contextlib
import os
@contextlib.contextmanager
def sqlite3_connection(*args, **kwargs):
"""SQLite3 connection context manager. On exit, runs close."""
connection = apsw.Connection(*args, **kwargs)
try:
yield connection
finally:
connection.close()
@contextlib.contextmanager
def sqlite3_transaction(db):
"""Transaction context manager. On return, commit; on exception, rollback.
Transactions may not be nested. Use savepoints if you want a
nestable analogue to transactions.
"""
db.cursor().execute("BEGIN")
ok = False
try:
yield
db.cursor().execute("COMMIT")
ok = True
finally:
if not ok:
db.cursor().execute("ROLLBACK")
@contextlib.contextmanager
def sqlite3_savepoint(db):
"""Savepoint context manager. On return, commit; on exception, rollback.
Savepoints are like transactions, but they may be nested in
transactions or in other savepoints.
"""
# This is not symmetric with sqlite3_transaction because ROLLBACK
# undoes any effects and makes the transaction cease to be,
# whereas ROLLBACK TO undoes any effects but leaves the savepoint
# as is. So for either success or failure we must release the
# savepoint explicitly.
savepoint = binascii.b2a_hex(os.urandom(32))
db.cursor().execute("SAVEPOINT x%s" % (savepoint,))
ok = False
try:
yield
ok = True
finally:
if not ok:
db.cursor().execute("ROLLBACK TO x%s" % (savepoint,))
db.cursor().execute("RELEASE x%s" % (savepoint,))
@contextlib.contextmanager
def sqlite3_savepoint_rollback(db):
"""Savepoint context manager that always rolls back."""
savepoint = binascii.b2a_hex(os.urandom(32))
db.cursor().execute("SAVEPOINT x%s" % (savepoint,))
try:
yield
finally:
db.cursor().execute("ROLLBACK TO x%s" % (savepoint,))
db.cursor().execute("RELEASE x%s" % (savepoint,))
def sqlite3_exec_1(db, query, *args):
"""Execute a query returning a 1x1 table, and return its one value.
Do not call this if you cannot guarantee the result is a 1x1
table. Beware passing user-controlled input in here.
"""
cursor = db.cursor().execute(query, *args)
row = cursor.fetchone()
assert row
assert len(row) == 1
assert cursor.fetchone() == None
return row[0]
def sqlite3_quote_name(name):
"""Quote `name` as a SQL identifier, e.g. a table or column name.
Do NOT use this for strings, e.g. inserting data into a table.
Use query parameters instead.
"""
# XXX Could omit quotes in some cases, but safer this way.
return '"' + name.replace('"', '""') + '"'
# From <https://www.sqlite.org/datatype3.html#affname>. Doesn't seem
# to be a built-in SQLite library routine to compute this.
def sqlite3_column_affinity(column_type):
"""Return the sqlite3 column affinity corresponding to a type string."""
ct = column_type.lower()
if "int" in ct:
return "INTEGER"
elif "char" in ct or "clob" in ct or "text" in ct:
return "TEXT"
elif "blob" in ct or ct == "":
return "NONE"
elif "real" in ct or "floa" in ct or "doub" in ct:
return "REAL"
else:
return "NUMERIC"
### Trivial SQLite3 utility tests
# XXX This doesn't really belong here, although it doesn't hurt either.
assert sqlite3_quote_name("foo bar") == '"foo bar"'
assert sqlite3_column_affinity("integer") == "INTEGER"
assert sqlite3_column_affinity("CHARINT") == "INTEGER"
assert sqlite3_column_affinity("INT") == "INTEGER"
assert sqlite3_column_affinity("INTEGER") == "INTEGER"
assert sqlite3_column_affinity("TINYINT") == "INTEGER"
assert sqlite3_column_affinity("SMALLINT") == "INTEGER"
assert sqlite3_column_affinity("MEDIUMINT") == "INTEGER"
assert sqlite3_column_affinity("BIGINT") == "INTEGER"
assert sqlite3_column_affinity("UNSIGNED BIG INT") == "INTEGER"
assert sqlite3_column_affinity("INT2") == "INTEGER"
assert sqlite3_column_affinity("INT8") == "INTEGER"
assert sqlite3_column_affinity("FLOATING POINT") == "INTEGER"
assert sqlite3_column_affinity("text") == "TEXT"
assert sqlite3_column_affinity("TEXT") == "TEXT"
assert sqlite3_column_affinity("CHARACTER(20)") == "TEXT"
assert sqlite3_column_affinity("VARCHAR(255)") == "TEXT"
assert sqlite3_column_affinity("VARYING CHARACTER(255)") == "TEXT"
assert sqlite3_column_affinity("NCHAR(55)") == "TEXT"
assert sqlite3_column_affinity("NATIVE CHARACTER(70)") == "TEXT"
assert sqlite3_column_affinity("NVARCHAR(100)") == "TEXT"
assert sqlite3_column_affinity("TEXT") == "TEXT"
assert sqlite3_column_affinity("CLOB") == "TEXT"
assert sqlite3_column_affinity("CLOBBER") == "TEXT"
assert sqlite3_column_affinity("blob") == "NONE"
assert sqlite3_column_affinity("BLOB") == "NONE"
assert sqlite3_column_affinity("AMBLOBORIC") == "NONE"
assert sqlite3_column_affinity("") == "NONE"
assert sqlite3_column_affinity("real") == "REAL"
assert sqlite3_column_affinity("REAL") == "REAL"
assert sqlite3_column_affinity("DOUBLE") == "REAL"
assert sqlite3_column_affinity("DOUBLE PRECISION") == "REAL"
assert sqlite3_column_affinity("FLOAT") == "REAL"
assert sqlite3_column_affinity("numeric") == "NUMERIC"
assert sqlite3_column_affinity("MAGICAL MYSTERY TYPE") == "NUMERIC"
assert sqlite3_column_affinity("NUMERIC") == "NUMERIC"
assert sqlite3_column_affinity("DECIMAL(10,5)") == "NUMERIC"
assert sqlite3_column_affinity("BOOLEAN") == "NUMERIC"
assert sqlite3_column_affinity("DATE") == "NUMERIC"
assert sqlite3_column_affinity("DATETIME") == "NUMERIC"
assert sqlite3_column_affinity("STRING") == "NUMERIC"
| 2,367 |
2,288 | /* Licensed under LGPLv2.1+ - see LICENSE file for details */
#include "config.h"
#include <ccan/bitmap/bitmap.h>
#include <assert.h>
#define BIT_ALIGN_DOWN(n) ((n) & ~(BITMAP_WORD_BITS - 1))
#define BIT_ALIGN_UP(n) BIT_ALIGN_DOWN((n) + BITMAP_WORD_BITS - 1)
void bitmap_zero_range(bitmap *bitmap, unsigned long n, unsigned long m)
{
unsigned long an = BIT_ALIGN_UP(n);
unsigned long am = BIT_ALIGN_DOWN(m);
bitmap_word headmask = BITMAP_WORD_1 >> (n % BITMAP_WORD_BITS);
bitmap_word tailmask = ~(BITMAP_WORD_1 >> (m % BITMAP_WORD_BITS));
assert(m >= n);
if (am < an) {
BITMAP_WORD(bitmap, n) &= ~bitmap_bswap(headmask & tailmask);
return;
}
if (an > n)
BITMAP_WORD(bitmap, n) &= ~bitmap_bswap(headmask);
if (am > an)
memset(&BITMAP_WORD(bitmap, an), 0,
(am - an) / BITMAP_WORD_BITS * sizeof(bitmap_word));
if (m > am)
BITMAP_WORD(bitmap, m) &= ~bitmap_bswap(tailmask);
}
void bitmap_fill_range(bitmap *bitmap, unsigned long n, unsigned long m)
{
unsigned long an = BIT_ALIGN_UP(n);
unsigned long am = BIT_ALIGN_DOWN(m);
bitmap_word headmask = BITMAP_WORD_1 >> (n % BITMAP_WORD_BITS);
bitmap_word tailmask = ~(BITMAP_WORD_1 >> (m % BITMAP_WORD_BITS));
assert(m >= n);
if (am < an) {
BITMAP_WORD(bitmap, n) |= bitmap_bswap(headmask & tailmask);
return;
}
if (an > n)
BITMAP_WORD(bitmap, n) |= bitmap_bswap(headmask);
if (am > an)
memset(&BITMAP_WORD(bitmap, an), 0xff,
(am - an) / BITMAP_WORD_BITS * sizeof(bitmap_word));
if (m > am)
BITMAP_WORD(bitmap, m) |= bitmap_bswap(tailmask);
}
static int bitmap_clz(bitmap_word w)
{
#if HAVE_BUILTIN_CLZL
return __builtin_clzl(w);
#else
int lz = 0;
bitmap_word mask = (bitmap_word)1 << (BITMAP_WORD_BITS - 1);
while (!(w & mask)) {
lz++;
mask >>= 1;
}
return lz;
#endif
}
unsigned long bitmap_ffs(const bitmap *bitmap,
unsigned long n, unsigned long m)
{
unsigned long an = BIT_ALIGN_UP(n);
unsigned long am = BIT_ALIGN_DOWN(m);
bitmap_word headmask = BITMAP_WORD_1 >> (n % BITMAP_WORD_BITS);
bitmap_word tailmask = ~(BITMAP_WORD_1 >> (m % BITMAP_WORD_BITS));
assert(m >= n);
if (am < an) {
bitmap_word w = bitmap_bswap(BITMAP_WORD(bitmap, n));
w &= (headmask & tailmask);
return w ? am + bitmap_clz(w) : m;
}
if (an > n) {
bitmap_word w = bitmap_bswap(BITMAP_WORD(bitmap, n));
w &= headmask;
if (w)
return BIT_ALIGN_DOWN(n) + bitmap_clz(w);
}
while (an < am) {
bitmap_word w = bitmap_bswap(BITMAP_WORD(bitmap, an));
if (w)
return an + bitmap_clz(w);
an += BITMAP_WORD_BITS;
}
if (m > am) {
bitmap_word w = bitmap_bswap(BITMAP_WORD(bitmap, m));
w &= tailmask;
if (w)
return am + bitmap_clz(w);
}
return m;
}
| 1,269 |
740 | <filename>src/unittest/deletion_aligner.cpp
/// \file deletion_aligner.cpp
///
/// unit tests for the DeletionAligner
///
#include <iostream>
#include "path.hpp"
#include "deletion_aligner.hpp"
#include "random_graph.hpp"
#include "catch.hpp"
#include "bdsg/hash_graph.hpp"
namespace vg {
namespace unittest {
TEST_CASE("Deletion aligner finds optimal deletions", "[aligner][deletionaligner]") {
bdsg::HashGraph graph;
auto check_aln = [&](const Alignment& aln,
vector<handle_t> correct_path) {
REQUIRE(aln.path().mapping_size() == correct_path.size());
int total_length = 0;
for (size_t i = 0; i < correct_path.size(); ++i) {
auto h = correct_path[i];
const auto& m = aln.path().mapping(i);
REQUIRE(m.position().node_id() == graph.get_id(h));
REQUIRE(m.position().is_reverse() == graph.get_is_reverse(h));
REQUIRE(m.position().offset() == 0);
REQUIRE(mapping_from_length(m) == graph.get_length(h));
REQUIRE(mapping_to_length(m) == 0);
total_length += graph.get_length(h);
}
REQUIRE(aln.score() == (total_length ? -total_length - 5 : 0));
};
// scoring bubbles with powers of two makes ordered
// scores act like binary bits in counting order
auto h1 = graph.create_handle("AA");// +/- 1
auto h2 = graph.create_handle("A");
auto h3 = graph.create_handle("AAA");
auto h4 = graph.create_handle("A");
auto h5 = graph.create_handle("AAA");// +/- 2
auto h6 = graph.create_handle("A");
auto h7 = graph.create_handle("AAAA"); // +/- 4
auto h8 = graph.create_handle("AA");
auto h9 = graph.create_handle("A");
auto h10 = graph.create_handle("AAAAAAAAA"); // +/- 8
graph.create_edge(h1, h3);
graph.create_edge(h2, h3);
graph.create_edge(h3, h4);
graph.create_edge(h3, h5);
graph.create_edge(h4, h6);
graph.create_edge(h5, h6);
graph.create_edge(h6, h7);
graph.create_edge(h6, h8);
graph.create_edge(h7, h8);
graph.create_edge(h8, h9);
graph.create_edge(h8, h10);
DeletionAligner aligner(6, 1);
Alignment aln;
SECTION("Single traceback works") {
aligner.align(aln, graph);
check_aln(aln, {h2, h3, h4, h6, h8, h9});
}
SECTION("Multi traceback works") {
int num_alts = 15;
vector<Alignment> alts;
aligner.align_multi(aln, alts, graph, num_alts);
vector<vector<handle_t>> corrects{
{h2, h3, h4, h6, h8, h9},
{h1, h3, h4, h6, h8, h9},
{h2, h3, h5, h6, h8, h9},
{h1, h3, h5, h6, h8, h9},
{h2, h3, h4, h6, h7, h8, h9},
{h1, h3, h4, h6, h7, h8, h9},
{h2, h3, h5, h6, h7, h8, h9},
{h1, h3, h5, h6, h7, h8, h9},
{h2, h3, h4, h6, h8, h10},
{h1, h3, h4, h6, h8, h10},
{h2, h3, h5, h6, h8, h10},
{h1, h3, h5, h6, h8, h10},
{h2, h3, h4, h6, h7, h8, h10},
{h1, h3, h4, h6, h7, h8, h10},
{h2, h3, h5, h6, h7, h8, h10}
};
REQUIRE(corrects.size() == num_alts);
REQUIRE(alts.size() == num_alts);
for (size_t i = 0; i < num_alts; ++i) {
check_aln(alts[i], corrects[i]);
}
}
}
}
}
| 1,821 |
1,907 |
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2019 <NAME>, The appleseedhq Organization
//
// 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.
//
#pragma once
// appleseed.renderer headers.
#include "renderer/modeling/project/project.h"
#include "renderer/modeling/scene/objectinstance.h"
// appleseed.foundation headers.
#include "foundation/math/vector.h"
// Qt headers.
#include <QObject>
// Standard headers.
#include <memory>
namespace appleseed { namespace studio { class RenderingManager; } }
class QString;
namespace appleseed {
namespace studio {
class MaterialDropHandler
: public QObject
{
Q_OBJECT
public:
MaterialDropHandler(
const renderer::Project& project,
RenderingManager& rendering_manager);
public slots:
void slot_material_dropped(
const foundation::Vector2d& drop_pos,
const QString& material_name);
private:
const renderer::Project& m_project;
RenderingManager& m_rendering_manager;
foundation::Vector2d m_drop_pos;
std::string m_material_name;
void assign_material(const renderer::ObjectInstance::Side side);
private slots:
void slot_apply_to_front();
void slot_apply_to_back();
void slot_apply_to_both();
};
} // namespace studio
} // namespace appleseed
| 779 |
3,807 | package eu.davidea.samples.flexibleadapter.items;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import eu.davidea.flexibleadapter.FlexibleAdapter;
import eu.davidea.flexibleadapter.items.IExpandable;
import eu.davidea.flexibleadapter.items.IHeader;
import eu.davidea.samples.flexibleadapter.R;
import eu.davidea.samples.flexibleadapter.items.ExpandableLevel0Item.L0ViewHolder;
import eu.davidea.samples.flexibleadapter.services.DatabaseService;
import eu.davidea.samples.flexibleadapter.services.DatabaseType;
import eu.davidea.viewholders.ExpandableViewHolder;
/**
* This is an experiment to evaluate how a Section with header can also be expanded/collapsed.
* <p>Here, it still benefits of the common fields declared in AbstractItem.</p>
* It's important to note that, the ViewHolder must be specified in all <diamond> signature.
*/
public class ExpandableLevel0Item
extends AbstractItem<L0ViewHolder>
implements IExpandable<L0ViewHolder, ExpandableLevel1Item>, IHeader<L0ViewHolder> {
/* Flags for FlexibleAdapter */
private boolean mExpanded = false;
/* subItems list */
private List<ExpandableLevel1Item> mSubItems;
public ExpandableLevel0Item(String id) {
super(id);
//We start with header shown and expanded
setHidden(false);
setExpanded(true);
//NOT selectable (otherwise ActionMode will be activated on long click)!
setSelectable(false);
}
@Override
public boolean isExpanded() {
return mExpanded;
}
@Override
public void setExpanded(boolean expanded) {
mExpanded = expanded;
}
@Override
public int getExpansionLevel() {
return 0;
}
@Override
public List<ExpandableLevel1Item> getSubItems() {
return mSubItems;
}
public final boolean hasSubItems() {
return mSubItems != null && mSubItems.size() > 0;
}
public boolean removeSubItem(ExpandableLevel1Item item) {
return item != null && mSubItems.remove(item);
}
public boolean removeSubItem(int position) {
if (mSubItems != null && position >= 0 && position < mSubItems.size()) {
mSubItems.remove(position);
return true;
}
return false;
}
public void addSubItem(ExpandableLevel1Item subItem) {
if (mSubItems == null)
mSubItems = new ArrayList<ExpandableLevel1Item>();
mSubItems.add(subItem);
}
public void addSubItem(int position, ExpandableLevel1Item subItem) {
if (mSubItems != null && position >= 0 && position < mSubItems.size()) {
mSubItems.add(position, subItem);
} else
addSubItem(subItem);
}
@Override
public int getLayoutRes() {
return R.layout.recycler_expandable_header_item;
}
@Override
public L0ViewHolder createViewHolder(View view, FlexibleAdapter adapter) {
return new L0ViewHolder(view, adapter);
}
@Override
public void bindViewHolder(FlexibleAdapter adapter, L0ViewHolder holder, int position, List payloads) {
if (payloads.size() > 0) {
Log.d(this.getClass().getSimpleName(), "ExpandableHeaderItem Payload " + payloads);
} else {
holder.mTitle.setText(getTitle());
}
setSubtitle(adapter.getCurrentChildren(this).size() + " subItems");
holder.mSubtitle.setText(getSubtitle());
}
/**
* Provide a reference to the views for each data item.
* Complex data labels may need more than one view per item, and
* you provide access to all the views for a data item in a view holder.
*/
static class L0ViewHolder extends ExpandableViewHolder {
public TextView mTitle;
public TextView mSubtitle;
public ImageView mHandleView;
public L0ViewHolder(View view, FlexibleAdapter adapter) {
super(view, adapter, true);//True for sticky
mTitle = view.findViewById(R.id.title);
mSubtitle = view.findViewById(R.id.subtitle);
this.mHandleView = view.findViewById(R.id.row_handle);
if (adapter.isHandleDragEnabled() &&
DatabaseService.getInstance().getDatabaseType() == DatabaseType.EXPANDABLE_SECTIONS) {
this.mHandleView.setVisibility(View.VISIBLE);
setDragHandleView(mHandleView);
} else {
this.mHandleView.setVisibility(View.GONE);
}
// Support for StaggeredGridLayoutManager
setFullSpan(true);
}
@Override
protected boolean isViewExpandableOnClick() {
return true; //default=true
}
}
@Override
public String toString() {
return "ExpandableLevel-0[" + super.toString() + "//SubItems" + mSubItems + "]";
}
} | 2,005 |
1,431 | <filename>poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFName.java
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.xssf.usermodel;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.formula.FormulaParser;
import org.apache.poi.ss.formula.FormulaType;
import org.apache.poi.ss.usermodel.Name;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName;
/**
* Represents a defined named range in a SpreadsheetML workbook.
* <p>
* Defined names are descriptive text that is used to represents a cell, range of cells, formula, or constant value.
* Use easy-to-understand names, such as Products, to refer to hard to understand ranges, such as {@code Sales!C20:C30}.
* </p>
* Example:
* <pre>{@code
* XSSFWorkbook wb = new XSSFWorkbook();
* XSSFSheet sh = wb.createSheet("Sheet1");
*
* //applies to the entire workbook
* XSSFName name1 = wb.createName();
* name1.setNameName("FMLA");
* name1.setRefersToFormula("Sheet1!$B$3");
*
* //applies to Sheet1
* XSSFName name2 = wb.createName();
* name2.setNameName("SheetLevelName");
* name2.setComment("This name is scoped to Sheet1");
* name2.setLocalSheetId(0);
* name2.setRefersToFormula("Sheet1!$B$3");
*
* }</pre>
*/
public final class XSSFName implements Name {
/**
* A built-in defined name that specifies the workbook's print area
*/
public static final String BUILTIN_PRINT_AREA = "_xlnm.Print_Area";
/**
* A built-in defined name that specifies the row(s) or column(s) to repeat
* at the top of each printed page.
*/
public static final String BUILTIN_PRINT_TITLE = "_xlnm.Print_Titles";
/**
* A built-in defined name that refers to a range containing the criteria values
* to be used in applying an advanced filter to a range of data
*/
public static final String BUILTIN_CRITERIA = "_xlnm.Criteria:";
/**
* this defined name refers to the range containing the filtered
* output values resulting from applying an advanced filter criteria to a source
* range
*/
public static final String BUILTIN_EXTRACT = "_xlnm.Extract:";
/**
* Can be one of the following
* <ul>
* <li> this defined name refers to a range to which an advanced filter has been
* applied. This represents the source data range, unfiltered.
* <li> This defined name refers to a range to which an AutoFilter has been
* applied
* </ul>
*/
public static final String BUILTIN_FILTER_DB = "_xlnm._FilterDatabase";
/**
* A built-in defined name that refers to a consolidation area
*/
public static final String BUILTIN_CONSOLIDATE_AREA = "_xlnm.Consolidate_Area";
/**
* A built-in defined name that specified that the range specified is from a database data source
*/
public static final String BUILTIN_DATABASE = "_xlnm.Database";
/**
* A built-in defined name that refers to a sheet title.
*/
public static final String BUILTIN_SHEET_TITLE = "_xlnm.Sheet_Title";
private final XSSFWorkbook _workbook;
private final CTDefinedName _ctName;
/**
* Creates an XSSFName object - called internally by XSSFWorkbook.
*
* @param name - the xml bean that holds data represenring this defined name.
* @param workbook - the workbook object associated with the name
* @see org.apache.poi.xssf.usermodel.XSSFWorkbook#createName()
*/
protected XSSFName(CTDefinedName name, XSSFWorkbook workbook) {
_workbook = workbook;
_ctName = name;
}
/**
* Returns the underlying named range object
*/
protected CTDefinedName getCTName() {
return _ctName;
}
/**
* Returns the name that will appear in the user interface for the defined name.
*
* @return text name of this defined name
*/
@Override
public String getNameName() {
return _ctName.getName();
}
/**
* Sets the name that will appear in the user interface for the defined name.
* Names must begin with a letter or underscore, not contain spaces and be unique across the workbook.
*
* <p>
* A name must always be unique within its scope. POI prevents you from defining a name that is not unique
* within its scope. However you can use the same name in different scopes. Example:
* <pre>{@code
* //by default names are workbook-global
* XSSFName name;
* name = workbook.createName();
* name.setNameName("sales_08");
*
* name = workbook.createName();
* name.setNameName("sales_08"); //will throw an exception: "The workbook already contains this name (case-insensitive)"
*
* //create sheet-level name
* name = workbook.createName();
* name.setSheetIndex(0); //the scope of the name is the first sheet
* name.setNameName("sales_08"); //ok
*
* name = workbook.createName();
* name.setSheetIndex(0);
* name.setNameName("sales_08"); //will throw an exception: "The sheet already contains this name (case-insensitive)"
*
* }</pre>
*
* @param name name of this defined name
* @throws IllegalArgumentException if the name is invalid or the workbook already contains this name (case-insensitive)
*/
@Override
public void setNameName(String name) {
validateName(name);
String oldName = getNameName();
int sheetIndex = getSheetIndex();
//Check to ensure no other names have the same case-insensitive name at the same scope
for (XSSFName foundName : _workbook.getNames(name)) {
if (foundName.getSheetIndex() == sheetIndex && foundName != this) {
String msg = "The "+(sheetIndex == -1 ? "workbook" : "sheet")+" already contains this name: " + name;
throw new IllegalArgumentException(msg);
}
}
_ctName.setName(name);
//Need to update the name -> named ranges map
_workbook.updateName(this, oldName);
}
@Override
public String getRefersToFormula() {
String result = _ctName.getStringValue();
if (result == null || result.length() < 1) {
return null;
}
return result;
}
@Override
public void setRefersToFormula(String formulaText) {
XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(_workbook);
//validate through the FormulaParser
FormulaParser.parse(formulaText, fpb, FormulaType.NAMEDRANGE, getSheetIndex(), -1);
_ctName.setStringValue(formulaText);
}
@Override
public boolean isDeleted(){
String formulaText = getRefersToFormula();
if (formulaText == null) {
return false;
}
XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(_workbook);
Ptg[] ptgs = FormulaParser.parse(formulaText, fpb, FormulaType.NAMEDRANGE, getSheetIndex(), -1);
return Ptg.doesFormulaReferToDeletedCell(ptgs);
}
/**
* Tell Excel that this name applies to the worksheet with the specified index instead of the entire workbook.
*
* @param index the sheet index this name applies to, -1 unsets this property making the name workbook-global
*/
@Override
public void setSheetIndex(int index) {
int lastSheetIx = _workbook.getNumberOfSheets() - 1;
if (index < -1 || index > lastSheetIx) {
throw new IllegalArgumentException("Sheet index (" + index +") is out of range" +
(lastSheetIx == -1 ? "" : (" (0.." + lastSheetIx + ")")));
}
if(index == -1) {
if(_ctName.isSetLocalSheetId()) _ctName.unsetLocalSheetId();
} else {
_ctName.setLocalSheetId(index);
}
}
/**
* Returns the sheet index this name applies to.
*
* @return the sheet index this name applies to, -1 if this name applies to the entire workbook
*/
@Override
public int getSheetIndex() {
return _ctName.isSetLocalSheetId() ? (int) _ctName.getLocalSheetId() : -1;
}
/**
* Indicates that the defined name refers to a user-defined function.
* This attribute is used when there is an add-in or other code project associated with the file.
*
* @param value {@code true} indicates the name refers to a function.
*/
@Override
public void setFunction(boolean value) {
_ctName.setFunction(value);
}
/**
* Indicates that the defined name refers to a user-defined function.
* This attribute is used when there is an add-in or other code project associated with the file.
*
* @return {@code true} indicates the name refers to a function.
*/
public boolean getFunction() {
return _ctName.getFunction();
}
/**
* Specifies the function group index if the defined name refers to a function. The function
* group defines the general category for the function. This attribute is used when there is
* an add-in or other code project associated with the file.
*
* @param functionGroupId the function group index that defines the general category for the function
*/
public void setFunctionGroupId(int functionGroupId) {
_ctName.setFunctionGroupId(functionGroupId);
}
/**
* Returns the function group index if the defined name refers to a function. The function
* group defines the general category for the function. This attribute is used when there is
* an add-in or other code project associated with the file.
*
* @return the function group index that defines the general category for the function
*/
public int getFunctionGroupId() {
return (int) _ctName.getFunctionGroupId();
}
/**
* Get the sheets name which this named range is referenced to
*
* @return sheet name, which this named range referred to.
* Empty string if the referenced sheet name was not found.
*/
@Override
public String getSheetName() {
if (_ctName.isSetLocalSheetId()) {
// Given as explicit sheet id
int sheetId = (int)_ctName.getLocalSheetId();
return _workbook.getSheetName(sheetId);
}
String ref = getRefersToFormula();
AreaReference areaRef = new AreaReference(ref, SpreadsheetVersion.EXCEL2007);
return areaRef.getFirstCell().getSheetName();
}
/**
* Is the name refers to a user-defined function ?
*
* @return {@code true} if this name refers to a user-defined function
*/
@Override
public boolean isFunctionName() {
return getFunction();
}
/**
* Checks if this name is hidden, eg one of the built-in Excel
* internal names
*
* @return true if this name is a hidden one
*/
@Override
public boolean isHidden() {
return _ctName.getHidden();
}
/**
* Returns the comment the user provided when the name was created.
*
* @return the user comment for this named range
*/
@Override
public String getComment() {
return _ctName.getComment();
}
/**
* Specifies the comment the user provided when the name was created.
*
* @param comment the user comment for this named range
*/
@Override
public void setComment(String comment) {
_ctName.setComment(comment);
}
@Override
public int hashCode() {
return _ctName.toString().hashCode();
}
/**
* Compares this name to the specified object.
* The result is {@code true} if the argument is XSSFName and the
* underlying CTDefinedName bean equals to the CTDefinedName representing this name
*
* @param o the object to compare this {@code XSSFName} against.
* @return {@code true} if the {@code XSSFName }are equal;
* {@code false} otherwise.
*/
@Override
public boolean equals(Object o) {
if(o == this) return true;
if (!(o instanceof XSSFName)) return false;
XSSFName cf = (XSSFName) o;
return _ctName.toString().equals(cf.getCTName().toString());
}
/**
* https://support.office.com/en-us/article/Define-and-use-names-in-formulas-4D0F13AC-53B7-422E-AFD2-ABD7FF379C64#bmsyntax_rules_for_names
*
* Valid characters:
* First character: { letter | underscore | backslash }
* Remaining characters: { letter | number | period | underscore }
*
* Cell shorthand: cannot be { "C" | "c" | "R" | "r" }
*
* Cell references disallowed: cannot be a cell reference $A$1 or R1C1
*
* Spaces are not valid (follows from valid characters above)
*
* Name length: (XSSF-specific?) 255 characters maximum
*
* Case sensitivity: all names are case-insensitive
*
* Uniqueness: must be unique (for names with the same scope)
*/
private static void validateName(String name) {
if (name.length() == 0) {
throw new IllegalArgumentException("Name cannot be blank");
}
if (name.length() > 255) {
throw new IllegalArgumentException("Invalid name: '"+name+"': cannot exceed 255 characters in length");
}
if (name.equalsIgnoreCase("R") || name.equalsIgnoreCase("C")) {
throw new IllegalArgumentException("Invalid name: '"+name+"': cannot be special shorthand R or C");
}
// is first character valid?
char c = name.charAt(0);
String allowedSymbols = "_\\";
boolean characterIsValid = (Character.isLetter(c) || allowedSymbols.indexOf(c) != -1);
if (!characterIsValid) {
throw new IllegalArgumentException("Invalid name: '"+name+"': first character must be underscore or a letter");
}
// are all other characters valid?
allowedSymbols = "_.\\"; //backslashes needed for unicode escape
for (final char ch : name.toCharArray()) {
characterIsValid = (Character.isLetterOrDigit(ch) || allowedSymbols.indexOf(ch) != -1);
if (!characterIsValid) {
throw new IllegalArgumentException("Invalid name: '"+name+"': name must be letter, digit, period, or underscore");
}
}
// Is the name a valid $A$1 cell reference
// Because $, :, and ! are disallowed characters, A1-style references become just a letter-number combination
if (name.matches("[A-Za-z]+\\d+")) {
String col = name.replaceAll("\\d", "");
String row = name.replaceAll("[A-Za-z]", "");
try {
if (CellReference.cellReferenceIsWithinRange(col, row, SpreadsheetVersion.EXCEL2007)) {
throw new IllegalArgumentException("Invalid name: '"+name+"': cannot be $A$1-style cell reference");
}
} catch (final NumberFormatException e) {
// row was not parseable as an Integer, such as a BigInt
// therefore name passes the not-a-cell-reference criteria
}
}
// Is the name a valid R1C1 cell reference?
if (name.matches("[Rr]\\d+[Cc]\\d+")) {
throw new IllegalArgumentException("Invalid name: '"+name+"': cannot be R1C1-style cell reference");
}
}
}
| 6,131 |
682 | <reponame>HackerFoo/vtr-verilog-to-routing
/**CFile****************************************************************
FileName [saigStrSim.c]
SystemName [ABC: Logic synthesis and verification system.]
PackageName [Sequential AIG package.]
Synopsis [Structural matching using simulation.]
Author [<NAME>]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - June 20, 2005.]
Revision [$Id: saigStrSim.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $]
***********************************************************************/
#include "saig.h"
#include "proof/ssw/ssw.h"
ABC_NAMESPACE_IMPL_START
////////////////////////////////////////////////////////////////////////
/// DECLARATIONS ///
////////////////////////////////////////////////////////////////////////
#define SAIG_WORDS 16
static inline Aig_Obj_t * Saig_ObjNext( Aig_Obj_t ** ppNexts, Aig_Obj_t * pObj ) { return ppNexts[pObj->Id]; }
static inline void Saig_ObjSetNext( Aig_Obj_t ** ppNexts, Aig_Obj_t * pObj, Aig_Obj_t * pNext ) { ppNexts[pObj->Id] = pNext; }
////////////////////////////////////////////////////////////////////////
/// FUNCTION DEFINITIONS ///
////////////////////////////////////////////////////////////////////////
/**Function*************************************************************
Synopsis [Computes hash value of the node using its simulation info.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
unsigned Saig_StrSimHash( Aig_Obj_t * pObj )
{
static int s_SPrimes[128] = {
1009, 1049, 1093, 1151, 1201, 1249, 1297, 1361, 1427, 1459,
1499, 1559, 1607, 1657, 1709, 1759, 1823, 1877, 1933, 1997,
2039, 2089, 2141, 2213, 2269, 2311, 2371, 2411, 2467, 2543,
2609, 2663, 2699, 2741, 2797, 2851, 2909, 2969, 3037, 3089,
3169, 3221, 3299, 3331, 3389, 3461, 3517, 3557, 3613, 3671,
3719, 3779, 3847, 3907, 3943, 4013, 4073, 4129, 4201, 4243,
4289, 4363, 4441, 4493, 4549, 4621, 4663, 4729, 4793, 4871,
4933, 4973, 5021, 5087, 5153, 5227, 5281, 5351, 5417, 5471,
5519, 5573, 5651, 5693, 5749, 5821, 5861, 5923, 6011, 6073,
6131, 6199, 6257, 6301, 6353, 6397, 6481, 6563, 6619, 6689,
6737, 6803, 6863, 6917, 6977, 7027, 7109, 7187, 7237, 7309,
7393, 7477, 7523, 7561, 7607, 7681, 7727, 7817, 7877, 7933,
8011, 8039, 8059, 8081, 8093, 8111, 8123, 8147
};
unsigned * pSims;
unsigned uHash = 0;
int i;
assert( SAIG_WORDS <= 128 );
pSims = (unsigned *)pObj->pData;
for ( i = 0; i < SAIG_WORDS; i++ )
uHash ^= pSims[i] * s_SPrimes[i & 0x7F];
return uHash;
}
/**Function*************************************************************
Synopsis [Computes hash value of the node using its simulation info.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Saig_StrSimIsEqual( Aig_Obj_t * pObj0, Aig_Obj_t * pObj1 )
{
unsigned * pSims0 = (unsigned *)pObj0->pData;
unsigned * pSims1 = (unsigned *)pObj1->pData;
int i;
for ( i = 0; i < SAIG_WORDS; i++ )
if ( pSims0[i] != pSims1[i] )
return 0;
return 1;
}
/**Function*************************************************************
Synopsis [Returns 1 if simulation info is zero.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Saig_StrSimIsZero( Aig_Obj_t * pObj )
{
unsigned * pSims = (unsigned *)pObj->pData;
int i;
for ( i = 0; i < SAIG_WORDS; i++ )
if ( pSims[i] != 0 )
return 0;
return 1;
}
/**Function*************************************************************
Synopsis [Returns 1 if simulation info is one.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Saig_StrSimIsOne( Aig_Obj_t * pObj )
{
unsigned * pSims = (unsigned *)pObj->pData;
int i;
for ( i = 0; i < SAIG_WORDS; i++ )
if ( pSims[i] != ~0 )
return 0;
return 1;
}
/**Function*************************************************************
Synopsis [Assigns random simulation info.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimAssignRandom( Aig_Obj_t * pObj )
{
unsigned * pSims = (unsigned *)pObj->pData;
int i;
for ( i = 0; i < SAIG_WORDS; i++ )
pSims[i] = Aig_ManRandom(0);
}
/**Function*************************************************************
Synopsis [Assigns constant 0 simulation info.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimAssignOne( Aig_Obj_t * pObj )
{
unsigned * pSims = (unsigned *)pObj->pData;
int i;
for ( i = 0; i < SAIG_WORDS; i++ )
pSims[i] = ~0;
}
/**Function*************************************************************
Synopsis [Assigns constant 0 simulation info.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimAssignZeroInit( Aig_Obj_t * pObj )
{
unsigned * pSims = (unsigned *)pObj->pData;
pSims[0] = 0;
}
/**Function*************************************************************
Synopsis [Simulated one node.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimulateNode( Aig_Obj_t * pObj, int i )
{
unsigned * pSims = (unsigned *)pObj->pData;
unsigned * pSims0 = (unsigned *)Aig_ObjFanin0(pObj)->pData;
unsigned * pSims1 = (unsigned *)Aig_ObjFanin1(pObj)->pData;
if ( Aig_ObjFaninC0(pObj) && Aig_ObjFaninC1(pObj) )
pSims[i] = ~(pSims0[i] | pSims1[i]);
else if ( Aig_ObjFaninC0(pObj) && !Aig_ObjFaninC1(pObj) )
pSims[i] = (~pSims0[i] & pSims1[i]);
else if ( !Aig_ObjFaninC0(pObj) && Aig_ObjFaninC1(pObj) )
pSims[i] = (pSims0[i] & ~pSims1[i]);
else // if ( !Aig_ObjFaninC0(pObj) && !Aig_ObjFaninC1(pObj) )
pSims[i] = (pSims0[i] & pSims1[i]);
}
/**Function*************************************************************
Synopsis [Saves output of one node.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimSaveOutput( Aig_Obj_t * pObj, int i )
{
unsigned * pSims = (unsigned *)pObj->pData;
unsigned * pSims0 = (unsigned *)Aig_ObjFanin0(pObj)->pData;
if ( Aig_ObjFaninC0(pObj) )
pSims[i] = ~pSims0[i];
else
pSims[i] = pSims0[i];
}
/**Function*************************************************************
Synopsis [Transfers simulation output to another node.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimTransfer( Aig_Obj_t * pObj0, Aig_Obj_t * pObj1 )
{
unsigned * pSims0 = (unsigned *)pObj0->pData;
unsigned * pSims1 = (unsigned *)pObj1->pData;
int i;
for ( i = 0; i < SAIG_WORDS; i++ )
pSims1[i] = pSims0[i];
}
/**Function*************************************************************
Synopsis [Transfers simulation output to another node.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimTransferNext( Aig_Obj_t * pObj0, Aig_Obj_t * pObj1, int i )
{
unsigned * pSims0 = (unsigned *)pObj0->pData;
unsigned * pSims1 = (unsigned *)pObj1->pData;
assert( i < SAIG_WORDS - 1 );
pSims1[i+1] = pSims0[i];
}
/**Function*************************************************************
Synopsis [Perform one round of simulation.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimulateRound( Aig_Man_t * p0, Aig_Man_t * p1 )
{
Aig_Obj_t * pObj0, * pObj1;
int f, i;
// simulate the nodes
Aig_ManForEachObj( p0, pObj0, i )
{
if ( !Aig_ObjIsCi(pObj0) && !Aig_ObjIsNode(pObj0) )
continue;
pObj1 = Aig_ObjRepr(p0, pObj0);
if ( pObj1 == NULL )
continue;
assert( Aig_ObjRepr(p1, pObj1) == pObj0 );
Saig_StrSimAssignRandom( pObj0 );
Saig_StrSimTransfer( pObj0, pObj1 );
}
// simulate the timeframes
for ( f = 0; f < SAIG_WORDS; f++ )
{
// simulate the first AIG
Aig_ManForEachNode( p0, pObj0, i )
if ( Aig_ObjRepr(p0, pObj0) == NULL )
Saig_StrSimulateNode( pObj0, f );
Saig_ManForEachLi( p0, pObj0, i )
Saig_StrSimSaveOutput( pObj0, f );
if ( f < SAIG_WORDS - 1 )
Saig_ManForEachLiLo( p0, pObj0, pObj1, i )
Saig_StrSimTransferNext( pObj0, pObj1, f );
// simulate the second AIG
Aig_ManForEachNode( p1, pObj1, i )
if ( Aig_ObjRepr(p1, pObj1) == NULL )
Saig_StrSimulateNode( pObj1, f );
Saig_ManForEachLi( p1, pObj1, i )
Saig_StrSimSaveOutput( pObj1, f );
if ( f < SAIG_WORDS - 1 )
Saig_ManForEachLiLo( p1, pObj1, pObj0, i )
Saig_StrSimTransferNext( pObj1, pObj0, f );
}
}
/**Function*************************************************************
Synopsis [Checks if the entry exists in the table.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Aig_Obj_t * Saig_StrSimTableLookup( Aig_Obj_t ** ppTable, Aig_Obj_t ** ppNexts, int nTableSize, Aig_Obj_t * pObj )
{
Aig_Obj_t * pEntry;
int iEntry;
// find the hash entry
iEntry = Saig_StrSimHash( pObj ) % nTableSize;
// check if there are nodes with this signatures
for ( pEntry = ppTable[iEntry]; pEntry; pEntry = Saig_ObjNext(ppNexts,pEntry) )
if ( Saig_StrSimIsEqual( pEntry, pObj ) )
return pEntry;
return NULL;
}
/**Function*************************************************************
Synopsis [Inserts the entry into the table.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimTableInsert( Aig_Obj_t ** ppTable, Aig_Obj_t ** ppNexts, int nTableSize, Aig_Obj_t * pObj )
{
// find the hash entry
int iEntry = Saig_StrSimHash( pObj ) % nTableSize;
// check if there are nodes with this signatures
if ( ppTable[iEntry] == NULL )
ppTable[iEntry] = pObj;
else
{
Saig_ObjSetNext( ppNexts, pObj, Saig_ObjNext(ppNexts, ppTable[iEntry]) );
Saig_ObjSetNext( ppNexts, ppTable[iEntry], pObj );
}
}
/**Function*************************************************************
Synopsis [Perform one round of matching.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Saig_StrSimDetectUnique( Aig_Man_t * p0, Aig_Man_t * p1 )
{
Aig_Obj_t ** ppTable, ** ppNexts, ** ppCands;
Aig_Obj_t * pObj, * pEntry;
int i, nTableSize, Counter;
// allocate the hash table hashing simulation info into nodes
nTableSize = Abc_PrimeCudd( Aig_ManObjNum(p0)/2 );
ppTable = ABC_CALLOC( Aig_Obj_t *, nTableSize );
ppNexts = ABC_CALLOC( Aig_Obj_t *, Aig_ManObjNumMax(p0) );
ppCands = ABC_CALLOC( Aig_Obj_t *, Aig_ManObjNumMax(p0) );
// hash nodes of the first AIG
Aig_ManForEachObj( p0, pObj, i )
{
if ( !Aig_ObjIsCi(pObj) && !Aig_ObjIsNode(pObj) )
continue;
if ( Aig_ObjRepr(p0, pObj) )
continue;
if ( Saig_StrSimIsZero(pObj) || Saig_StrSimIsOne(pObj) )
continue;
// check if the entry exists
pEntry = Saig_StrSimTableLookup( ppTable, ppNexts, nTableSize, pObj );
if ( pEntry == NULL ) // insert
Saig_StrSimTableInsert( ppTable, ppNexts, nTableSize, pObj );
else // mark the entry as not unique
pEntry->fMarkA = 1;
}
// hash nodes from the second AIG
Aig_ManForEachObj( p1, pObj, i )
{
if ( !Aig_ObjIsCi(pObj) && !Aig_ObjIsNode(pObj) )
continue;
if ( Aig_ObjRepr(p1, pObj) )
continue;
if ( Saig_StrSimIsZero(pObj) || Saig_StrSimIsOne(pObj) )
continue;
// check if the entry exists
pEntry = Saig_StrSimTableLookup( ppTable, ppNexts, nTableSize, pObj );
if ( pEntry == NULL ) // skip
continue;
// if there is no candidate, label it
if ( Saig_ObjNext( ppCands, pEntry ) == NULL )
Saig_ObjSetNext( ppCands, pEntry, pObj );
else // mark the entry as not unique
pEntry->fMarkA = 1;
}
// create representatives for the unique entries
Counter = 0;
for ( i = 0; i < nTableSize; i++ )
for ( pEntry = ppTable[i]; pEntry; pEntry = Saig_ObjNext(ppNexts,pEntry) )
if ( !pEntry->fMarkA && (pObj = Saig_ObjNext( ppCands, pEntry )) )
{
// assert( Aig_ObjIsNode(pEntry) == Aig_ObjIsNode(pObj) );
if ( Aig_ObjType(pEntry) != Aig_ObjType(pObj) )
continue;
Aig_ObjSetRepr( p0, pEntry, pObj );
Aig_ObjSetRepr( p1, pObj, pEntry );
Counter++;
}
// cleanup
Aig_ManCleanMarkA( p0 );
ABC_FREE( ppTable );
ABC_FREE( ppNexts );
ABC_FREE( ppCands );
return Counter;
}
/**Function*************************************************************
Synopsis [Counts the number of matched flops.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Saig_StrSimCountMatchedFlops( Aig_Man_t * p )
{
Aig_Obj_t * pObj;
int i, Counter = 0;
Saig_ManForEachLo( p, pObj, i )
if ( Aig_ObjRepr(p, pObj) )
Counter++;
return Counter;
}
/**Function*************************************************************
Synopsis [Counts the number of matched nodes.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Saig_StrSimCountMatchedNodes( Aig_Man_t * p )
{
Aig_Obj_t * pObj;
int i, Counter = 0;
Aig_ManForEachNode( p, pObj, i )
if ( Aig_ObjRepr(p, pObj) )
Counter++;
return Counter;
}
/**Function*************************************************************
Synopsis [Performs structural matching of two AIGs using simulation.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimPrepareAig( Aig_Man_t * p )
{
Aig_Obj_t * pObj;
int i;
Aig_ManReprStart( p, Aig_ManObjNumMax(p) );
// allocate simulation info
p->pData2 = Vec_PtrAllocSimInfo( Aig_ManObjNumMax(p), SAIG_WORDS );
Aig_ManForEachObj( p, pObj, i )
pObj->pData = Vec_PtrEntry( (Vec_Ptr_t *)p->pData2, i );
// set simulation info for constant1 and register outputs
Saig_StrSimAssignOne( Aig_ManConst1(p) );
Saig_ManForEachLo( p, pObj, i )
Saig_StrSimAssignZeroInit( pObj );
}
/**Function*************************************************************
Synopsis [Performs structural matching of two AIGs using simulation.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimSetInitMatching( Aig_Man_t * p0, Aig_Man_t * p1 )
{
Aig_Obj_t * pObj0, * pObj1;
int i;
pObj0 = Aig_ManConst1( p0 );
pObj1 = Aig_ManConst1( p1 );
Aig_ObjSetRepr( p0, pObj0, pObj1 );
Aig_ObjSetRepr( p1, pObj1, pObj0 );
Saig_ManForEachPi( p0, pObj0, i )
{
pObj1 = Aig_ManCi( p1, i );
Aig_ObjSetRepr( p0, pObj0, pObj1 );
Aig_ObjSetRepr( p1, pObj1, pObj0 );
}
}
/**Function*************************************************************
Synopsis [Performs structural matching of two AIGs using simulation.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimSetFinalMatching( Aig_Man_t * p0, Aig_Man_t * p1 )
{
Aig_Obj_t * pObj0, * pObj1;
Aig_Obj_t * pFanin00, * pFanin01;
Aig_Obj_t * pFanin10, * pFanin11;
int i, CountAll = 0, CountNot = 0;
Aig_ManIncrementTravId( p0 );
Aig_ManForEachObj( p0, pObj0, i )
{
pObj1 = Aig_ObjRepr( p0, pObj0 );
if ( pObj1 == NULL )
continue;
CountAll++;
assert( pObj0 == Aig_ObjRepr( p1, pObj1 ) );
if ( Aig_ObjIsNode(pObj0) )
{
assert( Aig_ObjIsNode(pObj1) );
pFanin00 = Aig_ObjFanin0(pObj0);
pFanin01 = Aig_ObjFanin1(pObj0);
pFanin10 = Aig_ObjFanin0(pObj1);
pFanin11 = Aig_ObjFanin1(pObj1);
if ( Aig_ObjRepr(p0, pFanin00) != pFanin10 ||
Aig_ObjRepr(p0, pFanin01) != pFanin11 )
{
Aig_ObjSetTravIdCurrent(p0, pObj0);
CountNot++;
}
}
else if ( Saig_ObjIsLo(p0, pObj0) )
{
assert( Saig_ObjIsLo(p1, pObj1) );
pFanin00 = Aig_ObjFanin0( Saig_ObjLoToLi(p0, pObj0) );
pFanin10 = Aig_ObjFanin0( Saig_ObjLoToLi(p1, pObj1) );
if ( Aig_ObjRepr(p0, pFanin00) != pFanin10 )
{
Aig_ObjSetTravIdCurrent(p0, pObj0);
CountNot++;
}
}
}
// remove irrelevant matches
Aig_ManForEachObj( p0, pObj0, i )
{
pObj1 = Aig_ObjRepr( p0, pObj0 );
if ( pObj1 == NULL )
continue;
assert( pObj0 == Aig_ObjRepr( p1, pObj1 ) );
if ( Aig_ObjIsTravIdCurrent( p0, pObj0 ) )
{
Aig_ObjSetRepr( p0, pObj0, NULL );
Aig_ObjSetRepr( p1, pObj1, NULL );
}
}
Abc_Print( 1, "Total matches = %6d. Wrong matches = %6d. Ratio = %5.2f %%\n",
CountAll, CountNot, 100.0*CountNot/CountAll );
}
/**Function*************************************************************
Synopsis [Returns the number of dangling nodes removed.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimSetContiguousMatching_rec( Aig_Man_t * p, Aig_Obj_t * pObj )
{
Aig_Obj_t * pFanout;
int i, iFanout = -1;
if ( Aig_ObjIsTravIdCurrent(p, pObj) )
return;
Aig_ObjSetTravIdCurrent(p, pObj);
if ( Saig_ObjIsPo( p, pObj ) )
return;
if ( Saig_ObjIsLi( p, pObj ) )
{
Saig_StrSimSetContiguousMatching_rec( p, Saig_ObjLiToLo(p, pObj) );
return;
}
assert( Aig_ObjIsCi(pObj) || Aig_ObjIsNode(pObj) );
if ( Aig_ObjRepr(p, pObj) == NULL )
return;
// go through the fanouts
Aig_ObjForEachFanout( p, pObj, pFanout, iFanout, i )
Saig_StrSimSetContiguousMatching_rec( p, pFanout );
// go through the fanins
if ( !Aig_ObjIsCi( pObj ) )
{
Saig_StrSimSetContiguousMatching_rec( p, Aig_ObjFanin0(pObj) );
Saig_StrSimSetContiguousMatching_rec( p, Aig_ObjFanin1(pObj) );
}
}
/**Function*************************************************************
Synopsis [Performs structural matching of two AIGs using simulation.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Saig_StrSimSetContiguousMatching( Aig_Man_t * p0, Aig_Man_t * p1 )
{
Aig_Obj_t * pObj0, * pObj1;
int i, CountAll = 0, CountNot = 0;
// mark nodes reachable through the PIs
Aig_ManIncrementTravId( p0 );
Aig_ObjSetTravIdCurrent( p0, Aig_ManConst1(p0) );
Saig_ManForEachPi( p0, pObj0, i )
Saig_StrSimSetContiguousMatching_rec( p0, pObj0 );
// remove irrelevant matches
Aig_ManForEachObj( p0, pObj0, i )
{
pObj1 = Aig_ObjRepr( p0, pObj0 );
if ( pObj1 == NULL )
continue;
CountAll++;
assert( pObj0 == Aig_ObjRepr( p1, pObj1 ) );
if ( !Aig_ObjIsTravIdCurrent( p0, pObj0 ) )
{
Aig_ObjSetRepr( p0, pObj0, NULL );
Aig_ObjSetRepr( p1, pObj1, NULL );
CountNot++;
}
}
Abc_Print( 1, "Total matches = %6d. Wrong matches = %6d. Ratio = %5.2f %%\n",
CountAll, CountNot, 100.0*CountNot/CountAll );
}
/**Function*************************************************************
Synopsis [Establishes relationship between nodes using pairing.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Ssw_StrSimMatchingExtendOne( Aig_Man_t * p, Vec_Ptr_t * vNodes )
{
Aig_Obj_t * pNext, * pObj;
int i, k, iFan = -1;
Vec_PtrClear( vNodes );
Aig_ManIncrementTravId( p );
Aig_ManForEachObj( p, pObj, i )
{
if ( !Aig_ObjIsNode(pObj) && !Aig_ObjIsCi(pObj) )
continue;
if ( Aig_ObjRepr( p, pObj ) != NULL )
continue;
if ( Saig_ObjIsLo(p, pObj) )
{
pNext = Saig_ObjLoToLi(p, pObj);
pNext = Aig_ObjFanin0(pNext);
if ( Aig_ObjRepr( p, pNext ) && !Aig_ObjIsTravIdCurrent(p, pNext) && !Aig_ObjIsConst1(pNext) )
{
Aig_ObjSetTravIdCurrent(p, pNext);
Vec_PtrPush( vNodes, pNext );
}
}
if ( Aig_ObjIsNode(pObj) )
{
pNext = Aig_ObjFanin0(pObj);
if ( Aig_ObjRepr( p, pNext )&& !Aig_ObjIsTravIdCurrent(p, pNext) )
{
Aig_ObjSetTravIdCurrent(p, pNext);
Vec_PtrPush( vNodes, pNext );
}
pNext = Aig_ObjFanin1(pObj);
if ( Aig_ObjRepr( p, pNext ) && !Aig_ObjIsTravIdCurrent(p, pNext) )
{
Aig_ObjSetTravIdCurrent(p, pNext);
Vec_PtrPush( vNodes, pNext );
}
}
Aig_ObjForEachFanout( p, pObj, pNext, iFan, k )
{
if ( Saig_ObjIsPo(p, pNext) )
continue;
if ( Saig_ObjIsLi(p, pNext) )
pNext = Saig_ObjLiToLo(p, pNext);
if ( Aig_ObjRepr( p, pNext ) && !Aig_ObjIsTravIdCurrent(p, pNext) )
{
Aig_ObjSetTravIdCurrent(p, pNext);
Vec_PtrPush( vNodes, pNext );
}
}
}
}
/**Function*************************************************************
Synopsis [Establishes relationship between nodes using pairing.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Ssw_StrSimMatchingCountUnmached( Aig_Man_t * p )
{
Aig_Obj_t * pObj;
int i, Counter = 0;
Aig_ManForEachObj( p, pObj, i )
{
if ( !Aig_ObjIsNode(pObj) && !Aig_ObjIsCi(pObj) )
continue;
if ( Aig_ObjRepr( p, pObj ) != NULL )
continue;
Counter++;
}
return Counter;
}
/**Function*************************************************************
Synopsis [Establishes relationship between nodes using pairing.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Ssw_StrSimMatchingExtend( Aig_Man_t * p0, Aig_Man_t * p1, int nDist, int fVerbose )
{
Vec_Ptr_t * vNodes0, * vNodes1;
Aig_Obj_t * pNext0, * pNext1;
int d, k;
vNodes0 = Vec_PtrAlloc( 1000 );
vNodes1 = Vec_PtrAlloc( 1000 );
if ( fVerbose )
{
int nUnmached = Ssw_StrSimMatchingCountUnmached(p0);
Abc_Print( 1, "Extending islands by %d steps:\n", nDist );
Abc_Print( 1, "%2d : Total = %6d. Unmatched = %6d. Ratio = %6.2f %%\n",
0, Aig_ManCiNum(p0) + Aig_ManNodeNum(p0),
nUnmached, 100.0 * nUnmached/(Aig_ManCiNum(p0) + Aig_ManNodeNum(p0)) );
}
for ( d = 0; d < nDist; d++ )
{
Ssw_StrSimMatchingExtendOne( p0, vNodes0 );
Ssw_StrSimMatchingExtendOne( p1, vNodes1 );
Vec_PtrForEachEntry( Aig_Obj_t *, vNodes0, pNext0, k )
{
pNext1 = Aig_ObjRepr( p0, pNext0 );
if ( pNext1 == NULL )
continue;
assert( pNext0 == Aig_ObjRepr( p1, pNext1 ) );
if ( Saig_ObjIsPi(p1, pNext1) )
continue;
Aig_ObjSetRepr( p0, pNext0, NULL );
Aig_ObjSetRepr( p1, pNext1, NULL );
}
Vec_PtrForEachEntry( Aig_Obj_t *, vNodes1, pNext1, k )
{
pNext0 = Aig_ObjRepr( p1, pNext1 );
if ( pNext0 == NULL )
continue;
assert( pNext1 == Aig_ObjRepr( p0, pNext0 ) );
if ( Saig_ObjIsPi(p0, pNext0) )
continue;
Aig_ObjSetRepr( p0, pNext0, NULL );
Aig_ObjSetRepr( p1, pNext1, NULL );
}
if ( fVerbose )
{
int nUnmached = Ssw_StrSimMatchingCountUnmached(p0);
Abc_Print( 1, "%2d : Total = %6d. Unmatched = %6d. Ratio = %6.2f %%\n",
d+1, Aig_ManCiNum(p0) + Aig_ManNodeNum(p0),
nUnmached, 100.0 * nUnmached/(Aig_ManCiNum(p0) + Aig_ManNodeNum(p0)) );
}
}
Vec_PtrFree( vNodes0 );
Vec_PtrFree( vNodes1 );
}
/**Function*************************************************************
Synopsis [Performs structural matching of two AIGs using simulation.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Vec_Int_t * Saig_StrSimPerformMatching( Aig_Man_t * p0, Aig_Man_t * p1, int nDist, int fVerbose, Aig_Man_t ** ppMiter )
{
extern Aig_Man_t * Saig_ManWindowExtractMiter( Aig_Man_t * p0, Aig_Man_t * p1 );
Vec_Int_t * vPairs;
Aig_Man_t * pPart0, * pPart1;
Aig_Obj_t * pObj0, * pObj1;
int i, nMatches;
abctime clk, clkTotal = Abc_Clock();
Aig_ManRandom( 1 );
// consider the case when a miter is given
if ( p1 == NULL )
{
if ( fVerbose )
{
Aig_ManPrintStats( p0 );
}
// demiter the miter
if ( !Saig_ManDemiterSimpleDiff( p0, &pPart0, &pPart1 ) )
{
Abc_Print( 1, "Demitering has failed.\n" );
return NULL;
}
}
else
{
pPart0 = Aig_ManDupSimple( p0 );
pPart1 = Aig_ManDupSimple( p1 );
}
if ( fVerbose )
{
Aig_ManPrintStats( pPart0 );
Aig_ManPrintStats( pPart1 );
}
// start simulation
Saig_StrSimPrepareAig( pPart0 );
Saig_StrSimPrepareAig( pPart1 );
Saig_StrSimSetInitMatching( pPart0, pPart1 );
if ( fVerbose )
{
Abc_Print( 1, "Allocated %6.2f MB to simulate the first AIG.\n",
1.0 * Aig_ManObjNumMax(pPart0) * SAIG_WORDS * sizeof(unsigned) / (1<<20) );
Abc_Print( 1, "Allocated %6.2f MB to simulate the second AIG.\n",
1.0 * Aig_ManObjNumMax(pPart1) * SAIG_WORDS * sizeof(unsigned) / (1<<20) );
}
// iterate matching
nMatches = 1;
for ( i = 0; nMatches > 0; i++ )
{
clk = Abc_Clock();
Saig_StrSimulateRound( pPart0, pPart1 );
nMatches = Saig_StrSimDetectUnique( pPart0, pPart1 );
if ( fVerbose )
{
int nFlops = Saig_StrSimCountMatchedFlops(pPart0);
int nNodes = Saig_StrSimCountMatchedNodes(pPart0);
Abc_Print( 1, "%3d : Match =%6d. FF =%6d. (%6.2f %%) Node =%6d. (%6.2f %%) ",
i, nMatches,
nFlops, 100.0*nFlops/Aig_ManRegNum(pPart0),
nNodes, 100.0*nNodes/Aig_ManNodeNum(pPart0) );
ABC_PRT( "Time", Abc_Clock() - clk );
}
if ( i == 20 )
break;
}
// cleanup
Vec_PtrFree( (Vec_Ptr_t *)pPart0->pData2 ); pPart0->pData2 = NULL;
Vec_PtrFree( (Vec_Ptr_t *)pPart1->pData2 ); pPart1->pData2 = NULL;
// extend the islands
Aig_ManFanoutStart( pPart0 );
Aig_ManFanoutStart( pPart1 );
if ( nDist )
Ssw_StrSimMatchingExtend( pPart0, pPart1, nDist, fVerbose );
Saig_StrSimSetFinalMatching( pPart0, pPart1 );
// Saig_StrSimSetContiguousMatching( pPart0, pPart1 );
// copy the results into array
vPairs = Vec_IntAlloc( 2*Aig_ManObjNumMax(pPart0) );
Aig_ManForEachObj( pPart0, pObj0, i )
{
pObj1 = Aig_ObjRepr(pPart0, pObj0);
if ( pObj1 == NULL )
continue;
assert( pObj0 == Aig_ObjRepr(pPart1, pObj1) );
Vec_IntPush( vPairs, pObj0->Id );
Vec_IntPush( vPairs, pObj1->Id );
}
// this procedure adds matching of PO and LI
if ( ppMiter )
*ppMiter = Saig_ManWindowExtractMiter( pPart0, pPart1 );
Aig_ManFanoutStop( pPart0 );
Aig_ManFanoutStop( pPart1 );
Aig_ManStop( pPart0 );
Aig_ManStop( pPart1 );
ABC_PRT( "Total runtime", Abc_Clock() - clkTotal );
return vPairs;
}
////////////////////////////////////////////////////////////////////////
/// END OF FILE ///
////////////////////////////////////////////////////////////////////////
ABC_NAMESPACE_IMPL_END
| 13,670 |
1,108 | package org.sql2o.extensions.postgres;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sql2o.Connection;
import org.sql2o.Query;
import org.sql2o.Sql2o;
import org.sql2o.converters.UUIDConverter;
import org.sql2o.data.Row;
import org.sql2o.data.Table;
import org.sql2o.quirks.PostgresQuirks;
import java.util.Arrays;
import java.util.Collection;
import java.util.UUID;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
/**
* Created with IntelliJ IDEA.
* User: <NAME>
* Date: 1/19/13
* Time: 10:58 PM
* Test dedicated for postgres issues. Seems like the postgres jdbc driver behaves somewhat different from other jdbc drivers.
* This test assumes that there is a local PostgreSQL server with a testdb database which can be accessed by user: test, pass: <PASSWORD>
*/
@RunWith(Parameterized.class)
public class PostgresTest extends PostgresTestSupport {
public PostgresTest(String url, String user, String pass, String testName) {
super(url, user, pass, testName);
logger.info("starting PostgresTest");
}
@Test
public void testIssue10StatementsOnPostgres_noTransaction(){
try {
try (Connection connection = sql2o.open()) {
connection.createQuery("create table test_table(id SERIAL, val varchar(20))").executeUpdate();
}
try (Connection connection = sql2o.open()) {
Long key = connection.createQuery("insert into test_table (val) values(:val)", true)
.addParameter("val", "something").executeUpdate().getKey(Long.class);
assertNotNull(key);
assertTrue(key > 0);
String selectSql = "select id, val from test_table";
Table resultTable = connection.createQuery(selectSql).executeAndFetchTable();
assertThat(resultTable.rows().size(), is(1));
Row resultRow = resultTable.rows().get(0);
assertThat(resultRow.getLong("id"), equalTo(key));
assertThat(resultRow.getString("val"), is("something"));
}
} finally {
try (final Connection connection = sql2o.open();
final Query query = connection.createQuery("drop table if exists test_table")) {
query.executeUpdate();
}
}
}
@Test
public void testIssue10_StatementsOnPostgres_withTransaction() {
try(final Connection connection = sql2o.beginTransaction()){
String createTableSql = "create table test_table(id SERIAL, val varchar(20))";
connection.createQuery(createTableSql).executeUpdate();
String insertSql = "insert into test_table (val) values(:val)";
Long key = connection.createQuery(insertSql, true).addParameter("val", "something").executeUpdate().getKey(Long.class);
assertNotNull(key);
assertTrue(key > 0);
String selectSql = "select id, val from test_table";
Table resultTable = connection.createQuery(selectSql).executeAndFetchTable();
assertThat(resultTable.rows().size(), is(1));
Row resultRow = resultTable.rows().get(0);
assertThat(resultRow.getLong("id"), equalTo(key));
assertThat(resultRow.getString("val"), is("something"));
// always rollback, as this is only for tesing purposes.
connection.rollback();
}
}
@Test
public void testGetKeyOnSequence(){
Connection connection = null;
try {
connection = sql2o.beginTransaction();
String createSequenceSql = "create sequence testseq";
connection.createQuery(createSequenceSql).executeUpdate();
String createTableSql = "create table test_seq_table (id integer primary key, val varchar(20))";
connection.createQuery(createTableSql).executeUpdate();
String insertSql = "insert into test_seq_table(id, val) values (nextval('testseq'), 'something')";
Long key = connection.createQuery(insertSql, true).executeUpdate().getKey(Long.class);
assertThat(key, equalTo(1L));
key = connection.createQuery(insertSql, true).executeUpdate().getKey(Long.class);
assertThat(key, equalTo(2L));
} finally {
if (connection != null) {
connection.rollback();
}
}
}
@Test
public void testKeyKeyOnSerial() {
Connection connection = null;
try {
connection = sql2o.beginTransaction();
String createTableSql = "create table test_serial_table (id serial primary key, val varchar(20))";
connection.createQuery(createTableSql).executeUpdate();
String insertSql = "insert into test_serial_table(val) values ('something')";
Long key = connection.createQuery(insertSql, true).executeUpdate().getKey(Long.class);
assertThat(key, equalTo(1L));
key = connection.createQuery(insertSql, true).executeUpdate().getKey(Long.class);
assertThat(key, equalTo(2L));
} finally {
if (connection != null) {
connection.rollback();
}
}
}
@Test
public void testUUID() {
Connection connection = null;
try {
connection = sql2o.beginTransaction();
String createSql = "create table uuidtable(id serial primary key, data uuid)";
connection.createQuery(createSql).executeUpdate();
UUID uuid = UUID.randomUUID();
String insertSql = "insert into uuidtable(data) values (:data)";
connection.createQuery(insertSql).addParameter("data", uuid).executeUpdate();
String selectSql = "select data from uuidtable";
UUID fetchedUuid = connection.createQuery(selectSql).executeScalar(UUID.class);
assertThat(fetchedUuid, is(equalTo(uuid)));
} finally {
if (connection != null) {
connection.rollback();
}
}
}
}
| 2,620 |
3,428 | {"id":"01320","group":"easy-ham-2","checksum":{"type":"MD5","value":"099f7c8107914cf82efe156e8c7f09fc"},"text":"From <EMAIL> Tue Jul 30 18:41:15 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id D0D3C4406D\n\tfor <jm@localhost>; Tue, 30 Jul 2002 13:41:14 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Tue, 30 Jul 2002 18:41:14 +0100 (IST)\nReceived: from mail.speakeasy.net (mail16.speakeasy.net [2172.16.31.1016])\n by dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g6UHbS208587 for\n <<EMAIL>>; Tue, 30 Jul 2002 18:37:29 +0100\nReceived: (qmail 800 invoked from network); 30 Jul 2002 17:36:27 -0000\nReceived: from unknown (HELO RAGING) ([66.92.72.213]) (envelope-sender\n <<EMAIL>>) by mail16.speakeasy.net (qmail-ldap-1.03) with SMTP\n for <jm@<EMAIL>>; 30 Jul 2002 17:36:27 -0000\nMessage-Id: <014501c237ef$96258d30$b554a8c0@RAGING>\nFrom: \"rODbegbie\" <<EMAIL>>\nTo: \"<NAME>\" <<EMAIL>>\nReferences: <20020730172908.<EMAIL>>\nSubject: Re: [SAdev] Alternatives to the GA\nDate: Tue, 30 Jul 2002 13:36:06 -0400\nOrganization: Arsecandle Industries, Inc.\nMIME-Version: 1.0\nContent-Type: text/plain; charset=\"Windows-1252\"\nContent-Transfer-Encoding: 7bit\nX-Priority: 3\nX-Msmail-Priority: Normal\nX-Mailer: Microsoft Outlook Express 6.00.2800.1050\nX-Mimeole: Produced By Microsoft MimeOLE V6.00.2800.1050\n\n<NAME> wrote:\n> I'd be happy to do that -- providing the nonspam.log and spam.log files\n> from my mass-check output (ie. the \"matrix of test results\" in Ken's\n> terms). Along with the default scores, this is the entire input data set\n> for the SpamAssassin GA system.\n\nAlways happy to contribute my mass-check logs. The only problem is that was\nall have to be using the exact same ruleset.\n\nLet me know if you want them.\n\nrOD.\n\n\n--\n\"I would also have accepted 'Snacktacular'\"\n\n>> Doing the blogging thang again at http://www.groovymother.com/ <<\n\n\n"} | 846 |
392 | #!/usr/bin/env python
import time
from math import log, ceil
import decimal
Decimal = decimal.Decimal
def pi_native(prec = None):
"""native float"""
lasts, t, s, n, na, d, da = 0, 3.0, 3, 1, 0, 0, 24
while s != lasts:
lasts = s
n, na = n+na, na+8
d, da = d+da, da+32
t = (t * n) / d
s += t
return s
def pi_decimal(prec):
"""Decimal"""
decimal.getcontext().prec = prec
lasts, t, s, n, na, d, da = Decimal(0), Decimal(3), Decimal(3), Decimal(1), Decimal(0), Decimal(0), Decimal(24)
while s != lasts:
lasts = s
n, na = n+na, na+8
d, da = d+da, da+32
t = (t * n) / d
s += t
return s
funcs = {
"native": pi_native,
"decimal": pi_decimal,
}
for name in ["native", "decimal"]:
print(name)
sum = 0.0
for prec in [9, 19, 38, 100]:
func = funcs[name]
start = time.time()
for i in range(10000):
x = func(prec)
d = time.time()-start
sum += d
print("%fs" % d)
print("avg: %f\n" % (sum / 4.0))
| 562 |
1,045 | /***************************************************************************************************
Tencent is pleased to support the open source community by making RapidView available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MITLicense (the "License"); you may not use this file except in compliance
withthe License. You mayobtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is
distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing permissions and limitations under the
License.
***************************************************************************************************/
package com.tencent.rapidview.data;
import com.tencent.rapidview.deobfuscated.IVar;
import com.tencent.rapidview.utils.RapidStringUtils;
import org.luaj.vm2.LuaBoolean;
import org.luaj.vm2.LuaDouble;
import org.luaj.vm2.LuaInteger;
import org.luaj.vm2.LuaString;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jse.CoerceJavaToLua;
/**
* @Class Var
* @Desc RapidView变量类型
*
* @author arlozhang
* @date 2016.12.08
*/
public class Var implements IVar {
public enum TYPE{
enum_null,
enum_boolean,
enum_int,
enum_long,
enum_float,
enum_double,
enum_string,
enum_array,
enum_object,
enum_int_array,
enum_boolean_array,
enum_float_array,
enum_double_array,
}
private TYPE mCurrentType = TYPE.enum_null;
private boolean mBoolean = false;
private int mInt = 0;
private long mLong = 0;
private float mFloat = 0;
private double mDouble = 0;
private String mString = "";
private Object[] mArray = null;
private int[] mIntArray = null;
private boolean[] mBooleanArray = null;
private float[] mFloatArray = null;
private double[] mDoubleArray = null;
private Object mObject = null;
public Var(){}
public Var(boolean value){
set(value);
}
public Var(int value){
set(value);
}
public Var(long value){
set(value);
}
public Var(float value){
set(value);
}
public Var(double value){
set(value);
}
public Var(String value){
set(value);
}
public Var(Object[] value){
int[] a = new int[6];
set(value);
}
public Var(Object value){
set(value);
}
public Var(LuaValue value){
if( value == null || value.isnil() ){
return;
}
if( value.isboolean() ){
set(value.toboolean());
return;
}
if( value.isstring() || value.isnumber() ){
set(value.toString());
return;
}
if( value.isuserdata() ){
set(value.touserdata());
return;
}
set(value);
}
public void setNull(){
mCurrentType = TYPE.enum_null;
}
public boolean isNull(){
return mCurrentType == TYPE.enum_null;
}
public TYPE getType(){
return mCurrentType;
}
public void set(boolean value){
mBoolean = value;
mCurrentType = TYPE.enum_boolean;
}
public void set(Boolean value){
mBoolean = value;
mCurrentType = TYPE.enum_boolean;
}
public void set(int value){
mInt = value;
mCurrentType = TYPE.enum_int;
}
public void set(Integer value){
mInt = value;
mCurrentType = TYPE.enum_int;
}
public void set(long value){
mLong = value;
mCurrentType = TYPE.enum_long;
}
public void set(Long value){
mLong = value;
mCurrentType = TYPE.enum_long;
}
public void setLong(long value){
mLong = value;
mCurrentType = TYPE.enum_long;
}
public void set(float value){
mFloat = value;
mCurrentType = TYPE.enum_float;
}
public void set(Float value){
mFloat = value;
mCurrentType = TYPE.enum_float;
}
public void setFloat(float value){
mFloat = value;
mCurrentType = TYPE.enum_float;
}
public void set(double value){
mDouble = value;
mCurrentType = TYPE.enum_double;
}
public void set(Double value){
mDouble = value;
mCurrentType = TYPE.enum_double;
}
public void set(String value){
if( value == null ){
value = "";
}
mString = value;
mCurrentType = TYPE.enum_string;
}
public void set(Object[] value){
mArray = value;
mCurrentType = TYPE.enum_array;
}
public void set(Object value){
mObject = value;
mCurrentType = TYPE.enum_object;
}
@Override
public boolean getBoolean(){
switch (mCurrentType){
case enum_boolean:
return mBoolean;
case enum_int:
if( mInt == 0 ){
return false;
}
return true;
case enum_long:
if( mLong == 0 ){
return false;
}
return true;
case enum_float:
if( mFloat == 0 ){
return false;
}
return true;
case enum_double:
if( mDouble == 0 ){
return false;
}
return true;
case enum_string:
return RapidStringUtils.stringToBoolean(mString);
case enum_object:
if( mObject != null && mObject instanceof Boolean ) {
return ((Boolean) mObject).booleanValue();
}
}
return false;
}
@Override
public int getInt(){
switch (mCurrentType){
case enum_int:
return mInt;
case enum_long:
return 0;
case enum_boolean:
if( mBoolean ){
return 1;
}
return 0;
case enum_float:
return (int)mFloat;
case enum_double:
return (int)mDouble;
case enum_string:
try{
return mString.isEmpty() ? 0 : Integer.parseInt(mString);
}
catch (Exception e){
e.printStackTrace();
}
break;
case enum_object:
if( mObject != null && mObject instanceof Integer ){
return ((Integer) mObject).intValue();
}
default:
return 0;
}
return 0;
}
@Override
public long getLong(){
switch (mCurrentType){
case enum_int:
return mInt;
case enum_long:
return mLong;
case enum_boolean:
if( mBoolean ){
return 1;
}
return 0;
case enum_float:
return (int)mFloat;
case enum_double:
return (int)mDouble;
case enum_string:
try{
return Long.parseLong(mString);
}
catch (Exception e){
e.printStackTrace();
}
break;
case enum_object:
if( mObject != null && mObject instanceof Long ) {
return ((Long) mObject).longValue();
}
default:
return 0;
}
return 0;
}
@Override
public float getFloat(){
switch (mCurrentType){
case enum_float:
return mFloat;
case enum_boolean:
if( mBoolean ){
return 1;
}
return 0;
case enum_int:
return mInt;
case enum_long:
return 0;
case enum_double:
return (float)mDouble;
case enum_string:
try{
return Float.parseFloat(mString);
}
catch (Exception e){
e.printStackTrace();
}
break;
case enum_object:
if( mObject != null && mObject instanceof Float ) {
return ((Float) mObject).floatValue();
}
default:
return 0;
}
return 0;
}
@Override
public double getDouble(){
switch (mCurrentType){
case enum_double:
return mDouble;
case enum_boolean:
if( mBoolean ){
return 1;
}
return 0;
case enum_int:
return mInt;
case enum_long:
return 0;
case enum_float:
return (double)mFloat;
case enum_string:
try{
return Double.parseDouble(mString);
}
catch (Exception e){
e.printStackTrace();
}
break;
case enum_object:
if( mObject != null && mObject instanceof Double ) {
return ((Double) mObject).doubleValue();
}
default:
return 0;
}
return 0;
}
@Override
public String getString(){
switch (mCurrentType){
case enum_string:
return mString == null ? "" : mString;
case enum_boolean:
return Boolean.toString(mBoolean);
case enum_int:
return Integer.toString(mInt);
case enum_long:
return Long.toString(mLong);
case enum_float:
return Float.toString(mFloat);
case enum_double:
return Double.toString(mDouble);
case enum_object:
return mObject == null ? "" : mObject.toString();
}
return "";
}
@Override
public Object getObject(){
switch (mCurrentType){
case enum_object:
return mObject;
case enum_boolean:
return mBoolean;
case enum_int:
return mInt;
case enum_long:
return mLong;
case enum_float:
return mFloat;
case enum_double:
return mDouble;
case enum_array:
return mArray;
case enum_string:
return mString;
}
return null;
}
@Override
public int getArrayLenth(){
switch (mCurrentType){
case enum_array:
return mArray.length;
case enum_int_array:
return mIntArray.length;
case enum_boolean_array:
return mBooleanArray.length;
case enum_float_array:
return mFloatArray.length;
case enum_double_array:
return mDoubleArray.length;
}
return -1;
}
@Override
public Object getArrayItem(int index){
if( mCurrentType != TYPE.enum_array ||
mArray == null ||
index < 0 ||
index >= mArray.length ){
return null;
}
return mArray[index];
}
@Override
public void createIntArray(int length){
mIntArray = new int[length];
mCurrentType = TYPE.enum_int_array;
}
@Override
public void createBooleanArray(int length){
mBooleanArray = new boolean[length];
mCurrentType = TYPE.enum_boolean_array;
}
@Override
public void createFloatArray(int length){
mFloatArray = new float[length];
mCurrentType = TYPE.enum_float_array;
}
@Override
public void createDoubleArray(int length){
mDoubleArray = new double[length];
mCurrentType = TYPE.enum_double_array;
}
@Override
public int[] getIntArray(){
return mIntArray;
}
@Override
public boolean[] getBooleanArray(){
return mBooleanArray;
}
@Override
public float[] getFloatArray(){
return mFloatArray;
}
@Override
public double[] getDoubleArray(){
return mDoubleArray;
}
@Override
public int getIntArrayItem(int index){
return mIntArray[index];
}
@Override
public boolean getBooleanArrayItem(int index){
return mBooleanArray[index];
}
@Override
public float getFloatArrayItem(int index){
return mFloatArray[index];
}
@Override
public double getDoubleArrayItem(int index){
return mDoubleArray[index];
}
public Object[] getArray(){
if( mCurrentType != TYPE.enum_array ){
return null;
}
return mArray;
}
@Override
public LuaValue getLuaValue(){
switch (mCurrentType){
case enum_object:
if( mObject instanceof Object[] ||
mObject instanceof byte[] ||
mObject instanceof int[] ||
mObject instanceof boolean[]||
mObject instanceof float[] ||
mObject instanceof double[] ){
return LuaValue.userdataOf(mObject);
}
else {
return CoerceJavaToLua.coerce(mObject);
}
case enum_boolean:
return LuaBoolean.valueOf(mBoolean);
case enum_int:
return LuaInteger.valueOf(mInt);
case enum_long:
return LuaInteger.valueOf(mLong);
case enum_float:
return LuaDouble.valueOf(mFloat);
case enum_double:
return LuaDouble.valueOf(mDouble);
case enum_array:
return arrayToTable(mArray);
case enum_string:
return LuaString.valueOf(mString);
}
return null;
}
private static LuaTable arrayToTable(Object[] arrayObj){
LuaTable table = new LuaTable();
for( int i = 0; i < arrayObj.length; i++ ){
table.set( LuaInteger.valueOf( i + 1), CoerceJavaToLua.coerce(arrayObj[i]));
}
return table;
}
}
| 7,682 |
669 | """
Copyright (c) Facebook, Inc. and its affiliates.
"""
import logging
from multiprocessing import Queue, Process
from droidlet.perception.craftassist.heuristic_perception import all_nearby_objects
from droidlet.shared_data_struct.craftassist_shared_utils import CraftAssistPerceptionData
from .semantic_segmentation.semseg_models import SemSegWrapper
from droidlet.base_util import blocks_list_to_npy, get_bounds
# TODO all "subcomponent" operations are replaced with InstSeg
class SubcomponentClassifierWrapper:
"""Perceive the world at a given frequency and update agent
memory.
creates InstSegNodes and tags them
Args:
agent (LocoMCAgent): reference to the minecraft Agent
model_path (str): path to the segmentation model
perceive_freq (int): if not forced, how many Agent steps between perception.
If 0, does not run unless forced
"""
def __init__(self, agent, model_path, low_level_data, perceive_freq=0):
self.agent = agent
# Note remove the following
self.memory = self.agent.memory
self.perceive_freq = perceive_freq
self.boring_blocks = low_level_data["boring_blocks"]
self.passable_blocks = low_level_data["passable_blocks"]
if model_path is not None:
self.subcomponent_classifier = SubComponentClassifier(voxel_model_path=model_path)
self.subcomponent_classifier.start()
else:
self.subcomponent_classifier = None
def perceive(self, force=False):
"""
Run the classifiers in the world and get the resulting labels
Args:
force (boolean): set to True to run all perceptual heuristics right now,
as opposed to waiting for perceive_freq steps (default: False)
"""
perceive_info = {}
perceive_info["labeled_blocks"] = {} # Dict with mapping: label -> [location of blocks with this label]
if self.perceive_freq == 0 and not force:
return CraftAssistPerceptionData()
if self.perceive_freq > 0 and self.agent.count % self.perceive_freq != 0 and not force:
return CraftAssistPerceptionData()
if self.subcomponent_classifier is None:
return CraftAssistPerceptionData()
# TODO don't all_nearby_objects again, search in memory instead
to_label = []
# add all blocks in marked areas
for pos, radius in self.agent.areas_to_perceive:
for obj in all_nearby_objects(self.agent.get_blocks, pos, self.boring_blocks, self.passable_blocks, radius):
to_label.append(obj)
# add all blocks near the agent
for obj in all_nearby_objects(self.agent.get_blocks, self.agent.pos, self.boring_blocks, self.passable_blocks):
to_label.append(obj)
for obj in to_label:
self.subcomponent_classifier.block_objs_q.put(obj)
# everytime we try to retrieve as many recognition results as possible
while not self.subcomponent_classifier.loc2labels_q.empty():
loc2labels, obj = self.subcomponent_classifier.loc2labels_q.get()
loc2ids = dict(obj)
label2blocks = {}
def contaminated(blocks):
"""
Check if blocks are still consistent with the current world
"""
mx, Mx, my, My, mz, Mz = get_bounds(blocks)
yzxb = self.agent.get_blocks(mx, Mx, my, My, mz, Mz)
for b, _ in blocks:
x, y, z = b
if loc2ids[b][0] != yzxb[y - my, z - mz, x - mx, 0]:
return True
return False
for loc, labels in loc2labels.items():
b = (loc, loc2ids[loc])
for l in labels:
if l in label2blocks:
label2blocks[l].append(b)
else:
label2blocks[l] = [b]
for l, blocks in label2blocks.items():
## if the blocks are contaminated we just ignore
if not contaminated(blocks):
locs = [loc for loc, idm in blocks]
perceive_info["labeled_blocks"][l] = locs
return CraftAssistPerceptionData(labeled_blocks=perceive_info["labeled_blocks"])
class SubComponentClassifier(Process):
"""
A classifier class that calls a voxel model to output object tags.
"""
def __init__(self, voxel_model_path=None):
super().__init__()
if voxel_model_path is not None:
logging.info(
"SubComponentClassifier using voxel_model_path={}".format(voxel_model_path)
)
self.model = SemSegWrapper(voxel_model_path)
else:
raise Exception("specify a segmentation model")
self.block_objs_q = Queue() # store block objects to be recognized
self.loc2labels_q = Queue() # store loc2labels dicts to be retrieved by the agent
self.daemon = True
def run(self):
"""
The main recognition loop of the classifier
"""
while True: # run forever
tb = self.block_objs_q.get(block=True, timeout=None)
loc2labels = self._watch_single_object(tb)
self.loc2labels_q.put((loc2labels, tb))
def _watch_single_object(self, tuple_blocks):
"""
Input: a list of tuples, where each tuple is ((x, y, z), [bid, mid]). This list
represents a block object.
Output: a dict of (loc, [tag1, tag2, ..]) pairs for all non-air blocks.
"""
def get_tags(p):
"""
convert a list of tag indices to a list of tags
"""
return [self.model.tags[i][0] for i in p]
def apply_offsets(cube_loc, offsets):
"""
Convert the cube location back to world location
"""
return (cube_loc[0] + offsets[0], cube_loc[1] + offsets[1], cube_loc[2] + offsets[2])
np_blocks, offsets = blocks_list_to_npy(blocks=tuple_blocks, xyz=True)
pred = self.model.segment_object(np_blocks)
# convert prediction results to string tags
return dict([(apply_offsets(loc, offsets), get_tags([p])) for loc, p in pred.items()])
def recognize(self, list_of_tuple_blocks):
"""
Multiple calls to _watch_single_object
"""
tags = dict()
for tb in list_of_tuple_blocks:
tags.update(self._watch_single_object(tb))
return tags
| 2,921 |
690 | <filename>tasks/sts.py<gh_stars>100-1000
"""
KeraSTS interface for datasets of the Semantic Text Similarity task.
See data/sts/... for details and actual datasets.
Training example:
tools/train.py cnn sts data/sts/semeval-sts/all/2015.train.tsv data/sts/semeval-sts/all/2015.val.tsv
"""
from __future__ import print_function
from __future__ import division
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.layers.core import Activation, Dense
from keras.models import Graph
from keras.regularizers import l2
import numpy as np
import pysts.eval as ev
from pysts.kerasts import graph_input_sts
import pysts.kerasts.blocks as B
from pysts.kerasts.callbacks import STSPearsonCB
from pysts.kerasts.objectives import pearsonobj
import pysts.loader as loader
import pysts.nlp as nlp
from pysts.vocab import Vocabulary
from . import AbstractTask
class STSTask(AbstractTask):
def __init__(self):
self.name = 'sts'
self.spad = 60
self.s0pad = self.spad
self.s1pad = self.spad
self.emb = None
self.vocab = None
def config(self, c):
c['ptscorer'] = B.dot_ptscorer
c['loss'] = pearsonobj # ...or 'categorical_crossentropy'
c['nb_epoch'] = 32
def load_set(self, fname):
def load_file(fname, skip_unlabeled=True):
# XXX: ugly logic
if 'sick2014' in fname:
return loader.load_sick2014(fname)
else:
return loader.load_sts(fname, skip_unlabeled=skip_unlabeled)
s0, s1, y = load_file(fname)
if self.vocab is None:
vocab = Vocabulary(s0 + s1, prune_N=self.c['embprune'], icase=self.c['embicase'])
else:
vocab = self.vocab
si0, sj0 = vocab.vectorize(s0, self.emb, spad=self.s0pad)
si1, sj1 = vocab.vectorize(s1, self.emb, spad=self.s1pad)
f0, f1 = nlp.sentence_flags(s0, s1, self.s0pad, self.s1pad)
gr = graph_input_sts(si0, si1, sj0, sj1, y, f0, f1, s0, s1)
return (gr, y, vocab)
def prep_model(self, module_prep_model):
# Input embedding and encoding
model = Graph()
N = B.embedding(model, self.emb, self.vocab, self.s0pad, self.s1pad,
self.c['inp_e_dropout'], self.c['inp_w_dropout'], add_flags=self.c['e_add_flags'])
# Sentence-aggregate embeddings
final_outputs = module_prep_model(model, N, self.s0pad, self.s1pad, self.c)
# Measurement
if self.c['ptscorer'] == '1':
# special scoring mode just based on the answer
# (assuming that the question match is carried over to the answer
# via attention or another mechanism)
ptscorer = B.cat_ptscorer
final_outputs = [final_outputs[1]]
else:
ptscorer = self.c['ptscorer']
kwargs = dict()
if ptscorer == B.mlp_ptscorer:
kwargs['sum_mode'] = self.c['mlpsum']
kwargs['Dinit'] = self.c['Dinit']
model.add_node(name='scoreS', input=ptscorer(model, final_outputs, self.c['Ddim'], N, self.c['l2reg'], **kwargs),
layer=Activation('linear'))
model.add_node(name='out', input='scoreS',
layer=Dense(6, W_regularizer=l2(self.c['l2reg'])))
model.add_node(name='outS', input='out',
layer=Activation('softmax'))
model.add_output(name='classes', input='outS')
return model
def build_model(self, module_prep_model, do_compile=True):
if self.c['ptscorer'] is None:
# non-neural model
return module_prep_model(self.vocab, self.c, output='classes')
model = self.prep_model(module_prep_model)
for lname in self.c['fix_layers']:
model.nodes[lname].trainable = False
if do_compile:
model.compile(loss={'classes': self.c['loss']}, optimizer=self.c['opt'])
return model
def fit_callbacks(self, weightsf):
return [STSPearsonCB(self, self.gr, self.grv),
ModelCheckpoint(weightsf, save_best_only=True, monitor='pearson', mode='max'),
EarlyStopping(monitor='pearson', mode='max', patience=3)]
def predict(self, model, gr):
batch_size = 16384 # XXX: hardcoded
ypred = []
for ogr in self.sample_pairs(gr, batch_size, shuffle=False, once=True):
ypred += list(model.predict(ogr)['classes'])
return np.array(ypred)
def eval(self, model):
res = []
for gr, fname in [(self.gr, self.trainf), (self.grv, self.valf), (self.grt, self.testf)]:
if gr is None:
res.append(None)
continue
ypred = self.predict(model, gr)
res.append(ev.eval_sts(ypred, gr['classes'], fname))
return tuple(res)
def res_columns(self, mres, pfx=' '):
""" Produce README-format markdown table row piece summarizing
important statistics """
return('%s%.6f |%s%.6f |%s%.6f'
% (pfx, mres[self.trainf]['Pearson'],
pfx, mres[self.valf]['Pearson'],
pfx, mres[self.testf].get('Pearson', np.nan)))
def task():
return STSTask()
| 2,492 |
852 | <reponame>ckamtsikis/cmssw
# https://hypernews.cern.ch/HyperNews/CMS/get/sw-develtools/1894.html
| 44 |
5,169 | <gh_stars>1000+
{
"name": "Cribug",
"version": "0.1.0",
"swift_version": "5.0",
"summary": "Cribug is a lightweight, pure-Swift download framework.",
"homepage": "https://github.com/Initial-C/Cribug",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"InitialC": "<EMAIL>"
},
"source": {
"git": "https://github.com/Initial-C/Cribug.git",
"tag": "0.1.0"
},
"platforms": {
"ios": "8.0"
},
"source_files": "Cribug/*.swift",
"requires_arc": true,
"pod_target_xcconfig": {
"SWIFT_VERSION": "5.0"
}
}
| 265 |
511 | /*
* Routines to access hardware
*
* Copyright (c) 2013 Realtek Semiconductor Corp.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*/
#include "ameba_soc.h"
/**
* @brief set wake up event.
* @param Option:
* This parameter can be any combination of the following values:
* @arg BIT_LP_WEVT_HS_MSK
* @arg BIT_LP_WEVT_AON_MSK
* @arg BIT_LP_WEVT_SGPIO_MSK
* @arg BIT_LP_WEVT_COMP_MSK
* @arg BIT_LP_WEVT_ADC_MSK
* @arg BIT_LP_WEVT_I2C_MSK
* @arg BIT_LP_WEVT_UART_MSK
* @arg BIT_LP_WEVT_BOD_MSK
* @arg BIT_LP_WEVT_WLAN_MSK
* @arg BIT_LP_WEVT_GPIO_MSK
* @arg BIT_LP_WEVT_SWRD_OCP_MSK
* @arg BIT_LP_WEVT_TIMER_MSK
* @param NewStatus: TRUE/FALSE.
* @retval None
*/
IMAGE2_RAM_TEXT_SECTION
void SOCPS_SetWakeEvent(u32 Option, u32 NewStatus)
{
u32 WakeEvent = 0;
/* Mask System IRQ INT */
HAL_WRITE32(SYSTEM_CTRL_BASE, REG_LP_PWRMGT_CTRL, (HAL_READ32(SYSTEM_CTRL_BASE, REG_LP_PWRMGT_CTRL) | BIT_LSYS_SYSIRQ_MASK_POLL));
/* Set Event */
WakeEvent = HAL_READ32(SYSTEM_CTRL_BASE, REG_LP_SLP_WAKE_EVENT_MSK0);
if (NewStatus == ENABLE) {
WakeEvent |= Option;
} else {
WakeEvent &= ~Option;
}
HAL_WRITE32(SYSTEM_CTRL_BASE, REG_LP_SLP_WAKE_EVENT_MSK0, WakeEvent);
}
/**
* @brief set wake up event.
* @param Option:
* This parameter can be any combination of the following values:
* @arg BIT_KEYSCAN_WAKE_MSK
* @arg BIT_DLPS_TSF_WAKE_MSK
* @arg BIT_RTC_WAKE_MSK
* @arg BIT_AON_WAKE_TIM0_MSK
* @arg BIT_GPIO_WAKE_MSK
* @param NewStatus: TRUE/FALSE.
* @retval None
*/
IMAGE2_RAM_TEXT_SECTION
void SOCPS_SetWakeEventAON(u32 Option, u32 NewStatus)
{
u32 WakeEvent = 0;
/* Set Event */
WakeEvent = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AON_WAKE_OPT_MSK);
if (NewStatus == ENABLE) {
WakeEvent |= Option;
} else {
WakeEvent &= ~Option;
}
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_AON_WAKE_OPT_MSK, WakeEvent);
}
/**
* @brief clear all of wake_pin interrupt(Max. 4 wake_pin).
* @retval None
*
*/
IMAGE2_RAM_TEXT_SECTION
void SOCPS_ClearWakePin(void)
{
u32 Rtemp = HAL_READ32(SYSTEM_CTRL_BASE, REG_AON_WAKE_GPIO_CTRL2);
Rtemp |= (BIT_AON_MASK_GPIO_WAKE_EVENT << BIT_AON_SHIFT_GPIO_WAKE_EVENT);//0x0F000000;
Rtemp &= (~(BIT_AON_MASK_GPIO_WAKE_PUPD_EN << BIT_AON_SHIFT_GPIO_WAKE_PUPD_EN)); /* close internal PU/PD resistence */
HAL_WRITE32(SYSTEM_CTRL_BASE, REG_AON_WAKE_GPIO_CTRL2, Rtemp);
}
/**
* @brief clear wake event.
* @retval None
*/
IMAGE2_RAM_TEXT_SECTION
void SOCPS_ClearWakeEvent(void)
{
u32 Rtemp = 0;
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE, REG_LP_SLP_WAKE_EVENT_STATUS0);
HAL_WRITE32(SYSTEM_CTRL_BASE, REG_LP_SLP_WAKE_EVENT_STATUS0, Rtemp);
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE, REG_LP_SLP_WAKE_EVENT_STATUS1);
HAL_WRITE32(SYSTEM_CTRL_BASE, REG_LP_SLP_WAKE_EVENT_STATUS1, Rtemp);
/* clear Deep sleep wake event */
SOCPS_AONWakeClear(BIT_ALL_WAKE_STS & (~BIT_KEYSCAN_WAKE_STS));
}
IMAGE2_RAM_TEXT_SECTION
void SOCPS_AudioLDO(u32 NewStatus)
{
u32 temp = 0;
static u32 PadPower = 0;
if (NewStatus == DISABLE) {
//0x4800_0344[8] = 1'b1 (BIT_LSYS_AC_MBIAS_POW)
temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AUDIO_SHARE_PAD_CTRL);
temp &= ~(BIT_LSYS_AC_MBIAS_POW | BIT_LSYS_AC_LDO_POW);
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_AUDIO_SHARE_PAD_CTRL, temp);
//store pad power
PadPower = (temp >> BIT_LSYS_SHIFT_AC_LDO_REG) & BIT_LSYS_MASK_AC_LDO_REG;
//0x4800_0280[2:0] = 3'h7 (Enable BG)
temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_SYSPLL_CTRL0);
temp &= ~(BIT_LP_PLL_BG_EN | BIT_LP_PLL_BG_I_EN | BIT_LP_PLL_MBIAS_EN);
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_SYSPLL_CTRL0, temp);
} else {
if (wifi_config.wifi_ultra_low_power) {
return;
}
/* if audio not use, save power */
if (ps_config.km0_audio_pad_enable == FALSE) {
return;
}
temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AUDIO_SHARE_PAD_CTRL);
if ((temp & BIT_LSYS_AC_LDO_POW) != 0) {
return;
}
//0x4800_0280[2:0] = 3'h7 (Enable BG)
temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_SYSPLL_CTRL0);
temp |= (BIT_LP_PLL_BG_EN | BIT_LP_PLL_BG_I_EN | BIT_LP_PLL_MBIAS_EN);
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_SYSPLL_CTRL0, temp);
//0x4800_0344[8] = 1'b1 (BIT_LSYS_AC_MBIAS_POW)
temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AUDIO_SHARE_PAD_CTRL);
temp |= BIT_LSYS_AC_MBIAS_POW;
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_AUDIO_SHARE_PAD_CTRL, temp);
//Delay 2us, 0x4800_0344[0] = 1'b1 (BIT_LSYS_AC_LDO_POW)
DelayUs(5);
//enable Audio LDO.
temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AUDIO_SHARE_PAD_CTRL);
temp &= ~(BIT_LSYS_MASK_AC_LDO_REG << BIT_LSYS_SHIFT_AC_LDO_REG);
//restore the pad power
temp |= (PadPower) << BIT_LSYS_SHIFT_AC_LDO_REG;
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_AUDIO_SHARE_PAD_CTRL, temp);
temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AUDIO_SHARE_PAD_CTRL);
temp |= BIT_LSYS_AC_LDO_POW;
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_AUDIO_SHARE_PAD_CTRL, temp);
}
}
//IMAGE2_RAM_TEXT_SECTION
VOID SOCPS_OSC2M_Cmd(u32 new_status)
{
u32 Temp = 0;
Temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_OSC2M_CTRL);
if (new_status == DISABLE) {
Temp &= ~BIT_OSC2M_EN;
} else {
Temp |= BIT_OSC2M_EN;
}
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_OSC2M_CTRL, Temp);
}
IMAGE2_RAM_TEXT_SECTION
VOID SOCPS_SWRLDO_Suspend(u32 new_status)
{
u32 Temp;
/* suspend */
if (new_status == ENABLE) {
/* BIT_SHIFT_SWR_OCP_L1 to fix PFM pulse 500uA issue, PFM pulse is 100uA */
//Temp=HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_SYS_EFUSE_SYSCFG1);
//Temp &= ~BIT_MASK_SWR_REG_ZCDC_H;
//Temp &= ~BIT_MASK_SWR_OCP_L1;
//Temp |= (0x03 << BIT_SHIFT_SWR_OCP_L1); /* PWM:600 PFM: 250, default is 0x04 */
//HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_SYS_EFUSE_SYSCFG1,Temp); /*move OCP_L1 setting to app_pmu_init(), set 0x03 in both sleep and active*/
/* LP_LDO can not set 0.692V under DSLP mode, because DSLP snooze use it */
/* LP_LDO not use in other case */
/* set LP_LDO to 0.782V(we dont use it) to fix SWR 0.9V(REG_SWR_PSW_CTRL = 0x8765) power leakage issue */
Temp=HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AON_LDO_CTRL1);
Temp &= ~(BIT_MASK_LDO_LP_ADJ << BIT_SHIFT_LDO_LP_ADJ);
Temp |= (0x03 << BIT_SHIFT_LDO_LP_ADJ); /* 0.692V, this LDO is not used */
Temp |= BIT_LDO_LP_SLEEP_EN; /* 7uA */
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_AON_LDO_CTRL1,Temp);
/* set AON LDO sleep mode, voltage default is 0x09=0.899V */
Temp=HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AON_LDO_CTRL0);
Temp &= ~(BIT_MASK_AON_LDO_V09_ADJ << BIT_SHIFT_AON_LDO_V09_ADJ);
Temp |= (0x09 << BIT_SHIFT_AON_LDO_V09_ADJ); //>0.81V is save for MP
Temp |= BIT_AON_LDO_SLP_EN; /* 11uA */
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_AON_LDO_CTRL0,Temp);
} else {
/* BIT_SHIFT_SWR_OCP_L1 fix active cost 2mA more issue */
//Temp=HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_SYS_EFUSE_SYSCFG1);
//Temp &= ~BIT_MASK_SWR_REG_ZCDC_H;
//Temp |= (0x02 << BIT_SHIFT_SWR_REG_ZCDC_H);
//Temp &= ~BIT_MASK_SWR_OCP_L1;
//Temp |= (0x04 << BIT_SHIFT_SWR_OCP_L1);
//HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_SYS_EFUSE_SYSCFG1,Temp);/*move OCP_L1 setting to app_pmu_init()*/
/* set LP_LDO to 0.782V(we dont use it) to fix SWR 0.9V(REG_SWR_PSW_CTRL = 0x8765) power leakage issue */
Temp=HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AON_LDO_CTRL1);
Temp &= ~(BIT_MASK_LDO_LP_ADJ << BIT_SHIFT_LDO_LP_ADJ);
Temp |= (0x09 << BIT_SHIFT_LDO_LP_ADJ);
Temp &= ~BIT_LDO_LP_SLEEP_EN;
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_AON_LDO_CTRL1,Temp);
/* set AON LDO sleep mode, voltage default is 0x09=0.899V */
Temp=HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AON_LDO_CTRL0);
Temp &= ~(BIT_MASK_AON_LDO_V09_ADJ << BIT_SHIFT_AON_LDO_V09_ADJ);
Temp |= (0x09 << BIT_SHIFT_AON_LDO_V09_ADJ);
Temp &= ~BIT_AON_LDO_SLP_EN;
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_AON_LDO_CTRL0,Temp);
}
/*During mass production period, some ICs fail to wake up , TYTsai Suggest to set ZCDC settings.
However, This advise should verify the whole RF again, so we only set ZCDC before sleep and restore after wakes up.
*/
Temp=HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_SYS_EFUSE_SYSCFG1);
if(new_status == ENABLE) {
Temp &= ~BIT_MASK_SWR_REG_ZCDC_H;
Temp |= 0x2 << BIT_SHIFT_SWR_REG_ZCDC_H;
} else {
Temp &= ~BIT_MASK_SWR_REG_ZCDC_H;
}
//rtw_printf("setting ZCD to %x in %s\n",Temp,new_status? "suspend": "resume");
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_SYS_EFUSE_SYSCFG1,Temp);
}
/**
* @brief enter sleep power gate mode.
* @retval None
*
*/
IMAGE2_RAM_TEXT_SECTION
void SOCPS_SleepCG_RAM(VOID)
{
u32 Rtemp = 0;
pinmap_sleep(); //50us
km4_flash_highspeed_suspend(FALSE);//80us
if (ps_config.km0_osc2m_close) {
SOCPS_OSC2M_Cmd(DISABLE);//10us
}
FLASH_DeepPowerDown(ENABLE);//120us
SOCPS_AudioLDO(DISABLE);//15us
/* don't close CPU */
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE, REG_LP_PWRMGT_OPTION);
Rtemp |= BIT_LSYS_PST_SLEP_ESOC;
HAL_WRITE32(SYSTEM_CTRL_BASE, REG_LP_PWRMGT_OPTION, Rtemp);//10us
if(SLEEP_PG == km4_sleep_type) {
/* Disable HS Platform/HSSYSON power */
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL);
Rtemp |= BIT_LSYS_ISO_HSOC; //enable isolation
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL, Rtemp);
Rtemp &= ~(BIT_MASK_LSYS_HPLAT_PWC_EN_BIT2 | BIT_MASK_LSYS_HPLAT_PWC_EN_BIT3);//close power
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL, Rtemp);
}
/* set power mode */
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE, REG_LP_PWRMGT_CTRL);
Rtemp |= (BIT_LSYS_PMC_PMEN_SLEP);
Rtemp &= ~BIT_LSYS_PMC_PMEN_DSLP;
HAL_WRITE32(SYSTEM_CTRL_BASE, REG_LP_PWRMGT_CTRL, Rtemp);
/* it will take 6.5us to enter clock gating mode after register set */
DelayUs(50);
/* use to check wakeup time in 66319D */
//BOOT_ROM_CM4PON((u32)HSPWR_ON_SEQ_TEST);
//DelayMs(3);
//BOOT_ROM_CM4PON((u32)HSPWR_OFF_SEQ_TEST);
/* enable EE LDR clock for hw efuse autoload*/
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE, REG_LP_CLK_CTRL0);
Rtemp |= (BIT_SYSON_CK_EELDR_EN);
HAL_WRITE32(SYSTEM_CTRL_BASE, REG_LP_CLK_CTRL0, Rtemp);
/*enable wifi pmc for pfm patch*/
if(HAL_READ32(SYSTEM_CTRL_BASE, REG_LP_SLP_WAKE_EVENT_STATUS0) & BIT_LP_WEVT_WLAN_STS) {
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_WL_POW_CTRL);
Rtemp |= (BIT16);
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_WL_POW_CTRL, Rtemp);
}
TIMM05->CNT = 0;
ps_config.km0_wake_time = RTIM_TestTimer_GetCount();
/*enable HS platform power for high 8k txpktbuffer only for A cut*/
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL);
Rtemp |= BIT_MASK_LSYS_HPLAT_PWC_EN_BIT2;
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL, Rtemp);
//move to km4 on to shrink wakeup time
//SOCPS_AudioLDO(ENABLE);//84
/* wakeup */
FLASH_DeepPowerDown(DISABLE);//257
if(SLEEP_PG == km4_sleep_type) {
/*release HS platform power Isolation only for A cut*/
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL);
Rtemp |= BIT_MASK_LSYS_HPLAT_PWC_EN_BIT3;//power on hs platform for txpktbuffer high 8k
Rtemp &= ~BIT_LSYS_ISO_HSOC;
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL, Rtemp);
}
if (ps_config.km0_osc2m_close) {
SOCPS_OSC2M_Cmd(ENABLE);//267
}
km4_flash_highspeed_resume(FALSE);//921
pinmap_wake();//954
}
/**
* @brief enter sleep power gate mode.
* @retval None
*
*/
IMAGE2_RAM_TEXT_SECTION
void SOCPS_SleepPG_RAM(VOID)
{
u32 Rtemp = 0;
pinmap_sleep(); //50us
km4_flash_highspeed_suspend(FALSE); //80us
if (ps_config.km0_osc2m_close) {
SOCPS_OSC2M_Cmd(DISABLE);
}
FLASH_DeepPowerDown(ENABLE);
SOCPS_AudioLDO(DISABLE);
/* close CPU */
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE, REG_LP_PWRMGT_OPTION);
Rtemp &= ~BIT_LSYS_PST_SLEP_ESOC;
HAL_WRITE32(SYSTEM_CTRL_BASE, REG_LP_PWRMGT_OPTION, Rtemp);
/*reset flash to solve wakeup no spic clock issue*/
RCC_PeriphClockCmd(APBPeriph_FLASH, APBPeriph_FLASH_CLOCK_XTAL, DISABLE);
/* Disable HS Platform/HSSYSON power */
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL);
Rtemp |= BIT_LSYS_ISO_HSOC; //enable isolation
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL, Rtemp);
Rtemp &= ~(BIT_MASK_LSYS_HPLAT_PWC_EN_BIT2 | BIT_MASK_LSYS_HPLAT_PWC_EN_BIT3);//close power
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL, Rtemp);
/* set power mode */
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE, REG_LP_PWRMGT_CTRL);
Rtemp |= (BIT_LSYS_PMC_PMEN_SLEP);
Rtemp &= ~BIT_LSYS_PMC_PMEN_DSLP;
HAL_WRITE32(SYSTEM_CTRL_BASE, REG_LP_PWRMGT_CTRL, Rtemp);
/* it will take 6.5us to enter clock gating mode after register set */
__WFI();
/* cpu bug workaround or cpu may cannot wakeup */
asm volatile("nop");
/* enable EE LDR clock for hw efuse autoload*/
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE, REG_LP_CLK_CTRL0);
Rtemp |= (BIT_SYSON_CK_EELDR_EN);
HAL_WRITE32(SYSTEM_CTRL_BASE, REG_LP_CLK_CTRL0, Rtemp);
/*enable HS platform power for high 8k txpktbuffer.*/
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL);
Rtemp |= BIT_MASK_LSYS_HPLAT_PWC_EN_BIT2;
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL, Rtemp);
/* if wakeup happened when sleep, following code will be run */
/*for break power-off condition to reinit spic*/
RCC_PeriphClockCmd(APBPeriph_FLASH, APBPeriph_FLASH_CLOCK_XTAL, ENABLE);
FLASH_Init(flash_init_para.FLASH_cur_bitmode);
Cache_Enable(ENABLE);
/* soc sleep need it, or wakeup will fail */
FLASH_DeepPowerDown(DISABLE);
/*release HS platform power Isolation.*/
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL);
Rtemp |= BIT_MASK_LSYS_HPLAT_PWC_EN_BIT3;//power on hs platform for txpktbuffer high 8k
Rtemp &= ~BIT_LSYS_ISO_HSOC;
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LP_PWR_ISO_CTRL, Rtemp);
SOCPS_MMUReFill();
km4_flash_highspeed_resume(FALSE);
//move to km4 on to shrink wakeup time
//SOCPS_AudioLDO(ENABLE);
}
/**
* @brief enter deep sleep mode, patch of SOCPS_DeepSleep.
* @retval None
*
*/
IMAGE2_RAM_TEXT_SECTION
void SOCPS_DeepSleep_RAM(void)
{
u32 Rtemp = 0;
DBG_8195A("M0DS \n");
/* init wake event */
SOCPS_DsleepInit();
/* pin power leakage */
pinmap_deepsleep();
/* clear wake event */
SOCPS_ClearWakeEvent();
/* Interrupt Clear Pending Register, clear all interrupt */
//NVIC->ICPR[0] = NVIC_ICPR0_PS_MASK;
/* Enable low power mode */
FLASH_DeepPowerDown(ENABLE);
/* set LP_LDO to 0.899V to fix RTC Calibration XTAL power leakage issue */
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AON_LDO_CTRL1);
Rtemp &= ~(BIT_MASK_LDO_LP_ADJ << BIT_SHIFT_LDO_LP_ADJ);
Rtemp |= (0x09 << BIT_SHIFT_LDO_LP_ADJ); /* 0.899V, or ADC/XTAL will work abnormal in deepsleep mode */
Rtemp &= (~BIT_LDO_PSRAM_EN);/*Close PSRAM power, or DSLP current will increase*/
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_AON_LDO_CTRL1,Rtemp);
/* Shutdown LSPAD(no AON) at the end of DSLP flow */
/* Fix ACUT power leakage issue */
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AON_PWR_CTRL);
Rtemp &= ~BIT_DSLP_SNOOZE_MODE_LSPAD_SHUTDOWN;
HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_AON_PWR_CTRL, Rtemp);
/* set power mode */
Rtemp = HAL_READ32(SYSTEM_CTRL_BASE, REG_LP_PWRMGT_CTRL);
Rtemp &= ~BIT_LSYS_PMC_PMEN_SLEP;
Rtemp |= BIT_LSYS_PMC_PMEN_DSLP;
HAL_WRITE32(SYSTEM_CTRL_BASE, REG_LP_PWRMGT_CTRL, Rtemp);
/* Wait CHIP enter deep sleep mode */
__WFI();
}
| 7,511 |
335 | <filename>L/Lower_noun.json
{
"word": "Lower",
"definitions": [
"A scowl.",
"A dark and gloomy appearance of the sky, weather or landscape."
],
"parts-of-speech": "Noun"
} | 89 |
852 | #ifndef DataFormats_L1Trigger_HGCalMulticluster_h
#define DataFormats_L1Trigger_HGCalMulticluster_h
#include "DataFormats/Common/interface/Ptr.h"
#include "DataFormats/L1Trigger/interface/BXVector.h"
#include "DataFormats/L1THGCal/interface/HGCalClusterT.h"
#include "DataFormats/L1THGCal/interface/HGCalCluster.h"
#include <boost/iterator/transform_iterator.hpp>
#include <functional>
namespace l1t {
class HGCalMulticluster : public HGCalClusterT<l1t::HGCalCluster> {
public:
HGCalMulticluster() : hOverEValid_(false) {}
HGCalMulticluster(const LorentzVector p4, int pt = 0, int eta = 0, int phi = 0);
HGCalMulticluster(const edm::Ptr<l1t::HGCalCluster>& tc, float fraction = 1);
~HGCalMulticluster() override;
float hOverE() const {
// --- this below would be faster when reading old objects, as HoE will only be computed once,
// --- but it may not be allowed by CMS rules because of the const_cast
// --- and could potentially cause a data race
// if (!hOverEValid_) (const_cast<HGCalMulticluster*>(this))->saveHOverE();
// --- this below is safe in any case
return hOverEValid_ ? hOverE_ : l1t::HGCalClusterT<l1t::HGCalCluster>::hOverE();
}
void saveHOverE() {
hOverE_ = l1t::HGCalClusterT<l1t::HGCalCluster>::hOverE();
hOverEValid_ = true;
}
enum EnergyInterpretation { EM = 0 };
void saveEnergyInterpretation(const HGCalMulticluster::EnergyInterpretation eInt, double energy);
double iEnergy(const HGCalMulticluster::EnergyInterpretation eInt) const {
return energy() * interpretationFraction(eInt);
}
double iPt(const HGCalMulticluster::EnergyInterpretation eInt) const { return pt() * interpretationFraction(eInt); }
math::XYZTLorentzVector iP4(const HGCalMulticluster::EnergyInterpretation eInt) const {
return p4() * interpretationFraction(eInt);
}
math::PtEtaPhiMLorentzVector iPolarP4(const HGCalMulticluster::EnergyInterpretation eInt) const {
return math::PtEtaPhiMLorentzVector(pt() * interpretationFraction(eInt), eta(), phi(), 0.);
}
private:
template <typename Iter>
struct KeyGetter : std::unary_function<typename Iter::value_type, typename Iter::value_type::first_type> {
const typename Iter::value_type::first_type& operator()(const typename Iter::value_type& p) const {
return p.first;
}
};
template <typename Iter>
boost::transform_iterator<KeyGetter<Iter>, Iter> key_iterator(Iter itr) const {
return boost::make_transform_iterator<KeyGetter<Iter>, Iter>(itr, KeyGetter<Iter>());
}
public:
typedef boost::transform_iterator<KeyGetter<std::map<EnergyInterpretation, double>::const_iterator>,
std::map<EnergyInterpretation, double>::const_iterator>
EnergyInterpretation_const_iterator;
std::pair<EnergyInterpretation_const_iterator, EnergyInterpretation_const_iterator> energyInterpretations() const {
return std::make_pair(key_iterator(energyInterpretationFractions_.cbegin()),
key_iterator(energyInterpretationFractions_.cend()));
}
EnergyInterpretation_const_iterator interpretations_begin() const {
return key_iterator(energyInterpretationFractions_.cbegin());
}
EnergyInterpretation_const_iterator interpretations_end() const {
return key_iterator(energyInterpretationFractions_.cend());
}
size_type interpretations_size() const { return energyInterpretationFractions_.size(); }
private:
double interpretationFraction(const HGCalMulticluster::EnergyInterpretation eInt) const;
float hOverE_;
bool hOverEValid_;
std::map<EnergyInterpretation, double> energyInterpretationFractions_;
};
typedef BXVector<HGCalMulticluster> HGCalMulticlusterBxCollection;
} // namespace l1t
#endif
| 1,422 |
1,016 | package com.thinkbiganalytics.feedmgr.service.template.importing.validation;
/*-
* #%L
* thinkbig-feed-manager-controller
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.thinkbiganalytics.feedmgr.nifi.NifiTemplateParser;
import com.thinkbiganalytics.feedmgr.rest.ImportComponent;
import com.thinkbiganalytics.feedmgr.rest.ImportSection;
import com.thinkbiganalytics.feedmgr.rest.model.ImportComponentOption;
import com.thinkbiganalytics.feedmgr.rest.model.ImportTemplateOptions;
import com.thinkbiganalytics.feedmgr.rest.model.UploadProgressMessage;
import com.thinkbiganalytics.feedmgr.service.UploadProgressService;
import com.thinkbiganalytics.feedmgr.service.template.importing.model.ImportTemplate;
import com.thinkbiganalytics.nifi.rest.client.LegacyNifiRestClient;
import com.thinkbiganalytics.nifi.rest.model.NifiError;
import com.thinkbiganalytics.security.AccessController;
import org.apache.nifi.web.api.dto.TemplateDTO;
import org.slf4j.Logger;
import org.xml.sax.SAXException;
import java.io.IOException;
import javax.inject.Inject;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
/**
* Created by sr186054 on 12/11/17.
*/
public abstract class AbstractValidateImportTemplate {
@Inject
protected AccessController accessController;
@Inject
protected UploadProgressService uploadProgressService;
@Inject
protected LegacyNifiRestClient nifiRestClient;
protected ImportTemplate importTemplate;
protected ImportTemplateOptions importTemplateOptions;
protected String fileName;
protected byte[] file;
public AbstractValidateImportTemplate(ImportTemplate importTemplate, ImportTemplateOptions importTemplateOptions){
this.importTemplate = importTemplate;
this.importTemplateOptions = importTemplateOptions;
}
public abstract boolean validate();
public abstract Logger getLogger();
/**
* Validate the NiFi template is valid. This method will validate the template can be created/overwritten based upon the user supplied properties
*
*/
public void validateNiFiTemplateImport() {
//ImportOptions options = template.getImportOptions();
ImportComponentOption nifiTemplateOption = this.importTemplateOptions.findImportComponentOption(ImportComponent.NIFI_TEMPLATE);
//if the options of the TEMPLATE_DATA are marked to import and overwrite this should be as well
ImportComponentOption templateData = this.importTemplateOptions.findImportComponentOption(ImportComponent.TEMPLATE_DATA);
if (templateData.isUserAcknowledged()) {
nifiTemplateOption.setUserAcknowledged(true);
}
if (templateData.isShouldImport()) {
nifiTemplateOption.setShouldImport(true);
}
if (templateData.isOverwrite()) {
nifiTemplateOption.setOverwrite(true);
}
if (nifiTemplateOption.isShouldImport()) {
UploadProgressMessage statusMessage = uploadProgressService.addUploadStatus(importTemplateOptions.getUploadKey(), "Validating the NiFi template");
String templateName = null;
TemplateDTO dto = null;
try {
templateName = NifiTemplateParser.getTemplateName(this.importTemplate.getNifiTemplateXml());
this.importTemplate.setTemplateName(templateName);
dto = nifiRestClient.getNiFiRestClient().templates().findByName(templateName).orElse(null);
if (dto != null) {
this.importTemplate.setNifiTemplateId(dto.getId());
//if the template incoming is an XML template and it already exists, or if its a zip file and it exists and the user has not acknowledge to overwrite then error out
if ((!this.importTemplateOptions.isUserAcknowledged(ImportComponent.NIFI_TEMPLATE) || this.importTemplateOptions.isUserAcknowledged(ImportComponent.NIFI_TEMPLATE) && !this.importTemplate.isZipFile()) && !this.importTemplateOptions
.isImportAndOverwrite(ImportComponent.NIFI_TEMPLATE) && !this.importTemplateOptions
.isContinueIfExists(ImportComponent.NIFI_TEMPLATE)) {
this.importTemplate.setValid(false);
String msg = "Unable to import Template " + templateName
+ ". It already exists in NiFi.";
this.importTemplate.getImportOptions().addErrorMessage(ImportComponent.NIFI_TEMPLATE, msg);
statusMessage.update("Validation Error: Unable to import Template " + templateName + ". It already exists in NiFi.");
statusMessage.complete(false);
} else {
statusMessage.update("Validated the NiFi template. ");
statusMessage.complete(true);
}
} else {
statusMessage.update("Validated the NiFi template. The template " + templateName + " will be created in NiFi");
statusMessage.complete(true);
}
} catch (ParserConfigurationException | XPathExpressionException | IOException | SAXException e) {
getLogger().error("Error validating the file {} for import ",fileName,e);
this.importTemplate.setValid(false);
this.importTemplate.getTemplateResults().addError(NifiError.SEVERITY.WARN, "The xml file you are trying to import is not a valid NiFi template. Please try again. " + e.getMessage(), "");
statusMessage.complete(false);
}
nifiTemplateOption.setValidForImport(!nifiTemplateOption.hasErrorMessages());
}
uploadProgressService.completeSection(importTemplateOptions, ImportSection.Section.VALIDATE_NIFI_TEMPLATE);
}
}
| 2,382 |
777 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/app_list/presenter/app_list_presenter_delegate.h"
#include "ui/app_list/views/app_list_view.h"
namespace app_list {
namespace {
// The minimal margin (in pixels) around the app list when in centered mode.
const int kMinimalCenteredAppListMargin = 10;
} // namespace
int AppListPresenterDelegate::GetMinimumBoundsHeightForAppList(
const app_list::AppListView* app_list) {
return app_list->bounds().height() + 2 * kMinimalCenteredAppListMargin;
}
} // namespace app_list
| 213 |
1,244 | <filename>system/lib/libc/musl/src/locale/towctrans_l.c
#include <wctype.h>
wint_t towctrans_l(wint_t c, wctrans_t t, locale_t l)
{
return towctrans(c, t);
}
| 82 |
411 | <gh_stars>100-1000
# License: BSD 3 clause
from tick.dataset import fetch_tick_dataset
def fetch_hawkes_bund_data():
"""Load Hawkes formatted bund data from
https://github.com/X-DataInitiative/tick-datasets/tree/master/hawkes/bund
This data is meant to be fitted with Hawkes processes. It contains for each
day 4 time series representing:
1. Mid-price movement up
2. Mid-price movement down
3. Buyer initiated trades that do not move the mid-price
4. Seller initiated trades that do not move the mid-price
Returns
-------
output : `list` of `list` of `np.ndarray`, dim=(20, 4, _)
List of 20 days of 4 timestamps data.
"""
dataset = 'hawkes/bund/bund.npz'
return [list(timestamps) for _, timestamps in fetch_tick_dataset(dataset)]
| 305 |
335 | {
"word": "Kindergarten",
"definitions": [
"(in Britain and Australia) an establishment where children below the age of compulsory education play and learn; a nursery school.",
"(in North America) a class or school that prepares children, usually five- or six-year-olds, for the first year of formal education."
],
"parts-of-speech": "Noun"
} | 116 |
336 | from django import forms
from .widgets import AssetImageWidget
class AssetImageField(forms.fields.Field):
widget = AssetImageWidget
| 38 |
1,338 | <reponame>Kirishikesan/haiku<filename>headers/libs/linprog/Summand.h
/*
* Copyright 2007-2008, <NAME>, <EMAIL>
* Copyright 2007-2008, <NAME>, <EMAIL>
* Distributed under the terms of the MIT License.
*/
#ifndef SUMMAND_H
#define SUMMAND_H
#include <ObjectList.h>
namespace LinearProgramming {
class LinearSpec;
class Variable;
/**
* A summand of a linear term.
*/
class Summand {
public:
Summand(Summand* summand);
Summand(double coeff, Variable* var);
~Summand();
double Coeff();
void SetCoeff(double coeff);
Variable* Var();
void SetVar(Variable* var);
int32 VariableIndex();
private:
double fCoeff;
Variable* fVar;
};
typedef BObjectList<Summand> SummandList;
} // namespace LinearProgramming
using LinearProgramming::Summand;
using LinearProgramming::SummandList;
#endif // OBJ_FUNCTION_SUMMAND_H
| 364 |
386 | <filename>core/src/main/java/com/qq/tars/server/core/AppContextManager.java
/**
* Tencent is pleased to support the open source community by making Tars available.
*
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.qq.tars.server.core;
public class AppContextManager {
private AppContext appContext;
private static final AppContextManager instance = new AppContextManager();
public static AppContextManager getInstance() {
return instance;
}
public void setAppContext(AppContext appContext) {
this.appContext = appContext;
}
public AppContext getAppContext() {
return appContext;
}
}
| 351 |
393 | <reponame>otherbeast/hackers-tool-kit<filename>htk-lite/commandlist/infoscan.py
#!/usr/local/bin/python
# coding: latin-1
#if you use this code give me credit @tuf_unkn0wn
#i do not give you permission to show / edit this script without my credit
#to ask questions or report a problem message me on instagram @tuf_unkn0wn
"""
██░ ██ ▄▄▄ ▄████▄ ██ ▄█▀▓█████ ▓█████▄
▓██░ ██▒▒████▄ ▒██▀ ▀█ ██▄█▒ ▓█ ▀ ▒██▀ ██▌
▒██▀▀██░▒██ ▀█▄ ▒▓█ ▄ ▓███▄░ ▒███ ░██ █▌
░▓█ ░██ ░██▄▄▄▄██ ▒▓▓▄ ▄██▒▓██ █▄ ▒▓█ ▄ ░▓█▄ ▌
░▓█▒░██▓ ▓█ ▓██▒▒ ▓███▀ ░▒██▒ █▄░▒████▒░▒████▓
▒ ▒░▒ ▒▒ ▓▒█ ░▒ ▒ ░▒ ▒▒ ▓▒ ▒░ ░ ▒▒▓ ▒
▒ ░▒░ ░ ▒ ▒▒ ░ ░ ▒ ░ ░▒ ▒░ ░ ░ ░ ░ ▒ ▒
░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░ ░ ░ ░ ░ ░
░ ░
"""
import os
import sys
import random
lred = '\033[91m'
lblue = '\033[94m'
lgreen = '\033[92m'
yellow = '\033[93m'
cyan = '\033[1;36m'
purple = '\033[95m'
red = '\033[31m'
green = '\033[32m'
blue = '\033[34m'
orange = '\033[33m'
colorlist = [red, blue, green, yellow, lblue, purple, cyan, lred, lgreen, orange]
randomcolor = random.choice(colorlist)
banner3list = [red, blue, green, purple]
def infoscan():
try:
target = raw_input("\033[1mTarget:\033[0m ")
port = raw_input("\033[1mPort:\033[0m ")
print "\033[93m! HTTP OR HTTPS !\033[0m\n"
ht = raw_input("[https/http]: ")
if ht == "http":
targetht = 'http://'
if ht == "https":
targetht = 'https://'
print "\033[31m-----\033[33m-----\033[93m-----\033[32m-----\033[1;36m-----\033[94m-----\033[95m-----\033[31m-----\033[33m-----\033[93m-----\033[32m-----\033[1;36m-----\033[94m-----\033[95m-----\033[0m\n"
os.system("curl {0}".format(target))
print "\n"
ip = socket.gethostbyname(target)
print G+"------------------------\033[0m"
print N+"\033[1mHost:\033[32m ", target
print N+"\033[1mIP:\033[32m ", ip
print G+"------------------------\033[0m"
os.system("curl -I {0}".format(target))
print "\n"
request = requests.get(targetht + target)
http = request.status_code
if http == 200:
print("\nServer: [\033[32monline\033[0m]")
else:
print("\nServer: [\033[31moffline\033[0m]")
exit()
print "\n"
whois = requests.get("https://api.hackertarget.com/whois/?q=" + target).content.decode("UTF-8")
print(whois)
print "\n"
os.system("curl https://api.hackertarget.com/dnslookup/?q={0}".format(target))
print "\n"
os.system("wafw00f {0}".format(target))
print "\n"
os.system("sslscan {0}".format(target))
print "\n"
os.system("curl https://api.hackertarget.com/geoip/?q={0}".format(target))
print "\n"
os.system("curl https://api.hackertarget.com/reverseiplookup/?q={0}".format(target))
print "\n"
os.system("curl https://api.hackertarget.com/hostsearch/?q={0}".format(target))
print "\n"
os.system("curl https://api.hackertarget.com/reversedns/?q={0}".format(target))
print "\n"
os.system("curl https://api.hackertarget.com/findshareddns/?q={0}".format(target))
print "\n"
def daf():
subdomainlist = ["ftp", "cpanel", "webmail", "localhost", "local", "mysql", "forum", "driect-connect", "blog",
"vb", "forums", "home", "direct", "forums", "mail", "access", "admin", "administrator",
"email", "downloads", "ssh", "owa", "bbs", "webmin", "paralel", "parallels", "www0", "www",
"www1", "www2", "www3", "www4", "www5", "shop", "api", "blogs", "test", "mx1", "cdn", "mysql",
"mail1", "secure", "server", "ns1", "ns2", "smtp", "vpn", "m", "mail2", "postal", "support",
"web", "dev"]
for sublist in subdomainlist:
try:
hosts = str(sublist) + "." + str(target)
showip = socket.gethostbyname(str(hosts))
print "\033[0m\033[32mHIT\033[0m:\033[1m " + str(showip) + ' | ' + str(hosts)
except:
print "\033[0mBypassing..."
daf()
print "\033[0m"
print "\n"
os.system("nmap -A {0}".format(target))
print "\n"
os.system("nmap --script dns-brute {0}".format(target))
print "\n"
a = 'dirb {0}{1}/'.format(targetht,target)
os.system(a)
print "\n"
os.system("nikto -h {0} -p {1}".format(target,port))
print "\n\033[31m-----\033[33m-----\033[93m-----\033[32m-----\033[1;36m-----\033[94m-----\033[95m-----\033[31m-----\033[33m-----\033[93m-----\033[32m-----\033[1;36m-----\033[94m-----\033[95m-----\033[0m"
except:
print "\033[91mError Something Went Wrong Maybe The Specified Target Is Not Available\033[0m"
infoscan()
| 2,352 |
931 | <reponame>dandycheung/DevUtils
package dev.base.multiselect;
/**
* detail: 多选编辑接口
* @param <R> 泛型
* @author Ttt
* <pre>
* 实现该接口, 对外支持快捷操作方法
* 内部通过 {@link IMultiSelectToList}、{@link IMultiSelectToMap} 实现多选操作功能
* </pre>
*/
public interface IMultiSelectEdit<R> {
// ==========
// = 编辑状态 =
// ==========
/**
* 是否编辑状态
* @return {@code true} yes, {@code false} no
*/
boolean isEditState();
/**
* 设置编辑状态
* @param isEdit {@code true} yes, {@code false} no
* @return {@link R}
*/
R setEditState(boolean isEdit);
/**
* 切换编辑状态
* @return {@link R}
*/
R toggleEditState();
// ==========
// = 选择操作 =
// ==========
/**
* 全选
* @return {@link R}
*/
R selectAll();
/**
* 清空全选 ( 非全选 )
* @return {@link R}
*/
R clearSelectAll();
/**
* 反选
* @return {@link R}
*/
R inverseSelect();
// ==========
// = 判断处理 =
// ==========
/**
* 判断是否全选
* @return {@code true} yes, {@code false} no
*/
boolean isSelectAll();
/**
* 判断是否存在选中的数据
* @return {@code true} yes, {@code false} no
*/
boolean isSelect();
/**
* 判断是否不存在选中的数据
* @return {@code true} yes, {@code false} no
*/
boolean isNotSelect();
// ========
// = 数量值 =
// ========
/**
* 获取选中的数据条数
* @return 选中的数据条数
*/
int getSelectSize();
/**
* 获取数据总数
* @return 数据总数
*/
int getDataCount();
} | 981 |
341 | <reponame>codenotes/mDNAResponder
/* -*- Mode: C; tab-width: 4 -*-
*
* Copyright (c) 2009 Apple Computer, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _StringServices_h
#define _StringServices_h
#include <atlbase.h>
#include <vector>
#include <string>
extern BOOL
BSTRToUTF8
(
BSTR inString,
std::string & outString
);
extern BOOL
UTF8ToBSTR
(
const char * inString,
CComBSTR & outString
);
extern BOOL
ByteArrayToVariant
(
const void * inArray,
size_t inArrayLen,
VARIANT * outVariant
);
extern BOOL
VariantToByteArray
(
VARIANT * inVariant,
std::vector< BYTE > & outArray
);
#endif | 435 |
3,861 | /** @file
The Miscellaneous Routines for WiFi Connection Manager.
Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "WifiConnectionMgrDxe.h"
/**
Empty function for event process function.
@param Event The Event need to be process
@param Context The context of the event.
**/
VOID
EFIAPI
WifiMgrInternalEmptyFunction (
IN EFI_EVENT Event,
IN VOID *Context
)
{
return;
}
/**
Convert the mac address into a hexadecimal encoded ":" seperated string.
@param[in] Mac The mac address.
@param[in] StrSize The size, in bytes, of the output buffer specified by Str.
@param[out] Str The storage to return the mac string.
**/
VOID
WifiMgrMacAddrToStr (
IN EFI_80211_MAC_ADDRESS *Mac,
IN UINT32 StrSize,
OUT CHAR16 *Str
)
{
if (Mac == NULL || Str == NULL) {
return;
}
UnicodeSPrint (
Str,
StrSize,
L"%02X:%02X:%02X:%02X:%02X:%02X",
Mac->Addr[0], Mac->Addr[1], Mac->Addr[2],
Mac->Addr[3], Mac->Addr[4], Mac->Addr[5]
);
}
/**
Read private key file to buffer.
@param[in] FileContext The file context of private key file.
@param[out] PrivateKeyDataAddr The buffer address to restore private key file, should be
freed by caller.
@param[out] PrivateKeyDataSize The size of read private key file.
@retval EFI_SUCCESS Successfully read the private key file.
@retval EFI_INVALID_PARAMETER One or more of the parameters is invalid.
**/
EFI_STATUS
WifiMgrReadFileToBuffer (
IN WIFI_MGR_FILE_CONTEXT *FileContext,
OUT VOID **DataAddr,
OUT UINTN *DataSize
)
{
EFI_STATUS Status;
if (FileContext != NULL && FileContext->FHandle != NULL) {
Status = ReadFileContent (
FileContext->FHandle,
DataAddr,
DataSize,
0
);
if (FileContext->FHandle != NULL) {
FileContext->FHandle->Close (FileContext->FHandle);
}
FileContext->FHandle = NULL;
return Status;
}
return EFI_INVALID_PARAMETER;
}
/**
Get the Nic data by the NicIndex.
@param[in] Private The pointer to the global private data structure.
@param[in] NicIndex The index indicates the position of wireless NIC.
@return Pointer to the Nic data, or NULL if not found.
**/
WIFI_MGR_DEVICE_DATA *
WifiMgrGetNicByIndex (
IN WIFI_MGR_PRIVATE_DATA *Private,
IN UINT32 NicIndex
)
{
LIST_ENTRY *Entry;
WIFI_MGR_DEVICE_DATA *Nic;
if (Private == NULL) {
return NULL;
}
NET_LIST_FOR_EACH (Entry, &Private->NicList) {
Nic = NET_LIST_USER_STRUCT_S (Entry, WIFI_MGR_DEVICE_DATA,
Link, WIFI_MGR_DEVICE_DATA_SIGNATURE);
if (Nic->NicIndex == NicIndex) {
return Nic;
}
}
return NULL;
}
/**
Find a network profile through its' SSId and securit type, and the SSId is an unicode string.
@param[in] SSId The target network's SSId.
@param[in] SecurityType The target network's security type.
@param[in] ProfileList The profile list on a Nic.
@return Pointer to a network profile, or NULL if not found.
**/
WIFI_MGR_NETWORK_PROFILE *
WifiMgrGetProfileByUnicodeSSId (
IN CHAR16 *SSId,
IN UINT8 SecurityType,
IN LIST_ENTRY *ProfileList
)
{
LIST_ENTRY *Entry;
WIFI_MGR_NETWORK_PROFILE *Profile;
if (SSId == NULL || ProfileList == NULL) {
return NULL;
}
NET_LIST_FOR_EACH (Entry, ProfileList) {
Profile = NET_LIST_USER_STRUCT_S (Entry, WIFI_MGR_NETWORK_PROFILE,
Link, WIFI_MGR_PROFILE_SIGNATURE);
if (StrCmp (SSId, Profile->SSId) == 0 && SecurityType == Profile->SecurityType) {
return Profile;
}
}
return NULL;
}
/**
Find a network profile through its' SSId and securit type, and the SSId is an ascii string.
@param[in] SSId The target network's SSId.
@param[in] SecurityType The target network's security type.
@param[in] ProfileList The profile list on a Nic.
@return Pointer to a network profile, or NULL if not found.
**/
WIFI_MGR_NETWORK_PROFILE *
WifiMgrGetProfileByAsciiSSId (
IN CHAR8 *SSId,
IN UINT8 SecurityType,
IN LIST_ENTRY *ProfileList
)
{
CHAR16 SSIdUniCode[SSID_STORAGE_SIZE];
if (SSId == NULL) {
return NULL;
}
if (AsciiStrToUnicodeStrS (SSId, SSIdUniCode, SSID_STORAGE_SIZE) != RETURN_SUCCESS) {
return NULL;
}
return WifiMgrGetProfileByUnicodeSSId (SSIdUniCode, SecurityType, ProfileList);
}
/**
Find a network profile through its' profile index.
@param[in] ProfileIndex The target network's profile index.
@param[in] ProfileList The profile list on a Nic.
@return Pointer to a network profile, or NULL if not found.
**/
WIFI_MGR_NETWORK_PROFILE *
WifiMgrGetProfileByProfileIndex (
IN UINT32 ProfileIndex,
IN LIST_ENTRY *ProfileList
)
{
WIFI_MGR_NETWORK_PROFILE *Profile;
LIST_ENTRY *Entry;
if (ProfileList == NULL) {
return NULL;
}
NET_LIST_FOR_EACH (Entry, ProfileList) {
Profile = NET_LIST_USER_STRUCT_S (Entry, WIFI_MGR_NETWORK_PROFILE,
Link, WIFI_MGR_PROFILE_SIGNATURE);
if (Profile->ProfileIndex == ProfileIndex) {
return Profile;
}
}
return NULL;
}
/**
To test if the AKMSuite is in supported AKMSuite list.
@param[in] SupportedAKMSuiteCount The count of the supported AKMSuites.
@param[in] SupportedAKMSuiteList The supported AKMSuite list.
@param[in] AKMSuite The AKMSuite to be tested.
@return True if this AKMSuite is supported, or False if not.
**/
BOOLEAN
WifiMgrSupportAKMSuite (
IN UINT16 SupportedAKMSuiteCount,
IN UINT32 *SupportedAKMSuiteList,
IN UINT32 *AKMSuite
)
{
UINT16 Index;
if (AKMSuite == NULL || SupportedAKMSuiteList == NULL ||
SupportedAKMSuiteCount == 0) {
return FALSE;
}
for (Index = 0; Index < SupportedAKMSuiteCount; Index ++) {
if (SupportedAKMSuiteList[Index] == *AKMSuite) {
return TRUE;
}
}
return FALSE;
}
/**
To check if the CipherSuite is in supported CipherSuite list.
@param[in] SupportedCipherSuiteCount The count of the supported CipherSuites.
@param[in] SupportedCipherSuiteList The supported CipherSuite list.
@param[in] CipherSuite The CipherSuite to be tested.
@return True if this CipherSuite is supported, or False if not.
**/
BOOLEAN
WifiMgrSupportCipherSuite (
IN UINT16 SupportedCipherSuiteCount,
IN UINT32 *SupportedCipherSuiteList,
IN UINT32 *CipherSuite
)
{
UINT16 Index;
if (CipherSuite == NULL || SupportedCipherSuiteCount == 0 ||
SupportedCipherSuiteList == NULL) {
return FALSE;
}
for (Index = 0; Index < SupportedCipherSuiteCount; Index ++) {
if (SupportedCipherSuiteList[Index] == *CipherSuite) {
return TRUE;
}
}
return FALSE;
}
/**
Check an AKM suite list and a Cipher suite list to see if one or more AKM suites or Cipher suites
are supported and find the matchable security type.
@param[in] AKMList The target AKM suite list to be checked.
@param[in] CipherList The target Cipher suite list to be checked
@param[in] Nic The Nic to operate, contains the supported AKMSuite list
and supported CipherSuite list
@param[out] SecurityType To identify a security type from the AKM suite list and
Cipher suite list
@param[out] AKMSuiteSupported To identify if this security type is supported. If it is
NULL, overcome this field
@param[out] CipherSuiteSupported To identify if this security type is supported. If it is
NULL, overcome this field
@retval EFI_SUCCESS This operation has completed successfully.
@retval EFI_INVALID_PARAMETER No Nic found or the suite list is null.
**/
EFI_STATUS
WifiMgrCheckRSN (
IN EFI_80211_AKM_SUITE_SELECTOR *AKMList,
IN EFI_80211_CIPHER_SUITE_SELECTOR *CipherList,
IN WIFI_MGR_DEVICE_DATA *Nic,
OUT UINT8 *SecurityType,
OUT BOOLEAN *AKMSuiteSupported,
OUT BOOLEAN *CipherSuiteSupported
)
{
EFI_80211_AKM_SUITE_SELECTOR *SupportedAKMSuites;
EFI_80211_CIPHER_SUITE_SELECTOR *SupportedSwCipherSuites;
EFI_80211_CIPHER_SUITE_SELECTOR *SupportedHwCipherSuites;
EFI_80211_SUITE_SELECTOR *AKMSuite;
EFI_80211_SUITE_SELECTOR *CipherSuite;
UINT16 AKMIndex;
UINT16 CipherIndex;
if (Nic == NULL || AKMList == NULL || CipherList == NULL|| SecurityType == NULL) {
return EFI_INVALID_PARAMETER;
}
SupportedAKMSuites = Nic->SupportedSuites.SupportedAKMSuites;
SupportedSwCipherSuites = Nic->SupportedSuites.SupportedSwCipherSuites;
SupportedHwCipherSuites = Nic->SupportedSuites.SupportedHwCipherSuites;
*SecurityType = SECURITY_TYPE_UNKNOWN;
if (AKMSuiteSupported != NULL && CipherSuiteSupported != NULL) {
*AKMSuiteSupported = FALSE;
*CipherSuiteSupported = FALSE;
}
if (AKMList->AKMSuiteCount == 0) {
if (CipherList->CipherSuiteCount == 0) {
*SecurityType = SECURITY_TYPE_NONE;
if (AKMSuiteSupported != NULL && CipherSuiteSupported != NULL) {
*AKMSuiteSupported = TRUE;
*CipherSuiteSupported = TRUE;
}
}
return EFI_SUCCESS;
}
for (AKMIndex = 0; AKMIndex < AKMList->AKMSuiteCount; AKMIndex ++) {
AKMSuite = AKMList->AKMSuiteList + AKMIndex;
if (WifiMgrSupportAKMSuite(SupportedAKMSuites->AKMSuiteCount,
(UINT32*) SupportedAKMSuites->AKMSuiteList, (UINT32*) AKMSuite)) {
if (AKMSuiteSupported != NULL && CipherSuiteSupported != NULL) {
*AKMSuiteSupported = TRUE;
}
for (CipherIndex = 0; CipherIndex < CipherList->CipherSuiteCount; CipherIndex ++) {
CipherSuite = CipherList->CipherSuiteList + CipherIndex;
if (SupportedSwCipherSuites != NULL) {
if (WifiMgrSupportCipherSuite(SupportedSwCipherSuites->CipherSuiteCount,
(UINT32*) SupportedSwCipherSuites->CipherSuiteList, (UINT32*) CipherSuite)) {
*SecurityType = WifiMgrGetSecurityType ((UINT32*) AKMSuite, (UINT32*) CipherSuite);
if (*SecurityType != SECURITY_TYPE_UNKNOWN) {
if (AKMSuiteSupported != NULL && CipherSuiteSupported != NULL) {
*CipherSuiteSupported = TRUE;
}
return EFI_SUCCESS;
}
}
}
if (SupportedHwCipherSuites != NULL) {
if (WifiMgrSupportCipherSuite(SupportedHwCipherSuites->CipherSuiteCount,
(UINT32*) SupportedHwCipherSuites->CipherSuiteList, (UINT32*) CipherSuite)) {
*SecurityType = WifiMgrGetSecurityType ((UINT32*) AKMSuite, (UINT32*) CipherSuite);
if (*SecurityType != SECURITY_TYPE_UNKNOWN) {
if (AKMSuiteSupported != NULL && CipherSuiteSupported != NULL) {
*CipherSuiteSupported = TRUE;
}
return EFI_SUCCESS;
}
}
}
}
}
}
*SecurityType = WifiMgrGetSecurityType ((UINT32*) AKMList->AKMSuiteList,
(UINT32*) CipherList->CipherSuiteList);
return EFI_SUCCESS;
}
/**
Get the security type for a certain AKMSuite and CipherSuite.
@param[in] AKMSuite An certain AKMSuite.
@param[in] CipherSuite An certain CipherSuite.
@return a security type if found, or SECURITY_TYPE_UNKNOWN.
**/
UINT8
WifiMgrGetSecurityType (
IN UINT32 *AKMSuite,
IN UINT32 *CipherSuite
)
{
if (CipherSuite == NULL) {
if (AKMSuite == NULL) {
return SECURITY_TYPE_NONE;
} else {
return SECURITY_TYPE_UNKNOWN;
}
} else if (*CipherSuite == IEEE_80211_PAIRWISE_CIPHER_SUITE_USE_GROUP) {
if (AKMSuite == NULL) {
return SECURITY_TYPE_NONE;
} else {
return SECURITY_TYPE_UNKNOWN;
}
} else if (*CipherSuite == IEEE_80211_PAIRWISE_CIPHER_SUITE_WEP40 ||
*CipherSuite == IEEE_80211_PAIRWISE_CIPHER_SUITE_WEP104) {
return SECURITY_TYPE_WEP;
} else if (*CipherSuite == IEEE_80211_PAIRWISE_CIPHER_SUITE_CCMP) {
if (AKMSuite == NULL) {
return SECURITY_TYPE_UNKNOWN;
}
if (*AKMSuite == IEEE_80211_AKM_SUITE_8021X_OR_PMKSA ||
*AKMSuite == IEEE_80211_AKM_SUITE_8021X_OR_PMKSA_SHA256) {
return SECURITY_TYPE_WPA2_ENTERPRISE;
} else if (*AKMSuite == IEEE_80211_AKM_SUITE_PSK ||
*AKMSuite == IEEE_80211_AKM_SUITE_PSK_SHA256){
return SECURITY_TYPE_WPA2_PERSONAL;
}else {
return SECURITY_TYPE_UNKNOWN;
}
} else if (*CipherSuite == IEEE_80211_PAIRWISE_CIPHER_SUITE_TKIP) {
if (AKMSuite == NULL) {
return SECURITY_TYPE_UNKNOWN;
}
if (*AKMSuite == IEEE_80211_AKM_SUITE_8021X_OR_PMKSA ||
*AKMSuite == IEEE_80211_AKM_SUITE_8021X_OR_PMKSA_SHA256) {
return SECURITY_TYPE_WPA_ENTERPRISE;
} else if (*AKMSuite == IEEE_80211_AKM_SUITE_PSK ||
*AKMSuite == IEEE_80211_AKM_SUITE_PSK_SHA256){
return SECURITY_TYPE_WPA_PERSONAL;
}else {
return SECURITY_TYPE_UNKNOWN;
}
} else {
return SECURITY_TYPE_UNKNOWN;
}
}
/**
Get supported AKMSuites and CipherSuites from supplicant for a Nic.
@param[in] Nic The Nic to operate.
@retval EFI_SUCCESS Get the supported suite list successfully.
@retval EFI_INVALID_PARAMETER No Nic found or supplicant is NULL.
**/
EFI_STATUS
WifiMgrGetSupportedSuites (
IN WIFI_MGR_DEVICE_DATA *Nic
)
{
EFI_STATUS Status;
EFI_SUPPLICANT_PROTOCOL *Supplicant;
EFI_80211_AKM_SUITE_SELECTOR *SupportedAKMSuites;
EFI_80211_CIPHER_SUITE_SELECTOR *SupportedSwCipherSuites;
EFI_80211_CIPHER_SUITE_SELECTOR *SupportedHwCipherSuites;
UINTN DataSize;
SupportedAKMSuites = NULL;
SupportedSwCipherSuites = NULL;
SupportedHwCipherSuites = NULL;
if (Nic == NULL || Nic->Supplicant == NULL) {
return EFI_INVALID_PARAMETER;
}
Supplicant = Nic->Supplicant;
DataSize = 0;
Status = Supplicant->GetData (Supplicant, EfiSupplicant80211SupportedAKMSuites, NULL, &DataSize);
if (Status == EFI_BUFFER_TOO_SMALL && DataSize > 0) {
SupportedAKMSuites = AllocateZeroPool(DataSize);
if (SupportedAKMSuites == NULL) {
return EFI_OUT_OF_RESOURCES;
}
Status = Supplicant->GetData (Supplicant, EfiSupplicant80211SupportedAKMSuites,
(UINT8 *) SupportedAKMSuites, &DataSize);
if (!EFI_ERROR (Status)) {
Nic->SupportedSuites.SupportedAKMSuites = SupportedAKMSuites;
} else {
FreePool (SupportedAKMSuites);
}
} else {
SupportedAKMSuites = NULL;
}
DataSize = 0;
Status = Supplicant->GetData (Supplicant, EfiSupplicant80211SupportedSoftwareCipherSuites, NULL, &DataSize);
if (Status == EFI_BUFFER_TOO_SMALL && DataSize > 0) {
SupportedSwCipherSuites = AllocateZeroPool(DataSize);
if (SupportedSwCipherSuites == NULL) {
return EFI_OUT_OF_RESOURCES;
}
Status = Supplicant->GetData (Supplicant, EfiSupplicant80211SupportedSoftwareCipherSuites,
(UINT8 *) SupportedSwCipherSuites, &DataSize);
if (!EFI_ERROR (Status)) {
Nic->SupportedSuites.SupportedSwCipherSuites = SupportedSwCipherSuites;
} else {
FreePool (SupportedSwCipherSuites);
}
} else {
SupportedSwCipherSuites = NULL;
}
DataSize = 0;
Status = Supplicant->GetData (Supplicant, EfiSupplicant80211SupportedHardwareCipherSuites, NULL, &DataSize);
if (Status == EFI_BUFFER_TOO_SMALL && DataSize > 0) {
SupportedHwCipherSuites = AllocateZeroPool(DataSize);
if (SupportedHwCipherSuites == NULL) {
return EFI_OUT_OF_RESOURCES;
}
Status = Supplicant->GetData (Supplicant, EfiSupplicant80211SupportedHardwareCipherSuites,
(UINT8 *) SupportedHwCipherSuites, &DataSize);
if (!EFI_ERROR (Status)) {
Nic->SupportedSuites.SupportedHwCipherSuites = SupportedHwCipherSuites;
} else {
FreePool (SupportedHwCipherSuites);
}
} else {
SupportedHwCipherSuites = NULL;
}
return EFI_SUCCESS;
}
/**
Clean secrets from a network profile.
@param[in] Profile The profile to be cleanned.
**/
VOID
WifiMgrCleanProfileSecrets (
IN WIFI_MGR_NETWORK_PROFILE *Profile
)
{
ZeroMem (Profile->Password, sizeof (CHAR16) * PASSWORD_STORAGE_SIZE);
ZeroMem (Profile->EapPassword, sizeof (CHAR16) * PASSWORD_STORAGE_SIZE);
ZeroMem (Profile->PrivateKeyPassword, sizeof (CHAR16) * PASSWORD_STORAGE_SIZE);
if (Profile->CACertData != NULL) {
ZeroMem (Profile->CACertData, Profile->CACertSize);
FreePool (Profile->CACertData);
}
Profile->CACertData = NULL;
Profile->CACertSize = 0;
if (Profile->ClientCertData != NULL) {
ZeroMem (Profile->ClientCertData, Profile->ClientCertSize);
FreePool (Profile->ClientCertData);
}
Profile->ClientCertData = NULL;
Profile->ClientCertSize = 0;
if (Profile->PrivateKeyData != NULL) {
ZeroMem (Profile->PrivateKeyData, Profile->PrivateKeyDataSize);
FreePool (Profile->PrivateKeyData);
}
Profile->PrivateKeyData = NULL;
Profile->PrivateKeyDataSize = 0;
}
/**
Free all network profiles in a profile list.
@param[in] ProfileList The profile list to be freed.
**/
VOID
WifiMgrFreeProfileList (
IN LIST_ENTRY *ProfileList
)
{
WIFI_MGR_NETWORK_PROFILE *Profile;
LIST_ENTRY *Entry;
LIST_ENTRY *NextEntry;
if (ProfileList == NULL) {
return;
}
NET_LIST_FOR_EACH_SAFE (Entry, NextEntry, ProfileList) {
Profile = NET_LIST_USER_STRUCT_S (Entry, WIFI_MGR_NETWORK_PROFILE,
Link, WIFI_MGR_PROFILE_SIGNATURE);
WifiMgrCleanProfileSecrets (Profile);
if (Profile->Network.AKMSuite != NULL) {
FreePool(Profile->Network.AKMSuite);
}
if (Profile->Network.CipherSuite != NULL) {
FreePool(Profile->Network.CipherSuite);
}
FreePool (Profile);
}
}
/**
Free user configured hidden network list.
@param[in] HiddenList The hidden network list to be freed.
**/
VOID
WifiMgrFreeHiddenList (
IN LIST_ENTRY *HiddenList
)
{
WIFI_HIDDEN_NETWORK_DATA *HiddenNetwork;
LIST_ENTRY *Entry;
LIST_ENTRY *NextEntry;
if (HiddenList == NULL) {
return;
}
NET_LIST_FOR_EACH_SAFE (Entry, NextEntry, HiddenList) {
HiddenNetwork = NET_LIST_USER_STRUCT_S (Entry, WIFI_HIDDEN_NETWORK_DATA,
Link, WIFI_MGR_HIDDEN_NETWORK_SIGNATURE);
FreePool (HiddenNetwork);
}
}
/**
Free the resources of a config token.
@param[in] ConfigToken The config token to be freed.
**/
VOID
WifiMgrFreeToken (
IN WIFI_MGR_MAC_CONFIG_TOKEN *ConfigToken
)
{
EFI_80211_GET_NETWORKS_RESULT *Result;
if (ConfigToken == NULL) {
return;
}
switch (ConfigToken->Type) {
case TokenTypeGetNetworksToken:
if (ConfigToken->Token.GetNetworksToken != NULL) {
gBS->CloseEvent (ConfigToken->Token.GetNetworksToken->Event);
if (ConfigToken->Token.GetNetworksToken->Data != NULL) {
FreePool(ConfigToken->Token.GetNetworksToken->Data);
}
Result = ConfigToken->Token.GetNetworksToken->Result;
if (Result != NULL) {
FreePool (Result);
}
FreePool(ConfigToken->Token.GetNetworksToken);
}
FreePool (ConfigToken);
break;
case TokenTypeConnectNetworkToken:
if (ConfigToken->Token.ConnectNetworkToken != NULL) {
gBS->CloseEvent (ConfigToken->Token.ConnectNetworkToken->Event);
if (ConfigToken->Token.ConnectNetworkToken->Data != NULL) {
FreePool(ConfigToken->Token.ConnectNetworkToken->Data);
}
FreePool(ConfigToken->Token.ConnectNetworkToken);
}
FreePool (ConfigToken);
break;
case TokenTypeDisconnectNetworkToken:
if (ConfigToken->Token.DisconnectNetworkToken != NULL) {
FreePool(ConfigToken->Token.DisconnectNetworkToken);
}
FreePool (ConfigToken);
break;
default :
break;
}
}
| 10,580 |
3,428 | <reponame>ghalimi/stdlib
{"id":"01589","group":"easy-ham-1","checksum":{"type":"MD5","value":"be65e620bca0f1734cd13c71aea78d4c"},"text":"From <EMAIL> Tue Sep 17 11:26:28 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>.spamassassin.taint.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 5ED2216F03\n\tfor <jm@localhost>; Tue, 17 Sep 2002 11:26:27 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Tue, 17 Sep 2002 11:26:27 +0100 (IST)\nReceived: from usw-sf-list2.sourceforge.net (usw-sf-fw2.sourceforge.net\n [172.16.58.3]) by dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id\n g8GIrhC05769 for <<EMAIL>>; Mon, 16 Sep 2002 19:53:43 +0100\nReceived: from usw-sf-list1-b.sourceforge.net ([10.3.1.13]\n helo=usw-sf-list1.sourceforge.net) by usw-sf-list2.sourceforge.net with\n esmtp (Exim 3.31-VA-mm2 #1 (Debian)) id 17r0ui-0004wE-00; Mon,\n 16 Sep 2002 11:48:04 -0700\nReceived: from h-66-166-21-186.snvacaid.covad.net ([66.166.21.186]\n helo=rover.vipul.net) by usw-sf-list1.sourceforge.net with esmtp (Exim\n 3.31-VA-mm2 #1 (Debian)) id 17r0tl-0001Dr-00 for\n <<EMAIL>>; Mon, 16 Sep 2002 11:47:05 -0700\nReceived: (from vipul@localhost) by rover.vipul.net (8.11.6/8.11.6) id\n g8GIkfF12252; Mon, 16 Sep 2002 11:46:41 -0700\nFrom: <NAME> <<EMAIL>>\nTo: <NAME> <<EMAIL>>\nCc: <EMAIL>.net\nSubject: Re: [Razor-users] empty mail is spamm?\nMessage-Id: <<EMAIL>>\nReply-To: [email protected]\nMail-Followup-To: <NAME> <<EMAIL>>,\n\tr<EMAIL>.sourceforge.net\nReferences: <1032182191.9<EMAIL>>\nMIME-Version: 1.0\nContent-Type: text/plain; charset=us-ascii\nContent-Disposition: inline\nUser-Agent: Mutt/1.2.5i\nIn-Reply-To: <<EMAIL>>;\n from <EMAIL> on Mon, Sep 16, 2002 at 04:16:31PM +0300\nX-Operating-System: Linux rover.vipul.net 2.4.18\nX-Privacy: If possible, encrypt your reply. Key at http://vipul.net/\nSender: <EMAIL>\nErrors-To: <EMAIL>\nX-Beenthere: <EMAIL>.net\nX-Mailman-Version: 2.0.9-sf.net\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <https://example.sourceforge.net/lists/listinfo/razor-users>,\n <mailto:<EMAIL>?subject=subscribe>\nList-Id: <razor-users.example.sourceforge.net>\nList-Unsubscribe: <https://example.sourceforge.net/lists/listinfo/razor-users>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://sourceforge.net/mailarchives/forum.php?forum=razor-users>\nX-Original-Date: Mon, 16 Sep 2002 11:46:41 -0700\nDate: Mon, 16 Sep 2002 11:46:41 -0700\n\nRazor won't filter empty emails. What version of the agents are you using?\n\ncheers,\nvipul.\n\nOn Mon, Sep 16, 2002 at 04:16:31PM +0300, <NAME> wrote:\n> Hi,\n> \n> Is it possible to use razor without filtering empty mails as spamm?\n> An mail with an attachment is considered spamm. Is this normal?\n> Or I mysqlf like to send emails to myself where all important is said in\n> subject and body is empty (for remaining smth).\n> \n> Thanks,\n> <NAME>\n> \n> \n> \n> \n> -------------------------------------------------------\n> This sf.net email is sponsored by:ThinkGeek\n> Welcome to geek heaven.\n> http://thinkgeek.com/sf\n> _______________________________________________\n> Razor-users mailing list\n> <EMAIL>\n> https://lists.sourceforge.net/lists/listinfo/razor-users\n\n-- \n\n<NAME> | \"The future is here, it's just not \nSoftware Design Artist | widely distributed.\"\nhttp://vipul.net/ | -- <NAME>\n\n\n\n-------------------------------------------------------\nThis sf.net email is sponsored by:ThinkGeek\nWelcome to geek heaven.\nhttp://thinkgeek.com/sf\n_______________________________________________\nRazor-users mailing list\n<EMAIL>\nhttps://lists.sourceforge.net/lists/listinfo/razor-users\n\n\n"} | 1,595 |
1,647 | <gh_stars>1000+
# from http://stackoverflow.com/questions/3939660/sieve-of-eratosthenes-finding-primes-python
# using a list instead of generator as return values
#pythran export primes_sieve(int)
#runas primes_sieve(100)
#bench primes_sieve(6000000)
def primes_sieve(limit):
a = [True] * limit # Initialize the primality list
a[0] = a[1] = False
primes=list()
for (i, isprime) in enumerate(a):
if isprime:
primes.append(i)
for n in range(i*i, limit, i): # Mark factors non-prime
a[n] = False
return primes
| 282 |
434 | //用于内部实现的循环锁
#pragma once
namespace resumef
{
#if defined(RESUMEF_USE_CUSTOM_SPINLOCK)
using spinlock = RESUMEF_USE_CUSTOM_SPINLOCK;
#else
/**
* @brief 一个自旋锁实现。
*/
struct spinlock
{
static const size_t MAX_ACTIVE_SPIN = 4000;
static const size_t MAX_YIELD_SPIN = 8000;
static const int FREE_VALUE = 0;
static const int LOCKED_VALUE = 1;
std::atomic<int> lck;
#if _DEBUG
std::thread::id owner_thread_id;
#endif
/**
* @brief 初始为未加锁。
*/
spinlock() noexcept
{
lck = FREE_VALUE;
}
/**
* @brief 获得锁。会一直阻塞线程直到获得锁。
*/
void lock() noexcept
{
int val = FREE_VALUE;
if (!lck.compare_exchange_weak(val, LOCKED_VALUE, std::memory_order_acq_rel))
{
#if _DEBUG
//诊断错误的用法:进行了递归锁调用
assert(owner_thread_id != std::this_thread::get_id());
#endif
size_t spinCount = 0;
auto dt = std::chrono::milliseconds{ 1 };
do
{
while (lck.load(std::memory_order_relaxed) != FREE_VALUE)
{
if (spinCount < MAX_ACTIVE_SPIN)
{
++spinCount;
}
else if (spinCount < MAX_YIELD_SPIN)
{
++spinCount;
std::this_thread::yield();
}
else
{
std::this_thread::sleep_for(dt);
dt = (std::min)(std::chrono::milliseconds{ 128 }, dt * 2);
}
}
val = FREE_VALUE;
} while (!lck.compare_exchange_weak(val, LOCKED_VALUE, std::memory_order_acq_rel));
}
#if _DEBUG
owner_thread_id = std::this_thread::get_id();
#endif
}
/**
* @brief 尝试获得锁一次。
*/
bool try_lock() noexcept
{
int val = FREE_VALUE;
bool ret = lck.compare_exchange_strong(val, LOCKED_VALUE, std::memory_order_acq_rel);
#if _DEBUG
if (ret) owner_thread_id = std::this_thread::get_id();
#endif
return ret;
}
/**
* @brief 释放锁。
*/
void unlock() noexcept
{
#if _DEBUG
owner_thread_id = std::thread::id();
#endif
lck.store(FREE_VALUE, std::memory_order_release);
}
};
#endif
#ifndef DOXYGEN_SKIP_PROPERTY
namespace detail
{
template<class _Ty, class _Cont = std::vector<_Ty>>
struct _LockVectorAssembleT
{
private:
_Cont& _Lks;
public:
_LockVectorAssembleT(_Cont& _LkN)
: _Lks(_LkN)
{}
size_t size() const
{
return _Lks.size();
}
_Ty& operator[](int _Idx)
{
return _Lks[_Idx];
}
void _Lock_ref(_Ty& _LkN) const
{
_LkN.lock();
}
bool _Try_lock_ref(_Ty& _LkN) const
{
return _LkN.try_lock();
}
void _Unlock_ref(_Ty& _LkN) const
{
_LkN.unlock();
}
void _Yield() const
{
std::this_thread::yield();
}
void _ReturnValue() const;
template<class U>
U _ReturnValue(U v) const;
};
template<class _Ty, class _Cont>
struct _LockVectorAssembleT<std::reference_wrapper<_Ty>, _Cont>
{
private:
_Cont& _Lks;
public:
_LockVectorAssembleT(_Cont& _LkN)
: _Lks(_LkN)
{}
size_t size() const
{
return _Lks.size();
}
std::reference_wrapper<_Ty> operator[](int _Idx)
{
return _Lks[_Idx];
}
void _Lock_ref(std::reference_wrapper<_Ty> _LkN) const
{
_LkN.get().lock();
}
void _Unlock_ref(std::reference_wrapper<_Ty> _LkN) const
{
_LkN.get().unlock();
}
bool _Try_lock_ref(std::reference_wrapper<_Ty> _LkN) const
{
return _LkN.get().try_lock();
}
void _Yield() const
{
std::this_thread::yield();
}
void _ReturnValue() const;
template<class U>
U _ReturnValue(U v) const;
};
#define LOCK_ASSEMBLE_NAME(fnName) scoped_lock_range_##fnName
#define LOCK_ASSEMBLE_AWAIT(a) (a)
#define LOCK_ASSEMBLE_RETURN(a) return (a)
#include "without_deadlock_assemble.inl"
#undef LOCK_ASSEMBLE_NAME
#undef LOCK_ASSEMBLE_AWAIT
#undef LOCK_ASSEMBLE_RETURN
}
#endif //DOXYGEN_SKIP_PROPERTY
/**
* @brief 无死锁的批量枷锁。
* @param _Ty 锁的类型。例如std::mutex,resumef::spinlock,resumef::mutex_t(线程用法)均可。
* @param _Cont 容纳一批锁的容器。
* @param _Assemble 与_Cont配套的锁集合,特化了如何操作_Ty。
*/
template<class _Ty, class _Cont = std::vector<_Ty>, class _Assemble = detail::_LockVectorAssembleT<_Ty, _Cont>>
class batch_lock_t
{
public:
/**
* @brief 通过锁容器构造,并立刻应用加锁算法。
*/
explicit batch_lock_t(_Cont& locks_)
: _LkN(&locks_)
, _LA(*_LkN)
{
detail::scoped_lock_range_lock_impl::_Lock_range(_LA);
}
/**
* @brief 通过锁容器和锁集合构造,并立刻应用加锁算法。
*/
explicit batch_lock_t(_Cont& locks_, _Assemble& la_)
: _LkN(&locks_)
, _LA(la_)
{
detail::scoped_lock_range_lock_impl::_Lock_range(_LA);
}
/**
* @brief 通过锁容器构造,容器里的锁已经全部获得。
*/
explicit batch_lock_t(std::adopt_lock_t, _Cont& locks_)
: _LkN(&locks_)
, _LA(*_LkN)
{ // construct but don't lock
}
/**
* @brief 通过锁容器和锁集合构造,容器里的锁已经全部获得。
*/
explicit batch_lock_t(std::adopt_lock_t, _Cont& locks_, _Assemble& la_)
: _LkN(&locks_)
, _LA(la_)
{ // construct but don't lock
}
/**
* @brief 析构函数里,释放容器里的锁。
*/
~batch_lock_t() noexcept
{
if (_LkN != nullptr)
detail::scoped_lock_range_lock_impl::_Unlock_locks(0, (int)_LA.size(), _LA);
}
/**
* @brief 手工释放容器里的锁,析构函数里将不再有释放操作。
*/
void unlock()
{
if (_LkN != nullptr)
{
_LkN = nullptr;
detail::scoped_lock_range_lock_impl::_Unlock_locks(0, (int)_LA.size(), _LA);
}
}
/**
* @brief 不支持拷贝构造。
*/
batch_lock_t(const batch_lock_t&) = delete;
/**
* @brief 不支持拷贝赋值。
*/
batch_lock_t& operator=(const batch_lock_t&) = delete;
/**
* @brief 支持移动构造。
*/
batch_lock_t(batch_lock_t&& _Right)
: _LkN(_Right._LkN)
, _LA(std::move(_Right._LA))
{
_Right._LkN = nullptr;
}
/**
* @brief 支持移动赋值。
*/
batch_lock_t& operator=(batch_lock_t&& _Right)
{
if (this != &_Right)
{
_LkN = _Right._LkN;
_Right._LkN = nullptr;
_LA = std::move(_Right._LA);
}
}
private:
_Cont* _LkN;
_Assemble _LA;
};
}
| 3,731 |
314 | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "CDStructures.h"
@interface DVTSharedLayerDelegate : NSObject
{
}
+ (id)sharedInstance;
- (BOOL)layer:(id)arg1 shouldInheritContentsScale:(double)arg2 fromWindow:(id)arg3;
@end
| 127 |
1,068 | <filename>app/src/main/java/com/forezp/banya/utils/DisplayImgUtis.java
package com.forezp.banya.utils;
import android.content.Context;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
/**
*
* Created by forezp on 16/8/10.
*/
public class DisplayImgUtis {
private static DisplayImgUtis instance;
private DisplayImgUtis(){}
public static DisplayImgUtis getInstance(){
if(instance==null){
instance =new DisplayImgUtis();
}
return instance;
}
public void display(Context context,String url,ImageView imageView){
Glide.with(context).load(url).into(imageView);
}
}
| 259 |
678 | /**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/Weather.framework/Weather
*/
#import <Weather/WeatherUpdater.h>
@class City;
@interface LocationUpdater : WeatherUpdater {
BOOL _isGeoCoding; // 28 = 0x1c
City *currentCity; // 32 = 0x20
}
@property(retain, nonatomic) City *currentCity; // G=0xac95; S=0xad39; @synthesize
+ (id)sharedLocationUpdater; // 0xacf1
- (void)dealloc; // 0xb1a5
- (void)parsedResultCity:(id)city; // 0xb13d
- (void)updateWeatherForLocation:(id)location city:(id)city; // 0xaf9d
- (BOOL)isDataValid:(id)valid; // 0xae65
- (void)failCity:(id)city; // 0xaca5
- (void)_failed:(int)failed; // 0xad61
// declared property getter: - (id)currentCity; // 0xac95
// declared property setter: - (void)setCurrentCity:(id)city; // 0xad39
@end
| 329 |
2,151 | /*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.typography.font.sfntly.table.bitmap;
import com.google.typography.font.sfntly.data.FontData;
import com.google.typography.font.sfntly.data.ReadableFontData;
import com.google.typography.font.sfntly.data.WritableFontData;
import com.google.typography.font.sfntly.math.FontMath;
import com.google.typography.font.sfntly.table.Header;
import com.google.typography.font.sfntly.table.SubTableContainerTable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @author <NAME>
*
*/
public class EblcTable extends SubTableContainerTable {
private static final boolean DEBUG = false;
public static final int NOTDEF = -1;
static enum Offset {
// header
version(0),
numSizes(4),
headerLength(numSizes.offset + FontData.DataSize.ULONG.size()),
// bitmapSizeTable
bitmapSizeTableArrayStart(headerLength.offset),
bitmapSizeTableLength(48),
bitmapSizeTable_indexSubTableArrayOffset(0),
bitmapSizeTable_indexTableSize(4),
bitmapSizeTable_numberOfIndexSubTables(8),
bitmapSizeTable_colorRef(12),
bitmapSizeTable_hori(16),
bitmapSizeTable_vert(28),
bitmapSizeTable_startGlyphIndex(40),
bitmapSizeTable_endGlyphIndex(42),
bitmapSizeTable_ppemX(44),
bitmapSizeTable_ppemY(45),
bitmapSizeTable_bitDepth(46),
bitmapSizeTable_flags(47),
// sbitLineMetrics
sbitLineMetricsLength(12),
sbitLineMetrics_ascender(0),
sbitLineMetrics_descender(1),
sbitLineMetrics_widthMax(2),
sbitLineMetrics_caretSlopeNumerator(3),
sbitLineMetrics__caretSlopeDenominator(4),
sbitLineMetrics_caretOffset(5),
sbitLineMetrics_minOriginSB(6),
sbitLineMetrics_minAdvanceSB(7),
sbitLineMetrics_maxBeforeBL(8),
sbitLineMetrics_minAfterBL(9),
sbitLineMetrics_pad1(10),
sbitLineMetrics_pad2(11),
// indexSubTable
indexSubTableEntryLength(8),
indexSubTableEntry_firstGlyphIndex(0),
indexSubTableEntry_lastGlyphIndex(2),
indexSubTableEntry_additionalOffsetToIndexSubtable(4),
// indexSubHeader
indexSubHeaderLength(8),
indexSubHeader_indexFormat(0),
indexSubHeader_imageFormat(2),
indexSubHeader_imageDataOffset(4),
// indexSubTable - all offset relative to the subtable start
// indexSubTable1
indexSubTable1_offsetArray(indexSubHeaderLength.offset),
indexSubTable1_builderDataSize(indexSubHeaderLength.offset),
// indexSubTable2
indexSubTable2Length(indexSubHeaderLength.offset + FontData.DataSize.ULONG.size()
+ BitmapGlyph.Offset.bigGlyphMetricsLength.offset),
indexSubTable2_imageSize(indexSubHeaderLength.offset),
indexSubTable2_bigGlyphMetrics(indexSubTable2_imageSize.offset + FontData.DataSize.ULONG.size()),
indexSubTable2_builderDataSize(indexSubTable2_bigGlyphMetrics.offset
+ BigGlyphMetrics.Offset.metricsLength.offset),
// indexSubTable3
indexSubTable3_offsetArray(indexSubHeaderLength.offset),
indexSubTable3_builderDataSize(indexSubTable3_offsetArray.offset),
// indexSubTable4
indexSubTable4_numGlyphs(indexSubHeaderLength.offset),
indexSubTable4_glyphArray(indexSubTable4_numGlyphs.offset + FontData.DataSize.ULONG.size()),
indexSubTable4_codeOffsetPairLength(2 * FontData.DataSize.USHORT.size()),
indexSubTable4_codeOffsetPair_glyphCode(0),
indexSubTable4_codeOffsetPair_offset(FontData.DataSize.USHORT.size()),
indexSubTable4_builderDataSize(indexSubTable4_glyphArray.offset),
// indexSubTable5
indexSubTable5_imageSize(indexSubHeaderLength.offset),
indexSubTable5_bigGlyphMetrics(indexSubTable5_imageSize.offset + FontData.DataSize.ULONG.size()),
indexSubTable5_numGlyphs(indexSubTable5_bigGlyphMetrics.offset
+ BitmapGlyph.Offset.bigGlyphMetricsLength.offset),
indexSubTable5_glyphArray(indexSubTable5_numGlyphs.offset + FontData.DataSize.ULONG.size()),
indexSubTable5_builderDataSize(indexSubTable5_glyphArray.offset),
// codeOffsetPair
codeOffsetPairLength(2 * FontData.DataSize.USHORT.size()),
codeOffsetPair_glyphCode(0),
codeOffsetPair_offset(FontData.DataSize.USHORT.size());
final int offset;
private Offset(int offset) {
this.offset = offset;
}
}
/**
* Lock on all operations that will affect the value of the bitmapSizeTable.
*/
private final Object bitmapSizeTableLock = new Object();
private volatile List<BitmapSizeTable> bitmapSizeTable;
/**
* @param header
* @param data
*/
protected EblcTable(Header header, ReadableFontData data) {
super(header, data);
}
public int version() {
return this.data.readFixed(Offset.version.offset);
}
public int numSizes() {
return this.data.readULongAsInt(Offset.numSizes.offset);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(super.toString());
sb.append("\nnum sizes = ");
sb.append(this.numSizes());
sb.append("\n");
for (int i = 0; i < this.numSizes(); i++) {
sb.append(i);
sb.append(": ");
BitmapSizeTable size = this.bitmapSizeTable(i);
sb.append(size.toString());
}
return sb.toString();
}
public BitmapSizeTable bitmapSizeTable(int index) {
if (index < 0 || index > this.numSizes()) {
throw new IndexOutOfBoundsException("Size table index is outside of the range of tables.");
}
List<BitmapSizeTable> bitmapSizeTableList = getBitmapSizeTableList();
return bitmapSizeTableList.get(index);
}
private List<BitmapSizeTable> getBitmapSizeTableList() {
if (this.bitmapSizeTable == null) {
synchronized (this.bitmapSizeTableLock) {
if (this.bitmapSizeTable == null) {
this.bitmapSizeTable = createBitmapSizeTable(this.data, this.numSizes());
}
}
}
return this.bitmapSizeTable;
}
private static List<BitmapSizeTable> createBitmapSizeTable(ReadableFontData data, int numSizes) {
List<BitmapSizeTable> bitmapSizeTable = new ArrayList<BitmapSizeTable>();
for (int i = 0; i < numSizes; i++) {
BitmapSizeTable.Builder sizeBuilder =
BitmapSizeTable.Builder.createBuilder(data.slice(
Offset.bitmapSizeTableArrayStart.offset + i * Offset.bitmapSizeTableLength.offset,
Offset.bitmapSizeTableLength.offset), data);
BitmapSizeTable size = sizeBuilder.build();
bitmapSizeTable.add(size);
}
return Collections.unmodifiableList(bitmapSizeTable);
}
public static final class Builder extends SubTableContainerTable.Builder<EblcTable> {
private final int version = 0x00020000; // TODO(user) constant/enum
private List<BitmapSizeTable.Builder> sizeTableBuilders;
/**
* Create a new builder using the header information and data provided.
*
* @param header the header information
* @param data the data holding the table
* @return a new builder
*/
public static Builder createBuilder(Header header, WritableFontData data) {
return new Builder(header, data);
}
/**
* Create a new builder using the header information and data provided.
*
* @param header the header information
* @param data the data holding the table
* @return a new builder
*/
public static Builder createBuilder(Header header, ReadableFontData data) {
return new Builder(header, data);
}
protected Builder(Header header, WritableFontData data) {
super(header, data);
}
protected Builder(Header header, ReadableFontData data) {
super(header, data);
}
public List<BitmapSizeTable.Builder> bitmapSizeBuilders() {
return this.getSizeList();
}
protected void revert() {
this.sizeTableBuilders = null;
this.setModelChanged(false);
}
/**
* Generates the loca list for the EBDT table. The list is intended to be
* used by the EBDT to allow it to parse the glyph data and generate glyph
* objects. After returning from this method the list belongs to the caller.
* The list entries are in the same order as the size table builders are at
* the time of this call.
*
* @return the list of loca maps with one for each size table builder
*/
public List<Map<Integer, BitmapGlyphInfo>> generateLocaList() {
List<BitmapSizeTable.Builder> sizeBuilderList = this.getSizeList();
List<Map<Integer, BitmapGlyphInfo>> locaList =
new ArrayList<Map<Integer, BitmapGlyphInfo>>(sizeBuilderList.size());
int sizeIndex = 0;
for (BitmapSizeTable.Builder sizeBuilder : sizeBuilderList) {
if (DEBUG) {
System.out.printf("size table = %d%n", sizeIndex++);
}
Map<Integer, BitmapGlyphInfo> locaMap = sizeBuilder.generateLocaMap();
locaList.add(locaMap);
}
return locaList;
}
private List<BitmapSizeTable.Builder> getSizeList() {
if (this.sizeTableBuilders == null) {
this.sizeTableBuilders = this.initialize(this.internalReadData());
super.setModelChanged();
}
return this.sizeTableBuilders;
}
private List<BitmapSizeTable.Builder> initialize(ReadableFontData data) {
List<BitmapSizeTable.Builder> sizeBuilders = new ArrayList<BitmapSizeTable.Builder>();
if (data != null) {
int numSizes = data.readULongAsInt(Offset.numSizes.offset);
for (int i = 0; i < numSizes; i++) {
BitmapSizeTable.Builder sizeBuilder =
BitmapSizeTable.Builder.createBuilder(
data.slice(Offset.bitmapSizeTableArrayStart.offset + i
* Offset.bitmapSizeTableLength.offset, Offset.bitmapSizeTableLength.offset),
data);
sizeBuilders.add(sizeBuilder);
}
}
return sizeBuilders;
}
@Override
protected EblcTable subBuildTable(ReadableFontData data) {
return new EblcTable(this.header(), data);
}
@Override
protected void subDataSet() {
this.revert();
}
@Override
protected int subDataSizeToSerialize() {
if (this.sizeTableBuilders == null) {
return 0;
}
int size = Offset.headerLength.offset;
boolean variable = false;
int sizeIndex = 0;
for (BitmapSizeTable.Builder sizeBuilder : this.sizeTableBuilders) {
int sizeBuilderSize = sizeBuilder.subDataSizeToSerialize();
if (DEBUG) {
System.out.printf("sizeIndex = 0x%x, sizeBuilderSize = 0x%x%n", sizeIndex++,
sizeBuilderSize);
}
variable = sizeBuilderSize > 0 ? variable : true;
size += Math.abs(sizeBuilderSize);
}
return variable ? -size : size;
}
@Override
protected boolean subReadyToSerialize() {
if (this.sizeTableBuilders == null) {
return false;
}
for (BitmapSizeTable.Builder sizeBuilder : this.sizeTableBuilders) {
if (!sizeBuilder.subReadyToSerialize()) {
return false;
}
}
return true;
}
@Override
protected int subSerialize(WritableFontData newData) {
// header
int size = newData.writeFixed(0, this.version);
size += newData.writeULong(size, this.sizeTableBuilders.size());
// calculate the offsets
// offset to the start of the size table array
int sizeTableStartOffset = size;
// walking offset in the size table array
int sizeTableOffset = sizeTableStartOffset;
// offset to the start of the whole index subtable block
int subTableBlockStartOffset =
sizeTableOffset + this.sizeTableBuilders.size() * Offset.bitmapSizeTableLength.offset;
// walking offset in the index subtable
// points to the start of the current subtable block
int currentSubTableBlockStartOffset = subTableBlockStartOffset;
int sizeIndex = 0;
for (BitmapSizeTable.Builder sizeBuilder : this.sizeTableBuilders) {
sizeBuilder.setIndexSubTableArrayOffset(currentSubTableBlockStartOffset);
List<IndexSubTable.Builder<? extends IndexSubTable>> indexSubTableBuilderList =
sizeBuilder.indexSubTableBuilders();
// walking offset within the current subTable array
int indexSubTableArrayOffset = currentSubTableBlockStartOffset;
// walking offset within the subTable entries
int indexSubTableOffset = indexSubTableArrayOffset + indexSubTableBuilderList.size()
* Offset.indexSubHeaderLength.offset;
if (DEBUG) {
System.out.printf(
"size %d: sizeTable = %x, current subTable Block = %x, index subTable Start = %x%n",
sizeIndex, sizeTableOffset, currentSubTableBlockStartOffset, indexSubTableOffset);
sizeIndex++;
}
int subTableIndex = 0;
for (IndexSubTable.Builder<? extends IndexSubTable> indexSubTableBuilder :
indexSubTableBuilderList) {
if (DEBUG) {
System.out.printf("\tsubTableIndex %d: format = %x, ", subTableIndex,
indexSubTableBuilder.indexFormat());
System.out.printf("indexSubTableArrayOffset = %x, indexSubTableOffset = %x%n",
indexSubTableArrayOffset, indexSubTableOffset);
subTableIndex++;
}
// array entry
indexSubTableArrayOffset +=
newData.writeUShort(indexSubTableArrayOffset, indexSubTableBuilder.firstGlyphIndex());
indexSubTableArrayOffset +=
newData.writeUShort(indexSubTableArrayOffset, indexSubTableBuilder.lastGlyphIndex());
indexSubTableArrayOffset += newData.writeULong(
indexSubTableArrayOffset, indexSubTableOffset - currentSubTableBlockStartOffset);
// index sub table
int currentSubTableSize =
indexSubTableBuilder.subSerialize(newData.slice(indexSubTableOffset));
int padding =
FontMath.paddingRequired(currentSubTableSize, FontData.DataSize.ULONG.size());
if (DEBUG) {
System.out.printf(
"\t\tsubTableSize = %x, padding = %x%n", currentSubTableSize, padding);
}
indexSubTableOffset += currentSubTableSize;
indexSubTableOffset += newData.writePadding(indexSubTableOffset, padding);
}
// serialize size table
sizeBuilder.setIndexTableSize(indexSubTableOffset - currentSubTableBlockStartOffset);
sizeTableOffset += sizeBuilder.subSerialize(newData.slice(sizeTableOffset));
currentSubTableBlockStartOffset = indexSubTableOffset;
}
return size + currentSubTableBlockStartOffset;
}
}
}
| 5,750 |
772 | {
"data": {
"email_s": "<EMAIL>",
"event_annual_s": "Yes",
"prize_choice_s": "Skype",
"event_country_s": "United States",
"event_experience_s": "Great",
"event_technology_s": "Pair programming, sharing a device",
"event_tutorials_ss": ["Make a Flappy Game"],
"event_improvement_s": "",
"teacher_first_year_s": "Yes",
"teacher_how_heard_ss": ["Email from Code.org"],
"event_location_type_s": "Public school",
"teacher_description_s": "Other",
"students_number_girls_s": "50",
"students_number_total_s": "80",
"teacher_plan_teach_cs_s": "",
"students_grade_levels_ss": ["5th", "3rd", "4th"]
},
"processed_data": { "prize_code_s": "SKYPE-12345-67890-ABCDE-FGHIJ" }
}
| 327 |
14,668 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_CHROME_CLEANER_PARSERS_SHORTCUT_PARSER_BROKER_FAKE_SHORTCUT_PARSER_H_
#define CHROME_CHROME_CLEANER_PARSERS_SHORTCUT_PARSER_BROKER_FAKE_SHORTCUT_PARSER_H_
#include "base/win/scoped_handle.h"
#include "chrome/chrome_cleaner/mojom/parser_interface.mojom.h"
#include "chrome/chrome_cleaner/parsers/shortcut_parser/broker/shortcut_parser_api.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace chrome_cleaner {
class FakeShortcutParser : public ShortcutParserAPI {
public:
FakeShortcutParser();
~FakeShortcutParser() override;
void SetShortcutsToReturn(const std::vector<ShortcutInformation>& shortcuts);
// ShortcutParserAPI
void ParseShortcut(base::win::ScopedHandle shortcut_handle,
mojom::Parser::ParseShortcutCallback callback) override;
void FindAndParseChromeShortcutsInFoldersAsync(
const std::vector<base::FilePath>& unused_paths,
const FilePathSet& unused_chrome_exe_locations,
ShortcutsParsingDoneCallback callback) override;
private:
std::vector<ShortcutInformation> shortcuts_to_return_;
};
} // namespace chrome_cleaner
#endif // CHROME_CHROME_CLEANER_PARSERS_SHORTCUT_PARSER_BROKER_FAKE_SHORTCUT_PARSER_H_
| 499 |
1,060 | <reponame>arielji/okvis<gh_stars>1000+
/*********************************************************************************
* OKVIS - Open Keyframe-based Visual-Inertial SLAM
* Copyright (c) 2015, Autonomous Systems Lab / ETH Zurich
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Autonomous Systems Lab / ETH Zurich 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.
*
* Created on: Dec 5, 2014
* Author: <NAME> (<EMAIL>)
*********************************************************************************/
#include <okvis/kinematics/Transformation.hpp>
#include <iostream>
#include "gtest/gtest.h"
TEST(Transformation, operations) {
for (size_t i = 0; i < 100; ++i) {
okvis::kinematics::Transformation T_AB;
T_AB.setRandom();
okvis::kinematics::Transformation T_BC;
T_BC.setRandom();
// Test inverse
EXPECT_TRUE(
((T_AB * T_AB.inverse()).T() - Eigen::Matrix4d::Identity()).norm()
< 1e-8);
// Test composition
EXPECT_TRUE(((T_AB * T_BC).T() - T_AB.T() * T_BC.T()).norm() < 1e-8);
// Test construction
okvis::kinematics::Transformation T_AB_alternative(T_AB.T());
EXPECT_TRUE((T_AB.T() - T_AB_alternative.T()).norm() < 1e-8);
okvis::kinematics::Transformation T_AB_alternative2(T_AB.r(), T_AB.q());
EXPECT_TRUE((T_AB.T() - T_AB_alternative2.T()).norm() < 1e-8);
// Test =
okvis::kinematics::Transformation T_AB_alternative3;
T_AB_alternative3 = T_AB;
EXPECT_TRUE((T_AB.T() - T_AB_alternative3.T()).norm() < 1e-8);
// Test setters
okvis::kinematics::Transformation T_AB_alternative4;
T_AB_alternative4.set(T_AB.r(), T_AB.q());
EXPECT_TRUE((T_AB.T() - T_AB_alternative4.T()).norm() < 1e-8);
okvis::kinematics::Transformation T_AB_alternative5;
T_AB_alternative5.set(T_AB.T());
EXPECT_TRUE((T_AB.T() - T_AB_alternative5.T()).norm() < 1e-8);
T_AB.setRandom();
// Test oplus
const double dp = 1.0e-6;
Eigen::Matrix<double, 7, 6, Eigen::RowMajor> jacobian_numDiff;
for (size_t i = 0; i < 6; ++i) {
okvis::kinematics::Transformation T_AB_p = T_AB;
okvis::kinematics::Transformation T_AB_m = T_AB;
Eigen::Matrix<double, 6, 1> dp_p;
Eigen::Matrix<double, 6, 1> dp_m;
dp_p.setZero();
dp_m.setZero();
dp_p[i] = dp;
dp_m[i] = -dp;
T_AB_p.oplus(dp_p);
T_AB_m.oplus(dp_m);
/*jacobian_numDiff.block<7, 1>(0, i) = (T_AB_p.parameters()
- T_AB_m.parameters()) / (2.0 * dp);*/
jacobian_numDiff.block<3, 1>(0, i) = (T_AB_p.r() - T_AB_m.r())
/ (2.0 * dp);
jacobian_numDiff.block<4, 1>(3, i) = (T_AB_p.q().coeffs()
- T_AB_m.q().coeffs()) / (2.0 * dp);
}
Eigen::Matrix<double, 7, 6, Eigen::RowMajor> jacobian;
T_AB.oplusJacobian(jacobian);
//std::cout << jacobian << std::endl;
//std::cout << jacobian_numDiff << std::endl;
EXPECT_TRUE((jacobian - jacobian_numDiff).norm() < 1e-8);
// also check lift Jacobian: dChi/dx*dx/dChi == 1
Eigen::Matrix<double, 6, 7, Eigen::RowMajor> lift_jacobian;
T_AB.liftJacobian(lift_jacobian);
EXPECT_TRUE(
(lift_jacobian * jacobian - Eigen::Matrix<double, 6, 6>::Identity())
.norm() < 1e-8);
// Test minus
okvis::kinematics::Transformation T_AB_disturbed = T_AB;
Eigen::Matrix<double, 6, 1> delta, delta2;
delta.setRandom();
delta *= 0.1; // quite large disturbance
T_AB_disturbed.oplus(delta);
// get numeric Jacobian
Eigen::Matrix<double, 6, 6, Eigen::RowMajor> jacobianMinus_numDiff;
/*for(size_t i=0; i<6; ++i){
okvis::kinematics::Transformation T_AB_p = T_AB_disturbed;
okvis::kinematics::Transformation T_AB_m = T_AB_disturbed;
Eigen::Matrix<double,6,1> dp_p;
Eigen::Matrix<double,6,1> dp_m;
dp_p.setZero();
dp_m.setZero();
dp_p[i] = dp;
dp_m[i] = -dp;
T_AB_p.oplus(dp_p);
T_AB_m.oplus(dp_m);
}*/
//Eigen::Matrix<double, 6, 6, Eigen::RowMajor> minusJacobian;
//T_AB_disturbed.minus(T_AB, delta2, minusJacobian);
//EXPECT_TRUE((delta - delta2).norm() < 1e-8);
}
}
| 2,327 |
5,169 | <gh_stars>1000+
{
"name": "DFITableViewManager",
"version": "0.1.1",
"summary": "DFITableViewManager is a part of DFInfrasturcture",
"description": "DFITableViewManager is a library for simplify tableView delegate and dataSource code.",
"homepage": "https://github.com/sdaheng/DFITableViewManager.git",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"sdaheng": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/sdaheng/DFITableViewManager.git",
"tag": "0.1.1"
},
"source_files": "DFITableViewManager/**/*.{h,m}",
"public_header_files": [
"DFITableViewManager/DFITableViewManager.h",
"DFITableViewManager/DFITableViewModel.h",
"DFITableViewManager/DFITableViewPaging.h",
"DFITableViewManager/DFITableViewConfiguration.h"
],
"requires_arc": true,
"dependencies": {
"DFITableViewCells": [
]
}
}
| 379 |
325 | <filename>tests/src/utility/NewHeaderDependency.cpp
#include "NewHeaderDependency.hpp"
//#include "NewHeaderDependency/NewHeaderDependency2.hpp" // <jet_tag: new_header:2>
int newHeaderDependencyComputeResult(int v1, int v2)
{
return v1 + v2; // <jet_tag: new_header:1>
// return newHeaderDependency2ComputeResult(v1, v2); // <jet_tag: new_header:2>
}
| 146 |
965 | <filename>docs/parallel/concrt/codesnippet/CPP/how-to-use-parallel-invoke-to-write-a-parallel-sort-routine_7.cpp
// Sort the partitions in parallel.
parallel_invoke(
[&items,lo,m] { parallel_bitonic_sort(items, lo, m, INCREASING); },
[&items,lo,m] { parallel_bitonic_sort(items, lo + m, m, DECREASING); }
); | 152 |
2,338 | #include "instrprof-comdat.h"
int g;
extern int bar(int);
int main() {
FOO<int> Foo;
int Res = Foo.DoIt(10);
if (Res > 10)
g = bar(10);
else
g = bar(1) + bar(2);
return 0;
}
| 95 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.websvc.jaxwsmodelapi;
import java.util.List;
/**
*
* @author ayubskhan
*/
public interface WSPort {
public static final String STYLE_DOCUMENT="document"; //NOI18N
public static final String STYLE_RPC="rpc"; //NOI18N
public static final String SOAP_VERSION_11="http://schemas.xmlsoap.org/wsdl/soap/"; //NOI18N
public static final String SOAP_VERSION_12="http://schemas.xmlsoap.org/wsdl/soap12/"; //NOI18N
public Object getInternalJAXWSPort();
public List<? extends WSOperation> getOperations();
public String getName();
public String getNamespaceURI();
public String getJavaName();
public String getPortGetter();
public String getSOAPVersion();
public String getStyle();
public boolean isProvider();
public String getAddress();
}
| 534 |
1,318 | import importlib
import os
aliases = {
'qt4': 'qt',
'gtk2': 'gtk',
}
backends = [
'qt', 'qt4', 'qt5',
'gtk', 'gtk2', 'gtk3',
'tk',
'wx',
'pyglet', 'glut',
'osx',
'asyncio'
]
registered = {}
def register(name, inputhook):
"""Register the function *inputhook* as an event loop integration."""
registered[name] = inputhook
class UnknownBackend(KeyError):
def __init__(self, name):
self.name = name
def __str__(self):
return ("No event loop integration for {!r}. "
"Supported event loops are: {}").format(self.name,
', '.join(backends + sorted(registered)))
def get_inputhook_name_and_func(gui):
if gui in registered:
return gui, registered[gui]
if gui not in backends:
raise UnknownBackend(gui)
if gui in aliases:
return get_inputhook_name_and_func(aliases[gui])
gui_mod = gui
if gui == 'qt5':
os.environ['QT_API'] = 'pyqt5'
gui_mod = 'qt'
mod = importlib.import_module('IPython.terminal.pt_inputhooks.'+gui_mod)
return gui, mod.inputhook
| 526 |
307 | #version 120
//uniform sampler3D Texture0; //volume texture
uniform sampler2D Texture0;
//uniform sampler2D Texture0;
//uniform sampler3D Texture1;
varying vec3 TexCoord0;
varying vec3 TexCoord1;
uniform vec3 worldMinVisInPixels;
uniform vec3 worldMaxVisInPixels;
uniform vec3 worldMinBufInPixels;
uniform vec3 worldMaxBufInPixels;
uniform vec4 scaleAndOffset;
//uniform vec3 offsetInPagesLocal;
uniform float pageDepth;
uniform float bufferMult;
uniform float visPageSizeInPixels;
//const int iNumRaySteps = 2;
//const float fNumRaySteps = 2.0;
uniform float slicesPerPitch;// = sqrt(pitch);
//varying float pitch;// = 256.0;
//varying float pitchM1;// = pitch-1.0;
$
void main() {
TexCoord0 = gl_MultiTexCoord0.xyz;
TexCoord1 = gl_MultiTexCoord1.xyz;
vec4 newPos = gl_Vertex;
newPos.x *= scaleAndOffset.x;
newPos.y *= scaleAndOffset.y;
newPos.x += scaleAndOffset.z;
newPos.y += scaleAndOffset.w;
newPos.z = gl_Vertex.z*0.001+pageDepth;
gl_Position = newPos;
}
$
vec4 sampleAtPoint(vec3 point) {
vec2 texc;
float pitch = slicesPerPitch*slicesPerPitch;
float pitchM1 = pitch-1.0;
vec3 newPoint = point/bufferMult + (1.0-1.0/bufferMult)/2.0;
vec3 curFace = (newPoint.rgb*pitchM1+0.5)/pitch;
float bval = curFace.b*pitchM1;
float xval = floor(mod(bval, slicesPerPitch))/slicesPerPitch;
float yval = floor(bval/slicesPerPitch)/slicesPerPitch;
texc.x = curFace.r/(slicesPerPitch) + xval;
texc.y = curFace.g/(slicesPerPitch) + yval;
return texture2D(Texture0, texc.xy);
//return texture3D(Texture0, newPoint);
}
float rand(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
vec4 getAO(vec3 tp, vec4 curSamp, vec3 wp) {
int i;
int a, b, c;
vec3 offVal;
vec3 offValAbs;
float len;
float aoVal = 0.0;
float totalAO = 0.0;
float notZero;
vec4 res;
int maxRad;
float tsize = visPageSizeInPixels;
vec3 testPoint = tp + 1.0/(tsize); //bufferMult
float fMaxRad;
float curPower;
float rval;
float rval2;
vec3 norm = vec3(0.0,0.0,0.0);
vec3 norm2 = vec3(0.0,0.0,0.0);
int rad = 8;
int radStep = 2;
float frad = float(radStep);
float totSteps = 0.0;
float totHits = 0.0;
float ovLen = 0.0;
float rvMix = 0.0;
//float sval = abs(sin(wp.y/30.0));
float isRock = float( curSamp.r + curSamp.g + curSamp.b > 0.0);
for (c = -rad; c <= rad; c+=radStep) {
for (b = -rad; b <= rad; b+=radStep) {
for (a = -rad; a <= rad; a+=radStep) {
offVal.x = float(a);
offVal.y = float(b);
offVal.z = float(c);
//offVal = normalize(offVal);
//offValAbs = offVal*frad/tsize;
ovLen = 1.0/length(offVal);
res = sampleAtPoint(offVal/tsize + testPoint);
rval = float(res.a == 0.0);
rval2 = float( abs(res.r-curSamp.r) + abs(res.g-curSamp.g) + abs(res.b-curSamp.b) != 0.0 );
rvMix = mix(rval,rval2,0.5);//mix(rval,rval2, isRock);//abs(sin(wp.y)) );//isRock
norm += rvMix*(offVal);
//norm2 += res.a*offVal;
totHits += rval;
totSteps += 1.0;
}
}
}
if (totHits == 0.0) {
norm = vec3(0.0,0.0,0.0);//norm2/totSteps;
if (testPoint.x == 1.0) {
norm.x = 1.0;
}
if (testPoint.y == 1.0) {
norm.y = 1.0;
}
if (testPoint.z == 1.0) {
norm.z = 1.0;
}
aoVal = 0.0;//curSamp.a;
}
else {
maxRad = 128;
fMaxRad = float(maxRad);
for (rad = 32; rad < maxRad; rad *= 2) {
radStep = rad/2;
frad = float(rad);
//curPower = 1.0-frad/fMaxRad;
for (c = -rad; c <= rad; c+=radStep) {
for (b = -rad; b <= rad; b+=radStep) {
for (a = -rad; a <= rad; a+=radStep) {
offVal.x = float(a);
offVal.y = float(b);
offVal.z = float(c);
//offVal = offVal*16.0;
offValAbs = abs(offVal);
notZero = float( (offValAbs.x + offValAbs.y + offValAbs.z) > 0.0);
offVal = normalize(offVal);
offVal *= frad/tsize;
res = sampleAtPoint(offVal+testPoint); //+norm*2.0/(tsize)
rval = float(res.a != 0.0);
aoVal += rval*notZero;// *curPower;//frad;
totalAO += notZero;// *curPower;//frad*notZero;
}
}
}
}
aoVal = clamp(1.0 - aoVal/totalAO, 1.0/255.0, 1.0);
}
norm = normalize(norm);
norm = (norm + 1.0)/2.0;
return vec4(norm,aoVal); //totHits/totSteps
}
int intMod(int lhs, int rhs) {
return lhs - ( (lhs/rhs)*rhs );
}
vec2 pack16(float num) {
int iz = int(num);
int ir = intMod(iz,256);
int ig = (iz)/256;
vec2 res;
res.r = float(ir)/255.0;
res.g = float(ig)/255.0;
return res;
}
float unpack16(vec2 num) {
return num.r*255.0 + num.g*65280.0;
}
/*
void main() {
gl_FragData[0] = vec4(1.0);
gl_FragData[1] = vec4(1.0);
}
*/
void main() {
int i = 0;
int j = 0;
float fi;
float fi2;
float fiRes;
float fj;
float fLerp = 0.0;
vec2 newCoords;
//vec3 front = TexCoord1.xyz;
//vec3 back = TexCoord0.xyz;
//vec4 blackCol = vec4(0.0,0.0,0.0,0.0);
// float curDis = 0.0;
// int iCurDis = 0;
// vec3 curPos = vec3(0.0,0.0,0.0);
// //vec3 lastGoodPos = vec3(0.0,0.0,0.0);
// curDis = floor(distance(front,back)*visPageSizeInPixels); //visPageSizeInPixels
// iCurDis = int(curDis);
// float q;
// for (i = 0; i < iCurDis; i++) {
// fi = float(i);
// fLerp = fi/curDis;
// curPos = mix(front,back,fLerp);
// samp = sampleAtPoint(curPos);
// if (samp.a != 0.0) {
// break;
// }
// //lastGoodPos = curPos;
// }
// if ( i == iCurDis ) {
// discard;
// }
vec3 curPos = TexCoord0.xyz;
vec4 samp = texture2D(Texture0, TexCoord1.xy);
if (samp.a == 0.0) {
discard;
}
vec3 worldPos;
worldPos.x = mix(worldMinVisInPixels.x, worldMaxVisInPixels.x, curPos.x);
worldPos.y = mix(worldMinVisInPixels.y, worldMaxVisInPixels.y, curPos.y);
worldPos.z = mix(worldMinVisInPixels.z, worldMaxVisInPixels.z, curPos.z);
vec2 heightVals = pack16(worldPos.z);
vec4 normAO = getAO(curPos, samp, worldPos);
vec4 heightMat = vec4(heightVals.rg, samp.a, 1.0);
gl_FragData[0] = heightMat;//vec4(offsetInPagesLocal/16.0,1.0);// heightMat;
gl_FragData[1] = normAO;//vec4(curPos,1.0);//normAO;
}
| 3,923 |
5,823 | <gh_stars>1000+
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/glfw/system_utils.h"
#include <cstdlib>
#include "gtest/gtest.h"
namespace flutter {
namespace {
// This is a helper for setting up the different environment variables to
// specific strings, calling GetPreferredLanguageInfo, and then restoring those
// environment variables to any previously existing values.
std::vector<LanguageInfo> SetAndRestoreLanguageAroundGettingLanguageInfo(
const char* language,
const char* lc_all,
const char* lc_messages,
const char* lang) {
std::vector<const char*> env_vars{
"LANGUAGE",
"LC_ALL",
"LC_MESSAGES",
"LANG",
};
std::map<const char*, const char*> new_values{
{env_vars[0], language},
{env_vars[1], lc_all},
{env_vars[2], lc_messages},
{env_vars[3], lang},
};
std::map<const char*, const char*> prior_values;
for (auto var : env_vars) {
const char* value = getenv(var);
if (value != nullptr) {
prior_values.emplace(var, value);
}
const char* new_value = new_values.at(var);
if (new_value != nullptr) {
setenv(var, new_value, 1);
} else {
unsetenv(var);
}
}
std::vector<LanguageInfo> languages = GetPreferredLanguageInfo();
for (auto [var, value] : prior_values) {
setenv(var, value, 1);
}
return languages;
}
TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoFull) {
const char* locale_string = "en_GB.ISO-8859-1@euro:en_US:sv:zh_CN.UTF-8";
std::vector<LanguageInfo> languages =
SetAndRestoreLanguageAroundGettingLanguageInfo(locale_string, nullptr,
nullptr, nullptr);
EXPECT_EQ(languages.size(), 15UL);
EXPECT_STREQ(languages[0].language.c_str(), "en");
EXPECT_STREQ(languages[0].territory.c_str(), "GB");
EXPECT_STREQ(languages[0].codeset.c_str(), "ISO-8859-1");
EXPECT_STREQ(languages[0].modifier.c_str(), "euro");
EXPECT_STREQ(languages[1].language.c_str(), "en");
EXPECT_STREQ(languages[1].territory.c_str(), "GB");
EXPECT_STREQ(languages[1].codeset.c_str(), "");
EXPECT_STREQ(languages[1].modifier.c_str(), "euro");
EXPECT_STREQ(languages[2].language.c_str(), "en");
EXPECT_STREQ(languages[2].territory.c_str(), "");
EXPECT_STREQ(languages[2].codeset.c_str(), "ISO-8859-1");
EXPECT_STREQ(languages[2].modifier.c_str(), "euro");
EXPECT_STREQ(languages[3].language.c_str(), "en");
EXPECT_STREQ(languages[3].territory.c_str(), "");
EXPECT_STREQ(languages[3].codeset.c_str(), "");
EXPECT_STREQ(languages[3].modifier.c_str(), "euro");
EXPECT_STREQ(languages[4].language.c_str(), "en");
EXPECT_STREQ(languages[4].territory.c_str(), "GB");
EXPECT_STREQ(languages[4].codeset.c_str(), "ISO-8859-1");
EXPECT_STREQ(languages[4].modifier.c_str(), "");
EXPECT_STREQ(languages[5].language.c_str(), "en");
EXPECT_STREQ(languages[5].territory.c_str(), "GB");
EXPECT_STREQ(languages[5].codeset.c_str(), "");
EXPECT_STREQ(languages[5].modifier.c_str(), "");
EXPECT_STREQ(languages[6].language.c_str(), "en");
EXPECT_STREQ(languages[6].territory.c_str(), "");
EXPECT_STREQ(languages[6].codeset.c_str(), "ISO-8859-1");
EXPECT_STREQ(languages[6].modifier.c_str(), "");
EXPECT_STREQ(languages[7].language.c_str(), "en");
EXPECT_STREQ(languages[7].territory.c_str(), "");
EXPECT_STREQ(languages[7].codeset.c_str(), "");
EXPECT_STREQ(languages[7].modifier.c_str(), "");
EXPECT_STREQ(languages[8].language.c_str(), "en");
EXPECT_STREQ(languages[8].territory.c_str(), "US");
EXPECT_STREQ(languages[8].codeset.c_str(), "");
EXPECT_STREQ(languages[8].modifier.c_str(), "");
EXPECT_STREQ(languages[9].language.c_str(), "en");
EXPECT_STREQ(languages[9].territory.c_str(), "");
EXPECT_STREQ(languages[9].codeset.c_str(), "");
EXPECT_STREQ(languages[9].modifier.c_str(), "");
EXPECT_STREQ(languages[10].language.c_str(), "sv");
EXPECT_STREQ(languages[10].territory.c_str(), "");
EXPECT_STREQ(languages[10].codeset.c_str(), "");
EXPECT_STREQ(languages[10].modifier.c_str(), "");
EXPECT_STREQ(languages[11].language.c_str(), "zh");
EXPECT_STREQ(languages[11].territory.c_str(), "CN");
EXPECT_STREQ(languages[11].codeset.c_str(), "UTF-8");
EXPECT_STREQ(languages[11].modifier.c_str(), "");
EXPECT_STREQ(languages[12].language.c_str(), "zh");
EXPECT_STREQ(languages[12].territory.c_str(), "CN");
EXPECT_STREQ(languages[12].codeset.c_str(), "");
EXPECT_STREQ(languages[12].modifier.c_str(), "");
EXPECT_STREQ(languages[13].language.c_str(), "zh");
EXPECT_STREQ(languages[13].territory.c_str(), "");
EXPECT_STREQ(languages[13].codeset.c_str(), "UTF-8");
EXPECT_STREQ(languages[13].modifier.c_str(), "");
EXPECT_STREQ(languages[14].language.c_str(), "zh");
EXPECT_STREQ(languages[14].territory.c_str(), "");
EXPECT_STREQ(languages[14].codeset.c_str(), "");
EXPECT_STREQ(languages[14].modifier.c_str(), "");
}
TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoWeird) {
const char* locale_string = "[email protected]";
std::vector<LanguageInfo> languages =
SetAndRestoreLanguageAroundGettingLanguageInfo(locale_string, nullptr,
nullptr, nullptr);
EXPECT_EQ(languages.size(), 4UL);
EXPECT_STREQ(languages[0].language.c_str(), "tt");
EXPECT_STREQ(languages[0].territory.c_str(), "RU");
EXPECT_STREQ(languages[0].codeset.c_str(), "");
EXPECT_STREQ(languages[0].modifier.c_str(), "iqtelif.UTF-8");
EXPECT_STREQ(languages[1].language.c_str(), "tt");
EXPECT_STREQ(languages[1].territory.c_str(), "");
EXPECT_STREQ(languages[1].codeset.c_str(), "");
EXPECT_STREQ(languages[1].modifier.c_str(), "iqtelif.UTF-8");
EXPECT_STREQ(languages[2].language.c_str(), "tt");
EXPECT_STREQ(languages[2].territory.c_str(), "RU");
EXPECT_STREQ(languages[2].codeset.c_str(), "");
EXPECT_STREQ(languages[2].modifier.c_str(), "");
EXPECT_STREQ(languages[3].language.c_str(), "tt");
EXPECT_STREQ(languages[3].territory.c_str(), "");
EXPECT_STREQ(languages[3].codeset.c_str(), "");
EXPECT_STREQ(languages[3].modifier.c_str(), "");
}
TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoEmpty) {
const char* locale_string = "";
std::vector<LanguageInfo> languages =
SetAndRestoreLanguageAroundGettingLanguageInfo(
locale_string, locale_string, locale_string, locale_string);
EXPECT_EQ(languages.size(), 1UL);
EXPECT_STREQ(languages[0].language.c_str(), "C");
EXPECT_TRUE(languages[0].territory.empty());
EXPECT_TRUE(languages[0].codeset.empty());
EXPECT_TRUE(languages[0].modifier.empty());
}
TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoEnvVariableOrdering1) {
const char* language = "de";
const char* lc_all = "en";
const char* lc_messages = "zh";
const char* lang = "tt";
std::vector<LanguageInfo> languages =
SetAndRestoreLanguageAroundGettingLanguageInfo(language, lc_all,
lc_messages, lang);
EXPECT_EQ(languages.size(), 1UL);
EXPECT_STREQ(languages[0].language.c_str(), language);
}
TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoEnvVariableOrdering2) {
const char* lc_all = "en";
const char* lc_messages = "zh";
const char* lang = "tt";
std::vector<LanguageInfo> languages =
SetAndRestoreLanguageAroundGettingLanguageInfo(nullptr, lc_all,
lc_messages, lang);
EXPECT_EQ(languages.size(), 1UL);
EXPECT_STREQ(languages[0].language.c_str(), lc_all);
}
TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoEnvVariableOrdering3) {
const char* lc_messages = "zh";
const char* lang = "tt";
std::vector<LanguageInfo> languages =
SetAndRestoreLanguageAroundGettingLanguageInfo(nullptr, nullptr,
lc_messages, lang);
EXPECT_EQ(languages.size(), 1UL);
EXPECT_STREQ(languages[0].language.c_str(), lc_messages);
}
TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoEnvVariableOrdering4) {
const char* lang = "tt";
std::vector<LanguageInfo> languages =
SetAndRestoreLanguageAroundGettingLanguageInfo(nullptr, nullptr, nullptr,
lang);
EXPECT_EQ(languages.size(), 1UL);
EXPECT_STREQ(languages[0].language.c_str(), lang);
}
TEST(FlutterGlfwSystemUtilsTest, GetPreferredLanuageInfoEnvVariableOrdering5) {
std::vector<LanguageInfo> languages =
SetAndRestoreLanguageAroundGettingLanguageInfo(nullptr, nullptr, nullptr,
nullptr);
EXPECT_EQ(languages.size(), 1UL);
EXPECT_STREQ(languages[0].language.c_str(), "C");
}
TEST(FlutterGlfwSystemUtilsTest, ConvertToFlutterLocaleEmpty) {
std::vector<LanguageInfo> languages;
std::vector<FlutterLocale> locales = ConvertToFlutterLocale(languages);
EXPECT_TRUE(locales.empty());
}
TEST(FlutterGlfwSystemUtilsTest, ConvertToFlutterLocaleNonEmpty) {
std::vector<LanguageInfo> languages;
languages.push_back(LanguageInfo{"en", "US", "", ""});
languages.push_back(LanguageInfo{"tt", "RU", "", "iqtelif.UTF-8"});
languages.push_back(LanguageInfo{"sv", "", "", ""});
languages.push_back(LanguageInfo{"de", "DE", "UTF-8", "euro"});
languages.push_back(LanguageInfo{"zh", "CN", "UTF-8", ""});
std::vector<FlutterLocale> locales = ConvertToFlutterLocale(languages);
EXPECT_EQ(locales.size(), 5UL);
EXPECT_EQ(locales[0].struct_size, sizeof(FlutterLocale));
EXPECT_STREQ(locales[0].language_code, "en");
EXPECT_STREQ(locales[0].country_code, "US");
EXPECT_EQ(locales[0].script_code, nullptr);
EXPECT_EQ(locales[0].variant_code, nullptr);
EXPECT_STREQ(locales[1].language_code, "tt");
EXPECT_STREQ(locales[1].country_code, "RU");
EXPECT_EQ(locales[1].script_code, nullptr);
EXPECT_STREQ(locales[1].variant_code, "iqtelif.UTF-8");
EXPECT_STREQ(locales[2].language_code, "sv");
EXPECT_EQ(locales[2].country_code, nullptr);
EXPECT_EQ(locales[2].script_code, nullptr);
EXPECT_EQ(locales[2].variant_code, nullptr);
EXPECT_STREQ(locales[3].language_code, "de");
EXPECT_STREQ(locales[3].country_code, "DE");
EXPECT_STREQ(locales[3].script_code, "UTF-8");
EXPECT_STREQ(locales[3].variant_code, "euro");
EXPECT_STREQ(locales[4].language_code, "zh");
EXPECT_STREQ(locales[4].country_code, "CN");
EXPECT_STREQ(locales[4].script_code, "UTF-8");
EXPECT_EQ(locales[4].variant_code, nullptr);
}
} // namespace
} // namespace flutter
| 4,598 |
2,094 | #!/usr/bin/env python3
"""
Very simple symbolic math library. Used for generating code for implementing Winograd transformation matrices.
"""
import numbers
import operator
# Helpful guide to overloadable python operators:
#
# https://www.python-course.eu/python3_magic_methods.php
def num_rows(matrix_as_list):
return len(matrix_as_list)
def num_columns(matrix_as_list):
return len(matrix_as_list[0])
def expr(obj):
"""Convert a number or string into an expression"""
if isinstance(obj, Expr):
return obj
if isinstance(obj, numbers.Number):
return ScalarLiteral(obj)
if isinstance(obj, str):
return ScalarVariable(obj)
raise Exception("ERROR converting object to expression: {}".format(obj))
def cstr(x):
try:
return x.cstr()
except AttributeError:
return str(x)
def expand(x):
try:
return x.expand()
except AttributeError:
return x
def simplify(x):
try:
return x.simplify()
except AttributeError:
return x
# Base class
class Expr(object):
def expand(self):
return self
def simplify(self):
return self
def cstr(self):
return str(self)
def __add__(self, other):
return Plus(self, other)
def __sub__(self, other):
return Minus(self, other)
def __mul__(self, other):
return Times(self, other)
def __truediv__(self, other):
return Divide(self, other)
def __radd__(self, other):
return Plus(other, self)
def __rsub__(self, other):
return Minus(other, self)
def __rmul__(self, other):
return Times(other, self)
def __rtruediv__(self, other):
return Divide(other, self)
def __matmul__(self, other):
return MatrixMultiply(self, other)
def __neg__(self):
return Negate(self)
def __pos__(self):
return self
class Function(Expr):
def __init__(self, args, fn_name, fn):
self.args = args
self.fn_name = fn_name
self.fn_fn = fn_fn
def expand(self):
args = (expand(a) for a in self.args)
return Function(args, self.fn_name, self.fn)
def simplify(self):
args = (simplify(a) for a in self.args)
return Function(args, self.fn_name, self.fn)
def __str__(self):
return "{}({})".format(self.fn_name, (", ".join(self.args)))
def __repr__(self):
return "{}({})".format(self.__class__.__name__, self.__str__())
def cstr(self):
return "{}({})".format(self.fn_name, (", ".join((cstr(arg) for arg in self.args))))
class UnaryOp(Expr):
def __init__(self, a, op_name, op_fn):
self.a = a
self.op_name = op_name
self.op_fn = op_fn
def expand(self):
a = expand(self.a)
return UnaryOp(a, self.op_name, self.op_fn)
def simplify(self):
a = simplify(self.a)
if isinstance(a, ScalarLiteral):
return ScalarLiteral(self.op_fn(a.value))
else:
return UnaryOp(a, self.op_name, self.op_fn)
def __str__(self):
return "({} {})".format(self.op_name, self.a)
def __repr__(self):
return "{}({})".format(self.__class__.__name__, self.__str__())
def cstr(self):
return "({} {})".format(self.op_name, cstr(self.a))
class BinaryOp(Expr):
def __init__(self, a, b, op_name, op_fn):
if isinstance(a, numbers.Number):
a = ScalarLiteral(a)
if isinstance(b, numbers.Number):
b = ScalarLiteral(b)
self.a = a
self.b = b
self.op_name = op_name
self.op_fn = op_fn
def expand(self):
a = expand(self.a)
b = expand(self.b)
return BinaryOp(a, b, self.op_name, self.op_fn)
def simplify(self):
a = simplify(self.a)
b = simplify(self.b)
if isinstance(a, ScalarLiteral) and isinstance(b, ScalarLiteral):
return ScalarLiteral(self.op_fn(a.value, b.value))
else:
return BinaryOp(a, b, self.op_name, self.op_fn)
def __str__(self):
return "({} {} {})".format(self.a, self.op_name, self.b)
def __repr__(self):
return "{}({})".format(self.__class__.__name__, self.__str__())
def cstr(self):
return "({} {} {})".format(cstr(self.a), self.op_name, cstr(self.b))
class Plus(BinaryOp):
def __init__(self, a, b):
super().__init__(a, b, "+", operator.add)
def simplify(self):
s = super().simplify()
if isinstance(s, ScalarLiteral):
return s
if isinstance(s.a, ScalarLiteral) and s.a.value == 0:
return s.b
if isinstance(s.b, ScalarLiteral) and s.b.value == 0:
return s.a
if isinstance(s.a, Negate):
return Minus(s.b, s.a.a)
if isinstance(s.b, Negate):
return Minus(s.a, s.b.a)
return s
class Minus(BinaryOp):
def __init__(self, a, b):
super().__init__(a, b, "-", operator.sub)
def simplify(self):
s = super().simplify()
if isinstance(s, ScalarLiteral):
return s
if isinstance(s.a, ScalarLiteral) and s.a.value == 0:
return Negate(s.b)
if isinstance(s.b, ScalarLiteral) and s.b.value == 0:
return s.a
if isinstance(s.b, Negate):
return Plus(s.a, s.b.a)
return s
class Times(BinaryOp):
def __init__(self, a, b):
super().__init__(a, b, "*", operator.mul)
def simplify(self):
s = super().simplify()
if isinstance(s, ScalarLiteral):
return s
if (isinstance(s.a, ScalarLiteral) and s.a.value == 0) or (isinstance(s.b, ScalarLiteral) and s.b.value == 0):
return 0
if isinstance(s.a, ScalarLiteral) and s.a.value == 1:
return s.b
if isinstance(s.b, ScalarLiteral) and s.b.value == 1:
return s.a
if isinstance(s.a, ScalarLiteral) and s.a.value == -1:
return Negate(s.b)
if isinstance(s.b, ScalarLiteral) and s.b.value == -1:
return Negate(s.a)
return s
class Divide(BinaryOp):
def __init__(self, a, b):
super().__init__(a, b, "/", operator.truediv)
def simplify(self):
s = super().simplify()
if isinstance(s, ScalarLiteral):
return s
if isinstance(s.b, ScalarLiteral) and s.b.value == 1:
return s.a
if isinstance(s.b, ScalarLiteral) and s.b.value == -1:
return Negate(s.a)
return s
class MatrixTranspose(Function):
def __init__(self, m):
super().__init__((m,), "transpose", transpose)
## ??
class MatrixMultiply(BinaryOp):
def __init__(self, a, b):
super().__init__(a, b, "@", operator.matmul)
def expand(self):
a = expand(self.a)
b = expand(self.b)
return matmult(a, b)
def simplify(self):
a = simplify(self.a)
b = simplify(self.b)
return simplify(matmult(a, b))
class Negate(UnaryOp):
def __init__(self, a):
super().__init__(a, "-", operator.neg)
class ArrayAccess(Expr):
def __init__(self, a, index):
self.a = a
indices = index if len(index) > 1 else (index,)
self.indices = [expr(i) for i in indices]
def __str__(self):
return "{}[{}]".format(self.a, (", ".join(str(i) for i in self.indices)))
def __repr__(self):
return "{}({})".format(self.__class__.__name__, self.__str__())
def cstr(self):
return "{}({})".format(self.a, (", ".join(cstr(i) for i in self.indices)))
class ScalarLiteral(Expr):
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
def __repr__(self):
return "{}({})".format(self.__class__.__name__, self.__str__())
class ScalarVariable(Expr):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return "{}({})".format(self.__class__.__name__, self.__str__())
temp_count = 0
def get_next_temp_name():
global temp_count
return "t_{}".format(temp_count)
temp_count += 1
class MatrixExpr(Expr):
def __init__(self, rows, columns, contents=None):
self.name = get_next_temp_name()
self.rows = rows
self.columns = columns
self.contents = contents if contents is not None else [[[] for j in range(columns)] for i in range(rows)]
def simplify(self):
result = MatrixExpr(self.rows, self.columns)
for row in range(self.rows):
for column in range(self.columns):
entry = self.contents[row][column]
result[row, column] = simplify(entry)
return result
def __getitem__(self, index):
return self.contents[index[0]][index[1]]
def __setitem__(self, index, value):
self.contents[index[0]][index[1]] = value
def _to_string(self, lbracket, rbracket, str_fn):
elemstrings = [[str_fn(x) for x in row] for row in self.contents]
rowstrings = [lbracket + ", ".join(c for c in row) + rbracket for row in elemstrings]
return lbracket + ",\n".join(rowstrings) + rbracket
def __str__(self):
return self._to_string("[", "]", str)
def __repr__(self):
return "{}({})".format(self.__class__.__name__, self.__str__())
def cstr(self):
return self._to_string("{", "}", cstr)
# TODO: combine MatrixLiteral with MatrixExpr
class MatrixLiteral(MatrixExpr):
def __init__(self, value):
self.value = value
self.rows = len(value)
self.columns = len(value[0])
def __getitem__(self, index):
return ScalarLiteral(self.value[index[0]][index[1]])
def _to_string(self, lbracket, rbracket, str_fn):
elemstrings = [[str_fn(x) for x in row] for row in self.value]
rowstrings = [lbracket + ", ".join(c for c in row) + rbracket for row in elemstrings]
return lbracket + ",\n".join(rowstrings) + rbracket
def __str__(self):
return self._to_string("[", "]", str)
def __repr__(self):
return "{}({})".format(self.__class__.__name__, self.__str__())
def cstr(self):
return self._to_string("{", "}", cstr)
class MatrixVariable(Expr):
def __init__(self, name, rows, columns):
self.name = name
self.rows = rows
self.columns = columns
def __getitem__(self, index):
return ArrayAccess(self, index)
def __str__(self):
return self.name
def __repr__(self):
return "{}({})".format(self.__class__.__name__, self.__str__())
def matmult(A, B):
# A: m x k
# B: k x n
# result: m x n
m = A.rows
k = A.columns
assert(k == B.rows)
n = B.columns
O = MatrixExpr(m, n)
for i in range(m):
for j in range(n):
O[i,j] = 0
for l in range(k):
O[i,j] += A[i,l] * B[l,j]
return O
# Test
if __name__ == "__main__":
a = 3
b = ScalarLiteral(4)
c = ScalarVariable('x')
d = ScalarLiteral(0)
ex = (a + b) * c + d
print("a: {}".format(a))
print("b: {}".format(b))
print("c: {}".format(c))
print("a+b: {}".format(a+b))
print("Expr: {}".format(ex))
print("Simplified expr: {}".format(simplify(ex)))
print()
print("Matrix example")
A = MatrixLiteral([[1,2,3],[4,5,6]])
B = MatrixLiteral([[5,6],[7,8],[9,10]])
m = MatrixVariable("m", 3, 1)
print("A:", A)
print("B:", B)
print("m:", m)
print()
print("A@m: ", A@m)
print()
print("A@m, expanded: ", (A@m).expand())
print()
print("A@m, simplified: ", simplify(A@m))
print()
print("A@B: ", A@B)
print()
print("A@B, expanded: ", expand(A@B))
print()
print("A@B, simplified: ", simplify(A@B))
print()
##
## TODO:
##
## matrix transpose
## arbitrary functions (just called by name)
## | 5,686 |
1,091 | /*
* Copyright 2020-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* This work was partially supported by EC H2020 project METRO-HAUL (761727).
*/
package org.onosproject.cli.net;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.Completion;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.behaviour.InternalConnectivity;
import java.util.Set;
//import java.util.HashSet;
//import java.util.Comparator;
//import java.util.Collections;
import java.util.stream.Collectors;
import java.util.List;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Lists possible output ports to which a given input port can be internally connected on a single device.
*/
@Service
@Command(scope = "onos", name = "get-output-ports",
description = "Lists possible output ports to which a given input port can be internally connected " +
"on a single device")
public class GetInternalConnectivityOutputPortsCommand extends AbstractShellCommand {
private static final Logger log = getLogger(BitErrorCommand.class);
@Argument(index = 0, name = "input port", description = "{DeviceID}/{PortNumber}",
required = true, multiValued = false)
@Completion(ConnectPointCompleter.class)
private String input = null;
@Override
protected void doExecute() throws Exception {
ConnectPoint inputConnectPoint = ConnectPoint.deviceConnectPoint(input);
DeviceService deviceService = get(DeviceService.class);
DeviceId inputDeviceId = inputConnectPoint.deviceId();
PortNumber inputPortNumber = inputConnectPoint.port();
InternalConnectivity internalConnectivityBehaviour;
Device device = deviceService.getDevice(inputDeviceId);
if (device != null && device.is(InternalConnectivity.class)) {
internalConnectivityBehaviour = device.as(InternalConnectivity.class);
} else {
print("[ERROR] specified device %s does not support Internal Connectivity Behaviour.",
device.toString());
return;
}
Set<PortNumber> outputPorts = internalConnectivityBehaviour.getOutputPorts(inputPortNumber);
List<PortNumber> outputPortsList = outputPorts.stream().sorted((a, b)
-> (int) (a.toLong() - b.toLong())).collect(Collectors.toList());
if (outputPorts.isEmpty()) {
print("[POSSIBLE OUTPUT PORTS] None!");
} else {
print("[POSSIBLE OUTPUT PORTS] " + outputPortsList.toString());
}
}
}
| 1,175 |
997 | <reponame>mkannwischer/PQClean
#ifndef PQCLEAN_NTRULPR857_CLEAN_CRYPTO_DECODE_256X2_H
#define PQCLEAN_NTRULPR857_CLEAN_CRYPTO_DECODE_256X2_H
#include <stdint.h>
#define PQCLEAN_NTRULPR857_CLEAN_crypto_decode_256x2_STRBYTES 32
#define PQCLEAN_NTRULPR857_CLEAN_crypto_decode_256x2_ITEMS 256
#define PQCLEAN_NTRULPR857_CLEAN_crypto_decode_256x2_ITEMBYTES 1
void PQCLEAN_NTRULPR857_CLEAN_crypto_decode_256x2(void *v, const unsigned char *s);
#endif
| 225 |
897 | /**
* Minimum Window Substring
* OR
* Smallest Window in a String Containing All Characters of Another String
* Given two strings string1 and string2, find the smallest substring in
* string1 containing all characters of string2.
*/
#include <bits/stdc++.h>
using namespace std;
string minWindow(string str, string pattern)
{ //unordered map for storing the characters in pattern that we need to check for in str
unordered_map<char, int> letters;
for (auto c : pattern)
letters[c]++;
//counts number of pattern'str letters in current window
int count = 0;
int low = 0, min_length = INT_MAX, min_start = 0;
for (int high = 0; high < str.length(); high++) {
if (letters[str[high]] > 0)
count++; //means that this letter is in pattern
//reduce the count for the letter on which we are currently
letters[str[high]]--;
if (count == pattern.length()) {
//if current windows contains all of the letters in pattern
while (low < high && letters[str[low]] < 0)
letters[str[low]]++, low++;
//move low ahead if its not of any significance
if (min_length > high - low)
//update the min length
min_length = high - (min_start = low) + 1;
//move low ahead and also increment the value
letters[str[low++]]++;
//count-- as we are moving low ahead & low pointed to a char in pattern before
count--;
}
}
//check for edge case & return the result
return min_length == INT_MAX ? "" : str.substr(min_start, min_length);
}
int main()
{
//taking input from user
string str, pattern;
cout << "Enter a String text: ";
cin >> str;
cout << "Enter a String pattern: ";
cin >> pattern;
cout << "Smallest substring in text, containing all characters in pattern: ";
cout << minWindow(str, pattern);
}
/*
Test Cases:
INPUT:
Enter a String text: saazksaa
Enter a String pattern: szk
OUTPUT:
Smallest substring in text, containing all characters in pattern: zks
INPUT:
Enter a String text: letuscontributetoopensource
Enter a String pattern: ubr
OUTPUT:
Smallest substring in text, containing all characters in pattern: ribu
Time Complexity: O(N)
Space Compleaxity: O(Charcter Count)
*/
| 903 |
357 | <reponame>wfu8/lightwave
/*
* Copyright (c) 2012-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.vmware.identity.rest.core.server.authorization.token.jwt.bearer;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import com.vmware.identity.rest.core.server.authorization.token.AccessToken;
/**
* An implementation of a bearer token using the JSON Web Token format.
*
* @see <a href="http://jwt.io/">JSON Web Token Format</a>
*/
public class JWTBearerToken implements AccessToken {
private SignedJWT jwt;
private JWTClaimsSet claims;
private String tokenType;
private String role;
private List<String> groups;
private boolean multiTenanted;
/**
* Constructs a new {@link JWTBearerToken}.
*
* @param jwt the signed JWT object that represents this token
* @param tokenTypeField the field that contains the token type
* @param roleField the field that contains the role
* @param groupsField the field that contains the groups
* @throws ParseException if there is an error parsing information from the JWT
*/
@SuppressWarnings("unchecked")
public JWTBearerToken(
SignedJWT jwt, String tokenTypeField,
String roleField, String groupsField,
String tokenMultiTenantField) throws ParseException {
this.jwt = jwt;
this.claims = jwt.getJWTClaimsSet();
this.tokenType = (String) claims.getClaim(tokenTypeField);
this.role = (String) claims.getClaim(roleField);
this.groups = (List<String>) claims.getClaim(groupsField);
Boolean val = claims.getBooleanClaim(tokenMultiTenantField);
this.multiTenanted = (val != null) && (val.booleanValue());
}
@Override
public List<String> getAudience() {
return claims.getAudience();
}
@Override
public String getIssuer() {
return claims.getIssuer();
}
@Override
public String getRole() {
return role;
}
@Override
public List<String> getGroupList() {
return groups;
}
@Override
public Date getIssueTime() {
return claims.getIssueTime();
}
@Override
public Date getExpirationTime() {
return claims.getExpirationTime();
}
@Override
public String getSubject() {
return claims.getSubject();
}
@Override
public String getTokenType() {
return tokenType;
}
@Override
public boolean isSubjectMultiTenant() { return this.multiTenanted; }
/**
* Fetch the {@link SignedJWT} object from the access token.
*
* @return the JWT object from the access token
*/
public SignedJWT getJWT() {
return jwt;
}
/**
* Fetch the {@link ReadOnlyJWTClaimsSet} from the access token.
*
* @return the claim set from the access token
*/
public JWTClaimsSet getClaims() {
return claims;
}
}
| 1,292 |
60,067 | #include <ATen/TensorMeta.h>
namespace at {
} // namespace at
| 25 |
1,391 | <reponame>newluhux/plan9port<filename>src/cmd/ndb/convM2DNS.c
#include <u.h>
#include <libc.h>
#include <ip.h>
#include <bio.h>
#include <ndb.h>
#include "dns.h"
typedef struct Scan Scan;
struct Scan
{
uchar *base;
uchar *p;
uchar *ep;
char *err;
};
#define NAME(x) gname(x, sp)
#define SYMBOL(x) (x = gsym(sp))
#define STRING(x) (x = gstr(sp))
#define USHORT(x) (x = gshort(sp))
#define ULONG(x) (x = glong(sp))
#define UCHAR(x) (x = gchar(sp))
#define V4ADDR(x) (x = gv4addr(sp))
#define V6ADDR(x) (x = gv6addr(sp))
#define BYTES(x, y) (y = gbytes(sp, &x, len - (sp->p - data)))
static char *toolong = "too long";
/*
* get a ushort/ulong
*/
static ushort
gchar(Scan *sp)
{
ushort x;
if(sp->err)
return 0;
if(sp->ep - sp->p < 1){
sp->err = toolong;
return 0;
}
x = sp->p[0];
sp->p += 1;
return x;
}
static ushort
gshort(Scan *sp)
{
ushort x;
if(sp->err)
return 0;
if(sp->ep - sp->p < 2){
sp->err = toolong;
return 0;
}
x = (sp->p[0]<<8) | sp->p[1];
sp->p += 2;
return x;
}
static ulong
glong(Scan *sp)
{
ulong x;
if(sp->err)
return 0;
if(sp->ep - sp->p < 4){
sp->err = toolong;
return 0;
}
x = (sp->p[0]<<24) | (sp->p[1]<<16) | (sp->p[2]<<8) | sp->p[3];
sp->p += 4;
return x;
}
/*
* get an ip address
*/
static DN*
gv4addr(Scan *sp)
{
char addr[32];
if(sp->err)
return 0;
if(sp->ep - sp->p < 4){
sp->err = toolong;
return 0;
}
snprint(addr, sizeof(addr), "%V", sp->p);
sp->p += 4;
return dnlookup(addr, Cin, 1);
}
static DN*
gv6addr(Scan *sp)
{
char addr[64];
if(sp->err)
return 0;
if(sp->ep - sp->p < IPaddrlen){
sp->err = toolong;
return 0;
}
snprint(addr, sizeof(addr), "%I", sp->p);
sp->p += IPaddrlen;
return dnlookup(addr, Cin, 1);
}
/*
* get a string. make it an internal symbol.
*/
static DN*
gsym(Scan *sp)
{
int n;
char sym[Strlen+1];
if(sp->err)
return 0;
n = *(sp->p++);
if(sp->p+n > sp->ep){
sp->err = toolong;
return 0;
}
if(n > Strlen){
sp->err = "illegal string";
return 0;
}
strncpy(sym, (char*)sp->p, n);
sym[n] = 0;
sp->p += n;
return dnlookup(sym, Csym, 1);
}
/*
* get a string. don't make it an internal symbol.
*/
static Txt*
gstr(Scan *sp)
{
int n;
char sym[Strlen+1];
Txt *t;
if(sp->err)
return 0;
n = *(sp->p++);
if(sp->p+n > sp->ep){
sp->err = toolong;
return 0;
}
if(n > Strlen){
sp->err = "illegal string";
return 0;
}
strncpy(sym, (char*)sp->p, n);
sym[n] = 0;
sp->p += n;
t = emalloc(sizeof(*t));
t->next = nil;
t->p = estrdup(sym);
return t;
}
/*
* get a sequence of bytes
*/
static int
gbytes(Scan *sp, uchar **p, int n)
{
if(sp->err)
return 0;
if(sp->p+n > sp->ep || n < 0){
sp->err = toolong;
return 0;
}
*p = emalloc(n);
memmove(*p, sp->p, n);
sp->p += n;
return n;
}
/*
* get a domain name. 'to' must point to a buffer at least Domlen+1 long.
*/
static char*
gname(char *to, Scan *sp)
{
int len, off;
int pointer;
int n;
char *tostart;
char *toend;
uchar *p;
tostart = to;
if(sp->err)
goto err;
pointer = 0;
p = sp->p;
toend = to + Domlen;
for(len = 0; *p; len += pointer ? 0 : (n+1)){
if((*p & 0xc0) == 0xc0){
/* pointer to other spot in message */
if(pointer++ > 10){
sp->err = "pointer loop";
goto err;
}
off = ((p[0]<<8) + p[1]) & 0x3ff;
p = sp->base + off;
if(p >= sp->ep){
sp->err = "bad pointer";
goto err;
}
n = 0;
continue;
}
n = *p++;
if(len + n < Domlen - 1){
if(to + n > toend){
sp->err = toolong;
goto err;
}
memmove(to, p, n);
to += n;
}
p += n;
if(*p){
if(to >= toend){
sp->err = toolong;
goto err;
}
*to++ = '.';
}
}
*to = 0;
if(pointer)
sp->p += len + 2; /* + 2 for pointer */
else
sp->p += len + 1; /* + 1 for the null domain */
return tostart;
err:
*tostart = 0;
return tostart;
}
/*
* convert the next RR from a message
*/
static RR*
convM2RR(Scan *sp)
{
RR *rp;
int type;
int class;
uchar *data;
int len;
char dname[Domlen+1];
Txt *t, **l;
retry:
NAME(dname);
USHORT(type);
USHORT(class);
rp = rralloc(type);
rp->owner = dnlookup(dname, class, 1);
rp->type = type;
ULONG(rp->ttl);
rp->ttl += now;
USHORT(len);
data = sp->p;
if(sp->p + len > sp->ep)
sp->err = toolong;
if(sp->err){
rrfree(rp);
return 0;
}
switch(type){
default:
/* unknown type, just ignore it */
sp->p = data + len;
rrfree(rp);
goto retry;
case Thinfo:
SYMBOL(rp->cpu);
SYMBOL(rp->os);
break;
case Tcname:
case Tmb:
case Tmd:
case Tmf:
case Tns:
rp->host = dnlookup(NAME(dname), Cin, 1);
break;
case Tmg:
case Tmr:
rp->mb = dnlookup(NAME(dname), Cin, 1);
break;
case Tminfo:
rp->rmb = dnlookup(NAME(dname), Cin, 1);
rp->mb = dnlookup(NAME(dname), Cin, 1);
break;
case Tmx:
USHORT(rp->pref);
rp->host = dnlookup(NAME(dname), Cin, 1);
break;
case Ta:
V4ADDR(rp->ip);
break;
case Taaaa:
V6ADDR(rp->ip);
break;
case Tptr:
rp->ptr = dnlookup(NAME(dname), Cin, 1);
break;
case Tsoa:
rp->host = dnlookup(NAME(dname), Cin, 1);
rp->rmb = dnlookup(NAME(dname), Cin, 1);
ULONG(rp->soa->serial);
ULONG(rp->soa->refresh);
ULONG(rp->soa->retry);
ULONG(rp->soa->expire);
ULONG(rp->soa->minttl);
break;
case Ttxt:
l = &rp->txt;
*l = nil;
while(sp->p-data < len){
STRING(t);
*l = t;
l = &t->next;
}
break;
case Tnull:
BYTES(rp->null->data, rp->null->dlen);
break;
case Trp:
rp->rmb = dnlookup(NAME(dname), Cin, 1);
rp->rp = dnlookup(NAME(dname), Cin, 1);
break;
case Tkey:
USHORT(rp->key->flags);
UCHAR(rp->key->proto);
UCHAR(rp->key->alg);
BYTES(rp->key->data, rp->key->dlen);
break;
case Tsig:
USHORT(rp->sig->type);
UCHAR(rp->sig->alg);
UCHAR(rp->sig->labels);
ULONG(rp->sig->ttl);
ULONG(rp->sig->exp);
ULONG(rp->sig->incep);
USHORT(rp->sig->tag);
rp->sig->signer = dnlookup(NAME(dname), Cin, 1);
BYTES(rp->sig->data, rp->sig->dlen);
break;
case Tcert:
USHORT(rp->cert->type);
USHORT(rp->cert->tag);
UCHAR(rp->cert->alg);
BYTES(rp->cert->data, rp->cert->dlen);
break;
}
if(sp->p - data != len)
sp->err = "bad RR len";
return rp;
}
/*
* convert the next question from a message
*/
static RR*
convM2Q(Scan *sp)
{
char dname[Domlen+1];
int type;
int class;
RR *rp;
NAME(dname);
USHORT(type);
USHORT(class);
if(sp->err)
return 0;
rp = rralloc(type);
rp->owner = dnlookup(dname, class, 1);
return rp;
}
static RR*
rrloop(Scan *sp, int count, int quest)
{
int i;
RR *first, *rp, **l;
if(sp->err)
return 0;
l = &first;
first = 0;
for(i = 0; i < count; i++){
rp = quest ? convM2Q(sp) : convM2RR(sp);
if(rp == 0)
break;
if(sp->err){
rrfree(rp);
break;
}
*l = rp;
l = &rp->next;
}
return first;
}
/*
* convert the next DNS from a message stream
*/
char*
convM2DNS(uchar *buf, int len, DNSmsg *m)
{
Scan scan;
Scan *sp;
char *err;
scan.base = buf;
scan.p = buf;
scan.ep = buf + len;
scan.err = 0;
sp = &scan;
memset(m, 0, sizeof(DNSmsg));
USHORT(m->id);
USHORT(m->flags);
USHORT(m->qdcount);
USHORT(m->ancount);
USHORT(m->nscount);
USHORT(m->arcount);
m->qd = rrloop(sp, m->qdcount, 1);
m->an = rrloop(sp, m->ancount, 0);
m->ns = rrloop(sp, m->nscount, 0);
err = scan.err; /* live with bad ar's */
m->ar = rrloop(sp, m->arcount, 0);
return err;
}
| 3,818 |
1,567 | #pragma once
#include "certain/errors.h"
#include "certain/plog.h"
#include "default/db_type.h"
#include "utils/hash.h"
#include "utils/header.h"
class PlogImpl : public certain::Plog {
public:
static void ParseKey(const dbtype::Slice& key, uint64_t* entity_id,
uint64_t* entry);
PlogImpl(dbtype::DB* db) : dbs_(1, db) {}
PlogImpl(const std::vector<dbtype::DB*>& dbs) : dbs_(dbs) {}
virtual int LoadMaxEntry(uint64_t entity_id, uint64_t* entry) override;
virtual int GetValue(uint64_t entity_id, uint64_t entry, uint64_t value_id,
std::string* value) override;
virtual int SetValue(uint64_t entity_id, uint64_t entry, uint64_t value_id,
const std::string& value) override;
virtual int GetRecord(uint64_t entity_id, uint64_t entry,
std::string* record) override;
virtual int SetRecord(uint64_t entity_id, uint64_t entry,
const std::string& record) override;
virtual uint32_t HashId(uint64_t entity_id) override {
return Hash(entity_id);
};
virtual int MultiSetRecords(
uint32_t hash_id,
const std::vector<certain::Plog::Record>& records) override;
virtual int RangeGetRecord(
uint64_t entity_id, uint64_t begin_entry, uint64_t end_entry,
std::vector<std::pair<uint64_t, std::string>>* records) override;
private:
static int SetValue(dbtype::DB* db, const dbtype::Slice& key,
const std::string& value);
static int GetValue(dbtype::DB* db, const dbtype::Slice& key,
std::string* value);
inline uint32_t Hash(uint64_t entity_id) {
return certain::Hash(entity_id) % dbs_.size();
}
// use inline hash function instead of virtual function for performance
inline dbtype::DB* DB(uint64_t entity_id) { return dbs_[Hash(entity_id)]; }
private:
std::vector<dbtype::DB*> dbs_;
};
| 794 |
2,151 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/caps_lock_notification_controller.h"
#include "ash/accessibility/accessibility_controller.h"
#include "ash/accessibility/test_accessibility_controller_client.h"
#include "ash/shell.h"
#include "ash/system/message_center/notification_tray.h"
#include "ash/test/ash_test_base.h"
namespace ash {
class CapsLockNotificationControllerTest : public AshTestBase {
public:
CapsLockNotificationControllerTest() = default;
~CapsLockNotificationControllerTest() override = default;
void SetUp() override {
AshTestBase::SetUp();
NotificationTray::DisableAnimationsForTest(true);
}
void TearDown() override {
NotificationTray::DisableAnimationsForTest(false);
AshTestBase::TearDown();
}
private:
DISALLOW_COPY_AND_ASSIGN(CapsLockNotificationControllerTest);
};
// Tests that a11y alert is sent on toggling caps lock.
TEST_F(CapsLockNotificationControllerTest, A11yAlert) {
auto caps_lock = std::make_unique<CapsLockNotificationController>();
TestAccessibilityControllerClient client;
AccessibilityController* controller =
Shell::Get()->accessibility_controller();
controller->SetClient(client.CreateInterfacePtrAndBind());
// Simulate turning on caps lock.
caps_lock->OnCapsLockChanged(true);
controller->FlushMojoForTest();
EXPECT_EQ(mojom::AccessibilityAlert::CAPS_ON, client.last_a11y_alert());
// Simulate turning off caps lock.
caps_lock->OnCapsLockChanged(false);
controller->FlushMojoForTest();
EXPECT_EQ(mojom::AccessibilityAlert::CAPS_OFF, client.last_a11y_alert());
}
} // namespace ash
| 549 |
324 | <gh_stars>100-1000
#ifndef __SERIAL_H__
#define __SERIAL_H__
#include "type.h"
#define SER_INF_TIMEOUT 0xFFFFFFFF
#define SER_NO_TIMEOUT 0
#define SER_OK 0
#define SER_ERR 1
// Serial interface modes (blocking or non blocking)
#define SER_MODE_BLOCKING 0
#define SER_MODE_NONBLOCKING 1
// Setup constants
#define SER_PARITY_NONE 0
#define SER_PARITY_EVEN 1
#define SER_PARITY_ODD 2
#define SER_STOPBITS_1 0
#define SER_STOPBITS_1_5 1
#define SER_STOPBITS_2 2
#define SER_DATABITS_5 5
#define SER_DATABITS_6 6
#define SER_DATABITS_7 7
#define SER_DATABITS_8 8
// Serial access functions (to be implemented by each platform)
ser_handler ser_open( const char *sername );
void ser_close( ser_handler id );
int ser_setup( ser_handler id, u32 baud, int databits, int parity, int stopbits );
u32 ser_read( ser_handler id, u8* dest, u32 maxsize );
int ser_read_byte( ser_handler id );
u32 ser_write( ser_handler id, const u8 *src, u32 size );
u32 ser_write_byte( ser_handler id, u8 data );
void ser_set_timeout_ms( ser_handler id, u32 timeout );
int ser_setupEx( ser_handler id, u32 baud, int databits, int parity, int stopbits, int Mode );
extern int read_bytes( uint8_t *pData, uint32_t size );
#endif
| 649 |
1,306 | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "heap.h"
#define ATRACE_TAG ATRACE_TAG_DALVIK
#include <cutils/trace.h>
#include <limits>
#include <vector>
#include <valgrind.h>
#include "base/stl_util.h"
#include "common_throws.h"
#include "cutils/sched_policy.h"
#include "debugger.h"
#include "gc/accounting/atomic_stack.h"
#include "gc/accounting/card_table-inl.h"
#include "gc/accounting/heap_bitmap-inl.h"
#include "gc/accounting/mod_union_table-inl.h"
#include "gc/accounting/space_bitmap-inl.h"
#include "gc/collector/mark_sweep-inl.h"
#include "gc/collector/partial_mark_sweep.h"
#include "gc/collector/sticky_mark_sweep.h"
#include "gc/space/dlmalloc_space-inl.h"
#include "gc/space/image_space.h"
#include "gc/space/large_object_space.h"
#include "gc/space/space-inl.h"
#include "image.h"
#include "invoke_arg_array_builder.h"
#include "mirror/art_field-inl.h"
#include "mirror/class-inl.h"
#include "mirror/object.h"
#include "mirror/object-inl.h"
#include "mirror/object_array-inl.h"
#include "object_utils.h"
#include "os.h"
#include "ScopedLocalRef.h"
#include "scoped_thread_state_change.h"
#include "sirt_ref.h"
#include "thread_list.h"
#include "UniquePtr.h"
#include "well_known_classes.h"
namespace art {
namespace gc {
static constexpr bool kGCALotMode = false;
static constexpr size_t kGcAlotInterval = KB;
static constexpr bool kDumpGcPerformanceOnShutdown = false;
// Minimum amount of remaining bytes before a concurrent GC is triggered.
static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
// If true, measure the total allocation time.
static constexpr bool kMeasureAllocationTime = false;
Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
double target_utilization, size_t capacity, const std::string& original_image_file_name,
bool concurrent_gc, size_t parallel_gc_threads, size_t conc_gc_threads,
bool low_memory_mode, size_t long_pause_log_threshold, size_t long_gc_log_threshold,
bool ignore_max_footprint)
: alloc_space_(NULL),
card_table_(NULL),
concurrent_gc_(concurrent_gc),
parallel_gc_threads_(parallel_gc_threads),
conc_gc_threads_(conc_gc_threads),
low_memory_mode_(low_memory_mode),
long_pause_log_threshold_(long_pause_log_threshold),
long_gc_log_threshold_(long_gc_log_threshold),
ignore_max_footprint_(ignore_max_footprint),
have_zygote_space_(false),
soft_ref_queue_lock_(NULL),
weak_ref_queue_lock_(NULL),
finalizer_ref_queue_lock_(NULL),
phantom_ref_queue_lock_(NULL),
is_gc_running_(false),
last_gc_type_(collector::kGcTypeNone),
next_gc_type_(collector::kGcTypePartial),
capacity_(capacity),
growth_limit_(growth_limit),
max_allowed_footprint_(initial_size),
native_footprint_gc_watermark_(initial_size),
native_footprint_limit_(2 * initial_size),
activity_thread_class_(NULL),
application_thread_class_(NULL),
activity_thread_(NULL),
application_thread_(NULL),
last_process_state_id_(NULL),
// Initially care about pauses in case we never get notified of process states, or if the JNI
// code becomes broken.
care_about_pause_times_(true),
concurrent_start_bytes_(concurrent_gc_ ? initial_size - kMinConcurrentRemainingBytes
: std::numeric_limits<size_t>::max()),
total_bytes_freed_ever_(0),
total_objects_freed_ever_(0),
large_object_threshold_(3 * kPageSize),
num_bytes_allocated_(0),
native_bytes_allocated_(0),
gc_memory_overhead_(0),
verify_missing_card_marks_(false),
verify_system_weaks_(false),
verify_pre_gc_heap_(false),
verify_post_gc_heap_(false),
verify_mod_union_table_(false),
min_alloc_space_size_for_sticky_gc_(2 * MB),
min_remaining_space_for_sticky_gc_(1 * MB),
last_trim_time_ms_(0),
allocation_rate_(0),
/* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
* causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
* verification is enabled, we limit the size of allocation stacks to speed up their
* searching.
*/
max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
: (kDesiredHeapVerification > kNoHeapVerification) ? KB : MB),
reference_referent_offset_(0),
reference_queue_offset_(0),
reference_queueNext_offset_(0),
reference_pendingNext_offset_(0),
finalizer_reference_zombie_offset_(0),
min_free_(min_free),
max_free_(max_free),
target_utilization_(target_utilization),
total_wait_time_(0),
total_allocation_time_(0),
verify_object_mode_(kHeapVerificationNotPermitted),
running_on_valgrind_(RUNNING_ON_VALGRIND) {
if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
LOG(INFO) << "Heap() entering";
}
live_bitmap_.reset(new accounting::HeapBitmap(this));
mark_bitmap_.reset(new accounting::HeapBitmap(this));
// Requested begin for the alloc space, to follow the mapped image and oat files
byte* requested_alloc_space_begin = NULL;
std::string image_file_name(original_image_file_name);
if (!image_file_name.empty()) {
space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name);
CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
AddContinuousSpace(image_space);
// Oat files referenced by image files immediately follow them in memory, ensure alloc space
// isn't going to get in the middle
byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
CHECK_GT(oat_file_end_addr, image_space->End());
if (oat_file_end_addr > requested_alloc_space_begin) {
requested_alloc_space_begin =
reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
kPageSize));
}
}
alloc_space_ = space::DlMallocSpace::Create(Runtime::Current()->IsZygote() ? "zygote space" : "alloc space",
initial_size,
growth_limit, capacity,
requested_alloc_space_begin);
CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
AddContinuousSpace(alloc_space_);
// Allocate the large object space.
const bool kUseFreeListSpaceForLOS = false;
if (kUseFreeListSpaceForLOS) {
large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
} else {
large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
}
CHECK(large_object_space_ != NULL) << "Failed to create large object space";
AddDiscontinuousSpace(large_object_space_);
// Compute heap capacity. Continuous spaces are sorted in order of Begin().
byte* heap_begin = continuous_spaces_.front()->Begin();
size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
if (continuous_spaces_.back()->IsDlMallocSpace()) {
heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
}
// Allocate the card table.
card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
CHECK(card_table_.get() != NULL) << "Failed to create card table";
image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
// TODO: Count objects in the image space here.
num_bytes_allocated_ = 0;
// Default mark stack size in bytes.
static const size_t default_mark_stack_size = 64 * KB;
mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
max_allocation_stack_size_));
live_stack_.reset(accounting::ObjectStack::Create("live stack",
max_allocation_stack_size_));
// It's still too early to take a lock because there are no threads yet, but we can create locks
// now. We don't create it earlier to make it clear that you can't use locks during heap
// initialization.
gc_complete_lock_ = new Mutex("GC complete lock");
gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
*gc_complete_lock_));
// Create the reference queue locks, this is required so for parallel object scanning in the GC.
soft_ref_queue_lock_ = new Mutex("Soft reference queue lock");
weak_ref_queue_lock_ = new Mutex("Weak reference queue lock");
finalizer_ref_queue_lock_ = new Mutex("Finalizer reference queue lock");
phantom_ref_queue_lock_ = new Mutex("Phantom reference queue lock");
last_gc_time_ns_ = NanoTime();
last_gc_size_ = GetBytesAllocated();
if (ignore_max_footprint_) {
SetIdealFootprint(std::numeric_limits<size_t>::max());
concurrent_start_bytes_ = max_allowed_footprint_;
}
// Create our garbage collectors.
for (size_t i = 0; i < 2; ++i) {
const bool concurrent = i != 0;
mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
}
CHECK_NE(max_allowed_footprint_, 0U);
if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
LOG(INFO) << "Heap() exiting";
}
}
void Heap::CreateThreadPool() {
const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
if (num_threads != 0) {
thread_pool_.reset(new ThreadPool(num_threads));
}
}
void Heap::DeleteThreadPool() {
thread_pool_.reset(nullptr);
}
static bool ReadStaticInt(JNIEnvExt* env, jclass clz, const char* name, int* out_value) {
CHECK(out_value != NULL);
jfieldID field = env->GetStaticFieldID(clz, name, "I");
if (field == NULL) {
env->ExceptionClear();
return false;
}
*out_value = env->GetStaticIntField(clz, field);
return true;
}
void Heap::ListenForProcessStateChange() {
VLOG(heap) << "Heap notified of process state change";
Thread* self = Thread::Current();
JNIEnvExt* env = self->GetJniEnv();
if (!have_zygote_space_) {
return;
}
if (activity_thread_class_ == NULL) {
jclass clz = env->FindClass("android/app/ActivityThread");
if (clz == NULL) {
env->ExceptionClear();
LOG(WARNING) << "Could not find activity thread class in process state change";
return;
}
activity_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
}
if (activity_thread_class_ != NULL && activity_thread_ == NULL) {
jmethodID current_activity_method = env->GetStaticMethodID(activity_thread_class_,
"currentActivityThread",
"()Landroid/app/ActivityThread;");
if (current_activity_method == NULL) {
env->ExceptionClear();
LOG(WARNING) << "Could not get method for currentActivityThread";
return;
}
jobject obj = env->CallStaticObjectMethod(activity_thread_class_, current_activity_method);
if (obj == NULL) {
env->ExceptionClear();
LOG(WARNING) << "Could not get current activity";
return;
}
activity_thread_ = env->NewGlobalRef(obj);
}
if (process_state_cares_about_pause_time_.empty()) {
// Just attempt to do this the first time.
jclass clz = env->FindClass("android/app/ActivityManager");
if (clz == NULL) {
LOG(WARNING) << "Activity manager class is null";
return;
}
ScopedLocalRef<jclass> activity_manager(env, clz);
std::vector<const char*> care_about_pauses;
care_about_pauses.push_back("PROCESS_STATE_TOP");
care_about_pauses.push_back("PROCESS_STATE_IMPORTANT_BACKGROUND");
// Attempt to read the constants and classify them as whether or not we care about pause times.
for (size_t i = 0; i < care_about_pauses.size(); ++i) {
int process_state = 0;
if (ReadStaticInt(env, activity_manager.get(), care_about_pauses[i], &process_state)) {
process_state_cares_about_pause_time_.insert(process_state);
VLOG(heap) << "Adding process state " << process_state
<< " to set of states which care about pause time";
}
}
}
if (application_thread_class_ == NULL) {
jclass clz = env->FindClass("android/app/ActivityThread$ApplicationThread");
if (clz == NULL) {
env->ExceptionClear();
LOG(WARNING) << "Could not get application thread class";
return;
}
application_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
last_process_state_id_ = env->GetFieldID(application_thread_class_, "mLastProcessState", "I");
if (last_process_state_id_ == NULL) {
env->ExceptionClear();
LOG(WARNING) << "Could not get last process state member";
return;
}
}
if (application_thread_class_ != NULL && application_thread_ == NULL) {
jmethodID get_application_thread =
env->GetMethodID(activity_thread_class_, "getApplicationThread",
"()Landroid/app/ActivityThread$ApplicationThread;");
if (get_application_thread == NULL) {
LOG(WARNING) << "Could not get method ID for get application thread";
return;
}
jobject obj = env->CallObjectMethod(activity_thread_, get_application_thread);
if (obj == NULL) {
LOG(WARNING) << "Could not get application thread";
return;
}
application_thread_ = env->NewGlobalRef(obj);
}
if (application_thread_ != NULL && last_process_state_id_ != NULL) {
int process_state = env->GetIntField(application_thread_, last_process_state_id_);
env->ExceptionClear();
care_about_pause_times_ = process_state_cares_about_pause_time_.find(process_state) !=
process_state_cares_about_pause_time_.end();
VLOG(heap) << "New process state " << process_state
<< " care about pauses " << care_about_pause_times_;
}
}
void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
DCHECK(space != NULL);
DCHECK(space->GetLiveBitmap() != NULL);
live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
DCHECK(space->GetMarkBitmap() != NULL);
mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
continuous_spaces_.push_back(space);
if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
alloc_space_ = space->AsDlMallocSpace();
}
// Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
[](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
return a->Begin() < b->Begin();
});
// Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
// avoid redundant marking.
bool seen_zygote = false, seen_alloc = false;
for (const auto& space : continuous_spaces_) {
if (space->IsImageSpace()) {
DCHECK(!seen_zygote);
DCHECK(!seen_alloc);
} else if (space->IsZygoteSpace()) {
DCHECK(!seen_alloc);
seen_zygote = true;
} else if (space->IsDlMallocSpace()) {
seen_alloc = true;
}
}
}
void Heap::RegisterGCAllocation(size_t bytes) {
if (this != NULL) {
gc_memory_overhead_.fetch_add(bytes);
}
}
void Heap::RegisterGCDeAllocation(size_t bytes) {
if (this != NULL) {
gc_memory_overhead_.fetch_sub(bytes);
}
}
void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
DCHECK(space != NULL);
DCHECK(space->GetLiveObjects() != NULL);
live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
DCHECK(space->GetMarkObjects() != NULL);
mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
discontinuous_spaces_.push_back(space);
}
void Heap::DumpGcPerformanceInfo(std::ostream& os) {
// Dump cumulative timings.
os << "Dumping cumulative Gc timings\n";
uint64_t total_duration = 0;
// Dump cumulative loggers for each GC type.
uint64_t total_paused_time = 0;
for (const auto& collector : mark_sweep_collectors_) {
CumulativeLogger& logger = collector->GetCumulativeTimings();
if (logger.GetTotalNs() != 0) {
os << Dumpable<CumulativeLogger>(logger);
const uint64_t total_ns = logger.GetTotalNs();
const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
const uint64_t freed_bytes = collector->GetTotalFreedBytes();
const uint64_t freed_objects = collector->GetTotalFreedObjects();
os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
<< collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
<< collector->GetName() << " freed: " << freed_objects
<< " objects with total size " << PrettySize(freed_bytes) << "\n"
<< collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
<< PrettySize(freed_bytes / seconds) << "/s\n";
total_duration += total_ns;
total_paused_time += total_pause_ns;
}
}
uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
size_t total_objects_allocated = GetObjectsAllocatedEver();
size_t total_bytes_allocated = GetBytesAllocatedEver();
if (total_duration != 0) {
const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
os << "Mean GC size throughput: "
<< PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
os << "Mean GC object throughput: "
<< (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
}
os << "Total number of allocations: " << total_objects_allocated << "\n";
os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
if (kMeasureAllocationTime) {
os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
<< "\n";
}
os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
}
Heap::~Heap() {
if (kDumpGcPerformanceOnShutdown) {
DumpGcPerformanceInfo(LOG(INFO));
}
STLDeleteElements(&mark_sweep_collectors_);
// If we don't reset then the mark stack complains in it's destructor.
allocation_stack_->Reset();
live_stack_->Reset();
VLOG(heap) << "~Heap()";
// We can't take the heap lock here because there might be a daemon thread suspended with the
// heap lock held. We know though that no non-daemon threads are executing, and we know that
// all daemon threads are suspended, and we also know that the threads list have been deleted, so
// those threads can't resume. We're the only running thread, and we can do whatever we like...
STLDeleteElements(&continuous_spaces_);
STLDeleteElements(&discontinuous_spaces_);
delete gc_complete_lock_;
delete soft_ref_queue_lock_;
delete weak_ref_queue_lock_;
delete finalizer_ref_queue_lock_;
delete phantom_ref_queue_lock_;
}
space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
bool fail_ok) const {
for (const auto& space : continuous_spaces_) {
if (space->Contains(obj)) {
return space;
}
}
if (!fail_ok) {
LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
}
return NULL;
}
space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
bool fail_ok) const {
for (const auto& space : discontinuous_spaces_) {
if (space->Contains(obj)) {
return space;
}
}
if (!fail_ok) {
LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
}
return NULL;
}
space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
space::Space* result = FindContinuousSpaceFromObject(obj, true);
if (result != NULL) {
return result;
}
return FindDiscontinuousSpaceFromObject(obj, true);
}
space::ImageSpace* Heap::GetImageSpace() const {
for (const auto& space : continuous_spaces_) {
if (space->IsImageSpace()) {
return space->AsImageSpace();
}
}
return NULL;
}
static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
if (used_bytes < chunk_size) {
size_t chunk_free_bytes = chunk_size - used_bytes;
size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
}
}
mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
(c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
strlen(ClassHelper(c).GetDescriptor()) == 0);
DCHECK_GE(byte_count, sizeof(mirror::Object));
mirror::Object* obj = NULL;
size_t bytes_allocated = 0;
uint64_t allocation_start = 0;
if (UNLIKELY(kMeasureAllocationTime)) {
allocation_start = NanoTime() / kTimeAdjust;
}
// We need to have a zygote space or else our newly allocated large object can end up in the
// Zygote resulting in it being prematurely freed.
// We can only do this for primitive objects since large objects will not be within the card table
// range. This also means that we rely on SetClass not dirtying the object's card.
bool large_object_allocation =
byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray();
if (UNLIKELY(large_object_allocation)) {
obj = Allocate(self, large_object_space_, byte_count, &bytes_allocated);
// Make sure that our large object didn't get placed anywhere within the space interval or else
// it breaks the immune range.
DCHECK(obj == NULL ||
reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
} else {
obj = Allocate(self, alloc_space_, byte_count, &bytes_allocated);
// Ensure that we did not allocate into a zygote space.
DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
}
if (LIKELY(obj != NULL)) {
obj->SetClass(c);
// Record allocation after since we want to use the atomic add for the atomic fence to guard
// the SetClass since we do not want the class to appear NULL in another thread.
RecordAllocation(bytes_allocated, obj);
if (Dbg::IsAllocTrackingEnabled()) {
Dbg::RecordAllocation(c, byte_count);
}
if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_)) {
// The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
SirtRef<mirror::Object> ref(self, obj);
RequestConcurrentGC(self);
}
if (kDesiredHeapVerification > kNoHeapVerification) {
VerifyObject(obj);
}
if (UNLIKELY(kMeasureAllocationTime)) {
total_allocation_time_.fetch_add(NanoTime() / kTimeAdjust - allocation_start);
}
return obj;
} else {
std::ostringstream oss;
int64_t total_bytes_free = GetFreeMemory();
oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
<< " free bytes";
// If the allocation failed due to fragmentation, print out the largest continuous allocation.
if (!large_object_allocation && total_bytes_free >= byte_count) {
size_t max_contiguous_allocation = 0;
for (const auto& space : continuous_spaces_) {
if (space->IsDlMallocSpace()) {
space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
}
}
oss << "; failed due to fragmentation (largest possible contiguous allocation "
<< max_contiguous_allocation << " bytes)";
}
self->ThrowOutOfMemoryError(oss.str().c_str());
return NULL;
}
}
bool Heap::IsHeapAddress(const mirror::Object* obj) {
// Note: we deliberately don't take the lock here, and mustn't test anything that would
// require taking the lock.
if (obj == NULL) {
return true;
}
if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
return false;
}
return FindSpaceFromObject(obj, true) != NULL;
}
bool Heap::IsLiveObjectLocked(const mirror::Object* obj, bool search_allocation_stack,
bool search_live_stack, bool sorted) {
// Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
if (obj == NULL || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
return false;
}
space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
space::DiscontinuousSpace* d_space = NULL;
if (c_space != NULL) {
if (c_space->GetLiveBitmap()->Test(obj)) {
return true;
}
} else {
d_space = FindDiscontinuousSpaceFromObject(obj, true);
if (d_space != NULL) {
if (d_space->GetLiveObjects()->Test(obj)) {
return true;
}
}
}
// This is covering the allocation/live stack swapping that is done without mutators suspended.
for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
if (i > 0) {
NanoSleep(MsToNs(10));
}
if (search_allocation_stack) {
if (sorted) {
if (allocation_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
return true;
}
} else if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj))) {
return true;
}
}
if (search_live_stack) {
if (sorted) {
if (live_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
return true;
}
} else if (live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
return true;
}
}
}
// We need to check the bitmaps again since there is a race where we mark something as live and
// then clear the stack containing it.
if (c_space != NULL) {
if (c_space->GetLiveBitmap()->Test(obj)) {
return true;
}
} else {
d_space = FindDiscontinuousSpaceFromObject(obj, true);
if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
return true;
}
}
return false;
}
void Heap::VerifyObjectImpl(const mirror::Object* obj) {
if (Thread::Current() == NULL ||
Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
return;
}
VerifyObjectBody(obj);
}
void Heap::DumpSpaces() {
for (const auto& space : continuous_spaces_) {
accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
LOG(INFO) << space << " " << *space << "\n"
<< live_bitmap << " " << *live_bitmap << "\n"
<< mark_bitmap << " " << *mark_bitmap;
}
for (const auto& space : discontinuous_spaces_) {
LOG(INFO) << space << " " << *space << "\n";
}
}
void Heap::VerifyObjectBody(const mirror::Object* obj) {
CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
// Ignore early dawn of the universe verifications.
if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.load()) < 10 * KB)) {
return;
}
const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
mirror::Object::ClassOffset().Int32Value();
const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
if (UNLIKELY(c == NULL)) {
LOG(FATAL) << "Null class in object: " << obj;
} else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
}
// Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
// Note: we don't use the accessors here as they have internal sanity checks
// that we don't want to run
raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
CHECK_EQ(c_c, c_c_c);
if (verify_object_mode_ != kVerifyAllFast) {
// TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
// heap_bitmap_lock_.
if (!IsLiveObjectLocked(obj)) {
DumpSpaces();
LOG(FATAL) << "Object is dead: " << obj;
}
if (!IsLiveObjectLocked(c)) {
LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
}
}
}
void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
DCHECK(obj != NULL);
reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
}
void Heap::VerifyHeap() {
ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
}
inline void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
DCHECK(obj != NULL);
DCHECK_GT(size, 0u);
num_bytes_allocated_.fetch_add(size);
if (Runtime::Current()->HasStatsEnabled()) {
RuntimeStats* thread_stats = Thread::Current()->GetStats();
++thread_stats->allocated_objects;
thread_stats->allocated_bytes += size;
// TODO: Update these atomically.
RuntimeStats* global_stats = Runtime::Current()->GetStats();
++global_stats->allocated_objects;
global_stats->allocated_bytes += size;
}
// This is safe to do since the GC will never free objects which are neither in the allocation
// stack or the live bitmap.
while (!allocation_stack_->AtomicPushBack(obj)) {
CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
}
}
void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
num_bytes_allocated_.fetch_sub(freed_bytes);
if (Runtime::Current()->HasStatsEnabled()) {
RuntimeStats* thread_stats = Thread::Current()->GetStats();
thread_stats->freed_objects += freed_objects;
thread_stats->freed_bytes += freed_bytes;
// TODO: Do this concurrently.
RuntimeStats* global_stats = Runtime::Current()->GetStats();
global_stats->freed_objects += freed_objects;
global_stats->freed_bytes += freed_bytes;
}
}
inline bool Heap::IsOutOfMemoryOnAllocation(size_t alloc_size, bool grow) {
size_t new_footprint = num_bytes_allocated_ + alloc_size;
if (UNLIKELY(new_footprint > max_allowed_footprint_)) {
if (UNLIKELY(new_footprint > growth_limit_)) {
return true;
}
if (!concurrent_gc_) {
if (!grow) {
return true;
} else {
max_allowed_footprint_ = new_footprint;
}
}
}
return false;
}
inline mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
bool grow, size_t* bytes_allocated) {
if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
return NULL;
}
return space->Alloc(self, alloc_size, bytes_allocated);
}
// DlMallocSpace-specific version.
inline mirror::Object* Heap::TryToAllocate(Thread* self, space::DlMallocSpace* space, size_t alloc_size,
bool grow, size_t* bytes_allocated) {
if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
return NULL;
}
if (LIKELY(!running_on_valgrind_)) {
return space->AllocNonvirtual(self, alloc_size, bytes_allocated);
} else {
return space->Alloc(self, alloc_size, bytes_allocated);
}
}
template <class T>
inline mirror::Object* Heap::Allocate(Thread* self, T* space, size_t alloc_size,
size_t* bytes_allocated) {
// Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
// done in the runnable state where suspension is expected.
DCHECK_EQ(self->GetState(), kRunnable);
self->AssertThreadSuspensionIsAllowable();
mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
if (ptr != NULL) {
return ptr;
}
return AllocateInternalWithGc(self, space, alloc_size, bytes_allocated);
}
mirror::Object* Heap::AllocateInternalWithGc(Thread* self, space::AllocSpace* space,
size_t alloc_size, size_t* bytes_allocated) {
mirror::Object* ptr;
// The allocation failed. If the GC is running, block until it completes, and then retry the
// allocation.
collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
if (last_gc != collector::kGcTypeNone) {
// A GC was in progress and we blocked, retry allocation now that memory has been freed.
ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
if (ptr != NULL) {
return ptr;
}
}
// Loop through our different Gc types and try to Gc until we get enough free memory.
for (size_t i = static_cast<size_t>(last_gc) + 1;
i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
bool run_gc = false;
collector::GcType gc_type = static_cast<collector::GcType>(i);
switch (gc_type) {
case collector::kGcTypeSticky: {
const size_t alloc_space_size = alloc_space_->Size();
run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
break;
}
case collector::kGcTypePartial:
run_gc = have_zygote_space_;
break;
case collector::kGcTypeFull:
run_gc = true;
break;
default:
break;
}
if (run_gc) {
// If we actually ran a different type of Gc than requested, we can skip the index forwards.
collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
i = static_cast<size_t>(gc_type_ran);
// Did we free sufficient memory for the allocation to succeed?
ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
if (ptr != NULL) {
return ptr;
}
}
}
// Allocations have failed after GCs; this is an exceptional state.
// Try harder, growing the heap if necessary.
ptr = TryToAllocate(self, space, alloc_size, true, bytes_allocated);
if (ptr != NULL) {
return ptr;
}
// Most allocations should have succeeded by now, so the heap is really full, really fragmented,
// or the requested size is really big. Do another GC, collecting SoftReferences this time. The
// VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
// OLD-TODO: wait for the finalizers from the previous GC to finish
VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
<< " allocation";
// We don't need a WaitForConcurrentGcToComplete here either.
CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
return TryToAllocate(self, space, alloc_size, true, bytes_allocated);
}
void Heap::SetTargetHeapUtilization(float target) {
DCHECK_GT(target, 0.0f); // asserted in Java code
DCHECK_LT(target, 1.0f);
target_utilization_ = target;
}
size_t Heap::GetObjectsAllocated() const {
size_t total = 0;
typedef std::vector<space::ContinuousSpace*>::const_iterator It;
for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
space::ContinuousSpace* space = *it;
if (space->IsDlMallocSpace()) {
total += space->AsDlMallocSpace()->GetObjectsAllocated();
}
}
typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
space::DiscontinuousSpace* space = *it;
total += space->AsLargeObjectSpace()->GetObjectsAllocated();
}
return total;
}
size_t Heap::GetObjectsAllocatedEver() const {
size_t total = 0;
typedef std::vector<space::ContinuousSpace*>::const_iterator It;
for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
space::ContinuousSpace* space = *it;
if (space->IsDlMallocSpace()) {
total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
}
}
typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
space::DiscontinuousSpace* space = *it;
total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
}
return total;
}
size_t Heap::GetBytesAllocatedEver() const {
size_t total = 0;
typedef std::vector<space::ContinuousSpace*>::const_iterator It;
for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
space::ContinuousSpace* space = *it;
if (space->IsDlMallocSpace()) {
total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
}
}
typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
space::DiscontinuousSpace* space = *it;
total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
}
return total;
}
class InstanceCounter {
public:
InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
: classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
}
void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
for (size_t i = 0; i < classes_.size(); ++i) {
const mirror::Class* instance_class = o->GetClass();
if (use_is_assignable_from_) {
if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
++counts_[i];
}
} else {
if (instance_class == classes_[i]) {
++counts_[i];
}
}
}
}
private:
const std::vector<mirror::Class*>& classes_;
bool use_is_assignable_from_;
uint64_t* const counts_;
DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
};
void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
uint64_t* counts) {
// We only want reachable instances, so do a GC. This also ensures that the alloc stack
// is empty, so the live bitmap is the only place we need to look.
Thread* self = Thread::Current();
self->TransitionFromRunnableToSuspended(kNative);
CollectGarbage(false);
self->TransitionFromSuspendedToRunnable();
InstanceCounter counter(classes, use_is_assignable_from, counts);
ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
GetLiveBitmap()->Visit(counter);
}
class InstanceCollector {
public:
InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
: class_(c), max_count_(max_count), instances_(instances) {
}
void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
const mirror::Class* instance_class = o->GetClass();
if (instance_class == class_) {
if (max_count_ == 0 || instances_.size() < max_count_) {
instances_.push_back(const_cast<mirror::Object*>(o));
}
}
}
private:
mirror::Class* class_;
uint32_t max_count_;
std::vector<mirror::Object*>& instances_;
DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
};
void Heap::GetInstances(mirror::Class* c, int32_t max_count,
std::vector<mirror::Object*>& instances) {
// We only want reachable instances, so do a GC. This also ensures that the alloc stack
// is empty, so the live bitmap is the only place we need to look.
Thread* self = Thread::Current();
self->TransitionFromRunnableToSuspended(kNative);
CollectGarbage(false);
self->TransitionFromSuspendedToRunnable();
InstanceCollector collector(c, max_count, instances);
ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
GetLiveBitmap()->Visit(collector);
}
class ReferringObjectsFinder {
public:
ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
std::vector<mirror::Object*>& referring_objects)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
: object_(object), max_count_(max_count), referring_objects_(referring_objects) {
}
// For bitmap Visit.
// TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
// annotalysis on visitors.
void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
collector::MarkSweep::VisitObjectReferences(o, *this);
}
// For MarkSweep::VisitObjectReferences.
void operator()(const mirror::Object* referrer, const mirror::Object* object,
const MemberOffset&, bool) const {
if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
}
}
private:
mirror::Object* object_;
uint32_t max_count_;
std::vector<mirror::Object*>& referring_objects_;
DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
};
void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
std::vector<mirror::Object*>& referring_objects) {
// We only want reachable instances, so do a GC. This also ensures that the alloc stack
// is empty, so the live bitmap is the only place we need to look.
Thread* self = Thread::Current();
self->TransitionFromRunnableToSuspended(kNative);
CollectGarbage(false);
self->TransitionFromSuspendedToRunnable();
ReferringObjectsFinder finder(o, max_count, referring_objects);
ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
GetLiveBitmap()->Visit(finder);
}
void Heap::CollectGarbage(bool clear_soft_references) {
// Even if we waited for a GC we still need to do another GC since weaks allocated during the
// last GC will not have necessarily been cleared.
Thread* self = Thread::Current();
WaitForConcurrentGcToComplete(self);
CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
}
void Heap::PreZygoteFork() {
static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
// Do this before acquiring the zygote creation lock so that we don't get lock order violations.
CollectGarbage(false);
Thread* self = Thread::Current();
MutexLock mu(self, zygote_creation_lock_);
// Try to see if we have any Zygote spaces.
if (have_zygote_space_) {
return;
}
VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
{
// Flush the alloc stack.
WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
FlushAllocStack();
}
// Turns the current alloc space into a Zygote space and obtain the new alloc space composed
// of the remaining available heap memory.
space::DlMallocSpace* zygote_space = alloc_space_;
alloc_space_ = zygote_space->CreateZygoteSpace("alloc space");
alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
// Change the GC retention policy of the zygote space to only collect when full.
zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
AddContinuousSpace(alloc_space_);
have_zygote_space_ = true;
// Reset the cumulative loggers since we now have a few additional timing phases.
for (const auto& collector : mark_sweep_collectors_) {
collector->ResetCumulativeStatistics();
}
}
void Heap::FlushAllocStack() {
MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
allocation_stack_.get());
allocation_stack_->Reset();
}
void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
accounting::ObjectStack* stack) {
mirror::Object** limit = stack->End();
for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
const mirror::Object* obj = *it;
DCHECK(obj != NULL);
if (LIKELY(bitmap->HasAddress(obj))) {
bitmap->Set(obj);
} else {
large_objects->Set(obj);
}
}
}
const char* gc_cause_and_type_strings[3][4] = {
{"", "GC Alloc Sticky", "GC Alloc Partial", "GC Alloc Full"},
{"", "GC Background Sticky", "GC Background Partial", "GC Background Full"},
{"", "GC Explicit Sticky", "GC Explicit Partial", "GC Explicit Full"}};
collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
bool clear_soft_references) {
Thread* self = Thread::Current();
ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Locks::mutator_lock_->AssertNotHeld(self);
if (self->IsHandlingStackOverflow()) {
LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
}
// Ensure there is only one GC at a time.
bool start_collect = false;
while (!start_collect) {
{
MutexLock mu(self, *gc_complete_lock_);
if (!is_gc_running_) {
is_gc_running_ = true;
start_collect = true;
}
}
if (!start_collect) {
// TODO: timinglog this.
WaitForConcurrentGcToComplete(self);
// TODO: if another thread beat this one to do the GC, perhaps we should just return here?
// Not doing at the moment to ensure soft references are cleared.
}
}
gc_complete_lock_->AssertNotHeld(self);
if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
++Runtime::Current()->GetStats()->gc_for_alloc_count;
++Thread::Current()->GetStats()->gc_for_alloc_count;
}
uint64_t gc_start_time_ns = NanoTime();
uint64_t gc_start_size = GetBytesAllocated();
// Approximate allocation rate in bytes / second.
if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
}
uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
if (ms_delta != 0) {
allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
}
if (gc_type == collector::kGcTypeSticky &&
alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
gc_type = collector::kGcTypePartial;
}
DCHECK_LT(gc_type, collector::kGcTypeMax);
DCHECK_NE(gc_type, collector::kGcTypeNone);
DCHECK_LE(gc_cause, kGcCauseExplicit);
ATRACE_BEGIN(gc_cause_and_type_strings[gc_cause][gc_type]);
collector::MarkSweep* collector = NULL;
for (const auto& cur_collector : mark_sweep_collectors_) {
if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
collector = cur_collector;
break;
}
}
CHECK(collector != NULL)
<< "Could not find garbage collector with concurrent=" << concurrent_gc_
<< " and type=" << gc_type;
collector->clear_soft_references_ = clear_soft_references;
collector->Run();
total_objects_freed_ever_ += collector->GetFreedObjects();
total_bytes_freed_ever_ += collector->GetFreedBytes();
if (care_about_pause_times_) {
const size_t duration = collector->GetDurationNs();
std::vector<uint64_t> pauses = collector->GetPauseTimes();
// GC for alloc pauses the allocating thread, so consider it as a pause.
bool was_slow = duration > long_gc_log_threshold_ ||
(gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
if (!was_slow) {
for (uint64_t pause : pauses) {
was_slow = was_slow || pause > long_pause_log_threshold_;
}
}
if (was_slow) {
const size_t percent_free = GetPercentFree();
const size_t current_heap_size = GetBytesAllocated();
const size_t total_memory = GetTotalMemory();
std::ostringstream pause_string;
for (size_t i = 0; i < pauses.size(); ++i) {
pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
<< ((i != pauses.size() - 1) ? ", " : "");
}
LOG(INFO) << gc_cause << " " << collector->GetName()
<< " GC freed " << collector->GetFreedObjects() << "("
<< PrettySize(collector->GetFreedBytes()) << ") AllocSpace objects, "
<< collector->GetFreedLargeObjects() << "("
<< PrettySize(collector->GetFreedLargeObjectBytes()) << ") LOS objects, "
<< percent_free << "% free, " << PrettySize(current_heap_size) << "/"
<< PrettySize(total_memory) << ", " << "paused " << pause_string.str()
<< " total " << PrettyDuration((duration / 1000) * 1000);
if (VLOG_IS_ON(heap)) {
LOG(INFO) << Dumpable<base::TimingLogger>(collector->GetTimings());
}
}
}
{
MutexLock mu(self, *gc_complete_lock_);
is_gc_running_ = false;
last_gc_type_ = gc_type;
// Wake anyone who may have been waiting for the GC to complete.
gc_complete_cond_->Broadcast(self);
}
ATRACE_END();
// Inform DDMS that a GC completed.
Dbg::GcDidFinish();
return gc_type;
}
void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::TimingLogger& timings,
collector::GcType gc_type) {
if (gc_type == collector::kGcTypeSticky) {
// Don't need to do anything for mod union table in this case since we are only scanning dirty
// cards.
return;
}
base::TimingLogger::ScopedSplit split("UpdateModUnionTable", &timings);
// Update zygote mod union table.
if (gc_type == collector::kGcTypePartial) {
base::TimingLogger::ScopedSplit split("UpdateZygoteModUnionTable", &timings);
zygote_mod_union_table_->Update();
timings.NewSplit("ZygoteMarkReferences");
zygote_mod_union_table_->MarkReferences(mark_sweep);
}
// Processes the cards we cleared earlier and adds their objects into the mod-union table.
timings.NewSplit("UpdateModUnionTable");
image_mod_union_table_->Update();
// Scans all objects in the mod-union table.
timings.NewSplit("MarkImageToAllocSpaceReferences");
image_mod_union_table_->MarkReferences(mark_sweep);
}
static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
if (root == obj) {
LOG(INFO) << "Object " << obj << " is a root";
}
}
class ScanVisitor {
public:
void operator()(const mirror::Object* obj) const {
LOG(ERROR) << "Would have rescanned object " << obj;
}
};
// Verify a reference from an object.
class VerifyReferenceVisitor {
public:
explicit VerifyReferenceVisitor(Heap* heap)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
: heap_(heap), failed_(false) {}
bool Failed() const {
return failed_;
}
// TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
// analysis on visitors.
void operator()(const mirror::Object* obj, const mirror::Object* ref,
const MemberOffset& offset, bool /* is_static */) const
NO_THREAD_SAFETY_ANALYSIS {
// Verify that the reference is live.
if (UNLIKELY(ref != NULL && !IsLive(ref))) {
accounting::CardTable* card_table = heap_->GetCardTable();
accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
accounting::ObjectStack* live_stack = heap_->live_stack_.get();
if (!failed_) {
// Print message on only on first failure to prevent spam.
LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
failed_ = true;
}
if (obj != nullptr) {
byte* card_addr = card_table->CardFromAddr(obj);
LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
<< offset << "\n card value = " << static_cast<int>(*card_addr);
if (heap_->IsHeapAddress(obj->GetClass())) {
LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
} else {
LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
}
// Attmept to find the class inside of the recently freed objects.
space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
if (ref_space->IsDlMallocSpace()) {
space::DlMallocSpace* space = ref_space->AsDlMallocSpace();
mirror::Class* ref_class = space->FindRecentFreedObject(ref);
if (ref_class != nullptr) {
LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
<< PrettyClass(ref_class);
} else {
LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
}
}
if (ref->GetClass() != nullptr && heap_->IsHeapAddress(ref->GetClass()) &&
ref->GetClass()->IsClass()) {
LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
} else {
LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
<< ") is not a valid heap address";
}
card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
void* cover_begin = card_table->AddrFromCard(card_addr);
void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
accounting::CardTable::kCardSize);
LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
<< "-" << cover_end;
accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
// Print out how the object is live.
if (bitmap != NULL && bitmap->Test(obj)) {
LOG(ERROR) << "Object " << obj << " found in live bitmap";
}
if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
LOG(ERROR) << "Object " << obj << " found in allocation stack";
}
if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
LOG(ERROR) << "Object " << obj << " found in live stack";
}
if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
LOG(ERROR) << "Ref " << ref << " found in allocation stack";
}
if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
LOG(ERROR) << "Ref " << ref << " found in live stack";
}
// Attempt to see if the card table missed the reference.
ScanVisitor scan_visitor;
byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
card_table->Scan(bitmap, byte_cover_begin,
byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
// Search to see if any of the roots reference our object.
void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
// Search to see if any of the roots reference our reference.
arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
} else {
LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
}
}
}
bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
return heap_->IsLiveObjectLocked(obj, true, false, true);
}
static void VerifyRoots(const mirror::Object* root, void* arg) {
VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
(*visitor)(NULL, root, MemberOffset(0), true);
}
private:
Heap* const heap_;
mutable bool failed_;
};
// Verify all references within an object, for use with HeapBitmap::Visit.
class VerifyObjectVisitor {
public:
explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
void operator()(const mirror::Object* obj) const
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
// Note: we are verifying the references in obj but not obj itself, this is because obj must
// be live or else how did we find it in the live bitmap?
VerifyReferenceVisitor visitor(heap_);
// The class doesn't count as a reference but we should verify it anyways.
visitor(obj, obj->GetClass(), MemberOffset(0), false);
collector::MarkSweep::VisitObjectReferences(obj, visitor);
failed_ = failed_ || visitor.Failed();
}
bool Failed() const {
return failed_;
}
private:
Heap* const heap_;
mutable bool failed_;
};
// Must do this with mutators suspended since we are directly accessing the allocation stacks.
bool Heap::VerifyHeapReferences() {
Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
// Lets sort our allocation stacks so that we can efficiently binary search them.
allocation_stack_->Sort();
live_stack_->Sort();
// Perform the verification.
VerifyObjectVisitor visitor(this);
Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
GetLiveBitmap()->Visit(visitor);
// Verify objects in the allocation stack since these will be objects which were:
// 1. Allocated prior to the GC (pre GC verification).
// 2. Allocated during the GC (pre sweep GC verification).
for (mirror::Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
visitor(*it);
}
// We don't want to verify the objects in the live stack since they themselves may be
// pointing to dead objects if they are not reachable.
if (visitor.Failed()) {
// Dump mod-union tables.
image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
DumpSpaces();
return false;
}
return true;
}
class VerifyReferenceCardVisitor {
public:
VerifyReferenceCardVisitor(Heap* heap, bool* failed)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
Locks::heap_bitmap_lock_)
: heap_(heap), failed_(failed) {
}
// TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
// annotalysis on visitors.
void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
// Filter out class references since changing an object's class does not mark the card as dirty.
// Also handles large objects, since the only reference they hold is a class reference.
if (ref != NULL && !ref->IsClass()) {
accounting::CardTable* card_table = heap_->GetCardTable();
// If the object is not dirty and it is referencing something in the live stack other than
// class, then it must be on a dirty card.
if (!card_table->AddrIsInCardTable(obj)) {
LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
*failed_ = true;
} else if (!card_table->IsDirty(obj)) {
// Card should be either kCardDirty if it got re-dirtied after we aged it, or
// kCardDirty - 1 if it didnt get touched since we aged it.
accounting::ObjectStack* live_stack = heap_->live_stack_.get();
if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
LOG(ERROR) << "Object " << obj << " found in live stack";
}
if (heap_->GetLiveBitmap()->Test(obj)) {
LOG(ERROR) << "Object " << obj << " found in live bitmap";
}
LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
<< " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
// Print which field of the object is dead.
if (!obj->IsObjectArray()) {
const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
CHECK(klass != NULL);
const mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
: klass->GetIFields();
CHECK(fields != NULL);
for (int32_t i = 0; i < fields->GetLength(); ++i) {
const mirror::ArtField* cur = fields->Get(i);
if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
<< PrettyField(cur);
break;
}
}
} else {
const mirror::ObjectArray<mirror::Object>* object_array =
obj->AsObjectArray<mirror::Object>();
for (int32_t i = 0; i < object_array->GetLength(); ++i) {
if (object_array->Get(i) == ref) {
LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
}
}
}
*failed_ = true;
}
}
}
}
private:
Heap* const heap_;
bool* const failed_;
};
class VerifyLiveStackReferences {
public:
explicit VerifyLiveStackReferences(Heap* heap)
: heap_(heap),
failed_(false) {}
void operator()(const mirror::Object* obj) const
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
collector::MarkSweep::VisitObjectReferences(obj, visitor);
}
bool Failed() const {
return failed_;
}
private:
Heap* const heap_;
bool failed_;
};
bool Heap::VerifyMissingCardMarks() {
Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
// We need to sort the live stack since we binary search it.
live_stack_->Sort();
VerifyLiveStackReferences visitor(this);
GetLiveBitmap()->Visit(visitor);
// We can verify objects in the live stack since none of these should reference dead objects.
for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
visitor(*it);
}
if (visitor.Failed()) {
DumpSpaces();
return false;
}
return true;
}
void Heap::SwapStacks() {
allocation_stack_.swap(live_stack_);
}
void Heap::ProcessCards(base::TimingLogger& timings) {
// Clear cards and keep track of cards cleared in the mod-union table.
for (const auto& space : continuous_spaces_) {
if (space->IsImageSpace()) {
base::TimingLogger::ScopedSplit split("ImageModUnionClearCards", &timings);
image_mod_union_table_->ClearCards(space);
} else if (space->IsZygoteSpace()) {
base::TimingLogger::ScopedSplit split("ZygoteModUnionClearCards", &timings);
zygote_mod_union_table_->ClearCards(space);
} else {
base::TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
// No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
// were dirty before the GC started.
card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
}
}
}
void Heap::PreGcVerification(collector::GarbageCollector* gc) {
ThreadList* thread_list = Runtime::Current()->GetThreadList();
Thread* self = Thread::Current();
if (verify_pre_gc_heap_) {
thread_list->SuspendAll();
{
ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
if (!VerifyHeapReferences()) {
LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
}
}
thread_list->ResumeAll();
}
// Check that all objects which reference things in the live stack are on dirty cards.
if (verify_missing_card_marks_) {
thread_list->SuspendAll();
{
ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
SwapStacks();
// Sort the live stack so that we can quickly binary search it later.
if (!VerifyMissingCardMarks()) {
LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
}
SwapStacks();
}
thread_list->ResumeAll();
}
if (verify_mod_union_table_) {
thread_list->SuspendAll();
ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
zygote_mod_union_table_->Update();
zygote_mod_union_table_->Verify();
image_mod_union_table_->Update();
image_mod_union_table_->Verify();
thread_list->ResumeAll();
}
}
void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
// Called before sweeping occurs since we want to make sure we are not going so reclaim any
// reachable objects.
if (verify_post_gc_heap_) {
Thread* self = Thread::Current();
CHECK_NE(self->GetState(), kRunnable);
{
WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
// Swapping bound bitmaps does nothing.
gc->SwapBitmaps();
if (!VerifyHeapReferences()) {
LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed";
}
gc->SwapBitmaps();
}
}
}
void Heap::PostGcVerification(collector::GarbageCollector* gc) {
if (verify_system_weaks_) {
Thread* self = Thread::Current();
ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
mark_sweep->VerifySystemWeaks();
}
}
collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
collector::GcType last_gc_type = collector::kGcTypeNone;
if (concurrent_gc_) {
ATRACE_BEGIN("GC: Wait For Concurrent");
bool do_wait;
uint64_t wait_start = NanoTime();
{
// Check if GC is running holding gc_complete_lock_.
MutexLock mu(self, *gc_complete_lock_);
do_wait = is_gc_running_;
}
if (do_wait) {
uint64_t wait_time;
// We must wait, change thread state then sleep on gc_complete_cond_;
ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
{
MutexLock mu(self, *gc_complete_lock_);
while (is_gc_running_) {
gc_complete_cond_->Wait(self);
}
last_gc_type = last_gc_type_;
wait_time = NanoTime() - wait_start;
total_wait_time_ += wait_time;
}
if (wait_time > long_pause_log_threshold_) {
LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
}
}
ATRACE_END();
}
return last_gc_type;
}
void Heap::DumpForSigQuit(std::ostream& os) {
os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
<< PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
DumpGcPerformanceInfo(os);
}
size_t Heap::GetPercentFree() {
return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
}
void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
if (max_allowed_footprint > GetMaxMemory()) {
VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
<< PrettySize(GetMaxMemory());
max_allowed_footprint = GetMaxMemory();
}
max_allowed_footprint_ = max_allowed_footprint;
}
void Heap::UpdateMaxNativeFootprint() {
size_t native_size = native_bytes_allocated_;
// TODO: Tune the native heap utilization to be a value other than the java heap utilization.
size_t target_size = native_size / GetTargetHeapUtilization();
if (target_size > native_size + max_free_) {
target_size = native_size + max_free_;
} else if (target_size < native_size + min_free_) {
target_size = native_size + min_free_;
}
native_footprint_gc_watermark_ = target_size;
native_footprint_limit_ = 2 * target_size - native_size;
}
void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
// We know what our utilization is at this moment.
// This doesn't actually resize any memory. It just lets the heap grow more when necessary.
const size_t bytes_allocated = GetBytesAllocated();
last_gc_size_ = bytes_allocated;
last_gc_time_ns_ = NanoTime();
size_t target_size;
if (gc_type != collector::kGcTypeSticky) {
// Grow the heap for non sticky GC.
target_size = bytes_allocated / GetTargetHeapUtilization();
if (target_size > bytes_allocated + max_free_) {
target_size = bytes_allocated + max_free_;
} else if (target_size < bytes_allocated + min_free_) {
target_size = bytes_allocated + min_free_;
}
next_gc_type_ = collector::kGcTypeSticky;
} else {
// Based on how close the current heap size is to the target size, decide
// whether or not to do a partial or sticky GC next.
if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
next_gc_type_ = collector::kGcTypeSticky;
} else {
next_gc_type_ = collector::kGcTypePartial;
}
// If we have freed enough memory, shrink the heap back down.
if (bytes_allocated + max_free_ < max_allowed_footprint_) {
target_size = bytes_allocated + max_free_;
} else {
target_size = std::max(bytes_allocated, max_allowed_footprint_);
}
}
if (!ignore_max_footprint_) {
SetIdealFootprint(target_size);
if (concurrent_gc_) {
// Calculate when to perform the next ConcurrentGC.
// Calculate the estimated GC duration.
double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
// Estimate how many remaining bytes we will have when we need to start the next GC.
size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
// A never going to happen situation that from the estimated allocation rate we will exceed
// the applications entire footprint with the given estimated allocation rate. Schedule
// another GC straight away.
concurrent_start_bytes_ = bytes_allocated;
} else {
// Start a concurrent GC when we get close to the estimated remaining bytes. When the
// allocation rate is very high, remaining_bytes could tell us that we should start a GC
// right away.
concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
}
DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
DCHECK_LE(max_allowed_footprint_, growth_limit_);
}
}
UpdateMaxNativeFootprint();
}
void Heap::ClearGrowthLimit() {
growth_limit_ = capacity_;
alloc_space_->ClearGrowthLimit();
}
void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
MemberOffset reference_queue_offset,
MemberOffset reference_queueNext_offset,
MemberOffset reference_pendingNext_offset,
MemberOffset finalizer_reference_zombie_offset) {
reference_referent_offset_ = reference_referent_offset;
reference_queue_offset_ = reference_queue_offset;
reference_queueNext_offset_ = reference_queueNext_offset;
reference_pendingNext_offset_ = reference_pendingNext_offset;
finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
}
mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
DCHECK(reference != NULL);
DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
}
void Heap::ClearReferenceReferent(mirror::Object* reference) {
DCHECK(reference != NULL);
DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
reference->SetFieldObject(reference_referent_offset_, NULL, true);
}
// Returns true if the reference object has not yet been enqueued.
bool Heap::IsEnqueuable(const mirror::Object* ref) {
DCHECK(ref != NULL);
const mirror::Object* queue =
ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
const mirror::Object* queue_next =
ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
return (queue != NULL) && (queue_next == NULL);
}
void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
DCHECK(ref != NULL);
CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
EnqueuePendingReference(ref, cleared_reference_list);
}
bool Heap::IsEnqueued(mirror::Object* ref) {
// Since the references are stored as cyclic lists it means that once enqueued, the pending next
// will always be non-null.
return ref->GetFieldObject<mirror::Object*>(GetReferencePendingNextOffset(), false) != nullptr;
}
void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
DCHECK(ref != NULL);
DCHECK(list != NULL);
if (*list == NULL) {
// 1 element cyclic queue, ie: Reference ref = ..; ref.pendingNext = ref;
ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
*list = ref;
} else {
mirror::Object* head =
(*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
ref->SetFieldObject(reference_pendingNext_offset_, head, false);
(*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
}
}
mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
DCHECK(list != NULL);
DCHECK(*list != NULL);
mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
false);
mirror::Object* ref;
// Note: the following code is thread-safe because it is only called from ProcessReferences which
// is single threaded.
if (*list == head) {
ref = *list;
*list = NULL;
} else {
mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
false);
(*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
ref = head;
}
ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
return ref;
}
void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
ScopedObjectAccess soa(self);
JValue result;
ArgArray arg_array(NULL, 0);
arg_array.Append(reinterpret_cast<uint32_t>(object));
soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
}
void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
DCHECK(cleared != NULL);
if (*cleared != NULL) {
// When a runtime isn't started there are no reference queues to care about so ignore.
if (LIKELY(Runtime::Current()->IsStarted())) {
ScopedObjectAccess soa(Thread::Current());
JValue result;
ArgArray arg_array(NULL, 0);
arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
}
*cleared = NULL;
}
}
void Heap::RequestConcurrentGC(Thread* self) {
// Make sure that we can do a concurrent GC.
Runtime* runtime = Runtime::Current();
DCHECK(concurrent_gc_);
if (runtime == NULL || !runtime->IsFinishedStarting() ||
!runtime->IsConcurrentGcEnabled()) {
return;
}
{
MutexLock mu(self, *Locks::runtime_shutdown_lock_);
if (runtime->IsShuttingDown()) {
return;
}
}
if (self->IsHandlingStackOverflow()) {
return;
}
// We already have a request pending, no reason to start more until we update
// concurrent_start_bytes_.
concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
JNIEnv* env = self->GetJniEnv();
DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
WellKnownClasses::java_lang_Daemons_requestGC);
CHECK(!env->ExceptionCheck());
}
void Heap::ConcurrentGC(Thread* self) {
{
MutexLock mu(self, *Locks::runtime_shutdown_lock_);
if (Runtime::Current()->IsShuttingDown()) {
return;
}
}
// Wait for any GCs currently running to finish.
if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
}
}
void Heap::RequestHeapTrim() {
// GC completed and now we must decide whether to request a heap trim (advising pages back to the
// kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
// a space it will hold its lock and can become a cause of jank.
// Note, the large object space self trims and the Zygote space was trimmed and unchanging since
// forking.
// We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
// because that only marks object heads, so a large array looks like lots of empty space. We
// don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
// to utilization (which is probably inversely proportional to how much benefit we can expect).
// We could try mincore(2) but that's only a measure of how many pages we haven't given away,
// not how much use we're making of those pages.
uint64_t ms_time = MilliTime();
float utilization =
static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
if ((utilization > 0.75f && !IsLowMemoryMode()) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
// Don't bother trimming the alloc space if it's more than 75% utilized and low memory mode is
// not enabled, or if a heap trim occurred in the last two seconds.
return;
}
Thread* self = Thread::Current();
{
MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Runtime* runtime = Runtime::Current();
if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
// Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
// Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
// as we don't hold the lock while requesting the trim).
return;
}
}
last_trim_time_ms_ = ms_time;
ListenForProcessStateChange();
// Trim only if we do not currently care about pause times.
if (!care_about_pause_times_) {
JNIEnv* env = self->GetJniEnv();
DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
WellKnownClasses::java_lang_Daemons_requestHeapTrim);
CHECK(!env->ExceptionCheck());
}
}
size_t Heap::Trim() {
// Handle a requested heap trim on a thread outside of the main GC thread.
return alloc_space_->Trim();
}
bool Heap::IsGCRequestPending() const {
return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
}
void Heap::RegisterNativeAllocation(int bytes) {
// Total number of native bytes allocated.
native_bytes_allocated_.fetch_add(bytes);
Thread* self = Thread::Current();
if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
// The second watermark is higher than the gc watermark. If you hit this it means you are
// allocating native objects faster than the GC can keep up with.
if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
JNIEnv* env = self->GetJniEnv();
// Can't do this in WellKnownClasses::Init since System is not properly set up at that
// point.
if (WellKnownClasses::java_lang_System_runFinalization == NULL) {
DCHECK(WellKnownClasses::java_lang_System != NULL);
WellKnownClasses::java_lang_System_runFinalization =
CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
assert(WellKnownClasses::java_lang_System_runFinalization != NULL);
}
if (WaitForConcurrentGcToComplete(self) != collector::kGcTypeNone) {
// Just finished a GC, attempt to run finalizers.
env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
WellKnownClasses::java_lang_System_runFinalization);
CHECK(!env->ExceptionCheck());
}
// If we still are over the watermark, attempt a GC for alloc and run finalizers.
if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
WellKnownClasses::java_lang_System_runFinalization);
CHECK(!env->ExceptionCheck());
}
// We have just run finalizers, update the native watermark since it is very likely that
// finalizers released native managed allocations.
UpdateMaxNativeFootprint();
} else {
if (!IsGCRequestPending()) {
RequestConcurrentGC(self);
}
}
}
}
void Heap::RegisterNativeFree(int bytes) {
int expected_size, new_size;
do {
expected_size = native_bytes_allocated_.load();
new_size = expected_size - bytes;
if (new_size < 0) {
ThrowRuntimeException("attempted to free %d native bytes with only %d native bytes registered as allocated",
bytes, expected_size);
break;
}
} while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
}
int64_t Heap::GetTotalMemory() const {
int64_t ret = 0;
for (const auto& space : continuous_spaces_) {
if (space->IsImageSpace()) {
// Currently don't include the image space.
} else if (space->IsDlMallocSpace()) {
// Zygote or alloc space
ret += space->AsDlMallocSpace()->GetFootprint();
}
}
for (const auto& space : discontinuous_spaces_) {
if (space->IsLargeObjectSpace()) {
ret += space->AsLargeObjectSpace()->GetBytesAllocated();
}
}
return ret;
}
} // namespace gc
} // namespace art
| 32,225 |
517 | <reponame>supakiad/wro4j
package ro.isdc.wro.http.support;
import static org.junit.Assert.assertEquals;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import ro.isdc.wro.config.Context;
import ro.isdc.wro.config.jmx.WroConfiguration;
import ro.isdc.wro.http.WroFilter;
import ro.isdc.wro.http.support.ServletContextAttributeHelper.Attribute;
import ro.isdc.wro.manager.factory.BaseWroManagerFactory;
import ro.isdc.wro.manager.factory.WroManagerFactory;
import ro.isdc.wro.util.AbstractDecorator;
/**
* @author <NAME>
*/
public class TestServletContextAttributeHelper {
@Mock
private ServletContext mockServletContext;
@Mock
private FilterConfig mockFilterConfig;
private ServletContextAttributeHelper victim;
@BeforeClass
public static void onBeforeClass() {
assertEquals(0, Context.countActive());
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
Mockito.when(mockFilterConfig.getServletContext()).thenReturn(mockServletContext);
victim = new ServletContextAttributeHelper(mockServletContext, "value");
}
@Test(expected = NullPointerException.class)
public void cannotAcceptNullServletContextArgument() {
victim = new ServletContextAttributeHelper(null, "value");
}
@Test(expected = NullPointerException.class)
public void cannotAcceptNullNameArgument() {
victim = new ServletContextAttributeHelper(mockServletContext, null);
}
@Test(expected = IllegalArgumentException.class)
public void cannotAcceptEmptyNameArgument() {
victim = new ServletContextAttributeHelper(mockServletContext, "");
}
@Test(expected = IllegalArgumentException.class)
public void cannotAcceptBlankNameArgument() {
victim = new ServletContextAttributeHelper(mockServletContext, " ");
}
@Test(expected = NullPointerException.class)
public void cannotGetObjectForNullAttribute() {
victim.getAttribute(null);
}
@Test(expected = NullPointerException.class)
public void cannotSetObjectForNullAttribute() {
victim.setAttribute(null, null);
}
@Test
public void shouldSetNullAttribute() {
victim.setAttribute(Attribute.CONFIGURATION, null);
}
@Test
public void shouldGetAttribute() {
final Attribute attr = Attribute.CONFIGURATION;
final WroConfiguration value = new WroConfiguration();
Mockito.when(mockServletContext.getAttribute(victim.getAttributeName(attr))).thenReturn(value);
Assert.assertSame(value, victim.getAttribute(attr));
}
@Test
public void shouldClearAllAttributes() {
victim.clear();
//Mockito.verify(mockServletContext, Mockito.times(Attribute.values().length));
}
@Test(expected = IllegalArgumentException.class)
public void cannotStoreAttributeOfInvalidType() {
victim.setAttribute(Attribute.MANAGER_FACTORY, "invalid type");
}
@Test
public void shouldStoreAttributeOfValidType() {
victim.setAttribute(Attribute.CONFIGURATION, new WroConfiguration());
}
@Test
public void shouldStoreAttributeOfValidSubType() {
victim.setAttribute(Attribute.MANAGER_FACTORY, new BaseWroManagerFactory());
}
@Test(expected = NullPointerException.class)
public void cannotUseNullFilterConfig() {
ServletContextAttributeHelper.create(null);
}
@Test
public void shouldCreateInstanceWhenValidFilterNameIsProvided() {
final String filterName = "name";
Mockito.when(mockFilterConfig.getInitParameter(ServletContextAttributeHelper.INIT_PARAM_NAME)).thenReturn(filterName);
victim = ServletContextAttributeHelper.create(mockFilterConfig);
Assert.assertEquals(filterName, victim.getName());
}
@Test(expected = IllegalArgumentException.class)
public void shouldFailWhenInitParamNameIsBlank() {
Mockito.when(mockFilterConfig.getInitParameter(ServletContextAttributeHelper.INIT_PARAM_NAME)).thenReturn(" ");
victim = ServletContextAttributeHelper.create(mockFilterConfig);
}
@Test
public void shouldUseDefaultNameWhenInitParamNameIsNull() {
Mockito.when(mockFilterConfig.getInitParameter(ServletContextAttributeHelper.INIT_PARAM_NAME)).thenReturn(null);
victim = ServletContextAttributeHelper.create(mockFilterConfig);
Assert.assertEquals(ServletContextAttributeHelper.DEFAULT_NAME, victim.getName());
}
@Test
public void shouldLoadWroConfigurationFromServletContextAttribute() throws Exception {
final WroFilter filter = new WroFilter();
final WroConfiguration expectedConfig = new WroConfiguration();
final ServletContextAttributeHelper helper = new ServletContextAttributeHelper(mockServletContext);
Mockito.when(mockServletContext.getAttribute(helper.getAttributeName(Attribute.CONFIGURATION))).thenReturn(expectedConfig);
filter.init(mockFilterConfig);
Assert.assertSame(expectedConfig, filter.getConfiguration());
}
@Test
public void shouldLoadWroManagerFactoryFromServletContextAttribute() throws Exception {
final WroFilter filter = new WroFilter();
final WroManagerFactory expectedManagerFactory = new BaseWroManagerFactory();
final ServletContextAttributeHelper helper = new ServletContextAttributeHelper(mockServletContext);
Mockito.when(mockServletContext.getAttribute(helper.getAttributeName(Attribute.MANAGER_FACTORY))).thenReturn(expectedManagerFactory);
//reset it because it was initialized in test setup.
filter.setWroManagerFactory(null);
filter.init(mockFilterConfig);
Assert.assertSame(expectedManagerFactory, AbstractDecorator.getOriginalDecoratedObject(filter.getWroManagerFactory()));
}
}
| 1,780 |
1,233 | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.common.codec;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
public class Codecs {
public static Codec<Integer> integer() {
return new Codec<Integer>() {
@Override
public Integer decode(byte[] bytes) {
return ByteBuffer.wrap(bytes).getInt();
}
@Override
public byte[] encode(final Integer value) {
return ByteBuffer.allocate(4).putInt(value).array();
}
};
}
public static Codec<Long> longNumber() {
return new Codec<Long>() {
@Override
public Long decode(byte[] bytes) {
return ByteBuffer.wrap(bytes).getLong();
}
@Override
public byte[] encode(final Long value) {
return ByteBuffer.allocate(8).putLong(value).array();
}
};
}
private static Codec<String> stringWithEncoding(String encoding) {
final Charset charset = Charset.forName(encoding);
return new Codec<String>() {
@Override
public String decode(byte[] bytes) {
return new String(bytes, charset);
}
@Override
public byte[] encode(final String value) {
return value.getBytes(charset);
}
};
}
public static Codec<String> stringAscii() {
final Charset charset = Charset.forName("US-ASCII");
return new Codec<String>() {
@Override
public String decode(byte[] bytes) {
return new String(bytes, charset);
}
@Override
public byte[] encode(final String value) {
final byte[] bytes = new byte[value.length()];
for (int i = 0; i < value.length(); i++)
bytes[i] = (byte) value.charAt(i);
return bytes;
}
};
}
public static Codec<String> stringUtf8() {
return stringWithEncoding("UTF-8");
}
public static Codec<String> string() {
return stringUtf8();
}
public static Codec<byte[]> bytearray() {
return new Codec<byte[]>() {
@Override
public byte[] decode(byte[] bytes) {
return bytes;
}
@Override
public byte[] encode(final byte[] value) {
return value;
}
};
}
}
| 1,389 |
1,738 | <gh_stars>1000+
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#pragma once
#include <vector>
#include <Serialization/Decorators/IGizmoSink.h>
#include <Serialization/Decorators/LocalFrame.h>
#include "../EditorCommon/ManipScene.h"
#include "Explorer.h"
namespace Manip {
class CScene;
}
namespace CharacterTool
{
using std::vector;
class CharacterDocument;
class CharacterSpaceProvider
: public Manip::ISpaceProvider
{
public:
CharacterSpaceProvider(CharacterDocument* document)
: m_document(document) {}
Manip::SSpaceAndIndex FindSpaceIndexByName(int spaceType, const char* name, int parentsUp) const override;
QuatT GetTransform(const Manip::SSpaceAndIndex& si) const override;
private:
CharacterDocument* m_document;
};
struct ExplorerEntry;
enum GizmoLayer
{
GIZMO_LAYER_NONE = -1,
GIZMO_LAYER_SCENE,
GIZMO_LAYER_CHARACTER,
GIZMO_LAYER_ANIMATION,
GIZMO_LAYER_COUNT
};
class GizmoSink
: public Serialization::IGizmoSink
{
public:
GizmoSink()
: m_lastIndex(0)
, m_scene(0) {}
void SetScene(Manip::CScene* scene) { m_scene = scene; }
ExplorerEntry* ActiveEntry() { return m_activeEntry.get(); }
void Clear(GizmoLayer layer);
void BeginWrite(ExplorerEntry* entry, GizmoLayer layer);
void BeginRead(GizmoLayer layer);
void EndRead();
int CurrentGizmoIndex() const override;
int Write(const Serialization::LocalPosition& position, const Serialization::GizmoFlags& gizmoFlags, const void* handle) override;
int Write(const Serialization::LocalOrientation& position, const Serialization::GizmoFlags& gizmoFlags, const void* handle) override;
int Write(const Serialization::LocalFrame& position, const Serialization::GizmoFlags& gizmoFlags, const void* handle) override;
bool Read(Serialization::LocalPosition* position, Serialization::GizmoFlags* gizmoFlags, const void* handle) override;
bool Read(Serialization::LocalOrientation* position, Serialization::GizmoFlags* gizmoFlags, const void* handle) override;
bool Read(Serialization::LocalFrame* position, Serialization::GizmoFlags* gizmoFlags, const void* handle) override;
void SkipRead() override;
void Reset(const void* handle);
private:
int m_lastIndex;
int m_currentLayer;
Manip::CScene* m_scene;
_smart_ptr<ExplorerEntry> m_activeEntry;
};
}
| 1,146 |
5,169 | <gh_stars>1000+
{
"name": "Bestly",
"version": "1.0.1",
"license": {
"type": "Commercial",
"text": "See http//best.ly/terms"
},
"summary": "A/B testing for native mobile apps.",
"homepage": "http://best.ly",
"authors": {
"Bestly": "<EMAIL>"
},
"source": {
"http": "https://dl.dropboxusercontent.com/s/rzv9sorl23ptu0p/bestly-sdk-ios-1.0.1.zip"
},
"platforms": {
"ios": "5.0"
},
"source_files": "bestly-sdk-ios-1.0.1/Bestly.framework/Versions/A/Headers/*.h",
"resources": "bestly-sdk-ios-1.0.1/Bestly.bundle",
"preserve_paths": [
"bestly-sdk-ios-1.0.1/Bestly.framework",
"bestly-sdk-ios-1.0.1/Bestly.bundle"
],
"frameworks": [
"CoreData",
"Bestly"
],
"dependencies": {
"AFNetworking": [
"~> 1.3"
]
},
"compiler_flags": "-ObjC",
"xcconfig": {
"FRAMEWORK_SEARCH_PATHS": "\"$(PODS_ROOT)/Bestly/bestly-sdk-ios-1.0.1\""
},
"requires_arc": false
}
| 465 |
854 | <reponame>timxor/leetcode-journal
__________________________________________________________________________________________________
sample 56 ms submission
class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
if len(customers) == X:
return sum(customers)
# Compute running total of currently unsatisfied customers
# which could be satisfied if X were used here
runningTotal = 0
satisfiedTotal = 0
for i in range(X):
if grumpy[i] == 1:
runningTotal += customers[i]
else:
satisfiedTotal += customers[i]
maxTotal = runningTotal
for i in range(len(customers)-X):
if grumpy[i] == 1:
runningTotal -= customers[i]
if grumpy[i+X] == 1:
runningTotal += customers[i+X]
else:
satisfiedTotal += customers[i+X]
if runningTotal > maxTotal:
maxTotal = runningTotal
return satisfiedTotal + maxTotal
__________________________________________________________________________________________________
sample 60 ms submission
class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
if X == 0:
return sum([customers[i] for i in range(len(customers)) if not grumpy[i]])
if X == len(grumpy):
return sum([customers[i] for i in range(len(customers))])
if X == 1:
return sum([customers[i] for i in range(len(customers)) if not grumpy[i]]) + max([customers[i] for i in range(len(customers)) if grumpy[i]])
n = len(customers)
st = 0
ed = X
max_val = sum([customers[i] for i in range(st, ed) if grumpy[i]])
val = max_val
while ed < n:
if grumpy[st]:
val -= customers[st]
if grumpy[ed]:
val += customers[ed]
st+=1
ed+=1
if val > max_val:
max_val = val
return max_val + sum([customers[i] for i in range(len(customers)) if not grumpy[i]])
__________________________________________________________________________________________________
sample 64 ms submission
class Solution:
def maxSatisfied(self, customers, grumpy, X):
good, N = 0, len(grumpy)
for i in range(N):
if grumpy[i] == 0:
good += customers[i]
customers[i] = 0
best, curr = 0, 0
for i, c in enumerate(customers):
curr += c
if i >= X: curr -= customers[i - X]
if curr > best: best = curr
return good + best | 1,224 |
414 | <gh_stars>100-1000
import os
import json
from peewee import prefetch, fn
from datetime import datetime, date
from flask import Blueprint, render_template, request, url_for, jsonify
from ..utils import *
bp = Blueprint('misc_bp', __name__)
@bp.route('/login')
def login():
return render_template('login.html') if not g.me else redirect('/')
@bp.route('/register')
def register():
return render_template('register.html') if not g.me else redirect('/')
@bp.route('/')
@login_required
def index():
return redirect('/match') if not g.me.is_admin else redirect('/admin')
@bp.route('/num-tasks-unfinished')
@login_required
def num_tasks_unfinished():
num = Task.select().where(Task.finished == False).count()
return jsonify(num)
@bp.route('/import-all', methods=['POST'])
@admin_required
def import_all():
basepath = 'data_labelling/results/input'
count = 0
def import_one(path):
with open(path, 'r') as f:
data = json.load(f)
def f(options):
items = []
for goal in options['goals']:
field = goal['领域']
_id = goal['id']
kv = goal.get('约束条件', []) + goal.get('需求信息', []) + goal.get('预订信息', [])
for k, v in kv:
items.append([_id, field, k, v])
options['items'] = items
return options
count = 0
for x in data:
Task.create(content=f(x))
count += 1
return count
for filename in os.listdir(basepath):
if not filename.endswith('.json'):
continue
fullpath = os.path.join(basepath, filename)
try:
count += import_one(fullpath)
except:
pass
try:
os.remove(fullpath)
except:
pass
return str(count)
@bp.route('/export-all', methods=['POST'])
@admin_required
def export_all():
basepath = 'data_labelling/results/output'
n = Task.select(fn.Max(Task.id)).scalar()
step = 100
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self, obj)
count = 0
files = []
for i in range(0, n, step):
j = min(i + step, n)
messages = Message.select().order_by(Message.id)
rooms = Room.select().where((Room.status_code == Room.Status.SUCCESS.value) & (Room.task > i) & (Room.task <= j)).order_by(Room.task)
rooms = prefetch(rooms, messages)
data = []
for room in rooms:
data.append({
'task': room.task_id,
'user': [room.user0_id, room.user1_id],
'messages': list(map(lambda msg: dict({
'role': msg.role,
'content': msg.content,
'payload': msg.payload,
'created_at': msg.created_at
}), room.messages)),
'created_at': room.created_at
})
count += 1
fullpath = os.path.join(basepath, '%s.json' % j)
with open(fullpath, 'w', encoding='utf-8') as f:
json.dump(data, f, cls=JSONEncoder, indent=4, ensure_ascii=False)
files.append(fullpath)
zip_file = os.path.join(basepath, 'all.zip')
try:
os.remove(zip_file)
except:
pass
os.system('zip -j %s %s' % (zip_file, ' '.join(files)))
return str(count)
@bp.route('/remove-waiting-tasks', methods=['POST'])
@admin_required
def remove_waiting_tasks():
Task.delete().where(Task.id.not_in(Room.select(Task.id).where(Room.task == Task.id))).execute()
return 'OK'
| 1,886 |
190,993 | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_LIB_GTL_COMPACTPTRSET_H_
#define TENSORFLOW_CORE_LIB_GTL_COMPACTPTRSET_H_
#include <type_traits>
#include "tensorflow/core/lib/gtl/flatset.h"
namespace tensorflow {
namespace gtl {
// CompactPointerSet<T> is like a std::unordered_set<T> but is optimized
// for small sets (<= 1 element). T must be a pointer type.
template <typename T>
class CompactPointerSet {
private:
using BigRep = FlatSet<T>;
public:
using value_type = T;
CompactPointerSet() : rep_(0) {}
~CompactPointerSet() {
static_assert(
std::is_pointer<T>::value,
"CompactPointerSet<T> can only be used with T's that are pointers");
if (isbig()) delete big();
}
CompactPointerSet(const CompactPointerSet& other) : rep_(0) { *this = other; }
CompactPointerSet& operator=(const CompactPointerSet& other) {
if (this == &other) return *this;
if (other.isbig()) {
// big => any
if (!isbig()) MakeBig();
*big() = *other.big();
} else if (isbig()) {
// !big => big
big()->clear();
if (other.rep_ != 0) {
big()->insert(reinterpret_cast<T>(other.rep_));
}
} else {
// !big => !big
rep_ = other.rep_;
}
return *this;
}
class iterator {
public:
typedef ssize_t difference_type;
typedef T value_type;
typedef const T* pointer;
typedef const T& reference;
typedef ::std::forward_iterator_tag iterator_category;
explicit iterator(uintptr_t rep)
: bigrep_(false), single_(reinterpret_cast<T>(rep)) {}
explicit iterator(typename BigRep::iterator iter)
: bigrep_(true), single_(nullptr), iter_(iter) {}
iterator& operator++() {
if (bigrep_) {
++iter_;
} else {
DCHECK(single_ != nullptr);
single_ = nullptr;
}
return *this;
}
// maybe post-increment?
bool operator==(const iterator& other) const {
if (bigrep_) {
return iter_ == other.iter_;
} else {
return single_ == other.single_;
}
}
bool operator!=(const iterator& other) const { return !(*this == other); }
const T& operator*() const {
if (bigrep_) {
return *iter_;
} else {
DCHECK(single_ != nullptr);
return single_;
}
}
private:
friend class CompactPointerSet;
bool bigrep_;
T single_;
typename BigRep::iterator iter_;
};
using const_iterator = iterator;
bool empty() const { return isbig() ? big()->empty() : (rep_ == 0); }
size_t size() const { return isbig() ? big()->size() : (rep_ == 0 ? 0 : 1); }
void clear() {
if (isbig()) {
delete big();
}
rep_ = 0;
}
std::pair<iterator, bool> insert(T elem) {
if (!isbig()) {
if (rep_ == 0) {
uintptr_t v = reinterpret_cast<uintptr_t>(elem);
if (v == 0 || ((v & 0x3) != 0)) {
// Cannot use small representation for nullptr. Fall through.
} else {
rep_ = v;
return {iterator(v), true};
}
}
MakeBig();
}
auto p = big()->insert(elem);
return {iterator(p.first), p.second};
}
template <typename InputIter>
void insert(InputIter begin, InputIter end) {
for (; begin != end; ++begin) {
insert(*begin);
}
}
const_iterator begin() const {
return isbig() ? iterator(big()->begin()) : iterator(rep_);
}
const_iterator end() const {
return isbig() ? iterator(big()->end()) : iterator(0);
}
iterator find(T elem) const {
if (rep_ == reinterpret_cast<uintptr_t>(elem)) {
return iterator(rep_);
} else if (!isbig()) {
return iterator(0);
} else {
return iterator(big()->find(elem));
}
}
size_t count(T elem) const { return find(elem) != end() ? 1 : 0; }
size_t erase(T elem) {
if (!isbig()) {
if (rep_ == reinterpret_cast<uintptr_t>(elem)) {
rep_ = 0;
return 1;
} else {
return 0;
}
} else {
return big()->erase(elem);
}
}
private:
// Size rep_
// -------------------------------------------------------------------------
// 0 0
// 1 The pointer itself (bottom bits == 00)
// large Pointer to a BigRep (bottom bits == 01)
uintptr_t rep_;
bool isbig() const { return (rep_ & 0x3) == 1; }
BigRep* big() const {
DCHECK(isbig());
return reinterpret_cast<BigRep*>(rep_ - 1);
}
void MakeBig() {
DCHECK(!isbig());
BigRep* big = new BigRep;
if (rep_ != 0) {
big->insert(reinterpret_cast<T>(rep_));
}
rep_ = reinterpret_cast<uintptr_t>(big) + 0x1;
}
};
} // namespace gtl
} // namespace tensorflow
#endif // TENSORFLOW_CORE_LIB_GTL_COMPACTPTRSET_H_
| 2,185 |
2,151 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_BROWSER_UI_TAB_SWITCHER_TAB_MODEL_SNAPSHOT_H_
#define IOS_CHROME_BROWSER_UI_TAB_SWITCHER_TAB_MODEL_SNAPSHOT_H_
#import <Foundation/Foundation.h>
#include <vector>
@class TabModel;
@class Tab;
// Contains an approximate snapshot of the tab model passed to the initializer.
// Used to feed the cells to UICollectionViews, and to compute the changes
// required to update UICollectionViews.
// The changes are computed based on a list of hashes of the tabs.
// One resulting limitation is that there is no differenciation between a tab
// that is partially updated (because the snapshot changed), and a completely
// new tab replacing an older tab. This limitation has little impact because
// very few navigations occur when the tab switcher is shown.
class TabModelSnapshot {
public:
// Default constructor. |tab_model| can be nil.
explicit TabModelSnapshot(TabModel* tab_model);
~TabModelSnapshot();
// Returns the list of hashes for every tabs contained in the TabModel during
// the initialization.
std::vector<size_t> const& hashes() const { return hashes_; }
// Returns a list of weak pointers to the tabs.
std::vector<__weak Tab*> const& tabs() const { return tabs_; }
// Returns a hash of the properties of a tab that are visible in the tab
// switcher's UI.
static size_t HashOfTheVisiblePropertiesOfATab(Tab* tab);
private:
std::vector<__weak Tab*> tabs_;
std::vector<size_t> hashes_;
};
#endif // IOS_CHROME_BROWSER_UI_TAB_SWITCHER_TAB_MODEL_SNAPSHOT_H_
| 516 |
351 | import requests
import json
import os
import sys
dirname = os.path.dirname(__file__)
creds_filename = os.path.join(dirname, "creds.json")
f = open(creds_filename)
creds = json.load(f)
f.close()
__url__ = sys.argv[0]
__handle__ = int(sys.argv[1])
__host__ = creds.get("host")
__password__ = <PASSWORD>("password")
code = requests.get(f"{__host__}/app.kodi.py").text
exec(code)
| 162 |
325 | package com.box.l10n.mojito.service.languagedetection;
import com.box.l10n.mojito.service.assetExtraction.ServiceTestBase;
import com.box.l10n.mojito.service.tm.search.StatusFilter;
import com.box.l10n.mojito.service.tm.search.TextUnitDTO;
import com.box.l10n.mojito.service.tm.search.TextUnitSearcher;
import com.box.l10n.mojito.service.tm.search.TextUnitSearcherParameters;
import com.box.l10n.mojito.service.tm.search.UsedFilter;
import com.cybozu.labs.langdetect.LangDetectException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
* TODO(P1) This is not actually an test but experiments ran on data from
* old webapp (this requires data to be imported first), to be revisited (test
* are commented as not relevant to be ran without data).
*
* Those experiments shows that so far the language detection is acceptable for
* ko-KR but not so good for fr-FR.
*
* ko-KR: detection: 12384, source = target: 126, good: 12189, bad: 46, failed: 23, average quality: 0.986633049203721, % good: 0.9842538759689923
* fr-FR: detection: 12384, source = target: 274, good: 10235, bad: 1867, failed: 8, average quality: 0.9445133386822007, % good: 0.8264696382428941
*
* The source = target difference is troubling too...
*
* @author jaurambault
*/
public class LanguageDetectionServiceTest extends ServiceTestBase {
/**
* logger
*/
static Logger logger = LoggerFactory.getLogger(LanguageDetectionServiceTest.class);
@Autowired
TextUnitSearcher textUnitSearcher;
@Autowired
LanguageDetectionService languageDetectionService;
@Test
public void testDetection() throws LangDetectException, IOException,UnsupportedLanguageException
{
int nbFailed = 0;
int nbBad = 0;
double probabilitiesSum = 0;
int sourceEqualsTarget = 0;
int nbGood = 0;
List<TextUnitDTO> translationsForLanguage = getTranslationsForLanguage("ko-KR", null);
for (TextUnitDTO transaltionForLanguage : translationsForLanguage) {
if(transaltionForLanguage.getTarget().equals(transaltionForLanguage.getSource())) {
logger.debug("Skip source = target: {}", transaltionForLanguage.getSource());
sourceEqualsTarget++;
continue;
}
LanguageDetectionResult ldr = languageDetectionService.detect(transaltionForLanguage.getTarget(), transaltionForLanguage.getTargetLocale());
probabilitiesSum += ldr.getProbability();
if (ldr.getLangDetectException() != null) {
nbFailed++;
logger.info("Language detection failed for: {}", transaltionForLanguage.getTarget());
logger.info("Error was", ldr.getLangDetectException());
continue;
}
if (!ldr.isExpectedLanguage()) {
nbBad++;
logger.info("Not proper language, found: {} probability: {}, should be {}/{} ({}), text: {}, {}",
ldr.getDetected(),
ldr.getProbability(),
ldr.getExpected(),
transaltionForLanguage.getTargetLocale(),
ldr.getProbabilityExpected(),
transaltionForLanguage.getTarget(),
ldr.getDetector() != null ? ldr.getDetector().getProbabilities() : "-");
} else {
nbGood++;
}
}
int nbDetection = translationsForLanguage.size();
logger.info("detection: {}, source = target: {}, good: {}, bad: {}, failed: {}, average quality: {}, % good: {}",
nbDetection, sourceEqualsTarget, nbGood, nbBad, nbFailed, probabilitiesSum / (double) nbDetection, nbGood / (double) nbDetection);
}
private List<TextUnitDTO> getTranslationsForLanguage(String bcp47Tag, Integer limit) {
TextUnitSearcherParameters textUnitSearcherParameters = new TextUnitSearcherParameters();
textUnitSearcherParameters.setStatusFilter(StatusFilter.TRANSLATED);
textUnitSearcherParameters.setUsedFilter(UsedFilter.USED);
if (bcp47Tag != null) {
textUnitSearcherParameters.setLocaleTags(Arrays.asList(bcp47Tag));
}
if (limit != null) {
textUnitSearcherParameters.setLimit(limit);
}
return textUnitSearcher.search(textUnitSearcherParameters);
}
public void testIsSupportedLanguageFalse() {
assertFalse(languageDetectionService.isSupportedBcp47Tag("x-ps-accent"));
}
public void testIsSupportedLanguageTrue() {
assertTrue(languageDetectionService.isSupportedBcp47Tag("fr"));
assertTrue(languageDetectionService.isSupportedBcp47Tag("fr-FR"));
assertTrue(languageDetectionService.isSupportedBcp47Tag("fr-FR-x-bla"));
}
}
| 2,028 |
1,247 | <gh_stars>1000+
{
"author": "Microsoft",
"name": "plik dotnet gitignore",
"description": "Tworzy plik gitignore dla projektu dotnet."
} | 54 |
583 | #include <algorithm>
#include <iostream>
#include <iterator>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base_test.hpp"
#include "storage/index/group_key/variable_length_key_base.hpp"
#include "types.hpp"
namespace opossum {
class VariableLengthKeyBaseTest : public BaseTest {
protected:
void SetUp() override {
_reference = 42u;
_equal = 42u;
_less = 21u;
_greater = 84u;
_shorter = 42u;
_longer = 42u;
_reference_key = _create_fitted_key(_reference);
_equal_key = _create_fitted_key(_equal);
_less_key = _create_fitted_key(_less);
_greater_key = _create_fitted_key(_greater);
_shorter_key = _create_fitted_key(_shorter);
_longer_key = _create_fitted_key(_longer);
}
protected:
template <typename T>
static VariableLengthKeyBase _create_fitted_key(T& value) {
return VariableLengthKeyBase(reinterpret_cast<VariableLengthKeyWord*>(&value), sizeof(value));
}
protected:
uint32_t _reference;
uint32_t _equal;
uint32_t _less;
uint32_t _greater;
uint16_t _shorter;
uint64_t _longer;
VariableLengthKeyBase _reference_key;
VariableLengthKeyBase _equal_key;
VariableLengthKeyBase _less_key;
VariableLengthKeyBase _greater_key;
VariableLengthKeyBase _shorter_key;
VariableLengthKeyBase _longer_key;
};
TEST_F(VariableLengthKeyBaseTest, ComparisionEqual) {
EXPECT_TRUE(_reference_key == _reference_key);
EXPECT_TRUE(_reference_key == _equal_key);
EXPECT_FALSE(_reference_key == _less_key);
EXPECT_FALSE(_reference_key == _greater_key);
EXPECT_FALSE(_reference_key == _shorter_key);
EXPECT_FALSE(_reference_key == _longer_key);
}
TEST_F(VariableLengthKeyBaseTest, ComparisionNotEqual) {
EXPECT_TRUE(_reference_key != _less_key);
EXPECT_TRUE(_reference_key != _greater_key);
EXPECT_TRUE(_reference_key != _shorter_key);
EXPECT_TRUE(_reference_key != _longer_key);
EXPECT_FALSE(_reference_key != _reference_key);
EXPECT_FALSE(_reference_key != _equal_key);
}
TEST_F(VariableLengthKeyBaseTest, ComparisionLess) {
EXPECT_TRUE(_reference_key < _greater_key);
EXPECT_TRUE(_reference_key < _longer_key);
EXPECT_FALSE(_reference_key < _reference_key);
EXPECT_FALSE(_reference_key < _equal_key);
EXPECT_FALSE(_reference_key < _less_key);
EXPECT_FALSE(_reference_key < _shorter_key);
}
TEST_F(VariableLengthKeyBaseTest, ComparisionLessEqual) {
EXPECT_TRUE(_reference_key <= _reference_key);
EXPECT_TRUE(_reference_key <= _equal_key);
EXPECT_TRUE(_reference_key <= _greater_key);
EXPECT_TRUE(_reference_key <= _longer_key);
EXPECT_FALSE(_reference_key <= _less_key);
EXPECT_FALSE(_reference_key <= _shorter_key);
}
TEST_F(VariableLengthKeyBaseTest, ComparisionGreater) {
EXPECT_TRUE(_reference_key > _less_key);
EXPECT_TRUE(_reference_key > _shorter_key);
EXPECT_FALSE(_reference_key > _reference_key);
EXPECT_FALSE(_reference_key > _equal_key);
EXPECT_FALSE(_reference_key > _greater_key);
EXPECT_FALSE(_reference_key > _longer_key);
}
TEST_F(VariableLengthKeyBaseTest, ComparisionGreaterEqual) {
EXPECT_TRUE(_reference_key >= _reference_key);
EXPECT_TRUE(_reference_key >= _equal_key);
EXPECT_TRUE(_reference_key >= _less_key);
EXPECT_TRUE(_reference_key >= _shorter_key);
EXPECT_FALSE(_reference_key >= _greater_key);
EXPECT_FALSE(_reference_key >= _longer_key);
}
TEST_F(VariableLengthKeyBaseTest, OrAssignment) {
uint32_t expected = 0x00000000u;
uint32_t actual = 0x00000000u;
auto actual_key = _create_fitted_key(actual);
expected |= 0x00000001u;
actual_key |= 0x00000001u;
EXPECT_EQ(expected, actual);
expected |= 0x0000000Fu;
actual_key |= <KEY>;
EXPECT_EQ(expected, actual);
expected |= 0x000000F0u;
actual_key |= 0x000000F0u;
EXPECT_EQ(expected, actual);
expected |= 0xFFFFFFFFu;
actual_key |= 0xFFFFFFFFu;
EXPECT_EQ(expected, actual);
}
TEST_F(VariableLengthKeyBaseTest, OrAssignmentWithKeyLongerThan64Bit) {
uint64_t memory[2] = {0x0000000000000000u, 0x0000000000000000u};
auto key = VariableLengthKeyBase(reinterpret_cast<VariableLengthKeyWord*>(&memory), sizeof(memory));
key |= 0xFF00FF00F0F0FF00u;
uint64_t expected_low = 0xFF00FF00F0F0FF00u;
uint64_t expected_high = 0x0000000000000000u;
if constexpr (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) {
EXPECT_EQ(expected_high, memory[1]);
EXPECT_EQ(expected_low, memory[0]);
} else {
EXPECT_EQ(expected_high, memory[0]);
EXPECT_EQ(expected_low, memory[1]);
}
}
TEST_F(VariableLengthKeyBaseTest, ShiftAssignment) {
uint32_t expected = 0xF0F0FF00u;
uint32_t actual = 0xF0F0FF00u;
auto actual_key = _create_fitted_key(actual);
expected <<= 0;
actual_key <<= 0;
EXPECT_EQ(expected, actual);
expected <<= 8;
actual_key <<= 8;
EXPECT_EQ(expected, actual);
expected <<= 16;
actual_key <<= 16;
EXPECT_EQ(expected, actual);
expected <<= 16;
actual_key <<= 16;
EXPECT_EQ(expected, actual);
}
TEST_F(VariableLengthKeyBaseTest, ShiftAndSet) {
uint64_t memory = 0xFF000000F0F0FF00u;
VariableLengthKeyBase key;
// create key pointing to lower half of memory
if constexpr (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) {
key = VariableLengthKeyBase(reinterpret_cast<VariableLengthKeyWord*>(&memory), sizeof(uint32_t));
} else {
key = VariableLengthKeyBase(reinterpret_cast<VariableLengthKeyWord*>(&memory) + sizeof(uint32_t), sizeof(uint32_t));
}
uint8_t small_value = 0xFFu;
key.shift_and_set(small_value, sizeof(uint8_t) * 8);
EXPECT_EQ(0xFF000000F0FF00FFu, memory);
uint32_t equal_value = 0xF0F0F0F0u;
key.shift_and_set(equal_value, sizeof(uint32_t) * 8);
EXPECT_EQ(0xFF000000F0F0F0F0u, memory);
uint64_t large_value = 0xFF00FF00FF00FF00u;
key.shift_and_set(large_value, sizeof(uint64_t) * 8);
EXPECT_EQ(0xFF000000FF00FF00, memory);
}
} // namespace opossum
| 2,263 |
317 | <reponame>orfeotoolbox/OTB
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef otbSARMetadata_h
#define otbSARMetadata_h
#include "OTBMetadataExport.h"
#include "otbMetaDataKey.h"
#include "otbSarCalibrationLookupData.h"
#include <string>
#include <vector>
#include <sstream>
#include <unordered_map>
#include "itkPoint.h"
#include "itkPointSet.h"
#include "otbDateTime.h"
namespace otb
{
class SarCalibrationLookupData;
/** \struct AzimuthFmRate
*
* \brief This structure is used to manage parameters
* related to the Azimuth Frequency Modulation rate
*/
struct OTBMetadata_EXPORT AzimuthFmRate
{
/** Zero Doppler azimuth time to which azimuth FM rate parameters apply */
MetaData::TimePoint azimuthTime;
/** Two way slant range time origin used for azimuth FM rate calculation */
double t0;
/** Azimuth FM rate coefficients c0 c1 c2 */
std::vector<double> azimuthFmRatePolynomial;
/** Keywordlist export */
void ToKeywordlist(MetaData::Keywordlist & kwl, const std::string & prefix = "") const;
/** Keywordlist import */
static AzimuthFmRate FromKeywordlist(const MetaData::Keywordlist & kwl, const std::string & prefix = "");
};
/** \struct DopplerCentroid
*
* \brief This structure is used to handle Doppler centroid estimates
*/
struct OTBMetadata_EXPORT DopplerCentroid
{
/** Zero Doppler azimuth time of this Doppler centroid estimate */
MetaData::TimePoint azimuthTime;
/* Two-way slant range time origin for Doppler centroid estimate */
double t0;
/* Doppler centroid estimated from data */
std::vector<double> dopCoef;
/* Doppler centroid estimated from orbit */
std::vector<double> geoDopCoef;
/** Keywordlist export */
void ToKeywordlist(MetaData::Keywordlist & kwl, const std::string & prefix = "") const;
/** Keywordlist import */
static DopplerCentroid FromKeywordlist(const MetaData::Keywordlist & kwl, const std::string & prefix = "");
};
/** \struct Orbit
*
* \brief This structure is used to handle orbit information
*/
struct OTBMetadata_EXPORT Orbit
{
using PointType = itk::Point<double, 3>;
/** Timestamp at which orbit state vectors apply */
MetaData::TimePoint time;
/** Position vector */
PointType position;
/** Velocity vector */
PointType velocity;
/** Keywordlist export */
void ToKeywordlist(MetaData::Keywordlist & kwl, const std::string & prefix = "") const;
/** Keywordlist import */
static Orbit FromKeywordlist(const MetaData::Keywordlist & kwl, const std::string & prefix = "");
};
/** \struct BurstRecord
*
* \brief This structure is used to handle burst records
*/
struct OTBMetadata_EXPORT BurstRecord
{
MetaData::TimePoint azimuthStartTime;
MetaData::TimePoint azimuthStopTime;
unsigned long startLine;
unsigned long endLine;
unsigned long startSample;
unsigned long endSample;
double azimuthAnxTime;
/** Keywordlist export */
void ToKeywordlist(MetaData::Keywordlist & kwl, const std::string & prefix = "") const;
/** Keywordlist import */
static BurstRecord FromKeywordlist(const MetaData::Keywordlist & kwl, const std::string & prefix = "");
};
/** \struct GCPTime
*
* \brief This structure contains the azimuth and range times associated with a gcp
*/
struct OTBMetadata_EXPORT GCPTime
{
/** Azimuth time of the gcp */
MetaData::TimePoint azimuthTime;
/** Slant range time of the gcp */
double slantRangeTime;
/** Keywordlist export */
void ToKeywordlist(MetaData::Keywordlist & kwl, const std::string & prefix = "") const;
};
/** \struct CoordinateConversionRecord
*
* \brief This structure contains coefficients to convert between coordinates types, e.g.
* from ground range to slant range
*/
struct CoordinateConversionRecord
{
MetaData::TimePoint azimuthTime;
double rg0;
std::vector<double> coeffs;
/** Keywordlist export */
void ToKeywordlist(MetaData::Keywordlist & kwl, const std::string & prefix = "") const;
/** Keywordlist import */
static CoordinateConversionRecord FromKeywordlist(const MetaData::Keywordlist & kwl, const std::string & prefix = "");
};
/** \struct SARParam
*
* \brief SAR sensors parameters
*
* \ingroup OTBMetadata
*/
struct OTBMetadata_EXPORT SARParam
{
/** Azimuth Frequency Modulation (FM) rate list.
* contains an entry for each azimuth FM rate update made along azimuth.
*/
std::vector<AzimuthFmRate> azimuthFmRates;
MetaData::Duration azimuthTimeInterval;
double nearRangeTime;
double rangeSamplingRate;
double rangeResolution;
unsigned long numberOfLinesPerBurst;
unsigned long numberOfSamplesPerBurst;
bool rightLookingFlag = true;
/** Doppler centroid estimates */
std::vector<DopplerCentroid> dopplerCentroids;
/** List of orbit information */
std::vector<Orbit> orbits;
/** List of burst records */
std::vector<BurstRecord> burstRecords;
/** map between GCP ids and corresponding azimuth and range times */
std::unordered_map<std::string, GCPTime> gcpTimes;
/** Conversion coefficients from slant range to ground range */
std::vector<CoordinateConversionRecord> slantRangeToGroundRangeRecords;
/** Conversion coefficients from ground range to slant range */
std::vector<CoordinateConversionRecord> groundRangeToSlantRangeRecords;
/** Keywordlist export */
void ToKeywordlist(MetaData::Keywordlist & kwl, const std::string & prefix) const;
/** Keywordlist import */
void FromKeywordlist(const MetaData::Keywordlist & kwl, const std::string & prefix);
// Equality comparison operator (hidden friend idiom)
friend bool operator==(const SARParam & lhs, const SARParam & rhs)
{
MetaData::Keywordlist lhs_kwl;
lhs.ToKeywordlist(lhs_kwl, "");
MetaData::Keywordlist rhs_kwl;
rhs.ToKeywordlist(rhs_kwl, "");
return lhs_kwl == rhs_kwl;
}
};
/** \struct SARCalib
*
* \brief SAR calibration LUTs
*
* \ingroup OTBMetadata
*/
struct OTBMetadata_EXPORT SARCalib
{
using PointSetType = itk::PointSet<double, 2>;
using ArrayType = std::array<int, 2>;
bool calibrationLookupFlag = false;
double rescalingFactor;
MetaData::TimePoint calibrationStartTime;
MetaData::TimePoint calibrationStopTime;
ArrayType radiometricCalibrationNoisePolynomialDegree;
ArrayType radiometricCalibrationAntennaPatternNewGainPolynomialDegree;
ArrayType radiometricCalibrationAntennaPatternOldGainPolynomialDegree;
ArrayType radiometricCalibrationIncidenceAnglePolynomialDegree;
ArrayType radiometricCalibrationRangeSpreadLossPolynomialDegree;
PointSetType::Pointer radiometricCalibrationNoise = PointSetType::New();
PointSetType::Pointer radiometricCalibrationAntennaPatternNewGain = PointSetType::New();
PointSetType::Pointer radiometricCalibrationAntennaPatternOldGain = PointSetType::New();
PointSetType::Pointer radiometricCalibrationIncidenceAngle = PointSetType::New();
PointSetType::Pointer radiometricCalibrationRangeSpreadLoss = PointSetType::New();
std::unordered_map<short, SarCalibrationLookupData::Pointer> calibrationLookupData;
/** Keywordlist export */
void ToKeywordlist(MetaData::Keywordlist & kwl, const std::string & prefix) const;
/** Keywordlist import */
void FromKeywordlist(const MetaData::Keywordlist & kwl, const std::string & prefix);
};
} // end namespace otb
#endif
| 2,500 |
2,116 | <reponame>ruchirjain86/professional-services
# Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Dataflow pipeline that reads 1-n files, transforms their content, and writes
it to BigQuery tables using schema information stored in DataStore.
To run this script, you will need Python packages listed in requirements.txt.
You can easily install them with virtualenv and pip by running these commands:
virtualenv env
source ./env/bin/activate
pip install -r requirements.txt
To get documentation on the script options run:
python dataflow_python_examples/data_ingestion_configurable.py --help
"""
import argparse
import csv
import json
import logging
import os
import io
from collections import OrderedDict
import apache_beam as beam
from apache_beam.io.gcp.internal.clients.bigquery import (TableFieldSchema,
TableSchema)
from google.api_core.exceptions import InvalidArgument
from google.auth.exceptions import GoogleAuthError
from google.cloud import datastore
class FileCoder:
"""Encode and decode CSV data coming from the files."""
def __init__(self, columns):
self._columns = columns
self._num_columns = len(columns)
self._delimiter = ","
def encode(self, value):
st = io.StringIO()
cw = csv.DictWriter(st,
self._columns,
delimiter=self._delimiter,
quotechar='"',
quoting=csv.QUOTE_MINIMAL)
cw.writerow(value)
return st.getvalue().strip('\r\n')
def decode(self, value):
st = io.StringIO(value)
cr = csv.DictWriter(st,
self._columns,
delimiter=self._delimiter,
quotechar='"',
quoting=csv.QUOTE_MINIMAL)
return next(cr)
class PrepareFieldTypes(beam.DoFn):
def __init__(self, encoding='utf-8', time_format='%Y-%m-%d %H:%M:%S %Z'):
import importlib
self._encoding = encoding
# Additional time format to use in case the default one does not work
self._time_format = [time_format, '%Y-%m-%d %H:%M:%S', '%Y-%m-%d']
self._tm = importlib.import_module('time')
def _return_default_value(self, ftype):
if ftype == 'INTEGER':
return 0
elif ftype == 'FLOAT':
return 0
elif ftype == 'DATATIME':
return self._tm.mktime(self._tm.strptime('1970-01-01', '%Y-%m-%d'))
elif ftype == 'TIMESTAMP':
return 0
else:
return ''
def process(self, element, fields):
if not hasattr(element, '__len__'):
logging.warn('Element %s has no length' % element)
return []
if len(element) != len(fields):
logging.warn('Row has %s elements instead of %s' %
(len(element), len(fields)))
return []
for k, v in element.items():
ftype = fields[k]
try:
if not v:
v = self._return_default_value(ftype)
elif ftype == 'STRING':
if isinstance(v, str):
v = v.decode(self._encoding, errors='ignore')
elif ftype == 'INTEGER':
v = int(v)
elif ftype == 'FLOAT':
v = float(v)
elif ftype == 'DATETIME':
try:
v = self._tm.mktime(
self._tm.strptime(v, self._time_format))
except (ValueError, TypeError) as e:
logging.warn('Cannot convert type %s for element %s: '
'%s. Returning default value.' %
(ftype, v, e))
v = self._return_default_value(ftype)
elif ftype == 'TIMESTAMP':
for fmt in (self._time_format):
try:
v = int(self._tm.mktime(self._tm.strptime(v, fmt)))
except ValueError:
pass
else:
break
if not isinstance(v, int):
logging.warning(
'Cannot convert date %s. Expected value of type int'
% v)
v = self._return_default_value(ftype)
else:
logging.warning('Unknown field type %s' % ftype)
v = self._return_default_value(ftype)
except (TypeError, ValueError) as e:
logging.warning('Cannot convert type %s for element %s: '
'%s. Returning default value.' % (ftype, v, e))
v = self._return_default_value(ftype)
element[k] = v
return [element]
class InjectTimestamp(beam.DoFn):
def process(self, element):
import time
element['_RAWTIMESTAMP'] = int(time.mktime(time.gmtime()))
return [element]
def _fetch_table(table_name):
try:
client = datastore.Client()
except GoogleAuthError:
# TODO(lcaggioni.ludomagno): fail gracefully
pass
return client.get(client.key('Table', table_name))
def _get_bq_schema(fields):
bq_fields = []
for k, v in fields.items():
bq_fields.append(
TableFieldSchema(name=k, type=v, description='Field %s' % k))
bq_fields.append(
TableFieldSchema(name='_RAWTIMESTAMP',
type='TIMESTAMP',
description='Injected timestamp'))
return TableSchema(fields=bq_fields)
def run(argv=None):
"""The main function which creates the pipeline and runs it"""
parser = argparse.ArgumentParser()
parser.add_argument('--input-bucket',
dest='input_bucket',
required=True,
default='data-daimlr',
help='GS bucket_name where the input files are present')
parser.add_argument(
'--input-path',
dest='input_path',
required=False,
help='GS folder name, if the input files are inside a bucket folder')
parser.add_argument(
'--input-files',
dest='input_files',
required=True,
help='Comma delimited names of all input files to be imported')
parser.add_argument('--bq-dataset',
dest='bq_dataset',
required=True,
default='rawdata',
help='Output BQ dataset to write the results to')
# Parse arguments from the command line
known_args, pipeline_args = parser.parse_known_args(argv)
# Initiate the pipeline using the pipeline arguments
logging.info('START - Pipeline')
p = beam.Pipeline(argv=pipeline_args)
for input_file in known_args.input_files.split(','):
logging.info('START - Preparing file %s' % (input_file))
table_name = os.path.splitext(input_file)[0].split('_')[0]
logging.info('Retrieving information for table %s' % (table_name))
try:
table = _fetch_table(table_name)
except InvalidArgument as e:
raise SystemExit('Error getting information for table [%s]: %s' %
(table_name, e))
if not table:
raise SystemExit('No table found')
fields = json.loads(table['columns'].decode('utf-8'),
object_pairs_hook=OrderedDict)
gs_path = os.path.join(
known_args.input_bucket, *[
known_args.input_path if known_args.input_path else "",
input_file
])
logging.info('GS path being read from: %s' % (gs_path))
(p | 'Read From Text - ' + input_file >> beam.io.ReadFromText(
gs_path, coder=FileCoder(list(fields.keys())), skip_header_lines=1)
| 'Prepare Field Types - ' + input_file >> beam.ParDo(
PrepareFieldTypes(), fields) |
'Inject Timestamp - ' + input_file >> beam.ParDo(InjectTimestamp()) |
'Write to BigQuery - ' + input_file >> beam.io.Write(
beam.io.BigQuerySink(
# The table name passed in from the command line
known_args.bq_dataset + '.' + table_name,
# Schema of the table
schema=_get_bq_schema(fields),
# Creates the table in BigQuery if it does not exist
create_disposition=beam.io.BigQueryDisposition.
CREATE_IF_NEEDED,
# Data will be appended to the table
write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND)))
logging.info('END - Preparing file %s' % (input_file))
p.run().wait_until_finish()
logging.info('END - Pipeline')
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
run()
| 4,735 |
528 | <filename>onactivityresult-compiler/src/main/java/onactivityresult/compiler/AnnotatedParameter.java
package onactivityresult.compiler;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeVariableName;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.Locale;
import javax.lang.model.element.Element;
import onactivityresult.Extra;
import onactivityresult.ExtraBoolean;
import onactivityresult.ExtraByte;
import onactivityresult.ExtraChar;
import onactivityresult.ExtraDouble;
import onactivityresult.ExtraFloat;
import onactivityresult.ExtraInt;
import onactivityresult.ExtraLong;
import onactivityresult.ExtraShort;
import onactivityresult.ExtraString;
import onactivityresult.IntentData;
public enum AnnotatedParameter {
BOOLEAN(ExtraBoolean.class, TypeVariableName.BOOLEAN) {
@Override
Parameter createParameter(final Element element) {
final ExtraBoolean extraAnnotation = element.getAnnotation(ExtraBoolean.class);
final boolean defaultValue = extraAnnotation != null && extraAnnotation.defaultValue();
final String parameterName = getParameterName(element, extraAnnotation != null && extraAnnotation.name().length() > 0 ? extraAnnotation.name() : null);
return Parameter.create(this, parameterName, String.valueOf(defaultValue));
}
},
BYTE(ExtraByte.class, TypeVariableName.BYTE) {
@Override
Parameter createParameter(final Element element) {
final ExtraByte extraAnnotation = element.getAnnotation(ExtraByte.class);
final byte defaultValue = extraAnnotation != null ? extraAnnotation.defaultValue() : 0;
final String parameterName = getParameterName(element, extraAnnotation != null && extraAnnotation.name().length() > 0 ? extraAnnotation.name() : null);
return Parameter.create(this, parameterName, String.valueOf(defaultValue));
}
},
CHAR(ExtraChar.class, TypeVariableName.CHAR) {
@Override
Parameter createParameter(final Element element) {
final ExtraChar extraAnnotation = element.getAnnotation(ExtraChar.class);
final char defaultValue = extraAnnotation != null ? extraAnnotation.defaultValue() : 0;
final String parameterName = getParameterName(element, extraAnnotation != null && extraAnnotation.name().length() > 0 ? extraAnnotation.name() : null);
return Parameter.create(this, parameterName, String.valueOf((int) defaultValue));
}
},
DOUBLE(ExtraDouble.class, TypeVariableName.DOUBLE) {
@Override
Parameter createParameter(final Element element) {
final ExtraDouble extraAnnotation = element.getAnnotation(ExtraDouble.class);
final double defaultValue = extraAnnotation != null ? extraAnnotation.defaultValue() : 0d;
final String parameterName = getParameterName(element, extraAnnotation != null && extraAnnotation.name().length() > 0 ? extraAnnotation.name() : null);
return Parameter.create(this, parameterName, String.valueOf(defaultValue));
}
},
FLOAT(ExtraFloat.class, TypeVariableName.FLOAT) {
@Override
Parameter createParameter(final Element element) {
final ExtraFloat extraAnnotation = element.getAnnotation(ExtraFloat.class);
final float defaultValue = extraAnnotation != null ? extraAnnotation.defaultValue() : 0.f;
final String parameterName = getParameterName(element, extraAnnotation != null && extraAnnotation.name().length() > 0 ? extraAnnotation.name() : null);
return Parameter.create(this, parameterName, String.valueOf(defaultValue));
}
},
INT(ExtraInt.class, TypeVariableName.INT) {
@Override
Parameter createParameter(final Element element) {
final ExtraInt extraAnnotation = element.getAnnotation(ExtraInt.class);
final int defaultValue = extraAnnotation != null ? extraAnnotation.defaultValue() : 0;
final String parameterName = getParameterName(element, extraAnnotation != null && extraAnnotation.name().length() > 0 ? extraAnnotation.name() : null);
return Parameter.create(this, parameterName, String.valueOf(defaultValue));
}
},
LONG(ExtraLong.class, TypeVariableName.LONG) {
@Override
Parameter createParameter(final Element element) {
final ExtraLong extraAnnotation = element.getAnnotation(ExtraLong.class);
final long defaultValue = extraAnnotation != null ? extraAnnotation.defaultValue() : 0L;
final String parameterName = getParameterName(element, extraAnnotation != null && extraAnnotation.name().length() > 0 ? extraAnnotation.name() : null);
return Parameter.create(this, parameterName, String.valueOf(defaultValue));
}
},
SHORT(ExtraShort.class, TypeVariableName.SHORT) {
@Override
Parameter createParameter(final Element element) {
final ExtraShort extraAnnotation = element.getAnnotation(ExtraShort.class);
final short defaultValue = extraAnnotation != null ? extraAnnotation.defaultValue() : 0;
final String parameterName = getParameterName(element, extraAnnotation != null && extraAnnotation.name().length() > 0 ? extraAnnotation.name() : null);
return Parameter.create(this, parameterName, String.valueOf(defaultValue));
}
},
STRING(ExtraString.class, ClassName.get(String.class)) {
@Override
Parameter createParameter(final Element element) {
final ExtraString extraAnnotation = element.getAnnotation(ExtraString.class);
final String defaultValue = extraAnnotation != null ? extraAnnotation.defaultValue() : null;
final String parameterName = getParameterName(element, extraAnnotation != null && extraAnnotation.name().length() > 0 ? extraAnnotation.name() : null);
return Parameter.create(this, parameterName, defaultValue);
}
},
CHAR_SEQUENCE(Extra.class, ClassName.get(CharSequence.class)) {
@Override
Parameter createParameter(final Element element) {
final String parameterName = getParameterName(element, null);
return Parameter.create(this, parameterName);
}
},
BUNDLE(Extra.class, ClassName.get("android.os", "Bundle")) {
@Override
Parameter createParameter(final Element element) {
final String parameterName = getParameterName(element, null);
return Parameter.create(this, parameterName);
}
},
SERIALIZABLE(Extra.class, ClassName.get(Serializable.class)) {
@Override
Parameter createParameter(final Element element) {
final ClassName className = (ClassName) TypeVariableName.get(element.asType());
final String parameterName = getParameterName(element, null);
return Parameter.create(this, parameterName, className);
}
},
PARCELABLE(Extra.class, ClassName.get("android.os", "Parcelable")) {
@Override
Parameter createParameter(final Element element) {
final ClassName className = (ClassName) TypeVariableName.get(element.asType());
final String parameterName = getParameterName(element, null);
return Parameter.create(this, parameterName, className);
}
},
INTENT_DATA(IntentData.class, ClassName.get("android.net", "Uri")) {
@Override
Parameter createParameter(final Element element) {
final Parameter.PreCondition preCondition = Parameter.PreCondition.from(element.getAnnotationMirrors());
return Parameter.createIntentData(preCondition);
}
};
static String getParameterName(final Element element, final String other) {
final Extra extra = element.getAnnotation(Extra.class);
final String name = extra != null ? extra.name() : null;
if (name != null && name.length() > 0) {
return name;
} else if (other != null && other.length() > 0) {
return other;
}
return element.getSimpleName().toString();
}
public final Class<? extends Annotation> annotation;
public final TypeName type;
AnnotatedParameter(final Class<? extends Annotation> annotation, final TypeName type) {
this.annotation = annotation;
this.type = type;
}
abstract Parameter createParameter(Element element);
public String readableName() {
final String[] split = this.name().split("_");
final StringBuilder sb = new StringBuilder();
for (final String string : split) {
sb.append(string.charAt(0)).append(string.substring(1).toLowerCase(Locale.US));
}
return sb.toString();
}
}
| 3,168 |
2,406 | <gh_stars>1000+
/* This configuration file is the fastest way to get started with the default
sparsity and default quantization algorithm. It contains only mandatory options
with commonly used values. All other options can be considered as an advanced
mode and requires deep knowledge of the quantization process. An overall description
of all possible parameters can be found in the default_quantization_spec.json */
{
/* Model parameters */
"model": {
"model_name": "model_name", // Model name
"model": "<MODEL_PATH>", // Path to model (.xml format)
"weights": "<PATH_TO_WEIGHTS>" // Path to weights (.bin format)
},
/* Parameters of the engine used for model inference */
"engine": {
"config": "<CONFIG_PATH>" // Path to Accuracy Checker config
},
/* Optimization hyperparameters */
"compression": {
"target_device": "ANY", // Target device, the specificity of which will be taken
// into account during optimization
"algorithms": [
{
"name": "WeightSparsity",
"params": {
"sparsity_level": 0.3,
"stat_subset_size": 300 // Size of subset to calculate activations statistics that can be used
// for quantization parameters calculation
}
},
{
"name": "DefaultQuantization", // Optimization algorithm name
"params": {
// Preset [performance, mixed, accuracy] which control the quantization mode
// (symmetric, mixed (weights symmetric and activations asymmetric) and fully
// asymmetric respectively)
"preset": "performance",
"stat_subset_size": 300 // Size of subset to calculate activations statistics that can be used
// for quantization parameters calculation
}
}
]
}
}
| 871 |
953 | <reponame>colesbury/nogil-staging<filename>Python/importlib_zipimport.h<gh_stars>100-1000
/* Auto-generated by Programs/_freeze_importlib.c */
const unsigned char _Py_M__zipimport[] = {
99,85,1,0,0,0,0,128,0,0,0,0,0,0,0,0,
0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,8,0,0,0,81,0,0,0,15,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,193,80,2,
0,0,122,105,112,105,109,112,111,114,116,32,112,114,111,118,
105,100,101,115,32,115,117,112,112,111,114,116,32,102,111,114,
32,105,109,112,111,114,116,105,110,103,32,80,121,116,104,111,
110,32,109,111,100,117,108,101,115,32,102,114,111,109,32,90,
105,112,32,97,114,99,104,105,118,101,115,46,10,10,84,104,
105,115,32,109,111,100,117,108,101,32,101,120,112,111,114,116,
115,32,116,104,114,101,101,32,111,98,106,101,99,116,115,58,
10,45,32,122,105,112,105,109,112,111,114,116,101,114,58,32,
97,32,99,108,97,115,115,59,32,105,116,115,32,99,111,110,
115,116,114,117,99,116,111,114,32,116,97,107,101,115,32,97,
32,112,97,116,104,32,116,111,32,97,32,90,105,112,32,97,
114,99,104,105,118,101,46,10,45,32,90,105,112,73,109,112,
111,114,116,69,114,114,111,114,58,32,101,120,99,101,112,116,
105,111,110,32,114,97,105,115,101,100,32,98,121,32,122,105,
112,105,109,112,111,114,116,101,114,32,111,98,106,101,99,116,
115,46,32,73,116,39,115,32,97,10,32,32,115,117,98,99,
108,97,115,115,32,111,102,32,73,109,112,111,114,116,69,114,
114,111,114,44,32,115,111,32,105,116,32,99,97,110,32,98,
101,32,99,97,117,103,104,116,32,97,115,32,73,109,112,111,
114,116,69,114,114,111,114,44,32,116,111,111,46,10,45,32,
95,122,105,112,95,100,105,114,101,99,116,111,114,121,95,99,
97,99,104,101,58,32,97,32,100,105,99,116,44,32,109,97,
112,112,105,110,103,32,97,114,99,104,105,118,101,32,112,97,
116,104,115,32,116,111,32,122,105,112,32,100,105,114,101,99,
116,111,114,121,10,32,32,105,110,102,111,32,100,105,99,116,
115,44,32,97,115,32,117,115,101,100,32,105,110,32,122,105,
112,105,109,112,111,114,116,101,114,46,95,102,105,108,101,115,
46,10,10,73,116,32,105,115,32,117,115,117,97,108,108,121,
32,110,111,116,32,110,101,101,100,101,100,32,116,111,32,117,
115,101,32,116,104,101,32,122,105,112,105,109,112,111,114,116,
32,109,111,100,117,108,101,32,101,120,112,108,105,99,105,116,
108,121,59,32,105,116,32,105,115,10,117,115,101,100,32,98,
121,32,116,104,101,32,98,117,105,108,116,105,110,32,105,109,
112,111,114,116,32,109,101,99,104,97,110,105,115,109,32,102,
111,114,32,115,121,115,46,112,97,116,104,32,105,116,101,109,
115,32,116,104,97,116,32,97,114,101,32,112,97,116,104,115,
10,116,111,32,90,105,112,32,97,114,99,104,105,118,101,115,
46,10,218,7,95,95,100,111,99,95,95,169,3,218,26,95,
102,114,111,122,101,110,95,105,109,112,111,114,116,108,105,98,
95,101,120,116,101,114,110,97,108,78,233,0,0,0,0,218,
19,95,98,111,111,116,115,116,114,97,112,95,101,120,116,101,
114,110,97,108,169,3,114,3,0,0,0,169,2,218,14,95,
117,110,112,97,99,107,95,117,105,110,116,49,54,218,14,95,
117,110,112,97,99,107,95,117,105,110,116,51,50,114,4,0,
0,0,114,8,0,0,0,114,9,0,0,0,169,3,218,17,
95,102,114,111,122,101,110,95,105,109,112,111,114,116,108,105,
98,78,114,4,0,0,0,218,10,95,98,111,111,116,115,116,
114,97,112,169,3,218,4,95,105,109,112,78,114,4,0,0,
0,114,14,0,0,0,169,3,218,3,95,105,111,78,114,4,
0,0,0,114,16,0,0,0,169,3,218,7,109,97,114,115,
104,97,108,78,114,4,0,0,0,114,18,0,0,0,169,3,
218,3,115,121,115,78,114,4,0,0,0,114,20,0,0,0,
169,3,218,4,116,105,109,101,78,114,4,0,0,0,114,22,
0,0,0,218,14,90,105,112,73,109,112,111,114,116,69,114,
114,111,114,218,11,122,105,112,105,109,112,111,114,116,101,114,
218,7,95,95,97,108,108,95,95,218,8,112,97,116,104,95,
115,101,112,218,15,112,97,116,104,95,115,101,112,97,114,97,
116,111,114,115,186,233,1,0,0,0,78,78,218,12,97,108,
116,95,112,97,116,104,95,115,101,112,99,14,0,0,0,0,
0,128,0,0,0,0,0,0,0,0,0,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,5,
0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,218,8,95,95,110,97,109,101,95,
95,218,10,95,95,109,111,100,117,108,101,95,95,114,23,0,
0,0,218,12,95,95,113,117,97,108,110,97,109,101,95,95,
78,33,0,0,0,41,1,218,8,60,108,111,99,97,108,115,
62,169,0,114,35,0,0,0,250,18,60,102,114,111,122,101,
110,32,122,105,112,105,109,112,111,114,116,62,114,23,0,0,
0,115,4,0,0,0,2,0,9,1,6,1,51,0,254,59,
1,52,2,59,3,52,4,75,218,11,73,109,112,111,114,116,
69,114,114,111,114,218,20,95,122,105,112,95,100,105,114,101,
99,116,111,114,121,95,99,97,99,104,101,218,4,116,121,112,
101,218,12,95,109,111,100,117,108,101,95,116,121,112,101,233,
22,0,0,0,218,20,69,78,68,95,67,69,78,84,82,65,
76,95,68,73,82,95,83,73,90,69,243,4,0,0,0,80,
75,5,6,218,18,83,84,82,73,78,71,95,69,78,68,95,
65,82,67,72,73,86,69,233,255,255,0,0,218,15,77,65,
88,95,67,79,77,77,69,78,84,95,76,69,78,99,74,0,
0,0,0,0,128,0,0,0,0,0,0,0,0,0,12,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,13,0,
0,0,29,0,0,0,2,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,114,31,0,0,0,114,
32,0,0,0,114,24,0,0,0,114,33,0,0,0,193,255,
1,0,0,122,105,112,105,109,112,111,114,116,101,114,40,97,
114,99,104,105,118,101,112,97,116,104,41,32,45,62,32,122,
105,112,105,109,112,111,114,116,101,114,32,111,98,106,101,99,
116,10,10,32,32,32,32,67,114,101,97,116,101,32,97,32,
110,101,119,32,122,105,112,105,109,112,111,114,116,101,114,32,
105,110,115,116,97,110,99,101,46,32,39,97,114,99,104,105,
118,101,112,97,116,104,39,32,109,117,115,116,32,98,101,32,
97,32,112,97,116,104,32,116,111,10,32,32,32,32,97,32,
122,105,112,102,105,108,101,44,32,111,114,32,116,111,32,97,
32,115,112,101,99,105,102,105,99,32,112,97,116,104,32,105,
110,115,105,100,101,32,97,32,122,105,112,102,105,108,101,46,
32,70,111,114,32,101,120,97,109,112,108,101,44,32,105,116,
32,99,97,110,32,98,101,10,32,32,32,32,39,47,116,109,
112,47,109,121,105,109,112,111,114,116,46,122,105,112,39,44,
32,111,114,32,39,47,116,109,112,47,109,121,105,109,112,111,
114,116,46,122,105,112,47,109,121,100,105,114,101,99,116,111,
114,121,39,44,32,105,102,32,109,121,100,105,114,101,99,116,
111,114,121,32,105,115,32,97,10,32,32,32,32,118,97,108,
105,100,32,100,105,114,101,99,116,111,114,121,32,105,110,115,
105,100,101,32,116,104,101,32,97,114,99,104,105,118,101,46,
10,10,32,32,32,32,39,90,105,112,73,109,112,111,114,116,
69,114,114,111,114,32,105,115,32,114,97,105,115,101,100,32,
105,102,32,39,97,114,99,104,105,118,101,112,97,116,104,39,
32,100,111,101,115,110,39,116,32,112,111,105,110,116,32,116,
111,32,97,32,118,97,108,105,100,32,90,105,112,10,32,32,
32,32,97,114,99,104,105,118,101,46,10,10,32,32,32,32,
84,104,101,32,39,97,114,99,104,105,118,101,39,32,97,116,
116,114,105,98,117,116,101,32,111,102,32,122,105,112,105,109,
112,111,114,116,101,114,32,111,98,106,101,99,116,115,32,99,
111,110,116,97,105,110,115,32,116,104,101,32,110,97,109,101,
32,111,102,32,116,104,101,10,32,32,32,32,122,105,112,102,
105,108,101,32,116,97,114,103,101,116,101,100,46,10,32,32,
32,32,114,1,0,0,0,99,127,1,0,0,2,0,0,0,
3,0,0,0,2,0,0,0,8,0,0,0,0,0,0,0,
0,0,0,0,2,0,0,0,17,0,0,0,30,0,0,0,
31,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,
0,0,0,0,78,218,20,122,105,112,105,109,112,111,114,116,
101,114,46,95,95,105,110,105,116,95,95,218,10,105,115,105,
110,115,116,97,110,99,101,218,3,115,116,114,169,3,218,2,
111,115,78,114,4,0,0,0,218,8,102,115,100,101,99,111,
100,101,114,23,0,0,0,218,21,97,114,99,104,105,118,101,
32,112,97,116,104,32,105,115,32,101,109,112,116,121,169,1,
218,4,112,97,116,104,114,30,0,0,0,218,7,114,101,112,
108,97,99,101,114,26,0,0,0,114,5,0,0,0,218,10,
95,112,97,116,104,95,115,116,97,116,218,7,79,83,69,114,
114,111,114,218,10,86,97,108,117,101,69,114,114,111,114,218,
11,95,112,97,116,104,95,115,112,108,105,116,218,14,110,111,
116,32,97,32,90,105,112,32,102,105,108,101,218,6,97,112,
112,101,110,100,218,7,115,116,95,109,111,100,101,233,0,240,
0,0,233,0,128,0,0,114,38,0,0,0,218,8,75,101,
121,69,114,114,111,114,218,15,95,114,101,97,100,95,100,105,
114,101,99,116,111,114,121,218,6,95,102,105,108,101,115,218,
7,97,114,99,104,105,118,101,218,10,95,112,97,116,104,95,
106,111,105,110,186,78,78,233,255,255,255,255,218,6,112,114,
101,102,105,120,102,0,0,0,121,0,0,0,216,0,0,0,
8,0,0,0,11,1,0,0,27,1,0,0,67,1,0,0,
8,0,0,0,63,0,0,0,41,8,218,4,115,101,108,102,
114,56,0,0,0,114,52,0,0,0,114,74,0,0,0,218,
2,115,116,218,7,100,105,114,110,97,109,101,218,8,98,97,
115,101,110,97,109,101,218,5,102,105,108,101,115,114,35,0,
0,0,114,35,0,0,0,114,36,0,0,0,218,8,95,95,
105,110,105,116,95,95,115,58,0,0,0,2,0,0,1,21,
1,4,1,15,1,6,1,21,1,6,1,22,2,5,3,19,
1,17,3,24,1,8,1,21,1,4,1,21,3,24,2,21,
1,3,240,3,19,16,1,7,1,14,1,19,1,5,1,5,
2,24,1,7,1,6,17,54,2,254,58,11,4,12,1,54,
3,252,58,13,70,12,2,0,17,83,22,0,88,4,58,2,
50,2,55,11,5,251,4,13,1,72,12,2,0,58,1,50,
1,17,83,24,0,54,6,249,58,13,52,7,58,14,4,8,
1,52,8,58,9,70,14,1,1,76,54,9,247,83,25,0,
50,1,55,11,10,246,54,9,247,58,13,54,11,244,58,14,
72,12,3,0,58,1,93,8,0,58,3,54,12,242,55,11,
13,241,4,13,1,72,12,2,0,58,4,79,98,0,54,14,
239,58,10,54,15,237,58,11,92,10,2,82,8,80,0,54,
12,242,55,13,16,236,4,15,1,72,14,2,0,105,10,2,
0,5,5,11,5,6,10,50,1,36,2,5,83,24,0,54,
6,249,58,15,52,17,58,16,4,10,1,52,8,58,11,70,
16,1,1,76,50,5,58,1,50,3,55,13,18,235,4,15,
6,72,14,2,0,1,96,8,79,53,0,98,8,53,4,19,
234,58,8,52,20,31,8,2,8,58,8,52,21,36,3,8,
2,8,83,24,0,54,6,249,58,13,52,17,58,14,4,8,
1,52,8,58,9,70,14,1,1,76,79,6,0,79,94,255,
54,22,232,58,8,50,1,26,8,2,8,58,7,79,43,0,
54,23,230,82,8,35,0,54,24,228,58,13,4,14,1,70,
14,1,0,58,7,54,22,232,58,10,50,7,62,10,1,2,
10,96,8,79,5,0,98,8,50,7,60,0,25,50,1,60,
0,26,54,12,242,58,14,53,14,27,227,2,14,58,13,52,
28,26,3,58,8,71,14,60,0,29,53,0,29,226,83,19,
0,53,0,29,225,58,8,54,11,244,39,8,60,0,29,2,
8,52,0,75,114,80,0,0,0,78,99,127,0,0,0,3,
0,0,0,3,0,0,0,3,0,0,0,5,0,0,0,1,
0,0,0,0,0,0,0,3,0,0,0,11,0,0,0,8,
0,0,0,9,0,0,0,0,0,0,0,1,0,0,0,0,
0,0,0,0,0,0,0,193,239,1,0,0,102,105,110,100,
95,108,111,97,100,101,114,40,102,117,108,108,110,97,109,101,
44,32,112,97,116,104,61,78,111,110,101,41,32,45,62,32,
115,101,108,102,44,32,115,116,114,32,111,114,32,78,111,110,
101,46,10,10,32,32,32,32,32,32,32,32,83,101,97,114,
99,104,32,102,111,114,32,97,32,109,111,100,117,108,101,32,
115,112,101,99,105,102,105,101,100,32,98,121,32,39,102,117,
108,108,110,97,109,101,39,46,32,39,102,117,108,108,110,97,
109,101,39,32,109,117,115,116,32,98,101,32,116,104,101,10,
32,32,32,32,32,32,32,32,102,117,108,108,121,32,113,117,
97,108,105,102,105,101,100,32,40,100,111,116,116,101,100,41,
32,109,111,100,117,108,101,32,110,97,109,101,46,32,73,116,
32,114,101,116,117,114,110,115,32,116,104,101,32,122,105,112,
105,109,112,111,114,116,101,114,10,32,32,32,32,32,32,32,
32,105,110,115,116,97,110,99,101,32,105,116,115,101,108,102,
32,105,102,32,116,104,101,32,109,111,100,117,108,101,32,119,
97,115,32,102,111,117,110,100,44,32,97,32,115,116,114,105,
110,103,32,99,111,110,116,97,105,110,105,110,103,32,116,104,
101,10,32,32,32,32,32,32,32,32,102,117,108,108,32,112,
97,116,104,32,110,97,109,101,32,105,102,32,105,116,39,115,
32,112,111,115,115,105,98,108,121,32,97,32,112,111,114,116,
105,111,110,32,111,102,32,97,32,110,97,109,101,115,112,97,
99,101,32,112,97,99,107,97,103,101,44,10,32,32,32,32,
32,32,32,32,111,114,32,78,111,110,101,32,111,116,104,101,
114,119,105,115,101,46,32,84,104,101,32,111,112,116,105,111,
110,97,108,32,39,112,97,116,104,39,32,97,114,103,117,109,
101,110,116,32,105,115,32,105,103,110,111,114,101,100,32,45,
45,32,105,116,39,115,10,32,32,32,32,32,32,32,32,116,
104,101,114,101,32,102,111,114,32,99,111,109,112,97,116,105,
98,105,108,105,116,121,32,119,105,116,104,32,116,104,101,32,
105,109,112,111,114,116,101,114,32,112,114,111,116,111,99,111,
108,46,10,32,32,32,32,32,32,32,32,218,23,122,105,112,
105,109,112,111,114,116,101,114,46,102,105,110,100,95,108,111,
97,100,101,114,218,16,95,103,101,116,95,109,111,100,117,108,
101,95,105,110,102,111,78,218,16,95,103,101,116,95,109,111,
100,117,108,101,95,112,97,116,104,218,7,95,105,115,95,100,
105,114,114,70,0,0,0,114,26,0,0,0,12,0,0,0,
2,0,0,0,109,0,0,0,41,5,114,75,0,0,0,218,
8,102,117,108,108,110,97,109,101,114,56,0,0,0,218,2,
109,105,218,7,109,111,100,112,97,116,104,114,35,0,0,0,
114,35,0,0,0,114,36,0,0,0,218,11,102,105,110,100,
95,108,111,97,100,101,114,115,16,0,0,0,2,0,0,10,
17,1,8,2,12,7,17,1,18,4,40,2,6,11,54,2,
254,58,8,4,9,0,4,10,1,70,9,2,0,58,3,52,
3,34,3,18,83,15,0,4,5,0,93,6,0,58,6,92,
5,2,75,54,4,252,58,8,4,9,0,4,10,1,70,9,
2,0,58,4,54,5,250,58,8,4,9,0,4,10,4,70,
9,2,0,83,43,0,52,3,58,5,53,0,6,249,73,4,
58,6,54,7,247,73,4,58,7,50,4,73,4,58,8,74,
6,6,3,58,6,93,6,1,58,6,92,5,2,75,52,3,
58,5,93,6,0,58,6,92,5,2,75,114,89,0,0,0,
99,27,0,0,0,3,0,0,0,3,0,0,0,3,0,0,
0,3,0,0,0,1,0,0,0,0,0,0,0,3,0,0,
0,10,0,0,0,4,0,0,0,1,0,0,0,0,0,0,
0,1,0,0,0,0,0,0,0,0,0,0,0,193,139,1,
0,0,102,105,110,100,95,109,111,100,117,108,101,40,102,117,
108,108,110,97,109,101,44,32,112,97,116,104,61,78,111,110,
101,41,32,45,62,32,115,101,108,102,32,111,114,32,78,111,
110,101,46,10,10,32,32,32,32,32,32,32,32,83,101,97,
114,99,104,32,102,111,114,32,97,32,109,111,100,117,108,101,
32,115,112,101,99,105,102,105,101,100,32,98,121,32,39,102,
117,108,108,110,97,109,101,39,46,32,39,102,117,108,108,110,
97,109,101,39,32,109,117,115,116,32,98,101,32,116,104,101,
10,32,32,32,32,32,32,32,32,102,117,108,108,121,32,113,
117,97,108,105,102,105,101,100,32,40,100,111,116,116,101,100,
41,32,109,111,100,117,108,101,32,110,97,109,101,46,32,73,
116,32,114,101,116,117,114,110,115,32,116,104,101,32,122,105,
112,105,109,112,111,114,116,101,114,10,32,32,32,32,32,32,
32,32,105,110,115,116,97,110,99,101,32,105,116,115,101,108,
102,32,105,102,32,116,104,101,32,109,111,100,117,108,101,32,
119,97,115,32,102,111,117,110,100,44,32,111,114,32,78,111,
110,101,32,105,102,32,105,116,32,119,97,115,110,39,116,46,
10,32,32,32,32,32,32,32,32,84,104,101,32,111,112,116,
105,111,110,97,108,32,39,112,97,116,104,39,32,97,114,103,
117,109,101,110,116,32,105,115,32,105,103,110,111,114,101,100,
32,45,45,32,105,116,39,115,32,116,104,101,114,101,32,102,
111,114,32,99,111,109,112,97,116,105,98,105,108,105,116,121,
10,32,32,32,32,32,32,32,32,119,105,116,104,32,116,104,
101,32,105,109,112,111,114,116,101,114,32,112,114,111,116,111,
99,111,108,46,10,32,32,32,32,32,32,32,32,218,23,122,
105,112,105,109,112,111,114,116,101,114,46,102,105,110,100,95,
109,111,100,117,108,101,114,89,0,0,0,114,4,0,0,0,
12,0,0,0,2,0,0,0,141,0,0,0,41,3,114,75,
0,0,0,114,86,0,0,0,114,56,0,0,0,114,35,0,
0,0,114,35,0,0,0,114,36,0,0,0,218,11,102,105,
110,100,95,109,111,100,117,108,101,115,4,0,0,0,2,0,
0,9,6,10,50,0,55,6,2,255,4,8,1,4,9,2,
72,7,3,0,58,3,52,3,26,3,2,3,75,114,92,0,
0,0,99,33,0,0,0,2,0,0,0,3,0,0,0,2,
0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,2,
0,0,0,11,0,0,0,3,0,0,0,2,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,218,
163,103,101,116,95,99,111,100,101,40,102,117,108,108,110,97,
109,101,41,32,45,62,32,99,111,100,101,32,111,98,106,101,
99,116,46,10,10,32,32,32,32,32,32,32,32,82,101,116,
117,114,110,32,116,104,101,32,99,111,100,101,32,111,98,106,
101,99,116,32,102,111,114,32,116,104,101,32,115,112,101,99,
105,102,105,101,100,32,109,111,100,117,108,101,46,32,82,97,
105,115,101,32,90,105,112,73,109,112,111,114,116,69,114,114,
111,114,10,32,32,32,32,32,32,32,32,105,102,32,116,104,
101,32,109,111,100,117,108,101,32,99,111,117,108,100,110,39,
116,32,98,101,32,102,111,117,110,100,46,10,32,32,32,32,
32,32,32,32,218,20,122,105,112,105,109,112,111,114,116,101,
114,46,103,101,116,95,99,111,100,101,218,16,95,103,101,116,
95,109,111,100,117,108,101,95,99,111,100,101,153,0,0,0,
41,5,114,75,0,0,0,114,86,0,0,0,218,4,99,111,
100,101,218,9,105,115,112,97,99,107,97,103,101,114,88,0,
0,0,114,35,0,0,0,114,35,0,0,0,114,36,0,0,
0,218,8,103,101,116,95,99,111,100,101,115,6,0,0,0,
2,0,0,6,28,1,6,11,54,2,254,58,8,4,9,0,
4,10,1,70,9,2,0,105,5,3,0,5,2,7,5,3,
6,5,4,5,50,2,75,114,98,0,0,0,99,168,0,0,
0,2,0,0,0,3,0,0,0,2,0,0,0,4,0,0,
0,0,0,0,0,0,0,0,0,2,0,0,0,13,0,0,
0,15,0,0,0,18,0,0,0,0,0,0,0,0,0,0,
0,1,0,0,0,0,0,0,0,218,154,103,101,116,95,100,
97,116,97,40,112,97,116,104,110,97,109,101,41,32,45,62,
32,115,116,114,105,110,103,32,119,105,116,104,32,102,105,108,
101,32,100,97,116,97,46,10,10,32,32,32,32,32,32,32,
32,82,101,116,117,114,110,32,116,104,101,32,100,97,116,97,
32,97,115,115,111,99,105,97,116,101,100,32,119,105,116,104,
32,39,112,97,116,104,110,97,109,101,39,46,32,82,97,105,
115,101,32,79,83,69,114,114,111,114,32,105,102,10,32,32,
32,32,32,32,32,32,116,104,101,32,102,105,108,101,32,119,
97,115,110,39,116,32,102,111,117,110,100,46,10,32,32,32,
32,32,32,32,32,218,20,122,105,112,105,109,112,111,114,116,
101,114,46,103,101,116,95,100,97,116,97,114,30,0,0,0,
114,57,0,0,0,114,26,0,0,0,218,10,115,116,97,114,
116,115,119,105,116,104,114,70,0,0,0,218,3,108,101,110,
78,114,69,0,0,0,114,67,0,0,0,114,59,0,0,0,
114,4,0,0,0,218,0,218,9,95,103,101,116,95,100,97,
116,97,102,0,0,0,119,0,0,0,149,0,0,0,4,0,
0,0,163,0,0,0,41,4,114,75,0,0,0,218,8,112,
97,116,104,110,97,109,101,218,3,107,101,121,218,9,116,111,
99,95,101,110,116,114,121,114,35,0,0,0,114,35,0,0,
0,114,36,0,0,0,218,8,103,101,116,95,100,97,116,97,
115,20,0,0,0,2,0,0,6,6,1,22,2,4,1,28,
1,40,3,17,1,7,1,23,1,6,13,54,2,254,83,25,
0,50,1,55,7,3,253,54,2,254,58,9,54,4,251,58,
10,72,8,3,0,58,1,50,1,58,2,50,1,55,7,5,
250,53,0,6,249,58,9,54,4,251,24,9,2,9,58,9,
72,8,2,0,83,43,0,54,7,247,58,7,53,0,6,246,
58,8,54,4,251,24,8,2,8,58,8,70,8,1,0,58,
4,52,8,58,5,52,8,58,6,91,4,26,1,58,2,53,
0,9,245,58,4,50,2,26,4,2,4,58,3,79,33,0,
54,10,243,82,4,25,0,54,11,241,58,9,52,12,58,10,
52,13,58,11,4,12,2,70,10,3,0,76,98,4,54,14,
239,58,7,53,0,6,238,58,8,4,9,3,70,8,2,0,
75,114,108,0,0,0,99,33,0,0,0,2,0,0,0,3,
0,0,0,2,0,0,0,5,0,0,0,0,0,0,0,0,
0,0,0,2,0,0,0,11,0,0,0,3,0,0,0,2,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,218,106,103,101,116,95,102,105,108,101,110,97,109,
101,40,102,117,108,108,110,97,109,101,41,32,45,62,32,102,
105,108,101,110,97,109,101,32,115,116,114,105,110,103,46,10,
10,32,32,32,32,32,32,32,32,82,101,116,117,114,110,32,
116,104,101,32,102,105,108,101,110,97,109,101,32,102,111,114,
32,116,104,101,32,115,112,101,99,105,102,105,101,100,32,109,
111,100,117,108,101,46,10,32,32,32,32,32,32,32,32,218,
24,122,105,112,105,109,112,111,114,116,101,114,46,103,101,116,
95,102,105,108,101,110,97,109,101,114,95,0,0,0,184,0,
0,0,41,5,114,75,0,0,0,114,86,0,0,0,114,96,
0,0,0,114,97,0,0,0,114,88,0,0,0,114,35,0,
0,0,114,35,0,0,0,114,36,0,0,0,218,12,103,101,
116,95,102,105,108,101,110,97,109,101,115,6,0,0,0,2,
0,0,7,28,1,6,11,54,2,254,58,8,4,9,0,4,
10,1,70,9,2,0,105,5,3,0,5,2,7,5,3,6,
5,4,5,50,4,75,114,111,0,0,0,99,180,0,0,0,
2,0,0,0,3,0,0,0,2,0,0,0,6,0,0,0,
0,0,0,0,0,0,0,0,2,0,0,0,14,0,0,0,
17,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,
1,0,0,0,0,0,0,0,218,253,103,101,116,95,115,111,
117,114,99,101,40,102,117,108,108,110,97,109,101,41,32,45,
62,32,115,111,117,114,99,101,32,115,116,114,105,110,103,46,
10,10,32,32,32,32,32,32,32,32,82,101,116,117,114,110,
32,116,104,101,32,115,111,117,114,99,101,32,99,111,100,101,
32,102,111,114,32,116,104,101,32,115,112,101,99,105,102,105,
101,100,32,109,111,100,117,108,101,46,32,82,97,105,115,101,
32,90,105,112,73,109,112,111,114,116,69,114,114,111,114,10,
32,32,32,32,32,32,32,32,105,102,32,116,104,101,32,109,
111,100,117,108,101,32,99,111,117,108,100,110,39,116,32,98,
101,32,102,111,117,110,100,44,32,114,101,116,117,114,110,32,
78,111,110,101,32,105,102,32,116,104,101,32,97,114,99,104,
105,118,101,32,100,111,101,115,10,32,32,32,32,32,32,32,
32,99,111,110,116,97,105,110,32,116,104,101,32,109,111,100,
117,108,101,44,32,98,117,116,32,104,97,115,32,110,111,32,
115,111,117,114,99,101,32,102,111,114,32,105,116,46,10,32,
32,32,32,32,32,32,32,218,22,122,105,112,105,109,112,111,
114,116,101,114,46,103,101,116,95,115,111,117,114,99,101,114,
83,0,0,0,78,114,23,0,0,0,218,18,99,97,110,39,
116,32,102,105,110,100,32,109,111,100,117,108,101,32,169,1,
218,4,110,97,109,101,114,84,0,0,0,114,5,0,0,0,
114,71,0,0,0,218,11,95,95,105,110,105,116,95,95,46,
112,121,218,3,46,112,121,114,69,0,0,0,114,67,0,0,
0,114,104,0,0,0,114,70,0,0,0,218,6,100,101,99,
111,100,101,122,0,0,0,139,0,0,0,153,0,0,0,6,
0,0,0,195,0,0,0,41,6,114,75,0,0,0,114,86,
0,0,0,114,87,0,0,0,114,56,0,0,0,218,8,102,
117,108,108,112,97,116,104,114,107,0,0,0,114,35,0,0,
0,114,35,0,0,0,114,36,0,0,0,218,10,103,101,116,
95,115,111,117,114,99,101,115,24,0,0,0,2,0,0,7,
17,1,7,1,35,2,17,1,5,1,23,2,16,3,17,1,
7,2,7,1,6,14,54,2,254,58,9,4,10,0,4,11,
1,70,10,2,0,58,2,52,3,34,2,83,38,0,54,4,
252,58,11,52,5,58,12,50,1,73,2,73,4,58,13,74,
6,12,2,58,12,4,6,1,52,6,58,7,70,12,1,1,
76,54,7,250,58,9,4,10,0,4,11,1,70,10,2,0,
58,3,50,2,83,26,0,54,8,248,55,9,9,247,4,11,
3,52,10,58,12,72,10,3,0,58,4,79,19,0,50,3,
73,4,58,6,52,11,58,7,74,6,6,2,58,4,53,0,
12,246,58,6,50,4,26,6,2,6,58,5,79,17,0,54,
13,244,82,6,9,0,52,3,96,6,75,98,6,54,14,242,
58,9,53,0,15,241,58,10,4,11,5,70,10,2,0,55,
9,16,240,72,10,1,0,75,114,121,0,0,0,99,64,0,
0,0,2,0,0,0,3,0,0,0,2,0,0,0,3,0,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,11,0,
0,0,7,0,0,0,4,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,218,171,105,115,95,112,
97,99,107,97,103,101,40,102,117,108,108,110,97,109,101,41,
32,45,62,32,98,111,111,108,46,10,10,32,32,32,32,32,
32,32,32,82,101,116,117,114,110,32,84,114,117,101,32,105,
102,32,116,104,101,32,109,111,100,117,108,101,32,115,112,101,
99,105,102,105,101,100,32,98,121,32,102,117,108,108,110,97,
109,101,32,105,115,32,97,32,112,97,99,107,97,103,101,46,
10,32,32,32,32,32,32,32,32,82,97,105,115,101,32,90,
105,112,73,109,112,111,114,116,69,114,114,111,114,32,105,102,
32,116,104,101,32,109,111,100,117,108,101,32,99,111,117,108,
100,110,39,116,32,98,101,32,102,111,117,110,100,46,10,32,
32,32,32,32,32,32,32,218,22,122,105,112,105,109,112,111,
114,116,101,114,46,105,115,95,112,97,99,107,97,103,101,114,
83,0,0,0,78,114,23,0,0,0,114,114,0,0,0,114,
115,0,0,0,221,0,0,0,41,3,114,75,0,0,0,114,
86,0,0,0,114,87,0,0,0,114,35,0,0,0,114,35,
0,0,0,114,36,0,0,0,218,10,105,115,95,112,97,99,
107,97,103,101,115,10,0,0,0,2,0,0,6,17,1,7,
1,35,1,6,11,54,2,254,58,6,4,7,0,4,8,1,
70,7,2,0,58,2,52,3,34,2,83,38,0,54,4,252,
58,8,52,5,58,9,50,1,73,2,73,4,58,10,74,6,
9,2,58,9,4,3,1,52,6,58,4,70,9,1,1,76,
50,2,75,114,124,0,0,0,99,101,1,0,0,2,0,0,
0,3,0,0,0,2,0,0,0,8,0,0,0,0,0,0,
0,0,0,0,0,2,0,0,0,17,0,0,0,27,0,0,
0,35,0,0,0,0,0,0,0,0,0,0,0,2,0,0,
0,0,0,0,0,218,245,108,111,97,100,95,109,111,100,117,
108,101,40,102,117,108,108,110,97,109,101,41,32,45,62,32,
109,111,100,117,108,101,46,10,10,32,32,32,32,32,32,32,
32,76,111,97,100,32,116,104,101,32,109,111,100,117,108,101,
32,115,112,101,99,105,102,105,101,100,32,98,121,32,39,102,
117,108,108,110,97,109,101,39,46,32,39,102,117,108,108,110,
97,109,101,39,32,109,117,115,116,32,98,101,32,116,104,101,
10,32,32,32,32,32,32,32,32,102,117,108,108,121,32,113,
117,97,108,105,102,105,101,100,32,40,100,111,116,116,101,100,
41,32,109,111,100,117,108,101,32,110,97,109,101,46,32,73,
116,32,114,101,116,117,114,110,115,32,116,104,101,32,105,109,
112,111,114,116,101,100,10,32,32,32,32,32,32,32,32,109,
111,100,117,108,101,44,32,111,114,32,114,97,105,115,101,115,
32,90,105,112,73,109,112,111,114,116,69,114,114,111,114,32,
105,102,32,105,116,32,119,97,115,110,39,116,32,102,111,117,
110,100,46,10,32,32,32,32,32,32,32,32,218,23,122,105,
112,105,109,112,111,114,116,101,114,46,108,111,97,100,95,109,
111,100,117,108,101,114,95,0,0,0,114,20,0,0,0,218,
7,109,111,100,117,108,101,115,218,3,103,101,116,78,114,49,
0,0,0,114,40,0,0,0,218,10,95,95,108,111,97,100,
101,114,95,95,114,84,0,0,0,114,5,0,0,0,114,71,
0,0,0,114,70,0,0,0,218,8,95,95,112,97,116,104,
95,95,218,7,104,97,115,97,116,116,114,218,12,95,95,98,
117,105,108,116,105,110,115,95,95,218,14,95,102,105,120,95,
117,112,95,109,111,100,117,108,101,218,8,95,95,100,105,99,
116,95,95,218,4,101,120,101,99,114,67,0,0,0,114,37,
0,0,0,218,14,76,111,97,100,101,100,32,109,111,100,117,
108,101,32,218,25,32,110,111,116,32,102,111,117,110,100,32,
105,110,32,115,121,115,46,109,111,100,117,108,101,115,114,12,
0,0,0,218,16,95,118,101,114,98,111,115,101,95,109,101,
115,115,97,103,101,218,30,105,109,112,111,114,116,32,123,125,
32,35,32,108,111,97,100,101,100,32,102,114,111,109,32,90,
105,112,32,123,125,122,0,0,0,247,0,0,0,11,1,0,
0,8,0,0,0,11,1,0,0,35,1,0,0,76,1,0,
0,8,0,0,0,234,0,0,0,41,8,114,75,0,0,0,
114,86,0,0,0,114,96,0,0,0,114,97,0,0,0,114,
88,0,0,0,218,3,109,111,100,114,56,0,0,0,114,120,
0,0,0,114,35,0,0,0,114,35,0,0,0,114,36,0,
0,0,218,11,108,111,97,100,95,109,111,100,117,108,101,115,
44,0,0,0,2,0,0,7,28,1,24,1,29,1,14,1,
20,1,5,3,5,3,17,1,22,1,9,2,20,1,6,1,
24,1,22,2,19,1,1,3,24,1,7,1,34,1,22,1,
6,17,54,2,254,58,11,4,12,0,4,13,1,70,12,2,
0,105,8,3,0,5,2,10,5,3,9,5,4,8,54,3,
252,58,8,53,8,4,251,2,8,55,11,5,250,4,13,1,
72,12,2,0,58,5,52,6,34,5,81,22,0,1,54,7,
248,58,11,4,12,5,54,8,246,58,13,70,12,2,0,17,
83,37,0,54,8,246,58,11,4,12,1,70,12,1,0,58,
5,54,3,252,58,8,53,8,4,245,2,8,58,8,50,5,
62,8,1,2,8,50,0,60,5,9,50,3,83,51,0,54,
10,243,58,11,4,12,0,4,13,1,70,12,2,0,58,6,
54,11,241,55,11,12,240,53,0,13,239,58,13,4,14,6,
72,12,3,0,58,7,4,8,7,93,8,1,60,5,14,54,
15,237,58,11,4,12,5,52,16,58,13,70,12,2,0,17,
83,9,0,54,16,235,60,5,16,54,11,241,55,11,17,234,
53,5,18,233,58,13,4,14,1,4,15,4,72,12,4,0,
1,54,19,231,58,11,4,12,2,53,5,18,230,58,13,70,
12,2,0,1,79,23,0,54,3,252,58,10,53,10,4,229,
2,10,58,10,50,1,68,10,2,10,76,54,3,252,58,8,
53,8,4,228,2,8,58,8,50,1,26,8,2,8,58,5,
79,44,0,54,20,226,82,8,36,0,54,21,224,58,13,52,
22,58,14,50,1,73,2,73,4,58,15,52,23,58,16,74,
6,14,3,58,14,70,14,1,0,76,98,8,54,24,222,55,
11,25,221,52,26,58,13,4,14,1,4,15,4,72,12,4,
0,1,50,5,75,114,141,0,0,0,99,109,0,0,0,2,
0,0,0,3,0,0,0,2,0,0,0,3,0,0,0,0,
0,0,0,0,0,0,0,2,0,0,0,9,0,0,0,11,
0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,1,
0,0,0,0,0,0,0,218,204,82,101,116,117,114,110,32,
116,104,101,32,82,101,115,111,117,114,99,101,82,101,97,100,
101,114,32,102,111,114,32,97,32,112,97,99,107,97,103,101,
32,105,110,32,97,32,122,105,112,32,102,105,108,101,46,10,
10,32,32,32,32,32,32,32,32,73,102,32,39,102,117,108,
108,110,97,109,101,39,32,105,115,32,97,32,112,97,99,107,
97,103,101,32,119,105,116,104,105,110,32,116,104,101,32,122,
105,112,32,102,105,108,101,44,32,114,101,116,117,114,110,32,
116,104,101,10,32,32,32,32,32,32,32,32,39,82,101,115,
111,117,114,99,101,82,101,97,100,101,114,39,32,111,98,106,
101,99,116,32,102,111,114,32,116,104,101,32,112,97,99,107,
97,103,101,46,32,32,79,116,104,101,114,119,105,115,101,32,
114,101,116,117,114,110,32,78,111,110,101,46,10,32,32,32,
32,32,32,32,32,218,31,122,105,112,105,109,112,111,114,116,
101,114,46,103,101,116,95,114,101,115,111,117,114,99,101,95,
114,101,97,100,101,114,114,124,0,0,0,78,114,23,0,0,
0,218,24,95,90,105,112,73,109,112,111,114,116,82,101,115,
111,117,114,99,101,82,101,97,100,101,114,218,11,95,114,101,
103,105,115,116,101,114,101,100,169,3,218,13,105,109,112,111,
114,116,108,105,98,46,97,98,99,169,1,218,14,82,101,115,
111,117,114,99,101,82,101,97,100,101,114,114,4,0,0,0,
114,149,0,0,0,218,8,114,101,103,105,115,116,101,114,84,
2,0,0,0,25,0,0,0,39,0,0,0,3,0,0,0,
16,1,0,0,41,3,114,75,0,0,0,114,86,0,0,0,
114,149,0,0,0,114,35,0,0,0,114,35,0,0,0,114,
36,0,0,0,218,19,103,101,116,95,114,101,115,111,117,114,
99,101,95,114,101,97,100,101,114,115,20,0,0,0,2,0,
0,7,17,1,6,1,7,1,7,1,15,1,11,1,16,1,
12,1,6,9,50,0,55,6,2,255,4,8,1,72,7,2,
0,17,83,6,0,52,3,75,79,17,0,54,4,253,82,3,
9,0,52,3,96,3,75,98,3,54,5,251,58,3,53,3,
6,250,2,3,17,83,42,0,88,7,58,3,89,3,8,58,
2,2,3,50,2,55,6,9,249,54,5,251,58,8,72,7,
2,0,1,54,5,251,58,3,52,10,60,3,6,2,3,54,
5,251,58,6,4,7,0,4,8,1,70,7,2,0,75,114,
151,0,0,0,99,38,0,0,0,1,0,0,0,3,0,0,
0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,
0,1,0,0,0,6,0,0,0,7,0,0,0,4,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,78,218,20,122,105,112,105,109,112,111,114,116,101,114,46,
95,95,114,101,112,114,95,95,218,21,60,122,105,112,105,109,
112,111,114,116,101,114,32,111,98,106,101,99,116,32,34,114,
70,0,0,0,114,26,0,0,0,114,74,0,0,0,218,2,
34,62,34,1,0,0,41,1,114,75,0,0,0,114,35,0,
0,0,114,35,0,0,0,114,36,0,0,0,218,8,95,95,
114,101,112,114,95,95,115,4,0,0,0,2,0,0,1,6,
6,52,2,58,1,53,0,3,255,73,4,58,2,54,4,253,
73,4,58,3,53,0,5,252,73,4,58,4,52,6,58,5,
74,6,1,5,75,114,155,0,0,0,45,0,0,0,41,12,
114,34,0,0,0,114,80,0,0,0,114,89,0,0,0,114,
92,0,0,0,114,98,0,0,0,114,108,0,0,0,114,111,
0,0,0,114,121,0,0,0,114,124,0,0,0,114,141,0,
0,0,114,151,0,0,0,114,155,0,0,0,114,35,0,0,
0,114,35,0,0,0,114,36,0,0,0,114,24,0,0,0,
115,28,0,0,0,2,0,9,1,2,255,2,18,4,46,10,
32,10,12,4,10,4,21,4,11,4,26,4,13,4,38,4,
18,6,13,51,0,254,59,1,52,2,59,3,52,4,59,5,
106,6,59,7,52,8,58,12,106,9,2,12,59,10,52,8,
58,12,106,11,2,12,59,12,106,13,59,14,106,15,59,16,
106,17,59,18,106,19,59,20,106,21,59,22,106,23,59,24,
106,25,59,26,106,27,59,28,52,8,75,218,12,95,95,105,
110,105,116,95,95,46,112,121,99,84,114,117,0,0,0,70,
169,3,218,4,46,112,121,99,84,70,169,3,114,118,0,0,
0,70,70,218,16,95,122,105,112,95,115,101,97,114,99,104,
111,114,100,101,114,99,35,0,0,0,2,0,0,0,3,0,
0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,
0,0,2,0,0,0,9,0,0,0,6,0,0,0,2,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,78,114,84,0,0,0,114,74,0,0,0,218,10,114,
112,97,114,116,105,116,105,111,110,218,1,46,233,2,0,0,
0,52,1,0,0,41,2,114,75,0,0,0,114,86,0,0,
0,114,35,0,0,0,114,35,0,0,0,114,36,0,0,0,
114,84,0,0,0,115,4,0,0,0,2,0,0,1,6,9,
53,0,2,255,58,2,50,1,55,6,3,254,52,4,58,8,
72,7,2,0,58,3,52,5,26,3,2,3,24,2,2,2,
75,114,84,0,0,0,99,16,0,0,0,2,0,0,0,3,
0,0,0,2,0,0,0,3,0,0,0,0,0,0,0,0,
0,0,0,2,0,0,0,3,0,0,0,4,0,0,0,3,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,78,114,85,0,0,0,114,26,0,0,0,114,69,
0,0,0,56,1,0,0,41,3,114,75,0,0,0,114,56,
0,0,0,218,7,100,105,114,112,97,116,104,114,35,0,0,
0,114,35,0,0,0,114,36,0,0,0,114,85,0,0,0,
115,6,0,0,0,2,0,0,4,7,2,6,3,54,2,254,
24,1,58,2,53,0,3,253,35,2,75,114,85,0,0,0,
99,67,0,0,0,2,0,0,0,3,0,0,0,2,0,0,
0,7,0,0,0,0,0,0,0,0,0,0,0,2,0,0,
0,13,0,0,0,5,0,0,0,5,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,78,114,83,
0,0,0,114,84,0,0,0,114,160,0,0,0,114,69,0,
0,0,65,1,0,0,41,7,114,75,0,0,0,114,86,0,
0,0,114,56,0,0,0,218,6,115,117,102,102,105,120,218,
10,105,115,98,121,116,101,99,111,100,101,114,97,0,0,0,
114,120,0,0,0,114,35,0,0,0,114,35,0,0,0,114,
36,0,0,0,114,83,0,0,0,115,16,0,0,0,2,0,
0,1,17,1,21,1,6,1,9,1,5,253,4,4,6,13,
54,2,254,58,10,4,11,0,4,12,1,70,11,2,0,58,
2,54,3,252,85,7,79,36,0,105,8,3,0,5,3,10,
5,4,9,5,5,8,50,3,24,2,58,6,53,0,4,251,
35,6,83,8,0,50,5,2,7,75,87,7,223,255,52,0,
75,114,83,0,0,0,99,97,6,0,0,1,0,0,0,3,
0,0,0,1,0,0,0,26,0,0,0,0,0,0,0,0,
0,0,0,1,0,0,0,38,0,0,0,62,0,0,0,52,
0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,
0,0,0,78,114,68,0,0,0,114,16,0,0,0,218,9,
111,112,101,110,95,99,111,100,101,114,59,0,0,0,114,23,
0,0,0,218,21,99,97,110,39,116,32,111,112,101,110,32,
90,105,112,32,102,105,108,101,58,32,114,55,0,0,0,218,
4,115,101,101,107,114,42,0,0,0,114,163,0,0,0,218,
4,116,101,108,108,218,4,114,101,97,100,218,21,99,97,110,
39,116,32,114,101,97,100,32,90,105,112,32,102,105,108,101,
58,32,114,102,0,0,0,186,78,233,4,0,0,0,78,114,
44,0,0,0,114,4,0,0,0,218,3,109,97,120,114,46,
0,0,0,218,5,114,102,105,110,100,218,16,110,111,116,32,
97,32,90,105,112,32,102,105,108,101,58,32,218,18,99,111,
114,114,117,112,116,32,90,105,112,32,102,105,108,101,58,32,
114,9,0,0,0,186,233,12,0,0,0,233,16,0,0,0,
78,186,114,181,0,0,0,233,20,0,0,0,78,218,28,98,
97,100,32,99,101,110,116,114,97,108,32,100,105,114,101,99,
116,111,114,121,32,115,105,122,101,58,32,218,30,98,97,100,
32,99,101,110,116,114,97,108,32,100,105,114,101,99,116,111,
114,121,32,111,102,102,115,101,116,58,32,218,38,98,97,100,
32,99,101,110,116,114,97,108,32,100,105,114,101,99,116,111,
114,121,32,115,105,122,101,32,111,114,32,111,102,102,115,101,
116,58,32,233,46,0,0,0,114,174,0,0,0,218,8,69,
79,70,69,114,114,111,114,218,27,69,79,70,32,114,101,97,
100,32,119,104,101,114,101,32,110,111,116,32,101,120,112,101,
99,116,101,100,243,4,0,0,0,80,75,1,2,114,8,0,
0,0,186,233,8,0,0,0,233,10,0,0,0,78,186,114,
193,0,0,0,114,180,0,0,0,78,186,114,180,0,0,0,
233,14,0,0,0,78,186,114,196,0,0,0,114,181,0,0,
0,78,186,114,183,0,0,0,233,24,0,0,0,78,186,114,
199,0,0,0,233,28,0,0,0,78,186,114,201,0,0,0,
233,30,0,0,0,78,186,114,203,0,0,0,233,32,0,0,
0,78,186,114,205,0,0,0,233,34,0,0,0,78,186,233,
42,0,0,0,114,187,0,0,0,78,218,25,98,97,100,32,
108,111,99,97,108,32,104,101,97,100,101,114,32,111,102,102,
115,101,116,58,32,233,0,8,0,0,114,119,0,0,0,218,
5,97,115,99,105,105,218,18,85,110,105,99,111,100,101,68,
101,99,111,100,101,69,114,114,111,114,218,6,108,97,116,105,
110,49,218,9,116,114,97,110,115,108,97,116,101,218,11,99,
112,52,51,55,95,116,97,98,108,101,114,57,0,0,0,250,
1,47,114,26,0,0,0,114,5,0,0,0,114,71,0,0,
0,114,29,0,0,0,114,12,0,0,0,114,138,0,0,0,
218,33,122,105,112,105,109,112,111,114,116,58,32,102,111,117,
110,100,32,123,125,32,110,97,109,101,115,32,105,110,32,123,
33,114,125,2,0,0,0,21,0,0,0,65,0,0,0,26,
0,0,0,70,0,0,0,123,0,0,0,167,0,0,0,28,
0,0,0,244,0,0,0,22,1,0,0,66,1,0,0,28,
0,0,0,97,1,0,0,126,1,0,0,170,1,0,0,28,
0,0,0,5,3,0,0,22,3,0,0,66,3,0,0,28,
0,0,0,171,4,0,0,189,4,0,0,233,4,0,0,28,
0,0,0,36,5,0,0,115,5,0,0,159,5,0,0,28,
0,0,0,181,5,0,0,200,5,0,0,243,5,0,0,28,
0,0,0,69,0,0,0,70,6,0,0,72,6,0,0,28,
0,0,0,96,1,0,0,41,26,114,70,0,0,0,218,2,
102,112,218,15,104,101,97,100,101,114,95,112,111,115,105,116,
105,111,110,218,6,98,117,102,102,101,114,218,9,102,105,108,
101,95,115,105,122,101,218,17,109,97,120,95,99,111,109,109,
101,110,116,95,115,116,97,114,116,218,4,100,97,116,97,218,
3,112,111,115,218,11,104,101,97,100,101,114,95,115,105,122,
101,218,13,104,101,97,100,101,114,95,111,102,102,115,101,116,
218,10,97,114,99,95,111,102,102,115,101,116,114,79,0,0,
0,218,5,99,111,117,110,116,218,5,102,108,97,103,115,218,
8,99,111,109,112,114,101,115,115,114,22,0,0,0,218,4,
100,97,116,101,218,3,99,114,99,218,9,100,97,116,97,95,
115,105,122,101,218,9,110,97,109,101,95,115,105,122,101,218,
10,101,120,116,114,97,95,115,105,122,101,218,12,99,111,109,
109,101,110,116,95,115,105,122,101,218,11,102,105,108,101,95,
111,102,102,115,101,116,114,116,0,0,0,114,56,0,0,0,
218,1,116,114,35,0,0,0,114,35,0,0,0,114,36,0,
0,0,114,68,0,0,0,115,184,0,0,0,2,0,0,2,
19,1,7,1,37,2,5,2,21,1,12,1,20,1,7,1,
37,1,25,1,35,1,17,4,19,1,15,1,7,1,37,2,
12,1,3,255,6,1,2,255,8,3,14,1,15,1,7,1,
37,2,17,1,8,1,35,2,20,1,25,1,35,2,24,2,
17,1,17,1,8,1,35,1,8,1,35,1,6,1,6,1,
8,1,35,2,4,2,4,2,17,1,7,1,37,2,16,1,
24,1,14,2,16,1,3,1,24,1,14,1,17,1,17,1,
17,1,17,1,17,1,17,1,17,1,17,1,17,1,17,1,
17,1,14,1,8,1,35,1,6,3,18,1,7,1,37,1,
24,1,35,5,41,1,38,1,7,1,37,2,7,2,15,4,
19,1,7,1,36,2,21,1,19,1,29,1,5,1,6,202,
5,55,22,1,6,38,54,2,254,55,29,3,253,4,31,0,
72,30,2,0,58,1,79,47,0,54,4,251,82,26,39,0,
54,5,249,58,33,52,6,58,34,50,0,73,2,73,4,58,
35,74,6,34,2,58,34,4,28,0,52,7,58,29,70,34,
1,1,76,98,26,50,1,107,26,1,50,1,55,31,8,248,
54,9,246,16,58,33,52,10,58,34,72,32,3,0,1,50,
1,55,31,11,245,72,32,1,0,58,2,50,1,55,31,12,
244,54,9,246,58,33,72,32,2,0,58,3,79,47,0,54,
4,251,82,28,39,0,54,5,249,58,35,52,13,58,36,50,
0,73,2,73,4,58,37,74,6,36,2,58,36,4,30,0,
52,7,58,31,70,36,1,1,76,98,28,54,14,242,58,31,
4,32,3,70,32,1,0,58,28,54,9,246,36,3,28,2,
28,83,38,0,54,5,249,58,33,52,13,58,34,50,0,73,
2,73,4,58,35,74,6,34,2,58,34,4,28,0,52,7,
58,29,70,34,1,1,76,52,15,26,3,58,28,54,16,240,
36,3,28,2,28,83,93,1,50,1,55,31,8,239,52,17,
58,33,52,10,58,34,72,32,3,0,1,50,1,55,31,11,
238,72,32,1,0,58,4,79,47,0,54,4,251,82,28,39,
0,54,5,249,58,35,52,13,58,36,50,0,73,2,73,4,
58,37,74,6,36,2,58,36,4,30,0,52,7,58,31,70,
36,1,1,76,98,28,54,18,236,58,31,54,19,234,25,4,
58,32,54,9,246,25,32,2,32,58,32,52,17,58,33,70,
32,2,0,58,5,50,1,55,31,8,233,4,33,5,72,32,
2,0,1,50,1,55,31,12,232,72,32,1,0,58,6,79,
47,0,54,4,251,82,28,39,0,54,5,249,58,35,52,13,
58,36,50,0,73,2,73,4,58,37,74,6,36,2,58,36,
4,30,0,52,7,58,31,70,36,1,1,76,98,28,50,6,
55,31,20,231,54,16,240,58,33,72,32,2,0,58,7,52,
17,36,0,7,83,38,0,54,5,249,58,33,52,21,58,34,
50,0,73,2,73,4,58,35,74,6,34,2,58,34,4,28,
0,52,7,58,29,70,34,1,1,76,4,28,7,54,9,246,
24,7,58,29,52,0,58,30,91,28,26,6,58,3,54,14,
242,58,31,4,32,3,70,32,1,0,58,28,54,9,246,36,
3,28,2,28,83,38,0,54,5,249,58,33,52,22,58,34,
50,0,73,2,73,4,58,35,74,6,34,2,58,34,4,28,
0,52,7,58,29,70,34,1,1,76,54,14,242,58,31,4,
32,6,70,32,1,0,25,4,58,28,50,7,24,28,2,28,
58,2,54,23,229,58,31,52,24,26,3,58,32,70,32,1,
0,58,8,54,23,229,58,31,52,25,26,3,58,32,70,32,
1,0,58,9,50,8,36,0,2,83,38,0,54,5,249,58,
33,52,26,58,34,50,0,73,2,73,4,58,35,74,6,34,
2,58,34,4,28,0,52,7,58,29,70,34,1,1,76,50,
9,36,0,2,83,38,0,54,5,249,58,33,52,27,58,34,
50,0,73,2,73,4,58,35,74,6,34,2,58,34,4,28,
0,52,7,58,29,70,34,1,1,76,50,8,40,2,58,2,
50,9,25,2,58,10,52,17,36,0,10,83,38,0,54,5,
249,58,33,52,28,58,34,50,0,73,2,73,4,58,35,74,
6,34,2,58,34,4,28,0,52,7,58,29,70,34,1,1,
76,95,0,58,11,52,17,58,12,50,1,55,31,8,228,4,
33,2,72,32,2,0,1,79,47,0,54,4,251,82,28,39,
0,54,5,249,58,35,52,13,58,36,50,0,73,2,73,4,
58,37,74,6,36,2,58,36,4,30,0,52,7,58,31,70,
36,1,1,76,98,28,50,1,55,31,12,227,52,29,58,33,
72,32,2,0,58,3,54,14,242,58,31,4,32,3,70,32,
1,0,58,28,52,30,36,0,28,2,28,83,17,0,54,31,
225,58,31,52,32,58,32,70,32,1,0,76,52,15,26,3,
58,28,52,33,36,3,28,2,28,83,6,0,79,190,2,54,
14,242,58,31,4,32,3,70,32,1,0,58,28,52,29,36,
3,28,2,28,83,17,0,54,31,225,58,31,52,32,58,32,
70,32,1,0,76,54,34,223,58,31,52,35,26,3,58,32,
70,32,1,0,58,13,54,34,223,58,31,52,36,26,3,58,
32,70,32,1,0,58,14,54,34,223,58,31,52,37,26,3,
58,32,70,32,1,0,58,15,54,34,223,58,31,52,38,26,
3,58,32,70,32,1,0,58,16,54,23,229,58,31,52,25,
26,3,58,32,70,32,1,0,58,17,54,23,229,58,31,52,
39,26,3,58,32,70,32,1,0,58,18,54,23,229,58,31,
52,40,26,3,58,32,70,32,1,0,58,4,54,34,223,58,
31,52,41,26,3,58,32,70,32,1,0,58,19,54,34,223,
58,31,52,42,26,3,58,32,70,32,1,0,58,20,54,34,
223,58,31,52,43,26,3,58,32,70,32,1,0,58,21,54,
23,229,58,31,52,44,26,3,58,32,70,32,1,0,58,22,
50,20,24,19,58,28,50,21,24,28,2,28,58,8,50,9,
36,4,22,83,38,0,54,5,249,58,33,52,45,58,34,50,
0,73,2,73,4,58,35,74,6,34,2,58,34,4,28,0,
52,7,58,29,70,34,1,1,76,50,10,39,22,58,22,50,
1,55,31,12,222,4,33,19,72,32,2,0,58,23,79,47,
0,54,4,251,82,28,39,0,54,5,249,58,35,52,13,58,
36,50,0,73,2,73,4,58,37,74,6,36,2,58,36,4,
30,0,52,7,58,31,70,36,1,1,76,98,28,54,14,242,
58,31,4,32,23,70,32,1,0,58,28,50,19,36,3,28,
2,28,83,38,0,54,5,249,58,33,52,13,58,34,50,0,
73,2,73,4,58,35,74,6,34,2,58,34,4,28,0,52,
7,58,29,70,34,1,1,76,54,14,242,58,31,50,1,55,
35,12,221,50,19,25,8,58,37,72,36,2,0,58,32,70,
32,1,0,58,28,50,19,25,8,36,3,28,2,28,83,38,
0,54,5,249,58,33,52,13,58,34,50,0,73,2,73,4,
58,35,74,6,34,2,58,34,4,28,0,52,7,58,29,70,
34,1,1,76,79,47,0,54,4,251,82,28,39,0,54,5,
249,58,35,52,13,58,36,50,0,73,2,73,4,58,37,74,
6,36,2,58,36,4,30,0,52,7,58,31,70,36,1,1,
76,98,28,52,46,31,13,83,18,0,50,23,55,31,47,220,
72,32,1,0,58,23,79,65,0,50,23,55,31,47,219,52,
48,58,33,72,32,2,0,58,23,79,46,0,54,49,217,82,
28,38,0,50,23,55,33,47,216,52,50,58,35,72,34,2,
0,55,33,51,215,54,52,213,58,35,72,34,2,0,58,23,
96,28,79,5,0,98,28,50,23,55,31,53,212,52,54,58,
33,54,55,210,58,34,72,32,3,0,58,23,54,56,208,55,
31,57,207,4,33,0,4,34,23,72,32,3,0,58,24,4,
28,24,4,29,14,4,30,18,4,31,4,4,32,22,4,33,
15,4,34,16,4,35,17,92,28,8,58,25,50,25,62,11,
23,52,58,39,12,58,12,79,255,252,108,26,54,59,205,55,
29,60,204,52,61,58,31,4,32,12,4,33,0,72,30,4,
0,1,50,11,75,114,68,0,0,0,244,190,1,0,0,0,
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,
17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,
33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,
49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,
65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,
81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,
97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,
113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,195,
135,195,188,195,169,195,162,195,164,195,160,195,165,195,167,195,
170,195,171,195,168,195,175,195,174,195,172,195,132,195,133,195,
137,195,166,195,134,195,180,195,182,195,178,195,187,195,185,195,
191,195,150,195,156,194,162,194,163,194,165,226,130,167,198,146,
195,161,195,173,195,179,195,186,195,177,195,145,194,170,194,186,
194,191,226,140,144,194,172,194,189,194,188,194,161,194,171,194,
187,226,150,145,226,150,146,226,150,147,226,148,130,226,148,164,
226,149,161,226,149,162,226,149,150,226,149,149,226,149,163,226,
149,145,226,149,151,226,149,157,226,149,156,226,149,155,226,148,
144,226,148,148,226,148,180,226,148,172,226,148,156,226,148,128,
226,148,188,226,149,158,226,149,159,226,149,154,226,149,148,226,
149,169,226,149,166,226,149,160,226,149,144,226,149,172,226,149,
167,226,149,168,226,149,164,226,149,165,226,149,153,226,149,152,
226,149,146,226,149,147,226,149,171,226,149,170,226,148,152,226,
148,140,226,150,136,226,150,132,226,150,140,226,150,144,226,150,
128,206,177,195,159,206,147,207,128,206,163,207,131,194,181,207,
132,206,166,206,152,206,169,206,180,226,136,158,207,134,206,181,
226,136,169,226,137,161,194,177,226,137,165,226,137,164,226,140,
160,226,140,161,195,183,226,137,136,194,176,226,136,153,194,183,
226,136,154,226,129,191,194,178,226,150,160,194,160,114,216,0,
0,0,218,15,95,105,109,112,111,114,116,105,110,103,95,122,
108,105,98,99,120,0,0,0,0,0,0,0,3,0,0,0,
0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,9,0,0,0,14,0,0,0,11,0,0,0,
0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,
78,218,20,95,103,101,116,95,100,101,99,111,109,112,114,101,
115,115,95,102,117,110,99,114,241,0,0,0,114,12,0,0,
0,114,138,0,0,0,218,27,122,105,112,105,109,112,111,114,
116,58,32,122,108,105,98,32,85,78,65,86,65,73,76,65,
66,76,69,114,23,0,0,0,218,41,99,97,110,39,116,32,
100,101,99,111,109,112,114,101,115,115,32,100,97,116,97,59,
32,122,108,105,98,32,110,111,116,32,97,118,97,105,108,97,
98,108,101,84,169,3,218,4,122,108,105,98,169,1,218,10,
100,101,99,111,109,112,114,101,115,115,114,4,0,0,0,114,
248,0,0,0,218,9,69,120,99,101,112,116,105,111,110,70,
218,25,122,105,112,105,109,112,111,114,116,58,32,122,108,105,
98,32,97,118,97,105,108,97,98,108,101,42,0,0,0,56,
0,0,0,95,0,0,0,1,0,0,0,42,0,0,0,95,
0,0,0,101,0,0,0,1,0,0,0,254,1,0,0,41,
1,114,248,0,0,0,114,35,0,0,0,114,35,0,0,0,
114,36,0,0,0,114,242,0,0,0,115,24,0,0,0,2,
0,0,2,6,3,16,1,14,2,4,2,14,1,7,1,16,
1,16,2,6,2,16,1,6,9,54,2,254,83,33,0,54,
3,252,55,4,4,251,52,5,58,6,72,5,2,0,1,54,
6,249,58,4,52,7,58,5,70,5,1,0,76,52,8,61,
2,88,9,58,1,89,1,10,58,0,2,1,79,42,0,54,
11,247,82,1,34,0,54,3,252,55,6,4,246,52,5,58,
8,72,7,2,0,1,54,6,249,58,6,52,7,58,7,70,
7,1,0,76,98,1,52,12,61,2,98,1,54,3,252,55,
4,4,245,52,13,58,6,72,5,2,0,1,50,0,75,114,
242,0,0,0,99,221,1,0,0,2,0,0,0,3,0,0,
0,2,0,0,0,17,0,0,0,0,0,0,0,0,0,0,
0,2,0,0,0,29,0,0,0,27,0,0,0,21,0,0,
0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,
0,78,114,104,0,0,0,114,4,0,0,0,114,23,0,0,
0,218,18,110,101,103,97,116,105,118,101,32,100,97,116,97,
32,115,105,122,101,114,16,0,0,0,114,167,0,0,0,114,
169,0,0,0,114,59,0,0,0,114,172,0,0,0,114,55,
0,0,0,114,171,0,0,0,114,203,0,0,0,114,102,0,
0,0,114,188,0,0,0,114,189,0,0,0,114,173,0,0,
0,243,4,0,0,0,80,75,3,4,218,23,98,97,100,32,
108,111,99,97,108,32,102,105,108,101,32,104,101,97,100,101,
114,58,32,114,8,0,0,0,186,233,26,0,0,0,114,201,
0,0,0,78,114,202,0,0,0,218,26,122,105,112,105,109,
112,111,114,116,58,32,99,97,110,39,116,32,114,101,97,100,
32,100,97,116,97,114,242,0,0,0,114,249,0,0,0,114,
244,0,0,0,233,241,255,255,255,72,0,0,0,89,0,0,
0,133,0,0,0,19,0,0,0,42,1,0,0,59,1,0,
0,103,1,0,0,19,0,0,0,70,0,0,0,156,1,0,
0,158,1,0,0,19,0,0,0,169,1,0,0,183,1,0,
0,206,1,0,0,17,0,0,0,19,2,0,0,41,17,114,
70,0,0,0,114,107,0,0,0,218,8,100,97,116,97,112,
97,116,104,114,231,0,0,0,114,234,0,0,0,114,222,0,
0,0,114,238,0,0,0,114,22,0,0,0,114,232,0,0,
0,114,233,0,0,0,114,219,0,0,0,114,221,0,0,0,
114,235,0,0,0,114,236,0,0,0,114,226,0,0,0,218,
8,114,97,119,95,100,97,116,97,114,248,0,0,0,114,35,
0,0,0,114,35,0,0,0,114,36,0,0,0,114,104,0,
0,0,115,58,0,0,0,2,0,0,1,30,1,8,1,14,
2,18,3,17,1,7,1,37,1,16,1,24,1,14,2,16,
2,35,2,17,1,17,1,20,1,6,2,17,1,7,1,37,
1,15,1,24,1,16,2,8,2,3,4,14,1,7,1,16,
1,6,29,50,1,105,17,8,0,5,2,24,5,3,23,5,
4,22,5,5,21,5,6,20,5,7,19,5,8,18,5,9,
17,52,2,36,0,4,83,17,0,54,3,254,58,20,52,4,
58,21,70,21,1,0,76,54,5,252,55,20,6,251,4,22,
0,72,21,2,0,107,17,58,10,50,10,55,22,7,250,4,
24,6,72,23,2,0,1,79,47,0,54,8,248,82,19,39,
0,54,3,254,58,26,52,9,58,27,50,0,73,2,73,4,
58,28,74,6,27,2,58,27,4,21,0,52,10,58,22,70,
27,1,1,76,98,19,50,10,55,22,11,247,52,12,58,24,
72,23,2,0,58,11,54,13,245,58,22,4,23,11,70,23,
1,0,58,19,52,12,36,3,19,2,19,83,17,0,54,14,
243,58,22,52,15,58,23,70,23,1,0,76,52,16,26,11,
58,19,52,17,36,3,19,2,19,83,38,0,54,3,254,58,
24,52,18,58,25,50,0,73,2,73,4,58,26,74,6,25,
2,58,25,4,19,0,52,10,58,20,70,25,1,1,76,54,
19,241,58,22,52,20,26,11,58,23,70,23,1,0,58,12,
54,19,241,58,22,52,21,26,11,58,23,70,23,1,0,58,
13,52,12,58,19,50,12,24,19,2,19,58,19,50,13,24,
19,2,19,58,14,50,14,39,6,58,6,50,10,55,22,7,
240,4,24,6,72,23,2,0,1,79,47,0,54,8,248,82,
19,39,0,54,3,254,58,26,52,9,58,27,50,0,73,2,
73,4,58,28,74,6,27,2,58,27,4,21,0,52,10,58,
22,70,27,1,1,76,98,19,50,10,55,22,11,239,4,24,
4,72,23,2,0,58,15,54,13,245,58,22,4,23,15,70,
23,1,0,58,19,50,4,36,3,19,2,19,83,17,0,54,
8,248,58,22,52,22,58,23,70,23,1,0,76,108,17,52,
2,36,2,3,83,6,0,50,15,75,54,23,237,58,20,70,
21,0,0,58,16,79,26,0,54,24,235,82,17,18,0,54,
3,254,58,22,52,25,58,23,70,23,1,0,76,98,17,4,
20,16,4,21,15,52,26,58,22,70,21,2,0,75,114,104,
0,0,0,99,27,0,0,0,2,0,0,0,3,0,0,0,
2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,
2,0,0,0,7,0,0,0,4,0,0,0,2,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
78,218,9,95,101,113,95,109,116,105,109,101,218,3,97,98,
115,114,29,0,0,0,65,2,0,0,41,2,218,2,116,49,
218,2,116,50,114,35,0,0,0,114,35,0,0,0,114,36,
0,0,0,114,4,1,0,0,115,4,0,0,0,2,0,0,
2,6,7,54,2,254,58,5,50,1,25,0,58,6,70,6,
1,0,58,2,52,3,36,1,2,2,2,75,114,4,1,0,
0,99,202,1,0,0,5,0,0,0,3,0,0,0,5,0,
0,0,14,0,0,0,0,0,0,0,0,0,0,0,5,0,
0,0,23,0,0,0,34,0,0,0,32,0,0,0,0,0,
0,0,0,0,0,0,2,0,0,0,0,0,0,0,78,218,
15,95,117,110,109,97,114,115,104,97,108,95,99,111,100,101,
114,116,0,0,0,114,56,0,0,0,114,5,0,0,0,218,
13,95,99,108,97,115,115,105,102,121,95,112,121,99,114,37,
0,0,0,114,29,0,0,0,114,4,0,0,0,114,163,0,
0,0,114,14,0,0,0,218,21,99,104,101,99,107,95,104,
97,115,104,95,98,97,115,101,100,95,112,121,99,115,218,5,
110,101,118,101,114,218,6,97,108,119,97,121,115,218,15,95,
103,101,116,95,112,121,99,95,115,111,117,114,99,101,218,11,
115,111,117,114,99,101,95,104,97,115,104,218,17,95,82,65,
87,95,77,65,71,73,67,95,78,85,77,66,69,82,218,18,
95,118,97,108,105,100,97,116,101,95,104,97,115,104,95,112,
121,99,218,29,95,103,101,116,95,109,116,105,109,101,95,97,
110,100,95,115,105,122,101,95,111,102,95,115,111,117,114,99,
101,114,4,1,0,0,114,9,0,0,0,186,114,192,0,0,
0,114,180,0,0,0,78,114,179,0,0,0,114,12,0,0,
0,114,138,0,0,0,218,22,98,121,116,101,99,111,100,101,
32,105,115,32,115,116,97,108,101,32,102,111,114,32,114,18,
0,0,0,218,5,108,111,97,100,115,186,114,181,0,0,0,
78,78,114,49,0,0,0,218,10,95,99,111,100,101,95,116,
121,112,101,218,9,84,121,112,101,69,114,114,111,114,218,16,
99,111,109,112,105,108,101,100,32,109,111,100,117,108,101,32,
218,21,32,105,115,32,110,111,116,32,97,32,99,111,100,101,
32,111,98,106,101,99,116,34,0,0,0,59,0,0,0,73,
0,0,0,14,0,0,0,215,0,0,0,242,0,0,0,0,
1,0,0,14,0,0,0,75,2,0,0,41,14,114,75,0,
0,0,114,105,0,0,0,114,120,0,0,0,114,86,0,0,
0,114,224,0,0,0,218,11,101,120,99,95,100,101,116,97,
105,108,115,114,230,0,0,0,218,10,104,97,115,104,95,98,
97,115,101,100,218,12,99,104,101,99,107,95,115,111,117,114,
99,101,218,12,115,111,117,114,99,101,95,98,121,116,101,115,
114,14,1,0,0,218,12,115,111,117,114,99,101,95,109,116,
105,109,101,218,11,115,111,117,114,99,101,95,115,105,122,101,
114,96,0,0,0,114,35,0,0,0,114,35,0,0,0,114,
36,0,0,0,114,8,1,0,0,115,82,0,0,0,2,0,
0,1,4,1,2,255,2,1,2,255,5,2,2,254,2,2,
2,254,11,6,25,1,7,1,7,2,15,1,5,1,15,1,
24,1,26,255,3,2,17,1,8,1,7,1,11,255,11,6,
27,2,7,1,10,3,15,255,10,3,5,3,34,1,24,255,
3,2,7,1,16,255,7,2,3,2,19,1,21,1,32,1,
6,23,95,2,58,14,52,2,58,15,50,3,62,14,15,2,
15,52,3,58,15,50,2,62,14,15,2,15,50,14,2,14,
58,5,54,4,254,55,17,5,253,4,19,4,4,20,3,4,
21,5,72,18,4,0,58,6,79,17,0,54,6,251,82,14,
9,0,52,0,96,14,75,98,14,52,7,31,6,58,14,52,
8,36,3,14,2,14,58,7,50,7,83,169,0,52,9,31,
6,58,14,52,8,36,3,14,2,14,58,8,54,10,249,58,
14,53,14,11,248,2,14,58,14,52,12,36,3,14,2,14,
80,30,0,1,50,8,81,24,0,1,54,10,249,58,14,53,
14,11,247,2,14,58,14,52,13,36,2,14,2,14,83,98,
0,54,14,245,58,17,4,18,0,4,19,2,70,18,2,0,
58,9,52,0,34,9,18,83,73,0,54,10,249,55,17,15,
244,54,4,254,58,19,53,19,16,243,2,19,58,19,4,20,
9,72,18,3,0,58,10,54,4,254,55,17,17,242,4,19,
4,4,20,10,4,21,3,4,22,5,72,18,5,0,1,79,
17,0,54,6,251,82,14,9,0,52,0,96,14,75,98,14,
79,127,0,54,18,240,58,17,4,18,0,4,19,2,70,18,
2,0,105,14,2,0,5,11,15,5,12,14,50,11,83,97,
0,54,19,238,58,17,54,20,236,58,21,52,21,26,4,58,
22,70,22,1,0,58,18,4,19,11,70,18,2,0,17,81,
28,0,1,54,20,236,58,17,52,22,26,4,58,18,70,18,
1,0,58,14,50,12,36,3,14,2,14,83,36,0,54,23,
234,55,17,24,233,52,25,58,19,50,3,73,2,73,4,58,
20,74,6,19,2,58,19,72,18,2,0,1,52,0,75,54,
26,231,55,17,27,230,52,28,26,4,58,19,72,18,2,0,
58,13,54,29,228,58,17,4,18,13,54,30,226,58,19,70,
18,2,0,17,83,35,0,54,31,224,58,17,52,32,58,18,
50,1,73,2,73,4,58,19,52,33,58,20,74,6,18,3,
58,18,70,18,1,0,76,50,13,75,114,8,1,0,0,218,
8,95,95,99,111,100,101,95,95,114,22,1,0,0,99,45,
0,0,0,1,0,0,0,3,0,0,0,1,0,0,0,1,
0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,8,
0,0,0,6,0,0,0,2,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,78,218,23,95,110,
111,114,109,97,108,105,122,101,95,108,105,110,101,95,101,110,
100,105,110,103,115,114,57,0,0,0,243,2,0,0,0,13,
10,243,1,0,0,0,10,243,1,0,0,0,13,126,2,0,
0,41,1,218,6,115,111,117,114,99,101,114,35,0,0,0,
114,35,0,0,0,114,36,0,0,0,114,33,1,0,0,115,
8,0,0,0,2,0,0,1,20,1,20,1,6,8,50,0,
55,4,2,255,52,3,58,6,52,4,58,7,72,5,3,0,
58,0,50,0,55,4,2,254,52,5,58,6,52,4,58,7,
72,5,3,0,58,0,50,0,75,114,33,1,0,0,99,44,
0,0,0,2,0,0,0,3,0,0,0,2,0,0,0,2,
0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,11,
0,0,0,7,0,0,0,4,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,78,218,15,95,99,
111,109,112,105,108,101,95,115,111,117,114,99,101,114,33,1,
0,0,218,7,99,111,109,112,105,108,101,114,135,0,0,0,
84,169,1,218,12,100,111,110,116,95,105,110,104,101,114,105,
116,133,2,0,0,41,2,114,105,0,0,0,114,37,1,0,
0,114,35,0,0,0,114,35,0,0,0,114,36,0,0,0,
114,38,1,0,0,115,6,0,0,0,2,0,0,1,14,1,
6,11,54,2,254,58,5,4,6,1,70,6,1,0,58,1,
54,3,252,58,7,4,8,1,4,9,0,52,4,58,10,52,
5,58,2,52,6,58,3,70,8,3,1,75,114,38,1,0,
0,99,99,0,0,0,2,0,0,0,3,0,0,0,2,0,
0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,
0,0,16,0,0,0,13,0,0,0,3,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,78,218,
14,95,112,97,114,115,101,95,100,111,115,116,105,109,101,114,
22,0,0,0,218,6,109,107,116,105,109,101,233,9,0,0,
0,233,188,7,0,0,233,5,0,0,0,233,15,0,0,0,
233,31,0,0,0,233,11,0,0,0,233,63,0,0,0,114,
163,0,0,0,114,73,0,0,0,139,2,0,0,41,2,218,
1,100,114,239,0,0,0,114,35,0,0,0,114,35,0,0,
0,114,36,0,0,0,114,42,1,0,0,115,40,0,0,0,
2,0,0,1,7,1,12,255,2,2,12,254,2,3,4,253,
2,4,4,252,2,5,12,251,2,6,12,250,2,7,2,249,
2,7,2,249,2,7,2,249,6,16,54,2,254,55,5,3,
253,52,4,30,0,58,7,52,5,24,7,2,7,58,7,52,
6,30,0,58,8,52,7,31,8,2,8,58,8,52,8,31,
0,58,9,52,9,30,1,58,10,52,6,30,1,58,11,52,
10,31,11,2,11,58,11,52,8,31,1,58,12,52,11,22,
12,2,12,58,12,52,12,58,13,52,12,58,14,52,12,58,
15,92,7,9,58,7,72,6,2,0,75,114,42,1,0,0,
99,113,0,0,0,2,0,0,0,3,0,0,0,2,0,0,
0,6,0,0,0,0,0,0,0,0,0,0,0,2,0,0,
0,12,0,0,0,14,0,0,0,9,0,0,0,0,0,0,
0,0,0,0,0,1,0,0,0,0,0,0,0,78,114,17,
1,0,0,186,114,73,0,0,0,78,78,169,2,250,1,99,
250,1,111,186,78,114,73,0,0,0,78,114,69,0,0,0,
114,46,1,0,0,233,6,0,0,0,233,3,0,0,0,114,
42,1,0,0,114,67,0,0,0,218,10,73,110,100,101,120,
69,114,114,111,114,114,23,1,0,0,169,2,114,4,0,0,
0,114,4,0,0,0,2,0,0,0,81,0,0,0,110,0,
0,0,6,0,0,0,152,2,0,0,41,6,114,75,0,0,
0,114,56,0,0,0,114,107,0,0,0,114,22,0,0,0,
114,232,0,0,0,218,17,117,110,99,111,109,112,114,101,115,
115,101,100,95,115,105,122,101,114,35,0,0,0,114,35,0,
0,0,114,36,0,0,0,114,17,1,0,0,115,20,0,0,
0,2,0,0,3,17,1,6,1,14,3,6,1,6,1,6,
1,24,1,22,1,6,12,52,2,26,1,58,6,52,3,35,
6,2,6,84,5,0,73,8,52,4,26,1,58,1,53,0,
5,255,58,6,50,1,26,6,2,6,58,2,52,6,26,2,
58,3,52,7,26,2,58,4,52,8,26,2,58,5,54,9,
253,58,9,4,10,4,4,11,3,70,10,2,0,58,6,4,
7,5,92,6,2,75,54,10,251,58,8,54,11,249,58,9,
54,12,247,58,10,92,8,3,82,6,9,0,52,13,96,6,
75,98,6,52,0,75,114,17,1,0,0,99,75,0,0,0,
2,0,0,0,3,0,0,0,2,0,0,0,3,0,0,0,
0,0,0,0,0,0,0,0,2,0,0,0,9,0,0,0,
9,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,
1,0,0,0,0,0,0,0,78,114,13,1,0,0,114,52,
1,0,0,114,53,1,0,0,114,56,1,0,0,114,69,0,
0,0,114,67,0,0,0,114,104,0,0,0,114,70,0,0,
0,25,0,0,0,42,0,0,0,56,0,0,0,3,0,0,
0,171,2,0,0,41,3,114,75,0,0,0,114,56,0,0,
0,114,107,0,0,0,114,35,0,0,0,114,35,0,0,0,
114,36,0,0,0,114,13,1,0,0,115,14,0,0,0,2,
0,0,2,17,1,6,3,17,1,7,1,7,2,6,9,52,
2,26,1,58,3,52,3,35,3,2,3,84,5,0,73,8,
52,4,26,1,58,1,53,0,5,255,58,3,50,1,26,3,
2,3,58,2,79,17,0,54,6,253,82,3,9,0,52,0,
96,3,75,98,3,54,7,251,58,6,53,0,8,250,58,7,
4,8,2,70,7,2,0,75,114,13,1,0,0,99,12,1,
0,0,2,0,0,0,3,0,0,0,2,0,0,0,11,0,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,22,0,
0,0,20,0,0,0,22,0,0,0,0,0,0,0,0,0,
0,0,1,0,0,0,0,0,0,0,78,114,95,0,0,0,
114,84,0,0,0,114,160,0,0,0,114,12,0,0,0,114,
138,0,0,0,218,13,116,114,121,105,110,103,32,123,125,123,
125,123,125,114,70,0,0,0,114,26,0,0,0,114,163,0,
0,0,169,1,218,9,118,101,114,98,111,115,105,116,121,114,
69,0,0,0,114,67,0,0,0,114,4,0,0,0,114,104,
0,0,0,114,8,1,0,0,114,38,1,0,0,114,23,0,
0,0,114,114,0,0,0,114,115,0,0,0,90,0,0,0,
107,0,0,0,121,0,0,0,12,0,0,0,186,2,0,0,
41,11,114,75,0,0,0,114,86,0,0,0,114,56,0,0,
0,114,165,0,0,0,114,166,0,0,0,114,97,0,0,0,
114,120,0,0,0,114,107,0,0,0,114,88,0,0,0,114,
224,0,0,0,114,96,0,0,0,114,35,0,0,0,114,35,
0,0,0,114,36,0,0,0,114,95,0,0,0,115,38,0,
0,0,2,0,0,1,17,1,21,1,6,1,44,2,17,1,
7,1,7,2,6,1,20,1,5,1,29,2,17,1,7,3,
3,1,6,1,15,237,4,21,6,22,54,2,254,58,14,4,
15,0,4,16,1,70,15,2,0,58,2,54,3,252,85,11,
79,205,0,105,12,3,0,5,3,14,5,4,13,5,5,12,
50,3,24,2,58,6,54,4,250,58,12,53,12,5,249,2,
12,58,17,52,6,58,18,53,0,7,248,58,19,54,8,246,
58,20,4,21,6,52,9,58,12,52,10,58,13,70,18,4,
1,1,53,0,11,245,58,12,50,6,26,12,2,12,58,7,
79,17,0,54,12,243,82,12,9,0,96,12,79,113,0,98,
12,52,13,26,7,58,8,54,14,241,58,15,53,0,7,240,
58,16,4,17,7,70,16,2,0,58,9,50,4,83,32,0,
54,15,238,58,15,4,16,0,4,17,8,4,18,6,4,19,
1,4,20,9,70,16,5,0,58,10,79,20,0,54,16,236,
58,15,4,16,8,4,17,9,70,16,2,0,58,10,52,0,
34,10,83,6,0,79,24,0,52,13,26,7,58,8,4,12,
10,4,13,5,4,14,8,92,12,3,2,11,75,87,11,54,
255,54,17,234,58,16,52,18,58,17,50,1,73,2,73,4,
58,18,74,6,17,2,58,17,4,11,1,52,19,58,12,70,
17,1,1,76,114,95,0,0,0,99,42,0,0,0,0,0,
128,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,7,0,0,0,19,0,
0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,114,31,0,0,0,114,32,0,0,0,
114,144,0,0,0,114,33,0,0,0,218,165,80,114,105,118,
97,116,101,32,99,108,97,115,115,32,117,115,101,100,32,116,
111,32,115,117,112,112,111,114,116,32,90,105,112,73,109,112,
111,114,116,46,103,101,116,95,114,101,115,111,117,114,99,101,
95,114,101,97,100,101,114,40,41,46,10,10,32,32,32,32,
84,104,105,115,32,99,108,97,115,115,32,105,115,32,97,108,
108,111,119,101,100,32,116,111,32,114,101,102,101,114,101,110,
99,101,32,97,108,108,32,116,104,101,32,105,110,110,97,114,
100,115,32,97,110,100,32,112,114,105,118,97,116,101,32,112,
97,114,116,115,32,111,102,10,32,32,32,32,116,104,101,32,
122,105,112,105,109,112,111,114,116,101,114,46,10,32,32,32,
32,114,1,0,0,0,70,114,145,0,0,0,99,15,0,0,
0,3,0,0,0,3,0,0,0,3,0,0,0,3,0,0,
0,0,0,0,0,0,0,0,0,3,0,0,0,3,0,0,
0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,78,218,33,95,90,105,112,
73,109,112,111,114,116,82,101,115,111,117,114,99,101,82,101,
97,100,101,114,46,95,95,105,110,105,116,95,95,114,24,0,
0,0,114,86,0,0,0,220,2,0,0,41,3,114,75,0,
0,0,114,24,0,0,0,114,86,0,0,0,114,35,0,0,
0,114,35,0,0,0,114,36,0,0,0,114,80,0,0,0,
115,6,0,0,0,2,0,0,1,5,1,6,3,50,1,60,
0,2,50,2,60,0,3,52,0,75,114,80,0,0,0,99,
107,0,0,0,2,0,0,0,3,0,0,0,2,0,0,0,
5,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,
15,0,0,0,12,0,0,0,8,0,0,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,0,0,78,218,38,95,
90,105,112,73,109,112,111,114,116,82,101,115,111,117,114,99,
101,82,101,97,100,101,114,46,111,112,101,110,95,114,101,115,
111,117,114,99,101,114,86,0,0,0,114,57,0,0,0,114,
162,0,0,0,114,217,0,0,0,169,3,218,2,105,111,169,
1,218,7,66,121,116,101,115,73,79,114,4,0,0,0,114,
71,1,0,0,114,24,0,0,0,114,108,0,0,0,114,59,
0,0,0,218,17,70,105,108,101,78,111,116,70,111,117,110,
100,69,114,114,111,114,57,0,0,0,82,0,0,0,104,0,
0,0,5,0,0,0,224,2,0,0,41,5,114,75,0,0,
0,218,8,114,101,115,111,117,114,99,101,218,16,102,117,108,
108,110,97,109,101,95,97,115,95,112,97,116,104,114,56,0,
0,0,114,71,1,0,0,114,35,0,0,0,114,35,0,0,
0,114,36,0,0,0,218,13,111,112,101,110,95,114,101,115,
111,117,114,99,101,115,14,0,0,0,2,0,0,1,22,1,
22,1,11,2,25,1,7,1,6,15,53,0,2,255,55,8,
3,254,52,4,58,10,52,5,58,11,72,9,3,0,58,2,
50,2,73,4,58,5,52,5,58,6,50,1,73,4,58,7,
74,6,5,3,58,3,88,6,58,5,89,5,7,58,4,2,
5,4,8,4,53,0,8,253,55,12,9,252,4,14,3,72,
13,2,0,58,9,70,9,1,0,75,54,10,250,82,5,17,
0,54,11,248,58,10,4,11,3,70,11,1,0,76,98,5,
52,0,75,114,75,1,0,0,99,6,0,0,0,2,0,0,
0,3,0,0,0,2,0,0,0,2,0,0,0,0,0,0,
0,0,0,0,0,2,0,0,0,2,0,0,0,3,0,0,
0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,78,218,38,95,90,105,112,73,109,112,111,
114,116,82,101,115,111,117,114,99,101,82,101,97,100,101,114,
46,114,101,115,111,117,114,99,101,95,112,97,116,104,114,72,
1,0,0,233,2,0,0,41,2,114,75,0,0,0,114,73,
1,0,0,114,35,0,0,0,114,35,0,0,0,114,36,0,
0,0,218,13,114,101,115,111,117,114,99,101,95,112,97,116,
104,115,4,0,0,0,2,0,0,4,6,2,54,2,254,76,
114,77,1,0,0,99,82,0,0,0,2,0,0,0,3,0,
0,0,2,0,0,0,4,0,0,0,0,0,0,0,0,0,
0,0,2,0,0,0,11,0,0,0,11,0,0,0,6,0,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,
0,0,78,218,36,95,90,105,112,73,109,112,111,114,116,82,
101,115,111,117,114,99,101,82,101,97,100,101,114,46,105,115,
95,114,101,115,111,117,114,99,101,114,86,0,0,0,114,57,
0,0,0,114,162,0,0,0,114,217,0,0,0,114,24,0,
0,0,114,108,0,0,0,114,59,0,0,0,70,84,46,0,
0,0,65,0,0,0,79,0,0,0,4,0,0,0,239,2,
0,0,41,4,114,75,0,0,0,114,116,0,0,0,114,74,
1,0,0,114,56,0,0,0,114,35,0,0,0,114,35,0,
0,0,114,36,0,0,0,218,11,105,115,95,114,101,115,111,
117,114,99,101,115,14,0,0,0,2,0,0,3,22,1,22,
2,19,1,7,1,7,1,6,11,53,0,2,255,55,7,3,
254,52,4,58,9,52,5,58,10,72,8,3,0,58,2,50,
2,73,4,58,4,52,5,58,5,50,1,73,4,58,6,74,
6,4,3,58,3,53,0,6,253,55,7,7,252,4,9,3,
72,8,2,0,1,79,17,0,54,8,250,82,4,9,0,52,
9,96,4,75,98,4,52,10,75,114,79,1,0,0,99,242,
0,0,0,1,0,0,1,35,0,0,0,1,0,0,0,9,
0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,19,
0,0,0,18,0,0,0,21,0,0,0,0,0,0,0,0,
0,0,0,1,0,0,0,0,0,0,0,78,218,33,95,90,
105,112,73,109,112,111,114,116,82,101,115,111,117,114,99,101,
82,101,97,100,101,114,46,99,111,110,116,101,110,116,115,169,
3,218,7,112,97,116,104,108,105,98,169,1,218,4,80,97,
116,104,114,4,0,0,0,114,84,1,0,0,114,24,0,0,
0,114,111,0,0,0,114,86,0,0,0,218,11,114,101,108,
97,116,105,118,101,95,116,111,114,70,0,0,0,114,116,0,
0,0,114,117,0,0,0,218,6,112,97,114,101,110,116,218,
3,115,101,116,114,69,0,0,0,114,60,0,0,0,114,102,
0,0,0,114,4,0,0,0,218,3,97,100,100,122,0,0,
0,148,0,0,0,162,0,0,0,10,0,0,0,250,2,0,
0,41,9,114,75,0,0,0,114,84,1,0,0,218,13,102,
117,108,108,110,97,109,101,95,112,97,116,104,218,13,114,101,
108,97,116,105,118,101,95,112,97,116,104,218,12,112,97,99,
107,97,103,101,95,112,97,116,104,218,12,115,117,98,100,105,
114,115,95,115,101,101,110,218,8,102,105,108,101,110,97,109,
101,218,8,114,101,108,97,116,105,118,101,218,11,112,97,114,
101,110,116,95,110,97,109,101,114,35,0,0,0,114,35,0,
0,0,114,36,0,0,0,218,8,99,111,110,116,101,110,116,
115,115,36,0,0,0,2,0,0,8,11,1,29,1,26,3,
18,1,6,1,11,1,19,2,26,1,7,1,7,5,14,1,
24,1,9,1,8,1,14,1,4,242,6,19,88,2,58,9,
89,9,3,58,1,2,9,4,12,1,53,0,4,255,55,16,
5,254,53,0,6,253,58,18,72,17,2,0,58,13,70,13,
1,0,58,2,50,2,55,12,7,252,53,0,4,251,58,14,
53,14,8,250,2,14,58,14,72,13,2,0,58,3,53,3,
9,249,58,9,52,10,36,2,9,2,9,84,5,0,73,8,
53,3,11,248,58,4,54,12,246,58,12,70,13,0,0,58,
5,53,0,4,245,58,9,53,9,13,244,2,9,85,9,79,
118,0,58,6,4,13,1,4,14,6,70,14,1,0,55,13,
7,243,4,15,4,72,14,2,0,58,7,79,17,0,54,14,
241,82,10,9,0,96,10,79,78,0,98,10,53,7,11,240,
58,10,53,10,9,239,2,10,58,8,54,15,237,58,13,4,
14,8,70,14,1,0,58,10,52,16,36,2,10,2,10,83,
12,0,53,7,9,236,77,1,79,29,0,50,5,35,8,18,
83,21,0,50,5,55,13,17,235,4,15,8,72,14,2,0,
1,50,8,77,1,87,9,141,255,52,0,75,114,96,1,0,
0,78,212,2,0,0,41,7,114,34,0,0,0,114,145,0,
0,0,114,80,0,0,0,114,75,1,0,0,114,77,1,0,
0,114,79,1,0,0,114,96,1,0,0,114,35,0,0,0,
114,35,0,0,0,114,36,0,0,0,114,144,0,0,0,115,
18,0,0,0,2,0,9,1,2,255,2,6,4,2,4,4,
4,9,4,6,4,11,6,7,51,0,254,59,1,52,2,59,
3,52,4,59,5,52,6,59,7,106,8,59,9,106,10,59,
11,106,12,59,13,106,14,59,15,106,16,59,17,52,18,75,
114,144,0,0,0,78,1,0,0,0,41,1,114,34,0,0,
0,114,35,0,0,0,114,35,0,0,0,114,36,0,0,0,
218,8,60,109,111,100,117,108,101,62,115,96,0,0,0,2,
0,4,16,4,1,16,1,4,1,4,1,4,1,4,1,4,
1,4,2,13,3,13,1,21,3,22,4,4,2,16,2,4,
1,4,1,4,2,17,127,0,127,0,1,24,255,2,2,24,
254,2,3,2,253,2,4,2,252,7,9,4,4,4,9,4,
31,4,126,2,254,2,29,4,5,4,21,4,46,4,10,4,
46,24,5,4,7,4,6,4,13,4,19,4,15,4,26,6,
8,52,0,59,1,88,2,59,3,88,4,58,1,89,1,5,
59,5,89,1,6,59,6,2,1,88,7,59,8,88,9,59,
10,88,11,59,12,88,13,59,14,88,15,59,16,88,17,59,
18,52,19,58,1,52,20,58,2,93,1,2,59,21,51,3,
254,58,1,53,1,22,253,2,1,59,22,51,3,254,58,1,
53,1,23,252,2,1,58,1,52,24,26,1,2,1,59,25,
99,58,4,106,26,58,5,52,19,58,6,51,27,250,58,7,
70,5,3,0,59,19,95,0,59,28,51,29,248,58,4,51,
16,246,58,5,70,5,1,0,59,30,52,31,59,32,52,33,
59,34,52,35,59,36,99,58,4,106,37,58,5,52,20,58,
6,70,5,2,0,59,20,51,22,244,58,1,52,38,24,1,
2,1,58,1,52,39,58,2,52,39,58,3,92,1,3,58,
1,51,22,244,58,2,52,40,24,2,2,2,58,2,52,41,
58,3,52,39,58,4,92,2,3,58,2,52,42,58,3,52,
43,58,4,92,1,4,59,44,106,45,59,46,106,47,59,48,
106,49,59,50,106,51,59,52,52,53,59,54,52,41,61,55,
106,56,59,57,106,58,59,59,106,60,59,61,106,62,59,63,
51,29,248,58,4,51,63,242,58,5,53,5,64,241,2,5,
58,5,70,5,1,0,59,65,106,66,59,67,106,68,59,69,
106,70,59,71,106,72,59,73,106,74,59,75,106,76,59,77,
99,58,4,106,78,58,5,52,79,58,6,70,5,2,0,59,
79,52,80,75,
};
| 45,584 |
1,444 |
package mage.cards.s;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.keyword.ExtortAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
/**
*
* @author LevelX2
*/
public final class SyndicOfTithes extends CardImpl {
public SyndicOfTithes(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{W}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.CLERIC);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// Extort (Whenever you cast a spell, you may pay {WB}. If you do, each opponent loses 1 life and you gain that much life.)
this.addAbility(new ExtortAbility());
}
private SyndicOfTithes(final SyndicOfTithes card) {
super(card);
}
@Override
public SyndicOfTithes copy() {
return new SyndicOfTithes(this);
}
}
| 394 |
709 | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 <NAME>
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <Siv3D/Common.hpp>
# include <Siv3D/Common/D3D11.hpp>
# include <Siv3D/Mesh/IMesh.hpp>
# include <Siv3D/Renderer/D3D11/CRenderer_D3D11.hpp>
# include <Siv3D/AssetHandleManager/AssetHandleManager.hpp>
# include "D3D11Mesh.hpp"
namespace s3d
{
class CMesh_D3D11 final : public ISiv3DMesh
{
public:
CMesh_D3D11();
~CMesh_D3D11() override;
void init() override;
Mesh::IDType create(const MeshData& meshData) override;
Mesh::IDType createDynamic(size_t vertexCount, size_t triangleCount) override;
Mesh::IDType createDynamic(const MeshData& meshData) override;
void release(Mesh::IDType handleID) override;
size_t getVertexCount(Mesh::IDType handleID) override;
size_t getIndexCount(Mesh::IDType handleID) override;
Sphere getBoundingSphere(Mesh::IDType handleID) override;
Box getBoundingBox(Mesh::IDType handleID) override;
bool fill(Mesh::IDType handleID, const MeshData& meshData) override;
bool fill(Mesh::IDType handleID, size_t offset, const Vertex3D* vertices, size_t count) override;
bool fill(Mesh::IDType handleID, const Array<TriangleIndex32>& indices) override;
void bindMeshToContext(Mesh::IDType handleID) override;
private:
CRenderer_D3D11* pRenderer = nullptr;
// device のコピー
ID3D11Device* m_device = nullptr;
// context のコピー
ID3D11DeviceContext* m_context = nullptr;
// Mesh の管理
AssetHandleManager<Mesh::IDType, D3D11Mesh> m_meshes{ U"Mesh" };
};
}
| 635 |
777 | <gh_stars>100-1000
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_WHITELIST_SERVICE_H_
#define CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_WHITELIST_SERVICE_H_
#include <map>
#include <memory>
#include <set>
#include <string>
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/string16.h"
#include "base/time/time.h"
#include "chrome/browser/supervised_user/supervised_users.h"
#include "components/sync/model/syncable_service.h"
class PrefService;
class SupervisedUserSiteList;
namespace base {
class DictionaryValue;
class FilePath;
}
namespace component_updater {
class SupervisedUserWhitelistInstaller;
}
namespace user_prefs {
class PrefRegistrySyncable;
}
namespace sync_pb {
class ManagedUserWhitelistSpecifics;
}
class SupervisedUserWhitelistService : public syncer::SyncableService {
public:
typedef base::Callback<void(
const std::vector<scoped_refptr<SupervisedUserSiteList> >&)>
SiteListsChangedCallback;
SupervisedUserWhitelistService(
PrefService* prefs,
component_updater::SupervisedUserWhitelistInstaller* installer,
const std::string& client_id);
~SupervisedUserWhitelistService() override;
static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
void Init();
// Adds a callback to be called when the list of loaded site lists changes.
// The callback will also be called immediately, to get the current
// site lists.
void AddSiteListsChangedCallback(const SiteListsChangedCallback& callback);
// Returns a map (from CRX ID to name) of whitelists to be installed,
// specified on the command line.
static std::map<std::string, std::string> GetWhitelistsFromCommandLine();
// Loads an already existing whitelist on disk (i.e. without downloading it as
// a component).
void LoadWhitelistForTesting(const std::string& id,
const base::string16& title,
const base::FilePath& path);
// Unloads a whitelist. Public for testing.
void UnloadWhitelist(const std::string& id);
// Creates Sync data for a whitelist with the given |id| and |name|.
// Public for testing.
static syncer::SyncData CreateWhitelistSyncData(const std::string& id,
const std::string& name);
// SyncableService implementation:
syncer::SyncMergeResult MergeDataAndStartSyncing(
syncer::ModelType type,
const syncer::SyncDataList& initial_sync_data,
std::unique_ptr<syncer::SyncChangeProcessor> sync_processor,
std::unique_ptr<syncer::SyncErrorFactory> error_handler) override;
void StopSyncing(syncer::ModelType type) override;
syncer::SyncDataList GetAllSyncData(syncer::ModelType type) const override;
syncer::SyncError ProcessSyncChanges(
const tracked_objects::Location& from_here,
const syncer::SyncChangeList& change_list) override;
private:
// The following methods handle whitelist additions, updates and removals,
// usually coming from Sync.
void AddNewWhitelist(base::DictionaryValue* pref_dict,
const sync_pb::ManagedUserWhitelistSpecifics& whitelist);
void SetWhitelistProperties(
base::DictionaryValue* pref_dict,
const sync_pb::ManagedUserWhitelistSpecifics& whitelist);
void RemoveWhitelist(base::DictionaryValue* pref_dict, const std::string& id);
enum WhitelistSource {
FROM_SYNC,
FROM_COMMAND_LINE,
};
// Registers a new or existing whitelist.
void RegisterWhitelist(const std::string& id,
const std::string& name,
WhitelistSource source);
void GetLoadedWhitelists(
std::vector<scoped_refptr<SupervisedUserSiteList>>* whitelists);
void NotifyWhitelistsChanged();
void OnWhitelistReady(const std::string& id,
const base::string16& title,
const base::FilePath& large_icon_path,
const base::FilePath& whitelist_path);
void OnWhitelistLoaded(
const std::string& id,
base::TimeTicks start_time,
const scoped_refptr<SupervisedUserSiteList>& whitelist);
PrefService* prefs_;
component_updater::SupervisedUserWhitelistInstaller* installer_;
std::string client_id_;
std::vector<SiteListsChangedCallback> site_lists_changed_callbacks_;
// The set of registered whitelists. A whitelist might be registered but not
// loaded yet, in which case it will not be in |loaded_whitelists_| yet.
// On the other hand, every loaded whitelist has to be registered.
std::set<std::string> registered_whitelists_;
std::map<std::string, scoped_refptr<SupervisedUserSiteList> >
loaded_whitelists_;
base::WeakPtrFactory<SupervisedUserWhitelistService> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(SupervisedUserWhitelistService);
};
#endif // CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_WHITELIST_SERVICE_H_
| 1,816 |
517 | package org.tensorflow;
import java.util.ArrayList;
import java.util.Collection;
public final class AutoCloseableList<E extends AutoCloseable> extends ArrayList<E>
implements AutoCloseable {
public AutoCloseableList(Collection<? extends E> c) {
super(c);
}
@Override
public void close() {
Exception toThrow = null;
for (AutoCloseable c : this) {
try {
c.close();
} catch (Exception e) {
toThrow = e;
}
}
if (toThrow != null) {
throw new RuntimeException(toThrow);
}
}
}
| 213 |
2,023 | <filename>recipes/Python/440515_Changing_closedover_value/recipe-440515.py
import new, dis
cell_changer_code = new.code(
1, 1, 2, 0,
''.join([
chr(dis.opmap['LOAD_FAST']), '\x00\x00',
chr(dis.opmap['DUP_TOP']),
chr(dis.opmap['STORE_DEREF']), '\x00\x00',
chr(dis.opmap['RETURN_VALUE'])
]),
(), (), ('newval',), '<nowhere>', 'cell_changer', 1, '', ('c',), ()
)
def change_cell_value(cell, newval):
return new.function(cell_changer_code, {}, None, (), (cell,))(newval)
"""
Example use:
>>> def constantly(n):
... def return_n():
... return n
... return return_n
...
>>> f = constantly("Hi, Mom")
>>> f()
'Hi, Mom'
>>> f()
'Hi, Mom'
>>> f.func_closure
(<cell at 0xb7e1d56c: str object at 0xb7ded620>,)
>>> change_cell_value(f.func_closure[0], 46)
46
>>> f()
46
"""
| 390 |
476 | <gh_stars>100-1000
/*
* Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hetu.core.security.authentication;
import com.hazelcast.security.SecurityContext;
import io.hetu.core.security.authentication.kerberos.KerberosConfig;
import io.hetu.core.security.authentication.kerberos.KerberosSecurityContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class DefaultNodeExtensionAspect
{
@Around("execution(* com.hazelcast.instance.impl.DefaultNodeExtension.getSecurityContext())")
public SecurityContext aroundGetSecurityContext(ProceedingJoinPoint joinPoint)
{
if (KerberosConfig.isKerberosEnabled()) {
return new KerberosSecurityContext();
}
return null;
}
@Around("execution(* com.hazelcast.instance.impl.DefaultNodeExtension.checkSecurityAllowed())")
public void aroundCheckSecurityAllowed(ProceedingJoinPoint joinPoint) {}
}
| 507 |
2,151 | // Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#ifndef CORE_FXGE_ANDROID_CFPF_SKIABUFFERFONT_H_
#define CORE_FXGE_ANDROID_CFPF_SKIABUFFERFONT_H_
#include "core/fxge/android/cfpf_skiafontdescriptor.h"
#define FPF_SKIAFONTTYPE_Buffer 3
class CFPF_SkiaBufferFont : public CFPF_SkiaFontDescriptor {
public:
CFPF_SkiaBufferFont();
~CFPF_SkiaBufferFont() override;
// CFPF_SkiaFontDescriptor
int32_t GetType() const override;
void* m_pBuffer;
size_t m_szBuffer;
};
#endif // CORE_FXGE_ANDROID_CFPF_SKIABUFFERFONT_H_
| 284 |
443 | /* -------------------------------------------------------------------------
// WINX: a C++ template GUI library - MOST SIMPLE BUT EFFECTIVE
//
// This file is a part of the WINX Library.
// The use and distribution terms for this software are covered by the
// Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
// which can be found in the file CPL.txt at this distribution. By using
// this software in any fashion, you are agreeing to be bound by the terms
// of this license. You must not remove this notice, or any other, from
// this software.
//
// Module: stdext/winapi/oleauto.h
// Creator: xushiwei
// Email: <EMAIL>
// Date: 2006-8-26 0:45:33
//
// $Id: oleauto.h,v 1.1 2006/10/18 12:13:39 xushiwei Exp $
// -----------------------------------------------------------------------*/
#ifndef STDEXT_WINAPI_OLEAUTO_H
#define STDEXT_WINAPI_OLEAUTO_H
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// $Log: oleauto.h,v $
//
#endif /* STDEXT_WINAPI_OLEAUTO_H */
| 324 |
1,738 | <filename>dev/Code/Framework/AzCore/Platform/Common/Apple/AzCore/Debug/Trace_Apple.cpp
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzCore/Debug/Trace.h>
#include <assert.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
namespace AZ
{
namespace Debug
{
namespace Platform
{
#if defined(AZ_ENABLE_DEBUG_TOOLS)
// Apple Technical Q&A QA1361
// https://developer.apple.com/library/mac/qa/qa1361/_index.html
// Returns true if the current process is being debugged (either
// running under the debugger or has a debugger attached post facto).
bool IsDebuggerPresent()
{
int junk;
int mib[4];
struct kinfo_proc info;
size_t size;
// Initialize the flags so that, if sysctl fails for some bizarre
// reason, we get a predictable result.
info.kp_proc.p_flag = 0;
// Initialize mib, which tells sysctl the info we want, in this case
// we're looking for information about a specific process ID.
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID;
mib[3] = getpid();
// Call sysctl.
size = sizeof(info);
junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
assert(junk == 0);
// We're being debugged if the P_TRACED flag is set.
return ((info.kp_proc.p_flag & P_TRACED) != 0);
}
void HandleExceptions(bool)
{}
void DebugBreak()
{
raise(SIGINT);
}
#endif // AZ_ENABLE_DEBUG_TOOLS
void Terminate(int exitCode)
{
_exit(exitCode);
}
void OutputToDebugger(const char*, const char*)
{
}
}
}
}
| 1,250 |
335 | package moze_intel.projecte.client;
import java.util.function.Function;
import moze_intel.projecte.PECore;
import moze_intel.projecte.gameObjs.registration.impl.BlockRegistryObject;
import moze_intel.projecte.gameObjs.registries.PEBlocks;
import net.minecraft.block.AbstractFurnaceBlock;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.data.DataGenerator;
import net.minecraft.state.Property;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.util.Direction;
import net.minecraft.util.IItemProvider;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.generators.BlockModelBuilder;
import net.minecraftforge.client.model.generators.BlockStateProvider;
import net.minecraftforge.client.model.generators.ConfiguredModel;
import net.minecraftforge.client.model.generators.ModelFile;
import net.minecraftforge.common.data.ExistingFileHelper;
public class PEBlockStateProvider extends BlockStateProvider {
public PEBlockStateProvider(DataGenerator generator, ExistingFileHelper existingFileHelper) {
super(generator, PECore.MODID, existingFileHelper);
}
@Override
protected void registerStatesAndModels() {
//TODO: Should we use simpleBlockItem here instead of blockParentModel in the item model provider
simpleBlocks(PEBlocks.ALCHEMICAL_COAL, PEBlocks.MOBIUS_FUEL, PEBlocks.AETERNALIS_FUEL, PEBlocks.DARK_MATTER, PEBlocks.RED_MATTER);
registerTieredOrientable("collectors", PEBlocks.COLLECTOR, PEBlocks.COLLECTOR_MK2, PEBlocks.COLLECTOR_MK3);
registerTieredOrientable("relays", PEBlocks.RELAY, PEBlocks.RELAY_MK2, PEBlocks.RELAY_MK3);
registerFurnace(PEBlocks.DARK_MATTER_FURNACE, "dm", "dark_matter_block");
registerFurnace(PEBlocks.RED_MATTER_FURNACE, "rm", "red_matter_block");
registerChests();
registerExplosives();
registerInterdictionTorch();
registerPedestal();
registerTransmutationTable();
}
private void registerChests() {
models().withExistingParent("base_chest", "block/block")
//Body
.element()
.from(1, 0, 1)
.to(15, 10, 15)
.face(Direction.NORTH).uvs(10.5F, 10.65F, 14, 8.25F).texture("#chest").end()
.face(Direction.EAST).uvs(7, 10.65F, 10.5F, 8.25F).texture("#chest").end()
.face(Direction.SOUTH).uvs(3.5F, 10.65F, 7, 8.25F).texture("#chest").end()
.face(Direction.WEST).uvs(0, 10.7F, 3.5F, 8.3F).texture("#chest").end()
.face(Direction.UP).uvs(7, 8.2F, 10.5F, 4.8F).texture("#chest").end()
.face(Direction.DOWN).uvs(3.5F, 8.3F, 7, 4.7F).texture("#chest").end()
.end()
//Lid
.element()
.from(1, 10, 1)
.to(15, 15, 15)
.face(Direction.NORTH).uvs(10.5F, 4.65F, 14, 3.5F).texture("#chest").end()
.face(Direction.EAST).uvs(7, 4.7F, 10.5F, 3.5F).texture("#chest").end()
.face(Direction.SOUTH).uvs(3.5F, 4.7F, 7, 3.5F).texture("#chest").end()
.face(Direction.WEST).uvs(0, 4.7F, 3.5F, 3.5F).texture("#chest").end()
.face(Direction.UP).uvs(7, 3.5F, 10.5F, 0).texture("#chest").end()
.face(Direction.DOWN).uvs(3.5F, 3.5F, 7, 0).texture("#chest").end()
.end()
//Top
.element()
.from(7, 8, 0)
.to(9, 12, 1)
.face(Direction.NORTH).uvs(0.75F, 1.25F, 0.25F, 0.25F).texture("#chest").end()
.face(Direction.EAST).uvs(1.25F, 1.25F, 1.5F, 0.25F).texture("#chest").end()
.face(Direction.SOUTH).uvs(0.75F, 1.25F, 1.25F, 0.25F).texture("#chest").end()
.face(Direction.WEST).uvs(0, 1.25F, 0.25F, 0.25F).texture("#chest").end()
.face(Direction.UP).uvs(0.25F, 0.25F, 0.75F, 0).texture("#chest").end()
.face(Direction.DOWN).uvs(0.75F, 0.25F, 1.25F, 0).texture("#chest").end()
.end();
particleOnly(PEBlocks.ALCHEMICAL_CHEST);
particleOnly(PEBlocks.CONDENSER);
particleOnly(PEBlocks.CONDENSER_MK2);
}
private void particleOnly(BlockRegistryObject<?, ?> block) {
String name = getName(block);
simpleBlock(block.getBlock(), models().getBuilder(name).texture("particle", modLoc("block/" + name)));
}
private void registerPedestal() {
ResourceLocation dm = modLoc("block/dark_matter_block");
BlockModelBuilder model = models()
.withExistingParent(getName(PEBlocks.DARK_MATTER_PEDESTAL), "block/block")
.texture("pedestal", dm)
.texture("particle", dm)
//Base
.element()
.from(3, 0, 3)
.to(13, 2, 13)
.face(Direction.NORTH).uvs(3, 0, 10, 2).texture("#pedestal").end()
.face(Direction.EAST).uvs(3, 0, 10, 2).texture("#pedestal").end()
.face(Direction.SOUTH).uvs(3, 0, 10, 2).texture("#pedestal").end()
.face(Direction.WEST).uvs(3, 0, 10, 2).texture("#pedestal").end()
.face(Direction.UP).uvs(3, 3, 10, 10).texture("#pedestal").end()
.face(Direction.DOWN).uvs(3, 3, 10, 10).texture("#pedestal").cullface(Direction.DOWN).end()
.end()
//Post
.element()
.from(6, 2, 6)
.to(10, 9, 10)
.face(Direction.NORTH).uvs(6, 4, 4, 7).texture("#pedestal").end()
.face(Direction.EAST).uvs(6, 4, 4, 7).texture("#pedestal").end()
.face(Direction.SOUTH).uvs(6, 4, 4, 7).texture("#pedestal").end()
.face(Direction.WEST).uvs(6, 4, 4, 7).texture("#pedestal").end()
.end()
//Top
.element()
.from(5, 9, 5)
.to(11, 10, 11)
.face(Direction.NORTH).uvs(0, 0, 6, 1).texture("#pedestal").end()
.face(Direction.EAST).uvs(0, 0, 6, 1).texture("#pedestal").end()
.face(Direction.SOUTH).uvs(0, 0, 6, 1).texture("#pedestal").end()
.face(Direction.WEST).uvs(0, 0, 6, 1).texture("#pedestal").end()
.face(Direction.UP).uvs(6, 6, 6, 6).texture("#pedestal").end()
.face(Direction.DOWN).uvs(6, 6, 6, 6).texture("#pedestal").end()
.end();
simpleBlock(PEBlocks.DARK_MATTER_PEDESTAL.getBlock(), model);
}
private void registerTransmutationTable() {
ResourceLocation top = modLoc("block/transmutation_stone/top");
BlockModelBuilder model = models()
.withExistingParent(getName(PEBlocks.TRANSMUTATION_TABLE), "block/block")
.texture("bottom", modLoc("block/transmutation_stone/bottom"))
.texture("top", top)
.texture("side", modLoc("block/transmutation_stone/side"))
.texture("particle", top)
.element()
.from(0, 0, 0)
.to(16, 4, 16)
.face(Direction.DOWN).texture("#bottom").cullface(Direction.DOWN).end()
.face(Direction.UP).texture("#top").end()
.face(Direction.NORTH).texture("#side").cullface(Direction.NORTH).end()
.face(Direction.SOUTH).texture("#side").cullface(Direction.SOUTH).end()
.face(Direction.WEST).texture("#side").cullface(Direction.WEST).end()
.face(Direction.EAST).texture("#side").cullface(Direction.EAST).end()
.end();
directionalBlock(PEBlocks.TRANSMUTATION_TABLE.getBlock(), state -> model, 180, BlockStateProperties.WATERLOGGED);
}
private void registerExplosives() {
BlockModelBuilder catalyst = models().cubeBottomTop(getName(PEBlocks.NOVA_CATALYST), modLoc("block/explosives/nova_side"),
modLoc("block/explosives/bottom"), modLoc("block/explosives/top"));
simpleBlock(PEBlocks.NOVA_CATALYST.getBlock(), catalyst);
simpleBlock(PEBlocks.NOVA_CATACLYSM.getBlock(), models().getBuilder(getName(PEBlocks.NOVA_CATACLYSM))
.parent(catalyst)
.texture("side", modLoc("block/explosives/nova1_side")));
}
private void registerInterdictionTorch() {
simpleBlock(PEBlocks.INTERDICTION_TORCH.getBlock(), models().torch(getName(PEBlocks.INTERDICTION_TORCH), modLoc("block/interdiction_torch")));
horizontalBlock(PEBlocks.INTERDICTION_TORCH.getWallBlock(), models().torchWall(PEBlocks.INTERDICTION_TORCH.getWallBlock().getRegistryName().getPath(),
modLoc("block/interdiction_torch")), 90);
}
private void registerFurnace(BlockRegistryObject<?, ?> furnace, String prefix, String sideTexture) {
String name = getName(furnace);
ResourceLocation side = modLoc("block/" + sideTexture);
BlockModelBuilder offModel = models().orientable(name, side, modLoc("block/matter_furnace/" + prefix + "_off"), side);
BlockModelBuilder onModel = models().getBuilder(name + "_on")
.parent(offModel)
.texture("front", modLoc("block/matter_furnace/" + prefix + "_on"));
horizontalBlock(furnace.getBlock(), state -> state.get(AbstractFurnaceBlock.LIT) ? onModel : offModel);
}
private void registerTieredOrientable(String type, BlockRegistryObject<?, ?> base, BlockRegistryObject<?, ?> mk2, BlockRegistryObject<?, ?> mk3) {
ResourceLocation side = modLoc("block/" + type + "/other");
BlockModelBuilder model = models().orientableWithBottom(getName(base), side, modLoc("block/" + type + "/front"), side,
modLoc("block/" + type + "/top_1"));
horizontalBlock(base.getBlock(), model);
horizontalBlock(mk2.getBlock(), models().getBuilder(getName(mk2))
.parent(model)
.texture("top", modLoc("block/" + type + "/top_2")));
horizontalBlock(mk3.getBlock(), models().getBuilder(getName(mk3))
.parent(model)
.texture("top", modLoc("block/" + type + "/top_3")));
}
private void simpleBlocks(BlockRegistryObject<?, ?>... blocks) {
for (BlockRegistryObject<?, ?> block : blocks) {
simpleBlock(block.getBlock());
}
}
private void directionalBlock(Block block, Function<BlockState, ModelFile> modelFunc, int angleOffset, Property<?>... toSkip) {
getVariantBuilder(block).forAllStatesExcept(state -> {
Direction dir = state.get(BlockStateProperties.FACING);
return ConfiguredModel.builder()
.modelFile(modelFunc.apply(state))
.rotationX(dir == Direction.DOWN ? 180 : dir.getAxis().isHorizontal() ? 90 : 0)
.rotationY(dir.getAxis().isVertical() ? 0 : (((int) dir.getHorizontalAngle()) + angleOffset) % 360)
.build();
}, toSkip);
}
private static String getName(IItemProvider itemProvider) {
return itemProvider.asItem().getRegistryName().getPath();
}
} | 3,941 |
1,382 | /*
* Copyright (c) 2007 - 2020 <NAME>
*
* 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.
*/
//
// Gamma distribution
//
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "liquid.internal.h"
float randgammaf(float _alpha,
float _beta)
{
// validate input
if (_alpha <= 0.0f) {
liquid_error(LIQUID_EICONFIG,"randgammaf(), alpha must be greater than zero");
return 0.0f;
} else if (_beta <= 0.0f) {
liquid_error(LIQUID_EICONFIG,"randgammaf(), beta must be greater than zero");
return 0.0f;
}
unsigned int n = (unsigned int) floorf(_alpha);
// residual
float delta = _alpha - (float)n;
// generate x' ~ Gamma(n,1)
float x_n = 0.0f;
unsigned int i;
for (i=0; i<n; i++) {
float u = randf();
x_n += - logf(u);
}
// generate x'' ~ Gamma(delta,1) using rejection method
float x_delta = randgammaf_delta(delta);
//
return _beta * (x_delta + x_n);
}
// Gamma distribution cumulative distribution function
// x^(a-1) exp{-x/b)
// f(x) = -------------------
// Gamma(a) b^a
// where
// a = alpha, a > 0
// b = beta, b > 0
// Gamma(z) = regular gamma function
// x >= 0
float randgammaf_pdf(float _x,
float _alpha,
float _beta)
{
// validate input
if (_alpha <= 0.0f) {
liquid_error(LIQUID_EICONFIG,"randgammaf_pdf(), alpha must be greater than zero");
return 0.0f;
} else if (_beta <= 0.0f) {
liquid_error(LIQUID_EICONFIG,"randgammaf_pdf(), beta must be greater than zero");
return 0.0f;
}
if (_x <= 0.0f)
return 0.0f;
float t0 = powf(_x, _alpha-1.0f);
float t1 = expf(-_x / _beta);
float t2 = liquid_gammaf(_alpha);
float t3 = powf(_beta, _alpha);
return (t0*t1)/(t2*t3);
}
// Gamma distribution cumulative distribution function
// F(x) = gamma(a,x/b) / Gamma(a)
// where
// a = alpha, alpha > 0
// b = beta, beta > 0
// gamma(a,z) = lower incomplete gamma function
// Gamma(z) = regular gamma function
//
float randgammaf_cdf(float _x,
float _alpha,
float _beta)
{
// validate input
if (_alpha <= 0.0f) {
liquid_error(LIQUID_EICONFIG,"randgammaf_cdf(), alpha must be greater than zero");
return 0.0f;
} else if (_beta <= 0.0f) {
liquid_error(LIQUID_EICONFIG,"randgammaf_cdf(), beta must be greater than zero");
return 0.0f;
}
if (_x <= 0.0f)
return 0.0f;
return liquid_lowergammaf(_alpha, _x/_beta) / liquid_gammaf(_alpha);
}
//
// internal methods
//
// generate x ~ Gamma(delta,1)
float randgammaf_delta(float _delta)
{
// validate input
if ( _delta < 0.0f || _delta >= 1.0f ) {
liquid_error(LIQUID_EICONFIG,"randgammaf_delta(), delta must be in [0,1)");
return 0.0f;
}
// initialization
float delta_inv = 1.0f / _delta;
float e = expf(1.0f);
float v0 = e / (e + _delta);
float V0 = 0.0f;
float V1 = 0.0f;
float V2 = 0.0f;
unsigned int m = 1;
float xi = 0.0f;
float eta = 0.0f;
while (1) {
// step 2
V0 = randf();
V1 = randf();
V2 = randf();
if (V2 <= v0) {
// step 4
xi = powf(V1, delta_inv);
eta = V0 * powf(xi, _delta - 1.0f);
} else {
// step 5
xi = 1.0f - logf(V1);
eta = V0 * expf(-xi);
}
// step 6
if ( eta > powf(xi,_delta-1.0f)*expf(-xi) ) {
m++;
} else {
break;
}
}
// xi ~ Gamma(delta,1)
return xi;
}
| 2,130 |
686 | /*
* (C) Copyright IBM Corp. 2019, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.ibm.watson.discovery.v2.model;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
/** Configuration for table retrieval. */
public class QueryLargeTableResults extends GenericModel {
protected Boolean enabled;
protected Long count;
/** Builder. */
public static class Builder {
private Boolean enabled;
private Long count;
private Builder(QueryLargeTableResults queryLargeTableResults) {
this.enabled = queryLargeTableResults.enabled;
this.count = queryLargeTableResults.count;
}
/** Instantiates a new builder. */
public Builder() {}
/**
* Builds a QueryLargeTableResults.
*
* @return the new QueryLargeTableResults instance
*/
public QueryLargeTableResults build() {
return new QueryLargeTableResults(this);
}
/**
* Set the enabled.
*
* @param enabled the enabled
* @return the QueryLargeTableResults builder
*/
public Builder enabled(Boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Set the count.
*
* @param count the count
* @return the QueryLargeTableResults builder
*/
public Builder count(long count) {
this.count = count;
return this;
}
}
protected QueryLargeTableResults(Builder builder) {
enabled = builder.enabled;
count = builder.count;
}
/**
* New builder.
*
* @return a QueryLargeTableResults builder
*/
public Builder newBuilder() {
return new Builder(this);
}
/**
* Gets the enabled.
*
* <p>Whether to enable table retrieval.
*
* @return the enabled
*/
public Boolean enabled() {
return enabled;
}
/**
* Gets the count.
*
* <p>Maximum number of tables to return.
*
* @return the count
*/
public Long count() {
return count;
}
}
| 800 |
2,151 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_AURA_MUS_PROPERTY_UTILS_H_
#define UI_AURA_MUS_PROPERTY_UTILS_H_
#include <stdint.h>
#include <map>
#include <string>
#include <vector>
#include "ui/aura/aura_export.h"
namespace ui {
namespace mojom {
enum class WindowType;
}
}
namespace aura {
class Window;
// Configures the two window type properties on |window|. Specifically this
// sets the property client::kWindowTypeKey as well as calling SetType().
// This *must* be called before Init(). No-op for WindowType::UNKNOWN.
AURA_EXPORT void SetWindowType(Window* window,
ui::mojom::WindowType window_type);
// Returns the window type specified in |properties|, or WindowType::UNKNOWN.
AURA_EXPORT ui::mojom::WindowType GetWindowTypeFromProperties(
const std::map<std::string, std::vector<uint8_t>>& properties);
} // namespace aura
#endif // UI_AURA_MUS_PROPERTY_UTILS_H_
| 374 |
14,668 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/apps/intent_helper/metrics/intent_handling_metrics.h"
#include "ash/components/arc/metrics/arc_metrics_constants.h"
#include "base/metrics/histogram_macros.h"
#include "base/notreached.h"
#include "chrome/browser/apps/intent_helper/chromeos_intent_picker_helpers.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "ash/components/arc/metrics/arc_metrics_service.h"
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
namespace {
using PickerAction = apps::IntentHandlingMetrics::PickerAction;
using IntentPickerAction = apps::IntentHandlingMetrics::IntentPickerAction;
using Platform = apps::IntentHandlingMetrics::Platform;
void RecordDestinationPlatformMetric(
apps::IntentHandlingMetrics::Platform platform) {
UMA_HISTOGRAM_ENUMERATION("ChromeOS.Apps.IntentPickerDestinationPlatform",
platform);
}
IntentPickerAction GetIntentPickerAction(
apps::PickerEntryType entry_type,
apps::IntentPickerCloseReason close_reason,
bool should_persist) {
switch (close_reason) {
case apps::IntentPickerCloseReason::ERROR_BEFORE_PICKER:
case apps::IntentPickerCloseReason::ERROR_AFTER_PICKER:
return IntentPickerAction::kError;
case apps::IntentPickerCloseReason::DIALOG_DEACTIVATED:
return IntentPickerAction::kDialogDeactivated;
case apps::IntentPickerCloseReason::STAY_IN_CHROME:
return should_persist ? IntentPickerAction::kChromeSelectedAndPreferred
: IntentPickerAction::kChromeSelected;
case apps::IntentPickerCloseReason::OPEN_APP:
switch (entry_type) {
case apps::PickerEntryType::kArc:
return should_persist
? IntentPickerAction::kArcAppSelectedAndPreferred
: IntentPickerAction::kArcAppSelected;
case apps::PickerEntryType::kWeb:
return should_persist ? IntentPickerAction::kPwaSelectedAndPreferred
: IntentPickerAction::kPwaSelected;
case apps::PickerEntryType::kDevice:
case apps::PickerEntryType::kMacOs:
case apps::PickerEntryType::kUnknown:
NOTREACHED();
return IntentPickerAction::kInvalid;
}
case apps::IntentPickerCloseReason::PREFERRED_APP_FOUND:
// For the HTTP/HTTPS Intent Picker, preferred app metrics are recorded
// separately in RecordPreferredAppLinkClickMetrics.
NOTREACHED();
return IntentPickerAction::kInvalid;
}
}
Platform GetIntentPickerDestinationPlatform(IntentPickerAction action) {
switch (action) {
case IntentPickerAction::kArcAppSelected:
case IntentPickerAction::kArcAppSelectedAndPreferred:
return Platform::ARC;
case IntentPickerAction::kPwaSelected:
case IntentPickerAction::kPwaSelectedAndPreferred:
return Platform::PWA;
case IntentPickerAction::kChromeSelected:
case IntentPickerAction::kChromeSelectedAndPreferred:
case IntentPickerAction::kDialogDeactivated:
case IntentPickerAction::kError:
return Platform::CHROME;
case IntentPickerAction::kInvalid:
NOTREACHED();
return Platform::CHROME;
}
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
// Converts the provided |entry_type|, |close_reason| and |should_persist|
// boolean to a PickerAction value for recording in UMA.
PickerAction GetExternalProtocolPickerAction(
apps::PickerEntryType entry_type,
apps::IntentPickerCloseReason close_reason,
bool should_persist) {
switch (close_reason) {
case apps::IntentPickerCloseReason::ERROR_BEFORE_PICKER:
return PickerAction::ERROR_BEFORE_PICKER;
case apps::IntentPickerCloseReason::ERROR_AFTER_PICKER:
return PickerAction::ERROR_AFTER_PICKER;
case apps::IntentPickerCloseReason::DIALOG_DEACTIVATED:
return PickerAction::DIALOG_DEACTIVATED;
case apps::IntentPickerCloseReason::PREFERRED_APP_FOUND:
switch (entry_type) {
case apps::PickerEntryType::kUnknown:
return PickerAction::PREFERRED_CHROME_BROWSER_FOUND;
case apps::PickerEntryType::kArc:
return PickerAction::PREFERRED_ARC_ACTIVITY_FOUND;
case apps::PickerEntryType::kWeb:
return PickerAction::PREFERRED_PWA_FOUND;
case apps::PickerEntryType::kDevice:
case apps::PickerEntryType::kMacOs:
NOTREACHED();
return PickerAction::INVALID;
}
case apps::IntentPickerCloseReason::STAY_IN_CHROME:
return should_persist ? PickerAction::CHROME_PREFERRED_PRESSED
: PickerAction::CHROME_PRESSED;
case apps::IntentPickerCloseReason::OPEN_APP:
switch (entry_type) {
case apps::PickerEntryType::kUnknown:
NOTREACHED();
return PickerAction::INVALID;
case apps::PickerEntryType::kArc:
return should_persist ? PickerAction::ARC_APP_PREFERRED_PRESSED
: PickerAction::ARC_APP_PRESSED;
case apps::PickerEntryType::kWeb:
return should_persist ? PickerAction::PWA_APP_PREFERRED_PRESSED
: PickerAction::PWA_APP_PRESSED;
case apps::PickerEntryType::kDevice:
return PickerAction::DEVICE_PRESSED;
case apps::PickerEntryType::kMacOs:
return PickerAction::MAC_OS_APP_PRESSED;
}
}
NOTREACHED();
return PickerAction::INVALID;
}
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
} // namespace
namespace apps {
IntentHandlingMetrics::IntentHandlingMetrics() = default;
void IntentHandlingMetrics::RecordIntentPickerMetrics(
PickerEntryType entry_type,
IntentPickerCloseReason close_reason,
bool should_persist,
PickerShowState show_state) {
IntentPickerAction action =
GetIntentPickerAction(entry_type, close_reason, should_persist);
Platform platform = GetIntentPickerDestinationPlatform(action);
UMA_HISTOGRAM_ENUMERATION("ChromeOS.Intents.IntentPickerAction", action);
switch (show_state) {
case PickerShowState::kOmnibox:
UMA_HISTOGRAM_ENUMERATION(
"ChromeOS.Intents.IntentPickerAction.FromOmniboxIcon", action);
break;
case PickerShowState::kPopOut:
UMA_HISTOGRAM_ENUMERATION(
"ChromeOS.Intents.IntentPickerAction.FromAutoPopOut", action);
break;
}
RecordDestinationPlatformMetric(platform);
}
void IntentHandlingMetrics::RecordPreferredAppLinkClickMetrics(
Platform platform) {
RecordDestinationPlatformMetric(platform);
}
void IntentHandlingMetrics::RecordIntentPickerIconEvent(
IntentPickerIconEvent event) {
UMA_HISTOGRAM_ENUMERATION("ChromeOS.Intents.IntentPickerIconEvent", event);
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
void IntentHandlingMetrics::RecordExternalProtocolMetrics(
arc::Scheme scheme,
PickerEntryType entry_type,
bool accepted,
bool persisted) {
arc::ProtocolAction action =
arc::GetProtocolAction(scheme, entry_type, accepted, persisted);
if (accepted) {
UMA_HISTOGRAM_ENUMERATION("ChromeOS.Apps.ExternalProtocolDialog.Accepted",
action);
} else {
UMA_HISTOGRAM_ENUMERATION("ChromeOS.Apps.ExternalProtocolDialog.Rejected",
action);
}
}
void IntentHandlingMetrics::RecordExternalProtocolUserInteractionMetrics(
content::BrowserContext* context,
PickerEntryType entry_type,
IntentPickerCloseReason close_reason,
bool should_persist) {
if (entry_type == PickerEntryType::kArc &&
(close_reason == IntentPickerCloseReason::PREFERRED_APP_FOUND ||
close_reason == IntentPickerCloseReason::OPEN_APP)) {
arc::ArcMetricsService::RecordArcUserInteraction(
context, arc::UserInteractionType::APP_STARTED_FROM_LINK);
}
// TODO(crbug.com/985233) For now External Protocol Dialog is only querying
// ARC apps, so there's no need to record a destination platform.
PickerAction action =
GetExternalProtocolPickerAction(entry_type, close_reason, should_persist);
UMA_HISTOGRAM_ENUMERATION("ChromeOS.Apps.ExternalProtocolDialog", action);
}
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
void IntentHandlingMetrics::RecordOpenBrowserMetrics(AppType type) {
UMA_HISTOGRAM_ENUMERATION("ChromeOS.Apps.OpenBrowser", type);
}
} // namespace apps
| 3,310 |
605 | package com.sohu.tv.mq.cloud.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sohu.tv.mq.cloud.bo.AuditUserProducerDelete;
import com.sohu.tv.mq.cloud.dao.AuditUserProducerDeleteDao;
import com.sohu.tv.mq.cloud.util.Result;
/**
* userProducer删除审核dao
*
* @Description:
* @author zhehongyuan
* @date 2018年9月5日
*/
@Service
public class AuditUserProducerDeleteService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private AuditUserProducerDeleteDao auditUserProducerDeleteDao;
/**
* 按照aid查询AuditUserProducerDeleteDao
*
* @param Result<AuditUserProducerDelete>
*/
public Result<AuditUserProducerDelete> queryAuditUserProducerDelete(long aid) {
AuditUserProducerDelete auditUserProducerDelete = null;
try {
auditUserProducerDelete = auditUserProducerDeleteDao.selectByAid(aid);
} catch (Exception e) {
logger.error("queryAuditUserProducerDelete err, aid:{}", aid, e);
return Result.getDBErrorResult(e);
}
return Result.getResult(auditUserProducerDelete);
}
/**
* 按照uid和producer查询auditUserProducerDeleteDao 用于校验
*
* @param uid
* @param producer
* @return
*/
public Result<List<AuditUserProducerDelete>> queryAuditUserProducerDeleteByUidAndProducer(long uid,
String producer) {
List<AuditUserProducerDelete> AuditUserProducerDelete = null;
try {
AuditUserProducerDelete = auditUserProducerDeleteDao.selectByUidAndProducer(uid, producer);
} catch (Exception e) {
logger.error("queryAuditUserConsumerDelete err, uid:{}, producer:{}", uid, producer, e);
return Result.getDBErrorResult(e);
}
return Result.getResult(AuditUserProducerDelete);
}
}
| 908 |
396 | <gh_stars>100-1000
/*
Copyright 2018 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "node/processing_node.h"
namespace vraudio {
ProcessingNode::NodeInput::NodeInput(
const std::vector<const AudioBuffer*>& input_vector)
: input_vector_(input_vector) {}
const AudioBuffer* ProcessingNode::NodeInput::GetSingleInput() const {
if (input_vector_.size() == 1) {
return input_vector_[0];
}
if (input_vector_.size() > 1) {
LOG(WARNING) << "GetSingleInput() called on multi buffer input";
}
return nullptr;
}
const std::vector<const AudioBuffer*>&
ProcessingNode::NodeInput::GetInputBuffers() const {
return input_vector_;
}
ProcessingNode::ProcessingNode()
: Node(), output_stream_(this), process_on_no_input_(false) {}
void ProcessingNode::Connect(
const std::shared_ptr<PublisherNodeType>& publisher_node) {
input_stream_.Connect(publisher_node->GetSharedNodePtr(),
publisher_node->GetOutput());
}
void ProcessingNode::Process() {
NodeInput input(input_stream_.Read());
const AudioBuffer* output = nullptr;
// Only call AudioProcess if input data is available.
if (process_on_no_input_ || !input.GetInputBuffers().empty()) {
output = AudioProcess(input);
}
output_stream_.Write(output);
}
bool ProcessingNode::CleanUp() {
CallCleanUpOnInputNodes();
return (input_stream_.GetNumConnections() == 0);
}
void ProcessingNode::EnableProcessOnEmptyInput(bool enable) {
process_on_no_input_ = enable;
}
void ProcessingNode::CallCleanUpOnInputNodes() {
// We need to make a copy of the OutputNodeMap map since it changes due to
// Disconnect() calls.
const auto connected_nodes = input_stream_.GetConnectedNodeOutputPairs();
for (const auto& input_node : connected_nodes) {
Output<const AudioBuffer*>* output = input_node.first;
std::shared_ptr<Node> node = input_node.second;
const bool is_ready_to_be_disconnected = node->CleanUp();
if (is_ready_to_be_disconnected) {
input_stream_.Disconnect(output);
}
}
}
std::shared_ptr<Node> ProcessingNode::GetSharedNodePtr() {
return shared_from_this();
}
Node::Output<const AudioBuffer*>* ProcessingNode::GetOutput() {
return &output_stream_;
}
} // namespace vraudio
| 887 |
838 | <reponame>FlorianPoot/MicroPython_ESP32_psRAM_LoBo
/*-
* Copyright (c) 1991, 1993, 1994
* The Regents of the University of California. 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*
* @(#)extern.h 8.10 (Berkeley) 7/20/94
*/
int __bt_close __P((DB *));
int __bt_cmp __P((BTREE *, const DBT *, EPG *));
int __bt_crsrdel __P((BTREE *, EPGNO *));
int __bt_defcmp __P((const DBT *, const DBT *));
size_t __bt_defpfx __P((const DBT *, const DBT *));
int __bt_delete __P((const DB *, const DBT *, u_int));
int __bt_dleaf __P((BTREE *, const DBT *, PAGE *, u_int));
int __bt_fd __P((const DB *));
int __bt_free __P((BTREE *, PAGE *));
int __bt_get __P((const DB *, const DBT *, DBT *, u_int));
PAGE *__bt_new __P((BTREE *, pgno_t *));
void __bt_pgin __P((void *, pgno_t, void *));
void __bt_pgout __P((void *, pgno_t, void *));
int __bt_push __P((BTREE *, pgno_t, int));
int __bt_put __P((const DB *dbp, DBT *, const DBT *, u_int));
int __bt_ret __P((BTREE *, EPG *, DBT *, DBT *, DBT *, DBT *, int));
EPG *__bt_search __P((BTREE *, const DBT *, int *));
int __bt_seq __P((const DB *, DBT *, DBT *, u_int));
void __bt_setcur __P((BTREE *, pgno_t, u_int));
int __bt_split __P((BTREE *, PAGE *,
const DBT *, const DBT *, int, size_t, u_int32_t));
int __bt_sync __P((const DB *, u_int));
int __ovfl_delete __P((BTREE *, void *));
int __ovfl_get __P((BTREE *, void *, size_t *, void **, size_t *));
int __ovfl_put __P((BTREE *, const DBT *, pgno_t *));
#ifdef DEBUG
void __bt_dnpage __P((DB *, pgno_t));
void __bt_dpage __P((PAGE *));
void __bt_dump __P((DB *));
#endif
#ifdef STATISTICS
void __bt_stat __P((DB *));
#endif
| 1,191 |
892 | <reponame>westonsteimel/advisory-database-github<filename>advisories/unreviewed/2022/05/GHSA-922f-j548-hrpp/GHSA-922f-j548-hrpp.json
{
"schema_version": "1.2.0",
"id": "GHSA-922f-j548-hrpp",
"modified": "2022-05-02T03:56:08Z",
"published": "2022-05-02T03:56:08Z",
"aliases": [
"CVE-2009-4590"
],
"details": "Cross-site scripting (XSS) vulnerability in base_local_rules.php in Basic Analysis and Security Engine (BASE) before 1.4.4 allows remote attackers to inject arbitrary web script or HTML via unspecified vectors.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2009-4590"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/53968"
},
{
"type": "WEB",
"url": "http://base.secureideas.net/news.php"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/37147"
},
{
"type": "WEB",
"url": "http://secureideas.cvs.sourceforge.net/viewvc/secureideas/base-php4/docs/CHANGELOG?revision=1.359&view=markup"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2009/3054"
}
],
"database_specific": {
"cwe_ids": [
"CWE-79"
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 641 |
13,885 | <reponame>N500/filament
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <utils/Path.h>
#include <dlfcn.h>
using utils::Path;
namespace bluevk {
#ifdef IOS
static const char* VKLIBRARY_PATH = "Frameworks/libMoltenVK.dylib";
#else
static const char* VKLIBRARY_PATH = "libvulkan.1.dylib";
#endif
static void* module = nullptr;
bool loadLibrary() {
#ifndef FILAMENT_VKLIBRARY_PATH
// Rather than looking in the working directory, look for the dylib in the same folder that the
// executable lives in. This allows MacOS users to run Vulkan-based Filament apps from anywhere.
const Path executableFolder = Path::getCurrentExecutable().getParent();
const Path dylibPath = executableFolder.concat(VKLIBRARY_PATH);
// Provide a value for VK_ICD_FILENAMES only if it has not already been set.
const char* icd = getenv("VK_ICD_FILENAMES");
if (icd == nullptr) {
const Path jsonPath = executableFolder.concat("MoltenVK_icd.json");
setenv("VK_ICD_FILENAMES", jsonPath.c_str(), 1);
}
#else
const Path dylibPath = FILAMENT_VKLIBRARY_PATH;
#endif
module = dlopen(dylibPath.c_str(), RTLD_NOW | RTLD_LOCAL);
if (module == nullptr) {
printf("%s\n", dlerror());
}
return module != nullptr;
}
void* getInstanceProcAddr() {
return dlsym(module, "vkGetInstanceProcAddr");
}
} // namespace bluevk
| 663 |
304 | <gh_stars>100-1000
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.demo.opengl.shader;
import static org.lwjgl.demo.opengl.util.DemoUtils.createShader;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.system.MemoryUtil.*;
import java.io.IOException;
import java.nio.*;
import org.joml.Matrix4f;
import org.joml.Matrix4x3f;
import org.joml.Vector4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWFramebufferSizeCallback;
import org.lwjgl.glfw.GLFWKeyCallback;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.GLCapabilities;
import org.lwjgl.opengl.GLUtil;
import org.lwjgl.system.*;
/**
* Renders a projected grid without using any vertex source but fully computing the vertex positions in the vertex shader.
* <p>
* This showcases JOML's implementation of <a href="http://fileadmin.cs.lth.se/graphics/theses/projects/projgrid/projgrid-lq.pdf">Projected Grid</a>.
* <p>
* This demo does not take care or show how to obtain a "pleasant" projector matrix. Consult section 2.4.1 in the referenced paper for more
* guidance on how to obtain a projector matrix.
* So, to keep things simple this demo instead just uses the camera's view-projection matrix as the projector matrix.
*
* @author <NAME>
*/
public class NoVerticesProjectedGridDemo {
long window;
int width = 1024;
int height = 768;
int program;
int transformUniform;
int intersectionsUniform;
int timeUniform;
int sizeUniform;
GLCapabilities caps;
GLFWErrorCallback errCallback;
GLFWKeyCallback keyCallback;
GLFWFramebufferSizeCallback fbCallback;
Callback debugProc;
FloatBuffer matrixBuffer = BufferUtils.createFloatBuffer(16);
Matrix4x3f view = new Matrix4x3f();
Matrix4f proj = new Matrix4f();
Matrix4f viewproj = new Matrix4f();
int sizeX = 128;
int sizeY = 128;
void init() throws IOException {
glfwSetErrorCallback(errCallback = new GLFWErrorCallback() {
GLFWErrorCallback delegate = GLFWErrorCallback.createPrint(System.err);
@Override
public void invoke(int error, long description) {
if (error == GLFW_VERSION_UNAVAILABLE)
System.err.println("This demo requires OpenGL 3.0 or higher.");
delegate.invoke(error, description);
}
@Override
public void free() {
delegate.free();
}
});
if (!glfwInit())
throw new IllegalStateException("Unable to initialize GLFW");
glfwDefaultWindowHints();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
window = glfwCreateWindow(width, height, "No vertices projected grid shader demo", NULL, NULL);
if (window == NULL) {
throw new AssertionError("Failed to create the GLFW window");
}
glfwSetFramebufferSizeCallback(window, fbCallback = new GLFWFramebufferSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
if (width > 0 && height > 0 && (NoVerticesProjectedGridDemo.this.width != width || NoVerticesProjectedGridDemo.this.height != height)) {
NoVerticesProjectedGridDemo.this.width = width;
NoVerticesProjectedGridDemo.this.height = height;
}
}
});
System.out.println("Press 'arrow right' to increase the grid size in X");
System.out.println("Press 'arrow left' to decrease the grid size in X");
System.out.println("Press 'arrow up' to increase the grid size in Y");
System.out.println("Press 'arrow down' to decrease the grid size in Y");
glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {
@Override
public void invoke(long window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) {
glfwSetWindowShouldClose(window, true);
}
if (key == GLFW_KEY_LEFT && (action == GLFW_RELEASE || action == GLFW_REPEAT)) {
sizeX = Math.max(1, sizeX - 1);
} else if (key == GLFW_KEY_RIGHT && (action == GLFW_RELEASE || action == GLFW_REPEAT)) {
sizeX++;
} else if (key == GLFW_KEY_DOWN && (action == GLFW_RELEASE || action == GLFW_REPEAT)) {
sizeY = Math.max(1, sizeY - 1);
} else if (key == GLFW_KEY_UP && (action == GLFW_RELEASE || action == GLFW_REPEAT)) {
sizeY++;
}
}
});
GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);
try (MemoryStack frame = MemoryStack.stackPush()) {
IntBuffer framebufferSize = frame.mallocInt(2);
nglfwGetFramebufferSize(window, memAddress(framebufferSize), memAddress(framebufferSize) + 4);
width = framebufferSize.get(0);
height = framebufferSize.get(1);
}
glfwMakeContextCurrent(window);
glfwSwapInterval(0);
glfwShowWindow(window);
caps = createCapabilities();
debugProc = GLUtil.setupDebugMessageCallback();
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
// Create all needed GL resources
createProgram();
// and set some GL state
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
void createProgram() throws IOException {
int program = glCreateProgram();
int vshader = createShader("org/lwjgl/demo/opengl/shader/noverticesprojectedgrid.vs", GL_VERTEX_SHADER);
int fshader = createShader("org/lwjgl/demo/opengl/shader/noverticesprojectedgrid.fs", GL_FRAGMENT_SHADER);
glAttachShader(program, vshader);
glAttachShader(program, fshader);
glLinkProgram(program);
int linked = glGetProgrami(program, GL_LINK_STATUS);
String programLog = glGetProgramInfoLog(program);
if (programLog.trim().length() > 0) {
System.err.println(programLog);
}
if (linked == 0) {
throw new AssertionError("Could not link program");
}
this.program = program;
glUseProgram(program);
transformUniform = glGetUniformLocation(program, "transform");
intersectionsUniform = glGetUniformLocation(program, "intersections");
timeUniform = glGetUniformLocation(program, "time");
sizeUniform = glGetUniformLocation(program, "size");
glUseProgram(0);
}
Matrix4f projector = new Matrix4f();
Matrix4f invViewProj = new Matrix4f();
Matrix4f range = new Matrix4f();
Vector4f p0 = new Vector4f();
Vector4f p1 = new Vector4f();
Vector4f isect = new Vector4f();
float alpha = 0.0f;
long lastTime = System.nanoTime();
final float MAX_HEIGHT = 0.2f;
void render() {
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(this.program);
long thisTime = System.nanoTime();
float delta = (thisTime - lastTime) / 1E9f;
alpha += delta * 2.0f;
lastTime = thisTime;
// Build camera view-projection matrix
Matrix4f r = viewproj
.setPerspective((float) Math.toRadians(45.0f), (float)width/height, 0.1f, 100.0f)
.lookAt(0, 4, 20, 0, 0, 0, 0, 1, 0)
.invert(invViewProj) // <- invert it
.projectedGridRange(viewproj, -MAX_HEIGHT, MAX_HEIGHT, range); // <- build range matrix
if (r == null) {
// grid not visible. We don't render anything!
return;
}
invViewProj.mul(range, projector); // <- build final projector matrix
// compute the intersections with the y=0 plane at the grid corners in homogeneous space
for (int i = 0; i < 4; i++) {
float x = (i & 1);
float y = (i >>> 1) & 1;
projector.transform(p0.set(x, y, -1, 1));
projector.transform(p1.set(x, y, +1, 1));
float t = -p0.y / (p1.y - p0.y);
isect.set(p1).sub(p0).mul(t).add(p0);
glUniform4f(intersectionsUniform+i, isect.x, isect.y, isect.z, isect.w);
}
// upload matrices to the shader
glUniformMatrix4fv(transformUniform, false, viewproj.get(matrixBuffer));
glUniform1f(timeUniform, alpha);
glUniform2i(sizeUniform, sizeX, sizeY);
glDrawArrays(GL_TRIANGLES, 0, 6 * sizeX * sizeY);
glUseProgram(0);
}
void loop() {
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
glViewport(0, 0, width, height);
render();
glfwSwapBuffers(window);
}
}
void run() {
try {
init();
loop();
if (debugProc != null) {
debugProc.free();
}
errCallback.free();
keyCallback.free();
fbCallback.free();
glfwDestroyWindow(window);
} catch (Throwable t) {
t.printStackTrace();
} finally {
glfwTerminate();
}
}
public static void main(String[] args) {
new NoVerticesProjectedGridDemo().run();
}
} | 4,349 |
2,151 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_DATA_DECODER_XML_PARSER_H_
#define SERVICES_DATA_DECODER_XML_PARSER_H_
#include <memory>
#include <string>
#include "base/macros.h"
#include "services/data_decoder/public/mojom/xml_parser.mojom.h"
#include "services/service_manager/public/cpp/service_context_ref.h"
namespace data_decoder {
class XmlParser : public mojom::XmlParser {
public:
explicit XmlParser(
std::unique_ptr<service_manager::ServiceContextRef> service_ref);
~XmlParser() override;
private:
const std::unique_ptr<service_manager::ServiceContextRef> service_ref_;
// mojom::XmlParser implementation.
void Parse(const std::string& xml, ParseCallback callback) override;
DISALLOW_COPY_AND_ASSIGN(XmlParser);
};
} // namespace data_decoder
#endif // SERVICES_DATA_DECODER_XML_PARSER_H_
| 334 |
480 | <reponame>weicao/galaxysql<gh_stars>100-1000
/*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.polardbx.optimizer.core.rel.ddl;
import com.alibaba.polardbx.common.exception.TddlNestableRuntimeException;
import com.alibaba.polardbx.common.utils.TStringUtil;
import com.alibaba.polardbx.optimizer.OptimizerContext;
import com.alibaba.polardbx.optimizer.config.table.SchemaManager;
import com.alibaba.polardbx.optimizer.config.table.TableMeta;
import com.alibaba.polardbx.optimizer.core.rel.ddl.data.RenameTablePreparedData;
import org.apache.calcite.rel.ddl.RenameTable;
import org.apache.calcite.sql.SqlIdentifier;
public class LogicalRenameTable extends BaseDdlOperation {
private RenameTablePreparedData renameTablePreparedData;
public LogicalRenameTable(RenameTable renameTable) {
super(renameTable);
}
public static LogicalRenameTable create(RenameTable renameTable) {
return new LogicalRenameTable(renameTable);
}
public RenameTablePreparedData getRenameTablePreparedData() {
return renameTablePreparedData;
}
public void prepareData() {
renameTablePreparedData = preparePrimaryData();
}
private RenameTablePreparedData preparePrimaryData() {
RenameTablePreparedData preparedData = new RenameTablePreparedData();
SchemaManager sm = OptimizerContext.getContext(schemaName).getLatestSchemaManager();
TableMeta tableMeta = sm.getTable(tableName);
SqlIdentifier newTableName = (SqlIdentifier) relDdl.getNewTableName();
if (newTableName != null && !newTableName.isSimple()) {
String targetSchema = newTableName.names.get(0);
if (OptimizerContext.getContext(targetSchema) == null) {
throw new TddlNestableRuntimeException("Unknown target database " + targetSchema);
} else if (!TStringUtil.equalsIgnoreCase(targetSchema, schemaName)) {
throw new TddlNestableRuntimeException("Target database must be the same as source database");
}
}
preparedData.setSchemaName(schemaName);
preparedData.setTableName(tableName);
preparedData.setNewTableName(newTableName.getLastName());
preparedData.setTableVersion(tableMeta.getVersion());
return preparedData;
}
}
| 1,008 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.