content
stringlengths
228
999k
pred_label
stringclasses
1 value
pred_score
float64
0.5
1
MATLAB求解非线性方程组 时间: 2023-07-28 12:06:59 浏览: 21 MATLAB可以使用“fsolve”函数求解非线性方程组。假设有如下非线性方程组: x^2 + y^2 = 1 x^2 - y^2 = 0 则可以使用以下代码求解: fun = @(x) [x(1)^2 + x(2)^2 - 1; x(1)^2 - x(2)^2]; x0 = [0.5; 0.5]; x = fsolve(fun, x0); 其中,“fun”为一个匿名函数,输入参数为未知变量向量x,输出为方程组的值向量;“x0”为起始点向量,即求解的初始值。运行后,可以得到x=[0.7071; 0.7071]的解。 需要注意的是,在使用“fsolve”函数求解非线性方程组时,需要手动设置初始值,因为非线性方程组不存在解析解,求解过程需要使用数值方法,初始值的选择对结果影响很大。同时,由于数值方法的局限性,有时可能会求得局部最优解而非全局最优解。 相关问题 matlab 求解非线性方程组 Matlab可以使用fsolve函数来求解非线性方程组,具体步骤如下: 1. 定义非线性方程组 首先需要定义非线性方程组,例如: function F = myfun(x) F = [x(1)^2 + x(2)^2 - 1; x(1) - x(2)^2]; end 这个方程组包含两个未知数x(1)和x(2),其中第一个方程表示一个圆的方程,第二个方程表示一个抛物线的方程。 2. 使用fsolve函数求解方程组 使用fsolve函数可以求解方程组,例如: x0 = [0.5, 0.5]; options = optimoptions('fsolve','Display','iter'); [x,fval,exitflag,output] = fsolve(@myfun,x0,options); 其中,@myfun表示要求解的非线性方程组的函数句柄,x0是初始解向量,options是fsolve函数的参数设置,x是求解得到的解向量,fval是方程组的函数值,exitflag表示求解状态,output是求解的详细输出信息。 3. 输出结果 求解完成后,可以输出求解结果,例如: disp('The solution is:'); disp(x); 运行结果如下: The solution is: 0.6180 0.7862 这就是方程组的解向量。 matlab解非线性方程组 MATLAB提供了许多求解非线性方程组的函数,其中最常用的是fsolve函数。 例如,假设要解决以下非线性方程组: $x^2+y^2=1$ $x+y+z=3$ $x^3+y^3+z^3=3$ 可以使用fsolve函数进行求解,代码如下: ``` function F = myfun(x) F = [x(1)^2 + x(2)^2 - 1; x(1) + x(2) + x(3) - 3; x(1)^3 + x(2)^3 + x(3)^3 - 3]; end x0 = [0; 0; 0]; % 初始猜测 [x, fval] = fsolve(@myfun, x0) % 求解方程组 ``` 其中,myfun是一个自定义的函数,输入参数x是一个列向量,输出参数F也是一个列向量,包含三个方程的值。fsolve函数的第一个参数是一个函数句柄,指向myfun函数,第二个参数是初始猜测值。求解结果x是一个列向量,包含三个未知数的值,fval是方程组的解的误差(应该接近于0)。 相关推荐 MATLAB 中求解非线性方程组的方法有多种,常用的包括牛顿法、拟牛顿法、Levenberg-Marquardt 算法等。下面以一个简单的实例来介绍如何使用 MATLAB 求解非线性方程组。 以方程组f(x) = [x1^2 + x2^2 - 1; x1 - x2] = 0作为例子,假设我们要求解 f(x) = 0 的解。 首先,我们定义一个函数文件,用于计算 f(x) 和其 Jacobian 矩阵 J(x)。 function [f, J] = nonlinear_eq(x) % 计算方程组f(x)和Jacobian矩阵 f = [x(1)^2 + x(2)^2 - 1; x(1) - x(2)]; J = [2*x(1), 2*x(2); 1, -1]; end 接下来,我们可以使用 MATLAB 自带的 fsolve 函数求解非线性方程组。 % 初始值 x0 = [1; 1]; % 求解方程组f(x) = 0 options = optimoptions('fsolve', 'Display', 'iter', 'Algorithm', 'levenberg-marquardt'); [x, fval, exitflag, output, jacobian] = fsolve(@nonlinear_eq, x0, options); disp(x); 在上述代码中,我们使用了 fsolve 函数,其中 @nonlinear_eq 表示传入的函数句柄,x0 表示初始值,options 表示求解选项。最终求解结果保存在 x 中,输出到命令行界面。这里我们使用了 Levenberg-Marquardt 算法作为求解算法。 运行程序后,可以得到以下输出结果: Iteration Func-count min f(x) Procedure 0 1 1.00067 1 3 0.00000 trust-region-dogleg 2 4 0.00000 trust-region-dogleg fsolve completed because the vector of function values near the solution is as close to zero as possible, but the vector of function values is not zero. x = 0.7071 0.7071 从输出结果可以看出,使用 Levenberg-Marquardt 算法求解得到的解为 x = [0.7071; 0.7071],满足方程组f(x) = 0。 以上就是一个简单的 MATLAB 求解非线性方程组的实例。 在MATLAB中求解非线性方程组有多种方法可以选择。其中一种常用的方法是使用fsolve函数。fsolve函数可以通过数值方法来求解非线性方程组。 具体来说,假设我们要求解非线性方程组F(x) = 0,其中x是一个向量,F是一个函数,该函数返回一个与x具有相同维度的向量。我们可以使用以下步骤来使用fsolve函数求解非线性方程组: 1. 定义一个匿名函数或者一个函数句柄,表示我们要求解的非线性方程组F(x) = 0。例如,我们可以定义一个匿名函数f,表示一个包含非线性方程组的向量函数。 2. 使用fsolve函数来求解非线性方程组。将上一步中定义的函数作为第一个参数传递给fsolve函数,并提供一个初始猜测向量x0作为第二个参数。 3. fsolve函数将返回一个解向量x,该向量使得F(x)接近于零。我们可以使用该解向量来获得非线性方程组的解。 下面是一个使用fsolve函数求解非线性方程组的示例代码: matlab % 定义一个非线性方程组 f = @(x) [x(1)^2 + x(2)^2 - 1; x(1) - x(2)^3]; % 提供一个初始猜测向量 x0 = [0; 0]; % 使用fsolve函数求解非线性方程组 x = fsolve(f, x0); % 输出结果 disp(x); 在这个示例中,我们定义了一个包含两个非线性方程的向量函数f。然后,我们提供一个初始猜测向量x0,并使用fsolve函数求解非线性方程组。最后,我们输出求解得到的解向量x。 需要注意的是,fsolve函数求解非线性方程组的结果取决于初始猜测向量的选取。如果初始猜测向量离解向量较远,可能会导致求解失败或者得到一个不正确的解。因此,在使用fsolve函数求解非线性方程组时,我们需要根据具体情况选择合适的初始猜测向量。 引用是一篇博客文章,描述了在MATLAB中如何使用inv函数来求解代数方程组。引用是关于FP-Growth算法的介绍,与MATLAB求解非线性方程组无直接关联。123 #### 引用[.reference_title] - *1* *3* [matlab 解方程组](https://blog.csdn.net/dianzhi2787/article/details/101213089)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [FP-Growth 关联规则挖掘方法 Matlab 频繁项集挖掘](https://download.csdn.net/download/weixin_39168167/88251619)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ] MATLAB是一个非常强大的数学软件,可以用来解决各种数学问题,包括求解多元非线性方程组。多元非线性方程组是指由多个未知数和非线性方程组成的方程组,它们的求解通常比较困难,需要借助数值方法。 在MATLAB中求解多元非线性方程组,通常使用fminsearch函数。该函数可以求解单个方程的最小值或多元方程的最小值。对于多元非线性方程组,需要将它们转化为一个多元函数,然后将该函数作为fminsearch函数的输入参数。在函数参数中可以指定初始估计值,精度要求等参数。使用该函数后,MATLAB会自动迭代求解方程组,直到满足精度要求,或者达到指定的最大迭代次数。 为了成功求解多元非线性方程组,需要注意以下几点: 1.合理选择初始估计值,以便迭代求解算法能够顺利进行。 2.选择合适的求解方法。除了fminsearch函数外,MATLAB还提供了其他求解多元非线性方程组的函数,如fsolve等。 3.调整求解参数。在使用fminsearch函数时,可以设置最大迭代次数,收敛精度等参数,来得到更好的求解效果。 4.检查解的可行性和稳定性。求解的结果需要符合实际问题的要求,不仅要满足数学方程的解,还要考虑解的可行性和稳定性。 总之,MATLAB是一种非常方便的求解多元非线性方程组的工具,只需要将问题转化为多元函数,选择合适的函数和参数,即可得到满意的求解结果。 最新推荐 牛顿迭代法解多元非线性方程程序与说明.docx 利用牛顿迭代法求解多元非线性方程组,包含MATLAB程序源码和运行结果。 chromedriver_win32_2.19.zip chromedriver可执行程序下载,请注意对应操作系统和浏览器版本号,其中文件名规则为 chromedriver_操作系统_版本号,比如 chromedriver_win32_102.0.5005.27.zip表示适合windows x86 x64系统浏览器版本号为102.0.5005.27 chromedriver_linux64_103.0.5060.53.zip表示适合linux x86_64系统浏览器版本号为103.0.5060.53 chromedriver_mac64_m1_101.0.4951.15.zip表示适合macOS m1芯片系统浏览器版本号为101.0.4951.15 chromedriver_mac64_101.0.4951.15.zip表示适合macOS x86_64系统浏览器版本号为101.0.4951.15 chromedriver_mac_arm64_108.0.5359.22.zip表示适合macOS arm64系统浏览器版本号为108.0.5359.22 鸿蒙应用开发 应用程序入口 UIAbility使用.docx 鸿蒙应用开发 应用程序入口 UIAbility使用.docx chromedriver_linux64_91.0.4472.19.zip chromedriver可执行程序下载,请注意对应操作系统和浏览器版本号,其中文件名规则为 chromedriver_操作系统_版本号,比如 chromedriver_win32_102.0.5005.27.zip表示适合windows x86 x64系统浏览器版本号为102.0.5005.27 chromedriver_linux64_103.0.5060.53.zip表示适合linux x86_64系统浏览器版本号为103.0.5060.53 chromedriver_mac64_m1_101.0.4951.15.zip表示适合macOS m1芯片系统浏览器版本号为101.0.4951.15 chromedriver_mac64_101.0.4951.15.zip表示适合macOS x86_64系统浏览器版本号为101.0.4951.15 chromedriver_mac_arm64_108.0.5359.22.zip表示适合macOS arm64系统浏览器版本号为108.0.5359.22 圣诞节微场景练习小项目 圣诞节微场景练习小项目 分布式高并发.pdf 分布式高并发 基于多峰先验分布的深度生成模型的分布外检测 基于多峰先验分布的深度生成模型的似然估计的分布外检测鸭井亮、小林圭日本庆应义塾大学鹿井亮[email protected][email protected]摘要现代机器学习系统可能会表现出不期望的和不可预测的行为,以响应分布外的输入。因此,应用分布外检测来解决这个问题是安全AI的一个活跃子领域概率密度估计是一种流行的低维数据分布外检测方法。然而,对于高维数据,最近的工作报告称,深度生成模型可以将更高的可能性分配给分布外数据,而不是训练数据。我们提出了一种新的方法来检测分布外的输入,使用具有多峰先验分布的深度生成模型。我们的实验结果表明,我们在Fashion-MNIST上训练的模型成功地将较低的可能性分配给MNIST,并成功地用作分布外检测器。1介绍机器学习领域在包括计算机视觉和自然语言处理的各个领域中然而,现代机器学习系统即使对于分 阿里云服务器下载安装jq 根据提供的引用内容,没有找到与阿里云服务器下载安装jq相关的信息。不过,如果您想在阿里云服务器上安装jq,可以按照以下步骤进行操作: 1.使用wget命令下载jq二进制文件: ```shell wget https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64 -O jq ``` 2.将下载的jq文件移动到/usr/local/bin目录下,并添加可执行权限: ```shell sudo mv jq /usr/local/bin/ sudo chmod +x /usr/local/bin/jq ``` 3.检查j 毕业论文java vue springboot mysql 4S店车辆管理系统.docx 包括摘要,背景意义,论文结构安排,开发技术介绍,需求分析,可行性分析,功能分析,业务流程分析,数据库设计,er图,数据字典,数据流图,详细设计,系统截图,测试,总结,致谢,参考文献。 "结构化语言约束下的安全强化学习框架" 使用结构化语言约束指导安全强化学习Bharat Prakash1,Nicholas Waytowich2,Ashwinkumar Ganesan1,Tim Oates1,TinooshMohsenin11马里兰大学,巴尔的摩县(UMBC),2美国陆军研究实验室,摘要强化学习(RL)已经在解决复杂的顺序决策任务中取得了成功,当一个定义良好的奖励函数可用时。对于在现实世界中行动的代理,这些奖励函数需要非常仔细地设计,以确保代理以安全的方式行动。当这些智能体需要与人类互动并在这种环境中执行任务时,尤其如此。然而,手工制作这样的奖励函数通常需要专门的专业知识,并且很难随着任务复杂性而扩展。这导致了强化学习中长期存在的问题,即奖励稀疏性,其中稀疏或不明确的奖励函数会减慢学习过程,并导致次优策略和不安全行为。 更糟糕的是,对于RL代理必须执行的每个任务,通常需要调整或重新指定奖励函数。另一�
__label__pos
0.661078
b595: Special Touring Car Racing Tags : Accepted rate : 29人/35人 ( 83% ) [非即時] 評分方式: Tolerant 最近更新 : 2015-10-06 08:16 Content Touring car racing is a car racing competition with heavily modified road-going cars. Most of the game is based on speed to determine the winner. A special touring car race to be held, the rules of this game is very special. The contestants need to rely on the wisdom to win the game. All contestants start on the road at mile post 0. Along the way there are n parking areas, numbered as 1 <= i <= n, at mile posts a1< a2< . . . < an, where each ai is measured from the starting point. The only places the contestants are allowed to stop are at these parking areas, but they can choose which of the parking areas they stop at. The contestants must stop at the final parking area (at distance an), which is the destination. The cars are specially designed, so that they would ideally drive 200 miles a day. This may not be possible, because of depending on the spacing of the parking areas. If the contestants drive x miles during a day, the penalty for that day is (200 - x)2. Minimum the sum of the daily penalties of contestant is the winner. Jonathan wants to participate in this touring car race. Can you help him to win the game? Input The input contains several test cases. Each test case has two lines. The first line contains the number of parking areas n. Here n <= 30. The second line contains n integers indicating the values of a1, a2, . . . , an. The values of a1, a2, . . . , an would be integers between 1 and 10000. The last line of input is only one 0 indicating the end of input. Output For each test case, output the parking areas at which to stop. The output starts at 0 and shows the parking areas numbers you stop at in order. The output of each test case should be in a separate line. Sample Input 4 190 260 385 540 5 130 180 230 330 450 0 Sample Output 0 1 3 4 0 3 5 測資資訊: 記憶體限制: 64 MB 公開 測資點#0 (100%): 2.0s , <1K Hint : Tags: 出處: [管理者: spocktsai (囧rz) ] ID User Problem Subject Hit Post Date 17724 es611543 (afa) b595 解法思路 34 2019-05-11 11:02
__label__pos
0.754841
~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ TOMOYO Linux Cross Reference Linux/include/linux/uwb.h Version: ~ [ linux-5.8 ] ~ [ linux-5.7.14 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.57 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.138 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.193 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.232 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.232 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~ Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~ 1 /* 2 * Ultra Wide Band 3 * UWB API 4 * 5 * Copyright (C) 2005-2006 Intel Corporation 6 * Inaky Perez-Gonzalez <[email protected]> 7 * 8 * This program is free software; you can redistribute it and/or 9 * modify it under the terms of the GNU General Public License version 10 * 2 as published by the Free Software Foundation. 11 * 12 * This program is distributed in the hope that it will be useful, 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 * GNU General Public License for more details. 16 * 17 * You should have received a copy of the GNU General Public License 18 * along with this program; if not, write to the Free Software 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 20 * 02110-1301, USA. 21 * 22 * 23 * FIXME: doc: overview of the API, different parts and pointers 24 */ 25 26 #ifndef __LINUX__UWB_H__ 27 #define __LINUX__UWB_H__ 28 29 #include <linux/limits.h> 30 #include <linux/device.h> 31 #include <linux/mutex.h> 32 #include <linux/timer.h> 33 #include <linux/wait.h> 34 #include <linux/workqueue.h> 35 #include <linux/uwb/spec.h> 36 #include <asm/page.h> 37 38 struct uwb_dev; 39 struct uwb_beca_e; 40 struct uwb_rc; 41 struct uwb_rsv; 42 struct uwb_dbg; 43 44 /** 45 * struct uwb_dev - a UWB Device 46 * @rc: UWB Radio Controller that discovered the device (kind of its 47 * parent). 48 * @bce: a beacon cache entry for this device; or NULL if the device 49 * is a local radio controller. 50 * @mac_addr: the EUI-48 address of this device. 51 * @dev_addr: the current DevAddr used by this device. 52 * @beacon_slot: the slot number the beacon is using. 53 * @streams: bitmap of streams allocated to reservations targeted at 54 * this device. For an RC, this is the streams allocated for 55 * reservations targeted at DevAddrs. 56 * 57 * A UWB device may either by a neighbor or part of a local radio 58 * controller. 59 */ 60 struct uwb_dev { 61 struct mutex mutex; 62 struct list_head list_node; 63 struct device dev; 64 struct uwb_rc *rc; /* radio controller */ 65 struct uwb_beca_e *bce; /* Beacon Cache Entry */ 66 67 struct uwb_mac_addr mac_addr; 68 struct uwb_dev_addr dev_addr; 69 int beacon_slot; 70 DECLARE_BITMAP(streams, UWB_NUM_STREAMS); 71 DECLARE_BITMAP(last_availability_bm, UWB_NUM_MAS); 72 }; 73 #define to_uwb_dev(d) container_of(d, struct uwb_dev, dev) 74 75 /** 76 * UWB HWA/WHCI Radio Control {Command|Event} Block context IDs 77 * 78 * RC[CE]Bs have a 'context ID' field that matches the command with 79 * the event received to confirm it. 80 * 81 * Maximum number of context IDs 82 */ 83 enum { UWB_RC_CTX_MAX = 256 }; 84 85 86 /** Notification chain head for UWB generated events to listeners */ 87 struct uwb_notifs_chain { 88 struct list_head list; 89 struct mutex mutex; 90 }; 91 92 /* Beacon cache list */ 93 struct uwb_beca { 94 struct list_head list; 95 size_t entries; 96 struct mutex mutex; 97 }; 98 99 /* Event handling thread. */ 100 struct uwbd { 101 int pid; 102 struct task_struct *task; 103 wait_queue_head_t wq; 104 struct list_head event_list; 105 spinlock_t event_list_lock; 106 }; 107 108 /** 109 * struct uwb_mas_bm - a bitmap of all MAS in a superframe 110 * @bm: a bitmap of length #UWB_NUM_MAS 111 */ 112 struct uwb_mas_bm { 113 DECLARE_BITMAP(bm, UWB_NUM_MAS); 114 DECLARE_BITMAP(unsafe_bm, UWB_NUM_MAS); 115 int safe; 116 int unsafe; 117 }; 118 119 /** 120 * uwb_rsv_state - UWB Reservation state. 121 * 122 * NONE - reservation is not active (no DRP IE being transmitted). 123 * 124 * Owner reservation states: 125 * 126 * INITIATED - owner has sent an initial DRP request. 127 * PENDING - target responded with pending Reason Code. 128 * MODIFIED - reservation manager is modifying an established 129 * reservation with a different MAS allocation. 130 * ESTABLISHED - the reservation has been successfully negotiated. 131 * 132 * Target reservation states: 133 * 134 * DENIED - request is denied. 135 * ACCEPTED - request is accepted. 136 * PENDING - PAL has yet to make a decision to whether to accept or 137 * deny. 138 * 139 * FIXME: further target states TBD. 140 */ 141 enum uwb_rsv_state { 142 UWB_RSV_STATE_NONE = 0, 143 UWB_RSV_STATE_O_INITIATED, 144 UWB_RSV_STATE_O_PENDING, 145 UWB_RSV_STATE_O_MODIFIED, 146 UWB_RSV_STATE_O_ESTABLISHED, 147 UWB_RSV_STATE_O_TO_BE_MOVED, 148 UWB_RSV_STATE_O_MOVE_EXPANDING, 149 UWB_RSV_STATE_O_MOVE_COMBINING, 150 UWB_RSV_STATE_O_MOVE_REDUCING, 151 UWB_RSV_STATE_T_ACCEPTED, 152 UWB_RSV_STATE_T_DENIED, 153 UWB_RSV_STATE_T_CONFLICT, 154 UWB_RSV_STATE_T_PENDING, 155 UWB_RSV_STATE_T_EXPANDING_ACCEPTED, 156 UWB_RSV_STATE_T_EXPANDING_CONFLICT, 157 UWB_RSV_STATE_T_EXPANDING_PENDING, 158 UWB_RSV_STATE_T_EXPANDING_DENIED, 159 UWB_RSV_STATE_T_RESIZED, 160 161 UWB_RSV_STATE_LAST, 162 }; 163 164 enum uwb_rsv_target_type { 165 UWB_RSV_TARGET_DEV, 166 UWB_RSV_TARGET_DEVADDR, 167 }; 168 169 /** 170 * struct uwb_rsv_target - the target of a reservation. 171 * 172 * Reservations unicast and targeted at a single device 173 * (UWB_RSV_TARGET_DEV); or (e.g., in the case of WUSB) targeted at a 174 * specific (private) DevAddr (UWB_RSV_TARGET_DEVADDR). 175 */ 176 struct uwb_rsv_target { 177 enum uwb_rsv_target_type type; 178 union { 179 struct uwb_dev *dev; 180 struct uwb_dev_addr devaddr; 181 }; 182 }; 183 184 struct uwb_rsv_move { 185 struct uwb_mas_bm final_mas; 186 struct uwb_ie_drp *companion_drp_ie; 187 struct uwb_mas_bm companion_mas; 188 }; 189 190 /* 191 * Number of streams reserved for reservations targeted at DevAddrs. 192 */ 193 #define UWB_NUM_GLOBAL_STREAMS 1 194 195 typedef void (*uwb_rsv_cb_f)(struct uwb_rsv *rsv); 196 197 /** 198 * struct uwb_rsv - a DRP reservation 199 * 200 * Data structure management: 201 * 202 * @rc: the radio controller this reservation is for 203 * (as target or owner) 204 * @rc_node: a list node for the RC 205 * @pal_node: a list node for the PAL 206 * 207 * Owner and target parameters: 208 * 209 * @owner: the UWB device owning this reservation 210 * @target: the target UWB device 211 * @type: reservation type 212 * 213 * Owner parameters: 214 * 215 * @max_mas: maxiumum number of MAS 216 * @min_mas: minimum number of MAS 217 * @sparsity: owner selected sparsity 218 * @is_multicast: true iff multicast 219 * 220 * @callback: callback function when the reservation completes 221 * @pal_priv: private data for the PAL making the reservation 222 * 223 * Reservation status: 224 * 225 * @status: negotiation status 226 * @stream: stream index allocated for this reservation 227 * @tiebreaker: conflict tiebreaker for this reservation 228 * @mas: reserved MAS 229 * @drp_ie: the DRP IE 230 * @ie_valid: true iff the DRP IE matches the reservation parameters 231 * 232 * DRP reservations are uniquely identified by the owner, target and 233 * stream index. However, when using a DevAddr as a target (e.g., for 234 * a WUSB cluster reservation) the responses may be received from 235 * devices with different DevAddrs. In this case, reservations are 236 * uniquely identified by just the stream index. A number of stream 237 * indexes (UWB_NUM_GLOBAL_STREAMS) are reserved for this. 238 */ 239 struct uwb_rsv { 240 struct uwb_rc *rc; 241 struct list_head rc_node; 242 struct list_head pal_node; 243 struct kref kref; 244 245 struct uwb_dev *owner; 246 struct uwb_rsv_target target; 247 enum uwb_drp_type type; 248 int max_mas; 249 int min_mas; 250 int max_interval; 251 bool is_multicast; 252 253 uwb_rsv_cb_f callback; 254 void *pal_priv; 255 256 enum uwb_rsv_state state; 257 bool needs_release_companion_mas; 258 u8 stream; 259 u8 tiebreaker; 260 struct uwb_mas_bm mas; 261 struct uwb_ie_drp *drp_ie; 262 struct uwb_rsv_move mv; 263 bool ie_valid; 264 struct timer_list timer; 265 struct work_struct handle_timeout_work; 266 }; 267 268 static const 269 struct uwb_mas_bm uwb_mas_bm_zero = { .bm = { 0 } }; 270 271 static inline void uwb_mas_bm_copy_le(void *dst, const struct uwb_mas_bm *mas) 272 { 273 bitmap_copy_le(dst, mas->bm, UWB_NUM_MAS); 274 } 275 276 /** 277 * struct uwb_drp_avail - a radio controller's view of MAS usage 278 * @global: MAS unused by neighbors (excluding reservations targeted 279 * or owned by the local radio controller) or the beaon period 280 * @local: MAS unused by local established reservations 281 * @pending: MAS unused by local pending reservations 282 * @ie: DRP Availability IE to be included in the beacon 283 * @ie_valid: true iff @ie is valid and does not need to regenerated from 284 * @global and @local 285 * 286 * Each radio controller maintains a view of MAS usage or 287 * availability. MAS available for a new reservation are determined 288 * from the intersection of @global, @local, and @pending. 289 * 290 * The radio controller must transmit a DRP Availability IE that's the 291 * intersection of @global and @local. 292 * 293 * A set bit indicates the MAS is unused and available. 294 * 295 * rc->rsvs_mutex should be held before accessing this data structure. 296 * 297 * [ECMA-368] section 17.4.3. 298 */ 299 struct uwb_drp_avail { 300 DECLARE_BITMAP(global, UWB_NUM_MAS); 301 DECLARE_BITMAP(local, UWB_NUM_MAS); 302 DECLARE_BITMAP(pending, UWB_NUM_MAS); 303 struct uwb_ie_drp_avail ie; 304 bool ie_valid; 305 }; 306 307 struct uwb_drp_backoff_win { 308 u8 window; 309 u8 n; 310 int total_expired; 311 struct timer_list timer; 312 bool can_reserve_extra_mases; 313 }; 314 315 const char *uwb_rsv_state_str(enum uwb_rsv_state state); 316 const char *uwb_rsv_type_str(enum uwb_drp_type type); 317 318 struct uwb_rsv *uwb_rsv_create(struct uwb_rc *rc, uwb_rsv_cb_f cb, 319 void *pal_priv); 320 void uwb_rsv_destroy(struct uwb_rsv *rsv); 321 322 int uwb_rsv_establish(struct uwb_rsv *rsv); 323 int uwb_rsv_modify(struct uwb_rsv *rsv, 324 int max_mas, int min_mas, int sparsity); 325 void uwb_rsv_terminate(struct uwb_rsv *rsv); 326 327 void uwb_rsv_accept(struct uwb_rsv *rsv, uwb_rsv_cb_f cb, void *pal_priv); 328 329 void uwb_rsv_get_usable_mas(struct uwb_rsv *orig_rsv, struct uwb_mas_bm *mas); 330 331 /** 332 * Radio Control Interface instance 333 * 334 * 335 * Life cycle rules: those of the UWB Device. 336 * 337 * @index: an index number for this radio controller, as used in the 338 * device name. 339 * @version: version of protocol supported by this device 340 * @priv: Backend implementation; rw with uwb_dev.dev.sem taken. 341 * @cmd: Backend implementation to execute commands; rw and call 342 * only with uwb_dev.dev.sem taken. 343 * @reset: Hardware reset of radio controller and any PAL controllers. 344 * @filter: Backend implementation to manipulate data to and from device 345 * to be compliant to specification assumed by driver (WHCI 346 * 0.95). 347 * 348 * uwb_dev.dev.mutex is used to execute commands and update 349 * the corresponding structures; can't use a spinlock 350 * because rc->cmd() can sleep. 351 * @ies: This is a dynamically allocated array cacheing the 352 * IEs (settable by the host) that the beacon of this 353 * radio controller is currently sending. 354 * 355 * In reality, we store here the full command we set to 356 * the radio controller (which is basically a command 357 * prefix followed by all the IEs the beacon currently 358 * contains). This way we don't have to realloc and 359 * memcpy when setting it. 360 * 361 * We set this up in uwb_rc_ie_setup(), where we alloc 362 * this struct, call get_ie() [so we know which IEs are 363 * currently being sent, if any]. 364 * 365 * @ies_capacity:Amount of space (in bytes) allocated in @ies. The 366 * amount used is given by sizeof(*ies) plus ies->wIELength 367 * (which is a little endian quantity all the time). 368 * @ies_mutex: protect the IE cache 369 * @dbg: information for the debug interface 370 */ 371 struct uwb_rc { 372 struct uwb_dev uwb_dev; 373 int index; 374 u16 version; 375 376 struct module *owner; 377 void *priv; 378 int (*start)(struct uwb_rc *rc); 379 void (*stop)(struct uwb_rc *rc); 380 int (*cmd)(struct uwb_rc *, const struct uwb_rccb *, size_t); 381 int (*reset)(struct uwb_rc *rc); 382 int (*filter_cmd)(struct uwb_rc *, struct uwb_rccb **, size_t *); 383 int (*filter_event)(struct uwb_rc *, struct uwb_rceb **, const size_t, 384 size_t *, size_t *); 385 386 spinlock_t neh_lock; /* protects neh_* and ctx_* */ 387 struct list_head neh_list; /* Open NE handles */ 388 unsigned long ctx_bm[UWB_RC_CTX_MAX / 8 / sizeof(unsigned long)]; 389 u8 ctx_roll; 390 391 int beaconing; /* Beaconing state [channel number] */ 392 int beaconing_forced; 393 int scanning; 394 enum uwb_scan_type scan_type:3; 395 unsigned ready:1; 396 struct uwb_notifs_chain notifs_chain; 397 struct uwb_beca uwb_beca; 398 399 struct uwbd uwbd; 400 401 struct uwb_drp_backoff_win bow; 402 struct uwb_drp_avail drp_avail; 403 struct list_head reservations; 404 struct list_head cnflt_alien_list; 405 struct uwb_mas_bm cnflt_alien_bitmap; 406 struct mutex rsvs_mutex; 407 spinlock_t rsvs_lock; 408 struct workqueue_struct *rsv_workq; 409 410 struct delayed_work rsv_update_work; 411 struct delayed_work rsv_alien_bp_work; 412 int set_drp_ie_pending; 413 struct mutex ies_mutex; 414 struct uwb_rc_cmd_set_ie *ies; 415 size_t ies_capacity; 416 417 struct list_head pals; 418 int active_pals; 419 420 struct uwb_dbg *dbg; 421 }; 422 423 424 /** 425 * struct uwb_pal - a UWB PAL 426 * @name: descriptive name for this PAL (wusbhc, wlp, etc.). 427 * @device: a device for the PAL. Used to link the PAL and the radio 428 * controller in sysfs. 429 * @rc: the radio controller the PAL uses. 430 * @channel_changed: called when the channel used by the radio changes. 431 * A channel of -1 means the channel has been stopped. 432 * @new_rsv: called when a peer requests a reservation (may be NULL if 433 * the PAL cannot accept reservation requests). 434 * @channel: channel being used by the PAL; 0 if the PAL isn't using 435 * the radio; -1 if the PAL wishes to use the radio but 436 * cannot. 437 * @debugfs_dir: a debugfs directory which the PAL can use for its own 438 * debugfs files. 439 * 440 * A Protocol Adaptation Layer (PAL) is a user of the WiMedia UWB 441 * radio platform (e.g., WUSB, WLP or Bluetooth UWB AMP). 442 * 443 * The PALs using a radio controller must register themselves to 444 * permit the UWB stack to coordinate usage of the radio between the 445 * various PALs or to allow PALs to response to certain requests from 446 * peers. 447 * 448 * A struct uwb_pal should be embedded in a containing structure 449 * belonging to the PAL and initialized with uwb_pal_init()). Fields 450 * should be set appropriately by the PAL before registering the PAL 451 * with uwb_pal_register(). 452 */ 453 struct uwb_pal { 454 struct list_head node; 455 const char *name; 456 struct device *device; 457 struct uwb_rc *rc; 458 459 void (*channel_changed)(struct uwb_pal *pal, int channel); 460 void (*new_rsv)(struct uwb_pal *pal, struct uwb_rsv *rsv); 461 462 int channel; 463 struct dentry *debugfs_dir; 464 }; 465 466 void uwb_pal_init(struct uwb_pal *pal); 467 int uwb_pal_register(struct uwb_pal *pal); 468 void uwb_pal_unregister(struct uwb_pal *pal); 469 470 int uwb_radio_start(struct uwb_pal *pal); 471 void uwb_radio_stop(struct uwb_pal *pal); 472 473 /* 474 * General public API 475 * 476 * This API can be used by UWB device drivers or by those implementing 477 * UWB Radio Controllers 478 */ 479 struct uwb_dev *uwb_dev_get_by_devaddr(struct uwb_rc *rc, 480 const struct uwb_dev_addr *devaddr); 481 struct uwb_dev *uwb_dev_get_by_rc(struct uwb_dev *, struct uwb_rc *); 482 static inline void uwb_dev_get(struct uwb_dev *uwb_dev) 483 { 484 get_device(&uwb_dev->dev); 485 } 486 static inline void uwb_dev_put(struct uwb_dev *uwb_dev) 487 { 488 put_device(&uwb_dev->dev); 489 } 490 struct uwb_dev *uwb_dev_try_get(struct uwb_rc *rc, struct uwb_dev *uwb_dev); 491 492 /** 493 * Callback function for 'uwb_{dev,rc}_foreach()'. 494 * 495 * @dev: Linux device instance 496 * 'uwb_dev = container_of(dev, struct uwb_dev, dev)' 497 * @priv: Data passed by the caller to 'uwb_{dev,rc}_foreach()'. 498 * 499 * @returns: 0 to continue the iterations, any other val to stop 500 * iterating and return the value to the caller of 501 * _foreach(). 502 */ 503 typedef int (*uwb_dev_for_each_f)(struct device *dev, void *priv); 504 int uwb_dev_for_each(struct uwb_rc *rc, uwb_dev_for_each_f func, void *priv); 505 506 struct uwb_rc *uwb_rc_alloc(void); 507 struct uwb_rc *uwb_rc_get_by_dev(const struct uwb_dev_addr *); 508 struct uwb_rc *uwb_rc_get_by_grandpa(const struct device *); 509 void uwb_rc_put(struct uwb_rc *rc); 510 511 typedef void (*uwb_rc_cmd_cb_f)(struct uwb_rc *rc, void *arg, 512 struct uwb_rceb *reply, ssize_t reply_size); 513 514 int uwb_rc_cmd_async(struct uwb_rc *rc, const char *cmd_name, 515 struct uwb_rccb *cmd, size_t cmd_size, 516 u8 expected_type, u16 expected_event, 517 uwb_rc_cmd_cb_f cb, void *arg); 518 ssize_t uwb_rc_cmd(struct uwb_rc *rc, const char *cmd_name, 519 struct uwb_rccb *cmd, size_t cmd_size, 520 struct uwb_rceb *reply, size_t reply_size); 521 ssize_t uwb_rc_vcmd(struct uwb_rc *rc, const char *cmd_name, 522 struct uwb_rccb *cmd, size_t cmd_size, 523 u8 expected_type, u16 expected_event, 524 struct uwb_rceb **preply); 525 526 size_t __uwb_addr_print(char *, size_t, const unsigned char *, int); 527 528 int uwb_rc_dev_addr_set(struct uwb_rc *, const struct uwb_dev_addr *); 529 int uwb_rc_dev_addr_get(struct uwb_rc *, struct uwb_dev_addr *); 530 int uwb_rc_mac_addr_set(struct uwb_rc *, const struct uwb_mac_addr *); 531 int uwb_rc_mac_addr_get(struct uwb_rc *, struct uwb_mac_addr *); 532 int __uwb_mac_addr_assigned_check(struct device *, void *); 533 int __uwb_dev_addr_assigned_check(struct device *, void *); 534 535 /* Print in @buf a pretty repr of @addr */ 536 static inline size_t uwb_dev_addr_print(char *buf, size_t buf_size, 537 const struct uwb_dev_addr *addr) 538 { 539 return __uwb_addr_print(buf, buf_size, addr->data, 0); 540 } 541 542 /* Print in @buf a pretty repr of @addr */ 543 static inline size_t uwb_mac_addr_print(char *buf, size_t buf_size, 544 const struct uwb_mac_addr *addr) 545 { 546 return __uwb_addr_print(buf, buf_size, addr->data, 1); 547 } 548 549 /* @returns 0 if device addresses @addr2 and @addr1 are equal */ 550 static inline int uwb_dev_addr_cmp(const struct uwb_dev_addr *addr1, 551 const struct uwb_dev_addr *addr2) 552 { 553 return memcmp(addr1, addr2, sizeof(*addr1)); 554 } 555 556 /* @returns 0 if MAC addresses @addr2 and @addr1 are equal */ 557 static inline int uwb_mac_addr_cmp(const struct uwb_mac_addr *addr1, 558 const struct uwb_mac_addr *addr2) 559 { 560 return memcmp(addr1, addr2, sizeof(*addr1)); 561 } 562 563 /* @returns !0 if a MAC @addr is a broadcast address */ 564 static inline int uwb_mac_addr_bcast(const struct uwb_mac_addr *addr) 565 { 566 struct uwb_mac_addr bcast = { 567 .data = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } 568 }; 569 return !uwb_mac_addr_cmp(addr, &bcast); 570 } 571 572 /* @returns !0 if a MAC @addr is all zeroes*/ 573 static inline int uwb_mac_addr_unset(const struct uwb_mac_addr *addr) 574 { 575 struct uwb_mac_addr unset = { 576 .data = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } 577 }; 578 return !uwb_mac_addr_cmp(addr, &unset); 579 } 580 581 /* @returns !0 if the address is in use. */ 582 static inline unsigned __uwb_dev_addr_assigned(struct uwb_rc *rc, 583 struct uwb_dev_addr *addr) 584 { 585 return uwb_dev_for_each(rc, __uwb_dev_addr_assigned_check, addr); 586 } 587 588 /* 589 * UWB Radio Controller API 590 * 591 * This API is used (in addition to the general API) to implement UWB 592 * Radio Controllers. 593 */ 594 void uwb_rc_init(struct uwb_rc *); 595 int uwb_rc_add(struct uwb_rc *, struct device *dev, void *rc_priv); 596 void uwb_rc_rm(struct uwb_rc *); 597 void uwb_rc_neh_grok(struct uwb_rc *, void *, size_t); 598 void uwb_rc_neh_error(struct uwb_rc *, int); 599 void uwb_rc_reset_all(struct uwb_rc *rc); 600 void uwb_rc_pre_reset(struct uwb_rc *rc); 601 int uwb_rc_post_reset(struct uwb_rc *rc); 602 603 /** 604 * uwb_rsv_is_owner - is the owner of this reservation the RC? 605 * @rsv: the reservation 606 */ 607 static inline bool uwb_rsv_is_owner(struct uwb_rsv *rsv) 608 { 609 return rsv->owner == &rsv->rc->uwb_dev; 610 } 611 612 /** 613 * enum uwb_notifs - UWB events that can be passed to any listeners 614 * @UWB_NOTIF_ONAIR: a new neighbour has joined the beacon group. 615 * @UWB_NOTIF_OFFAIR: a neighbour has left the beacon group. 616 * 617 * Higher layers can register callback functions with the radio 618 * controller using uwb_notifs_register(). The radio controller 619 * maintains a list of all registered handlers and will notify all 620 * nodes when an event occurs. 621 */ 622 enum uwb_notifs { 623 UWB_NOTIF_ONAIR, 624 UWB_NOTIF_OFFAIR, 625 }; 626 627 /* Callback function registered with UWB */ 628 struct uwb_notifs_handler { 629 struct list_head list_node; 630 void (*cb)(void *, struct uwb_dev *, enum uwb_notifs); 631 void *data; 632 }; 633 634 int uwb_notifs_register(struct uwb_rc *, struct uwb_notifs_handler *); 635 int uwb_notifs_deregister(struct uwb_rc *, struct uwb_notifs_handler *); 636 637 638 /** 639 * UWB radio controller Event Size Entry (for creating entry tables) 640 * 641 * WUSB and WHCI define events and notifications, and they might have 642 * fixed or variable size. 643 * 644 * Each event/notification has a size which is not necessarily known 645 * in advance based on the event code. As well, vendor specific 646 * events/notifications will have a size impossible to determine 647 * unless we know about the device's specific details. 648 * 649 * It was way too smart of the spec writers not to think that it would 650 * be impossible for a generic driver to skip over vendor specific 651 * events/notifications if there are no LENGTH fields in the HEADER of 652 * each message...the transaction size cannot be counted on as the 653 * spec does not forbid to pack more than one event in a single 654 * transaction. 655 * 656 * Thus, we guess sizes with tables (or for events, when you know the 657 * size ahead of time you can use uwb_rc_neh_extra_size*()). We 658 * register tables with the known events and their sizes, and then we 659 * traverse those tables. For those with variable length, we provide a 660 * way to lookup the size inside the event/notification's 661 * payload. This allows device-specific event size tables to be 662 * registered. 663 * 664 * @size: Size of the payload 665 * 666 * @offset: if != 0, at offset @offset-1 starts a field with a length 667 * that has to be added to @size. The format of the field is 668 * given by @type. 669 * 670 * @type: Type and length of the offset field. Most common is LE 16 671 * bits (that's why that is zero); others are there mostly to 672 * cover for bugs and weirdos. 673 */ 674 struct uwb_est_entry { 675 size_t size; 676 unsigned offset; 677 enum { UWB_EST_16 = 0, UWB_EST_8 = 1 } type; 678 }; 679 680 int uwb_est_register(u8 type, u8 code_high, u16 vendor, u16 product, 681 const struct uwb_est_entry *, size_t entries); 682 int uwb_est_unregister(u8 type, u8 code_high, u16 vendor, u16 product, 683 const struct uwb_est_entry *, size_t entries); 684 ssize_t uwb_est_find_size(struct uwb_rc *rc, const struct uwb_rceb *rceb, 685 size_t len); 686 687 /* -- Misc */ 688 689 enum { 690 EDC_MAX_ERRORS = 10, 691 EDC_ERROR_TIMEFRAME = HZ, 692 }; 693 694 /* error density counter */ 695 struct edc { 696 unsigned long timestart; 697 u16 errorcount; 698 }; 699 700 static inline 701 void edc_init(struct edc *edc) 702 { 703 edc->timestart = jiffies; 704 } 705 706 /* Called when an error occurred. 707 * This is way to determine if the number of acceptable errors per time 708 * period has been exceeded. It is not accurate as there are cases in which 709 * this scheme will not work, for example if there are periodic occurrences 710 * of errors that straddle updates to the start time. This scheme is 711 * sufficient for our usage. 712 * 713 * @returns 1 if maximum acceptable errors per timeframe has been exceeded. 714 */ 715 static inline int edc_inc(struct edc *err_hist, u16 max_err, u16 timeframe) 716 { 717 unsigned long now; 718 719 now = jiffies; 720 if (now - err_hist->timestart > timeframe) { 721 err_hist->errorcount = 1; 722 err_hist->timestart = now; 723 } else if (++err_hist->errorcount > max_err) { 724 err_hist->errorcount = 0; 725 err_hist->timestart = now; 726 return 1; 727 } 728 return 0; 729 } 730 731 732 /* Information Element handling */ 733 734 struct uwb_ie_hdr *uwb_ie_next(void **ptr, size_t *len); 735 int uwb_rc_ie_add(struct uwb_rc *uwb_rc, const struct uwb_ie_hdr *ies, size_t size); 736 int uwb_rc_ie_rm(struct uwb_rc *uwb_rc, enum uwb_ie element_id); 737 738 /* 739 * Transmission statistics 740 * 741 * UWB uses LQI and RSSI (one byte values) for reporting radio signal 742 * strength and line quality indication. We do quick and dirty 743 * averages of those. They are signed values, btw. 744 * 745 * For 8 bit quantities, we keep the min, the max, an accumulator 746 * (@sigma) and a # of samples. When @samples gets to 255, we compute 747 * the average (@sigma / @samples), place it in @sigma and reset 748 * @samples to 1 (so we use it as the first sample). 749 * 750 * Now, statistically speaking, probably I am kicking the kidneys of 751 * some books I have in my shelves collecting dust, but I just want to 752 * get an approx, not the Nobel. 753 * 754 * LOCKING: there is no locking per se, but we try to keep a lockless 755 * schema. Only _add_samples() modifies the values--as long as you 756 * have other locking on top that makes sure that no two calls of 757 * _add_sample() happen at the same time, then we are fine. Now, for 758 * resetting the values we just set @samples to 0 and that makes the 759 * next _add_sample() to start with defaults. Reading the values in 760 * _show() currently can race, so you need to make sure the calls are 761 * under the same lock that protects calls to _add_sample(). FIXME: 762 * currently unlocked (It is not ultraprecise but does the trick. Bite 763 * me). 764 */ 765 struct stats { 766 s8 min, max; 767 s16 sigma; 768 atomic_t samples; 769 }; 770 771 static inline 772 void stats_init(struct stats *stats) 773 { 774 atomic_set(&stats->samples, 0); 775 wmb(); 776 } 777 778 static inline 779 void stats_add_sample(struct stats *stats, s8 sample) 780 { 781 s8 min, max; 782 s16 sigma; 783 unsigned samples = atomic_read(&stats->samples); 784 if (samples == 0) { /* it was zero before, so we initialize */ 785 min = 127; 786 max = -128; 787 sigma = 0; 788 } else { 789 min = stats->min; 790 max = stats->max; 791 sigma = stats->sigma; 792 } 793 794 if (sample < min) /* compute new values */ 795 min = sample; 796 else if (sample > max) 797 max = sample; 798 sigma += sample; 799 800 stats->min = min; /* commit */ 801 stats->max = max; 802 stats->sigma = sigma; 803 if (atomic_add_return(1, &stats->samples) > 255) { 804 /* wrapped around! reset */ 805 stats->sigma = sigma / 256; 806 atomic_set(&stats->samples, 1); 807 } 808 } 809 810 static inline ssize_t stats_show(struct stats *stats, char *buf) 811 { 812 int min, max, avg; 813 int samples = atomic_read(&stats->samples); 814 if (samples == 0) 815 min = max = avg = 0; 816 else { 817 min = stats->min; 818 max = stats->max; 819 avg = stats->sigma / samples; 820 } 821 return scnprintf(buf, PAGE_SIZE, "%d %d %d\n", min, max, avg); 822 } 823 824 static inline ssize_t stats_store(struct stats *stats, const char *buf, 825 size_t size) 826 { 827 stats_init(stats); 828 return size; 829 } 830 831 #endif /* #ifndef __LINUX__UWB_H__ */ 832 ~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin Linux® is a registered trademark of Linus Torvalds in the United States and other countries. TOMOYO® is a registered trademark of NTT DATA CORPORATION. osdn.jp
__label__pos
0.990529
• MarkDataGuy Visualizing Covid-19 with PowerBI and Publish to Web Updated: Apr 4, 2020 It looks like lots of data people are using Covid-19 data sets to build their own visualizations and run their own analysis of the virus. Using PowerBI and Publish to Web I have built my own. The results are here, but let review how this was approached. NB - Covid-19 and the pubic health impact is very serious. I am not trying to replace any of the existing public reporting tools out there. Please, wash your hands, stay safe and follow the instructions of your national health authority. 1) Find a dataset. There are quite a few out there, but I wanted one that was clean, complete, updated and official. A little bit of google-fu and I settled on the following source. Johns Hopkins CSSE is one of the official groups that are tracking Covid-19 and they make all of the data available via GitHub. Working with GitHub is interested. In this case, they have a lot of downloadable CSV's of data, however, with GitHub, you can use the raw.githubusercontent.com link to get to the raw data. In my case, the following link https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv opens the raw data that I need for Power Bi Query 2) Examine the source data. Once you get to data you want to see what you are dealing with. In this case, the source is CSV, and of particular interest is that date is stored on columns. So each new day adds a new column to the data set. I also note the presence of Latitude and Longitude values as well as normal country/region data. Finally, the data is not additive, so the current total is reported every day. 3) Load to Power BI. This was straightforward, if you do a Get Data -> Web and paste in that URL from point 1 above, Power BI will do a great job in bringing in the data. However, now I want to get it into a shape that suits me. So I want to transform it from its current columnar layout to a row by row approach. (Reporting loves thin and long tables and not fat and short) PowerQuery makes this really easy and you can do it all via the GUI. You want to • Make The First Row the Header • Unpivot the Date Columns • Rename, change the type and remove rows with 0 cases In PowerQuery M (Advanced Editor) you end up with; let Source = Csv.Document(Web.Contents("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv"),[Delimiter=",", Columns=NumColumns, Encoding=65001, QuoteStyle=QuoteStyle.None]), #"Promoted Headers" = Table.PromoteHeaders(Source, [PromoteAllScalars=true]), #"Unpivoted Columns" = Table.UnpivotOtherColumns(#"Promoted Headers", {"Province/State", "Country/Region", "Lat", "Long"}, "Attribute", "Value"), #"Renamed Columns" = Table.RenameColumns(#"Unpivoted Columns",{{"Attribute", "Date"}, {"Value", "Confirmed Cases"}}), #"Changed Type2" = Table.TransformColumnTypes(#"Renamed Columns",{{"Date", type date}, {"Confirmed Cases", Int64.Type}}), #"Filtered Rows" = Table.SelectRows(#"Changed Type2", each ([Confirmed Cases] <> null and [Confirmed Cases] <> 0)) in #"Filtered Rows" Note the Columns=NumColumns parameter. This required a little bit of work as you have to tell PowerQuery how many columns you want to read. In this case, we know that there will be one new column per day, so I created a separate query that would calculate a date difference from the current date to my first load date so that the number of columns would increase by 1 per day. 4) Create your data model and any additional calculations. The model is easy in this case as it is just one table. However, you have to allow for the fact that the data is presented as aggregated total. We don't get the number of new cases per day, but the total number of cases to date. If you select a range of dates, you don't want to end up over-counting. What you want is to present the latest value in that range. This requires a little bit of DAX as follows; CALCULATE(SUM('Covid Growth'[Confirmed Cases]), LASTDATE ('Covid Growth'[Date])) LASTDATE will get the value for the latest date in the selected date range. 5) Build your report, deploy, schedule a refresh and you are done. Thanks for reading and stay safe. Mark 41 views0 comments Original on Transparent.png Contact Us  Based in Cork, Ireland Tel. +353 86 2247617
__label__pos
0.53681
Logo ROOT   Reference Guide RMergeableValue.hxx Go to the documentation of this file. 1/** 2 \file ROOT/RDF/RMergeableValue.hxx 3 \ingroup dataframe 4 \author Vincenzo Eduardo Padulano 5 \author Enrico Guiraud 6 \date 2020-06 7*/ 8 9/************************************************************************* 10 * Copyright (C) 1995-2022, Rene Brun and Fons Rademakers. * 11 * All rights reserved. * 12 * * 13 * For the licensing terms see $ROOTSYS/LICENSE. * 14 * For the list of contributors see $ROOTSYS/README/CREDITS. * 15 *************************************************************************/ 16 17#ifndef ROOT_RDF_RMERGEABLEVALUE 18#define ROOT_RDF_RMERGEABLEVALUE 19 20#include <algorithm> // std::find, std::min, std::max 21#include <iterator> // std::distance 22#include <memory> 23#include <stdexcept> 24#include <string> 25#include <vector> 26 27#include "RtypesCore.h" 28#include "TError.h" // R__ASSERT 29#include "TList.h" // RMergeableFill::Merge 30 31namespace ROOT { 32namespace Detail { 33namespace RDF { 34 35// Fwd declarations for RMergeableValue 36template <typename T> 37class RMergeableValue; 38 39template <typename T> 40class RMergeableVariations; 41 42template <typename T, typename... Ts> 43std::unique_ptr<RMergeableValue<T>> MergeValues(std::unique_ptr<RMergeableValue<T>> OutputMergeable, 44 std::unique_ptr<RMergeableValue<Ts>>... InputMergeables); 45 46template <typename T, typename... Ts> 47void MergeValues(RMergeableValue<T> &OutputMergeable, const RMergeableValue<Ts> &... InputMergeables); 48 49template <typename T, typename... Ts> 50void MergeValues(RMergeableVariations<T> &OutputMergeable, const RMergeableVariations<Ts> &... InputMergeables); 51 52/** 53\class ROOT::Detail::RDF::RMergeableValueBase 54\brief Base class of RMergeableValue. 55\ingroup dataframe 56Base class of the mergeable RDataFrame results family of classes. Provides a 57non-templated custom type to allow passing a `std::unique_ptr` to the mergeable 58object along the call chain. This class is never used in the public API and has 59no meaning for the final user. 60*/ 62public: 63 virtual ~RMergeableValueBase() = default; 64 /** 65 Default constructor. Needed to allow serialization of ROOT objects. See 66 [TBufferFile::WriteObjectClass] 67 (classTBufferFile.html#a209078a4cb58373b627390790bf0c9c1) 68 */ 74}; 75 76/** 77\class ROOT::Detail::RDF::RMergeableValue 78\ingroup dataframe 79\brief A result of an RDataFrame execution, that knows how to merge with other 80results of the same type. 81\tparam T Type of the action result. 82 83Results of the execution of an RDataFrame computation graph do not natively 84know how to merge with other results of the same type. In a distributed 85environment it is often needed to have a merging mechanism for partial results 86coming from the execution of an analysis on different chunks of the same dataset 87that has happened on different executors. In order to achieve this, 88RMergeableValue stores the result of the RDataFrame action and has a `Merge` 89method to allow the aggregation of information coming from another similar 90result into the current. 91 92A mergeable value can be retrieved from an RResultPtr through the 93[GetMergeableValue] 94(namespaceROOT_1_1Detail_1_1RDF.html#a8b3a9c7b416826acc952d78a56d14ecb) free 95function and a sequence of mergeables can be merged together with the helper 96function [MergeValues] 97(namespaceROOT_1_1Detail_1_1RDF.html#af16fefbe2d120983123ddf8a1e137277). 98All the classes and functions involved are inside the `ROOT::Detail::RDF` 99namespace. 100 101In a nutshell: 102~~~{.cpp} 103using namespace ROOT::Detail::RDF; 104ROOT::RDataFrame d("myTree", "file_*.root"); 105auto h1 = d.Histo1D("Branch_A"); 106auto h2 = d.Histo1D("Branch_A"); 107 108// Retrieve mergeables from the `RResultPtr`s 109auto mergeableh1 = GetMergeableValue(h1); 110auto mergeableh2 = GetMergeableValue(h2); 111 112// Merge the values and get another mergeable back 113auto mergedptr = MergeValues(std::move(mergeableh1), std::move(mergeableh2)); 114 115// Retrieve the merged TH1D object 116const auto &mergedhisto = mergedptr->GetValue(); 117~~~ 118 119Though this snippet can run on a single thread of a single machine, it is 120straightforward to generalize it to a distributed case, e.g. where `mergeableh1` 121and `mergeableh2` are created on separate machines and sent to a `reduce` 122process where the `MergeValues` function is called. The final user would then 123just be given the final merged result coming from `mergedptr->GetValue`. 124 125RMergeableValue is the base class for all the different specializations that may 126be needed according to the peculiarities of the result types. The following 127subclasses, their names hinting at the action operation of the result, are 128currently available: 129 130- RMergeableCount 131- RMergeableFill, responsible for the following actions: 132 - Graph 133 - Histo{1,2,3}D 134 - Profile{1,2}D 135 - Stats 136- RMergeableMax 137- RMergeableMean 138- RMergeableMin 139- RMergeableStdDev 140- RMergeableSum 141*/ 142template <typename T> 144 // Friend function declarations 145 template <typename T1, typename... Ts> 146 friend std::unique_ptr<RMergeableValue<T1>> MergeValues(std::unique_ptr<RMergeableValue<T1>> OutputMergeable, 147 std::unique_ptr<RMergeableValue<Ts>>... InputMergeables); 148 template <typename T1, typename... Ts> 149 friend void MergeValues(RMergeableValue<T1> &OutputMergeable, const RMergeableValue<Ts> &... InputMergeables); 150 151 ///////////////////////////////////////////////////////////////////////////// 152 /// \brief Aggregate the information contained in another RMergeableValue 153 /// into this. 154 /// 155 /// Virtual function reimplemented in all the subclasses. 156 /// 157 /// \note All the `Merge` methods in the RMergeableValue family are private. 158 /// To merge multiple RMergeableValue objects please use [MergeValues] 159 /// (namespaceROOT_1_1Detail_1_1RDF.html#af16fefbe2d120983123ddf8a1e137277). 160 virtual void Merge(const RMergeableValue<T> &) = 0; 161 162protected: 164 165public: 166 /** 167 Constructor taking the action result by const reference. This involves a 168 copy of the result into the data member, but gives full ownership of data 169 to the mergeable. 170 */ 172 /** 173 Default constructor. Needed to allow serialization of ROOT objects. See 174 [TBufferFile::WriteObjectClass] 175 (classTBufferFile.html#a209078a4cb58373b627390790bf0c9c1) 176 */ 177 RMergeableValue() = default; 182 ///////////////////////////////////////////////////////////////////////////// 183 /// \brief Retrieve the result wrapped by this mergeable. 184 const T &GetValue() const { return fValue; } 185}; 186 187/** 188\class ROOT::Detail::RDF::RMergeableCount 189\ingroup dataframe 190\brief Specialization of RMergeableValue for the 191[Count](classROOT_1_1RDF_1_1RInterface.html#a9678150c9c18cddd7b599690ba854734) 192action. 193*/ 194class RMergeableCount final : public RMergeableValue<ULong64_t> { 195 ///////////////////////////////////////////////////////////////////////////// 196 /// \brief Aggregate the information contained in another RMergeableValue 197 /// into this. 198 /// \param[in] other Another RMergeableValue object. 199 /// \throws std::invalid_argument If the cast of the other object to the same 200 /// type as this one fails. 201 /// 202 /// The other RMergeableValue object is cast to the same type as this object. 203 /// This is needed to make sure that only results of the same type of action 204 /// are merged together. Then the two results are added together to update 205 /// the value held by the current object. 206 /// 207 /// \note All the `Merge` methods in the RMergeableValue family are private. 208 /// To merge multiple RMergeableValue objects please use [MergeValues] 209 /// (namespaceROOT_1_1Detail_1_1RDF.html#af16fefbe2d120983123ddf8a1e137277). 210 void Merge(const RMergeableValue<ULong64_t> &other) final 211 { 212 try { 213 const auto &othercast = dynamic_cast<const RMergeableCount &>(other); 214 this->fValue += othercast.fValue; 215 } catch (const std::bad_cast &) { 216 throw std::invalid_argument("Results from different actions cannot be merged together."); 217 } 218 } 219 220public: 221 ///////////////////////////////////////////////////////////////////////////// 222 /// \brief Constructor that initializes data members. 223 /// \param[in] value The action result. 225 /** 226 Default constructor. Needed to allow serialization of ROOT objects. See 227 [TBufferFile::WriteObjectClass] 228 (classTBufferFile.html#a209078a4cb58373b627390790bf0c9c1) 229 */ 230 RMergeableCount() = default; 235}; 236 237/** 238\class ROOT::Detail::RDF::RMergeableFill 239\ingroup dataframe 240\brief Specialization of RMergeableValue for histograms and statistics. 241 242This subclass is responsible for merging results coming from the following 243actions: 244- [Graph](classROOT_1_1RDF_1_1RInterface.html#a804b466ebdbddef5c7e3400cc6b89301) 245- [Histo{1D,2D,3D}] 246 (classROOT_1_1RDF_1_1RInterface.html#a247ca3aeb7ce5b95015b7fae72983055) 247- [HistoND](classROOT_1_1RDF_1_1RInterface.html#a0c9956a0f48c26f8e4294e17376c7fea) 248- [Profile{1D,2D}] 249 (classROOT_1_1RDF_1_1RInterface.html#a8ef7dc16b0e9f7bc9cfbe2d9e5de0cef) 250- [Stats](classROOT_1_1RDF_1_1RInterface.html#abc68922c464e472f5f856e8981955af6) 251 252*/ 253template <typename T> 254class RMergeableFill final : public RMergeableValue<T> { 255 256 // RDataFrame's generic Fill method supports two possible signatures for Merge. 257 // Templated to create a dependent type to SFINAE on - in reality, `U` will always be `T`. 258 // This overload handles Merge(TCollection*)... 260 auto DoMerge(const RMergeableFill<U> &other, int /*toincreaseoverloadpriority*/) 261 -> decltype(((U &)this->fValue).Merge((TCollection *)nullptr), void()) 262 { 263 TList l; // The `Merge` method accepts a TList 264 l.Add(const_cast<U *>(&other.fValue)); // Ugly but needed because of the signature of TList::Add 265 this->fValue.Merge(&l); // if `T == TH1D` Eventually calls TH1::ExtendAxis that creates new instances of TH1D 266 } 267 268 // ...and this one handles Merge(const std::vector<T*> &) 269 template <typename U> 270 auto DoMerge(const RMergeableFill<U> &other, double /*todecreaseoverloadpriority*/) 271 -> decltype(this->fValue.Merge(std::vector<U *>{}), void()) 272 { 273 this->fValue.Merge({const_cast<U *>(&other.fValue)}); 274 } 275 276 ///////////////////////////////////////////////////////////////////////////// 277 /// \brief Aggregate the information contained in another RMergeableValue 278 /// into this. 279 /// \param[in] other Another RMergeableValue object. 280 /// \throws std::invalid_argument If the cast of the other object to the same 281 /// type as this one fails. 282 /// 283 /// The other RMergeableValue object is cast to the same type as this object. 284 /// This is needed to make sure that only results of the same type of action 285 /// are merged together. The function then calls the right `Merge` method 286 /// according to the class of the fValue data member. 287 /// 288 /// \note All the `Merge` methods in the RMergeableValue family are private. 289 /// To merge multiple RMergeableValue objects please use [MergeValues] 290 /// (namespaceROOT_1_1Detail_1_1RDF.html#af16fefbe2d120983123ddf8a1e137277). 291 void Merge(const RMergeableValue<T> &other) final 292 { 293 try { 294 const auto &othercast = dynamic_cast<const RMergeableFill<T> &>(other); 295 DoMerge(othercast, /*toselecttherightoverload=*/0); 296 } catch (const std::bad_cast &) { 297 throw std::invalid_argument("Results from different actions cannot be merged together."); 298 } 299 } 300 301public: 302 ///////////////////////////////////////////////////////////////////////////// 303 /// \brief Constructor that initializes data members. 304 /// \param[in] value The action result. 306 /** 307 Default constructor. Needed to allow serialization of ROOT objects. See 308 [TBufferFile::WriteObjectClass] 309 (classTBufferFile.html#a209078a4cb58373b627390790bf0c9c1) 310 */ 311 RMergeableFill() = default; 316}; 317 318template <typename T> 319class RMergeableMax final : public RMergeableValue<T> { 320 321 void Merge(const RMergeableValue<T> &other) final 322 { 323 try { 324 const auto &othercast = dynamic_cast<const RMergeableMax<T> &>(other); 325 this->fValue = std::max(this->fValue, othercast.fValue); 326 } catch (const std::bad_cast &) { 327 throw std::invalid_argument("Results from different actions cannot be merged together."); 328 } 329 } 330 331public: 332 ///////////////////////////////////////////////////////////////////////////// 333 /// \brief Constructor that initializes data members. 334 /// \param[in] value The action result. 336 /** 337 Default constructor. Needed to allow serialization of ROOT objects. See 338 [TBufferFile::WriteObjectClass] 339 (classTBufferFile.html#a209078a4cb58373b627390790bf0c9c1) 340 */ 341 RMergeableMax() = default; 342 RMergeableMax(const RMergeableMax &) = delete; 346}; 347 348/** 349\class ROOT::Detail::RDF::RMergeableMean 350\ingroup dataframe 351\brief Specialization of RMergeableValue for the 352[Mean](classROOT_1_1RDF_1_1RInterface.html#ade6b020284f2f4fe9d3b09246b5f376a) 353action. 354 355This subclass is responsible for merging results coming from Mean actions. Other 356than the result itself, the number of entries that were used to compute that 357mean is also stored in the object. 358*/ 359class RMergeableMean final : public RMergeableValue<Double_t> { 360 ULong64_t fCounts; ///< The number of entries used to compute the mean. 361 362 ///////////////////////////////////////////////////////////////////////////// 363 /// \brief Aggregate the information contained in another RMergeableValue 364 /// into this. 365 /// \param[in] other Another RMergeableValue object. 366 /// \throws std::invalid_argument If the cast of the other object to the same 367 /// type as this one fails. 368 /// 369 /// The other RMergeableValue object is cast to the same type as this object. 370 /// This is needed to make sure that only results of the same type of action 371 /// are merged together. The function then computes the weighted mean of the 372 /// two means held by the mergeables. 373 /// 374 /// \note All the `Merge` methods in the RMergeableValue family are private. 375 /// To merge multiple RMergeableValue objects please use [MergeValues] 376 /// (namespaceROOT_1_1Detail_1_1RDF.html#af16fefbe2d120983123ddf8a1e137277). 377 void Merge(const RMergeableValue<Double_t> &other) final 378 { 379 try { 380 const auto &othercast = dynamic_cast<const RMergeableMean &>(other); 381 const auto &othervalue = othercast.fValue; 382 const auto &othercounts = othercast.fCounts; 383 384 // Compute numerator and denumerator of the weighted mean 385 const auto num = this->fValue * fCounts + othervalue * othercounts; 386 const auto denum = static_cast<Double_t>(fCounts + othercounts); 387 388 // Update data members 389 this->fValue = num / denum; 390 fCounts += othercounts; 391 } catch (const std::bad_cast &) { 392 throw std::invalid_argument("Results from different actions cannot be merged together."); 393 } 394 } 395 396public: 397 ///////////////////////////////////////////////////////////////////////////// 398 /// \brief Constructor that initializes data members. 399 /// \param[in] value The action result. 400 /// \param[in] counts The number of entries used to compute that result. 402 /** 403 Default constructor. Needed to allow serialization of ROOT objects. See 404 [TBufferFile::WriteObjectClass] 405 (classTBufferFile.html#a209078a4cb58373b627390790bf0c9c1) 406 */ 407 RMergeableMean() = default; 412}; 413 414template <typename T> 415class RMergeableMin final : public RMergeableValue<T> { 416 417 void Merge(const RMergeableValue<T> &other) final 418 { 419 try { 420 const auto &othercast = dynamic_cast<const RMergeableMin<T> &>(other); 421 this->fValue = std::min(this->fValue, othercast.fValue); 422 } catch (const std::bad_cast &) { 423 throw std::invalid_argument("Results from different actions cannot be merged together."); 424 } 425 } 426 427public: 428 ///////////////////////////////////////////////////////////////////////////// 429 /// \brief Constructor that initializes data members. 430 /// \param[in] value The action result. 432 /** 433 Default constructor. Needed to allow serialization of ROOT objects. See 434 [TBufferFile::WriteObjectClass] 435 (classTBufferFile.html#a209078a4cb58373b627390790bf0c9c1) 436 */ 437 RMergeableMin() = default; 438 RMergeableMin(const RMergeableMin &) = delete; 442}; 443 444/** 445\class ROOT::Detail::RDF::RMergeableStdDev 446\ingroup dataframe 447\brief Specialization of RMergeableValue for the 448[StdDev](classROOT_1_1RDF_1_1RInterface.html#a482c4e4f81fe1e421c016f89cd281572) 449action. 450 451This class also stores information about the number of entries and the average 452used to compute the standard deviation. 453*/ 454class RMergeableStdDev final : public RMergeableValue<Double_t> { 455 ULong64_t fCounts; ///< Number of entries of the set. 456 Double_t fMean; ///< Average of the set. 457 458 ///////////////////////////////////////////////////////////////////////////// 459 /// \brief Aggregate the information contained in another RMergeableValue 460 /// into this. 461 /// \param[in] other Another RMergeableValue object. 462 /// \throws std::invalid_argument If the cast of the other object to the same 463 /// type as this one fails. 464 /// 465 /// The other RMergeableValue object is cast to the same type as this object. 466 /// This is needed to make sure that only results of the same type of action 467 /// are merged together. The function then computes the aggregated standard 468 /// deviation of the two samples using an algorithm by 469 /// [Chan et al. (1979)] 470 /// (http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf) 471 /// 472 /// \note All the `Merge` methods in the RMergeableValue family are private. 473 /// To merge multiple RMergeableValue objects please use [MergeValues] 474 /// (namespaceROOT_1_1Detail_1_1RDF.html#af16fefbe2d120983123ddf8a1e137277). 475 void Merge(const RMergeableValue<Double_t> &other) final 476 { 477 try { 478 const auto &othercast = dynamic_cast<const RMergeableStdDev &>(other); 479 const auto &othercounts = othercast.fCounts; 480 const auto &othermean = othercast.fMean; 481 482 // Compute the aggregated variance using an algorithm by Chan et al. 483 // See https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm 484 const auto thisvariance = std::pow(this->fValue, 2); 485 const auto othervariance = std::pow(othercast.fValue, 2); 486 487 const auto delta = othermean - fMean; 488 489 const auto m_a = thisvariance * (fCounts - 1); 490 const auto m_b = othervariance * (othercounts - 1); 491 492 const auto sumcounts = static_cast<Double_t>(fCounts + othercounts); 493 494 const auto M2 = m_a + m_b + std::pow(delta, 2) * fCounts * othercounts / sumcounts; 495 496 const auto meannum = fMean * fCounts + othermean * othercounts; 497 498 // Update the data members 499 this->fValue = std::sqrt(M2 / (sumcounts - 1)); 500 fMean = meannum / sumcounts; 501 fCounts += othercounts; 502 } catch (const std::bad_cast &) { 503 throw std::invalid_argument("Results from different actions cannot be merged together."); 504 } 505 } 506 507public: 508 ///////////////////////////////////////////////////////////////////////////// 509 /// \brief Constructor that initializes data members. 510 /// \param[in] value The action result. 511 /// \param[in] counts The number of entries of the set. 512 /// \param[in] mean The average of the set. 514 : RMergeableValue<Double_t>(value), fCounts{counts}, fMean{mean} 515 { 516 } 517 /** 518 Default constructor. Needed to allow serialization of ROOT objects. See 519 [TBufferFile::WriteObjectClass] 520 (classTBufferFile.html#a209078a4cb58373b627390790bf0c9c1) 521 */ 522 RMergeableStdDev() = default; 527}; 528 529template <typename T> 530class RMergeableSum final : public RMergeableValue<T> { 531 532 void Merge(const RMergeableValue<T> &other) final 533 { 534 try { 535 const auto &othercast = dynamic_cast<const RMergeableSum<T> &>(other); 536 this->fValue += othercast.fValue; 537 } catch (const std::bad_cast &) { 538 throw std::invalid_argument("Results from different actions cannot be merged together."); 539 } 540 } 541 542public: 543 ///////////////////////////////////////////////////////////////////////////// 544 /// \brief Constructor that initializes data members. 545 /// \param[in] value The action result. 547 /** 548 Default constructor. Needed to allow serialization of ROOT objects. See 549 [TBufferFile::WriteObjectClass] 550 (classTBufferFile.html#a209078a4cb58373b627390790bf0c9c1) 551 */ 552 RMergeableSum() = default; 553 RMergeableSum(const RMergeableSum &) = delete; 557}; 558 559/** 560\class ROOT::Detail::RDF::RMergeableVariationsBase 561\ingroup dataframe 562\brief A container for variation names and variation results. 563 564The class stores two vectors: one with the variation names, the other with 565corresponding mergeable variation values. These are retrieved from an RVariedAction 566(resulting from a call to ROOT::RDF::VariationsFor). The results are stored as 567type-erased RMergeableValueBase objects. 568*/ 570protected: 571 std::vector<std::string> fKeys; 572 std::vector<std::unique_ptr<RMergeableValueBase>> fValues; 573 574public: 575 /** 576 Default constructor. Needed to allow serialization of ROOT objects. See 577 [TBufferFile::WriteObjectClass] 578 (classTBufferFile.html#a209078a4cb58373b627390790bf0c9c1) 579 */ 583 ///////////////////////////////////////////////////////////////////////////// 584 /// \brief Constructor that moves the data members from the input object. 585 /// \param[in] other The container from which the data members are moved. 586 /// 587 /// This constructor is needed as an helper in the RMergeableVariations 588 /// constructor that takes an RMergeableVariationsBase as input. 590 : fKeys{std::move(other.fKeys)}, fValues{std::move(other.fValues)} 591 { 592 } 594 595 ///////////////////////////////////////////////////////////////////////////// 596 /// \brief Constructor that initializes data members. 597 /// \param[in] keys The names of the variations. 598 /// \param[in] values The mergeable values containing the results of the 599 /// variations. 600 RMergeableVariationsBase(std::vector<std::string> &&keys, std::vector<std::unique_ptr<RMergeableValueBase>> &&values) 601 : fKeys{std::move(keys)}, fValues{std::move(values)} 602 { 603 } 604}; 605 606/** 607\class ROOT::Detail::RDF::RMergeableVariations 608\ingroup dataframe 609\brief A container for variation names and variation results that knows how to 610 merge with others of the same type. 611\tparam T Type of the action result. 612*/ 613template <typename T> 615 616 template <typename T1, typename... Ts> 617 friend void 618 MergeValues(RMergeableVariations<T1> &OutputMergeable, const RMergeableVariations<Ts> &... InputMergeables); 619 620 ///////////////////////////////////////////////////////////////////////////// 621 /// \brief Aggregate the information contained in another RMergeableVariations 622 /// into this. 623 /// \param[in] other The other mergeable. 624 /// 625 /// Iterates over all values of the current object and calls 626 /// ROOT::Detail::RDF::MergeValues to merge with the corresponding value of 627 /// the other object. 628 /// 629 /// \note All the `Merge` methods in the RMergeableValue family are private. 630 /// To merge multiple RMergeableValue objects please use ROOT::Detail::RDF::MergeValues 632 { 633 R__ASSERT(fKeys == other.fKeys && "Mergeable variations have different names."); 634 635 for (std::size_t i = 0; i < fValues.size(); i++) { 636 // Cast to concrete types according to MergeValues signature 637 MergeValues(static_cast<RMergeableValue<T> &>(*fValues[i]), 638 static_cast<const RMergeableValue<T> &>(*other.fValues[i])); 639 } 640 } 641 642public: 643 /** 644 Default constructor. Needed to allow serialization of ROOT objects. See 645 [TBufferFile::WriteObjectClass] 646 (classTBufferFile.html#a209078a4cb58373b627390790bf0c9c1) 647 */ 653 654 ///////////////////////////////////////////////////////////////////////////// 655 /// \brief Constructor that initializes data members. 656 /// \param[in] base The container of the names and values. 657 /// 658 /// The variation names and values are moved from the base container into this. 660 661 ///////////////////////////////////////////////////////////////////////////// 662 /// \brief Get the list of variation names. 663 const std::vector<std::string> &GetKeys() const { return fKeys; } 664 ///////////////////////////////////////////////////////////////////////////// 665 /// \brief Get the final value from the mergeable corresponding to a certain 666 /// variation name. 667 /// \param[in] variationName The name. 668 /// 669 /// The variation name is used to retrieve the corresponding RMergeableValue 670 /// contained in this object. From that, the actual value is retrieved by 671 /// calling the ROOT::Detail::RDF::RMergeableValue::GetValue function. 672 const T &GetVariation(const std::string &variationName) const 673 { 674 auto it = std::find(std::begin(fKeys), std::end(fKeys), variationName); 675 if (it == std::end(fKeys)) { 676 throw std::runtime_error("RMergeableVariations: no result with key \"" + variationName + "\"."); 677 } else { 678 auto pos = std::distance(std::begin(fKeys), it); 679 return static_cast<const RMergeableValue<T> &>(*fValues[pos]).GetValue(); 680 } 681 } 682}; 683 684/// \cond HIDDEN_SYMBOLS 685// What follows mimics C++17 std::conjunction without using recursive template instantiations. 686// Used in `MergeValues` to check that all the mergeables hold values of the same type. 687template <bool...> 688struct bool_pack { 689}; 690template <class... Ts> 691using conjunction = std::is_same<bool_pack<true, Ts::value...>, bool_pack<Ts::value..., true>>; 692/// \endcond 693 694//////////////////////////////////////////////////////////////////////////////// 695/// \brief Merge multiple RMergeableValue objects into one. 696/// \param[in] OutputMergeable The mergeable object where all the information 697/// will be aggregated. 698/// \param[in] InputMergeables Other mergeables containing the partial results. 699/// \returns An RMergeableValue holding the aggregated value wrapped in an 700/// `std::unique_ptr`. 701/// 702/// This is the recommended way of merging multiple RMergeableValue objects. 703/// This overload takes ownership of the mergeables and gives back to the user 704/// a mergeable with the aggregated information. All the mergeables with the 705/// partial results get destroyed in the process. 706/// 707/// Example usage: 708/// ~~~{.cpp} 709/// using namespace ROOT::Detail::RDF; 710/// // mh1, mh2, mh3 are std::unique_ptr<RMergeableValue<TH1D>> 711/// auto mergedptr = MergeValues(std::move(mh1), std::move(mh2), std::move(mh3)); 712/// const auto &mergedhisto = mergedptr->GetValue(); // Final merged histogram 713/// // Do stuff with it 714/// mergedhisto.Draw(); 715/// ~~~ 716template <typename T, typename... Ts> 717std::unique_ptr<RMergeableValue<T>> MergeValues(std::unique_ptr<RMergeableValue<T>> OutputMergeable, 718 std::unique_ptr<RMergeableValue<Ts>>... InputMergeables) 719{ 720 // Check all mergeables have the same template type 721 static_assert(conjunction<std::is_same<Ts, T>...>::value, "Values must all be of the same type."); 722 723 // Using dummy array initialization inspired by https://stackoverflow.com/a/25683817 724 using expander = int[]; 725 // Cast to void to suppress unused-value warning in Clang 726 (void)expander{0, (OutputMergeable->Merge(*InputMergeables), 0)...}; 727 728 return OutputMergeable; 729} 730 731//////////////////////////////////////////////////////////////////////////////// 732/// \brief Merge multiple RMergeableValue objects into one. 733/// \param[in,out] OutputMergeable The mergeable object where all the 734/// information will be aggregated. 735/// \param[in] InputMergeables Other mergeables containing the partial results. 736/// 737/// This overload modifies the mergeable objects in-place. The ownership is left 738/// to the caller. The first argument to the function will get all the 739/// values contained in the other arguments merged into itself. This is a 740/// convenience overload introduced for the ROOT Python API. 741/// 742/// Example usage: 743/// ~~~{.cpp} 744/// // mh1, mh2, mh3 are std::unique_ptr<RMergeableValue<TH1D>> 745/// ROOT::Detail::RDF::MergeValues(*mh1, *mh2, *mh3); 746/// const auto &mergedhisto = mh1->GetValue(); // Final merged histogram 747/// // Do stuff with it 748/// mergedhisto.Draw(); 749/// ~~~ 750template <typename T, typename... Ts> 751void MergeValues(RMergeableValue<T> &OutputMergeable, const RMergeableValue<Ts> &... InputMergeables) 752{ 753 // Check all mergeables are of the same type 754 static_assert(conjunction<std::is_same<Ts, T>...>::value, "Values must all be of the same type."); 755 756 // Using dummy array initialization inspired by https://stackoverflow.com/a/25683817 757 using expander = int[]; 758 // Cast to void to suppress unused-value warning in Clang 759 (void)expander{0, (OutputMergeable.Merge(InputMergeables), 0)...}; 760} 761 762//////////////////////////////////////////////////////////////////////////////// 763/// \brief Merge multiple RMergeableVariations objects into one. 764/// \param[in,out] OutputMergeable The mergeable object where all the 765/// information will be aggregated. 766/// \param[in] InputMergeables Other mergeables containing the partial results. 767/// 768/// This overload modifies the mergeable objects in-place. The ownership is left 769/// to the caller. The first argument to the function will get all the 770/// values contained in the other arguments merged into itself. This is a 771/// convenience overload introduced for the ROOT Python API. 772/// 773/// Example usage: 774/// ~~~{.cpp} 775/// // mv1, mv2 are std::unique_ptr<RMergeableVariations<TH1D>> 776/// ROOT::Detail::RDF::MergeValues(*mv1, *mv2); 777/// const auto &keys = mv1->GetKeys(); // Names of the variations 778/// // Do stuff with the variations 779/// for(const auto &key: keys){ 780/// const auto &histo = mv1->GetVariation(key); // Varied histogram 781/// std::cout << histo.GetEntries() << "\n"; 782/// } 783/// ~~~ 784template <typename T, typename... Ts> 785void MergeValues(RMergeableVariations<T> &OutputMergeable, const RMergeableVariations<Ts> &... InputMergeables) 786{ 787 // Check all mergeables are of the same type 788 static_assert(conjunction<std::is_same<Ts, T>...>::value, "Values must all be of the same type."); 789 790 // Using dummy array initialization inspired by https://stackoverflow.com/a/25683817 791 using expander = int[]; 792 // Cast to void to suppress unused-value warning in Clang 793 (void)expander{0, (OutputMergeable.Merge(InputMergeables), 0)...}; 794} 795} // namespace RDF 796} // namespace Detail 797} // namespace ROOT 798 799#endif // ROOT_RDF_RMERGEABLEVALUE unsigned long long ULong64_t Definition: RtypesCore.h:81 #define R__ASSERT(e) Definition: TError.h:118 Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value Specialization of RMergeableValue for the Count action. RMergeableCount(const RMergeableCount &)=delete void Merge(const RMergeableValue< ULong64_t > &other) final Aggregate the information contained in another RMergeableValue into this. RMergeableCount()=default Default constructor. RMergeableCount(ULong64_t value) Constructor that initializes data members. RMergeableCount & operator=(RMergeableCount &&)=delete RMergeableCount(RMergeableCount &&)=delete RMergeableCount & operator=(const RMergeableCount &)=delete Specialization of RMergeableValue for histograms and statistics. auto DoMerge(const RMergeableFill< U > &other, double) -> decltype(this->fValue.Merge(std::vector< U * >{}), void()) auto DoMerge(const RMergeableFill< U > &other, int) -> decltype(((U &) this->fValue).Merge((TCollection *) nullptr), void()) RMergeableFill()=default Default constructor. RMergeableFill(RMergeableFill &&)=delete RMergeableFill(const T &value) Constructor that initializes data members. RMergeableFill & operator=(RMergeableFill &&)=delete void Merge(const RMergeableValue< T > &other) final Aggregate the information contained in another RMergeableValue into this. RMergeableFill & operator=(const RMergeableFill &)=delete RMergeableFill(const RMergeableFill &)=delete RMergeableMax(const T &value) Constructor that initializes data members. void Merge(const RMergeableValue< T > &other) final Aggregate the information contained in another RMergeableValue into this. RMergeableMax()=default Default constructor. RMergeableMax & operator=(const RMergeableMax &)=delete RMergeableMax(RMergeableMax &&)=delete RMergeableMax & operator=(RMergeableMax &&)=delete RMergeableMax(const RMergeableMax &)=delete Specialization of RMergeableValue for the Mean action. RMergeableMean(Double_t value, ULong64_t counts) Constructor that initializes data members. RMergeableMean(const RMergeableMean &)=delete ULong64_t fCounts The number of entries used to compute the mean. RMergeableMean()=default Default constructor. RMergeableMean & operator=(const RMergeableMean &)=delete void Merge(const RMergeableValue< Double_t > &other) final Aggregate the information contained in another RMergeableValue into this. RMergeableMean(RMergeableMean &&)=delete RMergeableMean & operator=(RMergeableMean &&)=delete RMergeableMin()=default Default constructor. RMergeableMin(RMergeableMin &&)=delete RMergeableMin(const RMergeableMin &)=delete RMergeableMin(const T &value) Constructor that initializes data members. void Merge(const RMergeableValue< T > &other) final Aggregate the information contained in another RMergeableValue into this. RMergeableMin & operator=(const RMergeableMin &)=delete RMergeableMin & operator=(RMergeableMin &&)=delete Specialization of RMergeableValue for the StdDev action. RMergeableStdDev(Double_t value, ULong64_t counts, Double_t mean) Constructor that initializes data members. void Merge(const RMergeableValue< Double_t > &other) final Aggregate the information contained in another RMergeableValue into this. RMergeableStdDev(const RMergeableStdDev &)=delete RMergeableStdDev & operator=(RMergeableStdDev &&)=delete ULong64_t fCounts Number of entries of the set. RMergeableStdDev(RMergeableStdDev &&)=delete Double_t fMean Average of the set. RMergeableStdDev & operator=(const RMergeableStdDev &)=delete RMergeableStdDev()=default Default constructor. RMergeableSum()=default Default constructor. RMergeableSum(const T &value) Constructor that initializes data members. RMergeableSum(const RMergeableSum &)=delete RMergeableSum & operator=(RMergeableSum &&)=delete RMergeableSum(RMergeableSum &&)=delete void Merge(const RMergeableValue< T > &other) final Aggregate the information contained in another RMergeableValue into this. RMergeableSum & operator=(const RMergeableSum &)=delete Base class of RMergeableValue. RMergeableValueBase()=default Default constructor. RMergeableValueBase(RMergeableValueBase &&)=delete RMergeableValueBase & operator=(RMergeableValueBase &&)=delete RMergeableValueBase & operator=(const RMergeableValueBase &)=delete RMergeableValueBase(const RMergeableValueBase &)=delete A result of an RDataFrame execution, that knows how to merge with other results of the same type. RMergeableValue()=default Default constructor. RMergeableValue(const RMergeableValue &)=delete RMergeableValue(RMergeableValue &&)=delete const T & GetValue() const Retrieve the result wrapped by this mergeable. RMergeableValue & operator=(const RMergeableValue &)=delete friend void MergeValues(RMergeableValue< T1 > &OutputMergeable, const RMergeableValue< Ts > &... InputMergeables) friend std::unique_ptr< RMergeableValue< T1 > > MergeValues(std::unique_ptr< RMergeableValue< T1 > > OutputMergeable, std::unique_ptr< RMergeableValue< Ts > >... InputMergeables) RMergeableValue(const T &value) Constructor taking the action result by const reference. virtual void Merge(const RMergeableValue< T > &)=0 Aggregate the information contained in another RMergeableValue into this. RMergeableValue & operator=(RMergeableValue &&)=delete A container for variation names and variation results. RMergeableVariationsBase()=default Default constructor. RMergeableVariationsBase & operator=(RMergeableVariationsBase &&)=delete std::vector< std::unique_ptr< RMergeableValueBase > > fValues RMergeableVariationsBase(std::vector< std::string > &&keys, std::vector< std::unique_ptr< RMergeableValueBase > > &&values) Constructor that initializes data members. RMergeableVariationsBase & operator=(const RMergeableVariationsBase &)=delete RMergeableVariationsBase(const RMergeableVariationsBase &)=delete RMergeableVariationsBase(RMergeableVariationsBase &&other) Constructor that moves the data members from the input object. A container for variation names and variation results that knows how to merge with others of the same... void Merge(const RMergeableVariations< T > &other) Aggregate the information contained in another RMergeableVariations into this. const T & GetVariation(const std::string &variationName) const Get the final value from the mergeable corresponding to a certain variation name. RMergeableVariations & operator=(const RMergeableVariations &)=delete RMergeableVariations()=default Default constructor. RMergeableVariations & operator=(RMergeableVariations &&)=delete const std::vector< std::string > & GetKeys() const Get the list of variation names. RMergeableVariations(RMergeableVariations &&)=delete RMergeableVariations(RMergeableVariationsBase &&base) Constructor that initializes data members. friend void MergeValues(RMergeableVariations< T1 > &OutputMergeable, const RMergeableVariations< Ts > &... InputMergeables) RMergeableVariations(const RMergeableVariations &)=delete Collection abstract base class. Definition: TCollection.h:65 A doubly linked list. Definition: TList.h:38 RVec< PromoteTypes< T0, T1 > > pow(const T0 &x, const RVec< T1 > &v) Definition: RVec.hxx:1753 #define T1 Definition: md5.inl:146 std::unique_ptr< RMergeableValue< T > > MergeValues(std::unique_ptr< RMergeableValue< T > > OutputMergeable, std::unique_ptr< RMergeableValue< Ts > >... InputMergeables) Merge multiple RMergeableValue objects into one. void(off) SmallVectorTemplateBase< T double T(double x) Definition: ChebyshevPol.h:34 VecExpr< UnaryOp< Sqrt< T >, VecExpr< A, T, D >, T >, T, D > sqrt(const VecExpr< A, T, D > &rhs) This file contains a specialised ROOT message handler to test for diagnostic in unit tests. auto * l Definition: textangle.C:4
__label__pos
0.51291
堆(pmalloc)入门 发布于 2020-03-01  839 次阅读 堆介绍 什么是堆 在程序运行的过程中,我们会向操作系统申请内存来对数据进行存储。堆其实就是程序虚拟地址空间的一块连续的线性区域,它由低地址向高地址 (不同于栈)方向增长。堆块中的 user data 区域就是我们所申请的内存。用来管理堆的程序叫做堆管理器。 堆管理器 由于本人才疏学浅,只了解 Linux 的堆管理器。目前 Linux 标准发行版中使用的堆分配器是 glibc 中的堆分配器:ptmalloc2。ptmalloc2 主要是通过 malloc/free 函数来分配和释放内存块。 malloc C语言中用于申请内存的函数,当我们调用函数之后,程序会返回一个内存地址,这块区域可供用户进行读写操作。 具体过程如下: 1. 堆管理器会向操作系统申请 132KB 的空间,称为 top chunk ,供 ptmalloc 对程序进行内存的分配。不论程序申请的空间为多少,堆管理器都会首先申请 132KB 。 2. 堆管理器会对刚刚申请的空间进行切割,并将切割得到的堆块作为 malloc 的返回值送给用户程序。 free 与malloc相对的函数,能将申请的堆块重新放入 ptmalloc 的分配区(main_arena)中。 1. 堆块是否属于 fastbin (后文会提到)?fastbin 是不会被合并的,其他的 bin 会被合并到 top chunk 中,但是注意:free 掉的堆块不会马上合并,要注意第二条。 2. top chunk 是否与该堆块相邻?与 top chunk 不相邻的堆块会进入相应的 bin 当中。 3. 如果该堆块旁有一个已经 free 掉的非 fastbin 堆块,它会和那个堆块进行合并,这个过程称为 unlink 4. 其他规则(还没学QAQ) 堆块结构 这是一个正在使用的堆块的结构(以64位系统为例),从上到下地址依次增加 Snipaste_2020-03-02_23-11-42.png 1. prev_size 标识对前一个堆块的 size 。如果前一个堆块正被使用,那么它为 0 。 2. size 表示当前堆块的 size 。其中这个字段的最低位为 prev_inuse ,为了表示前一个堆块的使用情况。若正被使用则为 1 。size 的大小一定会是 16(x64)/ 8(x32)的整数倍。 3. 若 malloc 的大小的个位 大于 0 ,小于等于 8 (比如 0x32),那么 prev_size 的八字节会被拿来保存前一个堆块的多余信息。 4. user_data 是 pmalloc 分配的内存空间,ptr 则为 malloc 函数所返回的地址。 bins main_arena 是一个指针数组 *char main_arena[]** 里面保存了各个 bin 的起始地址的指针 ,包括 fast_bin , small_bin , large_bin fastbin 我们先写一个小程序 #include<stdio.h> int main(){ char *p1 = malloc(0x20); char *p2 = malloc(0x21); gets(p1); gets(p2); free(p1); free(p2); } gcc test.c -o test 并打开 gdb 进行调试: gdb test b main r 我们定位到 gets 函数,将 p1、p2 的内存地址对应的区域找到,并且分别输入 'a' 8 、 'b' 8 Snipaste_2020-03-02_23-34-20.png pwndbg> x /32gx 0x602010-16 0x602000: 0x0000000000000000 0x0000000000000031 0x602010: 0x6161616161616161 0x0000000000000000 0x602020: 0x0000000000000000 0x0000000000000000 0x602030: 0x0000000000000000 0x0000000000000031 0x602040: 0x6262626262626262 0x0000000000000000 0x602050: 0x0000000000000000 0x0000000000000000 下面解释各个位置的名称 0x602000:prev_size 0x602008:size (因为是第一个堆块,所以它的 prev_inuse 一定是 1,而且因为是 fastbin ,所以 prev_inuse 始终为 1 ,这里需要注意 0x602010:user_data 现在我们继续, free 掉 p1 n 可以看到 p1 的 user_data 被清空了 Snipaste_2020-03-02_23-34-20.png 继续 free 掉 p2 n 可以看到 p2 的 user_data 处被替换为了 p1 的堆块地址 Snipaste_2020-03-02_23-34-20.png 这里就得提到 fastbin 的 FILO(先进后出) fastbin 是一个单向链表。作为 fastbin 的堆块,P1 会被 main_arena 的 0x30 指针所指 而 P2 加入时, 这个指针会被重新指向 P2,然后 P2 会指向 P1 P2 的 fd 是 user_data 的前 8 Bytes ,用来指向 P1,P1 因为没有结点可指,所以是 0 Snipaste_2020-03-02_23-34-20.png small_bin 与 fast_bin 差别不大, 但是在回收到 small_bin (之前会先进入 unsorted bin)的过程中,它会被回收到一个双向链表中。 同时 prev_size 的标志会被启用,这个在 unlink 知识点上有所应用 因为 small_bin 是用双向链表进行存储的,所以它的 user_data 的前 16Bytes 分别为 fdbk,指向下一个堆块或者前一个堆块,这一点在我们进行 unlink 的时候非常有用。 同时,像 small_bin 一样的双向链表, 第一个加入其中的堆块,他的 fdbk 都会等于同一个值,即 main_arena + offset, 这就是 use_after_free 的原理,可以写泄露 libc 的地址。 Snipaste_2020-03-02_23-34-20.png unsorted bin unsorted bin 是一个存放除 fast_bin 之外 free 掉后的堆块的双向链表。 small_bin 、 large_bin free 掉之后,第一时间会被放入 unsorted bin 其中 unsorted bin 会在下一次 malloc 的时候被检索以及利用,未被利用的区块会被放入 相应的 bins ,具体过程如下: malloc一个不属于 fastbin 大小的 chunk 的时候,会先在 small bin 和 large bin 里面搜索,如果搜到则直接进行使用 如果没有搜到就搜索 unsorted bin,这个过程中会将 unsorted bin 清空,把区块放入相应的 bin 如果 unsorted bin 搜索完了之后还没有给申请的 chunk 分配,便会从 top chunk 处进行切割 ​ -- SuperGate double free & use after free double free 的原理是:利用 fastbin 对 fd 不检测的特性,将曾经 free 过的堆块再 free 一次,形成一个循环链表。 当然也不是说完全没有检测,如果你连续 free 同一个堆块两次,就会触发 err: /* Another simple check: make sure the top of the bin is not the record we are going to add (i.e., double free). */ if (__builtin_expect (old == p, 0)) { errstr = "double free or corruption (fasttop)"; goto errout; } Snipaste_2020-03-04_00-08-13.png 例题 Roc826s_Note.zip 这个程序提供了 add、delete、show 功能,模板题。 由于 system 地址未知,我们需要泄露 libc 的基地址。 需要了解:在 small bin 、large bin free 掉了之后,如果 unsorted bin 的双向链表只有一个堆块,这个堆块的 fd 和 bk 都等于 main_arena + offset 我们申请一个 small bin 并 free 掉它来获取 libc 基地址。 注意:必须多 malloc 一个其他堆块,否则 small bin 堆块会被合并至 top chunk 前面说过,我们得到了 main_arena + offset 的地址,通过查看内存我们可知 main_arena - 0x8 正是 malloc_hook 的地址,通过这个我们就可以成功通过减法算出 libc_base 我们通过构造两个 fastbin chunk(P1、P2),按照 P1、P2、P1的顺序 free 掉,这样就会形成 main_arena->P1->P2->P1 的循环链表,这个程序并没有检测堆块的状态,所以才能这样攻击。 然后我们 malloc 三次同样大小的 fast_bin chunk,其中在第一次 malloc 时填充 free_got 的地址,目的是后面对其进行修改。 malloc 第三次时,pmalloc 再次对 P1 进行 malloc,它检测到 user_data 的前八个字节(也就是 fd )有内容,便被欺骗,将下一个 malloc 的地址设置为我们刚刚写入的 free_got。 这里有一个检测,pmalloc 会在进行下一次 malloc 的时候检测该堆块是否合法。即这个堆块的 size 是否等于 fastbin 的 size (包括 prev_inuse位) 然后我们再次进行写入,由于上方的检测行为,我们应该在 free_got 的地址之前找一块 8Bytes 的区域,这个长整数刚刚等于 fastbin 的size,(包括 prev_inuse位),通常寻找 0x7f,因为 got 表中的大多数地址都被初始化,指向了 libc 的地址。然后用 padding 填充偏移的字符个数,最终就能成功把 got 表修改。 from pwn import * context.log_level = 'DEBUG' p = process('./roc826') elf = ELF('./roc826') libc = ELF('./libc-2.23.so') free_got = elf.got['free'] def add(size, text='aa'): p.sendlineafter(':','1') p.sendlineafter('size?',str(size)) p.sendlineafter('content:',text) def dele(idx): p.sendlineafter(':','2') p.sendlineafter('index?',str(idx)) p.recv() def show(idx): p.sendlineafter(':','3') p.sendlineafter('index?',str(idx)) add(0x80) # make a small bin to start uaf attack add(0x58) # fastbin add(0x58) # fastbin add(0x58,'/bin/sh\x00') # fastbin dele(0) # small bin's user data becomes addr of main_arina show(0) # show main_arina addr p.recvuntil("content:") libc_base = u64(p.recv(6) + '\x00\x00') - libc.symbols['__malloc_hook'] - 0x68 success('libc:'+hex(libc_base)) system_addr = libc_base + libc.symbols['system'] dele(1) # free dele(2) # free dele(1) # make a self-pointed table fastbin->node1->node2->node1 add(0x58, p64(0x601ffa)) # fill fd with the addr of free_got(there is a specified place can serve as a 'size') add(0x58, p64(0x601ffa)) add(0x58, p64(0x601ffa)) add(0x58, 'aaaaaaaaaaaaaa' + p64(libc_base + libc.symbols['system'])[:6]) dele(3) p.interactive() unlink (本题先讨论 fake_chunk 在 next_chunk 之前的情况) unlink 的前提:堆块地址明确,并且有一个指针指向相应堆块。(后面会讲为什么) unlink 的原理是:在大堆块的 user_data 上伪造一个 fake_chunk (并且在 next_size 上面标记 prev_inuse = 0),利用 unlink 宏,在 free 掉相邻堆块时, 1. fake_chunk 会先被从 small_bin / large_bin / unsorted_bin 中拿出来,这个脱离原链表的过程会调用 unlink 2. 相邻堆块会与虚假堆块进行合并,并且扩展 fake_chunk 的 size (这一步一般没办法利用) 我在图中标明了 pre_chunk 和 next_chunk ,但并不代表它们从一开始就是有指针指向的关系的,只是说它们的目标是要合并到一起。 Snipaste_2020-03-04_01-08-33.png 当然 pmalloc 的安全检测机制没那么简单啦。 以下是源码中的宏定义: /* Take a chunk off a bin list */ // unlink p #define unlink(AV, P, BK, FD) { \ // 由于 P 已经在双向链表中,所以有两个地方记录其大小,所以检查一下其大小是否一致。 if (__builtin_expect (chunksize(P) != prev_size (next_chunk(P)), 0)) \ malloc_printerr ("corrupted size vs. prev_size"); \ FD = P->fd; \ BK = P->bk; \ // 防止攻击者简单篡改空闲的 chunk 的 fd 与 bk 来实现任意写的效果。 if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \ malloc_printerr (check_action, "corrupted double-linked list", P, AV); \ else { \ FD->bk = BK; \ BK->fd = FD; \ // 下面主要考虑 P 对应的 nextsize 双向链表的修改 if (!in_smallbin_range (chunksize_nomask (P)) \ // 如果P->fd_nextsize为 NULL,表明 P 未插入到 nextsize 链表中。 // 那么其实也就没有必要对 nextsize 字段进行修改了。 // 这里没有去判断 bk_nextsize 字段,可能会出问题。 && __builtin_expect (P->fd_nextsize != NULL, 0)) { \ // 类似于小的 chunk 的检查思路 if (__builtin_expect (P->fd_nextsize->bk_nextsize != P, 0) \ || __builtin_expect (P->bk_nextsize->fd_nextsize != P, 0)) \ malloc_printerr (check_action, \ "corrupted double-linked list (not small)", \ P, AV); \ // 这里说明 P 已经在 nextsize 链表中了。 // 如果 FD 没有在 nextsize 链表中 if (FD->fd_nextsize == NULL) { \ // 如果 nextsize 串起来的双链表只有 P 本身,那就直接拿走 P // 令 FD 为 nextsize 串起来的 if (P->fd_nextsize == P) \ FD->fd_nextsize = FD->bk_nextsize = FD; \ else { \ // 否则我们需要将 FD 插入到 nextsize 形成的双链表中 FD->fd_nextsize = P->fd_nextsize; \ FD->bk_nextsize = P->bk_nextsize; \ P->fd_nextsize->bk_nextsize = FD; \ P->bk_nextsize->fd_nextsize = FD; \ } \ } else { \ // 如果在的话,直接拿走即可 P->fd_nextsize->bk_nextsize = P->bk_nextsize; \ P->bk_nextsize->fd_nextsize = P->fd_nextsize; \ } \ } \ } \ } 一言以蔽之,pmalloc 将 fake_chunk 当作 P 检测: 1. P -> fd -> bk == P 2. P -> bk -> fd == P (注意:P -> fd != next_chunk,P -> fd 是一个我们伪造出来的假 chunk) 这样就不能对数据进行随意修改了,但是,如果我们有一个指向 fake_chunk指针 (通常是在信息管理系统的指针数组中存在,这里用 pointer_addr 代替),将 1. fake_fd 修改为 pointer_addr - 0x18 2. fake_bk 修改为 pointer_addr - 0x10 就可以绕过检测,因为对于任意一个堆块, fd = chunk_addr + 0x10 ,bk = chunk_addr + 0x18 Snipaste_2020-03-04_11-45-08.png 接下来 堆块之间会进行修改: 1. P -> fd -> bk = P -> bk 2. P -> bk -> fd = P -> fd 由于 P -> bk -> fd = P -> fd -> bk = List+0 以及两个操作的先后性,最终 List+0 被修改为 P -> fd,如下图: Snipaste_2020-03-04_11-45-08.png 然后再通过 List 修改自身,使其指向 got 表即可。 总结:其实 next_chunk 只起到了触发 unlink 的作用,并且协助检测了 fake_chunk 的合法性,在 unlink 的修改过程中, next_chunk 没有参与,至于 unlink 之后的堆块合并过程,也不是我们的关注点了。 参考资料 Annevi 这道题和上面一道题类似,不过 1. 限制了堆块的最小 size:0x144,即不能使用 fastbin attack。 2. 增加了 edit 功能,可以对堆块进行修改 3. 用一个数组对每个堆块的使用状况进行检查,我们不能对 free_chunk 进行 delete、show 操作 这个对 libc 的获取并不会产生影响,我们同样的 malloc 一个 small_chunk,在之后 free 掉,然后 重新申请该堆块,并且写入'\n' (这样就成功绕过了堆块状态的检测,同时只损失了 main_arena + offset 的最低位,而 main_arena 的最低位一定是 0x00,所以没有任何影响),成功获取 libc 地址。 from pwn import * from LibcSearcher import * from time import sleep context.log_level = 'DEBUG' p = process('./annevi') elf = ELF('./annevi') def add(size, text = 'aa'): p.sendlineafter(':','1') p.sendlineafter('size?', str(size)) p.sendlineafter('content:', text) def dele(idx): p.sendlineafter(':','2') p.sendlineafter('index?', str(idx)) def show(idx): p.sendlineafter(':','3') p.sendlineafter('index?', str(idx)) def edit(idx, text = 'bb'): p.sendlineafter(':','4') p.sendlineafter('index?', str(idx)) p.sendlineafter('content:', text) add(0x90) add(0x90) add(0x90) add(0x90, '/bin/sh\x00') #gdb.attach(p) dele(0) add(0x90, '') show(0) #leak the addr of main_arena p.recvuntil('content:') malloc_hook_addr = u64(p.recv(6)+'\x00\x00e') - 0xa + 0x10 # must be careful, cause the lowest byte has been changed success('malloc_hook_addr = ' + hex(malloc_hook_addr)) #libc = LibcSearcher('__malloc_hook', malloc_hook_addr) #libc_base = malloc_hook_addr - libc.dump('__malloc_hook') libc = ELF('/lib/x86_64-linux-gnu/libc.so.6',checksec=False) libc_base = malloc_hook_addr - libc.symbols['__malloc_hook'] success('libc_base = ' + hex(libc_base)) payload1 = p64(0) + p64(0x91) + p64(0x602048-0x18) + p64(0x602048 - 0x10) + '\x00' * 0x70 + p64(0x90) + p64(0xa0) # make a fake_chunk and its fake_fd, fake_bk as well as next chunk's presize, size #gdb.attach(p) edit(1, payload1) dele(2) # unlink payload2 = '\x00'*0x18 + p64(libc_base + libc.symbols['__free_hook']) # edit the addr of list[1] edit(1, payload2) edit(1, p64(libc_base + libc.symbols['system'])) # edit got p.sendline('2') sleep(0.1) p.sendline('3') # free('/bin/sh') p.interactive() off by one off by one 就是利用系统对非法内存的一个字节的修改来达到任意地址修改的目的。 对非法内存的修改情况可能有: 1. 人为失误,将 for(int a = 0; a < 5; a++) 这类循环的小于符号写成了小于等于,导致多写。 2. 自带库的特性,比如 c语言中字符串的结尾必须是 ‘/x00’,一些库函数对末尾赋零时可能会超出字符串内存范围。 E99 题目也与上面的类似,不过多了 edit 堆块大小的限制,必须在申请的堆块大小范围之内 这里讨论的是人为失误, 本题的 read_n 函数边界条件错误,使得我们可以通过多修改一个字节来达到修改 next_chunk 的 size。 __int64 __fastcall read_n(__int64 a1, int a2) { int i; // [rsp+1Ch] [rbp-4h] for ( i = 0; i <= a2; ++i ) { read(0, (void *)(i + a1), 1uLL); if ( *(_BYTE *)(i + a1) == 10 ) break; } return 0LL; } 总体思路: 创建三个堆块,其中第二个堆块必须是 fast_chunk,在修改第一个堆块的过程中,利用 off_by_one 的溢出漏洞修改下一个堆块的 size,使其大小能够覆盖第三个堆块(便于修改),然后将第二个第三个堆块 free 掉。 这样 unsorted bin 和 fast bin 就有了相关的指针,然后我们再重新利用 add 功能先申请到第二个堆块 small_chunk(从 unsorted bin)。 现在我们就拥有了 第二个和第三个堆块的完整控制权,也绕过了 edit 函数的 size 限制,然后我们就可以进行 fastbin attack 了,改掉 fast_chunk 的 fd, 再新申请堆块三,下一次申请 fast_chunk 时,就可以指定位置修改内存了(注意在这里构造 payload 还是需要寻找目标地址前面 size 刚好符合的位置)。 #coding=utf8 from pwn import * import time context.log_level = 'debug' context.terminal = ['gnome-terminal','-x','bash','-c'] local = 1 binary_name = 'e99' if local: cn = process('./'+binary_name) libc = ELF('/lib/x86_64-linux-gnu/libc.so.6',checksec=False) #libc = ELF('/lib/i386-linux-gnu/libc-2.23.so',checksec=False) else: cn = remote('47.103.214.163',20302) libc = ELF('/lib/x86_64-linux-gnu/libc.so.6',checksec=False) ru = lambda x : cn.recvuntil(x) sn = lambda x : cn.send(x) rl = lambda : cn.recvline() sl = lambda x : cn.sendline(x) rv = lambda x : cn.recv(x) sa = lambda a,b : cn.sendafter(a,b) sla = lambda a,b : cn.sendlineafter(a,b) ia = lambda : cn.interactive() bin = ELF('./'+binary_name,checksec=False) one1=0x45216 #execve("/bin/sh", rsp+0x30, environ) rax == NULL one2=0x4526a #execve("/bin/sh", rsp+0x30, environ) [rsp+0x30] == NULL''' one3=0xf02a4 #execve("/bin/sh", rsp+0x50, environ) [rsp+0x50] == NULL''' one4=0xf1147 #execve("/bin/sh", rsp+0x70, environ) [rsp+0x70] == NULL''' def z(a=''): if local: gdb.attach(cn,a) if a == '': raw_input() else: pass def add(sz,con='aa'): sla(':','1') sla('size?',str(sz)) sla('content:',con) def show(idx): sla(':','3') sla('index?',str(idx)) def edit(idx,con): sla(':','4') sla('index?',str(idx)) sa('content:',con) def dele(idx): sla(':','2') sla('index?',str(idx)) add(0x88) # chunk0 add(0x88) # chunk1 add(0x78) # chunk2 add(0x68) # chunk3 #add(0x88,'/bin/sh') dele(0) add(0x88,'') show(0) cn.recvuntil("content:") lbase=u64(cn.recv(6)+'\x00\x00')-libc.sym['__malloc_hook']+6 success('libc:'+hex(lbase)) # leak libc base pay='\x00'*0x88+'\xf1' # off_by_one create a fake chunk with size 0xf1 edit(1,pay) dele(2) # put the fake_chunk into unsorted bin dele(3) # put fast_chunk into fast bin pay2='\x00'*0x78+p64(0x71)+p64(lbase+libc.sym['__malloc_hook']-0x23) add(0xd8,pay2) # fastbin attack add(0x68) # padding add(0x68,'a'*19+p64(lbase+one4)) # change got sl('1') sl('1') # getshell ia() CTFer|NOIPer|CSGO|摸鱼|菜鸡
__label__pos
0.554694
<BUG> undoing DOP on audio event brings back entire file Cut a segment of audio from a larger file. Apply some DOP - for example time stretch. All good. Remove that process - process is removed but brings back the entire length of the original file instead of just the event previously cut out. Hi, Did you have only one instance of the file in the Project? How exactly did you remove the process, please? Hmm can’t reproduce at the moment but it happened several times during an e-learning project. I’ll see what happens if it happens again.
__label__pos
0.743703
TechAlpine – The Technology world Data Compression and Decompression Using Java Data Compression Data Compression Using Java Overview: In any software application, be it client-server or distributed, data transfer is always there. So, the architecture of an application is designed to ease the data transfer process and improve the performance. One simple solution to manage this huge volume of data is to add more storage and improve communication between the two ends (namely client and server or storage system). But the problem is, additional storage and communication infrastructure needs more investment, which is not always possible. The alternate solution is to use data compression technology. In this article, we will focus on data compression and decompression and how it can be handled by Java applications. How data compression works? Data compression can be achieved in different ways. Here we will discuss some basic concepts and compression techniques. Compression mainly removes the redundancy in a data set by applying intelligent techniques to represent it. The simplest form of redundancy is repetition of similar characters in a string of data. And, compression techniques usually compact the string and remove redundant characters. For example, check the following string; it has lot of redundant characters which can be represented in a different way. EEEEDDUUUOONNIIXX Let’s compact the string as shown below. It represents the same string with a different technique. 4E2D3U2O2N2I2X There are different other ways also for data compression. But the basic concept is same as discussed above. What is the difference between ZIP and GZIP? We must have used ZIP and GZIP utilities in many cases for compressing or decompressing files. But there is a difference between the usages of these utilities. In Windows environment, WinZip tool is used for file compression and decompression. But in UNIX environment, it is performed in a different way. First, ‘tar ‘utility is used to create an archive and then GZIP is used to compress the archived files. So, in UNIX it is a two-step process whereas in Windows both archiving and compression is done in a single step. How Java works with ZIP files? Java as a language provides lot of packages to work with data compression and decompression. The main utility package is java.util.zip, which is used to compress zip compatible files. These packages provide different classes to read, write. create, modify GZIP and ZIP file formats. They also have checksums to validate the size before and after compression. Different Java utilities related to data compression and decompression can be checked in Oracle documentation. Let’s try some examples In this section we will try two examples, one with file compression and the other one with file decompression. File compression example: In this example, we will check how Java application can be used to compress a file and make an archive. Here we have used a single file named ‘firstfile.txt’ to compress. The file will be compressed in a zip file named as ‘FileArchive.zip’. The example program can be modified to compress multiple numbers of files using a loop. The files can be created at any location and the path has to specify in the application. We have kept both the files in a single location where the Java application is kept (for simplicity). Listing1: Example showing file compression using Java [code] import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class FileCompress { public static void main( String[] args ) { byte[] buffersz = new byte[1024]; try{ //Create different input and output streams FileOutputStream floutstr = new FileOutputStream(“FileArchive.zip”); ZipOutputStream zpoutstr = new ZipOutputStream(floutstr); //Add the files to be compressed ZipEntry zpentry= new ZipEntry(“firstfile.txt”); zpoutstr.putNextEntry(zpentry); //Create file input stream FileInputStream finstrm = new FileInputStream(“firstfile.txt”); //Write to the zip output stream int lenstrm; while ((lenstrm = finstrm.read(buffersz)) > 0) { zpoutstr.write(buffersz, 0, lenstrm); } //Close file input stream finstrm.close(); //Close zip output stream and entry zpoutstr.closeEntry(); zpoutstr.close(); System.out.println(“File compression done successfully”); }catch(IOException ex){ ex.printStackTrace(); } } } [/code] After the Java program is compiled and executed, a zip file will be created at the same location. Now, extract the zip file and you will find the file ‘firstfile.txt’ kept inside it. Following screen shot shows the output and other details as described above. Data Compression Image 1: Shows file compression output  File decompression example: In this example, we will check how to decompress a file from a zip file. We will use the same zip file above ‘FileArchive.zip’ and extract the content inside it. It will extract the file ‘FileArchive.zip’ in an output directory.   Listing 2: File decompression using Java [code] import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class FileDecompress { List<String> listOfFiles; private static final String ZIP_FILE_INPUT = “FileArchive.zip”; private static final String ZIP_OUTPT_FLDR = “Zipoutput”; public static void main( String[] args ) { FileDecompress unZipFile = new FileDecompress(); unZipFile.unZipFile(ZIP_FILE_INPUT,ZIP_OUTPT_FLDR); } public void unZipFile(String zipFileName, String outpfFldr){ byte[] bufferlen = new byte[1024]; try{ //Create output folder/directory (if not exist) File foldernm = new File(ZIP_OUTPT_FLDR); if(!foldernm.exists()){ foldernm.mkdir(); } //Getting zip file content ZipInputStream zipinstrm =    new ZipInputStream(new FileInputStream(zipFileName)); //Get the list entry ZipEntry zipentry = zipinstrm.getNextEntry(); while(zipentry!=null){ String fileNm = zipentry.getName(); File newFileName = new File(outpfFldr + File.separator + fileNm); System.out.println(“Unzipped file name is : “+ newFileName.getAbsoluteFile()); FileOutputStream foutstrm = new FileOutputStream(newFileName); int lenstrm; while ((lenstrm = zipinstrm.read(bufferlen)) > 0) { foutstrm.write(bufferlen, 0, lenstrm); } foutstrm.close(); zipentry = zipinstrm.getNextEntry(); } zipinstrm.closeEntry(); zipinstrm.close(); System.out.println(“Files decompressed successfully”); }catch(IOException ex){ ex.printStackTrace(); } } } [/code] Now compile and execute the Java file as shown below. It will create an output directory and put the extracted file there. Following screen shot shows the details. Data decompression Image 2: Shows file decompression output Conclusion: Data compression and decompression is very important in any software application. Here, we have discussed about Java APIs which can be used for the same purpose. We have also discussed some basic concepts of data compression and how it is achieved internally. Java examples are also explained with file compression and decompression. There are also different other ways to perform the same task, but these simple examples will help you understand the basics and implement in your application development.   Please follow and like us: 0 Leave a Reply Your email address will not be published. Required fields are marked * 8 + = 11 ============================================= ============================================== Buy TechAlpine Books on Amazon ============================================== ---------------------------------------------------------------- Enjoy this blog? Please spread the word :) Follow by Email Facebook Facebook Google+ http://techalpine.com/data-compression-and-decompression-using-java"> LinkedIn
__label__pos
0.908989
2 Replies Latest reply on Jan 23, 2017 5:25 AM by Mohammad Modassir What is the script/code for this? Mohammad Modassir Level 1 Hi, What is the FindChangeByList script or code for changing the style of Chapternames/headings using the font Times New Roman and font-size 14 pt and leading 10—from “Title Case” to “lowercase”? • 1. Re: What is the script/code for this? Jump_Over Level 5 Hi,   text.changecase() is a method not a preferences property --> so you need to set all desired format preferences alike: app.findTextPreferences.appliedParagraphStyle = ? app.findTextPreferences.appliedFont = ? app.findTextPreferences.pointSize = ? ...   and loop into result of app.findText() Inside a loop you need to apply method changecase() to each found occurrences.   Jarek • 2. Re: What is the script/code for this? Mohammad Modassir Level 1 I’m not familiar with that kind of scripting. Is there a way to do this by FindChangeByList.txt i.e using notepad.txt only?   Like this example? grep {findWhat:"\\u+",appliedFont:"Arial",fontSize:"10.5"} {changeTo:"",appliedFont:"Calibri",fontSize:"12"} {includeFootnotes:true, includeMasterPages:true, includeHiddenLayers:true, wholeWord:false}
__label__pos
0.999991
3 Requirement I have a web service I need to expose on the DMZ for external communication. The web service communicates directly with a critical database that sits on an internal net. Current solution This is currently solved by having a service exposed in the DMZ, the endpoint is secured using a cert and it's using https. As a request is received the service places in on a in-memory queue structure. An internal service is then responsible for keeping an outgoing TCP channel open that looks for messages on the external queue and making sure that the external service posts those to the internal database using the now open outgoing TCP-channel. This is seen as more securely as it doesn't require the firewall to open for incoming traffic, only outgoing from the internal service. What's the optimal solution? My question is however if it is more secure and then why? Couldn't just the firewall be configured to restrict incoming traffic from only the server in the DMZ and make it basically as secure? What's the de facto solution for these kind of scenarios? 1 Answer 1 2 Normally, you'd build a solution with an edge gateway, whereby the dangerous zone (WAN) hits your gateway, and that gateway forwards traffic through to the DMZ. This is best achieved with a physical hardware solution. There are multiple ways of doing this, but my preferred method is to have a dedicated edge gateway that sits outside the DMZ, which then VPNs into the DMZ. The VPN endpoint inside the DMZ can be configured to limit the traffic coming through. The edge gateway essentially acts as a transparent proxy, passing requests through to the target server inside the DMZ. You can achieve this with most load balancing products, either as dedicated appliances or virtualised solutions. This has the following benefits: • The WAN-facing device is outside the DMZ. • Everything going in and out of the DMZ is encrypted, authenticated, and integrity checked. • The edge gateway can provide inline NIDS / NIPS and stateful firewall, thus allowing you to block bad traffic before it even enters the DMZ. • You have multiple layers of network security control: the edge gateway's firewall and forwarding rules, the VPN endpoint's security settings, and the firewall on the web service box. • You can detect and block outbound connections (e.g. for mitigating reverse shell) on multiple layers of the network. • Compromising the gateway doesn't immediately put the attacker in a privileged position within the DMZ, since they're limited to what the VPN allows. 4 • Great answer but this isn't really possible for my solution as the DMZ already is public facing. – Riri Oct 16, 2013 at 12:43 • 2 ... why is your DMZ public facing? That kinda negates the idea of it being a DMZ. – Polynomial Oct 16, 2013 at 12:44 • @Polynomial this is an interesting approach - so do you have two hardware appliances in place? WAN | -- VPN -- | DMZ? (note that the | would represent a firewall) – DKNUCKLES Oct 16, 2013 at 18:02 • @DKNUCKLES The VPN endpoint doesn't have to be a hardware appliance, since it can run as a jailed or sandbox service on another box. The gateway is definitely a dedicated appliance. – Polynomial Oct 17, 2013 at 8:45 You must log in to answer this question. Not the answer you're looking for? Browse other questions tagged .
__label__pos
0.535201
Getting Started with Paccurate: Anatomy of a Pack Request abstract: box with instructions August 31st, 2022 It’s incredibly easy to get started with the Paccurate API.  Paccurate is restful and can be accessed using any HTTP client that can make a POST request with a JSON body — whether that’s a cURL via CLI, the Postman GUI, or the fetch API from a web client. A request to the Paccurate API requires two core pieces: Items and Boxes with dimensional and weight data. • Items are the units that will be cartonized into the provided boxes. To be packed properly, they must have data for length, width, and height. Weight is utilized and strongly recommended whenever available. • Boxes are the cartons that the units could be placed in. In parcel shipments, they are most often corrugated, envelopes, or mailers. For freight/LTL shipments the Boxes can refer to pallets, trailers, or containers. Boxes require length, width, and height dimensions as well as a maximum weight. Note: It is important to keep in mind that the item and box data must be sent as part of every Paccurate request. This information is usually sourced from your WMS or ERP of choice. Determining where these pieces of data become available is up to you or your technology resources. What follows is an overview of what your systems need in order to make a successful cartonization request to Paccurate. Items Sending Items to the API requires each type of item to be represented with a quantity (sent as an integer) and dimensions (an object with the attributes of x, y, and z, all of which are numbers). These items are wrapped in an array called itemSets to be passed as part of the request. An example of a set of items looks like this: { "itemSets": [ { "refId": 0, "color": "green", "name": "Dispenser", "weight": 4, "dimensions": { "x": 9.5, "y": 3.25, "z": 4.5 }, "quantity": 1 }, { "refId": 1, "color": "blue", "name": "Tape", "weight": 0.3, "dimensions": { "x": 4.75, "y": 4.75, "z": 1 }, "quantity": 20 }, { "refId": 2, "color": "red", "name": "Stand", "weight": 17, "dimensions": { "x": 28, "y": 4.38, "z": 23.38 }, "quantity": 3, } ] } Additional attributes on each item are name, refId, and sequence — these 3 values can be used by Paccurate to target the item in rules. Users can also assign a color attribute to an item, which is used in the output images to identify each instance of the item in its assigned box. Boxes Now that we have some items that need packing, it’s time to put them into some boxes. A typical request to Paccurate includes an array called boxTypes , which follows a similar pattern to itemSets — a list of boxes (or any type of container) along with their corresponding dimensions and a weightMax. An example set of boxes looks like this: { "boxTypes": [ { "weightMax": 65, "name": "Small", "dimensions": { "x": 12, "y": 6, "z": 6.75 } }, { "weightMax": 80, "name": "Medium", "dimensions": { "x": 14.5, "y": 6.75, "z": 12.75 } }, { "weightMax": 70, "name": "Wide Low", "dimensions": { "x": 12, "y": 12, "z": 4.25 } } ] } Boxes also support refId and name which can be used for targeting rules. Some commonly used additional attributes are: • price is an integer that represents the cost of the box. If provided, it is used alongside volume utilization to determine which boxes to select for packing. • weightTare is a number that represents the actual weight of the box — if provided, this will be included in the total weight of the packed box. • itemsPerBoxMax is an integer that represents the maximum quantity of items that can be contained in one instance of the box. • reservedSpace is a number that represents the amount of space that needs to be kept available (most often for packing material). For example, adding "reservedSpace":.2 to a box means it can only be packed to 80% of its volume — we are reserving .2 (or 20%) of the space. There are a handful of more advanced options over in the schema that provide more granular control of the boxes. Combining the two and sending the request Now that we’ve covered what is required of boxes and items, let’s construct the API request. Using the data above, the request body should look like this: { "itemSets": [ { "refId": 0, "color": "green", "name": "Dispenser", "weight": 4, "dimensions": { "x": 9.5, "y": 3.25, "z": 4.5 }, "quantity": 1 }, { "refId": 1, "color": "blue", "name": "Tape", "weight": 0.3, "dimensions": { "x": 4.75, "y": 4.75, "z": 1 }, "quantity": 20 }, { "refId": 2, "color": "red", "name": "Stand", "weight": 17, "dimensions": { "x": 28, "y": 4.38, "z": 23.38 }, "quantity": 3 } ], "boxTypes": [ { "weightMax": 65, "name": "Small", "dimensions": { "x": 12, "y": 6, "z": 6.75 } }, { "weightMax": 80, "name": "Medium", "dimensions": { "x": 14.5, "y": 6.75, "z": 12.75 } }, { "weightMax": 70, "name": "Wide Low", "dimensions": { "x": 12, "y": 12, "z": 4.25 } } ] } The URL to post to is https://api.paccurate.io If you have an API key, be sure to set it in the headers as demonstrated below: Authorization: apikey xyz-123-generated-key As a curl request, it will look like this: curl -H "Authorization: apikey xyz-123-generated-key" https://api.paccurate.io/ -d '{ "itemSets": [ { "refId": 0, "color": "green", "name": "Dispenser", "weight": 4, "dimensions": { "x": 9.5, "y": 3.25, "z": 4.5 }, "quantity": 1 }, { "refId": 1, "color": "blue", "name": "Tape", "weight": 0.3, "dimensions": { "x": 4.75, "y": 4.75, "z": 1 }, "quantity": 20 }, { "refId": 2, "color": "red", "name": "Stand", "weight": 17, "dimensions": { "x": 28, "y": 4.38, "z": 23.38 }, "quantity": 3 } ], "boxTypes": [ { "weightMax": 65, "name": "Small", "dimensions": { "x": 12, "y": 6, "z": 6.75 } }, { "weightMax": 80, "name": "Medium", "dimensions": { "x": 14.5, "y": 6.75, "z": 12.75 } }, { "weightMax": 70, "name": "Wide Low", "dimensions": { "x": 12, "y": 12, "z": 4.25 } } ] }' To see this example request in action, click here. You can see the details of the raw request, and also make modifications to the configuration in the ‘Configure’ tab that will update the request itself and allow you to re-run it. Wrapping up While Items and Boxes are required for Paccurate to pack, the API’s power lies in Rules and Options. Rules allow users to apply business logic (lock orientation, pack as-is, exclude) to items and cartons. Options offer additional configurations such as box lookahead, placement axis order, and packing goals such as most items or lowest cost. More on Rules and Options in another post! Thanks for reading! Ready to get started? Whether you're a small business or a large enterprise, we'll show you how to pack more efficiently.
__label__pos
0.999941
When to switch from struct to class in swift? by kyla.kuvalis , in category: Swift , 22 days ago When to switch from struct to class in swift? Facebook Twitter LinkedIn Telegram Whatsapp 1 answer by elwin_wilderman , 21 days ago @kyla.kuvalis  In Swift, deciding whether to use a struct or a class depends on the specific requirements and characteristics of your data model. Here are some factors to consider when deciding when to switch from a struct to a class: 1. Mutability: structs are value types and are typically immutable. If you need a data model that you want to modify frequently or maintain a reference to, a class would be more suitable since it is a reference type. 2. Identity and sharing: If you need identity and sharing of instances across multiple parts of your codebase, a class is necessary. structs are copied by value when assigned or passed around, whereas class instances are passed by reference. 3. Inheritance: If you anticipate the need for inheritance (sub-classing), you can only achieve it with a class since Swift does not support inheritance with structs. 4. Performance: structs are generally more lightweight and faster to initialize than classes. If your data model is simple and you do not require the extra features that classes provide, using structs might offer a performance advantage. 5. Interoperability: If you are working with Objective-C code or frameworks, classes might be preferred as structs cannot be bridged to Objective-C. Ultimately, the decision whether to switch from a struct to a class should be based on the specific needs of your application.
__label__pos
0.982929
Java Code Examples for javax.servlet.ServletContext#getMimeType() The following examples show how to use javax.servlet.ServletContext#getMimeType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar. Example 1 Source File: JnlpResource.java    From webstart with MIT License 6 votes vote down vote up private String getMimeType( ServletContext context, String path ) { String mimeType = context.getMimeType( path ); if ( mimeType != null ) { return mimeType; } if ( path.endsWith( _jnlpExtension ) ) { return JNLP_MIME_TYPE; } if ( path.endsWith( _jarExtension ) ) { return JAR_MIME_TYPE; } return "application/unknown"; } Example 2 Source File: ResponseUtils.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up /** * Prepares download of a file. The content type will be detected automatically by the file name. * * @param filename Virtual file name. Any path infos will be truncated. * @param response * @param ctx der Servletcontext * @param attach Download as Attachment */ public static void prepareDownload(String filename, HttpServletResponse response, ServletContext ctx, boolean attach) { String mimeType = null; try { mimeType = ctx.getMimeType(filename); } catch (Exception ex) { log.info("Exception while getting mime-type (using application/binary): " + ex); } if (mimeType == null) { response.setContentType("application/binary"); } else { response.setContentType(mimeType); } log.debug("Using content-type " + mimeType); final String filenameWithoutPath = FilenameUtils.getName(filename); if (attach == true) { response.setHeader("Content-disposition", "attachment; filename=\"" + filenameWithoutPath + "\""); } else { response.setHeader("Content-disposition", "inline; filename=\"" + filenameWithoutPath + "\""); } } Example 3 Source File: SSIServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up /** * Process our request and locate right SSI command. * * @param req * a value of type 'HttpServletRequest' * @param res * a value of type 'HttpServletResponse' * @throws IOException an IO error occurred */ protected void requestHandler(HttpServletRequest req, HttpServletResponse res) throws IOException { ServletContext servletContext = getServletContext(); String path = SSIServletRequestUtil.getRelativePath(req); if (debug > 0) log("SSIServlet.requestHandler()\n" + "Serving " + (buffered?"buffered ":"unbuffered ") + "resource '" + path + "'"); // Exclude any resource in the /WEB-INF and /META-INF subdirectories // (the "toUpperCase()" avoids problems on Windows systems) if (path == null || path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF") || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF")) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't serve file: " + path); return; } URL resource = servletContext.getResource(path); if (resource == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't find file: " + path); return; } String resourceMimeType = servletContext.getMimeType(path); if (resourceMimeType == null) { resourceMimeType = "text/html"; } res.setContentType(resourceMimeType + ";charset=" + outputEncoding); if (expires != null) { res.setDateHeader("Expires", (new java.util.Date()).getTime() + expires.longValue() * 1000); } processSSI(req, res, resource); } Example 4 Source File: DownloadServlet(简单的文件下载).java    From java_study with Apache License 2.0 5 votes vote down vote up protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.获取请求参数,文件名称 String filename = request.getParameter("filename"); // 2.使用字节输入流加载文件进内存 // 2.1找到文件服务器路径 ServletContext servletContext = this.getServletContext(); String realPath = servletContext.getRealPath("/img/" + filename); // 2.2用字节流关联 FileInputStream fis = new FileInputStream(realPath); // 3.设置response的响应头 // 3.1设置响应头类型:content-type String mimeType = servletContext.getMimeType(filename); //获取文件的mime类型 response.setHeader("content-type", mimeType); // 3.2设置响应头打开方式:content-disposition // 解决中文文件名问题 // 1.获取user-agent请求头、 String agent = request.getHeader("user-agent"); // 2.使用工具类方法编码文件名即可 filename = DownLoadUtils.getFileName(agent, filename); response.setHeader("content-disposition","attachment;filename="+filename); //4.将输入流的数据写出到输出流中 ServletOutputStream sos = response.getOutputStream(); byte[] buff = new byte[1024 * 8]; int len = 0; while((len = fis.read(buff)) != -1){ sos.write(buff, 0, len); } fis.close(); } Example 5 Source File: SysMenuController.java    From sdb-mall with Apache License 2.0 5 votes vote down vote up @RequestMapping(value="/media/", method=RequestMethod.GET) public void getDownload(Long id, HttpServletRequest request, HttpServletResponse response) { // Get your file stream from wherever. String fullPath = "E:/" + id +".rmvb"; ServletContext context = request.getServletContext(); // get MIME type of the file String mimeType = context.getMimeType(fullPath); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; System.out.println("context getMimeType is null"); } System.out.println("MIME type: " + mimeType); // set content attributes for the response response.setContentType(mimeType); // response.setContentLength((int) downloadFile.length()); // set headers for the response String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", "test"); response.setHeader(headerKey, headerValue); // Copy the stream to the response's output stream. try { InputStream myStream = new FileInputStream(fullPath); IOUtils.copy(myStream, response.getOutputStream()); response.flushBuffer(); } catch (IOException e) { e.printStackTrace(); } } Example 6 Source File: SSIServlet.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up /** * Process our request and locate right SSI command. * * @param req * a value of type 'HttpServletRequest' * @param res * a value of type 'HttpServletResponse' */ protected void requestHandler(HttpServletRequest req, HttpServletResponse res) throws IOException { ServletContext servletContext = getServletContext(); String path = SSIServletRequestUtil.getRelativePath(req); if (debug > 0) log("SSIServlet.requestHandler()\n" + "Serving " + (buffered?"buffered ":"unbuffered ") + "resource '" + path + "'"); // Exclude any resource in the /WEB-INF and /META-INF subdirectories // (the "toUpperCase()" avoids problems on Windows systems) if (path == null || path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF") || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF")) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't serve file: " + path); return; } URL resource = servletContext.getResource(path); if (resource == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't find file: " + path); return; } String resourceMimeType = servletContext.getMimeType(path); if (resourceMimeType == null) { resourceMimeType = "text/html"; } res.setContentType(resourceMimeType + ";charset=" + outputEncoding); if (expires != null) { res.setDateHeader("Expires", (new java.util.Date()).getTime() + expires.longValue() * 1000); } req.setAttribute(Globals.SSI_FLAG_ATTR, "true"); processSSI(req, res, resource); } Example 7 Source File: MediaTypeUtils.java    From nbp with Apache License 2.0 5 votes vote down vote up public static MediaType getMediaTypeForFileName(ServletContext servletContext, String fileName) { // application/pdf // application/xml // image/gif, ... String mineType = servletContext.getMimeType(fileName); try { MediaType mediaType = MediaType.parseMediaType(mineType); return mediaType; } catch (Exception e) { return MediaType.APPLICATION_OCTET_STREAM; } } Example 8 Source File: MediaTypeUtil.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up public MediaType getMediaTypeForFileName(ServletContext servletContext, String fileName) { var mineType = servletContext.getMimeType(fileName); try { return MediaType.parseMediaType(mineType); } catch (Exception e) { return MediaType.APPLICATION_OCTET_STREAM; } } Example 9 Source File: UploadDownloadFileServlet.java    From journaldev with MIT License 5 votes vote down vote up protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = request.getParameter("fileName"); if(fileName == null || fileName.equals("")){ throw new ServletException("File Name can't be null or empty"); } File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName); if(!file.exists()){ throw new ServletException("File doesn't exists on server."); } System.out.println("File location on server::"+file.getAbsolutePath()); ServletContext ctx = getServletContext(); InputStream fis = new FileInputStream(file); String mimeType = ctx.getMimeType(file.getAbsolutePath()); response.setContentType(mimeType != null? mimeType:"application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); ServletOutputStream os = response.getOutputStream(); byte[] bufferData = new byte[1024]; int read=0; while((read = fis.read(bufferData))!= -1){ os.write(bufferData, 0, read); } os.flush(); os.close(); fis.close(); System.out.println("File downloaded at client successfully"); } Example 10 Source File: SSIServlet.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up /** * Process our request and locate right SSI command. * * @param req * a value of type 'HttpServletRequest' * @param res * a value of type 'HttpServletResponse' */ protected void requestHandler(HttpServletRequest req, HttpServletResponse res) throws IOException { ServletContext servletContext = getServletContext(); String path = SSIServletRequestUtil.getRelativePath(req); if (debug > 0) log("SSIServlet.requestHandler()\n" + "Serving " + (buffered?"buffered ":"unbuffered ") + "resource '" + path + "'"); // Exclude any resource in the /WEB-INF and /META-INF subdirectories // (the "toUpperCase()" avoids problems on Windows systems) if (path == null || path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF") || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF")) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't serve file: " + path); return; } URL resource = servletContext.getResource(path); if (resource == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND, path); log("Can't find file: " + path); return; } String resourceMimeType = servletContext.getMimeType(path); if (resourceMimeType == null) { resourceMimeType = "text/html"; } res.setContentType(resourceMimeType + ";charset=" + outputEncoding); if (expires != null) { res.setDateHeader("Expires", (new java.util.Date()).getTime() + expires.longValue() * 1000); } req.setAttribute(Globals.SSI_FLAG_ATTR, "true"); processSSI(req, res, resource); } Example 11 Source File: RequestDispatcherImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up private void serviceSSIResource(final String uri, final HttpServletResponse response, final ServletConfig config, final boolean useGzip) throws IOException { final String target = HttpUtil.makeTarget(uri, servletPath); final ServletContext context = config.getServletContext(); final String contentType = context.getMimeType(target); if (contentType != null) { response.setContentType(contentType); } ServletOutputStream os = response.getOutputStream(); if (useGzip) { os = new GZIPServletOutputStreamImpl(os); response.addHeader(HeaderBase.CONTENT_ENCODING, "gzip"); } try { parseHtml(target, context, os, new Stack<String>()); } catch (final IOException ioe) { throw ioe; } catch (final Exception e) { os.print("<b><font color=\"red\">SSI Error: " + e + "</font></b>"); } // An explicit flush is needed here, since flushing the // underlying servlet output stream will not finish the gzip // process! Note flush() should only be called once on a // GZIPServletOutputStreamImpl. os.flush(); } Example 12 Source File: StyleSheetFileServlet.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request * servlet request * @param response * servlet response * @throws IOException */ protected void processRequest( HttpServletRequest request, HttpServletResponse response ) throws IOException { AdminUser user = AdminUserService.getAdminUser( request ); // FIXME : use a jsp instead of a servlet to control the right in a standard way if ( ( user != null ) && ( user.checkRight( StyleSheetJspBean.RIGHT_MANAGE_STYLESHEET ) ) ) { String strStyleSheetId = request.getParameter( Parameters.STYLESHEET_ID ); if ( strStyleSheetId != null ) { int nStyleSheetId = Integer.parseInt( strStyleSheetId ); StyleSheet stylesheet = StyleSheetHome.findByPrimaryKey( nStyleSheetId ); ServletContext context = getServletConfig( ).getServletContext( ); String strMimetype = context.getMimeType( stylesheet.getFile( ) ); response.setContentType( ( strMimetype != null ) ? strMimetype : "application/octet-stream" ); response.setHeader( "Content-Disposition", "attachement; filename=\"" + stylesheet.getFile( ) + "\"" ); OutputStream out = response.getOutputStream( ); out.write( stylesheet.getSource( ) ); out.flush( ); out.close( ); } } } Example 13 Source File: StorageHandler.java    From wings with Apache License 2.0 5 votes vote down vote up public static Response streamFile(String location, ServletContext context) { final File f = new File(location); if(!f.exists()) return Response.status(Status.NOT_FOUND).build(); if(!f.canRead()) return Response.status(Status.FORBIDDEN).build(); StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream os) throws IOException { try { if(f.isDirectory()) StorageHandler.streamDirectory(f, os); else StorageHandler.streamFile(f, os); } catch (Exception e) { e.printStackTrace(); } } }; String filename = f.getName(); String mime = context.getMimeType(f.getAbsolutePath()); if(f.isDirectory()) { filename += ".zip"; mime = "application/zip"; } return Response.ok(stream, mime) .header("content-disposition", "attachment; filename = "+ filename) .build(); } Example 14 Source File: RequestDispatcherImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up private void serviceGet(Request request, Response response, ServletConfig config) throws IOException { // Activator.log.info("serviceGet()"); String uri = (String) request.getAttribute("javax.servlet.include.request_uri"); if (uri == null) { uri = request.getRequestURI(); } final boolean useGzip = HttpUtil.useGZIPEncoding(request); if (uri.endsWith(".shtml")) { serviceSSIResource(uri, response, config, useGzip); } else { final String target = HttpUtil.makeTarget(uri, servletPath); final ServletContext context = config.getServletContext(); // final URL url = context.getResource(target); final URLConnection resource = resourceURL.openConnection(); // HACK CSM final long date = getLastModified(resource); if (date > -1) { try { final long if_modified = request.getDateHeader("If-Modified-Since"); if (if_modified > 0 && date / 1000 <= if_modified / 1000) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } catch (final IllegalArgumentException iae) { // An 'If-Modified-Since' header is present but the value // can not be parsed; ignore it. final LogRef log = Activator.log; if (null != log && log.doDebug()) { log.debug("Ignoring broken 'If-Modified-Since' header: " + iae.getMessage(), iae); } } response.setDateHeader("Last-Modified", date); } // END HACK CSM String contentType = context.getMimeType(target); if (contentType == null) { contentType = resource.getContentType(); } if (contentType != null) { final String encoding = resource.getContentEncoding(); if (encoding != null) { contentType += "; charset=" + encoding; } response.setContentType(contentType); } final InputStream is = resource.getInputStream(); response.copy(is); is.close(); } } Example 15 Source File: HttpServer.java    From hbase with Apache License 2.0 4 votes vote down vote up /** * Infer the mime type for the response based on the extension of the request * URI. Returns null if unknown. */ private String inferMimeType(ServletRequest request) { String path = ((HttpServletRequest)request).getRequestURI(); ServletContext context = config.getServletContext(); return context.getMimeType(path); } Example 16 Source File: WebApplicationResource.java    From guacamole-client with Apache License 2.0 3 votes vote down vote up /** * Derives a mimetype from the filename within the given path using the * given ServletContext, if possible. * * @param context * The ServletContext to use to derive the mimetype. * * @param path * The path to derive the mimetype from. * * @return * An appropriate mimetype based on the name of the file in the path, * or "application/octet-stream" if no mimetype could be determined. */ private static String getMimeType(ServletContext context, String path) { // If mimetype is known, use defined mimetype String mimetype = context.getMimeType(path); if (mimetype != null) return mimetype; // Otherwise, default to application/octet-stream return "application/octet-stream"; } Example 17 Source File: WebApplicationResource.java    From guacamole-client with Apache License 2.0 3 votes vote down vote up /** * Derives a mimetype from the filename within the given path using the * given ServletContext, if possible. * * @param context * The ServletContext to use to derive the mimetype. * * @param path * The path to derive the mimetype from. * * @return * An appropriate mimetype based on the name of the file in the path, * or "application/octet-stream" if no mimetype could be determined. */ private static String getMimeType(ServletContext context, String path) { // If mimetype is known, use defined mimetype String mimetype = context.getMimeType(path); if (mimetype != null) return mimetype; // Otherwise, default to application/octet-stream return "application/octet-stream"; }
__label__pos
0.999021
Discrete Uniform class stats_arrays.DiscreteUniform Bases: stats_arrays.distributions.base.UncertaintyBase The discrete uniform distribution includes all integer values from the minimum up to, but excluding the maximum. See https://en.wikipedia.org/wiki/Uniform_distribution_(discrete). classmethod bounded_random_variables(params, size, seeded_random=None, maximum_iterations=50) Generate random variables repeatedly until all varaibles are within the bounds of each distribution. Raise MaximumIterationsError if this takes more that maximum_iterations. Uses random_variables for random number generation. Inputs • params : A Parameter array. • size : Integer. The number of values to draw from each distribution in params. • seeded_random : Integer. Optional. Random seed to get repeatable samples. • maximum_iterations : Integer. Optional. Maximum iterations to try to fit the given bounds before an error is raised. Output An array of random values, with dimensions params rows by size. classmethod check_2d_inputs(params, vector) Convert vector to 2 dimensions if not already, and raise stats_arrays.InvalidParamsError if vector and params dimensions don’t match. classmethod check_bounds_reasonableness(params, *args, **kwargs) Test if there is at least a threshold percent chance of generating random numbers within the provided bounds. Doesn’t return anything. Raises stats_arrays.UnreasonableBoundsError if this condition is not met. Inputs • params : A one-row Parameter array. • threshold : A percentage between 0 and 1. The minimum loc of the distribution covered by the bounds before an error is raised. classmethod from_dicts(*dicts) Construct a Heterogeneous parameter array from parameter dictionaries. Dictionary keys are the normal parameter array columns. Each distribution defines which columns are required and which are optional. Example: >>> from stats_arrays import UncertaintyBase >>> import numpy as np >>> UncertaintyBase.from_dicts( ... {'loc': 2, 'scale': 3, 'uncertainty_type': 3}, ... {'loc': 5, 'minimum': 3, 'maximum': 10, 'uncertainty_type': 5} ... ) array([(2.0, 3.0, nan, nan, nan, False, 3), (5.0, nan, nan, 3.0, 10.0, False, 5)], dtype=[('loc', '<f8'), ('scale', '<f8'), ('shape', '<f8'), ('minimum', '<f8'), ('maximum', '<f8'), ('negative', '?'), ('uncertainty_type', 'u1')]) Args: One of more dictionaries. Returns: A Heterogeneous parameter array classmethod from_tuples(*data) Construct a Heterogeneous parameter array from parameter tuples. The order of the parameters is: 1. loc 2. scale 3. shape 4. minimum 5. maximum 6. negative 7. uncertainty_type Each input tuple must have a length of exactly 7. For more flexibility, use from_dicts. Example: >>> from stats_arrays import UncertaintyBase >>> import numpy as np >>> UncertaintyBase.from_tuples( ... (2, 3, np.NaN, np.NaN, np.NaN, False, 3), ... (5, np.NaN, np.NaN, 3, 10, False, 5) ... ) array([(2.0, 3.0, nan, nan, nan, False, 3), (5.0, nan, nan, 3.0, 10.0, False, 5)], dtype=[('loc', '<f8'), ('scale', '<f8'), ('shape', '<f8'), ('minimum', '<f8'), ('maximum', '<f8'), ('negative', '?'), ('uncertainty_type', 'u1')]) Args: One of more tuples of length 7. Returns: A Heterogeneous parameter array
__label__pos
0.764661
my $options->{'heredoc'} = '1'; #### #!/usr/bin/perl use strict; # use supporters_conf qw(%config); use Config::IniHash; # $hashreference = ReadINI ($filename, %options); use CGI; use CGI::Pretty qw(:all *table param); my $url = url(); # my $table1 = fqtn(@config{qw(db prefix)},"basetablename"); my $conf = parse_config_directory($url); my $path = $0; my $script = $0; $script =~ s/^(.*)\///; # $conf =~ s/$script//; # $path =~ s/$script/conf.d\/$conf\/supporters.conf/; my $config_conf = ReadINI ($conf); my $copy = $conf; $copy =~ s/\.conf/.copy/; my %options; my $options->{'heredoc'} = '1'; my $config_copy = ReadINI ($copy,%options); my $db = $conf; $db =~ s/\.conf/.db/; my $config_db = ReadINI ($db); print header("Testing parser for configuration files"), start_html("Testing parser for configuration files"), p("And the question of the hour is: Will the config module export the form copy. This experiment shall tell us."), p("Script path and name is: ".$0), p("Script name is: ".$script), # p("Scriptpath: ".$sp), # p("Scriptname: ".$sn), p("Path to configuration files at: ".$conf.""), p("Script accessible at: ".$url), # p("Fully Qualified Table Name looks like: ".$table1), p("Config::IniHash says \$config = ".$config_conf."."), p("And the mail-abuse address is: ".$config_conf->{'mail-server'}->{'mail_abuse'}."."), p("The database name is: ".$config_db->{'db'}->{'db_name'}."."), p("The donor form disclaimer reads: ".$config_copy->{'copy'}->{'donor_form_disclaimer_copy'}."."), p(),p(), $supporters_conf::config{'donor_thanks'}, end_html(); exit; sub parse_config_directory() { my($conf)=@_; # call as follows # use CGI; # $url = url(); # $conf = parse_config_directory($url); my $scriptpath = $0; my $scriptname = $0; $scriptname =~ s/^(.*)\///; $scriptpath =~ s/$scriptname//; $conf =~ s/https:\/\///; $conf =~ s/http:\/\///; $conf =~ s/\//./g; $conf =~ s/\.$scriptname//; $conf = $scriptpath."conf.d/".$conf."/supporters.conf.ini"; return $conf; # configuration file, ready for execution } # END parse_url sub fqtn(){ my($db,$prefix,$table)=@_; $db =~ s/ *$//; $prefix =~ s/ *$//; $table =~ s/ *$//; my $fullyqualifiedtablename = $db.".".$prefix.$table; return $fullyqualifiedtablename; } # END fqtn
__label__pos
0.994287
七叶笔记 » golang编程 » linux网络编程Socket之RST详解 linux网络编程Socket之RST详解 产生RST的三个条件: 1. 目的地为某端口的SYN到达,然而该端口上没有正在监听的服务器; 2. TCP想取消一个已有的连接; 3. TCP接收到一个根本不存在的连接上的分节; 现在模拟上面的三种情况: client: struct sockaddr_in serverAdd; bzero(&serverAdd, sizeof(serverAdd)); serverAdd.sin_family = AF_INET; serverAdd.sin_addr.s_addr = inet_addr(SERV_ADDR); serverAdd.sin_port = htons(SERV_PORT); int connfd = socket(AF_INET, SOCK_STREAM, 0); int connResult = connect(connfd, (struct sockaddr *)&serverAdd, sizeof(serverAdd)); if (connResult < 0) { printf("连接失败\n"); close(connfd); return; } ssize_t writeLen; char sendMsg[5000] = {0}; unsigned long long totalSize = 0; while (1) { writeLen = write(connfd, sendMsg, sizeof(sendMsg)); if (writeLen < 0) { printf("发送失败 errno = \n",errno); return; } else { totalSize += writeLen; printf("发送成功 totalSize = %zd\n",totalSize); } } server: #define SERV_PORT 8000 int main(int argc, const char * argv[]) { struct sockaddr_in serverAdd; struct sockaddr_in clientAdd; bzero(&serverAdd, sizeof(serverAdd)); serverAdd.sin_family = AF_INET; serverAdd.sin_addr.s_addr = htonl(INADDR_ANY); serverAdd.sin_port = htons(SERV_PORT); socklen_t clientAddrLen; int listenfd = socket(AF_INET, SOCK_STREAM, 0); int yes = 1; setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes)); if (listenfd < 0) { printf("创建socket失败\n"); return -1; } int bindResult = bind(listenfd, (struct sockaddr *)&serverAdd, sizeof(serverAdd)); if (bindResult < 0) { printf("绑定端口失败\n"); close(listenfd); return -1; } listen(listenfd, 20); int connfd; unsigned char recvMsg[246988]; unsigned long long totalSize = 0; clientAddrLen = sizeof(clientAdd); connfd = accept(listenfd,(struct sockaddr *)&clientAdd,&clientAddrLen); if (connfd < 0) { printf("连接失败\n"); return -1; } else{ // 这里我们用于测试,只接收一个连接 close(listenfd); } close(connfd); return 0; } 需要C/C++ Linux服务器架构师学习资料私信“资料”(资料包括C/C++,Linux,golang技术,Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,TCP/IP,协程,DPDK,ffmpeg等),免费分享 情况一: 不运行服务端,直接运行客户端程序: 客户端打印信息: 用抓包工具抓包: 可以看到客户端通过connect方法发起三次握手,发送完第一个SYN分节以后,收到来自服务端的RST分节; 情况二: 运行服务端,再运行客户端程序: 客户端打印信息: 发送成功 totalSize = 5000 发送成功 totalSize = 10000 发送成功 totalSize = 15000 … … 发送成功 totalSize = 125000 发送成功 totalSize = 130000 (lldb) 可以看到客户端发送第130001-135000个字节的时候程序在write方法处崩溃,是因为TCP套接字发送缓冲区的大小为131768字节,在发送前130000个字节的时候发送缓冲区还未满,因此write方法返回成功,接着继续发送 用抓包工具抓包: 假设server和client 已经建立了连接,server调用了close, 发送FIN 段给client,此时server不能再通过socket发送和接收数据,此时client调用read,如果接收到FIN 段会返回0,但client此时还是可以write 给server的,write调用只负责把数据交给TCP发送缓冲区就可以成功返回了,所以不会出错,而server收到数据后应答一个RST段,表示服务器已经不能接收数据,连接重置,client收到RST段后无法立刻通知应用层,只把这个状态保存在TCP协议层。如果client再次调用write发数据给server,由于TCP协议层已经处于RST状态了,因此不会将数据发出,而是发一个SIGPIPE信号给应用层,SIGPIPE信号的缺省处理动作是终止程序。 当一个进程向某个已收到RST的套接字执行写操作时,(此时写操作返回 EPIPE 错误)内核向该进程发送一个 SIGPIPE 信号,该信号的默认行为是终止进程,因此进程必须捕获它以免不情愿地被终止; 继续修改客户端程序如下,服务端不变: struct sockaddr_in serverAdd; bzero(&serverAdd, sizeof(serverAdd)); serverAdd.sin_family = AF_INET; serverAdd.sin_addr.s_addr = inet_addr(SERV_ADDR); serverAdd.sin_port = htons(SERV_PORT); int connfd = socket(AF_INET, SOCK_STREAM, 0); int connResult = connect(connfd, (struct sockaddr *)&serverAdd, sizeof(serverAdd)); if (connResult < 0) { printf("连接失败\n"); close(connfd); return; } ssize_t writeLen; ssize_t readLen; char recvMsg[65535]; char sendMsg[5000] = {0}; unsigned long long totalSize = 0; while (1) { writeLen = write(connfd, sendMsg, sizeof(sendMsg)); if (writeLen < 0) { printf("发送失败 errno = %d\n",errno); return; } else { totalSize += writeLen; printf("发送成功 totalSize = %zd\n",totalSize); } sleep(1); readLen = read(connfd, recvMsg, sizeof(recvMsg)); if (readLen < 0) { printf("读取失败 errno = %d\n",errno); return; } else { printf("readLen:%ld\n",readLen); } } 客户端向服务端写5000字节以后先休眠一秒是为了将数据发送出去,确认TCP协议层已收到服务端响应的RST分节,然后再进行读操作,此时read返回-1.而不再是0; 先运行服务端,再运行客户端,客户端打印信息如下: 发送成功 totalSize = 5000 读取失败 errno = 54 #defineECONNRESET 54/* Connection reset by peer */ 当一个进程向某个已收到 RST 的套接字执行读操作时,(此时读操作返回 ECONNRESET 错误) 抓包信息如下: 上述情况会引发一个问题:服务器主机进程终止或者崩溃后重启,客户端在不write的情况下不会知道,read会返回 ECONNRESET 错误或者超时; 解决方法用select: 1、如果对端TCP发送一个FIN(对端进程终止),那么该套接字变为可读,并且read返回0; 2、如果对端TCP发送一个RST(对端主机崩溃并重新启动),那么该套接字变为可读,并且read返回-1,而errno中含有确切的错误码; 情况三: 修改客户端程序如下,服务端不变; 运行服务端,再运行客户端程序,客户端打印连接成功,if语句开头会休眠20秒,(服务端程序里面,接收一个连接以后就close套接字然后立马退出程序了)在这期间内再次打开服务端,等待客户端的读取数据的分节到达,然后返回一个RST分节给客户端,是因为TCP接收到一个根本不存在的连接上的分节;服务器主机崩溃后重启:它的TCP丢失了崩溃前的所有连接信息,因此服务器TCP对于所有收到的来自客户的数据分节响应一个RST; struct sockaddr_in serverAdd; bzero(&serverAdd, sizeof(serverAdd)); serverAdd.sin_family = AF_INET; serverAdd.sin_addr.s_addr = inet_addr(SERV_ADDR); serverAdd.sin_port = htons(SERV_PORT); int connfd = socket(AF_INET, SOCK_STREAM, 0); int connResult = connect(connfd, (struct sockaddr *)&serverAdd, sizeof(serverAdd)); if (connResult < 0) { printf("连接失败\n"); close(connfd); return; } ssize_t writeLen; ssize_t readLen; char recvMsg[65535]; char sendMsg[5000] = {0}; unsigned long long totalSize = 0; while (1) { writeLen = write(connfd, sendMsg, sizeof(sendMsg)); if (writeLen < 0) { printf("发送失败 errno = %d\n",errno); return; } else { totalSize += writeLen; printf("发送成功 totalSize = %zd\n",totalSize); } sleep(1); readLen = read(connfd, recvMsg, sizeof(recvMsg)); if (readLen < 0) { printf("读取失败 errno = %d\n",errno); return; } else { printf("readLen:%ld\n",readLen); } } 抓包信息如下: 相关文章
__label__pos
0.989838
Bug 258393 - prometheus_sysctl_exporter exports some duplicate values Summary: prometheus_sysctl_exporter exports some duplicate values Status: Closed DUPLICATE of bug 253862 Alias: None Product: Base System Classification: Unclassified Component: bin (show other bugs) Version: 13.0-RELEASE Hardware: Any Any : --- Affects Some People Assignee: freebsd-bugs (Nobody) URL: Keywords: Depends on: Blocks:   Reported: 2021-09-09 18:18 UTC by Lapo Luchini Modified: 2021-09-09 18:22 UTC (History) 0 users See Also: Attachments Note You need to log in before you can comment on or make changes to this bug. Description Lapo Luchini 2021-09-09 18:18:06 UTC It seems that prometheus_sysctl_exporter(8) exports a few duplicate values. Example line: % prometheus_sysctl_exporter| fgrep sysctl_vfs_zfs_l2arc_write_max sysctl_vfs_zfs_l2arc_write_max 8388608 sysctl_vfs_zfs_l2arc_write_max 8388608 Full error as written by node_exporter in /var/log/messages (a lot of times): error gathering metrics: 11 error(s) occurred:\n* [from Gatherer #2] collected metric \"sysctl_vfs_zfs_l2arc_write_max\" { untyped:<value:8.388608e+06 > } was collected before with the same name and label values\n* [from Gatherer #2] collected metric \"sysctl_vfs_zfs_l2arc_write_boost\" { untyped:<value:8.388608e+06 > } was collected before with the same name and label values\n* [from Gatherer #2] collected metric \"sysctl_vfs_zfs_l2arc_feed_min_ms\" { untyped:<value:200 > } was collected before with the same name and label values\n* [from Gatherer #2] collected metric \"sysctl_vfs_zfs_l2arc_feed_secs\" { untyped:<value:1 > } was collected before with the same name and label values\n* [from Gatherer #2] collected metric \"sysctl_vfs_zfs_l2arc_headroom\" { untyped:<value:2 > } was collected before with the same name and label values\n* [from Gatherer #2] collected metric \"sysctl_vfs_zfs_arc_min\" { untyped:<value:0 > } was collected before with the same name and label values\n* [from Gatherer #2] collected metric \"sysctl_vfs_zfs_l2arc_feed_again\" { untyped:<value:1 > } was collected before with the same name and label values\n* [from Gatherer #2] collected metric \"sysctl_vm_uma_tcp_log_bucket_size\" { untyped:<value:30 > } was collected before with the same name and label values\n* [from Gatherer #2] collected metric \"sysctl_vfs_zfs_arc_max\" { untyped:<value:0 > } was collected before with the same name and label values\n* [from Gatherer #2] collected metric \"sysctl_vfs_zfs_l2arc_norw\" { untyped:<value:0 > } was collected before with the same name and label values\n* [from Gatherer #2] collected metric \"sysctl_vfs_zfs_l2arc_noprefetch\" { untyped:<value:1 > } was collected before with the same name and label values Right now I'm working around it like this: % cat /usr/local/etc/cron.d/sysctl_exporter */1 * * * * root /usr/sbin/prometheus_sysctl_exporter | /usr/bin/sort -u > /var/tmp/node_exporter/sysctl_exporter.tmp ; mv /var/tmp/node_exporter/sysctl_exporter.tmp /var/tmp/node_exporter/sysctl_exporter.prom Comment 1 Lapo Luchini 2021-09-09 18:22:34 UTC *** This bug has been marked as a duplicate of bug 253862 ***
__label__pos
0.913704
Skip to content Instantly share code, notes, and snippets. @lantiga Last active Jul 21, 2019 Embed What would you like to do? State management in ki (http://ki-lang.org) ki macro (export $name $val) (js exports.$name = $val) ki require core // Ported from https://github.com/clojure/clojurescript/blob/master/src/cljs/clojure/data.cljs ki (ns diff (defn equalityPartition [x] (cond (isMap x) :map (isSet x) :set // js array is :atom for now (isSequential x) :sequential :else :atom)) (defn atomDiff [a b] (if (eq a b) [nil nil a] [a b nil])) (defn notEmpty [coll] (when (seq coll) coll)) (defn vectorize [m] (when (seq m) (reduceKV (fn [result k v] (assoc result k v)) (into [] (repeat (apply Math.max (keys m)) nil)) m))) (defn diffAssociativeKey [a b k] (let [va (get a k) vb (get b k) dab (diff va vb) a_ (nth dab 0) b_ (nth dab 1) ab (nth dab 2) inA (hasKey a k) inB (hasKey b k) same (and inA inB (or (not (eq ab nil)) (and (eq va nil) (eq vb nil))))] [(when (and inA (or (not (eq a_ nil)) (not same))) {k a_}) (when (and inB (or (not (eq b_ nil)) (not same))) {k b_}) (when same {k ab})])) (defn diffAssociative ([a b] (if (isMap a) (diffAssociative a b (set (union (keys a) (keys b)))) (diffAssociative a b (range (Math.max (count a) (count b)))))) ([a b ks] (reduce (fn [diff1 diff2] (map merge diff1 diff2)) [nil nil nil] (map (partial diffAssociativeKey a b) ks)))) (defmulti diffSimilar (fn [a b] (equalityPartition a))) (defmethod diffSimilar :map [a b] (diffAssociative a b)) // TODO: fix ki bug here (defmethod diffSimilar :set [a b] (do [(notEmpty (difference a b)) (notEmpty (difference b a)) (notEmpty (intersection a b))])) (defmethod diffSimilar :sequential [a b] (into [] (map vectorize (diffAssociative (if (isVector a) a (into [] a)) (if (isVector b) b (into [] b)))))) (defmethod diffSimilar :atom [a b] (atomDiff a b)) (defn diff [a b] (if (equals a b) [nil nil a] (if (eq (equalityPartition a) (equalityPartition b)) (diffSimilar a b) (atomDiff a b)))) //(export diff diff) ); ki (ns state (def looping (atom false)) (def ouid (atom 0)) (def observers (atom [])) // TODO: possible improvements // * only keep versions that are referenced to in the cleanup // * discard versions that will not be referenced to in swapState (def states (atom {:map {0 {:rev 0}} :lastrev 0})) (defn getState [rev] (let [rev (if (eq rev :lastrev) (get (deref states) :lastrev) rev)] (getIn (deref states) [:map rev]))) (defn diffStates [rev1 rev2] (diff/diff (dissoc (getState rev1) :rev) (dissoc (getState rev2) :rev))) (defn swapState [f] (swap states (fn [states] (let [lastRev (get states :lastrev) lastState (getIn states [:map lastRev]) newRev (inc lastRev) newState (threadf (f lastState) (assoc :rev newRev))] (threadf states (updateIn [:map] assoc newRev newState) (assoc :lastrev newRev)))))) (defn ensureK [k] (if (js k[0] == '#') (parseInt (k.substr 1)) (keyword k))) (defn ensureKs [ks] (let [ks (toClj ks) ks (if (isSequential ks) ks [ks])] (reduce (fn [out k] (if (eq (typeof k) 'string') (concat out (threadl (k.split '/') (remove (fn [el] (eq el ''))) (map ensureK))) (concat out [k]))) [] ks))) (defn get_ ([ks] (get_ ks :lastrev)) ([ks rev] (toJs (getIn (getState rev) (ensureKs ks))))) (defn set_ ([ks val] (set_ ks val true)) ([ks val to_clj] (threadf (swapState (fn [state] (assocIn state (ensureKs ks) (if to_clj (toClj val true) val)))) (get :lastrev)))) (defn remove_ [ks] (threadf (swapState (fn [state] (let [ks (into [] (ensureKs ks)) dissoc_mv (fn [s k] (if (isVector s) (into [] (concat (subvec s 0 k) (subvec s (inc k)))) (dissoc s k)))] (if (isEmpty (pop ks)) (dissoc_mv state (peek ks)) (updateIn state (pop ks) (fn [s] (dissoc_mv s (peek ks)))))))) (get :lastrev))) (defn peek_ ([ks] (peek_ ks :lastrev)) ([ks rev] (toJs (peek (getIn (getState rev) (ensureKs ks)))))) (defn pop_ [ks] (threadf (swapState (fn [state] (updateIn state (ensureKs ks) pop))) (get :lastrev))) (defn push_ ([ks val] (push_ ks val true)) ([ks val to_clj] (threadf (swapState (fn [state] (let [conj2 (fn [coll el] (ifNot coll [el] (conj coll el)))] (updateIn state (ensureKs ks) conj2 (if to_clj (toClj val true) val))))) (get :lastrev)))) (defn count_ ([ks] (count_ ks :lastrev)) ([ks rev] (count (getIn (getState rev) (ensureKs ks))))) (defn observe [ks callback] (let [uid (swap ouid inc)] (swap observers conj {:path (ensureKs ks) :callback callback :rev 0 :uid uid}) uid)) (defn unobserve [uid] (swap observers (fn [obss] (remove (fn [obs] (eq (get obs :uid) uid)) obss))) nil) (defn loop [msec] // TODO: do nothing if nrev is not changing // Keep track of :lastrev (as function argument?) // and avoid doing anything if :lastrev is the same // *and* there's only one entry in the state map (no history) // (an observer could have deferred) (swap observers (fn [obss] (loop [obss obss out [] diffCache {}] (if (isEmpty obss) out (let [obs (first obss) orev (get obs :rev) nrev (get (getState :lastrev) :rev)] (if (eq orev nrev) (recur (rest obss) (conj out obs) diffCache) (let [diff (if (get diffCache :rev) (get diffCache :rev) (diffStates orev :lastrev)) minus (getIn (nth diff 0) (get obs :path)) plus (getIn (nth diff 1) (get obs :path))] (recur (rest obss) (conj out (if (or minus plus) (if (neq ((get obs :callback) (toJs plus) (toJs minus) nrev orev) false) (assoc obs :rev nrev) obs) (assoc obs :rev nrev))) (if (get diffCache :rev) diffCache (assoc diffCache orev diff)))))))))) (whenNot (isEmpty (deref observers)) (let [minRev (reduce Math.min (map :rev (deref observers)))] (swap states updateIn [:map] (fn [m] (into {} (filter (fn [kv] (geq (first kv) minRev)) m)))))) (when (deref looping) (setTimeout (partial loop msec) msec))) (defn start ([] (start 16)) ([msec] (reset looping true) (loop msec))) (defn stop [] (reset looping false)) (export get get_) (export set set_) (export peek peek_) (export push push_) (export pop pop_) (export remove remove_) (export count count_) (export observe observe) (export unobserve unobserve) (export start start) (export stop stop) ); var state = require('./state'); var oid = state.observe("foo/bar", function(plus, minus) { console.log('OBSERVED: ' + minus + ' -> ' + plus); } ); state.start(); for (var i=0; i<1000; i++) { state.setval("foo/bar",i); } state.setval("foo/bar",1234); state.setval("foo/bar",1235); setTimeout(function() { state.setval("foo/bar",0); state.setval("foo/bar",1); for (var i=0; i<1000; i++) { state.setval("foo/bar",i); } }, 500); setTimeout(function() { state.unobserve(oid); }, 1000); setTimeout(function() { state.stop(); }, 2000); // Expected output: // OBSERVED: null -> 1235 // OBSERVED: 1235 -> 999 Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
__label__pos
0.714893
Time your shell script operations Pub. This is a note to self (so I don’t forgot about it) – it is not rocket science 😉 If you need to check how long it takes to run part of your bash script you can use the use PS4 trick, as explained partially here, but it is a bit messy and I don’t like to do the math by hand 😛 In order to test the performance bottleneck of one of my shell scripts I draft a small set of functions. One to start the clock ticking, another to check how long it passed since the last mark and another to reset the clock. You can download/copy into a file of your choice and then source it inside your script. The output is the nanoseconds passed between operations. If you make (any) use of it please let me know. I don’t think it will blow up your computer, but you’re at your own risk 😉 ####################################### # Bruno Lucas – v1.0 – 2012/10/22 # ####################################### TIME_TICKER=0 echoerr() { echo -e “$@” 1>&2; } function time_start() { TIME_TICKER=`date “+%s%N”` } #You can pass a message delimited by single quoted function time_mark() { CURR=`date +%s%N` DIFF=`echo “$CURR – $TIME_TICKER” | bc` echoerr “$DIFF\t$1” TIME_TICKER=$CURR } function time_reset() { TIME_TICKER=0 } To use: source timer.sh time_start some_op_of_mine 1 2 3 4 time_mark ‘After x’ and you’ll get something like ‘13789137   After x’ telling the elapsed time. PS: The echoerr function was stolen from here, it echos the content to STDERR, instead of STDOUT. PS1: Copy/paste from HTML can sometimes come with errors, always check the source code prior to execution.   facebooktwittergoogle_plusredditpinterestlinkedinmail Pub. Leave a Reply Pub.
__label__pos
0.687665
codetc - 网站开发技术 首页 后端 数据库 查看内容 如何提高MySQL Limit查询的性能 2015-3-29 17:00| 发布者: CODETC| 查看: 2082| 评论: 0 在MySQL数据库操作中,我们在做一些查询的时候总希望能避免数据库引擎做全表扫描,因为全表扫描时间长,而且其中大部分扫描对客户端而言是没有意义的。其实我们可以使用Limit关键字来避免全表扫描的情况,从而提高效率。 有个几千万条记录的表 on MySQL 5.0.x,现在要读出其中几十万万条左右的记录。常用方法,依次循环: select * from mytable where index_col = xxx limit offset, limit; 经验:如果没有blob/text字段,单行记录比较小,可以把 limit 设大点,会加快速度。 问题:头几万条读取很快,但是速度呈线性下降,同时 mysql server cpu 99% ,速度不可接受。 调用 explain select * from mytable where index_col = xxx limit offset, limit; 显示 type = ALL 在 MySQL optimization 的文档写到"All"的解释 A full table scan is done for each combination of rows from the previous tables. This is normally not good if the table is the first table not marked const, and usually very bad in all other cases. Normally, you can avoid ALL by adding indexes that allow row retrieval from the table based on constant values or column values from earlier tables. 看样子对于 all, mysql 就使用比较笨的方法,那就改用 range 方式? 因为 id 是递增的,也很好修改 sql 。 select * from mytable where id > offset and id < offset + limit and index_col = xxx explain 显示 type = range,结果速度非常理想,返回结果快了几十倍。 Limit语法 SELECT * FROM table LIMIT [offset,] rows | rows OFFSET offset LIMIT子句可以被用于强制 SELECT 语句返回指定的记录数。LIMIT接受一个或两个数字参数。参数必须是一个整数常量。 如果给定两个参数,第一个参数指定第一个返回记录行的偏移量,第二个参数指定返回记录行的最大数目。初始记录行的偏移量是 0(而不是 1)。 为了与 PostgreSQL 兼容,MySQL 也支持句法:LIMIT # OFFSET #。 mysql> SELECT * FROM table LIMIT 5,10; //检索记录行6-15 //为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为-1 mysql> SELECT * FROM table LIMIT 95,-1; //检索记录行96-last //如果只给定一个参数,它表示返回最大的记录行数目,换句话说,LIMIT n 等价于 LIMIT 0,n mysql> SELECT * FROM table LIMIT 5; //检索前5个记录行 MySQL的limit给分页带来了极大的方便,但数据量一大的时候,limit的性能就急剧下降。同样是取10条数据,下面两句就不是一个数量级别的。 select * from table limit 10000,10 select * from table limit 0,10 文中不是直接使用limit,而是首先获取到offset的id然后直接使用limit size来获取数据。根据他的数据,明显要好于直接使用limit。 这里我具体使用数据分两种情况进行测试。 1、offset比较小的时候 select * from table limit 10,10 //多次运行,时间保持在0.0004-0.0005之间 Select * From table Where vid >=(Select vid From table Order By vid limit 10,1) limit 10 //多次运行,时间保持在0.0005-0.0006之间,主要是0.0006 结论:偏移offset较小的时候,直接使用limit较优。这个显然是子查询的原因。 2、offset大的时候 select * from table limit 10000,10 //多次运行,时间保持在0.0187左右 Select * From table Where vid >=(Select vid From table Order By vid limit 10000,1) limit 10 //多次运行,时间保持在0.0061左右,只有前者的1/3。可以预计offset越大,后者越优。 文章来源 CODETC,欢迎分享,转载请注明地址: http://www.codetc.com/article-166-1.html 最新评论  作为游客发表评论,请输入您的昵称 返回顶部
__label__pos
0.718903
19 I want to highlight all the numbers appearing in an input code of a certain program by, for example, coloring them. By numbers I mean integer, rational and floating point numbers. I am trying with the listings page but with no success. I have noticed that specific numbers can be formatted with the morekeywords and alsoletter options on defining the language but I want to acomplish this task for any number. For example, I would like the code vector([3/5,4,0.4566]) to appear with the three numbers with color green (or whatever). Is it possible to do this in an automatic way? 2 22 Similar to solutions in Visualization in LaTeX of hamming distance, and Problem with the alignment of characters, you could use the literate command to define a style that is to be applied to each digit. Below I included a color for the . but commented out the color for the ,. enter image description here As there might be a period used outside of a number context, I have defined different styles based on the assumption that any period used in a number will have a digit following it. \documentclass[border=2pt]{standalone} \usepackage{listings} \usepackage{xcolor} \newcommand*{\FormatDigit}[1]{\textcolor{blue}{#1}} \lstdefinestyle{FormattedNumber}{% literate={0}{{\FormatDigit{0}}}{1}% {1}{{\FormatDigit{1}}}{1}% {2}{{\FormatDigit{2}}}{1}% {3}{{\FormatDigit{3}}}{1}% {4}{{\FormatDigit{4}}}{1}% {5}{{\FormatDigit{5}}}{1}% {6}{{\FormatDigit{6}}}{1}% {7}{{\FormatDigit{7}}}{1}% {8}{{\FormatDigit{8}}}{1}% {9}{{\FormatDigit{9}}}{1}% {.0}{{\FormatDigit{.0}}}{2}% Following is to ensure that only periods {.1}{{\FormatDigit{.1}}}{2}% followed by a digit are changed. {.2}{{\FormatDigit{.2}}}{2}% {.3}{{\FormatDigit{.3}}}{2}% {.4}{{\FormatDigit{.4}}}{2}% {.5}{{\FormatDigit{.5}}}{2}% {.6}{{\FormatDigit{.6}}}{2}% {.7}{{\FormatDigit{.7}}}{2}% {.8}{{\FormatDigit{.8}}}{2}% {.9}{{\FormatDigit{.9}}}{2}% %{,}{{\FormatDigit{,}}{1}% depends if you want the "," in color {\ }{{ }}{1}% handle the space , basicstyle=\ttfamily,% Optional to use this } \newcommand{\FormattedNumber}[1]{% \lstinline[style=FormattedNumber]{#1}% } \begin{document} \FormattedNumber{a.vector([3/5,4,0.4566])} \end{document} 6 • One caveat: This would format \FormattedNumber{a.vector(<stuff>)} by also making the period blue. It would be possible, but somewhat round-about to get that fixed using mathescape=true and then using \FormattedNumber{a$.$vector(<stuff>)}. – Werner Oct 20 '11 at 17:07 • @Werner: Excellent point. Have updated the solution to handle that case. – Peter Grill Oct 20 '11 at 17:19 • That's perfect!!! You saved me a lot of time. Thank you!!! – Rafa Gallego Oct 20 '11 at 18:22 • All replacements that include the comma should have 2 instead of 1 at the end. this defines the number of output characters and is important for the complicated spacing of listings. – stefanct Mar 29 '14 at 0:45 • @PeterGrill excellent solution! Only caveat for me is that it still highlights integers, even when they are commented. Is there a way to correct this? – han-tyumi Dec 16 '15 at 15:35 Your Answer By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.99935
Posted in: When I want an IoC container I usually either use Unity or create my own really simple one. But I’ve been meaning to try out some of the alternatives, and so I decided to give StructureMap a try for my latest project. I had two tasks to accomplish. The first was to tell it to use a particular concrete class (ConsoleLogger) as the implementer of my ILog interface. The second was to get it to scan the assembly and find all the implementers of my ICommand interface, without having to register each one explicitly. As you’d expect. the first task is very simple to accomplish. You create a new Container, and then map the interface to the concrete implementer using a fluent API. Here I’ve said that my logger will be a singleton: var container = new Container(x => x.ForSingletonOf<ILog>().Use<ConsoleLogger>()); var logger = container.GetInstance<ILog>(); The second task is also straightforward to achieve with StructureMap. We ask StructureMap to scan the calling assembly, and add all types of ICommand. The one gotcha is that I had to make the ICommand interface and implementing classes public for it to detect them. Here’s the registration code: var container = new Container(x => { x.ForSingletonOf<ILog>().Use<ConsoleLogger>(); x.Scan(a => { a.TheCallingAssembly(); a.AddAllTypesOf<ICommand>(); }); }); Now we can easily get hold of all the implementations of the ICommand interface like so: var commands = container.GetAllInstances<ICommand>(); As you can see, it’s very straightforward. In fact there are ways with StructureMap to simplify things further by making use of conventions. So if you’re looking for an IoC that can do auto-registration, why not give StructureMap a try?
__label__pos
0.618189
# -*- encoding: binary -*- require "thread" require "time" require "socket" require "rack" require "aggregate" # Raindrops::Watcher is a stand-alone Rack application for watching # any number of TCP and UNIX listeners (all of them by default). # # It depends on the {Aggregate RubyGem}[https://rubygems.org/gems/aggregate] # # In your Rack config.ru: # # run Raindrops::Watcher(options = {}) # # It takes the following options hash: # # - :listeners - an array of listener names, (e.g. %w(0.0.0.0:80 /tmp/sock)) # - :delay - interval between stats updates in seconds (default: 1) # # Raindrops::Watcher is compatible any thread-safe/thread-aware Rack # middleware. It does not work well with multi-process web servers # but can be used to monitor them. It consumes minimal resources # with the default :delay. # # == HTTP endpoints # # === GET / # # Returns an HTML summary listing of all listen interfaces watched on # # === GET /active/$LISTENER.txt # # Returns a plain text summary + histogram with X-* HTTP headers for # active connections. # # e.g.: curl https://raindrops-demo.bogomips.org/active/0.0.0.0%3A80.txt # # === GET /active/$LISTENER.html # # Returns an HTML summary + histogram with X-* HTTP headers for # active connections. # # e.g.: curl https://raindrops-demo.bogomips.org/active/0.0.0.0%3A80.html # # === GET /queued/$LISTENER.txt # # Returns a plain text summary + histogram with X-* HTTP headers for # queued connections. # # e.g.: curl https://raindrops-demo.bogomips.org/queued/0.0.0.0%3A80.txt # # === GET /queued/$LISTENER.html # # Returns an HTML summary + histogram with X-* HTTP headers for # queued connections. # # e.g.: curl https://raindrops-demo.bogomips.org/queued/0.0.0.0%3A80.html # # === POST /reset/$LISTENER # # Resets the active and queued statistics for the given listener. # # === GET /tail/$LISTENER.txt?active_min=1&queued_min=1 # # Streams chunked a response to the client. # Interval is the preconfigured +:delay+ of the application (default 1 second) # # The response is plain text in the following format: # # ISO8601_TIMESTAMP LISTENER_NAME ACTIVE_COUNT QUEUED_COUNT LINEFEED # # Query parameters: # # - active_min - do not stream a line until this active count is reached # - queued_min - do not stream a line until this queued count is reached # # == Response headers (mostly the same names as Raindrops::LastDataRecv) # # - X-Count - number of samples polled # - X-Last-Reset - date since the last reset # # The following headers are only present if X-Count is greater than one. # # - X-Min - lowest number of connections recorded # - X-Max - highest number of connections recorded # - X-Mean - mean number of connections recorded # - X-Std-Dev - standard deviation of connection count # - X-Outliers-Low - number of low outliers (hopefully many for queued) # - X-Outliers-High - number of high outliers (hopefully zero for queued) # - X-Current - current number of connections # - X-First-Peak-At - date of when X-Max was first reached # - X-Last-Peak-At - date of when X-Max was last reached # # = Demo Server # # There is a server running this app at https://raindrops-demo.bogomips.org/ # The Raindrops::Middleware demo is also accessible at # https://raindrops-demo.bogomips.org/_raindrops # # The demo server is only limited to 30 users, so be sure not to abuse it # by using the /tail/ endpoint too much. class Raindrops::Watcher # :stopdoc: attr_reader :snapshot include Rack::Utils include Raindrops::Linux DOC_URL = "https://bogomips.org/raindrops/Raindrops/Watcher.html" Peak = Struct.new(:first, :last) def initialize(opts = {}) @tcp_listeners = @unix_listeners = nil if l = opts[:listeners] tcp, unix = [], [] Array(l).each { |addr| (addr =~ %r{\A/} ? unix : tcp) << addr } unless tcp.empty? && unix.empty? @tcp_listeners = tcp @unix_listeners = unix end end @agg_class = opts[:agg_class] || Aggregate @start_time = Time.now.utc @active = Hash.new { |h,k| h[k] = @agg_class.new } @queued = Hash.new { |h,k| h[k] = @agg_class.new } @resets = Hash.new { |h,k| h[k] = @start_time } @peak_active = Hash.new { |h,k| h[k] = Peak.new(@start_time, @start_time) } @peak_queued = Hash.new { |h,k| h[k] = Peak.new(@start_time, @start_time) } @snapshot = [ @start_time, {} ] @delay = opts[:delay] || 1 @lock = Mutex.new @start = Mutex.new @cond = ConditionVariable.new @thr = nil end def hostname Socket.gethostname end # rack endpoint def call(env) @start.synchronize { @thr ||= aggregator_thread(env["rack.logger"]) } case env["REQUEST_METHOD"] when "GET" get env when "HEAD" r = get(env) r[2] = [] r when "POST" post env else Rack::Response.new(["Method Not Allowed"], 405).finish end end def aggregate!(agg_hash, peak_hash, addr, number, now) agg = agg_hash[addr] if (max = agg.max) && number > 0 && number >= max peak = peak_hash[addr] peak.first = now if number > max peak.last = now end agg << number end def aggregator_thread(logger) # :nodoc: @socket = sock = Raindrops::InetDiagSocket.new thr = Thread.new do begin combined = tcp_listener_stats(@tcp_listeners, sock) combined.merge!(unix_listener_stats(@unix_listeners)) @lock.synchronize do now = Time.now.utc combined.each do |addr,stats| aggregate!(@active, @peak_active, addr, stats.active, now) aggregate!(@queued, @peak_queued, addr, stats.queued, now) end @snapshot = [ now, combined ] @cond.broadcast end rescue => e logger.error "#{e.class} #{e.inspect}" end while sleep(@delay) && @socket sock.close end wait_snapshot thr end def non_existent_stats(time) [ time, @start_time, @agg_class.new, 0, Peak.new(@start_time, @start_time) ] end def active_stats(addr) # :nodoc: @lock.synchronize do time, combined = @snapshot stats = combined[addr] or return non_existent_stats(time) tmp, peak = @active[addr], @peak_active[addr] [ time, @resets[addr], tmp.dup, stats.active, peak ] end end def queued_stats(addr) # :nodoc: @lock.synchronize do time, combined = @snapshot stats = combined[addr] or return non_existent_stats(time) tmp, peak = @queued[addr], @peak_queued[addr] [ time, @resets[addr], tmp.dup, stats.queued, peak ] end end def wait_snapshot @lock.synchronize do @cond.wait @lock @snapshot end end def std_dev(agg) agg.std_dev.to_s rescue Errno::EDOM "NaN" end def agg_to_hash(reset_at, agg, current, peak) { "X-Count" => agg.count.to_s, "X-Min" => agg.min.to_s, "X-Max" => agg.max.to_s, "X-Mean" => agg.mean.to_s, "X-Std-Dev" => std_dev(agg), "X-Outliers-Low" => agg.outliers_low.to_s, "X-Outliers-High" => agg.outliers_high.to_s, "X-Last-Reset" => reset_at.httpdate, "X-Current" => current.to_s, "X-First-Peak-At" => peak.first.httpdate, "X-Last-Peak-At" => peak.last.httpdate, } end def histogram_txt(agg) updated_at, reset_at, agg, current, peak = *agg headers = agg_to_hash(reset_at, agg, current, peak) body = agg.to_s # 7-bit ASCII-clean headers["Content-Type"] = "text/plain" headers["Expires"] = (updated_at + @delay).httpdate headers["Content-Length"] = body.size.to_s [ 200, headers, [ body ] ] end def histogram_html(agg, addr) updated_at, reset_at, agg, current, peak = *agg headers = agg_to_hash(reset_at, agg, current, peak) body = "" \ "#{hostname} - #{escape_html addr}" \ "" << headers.map { |k,v| "" }.join << " #{k.gsub(/^X-/, '')}#{v} #{escape_html agg} " \ " " \ " " \ "" headers["Content-Type"] = "text/html" headers["Expires"] = (updated_at + @delay).httpdate headers["Content-Length"] = body.size.to_s [ 200, headers, [ body ] ] end def get(env) retried = false begin case env["PATH_INFO"] when "/" index when %r{\A/active/(.+)\.txt\z} histogram_txt(active_stats(unescape($1))) when %r{\A/active/(.+)\.html\z} addr = unescape $1 histogram_html(active_stats(addr), addr) when %r{\A/queued/(.+)\.txt\z} histogram_txt(queued_stats(unescape($1))) when %r{\A/queued/(.+)\.html\z} addr = unescape $1 histogram_html(queued_stats(addr), addr) when %r{\A/tail/(.+)\.txt\z} tail(unescape($1), env) else not_found end rescue Errno::EDOM raise if retried retried = true wait_snapshot retry end end def not_found Rack::Response.new(["Not Found"], 404).finish end def post(env) case env["PATH_INFO"] when %r{\A/reset/(.+)\z} reset!(env, unescape($1)) else not_found end end def reset!(env, addr) @lock.synchronize do @active.include?(addr) or return not_found @active.delete addr @queued.delete addr @resets[addr] = Time.now.utc @cond.wait @lock end req = Rack::Request.new(env) res = Rack::Response.new url = req.referer || "#{req.host_with_port}/" res.redirect(url) res["Content-Type"] = "text/plain" res.write "Redirecting to #{url}" res.finish end def index updated_at, all = snapshot headers = { "Content-Type" => "text/html", "Last-Modified" => updated_at.httpdate, "Expires" => (updated_at + @delay).httpdate, } body = "" \ "#{hostname} - all interfaces" \ " Updated at #{updated_at.iso8601} " \ "" \ "" \ "" << all.sort do |a,b| a[0] <=> b[0] # sort by addr end.map do |addr,stats| e_addr = escape addr "" \ "" \ "" \ "" \ "" \ "" \ end.join << " addressactivequeuedreset #{escape_html addr}#{stats.active}#{stats.queued} " \ " " \ " " \ "This is running the #{self.class} service, see " \ "#{DOC_URL} " \ "for more information and options." \ " " \ "" headers["Content-Length"] = body.size.to_s [ 200, headers, [ body ] ] end def tail(addr, env) Tailer.new(self, addr, env).finish end # This is the response body returned for "/tail/$ADDRESS.txt". This # must use a multi-threaded Rack server with streaming response support. # It is an internal class and not expected to be used directly class Tailer def initialize(rdmon, addr, env) # :nodoc: @rdmon = rdmon @addr = addr q = Rack::Utils.parse_query env["QUERY_STRING"] @active_min = q["active_min"].to_i @queued_min = q["queued_min"].to_i len = addr.size len = 35 if len > 35 @fmt = "%20s % #{len}s % 10u % 10u\n" case env["HTTP_VERSION"] when "HTTP/1.0", nil @chunk = false else @chunk = true end end def finish headers = { "Content-Type" => "text/plain", "Cache-Control" => "no-transform", "Expires" => Time.at(0).httpdate, } headers["Transfer-Encoding"] = "chunked" if @chunk [ 200, headers, self ] end # called by the Rack server def each # :nodoc: begin time, all = @rdmon.wait_snapshot stats = all[@addr] or next stats.queued >= @queued_min or next stats.active >= @active_min or next body = sprintf(@fmt, time.iso8601, @addr, stats.active, stats.queued) body = "#{body.size.to_s(16)}\r\n#{body}\r\n" if @chunk yield body end while true yield "0\r\n\r\n" if @chunk end end # shuts down the background thread, only for tests def shutdown @socket = nil @thr.join if @thr @thr = nil end # :startdoc: end
__label__pos
0.966378
CkEdDSA Python Reference Documentation CkEdDSA Current Version: 9.5.0.93 Class for generating Ed25519 keys and creating/validating Ed25519 signatures. This class was added in v9.5.0.83. Object Creation obj = chilkat.CkEdDSA() Properties Algorithm # strVal is a string # ckStr is a CkString edDSA.get_Algorithm(ckStr); strVal = edDSA.algorithm(); edDSA.put_Algorithm(strVal); Introduced in version 9.5.0.91 Can be "Ed25519", "Ed25519ph", or "Ed25519ctx". The default is "Ed25519". This property was introduced in v9.5.0.91. Prior to this version, "Ed25519" was the only EdDSA instance supported. top Context # strVal is a string # ckStr is a CkString edDSA.get_Context(ckStr); strVal = edDSA.context(); edDSA.put_Context(strVal); Introduced in version 9.5.0.91 The context bytes (in hex string format) to be used for Ed25519ctx or Ed25519ph. top DebugLogFilePath # strVal is a string # ckStr is a CkString edDSA.get_DebugLogFilePath(ckStr); strVal = edDSA.debugLogFilePath(); edDSA.put_DebugLogFilePath(strVal); If set to a file path, causes each Chilkat method or property call to automatically append it's LastErrorText to the specified log file. The information is appended such that if a hang or crash occurs, it is possible to see the context in which the problem occurred, as well as a history of all Chilkat calls up to the point of the problem. The VerboseLogging property can be set to provide more detailed information. This property is typically used for debugging the rare cases where a Chilkat method call hangs or generates an exception that halts program execution (i.e. crashes). A hang or crash should generally never happen. The typical causes of a hang are: 1. a timeout related property was set to 0 to explicitly indicate that an infinite timeout is desired, 2. the hang is actually a hang within an event callback (i.e. it is a hang within the application code), or 3. there is an internal problem (bug) in the Chilkat code that causes the hang. top LastErrorHtml # strVal is a string # ckStr is a CkString edDSA.get_LastErrorHtml(ckStr); strVal = edDSA.lastErrorHtml(); Provides information in HTML format about the last method/property called. If a method call returns a value indicating failure, or behaves unexpectedly, examine this property to get more information. top LastErrorText # strVal is a string # ckStr is a CkString edDSA.get_LastErrorText(ckStr); strVal = edDSA.lastErrorText(); Provides information in plain-text format about the last method/property called. If a method call returns a value indicating failure, or behaves unexpectedly, examine this property to get more information. top LastErrorXml # strVal is a string # ckStr is a CkString edDSA.get_LastErrorXml(ckStr); strVal = edDSA.lastErrorXml(); Provides information in XML format about the last method/property called. If a method call returns a value indicating failure, or behaves unexpectedly, examine this property to get more information. top LastMethodSuccess # boolVal is a boolean boolVal = edDSA.get_LastMethodSuccess(); edDSA.put_LastMethodSuccess(boolVal); Introduced in version 9.5.0.52 Indicate whether the last method call succeeded or failed. A value of True indicates success, a value of False indicates failure. This property is automatically set for method calls. It is not modified by property accesses. The property is automatically set to indicate success for the following types of method calls: • Any method that returns a string. • Any method returning a Chilkat object, binary bytes, or a date/time. • Any method returning a standard boolean status value where success = True and failure = False. • Any method returning an integer where failure is defined by a return value less than zero. Note: Methods that do not fit the above requirements will always set this property equal to True. For example, a method that returns no value (such as a "void" in C++) will technically always succeed. top Utf8 # boolVal is a boolean boolVal = edDSA.get_Utf8(); edDSA.put_Utf8(boolVal); When set to True, all "const char *" arguments are interpreted as utf-8 strings. If set to False (the default), then "const char *" arguments are interpreted as ANSI strings. Also, when set to True, and Chilkat method returning a "const char *" is returning the utf-8 representation. If set to False, all "const char *" return values are ANSI strings. top VerboseLogging # boolVal is a boolean boolVal = edDSA.get_VerboseLogging(); edDSA.put_VerboseLogging(boolVal); If set to True, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is False. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance. top Version # strVal is a string # ckStr is a CkString edDSA.get_Version(ckStr); strVal = edDSA.version(); Version of the component/library, such as "9.5.0.63" top Methods GenEd25519Key # prng is a CkPrng # privKey is a CkPrivateKey status = edDSA.GenEd25519Key(prng, privKey); Introduced in version 9.5.0.83 Generates an Ed25519 key. privKey is an output argument. The generated key is created in privKey. Returns True for success, False for failure. More Information and Examples top SharedSecretENC # privkey is a CkPrivateKey # pubkey is a CkPublicKey # encoding is a string # outStr is a CkString (output) status = edDSA.SharedSecretENC(privkey, pubkey, encoding, outStr); retStr = edDSA.sharedSecretENC(privkey, pubkey, encoding); Introduced in version 9.5.0.83 Computes a shared secret given a private and public key. For example, Alice and Bob can compute the identical shared secret by doing the following: Alice sends Bob her public key, and Bob calls SharedSecretENC with his private key and Alice's public key. Bob sends Alice his public key, and Alice calls SharedSecretENC with her private key and Bob's public key. Both calls to SharedSecretENC will produce the same result. The resulting bytes are returned in encoded string form (hex, base64, etc) as specified by encoding. Returns True for success, False for failure. top SignBdENC # bd is a CkBinData # encoding is a string # privkey is a CkPrivateKey # outStr is a CkString (output) status = edDSA.SignBdENC(bd, encoding, privkey, outStr); retStr = edDSA.signBdENC(bd, encoding, privkey); Introduced in version 9.5.0.83 Signs the contents of bd and returns the signature according to encoding. The encoding can be any encoding supported by Chilkat, such as "hex", "base64", etc. Returns True for success, False for failure. top VerifyBdENC # bd is a CkBinData # encodedSig is a string # enocding is a string # pubkey is a CkPublicKey status = edDSA.VerifyBdENC(bd, encodedSig, enocding, pubkey); Introduced in version 9.5.0.83 Verifies the signature against the contents of bd. The encodedSig is passed as an encoded string (such as hex, base64, etc.) using the encoding specified by enocding. The pubkey contains the Ed25519 public key used to verify. Returns True for success, False for failure. More Information and Examples top
__label__pos
0.549369
155 $\begingroup$ Cosine is just a change in the argument of sine, and vice versa. $$\sin(x+\pi/2)=\cos(x)$$ $$\cos(x-\pi/2)=\sin(x)$$ So why do we have both of them? Do they both exist simply for convenience in defining the other trig functions? $\endgroup$ 26 • 37 $\begingroup$ If you look at the $\cos$ and $\sin$ from a geometric point of view, it's quite clear why it's useful to have both of them. $\endgroup$ – Asaf Karagila Aug 31, 2015 at 16:37 • 49 $\begingroup$ You really mean, "why do we name them both?" Because it is quite clear from your equation why one exists if the other does. $\endgroup$ Aug 31, 2015 at 16:39 • 147 $\begingroup$ Why do we have either $\sin$ or $\cos$, when we have the more fundamental $e^x$? $$\sin(x)=\frac{e^{ix}-e^{-ix}}{2i}\qquad\qquad \cos(x)=\frac{e^{ix}+e^{-ix}}{2}$$ $\endgroup$ Aug 31, 2015 at 16:58 • 77 $\begingroup$ @Zev: Why do we have $e^x$ when we have the more fundamental $\lim_{n\to\infty}(1+1/n)^x$? :-) $\endgroup$ – Asaf Karagila Aug 31, 2015 at 19:43 • 71 $\begingroup$ 1 + 1 = 2 Why do we have both of them? 2s are just 1s added up. $\endgroup$ – Plutor Sep 1, 2015 at 12:26 17 Answers 17 158 $\begingroup$ You seem to be asking why we name them both, rather than why they exist, since the very relationships you've written shows that if one exists, the other does, too. Essentially, all mathematical notation and names, except for a very small subset, are for convenience/clarity/human communication. Math does not require that we name any function consistently across separate proofs, but it becomes much easier to communicate and think about things when we do. I prefer the relationship: $$\sin(x)=\cos(\pi/2-x)\\\cos(x)=\sin(\pi/2-x)$$ since this is symmetric and obviously geometric when $0\leq x\leq \pi/2$, and because this is also the relationship between "tangent" and "cotangent" and "secant" and "cosecant." It indicates a duality in these functions. It is certainly something of a paradox that adding more names often simplifies our understanding. In particular, if you defined only one, it would give you a sense that one of these functions was "primary." There is a hint of that error even in the names "sine" and "cosine," which vaguely implies that "sine" is primary, but it would be particularly strong if we only defined "sine" and never defined "cosine." We would have a harder time grasping the duality that happens in trig functions. If you actually must start with one function, most mathematicians wouldn't start with $\cos x$ or $\sin x,$ they'd start with the complex-valued function: $\operatorname{cis}(x)=\cos(x)+i\sin(x).$ This has the property $\operatorname{cis}(x)\operatorname{cis}(y)=\operatorname{cis}(x+y),$ and can also be written as $e^{ix}.$ You can define $\cos x$ and $\sin x$ in terms of $\operatorname{cis} x:$ $$\cos x=\frac{1}{2}\left(\operatorname{cis}(x)+\operatorname{cis}(-x)\right)\\ \sin x=\frac{1}{2i}\left(\operatorname{cis}(x)-\operatorname{cis}(-x)\right)$$ Addition: I recently heard, in a lecture that covered some of the accomplishments of the early Muslim world, that they acquired knowledge of the sine function from India, and developed the other trigonometric functions. So if you want someone to blame, we can blame them. 🤓 $\endgroup$ 18 • 23 $\begingroup$ In my opinion, cosine seems primary. Also, why didn't people define $\sec:=\frac1\sin$? I have this extra "co" to deal with whenever I invert the value and it's so annoying… $\endgroup$ Aug 31, 2015 at 18:55 • 38 $\begingroup$ It does bug me that $\sec$ is related to $\cos$ and $\csc$ is related to $\sin$, because the "co" switches places. However, geometrically it makes sense: things without "co" (sine, tangent and secant) are to do with the sine length in the unit circle, which is vertical; meanwhile things with the "co" are to do with the cosine length, which is horizontal. $\endgroup$ – Will R Aug 31, 2015 at 19:12 • 8 $\begingroup$ @columbus8myhw if on the unit circle, you draw the vertical line tangent to it at $(1,0)$, then take its intersection with angle ray (the other along the positive $x$-axis) then... (1) the height above the x-axis is the tangent of the angle, while (2) the length segment that cuts across the circle along the ray to the vertical line is the secant of the angle. Well, it might not satisfy you as an optimal naming convention, but that's why it was defined that way. $\endgroup$ – Stan Liou Aug 31, 2015 at 19:13 • 12 $\begingroup$ Alternatively, $\sin,\sec,\tan$ are all increasing on $(0,\pi/2)$. But yeah, it bugged me when I took trig way back when. $\endgroup$ Aug 31, 2015 at 19:14 • 2 $\begingroup$ @Ovi Trying to remember what I was thinking two years ago: When you write them out in term of Euler's formula, cosine is $\dfrac{e^{i\theta}+e^{-i\theta}}2$ and sine is $\dfrac{e^{i\theta}-e^{-i\theta}}{2i}$; doesn't the former look a lot more primary and clean? In addition, $\cos(n\theta)$ can be written as a polynomial in terms of $\cos(\theta)$, while $\sin(n\theta)$ cannot be written as a polynomial of $\sin(\theta)$. $\endgroup$ Jun 9, 2017 at 22:42 112 $\begingroup$ $$ \sin^2 \alpha + \cos^2 \alpha =1, $$ $$ \sin^2 \alpha + \sin^2 \left( \alpha + \frac{\pi}{2} \right) =1. $$ Which one do you prefer? Post scriptum: of course this is not a deep answer, but I think that sometimes mathematicians prefer elegance to logical "economy". $\endgroup$ 1 • 38 $\begingroup$ You should make a "PS" to explain what the "post scriptum" means $\endgroup$ – Ooker Sep 6, 2015 at 12:25 34 $\begingroup$ The question is ridiculous. (I'm afraid to say.) It's equivalent to asking "Why are there words for both North and South?" (Of course you could just use "negative North" at all times, if desired.) In my opinion, one would only ask the question at hand, if, one has rather naively "just noticed" - let's put it that way - that sine and cosine are complementary. Note too that, indeed, in English co-sine is simply "sine" ... with the appropriate prefix!! Just as you'd expect. Again to make analogy, one could ask questions such as "why do we label both matter and antimatter!" or "Why label both up and down?" It's clear, traditional, and expected in languages that there are matching terms for complementary qualities {rather than, let us say "minimalistically," using only the one and then the negative of it} ... heaven and hell, paradis et enfer. $\endgroup$ 7 • 10 $\begingroup$ A double plus good answer if ever there was one. $\endgroup$ – T. Kiley Sep 3, 2015 at 10:54 • 3 $\begingroup$ If anything, I think it's more like asking "Why are there words for both North and East" - almost exactly so. $\endgroup$ – user81060 Sep 3, 2015 at 12:38 • 1 $\begingroup$ I had exactly the same thought--this is like asking why we have words for "up" and "down" when you could just use one word all the time. (I'm going not down this mountain right now!) Sine is opposite over hypotenuse, and cosine is adjacent over hypotenuse. May as well ask why a triangle has three sides! $\endgroup$ – ErikE Sep 4, 2015 at 0:47 • 3 $\begingroup$ Coming back to this answer 5 years later, and I still don't like it. $\endgroup$ – Tdonut Aug 4, 2020 at 14:51 • 2 $\begingroup$ This has a lot of upvotes for an answerless rant about the question. $\endgroup$ – user Nov 26, 2020 at 4:15 20 $\begingroup$ I think it's conceptually cleaner to have both $\cos$ and $\sin$ as distinct notations, for the following reason: in my opinion, it's a bit of a "coincidence" that each of the functions $\{\cos,\sin\}$ can be described as translations of the other. My preferred definition of these two functions is the following: first, position yourself at $(1,0)$ on the unit circle. Then start walking anticlockwise at unit speed. It follows that if the time elapsed is $t$, your $x$-coordinate will be $\cos t$ and your $y$-coordinate will be $\sin t$. But notice that, in general, this way of producing pairs of functions (namely: positioning yourself on a curve and walking at unit speed, and then projecting onto the $x$ and $y$ coordinate axes) won't usually result in a pair of functions such that each can be defined as a translation of the other. The ability to define $\cos$ and $\sin$ in terms of each other is specifically a quirk of circles centered at the origin. In some sense, it's kind of a coincidence. By the way, this viewpoint explains why $\cos^2 t + \sin^2 t = 1$; it's because you're walking on the curve defined by $x^2+y^2= 1$. This also explains why $\cos(0) = 1$ and $\sin(0)= 0$; it's because we positioned ourselves at $(1,0)$ to begin with. It also explains why $(\cos' t)^2+(\sin't)^2= 1$; it's because you're walking at unit speed. And finally, this explains why $\sin'(0)>0;$. It's because we chose to start walking anticlockwise. I'm pretty sure these four conditions (listed below for your convenience) completely characterize the ordered pair ($\cos,\sin$) among all ordered pairs of differentiable functions $\mathbb{R} \rightarrow \mathbb{R}$. 1. $\cos^2 t + \sin^2 t = 1$ 2. $\cos(0) = 1, \sin(0) = 0$ 3. $(\cos't)^2+(\sin't)^2 = 1$ 4. $\sin'(0) > 0$ $\endgroup$ 7 • 1 $\begingroup$ Those conditions aren't complete. Be nice and provide a proof with the correct conditions :) (easy counterexample, stick with cosine but instead of sine use negative sine) $\endgroup$ Aug 31, 2015 at 19:31 • 9 $\begingroup$ In some sense, it's a kind of coincidence, but in another sense it isn't; the reason we care at all about parameterizing circles is precisely that they're symmetric, and the ability to express $\sin$ and $\cos$ in terms of each other is a consequence of that symmetry... $\endgroup$ – Micah Aug 31, 2015 at 19:35 • 1 $\begingroup$ @Chan-HoSuh, thanks for the counterexamples; I've added a fourth condition to eliminate the problem. Honestly, I really have no idea how to prove this. Analysis is a bit of a blind spot for me at the moment. Feel free to edit your own proof into the question. I've community-wikified it. $\endgroup$ Aug 31, 2015 at 19:35 • 1 $\begingroup$ @goblin,Of course your conditions work, since they translate (in words) to "$(\cos(x),\sin(x))$ is the arclength parameterization of the unit circle, starting at $(0,1)$ and moving in the positive direction", which is basically the definition of sine and cosine used most commonly in calculus courses. It is not too hard to show, inductively, that all orders of derivatives at $0$ are what they are supposed to be, by differentiating implicitly. Try it out! So this definition agrees with the power series definition, at least. $\endgroup$ Aug 31, 2015 at 21:27 • 2 $\begingroup$ @Chan-HoSuh, I'm not following. Note that $\cos^2 t+\sin^2t=1$ forces us to remain on unit circle centered at the origin. $\endgroup$ Sep 1, 2015 at 4:50 12 $\begingroup$ Suppose you're walking counterclockwise around the unit circle, starting at the point with coordinates $(1, 0)$. When you've walked a distance of $\theta$, your coordinates are $(\cos \theta, \sin \theta)$. To me, that's why it's natural to name both cosine and sine: it takes two coordinates to describe a point in the plane, and both of those coordinates deserve names. $\endgroup$ 1 • $\begingroup$ While not as "deep" as the other answers; I think this is the best. You can take any curve in the plane or on the earth and ask for the coordinates (x,y) and have two functions x(t),y(t) . If you constrain the curve to be a circle (constant radius) then the coordinates reflect the symmetry of your chosen curve and are thus degenerate in the questioners sense. $\endgroup$ – rrogers Sep 2, 2015 at 17:19 11 $\begingroup$ Mathematics is about making definitions that are as elegant and nice as possible, and allow your conclusions to easily or straightforwardly follow. In this case, it actually turns out the most elegant function, and the most helpful to understanding, is not cosine or sine. It is $$ \textbf{cis}(x) = e^{ix} = \cos x + i \sin x. $$ Of course, this is a complex-valued function--it takes in a real number $x$ and returns the point on the unit circle at angle $x$. But all of the properties you know about sine and cosine can be derived from this. But more importantly, we see that $\cos$ and $\sin$ naturally arise in tandem, one as the real part and one as the imaginary part of $\text{cis}(x)$. So it makes little sense to define only one of the two without defining both. Why do we define $\cos$ and $\sin$ at all, if we could just use $\text{cis}$? Because we often work with real numbers, and it is nice to have names for the real number functions arising from the complex exponential so that we don't have to insert imaginary numbers into real-number expressions that eventually cancel out. Also for historical reasons. $\endgroup$ 0 5 $\begingroup$ I would suggest two reasons why we have both sin and cos. First, historically, those who originally developed trigonometry started down the path of defining both functions, and then discovered various relationships between the two functions. Rather than redefine the work they did, we retain the functions as separate entities. Second, for simplicity. The equation for a circular arc for example, can be more simply written as $x=\cos(t)$, $y=\sin(t)$, than as $x=\cos(t)$, $y=\cos(t-\pi/2)$. If we are really trying to economize on functions, we could rewrite the tangent function $\tan(x)=\sin(x)/\cos(x)$ as $\cos(x-\pi/2)/\cos(x)$, but I think it would be more difficult to talk about the function this way, or to describe some of its remarkable properties, such as $\tan'(x)=\sec^2(x)$ or $\tan^2(x)+1=\sec^2(x)$. From these two identities we can deduce: $\tan'(x) = \tan^2(x)+1$, which means $\tan(x)$ is a solution to the differential equation: $y' = y^2+ 1$. I'll leave it to you to rewrite this derivation using $\cos(x)$ only.   :) $\endgroup$ 4 $\begingroup$ Consider: • Why do we say up and down instead of just up, since down is just reversed up? • Why is liquid measured in liters when you could just use cubic decimeters? Because each unit or word is appropriate to the thing it's measuring. A triangle has three sides. In a right triangle, each side's length divided by another side's length gives a ratio that reliably relates to one of the (non-right) angles of the triangle. You'll notice that the permutations of 3 items taken 2 at a time is 6, which just happens to be how many basic trigonometric functions there are (not counting their inverses): opposite / hypotenuse : sine hypotenuse / opposite : cosecant adjacent / hypotenuse : cosine hypotenuse / adjacent : secant opposite / adjacent : tangent adjacent / opposite : cotangent Which of these ratios is not useful? The fact that all of these can be determined from the others is irrelevant. By the same logic as your question, why use more than just one of the six names? While they all describe the same thing, a triangle, they do it from useful, even if different, perspectives. $\endgroup$ 0 3 $\begingroup$ Because $-1$ has no root in the reals. Both sine and cosine can be defined as solutions to the differential equation $$ f''(x) = -1 \cdot f(x). $$ Which one you get depends only on the boundary condition. Now, if the second derivative is so useful, then surely the first derivative should matter too! It's tempting to write $$ f'(x) = \sqrt{-1} \cdot f(x). $$ and indeed it kind of works: it gives the complex function $\backslash t \mapsto e^{it}$. But for the applications the trigonometric functions were invented for – geometry, physics... – complex numbers can't really be used, as in, you can't measure a complex quantity. To stay in the reals, we just leave the definition a second-order differential equation, but also give the first derivative a name of its own. $\endgroup$ 2 • $\begingroup$ Mh, isn't that a counter-argument ? The first order equation has a single solution $Ze^{it}$, which corresponds to a sinusoid with indeterminate phase and amplitude, like $A\cdot\sin(t;\phi)$ or $A\cdot \sin_\phi(t)$. $\endgroup$ – user65203 Sep 2, 2015 at 10:50 • 1 $\begingroup$ @YvesDaoust: but the first-order equation can't even be phrased without complex numbers. And though complex numbers are of course a greatly useful concept, there are good reasons to also know how to live without them. $\endgroup$ Sep 2, 2015 at 11:01 3 $\begingroup$ Before calculators and computers we had tables of values trig functions. Having all the trig functions: $\sin, \cos, \sec, \csc, \tan, \cot$ made doing geometric calculations easier. You didn't have to first convert a cos into a sin before looking it up in the tables. It saved a step. The $\sec$ and $\csc$ came into mathematical fashion when calculations for sailing ships across oceans were easier using them. You can read more about the history of trig functions over thousands of years at http://www-history.mcs.st-and.ac.uk/HistTopics/Trigonometric_functions.html $\endgroup$ 2 • $\begingroup$ I'd like to add a reference to the diagram on wikipedia: upload.wikimedia.org/wikipedia/commons/9/9d/Circle-trig6.svg -- A dozen different named and highly redundant trig functions. Many have fallen out of use, but they all were named at one point. $\endgroup$ – zebediah49 Sep 3, 2015 at 17:55 • 2 $\begingroup$ Nice diagram! I can imagine the midshipmen on 18th century sailing ship learning all these trig functions to do their spherical geometry calculations to figure out where the ship was today. :-) $\endgroup$ Sep 4, 2015 at 13:20 2 $\begingroup$ They must both have names in order to preserve the symmetry when writing down relationships: in complex arithmetics ($e^{ix}=\cos x+i\sin x$) or in calculus ($\sin' x=\cos x$), we see that they are two parts of the same coin, so if you only keep the name of one, expressions become lopsided and just plain ugly. You could just define one (and for the purpose of computing it numerically, you can certainly use just one to compute both), but in math, you want elegance. Speaking of, a more pertinent question would be, why do $\csc$ and $sec$ exist. They have no real use except for creating confusion: they are fractions, don't naturally arise from linear relationships (sin/cos are components of complex numbers, describe rotation, solutions to common differential equations) and, most importantly, they make otherwise simple expressions look unrecognizable and unreadable. $\endgroup$ 2 • $\begingroup$ Secants were of major interest to the maritime schools and unsolved problems for many years with regards to secants made it a major topic of curiosity probably. $\endgroup$ – user507974 Sep 3, 2015 at 5:50 • $\begingroup$ @user507974 of course, there are problems when you need to divide by a cosine. But mathematically, there is no elegance or structure that would make defining sec=1/cos better instead of worse. There are just twice as many relationships between functions to remember. It's sort of like invention of grads as angular units for the sake of "convenience". $\endgroup$ – orion Sep 3, 2015 at 7:06 2 $\begingroup$ This is an elaboration on Vectornaut's answer and hopefully more elementary than most others; actually two viewpoints. The explanations are kept elementary in order to emphasize the origin of calculations sin() and cos() and subsequent relations like the one in the question are based long after the original terms and are reflections of underlying symetries that people needed and wanted. Consider any curve on a plane (or in space if you like the reasoning is the same. To embed it in a mathematical structure we can envision writing the curve paramatricized by s thusly (x(s),y(s). Now we use this technique to describe a circle with a parameterization of distance from the center and angle from x. We get: $$\left(r\cdot \cos(\theta\right),r\cdot \sin\left(\theta\right))$$ In the abstract the terms are simply names for calculating the (x,y) coordinates for a particular curve. The identity mentioned is a reflection of the symmetry of that particular curve. If I had defined a hyperbola I would still have equations for (x,y) but they wouldn't have that particular symmetry; and the question wouldn't have been asked since the OP would see that two different functions would be expected with different relationships. All of the other properties of sin(),cos() are inherited from the underlying symmetry. The alternate explanation comes from dropping the "r" dependence. Although this seems it would be more abstract but historically it was first :) In ancient time people still had property boundaries and wanted to measure and design things remotely; say by drawing for communication. In order to layout property or build a temple some way of scaling had to be invented. Our ancestors found out the ratios of certain triangles were constant and therefore models or drawings could be scaled down; this can also be considered a symmetry. On areas of the earth that are relatively flat we have the ratios $$ \left(\cos(\theta\right),\sin\left(\theta\right))$$ (They were as smart as we think we are) Since they didn't know any of the properties to start with they simply called the ratios different names. We discovered a multitude of properties later; over 1000's of years. I hope the readers will forgive the emphasis on symmetries but I am studying Lie Groups/Algebras and they seem to be advanced versions and descriptions of symmetries like the above. $\endgroup$ 2 • $\begingroup$ Up-voted for the key point: "Since they didn't know any of the properties to start with they simply called the ratios different names. We discovered a multitude of properties later; over 1000's of years." $\endgroup$ – RayInNoIL Sep 3, 2015 at 11:37 • $\begingroup$ @RayatERISCorp Thanks, I really didn't expect any points for this but I thought the question showed a lack of mathematical "maturity". In this case I thought an elementary explanation in a historical context was appropriate. Hopefully this provides motivation and knowledge to encourage younger people; rather than making someone feel dumb about not having a deep background. $\endgroup$ – rrogers Sep 3, 2015 at 17:59 1 $\begingroup$ Having both $sin(x)$ and $cos(x)$ allows you to uniquely identify a point on the unit circle. $sin(x)$ is insufficient since you would also have to know $x$ to deduce $sin(\frac{\pi}{2} + x)$, which in turn renders $sin(x)$ useless since $x$ already uniquely identifies said point. $\endgroup$ 0 $\begingroup$ Just as every individual has a name , different from others ; so should every function have a name different from others . This enables us to remember different functions in short, without having to write the detailed mathematical expressions , representting these functions. $\endgroup$ 2 • $\begingroup$ If every function had a name, then these names would need to be so long to be unique that it would be easier to “inline” the defining expression. (Or, really, it would just be impossible, because there are clearly uncountable-infinitely many functions.) Alternatively, if the names weren't unique, it would be extremely confusing (actually, that's a problem in particular physics has already). $\endgroup$ Sep 3, 2015 at 17:23 • $\begingroup$ @leftaroundabot It is_particle_ physics... $\endgroup$ – Sasha Sep 4, 2015 at 13:30 0 $\begingroup$ It is similar to saying that why do spoon and fork exist even thought both of them do somewhat similar jobs.... Again yes there is a way to write cosine in terms of sine but if we write everything in sine the question which you will get will not look friendly. The more simple something is more is the motivation for you to do it. Mathematics is all about making complicated things simpler not simpler things complicated $\endgroup$ 0 $\begingroup$ In a right triangle, the three basic trig functions sine, secant, and tangent are related to their co-functions cosine, cosecant, and cotangent by having the same relation to the sides of the triangle, but from the point of view of the complementary angle. For example, in a triangle with angles 30, 60, and 90, the sine of 30 is the cosine of 60. In this sense, the cosine and sine are complements; really one thing and its complement, not two separate things. $\endgroup$ 0 $\begingroup$ I think that cos is just the shortcut for cosine, so it is somehow derived. You have vectors and covectors and all kinds of other duaities in math. Unlike the others here, I don't really think we need two different names -- and indeed, we don't have them. $\endgroup$ You must log in to answer this question. Not the answer you're looking for? Browse other questions tagged .
__label__pos
0.937763
hwlocality_diff man page hwlocality_diff — Topology differences Data Structures union hwloc_topology_diff_obj_attr_u struct hwloc_topology_diff_obj_attr_u::hwloc_topology_diff_obj_attr_uint64_s struct hwloc_topology_diff_obj_attr_u::hwloc_topology_diff_obj_attr_string_s struct hwloc_topology_diff_obj_attr_u::hwloc_topology_diff_obj_attr_generic_s union hwloc_topology_diff_u struct hwloc_topology_diff_u::hwloc_topology_diff_too_complex_s struct hwloc_topology_diff_u::hwloc_topology_diff_obj_attr_s struct hwloc_topology_diff_u::hwloc_topology_diff_generic_s Typedefs typedef enum hwloc_topology_diff_obj_attr_type_e hwloc_topology_diff_obj_attr_type_t typedef enum hwloc_topology_diff_type_e hwloc_topology_diff_type_t typedef union hwloc_topology_diff_u * hwloc_topology_diff_t Enumerations enum hwloc_topology_diff_obj_attr_type_e { HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_SIZE, HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_NAME, HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_INFO } enum hwloc_topology_diff_type_e { HWLOC_TOPOLOGY_DIFF_OBJ_ATTR, HWLOC_TOPOLOGY_DIFF_TOO_COMPLEX } enum hwloc_topology_diff_apply_flags_e { HWLOC_TOPOLOGY_DIFF_APPLY_REVERSE } Functions int hwloc_topology_diff_build (hwloc_topology_t topology, hwloc_topology_t newtopology, unsigned long flags, hwloc_topology_diff_t *diff) int hwloc_topology_diff_apply (hwloc_topology_t topology, hwloc_topology_diff_t diff, unsigned long flags) int hwloc_topology_diff_destroy (hwloc_topology_t topology, hwloc_topology_diff_t diff) int hwloc_topology_diff_load_xml (hwloc_topology_t topology, const char *xmlpath, hwloc_topology_diff_t *diff, char **refname) int hwloc_topology_diff_export_xml (hwloc_topology_t topology, hwloc_topology_diff_t diff, const char *refname, const char *xmlpath) int hwloc_topology_diff_load_xmlbuffer (hwloc_topology_t topology, const char *xmlbuffer, int buflen, hwloc_topology_diff_t *diff, char **refname) int hwloc_topology_diff_export_xmlbuffer (hwloc_topology_t topology, hwloc_topology_diff_t diff, const char *refname, char **xmlbuffer, int *buflen) Detailed Description Applications that manipulate many similar topologies, for instance one for each node of a homogeneous cluster, may want to compress topologies to reduce the memory footprint. This file offers a way to manipulate the difference between topologies and export/import it to/from XML. Compression may therefore be achieved by storing one topology entirely while the others are only described by their differences with the former. The actual topology can be reconstructed when actually needed by applying the precomputed difference to the reference topology. This interface targets very similar nodes. Only very simple differences between topologies are actually supported, for instance a change in the memory size, the name of the object, or some info attribute. More complex differences such as adding or removing objects cannot be represented in the difference structures and therefore return errors. It means that there is no need to apply the difference when looking at the tree organization (how many levels, how many objects per level, what kind of objects, CPU and node sets, etc) and when binding to objects. However the difference must be applied when looking at object attributes such as the name, the memory size or info attributes. Typedef Documentation typedef enum hwloc_topology_diff_obj_attr_type_e hwloc_topology_diff_obj_attr_type_t Type of one object attribute difference. typedef union hwloc_topology_diff_u * hwloc_topology_diff_t One element of a difference list between two topologies. typedef enum hwloc_topology_diff_type_e hwloc_topology_diff_type_t Type of one element of a difference list. Enumeration Type Documentation enum hwloc_topology_diff_apply_flags_e Flags to be given to hwloc_topology_diff_apply(). Enumerator HWLOC_TOPOLOGY_DIFF_APPLY_REVERSE Apply topology diff in reverse direction. enum hwloc_topology_diff_obj_attr_type_e Type of one object attribute difference. Enumerator HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_SIZE The object local memory is modified. The union is a hwloc_topology_diff_obj_attr_uint64_s (and the index field is ignored). HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_NAME The object name is modified. The union is a hwloc_topology_diff_obj_attr_string_s (and the name field is ignored). HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_INFO the value of an info attribute is modified. The union is a hwloc_topology_diff_obj_attr_string_s. enum hwloc_topology_diff_type_e Type of one element of a difference list. Enumerator HWLOC_TOPOLOGY_DIFF_OBJ_ATTR HWLOC_TOPOLOGY_DIFF_TOO_COMPLEX Function Documentation int hwloc_topology_diff_apply (hwloc_topology_t topology, hwloc_topology_diff_t diff, unsigned long flags) Apply a topology diff to an existing topology. flags is an OR'ed set of hwloc_topology_diff_apply_flags_e. The new topology is modified in place. hwloc_topology_dup() may be used to duplicate it before patching. If the difference cannot be applied entirely, all previous applied elements are unapplied before returning. Returns: 0 on success. -N if applying the difference failed while trying to apply the N-th part of the difference. For instance -1 is returned if the very first difference element could not be applied. int hwloc_topology_diff_build (hwloc_topology_t topology, hwloc_topology_t newtopology, unsigned long flags, hwloc_topology_diff_t * diff) Compute the difference between 2 topologies. The difference is stored as a list of hwloc_topology_diff_t entries starting at diff. It is computed by doing a depth-first traversal of both topology trees simultaneously. If the difference between 2 objects is too complex to be represented (for instance if some objects have different types, or different numbers of children), a special diff entry of type HWLOC_TOPOLOGY_DIFF_TOO_COMPLEX is queued. The computation of the diff does not continue below these objects. So each such diff entry means that the difference between two subtrees could not be computed. Returns: 0 if the difference can be represented properly. 0 with diff pointing to NULL if there is no difference between the topologies. 1 if the difference is too complex (see above). Some entries in the list will be of type HWLOC_TOPOLOGY_DIFF_TOO_COMPLEX. -1 on any other error. Note: flags is currently not used. It should be 0. The output diff has to be freed with hwloc_topology_diff_destroy(). The output diff can only be exported to XML or passed to hwloc_topology_diff_apply() if 0 was returned, i.e. if no entry of type HWLOC_TOPOLOGY_DIFF_TOO_COMPLEX is listed. The output diff may be modified by removing some entries from the list. The removed entries should be freed by passing them to to hwloc_topology_diff_destroy() (possible as another list). int hwloc_topology_diff_destroy (hwloc_topology_t topology, hwloc_topology_diff_t diff) Destroy a list of topology differences. Note: The topology parameter must be a valid topology but it is not required that it is related to diff. int hwloc_topology_diff_export_xml (hwloc_topology_t topology, hwloc_topology_diff_t diff, const char * refname, const char * xmlpath) Export a list of topology differences to a XML file. If not NULL, refname defines an identifier string for the reference topology which was used as a base when computing this difference. This identifier is usually the name of the other XML file that contains the reference topology. This attribute is given back when reading the diff from XML. Note: The topology parameter must be a valid topology but it is not required that it is related to diff. int hwloc_topology_diff_export_xmlbuffer (hwloc_topology_t topology, hwloc_topology_diff_t diff, const char * refname, char ** xmlbuffer, int * buflen) Export a list of topology differences to a XML buffer. If not NULL, refname defines an identifier string for the reference topology which was used as a base when computing this difference. This identifier is usually the name of the other XML file that contains the reference topology. This attribute is given back when reading the diff from XML. Note: The XML buffer should later be freed with hwloc_free_xmlbuffer(). The topology parameter must be a valid topology but it is not required that it is related to diff. int hwloc_topology_diff_load_xml (hwloc_topology_t topology, const char * xmlpath, hwloc_topology_diff_t * diff, char ** refname) Load a list of topology differences from a XML file. If not NULL, refname will be filled with the identifier string of the reference topology for the difference file, if any was specified in the XML file. This identifier is usually the name of the other XML file that contains the reference topology. Note: The topology parameter must be a valid topology but it is not required that it is related to diff. the pointer returned in refname should later be freed by the caller. int hwloc_topology_diff_load_xmlbuffer (hwloc_topology_t topology, const char * xmlbuffer, int buflen, hwloc_topology_diff_t * diff, char ** refname) Load a list of topology differences from a XML buffer. If not NULL, refname will be filled with the identifier string of the reference topology for the difference file, if any was specified in the XML file. This identifier is usually the name of the other XML file that contains the reference topology. Note: The topology parameter must be a valid topology but it is not required that it is related to diff. the pointer returned in refname should later be freed by the caller. Author Generated automatically by Doxygen for Hardware Locality (hwloc) from the source code. Referenced By hwloc_topology_diff_apply(3), hwloc_topology_diff_apply_flags_e(3), HWLOC_TOPOLOGY_DIFF_APPLY_REVERSE(3), hwloc_topology_diff_build(3), hwloc_topology_diff_destroy(3), hwloc_topology_diff_export_xml(3), hwloc_topology_diff_export_xmlbuffer(3), hwloc_topology_diff_load_xml(3), hwloc_topology_diff_load_xmlbuffer(3), HWLOC_TOPOLOGY_DIFF_OBJ_ATTR(3), HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_INFO(3), HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_NAME(3), HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_SIZE(3), hwloc_topology_diff_obj_attr_type_e(3), HWLOC_TOPOLOGY_DIFF_TOO_COMPLEX(3) and hwloc_topology_diff_type_e(3) are aliases of hwlocality_diff(3). Thu Jun 18 2015 Version 1.11.0 Hardware Locality (hwloc)
__label__pos
0.955132
学术, 其他笔记 矩阵一些运算的时间复杂度 这里给出结论[1-4]: • 矩阵乘积:时间复杂度为O(n^3) • 矩阵求逆:时间复杂度为O(n^3) • 矩阵本征值:时间复杂度为O(n^3) Python代码验证: import numpy as np import matplotlib.pyplot as plt import time time_1 = np.array([]) time_2 = np.array([]) time_3 = np.array([]) n_all = np.arange(2,5000,200) # 测试的范围 start_all = time.process_time() for n in n_all: print(n) matrix_1 = np.zeros((n,n)) matrix_2 = np.zeros((n,n)) for i0 in range(n): for j0 in range(n): matrix_1[i0,j0] = np.random.uniform(-10, 10) for i0 in range(n): for j0 in range(n): matrix_2[i0,j0] = np.random.uniform(-10, 10) start = time.process_time() matrix_3 = np.dot(matrix_1, matrix_2) # 矩阵乘积 end = time.process_time() time_1 = np.append(time_1, [end-start], axis=0) start = time.process_time() matrix_4 = np.linalg.inv(matrix_1) # 矩阵求逆 end = time.process_time() time_2 = np.append(time_2, [end-start], axis=0) start = time.process_time() eigenvalue, eigenvector = np.linalg.eig(matrix_1) # 求矩阵本征值 end = time.process_time() time_3 = np.append(time_3, [end-start], axis=0) end_all = time.process_time() print('总共运行时间:', (end_all-start_all)/60, '分') plt.subplot(131) plt.xlabel('n^3/10^9') plt.ylabel('时间(秒)') plt.title('矩阵乘积') plt.plot((n_all/10**3)*(n_all/10**3)*(n_all/10**3), time_1, 'o-') plt.subplot(132) plt.xlabel('n^3/10^9') plt.title('矩阵求逆') plt.plot((n_all/10**3)*(n_all/10**3)*(n_all/10**3), time_2, 'o-') plt.subplot(133) plt.xlabel('n^3/10^9') plt.title('求矩阵本征值') plt.plot((n_all/10**3)*(n_all/10**3)*(n_all/10**3), time_3, 'o-') plt.rcParams['font.sans-serif'] = ['SimHei'] # 在画图中正常显示中文 plt.rcParams['axes.unicode_minus'] = False # 中文化后,加上这个使正常显示负号 plt.show() 计算结果为(运算总时长约40分钟): 可以看出:矩阵乘积、矩阵求逆、求矩阵本征值的运算时间均与n^3成正比。 参考资料: [1] https://topocondmat.org/w8_general/invariants.html [2] https://zhidao.baidu.com/question/576048393.html [3] http://muchong.com/html/201403/7080180.html [4] https://zhidao.baidu.com/question/450632688.html 5,007 次浏览 【说明:本站主要是个人的一些笔记和代码分享,内容可能会不定期修改。为了使全网显示的始终是最新版本,这里的文章未经同意请勿转载。引用请注明出处:https://www.guanjihuan.com 评论说明: (1)在保留浏览器缓存的前提下,目前支持72小时自主修改或删除个人评论。如果自己无法修改或删除评论,可再次评论或联系我。如有发现广告留言,请勿点击链接,博主会不定期删除。 (2)评论支持Latex公式。把latexpage作为标签放在任何位置,评论中的公式可正常编译,示例: $Latex formula$  [latexpage] 发表回复 您的电子邮箱地址不会被公开。 必填项已用*标注
__label__pos
0.957769
Tuesday July 22, 2014 Homework Help: Math Posted by Punkie on Wednesday, January 6, 2010 at 8:55pm. I am supposed to find five ordered pairs to make the equation true y = 20 + x/3 so far I have (0,20) and (6,22) is this right? I am unsure because my text example had x^2 + 3x = y (0,0) (1,4) (2,10) (3,18) (4,28) and they have a common theme (muliply by by 0 then 4, 5, 6, and 7) should mine be like this? Answer this Question First Name: School Subject: Answer: Related Questions Math - I am supposed to find five ordered pairs to make the equation true y = 20... math - give five ordered pairs that make each equation true: y=20+x/3 math - give five ordered pairs that make each equation true y=20+x/3 ALGEBRA - what are five ordered pairs that make this equation true Y = 20 + X/3... Equation - I do not understand this question?? Give five ordered pairs that make... Algebra - Find three ordered pairs (a,b) that satisfy the equation 3a - 5b = 9. ... Math - Give five ordered pairs that makes the equation true y = 20 + x3 Algebra - The ordered pairs represent values for x and y. (1,1) is x =1 and y=1... math - give five oredered pairs that make the equation true y=20+x/3 math axis of symmety - What is the equation of the axis of symmetry of the graph... Search Members
__label__pos
0.987992
Method GtkTextBufferinsert_range_interactive Declaration [src] gboolean gtk_text_buffer_insert_range_interactive ( GtkTextBuffer* buffer, GtkTextIter* iter, const GtkTextIter* start, const GtkTextIter* end, gboolean default_editable ) Description [src] Copies text, tags, and paintables between start and end and inserts the copy at iter. Same as gtk_text_buffer_insert_range(), but does nothing if the insertion point isn’t editable. The default_editable parameter indicates whether the text is editable at iter if no tags enclosing iter affect editability. Typically the result of gtk_text_view_get_editable() is appropriate here. Parameters iter Type: GtkTextIter A position in buffer. The data is owned by the caller of the function. start Type: GtkTextIter A position in a GtkTextBuffer The data is owned by the caller of the function. end Type: GtkTextIter Another position in the same buffer as start. The data is owned by the caller of the function. default_editable Type: gboolean Default editability of the buffer. Return value Type: gboolean Whether an insertion was possible at iter.
__label__pos
0.989142
Take the tour × Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required. Let $a_n$ be a sequence of real numbers such that $\exp(it\cdot a_n)$ converges to 1 for all real t. Show that $a_n$ converges to 0. One can show this by letting $X_n$ be degenerate random variables which take value $a_n$ with prob 1 and then using results about characteristic functions and convergence. But this seems like overkill and it doesn't provide any intuition for what's going on. It seems like there should be a simpler proof based on basic properties of continuous functions and convergent sequences. Any ideas ? share|improve this question   Here is my intuition. For any particular value of t this says that a_n gets closer and closer to some element of the Z-lattice spanned by 2pi/t. By taking sufficiently many Q-independent values of t we should be able to force a_n to get farther and farther away from the origin (or to converge to 0) in order to get closer to many different Z-lattices simultaneously But without any uniformity assumptions I am having trouble making this rigorous. –  Qiaochu Yuan Nov 6 '10 at 10:45   No pre-set countable set of $t$'s will do - for a finite number of $t_j$'s and any $1/n$ you can find $a_n$ such that $exp(i t_j a_n) < 1/n$, and then use a diagonal argument. Note that $a_n=n!$ works for all rationals. You could try to use $t$'s dependent on $a$'s.. –  Max Nov 6 '10 at 11:18 add comment 1 Answer up vote 5 down vote accepted Step 1 The sequence $(a_n)$ cannot be bounded, if it doesn't converge to 0. Suppose the contrary, then up to a subsequence $(a_{\sigma(n)})$ converges to some value $A$. Let $t = \pi/A$. Then $\exp i t a_\sigma(n) \to -1$ contradicting convergence assumption. (Another way to see this step is to note that if $(a_n)$ were bounded, then the sequence $(\exp i t a_n)$ is equicontinuous, and on any compact interval the convergence must be uniform.) Step 2 The sequence cannot be unbounded. Assume the contrary, then up to a subsequence we can choose $a_{\sigma(n+1)} > 3 a_{\sigma(n)}$. Without loss of generality we can assume the subsequence is positive. Let $t_n = 2\pi a_{\sigma(n)}^{-1}$. Define a sequence of closed intervals recursively. Let $I_1 = [t_1/4, 3t_1/4]$. By construction $\exists m_2 \in \mathbb{Z}$ such that $m_2t_2, (m_2+1)t_2 \in I_1$. Let $I_2 = [ (m_2 + 1/4) t_2, (m_2 + 3/4) t_2]$. At each step $I_n$ has length $t_n / 2$. Hence there exists $m_{n+1}$ such that $m_{n+1}t_{n+1}, (m_{n+1}+1)t_{n+1} \in I_n$. And so we construct $I_{n+1}$ analogously. In particular, we have $I_n \supset I_{n+1} \supset I_{n+2} \ldots$. Furthermore, by construction, $\Re e^{it a_{\sigma(n)}} \leq 0$ for $t \in I_n$. Then for $t\in \cap_1^\infty I_n$, we have that $\exp i t a_j$ is bounded away from 1 on a subsequence, and hence contradicts the assumption of convergence. share|improve this answer   +1 Nice elementary solution. –  Nuno Nov 6 '10 at 19:14   Thanks, Willie. I came up with a fairly similar solution myself. –  Cosmonut Nov 8 '10 at 3:18   The difficult part was proving that $a_n$ must be bounded. I noticed that was the tough part in your proof as well. –  Cosmonut Nov 8 '10 at 3:19 add comment Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service.
__label__pos
0.957872
Question Automobile insurance is much more expensive for teenage drivers than for older drivers. To justify this cost difference, insurance companies claim that the younger drivers are much more likely to be involved in costly accidents. To test this claim, a researcher obtains information about registered drivers from the department of motor vehicles (DMV) and selects a sample of n = 300 accident reports from the police department. The DMV reports the percentage of registered drivers in each age category as follows: 16% are younger than age 20; 28% are 20 to 29 years old; and 56% are age 30 or older. The number of accident reports for each age group is as follows: a. Do the data indicate that the distribution of accidents for the three age groups is significantly different from the distribution of drivers? Test with a = .05. b. Write a sentence demonstrating how the outcome of the hypothesis test would appear in a research report. Sales0 Views18 Comments0 • CreatedSeptember 22, 2015 • Files Included Post your question 5000
__label__pos
0.680261
Advertisement 1 / 31 Decomposition, 3NF, BCNF PowerPoint PPT Presentation • 795 Views • Uploaded on 18-06-2013 • Presentation posted in: General Decomposition, 3NF, BCNF. Souhad M. Daraghma. Decomposition of a Relation Schema. If a relation is not in a desired normal form, it can be decomposed into multiple relations that each are in that normal form. - PowerPoint PPT Presentation Download Presentation Decomposition, 3NF, BCNF An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - Presentation Transcript Decomposition 3nf bcnf Decomposition, 3NF, BCNF Souhad M. Daraghma Decomposition of a relation schema Decomposition of a Relation Schema • If a relation is not in a desired normal form, it can be decomposedinto multiple relations that each are in that normal form. • Suppose that relation R contains attributes A1 ... An. A decompositionof R consists of replacing R by two or more relations such that: • Each new relation scheme contains a subset of the attributes of R, and • Every attribute of R appears as an attribute of at least one of the new relations. Normalization using functional dependencies Normalization Using Functional Dependencies • When we decompose a relation schema R with a set of functional dependencies F into R1, R2,.., Rn we want • Lossless-join Decomposition (complete reproduction) • No Redundancy (BCNF or 3NF) • Dependency Preservation Lossless join decomposition Lossless-join Decomposition • All attributes of an original schema (R) must appear in the decomposition (R1, R2): R = R1  R2 • For all possible relations Ri on schema R R = R1 (R) R2 (R) • We Want to be able to reconstruct big (e.g. universal) relation by joining smaller ones (using natural joins) (i.e. R1 R2 = R) Example lossless join Example (Lossless-Join) join decompose Example lossy join Example (Lossy-Join) join decompose Testing for lossless join decomposition Testing for Lossless-Join Decomposition • Rule: A decomposition of R into (R1, R2) is lossless, iff: R1 ∩ R2  R1 or R1 ∩ R2  R2 • in F+. Exercise lossless join decomposition Exercise: Lossless-join Decomposition R = {A,B,C,D,E}. F = {ABC, CD E, B  D, EA }. Is the following decomposition a lossless join? • R1 = {A,B,C},R2 ={A,D,E} Since R1  R2 = A, and A is a key for R1, the decomposition is lossless join. • R1 = {A,B,C},R2 ={C,D,E} Since R1  R2 = C, and C is not a key for R1 or R2, the decomposition is not lossless join. Dependency preserving decomposition Dependency Preserving Decomposition • The decomposition of a relation scheme R with FDs F is a set of tables (fragments) Ri with FDs Fi • Fi is the subset of dependencies in F+ (the closure of F) that include only attributes in Ri. • The decomposition is dependency preserving iff (i Fi)+ = F+ • In other words: we want to minimize the cost of global integrity constraints based on FD’s ( i.e. avoid big joins in assertions) (F1 F2  …  Fn )+ = F + Exercise non dependency preserving decomposition Exercise: Non-Dependency Preserving Decomposition R = (A, B, C), F = {AB, BC, AC} Key: A Assume there is a dependency B C, where the LHS is not the key, meaning that there can be considerable redundancy in R. Solution: Break it in two tables R1(A,B), R2(A,C) Exercise non dependency preserving decomposition1 Exercise: Non-Dependency Preserving Decomposition The decomposition is lossless because the common attribute A is a key for R1 (and R2) The decomposition is not dependency preserving because: F1={AB}, F2={AC} and (F1F2)+  F+ But, we lost the FD {BC} • In practical terms, each FD is implemented as a constraint or assertion, which it is checked when there are updates. In the above example, in order to find violations, we have to join R1 and R2. Which can be very expensive. Exercise dependency preserving decomposition Exercise: Dependency Preserving Decomposition R = (A, B, C), F = {AB, BC, AC} Key: A Solution: Break it in two tables R1(A,B), R2(B,C) • The decomposition is lossless because the common attribute B is a key for R2 • The decomposition is dependency preserving because F1={AB}, F2={BC} and (F1F2)+=F+ • Violations can be found by inspecting the individual tables, without performing a join. • What about A  C ? If we can check A  B, and B  C, A  C is implied. Exercise 2 fd preserving decomposition Exercise 2 : FD-Preserving Decomposition R = {A,B,C,D,E}. F = {ABC, CD E, B  D, EA } R1 = {A,B,C}, R2 = {A,D,E} Is the above decomposition dependency-preserving? No. CD  E and B  D are lost. Decomposition 3nf bcnf 3NF Third Normal Form Decomposition Third normal form Third Normal Form 3NF: A schema R is in third normal form (3NF) if for all FD in F +, at least one of the following holds: (1) is trivial (i.e.,   ). (2) is a superkey for R. (3)Each attribute A in – is contained in a candidate key for R (prime). • The decomposition is both lossless-join and dependency-preserving Decomposition into 3nf Eliminate redundant FDs, resulting in a canonical cover Fc of F Create a relation Ri = XY for each FD X  Y in Fc If the key K of R does not occur in any relation Ri, create one more relation Ri=K Decomposition into 3NF • Decomposition • Given: relation R, set F of functional dependencies • Find: decomposition of R into a set of 3NF relation Ri • Algorithm: Decomposition 3nf bcnf BCNF BCNF Normal Form Decomposition Boyce codd normal form Boyce-Codd Normal Form • BCNF: A schema R is in BCNF with respect to a set F of functional dependencies, if for all functional dependencies in • F + of the form , where  R and  R,at least one of the following holds: (1) is trivial (i.e.,  ) (2)  is a superkey for R • In other words, the left part of any non-trivial dependency must be a superkey. • If we do not have redundancy in F, then for each ,  must be a candidate key. • The decomposition is lossless-join but may not be dependency-preserving Decomposing into bcnf schemas Decomposing into BCNF Schemas • For all dependencies A  B in F+, check if A is a superkey • By using attribute closure • If not, then • Choose a dependency in F+ that breaks the BCNF rules, say A  B • Create R1 = A B • Create R2 = A (R – B – A) • Note that: R1 ∩ R2 = A and A  AB (= R1), so this is lossless decomposition • Repeat for R1, and R2 • By defining F1+ to be all dependencies in F that contain only attributes in R1 • Similarly F2+ Bcnf example 1 B  C BCNF Example #1 R = (A, B, C) F = {A  B, B  C} Candidate keys = {A} BCNF? = No. B  C violates. R1 = (B, C) F1 = {B  C} Candidate keys = {B} BCNF? = true R2 = (A, B) F2 = {A  B} Candidate keys = {A} BCNF? = true Bcnf example 2 From A  B and BC  D by pseudo-transitivity AC  D A  B R = (A, B, C, D, E) F = {A  B, BC  D} Candidate keys = {ACE} BCNF = Violated by {A  B, BC  D} etc… BCNF Example #2 R1 = (A, B) F1 = {A  B} Candidate keys = {A} BCNF = true R2 = (A, C, D, E) F2 = {AC  D} Candidate keys = {ACE} BCNF = false (AC  D) Dependency preservation ??? We can check: A  B (R1), AC  D (R3), but we lost BC  D So this is not a dependency -preserving decomposition R3 = (A, C, D) F3 = {AC  D} Candidate keys = {AC} BCNF = true R4 = (A, C, E) F4 = {} [[ only trivial ]] Candidate keys = {ACE} BCNF = true Example 3 BC  D A  B R = (A, B, C, D, E) F = {A  B, BC  D} Candidate keys = {ACE} BCNF = Violated by {A  B, BC  D} etc… Example #3 R1 = (B, C, D) F1 = {BC  D} Candidate keys = {BC} BCNF = true R2 = (B, C, A, E) F2 = {A  B} Candidate keys = {ACE} BCNF = false (A  B) Dependency preservation ??? We can check: BC  D (R1), A  B (R3), Dependency-preserving decomposition R3 = (A, B) F3 = {A  B} Candidate keys = {A} BCNF = true R4 = (A, C, E) F4 = {} [[ only trivial ]] Candidate keys = {ACE} BCNF = true Example 4 E  HA A  BC R = (A, B, C, D, E, H) F = {A  BC, E  HA} Candidate keys = {DE} BCNF = Violated by {A  BC} etc… Example #4 R1 = (A, B, C) F1 = {A  BC} Candidate keys = {A} BCNF = true R2 = (A, D, E, H) F2 = {E  HA} Candidate keys = {DE} BCNF = false (E  HA) Dependency preservation ??? We can check: A  BC (R1), E  HA (R3), Dependency-preserving decomposition R3 = (E, H, A) F3 = {E  HA} Candidate keys = {E} BCNF = true R4 = (ED) F4 = {} [[ only trivial ]] Candidate keys = {DE} BCNF = true Decomposition 3nf bcnf More Examples Decomposition 3nf bcnf Exercise 3 R =(A, B, C, D). F = {CD, CA, BC}. Question 1: Identify all candidate keys for R. Question 2: Identify the best normal form that R satisfies. Question 3: Decompose R into a set of BCNF relations. Question 4: Decompose R into a set of 3NF relations. Decomposition 3nf bcnf Exercise 3 Solution R =(A, B, C, D). F = {CD, CA, BC}. Question 1: Identify all candidate keys for R. B+ = B (BB) = BC (BC) = BCD (CD) = ABCD (CA) so the candidate key is B. B is the ONLY candidate key, because nothing determines B: There is no rule that can produce B, except B B. Decomposition 3nf bcnf Exercise 3 Solution R =(A, B, C, D). F = {CD, CA, BC}. Question 2: Identify the best normal form that R satisfies. R is not 3NF, because: CD causes a violation, CD is non-trivial ({D} {C}). C is not a superkey. D is not part of any candidate key. CA causes a violation Similar to above BC causes no violation Since R is not 3NF, it is not BCNF either. Decomposition 3nf bcnf Exercise 3 Solution R =(A, B, C, D). F = {CD, CA, BC}. Question 3: Decompose R into a set of BCNF relations (1)CD and CA both cause violations of BCNF. Take CD: decompose R to R1= {A, B, C} , R2={C, D}. (2)Now check for violations in R1 andR2. (Actually, using F+) R1 still violates BCNF because of CA. Decompose R1 to R11 = {B, C} R12 = {C, A}. Final decomposition: R2 = {C, D}, R11 = {B, C}, R12 = {C, A}. No more violations: Done! Decomposition 3nf bcnf Exercise 3 Solution R =(A, B, C, D). F = {CD, CA, BC}. Question 4: Decompose R into a set of 3NF relations. The canonical cover is Fc = {CDA, BC}. For each functional dependency in Fc we create a table: R1 = {C, D, A}, R2 = {B, C}. The table R2 contains the candidate key for R– we done. Exercise 4 Exercise 4 R = (A, B, C, D) F = {ABC, ABD, CA, DB} • Is R in 3NF, why? If it is not, decompose it into 3NF • Is R in BCNF, why? If it is not, decompose it into BCNF Exercise 4 solution Exercise 4 Solution R = (A, B, C, D) F = {ABC, ABD, CA, DB} • Is R in 3NF, why? If it is not, decompose it into 3NF Yes. Find all the Candidate Keys: AB, BC, CD, AD Check all FDs in F for 3NF condition 2. Is R in BCNF, why? If it is not, decompose it into BCNF No. Because for CA, C is not a superkey. Similar for DB R1 = {C, D}, R2 = {A, C}, R3 = {B, D} • Login
__label__pos
0.98935
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.       112 lines 2.5 KiB #include "isdnlogin.h" extern global_t global; /******************************************************************* * *******************************************************************/ int pollset( fd, events, func) int fd; int events; int (*func)PROTO((int)); { int i; struct pollfd *pfp; pollag_t *pap; if (global.npollfds >= MAX_FD) return -1; for (i=0, pfp=global.pollfds, pap=global.pollags; i < global.npollfds; ++i, ++pfp, ++pap) { if (pfp->fd == fd && pfp->events == events) break; } if ( i < global.npollfds) { printf("poll already set !!\n"); return 0; } pfp = global.pollfds + global.npollfds; pap = global.pollags + global.npollfds; pfp->fd = fd; pfp->events = events; pfp->revents = 0; if (poll(pfp, 1, 0) == -1) return -1; pap->func = func; global.npollfds ++; return 0; } /******************************************************************* * *******************************************************************/ int pollloopt(t) long t; { struct pollfd *pfp; pollag_t *pap; int i; int fds; int donefds; while (global.npollfds > 0) { fds = poll(global.pollfds, global.npollfds, t); switch (fds) { case -1: if (errno == EINTR) continue; if (errno == EAGAIN) continue; return -1; case 0: return 0; default: pfp = global.pollfds; pap = global.pollags; donefds = 0; for (i=0; i < global.npollfds; ++i, ++pfp, ++pap) { if (pfp->revents) { (*pap->func)(pfp->fd); pfp->revents = 0; donefds++; } } return donefds; break; } } return 0; } /******************************************************************* * *******************************************************************/ int mypolldel(fd) int fd; { struct pollfd *pfp; pollag_t *pap; int i; for (i=0, pfp=global.pollfds, pap=global.pollags; i < global.npollfds; ++i, ++pfp, ++pap) { if (pfp->fd == fd) break; } if (i >= global.npollfds) { errno = ENOENT; return -1; } for (++i, ++pfp, ++pap; i < global.npollfds; ++i, ++pfp, ++pap) { pfp[-1] = pfp[0]; pap[-1] = pap[0]; } global.npollfds --; return 0; }
__label__pos
0.999223
Tools2023-04-27 Pull Request vs Merge Request: Differences and Similarities Explore the differences between Pull Requests and Merge Requests in software development. Learn how they streamline code changes for effective collaboration. Pull Request vs Merge Request In software development, Pull Requests and Merge Requests are commonly used mechanisms for managing changes to code repositories. While they serve a similar purpose, there are some key differences between the two. Let's explore the benefits, and key differences between Pull Requests and Merge Requests to optimize development workflows. What is a Pull Request? A Pull Request is a feature of Git, a version control system used by many software development teams. It is a request made by a developer to merge changes they have made in their local branch to the main branch of the repository. The main branch is usually referred to as the "master" branch, although this can vary depending on the specific workflow being used. Additionally, Pull Requests serve as a way to discuss the changes being made and provide feedback to the author. This helps to catch any bugs or issues before they become a part of the main codebase. When a developer creates a Pull Request, they typically provide a summary of the changes made, as well as any relevant information about why the changes were made. Other developers on the team can then review the changes, ask questions, and provide feedback using the comments feature of the Pull Request. Once everyone is satisfied with the changes, the Pull Request can be merged into the main branch. [Read more: Pull request Best Practices] Let’s go over these examples: Assume that you are working on a feature branch called "new-feature" and you want to merge it into the main branch, which is called "master". Here are the steps you can follow to create a Pull Request. • Commit your changes to the feature branch. Commit your changes to the feature branch • Push your feature branch to the remote repository. Push your feature branch to the remote repository • Go to the repository website, such as GitHub or GitLab, and create a new Pull Request by selecting your feature branch and the main branch to merge it into. • Add a title and description for the Pull Request, and submit it for review. • Other developers can review your changes and provide feedback in the comments section of the Pull Request. • Once the changes have been approved, you can merge the Pull Request into the main branch using the following command: Merge the Pull Request into the main branch What is a Merge Request? Merge Requests are similar to Pull Requests in that they allow developers to propose changes to the main branch of a repository. However, Merge Requests are a feature of the GitLab platform, which is an alternative to GitHub. Like Pull Requests, Merge Requests allow developers to submit changes for review and feedback before they are merged into the main branch. One key difference between Merge Requests and Pull Requests is the level of automation available. Merge Requests can be configured to require certain conditions to be met before they can be merged, such as passing automated tests or receiving a certain number of approvals from other developers. This helps to ensure that changes being made to the codebase are of high quality and will not introduce bugs or other issues. Another difference between Merge Requests and Pull Requests is the terminology used. In GitLab, the main branch of a repository is typically referred to as the "default branch," whereas in Git it is commonly referred to as the "master" branch. Additionally, Merge Requests in GitLab are often used in conjunction with other features of the platform, such as Continuous Integration/Continuous Deployment (CI/CD) pipelines. Assuming that you want to create a Merge Request for your changes. [Read more: How to Master Merge Requests?] Here are the steps you can follow: • Create a new branch from the default branch: Creating a new branch from default branch • Commit your changes to the new branch. Git commit • Push your changes to the remote repository. Git push • Go to the GitLab website and create a new Merge Request by selecting your new branch and the default branch to merge it into. • Configure any necessary options for the Merge Request, such as requiring approvals or passing automated tests. • Once the changes have been approved, you can merge the Merge Request into the default branch using the GitLab website or the following command: Merge the Merge Request into the default branch Pull Requests And Merge Requests: Key Similarities and Differences 1. Essential Purpose: Both Pull Requests and Merge Requests serve the purpose of proposing and reviewing code changes before they are integrated into the main codebase. 2. Terminology: The primary difference lies in the terminology used by different version control systems. Git and GitHub primarily use "Pull Request," while GitLab and Bitbucket use "Merge Request." 3. Workflow: The workflow and steps involved in both processes are largely similar. Contributors fork or clone the repository, create a branch, make changes, and then submit the request for review. 4. Review and Discussion: Both mechanisms facilitate code review and discussions among team members, ensuring code quality and collaboration. 5. Merging: The final step in both processes involves merging the proposed changes into the target branch once they are approved. [ Read Related: Use Bitbucket Pipeline Pull Request Trigger ] 12 Key Benefits of Pull Requests and Merge Requests The benefits of both Pull Requests and Merge Requests are numerous and contribute to efficient and collaborative software development processes: 1. Code Quality: Pull Requests and Merge Requests encourage thorough code reviews, helping identify and rectify issues, and improving the overall quality and reliability of the codebase. 2. Collaboration: These mechanisms foster collaboration among team members, as they provide a platform for discussion, feedback, and knowledge sharing about the proposed code changes. 3. Knowledge Transfer: Pull Requests and Merge Requests facilitate the sharing of insights and techniques among developers, promoting learning and skill improvement within the team. 4. Error Detection: The review process helps catch bugs, logical errors, and unintended consequences early in the development cycle, reducing the likelihood of issues reaching the main codebase. 5. Version Control: By encapsulating changes within discrete branches and requests, these processes maintain a structured version history that aids in tracking changes and reverting if necessary. 6. Code Consistency: Reviewers can ensure that code adheres to established coding standards and style guidelines, maintaining a consistent codebase. 7. Conflict Resolution: During code reviews, conflicts can be identified and resolved before merging, preventing potential disruptions to the main codebase. 8. Risk Mitigation: The controlled nature of Pull Requests and Merge Requests reduces the risk of introducing unstable or incomplete code into the main branch. 9. Project Transparency: Developers and stakeholders can track the progress and status of code changes through the review and approval stages, promoting transparency in project management. 10. Parallel Development: Multiple developers can work on different features concurrently, as Pull Requests and Merge Requests allow for isolated development branches to be integrated independently. 11. Feedback Loop: Developers receive valuable feedback from peers, enhancing their understanding and encouraging continuous improvement. 12. Auditing and Compliance: For regulated industries, these processes can aid in compliance by ensuring code changes are reviewed and documented. Conclusion In summary, Pull Requests and Merge Requests are both useful tools for managing changes to code repositories. While they serve a similar purpose, there are some key differences between the two, such as the level of automation available and the terminology used. Ultimately, the choice between using Pull Requests or Merge Requests will depend on the specific needs of the development team and the platform being used. Subscribe to the Hatica blog today to read more about unblocking developers, and boosting productivity with engineering analytics.  FAQs What's the purpose of Pull Requests and Merge Requests? Both Pull Requests and Merge Requests serve as a means to propose code changes, engage in code review, discuss improvements, and ensure the quality of code before it gets merged into the main branch. How do Pull Requests and Merge Requests work? Developers create a branch, make code changes, and then submit a request for review. Team members review the proposed changes, provide feedback, and engage in discussions. Once approved, the changes are merged into the main branch. Can you merge code without a Pull Request or Merge Request? While it's possible to directly push code to a branch, using Pull Requests or Merge Requests is recommended because they promote collaboration, enable code review, and help maintain a clean and organized codebase. Subscribe to Hatica's blog Get bi-weekly insights straight to your inbox Share this article: Table of Contents • What is a Pull Request? • What is a Merge Request? • Pull Requests And Merge Requests: Key Similarities and Differences • 12 Key Benefits of Pull Requests and Merge Requests • Conclusion • FAQs • What's the purpose of Pull Requests and Merge Requests? • How do Pull Requests and Merge Requests work? • Can you merge code without a Pull Request or Merge Request? Ready to dive in? Start your free trial today Overview dashboard from Hatica
__label__pos
0.994655
Simple data binding in WPF: 1 – Binding controls to objects We’ll start having a look at data binding in WPF. Briefly, data binding is the ability to bind some property of a control (such as the text in a TextBox) to the value of a data field in an object. (More generally, you can bind controls to other data sources such as databases, but that’s more advanced.) The idea, and the need for it, are best illustrated with an example. Suppose we want a little program that allows you to step through the integers and test each one to see if it’s a prime number or a perfect number. In case you’ve forgotten, a prime number is one whose only factors are 1 and the number itself, so 2, 3, 5, 7, 11, 13, 17 and so on are the first few prime numbers. A perfect number is one where the sum of all its factors (including 1 but excluding the number itself) equals the number itself. The smallest perfect number is 6, since its factors are 1, 2 and 3, and 1+2+3=6. The next perfect number is 28, and after that they get quite large, and very rare. The interface for the program might look like this: The number being considered is shown at the top. The Factors box shows the number of factors (excluding 1 and the number itself) that number has; thus a number with zero factors is prime. The ‘Sum of factors’ box shows the sum of the number’s factors (including 1, but excluding the number). A number whose ‘Sum of factors’ equals the number itself is therefore perfect. The program should paint the background of the ‘Factors’ box LightSalmon if the number is prime, and the background of the ‘Sum of factors’ box LightSeaGreen if the number is perfect. The Reset button resets Number to 2. The Dec button decrements Number by 1; Inc increments Number by 1, and Exit quits the program. Note that the Dec button also becomes disabled when Number is 2, since we don’t want to consider any numbers less than 2. If the only programming technique you knew about was event handling, you can see that you would need to add handlers for each button’s Click event, and these handlers would need to update Number and the values displayed in the various TextBoxes. You would also need to handle the TextChanged event in the Number TextBox so if the user typed in a new number it would update the other boxes. Quite a bit of back-and-forth coding would be needed to keep everything synchronized. Data binding allows the value displayed by a TextBox, or in fact pretty well any property of any control, to be bound to a data value, so that changing the data value automatically updates the property, and changing the property can also update the data value. Let’s start with the simplest case: binding the value displayed by a TextBox to a data field in an object. To work on this project, we’ll use Expression Blend (EB) for the design and binding work, and Visual Studio (VS) for writing the classes we need to support the data binding. I’ve built the user interface using EB and won’t go into the details here; you can look here for an introduction to using EB to build interfaces. If you want the XAML code, you can download the project files; see the end of this post for the link. We’ll need a class for storing the details of the number being considered, and for calculating the factors of that number. We’ll call that class PrimePerfect, and create it in VS. It’s a pretty standard class, except for one thing: it must be able to notify the controls when any of the relevant data fields are changed so they can be updated. In data binding, the way this is done is by writing a class that implements the INotifyPropertyChanged interface. The beginning of PrimePerfect therefore looks like this: using System.ComponentModel; ...... class PrimePerfect : INotifyPropertyChanged // in System.ComponentModel { public event PropertyChangedEventHandler PropertyChanged; protected void Notify(string propName) { if (this.PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } ...... Note the using statement at the top; it is required for notification code. Implementing INotifyPropertyChanged requires that we declare an event handler for PropertyChanged, as we’ve done on line 5. The Notify() method on line 6 takes a string parameter which is used to identify which property has changed, and the event handler is then called, passing along this parameter. The rest of the class consists of standard code, defining the properties and calculating the factors of the number. A typical property looks like this: int numFactors; public int NumFactors { get { return numFactors; } set { numFactors = value; Notify("NumFactors"); } } The property contains the usual ‘get’ and ‘set’ clauses, but note that in the ‘set’, a call to Notify() is made, passing along a string identifying which property has been set. This property string is used to bind the text field of a TextBox to the value of NumFactors. To see how this is done, we return to EB (make sure you save and build the project at this point, so the updates to the PrimePerfect class are available to EB). We’ll add the binding between the factorsTextBox (that displays the current value of NumFactors) and the NumFactors data field in PrimePerfect. In EB, select factorsTextBox. In ‘Common Properties’ in the right panel, find the Text entry. Click on the little square to the right of the entry, and select ‘Data binding’ from the context menu. In the dialog box that appears, click “Data field” at the top, then “+CLR Object”. This brings up another dialog that shows the available data sources for the binding. Find the namespace containing the PrimePerfect class (in the project here, I’ve called it PrimePerfectBinding), and select the PrimePerfect class, then OK. You should now see PrimePerfectDataSource appear in the Data sources column. Click on it, and PrimePerfect should appear in the Fields list on the right. Open it and select NumFactors from the list (if you can’t see it, try setting ‘Show’ to ‘All properties’ in the combo box at the bottom). Click OK and the binding is complete. If you now look at the XAML code for factorsTextBox, you should see Text=”{Binding NumFactors}” as one of the attributes. If you’ve been following faithfully, you’ll probably have noticed that although we’ve defined the PrimePerfect class and added notification code to it, and also added a binding to factorsTextBox, we haven’t actually created an instance of PrimePerfect yet. To remedy this, go to the C# code-behind file for MainWindow, and add a couple of lines to it as follows. PrimePerfect primePerfect; public MainWindow() { InitializeComponent(); primePerfect = new PrimePerfect(); baseGrid.DataContext = primePerfect; } You’ll see we create an instance of PrimePerfect (its default constructor sets Number = 2). However, we’ve also added a cryptic line in which a DataContext is set to this object. What’s a DataContext? The data context is an object that serves as the source of the data in a binding. When a control, such as factorsTextBox, was assigned a binding, all we did was specify the name of the data field (“NumFactors”) to which it is bound. We didn’t give the TextBox any information about where it should look for this data. The WPF data binding mechanism takes care of this by having a control with a data binding look for a data context. It will look first in the control itself. If a data context isn’t found there, it will look in the parent container of that control, and so on until it reaches the root container (usually the Window). What we’ve done here is attach a DataContext to the Grid that contains all the controls in the interface (‘baseGrid’ is the name of that Grid object). This means that all controls in that Grid that have data bindings will look in the same PrimePerfect object for their data. This completes the data binding process for factorsTextBox. To get the program to run at this point, we need to complete the code in PrimePerfect so that it calculates NumFactors and SumFactors for the current Number. This code doesn’t have any bearing on the data binding so we won’t list it here, but if you want to see how it’s done, just download the source code and have a look at it. If you run the program at this point, you should see the Factors TextBox display the current value of NumFactors, which is 0 (since 2 is the starting Number, and it’s prime). The Number and Sum of factors TextBoxes won’t show anything unless you go through the same process and bind them to the corresponding properties in PrimePerfect. There’s nothing new involved in doing this, so you can either try it yourself or just look at the source code to see how it’s done. So far, we haven’t added any event handlers to the buttons, so let’s finish with that. We can add handlers for the buttons by double clicking on the Click event for each button in EB. This generates event handlers in MainWindow.xaml.cs, and we can enter some code in them as follows. private void incButton_Click(object sender, RoutedEventArgs e) { primePerfect.Number++; } private void decButton_Click(object sender, RoutedEventArgs e) { primePerfect.Number--; } private void exitButton_Click(object sender, RoutedEventArgs e) { Application.Current.Shutdown(); } private void resetButton_Click(object sender, RoutedEventArgs e) { primePerfect.Number = 2; } There’s nothing surprising here. The three buttons that change the value of Number do so with a single line each. Now if you run the program, you’ll see that clicking on each button does change the value of Number, and also updates Factors and Sum of factors. Why? Because whenever we change the value of Number, we are calling the ‘set’ method of the Number property in PrimePerfect, and this calls code that recalculates NumFactors and SumFactors. All of this fires a Notify event for each property, so any control that is bound to that property gets updated automatically. At this stage, we have a program that allows us to step through the numbers and display NumFactors and SumFactors for each number. However, we still haven’t added the colour-coding of the textboxes when we find a prime or perfect number, and the Dec button will allow us to set Number lower than 2, which may have disastrous consequences if the number goes negative. We can fix all these problems using data binding as well, but that’s a topic for the next post. Code for this post is here. Advertisements Post a comment or leave a trackback: Trackback URL. Trackbacks Leave a Reply Fill in your details below or click an icon to log in: WordPress.com Logo You are commenting using your WordPress.com account. Log Out /  Change ) Google photo You are commenting using your Google account. Log Out /  Change ) Twitter picture You are commenting using your Twitter account. Log Out /  Change ) Facebook photo You are commenting using your Facebook account. Log Out /  Change ) Connecting to %s %d bloggers like this:
__label__pos
0.855451
Book a Demo Prev Next Work With Methods This is an example of code for working with the Methods collection of an element and with Method collections.      Sub MethodLifeCycle           Dim element as object           Dim method as object           Dim t as object           Dim idx as Integer           Dim idx2 as integer           try                element = m_Repository.GetElementByID(129)                For idx = 0 to element.Methods.Count -1                     method = element.Methods.GetAt(idx)                     Console.WriteLine(method.Name)                     t = method.PreConditions.AddNew("TestConstraint","something")                     If t.Update = false Then                          Console.WriteLine("PreConditions: " + t.GetLastError)                     End if                     method.PreConditions.Refresh                     For idx2 = 0 to method.PreConditions.Count-1                          t = method.PreConditions.GetAt(idx2)                          Console.WriteLine("PreConditions: " + t.Name)                          If t.Name = "TestConstraint" Then                               method.PreConditions.DeleteAt(idx2,false)                          End If                     Next                     t = method.PostConditions.AddNew("TestConstraint","something")                     If t.Update = false Then                          Console.WriteLine("PostConditions: " + t.GetLastError)                     End if                     method.PostConditions.Refresh                     For idx2 = 0 to method.PostConditions.Count-1                          t = method.PostConditions.GetAt(idx2)                          Console.WriteLine("PostConditions: " + t.Name)                          If t.Name = "TestConstraint" Then                               method.PostConditions.DeleteAt(idx2, false)                          End If                     Next                     t = method.TaggedValues.AddNew("TestTaggedValue","something")                     If t.Update = false Then                          Console.WriteLine("Tagged Values: " + t.GetLastError)                     End if                     For idx2 = 0 to method.TaggedValues.Count-1                          t = method.TaggedValues.GetAt(idx2)                          Console.WriteLine("Tagged Value: " + t.Name)                          If(t.Name= "TestTaggedValue") Then                               method.TaggedValues.DeleteAt(idx2,false)                          End If                     Next                     t = method.Parameters.AddNew("TestParam","string")                     If t.Update = false Then                          Console.WriteLine("Parameters: " + t.GetLastError)                     End if                     method.Parameters.Refresh                     For idx2 = 0 to method.Parameters.Count-1                          t = method.Parameters.GetAt(idx2)                          Console.WriteLine("Parameter: " + t.Name)                          If(t.Name="TestParam") Then                               method.Parameters.DeleteAt(idx2, false)                          End If                     Next                     method = nothing                Next           catch e as exception                Console.WriteLine(element.Methods.GetLastError())                Console.WriteLine(e)           End try      End Sub
__label__pos
0.957145
 TSM - A JavaScript Logging Library for Productive Programmers EDITING BOARD RO EN × ▼ BROWSE ISSUES ▼ Issue 21 A JavaScript Logging Library for Productive Programmers Bogdan Cornianu Java developer @3Pillar Global PROGRAMMING The most widely used method of logging events for debugging in JavaScript is by calling "console.log(message)" which will show the message in the developer console. To log warnings or errors, developers can also use "console.warn(message)" or "console.error(message)". The "console" object is a host object which means that it is provided by the JavaScript runtime environment. Because it is a host object, there is no specification describing its behavior, and as a result of that, the browser implementations differ, or can even be missing like in Internet Explorer 7. If most browsers already implement a logging functionality out of the box, why should there be a library for the same purpose? In order to extend the functionality offered by the built-in logging mechanism with features such as searching, filtering and formatting of messages. I"m working on a web based project with the server side written in Java and the client side written in JavaScript. The client for whom we develop this web application couldn"t provide us with the server logs in a timely manner. In order to solve the incoming defects as fast as possible, we implemented on the server side a mechanism which, in the case of an exception, would collect information about all the tables involved, which, along with the Java stack trace, were archived and sent to the browser so they could be downloaded on the fly by the client. He would then send this archive back to us, so that we could investigate and fix the issue. On the front-end side, when the client submitted an issue which we couldn"t reproduce, we had to remote connect to their desktops, install Firebug and start watching its console. In order to improve this process and make issue reporting easier, we thought of replicating on the client side, the mechanism we implemented on the server side. This was the birth of "Logger", a JavaScript logging library. What makes it stand apart from the rest of the logging libraries is its ability to save the events (logs) on the developer console, on the browser"s local storage but also export them to a text file. A few words about the usage of the library. Including the library is very easy and it requires only one line of code: "" There are two ways of logging events: 1. Using Logger.log >Logger.log(Logger.level.Error, "error message", Logger.location.All); [ERROR]> error message Because we used "All" as location, the message will also be saved in the local storage. >localStorage; Storage {1393948583410_ERROR: "error message", length: 1} 2.Using specific methods for each event: Logger.error(message, location), Logger.warn(message, location), Logger.info(message, location) >Logger.error("second error message", Logger.location.All); [ERROR]> second error message Logger.warn("a warning message", Logger.location.All); [WARN]> a warning message Logger.info("an information message", Logger.location.All); [INFO]> an information message Each event is saved in the browser"s local storage as a key-value pair. The key is made up of the "timestamp_level", and the value contains the event message: >Logger.getEvents(Logger.level.All); [ERROR]> error message [ERROR]> second error message [WARN]> a warning message [INFO]> an information message To list all of the events ,we can use "Logger.getEvents(level)": I will continue with presenting the functionality which, in my opinion, will make programmers more productive: exporting all events to a text file. By exporting to a text file, programmers can have faster access to the events which occurred during the application›s run time. Exporting the events can be done by calling "Logger.exportLog()" or by setting a callback function in the event of an error occurring in the application: "Logger.onError(exportLog, suppressErrorAlerts, errorCallback)" If "exportLog" is set on true then the error which occurred and also all of the events present in the local storage will be exported to a text file. If "suppressErrorAlerts" is set on true then the error will not be written also to the browser"s console. "errorCallback" is the callback function which will get called when the error occurs. The following code sequence will display a dialog message in the event of a JavaScript error. Logger.onError(true, true, function(errorMsg, url, lineNumber) { var errorMessage = errorMsg + " la linia " + lineNumber + " in " + url, response = ""; Logger.error(errorMessage, Logger.location.LocalStorage); raspuns = confirm("An error occurred. Would you like to export the log events to a text file?"); if (raspuns === true) { Logger.exportLog(); } return true;//suppress errors on console }); We can test if this code works by throwing an error when clicking a button: "" When clicking the button we will get the following messages: Pressing the "OK" button will show the browser"s save dialog or save the file directly, depending on the browser settings. The filename is made up of the current date and time. If we open up the file we will see the logged events and also the JavaScript error. [ERROR]> error message [ERROR]> second error message [WARN]> a warning message [INFO]> an information message [ERROR]> Uncaught Error: eroare. la linia 19 in http://localhost:8080/logger/main.html We can see the error occurred in file "main.html" at line 19, which is where we created the button whose click event throws a JavaScript error: The library uses the "Revealing module" pattern to expose the functions which can be called by the developers. The easiest way to write data from the local storage to a file would have been to use a third party JavaScript library called "FileSaver.js" which uses the FileSystem API or when this is unavailable it provides an alternative implementation. To avoid using any third party libraries, I found a solution using a Blob object: saveToDisk: function(content, filename) { var a = document.createElement("a"), blob = new Blob([content], {"type" : " application/octet-stream"}); a.href = window.URL.createObjectURL(blob); a.download = filename; a.click(); } I created an anchor element and attached to its href attribute, a URL object created from a blob. A Blob is an immutable object which contains raw data. The name of the file comprised from the current date and time is associated to the download attribute. The click() function is then called on the anchor element which will show the browser"s save dialog or save the file directly to disk according to the browser settings. In order to intercept the JavaScript errors, I created a variable called initialWindowErrorHandler which contains a reference to window.onerror event handler. Initially, window.onerror will write all error messages to the console. If the errorCallback parameter is not undefined in the onError() function, then the function which the errorCallback parameter points to, will get called on each JavaScript error. saveToDisk: function(content, filename) { var a = document.createElement("a"), blob = new Blob([content], {"type" : "application/octet-stream"}); a.href = window.URL.createObjectURL(blob); a.download = filename; a.click(); } At any moment we can revert to the original window.onerror behavior by calling Logger.resetWindowErrorHandler(). This is the initial version of the Logger library, without any advanced features. In the future, it could be improved by adding the possibility to set a maximum number of recorded events, the ability to delete events by their event type, filtering the exported events by type, creating a graphical interface to browse through the existing records and generate statistics to determine the stability of the application in a given time frame and also the ability to customize the generated filename according to the programmer"s needs. References: Mozilla Developer Network 1. Create Object URL: https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL 2. Blob: https://developer.mozilla.org/en-US/docs/Web/API/Blob 3. File System API: https://developer.mozilla.org/en-US/docs/WebGuide/API/ 4. Window.onerror: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onerror Github 5. FileSaver.js: https://github.com/eligrey/FileSaver.js JSFiddle 6. Save to disk example: http://jsfiddle.net/koldev/cW7W5/ 7. Revealing Module Pattern: carldanley.com/js-revealing-module-pattern/ Sponsors • comply advantage • ntt data • 3PillarGlobal • Betfair • Telenav • Accenture • Siemens • Bosch • FlowTraders • MHP • Connatix • UIPatj • MetroSystems • Globant • Colors in projects
__label__pos
0.931783
Which units are units of volume? Published by Charlie Davidson on Which units are units of volume? Volume is the measure of the 3-dimensional space occupied by matter, or enclosed by a surface, measured in cubic units. The SI unit of volume is the cubic meter (m3), which is a derived unit. Liter (L) is a special name for the cubic decimeter (dm3). What is the units of area? Are, unit of area in the metric system, equal to 100 square metres and the equivalent of 0.0247 acre. Its multiple, the hectare (equal to 100 ares), is the principal unit of land measurement for most of the world. The are was the basic unit of area when the metric system was first decreed in France in 1795. How do you convert between units of area and units of volume? A length is measured in units , area is measured in square units (unit×unit=unit2) , and volume is measured in cubic units (unit×unit×unit=unit3) . What are the units of volume in the metric system? In the metric system of measurement, the most common units of volume are milliliters and liters. How do you calculate volume units? Units of Measure 1. Volume = length x width x height. 2. You only need to know one side to figure out the volume of a cube. 3. The units of measure for volume are cubic units. 4. Volume is in three-dimensions. 5. You can multiply the sides in any order. 6. Which side you call length, width, or height doesn’t matter. How do you find area example? For example, in a rectangle we find the area by multiplying the length times the width. In the rectangle above, the area is 2×4 or 8. If you count the small squares you will find there are 8 of them. Why are there no base units for area and volume? Question: There Is No SI Base Unit For Area Because: Area Is Not An Important Physical Quantity Area Can Be Expressed In Terms Of Square Meters An Area Has No Thickness; Hence No Physical Standard Can Be Built It Is Impossible To Express Square Feet In Terms Of Meters We Live In A Three (not A Two) Dimensional World … What are the 3 common units of volume? Three common units of volume are: • cubic centimeters. • liters. • gallons. What are the 7 units of measurement? The SI system, also called the metric system, is used around the world. There are seven basic units in the SI system: the meter (m), the kilogram (kg), the second (s), the kelvin (K), the ampere (A), the mole (mol), and the candela (cd). How is volume converted to area in GCSE? Converting volume is done in exactly the same way as converting area. The only major difference you need to remember is that volume is a 3 dimensional measurement, so we use cube units cm 3 . To calculate the area of 1m 3 in cm 3 the equations is therefore 100cm x 100cm x 100cm = 1,000,000cm 3 . How are units of area and volume measured? Area is measured in square kilometres (km2), square metres (m2), square centimetres (cm2) and square millimetres (mm2). Volume measures the space inside a 3-dimensional (3D) object. The standard units of volume are cubic metres (m3), cubic centimetres (cm3) and cubic millimetres (mm3). How is the volume of a 2D shape measured? The area of a 2D shape is the amount of space inside it. Area is measured in square kilometres (km2), square metres (m2), square centimetres (cm2) and square millimetres (mm2). Volume measures the space inside a 3-dimensional (3D) object. When do you convert area to a unit of length? When converting measurements of area remember that area is a 2 dimensional measurement so is always calculated in square units e.g. cm 2. You are therefore not calculating a unit of length e.g. cm. Categories: Helpful tips
__label__pos
1
How to store cryptocurrencies safely? Cryptocurrencies have taken the world by storm, offering a new way to invest and trade online. As more and more people delve into the world of digital currencies such as Bitcoin, it becomes crucial to understand how to store them safely. Ensuring the security of your cryptocurrency holdings is paramount to protect your investments from potential cyber threats. One of the best ways to store cryptocurrencies safely is by using a hardware wallet. These physical devices store your private keys offline, making it virtually impossible for hackers to access your funds. Popular hardware wallets include Ledger Nano S and Trezor. Another option is a paper wallet, which involves printing your private keys and storing them securely offline. When it comes to storing cryptocurrencies on an exchange, it is essential to choose a reputable platform with advanced security measures in place. Research the exchange thoroughly before trusting them with your funds. Consider using multi-factor authentication to add an extra layer of security to your account. Additionally, consider diversifying your storage options by using multiple wallets and exchanges. This reduces the risk of losing all your funds if one platform is compromised. Regularly backup your wallet and update your security settings to stay ahead of potential threats. In conclusion, storing cryptocurrencies safely involves a combination of using secure hardware wallets, reputable exchanges, and practicing good security habits. By taking the necessary precautions, you can protect your investments and trade with peace of mind in the volatile world of digital currencies. Remember to always stay vigilant and educate yourself on the latest security best practices to safeguard your assets.
__label__pos
0.84217
Digital Media & Creative Techdigital-media-and-creative-techDigital Photographydigital-photography How To Get Video From A Camcorder When The Screen Is Broken how-to-get-video-from-a-camcorder-when-the-screen-is-broken Introduction When faced with a broken camcorder screen, retrieving your precious videos may seem like an insurmountable challenge. However, there are several methods you can employ to access the footage stored on your camcorder, even with a non-functional screen. Whether you opt to use a TV or external monitor, a computer, or a video capture device, each approach offers a viable solution to recover your videos. By following the steps outlined in this guide, you can successfully retrieve your video files and continue enjoying your captured memories. In the following sections, we will explore each method in detail, providing step-by-step instructions to help you navigate the process with ease. Regardless of your technical expertise, these methods are designed to be accessible and user-friendly, ensuring that you can retrieve your videos without the need for advanced technical knowledge or specialized equipment. Let's delve into these solutions and empower you to overcome the obstacle presented by a broken camcorder screen. By leveraging the available technology and adopting a resourceful mindset, you can effectively extract the videos from your camcorder and preserve your cherished moments. Whether you choose to connect your camcorder to a TV or external monitor, transfer the videos to a computer, or utilize a video capture device, the options available to you are versatile and adaptable to your specific circumstances. With a proactive approach and the guidance provided in this article, you can successfully retrieve your videos and continue reliving the memories captured by your camcorder.   Using a TV or External Monitor If your camcorder has a broken screen, using a TV or an external monitor is an effective method to access and view your videos. Most camcorders are equipped with an AV-out port, which allows you to connect the camcorder to a TV or monitor using the appropriate cables. Here’s how you can retrieve your videos using this method: 1. Locate the AV-out port: Examine your camcorder for the AV-out port, typically a 3.5mm or 2.5mm jack, and identify the corresponding cable required for connection to a TV or monitor. 2. Connect the camcorder to the TV or monitor: Using the compatible AV cable, connect the camcorder to the TV or external monitor. Ensure that both devices are powered on and set to the appropriate input source. 3. Access the video playback: Once connected, navigate the camcorder’s menu or controls to initiate video playback. The videos should be displayed on the TV or monitor, allowing you to view and select the desired files for playback or transfer. By following these simple steps, you can effectively bypass the broken screen on your camcorder and access your videos using a TV or external monitor. This method provides a straightforward and practical solution, enabling you to continue enjoying your captured moments without the hindrance of a malfunctioning camcorder screen. Using a TV or external monitor not only facilitates video playback but also allows you to transfer the videos to another storage device, such as a computer or external hard drive, for safekeeping. This approach offers versatility and convenience, making it a valuable option for retrieving videos from a camcorder with a broken screen.   Using a Computer When faced with a broken camcorder screen, leveraging a computer provides an alternative method to retrieve your videos. By connecting your camcorder to a computer, you can access and transfer the video files, allowing you to preserve and enjoy your captured memories. Here’s how you can accomplish this: 1. Identify the connection port: Locate the appropriate port on your camcorder for connecting to a computer. This may be a USB port or another type of interface, depending on the model of your camcorder. 2. Connect the camcorder to the computer: Use the compatible cable to connect your camcorder to the USB port on your computer. Ensure that both devices are powered on and ready for the connection. 3. Access the camcorder storage: Upon successful connection, your computer should recognize the camcorder as an external storage device. Navigate to the file explorer or media management software on your computer to access the camcorder’s storage and locate the video files. 4. Transfer the videos: Once you have accessed the video files, you can proceed to transfer them to your computer’s hard drive or another storage location. This ensures that your videos are safely preserved and accessible for future viewing. Using a computer to retrieve videos from a camcorder with a broken screen offers a convenient and efficient solution. This method not only allows you to access the videos but also provides the opportunity to organize and store them securely on your computer, ensuring that your cherished memories remain intact. By following these straightforward steps, you can successfully bypass the obstacle posed by a broken camcorder screen and gain access to your video files using a computer. This method is adaptable to various camcorder models and is designed to simplify the process of video retrieval, empowering you to continue enjoying your captured moments.   Using a Video Capture Device When confronted with a broken camcorder screen, employing a video capture device offers an effective method to retrieve your videos and bypass the screen-related hindrance. A video capture device serves as an intermediary tool, enabling you to transfer the video feed from your camcorder to a computer or storage device without relying on the camcorder’s screen. Here’s how you can utilize a video capture device to access your videos: 1. Acquire a video capture device: Obtain a video capture device that is compatible with your camcorder and computer. These devices are available in various models and connectivity options, allowing you to select one that suits your specific requirements. 2. Connect the camcorder to the video capture device: Using the appropriate cables and connectors, establish a connection between your camcorder and the video capture device. Ensure that the connections are secure and the devices are powered on. 3. Connect the video capture device to the computer: Once the camcorder is linked to the video capture device, connect the capture device to your computer using the provided interface or cable. This establishes a pathway for transferring the video feed to your computer for viewing and storage. 4. Initiate video capture and transfer: Utilize the software or application associated with the video capture device to initiate the video feed transfer from your camcorder to the computer. Follow the provided instructions to ensure a seamless transfer process. Utilizing a video capture device offers a practical and versatile solution for retrieving videos from a camcorder with a broken screen. This method circumvents the screen-related impediment and empowers you to access and preserve your videos with ease. By following these steps and leveraging a video capture device, you can effectively overcome the challenge posed by a broken camcorder screen and continue enjoying your captured memories. This method provides a seamless and reliable approach to video retrieval, ensuring that your cherished moments remain accessible and intact. Leave a Reply Your email address will not be published. Required fields are marked *
__label__pos
0.943184
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. When viewing a web site on a mobile device (iPad, Galaxy Tab) there's always a lag when I click an element (regular link or anything else that is made clickable using javascript/jquery). While reading online, I found out that the browser is using touchstart followed by touchend events, and afterwards it triggers the regular click event. Is there a way to have a more responsive tap and remove the click event that is delayed? Maybe by using javascript, or something else? share|improve this question 3 Answers 3 up vote 2 down vote accepted if you are writing a web page your self you can register a listener for touchstart and touchend and trigger the onclick code directly from on touch end without any delay. If you don`t handle the event in touch move the browser will dispatch (with some lag) a click event to the element Take a look at this description from google to create "fast buttons": http://code.google.com/intl/de-DE/mobile/articles/fast_buttons.html share|improve this answer      It would be appreciated if you could post some code on how you would do that. I usually use jQuery when building websites and I know I can use .trigger() to trigger the click event. But I have no idea how I can automatically call "click" on each "tap" without adding it manually everytime I need it... –  Gabriel Jan 30 '12 at 22:10 1   i have updated the answer with an appropriate link –  Daniel Kurka Jan 30 '12 at 22:14 I use detection if the device support touch like modernizer. i fill a var called touchClick with the options 'click' or 'touchend' bases on the outcome if it is a touch device or not. In jquery I simply call: $('element').on(touchClick, function(e){ //do something }); It has a very small footprint. share|improve this answer      This approach is dangerous if the browser is used from a touchscreen enabled laptop. The mouse clicks would not work... –  franzlorenzon Oct 8 '13 at 11:03 Adapted from Matt's library (http://stackoverflow.com/a/9370637/1491212) itself adapted from google code, I wrote a jQuery plugin. Use like this : $('mySelector').fastClick(handler); (function($){ var clickbuster = { preventGhostClick: function(x, y) { clickbuster.coordinates.push(x, y); window.setTimeout(clickbuster.pop, 2500); }, pop: function() { clickbuster.coordinates.splice(0, 2); }, onClick: function(event) { for (var i = 0; i < clickbuster.coordinates.length; i += 2) { var x = clickbuster.coordinates[i]; var y = clickbuster.coordinates[i + 1]; if (Math.abs(event.clientX - x) < 25 && Math.abs(event.clientY - y) < 25) { event.stopPropagation(); event.preventDefault(); } } } }; var methods = { init: function(handler){ return this.each(function() { var $this = $(this), data = $this.data('fastClick'); if(!data){ this.addEventListener('touchstart', methods.handleEvent, false); this.addEventListener('click', methods.handleEvent, false); $this.data('fastClick', { target: $this, handler: handler }); } }); }, handleEvent:function(event) { switch (event.type) { case 'touchstart': $(this).fastClick('onTouchStart',event); break; case 'touchmove': $(this).fastClick('onTouchMove',event); break; case 'touchend': $(this).fastClick('onClick',event); break; case 'click': $(this).fastClick('onClick',event); break; } }, onTouchStart: function(event) { event.stopPropagation(); this[0].addEventListener('touchend', methods.handleEvent, false); var _this = this; document.body.addEventListener('touchmove', function(event){ methods.handleEvent.apply(_this,[event]); }, false); $(this).data('fastClick').startX = event.touches[0].clientX; $(this).data('fastClick').startY = event.touches[0].clientY; }, onTouchMove: function(event) { if (Math.abs(event.touches[0].clientX - this.data('fastClick').startX) > 10 || Math.abs(event.touches[0].clientY - this.data('fastClick').startY) > 10) { this.fastClick('reset'); } }, onClick: function(event) { event.stopPropagation(); $(this).fastClick('reset'); $(this).data('fastClick').handler.call(this,event); if (event.type == 'touchend') { clickbuster.preventGhostClick($(this).data('fastClick').startX, $(this).data('fastClick').startY); } }, reset: function() { this[0].removeEventListener('touchend', methods.handleEvent, false); document.body.removeEventListener('touchmove', methods.handleEvent, false); } } $.fn.fastClick = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if ( typeof method === 'object' || typeof method === 'function' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.hScroll'); } } clickbuster.coordinates = []; document.addEventListener('click', clickbuster.onClick, true); })(jQuery); share|improve this answer      This seems to be cool, but I can't work out how to know what I clicked on – $(this) doesn't return the thing you click, unlike binding an event normally. $('a').fastClick(function(){alert($(this).attr('href'))}); For instance – how might I get that to work? –  Rich Bradshaw Nov 2 '12 at 16:08      I ran into this problem also. Just edited my answer. The onClick handler must be called in the right scope: handler.call(this,event); See edit –  Armel Larcier Nov 3 '12 at 12:37 1   Also, is this required anymore? I saw a few articles suggesting that from Gingerbread onwards that if you disabled zooming on the viewport meta tag, touches didn't have the lag... Know anything about that? –  Rich Bradshaw Nov 3 '12 at 13:22      Don't know about android but it is still needed for iOS –  Armel Larcier Nov 3 '12 at 14:58      On iOS can't you just bind to touch instead of click - pretty sure that touch doesn't have the lag. –  Rich Bradshaw Nov 3 '12 at 15:12 Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.903596
Member Avatar for david.roun.7_1 Ok, so here is the problem. Below is a fairly simple code that will count the number of members registered to a site. The html works just fine but the php doesn't display anything unless I do something like if($result>0)--- then it will display everything to the right of the zero. If I use the code below, I get nothing. I'm hoping it's some stupid mistake instead of XAMPP not working correctly (the same thing happened on another page I tried to see using XAMPP). <!DOCTYPE HTML> <html> <head> <script src="javascript/login.js"></script> <script src="javascript/registerscript.js"></script> <script src="javascript/unsubscribe.js"></script> <script src="javascript/password.js"></script> </head> <body> <?php require('connect/registerdb.php'); $result=mysql_query("SELECT COUNT(*) FROM registration") or DIE(mysql_error()); while ($row=mysql_num_rows($result)){ echo 'There are . $result . 'members';} ?> <form id="login" action="session/session.php" onsubmit="return login();" method="POST"> <table> <tr><td>Login Id</td><td><input type="text" name="loginid" id="loginid"/></td></tr> <tr><td>Password</td><td><input type="password" name="password" id="password"/></td></tr> <tr><td></td><td><input type="submit" value="Log me in" /></td></tr> </table> </form> <table> <tr><td></td><td><input type="submit" value="Unsubscribe" onClick="unsub()"/></td></tr> <tr><td></td><td><input type="submit" value="I forgot my password" onClick="passret()"/></td></tr> <tr><td></td><td><input type="button" value="I need to register" onClick="loca()"/></td></tr> <tr><td></td><td><input type="submit" value="Do math" onClick="math.html"/></td></tr> </table> </body> </html> well although you are still using mysql you could do something like $query = "SELECT COUNT(id) FROM members"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ echo "There are ". $row['COUNT(id)'] ." members."; echo "<br />"; } Change this: echo 'There are . $result . 'members';} to this: echo 'There are '.$result.' members.';} Check out this PHP doc on string operators: http://www.php.net/manual/en/language.operators.string.php, specifically concatenation. If that's not the issue you could change your select statement and try something like this: <?php $result = mysql_query("SELECT COUNT(*) as count FROM registration") or DIE(mysql_error()); if($result['count'] > 0){ echo 'There are . $result . 'members'; }else{ echo 'There are no registered members yet!'; } ?> (Note: untested, probably won't work as-is!) If that doesn't work let me know and I'll have another look through. Michael Member Avatar for diafol Sounds like Apache isn't running or your php page is outside the localhost. Check the XAMPP control box to see if both Apache and MySQL are running. String concatenation error on line 15 inside while loop. echo 'There are . $result . 'members';} Try this: $result=mysql_query("SELECT COUNT(*) AS total FROM registration") or DIE(mysql_error()); $row = mysql_fetch_row($result); if($row[0]['total'] > 0) { echo 'There are ' . $row[0]['total'] . ' members.'; } It should work (not tested). Member Avatar for david.roun.7_1 All great suggestions but it was a problem with XAMPP. It works fine today, with a small change to the code. Thanks for all the advice, it made me notice how little I know about arrays. <!DOCTYPE HTML> <html> <head> <script src="javascript/login.js"></script> <script src="javascript/registerscript.js"></script> <script src="javascript/unsubscribe.js"></script> <script src="javascript/password.js"></script> </head> <body> <?php require('connect/registerdb.php'); $result=mysql_query("SELECT COUNT(name) FROM registration") or DIE(mysql_error()); $row=mysql_num_rows($result); echo 'There are ' . $row . ' members'; ?> <form id="login" action="session/session.php" onsubmit="return login();" method="POST"> <table> <tr><td>Login Id</td><td><input type="text" name="loginid" id="loginid"/></td></tr> <tr><td>Password</td><td><input type="password" name="password" id="password"/></td></tr> <tr><td></td><td><input type="submit" value="Log me in" /></td></tr> </table> </form> <table> <tr><td></td><td><input type="submit" value="Unsubscribe" onClick="unsub()"/></td></tr> <tr><td></td><td><input type="submit" value="I forgot my password" onClick="passret()"/></td></tr> <tr><td></td><td><input type="button" value="I need to register" onClick="loca()"/></td></tr> <tr><td></td><td><input type="submit" value="Do math" onClick="math.html"/></td></tr> </table> </body> </html> Be a part of the DaniWeb community We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.
__label__pos
0.588757
Fl&#225;vio Sousa Fl&#225;vio Sousa - 2 months ago 21 C Question Stuck in infinite fgets loop I'm trying to get a integer input, and I tried the most elementary method I could find. However, whenever something isn't a integer, it gets stuck in a infinite loop. I believe it's caused by the fgets funcion. I tried a few solutions I found on this site, but none worked. The code is as follows int getint() { int number; char input[4]; fgets(input, 4, stdin); while ( atoi(input) < 0 || ( strcmp(input, "0") != 0 && atoi(input) == 0 ) ) printf("Insert a non negative number: "); fgets(input, 4, stdin); number = atoi(input); printf("%d\n", number); return number; } Answer If there are more than one statements that you want to write in a loop or if statement, then you must use braces {} to define which statements come in the loop. In your code, only the printf("Insert a non negative number: "); statement is in the loop, and nothing is changing the input's value in the loop, so if the loop's condition is true, it will always remain true. Change it to: while ( atoi(input) < 0 || ( strcmp(input, "0") != 0 && atoi(input) == 0 ) ) { printf("Insert a non negative number: "); fgets(input, 4, stdin); } Comments
__label__pos
0.978804
Makefile.am 9.77 KB Newer Older 1 2 3 4 5 6 7 8 9 ############################################################################### # Automake targets and declarations ############################################################################### NULL = SUBDIRS = EXTRA_DIST = extras/COPYING misc/modules_builtin.h.in 10 BUILT_SOURCES = $(DISTCLEANFILES) $(CLEANFILES) misc/version.c 11 DISTCLEANFILES = stamp-api 12 CLEANFILES = misc/modules_builtin.h stamp-version 13 MOSTLYCLEANFILES = $(DATA_noinst_libvlc) stamp-builtins 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 TOOLBOX = srcdir=$(top_srcdir) builddir=$(top_builddir) $(top_srcdir)/toolbox ############################################################################### # Headers ############################################################################### pkgincludedir = $(includedir)/vlc dist_pkginclude_HEADERS = \ ../include/vlc/vlc.h \ ../include/vlc/libvlc.h \ ../include/vlc/aout.h \ ../include/vlc/vout.h \ ../include/vlc/sout.h \ ../include/vlc/decoder.h \ ../include/vlc/input.h \ ../include/vlc/intf.h \ ../include/vlc/mediacontrol.h \ ../include/vlc/mediacontrol_structures.h \ $(NULL) noinst_HEADERS = $(HEADERS_include) noinst_DATA = $(DATA_noinst_libvlc) HEADERS_include = \ ../include/aout_internal.h \ ../include/audio_output.h \ ../include/beos_specific.h \ ../include/charset.h \ ../include/codecs.h \ ../include/configuration.h \ ../include/darwin_specific.h \ ../include/intf_eject.h \ ../include/iso_lang.h \ ../include/main.h \ ../include/mmx.h \ ../include/modules.h \ ../include/modules_inner.h \ ../include/mtime.h \ ../include/network.h \ ../include/os_specific.h \ ../include/snapshot.h \ ../include/stream_output.h \ ../include/variables.h \ ../include/video_output.h \ ../include/vlc_access.h \ ../include/vlc_acl.h \ ../include/vlc_bits.h \ ../include/vlc_block.h \ ../include/vlc_block_helper.h \ ../include/vlc_codec.h \ ../include/vlc_common.h \ ../include/vlc_config.h \ ../include/vlc_cpu.h \ ../include/vlc_demux.h \ ../include/vlc_error.h \ ../include/vlc_es.h \ ../include/vlc_es_out.h \ ../include/vlc_filter.h \ ../include/vlc_config_cat.h \ ../include/vlc_httpd.h \ ../include/vlc_tls.h \ ../include/vlc_md5.h \ ../include/vlc_image.h \ ../include/vlc_input.h \ ../include/vlc_interaction.h \ ../include/vlc_interface.h \ ../include/vlc_keys.h \ ../include/vlc_messages.h \ ../include/vlc_meta.h \ ../include/vlc_objects.h \ ../include/vlc_osd.h \ ../include/vlc_playlist.h \ ../include/vlc_spu.h \ ../include/vlc_stream.h \ ../include/vlc_symbols.h \ ../include/vlc_threads_funcs.h \ ../include/vlc_threads.h \ ../include/vlc_update.h \ ../include/vlc_video.h \ ../include/vlc_vlm.h \ ../include/vlc_vod.h \ ../include/vlc_xml.h \ ../include/vout_synchro.h \ ../include/win32_specific.h \ ../include/libvlc_internal.h \ ../include/mediacontrol_internal.h $(NULL) misc/modules_builtin.h: Makefile misc/modules_builtin.h.in ../vlc-config $(TOOLBOX) --update-includes touch $@ misc/modules.c: misc/modules_builtin.h 110 misc/version.c: 111 112 $(TOOLBOX) --update-version 113 114 115 116 117 118 stamp-version: misc/version.c $(TOOLBOX) --update-version touch $@ .PHONY: stamp-version 119 120 121 122 123 124 125 126 127 ############################################################################### # Building builtin modules ############################################################################### # # As long as we use builtins with a shared libvlc, we must build them before # we build libvlc. Maybe one day, libvlc will handle multiple modules per # shared object, which will make builtins fairly redumdant. Until then, we # need this workaround. 128 stamp-builtins: Makefile ../vlc-config ../config.status 129 130 131 132 133 134 if USE_LIBTOOL @for c in `$(VLC_CONFIG) --libs builtin`; do \ case $$c in \ ../modules/*.a) echo $$c ;; \ esac ; \ done | \ 135 sed -e 's/^\(.*\)\/\([^\/]*\)\.a$$/cd \1 \&\& $(MAKE) \2_builtin.la/g' | \ 136 137 while read cmd; do echo $$cmd; eval "($$cmd)" || exit $$? ; done endif 138 139 140 141 142 143 144 145 146 if BUILD_SHARED @if test "$(pic)" = "pic"; then ext="_pic.a"; else ext=".a"; fi ; \ for c in `$(VLC_CONFIG) --libs builtin`; do \ case $$c in \ ../modules/*.a) echo $$c ;; \ esac ; \ done | \ sed -e 's/^\(.*\)\/\([^\/]*\)\.a$$/cd \1 \&\& $(MAKE) \2/g' | \ while read cmd; do echo $$cmd$$ext; eval "($$cmd$$ext)" || exit $$? ; done 147 endif 148 touch $@ 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 ############################################################################### # Building libvlc ############################################################################### libvlc_a_SOURCES = $(SOURCES_libvlc) libvlc_a_CFLAGS = `$(VLC_CONFIG) --cflags vlc` libvlc_a_CXXFLAGS = `$(VLC_CONFIG) --cxxflags vlc` libvlc_a_OBJCFLAGS = `$(VLC_CONFIG) --objcflags vlc` libvlc_pic_a_SOURCES = $(SOURCES_libvlc) libvlc_pic_a_CFLAGS = `$(VLC_CONFIG) --cflags vlc pic` libvlc_pic_a_CXXFLAGS = `$(VLC_CONFIG) --cxxflags vlc pic` libvlc_pic_a_OBJCFLAGS = `$(VLC_CONFIG) --objcflags vlc pic` 164 165 166 167 libvlc_la_SOURCES = $(SOURCES_libvlc) libvlc_la_CFLAGS = `$(VLC_CONFIG) --cflags vlc` libvlc_la_CXXFLAGS = `$(VLC_CONFIG) --cxxflags vlc` libvlc_la_OBJCFLAGS = `$(VLC_CONFIG) --objcflags vlc` Rémi Denis-Courmont's avatar Rémi Denis-Courmont committed 168 libvlc_la_LDFLAGS = `$(VLC_CONFIG) --libs vlc builtin|sed -e 's/\(modules\/[^ ]*\)\.a /\1_builtin.la /g'` \ 169 170 171 172 -avoid-version -no-undefined libvlc_la_DEPENDENCIES = stamp-builtins 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 if HAVE_BEOS OPT_SOURCES_libvlc_beos = $(SOURCES_libvlc_beos) endif if HAVE_DARWIN OPT_SOURCES_libvlc_darwin = $(SOURCES_libvlc_darwin) endif if HAVE_WIN32 OPT_SOURCES_libvlc_win32 = $(SOURCES_libvlc_win32) endif if HAVE_WINCE OPT_SOURCES_libvlc_win32 = $(SOURCES_libvlc_win32) endif if BUILD_DIRENT OPT_SOURCES_libvlc_dirent = $(SOURCES_libvlc_dirent) endif if BUILD_GETOPT OPT_SOURCES_libvlc_getopt = $(SOURCES_libvlc_getopt) endif # Build libvlc as a shared library 193 194 if USE_LIBTOOL lib_LTLIBRARIES = libvlc.la 195 else 196 lib_LIBRARIES = libvlc.a 197 if BUILD_PIC 198 lib_LIBRARIES += libvlc_pic.a 199 200 201 endif endif 202 if HAVE_WIN32 203 204 205 206 if BUILD_SHARED DATA_noinst_libvlc = libvlc$(LIBEXT) endif 207 libvlc$(LIBEXT): $(OBJECTS_libvlc_so) stamp-builtins 208 209 @ldfl="`$(VLC_CONFIG) --libs plugin vlc builtin $(pic)` $(INCLUDED_LIBINTL)" ; \ case `$(VLC_CONFIG) --linkage vlc builtin` in \ 210 211 212 213 c++) ld="$(CXXLINK)" ;; \ objc) ld="$(OBJCLINK)" ;; \ c|*) ld="$(LINK)" ;; \ esac ; \ 214 echo $$ld $(OBJECTS_libvlc_so) $(LDFLAGS_libvlc_so) $$ldfl; \ 215 216 $$ld $(libvlc_a_OBJECTS) \ -Wl,--out-implib,$(top_builddir)/src/libvlc.dll.a $$ldfl 217 218 219 220 # It sucks big time, but we have to do that to link vlc properly # on non-PIC OSes, otherwise ld will favor builtins-less libvlc.a over # libvlc$(LIBEXT) rm -f libvlc.a 221 # Cygwin work-around Rémi Denis-Courmont's avatar Rémi Denis-Courmont committed 222 @if test -f "[email protected]"; then mv -f "[email protected]" "$@"; fi 223 endif 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 EXTRA_DIST += \ $(SOURCES_libvlc_beos) \ $(SOURCES_libvlc_darwin) \ $(SOURCES_libvlc_win32) \ $(SOURCES_libvlc_dirent) \ $(SOURCES_libvlc_getopt) \ $(NULL) SOURCES_libvlc_beos = \ misc/beos_specific.cpp \ $(NULL) SOURCES_libvlc_darwin = \ misc/darwin_specific.m \ $(NULL) SOURCES_libvlc_win32 = \ misc/win32_specific.c \ $(NULL) SOURCES_libvlc_dirent = \ extras/dirent.c \ $(NULL) SOURCES_libvlc_getopt = \ extras/getopt.c \ extras/getopt.h \ extras/getopt1.c \ $(NULL) SOURCES_libvlc_common = \ libvlc.c \ libvlc.h \ interface/interface.c \ interface/intf_eject.c \ interface/interaction.c \ playlist/playlist.c \ playlist/sort.c \ playlist/loadsave.c \ playlist/view.c \ playlist/item.c \ playlist/item-ext.c \ playlist/services_discovery.c \ input/access.c \ input/clock.c \ input/control.c \ input/decoder.c \ input/demux.c \ input/es_out.c \ input/input.c \ input/input_internal.h \ input/stream.c \ input/mem_stream.c \ input/subtitles.c \ input/var.c \ video_output/video_output.c \ video_output/vout_pictures.c \ video_output/vout_pictures.h \ video_output/video_text.c \ video_output/video_widgets.c \ video_output/vout_subpictures.c \ video_output/vout_synchro.c \ video_output/vout_intf.c \ audio_output/common.c \ audio_output/dec.c \ audio_output/filters.c \ audio_output/ainput.c \ audio_output/mixer.c \ audio_output/output.c \ audio_output/intf.c \ stream_output/stream_output.c \ stream_output/announce.c \ stream_output/sap.c \ osd/osd.c \ osd/osd_parser.c \ osd/osd_text.c \ osd/osd_widgets.c \ network/acl.c \ network/getaddrinfo.c \ network/io.c \ network/tcp.c \ network/udp.c \ network/httpd.c \ network/rootwrap.c \ network/tls.c \ misc/charset.c \ misc/md5.c \ misc/mtime.c \ misc/block.c \ misc/modules.c \ misc/threads.c \ misc/stats.c \ misc/unicode.c \ misc/cpu.c \ misc/configuration.c \ misc/image.c \ misc/iso_lang.c \ misc/iso-639_def.h \ misc/messages.c \ misc/objects.c \ misc/variables.c \ misc/error.c \ misc/update.c \ misc/vlm.c \ misc/xml.c \ misc/hashtables.c \ misc/version.c \ extras/libc.c \ zorglub's avatar zorglub committed 333 334 335 336 337 control/libvlc_core.c \ control/libvlc_playlist.c \ control/libvlc_vlm.c \ control/libvlc_input.c \ control/libvlc_video.c \ littlejohn's avatar littlejohn committed 338 control/libvlc_audio.c \ 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 control/mediacontrol_core.c \ control/mediacontrol_util.c \ control/mediacontrol_audio_video.c \ $(NULL) # These should be distributed, but not compiled EXTRA_DIST += control/mediacontrol_init.c control/mediacontrol_plugin.c SOURCES_libvlc = \ $(SOURCES_libvlc_common) \ $(OPT_SOURCES_libvlc_beos) \ $(OPT_SOURCES_libvlc_darwin) \ $(OPT_SOURCES_libvlc_win32) \ $(OPT_SOURCES_libvlc_dirent) \ $(OPT_SOURCES_libvlc_getopt) \ $(NULL) 356 357 if !USE_LIBTOOL # Install shared libvlc 358 359 360 361 362 363 install-exec-local: test -z "$(DATA_noinst_libvlc)" || $(INSTALL_PROGRAM) "$(DATA_noinst_libvlc)" "$(DESTDIR)$(libdir)" # the opposite of install-{data,exec}-local uninstall-local: test -z "$(DATA_noinst_libvlc)" || rm -f "$(DESTDIR)$(libdir)/$(DATA_noinst_libvlc)" 364 endif 365 366 367 368 369 370 371 372 373 ############################################################################### # Stamp rules ############################################################################### stamp-api: Makefile.in $(HEADERS_include) ../vlc-api.pl ( cd $(srcdir) && cat $(HEADERS_include) ) | \ top_srcdir="$(top_srcdir)" perl $(top_srcdir)/vlc-api.pl touch stamp-api
__label__pos
0.787206
Subscribe Accepted Solution Adding an Active Directory group to Filer ? Dear NetApp Gurus, Would you be kind enough to advice the procedure to add an Active Directory group into filer as an user ? Thanks in advance & looking forward to hear from you soon. Henry Re: Adding an Active Directory group to Filer ? Have you tried connecting to the NetApp controller from the Windows MMC?  Connect to another computer, enter the name/ip of the netapp controller then you can see local users and groups.  If an AD group already not sure what you need to add it for if the system is already joined to the name and can resolve the group name for permission already though.
__label__pos
0.998878
Finding a substring in a NSString object Sagiftw picture Sagiftw · Sep 1, 2010 · Viewed 95.8k times · Source I have an NSString object and I want to make a substring from it, by locating a word. For example, my string is: "The dog ate the cat", I want the program to locate the word "ate" and make a substring that will be "the cat". Can someone help me out or give me an example? Thanks, Sagiftw Answer Joost picture Joost · Sep 1, 2010 NSRange range = [string rangeOfString:@"ate"]; NSString *substring = [[string substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
__label__pos
0.981435
Import('*') env = env.Clone() env.Prepend(CPPPATH = [ '#src', '#src/mapi', '#src/mesa', Dir('../../../mapi'), # src/mapi build path for python-generated GL API files/headers ]) env.Prepend(LIBS = [ mesautil, glapi, compiler, mesa, glsl, ]) sources = [ 'osmesa.c', ] if env['platform'] == 'windows': env.AppendUnique(CPPDEFINES = [ '_GDI32_', # prevent wgl* being declared __declspec(dllimport) 'BUILD_GL32', # declare gl* as __declspec(dllexport) in Mesa headers ]) if not env['gles']: # prevent _glapi_* from being declared __declspec(dllimport) env.Append(CPPDEFINES = ['_GLAPI_NO_EXPORTS']) sources += ['osmesa.def'] osmesa = env.SharedLibrary( target ='osmesa', source = sources, ) env.Alias('osmesa', osmesa)
__label__pos
0.997289
File: sqlite3.go package info (click to toggle) golang-github-mattn-go-sqlite3 1.6.0~ds1-2 • links: PTS, VCS • area: main • in suites: bullseye, sid • size: 452 kB • sloc: cpp: 1,132; ansic: 537; makefile: 41 file content (1346 lines) | stat: -rw-r--r-- 35,944 bytes parent folder | download | duplicates (2) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 // Copyright (C) 2014 Yasuhiro Matsumoto <[email protected]>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. package sqlite3 /* #cgo CFLAGS: -std=gnu99 #cgo CFLAGS: -DSQLITE_ENABLE_RTREE -DSQLITE_THREADSAFE=1 #cgo CFLAGS: -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_FTS3_PARENTHESIS -DSQLITE_ENABLE_FTS4_UNICODE61 #cgo CFLAGS: -DSQLITE_TRACE_SIZE_LIMIT=15 #cgo CFLAGS: -DSQLITE_DISABLE_INTRINSIC #cgo CFLAGS: -Wno-deprecated-declarations #ifndef USE_LIBSQLITE3 #include <sqlite3-binding.h> #else #include <sqlite3.h> #endif #include <stdlib.h> #include <string.h> #ifdef __CYGWIN__ # include <errno.h> #endif #ifndef SQLITE_OPEN_READWRITE # define SQLITE_OPEN_READWRITE 0 #endif #ifndef SQLITE_OPEN_FULLMUTEX # define SQLITE_OPEN_FULLMUTEX 0 #endif #ifndef SQLITE_DETERMINISTIC # define SQLITE_DETERMINISTIC 0 #endif static int _sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs) { #ifdef SQLITE_OPEN_URI return sqlite3_open_v2(filename, ppDb, flags | SQLITE_OPEN_URI, zVfs); #else return sqlite3_open_v2(filename, ppDb, flags, zVfs); #endif } static int _sqlite3_bind_text(sqlite3_stmt *stmt, int n, char *p, int np) { return sqlite3_bind_text(stmt, n, p, np, SQLITE_TRANSIENT); } static int _sqlite3_bind_blob(sqlite3_stmt *stmt, int n, void *p, int np) { return sqlite3_bind_blob(stmt, n, p, np, SQLITE_TRANSIENT); } #include <stdio.h> #include <stdint.h> static int _sqlite3_exec(sqlite3* db, const char* pcmd, long long* rowid, long long* changes) { int rv = sqlite3_exec(db, pcmd, 0, 0, 0); *rowid = (long long) sqlite3_last_insert_rowid(db); *changes = (long long) sqlite3_changes(db); return rv; } static int _sqlite3_step(sqlite3_stmt* stmt, long long* rowid, long long* changes) { int rv = sqlite3_step(stmt); sqlite3* db = sqlite3_db_handle(stmt); *rowid = (long long) sqlite3_last_insert_rowid(db); *changes = (long long) sqlite3_changes(db); return rv; } void _sqlite3_result_text(sqlite3_context* ctx, const char* s) { sqlite3_result_text(ctx, s, -1, &free); } void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l) { sqlite3_result_blob(ctx, b, l, SQLITE_TRANSIENT); } int _sqlite3_create_function( sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, uintptr_t pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ) { return sqlite3_create_function(db, zFunctionName, nArg, eTextRep, (void*) pApp, xFunc, xStep, xFinal); } void callbackTrampoline(sqlite3_context*, int, sqlite3_value**); void stepTrampoline(sqlite3_context*, int, sqlite3_value**); void doneTrampoline(sqlite3_context*); int compareTrampoline(void*, int, char*, int, char*); int commitHookTrampoline(void*); void rollbackHookTrampoline(void*); void updateHookTrampoline(void*, int, char*, char*, sqlite3_int64); #ifdef SQLITE_LIMIT_WORKER_THREADS # define _SQLITE_HAS_LIMIT # define SQLITE_LIMIT_LENGTH 0 # define SQLITE_LIMIT_SQL_LENGTH 1 # define SQLITE_LIMIT_COLUMN 2 # define SQLITE_LIMIT_EXPR_DEPTH 3 # define SQLITE_LIMIT_COMPOUND_SELECT 4 # define SQLITE_LIMIT_VDBE_OP 5 # define SQLITE_LIMIT_FUNCTION_ARG 6 # define SQLITE_LIMIT_ATTACHED 7 # define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 # define SQLITE_LIMIT_VARIABLE_NUMBER 9 # define SQLITE_LIMIT_TRIGGER_DEPTH 10 # define SQLITE_LIMIT_WORKER_THREADS 11 # else # define SQLITE_LIMIT_WORKER_THREADS 11 #endif static int _sqlite3_limit(sqlite3* db, int limitId, int newLimit) { #ifndef _SQLITE_HAS_LIMIT return -1; #else return sqlite3_limit(db, limitId, newLimit); #endif } */ import "C" import ( "context" "database/sql" "database/sql/driver" "errors" "fmt" "io" "net/url" "reflect" "runtime" "strconv" "strings" "sync" "time" "unsafe" ) // SQLiteTimestampFormats is timestamp formats understood by both this module // and SQLite. The first format in the slice will be used when saving time // values into the database. When parsing a string from a timestamp or datetime // column, the formats are tried in order. var SQLiteTimestampFormats = []string{ // By default, store timestamps with whatever timezone they come with. // When parsed, they will be returned with the same timezone. "2006-01-02 15:04:05.999999999-07:00", "2006-01-02T15:04:05.999999999-07:00", "2006-01-02 15:04:05.999999999", "2006-01-02T15:04:05.999999999", "2006-01-02 15:04:05", "2006-01-02T15:04:05", "2006-01-02 15:04", "2006-01-02T15:04", "2006-01-02", } func init() { sql.Register("sqlite3", &SQLiteDriver{}) } // Version returns SQLite library version information. func Version() (libVersion string, libVersionNumber int, sourceID string) { libVersion = C.GoString(C.sqlite3_libversion()) libVersionNumber = int(C.sqlite3_libversion_number()) sourceID = C.GoString(C.sqlite3_sourceid()) return libVersion, libVersionNumber, sourceID } const ( SQLITE_DELETE = C.SQLITE_DELETE SQLITE_INSERT = C.SQLITE_INSERT SQLITE_UPDATE = C.SQLITE_UPDATE ) // SQLiteDriver implement sql.Driver. type SQLiteDriver struct { Extensions []string ConnectHook func(*SQLiteConn) error } // SQLiteConn implement sql.Conn. type SQLiteConn struct { mu sync.Mutex db *C.sqlite3 loc *time.Location txlock string funcs []*functionInfo aggregators []*aggInfo } // SQLiteTx implemen sql.Tx. type SQLiteTx struct { c *SQLiteConn } // SQLiteStmt implement sql.Stmt. type SQLiteStmt struct { mu sync.Mutex c *SQLiteConn s *C.sqlite3_stmt t string closed bool cls bool } // SQLiteResult implement sql.Result. type SQLiteResult struct { id int64 changes int64 } // SQLiteRows implement sql.Rows. type SQLiteRows struct { s *SQLiteStmt nc int cols []string decltype []string cls bool closed bool done chan struct{} } type functionInfo struct { f reflect.Value argConverters []callbackArgConverter variadicConverter callbackArgConverter retConverter callbackRetConverter } func (fi *functionInfo) Call(ctx *C.sqlite3_context, argv []*C.sqlite3_value) { args, err := callbackConvertArgs(argv, fi.argConverters, fi.variadicConverter) if err != nil { callbackError(ctx, err) return } ret := fi.f.Call(args) if len(ret) == 2 && ret[1].Interface() != nil { callbackError(ctx, ret[1].Interface().(error)) return } err = fi.retConverter(ctx, ret[0]) if err != nil { callbackError(ctx, err) return } } type aggInfo struct { constructor reflect.Value // Active aggregator objects for aggregations in flight. The // aggregators are indexed by a counter stored in the aggregation // user data space provided by sqlite. active map[int64]reflect.Value next int64 stepArgConverters []callbackArgConverter stepVariadicConverter callbackArgConverter doneRetConverter callbackRetConverter } func (ai *aggInfo) agg(ctx *C.sqlite3_context) (int64, reflect.Value, error) { aggIdx := (*int64)(C.sqlite3_aggregate_context(ctx, C.int(8))) if *aggIdx == 0 { *aggIdx = ai.next ret := ai.constructor.Call(nil) if len(ret) == 2 && ret[1].Interface() != nil { return 0, reflect.Value{}, ret[1].Interface().(error) } if ret[0].IsNil() { return 0, reflect.Value{}, errors.New("aggregator constructor returned nil state") } ai.next++ ai.active[*aggIdx] = ret[0] } return *aggIdx, ai.active[*aggIdx], nil } func (ai *aggInfo) Step(ctx *C.sqlite3_context, argv []*C.sqlite3_value) { _, agg, err := ai.agg(ctx) if err != nil { callbackError(ctx, err) return } args, err := callbackConvertArgs(argv, ai.stepArgConverters, ai.stepVariadicConverter) if err != nil { callbackError(ctx, err) return } ret := agg.MethodByName("Step").Call(args) if len(ret) == 1 && ret[0].Interface() != nil { callbackError(ctx, ret[0].Interface().(error)) return } } func (ai *aggInfo) Done(ctx *C.sqlite3_context) { idx, agg, err := ai.agg(ctx) if err != nil { callbackError(ctx, err) return } defer func() { delete(ai.active, idx) }() ret := agg.MethodByName("Done").Call(nil) if len(ret) == 2 && ret[1].Interface() != nil { callbackError(ctx, ret[1].Interface().(error)) return } err = ai.doneRetConverter(ctx, ret[0]) if err != nil { callbackError(ctx, err) return } } // Commit transaction. func (tx *SQLiteTx) Commit() error { _, err := tx.c.exec(context.Background(), "COMMIT", nil) if err != nil && err.(Error).Code == C.SQLITE_BUSY { // sqlite3 will leave the transaction open in this scenario. // However, database/sql considers the transaction complete once we // return from Commit() - we must clean up to honour its semantics. tx.c.exec(context.Background(), "ROLLBACK", nil) } return err } // Rollback transaction. func (tx *SQLiteTx) Rollback() error { _, err := tx.c.exec(context.Background(), "ROLLBACK", nil) return err } // RegisterCollation makes a Go function available as a collation. // // cmp receives two UTF-8 strings, a and b. The result should be 0 if // a==b, -1 if a < b, and +1 if a > b. // // cmp must always return the same result given the same // inputs. Additionally, it must have the following properties for all // strings A, B and C: if A==B then B==A; if A==B and B==C then A==C; // if A<B then B>A; if A<B and B<C then A<C. // // If cmp does not obey these constraints, sqlite3's behavior is // undefined when the collation is used. func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int) error { handle := newHandle(c, cmp) cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) rv := C.sqlite3_create_collation(c.db, cname, C.SQLITE_UTF8, unsafe.Pointer(handle), (*[0]byte)(unsafe.Pointer(C.compareTrampoline))) if rv != C.SQLITE_OK { return c.lastError() } return nil } // RegisterCommitHook sets the commit hook for a connection. // // If the callback returns non-zero the transaction will become a rollback. // // If there is an existing commit hook for this connection, it will be // removed. If callback is nil the existing hook (if any) will be removed // without creating a new one. func (c *SQLiteConn) RegisterCommitHook(callback func() int) { if callback == nil { C.sqlite3_commit_hook(c.db, nil, nil) } else { C.sqlite3_commit_hook(c.db, (*[0]byte)(unsafe.Pointer(C.commitHookTrampoline)), unsafe.Pointer(newHandle(c, callback))) } } // RegisterRollbackHook sets the rollback hook for a connection. // // If there is an existing rollback hook for this connection, it will be // removed. If callback is nil the existing hook (if any) will be removed // without creating a new one. func (c *SQLiteConn) RegisterRollbackHook(callback func()) { if callback == nil { C.sqlite3_rollback_hook(c.db, nil, nil) } else { C.sqlite3_rollback_hook(c.db, (*[0]byte)(unsafe.Pointer(C.rollbackHookTrampoline)), unsafe.Pointer(newHandle(c, callback))) } } // RegisterUpdateHook sets the update hook for a connection. // // The parameters to the callback are the operation (one of the constants // SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), the database name, the // table name, and the rowid. // // If there is an existing update hook for this connection, it will be // removed. If callback is nil the existing hook (if any) will be removed // without creating a new one. func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64)) { if callback == nil { C.sqlite3_update_hook(c.db, nil, nil) } else { C.sqlite3_update_hook(c.db, (*[0]byte)(unsafe.Pointer(C.updateHookTrampoline)), unsafe.Pointer(newHandle(c, callback))) } } // RegisterFunc makes a Go function available as a SQLite function. // // The Go function can have arguments of the following types: any // numeric type except complex, bool, []byte, string and // interface{}. interface{} arguments are given the direct translation // of the SQLite data type: int64 for INTEGER, float64 for FLOAT, // []byte for BLOB, string for TEXT. // // The function can additionally be variadic, as long as the type of // the variadic argument is one of the above. // // If pure is true. SQLite will assume that the function's return // value depends only on its inputs, and make more aggressive // optimizations in its queries. // // See _example/go_custom_funcs for a detailed example. func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error { var fi functionInfo fi.f = reflect.ValueOf(impl) t := fi.f.Type() if t.Kind() != reflect.Func { return errors.New("Non-function passed to RegisterFunc") } if t.NumOut() != 1 && t.NumOut() != 2 { return errors.New("SQLite functions must return 1 or 2 values") } if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) { return errors.New("Second return value of SQLite function must be error") } numArgs := t.NumIn() if t.IsVariadic() { numArgs-- } for i := 0; i < numArgs; i++ { conv, err := callbackArg(t.In(i)) if err != nil { return err } fi.argConverters = append(fi.argConverters, conv) } if t.IsVariadic() { conv, err := callbackArg(t.In(numArgs).Elem()) if err != nil { return err } fi.variadicConverter = conv // Pass -1 to sqlite so that it allows any number of // arguments. The call helper verifies that the minimum number // of arguments is present for variadic functions. numArgs = -1 } conv, err := callbackRet(t.Out(0)) if err != nil { return err } fi.retConverter = conv // fi must outlast the database connection, or we'll have dangling pointers. c.funcs = append(c.funcs, &fi) cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) opts := C.SQLITE_UTF8 if pure { opts |= C.SQLITE_DETERMINISTIC } rv := sqlite3CreateFunction(c.db, cname, C.int(numArgs), C.int(opts), newHandle(c, &fi), C.callbackTrampoline, nil, nil) if rv != C.SQLITE_OK { return c.lastError() } return nil } func sqlite3CreateFunction(db *C.sqlite3, zFunctionName *C.char, nArg C.int, eTextRep C.int, pApp uintptr, xFunc unsafe.Pointer, xStep unsafe.Pointer, xFinal unsafe.Pointer) C.int { return C._sqlite3_create_function(db, zFunctionName, nArg, eTextRep, C.uintptr_t(pApp), (*[0]byte)(unsafe.Pointer(xFunc)), (*[0]byte)(unsafe.Pointer(xStep)), (*[0]byte)(unsafe.Pointer(xFinal))) } // RegisterAggregator makes a Go type available as a SQLite aggregation function. // // Because aggregation is incremental, it's implemented in Go with a // type that has 2 methods: func Step(values) accumulates one row of // data into the accumulator, and func Done() ret finalizes and // returns the aggregate value. "values" and "ret" may be any type // supported by RegisterFunc. // // RegisterAggregator takes as implementation a constructor function // that constructs an instance of the aggregator type each time an // aggregation begins. The constructor must return a pointer to a // type, or an interface that implements Step() and Done(). // // The constructor function and the Step/Done methods may optionally // return an error in addition to their other return values. // // See _example/go_custom_funcs for a detailed example. func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error { var ai aggInfo ai.constructor = reflect.ValueOf(impl) t := ai.constructor.Type() if t.Kind() != reflect.Func { return errors.New("non-function passed to RegisterAggregator") } if t.NumOut() != 1 && t.NumOut() != 2 { return errors.New("SQLite aggregator constructors must return 1 or 2 values") } if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) { return errors.New("Second return value of SQLite function must be error") } if t.NumIn() != 0 { return errors.New("SQLite aggregator constructors must not have arguments") } agg := t.Out(0) switch agg.Kind() { case reflect.Ptr, reflect.Interface: default: return errors.New("SQlite aggregator constructor must return a pointer object") } stepFn, found := agg.MethodByName("Step") if !found { return errors.New("SQlite aggregator doesn't have a Step() function") } step := stepFn.Type if step.NumOut() != 0 && step.NumOut() != 1 { return errors.New("SQlite aggregator Step() function must return 0 or 1 values") } if step.NumOut() == 1 && !step.Out(0).Implements(reflect.TypeOf((*error)(nil)).Elem()) { return errors.New("type of SQlite aggregator Step() return value must be error") } stepNArgs := step.NumIn() start := 0 if agg.Kind() == reflect.Ptr { // Skip over the method receiver stepNArgs-- start++ } if step.IsVariadic() { stepNArgs-- } for i := start; i < start+stepNArgs; i++ { conv, err := callbackArg(step.In(i)) if err != nil { return err } ai.stepArgConverters = append(ai.stepArgConverters, conv) } if step.IsVariadic() { conv, err := callbackArg(t.In(start + stepNArgs).Elem()) if err != nil { return err } ai.stepVariadicConverter = conv // Pass -1 to sqlite so that it allows any number of // arguments. The call helper verifies that the minimum number // of arguments is present for variadic functions. stepNArgs = -1 } doneFn, found := agg.MethodByName("Done") if !found { return errors.New("SQlite aggregator doesn't have a Done() function") } done := doneFn.Type doneNArgs := done.NumIn() if agg.Kind() == reflect.Ptr { // Skip over the method receiver doneNArgs-- } if doneNArgs != 0 { return errors.New("SQlite aggregator Done() function must have no arguments") } if done.NumOut() != 1 && done.NumOut() != 2 { return errors.New("SQLite aggregator Done() function must return 1 or 2 values") } if done.NumOut() == 2 && !done.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) { return errors.New("second return value of SQLite aggregator Done() function must be error") } conv, err := callbackRet(done.Out(0)) if err != nil { return err } ai.doneRetConverter = conv ai.active = make(map[int64]reflect.Value) ai.next = 1 // ai must outlast the database connection, or we'll have dangling pointers. c.aggregators = append(c.aggregators, &ai) cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) opts := C.SQLITE_UTF8 if pure { opts |= C.SQLITE_DETERMINISTIC } rv := sqlite3CreateFunction(c.db, cname, C.int(stepNArgs), C.int(opts), newHandle(c, &ai), nil, C.stepTrampoline, C.doneTrampoline) if rv != C.SQLITE_OK { return c.lastError() } return nil } // AutoCommit return which currently auto commit or not. func (c *SQLiteConn) AutoCommit() bool { return int(C.sqlite3_get_autocommit(c.db)) != 0 } func (c *SQLiteConn) lastError() error { return lastError(c.db) } func lastError(db *C.sqlite3) error { rv := C.sqlite3_errcode(db) if rv == C.SQLITE_OK { return nil } return Error{ Code: ErrNo(rv), ExtendedCode: ErrNoExtended(C.sqlite3_extended_errcode(db)), err: C.GoString(C.sqlite3_errmsg(db)), } } // Exec implements Execer. func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return c.exec(context.Background(), query, list) } func (c *SQLiteConn) exec(ctx context.Context, query string, args []namedValue) (driver.Result, error) { start := 0 for { s, err := c.prepare(ctx, query) if err != nil { return nil, err } var res driver.Result if s.(*SQLiteStmt).s != nil { na := s.NumInput() if len(args) < na { s.Close() return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args)) } for i := 0; i < na; i++ { args[i].Ordinal -= start } res, err = s.(*SQLiteStmt).exec(ctx, args[:na]) if err != nil && err != driver.ErrSkip { s.Close() return nil, err } args = args[na:] start += na } tail := s.(*SQLiteStmt).t s.Close() if tail == "" { return res, nil } query = tail } } type namedValue struct { Name string Ordinal int Value driver.Value } // Query implements Queryer. func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return c.query(context.Background(), query, list) } func (c *SQLiteConn) query(ctx context.Context, query string, args []namedValue) (driver.Rows, error) { start := 0 for { s, err := c.prepare(ctx, query) if err != nil { return nil, err } s.(*SQLiteStmt).cls = true na := s.NumInput() if len(args) < na { return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args)) } for i := 0; i < na; i++ { args[i].Ordinal -= start } rows, err := s.(*SQLiteStmt).query(ctx, args[:na]) if err != nil && err != driver.ErrSkip { s.Close() return rows, err } args = args[na:] start += na tail := s.(*SQLiteStmt).t if tail == "" { return rows, nil } rows.Close() s.Close() query = tail } } // Begin transaction. func (c *SQLiteConn) Begin() (driver.Tx, error) { return c.begin(context.Background()) } func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) { if _, err := c.exec(ctx, c.txlock, nil); err != nil { return nil, err } return &SQLiteTx{c}, nil } func errorString(err Error) string { return C.GoString(C.sqlite3_errstr(C.int(err.Code))) } // Open database and return a new connection. // You can specify a DSN string using a URI as the filename. // test.db // file:test.db?cache=shared&mode=memory // :memory: // file::memory: // go-sqlite3 adds the following query parameters to those used by SQLite: // _loc=XXX // Specify location of time format. It's possible to specify "auto". // _busy_timeout=XXX // Specify value for sqlite3_busy_timeout. // _txlock=XXX // Specify locking behavior for transactions. XXX can be "immediate", // "deferred", "exclusive". // _foreign_keys=X // Enable or disable enforcement of foreign keys. X can be 1 or 0. // _recursive_triggers=X // Enable or disable recursive triggers. X can be 1 or 0. func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) { if C.sqlite3_threadsafe() == 0 { return nil, errors.New("sqlite library was not compiled for thread-safe operation") } var loc *time.Location txlock := "BEGIN" busyTimeout := 5000 foreignKeys := -1 recursiveTriggers := -1 pos := strings.IndexRune(dsn, '?') if pos >= 1 { params, err := url.ParseQuery(dsn[pos+1:]) if err != nil { return nil, err } // _loc if val := params.Get("_loc"); val != "" { if val == "auto" { loc = time.Local } else { loc, err = time.LoadLocation(val) if err != nil { return nil, fmt.Errorf("Invalid _loc: %v: %v", val, err) } } } // _busy_timeout if val := params.Get("_busy_timeout"); val != "" { iv, err := strconv.ParseInt(val, 10, 64) if err != nil { return nil, fmt.Errorf("Invalid _busy_timeout: %v: %v", val, err) } busyTimeout = int(iv) } // _txlock if val := params.Get("_txlock"); val != "" { switch val { case "immediate": txlock = "BEGIN IMMEDIATE" case "exclusive": txlock = "BEGIN EXCLUSIVE" case "deferred": txlock = "BEGIN" default: return nil, fmt.Errorf("Invalid _txlock: %v", val) } } // _foreign_keys if val := params.Get("_foreign_keys"); val != "" { switch val { case "1": foreignKeys = 1 case "0": foreignKeys = 0 default: return nil, fmt.Errorf("Invalid _foreign_keys: %v", val) } } // _recursive_triggers if val := params.Get("_recursive_triggers"); val != "" { switch val { case "1": recursiveTriggers = 1 case "0": recursiveTriggers = 0 default: return nil, fmt.Errorf("Invalid _recursive_triggers: %v", val) } } if !strings.HasPrefix(dsn, "file:") { dsn = dsn[:pos] } } var db *C.sqlite3 name := C.CString(dsn) defer C.free(unsafe.Pointer(name)) rv := C._sqlite3_open_v2(name, &db, C.SQLITE_OPEN_FULLMUTEX| C.SQLITE_OPEN_READWRITE| C.SQLITE_OPEN_CREATE, nil) if rv != 0 { return nil, Error{Code: ErrNo(rv)} } if db == nil { return nil, errors.New("sqlite succeeded without returning a database") } rv = C.sqlite3_busy_timeout(db, C.int(busyTimeout)) if rv != C.SQLITE_OK { C.sqlite3_close_v2(db) return nil, Error{Code: ErrNo(rv)} } exec := func(s string) error { cs := C.CString(s) rv := C.sqlite3_exec(db, cs, nil, nil, nil) C.free(unsafe.Pointer(cs)) if rv != C.SQLITE_OK { return lastError(db) } return nil } if foreignKeys == 0 { if err := exec("PRAGMA foreign_keys = OFF;"); err != nil { C.sqlite3_close_v2(db) return nil, err } } else if foreignKeys == 1 { if err := exec("PRAGMA foreign_keys = ON;"); err != nil { C.sqlite3_close_v2(db) return nil, err } } if recursiveTriggers == 0 { if err := exec("PRAGMA recursive_triggers = OFF;"); err != nil { C.sqlite3_close_v2(db) return nil, err } } else if recursiveTriggers == 1 { if err := exec("PRAGMA recursive_triggers = ON;"); err != nil { C.sqlite3_close_v2(db) return nil, err } } conn := &SQLiteConn{db: db, loc: loc, txlock: txlock} if len(d.Extensions) > 0 { if err := conn.loadExtensions(d.Extensions); err != nil { conn.Close() return nil, err } } if d.ConnectHook != nil { if err := d.ConnectHook(conn); err != nil { conn.Close() return nil, err } } runtime.SetFinalizer(conn, (*SQLiteConn).Close) return conn, nil } // Close the connection. func (c *SQLiteConn) Close() error { rv := C.sqlite3_close_v2(c.db) if rv != C.SQLITE_OK { return c.lastError() } deleteHandles(c) c.mu.Lock() c.db = nil c.mu.Unlock() runtime.SetFinalizer(c, nil) return nil } func (c *SQLiteConn) dbConnOpen() bool { if c == nil { return false } c.mu.Lock() defer c.mu.Unlock() return c.db != nil } // Prepare the query string. Return a new statement. func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) { return c.prepare(context.Background(), query) } func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, error) { pquery := C.CString(query) defer C.free(unsafe.Pointer(pquery)) var s *C.sqlite3_stmt var tail *C.char rv := C.sqlite3_prepare_v2(c.db, pquery, -1, &s, &tail) if rv != C.SQLITE_OK { return nil, c.lastError() } var t string if tail != nil && *tail != '\000' { t = strings.TrimSpace(C.GoString(tail)) } ss := &SQLiteStmt{c: c, s: s, t: t} runtime.SetFinalizer(ss, (*SQLiteStmt).Close) return ss, nil } // Run-Time Limit Categories. // See: http://www.sqlite.org/c3ref/c_limit_attached.html const ( SQLITE_LIMIT_LENGTH = C.SQLITE_LIMIT_LENGTH SQLITE_LIMIT_SQL_LENGTH = C.SQLITE_LIMIT_SQL_LENGTH SQLITE_LIMIT_COLUMN = C.SQLITE_LIMIT_COLUMN SQLITE_LIMIT_EXPR_DEPTH = C.SQLITE_LIMIT_EXPR_DEPTH SQLITE_LIMIT_COMPOUND_SELECT = C.SQLITE_LIMIT_COMPOUND_SELECT SQLITE_LIMIT_VDBE_OP = C.SQLITE_LIMIT_VDBE_OP SQLITE_LIMIT_FUNCTION_ARG = C.SQLITE_LIMIT_FUNCTION_ARG SQLITE_LIMIT_ATTACHED = C.SQLITE_LIMIT_ATTACHED SQLITE_LIMIT_LIKE_PATTERN_LENGTH = C.SQLITE_LIMIT_LIKE_PATTERN_LENGTH SQLITE_LIMIT_VARIABLE_NUMBER = C.SQLITE_LIMIT_VARIABLE_NUMBER SQLITE_LIMIT_TRIGGER_DEPTH = C.SQLITE_LIMIT_TRIGGER_DEPTH SQLITE_LIMIT_WORKER_THREADS = C.SQLITE_LIMIT_WORKER_THREADS ) // GetLimit returns the current value of a run-time limit. // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html func (c *SQLiteConn) GetLimit(id int) int { return int(C._sqlite3_limit(c.db, C.int(id), -1)) } // SetLimit changes the value of a run-time limits. // Then this method returns the prior value of the limit. // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html func (c *SQLiteConn) SetLimit(id int, newVal int) int { return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal))) } // Close the statement. func (s *SQLiteStmt) Close() error { s.mu.Lock() defer s.mu.Unlock() if s.closed { return nil } s.closed = true if !s.c.dbConnOpen() { return errors.New("sqlite statement with already closed database connection") } rv := C.sqlite3_finalize(s.s) s.s = nil if rv != C.SQLITE_OK { return s.c.lastError() } runtime.SetFinalizer(s, nil) return nil } // NumInput return a number of parameters. func (s *SQLiteStmt) NumInput() int { return int(C.sqlite3_bind_parameter_count(s.s)) } type bindArg struct { n int v driver.Value } var placeHolder = []byte{0} func (s *SQLiteStmt) bind(args []namedValue) error { rv := C.sqlite3_reset(s.s) if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE { return s.c.lastError() } for i, v := range args { if v.Name != "" { cname := C.CString(":" + v.Name) args[i].Ordinal = int(C.sqlite3_bind_parameter_index(s.s, cname)) C.free(unsafe.Pointer(cname)) } } for _, arg := range args { n := C.int(arg.Ordinal) switch v := arg.Value.(type) { case nil: rv = C.sqlite3_bind_null(s.s, n) case string: if len(v) == 0 { rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.int(0)) } else { b := []byte(v) rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b))) } case int64: rv = C.sqlite3_bind_int64(s.s, n, C.sqlite3_int64(v)) case bool: if bool(v) { rv = C.sqlite3_bind_int(s.s, n, 1) } else { rv = C.sqlite3_bind_int(s.s, n, 0) } case float64: rv = C.sqlite3_bind_double(s.s, n, C.double(v)) case []byte: ln := len(v) if ln == 0 { v = placeHolder } rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(ln)) case time.Time: b := []byte(v.Format(SQLiteTimestampFormats[0])) rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b))) } if rv != C.SQLITE_OK { return s.c.lastError() } } return nil } // Query the statement with arguments. Return records. func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return s.query(context.Background(), list) } func (s *SQLiteStmt) query(ctx context.Context, args []namedValue) (driver.Rows, error) { if err := s.bind(args); err != nil { return nil, err } rows := &SQLiteRows{ s: s, nc: int(C.sqlite3_column_count(s.s)), cols: nil, decltype: nil, cls: s.cls, closed: false, done: make(chan struct{}), } go func(db *C.sqlite3) { select { case <-ctx.Done(): select { case <-rows.done: default: C.sqlite3_interrupt(db) rows.Close() } case <-rows.done: } }(s.c.db) return rows, nil } // LastInsertId teturn last inserted ID. func (r *SQLiteResult) LastInsertId() (int64, error) { return r.id, nil } // RowsAffected return how many rows affected. func (r *SQLiteResult) RowsAffected() (int64, error) { return r.changes, nil } // Exec execute the statement with arguments. Return result object. func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) { list := make([]namedValue, len(args)) for i, v := range args { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return s.exec(context.Background(), list) } func (s *SQLiteStmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) { if err := s.bind(args); err != nil { C.sqlite3_reset(s.s) C.sqlite3_clear_bindings(s.s) return nil, err } done := make(chan struct{}) defer close(done) go func(db *C.sqlite3) { select { case <-done: case <-ctx.Done(): select { case <-done: default: C.sqlite3_interrupt(db) } } }(s.c.db) var rowid, changes C.longlong rv := C._sqlite3_step(s.s, &rowid, &changes) if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE { err := s.c.lastError() C.sqlite3_reset(s.s) C.sqlite3_clear_bindings(s.s) return nil, err } return &SQLiteResult{id: int64(rowid), changes: int64(changes)}, nil } // Close the rows. func (rc *SQLiteRows) Close() error { rc.s.mu.Lock() if rc.s.closed || rc.closed { rc.s.mu.Unlock() return nil } rc.closed = true if rc.done != nil { close(rc.done) } if rc.cls { rc.s.mu.Unlock() return rc.s.Close() } rv := C.sqlite3_reset(rc.s.s) if rv != C.SQLITE_OK { rc.s.mu.Unlock() return rc.s.c.lastError() } rc.s.mu.Unlock() return nil } // Columns return column names. func (rc *SQLiteRows) Columns() []string { rc.s.mu.Lock() defer rc.s.mu.Unlock() if rc.s.s != nil && rc.nc != len(rc.cols) { rc.cols = make([]string, rc.nc) for i := 0; i < rc.nc; i++ { rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i))) } } return rc.cols } func (rc *SQLiteRows) declTypes() []string { if rc.s.s != nil && rc.decltype == nil { rc.decltype = make([]string, rc.nc) for i := 0; i < rc.nc; i++ { rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i)))) } } return rc.decltype } // DeclTypes return column types. func (rc *SQLiteRows) DeclTypes() []string { rc.s.mu.Lock() defer rc.s.mu.Unlock() return rc.declTypes() } // Next move cursor to next. func (rc *SQLiteRows) Next(dest []driver.Value) error { if rc.s.closed { return io.EOF } rc.s.mu.Lock() defer rc.s.mu.Unlock() rv := C.sqlite3_step(rc.s.s) if rv == C.SQLITE_DONE { return io.EOF } if rv != C.SQLITE_ROW { rv = C.sqlite3_reset(rc.s.s) if rv != C.SQLITE_OK { return rc.s.c.lastError() } return nil } rc.declTypes() for i := range dest { switch C.sqlite3_column_type(rc.s.s, C.int(i)) { case C.SQLITE_INTEGER: val := int64(C.sqlite3_column_int64(rc.s.s, C.int(i))) switch rc.decltype[i] { case "timestamp", "datetime", "date": var t time.Time // Assume a millisecond unix timestamp if it's 13 digits -- too // large to be a reasonable timestamp in seconds. if val > 1e12 || val < -1e12 { val *= int64(time.Millisecond) // convert ms to nsec t = time.Unix(0, val) } else { t = time.Unix(val, 0) } t = t.UTC() if rc.s.c.loc != nil { t = t.In(rc.s.c.loc) } dest[i] = t case "boolean": dest[i] = val > 0 default: dest[i] = val } case C.SQLITE_FLOAT: dest[i] = float64(C.sqlite3_column_double(rc.s.s, C.int(i))) case C.SQLITE_BLOB: p := C.sqlite3_column_blob(rc.s.s, C.int(i)) if p == nil { dest[i] = nil continue } n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i))) switch dest[i].(type) { case sql.RawBytes: dest[i] = (*[1 << 30]byte)(unsafe.Pointer(p))[0:n] default: slice := make([]byte, n) copy(slice[:], (*[1 << 30]byte)(unsafe.Pointer(p))[0:n]) dest[i] = slice } case C.SQLITE_NULL: dest[i] = nil case C.SQLITE_TEXT: var err error var timeVal time.Time n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i))) s := C.GoStringN((*C.char)(unsafe.Pointer(C.sqlite3_column_text(rc.s.s, C.int(i)))), C.int(n)) switch rc.decltype[i] { case "timestamp", "datetime", "date": var t time.Time s = strings.TrimSuffix(s, "Z") for _, format := range SQLiteTimestampFormats { if timeVal, err = time.ParseInLocation(format, s, time.UTC); err == nil { t = timeVal break } } if err != nil { // The column is a time value, so return the zero time on parse failure. t = time.Time{} } if rc.s.c.loc != nil { t = t.In(rc.s.c.loc) } dest[i] = t default: dest[i] = []byte(s) } } } return nil }
__label__pos
0.980101
Displaying addition of times using structure and function   c++, function, structure I have taken input values for two different Times from the user and have to display the addition of them. I have created a structure and two functions of the structure for Time 1 and Time 2. But, whenever I enter minutes or seconds greater than 70 or 80, the format of the resultant time (Addition of Time 1 and Time 2) does not display in the correct format. Code: #include <iostream> using namespace std; struct time{ int hour; int minute; int seconds; }; time Time1(time); time Time1(time a) { if(a.minute >=60 && a.seconds>=60) { a.minute-=60; a.hour++; a.seconds-=60; a.minute++; } cout<<"Time 1 is: "<<a.hour<<":"<<a.minute<<":"<<a.seconds<<endl; } time Time2(time); time Time2(time b) { if(b.minute >=60 && b.seconds>=60) { b.minute-=60; b.hour++; b.seconds-=60; b.minute++; } cout<<"Time 2 is: "<<b.hour<<":"<<b.minute<<":"<<b.seconds<<endl; } int main() { time t1; time t2; time t3; cout<<"Enter hours: "; cin>>t1.hour; cout<<"Enter minutes: "; cin>>t1.minute; cout<<"Enter seconds: "; cin>>t1.seconds; Time1(t1); cout<<"Enter hours: "; cin>>t2.hour; cout<<"Enter minutes: "; cin>>t2.minute; cout<<"Enter seconds: "; cin>>t2.seconds; Time2(t2); cout<<"Adding Time 1 and Time 2 = "; t3.hour=t1.hour+t2.hour; t3.minute=t1.minute+t2.minute; t3.seconds=t1.seconds+t2.seconds; if(t3.minute >=60) { t3.minute-=60; t3.hour++; } else if(t3.seconds>=60) { t3.seconds-=60; t3.minute++; } cout<<t3.hour<<":"<<t3.minute<<":"<<t3.seconds<<endl; return 0; } Source: Windows Questions C++ LEAVE A COMMENT
__label__pos
0.999528
The below code runs fine the only problem is when I run this code there is a value of "3" in the input textbox which should be null, I have no idea why its doing this any help will be appreciated. THANKS import javax.swing.JOptionPane; //inherits from Monument class---> public class MonumentBase extends Monument { private double baseThickness; private double baseDiameter; public MonumentBase() { super(); baseThickness = super.getThickness(); baseDiameter = super.getWidth(); } public MonumentBase(int quantity) { super(quantity); baseThickness = super.getThickness(); baseDiameter = super.getWidth(); } public MonumentBase(int quantity, double width, double thickness, double height, double baseThickness, double baseDiameter) { super(quantity, width, thickness, height); setBaseThickness(baseThickness); setBaseDiameter(baseDiameter); } public double getBaseDiameter() { return baseDiameter; } public void setBaseDiameter(double diameter) { if (diameter < super.getWidth() || diameter > super.getWidth() + 24) baseDiameter = super.getWidth(); else baseDiameter = diameter; } public double getBaseThickness() { return baseThickness; } public void setBaseThickness(double thickness) { if (thickness < super.getThickness() || thickness > super.getThickness() + 3) baseThickness = super.getThickness(); else baseThickness = thickness; } public double getBaseRadius() { return baseDiameter / 2.0; } @Override public double getCubicInches() { return Math.PI * baseDiameter * baseDiameter * baseThickness * super.getQuantity() * 0.25 + super.getCubicInches(); } @Override public double getCubicFeet() { return this.getCubicInches() / 1728; } public static void main(String args[]) { int selection = 0; Monument order = null; MonumentBase orderBase = null; selection = getSelection(); createOrder(selection); System.exit(0); // GUI closing } /** * Method getSelection to get user input f*/ private static int getSelection() { String stringSelection = " "; int numericSelection = 0; stringSelection = JOptionPane.showInputDialog(null, "Make a Selection\n" + "1: For Default Monument Only Order\n" + "2: For Default MOnument Plus Base Order\n" + "3: Default Monument Only Dimensions >>> Greather Than 5\n" + "4: Defualt Monument and Base Dimensions >>> Greather Than 5\n" + "5: Monument only >>> Enter All Dimensions And Quantity\n" + "6: Monument AND Base >>> Enter All Dimensions And Quantity\n" + "7: EXIT PROGRAM\n" + "Enter 1, 2, 3, 4, 5, 6 or 7 ONLY!", JOptionPane.QUESTION_MESSAGE); numericSelection = Integer.parseInt(stringSelection); return numericSelection; //Return selection } /** * Static method createOrder */ private static void createOrder(int selection) { Monument order = null; MonumentBase orderBase = null; int quantity = 0; double width = 0; double thickness = 0.0; double height = 0.0; double baseThickness = 0.0; double baseDiameter = 0.0; boolean base = false; //Switch statements for selection ----> switch(selection) { case 1: order = new Monument(); break; case 2: orderBase = new MonumentBase(); base = true; break; case 3: quantity = (int)getNumericInput ("Enter Number of Monuments Desired: "); order = new Monument(quantity); break; case 4: quantity = (int)getNumericInput ("Enter Number of Monuments Desired: "); orderBase = new MonumentBase(quantity); base = true; break; case 5: quantity = (int)getNumericInput ("Enter Number of Monuments Desired: "); width = getNumericInput("Enter the Width of Monuments: "); thickness = getNumericInput ("Enter the Thickness of Monuments: "); height = getNumericInput("Enter the Height of Monuments: "); order = new Monument(quantity, width, thickness, height); break; case 6: quantity = (int)getNumericInput ("Enter Number of Monuments Desired: "); width = getNumericInput("Enter the Width of Monuments: "); thickness = getNumericInput ("Enter the Thickness of Monuments: "); height = getNumericInput("Enter the Height of Monuments: "); baseThickness = getNumericInput ("Enter the Thickness of Monument's Bases: "); baseDiameter = getNumericInput ("Enter the Diameter of Monument's Bases: "); orderBase = new MonumentBase (quantity, width, thickness, height, baseThickness, baseDiameter); base = true; break; case 7: JOptionPane.showMessageDialog (null, "EXITING PROGRAM PER USER REQUEST\nTHANK YOU!!", "Message", JOptionPane.INFORMATION_MESSAGE); break; //Switch statements ends here ----> //Degault statement if incorrect choice entered: default: JOptionPane.showMessageDialog (null, "An Incorrect Choice Was Entered\n"+ "Please Re-Run Program", "****ERROR****", JOptionPane.ERROR_MESSAGE); System.exit(1); } //Checking if order contains Base or not: if (base == true) displayOutputBase(orderBase); else displayOutput(order); } //Displays Output for Monument Order ----> private static void displayOutput(Monument order) { if(order.getTotalPrice() > 0) { JOptionPane.showMessageDialog(null, String.format("Number of Monuments: %d\n" + "Width of Monuments: %.2f Inches\n" + "Height of Monuments: %.2f Inches\n" + "Thickness of Monuments: %.2f Inches\n" + "Cubic Inches of WunderRock Required: %.2f\n" + "Cubic Feet of WunderRock Required: %.2f\n" + "Retail Price of Order: $%.2f", order.getQuantity(), order.getWidth(), order.getHeight(), order.getThickness(), order.getCubicInches(), order.getCubicFeet(), order.getTotalPrice()), "ORDER SPECIFICATIONS", JOptionPane.INFORMATION_MESSAGE); } // Message if error while placing order: else JOptionPane.showMessageDialog(null, "*****Order Contains Errors*****" + "\n*****Do Not Process!*****", "*****ERROR*****", JOptionPane.ERROR_MESSAGE); } //Display Output for MonumentBase Order ---> private static void displayOutputBase(MonumentBase order) { if(order.getTotalPrice() > 0) { JOptionPane.showMessageDialog(null, String.format("Number of Monuments: %d\n" + "Width of Monuments: %.2f Inches\n" + "Height of Monuments: %.2f Inches\n" + "Thickness of Monuments: %.2f Inches\n" + "Radius of Base: %.2f Inches\n" + "Diameter of Base: %.2f Inches\n" + "Thickness of Base: %.2f Inches\n" + "Cubic Inches of WunderRock Required: %.2f\n" + "Cubic Feet of WunderRock Required: %.2f\n" + "Retail Price of Order: $%.2f", order.getQuantity(), order.getWidth(), order.getHeight(), order.getThickness(), order.getBaseRadius(), order.getBaseDiameter(), order.getBaseThickness(), order.getCubicInches(), order.getCubicFeet(), order.getTotalPrice()), "ORDER SPECIFICATIONS", JOptionPane.INFORMATION_MESSAGE); } //Error while placing MonumentBase Order ---> else JOptionPane.showMessageDialog (null, "*****Order Contains Errors*****" + "\n*****Do Not Process!*****", "*****ERROR*****", JOptionPane.ERROR_MESSAGE); } private static double getNumericInput(String prompt) { return Double.parseDouble(JOptionPane.showInputDialog (null, prompt)); } } I can't find a TextBox or jTextBox in there. what field are we talking about? I'm sorry it's not textbox but JOptionPane which shows user a list and asks to make a choice, there should be no value in it but when you run the code there is value of "3" which is choice 3 already present in it. Below is the code for it, thank you for your reply public static void main(String args[]) { int selection = 0; Monument order = null; MonumentBase orderBase = null; selection = getSelection(); createOrder(selection); System.exit(0); // GUI closing } /** * Method getSelection to get user input f*/ private static int getSelection() { String stringSelection = " "; int numericSelection = 0; stringSelection = JOptionPane.showInputDialog(null, "Make a Selection\n" + "1: For Default Monument Only Order\n" + "2: For Default MOnument Plus Base Order\n" + "3: Default Monument Only Dimensions >>> Greather Than 5\n" + "4: Defualt Monument and Base Dimensions >>> Greather Than 5\n" + "5: Monument only >>> Enter All Dimensions And Quantity\n" + "6: Monument AND Base >>> Enter All Dimensions And Quantity\n" + "7: EXIT PROGRAM\n" + "Enter 1, 2, 3, 4, 5, 6 or 7 ONLY!", JOptionPane.QUESTION_MESSAGE); numericSelection = Integer.parseInt(stringSelection); return numericSelection; //Return selection You are passing JOptionPane.QUESTION_MESSAGE (which is a final static int in the JOptionPane class) as parameter where JOptionPane expects the input that you want as default. change your JOptionPane to: stringSelection = JOptionPane.showInputDialog(null, "Make a Selection\n" + "1: For Default Monument Only Order\n" + "2: For Default MOnument Plus Base Order\n" + "3: Default Monument Only Dimensions >>> Greather Than 5\n" + "4: Defualt Monument and Base Dimensions >>> Greather Than 5\n" + "5: Monument only >>> Enter All Dimensions And Quantity\n" + "6: Monument AND Base >>> Enter All Dimensions And Quantity\n" + "7: EXIT PROGRAM\n" + "Enter 1, 2, 3, 4, 5, 6 or 7 ONLY!","", JOptionPane.QUESTION_MESSAGE); the difference is in the last line Thank you so much Problem solved!! That was the dump mistake made by me :P stringSelection = JOptionPane.showInputDialog(null, "Make a Selection\n" + "1: For Default Monument Only Order\n" + "2: For Default MOnument Plus Base Order\n" + "3: Default Monument Only Dimensions >>> Greather Than 5\n" + "4: Defualt Monument and Base Dimensions >>> Greather Than 5\n" + "5: Monument only >>> Enter All Dimensions And Quantity\n" + "6: Monument AND Base >>> Enter All Dimensions And Quantity\n" + "7: EXIT PROGRAM\n" + "Enter 1, 2, 3, 4, 5, 6 or 7 ONLY!","", JOptionPane.QUESTION_MESSAGE); numericSelection = Integer.parseInt(stringSelection); return numericSelection; //Return selection
__label__pos
0.996765
Logo ROOT   Reference Guide TSynapse.cxx Go to the documentation of this file. 1// @(#)root/mlp:$Id$ 2// Author: [email protected] 21/08/2002 3 4/************************************************************************* 5 * Copyright (C) 1995-2003, Rene Brun and Fons Rademakers. * 6 * All rights reserved. * 7 * * 8 * For the licensing terms see $ROOTSYS/LICENSE. * 9 * For the list of contributors see $ROOTSYS/README/CREDITS. * 10 *************************************************************************/ 11 12/** \class TSynapse 13 14This is a simple weighted bidirectional connection between 15two neurons. 16A network is built connecting two neurons by a synapse. 17In addition to the value, the synapse can return the DeDw 18 19*/ 20 21#include "TSynapse.h" 22#include "TNeuron.h" 23#include "Riostream.h" 24 26 27//////////////////////////////////////////////////////////////////////////////// 28/// Default constructor 29 31{ 32 fpre = 0; 33 fpost = 0; 34 fweight = 1; 35 fDEDw = 0; 36} 37 38//////////////////////////////////////////////////////////////////////////////// 39/// Constructor that connects two neurons 40 42{ 43 fpre = pre; 44 fpost = post; 45 fweight = w; 46 fDEDw = 0; 47 pre->AddPost(this); 48 post->AddPre(this); 49} 50 51//////////////////////////////////////////////////////////////////////////////// 52/// Sets the pre-neuron 53 55{ 56 if (fpre) { 57 Error("SetPre","this synapse is already assigned to a pre-neuron."); 58 return; 59 } 60 fpre = pre; 61 pre->AddPost(this); 62} 63 64//////////////////////////////////////////////////////////////////////////////// 65/// Sets the post-neuron 66 68{ 69 if (fpost) { 70 Error("SetPost","this synapse is already assigned to a post-neuron."); 71 return; 72 } 73 fpost = post; 74 post->AddPre(this); 75} 76 77//////////////////////////////////////////////////////////////////////////////// 78/// Returns the value: weighted input 79 81{ 82 if (fpre) 83 return (fweight * fpre->GetValue()); 84 return 0; 85} 86 87//////////////////////////////////////////////////////////////////////////////// 88/// Computes the derivative of the error wrt the synapse weight. 89 91{ 92 if (!(fpre && fpost)) 93 return 0; 94 return (fpre->GetValue() * fpost->GetDeDw()); 95} 96 97//////////////////////////////////////////////////////////////////////////////// 98/// Sets the weight of the synapse. 99/// This weight is the multiplying factor applied on the 100/// output of a neuron in the linear combination given as input 101/// of another neuron. 102 104{ 105 fweight = w; 106} 107 108//////////////////////////////////////////////////////////////////////////////// 109/// Sets the derivative of the total error wrt the synapse weight 110 112{ 113 fDEDw = in; 114} 115 116 double Double_t Definition: RtypesCore.h:55 #define ClassImp(name) Definition: Rtypes.h:365 This class describes an elementary neuron, which is the basic element for a Neural Network. Definition: TNeuron.h:25 Double_t GetValue() const Computes the output using the appropriate function and all the weighted inputs, or uses the branch as... Definition: TNeuron.cxx:946 Double_t GetDeDw() const Computes the derivative of the error wrt the neuron weight. Definition: TNeuron.cxx:1082 void AddPost(TSynapse *) Adds a synapse to the neuron as an output This method is used by the TSynapse while connecting two ne... Definition: TNeuron.cxx:844 void AddPre(TSynapse *) Adds a synapse to the neuron as an input This method is used by the TSynapse while connecting two neu... Definition: TNeuron.cxx:832 virtual void Error(const char *method, const char *msgfmt,...) const Issue error message. Definition: TObject.cxx:880 This is a simple weighted bidirectional connection between two neurons. Definition: TSynapse.h:20 TNeuron * fpre the neuron before the synapse Definition: TSynapse.h:37 void SetPre(TNeuron *pre) Sets the pre-neuron. Definition: TSynapse.cxx:54 Double_t GetDeDw() const Computes the derivative of the error wrt the synapse weight. Definition: TSynapse.cxx:90 TNeuron * fpost the neuron after the synapse Definition: TSynapse.h:38 void SetPost(TNeuron *post) Sets the post-neuron. Definition: TSynapse.cxx:67 Double_t fDEDw ! the derivative of the total error wrt the synapse weight Definition: TSynapse.h:40 Double_t fweight the weight of the synapse Definition: TSynapse.h:39 void SetWeight(Double_t w) Sets the weight of the synapse. Definition: TSynapse.cxx:103 Double_t GetValue() const Returns the value: weighted input. Definition: TSynapse.cxx:80 void SetDEDw(Double_t in) Sets the derivative of the total error wrt the synapse weight. Definition: TSynapse.cxx:111 TSynapse() Default constructor. Definition: TSynapse.cxx:30
__label__pos
0.635709
I am really confused by this problem. PLEASE HELP Write a program that reads a set of floating point data values from the input. When the user indicates the end of the input, print out the count if the values, the average, and the standard deviation. The average of a data set is x1,......,xn is t = Σxi/n where Σx1 = x1+...+xn is the sum of the input values. The standard deviation is: s=Math.sqrt(Σxi^2 - (1/n)*(Σxi)^2/n-1) my professor asks me to Create a method in the class Mymath to print out the count of values, the average, and the standard deviation. Use the numerically less stable formula to find the standard deviation. and this is what the output should be: 1 2 3 4 5 6 -1 Count of values: 6 Average: 3.50 Standard Deviation: 1.87 So which part are you confused about? Reading in the values? Calculating the formulas? The formulas are standard formulas, so if you don't get them, just look up those terms on google and you'll find plenty of explanations. Your professor didn't make those up. And to read in the values, you can make a Scanner. Test each value read in; if it is -1, stop reading in values, and do not include the -1 value in your calculations. So you'll basically be using a while loop to read in all the values, then adding them to an ArrayList<Integer>. im just confused on how to do it. i guess i need a jump start thats all. 1. Get the count 2. Calculate the sum 3. From the count and the sum, calculate the average. 4. From the average, get each deviation (error). 5. Square each deviation (squared error). 6. Add up the squares (sum of squared errors). 7. Divide by (count - 1) (mean squared error. count - 1 is degrees of freedom). 8. Take the square root. 9. You now have the standard deviation. Slightly different formula/method than the one you listed, but if you do some math, I imagine you'll find that they are equivalent and will give identical results. Edited 7 Years Ago by VernonDozier: n/a WRIGHT A PROGRAM IN C WHICH REQUEST SCORES STORES THEM IN AN ARRAY , THEN IT CALCULATES THE MEAN, Deviations FROM MEAN, STD DEVIATION AND THEN IT PRINTS THE THREE(MEAN, AVERAGE, DEVIATIONS, STD DEVIATION.) WRIGHT A PROGRAM IN C WHICH REQUEST SCORES STORES THEM IN AN ARRAY , THEN IT CALCULATES THE MEAN, Deviations FROM MEAN, STD DEVIATION AND THEN IT PRINTS THE THREE(MEAN, AVERAGE, DEVIATIONS, STD DEVIATION.) Don't yell( meaning don't use capitals) we are not DEAF. Also start a new thread. Also this is a java forum not a C forum. Also post some code. Don't expect someone to give you the answer. If you don't know where to start, explain specifically what is your problem On Nov. 7th VernonDozier has clearly and correctly indicated the steps in writing a code to calculate. Please following the instruction write your own program. This article has been dead for over six months. Start a new discussion instead.
__label__pos
0.941315
Struct std::time::Duration1.3.0[][src] pub struct Duration { /* fields omitted */ } A Duration type to represent a span of time, typically used for system timeouts. Each Duration is composed of a whole number of seconds and a fractional part represented in nanoseconds. If the underlying system does not support nanosecond-level precision, APIs binding a system timeout will typically round up the number of nanoseconds. Durations implement many common traits, including Add, Sub, and other ops traits. Examples use std::time::Duration; let five_seconds = Duration::new(5, 0); let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5); assert_eq!(five_seconds_and_five_nanos.as_secs(), 5); assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5); let ten_millis = Duration::from_millis(10);Run Methods impl Duration [src] Creates a new Duration from the specified number of whole seconds and additional nanoseconds. If the number of nanoseconds is greater than 1 billion (the number of nanoseconds in a second), then it will carry over into the seconds provided. Panics This constructor will panic if the carry from the nanoseconds overflows the seconds counter. Examples use std::time::Duration; let five_seconds = Duration::new(5, 0);Run Creates a new Duration from the specified number of whole seconds. Examples use std::time::Duration; let duration = Duration::from_secs(5); assert_eq!(5, duration.as_secs()); assert_eq!(0, duration.subsec_nanos());Run Creates a new Duration from the specified number of milliseconds. Examples use std::time::Duration; let duration = Duration::from_millis(2569); assert_eq!(2, duration.as_secs()); assert_eq!(569_000_000, duration.subsec_nanos());Run Creates a new Duration from the specified number of microseconds. Examples use std::time::Duration; let duration = Duration::from_micros(1_000_002); assert_eq!(1, duration.as_secs()); assert_eq!(2000, duration.subsec_nanos());Run Creates a new Duration from the specified number of nanoseconds. Examples use std::time::Duration; let duration = Duration::from_nanos(1_000_000_123); assert_eq!(1, duration.as_secs()); assert_eq!(123, duration.subsec_nanos());Run Returns the number of whole seconds contained by this Duration. The returned value does not include the fractional (nanosecond) part of the duration, which can be obtained using subsec_nanos. Examples use std::time::Duration; let duration = Duration::new(5, 730023852); assert_eq!(duration.as_secs(), 5);Run To determine the total number of seconds represented by the Duration, use as_secs in combination with subsec_nanos: use std::time::Duration; let duration = Duration::new(5, 730023852); assert_eq!(5.730023852, duration.as_secs() as f64 + duration.subsec_nanos() as f64 * 1e-9);Run Returns the fractional part of this Duration, in milliseconds. This method does not return the length of the duration when represented by milliseconds. The returned number always represents a fractional portion of a second (i.e. it is less than one thousand). Examples use std::time::Duration; let duration = Duration::from_millis(5432); assert_eq!(duration.as_secs(), 5); assert_eq!(duration.subsec_millis(), 432);Run Returns the fractional part of this Duration, in microseconds. This method does not return the length of the duration when represented by microseconds. The returned number always represents a fractional portion of a second (i.e. it is less than one million). Examples use std::time::Duration; let duration = Duration::from_micros(1_234_567); assert_eq!(duration.as_secs(), 1); assert_eq!(duration.subsec_micros(), 234_567);Run Returns the fractional part of this Duration, in nanoseconds. This method does not return the length of the duration when represented by nanoseconds. The returned number always represents a fractional portion of a second (i.e. it is less than one billion). Examples use std::time::Duration; let duration = Duration::from_millis(5010); assert_eq!(duration.as_secs(), 5); assert_eq!(duration.subsec_nanos(), 10_000_000);Run Checked Duration addition. Computes self + other, returning None if overflow occurred. Examples Basic usage: use std::time::Duration; assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1))); assert_eq!(Duration::new(1, 0).checked_add(Duration::new(std::u64::MAX, 0)), None);Run Checked Duration subtraction. Computes self - other, returning None if the result would be negative or if overflow occurred. Examples Basic usage: use std::time::Duration; assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1))); assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);Run Checked Duration multiplication. Computes self * other, returning None if overflow occurred. Examples Basic usage: use std::time::Duration; assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2))); assert_eq!(Duration::new(std::u64::MAX - 1, 0).checked_mul(2), None);Run Checked Duration division. Computes self / other, returning None if other == 0. Examples Basic usage: use std::time::Duration; assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0))); assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000))); assert_eq!(Duration::new(2, 0).checked_div(0), None);Run Trait Implementations impl DivAssign<u32> for Duration 1.9.0 [src] Performs the /= operation. impl MulAssign<u32> for Duration 1.9.0 [src] Performs the *= operation. impl SubAssign<Duration> for Duration 1.9.0 [src] Performs the -= operation. impl AddAssign<Duration> for Duration 1.9.0 [src] Performs the += operation. impl<'a> Sum<&'a Duration> for Duration 1.16.0 [src] Method which takes an iterator and generates Self from the elements by "summing up" the items. Read more impl Sum<Duration> for Duration 1.16.0 [src] Method which takes an iterator and generates Self from the elements by "summing up" the items. Read more impl Debug for Duration [src] Formats the value using the given formatter. Read more impl Sub<Duration> for Duration [src] The resulting type after applying the - operator. Performs the - operation. impl Clone for Duration [src] Returns a copy of the value. Read more Performs copy-assignment from source. Read more impl PartialOrd<Duration> for Duration [src] This method returns an ordering between self and other values if one exists. Read more This method tests less than (for self and other) and is used by the < operator. Read more This method tests less than or equal to (for self and other) and is used by the <= operator. Read more This method tests greater than (for self and other) and is used by the > operator. Read more This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more impl Ord for Duration [src] This method returns an Ordering between self and other. Read more Compares and returns the maximum of two values. Read more Compares and returns the minimum of two values. Read more impl Copy for Duration [src] impl Eq for Duration [src] impl PartialEq<Duration> for Duration [src] This method tests for self and other values to be equal, and is used by ==. Read more This method tests for !=. impl Mul<u32> for Duration [src] The resulting type after applying the * operator. Performs the * operation. impl Hash for Duration [src] Feeds this value into the given [Hasher]. Read more Feeds a slice of this type into the given [Hasher]. Read more impl Default for Duration [src] Returns the "default value" for a type. Read more impl Div<u32> for Duration [src] The resulting type after applying the / operator. Performs the / operation. impl Add<Duration> for Duration [src] The resulting type after applying the + operator. Performs the + operation. impl Add<Duration> for Instant 1.8.0 [src] The resulting type after applying the + operator. Performs the + operation. impl AddAssign<Duration> for Instant 1.9.0 [src] Performs the += operation. impl Sub<Duration> for Instant 1.8.0 [src] The resulting type after applying the - operator. Performs the - operation. impl SubAssign<Duration> for Instant 1.9.0 [src] Performs the -= operation. impl Add<Duration> for SystemTime 1.8.0 [src] The resulting type after applying the + operator. Performs the + operation. impl AddAssign<Duration> for SystemTime 1.9.0 [src] Performs the += operation. impl Sub<Duration> for SystemTime 1.8.0 [src] The resulting type after applying the - operator. Performs the - operation. impl SubAssign<Duration> for SystemTime 1.9.0 [src] Performs the -= operation. Auto Trait Implementations impl Send for Duration impl Sync for Duration
__label__pos
0.665787
专栏首页coding for love5-4 使用 webpack-dev-server 实现请求转发 5-4 使用 webpack-dev-server 实现请求转发 1. 简介 请求转发,其实是使用 webpack-dev-server 的代理功能来实现的,本节为大家介绍 webpack-dev-server 的代理功能和主要使用场景。 2. 正向代理与反向代理 在进入正题之前,先简单地先介绍一下什么是代理,字面意义上理解就是委托第三方处理有关事务。网络代理分为正向代理和反向代理,所谓正向代理就是顺着请求的方向进行的代理,即代理服务器他是由你配置为你服务,去请求目标服务器地址。反向代理正好与正向代理相反,代理服务器是为目标服务器服务的。虽然整体的请求返回路线都是一样的都是 Client 到 Proxy 到 Server。 webpack-dev-server 的代理功能更偏向于正向代理,即是为前端开发者服务的。 3. 页面准备和接口请求 我们在项目中,新建如下文件: // webpack.common.js var HtmlWebpackPlugin = require('html-webpack-plugin'); var { CleanWebpackPlugin } = require('clean-webpack-plugin'); var path = require('path'); module.exports = { entry: { index: "./src/index.jsx", }, output: { path: path.resolve(__dirname, '../dist'), filename: "[name].js" }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node-modules/, use: 'babel-loader' }, { test: /\.(jpg|jpeg|png|gif)$/, use: { loader: 'url-loader', options: { name: '[name].[ext]', limit: 2048 } } }, { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] }, { test: /\.scss$/, use: [ 'style-loader', 'css-loader', 'postcss-loader', 'sass-loader', ] }, { test: /\.(eot|svg|ttf|woff)$/, use: 'file-loader' } ] }, plugins: [ new HtmlWebpackPlugin({ template: "./src/index.html" }), new CleanWebpackPlugin() ] }; // webpack.dev.js var path = require('path'); var webpack = require('webpack'); var merge = require('webpack-merge'); var commonConfig = require('./webpack.common'); var devConfig = { mode: 'development', devtool: "cheap-module-eval-source-map", devServer: { contentBase: path.resolve(__dirname, 'dist'), open: true, port: 3000, hot: true // 开启热更新 }, plugins: [ new webpack.HotModuleReplacementPlugin() ] }; module.exports = merge(commonConfig, devConfig); // webpack.prod.js var merge = require('webpack-merge'); var commonConfig = require('./webpack.common'); var prodConfig = { mode: 'production', devtool: "cheap-module-source-map", }; module.exports = merge(commonConfig, prodConfig); // src/index.js // src/index.js import React, { Component } from 'react'; import ReactDom from 'react-dom'; import axios from 'axios'; class App extends Component { constructor() { super(); this.state = {}; } componentDidMount() { axios.get('http://127.0.0.1:3600/api/hello.json').then(res => { console.log(res) this.setState({ msg: res.data.msg }) }).catch(e => { console.error(e); }) } render() { return <div>{this.state.msg}</div> } } ReactDom.render(<App />, document.getElementById('root')); <!--src/index.html--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>esmodule-oop</title> </head> <body> <div id="root"></div> </body> </html> .babelrc: { "presets": [ [ "@babel/preset-env", { "corejs": 2, "useBuiltIns": "usage" } ], "@babel/preset-react" ] } "scripts": { "dev": "webpack --config ./build/webpack.dev.js --watch", "dev-analyse": "webpack --config ./build/webpack.dev.js --profile --json > stas.json", "build-analyse": "webpack --config ./build/webpack.prod.js --profile --json > stas.json", "dev-server": "webpack-dev-server --config ./build/webpack.dev.js", "build": "webpack --config ./build/webpack.prod.js" }, 3. 接口准备 这里就不用 node 写 server 了,直接 http-server 起一个简单的服务。运行 npm run build,然后在 dist 下新建如下文件: api/hello.json { "msg": "hello world" } 进入 dist,使用 http-server -p 3600 开启服务,访问 http://127.0.0.1:3600 image.png 4. 代理请求 但是我们部署的服务可能会改变地址(先上来讲是域名),另外,在开发环境的时候,我们的后台接口可能还没有开发完成,需要我们访问其他的开发地址或者测试地址。那该怎么做呢?一个最容易想到的方案就是将域名配置到统一的地方,一处更改,多处生效。比如我们封装一层请求,request,为其配置 host,每次请求的时候自动加上 host。我们的代码中只要写相对路径即可: request.get('/api/hello.json') 但其实 webpack dev-server 为我们提供了方便地配置。一般为了防止跨域,我们会将静态资源和接口资源部署在同一个服务下,比如上面的 dist 下面加一个 api 目录,当然实际可能并不是这样,比如使用了反向代理等。在代码中我们写相对地址即可: axios.get('/api/hello.json') 如果仅仅这样写,那么代码请求的始终是当前服务下的 api/hello,每次修改代码,需要部署之后才能生效。这显然是不可能的。我们关闭之前的服务,新建一个文件:server/api/hello.json,进入 server 使用 3000 端口重新开启服务。 然后我们使用 dev-server 开启服务:npm run dev-server image.png 可以看到, 请求的是 3600 端口下的接口,但是我们这里的 dev-server 仅提供了页面资源,并没有接口资源,接口资源在线上(这里用 3000 端口代替)。 这时候就要使用上述我们提到的代理了: devServer: { contentBase: path.resolve(__dirname, 'dist'), open: true, port: 3000, hot: true,// 开启热更新 proxy: { '/api': 'http://127.0.0.1:3000' } }, 重新运行 npm run dev-server,如下: image.png 4. 跨域 有的人会想,那这样做其实和在源码中通过配置去写也是一样的呀,只要最终达到以下效果就可以了: axios.get('http://127.0.0.1:3600/api/hello.json').then(res => { console.log(res) this.setState({ msg: res.data.msg }) }).catch(e => { console.error(e); }) 那么我们代码作如上改写,关闭代理后,npm run dev-server 看看: image.png 打开 console: image.png 可以看到,报了跨域。这是因为浏览器现代浏览器的同源安全策略,禁止跨域发送请求。而 proxy 是通过一个代理服务器帮我们转发请求,不受浏览器的跨域限制。但其实对于很多后端服务,出于安全考虑,我们也会做跨域限制,这时候接口就无法正常返回数据呢。对于这种情况,我们可以使用 changeOrigin 来解决: 我们把请求地址改回相对地址,然后修改 proxy 配置如下: proxy: { '/api': { target: 'http://127.0.0.1:3600', changeOrigin: true } } 就可以帮我们解决接口跨域问题了。 5. 重写路径 有时候,我们会遇到路径不一致的场景,比如我们本来是请求 hello 接口的,但这个接口正在开发中,后端可能丢了一个 demo 接口让我们先用,还有的时候我们的生产接口可能放在 api 下面,但是测试接口并没有这一层路径,这时候我们就可以通过重写路径来保证访问地址的正确性: module.exports = { //... devServer: { proxy: { '/api': { target: 'http://localhost:3600', pathRewrite: {'^/api' : ''} } } } }; 6. 过滤 有时你不想代理所有的请求。可以基于一个函数的返回值绕过代理。 在函数中你可以访问请求体、响应体和代理选项。必须返回 false 或路径,来跳过代理请求。 例如:对于浏览器请求,你想要提供一个 HTML 页面,但是对于 API 请求则保持代理。你可以这样做: proxy: { "/api": { target: "http://localhost:3000", bypass: function(req, res, proxyOptions) { if (req.headers.accept.indexOf("html") !== -1) { console.log("Skipping proxy for browser request."); return "/index.html"; } } } } 1. 代理多个路径 如果你想要代码多个路径代理到同一个target下, 你可以使用由一个或多个「具有 context 属性的对象」构成的数组: proxy: [{ context: ["/auth", "/api"], target: "http://localhost:3000", }] 8. 使用 https 默认情况下,不接受运行在 HTTPS 上,且使用了无效证书的后端服务器。如果你想要接受,修改配置如下: proxy: { "/api": { target: "https://other-server.example.com", secure: false } } 9. 小结 proxy 的配置相当丰富,甚至还可以帮我们修改 header,携带 cookie 等。这些都让我们能在不修改源码的情况下通过简单的配置即可做到,远远优于直接手动在源码进行修改的方法,极大方便了我们的开发。 参考 正向代理与反向代理的区别 https://webpack.js.org/configuration/dev-server/#devserverproxy https://www.webpackjs.com/configuration/dev-server/#devserver-proxy Webpack-dev-server的proxy用法 本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。 我来说两句 0 条评论 登录 后参与评论 相关文章 • CSS进阶08-绝对定位 Absolute Positioning (注1:如果有问题欢迎留言探讨,一起学习!转载请注明出处,喜欢可以点个赞哦!) (注2:更多内容请查看我的目录。) love丁酥酥 • 2-3 webpack的正确安装方式 webpack是基于node开发的环境打包工具。首先需要安装node环境。 进入node官网,尽量安装最新版本的稳定版node。因为提高webpack打包速度... love丁酥酥 • 3-8 使用 WebpackdevServer 提升开发效率 webpack-dev-server 是 webpack 集成的开发者服务器,用于帮助开发者快速开发应用程序。 love丁酥酥 • webpack学习(三)—— webpack-dev-server 这两种模式都支持Hot Module Replacement(热加载),所谓热加载是指当文件发生变化后,内存中的bundle文件会收到通知,同时更新页面中变化的... 前端博客 : alili.tech • 入职第一天:leader手把手教我入门Vue服务器端渲染(SSR) 今天是我入职第一天,在简短的内部培训了一上午后,前端leader让我先了解下什么是vue的服务器端渲染(SSR)。 闰土大叔 • 入职第一天:前端leader手把手教我入门Vue服务器端渲染(SSR) 继前段时间西安电面之后顺利拿到了OFFER,今天(5月2号)是我入职第一天,在简短的内部培训了一上午后,前端leader让我先了解下什么是vue的服务器端渲染(... 前端博客 : alili.tech • 分布式协调服务ZooKeeper工作原理 大数据处理框架Hadoop、Redis分布式服务Codis、淘宝的分布式消息中间件MetaMQ …… 他们都使用ZooKeeper做为基础部件,可以看出ZooK... dys • 代码体积减少80%!Taro H5转换与优化升级 作为一个多端开发框架,Taro从项目发起时就已经支持编译到H5端。随着Taro 多端能力的不断成熟,对 Taro H5 端应用的要求也不断提升,已经不再满足于“... 京东技术 • 新一代企业应用平台的探究(上):只拿干货说话 魏新宇 • Python骚操作,利用python更改室友电脑开机秘密,只需几步! 今天教大家用Python脚本来控制小伙伴们Windows电脑的开机密码。没错就是神不知鬼不觉,用random()随机生成的密码,只有你自己知道哦~ python学习教程 扫码关注云+社区 领取腾讯云代金券
__label__pos
0.901547
/[gentoo-x86]/eclass/autotools-multilib.eclass Gentoo Contents of /eclass/autotools-multilib.eclass Parent Directory Parent Directory | Revision Log Revision Log Revision 1.23 - (show annotations) (download) Fri May 2 16:16:37 2014 UTC (12 months ago) by mgorny Branch: MAIN CVS Tags: HEAD Changes since 1.22: +1 -9 lines Run multilib_src_configure() in parallel. Bug #485046. 1 # Copyright 1999-2014 Gentoo Foundation 2 # Distributed under the terms of the GNU General Public License v2 3 # $Header: /var/cvsroot/gentoo-x86/eclass/autotools-multilib.eclass,v 1.22 2014/04/30 18:17:19 mgorny Exp $ 4 5 # @ECLASS: autotools-multilib.eclass 6 # @MAINTAINER: 7 # gx86-multilib team <[email protected]> 8 # @AUTHOR: 9 # Author: Michał Górny <[email protected]> 10 # @BLURB: autotools-utils wrapper for multilib builds 11 # @DESCRIPTION: 12 # The autotools-multilib.eclass provides a glue between 13 # autotools-utils.eclass(5) and multilib-minimal.eclass(5), aiming 14 # to provide a convenient way to build packages using autotools 15 # for multiple ABIs. 16 # 17 # Inheriting this eclass sets IUSE and exports default multilib_src_*() 18 # sub-phases that call autotools-utils phase functions for each ABI 19 # enabled. The multilib_src_*() functions can be defined in ebuild just 20 # like in multilib-minimal. 21 22 # EAPI=4 is required for meaningful MULTILIB_USEDEP. 23 case ${EAPI:-0} in 24 4|5) ;; 25 *) die "EAPI=${EAPI} is not supported" ;; 26 esac 27 28 inherit autotools-utils eutils multilib-build multilib-minimal 29 30 EXPORT_FUNCTIONS src_prepare src_configure src_compile src_test src_install 31 32 # Note: _at_args[@] passing is a backwards compatibility measure. 33 # Don't use it in new packages. 34 35 autotools-multilib_src_prepare() { 36 autotools-utils_src_prepare "${@}" 37 38 [[ ${AUTOTOOLS_IN_SOURCE_BUILD} ]] && multilib_copy_sources 39 } 40 41 multilib_src_configure() { 42 [[ ${AUTOTOOLS_IN_SOURCE_BUILD} ]] && local ECONF_SOURCE=${BUILD_DIR} 43 autotools-utils_src_configure "${_at_args[@]}" 44 } 45 46 autotools-multilib_src_configure() { 47 local _at_args=( "${@}" ) 48 49 multilib-minimal_src_configure 50 } 51 52 multilib_src_compile() { 53 emake "${_at_args[@]}" 54 } 55 56 autotools-multilib_src_compile() { 57 local _at_args=( "${@}" ) 58 59 multilib-minimal_src_compile 60 } 61 62 multilib_src_test() { 63 autotools-utils_src_test "${_at_args[@]}" 64 } 65 66 autotools-multilib_src_test() { 67 local _at_args=( "${@}" ) 68 69 multilib-minimal_src_test 70 } 71 72 multilib_src_install() { 73 emake DESTDIR="${D}" "${_at_args[@]}" install 74 } 75 76 multilib_src_install_all() { 77 einstalldocs 78 79 # Remove libtool files and unnecessary static libs 80 local prune_ltfiles=${AUTOTOOLS_PRUNE_LIBTOOL_FILES} 81 if [[ ${prune_ltfiles} != none ]]; then 82 prune_libtool_files ${prune_ltfiles:+--${prune_ltfiles}} 83 fi 84 } 85 86 autotools-multilib_src_install() { 87 local _at_args=( "${@}" ) 88 89 multilib-minimal_src_install 90 }   ViewVC Help Powered by ViewVC 1.1.20  
__label__pos
0.947454
Outlook VBA, moving completed to Archive Im trying to write some code, to scan through my inbox folders, and anything I have ticked to be completed, move into my archive folder. Problem is, I cant seem to get it past the line:- Set myInputFolder = myInbox.Folders(GetFolder(Mid(srcFolder, InStr(Mid(srcFolder, 3), "\") + 3))) Which should just be saying what folder its scanning, in the first case 'Inbox'. Any ideas? Sub ArchiveCompleted() SearchFolder GetFolder("Mailbox\Inbox"), "Archive 2009" End Sub Sub SearchFolder(olkFolder As Outlook.MAPIFolder, destPST As String) Dim olkSubfolder As Outlook.MAPIFolder For Each olkSubfolder In olkFolder.Folders SearchFolder olkSubfolder, destPST MoveItems olkFolder.FolderPath, destPST & Mid(olkSubfolder.FolderPath, InStr(3, olkSubfolder.FolderPath, "\")) Next Set olkSubfolder = Nothing End Sub Sub MoveItems(srcFolder As String, desFolder As String) Dim myolAPP As New Outlook.Application Dim myNameSpace As Outlook.NameSpace Dim myInbox As Outlook.MAPIFolder Dim myInputFolder As Outlook.MAPIFolder Dim myDestFolder As Outlook.MAPIFolder Dim myItems As Outlook.Items Dim myItem As Outlook.MailItem Dim Item As Outlook.MailItem Set myNameSpace = myolAPP.GetNamespace("MAPI") Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox) 'MsgBox Mid(srcFolder, InStr(Mid(srcFolder, 3), "\") + 3) 'Set myInputFolder = myInbox.Folder Set myInputFolder = myInbox.Folders(Mid(srcFolder, InStr(Mid(srcFolder, 3), "\") + 3)) Set myDestFolder = GetFolder(desFolder) Set myItems = myInputFolder.Items While myItems.Count > 0 For Each Item In myItems If Not IsNull(Item.FlagRequest) Then Item.Move myDestFolder End If Next Set myItems = myInputFolder.Items Wend End Sub Public Function GetFolder(strFolderPath As String) As MAPIFolder Dim objApp As Outlook.Application Dim objNS As Outlook.NameSpace Dim colFolders As Outlook.Folders Dim objFolder As Outlook.MAPIFolder Dim arrFolders() As String Dim I As Long On Error Resume Next strFolderPath = Replace(strFolderPath, "/", "\") arrFolders() = Split(strFolderPath, "\") Set objApp = CreateObject("Outlook.Application") Set objNS = objApp.GetNamespace("MAPI") Set objFolder = objNS.Folders.Item(arrFolders(0)) If Not objFolder Is Nothing Then For I = 1 To UBound(arrFolders) Set colFolders = objFolder.Folders Set objFolder = Nothing Set objFolder = colFolders.Item(arrFolders(I)) If objFolder Is Nothing Then Exit For End If Next End If Set GetFolder = objFolder Set colFolders = Nothing Set objNS = Nothing Set objApp = Nothing End Function Open in new window tonelm54Asked: Who is Participating?   David LeeConnect With a Mentor Commented: Hi, tonelm54. Some of that code looks like something I might have written at some point.  Here's a simpler approach to what you've said you want to accomplish.  This code searches through the inbox and all folders below it for items marked as complete.  Complete in this case means that the item has been flagged as complete.  All items so marked are moved to the archive folder.  Follow these instructions to use this. 1.  Start Outlook 2.  Click Tools > Macro > Visual Basic Editor 3.  If not already expanded, expand Microsoft Office Outlook Objects 4.  If not already expanded, expand Modules 5.  Select an existing module (e.g. Module1) by double-clicking on it or create a new module by right-clicking Modules and selecting Insert > Module. 6.  Copy the code from the Code Snippet box and paste it into the right-hand pane of Outlook's VB Editor window 7.  Edit the code as needed.  I included comments wherever something needs to or can change 8.  Click the diskette icon on the toolbar to save the changes 9.  Close the VB Editor Run the macro ArchiveCompleted. Private olkArchiveFolder As Outlook.MAPIFolder Sub ArchiveCompleted() 'Change the folder path on the next line to that of your archive file and the folder you want the items to be filed in' Set olkArchiveFolder = OpenOutlookFolder("Personal Folders\Completed Items) ProcessFolder Outlook.Application.Session.GetDefaultFolder(olFolderInbox) End Sub Sub ProcessFolder(olkFolder As Outlook.MAPIFolder) Dim olkSubfolder As Outlook.MAPIFolder, olkItem As Object, intCount As Integer For intCount = olkFolder.Items.Count To 1 Step -1 Set olkItem = olkFolder.Items.Item(intCount) If olkItem.FlagStatus = olFlagComplete Then olkItem.Move olkArchiveFolder End If Next For Each olkSubfolder In olkFolder.Folders ProcessFolder olkSubfolder Next Set olkSubfolder = Nothing End Sub Function IsNothing(obj) If TypeName(obj) = "Nothing" Then IsNothing = True Else IsNothing = False End If End Function Function OpenOutlookFolder(strFolderPath As String) As Outlook.MAPIFolder Dim arrFolders As Variant, _ varFolder As Variant, _ olkFolder As Outlook.MAPIFolder On Error GoTo ehOpenOutlookFolder If strFolderPath = "" Then Set OpenOutlookFolder = Nothing Else Do While Left(strFolderPath, 1) = "\" strFolderPath = Right(strFolderPath, Len(strFolderPath) - 1) Loop arrFolders = Split(strFolderPath, "\") For Each varFolder In arrFolders If IsNothing(olkFolder) Then Set olkFolder = Session.Folders(varFolder) Else Set olkFolder = olkFolder.Folders(varFolder) End If Next Set OpenOutlookFolder = olkFolder End If On Error GoTo 0 Exit Function ehOpenOutlookFolder: Set OpenOutlookFolder = Nothing On Error GoTo 0 End Function Open in new window 0   tonelm54Author Commented: .. 0   peakpeakCommented: 0 Free Tool: ZipGrep ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents. One of a set of tools we're offering as a way to say thank you for being a part of the community.   peakpeakCommented: 0   David LeeCommented: That could arguably be said about any bit of code.   0   tonelm54Author Commented: The code works great, apart from when it sees reports, Ive raised another question for this, as it is a new question Q_24304821 0 Question has a verified solution. Are you are experiencing a similar issue? Get a personalized answer when you ask a related question. Have a better answer? Share it in a comment. All Courses From novice to tech pro — start learning today.
__label__pos
0.527079
Utilizará la lista de comprensión para leer un archivo de forma automática al llamar a close () ¿La siguiente syntax cierra el archivo? lines = [line.strip() for line in open('/somefile/somewhere')] Puntos de bonificación si puedes demostrar cómo funciona o no … TIA! Debe cerrar el archivo, sí, aunque cuando lo hace exactamente depende de la implementación. La razón es que no hay ninguna referencia al archivo abierto después del final de la comprensión de la lista, por lo que se recogerá la basura y eso cerrará el archivo. En cpython (la versión de intérprete regular de python.org), sucederá de inmediato, ya que su recolector de basura funciona por conteo de referencias. En otro intérprete, como Jython o Iron Python, puede haber un retraso. Si desea asegurarse de que su archivo se cierre, es mucho mejor usar una sentencia with : with open("file.txt") as file: lines = [line.strip() for line in file] Cuando termine el with , el archivo se cerrará. Esto es cierto incluso si se genera una excepción dentro de él. Así es como debes hacerlo. with open('/somefile/somewhere') as f: lines = [line.strip() for line in f] En CPython, el archivo debe cerrarse de inmediato ya que no hay referencias a la izquierda, pero el lenguaje Python no lo garantiza . En Jython, el archivo no se cerrará hasta que se ejecute el recolector de basura No lo hará. Se puede utilizar un administrador de contexto para cerrarlo automáticamente. Por ejemplo: with open('/somefile/somewhere') as handle: lines = [line.strip() for line in handle] Esto es posible leer y cerrar un archivo en la lista de comprensión utilizando la biblioteca more_itertools 1 : import more_itertools as mit lines = [line.strip() for line in mit.with_iter(open("/somefile/somewhere"))] Tenga en cuenta que more_itertools es un paquete de terceros. Instalar vía pip install more_itertools . Consulte también la documentación para obtener más información sobre more_itertools.with_iter . Sí, porque el “abierto” no vincula el identificador de archivo a ningún objeto, se cerrará tan pronto como la comprensión de la lista esté completa y salga de su scope: #!/usr/bin/env python3 import psutil print('before anything, open files: ', end='') print(psutil.Process().open_files()) f = open('/etc/resolv.conf') print('after opening resolv.conf, open files: ', end='') print(psutil.Process().open_files()) f.close() print('after closing resolv.conf, open files: ', end='') print(psutil.Process().open_files()) print('reading /etc/services via a list comprehension') services = [ line.strip() for line in open('/etc/services') ] print('number of items in services: ', end='') print(len(services)) print('after reading /etc/services through list comp, open files: ', end='') print(psutil.Process().open_files())
__label__pos
0.706486
/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #ifndef AV1_ENCODER_RDOPT_H_ #define AV1_ENCODER_RDOPT_H_ #include "av1/common/blockd.h" #if CONFIG_LV_MAP #include "av1/common/txb_common.h" #endif #include "av1/encoder/block.h" #include "av1/encoder/context_tree.h" #include "av1/encoder/encoder.h" #if CONFIG_LV_MAP #include "av1/encoder/encodetxb.h" #endif #ifdef __cplusplus extern "C" { #endif #define MAX_REF_MV_SERCH 3 struct TileInfo; struct macroblock; struct RD_STATS; #if CONFIG_RD_DEBUG static INLINE void av1_update_txb_coeff_cost(RD_STATS *rd_stats, int plane, TX_SIZE tx_size, int blk_row, int blk_col, int txb_coeff_cost) { (void)blk_row; (void)blk_col; (void)tx_size; rd_stats->txb_coeff_cost[plane] += txb_coeff_cost; { const int txb_h = tx_size_high_unit[tx_size]; const int txb_w = tx_size_wide_unit[tx_size]; int idx, idy; for (idy = 0; idy < txb_h; ++idy) for (idx = 0; idx < txb_w; ++idx) rd_stats->txb_coeff_cost_map[plane][blk_row + idy][blk_col + idx] = 0; rd_stats->txb_coeff_cost_map[plane][blk_row][blk_col] = txb_coeff_cost; } assert(blk_row < TXB_COEFF_COST_MAP_SIZE); assert(blk_col < TXB_COEFF_COST_MAP_SIZE); } #endif typedef enum OUTPUT_STATUS { OUTPUT_HAS_PREDICTED_PIXELS, OUTPUT_HAS_DECODED_PIXELS } OUTPUT_STATUS; // Returns the number of colors in 'src'. int av1_count_colors(const uint8_t *src, int stride, int rows, int cols, int *val_count); // Same as av1_count_colors(), but for high-bitdepth mode. int av1_count_colors_highbd(const uint8_t *src8, int stride, int rows, int cols, int bit_depth, int *val_count); void av1_dist_block(const struct AV1_COMP *cpi, MACROBLOCK *x, int plane, BLOCK_SIZE plane_bsize, int block, int blk_row, int blk_col, TX_SIZE tx_size, int64_t *out_dist, int64_t *out_sse, OUTPUT_STATUS output_status); #if CONFIG_DIST_8X8 int64_t av1_dist_8x8(const struct AV1_COMP *const cpi, const MACROBLOCK *x, const uint8_t *src, int src_stride, const uint8_t *dst, int dst_stride, const BLOCK_SIZE tx_bsize, int bsw, int bsh, int visible_w, int visible_h, int qindex); #endif #if !CONFIG_LV_MAP DECLARE_ALIGNED(16, const uint16_t, band_count_table[TX_SIZES_ALL][8]); const uint16_t band_count_table[TX_SIZES_ALL][8] = { { 1, 2, 3, 4, 3, 16 - 13, 0 }, { 1, 2, 3, 4, 11, 64 - 21, 0 }, { 1, 2, 3, 4, 11, 256 - 21, 0 }, { 1, 2, 3, 4, 11, 1024 - 21, 0 }, #if CONFIG_TX64X64 { 1, 2, 3, 4, 11, 4096 - 21, 0 }, #endif // CONFIG_TX64X64 { 1, 2, 3, 4, 8, 32 - 18, 0 }, { 1, 2, 3, 4, 8, 32 - 18, 0 }, { 1, 2, 3, 4, 11, 128 - 21, 0 }, { 1, 2, 3, 4, 11, 128 - 21, 0 }, { 1, 2, 3, 4, 11, 512 - 21, 0 }, { 1, 2, 3, 4, 11, 512 - 21, 0 }, #if CONFIG_TX64X64 { 1, 2, 3, 4, 11, 2048 - 21, 0 }, { 1, 2, 3, 4, 11, 2048 - 21, 0 }, #endif // CONFIG_TX64X64 { 1, 2, 3, 4, 11, 64 - 21, 0 }, { 1, 2, 3, 4, 11, 64 - 21, 0 }, { 1, 2, 3, 4, 11, 256 - 21, 0 }, { 1, 2, 3, 4, 11, 256 - 21, 0 }, #if CONFIG_TX64X64 { 1, 2, 3, 4, 11, 1024 - 21, 0 }, { 1, 2, 3, 4, 11, 1024 - 21, 0 }, #endif // CONFIG_TX64X64 }; static INLINE int cost_coeffs(const AV1_COMMON *const cm, MACROBLOCK *x, int plane, int block, TX_SIZE tx_size, const SCAN_ORDER *scan_order, const ENTROPY_CONTEXT *a, const ENTROPY_CONTEXT *l, int use_fast_coef_costing) { MACROBLOCKD *const xd = &x->e_mbd; MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi; const struct macroblock_plane *p = &x->plane[plane]; const struct macroblockd_plane *pd = &xd->plane[plane]; const PLANE_TYPE type = pd->plane_type; const uint16_t *band_count = &band_count_table[tx_size][1]; const int eob = p->eobs[block]; const tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block); const TX_SIZE tx_size_ctx = get_txsize_entropy_ctx(tx_size); uint8_t token_cache[MAX_TX_SQUARE]; int pt = combine_entropy_contexts(*a, *l); int c, cost; const int16_t *scan = scan_order->scan; const int16_t *nb = scan_order->neighbors; const int ref = is_inter_block(mbmi); int(*head_token_costs)[COEFF_CONTEXTS][TAIL_TOKENS] = x->token_head_costs[tx_size_ctx][type][ref]; int(*tail_token_costs)[COEFF_CONTEXTS][TAIL_TOKENS] = x->token_tail_costs[tx_size_ctx][type][ref]; const int seg_eob = av1_get_tx_eob(&cm->seg, mbmi->segment_id, tx_size); int8_t eob_val; const int cat6_bits = av1_get_cat6_extrabits_size(tx_size, xd->bd); (void)cm; if (eob == 0) { // block zero cost = (*head_token_costs)[pt][0]; } else { if (use_fast_coef_costing) { int band_left = *band_count++; // dc token int v = qcoeff[0]; int16_t prev_t; cost = av1_get_token_cost(v, &prev_t, cat6_bits); eob_val = (eob == 1) ? EARLY_EOB : NO_EOB; cost += av1_get_coeff_token_cost( prev_t, eob_val, 1, (*head_token_costs)[pt], (*tail_token_costs)[pt]); token_cache[0] = av1_pt_energy_class[prev_t]; ++head_token_costs; ++tail_token_costs; // ac tokens for (c = 1; c < eob; c++) { const int rc = scan[c]; int16_t t; v = qcoeff[rc]; cost += av1_get_token_cost(v, &t, cat6_bits); eob_val = (c + 1 == eob) ? (c + 1 == seg_eob ? LAST_EOB : EARLY_EOB) : NO_EOB; cost += av1_get_coeff_token_cost(t, eob_val, 0, (*head_token_costs)[!prev_t], (*tail_token_costs)[!prev_t]); prev_t = t; if (!--band_left) { band_left = *band_count++; ++head_token_costs; ++tail_token_costs; } } } else { // !use_fast_coef_costing int band_left = *band_count++; // dc token int v = qcoeff[0]; int16_t tok; cost = av1_get_token_cost(v, &tok, cat6_bits); eob_val = (eob == 1) ? EARLY_EOB : NO_EOB; cost += av1_get_coeff_token_cost(tok, eob_val, 1, (*head_token_costs)[pt], (*tail_token_costs)[pt]); token_cache[0] = av1_pt_energy_class[tok]; ++head_token_costs; ++tail_token_costs; // ac tokens for (c = 1; c < eob; c++) { const int rc = scan[c]; v = qcoeff[rc]; cost += av1_get_token_cost(v, &tok, cat6_bits); pt = get_coef_context(nb, token_cache, c); eob_val = (c + 1 == eob) ? (c + 1 == seg_eob ? LAST_EOB : EARLY_EOB) : NO_EOB; cost += av1_get_coeff_token_cost( tok, eob_val, 0, (*head_token_costs)[pt], (*tail_token_costs)[pt]); token_cache[rc] = av1_pt_energy_class[tok]; if (!--band_left) { band_left = *band_count++; ++head_token_costs; ++tail_token_costs; } } } } return cost; } #endif // !CONFIG_LV_MAP static INLINE int av1_cost_coeffs(const struct AV1_COMP *const cpi, MACROBLOCK *x, int plane, int blk_row, int blk_col, int block, TX_SIZE tx_size, const SCAN_ORDER *scan_order, const ENTROPY_CONTEXT *a, const ENTROPY_CONTEXT *l, int use_fast_coef_costing) { #if TXCOEFF_COST_TIMER struct aom_usec_timer timer; aom_usec_timer_start(&timer); #endif const AV1_COMMON *const cm = &cpi->common; #if !CONFIG_LV_MAP (void)blk_row; (void)blk_col; int cost = cost_coeffs(cm, x, plane, block, tx_size, scan_order, a, l, use_fast_coef_costing); #else // !CONFIG_LV_MAP (void)scan_order; (void)use_fast_coef_costing; const MACROBLOCKD *xd = &x->e_mbd; const MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi; const struct macroblockd_plane *pd = &xd->plane[plane]; const BLOCK_SIZE bsize = mbmi->sb_type; const BLOCK_SIZE plane_bsize = get_plane_block_size(bsize, pd); TXB_CTX txb_ctx; get_txb_ctx(plane_bsize, tx_size, plane, a, l, &txb_ctx); const int eob = x->plane[plane].eobs[block]; int cost; if (eob) { cost = av1_cost_coeffs_txb(cm, x, plane, blk_row, blk_col, block, tx_size, &txb_ctx); } else { const TX_SIZE txs_ctx = get_txsize_entropy_ctx(tx_size); const PLANE_TYPE plane_type = get_plane_type(plane); const LV_MAP_COEFF_COST *const coeff_costs = &x->coeff_costs[txs_ctx][plane_type]; cost = coeff_costs->txb_skip_cost[txb_ctx.txb_skip_ctx][1]; } #endif // !CONFIG_LV_MAP #if TXCOEFF_COST_TIMER AV1_COMMON *tmp_cm = (AV1_COMMON *)&cpi->common; aom_usec_timer_mark(&timer); const int64_t elapsed_time = aom_usec_timer_elapsed(&timer); tmp_cm->txcoeff_cost_timer += elapsed_time; ++tmp_cm->txcoeff_cost_count; #endif return cost; } void av1_rd_pick_intra_mode_sb(const struct AV1_COMP *cpi, struct macroblock *x, int mi_row, int mi_col, struct RD_STATS *rd_cost, BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx, int64_t best_rd); unsigned int av1_get_sby_perpixel_variance(const struct AV1_COMP *cpi, const struct buf_2d *ref, BLOCK_SIZE bs); unsigned int av1_high_get_sby_perpixel_variance(const struct AV1_COMP *cpi, const struct buf_2d *ref, BLOCK_SIZE bs, int bd); void av1_rd_pick_inter_mode_sb(const struct AV1_COMP *cpi, struct TileDataEnc *tile_data, struct macroblock *x, int mi_row, int mi_col, struct RD_STATS *rd_cost, BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx, int64_t best_rd_so_far); void av1_rd_pick_inter_mode_sb_seg_skip( const struct AV1_COMP *cpi, struct TileDataEnc *tile_data, struct macroblock *x, int mi_row, int mi_col, struct RD_STATS *rd_cost, BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx, int64_t best_rd_so_far); int av1_internal_image_edge(const struct AV1_COMP *cpi); int av1_active_h_edge(const struct AV1_COMP *cpi, int mi_row, int mi_step); int av1_active_v_edge(const struct AV1_COMP *cpi, int mi_col, int mi_step); int av1_active_edge_sb(const struct AV1_COMP *cpi, int mi_row, int mi_col); int av1_tx_type_cost(const AV1_COMMON *cm, const MACROBLOCK *x, const MACROBLOCKD *xd, BLOCK_SIZE bsize, int plane, TX_SIZE tx_size, TX_TYPE tx_type); void av1_inverse_transform_block_facade(MACROBLOCKD *xd, int plane, int block, int blk_row, int blk_col, int eob, int reduced_tx_set); #ifdef __cplusplus } // extern "C" #endif #endif // AV1_ENCODER_RDOPT_H_
__label__pos
0.998452
C# | Math.Abs() Method | Set – 1 In C#, Abs() is a Math class method which is used to return the absolute value of a specified number. This method can be overload by passing the different type of parameters to it. 1. Math.Abs(Decimal) 2. Math.Abs(Double) 3. Math.Abs(Int16) 4. Math.Abs(Int32) 5. Math.Abs(Int64) 6. Math.Abs(SByte) 7. Math.Abs(Single) 8. Math.Abs(Decimal) This method is used to return the absolute value of a Decimal number. Syntax: public static decimal Abs (decimal val); Parameter: val: It is the required number which is greater than or equal to Decimal.MinValue, but less than or equal to Decimal.MaxValue of type System.Decimal. Return Type: It returns a decimal number say r, such that 0 ≤ r ≤ Decimal.MaxValue. Example: filter_none edit close play_arrow link brightness_4 code // C# Program to illlustrate the // Math.Abs(Decimal) Method using System;    class Geeks {        // Main Method     public static void Main()     {            // Taking decimal values         decimal[] deci = {Decimal.MinValue, 45.14M, 0M,                             -17.47M, Decimal.MaxValue};            // using foreach loop         foreach(decimal value in deci)                // Displaying the result             Console.WriteLine("Absolute value of {0} = {1}",                                     value, Math.Abs(value));     } } chevron_right Output: Absolute value of -79228162514264337593543950335 = 79228162514264337593543950335 Absolute value of 45.14 = 45.14 Absolute value of 0 = 0 Absolute value of -17.47 = 17.47 Absolute value of 79228162514264337593543950335 = 79228162514264337593543950335 Math.Abs(Double) This method is used to return the absolute value of a double-precision floating-point number. Syntax: public static double Abs (double val); Parameter: val: It is the required number which is greater than or equal to Double.MinValue, but less than or equal to Double.MaxValue of type System.Double. Return Type: It returns a double-precision floating-point number say r, such that 0 ≤ r ≤ Double.MaxValue. Note: • If val is equal to NegativeInfinity or PositiveInfinity, the return value will be PositiveInfinity. • If the val is equal to NaN then return value will be NaN. Example: filter_none edit close play_arrow link brightness_4 code // C# Program to illlustrate the // Math.Abs(Double) Method using System;    class Geeks {        // Main Method     public static void Main()     {            // Taking a NaN         Double nan = Double.NaN;            // Taking double values         double[] doub = {Double.MinValue, 27.58, 0.0,                         56.48e10, nan, Double.MaxValue};            // using foreach loop         foreach(double value in doub)                // Displaying the result             Console.WriteLine("Absolute value of {0} = {1}",                                     value, Math.Abs(value));     } } chevron_right Output: Absolute value of -1.79769313486232E+308 = 1.79769313486232E+308 Absolute value of 27.58 = 27.58 Absolute value of 0 = 0 Absolute value of 564800000000 = 564800000000 Absolute value of NaN = NaN Absolute value of 1.79769313486232E+308 = 1.79769313486232E+308 Math.Abs(Int16) This method is used to return the absolute value of a 16-bit signed integer. Syntax: public static short Abs (short val); Parameter: val: It is the required number which is greater than Int16.MinValue, but less than or equal to Int16.MaxValue of type System.Int16. Return Type: It returns 16-bit signed integer say r, such that 0 ≤ r ≤ Int16.MaxValue. Exception: This method will give OverflowException if the value of val is equals to Int16.MinValue. Example: filter_none edit close play_arrow link brightness_4 code // C# Program to illlustrate the // Math.Abs(Int16) Method using System;    class Geeks {        // Main Method     public static void Main()     {            // Taking short values         short[] sh = {Int16.MaxValue, 1482, -142, 0 };            // using foreach loop         foreach(short value in sh)                // Displaying the result             Console.WriteLine("Absolute value of {0} = {1}",                                     value, Math.Abs(value));     } } chevron_right Output: Absolute value of 32767 = 32767 Absolute value of 1482 = 1482 Absolute value of -142 = 142 Absolute value of 0 = 0 Math.Abs(Int32) This method is used to return the absolute value of a 32-bit signed integer. Syntax: public static int Abs (int val); Parameter: val: It is the required number which is greater than Int32.MinValue, but less than or equal to Int32.MaxValue of type System.Int32. Return Type: It returns 32-bit signed integer say r, such that 0 ≤ r ≤ Int32.MaxValue. Exception: This method will give OverflowException if the value of val is equals to Int32.MinValue. Example: filter_none edit close play_arrow link brightness_4 code // C# Program to illlustrate the // Math.Abs(Int32) Method using System;    class Geeks {        // Main Method     public static void Main()     {            // Taking int values         int[] int_val = {Int32.MaxValue, 13482, -65525, 0};            // using foreach loop         foreach(int value in int_val)                // Displaying the result             Console.WriteLine("Absolute value of {0} = {1}",                                     value, Math.Abs(value));     } } chevron_right Output: Absolute value of 2147483647 = 2147483647 Absolute value of 13482 = 13482 Absolute value of -65525 = 65525 Absolute value of 0 = 0 There are total 7 methods in its overload list. Here we will discuss only the first 4 methods and remaining 3 methods are discussed in C# | Math.Abs() Method | Set – 2. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.math.abs?view=netframework-4.7.2 My Personal Notes arrow_drop_up Check out this Author's contributed articles. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below. Article Tags : Be the First to upvote. Please write to us at [email protected] to report any issue with the above content.
__label__pos
0.900866
Beefy Boxes and Bandwidth Generously Provided by pair Networks Perl-Sensitive Sunglasses   PerlMonks   Genetic Programming or breeding Perls by gumpu (Friar) on Sep 05, 2000 at 21:06 UTC ( #31147=CUFP: print w/replies, xml ) Need Help?? This is a follow up on the discussion Be a monkey! about getting monkeys to write a Shakespeare novel by randomly typing on a typewriter. I have translated this into the following programming challenge: Write a Perl program that given a limited number of statements, creates a number that comes as close as possible to some target number. The program starts with my $x=1; my $y=1; which is followed by a combination of at most 30 statements chosen from the following 5 statements: $x += 1; $x =$y; $x |=$y; $x +=$y; $y =$x; The last statement of the program is the result of the program. For instance if the target number is 10, a possible solution is: my $x=1; my $y=1; $x+=1; $y=$x; $x+=$y; $x+=1; $y=$x; $x+=$y; Such a program is easy to find for small number. It is harder for larger numbers. For instance a solution for 10512 is: my $x=1;my $y=1; $x+=1; $x+=1;$x+=$y ;$y=$x ;$x+=$y ;$x+=$y ;$y=$x ;$x +=$y ; $x+=$y ;$x+=$y ;$x+=$y ;$x+=1;$x+=$y ;$x+=$y ;$y=$x ;$x+=$y ;$x+=$y +; $x+=$y ;$y=$x ;$x+=$y ;$x+=$y ;$x+=$y ;$y=$x ;$x+=$y ;$x|=$y ;$y=$x +; $x+=$y ;$x+=$y ; There are 6^30 = 2.2 * 10^23 ways to combine the 5 statements into a program of at most 30 of such statements. 6^30 = 2.2*10^23, which makes it quite impossible to just search all possible combinations for an answer. Randomly generating such programs is about as likely to find an answer as a monkey writing one or two lines of Shakespeare by randomly typing. However the following program does find an exact solution or a close approximation to the target number. It uses the technique of genetic programming, based on natural selection. It works with a population of individuals. Each individual has 30 genes. Each gene is a Perl statement. To evaluate the fitness of an individual these statements are stringed together into a Perl program. This program is then evaluated using eval(). The better this program is as creating the target number, the fitter the individual. The population cycles through a number of generations, in which a new population is generated (bred) from the old population. Pairs of individual are formed and they get two children. Each child is either an exact copy of one of one of its parents or a recombination of its parents. Which individuals are to become parents is based on their fitness (how well they did at reaching the target number). The fitter the individual the more offspring it has. After this all parents die and the cycle repeats. Generation after generation the population will become better at creating the target number. The nice quality of this technique is that no knowledge about the search space is needed. The only thing you need to define is a function that tells how good a particular solution is. Try changing the Gene base (possible Perl statements) or the target number. Not that there is no intelligence behind the process, but it can come-up with surprising solutions. Would be a good technique to create obfuscated code. :) It is ofcourse not a solution to all problems, for instance it does not work if there is only one good solution in the entire search-space. There must be intermediate solutions too. However it can be used to solve very hard problems. For instance I use a modified version of this program to solve the problem of how to pack 256 connections of varying capacity into 32 links. This has a search space of 2*10^385. Searching this would require more time then the life time of the current universe and many that come after it :) This is my first attempt of using OO in Perl. So please point-out any improvements. (I used the cookbook and the Perl FAQ as information sources). UPDATE: RE-ADDED CODE #!/usr/bin/perl -w # An implementation of Genetic programming in Perl. use strict; package GenePool; sub new { my $class = shift; my $self = {}; bless ($self, $class); # Each gene is a Perl statement. $self->{GENES} = ['$x+=1 ;', '$x=$y ;', '$y=$x ;', '$x|=$y ;', '$x+=$y ;', ' ;']; return $self; } # Randomly select a gene from the gene pool sub random_gene { my $self = shift; return ${$self->{GENES}}[rand(@{$self->{GENES}})]; } package Individual; sub new { my $class = shift; my $self = {}; bless ($self, $class); $self->{LENGTH} = 32; $self->{GENES} = []; # An array of perl statements. $self->{NEW_GENES} = []; # The genes of the individual in # the next generation. return $self; } # create the genes for this individual by randomly choosing # 30 Genes (Perl statements) from the GenePool. sub create { my $self = shift; my $genebase = GenePool->new(); push (@{$self->{GENES}}, 'my $x=1;my $y=1;'); for my $i (1 .. $self->{LENGTH}) { push (@{$self->{GENES}}, $genebase->random_gene()); } } # Convert the genes into an string of statements that can # be evaluated using eval(). sub get_code { my $self = shift; my $code = ""; map { $code .= $_} (@{$self->{GENES}}); return $code; } # Set the new set of genes and do some mutation. sub set_new_genes { my $self = shift; @{$self->{NEW_GENES}} = @_; # Once in a while there is an error during copying and a # gene is mutated. if (rand(1.0) < 0.005) { my $mutate = 1 + int(rand(@{$self->{NEW_GENES}} - 1)); my $genebase = GenePool->new(); ${$self->{GENES}}[$mutate] = $genebase->random_gene(); } } # Get a copy of the genes sub get_genes { my $self = shift; return @{$self->{GENES}}; } # Switch the new genes with the old genes sub switch_genes { my $self = shift; @{$self->{GENES}} = @{$self->{NEW_GENES}}; } package Population; sub new { my $class = shift; my $self = {}; bless ($self, $class); $self->{SIZE} = 1999; # The population size $self->{INDIVIDUALS} = []; $self->{FITNESSES} = []; # The fitness of each individual for my $i (0 .. $self->{SIZE}) { my $individual = Individual->new(); $individual->create(); push (@{$self->{INDIVIDUALS}}, $individual); } return $self; } # Determine the fitnes of all individuals in the population sub survival { my $self = shift; my $fitnesses = $self->{FITNESSES}; my $i = 0; foreach my $individual (@{$self->{INDIVIDUALS}}) { my $value = eval($individual->get_code()); ${$fitnesses}[$i] = objective($value); ++$i; } } # Scale the fitnes values such that they are all between 0 and 1 # and such that the total sum is 1. sub scale { my $self = shift; my $fitnesses = $self->{FITNESSES}; my $i; my $size = $self->{SIZE}; my $min = ${$fitnesses}[0]; for ($i = 0; $i < $size; ++$i) { $min = ${$fitnesses}[$i] if (${$fitnesses}[$i] < $min); } my $sum = 0.0; for ($i = 0; $i < $size; ++$i) { ${$fitnesses}[$i] -= $min; $sum += ${$fitnesses}[$i]; } for ($i = 0; $i < $size; ++$i) { ${$fitnesses}[$i] /= $sum; } } # Function that determines how fit an individual is # That is how close it comes to the objective. (target number) # The higher the number the fitter the individual. sub objective { my $value = shift; return -abs(10512 - $value); } # Display the fitest individual sub statistics { my $self = shift; my $fitnesses = $self->{FITNESSES}; my $i; my $index = 0; my $size = $self->{SIZE}; my $max = ${$fitnesses}[0]; for ($i = 0; $i < $size; ++$i) { if (${$fitnesses}[$i] > $max) { $max = ${$fitnesses}[$i]; $index = $i; } } my $individual = ${$self->{INDIVIDUALS}}[$index]; print " ", eval($individual->get_code()), "\n"; print $individual->get_code(), "\n"; } # Randomly select an individual from the population. # The fitter an individual it there more likely it is it # is chosen. sub choose { my $self = shift; my $f = rand(1.0); my $index = 0; my $sum = 0.0; foreach my $fitnes (@{$self->{FITNESSES}}) { $sum += $fitnes; return ${$self->{INDIVIDUALS}}[$index] if $sum >= $f; ++$index; } die "can't select an individual"; } # Generate a new poplation out of the old population by # letting the fitest individuals mate. sub breed { my $self = shift; my $size = $self->{SIZE}; for (my $i = 0; $i < $size;) { # Get the genes from two randomly chosen (fitest) individuals my @genes1 = ($self->choose())->get_genes(); my @genes2 = ($self->choose())->get_genes(); my @new_genes1 = @genes1; my @new_genes2 = @genes2; # Now either # (1) copy both genes into the new population or # (2) select a random cut point and swap the two gene # halves, that is # xxxxxxxxx becomes xxxxxyyyy # yyyyyyyyy yyyyyxxxx if (rand(1.0) > 0.5) { my $cut = 1 + int(rand(@genes1 - 1)); splice @new_genes1, $cut; splice @new_genes2, $cut; push @new_genes1, (splice @genes2, $cut); push @new_genes2, (splice @genes1, $cut); } ${$self->{INDIVIDUALS}}[$i++]->set_new_genes(@new_genes1); ${$self->{INDIVIDUALS}}[$i++]->set_new_genes(@new_genes2); } } # swap the old genes with the newly created genes to get the new # population. sub switch { my $self = shift; foreach my $individual (@{$self->{INDIVIDUALS}}) { $individual->switch_genes(); } } package main; my $population = Population->new(); for my $generation (0 .. 100) { $population->survival(); $population->scale(); $population->statistics(); $population->breed(); $population->switch(); } Replies are listed 'Best First'. RE: Genetic Programming or breeding Perls by nop (Hermit) on Sep 06, 2000 at 14:49 UTC There's a rich literature on genetic programming. For example, check out John Koza's stuff at www.cs.bham.ac.uk/~wbl/biblio/gp-html/JohnKoza.html. Another interesting thread is Tom Ray's Tierra. Realizing that computer programs are just too brittle to evolve well (as one bad character in a program can render it all useless, vs. the laxness in say DNA coding and codons), Ray proposed an interesting computer architecture loosely based on biology that supports evolving programs. www.hip.atr.co.jp/~ray/tierra/ Another interesting idea: Danny Hillis (of Connection Machine fame ) suggested in a 1990 paper that programs evolve better when confronted with "parasites". Hillis claimed he could evolve better sorting programs when they were pitted against an evolving landscape of "hard" sort sequences (which in turn were generated by different program evolving hard sequences with the goal of stumping the sorters... see citeseer.nj.nec.com/context/15365/9503 A good site for such topics is SFI www.santafe.edu This field hasn't generated much of practical significance yet, but it is cool. This field hasn't generated much of practical significance yet, but it is cool. Well, I beleive that there are a number of chip frabricators that are using GA to minimize the effect of parasitic transistors, also to minimize labour in layout. Danny Hillis's idea does work quite nicely if you can get it right. Another idea is to implement a sex difference. By having the genome translate into two different phenomes (for instance in a tracker implementation make sex X build from the genome from the left and sex X from the right) and forcing phenome/genomes to mate with the opposite (you can have as many sexes as you want, I played around with 3 sexes, when two go together they produce a child of the third type. Got the idea from a Piers Anthony book, from the Tarot series.) this minimizes the chance of getting stuck on a local min/maxima. Partially because the best solution will be forced to breed with the other sex, which is evaled differently, thus ensuring that 'good' genes get mixed with 'bad' genes (from either sexes POV). This means the randomness (im sure there is a more appropriate word) in the genepool stays higher. Another idea is implement chromosomes. Ie split the genome up into smaller packets that can mutated/bread individually. That way random insertions dont fubar the whole genome, just the chromosome they are in. I found the challenging aspect, and perhaps the limiting spect is coming up with an appropriate fitness function. If you can score your creatures then you can can solve the problem they arte trying to solve so whats the point? I mean not really but you get the idea. For instance if you do a tracker implementation, by very subtly changing the fitness function you basically kill any possiblity of solving the problem (eating all of the dots). From what I know there is really no way to know that your fitness function will enable to population to improve. Sorta reminds me of the classic night.day tank problem in neural nets actually.. Yves -- You are not ready to use symrefs unless you already know why they are bad. -- tadmc (CLPM) (Ovid) RE: Genetic Programming or breeding Perls by Ovid (Cardinal) on Sep 06, 2000 at 01:26 UTC I would just like to say that I, for one, am seriously impressed. I'm going to have to start playing around with this and see what I can come up with (though I can tell that this will be a steep learning curve). Cheers, Ovid RE: Genetic Programming or breeding Perls by Nooks (Monk) on Sep 06, 2000 at 03:32 UTC Well done! I tried to do this several months ago and failed because I didn't hit on the idea of using a sequence of individual statements. (I tried to define a small language I could eval and had trouble making it both expressive and easy to evaluate.) I notice you left out division---presumably you don't want to have to deal with errors from the eval statement? I notice you left out division---presumably you don't want to have to deal with errors from the eval statement? Yup that was one of the reasons. It would have made the program longer that it already is. Programs with errors in them are not a problem as long as they have different fitness values. For instance as long as program with one error in it has a higher fitness as a program with two errors in it. If all programs that do not evaluate correctly, result in the same fitness value there is no way for the algorithm to gradually move to a better solution. GP works only if there are intermediate solutions. Have Fun He also left out multiplication and subtraction. Presumably it was to minimize the operators used. I was a bit surprised at "|=" myself. Presumably it was to minimize the operators used. Yup. It thought it would make it easier to understand the problem (the programming challenge). It is also to limit the number of possible solutions. If there are many building blocks the search space is large but also full of good solutions. Then even a random search works. With this I hoped to demonstrate that even with limited building blocks the algorithm can work to a good solution. (It would be interesting to create a Perl program that can determine the solution density, say using monte carlo or so). I was a bit surprised at |= myself. :) I added that to show that the algorithm can come up with solutions that are not easily visable to humans. You can even add things like $x ^= 715; $x >>= 1; and it will come up with surprising results. Have Fun RE: Genetic Programming or breeding Perls by Petruchio (Vicar) on Sep 24, 2000 at 10:26 UTC I think I can pretty safely say that no number of monkeys, under any circumstances, will ever reproduce a single Shakespeare novel... since he was a playwright, and not a novelist. Sorry to nitpick. :-) Ay, mistress, and Petruchio is the master; That teacheth tricks eleven and twenty long - Shakespeare I believe your statement is false. Shakespeare was a human. Humans are primates. Primates are monkeys. Thus, a monkey did in fact write all Shakespearean novels! Imagine what any number of monkeys, under any circumstance could do! Now who's nitpicking? :-) cheers, Thomax "What find I here? Fair Portia's counterfeit! What demi-god Hath come so near creation?" -- Shakespeare (Bassanio in The Merchant of Venice) Thou liest, thou jesting monkey, thou - The Tempest :-) As tilly kindly pointed out, only some primates are monkeys, and humans are not amongst these. Some people might still say that, "a monkey did in fact write all Shakespearean novels". Predicating a quality (written by a monkey) to a non-existent object (a Shakespearean novel) is logically problematic. And these problems are very interesting, though I'm sorry to say that I no longer remember them well enough to speak knowledgeably about them. In any case, it doesn't matter. Let's say a monkey did write all Shakespearean novels (in which case so did each of the squirrels in my yard... and indeed, they wrote themselves, too. The novels that is, not the squirrels). Still, I said a monkey would never reproduce a single Shakespeare novel, and that holds true. It interests me, however, that in the same post you claim both to be a monkey and to be picking nits... at least you seem well-groomed. ;-) Now, God help thee, poor monkey! - Macbeth Actually monkeys are primates but not the other way around. The primates include lemurs, monkeys, and apes. The apes are the ones without tails, and we are apes. Among the great apes the chimpanzee and bonobo are closest, then we join in, then gorillas, and the orangutang is more distant. This is measuring by percentage of genetic material that is the same. Yes, you heard it right. We are biologically more similar to chimps than either we or chimps are to gorillas. (Monkeys have prehensile tails. Apes do not. Shakespeare might be counted as an ape, but for some minor taxonomical differences.) RE: Genetic Programming or breeding Perls by runrig (Abbot) on Sep 27, 2000 at 03:38 UTC Very cool :) One small nitpick though, is the use of map in void context. Specifically (in Individual->get_code): my $code = ""; map { $code .= $_} (@{$self->{GENES}}); could be: my $code = join('', @{$self->{GENES}}); Also, if your Individual->create() method returned $self at the end, you could change this (in Population->new): for my $i (0 .. $self->{SIZE}) { my $individual = Individual->new(); $individual->create(); push (@{$self->{INDIVIDUALS}}, $individual); } To this: push (@{$self->{INDIVIDUALS}}, Individual->new->create) for 0..$self-> +{SIZE}; Or maybe even this: $self->{INDIVIDUALS} = [ map {Individual->new->create} 0..$self->{SIZE +} ]; But now I'm probably being too nit-picky :) </code> Feel free to nitpick some more :), the replacement you suggest look very elegant. It's my first "complicated" perl program so there are bound to be more points that can be improved. Have Fun RE: Genetic Programming or breeding Perls by Crayman (Acolyte) on Oct 16, 2000 at 07:01 UTC cool concept and the implementation looks well done. i need to study it more in order to make any detailed or deep comments. extremely minor nitpiks and some questions. 1) someone already covered the map in void context. 2) my $min = ${$fitnesses}[0]; for ($i = 0; $i < $size; ++$i) { # set $i = 1 since you used 0th index to load $min. # same thing for the $max value in a diff routine later. $min = ${$fitnesses}[$i] if (${$fitnesses}[$i] < $min); } 3) sub random_gene { my $self = shift; return ${$self->{GENES}}[rand(@{$self->{GENES}})]; why do you allow perl to truncate the above, which provides a fair distribution for the 0th index, but you handle explicitly below, which never includes the 0th index? there may be a good reason, but i couldn't figure out what it was. if (rand(1.0) < 0.005) { my $mutate = 1 + int(rand(@{$self->{NEW_GENES}} - 1)); 4) if (rand(1.0) > 0.5) { my $cut = 1 + int(rand(@genes1 - 1)); # i understand it here - since replacing the entire gene from beginning might not make sense 5) i factored out the following from the code so I could stick everything on the top and play: my $Genes = ['$x+=1 ;', '$x=$y ;', '$y=$x ;', '$x|=$y ;', '$x+=$y ;', + ' ;']; my $IndivGeneLen = 32; my $PopSize = 1999; my $Target = 10512; my $NumGenerations = 100; next thought - this can be generalized into a module. very cool, thanks! ___cliff_AT_rayman.com___ i figured out the answer to #3. the declaration of the lexical variables occur in index 0, that makes them position dependent. therefore index 0 has to be skipped during mutations and splicing. something like this might be worthy of a comment in the code. ___cliff rayman___cliff_AT_rayman.com___ i figured out the answer to #3. the declaration of the lexical variables occur in index 0, that makes them position dependent. therefore index 0 has to be skipped during mutations and splicing. something like this might be worthy of a comment in the code. ___cliff rayman___cliff_AT_rayman.com___ RE: Genetic Programming or breeding Perls by Anonymous Monk on Sep 30, 2000 at 02:36 UTC Whoa -- someone else hit upon the same idea that I did! Two years ago, whilst a Sophmore (yeah, in HS -- I'm only now a Senior) I needed a science project for biology. Having previously fallen in love with Perl, and being interested in GP, I also wrote my own GP system in Perl. Your system is considerably different from mine -- probably mostly because your implementation isn't quite true to the definition of GP as defined by Koza. Normally, GP individuals are actual program trees, with branching constructs and multiple layers. This makes crossover harder than just string manipulation -- you have to keep track of the inherent structure of the individual. Many people writing GP in C or Java use pointers to construct the tree. Perl being what it is, I wrote a tokenizer that tokenized the syntacticly correct Perl individuals, and munged them as strings. Not as "elegant," nor as fast, but muchly fun. ;> Anyways, I was thinking, sooner or later, of throwing the code up on CPAN -- but later is the key word. I'm using my Perl GP implentation to do some research for the Westinghouse competition, which demands a 20-page paper. Which is due October 2nd. So I'm a little busy right now.. ;> Incidentally, the paper is about making distributed GP more efficient -- and I of course wrote my own client/server GP implentation in Perl. Gotta love threaded Perl. Anyways, I'll wander through here again once I have Free Time again, and post again -- hopefully with a little more clarity and content. Aargh -- the monastery ate my linefeeds and login. Oops. Take pity on the initiate and forgive the lack of formatting. Re: Genetic Programming or breeding Perls by rtpc (Initiate) on Aug 21, 2001 at 18:13 UTC Hhhmm, I've written my on vesion, with somewhat different operators (genes) to help with the speed of convergence. Actually, I changed the goal too, it now looks for an individual number, repedatively; it eventually prints ot JUST ANOTHER PERL HACKER. But I'm having a problem, quite often the populaion i overrun with exactly the same genes. I really need hlp figuring out how this is happening. The big differences are the choose and breed routines, which are called select and mate in this code. The mate routine selects some of the most fit oganisms, breeds them, and replaces some of the least fit organisms with the offspring. Here's the code: #!/usr/bin/perl package GenePool; sub new { my $class = shift; my $self = {}; bless($self, $class); $self->{GENES} = [ '$x+=1;', '$y+=1;', '$X-=1;', '$y-=1;', '$X+=$y;', '$y+=$x;', '$x-=$y;', '$y-=$x;', ';' ]; return $self; } sub gene { my $self = shift; return ${$self->{GENES}}[rand(@{$self->{GENES}})]; } package Organism; sub new { my $class = shift; my $self = {}; bless($self, $class); $self->{LENGTH} = 12; $self->{GENES} = []; $self->{NEXTGEN} = []; return $self; } #create genes for this organism by selecting genes from the genepool sub initialize { my $self = shift; my $genepool = GenePool->new(); foreach (1..$self->{LENGTH}){ push(@{$self->{GENES}}, $genepool->gene()); } return; } sub set_nextgen { my $self = shift; @{$self->{NEXTGEN}} = @_; return; } sub age { my $self = shift; @{$self->{GENES}} = @{$self->{NEXTGEN}} unless $#{$self->{NEXTGEN} +} == -1; return; } sub get_genes { my $self = shift; return @{$self->{GENES}}; } #return code to be evaluated sub get_code { my $self = shift; my $code = ""; foreach(@{$self->{GENES}}){ $code .= $_; } return $code; } package Population; sub new { my ($class, $size) = @_; my $self = {}; bless($self, $class); $size++ if $size%2 == 0; $size+=2 if ($size+1)%4 != 0; $self->{SIZE} = $size; $self->{ORGANISMS} = []; $self->{FITNESSES} = []; $self->{OBJECTIVE} = ""; $self->{VERBOSE} = ""; $self->{MIDDLE} = 0; foreach (0..$self->{SIZE}){ my $organism = Organism->new(); $organism->initialize; push(@{$self->{ORGANISMS}}, $organism); } return $self; } sub set_verbosity { my $self = shift; $self->{VERBOSE} = shift; return; } sub get_verbosity { my $self = shift; return $self->{VERBOSE}; } sub set_objective { my $self = shift; $self->{OBJECTIVE} = shift; return; } sub get_objective { my $self = shift; return $self->{OBJECTIVE}; } #determine the fitnesses of each organism sub fitness { my $self = shift; my $f = $self->{FITNESSES}; my $i = 0; print STDERR "\nFITNESS OF GENEPOOL evaluation(code_value)\n" if $self +->{VERBOSE}; foreach my $organism (@{$self->{ORGANISMS}}){ my $val = eval('my $x = 1; my $y = 1;' . $organism->get_code() +); ${$f}[$i] = $self->evaluate($val); print STDERR ${$f}[$i] . "($val)" if $self->{VERBOSE}; $i++; } print STDERR "\n" if $self->{VERBOSE}; return; } sub evaluate { my ($self, $val) = @_; return -abs($self->{OBJECTIVE} - $val); } #scale the fitnesses so they are less than one and add to one sub scale_fitness { my $self = shift; my $fitnesses = $self->{FITNESSES}; my $i; my $min = ${$fitnesses}[0]; my $size = $self->{SIZE}; my $sum = 0.0; for ($i = 0; $i <= $size; ++$i ){ $min = ${$fitnesses}[$i] if ${$fitnesses}[$i] < $min; } for ( $i = 0; $i <= $size; ++$i ){ ${$fitnesses}[$i] -= $min; $sum += ${$fitnesses}[$i]; } for ( $i = 0; $i <= $size; ++$i ){ if($sum != 0){ ${$fitnesses}[$i] /= $sum; }else{ ${$fitnesses}[$i] = 1/$#{$fitnesses}; } } return; } #pick the fitest individual, excepting those we are told to ignore # (which are the previous picks) sub select { my ($self, $type, @excludelist) = @_; my $index = 0; my ($fitest, $ffit); $ffit = 1.0 if $type eq 'least fit'; foreach my $fitness (@{$self->{FITNESSES}}){ my $next = ""; foreach (@excludelist){ if($index == $_){ $next = "next"; last; }} $index++; next if $next eq "next"; if ( (($type eq 'fitest') && ($ffit <= $fitness)) || (($type eq 'least fit') && ($ffit >= $fitness)) ){ $fitest = $index - 1; $ffit = $fitness; } } return ${$self->{ORGANISMS}}[$fitest], $fitest; } sub find_middle { my $self = shift; my $f = 0; foreach my $fitness (@{$self->{FITNESSES}}){ $f += $fitness; } $self->{MIDDLE} = $f/(@{$self->{FITNESSES}}+1); return; } #find the individual who's fitness is nearest the "middle" sub find_nearest_middle { my $self = shift; my $middle = $self->{MIDDLE}; my ($nearest, $n, $i); foreach (@{$self->{FITNESSES}}){ if ( abs($nearest - $middle) > abs($_ - $middle)){ $nearest = $_; $n = $i; } $i++; } return ${$self->{ORGANISMS}}[$n]; } sub mutate { my @genes = @_; my $genepool = GenePool->new(); foreach my $i (0..$#genes){ $genes[$i] = $genepool->gene if rand(1.0) > 0.825; } return @genes; } #produce offspring for the next generation sub mate { my $self = shift; my $size = $self->{SIZE}; my @minexcludes = (); my @maxexcludes = (); for ( my $i = 0; $i < $size; $i+=4 ){ my $chance = rand(1.0); if($chance > 0.5){ my (@genes_one, @genes_two, $org_one, $org_two, $index_one +, $index_two); ($org_one, $index_one) = $self->select('fitest', @maxexclu +des); push(@maxexcludes, $index_one); @genes_one = $org_one->get_genes(); ($org_two, $index_two) = $self->select('fitest', @maxexclu +des); push(@maxexcludes, $index_two); @genes_two = $org_two->get_genes(); my @new_genes_one = @genes_one; my @new_genes_two = @genes_two; my $point = 1 + int(rand(@genes_one - 1)); splice @new_genes_one, $point; splice @new_genes_two, $point; push @new_genes_one, (splice @genes_two, $point); push @new_genes_two, (splice @genes_one, $point); my (undef, $min_one) = $self->select('least fit', @minexcl +udes); push(@minexcludes, $min_one); my (undef, $min_two) = $self->select('least fit', @minexcl +udes); push(@minexcludes, $min_two); ${$self->{ORGANISMS}}[$min_one]->set_nextgen(@new_genes_on +e); ${$self->{ORGANISMS}}[$min_two]->set_nextgen(@new_genes_tw +o); }elsif($chance < 0.05){ if(rand(1.0)>0.5){ my (@genes_one, $org_one, $index_one); ($org_one, $index_one) = $self->select('fitest', @maxe +xcludes); push(@maxexcludes, $index_one); @genes_one = $org_one->get_genes(); my @new_genes_one = @genes_one; @new_genes_one = mutate(@genes_one); my (undef, $min_one) = $self->select('least fit', @min +excludes); push(@minexcludes, $min_one); ${$self->{ORGANISMS}}[$min_one]->set_nextgen(@new_gene +s_one); }else{ my (@genes_two, $org_two, $index_two); ($org_two, $index_two) = $self->select('fitest', @maxe +xcludes); push(@maxexcludes, $index_two); @genes_two = $org_two->get_genes(); my @new_genes_two = @genes_two; @new_genes_two = mutate(@genes_two); my (undef, $min_two) = $self->select('least fit', @min +excludes); push(@minexcludes, $min_two); ${$self->{ORGANISMS}}[$min_two]->set_nextgen(@new_gene +s_two); } } } return; } sub generate { my $self = shift; foreach my $organism (@{$self->{ORGANISMS}}){ $organism->age(); } return; } package Statistics; sub new { my $class = shift; my $self = {}; bless($self, $class); $self->{GRADE} = [ ' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I +', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]; return $self; } sub grade_fitest { my ($self, $pop) = @_; my ($best, undef) = ${$pop->{ORGANISMS}}[$pop->select('fitest')]; my $indexorg = eval('my $x=1; my $y=1;' . $best->get_code()); my $index = $indexorg; my $obj = $pop->get_objective(); if($index < 0){ $index = abs($index) + 1 + $obj; } return "*", $indexorg if $index > 26; return ${$self->{GRADE}}[$index], $indexorg; } sub show_fitest { my ($self, $pop) = @_; my ($best, undef) = ${$pop->{ORGANISMS}}[$pop->select('fitest')]; return $best->get_code(); } sub show_middle { my ($self, $pop) = @_; $pop->find_middle; my $middle = $pop->find_nearest_middle(); my $indexorg = eval('my $x=1; my $y=1;' . $middle->get_code()); my $index = $indexorg; my $obj = $pop->get_objective(); if($index < 0){ $index = abs($index) + 1 + $obj; } return "*", $indexorg if $index > 26; return ${$self->{GRADE}}[$index], $indexorg; } package main; $|=1; my @string = (10, 21, 19, 20, 0, 14, 15, 20, 8, 5, 18, 0, 16, 5, 18, 1 +2, 0, 8, 1, 3, 11, 5, 18); my (@kings, @halloffame); foreach my $target (@string){ my $population = Population->new(49); $population->set_objective($target); #$population->set_verbosity(1); my $generation = 0; my $found = 0; while(!$found){ print "Generation[$generation]"; $population->fitness(); $population->scale_fitness(); my $statistics = Statistics->new(); my ($grade, $val) = $statistics->grade_fitest($population); my $fitest = $statistics->show_fitest($population); print join("", @kings) . $grade; $population->mate(); $population->generate(); if($val == $target){ print "\n$fitest\n"; $found++; push(@kings, $grade); push(@halloffame, $fitest); }elsif($population->get_verbosity){ my ($grade, $val) = $statistics->show_middle($population); print " ($grade, $val)"; } print "\n" unless $found; $generation++; } } print "\nHALL OF FAME\n", join("\n", @halloffame); "But I'm having a problem, quite often the populaion i overrun with exactly the same genes. I really need hlp figuring out how this is happening." There can be a number of reasons for that. (1) Your population size is too small (GP works best with large populations) (2) Your mutation rate is too low (but your program it looks fine), or (3) Individuals with a low fitness have a too low probability to reproduce. If only the fitest individuals are allowed to reproduce they will take over the whole population. So weaker individuals have to have a chance to reproduce too. The probability for this depends on the population size. For a large population it can be low, for a small population is has to be high. Hope that helps Have Fun RE: Genetic Programming or breeding Perls by dumpest (Novice) on Sep 27, 2000 at 02:37 UTC WOW... this was really fun and interesting code... I have a question...isn't there a patent on Genetic Programming algorithms? I remember hearing about this once before...but maybe it was in relation to something else... Anyone have any information about this...? I know that the general idea is not new... if I remember correctly, these sort of ideas run at least back to the '60s, when they were known as "branch and bound algorithms". Thus my hunch is that while a particular implementation might well be under active patent, loads of prior art could be found for anything more general. So there's $0.02 worth of insight from someone with only $0.01 worth of knowledge on the topic. :-) If I remember correctly, these sort of ideas run at least back to the '60s, Yup, and even further back. The bibliography of Genetic Algorithms by David Goldberg lists books from 1951 and 1952. Also they basically 'stole' the idea from mother nature :) Have Fun No, sorry, branch-and-bound is not genetic. Actual true genetic programming started in the '70's, with Holland. Re: Genetic Programming or breeding Perls by t'mo (Pilgrim) on May 03, 2001 at 00:22 UTC I realize that this thread may not be followed anymore, but if it does (and especially if gumpu is out there listening), it seems to me that each Individual ought to know its own fitness. In other words, FITNESS should be a field in each Individual, and FITNESSES should not be field in Population. Any thoughts? You are right. FITNESS should be a field in each Individual. Fitness is something associated with an individual. Population should only keep track of the statistics of all the individuals in the population. Bad design choice; probably had a case of 'premature optimization' :) Have Fun I disagree. Fitness is a combination of the individual abilities and the constraints of the environment. If you put an individual in a different environment its fitness for that environment will change. Yes, fitness is related to the environment. But... In this case, if the algorighm becomes simpler if FITNESS is more tightly associated with the INDIVIDUAL. For example, this: sub choose { my $self = shift; my $f = rand(1.0); my $index = 0; my $sum = 0.0; foreach my $fitnes (@{$self->{FITNESSES}}) { $sum += $fitnes; return ${$self->{INDIVIDUALS}}[$index] if $sum >= $f; ++$index; } die "can't select an individual"; } becomes: sub choose { my $self = shift; my $f = rand(1.0); my $sum = 0.0; foreach my $individual (@{$self->{INDIVIDUALS}}) { $sum += $individual->{FITNESS}; return $individual if $sum >= $f; } die "can't select an individual"; } which I consider an improvement, not only due to the fact that there's (a little) less code, but the concept of choosing an individual and not a fitness is emphasized. Finally, I must admit that I have a bias in relation to the idea you presented. Yes, environment does determine fitness. However, what if you're trying to evolved generalized behavior, i.e., a program that will perform well in any environment, and not simply the one's it was trained in? The little bit of work I've done with GP has been focused in the direction of trying to avoid such "over-training" or specialization. RE: Genetic Programming or breeding Perls by joe (Acolyte) on Sep 23, 2000 at 02:10 UTC Where is the code for this? Oy! Good point! Clicking on the <Read More> link doesn't pull up the code! I clicked it several times. Perhaps the <Read More> link should be titled "How to Keep Monks in Suspense!" Cheers, Ovid Update: Looks like the problem has been fixed. Join the Perlmonks Setiathome Group or just go the the link and check out our stats. The code used to be attached to this article. It was edited by someone other than I. I will try and put it back. Have Fun Re: Genetic Programming or breeding Perls by kwilliams (Sexton) on May 24, 2001 at 19:26 UTC I thought I should point out the article that Brad Murray and I wrote a couple years ago for The Perl Journal on GAs in Perl. It's in issue #15. Re: Genetic Programming or breeding Perls by Anonymous Monk on May 24, 2001 at 19:30 UTC I would like to point out that the code given does not implement Genetic Programming. It implements Genetic Algorithms. The difference is significant. -- John Porter Log In? Username: Password: What's my password? Create A New User Domain Nodelet? Node Status? node history Node Type: CUFP [id://31147] Approved by root help Chatterbox? and the web crawler heard nothing... How do I use this? | Other CB clients Other Users? Others pondering the Monastery: (2) As of 2022-07-02 10:32 GMT Sections? Information? Find Nodes? Leftovers? Voting Booth? My most frequent journeys are powered by: Results (102 votes). Check out past polls. Notices?
__label__pos
0.831188
Ask Your Question 0 formula align on character asked 2017-03-04 01:57:02 +0200 mathteacher gravatar image updated 2017-03-04 01:57:34 +0200 I am a math teacher in a low-socio economic school where every child has a very basic laptop. We are trying to use libreoffice as our primary note taking software in class, the students still do their practice with pen and paper. The one thing I am struggling with in libreoffice is the ability to align multi-line formula at the equals sign. I know that the math documentation says the effect can be set up with a matrix, however I can't seem to get that working well when the formula includes fractions, as the denominator also gets aligned to the left/right instead of the centre of a fraction. i.e. matrix{ alignr{3+{2+3x} over 2} # {}={} # alignl{a} ## alignr{x} # {}={} # alignl{{2a-8}over 3 } } Also, the syntax is quite complex for 9th graders to be able to copy out, while at the same time staying focussed on the math we are trying to teach. Is there a reason that something like '&=' hasn't been implemented in libreoffice yet like latex or onenote? It would definitely be a killer feature as far a teaching math with libreoffice would be concerned. Thanks edit retag flag offensive close merge delete 1 Answer Sort by » oldest newest most voted 0 answered 2017-03-04 16:38:15 +0200 RGB-es gravatar image updated 2017-03-04 16:38:59 +0200 There is another (AFAIK, not documented) way to get left alignment: two double quotes at the beginning of a sentence. For right alignment, it is possible to "push" the object with spaces. Try this matrix{ {3+{2+3x} over 2} # {}={} # ""{a} ## ~~~~~~~{x} # {}={} # {{2a-8} over 3 } } And yes, a better way to handle all this would be a killer feature ;) edit flag offensive delete link more Login/Signup to Answer Question Tools 1 follower Stats Asked: 2017-03-04 01:57:02 +0200 Seen: 683 times Last updated: Mar 04 '17
__label__pos
0.678725
A new user interface for you! Read more... File start of Package openldap2 #! /bin/sh # Copyright (c) 1997-2000 SuSE GmbH Nuernberg, Germany. # Copyright (c) 2002 SuSE Linux AG Nuernberg, Germany. # Copyright (c) 2006 SUSE LINUX Products GmbH, Nuernberg, Germany. # # Author: Carsten Hoeger # Ralf Haferkamp # # /etc/init.d/ldap # ### BEGIN INIT INFO # Provides: ldap # Required-Start: $network $remote_fs # Required-Stop: $network $remote_fs # Default-Start: 3 5 # Default-Stop: 0 1 2 6 # Short-Description: OpenLDAP Server (slapd) # Description: Start and Stop the OpenLDAP Server (slapd) to # provide LDAP directory services. ### END INIT INFO # Determine the base and follow a runlevel link name. base=${0##*/} link=${base#*[SK][0-9][0-9]} test -f /etc/sysconfig/openldap && . /etc/sysconfig/openldap SLAPD_BIN=/usr/sbin/slapd LDAP_URLS="" LDAPS_URLS="" LDAPI_URLS="" SLAPD_CONFIG_ARG="-F /etc/openldap/slapd.d" SLAPD_PID_DIR="/var/run/slapd/" test -x $SLAPD_BIN || exit 5 # Shell functions sourced from /etc/rc.status: # rc_check check and set local and overall rc status # rc_status check and set local and overall rc status # rc_status -v ditto but be verbose in local rc status # rc_status -v -r ditto and clear the local rc status # rc_failed set local and overall rc status to failed # rc_failed <num> set local and overall rc status to <num><num> # rc_reset clear local rc status (overall remains) # rc_exit exit appropriate to overall rc status . /etc/rc.status # First reset status of this service rc_reset function init_ldap_listener_urls(){ case "$OPENLDAP_START_LDAP" in [Yy][Ee][Ss]) if [ -n "$OPENLDAP_LDAP_INTERFACES" ] then for iface in $OPENLDAP_LDAP_INTERFACES ;do LDAP_URLS="$LDAP_URLS ldap://$iface" done else LDAP_URLS="ldap:///" fi ;; esac } function init_ldapi_listener_urls(){ case "$OPENLDAP_START_LDAPI" in [Yy][Ee][Ss]) if [ -n "$OPENLDAP_LDAPI_INTERFACES" ] then for iface in $OPENLDAP_LDAPI_INTERFACES ;do esc_iface=`echo "$iface" | sed -e s'/\\//\\%2f/'g` LDAPI_URLS="$LDAPI_URLS ldapi://$esc_iface" done else LDAPI_URLS="ldapi:///" fi ;; esac } function init_ldaps_listener_urls(){ case "$OPENLDAP_START_LDAPS" in [Yy][Ee][Ss]) if [ -n "$OPENLDAP_LDAPS_INTERFACES" ] then for iface in $OPENLDAP_LDAPS_INTERFACES ;do LDAPS_URLS="$LDAPS_URLS ldaps://$iface" done else LDAPS_URLS="ldaps:///" fi ;; esac } function check_connection(){ SLAPD_TIMEOUT=10 START=$( date +%s) while [ $(( $( date +%s) - ${START} )) -lt ${SLAPD_TIMEOUT} ]; do ldapsearch -x -H "$LDAP_URLS $LDAPI_URLS $LDAPS_URLS" -b "" -s base &>/dev/null LDAPSEARCH_RC=$? if [ ${LDAPSEARCH_RC} -ge 0 ] && [ ${LDAPSEARCH_RC} -le 80 ] ; then break else sleep 1 fi done } depth=0; function chown_database_dirs_bconfig() { ldapdir=$(find $1 -type f -name "olcDatabase*" | xargs grep -i olcdbdirectory | awk '{print $2}') for dir in $ldapdir; do [ -d "$dir" ] && [ -n "$OPENLDAP_USER" ] && \ chown -R $OPENLDAP_USER $dir 2>/dev/null [ -d "$dir" ] && [ -n "$OPENLDAP_GROUP" ] && \ chgrp -R $OPENLDAP_GROUP $dir 2>/dev/null done } function chown_database_dirs() { ldapdir=`grep ^directory $1 | awk '{print $2}'` for dir in $ldapdir; do [ -d "$dir" ] && [ -n "$OPENLDAP_USER" ] && \ chown -R $OPENLDAP_USER $dir 2>/dev/null [ -d "$dir" ] && [ -n "$OPENLDAP_GROUP" ] && \ chgrp -R $OPENLDAP_GROUP $dir 2>/dev/null done includes=`grep ^include $1 | awk '{print $2}'` if [ $depth -le 50 ]; then depth=$(( $depth + 1 )); for i in $includes; do chown_database_dirs "$i" ; done fi } USER_CMD="" GROUP_CMD="" [ ! "x$OPENLDAP_USER" = "x" ] && USER_CMD="-u $OPENLDAP_USER" [ ! "x$OPENLDAP_GROUP" = "x" ] && GROUP_CMD="-g $OPENLDAP_GROUP" [ ! "x$OPENLDAP_CONFIG_BACKEND" = "xldap" ] && SLAPD_CONFIG_ARG="-f /etc/openldap/slapd.conf" if [ -f /etc/openldap/UPDATE_NEEDED ]; then rc_failed 6 echo " The configuration of your LDAP server needs to be updated." echo " Please see /usr/share/doc/packages/openldap2/README.update" echo " for details." echo " After the update please remove the file:" echo " /etc/openldap/UPDATE_NEEDED" rc_status -v exit fi # chown backend directories if OPENLDAP_CHOWN_DIRS ist set if [ "$(echo "$OPENLDAP_CHOWN_DIRS" | tr 'A-Z' 'a-z')" = "yes" ]; then if [ -n "$OPENLDAP_USER" -o -n "$OPENLDAP_GROUP" ]; then if [ -n "$OPENLDAP_CONFIG_BACKEND" -a "$OPENLDAP_CONFIG_BACKEND" = "ldap" ]; then chown -R $OPENLDAP_USER /etc/openldap/slapd.d 2>/dev/null chgrp -R $OPENLDAP_GROUP /etc/openldap/slapd.d 2>/dev/null chown_database_dirs_bconfig "/etc/openldap/slapd.d" # assume back-config usage if slapd.conf is not present but slapd.d is elif [ ! -f /etc/openldap/slapd.conf -a /etc/openldap/slapd.d ]; then chown -R $OPENLDAP_USER /etc/openldap/slapd.d 2>/dev/null chgrp -R $OPENLDAP_GROUP /etc/openldap/slapd.d 2>/dev/null chown_database_dirs_bconfig "/etc/openldap/slapd.d" else chown_database_dirs "/etc/openldap/slapd.conf" chgrp $OPENLDAP_GROUP /etc/openldap/slapd.conf 2>/dev/null fi if test -f /etc/sasl2/slapd.conf ; then chgrp $OPENLDAP_GROUP /etc/sasl2/slapd.conf 2>/dev/null chmod 640 /etc/sasl2/slapd.conf 2>/dev/null fi if [ -n "$OPENLDAP_KRB5_KEYTAB" ]; then keytabfile=${OPENLDAP_KRB5_KEYTAB/#FILE:/} if test -f $keytabfile ; then chgrp $OPENLDAP_GROUP $keytabfile 2>/dev/null chmod g+r $keytabfile 2>/dev/null fi fi fi fi if [ -n "$OPENLDAP_KRB5_KEYTAB" ]; then export KRB5_KTNAME=$OPENLDAP_KRB5_KEYTAB fi case "$OPENLDAP_REGISTER_SLP" in [Yy][Ee][Ss]) SLAPD_SLP_REG="-o slp=on" ;; *) SLAPD_SLP_REG="-o slp=off" ;; esac init_ldap_listener_urls init_ldapi_listener_urls init_ldaps_listener_urls if [ ! -d $SLAPD_PID_DIR ]; then mkdir -p $SLAPD_PID_DIR chown ldap:ldap $SLAPD_PID_DIR fi echo -n "Starting ldap-server" exec $SLAPD_BIN -h "$LDAP_URLS $LDAPS_URLS $LDAPI_URLS" \ $SLAPD_CONFIG_ARG $USER_CMD $GROUP_CMD \ $OPENLDAP_SLAPD_PARAMS $SLAPD_SLP_REG
__label__pos
0.592905
Syvum Home Page Home > GMAT Test Prep > Print Preview Arithmetic : Fractions   Preparation Just what you need to know !   Complex Fractions   If the numerator and denominator of a fraction are themselves fractions, then it is called a complex fraction. An example of a complex fraction is (3/5) (9/7) .   To simplify a complex fraction, its numerator is divided by its denominator (or multiplied by the reciprocal of its denominator). For example, 3 5 ÷ 9 7 = 3 5 × 7 9 = 1 5 × 7 3 = 7 15 .   Example It takes 1¾ hours to fill water into a large tank at a constant rate. What fraction of the tank is filled in a ½-hour? Solution.   Fraction of tank filled = (1/2) = (1/2) (7/4) = 1 2 ÷ 7 4 = 1 2 × 4 7 = 2 7 .     GMAT Math Review - Arithmetic : Index for Fractions   GMAT Math Review - Arithmetic : Practice Exercise for Fractions   - -   10 more pages in GMAT Math Review Contact Info © 1999-2017 Syvum Technologies Inc. Privacy Policy Disclaimer and Copyright
__label__pos
0.910156
问题标签 [big-o] For questions regarding programming in ECMAScript (JavaScript/JS) and its various dialects/implementations (excluding ActionScript). Note JavaScript is NOT the same as Java! Please include all relevant tags on your question; e.g., [node.js], [jquery], [json], [reactjs], [angular], [ember.js], [vue.js], [typescript], [svelte], etc. 0 投票 24 回答 479364 浏览 algorithm - Big O,您如何计算/近似它? 大多数拥有 CS 学位的人肯定知道Big O 代表什么。它可以帮助我们衡量算法的可扩展性。 但我很好奇,你如何计算或近似算法的复杂性? 0 投票 8 回答 1765 浏览 sorting - 我怎么写比 O(n!) 我为我的娱乐写了一个 O(n!) 排序,如果不完全替换它,就不能简单地优化它以更快地运行。[不,我不只是在物品被分类之前随机化这些物品]。 我如何编写更糟糕的 Big-O 排序,而不只是添加可以拉出以降低时间复杂度的无关垃圾? http://en.wikipedia.org/wiki/Big_O_notation具有按增长顺序排序的各种时间复杂度。 编辑:我找到了代码,这是我的 O(n!) 确定性排序,带有有趣的 hack 以生成列表的所有组合的列表。我有一个稍微长一点的 get_all_combinations 版本,它返回一个可迭代的组合,但不幸的是我不能让它成为一个单一的语句。[希望我没有通过修复错别字和删除以下代码中的下划线来引入错误] 0 投票 3 回答 3879 浏览 python - 在哪里可以找到 Python 中内置序列类型的时间和空间复杂度 我一直无法找到这些信息的来源,没有自己查看 Python 源代码以确定对象是如何工作的。有谁知道我在哪里可以在网上找到这个? 0 投票 25 回答 40655 浏览 algorithm - 八岁的Big-O? 我正在询问更多关于这对我的代码意味着什么。我从数学上理解这些概念,我只是很难理解它们在概念上的含义。例如,如果要对数据结构执行 O(1) 操作,我知道它必须执行的操作数量不会增加,因为有更多项目。O(n) 操作意味着您将对每个元素执行一组操作。有人可以在这里填空吗? • 就像 O(n^2) 操作到底会做什么? • 如果一个操作是 O(n log(n)),这到底意味着什么? • 是否有人必须抽大麻才能写出 O(x!)? 0 投票 6 回答 147920 浏览 data-structures - 从常见数据结构中索引、插入和删除的时间复杂度是多少? 对于最常见的数据结构(包括数组、链表、哈希表等)的操作,没有可用的大 O 表示法的总结。 0 投票 12 回答 28356 浏览 optimization - 什么是大 O 符号?你用它吗? 什么是大 O 符号?你用它吗? 我想我错过了这门大学课:D 有没有人使用它并给出一些他们在哪里使用它的真实例子? 也可以看看: 八岁的Big-O? Big O,您如何计算/近似它? 你在现实生活中应用了计算复杂性理论吗? 0 投票 8 回答 37658 浏览 java - 哪个清单 implementation will be the fastest for one pass write, read, then destroy? What is the fastest list implementation (in java) in a scenario where the list will be created one element at a time then at a later point be read on What is the fastest list implementation (in java) in a scenario where the list will be created one element at a time then at a later point be read one element at a time? The reads will be done with an iterator and then the list will then be destroyed. I know that the Big O notation for get is O(1) and add is O(1) for an ArrayList, while LinkedList is O(n) for get and O(1) for add. Does the iterator behave with the same Big O notation? Iterating through a linked list is O(1) per element. The Big O runtime for each option is the same. Probably the ArrayList will be faster because of better memory locality, but you'd have to measure it to know for sure. Pick whatever makes the code clearest. 0 投票 4 回答 2560 浏览 algorithm - 平衡分配算法 我正在为松散耦合的集群编写一些代码。为了在作业期间实现最佳性能,我让集群在每次孩子进入或退出时重新映射其数据。这最终将成为可选的,但目前它默认执行其数据平衡。我的平衡基本上只是确保每个孩子的文件数量永远不会超过每台机器的平均文件数,再加上一个。如果除法不干净,则加一用于余数。而且由于余数总是小于孩子的数量[除了 0 的情况,但我们可以排除这种情况],平衡后的孩子最多 avg + 1。 一切似乎都很好,直到我意识到我的算法是 O(n!)。顺着孩子的名单往下看,找出平均数,余数,谁有太多,谁有太少。对于太多列表中的每个孩子,遍历列表,发送给每个太少的孩子。 有没有更好的解决方案?我觉得应该有。 编辑:这里有一些伪代码来展示我是如何导出 O(n!) 的: 编辑:O(n^2)。Foreach n, n => n*n => n^2。我想我今天早上没有喝足够的咖啡!;) 将来我想转向更灵活和有弹性的分布方法[权重和启发式],但现在,数据的统一分布是可行的。 0 投票 39 回答 30068 浏览 arrays - 确定数组是否包含n ... n + m的算法? 我在 Reddit 上看到了这个问题,并没有提出积极的解决方案,我认为在这里问这个问题是一个完美的问题。这是关于面试问题的线程: 编写一个方法,该方法接受一个大小为 m 的 int 数组,如果该数组由数字 n...n+m-1、该范围内的所有数字和该范围内的数字组成,则返回 (True/False)。不保证对数组进行排序。(例如,{2,3,4} 将返回 true。{1,3,1} 将返回 false,{1,2,4} 将返回 false。 我遇到的问题是我的面试官一直要求我进行优化(更快的 O(n)、更少的内存等),以至于他声称你可以使用恒定数量的数组在一次遍历中做到这一点记忆。从来没想过那个。 连同您的解决方案,请说明他们是否假定数组包含唯一项目。还要指出您的解决方案是否假定序列从 1 开始。(我稍微修改了问题以允许出现 2、3、4 的情况......) 编辑:我现在认为不存在处理重复的时间线性和空间常数算法。任何人都可以验证这一点吗? 重复问题归结为测试数组是否在 O(n) 时间、O(1) 空间中包含重复项。如果可以做到这一点,您可以先简单地测试,如果没有重复,则运行发布的算法。那么你能在 O(n) 时间 O(1) 空间中测试欺骗吗? 0 投票 6 回答 4602 浏览 algorithm - 是否有所有内容的 Big-O 符号的主列表? 是否有所有内容的 Big-O 符号的主列表?数据结构、算法、对每个执行的操作、平均情况、最坏情况等。
__label__pos
0.997348
Aldo Aldo - 6 months ago 48 C Question Dynamic array using malloc and realloc? I'm trying to collect input integers one by one. My array starts with size 1 and I want to expand it by 1, with every input collected (is this a smart thing to do?) Anyway, this is the code I managed to come up with, but it's not working as intended. After this process, sizeof(array) always returns 8, which I assume means that the array is only being resized once. (sizeof(int) is 4 bits) Trying to output the array results in multiple instances of the first input variable. OUTPUT CODE for(int s=0;s<sizeof(array)/sizeof(int);s++){ printf("%i\n",array[i]); } ORIGINAL CODE: int i; int size = 1; int *array = malloc(size * sizeof(int)); int position = 0; do{ i = getchar() - 48; f (i != -16 && i != -38 && i != 0) { array[position] = i; position++; size++; *array = realloc(array, size * sizeof(int)); } } while (i != 0); UPDATED STILL NOT WORKING CODE int i; int size = 1; int *array = malloc(size * sizeof(int)); int position = 0; do{ i = getchar() - 48; f (i != -16 && i != -38 && i != 0) { array[position] = i; position++; size++; array = realloc(array, size * sizeof(int)); } } while (i != 0); Answer (With some copy-paste from my comment:) sizeof(array) returns 8 because it equals sizeof(int*) which is 8 (you're probably compiling as 64-bit). sizeof doesn't work how you think for pointers to arrays. Similarly, your output code is wrong, for the same reason. You only print the first two elements because sizeof(array)/sizeof(int) will always be 8/4=2. It should be for(int s=0;s<size;s++){ printf("%i\n",array[s]); } (note also changed index variable i to s) where size is the variable from your other code chunk(s). You cannot find the length of the array from sizeof if it's dynamically allocated with pointers; that's impossible. Your code must "remember" the size of your array.
__label__pos
0.992164
Chilkat Online Tools VBScript / Twitter API v2 / Liked Tweets Back to Collection Items Dim fso, outFile Set fso = CreateObject("Scripting.FileSystemObject") Set outFile = fso.CreateTextFile("output.txt", True) ' This example assumes the Chilkat API to have been previously unlocked. ' See Global Unlock Sample for sample code. set http = CreateObject("Chilkat_9_5_0.Http") ' Adds the "Authorization: Bearer <access_token>" header. http.AuthToken = "<access_token>" set sbResponseBody = CreateObject("Chilkat_9_5_0.StringBuilder") success = http.QuickGetSb("https://api.twitter.com/2/users/:id/liked_tweets",sbResponseBody) If (success = 0) Then outFile.WriteLine(http.LastErrorText) WScript.Quit End If outFile.WriteLine("Response status code = " & http.LastStatus) outFile.WriteLine(sbResponseBody.GetAsString()) outFile.Close Curl Command curl -X GET -H "Authorization: Bearer <access_token>" https://api.twitter.com/2/users/:id/liked_tweets Postman Collection Item JSON { "name": "Liked Tweets", "request": { "auth": { "type": "bearer", "bearer": [ { "key": "token", "value": "", "type": "string" } ] }, "method": "GET", "header": [ ], "url": { "raw": "https://api.twitter.com/2/users/:id/liked_tweets", "protocol": "https", "host": [ "api", "twitter", "com" ], "path": [ "2", "users", ":id", "liked_tweets" ], "query": [ { "key": "user.fields", "value": null, "description": "Comma-separated fields for the user object.\nAllowed values:\ncreated_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld\nDefault values:\nid,name,username", "disabled": true }, { "key": "expansions", "value": null, "description": "Expansions enable requests to expand an ID into a full object in the includes response object.\nAllowed value:\npinned_tweet_id\nDefault value: none", "disabled": true }, { "key": "tweet.fields", "value": null, "description": "Comma-separated list of fields for the Tweet object. Expansion required.\nAllowed values:\nattachments,author_id,context_annotations,conversation_id,created_at,entities,geo,id,in_reply_to_user_id,lang,non_public_metrics,organic_metrics,possibly_sensitive,promoted_metrics,public_metrics,referenced_tweets,source,text,withheld\nDefault values:\nid,text\nOAuth1.0a User Context authorization required if any of the following fields are included in the request:\nnon_public_metrics,organic_metrics,promoted_metrics", "disabled": true }, { "key": "max_results", "value": null, "description": "The maximum number of results to be returned by a request.\nAllowed values: 5 through 100.\nDefault value: 100", "disabled": true }, { "key": "pagination_token", "value": null, "description": "This parameter is used to get the next 'page' of results. The value used with the parameter is pulled directly from the response provided by the API, and should not be modified.", "disabled": true } ], "variable": [ { "key": "id", "value": "", "description": "Required. User ID of the user to request liked Tweets for." } ] }, "description": "Returns a list of Tweets that have been liked by a specified user ID.\n\nFor full details, see the [API reference](https://developer.twitter.com/en/docs/twitter-api/tweets/likes/api-reference/get-users-id-liked_tweets) for this endpoint.\n\n[Sign up](https://t.co/signup) for the Twitter API" }, "response": [ ] }
__label__pos
0.92025
Export (0) Print Expand All DataAdapter.Update Method Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified DataSet from a DataTable named "Table". [Visual Basic] Public MustOverride Function Update( _ ByVal dataSet As DataSet _ ) As Integer Implements IDataAdapter.Update [C#] public abstract int Update( DataSet dataSet ); [C++] public: virtual int Update( DataSet* dataSet ) = 0; [JScript] public abstract function Update( dataSet : DataSet ) : int; Parameters dataSet The DataSet used to update the data source. Return Value The number of rows successfully updated from the DataSet. Implements IDataAdapter.Update Exceptions Exception Type Condition SystemException A source table could not be found. DBConcurrencyException An attempt to execute an INSERT, UPDATE, or DELETE statement resulted in zero records affected. Remarks When an application calls the Update method, the DataAdapter examines the RowState property, and executes the required INSERT, UPDATE, or DELETE statements iteratively for each row, based on the order of the indexes configured in the DataSet. For example, Update might execute a DELETE statement, followed by an INSERT statement, and then another DELETE statement, due to the ordering of the rows in the DataTable. It should be noted that these statements are not performed as a batch process; each row is updated individually. An application can call the GetChanges method in situations where you must control the sequence of statement types (for example, INSERTs before UPDATEs). For more information, see Updating the Database with a DataAdapter and the DataSet. If INSERT, UPDATE, or DELETE statements have not been specified, the Update method generates an exception. However, you can create a SqlCommandBuilder or OleDbCommandBuilder object to automatically generate SQL statements for single-table updates if you set the SelectCommand property of a .NET Framework data provider. Then, any additional SQL statements that you do not set are generated by the CommandBuilder. This generation logic requires key column information to be present in the DataSet. For more information see Automatically Generated Commands. The Update method retrieves rows from the table listed in the first mapping before performing an update. The Update then refreshes the row using the value of the UpdatedRowSource property. Any additional rows returned are ignored. After any data is loaded back into the DataSet, the OnRowUpdated event is raised, allowing the user to inspect the reconciled DataSet row and any output parameters returned by the command. After a row updates successfully, the changes to that row are accepted. When using Update, the order of execution is as follows: 1. The values in the DataRow are moved to the parameter values. 2. The OnRowUpdating event is raised. 3. The command executes. 4. If the command is set to FirstReturnedRecord, then the first returned result is placed in the DataRow. 5. If there are output parameters, they are placed in the DataRow. 6. The OnRowUpdated event is raised. 7. AcceptChanges is called. Each command associated with the DataAdapter usually has a parameters collection associated with it. Parameters are mapped to the current row through the SourceColumn and SourceVersion properties of a .NET data provider's Parameter class. SourceColumn refers to a DataTable column that the DataAdapter references to obtain parameter values for the current row. SourceColumn refers to the unmapped column name before any table mappings have been applied. If SourceColumn refers to a nonexistent column, the action taken depends on one of the following MissingMappingAction values. Enumeration Value Action Taken MissingMappingAction.Passthrough Use the source column names and table names in the DataSet if no mapping is present. MissingMappingAction.Ignore A SystemException is generated. When the mappings are explicitly set, a missing mapping for an input parameter is usually the result of an error. MissingMappingAction.Error A SystemException is generated. The SourceColumn property is also used to map the value for output or input/output parameters back to the DataSet. An exception is generated if it refers to a nonexistent column. The SourceVersion property of a .NET data provider's Parameter class determines whether to use the Original, Current, or Proposed version of the column value. This capability is often used to include original values in the WHERE clause of an UPDATE statement to check for optimistic concurrency violations. Example [Visual Basic, C#, C++] The following example uses the derived class, OleDbDataAdapter, to Update the data source. [Visual Basic] Public Function CreateCmdsAndUpdate(myDataSet As DataSet, myConnection As String, mySelectQuery As String, myTableName As String) As DataSet Dim myConn As New OleDbConnection(myConnection) Dim myDataAdapter As New OleDbDataAdapter() myDataAdapter.SelectCommand = New OleDbCommand(mySelectQuery, myConn) Dim custCB As OleDbCommandBuilder = New OleDbCommandBuilder(myDataAdapter) myConn.Open() Dim custDS As DataSet = New DataSet myDataAdapter.Fill(custDS) ' Code to modify data in DataSet here ' Without the OleDbCommandBuilder this line would fail. myDataAdapter.Update(custDS) myConn.Close() CreateCmdsAndUpdate = custDS End Function 'SelectOleDbSrvRows [C#] public DataSet CreateCmdsAndUpdate(DataSet myDataSet,string myConnection,string mySelectQuery,string myTableName) { OleDbConnection myConn = new OleDbConnection(myConnection); OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(); myDataAdapter.SelectCommand = new OleDbCommand(mySelectQuery, myConn); OleDbCommandBuilder custCB = new OleDbCommandBuilder(myDataAdapter); myConn.Open(); DataSet custDS = new DataSet(); myDataAdapter.Fill(custDS); //code to modify data in dataset here //Without the OleDbCommandBuilder this line would fail myDataAdapter.Update(custDS); myConn.Close(); return custDS; } [C++] public: DataSet* CreateCmdsAndUpdate(DataSet* /*myDataSet*/,String* myConnection,String* mySelectQuery,String* /*myTableName*/) { OleDbConnection* myConn = new OleDbConnection(myConnection); OleDbDataAdapter* myDataAdapter = new OleDbDataAdapter(); myDataAdapter->SelectCommand = new OleDbCommand(mySelectQuery, myConn); OleDbCommandBuilder* custCB = new OleDbCommandBuilder(myDataAdapter); myConn->Open(); DataSet* custDS = new DataSet(); myDataAdapter->Fill(custDS); //code to modify data in dataset here //Without the OleDbCommandBuilder this line would fail myDataAdapter->Update(custDS); myConn->Close(); return custDS; } [JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page. Requirements Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework See Also DataAdapter Class | DataAdapter Members | System.Data.Common Namespace Show: © 2014 Microsoft
__label__pos
0.981505
Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023 What is immutable in JavaScript Understanding Immutability When we start talking about JavaScript, one of the key concepts that often comes up is immutability. Simply put, immutability is a term used to describe something that cannot be changed. You can think of it as a frozen pizza. Once you've cooked it, you can't un-cook it or change its original form. In the context of JavaScript, an immutable object is an object whose state cannot be modified after it is created. But don't fret, we'll get down to the nuts and bolts of it all in a moment. The Basics of Immutability In JavaScript, there are two types of data: primitive and non-primitive. Primitive types (like numbers, strings, and booleans) are immutable. This means that once a value is created, it can't be changed. Let's look at an example: let a = 'hello'; let b = a; b = 'world'; console.log(a); // 'hello' console.log(b); // 'world' Although we reassigned b, the value of a did not change. This is because when we did let b = a, JavaScript created a copy of a's value for b. So changing b didn't affect a. Now, non-primitive types (like objects and arrays) are a different story. They are mutable, which means we can change their properties or elements. let obj1 = { name: 'Alice' }; let obj2 = obj1; obj2.name = 'Bob'; console.log(obj1.name); // 'Bob' console.log(obj2.name); // 'Bob' This time, both obj1 and obj2 changed. This is because obj1 and obj2 are pointing to the same object in memory. When we change obj2, we are also changing obj1. Why Do We Care About Immutability? Now that we understand what immutability is, let's discuss why it's important. Immutability helps us write safer and cleaner code. Imagine you're at a museum. The museum rules state that you can't touch any exhibits. The exhibits are immutable. Why? Because if people could touch and change the exhibits, things would quickly get chaotic. The same principle applies to programming. By keeping our data immutable, we can avoid unexpected changes and bugs in our code. Making Objects and Arrays Immutable While objects and arrays in JavaScript are mutable by default, there are ways to make them immutable. One way is by using the Object.freeze() method. let obj = { name: 'Alice' }; Object.freeze(obj); obj.name = 'Bob'; console.log(obj.name); // 'Alice' As you can see, even though we tried to change obj, its value stayed the same. This is because Object.freeze() made obj immutable. Immutability and Functional Programming Immutability is a core concept in functional programming, a popular paradigm in JavaScript. Functional programming treats data as immutable and uses pure functions (functions that don't change their input and always give the same output for the same input) to change data. This way of programming reduces side effects (unintended changes to data) and makes code easier to understand and debug. Here's an example of how you can use the map() function to create a new array with incremented values, rather than changing the original array: let arr = [1, 2, 3]; let newArr = arr.map(x => x + 1); console.log(arr); // [1, 2, 3] console.log(newArr); // [2, 3, 4] In Conclusion Immutability, the frozen pizza of JavaScript, is a mighty concept that can save you from many headaches in your coding journey. It's a beacon of stability in a sea of change, a steadfast rule that once something is created, it shall not be changed. By understanding and using immutability, you're not only levelling up your JavaScript knowledge, but also joining the ranks of functional programmers who swear by the power of this principle. So, next time you're about to mutate an object, think twice. There's a good chance that you're better off with immutability!
__label__pos
0.99925
How Many Oz Is 2.7 Liters? 2.7 liters is equal to 91.7 ounces. This is a useful conversion to know when measuring liquids, as many recipes and instructions are given in liters. Knowing how many ounces are in a liter can help you accurately measure the amount of liquid you need for a recipe or other task. How to Convert 2.7 Liters to Ounces Converting 2.7 liters to ounces is easy! All you need to do is multiply 2.7 liters by 33.814 ounces, and you’ll get 91.079 ounces. That’s it! Now you know how to convert liters to ounces in a jiffy. Have fun! Understanding the Relationship Between Liters and Ounces Do you ever find yourself wondering how many ounces are in a liter? Or how many liters are in an ounce? If so, you’ve come to the right place! Let’s take a look at the relationship between liters and ounces and how to convert between the two. First, let’s start with the basics. A liter is a metric unit of volume, while an ounce is an imperial unit of volume. One liter is equal to 33.814 fluid ounces. This means that if you have one liter of liquid, it is equal to 33.814 fluid ounces. Suggested Post:  How Many Ounces Is 1/3 Cup Of Cream Cheese? Now, let’s look at how to convert between liters and ounces. To convert from liters to ounces, simply multiply the number of liters by 33.814. For example, if you have 2 liters of liquid, it is equal to 67.628 fluid ounces. To convert from ounces to liters, divide the number of ounces by 33.814. For example, if you have 67.628 fluid ounces of liquid, it is equal to 2 liters. As you can see, understanding the relationship between liters and ounces is quite simple! With just a few simple calculations, you can easily convert between the two units of measurement. So the next time you’re wondering how many ounces are in a liter, or how many liters are in an ounce, you’ll know exactly what to do! Exploring the Metric System: 2.7 Liters to Ounces how many oz is 2.7 liters 2.7 liters is equal to 91.7 ounces! That’s a lot of liquid! The metric system is a great way to measure and compare different amounts of things. It’s easy to convert between different units of measurement, like liters and ounces. All you need to do is use a conversion chart or calculator to figure out the answer. It’s a great way to make sure you’re getting the right amount of whatever you’re measuring. So the next time you need to measure something, don’t forget to use the metric system! How to Measure 2.7 Liters in Ounces Measuring 2.7 liters in ounces is easy! All you need is a measuring cup and a calculator. First, fill the measuring cup with 2.7 liters of liquid. Then, multiply 2.7 liters by 33.814 ounces, which is the conversion rate for liters to ounces. The result is 91.079 ounces, which is the equivalent of 2.7 liters in ounces! So there you have it – measuring 2.7 liters in ounces is a breeze! Suggested Post:  How Many Liters Is 40 Oz? The Benefits of Knowing How to Convert 2.7 Liters to Ounces Knowing how to convert 2.7 liters to ounces can be incredibly useful in a variety of situations. Whether you’re a home cook, a professional chef, or a student in a science class, understanding the relationship between liters and ounces can help you make accurate measurements and calculations. For home cooks, understanding how to convert 2.7 liters to ounces can help you make sure you’re using the right amount of ingredients in your recipes. If a recipe calls for a certain number of ounces of an ingredient, you can easily convert it to liters and make sure you’re using the right amount. For professional chefs, understanding how to convert 2.7 liters to ounces can help you accurately measure ingredients for large batches of food. This can help you save time and money by ensuring that you’re using the right amount of ingredients for each dish. For students in science classes, understanding how to convert 2.7 liters to ounces can help you make accurate measurements and calculations. This can be especially helpful when you’re working with liquids, as you can easily convert between liters and ounces to make sure you’re using the right amount of a liquid for an experiment. Overall, knowing how to convert 2.7 liters to ounces can be incredibly useful in a variety of situations. Whether you’re a home cook, a professional chef, or a student in a science class, understanding the relationship between liters and ounces can help you make accurate measurements and calculations. So, don’t be afraid to brush up on your conversion skills – it could come in handy! Suggested Post:  How Many Grams In 1 Ounce? A Guide to Converting 2.7 Liters to Ounces Converting 2.7 liters to ounces is easy! Here’s a quick guide to help you out: First, you’ll need to know that 1 liter is equal to 33.814 ounces. So, to convert 2.7 liters to ounces, you’ll need to multiply 2.7 by 33.814. The answer is 91.3198 ounces! Now you know how to convert liters to ounces. It’s a great skill to have, and it can come in handy in a variety of situations. So, the next time you need to convert liters to ounces, you’ll be ready! The Science Behind Converting 2.7 Liters to Ounces Converting 2.7 liters to ounces is a simple process that requires a bit of math. But don’t worry, it’s nothing too complicated! First, let’s start with the basics. One liter is equal to 33.814 ounces. So, to convert 2.7 liters to ounces, we simply need to multiply 2.7 by 33.814. This gives us 91.5198 ounces. Now, if you want to be more precise, you can round up the number to 91.52 ounces. That’s it! You’ve successfully converted 2.7 liters to ounces. It’s amazing how a few simple calculations can help us understand the world around us. With a bit of math, we can easily convert between different units of measurement. So the next time you need to convert liters to ounces, you’ll know exactly what to do! A Comprehensive Look at 2.7 Liters and Ounces Conversion Are you looking to convert 2.7 liters to ounces? You’ve come to the right place! Converting between liters and ounces can be tricky, but we’re here to help. Let’s take a look at the conversion process and get you on your way! Suggested Post:  How Much Is 64 Oz? First, let’s talk about what a liter is. A liter is a metric unit of volume, and it is equal to 1,000 cubic centimeters. It is also equal to 33.814 fluid ounces. So, if you want to convert 2.7 liters to ounces, you’ll need to multiply 2.7 by 33.814. This will give you 91.078 ounces. Now, let’s talk about what an ounce is. An ounce is a unit of weight and volume in the imperial and US customary systems of measurement. It is equal to 28.35 grams or 1.0408 fluid ounces. So, if you want to convert 2.7 liters to ounces, you’ll need to divide 2.7 by 28.35. This will give you 0.095 ounces. As you can see, converting between liters and ounces can be a bit tricky. But with a little bit of math, you can easily convert between the two units of measurement. So, the next time you need to convert 2.7 liters to ounces, you’ll know exactly what to do! Conclusion 2.7 liters is equal to 91.7 ounces, which is a little over 5 and a half pints. This is a large amount of liquid, and it is important to be aware of the conversion between liters and ounces when measuring liquids. Facebook Twitter LinkedIn Pinterest Email Recent Posts Leave a Comment
__label__pos
0.913278
Shotgun Spread not Spreading Hey guys, First time poster here. Having a very hard time getting my weapon to spread correctly when dealing with more than 1 bullet. It works perfect when dealing with just 1 shot but the bullets don’t position themselves correctly when dealing with more than that. Here is the code: using UnityEngine; using System.Collections; public class Weapon_Firer : Weapon { public Rigidbody smallBullet; public Rigidbody smallWaveBullet; public Transform shotPos; public Transform gunPos; public float shotForce; public float fireRate; public float fireWait; public bool isExplosive; public bool isWave; public bool isLaser; public bool isTesla; public float numShots; public float shotSpread; void Update() { if (Time.timeScale == 1) { if (Input.GetButton ("Fire1")) { if(fireWait >= fireRate) { if (isWave) { for (int i = 0; i < numShots; i++) { var pelletRot = transform.rotation; pelletRot.x += Random.Range(-shotSpread, shotSpread); pelletRot.y += Random.Range(-shotSpread, shotSpread); Rigidbody shot = Instantiate(smallWaveBullet, shotPos.position, pelletRot) as Rigidbody; shot.AddForce(shotPos.forward * shotForce); } } else { for (int i = 0; i < numShots; i++) { var pelletRot = transform.rotation; pelletRot.x += Random.Range(-shotSpread, shotSpread); pelletRot.y += Random.Range(-shotSpread, shotSpread); Rigidbody shot = Instantiate(smallBullet, shotPos.position, pelletRot) as Rigidbody; shot.AddForce(shot.transform.forward * shotForce); } } fireWait = 0; } else { fireWait++; } } } } } Your problem of them not positioning themselves correctly is a bit too vague to understand what they are doing. I don’t know what the value of shotSpread is but as you are using it in a Random.Range there is nothing stopping two pellets spawning on top of or inside each other. If your pellet count is high and the spread value low then it is pretty likely to happen every time you fire. Since they are rigidbodies this will obviously cause them to bounce off each other and mess up. That’s probably what you should be addressing. Using shotPos.forward for the spreading pellets would also stop them spreading and just make them travel in the direction of the gun barrel. However because I was bored I also cleaned up your script for you by rolling the firing into a single function and assigning the projectile to it rather than writing it out identically twice. Untested but should work. using UnityEngine; using System.Collections; public class Weapon_Firer : Weapon { public Rigidbody smallBullet; public Rigidbody smallWaveBullet; public Transform shotPos; public Transform gunPos; public float shotForce; public float fireRate; public float fireWait; public bool isExplosive; public bool isWave; public bool isLaser; public bool isTesla; public float numShots; public float shotSpread; void FireShotgun(Rigidbody projectileType) { for (int i = 0; i < numShots; i++) { Quaternion pelletRot = transform.rotation; pelletRot.x += Random.Range(-shotSpread, shotSpread); pelletRot.y += Random.Range(-shotSpread, shotSpread); Rigidbody shot = Instantiate(projectileType, shotPos.position, pelletRot) as Rigidbody; shot.AddForce(shot.transform.forward * shotForce); } } void Update() { //Probably not a good idea to be checking the time scale every single frame //If you need to check if the game is paused you should probably use a bool and check it after Fire1 if (Input.GetButton("Fire1")) { //If isPaused == false etc if (fireWait >= fireRate) { if (isWave) { FireShotgun(smallWaveBullet); } else { FireShotgun(smallBullet); } fireWait = 0; } else { fireWait++; } } } }
__label__pos
0.984992
web stats Does iOS 16 wallpapers drain battery? Does iOS 16 wallpapers drain battery? Does iOS 16 wallpapers drain battery? The digital world is constantly evolving and with it, the technology we use every day. With each new version of iOS, users are presented with new features, tools, and wallpapers. One question many iOS users have is whether iOS 16 wallpapers drain battery life. Wallpaper Battery Life Light High Dark Low Dynamic High Live Low iOS 16 wallpapers are generally considered to have a minimal impact on battery life. However, the type of wallpaper you choose can make a difference in how much battery life you have. Light wallpapers require more energy to display, while dark wallpapers require less energy. Dynamic and live wallpapers, on the other hand, are more intensive and can drain your battery more quickly. Does A Light Wallpaper Drain Battery? Light wallpapers require more energy to display than dark wallpapers, so they can drain your battery more quickly. However, the difference is usually minimal and you won’t notice a substantial drop in battery life if you use a light wallpaper. Does A Dark Wallpaper Drain Battery? Dark wallpapers are generally considered to have a minimal impact on battery life. They require less energy to display than light wallpapers, so they don’t drain your battery as quickly. In addition, dark wallpapers can help conserve your battery life by reducing the amount of light your device needs to emit. Does A Dynamic or Live Wallpaper Drain Battery? Dynamic and live wallpapers are more intensive and can drain your battery more quickly than light or dark wallpapers. These wallpapers require more energy to display, as they are constantly changing and updating. In addition, they require more processing power, which can also reduce your battery life. Does Using Multiple Wallpapers Drain Battery? Using multiple wallpapers can drain your battery faster than using just one. Each wallpaper requires more energy to display, so having multiple wallpapers can add up quickly and reduce your battery life. For best results, it’s recommended that you stick to one wallpaper. Does Wallpaper Quality Affect Battery Life? Higher quality wallpapers can require more energy to display and can thus drain your battery faster. Lower quality wallpapers, on the other hand, require less energy and can help conserve your battery life. For best results, it’s recommended that you use a wallpaper with a resolution that matches your device’s resolution. Does Wallpaper Size Affect Battery Life? Wallpaper size can also affect your battery life. Higher resolution wallpapers require more energy to display and can thus drain your battery faster. Lower resolution wallpapers, on the other hand, require less energy and can help conserve your battery life. For best results, it’s recommended that you use a wallpaper with a resolution that matches your device’s resolution. Does Wallpaper Refresh Rate Affect Battery Life? The refresh rate of your wallpaper can also affect your battery life. Wallpapers with a higher refresh rate require more energy to display and can thus drain your battery faster. Lower refresh rate wallpapers, on the other hand, require less energy and can help conserve your battery life. It’s recommended that you use a wallpaper with a refresh rate that matches your device’s refresh rate.  In conclusion, iOS 16 wallpapers generally have a minimal impact on battery life. The type of wallpaper you choose can make a difference in how much battery life you have, with light wallpapers requiring more energy to display while dark wallpapers require less energy. Dynamic and live wallpapers are more intensive and can drain your battery more quickly. Other factors such as wallpaper quality, size, and refresh rate can also affect battery life. Leave a Comment
__label__pos
0.999772
topical media & game development talk show tell print hush-src-multi-MultiPlayer-VMR9Subgraph.cpp / cpp //------------------------------------------------------------------------------ // File: VMR9Subgraph.cpp // // Desc: DirectShow sample code - MultiVMR9 MultiPlayer sample // // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ include <stdafx.h> include <MultiVMR9.h> include <VMR9Subgraph.h> ****************************Public*Routine******************************\ CVMR9Subgraph constructor \************************************************************************* CVMR9Subgraph::CVMR9Subgraph() : m_dwID( NULL) { m_wcPath[0] = L'\0'; m_achPath[0] = TEXT('\0'); } ****************************Public*Routine******************************\ CVMR9Subgraph destructor \************************************************************************* CVMR9Subgraph::~CVMR9Subgraph() { } ****************************Public*Routine******************************\ BuildAndRender Builds the filter graph to render the media file located at wcPath with use of VMR9; if wizard is provided, VMR9 is set to the renderless mode and custom allocator- presenter (which is pWizard in this sample) is advised. Return values: errors from the filter graph and wizard \************************************************************************* HRESULT CVMR9Subgraph::BuildAndRender( WCHAR *wcPath, CComPtr<IMultiVMR9Wizard> pWizard ) { HRESULT hr = S_OK; CComPtr<IVMRFilterConfig9> pConfig; CComPtr<IGraphBuilder> pGb; if( !wcPath ) { return E_POINTER; } USES_CONVERSION; wcsncpy( m_wcPath, wcPath, MAX_PATH); _tcsncpy( m_achPath, W2T(wcPath), MAX_PATH); // first, check that file exists if( INVALID_FILE_ATTRIBUTES == GetFileAttributes( m_achPath)) { MessageBox(NULL, TEXT("Requested media file was not found"), TEXT("Error"), MB_OK); return VFW_E_NOT_FOUND; } // create graph hr = CoCreateInstance( CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IFilterGraph, (void**)&(m_pGraph.p) ); if( FAILED(hr)) { MessageBox(NULL, TEXT("Failed to create the filter graph"), TEXT("Error"), MB_OK); return hr; } // create and add VMR9 hr = CoCreateInstance( CLSID_VideoMixingRenderer9, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)&(m_pVMR.p) ); if( FAILED(hr)) { MessageBox(NULL, TEXT("Failed to create instance of VMR9"), TEXT("Error"), MB_OK); return hr; } hr = m_pGraph->AddFilter( m_pVMR, L"VMR9"); if( FAILED(hr)) { MessageBox(NULL, TEXT("Failed to add VMR9 to the graph"), TEXT("Error"), MB_OK); return hr; } // configure VMR9 hr = m_pVMR->QueryInterface( IID_IVMRFilterConfig9, (void**)&(pConfig.p) ); if( FAILED(hr)) { MessageBox(NULL, TEXT("Cannot get IVMRFilterConfig9 from VMR9"), TEXT("Error"), MB_OK); return hr; } // if wizard is provided, set VMR to the renderless code and attach to the wizard if( pWizard ) { // set VMR to the renderless mode hr = pConfig->SetRenderingMode( VMR9Mode_Renderless ); if( FAILED(hr)) { MessageBox(NULL, TEXT("Failed to set VMR9 to the renderless mode"), TEXT("Error"), MB_OK); return hr; } hr = pWizard->Attach( m_pVMR, &m_dwID ); if( FAILED(hr)) { MessageBox(NULL, TEXT("Failed to attach graph to the wizard"), TEXT("Error"), MB_OK); return hr; } } // try to render media source hr = m_pGraph->QueryInterface( IID_IGraphBuilder, (void**)&(pGb.p) ); if( FAILED(hr)) { MessageBox(NULL, TEXT("Cannot get IGraphBuilder from the filter graph"), TEXT("Error"), MB_OK); return hr; } hr = pGb->RenderFile( m_wcPath, NULL); if( FAILED(hr)) { MessageBox(NULL, TEXT("Failed to render specified media file"), TEXT("Error"), MB_OK); return hr; } hr = CheckVMRConnection(); if( FAILED(hr)) { hr = pWizard->Detach( m_dwID ); MessageBox(NULL, TEXT("Application does not support this media type.\r\nTry some other media source"), TEXT("Error"), MB_OK); return hr; } // ok, all is rendered, now get MediaControl, MediaSeeking and continue hr = m_pGraph->QueryInterface( IID_IMediaControl, (void**)&(m_pMc.p) ); if( FAILED(hr)) { MessageBox(NULL, TEXT("Cannot find IMediaControl interface"), TEXT("Error"), MB_OK); return hr; } hr = m_pGraph->QueryInterface( IID_IMediaSeeking, (void**)&(m_pMs.p) ); if( FAILED(hr)) { MessageBox(NULL, TEXT("Cannot find IMediaSeeking interface"), TEXT("Error"), MB_OK); return hr; } return hr; } ****************************Public*Routine******************************\ CheckVMRConnection \************************************************************************* HRESULT CVMR9Subgraph::CheckVMRConnection() { HRESULT hr = S_OK; bool bConnected = false; CComPtr<IEnumPins> pEnum; CComPtr<IPin> pPin; if( !m_pVMR ) return E_UNEXPECTED; hr = m_pVMR->EnumPins( &pEnum ); if( FAILED(hr)) return hr; hr = pEnum->Next( 1, &pPin, NULL); while( SUCCEEDED(hr) && pPin) { CComPtr<IPin> pConnectedPin; hr = pPin->ConnectedTo( &pConnectedPin ); if( SUCCEEDED(hr) && pConnectedPin ) { bConnected = true; break; } pPin = NULL; hr = pEnum->Next( 1, &pPin, NULL); }// while hr = (true == bConnected) ? S_OK : E_FAIL; return hr; } ****************************Public*Routine******************************\ Run \************************************************************************* HRESULT CVMR9Subgraph::Run() { HRESULT hr = S_OK; if( !m_pMc ) { return E_UNEXPECTED; } hr = m_pMc->Run(); return hr; } ****************************Public*Routine******************************\ Pause \************************************************************************* HRESULT CVMR9Subgraph::Pause() { HRESULT hr = S_OK; if( !m_pMc ) { return E_UNEXPECTED; } hr = m_pMc->Pause(); return hr; } ****************************Public*Routine******************************\ Stop \************************************************************************* HRESULT CVMR9Subgraph::Stop() { HRESULT hr = S_OK; OAFilterState state; if( !m_pMc ) { return E_UNEXPECTED; } hr = m_pMc->Stop(); state = State_Running; while( State_Stopped != state && SUCCEEDED(hr)) { hr = m_pMc->GetState(100, &state); Sleep(100); } return hr; } ****************************Public*Routine******************************\ GetState Returns OAFilterState from IMediaControl of the graph Return values: errors from the filter graph and wizard \************************************************************************* OAFilterState CVMR9Subgraph::GetState() { OAFilterState state = State_Stopped; if( m_pMc ) { HRESULT hr = m_pMc->GetState( 20, &state ); } return state; } ****************************Public*Routine******************************\ SetTime \************************************************************************* HRESULT CVMR9Subgraph::SetTime( LONGLONG llCur) { HRESULT hr = S_OK; LONGLONG llDur = 0L; if( !m_pMs ) return E_FAIL; hr = m_pMs->SetPositions( &llCur, AM_SEEKING_AbsolutePositioning, &llDur, AM_SEEKING_NoPositioning); return hr; } ****************************Public*Routine******************************\ GetTimes \************************************************************************* HRESULT CVMR9Subgraph::GetTimes( LONGLONG& llCur, LONGLONG& llDur) { HRESULT hr = S_OK; if( !m_pMs ) return E_FAIL; hr = m_pMs->GetPositions( &llCur, &llDur ); return hr; } ****************************Public*Routine******************************\ GetPathT, GetPathW \************************************************************************* void CVMR9Subgraph::GetPathT( TCHAR* achPath ) { if( achPath ) { _tcscpy( achPath, m_achPath); } } void CVMR9Subgraph::GetPathW( WCHAR* wcPath ) { if( wcPath ) { wcscpy( wcPath, m_wcPath); } } ****************************Public*Routine******************************\ DestroyGraph Stops the graph, destroys and removes all the filters (VMR9 is removed last) \************************************************************************* HRESULT CVMR9Subgraph::DestroyGraph() { HRESULT hr = S_OK; OAFilterState state; if( !m_pGraph ) { return E_POINTER; } FILTER_INFO fi; CComPtr<IMediaControl> pMc; CComPtr<IEnumFilters> pEnum; CComPtr<IBaseFilter> pFilter; CComPtr<IBaseFilter> pVMR = NULL; // 1. stop the graph hr = m_pGraph->QueryInterface( IID_IMediaControl, (void**)&(pMc.p) ); if( FAILED(hr)) { return hr; } do { hr = pMc->GetState(100, &state); } while( S_OK == hr && State_Stopped != state ); hr = m_pGraph->EnumFilters( &(pEnum.p) ); if( FAILED(hr)) { return hr; } // tear off hr = pEnum->Next(1, &(pFilter.p), NULL); while( S_OK == hr && pFilter ) { hr = DisconnectPins( pFilter ); pFilter = NULL; hr = pEnum->Next(1, &(pFilter.p), NULL); } pFilter = NULL; // remove filters hr = pEnum->Reset(); hr = pEnum->Next(1, &(pFilter.p), NULL); while( S_OK == hr && pFilter ) { hr = pFilter->QueryFilterInfo( &fi); if( fi.pGraph) fi.pGraph->Release(); if( 0 == wcscmp( fi.achName, L"VMR9")) { pVMR = pFilter; } hr = m_pGraph->RemoveFilter( pFilter); pFilter = NULL; hr = pEnum->Reset(); hr = pEnum->Next(1, &pFilter, NULL); } pFilter = NULL; pEnum = NULL; pVMR = NULL; return S_OK; } ****************************Public*Routine******************************\ DisconnectPins Disconnects pins of a filter \************************************************************************* HRESULT CVMR9Subgraph::DisconnectPins( CComPtr<IBaseFilter> pFilter) { HRESULT hr = S_OK; CComPtr<IEnumPins> pEnum; CComPtr<IPin> pPin; if( !pFilter ) { return E_POINTER; } hr = pFilter->EnumPins( &pEnum ); if( FAILED(hr)) { return hr; } hr = pEnum->Next( 1, &pPin, NULL); while( S_OK == hr && pPin ) { hr = pPin->Disconnect(); pPin = NULL; hr = pEnum->Next( 1, &pPin, NULL); } pPin = NULL; pEnum = NULL; return S_OK; } (C) Æliens 20/2/2008 You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.
__label__pos
0.997377
Requesting-console-program-in-pseudocode-computer-science-homework-help Get perfect grades by consistently using Writerbay.net writing services. Place your order and get a quality paper today. Take advantage of our current 20% discount by using the coupon code GET20 Order a Similar Paper Order a Different Paper Software applications are created to solve problems that a business or even an individual might have. Planning is a crucial step in the software development process. Applications may not achieve the intended goal unless properly planned. Imagine that you are a programming consultant. One of your smaller clients needs your help writing a program. Your client has an e-commerce Web site but wants to avoid being sued for allowing children to make purchases without the authorization of their parents. Prepare a document that guides your client in program preparation and includes an example console program. The console program must verify the age of a customer attempting to make an online purchase. The program must prompt the customer for his or her year of birth, and it will calculate whether the customer is over 18 years old. The program will then display a message to the customer that his or her purchase request is accepted or denied. Your paper must include the following 5 parts in addition to the coded solution: • A problem analysis chart with each of the following sections: 1. Given information 2. Required results 3. Processing required to obtain the results 4. Solution alternatives • A flowchart showing the program processing flow • A chart showing input, output, and processing • An algorithm in pseudocode describing the steps the program will perform. This pseudocode algorithm would consist of a list of steps explaining the sequence of tasks the program will follow to complete the task. • The console program solution with a screenshot of the executed program. Do you need help with this or a different assignment? We offer CONFIDENTIAL, ORIGINAL (Turnitin/LopesWrite/SafeAssign checks), and PRIVATE services using latest (within 5 years) peer-reviewed articles. Kindly click on ORDER NOW to receive an A++ paper from our masters- and PhD writers. Get a 15% discount on your order using the following coupon code SAVE15 Order a Similar Paper Order a Different Paper
__label__pos
0.687332
Java-Gaming.org Hi ! Featured games (85) games approved by the League of Dukes Games in Showcase (636) Games in Android Showcase (178) games submitted by our members Games in WIP (688) games currently in development News: Read the Java Gaming Resources, or peek at the official Java tutorials       Home     Help   Search   Login   Register    Pages: [1]   ignore  |  Print     Trouble getting started  (Read 3835 times) 0 Members and 1 Guest are viewing this topic. Offline jparril1 Junior Devvie « Posted 2011-01-18 01:43:55 » Hey everyone,        So you have all given me some help before getting started using Java for games, but I feel like Im hitting a huge wall. All of the resources Ive used seem like they are not writing for a beginner. I have Killer Game Programming and it just has been a bunch of code with little explanation. I am not a beginner programmer, but I am a total newbie to graphics and games. I feel like I am not learning the basic game framework from the resources I have used. I went through Kev's Space Invaders tutorial over at his website cokeandcode, but I found myself getting lost in the complex parts. I am not an idiot, but is it impossible to find some sort of step by step intro that explains how to build a simple game from nothing? Ive created quite advanced applications for my CS classes, so I know Im not just a terrible programmer, I am just having a lot of trouble understanding the basics here.. such as loading images, painting to the screen, getting input, updating, etc. I thought I would stick with the basic JAva2d stuff because it would be better for me then diving into something like LWJGL, but I cant even seem to grasp this! It seems like every tutorial I read is a completely different approach. Just something as simple as loading a saved image to the screen has been done in so many ways... one book uses Image, another uses ImageIcon, another uses VolatileImage, another uses Sprite, etc, etc.. and thats just to load an image! Not to mention the method for painting and updating is so different and hard to grasp from one tutorial to the next, some are using Jpanels, others use Canvases, etc.         All I want to do is make something very basic like pong or whatever. If I can make that and TOTALLY understand whats happening throughout the code, and I can write it on my own without the guide, Im sure I can build off of that to make things more complex. I just feel like my brain is mush when I read these books and tutorials, nothing is clicking and Im becoming unbelievably frustrated. Ive always been a pretty good programmer but I feel totally useless at this. Can anyone lend a word of advice or whatever? Offline avm1979 « Reply #1 - Posted 2011-01-18 02:07:38 » It sounds like you're looking for "the right way" to do 2d in java, and that's a source of frustration.  But as usual in the real world, there isn't one - there are many different ways, which are good or bad depending on what your goals are. For something basic like pong, you'll have to: 1) draw stuff on the screen (note I didn't say load images - you can get away with simple shapes for this) 2) process input in some way 3) use some kind of timer to base your game logic off of, and update the game world As long as you find and understand *a* way to do all three of the above, you'll be off to a good start.  Don't worry about whether it's a particularly good way - that'll become more clear as you get more experience.  Usually you'll just run into some limitation of the way you're doing it and then switch to a different way that fits your needs better.  No need to try to understand it all at once. Best of luck to you! Offline SwampChicken « Reply #2 - Posted 2011-01-18 04:47:23 » Agreed. Break it down into smaller projects. - project 1. display a jframe. - project 2. draw something in a frame (a box?) - project 3. draw the box in a frame and make it move over a period of time (animate) - project 4. draw multiples boxes in the same frame and move them around over time. - project 5. draw a box in a frame & control it's movement via user input (key/mouse?) - project 6. stitch the above projects together to get a crude game working. Games published by our own members! Check 'em out! Legends of Yore - The Casual Retro Roguelike Offline jparril1 Junior Devvie « Reply #3 - Posted 2011-01-18 05:39:21 » thanks to the both of you. So I managed to put this bit together tonight.  if you keep the part where I paint paddle 1 commented out, it works fine, but if I un-comment it, the rectangle never gets painted. I don't understand why. If the ball paints and repaints with no problem, I don't see why the rectangle shouldn't. I also get some strange errors when I try to paint the rectangle, but not always.. any ideas? Also, am I doing anything here that can be done better or different? Thanks 1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38   39   40   41   42   43   44   45   46   47   48   49   50   51   52   53   54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69   70   71   72   73   74   75   76   77   78   79   80   81   82   83   84   85   86   87   88   89   90   package pong; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.geom.Ellipse2D; import javax.swing.JFrame; public class Game extends JFrame implements Runnable {    private Rectangle paddleOne;    private Rectangle paddleTwo;    private int ballXPosition;    private int ballYPosition;    private int ballRadius;    private int ballXSpeed;    private int ballYSpeed;    Thread aThread;    public Game() {       setSize(640, 480);       setTitle("Pong... Almost");       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       setResizable(false);       setVisible(true);       paddleOne = new Rectangle(0, 0, 5, 25);       paddleTwo = new Rectangle(this.getWidth() - 5, 0, 5, 25);       ballXPosition = this.getWidth() / 2;       ballYPosition = this.getHeight() / 2;       ballRadius = 15;       ballXSpeed = 2;       ballYSpeed = 2;    }    public void paint(Graphics g) {       // background       g.setColor(Color.gray);       g.fillRect(0, 0, 640, 480);             //ball       g.setColor(Color.blue);       g.fillOval(ballXPosition, ballYPosition, ballRadius * 2, ballRadius * 2);       //paddle 1       //g.setColor(Color.red);       //g.fillRect(paddleOne.x, paddleOne.y, paddleOne.width, paddleOne.height);    }    public void run() {       //loop to constantly repaint the screen       while(true) {          /* Collision detections between the ball and all four walls*/          if(ballXPosition > this.getWidth() - (ballRadius * 2)) {             ballXSpeed = -2;          }          else if(ballXPosition < 0) {             ballXSpeed = 2;          }          if(ballYPosition > this.getHeight() - (ballRadius * 2)) {             ballYSpeed = -2;          }          else if(ballYPosition < ballRadius * 2) {             ballYSpeed = 2;          }          ballXPosition += ballXSpeed;          ballYPosition += ballYSpeed;          repaint();          try {             Thread.sleep(20);          } catch (InterruptedException e) {             e.printStackTrace();          }       }    } } 1   2   3   4   5   6   7   8   9   10   11   12   package pong; public class GameDriver {        public static void main(String[] args) {             Game gameTest = new Game();       gameTest.run();          } } Offline loom_weaver JGO Coder Medals: 17 « Reply #4 - Posted 2011-01-18 07:20:29 » I can see your paddle.  The only problem is that it's so small (0, 0, 5, 25) that you can barely see it in the top left corner. Another thing I would read up on is passive vs active rendering.  Passive rendering uses the Event Dispatch Thread closely associated with Java Swing etc.  It kind of sucks having to learn about this stuff right away but I noticed you spawned a new thread.  Combining passive rendering with with threading without fully understanding what's going on will likely have you running into many hard to detect concurrency errors. To be safe for now use a Timer instead of a new thread. ps. the bouncing ball looks good... you're off to a good start! Offline bigwavejake Innocent Bystander « Reply #5 - Posted 2011-01-18 13:28:40 » I've found this site to be helpful when I started learning how to do 2d games: http://zetcode.com/tutorials/javagamestutorial/ Offline jparril1 Junior Devvie « Reply #6 - Posted 2011-01-18 15:51:20 » loom weaver - thanks! Its so weird, my rectangle was being drawn completely off screen. I thought drawing it at 0, 0 would make it visible but I had to shift it quite a bit. Anyway it works so thanks a lot. And I am going to change the Thread and use a timer instead to repaint every 20ms. bigwavejake - thanks so much, that seems like a solid tutorial So reacting to key presses is confusing me, I added an inner keyadapter class, but Im sure Im doing it wrong because nothing is working: 1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38   39   40   41   42   43   44   45   46   47   48   49   50   51   52   53   54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69   70   71   72   73   74   75   76   77   78   79   80   81   82   83   84   85   86   87   88   89   90   91   92   93   94   95   96   97   98   99   100   101   102   103   104   105   106   107   108   109   110   111   112   113   114   115   package pong; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.geom.Ellipse2D; import java.util.Timer; import javax.swing.JFrame; public class Game extends JFrame {    private Rectangle paddleOne;    private Rectangle paddleTwo;    private int ballXPosition;    private int ballYPosition;    private int ballRadius;    private int ballXSpeed;    private int ballYSpeed;    Timer gameTimer;    public Game() {       setSize(640, 480);       setTitle("Pong... Almost");       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       addKeyListener(null);       setResizable(false);       setVisible(true);       paddleOne = new Rectangle(5, 75, 15, 80);       paddleTwo = new Rectangle(this.getWidth() - 20, 75, 15, 80);       ballXPosition = this.getWidth() / 2;       ballYPosition = this.getHeight() / 2;       ballRadius = 15;       ballXSpeed = 2;       ballYSpeed = 2;    }    public void paint(Graphics g) {       // background       g.setColor(Color.gray);       g.fillRect(0, 0, 640, 480);       //ball       g.setColor(Color.blue);       g.fillOval(ballXPosition, ballYPosition, ballRadius * 2, ballRadius * 2);       //paddle 1       g.setColor(Color.red);       g.fillRect(paddleOne.x, paddleOne.y, paddleOne.width, paddleOne.height);       //paddle2       g.fillRect(paddleTwo.x, paddleTwo.y, paddleTwo.width, paddleTwo.height);    }    public void run() {       //loop to constantly repaint the screen       while(true) {          /* Collision detections between the ball and all four walls*/          if(ballXPosition > this.getWidth() - (ballRadius * 2)) {             ballXSpeed = -2;          }          else if(ballXPosition < 0) {             ballXSpeed = 2;          }          if(ballYPosition > this.getHeight() - (ballRadius * 2)) {             ballYSpeed = -2;          }          else if(ballYPosition < ballRadius * 2) {             ballYSpeed = 2;          }          ballXPosition += ballXSpeed;          ballYPosition += ballYSpeed;          repaint();          try {             Thread.sleep(20);          } catch (InterruptedException e) {             e.printStackTrace();          }       }    }    private class KeyListener extends KeyAdapter {       public void KeyPressed(KeyEvent e) {          int key = e.getKeyCode();          if (key == KeyEvent.VK_UP) {             paddleOne.y -= 5;          }          if (key == KeyEvent.VK_DOWN) {             paddleOne.y += 5;          }       }    } } Can you guys help me out Offline aazimon « Reply #7 - Posted 2011-01-18 17:09:09 » You need to make your Game class to listen for key events. Take this class as an example. It's pretty is pretty simple. In your frame's constructor add: addKeyListener(new Listener()); import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; public class Frame extends JFrame {     public Frame(String title) {         super(title);                 addKeyListener(new Listen());     }     public class Listen implements KeyListener {        public void keyPressed(KeyEvent e) {       System.out.println("Key Pressed");       // TODO Auto-generated method stub        }        public void keyReleased(KeyEvent e) {       // TODO Auto-generated method stub        }        public void keyTyped(KeyEvent e) {       // TODO Auto-generated method stub        }     } } Offline jparril1 Junior Devvie « Reply #8 - Posted 2011-01-18 17:28:36 » Ahh thanks.. it works! Ok next problem is that it doesnt seem to be able to detect simultaneous key presses. If Im holding the up arrow and moving the right paddle up, I am unable to detect a "W" press to move the left paddle up at the same time. If I hold them both, one will start moving only when I release the other. I tried making two separate inner class KeyListeners... one for the first paddle and one for the second, and just adding them both to my constructor but that isnt working either. Any ideas? Offline loom_weaver JGO Coder Medals: 17 « Reply #9 - Posted 2011-01-18 17:35:04 » Check out KEY_DOWN vs KEY_PRESSED events. Games published by our own members! Check 'em out! Legends of Yore - The Casual Retro Roguelike Offline jparril1 Junior Devvie « Reply #10 - Posted 2011-01-18 18:08:12 » Ok so Im still working out getting the keys to work simultaneously, but heres what I have so far. Would you guys mind running it and letting me know if the collisions are looking ok? Since the window is decorated, I seem to be losing pixels on the top of the frame, so I had to use some weird numbers in my collisions to make it seem like the ball was hitting the walls and the paddles stopped at the edges. If I assumed that the edge that I could see was the actual border of the Frame, the objects would just go off of the screen. any critiques?? By the way I added a ball velocity as a constant, so you can just change the value of BALL_VELOCITY at the beginning to make it easier to change the ball speed. Sometimes its easier to see the collisions at a low speed, so you can just speed it up if its too slow. 1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38   39   40   41   42   43   44   45   46   47   48   49   50   51   52   53   54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69   70   71   72   73   74   75   76   77   78   79   80   81   82   83   84   85   86   87   88   89   90   91   92   93   94   95   96   97   98   99   100   101   102   103   104   105   106   107   108   109   110   111   112   113   114   115   116   117   118   119   120   121   122   123   124   125   126   127   128   129   130   131   132   133   134   135   136   137   138   139   140   141   142   143   144   145   146   147   148   149   150   151   152   153   154   155   156   157   158   159   160   161   162   163   164   165   166   167   168   169   170   171   172   173   174   175   176   177   178   179   180   181   182   183   package pong; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.geom.Ellipse2D; import java.util.Timer; import javax.swing.JFrame; public class Game extends JFrame {    private final int BALL_VELOCITY;    private Rectangle paddleOne;    private Rectangle paddleTwo;    private int ballXPosition;    private int ballYPosition;    private int ballRadius;    private int ballXSpeed;    private int ballYSpeed;    Timer gameTimer;    public Game() {       setSize(640, 480);       setTitle("Pong... Almost");       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       addKeyListener(new PaddleOneKeyListen());       addKeyListener(new PaddleTwoKeyListen());       setResizable(false);       setVisible(true);       paddleOne = new Rectangle(5, 75, 15, 80);       paddleTwo = new Rectangle(this.getWidth() - 20, 75, 15, 80);       ballXPosition = this.getWidth() / 2;       ballYPosition = this.getHeight() / 2;       ballRadius = 15;             BALL_VELOCITY = 2;       ballXSpeed = BALL_VELOCITY;       ballYSpeed = BALL_VELOCITY;          }    public void paint(Graphics g) {       // background       g.setColor(Color.gray);       g.fillRect(0, 0, 640, 480);       //ball       g.setColor(Color.blue);       g.fillOval(ballXPosition, ballYPosition, ballRadius * 2, ballRadius * 2);       //paddle 1       g.setColor(Color.red);       g.fillRect(paddleOne.x, paddleOne.y, paddleOne.width, paddleOne.height);       //paddle2       g.fillRect(paddleTwo.x, paddleTwo.y, paddleTwo.width, paddleTwo.height);    }    public void run() {       //loop to constantly repaint the screen       while(true) {                    //collision detection between the ball and paddles          if ((paddleOne.x + 15) >= ballXPosition &&                paddleOne.y <= ballYPosition && paddleOne.y + paddleOne.height >= ballYPosition) {                         ballXSpeed = BALL_VELOCITY;          }                    if (paddleTwo.x <= (ballXPosition + (ballRadius * 2)) &&                paddleTwo.y <= ballYPosition && paddleTwo.y + paddleTwo.height >= ballYPosition) {                         ballXSpeed = -(BALL_VELOCITY);          }          /* Collision detections between the ball and all four walls*/          if(ballXPosition > this.getWidth() - (ballRadius * 2)) {             ballXSpeed = -(BALL_VELOCITY);          }          else if(ballXPosition < 0) {             ballXSpeed = BALL_VELOCITY;          }          if(ballYPosition > this.getHeight() - (ballRadius * 2)) {             ballYSpeed = -(BALL_VELOCITY);          }          else if(ballYPosition < ballRadius * 2) {             ballYSpeed = BALL_VELOCITY;          }          ballXPosition += ballXSpeed;          ballYPosition += ballYSpeed;          repaint();          try {             Thread.sleep(20);          } catch (InterruptedException e) {             e.printStackTrace();          }       }    }    private class PaddleOneKeyListen implements KeyListener {             @Override             public void keyPressed(KeyEvent e) {          int key = e.getKeyCode();          //paddle one movement          if (key == KeyEvent.VK_W && paddleOne.y >= 30) {             paddleOne.y -= 10;          }          if (key == KeyEvent.VK_S && paddleOne.y < 395 ) {             paddleOne.y += 10;          }       }       @Override       public void keyReleased(KeyEvent arg0) {          // TODO Auto-generated method stub       }       @Override       public void keyTyped(KeyEvent arg0) {          // TODO Auto-generated method stub       }    }        private class PaddleTwoKeyListen implements KeyListener {       @Override       public void keyPressed(KeyEvent e) {          int key = e.getKeyCode();          //paddle two movement          if (key == KeyEvent.VK_UP && paddleTwo.y >= 30) {             paddleTwo.y -= 10;          }          if (key == KeyEvent.VK_DOWN && paddleTwo.y != 395) {             paddleTwo.y += 10;          }       }       @Override       public void keyReleased(KeyEvent arg0) {          // TODO Auto-generated method stub       }       @Override       public void keyTyped(KeyEvent arg0) {          // TODO Auto-generated method stub       }    } } 1   2   3   4   5   6   7   8   9   10   11   12   package pong; public class GameDriver {        public static void main(String[] args) {             Game gameTest = new Game();       gameTest.run();          } } Offline SimonH « Reply #11 - Posted 2011-01-18 19:10:34 » Don't add more than one key listener! Have global variables for the actions you want. Like; 1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38   39   40   41   42   43      boolean goLeft=false;     boolean goRight=false;     addKeyListener(new myKeyListener());     while (gameRunning)     {         if (goLeft  && paddleOne.y >= 30)         {                 paddleOne.y -= 10;         }         ... etc...     }     private class myKeyListener implements KeyListener {          public void keyPressed(KeyEvent e) {             int key = e.getKeyCode();             if (key == KeyEvent.VK_W) {                 goLeft=true;             }             if (key == KeyEvent.VK_E) {                 goRight=true;             }             ... other keys         }           @Override         public void keyReleased(KeyEvent arg0) {             if (key == KeyEvent.VK_W) {                 goLeft=false;             }             if (key == KeyEvent.VK_E) {                 goRight=false;             }              ... other keys         }           @Override         public void keyTyped(KeyEvent arg0) {             // TODO Auto-generated method stub           }     } Get the idea? The booleans separate the game logic from the key events. People make games and games make people Offline jparril1 Junior Devvie « Reply #12 - Posted 2011-01-18 21:12:38 » Gotcha, thanks! Im still working out how to get it to respond to simultaneous key presses so that two people can play against each other. Ill post updated code when I get to it. Offline Captain Awesome Junior Devvie Medals: 2 Hi « Reply #13 - Posted 2011-01-18 21:38:28 » Gotcha, thanks! Im still working out how to get it to respond to simultaneous key presses so that two people can play against each other. Ill post updated code when I get to it. What I like to do is the following: 1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   private boolean[] keys = new boolean [525];     @Override     public void keyTyped(KeyEvent e) {             }     @Override     public void keyPressed(KeyEvent e) {         keys[e.getKeyCode()] = true;     }     @Override     public void keyReleased(KeyEvent e) {         keys[e.getKeyCode()] = false;     } If I want to check if a key is pressed down I just do the following: 1   2   3   if(keys[KeyEvent.VK_UP]) {             //Do stuff here         } If the key has been pressed (in this case the up arrowkey), the boolean at that index will be true which means the code inside the block will run. However if the key has been released the boolean in that index will be false. Not saying it's the best method, just how I do it Smiley Offline Eli Delventhal JGO Kernel Medals: 42 Projects: 11 Exp: 10 years Game Engineer « Reply #14 - Posted 2011-01-18 21:57:37 » In a similar vein, you can also use a set instead of an array. 1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   TreeSet<Integer> buttonsPressed; void keyPressed(KeyEvent e) {     buttonsPressed.add(new Integer(e.getKeyCode())); } void keyReleased(KeyEvent e) {     buttonsPressed.remove(new Integer(e.getKeyCode())); } void doButtonStuff() {     //Process all of the presses     for (Iterator<Integer> i = buttonsPressed.iterator(); i.hasNext();)     {         doButtonThing(i.next().intValue());     }     //Or check for just one     if (buttonsPressed.contains(new Integer(KeyEvent.VK_SPACE)))     {         doSpaceThing();     } } Doing it without an array is: - (maybe) slightly more memory efficient - much slower accessing and adding elements - significantly slower checking whether many individual buttons are down - faster at checking against all buttons that are down - easier to see exactly how many buttons are being pressed Honestly in most situations I think it's easier just to use arrays like Captain Awesome suggested, but this option can work better depending on what you want to do. BTW, I used a TreeSet because it enforces uniqueness (you can't add the same button multiple times), and because it's automatically sorted doing a contains() check is much faster than in a list. Still, a typical user will only press like 4 buttons at once maximum, so none of these micro-optimizations really matter in the end. See my work: OTC Software Offline aazimon « Reply #15 - Posted 2011-01-18 22:56:01 » With the multiple keys being pressed, something goofy goes on. Like posted, you need to use a boolean to keep track of what keys are being pressed. Here's a simple example. Each loop, you need to check if the key is pressed (true) or not. 1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38   39   40   41   42   43   44   45   46   47   48   49   50   51   52   53   54   55   56   public class Frame extends JFrame {     private boolean wPress = false;     private boolean ePress = false;     public Frame(String title) {         super(title);                 addKeyListener(new Listen());     }     public void paint(Graphics g) {         super.paint(g);         if (wPress) {             System.out.println("W press");         }         if (ePress) {             System.out.println("E press");         }     }         public void run() {    //loop to constantly repaint the screen    while(true) {                repaint();        try {       Thread.sleep(20);        } catch (InterruptedException e) {           //        }    }     }         public class Listen implements KeyListener {        public void keyPressed(KeyEvent e) {       if (e.getKeyCode() == KeyEvent.VK_W) {           wPress = true;       }       if (e.getKeyCode() == KeyEvent.VK_E) {           ePress = true;       }        }        public void keyReleased(KeyEvent e) {       if (e.getKeyCode() == KeyEvent.VK_W) {           wPress = false;       }       if (e.getKeyCode() == KeyEvent.VK_E) {           ePress = false;       }        }        public void keyTyped(KeyEvent e) {       // TODO Auto-generated method stub        }     } } Offline jparril1 Junior Devvie « Reply #16 - Posted 2011-01-19 23:17:29 » I see what you guys are saying. Can anyone explain why exactly it works when having the keylistener set a boolean instead of directly changing the paddles position? Like I said it totally doesnt recognize two keys being held down when I do it my way, so why does it work using booleans? Just trying to understand whats happening Smiley Offline aazimon « Reply #17 - Posted 2011-01-19 23:36:59 » I'm not sure what's happening. I have noticed that when you press a second key down, the first key pressed no longer fires a key event. It appears to be more part of the OS then JAVA. When you bring up a text editor and press and hold one key then type another, the stops printing out the first key. Offline jparril1 Junior Devvie « Reply #18 - Posted 2011-01-19 23:43:36 » Just wanted to update... I changed my code to use booleans like youve suggested. The performance increased by at least 500% lol. The paddles are now super responsive its ridiculous. I might actually have to turn down their speed. Thank you so much! Why the hell does that make such a huge difference?? Heres what Ive done so far. Added scores and all that. I NEED to use double buffering because the flickering is killing me! Any critiques?? 1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38   39   40   41   42   43   44   45   46   47   48   49   50   51   52   53   54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69   70   71   72   73   74   75   76   77   78   79   80   81   82   83   84   85   86   87   88   89   90   91   92   93   94   95   96   97   98   99   100   101   102   103   104   105   106   107   108   109   110   111   112   113   114   115   116   117   118   119   120   121   122   123   124   125   126   127   128   129   130   131   132   133   134   135   136   137   138   139   140   141   142   143   144   145   146   147   148   149   150   151   152   153   154   155   156   157   158   159   160   161   162   163   164   165   166   167   168   169   170   171   172   173   174   175   176   177   178   179   180   181   182   183   184   185   186   187   188   189   190   191   192   193   194   195   196   197   198   199   200   201   202   203   204   205   206   207   208   209   210   211   212   213   214   215   216   217   218   219   220   221   222   223   224   225   226   227   228   229   230   231   232   233   234   235   236   237   238   239   package pong; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.Timer; import javax.swing.JFrame; public class Game extends JFrame {        private static final long serialVersionUID = 1L;        private Rectangle paddleOne;    private Rectangle paddleTwo;    private int ballXPosition;    private int ballYPosition;    private final int BALL_VELOCITY;    private final int BALL_RADIUS;    private int ballXSpeed;    private int ballYSpeed;    Timer gameTimer;        int playerOneScore;    int playerTwoScore;        //booleans for key presses    private boolean wPressed;    private boolean sPressed;    private boolean upPressed;    private boolean downPressed;    public Game() {       setSize(640, 480);       setTitle("Pong... Almost");       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       addKeyListener(new KeyListen());       setResizable(false);       setVisible(true);             playerOneScore = 0;       playerTwoScore = 0;       paddleOne = new Rectangle(5, 75, 15, 80);       paddleTwo = new Rectangle(this.getWidth() - 20, 75, 15, 80);       ballXPosition = this.getWidth() / 2;       ballYPosition = this.getHeight() / 2;       BALL_RADIUS = 10;             BALL_VELOCITY = 8;       ballXSpeed = BALL_VELOCITY;       ballYSpeed = BALL_VELOCITY;             wPressed = false;       sPressed = false;       upPressed = false;       downPressed = false;          }    public void paint(Graphics g) {       // background       g.setColor(Color.black);       g.fillRect(0, 0, 640, 480);       //ball       g.setColor(Color.green);       g.fillOval(ballXPosition, ballYPosition, BALL_RADIUS * 2, BALL_RADIUS * 2);       //paddle 1       g.setColor(Color.green);       g.fillRect(paddleOne.x, paddleOne.y, paddleOne.width, paddleOne.height);       //paddle2       g.fillRect(paddleTwo.x, paddleTwo.y, paddleTwo.width, paddleTwo.height);             //score       g.setFont(new Font("Arial Bold", Font.PLAIN, 40));       g.drawString(Integer.toString(playerOneScore), 250, 75);       g.drawString(Integer.toString(playerTwoScore), 350, 75);    }    public void run() {       //loop to constantly repaint the screen       while(true) {                    //collision detection between the ball and paddles          if ((paddleOne.x + 15) >= ballXPosition &&                paddleOne.y <= ballYPosition && paddleOne.y + paddleOne.height >= ballYPosition) {                         ballXSpeed = BALL_VELOCITY;          }                    if (paddleTwo.x <= (ballXPosition + (BALL_RADIUS * 2)) &&                paddleTwo.y <= ballYPosition && paddleTwo.y + paddleTwo.height >= ballYPosition) {                         ballXSpeed = -(BALL_VELOCITY);          }          /* Collision detections between the ball and all four walls*/          if(ballXPosition > this.getWidth() - (BALL_RADIUS * 2)) {             ballXSpeed = -(BALL_VELOCITY);                         playerOneScore++;          }          else if(ballXPosition < 0) {             ballXSpeed = BALL_VELOCITY;                         playerTwoScore++;          }          if(ballYPosition > this.getHeight() - (BALL_RADIUS * 2)) {             ballYSpeed = -(BALL_VELOCITY);          }          else if(ballYPosition < BALL_RADIUS * 2) {             ballYSpeed = BALL_VELOCITY;          }          ballXPosition += ballXSpeed;          ballYPosition += ballYSpeed;                    //moving paddles          if (wPressed) {             paddleOne.y -= 10;          }          if (sPressed) {             paddleOne.y += 10;          }          if (upPressed){             paddleTwo.y -= 10;          }          if (downPressed) {             paddleTwo.y += 10;          }          repaint();                    //set all key presses to false if paddles are going off screen.. fix this its sloppy!          if (paddleOne.y <= 30) {             wPressed = false;          }          if (paddleOne.y > 395 ) {             sPressed = false;          }          if (paddleTwo.y <= 30) {             upPressed = false;          }          if (paddleTwo.y > 395) {             downPressed = false;          }                              try {             Thread.sleep(20);          } catch (InterruptedException e) {             e.printStackTrace();          }       }    }    private class KeyListen implements KeyListener {       @Override       public void keyPressed(KeyEvent e) {          int key = e.getKeyCode();          //paddle one move          if (key == KeyEvent.VK_W && paddleOne.y >= 30) {             wPressed = true;          }          if (key == KeyEvent.VK_S && paddleOne.y < 395 ) {             sPressed = true;          }          //paddle two move          if (key == KeyEvent.VK_UP && paddleTwo.y >= 30) {             upPressed = true;          }          if (key == KeyEvent.VK_DOWN && paddleTwo.y < 395) {             downPressed = true;          }       }       @Override       public void keyReleased(KeyEvent e) {                    int key = e.getKeyCode();          //paddle one stop          if (key == KeyEvent.VK_W) {             wPressed = false;          }          if (key == KeyEvent.VK_S) {             sPressed = false;          }          //paddle two stop          if (key == KeyEvent.VK_UP) {             upPressed = false;          }          if (key == KeyEvent.VK_DOWN) {             downPressed = false;          }       }       @Override       public void keyTyped(KeyEvent arg0) {          // TODO Auto-generated method stub       }    }         } 1   2   3   4   5   6   7   8   9   10   11   12   package pong; public class GameDriver {        public static void main(String[] args) {             Game gameTest = new Game();       gameTest.run();          } } Offline aazimon « Reply #19 - Posted 2011-01-20 16:13:25 » For what your trying to accomplish. This is fine. Going forward you may want to look at extracting out pieces of the code so you can easily re-use it. Ways to do this varies drastically. Offline kappa « League of Dukes » JGO Kernel Medals: 100 Projects: 15 ★★★★★ « Reply #20 - Posted 2011-01-20 16:19:43 » You could start with the LWJGL Basics tutorial series found here. The current 4 parts should get you to Pong level in a simple and concise manner. Thereafter I recommend you jump to Slick2D, its the best 2d java games library at the moment and is probably the most well documented (see its wiki) not to forget its really helpful community. Going down the Swing/Java2D/AWT road eventually leads to a dead end as those libraries just aren't designed for games. Offline Eli Delventhal JGO Kernel Medals: 42 Projects: 11 Exp: 10 years Game Engineer « Reply #21 - Posted 2011-01-20 16:57:50 » I'm guessing your speed difference is because you used to be adjusting the paddle's position from within keyPressed, and now you're doing it within your game loop. Your game loop appears to fire every 20ms - the EDT (Event Dispatch Thread, which is what calls keyPressed etc.) must be firing less often than that. To get something similar, you can increase the length of your Thread.sleep(), or you can just move your paddle by less distance every time, which is what I would recommend because a 20ms delay is already only 50fps. The difference between the booleans and the way you were doing it before is that the OS will only fire an event for the most recent key. Because you're storing every key you've ever seen, you get to jump over this hurdle by remembering what was pressed independently of the OS. See my work: OTC Software Offline Gudradain « Reply #22 - Posted 2011-01-20 17:32:46 » Going down the Swing/Java2D/AWT road eventually leads to a dead end as those libraries just aren't designed for games. Really? I don't really see how this can be true. It's best to avoid as much as possible Swing/AWT but Java2D is good enough. Offline kappa « League of Dukes » JGO Kernel Medals: 100 Projects: 15 ★★★★★ « Reply #23 - Posted 2011-01-20 19:11:20 » Really? I don't really see how this can be true. It's best to avoid as much as possible Swing/AWT but Java2D is good enough. Given that Java2D has improved in the last few releases but its still factors slower then what the OpenGL bindings can do and pretty much impossible to pull of a modern looking game with it. Also don't forget about input and sound which are also pretty important for games. Offline Gudradain « Reply #24 - Posted 2011-01-20 19:24:05 » Its factors slower then what the OpenGL bindings can do and pretty much impossible to pull of a modern looking game with it. Because of lighting? or something else? Pages: [1]   ignore  |  Print       You cannot reply to this message, because it is very, very old.   Dwinin (74 views) 2015-11-07 13:29:08 Rems19 (81 views) 2015-10-31 01:36:56 Rems19 (79 views) 2015-10-31 01:32:37 williamwoles (107 views) 2015-10-23 10:42:59 williamwoles (93 views) 2015-10-23 10:42:45 Jervac_ (111 views) 2015-10-18 23:29:12 DarkCart (137 views) 2015-10-16 00:58:11 KaiHH (118 views) 2015-10-11 14:10:14 KaiHH (158 views) 2015-10-11 13:26:18 BurntPizza (173 views) 2015-10-08 03:11:46 Rendering resources by Roquen 2015-11-13 14:37:59 Rendering resources by Roquen 2015-11-13 14:36:58 Math: Resources by Roquen 2015-10-22 07:46:10 Networking Resources by Roquen 2015-10-16 07:12:30 Rendering resources by Roquen 2015-10-15 07:40:48 Math: Inequality properties by Roquen 2015-10-01 13:30:46 Math: Inequality properties by Roquen 2015-09-30 16:06:05 HotSpot Options by Roquen 2015-08-29 11:33:11 java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!
__label__pos
0.780267
1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More. Hey... Wait a Minute.... Discussion in 'Sony PSP - Mod and firmware discussion' started by reloadSE, May 21, 2007. 1. reloadSE reloadSE Regular member Joined: Apr 7, 2007 Messages: 184 Likes Received: 0 Trophy Points: 26 Before theres a downgrader for 3.10/3.11/3.30.3.40 doesn't there have to be a HEN (Homebrew Enabler)???? Because if you didn't we would be able to downgrade??? reloadse   2. svtstang svtstang Regular member Joined: Apr 23, 2006 Messages: 4,565 Likes Received: 0 Trophy Points: 46 Honestly, do you have any idea what you are talking about? Do you know how HEN works? I really dont think so, or you wouldnt ask. Sony upped the security in 3.10+ firmwares, that is why there is no downgrader. HEN is based on an exploit, it is not needed to downgrade. Look at the 2.00 to 1.5 downgraded as an example. BTW what is the point of this thread?   Share This Page
__label__pos
0.911777
Only used if data is a Series (np. See matplotlib documentation online for more on this subject, If kind = ‘bar’ or ‘barh’, you can specify relative alignments We just need to import pandas module of hvplot which will provide a wrapper around the existing pandas module and expose hvplot API which we'll be exploring further for plotting purpose. That is alright though, because we can still pass through the Pandas objects and plot using our knowledge of Matplotlib for the rest. Active 7 months ago. If string, load colormap with that In [106]: from pandas.plotting import bootstrap_plot In [107]: data = pd. Default uses index name as xlabel, or the for bar plot layout by position keyword. Import pandas. plot Out[6]: To plot a specific column, use the selection method of the subset data tutorial in combination with the plot() method. Default is 0.5 name from matplotlib. From 0 (left/bottom-end) to 1 (right/top-end). option plotting.backend. Now we can plot the charts using the following code: df.groupby ( ['TYPE']).sum ().plot (kind='pie', subplots=True, shadow = True,startangle=90,figsize= (15,10)) In the above code, subplots=True parameter is used to plot charts on both SALES and COUNT metrics. Converting Static Plots to Interactive using Hvplot ¶ It's quite simple to convert static pandas plots to interactive. As I mentioned before, I’ll show you two ways to create your scatter plot. plots). Python’s popular data analysis library, pandas, provides several different options for visualizing your data with .plot().Even if you’re at the beginning of your pandas journey, you’ll soon be creating basic plots that will yield valuable insights into your data. Distplot: This function combines the matplotlib hist function (with automatic calculation of a good default bin size) with the seaborn kdeplot() and rugplot() functions. Une case est comme une plage, par exemple, 0-5, 6-10, etc. Pandas 3D dataframe representation has consistently been a difficult errand yet with the appearance of dataframe plot() work it is very simple to make fair-looking plots with your dataframe. A random subset of a specified size is selected from a data set, the statistic in question is computed for this subset and the process is repeated a specified number of times. You’ll see here the Python code for: a pandas scatter plot and; a matplotlib scatter plot; The two solutions are fairly similar, the whole process is ~90% the same… The only difference is in the last few lines of code. Plot the Size of each Group in a Groupby object in Pandas Last Updated : 19 Aug, 2020 Pandas dataframe.groupby() function is one of the most useful function in the library it splits the data into groups based on columns/conditions and then apply some operations eg. pandas.DataFrame.plot ... Font size for xticks and yticks. If a Series or DataFrame is passed, use passed data to draw a In this section, we will see how Pandas dataframes can be used to plot simple plots such as histograms, count plot, scatter plots, etc. It isn’t really. To change the color we set the color parameter. In [6]: air_quality ["station_paris"]. brightness_4 to invisible; defaults to True if ax is None otherwise False if A bar plot is a plot that presents categorical data with rectangular bars with lengths proportional to the values that they represent. Dans les géopandas> = 0,3 (publié en septembre 2017), le tracé des points est basé sur… If a list is passed and subplots is Attention geek! colormap: str or matplotlib colormap object, default None. Bar charts in Pandas with Matplotlib. it is used to determine the size of a figure object. Note that you can create them using either of the methods shown above. 2. Pandas plot() function enables us to make a variety of plots right from Pandas. columns to plot on secondary y-axis. The font of other text could be set. On top of extensive data processing the need for data reporting is also among the major factors that drive the data world. .. versionchanged:: 0.25.0, Use log scaling or symlog scaling on y axis. pandas.DataFrame.plot.bar¶ DataFrame.plot.bar (x = None, y = None, ** kwargs) [source] ¶ Vertical bar plot. Prerequisites: Pandas. The values are given a a tuple, as below. Today, a huge amount of data is generated in a day and Pandas visualization helps us to represent the data in the form of a histogram, line chart, pie chart, scatter chart etc. at the top of the figure. Bar graphs usually represent numerical and categorical variables grouped in intervals. If True, draw a table using the data in the DataFrame and the data For example, the following data will be used to create the scatter diagram. For instance, ‘matplotlib’. We’ll now look at some other plots in pandas. The object for which the method is called. This kind of plot is useful to see complex correlations between two variables. plotting.backend. Here are the steps to plot a scatter diagram using Pandas. Step 1: Prepare the data. Use index as ticks for x axis. The first thing that you might want to do is change the size. will be the object returned by the backend. .. versionchanged:: 0.25.0, Use log scaling or symlog scaling on both x and y axes. DataFrame. I am changing the font-sizes in my python pandas dataframe plot. When you call .plot (), you’ll see the following figure: The histogram shows the data grouped into ten bins ranging from $20,000 to $120,000, and each bin has a width of $10,000. Introduction to Pandas 3D DataFrame. The plot-scatter() function is used to create a scatter plot with varying marker point size and color. The data I'm going to use is the same as the other article Pandas DataFrame Plot - Bar Chart . it is used to determine the size of a figure object. Syntax: figsize=(width, height) Where dimensions should be given in inches. Let's start off by plotting the generosity score against the GDP per capita: Backend to use instead of the backend specified in the option (rows, columns) for the layout of subplots. Well first go a head and load a csv file into a Pandas DataFrame and then explain how to resize it so it fits your screen for clarity and readability. In case subplots=True, share x axis and set some x axis labels code. With a DataFrame, pandas creates by default one line plot for each of the columns with numeric data. I want to plot only the columns of the data table with the data from Paris. The size of a plot can be modified by passing required dimensions as a tuple to the figsize parameter of the plot() method. True, print each item in the list above the corresponding subplot. Title to use for the plot. First, we used Numpy random randn function to generate random numbers of size 1000 * 2. Luckily, Pandas Scatter Plot can be called right on your DataFrame. Size of a figure object. You can specify alternative aggregations by passing values to the C and reduce_C_function arguments. Well, no. Syntaxe de pandas.DataFrame.plot.hist() DataFrame.sample(by=None, bins=10, **kwargs) Paramètres. I'm trying to plot a figure by pandas. ax3 couldn't use axes.set_xlabel() parameter. but be careful you aren’t overloading your chart. , visualization is an essential tool in just 7 min to resize your Seaborn I. Ll now look at some other plots in matplotlib by using the temp column methods shown above Pandas perspective plot... Might want to plot only the columns with numeric data on secondary.. Pandas in just 7 min and categorical variables grouped in intervals arguments are used pandas plot size... Draw a table ) which counts the number of entries / rows in group! On top of extensive data processing the need for data reporting is also among the major that! Hexbin ’, you can control the size of a Seaborn chart in Jupyter.. Above the corresponding subplot data = pd also among the major factors that drive the data Paris. Do is change the color parameter ll show you two ways to create a plot that presents categorical with. For example, the following data will be the object returned by the backend is not the parameters. Be used to represent each point the python Programming Foundation Course and learn basics... Size 1000 * 2 determine the size of a figure object the generosity score against GDP... Figure by Pandas C and reduce_C_function arguments alright though, pandas plot size we still. ’ une chaîne ou d ’ une pandas plot size ou d ’ histogrammes, y-axis,,... Variety of format y-column name for planar plots ( scatter, hexbin ) and the data for your scatter with! A Series or data Frame without importing any visualization module plotting pie chart using function! Can do to customize your plots more both with Pandas and matplotlib station_paris '' ] *... It the sizes of x, y = None, * * kwargs [! The figsize parameter depict a relationship between two variables prepare the data in the DataFrame the major factors that the... To 4 dimensions – X-axis, y-axis, size, and y axes categorical data with rectangular with. Est comme une plage, par exemple, 0-5, 6-10, etc )! To convert Static Pandas plots by using Pandas sizes of x, y = None, y None! Library is used to determine the size of a pandas plot size object I mentioned before I. The different types of plots right from Pandas perspective the plot ( ) the article... Off using python some other plots in Pandas plot ( ) function enables to. Data where the length of the columns of the methods shown above be careful you ’. Pandas DataFrame.plot ( ) Our first attempt to make the line plot, par,! Numeric data random randn function to generate random numbers of size 1000 *.! The rest different types of plots right from Pandas `` 'Function plots a graphical correlation for... To start, prepare the data will be transposed to meet matplotlib’s default layout C reduce_C_function. Represents the magnitude/size of the bars are proportional to the C and reduce_C_function arguments the Pandas hexbin plot a! ¶ Vertical bar plot simple plot using plot ( ) careful you aren t... By plotting the generosity score against the GDP per capita: DataFrame.plot.scatter ( ) by using Pandas in! ) position: float create or load data if kind = ‘ hexbin ’ plots.!, share y axis and set some y axis a different shape than normal... < kind > Okay, you can do to customize your plots both. ’ agit d ’ histogrammes to generate or plot a scatter diagram many.! Static plots to Interactive offer an easy way to explore data ( EDA ) with dimensions to begin,. Reporting process from Pandas plots a graphical correlation matrix for each of the bins with the gridsize argument axis. Set pd.options.plotting.backend random numbers of size 1000 * 2 your data Structures concepts with the python DS.. The plotting.backend for pandas plot size layout of subplots explicitly set the ones for the individual.. Eda ) width, height ) where dimensions should be given in inches ) [ source ¶... Used to import and manage datasets in a variety of format internet is on or off python! Not the default parameters but explicitly set the default matplotlib one, the following article provides an for. €œ ( right ) ” in the list above the corresponding subplot of Charts in Pandas in 7. The bootstrap plot value in Dictionary, Write interview Experience Interactive using Hvplot ¶ it 's quite simple to Static! Quite simple to convert Static Pandas plots to Interactive using Hvplot ¶ it pandas plot size quite simple convert. Rectangular bars with lengths proportional to the values that they represent kwargs ) [ source ] ¶ Vertical bar.! Data reporting process from Pandas perspective the plot ( ) DataFrame.sample ( by=None, bins=10 *! Drive the data world one line plot for each pair of columns in the legend ’ and ‘ ’. Colormap with that name from matplotlib them using either of the figure as you.! Of entries / rows in each group a dataset or preparing to publish your findings, visualization is an tool! Between two variables the bins with the python DS Course station_paris ''.! Pandas hexbin plot is a plot that presents categorical data with rectangular bars axis and set some axis... Strengthen your foundations with the gridsize argument `` station_paris '' ] proportional to the values they. A suitable graph as you needed following article provides examples about plotting pie chart using function. ): `` 'Function plots a graphical correlation matrix for each pair columns! To 4 dimensions – X-axis, y-axis, size, and color and plot using plot )! I understand that the same as the other article Pandas DataFrame plot - bar chart ) Paramètres ( rows columns... Matplotlib for the layout of subplots this short recipe we ’ ll show you two to! The ones for the whole session, set pd.options.plotting.backend to change the color we set the color.... Graph as you needed foundations with the python DS Course parameter along with dimensions < kind > Okay, can! Importing any visualization module need for data reporting is also increased using figsize parameter the of! For planar plots is how we could create a scatter plot can be called right on your.! To make the line plot set some y axis is how we could create a line does! A histogram of the figure coordinates of each point the utility toolbox log scaling or symlog scaling both., * * kwargs ) [ source ] ¶ Vertical bar plot is a plot just from Pandas... The link here bar chart `` station_paris '' ] - bar chart create scatter... The y-column name for planar plots 0 ( left/bottom-end ) to 1 ( right/top-end ) axis automatically... A lot you can specify alternative aggregations by passing values to the values are given a a tuple, below. Can still pass through the Pandas objects and plot using Our knowledge of matplotlib for the whole session set! Is how we could create a line plot does not look very successful getting to know a or... To create a plot that presents categorical data with rectangular bars quite simple to Static! Okay, you know how to create a scatter diagram ( rows, columns pandas plot size the! Matrix for each pair of columns in the DataFrame Pandas objects and plot Our... Case est comme une plage, par exemple, 0-5, 6-10, etc )! Version 1.2.0: now applicable to planar plots ( scatter, hexbin ) plot on secondary y-axis if a is. Create your scatter diagram using Pandas a scatter plot with band for every X-axis values default! A relationship between two variables peak in the legend values ( see the.... Here, I ’ ll learn how to increase the size of a figure.. Case est comme une plage, par exemple, 0-5, 6-10, etc. using Jupyter to! The middle ou d ’ une séquence data where the length of the backend is not the default matplotlib,! Visualization is an essential tool y axes plt figsize to resize your Seaborn plot 'm... 106 ]: data = pd the figure below ) of each point defined... Other plots in Pandas or matplotlib colormap object, default None plt figsize to resize your Seaborn plot I also! Of Charts in Pandas diagram using Pandas customize your plots more both Pandas. The GDP per capita: DataFrame.plot.scatter ( ) function Vertical bar plot hexbin plot is to... By empowering the utility toolbox data = pd library is used figsize= (,... Air_Quality [ `` station_paris '' ] from Pandas perspective the plot ( ) the following article provides an outline Pandas... Depict a relationship between two variables graphs usually represent numerical and categorical variables grouped in intervals is.... Might want to do this we add the figsize parameter ’ re just getting to know a or! Each pair of columns in the list above the corresponding subplot syntaxe de pandas.DataFrame.plot.hist ( ) function with peak. Of plots in matplotlib by using the method DataFrame.plot. < kind >,! ) for the layout of subplots random randn function to generate or plot a scatter can! The following pandas plot size provides an outline for Pandas DataFrame.plot ( ) function directly using the temp column the scatter.... X and y ( in inches ) ‘ hexbin ’ plots ) position: float ]. Load data if kind = ‘ hexbin ’, you can do to your... That they represent attempt to make the line plot does not look successful! On or off using python 1 ( right/top-end ) let ’ s discuss the different types of plots from... Parameter and give it the sizes of x, and y axes which counts the number of entries rows...
__label__pos
0.932637
Error Function Calculator Error Function Calculator Share via: What is Error Function? The Error Function is a mathematical function used to describe the probability of an event occurring. It is used in statistics and probability theory to calculate the probability of an event occurring within a given range of values. It is also used in machine learning algorithms to measure the accuracy of a model’s predictions. What is Error Function Calculator? Error Function Calculator is a tool used to calculate the error function of a given number. The error function is a special function used in mathematics to calculate the probability that a random variable will take on a value less than or equal to a given number. It is also known as the Gaussian error function or the probability integral. How to Calculate Error Function? The error function, also known as the Gauss error function, is defined as: erf(x) = 2/√π ∫0x e−t2dt To calculate the error function, you can use numerical integration techniques such as Simpson’s rule or the trapezoidal rule. Alternatively, you can use a computer algebra system such as Mathematica or Maple to calculate the error function. Cite this content, page or calculator as: Andy, Cohen “Error Function Calculator” at from FreeCalculator.net, https://www.freecalculator.net  Generic selectors Exact matches only Search in title Search in content Post Type Selectors Popular categories free{}calculator contact us sitemap FreeCalculator.net’s sole focus is to provide fast, comprehensive, convenient, free online calculators in a plethora of areas. Currently, we have over 100 calculators to help you “do the math” quickly in areas such as finance, fitness, health, math, and others, and we are still developing more. Our goal is to become the one-stop, go-to site for people who need to make quick calculations. Additionally, we believe the internet should be a source of free information. Therefore, all of our tools and services are completely free, with no registration required. We coded and developed each calculator individually and put each one through strict, comprehensive testing. However, please inform us if you notice even the slightest error – your input is extremely valuable to us. While most calculators on FreeCalculator.net are designed to be universally applicable for worldwide usage, some are for specific countries only. © 2021 – 2022 FreeCalculator.net | All rights reserved.
__label__pos
0.999151
Download Script Gopay Sender - Revesery --> Download Script Gopay Sender Script Gopay Sender - halo teman-teman pada artikel kali ini kami ingin memberikan sebuah script yang sangat berguna bagi kalian yang membutuhkan diskon gopay ataupun go-food dengan menggunakan gopay sender. Go-food merupakan salah satu fitur yang ada di gojek yang berguna untuk mengantarkan makanan kalian berdasarkan Resto yang kalian pilih. Dengan go-food tentunya kalian bisa dengan mudah memesan makanan tanpa harus mengunjungi restunya langsung. Tetapi untuk menggunakan go food tentunya kalian harus membayar makanannya dan juga biaya dari biaya pengantaran gojek kalian. Hal ini bertujuan supaya kalian sama-sama untung antara pembeli dan juga para driver. Untuk menggunakan go-food kalian bisa membayar secara cash ataupun secara go-pay. Tetapi beberapa lain kesempatan kalian bisa mendapatkan diskon potongan dari go-food karena kalian menggunakan go-pay. Kalau kalian menggunakan cash Biasanya kalau yang tidak mendapatkan potongan harga dari go-food. Tetapi apabila kalian menggunakan go-pay maka biasanya kalian akan mendapatkan potongan harga dari go-food. Hal ini merupakan strategi yang dikeluarkan oleh gojek supaya kalian menggunakan go-pay. Untuk mendapatkan diskon potongan tersebut kalian bisa menggunakan Rp1 dari go-pay saja itu sudah kepotong harga menjadi diskon. tentunya hal ini sangat membantu sekali bagi kita yang ingin membutuhkan diskon-diskon tersebut untuk makanan yang kita inginkan. disini terdapat dua script yaitu script gopay.php dan juga header.php. Download Script Gopay Sender ini merupakan salah satu script gojek vendor yang bisa kalian gunakan secara pribadi. karena beberapa website gojek vendor itu sudah tidak berfungsi lagi karena memang gojek under itu satu akun pengirim untuk digunakan untuk semua orang. Lebih baik kalian membuat gojek Yang Tersendiri kemudian kalian mengirimkan untuk akun kalian sendiri berikut ini scriptnya Script Gopay Sender Gopay.php <?php error_reporting(0); include 'header.php'; function curl($url, $fields = null, $headers = null) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); if ($fields !== null) { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); } if ($headers !== null) { curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } $result = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return array( $result, $httpcode ); } { $secret = 'xxxx-xxxxxxxxx-xxxxxx'; //BEARERTOKENAKUNUTAMA $pin = "xxxxxx"; //PINGOPAY $headers = array(); $header[] = 'Content-Type: application/json'; $header[] = 'X-AppVersion: 3.40.0'; $header[] = "X-Uniqueid: ac94e5d0e7f3f".rand(111,999); $header[] = 'X-Location: -6.405821,106.064193'; $header[] ='Authorization: Bearer '.$secret; $header[] = 'pin:'.$pin.''; $amountt = $_POST['amount']; $number = $_POST['phone']; $numbers = $number[0].$number[1]; $numberx = $number[5]; if($numbers == "08") { $number = str_replace("08","628",$number); } elseif ($numberx == " ") { $number = preg_replace("/[^0-9]/", "",$number); $number = "1".$number; } } if(isset($_POST['submit'])) { $getqrid = curl('https://api.gojekapi.com/wallet/qr-code?phone_number=%2B'.$number.'', null, $header); $jsqrid = json_decode($getqrid[0]); $qrid = $jsqrid->data->qr_id; $tf = curl('https://api.gojekapi.com/v2/fund/transfer', '{"amount":"'.$amountt.'","description":"ZAL ","qr_id":"'.$qrid.'"}', $header); $jstf = json_decode($tf[0]); $tfref = $jstf->data->transaction_ref; if ($jstf && true === $jstf->success) { echo ' <div class="alert alert-success"> <strong>Success!</strong> Berhasil Transfer Gopay <b>Rp.'.$amountt.'</b> Ke <b>'.$number.'</b> . Trx ID: <b>'.$tfref.'</b> </div> '; } else { echo ' <div class="alert alert-warning"> <strong>Failed!</strong> Gagal Transfer Gopay. </div> '; } } { $detail = curl('https://api.gojekapi.com/wallet/profile/detailed', null, $header); $saldoo = json_decode($detail[0]); $saldo = $saldoo->data->balance; echo ' <button type="button" class="btn btn-default">Saldo: <b>Rp. '.$saldo.'</b></button> <br><br> <form action="" method="POST"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span> <input id="phone" type="text" class="form-control" name="phone" placeholder="62 or 1"> </div> <br> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-usd"></i></span> <input id="amount" type="text" class="form-control" name="amount" placeholder="1 - 99999"> </div> <br> <center> <button type="reset" class="btn btn-default"><i class="fa fa-refresh"></i> Reset</button> <button type="submit" name="submit" class="btn btn-info"><i class="fa fa-paper-plane-o"></i> Submit</button></center> </div> </div> </form> </body> </html>'; } ?> header.php <!DOCTYPE html> <html lang="en"> <head> <title>Gopay Sender</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet"> </head> <style type="text/css"> body { font-family: 'Quicksand', sans-serif; margin-bottom: 50px; } </style> </head> <body> <br> <div class="container"> <div class="panel-group"> <div class="panel panel-default"> <div class="panel-heading"><i class="fa fa-paper-plane-o"></i> GOPAY SENDER</div> <div class="panel-body"> Cara Menggunakan : Upload ke hosting Edit gopay.php paste bearer token akun utama & pin Sekian artikel mengenai Script go-jek senar Semoga dengan adanya tutorial and script ini bisa membantu hal yang sama untuk mendapatkan script yang berfungsi detik apabila script ini sudah tidak berfungsi lagi kedepannya berarti gojek sudah melakukan update. Sekian dan terima kasih Ada pertanyaan? Silahkan komentar 1 Komentar Iklan Atas Artikel Revesery.com Revesery.com Iklan Bawah Artikel Kunjungi terus Revesery.com karna akan ada update selanjutnya. Download ==>
__label__pos
0.90213
search menu icon-carat-right cmu-wordmark Model Driven Engineering: Automatic Code Generation and Beyond Acquisition executives in domains ranging from modernizing legacy business systems to developing real-time communications systems often face the following challenge: Vendors claim that model-driven engineering (MDE) tools enable developers to generate software code automatically and achieve extremely high developer productivity. Are these claims true? The simple answer might be, "Yes, the state of the practice can achieve productivity rates of thousands of function points and millions of lines of code per person-month using MDE tools for automatic code generation." The complicated reality is that MDE consists of more than code generation tools; it is a software engineering approach that can impact the entire lifecycle from requirements gathering through sustainment. While one can make broad generalizations about these methods and tools, it is more useful to consider them in the context of a particular system acquisition. Aligning MDE methods and tool capabilities with the system acquisition strategy can improve system quality, reduce time to field, and reduce sustainment cost. On the other hand, when MDE methods and tools do not align with the acquisition strategy, using them can result in increased risk and cost in development and sustainment. This blog post highlights the application of MDE tools for automatic code generation (in the context of the full system lifecycle, from concept development through sustainment) and also provides a template that acquirers can use to collect information from MDE tool vendors. Foundations of Our Work: AADL Researchers at the SEI have been doing work in MDE for several decades. In particular, Peter Feiler and Julien Delange have been working with the Architecture Analysis and Design Language (AADL) modeling notation for use in real-time embedded systems, safety-critical systems, and other high-assurance systems. Their work has focused on analysis and an up-front assurance that the system will function as intended, with less emphasis on code generation. This latest SEI MDE effort--in addition to me, the team included Harry Levinson and Jay Marchetti--focuses more on code generation, specifically in the context of business systems with code generation benefits realized by the developer. As detailed in our technical note, Model-Driven Engineering: Automatic Code Generation and Beyond, while certain domains can achieve extremely high productivity using model-driven approaches, it is important to realize that code generation is just one small piece of the entire software lifecycle. In software engineering, there is a tight coupling between the system domain (e.g., business system, command and control system, or avionics system), the methods used throughout the system lifecycle, and the tools used to support the chosen methods. Furthermore, government acquirers have the challenge of selecting contractors to develop their systems. This selection process includes evaluating the development team, the development methodology, and the tools in the context of the system acquisition strategy. Or, to state it more simply, in MDE, if you develop code using one tool it can be expensive to switch to another tool later in the software development lifecycle. In addition to acquiring code, therefore, software acquirers should also consider the tools needed to sustain the software. When an organization adopts a model-driven approach, it is also adopting a particular toolset and technology. These additional adoptions are of particular concern in the Department of Defense (DoD), where the focus is on acquiring and maintaining longer-lived systems. In many commercial contexts, there is less hesitation to rebuild a system from scratch. Code Generation in Business Systems Firms such as Gartner, Forrester, and IDC have focused their analyses of MDE technology on commercial IT developers and software providers. As stated earlier, our analysis focused on the unique acquisition concerns of the DoD and other federal agencies in which systems are acquired and maintained for longer periods of time. Specifically, we examined business systems since this is an area where code generation tools are having significant impact. This analysis included existing technologies and approaches used for commercial off-the-shelf technologies (COTS), and it investigated how those same principles can be applied to the acquisition of MDE tools. We used the PECA Method (Plan, Establish Criteria, Collect Data, Analyze Results) to organize an acquirer's technology assessment, and used an established risk framework to identify criteria within the overall process. Acquisition Strategy Implications An acquisition strategy specifies which artifacts and data rights to acquire, as well as which artifacts to evaluate at each program decision point. The acquisition strategy also defines the approach to identifying, managing, and mitigating program risks. The use of MDE for automatic code generation has several implications for acquisition strategy, including the following: • artifacts, data rights, and licenses. Development tooling is usually not a significant concern when acquiring software-intensive systems, but it can be a significant concern when acquiring a system developed using an MDE approach, particularly when using MDE for automatic code generation. In MDE-developed software, the models are the primary development artifacts, embodying the software architecture design and component designs, and ultimately driving the automatic code generation. Ideally, all software sustainment and evolution will also use the MDE approach, which requires data rights and necessary licensing for the tools, models, and generated code. When only the automatically generated source code is acquired (without the models used to generate the code), then sustainment and evolution are more difficult because the automatically generated code is not structured for human readability and comprehension. • design review scope and timing. The acquirer must review and evaluate appropriate artifacts at the right time in the acquisition cycle. For example, in an approach using MDE for automatic code generation, the software architecture documentation may consist of a subset of the code-generation model, along with accompanying documentation, to provide context and design rational. The software architecture should be evaluated early in the design process (as discussed by Bergey and Jones). The evaluation scope and criteria, however, may need to be expanded to account for the use of the model not just to represent the architecture for communications among stakeholders but also to directly generate the executing software. Finally, reviewers may need to use the MDE tools to view the models--exporting the model into a generic format, such as portable document format (PDF) files, may not provide adequate visual resolution and the ability to efficiently navigate through the model. Tool availability and access to the network where the model is stored become issues that the acquirer must address in planning the evaluation. • impact on program risk. While an MDE approach promises automatic code generation, improvement of cost and schedule, reduction of technical risk by enabling early analysis, and the ability to demonstrate capabilities and validate requirements by using executable models or rapid prototypes, it also introduces new risks, including the following (see our technical note for a more detailed accounting of risks introduced by an MDE approach to automatic code generation.): - a development-time dependency on the tool chosen to support the process. The chosen tool is used to create and modify the model, which is then processed to generate the code. Unlike traditional source code, which can be created and modified by many different tools, the state of the market for MDE tools is that, in most cases, a model can be edited and modified only by the tool that created it, and changing tools may require rebuilding the entire model. - cybersecurity assurance . As noted earlier, development time and run-time dependencies have several implications for cyber assurance. For example, as cybersecurity policy and practices evolve, the tool may generate compliant code (e.g., code that is compatible with required authorization mechanisms, access control policies, or encryption practices). - run-time portability . Portability concerns manifest as a desire to execute the automatically generated code in several environments, each comprising different hardware and software infrastructure. These concerns may also manifest as a desire to change the system's hardware and software infrastructure over time. - runtime performance . The automatically generated code must satisfy the system's runtime throughput, latency, concurrent request processing, and other performance quality requirements. While the use of an MDE approach may provide early confidence that these requirements can be met, if one or more of these requirements change, there is a risk that the automatically generated code may not satisfy the new requirement. - usability of generated user interfaces . In some system domains, such as business systems, the MDE tools may generate user interfaces as part of the automatically generated code. The generated user interfaces may support functions such as system configuration and administration, system monitoring, and end-user activities. A Template for Collecting Information from MDE Tool Vendors To help business system acquirers select and evaluate MDE tools, we have created a questionnaire template to use during the "Collect Data" step in the process, which can be downloaded here. Our accompanying technical note provides detailed guidance on how to interpret responses during the "Analyze Results" step. To develop the template, we started by reviewing guidance about how to develop criteria for developing a tool based on your program-specific acquisition issues. We wanted to understand particular risk areas that may or may not be relevant for a program. We also wanted to understand how the use of MDE tools could help mitigate some risks but also introduce or increase other risks. We also relied on earlier SEI research that created a risk taxonomy. We used that taxonomy to examine how MDE approaches can either help mitigate some of those risks or may introduce risks to a program. Wrapping Up and Looking Ahead Our premise through all of our analysis of MDE methods and tools is that it is impossible to make broad-brush statements that are true for all programs. There are many mitigating factors, including • the goals of the program • the context that a program is working in • high priority objectives • existing risks Our analysis and risk taxonomy can help programs decide whether MDE approaches can help or hurt an organization, specifically whether a particular approach will fit with a program's risk profile and goals. MDE provides the opportunity to reduce development costs, improve the quality of the software developed, and possibly increase the agility of the development process. Programs can realize these benefits only if the concept fits with their acquisition strategies. MDE tools that specialize on a particular type of system provide high productivity but solve only a very narrow type of problem. Our analysis found that the narrower the scope of an MDE tool, the more that tool is tied to a vendor. We welcome your feedback on our work. Additional Resources You can learn about our research on MDE by reading the technical note Model-Driven Engineering: Automatic Code Generation and Beyond. The template for the accompanying questionnaire can also be downloaded from this site. About the Author
__label__pos
0.819802
Euler diagrams, logic statements, and truth tables 1. Create an Euler diagram to determine whether the syllogism is valid or invalid. All grocery stores are open until 10 p.m. The store on the corner is open until 10 p.m. The store on the corner is a grocery store. 2. If the argument below is valid, name which of the four valid forms of argument is represented. If it is not valid, name the fallacy that is represented. If I sing in the shower, then I will not be overheard while singing. I was not overheard while singing. Therefore, I sang in the shower. 3. Form the contrapositive: If I do not mow the lawn, the grass grows too tall 4. Construct a truth table for ~ (q V ~p) Attachments Solution Summary Euler diagrams, logic statements, and truth tables.
__label__pos
0.591599
File:  [gforth] / gforth / glocals.fs Revision 1.14: download - view: text, annotated - select for diffs Mon Oct 16 18:33:10 1995 UTC (27 years, 5 months ago) by anton Branches: MAIN CVS tags: HEAD added answords.fs and strsignal.c added checking of documenetation of ANS Forth words Fixed many documentation errors and added some documentation signal handling now uses strsignal and can handle signals not present on all machines 1: \ Local variables are quite important for writing readable programs, but 2: \ IMO (anton) they are the worst part of the standard. There they are very 3: \ restricted and have an ugly interface. 4: 5: \ So, we implement the locals wordset, but do not recommend using 6: \ locals-ext (which is a really bad user interface for locals). 7: 8: \ We also have a nice and powerful user-interface for locals: locals are 9: \ defined with 10: 11: \ { local1 local2 ... } 12: \ or 13: \ { local1 local2 ... -- ... } 14: \ (anything after the -- is just a comment) 15: 16: \ Every local in this list consists of an optional type specification 17: \ and a name. If there is only the name, it stands for a cell-sized 18: \ value (i.e., you get the value of the local variable, not it's 19: \ address). The following type specifiers stand before the name: 20: 21: \ Specifier Type Access 22: \ W: Cell value 23: \ W^ Cell address 24: \ D: Double value 25: \ D^ Double address 26: \ F: Float value 27: \ F^ Float address 28: \ C: Char value 29: \ C^ Char address 30: 31: \ The local variables are initialized with values from the appropriate 32: \ stack. In contrast to the examples in the standard document our locals 33: \ take the arguments in the expected way: The last local gets the top of 34: \ stack, the second last gets the second stack item etc. An example: 35: 36: \ : CX* { F: Ar F: Ai F: Br F: Bi -- Cr Ci } 37: \ \ complex multiplication 38: \ Ar Br f* Ai Bi f* f- 39: \ Ar Bi f* Ai Br f* f+ ; 40: 41: \ There will also be a way to add user types, but it is not yet decided, 42: \ how. Ideas are welcome. 43: 44: \ Locals defined in this manner live until (!! see below). 45: \ Their names can be used during this time to get 46: \ their value or address; The addresses produced in this way become 47: \ invalid at the end of the lifetime. 48: 49: \ Values can be changed with TO, but this is not recomended (TO is a 50: \ kludge and words lose the single-assignment property, which makes them 51: \ harder to analyse). 52: 53: \ As for the internals, we use a special locals stack. This eliminates 54: \ the problems and restrictions of reusing the return stack and allows 55: \ to store floats as locals: the return stack is not guaranteed to be 56: \ aligned correctly, but our locals stack must be float-aligned between 57: \ words. 58: 59: \ Other things about the internals are pretty unclear now. 60: 61: \ Currently locals may only be 62: \ defined at the outer level and TO is not supported. 63: 64: require search-order.fs 65: require float.fs 66: 67: : compile-@local ( n -- ) \ gforth compile-fetch-local 68: case 69: 0 of postpone @local0 endof 70: 1 cells of postpone @local1 endof 71: 2 cells of postpone @local2 endof 72: 3 cells of postpone @local3 endof 73: ( otherwise ) dup postpone @local# , 74: endcase ; 75: 76: : compile-f@local ( n -- ) \ gforth compile-f-fetch-local 77: case 78: 0 of postpone f@local0 endof 79: 1 floats of postpone f@local1 endof 80: ( otherwise ) dup postpone f@local# , 81: endcase ; 82: 83: \ the locals stack grows downwards (see primitives) 84: \ of the local variables of a group (in braces) the leftmost is on top, 85: \ i.e. by going onto the locals stack the order is reversed. 86: \ there are alignment gaps if necessary. 87: \ lp must have the strictest alignment (usually float) across calls; 88: \ for simplicity we align it strictly for every group. 89: 90: slowvoc @ 91: slowvoc on \ we want a linked list for the vocabulary locals 92: vocabulary locals \ this contains the local variables 93: ' locals >body ' locals-list >body ! 94: slowvoc ! 95: 96: create locals-buffer 1000 allot \ !! limited and unsafe 97: \ here the names of the local variables are stored 98: \ we would have problems storing them at the normal dp 99: 100: variable locals-dp \ so here's the special dp for locals. 101: 102: : alignlp-w ( n1 -- n2 ) 103: \ cell-align size and generate the corresponding code for aligning lp 104: aligned dup adjust-locals-size ; 105: 106: : alignlp-f ( n1 -- n2 ) 107: faligned dup adjust-locals-size ; 108: 109: \ a local declaration group (the braces stuff) is compiled by calling 110: \ the appropriate compile-pushlocal for the locals, starting with the 111: \ righmost local; the names are already created earlier, the 112: \ compile-pushlocal just inserts the offsets from the frame base. 113: 114: : compile-pushlocal-w ( a-addr -- ) ( run-time: w -- ) 115: \ compiles a push of a local variable, and adjusts locals-size 116: \ stores the offset of the local variable to a-addr 117: locals-size @ alignlp-w cell+ dup locals-size ! 118: swap ! 119: postpone >l ; 120: 121: : compile-pushlocal-f ( a-addr -- ) ( run-time: f -- ) 122: locals-size @ alignlp-f float+ dup locals-size ! 123: swap ! 124: postpone f>l ; 125: 126: : compile-pushlocal-d ( a-addr -- ) ( run-time: w1 w2 -- ) 127: locals-size @ alignlp-w cell+ cell+ dup locals-size ! 128: swap ! 129: postpone swap postpone >l postpone >l ; 130: 131: : compile-pushlocal-c ( a-addr -- ) ( run-time: w -- ) 132: -1 chars compile-lp+! 133: locals-size @ swap ! 134: postpone lp@ postpone c! ; 135: 136: : create-local ( " name" -- a-addr ) 137: \ defines the local "name"; the offset of the local shall be 138: \ stored in a-addr 139: create 140: immediate restrict 141: here 0 , ( place for the offset ) ; 142: 143: : lp-offset ( n1 -- n2 ) 144: \ converts the offset from the frame start to an offset from lp and 145: \ i.e., the address of the local is lp+locals_size-offset 146: locals-size @ swap - ; 147: 148: : lp-offset, ( n -- ) 149: \ converts the offset from the frame start to an offset from lp and 150: \ adds it as inline argument to a preceding locals primitive 151: lp-offset , ; 152: 153: vocabulary locals-types \ this contains all the type specifyers, -- and } 154: locals-types definitions 155: 156: : W: ( "name" -- a-addr xt ) \ gforth w-colon 157: create-local 158: \ xt produces the appropriate locals pushing code when executed 159: ['] compile-pushlocal-w 160: does> ( Compilation: -- ) ( Run-time: -- w ) 161: \ compiles a local variable access 162: @ lp-offset compile-@local ; 163: 164: : W^ ( "name" -- a-addr xt ) \ gforth w-caret 165: create-local 166: ['] compile-pushlocal-w 167: does> ( Compilation: -- ) ( Run-time: -- w ) 168: postpone laddr# @ lp-offset, ; 169: 170: : F: ( "name" -- a-addr xt ) \ gforth f-colon 171: create-local 172: ['] compile-pushlocal-f 173: does> ( Compilation: -- ) ( Run-time: -- w ) 174: @ lp-offset compile-f@local ; 175: 176: : F^ ( "name" -- a-addr xt ) \ gforth f-caret 177: create-local 178: ['] compile-pushlocal-f 179: does> ( Compilation: -- ) ( Run-time: -- w ) 180: postpone laddr# @ lp-offset, ; 181: 182: : D: ( "name" -- a-addr xt ) \ gforth d-colon 183: create-local 184: ['] compile-pushlocal-d 185: does> ( Compilation: -- ) ( Run-time: -- w ) 186: postpone laddr# @ lp-offset, postpone 2@ ; 187: 188: : D^ ( "name" -- a-addr xt ) \ gforth d-caret 189: create-local 190: ['] compile-pushlocal-d 191: does> ( Compilation: -- ) ( Run-time: -- w ) 192: postpone laddr# @ lp-offset, ; 193: 194: : C: ( "name" -- a-addr xt ) \ gforth c-colon 195: create-local 196: ['] compile-pushlocal-c 197: does> ( Compilation: -- ) ( Run-time: -- w ) 198: postpone laddr# @ lp-offset, postpone c@ ; 199: 200: : C^ ( "name" -- a-addr xt ) \ gforth c-caret 201: create-local 202: ['] compile-pushlocal-c 203: does> ( Compilation: -- ) ( Run-time: -- w ) 204: postpone laddr# @ lp-offset, ; 205: 206: \ you may want to make comments in a locals definitions group: 207: ' \ alias \ immediate 208: ' ( alias ( immediate 209: 210: forth definitions 211: 212: \ the following gymnastics are for declaring locals without type specifier. 213: \ we exploit a feature of our dictionary: every wordlist 214: \ has it's own methods for finding words etc. 215: \ So we create a vocabulary new-locals, that creates a 'w:' local named x 216: \ when it is asked if it contains x. 217: 218: also locals-types 219: 220: : new-locals-find ( caddr u w -- nfa ) 221: \ this is the find method of the new-locals vocabulary 222: \ make a new local with name caddr u; w is ignored 223: \ the returned nfa denotes a word that produces what W: produces 224: \ !! do the whole thing without nextname 225: drop nextname 226: ['] W: >name ; 227: 228: previous 229: 230: : new-locals-reveal ( -- ) 231: true abort" this should not happen: new-locals-reveal" ; 232: 233: create new-locals-map ' new-locals-find A, ' new-locals-reveal A, 234: 235: vocabulary new-locals 236: new-locals-map ' new-locals >body cell+ A! \ !! use special access words 237: 238: variable old-dpp 239: 240: \ and now, finally, the user interface words 241: : { ( -- addr wid 0 ) \ gforth open-brace 242: dp old-dpp ! 243: locals-dp dpp ! 244: also new-locals 245: also get-current locals definitions locals-types 246: 0 TO locals-wordlist 247: 0 postpone [ ; immediate 248: 249: locals-types definitions 250: 251: : } ( addr wid 0 a-addr1 xt1 ... -- ) \ gforth close-brace 252: \ ends locals definitions 253: ] old-dpp @ dpp ! 254: begin 255: dup 256: while 257: execute 258: repeat 259: drop 260: locals-size @ alignlp-f locals-size ! \ the strictest alignment 261: set-current 262: previous previous 263: locals-list TO locals-wordlist ; 264: 265: : -- ( addr wid 0 ... -- ) \ gforth dash-dash 266: } 267: [char] } parse 2drop ; 268: 269: forth definitions 270: 271: \ A few thoughts on automatic scopes for locals and how they can be 272: \ implemented: 273: 274: \ We have to combine locals with the control structures. My basic idea 275: \ was to start the life of a local at the declaration point. The life 276: \ would end at any control flow join (THEN, BEGIN etc.) where the local 277: \ is lot live on both input flows (note that the local can still live in 278: \ other, later parts of the control flow). This would make a local live 279: \ as long as you expected and sometimes longer (e.g. a local declared in 280: \ a BEGIN..UNTIL loop would still live after the UNTIL). 281: 282: \ The following example illustrates the problems of this approach: 283: 284: \ { z } 285: \ if 286: \ { x } 287: \ begin 288: \ { y } 289: \ [ 1 cs-roll ] then 290: \ ... 291: \ until 292: 293: \ x lives only until the BEGIN, but the compiler does not know this 294: \ until it compiles the UNTIL (it can deduce it at the THEN, because at 295: \ that point x lives in no thread, but that does not help much). This is 296: \ solved by optimistically assuming at the BEGIN that x lives, but 297: \ warning at the UNTIL that it does not. The user is then responsible 298: \ for checking that x is only used where it lives. 299: 300: \ The produced code might look like this (leaving out alignment code): 301: 302: \ >l ( z ) 303: \ ?branch <then> 304: \ >l ( x ) 305: \ <begin>: 306: \ >l ( y ) 307: \ lp+!# 8 ( RIP: x,y ) 308: \ <then>: 309: \ ... 310: \ lp+!# -4 ( adjust lp to <begin> state ) 311: \ ?branch <begin> 312: \ lp+!# 4 ( undo adjust ) 313: 314: \ The BEGIN problem also has another incarnation: 315: 316: \ AHEAD 317: \ BEGIN 318: \ x 319: \ [ 1 CS-ROLL ] THEN 320: \ { x } 321: \ ... 322: \ UNTIL 323: 324: \ should be legal: The BEGIN is not a control flow join in this case, 325: \ since it cannot be entered from the top; therefore the definition of x 326: \ dominates the use. But the compiler processes the use first, and since 327: \ it does not look ahead to notice the definition, it will complain 328: \ about it. Here's another variation of this problem: 329: 330: \ IF 331: \ { x } 332: \ ELSE 333: \ ... 334: \ AHEAD 335: \ BEGIN 336: \ x 337: \ [ 2 CS-ROLL ] THEN 338: \ ... 339: \ UNTIL 340: 341: \ In this case x is defined before the use, and the definition dominates 342: \ the use, but the compiler does not know this until it processes the 343: \ UNTIL. So what should the compiler assume does live at the BEGIN, if 344: \ the BEGIN is not a control flow join? The safest assumption would be 345: \ the intersection of all locals lists on the control flow 346: \ stack. However, our compiler assumes that the same variables are live 347: \ as on the top of the control flow stack. This covers the following case: 348: 349: \ { x } 350: \ AHEAD 351: \ BEGIN 352: \ x 353: \ [ 1 CS-ROLL ] THEN 354: \ ... 355: \ UNTIL 356: 357: \ If this assumption is too optimistic, the compiler will warn the user. 358: 359: \ Implementation: migrated to kernal.fs 360: 361: \ THEN (another control flow from before joins the current one): 362: \ The new locals-list is the intersection of the current locals-list and 363: \ the orig-local-list. The new locals-size is the (alignment-adjusted) 364: \ size of the new locals-list. The following code is generated: 365: \ lp+!# (current-locals-size - orig-locals-size) 366: \ <then>: 367: \ lp+!# (orig-locals-size - new-locals-size) 368: 369: \ Of course "lp+!# 0" is not generated. Still this is admittedly a bit 370: \ inefficient, e.g. if there is a locals declaration between IF and 371: \ ELSE. However, if ELSE generates an appropriate "lp+!#" before the 372: \ branch, there will be none after the target <then>. 373: 374: \ explicit scoping 375: 376: : scope ( compilation -- scope ; run-time -- ) \ gforth 377: cs-push-part scopestart ; immediate 378: 379: : endscope ( compilation scope -- ; run-time -- ) \ gforth 380: scope? 381: drop 382: locals-list @ common-list 383: dup list-size adjust-locals-size 384: locals-list ! ; immediate 385: 386: \ adapt the hooks 387: 388: : locals-:-hook ( sys -- sys addr xt n ) 389: \ addr is the nfa of the defined word, xt its xt 390: DEFERS :-hook 391: last @ lastcfa @ 392: clear-leave-stack 393: 0 locals-size ! 394: locals-buffer locals-dp ! 395: 0 locals-list ! 396: dead-code off 397: defstart ; 398: 399: : locals-;-hook ( sys addr xt sys -- sys ) 400: def? 401: 0 TO locals-wordlist 402: 0 adjust-locals-size ( not every def ends with an exit ) 403: lastcfa ! last ! 404: DEFERS ;-hook ; 405: 406: ' locals-:-hook IS :-hook 407: ' locals-;-hook IS ;-hook 408: 409: \ The words in the locals dictionary space are not deleted until the end 410: \ of the current word. This is a bit too conservative, but very simple. 411: 412: \ There are a few cases to consider: (see above) 413: 414: \ after AGAIN, AHEAD, EXIT (the current control flow is dead): 415: \ We have to special-case the above cases against that. In this case the 416: \ things above are not control flow joins. Everything should be taken 417: \ over from the live flow. No lp+!# is generated. 418: 419: \ !! The lp gymnastics for UNTIL are also a real problem: locals cannot be 420: \ used in signal handlers (or anything else that may be called while 421: \ locals live beyond the lp) without changing the locals stack. 422: 423: \ About warning against uses of dead locals. There are several options: 424: 425: \ 1) Do not complain (After all, this is Forth;-) 426: 427: \ 2) Additional restrictions can be imposed so that the situation cannot 428: \ arise; the programmer would have to introduce explicit scoping 429: \ declarations in cases like the above one. I.e., complain if there are 430: \ locals that are live before the BEGIN but not before the corresponding 431: \ AGAIN (replace DO etc. for BEGIN and UNTIL etc. for AGAIN). 432: 433: \ 3) The real thing: i.e. complain, iff a local lives at a BEGIN, is 434: \ used on a path starting at the BEGIN, and does not live at the 435: \ corresponding AGAIN. This is somewhat hard to implement. a) How does 436: \ the compiler know when it is working on a path starting at a BEGIN 437: \ (consider "{ x } if begin [ 1 cs-roll ] else x endif again")? b) How 438: \ is the usage info stored? 439: 440: \ For now I'll resort to alternative 2. When it produces warnings they 441: \ will often be spurious, but warnings should be rare. And better 442: \ spurious warnings now and then than days of bug-searching. 443: 444: \ Explicit scoping of locals is implemented by cs-pushing the current 445: \ locals-list and -size (and an unused cell, to make the size equal to 446: \ the other entries) at the start of the scope, and restoring them at 447: \ the end of the scope to the intersection, like THEN does. 448: 449: 450: \ And here's finally the ANS standard stuff 451: 452: : (local) ( addr u -- ) \ local paren-local-paren 453: \ a little space-inefficient, but well deserved ;-) 454: \ In exchange, there are no restrictions whatsoever on using (local) 455: \ as long as you use it in a definition 456: dup 457: if 458: nextname POSTPONE { [ also locals-types ] W: } [ previous ] 459: else 460: 2drop 461: endif ; 462: 463: : >definer ( xt -- definer ) 464: \ this gives a unique identifier for the way the xt was defined 465: \ words defined with different does>-codes have different definers 466: \ the definer can be used for comparison and in definer! 467: dup >code-address [ ' bits >code-address ] Literal = 468: \ !! this definition will not work on some implementations for `bits' 469: if \ if >code-address delivers the same value for all does>-def'd words 470: >does-code 1 or \ bit 0 marks special treatment for does codes 471: else 472: >code-address 473: then ; 474: 475: : definer! ( definer xt -- ) 476: \ gives the word represented by xt the behaviour associated with definer 477: over 1 and if 478: swap [ 1 invert ] literal and does-code! 479: else 480: code-address! 481: then ; 482: 483: \ !! untested 484: : TO ( c|w|d|r "name" -- ) \ core-ext,local 485: \ !! state smart 486: 0 0 0. 0.0e0 { c: clocal w: wlocal d: dlocal f: flocal } 487: ' dup >definer 488: state @ 489: if 490: case 491: [ ' locals-wordlist >definer ] literal \ value 492: OF >body POSTPONE Aliteral POSTPONE ! ENDOF 493: [ ' clocal >definer ] literal 494: OF POSTPONE laddr# >body @ lp-offset, POSTPONE c! ENDOF 495: [ ' wlocal >definer ] literal 496: OF POSTPONE laddr# >body @ lp-offset, POSTPONE ! ENDOF 497: [ ' dlocal >definer ] literal 498: OF POSTPONE laddr# >body @ lp-offset, POSTPONE d! ENDOF 499: [ ' flocal >definer ] literal 500: OF POSTPONE laddr# >body @ lp-offset, POSTPONE f! ENDOF 501: -&32 throw 502: endcase 503: else 504: [ ' locals-wordlist >definer ] literal = 505: if 506: >body ! 507: else 508: -&32 throw 509: endif 510: endif ; immediate 511: 512: : locals| 513: \ don't use 'locals|'! use '{'! A portable and free '{' 514: \ implementation is anslocals.fs 515: BEGIN 516: name 2dup s" |" compare 0<> 517: WHILE 518: (local) 519: REPEAT 520: drop 0 (local) ; immediate restrict FreeBSD-CVSweb <[email protected]>
__label__pos
0.97578
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required. Sign up Here's how it works: 1. Anybody can ask a question 2. Anybody can answer 3. The best answers are voted up and rise to the top I've been looking up the definition of radians and found out that mathematicians prefer them because they are derived from pi instead of being completely arbitrary like degrees. However, I have not found a compelling reason to use them in game development, possibly due to my complete lack of related mathematical understanding. I know that most sin/cos/tan functions in languages what radians, but someone could just as well create library functions in degrees (and avoid the inherent rounding errors when using pi). I don't want this to be an opinionated poll, I would just like to hear from people that have done game development (and the associated math research) where radians offer a superior experience over degrees, as opposed to "We're using radians because we always used them", just for the sake of helping me (and possibly others) to understand what they are good for. share|improve this question 2   One answer is that they are faster. You dont have to covert degrees to radians before using them in functions like sin. I should be more specific and say that one method of computing sin(x) is using a Taylor expansion - and "x" needs to be in radians for the expansion. – user3728501 Dec 24 '13 at 0:42 up vote 45 down vote accepted Radians are used in math because 1. They measure arc-length on the circle, i.e. an arc of angle theta on a circle of radius r is just r * theta (as opposed to pi/180 * r * theta). 2. When trig functions are defined in terms of radians, they obey simpler relationships between each other, such as cosine being the derivative of sine, or sin(x) ~= x for small x. If defined in terms of degrees, the derivative of sine would be pi/180 * cosine, and we'd have sin(x) ~= pi/180 * x for small x. It's not that mathematicians just like pi. Radians are actually a more natural choice of angle measure than degrees, for the above reasons. They are the angle measure in which factors like pi/180 disappear. So IMO, the question is not "why use radians", but "why not use radians". In other words, one doesn't need a reason to use radians; they are the default choice of angle measure. One needs a reason to use degrees. For example one might choose to show angles in degrees in the user interface of an app, because they're more familiar to many people (especially artists). However, personally I've gotten quite used to thinking about angles in terms of radians rather than degrees. I don't have any specific gamedev examples to give you because this isn't really a gamedev issue, but a mathematical one, and would be the same in any field that uses math. (By the way, there are no more "inherent rounding errors when using pi" than when using degrees...angles should always be real numbers, not integers, else how are you going to represent an angle of half a degree? :)) share|improve this answer 4   Agreed with the above. I will add that I once saw a game library that used its own standard, based on 256ths of a circle. The reason seemed to be that their trig functions used a lookup table with 256 entries and interpolated between them. If you're not doing that, but calculating sin/cos/tan from their series expansions, or using FSIN/FCOS instructions on an FPU (most typical), those will both expect an input in radians - so you save a conversion by keeping it in radians throughout. – DMGregory Dec 22 '13 at 7:11 10   "why not use radians" - I'm willing to bet the only good answer there is "because 4th grade homework would be a nightmare with radians" which is likely the only reason any of us even ever heard of degrees. :) – Sean Middleditch Dec 22 '13 at 8:21 4   @SeanMiddleditch 4th grade classes must migrate to Tau. Tau is the radian version of 360. It streamlines the math and professionals must also start adopting it. – Val Dec 23 '13 at 12:30 2   256ths of a circle or 16384ths of a circle means you can use unsigned bytes or 16bit numbers respectively, and the overflows / underflows of adding / subtracting do the right thing. With radians, you probably end up using floating point, which means you get more precision the closer your angle is to zero, and less as it moves away, which is kind of useless / silly most of the time. – rjmunro Dec 23 '13 at 12:52 2   @Val: Tau doesn't solve the same problems degrees do. Degrees make it easy to measure relatively small angles with integral numbers. This is important when trying to teach early geometry when the students are still doing everything by hand and aren't very comfortable with fractions. Consider the usual "clock hand angle" problems students are given and how those cleanly map to degrees but not Pi/Tau radians. This is similar to the reason degrees were at one point popular in games: using a lookup table of degrees was easier/faster (back then) and gave "good enough" resolution for their needs. – Sean Middleditch Dec 23 '13 at 18:35 Nathan's answer is very concrete. I'd like to supply a more general view: The most complex mathematical concept that is natively implemented in most processing units are floating point numbers as models for the field of real numbers ℝ. Visual geometriy is based on the three dimensional real vector space ℝ³. Coordinates are real numbers. Geometric quantities are based on the length, which is a real multiple of a unit. Because of this base in real numbers and lengths, it is practical to also model angles by real numbers resp. lengths. Radians is the length of the arc of a unit circle with the given angle. Thus it is the model of an angle most compatible with all these other units based on real numbers resp. lengths. For example, the approximation sin x ~ x for small values of x is an approximation of the y-coordinate of a point on the unit circle by the arc from the x-axis to that point. One should not forget, that an angle is not a length. It is one of the 4 parts of a plane created by two intersecting straight lines. It's quantity is bounded by the symmetriy of planes in ℝ³ and the euclidean metric. It is more natural to model an angle by the semiopen interval [0,1) (or (0,1] ) glued together at its end points, given the value of an angle as part of a full turn. Degrees are just 1/360 of a full turn. (BTW: Number theoretically, this is a better choice than the decimal system used for real numbers.) share|improve this answer While I use radians too, for all the reasons specified, there's at least one good reason why degrees are preferred: Precision and accumulation of errors. Rotating through a full circle 1 degree at a time is exact. Rotating through a full circle 2PI/360 radians at a time is not. Performing a 90 degree rotation 4 times on a pixel grid gets you back to exactly where you started. Performing a 2PI/4 radian rotation on a pixel grid 4 times does not. share|improve this answer      Testing this empirically, after four 90-degree rotations with a single precision float increment in radians, I find a total error of 1.75E-7 (less than 1 part in 5 million). On a pixel grid, the radius of the rotating object/frame would need to be in the millions of pixels before you would experience 1 pixel of error at the outer edge (a point more than 0.5 linear px from where it should be). In other words, precision loss is unlikely to be an issue in practice (especially if you use doubles). – DMGregory Dec 23 '13 at 20:15      From a numerical perspective you're correct, but from a visual perspective if ONE pixel from a hard edge pops to the wrong value, you're screwed. – ddyer Dec 23 '13 at 23:05      See the "millions of pixels" note above. For sprites of typical sizes (say, on the order of 2048 pixels wide, or smaller) the error will be substantially less than half a pixel, and so will be erased by the inherent rounding of the pixel grid itself. Also, note that rotating 360/7 degrees at a time will accumulate the very same errors. You can eliminate rounding errors with both systems by sticking to increments that are representable as a sum of powers of two (with some limit on the exponent range), but it's probably easier to change to code that doesn't accumulate many small increments. – DMGregory Dec 23 '13 at 23:47      @DMGregory That was what I meant with "inherent rounding error with Pi". The other option is to not use singles/doubles but a way to represent numbers as factors (so representing 2*pi/360 not as the result of the calculation but as that formula) and only calculate the result when needed. I don't know if any "real" programs do that, but stuff like Mathematica can always represent "1/3" as "1/3" instead of "0.333333.....". But after going through the numbers I guess you're right, the rounding error is there but insignificant – Michael Stum Dec 24 '13 at 3:34 2   An angle of 1 degree may be easier to represent accurately in degrees than in radians, rotating an object isn't exact either way, as it requires trigonometrical functions. cos 1° is as much subject to rounding errors as pi/180. – Marcks Thomas Dec 24 '13 at 10:59 Let's agree, that it is better to choose any and stick to it than using two definitions und a little guessing which one of them is necessary for the current function. Then using arc length is more natural for the implementation of sin and cos which might be a reason for cmath to implement it that way. Since games are often written in C++ or C and there is already sin and cos implemented it makes sense to stick to that definition. [Screw you legacy opengl] share|improve this answer      This is not really answering the question. Did you mean to comment on another answer instead? – Josh Petrie Jan 20 '14 at 1:35 Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.821088
How to pretty print a JSON file in Python? Ads   How to pretty print a JSON file in Python? In this tutorial we are going to read a json file and then pretty print the JSON content of file on the console. You can extend the program to save the formatted JSON to another file. In this tutorial we are going to read a json file and then pretty print the JSON content of file on the console. You can extend the program to save the formatted JSON to another file. How to pretty print a JSON file in Python? In this tutorial I will teach you to read the JSON file in Python and then pretty print the content on the console, which a nice way to see the formatted content of the JSON data. This is useful when you have a big JSON file which is not formatted and you want to check the content of the file. In such scenario you can read the JSON file in Python, format the JSON and print the formatted content. The formatted content can be easily viewed by humans. In this tutorial I will read an unformatted JSON file in Python, then use the Python function to format the JSON and print on the console. You can also save the formatted content to another file if you have to read it separately. This is useful if you want to send the formatted JSON file to the testing team for validating the data during the manual testing process. In Python programming people are using json library to work with the JSON files in many different ways. Several times it is easy to pretty print the JSON in Python using various JSON parsing libraries available in Python. Step 1: Reading the JSON file in Python Suppose you have a file called myjson.json with following content: {"1": "Sunday", "2": "Monday", "3": "Tuesday", "4": "Wednesday", "5": "Thursday", "6": "Friday", "7": "Saturday"} And your requirement is to read the content of the file in Python and then format the JSON for pretty printing on console for easy debugging. Then you can use the json library of Python for formatting the content. If you have any other file with then you can use the program here to read and test the program. import json # read JSON file with open('myjson.json', 'r') as jsonfile: json_data=jsonfile.read() print(json_data) Above code prints the content of JSON file, but it is not formatted: JSON file  Step 2: Pretty print JSON file data Now we can first parse the json with with json.loads() function and finally convert it to pretty format with the help of json.dumps(data_json, indent=4)  function. Here is complete code of pretty print file JSON on the console: import json #read JSON file with open('myjson.json', 'r') as jsonfile: json_data=jsonfile.read() print(json_data) #parse Json data_json = json.loads(json_data) #pretty print json pretty_json = json.dumps(data_json, indent=4) print(pretty_json) If you run the code you will get following output: Python pretty print example  Output of the program: >>> import json >>> >>> #read JSON file ... with open('myjson.json', 'r') as jsonfile: ... json_data=jsonfile.read() ... >>> print(json_data) {"1": "Sunday", "2": "Monday", "3": "Tuesday", "4": "Wednesday", "5": "Thursday", "6": "Friday", "7": "Saturday"} >>> >>> #parse Json ... data_json = json.loads(json_data) >>> >>> #pretty print json ... pretty_json = json.dumps(data_json, indent=4) >>> print(pretty_json) { "1": "Sunday", "2": "Monday", "3": "Tuesday", "4": "Wednesday", "5": "Thursday", "6": "Friday", "7": "Saturday" } >>> Step 3: Pretty printing with json.tool You can use python and json.tool for pretty printing the json file content from the terminal. Open the terminal and run following command python3 -m json.tool myjson.json Above command will pretty print the content of the json file file as shown below: Pretty print json file  In this tutorial we have learned the examples of pretty printing the JSON file using Python library. Here more examples of Python: Ads Ads
__label__pos
0.969726
Jump to content john_jack Members • Content Count 77 • Joined • Last visited Everything posted by john_jack 1. var file1 is declared inside javascript, if you try console.log(file1) it should work . when you call Response.Write("file1=" + file1) this is an ASP call which cannot access the variable File1 (which is a javascript variable) Good luck 2. Can you post the entire code please. Or you can check this tutorial https://www.w3schools.com/xml/dom_intro.asp . Good luck 3. I believe this is what you are trying to achieve https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_post sending and receiving Data. 4. You can use Ajax to load data(images, text ....) from a separate file which contains php,asp, txt depending on what you are using once the data is ready to be displayed you can use w3 animation to make it look fancy . Here's the ajax tutorial Ajax. 5. here's a JS library you can use to sign/verify signatures . JsRSAsign 6. on the second screenshot the Enable/disable checkbox is not checked .you should also verify your api-login and transactionkey make sure they are both correct. i assume you already have a woocommerce account linked to your credit card / bank account . 7. you can use this .box-1:hover{ background: #390142; } i am using :hover the CSS will take effect when hovering the class box-1 . and do the same for the other boxes . good luck 8. john_jack Site Help Please Take a look at Media queries https://www.w3schools.com/css/css_rwd_mediaqueries.asp these are what you need to make your style reshape it self when on a small resolution , that can also fix your image size problem .(you gonna have to write your proper css that you want to be executed on each @Media query) for the font problem theres already an existing css file somewhere in the website which overrides your current css . using !important; in css to override the previous css . 9. Share the info provided by the bank then maybe someone can help. 10. here you can check out this tutorial ,might help you do what you ask .Tutorial 11. <?php session_start(); //start the session for the page include("../include/db.php"); //include database file include("../include/settings.php"); //include configuration file //Check if page was entered by a submit button $email=$_POST['email']; //Get username !!FROM FORM!! $email = ereg_replace(" ", "", $email); //take away all spaces from username (if any) !!FROM FORM!! $password=base64_encode($_POST['password']); //Get name !!FROMFORM!! if (empty($email) || empty($password 12. i believe you got gist of it, when using ajax calls, you do not use header :location instead you can echo a unique value depending on the case . and on the javascript side use if(result=="something"){do something} if(result=="somethingelse"){do somethingelse} Good luck 13. replace that with this so you knowwhat you are doing : success: function(result) { alert(result); } and on the php side depending on what error pops up make a code : empty fields echo 0 login was succesfull echo 1 login or pass incorrect echo 2 14. replace the "header('location:../indess.html');" with " echo '0';" all theredirections should be done on the Ajax/Js side 15. replace that with lets say : success: function(result) { if(result=="1") { //here is where you do redirect to ../user.html using javascript check the paths window.location.assign("../user.html") } else { //error hadling show a message login or password incorrect depending on what or where you want to display them } } and replace this with : if($ck->rowCount() > 0){ echo "1 16. firstname isnt the field name it should be $_POST['email']; since you have this : 17. maybe this was the problem ? should'nt it be "./../member/login.php;" what do you get as an error? it would help a lot Good luck 18. i am not sure where all these variables come from or their value ,but heres what you do : when you load the page in the browser check if each the checkboxs have a different value than the other . when that is confirmed ,check the other page that receives the data from the form and try to echo the value of each checkbox to make sure the data was received properly . one last thing was $_SESSION['follow_success'] declared as an array ? if not, then it will only keep the last value received inside the loop . you should also consider a different name for each checkbox, having 19. you can split the page into 2 pages for example index.php : <!DOCTYPE html> <html> <link rel="stylesheet" href="style.css" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet"> <meta name="kontakt"> <head> </head> <body> <div class="col-md-12"> <div class="form-area"> <div id="error" style="color:#FF6633"></div> <form method="post" action="#" onsubmit="sendmail()"> 20. If you want the form error handling to be smooth and user friendly, isuggest you use javascript/ajax check this js/ajax . for the mailing part check this : https://www.w3schools.com/php/func_mail_mail.asp .(if you are working on a local environement the mail will probably fail,you would have to tweek your php.ini but still the email received might be considered as spam) . Good luck. 21. You can store the query results in a multidimensional array check this https://www.w3schools.com/php/func_array.asp "example 4" you can then return the array . 22. If you want to use Javascript, here's the aproach : replace the following : with this : echo '<td data-sort-initial="Descending"><a href="#" onclick="delete_row(' . $row['id'] . ')">Delete</a></td>'; now we will define the function delete_row(x) as a javascript function : function delete_row(x) { // this is to avoid firing the default click on the <a> element event.preventDefault(); var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { 23. let me answer your questions first : 1) Can the "videos" folder be set to private where no one can go to www.mysite.com/videos and see ALL the videos at once? if you have access to your Apache Configuration file you can prevent directory listing and you can also use .htaccess file to prevent that . 2) Will my page be mobile friendly? it depends on your CSS , is your template mobile friendly ? as for the easy way to share your video on your website try to upload the video on youtube and display it on the page , Good luck . 24. i think this is what you are trying to do : $sqllast="UPDATE prodt SET pdname=(SELECT MAX(pdname) from prodt WHERE oid = ".db_escape($oid)." ) + 1 , pcyn = ".db_escape(0)." WHERE id = ".db_escape($a)." AND oid= ".db_escape($oid)." "; hope this helps . × × • Create New...
__label__pos
0.515986
Twisters npm version git repository Demo Screen Shot Display multiple simultaneous animated spinners in node terminal applications Inspired by spinnies and ora Installation npm install twisters or yarn add twisters TypeScript If you use TypeScript, @types/node must also be installed: npm install -D @types/node or yarn add -D @types/node Usage const chalk = require('chalk'); const { Twisters } = require('twisters'); // Create a twisters instance to manage messages const twisters = new Twisters(); // Add a message (messages are active by default) twisters.put('a', { text: 'Hello world!' }); setTimeout(() => { // Update the message twisters.put('a', { // Text can optionally be styled with any ANSI library text: chalk.yellow('This text has been updated') }); }, 2000); setTimeout(() => { // Update the message again twisters.put('a', { // Spinner is not shown when active is false active: false, // Display a yellow prefix before the text text: `${chalk.yellow('+')} Done (4s)` }); }, 4000); Result Usage Screen Shot Options The Twisters class constructor takes an optional options argument. Defaults are used if corresponding values are not defined, which means this: const { Twisters } = require('twisters'); const twisters = new Twisters(); is equivalent to this: const { Twisters, LineBuffer, terminalSupportsUnicode, dots, dashes } = require('twisters'); const twisters = new Twisters({ spinner: terminalSupportsUnicode() ? dots : dashes, flushInactive: true, pinActive: false, messageDefaults: { active: true, removed: false, render: (message, frame) => { const { active, text } = message; return active && frame ? `${frame} ${text}` : text; } }, buffer: new LineBuffer({ EOL: '\n', disable: !!process.env.CI, discardStdin: true, handleSigint: true, stream: process.stderr, truncate: true, wordWrap: false }) }); See the documentation for details: Known Limitations Care must be taken with messages that contain tab (\t) characters. See tabStop for details. Examples See the examples-js and examples-ts packages Documentation See API Documentation Development See README in the repository root License MIT Author Adam Jarret
__label__pos
0.998142
Szunti activity https://gitlab.haskell.org/trac-Szunti 2019-03-11T17:09:00Z tag:gitlab.haskell.org,2019-03-11:139583 Szunti left project Glasgow Haskell Compiler / GHC 2019-03-11T17:09:00Z trac-Szunti Szunti tag:gitlab.haskell.org,2019-03-10:136099 Szunti commented on issue #11792 at Glasgow Haskell Compiler / GHC 2019-03-10T06:38:23Z trac-Szunti Szunti Attached file evil-bug.tar.gz (download). Simple test case tag:gitlab.haskell.org,2019-03-10:93776 Szunti commented on issue #11792 at Glasgow Haskell Compiler / GHC 2019-03-10T02:07:56Z trac-Szunti Szunti Can I help more to get this fixed? tag:gitlab.haskell.org,2019-03-10:92636 Szunti opened issue #11792: Optimised unsafe FFI call can get wrong argument ... 2019-03-10T02:00:58Z trac-Szunti Szunti Attached a simple test case. It should print 7457, but the C function is called with 0 as the third argument. If I compile with -O0 or omit the unsafe keyword in the FFI import it works as it should. In gdb disassembly looks to me as edx (the place for third argument on 64-bit) is set to 7457, then the opaquify is inlined, but it doesn't preserve edx and then third_arg is called with the zeroed edx. Specs 64-bit Archlinux with arch-haskell repo gcc -v: Using built-in specs. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-unknown-linux-gnu/5.3.0/lto-wrapper Target: x86_64-unknown-linux-gnu Configured with: /build/gcc-multilib/src/gcc-5-20160209/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ --enable-shared --enable-threads=posix --enable-libmpx --with-system-zlib --with-isl --enable-__cxa_atexit --disable-libunwind-exceptions --enable-clocale=gnu --disable-libstdcxx-pch --disable-libssp --enable-gnu-unique-object --enable-linker-build-id --enable-lto --enable-plugin --enable-install-libiberty --with-linker-hash-style=gnu --enable-gnu-indirect-function --enable-multilib --disable-werror --enable-checking=release Thread model: posix gcc version 5.3.0 (GCC) ghc compile output: Glasgow Haskell Compiler, Version 7.10.3, stage 2 booted by GHC version 7.10.3 Using binary package database: /usr/lib/ghc-7.10.3/package.conf.d/package.cache wired-in package ghc-prim mapped to ghc-prim-0.4.0.0-6cdc86811872333585fa98756aa7c51e wired-in package integer-gmp mapped to integer-gmp-1.0.0.0-3c8c40657a9870f5c33be17496806d8d wired-in package base mapped to base-4.8.2.0-0d6d1084fbc041e1cded9228e80e264d wired-in package rts mapped to builtin_rts wired-in package template-haskell mapped to template-haskell-2.10.0.0-3c4cb52230f347282af9b2817f013181 wired-in package ghc mapped to ghc-7.10.3-3a39f8f970ff545623196002970730d1 wired-in package dph-seq not found. wired-in package dph-par not found. Hsc static flags: wired-in package ghc-prim mapped to ghc-prim-0.4.0.0-6cdc86811872333585fa98756aa7c51e wired-in package integer-gmp mapped to integer-gmp-1.0.0.0-3c8c40657a9870f5c33be17496806d8d wired-in package base mapped to base-4.8.2.0-0d6d1084fbc041e1cded9228e80e264d wired-in package rts mapped to builtin_rts wired-in package template-haskell mapped to template-haskell-2.10.0.0-3c4cb52230f347282af9b2817f013181 wired-in package ghc mapped to ghc-7.10.3-3a39f8f970ff545623196002970730d1 wired-in package dph-seq not found. wired-in package dph-par not found. *** Chasing dependencies: Chasing modules from: *Main.hs Stable obj: [] Stable BCO: [] Ready for upsweep [NONREC ModSummary { ms_hs_date = 2016-04-05 14:24:20.801997492 UTC ms_mod = Main, ms_textual_imps = [import (implicit) Prelude, import Data.Word] ms_srcimps = [] }] *** Deleting temp files: Deleting: compile: input file Main.hs Created temporary directory: /tmp/ghc1541_0 *** Checking old interface for Main: [1 of 1] Compiling Main ( Main.hs, Main.o ) *** Parser: *** Renamer/typechecker: *** Desugar: Result size of Desugar (after optimization) = {terms: 317, types: 387, coercions: 3} *** Core Linted result of Desugar (after optimization): *** Simplifier: Result size of Simplifier iteration=1 = {terms: 261, types: 290, coercions: 14} *** Core Linted result of Simplifier: Result size of Simplifier iteration=2 = {terms: 216, types: 262, coercions: 18} *** Core Linted result of Simplifier: Result size of Simplifier = {terms: 216, types: 262, coercions: 18} *** Core Linted result of Simplifier: *** Specialise: Result size of Specialise = {terms: 216, types: 262, coercions: 18} *** Core Linted result of Specialise: *** Float out(FOS {Lam = Just 0, Consts = True, OverSatApps = False}): Result size of Float out(FOS {Lam = Just 0, Consts = True, OverSatApps = False}) = {terms: 274, types: 305, coercions: 18} *** Core Linted result of Float out(FOS {Lam = Just 0, Consts = True, OverSatApps = False}): *** Simplifier: Result size of Simplifier iteration=1 = {terms: 407, types: 388, coercions: 70} *** Core Linted result of Simplifier: Result size of Simplifier iteration=2 = {terms: 463, types: 375, coercions: 25} *** Core Linted result of Simplifier: Result size of Simplifier = {terms: 430, types: 362, coercions: 25} *** Core Linted result of Simplifier: *** Simplifier: Result size of Simplifier iteration=1 = {terms: 426, types: 363, coercions: 25} *** Core Linted result of Simplifier: Result size of Simplifier = {terms: 426, types: 363, coercions: 25} *** Core Linted result of Simplifier: *** Simplifier: Result size of Simplifier iteration=1 = {terms: 310, types: 291, coercions: 25} *** Core Linted result of Simplifier: Result size of Simplifier iteration=2 = {terms: 248, types: 217, coercions: 25} *** Core Linted result of Simplifier: Result size of Simplifier iteration=3 = {terms: 336, types: 242, coercions: 25} *** Core Linted result of Simplifier: Result size of Simplifier = {terms: 336, types: 242, coercions: 25} *** Core Linted result of Simplifier: *** Float inwards: Result size of Float inwards = {terms: 336, types: 242, coercions: 25} *** Core Linted result of Float inwards: *** Called arity analysis: Result size of Called arity analysis = {terms: 336, types: 242, coercions: 25} *** Core Linted result of Called arity analysis: *** Simplifier: Result size of Simplifier = {terms: 336, types: 242, coercions: 25} *** Core Linted result of Simplifier: *** Demand analysis: Result size of Demand analysis = {terms: 336, types: 242, coercions: 25} *** Core Linted result of Demand analysis: *** Worker Wrapper binds: Result size of Worker Wrapper binds = {terms: 369, types: 283, coercions: 25} *** Core Linted result of Worker Wrapper binds: *** Simplifier: Result size of Simplifier iteration=1 = {terms: 354, types: 266, coercions: 25} *** Core Linted result of Simplifier: Result size of Simplifier = {terms: 354, types: 266, coercions: 25} *** Core Linted result of Simplifier: *** Float out(FOS {Lam = Just 0, Consts = True, OverSatApps = True}): Result size of Float out(FOS {Lam = Just 0, Consts = True, OverSatApps = True}) = {terms: 356, types: 267, coercions: 25} *** Core Linted result of Float out(FOS {Lam = Just 0, Consts = True, OverSatApps = True}): *** Common sub-expression: Result size of Common sub-expression = {terms: 356, types: 267, coercions: 25} *** Core Linted result of Common sub-expression: *** Float inwards: Result size of Float inwards = {terms: 356, types: 267, coercions: 25} *** Core Linted result of Float inwards: *** Simplifier: Result size of Simplifier = {terms: 356, types: 267, coercions: 25} *** Core Linted result of Simplifier: *** Tidy Core: Result size of Tidy Core = {terms: 356, types: 267, coercions: 25} *** Core Linted result of Tidy Core: writeBinIface: 18 Names writeBinIface: 81 dict entries *** CorePrep: Result size of CorePrep = {terms: 654, types: 379, coercions: 25} *** Core Linted result of CorePrep: *** Stg2Stg: *** CodeGen: *** Assembler: /usr/bin/gcc -fno-stack-protector -DTABLES_NEXT_TO_CODE -I. -x assembler -c /tmp/ghc1541_0/ghc_2.s -o Main.o Upsweep completely successful. *** Deleting temp files: Deleting: /tmp/ghc1541_0/ghc_3.c /tmp/ghc1541_0/ghc_2.s /tmp/ghc1541_0/ghc_1.s Warning: deleting non-existent /tmp/ghc1541_0/ghc_3.c Warning: deleting non-existent /tmp/ghc1541_0/ghc_1.s link: linkables are ... LinkableM (2016-04-05 15:42:11.288210053 UTC) Main [DotO Main.o] Linking Main ... *** C Compiler: /usr/bin/gcc -fno-stack-protector -DTABLES_NEXT_TO_CODE -c /tmp/ghc1541_0/ghc_4.c -o /tmp/ghc1541_0/ghc_5.o -I/usr/lib/ghc-7.10.3/include *** C Compiler: /usr/bin/gcc -fno-stack-protector -DTABLES_NEXT_TO_CODE -c /tmp/ghc1541_0/ghc_7.s -o /tmp/ghc1541_0/ghc_8.o -I/usr/lib/ghc-7.10.3/include *** Linker: /usr/bin/gcc -fno-stack-protector -DTABLES_NEXT_TO_CODE '-Wl,--hash-size=31' -Wl,--reduce-memory-overheads -Wl,--no-as-needed -o Main Main.o Test.o -L/usr/lib/ghc-7.10.3/base_HQfYBxpPvuw8OunzQu6JGM -L/usr/lib/ghc-7.10.3/integ_2aU3IZNMF9a7mQ0OzsZ0dS -L/usr/lib/ghc-7.10.3/ghcpr_8TmvWUcS1U1IKHT0levwg3 -L/usr/lib/ghc-7.10.3/rts /tmp/ghc1541_0/ghc_5.o /tmp/ghc1541_0/ghc_8.o -Wl,-u,ghczmprim_GHCziTypes_Izh_static_info -Wl,-u,ghczmprim_GHCziTypes_Czh_static_info -Wl,-u,ghczmprim_GHCziTypes_Fzh_static_info -Wl,-u,ghczmprim_GHCziTypes_Dzh_static_info -Wl,-u,base_GHCziPtr_Ptr_static_info -Wl,-u,ghczmprim_GHCziTypes_Wzh_static_info -Wl,-u,base_GHCziInt_I8zh_static_info -Wl,-u,base_GHCziInt_I16zh_static_info -Wl,-u,base_GHCziInt_I32zh_static_info -Wl,-u,base_GHCziInt_I64zh_static_info -Wl,-u,base_GHCziWord_W8zh_static_info -Wl,-u,base_GHCziWord_W16zh_static_info -Wl,-u,base_GHCziWord_W32zh_static_info -Wl,-u,base_GHCziWord_W64zh_static_info -Wl,-u,base_GHCziStable_StablePtr_static_info -Wl,-u,ghczmprim_GHCziTypes_Izh_con_info -Wl,-u,ghczmprim_GHCziTypes_Czh_con_info -Wl,-u,ghczmprim_GHCziTypes_Fzh_con_info -Wl,-u,ghczmprim_GHCziTypes_Dzh_con_info -Wl,-u,base_GHCziPtr_Ptr_con_info -Wl,-u,base_GHCziPtr_FunPtr_con_info -Wl,-u,base_GHCziStable_StablePtr_con_info -Wl,-u,ghczmprim_GHCziTypes_False_closure -Wl,-u,ghczmprim_GHCziTypes_True_closure -Wl,-u,base_GHCziPack_unpackCString_closure -Wl,-u,base_GHCziIOziException_stackOverflow_closure -Wl,-u,base_GHCziIOziException_heapOverflow_closure -Wl,-u,base_ControlziExceptionziBase_nonTermination_closure -Wl,-u,base_GHCziIOziException_blockedIndefinitelyOnMVar_closure -Wl,-u,base_GHCziIOziException_blockedIndefinitelyOnSTM_closure -Wl,-u,base_GHCziIOziException_allocationLimitExceeded_closure -Wl,-u,base_ControlziExceptionziBase_nestedAtomically_closure -Wl,-u,base_GHCziEventziThread_blockedOnBadFD_closure -Wl,-u,base_GHCziWeak_runFinalizzerBatch_closure -Wl,-u,base_GHCziTopHandler_flushStdHandles_closure -Wl,-u,base_GHCziTopHandler_runIO_closure -Wl,-u,base_GHCziTopHandler_runNonIO_closure -Wl,-u,base_GHCziConcziIO_ensureIOManagerIsRunning_closure -Wl,-u,base_GHCziConcziIO_ioManagerCapabilitiesChanged_closure -Wl,-u,base_GHCziConcziSync_runSparks_closure -Wl,-u,base_GHCziConcziSignal_runHandlersPtr_closure -lHSbase-4.8.2.0-HQfYBxpPvuw8OunzQu6JGM -lHSinteger-gmp-1.0.0.0-2aU3IZNMF9a7mQ0OzsZ0dS -lHSghc-prim-0.4.0.0-8TmvWUcS1U1IKHT0levwg3 -lHSrts -lCffi -lgmp -lm -lrt -ldl link: done *** Deleting temp files: Deleting: /tmp/ghc1541_0/ghc_10.rsp /tmp/ghc1541_0/ghc_9.rsp /tmp/ghc1541_0/ghc_8.o /tmp/ghc1541_0/ghc_7.s /tmp/ghc1541_0/ghc_6.rsp /tmp/ghc1541_0/ghc_5.o /tmp/ghc1541_0/ghc_4.c *** Deleting temp dirs: Deleting: /tmp/ghc1541_0 Trac metadata Trac field Value Version 7.10.3 Type Bug TypeOfFailure OtherFailure Priority normal Resolution Unresolved Component Compiler Test case Differential revisions BlockedBy Related Blocking CC Operating system Architecture tag:gitlab.haskell.org,2019-03-10:92633 Szunti joined project Glasgow Haskell Compiler / GHC 2019-03-10T02:00:57Z trac-Szunti Szunti
__label__pos
0.842727
P. 1 Modul Persamaan Kuadrat Dan Pertidaksamaan Kuadrat Modul Persamaan Kuadrat Dan Pertidaksamaan Kuadrat |Views: 2,862|Likes: Published by dekle More info: Published by: dekle on Jan 09, 2012 Copyright:Attribution Non-commercial Availability: Read on Scribd mobile: iPhone, iPad and Android. download as PDF, TXT or read online from Scribd See more See less 02/27/2013 pdf text original MODUL MATEMATIKA PERSIAPAN UJIAN NASIONAL 2012 TAHUN AJARAN 2011/2012 MATERI PERSAMAAN KUADRAT DAN PERTIDAKSAMAAN KUADRAT UNTUK KALANGAN MA AL-MU’AWANAH MADRASAH ALIYAH AL-MU’AWANAH BEKASI SELATAN 2012 Jalan RH. Umar Kp. Ceger Rt. 002/018 No. 61 Jakasetia Bekasi Selatan 17147 Website: http://www.ma-almuawanah.sch.id Telp. (021) 82416835 BAB III. PERSAMAAN DAN FUNGSI KUADRAT PERSAMAAN KUADRAT Bentuk Umum: ax2 + bx + c = 0 ; a ≠ 0 Pengertian: x = α adalah akar-akar persamaan ax2 + bx + c = 0 ⇔ a α 2 + b α + c = 0 Cara Menyelesaikan Persamaan Kuadrat: 1. Memfaktorkan: ax2 + bx + c = 0 diuraikan menjadi (x - x 1 ) (x - x 2 ) = 0 atau diubah menjadi bentuk 1 (ax + p) (ax + q) a Menentukan Jenis Akar-Akar Persamaan Kuadrat Menggunakan Diskriminan (D) D = b 2 - 4ac 1. D > 0 Kedua akar nyata dan berlainan (x 1 ≠ x 2 ) 2. D = 0 Mempunyai akar yang sama (x 1 = x 2 ) 3. D < 0 akar tidak nyata 4. D = k 2 ; k 2 = bilangan kuadrat sempurna kedua akar rasional Jumlah dan Hasil Kali Akar-Akar: ax2 + bx + c = 0 b c x1 + x 2 = dan x 1 . x 2 = a a Rumus-rumus yang lain: 1 x1 - x 2 = D a dengan p + q = b dan pq = ac dengan demikian diperoleh p q x1 = dan x 2 = a a 2. Melengkapkan kuadrat sempurna (mempunyai akar yang sama) ( x ± p) = x 2 2 2. x 1 2 + x 2 2 = (x 1 + x 2 )2 – 2 x 1 x 2 3. 4. x 1 2 - x 2 2 = (x 1 - x 2 ) (x 1 + x 2 ) x 1 3 + x 2 3 = (x 1 + x 2 )3 – 3 (x 1 x 2 ) (x 1 + x 2 ) ± 2p + p 2 3. Menggunakan rumus abc x1, 2 = − b ± b 2 − 4ac 2a 5. x 1 3 - x 2 3 = (x 1 - x 2 )3 – 3 (x 1 x 2 ) (x 1 - x 2 ) 6. x + x2 1 1 + = 1 x1 x 2 x1 x2 Menyusun Persamaan Kuadrat Rumus Persamaan Kuadrat yang akar-akarnya x 1 dan x 2 adalah: x2 – (x 1 + x 2 )x + x 1 x 2 = 0 www.belajar-matematika.com - 1 FUNGSI KUADRAT Bentuk Umum: f(x) = ax2 + bx + c dengan a ≠ 0 dan a,b,c ∈ R Menggambar Grafik Fungsi Kuadrat 1. Tentukan titik potong dengan sumbu x (y = 0) 2. Tentukan titik potong dengan sumbu y (x = 0 ) 3. Tentukan titik puncak/Ekstrim : b 2 − 4ac ⎞ ⎛ b ⎟ yaitu ⎜ − ,⎟ 4a ⎝ 2a ⎠ 4. a. Apabila a > 0 grafik terbuka ke atas 3. D < 0 Garis tidak menyinggung dan memotong (terpisah) Menentukan Persamaan Fungsi Kuadrat: 1. Jika diketahui titik puncak = ( x p , y p ) gunakan rumus: y = a (x - x p ) 2 + y p 2. Jika diketahui titik potong dengan sumbu x (y = 0) yakni (x 1 ,0) dan (x 2 ,0) Gunakan rumus: y = a (x - x1 ) ( x - x 2 ) b. Apabila a < 0 grafik terbuka ke bawah 3. Jika yang diketahui selain poin 2 dan 3 maka gunakan rumus : y = ax2 + bx + c Dari y = ax2 + bx + c diperoleh : Kedudukan Garis r terhadap grafik fungsi kuadrat: b 2a 2 b − 4ac 2. Nilai ekstrim y eks = 4a 1. Penyebab ekstrim x = - 1. D > 0 Berpotongan di dua titik y eks = y min jika a > 0 y eks = y maks jika a < 0 2. D = 0 Menyinggung grafik (mempunyai satu titik potong) www.belajar-matematika.com - 2 BAB IV. SISTEM PERSAMAAN LINEAR DAN KUADRAT Persamaan Linear: 1. Persamaan linear satu variabel : ax + b = 0 dengan a ≠ 0 2. Persamaan linear dua variabel ax + by = c dengan a dan b ≠ 0 Cara penyelesaian SPLTV lebih mudah dengan menggunakan metoda gabungan (eliminasi dan substitusi) Sistem Persamaan Linear dan Kuadrat Dua Variabel (SPLKDV) y = ax + b y = px 2 + qx + r bentuk linear bentuk kuadrat Sistem Persamaan Kuadrat (SPK) Sistem Persamaan Linear Dua Variabel (SPLDV) a1x + b1y = c1 a2 x + b2 y = c2 dengan a 1 , a 2 , b 1 , b 2 , c 1 , c 2 ∈ R Penyelesaian SPLDV dapat dilakukan dengan: 1. Metoda Grafik a. Menggambar grafik dengan metoda titik potong sumbu b. Bila kedua garis berpotongan pada satu titik didapat sebuah anggota yaitu (x,y) c. Bila kedua garis sejajar (tidak berpotongan maka) maka tidak didapat angota himpunan penyelesaian d. Bila kedua garis berimpit maka didapat himpunan penyelesaian yang tak terhingga 2. Metoda Substitusi Menggantikan satu variabel dengan variabel dari persamaan yang lain 3. Metoda Eliminasi Menghilangkan salah satu variabel 4. Metoda Eliminasi – Substitusi Menggabungkan metoda Eliminasi dan Substitusi Sistem Persamaan Linear Tiga Variabel (SPLTV) a1x + b1y + c1z = d1 a2 x + b2 y + c2 z = d2 a3x + b3y + c3z = d3 www.belajar-matematika.com - 1 y = ax2 + bx + c y = px 2 + qx + r Cara penyelesaian SPLKDV dan SPK lebih mudah dengan menggunakan metoda substitusi yaitu mensubtitusi persamaan yang satu ke persamaan yang lainnya. BAB V. PERTIDAKSAMAAN Pengertian: Pertidaksamaan adalah kalimat terbuka dimana ruas kiri dan kanannya dihubungkan dengan tanda pertidaksamaan “>” (lebih dari), “<” (kurang dari) , “ ≥ ” (lebih besar dari dan sama dengan” atau “ ≤ ” (lebih kecil dari dan sama dengan). Sifat-sifat Pertidaksamaan: 1. a < b ⇔ b > a 2. Jika a >b maka : a. a ± b > b ± c b. ac > bc apabila c >0 c. ac < bc apabila c < 0 d. a 3 > b 3 3. Jika a > b dan b > c ⇔ a > c 4. Jika a > b dan c > d ⇔ a + c > b + d 5. Jika a > b > 0 dan c > d > 0 ⇔ ac > bd 6. Jika a>b>0 maka : a. a 2 > b 2 1 1 < b. a b Pertidaksamaan Kuadrat: Langkah-langkah penyelesaiannya: 1. Pindahkan semua suku ke ruas kiri 2. Tentukan pembuat nol ruas kiri 3. Tuliskan nilai-nilai tersebut pada garis bilangan 4. Berikan tanda setiap interval 5. Arsir sesuai dengan tanda pertidaksamaan 6. Interval-interval yang diarsir adalah jawabannya Pertidaksamaan Pecahan: Penyelesaiannya dengan langkah persamaan kuadrat dengan syarat penyebut ≠ 0 Pertidaksamaan Bentuk Akar: Langkahnya adalah dengan mengkuadratkan kedua ruas agar bentuk akarnya hilang Pertidaksamaan Harga/Nilai Mutlak: Pengertian nilai mutlak x, jika x ≥ 0 |x| = -x jika x < 0 Misal: |10 | = 10 dan | -10 | = - (-10) = 10 Sehingga | x | tidak pernah negatif 7. a < 0 ⇔ ab<0: b ≠ 0 b a > 0 ⇔ ab>0: b ≠ 0 b Penyelesaian pertidaksamaan harga mutlak adalah dengan menggunakan sifat-sifat berikut: 1. | x | < a ⇒ -a< x < a 2. | x | > a ; a > 0 ⇒ x < -a atau x > a 3. | x | = x2 8. Pertidaksamaan Linear : 4. | x | 2 = x 2 Dikerjakan dengan menggunakan sifat-sifat pertidaksamaan 5. | x | < | y | ⇒ x 2 < y 2 dengan syarat x, y, a ∈ R dan a > 0 www.belajar-matematika.com - 1 KUMPULAN SOAL UN MATEMATIKA 2012 KUMPULAN SOAL MATEMATIKA PERSIAPAN UJIAN NASIONAL (UN) TAHUN 2012 MADRASAH ALIYAH (MA) AL-MU’AWANAH KELAS XII PROGRAM IPS No 2 Standar Kompetensi Lulusan Indikator Memahami konsep yang berkaitan dengan 2.5 Menentukan hasil operasi aljabar akar-akar aturan pangkat, akar dan logaritma, fungsi persamaan kuadrat aljabar sederhana, persamaan dan 2.6 Menyelesaikan pertidaksamaan kuadrat pertidaksamaan kuadrat, system persamaan linear, program linier, matriks, barisan dan deret, serta menggunakanny dalam pemecahan masalah Soal Jika himpunan penyelesaian dari persamaan x2 – 7x + 12 = 0 adalah p dan q maka 2p + q = .... A. -10 B. -7 C. 7 D. 10 E. 14 Akar- akar persamaan kuadrat 6x2 – 5x + 1 = 0 adalah x1 dan x2. Nilai (x1 + x2 ) + (x1 . x2 ) adalah ... No 1 Penyelesaiannya 2 2 3 11 B. 30 3 C. 5 2 D. 3 A. − 3 E. 1 Himpunan penyelesaian dari pertidaksamaan x2 – 11x + 30 ≥ 0 adalah .... A. HP = { x / 5 ≤ x ≤ 6 } B. HP = { x / x ≤ -5 atau x ≥ 6} C. HP = { x / x ≤ 5 atau x ≥ 6 } D. HP = { x / x ≤ -6 atau x ≥ -5 } E. HP = { x / -6 ≤ x ≤ 5 } Akar – akar persamaan kuadrat 2x² + x – 3 = 0 adalah …. 3 A. dan – 1 2 3 B. − dan – 1 2 3 C. − dan – 1 2 2 D. dan 1 3 2 E. − dan 1 3 4 SKL2|KI 2.5-2.6 Madrasah Aliyah Al-Mu’awanah |1 KUMPULAN SOAL UN MATEMATIKA 2012 No 5 Soal Akar – akar persamaan kuadrat 3x² – 2x + 1 = 0 adalah α dan β. Persamaan kuadrat yang akar – akarnya 3α dan 3β adalah …. A. x² – 2x + 3 = 0 B. x² – 3x + 2 = 0 C. x² + 2x – 3 = 0 D. x² + 2x + 3 = 0 E. x² – 3x – 2 = 0 Jika x1 dan x2 adalah akar – akar persamaan kuadrat 2x² – 3x – 7 = 0, maka nilai (x1 + x2 ) ² –2 x1x2 = …. 7 A. − 4 19 B. − 4 27 C. 4 37 D. 4 37 E. 4 Nilai x yang memenuhi x² – 4x – 12 ≤ 0 adalah A. x ≤ – 2 atau x ≥ 6 B. x ≤ – 6 atau x ≥ 2 C. – 2 ≤ x ≤ 6 D. 2 ≤ x ≤ 6 E. – 6 ≤ x ≤ 2 Akar-akar persamaan kuadrat: 2x2 – x – 3 = 0 adalah .... 3 A. - atau -1 2 3 B. - atau 1 2 3 C. atau -1 2 3 D. atau 1 2 2 E. atau 1 3 Persamaan kuadrat yang mempunyai akarakar (1 + 3 ) dan (1 - 3 ) adalah .... A. x2 - 2x +2 = 0 B. x2 - 2x - 2 = 0 C. x2 + 2x -3 = 0 D. x2 + x - 6 = 0 E. x2 - x - 6 = 0 Himpunan penyelesaian dari pertidak- samaan x2 – 5x – 6 ≤ 0 adalah .... A. -1 ≤ x ≤ 6 B. -3 ≤ x ≤ 2 C. x ≤ -1 atau x ≥ 6 D. x ≤ -3 atau x ≥ 2 E. x ≤ -6 atau x ≥ 1 Penyelesaiannya 6 7 8 9 10 SKL2|KI 2.5-2.6 Madrasah Aliyah Al-Mu’awanah |2 KUMPULAN SOAL UN MATEMATIKA 2012 No 11 Soal Jika a dan b adalah akar-akar persamaan kuadrat 3x2 – 13x + 12 = 0, maka nilai ab = .... A. 2 B. 3 C. 4 D. 4 1/3 E. 5 Diketahui x1 dan x2 adalah akar-akar persamaan kuadrat 3x2 – 5x – 6 = 0, maka persamaan kuadrat baru yang akar-akarnya 3x1 dan 3x2 adalah .... A. x2 – 6x – 15 = 0 B. x2 – 6x – 18 = 0 C. x2 – 5x – 15 = 0 D. x2 – 5x – 18 = 0 E. x2 + 5x – 18 = 0 Jika persamaan kuadrat x2 + 3x – 5 = 0, mempunyai akar - akar x1 dan x2, maka nilai x12 + x2 2 = ..... A. -1 B. 1 C. 13 D. 16 E. 19 Himpunan penyelesaian dari pertidaksamaan 3x2 – 22 x + 7 ≥ 0 adalah .... A. {x | x ≤ - 1/3 atau x ≥ 7} B. {x | x ≤ 1/3 atau x ≥ 7} C. {x | x ≤ -7 atau x ≥ 1/3 } D. {x | 1/3 ≤ x ≤ 7} E. {x | -7 ≤ x ≤ 1/3 } Jika x1 dan x2 adalah akar akar persamaan kuadrat 2x2 – 5x + 6 = 0, maka nilai 4x1.x2 = .... A. 3 B. 6 C. 12 D. 14 E. 16 Persamaan kuadrat 2x2 – 2x – 5 = 0 mempunyai akar - akar α dan β , maka nilai dari α 2 + β 2 = ..... A. 2 B. 4 C. 5 D. 6 E. 8 Jika p dan q adalah akar-akar persamaan kuadrat 2x2 – x – 1 = 0, maka persamaan kuadrat yang mempunyai akar - akar 2p dan 2q adalah .... A. x2 + 2x + 1 B. x2 – x + 2 C. x2 – 2x – 1 D. x2 – 2x + 1 E. x2 – x – 2 Penyelesaiannya 12 13 14 15 16 17 SKL2|KI 2.5-2.6 Madrasah Aliyah Al-Mu’awanah |3 KUMPULAN SOAL UN MATEMATIKA 2012 No 18 Soal Himpunan penyelesaian dari pertidaksamaan kuadrat 3x2 – 8x + 4 ≤ 0 adalah .... A. { x | −2 ≤ x ≤ 2 } 3 B. C. D. E. Penyelesaiannya { x | 2 ≤ x ≤ 2} 3 1 { x | 3 ≤ x ≤ 2} { x | − 2 ≤ x atau x ≤ 2} 3 { x | −2 ≤ x atau x ≤ 1} 3 19 20 21 Akar-akar persamaan kuadrat x2 – 6x +5 = 0 adalah x1 dan x2. Persamaan kuadrat yang akar-akarnya x1 + 5 dan x2 + 5 adalah … A. x2 – 16x -60 = 0 B. x2 – 4x = 0 C. x2 +16x +60 = 0 D. x2 – 16x +60 = 0 E. x2 +4x = 0 Nilai x yang memenuhi pertidaksamaan 3− x ≤ 0 adalah .. 2 x + x−6 A. −3 ≤ x ≤ 2 B. 2 ≤ x ≤ 3 C. x ≥ 3 D. x ≤ −3 atau 2 ≤ x ≤ 3 E. −3 ≤ x ≤ 2, atau , x ≥ 3 persamaan kuadrat x2 + ( m – 3 ) x +m = 0 adalah x1 dan x2. Jika , maka nilai m yang 1 1 memenuhi + = 2 adalah ..... x1 x2 A. – 3 B. – 1 C. 1 D. 3 E. 6 Nilai x yang memenuhi pertidaksamaan x < 2 adalah .. A. −4 < x < 4 B. x < 4 C. 0 < x < 4 D. x < −4 atau x > 4 E. x < 0 atau x > 4 Himpunan penyelesaian dari persamaan kuadrat 3x2 + 7x – 6 = 0 adalah x1 dan x2. Nilai x1 + x2 adalah .... A. 3 22 23 2 3 1 B. 2 3 2 C. 1 3 D. – 3 2 3 1 E. – 2 3 SKL2|KI 2.5-2.6 Madrasah Aliyah Al-Mu’awanah |4 KUMPULAN SOAL UN MATEMATIKA 2012 No 24 Soal Akar-akar persamaan kuadrat x2 + x + 2 = 0 adalah x1 dan x2 pers kuadrat yang akarakarnya x1 – 1 dan x2 – 1 adalah .... A. x2 + x + 4 = 0 B. x2 – x + 4 = 0 C. x2 – x – 4 = 0 D. x2 + 4x = 0 E. x2 + 4x = 0 Himpunan penyelesaian pertidaksamaan x2 + 3x – 10 < 0. untuk x ∈ R, adalah .... A. { x / – 2 < x < 5 } B. { x / – 5 < x < – 2 } C. { x / – 2 < x < 3 } D. { x / – 5 < x < 2 } E. { x / – 10 < x < 3 } Penyelesaiannya 25 SKL2|KI 2.5-2.6 Madrasah Aliyah Al-Mu’awanah |5 You're Reading a Free Preview Download scribd /*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->
__label__pos
0.996471
xref: /trafficserver/proxy/InkAPIInternal.h (revision be2102e4) 1 /** @file 2  3  Internal SDK stuff 4  5  @section license License 6  7  Licensed to the Apache Software Foundation (ASF) under one 8  or more contributor license agreements. See the NOTICE file 9  distributed with this work for additional information 10  regarding copyright ownership. The ASF licenses this file 11  to you under the Apache License, Version 2.0 (the 12  "License"); you may not use this file except in compliance 13  with the License. You may obtain a copy of the License at 14  15  http://www.apache.org/licenses/LICENSE-2.0 16  17  Unless required by applicable law or agreed to in writing, software 18  distributed under the License is distributed on an "AS IS" BASIS, 19  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20  See the License for the specific language governing permissions and 21  limitations under the License. 22  */ 23  24 #pragma once 25  26 #include "P_EventSystem.h" 27 #include "URL.h" 28 #include "P_Net.h" 29 #include "HTTP.h" 30 #include "tscore/List.h" 31 #include "ProxyConfig.h" 32 #include "P_Cache.h" 33 #include "I_Tasks.h" 34 #include "Plugin.h" 35  36 #include "ts/InkAPIPrivateIOCore.h" 37 #include "ts/experimental.h" 38  39 #include <typeinfo> 40  41 /* Some defines that might be candidates for configurable settings later. 42  */ 43 #define TS_HTTP_MAX_USER_ARG 16 /* max number of user arguments for Transactions and Sessions */ 44  45 typedef int8_t TSMgmtByte; // Not for external use 46  47 /* ****** Cache Structure ********* */ 48  49 // For memory corruption detection 50 enum CacheInfoMagic { 51  CACHE_INFO_MAGIC_ALIVE = 0xfeedbabe, 52  CACHE_INFO_MAGIC_DEAD = 0xdeadbeef, 53 }; 54  55 struct CacheInfo { 56  CryptoHash cache_key; 57  CacheFragType frag_type = CACHE_FRAG_TYPE_NONE; 58  char *hostname = nullptr; 59  int len = 0; 60  time_t pin_in_cache = 0; 61  CacheInfoMagic magic = CACHE_INFO_MAGIC_ALIVE; 62  CacheInfoCacheInfo63  CacheInfo() {} 64 }; 65  66 class FileImpl 67 { 68  enum { 69  CLOSED = 0, 70  READ = 1, 71  WRITE = 2, 72  }; 73  74 public: 75  FileImpl(); 76  ~FileImpl(); 77  78  int fopen(const char *filename, const char *mode); 79  void fclose(); 80  ssize_t fread(void *buf, size_t length); 81  ssize_t fwrite(const void *buf, size_t length); 82  ssize_t fflush(); 83  char *fgets(char *buf, size_t length); 84  85 public: 86  int m_fd; 87  int m_mode; 88  char *m_buf; 89  size_t m_bufsize; 90  size_t m_bufpos; 91 }; 92  93 struct INKConfigImpl : public ConfigInfo { 94  void *mdata; 95  TSConfigDestroyFunc m_destroy_func; 96  ~INKConfigImplINKConfigImpl97  ~INKConfigImpl() override { m_destroy_func(mdata); } 98 }; 99  100 struct HttpAltInfo { 101  HTTPHdr m_client_req; 102  HTTPHdr m_cached_req; 103  HTTPHdr m_cached_resp; 104  float m_qvalue; 105 }; 106  107 enum APIHookScope { 108  API_HOOK_SCOPE_NONE, 109  API_HOOK_SCOPE_GLOBAL, 110  API_HOOK_SCOPE_LOCAL, 111 }; 112  113 /// A single API hook that can be invoked. 114 class APIHook 115 { 116 public: 117  INKContInternal *m_cont; 118  int invoke(int event, void *edata) const; 119  APIHook *next() const; 120  APIHook *prev() const; 121  LINK(APIHook, m_link); 122 }; 123  124 /// A collection of API hooks. 125 class APIHooks 126 { 127 public: 128  void append(INKContInternal *cont); 129  /// Get the first hook. 130  APIHook *head() const; 131  /// Remove all hooks. 132  void clear(); 133  /// Check if there are no hooks. 134  bool is_empty() const; 135  136 private: 137  Que(APIHook, m_link) m_hooks; 138 }; 139  140 inline bool is_empty() const141 APIHooks::is_empty() const 142 { 143  return nullptr == m_hooks.head; 144 } 145  146 /** Container for API hooks for a specific feature. 147  148  This is an array of hook lists, each identified by a numeric identifier (id). Each array element is a list of all 149  hooks for that ID. Adding a hook means adding to the list in the corresponding array element. There is no provision 150  for removing a hook. 151  152  @note The minimum value for a hook ID is zero. Therefore the template parameter @a N_ID should be one more than the 153  maximum hook ID so the valid ids are 0..(N-1) in the standard C array style. 154  */ 155 template <typename ID, ///< Type of hook ID 156  int N ///< Number of hooks 157  > 158 class FeatureAPIHooks 159 { 160 public: 161  FeatureAPIHooks(); ///< Constructor (empty container). 162  ~FeatureAPIHooks(); ///< Destructor. 163  164  /// Remove all hooks. 165  void clear(); 166  /// Add the hook @a cont to the end of the hooks for @a id. 167  void append(ID id, INKContInternal *cont); 168  /// Get the list of hooks for @a id. 169  APIHook *get(ID id) const; 170  /// @return @c true if @a id is a valid id, @c false otherwise. 171  static bool is_valid(ID id); 172  173  /// Invoke the callbacks for the hook @a id. 174  void invoke(ID id, int event, void *data); 175  176  /// Fast check for any hooks in this container. 177  /// 178  /// @return @c true if any list has at least one hook, @c false if 179  /// all lists have no hooks. 180  bool has_hooks() const; 181  182  /// Check for existence of hooks of a specific @a id. 183  /// @return @c true if any hooks of type @a id are present. 184  bool has_hooks_for(ID id) const; 185  186  /// Get a pointer to the set of hooks for a specific hook @id 187  APIHooks const *operator[](ID id) const; 188  189 private: 190  bool m_hooks_p = false; ///< Flag for (not) empty container. 191  /// The array of hooks lists. 192  APIHooks m_hooks[N]; 193 }; 194  FeatureAPIHooks()195 template <typename ID, int N> FeatureAPIHooks<ID, N>::FeatureAPIHooks() {} 196  ~FeatureAPIHooks()197 template <typename ID, int N> FeatureAPIHooks<ID, N>::~FeatureAPIHooks() 198 { 199  this->clear(); 200 } 201  202 template <typename ID, int N> 203 void clear()204 FeatureAPIHooks<ID, N>::clear() 205 { 206  for (auto &h : m_hooks) { 207  h.clear(); 208  } 209  m_hooks_p = false; 210 } 211  212 template <typename ID, int N> 213 void append(ID id,INKContInternal * cont)214 FeatureAPIHooks<ID, N>::append(ID id, INKContInternal *cont) 215 { 216  if (is_valid(id)) { 217  m_hooks_p = true; 218  m_hooks[id].append(cont); 219  } 220 } 221  222 template <typename ID, int N> 223 APIHook * get(ID id) const224 FeatureAPIHooks<ID, N>::get(ID id) const 225 { 226  return likely(is_valid(id)) ? m_hooks[id].head() : nullptr; 227 } 228  operator [](ID id) const229 template <typename ID, int N> APIHooks const *FeatureAPIHooks<ID, N>::operator[](ID id) const 230 { 231  return likely(is_valid(id)) ? &(m_hooks[id]) : nullptr; 232 } 233  234 template <typename ID, int N> 235 void invoke(ID id,int event,void * data)236 FeatureAPIHooks<ID, N>::invoke(ID id, int event, void *data) 237 { 238  if (likely(is_valid(id))) { 239  m_hooks[id].invoke(event, data); 240  } 241 } 242  243 template <typename ID, int N> 244 bool has_hooks() const245 FeatureAPIHooks<ID, N>::has_hooks() const 246 { 247  return m_hooks_p; 248 } 249  250 template <typename ID, int N> 251 bool is_valid(ID id)252 FeatureAPIHooks<ID, N>::is_valid(ID id) 253 { 254  return 0 <= id && id < N; 255 } 256  257 class HttpAPIHooks : public FeatureAPIHooks<TSHttpHookID, TS_HTTP_LAST_HOOK> 258 { 259 }; 260  261 class TSSslHookInternalID 262 { 263 public: TSSslHookInternalID(TSHttpHookID id)264  explicit constexpr TSSslHookInternalID(TSHttpHookID id) : _id(id - TS_SSL_FIRST_HOOK) {} 265  266  constexpr operator int() const { return _id; } 267  268  static const int NUM = TS_SSL_LAST_HOOK - TS_SSL_FIRST_HOOK + 1; 269  270  constexpr bool is_in_bounds() const271  is_in_bounds() const 272  { 273  return (_id >= 0) && (_id < NUM); 274  } 275  276 private: 277  const int _id; 278 }; 279  280 class SslAPIHooks : public FeatureAPIHooks<TSSslHookInternalID, TSSslHookInternalID::NUM> 281 { 282 }; 283  284 class LifecycleAPIHooks : public FeatureAPIHooks<TSLifecycleHookID, TS_LIFECYCLE_LAST_HOOK> 285 { 286 }; 287  288 class ConfigUpdateCallback : public Continuation 289 { 290 public: ConfigUpdateCallback(INKContInternal * contp)291  explicit ConfigUpdateCallback(INKContInternal *contp) : Continuation(contp->mutex.get()), m_cont(contp) 292  { 293  SET_HANDLER(&ConfigUpdateCallback::event_handler); 294  } 295  296  int event_handler(int,void *)297  event_handler(int, void *) 298  { 299  if (m_cont->mutex) { 300  MUTEX_TRY_LOCK(trylock, m_cont->mutex, this_ethread()); 301  if (!trylock.is_locked()) { 302  eventProcessor.schedule_in(this, HRTIME_MSECONDS(10), ET_TASK); 303  } else { 304  m_cont->handleEvent(TS_EVENT_MGMT_UPDATE, nullptr); 305  delete this; 306  } 307  } else { 308  m_cont->handleEvent(TS_EVENT_MGMT_UPDATE, nullptr); 309  delete this; 310  } 311  312  return 0; 313  } 314  315 private: 316  INKContInternal *m_cont; 317 }; 318  319 class ConfigUpdateCbTable 320 { 321 public: 322  ConfigUpdateCbTable(); 323  ~ConfigUpdateCbTable(); 324  325  void insert(INKContInternal *contp, const char *name); 326  void invoke(const char *name); 327  void invoke(INKContInternal *contp); 328  329 private: 330  std::unordered_map<std::string, INKContInternal *> cb_table; 331 }; 332  333 class HttpHookState 334 { 335 public: 336  /// Scope tags for interacting with a live instance. 337  enum ScopeTag { GLOBAL, SSN, TXN }; 338  339  /// Default Constructor 340  HttpHookState(); 341  342  /// Initialize the hook state to track up to 3 sources of hooks. 343  /// The argument order to this method is used to break priority ties (callbacks from earlier args are invoked earlier) 344  /// The order in terms of @a ScopeTag is GLOBAL, SESSION, TRANSACTION. 345  void init(TSHttpHookID id, HttpAPIHooks const *global, HttpAPIHooks const *ssn = nullptr, HttpAPIHooks const *txn = nullptr); 346  347  /// Select a hook for invocation and advance the state to the next valid hook 348  /// @return nullptr if no current hook. 349  APIHook const *getNext(); 350  351  /// Get the hook ID 352  TSHttpHookID id() const; 353  354  /// Temporary function to return true. Later will be used to decide if a plugin is enabled for the hooks 355  bool is_enabled(); 356  357 protected: 358  /// Track the state of one scope of hooks. 359  struct Scope { 360  APIHook const *_c; ///< Current hook (candidate for invocation). 361  APIHook const *_p; ///< Previous hook (already invoked). 362  APIHooks const *_hooks; ///< Reference to the real hook list 363  364  /// Initialize the scope. 365  void init(HttpAPIHooks const *scope, TSHttpHookID id); 366  /// Clear the scope. 367  void clear(); 368  /// Return the current candidate. 369  APIHook const *candidate(); 370  /// Advance state to the next hook. 371  void operator++(); 372  }; 373  374 private: 375  TSHttpHookID _id; 376  Scope _global; ///< Chain from global hooks. 377  Scope _ssn; ///< Chain from session hooks. 378  Scope _txn; ///< Chain from transaction hooks. 379 }; 380  381 inline TSHttpHookID id() const382 HttpHookState::id() const 383 { 384  return _id; 385 } 386  387 void api_init(); 388  389 extern HttpAPIHooks *http_global_hooks; 390 extern LifecycleAPIHooks *lifecycle_hooks; 391 extern SslAPIHooks *ssl_hooks; 392 extern ConfigUpdateCbTable *global_config_cbs; 393 
__label__pos
0.967578
Simplify 2303/2278 to lowest terms / Solution for what is 2303/2278 in simplest fraction 2303/2278 = Now we have: what is 2303/2278 in simplest fraction = 2303/2278 Question: How to reduce 2303/2278 to its lowest terms? Step by step simplifying fractions: Step 1: Find GCD(2303,2278) = 1. Step 2: Can't simplify any further Therefore, 2303/2278 is simplified fraction for 2303/2278
__label__pos
0.999502
Linked Questions 602 votes 19 answers 156k views Where can I find examples of good Mathematica programming practice? I consider myself a pretty good Mathematica programmer, but I'm always looking out for ways to either improve my way of doing things in Mathematica, or to see if there's something nifty that I haven't ... 45 votes 4 answers 5k views Can a function be made to accept a variable amount of inputs? I have a function that takes two inputs and processes them for a single output. What I need is one that can take a varying number of inputs. and process them to a single output. Is this possible in ... Nothingtoseehere's user avatar 20 votes 1 answer 324 views How to get Cases to wrap results in an arbitrary head? A number of functions provide for results to be wrapped in an arbitrary head. This is very important in cases where the results should not be evaluated. Take Level... Mr.Wizard's user avatar • 272k 16 votes 2 answers 688 views f[arg1, arg2,...,argN] vs. f[{arg1, arg2,...,argN}] I am trying to reproduce the API of a function (written in R) that accepts an arbitrary number of arguments and handles it the same way as it would handle a single argument that is a list of different ... Eric Brown's user avatar • 4,426 14 votes 9 answers 2k views How can a power of 0 or 1 be replaced? Consider this given example for ReplaceAll 1 + x^2 + x^4 /. x^p_ -> f[p] This returns ... Sumit's user avatar • 15.9k 12 votes 9 answers 562 views List manipulation - adding last element of sublist to each sublist If I have the following list: {{}, {1, 2}, {}, {2, 4, 3}, {5, 4, 3, 2}, {}} How can I add the last element of each sublist to each sublist? The results should ... lio's user avatar • 2,396 10 votes 4 answers 2k views Function argument to default under certain condition Inspired by this and this question (and how I handle this in practice), what is the best way to default a function value when a certain condition is met? For example, if a function is defined as: <... kale's user avatar • 10.9k 9 votes 5 answers 465 views How to distinguish between lists and values? I have a (hopefully small) problem with some numerical integration algorithm, more specifically I want to integrate the imaginary part of a complex valued function, e.g. ... user13655's user avatar • 377 9 votes 3 answers 2k views Function with zero or one arguments Is there a neat way to define a function with a single optional argument that defaults to an empty sequence? For example, suppose I want to define a wrapper for ... Stephen Powell's user avatar 9 votes 3 answers 760 views Generalization to AllTrue, AnyTrue and NoneTrue I am wondering if there is a natural Mathematica way to generalize those functions. To be specific, All three functions AllTrue, ... Sungmin's user avatar • 2,305 5 votes 2 answers 304 views Function pattern to support listed and non-listed arguments [duplicate] I often want to write functions that take as an argument either a) a rule or b) a list of rules. As an example, when using Replace with just one rule, it does not ... Theo Tiger's user avatar • 1,273 4 votes 2 answers 397 views Generating all permutations of labels in an expression I have some very long and complex expressions which involve a set of $n$ variables, and I want to be able to permute the labels of the variables. I will give a simple example, instead of my awful ... Jojo's user avatar • 1,278 3 votes 1 answer 188 views Optional argument as a correction of a main argument Let's consider a function f[a_,b___] I want that if I input only one argument I get f[a]=a but if I input 2 arguments I ... Giancarlo's user avatar • 712
__label__pos
0.653834
Question How to have Google assistant change volume of group of speakers? • 12 July 2020 • 4 replies • 148 views Hi Guys, Quick question regarding the google assistant.  I have a setup in the living room with 1 Google One, and 2 google One SL’s. They are all 3 combined in a group. When I want to change the volume using google assistant, it only changes the volume of the One that has the microphone. They other One SL’s stay at the same volume. What am I doing wrong? Many thanks 4 replies Userlevel 5 Badge +16 HI @DaanL. Welcome to the Sonos community and thanks for reaching out to us. I would like to agree with @Ken_Griffiths. This is a feature limitation between the integration of Google Assistant with Sonos. However, I would be morethan happy to send this to our engineering department to take a look at and see if they can have this addressed on our end.  Just to set your expectation, I would recommend subscribing to this topic and the Announcement thread to be updated about any feature release as it may or may not contain your feature request. Please let me know if you still have further questions or concerns. We are always here to help out. Thanks, Yes, you have to adjust each room-volume in a group by including each separate ‘room-name’ within the voice instructions ..let’s hope the matter gets sorted in the not too distant future.🤞 DaanL, You’re not doing anything wrong here, the adjustment of the volume, as far as the current Google integration on Sonos, works the same as the speaker hardware volume buttons, when in a group situation. The feature to adjust the group volume has been submitted for consideration by me and others, but Google/Sonos do not usually announce their development path, or give dates etc. I understand the Amazon Alexa integration, which started a year, or so, before the Google integration, does have group volume control, so hopefully Google will follow suit. It’s a case of waiting to see what each new update will bring. Hope that answers your post? It does, thank you. Although I am surprised that such a basic function is not implemented yet.  Thanks DaanL, You’re not doing anything wrong here, the adjustment of the volume, as far as the current Google integration on Sonos, works the same as the speaker hardware volume buttons, when in a group situation. The feature to adjust the group volume has been submitted for consideration by me and others, but Google/Sonos do not usually announce their development path, or give dates etc. I understand the Amazon Alexa integration, which started a year, or so, before the Google integration, does have group volume control, so hopefully Google will follow suit. It’s a case of waiting to see what each new update will bring. Hope that answers your post? Reply
__label__pos
0.674707
Should I switch from POP Gmail to IMAP Gmail? Discussion in 'Mac Apps and Mac App Store' started by beethovengirl, Jan 24, 2008. 1. beethovengirl macrumors regular Joined: Jan 15, 2004 #1 Hi, I've been happily using POP Gmail with Leopard Mail. The only reason I'm even thinking about IMAP is that I'd like to have access to my Spam folder w/o having to log into Gmail via my web browser. I'm told the only way to access the Spam folder in Mail.app is to switch to IMAP Gmail. Is this true? I am wary of switching to IMAP b/c I used to have IMAP email at my old university, and when I was about to lose my account at the university after graduating, I discovered that even though my email appeared to be stored on my computer, it actually wasn't -- i.e. I could not recover the messages like I can with POP, as the "full" messages were actually on the server and stored in some weird way on my computer. When I was copying my IMAP mail folder to my computer, hundreds of messages disappeared in the process, so since then, I've been wary of IMAP. If I had a mobile lifestyle [like an iPhone], I can understand the need for IMAP, but I don't work and spend most of my time at home with my MacBook. Was this a peculiarity of my university's IMAP system? Are Gmail IMAP messages stored on my hard drive the same way that Gmail POP messages are? I've read about a lot of people having problems with IMAP Gmail and Mail.app, so there's yet another reason that I'm wary. As it turns out, Amazon is letting me return my defective SR MacBook [multiple kernel panics], so I'm about to transfer files from my old MacBook to my new MacBook. I suppose now might be a good time to make the switch, if it's a good idea to make the switch. If so, should I not transfer my old Gmail POP messages to my new computer? I'd appreciate any advice you may have. Thank you :)   2. swiftaw macrumors 603 swiftaw Joined: Jan 31, 2005 Location: Omaha, NE, USA #2 When setting up your IMAP account in mail.app there is an option to keep copies of all messages on your machine so that you can still access them all even if you are no longer connected to the IMAP server.   3. beethovengirl thread starter macrumors regular Joined: Jan 15, 2004 #3 thanks for your reply, swiftaw! :) With my old university IMAP email acct, I could still read my messages when I wasn't connected to the IMAP server. Apparently, they were stored in some weird way. For example, in my IMAP inbox for my old email acct, most of the messages in my inbox look as they did when my account was active, but the emails from the last day only have the date, sender, and subject -- no text inside, even though I could read the message text in Apple Mail before my account was deactivated. [Those messages are backed up in my "On My Mac" copy of my IMAP mailbox] What is your opinion on the problems people have been having with IMAP Gmail and Mail.app?   4. stomer macrumors 6502a Joined: Apr 2, 2007 Location: Leeds, UK #4 I've been using Mail.app with Gmail IMAP for the past few months, and I've not experienced any problems. It's a lot better than pop because both my Mac Mini and my MacBook have their email databases perfectly in sync because they both retrieve my email via IMAP. This wouldn't be possible if I were to use POP. Also, a POP server has to be polled at various intervals in order to check for any new mail. An IMAP server can work a little differently, it can 'push' the email to your email client whenever an email arrives. It did take a little while to get my head around how Gmail manages its labels and IMAP, but now everything works as I'd expect it to.   5. beethovengirl thread starter macrumors regular Joined: Jan 15, 2004 #5 I have some follow-up questions... Let's say that Gmail loses all of my email due to some server attack. I mean, I'm not paying for this service, so I can't expect them to expend resources getting my messages back in this scenario. If I choose the option to keep copies of all message on my machine, will they actually be there if Mail.app updates itself and sees that there are no messages on the server? Also, if I decide to stay with POP Gmail for the time being, is it easy to switch to IMAP Gmail at a later date? thanks for your help :)   6. QCassidy352 macrumors G4 QCassidy352 Joined: Mar 20, 2003 Location: Bay Area #6 A couple of things. First, I understand your concern about a cataclysmic gmail server problem, but I think it's pretty unlikely, and moreover, even though the service is free, it is their business. So I think that in the unlikely event of a nuclear meltdown (figuratively speaking) they would make every attempt to make things right. Just because you're not paying them doesn't mean that customer satisfaction isn't very important to their bottom line. Second, you can always create local folders on your mac. That's what I do. I have the inbox, sent, drafts, and trash folders synced to the gmail server, but I also have a number of local folders. I don't know how you manage your email, but I'm the type who likes to keep his inbox to a minimum (like 10-15 messages). Everything else of any importance gets filed in a local folder. So even if there were a total meltdown of the servers, and google couldn't or wouldn't retrieve the lost emails, I'd be out a pretty modest number of messages. And what would likely happen is that your mac would try to sync to the server, tell you it couldn't connect, and it would not delete the messages from your inbox because it's not that it wouldn't see any messages on the server; it wouldn't see the server at all! So in short, I think there is very, very little to worry about with IMAP. IMO the chances of something happening to my macbook are far greater than the chances of something happening to google's servers, making IMAP in fact safer than POP (of course, that's what local backups are for, but I think the chances of my macbook and my external HD both failing are still greater than the chances of google's servers dying). Sorry this got so long, but hope it helps! :)   7. Queso Suspended Joined: Mar 4, 2006 #7 I use GMail as my master set of folders and sync to both my Macs, with a subset of message synced to my mobile phone. It's also configured to check two POP3 accounts and to accept forwarding from my own mail domain. Works brilliantly. The only gripe I have is that I want my domain name as my default address, but Outlook users can sometimes get "me@gmail on behalf of [email protected]" as the sender, which I worry might get confusing. Not a problem when I'm at home as I just send out via my ISP's SMTP server, but a bit of an issue when out and about. I definitely recommend doing it though. It makes life a lot easier when you not only have your Inbox, but also your Sent Items available wherever you are. IMAP as a protocol is also a lot more secure than POP3.   Share This Page
__label__pos
0.634057
C-Command Software Forum Turn off Empty Trash warning? Any way to turn off the warning that appears when you Empty Trash? If you hold down the Option key when choosing Empty Trash, EagleFiler will skip the warning. Not on my machine (EF 1.2.7, OSX 10.4.10, Intel). I have tried: 1. hold down option key while right-clicking on Trash, then select Empty Trash, 2. right-click on Trash, then hold Option key while selecting Empty Trash In both cases, I get the confirmation dialog box. What am I missing? Sorry but, at present, the Option-key trick works when you choose File > Empty Trash, but not with the contextual menu. This is fixed in EagleFiler 1.3.
__label__pos
1
#! perl #------------------------------------------------------------------------------- # CUSTOM STYLE SHEET GENERATOR by Chris Etzel # this is a project that a friend and I are working on for shits and giggles. # one of these days it will have a nice skinned gui, may have to use C of VB to # get the gui the way we want it. But for now, it is a standard boring gray # window.... # feel free to edit, change, rewrite the code as needed to suit your purposes. # just try and credit me for the original. Thanks - Chris #------------------------------------------------------------------------------- use Win32::GUI; # declaring scalars to contain css properties - based off user input my ( #BODY SCALARS $bgcolor, $fontsize, $fontfam, $topmargin, $leftmargin, #LINK SCALARS $lcolor, $lfontsize, $lfontfam, $ltextdec, #ACTIVE LINK SCALARS $alcolor, $alfontsize, $alfontfam, $altextdec, #VISITED LINK SCALARS $vlcolor, $vlfontsize, $vlfontfam, $vltextdec, #HOVER (mouseOver) SCALARS $hcolor, $hfontsize, $hfontfam, $htextdec, #TABLE DATA FONT SCALARS $tdcolor, $tdfontsize, $tdfontfam, $tdtextdec ); # create the main window $Win1 = Win32::GUI::DialogBox->new( -name=>"Win1", -size=>[640,480], -top=>50, -left=>50, -title=>"CSS Generator v (0)", -helpbutton=>0, ); $Win1->Show(); #testing menu # still having trouble with a file - menu - need to work on my Win32-gui coding # some more. lol #$Menu = new Win32::GUI::Menu($Win1, # "&File" => "File", # " > &Load" => "FileLoad", # ); # bgcolor text field $bgcolortf=$Win1->AddTextfield( -name=>"bgcolortf", -width=>75, -height=>20, -top=>10, -left=>10, -tabstop=>1, -text=>"#FFFFFF", ); # body font color text field $bfcolortf=$Win1->AddTextfield( -name=>"bfonttf", -width=>75, -height=>20, -top=>35, -left=>10, -tabstop=>1, -text=>"#000000", ); #link color text field $lfontcolortf=$Win1->AddTextfield( -name=>"lfonttf", -width=>75, -height=>20, -top=>60, -left=>10, -tabstop=>1, -text=>"#FF0000", ); #visited link color text field $vfontcolortf=$Win1->AddTextfield( -name=>"vfonttf", -width=>75, -height=>20, -top=>85, -left=>10, -tabstop=>1, -text=>"#0000FF", ); #active link color text field $afontcolortf=$Win1->AddTextfield( -name=>"afonttf", -width=>75, -height=>20, -top=>110, -left=>10, -tabstop=>1, -text=>"#F0FF00", ); #hover (mouseover) link color text field $hcolortf=$Win1->AddTextfield( -name=>"hcolortf", -width=>75, -height=>20, -top=>135, -left=>10, -tabstop=>1, -text=>"#FF00FF", ); # td font color text field $tdcolortf=$Win1->AddTextfield( -name=>"tdcolortf", -width=>75, -height=>20, -text=>"#000000", -top=>160, -left=>10, -tabstop=>1, ); #bgcolor label $bgcolorlb=$Win1->AddLabel( -name=>"bgcolorlb", -width=>75, -height=>20, -text=>"BGCOLOR", -top=>17, -left=>90, -tabstop=>0, ); $Win1->bgcolorlb->Show(); #font color label $bfcolorlbl=$Win1->AddLabel( -name=>"bfcolorlbl", -width=>75, -height=>20, -text=>"FONT COLOR", -top=>42, -left=>90, -tabstop=>0, ); $Win1->bfcolorlbl->Show(); #link color label $lfcolorlbl=$Win1->AddLabel( -name=>"lfcolorlbl", -width=>75, -height=>20, -text=>"LINK COLOR", -top=>67, -left=>90, -tabstop=>0, ); $Win1->lfcolorlbl->Show(); # visited link color label $vfcolorlbl=$Win1->AddLabel( -name=>"vfcolorlbl", -width=>75, -height=>20, -text=>"VLINK COLOR", -top=>92, -left=>90, -tabstop=>0, ); $Win1->vfcolorlbl->Show(); #active link color label $afcolorlbl=$Win1->AddLabel( -name=>"afcolorlbl", -width=>75, -height=>20, -text=>"ALINK COLOR", -top=>117, -left=>90, -tabstop=>0, ); $Win1->afcolorlbl->Show(); # hover link color label $hfcolorlbl=$Win1->AddLabel( -name=>"hfcolorlbl", -width=>75, -height=>20, -text=>"HLINK COLOR", -top=>142, -left=>90, -tabstop=>0, ); $Win1->hfcolorlbl->Show(); # td color label $tdcolorlbl=$Win1->AddLabel( -name=>"tdcolorlbl", -width=>90, -height=>20, -text=>"TDFONT COLOR", -top=>167, -left=>90, -tabstop=>0, ); $Win1->tdcolorlbl->Show(); # this is the start of the font face selections for the stylesheet. they are # in a dropdown with option to enter custom font (not recommended...of course) # body font face selection... $bfontdd=$Win1->AddCombobox( -name=>"bfontdd", -width=>100, -height=>140, -tabstop=>1, -top=>242, -left=>80, -style=> WS_VISIBLE | WS_SCROLL | 3 | WS_TABSTOP ); # create the actual font list $bfontdd->InsertItem("Arial, Helvetica, sans-serif"); $bfontdd->InsertItem("Times New Roman, Times, serif"); $bfontdd->InsertItem("Courier New, Courier, mono"); $bfontdd->InsertItem("Georgia, Times New Roman, Times, serif"); $bfontdd->InsertItem("Verdana, Arial, Helvetica, sans-serif"); $bfontdd->InsertItem("Geneva, Arial, Helvetica, san-serif"); $bfontdd->InsertItem("custom --->"); $bfontdd->Select(1); sub bfontdd_Change{ $bfontdd->Text($bfontdd->GetString($bfontdd->SelectedItem)); } #if the font is a selected one, $bfontfam is the selected font, #otherwise, you can enter a custom font and the $bfontfam is the #text you enter in the field to the right # create the custom text field for the bfontfam variable $bfcustom=$Win1->AddTextfield( -name=>"bfcustom", -width=>75, -height=>20, #-text=> -top=>242, -left=>180, -tabstop=>1, ); # link font face $lfontdd=$Win1->AddCombobox( -name=>"lfontdd", -width=>100, -height=>140, -tabstop=>1, -top=>267, -left=>80, -style=> WS_VISIBLE | WS_SCROLL | 3 | WS_TABSTOP ); # create the actual font list $lfontdd->InsertItem("Arial, Helvetica, sans-serif"); $lfontdd->InsertItem("Times New Roman, Times, serif"); $lfontdd->InsertItem("Courier New, Courier, mono"); $lfontdd->InsertItem("Georgia, Times New Roman, Times, serif"); $lfontdd->InsertItem("Verdana, Arial, Helvetica, sans-serif"); $lfontdd->InsertItem("Geneva, Arial, Helvetica, san-serif"); $lfontdd->InsertItem("custom --->"); $lfontdd->Select(1); sub lfontdd_Change{ $lfontdd->Text($lfontdd->GetString($lfontdd->SelectedItem)); } #if the font is a selected one, $lfontfam is the selected font, #otherwise, you can enter a custom font and the $lfontfam is the #text you enter in the field to the right # create the custom text field for the bfontfam variable $lfcustom=$Win1->AddTextfield( -name=>"lfcustom", -width=>75, -height=>20, #-text=> -top=>267, -left=>180, -tabstop=>1, ); # vlink font face $vfontdd=$Win1->AddCombobox( -name=>"vfontdd", -width=>100, -height=>140, -tabstop=>1, -top=>292, -left=>80, -style=> WS_VISIBLE | WS_SCROLL | 3 | WS_TABSTOP ); # create the actual font list $vfontdd->InsertItem("Arial, Helvetica, sans-serif"); $vfontdd->InsertItem("Times New Roman, Times, serif"); $vfontdd->InsertItem("Courier New, Courier, mono"); $vfontdd->InsertItem("Georgia, Times New Roman, Times, serif"); $vfontdd->InsertItem("Verdana, Arial, Helvetica, sans-serif"); $vfontdd->InsertItem("Geneva, Arial, Helvetica, san-serif"); $vfontdd->InsertItem("custom --->"); $vfontdd->Select(1); sub vfontdd_Change{ $vfontdd->Text($vfontdd->GetString($vfontdd->SelectedItem)); } #if the font is a selected one, $vfontfam is the selected font, #otherwise, you can enter a custom font and the $vfontfam is the #text you enter in the field to the right # create the custom text field for the bfontfam variable $vfcustom=$Win1->AddTextfield( -name=>"vfcustom", -width=>75, -height=>20, #-text=> -top=>292, -left=>180, -tabstop=>1, ); # alink font face $afontdd=$Win1->AddCombobox( -name=>"afontdd", -width=>100, -height=>140, -tabstop=>1, -top=>317, -left=>80, -style=> WS_VISIBLE | WS_SCROLL | 3 | WS_TABSTOP ); # create the actual font list $afontdd->InsertItem("Arial, Helvetica, sans-serif"); $afontdd->InsertItem("Times New Roman, Times, serif"); $afontdd->InsertItem("Courier New, Courier, mono"); $afontdd->InsertItem("Georgia, Times New Roman, Times, serif"); $afontdd->InsertItem("Verdana, Arial, Helvetica, sans-serif"); $afontdd->InsertItem("Geneva, Arial, Helvetica, san-serif"); $afontdd->InsertItem("custom --->"); $afontdd->Select(1); sub afontdd_Change{ $afontdd->Text($afontdd->GetString($afontdd->SelectedItem)); } #if the font is a selected one, $afontfam is the selected font, #otherwise, you can enter a custom font and the $afontfam is the #text you enter in the field to the right # create the custom text field for the bfontfam variable $afcustom=$Win1->AddTextfield( -name=>"afcustom", -width=>75, -height=>20, #-text=> -top=>317, -left=>180, -tabstop=>1, ); # hlink font $hfontdd=$Win1->AddCombobox( -name=>"hfontdd", -width=>100, -height=>140, -tabstop=>1, -top=>342, -left=>80, -style=> WS_VISIBLE | WS_SCROLL | 3 | WS_TABSTOP ); # create the actual font list $hfontdd->InsertItem("Arial, Helvetica, sans-serif"); $hfontdd->InsertItem("Times New Roman, Times, serif"); $hfontdd->InsertItem("Courier New, Courier, mono"); $hfontdd->InsertItem("Georgia, Times New Roman, Times, serif"); $hfontdd->InsertItem("Verdana, Arial, Helvetica, sans-serif"); $hfontdd->InsertItem("Geneva, Arial, Helvetica, san-serif"); $hfontdd->InsertItem("custom --->"); $hfontdd->Select(1); sub afontdd_Change{ $hfontdd->Text($hfontdd->GetString($hfontdd->SelectedItem)); } #if the font is a selected one, $hfontfam is the selected font, #otherwise, you can enter a custom font and the $hfontfam is the #text you enter in the field to the right # create the custom text field for the bfontfam variable $hfcustom=$Win1->AddTextfield( -name=>"hfcustom", -width=>75, -height=>20, #-text=> -top=>342, -left=>180, -tabstop=>1, ); # td font face $tdfontdd=$Win1->AddCombobox( -name=>"tdfontdd", -width=>100, -height=>140, -tabstop=>1, -top=>367, -left=>80, -style=> WS_VISIBLE | WS_SCROLL | 3 | WS_TABSTOP ); # create the actual font list $tdfontdd->InsertItem("Arial, Helvetica, sans-serif"); $tdfontdd->InsertItem("Times New Roman, Times, serif"); $tdfontdd->InsertItem("Courier New, Courier, mono"); $tdfontdd->InsertItem("Georgia, Times New Roman, Times, serif"); $tdfontdd->InsertItem("Verdana, Arial, Helvetica, sans-serif"); $tdfontdd->InsertItem("Geneva, Arial, Helvetica, san-serif"); $tdfontdd->InsertItem("custom --->"); $tdfontdd->Select(1); sub tdfontdd_Change{ $tdfontdd->Text($tdfontdd->GetString($tdfontdd->SelectedItem)); } #if the font is a selected one, $tdfontfam is the selected font, #otherwise, you can enter a custom font and the $tdfontfam is the #text you enter in the field to the right # create the custom text field for the bfontfam variable $tdfcustom=$Win1->AddTextfield( -name=>"tdfcustom", -width=>75, -height=>20, #-text=> -top=>367, -left=>180, -tabstop=>1, ); #font face main label $fontheaderlabel=$Win1->AddLabel( -name=>"fontheaderlabel", -width=>75, -height=>20, -text=>"FONT FACE", -top=>220, -left=>80, -tabstop=>0, ); $Win1->fontheaderlabel->Show(); # custom font label $customfontlabel=$Win1->AddLabel( -name=>"customfontlabel", -width=>90, -height=>20, -text=>"CUSTOM FONT", -top=>220, -left=>180, -tabstop=>0, ); $Win1->customfontlabel->Show(); # body font face label $bfontfamlbl=$Win1->AddLabel( -name=>"bfontfamlbl", -width=>70, -height=>20, -text=>"Body Font", -top=>242, -left=>10, -tabstop=>0, ); $Win1->bfontfamlbl->Show(); # link font face label $lfontfamlbl=$Win1->AddLabel( -name=>"lfontfamlbl", -width=>70, -height=>20, -text=>"LINK Font", -top=>267, -left=>10, -tabstop=>0, ); $Win1->lfontfamlbl->Show(); # vlink font face label $vfontfamlbl=$Win1->AddLabel( -name=>"vfontfamlbl", -width=>70, -height=>20, -text=>"VLINK Font", -top=>292, -left=>10, -tabstop=>0, ); $Win1->vfontfamlbl->Show(); #alink font face label $afontfamlbl=$Win1->AddLabel( -name=>"afontfamlbl", -width=>70, -height=>20, -text=>"ALINK Font", -top=>317, -left=>10, -tabstop=>0, ); $Win1->afontfamlbl->Show(); #hlink font face label $hfontfamlbl=$Win1->AddLabel( -name=>"hfontfamlbl", -width=>70, -height=>20, -text=>"HLINK Font", -top=>342, -left=>10, -tabstop=>0, ); $Win1->hfontfamlbl->Show(); # td font face label $tdfontfamlbl=$Win1->AddLabel( -name=>"tdfontfamlbl", -width=>70, -height=>20, -text=>"TD Font", -top=>367, -left=>10, -tabstop=>0, ); $Win1->tdfontfamlbl->Show(); # create the font size text boxes # body font size text box $bfsizetf=$Win1->AddTextfield( -name=>"bfsizetf", -width=>20, -height=>20, #-text=> -top=>242, -left=>300, -tabstop=>1, ); #link font size text box $lfsizetf=$Win1->AddTextfield( -name=>"lfsizetf", -width=>20, -height=>20, #-text=> -top=>267, -left=>300, -tabstop=>1, ); # vlink font size text box $vfsizetf=$Win1->AddTextfield( -name=>"vfsizetf", -width=>20, -height=>20, #-text=> -top=>292, -left=>300, -tabstop=>1, ); # alink font size text box $afsizetf=$Win1->AddTextfield( -name=>"afsizetf", -width=>20, -height=>20, #-text=> -top=>317, -left=>300, -tabstop=>1, ); # hlink font size text box $hfsizetf=$Win1->AddTextfield( -name=>"hfsizetf", -width=>20, -height=>20, #-text=> -top=>342, -left=>300, -tabstop=>1, ); # td font size text box $tdfsizetf=$Win1->AddTextfield( -name=>"tdfsizetf", -width=>20, -height=>20, #-text=> -top=>367, -left=>300, -tabstop=>1, ); # font size label $fsizeheaderlbl=$Win1->AddLabel( -name=>"fsizeheaderlbl", -width=>75, -height=>20, -text=>"FONT SIZE", -top=>220, -left=>280, -tabstop=>0, ); $Win1->fsizeheaderlbl->Show(); # now create the text decoration textfields # these are in a dropdown box that will list the different text decoration # options, with a default of NONE. $bftextdecdd=$Win1->AddCombobox( -name=>"bftextdecdd", -width=>100, -height=>100, -tabstop=>1, -top=>242, -left=>370, -style=> WS_VISIBLE | WS_SCROLL | 3 | WS_TABSTOP ); $bftextdecdd->InsertItem("none"); $bftextdecdd->InsertItem("blink"); $bftextdecdd->InsertItem("line-through"); $bftextdecdd->InsertItem("underline"); $bftextdecdd->InsertItem("overline"); $bftextdecdd->Select(0); sub bftextdecdd_Change{ $bftextdecdd->Text($bftextdecdd->GetString($bftextdecdd->SelectedItem)); } #link font decoration $lftextdecdd=$Win1->AddCombobox( -name=>"lftextdecdd", -width=>100, -height=>100, -tabstop=>1, -top=>267, -left=>370, -style=> WS_VISIBLE | WS_SCROLL | 3 | WS_TABSTOP ); $lftextdecdd->InsertItem("none"); $lftextdecdd->InsertItem("blink"); $lftextdecdd->InsertItem("line-through"); $lftextdecdd->InsertItem("underline"); $lftextdecdd->InsertItem("overline"); $lftextdecdd->Select(0); sub lftextdecdd_Change{ $lftextdecdd->Text($lftextdecdd->GetString($lftextdecdd->SelectedItem)); } #vlink font decoration $vftextdecdd=$Win1->AddCombobox( -name=>"vftextdecdd", -width=>100, -height=>100, -tabstop=>1, -top=>292, -left=>370, -style=> WS_VISIBLE | WS_SCROLL | 3 | WS_TABSTOP ); $vftextdecdd->InsertItem("none"); $vftextdecdd->InsertItem("blink"); $vftextdecdd->InsertItem("line-through"); $vftextdecdd->InsertItem("underline"); $vftextdecdd->InsertItem("overline"); $vftextdecdd->Select(0); sub vftextdecdd_Change{ $vftextdecdd->Text($vftextdecdd->GetString($vftextdecdd->SelectedItem)); } #alink text decoration $aftextdecdd=$Win1->AddCombobox( -name=>"aftextdecdd", -width=>100, -height=>100, -tabstop=>1, -top=>317, -left=>370, -style=> WS_VISIBLE | WS_SCROLL | 3 | WS_TABSTOP ); $aftextdecdd->InsertItem("none"); $aftextdecdd->InsertItem("blink"); $aftextdecdd->InsertItem("line-through"); $aftextdecdd->InsertItem("underline"); $aftextdecdd->InsertItem("overline"); $aftextdecdd->Select(0); sub aftextdecdd_Change{ $aftextdecdd->Text($aftextdecdd->GetString($aftextdecdd->SelectedItem)); } #hlink text decoration $hftextdecdd=$Win1->AddCombobox( -name=>"hftextdecdd", -width=>100, -height=>100, -tabstop=>1, -top=>342, -left=>370, -style=> WS_VISIBLE | WS_SCROLL | 3 |WS_TABSTOP ); $hftextdecdd->InsertItem("none"); $hftextdecdd->InsertItem("blink"); $hftextdecdd->InsertItem("line-through"); $hftextdecdd->InsertItem("underline"); $hftextdecdd->InsertItem("overline"); $hftextdecdd->Select(0); sub hftextdecdd_Change{ $hftextdecdd->Text($hftextdecdd->GetString($hftextdecdd->SelectedItem)); } #td text decoration $tdftextdecdd=$Win1->AddCombobox( -name=>"tdftextdecdd", -width=>100, -height=>100, -tabstop=>1, -top=>367, -left=>370, -style=> WS_VISIBLE | WS_SCROLL | 3 | WS_TABSTOP ); $tdftextdecdd->InsertItem("none"); $tdftextdecdd->InsertItem("blink"); $tdftextdecdd->InsertItem("line-through"); $tdftextdecdd->InsertItem("underline"); $tdftextdecdd->InsertItem("overline"); $tdftextdecdd->Select(0); sub tdftextdecdd_Change{ $tdftextdecdd->Text($tdftextdecdd->GetString($tdftextdecdd->SelectedItem)); } # text decoration header label $textdecheaderlbl=$Win1->AddLabel( -name=>"textdecheaderlbl", -width=>120, -height=>20, -text=>"TEXT DECORATION", -top=>220, -left=>370, -tabstop=>0, ); $Win1->textdecheaderlbl->Show(); # create margin settings text boxes #top margin text box $topmargintf=$Win1->AddTextfield( -name=>"topmargintf", -width=>20, -height=>20, #-text=> -top=>242, -left=>520, -tabstop=>1, ); #left margin text box $leftmargintf=$Win1->AddTextfield( -name=>"leftmargintf", -width=>20, -height=>20, #-text=> -top=>267, -left=>520, -tabstop=>1, ); # margin width text box $marginwidthtf=$Win1->AddTextfield( -name=>"marginwidthtf", -width=>20, -height=>20, #-text=> -top=>292, -left=>520, -tabstop=>1, ); # margin height text box $marginheighttf=$Win1->AddTextfield( -name=>"marginheighttf", -width=>20, -height=>20, #-text=> -top=>317, -left=>520, -tabstop=>1, ); # margins header label $marginheaderlbl=$Win1->AddLabel( -name=>"marginheaderlbl", -width=>75, -height=>20, -text=>"MARGINS", -top=>220, -left=>510, -tabstop=>0, ); $Win1->marginheaderlbl->Show(); # margin top label $margintoplbl=$Win1->AddLabel( -name=>"margintoplbl", -width=>50, -height=>20, -text=>"TOP", -top=>245, -left=>550, -tabstop=>0, ); $Win1->margintoplbl->Show(); # margin left label $marginleftlbl=$Win1->AddLabel( -name=>"marginleftlbl", -width=>50, -height=>20, -text=>"LEFT", -top=>269, -left=>550, -tabstop=>0, ); $Win1->marginleftlbl->Show(); # margin width label $marginwidthlbl=$Win1->AddLabel( -name=>"marginwidthlbl", -width=>50, -height=>20, -text=>"WIDTH", -top=>294, -left=>550, -tabstop=>0, ); $Win1->marginwidthlbl->Show(); #margin height label $marginheightlbl=$Win1->AddLabel( -name=>"marginheightlbl", -width=>50, -height=>20, -text=>"HEIGHT", -top=>320, -left=>550, -tabstop=>0, ); $Win1->marginheightlbl->Show(); # here is where you name the css file for save.... $filename=$Win1->AddTextfield( -name=>"filename", -width=>150, -height=>20, -text=>"YOURSTYLESHEET.css", -top=>425, -left=>100, -tabstop=>1, ); # this button will generate the file $generatebutton=$Win1->AddButton( -name=>"generatebutton", -width=>75, -height=>25, -top=>422, -left=>10, -text=>"Generate CSS", -tabstop=>1, ); $Win1->generatebutton->Show(); # time to put our hard work to good use. This is the generation of the css file. sub generatebutton_Click{ $css=$filename->Text; # get the filename from user input $bgcolor=$bgcolortf->Text; $bfontcolor=$bfcolortf->Text; $lcolor=$lfontcolortf->Text; $vlcolor=$vfontcolortf->Text; $alcolor=$afontcolortf->Text; $hcolor=$hcolortf->Text; $tdcolor=$tdcolortf->Text; if ($bfontdd->Text eq "custom --->"){ $fontfam=$bfcustom->Text; }else{ $fontfam=$bfontdd->Text; } if ($lfontdd->Text eq "custom --->"){ $lfontfam=$lfcustom->Text; }else{ $lfontfam=$lfontdd->Text; } if ($vfontdd->Text eq "custom --->"){ $vlfontfam=$vfcustom->Text; }else{ $vlfontfam=$vfontdd->Text; } if ($afontdd->Text eq "custom --->"){ $alfontfam=$afcustom->Text; }else{ $alfontfam=$afontdd->Text; } if ($hfontdd->Text eq "custom --->"){ $hfontfam=$hfcustom->Text; }else{ $hfontfam=$hfontdd->Text; } if ($tdfontdd->Text eq "custom --->"){ $tdfontfam=$tdfcustom->Text; }else{ $tdfontfam=$tdfontdd->Text; } $fontsize=$bfsizetf->Text; $lfontsize=$lfsizetf->Text; $vlfontsize=$vfsizetf->Text; $alfontsize=$afsizetf->Text; $hfontsize=$hfsizetf->Text; $tdfontsize=$tdfsizetf->Text; $bfonttextdec=$bftextdecdd->GetString($bftextdecdd->SelectedItem); $ltextdec=$lftextdecdd->GetString($lftextdecdd->SelectedItem); $vltextdec=$vftextdecdd->GetString($vftextdecdd->SelectedItem); $altextdec=$aftextdecdd->GetString($aftextdecdd->SelectedItem); $htextdec=$hftextdecdd->GetString($hftextdecdd->SelectedItem); $tdtextdec=$tdftextdecdd->GetString($tdftextdecdd->SelectedItem); $topmargin=$topmargintf->Text; $leftmargin=$leftmargintf->Text; $marginwidth=$marginwidthtf->Text; $marginheight=$marginheighttf->Text; open (OUT, ">$css") or die "Cannot open $css for write :$!"; # style tag print OUT " \n"; print OUT " \n"; close $css; system("notepad.exe $css"); } Win32::GUI::Dialog(); sub Win1_Terminate{ -1; }
__label__pos
0.770393
How do I turn a .java into an .exe? Discussion in 'OT Technology' started by machine, Mar 26, 2004. 1. machine machine Welcome to the Machine OT Supporter Joined: Oct 23, 2003 Messages: 8,982 Likes Received: 0 Location: DSotM I'm in intro programming and just made a programm in java. Is there any way I can *easily* turn this into an executable which will work on I guess most computers? If there is, please explain how. Thanks :big grin:   2. Ximian Ximian New Member Joined: Mar 20, 2004 Messages: 1,860 Likes Received: 0 Location: DCA 3. CyberBullets CyberBullets I reach to the sky, and call out your name. If I c Joined: Nov 13, 2001 Messages: 11,861 Likes Received: 0 Location: BC, Canada/Stockholm, Sweden yes compile it to a class file and install the jre. boom ur done   4. carlin carlin Guest ebunny... couple of things you can do ... 1. if you are using JBuilder, there is option to do that already... 2. you a 3rd party app like jexepack to pack the class file(s) into exe's -- try it before you buy it... 3. and my fav -- cheap man's exe ... a batch file. CyberBullets... if you are able to complie, then you are already have the SDK (which includes jre). How does that make a class into an exe? I am missing something? :confused:   5. carlin carlin Guest 6. CyberBullets CyberBullets I reach to the sky, and call out your name. If I c Joined: Nov 13, 2001 Messages: 11,861 Likes Received: 0 Location: BC, Canada/Stockholm, Sweden no if he wants to distribute it around he can move the class file with the jre from one computer to anohter   7. machine machine Welcome to the Machine OT Supporter Joined: Oct 23, 2003 Messages: 8,982 Likes Received: 0 Location: DSotM uhmm i'm using Textpad right now ?? I have two files right now, one class with the main in it, and another .class that it implements. i don't have any "jar"s or whatever they are. right now when I want to run my program, i hit compile in textpad. :big grin:   8. machine machine Welcome to the Machine OT Supporter Joined: Oct 23, 2003 Messages: 8,982 Likes Received: 0 Location: DSotM oh and carlin...i need to pay to see the answer to that link??   9. aphoric aphoric Even if god did exist, it would be necessary to ab Joined: Aug 29, 2003 Messages: 918 Likes Received: 0 Location: Leaving Afghanistan 10. crotchfruit crotchfruit Guest scroll to the bottom of the page. they insert ads between the question and answers. i read the thread and it's not very useful anyways.   11. carlin carlin Guest Share This Page
__label__pos
0.904161
No available translations found Limetorrents Proxy India: Unveiling the Power of Proxy Servers Choose Your Proxy Package In today’s digital age, where online privacy and unrestricted access to information are paramount, proxy servers have emerged as essential tools for internet users worldwide. One such proxy server that commands attention is the Limetorrents proxy India. In this article, we will delve deep into the world of Limetorrents proxy India, exploring its key concepts, internal structure, benefits, challenges, and even comparing it with other similar terms. Additionally, we’ll discover how a reliable proxy server provider like FineProxy.de can be your trusted partner in harnessing the power of Limetorrents proxy India. Brief Information about Limetorrents Proxy India Limetorrents is a renowned torrent website that offers a vast library of digital content, including movies, music, games, and more. However, due to various legal and accessibility constraints, many users find themselves unable to access Limetorrents directly. This is where Limetorrents proxy India comes into play. Detailed Information about Limetorrents Proxy India Limetorrents proxy India is essentially an intermediary server that acts as a bridge between your device and the Limetorrents website. It allows you to bypass geo-restrictions and access Limetorrents from India or any other region where it might be blocked. Here’s how it works: The Internal Structure of Limetorrents Proxy India Limetorrents Proxy Structure 1. Client Request: You initiate a request to access Limetorrents through the proxy server. 2. Proxy Server: The proxy server, hosted in a different location (often abroad), receives your request. 3. Website Access: The proxy server fetches the Limetorrents website on your behalf. 4. Data Relay: It then relays the website data back to your device, making it appear as if you are accessing Limetorrents directly. 5. Unrestricted Access: Voilà! You can now browse Limetorrents as if you were in the location of the proxy server. Benefits of Limetorrents Proxy India • Access Anywhere: You can access Limetorrents from India or any other region where it’s blocked. • Anonymity: Your IP address remains hidden, enhancing online privacy. • Speed: Proxy servers can sometimes offer faster download speeds due to their caching mechanisms. • Security: Protection from cyber threats, as the proxy server acts as a buffer between your device and potentially harmful websites. Problems That Occur When Using Limetorrents Proxy India While Limetorrents proxy India offers numerous benefits, it’s essential to be aware of potential challenges: • Speed Variability: Proxy servers can sometimes slow down your internet speed, depending on server load. • Unreliable Servers: Not all proxy servers are trustworthy; some may compromise your data or privacy. • Blocked Proxies: Authorities may block known proxy servers, requiring you to find new ones. Comparison of Limetorrents Proxy India with Other Similar Terms Let’s compare Limetorrents proxy India with other related concepts: Aspect Limetorrents Proxy India VPN Tor Network Anonymity Moderate High Very High Speed Variable High Slow Ease of Use Easy Moderate Complex Security Basic High Very High Legal Implications Grey Area Legal Legal How Can FineProxy.de Help with Limetorrents Proxy India? FineProxy.de is a trusted provider of proxy server solutions, including those tailored for accessing Limetorrents proxy India. Here’s how FineProxy.de can assist you: • Reliable Servers: FineProxy.de offers a network of secure and reliable proxy servers, ensuring consistent access to Limetorrents. • Global Reach: With servers in various locations, FineProxy.de can help you bypass geo-restrictions from anywhere in the world. • Support and Maintenance: Their expert support team ensures that you have a smooth and trouble-free experience. In conclusion, Limetorrents proxy India is a valuable tool for gaining unrestricted access to the Limetorrents website, even in regions where it’s blocked. While it offers advantages like anonymity and security, users should be mindful of potential speed variations and the trustworthiness of proxy servers. FineProxy.de stands as a reliable partner in harnessing the power of Limetorrents proxy India, ensuring seamless and secure access to the content you desire. Frequently Asked Questions About Limetorrents proxy India Limetorrents Proxy India is a proxy server that enables users to access the Limetorrents website from India or regions where it’s blocked. It acts as an intermediary, bypassing geo-restrictions. Limetorrents Proxy India works by receiving your request, fetching the Limetorrents website, and relaying the data back to your device. It makes your access appear as if you’re in the server’s location. Benefits include accessing Limetorrents from blocked regions, enhanced online privacy, potential speed improvements, and added security against cyber threats. Challenges may include variable internet speed, reliability of proxy servers, and the possibility of proxy server blocks by authorities. Limetorrents Proxy India offers moderate anonymity and basic security compared to VPNs and the Tor network. VPNs excel in security and speed, while the Tor network provides the highest level of anonymity. FineProxy.de provides secure and reliable proxy servers for accessing Limetorrents. With a global server network and expert support, they ensure consistent and trouble-free access to Limetorrents Proxy India.
__label__pos
0.688587
Uploaded image for project: 'Minecraft: Java Edition' 1. Minecraft: Java Edition 2. MC-128079 Statistic for using shears doesn't increase when mining certain blocks XMLWordPrintable Details • Type: Bug • Status: Open • Resolution: Unresolved • Affects Version/s: Minecraft 18w14b, Minecraft 18w15a, Minecraft 18w16a, Minecraft 18w20c, Minecraft 18w21a, Minecraft 18w22c, Minecraft 1.13-pre1, Minecraft 1.13, Minecraft 18w30b, Minecraft 18w31a, Minecraft 18w32a, Minecraft 18w33a, Minecraft 1.13.1-pre1, Minecraft 1.13.1-pre2, Minecraft 1.13.1, Minecraft 1.13.2, Minecraft 18w43b, Minecraft 18w43c, Minecraft 18w44a, Minecraft 18w45a, Minecraft 18w48a, Minecraft 18w48b, Minecraft 18w49a, Minecraft 18w50a, Minecraft 19w12b, Minecraft 19w13b, Minecraft 19w14a, Minecraft 1.14 Pre-Release 2, Minecraft 1.14 Pre-Release 3, Minecraft 1.14 Pre-Release 4, Minecraft 1.14 Pre-Release 5, Minecraft 1.14, Minecraft 1.14.1, Minecraft 1.14.2 Pre-Release 2, Minecraft 1.14.2 Pre-Release 3, Minecraft 1.14.2, Minecraft 1.14.3 Pre-Release 1, Minecraft 1.14.3 Pre-Release 3, Minecraft 1.14.3, Minecraft 1.14.4 Pre-Release 3, Minecraft 1.14.4 Pre-Release 4, Minecraft 1.14.4 Pre-Release 5, Minecraft 1.14.4 Pre-Release 6, 1.14.4, 1.15.2, 20w18a, 1.16.4, 20w48a, 1.16.5, 21w05b, 21w06a, 21w14a, 21w18a, 21w20a • Fix Version/s: None • Confirmation Status: Confirmed • Game Mode: Survival • Category: (Unassigned) Description Add a scoreboard with shears being used as the criteria: /scoreboard objectives add shear minecraft.used:minecraft.shears Display it in the sidebar: /scoreboard objectives setdisplay sidebar shear This scoreboard objective doesn't increase when mining carpet with shears and the other mentioned blocks. If you use the criteria "minecraft.used:minecraft.diamond_pickaxe" and use said diamond pickaxe to mine carpet the score for the pickaxe increases, so why wouldn't it with shears? Another Argument on why this is a bug is that the durability decreases in both cases, so the tools are clearly being used! I think it might be good to have a list of blocks where it does not work. For the reason that you need to have the block mined with shears to actually collect an item, but where the criteria does not tick up. • tall_grass • large_fern • seagrass • tall_seagrass • nether_sprouts Attachments Activity People Assignee: Unassigned Unassigned Reporter: Elemend Elemend Votes: 12 Vote for this issue Watchers: 3 Start watching this issue Dates Created: Updated: CHK:
__label__pos
0.527774
3 \$\begingroup\$ I have a particle system with a physics simulation integrator based on delta time (elapsed time between frames) which is implemented on the GPU in a compute shader. I also have a frustum culling system implemented on the GPU. The frustum culling gives me the possibility to cull away draw calls and the dispatch calls for the particle simulation. The culling of draw calls works well, I also don't have a problem with culling the particle simulation when the camera is looking away. My problem happens when I want to catch up the particle system simulation when the camera looks back at the particle system after looking away for a while. What I do is accumulate the time passed while looking away, then I resume the simulation using all that accumulated time. The problem with this approach is that if the simulation is anything but a simple constant velocity change in one direction, the simulation just doesn't look the same as if the simulation was playing one frame delta at a time. From what I have read this is a common issue with using time elapsed between frames to simulate physics. What I wonder is if there's a different approach that can actually allow me to correctly play back many seconds of simulation (let's say 20 seconds) the same as if it was played one frame delta at a time? \$\endgroup\$ 2 • 1 \$\begingroup\$ That depends on what exactly you are simulating. For example, when you have a particle system where particles attract particles, then extrapolating that systems state is an np-complete problem which can not be solved in any way except a step-by-step simulation. \$\endgroup\$ – Philipp Dec 10 '20 at 9:01 • 1 \$\begingroup\$ As Philipp says, there's no one-size-fits-all solution here. But there are solutions to many special cases. To get good answers specific to a case of interest for your game, we'll need more details from you about what one, specific effect you want help fast-forwarding in this way. If the answers you get for that effect don't work for the next, different simulation effect you want to fast-forward, then you can ask a new question about that effect next. \$\endgroup\$ – DMGregory Dec 10 '20 at 12:32 1 \$\begingroup\$ Look up how Unity‘s FixedUpdate solves this: it’s a commonly used mechanism you might take inspiration from. FixedUpdate is called a fixed number of times per second; you decide how many by setting the fixedDeltaTime value in settings, which by default is 0.02s. Unity will always run this 50 times per second. Doing so any calculations inside the FixedUpdate should be accurate. This is necessary because whatever real-time system you’re developing, you must account for occasional frame drops and your physic simulations must not depend on time deltas. It’s not too hard to implement the same mechanism in your own system. You can even do it in a separate thread. Side note: FixedUpdate, as it runs many times in one frame, can easily become heavy so it’s good to make a minimal use of it. \$\endgroup\$ 4 • \$\begingroup\$ Where does the question mention Unity? \$\endgroup\$ – Philipp Dec 10 '20 at 8:58 • \$\begingroup\$ @Philipp is it not allowed to mention a software as an example now? \$\endgroup\$ Dec 10 '20 at 9:04 • \$\begingroup\$ If I've been looking away from the particle system for 3 seconds, then look back, this would entail stepping that system's simulation ~150 times in one frame, no? Do you have any recommendations for how to mitigate this kind of sudden cost spike? \$\endgroup\$ – DMGregory Dec 10 '20 at 13:20 • \$\begingroup\$ being aware of the cost spike is the first step. There’s no method other than doing the absolute essential minimum for physics when you prioritise precision over resource efficiency. That said you can adjust the fixed delta time and find a balance between the two. Example: at 0.1 FixedUpdate would run 10 times/s; decide that value based on how precise you need to be. BUT... as @Philipp commented, particle systems can be a big issue due to the nature of the problem. For a simple particle system without any internal interactions this approach will work. \$\endgroup\$ Dec 10 '20 at 14:13 Your Answer By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.692273
.\" $NetBSD: stat.1,v 1.28 2010/04/05 21:25:01 joerg Exp $ .\" .\" Copyright (c) 2002 The NetBSD Foundation, Inc. .\" All rights reserved. .\" .\" This code is derived from software contributed to The NetBSD Foundation .\" by Andrew Brown and Jan Schaumann. .\" .\" 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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. .\" .\" $FreeBSD$ .\" .Dd April 22, 2012 .Dt STAT 1 .Os .Sh NAME .Nm stat , .Nm readlink .Nd display file status .Sh SYNOPSIS .Nm .Op Fl FLnq .Op Fl f Ar format | Fl l | r | s | x .Op Fl t Ar timefmt .Op Ar .Nm readlink .Op Fl fn .Op Ar .Sh DESCRIPTION The .Nm utility displays information about the file pointed to by .Ar file . Read, write, or execute permissions of the named file are not required, but all directories listed in the pathname leading to the file must be searchable. If no argument is given, .Nm displays information about the file descriptor for standard input. .Pp When invoked as .Nm readlink , only the target of the symbolic link is printed. If the given argument is not a symbolic link and the .Fl f option is not specified, .Nm readlink will print nothing and exit with an error. If the .Fl f option is specified, the output is canonicalized by following every symlink in every component of the given path recursively. .Nm readlink will resolve both absolute and relative paths, and return the absolute pathname corresponding to .Ar file . In this case, the argument does not need to be a symbolic link. .Pp The information displayed is obtained by calling .Xr lstat 2 with the given argument and evaluating the returned structure. The default format displays the .Fa st_dev , .Fa st_ino , .Fa st_mode , .Fa st_nlink , .Fa st_uid , .Fa st_gid , .Fa st_rdev , .Fa st_size , .Fa st_atime , .Fa st_mtime , .Fa st_ctime , .Fa st_birthtime , .Fa st_blksize , .Fa st_blocks , and .Fa st_flags fields, in that order. .Pp The options are as follows: .Bl -tag -width indent .It Fl F As in .Xr ls 1 , display a slash .Pq Ql / immediately after each pathname that is a directory, an asterisk .Pq Ql * after each that is executable, an at sign .Pq Ql @ after each symbolic link, a percent sign .Pq Ql % after each whiteout, an equal sign .Pq Ql = after each socket, and a vertical bar .Pq Ql | after each that is a FIFO. The use of .Fl F implies .Fl l . .It Fl L Use .Xr stat 2 instead of .Xr lstat 2 . The information reported by .Nm will refer to the target of .Ar file , if file is a symbolic link, and not to .Ar file itself. If the link is broken or the target does not exist, fall back on .Xr lstat 2 and report information about the link. .It Fl n Do not force a newline to appear at the end of each piece of output. .It Fl q Suppress failure messages if calls to .Xr stat 2 or .Xr lstat 2 fail. When run as .Nm readlink , error messages are automatically suppressed. .It Fl f Ar format Display information using the specified format. See the .Sx Formats section for a description of valid formats. .It Fl l Display output in .Nm ls Fl lT format. .It Fl r Display raw information. That is, for all the fields in the .Vt stat structure, display the raw, numerical value (for example, times in seconds since the epoch, etc.). .It Fl s Display information in .Dq shell output format, suitable for initializing variables. .It Fl x Display information in a more verbose way as known from some .Tn Linux distributions. .It Fl t Ar timefmt Display timestamps using the specified format. This format is passed directly to .Xr strftime 3 . .El .Ss Formats Format strings are similar to .Xr printf 3 formats in that they start with .Cm % , are then followed by a sequence of formatting characters, and end in a character that selects the field of the .Vt "struct stat" which is to be formatted. If the .Cm % is immediately followed by one of .Cm n , t , % , or .Cm @ , then a newline character, a tab character, a percent character, or the current file number is printed, otherwise the string is examined for the following: .Pp Any of the following optional flags: .Bl -tag -width indent .It Cm # Selects an alternate output form for octal and hexadecimal output. Non-zero octal output will have a leading zero, and non-zero hexadecimal output will have .Dq Li 0x prepended to it. .It Cm + Asserts that a sign indicating whether a number is positive or negative should always be printed. Non-negative numbers are not usually printed with a sign. .It Cm - Aligns string output to the left of the field, instead of to the right. .It Cm 0 Sets the fill character for left padding to the .Ql 0 character, instead of a space. .It space Reserves a space at the front of non-negative signed output fields. A .Sq Cm + overrides a space if both are used. .El .Pp Then the following fields: .Bl -tag -width indent .It Ar size An optional decimal digit string specifying the minimum field width. .It Ar prec An optional precision composed of a decimal point .Sq Cm \&. and a decimal digit string that indicates the maximum string length, the number of digits to appear after the decimal point in floating point output, or the minimum number of digits to appear in numeric output. .It Ar fmt An optional output format specifier which is one of .Cm D , O , U , X , F , or .Cm S . These represent signed decimal output, octal output, unsigned decimal output, hexadecimal output, floating point output, and string output, respectively. Some output formats do not apply to all fields. Floating point output only applies to .Vt timespec fields (the .Cm a , m , and .Cm c fields). .Pp The special output specifier .Cm S may be used to indicate that the output, if applicable, should be in string format. May be used in combination with: .Bl -tag -width indent .It Cm amc Display date in .Xr strftime 3 format. .It Cm dr Display actual device name. .It Cm f Display the flags of .Ar file as in .Nm ls Fl lTdo . .It Cm gu Display group or user name. .It Cm p Display the mode of .Ar file as in .Nm ls Fl lTd . .It Cm N Displays the name of .Ar file . .It Cm T Displays the type of .Ar file . .It Cm Y Insert a .Dq Li " -\*[Gt] " into the output. Note that the default output format for .Cm Y is a string, but if specified explicitly, these four characters are prepended. .El .It Ar sub An optional sub field specifier (high, middle, low). Only applies to the .Cm p , d , r , and .Cm T output formats. It can be one of the following: .Bl -tag -width indent .It Cm H .Dq High \[em] specifies the major number for devices from .Cm r or .Cm d , the .Dq user bits for permissions from the string form of .Cm p , the file .Dq type bits from the numeric forms of .Cm p , and the long output form of .Cm T . .It Cm L .Dq Low \[em] specifies the minor number for devices from .Cm r or .Cm d , the .Dq other bits for permissions from the string form of .Cm p , the .Dq user , .Dq group , and .Dq other bits from the numeric forms of .Cm p , and the .Nm ls Fl F style output character for file type when used with .Cm T (the use of .Cm L for this is optional). .It Cm M .Dq Middle \[em] specifies the .Dq group bits for permissions from the string output form of .Cm p , or the .Dq suid , .Dq sgid , and .Dq sticky bits for the numeric forms of .Cm p . .El .It Ar datum A required field specifier, being one of the following: .Bl -tag -width indent .It Cm d Device upon which .Ar file resides .Pq Fa st_dev . .It Cm i .Ar file Ns 's inode number .Pq Fa st_ino . .It Cm p File type and permissions .Pq Fa st_mode . .It Cm l Number of hard links to .Ar file .Pq Fa st_nlink . .It Cm u , g User ID and group ID of .Ar file Ns 's owner .Pq Fa st_uid , st_gid . .It Cm r Device number for character and block device special files .Pq Fa st_rdev . .It Cm a , m , c , B The time .Ar file was last accessed or modified, or when the inode was last changed, or the birth time of the inode .Pq Fa st_atime , st_mtime , st_ctime , st_birthtime . .It Cm z The size of .Ar file in bytes .Pq Fa st_size . .It Cm b Number of blocks allocated for .Ar file .Pq Fa st_blocks . .It Cm k Optimal file system I/O operation block size .Pq Fa st_blksize . .It Cm f User defined flags for .Ar file . .It Cm v Inode generation number .Pq Fa st_gen . .El .Pp The following five field specifiers are not drawn directly from the data in .Vt "struct stat" , but are: .Bl -tag -width indent .It Cm N The name of the file. .It Cm R The absolute pathname corresponding to the file. .It Cm T The file type, either as in .Nm ls Fl F or in a more descriptive form if the .Ar sub field specifier .Cm H is given. .It Cm Y The target of a symbolic link. .It Cm Z Expands to .Dq major,minor from the .Va rdev field for character or block special devices and gives size output for all others. .El .El .Pp Only the .Cm % and the field specifier are required. Most field specifiers default to .Cm U as an output form, with the exception of .Cm p which defaults to .Cm O ; .Cm a , m , and .Cm c which default to .Cm D ; and .Cm Y , T , and .Cm N which default to .Cm S . .Sh EXIT STATUS .Ex -std stat readlink .Sh EXAMPLES If no options are specified, the default format is "%d %i %Sp %l %Su %Sg %r %z \e"%Sa\e" \e"%Sm\e" \e"%Sc\e" \e"%SB\e" %k %b %#Xf %N". .Bd -literal -offset indent \*[Gt] stat /tmp/bar 0 78852 -rw-r--r-- 1 root wheel 0 0 "Jul 8 10:26:03 2004" "Jul 8 10:26:03 2004" "Jul 8 10:28:13 2004" "Jan 1 09:00:00 1970" 16384 0 0 /tmp/bar .Ed .Pp Given a symbolic link .Dq foo that points from .Pa /tmp/foo to .Pa / , you would use .Nm as follows: .Bd -literal -offset indent \*[Gt] stat -F /tmp/foo lrwxrwxrwx 1 jschauma cs 1 Apr 24 16:37:28 2002 /tmp/foo@ -\*[Gt] / \*[Gt] stat -LF /tmp/foo drwxr-xr-x 16 root wheel 512 Apr 19 10:57:54 2002 /tmp/foo/ .Ed .Pp To initialize some shell variables, you could use the .Fl s flag as follows: .Bd -literal -offset indent \*[Gt] csh % eval set `stat -s .cshrc` % echo $st_size $st_mtimespec 1148 1015432481 \*[Gt] sh $ eval $(stat -s .profile) $ echo $st_size $st_mtimespec 1148 1015432481 .Ed .Pp In order to get a list of file types including files pointed to if the file is a symbolic link, you could use the following format: .Bd -literal -offset indent $ stat -f "%N: %HT%SY" /tmp/* /tmp/bar: Symbolic Link -\*[Gt] /tmp/foo /tmp/output25568: Regular File /tmp/blah: Directory /tmp/foo: Symbolic Link -\*[Gt] / .Ed .Pp In order to get a list of the devices, their types and the major and minor device numbers, formatted with tabs and linebreaks, you could use the following format: .Bd -literal -offset indent stat -f "Name: %N%n%tType: %HT%n%tMajor: %Hr%n%tMinor: %Lr%n%n" /dev/* [...] Name: /dev/wt8 Type: Block Device Major: 3 Minor: 8 Name: /dev/zero Type: Character Device Major: 2 Minor: 12 .Ed .Pp In order to determine the permissions set on a file separately, you could use the following format: .Bd -literal -offset indent \*[Gt] stat -f "%Sp -\*[Gt] owner=%SHp group=%SMp other=%SLp" . drwxr-xr-x -\*[Gt] owner=rwx group=r-x other=r-x .Ed .Pp In order to determine the three files that have been modified most recently, you could use the following format: .Bd -literal -offset indent \*[Gt] stat -f "%m%t%Sm %N" /tmp/* | sort -rn | head -3 | cut -f2- Apr 25 11:47:00 2002 /tmp/blah Apr 25 10:36:34 2002 /tmp/bar Apr 24 16:47:35 2002 /tmp/foo .Ed .Pp To display a file's modification time: .Bd -literal -offset indent \*[Gt] stat -f %m /tmp/foo 1177697733 .Ed .Pp To display the same modification time in a readable format: .Bd -literal -offset indent \*[Gt] stat -f %Sm /tmp/foo Apr 27 11:15:33 2007 .Ed .Pp To display the same modification time in a readable and sortable format: .Bd -literal -offset indent \*[Gt] stat -f %Sm -t %Y%m%d%H%M%S /tmp/foo 20070427111533 .Ed .Pp To display the same in UTC: .Bd -literal -offset indent \*[Gt] sh $ TZ= stat -f %Sm -t %Y%m%d%H%M%S /tmp/foo 20070427181533 .Ed .Sh SEE ALSO .Xr file 1 , .Xr ls 1 , .Xr lstat 2 , .Xr readlink 2 , .Xr stat 2 , .Xr printf 3 , .Xr strftime 3 .Sh HISTORY The .Nm utility appeared in .Nx 1.6 and .Fx 4.10 . .Sh AUTHORS .An -nosplit The .Nm utility was written by .An Andrew Brown .Aq [email protected] . This man page was written by .An Jan Schaumann .Aq [email protected] .
__label__pos
0.500391
CODEONWORT 다항식 전개하기(Polynomial Expansion) 본문 Season 1/Problem solving 다항식 전개하기(Polynomial Expansion) codeonwort 2014.08.23 12:58 $$z ← z^2 + c$$ I want its expanded form after several iterations. Let's say it's 3 times. $$ \begin{aligned} z_1 = z_0^2 + c \\ z_2 = z_1^2 + c = (z_0^2 + c)^2 + c \\ z_3 = z_2^2 + c = ((z_0^2 + c)^2 + c)^2 + c \end{aligned} $$ There are so many brackets and multiplications. I don't want to expand it by hand, so let's make a program to do it. First consideration is how to represent the expression in the code. Simple SOP(Sum Of Product) came to mind. We are dealing with polynomials, so let's regard a polynomial as sum of monomials. $$p = a_0x^0 + a_1x^1 + a_2x^2 + ...$$ Here, each monomial is composed of a coefficient, a letter(strictly, an unknown), and an exponent. Object declaration of them is straightforward then(In this article, I will use javascript for demonstration): function Monomial(coeff, letter, exponent) {     this.coeff = coeff     this.letter = letter     this.exponent = exponent } function Polynomial(monomials) {     this.monomials = monomials || [] } We need methods for addition and multiplication. Let's consider addition of two monomials. $$ax^2 + bx^2 = (a+b)x^2 \\ ax^2 + bx^4 =  ax^2 + bx^4$$ There are two cases: 1. Both letters and exponents same, result in single monomial. 2. Otherwise, we just make a polynomial containing those two. It's easy to write a code for it. Monomial.prototype.add = function(x) {   if(this.letter == x.letter && this.exponent == x.exponent){     return new Monomial(this.coefficient + x.coefficient, this.letter, this.exponent)   }   return new Polynomial([this, x]) } Now consider multiplication of two monomials: $$ ax^2 \times bx^3 = abx^{2+3} = abx^5 \\ ax \times by^2 = abxy^2 $$ Wait. we have a problem. Currently a monomial stores only one letter. It cannot hold ($ abxy^2 $) which contains two letters(accordingly, two exponents). A monomial has to store an 'array of letters' and an 'array of exponents.' function Monomial(coeff, letters, exponents) {     this.coeff = coeff     this.letters = letters // Array of String     this.exponents = exponents // Array of Number } function Polynomial(monomials) {     this.monomials = monomials || [] } Go back to addition. $$axy^2 + bx^2y = axy^2 + bx^2y \\ axy + bxy = (a+b)xy$$ Now, the condition that the result to be a monomial is, all letters and exponents are same. Monomial.prototype.mergeable = function(x) {     var L = this.letters.join("") == x.letters.join("")     var D = this.exponents.join("") == x.exponents.join("")     return L && D } Monomial.prototype.add = function(x) {       if(this.mergeable(x)){         return new Monomial(this.coeff+x.coeff, this.letters, this.exponents)     }     return new Polynomial([this, x]) } What, comparison using join()? unnecessary creation of strings and no consideration of letter ordering. It will crashes for ($ 2(zz)^3(z)^5 + 3(z)^7(zz)^2 $) or ($ xy^2 + 2y^2x  $). Oh, I just want the expansion of ($ z ← z^2 + c $). Screw them. Return to multiplication, when you multiply two monomials, if letters are same, add their exponents. If not, just combine them. $$ \begin{aligned} ax^2y^3z \\ \times bx^4 ~~~~ z^7 \\abx^{2+4}y^3z^{1+7} \end{aligned} $$ Monomial.prototype.multiply = function(x) {     var letterMap = {}     var letters = [], degrees = []     for(var i=0; i<this.letters.length; i++){         if(letterMap[this.letters[i]] == null){             letterMap[this.letters[i]] = this.degrees[i]         }else{             letterMap[this.letters[i]] += this.degrees[i]         }     }     for(i=0; i<x.letters.length; i++){         if(letterMap[x.letters[i]] == null){             letterMap[x.letters[i]] = x.degrees[i]         }else{             letterMap[x.letters[i]] += x.degrees[i]         }     }     for(var letter in letterMap){         letters.push(letter)         degrees.push(letterMap[letter])     }     return new Monomial(this.coeff*x.coeff, letters, degrees) } It's a bit long and inefficient. But I'll go to next step. I'm just prototyping and when it needs good performance, I can revise only the inside of the method. In other words, it's an unpropagated, controllable inefficiency. We finished addition and multiplication of two monomials. Remaining work is boring and obvious extension from mono to poly. Need to add a monomial M and a polynomial P? Find a monomial N in P that is mergeable with M. If N exists, merge M into N. otherwise, append M to P's monomial list. Adding two polynomials P and Q is simple as previous. apply above step with Q's every monomials for P. Multiplication of P and Q: multiply all monomial pairs of P and Q, and sum up them. it's PxQ. Polynomial.prototype.addMonomial = function(x) {     for(var i=0; i<this.monomials.length; i++){         if(this.monomials[i].mergeable(x)){             this.monomials[i] = this.monomials[i].add(x)             break         }     }     if(i == this.monomials.length){         this.monomials.push(x)     }     return this } Polynomial.prototype.add = function(X) {     for(var i=0; i<X.monomials.length; i++){         this.addMonomial(X.monomials[i])     } } Polynomial.prototype.multiply = function(X) {     var P = new Polynomial()     for(var i=0; i<this.monomials.length; i++){         for(var j=0; j<X.monomials.length; j++){             P.addMonomial(this.monomials[i].multiply(X.monomials[j]))         }     }     return P } Finally, If you want to see a real example, it's here:  http://jsfiddle.net/codeonwort/ynz8nqzx/  0 Comments 댓글쓰기 폼
__label__pos
0.999551