max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
435
<reponame>amaajemyfren/data { "description": "Feedback session and Closing Address of PyCon Pune", "duration": 2966, "recorded": "2017-02-17", "speakers": [ "Various speakers" ], "thumbnail_url": "https://i.ytimg.com/vi/Bep1oQ2VW0o/hqdefault.jpg", "title": "Feedback session and Closing Address", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=Bep1oQ2VW0o" } ] }
185
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.maven.newproject.idenative; import org.netbeans.api.templates.TemplateRegistration; import org.netbeans.modules.maven.api.archetype.ArchetypeWizards; import static org.netbeans.modules.maven.newproject.idenative.Bundle.LBL_Maven_POM_Archetype; import org.openide.util.NbBundle; /** * * @author mkleint */ @TemplateRegistration(folder=ArchetypeWizards.TEMPLATE_FOLDER, position=980, displayName="#LBL_Maven_POM_Archetype", iconBase="org/netbeans/modules/maven/resources/Maven2Icon.gif", description="pom-root.html") @NbBundle.Messages("LBL_Maven_POM_Archetype=POM Project") public class PomJavaNativeMWI extends IDENativeMavenWizardIterator { public PomJavaNativeMWI() { super(LBL_Maven_POM_Archetype(), "org.codehaus.mojo.archetypes:pom-root:1.1", "pom"); } }
503
629
<reponame>unghee/TorchCraftAI /* * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <set> #include <vector> #include "module.h" #include "unitsinfo.h" namespace cherrypi { /** * The last module run in each frame. * Consumes all remaining unambiguous (sharp) UPCs and issues BWAPI commands * via TorchCraft. */ class UPCToCommandModule : public Module { public: UPCToCommandModule() {} virtual ~UPCToCommandModule() = default; virtual void step(State* s); private: struct UPCToCommandState { std::set<const Unit*> commandToUnit; std::vector<tc::Client::Command> commands; std::vector<int> upcIds; }; void checkDuplicateCommand( State* state, const Unit*, UpcId newUpcId, UPCToCommandState&); void registerCommand( State*, const Unit*, UpcId, tc::Client::Command, UPCToCommandState&); void stepUPC(State*, UPCToCommandState&, UpcId, UPCTuple* const); void postGameCommand(State*, UPCToCommandState&); void temporaryDebugDrawing(State*, UPCToCommandState&); }; } // namespace cherrypi
435
601
/* * Copyright 2018-2021 the original author or authors. * * 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 * * https://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.springframework.data.jdbc.core.mapping; import java.util.Objects; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * A reference to the aggregate root of a different aggregate. * * @param <T> the type of the referenced aggregate root. * @param <ID> the type of the id of the referenced aggregate root. * @author <NAME> * @author <NAME> * @since 1.0 */ public interface AggregateReference<T, ID> { static <T, ID> AggregateReference<T, ID> to(ID id) { return new IdOnlyAggregateReference<>(id); } /** * @return the id of the referenced aggregate. May be {@code null}. */ @Nullable ID getId(); /** * An {@link AggregateReference} that only holds the id of the referenced aggregate root. Note that there is no check * that a matching aggregate for this id actually exists. * * @param <T> * @param <ID> */ class IdOnlyAggregateReference<T, ID> implements AggregateReference<T, ID> { private final ID id; public IdOnlyAggregateReference(ID id) { Assert.notNull(id, "Id must not be null."); this.id = id; } @Override public ID getId() { return id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IdOnlyAggregateReference<?, ?> that = (IdOnlyAggregateReference<?, ?>) o; return id.equals(that.id); } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return "IdOnlyAggregateReference{" + "id=" + id + '}'; } } }
724
303
from datetime import datetime, timedelta from threading import current_thread from django.conf import settings from django.contrib import auth class AutoLogout: def process_request(self, request): if not request.user.is_authenticated(): return if 'last_touch' in request.session: max_inactive = timedelta(0, settings.AUTO_LOGOUT_DELAY * 60, 0) current_inactive = datetime.now() - request.session['last_touch'] if current_inactive > max_inactive: auth.logout(request) return request.session['last_touch'] = datetime.now() class UserMiddleware(object): _requests = {} @classmethod def current_user(cls): current_request = cls._requests.get(current_thread().ident, None) if not current_request: return return current_request.user @classmethod def set_current_user(cls, user): current_request = cls._requests[current_thread().ident] current_request.user = user def process_request(self, request): self._requests[current_thread().ident] = request def process_response(self, request, response): self._requests.pop(current_thread().ident, None) return response def process_exception(self, request, exception): self._requests.pop(current_thread().ident, None)
549
368
/************************************************************ * @file DDModule.h * @author 快刀<<EMAIL>> * summery 模块ID定义 ************************************************************/ #import <Foundation/Foundation.h> //static const uint16 MODULE_ID_REMOTEBASE = 0x0000U; //与服务器端交互的module id //static const uint16 MODULE_ID_LOCALBASE = 0x4000U; //本地业务的module id //enum //{ // MODULE_ID_NONE = 0, //与服务器端交互的module id // MODULE_ID_LOGIN = MODULE_ID_REMOTEBASE | 0x0002, //登陆模块 // MODULE_ID_FRIENDLIST = MODULE_ID_REMOTEBASE | 0x0003, //成员列表管理模块 // MODULE_ID_MESSAGE = MODULE_ID_REMOTEBASE | 0x0004, //消息管理模块 // MODULE_ID_HTTP = MODULE_ID_REMOTEBASE | 0x0005, //HTTP模块 // MODULE_ID_TCPLINK = MODULE_ID_REMOTEBASE | 0x0006, //TCP长连接模块 // MODULE_ID_MAIN = MODULE_ID_REMOTEBASE | 0x0007, //主窗口模块i // MODULE_ID_SESSION = MODULE_ID_REMOTEBASE | 0x0050, //会话模块 // MODULE_ID_GROUP = MODULE_ID_REMOTEBASE | 0x0052, // group module // MODULE_ID_P2P = MODULE_ID_REMOTEBASE | 0x0051, //P2P // MODULE_ID_FILETRANSFER = MODULE_ID_REMOTEBASE | 0x005A, //文件传输模块 //本地业务的module id // MODULE_ID_CAPTURE = MODULE_ID_LOCALBASE | 0x001, //截屏模块 // MODULE_ID_COMMON = MODULE_ID_LOCALBASE | 0X002, //多多公共函数库 //};
877
17,318
<gh_stars>1000+ { "targets": [ { "target_name": "nodecat", "sources": [ "src/nodecat.cc", ], "include_dirs": [ "include" ], "libraries": [ "-lcatclient" ] } ] }
226
2,651
class DataOverflowError(Exception): pass
14
7,482
<gh_stars>1000+ /* * Copyright (c) 2006-2021, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2009-01-05 Bernard first implementation * 2014-06-20 xiaonong ported to LPC43xx */ #include <rthw.h> #include <rtthread.h> #include "board.h" #include "drv_uart.h" /** M0 does not have SysTick so we have to use RIT timer for it... */ void RIT_OR_WWDT_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); if (LPC_RITIMER->CTRL & 0x01) { rt_tick_increase(); LPC_RITIMER->CTRL |= 0x01; } /* leave interrupt */ rt_interrupt_leave(); } extern void SystemCoreClockUpdate(void); /** * This function will initial LPC43xx board. */ void rt_hw_board_init() { SystemCoreClockUpdate(); /* Setup RIT timer. */ LPC_RITIMER->MASK = 0; LPC_RITIMER->COMPVAL = SystemCoreClock / RT_TICK_PER_SECOND; /* Enable auto-clear. */ LPC_RITIMER->CTRL |= 1 << 1; /* Reset the counter as the counter is enabled after reset. */ LPC_RITIMER->COUNTER = 0; NVIC_SetPriority(M0_RITIMER_OR_WWDT_IRQn, (1 << __NVIC_PRIO_BITS) - 1); NVIC_EnableIRQ(M0_RITIMER_OR_WWDT_IRQn); /* set pend exception priority */ NVIC_SetPriority(PendSV_IRQn, (1 << __NVIC_PRIO_BITS) - 1); /* init uart device */ rt_hw_uart_init(); /* setup the console device */ rt_console_set_device(RT_CONSOLE_DEVICE_NAME); }
674
387
from enum import IntEnum class AddressState(IntEnum): NoState = 0 InWallet = 1 WatchOnly = 2
41
4,348
/* * Copyright 2013 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. */ package com.google.maps.android; import com.google.android.gms.maps.model.LatLng; import java.util.List; import static java.lang.Math.*; public class SphericalUtil { private SphericalUtil() {} /** * The earth's radius, in meters. * Mean radius as defined by IUGG. */ static final double EARTH_RADIUS = 6371009; /** * Returns the heading from one LatLng to another LatLng. Headings are * expressed in degrees clockwise from North within the range [-180,180). * @return The heading in degrees clockwise from north. */ public static double computeHeading(LatLng from, LatLng to) { // http://williams.best.vwh.net/avform.htm#Crs double fromLat = toRadians(from.latitude); double fromLng = toRadians(from.longitude); double toLat = toRadians(to.latitude); double toLng = toRadians(to.longitude); double dLng = toLng - fromLng; double heading = atan2( sin(dLng) * cos(toLat), cos(fromLat) * sin(toLat) - sin(fromLat) * cos(toLat) * cos(dLng)); return wrap(toDegrees(heading), -180, 180); } /** * Returns the LatLng resulting from moving a distance from an origin * in the specified heading (expressed in degrees clockwise from north). * @param from The LatLng from which to start. * @param distance The distance to travel. * @param heading The heading in degrees clockwise from north. */ public static LatLng computeOffset(LatLng from, double distance, double heading) { distance /= EARTH_RADIUS; heading = toRadians(heading); // http://williams.best.vwh.net/avform.htm#LL double fromLat = toRadians(from.latitude); double fromLng = toRadians(from.longitude); double cosDistance = cos(distance); double sinDistance = sin(distance); double sinFromLat = sin(fromLat); double cosFromLat = cos(fromLat); double sinLat = cosDistance * sinFromLat + sinDistance * cosFromLat * cos(heading); double dLng = atan2( sinDistance * cosFromLat * sin(heading), cosDistance - sinFromLat * sinLat); return new LatLng(toDegrees(asin(sinLat)), toDegrees(fromLng + dLng)); } /** * Returns the location of origin when provided with a LatLng destination, * meters travelled and original heading. Headings are expressed in degrees * clockwise from North. This function returns null when no solution is * available. * @param to The destination LatLng. * @param distance The distance travelled, in meters. * @param heading The heading in degrees clockwise from north. */ public static LatLng computeOffsetOrigin(LatLng to, double distance, double heading) { heading = toRadians(heading); distance /= EARTH_RADIUS; // http://lists.maptools.org/pipermail/proj/2008-October/003939.html double n1 = cos(distance); double n2 = sin(distance) * cos(heading); double n3 = sin(distance) * sin(heading); double n4 = sin(toRadians(to.latitude)); // There are two solutions for b. b = n2 * n4 +/- sqrt(), one solution results // in the latitude outside the [-90, 90] range. We first try one solution and // back off to the other if we are outside that range. double n12 = n1 * n1; double discriminant = n2 * n2 * n12 + n12 * n12 - n12 * n4 * n4; if (discriminant < 0) { // No real solution which would make sense in LatLng-space. return null; } double b = n2 * n4 + sqrt(discriminant); b /= n1 * n1 + n2 * n2; double a = (n4 - n2 * b) / n1; double fromLatRadians = atan2(a, b); if (fromLatRadians < -PI / 2 || fromLatRadians > PI / 2) { b = n2 * n4 - sqrt(discriminant); b /= n1 * n1 + n2 * n2; fromLatRadians = atan2(a, b); } if (fromLatRadians < -PI / 2 || fromLatRadians > PI / 2) { // No solution which would make sense in LatLng-space. return null; } double fromLngRadians = toRadians(to.longitude) - atan2(n3, n1 * cos(fromLatRadians) - n2 * sin(fromLatRadians)); return new LatLng(toDegrees(fromLatRadians), toDegrees(fromLngRadians)); } /** * Returns the LatLng which lies the given fraction of the way between the * origin LatLng and the destination LatLng. * @param from The LatLng from which to start. * @param to The LatLng toward which to travel. * @param fraction A fraction of the distance to travel. * @return The interpolated LatLng. */ public static LatLng interpolate(LatLng from, LatLng to, double fraction) { // http://en.wikipedia.org/wiki/Slerp double fromLat = toRadians(from.latitude); double fromLng = toRadians(from.longitude); double toLat = toRadians(to.latitude); double toLng = toRadians(to.longitude); double cosFromLat = cos(fromLat); double cosToLat = cos(toLat); // Computes Spherical interpolation coefficients. double angle = computeAngleBetween(from, to); double sinAngle = sin(angle); if (sinAngle < 1E-6) { return from; } double a = sin((1 - fraction) * angle) / sinAngle; double b = sin(fraction * angle) / sinAngle; // Converts from polar to vector and interpolate. double x = a * cosFromLat * cos(fromLng) + b * cosToLat * cos(toLng); double y = a * cosFromLat * sin(fromLng) + b * cosToLat * sin(toLng); double z = a * sin(fromLat) + b * sin(toLat); // Converts interpolated vector back to polar. double lat = atan2(z, sqrt(x * x + y * y)); double lng = atan2(y, x); return new LatLng(toDegrees(lat), toDegrees(lng)); } /** * Returns the angle between two LatLngs, in radians. */ static double computeAngleBetween(LatLng from, LatLng to) { // Haversine's formula double fromLat = toRadians(from.latitude); double fromLng = toRadians(from.longitude); double toLat = toRadians(to.latitude); double toLng = toRadians(to.longitude); double dLat = fromLat - toLat; double dLng = fromLng - toLng; return 2 * asin(sqrt(pow(sin(dLat / 2), 2) + cos(fromLat) * cos(toLat) * pow(sin(dLng / 2), 2))); } /** * Returns the distance between two LatLngs, in meters. */ public static double computeDistanceBetween(LatLng from, LatLng to) { return computeAngleBetween(from, to) * EARTH_RADIUS; } /** * Returns the length of the given path. */ public static double computeLength(List<LatLng> path) { double length = 0; for (int i = 0, I = path.size() - 1; i < I; ++i) { length += computeDistanceBetween(path.get(i), path.get(i + 1)); } return length; } /** * Returns the area of a closed path. The computed area uses the same units as * the radius. * @param path A closed path. * @return The loop's area in square meters. */ public static double computeArea(List<LatLng> path) { return abs(computeSignedArea(path)); } /** * Returns the signed area of a closed path. The signed area may be used to * determine the orientation of the path. The computed area uses the same * units as the radius. * @param loop A closed path. * @return The loop's area in square meters. */ public static double computeSignedArea(List<LatLng> loop) { // For each edge, accumulate the signed area of the triangle formed with // the first point. We can skip the first and last edge as they form // triangles of zero area. LatLng origin = loop.get(0); double total = 0; for (int i = 1, I = loop.size() - 1; i < I; ++i) { total += computeSignedTriangleArea(origin, loop.get(i), loop.get(i + 1)); } return total * EARTH_RADIUS * EARTH_RADIUS; } /** * Compute the signed area of the triangle [a, b, c] on the unit sphere. */ static double computeSignedTriangleArea(LatLng a, LatLng b, LatLng c) { return computeTriangleArea(a, b, c) * isCCW(a, b, c); } /** * Compute the area of the triangle [a, b, c] on the unit sphere. * We use l'Huilier's theorem, which is the Spherical analogue of Heron's * theorem for the area of a triangle in R2. * @return The area. */ static double computeTriangleArea(LatLng a, LatLng b, LatLng c) { LatLng[] points = new LatLng[]{a, b, c, a}; // Simplify cyclic indexing // Compute the length of each edge, and s which is half the perimeter. double[] angles = new double[3]; double s = 0; for (int i = 0; i < 3; ++i) { angles[i] = computeAngleBetween(points[i], points[i + 1]); s += angles[i]; } s /= 2; // Apply l'Huilier's theorem double product = tan(s / 2); for (int i = 0; i < 3; ++i) { product *= tan((s - angles[i]) / 2); } return 4 * atan(sqrt(abs(product))); } /** * Compute the ordering of 3 points in a triangle: * Counter ClockWise (CCW) vs ClockWise (CW). * Results are indeterminate for triangles of area 0. * @return +1 if CCW, -1 if CW. */ static int isCCW(LatLng a, LatLng b, LatLng c) { // Convert the 3 points to 3 unit vectors on the sphere. LatLng[] points = new LatLng[]{a, b, c}; double[][] pointsR3 = new double[3][]; for (int i = 0; i < 3; ++i) { LatLng latLng = points[i]; double lat = toRadians(latLng.latitude); double lng = toRadians(latLng.longitude); double[] r3 = new double[3]; r3[0] = cos(lat) * cos(lng); r3[1] = cos(lat) * sin(lng); r3[2] = sin(lat); pointsR3[i] = r3; } // Compute the determinant of the matrix formed by the 3 unit vectors. double det = pointsR3[0][0] * pointsR3[1][1] * pointsR3[2][2] + pointsR3[1][0] * pointsR3[2][1] * pointsR3[0][2] + pointsR3[2][0] * pointsR3[0][1] * pointsR3[1][2] - pointsR3[0][0] * pointsR3[2][1] * pointsR3[1][2] - pointsR3[1][0] * pointsR3[0][1] * pointsR3[2][2] - pointsR3[2][0] * pointsR3[1][1] * pointsR3[0][2]; // Threshold to sign return det > 0 ? 1 : -1; } /** * Wraps the given value into the inclusive-exclusive interval between min and max. * @param n The value to wrap. * @param min The minimum. * @param max The maximum. */ static double wrap(double n, double min, double max) { return (n >= min && n < max) ? n : (mod(n - min, max - min) + min); } /** * Returns the non-negative remainder of x / m. * @param x The operand. * @param m The modulus. */ static double mod(double x, double m) { return ((x % m) + m) % m; } }
5,043
1,006
/**************************************************************************** * mm/iob/iob.h * * 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. * ****************************************************************************/ #ifndef __MM_IOB_IOB_H #define __MM_IOB_IOB_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <debug.h> #include <nuttx/mm/iob.h> #include <nuttx/semaphore.h> #ifdef CONFIG_MM_IOB /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #if defined(CONFIG_DEBUG_FEATURES) && defined(CONFIG_IOB_DEBUG) # define ioberr _err # define iobwarn _warn # define iobinfo _info #else # define ioberr _none # define iobwarn _none # define iobinfo _none #endif /* CONFIG_DEBUG_FEATURES && CONFIG_IOB_DEBUG */ /**************************************************************************** * Public Data ****************************************************************************/ /* A list of all free, unallocated I/O buffers */ extern FAR struct iob_s *g_iob_freelist; /* A list of I/O buffers that are committed for allocation */ extern FAR struct iob_s *g_iob_committed; #if CONFIG_IOB_NCHAINS > 0 /* A list of all free, unallocated I/O buffer queue containers */ extern FAR struct iob_qentry_s *g_iob_freeqlist; /* A list of I/O buffer queue containers that are committed for allocation */ extern FAR struct iob_qentry_s *g_iob_qcommitted; #endif /* Counting semaphores that tracks the number of free IOBs/qentries */ extern sem_t g_iob_sem; /* Counts free I/O buffers */ #if CONFIG_IOB_THROTTLE > 0 extern sem_t g_throttle_sem; /* Counts available I/O buffers when throttled */ #endif #if CONFIG_IOB_NCHAINS > 0 extern sem_t g_qentry_sem; /* Counts free I/O buffer queue containers */ #endif /**************************************************************************** * Public Function Prototypes ****************************************************************************/ /**************************************************************************** * Name: iob_alloc_qentry * * Description: * Allocate an I/O buffer chain container by taking the buffer at the head * of the free list. This function is intended only for internal use by * the IOB module. * ****************************************************************************/ FAR struct iob_qentry_s *iob_alloc_qentry(void); /**************************************************************************** * Name: iob_tryalloc_qentry * * Description: * Try to allocate an I/O buffer chain container by taking the buffer at * the head of the free list without waiting for the container to become * free. This function is intended only for internal use by the IOB module. * ****************************************************************************/ FAR struct iob_qentry_s *iob_tryalloc_qentry(void); /**************************************************************************** * Name: iob_free_qentry * * Description: * Free the I/O buffer chain container by returning it to the free list. * The link to the next I/O buffer in the chain is return. * ****************************************************************************/ FAR struct iob_qentry_s *iob_free_qentry(FAR struct iob_qentry_s *iobq); /**************************************************************************** * Name: iob_notifier_signal * * Description: * An IOB has become available. Signal all threads waiting for an IOB * that an IOB is available. * * When an IOB becomes available, *all* of the waiters in this thread will * be signaled. If there are multiple waiters then only the highest * priority thread will get the IOB. Lower priority threads will need to * call iob_notifier_setup() once again. * * Input Parameters: * None. * * Returned Value: * None. * ****************************************************************************/ #ifdef CONFIG_IOB_NOTIFIER void iob_notifier_signal(void); #endif /**************************************************************************** * Name: iob_stats_onalloc * * Description: * An IOB has just been allocated for the consumer. This is a hook for the * IOB statistics to be updated when /proc/iobinfo is enabled. * * Input Parameters: * consumerid - id representing who is consuming the IOB * * Returned Value: * None. * ****************************************************************************/ #if !defined(CONFIG_DISABLE_MOUNTPOINT) && defined(CONFIG_FS_PROCFS) && \ defined(CONFIG_MM_IOB) && !defined(CONFIG_FS_PROCFS_EXCLUDE_IOBINFO) void iob_stats_onalloc(enum iob_user_e consumerid); #endif /**************************************************************************** * Name: iob_stats_onfree * * Description: * An IOB has just been freed by the producer. This is a hook for the * IOB statistics to be updated when /proc/iobinfo is enabled. * * Input Parameters: * consumerid - id representing who is consuming the IOB * * Returned Value: * None. * ****************************************************************************/ #if !defined(CONFIG_DISABLE_MOUNTPOINT) && defined(CONFIG_FS_PROCFS) && \ defined(CONFIG_MM_IOB) && !defined(CONFIG_FS_PROCFS_EXCLUDE_IOBINFO) void iob_stats_onfree(enum iob_user_e producerid); #endif #endif /* CONFIG_MM_IOB */ #endif /* __MM_IOB_IOB_H */
1,803
977
<filename>src/external/IntelRDFPMathLib20U2/LIBRARY/src/bid128_quantize.c /****************************************************************************** Copyright (c) 2007-2018, Intel Corp. All rights reserved. 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 Intel Corporation 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. ******************************************************************************/ #define BID_FUNCTION_SETS_BINARY_FLAGS #define BID_128RES #include "bid_internal.h" BID128_FUNCTION_ARG2 (bid128_quantize, x, y) BID_UINT256 CT; BID_UINT128 CX, CY, T, CX2, CR, Stemp, res, REM_H, C2N; BID_UINT64 sign_x, sign_y, remainder_h, carry, CY64, valid_x; int_float tempx; int exponent_x, exponent_y, digits_x, extra_digits, amount; int expon_diff, total_digits, bin_expon_cx, rmode, status; BID_OPT_SAVE_BINARY_FLAGS() valid_x = unpack_BID128_value (&sign_x, &exponent_x, &CX, x); // unpack arguments, check for NaN or Infinity if (!unpack_BID128_value (&sign_y, &exponent_y, &CY, y)) { // y is Inf. or NaN #ifdef BID_SET_STATUS_FLAGS if ((x.w[1] & SNAN_MASK64) == SNAN_MASK64) // y is sNaN __set_status_flags (pfpsf, BID_INVALID_EXCEPTION); #endif // test if y is NaN if ((y.w[1] & 0x7c00000000000000ull) == 0x7c00000000000000ull) { #ifdef BID_SET_STATUS_FLAGS if ((y.w[1] & 0x7e00000000000000ull) == 0x7e00000000000000ull) { // set status flags __set_status_flags (pfpsf, BID_INVALID_EXCEPTION); } #endif if ((x.w[1] & 0x7c00000000000000ull) != 0x7c00000000000000ull) { res.w[1] = CY.w[1] & QUIET_MASK64; res.w[0] = CY.w[0]; } else { res.w[1] = CX.w[1] & QUIET_MASK64; res.w[0] = CX.w[0]; } BID_RETURN (res); } // y is Infinity? if ((y.w[1] & 0x7800000000000000ull) == 0x7800000000000000ull) { // check if x is not Inf. if (((x.w[1] & 0x7c00000000000000ull) < 0x7800000000000000ull)) { // return NaN #ifdef BID_SET_STATUS_FLAGS // set status flags __set_status_flags (pfpsf, BID_INVALID_EXCEPTION); #endif res.w[1] = 0x7c00000000000000ull; res.w[0] = 0; BID_RETURN (res); } else if (((x.w[1] & 0x7c00000000000000ull) <= 0x7800000000000000ull)) { res.w[1] = CX.w[1] & QUIET_MASK64; res.w[0] = CX.w[0]; BID_RETURN (res); } } } if (!valid_x) { // test if x is NaN or Inf if ((x.w[1] & 0x7c00000000000000ull) == 0x7800000000000000ull) { #ifdef BID_SET_STATUS_FLAGS // set status flags __set_status_flags (pfpsf, BID_INVALID_EXCEPTION); #endif res.w[1] = 0x7c00000000000000ull; res.w[0] = 0; BID_RETURN (res); } else if ((x.w[1] & 0x7c00000000000000ull) == 0x7c00000000000000ull) { if ((x.w[1] & 0x7e00000000000000ull) == 0x7e00000000000000ull) { #ifdef BID_SET_STATUS_FLAGS // set status flags __set_status_flags (pfpsf, BID_INVALID_EXCEPTION); #endif } res.w[1] = CX.w[1] & QUIET_MASK64; res.w[0] = CX.w[0]; BID_RETURN (res); } if (!CX.w[1] && !CX.w[0]) { bid_get_BID128_very_fast (&res, sign_x, exponent_y, CX); BID_RETURN (res); } } // get number of decimal digits in coefficient_x if (CX.w[1]) { tempx.d = (float) CX.w[1]; bin_expon_cx = ((tempx.i >> 23) & 0xff) - 0x7f + 64; } else { tempx.d = (float) CX.w[0]; bin_expon_cx = ((tempx.i >> 23) & 0xff) - 0x7f; } digits_x = bid_estimate_decimal_digits[bin_expon_cx]; if (CX.w[1] > bid_power10_table_128[digits_x].w[1] || (CX.w[1] == bid_power10_table_128[digits_x].w[1] && CX.w[0] >= bid_power10_table_128[digits_x].w[0])) digits_x++; expon_diff = exponent_x - exponent_y; total_digits = digits_x + expon_diff; if ((BID_UINT32) total_digits <= 34) { if (expon_diff >= 0) { T = bid_power10_table_128[expon_diff]; __mul_128x128_low (CX2, T, CX); bid_get_BID128_very_fast (&res, sign_x, exponent_y, CX2); BID_RETURN (res); } #ifndef IEEE_ROUND_NEAREST_TIES_AWAY #ifndef IEEE_ROUND_NEAREST rmode = rnd_mode; if (sign_x && (unsigned) (rmode - 1) < 2) rmode = 3 - rmode; #else rmode = 0; #endif #else rmode = 0; #endif // must round off -expon_diff digits extra_digits = -expon_diff; __add_128_128 (CX, CX, bid_round_const_table_128[rmode][extra_digits]); // get P*(2^M[extra_digits])/10^extra_digits __mul_128x128_to_256 (CT, CX, bid_reciprocals10_128[extra_digits]); // now get P/10^extra_digits: shift C64 right by M[extra_digits]-128 amount = bid_recip_scale[extra_digits]; CX2.w[0] = CT.w[2]; CX2.w[1] = CT.w[3]; if (amount >= 64) { CR.w[1] = 0; CR.w[0] = CX2.w[1] >> (amount - 64); } else { __shr_128 (CR, CX2, amount); } #ifndef IEEE_ROUND_NEAREST_TIES_AWAY #ifndef IEEE_ROUND_NEAREST if (rnd_mode == 0) #endif if (CR.w[0] & 1) { // check whether fractional part of initial_P/10^extra_digits is // exactly .5 this is the same as fractional part of // (initial_P + 0.5*10^extra_digits)/10^extra_digits is exactly zero // get remainder if (amount >= 64) { remainder_h = CX2.w[0] | (CX2.w[1] << (128 - amount)); } else remainder_h = CX2.w[0] << (64 - amount); // test whether fractional part is 0 if (!remainder_h && (CT.w[1] < bid_reciprocals10_128[extra_digits].w[1] || (CT.w[1] == bid_reciprocals10_128[extra_digits].w[1] && CT.w[0] < bid_reciprocals10_128[extra_digits].w[0]))) { CR.w[0]--; } } #endif #ifdef BID_SET_STATUS_FLAGS status = BID_INEXACT_EXCEPTION; // get remainder if (amount >= 64) { REM_H.w[1] = (CX2.w[1] << (128 - amount)); REM_H.w[0] = CX2.w[0]; } else { REM_H.w[1] = CX2.w[0] << (64 - amount); REM_H.w[0] = 0; } switch (rmode) { case BID_ROUNDING_TO_NEAREST: case BID_ROUNDING_TIES_AWAY: // test whether fractional part is 0 if (REM_H.w[1] == 0x8000000000000000ull && !REM_H.w[0] && (CT.w[1] < bid_reciprocals10_128[extra_digits].w[1] || (CT.w[1] == bid_reciprocals10_128[extra_digits].w[1] && CT.w[0] < bid_reciprocals10_128[extra_digits].w[0]))) status = BID_EXACT_STATUS; break; case BID_ROUNDING_DOWN: case BID_ROUNDING_TO_ZERO: if (!(REM_H.w[1] | REM_H.w[0]) && (CT.w[1] < bid_reciprocals10_128[extra_digits].w[1] || (CT.w[1] == bid_reciprocals10_128[extra_digits].w[1] && CT.w[0] < bid_reciprocals10_128[extra_digits].w[0]))) status = BID_EXACT_STATUS; break; default: // round up __add_carry_out (Stemp.w[0], CY64, CT.w[0], bid_reciprocals10_128[extra_digits].w[0]); __add_carry_in_out (Stemp.w[1], carry, CT.w[1], bid_reciprocals10_128[extra_digits].w[1], CY64); if (amount < 64) { C2N.w[1] = 0; C2N.w[0] = ((BID_UINT64) 1) << amount; REM_H.w[0] = REM_H.w[1] >> (64 - amount); REM_H.w[1] = 0; } else { C2N.w[1] = ((BID_UINT64) 1) << (amount - 64); C2N.w[0] = 0; REM_H.w[1] >>= (128 - amount); } REM_H.w[0] += carry; if (REM_H.w[0] < carry) REM_H.w[1]++; if (__unsigned_compare_ge_128 (REM_H, C2N)) status = BID_EXACT_STATUS; } __set_status_flags (pfpsf, status); #endif bid_get_BID128_very_fast (&res, sign_x, exponent_y, CR); BID_RETURN (res); } if (total_digits < 0) { CR.w[1] = CR.w[0] = 0; #ifndef IEEE_ROUND_NEAREST_TIES_AWAY #ifndef IEEE_ROUND_NEAREST rmode = rnd_mode; if (sign_x && (unsigned) (rmode - 1) < 2) rmode = 3 - rmode; if (rmode == BID_ROUNDING_UP) CR.w[0] = 1; #endif #endif #ifdef BID_SET_STATUS_FLAGS __set_status_flags (pfpsf, BID_INEXACT_EXCEPTION); #endif bid_get_BID128_very_fast (&res, sign_x, exponent_y, CR); BID_RETURN (res); } // else more than 34 digits in coefficient #ifdef BID_SET_STATUS_FLAGS __set_status_flags (pfpsf, BID_INVALID_EXCEPTION); #endif res.w[1] = 0x7c00000000000000ull; res.w[0] = 0; BID_RETURN (res); }
4,490
332
<reponame>BioQwer/vk-java-sdk package com.vk.api.sdk.queries; /** * Created by <NAME> on 22.09.16. */ public enum ReportReason implements EnumParam { SPAM("0"), CHILD_PORN("1"), EXTREMISM("2"), VIOLINCE("3"), DRUGS("4"), ADULT_MATERIALS("5"), INSULT("6"); private final String value; ReportReason(String value) { this.value = value; } @Override public String getValue() { return value; } }
209
416
package org.simpleflatmapper.util; import java.nio.ByteBuffer; import java.util.UUID; public class UUIDHelper { public static byte[] toBytes(UUID uuid) { byte[] bytes = new byte[16]; ByteBuffer .wrap(bytes) .putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); return bytes; } public static UUID fromBytes(byte[] bytes) { final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); return new UUID(byteBuffer.getLong(), byteBuffer.getLong()); } }
250
1,056
<filename>ide/schema2beans/src/org/netbeans/modules/schema2beans/Version.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.netbeans.modules.schema2beans; public class Version implements java.io.Serializable { public final static int MAJVER = 5; public final static int MINVER = 0; public final static int PTCVER = 0; private int major; private int minor; private int patch; public Version(int major, int minor, int patch) { this.major = major; this.minor = minor; this.patch = patch; } public int getMajor() { return this.major; } public int getMinor() { return this.minor; } public int getPatch() { return this.patch; } /** * Returns the current version of the runtime system. */ public static String getVersion() { return "version " + MAJVER + "." + MINVER + "." + PTCVER; } }
502
460
/* * Copyright (c) Microsoft Corporation. * * 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.microsoft.playwright; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * This test simply makes sure that all 4 main interfaces implement AutoCloseable. If it compiles, then it passes. */ public class TestAutoClose { @Test void shouldAllowUsingTryWithResources() { try (Playwright playwright = Playwright.create(); Browser browser = Utils.getBrowserTypeFromEnv(playwright).launch(); BrowserContext context = browser.newContext(); Page page = context.newPage()) { assertEquals(2021, page.evaluate("() => 2021")); } } }
362
5,422
// -*- mode: objective-c -*- @import Cocoa; #import "FingerCount.h" #import "FingerStatusEntry.h" #import "MultitouchPrivate.h" @interface FingerStatusManager : NSObject + (instancetype)sharedFingerStatusManager; - (void)update:(MTDeviceRef)device data:(Finger*)data fingers:(int)fingers timestamp:(double)timestamp frame:(int)frame; - (NSArray<FingerStatusEntry*>*)copyEntries; - (FingerCount*)createFingerCount; @end
180
1,150
# -*- coding: utf-8 -*- from wechat_sdk.utils import to_binary, to_text class PKCS7Encoder(object): """提供基于PKCS7算法的加解密接口""" block_size = 32 @classmethod def encode(cls, text): """ 对需要加密的明文进行填充补位 @param text: 需要进行填充补位操作的明文 @return: 补齐明文字符串 """ text_length = len(text) # 计算需要填充的位数 amount_to_pad = cls.block_size - (text_length % cls.block_size) if amount_to_pad == 0: amount_to_pad = cls.block_size # 获得补位所用的字符 pad = to_binary(chr(amount_to_pad)) return text + pad * amount_to_pad @classmethod def decode(cls, decrypted): """ 删除解密后明文的补位字符 @param decrypted: 解密后的明文 @return: 删除补位字符后的明文 """ pad = ord(decrypted[-1]) if pad < 1 or pad > 32: pad = 0 return decrypted[:-pad]
617
1,886
/* Module object implementation */ #include "Python.h" #include "pycore_pystate.h" #include "structmember.h" #include "frameobject.h" PyAPI_DATA(int) Py_LazyImportsAllFlag; static Py_ssize_t max_module_number; static PyMemberDef module_members[] = { {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY}, {0} }; static PyObject *deferred_name(PyDeferredObject *m); /* Helper for sanity check for traverse not handling m_state == NULL * Issue #32374 */ #ifdef Py_DEBUG static int bad_traverse_test(PyObject *self, void *arg) { assert(self != NULL); return 0; } #endif PyTypeObject PyModuleDef_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "moduledef", /* tp_name */ sizeof(struct PyModuleDef), /* tp_basicsize */ 0, /* tp_itemsize */ }; PyObject* PyModuleDef_Init(struct PyModuleDef* def) { if (PyType_Ready(&PyModuleDef_Type) < 0) return NULL; if (def->m_base.m_index == 0) { max_module_number++; Py_SET_REFCNT(def, 1); Py_TYPE(def) = &PyModuleDef_Type; def->m_base.m_index = max_module_number; } return (PyObject*)def; } static int module_init_dict(PyModuleObject *mod, PyObject *md_dict, PyObject *name, PyObject *doc) { _Py_IDENTIFIER(__name__); _Py_IDENTIFIER(__doc__); _Py_IDENTIFIER(__package__); _Py_IDENTIFIER(__loader__); _Py_IDENTIFIER(__spec__); if (md_dict == NULL) return -1; if (doc == NULL) doc = Py_None; if (_PyDict_SetItemId(md_dict, &PyId___name__, name) != 0) return -1; if (_PyDict_SetItemId(md_dict, &PyId___doc__, doc) != 0) return -1; if (_PyDict_SetItemId(md_dict, &PyId___package__, Py_None) != 0) return -1; if (_PyDict_SetItemId(md_dict, &PyId___loader__, Py_None) != 0) return -1; if (_PyDict_SetItemId(md_dict, &PyId___spec__, Py_None) != 0) return -1; if (PyUnicode_CheckExact(name)) { Py_INCREF(name); Py_XSETREF(mod->md_name, name); } return 0; } PyObject * PyModule_NewObject(PyObject *name) { PyModuleObject *m; m = PyObject_GC_New(PyModuleObject, &PyModule_Type); if (m == NULL) return NULL; m->md_def = NULL; m->md_state = NULL; m->md_weaklist = NULL; m->md_name = NULL; m->md_dict = PyDict_New(); if (module_init_dict(m, m->md_dict, name, NULL) != 0) goto fail; PyObject_GC_Track(m); return (PyObject *)m; fail: Py_DECREF(m); return NULL; } PyObject * PyModule_New(const char *name) { PyObject *nameobj, *module; nameobj = PyUnicode_FromString(name); if (nameobj == NULL) return NULL; module = PyModule_NewObject(nameobj); Py_DECREF(nameobj); return module; } /* Check API/ABI version * Issues a warning on mismatch, which is usually not fatal. * Returns 0 if an exception is raised. */ static int check_api_version(const char *name, int module_api_version) { if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) { int err; err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "Python C API version mismatch for module %.100s: " "This Python has API version %d, module %.100s has version %d.", name, PYTHON_API_VERSION, name, module_api_version); if (err) return 0; } return 1; } static int _add_methods_to_object(PyObject *module, PyObject *name, PyMethodDef *functions) { PyObject *func; PyMethodDef *fdef; for (fdef = functions; fdef->ml_name != NULL; fdef++) { if ((fdef->ml_flags & METH_CLASS) || (fdef->ml_flags & METH_STATIC)) { PyErr_SetString(PyExc_ValueError, "module functions cannot set" " METH_CLASS or METH_STATIC"); return -1; } func = PyCFunction_NewEx(fdef, (PyObject*)module, name); if (func == NULL) { return -1; } if (PyStrictModule_Check(module)) { PyObject *globals = ((PyStrictModuleObject *)module)->globals; if (PyDict_SetItemString(globals, fdef->ml_name, func) != 0) { Py_DECREF(func); return -1; } } else if (PyObject_SetAttrString(module, fdef->ml_name, func) != 0) { Py_DECREF(func); return -1; } Py_DECREF(func); } return 0; } PyObject * PyModule_Create2(struct PyModuleDef* module, int module_api_version) { if (!_PyImport_IsInitialized(_PyInterpreterState_Get())) Py_FatalError("Python import machinery not initialized"); return _PyModule_CreateInitialized(module, module_api_version); } PyObject * _PyModule_CreateInitialized(struct PyModuleDef* module, int module_api_version) { const char* name; PyModuleObject *m; if (!PyModuleDef_Init(module)) return NULL; name = module->m_name; if (!check_api_version(name, module_api_version)) { return NULL; } if (module->m_slots) { PyErr_Format( PyExc_SystemError, "module %s: PyModule_Create is incompatible with m_slots", name); return NULL; } /* Make sure name is fully qualified. This is a bit of a hack: when the shared library is loaded, the module name is "package.module", but the module calls PyModule_Create*() with just "module" for the name. The shared library loader squirrels away the true name of the module in _Py_PackageContext, and PyModule_Create*() will substitute this (if the name actually matches). */ if (_Py_PackageContext != NULL) { const char *p = strrchr(_Py_PackageContext, '.'); if (p != NULL && strcmp(module->m_name, p+1) == 0) { name = _Py_PackageContext; _Py_PackageContext = NULL; } } if ((m = (PyModuleObject*)PyModule_New(name)) == NULL) return NULL; if (module->m_size > 0) { m->md_state = PyMem_MALLOC(module->m_size); if (!m->md_state) { PyErr_NoMemory(); Py_DECREF(m); return NULL; } memset(m->md_state, 0, module->m_size); } if (module->m_methods != NULL) { if (PyModule_AddFunctions((PyObject *) m, module->m_methods) != 0) { Py_DECREF(m); return NULL; } } if (module->m_doc != NULL) { if (PyModule_SetDocString((PyObject *) m, module->m_doc) != 0) { Py_DECREF(m); return NULL; } } m->md_def = module; return (PyObject*)m; } PyObject * PyModule_FromDefAndSpec2(struct PyModuleDef* def, PyObject *spec, int module_api_version) { PyModuleDef_Slot* cur_slot; PyObject *(*create)(PyObject *, PyModuleDef*) = NULL; PyObject *nameobj; PyObject *m = NULL; int has_execution_slots = 0; const char *name; int ret; PyModuleDef_Init(def); nameobj = PyObject_GetAttrString(spec, "name"); if (nameobj == NULL) { return NULL; } name = PyUnicode_AsUTF8(nameobj); if (name == NULL) { goto error; } if (!check_api_version(name, module_api_version)) { goto error; } if (def->m_size < 0) { PyErr_Format( PyExc_SystemError, "module %s: m_size may not be negative for multi-phase initialization", name); goto error; } for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) { if (cur_slot->slot == Py_mod_create) { if (create) { PyErr_Format( PyExc_SystemError, "module %s has multiple create slots", name); goto error; } create = cur_slot->value; } else if (cur_slot->slot < 0 || cur_slot->slot > _Py_mod_LAST_SLOT) { PyErr_Format( PyExc_SystemError, "module %s uses unknown slot ID %i", name, cur_slot->slot); goto error; } else { has_execution_slots = 1; } } if (create) { m = create(spec, def); if (m == NULL) { if (!PyErr_Occurred()) { PyErr_Format( PyExc_SystemError, "creation of module %s failed without setting an exception", name); } goto error; } else { if (PyErr_Occurred()) { PyErr_Format(PyExc_SystemError, "creation of module %s raised unreported exception", name); goto error; } } } else { m = PyModule_NewObject(nameobj); if (m == NULL) { goto error; } } if (PyModule_Check(m)) { ((PyModuleObject*)m)->md_state = NULL; ((PyModuleObject*)m)->md_def = def; } else { if (def->m_size > 0 || def->m_traverse || def->m_clear || def->m_free) { PyErr_Format( PyExc_SystemError, "module %s is not a module object, but requests module state", name); goto error; } if (has_execution_slots) { PyErr_Format( PyExc_SystemError, "module %s specifies execution slots, but did not create " "a ModuleType instance", name); goto error; } } if (def->m_methods != NULL) { ret = _add_methods_to_object(m, nameobj, def->m_methods); if (ret != 0) { goto error; } } if (def->m_doc != NULL) { ret = PyModule_SetDocString(m, def->m_doc); if (ret != 0) { goto error; } } /* Sanity check for traverse not handling m_state == NULL * This doesn't catch all possible cases, but in many cases it should * make many cases of invalid code crash or raise Valgrind issues * sooner than they would otherwise. * Issue #32374 */ #ifdef Py_DEBUG if (def->m_traverse != NULL) { def->m_traverse(m, bad_traverse_test, NULL); } #endif Py_DECREF(nameobj); return m; error: Py_DECREF(nameobj); Py_XDECREF(m); return NULL; } int PyModule_ExecDef(PyObject *module, PyModuleDef *def) { PyModuleDef_Slot *cur_slot; const char *name; int ret; name = PyModule_GetName(module); if (name == NULL) { return -1; } if (def->m_size >= 0) { PyModuleObject *md = (PyModuleObject*)module; if (md->md_state == NULL) { /* Always set a state pointer; this serves as a marker to skip * multiple initialization (importlib.reload() is no-op) */ md->md_state = PyMem_MALLOC(def->m_size); if (!md->md_state) { PyErr_NoMemory(); return -1; } memset(md->md_state, 0, def->m_size); } } if (def->m_slots == NULL) { return 0; } for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) { switch (cur_slot->slot) { case Py_mod_create: /* handled in PyModule_FromDefAndSpec2 */ break; case Py_mod_exec: ret = ((int (*)(PyObject *))cur_slot->value)(module); if (ret != 0) { if (!PyErr_Occurred()) { PyErr_Format( PyExc_SystemError, "execution of module %s failed without setting an exception", name); } return -1; } if (PyErr_Occurred()) { PyErr_Format( PyExc_SystemError, "execution of module %s raised unreported exception", name); return -1; } break; default: PyErr_Format( PyExc_SystemError, "module %s initialized with unknown slot %i", name, cur_slot->slot); return -1; } } return 0; } int PyModule_AddFunctions(PyObject *m, PyMethodDef *functions) { int res; PyObject *name = PyModule_GetNameObject(m); if (name == NULL) { return -1; } res = _add_methods_to_object(m, name, functions); Py_DECREF(name); return res; } int PyModule_SetDocString(PyObject *m, const char *doc) { PyObject *v; _Py_IDENTIFIER(__doc__); v = PyUnicode_FromString(doc); if (v == NULL) { Py_DECREF(v); return -1; } else if (PyStrictModule_Check(m)) { PyObject *globals = ((PyStrictModuleObject*)m)->globals; if (_PyDict_SetItemId(globals, &PyId___doc__, v) != 0) { Py_DECREF(v); return -1; } } else if(_PyObject_SetAttrId(m, &PyId___doc__, v) != 0) { Py_XDECREF(v); return -1; } Py_DECREF(v); return 0; } PyObject * PyModule_GetDict(PyObject *m) { PyObject *d; if (!PyModule_Check(m)) { PyErr_BadInternalCall(); return NULL; } d = ((PyModuleObject *)m) -> md_dict; assert(d != NULL); return d; } PyObject* PyModule_GetNameObject(PyObject *m) { _Py_IDENTIFIER(__name__); PyObject *d; PyObject *name; if (!PyModule_Check(m)) { PyErr_BadArgument(); return NULL; } d = ((PyModuleObject *)m)->md_dict; if (d == NULL || (name = _PyDict_GetItemId(d, &PyId___name__)) == NULL || !PyUnicode_Check(name)) { PyErr_SetString(PyExc_SystemError, "nameless module"); return NULL; } Py_INCREF(name); return name; } const char * PyModule_GetName(PyObject *m) { PyObject *name = PyModule_GetNameObject(m); if (name == NULL) return NULL; Py_DECREF(name); /* module dict has still a reference */ return PyUnicode_AsUTF8(name); } PyObject* PyModule_GetFilenameObject(PyObject *m) { _Py_IDENTIFIER(__file__); PyObject *d; PyObject *fileobj; if (!PyModule_Check(m)) { PyErr_BadArgument(); return NULL; } d = ((PyModuleObject *)m)->md_dict; if (d == NULL || (fileobj = _PyDict_GetItemId(d, &PyId___file__)) == NULL || !PyUnicode_Check(fileobj)) { PyErr_SetString(PyExc_SystemError, "module filename missing"); return NULL; } Py_INCREF(fileobj); return fileobj; } const char * PyModule_GetFilename(PyObject *m) { PyObject *fileobj; const char *utf8; fileobj = PyModule_GetFilenameObject(m); if (fileobj == NULL) return NULL; utf8 = PyUnicode_AsUTF8(fileobj); Py_DECREF(fileobj); /* module dict has still a reference */ return utf8; } PyModuleDef* PyModule_GetDef(PyObject* m) { if (!PyModule_Check(m)) { PyErr_BadArgument(); return NULL; } return ((PyModuleObject *)m)->md_def; } void* PyModule_GetState(PyObject* m) { if (!PyModule_Check(m)) { PyErr_BadArgument(); return NULL; } return ((PyModuleObject *)m)->md_state; } void _PyModule_Clear(PyObject *m) { PyObject *d = ((PyModuleObject *)m)->md_dict; if (d != NULL) _PyModule_ClearDict(d); } void _PyModule_ClearDict(PyObject *d) { /* To make the execution order of destructors for global objects a bit more predictable, we first zap all objects whose name starts with a single underscore, before we clear the entire dictionary. We zap them by replacing them with None, rather than deleting them from the dictionary, to avoid rehashing the dictionary (to some extent). */ Py_ssize_t pos; PyObject *key, *value; int verbose = _PyInterpreterState_GET_UNSAFE()->config.verbose; _PyDict_UnsetHasDeferredObjects(d); /* First, clear only names starting with a single underscore */ pos = 0; while (PyDict_Next(d, &pos, &key, &value)) { if (value != Py_None && PyUnicode_Check(key)) { if (PyUnicode_READ_CHAR(key, 0) == '_' && PyUnicode_READ_CHAR(key, 1) != '_') { if (verbose > 1) { const char *s = PyUnicode_AsUTF8(key); if (s != NULL) PySys_WriteStderr("# clear[1] %s\n", s); else PyErr_Clear(); } if (PyDict_SetItem(d, key, Py_None) != 0) { PyErr_WriteUnraisable(NULL); } } } } /* Next, clear all names except for __builtins__ */ pos = 0; while (PyDict_Next(d, &pos, &key, &value)) { if (value != Py_None && PyUnicode_Check(key)) { if (PyUnicode_READ_CHAR(key, 0) != '_' || !_PyUnicode_EqualToASCIIString(key, "__builtins__")) { if (verbose > 1) { const char *s = PyUnicode_AsUTF8(key); if (s != NULL) PySys_WriteStderr("# clear[2] %s\n", s); else PyErr_Clear(); } if (PyDict_SetItem(d, key, Py_None) != 0) { PyErr_WriteUnraisable(NULL); } } } } /* Note: we leave __builtins__ in place, so that destructors of non-global objects defined in this module can still use builtins, in particularly 'None'. */ } /*[clinic input] class module "PyModuleObject *" "&PyModule_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3e35d4f708ecb6af]*/ #include "clinic/moduleobject.c.h" /* Methods */ /*[clinic input] module.__init__ name: unicode doc: object = None Create a module object. The name must be a string; the optional doc argument can have any type. [clinic start generated code]*/ static int module___init___impl(PyModuleObject *self, PyObject *name, PyObject *doc) /*[clinic end generated code: output=e7e721c26ce7aad7 input=57f9e177401e5e1e]*/ { PyObject *dict = self->md_dict; if (dict == NULL) { dict = PyDict_New(); if (dict == NULL) return -1; self->md_dict = dict; } if (module_init_dict(self, dict, name, doc) < 0) return -1; return 0; } static void module_dealloc(PyModuleObject *m) { int verbose = _PyInterpreterState_GET_UNSAFE()->config.verbose; PyObject_GC_UnTrack(m); if (verbose && m->md_name) { PySys_FormatStderr("# destroy %S\n", m->md_name); } if (m->md_weaklist != NULL) PyObject_ClearWeakRefs((PyObject *) m); if (m->md_def && m->md_def->m_free) m->md_def->m_free(m); Py_XDECREF(m->md_dict); Py_XDECREF(m->md_name); if (m->md_state != NULL) PyMem_FREE(m->md_state); Py_TYPE(m)->tp_free((PyObject *)m); } static PyObject * module_repr(PyModuleObject *m) { PyInterpreterState *interp = _PyInterpreterState_Get(); return PyObject_CallMethod(interp->importlib, "_module_repr", "O", m); } /* Check if the "_initializing" attribute of the module spec is set to true. Clear the exception and return 0 if spec is NULL. */ int _PyModuleSpec_IsInitializing(PyObject *spec) { if (spec != NULL) { _Py_IDENTIFIER(_initializing); PyObject *value = _PyObject_GetAttrId(spec, &PyId__initializing); if (value != NULL) { int initializing = PyObject_IsTrue(value); Py_DECREF(value); if (initializing >= 0) { return initializing; } } } PyErr_Clear(); return 0; } int PyDeferred_Match(PyDeferredObject *deferred, PyObject *mod_dict, PyObject *name) { _Py_IDENTIFIER(__name__); PyObject *mod_name = _PyDict_GetItemId(mod_dict, &PyId___name__); if (mod_name == NULL || !PyUnicode_Check(mod_name)) { return 0; } PyObject *fqn = PyUnicode_FromFormat("%U.%U", mod_name, name); PyObject *deferred_fqn = deferred_name(deferred); int match = PyUnicode_Tailmatch(deferred_fqn, fqn, 0, PyUnicode_GET_LENGTH(fqn), -1); Py_DECREF(fqn); Py_DECREF(deferred_fqn); return match; } static PyObject * module_lookupattro(PyModuleObject *m, PyObject *name, int suppress) { PyObject *attr, *mod_name, *getattr; if (Py_TYPE(m) != &PyModule_Type || m->md_dict == NULL || !PyUnicode_Check(name)) { /* Fall back to default behavior in odd ball cases */ attr = _PyObject_GenericGetAttrWithDict((PyObject *)m, name, NULL, 1); } else if (PyUnicode_GET_LENGTH(name) == 8 && PyUnicode_READ_CHAR(name, 0) == '_' && _PyUnicode_EqualToASCIIString(name, "__dict__")) { /* This is a data descriptor, it always takes precedence over * an entry in __dict__ */ Py_INCREF(m->md_dict); return m->md_dict; } else if (PyUnicode_GET_LENGTH(name) == 9 && PyUnicode_READ_CHAR(name, 0) == '_' && _PyUnicode_EqualToASCIIString(name, "__class__")) { Py_INCREF(&PyModule_Type); return (PyObject *) &PyModule_Type; } else { /* Otherwise we have no other data descriptors, just look in the * dictionary and elide the _PyType_Lookup */ attr = _PyDict_GetAttrItem_Unicode(m->md_dict, name); if (attr != NULL) { Py_INCREF(attr); return attr; } else if (PyErr_Occurred()) { if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } return NULL; } /* see if we're accessing a descriptor defined on the module type */ attr = _PyType_Lookup(&PyModule_Type, name); if (attr != NULL) { assert(!PyDescr_IsData( attr)); /* it better not be a data descriptor */ descrgetfunc f = attr->ob_type->tp_descr_get; if (f != NULL) { attr = f(attr, (PyObject *)m, (PyObject *)&PyModule_Type); if (attr == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } } else { Py_INCREF(attr); /* got a borrowed ref */ } } } if (attr) { return attr; } if (PyErr_Occurred()) { if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } return NULL; } if (m->md_dict) { _Py_IDENTIFIER(__getattr__); getattr = _PyDict_GetItemId(m->md_dict, &PyId___getattr__); if (getattr) { PyObject* stack[1] = {name}; PyObject *res = _PyObject_FastCall(getattr, stack, 1); if (res == NULL && suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } return res; } _Py_IDENTIFIER(__name__); mod_name = _PyDict_GetItemId(m->md_dict, &PyId___name__); if (mod_name && PyUnicode_Check(mod_name)) { _Py_IDENTIFIER(__spec__); Py_INCREF(mod_name); PyObject *spec = _PyDict_GetItemId(m->md_dict, &PyId___spec__); Py_XINCREF(spec); if (!suppress) { if (_PyModuleSpec_IsInitializing(spec)) { PyErr_Format(PyExc_AttributeError, "partially initialized " "module '%U' has no attribute '%U' " "(most likely due to a circular import)", mod_name, name); } else { PyErr_Format(PyExc_AttributeError, "module '%U' has no attribute '%U'", mod_name, name); } } Py_XDECREF(spec); Py_DECREF(mod_name); return NULL; } } if (!suppress) { PyErr_Format( PyExc_AttributeError, "module has no attribute '%U'", name); } return NULL; } static PyObject * module_getattro(PyModuleObject *m, PyObject *name) { return module_lookupattro(m, name, 0); } static int module_traverse(PyModuleObject *m, visitproc visit, void *arg) { if (m->md_def && m->md_def->m_traverse) { int res = m->md_def->m_traverse((PyObject*)m, visit, arg); if (res) return res; } Py_VISIT(m->md_dict); return 0; } static int module_clear(PyModuleObject *m) { if (m->md_def && m->md_def->m_clear) { int res = m->md_def->m_clear((PyObject*)m); if (res) return res; } Py_CLEAR(m->md_dict); return 0; } static PyObject * module_dir(PyObject *self, PyObject *args) { _Py_IDENTIFIER(__dict__); _Py_IDENTIFIER(__dir__); PyObject *result = NULL; PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__); if (dict != NULL) { if (PyDict_Check(dict)) { PyObject *dirfunc = _PyDict_GetItemIdWithError(dict, &PyId___dir__); if (dirfunc) { result = _PyObject_CallNoArg(dirfunc); } else if (!PyErr_Occurred()) { result = PyDict_Keys(dict); } } else { const char *name = PyModule_GetName(self); if (name) PyErr_Format(PyExc_TypeError, "%.200s.__dict__ is not a dictionary", name); } } Py_XDECREF(dict); return result; } static PyMethodDef module_methods[] = { {"__dir__", module_dir, METH_NOARGS, PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")}, {0} }; PyTypeObject PyModule_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "module", /* tp_name */ sizeof(PyModuleObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)module_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ (reprfunc)module_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ (getattrofunc)module_getattro, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ module___init____doc__, /* tp_doc */ (traverseproc)module_traverse, /* tp_traverse */ (inquiry)module_clear, /* tp_clear */ 0, /* tp_richcompare */ offsetof(PyModuleObject, md_weaklist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ module_methods, /* tp_methods */ module_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(PyModuleObject, md_dict), /* tp_dictoffset */ module___init__, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; PyObject * _PyModule_LookupAttr(PyObject *mod, PyObject *name) { return module_lookupattro((PyModuleObject *)mod, name, 1); } static int strictmodule_init(PyStrictModuleObject *self, PyObject *args, PyObject *kwds) { PyObject* d; PyObject* enable_patching; static char *kwlist[] = {"d", "enable_patching", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO", kwlist, &d, &enable_patching)){ return -1; } if (d == NULL || !PyDict_CheckExact(d)) { return -1; } if (enable_patching == NULL) { return -1; } return 0; } PyObject * PyStrictModule_New(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyStrictModuleObject *self; PyObject* d = NULL; PyObject* enable_patching = NULL; static char *kwlist[] = {"d", "enable_patching", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwlist, &d, &enable_patching)){ return NULL; } if (d != NULL && !PyDict_CheckExact(d)) { PyErr_SetString(PyExc_TypeError, "StrictModule.__new__ expected dict for 1st argument"); return NULL; } if (enable_patching != NULL && (enable_patching != Py_True && enable_patching != Py_False)) { PyErr_SetString(PyExc_TypeError, "StrictModule.__new__ expected bool for 2nd argument"); return NULL; } self = (PyStrictModuleObject *)type->tp_alloc(type, 0); if (self == NULL) { return NULL; } self->globals = d; Py_XINCREF(d); if (enable_patching == Py_True) { self->global_setter = d; Py_XINCREF(d); } return (PyObject *)self; } static void strictmodule_dealloc(PyStrictModuleObject *m) { Py_XDECREF(m->globals); Py_XDECREF(m->global_setter); module_dealloc((PyModuleObject *)m); } static int strictmodule_traverse(PyStrictModuleObject *m, visitproc visit, void *arg) { Py_VISIT(m->globals); Py_VISIT(m->global_setter); return 0; } static int strictmodule_clear(PyStrictModuleObject *m) { Py_CLEAR(m->globals); Py_CLEAR(m->global_setter); return 0; } int strictmodule_is_unassigned(PyObject *dict, PyObject *name) { if (!PyUnicode_Check(name)) { // somehow name is not unicode return 0; } else { PyObject *assigned_name = PyUnicode_FromFormat("<assigned:%U>", name); if (assigned_name == NULL) { return -1; } PyObject *assigned_status = _PyDict_GetAttrItem_Unicode(dict, assigned_name); Py_DECREF(assigned_name); if (assigned_status == Py_False) { // name has a corresponding <assigned:name> that's False return 1; } return 0; } } static PyObject * strict_module_dict_get(PyObject *self, void *closure) { PyStrictModuleObject *m = (PyStrictModuleObject *)self; if (m->globals == NULL) { // module is uninitialized, return None Py_RETURN_NONE; } assert(PyDict_Check(m->globals)); PyObject *dict = PyDict_New(); if (dict == NULL) { goto error; } Py_ssize_t i = 0; PyObject *key, *value; while (PyDict_NextUnresolved(m->globals, &i, &key, &value)){ if (key == NULL || value == NULL) { goto error; } if (PyUnicode_Check(key)) { PyObject * angle = PyUnicode_FromString("<"); if (angle == NULL) { goto error; } Py_ssize_t angle_pos = PyUnicode_Find(key, angle, 0, PyUnicode_GET_LENGTH(key), 1); Py_DECREF(angle); if (angle_pos == -2) { goto error; } if (angle_pos != 0) { // name does not start with <, report in __dict__ int unassigned = strictmodule_is_unassigned(m->globals, key); if (unassigned < 0) { goto error; } else if (!unassigned) { const char* key_string = PyUnicode_AsUTF8(key); if (key_string == NULL || PyDict_SetItemString(dict, key_string, value) < 0) { goto error; } } } } else { if (PyDict_SetItem(dict, key, value) < 0) { goto error; } } } if (_PyDict_HasDeferredObjects(m->globals)) { _PyDict_SetHasDeferredObjects(dict); } return dict; error: Py_XDECREF(dict); return NULL; } static PyObject * PyStrictModule_GetNameObject(PyStrictModuleObject *self) { PyStrictModuleObject *m = (PyStrictModuleObject *)self; _Py_IDENTIFIER(__name__); PyObject * name; if (m->globals == NULL || (name = _PyDict_GetItemId(m->globals, &PyId___name__)) == NULL || !PyUnicode_Check(name)) { PyErr_SetString(PyExc_SystemError, "nameless module"); return NULL; } Py_INCREF(name); return name; } static PyObject * strict_module_name_get(PyObject *self, void *closure) { PyObject *name = PyStrictModule_GetNameObject((PyStrictModuleObject*) self); if (name == NULL) { PyErr_Clear(); PyErr_SetString(PyExc_AttributeError, "strict module has no attribute __name__"); return NULL; } // already incref return name; } static PyObject * strict_module_patch_enabled(PyObject *self, void *closure) { if (((PyStrictModuleObject *) self) -> global_setter != NULL) { return Py_True; } return Py_False; } static PyObject * strictmodule_repr(PyStrictModuleObject *m) { PyObject *repr_obj; if (!PyStrictModule_Check(m)) { PyErr_BadArgument(); return NULL; } PyObject * name = PyStrictModule_GetNameObject(m); if (name == NULL) { PyErr_Clear(); name = PyUnicode_FromString("?"); if (name == NULL) { return NULL; } } _Py_IDENTIFIER(__file__); PyObject *d; PyObject *filename; d = m->globals; if (d == NULL || (filename = _PyDict_GetItemId(d, &PyId___file__)) == NULL || !PyUnicode_Check(filename)) { repr_obj = PyUnicode_FromFormat("<module '%U'>", name); } else { repr_obj = PyUnicode_FromFormat("<module '%U' from '%U'>", name, filename); } Py_DECREF(name); return repr_obj; } static PyObject * strictmodule_dir(PyObject *self, PyObject *args) { _Py_IDENTIFIER(__dict__); PyObject *result = NULL; PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__); if (dict != NULL) { if (PyDict_Check(dict)) { PyObject *dirfunc = PyDict_GetItemString(dict, "__dir__"); if (dirfunc) { result = _PyObject_CallNoArg(dirfunc); } else { result = PyDict_Keys(dict); } } else { PyObject *name = PyStrictModule_GetNameObject((PyStrictModuleObject *)self); if (name) { PyErr_Format(PyExc_TypeError, "%U.__dict__ is not a dictionary", name); Py_DECREF(name); } } } Py_XDECREF(dict); return result; } int _Py_do_strictmodule_patch(PyObject *self, PyObject *name, PyObject *value) { PyStrictModuleObject *mod = (PyStrictModuleObject *) self; PyObject * global_setter = mod->global_setter; if (global_setter == NULL){ PyObject* repr = strictmodule_repr(mod); if (repr == NULL) { return -1; } PyErr_Format(PyExc_AttributeError, "cannot modify attribute '%U' of strict module %U", name, repr); Py_DECREF(repr); return -1; } if (_PyObject_GenericSetAttrWithDict(self, name, value, global_setter) < 0) { return -1; } return 0; } static PyObject * strictmodule_patch(PyObject *self, PyObject *args) { PyObject* name; PyObject* value; if (!PyArg_ParseTuple(args, "UO", &name, &value)) { return NULL; } if (_Py_do_strictmodule_patch(self, name, value) < 0) { return NULL; } Py_RETURN_NONE; } static PyObject * strictmodule_patch_delete(PyObject *self, PyObject *args) { PyObject* name; if (!PyArg_ParseTuple(args, "U", &name)) { return NULL; } if (_Py_do_strictmodule_patch(self, name, NULL) < 0) { return NULL; } Py_RETURN_NONE; } static PyObject * strictmodule_lookupattro(PyStrictModuleObject *m, PyObject *name, int suppress) { PyObject *attr; if (Py_TYPE(m) != &PyStrictModule_Type || !PyUnicode_Check(name)) { attr = NULL; } else if (PyUnicode_GET_LENGTH(name) == 9 && PyUnicode_READ_CHAR(name, 0) == '_' && _PyUnicode_EqualToASCIIString(name, "__class__")) { Py_INCREF(&PyStrictModule_Type); return (PyObject *)&PyStrictModule_Type; } else if (PyUnicode_GET_LENGTH(name) == 8 && PyUnicode_READ_CHAR(name, 0) == '_' && _PyUnicode_EqualToASCIIString(name, "__dict__")) { return strict_module_dict_get((PyObject *) m, NULL); } else if (PyUnicode_GET_LENGTH(name) == 8 && PyUnicode_READ_CHAR(name, 0) == '_' && _PyUnicode_EqualToASCIIString(name, "__name__")) { /* This is a data descriptor, it always takes precedence over * an entry in __dict__ */ return strict_module_name_get((PyObject *) m, NULL); } else if (PyUnicode_GET_LENGTH(name) == 17 && PyUnicode_READ_CHAR(name, 0) == '_' && _PyUnicode_EqualToASCIIString(name, "__patch_enabled__")) { return strict_module_patch_enabled((PyObject *)m, NULL); } else { /* Otherwise we have no other data descriptors, just look in the * dictionary and elide the _PyType_Lookup */ if (m->globals) { int name_unassigned = strictmodule_is_unassigned(m->globals, name); if (name_unassigned < 0) { return NULL; } else if (!name_unassigned) { attr = _PyDict_GetAttrItem_Unicode(m->globals, name); if (attr != NULL) { Py_INCREF(attr); return attr; } else if (PyErr_Occurred()) { if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } return NULL; } } } /* see if we're accessing a descriptor defined on the module type */ attr = _PyType_Lookup(&PyStrictModule_Type, name); if (attr != NULL) { assert(!PyDescr_IsData( attr)); /* it better not be a data descriptor */ descrgetfunc f = attr->ob_type->tp_descr_get; if (f != NULL) { attr = f(attr, (PyObject *)m, (PyObject *)&PyStrictModule_Type); if (attr == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } } else { Py_INCREF(attr); /* got a borrowed ref */ } } } if (attr) { return attr; } if (PyErr_Occurred()) { if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } return NULL; } if (m->globals) { _Py_IDENTIFIER(__getattr__); PyObject *getattr = _PyDict_GetItemId(m->globals, &PyId___getattr__); if (getattr) { PyObject* stack[1] = {name}; PyObject *res = _PyObject_FastCall(getattr, stack, 1); if (res == NULL && suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } return res; } _Py_IDENTIFIER(__name__); PyObject *mod_name = _PyDict_GetItemId(m->globals, &PyId___name__); if (mod_name && PyUnicode_Check(mod_name)) { if (!suppress) { PyErr_Format(PyExc_AttributeError, "strict module '%U' has no attribute '%U'", mod_name, name); } return NULL; } } if (!suppress) { PyErr_Format( PyExc_AttributeError, "strict module has no attribute '%U'", name); } return NULL; } static PyObject * strictmodule_getattro(PyStrictModuleObject *m, PyObject *name) { return strictmodule_lookupattro(m, name, 0); } static int strictmodule_setattro(PyStrictModuleObject *m, PyObject *name, PyObject *value) { PyObject *modname = PyStrictModule_GetNameObject(m); if (modname == NULL) { return -1; } if (value == NULL) { PyErr_Format(PyExc_AttributeError, "cannot delete attribute '%U' of strict module %U", name, modname); } else { PyErr_Format(PyExc_AttributeError, "cannot modify attribute '%U' of strict module %U", name, modname); } Py_DECREF(modname); return -1; } static PyMemberDef strictmodule_members[] = { {NULL} }; static PyMethodDef strictmodule_methods[] = { {"__dir__", strictmodule_dir, METH_NOARGS, PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")}, { "patch", strictmodule_patch, METH_VARARGS, PyDoc_STR("Patch a strict module. Only enabled for testing") }, { "patch_delete", strictmodule_patch_delete, METH_VARARGS, PyDoc_STR("Patch by deleting a field from strict module. Only enabled for testing") }, {0} }; static PyGetSetDef strict_module_getset[] = { {"__dict__", strict_module_dict_get, NULL, NULL, NULL}, {"__name__", strict_module_name_get, NULL, NULL, NULL}, {"__patch_enabled__", strict_module_patch_enabled, NULL, NULL, NULL}, {NULL} }; PyTypeObject PyStrictModule_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "StrictModule", /* tp_name */ sizeof(PyStrictModuleObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)strictmodule_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)strictmodule_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ (getattrofunc)strictmodule_getattro, /* tp_getattro */ (setattrofunc)strictmodule_setattro, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)strictmodule_traverse, /* tp_traverse */ (inquiry)strictmodule_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ strictmodule_methods, /* tp_methods */ strictmodule_members, /* tp_members */ strict_module_getset, /* tp_getset */ &PyModule_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)strictmodule_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyStrictModule_New, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; Py_ssize_t strictmodule_dictoffset = offsetof(PyStrictModuleObject, globals); PyObject * PyDeferredModule_NewObject(PyObject *name, PyObject *globals, PyObject *locals, PyObject *fromlist, PyObject *level) { PyDeferredObject *m; if (!name || !PyUnicode_Check(name) || !globals || !locals || !fromlist || !level) { PyErr_BadArgument(); return NULL; } m = PyObject_GC_New(PyDeferredObject, &PyDeferred_Type); if (m == NULL) { return NULL; } m->df_deferred = NULL; Py_INCREF(name); m->df_name = name; Py_INCREF(globals); m->df_globals = globals; Py_INCREF(locals); m->df_locals = locals; Py_INCREF(fromlist); m->df_fromlist = fromlist; Py_INCREF(level); m->df_level = level; m->df_obj = NULL; m->df_next = NULL; m->df_resolving = 0; m->df_skip_warmup = 0; PyObject_GC_Track(m); return (PyObject *)m; } PyObject * PyDeferred_NewObject(PyObject *deferred, PyObject *name) { PyDeferredObject *m; if (!deferred || !PyDeferred_CheckExact(deferred) || !name || !PyUnicode_Check(name)) { PyErr_BadArgument(); return NULL; } m = PyObject_GC_New(PyDeferredObject, &PyDeferred_Type); if (m == NULL) { return NULL; } Py_INCREF(deferred); m->df_deferred = deferred; Py_INCREF(name); m->df_name = name; m->df_globals = NULL; m->df_locals = NULL; m->df_fromlist = NULL; m->df_level = NULL; m->df_obj = NULL; m->df_next = NULL; m->df_resolving = 0; m->df_skip_warmup = 0; PyObject_GC_Track(m); return (PyObject *)m; } static void deferred_dealloc(PyDeferredObject *m) { Py_XDECREF(m->df_deferred); Py_XDECREF(m->df_name); Py_XDECREF(m->df_globals); Py_XDECREF(m->df_locals); Py_XDECREF(m->df_fromlist); Py_XDECREF(m->df_level); Py_XDECREF(m->df_obj); Py_XDECREF(m->df_next); Py_TYPE(m)->tp_free((PyObject *)m); } static PyObject * deferred_name(PyDeferredObject *m) { if (m->df_deferred != NULL) { PyObject *name = deferred_name((PyDeferredObject *)m->df_deferred); PyObject *res = PyUnicode_FromFormat("%U.%U", name, m->df_name); Py_DECREF(name); return res; } if (m->df_fromlist == NULL || m->df_fromlist == Py_None || !PyObject_IsTrue(m->df_fromlist)) { Py_ssize_t dot = PyUnicode_FindChar(m->df_name, '.', 0, PyUnicode_GET_LENGTH(m->df_name), 1); if (dot >= 0) { return PyUnicode_Substring(m->df_name, 0, dot); } } Py_INCREF(m->df_name); return m->df_name; } static PyObject * deferred_repr(PyDeferredObject *m) { PyObject *name = deferred_name(m); PyObject *res = PyUnicode_FromFormat("<deferred '%U'>", name); Py_DECREF(name); return res; } static int deferred_traverse(PyDeferredObject *m, visitproc visit, void *arg) { Py_VISIT(m->df_deferred); Py_VISIT(m->df_name); Py_VISIT(m->df_globals); Py_VISIT(m->df_locals); Py_VISIT(m->df_fromlist); Py_VISIT(m->df_level); Py_VISIT(m->df_obj); Py_VISIT(m->df_next); return 0; } static int deferred_clear(PyDeferredObject *m) { Py_CLEAR(m->df_deferred); Py_CLEAR(m->df_name); Py_CLEAR(m->df_globals); Py_CLEAR(m->df_locals); Py_CLEAR(m->df_fromlist); Py_CLEAR(m->df_level); Py_CLEAR(m->df_obj); Py_CLEAR(m->df_next); return 0; } PyTypeObject PyDeferred_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "deferred", /* tp_name */ sizeof(PyDeferredObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)deferred_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)deferred_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ 0, /* tp_doc */ (traverseproc)deferred_traverse, /* tp_traverse */ (inquiry)deferred_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ };
27,345
852
import FWCore.ParameterSet.Config as cms WZInterestingEventSelector = cms.EDFilter( "WZInterestingEventSelector", electronCollection = cms.untracked.InputTag('gedGsfElectrons'), pfMetCollection = cms.untracked.InputTag('pfMet'), offlineBSCollection = cms.untracked.InputTag('offlineBeamSpot'), ptCut = cms.double(20.), missHitsCut = cms.int32(1), eb_trIsoCut = cms.double(0.1), eb_ecalIsoCut = cms.double(0.1), eb_hcalIsoCut = cms.double(0.1), eb_hoeCut = cms.double(0.1), eb_seeCut = cms.double(0.014), ee_trIsoCut = cms.double(0.1), ee_ecalIsoCut = cms.double(0.1), ee_hcalIsoCut = cms.double(0.1), ee_hoeCut = cms.double(0.1), ee_seeCut = cms.double(0.035), metCut = cms.double(12.), invMassCut = cms.double(40.) )
377
916
<filename>flexy-tests/flexy-test-hikaricp-java8/src/test/java/com/vladmihalcea/flexypool/HikariCPJava8IntegrationTest.java<gh_stars>100-1000 package com.vladmihalcea.flexypool; import org.junit.runner.RunWith; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * HikarCPJava8IntegrationTest - BasicDataSource HikariCP Java8 Integration Test * * @author <NAME> */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:spring/applicationContext-test.xml") @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class HikariCPJava8IntegrationTest extends HikarCPIntegrationTest { }
258
3,508
package com.fishercoder.solutions; import java.util.HashSet; import java.util.Set; public class _686 { public static class Solution1 { public int repeatedStringMatch(String A, String B) { Set<Character> set = new HashSet<>(); for (char c : A.toCharArray()) { set.add(c); } for (char c : B.toCharArray()) { if (!set.contains(c)) { return -1; } } StringBuilder stringBuilder = new StringBuilder(A); for (int i = 0; i < B.length(); i++) { if (stringBuilder.toString().contains(B)) { return i + 1; } stringBuilder.append(A); } return -1; } } public static class Solution2 { /** * Time: O(N(N+M)) * Space: O(N + M) */ public int repeatedStringMatch(String A, String B) { int count = 1; StringBuilder sb = new StringBuilder(A); for (; sb.length() < B.length(); count++) { sb.append(A); } if (sb.indexOf(B) >= 0) { return count; } sb.append(A); if (sb.indexOf(B) >= 0) { return count + 1; } return -1; } } }
803
1,909
package org.knowm.xchange.enigma.model; public class EnigmaException extends RuntimeException { public EnigmaException(String message) { super(message); } }
50
5,094
<filename>test/test-cases/regression/variable-WEBSERVER_ERROR_LOG.json<gh_stars>1000+ [ { "enabled":1, "version_min":300000, "version_max":0, "title":"Testing Variables :: WEBSERVER_ERROR_LOG (1/1)", "expected":{ "parser_error":"Line: 1. Column: 27. Variable VARIABLE_WEBSERVER_ERROR_LOG is not supported by libModSecurity" }, "rules":[ "secrule WEBSERVER_ERROR_LOG \"@contains test\" \"id:1,t:lowercase,t:none,msg:'This is a test, %{REQUEST_HEADERS:Accept}%'\"" ] } ]
222
625
# Scorer function Hi(z) in the complex plane cplot(scorerhi, [-8,8], [-8,8], points=50000)
36
1,470
<filename>android/src/main/java/com/pichillilorenzo/flutter_inappwebview/MyWebStorage.java package com.pichillilorenzo.flutter_inappwebview; import android.webkit.ValueCallback; import android.webkit.WebStorage; import androidx.annotation.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; public class MyWebStorage implements MethodChannel.MethodCallHandler { static final String LOG_TAG = "MyWebStorage"; public MethodChannel channel; public static WebStorage webStorageManager; @Nullable public InAppWebViewFlutterPlugin plugin; public MyWebStorage(final InAppWebViewFlutterPlugin plugin) { this.plugin = plugin; channel = new MethodChannel(plugin.messenger, "com.pichillilorenzo/flutter_inappwebview_webstoragemanager"); channel.setMethodCallHandler(this); webStorageManager = WebStorage.getInstance(); } @Override public void onMethodCall(MethodCall call, MethodChannel.Result result) { switch (call.method) { case "getOrigins": getOrigins(result); break; case "deleteAllData": webStorageManager.deleteAllData(); result.success(true); break; case "deleteOrigin": { String origin = (String) call.argument("origin"); webStorageManager.deleteOrigin(origin); } result.success(true); break; case "getQuotaForOrigin": { String origin = (String) call.argument("origin"); getQuotaForOrigin(origin, result); } break; case "getUsageForOrigin": { String origin = (String) call.argument("origin"); getUsageForOrigin(origin, result); } break; default: result.notImplemented(); } } public void getOrigins(final MethodChannel.Result result) { webStorageManager.getOrigins(new ValueCallback<Map>() { @Override public void onReceiveValue(Map value) { List<Map<String, Object>> origins = new ArrayList<>(); for(Object key : value.keySet()) { WebStorage.Origin originObj = (WebStorage.Origin) value.get(key); Map<String, Object> originInfo = new HashMap<>(); originInfo.put("origin", originObj.getOrigin()); originInfo.put("quota", originObj.getQuota()); originInfo.put("usage", originObj.getUsage()); origins.add(originInfo); } result.success(origins); } }); } public void getQuotaForOrigin(String origin, final MethodChannel.Result result) { webStorageManager.getQuotaForOrigin(origin, new ValueCallback<Long>() { @Override public void onReceiveValue(Long value) { result.success(value); } }); } public void getUsageForOrigin(String origin, final MethodChannel.Result result) { webStorageManager.getUsageForOrigin(origin, new ValueCallback<Long>() { @Override public void onReceiveValue(Long value) { result.success(value); } }); } public void dispose() { channel.setMethodCallHandler(null); plugin = null; } }
1,232
530
<filename>strongbox-web-core/src/main/java/org/carlspring/strongbox/converters/users/AccessModelFormToUserAccessModelDtoConverter.java package org.carlspring.strongbox.converters.users; import java.util.Collection; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.carlspring.strongbox.forms.users.AccessModelForm; import org.carlspring.strongbox.forms.users.RepositoryAccessModelForm; import org.carlspring.strongbox.users.domain.Privileges; import org.carlspring.strongbox.users.dto.AccessModelDto; import org.carlspring.strongbox.users.dto.PathPrivilegesDto; import org.carlspring.strongbox.users.dto.RepositoryPrivilegesDto; import org.carlspring.strongbox.users.dto.StoragePrivilegesDto; import org.springframework.core.convert.converter.Converter; /** * @author <NAME> * @author <NAME> */ public enum AccessModelFormToUserAccessModelDtoConverter implements Converter<AccessModelForm, AccessModelDto> { INSTANCE; @Override public AccessModelDto convert(AccessModelForm accessModelForm) { if (accessModelForm == null) { return null; } AccessModelDto userAccessModelDto = new AccessModelDto(); accessModelForm.getApiAccess() .stream() .map(p -> Privileges.valueOf(p)) .forEach(p -> userAccessModelDto.getApiAuthorities().add(p)); for (RepositoryAccessModelForm repositoryAccess : accessModelForm.getRepositoriesAccess()) { StoragePrivilegesDto storage = userAccessModelDto.getStorageAuthorities(repositoryAccess.getStorageId()) .orElseGet( () -> { StoragePrivilegesDto userStorageDto = new StoragePrivilegesDto(); userStorageDto.setStorageId( repositoryAccess.getStorageId()); userAccessModelDto.getStorageAuthorities().add(userStorageDto); return userStorageDto; }); RepositoryPrivilegesDto repository = storage.getRepositoryPrivileges(repositoryAccess.getRepositoryId()) .orElseGet( () -> { RepositoryPrivilegesDto userRepositoryDto = new RepositoryPrivilegesDto(); userRepositoryDto.setRepositoryId( repositoryAccess.getRepositoryId()); storage.getRepositoryPrivileges().add(userRepositoryDto); return userRepositoryDto; }); if (StringUtils.isBlank(repositoryAccess.getPath())) { repository.getRepositoryPrivileges().addAll(pullPrivileges(repositoryAccess)); continue; } PathPrivilegesDto pathPrivileges = repository.getPathPrivilege(repositoryAccess.getPath(), repositoryAccess.isWildcard()) .orElseGet( () -> { PathPrivilegesDto pathPrivilegesDto = new PathPrivilegesDto(); pathPrivilegesDto.setPath( repositoryAccess.getPath()); pathPrivilegesDto.setWildcard( repositoryAccess.isWildcard()); repository.getPathPrivileges() .add( pathPrivilegesDto); return pathPrivilegesDto; }); pathPrivileges.getPrivileges().addAll(pullPrivileges(repositoryAccess)); } return userAccessModelDto; } private Collection<Privileges> pullPrivileges(final RepositoryAccessModelForm repositoryAccess) { return repositoryAccess.getPrivileges() .stream() .map(p -> Privileges.valueOf(p)) .collect(Collectors.toSet()); } }
3,445
5,169
<gh_stars>1000+ { "name": "RSTimeAgo", "version": "0.1.0", "summary": "Util for time ago labels.", "description": "Util for time ago labels. Uses aproximated values for motnhs and years due performance reasons.", "homepage": "https://github.com/RishatShamsutdinov/RSTimeAgo", "license": "Apache License, Version 2.0", "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "7.1" }, "source": { "git": "https://github.com/RishatShamsutdinov/RSTimeAgo.git", "tag": "v0.1.0" }, "source_files": "RSTimeAgo/**/*.{h,m}", "requires_arc": true }
249
3,182
<gh_stars>1000+ import lombok.AccessLevel; import lombok.Getter; class Test { @Getter private float b; @Getter(AccessLevel.PROTECTED) private double c; @Getter(AccessLevel.PRIVATE) private String d; }
84
9,136
/* GWEN Copyright (c) 2010 <NAME> See license in Gwen.h */ #include "Gwen/Controls/TreeNode.h" #include "Gwen/Controls/TreeControl.h" #include "Gwen/Utility.h" using namespace Gwen; using namespace Gwen::Controls; class OpenToggleButton : public Button { GWEN_CONTROL_INLINE(OpenToggleButton, Button) { SetIsToggle(true); SetTabable(false); } virtual void RenderFocus(Skin::Base* /*skin*/) {} virtual void Render(Skin::Base* skin) { skin->DrawTreeButton(this, GetToggleState()); } }; const int TreeIndentation = 14; const int BranchLength = 16; GWEN_CONTROL_CONSTRUCTOR(TreeNode) { m_TreeControl = NULL; m_ToggleButton = new OpenToggleButton(this); m_ToggleButton->SetBounds(2, 2, 13, 13); m_ToggleButton->onToggle.Add(this, &TreeNode::OnToggleButtonPress); m_Title = new Button(this); m_Title->Dock(Pos::Top); m_Title->SetMargin(Margin(BranchLength, 0, 0, 0)); m_Title->SetAlignment(Pos::Left | Pos::CenterV); m_Title->SetShouldDrawBackground(false); m_Title->onDoubleClick.Add(this, &TreeNode::OnDoubleClickName); m_Title->onDown.Add(this, &TreeNode::OnClickName); m_Title->SetHeight(16); m_InnerPanel = new Base(this); m_InnerPanel->Dock(Pos::Top); m_InnerPanel->SetHeight(100); m_InnerPanel->SetMargin(Margin(TreeIndentation, 1, 0, 0)); m_InnerPanel->Hide(); m_bRoot = false; m_bSelected = false; m_bSelectable = true; } void TreeNode::Render(Skin::Base* skin) { int iBottom = 0; if (m_InnerPanel->Children.size() > 0) { iBottom = m_InnerPanel->Children.back()->Y() + m_InnerPanel->Y(); } skin->DrawTreeNode(this, m_InnerPanel->Visible(), IsSelected(), m_Title->Height(), m_Title->TextRight(), m_ToggleButton->Y() + m_ToggleButton->Height() * 0.5, iBottom, GetParent() == m_TreeControl); } TreeNode* TreeNode::AddNode(const UnicodeString& strLabel) { // int sz = sizeof(TreeNode); TreeNode* node = new TreeNode(this); node->SetText(strLabel); node->Dock(Pos::Top); node->SetRoot(this->DynamicCastTreeControl() != NULL); node->SetTreeControl(m_TreeControl); if (m_TreeControl) { m_TreeControl->OnNodeAdded(node); } return node; } TreeNode* TreeNode::AddNode(const String& strLabel) { return AddNode(Utility::StringToUnicode(strLabel)); } void TreeNode::Layout(Skin::Base* skin) { if (m_ToggleButton) { if (m_InnerPanel->NumChildren() == 0) { m_ToggleButton->Hide(); m_ToggleButton->SetToggleState(false); m_InnerPanel->Hide(); } else { m_ToggleButton->Show(); m_InnerPanel->SizeToChildren(false, true); } } BaseClass::Layout(skin); } //too many calls to PostLayout... //int numCalls = 0xfd; void TreeNode::PostLayout(Skin::Base* /*skin*/) { //int bla = numCalls&0xffff; //if (bla==0) // printf("TreeNode::PostLayout numCalls = %d\n", numCalls); //numCalls++; if (SizeToChildren(false, true)) { InvalidateParent(); } } void TreeNode::SetText(const UnicodeString& text) { m_Title->SetText(text); }; void TreeNode::SetText(const String& text) { m_Title->SetText(text); }; UnicodeString TreeNode::GetText() const { UnicodeString bla = m_Title->GetText(); return bla; } void TreeNode::Open() { m_InnerPanel->Show(); if (m_ToggleButton) m_ToggleButton->SetToggleState(true); Invalidate(); if (m_TreeControl) m_TreeControl->ForceUpdateScrollBars(); } void TreeNode::Close() { m_InnerPanel->Hide(); if (m_ToggleButton) m_ToggleButton->SetToggleState(false); Invalidate(); if (m_TreeControl) m_TreeControl->ForceUpdateScrollBars(); } void TreeNode::ExpandAll() { Open(); Base::List& children = m_InnerPanel->GetChildren(); for (Base::List::iterator iter = children.begin(); iter != children.end(); ++iter) { TreeNode* pChild = (*iter)->DynamicCastTreeNode(); if (!pChild) continue; pChild->ExpandAll(); } } Button* TreeNode::GetButton() { return m_Title; } void TreeNode::OnToggleButtonPress(Base* /*control*/) { if (m_ToggleButton->GetToggleState()) { Open(); } else { Close(); } } void TreeNode::OnDoubleClickName(Base* /*control*/) { if (!m_ToggleButton->Visible()) return; m_ToggleButton->Toggle(); } void TreeNode::OnClickName(Base* /*control*/) { onNamePress.Call(this); SetSelected(!IsSelected()); } void TreeNode::SetSelected(bool b) { if (!m_bSelectable) return; if (m_bSelected == b) return; m_bSelected = b; onSelectChange.Call(this); if (m_bSelected) onSelect.Call(this); else onUnselect.Call(this); } void TreeNode::DeselectAll() { m_bSelected = false; Base::List& children = m_InnerPanel->GetChildren(); for (Base::List::iterator iter = children.begin(); iter != children.end(); ++iter) { TreeNode* pChild = (*iter)->DynamicCastTreeNode(); if (!pChild) continue; pChild->DeselectAll(); } } void TreeNode::iterate(int action, int* curIndex, int* targetIndex) { Gwen::String name = Gwen::Utility::UnicodeToString(m_Title->GetText()); // int actualIndex = curIndex? *curIndex : -1; //printf("iterated over item %d with name = %s\n", actualIndex, name.c_str()); if (action == ITERATE_ACTION_SELECT) { if (curIndex && targetIndex) { if ((*curIndex) == (*targetIndex)) { SetSelected(true); *targetIndex = -1; } } } if (IsSelected()) { //printf("current selected: name = %s\n", name.c_str()); switch (action) { case ITERATE_ACTION_DESELECT_INDEX: { if (targetIndex && curIndex) { if (*targetIndex == *curIndex) SetSelected(false); } break; } case ITERATE_ACTION_FIND_SELECTED_INDEX: { if (targetIndex && curIndex) { *targetIndex = *curIndex; } break; } case ITERATE_ACTION_OPEN: { Open(); break; } case ITERATE_ACTION_CLOSE: { //either close or select parent if (this->GetChildren().size()) { if (m_ToggleButton && m_ToggleButton->GetToggleState()) { Close(); } else { TreeNode* pChild = (GetParent())->DynamicCastTreeNode(); TreeControl* pChild2 = (GetParent())->DynamicCastTreeControl(); if (pChild && !pChild2) { SetSelected(false); pChild->SetSelected(true); } } } else { TreeNode* pChild = (GetParent())->DynamicCastTreeNode(); TreeControl* pChild2 = (GetParent())->DynamicCastTreeControl(); if (pChild && !pChild2) { SetSelected(false); pChild->SetSelected(true); } } break; } default: { } }; } if (curIndex) (*curIndex)++; bool needsRecursion = true; if (action == ITERATE_ACTION_FIND_SELECTED_INDEX || action == ITERATE_ACTION_SELECT || action == ITERATE_ACTION_DESELECT_INDEX) { if (m_ToggleButton && !m_ToggleButton->GetToggleState()) { needsRecursion = false; } } if (needsRecursion) { Base::List& children = m_InnerPanel->GetChildren(); for (Base::List::iterator iter = children.begin(); iter != children.end(); ++iter) { TreeNode* pChild = (*iter)->DynamicCastTreeNode(); if (!pChild) continue; pChild->iterate(action, curIndex, targetIndex); } } }
2,906
2,151
// Copyright (c) 2012 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_UI_UNINSTALL_BROWSER_PROMPT_H_ #define CHROME_BROWSER_UI_UNINSTALL_BROWSER_PROMPT_H_ namespace chrome { // Asks user for uninstall confirmation and returns one of these values: // service_manager::RESULT_CODE_NORMAL_EXIT, // chrome::RESULT_CODE_UNINSTALL_DELETE_PROFILE or // chrome::RESULT_CODE_UNINSTALL_USER_CANCEL. int ShowUninstallBrowserPrompt(); } // namespace chrome #endif // CHROME_BROWSER_UI_UNINSTALL_BROWSER_PROMPT_H_
225
730
<gh_stars>100-1000 /* * cmdparser.h * * Created on: Oct 14, 2017 * Author: <NAME> */ #ifndef CMDPARSER_H_ #define CMDPARSER_H_ #include "thundersvm.h" #include "svmparam.h" /** * @brief Command-line parser */ class CMDParser{ public: CMDParser() : do_cross_validation(false), gamma_set(false), nr_fold(0), gpu_id(0), n_cores(-1) {}; void parse_command_line(int argc, char **argv); void parse_python(int argc, char **argv); bool check_parameter(); SvmParam param_cmd; bool do_cross_validation; bool gamma_set; int nr_fold; int gpu_id; int n_cores; string svmtrain_input_file_name; string svmpredict_input_file; string svmpredict_output_file; string svmpredict_model_file_name; string model_file_name; }; #endif /* CMDPARSER_H_ */
336
654
<reponame>rendikanyut/LowCostLoRaGw #from https://core-electronics.com.au/tutorials/how-to-make-a-safe-shutdown-button-for-raspberry-pi.html # from gpiozero import Button #import button from the Pi GPIO library import time # import time functions import os #imports OS library for Shutdown control stopButton = Button(26) # defines the button as an object and chooses GPIO 26 rebootButton = Button(21) # defines the button as an object and chooses GPIO 21 while True: #infinite loop if stopButton.is_pressed: #Check to see if button is pressed time.sleep(1) # wait for the hold time we want. if stopButton.is_pressed: #check if the user let go of the button os.system("shutdown now -h") #shut down the Pi -h is or -r will reset if rebootButton.is_pressed: #Check to see if button is pressed time.sleep(1) # wait for the hold time we want. if rebootButton.is_pressed: #check if the user let go of the button os.system("reboot") #reboot the Pi time.sleep(1) # wait to loop again so we don't use the processor too much.
330
660
<gh_stars>100-1000 /* * Copyright (c) 2017-2019, Intel Corporation * * 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. */ //! //! \file codechal_decode_downsampling_g12.h //! \brief Implements the decode interface extension for downsampling on Gen12. //! #ifndef __CODECHAL_DECODER_DOWNSAMPLING_G12_H__ #define __CODECHAL_DECODER_DOWNSAMPLING_G12_H__ #include "codechal_decode_downsampling.h" class FieldScalingInterfaceG12 : public FieldScalingInterface { public: //! //! \brief Constructor //! FieldScalingInterfaceG12(CodechalHwInterface *hwInterface); //! //! \brief Destructor //! ~FieldScalingInterfaceG12() {}; MOS_STATUS SetupMediaVfe( PMOS_COMMAND_BUFFER cmdBuffer, MHW_KERNEL_STATE *kernelState); MOS_STATUS InitMmcState(); }; #endif // __CODECHAL_DECODER_DOWNSAMPLING_G12_H__
627
756
<reponame>isabella232/pynacl<gh_stars>100-1000 /* Copyright 2020 <NAME> and individual contributors * * 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. */ #ifdef SODIUM_LIBRARY_MINIMAL static const int PYNACL_HAS_CRYPTO_PWHASH_SCRYPTSALSA208SHA256 = 0; size_t (*crypto_pwhash_scryptsalsa208sha256_saltbytes)(void) = NULL; size_t (*crypto_pwhash_scryptsalsa208sha256_strbytes)(void) = NULL; size_t (*crypto_pwhash_scryptsalsa208sha256_bytes_min)(void) = NULL; size_t (*crypto_pwhash_scryptsalsa208sha256_bytes_max)(void) = NULL; size_t (*crypto_pwhash_scryptsalsa208sha256_passwd_min)(void) = NULL; size_t (*crypto_pwhash_scryptsalsa208sha256_passwd_max)(void) = NULL; size_t (*crypto_pwhash_scryptsalsa208sha256_opslimit_min)(void) = NULL; size_t (*crypto_pwhash_scryptsalsa208sha256_opslimit_max)(void) = NULL; size_t (*crypto_pwhash_scryptsalsa208sha256_memlimit_min)(void) = NULL; size_t (*crypto_pwhash_scryptsalsa208sha256_memlimit_max)(void) = NULL; size_t (*crypto_pwhash_scryptsalsa208sha256_opslimit_interactive)(void) = NULL; size_t (*crypto_pwhash_scryptsalsa208sha256_memlimit_interactive)(void) = NULL; size_t (*crypto_pwhash_scryptsalsa208sha256_opslimit_sensitive)(void) = NULL; size_t (*crypto_pwhash_scryptsalsa208sha256_memlimit_sensitive)(void) = NULL; const char *(*crypto_pwhash_scryptsalsa208sha256_strprefix)(void) = NULL; int (*crypto_pwhash_scryptsalsa208sha256_ll)(const uint8_t * const, size_t, const uint8_t *, size_t, uint64_t, uint32_t, uint32_t, uint8_t *, size_t) = NULL; /* #define crypto_pwhash_scryptsalsa208sha256_STRBYTES 102 */ int (*crypto_pwhash_scryptsalsa208sha256_str)(char [102], const char * const, unsigned long long, unsigned long long, size_t) = NULL; int (*crypto_pwhash_scryptsalsa208sha256_str_verify)(const char [102], const char * const, unsigned long long) = NULL; #else static const int PYNACL_HAS_CRYPTO_PWHASH_SCRYPTSALSA208SHA256 = 1; #endif
1,412
461
<reponame>hzjane/HUSTER-CS #include<stdio.h> #include<unistd.h> #include<errno.h> #include<sys/syscall.h> #include<linux/kernel.h> int main(int argc,char *argv[]){ long int a=syscall(335,5); printf("System call sys_mycall return %ld\n",a); return 0; }
129
12,278
<gh_stars>1000+ // (C) Copyright <NAME> 2015 // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). #if !defined(BOOST_VMD_SEQ_PUSH_FRONT_HPP) #define BOOST_VMD_SEQ_PUSH_FRONT_HPP #include <boost/vmd/detail/setup.hpp> #if BOOST_PP_VARIADICS #include <boost/preprocessor/control/iif.hpp> #include <boost/preprocessor/seq/push_front.hpp> #include <boost/vmd/identity.hpp> #include <boost/vmd/is_empty.hpp> /* The succeeding comments in this file are in doxygen format. */ /** \file */ /** \def BOOST_VMD_SEQ_PUSH_FRONT(seq,elem) \brief inserts an element at the beginning of a seq. seq = seq to insert an element at. elem = element to insert. If the seq is an empty seq the result is a seq with the single element. Otherwise the result is a seq after inserting the element at the beginning. */ #define BOOST_VMD_SEQ_PUSH_FRONT(seq,elem) \ BOOST_VMD_IDENTITY_RESULT \ ( \ BOOST_PP_IIF \ ( \ BOOST_VMD_IS_EMPTY(seq), \ BOOST_VMD_IDENTITY((elem)), \ BOOST_PP_SEQ_PUSH_FRONT \ ) \ (seq,elem) \ ) \ /**/ #endif /* BOOST_PP_VARIADICS */ #endif /* BOOST_VMD_SEQ_PUSH_FRONT_HPP */
608
356
<reponame>EvilPudding/candle #include <utils/shader.h> #include <utils/str.h> static void shaders_candle_final() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "#include \"candle:common.glsl\"\n" "layout (location = 0) out vec4 FragColor;\n" "BUFFER {\n" " sampler2D depth;\n" " sampler2D albedo;\n" " sampler2D nn;\n" " sampler2D mrs;\n" " sampler2D emissive;\n" "} gbuffer;\n" "BUFFER {\n" " sampler2D occlusion;\n" "} ssao;\n" "BUFFER {\n" " sampler2D color;\n" "} light;\n" "BUFFER {\n" " sampler2D color;\n" "} refr;\n" "BUFFER {\n" " sampler2D color;\n" "} volum;\n" "uniform float ssr_power;\n" "uniform float ssao_power;\n"); str_cat(&shader_buffer, "vec4 upsample()\n" "{\n" " ivec2 fc = ivec2(gl_FragCoord.xy);\n" " vec3 volumetric = vec3(0.0);\n" " float ssao_factor = 0.0;\n" " float totalWeight = 0.0;\n" " /* Select the closest downscaled pixels. */\n" " int xOffset = fc.x % 2 == 0 ? -1 : 1;\n" " int yOffset = fc.y % 2 == 0 ? -1 : 1;\n" " ivec2 offsets[] = ivec2[](\n" " ivec2(0, 0),\n" " ivec2(0, yOffset),\n" " ivec2(xOffset, 0),\n" " ivec2(xOffset, yOffset));\n" " float frag_depth = linearize(texelFetch(gbuffer.depth, fc, 0).r);\n" " ivec2 dfc = fc / 2;\n"); str_cat(&shader_buffer, " for (int i = 0; i < 4; i ++)\n" " {\n" " ivec2 coord = clamp(dfc + offsets[i], ivec2(0), ivec2(screen_size) / 2 - 1);\n" " vec3 vol = texelFetch(volum.color, coord, 0).rgb;\n" " float dep = linearize(texelFetch(gbuffer.depth, coord * 2, 0).r);\n" " float w = max(0.0, 1.0 - 0.5 * abs(dep - frag_depth));\n" " if (ssao_power > 0.05)\n" " {\n" " vec2 sampled = texelFetch(ssao.occlusion, coord, 0).rg;\n" " float downscaledSsao = sampled.r;\n" " ssao_factor += (1.0 - downscaledSsao) * w;\n" " }\n"); str_cat(&shader_buffer, " volumetric += vol * w;\n" " totalWeight += w;\n" " }\n" " const float epsilon = 0.0001;\n" " float factor = totalWeight + epsilon;\n" " return vec4(volumetric, (factor - ssao_factor * ssao_power)) / factor;\n" "}\n"); str_cat(&shader_buffer, "void main(void)\n" "{\n" " ivec2 fc = ivec2(gl_FragCoord.xy);\n" " vec4 cc = texelFetch(light.color, fc, 0);\n" " vec4 refr0 = texelFetch(refr.color, fc, 0);\n" " cc = vec4(max(mix(refr0.rgb, cc.rgb, cc.a), 0.), 1.0);\n" " vec2 normal = texelFetch(gbuffer.nn, fc, 0).rg;\n" " vec2 metalic_roughness = texelFetch(gbuffer.mrs, fc, 0).rg;\n" " vec4 albedo = texelFetch(gbuffer.albedo, fc, 0);\n" " vec3 emissive = texelFetch(gbuffer.emissive, fc, 0).rgb;\n" " vec3 nor = decode_normal(normal);\n"); str_cat(&shader_buffer, " vec4 ssred = ssr_power > 0.05 ? ssr2(gbuffer.depth, refr.color, albedo,\n" " metalic_roughness, nor) * 1.5 : vec4(0.0);\n" " float frag_depth = linearize(texelFetch(gbuffer.depth, fc, 0).r);\n" " vec4 volum_ssao = upsample();\n" " cc.rgb *= volum_ssao.w;\n" " vec3 final = cc.rgb + ssred.rgb * (ssred.a * ssr_power) + emissive + volum_ssao.xyz;\n" " final = final * pow(2.0, camera(exposure));\n" " FragColor = vec4(final, 1.0);\n" "}\n"); shader_add_source("candle:final.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static vec3_t sss_gaussian(float variance, float red, vec3_t falloff) { int i; vec3_t g; for (i = 0; i < 3; i++) { float rr = red / (0.001f + ((float*)&falloff)[i]); ((float*)&g)[i] = exp((-(rr * rr)) / (2.0f * variance)) / (2.0f * 3.14f * variance); } return g; } static vec3_t sss_profile(float red, vec3_t falloff) { return vec3_add(vec3_scale(sss_gaussian(0.0484f, red, falloff), 0.100f), vec3_add(vec3_scale(sss_gaussian( 0.187f, red, falloff), 0.118f), vec3_add(vec3_scale(sss_gaussian( 0.567f, red, falloff), 0.113f), vec3_add(vec3_scale(sss_gaussian( 1.99f, red, falloff), 0.358f), vec3_scale(sss_gaussian( 7.41f, red, falloff), 0.078f))))); } static void sss_kernel(int num_samples, vec3_t falloff, char **str) { int i; const float RANGE = num_samples > 20? 3.0f : 2.0f; const float EXPONENT = 2.0f; vec4_t t; vec3_t sum = vec3(0.0f, 0.0f, 0.0f); vec4_t *kernel = malloc(sizeof(*kernel) * num_samples); /* Calculate the offsets: */ float step = 2.0f * RANGE / (num_samples - 1); for (i = 0; i < num_samples; i++) { float o = -RANGE + ((float)i) * step; float sign = o < 0.0f? -1.0f : 1.0f; kernel[i].w = RANGE * sign * fabs(powf(o, EXPONENT)) / powf(RANGE, EXPONENT); } /* Calculate the weights: */ for (i = 0; i < num_samples; i++) { float w0 = i > 0 ? fabs(kernel[i].w - kernel[i - 1].w) : 0.0f; float w1 = i < num_samples - 1 ? fabs(kernel[i].w - kernel[i + 1].w) : 0.0f; float area = (w0 + w1) / 2.0f; XYZ(kernel[i]) = vec3_scale(sss_profile(kernel[i].w, falloff), area); } /* We want the offset 0.0 to come first: */ t = kernel[num_samples / 2]; for (i = num_samples / 2; i > 0; i--) kernel[i] = kernel[i - 1]; kernel[0] = t; for (i = 0; i < num_samples; i++) sum = vec3_add(sum, XYZ(kernel[i])); for (i = 0; i < num_samples; i++) { kernel[i].x /= sum.x; kernel[i].y /= sum.y; kernel[i].z /= sum.z; } for (i = 0; i < num_samples; ++i) { str_catf(str, "vec4(%f,%f,%f,%f)%c", _vec4(kernel[i]), i == num_samples - 1 ? '\n':','); } free(kernel); } static void shaders_candle_sss() { /* Uses Separable SSS. Copyright (C) 2011 by <NAME> and <NAME>. */ char *shader_buffer = str_new(64); str_cat(&shader_buffer, "#include \"candle:common.glsl\"\n" "const vec4 kernel[25] = vec4[25](\n"); sss_kernel(25, vec3(1.0, 0.3, 0.3), &shader_buffer); str_cat(&shader_buffer, ");\n"); str_cat(&shader_buffer, "vec4 sssblur(vec2 tc, float power, sampler2D color_lit, sampler2D depth_tex,\n" " sampler2D props, sampler2D color, vec2 dir) {\n" " vec4 colorM = texture(color_lit, tc);\n" " float sssWidth = texture(props, tc).b;\n" " if (ceil(sssWidth) == 0.0) discard;\n" " float dist_to_projection = camera(projection)[1][1];\n" " float scale = dist_to_projection / linearize(texture(depth_tex, tc).r);\n" " vec4 surface_ = texture(color, tc);\n" " vec3 surface = surface_.rgb * (surface_.a - 0.5) * 2.0 * power;\n"); str_cat(&shader_buffer, " vec2 stepscale = sssWidth * scale * dir;\n" " stepscale *= 1.0 / 3.0;\n" " vec4 blurred = colorM;\n" " blurred.rgb *= surface * kernel[0].rgb + (1.0 - surface);\n" " for (int i = 1; i < 25; i++) {\n" " vec2 offset = tc + kernel[i].a * stepscale;\n" " vec4 color = texture(color_lit, offset);\n" " float sss_strength1 = ceil(texture(props, offset).b);\n" " color.rgb = mix(color.rgb, colorM.rgb, 1.0 - sss_strength1);\n" " blurred.rgb += kernel[i].rgb * surface * color.rgb;\n" " }\n" " return blurred;\n" "}\n"); str_cat(&shader_buffer, "layout (location = 0) out vec4 FragColor;\n" "BUFFER {\n" " sampler2D color;\n" "} buf;\n" "BUFFER {\n" " sampler2D albedo;\n" " sampler2D depth;\n" " sampler2D mrs;\n" "} gbuffer;\n" "uniform vec2 pass_dir;\n" "uniform float power;\n" "void main(void)\n" "{\n" " FragColor = sssblur(texcoord, power, buf.color, gbuffer.depth,\n" " gbuffer.mrs, gbuffer.albedo, pass_dir);\n" "}\n"); shader_add_source("candle:sss.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_ssao() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "#include \"candle:common.glsl\"\n" "#define ITERS 4.0\n" "#define TAPS 7u\n" "BUFFER {\n" " sampler2D depth;\n" " sampler2D nn;\n" " sampler2D mrs;\n" "} gbuffer;\n" "layout (location = 0) out float FragColor;\n" "vec2 hemicircle[] = vec2[](\n" " vec2(1.0, 0.0),\n" " vec2(0.92388, 0.38268),\n" " vec2(0.70711, 0.70711),\n" " vec2(0.38268, 0.92388),\n" " vec2(0.0, 1.0),\n" " vec2(-0.38268, 0.92388),\n" " vec2(-0.70711, 0.70711),\n" " vec2(-0.92388, 0.38268)\n" ");\n"); str_cat(&shader_buffer, "void main(void)\n" "{\n" " float ao = 0.0;\n" " vec2 tc = texcoord;\n" " vec3 n = decode_normal(texelFetch(gbuffer.nn, ivec2(gl_FragCoord.xy) * 2, 0).rg);\n" " float D = texelFetch(gbuffer.depth, ivec2(gl_FragCoord.xy) * 2, 0).r;\n" " float d0 = linearize(D);\n" " float dither = dither_value();\n" " float rad = (0.4 / d0);\n" " vec2 rnd = normalize(vec2(rand(tc), dither));\n" " float z = clamp((n.z + 0.5), 0.0, 1.0);\n"); str_cat(&shader_buffer, " for (uint j = 0u; j < TAPS; ++j)\n" " {\n" " float angle1 = -M_PI;\n" " float angle2 = -M_PI;\n" " float angle = M_PI * 2.0;\n" " vec2 offset = reflect(hemicircle[j], rnd) * rad;\n" " vec2 norm = normalize(n.xy);\n" " float d = (norm.x * offset.x + norm.y * offset.y);\n" " norm = norm * d;\n" " offset = offset - norm + norm * (1.0 - (1.0 - z));\n"); str_cat(&shader_buffer, " for (float i = 0.0; i < ITERS; ++i)\n" " {\n" " float c0 = pow((i + dither) / (ITERS - 1.0), 2.0) + 0.001;\n" " vec2 coord1 = offset * c0;\n" " ivec2 tp = ivec2((tc + coord1) * (screen_size)) * 2;\n" " ivec2 tn = ivec2((tc - coord1) * (screen_size)) * 2;\n" " float d1 = linearize(texelFetch(gbuffer.depth, tp, 0).r);\n" " float d2 = linearize(texelFetch(gbuffer.depth, tn, 0).r);\n" " float c1 = d0 - d1;\n" " float c2 = d0 - d2;\n"); str_cat(&shader_buffer, " if (abs(c1) < 1.0)\n" " angle1 = atan(c1, c0);\n" " else if (abs(c1) < 2.0)\n" " angle1 += (atan(c1, c0) - angle1) * (1.0 - (abs(c1) - 1.0));\n" " if (abs(c2) < 1.0)\n" " angle2 = atan(c2, c0);\n" " else if (abs(c2) < 2.0)\n" " angle2 += (atan(c2, c0) - angle2) * (1.0 - (abs(c2) - 1.0));\n" " angle = min(angle, M_PI - angle1 - angle2);\n"); str_cat(&shader_buffer, " float falloff = (1.0 + max(abs(c1), abs(c2)));\n" " ao += clamp(sin(angle) / falloff, 0.0, 1.0);\n" " }\n" " }\n" " ao = 1.0 - (ao / (float(TAPS) * ITERS));\n" " FragColor = clamp(ao, 0.0, 1.0); \n" "}\n"); shader_add_source("candle:ssao.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_color() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "layout (location = 0) out vec4 FragColor;\n" "in vec4 poly_color;\n" "void main(void)\n" "{\n" " FragColor = poly_color;\n" /* " FragColor = vec4(0.5, 0.5, 0.5, 1.0);\n" */ "}\n"); shader_add_source("candle:color.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_copyf() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "layout (location = 0) out vec4 FragColor;\n" "BUFFER {\n" " sampler2D color;\n" "} buf;\n" "uniform float level;\n" "uniform vec2 size;\n" "uniform vec2 screen_size;\n" "void main(void)\n" "{\n" " vec2 tc = (gl_FragCoord.xy - pos) / size;\n" " vec4 tex = textureLod(buf.color, tc, level);\n" " if(tex.a == 0.0) discard;\n" " FragColor = vec4(tc, 0.0, 1.0);\n" "}\n"); shader_add_source("candle:copyf.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_copy() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "layout (location = 0) out vec4 FragColor;\n" "BUFFER {\n" " sampler2D color;\n" "} buf;\n" "uniform int level;\n" "uniform ivec2 pos;\n" "void main(void)\n" "{\n" " ivec2 tc = ivec2(gl_FragCoord.xy) - pos;\n" " vec4 tex = texelFetch(buf.color, tc, level);\n" " if(tex.a == 0.0) discard;\n" " FragColor = tex;\n" "}\n"); shader_add_source("candle:copy.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_copy_gbuffer() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "layout (location = 0) out vec4 Alb;\n" "layout (location = 1) out vec2 NN;\n" "layout (location = 2) out vec3 MRS;\n" "layout (location = 3) out vec3 Emi;\n" "BUFFER {\n" " sampler2D depth;\n" " sampler2D albedo;\n" " sampler2D nn;\n" " sampler2D mrs;\n" " sampler2D emissive;\n" "} gbuffer;\n"); str_cat(&shader_buffer, "void main(void)\n" "{\n" " vec4 alb = texelFetch(gbuffer.albedo, ivec2(gl_FragCoord.xy), 0);\n" " if (alb.a < 0.5) discard;\n" " Alb = alb;\n" " NN = texelFetch(gbuffer.nn, ivec2(gl_FragCoord.xy), 0).rg;\n" " MRS = texelFetch(gbuffer.mrs, ivec2(gl_FragCoord.xy), 0).rgb;\n" " Emi = texelFetch(gbuffer.emissive, ivec2(gl_FragCoord.xy), 0).rgb;\n" " gl_FragDepth = texelFetch(gbuffer.depth, ivec2(gl_FragCoord.xy), 0).r;\n" "}\n"); shader_add_source("candle:copy_gbuffer.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_downsample() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "layout (location = 0) out vec4 FragColor;\n" "BUFFER {\n" " sampler2D color;\n" "} buf;\n" "uniform int level;\n" "void main(void)\n" "{\n" " vec2 pp = vec2(gl_FragCoord.xy) * 2.0;\n" " vec4 tex = vec4(0.0);\n" " ivec2 iv;\n" " for(iv.x = 0; iv.x < 2; iv.x++)\n" " for(iv.y = 0; iv.y < 2; iv.y++)\n" " tex += texelFetch(buf.color, ivec2(pp) + iv, level);\n" " tex /= 4.0;\n" " FragColor = tex;\n" "}\n"); shader_add_source("candle:downsample.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_upsample() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "#include \"candle:common.glsl\"\n" "layout (location = 0) out vec4 FragColor;\n" "BUFFER {\n" " sampler2D color;\n" "} buf;\n" "uniform int level;\n" "uniform float alpha;\n" "void main(void)\n" "{\n" " vec4 tex;\n" " tex = textureLod(buf.color, texcoord, float(level));\n" /* " tex.a = 1.0;\n" */ /* " tex.a = alpha;\n" */ " FragColor = tex;\n" "}\n"); shader_add_source("candle:upsample.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_kawase() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "layout (location = 0) out vec4 FragColor;\n" "uniform int distance;\n" "uniform int level;\n" "BUFFER {\n" " sampler2D color;\n" "} buf;\n" "vec3 fs(ivec2 coord)\n" "{\n" " if(coord.x < 0) coord.x = 0;\n" " if(coord.y < 0) coord.y = 0;\n" " ivec2 s = textureSize(buf.color, level);\n" " if(coord.x >= s.x) coord.x = s.x - 1;\n" " if(coord.y >= s.y) coord.y = s.y - 1;\n" " return texelFetch(buf.color, coord, level).rgb;\n" "}\n"); str_cat(&shader_buffer, "vec3 fetch(ivec2 coord)\n" "{\n" " return fs(coord).rgb +\n" " fs(coord + ivec2(1, 0)) +\n" " fs(coord + ivec2(1, 1)) +\n" " fs(coord + ivec2(0, 1));\n" "}\n" "void main(void)\n" "{\n" " ivec2 tc = ivec2(gl_FragCoord.xy);\n" " vec3 c = vec3(0.0);\n" " c += fetch(tc + ivec2(distance, distance));\n" " c += fetch(tc + ivec2(-distance - 1, -distance - 1));\n" " c += fetch(tc + ivec2(distance, -distance - 1));\n" " c += fetch(tc + ivec2(-distance - 1, distance));\n" " FragColor = vec4(c / 16.0, 1.0);\n" "}\n"); shader_add_source("candle:kawase.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_bright() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "#include \"candle:common.glsl\"\n" "layout (location = 0) out vec4 FragColor;\n" "BUFFER {\n" " sampler2D color;\n" "} buf;\n" "void main(void)\n" "{\n" " float brightPassThreshold = 0.99;\n" " vec3 luminanceVector = vec3(0.2125, 0.7154, 0.0721);\n" " vec3 c = textureLod(buf.color, texcoord, 0.0).rgb;\n" " float luminance = dot(luminanceVector, c);\n" " luminance = max(0.0, luminance - brightPassThreshold);\n" " c *= sign(luminance);\n" " FragColor = vec4(c, 1.0);\n" "}\n"); shader_add_source("candle:bright.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_framebuffer_draw() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "#include \"candle:common.glsl\"\n" "layout (location = 0) out vec4 Alb;\n" "layout (location = 1) out vec4 NN;\n" "layout (location = 2) out vec4 MR;\n" "layout (location = 3) out vec3 Emi;\n" "void main()\n" "{\n" " vec4 dif = textureLod(g_framebuffer, texcoord, 0.0);\n" " Alb = dif;\n" " if(dif.a < 0.7) discard;\n" " NN = vec4(encode_normal(get_normal(vec3(0.5, 0.5, 1.0))), 0.0, 1.0);\n" " MR = vec4(0.5, 0.5, 0.0, 1.0);\n" " Emi = vec3(0.0, 0.0, 0.0);\n" "}\n"); shader_add_source("candle:framebuffer_draw.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_quad() { /* TODO: Should probably be moved to systems/window.c */ char *shader_buffer = str_new(64); str_cat(&shader_buffer, "#include \"candle:common.glsl\"\n" "layout (location = 0) out vec4 FragColor;\n" "uniform sampler2D tex;\n" "void main(void)\n" "{\n" " FragColor = textureLod(tex, texcoord, 0.0);\n" "} \n"); shader_add_source("candle:quad.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_motion() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "#include \"candle:common.glsl\"\n" "layout (location = 0) out vec4 FragColor;\n" "BUFFER {\n" " sampler2D color;\n" "} buf;\n" "BUFFER {\n" " sampler2D depth;\n" " sampler2D albedo;\n" "} gbuffer;\n" "uniform float power;\n"); str_cat(&shader_buffer, "void main(void)\n" "{\n" " vec2 p = pixel_pos();\n" " vec3 c_pos = get_position(gbuffer.depth, p);\n" " vec4 w_pos = (camera(model) * vec4(c_pos, 1.0));\n" " vec4 previousPos = (camera(projection) * camera(previous_view)) * w_pos;\n" " vec2 pp = previousPos.xy / previousPos.w;\n" " const int num_samples = 4;\n" " pp = (pp + 1.0) / 2.0;\n" " vec2 velocity = ((p - pp) / float(num_samples)) * power;\n" " float samples = 0.0;\n"); str_cat(&shader_buffer, " p += velocity * dither_value();\n" " vec3 color = vec3(0.0);\n" " for(int i = 0; i < num_samples; ++i)\n" " {\n" " samples += 1.0;\n" " color += textureLod(buf.color, p, 0.0).rgb;\n" " p += velocity;\n" " if (p.x < 0.0 || p.x > 1.0 || p.y < 0.0 || p.y > 1.0)\n" " {\n" " break;\n" " }\n" " }\n" " FragColor = vec4(color / samples, 1.0);\n" "}\n"); shader_add_source("candle:motion.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_uniforms() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "#ifndef UNIFORMS\n" "#define UNIFORMS\n" "struct camera_t\n" "{\n" " mat4 previous_view;\n" " mat4 model;\n" " mat4 view;\n" " mat4 projection;\n" " mat4 inv_projection;\n" " vec3 pos;\n" " float exposure;\n" "};\n"); str_cat(&shader_buffer, "struct light_t\n" "{\n" " vec3 color;\n" " float volumetric;\n" " uvec2 pos;\n" " int lod;\n" " float radius;\n" "};\n" "layout(std140) uniform renderer_t\n" "{\n" " camera_t cam;\n" "} renderer;\n"); str_cat(&shader_buffer, "layout(std140) uniform scene_t\n" "{\n" " light_t lights[62];\n" " vec3 test_color;\n" " float time;\n" "} scene;\n" "#ifdef HAS_SKIN\n" "layout(std140) uniform skin_t\n" "{\n" " mat4 bones[64];\n" "} skin;\n" "#endif\n"); str_cat(&shader_buffer, /* layout(location = 23) */ "uniform vec2 screen_size;\n" /* layout(location = 24) */ "uniform bool has_tex;\n" /* layout(location = 25) */ "uniform bool has_normals;\n" /* layout(location = 26) */ "uniform bool receive_shadows;\n" /* layout(location = 27) */ "uniform sampler2D g_cache;\n" /* layout(location = 28) */ "uniform sampler2D g_indir;\n" /* layout(location = 29) */ "uniform sampler2D g_probes_depth;\n" /* layout(location = 30) */ "uniform sampler2D g_probes;\n" /* layout(location = 31) */ "uniform sampler2D g_framebuffer;\n" "#define light(prop) (scene.lights[matid].prop)\n" "#define camera(prop) (renderer.cam.prop)\n" "#endif\n"); shader_add_source("candle:uniforms.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_common() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "#ifndef FRAG_COMMON\n" "#define FRAG_COMMON\n" "#include \"candle:uniforms.glsl\"\n" "\n" "const float M_PI = 3.141592653589793;\n" "const float c_MinRoughness = 0.04;\n" "\n" "flat in uvec2 id;\n" "flat in uint matid;\n" "flat in vec2 object_id;\n" "flat in uvec2 poly_id;\n" "flat in vec3 obj_pos;\n" "flat in mat4 model;\n" "\n" "in vec4 poly_color;\n" "in vec3 vertex_position;\n" "in vec3 vertex_tangent;\n" "in vec3 vertex_normal;\n" "in vec3 vertex_world_position;\n" "in vec2 texcoord;\n" "\n"); str_cat(&shader_buffer, "float rand(vec2 co)\n" "{\n" " return fract(sin(dot(co.xy, vec2(12.9898,78.233))) * 43758.5453);\n" "}\n"); str_cat(&shader_buffer, "vec2 sampleCube(const vec3 v, out uint faceIndex, out float z)\n" "{\n" " vec3 vAbs = abs(v);\n" " float ma;\n" " vec2 uv;\n" " if(vAbs.z >= vAbs.x && vAbs.z >= vAbs.y)\n" " {\n" " faceIndex = v.z < 0.0 ? 5u : 4u;\n" " ma = 0.5 / vAbs.z;\n" " uv = vec2(v.z < 0.0 ? -v.x : v.x, -v.y);\n" " z = vAbs.z;\n" " }\n" " else if(vAbs.y >= vAbs.x)\n"); str_cat(&shader_buffer, " {\n" " faceIndex = v.y < 0.0 ? 3u : 2u;\n" " ma = 0.5 / vAbs.y;\n" " uv = vec2(v.x, v.y < 0.0 ? -v.z : v.z);\n" " z = vAbs.y;\n" " }\n" " else\n" " {\n" " faceIndex = v.x < 0.0 ? 1u : 0u;\n" " ma = 0.5 / vAbs.x;\n" " uv = vec2(v.x < 0.0 ? v.z : -v.z, -v.y);\n" " z = vAbs.x;\n" " }\n" " return uv * ma + 0.5;\n" "}\n"); str_cat(&shader_buffer, "vec2 pixel_pos()\n" "{\n" " return gl_FragCoord.xy / screen_size;\n" "}\n"); str_cat(&shader_buffer, "/* Does not take into account GL_TEXTURE_MIN_LOD/GL_TEXTURE_MAX_LOD/GL_TEXTURE_LOD_BIAS, */\n" "/* nor implementation-specific flexibility allowed by OpenGL spec */\n" "float mip_map_scalar(in vec2 texture_coordinate) /* in texel units */\n" "{\n" " vec2 dx_vtc = dFdx(texture_coordinate);\n" " vec2 dy_vtc = dFdy(texture_coordinate);\n" " return max(dot(dx_vtc, dx_vtc), dot(dy_vtc, dy_vtc));\n" "}\n"); str_cat(&shader_buffer, "#define MAX_MIPS 9u\n" "float mip_map_level(in vec2 texture_coordinate) // in texel units\n" "{\n" " return clamp(0.5 * log2(mip_map_scalar(texture_coordinate)), 0.0, float(MAX_MIPS - 1u));\n" "}\n" "\n" "#define g_indir_w 128u\n" "#define g_indir_h 128u\n" "#define g_cache_w 64u\n" "#define g_cache_h 32u\n" "\n" "uint round_power_of_two(uint v)\n" "{\n" " v--;\n" " v |= v >> 1u;\n" " v |= v >> 2u;\n" " v |= v >> 4u;\n" " v |= v >> 8u;\n" " v |= v >> 16u;\n" " return v + 1u;\n" "}\n"); str_cat(&shader_buffer, "vec4 solve_mip(uint tiles_per_row, uint base_tile, uint mip, vec2 coords,\n" " out uint tile_out)\n" "{\n" " float max_mips = log2(float(tiles_per_row));\n" " float mm = min(max_mips, float(mip));\n" " uint map_tiles = uint(exp2(2. * (max_mips + 1. - mm)) * (exp2(mm * 2.) - 1.)) / 3u;\n" " map_tiles += uint(max(0., float(mip) - max_mips));\n" " uint offset = base_tile + map_tiles;\n" " uint mip_tpr = tiles_per_row >> mip;\n" " uvec2 indir_coords = uvec2(floor(coords / (exp2(float(mip)) * 128.0)));\n"); str_cat(&shader_buffer, " uint tile_id = indir_coords.y * mip_tpr + indir_coords.x + offset;\n" " tile_out = tile_id;\n" " vec3 info = texelFetch(g_indir, ivec2(tile_id % g_indir_w,\n" " tile_id / g_indir_w), 0).rgb * 255.0;\n" " float actual_mip = info.b;\n" " const vec2 g_cache_size = vec2(g_cache_w, g_cache_h);\n" " vec2 tex_coords = coords / exp2(actual_mip);\n" " vec2 tile_coords = mod(tex_coords, 128.0) + 0.5f;\n" " return textureLod(g_cache,\n" " (info.xy + tile_coords / 129.) / g_cache_size, 0.0);\n" "}\n"); str_cat(&shader_buffer, "vec4 textureSVT(uvec2 size, uint base_tile, vec2 coords, out uint tile_out,\n" " float mip_scale)\n" "{\n" " coords.y = 1.0 - coords.y;\n" " vec2 rcoords = fract(coords) * vec2(size);\n" " uint max_dim = uint(ceil(float(max(size.x, size.y)) / 128.0));\n" " uint tiles_per_row = round_power_of_two(max_dim);\n"); str_cat(&shader_buffer, " float mip = mip_map_level(coords * vec2(size) * mip_scale);\n" " uint mip0 = uint(floor(mip));\n" " uint mip1 = uint(ceil(mip));\n" " uint ignore;\n" " return mix(solve_mip(tiles_per_row, base_tile, mip0, rcoords, tile_out),\n" " solve_mip(tiles_per_row, base_tile, mip1, rcoords, ignore), fract(mip));\n" "}\n"); str_cat(&shader_buffer, "#define NEAR 0.1\n" "#define FAR 1000.0\n" "float linearize(float depth)\n" "{\n" " return (2.0 * NEAR * FAR) / ((FAR + NEAR) - (2.0 * depth - 1.0) * (FAR - NEAR));\n" "}\n" "float unlinearize(float depth)\n" "{\n" " return FAR * (1.0 - (NEAR / depth)) / (FAR - NEAR);\n" "}\n"); str_cat(&shader_buffer, "const vec4 bitSh = vec4(256. * 256. * 256., 256. * 256., 256., 1.);\n" "const vec4 bitMsk = vec4(0.,vec3(1./256.0));\n" "const vec4 bitShifts = vec4(1.) / bitSh;\n" "\n" "vec4 encode_float_rgba_unit( float v ) {\n" " vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * v;\n" " enc = fract(enc);\n" " enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n" " return enc;\n" "}\n"); str_cat(&shader_buffer, "float decode_float_rgba_unit( vec4 rgba ) {\n" " return dot(rgba, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0) );\n" "}\n" "vec4 encode_float_rgba (float value) {\n" " value /= 256.0;\n" " vec4 comp = fract(value * bitSh);\n" " comp -= comp.xxyz * bitMsk;\n" " return comp;\n" "}\n" "\n" "float decode_float_rgba (vec4 color) {\n" " return dot(color, bitShifts) * (256.0);\n" "}\n"); str_cat(&shader_buffer, "float dither_value()\n" "{\n" " const float pattern[16] = float[16](0.0f, 0.5f, 0.125f, 0.625f,\n" " 0.75f, 0.22f, 0.875f, 0.375f, 0.1875f, 0.6875f, 0.0625f, 0.5625,\n" " 0.9375f, 0.4375f, 0.8125f, 0.3125);\n" " return pattern[ (int(gl_FragCoord.x) % 4) * 4\n" " + (int(gl_FragCoord.y) % 4)];\n" "}\n"); /* TODO: move to phong.glsl */ str_cat(&shader_buffer, "float lookup_single(vec3 shadowCoord, out float z)\n" "{\n" " uint size = 1024u / uint(pow(2.0, float(light(lod))));\n" " uint cube_layer;\n" " uvec2 tc = uvec2(floor(sampleCube(shadowCoord, cube_layer, z) * float(size)));\n" " uvec2 pos = uvec2(cube_layer % 2u, cube_layer / 2u) * size;\n" " float distance = texelFetch(g_probes_depth, ivec2(tc + pos + light(pos)), 0).r;\n" " return linearize(distance);\n" "}\n"); str_cat(&shader_buffer, "vec4 lookup_probe(vec3 shadowCoord, out float z)\n" "{\n" " uint size = 1024u / uint(pow(2.0, float(light(lod))));\n" " uint cube_layer;\n" " uvec2 tc = uvec2(floor(sampleCube(shadowCoord, cube_layer, z) * float(size)));\n" " uvec2 pos = uvec2(cube_layer % 2u, cube_layer / 2u) * size;\n" " return textureLod(g_probes, vec2(tc + pos + light(pos)) / vec2(1024.0 * 4.0, 1024.0 * 6.0), 0.0);\n" "}\n"); str_cat(&shader_buffer, "float lookup(vec3 coord)\n" "{\n" " /* float dist = length(coord); */\n" " float z;\n" " float dist = lookup_single(coord, z);\n" " return (dist > z - 0.08) ? 1.0 : 0.0;\n" "}\n"); str_cat(&shader_buffer, "float get_shadow(vec3 vec, float point_to_light, float dist_to_eye, float depth)\n" "{\n" " vec3 taps[] = vec3[](\n" " vec3(0.068824, -0.326151, 0.3),\n" " vec3(0.248043, 0.222679, 0.3),\n" " vec3(-0.316867, 0.103472, 0.3),\n" " vec3(-0.525182, 0.410644, 0.6),\n" " vec3(-0.618219, -0.249499, 0.6),\n" " vec3(-0.093037, -0.660143, 0.6),\n" " vec3(0.525182, -0.410644, 0.6),\n" " vec3(0.618219, 0.249499, 0.6),\n"); str_cat(&shader_buffer, " vec3(0.093037, 0.660143, 0.6),\n" " vec3(0.536822, -0.843695, 1.0),\n" " vec3(0.930210, -0.367028, 1.0),\n" " vec3(0.968289, 0.249832, 1.0),\n" " vec3(0.636515, 0.771264, 1.0),\n" " vec3(0.061613, 0.998100, 1.0),\n" " vec3(-0.536822, 0.843695, 1.0),\n" " vec3(-0.930210, 0.367028, 1.0),\n" " vec3(-0.968289, -0.249832, 1.0),\n" " vec3(-0.636515, -0.771264, 1.0),\n" " vec3(-0.061613, -0.998100, 1.0)\n" " );\n"); str_cat(&shader_buffer, " float z;\n" " float ocluder_to_light = lookup_single(-vec, z);\n" " if (ocluder_to_light > z - 0.08) return 0.0;\n" " ocluder_to_light = min(z, ocluder_to_light);\n" " float dither = dither_value();\n" /* " float dither = 1.0;\n" */ " float shadow_len = min(0.3 * (point_to_light / ocluder_to_light - 1.0), 10.0);\n" " if(shadow_len > 0.001)\n" " {\n" " vec3 normal = normalize(vec);\n" " vec3 tangent = cross(normal, vec3(0.0, 1.0, 0.0));\n" " vec3 bitangent = cross(normal, tangent);\n"); str_cat(&shader_buffer, " float min_dist = 1.0;\n" " for (uint j = 0u; j < 19u; j++)\n" " {\n" " vec3 offset = taps[j] * (4.0/3.0) * dither * shadow_len;\n" " if(lookup(-vec + (offset.x * tangent + offset.y * bitangent)) > 0.5)\n" " {\n" " min_dist = offset.z;\n" " break;\n" " }\n" " }\n" " return min_dist;\n" " }\n" " return 0.0;\n" "}\n"); str_cat(&shader_buffer, /* SPHEREMAP TRANSFORM */ /* https://aras-p.info/texts/CompactNormalStorage.html */ /* vec2 encode_normal(vec3 n) */ /* { */ /* vec2 enc = normalize(n.xy) * (sqrt(-n.z*0.5+0.5)); */ /* enc = enc*0.5+0.5; */ /* return enc; */ /* } */ /* vec3 decode_normal(vec2 enc) */ /* { */ /* vec4 nn = vec4(enc, 0.0, 0.0) * vec4(2.0, 2.0, 0.0, 0.0) + vec4(-1.0, -1.0, 1.0, -1.0); */ /* float l = dot(nn.xyz, -nn.xyw); */ /* nn.z = l; */ /* nn.xy *= sqrt(l); */ /* return nn.xyz * 2.0 + vec3(0.0, 0.0, -1.0); */ /* } */ "vec2 encode_normal(vec3 n)\n" "{\n" " float p = sqrt(n.z * 8.0 + 8.0);\n" " return vec2(n.xy/p + 0.5);\n" "}\n" "vec3 decode_normal(vec2 enc)\n" "{\n" " vec2 fenc = enc * 4.0 - 2.0;\n" " float f = dot(fenc,fenc);\n" " float g = sqrt(1.0 - f / 4.0);\n" " vec3 n;\n" " n.xy = fenc * g;\n" " n.z = 1.0 - f / 2.0;\n" " return n;\n" "}\n"); str_cat(&shader_buffer, "vec3 get_position(vec3 pos)\n" "{\n" " vec4 clip_pos = vec4(pos * 2.0 - 1.0, 1.0);\n" " vec4 view_pos = camera(inv_projection) * clip_pos;\n" " return view_pos.xyz / view_pos.w;\n" "}\n"); str_cat(&shader_buffer, "vec3 get_position(sampler2D depth, vec2 pos)\n" "{\n" " return get_position(vec3(pos, textureLod(depth, pos, 0.0).r));\n" "}\n" "vec3 get_normal(sampler2D buffer)\n" "{\n" " return decode_normal(texelFetch(buffer, ivec2(gl_FragCoord.x,\n" " gl_FragCoord.y), 0).rg);\n" "}\n" "mat3 TM()\n" "{\n" " vec3 vertex_bitangent = cross(normalize(vertex_tangent), normalize(vertex_normal));\n" " return mat3(vertex_tangent, vertex_bitangent, vertex_normal);\n" "}\n"); str_cat(&shader_buffer, "vec3 get_normal(vec3 color)\n" "{\n" " vec3 norm;\n" " if(has_tex)\n" " {\n" " vec3 texcolor = color * 2.0 - 1.0;\n" " norm = TM() * texcolor;\n" " }\n" " else\n" " {\n" " norm = vertex_normal;\n" " }\n" " if(!gl_FrontFacing)\n" " {\n" " norm = -norm;\n" " }\n" " return normalize(norm);\n" "}\n"); /* TODO: should go to ssr.glsl */ str_cat(&shader_buffer, "vec2 get_proj_coord(vec3 hitCoord)\n" "{\n" " vec4 projectedCoord = camera(projection) * vec4(hitCoord, 1.0);\n" " projectedCoord.xy /= projectedCoord.w;\n" " projectedCoord.xy = projectedCoord.xy * 0.5 + 0.5;\n" " return projectedCoord.xy;\n" "}\n"); str_cat(&shader_buffer, "vec2 BinarySearchCube(vec3 dir, inout vec3 hitCoord)\n" "{\n" " float depth;\n" " vec2 pc;\n" " dir = -dir * 0.5;\n" " float search_dir = -1.0;\n" " hitCoord += dir;\n" " for(uint i = 0u; i < 8u; i++)\n" " {\n" " float z;\n" " float pd = lookup_single(hitCoord, z);\n" " float dist = pd - z;\n"); str_cat(&shader_buffer, " dir = dir * 0.5;\n" " if (sign(dist) != sign(search_dir))\n" " {\n" " dir = -dir;\n" " search_dir = -search_dir;\n" " }\n" " hitCoord += dir;\n" " }\n" " uint cube_layer;\n" " float z;\n" " return sampleCube(hitCoord, cube_layer, z);\n" "}\n"); str_cat(&shader_buffer, "vec2 RayCastCube(vec3 dir, inout vec3 hitCoord)\n" "{\n" " dir *= 0.1;\n" " float step = 0.1;\n" " for(uint i = 0u; i < 16u; ++i) {\n" " hitCoord += dir;\n" " float z;\n" " float pd = lookup_single(hitCoord, z);\n" " float dist = pd - z;\n" " if(dist < 0.0)\n" " {\n" " return BinarySearchCube(dir, hitCoord);\n" " }\n" " dir *= 1.3;\n" " step *= 1.3;\n" " }\n" " return vec2(-1.0);\n" "}\n"); str_cat(&shader_buffer, "vec2 BinarySearch(sampler2D depthmap, vec3 dir, inout vec3 hitCoord)\n" "{\n" " float depth;\n" " vec2 pc;\n" " dir = -dir * 0.5;\n" " float search_dir = -1.0;\n" " hitCoord += dir;\n" " for(uint i = 0u; i < 8u; i++)\n" " {\n" " pc = get_proj_coord(hitCoord);\n" " vec3 c_pos = get_position(depthmap, pc);\n" " float dist = hitCoord.z - c_pos.z;\n"); str_cat(&shader_buffer, " if(pc.x > 1.0 || pc.y > 1.0 || pc.x < 0.0 || pc.y < 0.0) break;\n" " dir = dir * 0.5;\n" " if (sign(dist) != sign(search_dir))\n" " {\n" " dir = -dir;\n" " search_dir = -search_dir;\n" " }\n" " hitCoord += dir;\n" " }\n" " return get_proj_coord(hitCoord);\n" "}\n"); str_cat(&shader_buffer, "vec2 RayCast(sampler2D depthmap, vec3 dir, inout vec3 hitCoord)\n" "{\n" " dir *= 0.1;\n" " float step = 0.1;\n" " for(uint i = 0u; i < 16u; ++i) {\n" " hitCoord += dir;\n" " vec2 pc = get_proj_coord(hitCoord);\n" " vec3 c_pos = get_position(depthmap, pc);\n" " float dist = hitCoord.z - c_pos.z;\n" " if(pc.x > 1.0 || pc.y > 1.0 || pc.x < 0.0 || pc.y < 0.0) break;\n" " if(dist < 0.0 /*&& length(hitCoord - c_pos) < step*/)\n" " {\n" " return BinarySearch(depthmap, dir, hitCoord);\n" " }\n" " dir *= 1.3;\n" " step *= 1.3;\n" " }\n" " return vec2(-1.0);\n" "}\n"); str_cat(&shader_buffer, "float roughnessToSpecularPower(float r)\n" "{\n" " return pow(1.0 - r, 2.0);\n" "}\n" "float specularPowerToConeAngle(float specularPower)\n" "{\n" " const float xi = 0.244;\n" " float exponent = 1.0 / (specularPower + 1.0);\n" " return acos(pow(xi, exponent));\n" "}\n"); str_cat(&shader_buffer, "#define CNST_1DIVPI 0.31830988618\n" "float isoscelesTriangleInRadius(float a, float h)\n" "{\n" " float a2 = a * a;\n" " float fh2 = 4.0 * h * h;\n" " return (a * (sqrt(a2 + fh2) - a)) / (4.0 * h);\n" "}\n" "vec3 fresnelSchlick(vec3 F0, float cosTheta)\n" "{\n" " return F0 + (vec3(1.0) - F0) * pow(1.0 - cosTheta, 5.0);\n" "}\n"); str_cat(&shader_buffer, "vec4 ssr2(sampler2D depthmap, sampler2D screen, vec4 base_color,\n" " vec2 metallic_roughness, vec3 nor)\n" "{\n" " vec2 tc = pixel_pos();\n" " vec3 pos = get_position(depthmap, tc);\n" " float perceptualRoughness = metallic_roughness.y;\n" " float metallic = metallic_roughness.x;\n" " perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);\n" " if(perceptualRoughness > 0.95) return vec4(0.0);\n" " float gloss = 1.0 - perceptualRoughness;\n" " float specularPower = roughnessToSpecularPower(perceptualRoughness);\n"); str_cat(&shader_buffer, " perceptualRoughness *= 0.3;\n" " vec3 w_pos = (camera(model) * vec4(pos, 1.0)).xyz;\n" " vec3 w_nor = (camera(model) * vec4(nor, 0.0)).xyz;\n" " vec3 c_pos = camera(pos) - w_pos;\n" " vec3 eye_dir = normalize(-c_pos);\n" " vec3 reflected = normalize(reflect(pos, nor));\n"); str_cat(&shader_buffer, " /* Ray cast */\n" " vec3 hitPos = pos.xyz; // + vec3(0.0, 0.0, rand(camPos.xz) * 0.2 - 0.1);\n" " vec2 coords = RayCast(depthmap, reflected, hitPos);\n" " vec2 dCoords = abs(vec2(0.5, 0.5) - coords) * 2.0;\n" " float screenEdgefactor = (clamp(1.0 -\n" " (pow(dCoords.x, 4.0) + pow(dCoords.y, 4.0)), 0.0, 1.0));\n" " vec3 fallback_color = vec3(0.0);\n" " vec2 deltaP = coords - texcoord;\n"); str_cat(&shader_buffer, " float adjacentLength = length(deltaP);\n" " vec2 adjacentUnit = normalize(deltaP);\n" " uint numMips = MAX_MIPS;\n" " vec4 reflect_color = vec4(0.0);\n" " float glossMult = 1.0;\n"); str_cat(&shader_buffer, " for(int i = -4; i <= 4; ++i)\n" " {\n" " float len = adjacentLength * (float(i) / 4.0) * perceptualRoughness * 0.3;\n" " vec2 samplePos = coords + vec2(adjacentUnit.y, -adjacentUnit.x) * len;\n" " float mipChannel = perceptualRoughness * adjacentLength * 40.0;\n" " glossMult = 1.0;\n" " vec4 newColor = textureLod(screen, samplePos, mipChannel).rgba;\n" " reflect_color += clamp(newColor / 15.0, 0.0, 1.0);\n" " glossMult *= gloss;\n" " }\n"); str_cat(&shader_buffer, /* " vec3 f0 = vec3(0.04);\n" */ /* " vec3 specular_color = mix(f0, base_color.rgb, metallic);\n" */ " float NdotE = clamp(dot(w_nor, -eye_dir), 0.001, 1.0);\n" " vec3 specular_color = fresnelSchlick(vec3(1.0), NdotE) * CNST_1DIVPI;\n" " float fade_on_roughness = pow(1.0 - metallic_roughness.y, 2.0);\n" " float fade = screenEdgefactor * fade_on_roughness;\n" " return vec4(mix(fallback_color,\n" " reflect_color.xyz * specular_color, fade), 1.0);\n" "}\n"); /* TODO: should go to pbr.glsl*/ /* FROM https://github.com/KhronosGroup/glTF-WebGL-PBR */ str_cat(&shader_buffer, "struct PBRInfo\n" "{\n" " float NdotL;\n" /* cos angle between normal and light direction */ " float NdotV;\n" /* cos angle between normal and view direction */ " float NdotH;\n" /* cos angle between normal and half vector */ " float LdotH;\n" /* cos angle between light direction and half vector */ " float VdotH;\n" /* cos angle between view direction and half vector */ " float perceptualRoughness;\n"/* roughness value, as authored by the model creator (input to shader) */ " float metalness;\n" /* metallic value at the surface */ " vec3 reflectance0;\n" /* full reflectance color (normal incidence angle) */ " vec3 reflectance90;\n" /* reflectance color at grazing angle */ " float alpha_roughness_sq;\n" /* roughness mapped to a more linear change in the roughness (proposed by [2]) */ " vec3 diffuse_color;\n" /* color contribution from diffuse lighting */ " vec3 specular_color;\n" /* color contribution from specular lighting */ "};\n"); str_cat(&shader_buffer, "vec3 diffuse(PBRInfo pbrInputs)\n" "{\n" " return pbrInputs.diffuse_color / M_PI;\n" "}\n" "vec3 specularReflection(PBRInfo pbrInputs)\n" "{\n" " return pbrInputs.reflectance0 + (pbrInputs.reflectance90 - pbrInputs.reflectance0) * pow(clamp(1.0 - pbrInputs.VdotH, 0.0, 1.0), 5.0);\n" "}\n"); str_cat(&shader_buffer, "float geometricOcclusion(PBRInfo pbrInputs)\n" "{\n" " float NdotL = pbrInputs.NdotL;\n" " float NdotV = pbrInputs.NdotV;\n" " float r = pbrInputs.alpha_roughness_sq;\n" " float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r + (1.0 - r) * (NdotL * NdotL)));\n" " float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r + (1.0 - r) * (NdotV * NdotV)));\n" " return attenuationL * attenuationV;\n" "}\n"); str_cat(&shader_buffer, "float microfacetDistribution(PBRInfo pbrInputs)\n" "{\n" " float roughnessSq = pbrInputs.alpha_roughness_sq;\n" " float f = (pbrInputs.NdotH * roughnessSq - pbrInputs.NdotH) * pbrInputs.NdotH + 1.0;\n" " return roughnessSq / (M_PI * f * f);\n" "}\n"); str_cat(&shader_buffer, "vec3 hsv2rgb(vec3 c)\n" "{\n" " c.x = clamp(c.x, 0.0, 1.0);\n" " vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n" " vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);\n" " return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);\n" "}\n"); str_cat(&shader_buffer, "vec3 rgb2hsv(vec3 c)\n" "{\n" " vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n" " vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));\n" " vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));\n" " float d = q.x - min(q.w, q.y);\n" " float e = 1.0e-10;\n" " return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);\n" "}\n"); str_cat(&shader_buffer, "vec3 transmittance_profile(vec3 color, float thicc)" "{\n" " float dd = -thicc * thicc;\n" " vec3 hsv = rgb2hsv(color);\n" " hsv.g *= 1.3;\n" " vec3 p = hsv2rgb(vec3(hsv.r - 0.577724, hsv.g*0.640986, hsv.b*0.649)) * exp(dd / 0.0064) +\n"); str_cat(&shader_buffer, " hsv2rgb(vec3(hsv.r - 0.505464, hsv.g*0.709302, hsv.b*0.344)) * exp(dd / 0.0484) +\n" " hsv2rgb(vec3(hsv.r - 0.234007, hsv.g, hsv.b*0.198)) * exp(dd / 0.187) +\n" " hsv2rgb(vec3(hsv.r, hsv.g*1.0, hsv.b*0.113)) * exp(dd / 0.567) +\n" " hsv2rgb(vec3(hsv.r - 0.001862, hsv.g, hsv.b*0.358)) * exp(dd / 1.99) +\n" " hsv2rgb(vec3(hsv.r, hsv.g, hsv.b * 0.078)) * exp(dd / 7.41);\n" " return p;\n" "}\n"); /* Uses Separable SSS. Copyright (C) 2011 by <NAME> and <NAME>. */ str_cat(&shader_buffer, "vec3 transmittance(vec3 surface_color, float translucency,\n" " float sssWidth, vec3 w_pos, vec3 w_nor)\n" "{\n" " float scale = 8.25 * (1.0 - translucency) / sssWidth;\n" " vec3 shrinked_pos = w_pos - 0.005 * w_nor;\n" " float d2;\n" " float d1 = lookup_single(shrinked_pos - obj_pos, d2);\n" " float thicc = scale * abs(d1 - d2);\n" " return transmittance_profile(surface_color, thicc)\n" " * clamp(0.3 + dot(shrinked_pos - obj_pos, w_nor), 0.0, 1.0);\n" "}\n"); str_cat(&shader_buffer, "vec4 pbr(vec4 base_color, vec2 metallic_roughness,\n" " vec3 light_color, vec3 light_dir, vec3 c_pos,\n" " vec3 c_nor)\n" "{\n" " /* Metallic and Roughness material properties are packed together\n" " * In glTF, these factors can be specified by fixed scalar values\n" " * or from a metallic-roughness map */\n" " float perceptualRoughness = metallic_roughness.y;\n" " float metallic = metallic_roughness.x;\n" " perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);\n" " metallic = clamp(metallic, 0.0, 1.0);\n"); str_cat(&shader_buffer, " /* Roughness is authored as perceptual roughness; as is convention,\n" " * convert to material roughness by squaring the perceptual roughness. */\n" " float alpha_roughness_sq = perceptualRoughness * perceptualRoughness;\n" " alpha_roughness_sq = alpha_roughness_sq * alpha_roughness_sq;\n" " vec3 f0 = vec3(0.04);\n" " vec3 diffuse_color = base_color.rgb * (vec3(1.0) - f0);\n" " diffuse_color *= 1.0 - metallic;\n" " vec3 specular_color = mix(f0, base_color.rgb, metallic);\n"); str_cat(&shader_buffer, " float reflectance = max(max(specular_color.r, specular_color.g), specular_color.b);\n" /* For typical incident reflectance range (between 4% to 100%) set * the grazing reflectance to 100% for typical fresnel effect. */ /* For very low reflectance range on highly diffuse * objects (below 4%), incrementally reduce grazing reflecance to 0%. */ " float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);\n" " vec3 specularEnvironmentR0 = specular_color.rgb;\n" " vec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0) * reflectance90;\n"); str_cat(&shader_buffer, " vec3 v = normalize(-c_pos); /* Vector from surface point to camera */\n" " vec3 l = normalize(light_dir); /* Vector from surface point to light */\n" " vec3 h = normalize(l+v); /* Half vector between both l and v */\n"); str_cat(&shader_buffer, " float NdotL = clamp(dot(c_nor, l), 0.001, 1.0);\n" " float NdotV = clamp(abs(dot(c_nor, v)), 0.001, 1.0);\n" " float NdotH = clamp(dot(c_nor, h), 0.0, 1.0);\n" " float LdotH = clamp(dot(l, h), 0.0, 1.0);\n" " float VdotH = clamp(dot(v, h), 0.0, 1.0);\n"); str_cat(&shader_buffer, " PBRInfo pbrInputs = PBRInfo( NdotL, NdotV, NdotH, LdotH, VdotH,\n" " perceptualRoughness, metallic, specularEnvironmentR0,\n" " specularEnvironmentR90, alpha_roughness_sq, diffuse_color,\n" " specular_color);\n" " /* Calculate the shading terms for the microfacet specular shading model */\n" " vec3 F = specularReflection(pbrInputs);\n" " float G = geometricOcclusion(pbrInputs);\n" " float D = microfacetDistribution(pbrInputs);\n"); str_cat(&shader_buffer, " /* Calculation of analytical lighting contribution */\n" " vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInputs);\n" " vec3 specContrib = F * G * D / (4.0 * NdotL * NdotV);\n" " /* Obtain final intensity as reflectance (BRDF) scaled by the\n" " * energy of the light (cosine law) */\n" " vec3 color = NdotL * light_color * (diffuseContrib + specContrib);\n" " return vec4(pow(color,vec3(1.0/2.2)), base_color.a);\n" "}\n"); str_cat(&shader_buffer, "#endif\n"); shader_add_source("candle:common.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_volum() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "#include \"candle:common.glsl\"\n" "layout (location = 0) out vec4 FragColor;\n" "BUFFER {\n" " sampler2D depth;\n" " sampler2D albedo;\n" "} gbuffer;\n"); str_cat(&shader_buffer, "void main(void)\n" "{\n" " if (light(volumetric) == 0.0) discard;\n" " float depth = textureLod(gbuffer.depth, pixel_pos(), 0.0).r;\n" " if(gl_FragCoord.z < depth)\n" " {\n" " depth = gl_FragCoord.z;\n" " }\n" " float intensity = abs(light(volumetric));\n" " bool inverted = light(volumetric) < 0.0;\n"); str_cat(&shader_buffer, " vec3 c_pos = get_position(vec3(pixel_pos(), depth));\n" " vec3 w_cam = camera(pos);\n" " vec3 w_pos = (camera(model) * vec4(c_pos, 1.0)).xyz;\n" " float color = 0.0;\n" " int iterations = 32;\n" " vec3 norm_dir = normalize(w_cam - w_pos);\n" " vec3 dir = norm_dir * ((2.0 * light(radius)) / float(iterations));\n" " w_pos += dir * dither_value();\n" " bool passed = false;\n"); str_cat(&shader_buffer, " for (int i = 0; i < iterations; i++)\n" " {\n" " w_pos += dir;\n" " vec3 dif = w_pos - obj_pos;\n" " float len = length(dif);\n" " float l = len / light(radius);\n" " float attenuation = ((3.0 - l*3.0) / (1.0+1.3*(pow(l*3.0-0.1, 2.0))))/3.0;\n" " attenuation = clamp(attenuation, 0.0, 1.0);\n" " if (attenuation > 0.0) {\n" " passed = true;\n" " float z;\n" " float Z = lookup_single(dif, z);\n" " bool in_light = Z >= z;\n"); str_cat(&shader_buffer, " in_light = inverted ? !in_light : in_light;\n" " color += in_light ? attenuation * (1.0f - dot(norm_dir, dif / len)) : 0.0;\n" " }\n" " else if (passed)\n" " {\n" " break;\n" " }\n" " }\n" " FragColor = vec4(light(color).rgb * (color / float(iterations)) * intensity, 1.);\n" "}\n"); shader_add_source("candle:volum.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_gaussian() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "layout (location = 0) out vec4 FragColor;\n" "uniform bool horizontal;\n" "uniform float weight[6] = float[] (0.382925, 0.24173, 0.060598, 0.005977, 0.000229, 0.000003);\n" "BUFFER {\n" " sampler2D color;\n" "} buf;\n"); str_cat(&shader_buffer, "void main(void)\n" "{\n" " ivec2 tc = ivec2(gl_FragCoord);\n" " vec3 c = texelFetch(buf.color, pp, 0).rgb * weight[0];\n" " if(horizontal)\n" " {\n" " for(int i = 1; i < 6; ++i)\n" " {\n" " ivec2 off = ivec2(i, 0.0);\n" " c += texelFetch(buf.color, pp + off, 0).rgb * weight[i];\n" " c += texelFetch(buf.color, pp - off, 0).rgb * weight[i];\n" " }\n" " }\n"); str_cat(&shader_buffer, " else\n" " {\n" " for(int i = 1; i < 6; ++i)\n" " {\n" " ivec2 off = ivec2(0.0, * i);\n" " c += texelFetch(buf.color, pp + off, 0).rgb * weight[i];\n" " c += texelFetch(buf.color, pp - off, 0).rgb * weight[i];\n" " }\n" " }\n" " FragColor = vec4(c, 0.4);\n" "}\n"); shader_add_source("candle:gaussian.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_marching() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "uniform sampler3D values;\n" "/* uniform isampler2D triTableTex; */\n" "/* uniform float g_iso_level; */\n" "float g_iso_level = 0.9;\n" "float grid_size = 0.3;\n"); str_cat(&shader_buffer, "const vec3 vert_offsets[8] = vec3[](\n" " vec3(0.0, 0.0, 0.0),\n" " vec3(1.0, 0.0, 0.0),\n" " vec3(1.0, 1.0, 0.0),\n" " vec3(0.0, 1.0, 0.0),\n" " vec3(0.0, 0.0, 1.0),\n" " vec3(1.0, 0.0, 1.0),\n" " vec3(1.0, 1.0, 1.0),\n" " vec3(0.0, 1.0, 1.0)\n" ");\n"); str_cat(&shader_buffer, "#define b3(r,g,b) (ivec3(r, g, b))\n" "#define z3 ivec3(-1, -1, -1)\n" "ivec3 tri_table[256 * 5] = ivec3[](\n" " z3, z3, z3, z3, z3, \n" " b3( 0, 8, 3), z3, z3, z3, z3, \n" " b3( 0, 1, 9), z3, z3, z3, z3, \n" " b3( 1, 8, 3), b3( 9, 8, 1), z3, z3, z3, \n" " b3( 1, 2, 10), z3, z3, z3, z3, \n"); str_cat(&shader_buffer, " b3( 0, 8, 3), b3( 1, 2, 10), z3, z3, z3, \n" " b3( 9, 2, 10), b3( 0, 2, 9), z3, z3, z3, \n" " b3( 2, 8, 3), b3( 2, 10, 8), b3(10, 9, 8), z3, z3, \n" " b3( 3, 11, 2), z3, z3, z3, z3, \n" " b3( 0, 11, 2), b3( 8, 11, 0), z3, z3, z3, \n" " b3( 1, 9, 0), b3( 2, 3, 11), z3, z3, z3, \n"); str_cat(&shader_buffer, " b3( 1, 11, 2), b3( 1, 9, 11), b3( 9, 8, 11), z3, z3, \n" " b3( 3, 10, 1), b3(11, 10, 3), z3, z3, z3, \n" " b3( 0, 10, 1), b3( 0, 8, 10), b3( 8, 11, 10), z3, z3, \n" " b3( 3, 9, 0), b3( 3, 11, 9), b3(11, 10, 9), z3, z3, \n" " b3( 9, 8, 10), b3(10, 8, 11), z3, z3, z3, \n" " b3( 4, 7, 8), z3, z3, z3, z3, \n"); str_cat(&shader_buffer, " b3( 4, 3, 0), b3( 7, 3, 4), z3, z3, z3, \n" " b3( 0, 1, 9), b3( 8, 4, 7), z3, z3, z3, \n" " b3( 4, 1, 9), b3( 4, 7, 1), b3( 7, 3, 1), z3, z3, \n" " b3( 1, 2, 10), b3( 8, 4, 7), z3, z3, z3, \n" " b3( 3, 4, 7), b3( 3, 0, 4), b3( 1, 2, 10), z3, z3, \n" " b3( 9, 2, 10), b3( 9, 0, 2), b3( 8, 4, 7), z3, z3, \n"); str_cat(&shader_buffer, " b3( 2, 10, 9), b3( 2, 9, 7), b3( 2, 7, 3), b3( 7, 9, 4), z3, \n" " b3( 8, 4, 7), b3( 3, 11, 2), z3, z3, z3, \n" " b3(11, 4, 7), b3(11, 2, 4), b3( 2, 0, 4), z3, z3, \n" " b3( 9, 0, 1), b3( 8, 4, 7), b3( 2, 3, 11), z3, z3, \n" " b3( 4, 7, 11), b3( 9, 4, 11), b3( 9, 11, 2), b3( 9, 2, 1), z3, \n" " b3( 3, 10, 1), b3( 3, 11, 10), b3( 7, 8, 4), z3, z3, \n"); str_cat(&shader_buffer, " b3( 1, 11, 10), b3( 1, 4, 11), b3( 1, 0, 4), b3( 7, 11, 4), z3, \n" " b3( 4, 7, 8), b3( 9, 0, 11), b3( 9, 11, 10), b3(11, 0, 3), z3, \n" " b3( 4, 7, 11), b3( 4, 11, 9), b3( 9, 11, 10), z3, z3, \n" " b3( 9, 5, 4), z3, z3, z3, z3, \n" " b3( 9, 5, 4), b3( 0, 8, 3), z3, z3, z3, \n" " b3( 0, 5, 4), b3( 1, 5, 0), z3, z3, z3, \n"); str_cat(&shader_buffer, " b3( 8, 5, 4), b3( 8, 3, 5), b3( 3, 1, 5), z3, z3, \n" " b3( 1, 2, 10), b3( 9, 5, 4), z3, z3, z3, \n" " b3( 3, 0, 8), b3( 1, 2, 10), b3( 4, 9, 5), z3, z3, \n" " b3( 5, 2, 10), b3( 5, 4, 2), b3( 4, 0, 2), z3, z3, \n" " b3( 2, 10, 5), b3( 3, 2, 5), b3( 3, 5, 4), b3( 3, 4, 8), z3, \n" " b3( 9, 5, 4), b3( 2, 3, 11), z3, z3, z3, \n"); str_cat(&shader_buffer, " b3( 0, 11, 2), b3( 0, 8, 11), b3( 4, 9, 5), z3, z3, \n" " b3( 0, 5, 4), b3( 0, 1, 5), b3( 2, 3, 11), z3, z3, \n" " b3( 2, 1, 5), b3( 2, 5, 8), b3( 2, 8, 11), b3( 4, 8, 5), z3, \n" " b3(10, 3, 11), b3(10, 1, 3), b3( 9, 5, 4), z3, z3, \n" " b3( 4, 9, 5), b3( 0, 8, 1), b3( 8, 10, 1), b3( 8, 11, 10), z3, \n" " b3( 5, 4, 0), b3( 5, 0, 11), b3( 5, 11, 10), b3(11, 0, 3), z3, \n"); str_cat(&shader_buffer, " b3( 5, 4, 8), b3( 5, 8, 10), b3(10, 8, 11), z3, z3, \n" " b3( 9, 7, 8), b3( 5, 7, 9), z3, z3, z3, \n" " b3( 9, 3, 0), b3( 9, 5, 3), b3( 5, 7, 3), z3, z3, \n" " b3( 0, 7, 8), b3( 0, 1, 7), b3( 1, 5, 7), z3, z3, \n" " b3( 1, 5, 3), b3( 3, 5, 7), z3, z3, z3, \n" " b3( 9, 7, 8), b3( 9, 5, 7), b3(10, 1, 2), z3, z3, \n"); str_cat(&shader_buffer, " b3(10, 1, 2), b3( 9, 5, 0), b3( 5, 3, 0), b3( 5, 7, 3), z3, \n" " b3( 8, 0, 2), b3( 8, 2, 5), b3( 8, 5, 7), b3(10, 5, 2), z3, \n" " b3( 2, 10, 5), b3( 2, 5, 3), b3( 3, 5, 7), z3, z3, \n" " b3( 7, 9, 5), b3( 7, 8, 9), b3( 3, 11, 2), z3, z3, \n" " b3( 9, 5, 7), b3( 9, 7, 2), b3( 9, 2, 0), b3( 2, 7, 11), z3, \n" " b3( 2, 3, 11), b3( 0, 1, 8), b3( 1, 7, 8), b3( 1, 5, 7), z3, \n"); str_cat(&shader_buffer, " b3(11, 2, 1), b3(11, 1, 7), b3( 7, 1, 5), z3, z3, \n" " b3( 9, 5, 8), b3( 8, 5, 7), b3(10, 1, 3), b3(10, 3, 11), z3, \n" " b3( 5, 7, 0), b3( 5, 0, 9), b3( 7, 11, 0), b3( 1, 0, 10), b3(11, 10, 0),\n" " b3(11, 10, 0), b3(11, 0, 3), b3(10, 5, 0), b3( 8, 0, 7), b3( 5, 7, 0),\n" " b3(11, 10, 5), b3( 7, 11, 5), z3, z3, z3, \n" " b3(10, 6, 5), z3, z3, z3, z3, \n"); str_cat(&shader_buffer, " b3( 0, 8, 3), b3( 5, 10, 6), z3, z3, z3, \n" " b3( 9, 0, 1), b3( 5, 10, 6), z3, z3, z3, \n" " b3( 1, 8, 3), b3( 1, 9, 8), b3( 5, 10, 6), z3, z3, \n" " b3( 1, 6, 5), b3( 2, 6, 1), z3, z3, z3, \n" " b3( 1, 6, 5), b3( 1, 2, 6), b3( 3, 0, 8), z3, z3, \n" " b3( 9, 6, 5), b3( 9, 0, 6), b3( 0, 2, 6), z3, z3, \n"); str_cat(&shader_buffer, " b3( 5, 9, 8), b3( 5, 8, 2), b3( 5, 2, 6), b3( 3, 2, 8), z3, \n" " b3( 2, 3, 11), b3(10, 6, 5), z3, z3, z3, \n" " b3(11, 0, 8), b3(11, 2, 0), b3(10, 6, 5), z3, z3, \n" " b3( 0, 1, 9), b3( 2, 3, 11), b3( 5, 10, 6), z3, z3, \n" " b3( 5, 10, 6), b3( 1, 9, 2), b3( 9, 11, 2), b3( 9, 8, 11), z3, \n" " b3( 6, 3, 11), b3( 6, 5, 3), b3( 5, 1, 3), z3, z3, \n"); str_cat(&shader_buffer, " b3( 0, 8, 11), b3( 0, 11, 5), b3( 0, 5, 1), b3( 5, 11, 6), z3, \n" " b3( 3, 11, 6), b3( 0, 3, 6), b3( 0, 6, 5), b3( 0, 5, 9), z3, \n" " b3( 6, 5, 9), b3( 6, 9, 11), b3(11, 9, 8), z3, z3, \n" " b3( 5, 10, 6), b3( 4, 7, 8), z3, z3, z3, \n" " b3( 4, 3, 0), b3( 4, 7, 3), b3( 6, 5, 10), z3, z3, \n" " b3( 1, 9, 0), b3( 5, 10, 6), b3( 8, 4, 7), z3, z3, \n"); str_cat(&shader_buffer, " b3(10, 6, 5), b3( 1, 9, 7), b3( 1, 7, 3), b3( 7, 9, 4), z3, \n" " b3( 6, 1, 2), b3( 6, 5, 1), b3( 4, 7, 8), z3, z3, \n" " b3( 1, 2, 5), b3( 5, 2, 6), b3( 3, 0, 4), b3( 3, 4, 7), z3, \n" " b3( 8, 4, 7), b3( 9, 0, 5), b3( 0, 6, 5), b3( 0, 2, 6), z3, \n" " b3( 7, 3, 9), b3( 7, 9, 4), b3( 3, 2, 9), b3( 5, 9, 6), b3( 2, 6, 9),\n" " b3( 3, 11, 2), b3( 7, 8, 4), b3(10, 6, 5), z3, z3, \n"); str_cat(&shader_buffer, " b3( 5, 10, 6), b3( 4, 7, 2), b3( 4, 2, 0), b3( 2, 7, 11), z3, \n" " b3( 0, 1, 9), b3( 4, 7, 8), b3( 2, 3, 11), b3( 5, 10, 6), z3, \n" " b3( 9, 2, 1), b3( 9, 11, 2), b3( 9, 4, 11), b3( 7, 11, 4), b3( 5, 10, 6),\n" " b3( 8, 4, 7), b3( 3, 11, 5), b3( 3, 5, 1), b3( 5, 11, 6), z3, \n" " b3( 5, 1, 11), b3( 5, 11, 6), b3( 1, 0, 11), b3( 7, 11, 4), b3( 0, 4, 11),\n" " b3( 0, 5, 9), b3( 0, 6, 5), b3( 0, 3, 6), b3(11, 6, 3), b3( 8, 4, 7),\n"); str_cat(&shader_buffer, " b3( 6, 5, 9), b3( 6, 9, 11), b3( 4, 7, 9), b3( 7, 11, 9), z3, \n" " b3(10, 4, 9), b3( 6, 4, 10), z3, z3, z3, \n" " b3( 4, 10, 6), b3( 4, 9, 10), b3( 0, 8, 3), z3, z3, \n" " b3(10, 0, 1), b3(10, 6, 0), b3( 6, 4, 0), z3, z3, \n" " b3( 8, 3, 1), b3( 8, 1, 6), b3( 8, 6, 4), b3( 6, 1, 10), z3, \n" " b3( 1, 4, 9), b3( 1, 2, 4), b3( 2, 6, 4), z3, z3, \n"); str_cat(&shader_buffer, " b3( 3, 0, 8), b3( 1, 2, 9), b3( 2, 4, 9), b3( 2, 6, 4), z3, \n" " b3( 0, 2, 4), b3( 4, 2, 6), z3, z3, z3, \n" " b3( 8, 3, 2), b3( 8, 2, 4), b3( 4, 2, 6), z3, z3, \n" " b3(10, 4, 9), b3(10, 6, 4), b3(11, 2, 3), z3, z3, \n" " b3( 0, 8, 2), b3( 2, 8, 11), b3( 4, 9, 10), b3( 4, 10, 6), z3, \n" " b3( 3, 11, 2), b3( 0, 1, 6), b3( 0, 6, 4), b3( 6, 1, 10), z3, \n"); str_cat(&shader_buffer, " b3( 6, 4, 1), b3( 6, 1, 10), b3( 4, 8, 1), b3( 2, 1, 11), b3( 8, 11, 1),\n" " b3( 9, 6, 4), b3( 9, 3, 6), b3( 9, 1, 3), b3(11, 6, 3), z3, \n" " b3( 8, 11, 1), b3( 8, 1, 0), b3(11, 6, 1), b3( 9, 1, 4), b3( 6, 4, 1),\n" " b3( 3, 11, 6), b3( 3, 6, 0), b3( 0, 6, 4), z3, z3, \n" " b3( 6, 4, 8), b3(11, 6, 8), z3, z3, z3, \n" " b3( 7, 10, 6), b3( 7, 8, 10), b3( 8, 9, 10), z3, z3, \n"); str_cat(&shader_buffer, " b3( 0, 7, 3), b3( 0, 10, 7), b3( 0, 9, 10), b3( 6, 7, 10), z3, \n" " b3(10, 6, 7), b3( 1, 10, 7), b3( 1, 7, 8), b3( 1, 8, 0), z3, \n" " b3(10, 6, 7), b3(10, 7, 1), b3( 1, 7, 3), z3, z3, \n" " b3( 1, 2, 6), b3( 1, 6, 8), b3( 1, 8, 9), b3( 8, 6, 7), z3, \n" " b3( 2, 6, 9), b3( 2, 9, 1), b3( 6, 7, 9), b3( 0, 9, 3), b3( 7, 3, 9),\n" " b3( 7, 8, 0), b3( 7, 0, 6), b3( 6, 0, 2), z3, z3, \n"); str_cat(&shader_buffer, " b3( 7, 3, 2), b3( 6, 7, 2), z3, z3, z3, \n" " b3( 2, 3, 11), b3(10, 6, 8), b3(10, 8, 9), b3( 8, 6, 7), z3, \n" " b3( 2, 0, 7), b3( 2, 7, 11), b3( 0, 9, 7), b3( 6, 7, 10), b3( 9, 10, 7),\n" " b3( 1, 8, 0), b3( 1, 7, 8), b3( 1, 10, 7), b3( 6, 7, 10), b3( 2, 3, 11),\n" " b3(11, 2, 1), b3(11, 1, 7), b3(10, 6, 1), b3( 6, 7, 1), z3, \n" " b3( 8, 9, 6), b3( 8, 6, 7), b3( 9, 1, 6), b3(11, 6, 3), b3( 1, 3, 6),\n"); str_cat(&shader_buffer, " b3( 0, 9, 1), b3(11, 6, 7), z3, z3, z3, \n" " b3( 7, 8, 0), b3( 7, 0, 6), b3( 3, 11, 0), b3(11, 6, 0), z3, \n" " b3( 7, 11, 6), z3, z3, z3, z3, \n" " b3( 7, 6, 11), z3, z3, z3, z3, \n" " b3( 3, 0, 8), b3(11, 7, 6), z3, z3, z3, \n" " b3( 0, 1, 9), b3(11, 7, 6), z3, z3, z3, \n"); str_cat(&shader_buffer, " b3( 8, 1, 9), b3( 8, 3, 1), b3(11, 7, 6), z3, z3, \n" " b3(10, 1, 2), b3( 6, 11, 7), z3, z3, z3, \n" " b3( 1, 2, 10), b3( 3, 0, 8), b3( 6, 11, 7), z3, z3, \n" " b3( 2, 9, 0), b3( 2, 10, 9), b3( 6, 11, 7), z3, z3, \n" " b3( 6, 11, 7), b3( 2, 10, 3), b3(10, 8, 3), b3(10, 9, 8), z3, \n" " b3( 7, 2, 3), b3( 6, 2, 7), z3, z3, z3, \n"); str_cat(&shader_buffer, " b3( 7, 0, 8), b3( 7, 6, 0), b3( 6, 2, 0), z3, z3, \n" " b3( 2, 7, 6), b3( 2, 3, 7), b3( 0, 1, 9), z3, z3, \n" " b3( 1, 6, 2), b3( 1, 8, 6), b3( 1, 9, 8), b3( 8, 7, 6), z3, \n" " b3(10, 7, 6), b3(10, 1, 7), b3( 1, 3, 7), z3, z3, \n" " b3(10, 7, 6), b3( 1, 7, 10), b3( 1, 8, 7), b3( 1, 0, 8), z3, \n" " b3( 0, 3, 7), b3( 0, 7, 10), b3( 0, 10, 9), b3( 6, 10, 7), z3, \n"); str_cat(&shader_buffer, " b3( 7, 6, 10), b3( 7, 10, 8), b3( 8, 10, 9), z3, z3, \n" " b3( 6, 8, 4), b3(11, 8, 6), z3, z3, z3, \n" " b3( 3, 6, 11), b3( 3, 0, 6), b3( 0, 4, 6), z3, z3, \n" " b3( 8, 6, 11), b3( 8, 4, 6), b3( 9, 0, 1), z3, z3, \n" " b3( 9, 4, 6), b3( 9, 6, 3), b3( 9, 3, 1), b3(11, 3, 6), z3, \n" " b3( 6, 8, 4), b3( 6, 11, 8), b3( 2, 10, 1), z3, z3, \n"); str_cat(&shader_buffer, " b3( 1, 2, 10), b3( 3, 0, 11), b3( 0, 6, 11), b3( 0, 4, 6), z3, \n" " b3( 4, 11, 8), b3( 4, 6, 11), b3( 0, 2, 9), b3( 2, 10, 9), z3, \n" " b3(10, 9, 3), b3(10, 3, 2), b3( 9, 4, 3), b3(11, 3, 6), b3( 4, 6, 3),\n" " b3( 8, 2, 3), b3( 8, 4, 2), b3( 4, 6, 2), z3, z3, \n" " b3( 0, 4, 2), b3( 4, 6, 2), z3, z3, z3, \n" " b3( 1, 9, 0), b3( 2, 3, 4), b3( 2, 4, 6), b3( 4, 3, 8), z3, \n"); str_cat(&shader_buffer, " b3( 1, 9, 4), b3( 1, 4, 2), b3( 2, 4, 6), z3, z3, \n" " b3( 8, 1, 3), b3( 8, 6, 1), b3( 8, 4, 6), b3( 6, 10, 1), z3, \n" " b3(10, 1, 0), b3(10, 0, 6), b3( 6, 0, 4), z3, z3, \n" " b3( 4, 6, 3), b3( 4, 3, 8), b3( 6, 10, 3), b3( 0, 3, 9), b3(10, 9, 3),\n" " b3(10, 9, 4), b3( 6, 10, 4), z3, z3, z3, \n" " b3( 4, 9, 5), b3( 7, 6, 11), z3, z3, z3, \n"); str_cat(&shader_buffer, " b3( 0, 8, 3), b3( 4, 9, 5), b3(11, 7, 6), z3, z3, \n" " b3( 5, 0, 1), b3( 5, 4, 0), b3( 7, 6, 11), z3, z3, \n" " b3(11, 7, 6), b3( 8, 3, 4), b3( 3, 5, 4), b3( 3, 1, 5), z3, \n" " b3( 9, 5, 4), b3(10, 1, 2), b3( 7, 6, 11), z3, z3, \n" " b3( 6, 11, 7), b3( 1, 2, 10), b3( 0, 8, 3), b3( 4, 9, 5), z3, \n" " b3( 7, 6, 11), b3( 5, 4, 10), b3( 4, 2, 10), b3( 4, 0, 2), z3, \n"); str_cat(&shader_buffer, " b3( 3, 4, 8), b3( 3, 5, 4), b3( 3, 2, 5), b3(10, 5, 2), b3(11, 7, 6),\n" " b3( 7, 2, 3), b3( 7, 6, 2), b3( 5, 4, 9), z3, z3, \n" " b3( 9, 5, 4), b3( 0, 8, 6), b3( 0, 6, 2), b3( 6, 8, 7), z3, \n" " b3( 3, 6, 2), b3( 3, 7, 6), b3( 1, 5, 0), b3( 5, 4, 0), z3, \n" " b3( 6, 2, 8), b3( 6, 8, 7), b3( 2, 1, 8), b3( 4, 8, 5), b3( 1, 5, 8),\n" " b3( 9, 5, 4), b3(10, 1, 6), b3( 1, 7, 6), b3( 1, 3, 7), z3, \n"); str_cat(&shader_buffer, " b3( 1, 6, 10), b3( 1, 7, 6), b3( 1, 0, 7), b3( 8, 7, 0), b3( 9, 5, 4),\n" " b3( 4, 0, 10), b3( 4, 10, 5), b3( 0, 3, 10), b3( 6, 10, 7), b3( 3, 7, 10),\n" " b3( 7, 6, 10), b3( 7, 10, 8), b3( 5, 4, 10), b3( 4, 8, 10), z3, \n" " b3( 6, 9, 5), b3( 6, 11, 9), b3(11, 8, 9), z3, z3, \n" " b3( 3, 6, 11), b3( 0, 6, 3), b3( 0, 5, 6), b3( 0, 9, 5), z3, \n" " b3( 0, 11, 8), b3( 0, 5, 11), b3( 0, 1, 5), b3( 5, 6, 11), z3, \n"); str_cat(&shader_buffer, " b3( 6, 11, 3), b3( 6, 3, 5), b3( 5, 3, 1), z3, z3, \n" " b3( 1, 2, 10), b3( 9, 5, 11), b3( 9, 11, 8), b3(11, 5, 6), z3, \n" " b3( 0, 11, 3), b3( 0, 6, 11), b3( 0, 9, 6), b3( 5, 6, 9), b3( 1, 2, 10),\n" " b3(11, 8, 5), b3(11, 5, 6), b3( 8, 0, 5), b3(10, 5, 2), b3( 0, 2, 5),\n" " b3( 6, 11, 3), b3( 6, 3, 5), b3( 2, 10, 3), b3(10, 5, 3), z3, \n" " b3( 5, 8, 9), b3( 5, 2, 8), b3( 5, 6, 2), b3( 3, 8, 2), z3, \n"); str_cat(&shader_buffer, " b3( 9, 5, 6), b3( 9, 6, 0), b3( 0, 6, 2), z3, z3, \n" " b3( 1, 5, 8), b3( 1, 8, 0), b3( 5, 6, 8), b3( 3, 8, 2), b3( 6, 2, 8),\n" " b3( 1, 5, 6), b3( 2, 1, 6), z3, z3, z3, \n" " b3( 1, 3, 6), b3( 1, 6, 10), b3( 3, 8, 6), b3( 5, 6, 9), b3( 8, 9, 6),\n" " b3(10, 1, 0), b3(10, 0, 6), b3( 9, 5, 0), b3( 5, 6, 0), z3, \n" " b3( 0, 3, 8), b3( 5, 6, 10), z3, z3, z3, \n"); str_cat(&shader_buffer, " b3(10, 5, 6), z3, z3, z3, z3, \n" " b3(11, 5, 10), b3( 7, 5, 11), z3, z3, z3, \n" " b3(11, 5, 10), b3(11, 7, 5), b3( 8, 3, 0), z3, z3, \n" " b3( 5, 11, 7), b3( 5, 10, 11), b3( 1, 9, 0), z3, z3, \n" " b3(10, 7, 5), b3(10, 11, 7), b3( 9, 8, 1), b3( 8, 3, 1), z3, \n" " b3(11, 1, 2), b3(11, 7, 1), b3( 7, 5, 1), z3, z3, \n"); str_cat(&shader_buffer, " b3( 0, 8, 3), b3( 1, 2, 7), b3( 1, 7, 5), b3( 7, 2, 11), z3, \n" " b3( 9, 7, 5), b3( 9, 2, 7), b3( 9, 0, 2), b3( 2, 11, 7), z3, \n" " b3( 7, 5, 2), b3( 7, 2, 11), b3( 5, 9, 2), b3( 3, 2, 8), b3( 9, 8, 2),\n" " b3( 2, 5, 10), b3( 2, 3, 5), b3( 3, 7, 5), z3, z3, \n" " b3( 8, 2, 0), b3( 8, 5, 2), b3( 8, 7, 5), b3(10, 2, 5), z3, \n" " b3( 9, 0, 1), b3( 5, 10, 3), b3( 5, 3, 7), b3( 3, 10, 2), z3, \n"); str_cat(&shader_buffer, " b3( 9, 8, 2), b3( 9, 2, 1), b3( 8, 7, 2), b3(10, 2, 5), b3( 7, 5, 2),\n" " b3( 1, 3, 5), b3( 3, 7, 5), z3, z3, z3, \n" " b3( 0, 8, 7), b3( 0, 7, 1), b3( 1, 7, 5), z3, z3, \n" " b3( 9, 0, 3), b3( 9, 3, 5), b3( 5, 3, 7), z3, z3, \n" " b3( 9, 8, 7), b3( 5, 9, 7), z3, z3, z3, \n" " b3( 5, 8, 4), b3( 5, 10, 8), b3(10, 11, 8), z3, z3, \n"); str_cat(&shader_buffer, " b3( 5, 0, 4), b3( 5, 11, 0), b3( 5, 10, 11), b3(11, 3, 0), z3, \n" " b3( 0, 1, 9), b3( 8, 4, 10), b3( 8, 10, 11), b3(10, 4, 5), z3, \n" " b3(10, 11, 4), b3(10, 4, 5), b3(11, 3, 4), b3( 9, 4, 1), b3( 3, 1, 4),\n" " b3( 2, 5, 1), b3( 2, 8, 5), b3( 2, 11, 8), b3( 4, 5, 8), z3, \n" " b3( 0, 4, 11), b3( 0, 11, 3), b3( 4, 5, 11), b3( 2, 11, 1), b3( 5, 1, 11),\n" " b3( 0, 2, 5), b3( 0, 5, 9), b3( 2, 11, 5), b3( 4, 5, 8), b3(11, 8, 5),\n"); str_cat(&shader_buffer, " b3( 9, 4, 5), b3( 2, 11, 3), z3, z3, z3, \n" " b3( 2, 5, 10), b3( 3, 5, 2), b3( 3, 4, 5), b3( 3, 8, 4), z3, \n" " b3( 5, 10, 2), b3( 5, 2, 4), b3( 4, 2, 0), z3, z3, \n" " b3( 3, 10, 2), b3( 3, 5, 10), b3( 3, 8, 5), b3( 4, 5, 8), b3( 0, 1, 9),\n" " b3( 5, 10, 2), b3( 5, 2, 4), b3( 1, 9, 2), b3( 9, 4, 2), z3, \n" " b3( 8, 4, 5), b3( 8, 5, 3), b3( 3, 5, 1), z3, z3, \n"); str_cat(&shader_buffer, " b3( 0, 4, 5), b3( 1, 0, 5), z3, z3, z3, \n" " b3( 8, 4, 5), b3( 8, 5, 3), b3( 9, 0, 5), b3( 0, 3, 5), z3, \n" " b3( 9, 4, 5), z3, z3, z3, z3, \n" " b3( 4, 11, 7), b3( 4, 9, 11), b3( 9, 10, 11), z3, z3, \n" " b3( 0, 8, 3), b3( 4, 9, 7), b3( 9, 11, 7), b3( 9, 10, 11), z3, \n" " b3( 1, 10, 11), b3( 1, 11, 4), b3( 1, 4, 0), b3( 7, 4, 11), z3, \n"); str_cat(&shader_buffer, " b3( 3, 1, 4), b3( 3, 4, 8), b3( 1, 10, 4), b3( 7, 4, 11), b3(10, 11, 4),\n" " b3( 4, 11, 7), b3( 9, 11, 4), b3( 9, 2, 11), b3( 9, 1, 2), z3, \n" " b3( 9, 7, 4), b3( 9, 11, 7), b3( 9, 1, 11), b3( 2, 11, 1), b3( 0, 8, 3),\n" " b3(11, 7, 4), b3(11, 4, 2), b3( 2, 4, 0), z3, z3, \n" " b3(11, 7, 4), b3(11, 4, 2), b3( 8, 3, 4), b3( 3, 2, 4), z3, \n" " b3( 2, 9, 10), b3( 2, 7, 9), b3( 2, 3, 7), b3( 7, 4, 9), z3, \n"); str_cat(&shader_buffer, " b3( 9, 10, 7), b3( 9, 7, 4), b3(10, 2, 7), b3( 8, 7, 0), b3( 2, 0, 7),\n" " b3( 3, 7, 10), b3( 3, 10, 2), b3( 7, 4, 10), b3( 1, 10, 0), b3( 4, 0, 10),\n" " b3( 1, 10, 2), b3( 8, 7, 4), z3, z3, z3, \n" " b3( 4, 9, 1), b3( 4, 1, 7), b3( 7, 1, 3), z3, z3, \n" " b3( 4, 9, 1), b3( 4, 1, 7), b3( 0, 8, 1), b3( 8, 7, 1), z3, \n" " b3( 4, 0, 3), b3( 7, 4, 3), z3, z3, z3, \n"); str_cat(&shader_buffer, " b3( 4, 8, 7), z3, z3, z3, z3, \n" " b3( 9, 10, 8), b3(10, 11, 8), z3, z3, z3, \n" " b3( 3, 0, 9), b3( 3, 9, 11), b3(11, 9, 10), z3, z3, \n" " b3( 0, 1, 10), b3( 0, 10, 8), b3( 8, 10, 11), z3, z3, \n" " b3( 3, 1, 10), b3(11, 3, 10), z3, z3, z3, \n" " b3( 1, 2, 11), b3( 1, 11, 9), b3( 9, 11, 8), z3, z3, \n"); str_cat(&shader_buffer, " b3( 3, 0, 9), b3( 3, 9, 11), b3( 1, 2, 9), b3( 2, 11, 9), z3, \n" " b3( 0, 2, 11), b3( 8, 0, 11), z3, z3, z3, \n" " b3( 3, 2, 11), z3, z3, z3, z3, \n" " b3( 2, 3, 8), b3( 2, 8, 10), b3(10, 8, 9), z3, z3, \n" " b3( 9, 10, 2), b3( 0, 9, 2), z3, z3, z3, \n" " b3( 2, 3, 8), b3( 2, 8, 10), b3( 0, 1, 8), b3( 1, 10, 8), z3, \n"); str_cat(&shader_buffer, " b3( 1, 10, 2), z3, z3, z3, z3, \n" " b3( 1, 3, 8), b3( 9, 1, 8), z3, z3, z3, \n" " b3( 0, 9, 1), z3, z3, z3, z3, \n" " b3( 0, 3, 8), z3, z3, z3, z3, \n" " z3, z3, z3, z3, z3 \n" ");\n"); str_cat(&shader_buffer, "vec4 get_cubeColor(vec3 p)\n" "{\n" " float t = scene.time * 3.;\n" " float r0 = abs(cos(t * .3)) * 2. + .6;\n" " float r1 = abs(sin(t * .35)) * 2. + .6;\n" " vec3 origin = vec3(0., 2.5, 0.);\n" " vec3 p1 = vec3(sin(t), cos(t), sin(t * .612)) * r0;\n" " vec3 p2 = vec3(sin(t * 1.1), cos(t * 1.2), sin(t * .512)) * r1;\n"); str_cat(&shader_buffer, " float val = 1. / (dot(p - origin, p - origin) + 1.);\n" " float val2 = .6 / (dot(p - origin - p1, p - origin - p1) + 0.7);\n" " float val3 = .5 / (dot(p - origin - p2, p - origin - p2) + 0.9);\n" " return vec4(val, val2, val3, 1.0);\n" "}\n"); str_cat(&shader_buffer, "vec3 get_cubePos(int i)\n" "{\n" " return $vertex_position[0] + vert_offsets[i] * grid_size;\n" "}\n"); str_cat(&shader_buffer, "float get_cubeVal(vec3 p)\n" "{\n" " vec4 color = get_cubeColor(p);\n" " return color.x + color.y + color.z;\n" "}\n"); str_cat(&shader_buffer, "vec3 isonormal(vec3 pos)\n" "{\n" " vec3 nor;\n" " float offset = grid_size * 0.5;\n" " nor.x = get_cubeVal(pos + vec3(grid_size, 0.0, 0.0))\n" " - get_cubeVal(pos - vec3(grid_size, 0.0, 0.0));\n" " nor.y = get_cubeVal(pos + vec3(0.0, grid_size, 0.0))\n" " - get_cubeVal(pos - vec3(0.0, grid_size, 0.0));\n" " nor.z = get_cubeVal(pos + vec3(0.0, 0.0, grid_size))\n" " - get_cubeVal(pos - vec3(0.0, 0.0, grid_size));\n" " return -normalize(nor);\n" "}\n"); str_cat(&shader_buffer, "ivec3 triTableValue(int i, int j)\n" "{\n" " return tri_table[i * 5 + j];\n" " /* return texelFetch(triTableTex, ivec2(j, i), 0).a; */\n" "}\n" "vec3 vert_lerp(float iso_level, vec3 v0, float l0, vec3 v1, float l1)\n" "{\n" " return mix(v0, v1, (iso_level - l0) / (l1 - l0));\n" "}\n"); str_cat(&shader_buffer, "void main(void)\n" "{\n" " vec4 pos;\n" " id = $id[0];\n" " matid = $matid[0];\n" " object_id = $object_id[0];\n" " poly_id = $poly_id[0];\n" " obj_pos = $obj_pos[0];\n" " model = $model[0];\n" " int cubeindex = 0;\n" " vec3 cubesPos[8];\n"); str_cat(&shader_buffer, " cubesPos[0] = get_cubePos(0);\n" " cubesPos[1] = get_cubePos(1);\n" " cubesPos[2] = get_cubePos(2);\n" " cubesPos[3] = get_cubePos(3);\n" " cubesPos[4] = get_cubePos(4);\n" " cubesPos[5] = get_cubePos(5);\n" " cubesPos[6] = get_cubePos(6);\n" " cubesPos[7] = get_cubePos(7);\n"); str_cat(&shader_buffer, " float cubeVal0 = get_cubeVal(cubesPos[0]);\n" " float cubeVal1 = get_cubeVal(cubesPos[1]);\n" " float cubeVal2 = get_cubeVal(cubesPos[2]);\n" " float cubeVal3 = get_cubeVal(cubesPos[3]);\n" " float cubeVal4 = get_cubeVal(cubesPos[4]);\n" " float cubeVal5 = get_cubeVal(cubesPos[5]);\n" " float cubeVal6 = get_cubeVal(cubesPos[6]);\n" " float cubeVal7 = get_cubeVal(cubesPos[7]);\n"); /* Determine the index into the edge table which */ /* tells us which vertices are inside of the surface */ str_cat(&shader_buffer, " cubeindex = int(cubeVal0 < g_iso_level);\n" " cubeindex += int(cubeVal1 < g_iso_level)*2;\n" " cubeindex += int(cubeVal2 < g_iso_level)*4;\n" " cubeindex += int(cubeVal3 < g_iso_level)*8;\n" " cubeindex += int(cubeVal4 < g_iso_level)*16;\n" " cubeindex += int(cubeVal5 < g_iso_level)*32;\n" " cubeindex += int(cubeVal6 < g_iso_level)*64;\n" " cubeindex += int(cubeVal7 < g_iso_level)*128;\n" /* Cube is entirely in/out of the surface */ " if (cubeindex == 0)\n" " return;\n" " if (cubeindex == 255)\n" " return;\n"); /* Find the vertices where the surface intersects the cube */ str_cat(&shader_buffer, " vec3 vertlist[12];\n" " vertlist[0] = vert_lerp(g_iso_level, cubesPos[0], cubeVal0, cubesPos[1], cubeVal1);\n" " vertlist[1] = vert_lerp(g_iso_level, cubesPos[1], cubeVal1, cubesPos[2], cubeVal2);\n" " vertlist[2] = vert_lerp(g_iso_level, cubesPos[2], cubeVal2, cubesPos[3], cubeVal3);\n" " vertlist[3] = vert_lerp(g_iso_level, cubesPos[3], cubeVal3, cubesPos[0], cubeVal0);\n" " vertlist[4] = vert_lerp(g_iso_level, cubesPos[4], cubeVal4, cubesPos[5], cubeVal5);\n"); str_cat(&shader_buffer, " vertlist[5] = vert_lerp(g_iso_level, cubesPos[5], cubeVal5, cubesPos[6], cubeVal6);\n" " vertlist[6] = vert_lerp(g_iso_level, cubesPos[6], cubeVal6, cubesPos[7], cubeVal7);\n" " vertlist[7] = vert_lerp(g_iso_level, cubesPos[7], cubeVal7, cubesPos[4], cubeVal4);\n" " vertlist[8] = vert_lerp(g_iso_level, cubesPos[0], cubeVal0, cubesPos[4], cubeVal4);\n" " vertlist[9] = vert_lerp(g_iso_level, cubesPos[1], cubeVal1, cubesPos[5], cubeVal5);\n"); str_cat(&shader_buffer, " vertlist[10] = vert_lerp(g_iso_level, cubesPos[2], cubeVal2, cubesPos[6], cubeVal6);\n" " vertlist[11] = vert_lerp(g_iso_level, cubesPos[3], cubeVal3, cubesPos[7], cubeVal7);\n"); str_cat(&shader_buffer, " for(int i = 0; i < 5; i++)\n" " {\n" " ivec3 I = triTableValue(cubeindex, i);\n" " mat4 MV = camera(view) * model;\n" " if(I.x != -1)\n" " {\n" " vec4 pos0;\n" " vec4 pos1;\n" " vec4 pos2;\n" " vec3 wpos0;\n" " vec3 wpos1;\n" " vec3 wpos2;\n" " vec3 cpos0;\n" " vec3 cpos1;\n" " vec3 cpos2;\n" " vec3 norm0;\n" " vec3 norm1;\n" " vec3 norm2;\n"); str_cat(&shader_buffer, " pos0 = vec4(vertlist[I.x], 1.0);\n" " norm0 = isonormal(pos0.xyz);\n" " norm0 = (MV * vec4(norm0, 0.0f)).xyz;\n" " pos0 = model * pos0;\n" " wpos0 = pos0.xyz;\n" " pos0 = camera(view) * pos0;\n" " cpos0 = pos0.xyz;\n" " pos0 = camera(projection) * pos0;\n"); str_cat(&shader_buffer, " pos1 = vec4(vertlist[I.y], 1.0);\n" " norm1 = isonormal(pos1.xyz);\n" " norm1 = (MV * vec4(norm1, 0.0f)).xyz;\n" " pos1 = model * pos1;\n" " wpos1 = pos1.xyz;\n" " pos1 = camera(view) * pos1;\n" " cpos1 = pos1.xyz;\n" " pos1 = camera(projection) * pos1;\n"); str_cat(&shader_buffer, " pos2 = vec4(vertlist[I.z], 1.0);\n" " norm2 = isonormal(pos2.xyz);\n" " norm2 = (MV * vec4(norm2, 0.0f)).xyz;\n" " pos2 = model * pos2;\n" " wpos2 = pos2.xyz;\n" " pos2 = camera(view) * pos2;\n" " cpos2 = pos2.xyz;\n" " pos2 = camera(projection) * pos2;\n"); str_cat(&shader_buffer, " vertex_normal = norm0;\n" " poly_color = get_cubeColor(vertlist[I.x]);\n" " vertex_world_position = wpos0;\n" " vertex_position = cpos0;\n" " gl_Position = pos0;\n" " EmitVertex();\n"); str_cat(&shader_buffer, " vertex_world_position = wpos1;\n" " vertex_position = cpos1;\n" " poly_color = get_cubeColor(vertlist[I.y]);\n" " vertex_normal = norm1;\n" " gl_Position = pos1;\n" " EmitVertex();\n"); str_cat(&shader_buffer, " vertex_world_position = wpos2;\n" " vertex_position = cpos2;\n" " poly_color = get_cubeColor(vertlist[I.z]);\n" " vertex_normal = norm2;\n" " gl_Position = pos2;\n" " EmitVertex();\n"); str_cat(&shader_buffer, " EndPrimitive();\n" " }\n" " else\n" " {\n" " break;\n" " }\n" " }\n" "}\n"); shader_add_source("candle:marching.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } static void shaders_candle_pbr() { char *shader_buffer = str_new(64); str_cat(&shader_buffer, "#include \"candle:common.glsl\"\n" "layout (location = 0) out vec4 FragColor;\n" "BUFFER {\n" " sampler2D depth;\n" " sampler2D albedo;\n" " sampler2D nn;\n" " sampler2D mrs;\n" "} gbuffer;\n" "uniform bool opaque_pass;\n"); str_cat(&shader_buffer, "void main(void)\n" "{\n" " ivec2 fc = ivec2(gl_FragCoord.xy);\n" " vec2 pp = pixel_pos();\n" " vec4 dif = texelFetch(gbuffer.albedo, fc, 0);\n" " if(dif.a == 0.0) discard;\n"); str_cat(&shader_buffer, " float depth = textureLod(gbuffer.depth, pp, 0.0).r;\n" " vec3 c_pos = get_position(gbuffer.depth, pp);\n" " if(light(radius) > 0.0 && depth > gl_FragCoord.z) discard;\n" " vec2 normal = texelFetch(gbuffer.nn, fc, 0).rg;\n" " vec3 c_nor = decode_normal(normal);\n" " vec3 w_nor = (camera(model) * vec4(c_nor, 0.0)).xyz;\n" " vec3 w_pos = (camera(model) * vec4(c_pos, 1.0)).xyz;\n" " vec3 metal_rough_subsurf = texelFetch(gbuffer.mrs, fc, 0).rgb;\n"); str_cat(&shader_buffer, " float dist_to_eye = length(c_pos);\n" " vec3 color = vec3(0.0);\n" " if(light(radius) < 0.0)\n" " {\n" " color = light(color.rgb) * dif.xyz;\n" " }\n" " else if(light(color).r > 0.01 || light(color).g > 0.01 || light(color).b > 0.01)\n" " {\n" " vec3 c_light = (camera(view) * vec4(obj_pos, 1.0)).xyz;\n" " vec3 c_light_dir = c_light - c_pos;\n" " vec3 w_light_dir = obj_pos - w_pos;\n" " vec3 light_color = light(color);\n" " float point_to_light = length(c_light_dir);\n"); str_cat(&shader_buffer, " float sd = 0.0;\n" " vec3 shad = vec3(0.0);\n" " {\n" " float z;\n" " sd = get_shadow(w_light_dir, point_to_light, dist_to_eye, depth);\n" " shad = vec3(sd);\n" " if (opaque_pass)\n" " {\n" " vec4 prob = lookup_probe(-w_light_dir, z);\n" " shad -= prob.rgb * 16.0;\n" " }\n" " }\n"); str_cat(&shader_buffer, /* " if(sd < 0.95)\n" */ " {\n" " vec3 eye_dir = normalize(-c_pos);\n" " float l = point_to_light / light(radius);\n" " float attenuation = ((3.0 - l*3.0) / (1.0+1.3*(pow(l*3.0-0.1, 2.0))))/3.0;\n" " attenuation = clamp(attenuation, 0.0, 1.0);\n" " vec4 color_lit = pbr(dif, metal_rough_subsurf.rg,\n" " light_color * attenuation, c_light_dir, c_pos, c_nor);\n" " color.rgb += color_lit.rgb * (vec3(1.0) - shad);\n"); str_cat(&shader_buffer, " float subsurf_strength = (dif.a - 0.5) * 2.0;\n" " float subsurf_len = metal_rough_subsurf.b;\n" " if (metal_rough_subsurf.b * subsurf_strength > 0.0) {" " color.rgb += light_color * attenuation\n" " * transmittance(dif.rgb, metal_rough_subsurf.b * 0.2,\n" " metal_rough_subsurf.b, w_pos, w_nor) * subsurf_strength;\n" " }\n" " }\n" " }\n" "\n" " FragColor = vec4(color, 1.0);\n" "}\n"); shader_add_source("candle:pbr.glsl", shader_buffer, str_len(shader_buffer)); str_free(shader_buffer); } void shaders_candle() { shaders_candle_uniforms(); shaders_candle_final(); shaders_candle_sss(); shaders_candle_ssao(); shaders_candle_color(); shaders_candle_copy(); shaders_candle_copy_gbuffer(); shaders_candle_downsample(); shaders_candle_upsample(); shaders_candle_kawase(); shaders_candle_bright(); shaders_candle_framebuffer_draw(); shaders_candle_quad(); shaders_candle_motion(); shaders_candle_common(); shaders_candle_volum(); shaders_candle_gaussian(); shaders_candle_marching(); shaders_candle_pbr(); }
49,702
8,197
 #pragma once #define INIT_FAR_PSI(psi,fsf,info) \ psi = (PluginStartupInfo*)calloc(sizeof(*psi),1); \ fsf = (FarStandardFunctions*)calloc(sizeof(*fsf),1); \ if (psi == NULL || fsf == NULL) \ { \ _ASSERTE(psi && fsf); \ return; \ } \ memmove(psi, info, std::min(sizeof(*psi),(size_t)(info)->StructSize)); \ memmove(fsf, (info)->FSF, std::min(sizeof(*fsf),(size_t)(info)->FSF->StructSize)); \ psi->FSF = fsf;
205
841
package org.jboss.resteasy.test.client.resource; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import jakarta.ws.rs.client.ClientRequestContext; import jakarta.ws.rs.client.ClientResponseContext; import jakarta.ws.rs.client.ClientResponseFilter; public class ClientResponseWithEntityResponseFilter implements ClientResponseFilter { private static boolean called; public static boolean called() { return called; } @Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { replaceEntityStream(responseContext); called = true; } private static List<String> replaceEntityStream(ClientResponseContext ctx) throws IOException { List<String> entity = null; if (ctx.hasEntity()) { InputStream is = ctx.getEntityStream(); entity = readEntityFromStream(is); ByteArrayInputStream bais = new ByteArrayInputStream(linesToBytes(entity)); ctx.setEntityStream(bais); } return entity; } private static List<String> readEntityFromStream(InputStream is) throws IOException { String entity; List<String> lines = new LinkedList<String>(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while ((entity = br.readLine()) != null) lines.add(entity); return lines; } private static byte[] linesToBytes(List<String> lines) { StringBuilder sb = new StringBuilder(); for (Iterator<String> i = lines.iterator(); i.hasNext();) { sb.append(i.next()); if (i.hasNext()) sb.append("\n"); } return sb.toString().getBytes(); } }
672
2,816
#pragma once #include "duckdb.hpp" #ifndef DUCKDB_AMALGAMATION #include "duckdb/storage/statistics/base_statistics.hpp" #endif #include "parquet_types.h" namespace duckdb { using duckdb_parquet::format::ColumnChunk; using duckdb_parquet::format::SchemaElement; struct LogicalType; struct ParquetStatisticsUtils { static unique_ptr<BaseStatistics> TransformColumnStatistics(const SchemaElement &s_ele, const LogicalType &type, const ColumnChunk &column_chunk); static Value ConvertValue(const LogicalType &type, const duckdb_parquet::format::SchemaElement &schema_ele, const std::string &stats); }; } // namespace duckdb
295
3,102
// RUN: rm -rf %t // RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I%S/Inputs/anon-namespace -verify %s // expected-no-diagnostics #include "b1.h" #include "c.h" using namespace N;
87
307
""" riptable tests. """
12
357
/* * 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.openidconnect.server; import java.util.Set; import org.apache.commons.lang3.Validate; /** * @author <NAME> */ public class ResourceServerInfo { private final String name; private final Set<String> groupFilter; public ResourceServerInfo(String name, Set<String> groupFilter) { Validate.notEmpty(name, "name"); Validate.notNull(groupFilter, "groupFilter"); this.name = name; this.groupFilter = groupFilter; } public String getName() { return this.name; } public Set<String> getGroupFilter() { return this.groupFilter; } }
407
5,119
<filename>tests/codegen/map_key_array.cpp<gh_stars>1000+ #include "common.h" namespace bpftrace { namespace test { namespace codegen { TEST(codegen, map_key_array) { test("struct Foo { int arr[4]; }" "kprobe:f" "{" " @x[((struct Foo *)arg0)->arr] = 44;" "}", NAME); } } // namespace codegen } // namespace test } // namespace bpftrace
170
780
<reponame>Travelcompositor/selenide package integration.errormessages; import com.codeborne.selenide.Configuration; import com.codeborne.selenide.SelenideElement; import com.codeborne.selenide.ex.ElementNotFound; import com.codeborne.selenide.ex.UIAssertionError; import integration.IntegrationTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openqa.selenium.NoSuchElementException; import static com.codeborne.selenide.Condition.appear; import static com.codeborne.selenide.Condition.cssClass; import static com.codeborne.selenide.Condition.exactText; import static com.codeborne.selenide.Condition.exist; import static com.codeborne.selenide.Condition.text; import static com.codeborne.selenide.Condition.visible; import static com.codeborne.selenide.Selenide.$; import static com.codeborne.selenide.Selenide.$$; import static com.codeborne.selenide.WebDriverRunner.isFirefox; import static integration.errormessages.Helper.assertScreenshot; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; final class MethodCalledOnElementFailsOnTest extends IntegrationTest { @BeforeEach void openPage() { givenHtml( "<ul>Hello to:", "<li class='the-expanse detective'>Miller <label>detective</label></li>", "<li class='the-expanse missing'><NAME></li>", "</ul>" ); Configuration.timeout = 0; } @Test void shouldCondition_When$Element_WithNonExistentElement() { SelenideElement element = $("ul .nonexistent"); try { element.shouldHave(text("Miller")); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul .nonexistent}"); assertThat(expected) .hasMessageContaining("Expected: text 'Miller'"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(NoSuchElementException.class); assertCauseMessage(expected, "ul .nonexistent"); } } private void assertCauseMessage(UIAssertionError expected, String selector) { if (isFirefox()) { assertThat(expected.getCause()).hasMessageContaining("Unable to locate element: " + selector); } else { assertThat(expected.getCause()) .hasMessageContaining("Unable to locate element: {\"method\":\"css selector\",\"selector\":\"" + selector + "\"}"); } } @Test void shouldCondition_WhenCollectionElementByIndex_WithNonExistentCollection() { SelenideElement element = $$("ul .nonexistent").get(1); try { element.shouldHave(text("Miller")); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul .nonexistent[1]}"); assertThat(expected) .hasMessageContaining("Expected: visible"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(IndexOutOfBoundsException.class); assertThat(expected.getCause()) .hasMessageMatching("Index\\D+1\\D+0"); } } @Test void shouldCondition_WhenCollectionElementByIndex_WithIndexOutOfRange() { SelenideElement element = $$("ul li").get(10); try { element.shouldHave(text("Miller")); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul li[10]}"); assertThat(expected) .hasMessageContaining("Expected: text 'Miller'"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(IndexOutOfBoundsException.class); assertThat(expected.getCause()) .hasMessageMatching("Index\\D+10\\D+2"); } } @Test void actionWithVisibilityWaiting_WhenCollectionElementByIndex_WithIndexOutOfRange() { SelenideElement element = $$("ul li").get(10); try { element.click(); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul li[10]}"); assertThat(expected) .hasMessageContaining("Expected: visible"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(IndexOutOfBoundsException.class); assertThat(expected.getCause()) .hasMessageMatching("Index\\D+10\\D+2"); } } @Test void shouldCondition_WhenCollectionElementByCondition_WithNonExistentCollection() { SelenideElement element = $$(".nonexistent").findBy(cssClass("the-expanse")); try { element.shouldBe(exist); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {.nonexistent.findBy(css class 'the-expanse')}"); assertThat(expected) .hasMessageContaining("Expected: exist"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(ElementNotFound.class); assertThat(expected.getCause()) .hasMessageStartingWith("Element not found {.nonexistent.findBy(css class 'the-expanse')}"); } } @Test void shouldCondition_WhenCollectionElementByCondition_WithNotSatisfiedCondition() { SelenideElement element = $$("li").findBy(cssClass("nonexistent")); try { element.shouldBe(visible); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {li.findBy(css class 'nonexistent')}"); assertThat(expected) .hasMessageContaining("Expected: visible"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(ElementNotFound.class); assertThat(expected.getCause()) .hasMessageStartingWith("Element not found {li.findBy(css class 'nonexistent')}"); } } @Test void actionWithExistenceWaiting_WhenCollectionElementByCondition_WithNotSatisfiedCondition() { SelenideElement element = $$("li").findBy(cssClass("nonexistent")); try { element.text(); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {li.findBy(css class 'nonexistent')}"); assertThat(expected) .hasMessageContaining("Expected: css class 'nonexistent'"); //todo - is it correct? assertScreenshot(expected); assertThat(expected.getCause()) .isNull(); } } @Test void shouldCondition_WhenInnerElement_WithNonExistentOuterElement() { SelenideElement element = $(".nonexistent").find(".the-expanse"); try { element.should(appear); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {.nonexistent}"); assertThat(expected) .hasMessageContaining("Expected: exist"); //todo - is it correct? assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(NoSuchElementException.class); assertCauseMessage(expected, ".nonexistent"); } } @Test void shouldCondition_WhenInnerElement_WithNonExistentInnerElement() { SelenideElement element = $("ul").find(".nonexistent"); try { element.shouldBe(visible); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul/.nonexistent}"); assertThat(expected) .hasMessageContaining("Expected: visible"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(NoSuchElementException.class); assertCauseMessage(expected, ".nonexistent"); } } @Test void actionWithVisibilityWaiting_WhenInnerElement_WithNonExistentInnerElement() { SelenideElement element = $("ul").find(".nonexistent"); try { element.doubleClick(); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul/.nonexistent}"); assertThat(expected) .hasMessageContaining("Expected: visible"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(NoSuchElementException.class); assertCauseMessage(expected, ".nonexistent"); } } @Test void shouldCondition_WhenInnerElementFromOuterElementByConditionInFilteredCollection_WithNonExistentStartCollection() { SelenideElement element = $$("ul .nonexistent").filterBy(cssClass("the-expanse")).findBy(cssClass("detective")).find("label"); try { element.shouldHave(exactText("detective")); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul .nonexistent.filter(css class 'the-expanse').findBy(css class 'detective')}"); assertThat(expected) .hasMessageContaining("Expected: exist"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(ElementNotFound.class); assertThat(expected.getCause()) .hasMessageStartingWith("Element not found {ul .nonexistent.filter(css class 'the-expanse').findBy(css class 'detective')}"); } } @Test void shouldCondition_WhenInnerElementFromOuterElementByConditionInFilteredCollection_WithEmptyFilteredCollection() { SelenideElement element = $$("ul li").filterBy(cssClass("nonexistent")).findBy(cssClass("detective")).find("label"); try { element.shouldHave(exactText("detective")); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul li.filter(css class 'nonexistent').findBy(css class 'detective')}"); assertThat(expected) .hasMessageContaining("Expected: exist"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(ElementNotFound.class); assertThat(expected.getCause()) .hasMessageStartingWith("Element not found {ul li.filter(css class 'nonexistent').findBy(css class 'detective')}"); } } @Test void shouldCondition_WhenInnerElementFromOuterElementByConditionInFilteredCollection_WithNonExistentOuterElement() { SelenideElement element = $$("ul li").filterBy(cssClass("the-expanse")).findBy(cssClass("nonexistent")).find("label"); try { element.shouldHave(exactText("detective")); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul li.filter(css class 'the-expanse').findBy(css class 'nonexistent')}"); assertThat(expected) .hasMessageContaining("Expected: exist"); //todo - is it correct? assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(ElementNotFound.class); assertThat(expected.getCause()) .hasMessageStartingWith("Element not found {ul li.filter(css class 'the-expanse').findBy(css class 'nonexistent')}"); } } @Test void shouldCondition_WhenInnerElementFromOuterElementByConditionInFilteredCollection_WithNonExistentInnerElement() { SelenideElement element = $$("ul li").filterBy(cssClass("the-expanse")).findBy(cssClass("detective")).find(".nonexistent"); try { element.shouldHave(exactText("detective")); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul li.filter(css class 'the-expanse').findBy(css class 'detective')/.nonexistent}"); assertThat(expected) .hasMessageContaining("Expected: exact text 'detective'"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(NoSuchElementException.class); assertCauseMessage(expected, ".nonexistent"); } } @Test void shouldCondition_WhenInnerElementFromOuterElementFoundByIndexInFilteredCollection_WithNonExistentStartCollection() { SelenideElement element = $$("ul .nonexistent").filterBy(cssClass("the-expanse")).get(0).find("label"); try { element.shouldHave(exactText("detective")); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul .nonexistent.filter(css class 'the-expanse')[0]}"); assertThat(expected) .hasMessageContaining("Expected: visible"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(IndexOutOfBoundsException.class); assertThat(expected.getCause()) .hasMessageMatching("Index: 0"); } } @Test void shouldCondition_WhenInnerElementFromOuterElementFoundByIndexInFilteredCollection_WithEmptyFilteredCollection() { SelenideElement element = $$("ul li").filterBy(cssClass("nonexistent")).get(0).find("label"); try { element.shouldHave(exactText("detective")); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul li.filter(css class 'nonexistent')[0]}"); assertThat(expected) .hasMessageContaining("Expected: visible"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(IndexOutOfBoundsException.class); assertThat(expected.getCause()) .hasMessageMatching("Index: 0"); } } @Test void shouldCondition_WhenInnerElementFromOuterElementFoundByIndexInFilteredCollection_WithIndexOutOfRange() { SelenideElement element = $$("ul li").filterBy(cssClass("the-expanse")).get(2).find("label"); try { element.shouldHave(exactText("detective")); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul li.filter(css class 'the-expanse')[2]}"); assertThat(expected) .hasMessageContaining("Expected: exist"); //todo - is it correct? assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(IndexOutOfBoundsException.class); assertThat(expected.getCause()) .hasMessageMatching("Index: 2"); } } @Test void shouldCondition_WhenInnerElementFromOuterElementFoundByIndexInFilteredCollection_WithNonExistentInnerElement() { SelenideElement element = $$("ul li").filterBy(cssClass("the-expanse")).get(0).find(".nonexistent"); try { element.shouldHave(exactText("detective")); fail("Expected ElementNotFound"); } catch (ElementNotFound expected) { assertThat(expected) .hasMessageStartingWith("Element not found {ul li.filter(css class 'the-expanse')[0]/.nonexistent}"); assertThat(expected) .hasMessageContaining("Expected: exact text 'detective'"); assertScreenshot(expected); assertThat(expected.getCause()) .isInstanceOf(NoSuchElementException.class); assertCauseMessage(expected, ".nonexistent"); } } }
5,486
868
package com.sedmelluq.discord.lavaplayer.source.youtube; import com.sedmelluq.discord.lavaplayer.tools.FriendlyException; import com.sedmelluq.discord.lavaplayer.tools.JsonBrowser; import com.sedmelluq.discord.lavaplayer.tools.Units; import com.sedmelluq.discord.lavaplayer.tools.io.HttpClientTools; import com.sedmelluq.discord.lavaplayer.tools.io.HttpInterface; import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import com.sedmelluq.discord.lavaplayer.track.BasicAudioPlaylist; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeHttpContextFilter.PBJ_PARAMETER; import static com.sedmelluq.discord.lavaplayer.tools.FriendlyException.Severity.COMMON; public class DefaultYoutubePlaylistLoader implements YoutubePlaylistLoader { private static final String REQUEST_URL = "https://www.youtube.com/youtubei/v1/browse?key=<KEY>"; private static final String REQUEST_PAYLOAD = "{\"context\":{\"client\":{\"clientName\":\"WEB\",\"clientVersion\":\"2.20210302.07.01\"}},\"continuation\":\"%s\"}"; private volatile int playlistPageCount = 6; @Override public void setPlaylistPageCount(int playlistPageCount) { this.playlistPageCount = playlistPageCount; } @Override public AudioPlaylist load(HttpInterface httpInterface, String playlistId, String selectedVideoId, Function<AudioTrackInfo, AudioTrack> trackFactory) { HttpGet request = new HttpGet(getPlaylistUrl(playlistId) + PBJ_PARAMETER + "&hl=en"); try (CloseableHttpResponse response = httpInterface.execute(request)) { HttpClientTools.assertSuccessWithContent(response, "playlist response"); HttpClientTools.assertJsonContentType(response); JsonBrowser json = JsonBrowser.parse(response.getEntity().getContent()); return buildPlaylist(httpInterface, json, selectedVideoId, trackFactory); } catch (IOException e) { throw new RuntimeException(e); } } private AudioPlaylist buildPlaylist(HttpInterface httpInterface, JsonBrowser json, String selectedVideoId, Function<AudioTrackInfo, AudioTrack> trackFactory) throws IOException { JsonBrowser jsonResponse = json.index(1).get("response"); String errorAlertMessage = findErrorAlert(jsonResponse); if (errorAlertMessage != null) { throw new FriendlyException(errorAlertMessage, COMMON, null); } JsonBrowser info = jsonResponse .get("sidebar") .get("playlistSidebarRenderer") .get("items") .index(0) .get("playlistSidebarPrimaryInfoRenderer"); String playlistName = info .get("title") .get("runs") .index(0) .get("text") .text(); JsonBrowser playlistVideoList = jsonResponse .get("contents") .get("twoColumnBrowseResultsRenderer") .get("tabs") .index(0) .get("tabRenderer") .get("content") .get("sectionListRenderer") .get("contents") .index(0) .get("itemSectionRenderer") .get("contents") .index(0) .get("playlistVideoListRenderer") .get("contents"); List<AudioTrack> tracks = new ArrayList<>(); String continuationsToken = extractPlaylistTracks(playlistVideoList, tracks, trackFactory); int loadCount = 0; int pageCount = playlistPageCount; // Also load the next pages, each result gives us a JSON with separate values for list html and next page loader html while (continuationsToken != null && ++loadCount < pageCount) { HttpPost post = new HttpPost(REQUEST_URL); StringEntity payload = new StringEntity(String.format(REQUEST_PAYLOAD, continuationsToken), "UTF-8"); post.setEntity(payload); try (CloseableHttpResponse response = httpInterface.execute(post)) { HttpClientTools.assertSuccessWithContent(response, "playlist response"); JsonBrowser continuationJson = JsonBrowser.parse(response.getEntity().getContent()); JsonBrowser playlistVideoListPage = continuationJson.index(1) .get("response") .get("continuationContents") .get("playlistVideoListContinuation"); if (playlistVideoListPage.isNull()) { playlistVideoListPage = continuationJson.get("onResponseReceivedActions") .index(0) .get("appendContinuationItemsAction") .get("continuationItems"); } continuationsToken = extractPlaylistTracks(playlistVideoListPage, tracks, trackFactory); } } return new BasicAudioPlaylist(playlistName, tracks, findSelectedTrack(tracks, selectedVideoId), false); } private String findErrorAlert(JsonBrowser jsonResponse) { JsonBrowser alerts = jsonResponse.get("alerts"); if (!alerts.isNull()) { for(JsonBrowser alert : alerts.values()) { JsonBrowser alertInner = alert.values().get(0); String type = alertInner.get("type").text(); if("ERROR".equals(type)) { JsonBrowser textObject = alertInner.get("text"); String text; if(!textObject.get("simpleText").isNull()) { text = textObject.get("simpleText").text(); } else { text = textObject.get("runs").values().stream() .map(run -> run.get("text").text()) .collect(Collectors.joining()); } return text; } } } return null; } private AudioTrack findSelectedTrack(List<AudioTrack> tracks, String selectedVideoId) { if (selectedVideoId != null) { for (AudioTrack track : tracks) { if (selectedVideoId.equals(track.getIdentifier())) { return track; } } } return null; } private String extractPlaylistTracks(JsonBrowser playlistVideoList, List<AudioTrack> tracks, Function<AudioTrackInfo, AudioTrack> trackFactory) { if (playlistVideoList.isNull()) return null; final List<JsonBrowser> playlistTrackEntries = playlistVideoList.values(); for (JsonBrowser track : playlistTrackEntries) { JsonBrowser item = track.get("playlistVideoRenderer"); JsonBrowser shortBylineText = item.get("shortBylineText"); // If the isPlayable property does not exist, it means the video is removed or private // If the shortBylineText property does not exist, it means the Track is Region blocked if (!item.get("isPlayable").isNull() && !shortBylineText.isNull()) { String videoId = item.get("videoId").text(); JsonBrowser titleField = item.get("title"); String title = Optional.ofNullable(titleField.get("simpleText").text()) .orElse(titleField.get("runs").index(0).get("text").text()); String author = shortBylineText.get("runs").index(0).get("text").text(); JsonBrowser lengthSeconds = item.get("lengthSeconds"); long duration = Units.secondsToMillis(lengthSeconds.asLong(Units.DURATION_SEC_UNKNOWN)); AudioTrackInfo info = new AudioTrackInfo(title, author, duration, videoId, false, "https://www.youtube.com/watch?v=" + videoId); tracks.add(trackFactory.apply(info)); } } JsonBrowser continuations = playlistTrackEntries.get(playlistTrackEntries.size() - 1) .get("continuationItemRenderer") .get("continuationEndpoint") .get("continuationCommand"); String continuationsToken; if (!continuations.isNull()) { continuationsToken = continuations.get("token").text(); return continuationsToken; } return null; } private static String getPlaylistUrl(String playlistId) { return "https://www.youtube.com/playlist?list=" + playlistId; } }
3,119
2,739
# Copyright (c) 2020 PaddlePaddle 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. from __future__ import print_function from utils.static_ps.reader_helper import get_reader, get_example_num, get_file_list, get_word_num from utils.static_ps.program_helper import get_model, get_strategy from utils.static_ps.common import YamlHelper, is_distributed_env import argparse import time import sys import paddle.distributed.fleet as fleet import paddle.distributed.fleet.base.role_maker as role_maker import paddle import os import warnings import logging import paddle.fluid as fluid __dir__ = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.abspath(os.path.join(__dir__, '..'))) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) def parse_args(): parser = argparse.ArgumentParser("PaddleRec train script") parser.add_argument( '-m', '--config_yaml', type=str, required=True, help='config file path') args = parser.parse_args() args.abs_dir = os.path.dirname(os.path.abspath(args.config_yaml)) yaml_helper = YamlHelper() config = yaml_helper.load_yaml(args.config_yaml) config["yaml_path"] = args.config_yaml config["config_abs_dir"] = args.abs_dir yaml_helper.print_yaml(config) return config class Main(object): def __init__(self, config): self.metrics = {} self.config = config self.input_data = None self.reader = None self.exe = None self.train_result_dict = {} self.train_result_dict["speed"] = [] def run(self): fleet.init() self.network() if fleet.is_server(): self.run_server() elif fleet.is_worker(): self.run_online_worker() fleet.stop_worker() self.record_result() logger.info("Run Success, Exit.") def network(self): model = get_model(self.config) self.input_data = model.create_feeds() self.metrics = model.net(self.input_data) self.inference_target_var = model.inference_target_var logger.info("cpu_num: {}".format(os.getenv("CPU_NUM"))) model.create_optimizer(get_strategy(self.config)) def run_server(self): logger.info("Run Server Begin") fleet.init_server(config.get("runner.warmup_model_path")) fleet.run_server() def wait_and_prepare_dataset(self, day, pass_index): train_data_dir = self.config.get("runner.train_data_dir", []) dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") dataset.set_use_var(self.input_data) dataset.set_batch_size(self.config.get('runner.train_batch_size')) dataset.set_thread(self.config.get('runner.train_thread_num')) # may you need define your dataset_filelist for day/pass_index filelist = [] for path in train_data_dir: filelist += [path + "/%s" % x for x in os.listdir(path)] dataset.set_filelist(filelist) dataset.set_pipe_command(self.config.get("runner.pipe_command")) dataset.load_into_memory() return dataset def run_online_worker(self): logger.info("Run Online Worker Begin") use_cuda = int(config.get("runner.use_gpu")) place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace() self.exe = paddle.static.Executor(place) with open("./{}_worker_main_program.prototxt".format( fleet.worker_index()), 'w+') as f: f.write(str(paddle.static.default_main_program())) with open("./{}_worker_startup_program.prototxt".format( fleet.worker_index()), 'w+') as f: f.write(str(paddle.static.default_startup_program())) self.exe.run(paddle.static.default_startup_program()) fleet.init_worker() save_model_path = self.config.get("runner.model_save_path") if save_model_path and (not os.path.exists(save_model_path)): os.makedirs(save_model_path) days = os.popen("echo -n " + self.config.get("runner.days")).read().split(" ") pass_per_day = int(self.config.get("runner.pass_per_day")) for day_index in range(len(days)): day = days[day_index] for pass_index in range(1, pass_per_day + 1): logger.info("Day: {} Pass: {} Begin.".format(day, pass_index)) prepare_data_start_time = time.time() dataset = self.wait_and_prepare_dataset(day, pass_index) prepare_data_end_time = time.time() logger.info( "Prepare Dataset Done, using time {} second.".format(prepare_data_end_time - prepare_data_start_time)) train_start_time = time.time() self.dataset_train_loop(dataset, day, pass_index) train_end_time = time.time() logger.info( "Train Dataset Done, using time {} second.".format(train_end_time - train_start_time)) model_dir = "{}/{}/{}".format(save_model_path, day, pass_index) if fleet.is_first_worker() and save_model_path and is_distributed_env(): fleet.save_inference_model( self.exe, model_dir, [feed.name for feed in self.input_data], self.inference_target_var, mode=2) if fleet.is_first_worker() and save_model_path and is_distributed_env(): fleet.save_inference_model( self.exe, model_dir, [feed.name for feed in self.input_data], self.inference_target_var, mode=0) def dataset_train_loop(self, cur_dataset, day, pass_index): logger.info("Day: {} Pass: {}, Running Dataset Begin.".format(day, pass_index)) fetch_info = [ "Day: {} Pass: {} Var {}".format(day, pass_index, var_name) for var_name in self.metrics ] fetch_vars = [var for _, var in self.metrics.items()] print_step = int(config.get("runner.print_interval")) self.exe.train_from_dataset( program=paddle.static.default_main_program(), dataset=cur_dataset, fetch_list=fetch_vars, fetch_info=fetch_info, print_period=print_step, debug=config.get("runner.dataset_debug")) cur_dataset.release_memory() if __name__ == "__main__": paddle.enable_static() config = parse_args() # os.environ["CPU_NUM"] = str(config.get("runner.thread_num")) benchmark_main = Main(config) benchmark_main.run()
3,300
2,338
//===-- SBProcess.cpp -----------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/API/SBProcess.h" #include "SBReproducerPrivate.h" #include <cinttypes> #include "lldb/lldb-defines.h" #include "lldb/lldb-types.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/StreamFile.h" #include "lldb/Core/StructuredDataImpl.h" #include "lldb/Target/MemoryRegionInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/SystemRuntime.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/Args.h" #include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/State.h" #include "lldb/Utility/Stream.h" #include "lldb/API/SBBroadcaster.h" #include "lldb/API/SBCommandReturnObject.h" #include "lldb/API/SBDebugger.h" #include "lldb/API/SBEvent.h" #include "lldb/API/SBFile.h" #include "lldb/API/SBFileSpec.h" #include "lldb/API/SBMemoryRegionInfo.h" #include "lldb/API/SBMemoryRegionInfoList.h" #include "lldb/API/SBStream.h" #include "lldb/API/SBStringList.h" #include "lldb/API/SBStructuredData.h" #include "lldb/API/SBThread.h" #include "lldb/API/SBThreadCollection.h" #include "lldb/API/SBTrace.h" #include "lldb/API/SBUnixSignals.h" using namespace lldb; using namespace lldb_private; SBProcess::SBProcess() : m_opaque_wp() { LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBProcess); } // SBProcess constructor SBProcess::SBProcess(const SBProcess &rhs) : m_opaque_wp(rhs.m_opaque_wp) { LLDB_RECORD_CONSTRUCTOR(SBProcess, (const lldb::SBProcess &), rhs); } SBProcess::SBProcess(const lldb::ProcessSP &process_sp) : m_opaque_wp(process_sp) { LLDB_RECORD_CONSTRUCTOR(SBProcess, (const lldb::ProcessSP &), process_sp); } const SBProcess &SBProcess::operator=(const SBProcess &rhs) { LLDB_RECORD_METHOD(const lldb::SBProcess &, SBProcess, operator=,(const lldb::SBProcess &), rhs); if (this != &rhs) m_opaque_wp = rhs.m_opaque_wp; return LLDB_RECORD_RESULT(*this); } // Destructor SBProcess::~SBProcess() = default; const char *SBProcess::GetBroadcasterClassName() { LLDB_RECORD_STATIC_METHOD_NO_ARGS(const char *, SBProcess, GetBroadcasterClassName); return Process::GetStaticBroadcasterClass().AsCString(); } const char *SBProcess::GetPluginName() { LLDB_RECORD_METHOD_NO_ARGS(const char *, SBProcess, GetPluginName); ProcessSP process_sp(GetSP()); if (process_sp) { return process_sp->GetPluginName().GetCString(); } return "<Unknown>"; } const char *SBProcess::GetShortPluginName() { LLDB_RECORD_METHOD_NO_ARGS(const char *, SBProcess, GetShortPluginName); ProcessSP process_sp(GetSP()); if (process_sp) { return process_sp->GetPluginName().GetCString(); } return "<Unknown>"; } lldb::ProcessSP SBProcess::GetSP() const { return m_opaque_wp.lock(); } void SBProcess::SetSP(const ProcessSP &process_sp) { m_opaque_wp = process_sp; } void SBProcess::Clear() { LLDB_RECORD_METHOD_NO_ARGS(void, SBProcess, Clear); m_opaque_wp.reset(); } bool SBProcess::IsValid() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBProcess, IsValid); return this->operator bool(); } SBProcess::operator bool() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBProcess, operator bool); ProcessSP process_sp(m_opaque_wp.lock()); return ((bool)process_sp && process_sp->IsValid()); } bool SBProcess::RemoteLaunch(char const **argv, char const **envp, const char *stdin_path, const char *stdout_path, const char *stderr_path, const char *working_directory, uint32_t launch_flags, bool stop_at_entry, lldb::SBError &error) { LLDB_RECORD_METHOD(bool, SBProcess, RemoteLaunch, (const char **, const char **, const char *, const char *, const char *, const char *, uint32_t, bool, lldb::SBError &), argv, envp, stdin_path, stdout_path, stderr_path, working_directory, launch_flags, stop_at_entry, error); ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); if (process_sp->GetState() == eStateConnected) { if (stop_at_entry) launch_flags |= eLaunchFlagStopAtEntry; ProcessLaunchInfo launch_info(FileSpec(stdin_path), FileSpec(stdout_path), FileSpec(stderr_path), FileSpec(working_directory), launch_flags); Module *exe_module = process_sp->GetTarget().GetExecutableModulePointer(); if (exe_module) launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true); if (argv) launch_info.GetArguments().AppendArguments(argv); if (envp) launch_info.GetEnvironment() = Environment(envp); error.SetError(process_sp->Launch(launch_info)); } else { error.SetErrorString("must be in eStateConnected to call RemoteLaunch"); } } else { error.SetErrorString("unable to attach pid"); } return error.Success(); } bool SBProcess::RemoteAttachToProcessWithID(lldb::pid_t pid, lldb::SBError &error) { LLDB_RECORD_METHOD(bool, SBProcess, RemoteAttachToProcessWithID, (lldb::pid_t, lldb::SBError &), pid, error); ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); if (process_sp->GetState() == eStateConnected) { ProcessAttachInfo attach_info; attach_info.SetProcessID(pid); error.SetError(process_sp->Attach(attach_info)); } else { error.SetErrorString( "must be in eStateConnected to call RemoteAttachToProcessWithID"); } } else { error.SetErrorString("unable to attach pid"); } return error.Success(); } uint32_t SBProcess::GetNumThreads() { LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBProcess, GetNumThreads); uint32_t num_threads = 0; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); num_threads = process_sp->GetThreadList().GetSize(can_update); } return num_threads; } SBThread SBProcess::GetSelectedThread() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBThread, SBProcess, GetSelectedThread); SBThread sb_thread; ThreadSP thread_sp; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); thread_sp = process_sp->GetThreadList().GetSelectedThread(); sb_thread.SetThread(thread_sp); } return LLDB_RECORD_RESULT(sb_thread); } SBThread SBProcess::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) { LLDB_RECORD_METHOD(lldb::SBThread, SBProcess, CreateOSPluginThread, (lldb::tid_t, lldb::addr_t), tid, context); SBThread sb_thread; ThreadSP thread_sp; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); thread_sp = process_sp->CreateOSPluginThread(tid, context); sb_thread.SetThread(thread_sp); } return LLDB_RECORD_RESULT(sb_thread); } SBTarget SBProcess::GetTarget() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBTarget, SBProcess, GetTarget); SBTarget sb_target; TargetSP target_sp; ProcessSP process_sp(GetSP()); if (process_sp) { target_sp = process_sp->GetTarget().shared_from_this(); sb_target.SetSP(target_sp); } return LLDB_RECORD_RESULT(sb_target); } size_t SBProcess::PutSTDIN(const char *src, size_t src_len) { LLDB_RECORD_METHOD(size_t, SBProcess, PutSTDIN, (const char *, size_t), src, src_len); size_t ret_val = 0; ProcessSP process_sp(GetSP()); if (process_sp) { Status error; ret_val = process_sp->PutSTDIN(src, src_len, error); } return ret_val; } size_t SBProcess::GetSTDOUT(char *dst, size_t dst_len) const { LLDB_RECORD_CHAR_PTR_METHOD_CONST(size_t, SBProcess, GetSTDOUT, (char *, size_t), dst, "", dst_len); size_t bytes_read = 0; ProcessSP process_sp(GetSP()); if (process_sp) { Status error; bytes_read = process_sp->GetSTDOUT(dst, dst_len, error); } return bytes_read; } size_t SBProcess::GetSTDERR(char *dst, size_t dst_len) const { LLDB_RECORD_CHAR_PTR_METHOD_CONST(size_t, SBProcess, GetSTDERR, (char *, size_t), dst, "", dst_len); size_t bytes_read = 0; ProcessSP process_sp(GetSP()); if (process_sp) { Status error; bytes_read = process_sp->GetSTDERR(dst, dst_len, error); } return bytes_read; } size_t SBProcess::GetAsyncProfileData(char *dst, size_t dst_len) const { LLDB_RECORD_CHAR_PTR_METHOD_CONST(size_t, SBProcess, GetAsyncProfileData, (char *, size_t), dst, "", dst_len); size_t bytes_read = 0; ProcessSP process_sp(GetSP()); if (process_sp) { Status error; bytes_read = process_sp->GetAsyncProfileData(dst, dst_len, error); } return bytes_read; } void SBProcess::ReportEventState(const SBEvent &event, SBFile out) const { LLDB_RECORD_METHOD_CONST(void, SBProcess, ReportEventState, (const SBEvent &, SBFile), event, out); return ReportEventState(event, out.m_opaque_sp); } void SBProcess::ReportEventState(const SBEvent &event, FILE *out) const { LLDB_RECORD_METHOD_CONST(void, SBProcess, ReportEventState, (const lldb::SBEvent &, FILE *), event, out); FileSP outfile = std::make_shared<NativeFile>(out, false); return ReportEventState(event, outfile); } void SBProcess::ReportEventState(const SBEvent &event, FileSP out) const { LLDB_RECORD_METHOD_CONST(void, SBProcess, ReportEventState, (const SBEvent &, FileSP), event, out); if (!out || !out->IsValid()) return; ProcessSP process_sp(GetSP()); if (process_sp) { StreamFile stream(out); const StateType event_state = SBProcess::GetStateFromEvent(event); stream.Printf("Process %" PRIu64 " %s\n", process_sp->GetID(), SBDebugger::StateAsCString(event_state)); } } void SBProcess::AppendEventStateReport(const SBEvent &event, SBCommandReturnObject &result) { LLDB_RECORD_METHOD(void, SBProcess, AppendEventStateReport, (const lldb::SBEvent &, lldb::SBCommandReturnObject &), event, result); ProcessSP process_sp(GetSP()); if (process_sp) { const StateType event_state = SBProcess::GetStateFromEvent(event); char message[1024]; ::snprintf(message, sizeof(message), "Process %" PRIu64 " %s\n", process_sp->GetID(), SBDebugger::StateAsCString(event_state)); result.AppendMessage(message); } } bool SBProcess::SetSelectedThread(const SBThread &thread) { LLDB_RECORD_METHOD(bool, SBProcess, SetSelectedThread, (const lldb::SBThread &), thread); ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); return process_sp->GetThreadList().SetSelectedThreadByID( thread.GetThreadID()); } return false; } bool SBProcess::SetSelectedThreadByID(lldb::tid_t tid) { LLDB_RECORD_METHOD(bool, SBProcess, SetSelectedThreadByID, (lldb::tid_t), tid); bool ret_val = false; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); ret_val = process_sp->GetThreadList().SetSelectedThreadByID(tid); } return ret_val; } bool SBProcess::SetSelectedThreadByIndexID(uint32_t index_id) { LLDB_RECORD_METHOD(bool, SBProcess, SetSelectedThreadByIndexID, (uint32_t), index_id); bool ret_val = false; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); ret_val = process_sp->GetThreadList().SetSelectedThreadByIndexID(index_id); } return ret_val; } SBThread SBProcess::GetThreadAtIndex(size_t index) { LLDB_RECORD_METHOD(lldb::SBThread, SBProcess, GetThreadAtIndex, (size_t), index); SBThread sb_thread; ThreadSP thread_sp; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); thread_sp = process_sp->GetThreadList().GetThreadAtIndex(index, can_update); sb_thread.SetThread(thread_sp); } return LLDB_RECORD_RESULT(sb_thread); } uint32_t SBProcess::GetNumQueues() { LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBProcess, GetNumQueues); uint32_t num_queues = 0; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); num_queues = process_sp->GetQueueList().GetSize(); } } return num_queues; } SBQueue SBProcess::GetQueueAtIndex(size_t index) { LLDB_RECORD_METHOD(lldb::SBQueue, SBProcess, GetQueueAtIndex, (size_t), index); SBQueue sb_queue; QueueSP queue_sp; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); queue_sp = process_sp->GetQueueList().GetQueueAtIndex(index); sb_queue.SetQueue(queue_sp); } } return LLDB_RECORD_RESULT(sb_queue); } uint32_t SBProcess::GetStopID(bool include_expression_stops) { LLDB_RECORD_METHOD(uint32_t, SBProcess, GetStopID, (bool), include_expression_stops); ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); if (include_expression_stops) return process_sp->GetStopID(); else return process_sp->GetLastNaturalStopID(); } return 0; } SBEvent SBProcess::GetStopEventForStopID(uint32_t stop_id) { LLDB_RECORD_METHOD(lldb::SBEvent, SBProcess, GetStopEventForStopID, (uint32_t), stop_id); SBEvent sb_event; EventSP event_sp; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); event_sp = process_sp->GetStopEventForStopID(stop_id); sb_event.reset(event_sp); } return LLDB_RECORD_RESULT(sb_event); } StateType SBProcess::GetState() { LLDB_RECORD_METHOD_NO_ARGS(lldb::StateType, SBProcess, GetState); StateType ret_val = eStateInvalid; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); ret_val = process_sp->GetState(); } return ret_val; } int SBProcess::GetExitStatus() { LLDB_RECORD_METHOD_NO_ARGS(int, SBProcess, GetExitStatus); int exit_status = 0; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); exit_status = process_sp->GetExitStatus(); } return exit_status; } const char *SBProcess::GetExitDescription() { LLDB_RECORD_METHOD_NO_ARGS(const char *, SBProcess, GetExitDescription); const char *exit_desc = nullptr; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); exit_desc = process_sp->GetExitDescription(); } return exit_desc; } lldb::pid_t SBProcess::GetProcessID() { LLDB_RECORD_METHOD_NO_ARGS(lldb::pid_t, SBProcess, GetProcessID); lldb::pid_t ret_val = LLDB_INVALID_PROCESS_ID; ProcessSP process_sp(GetSP()); if (process_sp) ret_val = process_sp->GetID(); return ret_val; } uint32_t SBProcess::GetUniqueID() { LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBProcess, GetUniqueID); uint32_t ret_val = 0; ProcessSP process_sp(GetSP()); if (process_sp) ret_val = process_sp->GetUniqueID(); return ret_val; } ByteOrder SBProcess::GetByteOrder() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::ByteOrder, SBProcess, GetByteOrder); ByteOrder byteOrder = eByteOrderInvalid; ProcessSP process_sp(GetSP()); if (process_sp) byteOrder = process_sp->GetTarget().GetArchitecture().GetByteOrder(); return byteOrder; } uint32_t SBProcess::GetAddressByteSize() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBProcess, GetAddressByteSize); uint32_t size = 0; ProcessSP process_sp(GetSP()); if (process_sp) size = process_sp->GetTarget().GetArchitecture().GetAddressByteSize(); return size; } SBError SBProcess::Continue() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBProcess, Continue); SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); if (process_sp->GetTarget().GetDebugger().GetAsyncExecution()) sb_error.ref() = process_sp->Resume(); else sb_error.ref() = process_sp->ResumeSynchronous(nullptr); } else sb_error.SetErrorString("SBProcess is invalid"); return LLDB_RECORD_RESULT(sb_error); } SBError SBProcess::Destroy() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBProcess, Destroy); SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); sb_error.SetError(process_sp->Destroy(false)); } else sb_error.SetErrorString("SBProcess is invalid"); return LLDB_RECORD_RESULT(sb_error); } SBError SBProcess::Stop() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBProcess, Stop); SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); sb_error.SetError(process_sp->Halt()); } else sb_error.SetErrorString("SBProcess is invalid"); return LLDB_RECORD_RESULT(sb_error); } SBError SBProcess::Kill() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBProcess, Kill); SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); sb_error.SetError(process_sp->Destroy(true)); } else sb_error.SetErrorString("SBProcess is invalid"); return LLDB_RECORD_RESULT(sb_error); } SBError SBProcess::Detach() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBError, SBProcess, Detach); // FIXME: This should come from a process default. bool keep_stopped = false; return LLDB_RECORD_RESULT(Detach(keep_stopped)); } SBError SBProcess::Detach(bool keep_stopped) { LLDB_RECORD_METHOD(lldb::SBError, SBProcess, Detach, (bool), keep_stopped); SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); sb_error.SetError(process_sp->Detach(keep_stopped)); } else sb_error.SetErrorString("SBProcess is invalid"); return LLDB_RECORD_RESULT(sb_error); } SBError SBProcess::Signal(int signo) { LLDB_RECORD_METHOD(lldb::SBError, SBProcess, Signal, (int), signo); SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); sb_error.SetError(process_sp->Signal(signo)); } else sb_error.SetErrorString("SBProcess is invalid"); return LLDB_RECORD_RESULT(sb_error); } SBUnixSignals SBProcess::GetUnixSignals() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBUnixSignals, SBProcess, GetUnixSignals); if (auto process_sp = GetSP()) return LLDB_RECORD_RESULT(SBUnixSignals{process_sp}); return LLDB_RECORD_RESULT(SBUnixSignals{}); } void SBProcess::SendAsyncInterrupt() { LLDB_RECORD_METHOD_NO_ARGS(void, SBProcess, SendAsyncInterrupt); ProcessSP process_sp(GetSP()); if (process_sp) { process_sp->SendAsyncInterrupt(); } } SBThread SBProcess::GetThreadByID(tid_t tid) { LLDB_RECORD_METHOD(lldb::SBThread, SBProcess, GetThreadByID, (lldb::tid_t), tid); SBThread sb_thread; ThreadSP thread_sp; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); thread_sp = process_sp->GetThreadList().FindThreadByID(tid, can_update); sb_thread.SetThread(thread_sp); } return LLDB_RECORD_RESULT(sb_thread); } SBThread SBProcess::GetThreadByIndexID(uint32_t index_id) { LLDB_RECORD_METHOD(lldb::SBThread, SBProcess, GetThreadByIndexID, (uint32_t), index_id); SBThread sb_thread; ThreadSP thread_sp; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; const bool can_update = stop_locker.TryLock(&process_sp->GetRunLock()); std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); thread_sp = process_sp->GetThreadList().FindThreadByIndexID(index_id, can_update); sb_thread.SetThread(thread_sp); } return LLDB_RECORD_RESULT(sb_thread); } StateType SBProcess::GetStateFromEvent(const SBEvent &event) { LLDB_RECORD_STATIC_METHOD(lldb::StateType, SBProcess, GetStateFromEvent, (const lldb::SBEvent &), event); StateType ret_val = Process::ProcessEventData::GetStateFromEvent(event.get()); return ret_val; } bool SBProcess::GetRestartedFromEvent(const SBEvent &event) { LLDB_RECORD_STATIC_METHOD(bool, SBProcess, GetRestartedFromEvent, (const lldb::SBEvent &), event); bool ret_val = Process::ProcessEventData::GetRestartedFromEvent(event.get()); return ret_val; } size_t SBProcess::GetNumRestartedReasonsFromEvent(const lldb::SBEvent &event) { LLDB_RECORD_STATIC_METHOD(size_t, SBProcess, GetNumRestartedReasonsFromEvent, (const lldb::SBEvent &), event); return Process::ProcessEventData::GetNumRestartedReasons(event.get()); } const char * SBProcess::GetRestartedReasonAtIndexFromEvent(const lldb::SBEvent &event, size_t idx) { LLDB_RECORD_STATIC_METHOD(const char *, SBProcess, GetRestartedReasonAtIndexFromEvent, (const lldb::SBEvent &, size_t), event, idx); return Process::ProcessEventData::GetRestartedReasonAtIndex(event.get(), idx); } SBProcess SBProcess::GetProcessFromEvent(const SBEvent &event) { LLDB_RECORD_STATIC_METHOD(lldb::SBProcess, SBProcess, GetProcessFromEvent, (const lldb::SBEvent &), event); ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event.get()); if (!process_sp) { // StructuredData events also know the process they come from. Try that. process_sp = EventDataStructuredData::GetProcessFromEvent(event.get()); } return LLDB_RECORD_RESULT(SBProcess(process_sp)); } bool SBProcess::GetInterruptedFromEvent(const SBEvent &event) { LLDB_RECORD_STATIC_METHOD(bool, SBProcess, GetInterruptedFromEvent, (const lldb::SBEvent &), event); return Process::ProcessEventData::GetInterruptedFromEvent(event.get()); } lldb::SBStructuredData SBProcess::GetStructuredDataFromEvent(const lldb::SBEvent &event) { LLDB_RECORD_STATIC_METHOD(lldb::SBStructuredData, SBProcess, GetStructuredDataFromEvent, (const lldb::SBEvent &), event); return LLDB_RECORD_RESULT(SBStructuredData(event.GetSP())); } bool SBProcess::EventIsProcessEvent(const SBEvent &event) { LLDB_RECORD_STATIC_METHOD(bool, SBProcess, EventIsProcessEvent, (const lldb::SBEvent &), event); return (event.GetBroadcasterClass() == SBProcess::GetBroadcasterClass()) && !EventIsStructuredDataEvent(event); } bool SBProcess::EventIsStructuredDataEvent(const lldb::SBEvent &event) { LLDB_RECORD_STATIC_METHOD(bool, SBProcess, EventIsStructuredDataEvent, (const lldb::SBEvent &), event); EventSP event_sp = event.GetSP(); EventData *event_data = event_sp ? event_sp->GetData() : nullptr; return event_data && (event_data->GetFlavor() == EventDataStructuredData::GetFlavorString()); } SBBroadcaster SBProcess::GetBroadcaster() const { LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBBroadcaster, SBProcess, GetBroadcaster); ProcessSP process_sp(GetSP()); SBBroadcaster broadcaster(process_sp.get(), false); return LLDB_RECORD_RESULT(broadcaster); } const char *SBProcess::GetBroadcasterClass() { LLDB_RECORD_STATIC_METHOD_NO_ARGS(const char *, SBProcess, GetBroadcasterClass); return Process::GetStaticBroadcasterClass().AsCString(); } size_t SBProcess::ReadMemory(addr_t addr, void *dst, size_t dst_len, SBError &sb_error) { LLDB_RECORD_DUMMY(size_t, SBProcess, ReadMemory, (lldb::addr_t, void *, size_t, lldb::SBError &), addr, dst, dst_len, sb_error); size_t bytes_read = 0; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); bytes_read = process_sp->ReadMemory(addr, dst, dst_len, sb_error.ref()); } else { sb_error.SetErrorString("process is running"); } } else { sb_error.SetErrorString("SBProcess is invalid"); } return bytes_read; } size_t SBProcess::ReadCStringFromMemory(addr_t addr, void *buf, size_t size, lldb::SBError &sb_error) { LLDB_RECORD_DUMMY(size_t, SBProcess, ReadCStringFromMemory, (lldb::addr_t, void *, size_t, lldb::SBError &), addr, buf, size, sb_error); size_t bytes_read = 0; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); bytes_read = process_sp->ReadCStringFromMemory(addr, (char *)buf, size, sb_error.ref()); } else { sb_error.SetErrorString("process is running"); } } else { sb_error.SetErrorString("SBProcess is invalid"); } return bytes_read; } uint64_t SBProcess::ReadUnsignedFromMemory(addr_t addr, uint32_t byte_size, lldb::SBError &sb_error) { LLDB_RECORD_METHOD(uint64_t, SBProcess, ReadUnsignedFromMemory, (lldb::addr_t, uint32_t, lldb::SBError &), addr, byte_size, sb_error); uint64_t value = 0; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); value = process_sp->ReadUnsignedIntegerFromMemory(addr, byte_size, 0, sb_error.ref()); } else { sb_error.SetErrorString("process is running"); } } else { sb_error.SetErrorString("SBProcess is invalid"); } return value; } lldb::addr_t SBProcess::ReadPointerFromMemory(addr_t addr, lldb::SBError &sb_error) { LLDB_RECORD_METHOD(lldb::addr_t, SBProcess, ReadPointerFromMemory, (lldb::addr_t, lldb::SBError &), addr, sb_error); lldb::addr_t ptr = LLDB_INVALID_ADDRESS; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); ptr = process_sp->ReadPointerFromMemory(addr, sb_error.ref()); } else { sb_error.SetErrorString("process is running"); } } else { sb_error.SetErrorString("SBProcess is invalid"); } return ptr; } size_t SBProcess::WriteMemory(addr_t addr, const void *src, size_t src_len, SBError &sb_error) { LLDB_RECORD_DUMMY(size_t, SBProcess, WriteMemory, (lldb::addr_t, const void *, size_t, lldb::SBError &), addr, src, src_len, sb_error); size_t bytes_written = 0; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); bytes_written = process_sp->WriteMemory(addr, src, src_len, sb_error.ref()); } else { sb_error.SetErrorString("process is running"); } } return bytes_written; } bool SBProcess::GetDescription(SBStream &description) { LLDB_RECORD_METHOD(bool, SBProcess, GetDescription, (lldb::SBStream &), description); Stream &strm = description.ref(); ProcessSP process_sp(GetSP()); if (process_sp) { char path[PATH_MAX]; GetTarget().GetExecutable().GetPath(path, sizeof(path)); Module *exe_module = process_sp->GetTarget().GetExecutableModulePointer(); const char *exe_name = nullptr; if (exe_module) exe_name = exe_module->GetFileSpec().GetFilename().AsCString(); strm.Printf("SBProcess: pid = %" PRIu64 ", state = %s, threads = %d%s%s", process_sp->GetID(), lldb_private::StateAsCString(GetState()), GetNumThreads(), exe_name ? ", executable = " : "", exe_name ? exe_name : ""); } else strm.PutCString("No value"); return true; } SBStructuredData SBProcess::GetExtendedCrashInformation() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBStructuredData, SBProcess, GetExtendedCrashInformation); SBStructuredData data; ProcessSP process_sp(GetSP()); if (!process_sp) return LLDB_RECORD_RESULT(data); PlatformSP platform_sp = process_sp->GetTarget().GetPlatform(); if (!platform_sp) return LLDB_RECORD_RESULT(data); auto expected_data = platform_sp->FetchExtendedCrashInformation(*process_sp.get()); if (!expected_data) return LLDB_RECORD_RESULT(data); StructuredData::ObjectSP fetched_data = *expected_data; data.m_impl_up->SetObjectSP(fetched_data); return LLDB_RECORD_RESULT(data); } uint32_t SBProcess::GetNumSupportedHardwareWatchpoints(lldb::SBError &sb_error) const { LLDB_RECORD_METHOD_CONST(uint32_t, SBProcess, GetNumSupportedHardwareWatchpoints, (lldb::SBError &), sb_error); uint32_t num = 0; ProcessSP process_sp(GetSP()); if (process_sp) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); sb_error.SetError(process_sp->GetWatchpointSupportInfo(num)); } else { sb_error.SetErrorString("SBProcess is invalid"); } return num; } uint32_t SBProcess::LoadImage(lldb::SBFileSpec &sb_remote_image_spec, lldb::SBError &sb_error) { LLDB_RECORD_METHOD(uint32_t, SBProcess, LoadImage, (lldb::SBFileSpec &, lldb::SBError &), sb_remote_image_spec, sb_error); return LoadImage(SBFileSpec(), sb_remote_image_spec, sb_error); } uint32_t SBProcess::LoadImage(const lldb::SBFileSpec &sb_local_image_spec, const lldb::SBFileSpec &sb_remote_image_spec, lldb::SBError &sb_error) { LLDB_RECORD_METHOD( uint32_t, SBProcess, LoadImage, (const lldb::SBFileSpec &, const lldb::SBFileSpec &, lldb::SBError &), sb_local_image_spec, sb_remote_image_spec, sb_error); ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); PlatformSP platform_sp = process_sp->GetTarget().GetPlatform(); return platform_sp->LoadImage(process_sp.get(), *sb_local_image_spec, *sb_remote_image_spec, sb_error.ref()); } else { sb_error.SetErrorString("process is running"); } } else { sb_error.SetErrorString("process is invalid"); } return LLDB_INVALID_IMAGE_TOKEN; } uint32_t SBProcess::LoadImageUsingPaths(const lldb::SBFileSpec &image_spec, SBStringList &paths, lldb::SBFileSpec &loaded_path, lldb::SBError &error) { LLDB_RECORD_METHOD(uint32_t, SBProcess, LoadImageUsingPaths, (const lldb::SBFileSpec &, lldb::SBStringList &, lldb::SBFileSpec &, lldb::SBError &), image_spec, paths, loaded_path, error); ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); PlatformSP platform_sp = process_sp->GetTarget().GetPlatform(); size_t num_paths = paths.GetSize(); std::vector<std::string> paths_vec; paths_vec.reserve(num_paths); for (size_t i = 0; i < num_paths; i++) paths_vec.push_back(paths.GetStringAtIndex(i)); FileSpec loaded_spec; uint32_t token = platform_sp->LoadImageUsingPaths( process_sp.get(), *image_spec, paths_vec, error.ref(), &loaded_spec); if (token != LLDB_INVALID_IMAGE_TOKEN) loaded_path = loaded_spec; return token; } else { error.SetErrorString("process is running"); } } else { error.SetErrorString("process is invalid"); } return LLDB_INVALID_IMAGE_TOKEN; } lldb::SBError SBProcess::UnloadImage(uint32_t image_token) { LLDB_RECORD_METHOD(lldb::SBError, SBProcess, UnloadImage, (uint32_t), image_token); lldb::SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); PlatformSP platform_sp = process_sp->GetTarget().GetPlatform(); sb_error.SetError( platform_sp->UnloadImage(process_sp.get(), image_token)); } else { sb_error.SetErrorString("process is running"); } } else sb_error.SetErrorString("invalid process"); return LLDB_RECORD_RESULT(sb_error); } lldb::SBError SBProcess::SendEventData(const char *event_data) { LLDB_RECORD_METHOD(lldb::SBError, SBProcess, SendEventData, (const char *), event_data); lldb::SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); sb_error.SetError(process_sp->SendEventData(event_data)); } else { sb_error.SetErrorString("process is running"); } } else sb_error.SetErrorString("invalid process"); return LLDB_RECORD_RESULT(sb_error); } uint32_t SBProcess::GetNumExtendedBacktraceTypes() { LLDB_RECORD_METHOD_NO_ARGS(uint32_t, SBProcess, GetNumExtendedBacktraceTypes); ProcessSP process_sp(GetSP()); if (process_sp && process_sp->GetSystemRuntime()) { SystemRuntime *runtime = process_sp->GetSystemRuntime(); return runtime->GetExtendedBacktraceTypes().size(); } return 0; } const char *SBProcess::GetExtendedBacktraceTypeAtIndex(uint32_t idx) { LLDB_RECORD_METHOD(const char *, SBProcess, GetExtendedBacktraceTypeAtIndex, (uint32_t), idx); ProcessSP process_sp(GetSP()); if (process_sp && process_sp->GetSystemRuntime()) { SystemRuntime *runtime = process_sp->GetSystemRuntime(); const std::vector<ConstString> &names = runtime->GetExtendedBacktraceTypes(); if (idx < names.size()) { return names[idx].AsCString(); } } return nullptr; } SBThreadCollection SBProcess::GetHistoryThreads(addr_t addr) { LLDB_RECORD_METHOD(lldb::SBThreadCollection, SBProcess, GetHistoryThreads, (lldb::addr_t), addr); ProcessSP process_sp(GetSP()); SBThreadCollection threads; if (process_sp) { threads = SBThreadCollection(process_sp->GetHistoryThreads(addr)); } return LLDB_RECORD_RESULT(threads); } bool SBProcess::IsInstrumentationRuntimePresent( InstrumentationRuntimeType type) { LLDB_RECORD_METHOD(bool, SBProcess, IsInstrumentationRuntimePresent, (lldb::InstrumentationRuntimeType), type); ProcessSP process_sp(GetSP()); if (!process_sp) return false; std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); InstrumentationRuntimeSP runtime_sp = process_sp->GetInstrumentationRuntime(type); if (!runtime_sp.get()) return false; return runtime_sp->IsActive(); } lldb::SBError SBProcess::SaveCore(const char *file_name) { LLDB_RECORD_METHOD(lldb::SBError, SBProcess, SaveCore, (const char *), file_name); lldb::SBError error; ProcessSP process_sp(GetSP()); if (!process_sp) { error.SetErrorString("SBProcess is invalid"); return LLDB_RECORD_RESULT(error); } std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); if (process_sp->GetState() != eStateStopped) { error.SetErrorString("the process is not stopped"); return LLDB_RECORD_RESULT(error); } FileSpec core_file(file_name); SaveCoreStyle core_style = SaveCoreStyle::eSaveCoreFull; error.ref() = PluginManager::SaveCore(process_sp, core_file, core_style, ConstString()); return LLDB_RECORD_RESULT(error); } lldb::SBError SBProcess::GetMemoryRegionInfo(lldb::addr_t load_addr, SBMemoryRegionInfo &sb_region_info) { LLDB_RECORD_METHOD(lldb::SBError, SBProcess, GetMemoryRegionInfo, (lldb::addr_t, lldb::SBMemoryRegionInfo &), load_addr, sb_region_info); lldb::SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); sb_error.ref() = process_sp->GetMemoryRegionInfo(load_addr, sb_region_info.ref()); } else { sb_error.SetErrorString("process is running"); } } else { sb_error.SetErrorString("SBProcess is invalid"); } return LLDB_RECORD_RESULT(sb_error); } lldb::SBMemoryRegionInfoList SBProcess::GetMemoryRegions() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBMemoryRegionInfoList, SBProcess, GetMemoryRegions); lldb::SBMemoryRegionInfoList sb_region_list; ProcessSP process_sp(GetSP()); Process::StopLocker stop_locker; if (process_sp && stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); process_sp->GetMemoryRegions(sb_region_list.ref()); } return LLDB_RECORD_RESULT(sb_region_list); } lldb::SBProcessInfo SBProcess::GetProcessInfo() { LLDB_RECORD_METHOD_NO_ARGS(lldb::SBProcessInfo, SBProcess, GetProcessInfo); lldb::SBProcessInfo sb_proc_info; ProcessSP process_sp(GetSP()); ProcessInstanceInfo proc_info; if (process_sp && process_sp->GetProcessInfo(proc_info)) { sb_proc_info.SetProcessInfo(proc_info); } return LLDB_RECORD_RESULT(sb_proc_info); } lldb::addr_t SBProcess::AllocateMemory(size_t size, uint32_t permissions, lldb::SBError &sb_error) { LLDB_RECORD_METHOD(lldb::addr_t, SBProcess, AllocateMemory, (size_t, uint32_t, lldb::SBError &), size, permissions, sb_error); lldb::addr_t addr = LLDB_INVALID_ADDRESS; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); addr = process_sp->AllocateMemory(size, permissions, sb_error.ref()); } else { sb_error.SetErrorString("process is running"); } } else { sb_error.SetErrorString("SBProcess is invalid"); } return addr; } lldb::SBError SBProcess::DeallocateMemory(lldb::addr_t ptr) { LLDB_RECORD_METHOD(lldb::SBError, SBProcess, DeallocateMemory, (lldb::addr_t), ptr); lldb::SBError sb_error; ProcessSP process_sp(GetSP()); if (process_sp) { Process::StopLocker stop_locker; if (stop_locker.TryLock(&process_sp->GetRunLock())) { std::lock_guard<std::recursive_mutex> guard( process_sp->GetTarget().GetAPIMutex()); Status error = process_sp->DeallocateMemory(ptr); sb_error.SetError(error); } else { sb_error.SetErrorString("process is running"); } } else { sb_error.SetErrorString("SBProcess is invalid"); } return sb_error; } namespace lldb_private { namespace repro { template <> void RegisterMethods<SBProcess>(Registry &R) { LLDB_REGISTER_CONSTRUCTOR(SBProcess, ()); LLDB_REGISTER_CONSTRUCTOR(SBProcess, (const lldb::SBProcess &)); LLDB_REGISTER_CONSTRUCTOR(SBProcess, (const lldb::ProcessSP &)); LLDB_REGISTER_METHOD(const lldb::SBProcess &, SBProcess, operator=,(const lldb::SBProcess &)); LLDB_REGISTER_STATIC_METHOD(const char *, SBProcess, GetBroadcasterClassName, ()); LLDB_REGISTER_METHOD(const char *, SBProcess, GetPluginName, ()); LLDB_REGISTER_METHOD(const char *, SBProcess, GetShortPluginName, ()); LLDB_REGISTER_METHOD(void, SBProcess, Clear, ()); LLDB_REGISTER_METHOD_CONST(bool, SBProcess, IsValid, ()); LLDB_REGISTER_METHOD_CONST(bool, SBProcess, operator bool, ()); LLDB_REGISTER_METHOD(bool, SBProcess, RemoteLaunch, (const char **, const char **, const char *, const char *, const char *, const char *, uint32_t, bool, lldb::SBError &)); LLDB_REGISTER_METHOD(bool, SBProcess, RemoteAttachToProcessWithID, (lldb::pid_t, lldb::SBError &)); LLDB_REGISTER_METHOD(uint32_t, SBProcess, GetNumThreads, ()); LLDB_REGISTER_METHOD_CONST(lldb::SBThread, SBProcess, GetSelectedThread, ()); LLDB_REGISTER_METHOD(lldb::SBThread, SBProcess, CreateOSPluginThread, (lldb::tid_t, lldb::addr_t)); LLDB_REGISTER_METHOD_CONST(lldb::SBTarget, SBProcess, GetTarget, ()); LLDB_REGISTER_METHOD(size_t, SBProcess, PutSTDIN, (const char *, size_t)); LLDB_REGISTER_METHOD_CONST(void, SBProcess, ReportEventState, (const lldb::SBEvent &, FILE *)); LLDB_REGISTER_METHOD_CONST(void, SBProcess, ReportEventState, (const lldb::SBEvent &, FileSP)); LLDB_REGISTER_METHOD_CONST(void, SBProcess, ReportEventState, (const lldb::SBEvent &, SBFile)); LLDB_REGISTER_METHOD( void, SBProcess, AppendEventStateReport, (const lldb::SBEvent &, lldb::SBCommandReturnObject &)); LLDB_REGISTER_METHOD(bool, SBProcess, SetSelectedThread, (const lldb::SBThread &)); LLDB_REGISTER_METHOD(bool, SBProcess, SetSelectedThreadByID, (lldb::tid_t)); LLDB_REGISTER_METHOD(bool, SBProcess, SetSelectedThreadByIndexID, (uint32_t)); LLDB_REGISTER_METHOD(lldb::SBThread, SBProcess, GetThreadAtIndex, (size_t)); LLDB_REGISTER_METHOD(uint32_t, SBProcess, GetNumQueues, ()); LLDB_REGISTER_METHOD(lldb::SBQueue, SBProcess, GetQueueAtIndex, (size_t)); LLDB_REGISTER_METHOD(uint32_t, SBProcess, GetStopID, (bool)); LLDB_REGISTER_METHOD(lldb::SBEvent, SBProcess, GetStopEventForStopID, (uint32_t)); LLDB_REGISTER_METHOD(lldb::StateType, SBProcess, GetState, ()); LLDB_REGISTER_METHOD(int, SBProcess, GetExitStatus, ()); LLDB_REGISTER_METHOD(const char *, SBProcess, GetExitDescription, ()); LLDB_REGISTER_METHOD(lldb::pid_t, SBProcess, GetProcessID, ()); LLDB_REGISTER_METHOD(uint32_t, SBProcess, GetUniqueID, ()); LLDB_REGISTER_METHOD_CONST(lldb::ByteOrder, SBProcess, GetByteOrder, ()); LLDB_REGISTER_METHOD_CONST(uint32_t, SBProcess, GetAddressByteSize, ()); LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Continue, ()); LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Destroy, ()); LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Stop, ()); LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Kill, ()); LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Detach, ()); LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Detach, (bool)); LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, Signal, (int)); LLDB_REGISTER_METHOD(lldb::SBUnixSignals, SBProcess, GetUnixSignals, ()); LLDB_REGISTER_METHOD(void, SBProcess, SendAsyncInterrupt, ()); LLDB_REGISTER_METHOD(lldb::SBThread, SBProcess, GetThreadByID, (lldb::tid_t)); LLDB_REGISTER_METHOD(lldb::SBThread, SBProcess, GetThreadByIndexID, (uint32_t)); LLDB_REGISTER_STATIC_METHOD(lldb::StateType, SBProcess, GetStateFromEvent, (const lldb::SBEvent &)); LLDB_REGISTER_STATIC_METHOD(bool, SBProcess, GetRestartedFromEvent, (const lldb::SBEvent &)); LLDB_REGISTER_STATIC_METHOD(size_t, SBProcess, GetNumRestartedReasonsFromEvent, (const lldb::SBEvent &)); LLDB_REGISTER_STATIC_METHOD(const char *, SBProcess, GetRestartedReasonAtIndexFromEvent, (const lldb::SBEvent &, size_t)); LLDB_REGISTER_STATIC_METHOD(lldb::SBProcess, SBProcess, GetProcessFromEvent, (const lldb::SBEvent &)); LLDB_REGISTER_STATIC_METHOD(bool, SBProcess, GetInterruptedFromEvent, (const lldb::SBEvent &)); LLDB_REGISTER_STATIC_METHOD(lldb::SBStructuredData, SBProcess, GetStructuredDataFromEvent, (const lldb::SBEvent &)); LLDB_REGISTER_STATIC_METHOD(bool, SBProcess, EventIsProcessEvent, (const lldb::SBEvent &)); LLDB_REGISTER_STATIC_METHOD(bool, SBProcess, EventIsStructuredDataEvent, (const lldb::SBEvent &)); LLDB_REGISTER_METHOD_CONST(lldb::SBBroadcaster, SBProcess, GetBroadcaster, ()); LLDB_REGISTER_STATIC_METHOD(const char *, SBProcess, GetBroadcasterClass, ()); LLDB_REGISTER_METHOD(uint64_t, SBProcess, ReadUnsignedFromMemory, (lldb::addr_t, uint32_t, lldb::SBError &)); LLDB_REGISTER_METHOD(lldb::addr_t, SBProcess, ReadPointerFromMemory, (lldb::addr_t, lldb::SBError &)); LLDB_REGISTER_METHOD(bool, SBProcess, GetDescription, (lldb::SBStream &)); LLDB_REGISTER_METHOD(lldb::SBStructuredData, SBProcess, GetExtendedCrashInformation, ()); LLDB_REGISTER_METHOD_CONST(uint32_t, SBProcess, GetNumSupportedHardwareWatchpoints, (lldb::SBError &)); LLDB_REGISTER_METHOD(uint32_t, SBProcess, LoadImage, (lldb::SBFileSpec &, lldb::SBError &)); LLDB_REGISTER_METHOD( uint32_t, SBProcess, LoadImage, (const lldb::SBFileSpec &, const lldb::SBFileSpec &, lldb::SBError &)); LLDB_REGISTER_METHOD(uint32_t, SBProcess, LoadImageUsingPaths, (const lldb::SBFileSpec &, lldb::SBStringList &, lldb::SBFileSpec &, lldb::SBError &)); LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, UnloadImage, (uint32_t)); LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, SendEventData, (const char *)); LLDB_REGISTER_METHOD(uint32_t, SBProcess, GetNumExtendedBacktraceTypes, ()); LLDB_REGISTER_METHOD(const char *, SBProcess, GetExtendedBacktraceTypeAtIndex, (uint32_t)); LLDB_REGISTER_METHOD(lldb::SBThreadCollection, SBProcess, GetHistoryThreads, (lldb::addr_t)); LLDB_REGISTER_METHOD(bool, SBProcess, IsInstrumentationRuntimePresent, (lldb::InstrumentationRuntimeType)); LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, SaveCore, (const char *)); LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, GetMemoryRegionInfo, (lldb::addr_t, lldb::SBMemoryRegionInfo &)); LLDB_REGISTER_METHOD(lldb::SBMemoryRegionInfoList, SBProcess, GetMemoryRegions, ()); LLDB_REGISTER_METHOD(lldb::SBProcessInfo, SBProcess, GetProcessInfo, ()); LLDB_REGISTER_METHOD(lldb::addr_t, SBProcess, AllocateMemory, (size_t, uint32_t, lldb::SBError &)); LLDB_REGISTER_METHOD(lldb::SBError, SBProcess, DeallocateMemory, (lldb::addr_t)); LLDB_REGISTER_CHAR_PTR_METHOD_CONST(size_t, SBProcess, GetSTDOUT); LLDB_REGISTER_CHAR_PTR_METHOD_CONST(size_t, SBProcess, GetSTDERR); LLDB_REGISTER_CHAR_PTR_METHOD_CONST(size_t, SBProcess, GetAsyncProfileData); } } }
21,816
344
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "errorConfigurationFileDirty": "Non è possibile scrivere nel file di configurazione. Il file di configurazione è modificato ma non salvato", "errorInvalidConfiguration": "Non è possibile scrivere nel file di configurazione. Il file di configurazione trovato non è valido", "errorUnknownKey": "Non è possibile scrivere nel file di configurazione. La chiave è sconosciuta", "errorWorkspaceOpened": "Non è possibile scrivere nel file di configurazione. Non è stata aperta alcuna area di lavoro" }
232
434
/* * ALFA Network AP91-5G board support * * Copyright (C) 2018 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include <linux/gpio.h> #include <linux/platform_device.h> #include <asm/mach-ath79/ath79.h> #include <asm/mach-ath79/ar71xx_regs.h> #include "common.h" #include "dev-ap9x-pci.h" #include "dev-eth.h" #include "dev-gpio-buttons.h" #include "dev-leds-gpio.h" #include "dev-m25p80.h" #include "machtypes.h" #define AP91_5G_GPIO_LED_LAN 17 #define AP91_5G_GPIO_LED_SIGNAL1 12 #define AP91_5G_GPIO_LED_SIGNAL2 8 #define AP91_5G_GPIO_LED_SIGNAL3 6 #define AP91_5G_GPIO_LED_SIGNAL4 7 #define AP91_5G_GPIO_WDT_EN 1 #define AP91_5G_GPIO_WDT_IN 0 #define AP91_5G_GPIO_BTN_RESET 11 #define AP91_5G_KEYS_POLL_INTERVAL 20 #define AP91_5G_KEYS_DEBOUNCE_INTERVAL (3 * AP91_5G_KEYS_POLL_INTERVAL) #define AP91_5G_WMAC_CALDATA_OFFSET 0x1000 static struct gpio_led ap91_5g_leds_gpio[] __initdata = { { .name = "ap91-5g:green:lan", .gpio = AP91_5G_GPIO_LED_LAN, .active_low = 1, }, { .name = "ap91-5g:red:signal1", .gpio = AP91_5G_GPIO_LED_SIGNAL1, .active_low = 1, }, { .name = "ap91-5g:orange:signal2", .gpio = AP91_5G_GPIO_LED_SIGNAL2, .active_low = 1, }, { .name = "ap91-5g:green:signal3", .gpio = AP91_5G_GPIO_LED_SIGNAL3, .active_low = 1, }, { .name = "ap91-5g:green:signal4", .gpio = AP91_5G_GPIO_LED_SIGNAL4, .active_low = 1, }, }; static struct gpio_keys_button ap91_5g_gpio_keys[] __initdata = { { .desc = "reset", .type = EV_KEY, .code = KEY_RESTART, .debounce_interval = AP91_5G_KEYS_DEBOUNCE_INTERVAL, .gpio = AP91_5G_GPIO_BTN_RESET, .active_low = 1, }, }; static void __init ap91_5g_setup(void) { u8 *art = (u8 *) KSEG1ADDR(0x1fff0000); ath79_gpio_function_setup(AR724X_GPIO_FUNC_JTAG_DISABLE, AR724X_GPIO_FUNC_ETH_SWITCH_LED4_EN); gpio_set_value(AP91_5G_GPIO_LED_LAN, 1); gpio_set_value(AP91_5G_GPIO_LED_SIGNAL3, 1); gpio_set_value(AP91_5G_GPIO_LED_SIGNAL4, 1); ath79_register_m25p80(NULL); ath79_register_mdio(0, 0x0); /* LAN */ ath79_eth0_data.duplex = DUPLEX_FULL; ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_MII; ath79_eth0_data.phy_mask = BIT(4); ath79_eth0_data.speed = SPEED_100; ath79_init_mac(ath79_eth0_data.mac_addr, art, 0); ath79_register_eth(0); ath79_register_leds_gpio(-1, ARRAY_SIZE(ap91_5g_leds_gpio), ap91_5g_leds_gpio); ath79_register_gpio_keys_polled(-1, AP91_5G_KEYS_POLL_INTERVAL, ARRAY_SIZE(ap91_5g_gpio_keys), ap91_5g_gpio_keys); gpio_request_one(AP91_5G_GPIO_WDT_IN, GPIOF_OUT_INIT_LOW | GPIOF_EXPORT_DIR_FIXED, "WDT input"); gpio_request_one(AP91_5G_GPIO_WDT_EN, GPIOF_OUT_INIT_LOW | GPIOF_EXPORT_DIR_FIXED, "WDT enable"); ap91_pci_init(art + AP91_5G_WMAC_CALDATA_OFFSET, NULL); } MIPS_MACHINE(ATH79_MACH_AP91_5G, "AP91-5G", "ALFA Network AP91-5G", ap91_5g_setup);
1,570
778
<gh_stars>100-1000 // // Project Name: KratosPfemSolidMechanicsApplication $ // Created by: $Author: LMonforte $ // Last modified by: $Co-Author: $ // Date: $Date: July 2018 $ // Revision: $Revision: 0.0 $ // // #if !defined ( KRATOS_NON_LOCAL_PLASTICITY_PROCESS_H_INCLUDED ) #define KRATOS_NON_LOCAL_PLASTICITY_PROCESS_H_INCLUDED /* System includes */ /* External includes */ /* Project includes */ #include "processes/process.h" #include "includes/model_part.h" #include "includes/kratos_flags.h" #include "utilities/math_utils.h" #include "constitutive_models_application_variables.h" #include "includes/kratos_parameters.h" namespace Kratos { class KRATOS_API(CONSTITUTIVE_MODELS_APPLICATION) NonLocalPlasticityProcess : public Process { protected: struct GaussPoint { GaussPoint() {} GaussPoint( ConstitutiveLaw::Pointer & pConstLaw, array_1d<double, 3> rCoord) { pConstitutiveLaw = pConstLaw; Coordinates = rCoord; } void AddNeighbour( const int & rID, double weight) { NeighbourGP.push_back( rID); NeighbourWeight.push_back(weight); } ConstitutiveLaw::Pointer pConstitutiveLaw; array_1d<double, 3> Coordinates; std::vector< int > NeighbourGP; std::vector<double> NeighbourWeight; }; public: /**@name Type Definitions */ /*@{ */ // Pointer definition of Process KRATOS_CLASS_POINTER_DEFINITION( NonLocalPlasticityProcess ); typedef ModelPart::NodesContainerType NodesArrayType; typedef ModelPart::ConditionsContainerType ConditionsContainerType; typedef ModelPart::MeshType MeshType; /*@} */ /**@name Life Cycle */ /*@{ */ // Constructor. NonLocalPlasticityProcess( ModelPart& rModelPart, Parameters rParameters); /** Destructor. */ virtual ~NonLocalPlasticityProcess(); /*@} */ /**@name Operators */ /*@{ */ /*@} */ /**@name Operations */ /*@{ */ void operator()() { Execute(); } void Execute() override; protected: void PerformGaussPointSearch( std::vector< GaussPoint > & rNeighbourGP, const double CharacteristicLength); double& ComputeWeightFunction( const double& rDistance, const double & rCharacteristicLength, double & rAlpha); private: // member variables ModelPart& mrModelPart; double mCharacteristicLength; std::vector< Variable<double> > mLocalVariables; std::vector< Variable<double> > mNonLocalVariables; }; //end class NonLocalPlasticityProcess } // END namespace Kratos #endif //KRATOS_NON_LOCAL_PLASTICITY_PROCESS_H_INCLUDED
1,779
7,353
#define BLOG_CHANNEL_server 0 #define BLOG_CHANNEL_client 1 #define BLOG_CHANNEL_flooder 2 #define BLOG_CHANNEL_tun2socks 3 #define BLOG_CHANNEL_ncd 4 #define BLOG_CHANNEL_ncd_var 5 #define BLOG_CHANNEL_ncd_list 6 #define BLOG_CHANNEL_ncd_depend 7 #define BLOG_CHANNEL_ncd_multidepend 8 #define BLOG_CHANNEL_ncd_dynamic_depend 9 #define BLOG_CHANNEL_ncd_concat 10 #define BLOG_CHANNEL_ncd_if 11 #define BLOG_CHANNEL_ncd_strcmp 12 #define BLOG_CHANNEL_ncd_regex_match 13 #define BLOG_CHANNEL_ncd_logical 14 #define BLOG_CHANNEL_ncd_sleep 15 #define BLOG_CHANNEL_ncd_print 16 #define BLOG_CHANNEL_ncd_blocker 17 #define BLOG_CHANNEL_ncd_run 18 #define BLOG_CHANNEL_ncd_runonce 19 #define BLOG_CHANNEL_ncd_daemon 20 #define BLOG_CHANNEL_ncd_spawn 21 #define BLOG_CHANNEL_ncd_imperative 22 #define BLOG_CHANNEL_ncd_ref 23 #define BLOG_CHANNEL_ncd_index 24 #define BLOG_CHANNEL_ncd_alias 25 #define BLOG_CHANNEL_ncd_process_manager 26 #define BLOG_CHANNEL_ncd_ondemand 27 #define BLOG_CHANNEL_ncd_foreach 28 #define BLOG_CHANNEL_ncd_choose 29 #define BLOG_CHANNEL_ncd_net_backend_waitdevice 30 #define BLOG_CHANNEL_ncd_net_backend_waitlink 31 #define BLOG_CHANNEL_ncd_net_backend_badvpn 32 #define BLOG_CHANNEL_ncd_net_backend_wpa_supplicant 33 #define BLOG_CHANNEL_ncd_net_backend_rfkill 34 #define BLOG_CHANNEL_ncd_net_up 35 #define BLOG_CHANNEL_ncd_net_dns 36 #define BLOG_CHANNEL_ncd_net_iptables 37 #define BLOG_CHANNEL_ncd_net_ipv4_addr 38 #define BLOG_CHANNEL_ncd_net_ipv4_route 39 #define BLOG_CHANNEL_ncd_net_ipv4_dhcp 40 #define BLOG_CHANNEL_ncd_net_ipv4_arp_probe 41 #define BLOG_CHANNEL_ncd_net_watch_interfaces 42 #define BLOG_CHANNEL_ncd_sys_watch_input 43 #define BLOG_CHANNEL_ncd_sys_watch_usb 44 #define BLOG_CHANNEL_ncd_sys_evdev 45 #define BLOG_CHANNEL_ncd_sys_watch_directory 46 #define BLOG_CHANNEL_StreamPeerIO 47 #define BLOG_CHANNEL_DatagramPeerIO 48 #define BLOG_CHANNEL_BReactor 49 #define BLOG_CHANNEL_BSignal 50 #define BLOG_CHANNEL_FragmentProtoAssembler 51 #define BLOG_CHANNEL_BPredicate 52 #define BLOG_CHANNEL_ServerConnection 53 #define BLOG_CHANNEL_Listener 54 #define BLOG_CHANNEL_DataProto 55 #define BLOG_CHANNEL_FrameDecider 56 #define BLOG_CHANNEL_BSocksClient 57 #define BLOG_CHANNEL_BDHCPClientCore 58 #define BLOG_CHANNEL_BDHCPClient 59 #define BLOG_CHANNEL_NCDIfConfig 60 #define BLOG_CHANNEL_BUnixSignal 61 #define BLOG_CHANNEL_BProcess 62 #define BLOG_CHANNEL_PRStreamSink 63 #define BLOG_CHANNEL_PRStreamSource 64 #define BLOG_CHANNEL_PacketProtoDecoder 65 #define BLOG_CHANNEL_DPRelay 66 #define BLOG_CHANNEL_BThreadWork 67 #define BLOG_CHANNEL_DPReceive 68 #define BLOG_CHANNEL_BInputProcess 69 #define BLOG_CHANNEL_NCDUdevMonitorParser 70 #define BLOG_CHANNEL_NCDUdevMonitor 71 #define BLOG_CHANNEL_NCDUdevCache 72 #define BLOG_CHANNEL_NCDUdevManager 73 #define BLOG_CHANNEL_BTime 74 #define BLOG_CHANNEL_BEncryption 75 #define BLOG_CHANNEL_SPProtoDecoder 76 #define BLOG_CHANNEL_LineBuffer 77 #define BLOG_CHANNEL_BTap 78 #define BLOG_CHANNEL_lwip 79 #define BLOG_CHANNEL_NCDConfigTokenizer 80 #define BLOG_CHANNEL_NCDConfigParser 81 #define BLOG_CHANNEL_NCDValParser 82 #define BLOG_CHANNEL_nsskey 83 #define BLOG_CHANNEL_addr 84 #define BLOG_CHANNEL_PasswordListener 85 #define BLOG_CHANNEL_NCDInterfaceMonitor 86 #define BLOG_CHANNEL_NCDRfkillMonitor 87 #define BLOG_CHANNEL_udpgw 88 #define BLOG_CHANNEL_UdpGwClient 89 #define BLOG_CHANNEL_SocksUdpGwClient 90 #define BLOG_CHANNEL_BNetwork 91 #define BLOG_CHANNEL_BConnection 92 #define BLOG_CHANNEL_BSSLConnection 93 #define BLOG_CHANNEL_BDatagram 94 #define BLOG_CHANNEL_PeerChat 95 #define BLOG_CHANNEL_BArpProbe 96 #define BLOG_CHANNEL_NCDModuleIndex 97 #define BLOG_CHANNEL_NCDModuleProcess 98 #define BLOG_CHANNEL_NCDValGenerator 99 #define BLOG_CHANNEL_ncd_from_string 100 #define BLOG_CHANNEL_ncd_to_string 101 #define BLOG_CHANNEL_ncd_value 102 #define BLOG_CHANNEL_ncd_try 103 #define BLOG_CHANNEL_ncd_sys_request_server 104 #define BLOG_CHANNEL_NCDRequest 105 #define BLOG_CHANNEL_ncd_net_ipv6_wait_dynamic_addr 106 #define BLOG_CHANNEL_NCDRequestClient 107 #define BLOG_CHANNEL_ncd_request 108 #define BLOG_CHANNEL_ncd_sys_request_client 109 #define BLOG_CHANNEL_ncd_exit 110 #define BLOG_CHANNEL_ncd_getargs 111 #define BLOG_CHANNEL_ncd_arithmetic 112 #define BLOG_CHANNEL_ncd_parse 113 #define BLOG_CHANNEL_ncd_valuemetic 114 #define BLOG_CHANNEL_ncd_file 115 #define BLOG_CHANNEL_ncd_netmask 116 #define BLOG_CHANNEL_ncd_implode 117 #define BLOG_CHANNEL_ncd_call2 118 #define BLOG_CHANNEL_ncd_assert 119 #define BLOG_CHANNEL_ncd_reboot 120 #define BLOG_CHANNEL_ncd_explode 121 #define BLOG_CHANNEL_NCDPlaceholderDb 122 #define BLOG_CHANNEL_NCDVal 123 #define BLOG_CHANNEL_ncd_net_ipv6_addr 124 #define BLOG_CHANNEL_ncd_net_ipv6_route 125 #define BLOG_CHANNEL_ncd_net_ipv4_addr_in_network 126 #define BLOG_CHANNEL_ncd_net_ipv6_addr_in_network 127 #define BLOG_CHANNEL_dostest_server 128 #define BLOG_CHANNEL_dostest_attacker 129 #define BLOG_CHANNEL_ncd_timer 130 #define BLOG_CHANNEL_ncd_file_open 131 #define BLOG_CHANNEL_ncd_backtrack 132 #define BLOG_CHANNEL_ncd_socket 133 #define BLOG_CHANNEL_ncd_depend_scope 134 #define BLOG_CHANNEL_ncd_substr 135 #define BLOG_CHANNEL_ncd_sys_start_process 136 #define BLOG_CHANNEL_NCDBuildProgram 137 #define BLOG_CHANNEL_ncd_log 138 #define BLOG_CHANNEL_ncd_log_msg 139 #define BLOG_CHANNEL_ncd_buffer 140 #define BLOG_CHANNEL_ncd_getenv 141 #define BLOG_CHANNEL_BThreadSignal 142 #define BLOG_CHANNEL_BLockReactor 143 #define BLOG_CHANNEL_ncd_load_module 144 #define BLOG_CHANNEL_SocksUdpClient 145 #define BLOG_NUM_CHANNELS 146
2,373
382
/* * Copyright 2020 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 com.netflix.spinnaker.clouddriver.model.view; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public interface ModelObjectViewModelPostProcessor<T> { static <R> R applyExtensionsToObject( Optional<List<ModelObjectViewModelPostProcessor<R>>> extensions, R object) { return extensions .map(exts -> exts.stream().filter(ext -> ext.supports(object)).collect(Collectors.toList())) .filter(exts -> !exts.isEmpty()) .map( exts -> { for (ModelObjectViewModelPostProcessor<R> extension : exts) { extension.process(object); } return object; }) .orElse(object); } static <R> Collection<R> applyExtensions( Optional<List<ModelObjectViewModelPostProcessor<R>>> extensions, Collection<R> objects) { return extensions .map( ext -> (Collection<R>) objects.stream() .map(o -> applyExtensionsToObject(extensions, o)) .collect(Collectors.toList())) .orElse(objects); } boolean supports(T instance); void process(T model); }
699
310
<gh_stars>100-1000 { "name": "N9", "description": "A MeeGo-based smartphone.", "url": "https://en.wikipedia.org/wiki/Nokia_N9" }
57
335
/* * Copyright 2019-2020 the original author or authors. * * 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 * * https://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.vividus.proxy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.stream.Stream; import com.browserup.bup.BrowserUpProxyServer; import com.browserup.bup.filters.RequestFilter; import com.browserup.bup.filters.RequestFilterAdapter; import com.browserup.bup.filters.ResponseFilter; import com.browserup.bup.filters.ResponseFilterAdapter; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.littleshoot.proxy.HttpFiltersSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.openqa.selenium.Proxy.ProxyType; @ExtendWith(MockitoExtension.class) class ProxyTests { @Mock private IProxyServerFactory proxyServerFactory; @Mock private BrowserUpProxyServer browserUpProxyServer; @InjectMocks private Proxy proxy; @Test void testIfNotStartedAfterCreation() { assertFalse(proxy.isStarted()); verifyNoInteractions(proxyServerFactory); } @Test void testStart() { when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); proxy.start(); verify(browserUpProxyServer).start(); } @Test void testStartOnAddr() throws UnknownHostException { when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); InetAddress address = InetAddress.getLocalHost(); int port = 8080; proxy.start(port, address); verify(browserUpProxyServer).start(port, address); } @Test void testStartTwice() { when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); proxy.start(); proxy.start(); verify(browserUpProxyServer, times(1)).start(); } @Test void testGetServer() { when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); proxy.start(); assertEquals(browserUpProxyServer, proxy.getProxyServer()); } @Test void testStop() { when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); proxy.start(); proxy.stop(); verify(browserUpProxyServer).stop(); assertNull(proxy.getProxyServer()); } @Test void testStopTwice() { when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); proxy.start(); proxy.stop(); proxy.stop(); verify(browserUpProxyServer, times(1)).stop(); } @Test void testStartRecording() { when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); proxy.start(); proxy.startRecording(); verify(browserUpProxyServer).newHar(); } @Test void testClearRecordedData() { when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); proxy.start(); proxy.clearRecordedData(); verify(browserUpProxyServer).newHar(); } @Test void testGetRecordedData() { when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); proxy.start(); proxy.getRecordedData(); verify(browserUpProxyServer).getHar(); } @Test void testStopRecording() { when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); proxy.start(); proxy.startRecording(); proxy.stopRecording(); verify(browserUpProxyServer).endHar(); } @Test void testAddRequestFilter() { RequestFilter requestFilter = mock(RequestFilter.class); when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); proxy.start(); proxy.addRequestFilter(requestFilter); verify(browserUpProxyServer).addRequestFilter(requestFilter); } @Test void testClearRequestFilters() { BrowserUpProxyServer browserUpProxyServer = mock(BrowserUpProxyServer.class); ResponseFilter responseFilter = mock(ResponseFilter.class); RequestFilter requestFilter = mock(RequestFilter.class); ResponseFilterAdapter.FilterSource fsResponse = new ResponseFilterAdapter.FilterSource(responseFilter); RequestFilterAdapter.FilterSource fsRequest = new RequestFilterAdapter.FilterSource(requestFilter); when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); List<HttpFiltersSource> toRemove = new ArrayList<>(); toRemove.add(fsResponse); toRemove.add(fsRequest); when(browserUpProxyServer.getFilterFactories()).thenReturn(toRemove).thenReturn(toRemove); proxy.start(); proxy.clearRequestFilters(); assertTrue(toRemove.size() == 1 && toRemove.contains(fsResponse)); } @Test void shouldCreateSeleniumProxy() { when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); proxy.start(); when(browserUpProxyServer.getPort()).thenReturn(101); org.openqa.selenium.Proxy seleniumProxy = proxy.createSeleniumProxy(); assertEquals(InetAddress.getLoopbackAddress().getHostName() + ":101", seleniumProxy.getHttpProxy()); } @Test void shouldUseProvidedHostForASeleniumProxy() { Proxy proxy = new Proxy(proxyServerFactory, "host.docker.internal"); when(proxyServerFactory.createProxyServer()).thenReturn(browserUpProxyServer); proxy.start(); when(browserUpProxyServer.getPort()).thenReturn(101); org.openqa.selenium.Proxy seleniumProxy = proxy.createSeleniumProxy(); String proxyHostAndPort = "host.docker.internal:101"; assertEquals(proxyHostAndPort, seleniumProxy.getHttpProxy()); assertEquals(proxyHostAndPort, seleniumProxy.getSslProxy()); assertEquals(ProxyType.MANUAL, seleniumProxy.getProxyType()); } static Stream<Consumer<Proxy>> proxyActions() { return Stream.of( Proxy::startRecording, Proxy::stopRecording, Proxy::getRecordedData, Proxy::clearRecordedData, Proxy::clearRequestFilters, Proxy::createSeleniumProxy, proxy -> proxy.addRequestFilter(mock(RequestFilter.class)) ); } @ParameterizedTest @MethodSource("proxyActions") void shouldNotRunProxyActionWhenProxyIsNotStarted(Consumer<Proxy> proxyAction) { IllegalStateException exception = assertThrows(IllegalStateException.class, () -> proxyAction.accept(proxy)); assertEquals("Proxy is not started", exception.getMessage()); verifyNoInteractions(browserUpProxyServer); } }
2,986
1,656
/* * Copyright 2013-2021 the original author or authors. * * 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 * * https://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.springframework.cloud.sleuth.instrument.reactor.sample; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import java.util.stream.Collectors; import org.awaitility.Awaitility; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.cloud.sleuth.CurrentTraceContext; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.Tracer; import org.springframework.cloud.sleuth.autoconfig.instrument.reactor.Issue866Configuration; import org.springframework.cloud.sleuth.autoconfig.instrument.reactor.TraceReactorAutoConfigurationAccessorConfiguration; import org.springframework.cloud.sleuth.exporter.FinishedSpan; import org.springframework.cloud.sleuth.instrument.web.WebFluxSleuthOperators; import org.springframework.cloud.sleuth.test.TestSpanHandler; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.BDDAssertions.then; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RouterFunctions.route; // https://github.com/spring-cloud/spring-cloud-sleuth/issues/850 @ExtendWith(OutputCaptureExtension.class) public abstract class FlatMapTests { private static final Logger LOGGER = LoggerFactory.getLogger(FlatMapTests.class); @BeforeAll public static void setup() { TraceReactorAutoConfigurationAccessorConfiguration.close(); Issue866Configuration.hook = null; } @AfterAll public static void cleanup() { Issue866Configuration.hook = null; } @Test public void should_work_with_flat_maps_with_on_queues_instrumentation(CapturedOutput capture) { // given ConfigurableApplicationContext context = new SpringApplicationBuilder(FlatMapTests.TestConfiguration.class, testConfiguration(), Issue866Configuration.class) .web(WebApplicationType.REACTIVE) .properties("server.port=0", "spring.jmx.enabled=false", "spring.sleuth.reactor.instrumentation-type=DECORATE_QUEUES", "spring.application.name=TraceWebFluxOnQueuesTests", "security.basic.enabled=false", "management.security.enabled=false") .run(); assertReactorTracing(context, capture, () -> context.getBean(TestConfiguration.class).spanInFoo); } protected abstract Class testConfiguration(); @Test public void should_work_with_flat_maps_with_on_last_operator_instrumentation(CapturedOutput capture) { // given ConfigurableApplicationContext context = new SpringApplicationBuilder(FlatMapTests.TestConfiguration.class, testConfiguration(), Issue866Configuration.class) .web(WebApplicationType.REACTIVE) .properties("server.port=0", "spring.jmx.enabled=false", "spring.sleuth.reactor.instrumentation-type=DECORATE_ON_LAST", "spring.application.name=TraceWebFluxOnLastTests", "security.basic.enabled=false", "management.security.enabled=false") .run(); assertReactorTracing(context, capture, () -> context.getBean(TestConfiguration.class).spanInFoo); } @Test public void should_work_with_flat_maps_with_on_each_operator_instrumentation(CapturedOutput capture) { // given ConfigurableApplicationContext context = new SpringApplicationBuilder(FlatMapTests.TestConfiguration.class, testConfiguration(), Issue866Configuration.class) .web(WebApplicationType.REACTIVE) .properties("server.port=0", "spring.jmx.enabled=false", "spring.sleuth.reactor.instrumentation-type=DECORATE_ON_EACH", "spring.application.name=TraceWebFluxOnEachTests", "security.basic.enabled=false", "management.security.enabled=false") .run(); assertReactorTracing(context, capture, () -> context.getBean(TestConfiguration.class).spanInFoo); } @Test public void should_work_with_flat_maps_with_on_manual_operator_instrumentation(CapturedOutput capture) { // given ConfigurableApplicationContext context = new SpringApplicationBuilder( FlatMapTests.TestManualConfiguration.class, testConfiguration(), Issue866Configuration.class) .web(WebApplicationType.REACTIVE) .properties("server.port=0", "spring.jmx.enabled=false", "spring.sleuth.reactor.instrumentation-type=MANUAL", "spring.application.name=TraceWebFluxOnManualTests", "security.basic.enabled=false", "management.security.enabled=false") .run(); assertReactorTracing(context, capture, () -> context.getBean(TestManualConfiguration.class).spanInFoo); } private void assertReactorTracing(ConfigurableApplicationContext context, CapturedOutput capture, SpanProvider spanProvider) { TestSpanHandler spans = context.getBean(TestSpanHandler.class); int port = context.getBean(Environment.class).getProperty("local.server.port", Integer.class); RequestSender sender = context.getBean(RequestSender.class); FactoryUser factoryUser = context.getBean(FactoryUser.class); sender.port = port; spans.clear(); Awaitility.await().atMost(15, TimeUnit.SECONDS).pollInterval(1, TimeUnit.SECONDS).untilAsserted(() -> { // when LOGGER.info("Start"); spans.clear(); String firstTraceId = flatMapTraceId(spans, callFlatMap(port).block()); // then LOGGER.info("Checking first trace id"); thenAllWebClientCallsHaveSameTraceId(firstTraceId, sender); thenSpanInFooHasSameTraceId(firstTraceId, spanProvider); spans.clear(); LOGGER.info("All web client calls have same trace id"); // when LOGGER.info("Second trace start"); String secondTraceId = flatMapTraceId(spans, callFlatMap(port).block()); // then then(firstTraceId).as("Id will not be reused between calls").isNotEqualTo(secondTraceId); LOGGER.info("Id was not reused between calls"); thenSpanInFooHasSameTraceId(secondTraceId, spanProvider); LOGGER.info("Span in Foo has same trace id"); // and List<String> requestUri = Arrays.stream(capture.toString().split("\n")) .filter(s -> s.contains("Received a request to uri")).map(s -> s.split(",")[1]) .collect(Collectors.toList()); LOGGER.info("TracingFilter should not have any trace when receiving a request " + requestUri); then(requestUri).as("TracingFilter should not have any trace when receiving a request").containsOnly(""); // and #866 then(factoryUser.wasSchedulerWrapped).isTrue(); LOGGER.info("Factory was wrapped"); }); } private void thenAllWebClientCallsHaveSameTraceId(String traceId, RequestSender sender) { then(sender.span.context().traceId()).isEqualTo(traceId); } private void thenSpanInFooHasSameTraceId(String traceId, SpanProvider spanProvider) { then(spanProvider.get().context().traceId()).isEqualTo(traceId); } private Mono<ClientResponse> callFlatMap(int port) { return WebClient.create().get().uri("http://localhost:" + port + "/withFlatMap").exchange(); } private String flatMapTraceId(TestSpanHandler spans, ClientResponse response) { then(response.statusCode().value()).isEqualTo(200); then(spans).isNotEmpty(); LOGGER.info("Accumulated spans: " + spans); List<String> traceIdOfFlatMap = spans.reportedSpans().stream() .filter(span -> span.getTags().containsKey("http.path") && span.getTags().get("http.path").equals("/withFlatMap")) .map(FinishedSpan::getTraceId).collect(Collectors.toList()); then(traceIdOfFlatMap).hasSize(1); return traceIdOfFlatMap.get(0); } @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration static class TestConfiguration { Span spanInFoo; @Bean RouterFunction<ServerResponse> handlers(Tracer tracer, RequestSender requestSender) { return route(GET("/noFlatMap"), request -> { LOGGER.info("noFlatMap"); Flux<Integer> one = requestSender.getAll().map(String::length); return ServerResponse.ok().body(one, Integer.class); }).andRoute(GET("/withFlatMap"), request -> { LOGGER.info("withFlatMap"); Flux<Integer> one = requestSender.getAll().map(String::length); Flux<Integer> response = one.flatMap( size -> requestSender.getAll().doOnEach(sig -> LOGGER.info(sig.getContext().toString()))) .map(string -> { LOGGER.info("WHATEVER YEAH"); return string.length(); }); return ServerResponse.ok().body(response, Integer.class); }).andRoute(GET("/foo"), request -> { LOGGER.info("foo"); this.spanInFoo = tracer.currentSpan(); return ServerResponse.ok().body(Flux.just(1), Integer.class); }); } @Bean WebClient webClient() { return WebClient.create(); } @Bean RequestSender sender(WebClient client, Tracer tracer) { return new RequestSender(client, tracer); } // https://github.com/spring-cloud/spring-cloud-sleuth/issues/866 @Bean FactoryUser factoryUser() { return new FactoryUser(); } } @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration static class TestManualConfiguration { Span spanInFoo; @Bean RouterFunction<ServerResponse> handlers(org.springframework.cloud.sleuth.Tracer tracing, CurrentTraceContext currentTraceContext, ManualRequestSender requestSender) { return route(GET("/noFlatMap"), request -> { ServerWebExchange exchange = request.exchange(); WebFluxSleuthOperators.withSpanInScope(tracing, currentTraceContext, exchange, () -> LOGGER.info("noFlatMap")); Flux<Integer> one = requestSender.getAll().map(String::length); return ServerResponse.ok().body(one, Integer.class); }).andRoute(GET("/withFlatMap"), request -> { ServerWebExchange exchange = request.exchange(); WebFluxSleuthOperators.withSpanInScope(tracing, currentTraceContext, exchange, () -> LOGGER.info("withFlatMap")); Flux<Integer> one = requestSender.getAll().map(String::length); Flux<Integer> response = one .flatMap(size -> requestSender.getAll().doOnEach(sig -> WebFluxSleuthOperators .withSpanInScope(sig.getContext(), () -> LOGGER.info(sig.getContext().toString())))) .map(string -> { WebFluxSleuthOperators.withSpanInScope(tracing, currentTraceContext, exchange, () -> LOGGER.info("WHATEVER YEAH")); return string.length(); }); return ServerResponse.ok().body(response, Integer.class); }).andRoute(GET("/foo"), request -> { ServerWebExchange exchange = request.exchange(); WebFluxSleuthOperators.withSpanInScope(tracing, currentTraceContext, exchange, () -> { LOGGER.info("foo"); this.spanInFoo = tracing.currentSpan(); }); return ServerResponse.ok().body(Flux.just(1), Integer.class); }); } @Bean WebClient webClient() { return WebClient.create(); } @Bean ManualRequestSender sender(WebClient client, Tracer tracer) { return new ManualRequestSender(client, tracer); } // https://github.com/spring-cloud/spring-cloud-sleuth/issues/866 @Bean FactoryUser factoryUser() { return new FactoryUser(); } } } class FactoryUser { boolean wasSchedulerWrapped = false; FactoryUser() { Issue866Configuration.TestHook hook = Issue866Configuration.hook; this.wasSchedulerWrapped = hook != null && hook.executed; } } interface SpanProvider extends Supplier<Span> { }
4,438
1,738
<reponame>jeikabu/lumberyard /* * 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. #ifndef CRYINCLUDE_EDITOR_BSTEDITOR_DIALOGS_ADDNEWTIMESTAMPDIALOG_H #define CRYINCLUDE_EDITOR_BSTEDITOR_DIALOGS_ADDNEWTIMESTAMPDIALOG_H #pragma once class CAddNewTimestampDialog: public CDialog { DECLARE_DYNAMIC(CAddNewTimestampDialog) public: CAddNewTimestampDialog(CWnd* pParent = NULL); ~CAddNewTimestampDialog(){} // Dialog Data enum { IDD = IDD_BST_ADD_NEW_TIMESTAMP }; void Init( const string& timestampName="", const string& eventName="", string exclusiveToTimestampName="" ) { m_timestampName = timestampName; m_eventName = eventName; m_exclusiveToTimestampName = exclusiveToTimestampName; } string GetName() { return m_timestampName; } string GetEventName() { return m_eventName; } string GetExclusiveToTimestampName() {return m_exclusiveToTimestampName; } protected: virtual BOOL OnInitDialog(); virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() afx_msg void OnBnClickedOk(); private: void SetSelection( CComboBox& comboBox, const string& selection ); void GetVariables( std::list< string >& strList ); void GetSignals( std::list< string >& strList ); void LoadVarsFromXml( std::list< string >& strList, const XmlNodeRef& xmlNode ); private: CComboBox m_cbTimeStamp; CComboBox m_cbEventName; CComboBox m_cbExclusiveTo; string m_timestampName; string m_eventName; string m_exclusiveToTimestampName; }; #endif // CRYINCLUDE_EDITOR_BSTEDITOR_DIALOGS_ADDNEWTIMESTAMPDIALOG_H
748
339
/* * IPrinter.h * * Created on: Aug 24, 2015 * Author: fsedlaze */ #ifndef PRINT_IPRINTER_H_ #define PRINT_IPRINTER_H_ #include <vector> #include <iostream> #include <time.h> #include "../tree/Intervall_bed.h" #include "api/BamReader.h" #include "../Ignore_Regions.h" #include "../sub/Breakpoint.h" #include "../cluster/Cluster_SVs.h" #include "../Genotyper/Genotyper.h" #include <math.h> #include <cmath> #include <cstdlib> double const uniform_variance = 0.2886751; //sqrt(1/12) see variance of uniform distribution -> std void write_read(Alignment * tmp_aln, FILE * & ref_allel_reads); class IPrinter { protected: FILE *file; FILE *distances; FILE *tmp_file; uint id; RefVector ref; BamParser *mapped_file; IntervallTree_bed bed_tree; Leaf *root; virtual void print_header()=0; virtual void print_body(Breakpoint * &SV, RefVector ref)=0; virtual void print_body_recall(Breakpoint * &SV, RefVector ref)=0; long calc_pos(long pos, RefVector ref, std::string &chr); std::string get_chr(long pos, RefVector ref); std::string get_type(char type); void sort_insert(int pos, std::vector<int> & positons); bool is_huge_ins(Breakpoint * &SV); std::string assess_genotype(int ref, int support); public: IPrinter() { id = 0; root = NULL; //we just need the ref information: } virtual ~IPrinter() { delete mapped_file; } void printSV(Breakpoint * SV) { if(Parameter::Instance()->input_vcf.empty()){ print_body(SV, ref); }else{ //test print_body(SV, ref); //print_body_recall(SV,ref); } } void init() { try { if (!Parameter::Instance()->output_vcf.empty()) { file = fopen(Parameter::Instance()->output_vcf.c_str(), "w"); } else if (!Parameter::Instance()->output_bedpe.empty()) { file = fopen(Parameter::Instance()->output_bedpe.c_str(), "w"); } } catch (...) { std::cerr << "Output file could not be created. Please check if path exists and if you have write permissions." << std::endl; exit(0); } if (file == NULL) { std::cerr << "Output file could not be created. Please check if path exists and if you have write permissions." << std::endl; exit(EXIT_FAILURE); } BamParser *mapped_file = new BamParser(Parameter::Instance()->bam_files[0]); this->ref = mapped_file->get_refInfo(); print_header(); if (!Parameter::Instance()->ignore_regions_bed.empty()) { std::cout << "Cross checking..." << std::endl; initialize_bed(bed_tree, root, ref); } if (Parameter::Instance()->phase) { tmp_file = fopen(Parameter::Instance()->tmp_phasing.c_str(), "wb"); } } bool to_print(Breakpoint * &SV, pair<double, double> &std, pair<double, double> & kurtosis, double & std_length, int & zmw_num); void store_readnames(std::vector<long> names, int id); void close_file() { fclose(this->file); } void comp_std(Breakpoint * &SV, double & std_start, double & std_stop); void comp_std_med(Breakpoint * &SV, double & std_start, double & std_stop); pair<double, double> comp_std_quantile(Breakpoint * &SV, pair<double, double>& std, double & std_lenght, int & zmw_num); const std::string currentDateTime(); double fisher_exact(int sv_plus, int sv_minus, int ref_plus, int ref_minus); }; #endif /* PRINT_IPRINTER_H_ */
1,257
4,293
package com.github.pockethub.android.dagger; import com.github.pockethub.android.ui.commit.CommitCompareListFragment; import dagger.Module; import dagger.android.ContributesAndroidInjector; @Module interface CommitCompareViewFragmentProvider { @ContributesAndroidInjector CommitCompareListFragment commitCompareListFragment(); }
102
10,690
package io.invertase.firebase.database; /* * Copyright (c) 2016-present Invertase Limited & Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this library 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. * */ import static io.invertase.firebase.common.RCTConvertFirebase.mapPutValue; import static io.invertase.firebase.common.RCTConvertFirebase.toHashMap; import static io.invertase.firebase.database.ReactNativeFirebaseDatabaseCommon.castValue; import static io.invertase.firebase.database.ReactNativeFirebaseDatabaseCommon.snapshotToMap; import com.facebook.react.bridge.*; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.MutableData; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.Nullable; public class ReactNativeFirebaseDatabaseTransactionHandler { private final ReentrantLock lock; private final Condition condition; public Object value; boolean interrupted; boolean abort = false; boolean timeout = false; private int transactionId; private String appName; private String dbURL; private Map<String, Object> data; private boolean signalled; ReactNativeFirebaseDatabaseTransactionHandler(int id, String app, String url) { appName = app; dbURL = url; transactionId = id; lock = new ReentrantLock(); condition = lock.newCondition(); } /** * Signal that the transaction data has been received * * @param updates */ void signalUpdateReceived(ReadableMap updates) { Map<String, Object> updateData = toHashMap(updates); lock.lock(); value = updateData.get("value"); abort = (Boolean) updateData.get("abort"); try { if (signalled) { throw new IllegalStateException( "This transactionUpdateHandler has already been signalled."); } signalled = true; data = updateData; condition.signalAll(); } catch (Exception e) { // do nothing } finally { lock.unlock(); } } /** Wait for signalUpdateReceived to signal condition */ void await() throws InterruptedException { lock.lock(); signalled = false; long timeoutExpired = System.currentTimeMillis() + 5000; try { while (!timeout && !condition.await(250, TimeUnit.MILLISECONDS) && !signalled) { if (!signalled && System.currentTimeMillis() > timeoutExpired) { timeout = true; } } } finally { lock.unlock(); } } /** * Get the * * @return */ Map<String, Object> getUpdates() { return data; } /** * Create a RN map of transaction mutable data for sending to js * * @param updatesData * @return */ WritableMap createUpdateMap(MutableData updatesData) { final WritableMap updatesMap = Arguments.createMap(); updatesMap.putString("type", "update"); if (!updatesData.hasChildren()) { mapPutValue("value", updatesData.getValue(), updatesMap); } else { Object value = castValue(updatesData); if (value instanceof WritableNativeArray) { updatesMap.putArray("value", (WritableArray) value); } else { updatesMap.putMap("value", (WritableMap) value); } } return updatesMap; } WritableMap createResultMap( @Nullable DatabaseError error, boolean committed, DataSnapshot snapshot) { WritableMap resultMap = Arguments.createMap(); resultMap.putBoolean("timeout", timeout); resultMap.putBoolean("committed", committed); resultMap.putBoolean("interrupted", interrupted); if (error != null || timeout || interrupted) { resultMap.putString("type", "error"); if (error != null) { UniversalDatabaseException databaseException = new UniversalDatabaseException( error.getCode(), error.getMessage(), error.toException()); WritableMap errorMap = Arguments.createMap(); errorMap.putString("code", databaseException.getCode()); errorMap.putString("message", databaseException.getMessage()); resultMap.putMap("error", errorMap); } if (error == null && timeout) { WritableMap timeoutError = Arguments.createMap(); timeoutError.putString("code", "database/internal-timeout"); timeoutError.putString( "message", "A timeout occurred whilst waiting for React Native JavaScript thread to send" + " transaction updates."); resultMap.putMap("error", timeoutError); } } else { resultMap.putString("type", "complete"); resultMap.putMap("snapshot", snapshotToMap(snapshot)); } return resultMap; } }
1,793
416
// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #ifndef VSNRAY_DETAIL_COLOR_CONVERSION_H #define VSNRAY_DETAIL_COLOR_CONVERSION_H 1 #include <cassert> #include <cstddef> #include <visionaray/math/detail/math.h> #include <visionaray/math/matrix.h> #include <visionaray/math/unorm.h> #include <visionaray/math/vector.h> #include <visionaray/pixel_format.h> #include <visionaray/spectrum.h> #include "spd/blackbody.h" #include "macros.h" namespace visionaray { //-------------------------------------------------------------------------------------------------- // CIE 1931 color matching functions // // From: // https://research.nvidia.com/publication/simple-analytic-approximations-cie-xyz-color-matching-functions // VSNRAY_FUNC inline float cie_x(float lambda) { float t1 = (lambda - 442.0f) * ((lambda < 442.0f) ? 0.0624f : 0.0374f); float t2 = (lambda - 599.8f) * ((lambda < 599.8f) ? 0.0264f : 0.0323f); float t3 = (lambda - 501.1f) * ((lambda < 501.1f) ? 0.0490f : 0.0382f); return 0.362f * exp(-0.5f * t1 * t1) + 1.056f * exp(-0.5f * t2 * t2) - 0.065f * exp(-0.5f * t3 * t3); } VSNRAY_FUNC inline float cie_y(float lambda) { float t1 = (lambda - 568.8f) * ((lambda < 568.8f) ? 0.0213f : 0.0247f); float t2 = (lambda - 530.9f) * ((lambda < 530.9f) ? 0.0613f : 0.0322f); return 0.821f * exp(-0.5f * t1 * t1) + 0.286f * exp(-0.5f * t2 * t2); } VSNRAY_FUNC inline float cie_z(float lambda) { float t1 = (lambda - 437.0f) * ((lambda < 437.0f) ? 0.0845f : 0.0278f); float t2 = (lambda - 459.0f) * ((lambda < 459.0f) ? 0.0385f : 0.0725f); return 1.217f * exp(-0.5f * t1 * t1) + 0.681f * exp(-0.5f * t2 * t2); } //------------------------------------------------------------------------------------------------- // Hue and temperature to RGB // template <typename T> VSNRAY_FUNC inline vector<3, T> hue_to_rgb(T hue) { // assert(hue >= 0.0f && hue <= 1.0f); T s = saturate( hue ) * T(6.0f); T r = saturate( abs(s - T(3.0)) - T(1.0) ); T g = saturate( T(2.0) - abs(s - T(2.0)) ); T b = saturate( T(2.0) - abs(s - T(4.0)) ); return vector<3, T>(r, g, b); } template <typename T> VSNRAY_FUNC inline vector<3, T> temperature_to_rgb(T t) { T K = T(4.0f / 6.0f); T h = K - K * t; T v = T(0.5f) + T(0.5f) * t; return v * hue_to_rgb(h); } //------------------------------------------------------------------------------------------------- // XYZ to RGB // template <typename T> VSNRAY_FUNC inline vector<3, T> xyz_to_rgb(vector<3, T> const& xyz) { // see: http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html // Assume sRGB working space and D65 reference white return matrix<3, 3, T>( 3.2404542, -0.9692660, 0.0556434, -1.5371385, 1.8760108, -0.2040259, -0.4985314, 0.0415560, 1.0572252 ) * xyz; } //------------------------------------------------------------------------------------------------- // Convert an arbitrary spectral power distribution to RGB // template <typename SPD, typename T = float> VSNRAY_FUNC inline vector<3, T> spd_to_rgb(SPD const& spd, float lmin = 400.0f, float lmax = 700.0f, float step = 1.0f) { T x(0.0); T y(0.0); T z(0.0); T n(0.0); for (float lambda = lmin; lambda <= lmax; lambda += step) { auto p = spd(T(lambda)); x += p * cie_x(lambda); y += p * cie_y(lambda); z += p * cie_z(lambda); n += cie_y(lambda); } return xyz_to_rgb( vector<3, T>( x / n, y / n, z / n ) ); } //------------------------------------------------------------------------------------------------- // Convert an arbitrary spectral power distribution to RGB // VSNRAY_FUNC inline vector<3, float> spd_to_rgb(blackbody const& spd, float lmin = 400.0f, float lmax = 700.0f, float step = 1.0f, bool normalize = true) { float x = 0.0f; float y = 0.0f; float z = 0.0f; float n = 0.0f; // For normalization float max_radiance = 1.0f; if (normalize) { // lambda where radiance is max float lambda_max_radiance = 2.8977721e-3 / spd.temperature() * 1e9 /* m2nm */; max_radiance = spd(lambda_max_radiance); } for (float lambda = lmin; lambda <= lmax; lambda += step) { auto p = spd(lambda) / max_radiance; x += p * cie_x(lambda); y += p * cie_y(lambda); z += p * cie_z(lambda); n += cie_y(lambda); } return xyz_to_rgb( vector<3, float>( x / n, y / n, z / n ) ); } //------------------------------------------------------------------------------------------------- // Convert spectrum to RGB // template <typename T> VSNRAY_FUNC inline vector<3, T> spd_to_rgb(spectrum<T> const& spe) { const float lmin = spectrum<T>::lambda_min; const float lmax = spectrum<T>::lambda_max; const float step = (lmax - lmin) / (spectrum<T>::num_samples - 1); return spd_to_rgb(spe, lmin, lmax, step); } //------------------------------------------------------------------------------------------------- // Convert RGB to luminance (cd/m^2) // template <typename T> VSNRAY_FUNC inline T rgb_to_luminance(vector<3, T> const& rgb) { return T(0.3) * rgb.x + T(0.59) * rgb.y + T(0.11) * rgb.z; } //------------------------------------------------------------------------------------------------- // Convert spectrum to luminance (cd/m^2) // template <typename T> VSNRAY_FUNC inline T spd_to_luminance(spectrum<T> const& spe) { const float lmin = spectrum<T>::lambda_min; const float lmax = spectrum<T>::lambda_max; const float step = (lmax - lmin) / (spectrum<T>::num_samples - 1); T y(0.0); for (float lambda = lmin; lambda <= lmax; lambda += step) { auto p = spe(lambda); y += p * cie_y(lambda); } return y; } //------------------------------------------------------------------------------------------------- // Convert from linear to sRGB space // template <typename T> VSNRAY_FUNC inline vector<3, T> linear_to_srgb(vector<3, T> const& rgb) { vector<3, T> result; for (int i = 0; i < 3; ++i) { result[i] = select( rgb[i] <= T(0.0031308), T(12.92) * rgb[i], T(1.055) * pow(rgb[i], T(1.0 / 2.4)) - T(0.055) ); } return result; } //------------------------------------------------------------------------------------------------- // Convert from sRGB to linear space // template <typename T> VSNRAY_FUNC inline vector<3, T> srgb_to_linear(vector<3, T> const& srgb) { vector<3, T> result; for (int i = 0; i < 3; ++i) { result[i] = select( srgb[i] <= T(0.04045), srgb[i] / T(12.92), pow((srgb[i] + T(0.055)) / T(1.055), T(2.4)) ); } return result; } //------------------------------------------------------------------------------------------------- // Convert OpenGL pixel formats // template <pixel_format TF, pixel_format SF, typename TargetType, typename SourceType> VSNRAY_FUNC inline void convert( pixel_format_constant<TF> /* */, pixel_format_constant<SF> /* */, TargetType& target, SourceType const& source ) { target = static_cast<TargetType>(source); } // To PF_UNSPECIFIED (noop) template <pixel_format SF, typename TargetType, typename SourceType> VSNRAY_FUNC inline void convert( pixel_format_constant<PF_UNSPECIFIED> /* */, pixel_format_constant<SF> /* */, TargetType& /* */, SourceType const& /* */ ) { assert(0); } // From PF_UNSPECIFIED (noop) template <pixel_format TF, typename TargetType, typename SourceType> VSNRAY_FUNC inline void convert( pixel_format_constant<TF> /* */, pixel_format_constant<PF_UNSPECIFIED> /* */, TargetType& /* */, SourceType const& /* */ ) { assert(0); } // PF_DEPTH32F to PF_DEPTH24_STENCIL8 conversion template <typename TargetType, typename SourceType> VSNRAY_FUNC inline void convert( pixel_format_constant<PF_DEPTH24_STENCIL8> /* */, pixel_format_constant<PF_DEPTH32F> /* */, TargetType& target, SourceType const& source ) { auto depth_raw = convert_to_int(source * 16777215.0f); target = (depth_raw << 8); } // PF_DEPTH24_STENCIL8 to PF_DEPTH32F conversion template <typename TargetType, typename SourceType> VSNRAY_FUNC inline void convert( pixel_format_constant<PF_DEPTH32F> /* */, pixel_format_constant<PF_DEPTH24_STENCIL8> /* */, TargetType& target, SourceType const& source ) { auto depth_raw = (source & 0xFFFFFF00) >> 8; target = TargetType(depth_raw) / 16777215.0f; } // float to unorm conversion template <pixel_format TF, pixel_format SF, unsigned Bits, size_t Dim> VSNRAY_FUNC inline void convert( pixel_format_constant<TF> /* */, pixel_format_constant<SF> /* */, vector<Dim, unorm<Bits>>& target, vector<Dim, float> const& source ) { using V = vector<Dim, float>; target = vector<Dim, unorm<Bits>>(clamp(source, V(0.0), V(1.0))); } // unorm to float conversion // Ok. // RGBA to RGB conversion, multiply by alpha template <pixel_format TF, pixel_format SF, typename T, typename U> VSNRAY_FUNC inline void convert( pixel_format_constant<TF> /* */, pixel_format_constant<SF> /* */, vector<3, T>& target, vector<4, U> const& source ) { convert( pixel_format_constant<TF>{}, pixel_format_constant<SF>{}, target, source.xyz() * source.w ); } // RGB to RGBA conversion, let alpha = 1.0 template <pixel_format TF, pixel_format SF, typename T, typename U> VSNRAY_FUNC inline void convert( pixel_format_constant<TF> /* */, pixel_format_constant<SF> /* */, vector<4, T>& target, vector<3, U> const& source ) { convert( pixel_format_constant<TF>{}, pixel_format_constant<SF>{}, target, vector<4, U>(source, U(1.0)) ); } } // visionaray #endif // VSNRAY_DETAIL_COLOR_CONVERSION_H
4,708
364
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('photologue', '0002_photosize_data'), ] operations = [ migrations.AlterField( model_name='galleryupload', name='title', field=models.CharField(null=True, help_text='All uploaded photos will be given a title made up of this title + a sequential number.', max_length=50, verbose_name='title', blank=True), ), ]
215
14,425
<reponame>amahussein/hadoop /* * 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.hadoop.fs.s3a.auth.delegation; import java.io.IOException; import java.net.URI; import org.apache.hadoop.thirdparty.com.google.common.base.Preconditions; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.s3a.impl.StoreContext; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.service.AbstractService; import static java.util.Objects.requireNonNull; /** * This is the base class for both the delegation binding * code and the back end service created; allows for * shared methods across both. * * The lifecycle sequence is as follows * <pre> * - create * - bindToFileSystem(uri, ownerFS) * - init * - start * ...api calls... * - stop * </pre> * * As the S3ADelegation mechanism is all configured during the filesystem * initalize() operation, it is not ready for use through all the start process. */ public abstract class AbstractDTService extends AbstractService { /** * URI of the filesystem. * Valid after {@link #bindToFileSystem(URI, StoreContext, DelegationOperations)}. */ private URI canonicalUri; /** * Owner of the filesystem. * Valid after {@link #bindToFileSystem(URI, StoreContext, DelegationOperations)}. */ private UserGroupInformation owner; /** * Store Context for callbacks into the FS. * Valid after {@link #bindToFileSystem(URI, StoreContext, DelegationOperations)}. */ private StoreContext storeContext; /** * Callbacks for DT-related operations. */ private DelegationOperations policyProvider; /** * Protected constructor. * @param name service name. */ protected AbstractDTService(final String name) { super(name); } /** * Bind to the filesystem. * Subclasses can use this to perform their own binding operations - * but they must always call their superclass implementation. * This <i>Must</i> be called before calling {@code init()}. * * <b>Important:</b> * This binding will happen during FileSystem.initialize(); the FS * is not live for actual use and will not yet have interacted with * AWS services. * @param uri the canonical URI of the FS. * @param context store context * @param delegationOperations delegation operations * @throws IOException failure. */ public void bindToFileSystem( final URI uri, final StoreContext context, final DelegationOperations delegationOperations) throws IOException { requireServiceState(STATE.NOTINITED); Preconditions.checkState(canonicalUri == null, "bindToFileSystem called twice"); this.canonicalUri = requireNonNull(uri); this.storeContext = requireNonNull(context); this.owner = context.getOwner(); this.policyProvider = delegationOperations; } /** * Get the canonical URI of the filesystem, which is what is * used to identify the tokens. * @return the URI. */ public URI getCanonicalUri() { return canonicalUri; } /** * Get the owner of this Service. * @return owner; non-null after binding to an FS. */ public UserGroupInformation getOwner() { return owner; } protected StoreContext getStoreContext() { return storeContext; } protected DelegationOperations getPolicyProvider() { return policyProvider; } /** * Require that the service is in a given state. * @param state desired state. * @throws IllegalStateException if the condition is not met */ protected void requireServiceState(final STATE state) throws IllegalStateException { Preconditions.checkState(isInState(state), "Required State: %s; Actual State %s", state, getServiceState()); } /** * Require the service to be started. * @throws IllegalStateException if it is not. */ protected void requireServiceStarted() throws IllegalStateException { requireServiceState(STATE.STARTED); } @Override protected void serviceInit(final Configuration conf) throws Exception { super.serviceInit(conf); requireNonNull(canonicalUri, "service does not have a canonical URI"); } }
1,490
470
#include "AssetTypeActions_PrimaryAssetLabel.h" #include "Engine/PrimaryAssetLabel.h" #include "ToolMenuSection.h" #include "HotPatcherEditor.h" #include "Flib/FLibAssetManageHelperEx.h" #if WITH_EDITOR_SECTION void FAssetTypeActions_PrimaryAssetLabel::GetActions(const TArray<UObject*>& InObjects, FToolMenuSection& Section) { auto Labels = GetTypedWeakObjectPtrs<UPrimaryAssetLabel>(InObjects); const FSlateIcon Icon = FSlateIcon(FEditorStyle::GetStyleSetName(), "ContentBrowser.AssetActions.Duplicate"); Section.AddMenuEntry( "ObjectContext_AddToPatchIncludeFilters", NSLOCTEXT("AssetTypeActions_PrimaryAssetLabel", "ObjectContext_AddToPatchIncludeFilters", "Add To Patch Include Filters"), NSLOCTEXT("AssetTypeActions_PrimaryAssetLabel", "ObjectContext_AddToPatchIncludeFiltersTooltip", "Add the label to HotPatcher Include Filters."), Icon, FUIAction( FExecuteAction::CreateSP(this, &FAssetTypeActions_PrimaryAssetLabel::ExecuteAddToPatchIncludeFilter, Labels) )); Section.AddMenuEntry( "ObjectContext_AddToChunkConfig", NSLOCTEXT("AssetTypeActions_PrimaryAssetLabel", "ObjectContext_AddToChunkConfig", "Add To Chunk Config"), NSLOCTEXT("AssetTypeActions_PrimaryAssetLabel", "ObjectContext_AddToChunkConfigTooltip", "Add Label To Chunk Config"), Icon, FUIAction( FExecuteAction::CreateSP(this, &FAssetTypeActions_PrimaryAssetLabel::ExecuteAddToChunkConfig, Labels) )); Section.AddSubMenu( "ObjectContext_CookAndPakActionsSubMenu", NSLOCTEXT("AssetTypeActions_PrimaryAssetLabel", "ObjectContext_CookAndPakActionsSubMenu","Cook And Pak Label Actions"), NSLOCTEXT("AssetTypeActions_PrimaryAssetLabel", "ObjectContext_CookAndPakActionsSubMenu","Cook And Pak Label Actions"), FNewToolMenuDelegate::CreateRaw(this, &FAssetTypeActions_PrimaryAssetLabel::MakeCookAndPakActionsSubMenu,Labels), FUIAction( FExecuteAction() ), EUserInterfaceActionType::Button, false, FSlateIcon(FEditorStyle::GetStyleSetName(), "ContentBrowser.SaveAllCurrentFolder") ); } TArray<FPatcherSpecifyAsset> GetLabelsAssets(TArray<TWeakObjectPtr<UPrimaryAssetLabel>> Objects) { TArray<FPatcherSpecifyAsset> LabelAsstes; for(auto& Label:Objects) { if( Label->Rules.CookRule == EPrimaryAssetCookRule::NeverCook ) continue; for(const auto& Asset:Label->ExplicitAssets) { FPatcherSpecifyAsset CurrentAsset; CurrentAsset.Asset = Asset.ToSoftObjectPath(); CurrentAsset.bAnalysisAssetDependencies = Label->bLabelAssetsInMyDirectory; CurrentAsset.AssetRegistryDependencyTypes.AddUnique(EAssetRegistryDependencyTypeEx::Packages); LabelAsstes.AddUnique(CurrentAsset); } } return LabelAsstes; } TArray<FDirectoryPath> GetLabelsDirs(TArray<TWeakObjectPtr<UPrimaryAssetLabel>> Objects) { TArray<FDirectoryPath> Dirs; for(auto& Label:Objects) { if(Label->bLabelAssetsInMyDirectory && (Label->Rules.CookRule != EPrimaryAssetCookRule::NeverCook)) { FString PathName = Label->GetPathName(); TArray<FString> DirNames; PathName.ParseIntoArray(DirNames,TEXT("/")); FString FinalPath; for(size_t index = 0;index < DirNames.Num() - 1;++index) { FinalPath += TEXT("/") + DirNames[index]; } FDirectoryPath CurrentDir; CurrentDir.Path = FinalPath; Dirs.Add(CurrentDir); } } return Dirs; } void FAssetTypeActions_PrimaryAssetLabel::ExecuteAddToPatchIncludeFilter( TArray<TWeakObjectPtr<UPrimaryAssetLabel>> Objects) { FHotPatcherEditorModule::Get().OpenDockTab(); if(GPatchSettings) { GPatchSettings->IncludeSpecifyAssets.Append(GetLabelsAssets(Objects)); GPatchSettings->AssetIncludeFilters.Append(GetLabelsDirs(Objects)); } } TArray<FChunkInfo> GetChunksByAssetLabels(TArray<TWeakObjectPtr<UPrimaryAssetLabel>> Objects) { TArray<FChunkInfo> Chunks; for(const auto& Object:Objects) { FChunkInfo Chunk; Chunk.AssetIgnoreFilters = GetLabelsDirs(TArray<TWeakObjectPtr<UPrimaryAssetLabel>>{Object}); Chunk.IncludeSpecifyAssets = GetLabelsAssets(TArray<TWeakObjectPtr<UPrimaryAssetLabel>>{Object}); Chunk.bAnalysisFilterDependencies = Object->Rules.bApplyRecursively; FString LongPackageName; if(UFLibAssetManageHelperEx::ConvPackagePathToLongPackageName(Object->GetPathName(),LongPackageName)) { TArray<FString> DirNames; LongPackageName.ParseIntoArray(DirNames,TEXT("/")); Chunk.ChunkName = DirNames[DirNames.Num()-1]; } } return Chunks; } void FAssetTypeActions_PrimaryAssetLabel::ExecuteAddToChunkConfig(TArray<TWeakObjectPtr<UPrimaryAssetLabel>> Objects) { FHotPatcherEditorModule::Get().OpenDockTab(); if(GPatchSettings) { GPatchSettings->bEnableChunk = true; GPatchSettings->ChunkInfos.Append(GetChunksByAssetLabels(Objects)); } } void FAssetTypeActions_PrimaryAssetLabel::MakeCookAndPakActionsSubMenu(UToolMenu* Menu,TArray<TWeakObjectPtr<UPrimaryAssetLabel>> Objects) { FToolMenuSection& Section = Menu->AddSection("CookAndPakActionsSection"); UHotPatcherSettings* Settings = GetMutableDefault<UHotPatcherSettings>(); Settings->ReloadConfig(); for (auto Platform : FHotPatcherEditorModule::Get().GetAllCookPlatforms()) { if(Settings->bWhiteListCookInEditor && !Settings->PlatformWhitelists.Contains(Platform)) continue; Section.AddMenuEntry( FName(*UFlibPatchParserHelper::GetEnumNameByValue(Platform)), FText::Format(NSLOCTEXT("Platform","Platform", "{0}"), UKismetTextLibrary::Conv_StringToText(UFlibPatchParserHelper::GetEnumNameByValue(Platform))), FText(), FSlateIcon(), FUIAction( FExecuteAction::CreateRaw(this, &FAssetTypeActions_PrimaryAssetLabel::OnCookAndPakPlatform, Platform,Objects) ) ); } } void FAssetTypeActions_PrimaryAssetLabel::OnCookAndPakPlatform(ETargetPlatform Platform,TArray<TWeakObjectPtr<UPrimaryAssetLabel>> Objects) { FHotPatcherEditorModule::Get().CookAndPakByAssetsAndFilters(GetLabelsAssets(Objects),GetLabelsDirs(Objects),TArray<ETargetPlatform>{Platform},true); } #endif
2,255
2,610
<filename>advanced_functionality/autogluon-tabular-containers/ag_model.py<gh_stars>1000+ from sagemaker.estimator import Framework from sagemaker.predictor import Predictor from sagemaker.mxnet import MXNetModel from sagemaker.mxnet.model import MXNetPredictor from sagemaker import utils from sagemaker.serializers import CSVSerializer from sagemaker.deserializers import StringDeserializer ACCOUNT = 763104351884 ECR_TRAINING_REPO = "autogluon-training" ECR_INFERENCE_REPO = "autogluon-inference" TRAINING_IMAGE_CPU = "cpu-py37-ubuntu18.04" TRAINING_IMAGE_GPU = "gpu-py37-cu102-ubuntu18.04" INFERENCE_IMAGE_CPU = "cpu-py37-ubuntu16.04" class AutoGluonTraining(Framework): def __init__( self, entry_point, region, framework_version, image_type="cpu", source_dir=None, hyperparameters=None, **kwargs, ): image = TRAINING_IMAGE_GPU if image_type == "gpu" else TRAINING_IMAGE_CPU image = f"{framework_version}-{image}" image_uri = f"{ACCOUNT}.dkr.ecr.{region}.amazonaws.com/{ECR_TRAINING_REPO}:{image}" super().__init__(entry_point, source_dir, hyperparameters, image_uri=image_uri, **kwargs) def _configure_distribution(self, distributions): return def create_model( self, model_server_workers=None, role=None, vpc_config_override=None, entry_point=None, source_dir=None, dependencies=None, image_name=None, **kwargs, ): return None class AutoGluonTabularPredictor(Predictor): def __init__(self, *args, **kwargs): super().__init__( *args, serializer=CSVSerializer(), deserializer=StringDeserializer(), **kwargs ) class AutoGluonInferenceModel(MXNetModel): def __init__(self, model_data, role, entry_point, region, framework_version, **kwargs): image = f"{framework_version}-{INFERENCE_IMAGE_CPU}" image_uri = f"{ACCOUNT}.dkr.ecr.{region}.amazonaws.com/{ECR_INFERENCE_REPO}:{image}" super().__init__( model_data, role, entry_point, image_uri=image_uri, framework_version="1.8.0", **kwargs )
942
456
//===-- REPL.cpp ------------------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/Expression/REPL.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/StreamFile.h" #include "lldb/Expression/ExpressionVariable.h" #include "lldb/Expression/UserExpression.h" #include "lldb/Host/HostInfo.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/AnsiTerminal.h" #include <memory> using namespace lldb_private; REPL::REPL(LLVMCastKind kind, Target &target) : m_target(target), m_kind(kind) { // Make sure all option values have sane defaults Debugger &debugger = m_target.GetDebugger(); auto exe_ctx = debugger.GetCommandInterpreter().GetExecutionContext(); m_format_options.OptionParsingStarting(&exe_ctx); m_varobj_options.OptionParsingStarting(&exe_ctx); } REPL::~REPL() = default; lldb::REPLSP REPL::Create(Status &err, lldb::LanguageType language, Debugger *debugger, Target *target, const char *repl_options) { uint32_t idx = 0; lldb::REPLSP ret; while (REPLCreateInstance create_instance = PluginManager::GetREPLCreateCallbackAtIndex(idx++)) { ret = (*create_instance)(err, language, debugger, target, repl_options); if (ret) { break; } } return ret; } std::string REPL::GetSourcePath() { ConstString file_basename = GetSourceFileBasename(); FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir(); if (tmpdir_file_spec) { tmpdir_file_spec.GetFilename().SetCString(file_basename.AsCString()); m_repl_source_path = tmpdir_file_spec.GetPath(); } else { tmpdir_file_spec = FileSpec("/tmp"); tmpdir_file_spec.AppendPathComponent(file_basename.AsCString()); } return tmpdir_file_spec.GetPath(); } lldb::IOHandlerSP REPL::GetIOHandler() { if (!m_io_handler_sp) { Debugger &debugger = m_target.GetDebugger(); m_io_handler_sp = std::make_shared<IOHandlerEditline>( debugger, IOHandler::Type::REPL, "lldb-repl", // Name of input reader for history llvm::StringRef("> "), // prompt llvm::StringRef(". "), // Continuation prompt true, // Multi-line true, // The REPL prompt is always colored 1, // Line number *this, nullptr); // Don't exit if CTRL+C is pressed static_cast<IOHandlerEditline *>(m_io_handler_sp.get()) ->SetInterruptExits(false); if (m_io_handler_sp->GetIsInteractive() && m_io_handler_sp->GetIsRealTerminal()) { m_indent_str.assign(debugger.GetTabSize(), ' '); m_enable_auto_indent = debugger.GetAutoIndent(); } else { m_indent_str.clear(); m_enable_auto_indent = false; } } return m_io_handler_sp; } void REPL::IOHandlerActivated(IOHandler &io_handler, bool interactive) { lldb::ProcessSP process_sp = m_target.GetProcessSP(); if (process_sp && process_sp->IsAlive()) return; lldb::StreamFileSP error_sp(io_handler.GetErrorStreamFileSP()); error_sp->Printf("REPL requires a running target process.\n"); io_handler.SetIsDone(true); } bool REPL::IOHandlerInterrupt(IOHandler &io_handler) { return false; } void REPL::IOHandlerInputInterrupted(IOHandler &io_handler, std::string &line) { } const char *REPL::IOHandlerGetFixIndentationCharacters() { return (m_enable_auto_indent ? GetAutoIndentCharacters() : nullptr); } ConstString REPL::IOHandlerGetControlSequence(char ch) { if (ch == 'd') return ConstString(":quit\n"); return ConstString(); } const char *REPL::IOHandlerGetCommandPrefix() { return ":"; } const char *REPL::IOHandlerGetHelpPrologue() { return "\nThe REPL (Read-Eval-Print-Loop) acts like an interpreter. " "Valid statements, expressions, and declarations are immediately " "compiled and executed.\n\n" "The complete set of LLDB debugging commands are also available as " "described below. Commands " "must be prefixed with a colon at the REPL prompt (:quit for " "example.) Typing just a colon " "followed by return will switch to the LLDB prompt.\n\n"; } bool REPL::IOHandlerIsInputComplete(IOHandler &io_handler, StringList &lines) { // Check for meta command const size_t num_lines = lines.GetSize(); if (num_lines == 1) { const char *first_line = lines.GetStringAtIndex(0); if (first_line[0] == ':') return true; // Meta command is a single line where that starts with ':' } // Check if REPL input is done std::string source_string(lines.CopyList()); return SourceIsComplete(source_string); } int REPL::CalculateActualIndentation(const StringList &lines) { std::string last_line = lines[lines.GetSize() - 1]; int actual_indent = 0; for (char &ch : last_line) { if (ch != ' ') break; ++actual_indent; } return actual_indent; } int REPL::IOHandlerFixIndentation(IOHandler &io_handler, const StringList &lines, int cursor_position) { if (!m_enable_auto_indent) return 0; if (!lines.GetSize()) { return 0; } int tab_size = io_handler.GetDebugger().GetTabSize(); lldb::offset_t desired_indent = GetDesiredIndentation(lines, cursor_position, tab_size); int actual_indent = REPL::CalculateActualIndentation(lines); if (desired_indent == LLDB_INVALID_OFFSET) return 0; return (int)desired_indent - actual_indent; } void REPL::IOHandlerInputComplete(IOHandler &io_handler, std::string &code) { lldb::StreamFileSP output_sp(io_handler.GetOutputStreamFileSP()); lldb::StreamFileSP error_sp(io_handler.GetErrorStreamFileSP()); bool extra_line = false; bool did_quit = false; if (code.empty()) { m_code.AppendString(""); static_cast<IOHandlerEditline &>(io_handler) .SetBaseLineNumber(m_code.GetSize() + 1); } else { Debugger &debugger = m_target.GetDebugger(); CommandInterpreter &ci = debugger.GetCommandInterpreter(); extra_line = ci.GetSpaceReplPrompts(); ExecutionContext exe_ctx(m_target.GetProcessSP() ->GetThreadList() .GetSelectedThread() ->GetSelectedFrame() .get()); lldb::ProcessSP process_sp(exe_ctx.GetProcessSP()); if (code[0] == ':') { // Meta command // Strip the ':' code.erase(0, 1); if (!llvm::StringRef(code).trim().empty()) { // "lldb" was followed by arguments, so just execute the command dump // the results // Turn off prompt on quit in case the user types ":quit" const bool saved_prompt_on_quit = ci.GetPromptOnQuit(); if (saved_prompt_on_quit) ci.SetPromptOnQuit(false); // Execute the command CommandReturnObject result; result.SetImmediateOutputStream(output_sp); result.SetImmediateErrorStream(error_sp); ci.HandleCommand(code.c_str(), eLazyBoolNo, result); if (saved_prompt_on_quit) ci.SetPromptOnQuit(true); if (result.GetStatus() == lldb::eReturnStatusQuit) { did_quit = true; io_handler.SetIsDone(true); if (debugger.CheckTopIOHandlerTypes( IOHandler::Type::REPL, IOHandler::Type::CommandInterpreter)) { // We typed "quit" or an alias to quit so we need to check if the // command interpreter is above us and tell it that it is done as // well so we don't drop back into the command interpreter if we // have already quit lldb::IOHandlerSP io_handler_sp(ci.GetIOHandler()); if (io_handler_sp) io_handler_sp->SetIsDone(true); } } } else { // ":" was followed by no arguments, so push the LLDB command prompt if (debugger.CheckTopIOHandlerTypes( IOHandler::Type::REPL, IOHandler::Type::CommandInterpreter)) { // If the user wants to get back to the command interpreter and the // command interpreter is what launched the REPL, then just let the // REPL exit and fall back to the command interpreter. io_handler.SetIsDone(true); } else { // The REPL wasn't launched the by the command interpreter, it is the // base IOHandler, so we need to get the command interpreter and lldb::IOHandlerSP io_handler_sp(ci.GetIOHandler()); if (io_handler_sp) { io_handler_sp->SetIsDone(false); debugger.PushIOHandler(ci.GetIOHandler()); } } } } else { // Unwind any expression we might have been running in case our REPL // expression crashed and the user was looking around if (m_dedicated_repl_mode) { Thread *thread = exe_ctx.GetThreadPtr(); if (thread && thread->UnwindInnermostExpression().Success()) { thread->SetSelectedFrameByIndex(0, false); exe_ctx.SetFrameSP(thread->GetSelectedFrame()); } } const bool colorize_err = error_sp->GetFile().GetIsTerminalWithColors(); EvaluateExpressionOptions expr_options = m_expr_options; expr_options.SetCoerceToId(m_varobj_options.use_objc); expr_options.SetKeepInMemory(true); expr_options.SetUseDynamic(m_varobj_options.use_dynamic); expr_options.SetGenerateDebugInfo(true); expr_options.SetREPLEnabled(true); expr_options.SetColorizeErrors(colorize_err); expr_options.SetPoundLine(m_repl_source_path.c_str(), m_code.GetSize() + 1); expr_options.SetLanguage(GetLanguage()); PersistentExpressionState *persistent_state = m_target.GetPersistentExpressionStateForLanguage(GetLanguage()); const size_t var_count_before = persistent_state->GetSize(); const char *expr_prefix = nullptr; lldb::ValueObjectSP result_valobj_sp; Status error; lldb::ModuleSP jit_module_sp; lldb::ExpressionResults execution_results = UserExpression::Evaluate(exe_ctx, expr_options, code.c_str(), expr_prefix, result_valobj_sp, error, nullptr, // Fixed Expression &jit_module_sp); // CommandInterpreter &ci = debugger.GetCommandInterpreter(); if (process_sp && process_sp->IsAlive()) { bool add_to_code = true; bool handled = false; if (result_valobj_sp) { lldb::Format format = m_format_options.GetFormat(); if (result_valobj_sp->GetError().Success()) { handled |= PrintOneVariable(debugger, output_sp, result_valobj_sp); } else if (result_valobj_sp->GetError().GetError() == UserExpression::kNoResult) { if (format != lldb::eFormatVoid && debugger.GetNotifyVoid()) { error_sp->PutCString("(void)\n"); handled = true; } } } if (debugger.GetPrintDecls()) { for (size_t vi = var_count_before, ve = persistent_state->GetSize(); vi != ve; ++vi) { lldb::ExpressionVariableSP persistent_var_sp = persistent_state->GetVariableAtIndex(vi); lldb::ValueObjectSP valobj_sp = persistent_var_sp->GetValueObject(); PrintOneVariable(debugger, output_sp, valobj_sp, persistent_var_sp.get()); } } if (!handled) { bool useColors = error_sp->GetFile().GetIsTerminalWithColors(); switch (execution_results) { case lldb::eExpressionSetupError: case lldb::eExpressionParseError: add_to_code = false; LLVM_FALLTHROUGH; case lldb::eExpressionDiscarded: error_sp->Printf("%s\n", error.AsCString()); break; case lldb::eExpressionCompleted: break; case lldb::eExpressionInterrupted: if (useColors) { error_sp->Printf(ANSI_ESCAPE1(ANSI_FG_COLOR_RED)); error_sp->Printf(ANSI_ESCAPE1(ANSI_CTRL_BOLD)); } error_sp->Printf("Execution interrupted. "); if (useColors) error_sp->Printf(ANSI_ESCAPE1(ANSI_CTRL_NORMAL)); error_sp->Printf("Enter code to recover and continue.\nEnter LLDB " "commands to investigate (type :help for " "assistance.)\n"); break; case lldb::eExpressionHitBreakpoint: // Breakpoint was hit, drop into LLDB command interpreter if (useColors) { error_sp->Printf(ANSI_ESCAPE1(ANSI_FG_COLOR_RED)); error_sp->Printf(ANSI_ESCAPE1(ANSI_CTRL_BOLD)); } output_sp->Printf("Execution stopped at breakpoint. "); if (useColors) error_sp->Printf(ANSI_ESCAPE1(ANSI_CTRL_NORMAL)); output_sp->Printf("Enter LLDB commands to investigate (type help " "for assistance.)\n"); { lldb::IOHandlerSP io_handler_sp(ci.GetIOHandler()); if (io_handler_sp) { io_handler_sp->SetIsDone(false); debugger.PushIOHandler(ci.GetIOHandler()); } } break; case lldb::eExpressionTimedOut: error_sp->Printf("error: timeout\n"); if (error.AsCString()) error_sp->Printf("error: %s\n", error.AsCString()); break; case lldb::eExpressionResultUnavailable: // Shoulnd't happen??? error_sp->Printf("error: could not fetch result -- %s\n", error.AsCString()); break; case lldb::eExpressionStoppedForDebug: // Shoulnd't happen??? error_sp->Printf("error: stopped for debug -- %s\n", error.AsCString()); break; } } if (add_to_code) { const uint32_t new_default_line = m_code.GetSize() + 1; m_code.SplitIntoLines(code); // Update our code on disk if (!m_repl_source_path.empty()) { auto file = FileSystem::Instance().Open( FileSpec(m_repl_source_path), File::eOpenOptionWrite | File::eOpenOptionTruncate | File::eOpenOptionCanCreate, lldb::eFilePermissionsFileDefault); if (file) { std::string code(m_code.CopyList()); code.append(1, '\n'); size_t bytes_written = code.size(); file.get()->Write(code.c_str(), bytes_written); file.get()->Close(); } else { std::string message = llvm::toString(file.takeError()); error_sp->Printf("error: couldn't open %s: %s\n", m_repl_source_path.c_str(), message.c_str()); } // Now set the default file and line to the REPL source file m_target.GetSourceManager().SetDefaultFileAndLine( FileSpec(m_repl_source_path), new_default_line); } static_cast<IOHandlerEditline &>(io_handler) .SetBaseLineNumber(m_code.GetSize() + 1); } if (extra_line) { output_sp->Printf("\n"); } } } // Don't complain about the REPL process going away if we are in the // process of quitting. if (!did_quit && (!process_sp || !process_sp->IsAlive())) { error_sp->Printf( "error: REPL process is no longer alive, exiting REPL\n"); io_handler.SetIsDone(true); } } } void REPL::IOHandlerComplete(IOHandler &io_handler, CompletionRequest &request) { // Complete an LLDB command if the first character is a colon... if (request.GetRawLine().startswith(":")) { Debugger &debugger = m_target.GetDebugger(); // auto complete LLDB commands llvm::StringRef new_line = request.GetRawLine().drop_front(); CompletionResult sub_result; CompletionRequest sub_request(new_line, request.GetRawCursorPos() - 1, sub_result); debugger.GetCommandInterpreter().HandleCompletion(sub_request); StringList matches, descriptions; sub_result.GetMatches(matches); sub_result.GetDescriptions(descriptions); request.AddCompletions(matches, descriptions); return; } // Strip spaces from the line and see if we had only spaces if (request.GetRawLine().trim().empty()) { // Only spaces on this line, so just indent request.AddCompletion(m_indent_str); return; } std::string current_code; current_code.append(m_code.CopyList()); IOHandlerEditline &editline = static_cast<IOHandlerEditline &>(io_handler); const StringList *current_lines = editline.GetCurrentLines(); if (current_lines) { const uint32_t current_line_idx = editline.GetCurrentLineIndex(); if (current_line_idx < current_lines->GetSize()) { for (uint32_t i = 0; i < current_line_idx; ++i) { const char *line_cstr = current_lines->GetStringAtIndex(i); if (line_cstr) { current_code.append("\n"); current_code.append(line_cstr); } } } } current_code.append("\n"); current_code += request.GetRawLine(); StringList matches; int result = CompleteCode(current_code, matches); if (result == -2) { assert(matches.GetSize() == 1); request.AddCompletion(matches.GetStringAtIndex(0), "", CompletionMode::RewriteLine); } else request.AddCompletions(matches); } bool QuitCommandOverrideCallback(void *baton, const char **argv) { Target *target = (Target *)baton; lldb::ProcessSP process_sp(target->GetProcessSP()); if (process_sp) { process_sp->Destroy(false); process_sp->GetTarget().GetDebugger().ClearIOHandlers(); } return false; } Status REPL::RunLoop() { Status error; error = DoInitialization(); m_repl_source_path = GetSourcePath(); if (!error.Success()) return error; Debugger &debugger = m_target.GetDebugger(); lldb::IOHandlerSP io_handler_sp(GetIOHandler()); FileSpec save_default_file; uint32_t save_default_line = 0; if (!m_repl_source_path.empty()) { // Save the current default file and line m_target.GetSourceManager().GetDefaultFileAndLine(save_default_file, save_default_line); } debugger.PushIOHandler(io_handler_sp); // Check if we are in dedicated REPL mode where LLDB was start with the "-- // repl" option from the command line. Currently we know this by checking if // the debugger already has a IOHandler thread. if (!debugger.HasIOHandlerThread()) { // The debugger doesn't have an existing IOHandler thread, so this must be // dedicated REPL mode... m_dedicated_repl_mode = true; debugger.StartIOHandlerThread(); llvm::StringRef command_name_str("quit"); CommandObject *cmd_obj = debugger.GetCommandInterpreter().GetCommandObjectForCommand( command_name_str); if (cmd_obj) { assert(command_name_str.empty()); cmd_obj->SetOverrideCallback(QuitCommandOverrideCallback, &m_target); } } // Wait for the REPL command interpreter to get popped io_handler_sp->WaitForPop(); if (m_dedicated_repl_mode) { // If we were in dedicated REPL mode we would have started the IOHandler // thread, and we should kill our process lldb::ProcessSP process_sp = m_target.GetProcessSP(); if (process_sp && process_sp->IsAlive()) process_sp->Destroy(false); // Wait for the IO handler thread to exit (TODO: don't do this if the IO // handler thread already exists...) debugger.JoinIOHandlerThread(); } // Restore the default file and line if (save_default_file && save_default_line != 0) m_target.GetSourceManager().SetDefaultFileAndLine(save_default_file, save_default_line); return error; }
8,937
766
/* * Copyright 2008-2017 <NAME> * * See LICENCE for the full copyright terms. */ #include <assert.h> #include <limits.h> #include <stddef.h> #include <stdio.h> #include <fsm/fsm.h> #include <fsm/pred.h> #include <print/esc.h> #include <adt/set.h> #include <adt/bitmap.h> #include <adt/stateset.h> #include <adt/edgeset.h> #include "../internal.h" int fsm_iscomplete(const struct fsm *fsm, fsm_state_t state) { struct fsm_edge e; struct edge_iter it; struct bm bm; assert(fsm != NULL); assert(state < fsm->statecount); /* epsilon transitions have no effect on completeness */ (void) fsm->states[state].epsilons; bm_clear(&bm); for (edge_set_reset(fsm->states[state].edges, &it); edge_set_next(&it, &e); ) { assert(e.state < fsm->statecount); bm_set(&bm, e.symbol); } return bm_count(&bm) == FSM_SIGMA_COUNT; }
359
679
<reponame>Grosskopf/openoffice /************************************************************** * * 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. * *************************************************************/ #ifndef _SVX_OPTCHART_HXX #define _SVX_OPTCHART_HXX // header for SfxTabPage #include <sfx2/tabdlg.hxx> #include <vcl/fixed.hxx> // header for ValueSet #include <svtools/valueset.hxx> // header for ColorLB #include <svx/dlgctrl.hxx> // header for PushButton #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif // header for XColorList #include <svx/xtable.hxx> #include "cfgchart.hxx" class ChartColorLB : public ColorLB { public: ChartColorLB( Window* pParent, ResId Id ) : ColorLB( pParent, Id ) {} ChartColorLB( Window* pParent, WinBits aWB ) : ColorLB( pParent, aWB ) {} void FillBox( const SvxChartColorTable & rTab ); }; class SvxDefaultColorOptPage : public SfxTabPage { private: FixedLine aGbChartColors; ChartColorLB aLbChartColors; FixedLine aGbColorBox; ValueSet aValSetColorBox; PushButton aPBDefault; SvxChartOptions* pChartOptions; SvxChartColorTableItem* pColorConfig; XColorListSharedPtr maColorTab; DECL_LINK( ResetToDefaults, void * ); DECL_LINK( ListClickedHdl, ChartColorLB * ); DECL_LINK( BoxClickedHdl, ValueSet * ); void FillColorBox(); long GetColorIndex( const Color& rCol ); public: SvxDefaultColorOptPage( Window* pParent, const SfxItemSet& rInAttrs ); virtual ~SvxDefaultColorOptPage(); void Construct(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rInAttrs ); virtual sal_Bool FillItemSet( SfxItemSet& rOutAttrs ); virtual void Reset( const SfxItemSet& rInAttrs ); }; #endif // _SVX_OPTCHART_HXX
859
514
<gh_stars>100-1000 #include "level/area.hpp" using namespace level; void AreaRenderer::render( Tile::RenderPass render_pass, bgfx::ViewId view, u64 render_state) { // ensure all chunks have renderers, get rid of those that are no longer // valid for (auto it = this->chunk_renderers.begin(); it != this->chunk_renderers.end();) { auto &[offset, _] = *it; if (!this->area.contains_chunk(offset)) { this->chunk_renderers.erase(it++); } else { it++; } } for (auto &[offset, chunk] : this->area.chunks) { if (!this->chunk_renderers.contains(offset)) { this->chunk_renderers[offset] = std::make_unique<ChunkRenderer>( level::ChunkRenderer(*chunk.get())); } } // TODO: frustum culling for (auto &[_, renderer] : this->chunk_renderers) { renderer->render(render_pass, view, render_state); } }
452
354
<gh_stars>100-1000 /*------------------------------------------------------------------------- * drawElements Quality Program Test Executor * ------------------------------------------ * * Copyright 2014 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. * *//*! * \file * \brief Communication link abstraction. *//*--------------------------------------------------------------------*/ #include "xeCommLink.hpp" namespace xe { const char* getCommLinkStateName (CommLinkState state) { switch (state) { case COMMLINKSTATE_READY: return "COMMLINKSTATE_READY"; case COMMLINKSTATE_TEST_PROCESS_LAUNCHING: return "COMMLINKSTATE_PROCESS_LAUNCHING"; case COMMLINKSTATE_TEST_PROCESS_RUNNING: return "COMMLINKSTATE_PROCESS_RUNNING"; case COMMLINKSTATE_TEST_PROCESS_FINISHED: return "COMMLINKSTATE_FINISHED"; case COMMLINKSTATE_TEST_PROCESS_LAUNCH_FAILED: return "COMMLINKSTATE_LAUNCH_FAILED"; case COMMLINKSTATE_ERROR: return "COMMLINKSTATE_ERROR"; default: DE_ASSERT(false); return DE_NULL; } } CommLink::CommLink (void) { } CommLink::~CommLink (void) { } } // xe
519
511
/****************************************************************** * * Copyright 2014 Samsung Electronics 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 <jni.h> #include <stdio.h> #include <android/log.h> #include "caleutils.h" #include "logger.h" #include "cathreadpool.h" #include "uarraylist.h" #include "caadapterutils.h" #define TAG PCF("OIC_CA_LE_UTILS") jobject CALEGetUuidFromString(JNIEnv *env, const char* uuid) { VERIFY_NON_NULL_RET(uuid, TAG, "uuid is null", NULL); VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL); jclass jni_cid_UUID = (*env)->FindClass(env, "java/util/UUID"); if (!jni_cid_UUID) { OIC_LOG(ERROR, TAG, "jni_cid_UUID is not available"); goto error_exit; } jmethodID jni_mid_fromString = (*env)->GetStaticMethodID(env, jni_cid_UUID, "fromString", "(Ljava/lang/String;)" "Ljava/util/UUID;"); if (!jni_mid_fromString) { OIC_LOG(ERROR, TAG, "jni_mid_fromString is not available"); goto error_exit; } jstring str_uuid = (*env)->NewStringUTF(env, uuid); if (!str_uuid) { OIC_LOG(ERROR, TAG, "str_uuid is not available"); goto error_exit; } jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_UUID, jni_mid_fromString, str_uuid); if (!jni_obj_uuid) { OIC_LOG(ERROR, TAG, "Fail to get jni uuid object"); goto error_exit; } return jni_obj_uuid; error_exit: CACheckJNIException(env); return NULL; } jobject CALEGetParcelUuid(JNIEnv *env, jobject uuid) { VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL); VERIFY_NON_NULL_RET(uuid, TAG, "uuid is null", NULL); jclass jni_cid_ParcelUuid = (*env)->FindClass(env, "android/os/ParcelUuid"); if (!jni_cid_ParcelUuid) { OIC_LOG(ERROR, TAG, "jni_cid_ParcelUuid is not available"); goto error_exit; } jmethodID jni_mid_ParcelUuid = (*env)->GetMethodID(env, jni_cid_ParcelUuid, "<init>", "(Ljava/util/UUID;)V"); if (!jni_mid_ParcelUuid) { OIC_LOG(ERROR, TAG, "jni_mid_ParcelUuid is not available"); goto error_exit; } jobject jni_ParcelUuid = (*env)->NewObject(env, jni_cid_ParcelUuid, jni_mid_ParcelUuid, uuid); if (!jni_ParcelUuid) { OIC_LOG(ERROR, TAG, "Fail to get jni ParcelUuid"); goto error_exit; } return jni_ParcelUuid; error_exit: CACheckJNIException(env); return NULL; } jobject CALEGetParcelUuidFromString(JNIEnv *env, const char* uuid) { VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL); VERIFY_NON_NULL_RET(uuid, TAG, "uuid is null", NULL); jclass jni_cid_ParcelUuid = (*env)->FindClass(env, "android/os/ParcelUuid"); if (!jni_cid_ParcelUuid) { OIC_LOG(ERROR, TAG, "jni_cid_ParcelUuid is not available"); goto error_exit; } jmethodID jni_mid_fromString = (*env)->GetStaticMethodID(env, jni_cid_ParcelUuid, "fromString", "(Ljava/lang/String;)" "Landroid/os/ParcelUuid;"); if (!jni_mid_fromString) { OIC_LOG(ERROR, TAG, "jni_mid_fromString is not available"); goto error_exit; } jstring str_uuid = (*env)->NewStringUTF(env, uuid); if (!str_uuid) { OIC_LOG(ERROR, TAG, "str_uuid is not available"); goto error_exit; } jobject jni_obj_parcelUuid = (*env)->CallStaticObjectMethod(env, jni_cid_ParcelUuid, jni_mid_fromString, str_uuid); if (!jni_obj_parcelUuid) { OIC_LOG(ERROR, TAG, "Fail to get jni uuid object"); goto error_exit; } return jni_obj_parcelUuid; error_exit: CACheckJNIException(env); return NULL; } bool CALEIsBondedDevice(JNIEnv *env, jobject bluetoothDevice) { VERIFY_NON_NULL_RET(env, TAG, "env is null", false); VERIFY_NON_NULL_RET(bluetoothDevice, TAG, "bluetoothDevice is null", false); jmethodID jni_mid_getBondState = CAGetJNIMethodID(env, "android/bluetooth/BluetoothDevice", "getBondState", "()I"); if (!jni_mid_getBondState) { OIC_LOG(ERROR, TAG, "jni_mid_getBondState is null"); return false; } jint jni_bondState = (jint)(*env)->CallIntMethod(env, bluetoothDevice, jni_mid_getBondState); CACheckJNIException(env); OIC_LOG_V(DEBUG, TAG, "bond state is %d", jni_bondState); if (BOND_BONDED == jni_bondState) { OIC_LOG(DEBUG, TAG, "remote device is bonded"); return true; } else { OIC_LOG(DEBUG, TAG, "remote device is not bonded"); return false; } return false; } jobjectArray CALEGetBondedDevices(JNIEnv *env) { VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL); jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER); if (!jni_cid_BTAdapter) { OIC_LOG(ERROR, TAG, "getBondedDevices: jni_cid_BTAdapter is null"); goto error_exit; } jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM); CACheckJNIException(env); jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter); if (!jni_obj_BTAdapter) { OIC_LOG(ERROR, TAG, "getBondedDevices: bluetooth adapter is null"); goto error_exit; } // Get a list of currently paired devices jmethodID jni_mid_getBondedDevices = (*env)->GetMethodID(env, jni_cid_BTAdapter, "getBondedDevices", "()Ljava/util/Set;"); if (!jni_mid_getBondedDevices) { OIC_LOG(ERROR, TAG, "getBondedDevices: jni_mid_getBondedDevicesr is null"); goto error_exit; } jobject jni_obj_setPairedDevices = (*env)->CallObjectMethod(env, jni_obj_BTAdapter, jni_mid_getBondedDevices); if (!jni_obj_setPairedDevices) { OIC_LOG(ERROR, TAG, "getBondedDevices: jni_obj_setPairedDevices is null"); goto error_exit; } jmethodID jni_mid_toArray = CAGetJNIMethodID(env, "java/util/Set", "toArray", "()[Ljava/lang/Object;"); if (!jni_mid_toArray) { OIC_LOG(ERROR, TAG, "getBondedDevices: jni_mid_toArray is null"); return NULL; } jobjectArray jni_arrayPairedDevices = (jobjectArray)( (*env)->CallObjectMethod(env, jni_obj_setPairedDevices, jni_mid_toArray)); if (!jni_arrayPairedDevices) { OIC_LOG(ERROR, TAG, "getBondedDevices: jni_arrayPairedDevices is null"); goto error_exit; } return jni_arrayPairedDevices; error_exit: CACheckJNIException(env); return NULL; } jint CALEGetBTStateOnInfo(JNIEnv *env) { VERIFY_NON_NULL_RET(env, TAG, "env is null", -1); jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER); if (!jni_cid_BTAdapter) { OIC_LOG(ERROR, TAG, "getBTStateOnInfo: jni_cid_BTAdapter is null"); CACheckJNIException(env); return -1; } jfieldID jni_fid_stateon = (*env)->GetStaticFieldID(env, jni_cid_BTAdapter, "STATE_ON", "I"); if (!jni_fid_stateon) { OIC_LOG(ERROR, TAG, "get_field_state is not available"); CACheckJNIException(env); return -1; } jint jni_int_val = (*env)->GetStaticIntField(env, jni_cid_BTAdapter, jni_fid_stateon); CACheckJNIException(env); OIC_LOG_V(DEBUG, TAG, "bluetooth.STATE_ON state integer value : %d", jni_int_val); return jni_int_val; } CAResult_t CALECheckPlatformVersion(JNIEnv *env, uint16_t level) { jint jni_int_sdk = CALEGetBuildVersion(env); if (jni_int_sdk < level) { OIC_LOG(ERROR, TAG, "it is not supported"); return CA_NOT_SUPPORTED; } return CA_STATUS_OK; } jint CALEGetBuildVersion(JNIEnv *env) { VERIFY_NON_NULL_RET(env, TAG, "env is null", -1); // VERSION is a nested class within android.os.Build (hence "$" rather than "/") jclass jni_cls_version = (*env)->FindClass(env, "android/os/Build$VERSION"); if (!jni_cls_version) { OIC_LOG(ERROR, TAG, "jni_cls_version is null"); CACheckJNIException(env); return -1; } jfieldID jni_fid_sdk = (*env)->GetStaticFieldID(env, jni_cls_version, "SDK_INT", "I"); if (!jni_fid_sdk) { OIC_LOG(ERROR, TAG, "jni_fid_sdk is null"); CACheckJNIException(env); return -1; } jint jni_int_sdk = (*env)->GetStaticIntField(env, jni_cls_version, jni_fid_sdk); CACheckJNIException(env); OIC_LOG_V(DEBUG, TAG, "sdk version is %d", jni_int_sdk); return jni_int_sdk; } jint CALEGetBuildVersionCodeForName(JNIEnv *env, const char* versionName) { VERIFY_NON_NULL_RET(env, TAG, "env is null", -1); VERIFY_NON_NULL_RET(versionName, TAG, "versionName is null", -1); // VERSION is a nested class within android.os.Build (hence "$" rather than "/") jclass jni_cls_version = (*env)->FindClass(env, "android/os/Build$VERSION_CODES"); if (!jni_cls_version) { OIC_LOG(ERROR, TAG, "jni_cls_version is null"); CACheckJNIException(env); return -1; } jfieldID jni_fid_version = (*env)->GetStaticFieldID(env, jni_cls_version, versionName, "I"); if (!jni_fid_version) { OIC_LOG(ERROR, TAG, "jni_fid_version is null"); CACheckJNIException(env); return -1; } jint jni_int_version = (*env)->GetStaticIntField(env, jni_cls_version, jni_fid_version); CACheckJNIException(env); OIC_LOG_V(DEBUG, TAG, "version [%s] is %d",versionName, jni_int_version); return jni_int_version; } jboolean CALEIsEnableBTAdapter(JNIEnv *env) { VERIFY_NON_NULL_RET(env, TAG, "env is null", JNI_FALSE); jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER); if (!jni_cid_BTAdapter) { OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter: jni_cid_BTAdapter is null"); CACheckJNIException(env); return JNI_FALSE; } jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM); if (!jni_mid_getDefaultAdapter) { OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null"); CACheckJNIException(env); (*env)->DeleteLocalRef(env, jni_cid_BTAdapter); return JNI_FALSE; } jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter); if (!jni_obj_BTAdapter) { OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null"); CACheckJNIException(env); (*env)->DeleteLocalRef(env, jni_cid_BTAdapter); return JNI_FALSE; } // isEnable() jmethodID jni_mid_isEnable = (*env)->GetMethodID(env, jni_cid_BTAdapter, "isEnabled", "()Z"); if (!jni_mid_isEnable) { OIC_LOG(ERROR, TAG, "jni_mid_isEnable is null"); CACheckJNIException(env); (*env)->DeleteLocalRef(env, jni_cid_BTAdapter); (*env)->DeleteLocalRef(env, jni_obj_BTAdapter); return JNI_FALSE; } jboolean jni_isEnable = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter, jni_mid_isEnable); CACheckJNIException(env); OIC_LOG_V(DEBUG, TAG, "adapter state is %d", jni_isEnable); (*env)->DeleteLocalRef(env, jni_cid_BTAdapter); (*env)->DeleteLocalRef(env, jni_obj_BTAdapter); return jni_isEnable; } jstring CALEGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice) { VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL); VERIFY_NON_NULL_RET(bluetoothDevice, TAG, "bluetoothDevice is null", NULL); jmethodID jni_mid_getAddress = CAGetJNIMethodID(env, "android/bluetooth/BluetoothDevice", "getAddress", "()Ljava/lang/String;"); if (!jni_mid_getAddress) { OIC_LOG(ERROR, TAG, "jni_mid_getAddress is null"); return NULL; } jstring jni_address = (jstring)(*env)->CallObjectMethod(env, bluetoothDevice, jni_mid_getAddress); if (!jni_address) { OIC_LOG(ERROR, TAG, "jni_address is null"); CACheckJNIException(env); return NULL; } return jni_address; } jint CALEGetConstantsValue(JNIEnv *env, const char* classType, const char* name) { VERIFY_NON_NULL_RET(env, TAG, "env", -1); VERIFY_NON_NULL_RET(classType, TAG, "classType", -1); VERIFY_NON_NULL_RET(name, TAG, "name", -1); jclass jni_cid = (*env)->FindClass(env, classType); if (!jni_cid) { OIC_LOG(ERROR, TAG, "jni_cid is null"); CACheckJNIException(env); return -1; } jfieldID jni_fieldID = (*env)->GetStaticFieldID(env, jni_cid, name, "I"); if (!jni_fieldID) { OIC_LOG(ERROR, TAG, "jni_fieldID is null"); CACheckJNIException(env); return -1; } jint jni_id = (*env)->GetStaticIntField(env, jni_cid, jni_fieldID); CACheckJNIException(env); return jni_id; } jobject CALEGetRemoteDevice(JNIEnv *env, jstring address) { OIC_LOG(DEBUG, TAG, "CALEGetRemoteDevice"); VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL); VERIFY_NON_NULL_RET(address, TAG, "address is null", NULL); jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADAPTER); if (!jni_cid_BTAdapter) { OIC_LOG(ERROR, TAG, "jni_cid_BTAdapter is null"); goto error_exit; } // get remote bt adapter method jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM); if (!jni_mid_getDefaultAdapter) { OIC_LOG(ERROR, TAG, "jni_mid_getDefaultAdapter is null"); goto error_exit; } // gat bt adapter object jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter); if (!jni_obj_BTAdapter) { OIC_LOG(ERROR, TAG, "jni_obj_BTAdapter is null"); goto error_exit; } jmethodID jni_mid_getRemoteDevice = (*env)->GetMethodID(env, jni_cid_BTAdapter, "getRemoteDevice", METHODID_BT_REMOTE_DEVICE); if (!jni_mid_getRemoteDevice) { OIC_LOG(ERROR, TAG, "jni_mid_getRemoteDevice is null"); goto error_exit; } jobject jni_obj_device = (*env)->CallObjectMethod(env, jni_obj_BTAdapter, jni_mid_getRemoteDevice, address); if (!jni_obj_device) { OIC_LOG(ERROR, TAG, "jni_obj_device is null"); goto error_exit; } return jni_obj_device; error_exit: CACheckJNIException(env); return NULL; } jstring CALEGetAddressFromGatt(JNIEnv *env, jobject gatt) { OIC_LOG(DEBUG, TAG, "CALEGetAddressFromGatt"); VERIFY_NON_NULL_RET(env, TAG, "env is null", NULL); VERIFY_NON_NULL_RET(gatt, TAG, "gatt is null", NULL); jmethodID jni_mid_getDevice = CAGetJNIMethodID(env, CLASSPATH_BT_GATT, "getDevice", METHODID_BT_DEVICE); if (!jni_mid_getDevice) { OIC_LOG(ERROR, TAG, "jni_mid_getDevice is null"); return NULL; } jobject jni_obj_device = (*env)->CallObjectMethod(env, gatt, jni_mid_getDevice); if (!jni_obj_device) { OIC_LOG(ERROR, TAG, "jni_obj_device is null"); CACheckJNIException(env); return NULL; } jstring jni_address = CALEGetAddressFromBTDevice(env, jni_obj_device); if (!jni_address) { OIC_LOG(ERROR, TAG, "jni_address is null"); return NULL; } return jni_address; }
9,209
970
{"id":1,"name":"group issue board","group":{"id":5,"name":"Documentcloud","path":"documentcloud","owner_id":null,"created_at":"2018-05-07T06:52:45.788Z","updated_at":"2018-07-03T06:48:17.005Z","description":"Consequatur aut a aperiam ut.","avatar":{"url":null},"membership_lock":false,"share_with_group_lock":false,"visibility_level":20,"request_access_enabled":false,"ldap_sync_status":"ready","ldap_sync_error":null,"ldap_sync_last_update_at":null,"ldap_sync_last_successful_update_at":null,"ldap_sync_last_sync_at":null,"lfs_enabled":null,"parent_id":null,"shared_runners_minutes_limit":null,"repository_size_limit":null,"require_two_factor_authentication":false,"two_factor_grace_period":48,"plan_id":null,"project_creation_level":2,"runners_token":"<PASSWORD>"},"milestone":{"id":12,"title":"10.0"},"lists":[{"id":1,"label":{"name":"Testing","color":"#F0AD4E","description":null},"position":1},{"id":2,"label":{"name":"Ready","color":"#FF0000","description":null},"position":2},{"id":3,"label":{"name":"Production","color":"#FF5F00","description":null},"position":3}]}
355
14,668
<filename>components/content_creation/reactions/android/java/src/org/chromium/components/content_creation/reactions/ReactionMetadata.java // Copyright 2021 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. package org.chromium.components.content_creation.reactions; /** * Model class for a lightweight reaction. */ public class ReactionMetadata { public final @ReactionType int type; public final String localizedName; public final String thumbnailUrl; public final String assetUrl; public final int frameCount; public ReactionMetadata(@ReactionType int type, String localizedName, String thumbnailUrl, String assetUrl, int frameCount) { this.type = type; this.localizedName = localizedName; this.thumbnailUrl = thumbnailUrl; this.assetUrl = assetUrl; this.frameCount = frameCount; } }
306
5,672
<gh_stars>1000+ # Lint as: python3 # Copyright 2020 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. # ============================================================================== r"""Lint assertions that adhere to the Google dev docs style guide. This style module is a non-exhaustive implemention of style rules found in the Google developer documentation style guide: https://developers.google.com/style When adding lints, please link to the URL of the relevant style rule. """ import re from tensorflow_docs.tools.nblint.decorator import fail from tensorflow_docs.tools.nblint.decorator import lint from tensorflow_docs.tools.nblint.decorator import Options def search_wordlist(wordlist, src_str): """Search for wordlist entries in text and return set of found items. Args: wordlist: Dict of word entries and recommendations to search in string. src_str: String to search for word entries. Returns: A dict that is a subset of entries from `wordlist` found in `src_str`. """ found_words = {} for word in wordlist: # Word-boundary and ignore between path seperator '/'. if re.search(rf"[^/]\b{word}\b[^/]", src_str, re.IGNORECASE): alt_word = wordlist[word] if not alt_word: alt_word = "n/a" found_words[word] = alt_word return found_words # Non-exhaustive list: {word: alt-word} (Use False if alt not provided.) _INCLUSIVE_WORDLIST = { "blacklist": "blocked", "whitelist": "allowed", "master": "primary", "slave": "replica", "native": "built-in" } @lint( message="Use inclusive language: https://developers.google.com/style/inclusive-documentation", cond=Options.Cond.ALL) def inclusive_language(args): """Test for words found in inclusive wordlist and recommend alternatives.""" found_words = search_wordlist(_INCLUSIVE_WORDLIST, args["cell_source"]) if found_words: words = ", ".join([f"{word} => {alt}" for word, alt in found_words.items()]) fail(f"Use inclusive language where possible and accurate. Found: {words}") else: return True # Non-exhaustive list: {word: alt-word} (Use False if alt not provided.) _SECOND_PERSON_WORDLIST = {"we": "you", "we're": "you are"} @lint( message="Prefer second person instead of first person: https://developers.google.com/style/person", cond=Options.Cond.ALL) def second_person(args): """Test for first person usage in doc and recommend second person.""" found_words = search_wordlist(_SECOND_PERSON_WORDLIST, args["cell_source"]) if found_words: words = ", ".join([f"{word} => {alt}" for word, alt in found_words.items()]) fail(f"Prefer second person instead of first person. Found: {words}") else: return True
1,029
1,350
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.apimanagement.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** Custom hostname configuration. */ @Fluent public final class HostnameConfiguration { @JsonIgnore private final ClientLogger logger = new ClientLogger(HostnameConfiguration.class); /* * Hostname type. */ @JsonProperty(value = "type", required = true) private HostnameType type; /* * Hostname to configure on the Api Management service. */ @JsonProperty(value = "hostName", required = true) private String hostname; /* * Url to the KeyVault Secret containing the Ssl Certificate. If absolute * Url containing version is provided, auto-update of ssl certificate will * not work. This requires Api Management service to be configured with * aka.ms/apimmsi. The secret should be of type *application/x-pkcs12* */ @JsonProperty(value = "keyVaultId") private String keyVaultId; /* * System or User Assigned Managed identity clientId as generated by Azure * AD, which has GET access to the keyVault containing the SSL certificate. */ @JsonProperty(value = "identityClientId") private String identityClientId; /* * Base64 Encoded certificate. */ @JsonProperty(value = "encodedCertificate") private String encodedCertificate; /* * Certificate Password. */ @JsonProperty(value = "certificatePassword") private String certificatePassword; /* * Specify true to setup the certificate associated with this Hostname as * the Default SSL Certificate. If a client does not send the SNI header, * then this will be the certificate that will be challenged. The property * is useful if a service has multiple custom hostname enabled and it needs * to decide on the default ssl certificate. The setting only applied to * Proxy Hostname Type. */ @JsonProperty(value = "defaultSslBinding") private Boolean defaultSslBinding; /* * Specify true to always negotiate client certificate on the hostname. * Default Value is false. */ @JsonProperty(value = "negotiateClientCertificate") private Boolean negotiateClientCertificate; /* * Certificate information. */ @JsonProperty(value = "certificate") private CertificateInformation certificate; /** * Get the type property: Hostname type. * * @return the type value. */ public HostnameType type() { return this.type; } /** * Set the type property: Hostname type. * * @param type the type value to set. * @return the HostnameConfiguration object itself. */ public HostnameConfiguration withType(HostnameType type) { this.type = type; return this; } /** * Get the hostname property: Hostname to configure on the Api Management service. * * @return the hostname value. */ public String hostname() { return this.hostname; } /** * Set the hostname property: Hostname to configure on the Api Management service. * * @param hostname the hostname value to set. * @return the HostnameConfiguration object itself. */ public HostnameConfiguration withHostname(String hostname) { this.hostname = hostname; return this; } /** * Get the keyVaultId property: Url to the KeyVault Secret containing the Ssl Certificate. If absolute Url * containing version is provided, auto-update of ssl certificate will not work. This requires Api Management * service to be configured with aka.ms/apimmsi. The secret should be of type *application/x-pkcs12*. * * @return the keyVaultId value. */ public String keyVaultId() { return this.keyVaultId; } /** * Set the keyVaultId property: Url to the KeyVault Secret containing the Ssl Certificate. If absolute Url * containing version is provided, auto-update of ssl certificate will not work. This requires Api Management * service to be configured with aka.ms/apimmsi. The secret should be of type *application/x-pkcs12*. * * @param keyVaultId the keyVaultId value to set. * @return the HostnameConfiguration object itself. */ public HostnameConfiguration withKeyVaultId(String keyVaultId) { this.keyVaultId = keyVaultId; return this; } /** * Get the identityClientId property: System or User Assigned Managed identity clientId as generated by Azure AD, * which has GET access to the keyVault containing the SSL certificate. * * @return the identityClientId value. */ public String identityClientId() { return this.identityClientId; } /** * Set the identityClientId property: System or User Assigned Managed identity clientId as generated by Azure AD, * which has GET access to the keyVault containing the SSL certificate. * * @param identityClientId the identityClientId value to set. * @return the HostnameConfiguration object itself. */ public HostnameConfiguration withIdentityClientId(String identityClientId) { this.identityClientId = identityClientId; return this; } /** * Get the encodedCertificate property: Base64 Encoded certificate. * * @return the encodedCertificate value. */ public String encodedCertificate() { return this.encodedCertificate; } /** * Set the encodedCertificate property: Base64 Encoded certificate. * * @param encodedCertificate the encodedCertificate value to set. * @return the HostnameConfiguration object itself. */ public HostnameConfiguration withEncodedCertificate(String encodedCertificate) { this.encodedCertificate = encodedCertificate; return this; } /** * Get the certificatePassword property: Certificate Password. * * @return the certificatePassword value. */ public String certificatePassword() { return this.certificatePassword; } /** * Set the certificatePassword property: Certificate Password. * * @param certificatePassword the certificatePassword value to set. * @return the HostnameConfiguration object itself. */ public HostnameConfiguration withCertificatePassword(String certificatePassword) { this.certificatePassword = certificatePassword; return this; } /** * Get the defaultSslBinding property: Specify true to setup the certificate associated with this Hostname as the * Default SSL Certificate. If a client does not send the SNI header, then this will be the certificate that will be * challenged. The property is useful if a service has multiple custom hostname enabled and it needs to decide on * the default ssl certificate. The setting only applied to Proxy Hostname Type. * * @return the defaultSslBinding value. */ public Boolean defaultSslBinding() { return this.defaultSslBinding; } /** * Set the defaultSslBinding property: Specify true to setup the certificate associated with this Hostname as the * Default SSL Certificate. If a client does not send the SNI header, then this will be the certificate that will be * challenged. The property is useful if a service has multiple custom hostname enabled and it needs to decide on * the default ssl certificate. The setting only applied to Proxy Hostname Type. * * @param defaultSslBinding the defaultSslBinding value to set. * @return the HostnameConfiguration object itself. */ public HostnameConfiguration withDefaultSslBinding(Boolean defaultSslBinding) { this.defaultSslBinding = defaultSslBinding; return this; } /** * Get the negotiateClientCertificate property: Specify true to always negotiate client certificate on the hostname. * Default Value is false. * * @return the negotiateClientCertificate value. */ public Boolean negotiateClientCertificate() { return this.negotiateClientCertificate; } /** * Set the negotiateClientCertificate property: Specify true to always negotiate client certificate on the hostname. * Default Value is false. * * @param negotiateClientCertificate the negotiateClientCertificate value to set. * @return the HostnameConfiguration object itself. */ public HostnameConfiguration withNegotiateClientCertificate(Boolean negotiateClientCertificate) { this.negotiateClientCertificate = negotiateClientCertificate; return this; } /** * Get the certificate property: Certificate information. * * @return the certificate value. */ public CertificateInformation certificate() { return this.certificate; } /** * Set the certificate property: Certificate information. * * @param certificate the certificate value to set. * @return the HostnameConfiguration object itself. */ public HostnameConfiguration withCertificate(CertificateInformation certificate) { this.certificate = certificate; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (type() == null) { throw logger .logExceptionAsError( new IllegalArgumentException("Missing required property type in model HostnameConfiguration")); } if (hostname() == null) { throw logger .logExceptionAsError( new IllegalArgumentException("Missing required property hostname in model HostnameConfiguration")); } if (certificate() != null) { certificate().validate(); } } }
3,419
307
<gh_stars>100-1000 package se.jiderhamn.classloader.leak.prevention.cleanup; import com.fasterxml.jackson.databind.type.TypeFactory; import se.jiderhamn.classloader.PackagesLoadedOutsideClassLoader; /** * Test cases for {@link JacksonCleanUp} * @author <NAME> */ @PackagesLoadedOutsideClassLoader(packages = {"com.fasterxml.jackson.databind"}, addToDefaults = true) public class JacksonCleanUpTest extends ClassLoaderPreMortemCleanUpTestBase<JacksonCleanUp> { @Override protected void triggerLeak() throws Exception { TypeFactory.defaultInstance().constructSimpleType(JacksonCleanUpTest.class, null); } }
195
1,024
<filename>spec/test_templates/json/apigateway_accesslogging_v2/apigateway_with_no_access_logging.json<gh_stars>1000+ { "Resources": { "ApiGatewayNoAccessLogging": { "Type": "AWS::ApiGatewayV2::Stage", "Properties": { "ApiId": "ApiId" } } } }
125
515
/* * Copyright 2018-present HiveMQ and the HiveMQ Community * * 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.hivemq.client.internal.mqtt.message; import com.hivemq.client.internal.mqtt.datatypes.MqttUserPropertiesImpl; import com.hivemq.client.mqtt.mqtt5.message.Mqtt5MessageType; import org.jetbrains.annotations.NotNull; /** * Base class for MQTT messages with state-specific data. * * @param <M> the type of the stateless MQTT message. * @author <NAME> */ public abstract class MqttStatefulMessage<M extends MqttMessageWithUserProperties> implements MqttMessage.WithUserProperties { private final @NotNull M statelessMessage; protected MqttStatefulMessage(final @NotNull M statelessMessage) { this.statelessMessage = statelessMessage; } @Override public @NotNull Mqtt5MessageType getType() { return statelessMessage.getType(); } @Override public @NotNull MqttUserPropertiesImpl getUserProperties() { return statelessMessage.getUserProperties(); } /** * @return the stateless MQTT message. */ public @NotNull M stateless() { return statelessMessage; } protected @NotNull String toAttributeString() { return "stateless=" + statelessMessage; } /** * Base class for MQTT messages with a packet identifier and other state-specific data. * * @param <M> the type of the stateless MQTT message. * @author <NAME> */ public abstract static class WithId<M extends MqttMessageWithUserProperties> extends MqttStatefulMessage<M> implements MqttMessage.WithId { private final int packetIdentifier; protected WithId(final @NotNull M statelessMessage, final int packetIdentifier) { super(statelessMessage); this.packetIdentifier = packetIdentifier; } @Override public int getPacketIdentifier() { return packetIdentifier; } @Override protected @NotNull String toAttributeString() { return super.toAttributeString() + ", packetIdentifier=" + packetIdentifier; } } }
936
1,442
#include "app.h" #include "../apps_container.h" #include "graph_icon.h" #include <apps/i18n.h> using namespace Poincare; using namespace Shared; using namespace Escher; namespace Graph { I18n::Message App::Descriptor::name() const { return I18n::Message::FunctionApp; } I18n::Message App::Descriptor::upperName() const { return I18n::Message::FunctionAppCapital; } const Image * App::Descriptor::icon() const { return ImageStore::GraphIcon; } App::Snapshot::Snapshot() : Shared::FunctionApp::Snapshot::Snapshot(), m_functionStore(), m_graphRange() { } App * App::Snapshot::unpack(Container * container) { return new (container->currentAppBuffer()) App(this); } void App::Snapshot::reset() { Shared::FunctionApp::Snapshot::reset(); for (int i = 0; i < Shared::ContinuousFunction::k_numberOfPlotTypes; i++) { m_interval[i].reset(); } } static constexpr App::Descriptor sDescriptor; const App::Descriptor * App::Snapshot::descriptor() const { return &sDescriptor; } void App::Snapshot::tidy() { m_functionStore.tidy(); m_graphRange.setDelegate(nullptr); } App::App(Snapshot * snapshot) : FunctionApp(snapshot, &m_inputViewController), m_listController(&m_listFooter, &m_listHeader, &m_listFooter, this), m_listFooter(&m_listHeader, &m_listController, &m_listController, ButtonRowController::Position::Bottom, ButtonRowController::Style::EmbossedGray), m_listHeader(&m_listStackViewController, &m_listFooter, &m_listController), m_listStackViewController(&m_tabViewController, &m_listHeader), m_graphController(&m_graphAlternateEmptyViewController, this, snapshot->graphRange(), snapshot->cursor(), snapshot->indexFunctionSelectedByCursor(), snapshot->rangeVersion(), &m_graphHeader), m_graphAlternateEmptyViewController(&m_graphHeader, &m_graphController, &m_graphController), m_graphHeader(&m_graphStackViewController, &m_graphAlternateEmptyViewController, &m_graphController), m_graphStackViewController(&m_tabViewController, &m_graphHeader), m_valuesController(&m_valuesAlternateEmptyViewController, this, &m_valuesHeader), m_valuesAlternateEmptyViewController(&m_valuesHeader, &m_valuesController, &m_valuesController), m_valuesHeader(&m_valuesStackViewController, &m_valuesAlternateEmptyViewController, &m_valuesController), m_valuesStackViewController(&m_tabViewController, &m_valuesHeader), m_tabViewController(&m_inputViewController, snapshot, &m_listStackViewController, &m_graphStackViewController, &m_valuesStackViewController), m_inputViewController(&m_modalViewController, &m_tabViewController, this, this, this) { } CodePoint App::XNT() { int selectedFunctionIndex = m_listController.selectedRow(); if (selectedFunctionIndex >= 0) { assert(selectedFunctionIndex < functionStore()->numberOfModels()); Ion::Storage::Record record = functionStore()->recordAtIndex(selectedFunctionIndex); return functionStore()->modelForRecord(record)->symbol(); } return 'x'; } NestedMenuController * App::variableBoxForInputEventHandler(InputEventHandler * textInput) { MathVariableBoxController * varBox = AppsContainer::sharedAppsContainer()->variableBoxController(); varBox->setSender(textInput); varBox->lockDeleteEvent(MathVariableBoxController::Page::Function); return varBox; } }
1,029
419
<reponame>sigix/jaeger-client-java /* * Copyright (c) 2017, Uber Technologies, 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.jaegertracing.internal.baggage; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import io.jaegertracing.internal.baggage.http.BaggageRestrictionResponse; import io.jaegertracing.internal.exceptions.BaggageRestrictionManagerException; import io.jaegertracing.mocks.MockAgentResource; import java.net.URI; import java.util.List; import java.util.Properties; import javax.ws.rs.core.Application; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.glassfish.jersey.test.TestProperties; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class HttpBaggageRestrictionManagerProxyTest extends JerseyTest { private HttpBaggageRestrictionManagerProxy undertest; private BaggageRestrictionResponse expectedRestriction = new BaggageRestrictionResponse("key", 10); private static Properties originalProps; @BeforeClass public static void beforeClass() { originalProps = new Properties(System.getProperties()); if (System.getProperty(TestProperties.CONTAINER_PORT) == null) { System.setProperty(TestProperties.CONTAINER_PORT, "0"); } } @AfterClass public static void afterClass() { System.setProperties(originalProps); } @Override @Before public void setUp() throws Exception { super.setUp(); undertest = new HttpBaggageRestrictionManagerProxy(null); } @Override protected Application configure() { return new ResourceConfig(MockAgentResource.class); } @Test public void testGetBaggageRestrictions() throws Exception { URI uri = target().getUri(); undertest = new HttpBaggageRestrictionManagerProxy(uri.getHost() + ":" + uri.getPort()); List<BaggageRestrictionResponse> response = undertest.getBaggageRestrictions("clairvoyant"); assertNotNull(response); assertEquals(1, response.size()); assertEquals(expectedRestriction, response.get(0)); } @Test(expected = BaggageRestrictionManagerException.class) public void testGetSamplingStrategyError() throws Exception { URI uri = target().getUri(); undertest = new HttpBaggageRestrictionManagerProxy(uri.getHost() + ":" + uri.getPort()); undertest.getBaggageRestrictions(""); } @Test(expected = BaggageRestrictionManagerException.class) public void testParseInvalidJson() throws Exception { undertest.parseJson("invalid json"); } }
959
654
<reponame>cocolord/SegmenTron import torch import torch.nn as nn import torch.nn.functional as F from .segbase import SegBaseModel from .model_zoo import MODEL_REGISTRY from ..modules import _FCNHead from ..config import cfg __all__ = ["EDANet"] @MODEL_REGISTRY.register() class EDANet(SegBaseModel): def __init__(self): super(EDANet, self).__init__(need_backbone=False) self.layers = nn.ModuleList() self.dilation1 = [1, 1, 1, 2, 2] self.dilation2 = [2, 2, 4, 4, 8, 8, 16, 16] # DownsamplerBlock1 self.layers.append(DownsamplerBlock(3, 15)) # DownsamplerBlock2 self.layers.append(DownsamplerBlock(15, 60)) # EDA module 1-1 ~ 1-5 for i in range(5): self.layers.append(EDABlock(60 + 40 * i, self.dilation1[i])) # DownsamplerBlock3 self.layers.append(DownsamplerBlock(260, 130)) # EDA module 2-1 ~ 2-8 for j in range(8): self.layers.append(EDABlock(130 + 40 * j, self.dilation2[j])) # Projection layer self.project_layer = nn.Conv2d(450, self.nclass, kernel_size=1) self.weights_init() def weights_init(self): for idx, m in enumerate(self.modules()): classname = m.__class__.__name__ if classname.find('Conv') != -1: m.weight.data.normal_(0.0, 0.02) elif classname.find('BatchNorm') != -1: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) def forward(self, x): output = x for layer in self.layers: output = layer(output) output = self.project_layer(output) output = F.interpolate(output, size=x.size()[2:], mode='bilinear', align_corners=True) # Bilinear interpolation x8 # output = F.interpolate(output, scale_factor=8, mode='bilinear', align_corners=True) # # # Bilinear interpolation x2 (inference only) # if not self.training: # output = F.interpolate(output, scale_factor=2, mode='bilinear', align_corners=True) return tuple([output]) class DownsamplerBlock(nn.Module): def __init__(self, ninput, noutput): super(DownsamplerBlock, self).__init__() self.ninput = ninput self.noutput = noutput if self.ninput < self.noutput: # Wout > Win self.conv = nn.Conv2d(ninput, noutput - ninput, kernel_size=3, stride=2, padding=1) self.pool = nn.MaxPool2d(2, stride=2) else: # Wout < Win self.conv = nn.Conv2d(ninput, noutput, kernel_size=3, stride=2, padding=1) self.bn = nn.BatchNorm2d(noutput) def forward(self, x): if self.ninput < self.noutput: output = torch.cat([self.conv(x), self.pool(x)], 1) else: output = self.conv(x) output = self.bn(output) return F.relu(output) class EDABlock(nn.Module): def __init__(self, ninput, dilated, k=40, dropprob=0.02): super(EDABlock, self).__init__() # k: growthrate # dropprob:a dropout layer between the last ReLU and the concatenation of each module self.conv1x1 = nn.Conv2d(ninput, k, kernel_size=1) self.bn0 = nn.BatchNorm2d(k) self.conv3x1_1 = nn.Conv2d(k, k, kernel_size=(3, 1), padding=(1, 0)) self.conv1x3_1 = nn.Conv2d(k, k, kernel_size=(1, 3), padding=(0, 1)) self.bn1 = nn.BatchNorm2d(k) self.conv3x1_2 = nn.Conv2d(k, k, (3, 1), stride=1, padding=(dilated, 0), dilation=dilated) self.conv1x3_2 = nn.Conv2d(k, k, (1, 3), stride=1, padding=(0, dilated), dilation=dilated) self.bn2 = nn.BatchNorm2d(k) self.dropout = nn.Dropout2d(dropprob) def forward(self, x): input = x output = self.conv1x1(x) output = self.bn0(output) output = F.relu(output) output = self.conv3x1_1(output) output = self.conv1x3_1(output) output = self.bn1(output) output = F.relu(output) output = self.conv3x1_2(output) output = self.conv1x3_2(output) output = self.bn2(output) output = F.relu(output) if (self.dropout.p != 0): output = self.dropout(output) output = torch.cat([output, input], 1) # print output.size() #check the output return output
2,160
11,811
<filename>runtime/Python3/src/antlr4/ListTokenSource.py # # Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. # Use of this file is governed by the BSD 3-clause license that # can be found in the LICENSE.txt file in the project root. # # # Provides an implementation of {@link TokenSource} as a wrapper around a list # of {@link Token} objects. # # <p>If the final token in the list is an {@link Token#EOF} token, it will be used # as the EOF token for every call to {@link #nextToken} after the end of the # list is reached. Otherwise, an EOF token will be created.</p> # from antlr4.CommonTokenFactory import CommonTokenFactory from antlr4.Lexer import TokenSource from antlr4.Token import Token class ListTokenSource(TokenSource): __slots__ = ('tokens', 'sourceName', 'pos', 'eofToken', '_factory') # Constructs a new {@link ListTokenSource} instance from the specified # collection of {@link Token} objects and source name. # # @param tokens The collection of {@link Token} objects to provide as a # {@link TokenSource}. # @param sourceName The name of the {@link TokenSource}. If this value is # {@code null}, {@link #getSourceName} will attempt to infer the name from # the next {@link Token} (or the previous token if the end of the input has # been reached). # # @exception NullPointerException if {@code tokens} is {@code null} # def __init__(self, tokens:list, sourceName:str=None): if tokens is None: raise ReferenceError("tokens cannot be null") self.tokens = tokens self.sourceName = sourceName # The index into {@link #tokens} of token to return by the next call to # {@link #nextToken}. The end of the input is indicated by this value # being greater than or equal to the number of items in {@link #tokens}. self.pos = 0 # This field caches the EOF token for the token source. self.eofToken = None # This is the backing field for {@link #getTokenFactory} and self._factory = CommonTokenFactory.DEFAULT # # {@inheritDoc} # @property def column(self): if self.pos < len(self.tokens): return self.tokens[self.pos].column elif self.eofToken is not None: return self.eofToken.column elif len(self.tokens) > 0: # have to calculate the result from the line/column of the previous # token, along with the text of the token. lastToken = self.tokens[len(self.tokens) - 1] tokenText = lastToken.text if tokenText is not None: lastNewLine = tokenText.rfind('\n') if lastNewLine >= 0: return len(tokenText) - lastNewLine - 1 return lastToken.column + lastToken.stop - lastToken.start + 1 # only reach this if tokens is empty, meaning EOF occurs at the first # position in the input return 0 # # {@inheritDoc} # def nextToken(self): if self.pos >= len(self.tokens): if self.eofToken is None: start = -1 if len(self.tokens) > 0: previousStop = self.tokens[len(self.tokens) - 1].stop if previousStop != -1: start = previousStop + 1 stop = max(-1, start - 1) self.eofToken = self._factory.create((self, self.getInputStream()), Token.EOF, "EOF", Token.DEFAULT_CHANNEL, start, stop, self.line, self.column) return self.eofToken t = self.tokens[self.pos] if self.pos == len(self.tokens) - 1 and t.type == Token.EOF: self.eofToken = t self.pos += 1 return t # # {@inheritDoc} # @property def line(self): if self.pos < len(self.tokens): return self.tokens[self.pos].line elif self.eofToken is not None: return self.eofToken.line elif len(self.tokens) > 0: # have to calculate the result from the line/column of the previous # token, along with the text of the token. lastToken = self.tokens[len(self.tokens) - 1] line = lastToken.line tokenText = lastToken.text if tokenText is not None: line += tokenText.count('\n') # if no text is available, assume the token did not contain any newline characters. return line # only reach this if tokens is empty, meaning EOF occurs at the first # position in the input return 1 # # {@inheritDoc} # def getInputStream(self): if self.pos < len(self.tokens): return self.tokens[self.pos].getInputStream() elif self.eofToken is not None: return self.eofToken.getInputStream() elif len(self.tokens) > 0: return self.tokens[len(self.tokens) - 1].getInputStream() else: # no input stream information is available return None # # {@inheritDoc} # def getSourceName(self): if self.sourceName is not None: return self.sourceName inputStream = self.getInputStream() if inputStream is not None: return inputStream.getSourceName() else: return "List"
2,346
348
<filename>docs/data/leg-t1/085/08504021.json {"nom":"<NAME>","circ":"4ème circonscription","dpt":"Vendée","inscrits":1253,"abs":614,"votants":639,"blancs":14,"nuls":6,"exp":619,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":271},{"nuance":"UDI","nom":"<NAME>","voix":101},{"nuance":"FI","nom":"Mme <NAME>","voix":82},{"nuance":"FN","nom":"Mme <NAME>","voix":82},{"nuance":"ECO","nom":"Mme <NAME>","voix":48},{"nuance":"COM","nom":"Mme <NAME>","voix":18},{"nuance":"DVD","nom":"Mme <NAME>","voix":7},{"nuance":"EXG","nom":"Mme <NAME>","voix":6},{"nuance":"DIV","nom":"Mme <NAME>","voix":4}]}
245
10,608
<reponame>WojciechKusa/datasets<filename>datasets/muchocine/muchocine.py # coding=utf-8 # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor. # # 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. import glob import os import re from xml.dom.minidom import parseString import datasets # no BibTeX citation _CITATION = "" _DESCRIPTION = """\ The Muchocine reviews dataset contains 3,872 longform movie reviews in Spanish language, each with a shorter summary review, and a rating on a 1-5 scale. """ _LICENSE = "CC-BY-2.1" _URLs = {"default": "http://www.lsi.us.es/~fermin/corpusCine.zip"} class Muchocine(datasets.GeneratorBasedBuilder): VERSION = datasets.Version("1.1.1") def _info(self): features = datasets.Features( { "review_body": datasets.Value("string"), "review_summary": datasets.Value("string"), "star_rating": datasets.Value("int32"), } ) return datasets.DatasetInfo( description=_DESCRIPTION, features=features, supervised_keys=None, homepage="http://www.lsi.us.es/~fermin/index.php/Datasets", license=_LICENSE, citation=_CITATION, ) def _split_generators(self, dl_manager): my_urls = _URLs[self.config.name] data_dir = dl_manager.download_and_extract(my_urls) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "filepaths": sorted(glob.glob(os.path.join(data_dir, "corpusCriticasCine", "*.xml"))), "split": "train", }, ), ] def _generate_examples(self, filepaths, split): for filepath in filepaths: with open(filepath, encoding="latin-1") as f: id = re.search(r"\d+\.xml", filepath)[0][:-4] txt = f.read() txt = txt.replace("&ldquo;", '"').replace("&rdquo;", '"').replace("&hellip;", "") txt = txt.replace("&lsquo;", '"').replace("&rsquo;", '"').replace("&prime;", "") txt = txt.replace("&agrave;", "à").replace("&ndash;", "-").replace("&egrave;", "è") txt = txt.replace("&ouml;", "ö").replace("&ccedil;", "ç").replace("&", "and") try: doc = parseString(txt) except Exception as e: # skip 6 malformed xml files, for example unescaped < and > _ = e continue btxt = "" review_bod = doc.getElementsByTagName("body") if len(review_bod) > 0: for node in review_bod[0].childNodes: if node.nodeType == node.TEXT_NODE: btxt += node.data + " " rtxt = "" review_summ = doc.getElementsByTagName("summary") if len(review_summ) > 0: for node in review_summ[0].childNodes: if node.nodeType == node.TEXT_NODE: rtxt += node.data + " " yield id, { "review_body": btxt, "review_summary": rtxt, "star_rating": int(doc.documentElement.attributes["rank"].value), }
1,917
322
#!/ usr/bin/env # coding=utf-8 """ author: b5mali4 Copyright (c) 2018 >>> python3 hunter_celery.py -A hunter_celery worker -l info -c 1 """ import os import logging from celery import Celery from common import log from common.logo import logo from common.logo import celery_logo from common.logo import example_data from common.path import HUNTER_PATH from taskschedule.task_schedule import scan os.chdir("{}config".format(HUNTER_PATH)) celery = Celery() celery.config_from_object('celery_config') # logger = log.getLogger("celery") logger = log.get_default_logger() @celery.task def scan_celery(package, task_id, create_user, status): """ celey 调度模式扫描 注意,scan_celery函数只有在celey开启的时候才会 :param package: :param task_id: :param create_user: :param status: :return: """ logger.setLevel(logging.INFO) logger.info(logo) scan(package=package, task_id=task_id, create_user=create_user, status=status) @celery.task def system_notice_celery(message): """ 运行在多台服务器下的消费者接收来自系统的消息,常见的有新增插件,关闭插件,删除插件 :return: """ print(message) def init(): """ 启动的时候初始化,主要是新建一些日志目录之类的 :return: """ logger.propagate = False logger.setLevel(logging.DEBUG) logger.info(celery_logo) if __name__ == "__main__": init() celery.start()
681
1,444
package mage.abilities.condition; import mage.abilities.Ability; import mage.game.Game; /** * * @author LevelX2 */ public class FixedCondition implements Condition{ protected boolean conditionMet; public FixedCondition(boolean conditionMet) { this.conditionMet = conditionMet; } @Override public boolean apply(Game game, Ability source) { return conditionMet; } }
134
344
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_processing/vad/pole_zero_filter.h" #include <string.h> #include <algorithm> namespace webrtc { PoleZeroFilter* PoleZeroFilter::Create(const float* numerator_coefficients, size_t order_numerator, const float* denominator_coefficients, size_t order_denominator) { if (order_numerator > kMaxFilterOrder || order_denominator > kMaxFilterOrder || denominator_coefficients[0] == 0 || numerator_coefficients == NULL || denominator_coefficients == NULL) return NULL; return new PoleZeroFilter(numerator_coefficients, order_numerator, denominator_coefficients, order_denominator); } PoleZeroFilter::PoleZeroFilter(const float* numerator_coefficients, size_t order_numerator, const float* denominator_coefficients, size_t order_denominator) : past_input_(), past_output_(), numerator_coefficients_(), denominator_coefficients_(), order_numerator_(order_numerator), order_denominator_(order_denominator), highest_order_(std::max(order_denominator, order_numerator)) { memcpy(numerator_coefficients_, numerator_coefficients, sizeof(numerator_coefficients_[0]) * (order_numerator_ + 1)); memcpy(denominator_coefficients_, denominator_coefficients, sizeof(denominator_coefficients_[0]) * (order_denominator_ + 1)); if (denominator_coefficients_[0] != 1) { for (size_t n = 0; n <= order_numerator_; n++) numerator_coefficients_[n] /= denominator_coefficients_[0]; for (size_t n = 0; n <= order_denominator_; n++) denominator_coefficients_[n] /= denominator_coefficients_[0]; } } template <typename T> static float FilterArPast(const T* past, size_t order, const float* coefficients) { float sum = 0.0f; size_t past_index = order - 1; for (size_t k = 1; k <= order; k++, past_index--) sum += coefficients[k] * past[past_index]; return sum; } int PoleZeroFilter::Filter(const int16_t* in, size_t num_input_samples, float* output) { if (in == NULL || output == NULL) return -1; // This is the typical case, just a memcpy. const size_t k = std::min(num_input_samples, highest_order_); size_t n; for (n = 0; n < k; n++) { output[n] = in[n] * numerator_coefficients_[0]; output[n] += FilterArPast(&past_input_[n], order_numerator_, numerator_coefficients_); output[n] -= FilterArPast(&past_output_[n], order_denominator_, denominator_coefficients_); past_input_[n + order_numerator_] = in[n]; past_output_[n + order_denominator_] = output[n]; } if (highest_order_ < num_input_samples) { for (size_t m = 0; n < num_input_samples; n++, m++) { output[n] = in[n] * numerator_coefficients_[0]; output[n] += FilterArPast(&in[m], order_numerator_, numerator_coefficients_); output[n] -= FilterArPast(&output[m], order_denominator_, denominator_coefficients_); } // Record into the past signal. memcpy(past_input_, &in[num_input_samples - order_numerator_], sizeof(in[0]) * order_numerator_); memcpy(past_output_, &output[num_input_samples - order_denominator_], sizeof(output[0]) * order_denominator_); } else { // Odd case that the length of the input is shorter that filter order. memmove(past_input_, &past_input_[num_input_samples], order_numerator_ * sizeof(past_input_[0])); memmove(past_output_, &past_output_[num_input_samples], order_denominator_ * sizeof(past_output_[0])); } return 0; } } // namespace webrtc
1,910
1,144
#ifndef RKD_LOG_H #define RKD_LOG_H #include "RKLogServer.hpp" #include "RKLog.h" #include <stdarg.h> #include <vector> #define LOG_SIZE 3968 //1024*4-128 class RKLogServer; class RKDLog { public: static const int VERBOSE = 1; static const int DEBUG = 2; static const int INFO = 3; static const int WARN = 4; static const int ERROR = 5; static const int DEFAULT = RKDLog::VERBOSE; public: static int mLevel; static int mOutputFd; static size_t log(int level, const char *file, int line, const char *logtag, std::vector<char *> &args); static size_t log(int level, const char *file, int line, const char *logtag, const char *format, va_list args); static size_t log(int level, const char *file, int line, const char *logtag, const char *format, ...) { return LOG_VAR_ARGS_TAGS(level); } ~RKDLog(); private: static std::mutex mMutex; static char mBuffer[LOG_SIZE]; static int mLogPort; static RKLogServer *mLogServer; static struct LogHeaderSegs { size_t tsStart; size_t tsEnd; size_t fileStart; size_t fileEnd; size_t lineStart; size_t lineEnd; size_t totalLen; } mHeaderSegs; static size_t formatHeader(int level, const char *file, int line, const char *logtag); static size_t outPut(int level, size_t len, const char *logtag); static void logToServer(const char *buf, size_t len); }; #endif // RKD_LOG_H
608
647
/* * Copyright 2015 the original author or authors. * * 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.atomix.copycat.server.protocol; import io.atomix.copycat.protocol.Response; /** * Server leave configuration change response. * <p> * Leave responses are sent in response to a request to add a server to the cluster configuration. If a * configuration change is failed due to a conflict, the response status will be * {@link Response.Status#ERROR} but the response {@link #error()} will * be {@code null}. * * @author <a href="http://github.com/kuujo"><NAME></a> */ public class LeaveResponse extends ConfigurationResponse { /** * Returns a new leave response builder. * * @return A new leave response builder. */ public static Builder builder() { return new Builder(new LeaveResponse()); } /** * Returns an leave response builder for an existing response. * * @param response The response to build. * @return The leave response builder. */ public static Builder builder(LeaveResponse response) { return new Builder(response); } /** * Leave response builder. */ public static class Builder extends ConfigurationResponse.Builder<Builder, LeaveResponse> { protected Builder(LeaveResponse response) { super(response); } } }
498
773
// Copyright 2019 JD.com Inc. JD AI #ifndef BNN_ONNXCONVERTER_H #define BNN_ONNXCONVERTER_H #include <set> #include "optional.h" #include <common/Shaper.h> #include <common/StrKeyMap.h> #include <common/dab_generated.h> #include <common/helper.h> #include <glog/logging.h> #include <onnx/onnx_pb.h> namespace bnn { class OnnxConverter { private: Shaper shaper_; template <typename T> struct Tensor { std::vector<T> data; Shaper::Shape shape; bool align_hwc_to_128 = false; Tensor() = default; Tensor(const std::vector<T> &data, const Shaper::Shape &shape, const bool align_hwc_to_128): data(data), shape(shape), align_hwc_to_128(align_hwc_to_128) {} inline T get(const std::vector<Shaper::len_t> &x) { auto step = get_shape_for_accessing_element(); for (int i = shape.size() - 2; i >= 0; i--) { step[i] *= step[i + 1]; } step.push_back(1); step.erase(step.begin()); Shaper::len_t idx = 0; FORZ(i, x.size()) { idx += x[i] * step[i]; } // PNT(x, size, get_shape_for_accessing_element(), idx, // Shaper::total(size)); BNN_ASSERT(idx < Shaper::total(get_shape_for_accessing_element()), ""); return data[idx]; } Shaper::Shape get_shape_for_accessing_element(); }; using FTensor = Tensor<float>; using BTensor = Tensor<bin_t>; ONNX_NAMESPACE::ModelProto model_proto_; std::map<std::string, std::string> name_map_; std::string m(const std::string &str); flatbuffers::FlatBufferBuilder builder_; std::vector<std::string> operands_; StrKeyMap<FTensor> bnn_tensors_; StrKeyMap<FTensor> onnx_float_tensors_; std::vector<flatbuffers::Offset<flatbnn::Layer>> layers_; std::vector<flatbuffers::Offset<flatbnn::Tensor>> tensors_; BTensor bitpack(FTensor ftensor); std::vector<BTensor> split(BTensor input, int num); void AddBinConv(const std::string &input_name, const std::vector<int> &strides, const std::vector<int> &pads, const std::vector<int> &dilations, int group, const std::string &weight_name, const std::string &output_name, BTensor bin_weight); void AddFloatConv(const std::string &input_name, const std::vector<int> &strides, const std::vector<int> &pads, const std::vector<int> &dilations, int group, const std::string &weight_name, const nonstd::optional<std::string> &bias_name, const std::string &output_name, FTensor float_weight); void AddConv(const std::string &input_name, const std::vector<int> &strides, const std::vector<int> &pads, const std::vector<int> &dilations, int group, const std::string &ori_weight_name, const nonstd::optional<std::string> &bias_name, const std::string &output_name, const bool binary); void CalculateCoeff(const ONNX_NAMESPACE::NodeProto &node, const std::string &coeff_a_name, const std::string &coeff_b_name); void GetBinTensors(); /** * onnx: [filter_out_channel, filter_in_channel / group, height, width] * nnapi: [1, height, width, depth_out] */ template <typename T> Tensor<T> OnnxToNnapiDw(const Tensor<T> &src) { Tensor<T> dest; dest.data.resize(Product(src.shape)); // t for total auto out_t = src.shape[0], in_t = src.shape[1], h_t = src.shape[2], w_t = src.shape[3]; CHECK_EQ(in_t, 1u); for (uint32_t out = 0; out < out_t; out++) { for (uint32_t in = 0; in < in_t; in++) { for (uint32_t h = 0; h < h_t; h++) { for (uint32_t w = 0; w < w_t; w++) { auto onnx_idx = out * in_t * h_t * w_t + in * h_t * w_t + h * w_t + w; auto nnapi_idx = h * w_t * out_t + w * out_t + out; dest.data[nnapi_idx] = src.data[onnx_idx]; } } } } dest.shape = {in_t, h_t, w_t, out_t}; return dest; } /** * onnx: [filter_out_channel, filter_in_channel, height, width] * bnn: [depth_out, height, width, depth_in] */ template <typename T> Tensor<T> OnnxToBnn(const Tensor<T> &src) { Tensor<T> dest; dest.data.resize(Product(src.shape)); // t for total auto out_t = src.shape[0], in_t = src.shape[1], h_t = src.shape[2], w_t = src.shape[3]; for (uint32_t out = 0; out < out_t; out++) { for (uint32_t in = 0; in < in_t; in++) { for (uint32_t h = 0; h < h_t; h++) { for (uint32_t w = 0; w < w_t; w++) { auto onnx_idx = out * in_t * h_t * w_t + in * h_t * w_t + h * w_t + w; auto nnapi_idx = out * h_t * w_t * in_t + h * w_t * in_t + w * in_t + in; dest.data[nnapi_idx] = src.data[onnx_idx]; } } } } dest.shape = {out_t, h_t, w_t, in_t}; return dest; } public: enum class Level { kStrict, kModerate, kAggressive, }; std::vector<std::string> Convert(const ONNX_NAMESPACE::ModelProto &model, const std::string &filepath, const Level level, const std::vector<std::string> &expected_binary_conv_outputs); }; template <> inline Shaper::Shape OnnxConverter::Tensor<float>::get_shape_for_accessing_element() { return shape; } template <> inline Shaper::Shape OnnxConverter::Tensor<bin_t>::get_shape_for_accessing_element() { BNN_ASSERT(shape.size() == 4, ""); auto ret = shape; ret[3] /= 64; return ret; } } // namespace bnn #endif /* BNN_ONNXCONVERTER_H */
3,361
1,383
<reponame>Benatti1991/chrono // ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Author: <NAME> // ============================================================================= // // The global reference frame has Z up. // All units SI. // ============================================================================= #include <cstdio> #include <cmath> #include <vector> #include "chrono/physics/ChSystemSMC.h" #ifdef CHRONO_COLLISION #include "chrono/collision/ChCollisionSystemChrono.h" #endif #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/driver/ChPathFollowerDriver.h" #include "chrono_vehicle/terrain/SCMDeformableTerrain.h" #include "chrono_vehicle/utils/ChVehiclePath.h" #include "chrono_models/vehicle/hmmwv/HMMWV.h" #include "chrono_thirdparty/cxxopts/ChCLI.h" using namespace chrono; using namespace chrono::collision; using namespace chrono::vehicle; using namespace chrono::vehicle::hmmwv; #ifdef CHRONO_IRRLICHT #include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleIrrApp.h" using namespace chrono::irrlicht; #endif using std::cout; using std::endl; // ============================================================================= double terrainLength = 50; // size in X direction double terrainWidth = 50; // size in Y direction double delta = 0.05; // SCM grid spacing double target_speed = 10; // Simulation run time double end_time = 10; // Simulation step size double step_size = 2e-3; // Use Chrono multicore collision system (false: Bullet) bool chrono_collsys = false; // Number of SCM and collision threads int nthreads = 4; // Moving patches under each wheel bool wheel_patches = false; // Better conserve mass by displacing soil to the sides of a rut const bool bulldozing = false; // Run-time visualization? bool visualize = false; // ============================================================================= // Forward declares for straight forward helper functions void AddCommandLineOptions(ChCLI& cli); void PrintStepStatistics(std::ostream& os, const ChSystem& sys); // ============================================================================= int main(int argc, char* argv[]) { GetLog() << "Copyright (c) 2021 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n"; // ------------------------------------------------ // CLI SETUP - Get parameters from the command line // ------------------------------------------------ ChCLI cli(argv[0]); AddCommandLineOptions(cli); if (!cli.Parse(argc, argv, true)) return 0; step_size = cli.GetAsType<double>("step_size"); end_time = cli.GetAsType<double>("end_time"); nthreads = cli.GetAsType<int>("nthreads"); wheel_patches = cli.GetAsType<bool>("wheel_patches"); chrono_collsys = cli.GetAsType<bool>("csys"); #ifndef CHRONO_COLLISION if (chrono_collsys) cout << "Chrono was not built with Thrust support. Fall back to Bullet collision system." << endl; chrono_collsys = false; #endif visualize = cli.GetAsType<bool>("vis"); #ifndef CHRONO_IRRLICHT if (visualize) cout << "Chrono::Irrlicht not available. Disabling visualization." << endl; visualize = false; #endif std::cout << "Collision system: " << (chrono_collsys ? "Chrono" : "Bullet") << std::endl; std::cout << "Num SCM threads: " << nthreads << std::endl; // ------------------------ // Create the Chrono system // ------------------------ ChSystemSMC sys; sys.Set_G_acc(ChVector<>(0, 0, -9.81)); sys.SetNumThreads(nthreads, nthreads, 1); if (chrono_collsys) { #ifdef CHRONO_COLLISION auto collsys = chrono_types::make_shared<collision::ChCollisionSystemChrono>(); collsys->SetBroadphaseGridResolution(ChVector<int>(2, 2, 1)); sys.SetCollisionSystem(collsys); #endif } // -------------------- // Create HMMWV vehicle // -------------------- ChVector<> init_loc(0, 2, 0.5); ChQuaternion<> init_rot = Q_from_AngZ(0); HMMWV_Full hmmwv(&sys); hmmwv.SetChassisFixed(false); hmmwv.SetInitPosition(ChCoordsys<>(init_loc, init_rot)); hmmwv.SetPowertrainType(PowertrainModelType::SHAFTS); hmmwv.SetDriveType(DrivelineTypeWV::AWD); hmmwv.SetTireType(TireModelType::RIGID); hmmwv.SetTireStepSize(step_size); hmmwv.Initialize(); if (visualize) { hmmwv.SetChassisVisualizationType(VisualizationType::NONE); hmmwv.SetSuspensionVisualizationType(VisualizationType::MESH); hmmwv.SetSteeringVisualizationType(VisualizationType::NONE); hmmwv.SetWheelVisualizationType(VisualizationType::MESH); hmmwv.SetTireVisualizationType(VisualizationType::MESH); } else { hmmwv.SetChassisVisualizationType(VisualizationType::NONE); hmmwv.SetSuspensionVisualizationType(VisualizationType::NONE); hmmwv.SetSteeringVisualizationType(VisualizationType::NONE); hmmwv.SetWheelVisualizationType(VisualizationType::NONE); hmmwv.SetTireVisualizationType(VisualizationType::NONE); } // ----------------------------------------------------------- // Set tire contact material, contact model, and visualization // ----------------------------------------------------------- auto wheel_material = chrono_types::make_shared<ChMaterialSurfaceSMC>(); wheel_material->SetFriction(0.8f); wheel_material->SetYoungModulus(1.0e6f); wheel_material->SetRestitution(0.1f); // -------------------- // Create driver system // -------------------- double pathLength = 1.5 * target_speed * end_time; auto path = StraightLinePath(init_loc, init_loc + ChVector<>(pathLength, 0, 0), 0); ChPathFollowerDriver driver(hmmwv.GetVehicle(), path, "Box path", target_speed); driver.Initialize(); // Reasonable defaults for the underlying PID driver.GetSpeedController().SetGains(0.4, 0, 0); driver.GetSteeringController().SetGains(0.4, 0.1, 0.2); driver.GetSteeringController().SetLookAheadDistance(2); // ------------------ // Create the terrain // ------------------ SCMDeformableTerrain terrain(&sys, visualize); terrain.SetSoilParameters(2e6, // Bekker Kphi 0, // Bekker Kc 1.1, // Bekker n exponent 0, // Mohr cohesive limit (Pa) 30, // Mohr friction limit (degrees) 0.01, // Janosi shear coefficient (m) 2e8, // Elastic stiffness (Pa/m), before plastic yield 3e4 // Damping (Pa s/m), proportional to negative vertical speed (optional) ); if (bulldozing) { terrain.EnableBulldozing(true); // inflate soil at the border of the rut terrain.SetBulldozingParameters(55, // angle of friction for erosion of displaced material at rut border 0.8, // displaced material vs downward pressed material. 5, // number of erosion refinements per timestep 10); // number of concentric vertex selections subject to erosion } if (wheel_patches) { // Optionally, enable moving patch feature (multiple patches around each wheel) for (auto& axle : hmmwv.GetVehicle().GetAxles()) { terrain.AddMovingPatch(axle->m_wheels[0]->GetSpindle(), ChVector<>(0, 0, 0), ChVector<>(1, 0.5, 1)); terrain.AddMovingPatch(axle->m_wheels[1]->GetSpindle(), ChVector<>(0, 0, 0), ChVector<>(1, 0.5, 1)); } } else { // Optionally, enable moving patch feature (single patch around vehicle chassis) terrain.AddMovingPatch(hmmwv.GetChassisBody(), ChVector<>(0, 0, 0), ChVector<>(5, 3, 1)); } terrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_SINKAGE, 0, 0.1); terrain.Initialize(terrainLength, terrainWidth, delta); #ifdef CHRONO_IRRLICHT // Create the vehicle Irrlicht application std::shared_ptr<ChWheeledVehicleIrrApp> app; if (visualize) { app = chrono_types::make_shared<ChWheeledVehicleIrrApp>(&hmmwv.GetVehicle(), L"Chrono SCM test"); app->SetSkyBox(); app->AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130); app->SetChaseCamera(ChVector<>(0.0, 0.0, 1.75), 6.0, 0.5); app->SetTimestep(step_size); app->AssetBindAll(); app->AssetUpdateAll(); } // Time interval between two render frames (1/FPS) double render_step_size = 1.0 / 100; // Number of simulation steps between two render frames int render_steps = (int)std::ceil(render_step_size / step_size); #endif // --------------- // Simulation loop // --------------- bool stats_done = false; // Solver settings sys.SetSolverMaxIterations(50); // Initialize simulation frame counter int step_number = 0; double chrono_step = 0; double chrono_setup = 0; double raytest = 0; double raycast = 0; ChTimer<> timer; timer.start(); while (true) { double time = sys.GetChTime(); if (time > end_time) { if (!stats_done) { timer.stop(); double rtf = timer() / end_time; int nsteps = (int)(end_time / step_size); std::string fname = "stats_" + std::to_string(nthreads) + ".out"; std::ofstream ofile(fname.c_str(), std::ios_base::app); ofile << raytest / nsteps << " " << raycast / nsteps << " " << rtf << endl; ofile.close(); cout << "\nOUTPUT FILE: " << fname << endl; cout << endl; cout << "stop timer at (s): " << end_time << endl; cout << "elapsed time (s): " << timer() << endl; cout << "chrono step (s): " << chrono_step << endl; cout << "chrono setup (s): " << chrono_setup << endl; cout << "raytesting (s): " << raytest / 1e3 << endl; cout << "raycasting (s): " << raycast / 1e3 << endl; cout << "RTF: " << rtf << endl; cout << "\nSCM stats for last step:" << endl; terrain.PrintStepStatistics(cout); cout << "\nChrono stats for last step:" << endl; PrintStepStatistics(cout, sys); stats_done = true; } if (!visualize) break; } #ifdef CHRONO_IRRLICHT if (app && !app->GetDevice()->run()) // Irrlicht visualization has stopped break; // Render scene if (app && step_number % render_steps == 0) { app->BeginScene(); app->DrawAll(); app->EndScene(); } #endif // Driver inputs ChDriver::Inputs driver_inputs = driver.GetInputs(); // Update modules driver.Synchronize(time); terrain.Synchronize(time); hmmwv.Synchronize(time, driver_inputs, terrain); #ifdef CHRONO_IRRLICHT if (app) app->Synchronize("", driver_inputs); #endif // Advance dynamics driver.Advance(step_size); terrain.Advance(step_size); hmmwv.Advance(step_size); sys.DoStepDynamics(step_size); #ifdef CHRONO_IRRLICHT if (app) app->Advance(step_size); #endif chrono_step += sys.GetTimerStep(); chrono_setup += sys.GetTimerSetup(); raytest += terrain.GetTimerRayTesting(); raycast += terrain.GetTimerRayCasting(); // Increment frame number step_number++; } return 0; } void AddCommandLineOptions(ChCLI& cli) { cli.AddOption<double>("Test", "s,step_size", "Step size", std::to_string(step_size)); cli.AddOption<double>("Test", "e,end_time", "End time", std::to_string(end_time)); cli.AddOption<int>("Test", "n,nthreads", "Number threads", std::to_string(nthreads)); cli.AddOption<bool>("Test", "c,csys", "Use Chrono multicore collision (false: Bullet)", std ::to_string(chrono_collsys)); cli.AddOption<bool>("Test", "w,wheel_patches", "Use patches under each wheel", std::to_string(wheel_patches)); cli.AddOption<bool>("Test", "v,vis", "Enable run-time visualization", std::to_string(visualize)); } void PrintStepStatistics(std::ostream& os, const ChSystem& sys) { os << " Step (ms): " << 1e3 * sys.GetTimerStep() << std::endl; os << " Advance: " << 1e3 * sys.GetTimerAdvance() << std::endl; os << " LSsolve: " << 1e3 * sys.GetTimerLSsolve() << std::endl; os << " LSsetup: " << 1e3 * sys.GetTimerLSsetup() << std::endl; os << " Jacobian: " << 1e3 * sys.GetTimerJacobian() << std::endl; os << " Collision: " << 1e3 * sys.GetTimerCollision() << std::endl; os << " Setup: " << 1e3 * sys.GetTimerSetup() << std::endl; os << " Update: " << 1e3 * sys.GetTimerUpdate() << std::endl; }
5,548
4,538
/* * Copyright (C) 2020-2023 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <ulog/ulog.h> #include "uvoice_init.h" #include "uvoice_types.h" #include "uvoice_event.h" #include "uvoice_player.h" #include "uvoice_recorder.h" #include "ulog/ulog.h" #include "aos/kernel.h" #include "uvoice_os.h" #include "player.h" #define TAG "player" static aos_task_t play_task; static uvoice_player_t *uvocplayer; static char text_source[256]; static player_cb_t play_done_cb = NULL; static player_mp3_e g_file = PLAYER_MP3_MAX; extern int audio_install_codec_driver(); static int get_format_from_name(char *name, media_format_t *format) { if (!name || !format) { LOGE(TAG, "arg null !\n"); return -1; } if (strstr(name, ".mp3") || strstr(name, ".MP3")) *format = MEDIA_FMT_MP3; else if (strstr(name, ".wav") || strstr(name, ".WAV")) *format = MEDIA_FMT_WAV; else if (strstr(name, ".aac") || strstr(name, ".AAC")) *format = MEDIA_FMT_AAC; else if (strstr(name, ".m4a") || strstr(name, ".M4A")) *format = MEDIA_FMT_M4A; else if (strstr(name, ".pcm") || strstr(name, ".PCM")) *format = MEDIA_FMT_PCM; else if (strstr(name, ".spx") || strstr(name, ".SPX")) *format = MEDIA_FMT_SPX; else if (strstr(name, ".ogg") || strstr(name, ".OGG")) *format = MEDIA_FMT_OGG; else if (strstr(name, ".amrwb") || strstr(name, ".AMRWB")) *format = MEDIA_FMT_AMRWB; else if (strstr(name, ".amr") || strstr(name, ".AMR")) *format = MEDIA_FMT_AMR; else if (strstr(name, ".opus") || strstr(name, ".OPUS")) *format = MEDIA_FMT_OPS; else if (strstr(name, ".flac") || strstr(name, ".FLAC")) *format = MEDIA_FMT_FLAC; return 0; } static void *play_music(void *arg) { media_format_t format = MEDIA_FMT_UNKNOWN; get_format_from_name(text_source, &format); if (uvocplayer->set_source(text_source)) { LOGE(TAG, "set source failed !\n"); return NULL; } if (uvocplayer->start()) { LOGE(TAG, "start failed !\n"); uvocplayer->clr_source(); } // uvocplayer->wait_complete(); if (play_done_cb) play_done_cb(g_file); return NULL; } int32_t player_play(player_mp3_e file) { int32_t random; random = rand() % 240; LOG("random: %d\n", random); memset(text_source, 0, sizeof(text_source)); if (file == PLAYER_MP3_WELCOME) { strcpy(text_source, "fs:/data/mp3/welcome.mp3"); } else if (file == PLAYER_MP3_WAKEUP) { // if (random < 100) { // strcpy(text_source, "fs:/data/mp3/haas_intro.mp3"); // } else if (random > 0 && random < 150) { strcpy(text_source, "fs:/data/mp3/zhurenyoushenmkeyibangnin.mp3"); } else if (random > 150 && random < 200) { strcpy(text_source, "fs:/data/mp3/zhurenwozai.mp3"); } else { strcpy(text_source, "fs:/data/mp3/eiwozai.mp3"); } g_file = PLAYER_MP3_WAKEUP; } else if (file == PLAYER_MP3_LIGHT_ON) { strcpy(text_source, "fs:/data/mp3/haodeyiweinindakai.mp3"); g_file = PLAYER_MP3_LIGHT_ON; } else if (file == PLAYER_MP3_LIGHT_OFF) { strcpy(text_source, "fs:/data/mp3/haodeyiweininguanbi.mp3"); g_file = PLAYER_MP3_LIGHT_OFF; } #if 1 /*set player enter idle state after a long time*/ uvocplayer->set_standby(2147483646); play_music(NULL); uvocplayer->wait_complete(); aos_msleep(500); #else aos_task_new_ext(&play_task, "play music task", play_music, NULL, 8192, 0); #endif return 0; } int32_t player_stop(void) { player_state_t state; /*stop and clear current playing*/ uvocplayer->set_fade(40, 40); uvocplayer->stop_async(); uvocplayer->clr_source(); } int32_t player_wait_complete(void) { int32_t ret; ret = uvocplayer->wait_complete(); if (ret < 0) aos_msleep(1000); aos_msleep(500); } int32_t player_init(player_cb_t cb) { int32_t ret; /*Init uvoice to play mp3*/ ret = uvoice_init(); if (ret < 0) { LOGE(TAG, "uvoice_init failed !\n"); return -1; } /*create uvoice player*/ uvocplayer = uvoice_player_create(); if (!uvocplayer) { LOGE(TAG, "create media player failed !\n"); return -1; } /*set eq*/ uvocplayer->eq_enable(0); /*set play volume*/ uvocplayer->set_volume(10); play_done_cb = cb; return 0; }
2,175
3,680
<reponame>DougRogers-DigitalFish/USD<filename>pxr/base/gf/wrapHalf.cpp // // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/pxr.h" #include "pxr/base/gf/half.h" #include <boost/python/def.hpp> #include <boost/python/handle.hpp> #include <boost/python/to_python_converter.hpp> #include <boost/python/converter/from_python.hpp> using namespace boost::python; PXR_NAMESPACE_USING_DIRECTIVE namespace { // Registers to and from python conversions with boost.python for half. struct HalfPythonConversions { static void Register() { // to-python to_python_converter<GfHalf, HalfPythonConversions>(); // from-python converter::registry::push_back(&_convertible, &_construct, boost::python::type_id<GfHalf>()); } // to-python static PyObject *convert(GfHalf h) { return PyFloat_FromDouble(h); } private: // from-python static void *_convertible(PyObject *obj_ptr) { // Must be number-like. if (!PyNumber_Check(obj_ptr)) return NULL; // Try to convert to python float: if we can, then we can make a GfHalf. if (PyObject *flt = PyNumber_Float(obj_ptr)) return flt; // Otherwise we cannot produce a GfHalf. Clear any python exception // raised above when attempting to create the float. if (PyErr_Occurred()) PyErr_Clear(); return NULL; } static void _construct(PyObject *obj_ptr, converter:: rvalue_from_python_stage1_data *data) { // Pull out the python float we returned from _convertible(). PyObject *flt = (PyObject *)data->convertible; // Turn the python float into a C++ double, make a GfHalf from that // double, and store it where boost.python expects it. void *storage = ((converter::rvalue_from_python_storage<GfHalf>*)data)->storage.bytes; new (storage) GfHalf(static_cast<float>(PyFloat_AsDouble(flt))); data->convertible = storage; // Drop our reference to the python float we created. Py_DECREF(flt); } }; // Simple test function that takes and returns a GfHalf. static GfHalf _HalfRoundTrip(GfHalf in) { return in; } } // anonymous namespace void wrapHalf() { HalfPythonConversions::Register(); boost::python::def("_HalfRoundTrip", _HalfRoundTrip); }
1,246
4,205
<filename>reactor-core/src/main/java/reactor/core/CorePublisher.java /* * Copyright (c) 2016-2021 VMware Inc. or its affiliates, 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 * * https://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 reactor.core; import java.util.function.Function; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import reactor.core.publisher.Hooks; import reactor.util.context.Context; /** * A {@link CoreSubscriber} aware publisher. * * * @param <T> the {@link CoreSubscriber} data type * * @since 3.3.0 */ public interface CorePublisher<T> extends Publisher<T> { /** * An internal {@link Publisher#subscribe(Subscriber)} that will bypass * {@link Hooks#onLastOperator(Function)} pointcut. * <p> * In addition to behave as expected by {@link Publisher#subscribe(Subscriber)} * in a controlled manner, it supports direct subscribe-time {@link Context} passing. * * @param subscriber the {@link Subscriber} interested into the published sequence * @see Publisher#subscribe(Subscriber) */ void subscribe(CoreSubscriber<? super T> subscriber); }
470
2,118
<reponame>gidabite/libcds<filename>cds/intrusive/free_list_tagged.h // Copyright (c) 2006-2018 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef CDSLIB_INTRUSIVE_FREE_LIST_TAGGED_H #define CDSLIB_INTRUSIVE_FREE_LIST_TAGGED_H #include <cds/algo/atomic.h> namespace cds { namespace intrusive { /// Lock-free free list based on tagged pointers (required double-width CAS) /** @ingroup cds_intrusive_freelist This variant of \p FreeList is intended for processor architectures that support double-width CAS. It uses <a href="https://en.wikipedia.org/wiki/Tagged_pointer">tagged pointer</a> technique to solve ABA problem. \b How to use \code #include <cds/intrusive/free_list_tagged.h> // Your struct should be derived from TaggedFreeList::node struct Foo: public cds::intrusive::TaggedFreeList::node { // Foo fields }; // Simplified Foo allocator class FooAllocator { public: // free-list clear() must be explicitly called before destroying the free-list object ~FooAllocator() { m_FreeList.clear( []( freelist_node * p ) { delete static_cast<Foo *>( p ); }); } Foo * alloc() { freelist_node * p = m_FreeList.get(); if ( p ) return static_cast<Foo *>( p ); return new Foo; }; void dealloc( Foo * p ) { m_FreeList.put( static_cast<freelist_node *>( p )); }; private: typedef cds::intrusive::TaggedFreeList::node freelist_node; cds::intrusive::TaggedFreeList m_FreeList; }; \endcode */ class TaggedFreeList { public: struct node { //@cond atomics::atomic<node *> m_freeListNext; node() { m_freeListNext.store( nullptr, atomics::memory_order_release ); } //@endcond }; private: //@cond struct tagged_ptr { node * ptr; uintptr_t tag; tagged_ptr() : ptr( nullptr ) , tag( 0 ) {} tagged_ptr( node* p ) : ptr( p ) , tag( 0 ) {} }; static_assert(sizeof( tagged_ptr ) == sizeof( void * ) * 2, "sizeof( tagged_ptr ) violation"); //@endcond public: /// Creates empty free-list TaggedFreeList() : m_Head( tagged_ptr()) { // Your platform must support double-width CAS assert( m_Head.is_lock_free()); } /// Destroys the free list. Free-list must be empty. /** @warning dtor does not free elements of the list. To free elements you should manually call \p clear() with an appropriate disposer. */ ~TaggedFreeList() { assert( empty()); } /// Puts \p pNode to the free list void put( node * pNode ) { assert( m_Head.is_lock_free()); tagged_ptr currentHead = m_Head.load( atomics::memory_order_relaxed ); tagged_ptr newHead = { pNode }; do { newHead.tag = currentHead.tag + 1; pNode->m_freeListNext.store( currentHead.ptr, atomics::memory_order_relaxed ); CDS_TSAN_ANNOTATE_HAPPENS_BEFORE( &pNode->m_freeListNext ); } while ( cds_unlikely( !m_Head.compare_exchange_weak( currentHead, newHead, atomics::memory_order_release, atomics::memory_order_acquire ))); } /// Gets a node from the free list. If the list is empty, returns \p nullptr node * get() { tagged_ptr currentHead = m_Head.load( atomics::memory_order_acquire ); tagged_ptr newHead; while ( currentHead.ptr != nullptr ) { CDS_TSAN_ANNOTATE_HAPPENS_AFTER( &currentHead.ptr->m_freeListNext ); newHead.ptr = currentHead.ptr->m_freeListNext.load( atomics::memory_order_relaxed ); newHead.tag = currentHead.tag + 1; if ( cds_likely( m_Head.compare_exchange_weak( currentHead, newHead, atomics::memory_order_release, atomics::memory_order_acquire ))) break; } return currentHead.ptr; } /// Checks whether the free list is empty bool empty() const { return m_Head.load( atomics::memory_order_relaxed ).ptr == nullptr; } /// Clears the free list (not atomic) /** For each element \p disp disposer is called to free memory. The \p Disposer interface: \code struct disposer { void operator()( FreeList::node * node ); }; \endcode This method must be explicitly called before the free list destructor. */ template <typename Disposer> void clear( Disposer disp ) { node * head = m_Head.load( atomics::memory_order_relaxed ).ptr; m_Head.store( { nullptr }, atomics::memory_order_relaxed ); while ( head ) { node * next = head->m_freeListNext.load( atomics::memory_order_relaxed ); disp( head ); head = next; } } private: //@cond atomics::atomic<tagged_ptr> m_Head; //@endcond }; }} // namespace cds::intrusive #endif // CDSLIB_INTRUSIVE_FREE_LIST_TAGGED_H
2,885
2,753
/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2014 <NAME> * 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. * * 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. */ #include <gtest/gtest.h> #include <shogun/lib/SGVector.h> #include <shogun/features/DenseFeatures.h> #include <shogun/distributions/KernelDensity.h> #include <shogun/mathematics/RandomNamespace.h> #include <cmath> #include <random> using namespace shogun; TEST(KernelDensity,gaussian_kernel_with_euclidean_distance) { SGMatrix<float64_t> data(2,4); data(0,0)=0; data(0,1)=0; data(0,2)=2; data(0,3)=2; data(1,0)=0; data(1,1)=2; data(1,2)=0; data(1,3)=2; auto feats=std::make_shared<DenseFeatures<float64_t>>(data); auto k=std::make_shared<KernelDensity>(); k->train(feats); SGMatrix<float64_t> test(2,5); test(0,0)=1; test(1,0)=1; test(0,1)=0; test(1,1)=1; test(0,2)=2; test(1,2)=1; test(0,3)=1; test(1,3)=2; test(0,4)=1; test(1,4)=0; auto testfeats=std::make_shared<DenseFeatures<float64_t>>(test); SGVector<float64_t> res=k->get_log_density(testfeats); EXPECT_NEAR(res[0],-2.83787706,1e-8); EXPECT_NEAR(res[1],-2.90409623,1e-8); EXPECT_NEAR(res[2],-2.90409623,1e-8); EXPECT_NEAR(res[3],-2.90409623,1e-8); EXPECT_NEAR(res[4],-2.90409623,1e-8); } TEST(KernelDensity,gaussian_kernel_with_manhattan_distance) { SGMatrix<float64_t> data(2,4); data(0,0)=0; data(0,1)=0; data(0,2)=2; data(0,3)=2; data(1,0)=0; data(1,1)=2; data(1,2)=0; data(1,3)=2; auto feats=std::make_shared<DenseFeatures<float64_t>>(data); auto k=std::make_shared<KernelDensity>(1.0, K_GAUSSIAN, D_MANHATTAN); k->train(feats); SGMatrix<float64_t> test(2,5); test(0,0)=1; test(1,0)=1; test(0,1)=0; test(1,1)=1; test(0,2)=2; test(1,2)=1; test(0,3)=1; test(1,3)=2; test(0,4)=1; test(1,4)=0; auto testfeats=std::make_shared<DenseFeatures<float64_t>>(test); SGVector<float64_t> res=k->get_log_density(testfeats); EXPECT_NEAR(res[0],-3.83787706,1e-8); EXPECT_NEAR(res[1],-3.01287431,1e-8); EXPECT_NEAR(res[2],-3.01287431,1e-8); EXPECT_NEAR(res[3],-3.01287431,1e-8); EXPECT_NEAR(res[4],-3.01287431,1e-8); } TEST(KernelDensity,dual_tree) { SGMatrix<float64_t> data(2,4); data(0,0)=0; data(0,1)=0; data(0,2)=2; data(0,3)=2; data(1,0)=0; data(1,1)=2; data(1,2)=0; data(1,3)=2; auto feats=std::make_shared<DenseFeatures<float64_t>>(data); auto k=std::make_shared<KernelDensity>(1.0, K_GAUSSIAN, D_EUCLIDEAN, EM_BALLTREE_DUAL); k->train(feats); SGMatrix<float64_t> test(2,5); test(0,0)=1; test(1,0)=1; test(0,1)=0; test(1,1)=1; test(0,2)=2; test(1,2)=1; test(0,3)=1; test(1,3)=2; test(0,4)=1; test(1,4)=0; auto testfeats=std::make_shared<DenseFeatures<float64_t>>(test); SGVector<float64_t> res=k->get_log_density(testfeats); EXPECT_NEAR(res[0],-2.83787706,1e-8); EXPECT_NEAR(res[1],-2.90409623,1e-8); EXPECT_NEAR(res[2],-2.90409623,1e-8); EXPECT_NEAR(res[3],-2.90409623,1e-8); EXPECT_NEAR(res[4],-2.90409623,1e-8); } TEST(KernelDensity,dual_tree_single_tree_equivalence) { int32_t seed = 1; std::mt19937_64 prng(seed); SGMatrix<float64_t> data(5,100); random::fill_array(data, std::nextafter(0.0, 1.0), 1.0, prng); auto feats=std::make_shared<DenseFeatures<float64_t>>(data); SGMatrix<float64_t> test(5,20); random::fill_array(test, std::nextafter(0.0, 1.0), 1.0, prng); auto testfeats=std::make_shared<DenseFeatures<float64_t>>(test); auto k=std::make_shared<KernelDensity>(1.0, K_GAUSSIAN, D_EUCLIDEAN, EM_BALLTREE_DUAL,5); k->train(feats); SGVector<float64_t> res_dual=k->get_log_density(testfeats,2); k=std::make_shared<KernelDensity>(1.0, K_GAUSSIAN, D_EUCLIDEAN, EM_BALLTREE_SINGLE,5); k->train(feats); SGVector<float64_t> res_single=k->get_log_density(testfeats); for (int32_t i=0;i<res_dual.vlen;i++) EXPECT_NEAR(res_dual[i],res_single[i],1e-8); }
2,389
530
<filename>tests/functional/regressions/issue278/test_issue278_extend_input_object.py from typing import Any, Callable, Dict, Optional import pytest from tartiflette import Directive, Resolver, create_engine from tartiflette.types.exceptions.tartiflette import GraphQLSchemaError @pytest.fixture(scope="module") async def ttftt_engine(): schema_sdl = """ input anInput { a: String b: Float } type Query { test1(aParameter: anInput): String } input switchValuInput { c: Int } input anotherInput { g: Int } directive @switchValue(newValue: switchValuInput) on INPUT_OBJECT extend input anInput @switchValue(newValue: {c: 5}) { c: Int } extend input anotherInput @switchValue(newValue: switchValuInput) """ @Directive( name="switchValue", schema_name="test_issue_278_input_object_extend" ) class SwitchValue: async def on_post_input_coercion( self, directive_args: Dict[str, Any], next_directive: Callable, parent_node, value: Any, ctx: Optional[Any], ): value = await next_directive(parent_node, value, ctx) value.update(directive_args["newValue"]) return value @Resolver("Query.test1", schema_name="test_issue_278_input_object_extend") async def resolver_input_object_test_1(_pr, arguments, *_args, **_kwargs): return str(arguments) return await create_engine( schema_sdl, schema_name="test_issue_278_input_object_extend" ) @pytest.mark.asyncio @pytest.mark.parametrize( "query,expected", [ ( """ query { __type(name: "anInput") { name kind inputFields { name } } } """, { "data": { "__type": { "name": "anInput", "kind": "INPUT_OBJECT", "inputFields": [ {"name": "a"}, {"name": "b"}, {"name": "c"}, ], } } }, ), ( """ query { test1(aParameter: {a:"R", b:6.25, c:9}) } """, { "data": { "test1": "{'aParameter': {'a': 'R', 'b': 6.25, 'c': 5}}" } }, ), ], ) async def test_issue_278_input_object_extend(query, expected, ttftt_engine): assert await ttftt_engine.execute(query) == expected @pytest.mark.asyncio async def test_issue_278_extend_input_object_invalid_sdl(): with pytest.raises( GraphQLSchemaError, match=""" 0: Can't add < C > Directive to < bob > INPUT, cause it's already there. 1: Can't add Input Field < a > to Input Object < bob > cause it already exists 2: Can't add Input Field < b > to Input Object < bob > cause it already exists 3: Can't extend a non existing type < dontexists >. 4: Can't extend INPUT < aType > cause it's not an INPUT.""", ): await create_engine( sdl=""" directive @C on INPUT_OBJECT input bob @C { a: String b: Int } extend input bob @C { a: String b: Int } type aType { b: bob } type Query { a: bob } extend input dontexists @C extend input aType { d: Float } """, schema_name="test_issue_278_extend_input_object_invalid_sdl", )
2,225
1,928
# Copyright (c) Facebook, Inc. and its affiliates. # Mostly copy-pasted from # https://github.com/facebookresearch/detr/blob/master/models/transformer.py import copy from typing import Optional import torch import torch.nn.functional as F from torch import Tensor, nn class Transformer(nn.Module): def __init__(self, args): super().__init__() self.args = args self.d_model_enc = args.encoder_hidden_dim self.d_model_dec = args.decoder_hidden_dim self.dropout = args.dropout self.nhead = args.nheads self.dim_feedforward = args.dim_feedforward self.num_encoder_layers = args.enc_layers self.num_decoder_layers = args.dec_layers self.normalize_before = args.pre_norm self.return_intermediate_dec = True self.pass_pos_and_query = args.pass_pos_and_query self.share_decoders = args.share_decoders self.activation = "relu" self.pass_pos_and_query = self.pass_pos_and_query encoder_layer = TransformerEncoderLayer( self.d_model_enc, self.nhead, self.dim_feedforward, self.dropout, self.activation, self.normalize_before, ) encoder_norm = nn.LayerNorm(self.d_model_enc) if self.normalize_before else None self.encoder = TransformerEncoder( encoder_layer, self.num_encoder_layers, encoder_norm ) if self.d_model_dec != self.d_model_enc: self.enc2dec_proj = nn.Linear(self.d_model_enc, self.d_model_dec) self.pos_embed_proj = nn.Linear(self.d_model_enc, self.d_model_dec) else: self.enc2dec_proj = nn.Identity() self.pos_embed_proj = nn.Identity() if self.share_decoders: decoder_layer = TransformerDecoderLayer( self.d_model_dec, self.nhead, self.dim_feedforward, self.dropout, self.activation, self.normalize_before, ) decoder_norm = nn.LayerNorm(self.d_model_dec) self.decoder = TransformerDecoder( decoder_layer, self.num_decoder_layers, decoder_norm, return_intermediate=self.return_intermediate_dec, ) self._reset_parameters() def _reset_parameters(self): for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) def forward(self, *args, **kwargs): raise NotImplementedError() class UniTTransformer(Transformer): def __init__(self, args): super().__init__(args=args) num_queries = self.args.num_queries self.decoders = nn.ModuleDict() for task in num_queries: task_dict = nn.ModuleDict() for dataset in num_queries[task]: if self.share_decoders: task_dict[dataset] = self.decoder else: task_dict[dataset] = self.build_decoder_layer( d_model_dec=self.d_model_dec, nhead=self.nhead, dim_feedforward=self.dim_feedforward, dropout=self.dropout, activation=self.activation, normalize_before=self.normalize_before, num_decoder_layers=self.num_decoder_layers, return_intermediate_dec=self.return_intermediate_dec, ) self.decoders[task] = task_dict # A separate decoder for VQA MAX_TASK_NUM = 256 if args.use_task_embedding_in_img_encoder: self.task_embeddings_enc = nn.Embedding(MAX_TASK_NUM, self.d_model_enc) # when adding the task embedding to the beginning of the decoder, we'll strip # it from the hidden state outputs to make it compatible with previous models self.mem_out_begin_idx = 1 if args.use_task_embedding_in_img_encoder else 0 def build_decoder_layer( self, d_model_dec=512, nhead=8, num_decoder_layers=6, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False, return_intermediate_dec=False, ): decoder_layer = TransformerDecoderLayer( d_model_dec, nhead, dim_feedforward, dropout, activation, normalize_before ) decoder_norm = nn.LayerNorm(d_model_dec) return TransformerDecoder( decoder_layer, num_decoder_layers, decoder_norm, return_intermediate=return_intermediate_dec, ) def forward( self, img_src: Optional[Tensor] = None, img_mask: Optional[Tensor] = None, img_pos: Optional[Tensor] = None, text_src: Optional[Tensor] = None, text_mask: Optional[Tensor] = None, text_pos: Optional[Tensor] = None, query_embed: Optional[Tensor] = None, task_type: Optional[str] = None, dataset_name: Optional[str] = None, task_idx: Optional[int] = None, ): # flatten NxCxHxW to HWxNxC memories = [] pos_embeds = [] masks = [] if img_src is not None: bs, c, h, w = img_src.shape img_src = img_src.flatten(2).permute(2, 0, 1) img_pos = img_pos.flatten(2).permute(2, 0, 1) img_mask = img_mask.flatten(1) if text_src is None: query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1) if self.pass_pos_and_query: tgt = torch.zeros_like(query_embed) else: img_src, tgt, query_embed, img_pos = ( img_src + 0.1 * img_pos, query_embed, None, None, ) img_src, img_mask, img_pos = self._prefix_task_embedding_to_encoder_inputs( img_src, img_mask, img_pos, task_idx ) memory = self.encoder(img_src, src_key_padding_mask=img_mask, pos=img_pos) if self.mem_out_begin_idx != 0: img_src = img_src[self.mem_out_begin_idx :] img_pos = img_pos[self.mem_out_begin_idx :] img_mask = img_mask[:, self.mem_out_begin_idx :] memory = memory[self.mem_out_begin_idx :] if self.args.residual_in_encoder: memory = img_src + memory memory = self.enc2dec_proj(memory) img_pos = self.pos_embed_proj(img_pos) memories.append(memory) pos_embeds.append(img_pos) masks.append(img_mask) if text_src is not None: text_src = text_src.permute(1, 0, 2) memories.append(text_src) text_pos = text_pos.unsqueeze(1).repeat(1, text_src.size(1), 1) pos_embeds.append(text_pos) masks.append(text_mask != 1) query_embed = query_embed.unsqueeze(1).repeat(1, text_src.size(1), 1) if self.pass_pos_and_query: tgt = torch.zeros_like(query_embed) else: raise NotImplementedError() decoder = self.decoders[task_type][dataset_name] memories = torch.cat(memories) masks = torch.cat(masks, dim=-1) pos_embeds = torch.cat(pos_embeds) hs = decoder( tgt, memories, memory_key_padding_mask=masks, pos=pos_embeds, query_pos=query_embed, ) hs = hs.transpose(1, 2) # hs is num_layer x batch_size x seq_length x hidden_dim return hs, memories.permute(1, 2, 0) def _prefix_task_embedding_to_encoder_inputs( self, img_src, img_mask, img_pos, task_idx ): if not self.args.use_task_embedding_in_img_encoder: return img_src, img_mask, img_pos bs = img_src.size(1) task_embed = self.task_embeddings_enc.weight[task_idx] task_embed = task_embed.unsqueeze(0).unsqueeze(0).repeat(1, bs, 1) img_src = torch.cat([task_embed, img_src], dim=0) # 0 for non-padding in img_mask img_mask_pad = torch.zeros_like(img_mask[:, :1]) img_mask = torch.cat([img_mask_pad, img_mask], dim=1) img_pos_pad = torch.zeros_like(img_pos[:1]) img_pos = torch.cat([img_pos_pad, img_pos], dim=0) return img_src, img_mask, img_pos class TransformerEncoder(nn.Module): def __init__(self, encoder_layer, num_layers, norm=None): super().__init__() self.layers = _get_clones(encoder_layer, num_layers) self.num_layers = num_layers self.norm = norm def forward( self, src, mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, ): output = src for layer in self.layers: output = layer( output, src_mask=mask, src_key_padding_mask=src_key_padding_mask, pos=pos, ) if self.norm is not None: output = self.norm(output) return output class TransformerDecoder(nn.Module): def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False): super().__init__() self.layers = _get_clones(decoder_layer, num_layers) self.num_layers = num_layers self.norm = norm self.return_intermediate = return_intermediate def forward( self, tgt, memory, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None, ): output = tgt intermediate = [] for layer in self.layers: output = layer( output, memory, tgt_mask=tgt_mask, memory_mask=memory_mask, tgt_key_padding_mask=tgt_key_padding_mask, memory_key_padding_mask=memory_key_padding_mask, pos=pos, query_pos=query_pos, ) if self.return_intermediate: intermediate.append(self.norm(output)) if self.norm is not None: output = self.norm(output) if self.return_intermediate: intermediate.pop() intermediate.append(output) if self.return_intermediate: return torch.stack(intermediate) return output class TransformerEncoderLayer(nn.Module): def __init__( self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False, ): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) # Implementation of Feedforward model self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before def with_pos_embed(self, tensor, pos: Optional[Tensor]): return tensor if pos is None else tensor + pos def forward_post( self, src, src_mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, ): q = k = self.with_pos_embed(src, pos) src2 = self.self_attn( q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask )[0] src = src + self.dropout1(src2) src = self.norm1(src) src2 = self.linear2(self.dropout(self.activation(self.linear1(src)))) src = src + self.dropout2(src2) src = self.norm2(src) return src def forward_pre( self, src, src_mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, ): src2 = self.norm1(src) q = k = self.with_pos_embed(src2, pos) src2 = self.self_attn( q, k, value=src2, attn_mask=src_mask, key_padding_mask=src_key_padding_mask )[0] src = src + self.dropout1(src2) src2 = self.norm2(src) src2 = self.linear2(self.dropout(self.activation(self.linear1(src2)))) src = src + self.dropout2(src2) return src def forward( self, src, src_mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, ): if self.normalize_before: return self.forward_pre(src, src_mask, src_key_padding_mask, pos) return self.forward_post(src, src_mask, src_key_padding_mask, pos) class TransformerDecoderLayer(nn.Module): def __init__( self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False, ): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) # Implementation of Feedforward model self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.norm3 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.dropout3 = nn.Dropout(dropout) self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before def with_pos_embed(self, tensor, pos: Optional[Tensor]): return tensor if pos is None else tensor + pos def forward_post( self, tgt, memory, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None, ): q = k = self.with_pos_embed(tgt, query_pos) tgt2 = self.self_attn( q, k, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask )[0] tgt = tgt + self.dropout1(tgt2) tgt = self.norm1(tgt) tgt2 = self.multihead_attn( query=self.with_pos_embed(tgt, query_pos), key=self.with_pos_embed(memory, pos), value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask, )[0] tgt = tgt + self.dropout2(tgt2) tgt = self.norm2(tgt) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) tgt = tgt + self.dropout3(tgt2) tgt = self.norm3(tgt) return tgt def forward_pre( self, tgt, memory, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None, ): tgt2 = self.norm1(tgt) q = k = self.with_pos_embed(tgt2, query_pos) tgt2 = self.self_attn( q, k, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask )[0] tgt = tgt + self.dropout1(tgt2) tgt2 = self.norm2(tgt) tgt2 = self.multihead_attn( query=self.with_pos_embed(tgt2, query_pos), key=self.with_pos_embed(memory, pos), value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask, )[0] tgt = tgt + self.dropout2(tgt2) tgt2 = self.norm3(tgt) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) tgt = tgt + self.dropout3(tgt2) return tgt def forward( self, tgt, memory, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None, ): if self.normalize_before: return self.forward_pre( tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos, ) return self.forward_post( tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos, ) def _get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) def _get_activation_fn(activation): """Return an activation function given a string""" if activation == "relu": return F.relu if activation == "gelu": return F.gelu if activation == "glu": return F.glu raise RuntimeError(f"activation should be relu/gelu, not {activation}.")
9,350