content
stringlengths
228
999k
pred_label
stringclasses
1 value
pred_score
float64
0.5
1
fork で子プロセスを複数生成する C言語のforkで子プロセスを複数生成する方法。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #define P_MAX 10 //プロセス数 int main(){ int pid[P_MAX]; /* 子プロセス生成。子プロセスは次の行から始まるため、 このような記述をすると、子プロセスが子プロセスを生成しないで済む。 */ for( i=0 ; i < P_MAX && (pid[i] = fork()) > 0 ; i++ ); if( i == P_MAX ){ //親プロセスはすべての子プロセスの終了を待つ for( i = 0 ; i < P_MAX ; i++ ){ wait(&val); } }else if( pid[i] == 0){ //子プロセス printf("child:%d\n",i); exit(0); }else{ perror("child process") ; exit(0); } return 0; }
__label__pos
0.514263
What is a JSP Scriptlet? What is a JSP Scriptlet? JSP Scriptlets is a term used to refer to pieces of Java code that can be embedded in a JSP PAge. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked.    Top Blogs
__label__pos
0.999344
Contents Hide contents SwiftUI by Tutorials Before You Begin Section 0: 4 chapters Show chapters Hide chapters 8 State & Data Flow — Part I Written by Antonio Bello Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text. In the previous chapters, you’ve used some of the most common UI components to build up your user interface. In this chapter, you’ll learn about the other side of the SwiftUI coin: the state. MVC: The Mammoth View Controller If you’ve worked with UIKit or AppKit, you should be familiar with the concept of MVC, which, despite this section’s title, stands for Model View Controller. It’s vulgarly known as Massive View Controller. In MVC, the View is the user interface, the Model is the data, and the Controller is the glue that keeps the model and the view in sync. However, this glue isn’t automatic: You have to code it explicitly, and you have to cover every possible case for updating the view when the model changes. Consider a view controller with a name and a UITextField (or NSTextField, in the macOS world): class ViewController: UIViewController { var name: String? @IBOutlet var nameTextField: UITextField! } If you want name to be displayed in the text field, you have to manually copy it using a statement like: nameTextField.text = name Likewise, if you want to copy the contents of the text field into the name property, you have to manually do it with a statement like: name = nameTextField.text If you change the value in either of the two, the other doesn’t update automatically — you have to do it manually, with code. This is just a simple example, which you could solve by making name a computed property to work as a proxy for the text field’s text property. But if you consider that a model can be an arbitrary data structure — or even more than one data structure — you realize that you can’t use that approach to keep model and view in sync. Besides the model, the UI also depends on a state. Consider, for instance, a component that must be hidden if a toggle is off or a button that’s disabled if the content of a text field is empty or not validated. Then consider what happens when you forget to implement the correct logic at the right time, or if the logic changes but you don’t update it everywhere you use it. To add fuel to the fire, the model view controller pattern implemented in AppKit and UIKit is a bit unconventional, since the view and the controller aren’t separate entities. Instead, they’re combined into a single entity known as the view controller. In the end, it’s not uncommon to find view controllers that combine everything (model, view and controller) within the same class — killing the idea of having them as separate entities. That’s what caused the “Model” term in Model View Controller to be replaced with “Massive”, making it a brand new fat pattern known as Massive View Controller. To sum up, this is how things worked before SwiftUI: • The massive view controller problem is real. • Keeping the model and UI in sync is a manual process. • The state is not always in sync with the UI. • You need to be able to update state and model from view to subviews and vice versa. • All this is error-prone and open to bugs. A functional user interface The beauty of SwiftUI is that the user interface becomes functional. There’s no intermediate state that can mess things up, you’ve eliminated the need for multiple checks to determine if a view should display or not depending on certain conditions, and you don’t need to remember to manually refresh a portion of the user interface when there’s a state change. Initial Challenge View Iqizaoz Pnefkorbo Yeiq State If you’ve read along in this book so far, you’ve already encountered the @State attribute and you’ve developed an idea of what it’s for and how to use it. But it’s been an acquaintance — it’s time to let it become a friend. var numberOfAnswered = 0 var numberOfQuestions = 5 var body: some View { HStack { Text("\(numberOfAnswered)/\(numberOfQuestions)") .font(.caption) .padding(4) Spacer() } } Score View Sduka Vauv Button(action: { self.showAnswers.toggle() }) { QuestionView(question: challengeTest.challenge.question) .frame(height: 300) } // -Insert this- ScoreView() Challenge Score View Zlebrigfi Psama Daiw var body: some View { // 1 Button(action: { // 2 self.numberOfAnswered += 1 }) { // 3 HStack { Text("\(numberOfAnswered)/\(numberOfQuestions)") .font(.caption) .padding(4) Spacer() } } } Score View error Czoqi Buel igsaf Embedding the state into a struct What if you try moving the properties to a separate structure? Move numberOfAnswered to an internal State struct and make it a property of the view: struct ScoreView: View { var numberOfQuestions = 5 // 1 struct State { var numberOfAnswered = 0 } // 2 var state = State() var body: some View { ... } } Text("\(state.numberOfAnswered)/\(numberOfQuestions)") self.state.numberOfAnswered += 1 Embedding the state into a class By replacing a value type with a reference type, however, things change considerably. Try making State a class: class State { var numberOfAnswered = 0 } Score view live preview Zyuba wuek qaxe xpaqeec self.state.numberOfAnswered += 1 print("Answered: \(self.state.numberOfAnswered)") Wrap to class, embed to struct Now that you’ve seen it still doesn’t work, here’s a challenge: What if you want to get rid of the class and use a struct, again? class Box<T> { var wrappedValue: T init(initialValue value: T) { self.wrappedValue = value } } struct State { var numberOfAnswered = Box<Int>(initialValue: 0) } self.state.numberOfAnswered.wrappedValue += 1 print("Answered: \(self.state.numberOfAnswered.wrappedValue)") Text("\(state.numberOfAnswered.wrappedValue)/\(numberOfQuestions)") The real State At this point, you can officially ask: What’s the point of all this discussion? var _numberOfAnswered = State<Int>(initialValue: 0) struct ScoreView: View { var numberOfQuestions = 5 var _numberOfAnswered = State<Int>(initialValue: 0) var body: some View { Button(action: { self._numberOfAnswered.wrappedValue += 1 print("Answered: \(self._numberOfAnswered)") }) { HStack { Text("\(_numberOfAnswered.wrappedValue)/\(numberOfQuestions)") .font(.caption) .padding(4) Spacer() } } } } Score view updating Xhimo qoek ejvinuzt @State var numberOfAnswered = 0 var body: some View { Button(action: { // 1 self._numberOfAnswered.wrappedValue += 1 // 2 print("Answered: \(self._numberOfAnswered.wrappedValue)") }) { HStack { // 3 Text("\(_numberOfAnswered.wrappedValue)/\(numberOfQuestions)") .font(.caption) .padding(4) Spacer() } } } self.numberOfAnswered += 1 print("Answered: \(self.numberOfAnswered)") Text("\(numberOfAnswered)/\(numberOfQuestions)") var body: some View { HStack { Text("\(numberOfAnswered)/\(numberOfQuestions)") .font(.caption) .padding(4) Spacer() } } Not everything is reactive The score view defines two properties. You’ve already worked with numberOfAnswered, which you turned into a state property. What about the other one, numberOfQuestions? Why isn’t it a state property as well? let numberOfQuestions: Int ScoreView(numberOfQuestions: 5) Using binding for two-way reactions A state variable is not only useful to trigger a UI update when its value changes; it also works the other way around. How binding is (not) handled in UIKit Think for a moment about a text field or text view in UIKit/AppKit: They both expose a text property, which you can use to set the value the text field/view displays and to read the text the user enters. Owning the reference, not the data SwiftUI makes this process simpler. It uses a declarative approach and leverages the reactive nature of state properties to automatically update the user interface when the state property changes. struct RegisterView: View { var name: String = "" var body: some View { VStack { TextField("Type your name...", text: name) .bordered() } .padding() .background(WelcomeBackgroundImage()) } } struct RegisterView_Previews: PreviewProvider { static var previews: some View { RegisterView() } } var name: State<String> = State(initialValue: "") TextField("Type your name...", text: name.projectedValue) Editing in a Text Field Aramibh oy e Viqy Juung Text(name.wrappedValue) State and binding Hjese atg xaqxogy @State var name: String = "" TextField("Type your name...", text: $name) Text(name) State and binding Vveba ubb zinkusd if name.count >= 3 { Text(name) } Cleaning up Before moving on to the next topic, delete the code that you added in RegisterView and restore the code you commented out at the beginning of this section. Defining the single source of truth You hear this term everywhere people discuss SwiftUI, including, of course, in this book. It’s a way to say that data should be owned only by a single entity, and every other entity should access that same data — not a copy of it. @State var numberOfAnswered = 0 @State var numberOfAnswered: Int struct ScoreView_Previews: PreviewProvider { // 1 @State static var numberOfAnswered: Int = 0 static var previews: some View { // 2 ScoreView( numberOfQuestions: 5, numberOfAnswered: numberOfAnswered ) } } ScoreView( numberOfQuestions: 5, numberOfAnswered: numberOfAnswered ) self.numberOfAnswered += 1 Text("ChallengeView Counter: \(numberOfAnswered)") Text("ScoreView Counter: \(numberOfAnswered)") @Binding var numberOfAnswered: Int ScoreView( numberOfQuestions: 5, numberOfAnswered: $numberOfAnswered ) State and Binding 2 Qpawa obj Yavledn 4 Cleaning up again In the section above, you added some temporary code that you can now remove. @State var numberOfAnswered = 0 self.numberOfAnswered += 1 ScoreView(numberOfQuestions: 5) Text("ChallengeView Counter: \(numberOfAnswered)") @State var numberOfAnswered: Int = 0 Text("ScoreView Counter: \(numberOfAnswered)") ScoreView(numberOfQuestions: 5) Key points This was an intense and theoretical chapter. But in the end, the concepts are simple, once you understand how they work. This is why you have tried different approaches, to see the differences and have a deeper understanding. Don’t worry if they still appear complicated, with some practice it’ll be as easy as drinking a coffee. :] Where to go from here? You’ve only covered a few of the basics of state so far. In the next chapter you’ll dive deeper into state and data management in SwiftUI. Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here. © 2022 Kodeco Inc. You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription. Unlock Now
__label__pos
0.989567
0% 从零开始配置 react + typescript(三):webpack 本篇为 从零开始配置 react + typescript 系列第三篇,将带大家完成模板项目的 webpack 配置。整个项目的配置我力求达到以下目标: 灵活: 我在配置 eslint 是选择使用 js 格式而不是 json,就是为了灵活性,使用 js 文件可以让你使用导入其它模块,根据开发环境动态配置,充分发挥 js 语言的能力。 新潮: 我觉得时刻保持对新事物的关注和尝试去使用它是一个优秀的素质。当然,追新很容易碰到坑,但是,没关系,我已经帮你们踩过了,踩不过去我也不会写出来 😂。从我 eslint parserOptions.ecmaVersion 设置为 2020, 还有经常来一发 yarn upgrade --latest 都可以体现出来。 严格: 就像我平时判断相等性我大多数情况都是使用严格等 ===,而不是非严格等 ==,我觉得越严格,分析起来就越清晰,越早能发现问题。例如我么后面会使用一些 webpack 插件来严格检查模块大小写,检查是否有循环依赖。 安逸: 项目中会尽量集成当前前端生态界实用的和能提高开发愉悦性的(换个词就是花里胡哨)工具。 生产 ready:配置的时候针对不同的打包环境针对性优化,并确保能够投入生产环境使用。 本篇将分三大部分介绍: 1. dev server 2. 开发环境优化 3. 生产环境优化 如果读者是初次看到这篇文章,建议先看下前两篇: 1. 从零开始配置 react + typescript(一):dotfiles 2. 从零开始配置 react + typescript(二):linters 和 formatter 项目地址:react-typescript-boilerplate dev server 想当初我刚开始学前端框架的那时候,也是被 webpack 折磨的欲仙欲死,我是先自学的 node 才开始写前端,写 nodejs 很方便,自带的模块化方案 commonjs,写前端项目就要配置打包工具。当时最火的打包工具已经是 webpack 了,其次就是 gulp。配置 webpack 总是记不住 webpack 配置有哪些字段,还要扯到一堆相关的工具像 ES6 编译器 babel,CSS 预处理器 sass/less,CSS 后处理器 postcss,以及各种 webpack 的 loader 和 plugin。然后嫌麻烦就有一段时间都是用官方的脚手架,react 就用 cra,也就是 create-react-app,vue 就用 vue-cli。其实也挺好用的,不过说实话,我个人觉得,cravue-cli 设计的好,无论是易用性和扩展性都完败,cra 不方便用户修改 webpack 配置,vue-cli 不但易于用户修改 webpack 配置,还能让用户保存模板以及自带插件系统。我感觉 react 官方也意识到了这点,所以官方声称近期将会重点优化相关工具链。现在的话,如果我新建一个前端项目,我会选择自己配,不会去采用官方的 cli,因为我觉得我自己已经相当熟悉前端各种构建工具了,等我上半年忙完毕业和找工作的事情我应该会将一些常用的配置抽成一个 npm 包,现在每次写一个项目都 copy 改太累了,一个项目的构建配置有优化点,其它项目都要手动同步一下,效率太低。 技术选型 TypeScript 作为静态类型语言,相对于 js 而言,在类型提示上带来的提升无疑是巨大的。借助 IDE 的类型提示和代码补全,我们需要知道 webpack 配置对象有哪些字段就不用去查官方文档了,而且还不会敲错,很安逸,所以开发语言就选择 TypeScript 官方文档上有专门一节 Configuration Languages 介绍 webpack 命令行工具怎么使用 ts 格式的配置文件 ,我觉得 webpack-dev-server 命令行工具应该是一样的。 但是我不打算使用官方文档介绍的方式,我压根不打算使用命令行工具,用 node API 才是最灵活的配置方式。配置 webpack devServer 总结一下有以下方式: 1. webpack-dev-server,这是最不灵活的方式,当然使用场景简单的情况下还是很方便的 2. webpack-dev-server node API,在 node 脚本里面调用 web-dev-server 包提供的 node API 来启动 devServer 3. express + webpack devServer 相关中间件,实际上 webpack-dev-server 就是使用 express 以及一些 devServer 相关的中间件开发的。在这种方式下, 各种中间件直接暴露出来了,我们可以灵活配置各个中间件的选项。 4. koa + webpack devServer 相关中间件,我在 github 上还真的搜到了和 webpack devServer 相关的 webpack 中间件。其实 webpack devServer 就是一个 node server 嘛,用什么框架技术实现不重要,能实现我们需要的功能就行。 我最终采用 express + webpack devServer 相关中间件的方式,为什么不选择用 koa ?因为我觉得官方用的就是 express,用 express 肯定要比 koa 更成熟稳定,坑要少一些。 实现最基本的打包功能 从简到繁,我们先来实现最基本的打包功能使其能够打包 tsx 文件,在此基础上一步一步丰富,优化我们的配置。 配置入口文件 先安装 TypeScript: 1 2 # 本地安装开发依赖 typescript yarn add typescript -D 每个 TypeScript 项目都需要有一个 tsconfig.json 配置文件,使用下面的命令在 src 目录下新建 tsconfig.json 文件: 1 cd src && npx tsc --init && cd .. 我们暂时调整成这样: 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 { "compilerOptions": { /* Basic Options */ "jsx": "react", "isolatedModules": true, /* Strict Type-Checking Options */ "strict": true, /* Additional Checks */ "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, /* Module Resolution Options */ "moduleResolution": "node", "esModuleInterop": true, "resolveJsonModule": true, "baseUrl": "./", "paths": { // 配置模块路径映射 "@/*": ["./*"], }, /* Experimental Options */ "experimentalDecorators": true, "emitDecoratorMetadata": true, /* Advanced Options */ "forceConsistentCasingInFileNames": true, "skipLibCheck": true, // 下面这些选项对 babel 编译 TypeScript 没有作用但是可以让 VSCode 等编辑器正确提示错误 "target": "ES2019", "module": "ESNext" } } 我们将使用 babel 去编译 TypeScript,babel 在编译 TypeScript 代码是直接去掉 TypeScript 的类型,然后当成普通的 javascript 代码使用各种插件进行编译,tsc 并没有介入编译过程,因此 tsconfig.json 中很多选项例如 targetmodule 是没有用的。 启用 isolatedModules 选项会在 babel 编译代码时提供一些额外的检查,esModuleInterop 这个选项是用来为了让没有 default 属性的模块也可以使用默认导入,举个简单的例子,如果这个选项没开启,那你导入 fs 模块只能像下面这样导入: 1 import * as fs from 'fs'; 开启了以后,可以直接使用默认导入: 1 import fs from 'fs'; 本质上 ESM 默认导入是导入模块的 default 属性: 1 2 3 4 import fs from 'fs'; // 等同于 import * as __module__ from 'fs'; let fs = __module__.default; 但是 node 内建模块 fs 是没有 default 属性的,开启 isolatedModules 选项就会在没有 default 属性的情况下自动转换: 1 2 3 4 import fs, { resolve } from 'fs'; // 转换成 import * as fs from 'fs'; let { resolve } = fs; 我们添加一个入口文件 src/index.tsx,内容很简单: 1 2 3 import plus from './plus'; console.log(plus(404, 404, 404, 404, 404)); // => 2020 src/plus.ts 内容为: 1 2 3 export default function plus(...nums: number[]) { return nums.reduce((pre, current) => pre + current, 0); } 编译 TypeScript 我们知道 webpack 默认的模块化系统只支持 js 文件,对于其它类型的文件如 jsx, ts, tsx, vue 以及图片字体等文件类型,我们需要安装对应的 loader。对于 ts 文件,目前存在比较流行的方案有三种: 1. babel + @babel/preset-typescript 2. ts-loader 3. awesome-typescript-loader awesome-typescript-loader 就算了,作者已经放弃维护了。首先 babel 我们一定要用的,因为 babel 生态有很多实用的插件。虽然 babel 是可以和 ts-loader 一起用,ts-loader 官方给了一个例子 react-babel-karma-gulp,但是我觉得既然 babel 已经能够编译 TypeScript 我们就没必要再加一个 ts-loader,所以我选择方案一。需要指出的一点就是就是 babel 默认不会检查 TypeScript 的类型,后面 webpack 插件部分我们会通过配置 fork-ts-checker-webpack-plugin 来解决这个问题。 添加 webpack 配置 我们将把所有 node 脚本放到项目根目的 scripts 文件夹,因为 src 文件夹是前端项目,而 scripts 文件夹是 node 项目,我们应该分别配置 tsconfig.json,通过下面的命令在其中生成初始的 tsconfig.json 文件: 1 cd ./scripts && npx tsc --init && cd .. 我们调整成酱: 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 // scripts/tsconfig.json { "compilerOptions": { /* Basic Options */ "target": "ES2019", "module": "commonjs", /* Strict Type-Checking Options */ "strict": true, /* Additional Checks */ "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, /* Module Resolution Options */ "moduleResolution": "node", "esModuleInterop": true, "resolveJsonModule": true, /* Experimental Options */ "experimentalDecorators": true, "emitDecoratorMetadata": true, /* Advanced Options */ "forceConsistentCasingInFileNames": true, "skipLibCheck": true } } 提几个需要注意的地方: • "target": "ES2019",其实编译级别你调的很低是没问题的,你用高级语法 tsc 就转码呗,缺点就是转码后代码体积一般会变大,执行效率也会降低,原生语法一般都是被优化过的。我喜欢调高一点,一般来说只要不用那些在代码运行平台还不支持的语法就没问题。自从 TypeScript3.7 支持了可选链,我就开始尝试在 TypeScript 使用它,但是问题来了,我之前编译级别一直都是调成最高,也就是 ESNext,因为可选链在 ES2020 已经是标准了,所以 tsc 对于可选链不会转码的。然后 node 12 还不支持可选链,就会报语法错误,于是我就降到 ES2019 了。 • Strict Type-Checking Options,这部分全开,既然上了 TypeScript 的船,就用最严格的类型检查,拒绝 AnyScript 接着我们新建 scripts/configs文件夹,里面用来存放包括 webpack 的配置文件。在其中新建三个 webpack 的配置文件 webpack.common.tswebpack.dev.tswebapck.prod.tswebpack.common.ts 保存一些公共的配置文件,webpack.dev.ts 是开发环境用的,会被 devServer 读取,webapck.prod.ts 是我们在构建生产环境的 bundle 时用的。 我们接着安装 webpack 和 webpack-merge 以及它们的类型声明文件: 1 yarn add webpack webpack-merge @types/webpack @types/webpack-merge -D webpack-merge 是一个为 merge webpack 配置设计的 merge 工具,提供了一些高级的 merge 方式。不过我目前并没有用到那些高级的 merge 方式,就是当成普通的 merge 工具使用,后续可以探索一下这方面的优化。 为了编译 tsx,我们需要安装 babel-loader 和相关插件: 1 yarn add babel-loader @babel/core @babel/preset-typescript -D 新建 babel 配置文件 babel.config.js,现在我们只添加一个 TypeScript preset: 1 2 3 4 5 6 7 8 9 10 11 12 // babel.config.js module.exports = function (api) { api.cache(true); const presets = ['@babel/preset-typescript']; const plugins = []; return { presets, plugins, }; }; 添加 babel-loader 到 webpack.common.ts 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 // webpack.common.ts` import { Configuration } from 'webpack'; import { projectName, projectRoot, resolvePath } from '../env'; const commonConfig: Configuration = { context: projectRoot, entry: resolvePath(projectRoot, './src/index.tsx'), output: { publicPath: '/', path: resolvePath(projectRoot, './dist'), filename: 'js/[name]-[hash].bundle.js', // 加盐 hash hashSalt: projectName || 'react typescript boilerplate', }, resolve: { // 我们导入ts 等模块一般不写后缀名,webpack 会尝试使用这个数组提供的后缀名去导入 extensions: ['.ts', '.tsx', '.js', '.json'], }, module: { rules: [ { // 导入 jsx 的人少喝点 test: /\.(tsx?|js)$/, loader: 'babel-loader', // 开启缓存 options: { cacheDirectory: true }, exclude: /node_modules/, }, ], }, }; 我觉得这个 react + ts 项目不应该会出现 jsx 文件,如果导入了 jsx 文件 webpack 就会报错找不到对应的 loader,可以让我们及时处理掉这个有问题的文件。 使用 express 开发 devServer 我们先安装 express 以及和 webpack devServer 相关的一些中间件: 1 2 yarn add express webpack-dev-middleware webpack-hot-middleware @types/express @t ypes/webpack-dev-middleware @types/webpack-hot-middleware -D webpack-dev-middleware 这个 express 中间件的主要作用: 1. 作为一个静态文件服务器,使用内存文件系统托管 webpack 编译出的 bundle 2. 如果文件被修改了,会延迟服务器的请求直到编译完成 3. 配合 webpack-hot-middleware 实现热更新功能 webpack-hot-middleware 这个 express 中间件会将自己注册为一个 webpack 插件,监听 webpack 的编译事件。 你哪个 entry 需要实现热更新,就要在那个 entry 中导入这个插件提供的 webpack-hot-middleware/client.js 客户端补丁。这个前端代码会获取 devServer 的 Server Sent Events 连接,当有编译事件发生,devServer 会发布通知给这个客户端。客户端接受到通知后,会通过比对 hash 值判断本地代码是不是最新的,如果不是就会向 devServer 拉取更新补丁借助一些其它的工具例如 react-hot-loader 实现热更新。 下面是我另外一个还在开发的 electron 项目修改了一行代码后, client 补丁发送的两次请求: hash update 第一次请求返回的那个 h 值动动脚趾头就能猜出来就是 hash 值,发现和本地的 hash 值比对不上后,再次请求更新补丁。 我们新建文件 scripts/start.ts 用来启动我们的 devServer: 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 import chalk from 'chalk'; import getPort from 'get-port'; import logSymbols from 'log-symbols'; import open from 'open'; import { argv } from 'yargs'; import express, { Express } from 'express'; import webpack, { Compiler, Stats } from 'webpack'; import historyFallback from 'connect-history-api-fallback'; import cors from 'cors'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import proxy from './proxy'; import devConfig from './configs/webpack.dev'; import { hmrPath } from './env'; function openBrowser(compiler: Compiler, address: string) { if (argv.open) { let hadOpened = false; // 编译完成时执行 compiler.hooks.done.tap('open-browser-plugin', async (stats: Stats) => { // 没有打开过浏览器并且没有编译错误就打开浏览器 if (!hadOpened && !stats.hasErrors()) { await open(address); hadOpened = true; } }); } } function setupMiddlewares(compiler: Compiler, server: Express) { const publicPath = devConfig.output!.publicPath!; // 设置代理 proxy(server); // 使用 browserRouter 需要重定向所有 html 页面到首页 server.use(historyFallback()); // 开发 chrome 扩展的时候可能需要开启跨域,参考:https://juejin.im/post/5e2027096fb9a02fe971f6b8 server.use(cors()); const devMiddlewareOptions: webpackDevMiddleware.Options = { // 保持和 webpack 中配置一致 publicPath, // 只在发生错误或有新的编译时输出 stats: 'minimal', // 需要输出文件到磁盘可以开启 // writeToDisk: true }; server.use(webpackDevMiddleware(compiler, devMiddlewareOptions)); const hotMiddlewareOptions: webpackHotMiddleware.Options = { // sse 路由 path: hmrPath, // 编译出错会在网页中显示出错信息遮罩 overlay: true, // webpack 卡住自动刷新页面 reload: true, }; server.use(webpackHotMiddleware(compiler, hotMiddlewareOptions)); } async function start() { const HOST = '127.0.0.1'; // 4个备选端口,都被占用会使用随机端口 const PORT = await getPort({ port: [3000, 4000, 8080, 8888] }); const address = `http://${HOST}:${PORT}`; // 加载 webpack 配置 const compiler = webpack(devConfig); openBrowser(compiler, address); const devServer = express(); setupMiddlewares(compiler, devServer); const httpServer = devServer.listen(PORT, HOST, err => { if (err) { console.error(err); return; } // logSymbols.success 在 windows 平台渲染为 √ ,支持的平台会显示 ✔ console.log( `DevServer is running at ${chalk.magenta.underline(address)} ${logSymbols.success}`, ); }); // 我们监听了 node 信号,所以使用 cross-env-shell 而不是 cross-env // 参考:https://github.com/kentcdodds/cross-env#cross-env-vs-cross-env-shell ['SIGINT', 'SIGTERM'].forEach((signal: any) => { process.on(signal, () => { // 先关闭 devServer httpServer.close(); // 在 ctrl + c 的时候随机输出 'See you again' 和 'Goodbye' console.log( chalk.greenBright.bold(`\n${Math.random() > 0.5 ? 'See you again' : 'Goodbye'}!`), ); // 退出 node 进程 process.exit(); }); }); } // 写过 python 的人应该不会陌生这种写法 // require.main === module 判断这个模块是不是被直接运行的 if (require.main === module) { start(); } webpackHotMiddlewareoverlay 选项是用于是否开启错误遮罩: overlay 很多细节我都写到注释里面了,安装其中用到的一些工具库: 1 yarn add get-port log-symbols open yarg -D 前三个都是 sindresorhus 大佬的作品,get-port 用于获取可用端口,log-symbols 提供了下面四个 log 字符,open 用于系统应用打开 uriuri 包括文件和网址大家应该都知道), yargs 用于解析命令行参数。 log-symbols webpack-dev-middleware 并不支持 webpack-dev-server 中的 historyFallbackproxy 功能,其实无所谓,我们可以通过 DIY 我们的 express server 来实现,我们甚至可以使用 express 来集成 mock 功能。安装对应的两个中间件: 1 yarn add connect-history-api-fallback http-proxy-middleware @types/connect-history-api-fallback @types/http-proxy-middleware -D connect-history-api-fallback 可以直接作为 express 中间件集成到 express server,封装一下 http-proxy-middleware,可以在 proxyTable 中添加自己的代理配置: 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 import { createProxyMiddleware } from 'http-proxy-middleware'; import chalk from 'chalk'; import { Express } from 'express'; import { Options } from 'http-proxy-middleware/dist/types'; interface ProxyTable { [path: string]: Options; } const proxyTable: ProxyTable = { // 示例配置 '/path_to_be_proxy': { target: 'http://target.domain.com', changeOrigin: true }, }; // 修饰链接的辅助函数, 修改颜色并添加下划线 function renderLink(str: string) { return chalk.magenta.underline(str); } function proxy(server: Express) { Object.entries(proxyTable).forEach(([path, options]) => { const from = path; const to = options.target as string; console.log(`proxy ${renderLink(from)} ${chalk.green('->')} ${renderLink(to)}`); // eslint-disable-next-line no-param-reassign if (!options.logLevel) options.logLevel = 'warn'; server.use(path, createProxyMiddleware(options)); // 如果需要更灵活的定义方式,请在下面直接使用 server.use(path, proxyMiddleware(options)) 定义 }); process.stdout.write('\n'); } export default proxy; 为了启动 devServer,我们还需要安装两个命令行工具: 1 yarn add ts-node cross-env -D ts-node 可以让我们直接运行 TypeScript 代码,cross-env 是一个跨操作系统的设置环境变量的工具,添加启动命令到 npm script: 1 2 3 4 5 6 // package.json { "scripts": { "start": "cross-env-shell NODE_ENV=development ts-node --files -P ./scripts/tsconfig.json ./scripts/start.ts --open", } } cross-env 官方文档提到如果要在 windows 平台处理 node 信号例如 SIGINT,也就是我们 ctrl + c 时触发的信号应该使用 cross-env-shell 命令而不是 cross-env ts-node 为了提高执行速度,默认不会读取 tsconfig.json 中的 files, includeexclude 字段,而是基于模块依赖读取的。这会导致我们后面写的一些全局的 .d.ts 文件不会被读取,为此,我们需要指定 --files 参数,详情可以查看 help-my-types-are-missing。我们的 node 代码并不多,而且又不是经常性重启项目,直接让 ts-node 扫描整个 scripts 文件夹没多大影响。 启动我们的 dev server,通过 ctrl + c 退出: 1 npm start dev server 开发环境优化 plugins 每个 webpack plugin 都是一个包含 apply 方法的 class,在我们调用 compiler.run 或者 compiler.watch 的时候它就会被调用,并且把 compiler 作为参数传它。compiler 对象提供了各个时期的 hooks,我们可以通过这些 hooks 挂载回调函数来实现各种功能,例如压缩,优化统计信息,在在编译完弹个编译成功的通知等。 hooks 显示打包进度 webpack-dev-server 在打包时使用 --progress 参数会在控制台实时输出百分比表示当前的打包进度,但是从上面的图中可以看出只是输出了一些统计信息(stats)。想要实时显示打包进度我了解的有三种方式: 1. webpack 内置的 webpack.ProgressPlugin 插件 2. progress-bar-webpack-plugin 3. webpackbar 内置的 ProgressPlugig 非常的原始,你可以在回调函数获取当前进度,然后按照自己喜欢的格式去打印: 1 2 3 4 5 const handler = (percentage, message, ...args) => { // e.g. Output each progress message directly to the console: console.info(percentage, message, ...args); }; new webpack.ProgressPlugin(handler); progress-bar-webpack-plugin 这个插件不是显示百分比,而是显示一个用字符画出来的进度条: progress-bar-webpack-plugin 这个插件其实还是挺简洁实用的,但是有个 bug ,如果在打印进度条的时候输出了其它语句,进度条就会错位,我们的 devServer 会在启动后会输出地址: 1 console.log(`DevServer is running at ${chalk.magenta.underline(address)} ${logSymbols.success}`); 使用这个进度条插件就会出问题下面的问题,遂放弃。 progress-bar-webpack-plugin webpackbar 是 nuxt project 下的库,背靠 nuxt,质量绝对有保证。我之前有段时间用的是 progress-bar-webpack-plugin,因为我在 npm 官网搜索 webpack progress,综合看下来就它比较靠谱,webpackbar 都没搜出来。 看了下 webpackbarpackage.json,果然 keywords 都是空的。webpackBar 还是我在研究 ant design 的 webpack 配置看到它用了这个插件,才发现了这个宝藏: webpackbar 安装 webpackbar 1 yarn add webpackbar @types/webpackbar -D 添加配置到 webpack.common.ts 的 plugins 数组,颜色我们使用 react 蓝: 1 2 3 4 5 6 7 8 9 10 11 import { Configuration } from 'webpack'; const commonConfig: Configuration = { plugins: [ new WebpackBar({ name: 'react-typescript-boilerplate', // react 蓝 color: '#61dafb', }), ], }; 优化控制台输出 我们使用 friendly-errors-webpack-plugin 插件让控制台的输出更加友好,下面使用了之后编译成功时的效果: build successful 1 yarn add friendly-errors-webpack-plugin @types/friendly-errors-webpack-plugin -D 1 2 3 4 5 6 // webpack.common.ts import FriendlyErrorsPlugin from 'friendly-errors-webpack-plugin'; const commonConfig: Configuration = { plugins: [new FriendlyErrorsPlugin()], }; 构建通知 build notification 在我大四实习之前,我就没完整写过 vue 项目的,在上家公司实习的那段时间主要就是写 vue,当时我对 vue-cli 那个频繁的错误通知很反感,我和同事说我想去掉这个通知,没曾想同事都是比较喜欢那个通知,既然有人需要,那我们这个项目也配一下。 我们使用 webpack-build-notifier 来支持错误通知,这个插件是 TypeScript 写的,不需要安装 types: 1 yarn add webpack-build-notifier -D 1 2 3 4 5 6 7 8 9 // webpack.common.ts import WebpackBuildNotifierPlugin from 'webpack-build-notifier'; const commonConfig: Configuration = { plugins: [ // suppressSuccess: true 设置只在第一次编译成功时输出成功的通知, rebuild 成功的时候不通知 new WebpackBuildNotifierPlugin({ suppressSuccess: true }), ], }; 因为我不喜欢弹通知,所以模板项目中的我注释掉了这个插件,有需要的自己打开就行了。 严格检查路径大小写 下面的测试表明 webpack 默认对路径的大小写不敏感: path case 我们使用 case-sensitive-paths-webpack-plugin 对路径进行严格的大小写检查: 1 yarn add case-sensitive-paths-webpack-plugin @types/case-sensitive-paths-webpack-plugin -D 1 2 3 4 5 6 // webpack.common.ts import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin'; const commonConfig: Configuration = { plugins: [new CaseSensitivePathsPlugin()], }; path-case-check 实际打包测试中发现这个插件非常耗时,并且因为 eslint-import-plugin 默认会对只是大小写不一样的模块路径会报错,因此我们这个项目就不集成了。 case sensitive 循环依赖检查 circle-dependencies webpack 默认不会对循环依赖报错,通过 circular-dependency-plugin 这个 webpack 插件可以帮我们及时发现循环依赖的问题: 1 yarn add circular-dependency-plugin @types/circular-dependency-plugin -D 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // webpack.common.ts import CircularDependencyPlugin from 'circular-dependency-plugin'; import { projectRoot, resolvePath } from '../env'; const commonConfig: Configuration = { plugins: [ new CircularDependencyPlugin({ exclude: /node_modules/, failOnError: true, allowAsyncCycles: false, cwd: projectRoot, }), ], }; circle dependencies error 这里顺便提一下 cwd 也就是工作路径的问题,官方文档直接用 process.cwd(),这是一种不好的做法,项目路径和工作路径是不同的两个概念。在 node 中表示项目路径永远不要用 preocess.cwd(),因为总会有些沙雕用户不去项目根目录启动。process.cwd() 也就是工作路径返回的是你运行 node 时所在的路径,假设说项目在 /code/projectRoot,有些用户直接在系统根目录打开 terminal,来一句 node ./code/projectRoot/index.js,这时 index.jsprocess.cwd() 返回的是就是系统根路径 /,不是有些人认为的还是 /code/projectRoot 获取项目路径应该使用 path.resolve project root 这个问题 eslint-import-plugin 也会报错,并且在 TypeScript 项目中有时候就是需要循环导入文件,因此也不集成。 清理上次打包的 bundle 前面介绍了一些花里胡哨的插件,也介绍了一些让我们项目保持健康的插件,现在我们开始介绍一些打包用的插件。 clean-webpack-plugin 它会在第一次编译的时候删除 dist 目录中所有的文件,不过会保留 dist 文件夹,并且再每次 rebuild 的时候会删除所有不再被使用的文件。 这个项目也是 TypeScript 写的,总感觉 TypeScript 写的项目有种莫名的踏实感: 1 yarn add clean-webpack-plugin -D 1 2 3 4 5 6 // webpack.common.ts import { CleanWebpackPlugin } from 'clean-webpack-plugin'; const commonConfig: Configuration = { plugins: [new CleanWebpackPlugin()], }; 自动生成 index.html 众所周知,腾讯的前端面试很喜欢考计算机网络,我曾多次被问到过如何更新强缓存的问题。解决强缓存立即更新的问题我们一般就是采取在文件名中插入文件内容的 hash 值,然后首页不使用强缓存。这样只要你更新了某个被强缓存的资源文件,由于更新后内容的 hash 值会变化,生成的文件名也会变化,这样你请求首页的时候由于访问的是一个新的资源路径,就会向服务器请求最新的资源。关于浏览器 HTTP 缓存可以看我另一篇文章:通过-koa2-服务器实践探究浏览器 HTTP 缓存机制 我们后续优化生产环境构建的时候会对将 CSS 拆分成单独的文件,如果 index.html 中插入的引入外部样式的 link 标签的 href 是我们手动设置的,那每次修改样式文件,都会生成一个新的 hash 值,我们都要手动去修改这个路径,太麻烦了,更不要说在开发环境下文件是保存在内存文件系统的,你都看不到文件名。 build hash 使用 html-webpack-plugin 可以自动生成 index.html,并且插入引用到的 bundle 和被拆分的 CSS 等资源路径。 参考 creat-react-app 的模板,我们新建 public 文件夹,并在其中加入 index.htmlfavico.icomanifest.json 等文件。public 文件夹用于存放一些将被打包到 dist 文件夹一同发布的文件。 安装并配置 html-webpack-plugin 1 yarn add html-webpack-plugin @types/html-webpack-plugin -D 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 import HtmlWebpackPlugin from 'html-webpack-plugin'; import { __DEV__, projectName, resolvePath, projectRoot, hmrPath } from '../env'; const htmlMinifyOptions: HtmlMinifierOptions = { collapseWhitespace: true, collapseBooleanAttributes: true, collapseInlineTagWhitespace: true, removeComments: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, minifyCSS: true, minifyJS: true, minifyURLs: true, useShortDoctype: true, }; const commonConfig: Configuration = { output: { publicPath: '/', }, plugins: [ new HtmlWebpackPlugin({ // HtmlWebpackPlugin 会调用 HtmlMinifier 对 HTMl 文件进行压缩 // 只在生产环境压缩 minify: __DEV__ ? false : htmlMinifyOptions, // 指定 html 模板路径 template: resolvePath(projectRoot, './public/index.html'), // 类型不好定义,any 一时爽... // 定义一些可以在模板中访问的模板参数 templateParameters: (...args: any[]) => { const [compilation, assets, assetTags, options] = args; const rawPublicPath = commonConfig.output!.publicPath!; return { compilation, webpackConfig: compilation.options, htmlWebpackPlugin: { tags: assetTags, files: assets, options, }, // 除掉 publicPath 的反斜杠,让用户在模板中拼接路径更自然 PUBLIC_PATH: rawPublicPath.endsWith('/') ? rawPublicPath.slice(0, -1) : rawPublicPath, }; }, }), ], }; 为了让用户可以像 create-react-app 一样在 index.html 里面通过 PUBLIC_PATH 访问发布路径,需要配置 templateParameters 选项添加 PUBLIC_PATH 变量到模板参数,html-webpack-plugin 默认支持部分 ejs 语法,我们可以通过下面的方式动态设置 favicon.ico , mainfest.json 等资源路径: 1 2 3 4 5 6 7 8 9 10 11 12 13 <!DOCTYPE html> <html lang="en"> <head> <link rel="icon" href="<%= `${PUBLIC_PATH}/favicon.ico` %>" /> <link rel="apple-touch-icon" href="<%= `${PUBLIC_PATH}/logo192.png` %>" /> <link rel="manifest" href="<%= `${PUBLIC_PATH}/manifest.json` %>" /> <title>React App</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> </body> </html> 拷贝文件到 dist public 文件夹中有一些文件例如 favico.iconmainfest.json 需要被拷贝到 dist 文件夹,我们可以使用 copy-webpack-plugin 在使用 devServer 的情况下将文件拷贝到内存文件系统,在生产环境构建的时拷贝到磁盘: 1 yarn add copy-webpack-plugin @types/copy-webpack-plugin -D 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // webpack.common.ts import CopyPlugin from 'copy-webpack-plugin'; const commonConfig: Configuration = { plugins: [ new CopyPlugin( [ { // 所有一级文件 from: '*', to: resolvePath(projectRoot, './dist'), // 目标类型是文件夹 toType: 'dir', // index.html 会通过 html-webpack-plugin 自动生成,所以需要被忽略掉 ignore: ['index.html'], }, ], { context: resolvePath(projectRoot, './public') } ), ], }; 检查 TypeScript 类型 babel 为了提高编译速度只支持 TypeScript 语法编译而不支持类型检查,为了在 webpack 打包的同时支持 ts 类型检查,我们会使用 webpack 插件 fork-ts-checker-webpack-plugin,这个 webpack 插件会在一个单独的进程并行的进行 TypeScript 的类型检查,这个项目也是 TypeScript 写的,我们不需要安装 types。 1 yarn add fork-ts-checker-webpack-plugin -D 添加到 webpack.dev.ts,限制使用的内存为 1G: 1 2 3 4 5 6 7 8 9 10 11 12 import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'; const devConfig = merge(commonConfig, { mode: 'development', plugins: [ new ForkTsCheckerWebpackPlugin({ memoryLimit: 1024, // babel 转换的是我们前端代码,所以是指向前端代码的 tsconfig.json tsconfig: resolvePath(projectRoot, './src/tsconfig.json'), }), ], }); 同时修改 webpack.prod.ts,因为我们生产环境构建并不会长时间的占用内存,所以可以调大点,我们就默认限制生产环境的构建使用的内存为 2G: 1 2 3 4 5 6 7 8 9 10 // webpack.prod.ts const prodConfig = merge(commonConfig, { mode: 'production', plugins: [ new ForkTsCheckerWebpackPlugin({ memoryLimit: 1024 * 2, tsconfig: resolvePath(projectRoot, './src/tsconfig.json'), }), ], }); 缓存神器 hard-source-webpack-plugin 是一个给 modules 提供中间缓存步骤的 webpack 插件,为了看到效果我们可能需要运行两次,第一次就是正常的编译速度,第二次可能会快上很多倍,拿我开发的一个 VSCode 插件 来测试一下: 我先把 node_modules/.cache/hard-source 缓存文件夹删掉,看看没有缓存的时候编译速度: no cache 耗时 3.075 秒,重新编译: cache 哇 🚀,直接快了 3.6 倍多… 实测发现这个插件在初次打包会耗时严重,并且即将发布的 webpack5 将内置这个功能,具体可以看这个 issue: [spec: webpack 5] - A module disk cache between build processes 。因此我们这个项目就不集成这个插件了。 好了,插件部分介绍完了,接下来开始配置 loaders ! loaders webpack 默认只支持导入 js,处理不了其它文件,需要配置对应的 loader,像 excel-loader 就可以解析 excel 为一个对象,file-loader 可以解析 png 图片为最终的发布路径。loader 是作用于一类文件的,plugin 是作用于 webpack 编译的各个时期。 前面我们只配置了 babel-loader, 使得 webpack 能够处理 TypeScript 文件,实际的开发中我们还需要支持导入样式文件,图片文件,字体文件等。 处理样式文件 我们最终要达到的目标是支持 css/less/sass 三种语法,以及通过 postcssautoprefixer 插件实现自动补齐浏览器头等功能。 CSS 处理 css 文件我们需要安装 style-loadercss-loader 1 yarn add css-loader style-loader -D css-loader 作用是处理 CSS 文件中的 @importurl() 返回一个合并后的 CSS 字符串,而 style-loader 负责将返回的 CSS 字符串用 style 标签插到 DOM 中,并且还实现了 webpack 的热更新接口。 style-loader 官方示例配置是这样的: 1 2 3 4 5 6 7 8 9 10 11 module.exports = { module: { rules: [ { // i 后缀忽略大小写 test: /\.css$/i, use: ['style-loader', 'css-loader'], }, ], }, }; 可以看到匹配正则用了 i 后缀,我觉得这样不好,不应该提高一些无意义的容错率,用.CSS 做后缀就不应该让 webpack 编译通过。我们知道 webpack 的 loaders 加载顺序是从右到左的,所以需要先执行的 css-loader 应该在后执行的 style-loader 后面: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // webpack.common.ts const commonConfig: Configuration = { module: { rules: [ { test: /\.css$/, use: [ 'style-loader', { loader: 'css-loader', options: { // CSS modules 比较耗性能,默认就是禁用的 modules: false, // 开启 sourcemap sourceMap: true, // 指定在 CSS loader 处理前使用的 laoder 数量 importLoaders: 0, }, }, ], }, ], }, }; less less-loader 依赖 less 1 yarn add less less-loader -D 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 // webpack.common.ts const commonConfig: Configuration = { module: { rules: [ { test: /\.less$/, use: [ 'style-loader', { loader: 'css-loader', options: { modules: false, sourceMap: true, // 需要先被 less-loader 处理,所以这里设置为 1 importLoaders: 1, }, }, { // 先让 less-loader 将 less 文件转换成 css 文件 // 再交给 css-loader 处理 loader: 'less-loader', options: { sourceMap: true, }, }, ], }, ], }, }; sass 其实我本人从来不用 lessstylus,我一直用的是 sasssass 有两种语法格式,通过后缀名区分。.sass 后缀名是类似 yml 的缩进写法,.scss 是类似于 CSS 的花括号写法,不过支持嵌套和变量等特性。鉴于我基本上没看过哪个项目用 yml 格式的写法,用的人太少了,我们模板就只支持 scss 后缀好了。sass-loader 同样依赖 node-sassnode-sass 真是个碧池,没有代理还安装不了,所以我在系列第一篇就在 .npmrc 就配置了 node-sass 的镜像: 1 yarn add node-sass sass-loader -D 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 // webpack.common.ts const commonConfig: Configuration = { module: { rules: [ { test: /\.scss$/, use: [ 'style-loader', { loader: 'css-loader', options: { modules: false, sourceMap: true, importLoaders: 1, }, }, { loader: 'sass-loader', options: { // 中间每个 loader 都要开启 sourcemap,才能生成正确的 soucemap sourceMap: true, }, }, ], }, ], }, }; postcss browser prefix 记得我在大一上网页设计课学到 CSS3 的时候,很多属性都要加浏览器头处理兼容性,当时就对 CSS 兴趣大减,太麻烦了。自从 node 的出现,前端工程化开始飞速发展,以前前端老被叫做切图仔,现在前端工程师也可以用 node 做伪全栈开发了。 postcss 是 CSS 后处理器工具,因为先有 CSS,postcss 后去处理它,所以叫后处理器。 less/sass 被称之为 CSS 预处理器,因为它们需要被 lessnode-sass 预先编译代码到 CSS 嘛。 参考 create-react-app 对 postcss 的配置,安装以下插件: 1 yarn add postcss-loader postcss-flexbugs-fixes postcss-preset-env autoprefixer postcss-normalize -D 添加 postcss.config.js 用于配置 postcss 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 module.exports = { plugins: [ // 修复一些和 flex 布局相关的 bug require('postcss-flexbugs-fixes'), // 参考 browserslist 的浏览器兼容表自动对那些还不支持的现代 CSS 特性做转换 require('postcss-preset-env')({ // 自动添加浏览器头 autoprefixer: { // will add prefixes only for final and IE versions of specification flexbox: 'no-2009', }, stage: 3, }), // 根据 browserslist 自动导入需要的 normalize.css 内容 require('postcss-normalize'), ], }; 我们还需要添加 browserslist 配置到 package.json 1 2 3 4 5 6 7 8 9 10 // package.json { "browserslist": [ "last 2 versions", // ESR(Extended Support Release) 长期支持版本 "Firefox ESR", "> 1%", "ie >= 11" ], } 回顾 CSS, less,sass 的配置可以看到有大量的重复,我们重构并修改 importLoaders 选项: 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 function getCssLoaders(importLoaders: number) { return [ 'style-loader', { loader: 'css-loader', options: { modules: false, sourceMap: true, importLoaders, }, }, { loader: 'postcss-loader', options: { sourceMap: true }, }, ]; } const commonConfig: Configuration = { module: { rules: [ { test: /\.css$/, use: getCssLoaders(1), }, { test: /\.less$/, use: [ // postcss-loader + less-loader 两个 loader,所以 importLoaders 应该设置为 2 ...getCssLoaders(2), { loader: 'less-loader', options: { sourceMap: true, }, }, ], }, { test: /\.scss$/, use: [ ...getCssLoaders(2), { loader: 'sass-loader', options: { sourceMap: true }, }, ], }, ], }, }; 处理图片和字体 一般来说我们的项目在开发的时候会使用一些图片来测试效果,正式上线再替换成 CDN 而不是使用 webpack 打包的本地图片。处理文件的常用 loader 有俩,file-loaderurl-loaderfile-loader 用于解析导入的文件为发布时的 url, 并将文件输出到指定的位置,而后者是对前者的封装,提供了将低于阈值体积(下面就设置为 8192 个字节)的图片转换成 base64。我忽然想起以前腾讯的一个面试官问过这么个问题:使用 base64 有什么坏处吗?其实我觉得 base64 好处就是不用二次请求,坏处就是图片转 base64 体积反而会变大,变成原来的三分之四倍。 base64 1 yarn add url-loader -D 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 const commonConfig: Configuration = { module: { rules: [ { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], use: [ { loader: 'url-loader', options: { // 图片低于 10k 会被转换成 base64 格式的 dataUrl limit: 10 * 1024, // [hash] 占位符和 [contenthash] 是相同的含义 // 都是表示文件内容的 hash 值,默认是使用 md5 hash 算法 name: '[name].[contenthash].[ext]', // 保存到 images 文件夹下面 outputPath: 'images', }, }, ], }, { test: /\.(ttf|woff|woff2|eot|otf)$/, use: [ { loader: 'url-loader', options: { name: '[name]-[contenthash].[ext]', outputPath: 'fonts', }, }, ], }, ], }, }; 注意到我这里文件名中都插入了文件内容 hash 值,这样就可以解决强缓存需要立即更新的问题。 sourcemap devtool构建速度重新构建速度生产环境品质(quality) (none)++++++yes打包后的代码 eval++++++no生成后的代码 cheap-eval-source-map+++no转换过的代码(仅限行) cheap-module-eval-source-mapo++no原始源代码(仅限行) eval-source-map+no原始源代码 cheap-source-map+oyes转换过的代码(仅限行) cheap-module-source-mapo-yes原始源代码(仅限行) inline-cheap-source-map+ono转换过的代码(仅限行) inline-cheap-module-source-mapo-no原始源代码(仅限行) source-mapyes原始源代码 inline-source-mapno原始源代码 hidden-source-mapyes原始源代码 nosources-source-mapyes无源代码内容 +++ 非常快速, ++ 快速, + 比较快, o 中等, - 比较慢, -- sourcemap 是现在前端界很多工具必不可缺的一个功能,webpack,TypeScript,babel,powser-assert 等转换代码的工具都要提供 sourcemap 功能,源代码被压缩,混淆,polyfill,没有 sourcemap,根本没办法调试定位问题。 考虑到编译速度,调式友好性,我选择 eval-source-map,如果用户在打包时觉得慢,而且能够忍受没有列号,可以考虑调成 cheap-eval-source-map 我们修改 webpack.dev.ts 的 devtool 为 eval-source-map 1 2 3 4 5 6 // webpack.dev.ts import commonConfig from './webpack.common'; const devConfig = merge(commonConfig, { devtool: 'eval-source-map', }); 这里顺便提一下 webpack 插件 error-overlay-webpack-plugin,它提供了和 create-react-app 一样的错误遮罩: error overlay 但是它有一个限制就是不能使用任何一种基于 eval 的 sourcemap,感兴趣的读者可以尝试以下。 热更新 我们前面给 devServer 添加了 webpack-hot-middleware 中间件,参考它的文档我们需要先添加 webapck 插件webpack.HotModuleReplacementPlugin 1 2 3 4 5 6 // webpack.dev.ts import { HotModuleReplacementPlugin, NamedModulesPlugin } from 'webpack'; const devConfig = merge(commonConfig, { plugins: [new HotModuleReplacementPlugin()], }); 还要添加 'webpack-hot-middleware/client' 热更新补丁到我们的 bundle,加入 entry 数组即可: 1 2 3 4 5 6 7 8 9 10 11 // webpack.common.ts import { __DEV__, hmrPath } from '../env'; const commonConfig: Configuration = { entry: [resolvePath(projectRoot, './src/index.tsx')], }; if (__DEV__) { (commonConfig.entry as string[]).unshift(`webpack-hot-middleware/client?path=${hmrPath}`); } 通过在 entry 后面加 queryString 的方式可以让我们配置一些选项,它是怎么实现的呢?查看 'webpack-hot-middleware/client' 源码可以看到,webpack 会将 queryString 作为全局变量注入这个文件: entry query 其实到这我们也就支持了 CSS 的热更新(style-loader 实现了热更新接口),如果要支持 react 组件的热更新我们还需要配置 react-hot-loader ,配置它之前我们先来优化我们的 babel 配置。 babel 配置优化 前面我们在前面只配置了一个 @babel/preset-typescript 插件用于编译 TypeScript,其实还有很多可以优化的点。 @babel/preset-env 在 babel 中,preset 表示 plugin 的集合@babel/preset-env 可以让 babel 根据我们配置的 browserslist 只添加需要转换的语法和 polyfill。 安装 @babel/preset-env 1 yarn add @babel/preset-env -D @babel/plugin-transform-runtime 我们知道默认情况下, babel 在编译每一个模块的时候在需要的时候会插入一些辅助函数例如 _extend,每一个需要的模块都会生成这个辅助函数会造成没必要的代码膨胀,@babel/plugin-transform-runtime 这个插件会将所有的辅助函数都从 @babel/runtime 导入,来减少代码体积。 1 yarn add @babel/plugin-transform-runtime -D @babel/preset-react 虽然 @babel/preset-typescript 就能转换 tsx 成 js 代码,但是 @babel/preset-react 还集成了一些针对 react 项目的实用的插件。 @babel/preset-react 默认会开启下面这些插件: • @babel/plugin-syntax-jsx • @babel/plugin-transform-react-jsx • @babel/plugin-transform-react-display-name 如果设置了 development: true 还会开启: • @babel/plugin-transform-react-jsx-self • @babel/plugin-transform-react-jsx-source 安装依赖 @babel/preset-react 1 yarn add @babel/preset-react -D react-hot-loader 为了实现组件的局部刷新,我们需要安装 react-hot-loader 这个 babel 插件。 1 yarn add react-hot-loader 这个插件不需要安装成 devDependencies,它在生产环境下不会被执行并且会确保它占用的体积最小。其实官方正在开发下一代的 react 热更新插件 React Fast Refresh,不过目前还不支持 webpack。 为了看到测试效果,我们安装 react 全家桶并且调整一下 src 文件夹下的默认内容: 1 2 yarn add react react-dom react-router-dom yarn add @types/react @types/react-dom @types/react-router-dom -D react 是框架核心接口,react-dom 负责挂载我们的 react 组件到真实的 DOM 上, react-dom-router 是实现了 react-router 接口的 web 平台的路由库。 react-hot-loader 接管我们的 react 根组件,其实这个 hot 函数就是一个 hoc 嘛: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // App.ts import React from 'react'; import { hot } from 'react-hot-loader/root'; import './App.scss'; const App = () => { return ( <div className="app"> <h2 className="title">react typescript boilerplate</h2> </div> ); }; export default hot(App); 在 webpack entry 加入热更新补丁: 1 2 3 const commonConfig: Configuration = { entry: ['react-hot-loader/patch', resolvePath(projectRoot, './src/index.tsx')], }; 官方文档提到如果需要支持 react hooks 的热更新,我们还需要安装 @hot-loader/react-dom,使用它来替换默认的 react-dom 来添加一些额外的热更新特性,为了替换 react-dom 我们需要配置 webpack alias: 1 2 3 4 5 6 7 8 // webpack.common.ts module.exports = { resolve: { alias: { 'react-dom': '@hot-loader/react-dom', }, }, }; 结合前面提到 babel 插件,最终修改 babel.config.js 成: 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 const envPreset = [ '@babel/preset-env', { // 只导入需要的 polyfill useBuiltIns: 'usage', // 指定 corjs 版本 corejs: 3, // 禁用模块化方案转换 modules: false, }, ]; module.exports = function (api) { api.cache(true); return { presets: ['@babel/preset-typescript', envPreset], plugins: ['@babel/plugin-transform-runtime'], env: { // 开发环境配置 development: { presets: [['@babel/preset-react', { development: true }]], plugins: ['react-hot-loader/babel'], }, // 生产环境配置 production: { presets: ['@babel/preset-react'], plugins: ['@babel/plugin-transform-react-constant-elements', '@babel/plugin-transform-react-inline-elements'], }, }, }; }; 注意到我们生产环境下还安装了两个插件进行生产环境的优化: 1 yarn add @babel/plugin-transform-react-constant-elements @babel/plugin-transform-react-inline-elements -D @babel/plugin-transform-react-constant-elements 的作用是像下面样将函数组件中的变量提升到函数外来避免每次重新调用函数组件重复声明和没必要的垃圾回收: 1 2 3 4 5 6 7 8 9 10 11 const Hr = () => { return <hr className="hr" />; }; // 转换成 const _ref = <hr className="hr" />; const Hr = () => { return _ref; }; @babel/plugin-transform-react-inline-elements 的作用读者可以参考 react 的这个 issue:Optimizing Compiler: Inline ReactElements 生产环境优化 添加版权声明 这个直接用 webpack 内置的 BannerPlugin 即可: 1 2 3 4 5 6 7 8 9 10 11 import { BannerPlugin } from 'webpack'; const mergedConfig = merge(commonConfig, { mode: 'production', plugins: [ new BannerPlugin({ raw: true, banner: `/** @preserve Powered by react-typescript-boilerplate (https://github.com/tjx666/react-typescript-boilerplate) */`, }), ], }); copyright 需要注意的是我们在版权声明的注释中加了 @preserve 标记,我们后面会使用 terser 在生产环境构建时压缩代码,压缩代码时会去掉所有注释,除了一些包含特殊标记的注释,例如我们添加的 @preserve CSS 拆分 如果 CSS 是包含在我们打包的 JS bundle 中那会导致最后体积很大,严重情况下访问首页会造成短暂的白屏。拆分 CSS 我们直接使用 mini-css-extract-plugin 1 yarn add mini-css-extract-plugin -D 修改生产环境配置: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 // webpack.prod.ts import MiniCssExtractPlugin from 'mini-css-extract-plugin'; const prodConfig = merge(commonConfig, { mode: 'production', plugins: [ new MiniCssExtractPlugin({ // 文件名中插入文件内容的 hash 值 filename: 'css/[name].[contenthash].css', chunkFilename: 'css/[id].[contenthash].css', ignoreOrder: false, }), ], }); mini-css-extract-plugin 还提供了 mini-css-extract-plugin.loader,它不能和 style-loader 共存,所以我们修改 webpack.common.ts 的配置使得开发环境下使用 style-loader 生产环境下使用 mini-css-extract-plugin.loader 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import { loader as MiniCssExtractLoader } from 'mini-css-extract-plugin'; import { __DEV__ } from '../env'; function getCssLoaders(importLoaders: number) { return [ __DEV__ ? 'style-loader' : MiniCssExtractLoader, { loader: 'css-loader', options: { modules: false, sourceMap: true, importLoaders, }, }, { loader: 'postcss-loader', options: { sourceMap: true }, }, ]; } 代码压缩 JavaScript 压缩 网上很多教程在讲 webpack 压缩代码的时候都是使用 uglifyjs-webpack-plugin,其实这个仓库早就放弃维护了,而且它不支持 ES6 语法,webpack 的核心开发者 evilebottnawi 都转向维护 terser-webpack-plugin 了。我们使用 terser-webpack-plugin 在生产环境对代码进行压缩,并且我们可以利用 webpack4 新增的 tree-shaking 去除代码中的死代码,进一步减小 bundle 体积: 1 yarn add terser-webpack-plugin @types/terser-webpack-plugin -D treeshake 需要在 package.json 中配置 sideEffects 字段,详情可以阅读官方文档:Tree Shaking CSS 压缩 压缩 CSS 使用 optimize-css-assets-webpack-plugin 1 yarn add optimize-css-assets-webpack-plugin @types/optimize-css-assets-webpack-plugin -D 修改 webpack.prod.ts 1 2 3 4 5 6 7 8 9 10 11 12 import TerserPlugin from 'terser-webpack-plugin'; import OptimizeCSSAssetsPlugin from 'optimize-css-assets-webpack-plugin'; const prodConfig = merge(commonConfig, { mode: 'production', optimization: { // 使用 minimizer 而不是默认的 uglifyJS minimize: true, // 两个 minimizer:TerserPlugin 和 OptimizeCSSAssetsPlugin minimizer: [new TerserPlugin({ extractComments: false }), new OptimizeCSSAssetsPlugin()], }, }); 构建分析 我们添加一些 webpack 插件用来进行构建分析 时间统计 speed measure 我们使用 speed-measure-webpack-plugin 对打包时间进行统计: 1 yarn add speed-measure-webpack-plugin -D 项目进行到这,我们终于碰到第一个没有 TypeScript 类型声明文件的库了,新建 scripts/typings/index.d.ts 文件,因为需要编写的类型很少,index.d.ts 就作为一个全局声明文件,在其中添加 speed-measure-webpack-plugin 的外部模块声明: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // scripts/typings/index.d.ts declare module 'speed-measure-webpack-plugin' { import { Configuration, Plugin } from 'webpack'; // 查看官方文档,需要哪些选项就声明哪些选项就行 // 可以看出 TypeScript 是非常灵活的 interface SpeedMeasurePluginOptions { disable: boolean; outputFormat: 'json' | 'human' | 'humanVerbose' | ((outputObj: object) => void); outputTarget: string | ((outputObj: string) => void); pluginNames: object; granularLoaderData: boolean; } // 继承 Plugin 类, Plugin 类都有 apply 方法 class SpeedMeasurePlugin extends Plugin { constructor(options?: Partial<SpeedMeasurePluginOptions>); wrap(webpackConfig: Configuration): Configuration; } export = SpeedMeasurePlugin; } 修改 webpack.prod.ts 1 2 3 4 5 6 7 8 import SpeedMeasurePlugin from 'speed-measure-webpack-plugin'; const mergedConfig = merge(commonConfig, { // ... }); const smp = new SpeedMeasurePlugin(); const prodConfig = smp.wrap(mergedConfig); bundle 分析 bundle analyze 1 yarn add webpack-bundle-analyzer @types/webpack-bundle-analyzer -D 我们添加一个 npm script 用于带 bundle 分析的构建,因为有些时候我们并不想打开一个浏览器去分析各个模块的大小和占比: 1 2 3 4 "scripts": { "build": "cross-env-shell NODE_ENV=production ts-node --files -P scripts/tsconfig.json scripts/build", "build-analyze": "cross-env-shell NODE_ENV=production ts-node --files -P scripts/tsconfig.json scripts/build --analyze", }, 修改 webpack.prod.ts 1 2 3 4 5 6 // 添加 import { isAnalyze } from '../env'; if (isAnalyze) { mergedConfig.plugins!.push(new BundleAnalyzerPlugin()); } 这样当我们想看各个模块在 bundle 中的大小和占比的时候可以运行 npm run build-analyze,将会自动在浏览器中打开上图中的页面。 准备 gzip 压缩版本 我们使用官方维护的 compression-webpack-plugin 来为打包出来的各个文件准备 gzip 压缩版: 1 yarn add compression-webpack-plugin @types/compression-webpack-plugin -D 跟踪 gzip 后的资源大小 trace size size-plugin 是谷歌出品的一个显示 webpack 各个 chunk gzip 压缩后的体积大小以及相比于上一次的大小变化,上图中红框中的部分显示了我加了一句 log 之后 gizip 体积增加了 11B。 1 yarn add size-plugin -D 这个库有没有官方的 types 文件,我们添加 size-plugin 的外部模块声明: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // scripts/typings/index.d.ts declare module 'size-plugin' { import { Plugin } from 'webpack'; interface SizePluginOptions { pattern: string; exclude: string; filename: string; publish: boolean; writeFile: boolean; stripHash: Function; } class SizePlugin extends Plugin { constructor(options?: Partial<SizePluginOptions>); } export = SizePlugin; } 1 2 3 4 5 6 7 // webpack.prod.ts const mergedConfig = merge(commonConfig, { plugins: [ // 不输出文件大小到磁盘 new SizePlugin({ writeFile: false }), ], }); 总结 最近刚学会一个词 TL; DR,其实就是: Too long; didn’t read. 其实我自己也是经常这样,哈哈。到这里已经有 1 万多字了,我估计应该没几个人会看到这。整个流程走下来我觉得是还是非常自然的,从开发环境到生产环境,从基本的配置到优化控制台显示,准备 gzip 压缩版本这些锦上添花的步骤。写这篇文章其实大部分的时间都花费在了查阅资料上,每一个插件我都尽量描述好它们的作用,如果有值得注意的地方我也会在代码注释中或者文字描述中提出来。我知道可能这篇文章对于一些基础比较差或者没怎么手动配置过 webpack 的同学压力比较大,很可能看不下去,这是正常的,我以前也是这样,不过我觉得你如果能够咬咬牙坚持读完,尽管很多地方看不懂,你总是会从中学到一些对你有用的东西,或者你也可以收藏下来当自字典来查。这篇文章很多配置并不是和 react+typescript 强耦合的,你加一个 vue-loader 不就可以正常使用 vue 来开发了吗?更重要的是我希望一些读者可以从中学到探索精神,可怕不代表不可能,实践探索才能掌握真知。 最后我们加上我们的构建脚本 build.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // scripts/build.ts import webpack from 'webpack'; import prodConfig from './configs/webpack.prod'; import { isAnalyze } from './env'; const compiler = webpack(prodConfig); compiler.run((error, stats) => { if (error) { console.error(error); return; } const prodStatsOpts = { preset: 'normal', modules: isAnalyze, colors: true, }; console.log(stats.toString(prodStatsOpts)); }); effect 我最近一直在忙毕业和找工作的事情,下一篇可能要在一个月后左右了。如果读者对文章中有哪些不理解的地方建议先去看下源代码,还有问题的话可以在 github issues 或者发布平台的评论区向我提问,如果觉得本文对你有用,不妨赏颗 star 😁。 下一篇应该会讲述如何集成 ant designlodash 等流行库并对它们的打包进行优化… 本文为原创内容,首发于个人博客,转载请注明出处。 (完)
__label__pos
0.933575
Browse files Fixed #14496 -- Fixed conflict between ModelForm exclude and ModelAdm… …in readonly values. Thanks, Julien Phalip. git-svn-id: http://code.djangoproject.com/svn/django/trunk@16602 bcc190cf-cafb-0310-a4f2-bffc1f526a37 • Loading branch information... 1 parent e912ede commit 3d027b72ebaf3fa41c9f6c17873fe3cee08d9007 @jezdez jezdez committed Aug 12, 2011 Showing with 119 additions and 0 deletions. 1. +8 −0 django/contrib/admin/options.py 2. +18 −0 docs/ref/contrib/admin/index.txt 3. +93 −0 tests/regressiontests/modeladmin/tests.py View 8 django/contrib/admin/options.py @@ -437,6 +437,10 @@ def get_form(self, request, obj=None, **kwargs): else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields(request, obj)) + if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude: + # Take the custom ModelForm's Meta.exclude into account only if the + # ModelAdmin doesn't define its own. + exclude.extend(self.form._meta.exclude) # if exclude is an empty list we pass None to be consistant with the # default on modelform_factory exclude = exclude or None @@ -1343,6 +1347,10 @@ def get_formset(self, request, obj=None, **kwargs): else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields(request, obj)) + if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude: + # Take the custom ModelForm's Meta.exclude into account only if the + # InlineModelAdmin doesn't define its own. + exclude.extend(self.form._meta.exclude) # if exclude is an empty list we use None, since that's the actual # default exclude = exclude or None View 18 docs/ref/contrib/admin/index.txt @@ -313,6 +313,24 @@ subclass:: For an example see the section `Adding custom validation to the admin`_. + .. admonition:: Note + + If your ``ModelForm`` and ``ModelAdmin`` both define an ``exclude`` + option then ``ModelAdmin`` takes precedence:: + + class PersonForm(forms.ModelForm): + + class Meta: + model = Person + exclude = ['name'] + + class PersonAdmin(admin.ModelAdmin): + exclude = ['age'] + form = PersonForm + + In the above example, the "age" field will be excluded but the "name" + field will be included in the generated form. + .. attribute:: ModelAdmin.formfield_overrides This provides a quick-and-dirty way to override some of the View 93 tests/regressiontests/modeladmin/tests.py @@ -120,6 +120,99 @@ class BandAdmin(ModelAdmin): self.assertEqual(ma.get_form(request).base_fields.keys(), ['name']) + def test_custom_form_meta_exclude_with_readonly(self): + """ + Ensure that the custom ModelForm's `Meta.exclude` is respected when + used in conjunction with `ModelAdmin.readonly_fields` and when no + `ModelAdmin.exclude` is defined. + Refs #14496. + """ + # First, with `ModelAdmin` ----------------------- + + class AdminBandForm(forms.ModelForm): + + class Meta: + model = Band + exclude = ['bio'] + + class BandAdmin(ModelAdmin): + readonly_fields = ['name'] + form = AdminBandForm + + ma = BandAdmin(Band, self.site) + self.assertEqual(ma.get_form(request).base_fields.keys(), + ['sign_date',]) + + # Then, with `InlineModelAdmin` ----------------- + + class AdminConcertForm(forms.ModelForm): + + class Meta: + model = Concert + exclude = ['day'] + + class ConcertInline(TabularInline): + readonly_fields = ['transport'] + form = AdminConcertForm + fk_name = 'main_band' + model = Concert + + class BandAdmin(ModelAdmin): + inlines = [ + ConcertInline + ] + + ma = BandAdmin(Band, self.site) + self.assertEqual( + list(ma.get_formsets(request))[0]().forms[0].fields.keys(), + ['main_band', 'opening_band', 'id', 'DELETE',]) + + def test_custom_form_meta_exclude(self): + """ + Ensure that the custom ModelForm's `Meta.exclude` is overridden if + `ModelAdmin.exclude` or `InlineModelAdmin.exclude` are defined. + Refs #14496. + """ + # First, with `ModelAdmin` ----------------------- + + class AdminBandForm(forms.ModelForm): + + class Meta: + model = Band + exclude = ['bio'] + + class BandAdmin(ModelAdmin): + exclude = ['name'] + form = AdminBandForm + + ma = BandAdmin(Band, self.site) + self.assertEqual(ma.get_form(request).base_fields.keys(), + ['bio', 'sign_date',]) + + # Then, with `InlineModelAdmin` ----------------- + + class AdminConcertForm(forms.ModelForm): + + class Meta: + model = Concert + exclude = ['day'] + + class ConcertInline(TabularInline): + exclude = ['transport'] + form = AdminConcertForm + fk_name = 'main_band' + model = Concert + + class BandAdmin(ModelAdmin): + inlines = [ + ConcertInline + ] + + ma = BandAdmin(Band, self.site) + self.assertEqual( + list(ma.get_formsets(request))[0]().forms[0].fields.keys(), + ['main_band', 'opening_band', 'day', 'id', 'DELETE',]) + def test_custom_form_validation(self): # If we specify a form, it should use it allowing custom validation to work # properly. This won't, however, break any of the admin widgets or media. 0 comments on commit 3d027b7 Please sign in to comment.
__label__pos
0.928699
Using FreeImage to fit a PNG file in an image control Thanks Mike. How do I write it back to the control? PROGRAM INCLUDE('gdiplus.inc'), ONCE MAP END Window WINDOW('PNG image in C6'),AT(,,208,120),CENTER,GRAY,SYSTEM IMAGE,AT(9,14,64,59),USE(?IMAGE1) END bm TGdiPlusBitmap sBits &STRING, AUTO CODE OPEN(Window) bm.FromFile('CristmasTree.png') ! bm.FromFile('c:\development\apps\winapi\GdiPlus\examples\Metadata\myphoto.jpg') sBits &= bm.ToString('image/bmp') ?IMAGE1{PROP:ImageBits} = sBits DISPOSE(sBits) ACCEPT END Yes. I got that part to work. Now I need to scale and crop the bm to fit the IMAGE control. Look at .\examples\Using Images\UsingImages.clw, ScaleCropImage procedure. Hi Mike, Yes. That is what I was looking at in terms of code. The problem is that in the example, it is not writing back to an IMAGE control. You are getting the handle of the window and then drawing it manually to the window. I have a lot of controls on the window and the image part resizes. I was hoping that I can manipulate the image and then send it to a Clarion IMAGE control and not have to do everything non-Clarion. This is not true: I’m getting the handle of device context to create TGdiPlusGraphics object. In your case you should create TGdiPlusGraphics object over dest bitmap, draw what you want, then display the result in an image control. Thank Mike. It is the displaying the result in the image control that I don’t get. This I get. sBits &= bm.ToString(‘image/bmp’) ?IMAGE1{PROP:ImageBits} = sBits DISPOSE(sBits) This I don’t get in getting it assigned to the IMAGE control. 1. Load original bitmap: bm1.FromFile(‘image.png’) 2. Create new bitmap: bm2.CreateBitmap(1000, 1000, format) 3. Create Graphics object over bitmap2: g.FromImage(bm2) 4. Draw 1 on 2: g.DrawImage(bm1, 0, 0, 1000, 1000) Rename all your bm, bm1, bm2 etc into bmSrc and bmDst. Then: • load source image bmSrc • create destination image bmDst with desired size • create Graphics object g over bmDst • draw a part of source image on an area of dest image • display image bits of resulted dest image I understand the concept of what you are saying, the problem in the example of .\examples\Using Images\UsingImages.clw, ScaleCropImage procedure, there is no writing back to a defined IMAGE for a WINDOW. If I have Window WINDOW('Part Groups'),AT(,,397,224),FONT('Segoe UI',9),RESIZE,CENTER,ICON('module.ico'),GRAY,IMM,MAX LIST,AT(4,4,194,218),USE(?TreeList),FORMAT('1020L(2)|MIT@s255@'),FROM(TV1::Queue),#FIELDS(m_Display),#ORDINAL(1) IMAGE,AT(202,4,191,204),USE(?Diagram_Image),CENTERED,#ORDINAL(3) BUTTON('Close'),AT(357,211,36,12),USE(?CloseButton),FONT('Segoe UI',9,,FONT:regular),#ORIG(?Close),#SEQ(1),#ORDINAL(2) END I can bm1.FromFile(PGP:DIAGRAM_IMAGE) sBits &= bm1.ToString('image/bmp') ?Diagram_Image{PROP:ImageBits} = sBits DISPOSE(sBits) but how do I go about setting the ?Diagram_Image to the new graphics object. ?Diagram_Image{PROP:ImageBits} = ??? Here you display bm1 image. To display bm2 image, do the same: sBits &= bm2.ToString(‘image/bmp’) ?Diagram_Image{PROP:ImageBits} = sBits DISPOSE(sBits) Mike, Thanks for your help. bmSrc.FromFile(PGP:DIAGRAM_IMAGE) DO GetImageInformation bmDest.CreateBitmap(ImagePixelWidth, ImagePixelHeight, PixelFormat24bppRGB) g.FromImage(bmDest) g.DrawImage(bmSrc, ImagePixelXOffset,ImagePixelYOffset,ImagePixelWidth - ImagePixelXDiff,ImagePixelHeight - ImagePixelYDiff) sBits &= bmDest.ToString('image/bmp') ?Diagram_Image{PROP:ImageBits} = sBits DISPOSE(sBits) When using bmDest.CreateBitmap(ImagePixelWidth, ImagePixelHeight, PixelFormat24bppRGB) is there anyway to set the bitmap to transparent or a specific colour? Well, you can draw a rectangle using a solid brush of argb color. I switched to a PixelFormat32bppRGB from PixelFormat24bppRGB which should have gotten the Alpha channel, but it doesn’t work when I use GdipMakeARGB(0, 255, 255, 255). And I used g.GraphicsClear(GdipMakeARGB(255, 255, 255, 255)) Is there something in the code that is preventing the Alpha channel from being used for transparency? bmSrc.FromFile(PGP:DIAGRAM_IMAGE) DO GetImageInformation bmDest.CreateBitmap(ImagePixelWidth, ImagePixelHeight, PixelFormat32bppRGB) g.FromImage(bmDest) !brush.CreateSolidBrush(GdipMakeARGB(255, 255, 255, 255)) !g.FillRectangle(brush,0,0,ImagePixelWidth,ImagePixelHeight) g.GraphicsClear(GdipMakeARGB(255, 255, 255, 255)) g.DrawImage(bmSrc, ImagePixelXOffset,ImagePixelYOffset,ImagePixelWidth - ImagePixelXDiff,ImagePixelHeight - ImagePixelYDiff) sBits &= bmDest.ToString('image/bmp') ?Diagram_Image{PROP:ImageBits} = sBits DISPOSE(sBits) I know nothing about what you’re doing, but don’t you want to use the ARGB rendition of this? The place on the web page about PixelFormat32bppRGB, specifies that those 8 bits, normally used for alpha, are not used. Thanks Jeff. I missed that. bmDest.CreateBitmap(ImagePixelWidth, ImagePixelHeight, PixelFormat32bppARGB) g.FromImage(bmDest) g.GraphicsClear(GdipMakeARGB(0, 255, 255, 255)) Still makes a black background. g.FromImage(bmDest) g.GraphicsClear(GdipMakeARGB(1, 255, 255, 255)) This works. I just added Show method to display an image in IMAGE control: bm.Show(?Image1) 1 Like I couldn’t find any equates for g.Clear(Color.Transparent); Does anyone know if GDI+ supports AVIF? Does not support it.
__label__pos
0.871696
Source: Midjourney The generative AI boom is compute-bound. It has the unique property that adding more compute directly results in a better product. Usually, R&D investment is more directly tied to how valuable a product was, and that relationship is markedly sublinear. But this is not currently so with artificial intelligence and, as a result, a predominant factor driving the industry today is simply the cost of training and inference.  While we don’t know the true numbers, we’ve heard from reputable sources that the supply of compute is so constrained, demand outstrips it by a factor of 10(!) So we think it’s fair to say that, right now, access to compute resources—at the lowest total cost—has become a determining factor for the success of AI companies. In fact, we’ve seen many companies spend more than 80% of their total capital raised on compute resources! In this post, we try to break down the cost factors for an AI company. The absolute numbers will of course change over time, but we don’t see immediate relief from AI companies being bound by their access to compute resources. So, hopefully, this is a helpful framework for thinking through the landscape.  Why are AI models so computationally expensive? There is a wide variety of generative AI models, and inference and training costs depend on the size and type of the model. Fortunately, the most popular models today are mostly transformer-based architectures, which include popular large language models (LLMs) such as GPT-3, GPT-J, or BERT. While the exact number of operations for inference and learning of transformers is model-specific (see this paper), there is a fairly accurate rule of thumb that depends only on the number of parameters (i.e., the weights of the neural networks) of the model and the number of input and output tokens.  Tokens are essentially short sequences of a few characters. They correspond to words or parts of words. The best way to get an intuition for tokens is to try out tokenization with publicly available online tokenizers (e.g., OpenAI). For GPT-3, the average length of a token is 4 characters The rule of thumb for transformers is that a forward pass (i.e., inference) for a model with p parameters for an input and an output sequence of length n tokens each, takes approximately 2*n*p floating point operations (FLOPs)¹. Training for the same model takes approximately 6*p FLOPs per token (i.e., the additional backward pass requires four more operations²). You can approximate total training cost by multiplying this by the amount of tokens in the training data. Memory requirements for transformers also depend on model size. For inference, we need the p model parameters to fit into memory. For learning (i.e., back-propagation), we need to store additional intermediate values per parameter between the forward and backward pass. Assuming we use 32-bit floating point numbers, this is an additional 8 bytes per parameter. For training a 175-billion-parameter model, we would need to keep over a terabyte of data in memory — this exceeds any GPU in existence today and requires us to split the model up across cards. Memory requirements for inference and training can be optimized by using floating point values of shorter lengths, with 16-bit becoming common and 8-bit anticipated in the near future. The table above has sizes and compute costs for several popular models. GPT-3 has approximately 175 billion parameters, which for an input and output of 1,024 tokens, results in a computational cost of approximately 350 trillion floating point operations (i.e., Teraflops or TFLOPs). Training a model like GPT-3 takes about 3.14*10^23 floating point operations. Other models like Meta’s LLaMA have even higher compute requirements. Training such a model is one of the more computationally intensive tasks mankind has undertaken so far.  To summarize: AI infrastructure is expensive because the underlying algorithmic problems are extremely computationally hard. The algorithmic complexity of sorting a database table with a million entries is insignificant compared with the complexity of generating a single word with GPT-3. This means you want to pick the smallest model that solves your use case.  The good news is that, for transformers, we can easily estimate how much compute and memory a model of a certain size will consume. And, so, picking the right hardware becomes the next consideration.  The time and cost argument for GPUs How does computational complexity translate to time? A processor core can typically execute 1-2 instructions per cycle, and processor clock rates have been stable around 3 GHz for the past 15 years due to the end of Dennard Scaling. Executing a single GPT-3 inference operation without exploiting any parallel architecture would take on the order of 350 TFLOPs/(3 GHz*1 FLOP) or 116,000 seconds, or 32 hours. This is wildly impractical; instead we need specialized chips that accelerate this task. In practice, all AI models today run on cards that use a very large number of specialized cores. For example, an NVIDIA A100 GPU has 512 “tensor cores” that can perform a 4×4 matrix multiplication (which is equivalent to 64 multiplications and additions, or 128 FLOPs) in a single cycle. AI accelerator cards are often referred to as GPUs (graphics processing units), as the architecture was originally developed for desktop gaming. In the future we expect AI to increasingly become a distinct product family.  The A100 has a nominal performance of 312 TFLOPS which in theory would reduce the inference for GPT-3 to about 1 second. However this is an oversimplified calculation for several reasons. First, for most use cases, the bottleneck is not the compute power of the GPU but the ability to get data from the specialized graphics memory to the tensor cores. Second, the 175 billion weights would take up 700GB and won’t fit into the graphics memory of any GPU. Techniques such as partitioning and weight streaming need to be used. And, third, there are a number of optimizations (e.g., using shorter floating point representations, such as FP16, FP8, or sparse matrices) that are being used to accelerate computation. But, overall, the above math gives us an intuition of the overall computation cost of today’s LLMs. Training a transformer model takes about three times as long per token as doing inference. However, given that the training data set is about 300 million times larger than an inference prompt, training takes longer by a factor of 1 billion. On a single GPU, training would take decades; in practice this is done on large compute clusters in dedicated data centers or, more likely, in the cloud. Training is also harder to parallelize than inference, as updated weights have to be exchanged between nodes. Memory and bandwidth between GPUs often becomes a far more important factor, with high-speed interconnects and dedicated fabrics being common. For training very large models, creating a suitable network setup can be the primary challenge. Looking into the future, AI accelerators will have networking capabilities on the card or even on the chip.  How does this computational complexity translate to cost? A GPT-3 inference, which, as we saw above, takes approximately 1 second on an A100 would have a raw compute cost between $0.0002 and $0.0014 for 1,000 tokens (this compares to OpenAI’s pricing of $0.002/1000 tokens). A user generating 100 inference requests a day would cost in the order of dollars per year. This is a very low price point and makes most use cases of text-based AI by humans financially viable. Training GPT-3, on the other hand, is much more expensive. Again calculating only the compute cost for 3.14*10^23 FLOPs at the above rates gives us an estimate of $560,000 on A100 cards for a single training run. In practice, for training we will not get nearly 100% efficiency in the GPU; however we can also use optimizations to reduce the training time. Other estimates of GPT-3 training cost range from $500,000 to $4.6 million, depending on hardware assumptions. Note that this is the cost of a single run and not overall cost. Multiple runs will likely be required and cloud providers will want long-term commitments (more on this below). Training top-of-the-line models remains expensive, but within reach of a well-funded start-up. To summarize, generative AI requires massive investments in AI infrastructure today. There is no reason to believe that this will change in the near future. Training a model like GPT-3 is one of the most computationally intensive tasks mankind has ever undertaken. And while GPUs are getting faster, and we find ways to optimize training, the rapid expansion of AI negates both of these effects. Considerations for AI infrastructure To this point, we’ve tried to give you some intuition for the scale required to do training and inference of AI models, and what underlying parameters drive them. With that context, we now want to provide some practical guidance on how to decide which AI infrastructure to use. External vs. in-house infrastructure Let’s face it: GPUs are cool. Many engineers and engineering-minded founders have a bias toward provisioning their own AI hardware, not only because it gives fine-grained control over model training, but because there’s just something fun about harnessing large amounts of computing power (exhibit A). The reality, however, is that many startups—especially app companies—don’t need to build their own AI infrastructure on Day 1. Instead, hosted model services like OpenAI or Hugging Face (for language) and Replicate (for image generation) allow founders to search rapidly for product-market fit without the need to manage the underlying infrastructure or models. These services have gotten so good that many companies never graduate from them. Developers can achieve meaningful control over model performance through prompt engineering and higher-order fine-tuning abstractions (i.e., fine tuning through API calls). Pricing for these services is consumption-based, so it’s also often cheaper than running separate infrastructure. We’ve seen app companies generating more than $50 million of ARR, and valued over $1 billion, that run hosted model services under the hood. On the flip side, some startups—especially those training new foundation models or building vertically integrated AI applications—can’t avoid running their own models directly on GPUs. Either because the model is effectively the product and the team is searching for “model-market fit,” or because fine-grained control over training and/or inference is required to achieve certain capabilities or reduce marginal cost at large scale. Either way, managing the infrastructure can become a source of competitive advantage. The cloud vs. data center build out In most cases, the cloud is the right place for your AI infrastructure. Less up-front cost, the ability to scale up and down, regional availability, and less distraction from building your own data center are compelling for most startups and larger companies. But there are a few exceptions to this rule: • If you are operating at a very large scale, it may become more cost effective to run your own data center. The exact price point varies based on geographic location and setup, but it typically requires infrastructure spend of more than $50 million per year. • You need very specific hardware that you can’t obtain from a cloud provider. For example, GPU types that are not widely available, as well as unusual memory, storage, or networking requirements. • You cannot find a cloud that is acceptable for geopolitical considerations. If you do want to build your own data center, there have been comprehensive price/performance analysis of GPUs for your own setup (e.g., Tim Dettmer’s analysis). In addition to the cost and performance of the card itself, hardware selection also depends on power, space, and cooling. For example, two RTX 3080 Ti cards together have similar raw compute capacity to an A100, but respective power consumption is 700W vs. 300W. The 3,500 kWh power difference at market rates of $0.10/kWh over a three-year life cycle increases the cost of the RTX3080 Ti by nearly 2x (approximately $1,000). All of this said, we expect the vast majority of startups to use cloud computing.  Comparing the cloud service providers Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP) all offer GPU instances, but new providers are also appearing to focus on AI workloads specifically. Here’s a framework we’ve seen many founders use to choose a cloud provider: Price: The table below shows pricing for a number of major and smaller specialty clouds as of April 7, 2023. This data is only indicative, as the instances vary considerably in terms of network bandwidth, data egress costs, additional cost from CPU and network, available discounts, and other factors. For example, Google requires an A2 accelerated-optimized instance for an A100 40GB, which can increase cost by 25%. Compute capacity on specific hardware is a commodity. Naively, we would expect fairly uniform prices, but this is not the case. And while substantial feature differences between the clouds exist, they are insufficient to explain that the pricing for an on-demand NVIDIA A100 varies by a factor of almost 4x among providers. At the top end of the price scale, the big public clouds charge a premium based on brand reputation, proven reliability, and the need to manage a wide range of workloads. Smaller specialty AI providers offer lower prices, either by running purpose-built data centers (e.g., Coreweave) or arbitraging other clouds (e.g., Lambda Labs). Practically speaking, most larger buyers negotiate prices directly with the cloud providers, often committing to some minimum spending requirement as well as minimum time commitments (we have seen 1-3 years). The price differences between clouds shrink somewhat after negotiation, but we’ve seen the ranking in the table above remain relatively stable. It’s also important to note that smaller companies can get aggressive pricing from speciality clouds without large spending commitments. Availability: The most powerful GPUs (e.g., Nvidia A100s) have been consistently in short supply for the past 12-plus months.  It would be logical to think the top three cloud providers have the best availability, given their large purchasing power and pool of resources. But, somewhat surprisingly, many startups haven’t found that to be true. The big clouds have a lot of hardware but also have big customer needs to satisfy—e.g., Azure is the primary host for ChatGPT—and are constantly adding/leasing capacity to meet demand. Meanwhile, Nvidia has committed to making hardware available broadly across the industry, including allocations for new specialty providers. (They do this both to be fair and to reduce their dependence on a few large customers who also compete with them.) As a result, many startups find more available chips, including the cutting-edge Nvidia H100s, at smaller cloud providers. If you’re willing to work with a newer infrastructure company, you may be able to reduce wait times for hardware and possibly save money in the process. Compute delivery model: The large clouds today only offer instances with dedicated GPUs, the reason being that GPU virtualization is still an unsolved problem. Specialized AI clouds offer other models, such as containers or batch jobs, that can handle individual tasks without incurring the start-up and tear-down cost of an instance. If you are comfortable with this model, it can substantially reduce cost. Network interconnects: For training, specifically, network bandwidth is a major factor in provider selection. Clusters with dedicated fabrics between nodes, such as NVLink, are needed to train certain large models. For image generation, egress traffic fees can also be a major cost driver. Customer support: Large cloud providers serve a huge pool of customers across thousands of product SKUs. It can be hard to get the attention of customer support, or get a problem fixed, unless you’re a big customer. Many specialized AI clouds, on the other hand, offer fast and responsive support even for small customers. This is partly because they are operating at a smaller scale, but also because their workloads are more homogenous—so they are more incentivized to focus on AI-specific features and bugs. Comparing GPUs All else being equal, the top-end GPUs will perform best on nearly all workloads. However, as you can see in the table below, the best hardware is also substantially more expensive. Picking the right type of GPU for your specific application can substantially reduce cost and may make the difference between a viable and nonviable business model. Deciding how far down the list to go—that is, determining the most cost-effective GPU choices for your application—is largely a technical decision that is beyond the scope of this article. But we’ll share below some of the selection criteria we’ve seen are most important: Training vs. inference: As we saw in the first section above, training a Transformer model requires us to store 8 bytes of data for training in addition to the model weights. This means a typical high-end consumer GPU with 12GB of memory could barely be used to train a 4-billion-parameter model. In practice, training large models is done on clusters of machines with preferably many GPUs per server, lots of VRAM, and high bandwidth connections between the servers (i.e., clusters built using top-end data center GPUs). Specifically, many models will be most cost effective on the NVIDIA H100, but as of today it is hard to find and usually requires a long-term commitment of more than a year. The NVIDIA A100 runs most model-training today; it’s easier to find but, for large clusters, may also require a long-term commitment. Memory requirements: Large LLMs have parameter counts that are too high to fit in any card. They need to be split across multiple cards and require a setup similar to training. In other words, you probably need H100s or A100s even for LLM inference. But smaller models (e.g., Stable Diffusion) require much less VRAM. While the A100 is still popular, we have seen startups use the A10, A40, A4000, A5000 and A6000, or even RTX cards.  Hardware support: While the vast majority of workloads in companies that we have talked to run on NVIDIA, a few have started experimenting with other vendors. Most common is the Google TPU, but Intel’s Gaudi 2 appears to be getting some traction, as well. The challenge with these vendors is that performance of your model is often highly dependent on the availability of software optimizations for these chips. You will likely have to do a PoC in order to understand performance. Latency requirements: In general, less latency sensitive workloads (e.g., batch data processing or applications that don’t require interactive UI responses) can use less-powerful GPUs. This can reduce compute cost by as much as 3-4x (e.g., comparing A100s to A10s on AWS). User-facing apps, on the other hand, often need top-end cards to deliver an engaging, real-time user experience. Optimizing models is often necessary to bring costs to a manageable range. Spikiness: Generative AI companies often see dramatic spikes in demand since the technology is so new and exciting. It’s not unusual to see request volumes increase by 10x in a day, based on a new product release, or grow 50% per week consistently. Handling these spikes is often easier on lower-end GPUs, since more compute nodes are likely available on demand. It often makes sense, too, to serve this kind of traffic with lower-cost resources—at the expense of performance—if it comes from less engaged or less retentive users. Optimizing and scheduling models Software optimizations can hugely affect the running time of models—and 10x gains are not uncommon. However, you’ll need to determine which methods will be most effective with your particular model and system. Some techniques work with a fairly broad range of models. Using shorter floating point representations (i.e., FP16 or FP8 vs. the original FP32) or quantization (INT8, INT4, INT2) achieve a speedup that is often linear with the reduction of bits. This sometimes requires modifying the model, but there are, increasingly, technologies available that automate working with mixed or shorter precision. Pruning neural networks reduces the number of weights by ignoring weights with low values. Together with efficient sparse matrix multiplication, this can achieve a substantial speedup on modern GPUs. Another set of optimization techniques addresses the memory bandwidth bottleneck (e.g., by streaming model weights). Other optimizations are highly model-specific. For example, Stable Diffusion has made major advances in the amount of VRAM required for inference. Yet another class of optimizations is hardware-specific. NVIDIA’s TensorRT includes a number of optimizations, but will only work on NVIDIA hardware. Last, but not least, scheduling of AI tasks can create huge performance bottlenecks or improvements. Allocating models to GPUs in a way to minimize swapping of weights, picking the best GPU for a task if multiple ones are available, and minimizing downtime by batching workloads in advance are common techniques. In the end, model optimization is still a bit of a black art, and the majority of startups that we talk to work with third parties to help with some of these software aspects. Often, these are not traditional MLops vendors, but instead are companies that specialize in optimizations for specific generative models (e.g., OctoML or SegMind). How will AI infrastructure cost evolve? Over the last few years, we have seen exponential growth of both model parameters and GPU compute power. It is unclear if this trend will continue. Today, it is widely accepted that there is a relationship between optimal number of parameters and the size of the training data set (see Deepmind’s Chinchilla work for more on this). The best LLMs today are trained on the Common Crawl (a collection of 4.5 billion web pages, or about 10% of all web pages in existence). The training corpus also includes Wikipedia and a collection of books, although both are much smaller (the total number of books in existence is estimated to be only around 100 million). Other ideas, such as transcribing video or audio content, have been suggested, but none of these come close in size. It is not clear if we could obtain a non-synthetic training dataset that is 10x larger than what has already been used. GPU performance will continue to increase, but also at a slower rate. Moore’s Law is still intact allowing for more transistors and more cores, but power and I/O are becoming limiting factors. Additionally, many of the low-hanging fruit for optimizations have been picked.  However, none of this means we don’t expect an increase in demand for compute capacity. Even if model and training set growth slows, the growth of the AI industry and increase in the number of AI developers will fuel a demand for more and faster GPUs. A large fraction of GPU capacity is used for testing by developers during the development phase of a model, and this demand scales linearly with headcount. There is no sign that the GPU shortage we have today will abate in the near future. Will this continued high cost of AI infrastructure create a moat that makes it impossible for new entrants to catch up with well-funded incumbents? We don’t know the answer to this question yet. The training cost of an LLM may look like a moat today, but open source models such as Alpaca or Stable Diffusion have shown that these markets are still early and may change quickly. Over time, the cost structure of the emerging AI software stack (see our previous post) may start looking more like the traditional software industry.  Ultimately, this would be a good thing: History has shown that this leads to vibrant ecosystems with rapid innovation and lots of opportunities for entrepreneurial founders. Thanks to Moin Nadeem and Shangda Xu for their input and guidance during the writing process. ¹ The intuition here is that for any parameter (i.e. weight) in a neural network, an inference operation (i.e. forward pass) needs to perform two floating point operations per parameter. First, it multiplies the value of the input node of the neural network with the parameter. Second, it adds the result of the summation to the output node of the neural network. The parameters in the encoder are used once per input token and the parameters in the decoder are used once per output token. If we assume a model has p parameters and input and output both have a length n tokens, total floating point operations are n * p. There are many other operations (e.g. normalization, encoding/decoding the embedding) that happen in a model, but the time it takes to perform them is small in comparison.  ² Learning first requires a forward pass through the transformer as described above, followed by a backward pass that incurs four additional operations per parameter to calculate the gradient and adjust the weight. Note that calculating the gradient requires preserving the calculated node values from the forward pass. For GPT-3, Language Models are Few-Shot Learners discusses training cost. * * * The views expressed here are those of the individual AH Capital Management, L.L.C. (“a16z”) personnel quoted and are not the views of a16z or its affiliates. Certain information contained in here has been obtained from third-party sources, including from portfolio companies of funds managed by a16z. While taken from sources believed to be reliable, a16z has not independently verified such information and makes no representations about the enduring accuracy of the information or its appropriateness for a given situation. In addition, this content may include third-party advertisements; a16z has not reviewed such advertisements and does not endorse any advertising content contained therein. This content is provided for informational purposes only, and should not be relied upon as legal, business, investment, or tax advice. You should consult your own advisers as to those matters. References to any securities or digital assets are for illustrative purposes only, and do not constitute an investment recommendation or offer to provide investment advisory services. Furthermore, this content is not directed at nor intended for use by any investors or prospective investors, and may not under any circumstances be relied upon when making a decision to invest in any fund managed by a16z. (An offering to invest in an a16z fund will be made only by the private placement memorandum, subscription agreement, and other relevant documentation of any such fund and should be read in their entirety.) Any investments or portfolio companies mentioned, referred to, or described are not representative of all investments in vehicles managed by a16z, and there can be no assurance that the investments will be profitable or that other investments made in the future will have similar characteristics or results. A list of investments made by funds managed by Andreessen Horowitz (excluding investments for which the issuer has not provided permission for a16z to disclose publicly as well as unannounced investments in publicly traded digital assets) is available at https://a16z.com/investments/. Charts and graphs provided within are for informational purposes solely and should not be relied upon when making any investment decision. Past performance is not indicative of future results. The content speaks only as of the date indicated. Any projections, estimates, forecasts, targets, prospects, and/or opinions expressed in these materials are subject to change without notice and may differ or be contrary to opinions expressed by others. Please see https://a16z.com/disclosures for additional important information. Stay up to date on the latest from a16z Infra team Sign up for our a16z newsletter to get analysis and news covering the latest trends reshaping AI and infrastructure. Thanks for signing up. Check your inbox for a welcome note. MANAGE MY SUBSCRIPTIONS By clicking the Subscribe button, you agree to the Privacy Policy.
__label__pos
0.520101
0342. Power of Four 342. Power of Four # 题目 # Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example 1: Input: 16 Output: true Example 2: Input: 5 Output: false Follow up: Could you solve it without loops/recursion? 题目大意 # 给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。 解题思路 # • 判断一个数是不是 4 的 n 次方。 • 这一题最简单的思路是循环,可以通过。但是题目要求不循环就要判断,这就需要用到数论的知识了。 • 证明 (4^n - 1) % 3 == 0,(1) 4^n - 1 = (2^n + 1) * (2^n - 1)(2) 在任何连续的 3 个数中 (2^n-1)(2^n)(2^n+1),一定有一个数是 3 的倍数。(2^n) 肯定不是 3 的倍数,那么 (2^n-1) 或者 (2^n+1) 中一定有一个是 3 的倍数。所以 4^n-1 一定是 3 的倍数。 代码 # package leetcode // 解法一 数论 func isPowerOfFour(num int) bool { return num > 0 && (num&(num-1)) == 0 && (num-1)%3 == 0 } // 解法二 循环 func isPowerOfFour1(num int) bool { for num >= 4 { if num%4 == 0 { num = num / 4 } else { return false } } return num == 1 } ⬅️上一页 下一页➡️ Calendar Sep 11, 2022 Edit Edit this page 本站总访问量:  次 您是本站第  位访问者
__label__pos
0.999413
eM Client on two computers one e Mail account Can the same license be use on two different computers for the same e-mail account. If so how is it done? There are already many replies in thus. . You have to register each computer with a different email address but once registered you can put the same email acc on both.
__label__pos
0.999944
blob: 6591d27e53a43413656a18a6eedb25d7bb5fe034 [file] [log] [blame] /* Copyright 2011, Siemens AG * written by Alexander Smirnov <[email protected]> */ /* Based on patches from Jon Smirl <[email protected]> * Copyright (c) 2011 Jon Smirl <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ /* Jon's code is based on 6lowpan implementation for Contiki which is: * Copyright (c) 2008, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE 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 INSTITUTE 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. */ #include <linux/bitops.h> #include <linux/if_arp.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/netdevice.h> #include <net/af_ieee802154.h> #include <net/ieee802154.h> #include <net/ieee802154_netdev.h> #include <net/6lowpan.h> #include <net/ipv6.h> #include "reassembly.h" static LIST_HEAD(lowpan_devices); /* private device info */ struct lowpan_dev_info { struct net_device *real_dev; /* real WPAN device ptr */ struct mutex dev_list_mtx; /* mutex for list ops */ __be16 fragment_tag; }; struct lowpan_dev_record { struct net_device *ldev; struct list_head list; }; static inline struct lowpan_dev_info *lowpan_dev_info(const struct net_device *dev) { return netdev_priv(dev); } static inline void lowpan_address_flip(u8 *src, u8 *dest) { int i; for (i = 0; i < IEEE802154_ADDR_LEN; i++) (dest)[IEEE802154_ADDR_LEN - i - 1] = (src)[i]; } static int lowpan_header_create(struct sk_buff *skb, struct net_device *dev, unsigned short type, const void *_daddr, const void *_saddr, unsigned int len) { const u8 *saddr = _saddr; const u8 *daddr = _daddr; struct ieee802154_addr sa, da; struct ieee802154_mac_cb *cb = mac_cb_init(skb); /* TODO: * if this package isn't ipv6 one, where should it be routed? */ if (type != ETH_P_IPV6) return 0; if (!saddr) saddr = dev->dev_addr; raw_dump_inline(__func__, "saddr", (unsigned char *)saddr, 8); raw_dump_inline(__func__, "daddr", (unsigned char *)daddr, 8); lowpan_header_compress(skb, dev, type, daddr, saddr, len); /* NOTE1: I'm still unsure about the fact that compression and WPAN * header are created here and not later in the xmit. So wait for * an opinion of net maintainers. */ /* NOTE2: to be absolutely correct, we must derive PANid information * from MAC subif of the 'dev' and 'real_dev' network devices, but * this isn't implemented in mainline yet, so currently we assign 0xff */ cb->type = IEEE802154_FC_TYPE_DATA; /* prepare wpan address data */ sa.mode = IEEE802154_ADDR_LONG; sa.pan_id = ieee802154_mlme_ops(dev)->get_pan_id(dev); sa.extended_addr = ieee802154_devaddr_from_raw(saddr); /* intra-PAN communications */ da.pan_id = sa.pan_id; /* if the destination address is the broadcast address, use the * corresponding short address */ if (lowpan_is_addr_broadcast(daddr)) { da.mode = IEEE802154_ADDR_SHORT; da.short_addr = cpu_to_le16(IEEE802154_ADDR_BROADCAST); } else { da.mode = IEEE802154_ADDR_LONG; da.extended_addr = ieee802154_devaddr_from_raw(daddr); } cb->ackreq = !lowpan_is_addr_broadcast(daddr); return dev_hard_header(skb, lowpan_dev_info(dev)->real_dev, type, (void *)&da, (void *)&sa, 0); } static int lowpan_give_skb_to_devices(struct sk_buff *skb, struct net_device *dev) { struct lowpan_dev_record *entry; struct sk_buff *skb_cp; int stat = NET_RX_SUCCESS; rcu_read_lock(); list_for_each_entry_rcu(entry, &lowpan_devices, list) if (lowpan_dev_info(entry->ldev)->real_dev == skb->dev) { skb_cp = skb_copy(skb, GFP_ATOMIC); if (!skb_cp) { stat = -ENOMEM; break; } skb_cp->dev = entry->ldev; stat = netif_rx(skb_cp); } rcu_read_unlock(); return stat; } static int process_data(struct sk_buff *skb, const struct ieee802154_hdr *hdr) { u8 iphc0, iphc1; struct ieee802154_addr_sa sa, da; void *sap, *dap; raw_dump_table(__func__, "raw skb data dump", skb->data, skb->len); /* at least two bytes will be used for the encoding */ if (skb->len < 2) goto drop; if (lowpan_fetch_skb_u8(skb, &iphc0)) goto drop; if (lowpan_fetch_skb_u8(skb, &iphc1)) goto drop; ieee802154_addr_to_sa(&sa, &hdr->source); ieee802154_addr_to_sa(&da, &hdr->dest); if (sa.addr_type == IEEE802154_ADDR_SHORT) sap = &sa.short_addr; else sap = &sa.hwaddr; if (da.addr_type == IEEE802154_ADDR_SHORT) dap = &da.short_addr; else dap = &da.hwaddr; return lowpan_process_data(skb, skb->dev, sap, sa.addr_type, IEEE802154_ADDR_LEN, dap, da.addr_type, IEEE802154_ADDR_LEN, iphc0, iphc1, lowpan_give_skb_to_devices); drop: kfree_skb(skb); return -EINVAL; } static int lowpan_set_address(struct net_device *dev, void *p) { struct sockaddr *sa = p; if (netif_running(dev)) return -EBUSY; /* TODO: validate addr */ memcpy(dev->dev_addr, sa->sa_data, dev->addr_len); return 0; } static struct sk_buff* lowpan_alloc_frag(struct sk_buff *skb, int size, const struct ieee802154_hdr *master_hdr) { struct net_device *real_dev = lowpan_dev_info(skb->dev)->real_dev; struct sk_buff *frag; int rc; frag = alloc_skb(real_dev->hard_header_len + real_dev->needed_tailroom + size, GFP_ATOMIC); if (likely(frag)) { frag->dev = real_dev; frag->priority = skb->priority; skb_reserve(frag, real_dev->hard_header_len); skb_reset_network_header(frag); *mac_cb(frag) = *mac_cb(skb); rc = dev_hard_header(frag, real_dev, 0, &master_hdr->dest, &master_hdr->source, size); if (rc < 0) { kfree_skb(frag); return ERR_PTR(-rc); } } else { frag = ERR_PTR(-ENOMEM); } return frag; } static int lowpan_xmit_fragment(struct sk_buff *skb, const struct ieee802154_hdr *wpan_hdr, u8 *frag_hdr, int frag_hdrlen, int offset, int len) { struct sk_buff *frag; raw_dump_inline(__func__, " fragment header", frag_hdr, frag_hdrlen); frag = lowpan_alloc_frag(skb, frag_hdrlen + len, wpan_hdr); if (IS_ERR(frag)) return -PTR_ERR(frag); memcpy(skb_put(frag, frag_hdrlen), frag_hdr, frag_hdrlen); memcpy(skb_put(frag, len), skb_network_header(skb) + offset, len); raw_dump_table(__func__, " fragment dump", frag->data, frag->len); return dev_queue_xmit(frag); } static int lowpan_xmit_fragmented(struct sk_buff *skb, struct net_device *dev, const struct ieee802154_hdr *wpan_hdr) { u16 dgram_size, dgram_offset; __be16 frag_tag; u8 frag_hdr[5]; int frag_cap, frag_len, payload_cap, rc; int skb_unprocessed, skb_offset; dgram_size = lowpan_uncompress_size(skb, &dgram_offset) - skb->mac_len; frag_tag = lowpan_dev_info(dev)->fragment_tag++; frag_hdr[0] = LOWPAN_DISPATCH_FRAG1 | ((dgram_size >> 8) & 0x07); frag_hdr[1] = dgram_size & 0xff; memcpy(frag_hdr + 2, &frag_tag, sizeof(frag_tag)); payload_cap = ieee802154_max_payload(wpan_hdr); frag_len = round_down(payload_cap - LOWPAN_FRAG1_HEAD_SIZE - skb_network_header_len(skb), 8); skb_offset = skb_network_header_len(skb); skb_unprocessed = skb->len - skb->mac_len - skb_offset; rc = lowpan_xmit_fragment(skb, wpan_hdr, frag_hdr, LOWPAN_FRAG1_HEAD_SIZE, 0, frag_len + skb_network_header_len(skb)); if (rc) { pr_debug("%s unable to send FRAG1 packet (tag: %d)", __func__, frag_tag); goto err; } frag_hdr[0] &= ~LOWPAN_DISPATCH_FRAG1; frag_hdr[0] |= LOWPAN_DISPATCH_FRAGN; frag_cap = round_down(payload_cap - LOWPAN_FRAGN_HEAD_SIZE, 8); do { dgram_offset += frag_len; skb_offset += frag_len; skb_unprocessed -= frag_len; frag_len = min(frag_cap, skb_unprocessed); frag_hdr[4] = dgram_offset >> 3; rc = lowpan_xmit_fragment(skb, wpan_hdr, frag_hdr, LOWPAN_FRAGN_HEAD_SIZE, skb_offset, frag_len); if (rc) { pr_debug("%s unable to send a FRAGN packet. (tag: %d, offset: %d)\n", __func__, frag_tag, skb_offset); goto err; } } while (skb_unprocessed > frag_cap); consume_skb(skb); return NET_XMIT_SUCCESS; err: kfree_skb(skb); return rc; } static netdev_tx_t lowpan_xmit(struct sk_buff *skb, struct net_device *dev) { struct ieee802154_hdr wpan_hdr; int max_single; pr_debug("package xmit\n"); if (ieee802154_hdr_peek(skb, &wpan_hdr) < 0) { kfree_skb(skb); return NET_XMIT_DROP; } max_single = ieee802154_max_payload(&wpan_hdr); if (skb_tail_pointer(skb) - skb_network_header(skb) <= max_single) { skb->dev = lowpan_dev_info(dev)->real_dev; return dev_queue_xmit(skb); } else { netdev_tx_t rc; pr_debug("frame is too big, fragmentation is needed\n"); rc = lowpan_xmit_fragmented(skb, dev, &wpan_hdr); return rc < 0 ? NET_XMIT_DROP : rc; } } static struct wpan_phy *lowpan_get_phy(const struct net_device *dev) { struct net_device *real_dev = lowpan_dev_info(dev)->real_dev; return ieee802154_mlme_ops(real_dev)->get_phy(real_dev); } static __le16 lowpan_get_pan_id(const struct net_device *dev) { struct net_device *real_dev = lowpan_dev_info(dev)->real_dev; return ieee802154_mlme_ops(real_dev)->get_pan_id(real_dev); } static __le16 lowpan_get_short_addr(const struct net_device *dev) { struct net_device *real_dev = lowpan_dev_info(dev)->real_dev; return ieee802154_mlme_ops(real_dev)->get_short_addr(real_dev); } static u8 lowpan_get_dsn(const struct net_device *dev) { struct net_device *real_dev = lowpan_dev_info(dev)->real_dev; return ieee802154_mlme_ops(real_dev)->get_dsn(real_dev); } static struct header_ops lowpan_header_ops = { .create = lowpan_header_create, }; static struct lock_class_key lowpan_tx_busylock; static struct lock_class_key lowpan_netdev_xmit_lock_key; static void lowpan_set_lockdep_class_one(struct net_device *dev, struct netdev_queue *txq, void *_unused) { lockdep_set_class(&txq->_xmit_lock, &lowpan_netdev_xmit_lock_key); } static int lowpan_dev_init(struct net_device *dev) { netdev_for_each_tx_queue(dev, lowpan_set_lockdep_class_one, NULL); dev->qdisc_tx_busylock = &lowpan_tx_busylock; return 0; } static const struct net_device_ops lowpan_netdev_ops = { .ndo_init = lowpan_dev_init, .ndo_start_xmit = lowpan_xmit, .ndo_set_mac_address = lowpan_set_address, }; static struct ieee802154_mlme_ops lowpan_mlme = { .get_pan_id = lowpan_get_pan_id, .get_phy = lowpan_get_phy, .get_short_addr = lowpan_get_short_addr, .get_dsn = lowpan_get_dsn, }; static void lowpan_setup(struct net_device *dev) { dev->addr_len = IEEE802154_ADDR_LEN; memset(dev->broadcast, 0xff, IEEE802154_ADDR_LEN); dev->type = ARPHRD_IEEE802154; /* Frame Control + Sequence Number + Address fields + Security Header */ dev->hard_header_len = 2 + 1 + 20 + 14; dev->needed_tailroom = 2; /* FCS */ dev->mtu = IPV6_MIN_MTU; dev->tx_queue_len = 0; dev->flags = IFF_BROADCAST | IFF_MULTICAST; dev->watchdog_timeo = 0; dev->netdev_ops = &lowpan_netdev_ops; dev->header_ops = &lowpan_header_ops; dev->ml_priv = &lowpan_mlme; dev->destructor = free_netdev; } static int lowpan_validate(struct nlattr *tb[], struct nlattr *data[]) { if (tb[IFLA_ADDRESS]) { if (nla_len(tb[IFLA_ADDRESS]) != IEEE802154_ADDR_LEN) return -EINVAL; } return 0; } static int lowpan_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { struct ieee802154_hdr hdr; int ret; skb = skb_share_check(skb, GFP_ATOMIC); if (!skb) goto drop; if (!netif_running(dev)) goto drop_skb; if (dev->type != ARPHRD_IEEE802154) goto drop_skb; if (ieee802154_hdr_peek_addrs(skb, &hdr) < 0) goto drop_skb; /* check that it's our buffer */ if (skb->data[0] == LOWPAN_DISPATCH_IPV6) { skb->protocol = htons(ETH_P_IPV6); skb->pkt_type = PACKET_HOST; /* Pull off the 1-byte of 6lowpan header. */ skb_pull(skb, 1); ret = lowpan_give_skb_to_devices(skb, NULL); if (ret == NET_RX_DROP) goto drop; } else { switch (skb->data[0] & 0xe0) { case LOWPAN_DISPATCH_IPHC: /* ipv6 datagram */ ret = process_data(skb, &hdr); if (ret == NET_RX_DROP) goto drop; break; case LOWPAN_DISPATCH_FRAG1: /* first fragment header */ ret = lowpan_frag_rcv(skb, LOWPAN_DISPATCH_FRAG1); if (ret == 1) { ret = process_data(skb, &hdr); if (ret == NET_RX_DROP) goto drop; } break; case LOWPAN_DISPATCH_FRAGN: /* next fragments headers */ ret = lowpan_frag_rcv(skb, LOWPAN_DISPATCH_FRAGN); if (ret == 1) { ret = process_data(skb, &hdr); if (ret == NET_RX_DROP) goto drop; } break; default: break; } } return NET_RX_SUCCESS; drop_skb: kfree_skb(skb); drop: return NET_RX_DROP; } static int lowpan_newlink(struct net *src_net, struct net_device *dev, struct nlattr *tb[], struct nlattr *data[]) { struct net_device *real_dev; struct lowpan_dev_record *entry; pr_debug("adding new link\n"); if (!tb[IFLA_LINK]) return -EINVAL; /* find and hold real wpan device */ real_dev = dev_get_by_index(src_net, nla_get_u32(tb[IFLA_LINK])); if (!real_dev) return -ENODEV; if (real_dev->type != ARPHRD_IEEE802154) { dev_put(real_dev); return -EINVAL; } lowpan_dev_info(dev)->real_dev = real_dev; mutex_init(&lowpan_dev_info(dev)->dev_list_mtx); entry = kzalloc(sizeof(*entry), GFP_KERNEL); if (!entry) { dev_put(real_dev); lowpan_dev_info(dev)->real_dev = NULL; return -ENOMEM; } entry->ldev = dev; /* Set the lowpan harware address to the wpan hardware address. */ memcpy(dev->dev_addr, real_dev->dev_addr, IEEE802154_ADDR_LEN); mutex_lock(&lowpan_dev_info(dev)->dev_list_mtx); INIT_LIST_HEAD(&entry->list); list_add_tail(&entry->list, &lowpan_devices); mutex_unlock(&lowpan_dev_info(dev)->dev_list_mtx); register_netdevice(dev); return 0; } static void lowpan_dellink(struct net_device *dev, struct list_head *head) { struct lowpan_dev_info *lowpan_dev = lowpan_dev_info(dev); struct net_device *real_dev = lowpan_dev->real_dev; struct lowpan_dev_record *entry, *tmp; ASSERT_RTNL(); mutex_lock(&lowpan_dev_info(dev)->dev_list_mtx); list_for_each_entry_safe(entry, tmp, &lowpan_devices, list) { if (entry->ldev == dev) { list_del(&entry->list); kfree(entry); } } mutex_unlock(&lowpan_dev_info(dev)->dev_list_mtx); mutex_destroy(&lowpan_dev_info(dev)->dev_list_mtx); unregister_netdevice_queue(dev, head); dev_put(real_dev); } static struct rtnl_link_ops lowpan_link_ops __read_mostly = { .kind = "lowpan", .priv_size = sizeof(struct lowpan_dev_info), .setup = lowpan_setup, .newlink = lowpan_newlink, .dellink = lowpan_dellink, .validate = lowpan_validate, }; static inline int __init lowpan_netlink_init(void) { return rtnl_link_register(&lowpan_link_ops); } static inline void lowpan_netlink_fini(void) { rtnl_link_unregister(&lowpan_link_ops); } static int lowpan_device_event(struct notifier_block *unused, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); LIST_HEAD(del_list); struct lowpan_dev_record *entry, *tmp; if (dev->type != ARPHRD_IEEE802154) goto out; if (event == NETDEV_UNREGISTER) { list_for_each_entry_safe(entry, tmp, &lowpan_devices, list) { if (lowpan_dev_info(entry->ldev)->real_dev == dev) lowpan_dellink(entry->ldev, &del_list); } unregister_netdevice_many(&del_list); } out: return NOTIFY_DONE; } static struct notifier_block lowpan_dev_notifier = { .notifier_call = lowpan_device_event, }; static struct packet_type lowpan_packet_type = { .type = htons(ETH_P_IEEE802154), .func = lowpan_rcv, }; static int __init lowpan_init_module(void) { int err = 0; err = lowpan_net_frag_init(); if (err < 0) goto out; err = lowpan_netlink_init(); if (err < 0) goto out_frag; dev_add_pack(&lowpan_packet_type); err = register_netdevice_notifier(&lowpan_dev_notifier); if (err < 0) goto out_pack; return 0; out_pack: dev_remove_pack(&lowpan_packet_type); lowpan_netlink_fini(); out_frag: lowpan_net_frag_exit(); out: return err; } static void __exit lowpan_cleanup_module(void) { lowpan_netlink_fini(); dev_remove_pack(&lowpan_packet_type); lowpan_net_frag_exit(); unregister_netdevice_notifier(&lowpan_dev_notifier); } module_init(lowpan_init_module); module_exit(lowpan_cleanup_module); MODULE_LICENSE("GPL"); MODULE_ALIAS_RTNL_LINK("lowpan");
__label__pos
0.963142
1. 首页 Vue 中的无状态组件你搞懂了没 啥是应用程序状态,为什么咱们需要它? 状态管理通常在较小的项目并不需要,但是当涉及到更大的范围时,如企业级的应用大部分需要它了。简单的说,状态是一个包含应用程序使用的最新值的对象。但是,如果咱们从结构的、更抽象的角度来看待它,就会清楚地看到,状态是复杂应该中重要一块,它使能够构建干净的体系结构,并将关注点强有力地分离开来。 通常,缺乏经验的开发人员无法预测对状态管理的需求,以及如何实现状态管理,因此很难了解状态管理的重要性。如果基于状态的组件堆积起来,它们之间的数据管理和共享将成为一场噩梦。从长远来看,拥有的基于状态的组件越多,出现的问题就越多。 如果没有使用外部包进行状态管理,那么最好尽可能少地使用基于状态的组件,而展示组件则使用围绕它们构建的状态。 Vue 和无状态(函数)组件 Vue 中的无状态组件其实就是函数组件。但函数组件又是啥呢? 要回答这个问题,咱们首先必须理解什么是函数式编程。 与将程序分解为对象的面向对象方法不同,函数式编程鼓励将程序分解为小函数,这些小函数用于形成更高级的程序。我们创建的函数不依赖于或可以改变任何外部状态,这导致另一个观察结果,对于给定的输入,它们总是返回相同的输出。 因此,函数组件是没有状态的组件,并且可以更改它。函数组件输出总是基于给定的输入。在 Vue 方面,这类组件会根据给定的props给出不同的输出。 语法 Vue 提供了一种定义函数组件的简单方法。咱们只需要给个 functional 关键字就可以。在 2.5.0 及以上版本中,如果使用了单文件组件,那么基于模板的函数式组件可以这样声明:: <template functional> <div> 函数/无状态组件 </div> </template> 或者 export default { functional: true, props: { // ... }, render(createElement, context) { return createElement( 'div', '函数/无状态组件' ) } } 码农进阶题库,每天一道面试题 or Js小知识 注意:在 2.3.0 之前的版本中,如果一个函数式组件想要接收 prop,则 props 选项是必须的。在 2.3.0 或以上的版本中,你可以省略 props 选项,所有组件上的特性都会被自动隐式解析为 prop 当使用函数式组件时,该引用将会是 HTMLElement,因为他们是无状态的也是无实例的。 需要注意的是,传递给函数组件的惟一数据是props。这些组件是完全无状态的(没有响应数据),它们忽略传递给它们的任何状态,并且不触发任何生命周期方法(createdmounted等等)。 而且,咱们也不能通过使用 this 关键字来访问实例,因为这些组件也是不实例化的。相反,组件需要的所有东西都是通过context提供的。在render函数中,它作为createElement方法的第二个参数传递。 组件需要的一切都是通过 context 参数传递,它是一个包括如下字段的对象: • props:提供所有 prop 的对象 • children: VNode 子节点的数组 • slots: 一个函数,返回了包含所有插槽的对象 • scopedSlots: (2.6.0+) 一个暴露传入的作用域插槽的对象。也以函数形式暴露普通插槽。 • data:传递给组件的整个数据对象,作为 createElement 的第二个参数传入组件 • parent:对父组件的引用 • listeners: (2.3.0+) 一个包含了所有父组件为当前组件注册的事件监听器的对象。这是 data.on 的一个别名。 • injections: (2.3.0+) 如果使用了 inject 选项,则该对象包含了应当被注入的属性。 为什么咱们需要无状态组件 到目前为止,咱们已经了解到函数组件是无状态的,在它们的核心中,它们只是可执行的函数,接受一些输入并根据其提供输出。 就它们的用法而言,因为函数式组件只是函数,所以渲染开销也低很多,这也意味着它们是非常高效的,不需要花太多时间渲染。同时,考虑高阶组件,它们不需要任何状态,它们所要做的就是用额外的逻辑或样式包装给定的子组件。 接下来,通例事例展示一样啥时使用函数组件,函数组件非常适合此类任务。 实例 在这个示例中,咱们创建一个panel组件,它充当一个包装器,并提供所需的样式。子组件将在panel 主体中渲染: export default { name: 'panel', functional: true, props: { title: String }, render(createElement, context) { const slots = context.slots(); const header = createElement('header', { attrs: { class: 'panel-header'} }, context.props.title); const body = createElement('main', { attrs: { class: 'panel-body'} }, slots.default); return createElement('section', { attrs: { class: 'panel' } }, [header, body]); } } 如上所述,此组件的唯一目的是提供类似于面板(卡片)的样式,它有headermain元素,分别保存面板标题和HTML内容。整个过程是通过使用render函数中的createElement参数在中完成。createElementVue 核心中实现的虚拟 Dom 系统的一部分。 虚拟 DOM Vue 通过建立一个虚拟 DOM 来追踪自己要如何改变真实 DOM。请仔细看这行代码: return createElement('h1', this.blogTitle) createElement 到底会返回什么呢?其实不是一个实际的 DOM 元素。它更准确的名字可能是 createNodeDescription,因为它所包含的信息会告诉 Vue 页面上需要渲染什么样的节点,包括及其子节点的描述信息。我们把这样的节点描述为“虚拟节点 (virtual node)”,也常简写它为“VNode”。“虚拟 DOM”是我们对由 Vue 组件树建立起来的整个 VNode 树的称呼。 createElement 参数 接下来你需要熟悉的是如何在 createElement 函数中使用模板中的那些功能。这里是 createElement 接受的参数: // @returns {VNode} createElement( // {String | Object | Function} // 一个 HTML 标签名、组件选项对象,或者 // resolve 了上述任何一种的一个 async 函数。必填项。 'div', // {Object} // 一个与模板中属性对应的数据对象。可选。 { // (详情见下一节) }, // {String | Array} // 子级虚拟节点 (VNodes),由 `createElement()` 构建而成, // 也可以使用字符串来生成“文本虚拟节点”。可选。 [ '先写一些文字', createElement('h1', '一则头条'), createElement(MyComponent, { props: { someProp: 'foobar' } }) ] ) ```javascript 面板 CSS 样式如下: .panel { margin-bottom: .5rem } .panel, .panel-header { border: 1px solid #d3d3d3; border-radius: 4px; } .panel-header, .panel-body, .panel { padding: .5rem; } .panel-header { background-color:#efefef; color: #eeeee } 这是一个简单直接的 CSS,提供了一些`padding` 和`color`。 #### 子组件 现在,为了让例子更加生动为此,咱们再创建两个附加组件,一个显示汽车列表,另一个只是一个简单`lorem-ipsum`的文本组件,要求它们具有相同的面板样式和外观。 **列表组件:** ```javascript export default { name: 'cars', props: { data: Array } } template: <template> <ul> <li v-for="car in data" :key="car">{{car}}</li> </ul> </template> 文本组件: export default { name: 'lorem-ipsum' } template: <template> <p> 终身学习者,终身学习者,终身学习者,终身学习者,终身学习者 </p> </template> 现在,有了可用的子组件,咱们所需要做的就是用panel组件将它们封装到应用程序中,如下所示: <div class="vue-app"> <panel :title="'Car Manufacturers'"> <cars :data="['Mazda', 'Ford', 'Mercedes']"></cars> </panel> <panel :title="'Lorem Ipsum'"> <lorem-ipsum></lorem-ipsum> </panel> </div> 请注意,使用这些组件是因为示例比较简单。在实际应用中,它可以是任何类型的组件。 完整代码 hmtl <div class="vue-app"> <panel :title="'Car Manufacturers'"> <cars :data="['Mazda', 'Ford', 'Mercedes']"></cars> </panel> <panel :title="'Lorem Ipsum'"> <lorem-ipsum></lorem-ipsum> </panel> </div> <script type="text/x-template" id="cars"> <template> <ul> <li v-for="car in data" :key="car">{{car}}</li> </ul> </template> </script> <script type="text/x-template" id="lorem-ipsum"> <template> <p>前端小智, 终身学习者,终身学习者,终身学习者,终身学习者,终身学习者</p> </template> </script> css body { padding: .5rem } * { padding: 0; margin:0; box-sizing: border-box; } .panel { margin-bottom: .5rem } .panel, .panel-header { border: 1px solid #d3d3d3; border-radius: 4px; } .panel-header, .panel-body, .panel { padding: .5rem; } .panel-header { background-color:#efefef; color: #eeeee } ul { list-style: none; } ul > li { padding: .5rem .2rem } js // the wrapper panel const panel = { functional: true, name: "panel", props: { title: String }, render(createElement, context) { const slots = context.slots(); const header = createElement('header', { attrs: { class: 'panel-header'} }, context.props.title); const body = createElement('main', { attrs: { class: 'panel-body'} }, slots.default); return createElement('section', { attrs: { class: 'panel' } }, [header, body]); } } // sample components const cars = { name: 'cars', template: '#cars', props: { data: Array } } const loremIpsum = { name: 'lorem-ipsum', template: '#lorem-ipsum' } new Vue({ el: '.vue-app', components: { panel, cars, 'lorem-ipsum': loremIpsum } }); 运行效果: Js中文网 一个帮助开发者成长的社区,你想要的,在这里都能找到 作者:Milos Protic 作者:前端小智 链接:https://segmentfault.com/a/1190000021062929 看完两件小事 如果你觉得这篇文章对你挺有启发,我想请你帮我两个小忙: 1. 关注我们的 GitHub 博客,让我们成为长期关系 2. 把这篇文章分享给你的朋友 / 交流群,让更多的人看到,一起进步,一起成长! 3. 关注公众号 「画漫画的程序员」,公众号后台回复「资源」 免费领取我精心整理的前端进阶资源教程 JS中文网是中国领先的新一代开发者社区和专业的技术媒体,一个帮助开发者成长的社区,目前已经覆盖和服务了超过 300 万开发者,你每天都可以在这里找到技术世界的头条内容。欢迎热爱技术的你一起加入交流与学习,JS中文网的使命是帮助开发者用代码改变世界 本文著作权归作者所有,如若转载,请注明出处 转载请注明:文章转载自「 Js中文网 · 前端进阶资源教程 」https://www.javascriptc.com 标题:Vue 中的无状态组件你搞懂了没 链接:https://www.javascriptc.com/3509.html « 汇总ECMAScript 2016、2017、2018中所有新特性 构建无渲染的 Vue 组件(函数式组件)» Flutter 中文教程资源 相关推荐 QR code
__label__pos
0.977881
Maven 3.x is the Maven version for the people. The Maven team has gone to the ends of the earth to ensure backward compatibility, improve usability, increase performance, allow safe embedding, and pave the way for implement many highly demanded features. This talk will briefly cover the process and tooling changes that have occured in the Maven project in order to accomplish what we have done with Maven 3.0, as well as discuss the architectural and feature changes. Some of the process changes include We also built out a framework that measures disk I/O, network I/O, memory consumption, and CPU utilization to ensure that performance doesn't degrade. The architectural changes center around how POMs are constructed, how the lifecycle is executed, how the plugin manager executes, and how artifacts are resolved. Some features derived from these architectural changes include • lifecycle extension points, • plugin extension points, • our new single point of entry artifact resolution mechanism, Aether . Some features not done in Maven 3.0.x but in discussion for future releases are • any-source POMs, • versionless parent elements, • a compositional form of Maven POM configuration we call mixins
__label__pos
0.694728
How to control the priority of Web resource loading? Hello, I'm Conard Li. Today, let's take a look at the priority of Web resource loading. The browser resolves the priority of the resource When the browser starts parsing web pages and downloading resources such as pictures, scripts and CSS, the browser will assign a fetch priority flag representing the download priority of resources to each resource. The order of resource downloading depends on this priority flag, and the calculation logic of this priority flag will be affected by many factors: • Different resource types such as Script, CSS, Font and Image have different priorities. • The location or order in which resources are referenced in HTML documents will also affect the priority of resources (for example, image resources in the viewport may have a high priority, while CSS loaded in the < link > tag that blocks rendering has a higher priority). • Resources with the preload attribute can help the browser discover resources faster. In fact, it also affects the priority of resource loading. • The async or defer attribute of a Script affects its priority. Considering these factors, the following is the priority and ranking of most resources in Chrome: The browser downloads resources with the same calculation priority in the order in which the resources are found. You can see the priorities assigned to different resources under DevTools Network: Although browsers are good at this, the default download priority is not the best in all cases. Why do you need Priority Hints? Knowing how the browser assigns download priority to resources, we can make some adjustments according to the actual business scenario: • Resource tags are placed according to the desired download order of resources, such as < script > and < link >, and resources with the same priority are usually loaded in the order in which they are placed. • Use the preload attribute to download necessary resources in advance, especially those that are not easy to find in the early stage of the browser. • Use async or defer to download non first screen resources that do not need to be blocked. • Delay loading some first screen content so that the browser can use the available network bandwidth for more important first screen resources. These technologies can let us better control the priority calculation of the browser, so as to improve the Core Web Vitals performance index of the web page. For example, we can improve the maximum content rendering index (LCP) by preloading the key background images of web pages. However, the above technologies are not enough for us to control the priority in all scenarios, such as the following scenarios: • The website now has multiple first screen images, but they do not have the same priority. For example, in the rotation map, only the first image needs higher priority. • Declaring < script > as async or defer tells the browser to load them asynchronously. However, according to our analysis above, these < script > are also assigned "low" priority. But you may want to make sure that browsers download them asynchronously while raising their priority, especially some scripts that are critical to the user experience. • The browser assigns high priority to the JavaScript fetch API to asynchronously obtain resources or data, but in some scenarios, you may not want to request all resources with high priority. • The browser assigns the same high priority to CSS and Font, but not all CSS and Font resources are equally important. You may need to specify their priority more specifically. Therefore, the browser provides us with a function that can better control the priority loading of resources: Priority Hints. importance property You can use an importance attribute to more carefully control the priority of resource loading, including link, img, script and iframe tags. The importance property can specify three values: • High: you think this resource has high priority and want the browser to prioritize it. • low: you think this resource has a lower priority and want the browser to lower its priority. • auto: uses the browser's default priority. <!-- We don't want a high priority for this above-the-fold image --> <img src="/images/in_viewport_but_not_important.svg" importance="low" alt="I'm an unimportant image!"> <!-- We want to initiate an early fetch for a resource, but also deprioritize it --> <link rel="preload" href="/js/script.js" as="script" importance="low"> <script> fetch('https://example.com/', {importance: 'low'}).then(data => { // Trigger a low priority fetch }); </script> <!-- The third-party contents of this iframe can load with a low priority --> <iframe src="https://example.com" width="600" height="400" importance="low"></iframe> practical application Raise the priority of LCP images Now that you have more flexible priority configuration, you can use it to improve the Core Web Vitals of your web pages. For example, in Google Flights, the main reason affecting its LCP index is its background image. Now we use the importance attribute to improve its loading priority: <img src="lcp-image.jpg" importance="high"> It can be found that the LCP of the web page has increased from 2.6s to 1.9s: Reduce the priority of the first screen picture Use the importance attribute to lower the priority of the first screen picture that may not be important, such as the following picture in the rotation picture: <ul class="carousel"> <img src="img/carousel-1.jpg" importance="high"> <img src="img/carousel-2.jpg" importance="low"> <img src="img/carousel-3.jpg" importance="low"> <img src="img/carousel-4.jpg" importance="low"> </ul> Reduce the priority of preloaded resources To prevent competition between preloaded resources and other critical resources, you can lower their priority: <!-- Lower priority only for non-critical preloaded scripts --> <link rel="preload" as="script" href="critical-script.js"> <link rel="preload" href="/js/script.js" as="script" importance="low"> <!-- Preload CSS and hero images without blocking other resources --> <link rel="preload" as="style" href="theme.css" importance="low" onload="this.rel=stylesheet"> Priority of script If there are some necessary interactive scripts on the page, but there is no need to block other resources, you can mark them as having high priority and load them asynchronously: <script src="async_but_important.js" async importance="high"></script> If scripts depend on specific DOM nodes, they cannot be marked as loaded asynchronously. However, if they are not necessary for first screen rendering, you can lower their priority: <script src="blocking_but_unimportant.js" importance="low"></script> fetch The browser will execute fetch requests with high priority by default. You can lower the priority of less critical data requests: // Important validation data (high by default) let authenticate = await fetch('/user'); // Less important content data (suggested low) let suggestedContent = await fetch('/content/suggested', {importance: 'low'}); Start trial You can try this feature by opening Experimental Web Platform Features in Chrome settings. reference resources https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/1.5/Changing_the_priority_of_HTTP_requests https://developer.chrome.com/blog/new-in-chrome-96/#pri-hints https://web.dev/priority-hints/ Posted by Hard Styler on Wed, 01 Dec 2021 20:15:42 -0800
__label__pos
0.891417
How To Turn Off Notifications On Snapchat IPhone, Android Are you tired of getting notifications from Snapchat? Do you want to get a break from all the snaps and stories alerts? If so, then you might want to turn off your Snapchat notifications for a while or forever. They are few ways you can do that, in-app or through your phone. It would be easier to turn off Snapchat notifications completely while using an android phone than on an ios device. This is because turning off notifications on an android device is pretty straightforward and even a newbie can figure it out in less than a minute. However, it is still doable on both devices or you can turn it off inside the application. In this guide, you will learn how to turn off all kinds of Snapchat notifications. Turn off notifications for Snapchat on an android phone By default, when you enable notifications for Snapchat on your android phone, you will get alerts when a friend posts a story or sends you a snap. If you don’t want to receive alerts from Snapchat on your android or want to turn off specific notification, follow the steps below: 1. Navigate to the Settings app on your android phone. 2. Tap on Notifications. Disable Snapchat notifications on android Samsung phone 3. A list of other applications will be shown, select the app you want to enable or disable it’s notifications, in this case Snapchat. Disable Snapchat notifications on android Samsung Galaxy Note 8 phone 4. Turn on or off the alerts of the app you want on or off. Or if you want to turn off all notifications you can toggle on the show notifications. It will look something like this: See also  How To Unpin A Deleted Account On Snapchat Disable Snapchat notifications on android Samsung Galaxy Note 8 phone Turn off Snapchat notifications on iPhone If you want reduce or turn off all notifications on your iOS device that is your iPhone, the steps are easy. Follow the steps below to execute: 1. Go to the Settings app on your iPhone. 2. Scroll up to notifications and tap on it. 3. Find Snapchat app and disable “sounds” 4. Now, navigate to your Snapchat app and go to settings tab. 5. Find “notifications”, tap on it 6. Toggle on the notification you want on or off. Depending on which notifications you turned off, your phone will not get any alert anymore. However, if you want to turn them back on, follow the same aforementioned steps and you will start getting Snapchat notifications on your iOS device again. How to turn off Snapchat notifications on the Apple watch If you use the Apple watch and you don’t want to be getting notifys from Snapchat. They are simple steps you can follow to turn them off which are as follows: 1. Make sure that on notifications in your settings app on your iPhone that Snapchat “sounds” is not enabled. 2. Now, go to the apple watch application, tap on “Settings” then “notifications” 3. Next, tap on “Mirror iPhone alerts from:” you will then see a list of apps. 4. Toggle on the on/off button next to Snapchat to turn off notifications from Snapchat to your Apple watch. Why do I get a Snapchat notification saying someone is typing, but then get nothing? When you get the “x is typing” notification from Snapchat, but then get nothing. It could mean a couple of things. See also  Can My Friends See That I’m On A Voice Channel In A Server They Are Not In? Answered Majority of the these things may include something like: They mistakenly opened your message and started to reply but then changed their mind. Or that they are doing it on purpose, as a joke or a funny prank. How do I make Snapchat notifications not vibrate? If you want to disable vibrating alert when you get an alert from Snapchat, you have to do so from your phone. Go to sounds and turn off “vibrate on ring” and “vibrate on silent” This will stop you from getting Snapchat notifications and all other app notifications that make your phone vibrate. How can someone see Snapchat notifications of screenshots taken of a chat between two people? By default, Snapchat will notify you when someone you are texting with takes a screenshot of your chats. However, if you have failed to see a notification, you can check open the conversation and you will see a gray notification that looks like this: Screenshot of Snapchat chat This is just a way of protecting your privacy and allows you to be careful with what you put out there on social media. Conclusion Snapchat has different features which include notifying users when someone takes a screenshot of a conversation, posts on their stories or sends you a snap or even when your message are updating. However, if you want to stop your phone from blowing up with notifications from Snapchat you will need to disable the notifications. The way to do this is by turning off the inbuilt notifications directly on the Snapchat app or by turning it on your settings app on your android phone or iOS. Join 5,000+ subscribers * indicates required Brianna Bailey Brianna is based in Minnesota in the US at the moment, and has been writing since 2017. She is currently a 3rd Year med student at the time of writing this.
__label__pos
0.648883
5 $\begingroup$ Symmetric/Metric TSP can be solved via the Held-Karp algorithm in $\mathcal O(n^2 2^n)$. See A dynamic programming approach to sequencing problems by Michael Held and Richard M. Karp, 1962. In Exact Algorithms for NP-Hard Problems: A Survey (PDF) Woeginger writes: This result was published in 1962, and from nowadays point of view almost looks trivial. Still, it yields the best time complexity that is known today. Thus, this is the best known upper-bound. Question: Are there any better results for Euclidean TSP? Or does that best-known bound apply to Euclidean TSP as well. How is Euclidean TSP different? Well, • Euclidean TSP can be encoded into $\mathcal O(n \log m)$ space, where $n$ is the number of cities, and $m$ is the bound on the integer coordinates of the city locations. As opposed to (sym)metric TSP variants, which essentially require a distance matrix of size $\mathcal O(n^2 \log m)$. Thus, it might be easier to solve; for example, perhaps Euclidean TSP can be more easily encoded into k-SAT, because the distance function is implicit. • Contrary to popular notion, Euclidean TSP's reduction from k-SAT is quite different from (sym)metric TSP. UHC (undirected Hamiltonian cycle), symmetric TSP, and metric TSP are pretty directly related to each-other. But formulations of reductions from (sym)metric TSP to Euclidean TSP are not easy to come by. Paragraph, from interesting article, The Travelling Salesman’s Power by K. W. Regan (bold mine): Now the reductions from 3SAT to TSP, especially Euclidean TSP, are less familiar, and we ascribe this to their being far more “expansive.” Texts usually reduce 3SAT to Hamiltonian Cycle, then present the latter as a special case of TSP, but this does not apply to Euclidean TSP. The ${\mathsf{NP}}$-completeness of Euclidean TSP took a few years until being shown by Christos Papadimitriou, and a 1981 paper by him with Alon Itai and Jayme Luiz Szwarcfiter advertised a “new, relatively simple, proof.” This proof uses vertex-induced subgraphs of the grid graph in the plane, for which the shortest possible TSP tour and any Hamiltonian cycle have the same length. Despite this simplification, the gadgets involved are large—a diagram of one occupies most of one journal page. Hunting down k-SAT $\rightarrow$ Euclidean TSP reductions is quite an adventure; so far I've found two of them. One $\rm k\text{-}SAT \rightarrow CircuitSAT \rightarrow PlanarCircuitSAT \rightarrow EuclideanTSP$, and another, even tougher one to find, $\rm k\text{-}SAT \rightarrow DHC \rightarrow UHC \rightarrow PlanarUHC \rightarrow EuclideanTSP$. The latter reduction can perhaps be seen to make Euclidean TSP parallel (sym)metric TSP. $\endgroup$ 4 $\begingroup$ One can exploit planar separator structures in a geometric setting and thus solve Euclidean TSP exactly in $O(n^{c \sqrt{n}})$ time, where $c$ is some small constant greater than 1. There's at least three simultaneous results for this; Smith's PhD thesis [1], Kann's PhD thesis [2], and Hwang et al. [3]. Each algorithm has a running time of $O^*(c^{\sqrt{n} \log n})$. This is much better than $O(n^2 2^n)$. As far as I know, it is still an open question whether the running time can be improved by say getting rid of the logarithmic term. [1] W.D. Smith, Studies in computational geometry motivated by mesh generation. Ph.D. Thesis, Princeton University, Princeton. [2] V. Kann, On the approximability of NP-complete optimization problems, Ph.D. Thesis, Kungliga Tekniska Högskolan, Stockholm, 1992. [3] R.Z. Hwang, R.C. Chang, R.C.T. Lee, The searching over separators strategy to solve some NP-hard problems in subexponential time, Algorithmica 9 (1993) 398–423. | cite | improve this answer | | $\endgroup$ 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.841599
WebSocket(realtime) Authorization Clients have to provide an access-token as query parameter to authenticate themselves with the WebSocket Server. You have to use REST API To get an access-token. Please check Obtain an access-token API. Open a WebSocket connection To open a WebSocket connection you have to obtain an access-token and provide it as query parameter in the url. By default the API only accepts secured connections via wss. The Access Token from REST API is for one-time use. It should be issued on every new connection. wss://zeroth.goodatlas.com:2087/client/ws/speech?access-token=<access-token>&language=<language> Mandatory Parameter access-token - Your access token. language Currently we provide two different language models, eng for English and kor for Korean. Optional Parameter final-only Set to true if you only want the final result. (default false) content-type Only needed if your audio source is recorded with a microphone. The most common option are: • 16 KHz, Mono: audio/x-raw,+layout=(string)interleaved,+rate=(int)16000,+format=(string)S16LE,+channels=(int)1 • 44 KHz, Mono: audio/x-raw,+layout=(string)interleaved,+rate=(int)44100,+format=(string)S16LE,+channels=(int)1 Handshake status codes It is recommended to read the http status code of the handshake response and handle possible errors. The following list shows possible status codes of the handshake response 101 - OK 400 - Missing mandatory parameter 401 - Invalid access-token 403 - Free usage exceeded and no credit card available Sending audio data Once a connection is established, the client can start sending audio data (e.g. a file or microphone recording) as binary. We are supporting most of the common audio files like .mp3, .flac, .wav, .ogg, .oga, .mp4,... After all audio data is sent to the server, the client should send a text message with the content EOS through the same connection. This message tells the server that the audio transmission is complete. Receiving transcription Transcribed text of the audio will be sent back to the client in real time. The format of the transcription object depends on the parameters the client used to establish the connection. Partial Result { "transcript": "hello", "final": false } transcript: The transcribed text. final: Flag to indicate if the result is final or partial. Final Result { "transcript": "hello", "likelihood": 61.4353, "word-alignment": [ { "start": 0.27, "length": 0.99, "word": "hello", "confidence": 0.866439 } ], "final": true, "segment-start": 0, "segment-length": 2.1, "total-length": 2.1 } transcript: The transcribed text. likelihood: Likelihood of the transcribed text. word-alignment: final: Flag to indicate if the results is final or partial. segment-start: Start time of this segment in seconds. segment-length: Length of this segment in seconds. total-length: Length of all segments in seconds. Closing connection The client should not manually close the connection, which would be handled as an error on the server side. The server will automatically close the connection to the client after the last result was transmitted to the client. Close Status The server closes the websocket connection to the client with one of the following status codes. Consider to check the status code for error handling on the client side or for reporting any issues. Status Code Reason 1000 Success 1006 Client closed connection abnormally 1007 Unsupported audio type or bad quality 1011 Terminating connection because of unexpected server error 1013 No free capacity
__label__pos
0.782355
How do I create a batch file? Step 1 To create a batch file, start by opening an Excel file with the following column names. Column Name Requirements Column Description first_name* required Transaction partner: first name middle_name optional Transaction partner: middle name last_name* required Transaction partner: last name business_name optional Transaction partner: business name institution_number* required Transaction partner: institution number branch_number* required Transaction partner: branch number account_number* required Transaction partner: account number transaction_type* required Action required, either direct_debit or direct_credit amount_in_cents* required Amounts of funds to be transferred in cents transaction_reference optional Note for your internal reference memo optional If populated, this information will show on the recipient’s bank statement as the description for the transaction Step 2 Once the information has been entered into the spreadsheet, save the file as a .CSV (also known as Comma delimited). Common Batch File Questions Optional Columns: These columns can be left blank if needed because they are not required fields, however the column name does need to be present otherwise the file will not process. Do not delete any of the column headers; the format of the file must remain as is. Leading Zeros: If there are numbers with leading zeros, e.g. for any of the banking information, you may notice that the zeros disappear causing problems with the file. You can format the field, starting the leading zeros with an apostrophe (‘) which will allow the cell to retain the leading zeros. For example, 001 is entered as ‘001 to retain the leading zeros. Multiple Transaction Types: Each batch file can only contain 1 transaction_type. Please create separate batch files for direct_debit and direct_credit transactions. 2019-05-02T16:45:22-04:00April 5th, 2018|PayPort FAQ|
__label__pos
0.954602
Sunday, 4 March 2012 Weblogic Admin Interview Questions-Part 1 1. What is the default HTTP Port? 2. What is the difference between production mode and development mode? 1. What is weblogic domain and what are the different servers? 2. How do you find the version of WL Server? 3. What is the default Weblogic Admin console port number? 4. Which of the following statements is NOT True? a)     Managed Servers in a Domain must run the same version of Weblogic Server b)     A Domain comprises only the Admin Server, only the Managed Server, or the             Administration and Managed Servers c)     The Admin Server stores the configuration information and logs for a domain d)     The Admin Server in a domain must run the same or higher version of WLS as the MS in the domain. 7.      Which of the following statements is NOT True? a)     There can be multiple clusters in a domain b)     All the servers in a cluster must be at the same version level c)     All the server in a cluster must also be in the same domain d)     A cluster can span multiple domains. 8.      The Admin Console is unavailable if the Admin Server is Shut Down. a)     TRUE                     b)   FALSE 9.      Which of the following statement is true? a)     There is one Node Manager for each Machine b)     There is one Node Manager for each Domain c)     There is one Node Manager for each Cluster 10. Oracle Weblogic Server 10.3 is certified with JDK 1.6? a)     TRUE                     b)   FALSE 11. Net installer is preferred over the package installer if you want to install select components using only the custom option and have access to the Internet. a)     TRUE                     b)   FALSE 12. How do you set up class path? 13. How to start Web logic Admin Server? 14. How many ways you can install weblogic? 15. How many domains you can create? 16. What weblogic utils contains? 17. Can we disable admin console? 18. Difference between Weblogic server and Web server? 19. What happens when we give www.abc.com in URL (what is process)? 20. Is Managed server can be restarted independently when admin is down? 21.  What is the difference between JNDI & JDBC? 22.  Difference between versions 8.X, 9.X, 10.X? 23.  What is the Connection Pool? How to create a Connection Pool? 24.  What is Domain? How many domains are possible in a single instance? 25.  What is DataSource? How can it is associated with connection pools ? 26.  Are WebLogic Servers password secure?       27.  Do you require JDK/JRE for installing a WL Domain? 28.  What is the basic requirement for starting a WebLogic server? 29.  What is the major difference between Managed Server and Admin Server? 30.  When starting the managed server it is coming to admin state. Click on resume button in admin Console, so that is coming to running state. How to resolve this problem for ever so that the server will come directly to running state instead of going to admin state? 31.  In which file/script we need to change the heap size? What is the variable name to search to change the heap size 32.  Where can we set Classpath, which will reflect to whole domain? 33.  What is MSI mode? 34.  How to find the heap memory of Managed Server? 35.  What happen if we deploy our component in weblogic server? What are the States? 36.  What is WLS T3 protocol? 37.  What is Node Manager and why it is required? 38.  How would you check the weblogic instance whether the server is started or not? 39.  Specify some important jar files in the weblogic server 40. How does the WLST communicate with WLS to retrieve and update resources on a running server?
__label__pos
0.989074
There is a new version of this tutorial available for Ubuntu 22.04 (Jammy Jellyfish). How to Install and Configure OpenLDAP and phpLDAPadmin on Ubuntu 20.04 LDAP is a Lightweight Directory Access Protocol used for accessing and maintaining distributed directory over an internet protocol. phpLDAPadmin is a web-based LDAP client used for managing and administering the LDAP server. Its powerful search functionality and hierarchical tree view make it easier to manage the LDAP server through the web browser. You can add and delete records, view and edit image attributes, manage user password hashes and many more using phpLDAPadmin. In this tutorial, we will explain how to install phpLDAPadmin on Ubuntu 20.04. Prerequisites • A server running Ubuntu 20.04. • A valid domain name pointed with your server IP. • A root password is configured the server. Getting Started Before starting, it is always recommended to update your system with the latest version of packages. You can update it with the following command: apt-get update -y Once all the packages are updated, you can proceed to the next step. Install and Configure OpenLDAP Server First, you will need to install Slapd and other LDAP utilities in your server. You can install them by running the following command: apt-get install slapd ldap-utils During the installation, you will be asked to set up an administrator password as shown below: Configure slapd Provide your secure password and hit Enter to continue. Once the installation has been finished, you will need to reconfigure the SLAPD package to set your domain information. You can reconfigure it with the following command: dpkg-reconfigure slapd You will be asked to omit the OpenLDAP server configuration as shown below: OpenLdap configuration Select No and hit Enter to continue. You will be asked to provide a DNS domain name as shown below: Configure slapd Provide your domain name and hit Enter to continue. You will be asked to provide the organization name as shown below: Organization name Provide your desired organization name and hit Enter to continue. You will be asked for the admin password as shown below: admin password Provide your administrator password and hit Enter to continue. You will be asked to remove the database as shown below: purge database Select Yes and hit Enter to finish the configuration. Now, you can verify your LDAP information using the following command: slapcat You should get the following output: dn: dc=example,dc=com objectClass: top objectClass: dcObject objectClass: organization o: example.com dc: example structuralObjectClass: organization entryUUID: 971829cc-ac5f-103a-8e42-9f8486ff5685 creatorsName: cn=admin,dc=example,dc=com createTimestamp: 20201027051828Z entryCSN: 20201027051828.103064Z#000000#000#000000 modifiersName: cn=admin,dc=example,dc=com modifyTimestamp: 20201027051828Z dn: cn=admin,dc=example,dc=com objectClass: simpleSecurityObject objectClass: organizationalRole cn: admin description: LDAP administrator userPassword:: e1NTSEF9Tm5OYlpSMktkYjVnUUprb284MHFPTEVkMjQrQXpQWEk= structuralObjectClass: organizationalRole entryUUID: 9718c198-ac5f-103a-8e43-9f8486ff5685 creatorsName: cn=admin,dc=example,dc=com createTimestamp: 20201027051828Z entryCSN: 20201027051828.107057Z#000000#000#000000 modifiersName: cn=admin,dc=example,dc=com modifyTimestamp: 20201027051828Z Create OpenLDAP User Accounts First, you will need to create the organization unit containers to store users and group information. You can create it with the following command: nano users-ou.ldif Add the following lines: dn: ou=people,dc=example,dc=com objectClass: organizationalUnit objectClass: top ou: people dn: ou=groups,dc=example,dc=com objectClass: organizationalUnit objectClass: top ou: groups Save and close the file when you are finished then adjust the SLAPD database access controls by creating the following file: nano update-mdb-acl.ldif Add the following lines: dn: olcDatabase={1}mdb,cn=config changetype: modify replace: olcAccess olcAccess: to attrs=userPassword,shadowLastChange,shadowExpire by self write by anonymous auth by dn.subtree="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage by dn.exact="cn=readonly,ou=people,dc=example,dc=com" read by * none olcAccess: to dn.exact="cn=readonly,ou=people,dc=example,dc=com" by dn.subtree="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage by * none olcAccess: to dn.subtree="dc=example,dc=com" by dn.subtree="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage by users read by * none Save and close the file then update database ACL with the above information by running the following command: ldapadd -Y EXTERNAL -H ldapi:/// -f update-mdb-acl.ldif You should get the following output: SASL/EXTERNAL authentication started SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth SASL SSF: 0 modifying entry "olcDatabase={1}mdb,cn=config" Next, update the database with the user OU information by running the following command: ldapadd -Y EXTERNAL -H ldapi:/// -f users-ou.ldif You should get the following output: SASL/EXTERNAL authentication started SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth SASL SSF: 0 adding new entry "ou=people,dc=example,dc=com" adding new entry "ou=groups,dc=example,dc=com" Next, create a new user account named hiteshj by creating the following file: nano hitesh.ldif Add the following lines: dn: uid=hiteshj,ou=people,dc=example,dc=com objectClass: inetOrgPerson objectClass: posixAccount objectClass: shadowAccount uid: hiteshj cn: Hitesh sn: Jethva loginShell: /bin/bash uidNumber: 10000 gidNumber: 10000 homeDirectory: /home/hiteshj shadowMax: 60 shadowMin: 1 shadowWarning: 7 shadowInactive: 7 shadowLastChange: 0 dn: cn=hiteshj,ou=groups,dc=example,dc=com objectClass: posixGroup cn: hiteshj gidNumber: 10000 memberUid: hiteshj Save and close the file then add the user to the database with the following command: ldapadd -Y EXTERNAL -H ldapi:/// -f hitesh.ldif You should get the following output: SASL/EXTERNAL authentication started SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth SASL SSF: 0 adding new entry "uid=hiteshj,ou=people,dc=example,dc=com" adding new entry "cn=hiteshj,ou=groups,dc=example,dc=com" Next, you will need to set the password for the user. You can set it with the following command: ldappasswd -H ldapi:/// -Y EXTERNAL -S "uid=hiteshj,ou=people,dc=example,dc=com" You should se the following output: New password: Re-enter new password: SASL/EXTERNAL authentication started SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth SASL SSF: 0 Once you are finished, you can proceed to the next step. Create OpenLDAP Bind DN Next, you will need to define username and password for querying the directory server. First, generate the password hash for the bind DN user using the following command: slappasswd You should get the following output: New password: Re-enter new password: {SSHA}DhjyJN5akaj2etaFKoyeAY8QMgSD/OTb Next, create a Bind DN name readonly with the following command: nano readonly-user.ldif Add the following lines: dn: cn=readonly,ou=people,dc=example,dc=com objectClass: organizationalRole objectClass: simpleSecurityObject cn: readonly userPassword: {SSHA}DhjyJN5akaj2etaFKoyeAY8QMgSD/OTb description: Bind DN user for LDAP Operations Save and close the file when you are finished then add the BIND user to the database with the following command: ldapadd -Y EXTERNAL -H ldapi:/// -f readonly-user.ldif You should get the following output: SASL/EXTERNAL authentication started SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth SASL SSF: 0 adding new entry "cn=readonly,ou=people,dc=example,dc=com" Next, verify the Bind DN ACL with the following command: ldapsearch -Q -LLL -Y EXTERNAL -H ldapi:/// -b cn=config '(olcDatabase={1}mdb)' olcAccess You should get the following output: dn: olcDatabase={1}mdb,cn=config olcAccess: {0}to attrs=userPassword,shadowLastChange,shadowExpire by self writ e by anonymous auth by dn.subtree="gidNumber=0+uidNumber=0,cn=peercred,cn=ext ernal,cn=auth" manage by dn.exact="cn=readonly,ou=people,dc=example,dc=com" read by * none olcAccess: {1}to dn.exact="cn=readonly,ou=people,dc=example,dc=com" by dn.subt ree="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage by * non e olcAccess: {2}to dn.subtree="dc=example,dc=com" by dn.subtree="gidNumber=0+uid Number=0,cn=peercred,cn=external,cn=auth" manage by users read by * none Install and Configure phpLDAPadmin By default, phpLDAPadmin package is available in the Ubuntu 20.04 default repository. You can install it by running the following command: apt-get install phpldapadmin -y After installing phpLDAPadmin, you will need to configure phpLDAPadmin and define your domain information. You can do it by editing the file /etc/phpldapadmin/config.php: nano /etc/phpldapadmin/config.php Change the following lines: $servers->setValue('server','name','My LDAP Server'); $servers->setValue('server','host','69.87.216.102'); $servers->;setValue('server','base',array('dc=example,dc=com')); $servers->setValue('login','auth_type','session'); $servers->setValue('login','bind_id','cn=admin,dc=example,dc=com'); $servers->setValue('auto_number','min',array('uidNumber'=>10000,'gidNumber'=>10000)); Save and close the file when you are finished. Configure Apache for phpLDAPadmin phpLDAPadmin default configuration file for Apache is located at /etc/apache2/conf-available/phpldapadmin.conf. Don't make any changes and go with default settings. Next, disable the default Apache virtual host configuration file and restart the Apache service to apply the changes: a2dissite 000-default.conf systemctl restart apache2 Once you are finished, you can proceed to the next step. Access phpLDAPadmin Web UI Now, open your web browser and access the phpLDAPadmin using the URL http://your-server-ip/phpldapadmin. You should see the following screen: phpladpadmin Now, click on the login button. You should see the phpLDAPadmin login screen: phpladpadmin login Provide your login DN, password and click on the Authenticate button. You should see the phpLDAPadmin dashboard in the following screen: Ldap dashboard Conclusion Congratulations! you have successfully installed and configured phpLDAPadmin on Ubuntu 20.04 server. You can now manage your LDAP server and perform several tasks including, adding organizational units, groups, and users with phpLDAPadmin web UI. Feel free to ask me if you have any questions. Share this page: Suggested articles 4 Comment(s) Add comment Comments By: John Nice guide. How could i add TLS support, please? By: thaj nice artical ... By: Jean Alexandre Thanks for the tutorial, it was very important, please and I have a question, how do I give login permissions so that the user can only manage their OU Jean By: ramana Nice guide, I have configured LDAP server successfully according to your guide. How to add multiple users (I have 500+ users) to LDAP server.
__label__pos
0.962622
LeetCode 1534. Count Good Triplets Description https://leetcode.com/problems/count-good-triplets/ Given an array of integers arr, and three integers ab and c. You need to find the number of good triplets. A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true: • 0 <= i < j < k < arr.length • |arr[i] - arr[j]| <= a • |arr[j] - arr[k]| <= b • |arr[i] - arr[k]| <= c Where |x| denotes the absolute value of x. Return the number of good triplets. Example 1: Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3 Output: 4 Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)]. Example 2: Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1 Output: 0 Explanation: No triplet satisfies all conditions. Constraints: • 3 <= arr.length <= 100 • 0 <= arr[i] <= 1000 • 0 <= a, b, c <= 1000 Explanation Just implement as the problem description is. Python Solution class Solution: def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int: results = [] for i in range(0, len(arr)): for j in range(i + 1, len(arr)): for k in range(j + 1, len(arr)): if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c: results.append([i, j, k]) return len(results) • Time Complexity: O(N^3) • Space Complexity: O(N) Leave a Reply Your email address will not be published. Required fields are marked *
__label__pos
0.995654
Stationary camera, moving scene Previously, we talked about revolving the entire 3D scene about the camera, and also the problem of the camera looking directly downwards. Today, we’ll look at the mechanics of implementing that stationary camera (it ain’t pretty). There are 2 transformations to take care of: translation and rotation. Translation takes care of the distance between the camera and the point it’s looking at. Rotation takes care of simulating the camera turning around to look at objects, roughly speaking. Let me use a 2D version to illustrate the concept. Reverse translation and rotation of 2D scene Suppose the camera is at some arbitrary position looking at an object. Based on the positions of the camera and the object, you can find the distance between them. You know, with this: d = sqrt( (cx-ox)^2 + (cy-oy)^2 ) where cx and cy are the x-coordinate and y-coordinate of the camera respectively, and ox and oy are the x-coordinate and y-coordinate of the object respectively. The camera is looking at the object, so the angle (theta) of its line of sight with respect to the (for example) x-axis can be calculated. Suppose we want the stationary camera to look in the direction of the positive y-axis, and be positioned at the origin (0,0). To make the scene viewed through a stationary camera the same as that in the original version (the default by the 3D engine), we would rotate the entire scene (90 – theta) degrees, then translate the result of that d units along the positive y-axis. Remember that order of transformations is important. Rotating first then translating, is (generally) different from translating then rotating. So that’s the general idea of making a stationary camera work, by moving and rotating the entire scene. The fun part comes because it’s in 3D. The distance calculation still holds true: d = sqrt(x^2 + y^2 + z^2) The angle… not so much. Because it’s in 3D, I adopted spherical coordinates. The radius would simply be the distance calculated previously. But there are now 2 angles to calculate, theta and phi. Spherical coordinate angles Suppose the camera is at (a,b,c) and the viewed object is at (p,q,r). We make the viewed object the centre of our attention, so we start our calculations with the object at the origin. Therefore, the camera is at (a-p, b-q, c-r). We can calculate the distance between them as d = sqrt( (a-p)^2 + (b-q)^2 + (c-r)^2 ) Then we also solve for the following set of simultaneous equations (note I’m using y-axis as the “upward” axis) x = r * sin(theta) * sin(phi) y = r * cos(phi) z = r * cos(theta) * sin(phi) ==> a-p = d * sin(theta) * sin(phi) b-q = d * cos(phi) c-r = d * cos(theta) * sin(phi) to look for the angles theta and phi, where 0 <= theta <= 2*PI 0 <= phi < PI Once found, the rendering occurs by rotating the entire scene phi degrees about the positive z-axis (starting from negative y-axis as 0 degrees), then rotate about the positive y-axis (starting from the positive z-axis as 0 degrees), then translate by (-a,-b,-c) (this moves the entire scene away from the camera positioned at the origin). Well, that was a lot of trouble. What was I trying to solve again? Oh yeah, that looking down and losing the "up" vector problem. Notice anything wrong in this implementation? The "up" vector of the camera was never considered. But figuring out all the math was fun... if only it solved something too... *sigh* [Note: all use of "degrees" in this article can be substituted with "radians", depending on your situation. Use accordingly.] Dissecting Trigonometric Particles part 2 – Axis functions This is a continuation of the explanation behind Trigonometric Particles. Read up on part 1 if you haven’t done so. Actually, there isn’t a clever coding construct I used to implement the axis functions. I just created a function that does a combination of polynomials and trigonometry functions. It looks something like this: float function AxisFunction(float t, float p0, float p1, float p2, float p3, float p4, float p5, float p6) { float result = 0.0; result += p0 + p1*t + p2*t*t + p3*t*t*t; result += p4*sin(t) + p5*cos(t) + p6*tan(t); return result; } The variable t is the time elapsed. The first part of the function is basically a cubic polynomial. The second part is a sum of the 3 standard trigonometric functions. Basically, I’m just passing in parameters which are the coefficients of the respective terms. To simulate a sphere, since I can’t quite summon the mental energy to switch between my preferred Y-axis-pointing-skywards and the more widely known Z-axis-pointing-skywards coordinate system, I’ll just use the more famous version to illustrate. So the axes are: x = r * sin(theta) * cos(phi) y = r * sin(theta) * sin(phi) z = r * cos(theta) To calculate the X, Y, Z coordinates, I just use different combinations of AxisFunction(). So x = AxisFunction(t, 0,0,0,0, r,0,0) * AxisFunction(t/2, 0,0,0,0, 0,1,0) y = AxisFunction(t, 0,0,0,0, r,0,0) * AxisFunction(t/2, 0,0,0,0, 1,0,0) z = AxisFunction(t, 0,0,0,0, 0,r,0) I’m passing t/2 for a different-valued phi. I can’t remember the exact multiple of t I used… so I’m just using t/2 as an example. For the sphere simulation, I was playing around with t to get the particles to swirl and end roughly near the top of the sphere. Took me a while to figure out the right magic number… To simulate a cylinder, just set polar coordinates on X and Y, then use Z as the height. x = AxisFunction(t, 0,0,0,0, 0,r,0) y = AxisFunction(t, 0,0,0,0, r,0,0) z = AxisFunction(t, 0,H,0,0, 0,0,0) where H corresponds to the speed value you want the particles to “climb” the cylinder. Again, much time taken to figure out the right magic number… As for the tornado simulation, notice that it’s similar to that of a cylinder, and the particles circle with a wider radius as they climb the cylinder. So the radius is now a function of the height. Actually, we just need the radius to increase as t increases, not necessarily as a function of height. So we apply a linear function to r. x = AF(t, 0,0,0,0, 0, r * AF(t, 0,L,0,0, 0,0,0), 0) y = AF(t, 0,0,0,0, r * AF(t, 0,L,0,0, 0,0,0), 0,0) z = AF(t, 0,H,0,0, 0,0,0) where L is some magic number such that the radius increases in a reasonable manner proportionate to the time elapsed (and effectively proportionate to the height). I have a confession to make. When I first introduced Trigonometric Particles, I said I used a W axis as well as composite functions. Well I truly remembered having a W axis, and I think I used it as such: x = W * AF(…) or maybe x = AF( … W, …) But I’m not using W in my explanations above. Hmm… somehow while writing the explanations, the W axis wasn’t required. As for composite functions, a short description. H is a composite function when H(x) = F(G(x)) meaning you calculate G(x) first, then calculate function F using G(x). That’s what we’re doing when we passed in one form of AxisFunction() to another AxisFunction() as a parameter. Well, my memory being foggy, I seem to recall having both W axis and the use of composite functions. It appears one can simulate the results with one or the other. Oh well, no one’s perfect… And the last simulation pattern, the sun’s surface? I think I used a pure polynomial. Quadratic, I think…
__label__pos
0.942329
comm package Version: v1.4.8 Latest Latest Warning This package is not in the latest version of its module. Go to latest Published: Jul 22, 2020 License: Apache-2.0 Imports: 27 Imported by: 0 Documentation Index Constants View Source const ( DefDialTimeout = time.Second * 3 DefConnTimeout = time.Second * 2 DefRecvBuffSize = 20 DefSendBuffSize = 20 ) Variables This section is empty. Functions func GenerateCertificatesOrPanic func GenerateCertificatesOrPanic() tls.Certificate GenerateCertificatesOrPanic generates a a random pair of public and private keys and return TLS certificate Types type AggregatedSendResult type AggregatedSendResult []SendResult AggregatedSendResult represents a slice of SendResults func (AggregatedSendResult) AckCount func (ar AggregatedSendResult) AckCount() int AckCount returns the number of successful acknowledgements func (AggregatedSendResult) NackCount func (ar AggregatedSendResult) NackCount() int NackCount returns the number of unsuccessful acknowledgements func (AggregatedSendResult) String func (ar AggregatedSendResult) String() string String returns a JSONed string representation of the AggregatedSendResult type ChannelDeMultiplexer type ChannelDeMultiplexer struct { // contains filtered or unexported fields } ChannelDeMultiplexer is a struct that can receive channel registrations (AddChannel) and publications (DeMultiplex) and it broadcasts the publications to registrations according to their predicate func NewChannelDemultiplexer func NewChannelDemultiplexer() *ChannelDeMultiplexer NewChannelDemultiplexer creates a new ChannelDeMultiplexer func (*ChannelDeMultiplexer) AddChannel func (m *ChannelDeMultiplexer) AddChannel(predicate common.MessageAcceptor) chan interface{} AddChannel registers a channel with a certain predicate func (*ChannelDeMultiplexer) Close func (m *ChannelDeMultiplexer) Close() Close closes this channel, which makes all channels registered before to close as well. func (*ChannelDeMultiplexer) DeMultiplex func (m *ChannelDeMultiplexer) DeMultiplex(msg interface{}) DeMultiplex broadcasts the message to all channels that were returned by AddChannel calls and that hold the respected predicates. type Comm type Comm interface { // GetPKIid returns this instance's PKI id GetPKIid() common.PKIidType // Send sends a message to remote peers Send(msg *proto.SignedGossipMessage, peers ...*RemotePeer) // SendWithAck sends a message to remote peers, waiting for acknowledgement from minAck of them, or until a certain timeout expires SendWithAck(msg *proto.SignedGossipMessage, timeout time.Duration, minAck int, peers ...*RemotePeer) AggregatedSendResult // Probe probes a remote node and returns nil if its responsive, // and an error if it's not. Probe(peer *RemotePeer) error // Handshake authenticates a remote peer and returns // (its identity, nil) on success and (nil, error) Handshake(peer *RemotePeer) (api.PeerIdentityType, error) // Accept returns a dedicated read-only channel for messages sent by other nodes that match a certain predicate. // Each message from the channel can be used to send a reply back to the sender Accept(common.MessageAcceptor) <-chan proto.ReceivedMessage // PresumedDead returns a read-only channel for node endpoints that are suspected to be offline PresumedDead() <-chan common.PKIidType // IdentitySwitch returns a read-only channel about identity change events IdentitySwitch() <-chan common.PKIidType // CloseConn closes a connection to a certain endpoint CloseConn(peer *RemotePeer) // Stop stops the module Stop() } Comm is an object that enables to communicate with other peers that also embed a CommModule. func NewCommInstance func NewCommInstance(s *grpc.Server, certs *common.TLSCertificates, idStore identity.Mapper, peerIdentity api.PeerIdentityType, secureDialOpts api.PeerSecureDialOpts, sa api.SecurityAdvisor, commMetrics *metrics.CommMetrics, config CommConfig, dialOpts ...grpc.DialOption) (Comm, error) NewCommInstance creates a new comm instance that binds itself to the given gRPC server type CommConfig type CommConfig struct { DialTimeout time.Duration // Dial timeout ConnTimeout time.Duration // Connection timeout RecvBuffSize int // Buffer size of received messages SendBuffSize int // Buffer size of sending messages } CommConfig is the configuration required to initialize a new comm type ConnConfig type ConnConfig struct { RecvBuffSize int SendBuffSize int } ConnConfig is the configuration required to initialize a new conn type MockStream type MockStream interface { proto.Gossip_GossipStreamClient } type ReceivedMessageImpl type ReceivedMessageImpl struct { *proto.SignedGossipMessage // contains filtered or unexported fields } ReceivedMessageImpl is an implementation of ReceivedMessage func (*ReceivedMessageImpl) Ack func (m *ReceivedMessageImpl) Ack(err error) Ack returns to the sender an acknowledgement for the message func (*ReceivedMessageImpl) GetConnectionInfo func (m *ReceivedMessageImpl) GetConnectionInfo() *proto.ConnectionInfo GetConnectionInfo returns information about the remote peer that send the message func (*ReceivedMessageImpl) GetGossipMessage func (m *ReceivedMessageImpl) GetGossipMessage() *proto.SignedGossipMessage GetGossipMessage returns the inner GossipMessage func (*ReceivedMessageImpl) GetSourceEnvelope func (m *ReceivedMessageImpl) GetSourceEnvelope() *proto.Envelope GetSourceEnvelope Returns the Envelope the ReceivedMessage was constructed with func (*ReceivedMessageImpl) Respond func (m *ReceivedMessageImpl) Respond(msg *proto.GossipMessage) Respond sends a msg to the source that sent the ReceivedMessageImpl type RemotePeer type RemotePeer struct { Endpoint string PKIID common.PKIidType } RemotePeer defines a peer's endpoint and its PKIid func (*RemotePeer) String func (p *RemotePeer) String() string String converts a RemotePeer to a string type SecurityAdvisor type SecurityAdvisor interface { // OrgByPeerIdentity returns the organization identity of the given PeerIdentityType OrgByPeerIdentity(api.PeerIdentityType) api.OrgIdentityType } SecurityAdvisor defines an external auxiliary object that provides security and identity related capabilities type SendResult type SendResult struct { RemotePeer // contains filtered or unexported fields } SendResult defines a result of a send to a remote peer func (SendResult) Error func (sr SendResult) Error() string Error returns the error of the SendResult, or an empty string if an error hasn't occurred Directories Path Synopsis Jump to Keyboard shortcuts ? : This menu / : Search site f or F : Jump to y or Y : Canonical URL
__label__pos
0.796355
RecitationMATLAB - y [ n ] = 1 . 3 sin (2 60 n/f s ) + 0 .... Info iconThis preview shows page 1. Sign up to view the full content. View Full Document Right Arrow Icon Rensselaer Electrical, Computer, and Systems Engineering Department ECSE 4500 Probability for Engineering Applications MATLAB Recitation Tuesday February 16, 2010 1. Before using MATLAB as a tool for various functions of interest in probability, we review a brief list of common commands: size , length , plot , axis , hold on , hold o f and for . .. end . Apart from these we also review how arrays and matrices are declared and used in MATLAB. 2. Next we look at the 3 M- f les available on the course LMS page. These include DeterFreq.m , RelFreq.m ,and RelativeFrequencies.m . P leaserunthecodeforsevera ld i f erent parameter values and explain the results. 3. (Convolution and Fourier Transform) Consider the following two discrete-time signals: x [ n ]= 0 . 6sin(2 π × 50 n/f s )+1 . 5sin(2 π × 70 n/f s )+0 . 8sin(2 π × 90 n/f s ) +1 . 2sin(2 π × 110 n/f s )+0 . 7sin(2 π × 130 n/f s ) ,n =1 , 2 ,..., 100 . 0 , Background image of page 1 This is the end of the preview. Sign up to access the rest of the document. Unformatted text preview: y [ n ] = 1 . 3 sin (2 60 n/f s ) + 0 . 3 sin (2 80 n/f s ) + 1 . 4 sin (2 100 n/f s ) +0 . 6 sin (2 120 n/f s ) + 1 . 5 sin (2 140 n/f s ) , n = 1 , 2 , ..., 80 . , otherwise. where f s = 1000 . Please do the following using MATLAB: a. Compute the convolution w of the two sequences x and y . b. Compute the 179-point fast Fourier transform X of the sequence x . c. Compute the 179-point fast Fourier transform Y of the sequence y . d. Calculate the product Z of X and Y (using element-by-element multiplication). e. Compute the inverse Fourier transform z of Z . f. Plot the sequences w and z in the same f gure. Please verify w = z and explain why. (Hint: The following commands may be useful here: conv , f t , i f t ) 1... View Full Document This note was uploaded on 04/15/2010 for the course ECSE 4500 taught by Professor Woods during the Spring '08 term at Rensselaer Polytechnic Institute. Ask a homework question - tutors are online
__label__pos
0.54048
Avatar of brunnock brunnock's solution to Collatz Conjecture in the JavaScript Track Published at Aug 24 2018 · 0 comments Instructions Test suite Solution The Collatz Conjecture or 3x+1 problem can be summarized as follows: Take any positive integer n. If n is even, divide n by 2 to get n / 2. If n is odd, multiply n by 3 and add 1 to get 3n + 1. Repeat the process indefinitely. The conjecture states that no matter which number you start with, you will always reach 1 eventually. Given a number n, return the number of steps required to reach 1. Examples Starting with n = 12, the steps would be as follows: 1. 12 2. 6 3. 3 4. 10 5. 5 6. 16 7. 8 8. 4 9. 2 10. 1 Resulting in 9 steps. So for input n = 12, the return value would be 9. Setup Go through the setup instructions for ECMAScript to install the necessary dependencies: http://exercism.io/languages/ecmascript Requirements Install assignment dependencies: $ npm install Making the test suite pass Execute the tests with: $ npm test In the test suites all tests but the first have been skipped. Once you get a test passing, you can enable the next one by changing xtest to test. Source An unsolved problem in mathematics named after mathematician Lothar Collatz https://en.wikipedia.org/wiki/3x_%2B_1_problem Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. collatz-conjecture.spec.js import { steps } from './collatz-conjecture'; describe('steps()', () => { test('zero steps for one', () => { expect(steps(1)).toEqual(0); }); xtest('divide if even', () => { expect(steps(16)).toEqual(4); }); xtest('even and odd steps', () => { expect(steps(12)).toEqual(9); }); xtest('Large number of even and odd steps', () => { expect(steps(1000000)).toEqual(152); }); xtest('zero is an error', () => { expect(() => { steps(0); }).toThrow(new Error('Only positive numbers are allowed')); }); xtest('negative value is an error', () => { expect(() => { steps(-15); }).toThrow(new Error('Only positive numbers are allowed')); }); }); function steps(n,nSteps=0) { if (n<1) { throw('Only positive numbers are allowed'); } else if (n===1) { return(nSteps); } else if (n%2===0) { n/=2; } else { n = n*3 +1; } return steps(n, ++nSteps); } module.exports={steps} Community comments Find this solution interesting? Ask the author a question to learn more. What can you learn from this solution? A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public. Here are some questions to help you reflect on this solution and learn the most from it. • What compromises have been made? • Are there new concepts here that you could read more about to improve your understanding?
__label__pos
0.995632
Validation with Regex (force users to write according to a specific format with a custom html input) Updated 1 week ago by Enrico A regular expression or simply regex is a sequence of characters that define a search pattern. Usually this pattern is used for operations as "find" on strings and for input validation. In Landbot you can use your own Javascript and the Design Advanced settings to have a custom code to validate your own inputs. In this article we will see how to validate a phone number of 9 digits with this format (123456789). Here is a demo showing how it works. To correctly set the Regex configuration in your flow, you will need to follow the below procedure. Your final flow will be similar to this: 1. After the Start Message, add a Send Message requesting the format that we want to use: 1. Go ahead adding a Buttons type question, paste the code you find below after the picture but do not add any buttons. ​Code: {html} ​<p class="inputLabel">Please type input</p><div class="inputSpace"><input class="inputArea" id="inputArea1" value="" /><button id="inputButton1"  onclick="onInput1()" class="inputButton" ><svg x="0px" y="0px" width="20px" height="20px" viewBox="0 0 535.5 535.5" style="enable-background:new 0 0 20 20;" xml:space="preserve"><g><g id="send"><polygon points="0,497.25 535.5,267.75 0,38.25 0,216.75 382.5,267.75 0,318.75"/></g></g></svg></button></div><p class="inputErrorMessage" id="errorMessageInput1"></p>{/html} 1.  At this point, add another Send a Message block where to display (if needed) the input that has been stored in the variable @variableinput1: 1. When we are done with the Builder, go the Advanced option of the Design section and add the following code: CSS code (Custom Style Sheet): .inputLabel {  margin-bottom: -10px; } .inputSpace {display: flex;  flex-direction: row;border: 1px none grey;  padding: 2px;  background-color: #fdf9f9;} .inputArea{flex-grow: 2;  background-color: #fdf9f9;  border: none} .inputButton{  border: none;  background-color: #fdf9f9; } .inputErrorMessage{color: red;  text-align: center;  margin-top: 1em;  font-size: 0.8em;} JS code (Custom scripts): <script>var regexInput1 = /^[0-9]{9}$/; function onInput1(){        var value1 = window.document.getElementById("inputArea1").value;    if (value1.match(regexInput1)) {        window.document.getElementById("errorMessageInput1").innerHTML = ""        submitInput1(value1)    } else {        window.document.getElementById("errorMessageInput1").innerHTML = "Input format is not valid, please repeat"    }}     function submitInput1(inputValue) {    Landbot.exec('landbot-custom-data', { variableinput1: inputValue })   Landbot.exec('landbot-msg-send', {        message:"Input Validated",        text: '***',        payload:'****',        type: 'button',    }); }</script> 1. Double check that you have correctly copied and pasted all the codes and give it a try! These scripts and how to's are not native functionalities. Landbot won't be able to support, help or guarantee these scripts and how to's. These Workarounds and How to's are for developers, as a learning and example material on how to extend or modify some of the platform limitations.  Due to platform updates, some scripts might stop working in the future.Please, note that in case of Scripts and Workaround the Custom Success Team can deliver limited support. How did we do?
__label__pos
0.979982
Примитивные типы данных Пришло время познакомиться с примитивными типами данных в JavaScript. В самом простом случае, когда мы объявляем переменную вот так: let a = 2; то переменная принимает числовой тип (number). Этот пример показывает, что тип переменной определяется типом данных, которые мы ей присваиваем. Если переменной присвоить строку: let b = "Строка"; то переменная b принимает строковый тип. В JavaScript существует семь основных типов данных. Рассмотрим их по порядку. Числовой тип (number) Числовой тип данных представляет как целочисленные значения, так и числа с плавающей точкой. Например, обе эти переменные будут относиться к числовому типу: let a = 5; let b = 7.23; JavaScript «знает» пять основных типов числовых литералов: • десятичный – целое число (например, 0, 5, -10, -100, 56); • приближенные к вещественным – приблизительные вещественные числа (например, 6.7, 8.54, -10.34); • экспоненциальный (научный) – с использованием буквы ‘e’ (например, 10 = 1e1, 20 = 2e1, 25000 = 25e3, 8700 = 8.7e3); • восьмиричная: 0o777; • шестнадцатиричная: 0xff24f. Однако, на практике чаще всего используются целые и приближенные к вещественным. Оператор typeof Чтобы узнать тип переменной используется оператор typeof, который имеет такой синтаксис: typeof <переменная>; или typeof(<переменная>); его можно вызывать как со скобками, так и без скобок. Обычно используют первый вариант. Выведем тип переменной a: console.log(typeof a); Мы видим значение number – числовой тип. Infinity и NaN Кроме обычных чисел, существуют так называемые «специальные числовые значения», которые относятся к этому же типу данных: Infinity, -Infinity и NaN. Infinity представляет собой математическую бесконечность ∞. Это особое значение, которое больше любого числа. Мы можем получить его в результате деления на ноль: let c = 1/0; или задать его явно: let d = Infinity; let d2 = -Infinity; Мы можем также получить бесконечность, если попытаемся записать в переменную очень большое число, которое выходит за пределы представления чисел в JavaScript. Например, такое: let inf = 1.0e1000; Следующее значение NaN (от англ. Not a Number – не число) означает вычислительную ошибку. Это результат неправильной или неопределённой математической операции, например: let c = "строка"/2; Значение NaN «прилипчиво». Любая операция с NaN возвращает NaN: let c = "строка"/2 + 2; Значения Infinity и NaN хотя и относятся к числовым типам, но скорее являются индикаторами, говорящими разработчику скрипта что пошло не так. Строковый тип (string) Как мы говорили на предыдущем занятии, строки можно задавать через такие кавычки: let msg1 = "строка 1"; let msg2 = 'строка 2'; let msg3 = `строка 3`; Двойные или одинарные кавычки являются «простыми», между ними нет разницы в JavaScript. Обратные кавычки (апострофы) имеют «расширенный функционал» и были введены в ES6. Они позволяют встраивать выражения в строку, заключая их в ${…}. Например, так: let msg3 = `Значение a = ${a}`; Здесь вместо ${a} будет подставлено значение переменной a и в консоле увидим «Значение a = 5». Вместо переменной можно записать любое выражение языка JavaScript: let msg3 = `Значение a = ${1+2}`; Получим строку «Значение a = 3». Все это работает только с обратными кавычками. Если их заменить на простые, то никакой подстановки не произойдет: let msg3 = 'Значение a = ${a}'; Тем, кто знаком с другими языками программирования следует знать, что в JavaScript нет типа данных для отдельного символа (типа char). Здесь есть только строки и даже один символ – это строка из одного символа. А как быть, если мы хотим в строке записать кавычки? Например, так: let msg1 = "строка "привет""; Есть несколько способов это сделать. Первый – заменить двойные кавычки всей строки на одинарные: let msg1 = 'строка "привет" '; Второй способ – использовать так называемое экранирование символов: let msg1 = "строка \"привет\""; мы здесь перед каждой кавычкой внутри строки поставили обратный слеш. Это называется экранированием символов. На практике используются оба способа, так что выбирайте любой удобный для себя. Кстати, если нужно просто отобразить обратный слеш, то его следует записать так: let msg1 = "строка \\"; Булевый (логический) тип Булевый тип (boolean) может принимать только два значения: true (истина) и false (ложь). Такой тип, как правило, используется для хранения значений да/нет: true значит «да, правильно», а false значит «нет, не правильно». Например: let isWin = true, isCheckedField = false; Булевые значения также могут быть получены из результатов сравнения: let isGreater = 4 > 1; и часто применяются в условных операторах, о которых мы будем говорить на последующих занятиях. Значение «null» Специальное значение null не относится ни к одному из типов, описанных выше. Оно формирует отдельный тип, который содержит только значение null: let idProcess = null; В JavaScript null не является «ссылкой на несуществующий объект» или «нулевым указателем», как в некоторых других языках. Это просто специальное значение, которое представляет собой «ничего», «пусто» или «значение неизвестно». Значение «undefined» Это свой тип данных, который имеет только одно значение undefined, означающее, что значение не было присвоено. Если переменная объявлена, но ей не присвоено никакого значения, то её значением будет undefined: let arg; По идее мы можем присвоить значение undefined любой переменной: let a = undefined; Но так делать не рекомендуется. Если нам нужно отметить, что переменная не содержит данных, то для этого используется значение null, а undefined – только для проверок: была ли переменная инициализирована или по каким-то причинам ей «забыли» присвоить значение. Тип Symbol Это новый тип данных (symbol), который впервые появился в спецификации ES6. Он используется для создания уникальных идентификаторов. Например, так: let id = Symbol(); И в большей степени он удобен для дальнейшего развития JavaScript. Чтобы можно было добавлять новые идентификаторы, не меняя код, в котором он уже мог использоваться. Символы создаются конструктором Symbol() и могут дополняться необязательным описанием: let id2 = Symbol("id2"); Их уникальность можно проверить оператором идентичности, о котором мы будем говорить на следующих занятиях. Здесь приведу лишь пример: console.log(id === id2); В некоторой степени они похожи на объекты, но относятся к примитивным типам. Если сейчас вам не совсем понятно, что такое Symbol, просто пропустите этот момент. Когда придет время для его использования, все встанет на свои места. Видео по теме
__label__pos
0.707623
Drake context.h Go to the documentation of this file. 1 #pragma once 2  3 #include <memory> 4 #include <utility> 5  14  15 namespace drake { 16 namespace systems { 17  18 /// Contains information about the independent variable including time and 19 /// step number. 20 // TODO(sherm1) Add step information. 21 template <typename T> 22 struct StepInfo { 23  /// The time, in seconds. For typical T implementations based on 24  /// doubles, time resolution will gradually degrade as time increases. 25  // TODO(sherm1): Consider whether this is sufficiently robust. 26  T time_sec{0.0}; 27 }; 28  29 /// %Context is an abstract class template that represents all the typed values 30 /// that are used in a System's computations: time, numeric-valued input ports, 31 /// numerical state, and numerical parameters. There are also type-erased 32 /// abstract state variables, abstract-valued input ports, abstract parameters, 33 /// and a double accuracy setting. The framework provides two concrete 34 /// subclasses of %Context: LeafContext (for leaf Systems) and DiagramContext 35 /// (for composite System Diagrams). Users are forbidden to extend 36 /// DiagramContext and are discouraged from subclassing LeafContext. 37 /// 38 /// @tparam T The mathematical type of the context, which must be a valid Eigen 39 /// scalar. 40 template <typename T> 41 class Context : public ContextBase { 42  public: 43  /// @name Does not allow copy, move, or assignment. 44  //@{ 45  // Copy constructor is protected for use in implementing Clone(). 46  Context(Context&&) = delete; 47  Context& operator=(const Context&) = delete; 48  Context& operator=(Context&&) = delete; 49  //@} 50  51  /// Returns a deep copy of this Context. 52  // This is just an intentional shadowing of the base class method to return 53  // a more convenient type. 54  std::unique_ptr<Context<T>> Clone() const { 55  return dynamic_pointer_cast_or_throw<Context<T>>(ContextBase::Clone()); 56  } 57  58  ~Context() override = default; 59  60  // ========================================================================= 61  // Accessors and Mutators for Time. 62  63  /// Returns the current time in seconds. 64  const T& get_time() const { return get_step_info().time_sec; } 65  66  /// Set the current time in seconds. 67  virtual void set_time(const T& time_sec) { 68  step_info_.time_sec = time_sec; 69  } 70  71  // ========================================================================= 72  // Accessors and Mutators for State. 73  74  virtual const State<T>& get_state() const = 0; 75  virtual State<T>& get_mutable_state() = 0; 76  77  /// Returns true if the Context has no state. 78  bool is_stateless() const { 79  const int nxc = get_continuous_state().size(); 80  const int nxd = get_num_discrete_state_groups(); 81  const int nxa = get_num_abstract_states(); 82  return nxc == 0 && nxd == 0 && nxa == 0; 83  } 84  85  /// Returns true if the Context has continuous state, but no discrete or 86  /// abstract state. 88  const int nxc = get_continuous_state().size(); 89  const int nxd = get_num_discrete_state_groups(); 90  const int nxa = get_num_abstract_states(); 91  return nxc > 0 && nxd == 0 && nxa == 0; 92  } 93  94  /// Returns true if the Context has discrete state, but no continuous or 95  /// abstract state. 96  bool has_only_discrete_state() const { 97  const int nxc = get_continuous_state().size(); 98  const int nxd = get_num_discrete_state_groups(); 99  const int nxa = get_num_abstract_states(); 100  return nxd > 0 && nxc == 0 && nxa == 0; 101  } 102  103  /// Returns the total dimension of all of the basic vector states (as if they 104  /// were muxed). 105  /// @throws std::runtime_error if the system contains any abstract state. 106  int get_num_total_states() const { 107  DRAKE_THROW_UNLESS(get_num_abstract_states() == 0); 108  int count = get_continuous_state().size(); 109  for (int i = 0; i < get_num_discrete_state_groups(); i++) 110  count += get_discrete_state(i).size(); 111  return count; 112  } 113  114  /// Sets the continuous state to @p xc, deleting whatever was there before. 115  void set_continuous_state(std::unique_ptr<ContinuousState<T>> xc) { 116  get_mutable_state().set_continuous_state(std::move(xc)); 117  } 118  119  /// Returns a mutable reference to the continuous component of the state, 120  /// which may be of size zero. 122  return get_mutable_state().get_mutable_continuous_state(); 123  } 124  125  /// Returns a mutable reference to the continuous state vector, devoid 126  /// of second-order structure. The vector may be of size zero. 128  return get_mutable_continuous_state().get_mutable_vector(); 129  } 130  131  /// Returns a const reference to the continuous component of the state, 132  /// which may be of size zero. 134  return get_state().get_continuous_state(); 135  } 136  137  /// Returns a reference to the continuous state vector, devoid of second-order 138  /// structure. The vector may be of size zero. 140  return get_continuous_state().get_vector(); 141  } 142  143  /// Returns the number of vectors (groups) in the discrete state. 145  return get_state().get_discrete_state().num_groups(); 146  } 147  148  /// Returns a reference to the entire discrete state, which may consist of 149  /// multiple discrete state vectors (groups). 151  return get_state().get_discrete_state(); 152  } 153  154  /// Returns a reference to the _only_ discrete state vector. The vector may be 155  /// of size zero. 156  /// @pre There is only one discrete state group. 158  return get_discrete_state().get_vector(); 159  } 160  161  /// Returns a mutable reference to the discrete component of the state, 162  /// which may be of size zero. 164  return get_mutable_state().get_mutable_discrete_state(); 165  } 166  167  /// Returns a mutable reference to the _only_ discrete state vector. 168  /// @sa get_discrete_state_vector(). 169  /// @pre There is only one discrete state group. 171  return get_mutable_discrete_state().get_mutable_vector(); 172  } 173  174  /// Returns a mutable reference to group (vector) @p index of the discrete 175  /// state. 176  /// @pre @p index must identify an existing group. 178  DiscreteValues<T>& xd = get_mutable_discrete_state(); 179  return xd.get_mutable_vector(index); 180  } 181  182  /// Sets the discrete state to @p xd, deleting whatever was there before. 183  void set_discrete_state(std::unique_ptr<DiscreteValues<T>> xd) { 184  get_mutable_state().set_discrete_state(std::move(xd)); 185  } 186  187  /// Returns a const reference to group (vector) @p index of the discrete 188  /// state. 189  /// @pre @p index must identify an existing group. 190  const BasicVector<T>& get_discrete_state(int index) const { 191  const DiscreteValues<T>& xd = get_state().get_discrete_state(); 192  return xd.get_vector(index); 193  } 194  195  /// Returns the number of elements in the abstract state. 197  return get_state().get_abstract_state().size(); 198  } 199  200  /// Returns a const reference to the abstract component of the state, which 201  /// may be of size zero. 203  return get_state().get_abstract_state(); 204  } 205  206  /// Returns a mutable reference to the abstract component of the state, 207  /// which may be of size zero. 209  return get_mutable_state().get_mutable_abstract_state(); 210  } 211  212  /// Returns a mutable reference to element @p index of the abstract state. 213  /// @pre @p index must identify an existing element. 214  template <typename U> 216  AbstractValues& xa = get_mutable_abstract_state(); 217  return xa.get_mutable_value(index).GetMutableValue<U>(); 218  } 219  220  /// Sets the abstract state to @p xa, deleting whatever was there before. 221  void set_abstract_state(std::unique_ptr<AbstractValues> xa) { 222  get_mutable_state().set_abstract_state(std::move(xa)); 223  } 224  225  /// Returns a const reference to the abstract component of the 226  /// state at @p index. 227  /// @pre @p index must identify an existing element. 228  template <typename U> 229  const U& get_abstract_state(int index) const { 230  const AbstractValues& xa = get_state().get_abstract_state(); 231  return xa.get_value(index).GetValue<U>(); 232  } 233  234  // ========================================================================= 235  // Accessors and Mutators for Input. 236  237  // Allow access to the base class method (takes an AbstractValue). 239  240  /// Connects the input port at @p index to a FixedInputPortValue with 241  /// the given vector @p vec. Aborts if @p index is out of range. 242  /// Returns a reference to the allocated FixedInputPortValue. The 243  /// reference will remain valid until this input port's value source is 244  /// replaced or the %Context is destroyed. You may use that reference to 245  /// modify the input port's value using the appropriate 246  /// FixedInputPortValue method, which will ensure that invalidation 247  /// notifications are delivered. 250  index, std::make_unique<Value<BasicVector<T>>>(vec.Clone())); 251  } 252  253  /// Same as above method but starts with an Eigen vector whose contents are 254  /// used to initialize a BasicVector in the FixedInputPortValue. 256  int index, const Eigen::Ref<const VectorX<T>>& data) { 257  return FixInputPort(index, BasicVector<T>(data)); 258  } 259  260  /// Same as the above method that takes a `const BasicVector<T>&`, but here 261  /// the vector is passed by unique_ptr instead of by const reference. The 262  /// caller must not retain any aliases to `vec`; within this method, `vec` 263  /// is cloned and then deleted. 264  /// @note This overload will become deprecated in the future, because it can 265  /// mislead users to believe that they can retain an alias of `vec` to mutate 266  /// the fixed value during a simulation. Callers should prefer to use one of 267  /// the other overloads instead. 269  int index, std::unique_ptr<BasicVector<T>> vec) { 270  DRAKE_THROW_UNLESS(vec.get() != nullptr); 271  return FixInputPort(index, *vec); 272  } 273  274  // ========================================================================= 275  // Accessors and Mutators for Parameters. 276  277  virtual const Parameters<T>& get_parameters() const = 0; 278  virtual Parameters<T>& get_mutable_parameters() = 0; 279  280  /// Returns the number of vector-valued parameters. 282  return get_parameters().num_numeric_parameters(); 283  } 284  285  /// Returns a const reference to the vector-valued parameter at @p index. 286  /// Asserts if @p index doesn't exist. 287  const BasicVector<T>& get_numeric_parameter(int index) const { 288  return get_parameters().get_numeric_parameter(index); 289  } 290  291  /// Returns a mutable reference to element @p index of the vector-valued 292  /// parameters. Asserts if @p index doesn't exist. 294  return get_mutable_parameters().get_mutable_numeric_parameter(index); 295  } 296  297  /// Returns the number of abstract-valued parameters. 299  return get_parameters().num_abstract_parameters(); 300  } 301  302  /// Returns a const reference to the abstract-valued parameter at @p index. 303  /// Asserts if @p index doesn't exist. 304  const AbstractValue& get_abstract_parameter(int index) const { 305  return get_parameters().get_abstract_parameter(index); 306  } 307  308  /// Returns a mutable reference to element @p index of the abstract-valued 309  /// parameters. Asserts if @p index doesn't exist. 311  return get_mutable_parameters().get_mutable_abstract_parameter(index); 312  } 313  314  // ========================================================================= 315  // Accessors and Mutators for Accuracy. 316  317  /// Records the user's requested accuracy. If no accuracy is requested, 318  /// computations are free to choose suitable defaults, or to refuse to 319  /// proceed without an explicit accuracy setting. 320  /// 321  /// Requested accuracy is stored in the %Context for two reasons: 322  /// - It permits all computations performed over a System to see the _same_ 323  /// accuracy request since accuracy is stored in one shared place, and 324  /// - it allows us to invalidate accuracy-dependent cached computations when 325  /// the requested accuracy has changed. 326  /// 327  /// The accuracy of a complete simulation or other numerical study depends on 328  /// the accuracy of _all_ contributing computations, so it is important that 329  /// each computation is done in accordance with the overall requested 330  /// accuracy. Some examples of where this is needed: 331  /// - Error-controlled numerical integrators use the accuracy setting to 332  /// decide what step sizes to take. 333  /// - The Simulator employs a numerical integrator, but also uses accuracy to 334  /// decide how precisely to isolate witness function zero crossings. 335  /// - Iterative calculations reported as results or cached internally depend 336  /// on accuracy to decide how strictly to converge the results. Examples of 337  /// these are: constraint projection, calculation of distances between 338  /// smooth shapes, and deformation calculations for soft contact. 339  /// 340  /// The common thread among these examples is that they all share the 341  /// same %Context, so by keeping accuracy here it can be used effectively to 342  /// control all accuracy-dependent computations. 343  // TODO(edrumwri) Invalidate all cached accuracy-dependent computations, and 344  // propagate accuracy to all subcontexts in a diagram context. 345  virtual void set_accuracy(const optional<double>& accuracy) { 346  accuracy_ = accuracy; 347  } 348  349  /// Returns the accuracy setting (if any). 350  /// @see set_accuracy() for details. 351  const optional<double>& get_accuracy() const { return accuracy_; } 352  353  // ========================================================================= 354  // Miscellaneous Public Methods 355  356  /// Returns a deep copy of this Context's State. 357  std::unique_ptr<State<T>> CloneState() const { 358  return DoCloneState(); 359  } 360  361  /// Initializes this context's time, state, and parameters from the real 362  /// values in @p source, regardless of this context's scalar type. 363  /// Requires a constructor T(double). 364  // TODO(sherm1) Should treat fixed input port values same as parameters. 366  set_time(T(source.get_time())); 367  set_accuracy(source.get_accuracy()); 368  get_mutable_state().SetFrom(source.get_state()); 369  get_mutable_parameters().SetFrom(source.get_parameters()); 370  371  // TODO(sherm1) Fixed input copying goes here. 372  } 373  374  protected: 375  Context() = default; 376  377  /// Copy constructor takes care of base class and `Context<T>` data members. 378  /// Derived classes must implement copy constructors that delegate to this 379  /// one for use in their DoCloneWithoutPointers() implementations. 380  // Default implementation invokes the base class copy constructor and then 381  // the local member copy constructors. 382  Context(const Context<T>&) = default; 383  384  /// Clones a context but without any of its internal pointers. 385  // Structuring this as a static method permits a DiagramContext to invoke 386  // this protected functionality on its children. 387  // This is just an intentional shadowing of the base class method to return a 388  // more convenient type. 389  static std::unique_ptr<Context<T>> CloneWithoutPointers( 390  const Context<T>& source) { 391  return dynamic_pointer_cast_or_throw<Context<T>>( 393  } 394  395  /// Override to return the appropriate concrete State class to be returned 396  /// by CloneState(). 397  virtual std::unique_ptr<State<T>> DoCloneState() const = 0; 398  399  /// Returns a const reference to current time and step information. 400  const StepInfo<T>& get_step_info() const { return step_info_; } 401  402  private: 403  // Current time and step information. 404  StepInfo<T> step_info_; 405  406  // Accuracy setting. 407  optional<double> accuracy_; 408 }; 409  410 } // namespace systems 411 } // namespace drake AbstractValues is a container for non-numerical state and parameters. Definition: abstract_values.h:18 const AbstractValue & get_abstract_parameter(int index) const Returns a const reference to the abstract-valued parameter at index. Definition: context.h:304 DiscreteValues< T > & get_mutable_discrete_state() Returns a mutable reference to the discrete component of the state, which may be of size zero... Definition: context.h:163 DiscreteValues is a container for numerical but non-continuous state and parameters. Definition: discrete_values.h:33 const AbstractValues & get_abstract_state() const Returns a const reference to the abstract component of the state, which may be of size zero... Definition: context.h:202 std::unique_ptr< Context< T > > Clone() const Returns a deep copy of this Context. Definition: context.h:54 FixedInputPortValue & FixInputPort(int index, std::unique_ptr< BasicVector< T >> vec) Same as the above method that takes a const BasicVector<T>&, but here the vector is passed by unique_... Definition: context.h:268 int i Definition: reset_after_move_test.cc:51 const BasicVector< T > & get_numeric_parameter(int index) const Returns a const reference to the vector-valued parameter at index. Definition: context.h:287 bool has_only_discrete_state() const Returns true if the Context has discrete state, but no continuous or abstract state. Definition: context.h:96 virtual const State< T > & get_state() const =0 Provides a convenient wrapper to throw an exception when a condition is unmet. Definition: automotive_demo.cc:90 const BasicVector< T > & get_discrete_state(int index) const Returns a const reference to group (vector) index of the discrete state. Definition: context.h:190 void set_discrete_state(std::unique_ptr< DiscreteValues< T >> xd) Sets the discrete state to xd, deleting whatever was there before. Definition: context.h:183 int num_abstract_parameters() const Returns the number of abstract-valued parameters. Definition: context.h:298 const VectorBase< T > & get_continuous_state_vector() const Returns a reference to the continuous state vector, devoid of second-order structure. Definition: context.h:139 Context is an abstract class template that represents all the typed values that are used in a System&#39;... Definition: context.h:41 Eigen::Matrix< Scalar, Eigen::Dynamic, 1 > VectorX A column vector of any size, templated on scalar type. Definition: eigen_types.h:46 static std::unique_ptr< ContextBase > CloneWithoutPointers(const ContextBase &source) Clones a context but without copying any of its internal pointers; the clone&#39;s pointers are set to nu... Definition: context_base.h:238 void set_continuous_state(std::unique_ptr< ContinuousState< T >> xc) Sets the continuous state to xc, deleting whatever was there before. Definition: context.h:115 BasicVector< T > & get_mutable_discrete_state_vector() Returns a mutable reference to the only discrete state vector. Definition: context.h:170 VectorBase is an abstract base class that real-valued signals between Systems and real-valued System ... Definition: vector_base.h:27 #define DRAKE_THROW_UNLESS(condition) Evaluates condition and iff the value is false will throw an exception with a message showing at leas... Definition: drake_throw.h:23 virtual const Parameters< T > & get_parameters() const =0 std::unique_ptr< BasicVector< T > > Clone() const Copies the entire vector to a new BasicVector, with the same concrete implementation type... Definition: basic_vector.h:130 FixedInputPortValue & FixInputPort(int index, std::unique_ptr< AbstractValue > value) Connects the input port at index to a FixedInputPortValue with the given abstract value... Definition: context_base.cc:54 static std::unique_ptr< Context< T > > CloneWithoutPointers(const Context< T > &source) Clones a context but without any of its internal pointers. Definition: context.h:389 stx::optional< T > optional Definition: drake_optional.h:22 std::unique_ptr< ContextBase > Clone() const Creates an identical copy of the concrete context object. Definition: context_base.cc:11 const T & GetValue() const Returns the value wrapped in this AbstractValue, which must be of exactly type T. ... Definition: value.h:142 Provides non-templatized functionality shared by the templatized derived classes. ... Definition: context_base.h:38 const BasicVector< T > & get_discrete_state_vector() const Returns a reference to the only discrete state vector. Definition: context.h:157 U & get_mutable_abstract_state(int index) Returns a mutable reference to element index of the abstract state. Definition: context.h:215 T time_sec The time, in seconds. Definition: context.h:26 BasicVector< T > & get_mutable_vector() Returns a mutable reference to the BasicVector containing the values for the only group... Definition: discrete_values.h:112 FixedInputPortValue & FixInputPort(int index, const Eigen::Ref< const VectorX< T >> &data) Same as above method but starts with an Eigen vector whose contents are used to initialize a BasicVec... Definition: context.h:255 void SetTimeStateAndParametersFrom(const Context< double > &source) Initializes this context&#39;s time, state, and parameters from the real values in source, regardless of this context&#39;s scalar type. Definition: context.h:365 virtual void set_time(const T &time_sec) Set the current time in seconds. Definition: context.h:67 const U & get_abstract_state(int index) const Returns a const reference to the abstract component of the state at index. Definition: context.h:229 int get_num_discrete_state_groups() const Returns the number of vectors (groups) in the discrete state. Definition: context.h:144 bool has_only_continuous_state() const Returns true if the Context has continuous state, but no discrete or abstract state. Definition: context.h:87 Provides drake::optional as an alias for the appropriate implementation of std::optional or std::expe... State is a container for all the data comprising the complete state of a particular System at a parti... Definition: state.h:27 int num_numeric_parameters() const Returns the number of vector-valued parameters. Definition: context.h:281 const StepInfo< T > & get_step_info() const Returns a const reference to current time and step information. Definition: context.h:400 const T & get_time() const Returns the current time in seconds. Definition: context.h:64 VectorBase< T > & get_mutable_continuous_state_vector() Returns a mutable reference to the continuous state vector, devoid of second-order structure... Definition: context.h:127 BasicVector is a semantics-free wrapper around an Eigen vector that satisfies VectorBase. Definition: basic_vector.h:25 AbstractValue & get_mutable_abstract_parameter(int index) Returns a mutable reference to element index of the abstract-valued parameters. Definition: context.h:310 A fully type-erased container class. Definition: value.h:101 AbstractValues & get_mutable_abstract_state() Returns a mutable reference to the abstract component of the state, which may be of size zero... Definition: context.h:208 const AbstractValue & get_value(int index) const Returns the element of AbstractValues at the given index, or aborts if the index is out-of-bounds... Definition: abstract_values.cc:33 BasicVector< T > & get_mutable_numeric_parameter(int index) Returns a mutable reference to element index of the vector-valued parameters. Definition: context.h:293 ContinuousState< T > & get_mutable_continuous_state() Returns a mutable reference to the continuous component of the state, which may be of size zero... Definition: context.h:121 Parameters is a container for variables that parameterize a System so that it can represent a family ... Definition: parameters.h:26 int get_num_total_states() const Returns the total dimension of all of the basic vector states (as if they were muxed). Definition: context.h:106 BasicVector< T > & get_mutable_discrete_state(int index) Returns a mutable reference to group (vector) index of the discrete state. Definition: context.h:177 const optional< double > & get_accuracy() const Returns the accuracy setting (if any). Definition: context.h:351 virtual void set_accuracy(const optional< double > &accuracy) Records the user&#39;s requested accuracy. Definition: context.h:345 FixedInputPortValue & FixInputPort(int index, const BasicVector< T > &vec) Connects the input port at index to a FixedInputPortValue with the given vector vec. Definition: context.h:248 Contains information about the independent variable including time and step number. Definition: context.h:22 int get_num_abstract_states() const Returns the number of elements in the abstract state. Definition: context.h:196 ContinuousState is a view of, and optionally a container for, all the continuous state variables xc o... Definition: continuous_state.h:76 const DiscreteValues< T > & get_discrete_state() const Returns a reference to the entire discrete state, which may consist of multiple discrete state vector... Definition: context.h:150 A container class for an arbitrary type T. Definition: value.h:252 AbstractValue & get_mutable_value(int index) Returns the element of AbstractValues at the given index, or aborts if the index is out-of-bounds... Definition: abstract_values.cc:39 A FixedInputPortValue encapsulates a vector or abstract value for use as an internal value source for... Definition: fixed_input_port_value.h:35 const BasicVector< T > & get_vector() const Returns a const reference to the BasicVector containing the values for the only group. Definition: discrete_values.h:105 const ContinuousState< T > & get_continuous_state() const Returns a const reference to the continuous component of the state, which may be of size zero... Definition: context.h:133 std::unique_ptr< State< T > > CloneState() const Returns a deep copy of this Context&#39;s State. Definition: context.h:357 bool is_stateless() const Returns true if the Context has no state. Definition: context.h:78 void set_abstract_state(std::unique_ptr< AbstractValues > xa) Sets the abstract state to xa, deleting whatever was there before. Definition: context.h:221 int data Definition: value_test.cc:20 T & GetMutableValue() Returns the value wrapped in this AbstractValue, which must be of exactly type T. ... Definition: value.h:171
__label__pos
0.850228
react-component-export-image TypeScript icon, indicating that this package has built-in type declarations 1.0.6 • Public • Published react-component-export-image Demo Codesandbox Introduction • Export component as jpeg, png or pdf • Each export expect a {React.RefObject} node, optional fileName, and optional html2CanvasOptions object which you wish to pass it to html2Canvas • exportComponentAsPDF also accepts an optional pdfOptions object with these optional fields {w, h, x, y, unit, orientation, pdfFormat} w = 100 (Width in pixels - defaults to the width of the element) h = 50 (Height in pixels - defaults to the height of the element) x = 0 (X Coordinate in pixels against left edge of the page - defaults to 0) y = 0 (Y Coordinate in pixels against left edge of the page - defaults to 0) unit = 'px' (Measurement unit (base unit) to be used when coordinates are specified. Possible values are "pt" (points), "mm", "cm", "m", "in" or "px". - defaults to 'mm') - if you are trying to get the pdf to fill up the exact space, try setting unit to "px" orientation = 'p' (portrait) OR 'l' (landscape) - defaults: - landscape if width > height or - portrait if height > width The format of the PDF. Can be: a0 - a10 b0 - b10 c0 - c10 dl letter government-letter legal junior-legal ledger tabloid credit-card Default is "a4". If you want to use your own format just pass instead of one of the above predefined formats the size as an number-array, e.g. [595.28, 841.89] How to Upgrade The previous way of using an export looked like this: exportComponentAsJPEG(node, fileName, type, backgroundColor, options) The new way: pass node & an optional object with only the fields you need. • backgroundColor is no longer accepted in this main object, but is accepted in the "html2CanvasOptions" object, which is passed directly to html2canvas • type is no longer accepted - JPG will always produce JPG, PNG => PNG, PDF => PDF exportComponentAsJPEG(node, {fileName, html2CanvasOptions}) • exportComponentAsPDF also accepts an additional pdfOptions object (see introduction) exportComponentAsPDF(node, {fileName, html2CanvasOptions, pdfOptions}) Code Samples Component import { exportComponentAsJPEG, exportComponentAsPDF, exportComponentAsPNG } from 'react-component-export-image'; import React from 'react'; class ComponentToPrint extends React.Component { render() { return <div>Hello World</div>; } } export default class MyComponent extends React.Component { constructor(props) { super(props); this.componentRef = React.createRef(); } render() { return ( <React.Fragment> <ComponentToPrint ref={this.componentRef} /> <button onClick={() => exportComponentAsJPEG(this.componentRef)}> Export As JPEG </button> <button onClick={() => exportComponentAsPDF(this.componentRef)}> Export As PDF </button> <button onClick={() => exportComponentAsPNG(this.componentRef)}> Export As PNG </button> </React.Fragment> ); } } Function component import { exportComponentAsJPEG, exportComponentAsPDF, exportComponentAsPNG } from 'react-component-export-image'; import React, { useRef } from 'react'; const ComponentToPrint = React.forwardRef((props, ref) => ( <div ref={ref}>Hello World</div> )); const MyComponent = () => { const componentRef = useRef(); return ( <React.Fragment> <ComponentToPrint ref={componentRef} /> <button onClick={() => exportComponentAsJPEG(componentRef)}> Export As JPEG </button> <button onClick={() => exportComponentAsPDF(componentRef)}> Export As PDF </button> <button onClick={() => exportComponentAsPNG(componentRef)}> Export As PNG </button> </React.Fragment> ); }; export default MyComponent; Installation npm i react-component-export-image or yarn add react-component-export-image Install npm i react-component-export-image DownloadsWeekly Downloads 5,574 Version 1.0.6 License MIT Unpacked Size 480 kB Total Files 6 Last publish Collaborators • avatar
__label__pos
0.752068
Order Of Operations Example 1 Here is an example of how to use the order of operations.  Remember to read the lesson on this topic. Basic steps to follow: 1. First know the meaning of PEMDAS- Parentheses, Exponents(powers), Multiplication, Division, Addition, Subtraction 2. Always start inside of parentheses working from the inside out and left to right 3. Continue to simplify the expression from left to right keeping in mind PEMDAS and that you do multiplication or division first from left to right and addition or subtraction whatever you see from left to right Numbers and Operations-order-of-operations-1   Important habits to master math: 1. write out all steps 2. be very neat 3. use pencil not pen 4. review your work as your go 5. make sure you know the basics like fractions, positive and negative numbers and order of operations Comments are closed.
__label__pos
0.999967
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.         circuitpython/py/vm.c 1485 lines 64 KiB /* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George * Copyright (c) 2014 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include <assert.h> #include "py/emitglue.h" #include "py/objtype.h" #include "py/runtime.h" #include "py/bc0.h" #include "py/bc.h" #if 0 #define TRACE(ip) printf("sp=%d ", (int)(sp - &code_state->state[0] + 1)); mp_bytecode_print2(ip, 1, code_state->fun_bc->const_table); #else #define TRACE(ip) #endif // Value stack grows up (this makes it incompatible with native C stack, but // makes sure that arguments to functions are in natural order arg1..argN // (Python semantics mandates left-to-right evaluation order, including for // function arguments). Stack pointer is pre-incremented and points at the // top element. // Exception stack also grows up, top element is also pointed at. #define DECODE_UINT \ mp_uint_t unum = 0; \ do { \ unum = (unum << 7) + (*ip & 0x7f); \ } while ((*ip++ & 0x80) != 0) #define DECODE_ULABEL size_t ulab = (ip[0] | (ip[1] << 8)); ip += 2 #define DECODE_SLABEL size_t slab = (ip[0] | (ip[1] << 8)) - 0x8000; ip += 2 #if MICROPY_PERSISTENT_CODE #define DECODE_QSTR \ qstr qst = ip[0] | ip[1] << 8; \ ip += 2; #define DECODE_PTR \ DECODE_UINT; \ void *ptr = (void*)(uintptr_t)code_state->fun_bc->const_table[unum] #define DECODE_OBJ \ DECODE_UINT; \ mp_obj_t obj = (mp_obj_t)code_state->fun_bc->const_table[unum] #else #define DECODE_QSTR qstr qst = 0; \ do { \ qst = (qst << 7) + (*ip & 0x7f); \ } while ((*ip++ & 0x80) != 0) #define DECODE_PTR \ ip = (byte*)MP_ALIGN(ip, sizeof(void*)); \ void *ptr = *(void**)ip; \ ip += sizeof(void*) #define DECODE_OBJ \ ip = (byte*)MP_ALIGN(ip, sizeof(mp_obj_t)); \ mp_obj_t obj = *(mp_obj_t*)ip; \ ip += sizeof(mp_obj_t) #endif #define PUSH(val) *++sp = (val) #define POP() (*sp--) #define TOP() (*sp) #define SET_TOP(val) *sp = (val) #if MICROPY_PY_SYS_EXC_INFO #define CLEAR_SYS_EXC_INFO() MP_STATE_VM(cur_exception) = NULL; #else #define CLEAR_SYS_EXC_INFO() #endif #define PUSH_EXC_BLOCK(with_or_finally) do { \ DECODE_ULABEL; /* except labels are always forward */ \ ++exc_sp; \ exc_sp->handler = ip + ulab; \ exc_sp->val_sp = MP_TAGPTR_MAKE(sp, ((with_or_finally) << 1) | currently_in_except_block); \ exc_sp->prev_exc = NULL; \ currently_in_except_block = 0; /* in a try block now */ \ } while (0) #define POP_EXC_BLOCK() \ currently_in_except_block = MP_TAGPTR_TAG0(exc_sp->val_sp); /* restore previous state */ \ exc_sp--; /* pop back to previous exception handler */ \ CLEAR_SYS_EXC_INFO() /* just clear sys.exc_info(), not compliant, but it shouldn't be used in 1st place */ // fastn has items in reverse order (fastn[0] is local[0], fastn[-1] is local[1], etc) // sp points to bottom of stack which grows up // returns: // MP_VM_RETURN_NORMAL, sp valid, return value in *sp // MP_VM_RETURN_YIELD, ip, sp valid, yielded value in *sp // MP_VM_RETURN_EXCEPTION, exception in fastn[0] mp_vm_return_kind_t mp_execute_bytecode(mp_code_state_t *code_state, volatile mp_obj_t inject_exc) { #define SELECTIVE_EXC_IP (0) #if SELECTIVE_EXC_IP #define MARK_EXC_IP_SELECTIVE() { code_state->ip = ip; } /* stores ip 1 byte past last opcode */ #define MARK_EXC_IP_GLOBAL() #else #define MARK_EXC_IP_SELECTIVE() #define MARK_EXC_IP_GLOBAL() { code_state->ip = ip; } /* stores ip pointing to last opcode */ #endif #if MICROPY_OPT_COMPUTED_GOTO #include "py/vmentrytable.h" #define DISPATCH() do { \ TRACE(ip); \ MARK_EXC_IP_GLOBAL(); \ goto *entry_table[*ip++]; \ } while (0) #define DISPATCH_WITH_PEND_EXC_CHECK() goto pending_exception_check #define ENTRY(op) entry_##op #define ENTRY_DEFAULT entry_default #else #define DISPATCH() goto dispatch_loop #define DISPATCH_WITH_PEND_EXC_CHECK() goto pending_exception_check #define ENTRY(op) case op #define ENTRY_DEFAULT default #endif // nlr_raise needs to be implemented as a goto, so that the C compiler's flow analyser // sees that it's possible for us to jump from the dispatch loop to the exception // handler. Without this, the code may have a different stack layout in the dispatch // loop and the exception handler, leading to very obscure bugs. #define RAISE(o) do { nlr_pop(); nlr.ret_val = MP_OBJ_TO_PTR(o); goto exception_handler; } while (0) #if MICROPY_STACKLESS run_code_state: ; #endif // Pointers which are constant for particular invocation of mp_execute_bytecode() mp_obj_t * /*const*/ fastn; mp_exc_stack_t * /*const*/ exc_stack; { size_t n_state = mp_decode_uint_value(code_state->fun_bc->bytecode); fastn = &code_state->state[n_state - 1]; exc_stack = (mp_exc_stack_t*)(code_state->state + n_state); } // variables that are visible to the exception handler (declared volatile) volatile bool currently_in_except_block = MP_TAGPTR_TAG0(code_state->exc_sp); // 0 or 1, to detect nested exceptions mp_exc_stack_t *volatile exc_sp = MP_TAGPTR_PTR(code_state->exc_sp); // stack grows up, exc_sp points to top of stack #if MICROPY_PY_THREAD_GIL && MICROPY_PY_THREAD_GIL_VM_DIVISOR // This needs to be volatile and outside the VM loop so it persists across handling // of any exceptions. Otherwise it's possible that the VM never gives up the GIL. volatile int gil_divisor = MICROPY_PY_THREAD_GIL_VM_DIVISOR; #endif // outer exception handling loop for (;;) { nlr_buf_t nlr; outer_dispatch_loop: if (nlr_push(&nlr) == 0) { // local variables that are not visible to the exception handler const byte *ip = code_state->ip; mp_obj_t *sp = code_state->sp; mp_obj_t obj_shared; MICROPY_VM_HOOK_INIT // If we have exception to inject, now that we finish setting up // execution context, raise it. This works as if RAISE_VARARGS // bytecode was executed. // Injecting exc into yield from generator is a special case, // handled by MP_BC_YIELD_FROM itself if (inject_exc != MP_OBJ_NULL && *ip != MP_BC_YIELD_FROM) { mp_obj_t exc = inject_exc; inject_exc = MP_OBJ_NULL; exc = mp_make_raise_obj(exc); RAISE(exc); } // loop to execute byte code for (;;) { dispatch_loop: #if MICROPY_OPT_COMPUTED_GOTO DISPATCH(); #else TRACE(ip); MARK_EXC_IP_GLOBAL(); switch (*ip++) { #endif ENTRY(MP_BC_LOAD_CONST_FALSE): PUSH(mp_const_false); DISPATCH(); ENTRY(MP_BC_LOAD_CONST_NONE): PUSH(mp_const_none); DISPATCH(); ENTRY(MP_BC_LOAD_CONST_TRUE): PUSH(mp_const_true); DISPATCH(); ENTRY(MP_BC_LOAD_CONST_SMALL_INT): { mp_int_t num = 0; if ((ip[0] & 0x40) != 0) { // Number is negative num--; } do { num = (num << 7) | (*ip & 0x7f); } while ((*ip++ & 0x80) != 0); PUSH(MP_OBJ_NEW_SMALL_INT(num)); DISPATCH(); } ENTRY(MP_BC_LOAD_CONST_STRING): { DECODE_QSTR; PUSH(MP_OBJ_NEW_QSTR(qst)); DISPATCH(); } ENTRY(MP_BC_LOAD_CONST_OBJ): { DECODE_OBJ; PUSH(obj); DISPATCH(); } ENTRY(MP_BC_LOAD_NULL): PUSH(MP_OBJ_NULL); DISPATCH(); ENTRY(MP_BC_LOAD_FAST_N): { DECODE_UINT; obj_shared = fastn[-unum]; load_check: if (obj_shared == MP_OBJ_NULL) { local_name_error: { MARK_EXC_IP_SELECTIVE(); mp_obj_t obj = mp_obj_new_exception_msg(&mp_type_NameError, translate("local variable referenced before assignment")); RAISE(obj); } } PUSH(obj_shared); DISPATCH(); } ENTRY(MP_BC_LOAD_DEREF): { DECODE_UINT; obj_shared = mp_obj_cell_get(fastn[-unum]); goto load_check; } #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE ENTRY(MP_BC_LOAD_NAME): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; PUSH(mp_load_name(qst)); DISPATCH(); } #else ENTRY(MP_BC_LOAD_NAME): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t key = MP_OBJ_NEW_QSTR(qst); mp_uint_t x = *ip; if (x < mp_locals_get()->map.alloc && mp_locals_get()->map.table[x].key == key) { PUSH(mp_locals_get()->map.table[x].value); } else { mp_map_elem_t *elem = mp_map_lookup(&mp_locals_get()->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP); if (elem != NULL) { *(byte*)ip = (elem - &mp_locals_get()->map.table[0]) & 0xff; PUSH(elem->value); } else { PUSH(mp_load_name(MP_OBJ_QSTR_VALUE(key))); } } ip++; DISPATCH(); } #endif #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE ENTRY(MP_BC_LOAD_GLOBAL): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; PUSH(mp_load_global(qst)); DISPATCH(); } #else ENTRY(MP_BC_LOAD_GLOBAL): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t key = MP_OBJ_NEW_QSTR(qst); mp_uint_t x = *ip; if (x < mp_globals_get()->map.alloc && mp_globals_get()->map.table[x].key == key) { PUSH(mp_globals_get()->map.table[x].value); } else { mp_map_elem_t *elem = mp_map_lookup(&mp_globals_get()->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP); if (elem != NULL) { *(byte*)ip = (elem - &mp_globals_get()->map.table[0]) & 0xff; PUSH(elem->value); } else { PUSH(mp_load_global(MP_OBJ_QSTR_VALUE(key))); } } ip++; DISPATCH(); } #endif #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE ENTRY(MP_BC_LOAD_ATTR): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; SET_TOP(mp_load_attr(TOP(), qst)); DISPATCH(); } #else ENTRY(MP_BC_LOAD_ATTR): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t top = TOP(); if (mp_obj_is_instance_type(mp_obj_get_type(top))) { mp_obj_instance_t *self = MP_OBJ_TO_PTR(top); mp_uint_t x = *ip; mp_obj_t key = MP_OBJ_NEW_QSTR(qst); mp_map_elem_t *elem; if (x < self->members.alloc && self->members.table[x].key == key) { elem = &self->members.table[x]; } else { elem = mp_map_lookup(&self->members, key, MP_MAP_LOOKUP); if (elem != NULL) { *(byte*)ip = elem - &self->members.table[0]; } else { goto load_attr_cache_fail; } } SET_TOP(elem->value); ip++; DISPATCH(); } load_attr_cache_fail: SET_TOP(mp_load_attr(top, qst)); ip++; DISPATCH(); } #endif ENTRY(MP_BC_LOAD_METHOD): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_load_method(*sp, qst, sp); sp += 1; DISPATCH(); } ENTRY(MP_BC_LOAD_SUPER_METHOD): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; sp -= 1; mp_load_super_method(qst, sp - 1); DISPATCH(); } ENTRY(MP_BC_LOAD_BUILD_CLASS): MARK_EXC_IP_SELECTIVE(); PUSH(mp_load_build_class()); DISPATCH(); ENTRY(MP_BC_LOAD_SUBSCR): { MARK_EXC_IP_SELECTIVE(); mp_obj_t index = POP(); SET_TOP(mp_obj_subscr(TOP(), index, MP_OBJ_SENTINEL)); DISPATCH(); } ENTRY(MP_BC_STORE_FAST_N): { DECODE_UINT; fastn[-unum] = POP(); DISPATCH(); } ENTRY(MP_BC_STORE_DEREF): { DECODE_UINT; mp_obj_cell_set(fastn[-unum], POP()); DISPATCH(); } ENTRY(MP_BC_STORE_NAME): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_store_name(qst, POP()); DISPATCH(); } ENTRY(MP_BC_STORE_GLOBAL): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_store_global(qst, POP()); DISPATCH(); } #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE ENTRY(MP_BC_STORE_ATTR): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_store_attr(sp[0], qst, sp[-1]); sp -= 2; DISPATCH(); } #else // This caching code works with MICROPY_PY_BUILTINS_PROPERTY and/or // MICROPY_PY_DESCRIPTORS enabled because if the attr exists in // self->members then it can't be a property or have descriptors. A // consequence of this is that we can't use MP_MAP_LOOKUP_ADD_IF_NOT_FOUND // in the fast-path below, because that store could override a property. ENTRY(MP_BC_STORE_ATTR): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t top = TOP(); if (mp_obj_is_instance_type(mp_obj_get_type(top)) && sp[-1] != MP_OBJ_NULL) { mp_obj_instance_t *self = MP_OBJ_TO_PTR(top); mp_uint_t x = *ip; mp_obj_t key = MP_OBJ_NEW_QSTR(qst); mp_map_elem_t *elem; if (x < self->members.alloc && self->members.table[x].key == key) { elem = &self->members.table[x]; } else { elem = mp_map_lookup(&self->members, key, MP_MAP_LOOKUP); if (elem != NULL) { *(byte*)ip = elem - &self->members.table[0]; } else { goto store_attr_cache_fail; } } elem->value = sp[-1]; sp -= 2; ip++; DISPATCH(); } store_attr_cache_fail: mp_store_attr(sp[0], qst, sp[-1]); sp -= 2; ip++; DISPATCH(); } #endif ENTRY(MP_BC_STORE_SUBSCR): MARK_EXC_IP_SELECTIVE(); mp_obj_subscr(sp[-1], sp[0], sp[-2]); sp -= 3; DISPATCH(); ENTRY(MP_BC_DELETE_FAST): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; if (fastn[-unum] == MP_OBJ_NULL) { goto local_name_error; } fastn[-unum] = MP_OBJ_NULL; DISPATCH(); } ENTRY(MP_BC_DELETE_DEREF): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; if (mp_obj_cell_get(fastn[-unum]) == MP_OBJ_NULL) { goto local_name_error; } mp_obj_cell_set(fastn[-unum], MP_OBJ_NULL); DISPATCH(); } ENTRY(MP_BC_DELETE_NAME): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_delete_name(qst); DISPATCH(); } ENTRY(MP_BC_DELETE_GLOBAL): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_delete_global(qst); DISPATCH(); } ENTRY(MP_BC_DUP_TOP): { mp_obj_t top = TOP(); PUSH(top); DISPATCH(); } ENTRY(MP_BC_DUP_TOP_TWO): sp += 2; sp[0] = sp[-2]; sp[-1] = sp[-3]; DISPATCH(); ENTRY(MP_BC_POP_TOP): sp -= 1; DISPATCH(); ENTRY(MP_BC_ROT_TWO): { mp_obj_t top = sp[0]; sp[0] = sp[-1]; sp[-1] = top; DISPATCH(); } ENTRY(MP_BC_ROT_THREE): { mp_obj_t top = sp[0]; sp[0] = sp[-1]; sp[-1] = sp[-2]; sp[-2] = top; DISPATCH(); } ENTRY(MP_BC_JUMP): { DECODE_SLABEL; ip += slab; DISPATCH_WITH_PEND_EXC_CHECK(); } ENTRY(MP_BC_POP_JUMP_IF_TRUE): { DECODE_SLABEL; if (mp_obj_is_true(POP())) { ip += slab; } DISPATCH_WITH_PEND_EXC_CHECK(); } ENTRY(MP_BC_POP_JUMP_IF_FALSE): { DECODE_SLABEL; if (!mp_obj_is_true(POP())) { ip += slab; } DISPATCH_WITH_PEND_EXC_CHECK(); } ENTRY(MP_BC_JUMP_IF_TRUE_OR_POP): { DECODE_SLABEL; if (mp_obj_is_true(TOP())) { ip += slab; } else { sp--; } DISPATCH_WITH_PEND_EXC_CHECK(); } ENTRY(MP_BC_JUMP_IF_FALSE_OR_POP): { DECODE_SLABEL; if (mp_obj_is_true(TOP())) { sp--; } else { ip += slab; } DISPATCH_WITH_PEND_EXC_CHECK(); } ENTRY(MP_BC_SETUP_WITH): { MARK_EXC_IP_SELECTIVE(); // stack: (..., ctx_mgr) mp_obj_t obj = TOP(); mp_load_method(obj, MP_QSTR___exit__, sp); mp_load_method(obj, MP_QSTR___enter__, sp + 2); mp_obj_t ret = mp_call_method_n_kw(0, 0, sp + 2); sp += 1; PUSH_EXC_BLOCK(1); PUSH(ret); // stack: (..., __exit__, ctx_mgr, as_value) DISPATCH(); } ENTRY(MP_BC_WITH_CLEANUP): { MARK_EXC_IP_SELECTIVE(); // Arriving here, there's "exception control block" on top of stack, // and __exit__ method (with self) underneath it. Bytecode calls __exit__, // and "deletes" it off stack, shifting "exception control block" // to its place. // The bytecode emitter ensures that there is enough space on the Python // value stack to hold the __exit__ method plus an additional 4 entries. if (TOP() == mp_const_none) { // stack: (..., __exit__, ctx_mgr, None) sp[1] = mp_const_none; sp[2] = mp_const_none; sp -= 2; mp_call_method_n_kw(3, 0, sp); SET_TOP(mp_const_none); } else if (MP_OBJ_IS_SMALL_INT(TOP())) { // Getting here there are two distinct cases: // - unwind return, stack: (..., __exit__, ctx_mgr, ret_val, SMALL_INT(-1)) // - unwind jump, stack: (..., __exit__, ctx_mgr, dest_ip, SMALL_INT(num_exc)) // For both cases we do exactly the same thing. mp_obj_t data = sp[-1]; mp_obj_t cause = sp[0]; sp[-1] = mp_const_none; sp[0] = mp_const_none; sp[1] = mp_const_none; mp_call_method_n_kw(3, 0, sp - 3); sp[-3] = data; sp[-2] = cause; sp -= 2; // we removed (__exit__, ctx_mgr) } else { assert(mp_obj_is_exception_instance(TOP())); // stack: (..., __exit__, ctx_mgr, exc_instance) // Need to pass (exc_type, exc_instance, None) as arguments to __exit__. sp[1] = sp[0]; sp[0] = MP_OBJ_FROM_PTR(mp_obj_get_type(sp[0])); sp[2] = mp_const_none; sp -= 2; mp_obj_t ret_value = mp_call_method_n_kw(3, 0, sp); if (mp_obj_is_true(ret_value)) { // We need to silence/swallow the exception. This is done // by popping the exception and the __exit__ handler and // replacing it with None, which signals END_FINALLY to just // execute the finally handler normally. SET_TOP(mp_const_none); assert(exc_sp >= exc_stack); POP_EXC_BLOCK(); } else { // We need to re-raise the exception. We pop __exit__ handler // by copying the exception instance down to the new top-of-stack. sp[0] = sp[3]; } } DISPATCH(); } ENTRY(MP_BC_UNWIND_JUMP): { MARK_EXC_IP_SELECTIVE(); DECODE_SLABEL; PUSH((mp_obj_t)(mp_uint_t)(uintptr_t)(ip + slab)); // push destination ip for jump PUSH((mp_obj_t)(mp_uint_t)(*ip)); // push number of exception handlers to unwind (0x80 bit set if we also need to pop stack) unwind_jump:; mp_uint_t unum = (mp_uint_t)POP(); // get number of exception handlers to unwind while ((unum & 0x7f) > 0) { unum -= 1; assert(exc_sp >= exc_stack); if (MP_TAGPTR_TAG1(exc_sp->val_sp)) { // Getting here the stack looks like: // (..., X, dest_ip) // where X is pointed to by exc_sp->val_sp and in the case // of a "with" block contains the context manager info. // We're going to run "finally" code as a coroutine // (not calling it recursively). Set up a sentinel // on the stack so it can return back to us when it is // done (when WITH_CLEANUP or END_FINALLY reached). // The sentinel is the number of exception handlers left to // unwind, which is a non-negative integer. PUSH(MP_OBJ_NEW_SMALL_INT(unum)); ip = exc_sp->handler; // get exception handler byte code address exc_sp--; // pop exception handler goto dispatch_loop; // run the exception handler } POP_EXC_BLOCK(); } ip = (const byte*)MP_OBJ_TO_PTR(POP()); // pop destination ip for jump if (unum != 0) { // pop the exhausted iterator sp -= MP_OBJ_ITER_BUF_NSLOTS; } DISPATCH_WITH_PEND_EXC_CHECK(); } // matched against: POP_BLOCK or POP_EXCEPT (anything else?) ENTRY(MP_BC_SETUP_EXCEPT): ENTRY(MP_BC_SETUP_FINALLY): { MARK_EXC_IP_SELECTIVE(); #if SELECTIVE_EXC_IP PUSH_EXC_BLOCK((code_state->ip[-1] == MP_BC_SETUP_FINALLY) ? 1 : 0); #else PUSH_EXC_BLOCK((code_state->ip[0] == MP_BC_SETUP_FINALLY) ? 1 : 0); #endif DISPATCH(); } ENTRY(MP_BC_END_FINALLY): MARK_EXC_IP_SELECTIVE(); // if TOS is None, just pops it and continues // if TOS is an integer, finishes coroutine and returns control to caller // if TOS is an exception, reraises the exception if (TOP() == mp_const_none) { sp--; } else if (MP_OBJ_IS_SMALL_INT(TOP())) { // We finished "finally" coroutine and now dispatch back // to our caller, based on TOS value mp_int_t cause = MP_OBJ_SMALL_INT_VALUE(POP()); if (cause < 0) { // A negative cause indicates unwind return goto unwind_return; } else { // Otherwise it's an unwind jump and we must push as a raw // number the number of exception handlers to unwind PUSH((mp_obj_t)cause); goto unwind_jump; } } else { assert(mp_obj_is_exception_instance(TOP())); RAISE(TOP()); } DISPATCH(); ENTRY(MP_BC_GET_ITER): MARK_EXC_IP_SELECTIVE(); SET_TOP(mp_getiter(TOP(), NULL)); DISPATCH(); // An iterator for a for-loop takes MP_OBJ_ITER_BUF_NSLOTS slots on // the Python value stack. These slots are either used to store the // iterator object itself, or the first slot is MP_OBJ_NULL and // the second slot holds a reference to the iterator object. ENTRY(MP_BC_GET_ITER_STACK): { MARK_EXC_IP_SELECTIVE(); mp_obj_t obj = TOP(); mp_obj_iter_buf_t *iter_buf = (mp_obj_iter_buf_t*)sp; sp += MP_OBJ_ITER_BUF_NSLOTS - 1; obj = mp_getiter(obj, iter_buf); if (obj != MP_OBJ_FROM_PTR(iter_buf)) { // Iterator didn't use the stack so indicate that with MP_OBJ_NULL. sp[-MP_OBJ_ITER_BUF_NSLOTS + 1] = MP_OBJ_NULL; sp[-MP_OBJ_ITER_BUF_NSLOTS + 2] = obj; } DISPATCH(); } ENTRY(MP_BC_FOR_ITER): { MARK_EXC_IP_SELECTIVE(); DECODE_ULABEL; // the jump offset if iteration finishes; for labels are always forward code_state->sp = sp; mp_obj_t obj; if (sp[-MP_OBJ_ITER_BUF_NSLOTS + 1] == MP_OBJ_NULL) { obj = sp[-MP_OBJ_ITER_BUF_NSLOTS + 2]; } else { obj = MP_OBJ_FROM_PTR(&sp[-MP_OBJ_ITER_BUF_NSLOTS + 1]); } mp_obj_t value = mp_iternext_allow_raise(obj); if (value == MP_OBJ_STOP_ITERATION) { sp -= MP_OBJ_ITER_BUF_NSLOTS; // pop the exhausted iterator ip += ulab; // jump to after for-block } else { PUSH(value); // push the next iteration value } DISPATCH(); } // matched against: SETUP_EXCEPT, SETUP_FINALLY, SETUP_WITH ENTRY(MP_BC_POP_BLOCK): // we are exiting an exception handler, so pop the last one of the exception-stack assert(exc_sp >= exc_stack); POP_EXC_BLOCK(); DISPATCH(); // matched against: SETUP_EXCEPT ENTRY(MP_BC_POP_EXCEPT): assert(exc_sp >= exc_stack); assert(currently_in_except_block); POP_EXC_BLOCK(); DISPATCH(); ENTRY(MP_BC_BUILD_TUPLE): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; sp -= unum - 1; SET_TOP(mp_obj_new_tuple(unum, sp)); DISPATCH(); } ENTRY(MP_BC_BUILD_LIST): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; sp -= unum - 1; SET_TOP(mp_obj_new_list(unum, sp)); DISPATCH(); } ENTRY(MP_BC_BUILD_MAP): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; PUSH(mp_obj_new_dict(unum)); DISPATCH(); } ENTRY(MP_BC_STORE_MAP): MARK_EXC_IP_SELECTIVE(); sp -= 2; mp_obj_dict_store(sp[0], sp[2], sp[1]); DISPATCH(); #if MICROPY_PY_BUILTINS_SET ENTRY(MP_BC_BUILD_SET): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; sp -= unum - 1; SET_TOP(mp_obj_new_set(unum, sp)); DISPATCH(); } #endif #if MICROPY_PY_BUILTINS_SLICE ENTRY(MP_BC_BUILD_SLICE): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; if (unum == 2) { mp_obj_t stop = POP(); mp_obj_t start = TOP(); SET_TOP(mp_obj_new_slice(start, stop, mp_const_none)); } else { mp_obj_t step = POP(); mp_obj_t stop = POP(); mp_obj_t start = TOP(); SET_TOP(mp_obj_new_slice(start, stop, step)); } DISPATCH(); } #endif ENTRY(MP_BC_STORE_COMP): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; mp_obj_t obj = sp[-(unum >> 2)]; if ((unum & 3) == 0) { mp_obj_list_append(obj, sp[0]); sp--; } else if (!MICROPY_PY_BUILTINS_SET || (unum & 3) == 1) { mp_obj_dict_store(obj, sp[0], sp[-1]); sp -= 2; #if MICROPY_PY_BUILTINS_SET } else { mp_obj_set_store(obj, sp[0]); sp--; #endif } DISPATCH(); } ENTRY(MP_BC_UNPACK_SEQUENCE): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; mp_unpack_sequence(sp[0], unum, sp); sp += unum - 1; DISPATCH(); } ENTRY(MP_BC_UNPACK_EX): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; mp_unpack_ex(sp[0], unum, sp); sp += (unum & 0xff) + ((unum >> 8) & 0xff); DISPATCH(); } ENTRY(MP_BC_MAKE_FUNCTION): { DECODE_PTR; PUSH(mp_make_function_from_raw_code(ptr, MP_OBJ_NULL, MP_OBJ_NULL)); DISPATCH(); } ENTRY(MP_BC_MAKE_FUNCTION_DEFARGS): { DECODE_PTR; // Stack layout: def_tuple def_dict <- TOS mp_obj_t def_dict = POP(); SET_TOP(mp_make_function_from_raw_code(ptr, TOP(), def_dict)); DISPATCH(); } ENTRY(MP_BC_MAKE_CLOSURE): { DECODE_PTR; size_t n_closed_over = *ip++; // Stack layout: closed_overs <- TOS sp -= n_closed_over - 1; SET_TOP(mp_make_closure_from_raw_code(ptr, n_closed_over, sp)); DISPATCH(); } ENTRY(MP_BC_MAKE_CLOSURE_DEFARGS): { DECODE_PTR; size_t n_closed_over = *ip++; // Stack layout: def_tuple def_dict closed_overs <- TOS sp -= 2 + n_closed_over - 1; SET_TOP(mp_make_closure_from_raw_code(ptr, 0x100 | n_closed_over, sp)); DISPATCH(); } ENTRY(MP_BC_CALL_FUNCTION): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional // (unum >> 8) & 0xff == n_keyword sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe); #if MICROPY_STACKLESS if (mp_obj_get_type(*sp) == &mp_type_fun_bc) { code_state->ip = ip; code_state->sp = sp; code_state->exc_sp = MP_TAGPTR_MAKE(exc_sp, currently_in_except_block); mp_code_state_t *new_state = mp_obj_fun_bc_prepare_codestate(*sp, unum & 0xff, (unum >> 8) & 0xff, sp + 1); #if !MICROPY_ENABLE_PYSTACK if (new_state == NULL) { // Couldn't allocate codestate on heap: in the strict case raise // an exception, otherwise just fall through to stack allocation. #if MICROPY_STACKLESS_STRICT deep_recursion_error: mp_raise_recursion_depth(); #endif } else #endif { new_state->prev = code_state; code_state = new_state; nlr_pop(); goto run_code_state; } } #endif SET_TOP(mp_call_function_n_kw(*sp, unum & 0xff, (unum >> 8) & 0xff, sp + 1)); DISPATCH(); } ENTRY(MP_BC_CALL_FUNCTION_VAR_KW): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional // (unum >> 8) & 0xff == n_keyword // We have following stack layout here: // fun arg0 arg1 ... kw0 val0 kw1 val1 ... seq dict <- TOS sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe) + 2; #if MICROPY_STACKLESS if (mp_obj_get_type(*sp) == &mp_type_fun_bc) { code_state->ip = ip; code_state->sp = sp; code_state->exc_sp = MP_TAGPTR_MAKE(exc_sp, currently_in_except_block); mp_call_args_t out_args; mp_call_prepare_args_n_kw_var(false, unum, sp, &out_args); mp_code_state_t *new_state = mp_obj_fun_bc_prepare_codestate(out_args.fun, out_args.n_args, out_args.n_kw, out_args.args); #if !MICROPY_ENABLE_PYSTACK // Freeing args at this point does not follow a LIFO order so only do it if // pystack is not enabled. For pystack, they are freed when code_state is. mp_nonlocal_free(out_args.args, out_args.n_alloc * sizeof(mp_obj_t)); #endif #if !MICROPY_ENABLE_PYSTACK if (new_state == NULL) { // Couldn't allocate codestate on heap: in the strict case raise // an exception, otherwise just fall through to stack allocation. #if MICROPY_STACKLESS_STRICT goto deep_recursion_error; #endif } else #endif { new_state->prev = code_state; code_state = new_state; nlr_pop(); goto run_code_state; } } #endif SET_TOP(mp_call_method_n_kw_var(false, unum, sp)); DISPATCH(); } ENTRY(MP_BC_CALL_METHOD): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional // (unum >> 8) & 0xff == n_keyword sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe) + 1; #if MICROPY_STACKLESS if (mp_obj_get_type(*sp) == &mp_type_fun_bc) { code_state->ip = ip; code_state->sp = sp; code_state->exc_sp = MP_TAGPTR_MAKE(exc_sp, currently_in_except_block); size_t n_args = unum & 0xff; size_t n_kw = (unum >> 8) & 0xff; int adjust = (sp[1] == MP_OBJ_NULL) ? 0 : 1; mp_code_state_t *new_state = mp_obj_fun_bc_prepare_codestate(*sp, n_args + adjust, n_kw, sp + 2 - adjust); #if !MICROPY_ENABLE_PYSTACK if (new_state == NULL) { // Couldn't allocate codestate on heap: in the strict case raise // an exception, otherwise just fall through to stack allocation. #if MICROPY_STACKLESS_STRICT goto deep_recursion_error; #endif } else #endif { new_state->prev = code_state; code_state = new_state; nlr_pop(); goto run_code_state; } } #endif SET_TOP(mp_call_method_n_kw(unum & 0xff, (unum >> 8) & 0xff, sp)); DISPATCH(); } ENTRY(MP_BC_CALL_METHOD_VAR_KW): { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional // (unum >> 8) & 0xff == n_keyword // We have following stack layout here: // fun self arg0 arg1 ... kw0 val0 kw1 val1 ... seq dict <- TOS sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe) + 3; #if MICROPY_STACKLESS if (mp_obj_get_type(*sp) == &mp_type_fun_bc) { code_state->ip = ip; code_state->sp = sp; code_state->exc_sp = MP_TAGPTR_MAKE(exc_sp, currently_in_except_block); mp_call_args_t out_args; mp_call_prepare_args_n_kw_var(true, unum, sp, &out_args); mp_code_state_t *new_state = mp_obj_fun_bc_prepare_codestate(out_args.fun, out_args.n_args, out_args.n_kw, out_args.args); #if !MICROPY_ENABLE_PYSTACK // Freeing args at this point does not follow a LIFO order so only do it if // pystack is not enabled. For pystack, they are freed when code_state is. mp_nonlocal_free(out_args.args, out_args.n_alloc * sizeof(mp_obj_t)); #endif #if !MICROPY_ENABLE_PYSTACK if (new_state == NULL) { // Couldn't allocate codestate on heap: in the strict case raise // an exception, otherwise just fall through to stack allocation. #if MICROPY_STACKLESS_STRICT goto deep_recursion_error; #endif } else #endif { new_state->prev = code_state; code_state = new_state; nlr_pop(); goto run_code_state; } } #endif SET_TOP(mp_call_method_n_kw_var(true, unum, sp)); DISPATCH(); } ENTRY(MP_BC_RETURN_VALUE): MARK_EXC_IP_SELECTIVE(); // These next 3 lines pop a try-finally exception handler, if one // is there on the exception stack. Without this the finally block // is executed a second time when the return is executed, because // the try-finally exception handler is still on the stack. // TODO Possibly find a better way to handle this case. if (currently_in_except_block) { POP_EXC_BLOCK(); } unwind_return: while (exc_sp >= exc_stack) { if (MP_TAGPTR_TAG1(exc_sp->val_sp)) { // Getting here the stack looks like: // (..., X, [iter0, iter1, ...,] ret_val) // where X is pointed to by exc_sp->val_sp and in the case // of a "with" block contains the context manager info. // There may be 0 or more for-iterators between X and the // return value, and these must be removed before control can // pass to the finally code. We simply copy the ret_value down // over these iterators, if they exist. If they don't then the // following is a null operation. mp_obj_t *finally_sp = MP_TAGPTR_PTR(exc_sp->val_sp); finally_sp[1] = sp[0]; sp = &finally_sp[1]; // We're going to run "finally" code as a coroutine // (not calling it recursively). Set up a sentinel // on a stack so it can return back to us when it is // done (when WITH_CLEANUP or END_FINALLY reached). PUSH(MP_OBJ_NEW_SMALL_INT(-1)); ip = exc_sp->handler; exc_sp--; goto dispatch_loop; } exc_sp--; } nlr_pop(); code_state->sp = sp; assert(exc_sp == exc_stack - 1); MICROPY_VM_HOOK_RETURN #if MICROPY_STACKLESS if (code_state->prev != NULL) { mp_obj_t res = *sp; mp_globals_set(code_state->old_globals); mp_code_state_t *new_code_state = code_state->prev; #if MICROPY_ENABLE_PYSTACK // Free code_state, and args allocated by mp_call_prepare_args_n_kw_var // (The latter is implicitly freed when using pystack due to its LIFO nature.) // The sizeof in the following statement does not include the size of the variable // part of the struct. This arg is anyway not used if pystack is enabled. mp_nonlocal_free(code_state, sizeof(mp_code_state_t)); #endif code_state = new_code_state; *code_state->sp = res; goto run_code_state; } #endif return MP_VM_RETURN_NORMAL; ENTRY(MP_BC_RAISE_VARARGS): { MARK_EXC_IP_SELECTIVE(); mp_uint_t unum = *ip; mp_obj_t obj; if (unum == 2) { mp_warning("exception chaining not supported"); // ignore (pop) "from" argument sp--; } if (unum == 0) { // search for the inner-most previous exception, to reraise it obj = MP_OBJ_NULL; for (mp_exc_stack_t *e = exc_sp; e >= exc_stack; e--) { if (e->prev_exc != NULL) { obj = MP_OBJ_FROM_PTR(e->prev_exc); break; } } if (obj == MP_OBJ_NULL) { obj = mp_obj_new_exception_msg(&mp_type_RuntimeError, translate("no active exception to reraise")); RAISE(obj); } } else { obj = TOP(); } obj = mp_make_raise_obj(obj); RAISE(obj); } ENTRY(MP_BC_YIELD_VALUE): yield: nlr_pop(); code_state->ip = ip; code_state->sp = sp; code_state->exc_sp = MP_TAGPTR_MAKE(exc_sp, currently_in_except_block); return MP_VM_RETURN_YIELD; ENTRY(MP_BC_YIELD_FROM): { MARK_EXC_IP_SELECTIVE(); //#define EXC_MATCH(exc, type) MP_OBJ_IS_TYPE(exc, type) #define EXC_MATCH(exc, type) mp_obj_exception_match(exc, type) #define GENERATOR_EXIT_IF_NEEDED(t) if (t != MP_OBJ_NULL && EXC_MATCH(t, MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { RAISE(t); } mp_vm_return_kind_t ret_kind; mp_obj_t send_value = POP(); mp_obj_t t_exc = MP_OBJ_NULL; mp_obj_t ret_value; code_state->sp = sp; // Save sp because it's needed if mp_resume raises StopIteration if (inject_exc != MP_OBJ_NULL) { t_exc = inject_exc; inject_exc = MP_OBJ_NULL; ret_kind = mp_resume(TOP(), MP_OBJ_NULL, t_exc, &ret_value); } else { ret_kind = mp_resume(TOP(), send_value, MP_OBJ_NULL, &ret_value); } if (ret_kind == MP_VM_RETURN_YIELD) { ip--; PUSH(ret_value); goto yield; } else if (ret_kind == MP_VM_RETURN_NORMAL) { // Pop exhausted gen sp--; if (ret_value == MP_OBJ_STOP_ITERATION) { // Optimize StopIteration // TODO: get StopIteration's value PUSH(mp_const_none); } else { PUSH(ret_value); } // If we injected GeneratorExit downstream, then even // if it was swallowed, we re-raise GeneratorExit GENERATOR_EXIT_IF_NEEDED(t_exc); DISPATCH(); } else { assert(ret_kind == MP_VM_RETURN_EXCEPTION); // Pop exhausted gen sp--; if (EXC_MATCH(ret_value, MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { PUSH(mp_obj_exception_get_value(ret_value)); // If we injected GeneratorExit downstream, then even // if it was swallowed, we re-raise GeneratorExit GENERATOR_EXIT_IF_NEEDED(t_exc); DISPATCH(); } else { RAISE(ret_value); } } } ENTRY(MP_BC_IMPORT_NAME): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t obj = POP(); SET_TOP(mp_import_name(qst, obj, TOP())); DISPATCH(); } ENTRY(MP_BC_IMPORT_FROM): { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t obj = mp_import_from(TOP(), qst); PUSH(obj); DISPATCH(); } ENTRY(MP_BC_IMPORT_STAR): MARK_EXC_IP_SELECTIVE(); mp_import_all(POP()); DISPATCH(); #if MICROPY_OPT_COMPUTED_GOTO ENTRY(MP_BC_LOAD_CONST_SMALL_INT_MULTI): PUSH(MP_OBJ_NEW_SMALL_INT((mp_int_t)ip[-1] - MP_BC_LOAD_CONST_SMALL_INT_MULTI - 16)); DISPATCH(); ENTRY(MP_BC_LOAD_FAST_MULTI): obj_shared = fastn[MP_BC_LOAD_FAST_MULTI - (mp_int_t)ip[-1]]; goto load_check; ENTRY(MP_BC_STORE_FAST_MULTI): fastn[MP_BC_STORE_FAST_MULTI - (mp_int_t)ip[-1]] = POP(); DISPATCH(); ENTRY(MP_BC_UNARY_OP_MULTI): MARK_EXC_IP_SELECTIVE(); SET_TOP(mp_unary_op(ip[-1] - MP_BC_UNARY_OP_MULTI, TOP())); DISPATCH(); ENTRY(MP_BC_BINARY_OP_MULTI): { MARK_EXC_IP_SELECTIVE(); mp_obj_t rhs = POP(); mp_obj_t lhs = TOP(); SET_TOP(mp_binary_op(ip[-1] - MP_BC_BINARY_OP_MULTI, lhs, rhs)); DISPATCH(); } ENTRY_DEFAULT: MARK_EXC_IP_SELECTIVE(); #else ENTRY_DEFAULT: if (ip[-1] < MP_BC_LOAD_CONST_SMALL_INT_MULTI + 64) { PUSH(MP_OBJ_NEW_SMALL_INT((mp_int_t)ip[-1] - MP_BC_LOAD_CONST_SMALL_INT_MULTI - 16)); DISPATCH(); } else if (ip[-1] < MP_BC_LOAD_FAST_MULTI + 16) { obj_shared = fastn[MP_BC_LOAD_FAST_MULTI - (mp_int_t)ip[-1]]; goto load_check; } else if (ip[-1] < MP_BC_STORE_FAST_MULTI + 16) { fastn[MP_BC_STORE_FAST_MULTI - (mp_int_t)ip[-1]] = POP(); DISPATCH(); } else if (ip[-1] < MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NUM_BYTECODE) { SET_TOP(mp_unary_op(ip[-1] - MP_BC_UNARY_OP_MULTI, TOP())); DISPATCH(); } else if (ip[-1] < MP_BC_BINARY_OP_MULTI + MP_BINARY_OP_NUM_BYTECODE) { mp_obj_t rhs = POP(); mp_obj_t lhs = TOP(); SET_TOP(mp_binary_op(ip[-1] - MP_BC_BINARY_OP_MULTI, lhs, rhs)); DISPATCH(); } else #endif { mp_obj_t obj = mp_obj_new_exception_msg(&mp_type_NotImplementedError, translate("byte code not implemented")); nlr_pop(); fastn[0] = obj; return MP_VM_RETURN_EXCEPTION; } #if !MICROPY_OPT_COMPUTED_GOTO } // switch #endif pending_exception_check: MICROPY_VM_HOOK_LOOP #if MICROPY_ENABLE_SCHEDULER // This is an inlined variant of mp_handle_pending if (MP_STATE_VM(sched_state) == MP_SCHED_PENDING) { MARK_EXC_IP_SELECTIVE(); mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION(); mp_obj_t obj = MP_STATE_VM(mp_pending_exception); if (obj != MP_OBJ_NULL) { MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL; if (!mp_sched_num_pending()) { MP_STATE_VM(sched_state) = MP_SCHED_IDLE; } MICROPY_END_ATOMIC_SECTION(atomic_state); RAISE(obj); } mp_handle_pending_tail(atomic_state); } #else // This is an inlined variant of mp_handle_pending if (MP_STATE_VM(mp_pending_exception) != MP_OBJ_NULL) { MARK_EXC_IP_SELECTIVE(); mp_obj_t obj = MP_STATE_VM(mp_pending_exception); MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL; RAISE(obj); } #endif #if MICROPY_PY_THREAD_GIL #if MICROPY_PY_THREAD_GIL_VM_DIVISOR if (--gil_divisor == 0) #endif { #if MICROPY_PY_THREAD_GIL_VM_DIVISOR gil_divisor = MICROPY_PY_THREAD_GIL_VM_DIVISOR; #endif #if MICROPY_ENABLE_SCHEDULER // can only switch threads if the scheduler is unlocked if (MP_STATE_VM(sched_state) == MP_SCHED_IDLE) #endif { MP_THREAD_GIL_EXIT(); MP_THREAD_GIL_ENTER(); } } #endif } // for loop } else { exception_handler: // exception occurred #if MICROPY_PY_SYS_EXC_INFO MP_STATE_VM(cur_exception) = nlr.ret_val; #endif #if SELECTIVE_EXC_IP // with selective ip, we store the ip 1 byte past the opcode, so move ptr back code_state->ip -= 1; #endif if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { if (code_state->ip) { // check if it's a StopIteration within a for block if (*code_state->ip == MP_BC_FOR_ITER) { const byte *ip = code_state->ip + 1; DECODE_ULABEL; // the jump offset if iteration finishes; for labels are always forward code_state->ip = ip + ulab; // jump to after for-block code_state->sp -= MP_OBJ_ITER_BUF_NSLOTS; // pop the exhausted iterator goto outer_dispatch_loop; // continue with dispatch loop } else if (*code_state->ip == MP_BC_YIELD_FROM) { // StopIteration inside yield from call means return a value of // yield from, so inject exception's value as yield from's result // (Instead of stack pop then push we just replace exhausted gen with value) *code_state->sp = mp_obj_exception_get_value(MP_OBJ_FROM_PTR(nlr.ret_val)); code_state->ip++; // yield from is over, move to next instruction goto outer_dispatch_loop; // continue with dispatch loop } } } #if MICROPY_STACKLESS unwind_loop: #endif // set file and line number that the exception occurred at // TODO: don't set traceback for exceptions re-raised by END_FINALLY. // But consider how to handle nested exceptions. if (nlr.ret_val != &mp_const_GeneratorExit_obj) { const byte *ip = code_state->fun_bc->bytecode; ip = mp_decode_uint_skip(ip); // skip n_state ip = mp_decode_uint_skip(ip); // skip n_exc_stack ip++; // skip scope_params ip++; // skip n_pos_args ip++; // skip n_kwonly_args ip++; // skip n_def_pos_args size_t bc = code_state->ip - ip; size_t code_info_size = mp_decode_uint_value(ip); ip = mp_decode_uint_skip(ip); // skip code_info_size bc -= code_info_size; #if MICROPY_PERSISTENT_CODE qstr block_name = ip[0] | (ip[1] << 8); qstr source_file = ip[2] | (ip[3] << 8); ip += 4; #else qstr block_name = mp_decode_uint_value(ip); ip = mp_decode_uint_skip(ip); qstr source_file = mp_decode_uint_value(ip); ip = mp_decode_uint_skip(ip); #endif size_t source_line = 1; size_t c; while ((c = *ip)) { size_t b, l; if ((c & 0x80) == 0) { // 0b0LLBBBBB encoding b = c & 0x1f; l = c >> 5; ip += 1; } else { // 0b1LLLBBBB 0bLLLLLLLL encoding (l's LSB in second byte) b = c & 0xf; l = ((c << 4) & 0x700) | ip[1]; ip += 2; } if (bc >= b) { bc -= b; source_line += l; } else { // found source line corresponding to bytecode offset break; } } mp_obj_exception_add_traceback(MP_OBJ_FROM_PTR(nlr.ret_val), source_file, source_line, block_name); } while (currently_in_except_block) { // nested exception assert(exc_sp >= exc_stack); // TODO make a proper message for nested exception // at the moment we are just raising the very last exception (the one that caused the nested exception) // move up to previous exception handler POP_EXC_BLOCK(); } if (exc_sp >= exc_stack) { // set flag to indicate that we are now handling an exception currently_in_except_block = 1; // catch exception and pass to byte code code_state->ip = exc_sp->handler; mp_obj_t *sp = MP_TAGPTR_PTR(exc_sp->val_sp); // save this exception in the stack so it can be used in a reraise, if needed exc_sp->prev_exc = nlr.ret_val; // push exception object so it can be handled by bytecode PUSH(MP_OBJ_FROM_PTR(nlr.ret_val)); code_state->sp = sp; #if MICROPY_STACKLESS } else if (code_state->prev != NULL) { mp_globals_set(code_state->old_globals); mp_code_state_t *new_code_state = code_state->prev; #if MICROPY_ENABLE_PYSTACK // Free code_state, and args allocated by mp_call_prepare_args_n_kw_var // (The latter is implicitly freed when using pystack due to its LIFO nature.) // The sizeof in the following statement does not include the size of the variable // part of the struct. This arg is anyway not used if pystack is enabled. mp_nonlocal_free(code_state, sizeof(mp_code_state_t)); #endif code_state = new_code_state; size_t n_state = mp_decode_uint_value(code_state->fun_bc->bytecode); fastn = &code_state->state[n_state - 1]; exc_stack = (mp_exc_stack_t*)(code_state->state + n_state); // variables that are visible to the exception handler (declared volatile) currently_in_except_block = MP_TAGPTR_TAG0(code_state->exc_sp); // 0 or 1, to detect nested exceptions exc_sp = MP_TAGPTR_PTR(code_state->exc_sp); // stack grows up, exc_sp points to top of stack goto unwind_loop; #endif } else { // propagate exception to higher level // TODO what to do about ip and sp? they don't really make sense at this point fastn[0] = MP_OBJ_FROM_PTR(nlr.ret_val); // must put exception here because sp is invalid return MP_VM_RETURN_EXCEPTION; } } } }
__label__pos
0.997742
How to Import a Patient Database Import and merge your current patient database with your KUDUwave software. You can import your existing patient database into the KUDUwave with these 6 simple steps: 1. Prepare a spreadsheet with all your patients’ information. Use these exact headings, in order, when compiling your spreadsheet. KUDUwave software patient data example Please do not use any commas [ , ] or pipes [ | ] in the patient details. 2. Save your complete spreadsheet in a csv (comma-separated values) format. 3. Create a folder in the KUDUwave software or make sure you have selected the correct, already existing, folder you wish to import the database into. 4. Import the csv file into the folder by clicking on import, then selecting the second option listed. Import option 5. Select the saved csv database file and click open to begin the import. open csv file to import data 6. Once finished, reopen the KUDUwave software and your patient’s will be in the folder you created in step 3. patients successfully imported imported patients You can edit the patient details by double clicking on them and correcting the data found in the patient profile.
__label__pos
0.975217
emuansi.dll Process name: emuansi.dll Module Application using this process: emuansi.dll Module emuansi.dll Process name: emuansi.dll Module Application using this process: emuansi.dll Module emuansi.dll Click here to run a scan if you are experiencing issues with this process. Process name: emuansi.dll Module Application using this process: emuansi.dll Module Recommended: Scan your system for invalid registry entries. What is emuansi.dll doing on my computer? emuansi.dll is a DLL file This process is still being reviewed. If you have some information about it feel free to send us an email at pl[at]uniblue[dot]com Non-system processes like emuansi.dll originate from software you installed on your system. Since most applications store data in your system's registry, it is likely that over time your registry suffers fragmentation and accumulates invalid entries which can affect your PC's performance. It is recommended that you check your registry to identify slowdown issues. emuansi.dll In order to ensure your files and data are not lost, be sure to back up your files online. Using a cloud backup service will allow you to safely secure all your digital files. This will also enable you to access any of your files, at any time, on any device. Is emuansi.dll harmful? emuansi.dll is unrated Can I stop or remove emuansi.dll? Most non-system processes that are running can be stopped because they are not involved in running your operating system. Scan your system now to identify unused processes that are using up valuable resources. emuansi.dll is used by 'emuansi.dll Module'.This is an application created by 'Unknown'. To stop emuansi.dll permanently uninstall 'emuansi.dll Module' from your system. Uninstalling applications can leave invalid registry entries, accumulating over time. Run a free scan to find out how to optimize software and system performance. Is emuansi.dll CPU intensive? This process is not considered CPU intensive. However, running too many processes on your system may affect your PC’s performance. To reduce system overload, you can use the Microsoft System Configuration Utility to manually find and disable processes that launch upon start-up. Alternatively, download PC Mechanic to automatically scan and identify any PC issues. Why is emuansi.dll giving me errors? Process related issues are usually related to problems encountered by the application that runs it. A safe way to stop these errors is to uninstall the application and run a system scan to automatically identify any PC issues. Process Library is the unique and indispensable process listing database since 2004 Now counting 140,000 processes and 55,000 DLLs. Join and subscribe now! System Tools SpeedUpMyPC PC Mechanic Toolbox ProcessQuicklink
__label__pos
0.959727
Uploaded image for project: 'Minecraft (Bedrock codebase)' 1. Minecraft (Bedrock codebase) 2. MCPE-147023 Stronghold doesn't have a chance to generate below y=0 / negative Y levels XMLWordPrintable Details • Icon: Bug Bug • Resolution: Fixed • 1.18.10 • 1.18.10.20 Beta, 1.18.0.27 Beta, 1.18.0.24 Beta, 1.18.0.25 Beta, 1.18.0, 1.18.2 Hotfix • Confirmed • Multiple • 655402 Description In the 1.18 update, you can find structures below y=0 such as dungeons and mineshafts. However, strongholds cannot be found below y=0. This is already a feature on Java, so this can be considered a parity issue. Step to Reproduce 1. Create a new world. 2. Do /locate stronghold and teleport to that stronghold. 3. Check if it's generating below Y=0/on negative Y levels. 4. Repeat this from step 2 but by teleporting away from the previous stronghold. Expected Result Some of the strongholds are generating below Y=0/on negative Y levels. Observed Result None of them are generating below Y=0/on negative Y levels. Attachments Activity People MCPE4theBeacon [Helper] MCPE4theBeacon / lillybeacon Votes: 14 Vote for this issue Watchers: 5 Start watching this issue Dates Created: Updated: Resolved: CHK:
__label__pos
0.951738
1/* 2 +----------------------------------------------------------------------+ 3 | Zend Engine | 4 +----------------------------------------------------------------------+ 5 | Copyright (c) 1998-2014 Zend Technologies Ltd. (http://www.zend.com) | 6 +----------------------------------------------------------------------+ 7 | This source file is subject to version 2.00 of the Zend license, | 8 | that is bundled with this package in the file LICENSE, and is | 9 | available through the world-wide-web at the following url: | 10 | http://www.zend.com/license/2_00.txt. | 11 | If you did not receive a copy of the Zend license and are unable to | 12 | obtain it through the world-wide-web, please send a note to | 13 | [email protected] so we can mail you a copy immediately. | 14 +----------------------------------------------------------------------+ 15 | Authors: Marcus Boerger <[email protected]> | 16 | Nuno Lopes <[email protected]> | 17 | Scott MacVicar <[email protected]> | 18 | Flex version authors: | 19 | Andi Gutmans <[email protected]> | 20 | Zeev Suraski <[email protected]> | 21 +----------------------------------------------------------------------+ 22*/ 23 24/* $Id$ */ 25 26#if 0 27# define YYDEBUG(s, c) printf("state: %d char: %c\n", s, c) 28#else 29# define YYDEBUG(s, c) 30#endif 31 32#include "zend_language_scanner_defs.h" 33 34#include <errno.h> 35#include "zend.h" 36#ifdef PHP_WIN32 37# include <Winuser.h> 38#endif 39#include "zend_alloc.h" 40#include <zend_language_parser.h> 41#include "zend_compile.h" 42#include "zend_language_scanner.h" 43#include "zend_highlight.h" 44#include "zend_constants.h" 45#include "zend_variables.h" 46#include "zend_operators.h" 47#include "zend_API.h" 48#include "zend_strtod.h" 49#include "zend_exceptions.h" 50#include "zend_virtual_cwd.h" 51#include "tsrm_config_common.h" 52 53#define YYCTYPE unsigned char 54#define YYFILL(n) { if ((YYCURSOR + n) >= (YYLIMIT + ZEND_MMAP_AHEAD)) { return 0; } } 55#define YYCURSOR SCNG(yy_cursor) 56#define YYLIMIT SCNG(yy_limit) 57#define YYMARKER SCNG(yy_marker) 58 59#define YYGETCONDITION() SCNG(yy_state) 60#define YYSETCONDITION(s) SCNG(yy_state) = s 61 62#define STATE(name) yyc##name 63 64/* emulate flex constructs */ 65#define BEGIN(state) YYSETCONDITION(STATE(state)) 66#define YYSTATE YYGETCONDITION() 67#define yytext ((char*)SCNG(yy_text)) 68#define yyleng SCNG(yy_leng) 69#define yyless(x) do { YYCURSOR = (unsigned char*)yytext + x; \ 70 yyleng = (unsigned int)x; } while(0) 71#define yymore() goto yymore_restart 72 73/* perform sanity check. If this message is triggered you should 74 increase the ZEND_MMAP_AHEAD value in the zend_streams.h file */ 75/*!max:re2c */ 76#if ZEND_MMAP_AHEAD < YYMAXFILL 77# error ZEND_MMAP_AHEAD should be greater than or equal to YYMAXFILL 78#endif 79 80#ifdef HAVE_STDARG_H 81# include <stdarg.h> 82#endif 83 84#ifdef HAVE_UNISTD_H 85# include <unistd.h> 86#endif 87 88/* Globals Macros */ 89#define SCNG LANG_SCNG 90#ifdef ZTS 91ZEND_API ts_rsrc_id language_scanner_globals_id; 92#else 93ZEND_API zend_php_scanner_globals language_scanner_globals; 94#endif 95 96#define HANDLE_NEWLINES(s, l) \ 97do { \ 98 char *p = (s), *boundary = p+(l); \ 99 \ 100 while (p<boundary) { \ 101 if (*p == '\n' || (*p == '\r' && (*(p+1) != '\n'))) { \ 102 CG(zend_lineno)++; \ 103 } \ 104 p++; \ 105 } \ 106} while (0) 107 108#define HANDLE_NEWLINE(c) \ 109{ \ 110 if (c == '\n' || c == '\r') { \ 111 CG(zend_lineno)++; \ 112 } \ 113} 114 115/* To save initial string length after scanning to first variable */ 116#define SET_DOUBLE_QUOTES_SCANNED_LENGTH(len) SCNG(scanned_string_len) = (len) 117#define GET_DOUBLE_QUOTES_SCANNED_LENGTH() SCNG(scanned_string_len) 118 119#define IS_LABEL_START(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') || (c) == '_' || (c) >= 0x7F) 120 121#define ZEND_IS_OCT(c) ((c)>='0' && (c)<='7') 122#define ZEND_IS_HEX(c) (((c)>='0' && (c)<='9') || ((c)>='a' && (c)<='f') || ((c)>='A' && (c)<='F')) 123 124BEGIN_EXTERN_C() 125 126static size_t encoding_filter_script_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) 127{ 128 const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); 129 assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); 130 return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, LANG_SCNG(script_encoding) TSRMLS_CC); 131} 132 133static size_t encoding_filter_script_to_intermediate(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) 134{ 135 return zend_multibyte_encoding_converter(to, to_length, from, from_length, zend_multibyte_encoding_utf8, LANG_SCNG(script_encoding) TSRMLS_CC); 136} 137 138static size_t encoding_filter_intermediate_to_script(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) 139{ 140 return zend_multibyte_encoding_converter(to, to_length, from, from_length, 141LANG_SCNG(script_encoding), zend_multibyte_encoding_utf8 TSRMLS_CC); 142} 143 144static size_t encoding_filter_intermediate_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) 145{ 146 const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); 147 assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); 148 return zend_multibyte_encoding_converter(to, to_length, from, from_length, 149internal_encoding, zend_multibyte_encoding_utf8 TSRMLS_CC); 150} 151 152 153static void _yy_push_state(int new_state TSRMLS_DC) 154{ 155 zend_stack_push(&SCNG(state_stack), (void *) &YYGETCONDITION()); 156 YYSETCONDITION(new_state); 157} 158 159#define yy_push_state(state_and_tsrm) _yy_push_state(yyc##state_and_tsrm) 160 161static void yy_pop_state(TSRMLS_D) 162{ 163 int *stack_state = zend_stack_top(&SCNG(state_stack)); 164 YYSETCONDITION(*stack_state); 165 zend_stack_del_top(&SCNG(state_stack)); 166} 167 168static void yy_scan_buffer(char *str, unsigned int len TSRMLS_DC) 169{ 170 YYCURSOR = (YYCTYPE*)str; 171 YYLIMIT = YYCURSOR + len; 172 if (!SCNG(yy_start)) { 173 SCNG(yy_start) = YYCURSOR; 174 } 175} 176 177void startup_scanner(TSRMLS_D) 178{ 179 CG(parse_error) = 0; 180 CG(doc_comment) = NULL; 181 zend_stack_init(&SCNG(state_stack), sizeof(int)); 182 zend_ptr_stack_init(&SCNG(heredoc_label_stack)); 183} 184 185static void heredoc_label_dtor(zend_heredoc_label *heredoc_label) { 186 efree(heredoc_label->label); 187} 188 189void shutdown_scanner(TSRMLS_D) 190{ 191 CG(parse_error) = 0; 192 RESET_DOC_COMMENT(); 193 zend_stack_destroy(&SCNG(state_stack)); 194 zend_ptr_stack_clean(&SCNG(heredoc_label_stack), (void (*)(void *)) &heredoc_label_dtor, 1); 195 zend_ptr_stack_destroy(&SCNG(heredoc_label_stack)); 196} 197 198ZEND_API void zend_save_lexical_state(zend_lex_state *lex_state TSRMLS_DC) 199{ 200 lex_state->yy_leng = SCNG(yy_leng); 201 lex_state->yy_start = SCNG(yy_start); 202 lex_state->yy_text = SCNG(yy_text); 203 lex_state->yy_cursor = SCNG(yy_cursor); 204 lex_state->yy_marker = SCNG(yy_marker); 205 lex_state->yy_limit = SCNG(yy_limit); 206 207 lex_state->state_stack = SCNG(state_stack); 208 zend_stack_init(&SCNG(state_stack), sizeof(int)); 209 210 lex_state->heredoc_label_stack = SCNG(heredoc_label_stack); 211 zend_ptr_stack_init(&SCNG(heredoc_label_stack)); 212 213 lex_state->in = SCNG(yy_in); 214 lex_state->yy_state = YYSTATE; 215 lex_state->filename = zend_get_compiled_filename(TSRMLS_C); 216 lex_state->lineno = CG(zend_lineno); 217 218 lex_state->script_org = SCNG(script_org); 219 lex_state->script_org_size = SCNG(script_org_size); 220 lex_state->script_filtered = SCNG(script_filtered); 221 lex_state->script_filtered_size = SCNG(script_filtered_size); 222 lex_state->input_filter = SCNG(input_filter); 223 lex_state->output_filter = SCNG(output_filter); 224 lex_state->script_encoding = SCNG(script_encoding); 225} 226 227ZEND_API void zend_restore_lexical_state(zend_lex_state *lex_state TSRMLS_DC) 228{ 229 SCNG(yy_leng) = lex_state->yy_leng; 230 SCNG(yy_start) = lex_state->yy_start; 231 SCNG(yy_text) = lex_state->yy_text; 232 SCNG(yy_cursor) = lex_state->yy_cursor; 233 SCNG(yy_marker) = lex_state->yy_marker; 234 SCNG(yy_limit) = lex_state->yy_limit; 235 236 zend_stack_destroy(&SCNG(state_stack)); 237 SCNG(state_stack) = lex_state->state_stack; 238 239 zend_ptr_stack_clean(&SCNG(heredoc_label_stack), (void (*)(void *)) &heredoc_label_dtor, 1); 240 zend_ptr_stack_destroy(&SCNG(heredoc_label_stack)); 241 SCNG(heredoc_label_stack) = lex_state->heredoc_label_stack; 242 243 SCNG(yy_in) = lex_state->in; 244 YYSETCONDITION(lex_state->yy_state); 245 CG(zend_lineno) = lex_state->lineno; 246 zend_restore_compiled_filename(lex_state->filename TSRMLS_CC); 247 248 if (SCNG(script_filtered)) { 249 efree(SCNG(script_filtered)); 250 SCNG(script_filtered) = NULL; 251 } 252 SCNG(script_org) = lex_state->script_org; 253 SCNG(script_org_size) = lex_state->script_org_size; 254 SCNG(script_filtered) = lex_state->script_filtered; 255 SCNG(script_filtered_size) = lex_state->script_filtered_size; 256 SCNG(input_filter) = lex_state->input_filter; 257 SCNG(output_filter) = lex_state->output_filter; 258 SCNG(script_encoding) = lex_state->script_encoding; 259 260 RESET_DOC_COMMENT(); 261} 262 263ZEND_API void zend_destroy_file_handle(zend_file_handle *file_handle TSRMLS_DC) 264{ 265 zend_llist_del_element(&CG(open_files), file_handle, (int (*)(void *, void *)) zend_compare_file_handles); 266 /* zend_file_handle_dtor() operates on the copy, so we have to NULLify the original here */ 267 file_handle->opened_path = NULL; 268 if (file_handle->free_filename) { 269 file_handle->filename = NULL; 270 } 271} 272 273#define BOM_UTF32_BE "\x00\x00\xfe\xff" 274#define BOM_UTF32_LE "\xff\xfe\x00\x00" 275#define BOM_UTF16_BE "\xfe\xff" 276#define BOM_UTF16_LE "\xff\xfe" 277#define BOM_UTF8 "\xef\xbb\xbf" 278 279static const zend_encoding *zend_multibyte_detect_utf_encoding(const unsigned char *script, size_t script_size TSRMLS_DC) 280{ 281 const unsigned char *p; 282 int wchar_size = 2; 283 int le = 0; 284 285 /* utf-16 or utf-32? */ 286 p = script; 287 while ((p-script) < script_size) { 288 p = memchr(p, 0, script_size-(p-script)-2); 289 if (!p) { 290 break; 291 } 292 if (*(p+1) == '\0' && *(p+2) == '\0') { 293 wchar_size = 4; 294 break; 295 } 296 297 /* searching for UTF-32 specific byte orders, so this will do */ 298 p += 4; 299 } 300 301 /* BE or LE? */ 302 p = script; 303 while ((p-script) < script_size) { 304 if (*p == '\0' && *(p+wchar_size-1) != '\0') { 305 /* BE */ 306 le = 0; 307 break; 308 } else if (*p != '\0' && *(p+wchar_size-1) == '\0') { 309 /* LE* */ 310 le = 1; 311 break; 312 } 313 p += wchar_size; 314 } 315 316 if (wchar_size == 2) { 317 return le ? zend_multibyte_encoding_utf16le : zend_multibyte_encoding_utf16be; 318 } else { 319 return le ? zend_multibyte_encoding_utf32le : zend_multibyte_encoding_utf32be; 320 } 321 322 return NULL; 323} 324 325static const zend_encoding* zend_multibyte_detect_unicode(TSRMLS_D) 326{ 327 const zend_encoding *script_encoding = NULL; 328 int bom_size; 329 unsigned char *pos1, *pos2; 330 331 if (LANG_SCNG(script_org_size) < sizeof(BOM_UTF32_LE)-1) { 332 return NULL; 333 } 334 335 /* check out BOM */ 336 if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_BE, sizeof(BOM_UTF32_BE)-1)) { 337 script_encoding = zend_multibyte_encoding_utf32be; 338 bom_size = sizeof(BOM_UTF32_BE)-1; 339 } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_LE, sizeof(BOM_UTF32_LE)-1)) { 340 script_encoding = zend_multibyte_encoding_utf32le; 341 bom_size = sizeof(BOM_UTF32_LE)-1; 342 } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_BE, sizeof(BOM_UTF16_BE)-1)) { 343 script_encoding = zend_multibyte_encoding_utf16be; 344 bom_size = sizeof(BOM_UTF16_BE)-1; 345 } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_LE, sizeof(BOM_UTF16_LE)-1)) { 346 script_encoding = zend_multibyte_encoding_utf16le; 347 bom_size = sizeof(BOM_UTF16_LE)-1; 348 } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF8, sizeof(BOM_UTF8)-1)) { 349 script_encoding = zend_multibyte_encoding_utf8; 350 bom_size = sizeof(BOM_UTF8)-1; 351 } 352 353 if (script_encoding) { 354 /* remove BOM */ 355 LANG_SCNG(script_org) += bom_size; 356 LANG_SCNG(script_org_size) -= bom_size; 357 358 return script_encoding; 359 } 360 361 /* script contains NULL bytes -> auto-detection */ 362 if ((pos1 = memchr(LANG_SCNG(script_org), 0, LANG_SCNG(script_org_size)))) { 363 /* check if the NULL byte is after the __HALT_COMPILER(); */ 364 pos2 = LANG_SCNG(script_org); 365 366 while (pos1 - pos2 >= sizeof("__HALT_COMPILER();")-1) { 367 pos2 = memchr(pos2, '_', pos1 - pos2); 368 if (!pos2) break; 369 pos2++; 370 if (strncasecmp((char*)pos2, "_HALT_COMPILER", sizeof("_HALT_COMPILER")-1) == 0) { 371 pos2 += sizeof("_HALT_COMPILER")-1; 372 while (*pos2 == ' ' || 373 *pos2 == '\t' || 374 *pos2 == '\r' || 375 *pos2 == '\n') { 376 pos2++; 377 } 378 if (*pos2 == '(') { 379 pos2++; 380 while (*pos2 == ' ' || 381 *pos2 == '\t' || 382 *pos2 == '\r' || 383 *pos2 == '\n') { 384 pos2++; 385 } 386 if (*pos2 == ')') { 387 pos2++; 388 while (*pos2 == ' ' || 389 *pos2 == '\t' || 390 *pos2 == '\r' || 391 *pos2 == '\n') { 392 pos2++; 393 } 394 if (*pos2 == ';') { 395 return NULL; 396 } 397 } 398 } 399 } 400 } 401 /* make best effort if BOM is missing */ 402 return zend_multibyte_detect_utf_encoding(LANG_SCNG(script_org), LANG_SCNG(script_org_size) TSRMLS_CC); 403 } 404 405 return NULL; 406} 407 408static const zend_encoding* zend_multibyte_find_script_encoding(TSRMLS_D) 409{ 410 const zend_encoding *script_encoding; 411 412 if (CG(detect_unicode)) { 413 /* check out bom(byte order mark) and see if containing wchars */ 414 script_encoding = zend_multibyte_detect_unicode(TSRMLS_C); 415 if (script_encoding != NULL) { 416 /* bom or wchar detection is prior to 'script_encoding' option */ 417 return script_encoding; 418 } 419 } 420 421 /* if no script_encoding specified, just leave alone */ 422 if (!CG(script_encoding_list) || !CG(script_encoding_list_size)) { 423 return NULL; 424 } 425 426 /* if multiple encodings specified, detect automagically */ 427 if (CG(script_encoding_list_size) > 1) { 428 return zend_multibyte_encoding_detector(LANG_SCNG(script_org), LANG_SCNG(script_org_size), CG(script_encoding_list), CG(script_encoding_list_size) TSRMLS_CC); 429 } 430 431 return CG(script_encoding_list)[0]; 432} 433 434ZEND_API int zend_multibyte_set_filter(const zend_encoding *onetime_encoding TSRMLS_DC) 435{ 436 const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); 437 const zend_encoding *script_encoding = onetime_encoding ? onetime_encoding: zend_multibyte_find_script_encoding(TSRMLS_C); 438 439 if (!script_encoding) { 440 return FAILURE; 441 } 442 443 /* judge input/output filter */ 444 LANG_SCNG(script_encoding) = script_encoding; 445 LANG_SCNG(input_filter) = NULL; 446 LANG_SCNG(output_filter) = NULL; 447 448 if (!internal_encoding || LANG_SCNG(script_encoding) == internal_encoding) { 449 if (!zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { 450 /* and if not, work around w/ script_encoding -> utf-8 -> script_encoding conversion */ 451 LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; 452 LANG_SCNG(output_filter) = encoding_filter_intermediate_to_script; 453 } else { 454 LANG_SCNG(input_filter) = NULL; 455 LANG_SCNG(output_filter) = NULL; 456 } 457 return SUCCESS; 458 } 459 460 if (zend_multibyte_check_lexer_compatibility(internal_encoding)) { 461 LANG_SCNG(input_filter) = encoding_filter_script_to_internal; 462 LANG_SCNG(output_filter) = NULL; 463 } else if (zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { 464 LANG_SCNG(input_filter) = NULL; 465 LANG_SCNG(output_filter) = encoding_filter_script_to_internal; 466 } else { 467 /* both script and internal encodings are incompatible w/ flex */ 468 LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; 469 LANG_SCNG(output_filter) = encoding_filter_intermediate_to_internal; 470 } 471 472 return 0; 473} 474 475ZEND_API int open_file_for_scanning(zend_file_handle *file_handle TSRMLS_DC) 476{ 477 const char *file_path = NULL; 478 char *buf; 479 size_t size, offset = 0; 480 zend_string *compiled_filename; 481 482 /* The shebang line was read, get the current position to obtain the buffer start */ 483 if (CG(start_lineno) == 2 && file_handle->type == ZEND_HANDLE_FP && file_handle->handle.fp) { 484 if ((offset = ftell(file_handle->handle.fp)) == -1) { 485 offset = 0; 486 } 487 } 488 489 if (zend_stream_fixup(file_handle, &buf, &size TSRMLS_CC) == FAILURE) { 490 return FAILURE; 491 } 492 493 zend_llist_add_element(&CG(open_files), file_handle); 494 if (file_handle->handle.stream.handle >= (void*)file_handle && file_handle->handle.stream.handle <= (void*)(file_handle+1)) { 495 zend_file_handle *fh = (zend_file_handle*)zend_llist_get_last(&CG(open_files)); 496 size_t diff = (char*)file_handle->handle.stream.handle - (char*)file_handle; 497 fh->handle.stream.handle = (void*)(((char*)fh) + diff); 498 file_handle->handle.stream.handle = fh->handle.stream.handle; 499 } 500 501 /* Reset the scanner for scanning the new file */ 502 SCNG(yy_in) = file_handle; 503 SCNG(yy_start) = NULL; 504 505 if (size != -1) { 506 if (CG(multibyte)) { 507 SCNG(script_org) = (unsigned char*)buf; 508 SCNG(script_org_size) = size; 509 SCNG(script_filtered) = NULL; 510 511 zend_multibyte_set_filter(NULL TSRMLS_CC); 512 513 if (SCNG(input_filter)) { 514 if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { 515 zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " 516 "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); 517 } 518 buf = (char*)SCNG(script_filtered); 519 size = SCNG(script_filtered_size); 520 } 521 } 522 SCNG(yy_start) = (unsigned char *)buf - offset; 523 yy_scan_buffer(buf, size TSRMLS_CC); 524 } else { 525 zend_error_noreturn(E_COMPILE_ERROR, "zend_stream_mmap() failed"); 526 } 527 528 BEGIN(INITIAL); 529 530 if (file_handle->opened_path) { 531 file_path = file_handle->opened_path; 532 } else { 533 file_path = file_handle->filename; 534 } 535 536 compiled_filename = STR_INIT(file_path, strlen(file_path), 0); 537 zend_set_compiled_filename(compiled_filename TSRMLS_CC); 538 STR_RELEASE(compiled_filename); 539 540 if (CG(start_lineno)) { 541 CG(zend_lineno) = CG(start_lineno); 542 CG(start_lineno) = 0; 543 } else { 544 CG(zend_lineno) = 1; 545 } 546 547 RESET_DOC_COMMENT(); 548 CG(increment_lineno) = 0; 549 return SUCCESS; 550} 551END_EXTERN_C() 552 553 554ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) 555{ 556 zend_lex_state original_lex_state; 557 zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); 558 zend_op_array *original_active_op_array = CG(active_op_array); 559 zend_op_array *retval=NULL; 560 int compiler_result; 561 zend_bool compilation_successful=0; 562 znode retval_znode; 563 zend_bool original_in_compilation = CG(in_compilation); 564 565 retval_znode.op_type = IS_CONST; 566 ZVAL_LONG(&retval_znode.u.constant, 1); 567 568 zend_save_lexical_state(&original_lex_state TSRMLS_CC); 569 570 retval = op_array; /* success oriented */ 571 572 if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) { 573 if (type==ZEND_REQUIRE) { 574 zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC); 575 zend_bailout(); 576 } else { 577 zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC); 578 } 579 compilation_successful=0; 580 } else { 581 init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); 582 CG(in_compilation) = 1; 583 CG(active_op_array) = op_array; 584 zend_stack_push(&CG(context_stack), (void *) &CG(context)); 585 zend_init_compiler_context(TSRMLS_C); 586 compiler_result = zendparse(TSRMLS_C); 587 zend_do_return(&retval_znode, 0 TSRMLS_CC); 588 CG(in_compilation) = original_in_compilation; 589 if (compiler_result != 0) { /* parser error */ 590 zend_bailout(); 591 } 592 compilation_successful=1; 593 } 594 595 if (retval) { 596 CG(active_op_array) = original_active_op_array; 597 if (compilation_successful) { 598 pass_two(op_array TSRMLS_CC); 599 zend_release_labels(0 TSRMLS_CC); 600 } else { 601 efree(op_array); 602 retval = NULL; 603 } 604 } 605 zend_restore_lexical_state(&original_lex_state TSRMLS_CC); 606 return retval; 607} 608 609 610zend_op_array *compile_filename(int type, zval *filename TSRMLS_DC) 611{ 612 zend_file_handle file_handle; 613 zval tmp; 614 zend_op_array *retval; 615 char *opened_path = NULL; 616 617 if (Z_TYPE_P(filename) != IS_STRING) { 618 tmp = *filename; 619 zval_copy_ctor(&tmp); 620 convert_to_string(&tmp); 621 filename = &tmp; 622 } 623 file_handle.filename = Z_STRVAL_P(filename); 624 file_handle.free_filename = 0; 625 file_handle.type = ZEND_HANDLE_FILENAME; 626 file_handle.opened_path = NULL; 627 file_handle.handle.fp = NULL; 628 629 retval = zend_compile_file(&file_handle, type TSRMLS_CC); 630 if (retval && file_handle.handle.stream.handle) { 631 if (!file_handle.opened_path) { 632 file_handle.opened_path = opened_path = estrndup(Z_STRVAL_P(filename), Z_STRLEN_P(filename)); 633 } 634 635 zend_hash_str_add_empty_element(&EG(included_files), file_handle.opened_path, strlen(file_handle.opened_path)); 636 637 if (opened_path) { 638 efree(opened_path); 639 } 640 } 641 zend_destroy_file_handle(&file_handle TSRMLS_CC); 642 643 if (filename==&tmp) { 644 zval_dtor(&tmp); 645 } 646 return retval; 647} 648 649ZEND_API int zend_prepare_string_for_scanning(zval *str, char *filename TSRMLS_DC) 650{ 651 char *buf; 652 size_t size, old_len; 653 zend_string *new_compiled_filename; 654 655 /* enforce ZEND_MMAP_AHEAD trailing NULLs for flex... */ 656 old_len = Z_STRLEN_P(str); 657 Z_STR_P(str) = STR_REALLOC(Z_STR_P(str), old_len + ZEND_MMAP_AHEAD, 0); 658 Z_TYPE_INFO_P(str) = IS_STRING_EX; 659 memset(Z_STRVAL_P(str) + old_len, 0, ZEND_MMAP_AHEAD + 1); 660 661 SCNG(yy_in) = NULL; 662 SCNG(yy_start) = NULL; 663 664 buf = Z_STRVAL_P(str); 665 size = old_len; 666 667 if (CG(multibyte)) { 668 SCNG(script_org) = (unsigned char*)buf; 669 SCNG(script_org_size) = size; 670 SCNG(script_filtered) = NULL; 671 672 zend_multibyte_set_filter(zend_multibyte_get_internal_encoding(TSRMLS_C) TSRMLS_CC); 673 674 if (SCNG(input_filter)) { 675 if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { 676 zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " 677 "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); 678 } 679 buf = (char*)SCNG(script_filtered); 680 size = SCNG(script_filtered_size); 681 } 682 } 683 684 yy_scan_buffer(buf, size TSRMLS_CC); 685 686 new_compiled_filename = STR_INIT(filename, strlen(filename), 0); 687 zend_set_compiled_filename(new_compiled_filename TSRMLS_CC); 688 STR_RELEASE(new_compiled_filename); 689 CG(zend_lineno) = 1; 690 CG(increment_lineno) = 0; 691 RESET_DOC_COMMENT(); 692 return SUCCESS; 693} 694 695 696ZEND_API size_t zend_get_scanned_file_offset(TSRMLS_D) 697{ 698 size_t offset = SCNG(yy_cursor) - SCNG(yy_start); 699 if (SCNG(input_filter)) { 700 size_t original_offset = offset, length = 0; 701 do { 702 unsigned char *p = NULL; 703 if ((size_t)-1 == SCNG(input_filter)(&p, &length, SCNG(script_org), offset TSRMLS_CC)) { 704 return (size_t)-1; 705 } 706 efree(p); 707 if (length > original_offset) { 708 offset--; 709 } else if (length < original_offset) { 710 offset++; 711 } 712 } while (original_offset != length); 713 } 714 return offset; 715} 716 717 718zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC) 719{ 720 zend_lex_state original_lex_state; 721 zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); 722 zend_op_array *original_active_op_array = CG(active_op_array); 723 zend_op_array *retval; 724 zval tmp; 725 int compiler_result; 726 zend_bool original_in_compilation = CG(in_compilation); 727 728 if (Z_STRLEN_P(source_string)==0) { 729 efree(op_array); 730 return NULL; 731 } 732 733 CG(in_compilation) = 1; 734 735 ZVAL_DUP(&tmp, source_string); 736 convert_to_string(&tmp); 737 source_string = &tmp; 738 739 zend_save_lexical_state(&original_lex_state TSRMLS_CC); 740 if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) { 741 efree(op_array); 742 retval = NULL; 743 } else { 744 zend_bool orig_interactive = CG(interactive); 745 746 CG(interactive) = 0; 747 init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); 748 CG(interactive) = orig_interactive; 749 CG(active_op_array) = op_array; 750 zend_stack_push(&CG(context_stack), (void *) &CG(context)); 751 zend_init_compiler_context(TSRMLS_C); 752 BEGIN(ST_IN_SCRIPTING); 753 compiler_result = zendparse(TSRMLS_C); 754 755 if (SCNG(script_filtered)) { 756 efree(SCNG(script_filtered)); 757 SCNG(script_filtered) = NULL; 758 } 759 760 if (compiler_result != 0) { 761 CG(active_op_array) = original_active_op_array; 762 CG(unclean_shutdown)=1; 763 destroy_op_array(op_array TSRMLS_CC); 764 efree(op_array); 765 retval = NULL; 766 } else { 767 zend_do_return(NULL, 0 TSRMLS_CC); 768 CG(active_op_array) = original_active_op_array; 769 pass_two(op_array TSRMLS_CC); 770 zend_release_labels(0 TSRMLS_CC); 771 retval = op_array; 772 } 773 } 774 zend_restore_lexical_state(&original_lex_state TSRMLS_CC); 775 zval_dtor(&tmp); 776 CG(in_compilation) = original_in_compilation; 777 return retval; 778} 779 780 781BEGIN_EXTERN_C() 782int highlight_file(char *filename, zend_syntax_highlighter_ini *syntax_highlighter_ini TSRMLS_DC) 783{ 784 zend_lex_state original_lex_state; 785 zend_file_handle file_handle; 786 787 file_handle.type = ZEND_HANDLE_FILENAME; 788 file_handle.filename = filename; 789 file_handle.free_filename = 0; 790 file_handle.opened_path = NULL; 791 zend_save_lexical_state(&original_lex_state TSRMLS_CC); 792 if (open_file_for_scanning(&file_handle TSRMLS_CC)==FAILURE) { 793 zend_message_dispatcher(ZMSG_FAILED_HIGHLIGHT_FOPEN, filename TSRMLS_CC); 794 zend_restore_lexical_state(&original_lex_state TSRMLS_CC); 795 return FAILURE; 796 } 797 zend_highlight(syntax_highlighter_ini TSRMLS_CC); 798 if (SCNG(script_filtered)) { 799 efree(SCNG(script_filtered)); 800 SCNG(script_filtered) = NULL; 801 } 802 zend_destroy_file_handle(&file_handle TSRMLS_CC); 803 zend_restore_lexical_state(&original_lex_state TSRMLS_CC); 804 return SUCCESS; 805} 806 807int highlight_string(zval *str, zend_syntax_highlighter_ini *syntax_highlighter_ini, char *str_name TSRMLS_DC) 808{ 809 zend_lex_state original_lex_state; 810 zval tmp = *str; 811 812 str = &tmp; 813 zval_copy_ctor(str); 814 zend_save_lexical_state(&original_lex_state TSRMLS_CC); 815 if (zend_prepare_string_for_scanning(str, str_name TSRMLS_CC)==FAILURE) { 816 zend_restore_lexical_state(&original_lex_state TSRMLS_CC); 817 return FAILURE; 818 } 819 BEGIN(INITIAL); 820 zend_highlight(syntax_highlighter_ini TSRMLS_CC); 821 if (SCNG(script_filtered)) { 822 efree(SCNG(script_filtered)); 823 SCNG(script_filtered) = NULL; 824 } 825 zend_restore_lexical_state(&original_lex_state TSRMLS_CC); 826 zval_dtor(str); 827 return SUCCESS; 828} 829 830ZEND_API void zend_multibyte_yyinput_again(zend_encoding_filter old_input_filter, const zend_encoding *old_encoding TSRMLS_DC) 831{ 832 size_t length; 833 unsigned char *new_yy_start; 834 835 /* convert and set */ 836 if (!SCNG(input_filter)) { 837 if (SCNG(script_filtered)) { 838 efree(SCNG(script_filtered)); 839 SCNG(script_filtered) = NULL; 840 } 841 SCNG(script_filtered_size) = 0; 842 length = SCNG(script_org_size); 843 new_yy_start = SCNG(script_org); 844 } else { 845 if ((size_t)-1 == SCNG(input_filter)(&new_yy_start, &length, SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { 846 zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " 847 "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); 848 } 849 if (SCNG(script_filtered)) { 850 efree(SCNG(script_filtered)); 851 } 852 SCNG(script_filtered) = new_yy_start; 853 SCNG(script_filtered_size) = length; 854 } 855 856 SCNG(yy_cursor) = new_yy_start + (SCNG(yy_cursor) - SCNG(yy_start)); 857 SCNG(yy_marker) = new_yy_start + (SCNG(yy_marker) - SCNG(yy_start)); 858 SCNG(yy_text) = new_yy_start + (SCNG(yy_text) - SCNG(yy_start)); 859 SCNG(yy_limit) = new_yy_start + (SCNG(yy_limit) - SCNG(yy_start)); 860 861 SCNG(yy_start) = new_yy_start; 862} 863 864 865// TODO: avoid reallocation ??? 866# define zend_copy_value(zendlval, yytext, yyleng) \ 867 if (SCNG(output_filter)) { \ 868 size_t sz = 0; \ 869 char *s = NULL; \ 870 SCNG(output_filter)((unsigned char **)&s, &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); \ 871 ZVAL_STRINGL(zendlval, s, sz); \ 872 efree(s); \ 873 } else { \ 874 ZVAL_STRINGL(zendlval, yytext, yyleng); \ 875 } 876 877// TODO: some extensions might need content, but we don't copy it intentional ??? 878#if 0 879# define DUMMY_STRINGL(zendlval, yytext, yyleng) \ 880 ZVAL_STRINGL(zendlval, yytext, yyleng) 881#else 882# define DUMMY_STRINGL(zendlval, yytext, yyleng) \ 883 ZVAL_EMPTY_STRING(zendlval) 884#endif 885 886static void zend_scan_escape_string(zval *zendlval, char *str, int len, char quote_type TSRMLS_DC) 887{ 888 register char *s, *t; 889 char *end; 890 891 ZVAL_STRINGL(zendlval, str, len); 892 893 /* convert escape sequences */ 894 s = t = Z_STRVAL_P(zendlval); 895 end = s+Z_STRLEN_P(zendlval); 896 while (s<end) { 897 if (*s=='\\') { 898 s++; 899 if (s >= end) { 900 *t++ = '\\'; 901 break; 902 } 903 904 switch(*s) { 905 case 'n': 906 *t++ = '\n'; 907 Z_STRLEN_P(zendlval)--; 908 break; 909 case 'r': 910 *t++ = '\r'; 911 Z_STRLEN_P(zendlval)--; 912 break; 913 case 't': 914 *t++ = '\t'; 915 Z_STRLEN_P(zendlval)--; 916 break; 917 case 'f': 918 *t++ = '\f'; 919 Z_STRLEN_P(zendlval)--; 920 break; 921 case 'v': 922 *t++ = '\v'; 923 Z_STRLEN_P(zendlval)--; 924 break; 925 case 'e': 926#ifdef PHP_WIN32 927 *t++ = VK_ESCAPE; 928#else 929 *t++ = '\e'; 930#endif 931 Z_STRLEN_P(zendlval)--; 932 break; 933 case '"': 934 case '`': 935 if (*s != quote_type) { 936 *t++ = '\\'; 937 *t++ = *s; 938 break; 939 } 940 case '\\': 941 case '$': 942 *t++ = *s; 943 Z_STRLEN_P(zendlval)--; 944 break; 945 case 'x': 946 case 'X': 947 if (ZEND_IS_HEX(*(s+1))) { 948 char hex_buf[3] = { 0, 0, 0 }; 949 950 Z_STRLEN_P(zendlval)--; /* for the 'x' */ 951 952 hex_buf[0] = *(++s); 953 Z_STRLEN_P(zendlval)--; 954 if (ZEND_IS_HEX(*(s+1))) { 955 hex_buf[1] = *(++s); 956 Z_STRLEN_P(zendlval)--; 957 } 958 *t++ = (char) strtol(hex_buf, NULL, 16); 959 } else { 960 *t++ = '\\'; 961 *t++ = *s; 962 } 963 break; 964 default: 965 /* check for an octal */ 966 if (ZEND_IS_OCT(*s)) { 967 char octal_buf[4] = { 0, 0, 0, 0 }; 968 969 octal_buf[0] = *s; 970 Z_STRLEN_P(zendlval)--; 971 if (ZEND_IS_OCT(*(s+1))) { 972 octal_buf[1] = *(++s); 973 Z_STRLEN_P(zendlval)--; 974 if (ZEND_IS_OCT(*(s+1))) { 975 octal_buf[2] = *(++s); 976 Z_STRLEN_P(zendlval)--; 977 } 978 } 979 *t++ = (char) strtol(octal_buf, NULL, 8); 980 } else { 981 *t++ = '\\'; 982 *t++ = *s; 983 } 984 break; 985 } 986 } else { 987 *t++ = *s; 988 } 989 990 if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { 991 CG(zend_lineno)++; 992 } 993 s++; 994 } 995 *t = 0; 996 if (SCNG(output_filter)) { 997 size_t sz = 0; 998 unsigned char *str; 999 // TODO: avoid realocation ??? 1000 s = Z_STRVAL_P(zendlval); 1001 SCNG(output_filter)(&str, &sz, (unsigned char *)s, (size_t)Z_STRLEN_P(zendlval) TSRMLS_CC); 1002 zval_ptr_dtor(zendlval); 1003 ZVAL_STRINGL(zendlval, str, sz); 1004 efree(str); 1005 } 1006} 1007 1008 1009int lex_scan(zval *zendlval TSRMLS_DC) 1010{ 1011restart: 1012 SCNG(yy_text) = YYCURSOR; 1013 1014yymore_restart: 1015 1016/*!re2c 1017re2c:yyfill:check = 0; 1018LNUM [0-9]+ 1019DNUM ([0-9]*"."[0-9]+)|([0-9]+"."[0-9]*) 1020EXPONENT_DNUM (({LNUM}|{DNUM})[eE][+-]?{LNUM}) 1021HNUM "0x"[0-9a-fA-F]+ 1022BNUM "0b"[01]+ 1023LABEL [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]* 1024WHITESPACE [ \n\r\t]+ 1025TABS_AND_SPACES [ \t]* 1026TOKENS [;:,.\[\]()|^&+-/*=%!~$<>?@] 1027ANY_CHAR [^] 1028NEWLINE ("\r"|"\n"|"\r\n") 1029 1030/* compute yyleng before each rule */ 1031<!*> := yyleng = YYCURSOR - SCNG(yy_text); 1032 1033<ST_IN_SCRIPTING>"exit" { 1034 return T_EXIT; 1035} 1036 1037<ST_IN_SCRIPTING>"die" { 1038 return T_EXIT; 1039} 1040 1041<ST_IN_SCRIPTING>"function" { 1042 return T_FUNCTION; 1043} 1044 1045<ST_IN_SCRIPTING>"const" { 1046 return T_CONST; 1047} 1048 1049<ST_IN_SCRIPTING>"return" { 1050 return T_RETURN; 1051} 1052 1053<ST_IN_SCRIPTING>"yield" { 1054 return T_YIELD; 1055} 1056 1057<ST_IN_SCRIPTING>"try" { 1058 return T_TRY; 1059} 1060 1061<ST_IN_SCRIPTING>"catch" { 1062 return T_CATCH; 1063} 1064 1065<ST_IN_SCRIPTING>"finally" { 1066 return T_FINALLY; 1067} 1068 1069<ST_IN_SCRIPTING>"throw" { 1070 return T_THROW; 1071} 1072 1073<ST_IN_SCRIPTING>"if" { 1074 return T_IF; 1075} 1076 1077<ST_IN_SCRIPTING>"elseif" { 1078 return T_ELSEIF; 1079} 1080 1081<ST_IN_SCRIPTING>"endif" { 1082 return T_ENDIF; 1083} 1084 1085<ST_IN_SCRIPTING>"else" { 1086 return T_ELSE; 1087} 1088 1089<ST_IN_SCRIPTING>"while" { 1090 return T_WHILE; 1091} 1092 1093<ST_IN_SCRIPTING>"endwhile" { 1094 return T_ENDWHILE; 1095} 1096 1097<ST_IN_SCRIPTING>"do" { 1098 return T_DO; 1099} 1100 1101<ST_IN_SCRIPTING>"for" { 1102 return T_FOR; 1103} 1104 1105<ST_IN_SCRIPTING>"endfor" { 1106 return T_ENDFOR; 1107} 1108 1109<ST_IN_SCRIPTING>"foreach" { 1110 return T_FOREACH; 1111} 1112 1113<ST_IN_SCRIPTING>"endforeach" { 1114 return T_ENDFOREACH; 1115} 1116 1117<ST_IN_SCRIPTING>"declare" { 1118 return T_DECLARE; 1119} 1120 1121<ST_IN_SCRIPTING>"enddeclare" { 1122 return T_ENDDECLARE; 1123} 1124 1125<ST_IN_SCRIPTING>"instanceof" { 1126 return T_INSTANCEOF; 1127} 1128 1129<ST_IN_SCRIPTING>"as" { 1130 return T_AS; 1131} 1132 1133<ST_IN_SCRIPTING>"switch" { 1134 return T_SWITCH; 1135} 1136 1137<ST_IN_SCRIPTING>"endswitch" { 1138 return T_ENDSWITCH; 1139} 1140 1141<ST_IN_SCRIPTING>"case" { 1142 return T_CASE; 1143} 1144 1145<ST_IN_SCRIPTING>"default" { 1146 return T_DEFAULT; 1147} 1148 1149<ST_IN_SCRIPTING>"break" { 1150 return T_BREAK; 1151} 1152 1153<ST_IN_SCRIPTING>"continue" { 1154 return T_CONTINUE; 1155} 1156 1157<ST_IN_SCRIPTING>"goto" { 1158 return T_GOTO; 1159} 1160 1161<ST_IN_SCRIPTING>"echo" { 1162 return T_ECHO; 1163} 1164 1165<ST_IN_SCRIPTING>"print" { 1166 return T_PRINT; 1167} 1168 1169<ST_IN_SCRIPTING>"class" { 1170 return T_CLASS; 1171} 1172 1173<ST_IN_SCRIPTING>"interface" { 1174 return T_INTERFACE; 1175} 1176 1177<ST_IN_SCRIPTING>"trait" { 1178 return T_TRAIT; 1179} 1180 1181<ST_IN_SCRIPTING>"extends" { 1182 return T_EXTENDS; 1183} 1184 1185<ST_IN_SCRIPTING>"implements" { 1186 return T_IMPLEMENTS; 1187} 1188 1189<ST_IN_SCRIPTING>"->" { 1190 yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); 1191 return T_OBJECT_OPERATOR; 1192} 1193 1194<ST_IN_SCRIPTING,ST_LOOKING_FOR_PROPERTY>{WHITESPACE}+ { 1195 DUMMY_STRINGL(zendlval, yytext, yyleng); 1196 HANDLE_NEWLINES(yytext, yyleng); 1197 return T_WHITESPACE; 1198} 1199 1200<ST_LOOKING_FOR_PROPERTY>"->" { 1201 return T_OBJECT_OPERATOR; 1202} 1203 1204<ST_LOOKING_FOR_PROPERTY>{LABEL} { 1205 yy_pop_state(TSRMLS_C); 1206 zend_copy_value(zendlval, yytext, yyleng); 1207 return T_STRING; 1208} 1209 1210<ST_LOOKING_FOR_PROPERTY>{ANY_CHAR} { 1211 yyless(0); 1212 yy_pop_state(TSRMLS_C); 1213 goto restart; 1214} 1215 1216<ST_IN_SCRIPTING>"::" { 1217 return T_PAAMAYIM_NEKUDOTAYIM; 1218} 1219 1220<ST_IN_SCRIPTING>"\\" { 1221 return T_NS_SEPARATOR; 1222} 1223 1224<ST_IN_SCRIPTING>"..." { 1225 return T_ELLIPSIS; 1226} 1227 1228<ST_IN_SCRIPTING>"new" { 1229 return T_NEW; 1230} 1231 1232<ST_IN_SCRIPTING>"clone" { 1233 return T_CLONE; 1234} 1235 1236<ST_IN_SCRIPTING>"var" { 1237 return T_VAR; 1238} 1239 1240<ST_IN_SCRIPTING>"("{TABS_AND_SPACES}("int"|"integer"){TABS_AND_SPACES}")" { 1241 return T_INT_CAST; 1242} 1243 1244<ST_IN_SCRIPTING>"("{TABS_AND_SPACES}("real"|"double"|"float"){TABS_AND_SPACES}")" { 1245 return T_DOUBLE_CAST; 1246} 1247 1248<ST_IN_SCRIPTING>"("{TABS_AND_SPACES}("string"|"binary"){TABS_AND_SPACES}")" { 1249 return T_STRING_CAST; 1250} 1251 1252<ST_IN_SCRIPTING>"("{TABS_AND_SPACES}"array"{TABS_AND_SPACES}")" { 1253 return T_ARRAY_CAST; 1254} 1255 1256<ST_IN_SCRIPTING>"("{TABS_AND_SPACES}"object"{TABS_AND_SPACES}")" { 1257 return T_OBJECT_CAST; 1258} 1259 1260<ST_IN_SCRIPTING>"("{TABS_AND_SPACES}("bool"|"boolean"){TABS_AND_SPACES}")" { 1261 return T_BOOL_CAST; 1262} 1263 1264<ST_IN_SCRIPTING>"("{TABS_AND_SPACES}("unset"){TABS_AND_SPACES}")" { 1265 return T_UNSET_CAST; 1266} 1267 1268<ST_IN_SCRIPTING>"eval" { 1269 return T_EVAL; 1270} 1271 1272<ST_IN_SCRIPTING>"include" { 1273 return T_INCLUDE; 1274} 1275 1276<ST_IN_SCRIPTING>"include_once" { 1277 return T_INCLUDE_ONCE; 1278} 1279 1280<ST_IN_SCRIPTING>"require" { 1281 return T_REQUIRE; 1282} 1283 1284<ST_IN_SCRIPTING>"require_once" { 1285 return T_REQUIRE_ONCE; 1286} 1287 1288<ST_IN_SCRIPTING>"namespace" { 1289 return T_NAMESPACE; 1290} 1291 1292<ST_IN_SCRIPTING>"use" { 1293 return T_USE; 1294} 1295 1296<ST_IN_SCRIPTING>"insteadof" { 1297 return T_INSTEADOF; 1298} 1299 1300<ST_IN_SCRIPTING>"global" { 1301 return T_GLOBAL; 1302} 1303 1304<ST_IN_SCRIPTING>"isset" { 1305 return T_ISSET; 1306} 1307 1308<ST_IN_SCRIPTING>"empty" { 1309 return T_EMPTY; 1310} 1311 1312<ST_IN_SCRIPTING>"__halt_compiler" { 1313 return T_HALT_COMPILER; 1314} 1315 1316<ST_IN_SCRIPTING>"static" { 1317 return T_STATIC; 1318} 1319 1320<ST_IN_SCRIPTING>"abstract" { 1321 return T_ABSTRACT; 1322} 1323 1324<ST_IN_SCRIPTING>"final" { 1325 return T_FINAL; 1326} 1327 1328<ST_IN_SCRIPTING>"private" { 1329 return T_PRIVATE; 1330} 1331 1332<ST_IN_SCRIPTING>"protected" { 1333 return T_PROTECTED; 1334} 1335 1336<ST_IN_SCRIPTING>"public" { 1337 return T_PUBLIC; 1338} 1339 1340<ST_IN_SCRIPTING>"unset" { 1341 return T_UNSET; 1342} 1343 1344<ST_IN_SCRIPTING>"=>" { 1345 return T_DOUBLE_ARROW; 1346} 1347 1348<ST_IN_SCRIPTING>"list" { 1349 return T_LIST; 1350} 1351 1352<ST_IN_SCRIPTING>"array" { 1353 return T_ARRAY; 1354} 1355 1356<ST_IN_SCRIPTING>"callable" { 1357 return T_CALLABLE; 1358} 1359 1360<ST_IN_SCRIPTING>"++" { 1361 return T_INC; 1362} 1363 1364<ST_IN_SCRIPTING>"--" { 1365 return T_DEC; 1366} 1367 1368<ST_IN_SCRIPTING>"===" { 1369 return T_IS_IDENTICAL; 1370} 1371 1372<ST_IN_SCRIPTING>"!==" { 1373 return T_IS_NOT_IDENTICAL; 1374} 1375 1376<ST_IN_SCRIPTING>"==" { 1377 return T_IS_EQUAL; 1378} 1379 1380<ST_IN_SCRIPTING>"!="|"<>" { 1381 return T_IS_NOT_EQUAL; 1382} 1383 1384<ST_IN_SCRIPTING>"<=" { 1385 return T_IS_SMALLER_OR_EQUAL; 1386} 1387 1388<ST_IN_SCRIPTING>">=" { 1389 return T_IS_GREATER_OR_EQUAL; 1390} 1391 1392<ST_IN_SCRIPTING>"+=" { 1393 return T_PLUS_EQUAL; 1394} 1395 1396<ST_IN_SCRIPTING>"-=" { 1397 return T_MINUS_EQUAL; 1398} 1399 1400<ST_IN_SCRIPTING>"*=" { 1401 return T_MUL_EQUAL; 1402} 1403 1404<ST_IN_SCRIPTING>"*\*" { 1405 return T_POW; 1406} 1407 1408<ST_IN_SCRIPTING>"*\*=" { 1409 return T_POW_EQUAL; 1410} 1411 1412<ST_IN_SCRIPTING>"/=" { 1413 return T_DIV_EQUAL; 1414} 1415 1416<ST_IN_SCRIPTING>".=" { 1417 return T_CONCAT_EQUAL; 1418} 1419 1420<ST_IN_SCRIPTING>"%=" { 1421 return T_MOD_EQUAL; 1422} 1423 1424<ST_IN_SCRIPTING>"<<=" { 1425 return T_SL_EQUAL; 1426} 1427 1428<ST_IN_SCRIPTING>">>=" { 1429 return T_SR_EQUAL; 1430} 1431 1432<ST_IN_SCRIPTING>"&=" { 1433 return T_AND_EQUAL; 1434} 1435 1436<ST_IN_SCRIPTING>"|=" { 1437 return T_OR_EQUAL; 1438} 1439 1440<ST_IN_SCRIPTING>"^=" { 1441 return T_XOR_EQUAL; 1442} 1443 1444<ST_IN_SCRIPTING>"||" { 1445 return T_BOOLEAN_OR; 1446} 1447 1448<ST_IN_SCRIPTING>"&&" { 1449 return T_BOOLEAN_AND; 1450} 1451 1452<ST_IN_SCRIPTING>"OR" { 1453 return T_LOGICAL_OR; 1454} 1455 1456<ST_IN_SCRIPTING>"AND" { 1457 return T_LOGICAL_AND; 1458} 1459 1460<ST_IN_SCRIPTING>"XOR" { 1461 return T_LOGICAL_XOR; 1462} 1463 1464<ST_IN_SCRIPTING>"<<" { 1465 return T_SL; 1466} 1467 1468<ST_IN_SCRIPTING>">>" { 1469 return T_SR; 1470} 1471 1472<ST_IN_SCRIPTING>{TOKENS} { 1473 return yytext[0]; 1474} 1475 1476 1477<ST_IN_SCRIPTING>"{" { 1478 yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); 1479 return '{'; 1480} 1481 1482 1483<ST_DOUBLE_QUOTES,ST_BACKQUOTE,ST_HEREDOC>"${" { 1484 yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); 1485 return T_DOLLAR_OPEN_CURLY_BRACES; 1486} 1487 1488 1489<ST_IN_SCRIPTING>"}" { 1490 RESET_DOC_COMMENT(); 1491 if (!zend_stack_is_empty(&SCNG(state_stack))) { 1492 yy_pop_state(TSRMLS_C); 1493 } 1494 return '}'; 1495} 1496 1497 1498<ST_LOOKING_FOR_VARNAME>{LABEL}[[}] { 1499 yyless(yyleng - 1); 1500 zend_copy_value(zendlval, yytext, yyleng); 1501 yy_pop_state(TSRMLS_C); 1502 yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); 1503 return T_STRING_VARNAME; 1504} 1505 1506 1507<ST_LOOKING_FOR_VARNAME>{ANY_CHAR} { 1508 yyless(0); 1509 yy_pop_state(TSRMLS_C); 1510 yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); 1511 goto restart; 1512} 1513 1514<ST_IN_SCRIPTING>{BNUM} { 1515 char *bin = yytext + 2; /* Skip "0b" */ 1516 int len = yyleng - 2; 1517 1518 /* Skip any leading 0s */ 1519 while (*bin == '0') { 1520 ++bin; 1521 --len; 1522 } 1523 1524 if (len < SIZEOF_LONG * 8) { 1525 if (len == 0) { 1526 ZVAL_LONG(zendlval, 0); 1527 } else { 1528 ZVAL_LONG(zendlval, strtol(bin, NULL, 2)); 1529 } 1530 return T_LNUMBER; 1531 } else { 1532 ZVAL_DOUBLE(zendlval, zend_bin_strtod(bin, NULL)); 1533 return T_DNUMBER; 1534 } 1535} 1536 1537<ST_IN_SCRIPTING>{LNUM} { 1538 if (yyleng < MAX_LENGTH_OF_LONG - 1) { /* Won't overflow */ 1539 ZVAL_LONG(zendlval, strtol(yytext, NULL, 0)); 1540 } else { 1541 errno = 0; 1542 ZVAL_LONG(zendlval, strtol(yytext, NULL, 0)); 1543 if (errno == ERANGE) { /* Overflow */ 1544 if (yytext[0] == '0') { /* octal overflow */ 1545 ZVAL_DOUBLE(zendlval, zend_oct_strtod(yytext, NULL)); 1546 } else { 1547 ZVAL_DOUBLE(zendlval, zend_strtod(yytext, NULL)); 1548 } 1549 return T_DNUMBER; 1550 } 1551 } 1552 return T_LNUMBER; 1553} 1554 1555<ST_IN_SCRIPTING>{HNUM} { 1556 char *hex = yytext + 2; /* Skip "0x" */ 1557 int len = yyleng - 2; 1558 1559 /* Skip any leading 0s */ 1560 while (*hex == '0') { 1561 hex++; 1562 len--; 1563 } 1564 1565 if (len < SIZEOF_LONG * 2 || (len == SIZEOF_LONG * 2 && *hex <= '7')) { 1566 if (len == 0) { 1567 ZVAL_LONG(zendlval, 0); 1568 } else { 1569 ZVAL_LONG(zendlval, strtol(hex, NULL, 16)); 1570 } 1571 return T_LNUMBER; 1572 } else { 1573 ZVAL_DOUBLE(zendlval, zend_hex_strtod(hex, NULL)); 1574 return T_DNUMBER; 1575 } 1576} 1577 1578<ST_VAR_OFFSET>[0]|([1-9][0-9]*) { /* Offset could be treated as a long */ 1579 if (yyleng < MAX_LENGTH_OF_LONG - 1 || (yyleng == MAX_LENGTH_OF_LONG - 1 && strcmp(yytext, long_min_digits) < 0)) { 1580 ZVAL_LONG(zendlval, strtol(yytext, NULL, 10)); 1581 } else { 1582 ZVAL_STRINGL(zendlval, yytext, yyleng); 1583 } 1584 return T_NUM_STRING; 1585} 1586 1587<ST_VAR_OFFSET>{LNUM}|{HNUM}|{BNUM} { /* Offset must be treated as a string */ 1588 ZVAL_STRINGL(zendlval, yytext, yyleng); 1589 return T_NUM_STRING; 1590} 1591 1592<ST_IN_SCRIPTING>{DNUM}|{EXPONENT_DNUM} { 1593 ZVAL_DOUBLE(zendlval, zend_strtod(yytext, NULL)); 1594 return T_DNUMBER; 1595} 1596 1597<ST_IN_SCRIPTING>"__CLASS__" { 1598 zend_class_entry *ce = CG(active_class_entry); 1599 if (ce && ZEND_ACC_TRAIT == (ce->ce_flags & ZEND_ACC_TRAIT)) { 1600 /* We create a special __CLASS__ constant that is going to be resolved 1601 at run-time */ 1602 ZVAL_STRINGL(zendlval, "__CLASS__", sizeof("__CLASS__") - 1); 1603 Z_TYPE_INFO_P(zendlval) = IS_CONSTANT_EX; 1604 } else { 1605 if (ce && ce->name) { 1606 ZVAL_STR(zendlval, STR_COPY(ce->name)); 1607 } else { 1608 ZVAL_EMPTY_STRING(zendlval); 1609 } 1610 } 1611 return T_CLASS_C; 1612} 1613 1614<ST_IN_SCRIPTING>"__TRAIT__" { 1615 zend_class_entry *ce = CG(active_class_entry); 1616 if (ce && ce->name && ZEND_ACC_TRAIT == (ce->ce_flags & ZEND_ACC_TRAIT)) { 1617 ZVAL_STR(zendlval, STR_COPY(ce->name)); 1618 } else { 1619 ZVAL_EMPTY_STRING(zendlval); 1620 } 1621 return T_TRAIT_C; 1622} 1623 1624<ST_IN_SCRIPTING>"__FUNCTION__" { 1625 zend_op_array *op_array = CG(active_op_array); 1626 if (op_array && op_array->function_name) { 1627 ZVAL_STR(zendlval, STR_COPY(op_array->function_name)); 1628 } else { 1629 ZVAL_EMPTY_STRING(zendlval); 1630 } 1631 return T_FUNC_C; 1632} 1633 1634<ST_IN_SCRIPTING>"__METHOD__" { 1635 if (CG(active_class_entry)) { 1636 int len = 0; 1637 1638 if (CG(active_class_entry)->name) { 1639 len += CG(active_class_entry)->name->len; 1640 } 1641 if (CG(active_op_array) && CG(active_op_array)->function_name) { 1642 len += sizeof("::")-1; 1643 len += CG(active_op_array)->function_name->len; 1644 } 1645 ZVAL_NEW_STR(zendlval, STR_ALLOC(len, 0)); 1646 len = 0; 1647 if (CG(active_class_entry)->name) { 1648 memcpy(Z_STRVAL_P(zendlval), CG(active_class_entry)->name->val, CG(active_class_entry)->name->len); 1649 len += CG(active_class_entry)->name->len; 1650 } 1651 if (CG(active_op_array) && CG(active_op_array)->function_name) { 1652 memcpy(Z_STRVAL_P(zendlval) + len, "::", sizeof("::")-1); 1653 len += sizeof("::")-1; 1654 memcpy(Z_STRVAL_P(zendlval) + len, CG(active_op_array)->function_name->val, CG(active_op_array)->function_name->len); 1655 len += CG(active_op_array)->function_name->len; 1656 } 1657 Z_STRVAL_P(zendlval)[len] = 0; 1658 } else if (CG(active_op_array) && CG(active_op_array)->function_name) { 1659 ZVAL_STR(zendlval, STR_COPY(CG(active_op_array)->function_name)); 1660 } else { 1661 ZVAL_EMPTY_STRING(zendlval); 1662 } 1663 return T_METHOD_C; 1664} 1665 1666<ST_IN_SCRIPTING>"__LINE__" { 1667 ZVAL_LONG(zendlval, CG(zend_lineno)); 1668 return T_LINE; 1669} 1670 1671<ST_IN_SCRIPTING>"__FILE__" { 1672 zend_string *filename = zend_get_compiled_filename(TSRMLS_C); 1673 1674 if (!filename) { 1675 ZVAL_EMPTY_STRING(zendlval); 1676 } else { 1677 ZVAL_STR(zendlval, STR_COPY(filename)); 1678 } 1679 return T_FILE; 1680} 1681 1682<ST_IN_SCRIPTING>"__DIR__" { 1683 zend_string *filename = zend_get_compiled_filename(TSRMLS_C); 1684 zend_string *dirname; 1685 1686 if (!filename) { 1687 filename = STR_EMPTY_ALLOC(); 1688 } 1689 1690 dirname = STR_INIT(filename->val, filename->len, 0); 1691 zend_dirname(dirname->val, dirname->len); 1692 1693 if (strcmp(dirname->val, ".") == 0) { 1694 dirname = STR_REALLOC(dirname, MAXPATHLEN, 0); 1695#if HAVE_GETCWD 1696 VCWD_GETCWD(dirname->val, MAXPATHLEN); 1697#elif HAVE_GETWD 1698 VCWD_GETWD(dirname->val); 1699#endif 1700 } 1701 1702 dirname->len = strlen(dirname->val); 1703 ZVAL_STR(zendlval, dirname); 1704 return T_DIR; 1705} 1706 1707<ST_IN_SCRIPTING>"__NAMESPACE__" { 1708 if (Z_TYPE(CG(current_namespace)) != IS_UNDEF) { 1709 ZVAL_DUP(zendlval, &CG(current_namespace)); 1710 } else { 1711 ZVAL_EMPTY_STRING(zendlval); 1712 } 1713 return T_NS_C; 1714} 1715 1716<INITIAL>"<script"{WHITESPACE}+"language"{WHITESPACE}*"="{WHITESPACE}*("php"|"\"php\""|"'php'"){WHITESPACE}*">" { 1717 YYCTYPE *bracket = (YYCTYPE*)zend_memrchr(yytext, '<', yyleng - (sizeof("script language=php>") - 1)); 1718 1719 if (bracket != SCNG(yy_text)) { 1720 /* Handle previously scanned HTML, as possible <script> tags found are assumed to not be PHP's */ 1721 YYCURSOR = bracket; 1722 goto inline_html; 1723 } 1724 1725 HANDLE_NEWLINES(yytext, yyleng); 1726 DUMMY_STRINGL(zendlval, yytext, yyleng); 1727 BEGIN(ST_IN_SCRIPTING); 1728 return T_OPEN_TAG; 1729} 1730 1731 1732<INITIAL>"<%=" { 1733 if (CG(asp_tags)) { 1734 DUMMY_STRINGL(zendlval, yytext, yyleng); 1735 BEGIN(ST_IN_SCRIPTING); 1736 return T_OPEN_TAG_WITH_ECHO; 1737 } else { 1738 goto inline_char_handler; 1739 } 1740} 1741 1742 1743<INITIAL>"<?=" { 1744 DUMMY_STRINGL(zendlval, yytext, yyleng); 1745 BEGIN(ST_IN_SCRIPTING); 1746 return T_OPEN_TAG_WITH_ECHO; 1747} 1748 1749 1750<INITIAL>"<%" { 1751 if (CG(asp_tags)) { 1752 DUMMY_STRINGL(zendlval, yytext, yyleng); 1753 BEGIN(ST_IN_SCRIPTING); 1754 return T_OPEN_TAG; 1755 } else { 1756 goto inline_char_handler; 1757 } 1758} 1759 1760 1761<INITIAL>"<?php"([ \t]|{NEWLINE}) { 1762 DUMMY_STRINGL(zendlval, yytext, yyleng); 1763 HANDLE_NEWLINE(yytext[yyleng-1]); 1764 BEGIN(ST_IN_SCRIPTING); 1765 return T_OPEN_TAG; 1766} 1767 1768 1769<INITIAL>"<?" { 1770 if (CG(short_tags)) { 1771 DUMMY_STRINGL(zendlval, yytext, yyleng); 1772 BEGIN(ST_IN_SCRIPTING); 1773 return T_OPEN_TAG; 1774 } else { 1775 goto inline_char_handler; 1776 } 1777} 1778 1779<INITIAL>{ANY_CHAR} { 1780 if (YYCURSOR > YYLIMIT) { 1781 return 0; 1782 } 1783 1784inline_char_handler: 1785 1786 while (1) { 1787 YYCTYPE *ptr = memchr(YYCURSOR, '<', YYLIMIT - YYCURSOR); 1788 1789 YYCURSOR = ptr ? ptr + 1 : YYLIMIT; 1790 1791 if (YYCURSOR < YYLIMIT) { 1792 switch (*YYCURSOR) { 1793 case '?': 1794 if (CG(short_tags) || !strncasecmp((char*)YYCURSOR + 1, "php", 3) || (*(YYCURSOR + 1) == '=')) { /* Assume [ \t\n\r] follows "php" */ 1795 break; 1796 } 1797 continue; 1798 case '%': 1799 if (CG(asp_tags)) { 1800 break; 1801 } 1802 continue; 1803 case 's': 1804 case 'S': 1805 /* Probably NOT an opening PHP <script> tag, so don't end the HTML chunk yet 1806 * If it is, the PHP <script> tag rule checks for any HTML scanned before it */ 1807 YYCURSOR--; 1808 yymore(); 1809 default: 1810 continue; 1811 } 1812 1813 YYCURSOR--; 1814 } 1815 1816 break; 1817 } 1818 1819inline_html: 1820 yyleng = YYCURSOR - SCNG(yy_text); 1821 1822 if (SCNG(output_filter)) { 1823 int readsize; 1824 char *s = NULL; 1825 size_t sz = 0; 1826 // TODO: avoid reallocation ??? 1827 readsize = SCNG(output_filter)((unsigned char **)&s, &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); 1828 ZVAL_STRINGL(zendlval, s, sz); 1829 efree(s); 1830 if (readsize < yyleng) { 1831 yyless(readsize); 1832 } 1833 } else { 1834 ZVAL_STRINGL(zendlval, yytext, yyleng); 1835 } 1836 HANDLE_NEWLINES(yytext, yyleng); 1837 return T_INLINE_HTML; 1838} 1839 1840 1841/* Make sure a label character follows "->", otherwise there is no property 1842 * and "->" will be taken literally 1843 */ 1844<ST_DOUBLE_QUOTES,ST_HEREDOC,ST_BACKQUOTE>"$"{LABEL}"->"[a-zA-Z_\x7f-\xff] { 1845 yyless(yyleng - 3); 1846 yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); 1847 zend_copy_value(zendlval, (yytext+1), (yyleng-1)); 1848 return T_VARIABLE; 1849} 1850 1851/* A [ always designates a variable offset, regardless of what follows 1852 */ 1853<ST_DOUBLE_QUOTES,ST_HEREDOC,ST_BACKQUOTE>"$"{LABEL}"[" { 1854 yyless(yyleng - 1); 1855 yy_push_state(ST_VAR_OFFSET TSRMLS_CC); 1856 zend_copy_value(zendlval, (yytext+1), (yyleng-1)); 1857 return T_VARIABLE; 1858} 1859 1860<ST_IN_SCRIPTING,ST_DOUBLE_QUOTES,ST_HEREDOC,ST_BACKQUOTE,ST_VAR_OFFSET>"$"{LABEL} { 1861 zend_copy_value(zendlval, (yytext+1), (yyleng-1)); 1862 return T_VARIABLE; 1863} 1864 1865<ST_VAR_OFFSET>"]" { 1866 yy_pop_state(TSRMLS_C); 1867 return ']'; 1868} 1869 1870<ST_VAR_OFFSET>{TOKENS}|[{}"`] { 1871 /* Only '[' can be valid, but returning other tokens will allow a more explicit parse error */ 1872 return yytext[0]; 1873} 1874 1875<ST_VAR_OFFSET>[ \n\r\t\\'#] { 1876 /* Invalid rule to return a more explicit parse error with proper line number */ 1877 yyless(0); 1878 yy_pop_state(TSRMLS_C); 1879 return T_ENCAPSED_AND_WHITESPACE; 1880} 1881 1882<ST_IN_SCRIPTING,ST_VAR_OFFSET>{LABEL} { 1883 zend_copy_value(zendlval, yytext, yyleng); 1884 return T_STRING; 1885} 1886 1887 1888<ST_IN_SCRIPTING>"#"|"//" { 1889 while (YYCURSOR < YYLIMIT) { 1890 switch (*YYCURSOR++) { 1891 case '\r': 1892 if (*YYCURSOR == '\n') { 1893 YYCURSOR++; 1894 } 1895 /* fall through */ 1896 case '\n': 1897 CG(zend_lineno)++; 1898 break; 1899 case '%': 1900 if (!CG(asp_tags)) { 1901 continue; 1902 } 1903 /* fall through */ 1904 case '?': 1905 if (*YYCURSOR == '>') { 1906 YYCURSOR--; 1907 break; 1908 } 1909 /* fall through */ 1910 default: 1911 continue; 1912 } 1913 1914 break; 1915 } 1916 1917 yyleng = YYCURSOR - SCNG(yy_text); 1918 1919 return T_COMMENT; 1920} 1921 1922<ST_IN_SCRIPTING>"/*"|"/**"{WHITESPACE} { 1923 int doc_com; 1924 1925 if (yyleng > 2) { 1926 doc_com = 1; 1927 RESET_DOC_COMMENT(); 1928 } else { 1929 doc_com = 0; 1930 } 1931 1932 while (YYCURSOR < YYLIMIT) { 1933 if (*YYCURSOR++ == '*' && *YYCURSOR == '/') { 1934 break; 1935 } 1936 } 1937 1938 if (YYCURSOR < YYLIMIT) { 1939 YYCURSOR++; 1940 } else { 1941 zend_error(E_COMPILE_WARNING, "Unterminated comment starting line %d", CG(zend_lineno)); 1942 } 1943 1944 yyleng = YYCURSOR - SCNG(yy_text); 1945 HANDLE_NEWLINES(yytext, yyleng); 1946 1947 if (doc_com) { 1948 CG(doc_comment) = STR_INIT(yytext, yyleng, 0); 1949 return T_DOC_COMMENT; 1950 } 1951 1952 return T_COMMENT; 1953} 1954 1955<ST_IN_SCRIPTING>("?>"|"</script"{WHITESPACE}*">"){NEWLINE}? { 1956 DUMMY_STRINGL(zendlval, yytext, yyleng); 1957 BEGIN(INITIAL); 1958 return T_CLOSE_TAG; /* implicit ';' at php-end tag */ 1959} 1960 1961 1962<ST_IN_SCRIPTING>"%>"{NEWLINE}? { 1963 if (CG(asp_tags)) { 1964 BEGIN(INITIAL); 1965 DUMMY_STRINGL(zendlval, yytext, yyleng); 1966 return T_CLOSE_TAG; /* implicit ';' at php-end tag */ 1967 } else { 1968 yyless(1); 1969 return yytext[0]; 1970 } 1971} 1972 1973 1974<ST_IN_SCRIPTING>b?['] { 1975 register char *s, *t; 1976 char *end; 1977 int bprefix = (yytext[0] != '\'') ? 1 : 0; 1978 1979 while (1) { 1980 if (YYCURSOR < YYLIMIT) { 1981 if (*YYCURSOR == '\'') { 1982 YYCURSOR++; 1983 yyleng = YYCURSOR - SCNG(yy_text); 1984 1985 break; 1986 } else if (*YYCURSOR++ == '\\' && YYCURSOR < YYLIMIT) { 1987 YYCURSOR++; 1988 } 1989 } else { 1990 yyleng = YYLIMIT - SCNG(yy_text); 1991 1992 /* Unclosed single quotes; treat similar to double quotes, but without a separate token 1993 * for ' (unrecognized by parser), instead of old flex fallback to "Unexpected character..." 1994 * rule, which continued in ST_IN_SCRIPTING state after the quote */ 1995 return T_ENCAPSED_AND_WHITESPACE; 1996 } 1997 } 1998 1999 ZVAL_STRINGL(zendlval, yytext+bprefix+1, yyleng-bprefix-2); 2000 2001 /* convert escape sequences */ 2002 s = t = Z_STRVAL_P(zendlval); 2003 end = s+Z_STRLEN_P(zendlval); 2004 while (s<end) { 2005 if (*s=='\\') { 2006 s++; 2007 2008 switch(*s) { 2009 case '\\': 2010 case '\'': 2011 *t++ = *s; 2012 Z_STRLEN_P(zendlval)--; 2013 break; 2014 default: 2015 *t++ = '\\'; 2016 *t++ = *s; 2017 break; 2018 } 2019 } else { 2020 *t++ = *s; 2021 } 2022 2023 if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { 2024 CG(zend_lineno)++; 2025 } 2026 s++; 2027 } 2028 *t = 0; 2029 2030 if (SCNG(output_filter)) { 2031 size_t sz = 0; 2032 char *str = NULL; 2033 s = Z_STRVAL_P(zendlval); 2034 // TODO: avoid reallocation ??? 2035 SCNG(output_filter)((unsigned char **)&str, &sz, (unsigned char *)s, (size_t)Z_STRLEN_P(zendlval) TSRMLS_CC); 2036 ZVAL_STRINGL(zendlval, str, sz); 2037 efree(s); 2038 } 2039 return T_CONSTANT_ENCAPSED_STRING; 2040} 2041 2042 2043<ST_IN_SCRIPTING>b?["] { 2044 int bprefix = (yytext[0] != '"') ? 1 : 0; 2045 2046 while (YYCURSOR < YYLIMIT) { 2047 switch (*YYCURSOR++) { 2048 case '"': 2049 yyleng = YYCURSOR - SCNG(yy_text); 2050 zend_scan_escape_string(zendlval, yytext+bprefix+1, yyleng-bprefix-2, '"' TSRMLS_CC); 2051 return T_CONSTANT_ENCAPSED_STRING; 2052 case '$': 2053 if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { 2054 break; 2055 } 2056 continue; 2057 case '{': 2058 if (*YYCURSOR == '$') { 2059 break; 2060 } 2061 continue; 2062 case '\\': 2063 if (YYCURSOR < YYLIMIT) { 2064 YYCURSOR++; 2065 } 2066 /* fall through */ 2067 default: 2068 continue; 2069 } 2070 2071 YYCURSOR--; 2072 break; 2073 } 2074 2075 /* Remember how much was scanned to save rescanning */ 2076 SET_DOUBLE_QUOTES_SCANNED_LENGTH(YYCURSOR - SCNG(yy_text) - yyleng); 2077 2078 YYCURSOR = SCNG(yy_text) + yyleng; 2079 2080 BEGIN(ST_DOUBLE_QUOTES); 2081 return '"'; 2082} 2083 2084 2085<ST_IN_SCRIPTING>b?"<<<"{TABS_AND_SPACES}({LABEL}|([']{LABEL}['])|(["]{LABEL}["])){NEWLINE} { 2086 char *s; 2087 int bprefix = (yytext[0] != '<') ? 1 : 0; 2088 zend_heredoc_label *heredoc_label = emalloc(sizeof(zend_heredoc_label)); 2089 2090 CG(zend_lineno)++; 2091 heredoc_label->length = yyleng-bprefix-3-1-(yytext[yyleng-2]=='\r'?1:0); 2092 s = yytext+bprefix+3; 2093 while ((*s == ' ') || (*s == '\t')) { 2094 s++; 2095 heredoc_label->length--; 2096 } 2097 2098 if (*s == '\'') { 2099 s++; 2100 heredoc_label->length -= 2; 2101 2102 BEGIN(ST_NOWDOC); 2103 } else { 2104 if (*s == '"') { 2105 s++; 2106 heredoc_label->length -= 2; 2107 } 2108 2109 BEGIN(ST_HEREDOC); 2110 } 2111 2112 heredoc_label->label = estrndup(s, heredoc_label->length); 2113 2114 /* Check for ending label on the next line */ 2115 if (heredoc_label->length < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, s, heredoc_label->length)) { 2116 YYCTYPE *end = YYCURSOR + heredoc_label->length; 2117 2118 if (*end == ';') { 2119 end++; 2120 } 2121 2122 if (*end == '\n' || *end == '\r') { 2123 BEGIN(ST_END_HEREDOC); 2124 } 2125 } 2126 2127 zend_ptr_stack_push(&SCNG(heredoc_label_stack), (void *) heredoc_label); 2128 2129 return T_START_HEREDOC; 2130} 2131 2132 2133<ST_IN_SCRIPTING>[`] { 2134 BEGIN(ST_BACKQUOTE); 2135 return '`'; 2136} 2137 2138 2139<ST_END_HEREDOC>{ANY_CHAR} { 2140 zend_heredoc_label *heredoc_label = zend_ptr_stack_pop(&SCNG(heredoc_label_stack)); 2141 2142 YYCURSOR += heredoc_label->length - 1; 2143 yyleng = heredoc_label->length; 2144 2145 heredoc_label_dtor(heredoc_label); 2146 efree(heredoc_label); 2147 2148 BEGIN(ST_IN_SCRIPTING); 2149 return T_END_HEREDOC; 2150} 2151 2152 2153<ST_DOUBLE_QUOTES,ST_BACKQUOTE,ST_HEREDOC>"{$" { 2154 Z_LVAL_P(zendlval) = (long) '{'; 2155 yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); 2156 yyless(1); 2157 return T_CURLY_OPEN; 2158} 2159 2160 2161<ST_DOUBLE_QUOTES>["] { 2162 BEGIN(ST_IN_SCRIPTING); 2163 return '"'; 2164} 2165 2166<ST_BACKQUOTE>[`] { 2167 BEGIN(ST_IN_SCRIPTING); 2168 return '`'; 2169} 2170 2171 2172<ST_DOUBLE_QUOTES>{ANY_CHAR} { 2173 if (GET_DOUBLE_QUOTES_SCANNED_LENGTH()) { 2174 YYCURSOR += GET_DOUBLE_QUOTES_SCANNED_LENGTH() - 1; 2175 SET_DOUBLE_QUOTES_SCANNED_LENGTH(0); 2176 2177 goto double_quotes_scan_done; 2178 } 2179 2180 if (YYCURSOR > YYLIMIT) { 2181 return 0; 2182 } 2183 if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { 2184 YYCURSOR++; 2185 } 2186 2187 while (YYCURSOR < YYLIMIT) { 2188 switch (*YYCURSOR++) { 2189 case '"': 2190 break; 2191 case '$': 2192 if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { 2193 break; 2194 } 2195 continue; 2196 case '{': 2197 if (*YYCURSOR == '$') { 2198 break; 2199 } 2200 continue; 2201 case '\\': 2202 if (YYCURSOR < YYLIMIT) { 2203 YYCURSOR++; 2204 } 2205 /* fall through */ 2206 default: 2207 continue; 2208 } 2209 2210 YYCURSOR--; 2211 break; 2212 } 2213 2214double_quotes_scan_done: 2215 yyleng = YYCURSOR - SCNG(yy_text); 2216 2217 zend_scan_escape_string(zendlval, yytext, yyleng, '"' TSRMLS_CC); 2218 return T_ENCAPSED_AND_WHITESPACE; 2219} 2220 2221 2222<ST_BACKQUOTE>{ANY_CHAR} { 2223 if (YYCURSOR > YYLIMIT) { 2224 return 0; 2225 } 2226 if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { 2227 YYCURSOR++; 2228 } 2229 2230 while (YYCURSOR < YYLIMIT) { 2231 switch (*YYCURSOR++) { 2232 case '`': 2233 break; 2234 case '$': 2235 if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { 2236 break; 2237 } 2238 continue; 2239 case '{': 2240 if (*YYCURSOR == '$') { 2241 break; 2242 } 2243 continue; 2244 case '\\': 2245 if (YYCURSOR < YYLIMIT) { 2246 YYCURSOR++; 2247 } 2248 /* fall through */ 2249 default: 2250 continue; 2251 } 2252 2253 YYCURSOR--; 2254 break; 2255 } 2256 2257 yyleng = YYCURSOR - SCNG(yy_text); 2258 2259 zend_scan_escape_string(zendlval, yytext, yyleng, '`' TSRMLS_CC); 2260 return T_ENCAPSED_AND_WHITESPACE; 2261} 2262 2263 2264<ST_HEREDOC>{ANY_CHAR} { 2265 int newline = 0; 2266 2267 zend_heredoc_label *heredoc_label = zend_ptr_stack_top(&SCNG(heredoc_label_stack)); 2268 2269 if (YYCURSOR > YYLIMIT) { 2270 return 0; 2271 } 2272 2273 YYCURSOR--; 2274 2275 while (YYCURSOR < YYLIMIT) { 2276 switch (*YYCURSOR++) { 2277 case '\r': 2278 if (*YYCURSOR == '\n') { 2279 YYCURSOR++; 2280 } 2281 /* fall through */ 2282 case '\n': 2283 /* Check for ending label on the next line */ 2284 if (IS_LABEL_START(*YYCURSOR) && heredoc_label->length < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, heredoc_label->label, heredoc_label->length)) { 2285 YYCTYPE *end = YYCURSOR + heredoc_label->length; 2286 2287 if (*end == ';') { 2288 end++; 2289 } 2290 2291 if (*end == '\n' || *end == '\r') { 2292 /* newline before label will be subtracted from returned text, but 2293 * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ 2294 if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { 2295 newline = 2; /* Windows newline */ 2296 } else { 2297 newline = 1; 2298 } 2299 2300 CG(increment_lineno) = 1; /* For newline before label */ 2301 BEGIN(ST_END_HEREDOC); 2302 2303 goto heredoc_scan_done; 2304 } 2305 } 2306 continue; 2307 case '$': 2308 if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { 2309 break; 2310 } 2311 continue; 2312 case '{': 2313 if (*YYCURSOR == '$') { 2314 break; 2315 } 2316 continue; 2317 case '\\': 2318 if (YYCURSOR < YYLIMIT && *YYCURSOR != '\n' && *YYCURSOR != '\r') { 2319 YYCURSOR++; 2320 } 2321 /* fall through */ 2322 default: 2323 continue; 2324 } 2325 2326 YYCURSOR--; 2327 break; 2328 } 2329 2330heredoc_scan_done: 2331 yyleng = YYCURSOR - SCNG(yy_text); 2332 2333 zend_scan_escape_string(zendlval, yytext, yyleng - newline, 0 TSRMLS_CC); 2334 return T_ENCAPSED_AND_WHITESPACE; 2335} 2336 2337 2338<ST_NOWDOC>{ANY_CHAR} { 2339 int newline = 0; 2340 2341 zend_heredoc_label *heredoc_label = zend_ptr_stack_top(&SCNG(heredoc_label_stack)); 2342 2343 if (YYCURSOR > YYLIMIT) { 2344 return 0; 2345 } 2346 2347 YYCURSOR--; 2348 2349 while (YYCURSOR < YYLIMIT) { 2350 switch (*YYCURSOR++) { 2351 case '\r': 2352 if (*YYCURSOR == '\n') { 2353 YYCURSOR++; 2354 } 2355 /* fall through */ 2356 case '\n': 2357 /* Check for ending label on the next line */ 2358 if (IS_LABEL_START(*YYCURSOR) && heredoc_label->length < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, heredoc_label->label, heredoc_label->length)) { 2359 YYCTYPE *end = YYCURSOR + heredoc_label->length; 2360 2361 if (*end == ';') { 2362 end++; 2363 } 2364 2365 if (*end == '\n' || *end == '\r') { 2366 /* newline before label will be subtracted from returned text, but 2367 * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ 2368 if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { 2369 newline = 2; /* Windows newline */ 2370 } else { 2371 newline = 1; 2372 } 2373 2374 CG(increment_lineno) = 1; /* For newline before label */ 2375 BEGIN(ST_END_HEREDOC); 2376 2377 goto nowdoc_scan_done; 2378 } 2379 } 2380 /* fall through */ 2381 default: 2382 continue; 2383 } 2384 } 2385 2386nowdoc_scan_done: 2387 yyleng = YYCURSOR - SCNG(yy_text); 2388 2389 zend_copy_value(zendlval, yytext, yyleng - newline); 2390 HANDLE_NEWLINES(yytext, yyleng - newline); 2391 return T_ENCAPSED_AND_WHITESPACE; 2392} 2393 2394 2395<ST_IN_SCRIPTING,ST_VAR_OFFSET>{ANY_CHAR} { 2396 if (YYCURSOR > YYLIMIT) { 2397 return 0; 2398 } 2399 2400 zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE); 2401 goto restart; 2402} 2403 2404*/ 2405} 2406
__label__pos
0.997461
Python To 32 Bit Signed Float With Code Examples Python To 32 Bit Signed Float With Code Examples This article will show you, via a series of examples, how to fix the Python To 32 Bit Signed Float problem that occurs in code. >>> '{:032b}'.format(100) '00000000000000000000000001100100' >>> '{:032b}'.format(8589934591) '111111111111111111111111111111111' >>> '{:032b}'.format(8589934591 + 1) '1000000000000000000000000000000000' # N.B. this is 33 digits long As we have seen, the Python To 32 Bit Signed Float problemcode was solved by using a number of different instances. Is Python float 32 or 64? Python's floating-point numbers are usually 64-bit floating-point numbers, nearly equivalent to np.float64 . In some unusual situations it may be useful to use floating-point numbers with more precision. How do you convert to float in Python? We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.03-Aug-2022 Does Python have 32 bit float? Python's floating-point numbers are usually 64-bit floating-point numbers, nearly equivalent to np. float64 . Is float guaranteed to be 32 bit? Knowing that the sizeof(float) is 32 bits may be sufficient, in general, but insufficient in all cases. IEEE 758 defines the well known 32-bit binary32 which is commonly implemented. But IEEE 758 also defines a 32-bit decimal32, which is primarily use for storage and not computation.09-Sept-2013 What is float 32 and float64? float32 is a 32 bit number – float64 uses 64 bits. That means that float64's take up twice as much memory – and doing operations on them may be a lot slower in some machine architectures. However, float64's can represent numbers much more accurately than 32 bit floats. They also allow much larger numbers to be stored.16-Apr-2017 Does Python use 64-bit float? Python float values are represented as 64-bit double-precision values. The maximum value any floating-point number can be is approx 1.8 x 10308. Any number greater than this will be indicated by the string inf in Python.16-Nov-2018 What is float () in Python? Python float() Function The float() function converts the specified value into a floating point number. How do you convert data type in Python? To convert between types, you simply use the type name as a function. There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.24-Jan-2020 Why can't I convert string to float? The Python "ValueError: could not convert string to float" occurs when we pass a string that cannot be converted to a float (e.g. an empty string or one containing characters) to the float() class. To solve the error, remove all unnecessary characters from the string.24-Apr-2022 What is floating-point 32 bit? Single-precision floating-point format (sometimes called FP32 or float32) is a computer number format, usually occupying 32 bits in computer memory; it represents a wide dynamic range of numeric values by using a floating radix point. Follow us on Social Media
__label__pos
0.999603
Virtual reality and augmented reality are two similar technologies, but they have important differences. In this article, we will examine the differences between virtual and augmented reality, and how these technologies can be used in various applications. Virtual reality: immersed in a virtual world Virtual reality is a technology that allows users to immerse themselves in a computer-generated virtual world. It requires a special headset that completely covers the user’s eyes and ears. Virtual reality creates a simulated 3D environment, in which the user can move around and interact with various objects. The user’s movements are tracked by sensors integrated into the headset, which allows for an immersive experience. The applications of virtual reality are numerous, including in video games, education, military training, product design, and medical therapy. Virtual reality offers a complete simulation experience, which means that users can find themselves in virtual environments that would be dangerous, expensive, or simply impossible to create in real life. Augmented reality: adding virtual elements to the real world Augmented reality is a technology that overlays virtual elements onto the real world. It is often used on a smartphone or tablet, but it can also be integrated into special glasses. Augmented reality uses the device’s camera to track the user’s movements and adds virtual elements to the live view. Applications of augmented reality include advertising, product visualization, training, and orientation in museums or theme parks. Unlike virtual reality, augmented reality does not create a fully virtual environment. It simply adds virtual elements to the existing environment. The user can still see and interact with the real world, but there are also virtual elements that can be seen. Conclusion Virtual reality and augmented reality are two rapidly expanding technologies that offer many possibilities. Virtual reality creates a virtual 3D environment, while augmented reality adds virtual elements to the real world. Although these two technologies may seem similar, it is important to understand their differences in order to choose the best application for each use. Virtual reality is ideal for situations where users need to be completely immersed in a simulated environment, while augmented reality is useful for applications that require the addition of virtual elements to the real world. With advances in technology, it will be interesting to see how these two technologies continue to evolve and be integrated into new applications.
__label__pos
0.913714
Enhance your tuples Wed May 03, 2017 · 110 words Standard Python tuples are lightweight sequences of immutable objects, yet their implementation may prove inconvenient in some scenarios. Instead, the collections module provides an enhanced version of a tuple, namedtuple, that makes member access more natural (rather than using integer indexes). Import namedtuple: from collections import namedtuple Create a namedtuple object: point = namedtuple('3DPoint', 'x y z') A = point(x=3, y=5, z=6) print(A) # 3DPoint(x=3, y=5, z=6) Access a specific member: print(A.x) # 3 Because namedtuples are backwards compatible with normal tuples, member access can be also done with indexes: print(A[0]) # 3 To convert a namedtuple to a dict (Actually an OrderedDict): print(A._asdict()) #OrderedDict([('x', 3), ('y', 5), ('z', 6)]) back · he thought · he could · so he did · main
__label__pos
0.996092
top of page Search What is the Metaverse? CEOs and business owners are always looking for the next big thing. They want to be ahead of the curve, and often, that means being the first to embrace new technology. But what is the Metaverse? Simply put, it’s a digital world that exists in parallel to our own. It’s a place where people can interact with each other and with digital content in a completely immersive environment. And it’s not just a gaming platform – businesses are starting to explore how they can use the Metaverse for marketing, training, and more. So if you’re curious about this emerging trend, read on to learn more about the Metaverse and what it could mean for your business. The Metaverse is a virtual world that exists parallel to our own Fantasies of a world that exists in parallel to our own have been around for centuries, but now with virtual reality technology they can become a reality. The Metaverse is a fascinating example of what happens when the physical and digital worlds collide. Imagine walking through city streets bustling with people and aliens, or racing off on an epic adventure that takes you across multiple galaxies. Beyond its awe-inspiring visuals, the Metaverse offers endless opportunities for creativity, collaboration and communication – making it ideal for gamers, entrepreneurs and people who simply want to explore their imaginations. It’s no wonder then why this parallel world has become an adventurous destination for so many; unveiling technological achievements that only decades ago seemed like impossible dreams. From sculptures to startups, from artwork to wellness programs – the Metaverse is unique and ever-evolving, giving all explorers something new to discover every time they go on an adventure. Who knows what extraordinary revelations await us as we venture deeper into this captivating parallel universe? It is a place where people and brands can interact with each other and explore their creativity It isn’t quite a utopia, but it does provide an ideal social netowork where people and brands can find each other, get to know one another, and express their creativity. Think of it as an online playground where everyone has something unique to offer. It’s the perfect place for businesses to share their ideas and reach out to customers in meaningful ways. People can also connect with others who are interested in similar interests or hobbies, expand their network of contacts, and explore new opportunities. You can access the Metaverse from anywhere in the world, as long as you have an internet connection The metaverse is an exciting new world of possibility, limited only by the imagination. With just an internet connection, you can explore worlds beyond your own, from the comforts of home. No matter where in the world you are, it’s easy to join one of the many vibrant communities flourishing within this otherworldly space – from gamers meeting up for tournaments to NFT artist networking with collectors from around the globe . With virtual reality gaining greater traction each day, accessing the metaverse has never been so simple. All of a sudden, far-flung lands have become as close as typing a few words into your computer – there’s truly something here for everyone! Whether it’s shopping on a replicated version of your favourite street or joining a club recreating never-seen-before activities – all that lies just one click away. Now’s your chance to broaden your horizons and see what all these newfound possibilities have in store! If you’re looking for an escape from the everyday, or a place to explore your creativity, the Metaverse is definitely worth checking out. With so many different worlds to choose from, there’s something for everyone. And who knows? You might just find your new favorite hangout spot. 13 views0 comments bottom of page
__label__pos
0.541343
Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 You can Download Samacheer Kalvi 11th Maths Book Solutions Guide Pdf, Tamilnadu State Board help you to revise the complete Syllabus and score more marks in your examinations. Tamilnadu Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 Question 1. Determine whether the following measurements produce one triangle, two triangles or no triangle: ∠B = 88°, a = 23, b = 2. Solve if solution exists. Solution: We are given a = 23, b = 2, and ∠B = 88°. So we can Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 1 Question 2. If the sides of a ∆ABC are a = 4, b = 6 and c = 8, then show that 4 cos B + 3 cos C = 2. Solution: a = 4, b = 6, c = 8 To prove 4 cos B + 3 cos C = 2 Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 2 Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 Question 3. In a ∆ABC, if a = \(\sqrt{3}\) – 1, b = \(\sqrt{3}\) + 1 and C = 60°, find the other side and other two angles. Solution: Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 3 Question 4. Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 4 Solution: Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 5 Question 5. In a ∆ABC, if a = 12 cm, b = 8 cm and C = 30°, then show that its area is 24 sq.cm. Solution: a = 12 cm, b = 8 cm, C = 30° Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 6 Question 6. In a ∆ABC, if a = 18 cm, b = 24 cm and c = 30 cm, then show that its area is 216 sq.cm. Solution: a = 18 cm, b = 24 cm, c = 30 cm The sides form a right angled triangle Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 7 Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 Question 7. Two soldiers A and B in two different underground bunkers on a straight road, spot an intruder at the top of a hill. The angle of elevation of the intruder from A and B to the ground level in the eastern direction are 30° and 45° respectively. If A and B stand 5 km apart, find the distance of the intruder from B. Solution: By using sine formula \(\frac{x}{\sin 30^{\circ}}=\frac{5}{\sin 15^{\circ}}\) Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 8 Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 9 Question 8. A researcher wants to determine the width of a pond from east to west, which cannot be done by actual measurement. From a point P, he finds the distance to the eastern-most point of the pond to be 8 km, while the distance to the western most point from P to be 6 km. If the angle between the two lines of sight is 60°, find the width of the pond. Solution: p2 = W2 + E2 – 2WE cos P P2 = 64 + 36 – 2 × 8 × 6 × Cos 60° Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 10 Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 11 Question 9. Two Navy helicopters A and B are flying over the Bay of Bengal at same altitude from the sea level to search a missing boat. Pilots of both the helicopters sight the boat at the same time while they are apart 10 km from each other. If the distance of the boat from A is 6 km and if the line segment AB subtends 60° at the boat, find the distance of the boat from B. Solution: Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 12 Question 10. A straight tunnel is to be made through a mountain. A surveyor observes the two extremities A and B of the tunnel to be built from a point P in front of the mountain. If AP = 3 km, BP = 5 km and ∠APB = 120°, then find the length of the tunnel to be built. Solution: Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 13 A, B are the two extremities of the tunnel. P – Point of observation. PA , PB are the directions of the points A, B as observed from the point P AP = 3 km, BP = 5 km, ∠ APB = 120° Using cosine formula in ∆ APB AB2 = AP2 + BP2 – 2AP. BP. cos(120°) AB2 = 32 + 52 – 2 × 3 × 5 cos (180° – 60°) = 9 + 25 – 30 (- cos 60°) = 34 + 30 × \(\frac { 1 }{ 2 }\) = 34 + 15 = 49 AB = √49 = 7 ∴ The length of the tunnel AB = 7 k.m. Question 11. A farmer wants to purchase a triangular-shaped land with sides 120 feet and 60 feet and the angle included between these two sides is 60°. If the land costs ₹ 500 per sq. ft, find the amount he needed to purchase the land. Also, find the perimeter of the land. Solution: Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 14 Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 Question 12. A fighter jet has to hit a small target by flying a horizontal distance. When the target is sighted, the pilot measures the angle of depression to be 30°. If after 100 km, the target has an angle of depression of 60°, how far is the target from the fighter jet at that instant? Solution: Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 15 Question 13. A plane is 1 km from one landmark and 2 km from another. From the plane’s point of view, the land between them subtends an angle of 60°. How far apart are the landmarks? Solution: Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 16 Question 14. A man starts his morning walk at a point A reaches two points B and C and finally back to A such that ∠A= 60° and ∠B = 45°, AC = 4 km in the ∆ABC. Find the total distance he covered during his morning walk. Solution: Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 17 Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 Question 15. Two vehicles leave the same place P at the same time moving along two different roads. One vehicle moves at an average speed of 60 km/hr and the other vehicle moves at an average speed of 80 km/hr. After half an hour the vehicle reaches destinations A and B. If AB subtends 60° at the initial point P, then find AB. Solution: Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 18 = 900+ 1600 – 1200 = 1300 Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 19 Question 16. Suppose that a satellite in space, an earth station, and the centre of earth all lie in the same plane. Let r be the radius of earth and R be the distance from the centre of the earth to the satellite. Let d be the distance from the earth station to the satellite. Let 30° be the angle of elevation from the earth station to the satellite. If the line segment connecting earth station and satellite subtends angle α at the centre of the earth, then prove that Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 200 Solution: Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 20 Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 Additional Questions Solved Question 1. Given a = 8, b = 9, c = 10, find all the angles. Solution: Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 21 Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 Question 2. Given a = 31, b = 42, c = 57, find all the angles. Solution: Since the sides are larger quantities, use half angles formulae Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 22 Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 23 Question 3. In a triangle ABC, A = 35° 17′ ; C = 45° 13′ ; b = 42.1 Solve the triangle Solution: The unknown parts are B, a, c, B = 180 – (A + C) = 180 – (35° 17′ + 45° 13′) = 99° 30′ To find sides, use sine formula Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 25 Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 26 log c = log 42.1 + log sin 45° 31 – log sin 99° 30′ = 1.6243 + 1.8511 – 1.9940 = 1.4754 – 1.9940 = 1.4754 – [-1 + 0.9940] = 1.4814 ⇒ c = 30.3° Thus B = 99° 30′ ; a = 24.65° ; c = 30.3° Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 Question 4. Solve the triangle ABC if a = 5, b = 4 and C = 68°. Solution: To find c, use c2 = a2 + b2 – 2ab cos C c2 = 25 + 16 – 2 × 5 × 4 cos 68° = 41 – 40 × 0.3746 = 26.016 c = 5.1 To find the other two angles, use sine formula. Samacheer Kalvi 11th Maths Solutions Chapter 3 Trigonometry Ex 3.10 27 Leave a Comment Your email address will not be published. Required fields are marked *
__label__pos
0.990577
POP vs. IMAP: What Do They Mean and Which One Should You Use? 0 Comments Editor Ratings: User Ratings: [Total: 0 Average: 0] Here is a quick explanation about what does POP and IMAP mean and when should you use POP and when to use IMAP. These days, everyone and their mother uses E-mail. It’s one modern technology that has totally transformed the way we communicate with each other. From the early days of Hotmail and Yahoo Mail, when Webmail used to look like something coded in Notepad and mailboxes were 5-10 MB tops, to the modern day Webmail services that can do almost everything (Chat, Voice Calling, Social Networking, video calling, to name a few) and have practically unlimited storage, E-mail surely has come a long way. But deep down, the core technologies that drive E-mail communication have remained more or less the same. POP vs IMAP Although these days, majority of Email users login to their E-mail service providers’ webmail UI to handle E-mail communication,  thanks to the increase in both the speed and stability of Internet connectivity, it wasn’t always the same. Back in the days, when a 28.8 or 56 Kbps Dial-up connection was all a normal person could afford, Email communication was mostly handled using Software known as Email Clients. To clarify, an Email client is a software that enables you to access your Email without having to open up your Webmail provider’s Email portal. Now, these Email clients need to access our Email from the service providers’ mail servers in order to enable the users access to their Email. And this is where POP and IMAP come into play. They are protocols (a set of rules that govern how a particular system works) that define how E-mail clients interact with the E-mail providers’ servers. Heralded as two of the best known protocols of the TCP/IP stack, POP and IMAP enable power Email users to work with their Emails, the way they want to. What is POP? POP stands for Post Office Protocol. It’s been through many version revisions, with POP3 being the most recent one. The basic working of POP can be underlined as follows: • E-mail client connects to remote webmail provider’s (Gmail, Yahoo etc.) mail server through user’s credentials (username & password). • All email messages present on the server are fetched by the email client, and stored as New mail (unread) on the user’s machine. • After all the messages have been downloaded to the user’s machine, the same are deleted from the email provider’s server (s) (this is optional). • The email client disconnects itself from the remote server. Thus, POP focuses on the fact that user should have access to all his/her E-mail locally, at all times. What is IMAP? IMAP is an acronym for Internet Message Access Protocol. It’s a more recent technology than POP, and somehow, a consequent development of the increasing speeds and reliabilities of modern day always on Internet Connectivity. IMAP, like POP too has been under a number of version revisions, with IMAP4 being the industry standard. The basic procedure that IMAP follows for dealing with email, can be sequentially described as follows: • email client connects to remote webmail provider’s (Gmail, Yahoo etc.) mail server through user’s credentials (username & password). • Instead of downloading the entire email (textual and graphic content, attachments etc.), only basic information (List of new emails, email headers etc.) is cached locally on the user’s machine. • Entire email content is downloaded only at the explicit request of the user (For example, when a user clicks to read a rich HTML E-mail with attachments, all these are downloaded). • Disconnect after syncing the changes to the remote server. Clearly, the working of IMAP is a little more complex than POP. Also check out: What is IRC? POP vs. IMAP: How they differ? 1. POP downloads users’ email locally entirely, making their communication accessible at all times. On the other hand, IMAP just grabs the necessary information unless the content is explicitly requested by the user. 2. POP is more of a passive protocol, that downloads your email locally, deletes it from the mail server, and disconnects from the server. By contrast, IMAP is an active protocol that syncs the changes you make to your emails locally to the server. 3. POP gives the users more control over their email, making it accessible and private to them at all times. IMAP, on the other hand, ensures that users can access their emails from different machines, regardless of their location, as long as Internet Connectivity is there. 4. POP just downloads the bulk of email in one go, while IMAP maintains directory structures at all times (due to its capability to sync changes), on all locations where email is present. This essentially means that the E-mail sent from the E-mail client will appear in the “sent” category of E-mail client, as well as Webmail. Tip: Though POP’s default behavior is to locally download the E-mail and then delete it from the server, modern E-mail services/clients can be configured to leave it on the server, if the user desires so. Which one of POP and IMAP should you choose? The answer to this question largely depends on how a user interacts with his/her E-mail. For the majority of Email users, this isn’t even relevant because they use the webmail UI to access their E-mail. For the ones who choose to use E-mail clients, the following pointers should help: Choose the good ol’ POP (Post Office Protocol) if: • If you want complete access to your E-mails locally, at all times. • You normally work on your E-mail from a single machine. • The storage space on your Email provider’s server is limited. • You have unreliable Internet connectivity. • You want to consolidate E-mail from different accounts into a unified inbox. Choose the modern IMAP (Internet Message Access Protocol) if: • If you want your E-mail readily accessible from multiple machines, and multiple locations. • The storage space on your local machine is limited. • You have a stable and almost always on Internet connectivity. • You want to maintain the directory and folder structures across all devices you access your E-mail on (Webmail, E-mail client, Smartphone etc.) I know I haven’t given any recommendation around which protocol to choose, but I really can’t. It purely depends on how you interact with your email. I have long stopped using email clients and rely on webmails only, especially since emails have been available on smartphone too. If you are interested in knowing more about these protocols, you can check Wikipedia for POP and IMAP. Let me know in comments if you have any thoughts on these protocols, and if you have any favorite among these. Editor Ratings: User Ratings: [Total: 0 Average: 0] Free/Paid: Free Get 100 GB FREE Provide details to get this offer
__label__pos
0.697522
Binary search tree or BST is a node based tree in which each node has two children, we call it as left and right child. The top most node is called the root of the tree. The children of a node also have their own child nodes. It is a nested tree in which each branch has its two (binary) of its own child branches. This image has an empty alt attribute; its file name is BST.png BST As you can observe in the above binary search tree that the left node/child has lesser value than the parent node and right node has greater value than the parent node. So this is a convention we follow while creating or using binary search tree so that searching, inserting and deleting in the binary search tree is easier to implement and also time complexity is less than traversing the complete array. Also, No duplicates allowed in Binary Search Tree. Insertion in Binary Search Tree Insertion is always done at the ‘leaf’ node that is the bottom most suitable node. Once the leaf node is found then the value is entered as a child node to that leaf node. This image has an empty alt attribute; its file name is Screenshot-2019-09-09-at-9.23.30-PM.png Python Code For Insertion 1. Check for root. 2. If inserting element is less than root, recursively check for left node, else recursively check for right node 3. Reached end? Insert to current node’s left node if less value than current node key, else insert to right. class Node: def __init__(self,key): self.right = None self.left = None self.val = key def insert(root,node): if root is None: root = node else: if node.val > root.val: if root.right is None: root.right = node else: insert(root.right, node) else: if root.left is None: root.left = node else: insert(root.left, node) So basically, we have created a class Node and all nodes/branches of the binary search tree will behave like the objects of this class Node. For inserting value in the binary search tree, we have created a member function which operates recursively and inserts the key at the desired position. Searching a key in Binary Search Tree For searching a key in Binary Search Tree, check for root value, if root value is equal to the key return root. If key is smaller than the root value check recursively for the left node, else for right node. 1. Check the root 2. If key is smaller than root value, check recursively for left node, else for right node 3. Return true when element found, else return false. Python code for searching def search(root,key): ##when root is null or key is present if root is None or root.val==key: return root else: if key > root.val: ##when root value is smaller return search(root.right, key) ##when root value is larger return search(root.left,key) Deleting a key in Binary Search Tree There are three cases possible for deleting a key in a binary search tree 1.Deleting a leaf, that is the bottommost element. Remove the element from the tree simply. This image has an empty alt attribute; its file name is Screenshot-2019-09-09-at-8.37.21-PM.png 2. Deleting a node with a single child node. Delete the element and copy the contents of child node to that element position This image has an empty alt attribute; its file name is Screenshot-2019-09-09-at-8.45.24-PM.png 3. Deleting a node with two child node/elements. Find the inorder successor and copy the contents of it to the node and delete the inorder successor. If the inorder successor of the node is empty, then we can use inorder predecessor too. This image has an empty alt attribute; its file name is Screenshot-2019-09-09-at-9.03.12-PM.png Inorder Successor Inorder successor of a a node in a binary search tree is the smallest key greater than the input node. Deletion of key python code # Returns the node with min value in the tree def minValue(node): current = node #looping down to leftmost leaf while(current.left is not None): current = current.left return current #Given a binary search tree,key . Deletes the key from the binary search tree. def delete(root, key): if root is None: return root #if key is larger, then it lies in right subtree if key > root.val: root.right = delete(root.right,key) #if key is smaller, then it lies in left subtree elif key < root.val: root.left = delete(root.left,key) #key is same as the root's value else: #node with one child node or none child node if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp #Node with two child node temp = minValue(root.right) #Get inorder successor's root.val = temp.val #Delete the inorder successor root.right = delete(root.right,temp.val) LEAVE A REPLY
__label__pos
0.992188
Symbol.unscopables Широко известный символ Symbol.unscopables используется для указания значения объекта, чьи собственные и наследуемые имена свойств исключаются из привязок связанного объекта оператора with. Атрибуты свойства Symbol.unscopables Записываемое нет Перечисляемое нет Настраиваемое нет Описание Символ @@unscopables (Symbol.unscopables) может быть определён к любому объекту, чтобы исключить имена свойств из-за того, что они отображаются как лексические переменные с привязкой окружения with. Обратите внимание: если использовать "Строгий режим", оператор with будет недоступен и вероятнее всего также не понадобится этот символ. Если вы зададите свойству значение true в объекте unscopables сделает его "unscopable" и, следовательно, оно не будет задействовано в области лексических переменных. Придав свойству значение false, Вы сделаете его scopable и, как следствие, оно будет задействовано в области лексических переменных. Примеры Приведённый код отлично работает в ES5 и ниже. Однако в ECMAScript 2015 и более поздних версиях был введён метод Array.prototype.keys(). Это означает, что внутри окружения with, "ключи" будут методом, а не переменной. Вот где теперь встроенные свойства символа Array.prototype[@@unscopables] вступают в игру и препятствуют тому, чтобы некоторые из методов Array были включены в оператор with. js var keys = []; with (Array.prototype) { keys.push("что-то"); } Object.keys(Array.prototype[Symbol.unscopables]); // ["copyWithin", "entries", "fill", "find", "findIndex", // "includes", "keys", "values"] Вы также можете задать unscopables для собственных объектов. js var obj = { foo: 1, bar: 2, }; obj[Symbol.unscopables] = { foo: false, bar: true, }; with (obj) { console.log(foo); // 1 console.log(bar); // ReferenceError: bar is not defined } Спецификации Specification ECMAScript Language Specification # sec-symbol.unscopables Совместимость с браузерами BCD tables only load in the browser Смотрите также
__label__pos
0.624065
Luke Luke - 10 months ago 111 Objective-C Question NSStatusBarButton keep highlighted As of OS X 10.10 most of NSStatusItem has been deprecated in favour of the button property, which consists of an NSStatusBarButton. It should work like a normal button but unfortunately the cell and setCell methods in NSStatusButton have also been deprecated. As a result of this I'm struggling to find a way to keep the button highlighted after it's clicked (Normally the button is highlighted on mouse down, and unhighlighted on mouse up. I want to keep it highlighted after mouse up). Calling [NSStatusButton setHighlighted:] in its action doesn't work because it seems to unhighlight itself once the mouse is up. On the other hand, using a delay to call it on the next loop i.e. [self performSelector: withDelay:] causes the highlight to flash in a rather unsightly way. It works, but doesn't look nice. Setting the button type to NSToggleButton removes the highlight entirely and instead highlights the template image which was odd. Those were the only methods I could think of. Is there anyway to override this NSButtonCell mouseUp behaviour? Answer I added a subview to the status item, and inside that view I added event handlers for mouseDown etc. which called [[statusItem button] highlight:true]. As it turns out setHighlighted: doesn't do the same thing as highlight:. NSArray *array = [NSArray arrayWithObjects:[statusItem button], [self statusItemView], nil]; [[[statusItem button] superview] setSubviews:array]; //Highlight like so: [[statusItem button] highlight:true]; EDIT: As of El Capitan this method no longer works, and neither does statusItem.button.highlight = true either
__label__pos
0.786634
Source AutoRebuild / autorebuild.py Full commit """ AutoRebuild =========== A plugin that will perform a rebuild when a file changes. """ import os import glob from cherrypy.process.plugins import Autoreloader class AutoRebuild(Autoreloader): taskmap = {} def tasks(self): """ See if any files have changed for a certain task. """ tasks = [] for regex, task in self.taskmap.iteritems(): changed = [] for filename in glob.iglob(regex): oldtime = self.mtimes.get(filename, 0) if oldtime is None: continue try: mtime = os.stat(filename).st_mtime except OSError: mtime = None self.mtimes[filename] = mtime if mtime is None or mtime > oldtime: changed.append(filename) if changed: tasks.append((task, changed)) return tasks def run(self): for task, changed in self.tasks(): self.bus.log('Executing %s. These changed: %s' % (task, changed)) task() if __name__ == '__main__': import cherrypy from subprocess import call class Root(object): def index(self): return 'Hello World!' index.exposed = True def build_css(): call(['make', 'css']) cherrypy.engine.autorebuild = AutoRebuild(cherrypy.engine) cherrypy.engine.autorebuild.subscribe() cherrypy.config.update({ 'engine.autorebuild.on': True, 'engine.autorebuild.taskmap': {'*.less': build_css}}) cherrypy.tree.mount(Root(), '/') cherrypy.engine.start() cherrypy.engine.block()
__label__pos
0.900243
blob: 1473d8b4bf0f345e3fc2c2b99c34a444b3286085 [file] [log] [blame] // SPDX-License-Identifier: GPL-2.0+ /* * Test cases for bitfield helpers. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <kunit/test.h> #include <linux/bitfield.h> #define CHECK_ENC_GET_U(tp, v, field, res) do { \ { \ u##tp _res; \ \ _res = u##tp##_encode_bits(v, field); \ KUNIT_ASSERT_FALSE_MSG(context, _res != res, \ "u" #tp "_encode_bits(" #v ", " #field ") is 0x%llx != " #res "\n", \ (u64)_res); \ KUNIT_ASSERT_FALSE(context, \ u##tp##_get_bits(_res, field) != v); \ } \ } while (0) #define CHECK_ENC_GET_LE(tp, v, field, res) do { \ { \ __le##tp _res; \ \ _res = le##tp##_encode_bits(v, field); \ KUNIT_ASSERT_FALSE_MSG(context, \ _res != cpu_to_le##tp(res), \ "le" #tp "_encode_bits(" #v ", " #field ") is 0x%llx != 0x%llx",\ (u64)le##tp##_to_cpu(_res), \ (u64)(res)); \ KUNIT_ASSERT_FALSE(context, \ le##tp##_get_bits(_res, field) != v);\ } \ } while (0) #define CHECK_ENC_GET_BE(tp, v, field, res) do { \ { \ __be##tp _res; \ \ _res = be##tp##_encode_bits(v, field); \ KUNIT_ASSERT_FALSE_MSG(context, \ _res != cpu_to_be##tp(res), \ "be" #tp "_encode_bits(" #v ", " #field ") is 0x%llx != 0x%llx", \ (u64)be##tp##_to_cpu(_res), \ (u64)(res)); \ KUNIT_ASSERT_FALSE(context, \ be##tp##_get_bits(_res, field) != v);\ } \ } while (0) #define CHECK_ENC_GET(tp, v, field, res) do { \ CHECK_ENC_GET_U(tp, v, field, res); \ CHECK_ENC_GET_LE(tp, v, field, res); \ CHECK_ENC_GET_BE(tp, v, field, res); \ } while (0) static void __init test_bitfields_constants(struct kunit *context) { /* * NOTE * This whole function compiles (or at least should, if everything * is going according to plan) to nothing after optimisation. */ CHECK_ENC_GET(16, 1, 0x000f, 0x0001); CHECK_ENC_GET(16, 3, 0x00f0, 0x0030); CHECK_ENC_GET(16, 5, 0x0f00, 0x0500); CHECK_ENC_GET(16, 7, 0xf000, 0x7000); CHECK_ENC_GET(16, 14, 0x000f, 0x000e); CHECK_ENC_GET(16, 15, 0x00f0, 0x00f0); CHECK_ENC_GET_U(8, 1, 0x0f, 0x01); CHECK_ENC_GET_U(8, 3, 0xf0, 0x30); CHECK_ENC_GET_U(8, 14, 0x0f, 0x0e); CHECK_ENC_GET_U(8, 15, 0xf0, 0xf0); CHECK_ENC_GET(32, 1, 0x00000f00, 0x00000100); CHECK_ENC_GET(32, 3, 0x0000f000, 0x00003000); CHECK_ENC_GET(32, 5, 0x000f0000, 0x00050000); CHECK_ENC_GET(32, 7, 0x00f00000, 0x00700000); CHECK_ENC_GET(32, 14, 0x0f000000, 0x0e000000); CHECK_ENC_GET(32, 15, 0xf0000000, 0xf0000000); CHECK_ENC_GET(64, 1, 0x00000f0000000000ull, 0x0000010000000000ull); CHECK_ENC_GET(64, 3, 0x0000f00000000000ull, 0x0000300000000000ull); CHECK_ENC_GET(64, 5, 0x000f000000000000ull, 0x0005000000000000ull); CHECK_ENC_GET(64, 7, 0x00f0000000000000ull, 0x0070000000000000ull); CHECK_ENC_GET(64, 14, 0x0f00000000000000ull, 0x0e00000000000000ull); CHECK_ENC_GET(64, 15, 0xf000000000000000ull, 0xf000000000000000ull); } #define CHECK(tp, mask) do { \ u64 v; \ \ for (v = 0; v < 1 << hweight32(mask); v++) \ KUNIT_ASSERT_FALSE(context, \ tp##_encode_bits(v, mask) != v << __ffs64(mask));\ } while (0) static void __init test_bitfields_variables(struct kunit *context) { CHECK(u8, 0x0f); CHECK(u8, 0xf0); CHECK(u8, 0x38); CHECK(u16, 0x0038); CHECK(u16, 0x0380); CHECK(u16, 0x3800); CHECK(u16, 0x8000); CHECK(u32, 0x80000000); CHECK(u32, 0x7f000000); CHECK(u32, 0x07e00000); CHECK(u32, 0x00018000); CHECK(u64, 0x8000000000000000ull); CHECK(u64, 0x7f00000000000000ull); CHECK(u64, 0x0001800000000000ull); CHECK(u64, 0x0000000080000000ull); CHECK(u64, 0x000000007f000000ull); CHECK(u64, 0x0000000018000000ull); CHECK(u64, 0x0000001f8000000ull); } #ifdef TEST_BITFIELD_COMPILE static void __init test_bitfields_compile(struct kunit *context) { /* these should fail compilation */ CHECK_ENC_GET(16, 16, 0x0f00, 0x1000); u32_encode_bits(7, 0x06000000); /* this should at least give a warning */ u16_encode_bits(0, 0x60000); } #endif static struct kunit_case __refdata bitfields_test_cases[] = { KUNIT_CASE(test_bitfields_constants), KUNIT_CASE(test_bitfields_variables), {} }; static struct kunit_suite bitfields_test_suite = { .name = "bitfields", .test_cases = bitfields_test_cases, }; kunit_test_suites(&bitfields_test_suite); MODULE_AUTHOR("Johannes Berg <[email protected]>"); MODULE_LICENSE("GPL");
__label__pos
0.889072
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. I've run into a peculiar problem which I don't seem to be able to wrap my head around. I'll get right into it. The problem is matching a set of cards to a set of rules. It is possible to define a set of rules as a string. It is composed of comma separated tuples of <suit>:<value>. For example H:4, S:1 should match Four of Hearts and Ace of Spades. It is also possible to wildcard, for example *:* matches any card, D:* matches any card with in the diamond suit, and *:2matches a Two in any suit. Rules can be combined with comma: *:*,*:*,H:4 would match a set of cards if it held 2 random cards and a Four of Hearts. So far so good. A parser for this is easy and straight forward to write. Here comes the tricky part. To make it easy to compose these rules, two more constructions can be used for suit and value. These are < (legal for suit and value) and +n (legal only for value) where n is a number. < means "the same as previous match" and +n means "n higher than previous match". An example: *:*, <:*, *:< Means: match any card, then match a card with the same suit as the first match, next match another card with the same value as the second match. This hand would match: H:4,H:8,C:8 Because Hearts of Four and Hearts of Eight is the same suit, while Eight of Hearts and Eight of Clubs is the same value. It is allowed to have more cards as long as all rules match (so, adding C:10 to the above hand would still match the rule). My first approach at solving this is basically taking the set of cards which should be matched, attempting to apply the first rule to it. If it matched, I moved on to the next rule and attempted to match it from the set of cards, and so on until either all rules were matched, or I found a rule that didn't match. This approach have (at least) one flaw, consider example above above: *:*,<:*,*:<, but with the cards in this order: H:8,C:8,H:4. • It would match the H:8 of for the first rule. Matched: H:8 • Next it attempts to find one with the same suit (Hearts). There is a Four of Hearts. Matched: H:8, H:4 • Moving on, it want to find a card with the same value (Four), and fails. I don't want the way the set of cards is ordered to have any impact on the result as it does in the above example. I could sort the set of cards if I could think of any great strategy that worked well with any set of rules. I have no knowledge of the quantity of cards or number oof rules, so a brute force approach is not feasible. Thank you for reading this far, I am grateful for any tip or insight. share|improve this question 1   You say you don't want the order of the cards to matter, but your rules specifically rely on the order of the cards. Thus, you may have to try every possible ordering. You can prune a large number of them by considering the cards from left to right, and not branching any further when you reach a card that breaks the rule. Using this method, you could probably search hands up to 10-12 cards in a reasonable amount of time. There may be a way of doing this in time better than O(n!), but if so, I can't think of it. –  BlueRaja - Danny Pflughoeft Aug 21 '12 at 19:42      The average case would probably not be so bad. You're correct in that a lot of branches will not even be worth considering. Worst case scenario is still (as you state) O(n!), which isn't good at all. –  Alexander Olsson Aug 21 '12 at 19:54 1 Answer 1 Your problem is actually an ordering problem. Here's a simple version for it: given an input sequence of numbers and a pattern, reorder them so that they fit the pattern. The pattern can contain "*", meaning "any number" and ">", meaning "bigger than the previous number. For example, given pattern [* * > >] and sequence [10 10 2 1] such an ordering exists and it is [10 1 2 10]. Some inputs might give no outputs, others 1, while even others many (think the input [10 10 2 1] and the pattern [* * * *]). I'd say that once you have the solution for this simplified problem, switching to your problem is just a matter of adding another dimension and some operators. Sorry for not being of more help :/ . LE. keep in mind that if the allowed character symbols are finite (i.e. 4) and also the allowed numbers (i.e. 9) things might get easier. share|improve this answer      I fail to see how sorting helps here. Given two values, how do you know which comes first? –  BlueRaja - Danny Pflughoeft Aug 21 '12 at 19:36      This is what your problem, as you describe it, asks. To find a permutation of the input "cards" so that they match the pattern. –  foxx1337 Aug 21 '12 at 19:37      So you're just restating the problem? –  BlueRaja - Danny Pflughoeft Aug 21 '12 at 19:39      It amuses me how you find my answer tldr while you took the time to read the op post. Keep in mind that SO is not a place where others do your homework for you. LE - accidentally the usernames. –  foxx1337 Aug 21 '12 at 19:43      I did read your answer, but I don't see how it answers the question. Also, I am not the original poster. –  BlueRaja - Danny Pflughoeft Aug 21 '12 at 19:44 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.540586
[NodrakorId]Race 5.540p.mp4 Size: 236.8 MB / Uploaded: 2023-05-24 or Import to About the file format .MP4: MP4 is a file format created by the Moving Picture Experts Group (MPEG) as a multimedia container format designed to store audiovisual data but can also be used to store other data such as subtitles and still images. Like most modern container formats, it allows streaming over the Internet. The MP4 is largely replacing earlier multimedia file formats, and creating some changes in the way that vendors sell audiovisual files to the public. File Identity: [NodrakorId]Race 5.540p.mp4 File Size: 236.8 MB File Fingerprint: MD5: soWxynv/q0tC+FCX6xo00Q SHA-256:976894be8e925e84e0e89ccf12cc9186db750b74e481bf16b3e98fae6bfe7b3b
__label__pos
0.500931
APIs Show: // --------- This code has been automatically generated !!! 2017-12-15T21:13:56.082Z "use strict"; /** * @module opcua.address_space.types */ var assert = require("node-opcua-assert"); var util = require("util"); var _ = require("underscore"); var makeNodeId = require("node-opcua-nodeid").makeNodeId; var schema_helpers = require("node-opcua-factory/src/factories_schema_helpers"); var extract_all_fields = schema_helpers.extract_all_fields; var resolve_schema_field_types = schema_helpers.resolve_schema_field_types; var initialize_field = schema_helpers.initialize_field; var initialize_field_array = schema_helpers.initialize_field_array; var check_options_correctness_against_schema = schema_helpers.check_options_correctness_against_schema; var _defaultTypeMap = require("node-opcua-factory/src/factories_builtin_types")._defaultTypeMap; var ec = require("node-opcua-basic-types"); var encodeArray = ec.encodeArray; var decodeArray = ec.decodeArray; var makeExpandedNodeId = require("node-opcua-nodeid/src/expanded_nodeid").makeExpandedNodeId; var generate_new_id = require("node-opcua-factory").generate_new_id; var _enumerations = require("node-opcua-factory/src/factories_enumerations")._private._enumerations; var schema = require("../schemas/DataValue_schema").DataValue_Schema; var getFactory = require("node-opcua-factory/src/factories_factories").getFactory; var Variant = getFactory("Variant"); var BaseUAObject = require("node-opcua-factory/src/factories_baseobject").BaseUAObject; /** * * @class DataValue * @constructor * @extends BaseUAObject * @param options {Object} * @param [options.value = null] {Variant} * @param [options.statusCode = 0] {StatusCode} * @param [options.sourceTimestamp = null] {DateTime} * @param [options.sourcePicoseconds = 0] {UInt16} * @param [options.serverTimestamp = null] {DateTime} * @param [options.serverPicoseconds = 0] {UInt16} */ function DataValue(options) { options = options || {}; /* istanbul ignore next */ if (schema_helpers.doDebug) { check_options_correctness_against_schema(this,schema,options); } var self = this; assert(this instanceof BaseUAObject); // ' keyword "new" is required for constructor call') resolve_schema_field_types(schema); BaseUAObject.call(this,options); /** * * @property value * @type {Variant} * @default null */ self.value = (options.value) ? new Variant( options.value) : null; /** * * @property statusCode * @type {StatusCode} * @default 0 */ self.statusCode = initialize_field(schema.fields[1], options.statusCode); /** * * @property sourceTimestamp * @type {DateTime} * @default null */ self.sourceTimestamp = initialize_field(schema.fields[2], options.sourceTimestamp); /** * * @property sourcePicoseconds * @type {UInt16} * @default 0 */ self.sourcePicoseconds = initialize_field(schema.fields[3], options.sourcePicoseconds); /** * * @property serverTimestamp * @type {DateTime} * @default null */ self.serverTimestamp = initialize_field(schema.fields[4], options.serverTimestamp); /** * * @property serverPicoseconds * @type {UInt16} * @default 0 */ self.serverPicoseconds = initialize_field(schema.fields[5], options.serverPicoseconds); // Object.preventExtensions(self); } util.inherits(DataValue,BaseUAObject); schema.id = generate_new_id(); DataValue.prototype.encodingDefaultBinary = makeExpandedNodeId(schema.id); DataValue.prototype._schema = schema; var encode_StatusCode = _defaultTypeMap.StatusCode.encode; var decode_StatusCode = _defaultTypeMap.StatusCode.decode; var encode_DateTime = _defaultTypeMap.DateTime.encode; var decode_DateTime = _defaultTypeMap.DateTime.decode; var encode_UInt16 = _defaultTypeMap.UInt16.encode; var decode_UInt16 = _defaultTypeMap.UInt16.decode; DataValue.prototype.encode = function(stream,options) { schema.encode(this,stream,options); }; /** * decode the object from a binary stream * @method decode * * @param stream {BinaryStream} * @param [option] {object} */ DataValue.prototype.decode = function(stream,options) { schema.decode(this,stream,options); }; DataValue.prototype.decode_debug = function(stream,options) { schema.decode_debug(this,stream,options); }; /** * * verify that all object attributes values are valid according to schema * @method isValid * @return {Boolean} */ DataValue.prototype.isValid = function() { return schema.isValid(this); }; DataValue.possibleFields = [ "value", "statusCode", "sourceTimestamp", "sourcePicoseconds", "serverTimestamp", "serverPicoseconds" ]; exports.DataValue = DataValue; var register_class_definition = require("node-opcua-factory/src/factories_factories").register_class_definition; register_class_definition("DataValue",DataValue);
__label__pos
0.986056
Uploaded image for project: 'Magnolia UI' 1. Magnolia UI 2. MGNLUI-7035 Screen jumps when moving value of TwinColumnSelectField XMLWordPrintable Details Description Steps to reproduce 1. Decorate stories app to add a twin column field as a new block. The existing decoration in /travel-demo-stories-app/decorations/stories-app/apps/stories.yaml can be modified to reproduce this bug as follows: subApps: editor: form: properties: relatedContent: properties: tours: label: stories.editor.relatedContent.tours.label $type: jcrMultiValueField buttonSelectAddLabel: stories.editor.relatedContent.tours.add.label field: $type: linkField chooserId: stories-app:chooserTours datasource: $type: jcrDatasource workspace: tours buttonSelectNewLabel: stories.editor.relatedContent.tours.browse.label twinSelect: label: Groups $type: twinColSelectField leftColumnCaption: "Available groups" rightColumnCaption: "User is member of" datasource: $type: jcrDatasource workspace: usergroups allowedNodeTypes: - mgnl:group blocks: blocks: - text - image - video - externalLink - date - tour - twinSelect permissions: roles: travel-demo-publisher: travel-demo-publisher travel-demo-editor: travel-demo-editor 2. Make use of the new column field by moving values from one column to another Expected results Twin column field can be used without any issue Actual results Focus is lost and scroll moves in a jump. This is more noticeable in smaller screens (laptop) than in bigger ones, where the jump is lighter. Checklists Acceptance criteria Attachments Issue Links Activity People jsarf Jaromir Sarf jayala Jonathan Ayala Nucleus Votes: 0 Vote for this issue Watchers: 8 Start watching this issue Dates Created: Updated: Resolved: Work Started: Checklists Bug DoR Task DoD Time Tracking Estimated: Original Estimate - Not Specified Not Specified Remaining: Remaining Estimate - Not Specified Not Specified Logged: Time Spent - 1d 7h 1d 7h
__label__pos
0.994402
Quick Answer: What Data Is Lost When Factory Reset IPhone? Will a hard reset delete everything on my phone? A factory data reset erases your data from the phone. While data stored in your Google Account can be restored, all apps and their data will be uninstalled. To be ready to restore your data, make sure that it’s in your Google Account.. Does erasing old iPhone delete new one? No, it will not. Erasing the old device will not affect the new one. That is necessary for you to be able to wipe the device. What happens when you restore iPhone to factory settings? Your computer erases your device and installs the latest iOS, iPadOS, or iPod software. After your device restores to factory settings, it restarts. Now you can set it up as new. Can you restore iPhone after Erase all content and settings? Use a computer to erase all content and settings from iPhone Before iPhone is erased, you have the option to back it up. If you make a backup, you can use the backup to restore your data and settings on your iPhone or on a new device. How do I permanently delete data from my phone? Go to Settings > Backup & reset. Tap Factory data reset. On the next screen, tick the box marked Erase phone data. You can also choose to remove data from the memory card on some phones – so be careful what button you tap on. What does a factory reset Delete on iPhone? Factory reset or hard reset deletes complete data and settings from your iPhone. All your photos, videos, contacts, call logs, passwords, messages, browsing history, calendar, chat history, notes, installed apps, etc., get deleted from the iOS device. How do I factory reset my iPhone without losing data? To reset the settings on your device go to Settings >> General then scroll down and tap the Reset button at the bottom. On the Reset screen tap Reset All Settings – Not Erase All Content and Settings – then you’ll need to verify you want to do it twice. It should only take a couple of minutes at most. How do I permanently delete data from iPhone? The general method to erase all iPhone data is a factory reset. To erase your iPhone, iPad, or iPod Touch, launch the Settings app from the Home screen of your iPhone or iPad, tap General, scroll all the way to the bottom and tap on Reset, then “Erase All content and Settings“. What are the disadvantages of factory reset? Disadvantages of Android Factory Reset: It will remove all the application and their data which might cause a problem in the future. All of your login credentials will be lost and you have to sign-in all of your accounts again. Your personal contact list will also be erased from your phone during the factory reset. Will hard reset delete everything iPhone 7? The hard reset is a lot more dramatic. It totally erases all the information on your iPhone 7 and restores it to factory settings, which is why the hard reset is also known as a factory reset. Can data be recovered from a factory reset iPhone? Frankly speaking, it is impossible can recover data directly from a factory reset iPhone. Those who claim that they can recover data directly from iPhone after a factory reset is frauds. But don’t lose hope, you can still recover them from your iTunes backup or iCloud backup. Does factory reset delete data? Factory Reset does NOT delete all data When you factory reset your Android phone, even though your phone system becomes factory new, but some of the old Personal information is not deleted. This information is actually “marked as deleted” and hidden so you can’t see it at a glance. What is the difference between hard reset and factory reset? The two terms factory and hard reset are associated with settings. A factory reset relates to the rebooting of the entire system, while hard resets relates to the resetting of any hardware in the system. … The factory reset makes the device function again in a new form. It cleans the entire system of the device. Should I erase my iPhone before service? The short answer is “no, you shouldn’t erase your iPhone before screen repair.” However, the complete answer would be “yet, you should save your data before handing your device to the repair shop.” And here is why Mr. Fix cell phone repair services always insist on our customers doing so. Does factory reset delete iCloud? No, factory resetting your iPhone will not alter your iCloud. Upon setting up your iPhone again you will be given the option to reconnect to your iCloud account if you desire. iCloud also stores iPhone backups that you can restore your phone from. How do you factory reset a locked iPhone? Perform a hard reset on your phone by holding down the sleep/wake button and the Home button at the same time. Hold the buttons until the “Connect to iTunes” screen appears. On your computer, choose “Restore” from the iTunes screen. This will delete all data from your phone. Does erase iPhone delete everything? When you tap Erase All Content and Settings, it completely erases your device, including any credit or debit cards you added for Apple Pay and any photos, contacts, music, or apps. It will also turn off iCloud, iMessage, FaceTime, Game Center, and other services. What happens when you erase a lost iPhone? What happens when you erase a device in Find My iPhone? … After you erase a device, you can’t use Find My iPhone to locate the device or play a sound on it. However, you may still be able to locate your Mac or Apple Watch if it’s near a previously used Wi-Fi network. Apple Pay is disabled for your device. How do you erase your data so no one can ever recover it? There are, however, a few ways to ensure your data is really erased forever.Encrypt your phone. Encrypting your Android device is the strongest way to prevent its data from being recovered. … Overwrite it with throwaway data. … Repeat.Jun 26, 2016
__label__pos
0.996468
User Guide Writing Custom Code Last Updated: Sep 03, 2015 06:04PM PDT Custom actions make it possible to create many kinds of SMS services without needing programming expertise. However, some kinds of SMS services can't be built by combining the basic actions provided by Telerivet. For example, if you want to integrate your SMS service with your own database or website, or connect to a third-party data source, then the basic actions and variables provided by Telerivet won't be enough. In these cases, Telerivet provides two ways for you to run custom code to automatically handle incoming messages: • The Notify Webhook URL action lets you forward incoming messages to a script on your own server. This lets you write code in any programming language, such as PHP, Java, Python, or Ruby. • The Run JavaScript code action lets you write code in the JavaScript programming language. This code runs on Telerivet's servers whenever you receive an incoming message, so you don't need your own server. Using a Webhook URL Whenever a new message matches a Notify webhook URL action, Telerivet will automatically notify your server by making a HTTP POST request to a particular URL, where you can write your own code to handle the message and send replies. Suppose you have a web server at http://myserver.example.com where you can run your own PHP scripts. (This example assumes that your code is written in PHP, though you can use any programming language.) Then you can create a Webhook rule pointing to a script on your server (e.g. telerivet.php): The Webhook API documentation explains in detail how the incoming message will be passed to your script, and how your script can send automatic replies. Writing JavaScript code Whenever a new message matches a Run JavaScript code action, Telerivet will execute your JavaScript code on its own servers. Telerivet provides several variables and functions to your JavaScript code that let you access properties of the incoming message, and perform actions equivalent to many rules, such as sending SMS messages or changing the contact's group membership. In addition, Telerivet provides the capability for JavaScript code to make HTTP requests, which allows your service to interact with other web APIs. It also allows you to store limited amounts of data on Telerivet's servers. For more information, see the complete Cloud Script API documentation. Example 1 Suppose you want to create an SMS service that offers the weather forecast for any city in Tanzania, whenever someone sends your SMS service the name of a city. Then you could sign up for the wunderground.com Weather API, and create a PHP script to that implements Telerivet's Webhook API like so: <?php $webhook_secret = 'YOUR_WEBHOOK_SECRET_HERE'; $country = 'Tanzania'; $wug_key = 'YOUR_WUNDERGROUND_API_KEY_HERE'; // Make sure request is actually generated by Telerivet if ($_POST['secret'] !== $webhook_secret) { header('HTTP/1.1 403 Forbidden'); echo "Invalid webhook secret"; } else if ($_POST['event'] == 'incoming_message') { $city = $_POST['content']; // Make query to wunderground.com Weather API $city_query = $country."/".urlencode($city); $url = "http://api.wunderground.com/api/{$wug_key}/forecast/q/{$city_query}.json"; $json = file_get_contents($url); $res = json_decode($json, true); // Extract text forecast for tomorrow from Weather API response if (isset($res['forecast'])) { $tomorrow = $res['forecast']['txt_forecast']['forecastday'][0]; $reply = $tomorrow['title'] . ": " . $tomorrow['fcttext_metric']; } else { $reply = "Unknown city '$city'."; } // Send reply via Telerivet Webhook API header("Content-Type: application/json"); echo json_encode(array('messages' => array( array('content' => $reply) ) )); } Then, if someone sends a text message like "Moshi", your service will respond with a message like this: Friday: Overcast in the morning, then clear. High of 23C. Winds from the South at 5 to 15 km/h. Example 2 Suppose you want to create the same weather forecast service as above, but without needing to run your own server. In this case, you could create a service with a Run JavaScript code action as follows: var wugKey = "YOUR_WUNDERGROUND_API_KEY_HERE"; var cityQuery = "Tanzania/" + encodeURIComponent(content); var response = httpClient.request({ url: "http://api.wunderground.com/api/" + wugKey + "/forecast/q/" + cityQuery + ".json" }); var res = JSON.parse(response.content); if (res.forecast) { var tomorrow = res.forecast.txt_forecast.forecastday[0]; var forecast = tomorrow.fcttext_metric; sendReply(tomorrow.title + ": " + forecast); } else { sendReply("Unknown city '"+message.content+"'."); } Contact Us http://assets1.desk.com/ false desk Loading seconds ago a minute ago minutes ago an hour ago hours ago a day ago days ago about false Invalid characters found /customer/en/portal/articles/autocomplete
__label__pos
0.716747
u2c Форум поддержки U2C S+, OptiBox, CryptoBox, Amiko, Vu+, Alma и других спутниковых ресиверов. Краткий FAQ по MGcamd Эмулятор (BISS, CW) + клиент для шapы Краткий FAQ по MGcamd Сообщение support » 22 окт 2012, 15:01 Файлы конфигурации MgCamd: /var/keys/mg_cfg /var/keys/newcamd.list /var/keys/ignore.list /var/keys/priority.list /var/keys/replace.list /var/keys/AutoRoll.Key /var/keys/SoftCam.Key - в этих файлах хранятся ключи для чисто эмуляционной части mgcamd.Для шapингa эти файлы не нужны. В файле mg_cfg содержится основная системная конфигурация mcgamd. Файлы ignore.list, priority.list и replace.list позволяют произвести "тонкую настройку", параметров шapингa, чтобы каналы которые идут в нескольких кодировках открывались быстрее. newcamd.list- файл, который содержит информацию: на какой сервер нужно коннектиться, с каким именем, паролем и по какому порту. Естественно, исходя из имени файла, всё это для коннекта на сервер(ы) по протоколу newcamd. Разберём главный конфигурационный файл mg_cfg. Буква: { цифра } дополнительные параметры Буква означает тот или иной параметр, как описано ниже. Цифра означает одно из возможных значений параметра. Дополнительные параметры должны присутствовать только там, где это необходимо.  Пример файла mg_cfg # AU - автообновление. Выбрать одно из четырех: # 0 выключить функцию AU # 1 включить обработку EMM для софт-эмулятора и карт шapингa # 2 авторежим, включать EMM только если канал не открывается # 3 включить EMM обработку только для карт доступных по сети # Насколько мне известно, это дело нужно было для пакета TPS на # спутнике Hotbird, но теперь всё это дело прошлого. Поэтому выключаем. A: { 0 } # Тип устройства # 0 авто # 1 dbox2 # 2 dreambox # 3 triple-dragon # 4 relook # 5 openbox # рекомендуется оставить авто: B: { 0 } # ECM messages # Показ EСM-cообщений. В качестве значения выбрать одно из трех: # 0 не показывать ничего # 1 обычный режим: показывать PID, и декодированные ECM и CW # 2 подробный режим: показывать всё подряд включая весь дамп # Это дело лучше видеть, чтобы сразу было понятно, работает # шapинг или нет, поэтому включим обычный режим: C: { 1 } # Отладочная информация в лог-файле # 0 off (default) # 1 ecm # 2 emm # 4 network ecm # 8 network emm # 16 network login # 32 показывать статистику загрузки памяти и CPU каждую минуту # 64 добавить дату и время к каждой записи в лог # обычно эту опцию включать не нужно, но ради интереса можно попробовать. # в логе будет гораздо больше информации, чем обычно D: { 0 } # кэширование ECM (в секундах) # каждая запись в кэш отъедает 28 байт, поэтому 24 часа кэша отъест 240-400 КБ памяти # вполне можно позволить себе такую роскошь, чтобы не обращаться заново к карте шapингa # если вы скачете по каналам туда сюда, как угорелый. Хотя вообще-то это бесполезно, # так как нынче ключики живут считанные секунды. E: { 3600 } # Сетевой протокол для шapингa. # Можно выбрать несколько значений, просуммировав отдельные опции. # 0 сеть отсутствует (шapингa не предвидится) # 1 клиент newcamd # 2 клиент radegast # 4 клиент camd3 # 8 клиент gbox # Как говорится, "стандарт индустрии", протокол newcamd. # Кстати, протокол camd3 сломан в версии mgcamd 1.31 на IPBOX - у меня так и не заработал G: { 1 } # Что кэшировать? Значений может быть несколько как сумма следущих: # 0 отключить кэширование # 1 кэшировать Ecm pids, и сохранять в файле /tmp/ca_cache.list при перезапуске # 2 вести кэш Ecm, и помнить значения столько секунд, сколько указано в опции "E" выше # 4 вести кэш Emm для карт доступных по сети, чтобы не слать один и тот же EMM снова # Как уже сказано в опции E, толку от этого кэширования достаточно мало, но пусть будет: H: { 7 } # Значение в секундах для тайм-аута сетевого запроса. # Поставим 3 секунды, так как обычно сервер должен ответить в этих пределах. # Для некоторых глючных пакетов, типа Nova, этот параметр можно и увеличить до 5. # Но помните, чем больше этот параметр, тем медленней mgcamd будет # обращаться к серверу если от сервера не пришел ответ во время. # Если сервер не отвечает за это время, см. параметр "N". K: { 3 } # Опции для лог файлов, можно выбрать несколько параметров как сумму: # 0 не вести лог # 1 лог через сеть (по протоколу UDP Syslog) # 2 лог на консоль # 4 лог в файл (который будет всё время расти, и поэтому он может забить # всю флеш-память - его вам придется чистить вручную) # дополнтельные параметры: IP-адрес + UDP порт для сетевого лога + имя лог-файла # # Это очень важная опция для того, чтобы сразу увидеть где грабли, если # что-то не работает, или работает не так как надо. Идеальней всего использовать # лог по сети. Эта процедура описана ниже подробнее. Здесь же нужно указать # IP адрес вашего обычного компьютера в вашей локальной сети, UDP порт, который # обычно должен быть 514 и если хотите включить лог-файл на самом ресивере, то # имя файла, где-нибудь, например в папке /tmp. Для включения лога в файл, # нужно поменять { 1 } на { 4 } или { 5 }. Если параметр не 4 и не 5, то имя лог файла # можно не писать. L: { 1 } 192.168.1.1 514 /tmp/mgcamd.log # Показ EMM-cообщений. В качестве значения выбрать одно из трех: # 0 не показывать никаких EMM # 1 показывать только верные EMM # 2 показывать верные и неверные сообщения EMM, включая весь дамп # Это дело нам не понадобится, поэтому выбираем "не показывать": M: { 0 } # Повторная попытка при работе с сетью. Очень важный параметр!!! # Можно выбрать несколько значений, просуммировав отдельные опции. # 0 не пытаться повторить запрос # 1 повторная попытка при каждом новом ECM # 2 повторная попытка присоединиться к недоступному ранее серверу # каждые Q секунд (Q дается как отдельный параметр "Q" ниже) # 4 пробовать быстро пере-соединиться к отрубившемуся серверу: # либо после XX ECM запросов без ответа от сервера, # либо если нет ответа от сервера в течение YY секунд # Числа XX и YY даются как дополнительные параметры # Относительно числа XX - mgcamd будет ждать ответа от сервера столько # секунд, сколько указано в параметре "К" # # Рекомендую установить все опции 01 + 02 + 04, то есть их сумму = 07. # В качестве дополнительных параметров XX и YY можно взять 4 запроса # без ответа или 30 секунд. Хотя, наилучшие значения будут напрямую зависеть # от качества вашего Интернета и провайдера шapы. N: { 7 } 4 30 # разновидность экранного интерфейса: # 0 нет меню на экране # 1 neutrino # 2 enigma # 3 relook # + имя пароль (как дополнительные параметры для авторизации) # Это всё нам вообще не понадобится. Это для других ресиверов: O: { 0 } username password # Приоритет протоколов (если у вас их несколько) # 0 gbox, newcamd, radegast, camd3 # 1 camd3, radegast, newcamd, gbox # 2 newcamd, camd3, gbox, radegast # нас интересует newcamd, поэтому поставим его на первое место: P: { 2 } # Пытаться коннектиться на "мертвый" сервер каждые 30 секунд # (если включено в опции "N" выше) Q: { 30 } # Cчитывать файлы конфигурации повторно. # Параметр может быть суммой следующих значений: # 0 считывать все файлы конфигурации только раз при запуске mgcamd # 1 считывать файлы каждый раз при смене канала # 2 считывать файл SoftCam.Key каждый раз при смене канала # 4 считывать файл SoftCam.Key, если он изменился # Поскольку меняться будет потенциально только SoftCam.Key (и то редко), установим 04: R: { 4 } # Что показывать на экранном меню: # 1 emu ecm # 2 шapy через сеть # 4 показывать "некодированный канал" / "не могу открыть" # 8 показывать обновление ключей EMM # + web порт для экранного меню # Это всё нам не понадобится. Это для для других ресиверов: S: { 0 } 80 # Папка с файлами конфигурации (softcam, autoroll, ignore/priority) # 0 файлы в папке /var/keys # 1 файлы в /tmp # Тут и так понятно, что нужно выбрать 0: T: { 0 } # Обновление ключей. Нужно выбрать 2 параметра, как сумму 01/02 плюс 04 # 1 обновлять только новые ключи # 2 обновлять все ключи (для валидации PMK) # 4 включить функцию TPS AU (в дополнительных параметрах указать # SID, в котором pmt pid содержит au pid): U: { 5 } 0x1234 # Это дело работает вместе с параметром "A". # Поскольку мы вырубили "A", выключаем и это дело тоже: U: { 0 } Второй по значимости файл для шapингa: newcamd.list.  Пример файла newcamd.list CWS_KEEPALIVE = 300 CWS_INCOMING_PORT = 21000 CWS = 127.0.0.1 34000 dummy dummy 01 02 03 04 05 06 07 08 09 10 11 12 13 14 lan newcs CWS = 127.0.0.1 34001 dummy dummy 01 02 03 04 05 06 07 08 09 10 11 12 13 14 lan newcs CWS = 127.0.0.1 34002 dummy dummy 01 02 03 04 05 06 07 08 09 10 11 12 13 14 lan newcs CWS_MULTIPLE = 192.168.1.2 20000:20005 dummy dummy 10 02 13 04 15 06 17 08 01 10 11 12 13 14 lan server2 Первая строка - CWS_KEEPALIVE задает время в секундах, через которое эмулятор MgCamd проверяет соединение с сервером кардшаринга по прописанным в настройках портам. Во второй строчке CWS_INCOMING_PORT задается порт для прослушивания входящих соединений с сервера, данную строчку можно опустить. В строчке CWS прописываются параметры сервера кардшаринга, для открытия определенных пакетов. Вместо 127.0.0.1 необходимо прописать реальный IP или доменный адрес сервера кардшаринга, далее следует порт сервера - 34000, вместо которого прописываем рабочий для определенного пакета каналов, после этого следуют логин и пароль - dummy dummy, которые также правим на правильные, затем указывается DES ключ - 01 02 03 04 05 06 07 08 09 10 11 12 13 14, при необходимости который также изменяется и в заключении следует - lan newcs, которые в большинстве случаев не влияют на работу кардшаринга, а используются только при применении camdcmd протокола. Даже если сервер один и тот же, на каждый пакет может быть свой отдельный порт, поэтому нужно прописать все отдельно. Файл - priority.list используется для указания идентов, через которые будут открываться каналы. Например, для пакета нтв+ используются иденты 023700 и 030600, в этом случае в файле необходимо прописать две строки: V: { 02 37 00 } V: { 05 0B 00 } В которой буква V - означает используемую кодировку - Viaccess, 030600- идент для открытия каналов нтв+ в высоком разрешении HD. Файл - ignore.list содержит все иденты оператора, которые не используются для просмотра каналов: V: { 04 06 00 } V: { 04 06 10 } Файл - replace.list применяется для замены неверных идентов на правильные с указанием дополнительных параметров каналов. В основном применяется для HD каналов: R:{{2F4A}{0500}{023700}{0FA6}{0500}{030600}{0BBE}} #MTVNHD R:{{2F4A}{0500}{040610}{138E}{0500}{030600}{0BBE}} #MTVNHD R:{{2F45}{0500}{023700}{0FA1}{0500}{030600}{0BB9}} #HD-Кино R:{{2F45}{0500}{040610}{1389}{0500}{030600}{0BB9}} #HD-Кино R:{{2F46}{0500}{023700}{0FA2}{0500}{030600}{0BBA}} #HD-Спорт R:{{2F46}{0500}{040610}{138A}{0500}{030600}{0BBA}} #HD-Спорт R:{{2F47}{0500}{023700}{0FA3}{0500}{030600}{0BBB}} #HD-Life R:{{2F47}{0500}{040610}{138B}{0500}{030600}{0BBB}} #HD-Life R:{{2F48}{0500}{023700}{0FA4}{0500}{030600}{0BBC}} #Eurosport HD R:{{2F48}{0500}{040610}{138C}{0500}{030600}{0BBC}} #Eurosport HD R:{{2F49}{0500}{023700}{0FA5}{0500}{030600}{0BBD}} #Discovery HD R:{{2F49}{0500}{040610}{138D}{0500}{030600}{0BBD}} #Discovery HD В котором: {2F4A} - сид канала, {0500} - тип кодировки Viaccess, {023700} - идент который будет заменен, {0FA6} - есм пид, {0500} - новый тип кодировки, {030600} – идент после замены, {0BBE} - верный есм пид канала. Аватара пользователя support Admin groups Admin groups   Сообщения: 1520 Зарегистрирован: 01 июн 2012, 12:31 Благодарил (а): 106 раз. Поблагодарили: 1095 раз. Вернуться в MgCamd Кто сейчас на конференции Зарегистрированные пользователи: Bing [Bot], Google [Bot], seriojamd, ursul, Yahoo [Bot] Вверх страницы Вниз страницы
__label__pos
0.721846
trigonometry questions in cat • Quantitative Aptitude , Strategy Tips Introduction to Trigonometry for CAT Trigonometry is an essential topic in CAT exam. Its questions come in combination with other geometrical concepts in the Quantitative Aptitude Section. Scoring well in Trigonometric questions means understanding the basic concepts well. This article covers all the basic concepts you would need. • December 16, 2021 Trigonometry in the CAT exam is a broad topic. However, that doesn’t imply direct questions will appear in the exam from this topic. Mostly, trigonometric concepts appear in relation to geometric problems in the Quantitative Aptitude Section . The questions in relation to Trigonometric concepts appear in relation to other related concepts in the Quant section. Most students often overlook these basic concepts. This causes them to forget the basics and results in losing points. Consequently, this results in an unsatisfactory overall CAT percentile. That’s why our CAT coaching has compiled this article to help you study important trigonometric basics in less than 7 minutes. In this article, we will discuss concepts, basic formulas and some examples in brief. Basic Trigonometric Concepts Trigonometry for CAT The fundamental concept in trigonometry is based on ratios of the angles in a triangle. These ratios are Trigonometric ratios. There are six Trigonometric ratios. Each fundamental trigonometric ratio is unique. Let’s consider the above triangle as ABC. So, AC = Hypotenuse of the triangle AB = Adjacent side to the Angle θ BC = Opposite side to Angle θ Then, the trigonometric ratios are • Sin θ = Sine of angle θ = (Opposite side to Angle θ)/(Hypotenuse of the Triangle) = (BC/AC) • Cos θ = Cosine of angle θ = (Adjacent side to Angle θ)/(Hypotenuse of the Triangle) = (AB/AC) • Tan θ = Tangent of angle θ = (Opposite side to Angle θ)/(Adjacent side to Angle θ) = (BC/AB) • Cot θ = Cotangent of angle θ = (Adjacent side to Angle θ)/(Opposite side to Angle θ) = (AB/BC) • Sec θ = Secant of angle θ = (Hypotenuse of the Triangle)/(Adjacent side to Angle θ) = (AC/AB) • Cosec θ = Cosecant of angle θ = (Hypotenuse of the Triangle)/(Opposite side to Angle θ) = (AC/BC) Trigonometric ratios with respect to Angles: These trigonometric ratios of some specific angles are widely used in numerous mathematical problems. Simultaneously, these ratios are easy to remember as well as they follow a certain discernible pattern. Basic Identities and Formulae: Trigonometric ratios of complementary angles:. • Sin (90° − θ) = Cos θ • Cos (90° − θ) = Sin θ • Tan  (90° − θ) = Cot θ • Cot (90° − θ) = Tan θ • Sec (90° − θ) = Cosec θ • Cosec (90° − θ) = Sec θ Trigonometric Identities: • Sin² θ + Cos² θ = 1 • Tan² θ + 1 = Sec² θ • Cot² θ + 1 = Cosec² θ Special Triangles’ Ratio: There are two triangles that have the same trigonometric ratio value regardless of the length of their sides. These two triangles have sides with angles 45°-45°-90° and 30°-60°-90°. In a 45°-45°-90° triangle, the ratio of sides, are 1:1:2 ½  respectively. In a 60°-30°-90° triangle, the ratio of sides are 1:3 ½ :2 respectively. Example Questions: 1.   In a triangle ABC, if Sin A, Sin B, Sin C are sines of angles A, B, C respectively, then a Sin (B − C) + b Sin ( C − A) + c Sin (A − B) = in triangle ABC, let’s assume that a/Sin A = b/Sin B = c/Sin C = K a = k Sin A, b = k Sin B c = k Sin C Now consider the equation given which is ⇒ a Sin (B − C) + b Sin (C − A) + c Sin (A − B) Substitute the values of a, b, c in the above equation = k Sin A (Sin B Cos C −Cos B Sin C) + k Sin B (Sin C Cos A − Cos C Sin A) + k Sin C (Sin A Cos B − Cos A Sin B) =k Sin A (Sin B Cos C − Cos B Sin C) + k Sin B (Sin C Cos A − Cos C Sin A) + k Sin C (Sin A Cos B − Cos A Sin B) = k Sin A Sin B Cos C − k Sin A Cos B Sin C + k Sin B Sin C Cos A −k Sin B Cos C Sin A + k Sin C Sin A Cos B − k Sin C Cos A Sin B Hence, the correct option is (a) 2.  If Cos A + Cos² A = 1 and a Sin 12 A + b Sin 10 A + c Sin 8  A + d Sin 6   A − 1 = 0. Find the value of a+(b/c)+d Cos A = 1 − Cos 2 A Cos A = Sin 2  A Square on both sides Then, Cos 2 A = Sin 4 A 1 − Sin 2 A = Sin 4 A 1 = Sin 4 A + Sin 2 A Cube on both sides 1 3  = (Sin 4 A + Sin 2 A) 3 1 = Sin 12 A + Sin 6 A + 3Sin 8 A + 3Sin 10 A Sin 12 A + Sin 6 A + 3Sin 8 A +3Sin 10 A − 1 = 0 on comparing with the given equation in the question, a = 1, b = 3, c = 3, d = 1 a+(b/c)+d = 3 So, the correct option is (b) Hope this article was helpful. Related Posts trigonometry questions in cat Ask for Guidance Want help with a specific topic or facing difficulties with your MBA prep? We are here to help. Just type in whatever you need guidance on and we will have our experts write a blog on it. Subscribe with us bellcat Leave a Comment Cancel Reply You must be logged in to post a comment. WhatsApp us Geometry - Trigonometry - Previous Year CAT/MBA Questions The best way to prepare for Geometry - Trigonometry is by going through the previous year Geometry - Trigonometry XAT questions . Here we bring you all previous year Geometry - Trigonometry XAT questions along with detailed solutions. Click here for previous year questions of other topics. It would be best if you clear your concepts before you practice previous year Geometry - Trigonometry XAT questions. Find the value of: sin 6 15 ° + sin 6 75 ° + 6 sin 2 15 ° sin 2 75 ° sin 4 15 ° + sin 4 75 ° + 5 sin 2 15 ° sin 2 75 ° sin 15° + sin 75° sin 15° cos 15° None of the above Answer: Option C Let sin 2 15° = a and sin 2 75° = b ∴  sin 6 15 ° + sin 6 75 ° + 6 sin 2 15 ° sin 2 75 ° sin 4 15 ° + sin 4 75 ° + 5 sin 2 15 ° sin 2 75 °  =  a 3 + b 3 + 6 ab a 2 + b 2 + 5 ab Now, a 3 + b 3 = (a + b) 3 - 3ab(a + b), and a 2 + b 2 = (a + b) 2 - 2ab ∴  sin 6 15 ° + sin 6 75 ° + 6 sin 2 15 ° sin 2 75 ° sin 4 15 ° + sin 4 75 ° + 5 sin 2 15 ° sin 2 75 °  =  ( a + b ) 3 - 3 ab ( a + b ) + 6 ab ( a + b ) 2 - 2 ab + 5 ab Now, a + b = sin 2 15° + sin 2 75° = sin 2 15° + cos 2 15° = 1 [∵ Sin𝜃 = Cos(90 - 𝜃)] ∴  sin 6 15 ° + sin 6 75 ° + 6 sin 2 15 ° sin 2 75 ° sin 4 15 ° + sin 4 75 ° + 5 sin 2 15 ° sin 2 75 °  =  1 - 3 ab + 6 ab 1 - 2 ab + 5 ab  =  1 + 3 ab 1 + 3 ab  = 1 Hence, option (c).  trigonometry questions in cat A tall tower has its base at point K. Three points A, B and C are located at distances of 4 metres, 8 metres and 16 metres respectively from K. The angles of elevation of the top of the tower from A and C are complementary. What is the angle of elevation (in degrees) of the tower’s top from B? We need more information to solve this. trigonometry questions in cat Given the distances are : AE = 4 meters , EB = 8 meters and EC = 16 meters. Considering the length of ED = K. Given the angles DAE and angle DCE are complementary. Hence the angles are A and 90 - A. Tan(90 - A) = Cot A tan DAE =  k 4  and tan DCE = tan  1 D A E  =  k 16 Hence  k 16  =  4 k k = 8 meters. The angle DBE is given by tan DBE =  k 8  = 1 Hence the angle is equal to 45 degrees. A boat, stationed at the North of a lighthouse, is making an angle of 30° with the top of the lighthouse. Simultaneously, another boat, stationed at the East of the same lighthouse, is making an angle of 45° with the top of the lighthouse. What will be the shortest distance between these two boats? The height of the lighthouse is 300 feet. Assume both the boats are of negligible dimensions. 600√3 feet 300√3 feet Answer: Option D Let LM be the lighthouse and B 1 and B 2 be the positions of the two boats. trigonometry questions in cat In ∆LMB 1 , Tan 30° = LM/MB 1 ⇒ MB 1  = LM√3 = 300√3 Also, in ∆LMB 2 , Tan 45° = LM/MB 2 ⇒ MB 2  = LM = 300 In ∆MB 1 B 2 ,  (B 1 B 2 ) 2 = (MB 1 ) 2  + (MB 2 ) 2 ⇒ (B 1 B 2 ) 2 = (300√3) 2  + (300) 2 ⇒ (B 1 B 2 ) 2  = 300 2  × [(√3) 2  + (1) 2 ] ⇒ (B 1 B 2 ) 2  = 300 2  × 4 ⇒ B 1 B 2 = 300 × 2 = 600 Hence, option (d). If 5° ≤ x° ≤ 15°, then the value of sin 30° + cos x° - sin x° will be: Between -1 and -0.5 inclusive Between -0.5 and 0 inclusive Between 0 and 0.5 inclusive Between 0.5 and 1 inclusive Answer: Option E sin 30° + cos x° – sin x° where 5° ≤ x° ≤ 15°.  For the given range, cos x > sin x So, cos x° – sin x° > 0  Also, sin 30° = 0.5 sin 30° + cos x° – sin x° > 0.5 So, first four options are eliminated.  Hence, option (e). A person standing on the ground at point A saw an object at point B on the ground at a distance of 600 meters. The object started flying towards him at an angle of 30° with the ground. The person saw the object for the second time at point C flying at 30° angle with him. At point C, the object changed direction and continued flying upwards. The person saw the object for the third time when the object was directly above him. The object was flying at a constant speed of 10 kmph. trigonometry questions in cat Find the angle at which the object was flying after the person saw it for the second time. You may use additional statement(s) if required. Statement I: After changing direction the object took 3 more minutes than it had taken before. Statement II: After changing direction the object travelled an additional 200√3 meters. Which of the following is the correct option? Statement I alone is sufficient to find the angle but statement II is not. Statement II alone is sufficient to find the angle but statement I is not. Statement I and Statement II are consistent with each other. Statement I and Statement II are inconsistent with each other. Neither Statement I nor Statement II is sufficient to find the angle. From the given data, m∠CAB = 30°; m∠CBA = 30° and AB = 600 m ∴ BC = AC = 200√3 m … [By sine rule] trigonometry questions in cat Statement I: After changing the direction the object took 3 more minutes than it had taken before. The object travels 200√3 m from B to C at 10 km/hr Thus, in 3 minutes it can travel 500 m. Hence, the object travels a total of 500 + 200√3m from C. Thus, we know the hypotenuse CD by which we can find out the angle. Statement II: After changing directions, the object travels 200√3 m. Since, the object travels the same distance as before, this can only happen if the object stays on the course as before without changing any direction. Thus, we can clearly see that the two angles from the statements are inconsistent with each other. A person is standing at a distance of 1800 meters facing a giant clock at the top of a tower. At 5.00 p.m., he can see the tip of the minute hand of the clock at 30 degree elevation from his eye-level. Immediately, the person starts walking towards the tower. At 5.10 pm., the person noticed that the tip of the minute hand made an angle of 60 degrees with respect to his eye-level. Using three-dimensional vision, find the speed at which the person is walking. The length of the minutes hand is 200√3 meters (√3 = 1.732). 7.2 km/hour 7.5 km/hour 7.8 km/hour 8.4 km/hour trigonometry questions in cat At 5.00 p.m., position of the person be P PB = 1800 (Given) m∠DPB = 30° ⇒ DB = 1800 tan 30° = 600√3 At 5.10 p.m. the minute hand of the clock moves by 60° trigonometry questions in cat DC = CF = 200√3 m (Given) ∆FEC is 30° - 60° - 90° triangle. So, EC = 100√3 m and EF = 300 m DE = DC – EC = 200√3 – 100√3 = 100√3 m FG = DB – DE = 600√3 – 100√3 = 500√3 m In ∆AFG, m∠FAG = 60° and FG = 500√3 m By theorem of 30°-60°-90° triangle, BG = EF = 300 m In ∆ABG, AG = 500 m and BG = 300 m ⇒ AB = 400 m PA = PB – AB = 1800 – 400 = 1400 m = 1.4 km Time taken = 10 minutes = (1/6) hours Speed = 1.4 × 6 = 8.4 km/hr Get Free Exam Preparation With expert teachers. Help us build a Free and Comprehensive Preparation portal for various competitive exams by providing us your valuable feedback about Apti4All and how it can be improved. Subscribe to our Newsletter 🎯 Take 2IIM's CAT Scholarship Test and get upto 50% off on all our courses | Date: 3-4th Feb Learn from 5 time cat 100%iler | best cat online coaching | cat preparation, learn from 4 time cat 100%iler | best cat online coaching | cat preparation, write cat 2iim scholarship test and get up to 50% off. ★ click here to take the test. • 1000 Hour Online CAT Coaching • CAT Coaching in Chennai • CAT Preparation Books • CAT Previous Year Papers • 2IIM's CAT Questions • XAT Previous Year Papers • IIFT Previous Year Papers • How to prepare for CAT Quantitative Aptitude • How to prepare for CAT DILR Section • How to prepare for CAT VARC Section • What is CAT Exam All about • CAT Syllabus • CAT Online Live Classes GMAT Preparation Online • 2IIM CAT Preparation Blog • 2IIM CAT Preparation Reviews • CAT Preparation Quora Answers • CAT Preparation Videos • CAT Preparation Facebook Group • CAT Preparation Facebook Page • CAT Questions Quantitative Aptitude Blog • CAT Preparation Blog • Work for Us • IPMAT 2023 Coaching Online 🎉 Learn from 4 time CAT 100%iler | Best CAT Online Coaching | CAT Preparation Cat quantitative aptitude questions | geometry questions for cat - trigonometry, cat questions | cat trigonometry questions | heights and distances. CAT Questions / Geometry - Trigonometry / Question 3 T he question is from CAT Geometry - Trigonometry. This is about Heights and distances. We need to find out the ratio of the heights of the tower which are placed in a hexagon. Trigonometry is an important topic for CAT Preparation for the CAT Exam. Trigonometric ideas can be completely opposite, as in, some questions test lot of common sense with direction, heights and distances, while others could test you on identities. CAT exam could test one on both these fronts. Make sure you master both in CAT - Trigonometry. Question 3 : Consider a regular hexagon ABCDEF. There are towers placed at B and D. The angle of elevation from A to the tower at B is 30 degrees, and to the top of the tower at D is 45 degrees. What is the ratio of the heights of towers at B and D? 🎉 Get flat ₹ 8,000 off on CAT Self-Paced Courses! Valid on 10th and 11th February 2024! ★ register now, best cat online coaching try upto 40 hours for free learn from the best, 2iim : best online cat coaching., 🎉 republic day discount upto ₹ 7,000 off on our cat '24 courses valid till 28th jan 2024, 🎯 take 2iim's cat scholarship test and get upto 50% off on all our courses date: 3-4th feb, 🎉 learn from 4 time 100%iler. self paced courses. signup to check out sample classes., best cat coaching in chennai, cat coaching in chennai - cat 2022 limited seats available - register now, explanatory answer, method of solving this cat question from cat geometry - trigonometry : when you look at your reflection through a mirror, the image is at a distance equal to the distance between mirror and you. now, think about what this has to with trigonometry.. The question is "What is the ratio of heights?" Hence, the answer is 1:2√3 Choice B is the correct answer. ★ Sign up Now! 🎉 Get flat ₹8,000 off on CAT Self-Paced Courses. Valid on 10th and 11th February 2024! ★Register Now! 🎯 Take 2IIM's CAT Scholarship Test and get upto 50% off on all our courses. Date: 3-4th Feb Write cat 2iim scholarship test and get up to 50% off.. ★ Click Here to take the test! 🎉 Fabulous Offer! Get 2IIM's Self-Paced Crash Course for just Rs. 10k &. Valid until 5th Sep ★ Register now TAPMI Prepare for CAT 2023 with 2IIM's Daily Preparation Schedule ★ Download Schedule Know all about CAT Exam Syllabus and what to expect in CAT ★ Download CAT Syllabus PDF 2IIM CAT Online Coaching Classes Already have an Account? ★ Login to Continue CAT Coaching in Chennai CAT 2024 Classroom Batches Starting Now! @Gopalapuram ★ CAT Coaching Best CAT Coaching in Chennai Introductory offer of 5000/- Attend a Demo Class ★ Schedule a Demo! Best Indore IPM & Rohtak IPM Coaching Signup and sample 9 full classes for free. Register now! ★ Signup now 2IIM CAT Online Coaching Classes CAT Preparation Online | CAT Geometry - Trigonometry Videos On YouTube Other useful sources for Geometry Questions | Trigonometry Questions Ascent MBA entrance exam Question Bank in Geometry - Trigonometry | Sample Questions in Trigonometry PiVerb CAT Questions | CAT Quantitative Aptitude CAT Questions | HCF LCM CAT Questions | Factors CAT Questions | Remainders CAT Questions | Factorials CAT Questions | Digits CAT Questions | Ratios, Mixtures, Averages CAT Questions | Percentages, Profit Loss, SICI CAT Questions | Time Speed and Distance, Races CAT Questions | Logarithms & Exponents CAT Questions | Pipes Cisterns, Work Time CAT Questions | Set Theory CAT Questions | Geometry CAT Questions | Coordinate-Geometry CAT Questions | Mensuration CAT Questions | Trigonometry CAT Questions | Linear & Quadratic Equations CAT Questions | Functions CAT Questions | Inequalities CAT Questions | Polynomials CAT Questions | Progressions CAT Questions | Permutation Combination, Probability CAT Questions | CAT DILR CAT DILR | Sequencing CAT DILR | Pie Charts CAT DILR | Multiple Graphs CAT DILR | Word Problems CAT DILR | Line Graphs CAT DILR | Bar Graphs CAT DILR | Grid Puzzle CAT DILR | Math Puzzle CAT DILR | Visualization CAT DILR | Other Patterns CAT 2017 DILR Slot 2 | Assets CAT 2017 DILR Slot 2 | Pizzeria CAT 2017 DILR Slot 2 | Electives CAT 2017 DILR Slot 2 | Chess CAT 2017 DILR Slot 2 | Dorms CAT 2017 DILR Slot 2 | Tea CAT 2017 DILR Slot 2 | Friends CAT 2017 DILR Slot 1 | CET CAT 2017 DILR Slot 1 | Survey CAT 2017 DILR Slot 1 | Happiness CAT Questions | Verbal Ability for CAT Verbal Ability for CAT | CAT Reading Comprehension Verbal Ability for CAT| CAT Para Jumble Verbal Ability for CAT | CAT Sentence Elimination Verbal Ability for CAT | CAT Paragraph Completion Verbal Ability for CAT | CAT Critical Reasoning Verbal Ability for CAT | CAT Word Usage Verbal Ability for CAT| CAT Para Summary Verbal Ability for CAT | CAT Text Completion Verbal Ability for CAT | CAT Sentence Correction Copyrights © All Rights Reserved by 2IIM.com - A Fermat Education Initiative . Privacy Policy | Terms & Conditions CAT ® (Common Admission Test) is a registered trademark of the Indian Institutes of Management. This website is not endorsed or approved by IIMs. Where is 2IIM located? 2IIM Online CAT Coaching A Fermat Education Initiative, 58/16, Indira Gandhi Street, Kaveri Rangan Nagar, Saligramam, Chennai 600 093 How to reach 2IIM? Phone: (91) 44 4505 8484 Mobile: (91) 99626 48484 WhatsApp: WhatsApp Now Email: [email protected] Wizako GMAT Preparation GMAT Coaching in Chennai GMAT Sample Questions GMAT Prep Videos GRE Coaching in Chennai GRE Questions Online GRE Coaching GRE Preparation Videos Ascent TANCET Coaching TANCET Classes Online TANCET Coaching Centres in Chennai TANCET Previous Year Question Papers TANCET Questions Maxtute CBSE Maths Classes CBSE Online Classes NCERT Solution for Class 10 Maths CBSE Sample Papers for class 10 Class 10 Maths Videos Intuitive Math learning School Math Videos 🎉 Republic Day Discount | Upto ₹ 7,000 off on our CAT '24 Courses! | Valid till 28th Jan 2024 🎯 take 2iim's cat scholarship test and get upto 50% off on all our courses | date: 3-4th feb, 🎉get flat ₹8,000 off on cat self-paced courses. valid on 10th and 11th february 2024, learn from 5 time cat 100%iler | best cat online coaching | cat preparation. • 1000 Hour Online CAT Coaching • CAT Coaching in Chennai • CAT Preparation Books • CAT Previous Year Papers • 2IIM's CAT Questions • XAT Previous Year Papers • IIFT Previous Year Papers • How to prepare for CAT Quantitative Aptitude • How to prepare for CAT DILR Section • How to prepare for CAT VARC Section • What is CAT Exam All about • CAT Syllabus • CAT Online Live Classes GMAT Preparation Online • 2IIM CAT Preparation Blog • 2IIM CAT Preparation Reviews • CAT Preparation Quora Answers • CAT Preparation Videos • CAT Preparation Facebook Group • CAT Preparation Facebook Page • CAT Questions Quantitative Aptitude Blog • CAT Preparation Blog • Work for Us • IPMAT 2024 Coaching Online CAT 2019 Question Paper | Quants Slot 1 Cat previous year paper | cat quants questions | question 17. CAT Questions / CAT 2019 Question Paper Quants-slot-1 / Question 17 H ere is a slightly tough question in CAT 2019. It combines the topics of trigonometry and algebra. It is very important to have done a solid CAT Preparation to be sure about the concepts and trigonometry formula to even attempt this question. Once you are clear with the concepts & formulas, it would be prudent to practice them from CAT previous year paper . Question 17 : The number of the real roots of the equation 2cos(x(x + 1)) = 2 x + 2 -x is 🎯 Take 2IIM's CAT Scholarship Test and get upto 50% off on all our courses Date: 3-4th Feb 2iim : best online cat coaching., register now, best cat online coaching try upto 40 hours for free learn from the best, video explanation, best cat coaching in chennai, cat coaching in chennai - cat 2022 limited seats available - register now, explanatory answer. The question is "The number of the real roots of the equation 2cos(x(x + 1)) = 2 x + 2 -x is " Hence, the answer is 1 Choice C is the correct answer. 🎉 Independence Day Offer! Get Upto ₹6000 off on our CAT 23/24 courses. Valid until 15th Aug ★ Register now 🎉 Fabulous Offer! Get 2IIM's Self-Paced Crash Course for just Rs. 10k &. Valid until 5th Sep ★ Register Now! 🎯 Take 2IIM's CAT Scholarship Test and get upto 50% off on all our courses. Date: 3-4th Feb ★Register Now! Write CAT 2IIM scholarship test and Get Up To 50% off. ★ Click Here to take the test! ★ Sign up Now! Welingkar Prepare for CAT 2024 with 2IIM's Daily Preparation Schedule ★ Download Schedule Know all about CAT Exam Syllabus and what to expect in CAT ★ Download CAT Syllabus PDF 2IIM CAT Online Coaching Classes Already have an Account? ★ Login to Continue CAT Coaching in Chennai CAT 2024 Classroom Batches Starting Now! @Gopalapuram ★ CAT Coaching Best CAT Coaching in Chennai Introductory offer of 5000/- Attend a Demo Class ★ Schedule a Demo! Best Indore IPM & Rohtak IPM Coaching Signup and sample 9 full classes for free. Register now! ★ Signup now 2IIM CAT Online Coaching Classes CAT Questions | CAT Quantitative Aptitude CAT Questions | HCF LCM CAT Questions | Factors CAT Questions | Remainders CAT Questions | Factorials CAT Questions | Digits CAT Questions | Ratios, Mixtures, Averages CAT Questions | Percentages, Profit Loss, SICI CAT Questions | Time Speed and Distance, Races CAT Questions | Logarithms & Exponents CAT Questions | Pipes Cisterns, Work Time CAT Questions | Set Theory CAT Questions | Geometry CAT Questions | Coordinate-Geometry CAT Questions | Mensuration CAT Questions | Trigonometry CAT Questions | Linear & Quadratic Equations CAT Questions | Functions CAT Questions | Inequalities CAT Questions | Polynomials CAT Questions | Progressions CAT Questions | Permutation Combination, Probability CAT Questions | CAT DILR CAT DILR | Sequencing CAT DILR | Pie Charts CAT DILR | Multiple Graphs CAT DILR | Word Problems CAT DILR | Line Graphs CAT DILR | Bar Graphs CAT DILR | Grid Puzzle CAT DILR | Math Puzzle CAT DILR | Visualization CAT DILR | Other Patterns CAT 2017 DILR Slot 2 | Assets CAT 2017 DILR Slot 2 | Pizzeria CAT 2017 DILR Slot 2 | Electives CAT 2017 DILR Slot 2 | Chess CAT 2017 DILR Slot 2 | Dorms CAT 2017 DILR Slot 2 | Tea CAT 2017 DILR Slot 2 | Friends CAT 2017 DILR Slot 1 | CET CAT 2017 DILR Slot 1 | Survey CAT 2017 DILR Slot 1 | Happiness CAT Questions | Verbal Ability for CAT Verbal Ability for CAT | CAT Reading Comprehension Verbal Ability for CAT| CAT Para Jumble Verbal Ability for CAT | CAT Sentence Elimination Verbal Ability for CAT | CAT Paragraph Completion Verbal Ability for CAT | CAT Critical Reasoning Verbal Ability for CAT | CAT Word Usage Verbal Ability for CAT| CAT Para Summary Verbal Ability for CAT | CAT Text Completion Verbal Ability for CAT | CAT Sentence Correction Copyrights © All Rights Reserved by 2IIM.com - A Fermat Education Initiative . Privacy Policy | Terms & Conditions CAT ® (Common Admission Test) is a registered trademark of the Indian Institutes of Management. This website is not endorsed or approved by IIMs. Where is 2IIM located? 2IIM Online CAT Coaching A Fermat Education Initiative, 58/16, Indira Gandhi Street, Kaveri Rangan Nagar, Saligramam, Chennai 600 093 How to reach 2IIM? Mobile: (91) 99626 48484 / 94459 38484 WhatsApp: WhatsApp Now Email: [email protected] Wizako GMAT Preparation GMAT Coaching in Chennai GMAT Sample Questions GMAT Prep Videos GRE Coaching in Chennai GRE Questions Online GRE Coaching GRE Preparation Videos Ascent TANCET Coaching TANCET Classes Online TANCET Coaching Centres in Chennai TANCET Previous Year Question Papers TANCET Questions Maxtute CBSE Maths Classes CBSE Online Classes NCERT Solution for Class 10 Maths CBSE Sample Papers for class 10 Class 10 Maths Videos Intuitive Math learning School Math Videos Cat Lovers Hub Trigonometry for Felines. Do Cats Really Understand Angles and Triangles? Table of Contents 1. Introduction The title question, “Does trigonometry come in cat?”, is asking if concepts of trigonometry can be applied to understand cat behavior and abilities. Trigonometry is a branch of mathematics that studies relationships between angles and lengths of sides in triangles. Some key trigonometric concepts are sine, cosine, tangent, cotangent, secant, and cosecant. These concepts describe ratios between angles and side lengths in right triangles. While trigonometry originated from the study of triangles, it can be applied more broadly to any cyclical phenomena or wave patterns. Cats exhibit many cyclical behaviors like sleeping, eating, grooming, and playing. Their agility and acrobatic abilities also rely on precise perception of angles and distances. This suggests trigonometry may provide insight into understanding cat capabilities and instincts. This content will provide an overview of key trigonometry concepts and how they could potentially relate to cat behavior and abilities. We will explore if and how abstract mathematical principles like sine, cosine, tangent, and triangles apply to our feline friends. The goal is to satisfy the curiosity prompted by the title question and determine if trigonometry provides a meaningful framework for understanding the essence of cats. What is Trigonometry? Trigonometry is the branch of mathematics that deals with the relationships between the sides and angles of triangles. The word trigonometry comes from the Greek words trigonon (triangle) and metron (measure). Some key definitions of trigonometry include: Trigonometry, the branch of mathematics concerned with specific functions of angles and their application to calculations. Of, relating to, or being in accordance with trigonometry. Trigonometry allows us to calculate unknown sides or angles in a triangle if we know some of the other sides or angles. The field uses trigonometric functions like sine, cosine, and tangent to relate the angles and sides. Trigonometry is important in many scientific and mathematical fields. It is used in: • Engineering • Architecture Overall, trigonometry allows us to model and understand spatial relationships, which is critical for mapping, measurement, and more in math and science. Cat Behavior Cats have excellent spatial reasoning abilities that they rely on for hunting, navigation, and play. Spatial reasoning involves being able to visualize and mentally manipulate objects and their positions in space (Source 1) . For cats, this ability allows them to calculate distances when pouncing on prey, squeeze into tight spaces, climb to high vantage points, and map out environments in their mind (Source 2) . A key component of feline spatial reasoning is their vestibular sense, which gives cats an innate sense of balance and spatial orientation. This allows them to gracefully navigate uneven terrain, make daring leaps and jumps, and always land on their feet. Cats use their highly flexible spines and spatial awareness to twist themselves mid-air and reorient during a fall so they land upright. Their spatial reasoning helps cats determine how to contort their body to fit into a box, bag, or other tight space. It also enables behaviors like squeezing through small openings and climbing narrow ledges or trees with confidence. Spatial reasoning comes into play when cats hunt. They are able to pinpoint the location of prey using their excellent hearing and assess the distance and trajectory needed to pounce with accuracy. Cats rely on spatial memory to remember where resources like food, water, and litter boxes are located within their territory. Spatial mapping abilities allow cats to navigate back to places they have already explored and to find new paths and shortcuts. Overall, spatial reasoning is an integral part of the feline brain that enables their agility, predatory skills, navigation, and other complex behaviors. Cats and Geometry Cats regularly interact with shapes and objects in their environment. Their ability to recognize shapes allows them to navigate spaces and perform tasks. For example, cats can match the shape of their food bowl to find where their food is located. They are also adept at fitting into boxes, bags, and other containers of different shapes and sizes as part of their playful nature. According to research, cats can understand basic geometric shapes such as circles, squares, rectangles, and triangles in order to complete tasks requiring shape recognition. One study at the University of Quebec tested cats’ ability to recognize shapes by training them to choose between two objects of different shapes to get a food reward. The cats were consistently able to correctly identify the shape they had been trained to select, demonstrating an understanding of basic geometric shapes (1). In another example, many cat owners have observed their cats enjoying sitting in square or rectangular boxes. The box’s angular shape seems pleasing to a cat’s geometry-attuned senses. (1) https://www.quora.com/Can-animals-understand-true-geometric-shapes-in-their-environments Cats and Angles Cats have excellent vision and spatial awareness that allows them to perceive depth and distance. Their eyes are positioned on the front of their heads, giving them binocular vision that overlaps and allows for judging distances between objects (1). This ability to perceive depth helps cats navigate environments and accurately leap and land. In addition, cats have a wide field of view of about 200 degrees, enhanced by the ability to move their heads up to 270 degrees. Their peripheral vision is excellent. This grants them a panoramic view of their surroundings and the ability to detect movement from the sides without having to fully turn their heads (2). With their advanced vision, cats are able to understand basic geometric concepts like angles and angular relationships. When observing surroundings or tracking prey, cats can visually determine angles formed between objects and surfaces. For example, they can calculate the best angle of approach to leap onto a chair or to pounce on a toy. Cats likely use angular calculations instinctively to aid their agility and navigation. Researchers have studied cats’ spatial cognition abilities using tests that require understanding angles and distances. Studies have shown cats can learn to visually compare angles and choose the larger or smaller one to earn a food reward (3). So while cats may not comprehend advanced trigonometry, their innate senses give them an implicit understanding of basic angles and spatial relationships. (1) https://www.pawschicago.org/news-resources/all-about-cats/kitty-basics/cat-senses (2) https://en.wikipedia.org/wiki/Cat_senses (3) https://www.sciencedaily.com/releases/2020/04/200401100938.htm Cats and Triangles Cats can actually perceive and interact with triangles in their environment in a few key ways. According to a blog post on Cat Bandit, cats may recognize and respond to the triangular shapes in a visual scene when looking at objects or surfaces around them ( Source ). The blog shows a picture of a cat with multiple triangles overlaid on it and discusses how identifying those triangles can help improve pattern recognition abilities. In particular, cats seem especially attuned to triangles when it comes to assessing whether they can fit into a tight, triangular space. Cats have great spatial awareness and appear to analyze shapes and openings geometrically. They seem to recognize that a triangular opening may allow them to sneak into an area, whereas a square opening would not. This shows an implicit understanding of angles and vertexes within triangular shapes. Additionally, some cat toys and scratching posts feature triangular designs and surfaces. Cats may visually fixate on the triangular patterns and target scratching and playing on those specific areas. The triangular shapes likely stand out as distinct objects for the cat to interact with in their environment. So in summary, evidence indicates cats can perceive, recognize, and respond to triangular shapes and spaces around them. Advanced Cat Math Recent studies on cat numerical cognition show that cats have some basic mathematical abilities. Cats are able to perceive and differentiate between small quantities such as 1, 2, 3, or 4 objects. However, they struggle with larger quantities and exact numerical values above 4 (Moorthy, Content Study: PEG+CAT, 2014). Cats can understand the concepts of “more” and “less” when comparing two sets of objects. A study found that cats spent more time examining a display with a larger quantity of food items vs a smaller quantity, indicating they understood more vs less. However, their math skills are limited to these simple comparative judgments (Research Shows Early Math Improvement with Home Use of … PBS Kids’ Series Peg + Cat, 2015). While cats have rudimentary numerical and quantitative reasoning abilities, they do not possess advanced math skills. There is no evidence that cats can perform exact arithmetic, understand complex operations like multiplication or division, or grasp abstract mathematical concepts. Their math proficiency extends only to basic perception of small numerosities, relative quantities, and simple comparisons. Applying Trig to Cats While trigonometry is primarily used in fields like engineering and physics, we can conduct some thought experiments to imagine how it could be relevant to understanding cats. For example, we could look at how a cat determines the angle to pounce on prey. Cats have excellent depth perception and ability to judge distances, which likely involves rapid trigonometric calculations in their brains. We can also look at how a cat perceives the angle of sunlight coming through a window. The intensity and angle of the light affects how warm and soothing an area is for a cat to nap. Trigonometric concepts like sines and cosines could model how the angle of sunlight changes over the course of a day. When a cat jumps between surfaces at different heights and distances, trigonometry comes into play. The cat must calculate the optimal angle and force to exert. Physics calculations involving projectile motion and trigonometry can help explain how cats make these amazing leaps and judgements. While cats don’t actively study trigonometry, their innate spatial reasoning abilities likely involve similar concepts. Thinking about how trigonometry manifests in cat behavior gives us some interesting insights into how their minds work. In summary, while cats do not possess advanced mathematical knowledge or an understanding of complex concepts like trigonometry, they do have some basic geometric and spatial skills. Cats are able to judge distances and heights when jumping and climbing. They can locate objects and navigate environments using their spatial memory. Studies show cats understand object permanence and can mentally rotate objects and recognize shapes. So in their daily activities, cats rely on innate math abilities like estimation, measurement, and basic geometry. However, there is no evidence cats grasp abstract concepts like trigonometric functions. The title question “Does trigonometry come in cat?” is playful hyperbole – cats have rudimentary math skills but not higher-level math knowledge. While fascinating creatures, cats do not actually understand the principles of trigonometry. Further Reading There are many additional resources available for those interested in learning more about trigonometry, geometry, and cats: The website Trigonometry CAT Questions: Concepts, Formulae to Prepare provides an overview of key trigonometry concepts and formulas that are helpful for CAT exam preparation. The Geometry: Trigonometry Questions page on the 2IIM website has lots of example CAT quantitative questions involving trigonometry. For an introduction to using trigonometry concepts with cats, check out the Introduction to Trigonometry for CAT guide from BellCAT. There are many books and online learning platforms with extensive trigonometry resources as well. Mastering trigonometry takes practice, but the resources above provide a solid starting point. Leave a Comment Cancel Reply Your email address will not be published. Required fields are marked * Save my name, email, and website in this browser for the next time I comment. Corbettmaths Trigonometry Practice Questions Click here for questions, click here for answers. Answers – Version 1 Answers – Version 2 GCSE Revision Cards trigonometry questions in cat 5-a-day Workbooks trigonometry questions in cat Primary Study Cards trigonometry questions in cat Privacy Policy Terms and Conditions Corbettmaths © 2012 – 2024 trigonometry questions in cat Trigonometry - Level-wise Practice Questions for CAT Preparation - CAT - Formulas, Tricks, Videos & Tests Part of the course, trigonometry study material, notes for trigonometry - level-wise practice questions for cat preparation for cat, other chapters in level-wise practice questions for cat preparation, how to prepare for cat, frequently asked questions about cat examination. • How many attempts does a CAT have? There is no limit for the CAT exam candidates to the number of attempts of giving the exam. A candidate can appear unlimited time throughout his / her entire lifespan. But the candidates should have some criteria for the candidate to hold a minimum of 50 % marks or equal to no CGPA or grade in Graduation. • Is calculator allowed in CAT? Yes – a calculator is allowed in the CAT exam. But this does not mean that you can carry your own calculator in the exam. You will be allowed to use an on-screen calculator on your computer. • Is GK asked in CAT? While GK or Business GK has not been part of the CAT testing, it is very important for an aspirant to be comfortable with these. Other examinations – like the XAT – have a section on GK. Barring that, the preparation for CAT does not end with giving the CAT examination. Top Courses for CAT Related cat content. trigonometry questions in cat Importance of Trigonometry CAT Trigonometry notes free pdf download, important questions for trigonometry, trigonometry practice questions, welcome back, create you account for free. trigonometry questions in cat Forgot Password Unattempted tests, change country. • Skip to main content • Keyboard shortcuts for audio player trigonometry questions in cat Untangling Disinformation Ai fakes raise election risks as lawmakers and tech companies scramble to catch up. Shannon Bond Shannon Bond trigonometry questions in cat Voters wait to cast their ballots on Jan. 23 in Loudon, N.H. Shortly before voting began, some voters in the state got calls from a faked version of President Biden's voice urging them not to vote, a sign of the potential that deepfakes could have on the electoral process. Tasos Katopodis/Getty Images hide caption Voters wait to cast their ballots on Jan. 23 in Loudon, N.H. Shortly before voting began, some voters in the state got calls from a faked version of President Biden's voice urging them not to vote, a sign of the potential that deepfakes could have on the electoral process. "What a bunch of malarkey." That's what thousands of New Hampshire voters heard last month when they received a robocall purporting to be from President Biden. The voice on the other end sounded like the president, and the catchphrase was his. But the message that Democrats shouldn't vote in the upcoming primary election didn't make sense. "Your vote makes a difference in November, not this Tuesday," the voice said. New Hampshire is investigating a robocall that was made to sound like Biden New Hampshire is investigating a robocall that was made to sound like Biden It quickly emerged that the voice wasn't Biden at all. It was the product of artificial intelligence. Bloomberg reported that ElevenLabs, maker of the AI voice-cloning software believed to have made the digital voice, banned the account involved. On Tuesday, New Hampshire's attorney general said a Texas telemarketing company was behind the call and was being investigated for illegal voter suppression. On Thursday, the Federal Communications Commission ruled robocalls using AI-generated voices illegal under federal telecoms law, opening the door to fines and lawsuits against violators. AI-generated deepfakes are moving fast. Policymakers can't keep up AI-generated deepfakes are moving fast. Policymakers can't keep up Faking a robocall is not new. But making a persuasive hoax has gotten easier, faster and cheaper thanks to generative AI tools that can create realistic images, video and audio depicting things that never happened. As AI-generated deepfakes are being used to spread false information in elections around the world , policymakers, tech companies and governments are trying to catch up. "We don't really think of [AI] as a free-standing threat but as more of a threat amplifier," said Dan Weiner, director of the elections and government program at the Brennan Center for Justice at New York University School of Law. 2024 elections are ripe targets for foes of democracy 2024 elections are ripe targets for foes of democracy He worries that AI will turbocharge efforts to discourage voters or spread bogus claims, especially in the immediate run-up to an election, when there's little time for journalists or campaigns to fact-check or debunk. That's what appears to have happened last fall in Slovakia , just days before voters went to the polls. Faked audio seeming to show one candidate discussing rigging votes and raising the cost of beer started to spread online. His pro-Western party ended up losing to one led by a pro-Russian politician . Because the stakes were high and the deepfake came at a critical moment, "there is a plausible case that that really did impact the outcome," Weiner said. Worry and concern follow pro-Kremlin candidate's victory in Slovakia election Worry and concern follow pro-Kremlin candidate's victory in Slovakia election While high-profile fakes like the Biden robocall get a lot of attention, Josh Lawson, director of AI and democracy at the Aspen Institute, is focused on how AI could be used for personalized targeting. "We are quickly advancing towards a point in the technology, likely before the election itself, when you can have real-time synthetic audio conversations," said Lawson, a former election lawyer who previously worked on elections at Facebook owner Meta. He imagines a scenario where a bad actor deploys AI, sounding like a real person, to call a voter and give false information about their specific polling place. That could be repeated for other voters in multiple languages. He's also worried about AI fakes targeting lower-profile elections, especially given the collapse of local news. "The concern ... is not the big, bad deepfake of somebody at the top of the ticket, where all kinds of national press is going to be out there to verify it," Lawson said. "It's about your local mayor's race. It's about misinformation that's harder and harder for local journalists to tackle, when those local journalists exist at all. And so that's where we see synthetic media being something that will be particularly difficult for voters to navigate with candidates." Deceiving voters, including spreading false information about when and where to vote, is already illegal under federal law. Many states prohibit false statements about candidates, endorsements or issues on the ballot. But growing concerns about other ways that AI could warp elections are driving a raft of new legislation. While bills have been introduced in Congress, experts say states are moving faster. In the first six weeks of this year, lawmakers in 27 states have introduced bills to regulate deepfakes in elections, according to the progressive advocacy group Public Citizen. "There's huge momentum in the states to address this issue," Public Citizen President Robert Weissman said. "We're seeing bipartisan support ... to recognize there is no partisan interest in being subjected to deepfake fraud." Many state-level bills focus on transparency, mandating that campaigns and candidates put disclaimers on AI-generated media. Other measures would ban deepfakes within a certain window — say 60 or 90 days before an election. Still others take aim specifically at AI-generated content in political ads. These cautious approaches reflect the need to weigh potential harms against free speech rights. "It is important to remember that under the First Amendment, even if something is not true, generally speaking you can't just prohibit lying for its own sake," Weiner said. "There is no truth-in-advertising rule in political advertising. You need to have solutions that are tailored to the problems the government has identified." Just how prominent a role deepfakes end up playing in the 2024 election will help determine the shape of further regulation, Weiner said. Meta will start labeling AI-generated images on Instagram and Facebook Meta will start labeling AI-generated images on Instagram and Facebook Tech companies are weighing in too. Meta, YouTube and TikTok have begun requiring people to disclose when they post AI content. Meta said on Tuesday that it is working with OpenAI, Microsoft, Adobe and other companies to develop industrywide standards for AI-generated images that could be used to automatically trigger labels on platforms. But Meta also came under fire this week from its own oversight board over its policy prohibiting what it calls "manipulated media." The board, which Meta funds through an independent trust, said the policy is "incoherent" and contains major loopholes, and it called on the company to overhaul it. "As it stands, the policy makes little sense," said Michael McConnell, the board's co-chair. "It bans altered videos that show people saying things they do not say, but does not prohibit posts depicting an individual doing something they did not do. It only applies to video created through AI, but lets other fake content off the hook. Perhaps most worryingly, it does not cover audio fakes, which are one of the most potent forms of electoral disinformation we're seeing around the world." The moves to develop laws and guardrails reining in AI in elections are a good start, said Lawson, but they won't stop determined bad actors. He said voters, campaigns, lawmakers and tech platforms have to adapt, creating not just laws but social norms around the use of AI. "We need to get to a place where things like deepfakes are looked at almost like spam. They're annoying, they happen, but they don't ruin our day," he said. "But the question is, this election, are we going to have gotten to that place?" • 2024 election • voting stories • artificial intelligence Trigonometry Questions Trigonometry questions given here involve finding the missing sides of a triangle with the help of trigonometric ratios and proving trigonometry identities. We know that trigonometry is one of the most important chapters of Class 10 Maths. Hence, solving these questions will help you to improve your problem-solving skills. What is Trigonometry? The word ‘trigonometry’ is derived from the Greek words ‘tri’ (meaning three), ‘gon’ (meaning sides) and ‘metron’ (meaning measure). Trigonometry is the study of relationships between the sides and angles of a triangle. The basic trigonometric ratios are defined as follows. sine of ∠A = sin A = Side opposite to ∠A/ Hypotenuse cosine of ∠A = cos A = Side adjacent to ∠A/ Hypotenuse tangent of ∠A = tan A = (Side opposite to ∠A)/ (Side adjacent to ∠A) cosecant of ∠A = cosec A = 1/sin A = Hypotenuse/ Side opposite to ∠A secant of ∠A = sec A = 1/cos A = Hypotenuse/ Side adjacent to ∠A cotangent of ∠A = cot A = 1/tan A = (Side adjacent to ∠A)/ (Side opposite to ∠A) Also, tan A = sin A/cos A cot A = cos A/sin A Also, read: Trigonometry Trigonometry Questions and Answers 1. From the given figure, find tan P – cot R. Trigonometry Questions Q1 From the given, In the right triangle PQR, Q is right angle. By Pythagoras theorem, PR 2 = PQ 2 + QR 2 QR 2 = (13) 2 – (12) 2 = 169 – 144 tan P = QR/PQ = 5/12 cot R = QR/PQ = 5/12 So, tan P – cot R = (5/12) – (5/12) = 0 2. Prove that (sin 4 θ – cos 4 θ +1) cosec 2 θ = 2 L.H.S. = (sin 4 θ – cos 4 θ +1) cosec 2 θ = [(sin 2 θ – cos 2 θ) (sin 2 θ + cos 2 θ) + 1] cosec 2 θ Using the identity sin 2 A + cos 2 A = 1, = (sin 2 θ – cos 2 θ + 1) cosec 2 θ = [sin 2 θ – (1 – sin 2 θ) + 1] cosec 2 θ = 2 sin 2 θ cosec 2 θ = 2 sin 2 θ (1/sin 2 θ) 3. Prove that (√3 + 1) (3 – cot 30°) = tan 3 60° – 2 sin 60°. LHS = (√3 + 1)(3 – cot 30°) = (√3 + 1)(3 – √3) = 3√3 – √3.√3 + 3 – √3 = 2√3 – 3 + 3 RHS = tan 3 60° – 2 sin 60° = (√3) 3 – 2(√3/2) = 3√3 – √3 Therefore, (√3 + 1) (3 – cot 30°) = tan 3 60° – 2 sin 60°. Hence proved. 4. If tan(A + B) = √3 and tan(A – B) = 1/√3 ; 0° < A + B ≤ 90°; A > B, find A and B. tan(A + B) = √3 tan(A + B) = tan 60° A + B = 60°….(i) tan(A – B) = 1/√3 tan(A – B) = tan 30° A – B = 30°….(ii) Adding (i) and (ii), A + B + A – B = 60° + 30° Substituting A = 45° in (i), 45° + B = 60° B = 60° – 45° = 15° Therefore, A = 45° and B = 15°. 5. If sin 3A = cos (A – 26°), where 3A is an acute angle, find the value of A. sin 3A = cos(A – 26°); 3A is an acute angle cos(90° – 3A) = cos(A – 26°) {since cos(90° – A) = sin A} ⇒ 90° – 3A = A – 26 ⇒ 3A + A = 90° + 26° ⇒ 4A = 116° ⇒ A = 116°/4 6. If A, B and C are interior angles of a triangle ABC, show that sin (B + C/2) = cos A/2. We know that, for a given triangle, the sum of all the interior angles of a triangle is equal to 180° A + B + C = 180° ….(1) B + C = 180° – A Dividing both sides of this equation by 2, we get; ⇒ (B + C)/2 = (180° – A)/2 ⇒ (B + C)/2 = 90° – A/2 Take sin on both sides, sin (B + C)/2 = sin (90° – A/2) ⇒ sin (B + C)/2 = cos A/2 {since sin(90° – x) = cos x} 7. If tan θ + sec θ = l, prove that sec θ = (l 2 + 1)/2l. tan θ + sec θ = l….(i) We know that, sec 2 θ – tan 2 θ = 1 (sec θ – tan θ)(sec θ + tan θ) = 1 (sec θ – tan θ) l = 1 {from (i)} sec θ – tan θ = 1/l….(ii) tan θ + sec θ + sec θ – tan θ = l + (1/l) 2 sec θ = (l 2 + 1)l sec θ = (l 2 + 1)/2l 8. Prove that (cos A – sin A + 1)/ (cos A + sin A – 1) = cosec A + cot A, using the identity cosec 2 A = 1 + cot 2 A. LHS = (cos A – sin A + 1)/ (cos A + sin A – 1) Dividing the numerator and denominator by sin A, we get; = (cot A – 1 + cosec A)/(cot A + 1 – cosec A) Using the identity cosec 2 A = 1 + cot 2 A ⇒ cosec 2 A – cot 2 A = 1, = [cot A – (cosec 2 A – cot 2 A) + cosec A]/ (cot A + 1 – cosec A) = [(cosec A + cot A) – (cosec A – cot A)(cosec A + cot A)] / (cot A + 1 – cosec A) = cosec A + cot A 9. Prove that: (cosec A – sin A)(sec A – cos A) = 1/(tan A + cot A) [Hint: Simplify LHS and RHS separately] LHS = (cosec A – sin A)(sec A – cos A) = (cos 2 A/sin A) (sin 2 A/cos A) = cos A sin A….(i) RHS = 1/(tan A + cot A) = (sin A cos A)/ (sin 2 A + cos 2 A) = (sin A cos A)/1 = sin A cos A….(ii) From (i) and (ii), i.e. (cosec A – sin A)(sec A – cos A) = 1/(tan A + cot A) 10. If a sin θ + b cos θ = c, prove that a cosθ – b sinθ = √(a 2 + b 2 – c 2 ). a sin θ + b cos θ = c Squaring on both sides, (a sin θ + b cos θ) 2 = c 2 a 2 sin 2 θ + b 2 cos 2 θ + 2ab sin θ cos θ = c 2 a 2 (1 – cos 2 θ) + b 2 (1 – sin 2 θ) + 2ab sin θ cos θ = c 2 a 2 – a 2 cos 2 θ + b 2 – b 2 sin 2 θ + 2ab sin θ cos θ = c 2 a 2 + b 2 – c 2 = a 2 cos 2 θ + b 2 sin 2 θ – 2ab sin θ cos θ a 2 + b 2 – c 2 = (a cos θ – b sin θ ) 2 ⇒ a cos θ – b sin θ = √(a 2 + b 2 – c 2 ) Video Lesson on Trigonometry trigonometry questions in cat Practice Questions on Trigonometry Solve the following trigonometry problems. • Prove that (sin α + cos α) (tan α + cot α) = sec α + cosec α. • If ∠A and ∠B are acute angles such that cos A = cos B, then show that ∠A = ∠B. • If sin θ + cos θ = √3, prove that tan θ + cot θ = 1. • Evaluate: 2 tan 2 45° + cos 2 30° – sin 2 60° • Express cot 85° + cos 75° in terms of trigonometric ratios of angles between 0° and 45°. Leave a Comment Cancel reply Your Mobile number and Email id will not be published. Required fields are marked * Request OTP on Voice Call Post My Comment trigonometry questions in cat • Share Share Register with BYJU'S & Download Free PDFs Register with byju's & watch live videos. close • International edition • Australia edition • Europe edition Illustration of a dinosaur like T rex, in blue and green, on a white background What was the first dinosaur and why do cats like to eat butter? Try our kids’ quiz Five multiple-choice questions – set by children – to test your knowledge, and a chance to submit your own junior brainteasers for future quizzes • Submit a question • 1. Jacob, 7, asks: what was the first dinosaur that lived? Spinosaurus, who had a large fin, like a sail, along its back and could probably swim Tyrannosaurus rex, who was about 4 metres tall and had razor-sharp teeth Nyasasaurus parringtoni, who had a tall neck and long legs, and measured two to three metres long Diplodocus, who had a very long neck Reveal • 2. Beatrix, 5, asks: why do some insects lay their eggs in my pond? Some young insects breathe underwater before they are fully grown A pond can offer protection Ponds are full of food for the young insects All of the above! Reveal • 3. Zac, 13, asks: how long would it take to drive to space if there was a motorway to get there? About 1 hour 15 minutes About 17 months 3 days and 6 hours 22 hours 35 minutes Reveal • 4. Jacob, 7, asks: what is the fastest kind of fly? Dragonfly Horsefly Mayfly Bluebottle Reveal • 5. Nora, 7, asks: our cat likes to eat butter. Why? That’s not normal behaviour for a cat! Because cats are attracted to food with high fat and high protein levels Because cats love all yellow food Because cats love the cooling sensation of chilled butter on their tongues Reveal Molly Oldfield hosts Everything Under the Sun , a weekly podcast answering children’s questions, out now as a book . Does your child have a question? Submit one here • The kids' quiz • Quiz and trivia games Most viewed IMAGES 1. The CAT Trigonometry concepts with questions trigonometry questions in cat 2. CAT : Trigonometry Questions for Quantitative Aptitude trigonometry questions in cat 3. CAT MBA : How to solve a Trigonometry problem in CAT Exam trigonometry questions in cat 4. CAT Preparation -Trigonometry Question 01 trigonometry questions in cat 5. CAT Trigonometry Questions: Concepts, Formulas, Sample Questions PDF trigonometry questions in cat 6. Important Questions of Trigonometry for CAT by Deepanshu trigonometry questions in cat VIDEO 1. TRIGONOMETRY QUESTIONS PRACTICE SET-01 BY-PIYUSH KANT #PPSIan 2. trigonometry Questions #trigonometry #maths #mathstricks #shortvideo #shorts 3. CAT 2023 Algebra : Find the difference of maximum and minimum values of p^3 4. #maths #cat #cats #trigonometry #jump #funny #shorts #fyp #viral 5. Trigonometry questions Maths || 10th board important #youtube #trending 6. Trigonometry questions।। trigonometry mcq।। #trigonometry #upboard #boardexam #exams#shorts COMMENTS 1. CAT Questions A CAT Geometry question from the topic - CAT Trigoneometry that appears in the Quantitative Aptitude section of the CAT Exam broadly tests an aspirant on the concepts - Basic Trigonometric Functions, Heights and Distances, Sine rule, Cosine rule etc . In CAT Exam, one can generally expect to get approx. 1 question from CAT Trigonmetry. 2. Trigonometry for CAT 2023: Sample Questions, Basic Concepts and cosec A = 1/ sin A sec A = 1/ cos A cot AA = 1/ tan A CAT Trigonometry Table of Angles The important formulas related to the trigonometry angles are mentioned below: Definitions and Fundamental identities of Trigonometric Functions Fundamental Identities Reciprocal Identities 3. Trigonometry Practice Questions Hello folks!We're starting a new video series on Trigonometry where we'll be releasing questions on Trigonometry that appeared in PYP of IPMAT, CAT etc. - th... 4. How to Approach 'Trigonometry/Heights and Distances' Questions in CAT Daily Revision Series for CAT 2021. Essential Concepts, Approaches and Questions will be discussed. These videos will be very useful for CAT 2021 and OMETs.D... 5. Trigonometry for CAT 47 Days to CAT - ' Trigonometry ' - A topic where we don't want to invest so much time and don't want to miss either as it may come indirectly with Geometry ... 6. Types of trigonometry and their importance in CAT exams Question 1. The elevation angle of the top of the building at a distance of 50 m from its foot on a horizontal plane is found to be 60°. 7. Trigonometry for CAT & Aptitude Tests Trigonometry-5 | Most Important Rule | Sine Rule, Cosine Rule & It's Application | CAT question. Trigonometry-6 | Maximum and Minimum Value of asinx + bcosx | CAT Question on Trigonometry. Heights & Distance-1 | Fundamentals | Basic Questions | Application of 30-60-90 & 45-45-90 Triangle. 8. Introduction to Trigonometry for CAT By bellcat December 16, 2021 Trigonometry in the CAT exam is a broad topic. However, that doesn't imply direct questions will appear in the exam from this topic. Mostly, trigonometric concepts appear in relation to geometric problems in the Quantitative Aptitude Section. 9. Previous Year CAT Questions for Geometry Geometry - Trigonometry CAT Questions Quantitative Ability Arithmetic - Ratio, Proportion & Variation Learn Concepts Ratio, Proportion, Variation and Partnerships Concept Review Exercise CRE 1 - Ratio CRE 2 - Proportion CRE 3 - Variation CRE 4 - Partnership Practice Exercise PE 1 - Ratio PE 2 - Ratio PE 3 - Ratio PE 4 - Ratio PE 5 - Ratio 10. Trigonometry CAT Questions: Concepts, Formulae to Prepare 1. What are CAT Trigonometry Questions? 2. Table of Angles for CAT Trigonometry Questions 3. Definitions and Fundamental identities of CAT Trigonometry 4. Trigonometry CAT Questions PDF 5. Trigonometry Questions for CAT: Sample 6. How to Prepare CAT Trigonometry Questions? 7. Best Books for Trigonometry CAT Questions 11. Trigonometry Crash Course for CAT This Trigonometry for CAT page is a collection of topic-wise notes, short techniques, tips and tricks, important formulas and topic-wise tests based on Previous Year papers to solve Trigonometry in CAT examination. This collection is designed in a way where you get a complete package for your preparation of the Trigonometry for CAT in one place ... 12. Geometry Solution Discuss Report 2. XAT 2022 QADI | Geometry - Trigonometry XAT Question A tall tower has its base at point K. Three points A, B and C are located at distances of 4 metres, 8 metres and 16 metres respectively from K. The angles of elevation of the top of the tower from A and C are complementary. 13. CAT Questions Method of solving this CAT Question from CAT Geometry - Trigonometry : When you look at your reflection through a mirror, the image is at a distance equal to the distance between mirror and you. Now, think about what this has to with trigonometry. Let the hexagon ABCDEF be of side 'a'. Line AD = 2a. 14. CAT 2019 Question Paper H ere is a slightly tough question in CAT 2019. It combines the topics of trigonometry and algebra. It is very important to have done a solid CAT Preparation to be sure about the concepts and trigonometry formula to even attempt this question. Once you are clear with the concepts & formulas, it would be prudent to practice them from CAT previous year paper. 15. CAT Preparation -Trigonometry Question 01 CAT level question in Trigonometry - 01Questions: Sin²⁰¹⁴x + Cos²⁰¹⁴x = 1, x in the range of [ -5π, 5π ], how many values can x take?(a) 0 (b) 10(c)... 16. CAT Geometry Questions Tips & Concepts The CAT Geometry Questions are the most important chapter of the QA section. The exam-conducting body asks these questions to judge candidates' concepts of circles, triangles, polygons, and other geometry-related questions. So, if you are preparing for CAT 2023, then practised CAT Geometry Questions without forgetting. 17. Trigonometry for Felines. Do Cats Really Understand Angles and The title question, "Does trigonometry come in cat?", is asking if concepts of trigonometry can be applied to understand cat behavior and abilities. 18. Trigonometry Practice Questions Trigonometry Practice Questions. Click here for Questions. Click here for Answers. Answers - Version 1. Answers - Version 2. Practice Questions. Previous: Standard Form Practice Questions. Next: Similar Shapes Area/Volume Practice Questions. GCSE Revision Cards. 5-a-day Workbooks. Primary Study Cards. Search. Search. 19. Trigonometry Get ready to ace your CAT exam with Trigonometry Practice Questions! This comprehensive collection of practice papers and question papers is designed to help you master the exam. Boost your preparation with paper analysis and best books recommended by toppers. Access study material, notes, and sample papers for thorough revision. ... 20. CAT Preparation -Trigonometry Question 02 CAT Preparation -Trigonometry Question 02 2IIM CAT Preparation 156K subscribers Subscribe 5.5K views 4 years ago Geometry Questions - CAT | XAT | IIFT CAT level question in... 21. Artificial intelligence deepfakes are a threat to elections : NPR As AI-generated deepfakes are being used to spread false information in elections in the U.S. and around the world, policymakers, tech platforms and governments are trying to catch up. 22. Trigonometry Questions 1. From the given figure, find tan P - cot R. Solution: From the given, PQ = 12 cm PR = 13 cm In the right triangle PQR, Q is right angle. By Pythagoras theorem, PR 2 = PQ 2 + QR 2 QR 2 = (13) 2 - (12) 2 = 169 - 144 = 25 QR = 5 cm tan P = QR/PQ = 5/12 cot R = QR/PQ = 5/12 So, tan P - cot R = (5/12) - (5/12) = 0 2. 23. What was the first dinosaur and why do cats like to eat butter? Try our Because cats love the cooling sensation of chilled butter on their tongues Reveal Molly Oldfield hosts Everything Under the Sun , a weekly podcast answering children's questions, out now as a book . 24. Trigonometry Practice Questions Share your videos with friends, family, and the world
__label__pos
0.860274
Quantcast Jump to content Search In • More options... Find results that contain... Find results in... 1. Welcome to GTAForums!   (93,073 visits to this link) 2. News 1. GTA Online 1. Find Lobbies & Players 2. Guides & Strategies 3. Vehicles 4. Content Creator 5. Help & Support 2. Crews 1. Events 2. Recruitment 1. Grand Theft Auto Series 2. GTA Next 3. GTA V 1. PC 2. Guides & Strategies 3. Help & Support 4. GTA IV 1. Episodes from Liberty City 2. Multiplayer 3. Guides & Strategies 4. Help & Support 5. GTA Mods 5. GTA Chinatown Wars 6. GTA Vice City Stories 7. GTA Liberty City Stories 8. GTA San Andreas 1. Guides & Strategies 2. Help & Support 3. GTA Mods 9. GTA Vice City 1. Guides & Strategies 2. Help & Support 3. GTA Mods 10. GTA III 1. Guides & Strategies 2. Help & Support 3. GTA Mods 11. Top Down Games 1. GTA Advance 2. GTA 2 3. GTA 12. Wiki 1. Merchandising 1. GTA Modding 1. GTA V 2. GTA IV 3. GTA III, VC & SA 4. Tutorials 2. Mod Showroom 1. Scripts & Plugins 2. Maps 3. Total Conversions 4. Vehicles 5. Textures 6. Characters 7. Tools 8. Other 9. Workshop 3. Featured Mods 1. DYOM 2. OpenIV 3. GTA: Underground 4. GTA: Liberty City 5. GTA: State of Liberty 1. Red Dead Redemption 2 2. Red Dead Redemption 3. Rockstar Games 1. Off-Topic 1. General Chat 2. Gaming 3. Technology 4. Programming 5. Movies & TV 6. Music 7. Sports 8. Vehicles 2. Expression 1. Graphics / Visual Arts 2. GFX Requests & Tutorials 3. Writers' Discussion 4. Debates & Discussion 1. Forum Support 2. Site Suggestions • 0 Sign in to follow this   goodidea82 Deleted Topics Question goodidea82 In the past I have created several topics for my mods and other discussion and now I see that they do not exist anymore. This is frustrating.   Was there a technical problem that caused the deletion of topics or are topics deleted intentionally? What are the rules for keeping or deleting topics? Are deleted topics archived somewhere? Share this post Link to post Share on other sites 5 answers to this question Recommended Posts • 0 Spider-Vice 4 hours ago, goodidea82 said: - GTA Soccer TeamPlay (I have created a new topic with this title because I wasn't able to find the original that I created in 2014).   It's listed in your profile when you see Your Activity: https://gtaforums.com/topic/708965-relsa-soccer-team-play/     4 hours ago, goodidea82 said: - Camping mobile safehouse Same thing: https://gtaforums.com/topic/818883-camping-mobile-save-house-20-and-trailer-attach-mod/     4 hours ago, goodidea82 said: - combine GTA by parallel exeuction (very roughtly the title) Same thing: https://gtaforums.com/topic/563658-combining-several-gta-games-by-parallel-execution/     Nothing was deleted or hidden, everything is visible, not sure how you didn't find them. There is a button in your profile saying "See their activity", you can use this, and then select Topics. Everything is there. https://gtaforums.com/profile/799628-goodidea82/?do=content&amp;type=forums_topic&amp;change_section=1   Share this post Link to post Share on other sites • 0 Spider-Vice Can you tell us some examples of topics that may have been deleted? We usually don't delete topics, we either hide them or put them in a bin, and I can't find any past topics by you in either the bin, or hidden. Share this post Link to post Share on other sites • 0 goodidea82 Posted (edited) Quote Can you tell us some examples of topics that may have been deleted? We usually don't delete topics, we either hide them or put them in a bin, and I can't find any past topics by you in either the bin, or hidden. Then perhaps it is a technical problem. I was never informed that any of my topics get deleted or hidden.   I don't remember exactly the titles but the title and/or content contained these words: - GTA Soccer TeamPlay (I have created a new topic with this title because I wasn't able to find the original that I created in 2014). - Camping mobile safehouse - combine GTA by parallel exeuction (very roughtly the title) Can't search for the others because of : "Sorry, there is a problem Please wait 1 second before attempting another search " Edited by goodidea82 Share this post Link to post Share on other sites • 0 goodidea82 Wonderful and thank you! I was worried about my posts. I did the following effort when searching:   1. Kicked on my profile. Clicked on "See my activity", actually I found it once, and another time I had problems to find it because I was looking at the top and on the left for it. Once I found "See my activity" I searched in "All activity". The relevant posts are not listed there. There is also no "next page". I have assumed that "All activity" includes my topics, so I did not click on "Topics". Suggestion: either remove "All activity" or make sure it is what it means. Also, since the word "Forums" below "All activity" is not clickable, one may think that the words blow are also not-clickable.   2. I have also used the search field in the forums. For example, I clicked on the forum "Scripts & Plugins", then used the search field, clicked on "More search options" and added my user name. The search gives no results. Here is the URL generated by the search field: https://gtaforums.com/search/?&q=Soccer&author=goodidea82&search_and_or=or&sortby=relevancy     Share this post Link to post Share on other sites • 0 goodidea82 Posted (edited) Meanwhile I have reported my duplication of the topic so the new one can be closed and the original one should stay.     Edited by goodidea82 Share this post Link to post Share on other sites Create an account or sign in to comment You need to be a member in order to leave a comment Create an account Sign up for a new account in our community. It's easy! Register a new account Sign in Already have an account? Sign in here. Sign In Now Sign in to follow this   × Important Information By using GTAForums.com, you agree to our Terms of Use and Privacy Policy.
__label__pos
0.767891
Deka87 Deka87 - 1 month ago 9 CSS Question Is it important to have relative units to ensure Section 508 / WCAG 2.0 Level AA compatibility? I have all my font sizes defined in pixels, e.g. body { font-size: 14px; } h1 { font-size: 42px; } One of the online Section 508 / WCAG 2.0 Level AA compatibility checkers advised me to replace it with relative units to make it accessible to people who increased their font size via browser. Is that a real requirement to follow? I doubt because none of the other online checkers advised me so (although I do understand that it's not always possible to test it automatically). Answer As far as I know, 508 does not specifically require that font size be adjustable, but experts expressly recommend allowing font resize. Nielson says: Let Users Control Font Size: Tiny text tyrannizes users by dramatically reducing task throughput. IE4 had a great UI that let users easily change font sizes; let's get this design back in the next generation of browsers. On this line, Section 508 § 1194.21(g) does state: Applications shall not override user selected contrast and color selections and other individual display attributes which includes font size and is compatible with the WCAG text resize success criterion that: The author's responsibility is to create Web content that does not prevent the user agent from scaling the content effectively So long as you're not forbidding text resizing (like using images of text or using the text-resize-adjust CSS), you're good. But, at the end of the day, the use of relative font size provides for a better experience resizing text, which includes not just size of the font but attributes like line wrapping. For these reasons, I'd consider relative font sizes important for aesthetics but not important for accessibility.
__label__pos
0.875835
Should you only use futures for I/O-bound tasks? So I'm wondering if you should use futures for I/O-bound tasks and not CPU-bound tasks and does using CPU-bound tasks effect the performance in some way or is it bad for some reason? Design of async is inherently based on a "trick" for running many I/O-bound tasks without using many threads, but it's not possible to run many CPU-bound tasks without using threads. So I/O-bound tasks should just have threads only for I/O and CPU-bound tasks should have threads only for CPU. Though what if a CPU-bound task depends on an I/O-bound task? This is not quite accurate in the case where you have a mix of the two: ideally you should be thinking about having a pool of threads that can, in theory, run any task, and the maximum amount of uninterrupted (blocking) time any of these can use. This is because there's only a certain amount of hardware CPU cores that can run either type of task, and each thread uses a base amount of resources, so you should avoid creating an unbounded amount of them. If you're in a purely CPU bound task that could take long enough for it to affect the rest of the system by occupying a thread so another task can't progress, you can break up it's progress by inserting calls to APIs like yield_now in tokio::task - Rust Alternatively, you can simply take the hit of spinning up a thread if needed with APIs like spawn_blocking in tokio::task - Rust, or use channels to communicate from "the sync world", if you're wanting to use a specialized for CPU task library like rayon - Rust Though I won't have a lot of I/O-bound tasks so would it be possible to have just one thread pool with worker threads that are mostly for the CPU-bound tasks and maybe one or two for I/O-bound tasks and not use futures for the I/O-bound tasks as I won't have many of them and futures have a bit of an overhead. It's just I don't want a CPU-bound tasks to have to block for a long time because of an I/O bound task it depends on. So maybe everything that depends on the I/O-bound task should be put with it so it doesn't slow the rest of the CPU-bound task down. Handling either of resources should be separated (separate computers ideally as you'd need different hardware specs for each, separate threads otherwise). So you may want to have say on 8 core machine 1 or two threads dedicated to handling io and the rest for handling cpu-intensive computations (depending on the load balance), because you don't want computations to block io. what if a CPU-bound task depends on an I/O-bound task? That's why you have queues. Thread running computations will do as much as it can, than do something else, while the task is waiting for io completion, and when that's done it will continue computation. There are various guidelines for how often to do these yields, too. For Web browsers and GUI applications, either 50ms (keep responsive at a 100ms deadline) or 15ms (1 frame @ 60fps) are good choices. For latency sensitive servers, 500 microseconds is a common choice. For batch processing (not latency sensitive), you can sometimes reach all the way up to 1 second but things like network timeouts may limit you to 360ms, and you should emit progress information instead of a simple yield. This can actually be a reason to use async for CPU-bound tasks — as long as you keep them on a separate thread pool (perhaps managed by an independent async executor). When the CPU-bound task awaits something completing on the other pool, it will necessarily yield, allowing the executor to schedule a different CPU-bound task. (In contrast, if you run a synchronous-blocking task, you can't tell from the outside whether the task is currently computing or blocking — unless it announces it somehow like rayon does, but rayon's scheduling strategy is not suitable for interacting with non-CPU-bound tasks.) In general, async is a very flexible mechanism, and the thing to keep in mind is not so much “whether to use async”, but rather, if you are using async, to think about the character of the tasks you're running, and try not to mix tasks with incompatible latency requirements and yield-periods on the same executor. 2 Likes Let me plug something I wrote which fits in right here: yield-progress defines a common abstraction for “emit a task report progress and yield”, letting tasks be independent of the destination of their progress info and the particular flavor of yield() needed (for an executor, or to check a clock before yielding). It's not all that polished yet, but I hope it'll be useful for those using async in domains beyond simple IO multiplexing. 1 Like Some form of spawning tasks and then waiting for their results can be useful for certain kinds of CPU-bound computations. But other approaches like scoped threads, query systems, rayon's parallel iterators can be used too. I figure async runtimes are mostly geared towards IO because that's the pattern you get when you're trying to do several latency-sensitive IO things concurrently while maintaining a facade of imperative code. For batch processing those patterns may not be needed when one can have a bunch of threads slurp in large amounts of data, process them in memory and then persist them at the end (or on another thread) with large writes. You might also want to look into other approaches to structure CPU tasks, such as scoped threads, rayon, channels, concurrent data structures, query systems, ... Thanks so much this really helped explain things to me as I was just really against async as it seemed to block a lot and I didn't think of just stealing work from somewhere and executing that work while waiting for the other work to finish in order to keep being as efficient as possible. So I'm going to use sync when not depending on I/O-bound tasks and async when depending on I/O-bound tasks. Though I may not actually use yielding as it switches the context which can be expensive. Which is why I will just have a Sync Thread Pool, Async Thread Pool, and I/O Thread Pool.
__label__pos
0.927676
Browse Source adjust paths to local cbox master Nils 7 months ago parent commit a09601639d 1. 2   engine/api.py 2. 4   engine/input_apcmini.py 3. 4   engine/main.py 4. 5   engine/pattern.py 5. 36   template/calfbox/nullbox.py 6. 16   template/start.py 2 engine/api.py @ -26,7 +26,7 @@ import logging; logger = logging.getLogger(__name__); logger.info("import") from typing import List, Set, Dict, Tuple #Third Party Modules from calfbox import cbox from template.calfbox import cbox #Template Modules import template.engine.api #we need direct access to the module to inject data in the provided structures. but we also need the functions directly. next line: 4 engine/input_apcmini.py @ -25,10 +25,8 @@ import logging; logging.info("import {}".format(__file__)) #Python Standard Library import atexit #Third Party Modules from calfbox import cbox #Template Modules from template.calfbox import cbox from template.engine.input_midi import MidiInput #Our Modules 4 engine/main.py @ -23,10 +23,8 @@ import logging; logger = logging.getLogger(__name__); logger.info("import") #Standard Library Modules #Third Party Modules from calfbox import cbox #Template Modules from template.calfbox import cbox from template.engine.data import Data as TemplateData import template.engine.sequencer from template.engine.sequencer import SequencerInterface #group tracks 5 engine/pattern.py @ -26,8 +26,8 @@ from typing import List, Set, Dict, Tuple from warnings import warn from statistics import median #Third Party Modules from calfbox import cbox #Template Modules from template.calfbox import cbox DEFAULT_VELOCITY = 90 @ -426,4 +426,3 @@ class Pattern(object): return self #No export. Track uses pattern data directly in its own export. 36 template/calfbox/nullbox.py @ -1,18 +1,23 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- import importlib class NullCalfbox(str): #iterable """A drop-in replacement for calfboxs python module. Use this for testing and development. At the start of your program, first file, insert: import nullbox import prefix.calfbox.nullbox or from SOMETHING import nullbox All further from calfbox import cbox from prefix.calfbox import cbox will use the null module. Even additional import calfbox import prefix.calfbox will use the nullbox module. """ @ -55,13 +60,28 @@ class NullCalfbox(str): #iterable import sys import nullbox #Hack 'from calfbox import cbox' sys.modules["calfbox"] = sys.modules["nullbox"] import calfbox try: import nullbox except ModuleNotFoundError: from . import nullbox for key, value in sys.modules.items(): if "nullbox" in key: r = key break else: raise ValueError("Nullbox Module not found") #r is the actual name of the calfbox parent modul. We cannot assume it to be "calfbox". calfboxModuleName = r[:-len(".nullbox")] #remove suffix sys.modules[calfboxModuleName] = sys.modules[r] #e.g. sys.modules["calfbox"] is now nullbox #Hack 'from prefix.calfbox import cbox' importlib.import_module(calfboxModuleName) #Imported once here, all modules will import this variant later. #import calfbox cbox = NullCalfbox("fake cbox null client") #Hack direct call 'import cbox' sys.modules["cbox"] = cbox import cbox import cbox #Imported once here, all modules will import this variant later. 16 template/start.py @ -111,20 +111,11 @@ if compiledVersion: "desktopfile": os.path.join(prefix, "share", "applications", METADATA["shortName"] + ".desktop"), # type: ignore #not ~/Desktop but our desktop file "share": os.path.join(prefix, "share", METADATA["shortName"]), # type: ignore "templateShare": os.path.join(prefix, "share", METADATA["shortName"], "template"), # type: ignore #"lib": os.path.join(prefix, "lib", METADATA["shortName"]), #cbox is found via the PYTHONPATH } _root = os.path.dirname(__file__) _root = os.path.abspath(os.path.join(_root, "..")) import zipfile import tempfile logger.info("Extracting shared library to temporary directory") zipfilePath = get_script_dir().rstrip("/template") assert zipfile.is_zipfile(zipfilePath), (zipfilePath) #in our tests this worked. but in lss this results not in a zip file header. linux file also says it is no zip. However, unzip works. #Extract included .so to tmp dir, tmp dir gets garbage collected at the end of our program. libsharedDir = tempfile.TemporaryDirectory() #Not compiled, not installed. Running pure python directly in the source tree. else: _root = os.path.dirname(__file__) @ -136,7 +127,6 @@ else: "desktopfile": os.path.join(_root, "desktop", "desktop.desktop"), #not ~/Desktop but our desktop file "share": os.path.join(_root, "engine", "resources"), "templateShare": os.path.join(_root, "template", "engine", "resources"), #"lib": "", #use only system paths } logger.info("PATHS: {}".format(PATHS)) @ -326,13 +316,9 @@ if args.mute: Needs adding of the local tree into python search path. 4) impossible: run program installed, calfbox in local tree """ #if not compiledVersion: #import template.calfbox.py # sys.modules["calfbox"] = sys.modules["template.calfbox.py"] import template.calfbox.nullbox logger.info(f"Using {sys.modules['template.calfbox']} as calfbox/nullbox") else: import ctypes.util libname = ctypes.util.find_library("calfbox-lss") #returns something like 'libcalfbox-lss.so.1' without a path, but with "lib" Loading… Cancel Save
__label__pos
0.816058
What is Sacred Geometry and how can you benefit from it? The term ‘Geometry’ has its origin from two Greek words: Geos, which mean Earth and Metron, which means ‘to measure.’ The two words together literally mean ‘measuring the earth’ or ‘earthly measurements.’ Measuring the earth was an art that was traditionally restricted to the priesthood. Sacred geometry has been around across the ages, beginning with the Minoans, the Egyptians, Sumerians, Hindus, Chinese, Phoenicians, and the Greeks who offered it to the public. Sacred geometry refers to the various shapes and forms that were traditionally used in architecture, art, and meditation through the centuries. They are the same forms and shapes that are found in natural organisms. To many people, sacred geometry seems to be esoteric but it is important to understand the same as they could help us view our world, which could be useful in our own life. In ancient cultures, there was the recognition that various patterns or geometric shapes appear repeatedly throughout nature such as the spiral shell of snails and the hexagonal honeycombs. These common shapes and patterns that can be seen in nature are referred to as sacred geometry. Sacred geometry may be broken down further in mathematical formulas and symbols that form the building blocks of everything in the universe. This ancient theory is supported by modern science because the molecular shapes form the basis of life, the same shapes that are identified by ancient cultures. It is believed that the construction of sacred structures, such as mosques, temples, monuments, megaliths, and churches; sacred spaces such as tabernacles or altars; historical buildings, such as the pyramids of Egypt, the Parthenon in Greece, and the temples found throughout South and Central America; meeting places; and the creation of religious arts and iconography. Sacred geometry in arts may be ephemeral, such as sand paintings, medicine wheels, and visualization. Sacred geometry is a worldview of pattern recognition. It is a complex system of religious structures and symbols that involve time, space, and form. Following this view, the basic patterns of existence are sacred. By studying the nature of the forms, patterns, and relationships and their connections, it will be easier to gain an insight into the history and mysterious laws of the Universe.   Sacred Geometry’s significant shapes   Sphere   It is a container that has the ability to hold all forms. Sphere represents inclusion, oneness, and integrity because all measurements are equal in a sphere. The spherical shape can be seen in planets, cells, seeds, and atoms.   Circle   It is a two-dimensional representation of the sphere. It shows the total completeness and unity of the universe. The ratio of its circumference compared to its diameter is the Pi, an infinite number that never ends.   Point   It is the center of both a sphere and a circle. The point is the beginning and the end of all measurements, hence its association with the beginning and the end of all creations.   Spirals   All types of spirals – flat, right-handed, left-handed, 3-D, equiangular, or logarithmic – show expansion and growth, which makes them symbolize infinity.   Toroids   A torus is similar to an inner tube, with the round sides perfectly circular. The torus is a primary shape in sacred geometry, such as the seven primary muscles in the heart having a toroid shape.   The Vesica Piscis   The words are Latin for a bladder of fish. It is actually the intersection of two circles having the same size as their centers touching each other. It represents common ground between people. It is the symbol of Christ in the Christian religion.   Platonic solids   They are 3-dimensional shapes with each one made of equal-sized faces. The platonic solids are:   • Tetrahedron – 4 faces of pyramid shapes • Hexahedron – 6 faces such as a cube • Octahedron – 8 faces • Dodecahedron – 12 faces • Icosahedron – 20 faces   Metatron’s Cube   The Metatron’s cube contains all the Platonic solids, making it called the building blocks of creation. Metatron in Judaism is the angel who is guarding God’s throne.   Flower of Life It is represented by several evenly-spaced circles that overlap each other, forming a flower-like pattern. The Flower of Life contains all the Platonic solids and Metatron’s Cube.   The Golden Ratio   It is a mathematical ratio occurring when two items having the same ratio when compared to each other as the ratio of their sum compared to the larger of the two items.   Sacred Geometry Jewelry   Sacred Geometry has been used by anthropologists, archeologists, and geometricians in incorporating the religious, spiritual, and philosophical beliefs that have sprung up from geometry in various cultures over the centuries. The various shapes of sacred geometry can be found everywhere in nature as they reveal to mankind the concept of oneness through geometry.   The various sacred geometry shapes have been incorporated in jewelry designs in order to facilitate the balance, healing, and self-discovery while at the same time inspiring the wearer as he or she travels towards the totality and unity of the whole self.   Tiny Devotions We are a sisterhood  devoted to empowering the bold and courageous women of the community. The various types of jewelry that we create are meant to activate energy and knowledge in the mind as a way of achieving spiritual clarity. By exploring the building blocks of the universe through the different jewelry pieces, one can find the secret source of life.   Our Sacred Geometry rings are meant to inspire and help you in whatever path your journey takes you. Light and Love!   Speak Your Mind * nine − = 8
__label__pos
0.95389
How to create an array in PowerShell from CSV file In this PowerShell tutorial, we will discuss how to create a PowerShell array from a CSV file. We can easily create an array from a comma-separated string in PowerShell. PowerShell create array from csv file example in detail. PowerShell create array from CSV file To create an array from a CSV file in PowerShell, we need to first create the CSV file. I have created a CSV file with below two columns: • Name • Salary The CSV file looks like below: powershell array from csv We can use Import-Csv to manipulate and work with a CSV file. The Import-CSV cmdlets in PowerShell create a table like custom objects from the items presented in the CSV file. In the below PowerShell script, we will use the Import-CSV cmdlets to assign the CSV file data to a variable of PowerShell array type. You can run the below script in PowerShell ISE. $users=Import-Csv E:\Bijay\Users.csv $users You can see the output in the array format. powershell array from csv file Access Array Elements after import-csv We can access various array elements after creating an array using Import-Csv. To access all the elements, we can use the object like below: $users=Import-Csv E:\Bijay\Users.csv $users To retrieve the first element from the array we can write the PowerShell cmdlet like below: $users=Import-Csv E:\Bijay\Users.csv $users[0] powershell create array import-csv We can access the property from a particular element from the PowerShell array like below: $users=Import-Csv E:\Bijay\Users.csv $users[0].Name powershell create array from comma separated string We can count the number of elements by using the count property like below: $users=Import-Csv E:\Bijay\Users.csv $users.Count powershell create array from csv Import into different arrays in PowerShell We can also import into different arrays based on the column after creating an array from the csv file in PowerShell. We can use Import-CSV foreach to loop through PowerShell array. Here, I have created two empty array and then I am assigning the values to it. $Names=@() $Salaries =@() Import-Csv E:\Bijay\Users.csv | ForEach-Object { $Names += $_.Name $Salaries += $_.Salary } $Names Write-Host("******************") $Salaries $_ represents the current object or the current row. You can see the output like below: powershell create array from csv file Here, the first array displays the Names, and the second array displays the Salaries. You may like following tutorials: In this tutorial we learned: • How to create an array from CSV file • Access Array Elements after import-csv • Import into different arrays in PowerShell • Hello, Bijay. Would you please help provide a sample powershell script “how to create Hashtable from CSV file”. Looking forward to hearing from you. Thanks. PS I have learned a lot from your blog “how to create an array from CSV file”. • you left out the most useful usecase! How do you find the value for a given varialbe. Using your example how do you display the salary for padmini • >
__label__pos
0.988467
UIbuilder VueX and VueRouter To (amateurs) whom it may concern, some concepts of Vue(X) and VueRouter which kept me busy using the UIBuilder node , and just to add my fun experience : Passing parameters with Vue between components and/or routes. 1. In Vue-Router, if you wanted to pass an object as a param , you might have noticed you get errors when trying to display them. Imagine the following template : <template> <div> <h1> List </h1> <div v-for="timer,i in example" :key="i"> <router-link :to="{ name:'TimerDetails', params: {id:i, org:timerobject }}"> <h2 >{{ timer.name }}</h2> </router-link> </div> </div> </template> params: {id:i, org:timerobject }} Vue-router does not support passing object parameters, so the workaround is to use JSON.stringify : params: {id:i, org:JSON.stringify(timerobject) }} In this case the "timerobject" will be passed as a string. In the appropriate route .vue file, in this example "TimerDetails.vue", you can parse back the json string. export default { data() { return { id: this.$route.params.id, org: JSON.parse(this.$route.params.org) } } } 1. Looking at : a better solution to passing params depending on size/complexity/criticality etc. , VueX comes into view . This also has the advantage of the Vue-client app being able to dynamically receive updates from the server without having to resort to using api's . .vue file : <script> export default { computed: { example () { return this.$store.state.timers } } } </script> index.js file : import Vue from 'vue' import App from './App.vue' import VueRouter from 'vue-router' import router from './router' import Vuex from 'vuex' Vue.use(Vuex); Vue.use(VueRouter) const store = new Vuex.Store({ state: { timers:[{name:'s0'}], }, mutations: { populate (state,elem) { state.timers = elem } } }) new Vue({ el: '#app', router, store, render: h => h(App), mounted: function(){ const vueApp = this }, // --- End of mounted hook --- // }) and the App.vue file (extract related to Vuex and uibuilder/node-red) mounted() { const app = this; uibuilder.onChange('msg', function(msg){ //console.log('Vue:mounted:UIBUILDER: property msg changed! ', msg) app.msgreceived = msg.payload app.mytimers = msg.original app.timerevents = msg.timer app.$store.commit('populate',msg.original) }) // ---- End of uibuilder.onChange() watcher function ---- // }, So, every message from node-red UIbuilder node will result in populating the $store variables , in this case "timers" . They will be computed in the various routes where you get them using : (use the compute section in your area of the vue file) this.$store.state.timers Cool, thanks for sharing that. Would you be OK with me adding this to the WIKI? Or indeed, you could add a new page to the WIKI yourself if you like? I do need to try and find time to play with VueX and VueRouter. Most of my use of Vue though is pretty straight-forward. Oh , of course. I've got to make it complete though. Feel free to add in a new wiki. It needs some cleaning up probably. note that this is currently an example WITH a build step. I am contemplating of converting this to a vanilla uibuilder project without a build step :slight_smile: This is a project to list/view timers (an array of objects, 1 object per timer), which have an on/off state, and have schedules attached to each of them (i.e. active at certain day(s) of the week ). Each timer runs in its own timezone , if defined, otherwise system time. UIBuilder gets all properties of the list of timers , in the 'msg.original' object from node-red. (every minute). It also receives a list of "next" events , i.e timers that are going to change state , in the 'msg.timers'. Another requirement of the design is to make it user friendly, viewable on iOS, hence the 'large' amount of styling involved. Main object received from node red : msg.original (array of timers). Each timer has a property list , which is an array of schedules, and a property params, which is an array of parameters. Below is one element of this array as an example of what is received. [{"name":"s1","params":[{"name":"outputformat","value":0},{"name":"status","value":"1"},{"name":"location","value":""},{"name":"timezone","value":0}],"list":[{"startstop":{"Start":"10:50","Stop":"11:45"},"days":[{"name":"monday","value":true},{"name":"tuesday","value":false},{"name":"wednesday","value":true},{"name":"thursday","value":false},{"name":"friday","value":true},{"name":"saturday","value":false},{"name":"sunday","value":false}]}]},...] Secondary object received is the list of upcoming events , all that logic in node-red , not in uibuilder. Below is the object [{"timer":"s5","period":30,"old_value":0,"new_value":1,"timeperiod":"21:29","state":"success"},{"timer":"s3","period":39,"old_value":1,"new_value":0,"timeperiod":"21:38","state":"danger"},{"timer":"s4","period":443,"old_value":1,"new_value":0,"timeperiod":"04:22","state":"danger"}] it looks as follows : image image image File structure : : project_dir -- src App.vue index.js index.html -- src/views/ Home.vue About.vue TimeComp.vue -- src/views/timers Timers.vue TimerDetails.vue -- src/router index.js index.js (router) file : import VueRouter from 'vue-router' import Home from '../views/Home.vue' import About from '../views/About.vue' import Timers from '../views/timers/Timers.vue' import TimerDetails from '../views/timers/TimerDetails.vue' const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/timers', name: 'Timers', component: Timers }, { path: '/timers/:id', name: 'TimerDetails', component: TimerDetails }, { path: '/about', name: 'About', component: About }, { path: '/:catchAll(.*)', redirect: { name: 'Home'} } ] const router = new VueRouter({ //history: createWebHistory(process.env.BASE_URL), mode: 'history', base: '/uirouter', routes }) index.js (in src) file import VueRouter from 'vue-router' import router from './router' import Vuex from 'vuex' import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' Vue.use(Vuex); Vue.use(VueRouter) Vue.use(BootstrapVue) Vue.use(IconsPlugin) const store = new Vuex.Store({ state: { timers:[{name:'s0'}], timerevents:[] }, mutations: { populate (state,elem) { state.timers = elem }, populate_timerevents(state,elem) { state.timerevents = elem } } }) new Vue({ el: '#app', router, store, render: h => h(App), mounted: function(){ const vueApp = this }, // --- End of mounted hook --- // }) App.vue file <template> <div> <div id="nav"> <router-link :to="{name:'Home'}">Home</router-link>| <router-link :to="{name:'About'}">About</router-link>| <router-link :to="{name:'Timers', params: {org:JSON.stringify(mytimers) }}">Timers</router-link> <TimeComp/> </div> <router-view /> </div> </template> <script> import uibuilder from './../../../node_modules/node-red-contrib-uibuilder/front-end/src/uibuilderfe.js' import TimeComp from './views/TimeComp.vue' export default { data() { return { msgreceived:"", mytimers:[], } }, created() { uibuilder.start(this) }, methods: { }, mounted() { const app = this; uibuilder.onChange('msg', function(msg){ //console.log('Vue:mounted:UIBUILDER: property msg changed! ', msg) app.msgreceived = msg.payload app.mytimers = msg.original app.timerevents = msg.timer app.$store.commit('populate',msg.original) app.$store.commit('populate_timerevents',msg.timer) //console.log(app.$store.state) }) // ---- End of uibuilder.onChange() watcher function ---- // }, components: { TimeComp } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } #nav { padding: 30px; text-align: center; font-family: Roboto; font-size: 24px; margin: 10px auto; } #nav a { font-weight: bold; color: #2c3e50; text-decoration: none; padding: 10px; border-radius: 5px; } #nav a.router-link-exact-active { color: white; background: crimson; } </style> Timer.vue <template> <div> <h1 class="fade-in-image"> List </h1> <div v-for="timer,i in example" :key="i" class="timer"> <router-link :to="{ name:'TimerDetails', params: {id:i, org:JSON.stringify(timer) }}"> <h2 >{{ timer.name }}</h2> </router-link> </div> </div> </template> <script> export default { data () { return { mytimers: this.$store.state.timers } }, created() { }, mounted() { }, computed: { example () { return this.$store.state.timers } } } </script> <style> h1 { margin:10px auto; padding:10px; text-align: center; font-family: Roboto; } .timer h2 { background: #f4f4f4; padding: 20px; border-radius: 15px; margin:10px auto; max-width: 600px; cursor: pointer; color: #444; } .timer h2:hover { background: #ddd; text-decoration:none!important; } .timer a { text-decoration:none } .timer a:hover { text-decoration:none } .fade-enter-from { opacity: 0; } .fade-enter-to { opacity: 1 } .fade-enter-active { transition: all 2s ease; } .fade-leave-from { opacity: 1; } .fade-leave-to { opacity: 0; } .fade-leave-active { transition: all 2s ease; } .fade-in-image { animation: fadein 2s; -moz-animation: fadein 2s; /* Firefox */ -webkit-animation: fadein 2s; /* Safari and Chrome */ -o-animation: fadein 2s; /* Opera */ } @keyframes fadein { from { opacity:0; } to { opacity:1; } } @-moz-keyframes fadein { /* Firefox */ from { opacity:0; } to { opacity:1; } } @-webkit-keyframes fadein { /* Safari and Chrome */ from { opacity:0; } to { opacity:1; } } @-o-keyframes fadein { /* Opera */ from { opacity:0; } to { opacity: 1; } } </style> TimerDetails.vue <template> <div> <h1> Timer <b-badge variant="danger">{{ org.name }}</b-badge> </h1> <div class="paramcontainer"> <div class="params"> <div class="paramitem" v-for="(param, i) in paramtable" :key="i"> <b-badge variant="light"> {{ param.name }}</b-badge> <b-badge variant="primary"> {{ param.value }}</b-badge> </div> </div> </div> <div class="schedulecontainer"> <div class="scheduleheader"> <span class="schedheaders" ><b-badge variant="secondary">Start</b-badge></span > <span class="schedheaders" ><b-badge variant="secondary">Stop</b-badge></span > <div class="dayheaders"> <b-badge variant="secondary">Days</b-badge> </div> </div> <div class="schedule" v-for="(schedule, i) in org.list" :key="i"> <b-badge variant="success"> {{ schedule.startstop.Start }}</b-badge> <b-badge variant="danger"> {{ schedule.startstop.Stop }}</b-badge> <div class="dayscontainer"> <div class="weekdays" v-for="(day, j) in schedule.days" :key="j"> <img :class="(day.value && 'dayshow') || 'dayhide'" :src="dayicons[j]" /> </div> </div> </div> </div> </div> </template> <script> export default { data() { return { id: this.$route.params.id, org: JSON.parse(this.$route.params.org), ptable: [], format: ["String", "Numeric", "Boolean"], timerstatus: ["Disabled", "Enabled"], tzformat: ["System", "Local"], dayicons: [ "/icons8-monday-40.png", "/icons8-tuesday-40.png", "/icons8-wednesday-40.png", "/icons8-thursday-40.png", "/icons8-friday-40.png", "/icons8-saturday-40.png", "/icons8-sunday-40.png", ], }; }, computed: { paramtable() { this.ptable.push( { name: "Format", value: this.format[ this.org.params.find((el) => el.name === "outputformat").value ], }, { name: "Status", value: this.timerstatus[ this.org.params.find((el) => el.name === "status").value ], }, { name: "Location", value: this.org.params.find((el) => el.name === "location").value, }, { name: "Timezone", value: this.tzformat[ this.org.params.find((el) => el.name === "timezone").value ], } ); return this.ptable; }, }, }; </script> <style> .schedtable { text-align: center; margin: 10px auto; max-width: 400px; } .schedule { width: 25%; margin: 0px auto; } .schedulecontainer { margin-top: 40px; } .scheduleheader { width: 25%; margin: 0px auto; font: italic 16px Roboto; background: ghostwhite; } @media screen and (max-width: 600px) { .scheduleheader, .schedule { width: 100%; } } .schedheaders { display: inline-block; margin-left: 3px; } .dayheaders { display: inline-block; margin-left: 25%; } .dayscontainer { display: inline-block; } .dayshow { opacity: 1; width: 100%; } .dayhide { opacity: 0; width: 100%; } .weekdays { display: inline-block; } @media screen and (max-width: 600px) { .weekdays { width: 32px; } } @media screen and (max-width: 600px) { .dayshow, .dayhide { width: 95%; } } .paramitem { display: flex; justify-content: space-between; padding: 1px; } .paramcontainer { display: flex; justify-content: center; } </style> index.html <!doctype html> <html lang="en"><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>NodeRED UI Builder Blank template</title> <meta name="description" content="Node-RED UI Builder - Blank template"> <link rel="icon" href="./images/node-blue.ico"> <link type="text/css" rel="stylesheet" href="./index.css" media="all"> </head><body> <div id="app"></div> <!--<script src="../uibuilder/vendor/socket.io/socket.io.js"></script>--> <!-- Note no leading / --> <script src="./main.js" type="text/javascript"></script> </body></html> 3 Likes thanks for the awesome information. Oh and I forgot. The icons of the weekdays are in the static httpStatic directory of node-red, as defined in node-red's settings.json, which is in home-dir of node-red (in my case /home/xxx/.node-red) httpStatic: '/home/xxx/.node-red/static/', This means references to them in uibuilder are referenced as "/icons8-monday-40.png" And in the main project directory (root directory under which all other files/directories are), to enable you to run "npm run build" and "npm run serve" webpack.config.dev.js (development mode currently) (manifest.json not needed , as per @TotallyInformation ). 'use strict' const { VueLoaderPlugin } = require('vue-loader') const CopyWebpackPlugin = require('copy-webpack-plugin') module.exports = { mode: 'development', entry: ['./src/index.js'], module: { rules: [ { test: /\.vue$/, use: 'vue-loader' }, { test: /\.css$/, use: [ 'vue-style-loader', 'css-loader' ] }, ] }, // @see https://webpack.js.org/plugins/ plugins: [ new VueLoaderPlugin(), // Copies from wherever to the dist folder new CopyWebpackPlugin({ patterns: [ {from: './src/index.html'}, {from: './src/index.css'}, {from: './src/manifest.json'}, ] }), ], } package.json { "name": "uirouter", "version": "1.0.0", "description": "This is about the simplest template you can get for uibuilder.", "main": ".eslintrc.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack --config ./webpack.config.dev.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "bootstrap-vue": "^2.21.2", "engine.io": "^5.2.0", "socket.io-client": "^4.2.0", "vue": "^2.6.14", "vue-router": "^3.5.2", "vuex": "^3.6.2" }, "devDependencies": { "copy-webpack-plugin": "^9.0.1", "css-loader": "^6.2.0", "engine.io-client": "^5.2.0", "vue-loader": "^15.9.8", "vue-style-loader": "^4.1.3", "vue-template-compiler": "^2.6.14", "webpack": "^5.53.0", "webpack-cli": "^4.8.0" } } Home.vue file : <template> <div class="home"> <h3 class="subtitle">Upcoming events </h3> <b-list-group> <b-list-group-item class="eventitems" v-for="(timerevent,i) in timerevents" :key="i" href="#" :variant="timerevent.state"> <div class="d-flex w-100 justify-content-between"> <h4 class="mb-1">{{timerevent.timeperiod}} </h4> <h5>{{displaystatus[timerevent.new_value]}}</h5> <h5>{{timerevent.timer}}</h5> </div> </b-list-group-item> </b-list-group> </div> </template> <script> // @ is an alias to /src export default { name: 'Home', components: {}, data() { return { displaystatus: ['Off','On'] } }, computed: { timerevents () { return this.$store.state.timerevents } } } </script> <style scoped> .subtitle { text-align: center; } .eventitems { width:50%; margin:0px auto; } </style> TimeComp.vue (just a clock) <template> <div> <div id="clock"> <p class="date">{{date}}</p> <p class="time">{{time}}</p> </div> </div> </template> <script> export default { name: 'TimeComp', data() { return { time:"", date:"", week : ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'] } }, methods: { zeroPadding(num, digit) { var zero = ''; for(var i = 0; i < digit; i++) { zero += '0'; } return (zero + num).slice(-digit); }, updateTime() { var cd = new Date(); this.time = this.zeroPadding(cd.getHours(), 2) + ':' + this.zeroPadding(cd.getMinutes(), 2) + ':' + this.zeroPadding(cd.getSeconds(), 2); this.date = this.zeroPadding(cd.getFullYear(), 4) + '-' + this.zeroPadding(cd.getMonth()+1, 2) + '-' + this.zeroPadding(cd.getDate(), 2) + ' ' + this.week[cd.getDay()]; } }, mounted() { var timerID = setInterval(this.updateTime, 1000); } } </script> <style scoped> p { margin: 0; padding: 0; } #clock { font-family: "Share Tech Mono", monospace; text-align: center; color: black; text-shadow: 0 0 20px crimson, 0 0 20px rgba(10, 175, 230, 0); } #clock .time { letter-spacing: 0.05em; font-size: 18px; font-weight: bold; } #clock .date { letter-spacing: 0.1em; font-size: 18px; padding: 20px 0 0 0; font-weight: bold; } Some final comments : Vue2/Vue3 Note that the the router index.js file at the end contains const router = new VueRouter({ //history: createWebHistory(process.env.BASE_URL), mode: 'history', base: '/uirouter', routes }) The base is the name of the URL as in the uibuilder node. This is Vue2 code. Vue3 (should you use that is slightly different). I kindly refer to https://next.router.vuejs.org/guide/migration/ How to make sure a vue route is updated dynamically when you change the params of an active (mounted) route (i.e. a list of users where you want to go to the next user .../user/id) I could find the following solutions 1. <router-view :key="$route.fullPath"/> Do this in the vue file where you have your router-view (obviously). This forces a refresh as your fullPath will contain your param.In my case this is done in the main App.vue as I don't have nested views. 1. watch: { $route(to,from) { this.id = to.params.id this.org = JSON.parse(to.params.org) } }, The above is in the script section of the route vue file that you want to update Nice. Not sure if this helps at all but worth noting that the initial connect msg from Node-RED to your front-end contains a time offset which tells you if the server has an offset from the client (e.g. in a different timezone). You have the common folder if you want to put that under uibuilder's folder structure instead. It does the same thing. One possible advantage of that is that it should use uibuilder's own security rather than Node-RED's - if I can ever work out how to get security working properly that is! But that might be a future benefit anyway. Yes, Vue3 does not seem to me to be anywhere near mature enough yet to warrent its use right now. Thanks @TotallyInformation On the timezone, definitely interesting , I saw that ! At this stage my server and browser are still in same timezone, but that will change. It's on my todo list to use this once I migrate the data entry code to uibuilder ! The timers (of this project) themselves send info to smart switches and valves that are located outside the server and client timezone though. (e.g. a switch in Europe needs to be turned on from 10:00 AM local time...). So in that case the time entered is UTC or close to it ;-). On the common folder, definitely , I learnt something ! I must admit one of the big missing pieces so far in the node-red world is indeed built-in security , but thats another story of course . I am following the progress on that topic ! No complaints though, it's not obvious. In the meantime,I added a sidebar and updated the code, I will edit the above pages very soon. My experiences :slight_smile: (I could be completely wrong) • Bootstrap-vue sidebar : This sidebar is activated with a button that you have to design ,so I am not entirely convinced of the added benefit. And the animation options are very limited (bootstrap 4) • Self made sidebar : Biggest learning was how to code : As a separate route,component or just in main Vue file. At this stage , I've added it as it's own component <SideBar/> . I am always showing the component from a component view , so no <v-if="showSideBar"> stuff. This also made it much simpler as no parent-child component communication/events are needed such as this.$event("close") So, the component is 2 way. The sidebar and a button, the button being used to extract the sidebar. Clicking inside the sidebar makes it go away. There are 3 classes . One for opening with animation, one as opened, and one for closing with oppisite animation. So , I use the :class="sidebarClass"prop to define the class used based on clicking. Here is the new components code <template> <div> <button class="sidebarbutton" @click="opensidebar"> <b-icon font-scale="0.5" icon="list" aria-hidden="true"></b-icon> </button> <div :class="sideBarClass" @click="closesidebar"> <h5 class="sidetitle">Timers</h5> <div class="sidetimer" v-for="(timer, i) in timers" :key="i"> <router-link :to="{ name: 'TimerDetails', params: { id: i } }"> {{ timer.name }} </router-link> </div> </div> </div> </template> <script> export default { data() { return { sideBarClass: "finalsidebarclosed", }; }, methods: { //async closesidebar() { closesidebar() { this.sideBarClass = "finalsidebarclosing"; //await new Promise((r) => setTimeout(r, 2000)); //this.$emit("closebar"); }, opensidebar() { this.sideBarClass = "finalsidebaropen" } }, computed: { timers() { return this.$store.state.timers; }, }, }; </script> <style> /* The side navigation menu */ .sidetitle { padding: 50px 0px 20px 0px; } .finalsidebaropen { text-align: center; font-family: Roboto; margin: 0; padding: 0; left: -300px; width: 200px; background-color: #f1f1f1; height: 100%; overflow: auto; position: absolute; top: 0%; -webkit-animation: slide 1s forwards; animation: slide 1s forwards; } .finalsidebarclosed { margin: 0; padding: 0; left: -300px; width: 200px; background-color: #f1f1f1; height: 100%; overflow: auto; position: absolute; top: 0%; } .finalsidebarclosing { margin: 0; padding: 0; left: 0px; width: 200px; background-color: #f1f1f1; height: 100%; overflow: auto; position: absolute; top: 0%; -webkit-animation: slideclose 0.5s forwards; animation: slideclose 1s forwards; } /* Sidebar links */ .sidetimer a { display: block; color: darkslategray; padding: 4px; text-decoration: none; } /* Active/current link */ .sidetimer a.active { background-color: #04aa6d; color: white; text-decoration: none; } /* Links on mouse-over */ .sidetimer a:hover:not(.active) { background-color: #dc2c3b; color: white; border-radius: 44px; text-decoration: none; } @-webkit-keyframes slideclose { 100% { left: -300px; } } @keyframes slideclose { 100% { left: -300px; } } @-webkit-keyframes slide { 100% { left: 0; } } @keyframes slide { 100% { left: 0; } } .sidebarbutton { position: absolute; background: lightgray; top: 30%; left: -4px; height: 200px; border-radius: 5px; border: none; box-shadow: 2px 2px #eeeeee; } </style> As can be seen an earlier version contained , the following code: async closesidebar() { closesidebar() { this.sideBarClass = "finalsidebarclosing"; await new Promise((r) => setTimeout(r, 2000)); this.$emit("closebar"); }, This was at the time I was using a v-if on the main App.vue to show/hide the component, but I had to use this async function to make sure the animation of closing the sidebar was shown. You could try to use the <transition></transition> element ,but there I encountered issues with a transition showing a slide . (all the examples are related to an opacity animation. ). Voila. that's it for today ! App.vue (updated) <template> <div> <div id="nav"> <router-link :to="{ name: 'Home' }">Home</router-link>| <router-link :to="{ name: 'About' }">About</router-link>| <router-link :to="{ name: 'Timers' }">Timers</router-link> <TimeComp /> </div> <router-view /> <div> <SideBar /> </div> <!--<div class="backdropsection2" @click="offsidebar"></div>--> </div> </template> <script> import uibuilder from "./../../../node_modules/node-red-contrib-uibuilder/front-end/src/uibuilderfe.js"; import TimeComp from "./views/TimeComp.vue"; import SideBar from "./views/SideBar.vue"; export default { data() { return { msgreceived: "", mytimers: [], showSideBar: false, }; }, created() { uibuilder.start(this); }, methods: { opensidebar() { this.showSideBar = true; }, closesidebar() { this.showSideBar = false; }, }, mounted() { const app = this; uibuilder.onChange("msg", function (msg) { app.msgreceived = msg.payload; app.mytimers = msg.original; app.timerevents = msg.timer; app.$store.commit("populate", msg.original); app.$store.commit("populate_timerevents", msg.timer); }); // ---- End of uibuilder.onChange() watcher function ---- // }, components: { TimeComp, SideBar, }, }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } #nav { padding: 30px; text-align: center; font-family: Roboto; font-size: 24px; margin: 10px auto; } #nav a { font-weight: bold; color: #2c3e50; text-decoration: none; padding: 10px; border-radius: 5px; } #nav a.router-link-exact-active { color: white; background: crimson; } .backdropsection2 { height: 100%; } .sidebarbutton { position: absolute; background: lightgray; top: 30%; left: -4px; height: 200px; border-radius: 5px; border: none; box-shadow: 2px 2px #eeeeee; } </style> Oh, I also added a monitor screen in the about menu (which I should rename). This uses a bootstrap-vue progress bar, to show not progress, but status (green/red animated). found this an elegant way iso designing green/red buttons ! About.vue <template> <div class="fade-in-image about"> <div class="monitorcontainer"> <div> <div v-for="(timer, i) in timers" :key="i" class="monitoritem"> <router-link :to="{ name: 'TimerDetails', params: { id: i } }"> <div class="badgeprocesscontainer"> <b-badge class="monitorbadge" variant="secondary">{{ timer.name }}</b-badge> <b-progress class="monitorprogress" :variant="isActive(i)" value="10" max="10" animated ></b-progress> </div> </router-link> </div> </div> </div> <div class="copyright"> Written in Vue,Bootstrap Vue , Vuex ,Vue Router, uIbuilder and Node Red </div> </div> </template> <script> export default { methods: { isActive(key) { if (this.$store.state.timers[key].currentstatus === 0) { return "danger"; } else { return "success"; } }, }, computed: { timers() { return this.$store.state.timers; }, }, }; </script> <style> .about { font-family: Roboto; } .monitorcontainer { display: flex; justify-content: center; } .monitorbadge { vertical-align: super !important; } .monitoritem { padding: 10px 2px 0px 0px; display: flex; justify-content: end; } .copyright { font-family: Roboto; text-align: center; padding-top: 10px; } .monitorprogress { width: 30px; margin-left: 10px; } .monitoritem a:hover { text-decoration:none!important;} .badgeprocesscontainer { display: flex; } </style> image Frankly it is driving me mad! :grinning: I know security from an IT and governance perspective but I am not a security engineer. So getting the process right is proving to be infuriating. But each itteration of my thinking is bringing me closer and I'm hopeful I'll crack the remaining problems soon. In the meantime, it is forcing me to continue to improve the code-base and the next itteration of uibuilder will be a LOT more modular. I'm also introducing a new "Experimental" flag so that in the future, I can include code in live releases that may not be ready for production use but that you might want to trial. I included bootstrap-vue originally because it gives people a pretty much zero touch, minimal boilerplate "nice" layout and style. I do wonder though whether bootstrap is keeping up with the times? Cool, that could be interesting. Not sure if you've seen my experimental components? These were put together to test out some concepts on bridging the gap between the simplicity of Node-RED's Dashboard and the coding requirements of uibuilder. The idea being that you can add a simple component to your HTML and control it from Node-RED just by sending a message with the right data schema. Not sure if that is useful for your sidebar but I am definatly looking for ways to continue to bridge that gap. I'm also starting to prepare the ground for allowing other, 3rd-party nodes to interact with uibuilder. Definately some great ideas in your code, thanks for sharing. I have switched to vuetify (in both uibuilder and standalone projects) It has decent capabilities. The reason I didn't use that was that it needed a build step in order to use it and I wanted to avoid forcing people who already struggle with the concepts to learn a whole bunch of other concepts just to get started. It would be interesting to get a quick write-up of your tooling and workflow though Steve and now that uibuilder accepts external templates, it might be really interesting to have a vuetify template! Templates now cover the whole root folder for a uibuilder instance which means they can include a package.json with a build script and dev dependencies built right in. In a future release, the uibuilder editor panel will recognise common package.json script names and present them in the panel UI to make them easy to run as well. 1 Like
__label__pos
0.990088
Skip to content Permalink Branch: master Find file Copy path Fetching contributors… Cannot retrieve contributors at this time 1107 lines (767 sloc) 47.3 KB Chapter 2. Program Structure This chapter provides details about the basic structural elements of a Go program. Names In Go, the names of functions, variables, constants, types, statement labels, and packages follow a simple rule: a name begins with a letter (anything that Unicode deems a letter) or an underscore and may have any number of additional letters, digits, and underscores. The names are case-sensitive: heapSort and Heapsort are different names. Go has 25 keywords like if and switch that may be used only where the syntax permits; they can't be used as names. | | | -|-|-|- break|default|func|interface|select case|defer|go|map|struct chan|else|goto|package|switch const|fallthrough|if|range|type continue|for|import|return|var In addition, there are about three dozen predeclared names like int and true for built-in constants, types, and functions: | -|- Constants: | true false iota nil Types: | int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr float32 float64 complex128 complex64 bool byte rune string error Functions: | make len cap new append copy close delete complex real imag panic recover These names are not reserved, so you may use them in declarations. Beware of the potential for confusion. Local and exported names * If an entity is: • Declared within a function: it is local to that function. • Declared outside of a function: it is visible in all files of the package to which it belongs. The case of the first letter of a name determines its visibility across package boundaries: • If the name begins with an upper-case letter, it is exported (visible and accessible outside of its own package and may be referred to by other parts of the program), as with Printf in the fmt package. • Package names themselves are always in lower case. Naming convention and style * • There is no limit on name length; • Short names are preferred, especially for local variables with small scopes (i is better than theLoopIndex); • The larger the scope of a name, the longer and more meaningful it should be. • Camel case are used when forming names by combining words, e.g. QuoteRuneToASCII and parseRequestLine (instead of quote_rune_to_ASCII or parse_request_line). • The letters of acronyms and initialisms like ASCII and HTML are always rendered in the same case, so a function might be called htmlEscape, HTMLEscape, or escapeHTML, but not escapeHtml. Declarations A declaration names a program entity and specifies its properties. There are four major kinds of declarations: 1. var (variables) 2. const (constants) 3. type (types) 4. func (functions) This chapter discusses variables and types. Constants are disucssed in Chapter 3, and functions in Chapter 5. Each .go file has declarations in the following order: 1. A package declaration that says what package the file is part of. 2. Any import declarations 3. A sequence of package-level declarations of types, variables, constants, and functions, in any order. For example, the following program declares a constant, a function, and a couple of variables: gopl.io/ch2/boiling/main.go // Boiling prints the boiling point of water. package main import "fmt" const boilingF = 212.0 func main() { var f = boilingF var c = (f - 32) * 5 / 9 fmt.Printf("boiling point = %g°F or %g°C\n", f, c) // Output: // boiling point = 212°F or 100°C } • Each package-level name is visible in all the files of the package. • Local declarations are visible only within the function in which they are declared. A function declaration has a name, a list of parameters an optional list of results (omitted if the function does not return anything), and the function body. Variables A var declaration creates a variable of a particular type, attaches a name to it, and sets its initial value, with the general form: var name type = expression Either the type or the = expression part may be omitted, but not both: • If the type is omitted, it is determined by the initializer expression. • If the expression is omitted, the initial value is the zero value for the type, which is: • 0 for numbers • false for booleans • "" for strings • nil for interfaces and reference types (slice, pointer, map, channel, function). The zero value of an aggregate type like an array or a struct has the zero value of all of its elements or fields. The zero-value mechanism ensures that a variable always holds a well-defined value of its type; in Go there is no such thing as an uninitialized variable. This simplifies code and often ensures sensible behavior of boundary conditions without extra work. For example, var s string fmt.Println(s) // "" Go programmers often go to some effort to make the zero value of a more complicated type meaningful, so that variables begin life in a useful state. It is possible to declare and optionally initialize a set of variables in a single declaration, with a matching list of expressions. Omitting the type allows declaration of multiple variables of different types: var i, j, k int // int, int, int var b, f, s = true, 2.3, "four" // bool, float64, string • Initializers may be literal values or arbitrary expressions. • Package-level variables are initialized before main begins (Section 2.6.2). • Local variables are initialized as their declarations are encountered during function execution. A set of variables can also be initialized by calling a function that returns multiple values: var f, err = os.Open(name) // os.Open returns a file and an error Short Variable Declarations Within a function, an alternate form called a short variable declaration may be used to declare and initialize local variables. It takes the form name := expression, and the type of name is determined by the type of expression. For exmaple (Animated GIFs), When to use short variable declaration and var declaration * • Short variable declarations are used to declare and initialize the majority of local variables, for brevity and flexibility. • A var declaration tends to be reserved for: • Local variables that need an explicit type that differs from that of the initializer expression; • Local variables when they will be assigned a value later and its initial value is unimportant. i := 100 // an int var boiling float64 = 100 // a float64 var names []string var err error var p Point As with var declarations, multiple variables may be declared and initialized in the same short variable declaration: i, j := 0, 1 However, declarations with multiple initializer expressions should be used only when they help readability, such as for short and natural groupings like the initialization part of a for loop. Keep in mind that := is a declaration, whereas = is an assignment. A multi-variable declaration should not be confused with a tuple assignment, in which each variable on the left-hand side is assigned the corresponding value from the right-hand side: i, j = j, i // swap values of i and j Like var declarations, short variable declarations may be used for calls to functions like os.Open that return two or more values: f, err := os.Open(name) if err != nil { return err } // ...use f... f.Close() One subtle but important point * A short variable declaration does not necessarily declare all the variables on its left-hand side. If some of them were already declared in the same lexical block , then the short variable declaration acts like an assignment to those variables. For example, in, err := os.Open(infile) // ... out, err := os.Create(outfile) In the above code: • The first statement declares both in and err. • The second declares out but only assigns a value to the existing err variable. A short variable declaration must declare at least one new variable. Therefore, the following code will not compile: f, err := os.Open(infile) // ... f, err := os.Create(outfile) // compile error: no new variables The fix is to use an ordinary assignment for the second statement. A short variable declaration acts like an assignment only to variables that were already declared in the same lexical block; declarations in an outer block are ignored. Pointers A variable is a piece of storage containing a value. • Variables created by declarations are identified by a name, such as x • Many other variables are identified only by expressions like x[i] or x.f. All these expressions read the value of a variable, except when they appear on the lefthand side of an assignment, in which case a new value is assigned to the variable. A pointer value is the address of a variable. A pointer is thus the location at which a value is stored. Not every value has an address, but every variable does. With a pointer, we can read or update the value of a variable indirectly, without using or even knowing the name of the variable, if indeed it has a name. Pointer type (*type) and address-of (&) operators * If a variable is declared var x int, the expression &x ("address of x") yields a pointer to an integer variable (a value of type *int, which is pronounced "pointer to int"). If this value is called p, we say "p points to x", or equivalently "p contains the address of x". The variable to which p points is written *p. The expression *p yields the value of that variable, an int, but since *p denotes a variable, it may also appear on the left-hand side of an assignment, in which case the assignment updates the variable. x := 1 p := &x // p, of type *int, points to x fmt.Println(*p) // "1" *p = 2 // equivalent to x = 2 fmt.Println(x) // "2" Each component of a variable of aggregate type: a field of a struct or an element of an array, is also a variable and thus has an address too. Variables are sometimes described as addressable values. Expressions that denote variables are the only expressions to which the address-of operator & may be applied. Comparing pointers * The zero value for a pointer of any type is nil. The test p != nil is true if p points to a variable. Pointers are comparable; two pointers are equal if and only if they point to the same variable or both are nil. var x, y int fmt.Println(&x == &x, &x == &y, &x == nil) // "true false false" It is perfectly safe for a function to return the address of a local variable. For example: var p = f() func f() *int { v := 1 return &v } The local variable v created by this particular call to f will remain in existence even after the call has returned, and the pointer p will still refer to it. Each call of f returns a distinct value: fmt.Println(f() == f()) // "false" Passing a pointer argument to a function makes it possible for the function to update the variable that was indirectly passed. For example: func incr(p *int) int { *p++ // increments what p points to; does not change p return *p } v := 1 incr(&v) // side effect: v is now 2 fmt.Println(incr(&v)) // "3" (and v is 3) Pointer aliasing * Each time we take the address of a variable or copy a pointer, we create new aliases or ways to identify the same variable. For example, *p is an alias for v. Pointer aliasing is useful because it allows us to access a variable without using its name, but this is a double-edged sword: to find all the statements that access a variable, we have to know all its aliases. Aliasing also occurs when we copy values of other reference types like slices, maps, and channels, and even structs, arrays, and interfaces that contain these types. Pointer and the flag package Pointers are key to the flag package, which uses a program's command-line arguments to set the values of certain variables for the entire program. To illustrate, this variation on the earlier echo command takes two optional flags: • -n causes echo to omit the trailing newline that would normally be printed; • -s sep causes it to separate the output arguments by the contents of the string sep instead of the default single space. gopl.io/ch2/echo4/main.go // Echo4 prints its command-line arguments. package main import ( "flag" "fmt" "strings" ) var n = flag.Bool("n", false, "omit trailing newline") var sep = flag.String("s", " ", "separator") func main() { flag.Parse() fmt.Print(strings.Join(flag.Args(), *sep)) if !*n { fmt.Println() } } The function flag.Bool creates a new flag variable of type bool. It takes three arguments: • The name of the flag ("n"), • The variable's default value (false), • A message that will be printed if the user provides an invalid argument, an invalid flag, or -h or -help. This is similar to flag.String. The variables sep and n are pointers to the flag variables, which must be accessed indirectly as *sep and *n. When the program is run, it must call flag.Parse before the flags are used, to update the flag variables from their default values. The non-flag arguments are available from flag.Args() as a slice of strings. If flag.Parse encounters an error, it prints a usage message and calls os.Exit(2) to terminate the program. The following are some test results: $ go build gopl.io/ch2/echo4 $ ./echo4 a bc def a bc def $ ./echo4 -s / a bc def a/bc/def $ ./echo4 -n a bc def a bc def$ $ ./echo4 -help Usage of ./echo4: -n omit trailing newline -s string separator (default " ") The new Function Another way to create a variable is to use the built-in function new. The expression new(T) creates an unnamed variable (anonymous variable) of type T, initializes it to the zero value of T, and returns its address, which is a value of type *T. p := new(int) // p, of type *int, points to an unnamed int variable fmt.Println(*p) // "0" *p = 2 // sets the unnamed int to 2 fmt.Println(*p) // "2" A variable created with new is no different from an ordinary local variable whose address is taken, except that there's no need to invent (and declare) a dummy name, and we can use new(T) in an expression. Thus new is only a syntactic convenience, not a fundamental notion. The two newInt functions below have identical behaviors: func newInt() *int { return new(int) } func newInt() *int { var dummy int return &dummy } Each call to new returns a distinct variable with a unique address: p := new(int) q := new(int) fmt.Println(p == q) // "false" There is one exception to this rule: two variables whose type carries no information and is therefore of size zero, such as struct{} or [0]int, may have the same address (depending on the implementation). The new function is relatively rarely used because the most common unnamed variables are of struct types, for which the struct literal syntax (Section 4.4.1) is more flexible. Since new is a predeclared function, not a keyword, it's possible to redefine the name for something else within a function, for example: func delta(old, new int) int { return new - old } Within delta, the built-in new function is unavailable. Lifetime of Variables The lifetime of a variable is the interval of time during which it exists as the program executes. • The lifetime of a package-level variable is the entire execution of the program. • Local variables have dynamic lifetimes: a new instance is created each time the declaration statement is executed, and the variable lives on until it becomes unreachable, at which point its storage may be recycled. • Function parameters and results are also local variables; they are created each time their enclosing function is called. For example, in this excerpt from the Lissajous program of Section 1.4: for t := 0.0; t < cycles*2*math.Pi; t += res { x := math.Sin(t) y := math.Sin(t*freq + phase) img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5), blackIndex) } • The variable t is created each time the for loop begins. • New variables x and y are created on each iteration of the loop. How does the garbage collector know that a variable's storage can be reclaimed? * The basic idea is that every package-level variable, and every local variable of each currently active function, can potentially be the start or root of a path to the variable in question, following pointers and other kinds of references that ultimately lead to the variable. If no such path exists, the variable has become unreachable, so it can no longer affect the rest of the computation. Because the lifetime of a variable is determined only by whether or not it is reachable, a local variable may outlive a single iteration of the enclosing loop. It may continue to exist even after its enclosing function has returned. Heap or stack? * A compiler may choose to allocate local variables on the heap or on the stack, but this choice is not determined by whether var or new was used to declare the variable. var global *int func f() { var x int x = 1 global = &x } func g() { y := new(int) *y = 1 } In the above code: • x must be heap-allocated because it is still reachable from the variable global after f has returned, despite being declared as a local variable; we say x escapes from f. • Conversely, when g returns, the variable *y becomes unreachable and can be recycled. Since *y does not escape from g, it's safe for the compiler to allocate *y on the stack, even though it was allocated with new. In any case, the notion of escaping is not something that you need to worry about in order to write correct code, though it's good to keep in mind during performance optimization, since each variable that escapes requires an extra memory allocation. Thoughts on garbage collection * Garbage collection is a tremendous help in writing correct programs, but it does not relieve you of the burden of thinking about memory. You don't need to explicitly allocate and free memory, but to write efficient programs you still need to be aware of the lifetime of variables. For example, keeping unnecessary pointers to short-lived objects within long-lived objects, especially global variables, will prevent the garbage collector from reclaiming the short-lived objects. Assignments The value held by a variable is updated by an assignment statement. In its simplest form, an assignment has a variable on the left of the = sign and an expression on the right: x = 1 // named variable *p = true // indirect variable person.name = "bob" // struct field count[x] = count[x] * scale // array or slice or map element Each of the arithmetic and bitwise binary operators has a corresponding assignment operator, which allows the last statement to be rewritten like count[x] *= scale. This saves us from having to repeat (and re-evaluate) the expression for the variable. Numeric variables can also be incremented and decremented by ++ and -- statements: v := 1 v++ // same as v = v + 1; v becomes 2 v-- // same as v = v - 1; v becomes 1 again Tuple Assignment Tuple assignment allows several variables to be assigned at once. All of the right-hand side expressions are evaluated before any of the variables are updated, making this form most useful when some of the variables appear on both sides of the assignment. Tple assignment can be used in the following scenarios and examples: Swapping the values of two variables: x, y = y, x a[i], a[j] = a[j], a[i] Computing the greatest common divisor (GCD) of two integers: func gcd(x, y int) int { for y != 0 { x, y = y, x%y } return x } Computing the n-th Fibonacci number iteratively: func fib(n int) int { x, y := 0, 1 for i := 0; i < n; i++ { x, y = y, x+y } return x } Tuple assignment can also make a sequence of trivial assignments more compact: i, j, k = 2, 3, 5 However, as a matter of style, avoid the tuple form if the expressions are complex, since a sequence of separate statements is easier to read. Expressions that produce multiple results * Certain expressions produce several values. When such a call is used in an assignment statement, the left-hand side must have as many variables as the function has results. For example, a function call with multiple results: f, err = os.Open("foo.txt") // function call returns two values Often, functions use these additional results to indicate some kind of error by returning either of the following: • An error (as in the call to os.Open) • A bool, usually called ok. There are three operators that sometimes also behave this way: • Map lookup (§4.3) • Type assertion (§7.10) • Channel receive (§8.4.2) When any of the above three appears in an assignment in which two results are expected, each produces an additional boolean result: v, ok = m[key] // map lookup v, ok = x.(T) // type assertion v, ok = <-ch // channel receive As with variable declarations, we can assign unwanted values to the blank identifier: _, err = io.Copy(dst, src) // discard byte count _, ok = x.(T) // check type but discard result Assignability Assignment statements are an explicit form of assignment. There are many places in a program where an assignment occurs implicitly: • A function call implicitly assigns the argument values to the corresponding parameter variables; • A return statement implicitly assigns the return operands to the corresponding result variables; • A literal expression for a composite type such as this slice: medals := []string{"gold", "silver", "bronze"} This implicitly assign each element, as if written like this: medals[0] = "gold" medals[1] = "silver" medals[2] = "bronze" This implicit assignment also applies to the elements of maps and channels. Assignability rule * An assignment, explicit or implicit, is always legal if the left-hand side (the variable) and the right-hand side (the value) have the same type. More generally, the assignment is legal only if the value is assignable to the type of the variable. The rule for assignability has cases for various types. Relevant cases will be explained when each new type is introduced. For the types discussed so far, the rules are simple: • The types must exactly match. • nil may be assigned to any variable of interface or reference type. Constants have more flexible rules for assignability that avoid the need for most explicit conversions. Assignability and comparability * Whether two values may be compared with == and != is related to assignability: in any comparison, the first operand must be assignable to the type of the second operand, or vice versa. As with assignability, relevant cases for comparability will be explained when each new type is introduced. Type Declarations The type of a variable or expression defines the characteristics of the values it may take on, such as: • Size. • How they are represented internally. • Intrinsic operations that can be performed on them. • Methods associated with them. Variables can share the same representation but signify very different concepts. [p39] A type declaration defines a new named type that has the same underlying type as an existing type. The named type provides a way to separate different and perhaps incompatible uses of the underlying type so that they can't be mixed unintentionally. type name underlying-type Type declarations most often appear at package level, where the named type is visible throughout the package; if the name is exported (it starts with an upper-case letter), it's accessible from other packages as well. Example of type declarations: temperature scales * The following example turns different temperature scales into different types: gopl.io/ch2/tempconv0/celsius.go // Package tempconv performs Celsius and Fahrenheit temperature computations. package tempconv import "fmt" type Celsius float64 type Fahrenheit float64 const ( AbsoluteZeroC Celsius = -273.15 FreezingC Celsius = 0 BoilingC Celsius = 100 ) func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) } func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) } This package defines two types, Celsius and Fahrenheit for the two units of temperature. Even though both have the same underlying type, float64, they are not the same type, so they cannot be compared or combined in arithmetic expressions. Defining two types avoids errors like inadvertently combining temperatures in the two different scales; an explicit type conversion like Celsius(t) or Fahrenheit(t) is required to convert from a float64. • Celsius(t) and Fahrenheit(t) are conversions, not function calls. They don't change the value or representation in any way, but they make the change of meaning explicit. • The functions CToF and FToC convert between the two scales; they do return different values. Type conversion * For every type T, there is a corresponding conversion operation T(x) that converts the value x to type T. A conversion from one type to another is allowed if any of the following holds: • Both have the same underlying type. • Both are unnamed pointer types that point to variables of the same underlying type. These conversions change the type but not the representation of the value. If x is assignable to T, a conversion is permitted but is usually redundant. Conversions are also allowed in the following cases: • Between numeric types • Between string and some slice types (discussed in Chapter 3). These conversions may change the representation of the value. For instance, converting a floating-point number to an integer discards any fractional part, and converting a string to a []byte slice allocates a copy of the string data. In any case, a conversion never fails at run time. The underlying type of a named type determines its structure and representation, and also the set of intrinsic operations it supports, which are the same as if the underlying type had been used directly. That means that arithmetic operators work the same for Celsius and Fahrenheit as they do for float64. fmt.Printf("%g\n", BoilingC-FreezingC) // "100" °C boilingF := CToF(BoilingC) fmt.Printf("%g\n", boilingF-CToF(FreezingC)) // "180" °F fmt.Printf("%g\n", boilingF-FreezingC) // compile error: type mismatch Comparison operators like == and < can also be used to compare a value of a named type to another of the same type, or to a value of the underlying type. But two values of different named types cannot be compared directly: var c Celsius var f Fahrenheit fmt.Println(c == 0) // "true" fmt.Println(f >= 0) // "true" fmt.Println(c == f) // compile error: type mismatch fmt.Println(c == Celsius(f)) // "true"! Note that in the last case, the type conversion Celsius(f) does not change the value of its argument, just its type. The test is true because c and f are both zero. Advantages of named types * A named type provides notational convenience if it helps avoid writing out complex types over and over again. The advantage is small when the underlying type is simple like float64, but big for complicated types (detailed when discussing structs). Named types also make it possible to define new behaviors for values of the type. These behaviors are expressed as a set of functions associated with the type, called the type's methods. Methods are discussed in Chapter 6. The following example of the String method gives a taste the mechanism. The declaration below, in which the Celsius parameter c appears before the function name, associates with the Celsius type a method named String that returns c's numeric value followed by °C: func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) } The String method * Many types declare a String method of this form because it controls how values of the type appear when printed as a string by the fmt package, discussed in Section 7.1. c := FToC(212.0) fmt.Println(c.String()) // "100°C" fmt.Printf("%v\n", c) // "100°C"; no need to call String explicitly fmt.Printf("%s\n", c) // "100°C" fmt.Println(c) // "100°C" fmt.Printf("%g\n", c) // "100"; does not call String fmt.Println(float64(c)) // "100"; does not call String Packages and Files Similar to libraries or modules in other languages, packages in Go supports modularity, encapsulation, separate compilation, and reuse. The source code for a package resides in one or more .go files, usually in a directory whose name ends with the import path; for instance, the files of the gopl.io/ch1/helloworld package are stored in directory $GOPATH/src/gopl.io/ch1/helloworld. • Each package serves as a separate name space for its declarations. For example, within the image package the identifier Decode refers to a different function than does the same identifier in the unicode/utf16 package. To refer to a function from outside its package, we must qualify the identifier to make explicit whether we mean image.Decode or utf16.Decode. • Packages hides information by controlling which names are visible outside the package, or exported. In Go, exported identifiers start with an upper-case letter. Suppose we want to make our temperature conversion software available to the Go community as a new package. Create a package called gopl.io/ch2/tempconv, a variation on the previous example. The package itself is stored in two files to show how declarations in separate files of a package are accessed. The declarations of the types, their constants, and their methods are in tempconv.go: gopl.io/ch2/tempconv/tempconv.go package tempconv import "fmt" type Celsius float64 type Fahrenheit float64 const ( AbsoluteZeroC Celsius = -273.15 FreezingC Celsius = 0 BoilingC Celsius = 100 ) func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) } func (f Fahrenheit) String() string { return fmt.Sprintf("%g°F", f) } The conversion functions are in conv.go: gopl.io/ch2/tempconv/conv.go // Package tempconv performs Celsius and Fahrenheit conversions. package tempconv // CToF converts a Celsius temperature to Fahrenheit. func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) } // FToC converts a Fahrenheit temperature to Celsius. func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) } Each file starts with a package declaration that defines the package name. When the package is imported, its members are referred to as tempconv.CToF and so on. Package-level names declared in one file of a package are visible to all the other files of the package, as if the source code were all in a single file. [p42] To convert a Celsius temperature to Fahrenheit in a package that imports gopl.io/ch2/tempconv, we can write the following code: fmt.Println(tempconv.CToF(tempconv.BoilingC)) // "212°F" Doc comment of a package * The doc comment (Section 10.7.4) immediately preceding the package declaration documents the package as a whole. • Conventionally, it should start with a summary sentence in the style illustrated. • Only one file in each package should have a package doc comment. • Extensive doc comments are often placed in a file of their own, conventionally called doc.go. Imports Import path * Every package within a Go program is identified by a unique string called its import path, which appears in an import declaration like gopl.io/ch2/tempconv. The language specification doesn't define where these strings come from or what they mean; it's up to the tools to interpret them. When using the go tool (Chapter 10), an import path denotes a directory containing Go source files that make up the package. Package name * In addition to its import path, each package has a package name, which is the short buy not necessarily unique name that appears in its package declaration. By convention, a package's name matches the last segment of its import path. For example, the package name of gopl.io/ch2/tempconv is tempconv. To use gopl.io/ch2/tempconv, we must import it: gopl.io/ch2/cf/main.go // Cf converts its numeric argument to Celsius and Fahrenheit. package main import ( "fmt" "os" "strconv" "gopl.io/ch2/tempconv" ) func main() { for _, arg := range os.Args[1:] { t, err := strconv.ParseFloat(arg, 64) if err != nil { fmt.Fprintf(os.Stderr, "cf: %v\n", err) os.Exit(1) } f := tempconv.Fahrenheit(t) c := tempconv.Celsius(t) fmt.Printf("%s = %s, %s = %s\n", f, tempconv.FToC(f), c, tempconv.CToF(c)) } } The import declaration binds a short name to the imported package that may be used to refer to its contents throughout the file. The import the above code enables us refer to names within gopl.io/ch2/tempconv by using a qualified identifier like tempconv.CToF. By default, the short name is the package name (tempconv in this case), but an import declaration may specify an alternative name to avoid a conflict (Section 10.3). The cf program converts a single numeric command-line argument to its value in both Celsius and Fahrenheit: $ go build gopl.io/ch2/cf $ ./cf 32 32°F = 0°C, 32°C = 89.6°F $ ./cf 212 212°F = 100°C, 212°C = 413.6°F $ ./cf -40 -40°F = -40°C, -40°C = -40°F It is an error to import a package and then not refer to it. This check helps eliminate dependencies that become unnecessary as the code evolves, although it can be a nuisance during debugging. [p44] goimports * The golang.org/x/tools/cmd/goimports tool automatically inserts and removes packages from the import declaration as necessary; most editors can be configured to run goimports each time you save a file. Like the gofmt tool, it also pretty-prints Go source files in the canonical format. Package Initialization Package initialization begins by initializing package-level variables in the order in which they are declared, except that dependencies are resolved first: var a = b + c // a initialized third, to 3 var b = f() // b initialized second, to 2, by calling f var c = 1 // c initialized first, to 1 func f() int { return c + 1 } If the package has multiple .go files, they are sorted by the go tool, given to the compiler and initialized in this order. An variable declared at package level starts life with the value of its optional initializer expression. However, for some variables, like tables of data, it's not easy to set their initial values using initializer expressions, in which case the init function mechanism may be simpler. A file may contain any number of init functions like the following: func init() { /* ... */ } Except that init functions can't be called or referenced, they are normal functions. Within each file, init functions are automatically executed when the program starts, in the order in which they are declared. • One package is initialized at a time, in the order of imports in the program, dependencies first. • For example, if package p imports q, then q is fully initialized before p's initialization begins. • Initialization proceeds from the bottom up; the main package is the last to be initialized. All packages are fully initialized before the application's main function begins. The package below defines a function PopCount that returns the number of set bits (bits whose value is 1) in a uint64 value, which is called its population count. It uses an init function to precompute a table of results, pc, for each possible 8-bit value so that the PopCount function needn't take 64 steps but can just return the sum of eight table lookups. (This is definitely not the fastest algorithm for counting bits, but it's convenient for illustrating init functions, and for showing how to precompute a table of values, which is often a useful programming technique.) gopl.io/ch2/popcount package popcount // pc[i] is the population count of i. var pc [256]byte func init() { for i := range pc { pc[i] = pc[i/2] + byte(i&1) } } // PopCount returns the population count (number of set bits) of x. func PopCount(x uint64) int { return int(pc[byte(x>>(0*8))] + pc[byte(x>>(1*8))] + pc[byte(x>>(2*8))] + pc[byte(x>>(3*8))] + pc[byte(x>>(4*8))] + pc[byte(x>>(5*8))] + pc[byte(x>>(6*8))] + pc[byte(x>>(7*8))]) } Note that in the above code the range loop in init uses only the index, since the value is not need. The loop could also have been written as: for i, _ := range pc { Scope A declaration associates a name with a program entity, such as a function or a variable. The scope of a declaration is the part of the source code where a use of the declared name refers to that declaration. Scope vs. Lifetime * Don't confuse scope with lifetime. • The scope of a declaration is a region of the program text; it is a compile-time property. • The lifetime of a variable is the range of time during execution when the variable can be referred to by other parts of the program; it is a run-time property. Lexical Blocks * Syntactic Block and Lexical Block * • A syntactic block (or block) is a sequence of statements enclosed in braces (e.g. function, loop). A name declared inside a syntactic block is not visible outside that block. The block encloses its declarations and determines their scope. • A lexical block does not surround declarations with braces. It is generalized from the notion of syntactic blocks. Each of the following elements has a lexical block: • The entire source code, called universe block • Each package • Each file • Each for, if, and switch statement • Each case in a switch or select statement • Each explicit syntactic block Determining Scopes * The lexical block of a declaration determines its scope. • Entire source code. The declarations of built-in types, functions, and constants (e.g. int, len and true) are in the universe block. They can be referred to throughout the entire program. • Package. Declarations outside any function (i.e. at package level) can be referred to from any file in the same package. • File. Imported packages (e.g. fmt in the tempconv example) are declared at the file level, so they can be referred to from the same file, but not from another file in the same package without another import. • Local. Many declarations (e.g. the variable c in the tempconv.CToF function) are local, so they can be referred to only from within the same function or a part of it. The scope of a control-flow label, as used by break, continue, and goto statements, is the entire enclosing function. Multiple declarations of the same name * A program may contain multiple declarations of the same name as long as each declaration is in a different lexical block. For example: • You can declare a local variable with the same name as a package-level variable. • As shown in Section 2.3.3, you can declare a function parameter called new, even though a function of this name is predeclared in the universe block. However, this should not be overdone. The larger the scope of the redeclaration, the more likely you are to surprise the reader. When the compiler encounters a reference to a name, it looks for a declaration, starting with the innermost enclosing lexical block, up to the universe block: • If the compiler finds no declaration, it reports an "undeclared name" error. • If a name is declared in both an outer block and an inner block, the inner declaration will be found first. In that case, the inner declaration is said to shadow (or hide) the outer one, making it inaccessible. For example: func f() {} var g = "g" func main() { f := "f" fmt.Println(f) // "f"; local var f shadows package-level func f fmt.Println(g) // "g"; package-level var fmt.Println(h) // compile error: undefined: h } Within a function, lexical blocks may be nested to arbitrary depth, so one local declaration can shadow another. Most blocks are created by control-flow constructs like if statements and for loops. The program below has three different variables called x because each declaration appears in a different lexical block. func main() { x := "hello!" for i := 0; i < len(x); i++ { x := x[i] if x != '!' { x := x + 'A' - 'a' fmt.Printf("%c", x) // "HELLO" (one letter per iteration) } } } The expressions x[i] and x + 'A' - 'a' each refer to a declaration of x from an outer block. (Note that the latter expression is not equivalent to unicode.ToUpper). This is explained in detail below. Explicit and Implicit Blocks * Not all lexical blocks correspond to explicit brace-delimited sequences of statements; some of them also correspond to implicit blocks. In the previous example, the for loop above creates two lexical blocks: • The explicit block for the loop body. • An implicit block that additionally encloses the variables (e.g. i) declared by the initialization clause. The scope of a variable declared in the implicit block is the condition, post-statement (i++), and body of the for statement. The example below also has three variables named x, each declared in a different block: one in the function body, one in the for statement's block, and one in the loop body; but only two of the blocks are explicit: func main() { x := "hello" for _, x := range x { x := x + 'A' - 'a' fmt.Printf("%c", x) // "HELLO" (one letter per iteration) } } Like for loops, if statements and switch statements also create implicit blocks in addition to their body blocks. The code in the following if-else chain shows the scope of x and y: if x := f(); x == 0 { fmt.Println(x) } else if y := g(x); x == y { fmt.Println(x, y) } else { fmt.Println(x, y) } fmt.Println(x, y) // compile error: x and y are not visible here The second if statement is nested within the first, so variables declared within the first if statement's initializer are visible within the second. Similar rules apply to each case of a switch statement: there is a block for the condition and a block for each case body. At the package level, the order in which declarations appear has no effect on their scope, so a declaration may refer to itself or to another that follows it. This enables us to declare recursive or mutually recursive types and functions. However, the compiler will report an error if a constant or variable declaration refers to itself. Examples: if statement * In the following program: if f, err := os.Open(fname); err != nil { // compile error: unused: f return err } f.ReadByte() // compile error: undefined f f.Close() // compile error: undefined f The scope of f is just the if statement, so f is not accessible to the statements that follow, resulting in compiler errors: "undefined f". Depending on the compiler, you may get an additional error reporting that the local variable f was never used. Thus it is often necessary to declare f before the condition so that it is accessible after: f, err := os.Open(fname) if err != nil { return err } f.ReadByte() f.Close() You may be tempted to avoid declaring f and err in the outer block by moving the calls to ReadByte and Close inside an else block: if f, err := os.Open(fname); err != nil { return err } else { // f and err are visible here too f.ReadByte() f.Close() } However, the normal practice in Go is to deal with the error in the if block and then return, so that the successful execution path is not indented. Short variable declarations and scope * Short variable declarations require awareness of scope. The following program starts by obtaining its current working directory and saving it in a package-level variable. This could be done by calling os.Getwd in function main, but it might be better to separate this concern from the primary logic, especially if failing to get the directory is a fatal error. The function log.Fatalf prints a message and calls os.Exit(1). var cwd string func init() { cwd, err := os.Getwd() // compile error: unused: cwd if err != nil { log.Fatalf("os.Getwd failed: %v", err) } } The := statement declares cwd and err as local variables. The inner declaration of cwd makes the outer one inaccessible, so the statement does not update the package-level cwd variable as intended. Current Go compilers detect that the local cwd variable is never used and report this as an error, but they are not strictly required to perform this check. A minor change (as shown below), such as the addition of a logging statement that refers to the local cwd as shown below, would defeat the check. var cwd string func init() { cwd, err := os.Getwd() // NOTE: wrong! if err != nil { log.Fatalf("os.Getwd failed: %v", err) } log.Printf("Working directory = %s", cwd) } The global cwd variable remains uninitialized, and the apparently normal log output obfuscates the bug. There are a number of ways to deal with this potential problem. The most direct is to avoid := by declaring err in a separate var declaration: var cwd string func init() { var err error cwd, err = os.Getwd() if err != nil { log.Fatalf("os.Getwd failed: %v", err) } } Doubts and Solutions Verbatim p32 on short variable declaration A short variable declaration acts like an assignment only to variables that were already declared in the same lexical block; declarations in an outer block are ignored. Question: What does "declarations in an outer block are ignored" mean? p45 on init function Question: What exact algorithm does PopCount use? It seems different from the Hamming weight algorithm on Wikipedia. You can’t perform that action at this time.
__label__pos
0.956466
The ImageToolbox Gold API Reference *********************************** Version: 3.0 December 2000 The ImageToolbox Gold (ITBG30.DLL) supports all the functions found in the Silver version, plus many additional features that dramatically enhance the file format support. All the image conversion features found in this product decompress the image data then recompress the image in the output format once the selected changes to the image have been applied. When compared to the functions in the ImageToolbox Silver these conversions require far more computing for the image manipulation, and as a result take longer to process each image (but are still very fast). We call these image conversion operations "translations" to indicate that the image data is modified while being processed. As with the ImageToolbox Silver, running the conversions on a computer with a fast hard drive is very desirable. Running this version of the Toolbox on a fast processor will make make much more difference in the processing speed per page than with the ImageToolbox Silver due to the extra image processing required. This is especially true when changing image resolutions. ---------------------------------------------------------------------- Files Included In The ImageToolbox Gold --------------------------------------- The ImageToolbox Gold has two runtime DLLs. Both ITBG30.DLL and the support file ITBG3IX.DLL should normally reside in the same directory as the application that will be calling the API functions. When creating your application, the include file ITBDEFS.H provides all function prototypes and error return code definitions for C language development. For Visual Basic developers, the file ITBGDEFS.BAS can be included in the project instead to provide the same information. NOTE: The names of the DLL files have changed from earlier versions. If you are upgrading from an earlier version of the Toolbox, please delete your old Toolbox files and replace them with the files included in this package. Your code must be rebuilt to use these changed filenames. ---------------------------------------------------------------------- Translation Functions Included In The ImageToolbox Gold ------------------------------------------------------- All the ImageToolbox Gold APIs that translate the image use "Trans" in the function name instead of "Cnv" used in the Silver API function names. These functions all return the error ERR_FUNCTIONNOTSUPPORTED if used in the ImageToolbox Silver product. ---------------------------------------------------------------------- Environment Variables Used -------------------------- Some translations create an intermediate temporary file which is deleted after the final output file is written. The directory to use for temporary files is determined by examining the environment setting of TEMP. If there is no TEMP setting, the TMP setting is used. If there is no TMP setting, the root of drive C: is used (C:\). It is a good idea to use a fast hard drive for the temporary directory. The maximum space required for the temporary file is the size of the largest image that will be created in the conversions. ********************************************************************** *** UPGRADE FUNCTIONS FROM IMAGETOOLBOX SILVER THAT INCLUDE IMAGE TRANSLATION SUPPORT *** BACKGROUND AND IMPLEMENTATION NOTES: These functions are upgrades for the functions found in the ImageToolbox Silver. The functions are similarly named (with "Trans" replacing "Cnv" in the Silver product) and have extra parameters to select the image compression method desired. Using these functions is the fastest method to upgrade from Silver to Gold. int ITBAPI ITB_TransModca2Tif(char FAR *lpModcaFileSpec, int FilesToConvert, char FAR *lpTiffFileBase, int NamingMethod, int NameDigits, int ModcaCompression, int TiffCompression) Description: Translate a MO:DCA file to a TIFF file using a different compression format. If the MO:DCA and TIFF files both use G4 compression, the "Cnv" function is invoked instead. Parameters: lpModcaFileSpec Far pointer to a null terminated string containing a fully qualified path to the MO:DCA file to be translated. FilesToConvert Which pages in the file to translate. 1 = translate the first image only 2 = translate all images in the MO:DCA file to separate TIFF files 3 = translate all images in the MO:DCA file to a single TIFF file lpTiffFileBase The base of a fully qualified path to the TIFF file(s) to be written. The way this filespec is used is controlled by the NamingMethod. NamingMethod The output file naming strategy. These values determine how the lpTiffFileBase parameter is used. 1 = use the name as specified in lpTiffFileBase 2 = append numeric extensions to each file starting with ".001" 3 = append a right justified numeric then ".TIF". The length of the numeric string is controlled by NameDigits. The extension can be changed using the API ITB_SetTiffExtension(). NameDigits Specifies how many digits are appended to the filename base when NamingMethod 3 is used. The value is ignored if NamingMethod is not set to 3. ModcaCompression Compression in use in the source MO:DCA file. TRANS_MODCA_G4 = Group 4 compression (this is usually the format) TRANS_MODCA_MMR = IBM MMR format (may not be supported by all versions of the Toolbox). TiffCompression Compression to use for the output TIFF file. TRANS_TIFF_G4 = Group 4 compression TRANS_TIFF_G3 = Group 3 compression TRANS_TIFF_UNCOMPRESSED = uncompressed raw bitmap Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H Implementation Notes: * If the input MO:DCA file compression used is unknown, or if you want to force the image decompress/recompress operation, set the value ModcaCompression = TRANS_MODCA_MMR. This will disable the conversion optimizations built into to the Toolbox and force the slower translation. int ITBAPI ITB_TransTif2Modca(char FAR *lpTiffFileSpec, int FilesToConvert, char FAR *lpModcaFileBase, int NamingMethod, int NameDigits, int ModcaFormat, int TiffCompression) Description: Translate a TIFF file to a MO:DCA file using a different compression format. If the TIFF and MO:DCA files both use G4 compression, the "Cnv" function is invoked instead. Parameters: lpTiffFileSpec Far pointer to a null terminated string containing a fully qualified path to the TIFF file to be translated. FilesToConvert Which pages in the file to translate. 1 = translate the first image only 2 = translate all images in the TIFF file to separate MO:DCA files 3 = translate all images in the TIFF file to a single MO:DCA file lpModcaFileBase The base of a fully qualified path to the MO:DCA file(s) to be written. The way this filespec is used is controlled by the NamingMethod. NamingMethod The output file naming strategy. These values determine how the lpModcaFileBase parameter is used. 1 = use the name as specified in lpModcaFileBase 2 = append numeric extensions to each file starting with ".001" 3 = append a right justified numeric then ".MOD" or ".ICA". The length of the numeric string is controlled by NameDigits. The extension can be changed using the APIs ITB_SetModcaExtension() or ITB_SetIocaExtension(). NameDigits Specifies how many digits are appended to the filename base when NamingMethod 3 is used. The value is ignored if NamingMethod is not set to 3. ModcaFormat Which type of output file to create. 1 = create MO:DCA format output files 0 = create single image IOCA files TiffCompression Compression in use in the source TIFF file. TRANS_TIFF_G4 = Group 4 compression TRANS_TIFF_G3 = Group 3 compression TRANS_TIFF_UNCOMPRESSED = uncompressed raw bitmap Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H Implementation Notes: * If the input TIFF file compression used is unknown, or if you want to force the image decompress/recompress operation, set the value TiffCompression = TRANS_TIFF_G3. This will disable the conversion optimizations built into to the Toolbox and force the slower translation. int ITBAPI ITB_T2M_TransBatch(char FAR *lpTiffFileSpec, int WriteAll, int TiffCompression) Description: Translate the contents of a TIFF file to the MO:DCA file previously opened with the function ITB_T2M_BeginBatch(). This function is compatible with the function ITB_T2M_WriteBatch() and can be called with it when writing a batch of files. If the TIFF compression is G4, the file is not translated, and the function ITB_T2M_WriteBatch() is invoked instead. The MO:DCA file is always written using G4 compression. Please see the additional implementation notes in the function ITB_T2M_WriteBatch() description. Parameters: lpTiffFileSpec Specifies the fully qualified name of a TIFF file to be translated. WriteAll Specifies which source file images to write. 0 = first image of the TIFF file 1 = all images in the TIFF file TiffCompression Compression format of the source TIFF file. TRANS_TIFF_G4 = Group 4 compression TRANS_TIFF_G3 = Group 3 compression TRANS_TIFF_UNCOMPRESSED = uncompressed raw bitmap Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H ---------------------------------------------------------------------- *** PTOCA FILE SUPPORT *** BACKGROUND AND IMPLEMENTATION NOTES: Some IBM products create MO:DCA files with PTOCA content. The full name of this IBM format is Presentation Text Object Content Architecture. Each file contains one or more pages of formatted text. The text and positioning data is stored in IBM EBCDIC (Extended Binary-Coded Decimal Interchange Code) characters. Each page may reference a PTOCA Overlay, which is merged with the text as a background. The overlay is not required to create the image, however without the overlay the text is presented on a white background. There are often a small number of PTOCA Overlay files on an IBM system, and they are all stored together. Your system administrator will know where to find them. Before processing any PTOCA files you should copy all the Overlay files to an overlay directory on your PC. These files should all share the same extension (not "TIF"), and this extension should be unique in this directory. Make sure only the overlay files share the same extension, otherwise conversion errors will be reported when non-overlay files with the same extension are processed later. When the API function ITB_SetPtocaOptions() is called, the overlay files will be converted to TIFF format and stored with the same base name and "TIF" extension (ovr1 -> ovr1.tif). This overlay file conversion is only done once. Once the TIFF equivalent files exist they are not regenerated. It might be necessary to switch the TIFF black bit setting before converting the overlays if they are generated as white on black. This can be done by calling the API ITB_SetTiffBlackBit() before the initialization call. To force regeneration of the TIFF overlay files after a setting change, delete the *.TIF files from your overlay directory. Since all PTOCA information is stored in EBCDIC, all data must be converted by the ImageToolbox before being used. The error reporting strategy and substitution character to use when unknown EBCDIC codes are detected is specified in the PTOCA initialization call ITB_SetPtocaOptions(). The TIFF file created by the PTOCA conversion is always stored using G4 compression. During the PTOCA file conversion, a temporary file is created in the same directory as the output file. This file is deleted before the conversion function returns. This does not normally cause any problem, however in a networked environment the user will require "delete" and "rename" privileges. It also means the conversions cannot write directly to a device like a CD. Only "pure" PTOCA content files can be processed in this version. Files that contain mixed PTOCA and IOCA image will generate an error if processed. Files of mixed text and image content are very rare, so this will not likely be a problem in your case. API function call examples are included in the "sample code" section at the end of this file. int ITBAPI ITB_SetPtocaOptions(char FAR *lpPtocaFontName, int FontPointSize, int FontBold, int FontItalic, int ErrOnUnknownChar, char FAR *lpSubstitutionChar, int ImageWithSpecifiedOverlay, int PrintWithSpecifiedOverlay, int ErrOnMissingOverlay, char FAR *lpOverlayPath, char FAR *lpOverlayExtension) Description: Before processing any PTOCA files the configuration options must be initialized by calling this function. If all the function inputs are valid and overlay files are to be used for either image creation or printing, the overlay files are preprocessed before the function returns. This preprocessing converts any files with a matching overlay filename extension and writes a TIFF file of the same name to the same directory. If a matching TIFF file already exists the file is not converted. If the overlays are converted to white on black, delete the TIFF files in the overlay directory to force the files to be regenerated, and add a call to the API function ITB_SetTiffBlackBit() before invoking this function to generate black on white overlays. If this function returns an error the PTOCA file processing features of the ImageToolbox Gold will be disabled. Parameters: lpPtocaFontName The name of a TrueType font to use to present the PTOCA text (such as "Courier New"). Normally this should be a monospaced font (where all letters, numbers and punctuation have the same character width). FontPointSize The font pointsize to use from 4 to 72. FontBold 1 = bold 0 = normal FontItalic 1 = italic 0 = normal ErrOnUnknownChar 1 = generate an error if an unknown EBCDIC character is detected 0 = no error reported - replace unknowns with the substitution character lpSubstitutionChar The substitution character for unknown EBCDIC characters specified as a string (such as "?"). ImageWithSpecifiedOverlay 1 = use the overlay specified in the PTOCA file when creating the TIFF image file. 0 = do not include the overlay in the image file PrintWithSpecifiedOverlay This parameter is included for future use but is ignored in this version. PTOCA format files cannot be printed directly. To print PTOCA format translate the file to TIFF using the API ITB_TransPtoca2Tif(), then print the TIFF file. ErrOnMissingOverlay 1 = generate an error if the required overlay file is missing 0 = no error reported - the file is processed without the overlay lpOverlayPath The path where the overlay files can be found (such as "c:\overlays") lpOverlayExtension The filename extension used by all overlay files in the specified overlay directory. If the files have no extension, specify a zero length string (as ""). Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H void ITBAPI ITB_SetPtocaCnvEnable(int AutoDetectPtoca) Description: Enable or disable automatic detection and handling of PTOCA format files by the API function ITB_CnvModca2Tif(). When this feature is enabled it is not necessary to determine if the input MO:DCA file contains PTOCA content before calling the function. If the PTOCA handling is disabled (default), the API function ITB_CnvModca2Tif() will report a file format error when PTOCA files are processed. In this situation, these files can be processed properly by the API function ITB_TransPtoca2Tif(). It may be desirable to keep this feature disabled if you want to detect PTOCA files for special processing. The PTOCA option initialization call to the API function ITB_SetPtocaOptions() must be successful before PTOCA files can be processed by ITB_CnvModca2Tif(). When using the ImageToolbox Silver this function has no effect. PTOCA file support is only available in the Gold version. Parameters: AutoDetectPtoca 1 = process PTOCA files in ITB_CnvModca2Tif() 0 = disable PTOCA file support in ITB_CnvModca2Tif() (default setting) Return Value: none int ITBAPI ITB_TransPtoca2Tif(char FAR *lpPtocaFileSpec, int FilesToConvert, char FAR *lpTiffFileBase, int NamingMethod, int NameDigits) Description: Translate a PTOCA file to a TIFF file using the current PTOCA generation settings. The PTOCA option initialization call to the API function ITB_SetPtocaOptions() must be successful before calling this function. Automatic PTOCA file detection is also available using the APIs ITB_SetPtocaCnvEnable() and ITB_CnvModca2Tif(). Parameters: lpPtocaFileSpec Far pointer to a null terminated string containing a fully qualified path to the PTOCA file to be translated. FilesToConvert Which pages in the file to translate. 1 = translate the first page only 2 = translate all pages in the PTOCA file to separate TIFF files 3 = translate all pages in the PTOCA file to a single TIFF file lpTiffFileBase The base of a fully qualified path to the TIFF file(s) to be written. The way this filespec is used is controlled by the NamingMethod. NamingMethod The output file naming strategy. These values determine how the lpTiffFileBase parameter is used. 1 = use the name as specified in lpTiffFileBase 2 = append numeric extensions to each file starting with ".001" 3 = append a right justified numeric then ".TIF". The length of the numeric string is controlled by NameDigits. The extension can be changed using the API ITB_SetTiffExtension(). NameDigits Specifies how many digits are appended to the filename base when NamingMethod 3 is used. The value is ignored if NamingMethod is not set to 3. Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H ---------------------------------------------------------------------- *** AUTOMATIC IMAGE FILE TRANSLATION FUNCTIONS *** BACKGROUND AND IMPLEMENTATION NOTES: Now it's possible to read many popular bitonal and color image formats and write the images out to selected file formats. Each output file format has a separate API function to provide the maximum flexibility supported by the format (such as multipage files, image compression selection and image size reduction). The current file formats supported for reading are listed below. Generally most compression types and bits per pel are supported for each format except LZW compression. TIFF MODCA IOCA JPEG PNG BMP PCX DCX DICOM JEDMICS KOFAX WINFAX Others - The list is always growing. If your desired format is not listed here please contact us for possible support. Notes: 1. PTOCA files cannot be translated directly. Please use the PTOCA file handing API functions described in this documentation to translate these files to TIFF, then using the TIFF file as an input for one of these functions. 2. Adobe PDF file reading is not supported. Additional API functions allow you to specify image handling strategies that are common to all file formats. These are described in the "Translation Configuration Functions" section of this documentation. Please review those APIs for important features that affect these functions. int ITBAPI ITB_TransImage2Tif(char FAR *lpSourceFileSpec, int FilesToConvert, char FAR *lpTifFileBase, int NamingMethod, int NameDigits, int OutputCompression, int AppendExisting) Description: Translate an image file to a TIFF file using the specified values and current output configuration settings. Parameters: lpSourceFileSpec Far pointer to a null terminated string containing a fully qualified path to the image file to be translated. FilesToConvert Which pages in the file to translate. 1 = translate the first page only 2 = translate all pages in the image file to separate TIFF files 3 = translate all pages in the image file to a single TIFF file lpTiffFileBase The base of a fully qualified path to the TIFF file(s) to be written. The way this filespec is used is controlled by the NamingMethod. NamingMethod The output file naming strategy. These values determine how the lpTiffFileBase parameter is used. 1 = use the name as specified in lpTiffFileBase 2 = append numeric extensions to each file starting with ".001" 3 = append a right justified numeric then ".TIF". The length of the numeric string is controlled by NameDigits. The extension can be changed using the API ITB_SetTiffExtension(). NameDigits Specifies how many digits are appended to the filename base when NamingMethod 3 is used. The value is ignored if NamingMethod is not set to 3. OutputCompression One of the following settings as defined in ITBDEFS.H: ITB_COMPRESSION_UNCOMPRESSED ITB_COMPRESSION_HUFFMAN ITB_COMPRESSION_PACKBITS ITB_COMPRESSION_G3 ITB_COMPRESSION_G4 AppendExisting Determines whether the output file should be appended to an existing file of the same name, or overwrite it. 0 = overwrite an existing file of same name without warning. non-zero = append pages to any existing TIFF file of the same name. Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H int ITBAPI ITB_TransImage2Modca(char FAR *lpSourceFileSpec, int FilesToConvert, char FAR *lpModcaFileBase, int NamingMethod, int NameDigits, int AppendExisting) Description: Translate an image file to a MODCA file using the specified values and current output configuration settings. All output images are saved as bitonal (1 bit per pel) using group 4 compression. Parameters: lpSourceFileSpec Far pointer to a null terminated string containing a fully qualified path to the image file to be translated. FilesToConvert Which pages in the file to translate. 1 = translate the first page only 2 = translate all pages in the image file to separate MODCA files 3 = translate all pages in the image file to a single MODCA file lpModcaFileBase The base of a fully qualified path to the MODCA file(s) to be written. The way this filespec is used is controlled by the NamingMethod. NamingMethod The output file naming strategy. These values determine how the lpModcaFileBase parameter is used. 1 = use the name as specified in lpModcaFileBase 2 = append numeric extensions to each file starting with ".001" 3 = append a right justified numeric then ".MOD". The length of the numeric string is controlled by NameDigits. The extension can be changed using the API ITB_SetModcaExtension(). NameDigits Specifies how many digits are appended to the filename base when NamingMethod 3 is used. The value is ignored if NamingMethod is not set to 3. AppendExisting Determines whether the output file should be appended to an existing file of the same name, or overwrite it. 0 = overwrite an existing file of same name without warning. non-zero = append pages to any existing MODCA file of the same name. Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H int ITBAPI ITB_TransImage2Jpeg(char FAR *lpSourceFileSpec, int FilesToConvert, char FAR *lpJpegFileBase, int NamingMethod, int NameDigits, int MaxPixelWidth, int MaxPixelHeight) Description: Translate an image file to a JPEG file using the specified values and current output configuration settings. All output images are saved as color using JPEG compression. If the input file is bitonal, it is promoted to 8 bits per pel before saving. Note that JPEG files only support a single image per file. If you are translating multiple page files, separate output files must be created. Parameters: lpSourceFileSpec Far pointer to a null terminated string containing a fully qualified path to the image file to be translated. FilesToConvert Which pages in the file to translate. 1 = translate the first page only 2 = translate all pages in the image file to separate JPEG files lpJpegFileBase The base of a fully qualified path to the JPEG file(s) to be written. The way this filespec is used is controlled by the NamingMethod. NamingMethod The output file naming strategy. These values determine how the lpJpegFileBase parameter is used. 1 = use the name as specified in lpJpegFileBase 2 = append numeric extensions to each file starting with ".001" 3 = append a right justified numeric then ".JPG". The length of the numeric string is controlled by NameDigits. The extension can be changed using the API ITB_SetJpegExtension(). NameDigits Specifies how many digits are appended to the filename base when NamingMethod 3 is used. The value is ignored if NamingMethod is not set to 3. MaxPixelWidth The maximum width the output image should be in pixels. If the image is larger than this size, reduce it down to this maximum. This feature allows you to generate an image that fits in a standard size on an HTML (web) page. The image height will be affected by this size reduction as well. To translate without specifying a maximum value, use "-1" for this input. MaxPixelHeight The maximum height the output image should be in pixels. If the image is larger than this size, reduce it down to this maximum. This feature allows you to generate an image that fits in a standard size on an HTML (web) page. The image width will be affected by this size reduction as well. To translate without specifying a maximum value, use "-1" for this input. Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H int ITBAPI ITB_TransImage2Png(char FAR *lpSourceFileSpec, int FilesToConvert, char FAR *lpPngFileBase, int NamingMethod, int NameDigits, int MaxPixelWidth, int MaxPixelHeight) Description: Translate an image file to a PNG file using the specified values and current output configuration settings. The PNG file format supports both bitonal and color images. The format is not currently supported by all internet browsers. Note that PNG files only support a single image per file. If you are translating multiple page files, separate output files must be created. Parameters: lpSourceFileSpec Far pointer to a null terminated string containing a fully qualified path to the image file to be translated. FilesToConvert Which pages in the file to translate. 1 = translate the first page only 2 = translate all pages in the image file to separate PNG files lpPngFileBase The base of a fully qualified path to the PNG file(s) to be written. The way this filespec is used is controlled by the NamingMethod. NamingMethod The output file naming strategy. These values determine how the lpPngFileBase parameter is used. 1 = use the name as specified in lpPngFileBase 2 = append numeric extensions to each file starting with ".001" 3 = append a right justified numeric then ".PNG". The length of the numeric string is controlled by NameDigits. The extension can be changed using the API ITB_SetPngExtension(). NameDigits Specifies how many digits are appended to the filename base when NamingMethod 3 is used. The value is ignored if NamingMethod is not set to 3. MaxPixelWidth The maximum width the output image should be in pixels. If the image is larger than this size, reduce it down to this maximum. This feature allows you to generate an image that fits in a standard size on an HTML (web) page. The image height will be affected by this size reduction as well. To translate without specifying a maximum value, use "-1" for this input. MaxPixelHeight The maximum height the output image should be in pixels. If the image is larger than this size, reduce it down to this maximum. This feature allows you to generate an image that fits in a standard size on an HTML (web) page. The image width will be affected by this size reduction as well. To translate without specifying a maximum value, use "-1" for this input. Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H ---------------------------------------------------------------------- *** AUTOMATIC IMAGE FILE TRANSLATION TO ADOBE ACROBAT PDF FUNCTIONS *** BACKGROUND AND IMPLEMENTATION NOTES: Now many popular bitonal and color image file formats can be translated to Adobe Acrobat PDF files. The Acrobat driver is not required to create the output files. The images are stored in the PDF file(s) as image data. A list of the supported input file formats can be found in the "Automatic Image File Translation" section. It is possible to configure a number of PDF file creation settings to match your exact output requirements using the API function ITB_SetTransPdfOptions(). Additional API functions allow you to specify image handling strategies that are common to all file formats. These are described in the "Translation Configuration Functions" section of this documentation. Please review those APIs for important features that affect these functions. If you want to create PDF files using the Acrobat driver, please see the printing API functions in the "Image Printing Functions" section of this documentation. int ITBAPI ITB_SetTransPdfOptions(int PageSize, int PageOrientation, int HorizontalMargin, int VerticalMargin, int InitialRotation, int OptimizedRotation) Description: Set various characteristics of the output PDF files. This function should be called once before translating to PDF. The settings remain in effect until called again or the DLL is unloaded from memory. If this function is not called, the default values for each setting are used. Parameters: PageSize This is the page size to create for each image. Use one of the following settings as defined in ITBDEFS.H: ITB_LETTER (default) ITB_LEGAL ITB_EXECUTIVE ITB_A4 ITB_A5 ITB_B5 ITB_IMAGESIZE = make the page size the same as the image PageOrientation This is the page orientation to use for each page. If the PageSize selected is ITB_IMAGESIZE this value has no effect. Use one of the following settings as defined in ITBDEFS.H: ITB_PORTRAIT (default) ITB_LANDSCAPE HorizontalMargin This is the margin (white space) to use on the left and right of the image in points (1/72 inch). Use 0 for no margin up to the maximum of 144. If the PageSize selected is ITB_IMAGESIZE this value will be added to sides of the image to create a larger page size. The default is 0. VerticalMargin This is the margin (white space) to use on the top and bottom of the image in points (1/72 inch). Use 0 for no margin up to the maximum of 144. If the PageSize selected is ITB_IMAGESIZE this value will be added to top and bottom of the image to create a larger page size. The default is 0. InitialRotation The number of degrees to rotate the image clockwise before determining how it fits on the page. Use this feature to rotate consistently inverted images (scanned upside down), or switch between landscape and portrait orientations. If the PageSize selected is ITB_IMAGESIZE this value has no effect. Valid values are 0, 90, 180 and 270. Use 0 for no initial rotation. The default is 0. OptimizedRotation The number of degrees to rotate the image clockwise if it fits on the page better (with less or no image reduction). If there is an InitialRotation value specified, this optimization is performed after the first rotation. Use this feature when it is desirable to to rotate some images that may be taller or wider than others, such as situations where various types of documents are scanned in a set. If the PageSize selected is ITB_IMAGESIZE this value has no effect. Valid values are 0, 90 and 270. Use 0 for no optimization. The default is 0. Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H Implementation Notes: * Some bitonal images will have better display quality if a standard page size is selected for PageSize rather than ITB_IMAGESIZE. * Combining large margin values with OptimizedRotation can cause unintentional image rotation. Documents that are wide and short (such checks or receipts) combined with large horizontal margins may fit without image reduction if rotated. Reduce your margin settings if you find your images rotated unexpectedly. * Margins on JPEG compressed images may be wider than specified depending on the program that created the source file. int ITBAPI ITB_TransImage2Pdf(char FAR *lpSourceFileSpec, int FilesToConvert, char FAR *lpPdfFileBase, int NamingMethod, int NameDigits, int AppendExisting) Description: Translate an image file to an Adobe Acrobat PDF file using the specified values and current output configuration option settings. If an image does not fit on the selected page size it is reduced to fit on the page. Each image is written to a separate page in the same order they are found in the source file. Use the API function ITB_SetTransPdfOptions() to customize the characteristics of each PDF page and how the images are positioned on the page. Parameters: lpSourceFileSpec Far pointer to a null terminated string containing a fully qualified path to the image file to be translated. FilesToConvert Which pages in the file to translate. 1 = translate the first page only 2 = translate all pages in the image file to separate PDF files 3 = translate all pages in the image file to a single PDF file lpPdfFileBase The base of a fully qualified path to the PDF file(s) to be written. The way this filespec is used is controlled by the NamingMethod. NamingMethod The output file naming strategy. These values determine how the lpPdfFileBase parameter is used. 1 = use the name as specified in lpPdfFileBase 2 = append numeric extensions to each file starting with ".001" 3 = append a right justified numeric then ".PDF". The length of the numeric string is controlled by NameDigits. The extension can be changed using the API ITB_SetPdfExtension(). NameDigits Specifies how many digits are appended to the filename base when NamingMethod 3 is used. The value is ignored if NamingMethod is not set to 3. AppendExisting Determines whether the output file should be appended to an existing file of the same name, or overwrite it. 0 = overwrite an existing file of same name without warning. non-zero = append pages to any existing PDF file of the same name. Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H ---------------------------------------------------------------------- *** IMAGE TRANSLATION CONFIGURATION FUNCTIONS *** BACKGROUND AND IMPLEMENTATION NOTES: These API functions allow you to specify image handling strategies that are common to all translated file formats. These allow you to specify algorithms and settings to best batch your image characteristics and output file requirements. void ITBAPI ITB_SetPdfExtension(char FAR *lpExtension) void ITBAPI ITB_SetPngExtension(char FAR *lpExtension) Description: Set the extension used for each file type when using NamingMethod 3. The default three character extensions for each file type are: PDF -> PDF PNG -> PNG Note that the extensions for other output file types that can be also be "converted" are specified using the functions ITB_SetTiffExtension(), ITB_SetModcaExtension(), ITB_SetIocaExtension() and ITB_SetJpegExtension() as described in the ImageToolbox Silver documentation. Parameters: lpExtension Far pointer to a null terminated string of up to 6 characters. All characters must be valid DOS filename characters. Return Value: none int ITBAPI ITB_SetTransScalingMethod(int ScalingMethod) Description: Select the scaling method to use when an image size is reduced to fit on a page or stretched to increase the DPI (dots per inch). Different scaling methods work best on different types of images. Experiment with some samples of your images to determine the best setting. This function should be called once before translating any images if you want to change the setting. Parameters: ScalingMethod The desired type of scaling to use. Use one of the following settings as defined in ITBDEFS.H: ITB_SCALEAVERAGE - averages neighboring pixels and retains more black information (default) ITB_SCALEREDUCE - scales without examining neighboring pixels which can result in lost black information Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H Implementation Notes: Here are some guidelines for using each setting: ITB_SCALEAVERAGE: - When reducing the size of a color image this will soften the image in much the same way a "fog filter" does in photography. - Retains more black detail in bitonal images but can also turn some images into a mass of black depending on the amount of black in the original. - Will retain horizontal and vertical lines on images that were skewed during scanning. ITB_SCALEREDUCE: - When reducing the size of a color image will retain more of the sharpness of the original. - Will result in cleaner looking bitonal images but will sometimes drop too much black information from the image. - Horizontal lines in skewed images may have white gaps. int ITBAPI ITB_SetTransColorStrategy(int ColorTranslationStrategy) Description: Select the color modification strategy to use when converting color images to bitonal. Different color reduction methods work best on different types of images. Experiment with some samples of your images to determine the best setting. The setting also affects the way images are printed. See the description of ITB_SetPrintOptions() for more information. This function should be called once before translating any images if you want to change the setting. Parameters: ColorTranslationStrategy The desired type of conversion to use. Use one of the following settings as defined in ITBDEFS.H: ITB_COLOR_KEEP - retain the color in the output file. If not possible due to the output format use the ITB_COLOR_HALFTONE option. (default) ITB_COLOR_BAYER - reduce to bitonal using a Bayer fixed matrix dithering technique ITB_COLOR_DIFFUSION - reduce to bitonal using error diffusion ITB_COLOR_HALFTONE - reduce to bitonal using a fixed halftone matrix dithering technique Implementation Note: Each image format has different color support and may ignore some settings. Please use a setting that makes sense for the type of file you are creating. Here are the valid settings by output file type: MODCA - bitonal only, don't use ITB_COLOR_KEEP TIFF - color support varies depending upon the output file compression: - JPEG compression - 8 and 24 bit per pel color - ignores all settings - uncompressed - 1,4,8 and 24 bits per pel - all color strategies supported - all other compression types support bitonal only so don't use the ITB_COLOR_KEEP setting JPEG - 8 and 24 bit per pel color, ignores all settings PNG - 1,4,8 and 24 bits per pel, all color strategies supported Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H int ITBAPI ITB_SetTransJpegQuality(int JpegQuality, int HorizontalSampleRate, int VerticalSampleRate) Description: Select the JPEG quality values to use when saving JPEG compressed images. Different values work best on different types of images. Experiment with some samples of your images to determine the best settings. This function should be called once before translating any images if you want to change the setting. Parameters: JpegQuality This value adjusts the compression ratio to quality factor. The smallest output files have the least detailed images. Valid values are from 1 to 100 where: 1 = the smallest file size but the least image quality 100 = the best image quality but largest file size HorizontalSampleRate The horizontal sampling rate when determining the color to store in the output image. A value of 1 samples every pixel, 2 skips every other pixel, and so on. The best image quality will be retained using every pixel. Sampling fewer pixels may reduce the compressed image size. Valid values are 1 and up. The default value is 2. VerticalSampleRate The vertical sampling rate when determining the color to store in the output image. A value of 1 samples every pixel, 2 skips every other pixel, and so on. The best image quality will be retained using every pixel. Sampling fewer pixels may reduce the compressed image size. Valid values are 1 and up. The default value is 1. Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H Implementation Notes: * Reducing the JpegQuality value can have a dramatic effect on the output file size in the range between 80 to 100. It is often possible to use a value around 80 as a starting point for your testing. Reducing the value down to 60 may not have much impact on the file size, but noticable image quality degradation may occur. * These settings have no effect on color images stored in PDF format output files because their color content is not stored using JPEG compression. ---------------------------------------------------------------------- *** IMAGE MODIFICATION FUNCTIONS *** BACKGROUND AND IMPLEMENTATION NOTES: When processing an image file it is sometimes desirable to apply one or more modifications to the image before saving it in the output file. These functions specify the desired changes or settings to use when processing the image files. Call any of these functions once and the settings will be used when processing all subsequent image files. void ITBAPI ITB_TransInvertBitmap(int InvertDuringTranslation) Description: During translation invert all pels in the image. This can be used to turn a white on black image to black on white. The default setting is not to invert the image. Undesired switching of the bitmap can happen during conversion when default formating tags are missing in an image file. If the "translation" actually "converts" the image instead, this function will have no effect. Use the ITB_SetTiffBlackBit() function instead. Parameters: InvertDuringTranslation 1 = invert the image during translation 0 = do not invert the image Return Value: none void ITBAPI ITB_TransChangeResolution(int ChangeDuringTranslation, int HorizontalDPI, int VerticalDPI, int ToleranceDPI) Description: During a translation, the resolution of the image may be changed. This feature is useful if your images come from a variety of sources and have different resolutions. Some viewers do not handle very low or high resolution images very well. The default setting is not to modify the image resolution during translation. If this setting is turned on, the optimizations in the translation APIs are disabled (where supported), and all images are decompressed and recompressed. Only the Gold translation functions are affected. The Silver conversion functions ignore this setting. This feature works when translating between most formats. The ToleranceDPI parameter allows up to the specified DPI variation from the desired DPI before the modification will occur. If you want the exact DPI values specified, set this parameter to 0. Even if one direction requires modification, the other will not necessarily be changed unless it exceeds the tolerance threshold. This can be useful if low resolution FAX are being processed for example where the image DPI is not exactly 100 or 200 (204 x 98 for low resolution fax). If the image resolution is adjusted, the bitmap is stretched in the desired direction and the image header value for the DPI is changed. The new resolution is the exact value specified in the API parameter. To turn off the feature, call the function with the parameter ChangeDuringTranslation set to 0. All other parameter values are ignored. Parameters: ChangeDuringTranslation 1 = change the image resolution during translation 0 = do not attempt resolution modifications HorizontalDPI The horizontal DPI desired for the translated image. VerticalDPI The vertical DPI desired for the translated image. ToleranceDPI The amount the DPI can vary from the desired value before DPI translation is performed. Any positive from 0 up is valid. Return Value: none ---------------------------------------------------------------------- *** IMAGE PRINTING FUNCTIONS *** BACKGROUND AND IMPLEMENTATION NOTES: Now many popular bitonal and color image file formats can be printed directly from your application using most Windows printer drivers. A list of the supported input file formats can be found in the "Automatic Image File Translation" section. It is possible to configure a number of print settings to match your exact requirements using the API function ITB_SetPrintOptions(). The printing function allows you to print directly to a selected filename and obtain status information at the end of the print processing. If you want to create PDF files without using the Adobe Acrobat driver, please see the PDF creation API functions in the "Adobe Acrobat PDF Functions" section of this documentation. int ITBAPI ITB_SetPrintOptions(int FastPrinting, int AdjustAspectRatio, int ReverseBits, int HorizontalMargin, int VerticalMargin, int InitialRotation, int OptimizedRotation) Description: Set various options to be used when printing image files. This function should be called once before printing. The settings remain in effect until called again or the DLL is unloaded from memory. If this function is not called, the default values for each setting are used. Parameters: FastPrinting Selects the type of printing used. Fast printing sends the bitmap to the printer where it may be scaled and reduced to bitonal (if required). This can result in significantly faster printing and sometimes better image quality (especially Postscript printers). Some printers may have problems or even fail to print using the FastPrinting mode. Regular printing performs all the image scaling and color conversion before sending the page to the printer and will normally work properly on all printers. Valid inputs are: 0 = use regular printing (default) non-zero = use fast printing AdjustAspectRatio Selecting this option causes images that have different values for their horizontal and vertical DPI (dots per inch) to be adjusted to the same DPI before printing. The larger DPI value is used. This can be useful when printing images such as low resolution fax pages which can sometimes print compressed vertically. The scaling method used is selected using the API ITB_SetTransScalingMethod(). Images with identical horizontal and vertical DPI values are not modified. Valid inputs are: 0 = no aspect ratio adjustment before printing non-zero = test and adjust images before printing (default) ReverseBits Reverse the setting of black and white bits before printing. This can be useful when printing documents scanned white on black. Valid inputs are: 0 = do not reverse bits before printing (default) non-zero = reverse bits before printing HorizontalMargin This is the margin (white space) to use on the left and right of the image in points (1/72 inch). Use 0 for no margin up to the maximum of 144. The default is 0. VerticalMargin This is the margin (white space) to use on the top and bottom of the image in points (1/72 inch). Use 0 for no margin up to the maximum of 144. The default is 0. InitialRotation The number of degrees to rotate the image clockwise before determining how it fits on the page. Use this feature to rotate consistently inverted images (scanned upside down), or switch between landscape and portrait orientations. Valid values are 0, 90, 180 and 270. Use 0 for no initial rotation. The default is 0. OptimizedRotation The number of degrees to rotate the image clockwise if it fits on the page better (with less or no image reduction). If there is an InitialRotation value specified, this optimization is performed after the first rotation. Use this feature when it is desirable to to rotate some images that may be taller or wider than others, such as situations where various types of documents are scanned in a set. Valid values are 0, 90 and 270. Use 0 for no optimization. The default is 0. Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H Implementation Notes: * The current setting of ITB_SetTransColorStrategy() is used to determine how to handle color images. If the current setting is ITB_COLOR_KEEP and you are printing to a bitonal printer, the driver will convert the image from color. In some cases the Windows printer driver will not manage this properly and the image will be printed as a black rectangle. In this situation, change the API setting to one of the conversion options to force the ImageToolbox to make the image bitonal before sending it to the printer. * Some printer drivers automatically add a page margin to their output to take into account the paper edge area that cannot be reliably printed. In this case the margins specified in this function are usually added to the margins created by the printer driver. If your margins are too large the setting values may need to be reduced to create the margin sizes you desire. * Combining large margin values with OptimizedRotation can cause unintentional image rotation. Documents that are wide and short (such checks or receipts) combined with large horizontal margins may fit without image reduction if rotated. Reduce your margin settings if you find your images rotated unexpectedly. int ITBAPI ITB_PrintFile(HWND hWnd, char FAR *Filename, int ShowPrintDialog, int PrintAllPages, int PrintBeginPage, int PrintEndPage, char FAR *Print2Filename, int *UserCancel, int *PagesPrinted) Description: Print an image file on the default printer. To set various print options call the API ITB_SetPrintOptions() once before printing. Parameters: hWnd The handle of the main window in your application. This value is used to associate the standard Windows "Print" dialog with your application. If you don't have access to the value of your window handle, the value NULL or 0 may be used. The value is used internally even if you do not display the dialog using the ShowPrintDialog setting. Filename The name of the image file to print. ShowPrintDialog Specifies whether the standard Windows Print dialog should be displayed before printing. If the dialog is display the user may override the values specified for PrintAllPages, PrintBeginPage, PrintEndPage and Print2Filename. Valid inputs are: 0 = do not display the dialog non-zero = display the dialog PrintAllPages Print all the pages of the image file. This value can be overridden using the Windows Print dialog if it is displayed. Valid inputs are: 0 = no, a begin and end page are specified below non-zero = yes print all the pages PrintBeginPage If PrintAllPages is zero, this specifies the first page to print, from 1 to the number of pages in the image file. This value can be overridden using the Windows Print dialog if it is displayed. PrintEndPage If PrintAllPages is zero, this specifies the last page to print, from 1 to the number of pages in the image file. This value can be overridden using the Windows Print dialog if it is displayed. Print2Filename If the print data stream should be printed to a file, this specifies the name of the file to store the print output. This has the same effect as selecting the "Print to file" option on a standard Windows Print dialog except that the output file naming is specified here. The user will not be presented with a filename query dialog when the print job begins. Specify a fully qualified path to a print file if you want to enable this feature. To print normally, specify a null pointer or string (NULL, 0 or ""). If a print file is specified the user cannot override this in the print dialog. UserCancel Indicates if the user cancelled the print operation from the Windows Print dialog. If the dialog is not displayed, the returned value will be 0. If the user cancels from a printer driver dialog, this return code will not be able to detect the action and will report that the job was not cancelled. Valid return values are: 0 = the user did not cancel the print operation from the print dialog non-zero = the user did cancel the print operation PagesPrinted Indicates the number of pages printed. The returned value can be from 0 to the number of pages in the image file. If the user cancels printing or an error is returned by the API function, this value will still be accurate. Return Value: 0 = no errors non-zero = error as defined in ITBDEFS.H ---------------------------------------------------------------------- Sample Code For The ImageToolbox Gold Functions ----------------------------------------------- For code samples of ImageToolbox Silver functions, please see the file ITBSAPI.TXT. #include "itbdefs.h" int rc; int UserCancel; int PagesPrinted; ITB_SetTiffExtension((char FAR *)"FAX"); // TIFF files created using NamingMethod 3 will have this extension ITB_SetModcaExtension((char FAR *)"MDA"); // MO:DCA files created using NamingMethod 3 will have this extension ITB_SetIocaExtension((char FAR *)"IOC"); // IOCA files created using NamingMethod 3 will have this extension ITB_SetJpegExtension((char FAR *)"JPEG"); // JPEG files created using NamingMethod 3 will have this extension ITB_SetPdfExtension((char FAR *)"PDF"); // PDF files created using NamingMethod 3 will have this extension ITB_SetPngExtension((char FAR *)"PNG"); // PNG files created using NamingMethod 3 will have this extension ITB_TransInvertBitmap(1); // invert the pels in all bitmaps translated /* Translate functions work same way as Convert functions. For more examples please see the samples in ITBSAPI.TXT. All parameters with the same name have the same input values and meanings. */ // During translations, convert all images to approximately 200 DPI. // Low res FAX (204W x 98H) will only be converted in height and the // width left at 204 DPI because the tolerance has been set to 5. ITB_TransChangeResolution(1,200,200,5); // All pages using the named base and appending a two digit zero padded // right justified number and extension. The extension is the default // or the last specified value in ITB_SetTiffExtension(). rc = ITB_TransModca2Tif((LPSTR)"source.mod",2,(LPSTR)"image_",3,2, TRANS_MODCA_G4,TRANS_TIFF_G3); // results in files image_01.fax, image_02.fax, image_03.fax ... // Turn off resolution modification during translation ITB_TransChangeResolution(0,0,0,0); // All pages using the named base and appending a two digit zero padded // right justified number and extension (MO:DCA). The extension used // is the default or one last specified by ITB_SetModcaExtension(). rc = ITB_TransTif2Modca((LPSTR)"source.tif",2,(LPSTR)"image_",3,2,1, TRANS_TIFF_G3); // results in files image_01.mda, image_02.mda, image_03.mda ... // All pages using the named base and appending a three digit zero padded // right justified number and extension (IOCA). The extension used // is the default or one last specified by ITB_SetIocaExtension(). rc = ITB_TransTif2Modca((LPSTR)"source.tif",2,(LPSTR)"image",3,3,0, TRANS_TIFF_UNCOMPRESSED); // results in files image001.ioc, image002.ioc, image003.ioc ... ITB_TransInvertBitmap(0); // turn off pel inverting when translating // Translate a batch of TIFF files to a single MO:DCA file rc = ITB_T2M_BeginBatch("G:\\BATCH.MOD"); // open the MO:DCA file if (! rc) { rc = ITB_T2M_TransBatch("G:\\src1.tif",0,TRANS_TIFF_G3); // write 1st image only if (! rc) { rc = ITB_T2M_TransBatch("G:\\src2.tif",1,TRANS_TIFF_G3); // write all images if (! rc) { rc = ITB_T2M_EndBatch(); // close the MO:DCA file } } } // Convert PTOCA files to TIFF ITB_SetTiffBlackBit(0); // overlays created using this setting // set all PTOCA processing options and preprocess the overlays rc = ITB_SetPtocaOptions("Courier New",10,1,0, 1,"$", 1,1,1, "f:\\overlays","OVL"); if (! rc) { // Enable PTOCA processing by the API ITB_CnvModca2Tif(), otherwise // encountering a PTOCA file in the Cnv function would return an error. ITB_SetPtocaCnvEnable(1); // convert MODCA/IOCA/PTOCA file types to TIFF rc = ITB_CnvModca2Tif((LPSTR)"f:\\samples\\src.pot",3, (LPSTR)"f:\\samples\\destpotc.tif",1,0); if (! rc) { // also process only PTOCA files using the dedicated function rc = ITB_TransPtoca2Tif((LPSTR)"f:\\samples\\src.pot",3, (LPSTR)"f:\\samples\\destpott.tif",1,0); } } /* Many popular image file formats can be read and converted to a selection of output file formats. */ // select the options to use during translations (call each function // once before translating to change any default values) rc = ITB_SetTransScalingMethod(ITB_SCALEREDUCE); // scaling may drop some image information rc = ITB_SetTransColorStrategy(ITB_COLOR_KEEP); // retain the input color where possible rc = ITB_SetTransJpegQuality(80,2,1); // retain most image information but create a smaller output file // now translate some image files // create a multiple page tif file stored in G4 format by appending other // TIFF files to the output file rc = ITB_TransImage2Tif((LPSTR)"source.tif",3, (LPSTR)"bigfile.tif",1,3, ITB_COMPRESSION_G4,TRUE); // create a single page bitonal MODCA file from a color JPEG using a // halftone dithering technique rc = ITB_TransImage2Modca((LPSTR)"source.jpeg",1, (LPSTR)"photo.modca",1,3, FALSE); // translate the bitonal TIFF document to JPEG and make the maximum width // and height 300 pixels for proper display on the HTML page rc = ITB_TransImage2Jpeg((LPSTR)"document.tiff",1, (LPSTR)"webdoc.jpg",1,3, 300,300); // translate the first page of a bitonal MODCA document to PNG with the // output page size the same as the source rc = ITB_TransImage2Png((LPSTR)"document.mod",1, (LPSTR)"webdoc.png",1,3, -1,-1); /* Many popular image file formats can be read and converted to Adobe Acrobat format PDF files. */ // Create images on letter sized paper in portrait orientation with no // margins added. If the source image is landscape and would fit better // rotated, do the rotation so that the bottom of the original image is // on the right side of the paper. rc = ITB_SetTransPdfOptions(ITB_LETTER,ITB_PORTRAIT, 0,0, 0,270); // translate all the pages in the TIFF file to the named PDF file and // overwrite an existing PDF file of the same name rc = ITB_TransImage2Pdf((LPSTR)"miscdocs.tif",3, (LPSTR)"thiscase.pdf",1,3, FALSE); // create actual size pages with a 1/4 inch white border that are // rotated 90 degrees clockwise rc = ITB_SetTransPdfOptions(ITB_IMAGESIZE, ITB_PORTRAIT, // ignored 18,18, 90, 0); // ignored // translate the JPEG image to the PDF in color and append it to the // existing PDF file rc = ITB_TransImage2Pdf((LPSTR)"frame6.jpg",1, (LPSTR)"vacation.pdf",1,3, TRUE); /* Many popular image file formats can be printed. */ // print using 1 inch horizontal and 1/2 inch vertical margins with // initial rotation and optimized rotations. rc = ITB_SetPrintOptions(FALSE,FALSE,FALSE, 72,36, 90,90); // Print all the pages in the MODCA file. If the function returns without // an error the values of usercancel and pagesprinted can be used for // any extra handling desired. rc = ITB_PrintFile((HWND)NULL, (LPSTR)"landscape.mod", TRUE,TRUE,0,0, (LPSTR)"", &usercancel,&pagesprinted);
__label__pos
0.954035
All step-by-step guides draw.io Training – Exercise 7: Create a diagram with layers and images May 11th, 2021| Reading Time: 7 min Building your diagram by using layers allows you a lot more flexibility - you can switch between different views of your diagram, group related elements and protect them from being modified when you work in a different layer. In this exercise, you'll create a diagram in a top layer, following an image 'template' that you paste into the background layer. draw.io Training – Exercise 6: Work with the shape libraries May 11th, 2021| Reading Time: 5 min You're ready to start creating more complex diagrams! You should be comfortable inserting and formatting shapes, drawing connectors and inserting text. Plus in the last exercise, you used some more advanced formatting to create your tree. In this exercise, you will create a flow chart, with a very important theme - drinking coffee! draw.io Training – Exercise 8: Add links and tooltips May 11th, 2021| Reading Time: 8 min You can add links so that when a viewer clicks on a shape or a line of text in your diagram, they can be taken directly to another page or diagram. And you can add tooltips, so when a viewer hovers their mouse over a section of the diagram, they will be shown additional information in a tooltip. draw.io Training – Exercise 10: Export and import August 17th, 2017| Reading Time: 3 min If you are using a platform or creating a document that can't embed a draw.io diagram, you'll want to export it as an image. Importing is just as important, especially if you want to move your diagrams from another diagramming tool into draw.io to take advantage of its rich features.
__label__pos
0.535773
Open In App Related Articles Broadcast Receiver in Android With Example Improve Article Improve Save Article Save Like Article Like Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events. Broadcast Receivers allow us to register for the system and application events, and when that event happens, then the register receivers get notified. There are mainly two types of Broadcast Receivers: • Static Broadcast Receivers: These types of Receivers are declared in the manifest file and works even if the app is closed. • Dynamic Broadcast Receivers: These types of receivers work only if the app is active or minimized. Since from API Level 26, most of the broadcast can only be caught by the dynamic receiver, so we have implemented dynamic receivers in our sample project given below. There are some static fields defined in the Intent class which can be used to broadcast different events. We have taken a change of airplane mode as a broadcast event, but there are many events for which broadcast register can be used. Following are some of the important system-wide generated intents:-                        Intent Description Of Event android.intent.action.BATTERY_LOW : Indicates low battery condition on the device. android.intent.action.BOOT_COMPLETED This is broadcast once after the system has finished booting android.intent.action.CALL  To perform a call to someone specified by the data android.intent.action.DATE_CHANGED  Indicates that the date has changed android.intent.action.REBOOT Indicates that the device has been a reboot android.net.conn.CONNECTIVITY_CHANGE The mobile network or wifi connection is changed(or reset) android.intent.ACTION_AIRPLANE_MODE_CHANGED This indicates that airplane mode has been switched on or off. The two main things that we have to do in order to use the broadcast receiver in our application are: Creating the Broadcast Receiver: class AirplaneModeChangeReceiver:BroadcastReceiver() {        override fun onReceive(context: Context?, intent: Intent?) {             // logic of the code needs to be written here       } }   Registering a BroadcastReceiver: IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {                      // receiver is the broadcast receiver that we have registered                     // and it is the intent filter that we have created                     registerReceiver(receiver,it)       }   Example Below is the sample project showing how to create the broadcast Receiver and how to register them for a particular event and how to use them in the application. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Step 2: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity"> </androidx.constraintlayout.widget.ConstraintLayout> Step 3: Working with the MainActivity file  Go to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail.  Kotlin import android.content.Intent import android.content.IntentFilter import android.os.Bundle import androidx.appcompat.app.AppCompatActivity   class MainActivity : AppCompatActivity() {       // register the receiver in the main activity in order     // to receive updates of broadcasts events if they occur     lateinit var receiver: AirplaneModeChangeReceiver     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)           receiver = AirplaneModeChangeReceiver()           // Intent Filter is useful to determine which apps wants to receive         // which intents,since here we want to respond to change of         // airplane mode         IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {             // registering the receiver             // it parameter which is passed in  registerReceiver() function             // is the intent filter that we have just created             registerReceiver(receiver, it)         }     }       // since AirplaneModeChangeReceiver class holds a instance of Context     // and that context is actually the activity context in which     // the receiver has been created     override fun onStop() {         super.onStop()         unregisterReceiver(receiver)     } } Java import androidx.appcompat.app.AppCompatActivity;   import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle;   public class MainActivity extends AppCompatActivity {       AirplaneModeChangeReceiver airplaneModeChangeReceiver = new AirplaneModeChangeReceiver();       @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);     }       @Override     protected void onStart() {         super.onStart();         IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);         registerReceiver(airplaneModeChangeReceiver, filter);     }       @Override     protected void onStop() {         super.onStop();         unregisterReceiver(airplaneModeChangeReceiver);     } } Step 4: Create a new class  Go to app > java > your package name(in which the MainActicity is present) > right-click > New > Kotlin File/Class and name the files as AirplaneModeChangeReceiver. Below is the code for the AirplaneModeChangeReceiver file. Comments are added inside the code to understand the code in more detail.  Kotlin import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.widget.Toast   // AirplaneModeChangeReceiver class extending BroadcastReceiver class class AirplaneModeChangeReceiver : BroadcastReceiver() {       // this function will be executed when the user changes his     // airplane mode     override fun onReceive(context: Context?, intent: Intent?) {                   // intent contains the information about the broadcast         // in our case broadcast is change of airplane mode           // if getBooleanExtra contains null value,it will directly return back         val isAirplaneModeEnabled = intent?.getBooleanExtra("state", false) ?: return                   // checking whether airplane mode is enabled or not         if (isAirplaneModeEnabled) {             // showing the toast message if airplane mode is enabled             Toast.makeText(context, "Airplane Mode Enabled", Toast.LENGTH_LONG).show()         } else {             // showing the toast message if airplane mode is disabled             Toast.makeText(context, "Airplane Mode Disabled", Toast.LENGTH_LONG).show()         }     } } Java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.provider.Settings; import android.widget.Toast;   public class AirplaneModeChangeReceiver extends BroadcastReceiver {       @Override     public void onReceive(Context context, Intent intent) {           if (isAirplaneModeOn(context.getApplicationContext())) {             Toast.makeText(context, "AirPlane mode is on", Toast.LENGTH_SHORT).show();         } else {             Toast.makeText(context, "AirPlane mode is off", Toast.LENGTH_SHORT).show();         }     }       private static boolean isAirplaneModeOn(Context context) {         return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;     } } Output: Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now! Last Updated : 18 Jan, 2022 Like Article Save Article Previous Next Similar Reads
__label__pos
0.94187
VueJS 2: Tìm hiểu Methods Methods không còn xa lạ với nhưng bạn đã từng tìm hiểu qua lập trình hướng đối tượng phải không nào,  nó là những hàm đặc biệt thể hiện cho những hành động của một đối tượng. Vậy trong VueJS cách trình bày methods như thế nào để đúng chuẩn thì trong bài này chúng ta cùng tìm hiểu nhé. Methods trong VueJS Việc phân chia từng phần trong VueJS giúp việc quản lý của nó trở nên đơn giản hơn, ví dụ với dữ liệu thì bạn sẽ lưu trữ trong key data. Ví dụ var vm = new Vue({ el: '#example', data: { message: 'Chào mừng đến với freetuts.net', author : "[email protected]" } }); Nếu chúng ta muốn tạo một hàm để xử lý dữ liệu thì có thể tạo nó ngay trong data luôn. Code RUN <div id="example"> <p>"{{ showMessage() }}"</p> </div> <script language="javascript"> var vm = new Vue({ el: '#example', data: { message: 'Chào mừng đến với freetuts.net', showMessage : function(){ return "[" + this.message + "]"; } } }); </script> Cách làm này không thực sự hay lắm, vì vậy VueJS tạo ra một  key methods để chúng ta tạo các hàm ở bên trong đó. Như ở ví dụ trên thì mình sẽ viết lại như sau. Code RUN <div id="example"> <p>"{{ showMessage() }}"</p> </div> <script language="javascript"> var vm = new Vue({ el: '#example', data: { message: 'Chào mừng đến với freetuts.net' }, methods : { showMessage : function(){ return "[" + this.message + "]"; } } }); </script> Việc phân chia nơi lưu trữ data và methods giúp cho chương trình sáng hơn, quản lý code dễ hơn. Lưu ý: Việc xử lý của các methods sẽ không được cached, vì vậy cho dù bạn gọi một method nhiều lần thì nó cũng sẽ tính toán lại từ đầu. Ví dụ bạn có một method tính tổng hai số A và B và bạn gọi method này 2 lần thì nó sẽ thực hiện phép toán cộng hai lần, điều này khác hoàn toàn với computed. Nguồn: freetuts.net KHÓA HỌC ĐANG GIẢM GIÁ UNICA - Lập trình Web tốc độ cao, thời gian thực với NodeJS (Giảng viên: ) XEM UNICA - Thành thạo với Google Spreadsheets (Giảng viên: ) XEM UNICA - Học jQuery từ cơ bản đến nâng cao (Giảng viên: ) XEM UNICA - Toàn tập ngôn ngữ lập trình C# (Giảng viên: ) XEM UNICA - Lập trình WinForm với C#: 10 ứng dụng (Giảng viên: ) XEM
__label__pos
0.555766
js/src/jsapi.cpp author Luke Wagner <[email protected]> Tue, 04 Sep 2012 14:43:25 -0700 changeset 107555 46c3160c248125f2e493070d5c8089e678b0d98d parent 107435 f27c74c5ac8044453ad4ed38f9cc362daa444874 child 107579 acec40170961cea7d91c3f58fab338e6f01e1939 permissions -rw-r--r-- Bug 792235 - rm JS_SuspendRequest (r=mrbkap) /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sw=4 et tw=78: * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * JavaScript API. */ #include "mozilla/FloatingPoint.h" #include "mozilla/ThreadLocal.h" #include <ctype.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include "jstypes.h" #include "jsutil.h" #include "jsclist.h" #include "jsprf.h" #include "jsapi.h" #include "jsarray.h" #include "jsatom.h" #include "jsbool.h" #include "jsclone.h" #include "jscntxt.h" #include "jsversion.h" #include "jsdate.h" #include "jsdtoa.h" #include "jsexn.h" #include "jsfun.h" #include "jsgc.h" #include "jsinterp.h" #include "jsiter.h" #include "jslock.h" #include "jsmath.h" #include "jsnativestack.h" #include "jsnum.h" #include "json.h" #include "jsobj.h" #include "jsopcode.h" #include "jsprobes.h" #include "jsproxy.h" #include "jsscope.h" #include "jsscript.h" #include "jsstr.h" #include "prmjtime.h" #include "jsweakmap.h" #include "jsworkers.h" #include "jswrapper.h" #include "jstypedarray.h" #include "jsxml.h" #include "builtin/Eval.h" #include "builtin/MapObject.h" #include "builtin/RegExp.h" #include "builtin/ParallelArray.h" #include "ds/LifoAlloc.h" #include "frontend/BytecodeCompiler.h" #include "gc/Marking.h" #include "gc/Memory.h" #include "js/MemoryMetrics.h" #include "vm/NumericConversions.h" #include "vm/StringBuffer.h" #include "vm/Xdr.h" #include "yarr/BumpPointerAllocator.h" #include "jsatominlines.h" #include "jsinferinlines.h" #include "jsinterpinlines.h" #include "jsobjinlines.h" #include "jsscopeinlines.h" #include "jsscriptinlines.h" #include "vm/ObjectImpl-inl.h" #include "vm/RegExpObject-inl.h" #include "vm/RegExpStatics-inl.h" #include "vm/Stack-inl.h" #include "vm/String-inl.h" #if ENABLE_YARR_JIT #include "assembler/jit/ExecutableAllocator.h" #include "methodjit/Logging.h" #endif #ifdef JS_METHODJIT #include "ion/Ion.h" #endif using namespace js; using namespace js::gc; using namespace js::types; using js::frontend::Parser; bool JS::detail::CallMethodIfWrapped(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args) { const Value &thisv = args.thisv(); JS_ASSERT(!test(thisv)); if (thisv.isObject()) { JSObject &thisObj = args.thisv().toObject(); if (thisObj.isProxy()) return Proxy::nativeCall(cx, test, impl, args); } ReportIncompatible(cx, args); return false; } /* * This class is a version-establishing barrier at the head of a VM entry or * re-entry. It ensures that: * * - |newVersion| is the starting (default) version used for the context. * - The starting version state is not an override. * - Overrides in the VM session are not propagated to the caller. */ class AutoVersionAPI { JSContext * const cx; JSVersion oldDefaultVersion; bool oldHasVersionOverride; JSVersion oldVersionOverride; #ifdef DEBUG unsigned oldCompileOptions; #endif JSVersion newVersion; public: AutoVersionAPI(JSContext *cx, JSVersion newVersion) : cx(cx), oldDefaultVersion(cx->getDefaultVersion()), oldHasVersionOverride(cx->isVersionOverridden()), oldVersionOverride(oldHasVersionOverride ? cx->findVersion() : JSVERSION_UNKNOWN) #ifdef DEBUG , oldCompileOptions(cx->getCompileOptions()) #endif { #if JS_HAS_XML_SUPPORT // For backward compatibility, AutoVersionAPI clobbers the // JSOPTION_MOAR_XML bit in cx, but not the JSOPTION_ALLOW_XML bit. newVersion = JSVersion(newVersion | (oldDefaultVersion & VersionFlags::ALLOW_XML)); #endif this->newVersion = newVersion; cx->clearVersionOverride(); cx->setDefaultVersion(newVersion); } ~AutoVersionAPI() { cx->setDefaultVersion(oldDefaultVersion); if (oldHasVersionOverride) cx->overrideVersion(oldVersionOverride); else cx->clearVersionOverride(); JS_ASSERT(oldCompileOptions == cx->getCompileOptions()); } /* The version that this scoped-entity establishes. */ JSVersion version() const { return newVersion; } }; #ifdef HAVE_VA_LIST_AS_ARRAY #define JS_ADDRESSOF_VA_LIST(ap) ((va_list *)(ap)) #else #define JS_ADDRESSOF_VA_LIST(ap) (&(ap)) #endif #ifdef JS_USE_JSID_STRUCT_TYPES jsid JS_DEFAULT_XML_NAMESPACE_ID = { size_t(JSID_TYPE_DEFAULT_XML_NAMESPACE) }; jsid JSID_VOID = { size_t(JSID_TYPE_VOID) }; jsid JSID_EMPTY = { size_t(JSID_TYPE_OBJECT) }; #endif const jsval JSVAL_NULL = IMPL_TO_JSVAL(BUILD_JSVAL(JSVAL_TAG_NULL, 0)); const jsval JSVAL_ZERO = IMPL_TO_JSVAL(BUILD_JSVAL(JSVAL_TAG_INT32, 0)); const jsval JSVAL_ONE = IMPL_TO_JSVAL(BUILD_JSVAL(JSVAL_TAG_INT32, 1)); const jsval JSVAL_FALSE = IMPL_TO_JSVAL(BUILD_JSVAL(JSVAL_TAG_BOOLEAN, JS_FALSE)); const jsval JSVAL_TRUE = IMPL_TO_JSVAL(BUILD_JSVAL(JSVAL_TAG_BOOLEAN, JS_TRUE)); const jsval JSVAL_VOID = IMPL_TO_JSVAL(BUILD_JSVAL(JSVAL_TAG_UNDEFINED, 0)); /* Make sure that jschar is two bytes unsigned integer */ JS_STATIC_ASSERT((jschar)-1 > 0); JS_STATIC_ASSERT(sizeof(jschar) == 2); JS_PUBLIC_API(int64_t) JS_Now() { return PRMJ_Now(); } JS_PUBLIC_API(jsval) JS_GetNaNValue(JSContext *cx) { return cx->runtime->NaNValue; } JS_PUBLIC_API(jsval) JS_GetNegativeInfinityValue(JSContext *cx) { return cx->runtime->negativeInfinityValue; } JS_PUBLIC_API(jsval) JS_GetPositiveInfinityValue(JSContext *cx) { return cx->runtime->positiveInfinityValue; } JS_PUBLIC_API(jsval) JS_GetEmptyStringValue(JSContext *cx) { return STRING_TO_JSVAL(cx->runtime->emptyString); } JS_PUBLIC_API(JSString *) JS_GetEmptyString(JSRuntime *rt) { JS_ASSERT(rt->hasContexts()); return rt->emptyString; } static void AssertHeapIsIdle(JSRuntime *rt) { JS_ASSERT(rt->heapState == JSRuntime::Idle); } static void AssertHeapIsIdle(JSContext *cx) { AssertHeapIsIdle(cx->runtime); } static void AssertHeapIsIdleOrIterating(JSRuntime *rt) { JS_ASSERT(rt->heapState != JSRuntime::Collecting); } static void AssertHeapIsIdleOrIterating(JSContext *cx) { AssertHeapIsIdleOrIterating(cx->runtime); } static void AssertHeapIsIdleOrStringIsFlat(JSContext *cx, JSString *str) { /* * We allow some functions to be called during a GC as long as the argument * is a flat string, since that will not cause allocation. */ JS_ASSERT_IF(cx->runtime->isHeapBusy(), str->isFlat()); } JS_PUBLIC_API(JSBool) JS_ConvertArguments(JSContext *cx, unsigned argc, jsval *argv, const char *format, ...) { va_list ap; JSBool ok; AssertHeapIsIdle(cx); va_start(ap, format); ok = JS_ConvertArgumentsVA(cx, argc, argv, format, ap); va_end(ap); return ok; } JS_PUBLIC_API(JSBool) JS_ConvertArgumentsVA(JSContext *cx, unsigned argc, jsval *argv, const char *format, va_list ap) { jsval *sp; JSBool required; char c; double d; JSString *str; RootedObject obj(cx); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, JSValueArray(argv - 2, argc + 2)); sp = argv; required = JS_TRUE; while ((c = *format++) != '\0') { if (isspace(c)) continue; if (c == '/') { required = JS_FALSE; continue; } if (sp == argv + argc) { if (required) { if (JSFunction *fun = ReportIfNotFunction(cx, argv[-2])) { char numBuf[12]; JS_snprintf(numBuf, sizeof numBuf, "%u", argc); JSAutoByteString funNameBytes; if (const char *name = GetFunctionNameBytes(cx, fun, &funNameBytes)) { JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_MORE_ARGS_NEEDED, name, numBuf, (argc == 1) ? "" : "s"); } } return JS_FALSE; } break; } switch (c) { case 'b': *va_arg(ap, JSBool *) = ToBoolean(*sp); break; case 'c': if (!JS_ValueToUint16(cx, *sp, va_arg(ap, uint16_t *))) return JS_FALSE; break; case 'i': if (!JS_ValueToECMAInt32(cx, *sp, va_arg(ap, int32_t *))) return JS_FALSE; break; case 'u': if (!JS_ValueToECMAUint32(cx, *sp, va_arg(ap, uint32_t *))) return JS_FALSE; break; case 'j': if (!JS_ValueToInt32(cx, *sp, va_arg(ap, int32_t *))) return JS_FALSE; break; case 'd': if (!JS_ValueToNumber(cx, *sp, va_arg(ap, double *))) return JS_FALSE; break; case 'I': if (!JS_ValueToNumber(cx, *sp, &d)) return JS_FALSE; *va_arg(ap, double *) = ToInteger(d); break; case 'S': case 'W': str = ToString(cx, *sp); if (!str) return JS_FALSE; *sp = STRING_TO_JSVAL(str); if (c == 'W') { JSFixedString *fixed = str->ensureFixed(cx); if (!fixed) return JS_FALSE; *va_arg(ap, const jschar **) = fixed->chars(); } else { *va_arg(ap, JSString **) = str; } break; case 'o': if (!js_ValueToObjectOrNull(cx, *sp, &obj)) return JS_FALSE; *sp = OBJECT_TO_JSVAL(obj); *va_arg(ap, JSObject **) = obj; break; case 'f': obj = ReportIfNotFunction(cx, *sp); if (!obj) return JS_FALSE; *sp = OBJECT_TO_JSVAL(obj); *va_arg(ap, JSFunction **) = obj->toFunction(); break; case 'v': *va_arg(ap, jsval *) = *sp; break; case '*': break; default: JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_CHAR, format); return JS_FALSE; } sp++; } return JS_TRUE; } JS_PUBLIC_API(JSBool) JS_ConvertValue(JSContext *cx, jsval valueArg, JSType type, jsval *vp) { RootedValue value(cx, valueArg); JSBool ok; RootedObject obj(cx); JSString *str; double d; AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, value); switch (type) { case JSTYPE_VOID: *vp = JSVAL_VOID; ok = JS_TRUE; break; case JSTYPE_OBJECT: ok = js_ValueToObjectOrNull(cx, value, &obj); if (ok) *vp = OBJECT_TO_JSVAL(obj); break; case JSTYPE_FUNCTION: *vp = value; obj = ReportIfNotFunction(cx, *vp); ok = (obj != NULL); break; case JSTYPE_STRING: str = ToString(cx, value); ok = (str != NULL); if (ok) *vp = STRING_TO_JSVAL(str); break; case JSTYPE_NUMBER: ok = JS_ValueToNumber(cx, value, &d); if (ok) *vp = DOUBLE_TO_JSVAL(d); break; case JSTYPE_BOOLEAN: *vp = BooleanValue(ToBoolean(value)); return JS_TRUE; default: { char numBuf[12]; JS_snprintf(numBuf, sizeof numBuf, "%d", (int)type); JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_TYPE, numBuf); ok = JS_FALSE; break; } } return ok; } JS_PUBLIC_API(JSBool) JS_ValueToObject(JSContext *cx, jsval valueArg, JSObject **objpArg) { RootedValue value(cx, valueArg); RootedObject objp(cx, *objpArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, value); if (!js_ValueToObjectOrNull(cx, value, &objp)) return false; *objpArg = objp; return true; } JS_PUBLIC_API(JSFunction *) JS_ValueToFunction(JSContext *cx, jsval valueArg) { RootedValue value(cx, valueArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, value); return ReportIfNotFunction(cx, value); } JS_PUBLIC_API(JSFunction *) JS_ValueToConstructor(JSContext *cx, jsval valueArg) { RootedValue value(cx, valueArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, value); return ReportIfNotFunction(cx, value); } JS_PUBLIC_API(JSString *) JS_ValueToString(JSContext *cx, jsval valueArg) { RootedValue value(cx, valueArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, value); return ToString(cx, value); } JS_PUBLIC_API(JSString *) JS_ValueToSource(JSContext *cx, jsval valueArg) { RootedValue value(cx, valueArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, value); return js_ValueToSource(cx, value); } JS_PUBLIC_API(JSBool) JS_ValueToNumber(JSContext *cx, jsval valueArg, double *dp) { RootedValue value(cx, valueArg); return JS::ToNumber(cx, value, dp); } JS_PUBLIC_API(JSBool) JS_DoubleIsInt32(double d, int32_t *ip) { return MOZ_DOUBLE_IS_INT32(d, ip); } JS_PUBLIC_API(int32_t) JS_DoubleToInt32(double d) { return ToInt32(d); } JS_PUBLIC_API(uint32_t) JS_DoubleToUint32(double d) { return ToUint32(d); } JS_PUBLIC_API(JSBool) JS_ValueToECMAInt32(JSContext *cx, jsval valueArg, int32_t *ip) { RootedValue value(cx, valueArg); return JS::ToInt32(cx, value, ip); } JS_PUBLIC_API(JSBool) JS_ValueToECMAUint32(JSContext *cx, jsval valueArg, uint32_t *ip) { RootedValue value(cx, valueArg); return JS::ToUint32(cx, value, ip); } JS_PUBLIC_API(JSBool) JS_ValueToInt64(JSContext *cx, jsval valueArg, int64_t *ip) { RootedValue value(cx, valueArg); return JS::ToInt64(cx, value, ip); } JS_PUBLIC_API(JSBool) JS_ValueToUint64(JSContext *cx, jsval valueArg, uint64_t *ip) { RootedValue value(cx, valueArg); return JS::ToUint64(cx, value, ip); } JS_PUBLIC_API(JSBool) JS_ValueToInt32(JSContext *cx, jsval vArg, int32_t *ip) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); RootedValue v(cx, vArg); assertSameCompartment(cx, v); if (v.isInt32()) { *ip = v.toInt32(); return true; } double d; if (v.isDouble()) { d = v.toDouble(); } else if (!ToNumberSlow(cx, v, &d)) { return false; } if (MOZ_DOUBLE_IS_NaN(d) || d <= -2147483649.0 || 2147483648.0 <= d) { js_ReportValueError(cx, JSMSG_CANT_CONVERT, JSDVG_SEARCH_STACK, v, NullPtr()); return false; } *ip = (int32_t) floor(d + 0.5); /* Round to nearest */ return true; } JS_PUBLIC_API(JSBool) JS_ValueToUint16(JSContext *cx, jsval valueArg, uint16_t *ip) { RootedValue value(cx, valueArg); return ToUint16(cx, value, ip); } JS_PUBLIC_API(JSBool) JS_ValueToBoolean(JSContext *cx, jsval valueArg, JSBool *bp) { RootedValue value(cx, valueArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, value); *bp = ToBoolean(value); return JS_TRUE; } JS_PUBLIC_API(JSType) JS_TypeOfValue(JSContext *cx, jsval valueArg) { RootedValue value(cx, valueArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, value); return TypeOfValue(cx, value); } JS_PUBLIC_API(const char *) JS_GetTypeName(JSContext *cx, JSType type) { if ((unsigned)type >= (unsigned)JSTYPE_LIMIT) return NULL; return TypeStrings[type]; } JS_PUBLIC_API(JSBool) JS_StrictlyEqual(JSContext *cx, jsval value1Arg, jsval value2Arg, JSBool *equal) { RootedValue value1(cx, value1Arg); RootedValue value2(cx, value2Arg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, value1, value2); bool eq; if (!StrictlyEqual(cx, value1, value2, &eq)) return false; *equal = eq; return true; } JS_PUBLIC_API(JSBool) JS_LooselyEqual(JSContext *cx, jsval value1Arg, jsval value2Arg, JSBool *equal) { RootedValue value1(cx, value1Arg); RootedValue value2(cx, value2Arg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, value1, value2); bool eq; if (!LooselyEqual(cx, value1, value2, &eq)) return false; *equal = eq; return true; } JS_PUBLIC_API(JSBool) JS_SameValue(JSContext *cx, jsval value1Arg, jsval value2Arg, JSBool *same) { RootedValue value1(cx, value1Arg); RootedValue value2(cx, value2Arg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, value1, value2); bool s; if (!SameValue(cx, value1, value2, &s)) return false; *same = s; return true; } JS_PUBLIC_API(JSBool) JS_IsBuiltinEvalFunction(JSFunction *fun) { return IsAnyBuiltinEval(fun); } JS_PUBLIC_API(JSBool) JS_IsBuiltinFunctionConstructor(JSFunction *fun) { return IsBuiltinFunctionConstructor(fun); } /************************************************************************/ /* * Has a new runtime ever been created? This flag is used to detect unsafe * changes to js_CStringsAreUTF8 after a runtime has been created, and to * control things that should happen only once across all runtimes. */ static JSBool js_NewRuntimeWasCalled = JS_FALSE; /* * Thread Local Storage slot for storing the runtime for a thread. */ namespace JS { mozilla::ThreadLocal<JSRuntime *> TlsRuntime; #ifdef DEBUG JS_FRIEND_API(void) EnterAssertNoGCScope() { ++TlsRuntime.get()->gcAssertNoGCDepth; } JS_FRIEND_API(void) LeaveAssertNoGCScope() { --TlsRuntime.get()->gcAssertNoGCDepth; JS_ASSERT(TlsRuntime.get()->gcAssertNoGCDepth >= 0); } JS_FRIEND_API(bool) InNoGCScope() { return TlsRuntime.get()->gcAssertNoGCDepth > 0; } JS_FRIEND_API(bool) NeedRelaxedRootChecks() { return TlsRuntime.get()->gcRelaxRootChecks; } #else JS_FRIEND_API(void) EnterAssertNoGCScope() {} JS_FRIEND_API(void) LeaveAssertNoGCScope() {} JS_FRIEND_API(bool) InNoGCScope() { return false; } JS_FRIEND_API(bool) NeedRelaxedRootChecks() { return false; } #endif } /* namespace JS */ static const JSSecurityCallbacks NullSecurityCallbacks = { }; JSRuntime::JSRuntime() : atomsCompartment(NULL), #ifdef JS_THREADSAFE ownerThread_(NULL), #endif tempLifoAlloc(TEMP_LIFO_ALLOC_PRIMARY_CHUNK_SIZE), freeLifoAlloc(TEMP_LIFO_ALLOC_PRIMARY_CHUNK_SIZE), execAlloc_(NULL), bumpAlloc_(NULL), #ifdef JS_METHODJIT jaegerRuntime_(NULL), #endif selfHostedGlobal_(NULL), nativeStackBase(0), nativeStackQuota(0), interpreterFrames(NULL), cxCallback(NULL), destroyCompartmentCallback(NULL), compartmentNameCallback(NULL), activityCallback(NULL), activityCallbackArg(NULL), #ifdef JS_THREADSAFE requestDepth(0), # ifdef DEBUG checkRequestDepth(0), # endif #endif gcSystemAvailableChunkListHead(NULL), gcUserAvailableChunkListHead(NULL), gcKeepAtoms(0), gcBytes(0), gcMaxBytes(0), gcMaxMallocBytes(0), gcNumArenasFreeCommitted(0), gcVerifyPreData(NULL), gcVerifyPostData(NULL), gcChunkAllocationSinceLastGC(false), gcNextFullGCTime(0), gcLastGCTime(0), gcJitReleaseTime(0), gcMode(JSGC_MODE_GLOBAL), gcHighFrequencyGC(false), gcHighFrequencyTimeThreshold(1000), gcHighFrequencyLowLimitBytes(100 * 1024 * 1024), gcHighFrequencyHighLimitBytes(500 * 1024 * 1024), gcHighFrequencyHeapGrowthMax(3.0), gcHighFrequencyHeapGrowthMin(1.5), gcLowFrequencyHeapGrowth(1.5), gcDynamicHeapGrowth(false), gcDynamicMarkSlice(false), gcShouldCleanUpEverything(false), gcIsNeeded(0), gcWeakMapList(NULL), gcStats(thisFromCtor()), gcNumber(0), gcStartNumber(0), gcIsFull(false), gcTriggerReason(gcreason::NO_REASON), gcStrictCompartmentChecking(false), gcDisableStrictProxyCheckingCount(0), gcIncrementalState(gc::NO_INCREMENTAL), gcLastMarkSlice(false), gcSweepOnBackgroundThread(false), gcSweepingCompartments(NULL), gcSweepPhase(0), gcSweepCompartmentIndex(0), gcSweepKindIndex(0), gcArenasAllocatedDuringSweep(NULL), gcInterFrameGC(0), gcSliceBudget(SliceBudget::Unlimited), gcIncrementalEnabled(true), gcExactScanningEnabled(true), #ifdef DEBUG gcRelaxRootChecks(false), gcAssertNoGCDepth(0), #endif gcPoke(false), heapState(Idle), #ifdef JS_GC_ZEAL gcZeal_(0), gcZealFrequency(0), gcNextScheduled(0), gcDeterministicOnly(false), gcIncrementalLimit(0), #endif gcValidate(true), gcCallback(NULL), gcSliceCallback(NULL), gcFinalizeCallback(NULL), analysisPurgeCallback(NULL), analysisPurgeTriggerBytes(0), gcMallocBytes(0), gcBlackRootsTraceOp(NULL), gcBlackRootsData(NULL), gcGrayRootsTraceOp(NULL), gcGrayRootsData(NULL), autoGCRooters(NULL), scriptAndCountsVector(NULL), NaNValue(UndefinedValue()), negativeInfinityValue(UndefinedValue()), positiveInfinityValue(UndefinedValue()), emptyString(NULL), sourceHook(NULL), debugMode(false), spsProfiler(thisFromCtor()), profilingScripts(false), alwaysPreserveCode(false), hadOutOfMemory(false), debugScopes(NULL), data(NULL), gcLock(NULL), gcHelperThread(thisFromCtor()), #ifdef JS_THREADSAFE sourceCompressorThread(thisFromCtor()), #endif defaultFreeOp_(thisFromCtor(), false), debuggerMutations(0), securityCallbacks(const_cast<JSSecurityCallbacks *>(&NullSecurityCallbacks)), DOMcallbacks(NULL), destroyPrincipals(NULL), structuredCloneCallbacks(NULL), telemetryCallback(NULL), propertyRemovals(0), thousandsSeparator(0), decimalSeparator(0), numGrouping(0), waiveGCQuota(false), mathCache_(NULL), dtoaState(NULL), trustedPrincipals_(NULL), wrapObjectCallback(TransparentObjectWrapper), sameCompartmentWrapObjectCallback(NULL), preWrapObjectCallback(NULL), preserveWrapperCallback(NULL), #ifdef DEBUG noGCOrAllocationCheck(0), #endif inOOMReport(0), jitHardening(false), ionTop(NULL), ionJSContext(NULL), ionStackLimit(0), ionActivation(NULL), ionReturnOverride_(MagicValue(JS_ARG_POISON)) { /* Initialize infallibly first, so we can goto bad and JS_DestroyRuntime. */ JS_INIT_CLIST(&contextList); JS_INIT_CLIST(&debuggerList); PodZero(&debugHooks); PodZero(&atomState); #if JS_STACK_GROWTH_DIRECTION > 0 nativeStackLimit = UINTPTR_MAX; #endif } bool JSRuntime::init(uint32_t maxbytes) { #ifdef JS_THREADSAFE ownerThread_ = PR_GetCurrentThread(); #endif JS::TlsRuntime.set(this); #ifdef JS_METHODJIT_SPEW JMCheckLogging(); #endif #if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) PodArrayZero(thingGCRooters); #endif if (!js_InitGC(this, maxbytes)) return false; if (!gcMarker.init()) return false; const char *size = getenv("JSGC_MARK_STACK_LIMIT"); if (size) SetMarkStackLimit(this, atoi(size)); if (!(atomsCompartment = this->new_<JSCompartment>(this)) || !atomsCompartment->init(NULL) || !compartments.append(atomsCompartment)) { js_delete(atomsCompartment); return false; } atomsCompartment->isSystemCompartment = true; atomsCompartment->setGCLastBytes(8192, 8192, GC_NORMAL); if (!InitAtoms(this)) return false; if (!InitRuntimeNumberState(this)) return false; dtoaState = js_NewDtoaState(); if (!dtoaState) return false; if (!stackSpace.init()) return false; if (!scriptFilenameTable.init()) return false; #ifdef JS_THREADSAFE # ifdef JS_ION workerThreadState = this->new_<WorkerThreadState>(); if (!workerThreadState || !workerThreadState->init(this)) return false; # endif if (!sourceCompressorThread.init()) return false; #endif if (!evalCache.init()) return false; debugScopes = this->new_<DebugScopes>(this); if (!debugScopes || !debugScopes->init()) { js_delete(debugScopes); return false; } nativeStackBase = GetNativeStackBase(); return true; } JSRuntime::~JSRuntime() { #ifdef JS_THREADSAFE clearOwnerThread(); #endif js_delete(debugScopes); /* * Even though all objects in the compartment are dead, we may have keep * some filenames around because of gcKeepAtoms. */ FreeScriptFilenames(this); #ifdef JS_THREADSAFE # ifdef JS_ION js_delete(workerThreadState); # endif sourceCompressorThread.finish(); #endif #ifdef DEBUG /* Don't hurt everyone in leaky ol' Mozilla with a fatal JS_ASSERT! */ if (!JS_CLIST_IS_EMPTY(&contextList)) { unsigned cxcount = 0; for (ContextIter acx(this); !acx.done(); acx.next()) { fprintf(stderr, "JS API usage error: found live context at %p\n", (void *) acx.get()); cxcount++; } fprintf(stderr, "JS API usage error: %u context%s left in runtime upon JS_DestroyRuntime.\n", cxcount, (cxcount == 1) ? "" : "s"); } #endif FinishRuntimeNumberState(this); FinishAtoms(this); if (dtoaState) js_DestroyDtoaState(dtoaState); js_FinishGC(this); #ifdef JS_THREADSAFE if (gcLock) PR_DestroyLock(gcLock); #endif js_delete(bumpAlloc_); js_delete(mathCache_); #ifdef JS_METHODJIT js_delete(jaegerRuntime_); #endif js_delete(execAlloc_); /* Delete after jaegerRuntime_. */ } #ifdef JS_THREADSAFE void JSRuntime::setOwnerThread() { JS_ASSERT(ownerThread_ == (void *)0xc1ea12); /* "clear" */ JS_ASSERT(requestDepth == 0); JS_ASSERT(js_NewRuntimeWasCalled); JS_ASSERT(JS::TlsRuntime.get() == NULL); ownerThread_ = PR_GetCurrentThread(); JS::TlsRuntime.set(this); nativeStackBase = GetNativeStackBase(); if (nativeStackQuota) JS_SetNativeStackQuota(this, nativeStackQuota); } void JSRuntime::clearOwnerThread() { assertValidThread(); JS_ASSERT(requestDepth == 0); JS_ASSERT(js_NewRuntimeWasCalled); ownerThread_ = (void *)0xc1ea12; /* "clear" */ JS::TlsRuntime.set(NULL); nativeStackBase = 0; #if JS_STACK_GROWTH_DIRECTION > 0 nativeStackLimit = UINTPTR_MAX; #else nativeStackLimit = 0; #endif } JS_FRIEND_API(void) JSRuntime::abortIfWrongThread() const { if (ownerThread_ != PR_GetCurrentThread()) MOZ_CRASH(); if (this != JS::TlsRuntime.get()) MOZ_CRASH(); } JS_FRIEND_API(void) JSRuntime::assertValidThread() const { JS_ASSERT(ownerThread_ == PR_GetCurrentThread()); JS_ASSERT(this == JS::TlsRuntime.get()); } #endif /* JS_THREADSAFE */ JS_PUBLIC_API(JSRuntime *) JS_NewRuntime(uint32_t maxbytes) { if (!js_NewRuntimeWasCalled) { #ifdef DEBUG /* * This code asserts that the numbers associated with the error names * in jsmsg.def are monotonically increasing. It uses values for the * error names enumerated in jscntxt.c. It's not a compile-time check * but it's better than nothing. */ int errorNumber = 0; #define MSG_DEF(name, number, count, exception, format) \ JS_ASSERT(name == errorNumber++); #include "js.msg" #undef MSG_DEF #define MSG_DEF(name, number, count, exception, format) \ JS_BEGIN_MACRO \ unsigned numfmtspecs = 0; \ const char *fmt; \ for (fmt = format; *fmt != '\0'; fmt++) { \ if (*fmt == '{' && isdigit(fmt[1])) \ ++numfmtspecs; \ } \ JS_ASSERT(count == numfmtspecs); \ JS_END_MACRO; #include "js.msg" #undef MSG_DEF #endif /* DEBUG */ InitMemorySubsystem(); if (!JS::TlsRuntime.init()) return NULL; js_NewRuntimeWasCalled = JS_TRUE; } JSRuntime *rt = js_new<JSRuntime>(); if (!rt) return NULL; #if defined(JS_METHODJIT) && defined(JS_ION) if (!ion::InitializeIon()) return NULL; #endif if (!rt->init(maxbytes)) { JS_DestroyRuntime(rt); return NULL; } Probes::createRuntime(rt); return rt; } JS_PUBLIC_API(void) JS_DestroyRuntime(JSRuntime *rt) { Probes::destroyRuntime(rt); js_delete(rt); } JS_PUBLIC_API(void) JS_ShutDown(void) { Probes::shutdown(); PRMJ_NowShutdown(); } JS_PUBLIC_API(void *) JS_GetRuntimePrivate(JSRuntime *rt) { return rt->data; } JS_PUBLIC_API(void) JS_SetRuntimePrivate(JSRuntime *rt, void *data) { rt->data = data; } #ifdef JS_THREADSAFE static void StartRequest(JSContext *cx) { JSRuntime *rt = cx->runtime; rt->assertValidThread(); if (rt->requestDepth) { rt->requestDepth++; } else { /* Indicate that a request is running. */ rt->requestDepth = 1; if (rt->activityCallback) rt->activityCallback(rt->activityCallbackArg, true); } } static void StopRequest(JSContext *cx) { JSRuntime *rt = cx->runtime; rt->assertValidThread(); JS_ASSERT(rt->requestDepth != 0); if (rt->requestDepth != 1) { rt->requestDepth--; } else { rt->conservativeGC.updateForRequestEnd(); rt->requestDepth = 0; if (rt->activityCallback) rt->activityCallback(rt->activityCallbackArg, false); } } #endif /* JS_THREADSAFE */ JS_PUBLIC_API(void) JS_BeginRequest(JSContext *cx) { #ifdef JS_THREADSAFE cx->outstandingRequests++; StartRequest(cx); #endif } JS_PUBLIC_API(void) JS_EndRequest(JSContext *cx) { #ifdef JS_THREADSAFE JS_ASSERT(cx->outstandingRequests != 0); cx->outstandingRequests--; StopRequest(cx); #endif } JS_PUBLIC_API(JSBool) JS_IsInRequest(JSRuntime *rt) { #ifdef JS_THREADSAFE rt->assertValidThread(); return rt->requestDepth != 0; #else return false; #endif } JS_PUBLIC_API(JSContextCallback) JS_SetContextCallback(JSRuntime *rt, JSContextCallback cxCallback) { JSContextCallback old; old = rt->cxCallback; rt->cxCallback = cxCallback; return old; } JS_PUBLIC_API(JSContext *) JS_NewContext(JSRuntime *rt, size_t stackChunkSize) { return NewContext(rt, stackChunkSize); } JS_PUBLIC_API(void) JS_DestroyContext(JSContext *cx) { DestroyContext(cx, DCM_FORCE_GC); } JS_PUBLIC_API(void) JS_DestroyContextNoGC(JSContext *cx) { DestroyContext(cx, DCM_NO_GC); } JS_PUBLIC_API(void *) JS_GetContextPrivate(JSContext *cx) { return cx->data; } JS_PUBLIC_API(void) JS_SetContextPrivate(JSContext *cx, void *data) { cx->data = data; } JS_PUBLIC_API(void *) JS_GetSecondContextPrivate(JSContext *cx) { return cx->data2; } JS_PUBLIC_API(void) JS_SetSecondContextPrivate(JSContext *cx, void *data) { cx->data2 = data; } JS_PUBLIC_API(JSRuntime *) JS_GetRuntime(JSContext *cx) { return cx->runtime; } JS_PUBLIC_API(JSContext *) JS_ContextIterator(JSRuntime *rt, JSContext **iterp) { JSContext *cx = *iterp; JSCList *next = cx ? cx->link.next : rt->contextList.next; cx = (next == &rt->contextList) ? NULL : JSContext::fromLinkField(next); *iterp = cx; return cx; } JS_PUBLIC_API(JSVersion) JS_GetVersion(JSContext *cx) { return VersionNumber(cx->findVersion()); } JS_PUBLIC_API(JSVersion) JS_SetVersion(JSContext *cx, JSVersion newVersion) { JS_ASSERT(VersionIsKnown(newVersion)); JS_ASSERT(!VersionHasFlags(newVersion)); JSVersion newVersionNumber = newVersion; #ifdef DEBUG unsigned coptsBefore = cx->getCompileOptions(); #endif JSVersion oldVersion = cx->findVersion(); JSVersion oldVersionNumber = VersionNumber(oldVersion); if (oldVersionNumber == newVersionNumber) return oldVersionNumber; /* No override actually occurs! */ /* We no longer support 1.4 or below. */ if (newVersionNumber != JSVERSION_DEFAULT && newVersionNumber <= JSVERSION_1_4) return oldVersionNumber; VersionCopyFlags(&newVersion, oldVersion); cx->maybeOverrideVersion(newVersion); JS_ASSERT(cx->getCompileOptions() == coptsBefore); return oldVersionNumber; } static struct v2smap { JSVersion version; const char *string; } v2smap[] = { {JSVERSION_1_0, "1.0"}, {JSVERSION_1_1, "1.1"}, {JSVERSION_1_2, "1.2"}, {JSVERSION_1_3, "1.3"}, {JSVERSION_1_4, "1.4"}, {JSVERSION_ECMA_3, "ECMAv3"}, {JSVERSION_1_5, "1.5"}, {JSVERSION_1_6, "1.6"}, {JSVERSION_1_7, "1.7"}, {JSVERSION_1_8, "1.8"}, {JSVERSION_ECMA_5, "ECMAv5"}, {JSVERSION_DEFAULT, js_default_str}, {JSVERSION_UNKNOWN, NULL}, /* must be last, NULL is sentinel */ }; JS_PUBLIC_API(const char *) JS_VersionToString(JSVersion version) { int i; for (i = 0; v2smap[i].string; i++) if (v2smap[i].version == version) return v2smap[i].string; return "unknown"; } JS_PUBLIC_API(JSVersion) JS_StringToVersion(const char *string) { int i; for (i = 0; v2smap[i].string; i++) if (strcmp(v2smap[i].string, string) == 0) return v2smap[i].version; return JSVERSION_UNKNOWN; } JS_PUBLIC_API(uint32_t) JS_GetOptions(JSContext *cx) { /* * Can't check option/version synchronization here. * We may have been synchronized with a script version that was formerly on * the stack, but has now been popped. */ return cx->allOptions(); } static unsigned SetOptionsCommon(JSContext *cx, unsigned options) { JS_ASSERT((options & JSALLOPTION_MASK) == options); unsigned oldopts = cx->allOptions(); unsigned newropts = options & JSRUNOPTION_MASK; unsigned newcopts = options & JSCOMPILEOPTION_MASK; cx->setRunOptions(newropts); cx->setCompileOptions(newcopts); cx->updateJITEnabled(); return oldopts; } JS_PUBLIC_API(uint32_t) JS_SetOptions(JSContext *cx, uint32_t options) { return SetOptionsCommon(cx, options); } JS_PUBLIC_API(uint32_t) JS_ToggleOptions(JSContext *cx, uint32_t options) { unsigned oldopts = cx->allOptions(); unsigned newopts = oldopts ^ options; return SetOptionsCommon(cx, newopts); } JS_PUBLIC_API(void) JS_SetJitHardening(JSRuntime *rt, JSBool enabled) { rt->setJitHardening(!!enabled); } JS_PUBLIC_API(const char *) JS_GetImplementationVersion(void) { return "JavaScript-C 1.8.5+ 2011-04-16"; } JS_PUBLIC_API(void) JS_SetDestroyCompartmentCallback(JSRuntime *rt, JSDestroyCompartmentCallback callback) { rt->destroyCompartmentCallback = callback; } JS_PUBLIC_API(void) JS_SetCompartmentNameCallback(JSRuntime *rt, JSCompartmentNameCallback callback) { rt->compartmentNameCallback = callback; } JS_PUBLIC_API(JSWrapObjectCallback) JS_SetWrapObjectCallbacks(JSRuntime *rt, JSWrapObjectCallback callback, JSSameCompartmentWrapObjectCallback sccallback, JSPreWrapCallback precallback) { JSWrapObjectCallback old = rt->wrapObjectCallback; rt->wrapObjectCallback = callback; rt->sameCompartmentWrapObjectCallback = sccallback; rt->preWrapObjectCallback = precallback; return old; } JS_PUBLIC_API(JSCompartment *) JS_EnterCompartment(JSContext *cx, JSRawObject target) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); JSCompartment *oldCompartment = cx->compartment; cx->enterCompartment(target->compartment()); return oldCompartment; } JS_PUBLIC_API(JSCompartment *) JS_EnterCompartmentOfScript(JSContext *cx, JSScript *target) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); GlobalObject &global = target->global(); return JS_EnterCompartment(cx, &global); } JS_PUBLIC_API(void) JS_LeaveCompartment(JSContext *cx, JSCompartment *oldCompartment) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); cx->leaveCompartment(oldCompartment); } JSAutoCompartment::JSAutoCompartment(JSContext *cx, JSRawObject target) : cx_(cx), oldCompartment_(cx->compartment) { AssertHeapIsIdleOrIterating(cx_); cx_->enterCompartment(target->compartment()); } JSAutoCompartment::JSAutoCompartment(JSContext *cx, JSScript *target) : cx_(cx), oldCompartment_(cx->compartment) { AssertHeapIsIdleOrIterating(cx_); cx_->enterCompartment(target->compartment()); } JSAutoCompartment::JSAutoCompartment(JSContext *cx, JSStackFrame *target) : cx_(cx), oldCompartment_(cx->compartment) { AssertHeapIsIdleOrIterating(cx_); cx_->enterCompartment(Valueify(target)->global().compartment()); } JSAutoCompartment::~JSAutoCompartment() { cx_->leaveCompartment(oldCompartment_); } JS_PUBLIC_API(void) JS_SetCompartmentPrivate(JSCompartment *compartment, void *data) { compartment->data = data; } JS_PUBLIC_API(void *) JS_GetCompartmentPrivate(JSCompartment *compartment) { return compartment->data; } JS_PUBLIC_API(JSBool) JS_WrapObject(JSContext *cx, JSObject **objp) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return cx->compartment->wrap(cx, objp); } JS_PUBLIC_API(JSBool) JS_WrapValue(JSContext *cx, jsval *vp) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return cx->compartment->wrap(cx, vp); } /* * Identity remapping. Not for casual consumers. * * Normally, an object's contents and its identity are inextricably linked. * Identity is determined by the address of the JSObject* in the heap, and * the contents are what is located at that address. Transplanting allows these * concepts to be separated through a combination of swapping (exchanging the * contents of two same-compartment objects) and remapping cross-compartment * identities by altering wrappers. * * The |origobj| argument should be the object whose identity needs to be * remapped, usually to another compartment. The contents of |origobj| are * destroyed. * * The |target| argument serves two purposes: * * First, |target| serves as a hint for the new identity of the object. The new * identity object will always be in the same compartment as |target|, but * if that compartment already had an object representing |origobj| (either a * cross-compartment wrapper for it, or |origobj| itself if the two arguments * are same-compartment), the existing object is used. Otherwise, |target| * itself is used. To avoid ambiguity, JS_TransplantObject always returns the * new identity. * * Second, the new identity object's contents will be those of |target|. A swap() * is used to make this happen if an object other than |target| is used. */ JS_PUBLIC_API(JSObject *) JS_TransplantObject(JSContext *cx, JSObject *origobjArg, JSObject *targetArg) { RootedObject origobj(cx, origobjArg); RootedObject target(cx, targetArg); AssertHeapIsIdle(cx); JS_ASSERT(origobj != target); JS_ASSERT(!IsCrossCompartmentWrapper(origobj)); JS_ASSERT(!IsCrossCompartmentWrapper(target)); /* * Transplantation typically allocates new wrappers in every compartment. If * an incremental GC is active, this causes every compartment to be leaked * for that GC. Hence, we finish any ongoing incremental GC before the * transplant to avoid leaks. */ if (cx->runtime->gcIncrementalState != NO_INCREMENTAL) { PrepareForIncrementalGC(cx->runtime); FinishIncrementalGC(cx->runtime, gcreason::TRANSPLANT); } JSCompartment *destination = target->compartment(); WrapperMap &map = destination->crossCompartmentWrappers; Value origv = ObjectValue(*origobj); JSObject *newIdentity; if (origobj->compartment() == destination) { // If the original object is in the same compartment as the // destination, then we know that we won't find a wrapper in the // destination's cross compartment map and that the same // object will continue to work. if (!origobj->swap(cx, target)) return NULL; newIdentity = origobj; } else if (WrapperMap::Ptr p = map.lookup(origv)) { // There might already be a wrapper for the original object in // the new compartment. If there is, we use its identity and swap // in the contents of |target|. newIdentity = &p->value.toObject(); // When we remove origv from the wrapper map, its wrapper, newIdentity, // must immediately cease to be a cross-compartment wrapper. Neuter it. map.remove(p); NukeCrossCompartmentWrapper(newIdentity); if (!newIdentity->swap(cx, target)) return NULL; } else { // Otherwise, we use |target| for the new identity object. newIdentity = target; } // Now, iterate through other scopes looking for references to the // old object, and update the relevant cross-compartment wrappers. if (!RemapAllWrappersForObject(cx, origobj, newIdentity)) return NULL; // Lastly, update the original object to point to the new one. if (origobj->compartment() != destination) { RootedObject newIdentityWrapper(cx, newIdentity); AutoCompartment ac(cx, origobj); if (!JS_WrapObject(cx, newIdentityWrapper.address())) return NULL; if (!origobj->swap(cx, newIdentityWrapper)) return NULL; origobj->compartment()->crossCompartmentWrappers.put(ObjectValue(*newIdentity), origv); } // The new identity object might be one of several things. Return it to avoid // ambiguity. return newIdentity; } /* * Some C++ objects (such as the location object and XBL) require both an XPConnect * reflector and a security wrapper for that reflector. We expect that there are * no live references to the reflector, so when we perform the transplant we turn * the security wrapper into a cross-compartment wrapper. Just in case there * happen to be live references to the reflector, we swap it out to limit the harm. */ JS_FRIEND_API(JSObject *) js_TransplantObjectWithWrapper(JSContext *cx, JSObject *origobjArg, JSObject *origwrapperArg, JSObject *targetobjArg, JSObject *targetwrapperArg) { RootedObject origobj(cx, origobjArg); RootedObject origwrapper(cx, origwrapperArg); RootedObject targetobj(cx, targetobjArg); RootedObject targetwrapper(cx, targetwrapperArg); AssertHeapIsIdle(cx); JS_ASSERT(!IsCrossCompartmentWrapper(origobj)); JS_ASSERT(!IsCrossCompartmentWrapper(origwrapper)); JS_ASSERT(!IsCrossCompartmentWrapper(targetobj)); JS_ASSERT(!IsCrossCompartmentWrapper(targetwrapper)); JSObject *newWrapper; JSCompartment *destination = targetobj->compartment(); WrapperMap &map = destination->crossCompartmentWrappers; // |origv| is the map entry we're looking up. The map entries are going to // be for |origobj|, not |origwrapper|. Value origv = ObjectValue(*origobj); // There might already be a wrapper for the original object in the new // compartment. if (WrapperMap::Ptr p = map.lookup(origv)) { // There is. Make the existing cross-compartment wrapper a same- // compartment wrapper. newWrapper = &p->value.toObject(); // When we remove origv from the wrapper map, its wrapper, newWrapper, // must immediately cease to be a cross-compartment wrapper. Neuter it. map.remove(p); NukeCrossCompartmentWrapper(newWrapper); if (!newWrapper->swap(cx, targetwrapper)) return NULL; } else { // Otherwise, use the passed-in wrapper as the same-compartment wrapper. newWrapper = targetwrapper; } // Now, iterate through other scopes looking for references to the old // object. Note that the entries in the maps are for |origobj| and not // |origwrapper|. They need to be updated to point at the new object. if (!RemapAllWrappersForObject(cx, origobj, targetobj)) return NULL; // Lastly, update things in the original compartment. Our invariants dictate // that the original compartment can only have one cross-compartment wrapper // to the new object. So we choose to update |origwrapper|, not |origobj|, // since there are probably no live direct intra-compartment references to // |origobj|. { AutoCompartment ac(cx, origobj); // We can't be sure that the reflector is completely dead. This is bad, // because it is in a weird state. To minimize potential harm we create // a new unreachable dummy object and swap it with the reflector. // After the swap we have a possibly-live object that isn't dangerous, // and a possibly-dangerous object that isn't live. RootedObject reflectorGuts(cx, NewDeadProxyObject(cx, JS_GetGlobalForObject(cx, origobj))); if (!reflectorGuts || !origobj->swap(cx, reflectorGuts)) return NULL; // Turn origwrapper into a CCW to the new object. RootedObject wrapperGuts(cx, targetobj); if (!JS_WrapObject(cx, wrapperGuts.address())) return NULL; if (!origwrapper->swap(cx, wrapperGuts)) return NULL; origwrapper->compartment()->crossCompartmentWrappers.put(ObjectValue(*targetobj), ObjectValue(*origwrapper)); } return newWrapper; } /* * Recompute all cross-compartment wrappers for an object, resetting state. * Gecko uses this to clear Xray wrappers when doing a navigation that reuses * the inner window and global object. */ JS_PUBLIC_API(JSBool) JS_RefreshCrossCompartmentWrappers(JSContext *cx, JSObject *objArg) { RootedObject obj(cx, objArg); return RemapAllWrappersForObject(cx, obj, obj); } JS_PUBLIC_API(JSObject *) JS_GetGlobalObject(JSContext *cx) { return cx->maybeDefaultCompartmentObject(); } JS_PUBLIC_API(void) JS_SetGlobalObject(JSContext *cx, JSRawObject obj) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); cx->setDefaultCompartmentObject(obj); } JS_PUBLIC_API(JSBool) JS_InitStandardClasses(JSContext *cx, JSObject *objArg) { RootedObject obj(cx, objArg); JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); cx->setDefaultCompartmentObjectIfUnset(obj); assertSameCompartment(cx, obj); Rooted<GlobalObject*> global(cx, &obj->global()); return GlobalObject::initStandardClasses(cx, global); } #define CLASP(name) (&name##Class) #define TYPED_ARRAY_CLASP(type) (&TypedArray::classes[TypedArray::type]) #define EAGER_ATOM(name) NAME_OFFSET(name) #define EAGER_CLASS_ATOM(name) NAME_OFFSET(name) #define EAGER_ATOM_AND_CLASP(name) EAGER_CLASS_ATOM(name), CLASP(name) typedef struct JSStdName { JSClassInitializerOp init; size_t atomOffset; /* offset of atom pointer in JSAtomState */ Class *clasp; } JSStdName; static Handle<PropertyName*> StdNameToPropertyName(JSContext *cx, JSStdName *stdn) { return OFFSET_TO_NAME(cx->runtime, stdn->atomOffset); } /* * Table of class initializers and their atom offsets in rt->atomState. * If you add a "standard" class, remember to update this table. */ static JSStdName standard_class_atoms[] = { {js_InitFunctionClass, EAGER_ATOM_AND_CLASP(Function)}, {js_InitObjectClass, EAGER_ATOM_AND_CLASP(Object)}, {js_InitArrayClass, EAGER_ATOM_AND_CLASP(Array)}, {js_InitBooleanClass, EAGER_ATOM_AND_CLASP(Boolean)}, {js_InitDateClass, EAGER_ATOM_AND_CLASP(Date)}, {js_InitMathClass, EAGER_ATOM_AND_CLASP(Math)}, {js_InitNumberClass, EAGER_ATOM_AND_CLASP(Number)}, {js_InitStringClass, EAGER_ATOM_AND_CLASP(String)}, {js_InitExceptionClasses, EAGER_ATOM_AND_CLASP(Error)}, {js_InitRegExpClass, EAGER_ATOM_AND_CLASP(RegExp)}, #if JS_HAS_XML_SUPPORT {js_InitXMLClass, EAGER_ATOM_AND_CLASP(XML)}, {js_InitNamespaceClass, EAGER_ATOM_AND_CLASP(Namespace)}, {js_InitQNameClass, EAGER_ATOM_AND_CLASP(QName)}, #endif #if JS_HAS_GENERATORS {js_InitIteratorClasses, EAGER_ATOM_AND_CLASP(StopIteration)}, #endif {js_InitJSONClass, EAGER_ATOM_AND_CLASP(JSON)}, {js_InitTypedArrayClasses, EAGER_CLASS_ATOM(ArrayBuffer), &js::ArrayBufferObject::protoClass}, {js_InitWeakMapClass, EAGER_CLASS_ATOM(WeakMap), &js::WeakMapClass}, {js_InitMapClass, EAGER_CLASS_ATOM(Map), &js::MapObject::class_}, {js_InitSetClass, EAGER_CLASS_ATOM(Set), &js::SetObject::class_}, {js_InitParallelArrayClass, EAGER_CLASS_ATOM(ParallelArray), &js::ParallelArrayObject::class_}, {NULL, 0, NULL} }; /* * Table of top-level function and constant names and their init functions. * If you add a "standard" global function or property, remember to update * this table. */ static JSStdName standard_class_names[] = { {js_InitObjectClass, EAGER_ATOM(eval), CLASP(Object)}, /* Global properties and functions defined by the Number class. */ {js_InitNumberClass, EAGER_ATOM(NaN), CLASP(Number)}, {js_InitNumberClass, EAGER_ATOM(Infinity), CLASP(Number)}, {js_InitNumberClass, EAGER_ATOM(isNaN), CLASP(Number)}, {js_InitNumberClass, EAGER_ATOM(isFinite), CLASP(Number)}, {js_InitNumberClass, EAGER_ATOM(parseFloat), CLASP(Number)}, {js_InitNumberClass, EAGER_ATOM(parseInt), CLASP(Number)}, /* String global functions. */ {js_InitStringClass, EAGER_ATOM(escape), CLASP(String)}, {js_InitStringClass, EAGER_ATOM(unescape), CLASP(String)}, {js_InitStringClass, EAGER_ATOM(decodeURI), CLASP(String)}, {js_InitStringClass, EAGER_ATOM(encodeURI), CLASP(String)}, {js_InitStringClass, EAGER_ATOM(decodeURIComponent), CLASP(String)}, {js_InitStringClass, EAGER_ATOM(encodeURIComponent), CLASP(String)}, #if JS_HAS_UNEVAL {js_InitStringClass, EAGER_ATOM(uneval), CLASP(String)}, #endif /* Exception constructors. */ {js_InitExceptionClasses, EAGER_CLASS_ATOM(Error), CLASP(Error)}, {js_InitExceptionClasses, EAGER_CLASS_ATOM(InternalError), CLASP(Error)}, {js_InitExceptionClasses, EAGER_CLASS_ATOM(EvalError), CLASP(Error)}, {js_InitExceptionClasses, EAGER_CLASS_ATOM(RangeError), CLASP(Error)}, {js_InitExceptionClasses, EAGER_CLASS_ATOM(ReferenceError), CLASP(Error)}, {js_InitExceptionClasses, EAGER_CLASS_ATOM(SyntaxError), CLASP(Error)}, {js_InitExceptionClasses, EAGER_CLASS_ATOM(TypeError), CLASP(Error)}, {js_InitExceptionClasses, EAGER_CLASS_ATOM(URIError), CLASP(Error)}, #if JS_HAS_XML_SUPPORT {js_InitXMLClass, EAGER_ATOM(XMLList), CLASP(XML)}, {js_InitXMLClass, EAGER_ATOM(isXMLName), CLASP(XML)}, #endif {js_InitIteratorClasses, EAGER_CLASS_ATOM(Iterator), &PropertyIteratorObject::class_}, /* Typed Arrays */ {js_InitTypedArrayClasses, EAGER_CLASS_ATOM(ArrayBuffer), &ArrayBufferClass}, {js_InitTypedArrayClasses, EAGER_CLASS_ATOM(Int8Array), TYPED_ARRAY_CLASP(TYPE_INT8)}, {js_InitTypedArrayClasses, EAGER_CLASS_ATOM(Uint8Array), TYPED_ARRAY_CLASP(TYPE_UINT8)}, {js_InitTypedArrayClasses, EAGER_CLASS_ATOM(Int16Array), TYPED_ARRAY_CLASP(TYPE_INT16)}, {js_InitTypedArrayClasses, EAGER_CLASS_ATOM(Uint16Array), TYPED_ARRAY_CLASP(TYPE_UINT16)}, {js_InitTypedArrayClasses, EAGER_CLASS_ATOM(Int32Array), TYPED_ARRAY_CLASP(TYPE_INT32)}, {js_InitTypedArrayClasses, EAGER_CLASS_ATOM(Uint32Array), TYPED_ARRAY_CLASP(TYPE_UINT32)}, {js_InitTypedArrayClasses, EAGER_CLASS_ATOM(Float32Array), TYPED_ARRAY_CLASP(TYPE_FLOAT32)}, {js_InitTypedArrayClasses, EAGER_CLASS_ATOM(Float64Array), TYPED_ARRAY_CLASP(TYPE_FLOAT64)}, {js_InitTypedArrayClasses, EAGER_CLASS_ATOM(Uint8ClampedArray), TYPED_ARRAY_CLASP(TYPE_UINT8_CLAMPED)}, {js_InitTypedArrayClasses, EAGER_CLASS_ATOM(DataView), &DataViewClass}, {js_InitWeakMapClass, EAGER_ATOM_AND_CLASP(WeakMap)}, {js_InitProxyClass, EAGER_ATOM_AND_CLASP(Proxy)}, {NULL, 0, NULL} }; static JSStdName object_prototype_names[] = { /* Object.prototype properties (global delegates to Object.prototype). */ {js_InitObjectClass, EAGER_ATOM(proto), CLASP(Object)}, #if JS_HAS_TOSOURCE {js_InitObjectClass, EAGER_ATOM(toSource), CLASP(Object)}, #endif {js_InitObjectClass, EAGER_ATOM(toString), CLASP(Object)}, {js_InitObjectClass, EAGER_ATOM(toLocaleString), CLASP(Object)}, {js_InitObjectClass, EAGER_ATOM(valueOf), CLASP(Object)}, #if JS_HAS_OBJ_WATCHPOINT {js_InitObjectClass, EAGER_ATOM(watch), CLASP(Object)}, {js_InitObjectClass, EAGER_ATOM(unwatch), CLASP(Object)}, #endif {js_InitObjectClass, EAGER_ATOM(hasOwnProperty), CLASP(Object)}, {js_InitObjectClass, EAGER_ATOM(isPrototypeOf), CLASP(Object)}, {js_InitObjectClass, EAGER_ATOM(propertyIsEnumerable), CLASP(Object)}, #if OLD_GETTER_SETTER_METHODS {js_InitObjectClass, EAGER_ATOM(defineGetter), CLASP(Object)}, {js_InitObjectClass, EAGER_ATOM(defineSetter), CLASP(Object)}, {js_InitObjectClass, EAGER_ATOM(lookupGetter), CLASP(Object)}, {js_InitObjectClass, EAGER_ATOM(lookupSetter), CLASP(Object)}, #endif {NULL, 0, NULL} }; JS_PUBLIC_API(JSBool) JS_ResolveStandardClass(JSContext *cx, JSObject *objArg, jsid id, JSBool *resolved) { RootedObject obj(cx, objArg); JSString *idstr; JSRuntime *rt; JSAtom *atom; JSStdName *stdnm; unsigned i; AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, id); *resolved = false; rt = cx->runtime; if (!rt->hasContexts() || !JSID_IS_ATOM(id)) return true; idstr = JSID_TO_STRING(id); /* Check whether we're resolving 'undefined', and define it if so. */ atom = rt->atomState.undefined; if (idstr == atom) { *resolved = true; RootedValue undefinedValue(cx, UndefinedValue()); return JSObject::defineProperty(cx, obj, atom->asPropertyName(), undefinedValue, JS_PropertyStub, JS_StrictPropertyStub, JSPROP_PERMANENT | JSPROP_READONLY); } /* Try for class constructors/prototypes named by well-known atoms. */ stdnm = NULL; for (i = 0; standard_class_atoms[i].init; i++) { JS_ASSERT(standard_class_atoms[i].clasp); atom = OFFSET_TO_NAME(rt, standard_class_atoms[i].atomOffset); if (idstr == atom) { stdnm = &standard_class_atoms[i]; break; } } if (!stdnm) { /* Try less frequently used top-level functions and constants. */ for (i = 0; standard_class_names[i].init; i++) { JS_ASSERT(standard_class_names[i].clasp); atom = StdNameToPropertyName(cx, &standard_class_names[i]); if (!atom) return false; if (idstr == atom) { stdnm = &standard_class_names[i]; break; } } if (!stdnm && !obj->getProto()) { /* * Try even less frequently used names delegated from the global * object to Object.prototype, but only if the Object class hasn't * yet been initialized. */ for (i = 0; object_prototype_names[i].init; i++) { JS_ASSERT(object_prototype_names[i].clasp); atom = StdNameToPropertyName(cx, &object_prototype_names[i]); if (!atom) return false; if (idstr == atom) { stdnm = &object_prototype_names[i]; break; } } } } if (stdnm) { /* * If this standard class is anonymous, then we don't want to resolve * by name. */ JS_ASSERT(obj->isGlobal()); if (stdnm->clasp->flags & JSCLASS_IS_ANONYMOUS) return true; if (IsStandardClassResolved(obj, stdnm->clasp)) return true; #if JS_HAS_XML_SUPPORT if ((stdnm->init == js_InitXMLClass || stdnm->init == js_InitNamespaceClass || stdnm->init == js_InitQNameClass) && !VersionHasAllowXML(cx->findVersion())) { return true; } #endif if (!stdnm->init(cx, obj)) return false; *resolved = true; } return true; } JS_PUBLIC_API(JSBool) JS_EnumerateStandardClasses(JSContext *cx, JSObject *objArg) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); /* * Check whether we need to bind 'undefined' and define it if so. * Since ES5 15.1.1.3 undefined can't be deleted. */ HandlePropertyName undefinedName = cx->names().undefined; RootedValue undefinedValue(cx, UndefinedValue()); if (!obj->nativeContains(cx, undefinedName) && !JSObject::defineProperty(cx, obj, undefinedName, undefinedValue, JS_PropertyStub, JS_StrictPropertyStub, JSPROP_PERMANENT | JSPROP_READONLY)) { return false; } /* Initialize any classes that have not been initialized yet. */ for (unsigned i = 0; standard_class_atoms[i].init; i++) { const JSStdName &stdnm = standard_class_atoms[i]; if (!js::IsStandardClassResolved(obj, stdnm.clasp) #if JS_HAS_XML_SUPPORT && ((stdnm.init != js_InitXMLClass && stdnm.init != js_InitNamespaceClass && stdnm.init != js_InitQNameClass) || VersionHasAllowXML(cx->findVersion())) #endif ) { if (!stdnm.init(cx, obj)) return false; } } return true; } static JSIdArray * NewIdArray(JSContext *cx, int length) { JSIdArray *ida; ida = (JSIdArray *) cx->calloc_(offsetof(JSIdArray, vector) + length * sizeof(jsval)); if (ida) ida->length = length; return ida; } /* * Unlike realloc(3), this function frees ida on failure. */ static JSIdArray * SetIdArrayLength(JSContext *cx, JSIdArray *ida, int length) { JSIdArray *rida; rida = (JSIdArray *) JS_realloc(cx, ida, offsetof(JSIdArray, vector) + length * sizeof(jsval)); if (!rida) { JS_DestroyIdArray(cx, ida); } else { rida->length = length; } return rida; } static JSIdArray * AddNameToArray(JSContext *cx, PropertyName *name, JSIdArray *ida, int *ip) { int i = *ip; int length = ida->length; if (i >= length) { ida = SetIdArrayLength(cx, ida, Max(length * 2, 8)); if (!ida) return NULL; JS_ASSERT(i < ida->length); } ida->vector[i].init(NameToId(name)); *ip = i + 1; return ida; } static JSIdArray * EnumerateIfResolved(JSContext *cx, Handle<JSObject*> obj, Handle<PropertyName*> name, JSIdArray *ida, int *ip, JSBool *foundp) { *foundp = obj->nativeContains(cx, name); if (*foundp) ida = AddNameToArray(cx, name, ida, ip); return ida; } JS_PUBLIC_API(JSIdArray *) JS_EnumerateResolvedStandardClasses(JSContext *cx, JSObject *objArg, JSIdArray *ida) { RootedObject obj(cx, objArg); JSRuntime *rt; int i, j, k; JSBool found; JSClassInitializerOp init; AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, ida); rt = cx->runtime; if (ida) { i = ida->length; } else { ida = NewIdArray(cx, 8); if (!ida) return NULL; i = 0; } /* Check whether 'undefined' has been resolved and enumerate it if so. */ ida = EnumerateIfResolved(cx, obj, cx->names().undefined, ida, &i, &found); if (!ida) return NULL; /* Enumerate only classes that *have* been resolved. */ Rooted<PropertyName*> name(cx); for (j = 0; standard_class_atoms[j].init; j++) { name = OFFSET_TO_NAME(rt, standard_class_atoms[j].atomOffset); ida = EnumerateIfResolved(cx, obj, name, ida, &i, &found); if (!ida) return NULL; if (found) { init = standard_class_atoms[j].init; for (k = 0; standard_class_names[k].init; k++) { if (standard_class_names[k].init == init) { name = StdNameToPropertyName(cx, &standard_class_names[k]); ida = AddNameToArray(cx, name, ida, &i); if (!ida) return NULL; } } if (init == js_InitObjectClass) { for (k = 0; object_prototype_names[k].init; k++) { name = StdNameToPropertyName(cx, &object_prototype_names[k]); ida = AddNameToArray(cx, name, ida, &i); if (!ida) return NULL; } } } } /* Trim to exact length. */ return SetIdArrayLength(cx, ida, i); } #undef CLASP #undef EAGER_ATOM #undef EAGER_CLASS_ATOM #undef EAGER_ATOM_CLASP JS_PUBLIC_API(JSBool) JS_GetClassObject(JSContext *cx, JSRawObject obj, JSProtoKey key, JSObject **objpArg) { RootedObject objp(cx, *objpArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); if (!js_GetClassObject(cx, obj, key, &objp)) return false; *objpArg = objp; return true; } JS_PUBLIC_API(JSBool) JS_GetClassPrototype(JSContext *cx, JSProtoKey key, JSObject **objp_) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); RootedObject objp(cx); bool result = js_GetClassPrototype(cx, key, &objp); *objp_ = objp; return result; } JS_PUBLIC_API(JSProtoKey) JS_IdentifyClassPrototype(JSContext *cx, JSObject *obj) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); JS_ASSERT(!IsCrossCompartmentWrapper(obj)); return js_IdentifyClassPrototype(obj); } JS_PUBLIC_API(JSObject *) JS_GetObjectPrototype(JSContext *cx, JSRawObject forObj) { CHECK_REQUEST(cx); assertSameCompartment(cx, forObj); return forObj->global().getOrCreateObjectPrototype(cx); } JS_PUBLIC_API(JSObject *) JS_GetFunctionPrototype(JSContext *cx, JSRawObject forObj) { CHECK_REQUEST(cx); assertSameCompartment(cx, forObj); return forObj->global().getOrCreateFunctionPrototype(cx); } JS_PUBLIC_API(JSObject *) JS_GetGlobalForObject(JSContext *cx, JSRawObject obj) { AssertHeapIsIdle(cx); assertSameCompartment(cx, obj); return &obj->global(); } JS_PUBLIC_API(JSObject *) JS_GetGlobalForCompartmentOrNull(JSContext *cx, JSCompartment *c) { AssertHeapIsIdleOrIterating(cx); assertSameCompartment(cx, c); return c->maybeGlobal(); } JS_PUBLIC_API(JSObject *) JS_GetGlobalForScopeChain(JSContext *cx) { AssertHeapIsIdleOrIterating(cx); CHECK_REQUEST(cx); return cx->global(); } JS_PUBLIC_API(jsval) JS_ComputeThis(JSContext *cx, jsval *vp) { AssertHeapIsIdle(cx); assertSameCompartment(cx, JSValueArray(vp, 2)); CallReceiver call = CallReceiverFromVp(vp); if (!BoxNonStrictThis(cx, call)) return JSVAL_NULL; return call.thisv(); } JS_PUBLIC_API(void) JS_MallocInCompartment(JSCompartment *comp, size_t nbytes) { comp->mallocInCompartment(nbytes); } JS_PUBLIC_API(void) JS_FreeInCompartment(JSCompartment *comp, size_t nbytes) { comp->freeInCompartment(nbytes); } JS_PUBLIC_API(void *) JS_malloc(JSContext *cx, size_t nbytes) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return cx->malloc_(nbytes); } JS_PUBLIC_API(void *) JS_realloc(JSContext *cx, void *p, size_t nbytes) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return cx->realloc_(p, nbytes); } JS_PUBLIC_API(void) JS_free(JSContext *cx, void *p) { return js_free(p); } JS_PUBLIC_API(void) JS_freeop(JSFreeOp *fop, void *p) { return FreeOp::get(fop)->free_(p); } JS_PUBLIC_API(JSFreeOp *) JS_GetDefaultFreeOp(JSRuntime *rt) { return rt->defaultFreeOp(); } JS_PUBLIC_API(void) JS_updateMallocCounter(JSContext *cx, size_t nbytes) { return cx->runtime->updateMallocCounter(cx, nbytes); } JS_PUBLIC_API(char *) JS_strdup(JSContext *cx, const char *s) { AssertHeapIsIdle(cx); size_t n = strlen(s) + 1; void *p = cx->malloc_(n); if (!p) return NULL; return (char *)js_memcpy(p, s, n); } #undef JS_AddRoot JS_PUBLIC_API(JSBool) JS_AddValueRoot(JSContext *cx, jsval *vp) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return js_AddRoot(cx, vp, NULL); } JS_PUBLIC_API(JSBool) JS_AddStringRoot(JSContext *cx, JSString **rp) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return js_AddGCThingRoot(cx, (void **)rp, NULL); } JS_PUBLIC_API(JSBool) JS_AddObjectRoot(JSContext *cx, JSObject **rp) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return js_AddGCThingRoot(cx, (void **)rp, NULL); } JS_PUBLIC_API(JSBool) JS_AddGCThingRoot(JSContext *cx, void **rp) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return js_AddGCThingRoot(cx, (void **)rp, NULL); } JS_PUBLIC_API(JSBool) JS_AddNamedValueRoot(JSContext *cx, jsval *vp, const char *name) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return js_AddRoot(cx, vp, name); } JS_PUBLIC_API(JSBool) JS_AddNamedStringRoot(JSContext *cx, JSString **rp, const char *name) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return js_AddGCThingRoot(cx, (void **)rp, name); } JS_PUBLIC_API(JSBool) JS_AddNamedObjectRoot(JSContext *cx, JSObject **rp, const char *name) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return js_AddGCThingRoot(cx, (void **)rp, name); } JS_PUBLIC_API(JSBool) JS_AddNamedScriptRoot(JSContext *cx, JSScript **rp, const char *name) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return js_AddGCThingRoot(cx, (void **)rp, name); } JS_PUBLIC_API(JSBool) JS_AddNamedGCThingRoot(JSContext *cx, void **rp, const char *name) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return js_AddGCThingRoot(cx, (void **)rp, name); } /* We allow unrooting from finalizers within the GC */ JS_PUBLIC_API(void) JS_RemoveValueRoot(JSContext *cx, jsval *vp) { CHECK_REQUEST(cx); js_RemoveRoot(cx->runtime, (void *)vp); } JS_PUBLIC_API(void) JS_RemoveStringRoot(JSContext *cx, JSString **rp) { CHECK_REQUEST(cx); js_RemoveRoot(cx->runtime, (void *)rp); } JS_PUBLIC_API(void) JS_RemoveObjectRoot(JSContext *cx, JSObject **rp) { CHECK_REQUEST(cx); js_RemoveRoot(cx->runtime, (void *)rp); } JS_PUBLIC_API(void) JS_RemoveScriptRoot(JSContext *cx, JSScript **rp) { CHECK_REQUEST(cx); js_RemoveRoot(cx->runtime, (void *)rp); } JS_PUBLIC_API(void) JS_RemoveGCThingRoot(JSContext *cx, void **rp) { CHECK_REQUEST(cx); js_RemoveRoot(cx->runtime, (void *)rp); } JS_PUBLIC_API(void) JS_RemoveValueRootRT(JSRuntime *rt, jsval *vp) { js_RemoveRoot(rt, (void *)vp); } JS_PUBLIC_API(void) JS_RemoveStringRootRT(JSRuntime *rt, JSString **rp) { js_RemoveRoot(rt, (void *)rp); } JS_PUBLIC_API(void) JS_RemoveObjectRootRT(JSRuntime *rt, JSObject **rp) { js_RemoveRoot(rt, (void *)rp); } JS_PUBLIC_API(void) JS_RemoveScriptRootRT(JSRuntime *rt, JSScript **rp) { js_RemoveRoot(rt, (void *)rp); } JS_NEVER_INLINE JS_PUBLIC_API(void) JS_AnchorPtr(void *p) { } #ifdef DEBUG JS_PUBLIC_API(void) JS_DumpNamedRoots(JSRuntime *rt, void (*dump)(const char *name, void *rp, JSGCRootType type, void *data), void *data) { js_DumpNamedRoots(rt, dump, data); } #endif /* DEBUG */ JS_PUBLIC_API(uint32_t) JS_MapGCRoots(JSRuntime *rt, JSGCRootMapFun map, void *data) { return js_MapGCRoots(rt, map, data); } JS_PUBLIC_API(JSBool) JS_LockGCThing(JSContext *cx, void *thing) { JSBool ok; AssertHeapIsIdle(cx); CHECK_REQUEST(cx); ok = js_LockGCThingRT(cx->runtime, thing); if (!ok) JS_ReportOutOfMemory(cx); return ok; } JS_PUBLIC_API(JSBool) JS_LockGCThingRT(JSRuntime *rt, void *thing) { return js_LockGCThingRT(rt, thing); } JS_PUBLIC_API(JSBool) JS_UnlockGCThing(JSContext *cx, void *thing) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); js_UnlockGCThingRT(cx->runtime, thing); return true; } JS_PUBLIC_API(JSBool) JS_UnlockGCThingRT(JSRuntime *rt, void *thing) { js_UnlockGCThingRT(rt, thing); return true; } JS_PUBLIC_API(void) JS_SetExtraGCRootsTracer(JSRuntime *rt, JSTraceDataOp traceOp, void *data) { AssertHeapIsIdle(rt); rt->gcBlackRootsTraceOp = traceOp; rt->gcBlackRootsData = data; } JS_PUBLIC_API(void) JS_TracerInit(JSTracer *trc, JSRuntime *rt, JSTraceCallback callback) { InitTracer(trc, rt, callback); } JS_PUBLIC_API(void) JS_TraceRuntime(JSTracer *trc) { AssertHeapIsIdle(trc->runtime); TraceRuntime(trc); } JS_PUBLIC_API(void) JS_TraceChildren(JSTracer *trc, void *thing, JSGCTraceKind kind) { js::TraceChildren(trc, thing, kind); } JS_PUBLIC_API(void) JS_CallTracer(JSTracer *trc, void *thing, JSGCTraceKind kind) { js::CallTracer(trc, thing, kind); } JS_PUBLIC_API(void) JS_GetTraceThingInfo(char *buf, size_t bufsize, JSTracer *trc, void *thing, JSGCTraceKind kind, JSBool details) { const char *name = NULL; /* silence uninitialized warning */ size_t n; if (bufsize == 0) return; switch (kind) { case JSTRACE_OBJECT: { name = static_cast<JSObject *>(thing)->getClass()->name; break; } case JSTRACE_STRING: name = ((JSString *)thing)->isDependent() ? "substring" : "string"; break; case JSTRACE_SCRIPT: name = "script"; break; case JSTRACE_IONCODE: name = "ioncode"; break; case JSTRACE_SHAPE: name = "shape"; break; case JSTRACE_BASE_SHAPE: name = "base_shape"; break; case JSTRACE_TYPE_OBJECT: name = "type_object"; break; #if JS_HAS_XML_SUPPORT case JSTRACE_XML: name = "xml"; break; #endif } n = strlen(name); if (n > bufsize - 1) n = bufsize - 1; js_memcpy(buf, name, n + 1); buf += n; bufsize -= n; *buf = '\0'; if (details && bufsize > 2) { switch (kind) { case JSTRACE_OBJECT: { JSObject *obj = (JSObject *)thing; Class *clasp = obj->getClass(); if (clasp == &FunctionClass) { JSFunction *fun = obj->toFunction(); if (!fun) { JS_snprintf(buf, bufsize, " <newborn>"); } else if (fun != obj) { JS_snprintf(buf, bufsize, " %p", fun); } else { if (fun->displayAtom()) { *buf++ = ' '; bufsize--; PutEscapedString(buf, bufsize, fun->displayAtom(), 0); } } } else if (clasp->flags & JSCLASS_HAS_PRIVATE) { JS_snprintf(buf, bufsize, " %p", obj->getPrivate()); } else { JS_snprintf(buf, bufsize, " <no private>"); } break; } case JSTRACE_STRING: { *buf++ = ' '; bufsize--; JSString *str = (JSString *)thing; if (str->isLinear()) PutEscapedString(buf, bufsize, &str->asLinear(), 0); else JS_snprintf(buf, bufsize, "<rope: length %d>", (int)str->length()); break; } case JSTRACE_SCRIPT: { JSScript *script = static_cast<JSScript *>(thing); JS_snprintf(buf, bufsize, " %s:%u", script->filename, unsigned(script->lineno)); break; } case JSTRACE_IONCODE: case JSTRACE_SHAPE: case JSTRACE_BASE_SHAPE: case JSTRACE_TYPE_OBJECT: break; #if JS_HAS_XML_SUPPORT case JSTRACE_XML: { extern const char *js_xml_class_str[]; JSXML *xml = (JSXML *)thing; JS_snprintf(buf, bufsize, " %s", js_xml_class_str[xml->xml_class]); break; } #endif } } buf[bufsize - 1] = '\0'; } extern JS_PUBLIC_API(const char *) JS_GetTraceEdgeName(JSTracer *trc, char *buffer, int bufferSize) { if (trc->debugPrinter) { trc->debugPrinter(trc, buffer, bufferSize); return buffer; } if (trc->debugPrintIndex != (size_t) - 1) { JS_snprintf(buffer, bufferSize, "%s[%lu]", (const char *)trc->debugPrintArg, trc->debugPrintIndex); return buffer; } return (const char*)trc->debugPrintArg; } #ifdef DEBUG typedef struct JSHeapDumpNode JSHeapDumpNode; struct JSHeapDumpNode { void *thing; JSGCTraceKind kind; JSHeapDumpNode *next; /* next sibling */ JSHeapDumpNode *parent; /* node with the thing that refer to thing from this node */ char edgeName[1]; /* name of the edge from parent->thing into thing */ }; typedef HashSet<void *, PointerHasher<void *, 3>, SystemAllocPolicy> VisitedSet; typedef struct JSDumpingTracer { JSTracer base; VisitedSet visited; bool ok; void *startThing; void *thingToFind; void *thingToIgnore; JSHeapDumpNode *parentNode; JSHeapDumpNode **lastNodep; char buffer[200]; } JSDumpingTracer; static void DumpNotify(JSTracer *trc, void **thingp, JSGCTraceKind kind) { JS_ASSERT(trc->callback == DumpNotify); JSDumpingTracer *dtrc = (JSDumpingTracer *)trc; void *thing = *thingp; if (!dtrc->ok || thing == dtrc->thingToIgnore) return; /* * Check if we have already seen thing unless it is thingToFind to include * it to the graph each time we reach it and print all live things that * refer to thingToFind. * * This does not print all possible paths leading to thingToFind since * when a thing A refers directly or indirectly to thingToFind and A is * present several times in the graph, we will print only the first path * leading to A and thingToFind, other ways to reach A will be ignored. */ if (dtrc->thingToFind != thing) { /* * The startThing check allows to avoid putting startThing into the * hash table before tracing startThing in JS_DumpHeap. */ if (thing == dtrc->startThing) return; VisitedSet::AddPtr p = dtrc->visited.lookupForAdd(thing); if (p) return; if (!dtrc->visited.add(p, thing)) { dtrc->ok = false; return; } } const char *edgeName = JS_GetTraceEdgeName(&dtrc->base, dtrc->buffer, sizeof(dtrc->buffer)); size_t edgeNameSize = strlen(edgeName) + 1; size_t bytes = offsetof(JSHeapDumpNode, edgeName) + edgeNameSize; JSHeapDumpNode *node = (JSHeapDumpNode *) js_malloc(bytes); if (!node) { dtrc->ok = false; return; } node->thing = thing; node->kind = kind; node->next = NULL; node->parent = dtrc->parentNode; js_memcpy(node->edgeName, edgeName, edgeNameSize); JS_ASSERT(!*dtrc->lastNodep); *dtrc->lastNodep = node; dtrc->lastNodep = &node->next; } /* Dump node and the chain that leads to thing it contains. */ static JSBool DumpNode(JSDumpingTracer *dtrc, FILE* fp, JSHeapDumpNode *node) { JSHeapDumpNode *prev, *following; size_t chainLimit; enum { MAX_PARENTS_TO_PRINT = 10 }; JS_GetTraceThingInfo(dtrc->buffer, sizeof dtrc->buffer, &dtrc->base, node->thing, node->kind, JS_TRUE); if (fprintf(fp, "%p %-22s via ", node->thing, dtrc->buffer) < 0) return JS_FALSE; /* * We need to print the parent chain in the reverse order. To do it in * O(N) time where N is the chain length we first reverse the chain while * searching for the top and then print each node while restoring the * chain order. */ chainLimit = MAX_PARENTS_TO_PRINT; prev = NULL; for (;;) { following = node->parent; node->parent = prev; prev = node; node = following; if (!node) break; if (chainLimit == 0) { if (fputs("...", fp) < 0) return JS_FALSE; break; } --chainLimit; } node = prev; prev = following; bool ok = true; do { /* Loop must continue even when !ok to restore the parent chain. */ if (ok) { if (!prev) { /* Print edge from some runtime root or startThing. */ if (fputs(node->edgeName, fp) < 0) ok = false; } else { JS_GetTraceThingInfo(dtrc->buffer, sizeof dtrc->buffer, &dtrc->base, prev->thing, prev->kind, JS_FALSE); if (fprintf(fp, "(%p %s).%s", prev->thing, dtrc->buffer, node->edgeName) < 0) { ok = false; } } } following = node->parent; node->parent = prev; prev = node; node = following; } while (node); return ok && putc('\n', fp) >= 0; } JS_PUBLIC_API(JSBool) JS_DumpHeap(JSRuntime *rt, FILE *fp, void* startThing, JSGCTraceKind startKind, void *thingToFind, size_t maxDepth, void *thingToIgnore) { if (maxDepth == 0) return true; JSDumpingTracer dtrc; if (!dtrc.visited.init()) return false; JS_TracerInit(&dtrc.base, rt, DumpNotify); dtrc.ok = true; dtrc.startThing = startThing; dtrc.thingToFind = thingToFind; dtrc.thingToIgnore = thingToIgnore; dtrc.parentNode = NULL; JSHeapDumpNode *node = NULL; dtrc.lastNodep = &node; if (!startThing) { JS_ASSERT(startKind == JSTRACE_OBJECT); TraceRuntime(&dtrc.base); } else { JS_TraceChildren(&dtrc.base, startThing, startKind); } if (!node) return dtrc.ok; size_t depth = 1; JSHeapDumpNode *children, *next, *parent; bool thingToFindWasTraced = thingToFind && thingToFind == startThing; for (;;) { /* * Loop must continue even when !dtrc.ok to free all nodes allocated * so far. */ if (dtrc.ok) { if (thingToFind == NULL || thingToFind == node->thing) dtrc.ok = DumpNode(&dtrc, fp, node); /* Descend into children. */ if (dtrc.ok && depth < maxDepth && (thingToFind != node->thing || !thingToFindWasTraced)) { dtrc.parentNode = node; children = NULL; dtrc.lastNodep = &children; JS_TraceChildren(&dtrc.base, node->thing, node->kind); if (thingToFind == node->thing) thingToFindWasTraced = JS_TRUE; if (children != NULL) { ++depth; node = children; continue; } } } /* Move to next or parents next and free the node. */ for (;;) { next = node->next; parent = node->parent; js_free(node); node = next; if (node) break; if (!parent) return dtrc.ok; JS_ASSERT(depth > 1); --depth; node = parent; } } JS_ASSERT(depth == 1); return dtrc.ok; } #endif /* DEBUG */ extern JS_PUBLIC_API(JSBool) JS_IsGCMarkingTracer(JSTracer *trc) { return IS_GC_MARKING_TRACER(trc); } JS_PUBLIC_API(void) JS_GC(JSRuntime *rt) { AssertHeapIsIdle(rt); PrepareForFullGC(rt); GC(rt, GC_NORMAL, gcreason::API); } JS_PUBLIC_API(void) JS_MaybeGC(JSContext *cx) { MaybeGC(cx); } JS_PUBLIC_API(void) JS_SetGCCallback(JSRuntime *rt, JSGCCallback cb) { AssertHeapIsIdle(rt); rt->gcCallback = cb; } JS_PUBLIC_API(void) JS_SetFinalizeCallback(JSRuntime *rt, JSFinalizeCallback cb) { AssertHeapIsIdle(rt); rt->gcFinalizeCallback = cb; } JS_PUBLIC_API(JSBool) JS_IsAboutToBeFinalized(void *thing) { gc::Cell *t = static_cast<gc::Cell *>(thing); bool isMarked = IsCellMarked(&t); JS_ASSERT(t == thing); return !isMarked; } JS_PUBLIC_API(void) JS_SetGCParameter(JSRuntime *rt, JSGCParamKey key, uint32_t value) { switch (key) { case JSGC_MAX_BYTES: { JS_ASSERT(value >= rt->gcBytes); rt->gcMaxBytes = value; break; } case JSGC_MAX_MALLOC_BYTES: rt->setGCMaxMallocBytes(value); break; case JSGC_SLICE_TIME_BUDGET: rt->gcSliceBudget = SliceBudget::TimeBudget(value); break; case JSGC_MARK_STACK_LIMIT: js::SetMarkStackLimit(rt, value); break; case JSGC_HIGH_FREQUENCY_TIME_LIMIT: rt->gcHighFrequencyTimeThreshold = value; break; case JSGC_HIGH_FREQUENCY_LOW_LIMIT: rt->gcHighFrequencyLowLimitBytes = value * 1024 * 1024; break; case JSGC_HIGH_FREQUENCY_HIGH_LIMIT: rt->gcHighFrequencyHighLimitBytes = value * 1024 * 1024; break; case JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX: rt->gcHighFrequencyHeapGrowthMax = value / 100.0; break; case JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN: rt->gcHighFrequencyHeapGrowthMin = value / 100.0; break; case JSGC_LOW_FREQUENCY_HEAP_GROWTH: rt->gcLowFrequencyHeapGrowth = value / 100.0; break; case JSGC_DYNAMIC_HEAP_GROWTH: rt->gcDynamicHeapGrowth = value; break; case JSGC_DYNAMIC_MARK_SLICE: rt->gcDynamicMarkSlice = value; break; case JSGC_ANALYSIS_PURGE_TRIGGER: rt->analysisPurgeTriggerBytes = value * 1024 * 1024; break; default: JS_ASSERT(key == JSGC_MODE); rt->gcMode = JSGCMode(value); JS_ASSERT(rt->gcMode == JSGC_MODE_GLOBAL || rt->gcMode == JSGC_MODE_COMPARTMENT || rt->gcMode == JSGC_MODE_INCREMENTAL); return; } } JS_PUBLIC_API(uint32_t) JS_GetGCParameter(JSRuntime *rt, JSGCParamKey key) { switch (key) { case JSGC_MAX_BYTES: return uint32_t(rt->gcMaxBytes); case JSGC_MAX_MALLOC_BYTES: return rt->gcMaxMallocBytes; case JSGC_BYTES: return uint32_t(rt->gcBytes); case JSGC_MODE: return uint32_t(rt->gcMode); case JSGC_UNUSED_CHUNKS: return uint32_t(rt->gcChunkPool.getEmptyCount()); case JSGC_TOTAL_CHUNKS: return uint32_t(rt->gcChunkSet.count() + rt->gcChunkPool.getEmptyCount()); case JSGC_SLICE_TIME_BUDGET: return uint32_t(rt->gcSliceBudget > 0 ? rt->gcSliceBudget / PRMJ_USEC_PER_MSEC : 0); case JSGC_MARK_STACK_LIMIT: return rt->gcMarker.sizeLimit(); case JSGC_HIGH_FREQUENCY_TIME_LIMIT: return rt->gcHighFrequencyTimeThreshold; case JSGC_HIGH_FREQUENCY_LOW_LIMIT: return rt->gcHighFrequencyLowLimitBytes / 1024 / 1024; case JSGC_HIGH_FREQUENCY_HIGH_LIMIT: return rt->gcHighFrequencyHighLimitBytes / 1024 / 1024; case JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX: return uint32_t(rt->gcHighFrequencyHeapGrowthMax * 100); case JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN: return uint32_t(rt->gcHighFrequencyHeapGrowthMin * 100); case JSGC_LOW_FREQUENCY_HEAP_GROWTH: return uint32_t(rt->gcLowFrequencyHeapGrowth * 100); case JSGC_DYNAMIC_HEAP_GROWTH: return rt->gcDynamicHeapGrowth; case JSGC_DYNAMIC_MARK_SLICE: return rt->gcDynamicMarkSlice; case JSGC_ANALYSIS_PURGE_TRIGGER: return rt->analysisPurgeTriggerBytes / 1024 / 1024; default: JS_ASSERT(key == JSGC_NUMBER); return uint32_t(rt->gcNumber); } } JS_PUBLIC_API(void) JS_SetGCParameterForThread(JSContext *cx, JSGCParamKey key, uint32_t value) { JS_ASSERT(key == JSGC_MAX_CODE_CACHE_BYTES); } JS_PUBLIC_API(uint32_t) JS_GetGCParameterForThread(JSContext *cx, JSGCParamKey key) { JS_ASSERT(key == JSGC_MAX_CODE_CACHE_BYTES); return 0; } JS_PUBLIC_API(JSString *) JS_NewExternalString(JSContext *cx, const jschar *chars, size_t length, const JSStringFinalizer *fin) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); JSString *s = JSExternalString::new_(cx, chars, length, fin); Probes::createString(cx, s, length); return s; } extern JS_PUBLIC_API(JSBool) JS_IsExternalString(JSString *str) { return str->isExternal(); } extern JS_PUBLIC_API(const JSStringFinalizer *) JS_GetExternalStringFinalizer(JSString *str) { return str->asExternal().externalFinalizer(); } JS_PUBLIC_API(void) JS_SetNativeStackQuota(JSRuntime *rt, size_t stackSize) { rt->nativeStackQuota = stackSize; if (!rt->nativeStackBase) return; #if JS_STACK_GROWTH_DIRECTION > 0 if (stackSize == 0) { rt->nativeStackLimit = UINTPTR_MAX; } else { JS_ASSERT(rt->nativeStackBase <= size_t(-1) - stackSize); rt->nativeStackLimit = rt->nativeStackBase + stackSize - 1; } #else if (stackSize == 0) { rt->nativeStackLimit = 0; } else { JS_ASSERT(rt->nativeStackBase >= stackSize); rt->nativeStackLimit = rt->nativeStackBase - (stackSize - 1); } #endif } /************************************************************************/ JS_PUBLIC_API(int) JS_IdArrayLength(JSContext *cx, JSIdArray *ida) { return ida->length; } JS_PUBLIC_API(jsid) JS_IdArrayGet(JSContext *cx, JSIdArray *ida, int index) { JS_ASSERT(index >= 0 && index < ida->length); return ida->vector[index]; } JS_PUBLIC_API(void) JS_DestroyIdArray(JSContext *cx, JSIdArray *ida) { DestroyIdArray(cx->runtime->defaultFreeOp(), ida); } JS_PUBLIC_API(JSBool) JS_ValueToId(JSContext *cx, jsval valueArg, jsid *idp) { RootedValue value(cx, valueArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, value); return ValueToId(cx, value, idp); } JS_PUBLIC_API(JSBool) JS_IdToValue(JSContext *cx, jsid id, jsval *vp) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); *vp = IdToJsval(id); assertSameCompartment(cx, *vp); return JS_TRUE; } JS_PUBLIC_API(JSBool) JS_DefaultValue(JSContext *cx, JSObject *objArg, JSType hint, jsval *vp) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); JS_ASSERT(obj != NULL); JS_ASSERT(hint == JSTYPE_VOID || hint == JSTYPE_STRING || hint == JSTYPE_NUMBER); RootedValue value(cx); if (!JSObject::defaultValue(cx, obj, hint, &value)) return false; *vp = value; return true; } JS_PUBLIC_API(JSBool) JS_PropertyStub(JSContext *cx, JSHandleObject obj, JSHandleId id, JSMutableHandleValue vp) { return JS_TRUE; } JS_PUBLIC_API(JSBool) JS_StrictPropertyStub(JSContext *cx, JSHandleObject obj, JSHandleId id, JSBool strict, JSMutableHandleValue vp) { return JS_TRUE; } JS_PUBLIC_API(JSBool) JS_EnumerateStub(JSContext *cx, JSHandleObject obj) { return JS_TRUE; } JS_PUBLIC_API(JSBool) JS_ResolveStub(JSContext *cx, JSHandleObject obj, JSHandleId id) { return JS_TRUE; } JS_PUBLIC_API(JSBool) JS_ConvertStub(JSContext *cx, JSHandleObject obj, JSType type, JSMutableHandleValue vp) { JS_ASSERT(type != JSTYPE_OBJECT && type != JSTYPE_FUNCTION); JS_ASSERT(obj); return DefaultValue(cx, obj, type, vp); } JS_PUBLIC_API(JSObject *) JS_InitClass(JSContext *cx, JSObject *objArg, JSObject *parent_protoArg, JSClass *clasp, JSNative constructor, unsigned nargs, JSPropertySpec *ps, JSFunctionSpec *fs, JSPropertySpec *static_ps, JSFunctionSpec *static_fs) { RootedObject obj(cx, objArg); RootedObject parent_proto(cx, parent_protoArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, parent_proto); return js_InitClass(cx, obj, parent_proto, Valueify(clasp), constructor, nargs, ps, fs, static_ps, static_fs); } JS_PUBLIC_API(JSBool) JS_LinkConstructorAndPrototype(JSContext *cx, JSObject *ctorArg, JSObject *protoArg) { RootedObject ctor(cx, ctorArg); RootedObject proto(cx, protoArg); return LinkConstructorAndPrototype(cx, ctor, proto); } JS_PUBLIC_API(JSClass *) JS_GetClass(RawObject obj) { return obj->getJSClass(); } JS_PUBLIC_API(JSBool) JS_InstanceOf(JSContext *cx, JSObject *objArg, JSClass *clasp, jsval *argv) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); #ifdef DEBUG if (argv) { assertSameCompartment(cx, obj); assertSameCompartment(cx, JSValueArray(argv - 2, 2)); } #endif if (!obj || obj->getJSClass() != clasp) { if (argv) ReportIncompatibleMethod(cx, CallReceiverFromArgv(argv), Valueify(clasp)); return false; } return true; } JS_PUBLIC_API(JSBool) JS_HasInstance(JSContext *cx, JSObject *objArg, jsval valueArg, JSBool *bp) { RootedObject obj(cx, objArg); RootedValue value(cx, valueArg); AssertHeapIsIdle(cx); assertSameCompartment(cx, obj, value); return HasInstance(cx, obj, value, bp); } JS_PUBLIC_API(void *) JS_GetPrivate(RawObject obj) { /* This function can be called by a finalizer. */ return obj->getPrivate(); } JS_PUBLIC_API(void) JS_SetPrivate(RawObject obj, void *data) { /* This function can be called by a finalizer. */ obj->setPrivate(data); } JS_PUBLIC_API(void *) JS_GetInstancePrivate(JSContext *cx, JSObject *objArg, JSClass *clasp, jsval *argv) { RootedObject obj(cx, objArg); if (!JS_InstanceOf(cx, obj, clasp, argv)) return NULL; return obj->getPrivate(); } JS_PUBLIC_API(JSObject *) JS_GetPrototype(RawObject obj) { return obj->getProto(); } JS_PUBLIC_API(JSBool) JS_SetPrototype(JSContext *cx, JSObject *objArg, JSObject *protoArg) { RootedObject obj(cx, objArg); RootedObject proto(cx, protoArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, proto); return SetProto(cx, obj, proto, JS_FALSE); } JS_PUBLIC_API(JSObject *) JS_GetParent(RawObject obj) { JS_ASSERT(!obj->isScope()); return obj->getParent(); } JS_PUBLIC_API(JSBool) JS_SetParent(JSContext *cx, JSObject *objArg, JSObject *parentArg) { RootedObject obj(cx, objArg); RootedObject parent(cx, parentArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); JS_ASSERT(!obj->isScope()); JS_ASSERT(parent || !obj->getParent()); assertSameCompartment(cx, obj, parent); return JSObject::setParent(cx, obj, parent); } JS_PUBLIC_API(JSObject *) JS_GetConstructor(JSContext *cx, JSObject *protoArg) { RootedObject proto(cx, protoArg); RootedValue cval(cx); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, proto); { JSAutoResolveFlags rf(cx, JSRESOLVE_QUALIFIED); if (!JSObject::getProperty(cx, proto, proto, cx->names().constructor, &cval)) return NULL; } if (!IsFunctionObject(cval)) { JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NO_CONSTRUCTOR, proto->getClass()->name); return NULL; } return &cval.toObject(); } JS_PUBLIC_API(JSBool) JS_GetObjectId(JSContext *cx, JSRawObject obj, jsid *idp) { AssertHeapIsIdle(cx); assertSameCompartment(cx, obj); *idp = OBJECT_TO_JSID(obj); return JS_TRUE; } class AutoHoldCompartment { public: explicit AutoHoldCompartment(JSCompartment *compartment JS_GUARD_OBJECT_NOTIFIER_PARAM) : holdp(&compartment->hold) { JS_GUARD_OBJECT_NOTIFIER_INIT; *holdp = true; } ~AutoHoldCompartment() { *holdp = false; } private: bool *holdp; JS_DECL_USE_GUARD_OBJECT_NOTIFIER }; JS_PUBLIC_API(JSObject *) JS_NewGlobalObject(JSContext *cx, JSClass *clasp, JSPrincipals *principals) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); JSCompartment *compartment = NewCompartment(cx, principals); if (!compartment) return NULL; AutoHoldCompartment hold(compartment); JSCompartment *saved = cx->compartment; cx->setCompartment(compartment); GlobalObject *global = GlobalObject::create(cx, Valueify(clasp)); cx->setCompartment(saved); return global; } JS_PUBLIC_API(JSObject *) JS_NewObject(JSContext *cx, JSClass *jsclasp, JSObject *protoArg, JSObject *parentArg) { RootedObject proto(cx, protoArg); RootedObject parent(cx, parentArg); JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, proto, parent); Class *clasp = Valueify(jsclasp); if (!clasp) clasp = &ObjectClass; /* default class is Object */ JS_ASSERT(clasp != &FunctionClass); JS_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL)); JSObject *obj = NewObjectWithClassProto(cx, clasp, proto, parent); AutoAssertNoGC nogc; if (obj) { if (clasp->ext.equality) MarkTypeObjectFlags(cx, obj, OBJECT_FLAG_SPECIAL_EQUALITY); } JS_ASSERT_IF(obj, obj->getParent()); return obj; } JS_PUBLIC_API(JSObject *) JS_NewObjectWithGivenProto(JSContext *cx, JSClass *jsclasp, JSObject *protoArg, JSObject *parentArg) { RootedObject proto(cx, protoArg); RootedObject parent(cx, parentArg); JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, proto, parent); Class *clasp = Valueify(jsclasp); if (!clasp) clasp = &ObjectClass; /* default class is Object */ JS_ASSERT(clasp != &FunctionClass); JS_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL)); JSObject *obj = NewObjectWithGivenProto(cx, clasp, proto, parent); AutoAssertNoGC nogc; if (obj) MarkTypeObjectUnknownProperties(cx, obj->type()); return obj; } JS_PUBLIC_API(JSObject *) JS_NewObjectForConstructor(JSContext *cx, JSClass *clasp, const jsval *vp) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, *vp); RootedObject obj(cx, JSVAL_TO_OBJECT(*vp)); return js_CreateThis(cx, Valueify(clasp), obj); } JS_PUBLIC_API(JSBool) JS_IsExtensible(JSRawObject obj) { return obj->isExtensible(); } JS_PUBLIC_API(JSBool) JS_IsNative(JSRawObject obj) { return obj->isNative(); } JS_PUBLIC_API(JSRuntime *) JS_GetObjectRuntime(JSRawObject obj) { return obj->compartment()->rt; } JS_PUBLIC_API(JSBool) JS_FreezeObject(JSContext *cx, JSObject *objArg) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); return JSObject::freeze(cx, obj); } JS_PUBLIC_API(JSBool) JS_DeepFreezeObject(JSContext *cx, JSObject *objArg) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); /* Assume that non-extensible objects are already deep-frozen, to avoid divergence. */ if (!obj->isExtensible()) return true; if (!JSObject::freeze(cx, obj)) return false; /* Walk slots in obj and if any value is a non-null object, seal it. */ for (uint32_t i = 0, n = obj->slotSpan(); i < n; ++i) { const Value &v = obj->getSlot(i); if (v.isPrimitive()) continue; RootedObject obj(cx, &v.toObject()); if (!JS_DeepFreezeObject(cx, obj)) return false; } return true; } static JSBool LookupPropertyById(JSContext *cx, HandleObject obj, HandleId id, unsigned flags, MutableHandleObject objp, MutableHandleShape propp) { AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, id); JSAutoResolveFlags rf(cx, flags); return JSObject::lookupGeneric(cx, obj, id, objp, propp); } #define AUTO_NAMELEN(s,n) (((n) == (size_t)-1) ? js_strlen(s) : (n)) static JSBool LookupResult(JSContext *cx, HandleObject obj, HandleObject obj2, jsid id, HandleShape shape, Value *vp) { if (!shape) { /* XXX bad API: no way to tell "not defined" from "void value" */ vp->setUndefined(); return JS_TRUE; } if (obj2->isNative()) { /* Peek at the native property's slot value, without doing a Get. */ if (shape->hasSlot()) { *vp = obj2->nativeGetSlot(shape->slot()); return true; } } else { if (obj2->isDenseArray()) return js_GetDenseArrayElementValue(cx, obj2, id, vp); if (obj2->isProxy()) { AutoPropertyDescriptorRooter desc(cx); if (!Proxy::getPropertyDescriptor(cx, obj2, id, false, &desc)) return false; if (!(desc.attrs & JSPROP_SHARED)) { *vp = desc.value; return true; } } } /* XXX bad API: no way to return "defined but value unknown" */ vp->setBoolean(true); return true; } JS_PUBLIC_API(JSBool) JS_LookupPropertyById(JSContext *cx, JSObject *objArg, jsid idArg, jsval *vp) { RootedId id(cx, idArg); RootedObject obj(cx, objArg); RootedObject obj2(cx); RootedShape prop(cx); return LookupPropertyById(cx, obj, id, JSRESOLVE_QUALIFIED, &obj2, &prop) && LookupResult(cx, obj, obj2, id, prop, vp); } JS_PUBLIC_API(JSBool) JS_LookupElement(JSContext *cx, JSObject *objArg, uint32_t index, jsval *vp) { RootedObject obj(cx, objArg); CHECK_REQUEST(cx); jsid id; if (!IndexToId(cx, index, &id)) return false; return JS_LookupPropertyById(cx, obj, id, vp); } JS_PUBLIC_API(JSBool) JS_LookupProperty(JSContext *cx, JSObject *objArg, const char *name, jsval *vp) { RootedObject obj(cx, objArg); JSAtom *atom = Atomize(cx, name, strlen(name)); return atom && JS_LookupPropertyById(cx, obj, AtomToId(atom), vp); } JS_PUBLIC_API(JSBool) JS_LookupUCProperty(JSContext *cx, JSObject *objArg, const jschar *name, size_t namelen, jsval *vp) { RootedObject obj(cx, objArg); JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); return atom && JS_LookupPropertyById(cx, obj, AtomToId(atom), vp); } JS_PUBLIC_API(JSBool) JS_LookupPropertyWithFlagsById(JSContext *cx, JSObject *objArg, jsid id_, unsigned flags, JSObject **objpArg, jsval *vp) { RootedObject obj(cx, objArg); RootedObject objp(cx, *objpArg); RootedId id(cx, id_); RootedShape prop(cx); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, id); if (!(obj->isNative() ? LookupPropertyWithFlags(cx, obj, id, flags, &objp, &prop) : JSObject::lookupGeneric(cx, obj, id, &objp, &prop))) return false; if (!LookupResult(cx, obj, objp, id, prop, vp)) return false; *objpArg = objp; return true; } JS_PUBLIC_API(JSBool) JS_LookupPropertyWithFlags(JSContext *cx, JSObject *objArg, const char *name, unsigned flags, jsval *vp) { RootedObject obj(cx, objArg); JSObject *obj2; JSAtom *atom = Atomize(cx, name, strlen(name)); return atom && JS_LookupPropertyWithFlagsById(cx, obj, AtomToId(atom), flags, &obj2, vp); } JS_PUBLIC_API(JSBool) JS_HasPropertyById(JSContext *cx, JSObject *objArg, jsid idArg, JSBool *foundp) { RootedObject obj(cx, objArg); RootedId id(cx, idArg); RootedObject obj2(cx); RootedShape prop(cx); JSBool ok = LookupPropertyById(cx, obj, id, JSRESOLVE_QUALIFIED | JSRESOLVE_DETECTING, &obj2, &prop); *foundp = (prop != NULL); return ok; } JS_PUBLIC_API(JSBool) JS_HasElement(JSContext *cx, JSObject *objArg, uint32_t index, JSBool *foundp) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); jsid id; if (!IndexToId(cx, index, &id)) return false; return JS_HasPropertyById(cx, obj, id, foundp); } JS_PUBLIC_API(JSBool) JS_HasProperty(JSContext *cx, JSObject *objArg, const char *name, JSBool *foundp) { RootedObject obj(cx, objArg); JSAtom *atom = Atomize(cx, name, strlen(name)); return atom && JS_HasPropertyById(cx, obj, AtomToId(atom), foundp); } JS_PUBLIC_API(JSBool) JS_HasUCProperty(JSContext *cx, JSObject *objArg, const jschar *name, size_t namelen, JSBool *foundp) { RootedObject obj(cx, objArg); JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); return atom && JS_HasPropertyById(cx, obj, AtomToId(atom), foundp); } JS_PUBLIC_API(JSBool) JS_AlreadyHasOwnPropertyById(JSContext *cx, JSObject *objArg, jsid id_, JSBool *foundp) { RootedObject obj(cx, objArg); RootedId id(cx, id_); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, id); if (!obj->isNative()) { RootedObject obj2(cx); RootedShape prop(cx); if (!LookupPropertyById(cx, obj, id, JSRESOLVE_QUALIFIED | JSRESOLVE_DETECTING, &obj2, &prop)) { return JS_FALSE; } *foundp = (obj == obj2); return JS_TRUE; } *foundp = obj->nativeContains(cx, id); return JS_TRUE; } JS_PUBLIC_API(JSBool) JS_AlreadyHasOwnElement(JSContext *cx, JSObject *objArg, uint32_t index, JSBool *foundp) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); jsid id; if (!IndexToId(cx, index, &id)) return false; return JS_AlreadyHasOwnPropertyById(cx, obj, id, foundp); } JS_PUBLIC_API(JSBool) JS_AlreadyHasOwnProperty(JSContext *cx, JSObject *objArg, const char *name, JSBool *foundp) { RootedObject obj(cx, objArg); JSAtom *atom = Atomize(cx, name, strlen(name)); return atom && JS_AlreadyHasOwnPropertyById(cx, obj, AtomToId(atom), foundp); } JS_PUBLIC_API(JSBool) JS_AlreadyHasOwnUCProperty(JSContext *cx, JSObject *objArg, const jschar *name, size_t namelen, JSBool *foundp) { RootedObject obj(cx, objArg); JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); return atom && JS_AlreadyHasOwnPropertyById(cx, obj, AtomToId(atom), foundp); } /* Wrapper functions to create wrappers with no corresponding JSJitInfo from API * function arguments. */ static JSPropertyOpWrapper GetterWrapper(JSPropertyOp getter) { JSPropertyOpWrapper ret; ret.op = getter; ret.info = NULL; return ret; } static JSStrictPropertyOpWrapper SetterWrapper(JSStrictPropertyOp setter) { JSStrictPropertyOpWrapper ret; ret.op = setter; ret.info = NULL; return ret; } static JSBool DefinePropertyById(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, const JSPropertyOpWrapper &get, const JSStrictPropertyOpWrapper &set, unsigned attrs, unsigned flags, int tinyid) { PropertyOp getter = get.op; StrictPropertyOp setter = set.op; /* * JSPROP_READONLY has no meaning when accessors are involved. Ideally we'd * throw if this happens, but we've accepted it for long enough that it's * not worth trying to make callers change their ways. Just flip it off on * its way through the API layer so that we can enforce this internally. */ if (attrs & (JSPROP_GETTER | JSPROP_SETTER)) attrs &= ~JSPROP_READONLY; /* * When we use DefineProperty, we need full scriptable Function objects rather * than JSNatives. However, we might be pulling this property descriptor off * of something with JSNative property descriptors. If we are, wrap them in * JS Function objects. */ if (attrs & JSPROP_NATIVE_ACCESSORS) { JS_ASSERT(!(attrs & (JSPROP_GETTER | JSPROP_SETTER))); attrs &= ~JSPROP_NATIVE_ACCESSORS; if (getter) { RootedObject global(cx, (JSObject*) &obj->global()); JSFunction *getobj = JS_NewFunction(cx, (Native) getter, 0, 0, global, NULL); if (!getobj) return false; if (get.info) getobj->setJitInfo(get.info); getter = JS_DATA_TO_FUNC_PTR(PropertyOp, getobj); attrs |= JSPROP_GETTER; } if (setter) { // Root just the getter, since the setter is not yet a JSObject. AutoRooterGetterSetter getRoot(cx, JSPROP_GETTER, &getter, NULL); RootedObject global(cx, (JSObject*) &obj->global()); JSFunction *setobj = JS_NewFunction(cx, (Native) setter, 1, 0, global, NULL); if (!setobj) return false; if (set.info) setobj->setJitInfo(set.info); setter = JS_DATA_TO_FUNC_PTR(StrictPropertyOp, setobj); attrs |= JSPROP_SETTER; } } AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, id, value, (attrs & JSPROP_GETTER) ? JS_FUNC_TO_DATA_PTR(JSObject *, getter) : NULL, (attrs & JSPROP_SETTER) ? JS_FUNC_TO_DATA_PTR(JSObject *, setter) : NULL); JSAutoResolveFlags rf(cx, JSRESOLVE_QUALIFIED); if (flags != 0 && obj->isNative()) { return !!DefineNativeProperty(cx, obj, id, value, getter, setter, attrs, flags, tinyid); } return JSObject::defineGeneric(cx, obj, id, value, getter, setter, attrs); } JS_PUBLIC_API(JSBool) JS_DefinePropertyById(JSContext *cx, JSObject *objArg, jsid idArg, jsval valueArg, JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs) { RootedObject obj(cx, objArg); RootedId id(cx, idArg); RootedValue value(cx, valueArg); return DefinePropertyById(cx, obj, id, value, GetterWrapper(getter), SetterWrapper(setter), attrs, 0, 0); } JS_PUBLIC_API(JSBool) JS_DefineElement(JSContext *cx, JSObject *objArg, uint32_t index, jsval valueArg, JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs) { RootedObject obj(cx, objArg); RootedValue value(cx, valueArg); AutoRooterGetterSetter gsRoot(cx, attrs, &getter, &setter); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); RootedId id(cx); if (!IndexToId(cx, index, id.address())) return false; return DefinePropertyById(cx, obj, id, value, GetterWrapper(getter), SetterWrapper(setter), attrs, 0, 0); } static JSBool DefineProperty(JSContext *cx, JSHandleObject obj, const char *name, const Value &value_, const JSPropertyOpWrapper &getter, const JSStrictPropertyOpWrapper &setter, unsigned attrs, unsigned flags, int tinyid) { RootedValue value(cx, value_); AutoRooterGetterSetter gsRoot(cx, attrs, const_cast<JSPropertyOp *>(&getter.op), const_cast<JSStrictPropertyOp *>(&setter.op)); RootedId id(cx); if (attrs & JSPROP_INDEX) { id = INT_TO_JSID(intptr_t(name)); attrs &= ~JSPROP_INDEX; } else { JSAtom *atom = Atomize(cx, name, strlen(name)); if (!atom) return JS_FALSE; id = AtomToId(atom); } return DefinePropertyById(cx, obj, id, value, getter, setter, attrs, flags, tinyid); } JS_PUBLIC_API(JSBool) JS_DefineProperty(JSContext *cx, JSObject *objArg, const char *name, jsval valueArg, PropertyOp getter, JSStrictPropertyOp setter, unsigned attrs) { RootedObject obj(cx, objArg); RootedValue value(cx, valueArg); return DefineProperty(cx, obj, name, value, GetterWrapper(getter), SetterWrapper(setter), attrs, 0, 0); } JS_PUBLIC_API(JSBool) JS_DefinePropertyWithTinyId(JSContext *cx, JSObject *objArg, const char *name, int8_t tinyid, jsval valueArg, PropertyOp getter, JSStrictPropertyOp setter, unsigned attrs) { RootedObject obj(cx, objArg); RootedValue value(cx, valueArg); return DefineProperty(cx, obj, name, value, GetterWrapper(getter), SetterWrapper(setter), attrs, Shape::HAS_SHORTID, tinyid); } static JSBool DefineUCProperty(JSContext *cx, JSHandleObject obj, const jschar *name, size_t namelen, const Value &value_, PropertyOp getter, StrictPropertyOp setter, unsigned attrs, unsigned flags, int tinyid) { RootedValue value(cx, value_); AutoRooterGetterSetter gsRoot(cx, attrs, &getter, &setter); JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); if (!atom) return false; RootedId id(cx, AtomToId(atom)); return DefinePropertyById(cx, obj, id, value, GetterWrapper(getter), SetterWrapper(setter), attrs, flags, tinyid); } JS_PUBLIC_API(JSBool) JS_DefineUCProperty(JSContext *cx, JSObject *objArg, const jschar *name, size_t namelen, jsval valueArg, JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs) { RootedObject obj(cx, objArg); RootedValue value(cx, valueArg); return DefineUCProperty(cx, obj, name, namelen, value, getter, setter, attrs, 0, 0); } JS_PUBLIC_API(JSBool) JS_DefineUCPropertyWithTinyId(JSContext *cx, JSObject *objArg, const jschar *name, size_t namelen, int8_t tinyid, jsval valueArg, JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs) { RootedObject obj(cx, objArg); RootedValue value(cx, valueArg); return DefineUCProperty(cx, obj, name, namelen, value, getter, setter, attrs, Shape::HAS_SHORTID, tinyid); } JS_PUBLIC_API(JSBool) JS_DefineOwnProperty(JSContext *cx, JSObject *objArg, jsid idArg, jsval descriptor, JSBool *bp) { RootedObject obj(cx, objArg); RootedId id(cx, idArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, id, descriptor); return js_DefineOwnProperty(cx, obj, id, descriptor, bp); } JS_PUBLIC_API(JSObject *) JS_DefineObject(JSContext *cx, JSObject *objArg, const char *name, JSClass *jsclasp, JSObject *protoArg, unsigned attrs) { RootedObject obj(cx, objArg); RootedObject proto(cx, protoArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, proto); Class *clasp = Valueify(jsclasp); if (!clasp) clasp = &ObjectClass; /* default class is Object */ RootedObject nobj(cx, NewObjectWithClassProto(cx, clasp, proto, obj)); if (!nobj) return NULL; if (!DefineProperty(cx, obj, name, ObjectValue(*nobj), GetterWrapper(NULL), SetterWrapper(NULL), attrs, 0, 0)) { return NULL; } return nobj; } JS_PUBLIC_API(JSBool) JS_DefineConstDoubles(JSContext *cx, JSObject *objArg, JSConstDoubleSpec *cds) { RootedObject obj(cx, objArg); JSBool ok; unsigned attrs; AssertHeapIsIdle(cx); CHECK_REQUEST(cx); JSPropertyOpWrapper noget = GetterWrapper(NULL); JSStrictPropertyOpWrapper noset = SetterWrapper(NULL); for (ok = JS_TRUE; cds->name; cds++) { Value value = DoubleValue(cds->dval); attrs = cds->flags; if (!attrs) attrs = JSPROP_READONLY | JSPROP_PERMANENT; ok = DefineProperty(cx, obj, cds->name, value, noget, noset, attrs, 0, 0); if (!ok) break; } return ok; } JS_PUBLIC_API(JSBool) JS_DefineProperties(JSContext *cx, JSObject *objArg, JSPropertySpec *ps) { RootedObject obj(cx, objArg); JSBool ok; for (ok = true; ps->name; ps++) { ok = DefineProperty(cx, obj, ps->name, UndefinedValue(), ps->getter, ps->setter, ps->flags, Shape::HAS_SHORTID, ps->tinyid); if (!ok) break; } return ok; } static JSBool GetPropertyDescriptorById(JSContext *cx, HandleObject obj, HandleId id, unsigned flags, JSBool own, PropertyDescriptor *desc) { RootedObject obj2(cx); RootedShape shape(cx); if (!LookupPropertyById(cx, obj, id, flags, &obj2, &shape)) return JS_FALSE; if (!shape || (own && obj != obj2)) { desc->obj = NULL; desc->attrs = 0; desc->getter = NULL; desc->setter = NULL; desc->value.setUndefined(); return JS_TRUE; } desc->obj = obj2; if (obj2->isNative()) { desc->attrs = shape->attributes(); desc->getter = shape->getter(); desc->setter = shape->setter(); if (shape->hasSlot()) desc->value = obj2->nativeGetSlot(shape->slot()); else desc->value.setUndefined(); } else { if (obj2->isProxy()) { JSAutoResolveFlags rf(cx, flags); return own ? Proxy::getOwnPropertyDescriptor(cx, obj2, id, false, desc) : Proxy::getPropertyDescriptor(cx, obj2, id, false, desc); } if (!JSObject::getGenericAttributes(cx, obj2, id, &desc->attrs)) return false; desc->getter = NULL; desc->setter = NULL; desc->value.setUndefined(); } return true; } JS_PUBLIC_API(JSBool) JS_GetPropertyDescriptorById(JSContext *cx, JSObject *objArg, jsid idArg, unsigned flags, JSPropertyDescriptor *desc_) { RootedObject obj(cx, objArg); RootedId id(cx, idArg); AutoPropertyDescriptorRooter desc(cx); if (!GetPropertyDescriptorById(cx, obj, id, flags, JS_FALSE, &desc)) return false; *desc_ = desc; return true; } JS_PUBLIC_API(JSBool) JS_GetPropertyAttrsGetterAndSetterById(JSContext *cx, JSObject *objArg, jsid idArg, unsigned *attrsp, JSBool *foundp, JSPropertyOp *getterp, JSStrictPropertyOp *setterp) { RootedObject obj(cx, objArg); RootedId id(cx, idArg); AutoPropertyDescriptorRooter desc(cx); if (!GetPropertyDescriptorById(cx, obj, id, JSRESOLVE_QUALIFIED, JS_FALSE, &desc)) return false; *attrsp = desc.attrs; *foundp = (desc.obj != NULL); if (getterp) *getterp = desc.getter; if (setterp) *setterp = desc.setter; return true; } JS_PUBLIC_API(JSBool) JS_GetPropertyAttributes(JSContext *cx, JSObject *objArg, const char *name, unsigned *attrsp, JSBool *foundp) { RootedObject obj(cx, objArg); JSAtom *atom = Atomize(cx, name, strlen(name)); return atom && JS_GetPropertyAttrsGetterAndSetterById(cx, obj, AtomToId(atom), attrsp, foundp, NULL, NULL); } JS_PUBLIC_API(JSBool) JS_GetUCPropertyAttributes(JSContext *cx, JSObject *objArg, const jschar *name, size_t namelen, unsigned *attrsp, JSBool *foundp) { RootedObject obj(cx, objArg); JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); return atom && JS_GetPropertyAttrsGetterAndSetterById(cx, obj, AtomToId(atom), attrsp, foundp, NULL, NULL); } JS_PUBLIC_API(JSBool) JS_GetPropertyAttrsGetterAndSetter(JSContext *cx, JSObject *objArg, const char *name, unsigned *attrsp, JSBool *foundp, JSPropertyOp *getterp, JSStrictPropertyOp *setterp) { RootedObject obj(cx, objArg); JSAtom *atom = Atomize(cx, name, strlen(name)); return atom && JS_GetPropertyAttrsGetterAndSetterById(cx, obj, AtomToId(atom), attrsp, foundp, getterp, setterp); } JS_PUBLIC_API(JSBool) JS_GetUCPropertyAttrsGetterAndSetter(JSContext *cx, JSObject *objArg, const jschar *name, size_t namelen, unsigned *attrsp, JSBool *foundp, JSPropertyOp *getterp, JSStrictPropertyOp *setterp) { RootedObject obj(cx, objArg); JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); return atom && JS_GetPropertyAttrsGetterAndSetterById(cx, obj, AtomToId(atom), attrsp, foundp, getterp, setterp); } JS_PUBLIC_API(JSBool) JS_GetOwnPropertyDescriptor(JSContext *cx, JSObject *objArg, jsid idArg, jsval *vp) { RootedObject obj(cx, objArg); RootedId id(cx, idArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); return GetOwnPropertyDescriptor(cx, obj, id, vp); } static JSBool SetPropertyAttributesById(JSContext *cx, HandleObject obj, HandleId id, unsigned attrs, JSBool *foundp) { RootedObject obj2(cx); RootedShape shape(cx); if (!LookupPropertyById(cx, obj, id, JSRESOLVE_QUALIFIED, &obj2, &shape)) return false; if (!shape || obj != obj2) { *foundp = false; return true; } JSBool ok = obj->isNative() ? JSObject::changePropertyAttributes(cx, obj, shape, attrs) : JSObject::setGenericAttributes(cx, obj, id, &attrs); if (ok) *foundp = true; return ok; } JS_PUBLIC_API(JSBool) JS_SetPropertyAttributes(JSContext *cx, JSObject *objArg, const char *name, unsigned attrs, JSBool *foundp) { RootedObject obj(cx, objArg); JSAtom *atom = Atomize(cx, name, strlen(name)); RootedId id(cx, AtomToId(atom)); return atom && SetPropertyAttributesById(cx, obj, id, attrs, foundp); } JS_PUBLIC_API(JSBool) JS_SetUCPropertyAttributes(JSContext *cx, JSObject *objArg, const jschar *name, size_t namelen, unsigned attrs, JSBool *foundp) { RootedObject obj(cx, objArg); JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); RootedId id(cx, AtomToId(atom)); return atom && SetPropertyAttributesById(cx, obj, id, attrs, foundp); } JS_PUBLIC_API(JSBool) JS_GetPropertyById(JSContext *cx, JSObject *objArg, jsid idArg, jsval *vp) { return JS_ForwardGetPropertyTo(cx, objArg, idArg, objArg, vp); } JS_PUBLIC_API(JSBool) JS_ForwardGetPropertyTo(JSContext *cx, JSObject *objArg, jsid idArg, JSObject *onBehalfOfArg, jsval *vp) { RootedObject obj(cx, objArg); RootedObject onBehalfOf(cx, onBehalfOfArg); RootedId id(cx, idArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, id); assertSameCompartment(cx, onBehalfOf); JSAutoResolveFlags rf(cx, JSRESOLVE_QUALIFIED); RootedValue value(cx); if (!JSObject::getGeneric(cx, obj, onBehalfOf, id, &value)) return false; *vp = value; return true; } JS_PUBLIC_API(JSBool) JS_GetPropertyByIdDefault(JSContext *cx, JSObject *objArg, jsid idArg, jsval defArg, jsval *vp) { RootedObject obj(cx, objArg); RootedId id(cx, idArg); RootedValue def(cx, defArg); RootedValue value(cx); if (!baseops::GetPropertyDefault(cx, obj, id, def, &value)) return false; *vp = value; return true; } JS_PUBLIC_API(JSBool) JS_GetElement(JSContext *cx, JSObject *objArg, uint32_t index, jsval *vp) { return JS_ForwardGetElementTo(cx, objArg, index, objArg, vp); } JS_PUBLIC_API(JSBool) JS_ForwardGetElementTo(JSContext *cx, JSObject *objArg, uint32_t index, JSObject *onBehalfOfArg, jsval *vp) { RootedObject obj(cx, objArg); RootedObject onBehalfOf(cx, onBehalfOfArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); JSAutoResolveFlags rf(cx, JSRESOLVE_QUALIFIED); RootedValue value(cx); if (!JSObject::getElement(cx, obj, onBehalfOf, index, &value)) return false; *vp = value; return true; } JS_PUBLIC_API(JSBool) JS_GetElementIfPresent(JSContext *cx, JSObject *objArg, uint32_t index, JSObject *onBehalfOfArg, jsval *vp, JSBool* present) { RootedObject obj(cx, objArg); RootedObject onBehalfOf(cx, onBehalfOfArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); JSAutoResolveFlags rf(cx, JSRESOLVE_QUALIFIED); RootedValue value(cx); bool isPresent; if (!JSObject::getElementIfPresent(cx, obj, onBehalfOf, index, &value, &isPresent)) return false; *vp = value; *present = isPresent; return true; } JS_PUBLIC_API(JSBool) JS_GetProperty(JSContext *cx, JSObject *objArg, const char *name, jsval *vp) { RootedObject obj(cx, objArg); JSAtom *atom = Atomize(cx, name, strlen(name)); return atom && JS_GetPropertyById(cx, obj, AtomToId(atom), vp); } JS_PUBLIC_API(JSBool) JS_GetPropertyDefault(JSContext *cx, JSObject *objArg, const char *name, jsval def, jsval *vp) { RootedObject obj(cx, objArg); JSAtom *atom = Atomize(cx, name, strlen(name)); return atom && JS_GetPropertyByIdDefault(cx, obj, AtomToId(atom), def, vp); } JS_PUBLIC_API(JSBool) JS_GetUCProperty(JSContext *cx, JSObject *objArg, const jschar *name, size_t namelen, jsval *vp) { RootedObject obj(cx, objArg); JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); return atom && JS_GetPropertyById(cx, obj, AtomToId(atom), vp); } JS_PUBLIC_API(JSBool) JS_GetMethodById(JSContext *cx, JSObject *objArg, jsid idArg, JSObject **objp, jsval *vp) { RootedObject obj(cx, objArg); RootedId id(cx, idArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, id); RootedValue value(cx); if (!GetMethod(cx, obj, id, 0, &value)) return JS_FALSE; *vp = value; if (objp) *objp = obj; return JS_TRUE; } JS_PUBLIC_API(JSBool) JS_GetMethod(JSContext *cx, JSObject *objArg, const char *name, JSObject **objp, jsval *vp) { JSAtom *atom = Atomize(cx, name, strlen(name)); return atom && JS_GetMethodById(cx, objArg, AtomToId(atom), objp, vp); } JS_PUBLIC_API(JSBool) JS_SetPropertyById(JSContext *cx, JSObject *objArg, jsid idArg, jsval *vp) { RootedObject obj(cx, objArg); RootedId id(cx, idArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, id); JSAutoResolveFlags rf(cx, JSRESOLVE_QUALIFIED | JSRESOLVE_ASSIGNING); RootedValue value(cx, *vp); if (!JSObject::setGeneric(cx, obj, obj, id, &value, false)) return false; *vp = value; return true; } JS_PUBLIC_API(JSBool) JS_SetElement(JSContext *cx, JSObject *objArg, uint32_t index, jsval *vp) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, *vp); JSAutoResolveFlags rf(cx, JSRESOLVE_QUALIFIED | JSRESOLVE_ASSIGNING); RootedValue value(cx, *vp); if (!JSObject::setElement(cx, obj, obj, index, &value, false)) return false; *vp = value; return true; } JS_PUBLIC_API(JSBool) JS_SetProperty(JSContext *cx, JSObject *objArg, const char *name, jsval *vp) { RootedObject obj(cx, objArg); JSAtom *atom = Atomize(cx, name, strlen(name)); return atom && JS_SetPropertyById(cx, obj, AtomToId(atom), vp); } JS_PUBLIC_API(JSBool) JS_SetUCProperty(JSContext *cx, JSObject *objArg, const jschar *name, size_t namelen, jsval *vp) { RootedObject obj(cx, objArg); JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); return atom && JS_SetPropertyById(cx, obj, AtomToId(atom), vp); } JS_PUBLIC_API(JSBool) JS_DeletePropertyById2(JSContext *cx, JSObject *objArg, jsid id, jsval *rval) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, id); JSAutoResolveFlags rf(cx, JSRESOLVE_QUALIFIED); RootedValue value(cx); if (JSID_IS_SPECIAL(id)) { Rooted<SpecialId> sid(cx, JSID_TO_SPECIALID(id)); if (!JSObject::deleteSpecial(cx, obj, sid, &value, false)) return false; } else { if (!JSObject::deleteByValue(cx, obj, IdToValue(id), &value, false)) return false; } *rval = value; return true; } JS_PUBLIC_API(JSBool) JS_DeleteElement2(JSContext *cx, JSObject *objArg, uint32_t index, jsval *rval) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); JSAutoResolveFlags rf(cx, JSRESOLVE_QUALIFIED); RootedValue value(cx); if (!JSObject::deleteElement(cx, obj, index, &value, false)) return false; *rval = value; return true; } JS_PUBLIC_API(JSBool) JS_DeleteProperty2(JSContext *cx, JSObject *objArg, const char *name, jsval *rval) { RootedObject obj(cx, objArg); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); JSAutoResolveFlags rf(cx, JSRESOLVE_QUALIFIED); JSAtom *atom = Atomize(cx, name, strlen(name)); if (!atom) return false; RootedValue value(cx); if (!JSObject::deleteByValue(cx, obj, StringValue(atom), &value, false)) return false; *rval = value; return true; } JS_PUBLIC_API(JSBool) JS_DeleteUCProperty2(JSContext *cx, JSObject *objArg, const jschar *name, size_t namelen, jsval *rval) { RootedObject obj(cx, objArg); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); JSAutoResolveFlags rf(cx, JSRESOLVE_QUALIFIED); JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); if (!atom) return false; RootedValue value(cx); if (!JSObject::deleteByValue(cx, obj, StringValue(atom), &value, false)) return false; *rval = value; return true; } JS_PUBLIC_API(JSBool) JS_DeletePropertyById(JSContext *cx, JSObject *objArg, jsid idArg) { jsval junk; return JS_DeletePropertyById2(cx, objArg, idArg, &junk); } JS_PUBLIC_API(JSBool) JS_DeleteElement(JSContext *cx, JSObject *objArg, uint32_t index) { jsval junk; return JS_DeleteElement2(cx, objArg, index, &junk); } JS_PUBLIC_API(JSBool) JS_DeleteProperty(JSContext *cx, JSObject *objArg, const char *name) { jsval junk; return JS_DeleteProperty2(cx, objArg, name, &junk); } static Shape * LastConfigurableShape(JSObject *obj) { for (Shape::Range r(obj->lastProperty()->all()); !r.empty(); r.popFront()) { Shape *shape = &r.front(); if (shape->configurable()) return shape; } return NULL; } JS_PUBLIC_API(void) JS_ClearNonGlobalObject(JSContext *cx, JSObject *objArg) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); JS_ASSERT(!obj->isGlobal()); if (!obj->isNative()) return; /* Remove all configurable properties from obj. */ while (Shape *shape = LastConfigurableShape(obj)) { if (!obj->removeProperty(cx, shape->propid())) return; } /* Set all remaining writable plain data properties to undefined. */ for (Shape::Range r(obj->lastProperty()->all()); !r.empty(); r.popFront()) { Shape *shape = &r.front(); if (shape->isDataDescriptor() && shape->writable() && shape->hasDefaultSetter() && shape->hasSlot()) { obj->nativeSetSlot(shape->slot(), UndefinedValue()); } } } JS_PUBLIC_API(void) JS_SetAllNonReservedSlotsToUndefined(JSContext *cx, JSObject *objArg) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); if (!obj->isNative()) return; Class *clasp = obj->getClass(); unsigned numReserved = JSCLASS_RESERVED_SLOTS(clasp); unsigned numSlots = obj->slotSpan(); for (unsigned i = numReserved; i < numSlots; i++) obj->setSlot(i, UndefinedValue()); } JS_PUBLIC_API(JSIdArray *) JS_Enumerate(JSContext *cx, JSObject *objArg) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); AutoIdVector props(cx); JSIdArray *ida; if (!GetPropertyNames(cx, obj, JSITER_OWNONLY, &props) || !VectorToIdArray(cx, props, &ida)) return NULL; return ida; } /* * XXX reverse iterator for properties, unreverse and meld with jsinterp.c's * prop_iterator_class somehow... * + preserve the obj->enumerate API while optimizing the native object case * + native case here uses a Shape *, but that iterates in reverse! * + so we make non-native match, by reverse-iterating after JS_Enumerating */ const uint32_t JSSLOT_ITER_INDEX = 0; static void prop_iter_finalize(FreeOp *fop, JSObject *obj) { void *pdata = obj->getPrivate(); if (!pdata) return; if (obj->getSlot(JSSLOT_ITER_INDEX).toInt32() >= 0) { /* Non-native case: destroy the ida enumerated when obj was created. */ JSIdArray *ida = (JSIdArray *) pdata; DestroyIdArray(fop, ida); } } static void prop_iter_trace(JSTracer *trc, JSObject *obj) { void *pdata = obj->getPrivate(); if (!pdata) return; if (obj->getSlot(JSSLOT_ITER_INDEX).toInt32() < 0) { /* * Native case: just mark the next property to visit. We don't need a * barrier here because the pointer is updated via setPrivate, which * always takes a barrier. */ Shape *tmp = (Shape *)pdata; MarkShapeUnbarriered(trc, &tmp, "prop iter shape"); obj->setPrivateUnbarriered(tmp); } else { /* Non-native case: mark each id in the JSIdArray private. */ JSIdArray *ida = (JSIdArray *) pdata; MarkIdRange(trc, ida->length, ida->vector, "prop iter"); } } static Class prop_iter_class = { "PropertyIterator", JSCLASS_HAS_PRIVATE | JSCLASS_IMPLEMENTS_BARRIERS | JSCLASS_HAS_RESERVED_SLOTS(1), JS_PropertyStub, /* addProperty */ JS_PropertyStub, /* delProperty */ JS_PropertyStub, /* getProperty */ JS_StrictPropertyStub, /* setProperty */ JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, prop_iter_finalize, NULL, /* checkAccess */ NULL, /* call */ NULL, /* construct */ NULL, /* hasInstance */ prop_iter_trace }; JS_PUBLIC_API(JSObject *) JS_NewPropertyIterator(JSContext *cx, JSObject *objArg) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); RootedObject iterobj(cx, NewObjectWithClassProto(cx, &prop_iter_class, NULL, obj)); if (!iterobj) return NULL; int index; if (obj->isNative()) { /* Native case: start with the last property in obj. */ iterobj->setPrivateGCThing(obj->lastProperty()); index = -1; } else { /* Non-native case: enumerate a JSIdArray and keep it via private. */ JSIdArray *ida = JS_Enumerate(cx, obj); if (!ida) return NULL; iterobj->setPrivate((void *)ida); index = ida->length; } /* iterobj cannot escape to other threads here. */ iterobj->setSlot(JSSLOT_ITER_INDEX, Int32Value(index)); return iterobj; } JS_PUBLIC_API(JSBool) JS_NextProperty(JSContext *cx, JSObject *iterobjArg, jsid *idp) { RootedObject iterobj(cx, iterobjArg); AutoAssertNoGC nogc; int32_t i; Shape *shape; JSIdArray *ida; AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, iterobj); i = iterobj->getSlot(JSSLOT_ITER_INDEX).toInt32(); if (i < 0) { /* Native case: private data is a property tree node pointer. */ JS_ASSERT(iterobj->getParent()->isNative()); shape = (Shape *) iterobj->getPrivate(); while (shape->previous() && !shape->enumerable()) shape = shape->previous(); if (!shape->previous()) { JS_ASSERT(shape->isEmptyShape()); *idp = JSID_VOID; } else { iterobj->setPrivateGCThing(const_cast<Shape *>(shape->previous().get())); *idp = shape->propid(); } } else { /* Non-native case: use the ida enumerated when iterobj was created. */ ida = (JSIdArray *) iterobj->getPrivate(); JS_ASSERT(i <= ida->length); STATIC_ASSUME(i <= ida->length); if (i == 0) { *idp = JSID_VOID; } else { *idp = ida->vector[--i]; iterobj->setSlot(JSSLOT_ITER_INDEX, Int32Value(i)); } } return JS_TRUE; } JS_PUBLIC_API(JSBool) JS_ArrayIterator(JSContext *cx, unsigned argc, jsval *vp) { CallArgs args = CallArgsFromVp(argc, vp); Rooted<Value> target(cx, args.thisv()); AssertHeapIsIdle(cx); assertSameCompartment(cx, target); CHECK_REQUEST(cx); JSObject *iterobj = ElementIteratorObject::create(cx, target); if (!iterobj) return false; vp->setObject(*iterobj); return true; } JS_PUBLIC_API(jsval) JS_GetReservedSlot(RawObject obj, uint32_t index) { return obj->getReservedSlot(index); } JS_PUBLIC_API(void) JS_SetReservedSlot(RawObject obj, uint32_t index, RawValue value) { obj->setReservedSlot(index, value); } JS_PUBLIC_API(JSObject *) JS_NewArrayObject(JSContext *cx, int length, jsval *vector) { JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, JSValueArray(vector, vector ? (uint32_t)length : 0)); return NewDenseCopiedArray(cx, (uint32_t)length, vector); } JS_PUBLIC_API(JSBool) JS_IsArrayObject(JSContext *cx, JSObject *objArg) { RootedObject obj(cx, objArg); assertSameCompartment(cx, obj); return ObjectClassIs(*obj, ESClass_Array, cx); } JS_PUBLIC_API(JSBool) JS_GetArrayLength(JSContext *cx, JSObject *objArg, uint32_t *lengthp) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); return GetLengthProperty(cx, obj, lengthp); } JS_PUBLIC_API(JSBool) JS_SetArrayLength(JSContext *cx, JSObject *objArg, uint32_t length) { RootedObject obj(cx, objArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); return SetLengthProperty(cx, obj, length); } JS_PUBLIC_API(JSBool) JS_CheckAccess(JSContext *cx, JSObject *objArg, jsid idArg, JSAccessMode mode, jsval *vp, unsigned *attrsp) { RootedObject obj(cx, objArg); RootedId id(cx, idArg); RootedValue value(cx, *vp); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, id); JSBool status = CheckAccess(cx, obj, id, mode, &value, attrsp); *vp = value; return status; } JS_PUBLIC_API(void) JS_HoldPrincipals(JSPrincipals *principals) { JS_ATOMIC_INCREMENT(&principals->refcount); } JS_PUBLIC_API(void) JS_DropPrincipals(JSRuntime *rt, JSPrincipals *principals) { int rc = JS_ATOMIC_DECREMENT(&principals->refcount); if (rc == 0) rt->destroyPrincipals(principals); } JS_PUBLIC_API(void) JS_SetSecurityCallbacks(JSRuntime *rt, const JSSecurityCallbacks *scb) { JS_ASSERT(scb != &NullSecurityCallbacks); rt->securityCallbacks = scb ? scb : &NullSecurityCallbacks; } JS_PUBLIC_API(const JSSecurityCallbacks *) JS_GetSecurityCallbacks(JSRuntime *rt) { return (rt->securityCallbacks != &NullSecurityCallbacks) ? rt->securityCallbacks : NULL; } JS_PUBLIC_API(void) JS_SetTrustedPrincipals(JSRuntime *rt, JSPrincipals *prin) { rt->setTrustedPrincipals(prin); } extern JS_PUBLIC_API(void) JS_InitDestroyPrincipalsCallback(JSRuntime *rt, JSDestroyPrincipalsOp destroyPrincipals) { JS_ASSERT(destroyPrincipals); JS_ASSERT(!rt->destroyPrincipals); rt->destroyPrincipals = destroyPrincipals; } JS_PUBLIC_API(JSFunction *) JS_NewFunction(JSContext *cx, JSNative native, unsigned nargs, unsigned flags, JSObject *parentArg, const char *name) { RootedObject parent(cx, parentArg); JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); JSAtom *atom; AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, parent); if (!name) { atom = NULL; } else { atom = Atomize(cx, name, strlen(name)); if (!atom) return NULL; } return js_NewFunction(cx, NULL, native, nargs, flags, parent, atom); } JS_PUBLIC_API(JSFunction *) JS_NewFunctionById(JSContext *cx, JSNative native, unsigned nargs, unsigned flags, JSObject *parentArg, jsid id) { RootedObject parent(cx, parentArg); JS_ASSERT(JSID_IS_STRING(id)); JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, parent); return js_NewFunction(cx, NULL, native, nargs, flags, parent, JSID_TO_ATOM(id)); } JS_PUBLIC_API(JSObject *) JS_CloneFunctionObject(JSContext *cx, JSObject *funobjArg, JSRawObject parentArg) { RootedObject funobj(cx, funobjArg); RootedObject parent(cx, parentArg); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, parent); // XXX no funobj for now if (!parent) parent = cx->global(); if (!funobj->isFunction()) { ReportIsNotFunction(cx, ObjectValue(*funobj)); return NULL; } /* * If a function was compiled to be lexically nested inside some other * script, we cannot clone it without breaking the compiler's assumptions. */ RootedFunction fun(cx, funobj->toFunction()); if (fun->isInterpreted() && (fun->script()->enclosingStaticScope() || (fun->script()->compileAndGo && !parent->isGlobal()))) { JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_CLONE_FUNOBJ_SCOPE); return NULL; } if (fun->isBoundFunction()) { JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_CLONE_OBJECT); return NULL; } return CloneFunctionObject(cx, fun, parent, fun->getAllocKind()); } JS_PUBLIC_API(JSObject *) JS_GetFunctionObject(JSFunction *fun) { return fun; } JS_PUBLIC_API(JSString *) JS_GetFunctionId(JSFunction *fun) { return fun->atom(); } JS_PUBLIC_API(JSString *) JS_GetFunctionDisplayId(JSFunction *fun) { return fun->displayAtom(); } JS_PUBLIC_API(unsigned) JS_GetFunctionFlags(JSFunction *fun) { return fun->flags; } JS_PUBLIC_API(uint16_t) JS_GetFunctionArity(JSFunction *fun) { return fun->nargs; } JS_PUBLIC_API(JSBool) JS_ObjectIsFunction(JSContext *cx, RawObject obj) { return obj->isFunction(); } JS_PUBLIC_API(JSBool) JS_ObjectIsCallable(JSContext *cx, RawObject obj) { return obj->isCallable(); } JS_PUBLIC_API(JSBool) JS_IsNativeFunction(JSRawObject funobj, JSNative call) { if (!funobj->isFunction()) return false; JSFunction *fun = funobj->toFunction(); return fun->isNative() && fun->native() == call; } JS_PUBLIC_API(JSObject*) JS_BindCallable(JSContext *cx, JSObject *targetArg, JSRawObject newThis) { RootedObject target(cx, targetArg); RootedValue thisArg(cx, ObjectValue(*newThis)); return js_fun_bind(cx, target, thisArg, NULL, 0); } JSBool js_generic_native_method_dispatcher(JSContext *cx, unsigned argc, Value *vp) { CallArgs args = CallArgsFromVp(argc, vp); JSFunctionSpec *fs = (JSFunctionSpec *) vp->toObject().toFunction()->getExtendedSlot(0).toPrivate(); JS_ASSERT((fs->flags & JSFUN_GENERIC_NATIVE) != 0); if (argc < 1) { js_ReportMissingArg(cx, args.calleev(), 0); return JS_FALSE; } /* * Copy all actual (argc) arguments down over our |this| parameter, vp[1], * which is almost always the class constructor object, e.g. Array. Then * call the corresponding prototype native method with our first argument * passed as |this|. */ memmove(vp + 1, vp + 2, argc * sizeof(jsval)); /* Clear the last parameter in case too few arguments were passed. */ vp[2 + --argc].setUndefined(); return fs->call.op(cx, argc, vp); } JS_PUBLIC_API(JSBool) JS_DefineFunctions(JSContext *cx, JSObject *objArg, JSFunctionSpec *fs) { RootedObject obj(cx, objArg); JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); unsigned flags; RootedObject ctor(cx); JSFunction *fun; AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); for (; fs->name; fs++) { flags = fs->flags; RootedAtom atom(cx, Atomize(cx, fs->name, strlen(fs->name))); if (!atom) return JS_FALSE; Rooted<jsid> id(cx, AtomToId(atom)); /* * Define a generic arity N+1 static method for the arity N prototype * method if flags contains JSFUN_GENERIC_NATIVE. */ if (flags & JSFUN_GENERIC_NATIVE) { if (!ctor) { ctor = JS_GetConstructor(cx, obj); if (!ctor) return JS_FALSE; } flags &= ~JSFUN_GENERIC_NATIVE; fun = js_DefineFunction(cx, ctor, id, js_generic_native_method_dispatcher, fs->nargs + 1, flags, NULL, JSFunction::ExtendedFinalizeKind); if (!fun) return JS_FALSE; /* * As jsapi.h notes, fs must point to storage that lives as long * as fun->object lives. */ fun->setExtendedSlot(0, PrivateValue(fs)); } fun = js_DefineFunction(cx, obj, id, fs->call.op, fs->nargs, flags, fs->selfHostedName); if (!fun) return JS_FALSE; if (fs->call.info) fun->setJitInfo(fs->call.info); } return JS_TRUE; } JS_PUBLIC_API(JSFunction *) JS_DefineFunction(JSContext *cx, JSObject *objArg, const char *name, JSNative call, unsigned nargs, unsigned attrs) { RootedObject obj(cx, objArg); JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); JSAtom *atom = Atomize(cx, name, strlen(name)); if (!atom) return NULL; Rooted<jsid> id(cx, AtomToId(atom)); return js_DefineFunction(cx, obj, id, call, nargs, attrs); } JS_PUBLIC_API(JSFunction *) JS_DefineUCFunction(JSContext *cx, JSObject *objArg, const jschar *name, size_t namelen, JSNative call, unsigned nargs, unsigned attrs) { RootedObject obj(cx, objArg); JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); if (!atom) return NULL; Rooted<jsid> id(cx, AtomToId(atom)); return js_DefineFunction(cx, obj, id, call, nargs, attrs); } extern JS_PUBLIC_API(JSFunction *) JS_DefineFunctionById(JSContext *cx, JSObject *objArg, jsid id_, JSNative call, unsigned nargs, unsigned attrs) { RootedObject obj(cx, objArg); RootedId id(cx, id_); JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); return js_DefineFunction(cx, obj, id, call, nargs, attrs); } struct AutoLastFrameCheck { AutoLastFrameCheck(JSContext *cx JS_GUARD_OBJECT_NOTIFIER_PARAM) : cx(cx) { JS_ASSERT(cx); JS_GUARD_OBJECT_NOTIFIER_INIT; } ~AutoLastFrameCheck() { if (cx->isExceptionPending() && !JS_IsRunning(cx) && !cx->hasRunOption(JSOPTION_DONT_REPORT_UNCAUGHT)) { js_ReportUncaughtException(cx); } } private: JSContext *cx; JS_DECL_USE_GUARD_OBJECT_NOTIFIER }; /* Use the fastest available getc. */ #if defined(HAVE_GETC_UNLOCKED) # define fast_getc getc_unlocked #elif defined(HAVE__GETC_NOLOCK) # define fast_getc _getc_nolock #else # define fast_getc getc #endif typedef Vector<char, 8, TempAllocPolicy> FileContents; static bool ReadCompleteFile(JSContext *cx, FILE *fp, FileContents &buffer) { /* Get the complete length of the file, if possible. */ struct stat st; int ok = fstat(fileno(fp), &st); if (ok != 0) return false; if (st.st_size > 0) { if (!buffer.reserve(st.st_size)) return false; } // Read in the whole file. Note that we can't assume the data's length // is actually st.st_size, because 1) some files lie about their size // (/dev/zero and /dev/random), and 2) reading files in text mode on // Windows collapses "\r\n" pairs to single \n characters. for (;;) { int c = fast_getc(fp); if (c == EOF) break; if (!buffer.append(c)) return false; } return true; } class AutoFile { FILE *fp_; public: AutoFile() : fp_(NULL) {} ~AutoFile() { if (fp_ && fp_ != stdin) fclose(fp_); } FILE *fp() const { return fp_; } bool open(JSContext *cx, const char *filename); bool readAll(JSContext *cx, FileContents &buffer) { JS_ASSERT(fp_); return ReadCompleteFile(cx, fp_, buffer); } }; /* * Open a source file for reading. Supports "-" and NULL to mean stdin. The * return value must be fclosed unless it is stdin. */ bool AutoFile::open(JSContext *cx, const char *filename) { if (!filename || strcmp(filename, "-") == 0) { fp_ = stdin; } else { fp_ = fopen(filename, "r"); if (!fp_) { JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_OPEN, filename, "No such file or directory"); return false; } } return true; } JS::CompileOptions::CompileOptions(JSContext *cx) : principals(NULL), originPrincipals(NULL), version(cx->findVersion()), versionSet(false), utf8(false), filename(NULL), lineno(1), compileAndGo(cx->hasRunOption(JSOPTION_COMPILE_N_GO)), noScriptRval(cx->hasRunOption(JSOPTION_NO_SCRIPT_RVAL)), selfHostingMode(false), sourcePolicy(SAVE_SOURCE) { } JSScript * JS::Compile(JSContext *cx, HandleObject obj, CompileOptions options, const jschar *chars, size_t length) { Maybe<AutoVersionAPI> mava; if (options.versionSet) { mava.construct(cx, options.version); // AutoVersionAPI propagates some compilation flags through. options.version = mava.ref().version(); } JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, options.principals, options.originPrincipals); AutoLastFrameCheck lfc(cx); return frontend::CompileScript(cx, obj, NULL, options, chars, length); } JSScript * JS::Compile(JSContext *cx, HandleObject obj, CompileOptions options, const char *bytes, size_t length) { jschar *chars; if (options.utf8) chars = InflateString(cx, bytes, &length, CESU8Encoding); else chars = InflateString(cx, bytes, &length); if (!chars) return NULL; JSScript *script = Compile(cx, obj, options, chars, length); js_free(chars); return script; } JSScript * JS::Compile(JSContext *cx, HandleObject obj, CompileOptions options, FILE *fp) { FileContents buffer(cx); if (!ReadCompleteFile(cx, fp, buffer)) return NULL; JSScript *script = Compile(cx, obj, options, buffer.begin(), buffer.length()); return script; } JSScript * JS::Compile(JSContext *cx, HandleObject obj, CompileOptions options, const char *filename) { AutoFile file; if (!file.open(cx, filename)) return NULL; options = options.setFileAndLine(filename, 1); JSScript *script = Compile(cx, obj, options, file.fp()); return script; } extern JS_PUBLIC_API(JSScript *) JS_CompileUCScriptForPrincipalsVersion(JSContext *cx, JSObject *objArg, JSPrincipals *principals, const jschar *chars, size_t length, const char *filename, unsigned lineno, JSVersion version) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setPrincipals(principals) .setFileAndLine(filename, lineno) .setVersion(version); return Compile(cx, obj, options, chars, length); } extern JS_PUBLIC_API(JSScript *) JS_CompileUCScriptForPrincipalsVersionOrigin(JSContext *cx, JSObject *objArg, JSPrincipals *principals, JSPrincipals *originPrincipals, const jschar *chars, size_t length, const char *filename, unsigned lineno, JSVersion version) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setPrincipals(principals) .setOriginPrincipals(originPrincipals) .setFileAndLine(filename, lineno) .setVersion(version); return Compile(cx, obj, options, chars, length); } JS_PUBLIC_API(JSScript *) JS_CompileUCScriptForPrincipals(JSContext *cx, JSObject *objArg, JSPrincipals *principals, const jschar *chars, size_t length, const char *filename, unsigned lineno) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setPrincipals(principals) .setFileAndLine(filename, lineno); return Compile(cx, obj, options, chars, length); } JS_PUBLIC_API(JSScript *) JS_CompileUCScript(JSContext *cx, JSObject *objArg, const jschar *chars, size_t length, const char *filename, unsigned lineno) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setFileAndLine(filename, lineno); return Compile(cx, obj, options, chars, length); } JS_PUBLIC_API(JSScript *) JS_CompileScriptForPrincipalsVersion(JSContext *cx, JSObject *objArg, JSPrincipals *principals, const char *bytes, size_t length, const char *filename, unsigned lineno, JSVersion version) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setPrincipals(principals) .setFileAndLine(filename, lineno) .setVersion(version); return Compile(cx, obj, options, bytes, length); } JS_PUBLIC_API(JSScript *) JS_CompileScriptForPrincipals(JSContext *cx, JSObject *objArg, JSPrincipals *principals, const char *bytes, size_t length, const char *filename, unsigned lineno) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setPrincipals(principals) .setFileAndLine(filename, lineno); return Compile(cx, obj, options, bytes, length); } JS_PUBLIC_API(JSScript *) JS_CompileScript(JSContext *cx, JSObject *objArg, const char *bytes, size_t length, const char *filename, unsigned lineno) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setFileAndLine(filename, lineno); return Compile(cx, obj, options, bytes, length); } JS_PUBLIC_API(JSBool) JS_BufferIsCompilableUnit(JSContext *cx, JSBool bytes_are_utf8, JSObject *objArg, const char *bytes, size_t length) { RootedObject obj(cx, objArg); jschar *chars; JSBool result; JSExceptionState *exnState; JSErrorReporter older; AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); if (bytes_are_utf8) chars = InflateString(cx, bytes, &length, CESU8Encoding); else chars = InflateString(cx, bytes, &length); if (!chars) return JS_TRUE; /* * Return true on any out-of-memory error, so our caller doesn't try to * collect more buffered source. */ result = JS_TRUE; exnState = JS_SaveExceptionState(cx); { CompileOptions options(cx); options.setCompileAndGo(false); Parser parser(cx, options, chars, length, /* foldConstants = */ true); if (parser.init()) { older = JS_SetErrorReporter(cx, NULL); if (!parser.parse(obj) && parser.tokenStream.isUnexpectedEOF()) { /* * We ran into an error. If it was because we ran out of * source, we return false so our caller knows to try to * collect more buffered source. */ result = JS_FALSE; } JS_SetErrorReporter(cx, older); } } js_free(chars); JS_RestoreExceptionState(cx, exnState); return result; } JS_PUBLIC_API(JSScript *) JS_CompileUTF8File(JSContext *cx, JSObject *objArg, const char *filename) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setUTF8(true) .setFileAndLine(filename, 1); return Compile(cx, obj, options, filename); } JS_PUBLIC_API(JSScript *) JS_CompileUTF8FileHandleForPrincipals(JSContext *cx, JSObject *objArg, const char *filename, FILE *file, JSPrincipals *principals) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setUTF8(true) .setFileAndLine(filename, 1) .setPrincipals(principals); return Compile(cx, obj, options, file); } JS_PUBLIC_API(JSScript *) JS_CompileUTF8FileHandleForPrincipalsVersion(JSContext *cx, JSObject *objArg, const char *filename, FILE *file, JSPrincipals *principals, JSVersion version) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setUTF8(true) .setFileAndLine(filename, 1) .setPrincipals(principals) .setVersion(version); return Compile(cx, obj, options, file); } JS_PUBLIC_API(JSScript *) JS_CompileUTF8FileHandle(JSContext *cx, JSObject *objArg, const char *filename, FILE *file) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setUTF8(true) .setFileAndLine(filename, 1); return Compile(cx, obj, options, file); } JS_PUBLIC_API(JSObject *) JS_GetGlobalFromScript(JSScript *script) { JS_ASSERT(!script->isCachedEval); return &script->global(); } JS_PUBLIC_API(JSFunction *) JS::CompileFunction(JSContext *cx, HandleObject obj, CompileOptions options, const char *name, unsigned nargs, const char **argnames, const jschar *chars, size_t length) { Maybe<AutoVersionAPI> mava; if (options.versionSet) { mava.construct(cx, options.version); // AutoVersionAPI propagates some compilation flags through. options.version = mava.ref().version(); } JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, options.principals, options.originPrincipals); AutoLastFrameCheck lfc(cx); RootedAtom funAtom(cx); if (name) { funAtom = Atomize(cx, name, strlen(name)); if (!funAtom) return NULL; } AutoNameVector formals(cx); for (unsigned i = 0; i < nargs; i++) { RootedAtom argAtom(cx, Atomize(cx, argnames[i], strlen(argnames[i]))); if (!argAtom || !formals.append(argAtom->asPropertyName())) return NULL; } RootedFunction fun(cx, js_NewFunction(cx, NULL, NULL, 0, JSFUN_INTERPRETED, obj, funAtom)); if (!fun) return NULL; if (!frontend::CompileFunctionBody(cx, fun, options, formals, chars, length)) return NULL; if (obj && funAtom) { Rooted<jsid> id(cx, AtomToId(funAtom)); RootedValue value(cx, ObjectValue(*fun)); if (!JSObject::defineGeneric(cx, obj, id, value, NULL, NULL, JSPROP_ENUMERATE)) return NULL; } return fun; } JS_PUBLIC_API(JSFunction *) JS::CompileFunction(JSContext *cx, HandleObject obj, CompileOptions options, const char *name, unsigned nargs, const char **argnames, const char *bytes, size_t length) { jschar *chars; if (options.utf8) chars = InflateString(cx, bytes, &length, CESU8Encoding); else chars = InflateString(cx, bytes, &length); if (!chars) return NULL; JSFunction *fun = CompileFunction(cx, obj, options, name, nargs, argnames, chars, length); js_free(chars); return fun; } JS_PUBLIC_API(JSFunction *) JS_CompileUCFunctionForPrincipalsVersion(JSContext *cx, JSObject *obj_, JSPrincipals *principals, const char *name, unsigned nargs, const char **argnames, const jschar *chars, size_t length, const char *filename, unsigned lineno, JSVersion version) { RootedObject obj(cx, obj_); CompileOptions options(cx); options.setPrincipals(principals) .setFileAndLine(filename, lineno) .setVersion(version); return CompileFunction(cx, obj, options, name, nargs, argnames, chars, length); } JS_PUBLIC_API(JSFunction *) JS_CompileUCFunctionForPrincipals(JSContext *cx, JSObject *objArg, JSPrincipals *principals, const char *name, unsigned nargs, const char **argnames, const jschar *chars, size_t length, const char *filename, unsigned lineno) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setPrincipals(principals) .setFileAndLine(filename, lineno); return CompileFunction(cx, obj, options, name, nargs, argnames, chars, length); } JS_PUBLIC_API(JSFunction *) JS_CompileUCFunction(JSContext *cx, JSObject *objArg, const char *name, unsigned nargs, const char **argnames, const jschar *chars, size_t length, const char *filename, unsigned lineno) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setFileAndLine(filename, lineno); return CompileFunction(cx, obj, options, name, nargs, argnames, chars, length); } JS_PUBLIC_API(JSFunction *) JS_CompileFunctionForPrincipals(JSContext *cx, JSObject *objArg, JSPrincipals *principals, const char *name, unsigned nargs, const char **argnames, const char *bytes, size_t length, const char *filename, unsigned lineno) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setPrincipals(principals) .setFileAndLine(filename, lineno); return CompileFunction(cx, obj, options, name, nargs, argnames, bytes, length); } JS_PUBLIC_API(JSFunction *) JS_CompileFunction(JSContext *cx, JSObject *objArg, const char *name, unsigned nargs, const char **argnames, const char *bytes, size_t length, const char *filename, unsigned lineno) { RootedObject obj(cx, objArg); CompileOptions options(cx); options.setFileAndLine(filename, lineno); return CompileFunction(cx, obj, options, name, nargs, argnames, bytes, length); } JS_PUBLIC_API(JSString *) JS_DecompileScript(JSContext *cx, JSScript *script, const char *name, unsigned indent) { JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); RootedFunction fun(cx, script->function()); if (fun) return JS_DecompileFunction(cx, fun, indent); return script->sourceData(cx); } JS_PUBLIC_API(JSString *) JS_DecompileFunction(JSContext *cx, JSFunction *funArg, unsigned indent) { JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, funArg); RootedFunction fun(cx, funArg); return FunctionToString(cx, fun, false, !(indent & JS_DONT_PRETTY_PRINT)); } JS_PUBLIC_API(JSString *) JS_DecompileFunctionBody(JSContext *cx, JSFunction *funArg, unsigned indent) { JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, funArg); RootedFunction fun(cx, funArg); return FunctionToString(cx, fun, true, !(indent & JS_DONT_PRETTY_PRINT)); } JS_NEVER_INLINE JS_PUBLIC_API(JSBool) JS_ExecuteScript(JSContext *cx, JSObject *objArg, JSScript *scriptArg, jsval *rval) { RootedObject obj(cx, objArg); RootedScript script(cx, scriptArg); JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj); if (cx->compartment != obj->compartment()) *(volatile int *) 0 = 0xf0; AutoLastFrameCheck lfc(cx); /* * Mozilla caches pre-compiled scripts (e.g., in the XUL prototype cache) * and runs them against multiple globals. With a compartment per global, * this requires cloning the pre-compiled script into each new global. * Since each script gets run once, there is no point in trying to cache * this clone. Ideally, this would be handled at some pinch point in * mozilla, but there doesn't seem to be one, so we handle it here. */ if (script->compartment() != obj->compartment()) { script = CloneScript(cx, NullPtr(), NullPtr(), script); if (!script.get()) return false; } else { script = scriptArg; } return Execute(cx, script, *obj, rval); } JS_PUBLIC_API(JSBool) JS_ExecuteScriptVersion(JSContext *cx, JSObject *objArg, JSScript *script, jsval *rval, JSVersion version) { RootedObject obj(cx, objArg); AutoVersionAPI ava(cx, version); return JS_ExecuteScript(cx, obj, script, rval); } extern JS_PUBLIC_API(bool) JS::Evaluate(JSContext *cx, HandleObject obj, CompileOptions options, const jschar *chars, size_t length, jsval *rval) { Maybe<AutoVersionAPI> mava; if (options.versionSet) { mava.construct(cx, options.version); // AutoVersionAPI propagates some compilation flags through. options.version = mava.ref().version(); } JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment); AssertHeapIsIdle(cx); CHECK_REQUEST(cx); assertSameCompartment(cx, obj, options.principals, options.originPrincipals); AutoLastFrameCheck lfc(cx); options.setCompileAndGo(true); options.setNoScriptRval(!rval); RootedScript script(cx, frontend::CompileScript(cx, obj, NULL, options, chars, length)); if (!script) return false; JS_ASSERT(script->getVersion() == options.version); return Execute(cx, script, *obj, rval); } extern JS_PUBLIC_API(bool) JS::Evaluate(JSContext *cx, HandleObject obj, CompileOptions options, const char *bytes, size_t length, jsval *rval) { jschar *chars; if (options.utf8) chars = InflateString(cx, bytes, &length, CESU8Encoding); else chars = InflateString(cx, bytes, &length); if (!chars) return false; bool ok = Evaluate(cx, obj, options, chars, length, rval); js_free(chars); return ok; } extern JS_PUBLIC_API(bool) JS::Evaluate(JSContext *cx, HandleObject obj, CompileOptions options, const char *filename, jsval *rval) { FileContents buffer(cx); { AutoFile file; if (!file.open(cx, filename) || !file.readAll(cx, buffer)) return false; } options = options.setFileAndLine(filename, 1); return Evaluate(cx, obj, options, buffer.begin(), buffer.length(), rval); } JS_PUBLIC_API(JSBool) JS_EvaluateUCScriptForPrincipals(JSContext *cx, JSObject *objArg,
__label__pos
0.988671
Aging Scheme for Time Based Indexes: Statistic Based Automated Index Generation Context: I am working on building out an aging scheme for time based indexes for log data. I know about closing/opening, snapshot/restore, flushing and deleting, however each of these methods functions off the presumption that you are more concerned with the Elasticsearch index entities themselves, and not the powerful data control and query results that Elasticsearch offers. When it comes to long-term statistics there comes a point when I don't need elastic anymore, I just need some specific aggregation and query results to get the "summery" of historical events, currently stored in indexes. I am trying to figure out how to automatically generate and store statistical data (generated as query results) from existing indexes (populated by docs that are individual traffic and error logs) and store this information in a new index before deleting the queried indexes, thus retaining the "meat" of the data (which is the only important part after a period of time for gleaning historical use patterns: a long term issue) while thinning out the extraneous information that is only needed to resolve bugs and address traffic issues: a problem of the now. Update: I also have looked into Curator, but it does not seem to have been built into versions beyond 5.2. Is it still supported in 5.6? Additionally I have looked at just writing a cron job that makes my searches, stores the results, and PUTs the results in a new index, then deletes the same indexes searched, all via the RESTful API from the server my nodes are running on. This would work, but I am interested if this is possible inside Elasticserach. Question 1: Is there a way to internally automate queries/searches/aggregations at specified times and store the results of this search as a document in a new index? Question 2: Is there a way to automate the deletion of indexes after a specified age? This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
__label__pos
0.972711
lorenz.py import numpy as np from scipy.integrate import odeint from bokeh.plotting import figure, show, output_file sigma = 10 rho = 28 beta = 8.0/3 theta = 3 * np.pi / 4 def lorenz(xyz, t): x, y, z = xyz x_dot = sigma * (y - x) y_dot = x * rho - x * z - y z_dot = x * y - beta* z return [x_dot, y_dot, z_dot] initial = (-10, -7, 35) t = np.arange(0, 100, 0.006) solution = odeint(lorenz, initial, t) x = solution[:, 0] y = solution[:, 1] z = solution[:, 2] xprime = np.cos(theta) * x - np.sin(theta) * y colors = ["#C6DBEF", "#9ECAE1", "#6BAED6", "#4292C6", "#2171B5", "#08519C", "#08306B",] p = figure(title="lorenz example") p.multi_line(np.array_split(xprime, 7), np.array_split(z, 7), line_color=colors, line_alpha=0.8, line_width=1.5) output_file("lorenz.html", title="lorenz.py example") show(p) # open a browser
__label__pos
0.994392
使用RecycleView打造水平分页GridView 2017-01-14 10:04:36来源:http://www.jianshu.com/p/262f4b632a41作者:zhuguohui人点击 效果 效果 特点 1.支持纵向,横向,水平分页三种布局方式。 2.支持点击事件。 3.支持分割线设置,支持自定义分页指示器。 4.使用简单方便 使用 1.在布局文件中定义 这里写图片描述 支持的属性如下 这里写图片描述 2.设置Adapter //设置adapter pageGridView.setAdapter(adapter1); //设置点击监听器 pageGridView.setOnItemClickListener(adapter1); //设置分页指示器 pageGridView2.setPageIndicator(pageIndicator); 注意 如果使用分页显示,由于会对数据进行重排序,所以点击事件的position只用和数据集合结合使用。 下面是各个借口的定义 使用分页功能必须使用此Adapter 这里写图片描述 点击监听器 这里写图片描述 分页指示器 这里写图片描述 实现 遇到的问题 其实打造分页的GridView可以使用多种方式,比如常见的用GridView加ViewPager实现,但是这种方式没有实现对View的复用,而且编码复杂,光是对Adapter的处理就很头疼,所以我将这些辛苦的工作我都做了,辛苦我一个方便大家。我的思路是使用RecycleView结合StaggeredGridLayoutManager来实现分页,但是在默认的效果中只能实现如下效果。 这里写图片描述 对比分页的样式 这里写图片描述 发下有下列问题: 1.数据排列,分页的数据是一页页,一行行的排。 2.滑动事件的处理,分页的数据应该是一页一页显示,当滑动停止的时候自动停在最近一页。 1.重排序 下面我一个一个的解决这些问题,首先是数据排列。我通过以下算法对数据就行了重排序。 这里写图片描述 关键的逻辑是获取到Adapter的数据,并对它安装分页的方式进行重排序,对于一些位置采用了空数据处理。所以为了实现这些功能,使用者的Adapter必须实现PagingAdapter 这里写图片描述 而且必须对空对象进行处理 这里写图片描述 2.滑动事件 由于RecycleView自己并不处理滑动事件,而是委派给LayoutManager处理,所以通过RecycleView的getScrollX方法不能获取到滑动的偏移量,而且使用smoothScrollToPosition()方法有一个问题,就是当指定Position的view已经在视线内的时候,是不会滑动的。因此经过我反复的实验采用以下的方法解决了问题。即通过给RecycleView设置OnScrollListener实现。 int scrollX = 0; boolean isAuto = false; int Target = 0; int currentPage = 0; int lastPage = 0; public class PagingScrollListener extends RecyclerView.OnScrollListener { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState == 0) { if (!isAuto) { int p = scrollX / getWidth(); int offset = scrollX % getWidth(); if (offset > getWidth() / 2) { p++; } Target = p * getWidth(); isAuto = true; currentPage = p; if (pageIndicator != null) { pageIndicator.onPageUnSelected(lastPage); pageIndicator.onPageSelected(currentPage); } if (onPageChangeListenerList != null) { for (OnPageChangeListener listener : onPageChangeListenerList) { listener.onPageChanged(currentPage); } } recyclerView.smoothScrollBy(Target - scrollX, 0); } } else if (newState == 2) { isAuto = false; lastPage = currentPage; } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { scrollX += dx; } } 3.点击事件的处理 我通过重写dispatchTouchEvent方法实现 @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (onItemClickListener != null) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: dX = (int) ev.getRawX(); dY = (int) ev.getRawY(); dTime = System.currentTimeMillis(); break; case MotionEvent.ACTION_UP: int mx = (int) Math.abs(ev.getRawX() - dX); int my = (int) Math.abs(ev.getRawY() - dY); int time = (int) (System.currentTimeMillis() - dTime); if (mx <= 10 && my <= 10 && time < 200) { int position = getPositionByXY((int) ev.getRawX(), (int) ev.getRawY()); if (position != -1) { onItemClickListener.onItemClick(this, position); } } break; } } return super.dispatchTouchEvent(ev); } private int getPositionByXY(int x, int y) { int position = -1; Rect rect = new Rect(); for (int i = 0; i < getChildCount(); i++) { View view = getChildAt(i); view.getGlobalVisibleRect(rect); if (rect.contains(x, y)) { position = i; break; } } if (mRows > 0) { int offset = getChildPosition(getLayoutManager().getChildAt(0)); position += offset; } return position; } private OnItemClickListener onItemClickListener; public void setOnItemClickListener(OnItemClickListener listener) { onItemClickListener = listener; } 关于更多的细节请查看源码。 GitHub github地址 最新文章 123 最新摄影 微信扫一扫 第七城市微信公众平台
__label__pos
0.978073
Create an aggregate Contributors NetAppZacharyWambold If you do not want to use an existing aggregate, you can create a new aggregate to provide physical storage to the volume which you are provisioning. Steps 1. Enter the URL https://IP-address-of-cluster-management-LIF in a web browser and log in to System Manager using your cluster administrator credential. 2. Navigate to the Aggregates window. 3. Click Create. 4. Follow the instructions on the screen to create the aggregate using the default RAID-DP configuration, and then click Create. Creating an aggregate screen in System Manager Results The aggregate is created with the specified configuration and added to the list of aggregates in the Aggregates window.
__label__pos
0.976757
How do you use #sintheta=1/3# to find #tantheta#? 1 Answer Jan 8, 2017 #+- sqrt2/4# Explanation: First find cos t. #cos^2 t = 1 - sin^2 t# #cos ^2 t = 1 - 1/9 = 8/9# #cos t = +- (2sqrt2)/3# #tan t = sin t/(cos t) = +- (1/3)(3/(2sqrt2)) = +- 1/(2sqrt2) = +- sqrt2/4# Note about the signs of tan t. On the unit circle: sin t = 1/3 --> cos t either + or - , there for --> tan t either + or - Check by calculator. #sin t = 1/3# --> #t = 19^@47# and #t = 180 - 19.47 = 160^@53# tan 19.47 = 0.35 and tan 160.53 = - 0.35 #+- sqrt2/4 = +- 1.414/5 = +- 0.35# OK
__label__pos
0.999899
Hatefiend Hatefiend - 1 year ago 55 Java Question Java - Pointer to integer type I want to have a pointer to an Integer type, without making a custom class that has an element which is an integer. My desired effect: Byte x = 5; // Byte is just an example and WILL NOT work. Byte y = x; y--; System.out.println(x + "," + y); In which I want to print: 4,4 I thought Byte , Integer , or Double might be able to do this because they are sort of classes with an inner variable which is a primitive type but they don't keep references to the object that they are assigned to. Answer Source You can't use a primitive wrapper type, because those are immutable. You could use an AtomicInteger to do this. Something like, AtomicInteger x = new AtomicInteger(5); AtomicInteger y = x; System.out.println(y.decrementAndGet() + "," + x.get()); Outputs (as requested) 4,4 Or, you could use an int[] like int[] x = { 5 }; int[] y = x; System.out.println(--x[0] + "," + y[0]); for the same output.
__label__pos
0.950976
福寿年高不难的登录和登记,MVC配置详解 1.创立三个动态的web工程 今昔主流的Web MVC框架除了Struts这么些主力外,其次便是springMVC了,因而那也是用作一名程序员供给控制的主流框架,框架选取多了,应对形成的急需和事务时,可举行的方案自然就多了。不过要想灵活运用Spring MVC来应对超过半数的Web开发,就必须要了然它的配备及原理。 2.导入springMvc所急需的jar包(那里能够去网上找,能源有层见迭出) 一 、Spring MVC环境搭建:(Spring 2.5.6 +hibernate3.2.0) 前两部就不详细描述了,前面才是不俗代码~ 1. jar包引入 第③有三个web.xml文件,这一个属于大布局文件,由于只要写login,里面大致陈设一下主导条件就能够 Spring 2.5.6:spring.jar、spring-webmvc.jar、commons-logging.jar、cglib-nodep-2.1_3.jar   Hibernate 3.6.8:hibernate3.jar、hibernate-jpa-2.0-api-1.0.1.Final.jar、antlr-2.7.6.jar、commons-collections-3.1、dom4j-1.6.1.jar、javassist-3.12.0.GA.jar、jta-1.1.jar、slf4j-api-1.6.1.jar、slf4j-nop-1.6.4.jar、相应数据库的驱动jar包 <servlet> <servlet-name>springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> OPEN CI 投入的这么些叫Dispatcher Servlet,能够依照servlet-name找到相应的小铺排文件,也便是布署spring MVC的公文 开源规范化项目管理化解方案,达成软件流水线式生产,保险科学、可信赖性 在web.xml文件同级目录下新建springmvc-servlet.xml文件,下边是springmvc-servlet.xml文件中的内容 向导式创造、导入项目,集成版本控制(Git/SVN)、项目管理(Trac/Redmine)、代码品质(Sonar)、持续集成(Jenkins)   个人安插,统一保管,为开发者而生 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!--默认的注解映射的支持 --> <mvc:annotation-driven/> <!--启用自动扫描 --> <context:component-scan base-package="controller"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans> 分布式 留神表达的是,运营自动扫描,spring会在钦命的包下(例如作者那边是controller包),自动扫描标注@Controller的类 分布式服务:Dubbo+Zookeeper+Proxy+Restful prefix指的是回到的值给机关加1个前缀,同理suffix指的便是后缀 分布式音讯中间件:KafKa+Flume+Zookeeper 图片 1 分布式缓存:Redis分布式文件:法斯特DFS   负载均衡:Keepalived+Nginx+Proxy(三重负载)  图片 2 图片 3 总的来看这里也是够劳累了,下边是交由的完全目录,下边初步写逻辑代码,先从loginController开首 SpringMVC是2个根据DispatcherServlet的MVC框架,每二个呼吁发轫访问的都是DispatcherServlet,DispatcherServlet负责转载每2个Request请求给相应的Handler,Handler处理未来再回来相应的视图(View)和模型(Model),再次来到的视图和模型都足以不钦赐,即能够只回去Model或只回去View或都不回来。 @Controller public class LoginController { @RequestMapping(value="/",method=RequestMethod.GET) public String sayHello(){ //model.addAttribute("msg", "Hello,World!"); return "login"; } DispatcherServlet是后续自HttpServlet的,既然SpringMVC是遵照DispatcherServlet的,那么大家先来配置一下DispatcherServlet,好让它亦可管理我们盼望它管理的始末。HttpServlet是在web.xml文件中宣称的。 表明上边代码,@Controller,标注那个类是Controller类,spring会自动进行围观,@Request Mapping中的value指的是url中的地址后缀,设置成/的指标自然是为着便于啊, spring 比如说运营工程时,url只须求输入什么localhost:8080/项目名,它就会自动跳转到login页面;method指的是来的url是post请求还是get请求 org.springframework.web.servlet.DispatcherServlet return的是login字符串,我们还记得下面说的prefix了啊,它就会把你的url自动拼接上,完整路径正是上面这几个 contextConfigLocation /WEB-INF/jsp/login.jsp /WEB-INF/spring-servlet.xml  默认  接下来看login.jsp –>1spring*.doorg.springframework.web.context.ContextLoaderListenercontextConfigLocationclasspath:config/applicationContext.xml <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>login</title> </head> <body> <form action="login" method="post"> 用户名:<input type="text" name="username"/><br/> 密&nbsp;&nbsp;码:<input type="password" name="password"/> <input type="submit" value="登陆"/> <a href="regist">注册</a> </form> </body> </html> spring-servlet.xml配置 此间的action再次回到的是login,Controller会自动捕获到这么些请求,于是在login Controller中要有一个艺术来捕获这一个请求 spring-servlet那个名字是因为地点web.xml中标签配的值为spring(spring),再加上“-servlet”后缀而形成的spring-servlet.xml文件名,若是改为springMVC,对应的公文名则为springMVC-servlet.xml。 @RequestMapping(value="login",method=RequestMethod.POST) public String login(Model model, // 向前台页面传的值放入model中 HttpServletRequest request){ // 从前台页面取得的值 String username = request.getParameter("username"); String password = request.getParameter("password"); String user_name = LoginCheck.check(username, password); if(user_name != null && user_name != ""){ model.addAttribute("msg", user_name); return "success"; }else{ return "login2"; } } http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 登陆嘛,当然要有认证,于是就有了LoginCheck,不多说,上代码 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd package logic; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import dao.Dao; public class LoginCheck { public static String check(String username,String password){ try { Connection conn = Dao.getConnection(); PreparedStatement p = conn.prepareStatement("select * from user_t where user_name=? and password=?"); p.setString(1, username); p.setString(2, password); ResultSet rs = p.executeQuery(); if(rs.next()){ String user_name = rs.getString("user_name"); Dao.close(rs, p, conn); return user_name; } Dao.close(rs, p, conn); } catch (Exception e) { e.printStackTrace(); } return ""; } } http://www.springframework.org/schema/context[http://www.springframework.org/schema/context/spring-context-3.0.xsd](https://link.jianshu.com?t=http://www.springframework.org/schema/context/spring-context-3.0.xsd)"&gt; 向数据库查询就要有DAO啦,Dao网上都有,我的就是在网上随便找二个改动就用了~ DispatcherServlet会利用部分非同一般的bean来处理Request请求和浮动对应的视图再次回到。 package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Dao { // 获取数据库连接 public static Connection getConnection(){ Connection conn = null; String url = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong"; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(url,"root","数据库密码");//大家分享代码的时候也不要暴露自己的数据库密码,这样是非常不安全的 } catch(ClassNotFoundException e) { e.printStackTrace(); System.out.println("数据库驱动加载出错"); } catch(SQLException e) { e.printStackTrace(); System.out.println("数据库出错"); } return conn; } //关闭相关通道 public static void close(ResultSet rs,PreparedStatement p,Connection conn) { try { if(!rs.isClosed()){ rs.close(); } if(!p.isClosed()){ p.close(); } if(!conn.isClosed()){ conn.close(); } } catch(SQLException e) { e.printStackTrace(); System.out.println("数据关闭出错"); } } //关闭相关通道 public static void close(PreparedStatement p,Connection conn) { try { if(!p.isClosed()){ p.close(); } if(!conn.isClosed()){ conn.close(); } } catch(SQLException e) { e.printStackTrace(); System.out.println("数据关闭出错"); } } } 关于视图的回来,Controller只承担传回到几个值,然后到底重返的是怎么样视图,是由视图解析器控制的,在jsp中常用的视图解析器是InternalResourceViewResovler,它会须要一个前缀和四个后缀 好了,若是查询的结果非常上数据库中询问到的值了,那么就能够跳转到success页面了,success.jsp 在上述视图解析器中,假诺Controller重返的是blog/index,那么通过视图解析器解析之后的视图就是/jsp/blog/index.jsp。 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登陆成功</title> </head> <body> 登陆成功! 欢迎~${msg}; </body> </html> 重视是说说Controller. login旗开得胜,接下去的注册页面和那些道理相似,笔者不多废话了,把代码附上供大家参考 一个类应用了@Controller实行标记的都是Controller 首先是regist.jsp packagecontroller;importjavax.servlet.http.HttpServletRequest;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importentity.User; <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>注册页面</title> </head> <body> <form action="registSuccess" method="Post"> 用户名:<input type="text" name="username"/> 密&nbsp;&nbsp;码<input type="text" name="password"/> 年&nbsp;&nbsp;龄<input type="number" name="age"/> <input type="submit" value="提交"/> </form> </body> </html> @Controller//类似Struts的ActionpublicclassTestController { 接下去是RegistController @RequestMapping(“test/login.do”)//请求url地址映射,类似Struts的action-mappingpublicString testLogin(@RequestParam(value=”username”)String username, String password, HttpServletRequest request) {//@RequestParam是指请求url地址映射中必须包蕴的参数(除非属性required=false)//@RequestParam可简写为:@RequestParam(“username”)if(!”admin”.equals(username) || !”admin”.equals(password)) {return”loginError”;//跳转页面路径(暗中认可为转载),该路线不必要包罗spring-servlet配置文件中配置的前缀和后缀}return”loginSuccess”; package controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import logic.RegistCheck; @Controller public class RegistController { @RequestMapping(value="regist",method=RequestMethod.GET) public String regist(){ return "regist"; } @RequestMapping(value="registSuccess",method=RequestMethod.POST) public String registSuccess(HttpServletRequest request,Model model){ String username = request.getParameter("username"); String password = request.getParameter("password"); String age = request.getParameter("age"); if(RegistCheck.registCheck(username, password,age)){ model.addAttribute("username", username); return "login"; }else{ return "regist2"; } } } } 接下去是RegistCheck @RequestMapping(“/test/login2.do”)publicModelAndView testLogin2(String username, String password,intage){//request和response不必非要出现在方式中,假如用不上的话能够去掉//参数的称呼是与页面控件的name相匹配,参数类型会自动被更换if(!”admin”.equals(username) || !”admin”.equals(password) || age < 5) {returnnewModelAndView(“loginError”);//手动实例化ModelAndView达成跳转页面(转载),效果等同上面包车型地铁法门再次来到字符串}returnnewModelAndView(newRedirectView(“../index.jsp”));//接纳重定向方式跳转页面//重定向还有一种简易写法//return new ModelAndView(“redirect:../index.jsp”);}   @RequestMapping(“/test/login3.do”)publicModelAndView testLogin3(User user) {//同样援救参数为表单对象,类似于Struts的ActionForm,User不必要别的配置,直接写即可String username =user.getUsername(); package logic; import java.sql.Connection; import java.sql.PreparedStatement; import dao.Dao; public class RegistCheck { public static boolean registCheck(String username,String password,String age){ String user_name = LoginCheck.check(username, password); if(user_name == null || user_name == ""){ try { Connection conn = Dao.getConnection(); PreparedStatement p = conn.prepareStatement("insert user_t(user_name,password,age) VALUES (?,?,?);"); p.setString(1, username); p.setString(2, password); p.setString(3, age); p.executeUpdate(); System.out.println("注册成功"); Dao.close(p, conn); return true; } catch (Exception e) { e.printStackTrace(); } } return false; } } String password=user.getPassword();intage =user.getAge();if(!”admin”.equals(username) || !”admin”.equals(password) || age < 5) {returnnewModelAndView(“loginError”); 还有多少个registSuccess.jsp,成功重临的页面,小编只是放了个空页面,没内容 }returnnewModelAndView(“loginSuccess”); <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>注册成功</title> </head> <body> 注册成功! </body> </html> } 好了,以往了却login和挂号页面都写好了,新人刚到公司的时候分外不难碰着那样的小演练,哈哈哈说多了,喜欢就点赞哈 @Resource(name= “loginService”)//获取applicationContext.xml中bean的id为loginService的,并流入privateLogin瑟维斯login瑟维斯;//等价于spring古板注入格局写get和set方法,这样的裨益是精简工整,省去了不要要得代码@RequestMapping(“/test/login4.do”)publicString testLogin4(User user) {if(loginService.login(user) ==false) {return”loginError”; 欢迎转发,转发请注脚出处~ }return”loginSuccess”; Java从学习到放任,MySQL从删库到跑路,哈哈哈 }   } 如上几个法子言传身教,是八个Controller里富含差异的伸手url,也得以采纳两个url访问,通过url参数来分别访问不一致的格局,代码如下: packagecontroller;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping(“/test2/login.do”)//钦命唯一1个*.do请求关联到该ControllerpublicclassTestController2 { @RequestMappingpublicString testLogin(String username, String password,intage) {//如若不加任何参数,则在呼吁/test2/login.do时,便暗中同意执行该格局if(!”admin”.equals(username) || !”admin”.equals(password) || age < 5) {return”loginError”; }return”loginSuccess”; } @RequestMapping(params= “method=1″, method=RequestMethod.POST)publicString testLogin2(String username, String password) {//依照params的参数method的值来区分分化的调用方法//能够钦赐页面请求情势的花色,暗许为get请求if(!”admin”.equals(username) || !”admin”.equals(password)) {return”loginError”; }return”loginSuccess”; } @RequestMapping(params= “method=2″)publicString testLogin3(String username, String password,intage) {if(!”admin”.equals(username) || !”admin”.equals(password) || age < 5) {return”loginError”; }return”loginSuccess”; } } 其实RequestMapping在Class上,可看成是父Request请求url,而RequestMapping在艺术上的可看做是子Request请求url,父子请求url最后会拼起来与页面请求url实行匹配,由此RequestMapping也能够那样写: packagecontroller;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping(“/test3/*”)//父request请求urlpublicclassTestController3 { @RequestMapping(“login.do”)//子request请求url,拼接后等价于/test3/login.dopublicString testLogin(String username, String password,intage) {if(!”admin”.equals(username) || !”admin”.equals(password) || age < 5) {return”loginError”; }return”loginSuccess”; } } 在SpringMVC中常用的注释还有@PathVariable,@RequestParam,@PathVariable标记在措施的参数上,利用它标志的参数能够选拔请求路径传值,看上边贰个例证 @RequestMapping(value=”/comment/{blogId}”, method=RequestMethod.POST)publicvoidcomment(Comment comment,@PathVariableintblogId, HttpSession session, HttpServletResponse response)throwsIOException { } 在该例子中,blogId是被@PathVariable标记为呼吁路径变量的,假诺请求的是/blog/comment/1.do的时候就表示blogId的值为1. 同一@RequestParam也是用来给参数字传送值的,不过它是从头request的参数里面取值,约等于request.getParameter(“参数名”)方法。 在Controller的艺术中,如若急需WEB成分HttpServletRequest,HttpServletResponse和HttpSession,只必要在给艺术多个应和的参数,那么在做客的时候SpringMVC就会自行给其传值,可是须要注意的是在流传Session的时候假设是第二遍访问系统的时候就调用session会报错,因为这些时候session还没有变化。 欢迎大家共同上学商讨有关技能愿意精晓框架技术或许源码的情侣一直加求求(企鹅):2042849237 越来越多详细源码参考来源:http://minglisoft.cn/technology 相关文章
__label__pos
0.612688
Does Samsung Galaxy S6 Have Miracast? Find Out Here The Samsung Galaxy S6 is a widely popular smartphone that boasts an array of impressive features. Among them, the ability to connect to other devices through screen mirroring is a sought-after functionality. In this article, we will delve into the question of whether the Samsung Galaxy S6 supports Miracast, a technology that enables wireless display connectivity. Keep reading to find out if this flagship device lives up to the expectations of Miracast users. Understanding Miracast Technology Miracast is a wireless display technology that enables users to mirror the screen of one device onto another. It allows seamless sharing of audio and video content from a compatible device, such as Samsung Galaxy S6, to a larger screen like a TV or monitor. This technology works by establishing a direct Wi-Fi connection between the transmitting device (Galaxy S6) and the receiving device (TV or monitor). Miracast uses Wi-Fi Direct, which enables devices to connect without the need for a router or internet connection. The Miracast standard is supported by a wide range of devices, including smartphones, tablets, smart TVs, and computers. However, it is important to note that not all devices are compatible with Miracast. Both the transmitting and receiving devices must have Miracast support built-in to establish a connection successfully. Samsung Galaxy S6 features built-in Miracast support, allowing users to cast their screen onto a Miracast-enabled display effortlessly. With this feature, users can enjoy streaming videos, playing games, or presenting content on a larger screen without any wired connections. What Is Miracast And How Does It Work? Miracast is a wireless display technology that allows users to mirror the screen of one device onto another, such as a smartphone onto a TV or a laptop onto a projector. It works by creating a direct connection between the source device (in this case, the Samsung Galaxy S6) and the display device, bypassing the need for an internet connection or a dedicated Wi-Fi network. To establish a Miracast connection, both the source and display devices must support Miracast technology. The source device, in this case, the Galaxy S6, must have a Miracast feature built-in, while the display device must also be Miracast-compatible. When a Miracast connection is established, the source device’s screen is wirelessly transmitted to the display device, allowing users to view photos, videos, or any other content on a larger screen. This technology is particularly useful in scenarios such as presentations, gaming, or simply enjoying multimedia content comfortably from a bigger display. Miracast operates on Wi-Fi Direct, which creates a direct connection between the devices. This allows for a fast and reliable wireless display experience without any additional cables or adapters required. Overall, Miracast is a handy feature that brings convenience and versatility to the Samsung Galaxy S6 and enables users to effortlessly share their content on multiple screens. Miracast Compatibility: Which Devices Support It? Miracast is a wireless display technology that allows users to mirror the screen of one device onto another. However, it is important to note that not all devices are compatible with Miracast. So, if you are wondering whether your Samsung Galaxy S6 supports Miracast, here is everything you need to know. The Samsung Galaxy S6 is indeed equipped with Miracast capabilities. This means that you can easily mirror your smartphone’s screen onto a larger display, such as a TV or a monitor, wirelessly. With Miracast support, you can enjoy your favorite movies, videos, photos, and even games on a bigger screen without the need for any cables. But it’s not just the Samsung Galaxy S6 that supports this technology. Many other devices, including smart TVs, laptops, tablets, and other smartphones, also come with Miracast compatibility. This makes it easier for you to connect and stream content from various devices onto a single screen. So, if you are looking for a way to enhance your multimedia experience and enjoy the convenience of wireless screen mirroring, the Samsung Galaxy S6 with its Miracast compatibility is an excellent choice. Start exploring the endless possibilities of this technology and watch as your smartphone becomes a powerful multimedia hub. Exploring The Wireless Display Capabilities Of Samsung Galaxy S6 The Samsung Galaxy S6 is equipped with the Miracast technology, which allows users to wirelessly display the content from their device on a larger screen, such as a television or computer monitor. This feature is particularly useful for sharing photos, videos, or presentations with a larger audience. With the Miracast technology, the Galaxy S6 can establish a direct Wi-Fi connection with the display device, eliminating the need for any physical cables. This ensures a seamless and convenient streaming experience. Users can easily mirror their device screen onto the larger display, making it perfect for gaming, watching movies, or even giving presentations. Moreover, the Galaxy S6 supports Full HD resolution for Miracast display, ensuring that the content is crisp and vibrant on the bigger screen. This high-quality display makes for a more immersive viewing experience. To use Miracast on the Samsung Galaxy S6, simply access the quick settings menu by swiping down from the top of the screen, and then tap on the “Screen Mirroring” option. The device will then scan for available display devices, and once connected, users can start mirroring their screen. Overall, the wireless display capabilities of the Samsung Galaxy S6, powered by Miracast technology, offer a convenient and high-quality solution for sharing content on a larger screen without any complications. How To Use Miracast On Samsung Galaxy S6 Miracast is a convenient feature that allows you to wirelessly mirror the display of your Samsung Galaxy S6 onto a larger screen such as a TV or monitor. By following a few simple steps, you can easily utilize Miracast on your device. To begin using Miracast on your Galaxy S6, ensure that your TV or monitor supports the Miracast technology. Next, make sure that both your Galaxy S6 and the display device are connected to the same Wi-Fi network. Once that is confirmed, follow these steps: 1. Swipe down from the top of your Galaxy S6 screen to access the Quick Settings menu. 2. Locate and tap on the “Screen Mirroring” option. 3. A list of available devices will appear. Select the display device you wish to mirror your screen on. 4. Once the connection is established, your Galaxy S6 screen will appear on the external display. You can now enjoy movies, photos, and any other content from your Galaxy S6 on a larger screen. This feature not only enhances the overall viewing experience but also allows you to share presentations or play games with friends and family. In case you experience any issues during the Miracast connection process, refer to the troubleshooting section or consider exploring alternative wireless display technologies. **6. Troubleshooting common Miracast issues on Galaxy S6** One of the advantages of Miracast technology is its ability to seamlessly stream content from your Samsung Galaxy S6 to a compatible display device. However, like any other technology, Miracast may encounter some common issues that can hinder its functionality. Here are a few troubleshooting tips to resolve potential problems: 1. **Connectivity**: Ensure that both your Galaxy S6 and the receiving device are connected to the same Wi-Fi network. Miracast requires a stable wireless connection for optimal performance. 2. **Software and firmware updates**: Check for any available updates for your Galaxy S6 and the receiving device. Outdated software can often cause compatibility issues between devices. 3. **Restart devices**: Restarting both your Galaxy S6 and the receiving device can often resolve minor glitches and restore the connection. 4. **Close background apps**: Running multiple apps in the background can potentially interfere with Miracast. Close any unnecessary apps to improve streaming quality. 5. **Check for device compatibility**: Ensure that your receiving device supports Miracast technology. Not all devices are compatible, so it’s essential to verify compatibility before troubleshooting further. By following these troubleshooting tips, you can address common Miracast issues on your Samsung Galaxy S6 and enjoy seamless wireless screen mirroring. Alternatives To Miracast For Screen Mirroring On Galaxy S6 There are several alternatives to Miracast for screen mirroring on the Samsung Galaxy S6. While Miracast is a popular and widely used technology, it may not be the most suitable option for every user. Here are some alternative options to consider: 1. Chromecast: With a Google Chromecast device, you can easily mirror your Galaxy S6 screen to your TV. Simply plug the device into your TV’s HDMI port and use the Chromecast app on your phone to establish a connection. 2. Apple AirPlay: If you have an Apple TV, you can use AirPlay Mirroring to mirror your Galaxy S6 screen wirelessly. This option is limited to Apple devices, so it may not be suitable if you have a mixed ecosystem of devices. 3. DLNA: The Digital Living Network Alliance (DLNA) standard allows you to stream media content from your Galaxy S6 to DLNA-compatible devices, such as smart TVs or game consoles. While it may not support full screen mirroring, it can still be a useful option for sharing media files. 4. Third-party apps: There are several third-party apps available on the Google Play Store that can enable screen mirroring on your Galaxy S6. Some popular options include AllCast and AirServer. It’s important to note that the availability and functionality of these alternatives may vary depending on your specific device and software version. So, make sure to check for compatibility before relying on any particular option for screen mirroring on your Samsung Galaxy S6. Miracast Vs. Other Wireless Display Technologies: A Comparison Miracast is a popular wireless display technology that allows users to wirelessly stream content from one device to another. It enables screen mirroring between devices, making it convenient for users to share their smartphone or tablet screens on a larger display, such as a TV or computer monitor. However, Miracast is not the only wireless display technology available in the market. Other wireless display technologies, such as Google Chromecast and Apple AirPlay, also offer similar functionalities. While Miracast is supported by a wide range of devices, including Samsung Galaxy S6, Chromecast is specifically designed for casting content from mobile devices to a TV. On the other hand, AirPlay is primarily limited to Apple devices. When it comes to compatibility, Miracast offers broader device support, making it more versatile than other wireless display technologies. However, Chromecast and AirPlay often provide a more seamless user experience and may offer additional features, such as multi-room audio streaming. In terms of performance, Miracast offers real-time mirroring without compromising on video quality. The technology utilizes Wi-Fi Direct, which ensures a stable connection and low latency. However, Chromecast and AirPlay may offer smoother playback and improved picture quality due to their optimized streaming protocols. Ultimately, the choice between Miracast and other wireless display technologies depends on the specific needs and preferences of the user. FAQs 1. Does the Samsung Galaxy S6 support Miracast? Yes, the Samsung Galaxy S6 does support Miracast. It allows users to wirelessly mirror their screen onto compatible devices such as televisions or projectors, making it convenient for presentations or enjoying multimedia content on a larger screen. 2. How can I use Miracast on my Samsung Galaxy S6? To use Miracast on your Samsung Galaxy S6, you will need a compatible Miracast receiver, such as a smart TV or a Miracast dongle. Make sure both your phone and the receiving device are connected to the same Wi-Fi network. Then, go to the Settings menu on your Galaxy S6, locate the Display settings, and select the option for wireless display. Your phone will scan for available devices, and you can select the desired receiver to start screen mirroring. 3. Can I stream videos from apps such as Netflix using Miracast on my Samsung Galaxy S6? Yes, you can stream videos from apps like Netflix using Miracast on your Samsung Galaxy S6. By mirroring your phone’s screen onto a compatible device, you can enjoy your favorite shows and movies with a wider audience. However, do note that some streaming apps may have restrictions on streaming protected content, so it’s essential to check the specific app’s capabilities before attempting to use Miracast for streaming. Wrapping Up In conclusion, the Samsung Galaxy S6 does not have built-in support for Miracast. However, users have the option to use third-party apps or adapters to enable screen mirroring and wireless display streaming on their device. Despite this limitation, the Galaxy S6 still offers a plethora of advanced features and innovative technology that make it a popular choice among smartphone users. Leave a Comment
__label__pos
0.93754
No description, website, or topics provided. C++ C Other Switch branches/tags Nothing to show Fetching latest commit… Cannot retrieve the latest commit at this time. Permalink Failed to load latest commit information. archives query_example src .gitignore README.md README.md #Page based persistance storage library.# Code is based on the submitted assignments from Database System Technology CSC443, Winter 2013, at University of Toronto. ##Specifications are as follows## ###Directory based heap file### Images taken from http://dblab.cs.toronto.edu/courses/443/2013/03.data-layout.html ###Page format for fixed length records ###Requirements • offers efficient append of new data, • supports sequential scanning, • does not offer random access. • Data exists on secondary storage: it's designed to efficient for large data volume, with capacity only limited by the available secondary storage. • A heap file can span over multiple disks or machines: heap file can use large addressing schemes to span across multiple disks or ever networks. • Data is organized into pages. • Pages can be partially empty. • Pages may be segmented over different physical regions of a hard drive, or may be scattered over different drives, or even across different networks. We simply assume that each page is a unique page ID of the type PageAddress, and the operating system can locate the page for us. Every page p as an entry in the heap directory of (page_offset, freespace). The page ID of p can be the index of its entry in the directory. We call this: ID(p). Every record r is stored at some slot in some page p. The record ID, ID(r) is the contenation of ID(p) and the slot index in p. Suppose we have the following parameters: Page size : 16 KB Page address size : 32 bits Each entry in the directory would be: Bits for free space+Bits for page address = log2(16 KB)+32=17+32 bits = 49 bits Thus, each directory page can index up to: 16 KB49 bits=2674 pages=42 MB ###API### /** * Compute the number of bytes required to serialize record */ int fixed_len_sizeof(Record *record); /** * Serialize the record to a byte array to be stored in buf. */ void fixed_len_write(Record *record, void *buf); /** * Deserializes from `size` bytes from the buffer, `buf`, and * stores the record in `record`. */ void fixed_len_read(void *buf, int size, Record *record); /** * Compute the number of bytes required to serialize record */ int var_len_sizeof(Record *record); /** * Serialize the record using variable record encoding */ void var_len_write(Record *record, void *buf); /** * Deserialize the `buf` which contains the variable record encoding. */ void var_len_read(void *buf, int size, Record *record); /** * Initializes a page using the given slot size */ void init_fixed_len_page(Page *page, int page_size, int slot_size); /** * Calculates the maximal number of records that fit in a page */ int fixed_len_page_capacity(Page *page); /** * Calculate the free space (number of free slots) in the page */ int fixed_len_page_freeslots(Page *page); /** * Add a record to the page * Returns: * record slot offset if successful, * -1 if unsuccessful (page full) */ int add_fixed_len_page(Page *page, Record *r); /** * Write a record into a given slot. */ void write_fixed_len_page(Page *page, int slot, Record *r); /** * Read a record from the page from a given slot. */ void read_fixed_len_page(Page *page, int slot, Record *r); void write_page_to_file(char* fname, Page* page); /** * Initalize a heapfile to use the file and page size given. */ void init_heapfile(Heapfile *heapfile, int page_size, FILE *file); /** * Allocate another page in the heapfile. This grows the file by a page. */ PageID alloc_page(Heapfile *heapfile); /** * Read a page into memory */ void read_page(Heapfile *heapfile, PageID pid, Page *page); /** * Write a page from memory to disk */ void write_page(Page *page, Heapfile *heapfile, PageID pid); /** * Initialize record iterator */ void init_record_iterator(RecordIterator *iterator, Heapfile *heapfile, int slot_size, int page_size); /** * Move the iterator to the next record */ void iterate_record(RecordIterator *iterator); /** * Read the current record */ void read_current_record(RecordIterator *iterator, Record *record); ##Graphs## ###Querying performances versus SQLite Parametrized SQL query SELECT SUBSTRING(A2, 1, 5), COUNT(*) FROM T WHERE A1 >= start AND A1 <= end GROUP BY SUBSTRING(A2, 1, 5) githalytics.com alpha Bitdeli Badge
__label__pos
0.777329
Change language Laravel | CSRF Protection | Laravel protects against CSRFattacks by generating a CSRF token . This CSRF tokenis generated automatically for each user. This token - is nothing more than a random string that is manipulated by the Laravel application to validate custom requests.How to use:this CSRF token protection can be applied to any HTML form in the Laravel application by specifying a hidden CSRF token form field. Requests are automatically validatedby the CSRF middleware VerifyCsrfToken .There are three different ways to do this. • @csrf • csrf_field() • csrf_token() • @csrf:is a blade template directive to generate a hidden input field in an HTML form. • Syntax: < form method = "POST" > @csrf // Generate hidden input field ..... ..... < / form > • Example : < html > < head > < title > Laravel | CSRF Protection < / title > < / head > < body > < section > < h1 > CSRF Protected HTML Form < / h1 > < form method = "POST" > @ csrf < input type = "text" name = "username" placeholder = " Username " > < input type = "password" name = "password" placeholder = "Password" > < input type = "submit" name = "submit" value = "Submit" > < / form > < / section > < / body > < / html > csrf_field(): this function can be used to create a hidden input field in an HTML form.Note:this function must be written inside double curly braces. • Syntax: < form method = "POST" < // Generate hidden input field {{csrf_field()}} ..... ..... < / form > • Example: < html > < head > < title > Laravel | CSRF Protection < / title > < / head > < body > < section > < h1 > CSRF Protected HTML Form < / h1 > < form method = "POST" > {{csrf_field()}} < input type = "text" name = "username" placeholder = "Username" > < input type = "password" name = "password" placeholder = "Password" > < input type = "submit" name = "submit" value = "Submit" > < / form > < / section > < / body > < / html > csrf_token(): this function just produces a random string. This function does not generate a hidden input field.Note:HTML input must be written explicitly. This function must be written inside double curly braces. • Syntax: < form method = "POST" >  ..... ..... < / form > • Example : < html > < head > < title > Laravel | CSRF Protection < / title > < / head > < body > < section > < h1 > CSRF Protected HTML Form < / h1 > < form method = "POST" > < input type = "hidden" name = "_ token" value = "{{csrf_token()}}" > < input type = "text" name = "username" placeholder = "Username" > < input type = "password" name = "password" placeholder = "Password" > < input type = "submit" name = "submit" value = "Submit" > < / form > < / section > < / body > < / html > Output data: the output will be the same for any of the above three ways to generate a CSRF token. The CSRF token field must be written / generated at the beginning of every HTML form in any of three ways in a Laravel application. Check element output: Link: https://laravel.com/docs/6.x/csrf Shop Learn programming in R: courses $ Best Python online courses for 2022 $ Best laptop for Fortnite $ Best laptop for Excel $ Best laptop for Solidworks $ Best laptop for Roblox $ Best computer for crypto mining $ Best laptop for Sims 4 $ Latest questions NUMPYNUMPY Common xlabel/ylabel for matplotlib subplots 12 answers NUMPYNUMPY How to specify multiple return types using type-hints 12 answers NUMPYNUMPY Why do I get "Pickle - EOFError: Ran out of input" reading an empty file? 12 answers NUMPYNUMPY Flake8: Ignore specific warning for entire file 12 answers NUMPYNUMPY glob exclude pattern 12 answers NUMPYNUMPY How to avoid HTTP error 429 (Too Many Requests) python 12 answers NUMPYNUMPY Python CSV error: line contains NULL byte 12 answers NUMPYNUMPY csv.Error: iterator should return strings, not bytes 12 answers Wiki Python | How to copy data from one Excel sheet to another Common xlabel/ylabel for matplotlib subplots Check if one list is a subset of another in Python sin How to specify multiple return types using type-hints exp Printing words vertically in Python exp Python Extract words from a given string Cyclic redundancy check in Python Finding mean, median, mode in Python without libraries cos Python add suffix / add prefix to strings in a list Why do I get "Pickle - EOFError: Ran out of input" reading an empty file? Python - Move item to the end of the list Python - Print list vertically
__label__pos
0.974857
HomeTECHWhat Is Cloud Migration? What Is Cloud Migration? The cloud has been one of the major tech innovations of the last decade. The idea of cloud computing has changed the way that many businesses operate, and these changes have continued to ripple across industries.  If you’re still somewhat new to the world of cloud computing, you may be curious about how it all works. For example, what is cloud migration You don’t need to be a cloud migration expert to get a basic understanding of the ins and outs of this process. Read on and we’ll walk you through what you need to know.  What is Cloud Migration?  Simply stated, cloud migration is the process of moving digital business operations into the cloud system. The cloud is an online hard drive of sorts that can be accessed from everywhere, the prioritizes online storage over local.  Cloud migration is the process of moving data, applications, and IT processes from a local storage point to an online cloud storage point.  You can think about this move in much the same way that you might think about a physical move. Going from a smaller office to a larger one would require a lot of planning and organization, and so does cloud migration.  The more preparation and organization you invest in, the easier the move will be and the less you’ll need to pay.  Cloud Migrations Tips and Tricks How can you go about making this process run as smoothly as possible for your business? There are a few steps you can take.  First, make sure you’re clear about what your goals are. Why do you want to switch to cloud computing and what do you hope to get from this change? You’ll want to keep these goals in mind as you set up your new system to ensure you get the maximum benefit out of your investment.  You’ll also want to make a strong security strategy ahead of time as well. While cloud computing has many benefits, it also runs a slightly higher risk of hacking and other tech threats. You’ll need to make sure you take the proper steps to defend yourself. You’ll also need to decide how you want to organize your data in the cloud. Are you porting over a similar organization system to your current one, or is this an opportunity to start fresh?  All of this is worth considering as you start your move. If these tasks seem difficult to wrap your head around, it might be worth looking into professional it services to help handle these needs with their seasoned expertise. Cloud Migration Explained What is cloud migration? If you were in the dark about this process before, the above information should help to clear everything up. The above will help you understand the basics of this process as well as the steps needed to do it all right. Need more advice and info on tech and business? Keep scrolling our blog for more. LEAVE A REPLY Please enter your comment! Please enter your name here Must Read
__label__pos
0.558329
How do you present a regression table in APA? To report the results of a regression analysis in the text, include the following: 1. the R2 value (the coefficient of determination) 2. the F value (also referred to as the F statistic) 3. the degrees of freedom in parentheses. 4. the p value. How do you report a regression table in APA? 1. There are two ways to report regression analyses: 2. If the study was neither only applied nor only theoretical, list both standardized and unstandardized coefficients. 3. Specify the type of analysis (hierarchical or simultaneous) 4. If hierarchical regression is used: provide the increments of change. What should be included in a multiple regression table? Still, in presenting the results for any multiple regression equation, it should always be clear from the table: (1) what the dependent variable is; (2) what the independent variables are; (3) the values of the partial slope coefficients (either unstandardized, standardized, or both); and (4) the details of any test of … How do you format a table in APA format? Basic Rules for Tables in APA Format All tables should be numbered (e.g. Table 1, Table 2, Table 3). Each table should have an individual title, italicized and presented with each word capitalized (except and, in, of, with, etc.). For example, Correlations Between Age and Test Scores. Each table should begin on a separate page. How to cite a table in APA? Write ” Figure ” or ” Table ” in bold font,flush left,followed by the number,for example,Figure 1. • Write the figure/table title using italic case below the figure/table number, • Double-space the figure/table number and title, • Embed image. • What is the equation for multiple regression? The multiple linear regression equation is as follows: where is the predicted or expected value of the dependent variable, X1 through Xp are p distinct independent or predictor variables, b0 is the value of Y when all of the independent variables (X1 through Xp) are equal to zero, and b1 through bp are the estimated regression coefficients. How to cite a chart in APA? Method 2 of 4: Citing a Graph in APA Format Download Article Refer to the figure in your text. You should not include any figure that you don’t mention in the text. Place the citation underneath the graph. Label the graph or chart “Figure X.” Italicize this part. Provide a brief description of the graph. Begin your citation information. List the volume’s name, then the page number in parentheses.
__label__pos
1
What is the difference between / and // in xpath? 0 votes What is the difference between / and // in selenium? How can these two be used? Dec 24, 2018 in Selenium by Anjali • 2,930 points 1,134 views 2 answers to this question. 0 votes Single Slash “/” – Single slash is used to create Xpath with absolute path i.e. the xpath would be created to start selection from the document node/start node. Double Slash “//” – Double slash is used to create Xpath with relative path i.e. the xpath would be created to start selection from anywhere within the document. Hope this helps.  answered Dec 24, 2018 by Shuvodip 0 votes / - Selects from the root node // - Selects nodes in the document from the current node that match the selection no matter where they are answered May 29 by anonymous Can you explain it in detail with an example? Related Questions In Selenium 0 votes 1 answer What is the difference between dot and text() in XPath? Even though there is some difference between ...READ MORE answered Apr 25, 2018 in Selenium by king_kenny • 3,650 points 1,536 views 0 votes 1 answer What is the difference between findElement and findElements in Selenium Webdriver? Hi Nilaabh, Selenium Webdriver uses findElement and ...READ MORE answered May 8 in Selenium by Anvi • 13,960 points 585 views 0 votes 1 answer 0 votes 1 answer Finding WebDriver element with Class Name in java The better way to handle this element ...READ MORE answered Apr 10, 2018 in Selenium by nsv999 • 5,110 points 968 views 0 votes 1 answer 0 votes 1 answer Geo-location microphone camera pop up To Allow or Block the notification, access using Selenium and you have to ...READ MORE answered May 11, 2018 in Selenium by Samarpit • 5,130 points 1,130 views 0 votes 1 answer How to use such xpath to find web elements It's much simpler to use: #MyDiv123 > div.super or ...READ MORE answered Jun 14, 2018 in Selenium by Samarpit • 5,130 points 869 views 0 votes 1 answer What is the difference between relative and absolute XPath? Absolute Xpath: It contains the complete path ...READ MORE answered Dec 19, 2018 in Selenium by Nabarupa 2,426 views 0 votes 1 answer What is the difference between getWindowHandle() and getWindowHandles() methods in Selenium WebDriver? Hey Jennifer, difference between getWindowHandle() and getWindowHandles() ...READ MORE answered Jun 3 in Selenium by Anvi • 13,960 points 533 views
__label__pos
0.966756
Skip to content HTTPS clone URL Subversion checkout URL You can clone with or . Download ZIP Newer Older 100644 498 lines (359 sloc) 21.663 kB 3f957e4 @Sutto Add Gemnasium status authored 1 # RocketPants! [![Build Status](https://secure.travis-ci.org/filtersquad/rocket_pants.png?branch=master)](http://travis-ci.org/filtersquad/rocket_pants) [![Dependency Status](https://gemnasium.com/filtersquad/rocket_pants.png)](https://gemnasium.com/filtersquad/rocket_pants) 2 22b6142 @Sutto More readme tweaks. authored 3 ## Introduction 4 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 5 First thing's first, you're probably asking yourself - "Why the ridiculous name?". It's simple, really - RocketPants is memorable, and sounds completely bad ass. - everything a library needs. 98d2351 @Sutto README work and License tweaks authored 6 5e788d8 @levibuzolic Fixed typo in README levibuzolic authored 7 At its core, RocketPants is a set of tools (built around existing toolsets such as ActionPack) to make it easier to build well-designed APIs in Ruby and more importantly, along side Rails. You can think of it like [Grape](https://github.com/intridea/grape), a fantastic library which RocketPants was originally inspired by but with deeper Rails and ActionPack integration. 98d2351 @Sutto README work and License tweaks authored 8 9 ## Key Features 10 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 11 Why use RocketPants over alternatives like Grape or normal Rails? The reasons we built it come down to a couple of simple things: 98d2351 @Sutto README work and License tweaks authored 12 13 1. **It's opinionated** (like Grape) - In this case, we dictate a certain JSON structure we've found nice to work with (after having worked with and investigated a large number of other apis), it makes it simple to add metadata along side requests and the like. 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 14 2. **Simple and Often Automatic Response Metadata** - RocketPants automatically takes care of sending metadata about paginated responses and arrays where possible. This means as a user, you only need to worry about writing `expose object_or_presenter` in your controller and RocketPants will do it's best to send as much information back to the user. 15 3. **Extended Error Support** - RocketPants has a built in framework to manage errors it knows how to handle (in the forms of mapping exceptions to a well defined JSON structure) as well as tools to make it simple to hook up to Airbrake and do things such as including an error identifier in the response. 16 4. **It's built on ActionPack** - One of the key differentiators to Grape is that RocketPants embraces ActionPack and uses the modular components included from Rails 3.0 onwards to provide things you're familiar with already such as filters. 17 5. **Semi-efficient Caching Support** - Thanks to a combination of Rails middleware and collection vs. resource distinctions, RocketPants makes it relatively easy to implement "Efficient Validation" (See [here](http://rtomayko.github.com/rack-cache/faq)). As a developer, this means you get even more benefits of http caching where possible, without the need to generate full requests when etags are present. 0222651 @Sutto Add client examples authored 18 6. **Simple tools to consume RocketPants apis** - RocketPants includes the `RocketPants::Client` class which builds upon [APISmith](https://github.com/filtersquad/api_smith) to make it easier to build clients e.g. automatically converting paginated responses back. 9d28bed @Sutto Add in more docs authored 19 7. **Build in Header Metadata Support** - APIs can easily expose `Link:` headers (it's even partly built in for paginated data - see below) and request metadata (e.g. Object count etc) can easily be embedded in the headers of the response, making useful `HEAD` requests. 20 8. **Out of the Box ActiveRecord mapping** - We'll automatically take care of mapping `ActiveRecord::RecordNotFound`, `ActiveRecord::RecordNotSaved` and `ActiveRecord::RecordInvalid` for you, even including validation messages where possible. 98d2351 @Sutto README work and License tweaks authored 21 22b6142 @Sutto More readme tweaks. authored 22 ## Examples 23 24 ### A full example application 74b4567 @Sutto Add link to example app (not yet there) authored 25 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 26 Learn better by reading code? There is also have an example app mixing models and api clients over at [Sutto/transperth-api](https://github.com/Sutto/transperth-api) that is built using RocketPants. 74b4567 @Sutto Add link to example app (not yet there) authored 27 0222651 @Sutto Add client examples authored 28 ### Example Server Code 22b6142 @Sutto More readme tweaks. authored 29 7a362ce @Sutto More tweaks! Namely to the README authored 30 Say, for example, you have a basic Food model: 22b6142 @Sutto More readme tweaks. authored 31 32 ```ruby 7a362ce @Sutto More tweaks! Namely to the README authored 33 class Food < ActiveRecord::Base 34 include RocketPants::Cacheable 35 end 36 ``` 37 38 ```ruby 39 class FoodsController < RocketPants::Base 40 41 version 1 42 43 # The list of foods is paginated for 5 minutes, the food itself is cached 44 # until it's modified (using Efficient Validation) 45 caches :index, :show, :caches_for => 5.minutes 22b6142 @Sutto More readme tweaks. authored 46 47 def index 7a362ce @Sutto More tweaks! Namely to the README authored 48 expose Food.paginate(:page => params[:page]) 22b6142 @Sutto More readme tweaks. authored 49 end 50 51 def show 7a362ce @Sutto More tweaks! Namely to the README authored 52 expose Food.find(params[:id]) 22b6142 @Sutto More readme tweaks. authored 53 end 54 55 end 56 ``` 57 58 And in the router we'd just use the normal REST-like routes in Rails: 59 60 ```ruby 7a362ce @Sutto More tweaks! Namely to the README authored 61 api :version => 1 do 62 resources :foods, :only => [:index, :show] 63 end 64 ``` 65 d6092e9 @Sutto We need the version in the URL authored 66 And then, using this example, hitting `GET http://localhost:3000/1/foods` would result in: 7a362ce @Sutto More tweaks! Namely to the README authored 67 68 ```json 69 { 70 "response": [{ 71 "id": 1, 72 "name": "Delicious Food" 73 }, { 74 "id": 2, 75 "name": "More Delicious Food" 76 }], 77 "count": 2, 78 "pagination": { 79 "previous": nil, 80 "next": nil, 81 "current": 1, 82 "per_page": 10, 83 "count": 2, 84 "pages": 1 85 } 86 } 22b6142 @Sutto More readme tweaks. authored 87 ``` 88 d6092e9 @Sutto We need the version in the URL authored 89 with the `Cache-Control` header set whilst hitting `GET http://localhost:3000/1/foods/1` would return: 7a362ce @Sutto More tweaks! Namely to the README authored 90 91 ```json 92 { 93 "response": { 94 "id": 1, 95 "name": "Delicious Food" 96 } 97 } 98 ``` 99 100 with the `Etag` header set. 101 aa5dc16 @Sutto Add JSONP notes authored 102 #### JSONP 103 104 If you want to enable JSONP support, it's as simple as calling `jsonp` in your class method: 105 106 ```ruby 107 class MyController < RocketPants::Base 108 jsonp 109 end 110 ``` 111 112 By default this will use the `callback` parameter, e.g. `GET /1/my?callback=console.log`. 113 To change this parameter, specify the `parameter` option like so: 114 115 ```ruby 116 class MyController < RocketPants::Base 117 jsonp :parameter => :jsonp 118 end 119 ``` 120 121 Finally, to disable it in a subclass, simple call `jsonp` in the child and pass `:enable => false` as an option. 122 6c3caed @Sutto Initial link documentation authored 123 #### Header Metadata 124 125 When `RocketPants.header_metadata` or `config.rocket_pants.header_metadata` are set to true, RocketPants can automatically 126 expose metadata via `X-Api-` headers. Likewise, for paginated responses, if you implement `page_url(page_number)` in your controller 127 with header metadata enabled, RocketPants will automatically add HTTP Link Headers for the next, prev, first and last to your 128 response. 129 130 Likewise, you can manually add link headers using the `link(rel, href, attributes = {})` method like so: 131 132 ```ruby 133 def index 134 # Not an actual rel, just an example... 135 link :profile, user_profile_path(current_user) 136 expose current_user 137 end 138 ``` 139 140 For batch adding links, you can use the `links` method: 141 142 ```ruby 143 def index 144 # Probably not the best example... 145 links :next => random_wallpaper_path, :prev => random_wallpaper_path 146 expose Wallpaper.random 147 end 148 ``` 149 0222651 @Sutto Add client examples authored 150 ### Example Client Code 151 152 Using the example above, we could then use the following to write a client: 153 154 ```ruby 155 class FoodsClient < RocketPants::Client 156 157 version 1 158 base_uri 'http://localhost:3000' 159 160 class Food < APISmith::Smash 161 property :id 162 property :name 163 end 164 165 def foods 166 get 'foods', :transformer => Food 167 end 168 169 def food(id) 170 get "foods/#{id}", :transformer => Food 171 end 172 173 end 174 ``` 175 98d2351 @Sutto README work and License tweaks authored 176 ## General Structure 177 178 RocketPants builds upon the mixin-based approach to ActionController-based rails applications that Rails 3 made possible. Instead of including everything like Rails does in `ActionController::Base`, RocketPants only includes the bare minimum to make apis. In the near future, it may be modified to work with `ActionController::Base` for the purposes of better compatibility with other gems. 179 180 Out of the box, we use the following ActionController components: 181 182 * `ActionController::HideActions` - Lets you hide methods from actions. 183 * `ActionController::UrlFor` - `url_for` helpers / tweaks by Rails to make integration with routes work better. 184 * `ActionController::Redirecting` - Allows you to use `redirect_to`. 185 * `ActionController::ConditionalGet` - Adds support for Rails caching controls, e.g. `fresh_when` and `expires_in`. 186 * `ActionController::RackDelegation` - Lets you reset the session and set the response body. 187 * `ActionController::RecordIdentifier` - Gives `dom_class` and `dom_id` methods, used for polymorphic routing. 9858dfb @Sutto Readme updates authored 188 * `ActionController::HttpAuthentication` Mixins - Gives Token, Digest and Basic authentication. 98d2351 @Sutto README work and License tweaks authored 189 * `AbstractController::Callbacks` - Adds support for callbacks / filters. 190 * `ActionController::Rescue` - Lets you use `rescue_from`. 191 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 192 And added our own: 98d2351 @Sutto README work and License tweaks authored 193 194 * `RocketPants::UrlFor` - Automatically includes the current version when generating URLs from the controller. 195 * `RocketPants::Respondable` - The core of RocketPants, the code that handles converting objects to the different container types. 196 * `RocketPants::Versioning` - Allows versioning requirements on the controller to ensure it is only callable with a specific api version. 197 * `RocketPants::Instrumentation` - Adds Instrumentation notifications making it easy to use and hook into with Rails. 198 * `RocketPants::Caching` - Implements time-based caching for index actions and etag-based efficient validation for singular resources. 199 * `RocketPants::ErrorHandling` - Short hand to create errors as well as simplifications to catch and render a standardised error representation. 200 * `RocketPants::Rescuable` - Allows you to hook in to rescuing exceptions and to make it easy to post notifications to tools such as AirBrake. 201 202 To use RocketPants, instead of inheriting from `ActionController::Base`, just inherit from `RocketPants::Base`. 203 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 204 Likewise, in Rails applications RocketPants also adds `RocketPants::CacheMiddleware` before the controller endpoints to implement ["Efficient Validation"](http://rtomayko.github.com/rack-cache/faq). 98d2351 @Sutto README work and License tweaks authored 205 149db46 @Sutto More README docs / tweaks authored 206 ## Installing RocketPants 207 208 Installing RocketPants is a simple matter of adding: 209 210 gem 'rocket_pants', '~> 1.0' 211 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 212 To your `Gemfile` and running `bundle install`. Next, instead of inherited from `ActionController::Base`, simply inherit from `RocketPants::Base` instead. If you're working with an API-only application, I typically change this in `ApplicationController` and inherit from `ApplicationController` as usual. Otherwise, I generate a new `ApiController` base controller along side `ApplicationController` which instead inherits from `RocketPants::Base` and place all my logic there. 149db46 @Sutto More README docs / tweaks authored 213 214 ## Configuration 215 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 216 Setting up RocketPants in your rails application is pretty simple and requires a minimal amount of effort. Inside your environment configuration, RocketPants offers the following options to control how it's configured (and their expanded alternatives): 149db46 @Sutto More README docs / tweaks authored 217 218 - `config.rocket_pants.use_caching` - Defaulting to true for production environments and false elsewhere, defines whether RocketPants caching setup as described below is used. 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 219 - `config.rocket_pants.cache` - A `Moneta::Store` instance used as the RocketPants cache, defaulting to a moneta memory instance. Change for proper caching. (See [here](https://github.com/wycats/moneta) for more information on Moneta.) 6b2a363 @Sutto Update the readme with configuration documentation authored 220 - `config.rocket_pants.header_metadata` - Defaults to false, if true enables header metadata in the application. 221 - `config.rocket_pants.pass_through_errors` - Defaults true in development and test, false otherwise. If true, will pass through errors up the stack otherwise will swallow them and return a system error via JSON for any unhandled exceptions. 149db46 @Sutto More README docs / tweaks authored 222 223 ## Version Controllers / Routes 224 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 225 The current preferred way of dealing with version APIs in RocketPants is to do it using routes in the form of `/:version/:endpoint` - e.g. `GET /1/users/324`. RocketPants has support in the router and controller level for enforcing and controlling this. In the controller, it's a matter of specifying the required API versions: 149db46 @Sutto More README docs / tweaks authored 226 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 227 ```ruby 228 class UsersController < RocketPants::Base 229 version 1 # A single version 230 # or... 231 version 2..3 # 2-3 support this controller 232 end 233 ``` 149db46 @Sutto More README docs / tweaks authored 234 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 235 And in the case of multiple versions, I strongly encourage namespaces the controllers inside modules. If the version param (as specified) by the URL does not match, then the specified controller will return an `:invalid_version` error as shown below. 149db46 @Sutto More README docs / tweaks authored 236 237 Next, in your `config/routes.rb` file, you can also declare versions using the following syntax and it will automatically set up the routes for you: 238 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 239 ```ruby 240 api :version => 1 do 241 get 'x', :to => 'test#item' 242 end 243 ``` 149db46 @Sutto More README docs / tweaks authored 244 245 Which will route `GET /1/x` to `TestController#item`. 246 247 Likewise, you can specify a route for multiple versions by: 248 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 249 ```ruby 250 api :versions => 1..3 do 251 get 'x', :to => 'test#item' 252 end 253 ``` 149db46 @Sutto More README docs / tweaks authored 254 98d2351 @Sutto README work and License tweaks authored 255 ## Working with data 256 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 257 When using RocketPants, you write your controllers the same as how you would with normal ActionController, the only thing that changes is how you handle data. `head` and `redirect_to` still work exactly the same as in Rails, but instead of using `respond_with` and `render` you instead use RocketPant's `exposes` methods (and it's kind). Namely: 3f8d609 @Sutto More type conversion docs authored 258 259 - `expose` / `exposes` - The core of all type conversion, will check the type of data and automatically convert it to the correct time (for either a singular, collection or paginated resource). 260 - `paginated` - Render an object as a paginated collection of data. 261 - `collection` - Renders a collection of objects - e.g. an array of users. 262 - `resource` - Renders a single object. 263 264 Along side the above that wrap data, it also provides: 265 266 - `responds` - Renders JSON, normalizing the object first (unwrapped). 267 - `render_json` - Renders an object as JSON. 268 269 ### Singular Resources 270 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 271 Singular resources will be converted to JSON via `serializable_hash`, passing through any objects 3f8d609 @Sutto More type conversion docs authored 272 and then wrapped in an object as the `response` key: 273 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 274 ```json 275 { 276 "response": { 277 "your": "serialized-object" 278 } 279 } 280 ``` 3f8d609 @Sutto More type conversion docs authored 281 282 ### Collections 283 284 Similar to singular resources, but also include extra data about the count of items. 285 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 286 ```json 287 { 288 "response": [{ 289 "name": "object-one" 290 }, { 291 "name": "object-two" 292 }], 293 "count": 2 294 } 295 ``` 3f8d609 @Sutto More type conversion docs authored 296 297 ### Paginated Collections 298 c741f37 @paxer typo fix paxer authored 299 The final type, similar to collection objects but it includes details about the paginated data: 3f8d609 @Sutto More type conversion docs authored 300 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 301 ```json 302 { 303 "response": [ 304 {"name": "object-one"}, 305 {"name": "object-two"}, 306 {"name": "object-three"}, 307 {"name": "object-four"}, 308 {"name": "object-five"} 309 ], 310 "count": 5, 311 "pagination": { 312 "previous": 1, 313 "next": 3, 314 "current": 2, 315 "per_page": 5, 1e498dc @levibuzolic Missing comma in paginated collections example levibuzolic authored 316 "count": 23, 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 317 "pages": 5 318 } 319 } 320 ``` 98d2351 @Sutto README work and License tweaks authored 321 322 ## Registering / Dealing with Errors 323 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 324 One of the built in features of RocketPants is the ability to handle rescuing / controlling exceptions and more importantly to handle mapping exceptions to names, messages and error codes. 4da07ec @Sutto Started writing docs on the error handling authored 325 a270612 @Sutto Add ActiveRecord integration and specs, docs! authored 326 This comes in useful when you wish to automatically convert exceptions such as `ActiveRecord::RecordNotFound` (Note: This case is handled already) to a structured bit of data in the response. Namely, it makes it trivial to generate objects that follow the JSON structure of: 4da07ec @Sutto Started writing docs on the error handling authored 327 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 328 ```json 329 { 330 "error": "standard_error_name", 331 "error_description": "A translated error message describing what happened." 332 } 333 ``` 4da07ec @Sutto Started writing docs on the error handling authored 334 335 It also adds a facilities to make it easy to add extra information to the response. 336 337 RocketPants will also attempt to convert all errors in the controller, defaulting to the `"system"` exception name and message as the error description. We also provide a registry to allow throwing exception from their symbolic name like so: 338 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 339 ```ruby 340 error! :not_found 341 ``` 4da07ec @Sutto Started writing docs on the error handling authored 342 343 In the controller. 344 345 Out of the box, the following exceptions come pre-registered and setup: 346 347 - `:throttled` - The user has hit an api throttled error. 348 - `:unauthenticated` - The user doesn't have valid authentication details. 349 - `:invalid_version` - An invalid API version was specified. 350 - `:not_implemented` - The specified endpoint is not yet implemented. 351 - `:not_found` - The given resource could not be found. a270612 @Sutto Add ActiveRecord integration and specs, docs! authored 352 - `:invalid_resource` - The given resource was invalid. 353 - `:bad_request` - The given request was not as expected. 4da07ec @Sutto Started writing docs on the error handling authored 354 6d970f0 @Sutto Add error context extras to the README authored 355 Note that error also excepts a Hash of contextual options, many which will be passed through to the Rails I18N subsystem. E.g: 356 357 ```ruby 358 error! :throttled, :max_per_hour => 100 359 ``` 360 361 Will look up the translation `rocket_pants.errors.throttled` in your I18N files, and call them with `:max_per_hour` as an argument. 362 363 Finally, You can use this to also pass custom values to include in the response, e.g: 364 365 ```ruby 366 error! :throttled, :extras => {:code => 123} 367 ``` 368 369 Will return something similar to: 370 371 ```json 372 { 373 "error": "throttled", 374 "error_description": "The example error message goes here", 375 "code": 123 376 } 377 ``` 378 a270612 @Sutto Add ActiveRecord integration and specs, docs! authored 379 ### Build in ActiveRecord Errors 380 381 Out of the box, Rocket Pants will automatically map the following to built in errors and rescue them 382 as appropriate. 383 384 - `ActiveRecord::RecordNotFound` into `RocketPants::NotFound` 385 - `ActiveRecord::RecordNotSaved` into `RocketPants::InvalidResource (with no validation messages).` 386 - `ActiveRecord::RecordInvalid` into `RocketPants::InvalidResource (with messages in the "messages" key of the JSON).` 387 388 For Invalid Resource messages, the response looks roughly akin to: 389 9d28bed @Sutto Add in more docs authored 390 ```json 391 { 392 "error": "invalid_resource", 393 "error_description": "The current resource was deemed invalid.", 394 "messages": { 395 "name": ["can't be blank"], 396 "child_number":["can't be blank", "is not a number"], 397 "latin_name": ["is too short (minimum is 5 characters)", "is invalid"] 398 } 399 } 400 ``` a270612 @Sutto Add ActiveRecord integration and specs, docs! authored 401 98d2351 @Sutto README work and License tweaks authored 402 ## Implementing Efficient Validation 403 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 404 One of the core design principles built into RocketPants is simple support for "Efficient Validation" as described in the [Rack::Cache FAQ](http://rtomayko.github.com/rack-cache/faq) - Namely, it adds simple support for object-level caching using etags with fast verification thanks to the `RocketPants::CacheMiddleware` cache middleware. 149db46 @Sutto More README docs / tweaks authored 405 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 406 To do this, it uses `RocketPants.cache`, by default any Moneta-based store, to keep a mapping of object -> current cache key. RocketPants will then generate the etag when caching is enabled in the controller for singular-responses, generating an etag that can be quickly validated. 149db46 @Sutto More README docs / tweaks authored 407 408 For example, you'd add the following to your model: 409 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 410 ```ruby 411 class User < ActiveRecord::Base 412 include RocketPants::Cacheable 413 end 414 ``` 149db46 @Sutto More README docs / tweaks authored 415 416 And then in your controller, you'd have something like: 417 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 418 ```ruby 419 class UsersController < RocketPants::Base 149db46 @Sutto More README docs / tweaks authored 420 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 421 version 1 149db46 @Sutto More README docs / tweaks authored 422 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 423 # Time based, e.g. collections, will be cached for 5 minutes - whilst singular 424 # items e.g. show will use etag-based caching: 425 caches :show, :index, :caches_for => 5.minutes 149db46 @Sutto More README docs / tweaks authored 426 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 427 def index 428 expose User.all 429 end 149db46 @Sutto More README docs / tweaks authored 430 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 431 def show 432 expose User.find(params[:id]) 433 end 149db46 @Sutto More README docs / tweaks authored 434 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 435 end 436 ``` 149db46 @Sutto More README docs / tweaks authored 437 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 438 When the user hits the index endpoint, it will generate an expiry-based caching header that caches the result for up to 5 minutes. When the user instead hits the show endpoint, it will generate a special etag that contains and object identifier portion and an object cache key. Inside `RocketPants.cache`, we store the mapping and then inside `RocketPants::CacheMiddleware`, we simply check if the given cache key matches the specified object identifier. If it does, we return a not modified response otherwise we pass it through to controller - giving the advantage of efficient caching without having to hit the full database on every request. 98d2351 @Sutto README work and License tweaks authored 439 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 440 ## Using with RSpec 73b2f4e Add misc. test helpers Darcy Laycock authored 441 f0a3bbd @Sutto Update README.md to mention needing the version parameters in specs. … authored 442 When testing controllers written using RocketPants, your normal rails approach should work. 443 The only difference one needs to take into the account is the need to specify the `:version` 444 parameter on any http requests, e.g: 445 446 ```ruby 447 get :index, :version => 1 448 ``` 449 450 Otherwise it will raise an exception. 451 98d2351 @Sutto README work and License tweaks authored 452 RocketPants includes a set of helpers to make testing controllers built on `RocketPants::Base` simpler. 453 19b8bc5 @Sutto RSpec integration docs authored 454 * `be_singular_resource` - Checks the response is a single resource - e.g. `response.should be_siingular_resource`. 455 * `be_collection_resource` - Checks the response is collection of resources - e.g. `response.should be_collection_resource`. e7f4299 @Sutto Finish implementing jsonp, add a stubbed out helper_method implementa… authored 456 * `be_paginated_resource` - Checks the response is paginated - e.g. `response.should be_paginated_resource`. 19b8bc5 @Sutto RSpec integration docs authored 457 * `be_api_error(type = any)` - Checks it returned an error for the specified exception (or check the response is an error without any argument) - e.g. `response.should be_api_error RocketPants::NotFound`. 458 * `have_exposed(data, options = {})` - Given an object and conversion options, lets you check the output exposed the same object. e.g: `response.should have_exposed user` 459 460 Likewise, it adds the following helper methods: 461 462 - `parsed_body` - A parsed-JSON representation of the response. 463 - `decoded_body` - A `Hashie::Mash` of the response body. 464 465 To set up the integration, in your `spec/spec_helper.rb` add: 466 45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README fredwu authored 467 ```ruby 468 config.include RocketPants::TestHelper, :type => :controller 469 config.include RocketPants::RSpecMatchers, :type => :controller 470 ``` 19b8bc5 @Sutto RSpec integration docs authored 471 472 Inside the `RSpec.configure do |config|` block. 98d2351 @Sutto README work and License tweaks authored 473 8ced3cb @Sutto Update README.md authored 474 ## Contributors 475 476 - [Darcy Laycock](https://github.com/Sutto) - Main developer, current maintainer. 477 - [Steve Webb](https://github.com/swebb) - Helped with original work at [The Frontier Group](https://github.com/thefrontiergroup), inc. original design. 478 - [Fred Wu](https://github.com/fredwu) - README fixes. 479 - [Levi Buzolic](https://github.com/levibuzolic) - README fixes. 480 98d2351 @Sutto README work and License tweaks authored 481 ## Contributing 482 483 We encourage all community contributions. Keeping this in mind, please follow these general guidelines when contributing: 484 485 * Fork the project 486 * Create a topic branch for what you’re working on (git checkout -b awesome_feature) 487 * Commit away, push that up (git push your\_remote awesome\_feature) 488 * Create a new GitHub Issue with the commit, asking for review. Alternatively, send a pull request with details of what you added. 489 * Once it’s accepted, if you want access to the core repository feel free to ask! Otherwise, you can continue to hack away in your own fork. 490 491 Other than that, our guidelines very closely match the GemCutter guidelines [here](http://wiki.github.com/qrush/gemcutter/contribution-guidelines). 492 493 (Thanks to [GemCutter](http://wiki.github.com/qrush/gemcutter/) for the contribution guide) 73b2f4e Add misc. test helpers Darcy Laycock authored 494 98d2351 @Sutto README work and License tweaks authored 495 ## License 73b2f4e Add misc. test helpers Darcy Laycock authored 496 22b6142 @Sutto More readme tweaks. authored 497 RocketPants is released under the MIT License (see the [license file](https://github.com/filtersquad/rocket_pants/blob/master/LICENSE)) and is copyright Filter Squad, 2012. Something went wrong with that request. Please try again.
__label__pos
0.936548
1 /* 2 * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "classfile/javaClasses.hpp" 27 #include "classfile/symbolTable.hpp" 28 #include "classfile/systemDictionary.hpp" 29 #include "classfile/vmSymbols.hpp" 30 #include "code/codeCache.hpp" 31 #include "code/icBuffer.hpp" 32 #include "gc_implementation/shared/gcHeapSummary.hpp" 33 #include "gc_implementation/shared/gcTimer.hpp" 34 #include "gc_implementation/shared/gcTrace.hpp" 35 #include "gc_implementation/shared/gcTraceTime.hpp" 36 #include "gc_interface/collectedHeap.inline.hpp" 37 #include "memory/genCollectedHeap.hpp" 38 #include "memory/genMarkSweep.hpp" 39 #include "memory/genOopClosures.inline.hpp" 40 #include "memory/generation.inline.hpp" 41 #include "memory/modRefBarrierSet.hpp" 42 #include "memory/referencePolicy.hpp" 43 #include "memory/space.hpp" 44 #include "oops/instanceRefKlass.hpp" 45 #include "oops/oop.inline.hpp" 46 #include "prims/jvmtiExport.hpp" 47 #include "runtime/fprofiler.hpp" 48 #include "runtime/handles.inline.hpp" 49 #include "runtime/synchronizer.hpp" 50 #include "runtime/thread.inline.hpp" 51 #include "runtime/vmThread.hpp" 52 #include "utilities/copy.hpp" 53 #include "utilities/events.hpp" 54 55 void GenMarkSweep::invoke_at_safepoint(int level, ReferenceProcessor* rp, bool clear_all_softrefs) { 56 guarantee(level == 1, "We always collect both old and young."); 57 assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint"); 58 59 GenCollectedHeap* gch = GenCollectedHeap::heap(); 60 #ifdef ASSERT 61 if (gch->collector_policy()->should_clear_all_soft_refs()) { 62 assert(clear_all_softrefs, "Policy should have been checked earlier"); 63 } 64 #endif 65 66 // hook up weak ref data so it can be used during Mark-Sweep 67 assert(ref_processor() == NULL, "no stomping"); 68 assert(rp != NULL, "should be non-NULL"); 69 _ref_processor = rp; 70 rp->setup_policy(clear_all_softrefs); 71 72 GCTraceTime t1(GCCauseString("Full GC", gch->gc_cause()), PrintGC && !PrintGCDetails, true, NULL); 73 74 gch->trace_heap_before_gc(_gc_tracer); 75 76 // When collecting the permanent generation Method*s may be moving, 77 // so we either have to flush all bcp data or convert it into bci. 78 CodeCache::gc_prologue(); 79 Threads::gc_prologue(); 80 81 // Increment the invocation count 82 _total_invocations++; 83 84 // Capture heap size before collection for printing. 85 size_t gch_prev_used = gch->used(); 86 87 // Capture used regions for each generation that will be 88 // subject to collection, so that card table adjustments can 89 // be made intelligently (see clear / invalidate further below). 90 gch->save_used_regions(level); 91 92 allocate_stacks(); 93 94 mark_sweep_phase1(level, clear_all_softrefs); 95 96 mark_sweep_phase2(); 97 98 // Don't add any more derived pointers during phase3 99 COMPILER2_PRESENT(assert(DerivedPointerTable::is_active(), "Sanity")); 100 COMPILER2_PRESENT(DerivedPointerTable::set_active(false)); 101 102 mark_sweep_phase3(level); 103 104 mark_sweep_phase4(); 105 106 restore_marks(); 107 108 // Set saved marks for allocation profiler (and other things? -- dld) 109 // (Should this be in general part?) 110 gch->save_marks(); 111 112 deallocate_stacks(); 113 114 // If compaction completely evacuated all generations younger than this 115 // one, then we can clear the card table. Otherwise, we must invalidate 116 // it (consider all cards dirty). In the future, we might consider doing 117 // compaction within generations only, and doing card-table sliding. 118 bool all_empty = true; 119 for (int i = 0; all_empty && i < level; i++) { 120 Generation* g = gch->get_gen(i); 121 all_empty = all_empty && gch->get_gen(i)->used() == 0; 122 } 123 GenRemSet* rs = gch->rem_set(); 124 Generation* old_gen = gch->get_gen(level); 125 // Clear/invalidate below make use of the "prev_used_regions" saved earlier. 126 if (all_empty) { 127 // We've evacuated all generations below us. 128 rs->clear_into_younger(old_gen); 129 } else { 130 // Invalidate the cards corresponding to the currently used 131 // region and clear those corresponding to the evacuated region. 132 rs->invalidate_or_clear(old_gen); 133 } 134 135 Threads::gc_epilogue(); 136 CodeCache::gc_epilogue(); 137 JvmtiExport::gc_epilogue(); 138 139 if (PrintGC && !PrintGCDetails) { 140 gch->print_heap_change(gch_prev_used); 141 } 142 143 // refs processing: clean slate 144 _ref_processor = NULL; 145 146 // Update heap occupancy information which is used as 147 // input to soft ref clearing policy at the next gc. 148 Universe::update_heap_info_at_gc(); 149 150 // Update time of last gc for all generations we collected 151 // (which currently is all the generations in the heap). 152 // We need to use a monotonically non-decreasing time in ms 153 // or we will see time-warp warnings and os::javaTimeMillis() 154 // does not guarantee monotonicity. 155 jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC; 156 gch->update_time_of_last_gc(now); 157 158 gch->trace_heap_after_gc(_gc_tracer); 159 } 160 161 void GenMarkSweep::allocate_stacks() { 162 GenCollectedHeap* gch = GenCollectedHeap::heap(); 163 // Scratch request on behalf of oldest generation; will do no 164 // allocation. 165 ScratchBlock* scratch = gch->gather_scratch(gch->_gens[gch->_n_gens-1], 0); 166 167 // $$$ To cut a corner, we'll only use the first scratch block, and then 168 // revert to malloc. 169 if (scratch != NULL) { 170 _preserved_count_max = 171 scratch->num_words * HeapWordSize / sizeof(PreservedMark); 172 } else { 173 _preserved_count_max = 0; 174 } 175 176 _preserved_marks = (PreservedMark*)scratch; 177 _preserved_count = 0; 178 } 179 180 181 void GenMarkSweep::deallocate_stacks() { 182 if (!UseG1GC) { 183 GenCollectedHeap* gch = GenCollectedHeap::heap(); 184 gch->release_scratch(); 185 } 186 187 _preserved_mark_stack.clear(true); 188 _preserved_oop_stack.clear(true); 189 _marking_stack.clear(); 190 _objarray_stack.clear(true); 191 } 192 193 void GenMarkSweep::mark_sweep_phase1(int level, 194 bool clear_all_softrefs) { 195 // Recursively traverse all live objects and mark them 196 GCTraceTime tm("phase 1", PrintGC && Verbose, true, _gc_timer); 197 trace(" 1"); 198 199 GenCollectedHeap* gch = GenCollectedHeap::heap(); 200 201 // Because follow_root_closure is created statically, cannot 202 // use OopsInGenClosure constructor which takes a generation, 203 // as the Universe has not been created when the static constructors 204 // are run. 205 follow_root_closure.set_orig_generation(gch->get_gen(level)); 206 207 // Need new claim bits before marking starts. 208 ClassLoaderDataGraph::clear_claimed_marks(); 209 210 gch->gen_process_strong_roots(level, 211 false, // Younger gens are not roots. 212 true, // activate StrongRootsScope 213 SharedHeap::SO_SystemClasses, 214 &follow_root_closure, 215 &follow_root_closure, 216 &follow_klass_closure); 217 218 // Process reference objects found during marking 219 { 220 ref_processor()->setup_policy(clear_all_softrefs); 221 const ReferenceProcessorStats& stats = 222 ref_processor()->process_discovered_references( 223 &is_alive, &keep_alive, &follow_stack_closure, NULL, _gc_timer); 224 gc_tracer()->report_gc_reference_stats(stats); 225 } 226 227 // This is the point where the entire marking should have completed. 228 assert(_marking_stack.is_empty(), "Marking should have completed"); 229 230 // Unload classes and purge the SystemDictionary. 231 bool purged_class = SystemDictionary::do_unloading(&is_alive); 232 233 // Unload nmethods. 234 CodeCache::do_unloading(&is_alive, purged_class); 235 236 // Prune dead klasses from subklass/sibling/implementor lists. 237 Klass::clean_weak_klass_links(&is_alive); 238 239 // Delete entries for dead interned strings. 240 StringTable::unlink(&is_alive); 241 242 // Clean up unreferenced symbols in symbol table. 243 SymbolTable::unlink(); 244 245 gc_tracer()->report_object_count_after_gc(&is_alive); 246 } 247 248 249 void GenMarkSweep::mark_sweep_phase2() { 250 // Now all live objects are marked, compute the new object addresses. 251 252 // It is imperative that we traverse perm_gen LAST. If dead space is 253 // allowed a range of dead object may get overwritten by a dead int 254 // array. If perm_gen is not traversed last a Klass* may get 255 // overwritten. This is fine since it is dead, but if the class has dead 256 // instances we have to skip them, and in order to find their size we 257 // need the Klass*! 258 // 259 // It is not required that we traverse spaces in the same order in 260 // phase2, phase3 and phase4, but the ValidateMarkSweep live oops 261 // tracking expects us to do so. See comment under phase4. 262 263 GenCollectedHeap* gch = GenCollectedHeap::heap(); 264 265 GCTraceTime tm("phase 2", PrintGC && Verbose, true, _gc_timer); 266 trace("2"); 267 268 gch->prepare_for_compaction(); 269 } 270 271 class GenAdjustPointersClosure: public GenCollectedHeap::GenClosure { 272 public: 273 void do_generation(Generation* gen) { 274 gen->adjust_pointers(); 275 } 276 }; 277 278 void GenMarkSweep::mark_sweep_phase3(int level) { 279 GenCollectedHeap* gch = GenCollectedHeap::heap(); 280 281 // Adjust the pointers to reflect the new locations 282 GCTraceTime tm("phase 3", PrintGC && Verbose, true, _gc_timer); 283 trace("3"); 284 285 // Need new claim bits for the pointer adjustment tracing. 286 ClassLoaderDataGraph::clear_claimed_marks(); 287 288 // Because the closure below is created statically, we cannot 289 // use OopsInGenClosure constructor which takes a generation, 290 // as the Universe has not been created when the static constructors 291 // are run. 292 adjust_pointer_closure.set_orig_generation(gch->get_gen(level)); 293 294 gch->gen_process_strong_roots(level, 295 false, // Younger gens are not roots. 296 true, // activate StrongRootsScope 297 SharedHeap::SO_AllClasses | SharedHeap::SO_AllCodeCache, 298 &adjust_pointer_closure, 299 &adjust_pointer_closure, 300 &adjust_klass_closure); 301 302 gch->gen_process_weak_roots(&adjust_pointer_closure); 303 304 adjust_marks(); 305 GenAdjustPointersClosure blk; 306 gch->generation_iterate(&blk, true); 307 } 308 309 class GenCompactClosure: public GenCollectedHeap::GenClosure { 310 public: 311 void do_generation(Generation* gen) { 312 gen->compact(); 313 } 314 }; 315 316 void GenMarkSweep::mark_sweep_phase4() { 317 // All pointers are now adjusted, move objects accordingly 318 319 // It is imperative that we traverse perm_gen first in phase4. All 320 // classes must be allocated earlier than their instances, and traversing 321 // perm_gen first makes sure that all Klass*s have moved to their new 322 // location before any instance does a dispatch through it's klass! 323 324 // The ValidateMarkSweep live oops tracking expects us to traverse spaces 325 // in the same order in phase2, phase3 and phase4. We don't quite do that 326 // here (perm_gen first rather than last), so we tell the validate code 327 // to use a higher index (saved from phase2) when verifying perm_gen. 328 GenCollectedHeap* gch = GenCollectedHeap::heap(); 329 330 GCTraceTime tm("phase 4", PrintGC && Verbose, true, _gc_timer); 331 trace("4"); 332 333 GenCompactClosure blk; 334 gch->generation_iterate(&blk, true); 335 }
__label__pos
0.919998
roblox-ts API Reference An API reference for the Roact library for roblox-ts. Methods Roact.createElement function createElement( component: string | typeof Roact.Component, props?: | Dictionary<string, any> | Properties<Roact.Component>, children?: | Roact.Element[] | Dictionary<string, Roact.Element[]>, ): Roact.Element; Creates a new Roact element representing the given component. Elements are lightweight descriptions about what a Roblox Instance should look like, like a blueprint! The children argument should be specified as a dictionary of names to elements. component can be a string, a function, or a component class created by class MyComponentClass extends Roact.Component. Once props or children are passed into the createElement, make sure you don’t modify them! Roact.mount function mount( element: Roact.Element, parent?: Instance, key?: string, ): Roact.ComponentInstanceHandle; Creates a Roblox Instance given a Roact element, and optionally a parent to put it in, and a key to use as the instance’s Name. The result is a ComponentInstanceHandle, which is an opaque handle that represents this specific instance of the root component. You can pass this to APIs like Roact.unmount and the future debug API. Roact.reconcile function reconcile( instanceHandle: ComponentInstanceHandle, element: Roact.Element, ): ComponentInstanceHandle; Updates an existing instance handle with a new element, returning a new handle. This can be used to update a UI created with Roact.mount by passing in a new element with new props. reconcile can be used to change the props of a component instance created with mount and is useful for putting Roact content into non-Roact applications. Roact.reconcile takes ownership of the instanceHandle passed into it and may unmount it and mount a new tree! Make sure to use the handle that reconcile returns in any operations after reconcile, including unmount. Roact.unmount function unmount(instanceHandle: ComponentInstanceHandle): void; Destroys the given ComponentInstanceHandle and all of its descendents. Does not operate on a Roblox Instance – this must be given a handle that was returned by Roact.mount. Roact.oneChild function oneChild( children?: Roact.Element[], ): Roact.Element | undefined; Given a dictionary of children, returns a single child element. If children contains more than one child, oneChild function will throw an error. This is intended to denote an error when using the component using oneChild. If children is undefined or contains no children, oneChild will return undefined. You should ensure that the returned result is not undefined before returning it via the render() method. Roact.createRef // implictly defined as typeof Instance reference function createRef(): Roact.Ref; // explicit type reference function createRef<T extends Rbx_Instance>: Roact.Ref<T>; Component Classes class Roact.Component The base component instance that can be extended to make stateful components. class MyComponent extends Roact.Component<P, S> • P is the type of the props. • S is the type of the state. Both can be omitted if not required. If you want to use props but not state, simply omit S. If you want to use state but not props, set your props as {}. class Roact.PureComponent Exactly like Roact.Component except shouldUpdate is handled differently. class MyPureCompopnent extends Roact.PureComponent<P, S> class Roact.Portal interface PortalProps { instance: Instance; } class Roact.Portal extends Roact.Component<PortalProps> Used in Portals. This class cannot be inherited Component API defaultProps interface DefaultProps { value?: number; } class DefaultPropsExample extends Roact.Component<DefaultProps> { static defaultProps: DefaultProps = { value: 10, }; } If defaultProps is defined on a stateful component, any props that aren’t specified when a component is created will be taken from there. This is useful for setting props that can be undefined to a value. props[Roact.Children] class SingleChildComponent extends Roact.Component { public render(): Roact.Element { return Roact.oneChild(this.props[Roact.Children]); } } This contains any child elements that have been passed to this component. constructor class MyComponent extends Roact.Component { constructor(props: P) { super(props); // ... } } The constructor is called exactly once when a new instance of a component is created. It can be used to set up the initial state as well as any non-render related values directly on the component. render class HelloWorldComponent extends Roact.Component { public render(): Roact.Element { return Roact.createElement("TextLabel", { Text: "Hello, World!", }); } } class HelloWorldComponent extends Roact.Component { public render(): Roact.Element { return <textlabel Text="Hello, World!"/>; } } render describes what a component should display at the current instant in time. Roact assumes that render act likes a pure function: the result of render must depend only on props and state, and it must not have side-effects. rbx-roact will not compile without render being defined. setState class MyComponent extends Roact.Component<P, S>{ public setState( stateFn: (prevState: Readonly<S>, props: P): AnyKeyValueOf<S>, ): void; public setState( state: AnyKeyValueOf<S>, ): void; } setState can be called from anywhere except: Lifecycle hooks: willUnmount Pure functions: render, shouldUpdate Calling setState inside of init or willUpdate has special behavior. Because Roact is already going to update component in these cases, that update will be replaced instead of another being scheduled. Roact may support calling setState in currently-disallowed places in the future. setState does not always resolve synchronously! Roact may batch and reschedule state updates in order to reduce the number of total renders. When depending on the previous value of state, like when incrementing a counter, use the functional form to guarantee that all state updates occur!
__label__pos
0.874941
How to write sql table output at a specific range or cell. sarita kumari 1 Reputation point 2020-08-18T16:47:03.733+00:00 I need to export Sql server data into Excel at a specific range. Below is the query I am using:- INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0; Database=C:\Users\Documents\Discrepancy Report.xlsx;','SELECT * FROM [Sheet1$A22:C37]') select * from [Test] It is throwing error as Cannot process the object "SELECT * FROM [Sheet1$A22:C37]". The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" indicates that either the object has no columns or the current user does not have permissions on that object. How can i do this SQL Server SQL Server A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions. 13,463 questions SQL Server Integration Services SQL Server Integration Services A Microsoft platform for building enterprise-level data integration and data transformations solutions. 2,539 questions Transact-SQL Transact-SQL A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions. 4,613 questions 0 comments No comments {count} votes 2 answers Sort by: Most helpful 1. Guoxiong 8,201 Reputation points 2020-08-18T18:04:51.767+00:00 Go to the "SQL Server (MSSQLSERVER)" service and change the service account from NT Service\MSSQLSERVER to Local System and then restart the service. If you want to export the specific table columns to the excel, you need to have the column headers in the excel sheet. And then run the following query: INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0; Database=C:\Users\Documents\Discrepancy Report.xlsx;','SELECT * FROM [Sheet1$]') SELECT Col1, Col2, ... FROM [Test] You need to specify the names of the columns you want to export data from . 0 comments No comments 2. Monalv-MSFT 5,896 Reputation points 2020-08-19T02:13:13.377+00:00 Hi saritakumari, We can use OLEDB Source and Excel Destination in SSIS package. 18662-df.png When configuring Excel Destination, we can use the following two methods to get specific range: Method1: Set AccessMode as SQL Command 18671-sqlcommand1.png 18635-sqlcommand2.png Method2: Set AccessMode as OpenRowset 18681-openrowset1.png 18682-openrowset2.png Please refer to How to read data from an Excel file starting from the nth row with SQL Server Integration Services. Best Regards, Mona ---------- If the response is helpful, please click "Accept Answer" and upvote it.
__label__pos
0.655253
Detailed description of four transaction isolation levels of MySQL and four levels of mysql Source: Internet Author: User Detailed description of four transaction isolation levels of MySQL and four levels of mysql Test environment of this experiment: Windows 10 + cmd + MySQL5.6.36 + InnoDB I. Basic Elements of transactions (ACID) 1. Atomicity: All operations after the transaction starts, either completed or not done, cannot be stuck in the intermediate stage. If an error occurs during the transaction execution, it is rolled back to the state before the start of the transaction. All the operations are the same as none. That is to say, a transaction is an inseparable whole, just like an atom learned by chemistry, which is the basic unit of material composition. 2. Consistency: The integrity constraints of the database are not damaged before and after the transaction starts and ends. For example, if A transfers money to B, it is impossible for A to deduct the money, but B does not receive the money. 3. Isolation: At the same time, only one transaction can request the same data. Different transactions have no interference with each other. For example, if A is taking money from A bank card, B cannot transfer money to the card before A's withdrawal. 4. Durability: after the transaction is completed, all updates to the database by the transaction will be saved to the database and cannot be rolled back. Conclusion: Atomicity is the foundation of transaction isolation, isolation and persistence are the means, and the ultimate goal is to maintain data consistency. Ii. Transaction concurrency 1. Dirty read: Transaction A reads the data updated by transaction B, and then B rolls back, then the data read by transaction A is dirty data. 2. Non-repeated read: Transaction A reads the same data multiple times, and transaction B updates and submits the data while transaction A reads the data multiple times, as A result, transaction A reads the same data multiple times and the results are inconsistent. 3. Phantom read: System Administrator A changes the score of all the students in the database from the specific score to the ABCDE grade, but System Administrator B inserts A specific score record at this time, after System Administrator A completes the change, he finds that another record has not been changed, just like an illusion. This is called phantom read. Summary: Non-repeated reads and Phantom reads are easy to confuse. Non-repeated reads focus on modifications, and Phantom reads focus on addition or deletion. To solve the problem of non-repeated read, you only need to lock the rows that meet the conditions and solve the phantom read need to lock the table. Iii. MySQL transaction isolation level The default transaction isolation level of mysql is repeatable-read. 4. Use examples to illustrate the isolation levels 1. Read not submitted: (1) Open A Client A and set the current transaction mode to read uncommitted (uncommitted read). query the initial values of the Table account: (2) Before the transaction commit of Client A, open another client B and update the table account: (3) at this time, although the transaction of client B has not been committed, client A can query the data updated by client B: (4) Once the transaction of client B is rolled back for some reason, all operations will be canceled, and the data queried by Client A is actually dirty data: (5) execute the update statement update account set balance = balance-50 where id = 1 on Client A. The balance of lilei is not changed to 350, but it is 400. Isn't it strange, data Consistency is not a question. If you think so, it would be naive. In the application, we will use 400-50 = 350, and we do not know that other sessions are rolled back, to solve this problem, you can use the Read committed isolation level. 2. Read committed (1) Open A Client A, set the current transaction mode to read committed (uncommitted read), and query the initial values of the Table account: (2) Before the transaction commit of Client A, open another client B and update the table account: (3) At this time, the transaction of client B has not been committed, and client A cannot query the data updated by client B, solving the dirty read problem: (4) transaction commit of client B (5) Client A executes the same query as the previous step, and the results are inconsistent with the previous step, that is, the problem of non-repeated reading occurs. In the application, assume that we are in the session of Client, the balance of lilei is found to be 450, but other transactions change the balance value of lilei to 400. We do not know if other operations are performed with the value of 450, however, this probability is really small. To avoid this problem, you can adopt a Repeatable read isolation level. 3. Repeatable read (1) Open A Client A and set the current transaction mode to repeatable read. query the initial values of the Table account: (2) Before the transaction commit of Client A, open another client B, update the table account and submit the transaction. The transaction of client B can actually modify the row queried by client A transaction, that is to say, mysql's repeatable reads won't lock the rows queried by the transaction. This is beyond my expectation. in SQL standards, when the transaction isolation level is repeatable, read/write operations need to lock the rows, mysql does not have a lock. I went there. In the application, pay attention to apply the row lock. Otherwise, you will take the lilei balance in step (1) as the center value for other operations. (3) perform the query in step (1) on Client: (4) in step 1, the balance of lilei is still 400 consistent with the query result of step (1), and there is no problem of repeated reading; then execute update balance = balance-50 where id = 1, balance does not change to 400-50 = 350, and the balance value of lilei is calculated using 350 in step (2, so it's 300. Data Consistency is not broken. It's amazing. Maybe it's a special feature of mysql. mysql> select * from account;+------+--------+---------+| id | name | balance |+------+--------+---------+| 1 | lilei | 400 || 2 | hanmei | 16000 || 3 | lucy | 2400 |+------+--------+---------+rows in set (0.00 sec)mysql> update account set balance = balance - 50 where id = 1;Query OK, 1 row affected (0.00 sec)Rows matched: 1 Changed: 1 Warnings: 0mysql> select * from account;+------+--------+---------+| id | name | balance |+------+--------+---------+| 1 | lilei | 300 || 2 | hanmei | 16000 || 3 | lucy | 2400 |+------+--------+---------+rows in set (0.00 sec) (5) Start A transaction on Client A and query the initial values of the Table account mysql> start transaction;Query OK, 0 rows affected (0.00 sec)mysql> select * from account;+------+--------+---------+| id | name | balance |+------+--------+---------+| 1 | lilei | 300 || 2 | hanmei | 16000 || 3 | lucy | 2400 |+------+--------+---------+rows in set (0.00 sec) (6) Start the transaction on client B and add a new piece of data. The balance field value is 600, and submit mysql> start transaction;Query OK, 0 rows affected (0.00 sec)mysql> insert into account values(4,'lily',600);Query OK, 1 row affected (0.00 sec)mysql> commit;Query OK, 0 rows affected (0.01 sec) (7) Calculate the sum of balance on Client A, with A value of 300 + 16000 + 2400 = 18700. The value of client B is not included, and client A submits the value before calculating the sum of balance, this is because 19300 of client B is included. From the customer's point of view, the customer cannot see client B, and it will think it is a pie in the world, with 600 more data blocks, this is phantom reading. From the developer's perspective, data consistency is not broken. However, in the application, the Code may submit 18700 to the user. If you must avoid this situation, then we need to adopt the transaction isolation level "serialize" described below" mysql> select sum(balance) from account;+--------------+| sum(balance) |+--------------+| 18700 |+--------------+1 row in set (0.00 sec)mysql> commit;Query OK, 0 rows affected (0.00 sec)mysql> select sum(balance) from account;+--------------+| sum(balance) |+--------------+| 19300 |+--------------+1 row in set (0.00 sec) 4. serialization (1) Open A Client A and set the current transaction mode to serializable. query the initial values of the Table account: mysql> set session transaction isolation level serializable;Query OK, 0 rows affected (0.00 sec)mysql> start transaction;Query OK, 0 rows affected (0.00 sec)mysql> select * from account;+------+--------+---------+| id | name | balance |+------+--------+---------+| 1 | lilei | 10000 || 2 | hanmei | 10000 || 3 | lucy | 10000 || 4 | lily | 10000 |+------+--------+---------+rows in set (0.00 sec) (2) open a client B, set the current transaction mode to serializable, insert a record, and report an error. If the table is locked, insertion fails. When the transaction isolation level in mysql is serializable, the table will be locked, therefore, there will be no phantom read. This isolation-level concurrency is extremely low, and often one transaction occupies a table. Thousands of other transactions can only be used when they are used up and committed, it is rarely used in development. mysql> set session transaction isolation level serializable;Query OK, 0 rows affected (0.00 sec)mysql> start transaction;Query OK, 0 rows affected (0.00 sec)mysql> insert into account values(5,'tom',0);ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction Supplement:  1. The specific implementation of different databases may vary according to the standards specified by SQL specifications. 2. The default transaction isolation level in mysql is that the read row will not be locked during Repeatable read. 3. When the transaction isolation level is serialized, reading data locks the entire table 4. When reading this article, from the developer's point of view, you may feel that repeated and Phantom reads are not allowed. Logically, there is no problem, and the final data is still consistent, but from the user's point of view, they can only see one transaction (only client A can be seen, and client B is unknown), without considering the phenomenon of concurrent transaction execution, once the same data is read differently for multiple times, or a new record appears out of thin air, they may have doubts, which is a problem of user experience. 5. when a transaction is executed in mysql, Data Consistency does not occur in the final result, because in a transaction, mysql may not use the intermediate result of the previous operation to execute an operation, it will be collected and processed based on the actual situation of other concurrent transactions. It looks illogical, but ensures data consistency. However, when a transaction is executed in an application, the result of one operation is used by the next operation and is calculated by other operations. This is because we should be careful that we should lock rows during repeatable reads and lock tables during serialization. Otherwise, data consistency will be damaged. 6. When a transaction is executed in mysql, mysql will comprehensively process it based on the actual situation of each transaction, resulting in Data Consistency not being broken, but the application will play the cards according to the logic routine, without the knowledge of mysql, Data Consistency may inevitably occur. 7. The higher the isolation level, the more data integrity and consistency can be ensured, but the greater the impact on concurrency performance, the fish and the bear's paw cannot have both. For most applications, the isolation level of the database system can be set to Read Committed, which can avoid dirty reading and has good concurrency performance. Although it can cause non-repeated read and phantom read concurrency problems, in some cases where such problems may occur, the application can adopt pessimistic locks or optimistic locks to control. The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers. Related Article Contact Us The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email. If you find any instances of plagiarism from the community, please send an email to: [email protected] and provide relevant evidence. A staff member will contact you within 5 working days. A Free Trial That Lets You Build Big! Start building with 50+ products and up to 12 months usage for Elastic Compute Service • Sales Support 1 on 1 presale consultation • After-Sales Support 24/7 Technical Support 6 Free Tickets per Quarter Faster Response • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.
__label__pos
0.695863
Trait scale_info::prelude::ops::Index 1.0.0 · source · [] pub trait Index<Idx> where     Idx: ?Sized { type Output: ?Sized; fn index(&self, index: Idx) -> &Self::Output; } Expand description Used for indexing operations (container[index]) in immutable contexts. container[index] is actually syntactic sugar for *container.index(index), but only when used as an immutable value. If a mutable value is requested, IndexMut is used instead. This allows nice things such as let value = v[index] if the type of value implements Copy. Examples The following example implements Index on a read-only NucleotideCount container, enabling individual counts to be retrieved with index syntax. use std::ops::Index; enum Nucleotide { A, C, G, T, } struct NucleotideCount { a: usize, c: usize, g: usize, t: usize, } impl Index<Nucleotide> for NucleotideCount { type Output = usize; fn index(&self, nucleotide: Nucleotide) -> &Self::Output { match nucleotide { Nucleotide::A => &self.a, Nucleotide::C => &self.c, Nucleotide::G => &self.g, Nucleotide::T => &self.t, } } } let nucleotide_count = NucleotideCount {a: 14, c: 9, g: 10, t: 12}; assert_eq!(nucleotide_count[Nucleotide::A], 14); assert_eq!(nucleotide_count[Nucleotide::C], 9); assert_eq!(nucleotide_count[Nucleotide::G], 10); assert_eq!(nucleotide_count[Nucleotide::T], 12); Required Associated Types The returned type after indexing. Required Methods Performs the indexing (container[index]) operation. Panics May panic if the index is out of bounds. Implementors
__label__pos
0.999697
• Advertisement Sign in to follow this   understanding glBlendFunc ops This topic is 4648 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic. If you intended to correct an error in the post then please contact us. Recommended Posts Hi .I want to simulate some of the glBlendFunc operations in a fragment shader that I will be writing to tint the underlying texture(amongst other things), but I would like to know how they work , not least because it will make the process easier. What I don't understand from the documentation for glBlendFunc is how the source and destinitation scalefactors works as quoted below: GL_ONE............... S:(1,1,1,1)...D:(1,1,1,1) GL_SRC_COLOR..........S:(R s / k R , G s / k G , B s / k B , A s / k A ) D:(R s / k R , G s / k G , B s / k B , A s / k A ) where kR,kG,kB = max number of colours per channel. ( e.g 255 for 24 bit image ) etc... with the final equations being Rs = min(kr,RssR + Rd+dR) etc. GL_ONE is obvious enough since its just doing additive blending,but I don't understand the logic behind the calculation of the scale factors for the other blend funcs. Can someone enlighten me. Mark Share this post Link to post Share on other sites Advertisement You realize that, because the fragment shader can't read from the frame buffer, you can't actually do alpha blending in the shader? Share this post Link to post Share on other sites Quote: Original post by Promit You realize that, because the fragment shader can't read from the frame buffer, you can't actually do alpha blending in the shader? I intend to use a fragment shader with a texture copied from the framebuffer using glCopyTexImage2D. Although I'm new to shaders, I've had a look at some demos that do image processing in this way, which makes me think its possible. Am I right. Mark Share this post Link to post Share on other sites Yeah, that will work, although it will be a bit more expensive. Anyway, basically what you have in alpha blending is a source color and a destination color. Source is the incoming fragment, and Dest is what's in the framebuffer. So in this case, Source is what you would normally give as the color output, and Dest is the pixel that you look up from the shader. Blending simply involves combining these in various ways. For example, ONE, ONE will make Result = 1 * Source + 1 * Dest. SRC_ALPHA, ONE_MINUS_SRC_ALPHA does Result = SourceAlpha * Source + (1 - SourceAlpha) * Dest. I don't really like how the documentation on OGL blending is written. This way of looking at it is far simpler and more intuitive. Share this post Link to post Share on other sites Sign in to follow this   • Advertisement
__label__pos
0.597758
milliLampson [prev][up][next] milliLampson /mil'*-lamp`sn/ /n./ A unit of talking speed, abbreviated mL. Most people run about 200 milliLampsons. The eponymous Butler Lampson (a CS theorist and systems implementor highly regarded among hackers) goes at 1000. A few people speak faster. This unit is sometimes used to compare the (sometimes widely disparate) rates at which people can generate ideas and actually emit them in speech. For example, noted computer architect C. Gordon Bell (designer of the PDP-11) is said, with some awe, to think at about 1200 mL but only talk at about 300; he is frequently reduced to fragments of sentences as his mouth tries to keep up with his speeding brain. [prev][up][next] Return to Cool Jargon of the Day
__label__pos
0.813883
Motivations The motivation for this model is typically when dealing with survey data it is nice to be able to discriminate between the “student” difficulty (\(\alpha\)), the question difficulty (\(\beta\)) and the discrimination of the questions \(\gamma\). Data Generating Process \[P(y_n = 1) = logit^{-1}(\gamma_{kk|n|}(\alpha_{jj|n|} -\beta_{kk|n|}))\] J <- 30 # Students K <- 10 # Questions N <- J * K alpha <- runif(K, .5, 2) #slopes beta <- runif(K, -2, 3) # intercepts theta_mu <- 0 # population mean of person ability theta_sig <- 1 # population sd of person ability theta <-rnorm(J, theta_mu, theta_sig) # generate 500 ability parameters slope.ability <-outer(theta, alpha) # multiply the slope vector by the ability vector intercept <- matrix(rep(beta, J), nrow = J, byrow = TRUE) prob <- plogis(intercept + slope.ability) # 1/(1 + exp(.)) data <-ifelse(runif(N) < prob, 1, 0) # generate matrix of Bernoulli 0-1 responses Now we can format our data. tidy_data <- data %>% as_tibble() %>% mutate(person_id = row_number()) %>% gather(item, response, -person_id) %>% mutate(item = as.numeric(as.factor(item))) ## Warning: `as_tibble.matrix()` requires a matrix with column names or a `.name_repair` argument. Using compatibility `.name_repair`. ## This warning is displayed once per session. Model Now we can build our Stan model using this reference. Stan writeLines(readLines("stan_2pl.stan")) // 2PL IRT in Stan // Modified from the Stan Users Guide <https://mc-stan.org/docs/> data { int<lower=1> J; // number of students int<lower=1> K; // number of questions int<lower=1> N; // number of observations int<lower=1,upper=J> jj[N]; // student for observation n int<lower=1,upper=K> kk[N]; // question for observation n int<lower=0,upper=1> y[N]; // correctness for observation n } parameters { real mu_beta; // mean question difficulty vector[J] alpha; // ability for j - mean vector[K] beta; // difficulty for k vector<lower=0>[K] gamma; // discrimination of k //real<lower=0> sigma_beta; // scale of difficulties //real<lower=0> sigma_gamma; // scale of log discrimination } model { alpha ~ std_normal(); // normal(y| 0,1) //Can make these hierarchical priors if desired //beta ~ normal(0, sigma_beta); //gamma ~ lognormal(0, sigma_gamma); beta ~ normal(0, 5); gamma ~ lognormal(0, 2); mu_beta ~ cauchy(0, 5); //sigma_beta ~ cauchy(0, 5); //sigma_gamma ~ cauchy(0, 5); y ~ bernoulli_logit(gamma[kk] .* (alpha[jj] - (beta[kk] + mu_beta))); } Data Prep Of course, we need to prepare our data for Stan. stan_dat <- list( J = length(unique(tidy_data[["person_id"]])), K = length(unique(tidy_data[["item"]])), N = nrow(tidy_data), jj = tidy_data[["person_id"]], kk = tidy_data[["item"]], y = tidy_data[["response"]] ) Modeling library(rstan) ## Loading required package: StanHeaders ## rstan (Version 2.18.2, GitRev: 2e1f913d3ca3) ## For execution on a local, multicore CPU with excess RAM we recommend calling ## options(mc.cores = parallel::detectCores()). ## To avoid recompilation of unchanged Stan programs, we recommend calling ## rstan_options(auto_write = TRUE) ## ## Attaching package: 'rstan' ## The following object is masked from 'package:tidyr': ## ## extract rstan_options(auto_write = TRUE) model <- stan_model("stan_2pl.stan") Now we can run our compiled model with our data: fit_2pl <- sampling(model, stan_dat, cores = 2, chains = 2, iter = 2000, refresh = 0) ## Warning: There were 47 divergent transitions after warmup. Increasing adapt_delta above 0.8 may help. See ## http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup ## Warning: Examine the pairs() plot to diagnose sampling problems Model Checking util <- new.env() source('stan_utilities.R', local=util) util$check_all_diagnostics(fit_2pl) If this were for a more serious application I would also check the pair plot and the traces. Inferences First we can look at our question difficulties. If an item has a higher value then it requires a higher level of ability to get it “correct.” print(fit_2pl, pars = "beta") ## Inference for Stan model: stan_2pl. ## 2 chains, each with iter=2000; warmup=1000; thin=1; ## post-warmup draws per chain=1000, total post-warmup draws=2000. ## ## mean se_mean sd 2.5% 25% 50% 75% 98% n_eff Rhat ## beta[1] -0.79 0.16 2.3 -6.15 -2.0 -0.51 0.62 3.14 214 1 ## beta[2] -1.46 0.14 2.5 -7.14 -2.7 -1.11 0.17 2.65 305 1 ## beta[3] -1.49 0.15 2.6 -7.73 -2.9 -1.16 0.35 2.72 323 1 ## beta[4] -4.75 0.15 3.2 -11.48 -6.7 -4.55 -2.49 0.66 455 1 ## beta[5] 3.25 0.11 2.2 -0.44 1.8 2.97 4.36 8.37 397 1 ## beta[6] 3.01 0.14 2.5 -1.52 1.4 2.76 4.47 8.51 325 1 ## beta[7] 0.49 0.17 3.5 -7.96 -1.3 0.63 2.61 6.74 431 1 ## beta[8] 3.98 0.13 2.6 -0.47 2.3 3.81 5.51 9.64 416 1 ## beta[9] -4.00 0.17 3.2 -11.22 -5.8 -3.59 -1.77 0.95 337 1 ## beta[10] 0.09 0.14 1.8 -3.38 -1.1 0.17 1.25 3.50 175 1 ## ## Samples were drawn using NUTS(diag_e) at Tue Feb 26 22:00:53 2019. ## For each parameter, n_eff is a crude measure of effective sample size, ## and Rhat is the potential scale reduction factor on split chains (at ## convergence, Rhat=1). Similarlly we can look at our item \(\gamma\)s to check for discrimination. print(fit_2pl, pars = "gamma") ## Inference for Stan model: stan_2pl. ## 2 chains, each with iter=2000; warmup=1000; thin=1; ## post-warmup draws per chain=1000, total post-warmup draws=2000. ## ## mean se_mean sd 2.5% 25% 50% 75% 98% n_eff Rhat ## gamma[1] 2.11 0.19 3.86 0.16 0.60 1.18 2.18 10.22 413 1.0 ## gamma[2] 6.61 0.89 12.51 0.29 1.04 2.28 5.88 52.83 196 1.0 ## gamma[3] 1.28 0.54 4.92 0.07 0.25 0.49 0.93 3.74 84 1.0 ## gamma[4] 0.31 0.01 0.21 0.07 0.17 0.26 0.38 0.86 616 1.0 ## gamma[5] 2.02 0.43 6.20 0.06 0.32 0.68 1.38 14.24 208 1.0 ## gamma[6] 2.87 1.03 8.06 0.02 0.25 0.67 1.60 32.59 61 1.1 ## gamma[7] 0.28 0.04 0.42 0.01 0.06 0.13 0.32 1.43 129 1.0 ## gamma[8] 0.45 0.02 0.41 0.03 0.17 0.33 0.59 1.50 614 1.0 ## gamma[9] 0.49 0.02 0.36 0.11 0.25 0.39 0.60 1.51 275 1.0 ## gamma[10] 12.16 0.92 17.52 0.39 2.78 5.71 13.98 61.90 364 1.0 ## ## Samples were drawn using NUTS(diag_e) at Tue Feb 26 22:00:53 2019. ## For each parameter, n_eff is a crude measure of effective sample size, ## and Rhat is the potential scale reduction factor on split chains (at ## convergence, Rhat=1). Summarising with ICC Now we can pull out some of our valuess and plot the ICCs for the different items. library(tidybayes) ## NOTE: As of tidybayes version 1.0, several functions, arguments, and output column names ## have undergone significant name changes in order to adopt a unified naming scheme. ## See help('tidybayes-deprecated') for more information. difficulties <- extract(fit_2pl)["beta"][[1]] %>% as_tibble() %>% colMeans() discrimination <- extract(fit_2pl)["gamma"][[1]] %>% as_tibble() %>% colMeans() instrument <- tibble(difficulties = difficulties, discrimination = discrimination) %>% mutate(item_id = sprintf("Item %s", 1:length(difficulties))) ability_range <- seq(-4,4, .05) probs <- crossing(instrument, ability_range) %>% rowwise() %>% mutate(prob = arm::invlogit(discrimination*(ability_range-difficulties))) And now we can look at our ICCs. probs %>% ggplot(aes(ability_range, prob, group = item_id, color = item_id))+ geom_line(se = FALSE)+ theme_minimal() ## Warning: Ignoring unknown parameters: se We could also take the time to look at our student abilities. extract(fit_2pl)["alpha"][[1]] %>% as_tibble() %>% colMeans() %>% hist(breaks = 30, main = "Histogram of Student Abilities") Research and Methods Resources [email protected] Winston- Salem, NC Michael DeWitt Copyright © 2018 Michael DeWitt. All rights reserved.
__label__pos
0.792329
<meta http-equiv="refresh" content="1; url=/nojavascript/"> Linear Approximation | CK-12 Foundation Dismiss Skip Navigation You are reading an older version of this FlexBook® textbook: CK-12 Texas Instruments Calculus Teacher's Edition Go to the latest version. This activity is intended to supplement Calculus, Chapter 3, Lesson 8. ID: 9470 Time required: 45 minutes Activity Overview In this activity, students will graph the functions, construct the tangent line at a point, and find an estimate from a linear approximation. They will then determine whether the estimate is an overestimate or an underestimate, and find an interval for a desired accuracy. Topic: Application of Derivatives • Calculate the equation of the tangent line to a graph at any given point. • Construct a tangent line to the graph of a differentiable function at x = a to approximate its value near x = a. • Construct a tangent line to the graph of a differentiable function at x = 0 to approximate its value near x = 0. Teacher Preparation and Notes • This investigation offers an opportunity for students to develop an understanding of how a tangent line to a curve can be used to approximate the values of a function near the point of tangency. Linear approximations are often used in scientific applications, including formulas used in physics where \sin \theta is replaced with its linear approximation, \theta. • This activity is designed to be student-centered with the teacher acting as a facilitator while students work cooperatively. The student worksheet is intended to guide students through the main ideas of the activity and provide a place for them to record their observations. • The students will need to be able to enter the functions and use the commands on their own. • Before starting this activity, students should go to the home screen and select F6 :Clean Up > 2:NewProb, then press ENTER. This will clear any stored variables, turn off any functions and plots, and clear the drawing and home screens. Associated Materials Part 1 – Introduction From top to bottom, the points where the horizontal lines cross the y-axis are L(x), \ f(x), \ f(a). L(x) will be the linear approximation. L(x) - f(x) = error of this estimate. Since L(x) > f(x), this estimate is an overestimate. To get the horizontal line, students can use graph > F7 :Pencil > 5:Horizontal To get the vertical line, they can use graph > F7 :Pencil > 6:Vertical. Part 2 – Investigating linear approximation Students are to graph the function of f1(x) = x^3 - 3x^2 - 2x + 6 and the tangent at a = -1. The point p is where the vertical line crosses the function. The point q is where the vertical line crosses the tangent line. For the x-value 0.2: L(0.2) = 12.4 is the linear approximation. The error is the length pq = 6.912 \ (12.4 - 5.488). The true value, f(0.2) = 5.488. It is an overestimation. linear approx. of f1(q) real value of f1(q) error underestimation/overestimation x = -0.2 9.6 6.272 3.328 overestimation x = -0.5 7.5 6.125 1.375 overestimation x = -0.6 6.8 5.904 0.896 overestimation x = -1.2 2.6 2.352 0.248 overestimation As you get close to the point of tangency, the graph of the function and the graph of the tangent line appear to be the same. They are called local linearization because the graph acts like a straight line at the point of tangency and that line is the tangent line. Students are to find the derivative of f1(x) = x^3 - 3x^2 - 2x + 6 and evaluate it at x = -1. They should use the slope and the point (-1, 4) to get the equation of the line. y - 4 = 7(x + 1) \to y & = 7x + 11 \\ L(x) & = 7x + 11 L(-1.03) = 3.79. This is the linear approximation. \text{Error} = 3.79 - 3.78457 = 0.005427 Part 3 – Underestimates versus overestimates Students are to graph f1(x) = x^3 - 3x^2 - 2x + 6 and place a tangent line a = 1. If p is to the left of a = 1, then the tangent line will be above the function and the linear approximation is an overestimate. If p is to the right of a = 1, then the tangent line will be below the function and the linear approximation is an underestimate. The point a = 1 is a point of inflection. Students can look at the second derivative and set it equal to zero to confirm this. Students should see that in general the linear approximation will overestimate if the curve is concave down and it will underestimate when the curve is concave up. Part 4 – Finding intervals of accuracy Students are posed with the question: How close to –1 must x be for the linear approximation to be within 0.2 units of the true value of f1(x)? When students look at the graph, they want the tangent line to be within the bound of f1(x) + 0.2 and f1(x) - 0.2. Since the linear approximation overestimates in this region, they want to compare L(x) and f1(x) + 0.2. Students can zoom in graphically or solve algebraically. The interval is (–1.1799, –0.81453) using the solve command. Because the tangent line overestimates to the left of x = 1 and underestimates to the right of x = 1 students will have to do this in two parts. Since the linear approximation overestimates in the region to the left of x = 1, students need to compare L(x) and f1(x) + 0.2 there. They can zoom in graphically or solve algebraically. The interval is (0.415196, 1) using the solve command. Since the linear approximation underestimates in the region to the right of x = 1, students want to compare L(x) and f1(x) - 0.2 there. They can zoom in graphically or solve algebraically. The interval is (1, 1.5848) using the solve command. Image Attributions Files can only be attached to the latest version of None Reviews Please wait... Please wait... Image Detail Sizes: Medium | Original   TI.MAT.ENG.TE.1.Calculus.4.4 ShareThis Copy and Paste Original text
__label__pos
0.96704
blob: db22a583133015201000c76d5aea9e3dfbc5a7d5 [file] [log] [blame] /* * FreeRTOS+UDP V1.0.3 (C) 2014 Real Time Engineers ltd. * All rights reserved * * This file is part of the FreeRTOS+UDP distribution. The FreeRTOS+UDP license * terms are different to the FreeRTOS license terms. * * FreeRTOS+UDP uses a dual license model that allows the software to be used * under a standard GPL open source license, or a commercial license. The * standard GPL license (unlike the modified GPL license under which FreeRTOS * itself is distributed) requires that all software statically linked with * FreeRTOS+UDP is also distributed under the same GPL V2 license terms. * Details of both license options follow: * * - Open source licensing - * FreeRTOS+UDP is a free download and may be used, modified, evaluated and * distributed without charge provided the user adheres to version two of the * GNU General Public License (GPL) and does not remove the copyright notice or * this text. The GPL V2 text is available on the gnu.org web site, and on the * following URL: http://www.FreeRTOS.org/gpl-2.0.txt. * * - Commercial licensing - * Businesses and individuals that for commercial or other reasons cannot comply * with the terms of the GPL V2 license must obtain a commercial license before * incorporating FreeRTOS+UDP into proprietary software for distribution in any * form. Commercial licenses can be purchased from http://shop.freertos.org/udp * and do not require any source files to be changed. * * FreeRTOS+UDP is distributed in the hope that it will be useful. You cannot * use FreeRTOS+UDP unless you agree that you use the software 'as is'. * FreeRTOS+UDP is provided WITHOUT ANY WARRANTY; without even the implied * warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. Real Time Engineers Ltd. disclaims all conditions and terms, be they * implied, expressed, or statutory. * * 1 tab == 4 spaces! * * http://www.FreeRTOS.org * http://www.FreeRTOS.org/udp * */ /****************************************************************************** * * See the following web page for essential buffer allocation scheme usage and * configuration details: * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_UDP/Embedded_Ethernet_Buffer_Management.shtml * ******************************************************************************/ /* THIS FILE SHOULD NOT BE USED IF THE PROJECT INCLUDES A MEMORY ALLOCATOR THAT WILL FRAGMENT THE HEAP MEMORY. For example, heap_2 must not be used, heap_4 can be used. */ /* Standard includes. */ #include <stdint.h> /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "semphr.h" /* FreeRTOS+UDP includes. */ #include "FreeRTOS_UDP_IP.h" #include "FreeRTOS_IP_Private.h" #include "NetworkInterface.h" /* For an Ethernet interrupt to be able to obtain a network buffer there must be at least this number of buffers available. */ #define ipINTERRUPT_BUFFER_GET_THRESHOLD ( 3 ) /* A list of free (available) xNetworkBufferDescriptor_t structures. */ static xList xFreeBuffersList; /* Declares the pool of xNetworkBufferDescriptor_t structures that are available to the system. All the network buffers referenced from xFreeBuffersList exist in this array. The array is not accessed directly except during initialisation, when the xFreeBuffersList is filled (as all the buffers are free when the system is booted). */ static xNetworkBufferDescriptor_t xNetworkBuffers[ ipconfigNUM_NETWORK_BUFFERS ]; /* The semaphore used to obtain network buffers. */ static xSemaphoreHandle xNetworkBufferSemaphore = NULL; /*-----------------------------------------------------------*/ portBASE_TYPE xNetworkBuffersInitialise( void ) { portBASE_TYPE xReturn, x; /* Only initialise the buffers and their associated kernel objects if they have not been initialised before. */ if( xNetworkBufferSemaphore == NULL ) { xNetworkBufferSemaphore = xSemaphoreCreateCounting( ipconfigNUM_NETWORK_BUFFERS, ipconfigNUM_NETWORK_BUFFERS ); configASSERT( xNetworkBufferSemaphore ); vQueueAddToRegistry( xNetworkBufferSemaphore, "NetBufSem" ); /* If the trace recorder code is included name the semaphore for viewing in FreeRTOS+Trace. */ #if ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1 { extern xQueueHandle xNetworkEventQueue; vTraceSetQueueName( xNetworkEventQueue, "IPStackEvent" ); vTraceSetQueueName( xNetworkBufferSemaphore, "NetworkBufferCount" ); } #endif /* ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1 */ if( xNetworkBufferSemaphore != NULL ) { vListInitialise( &xFreeBuffersList ); /* Initialise all the network buffers. No storage is allocated to the buffers yet. */ for( x = 0; x < ipconfigNUM_NETWORK_BUFFERS; x++ ) { /* Initialise and set the owner of the buffer list items. */ xNetworkBuffers[ x ].pucEthernetBuffer = NULL; vListInitialiseItem( &( xNetworkBuffers[ x ].xBufferListItem ) ); listSET_LIST_ITEM_OWNER( &( xNetworkBuffers[ x ].xBufferListItem ), &xNetworkBuffers[ x ] ); /* Currently, all buffers are available for use. */ vListInsert( &xFreeBuffersList, &( xNetworkBuffers[ x ].xBufferListItem ) ); } } } if( xNetworkBufferSemaphore == NULL ) { xReturn = pdFAIL; } else { xReturn = pdPASS; } return xReturn; } /*-----------------------------------------------------------*/ uint8_t *pucEthernetBufferGet( size_t *pxRequestedSizeBytes ) { uint8_t *pucEthernetBuffer; if( *pxRequestedSizeBytes < sizeof( xARPPacket_t ) ) { /* Buffers must be at least large enough to hold ARP packets, otherwise nothing can be done. */ *pxRequestedSizeBytes = sizeof( xARPPacket_t ); } /* Allocate a buffer large enough to store the requested Ethernet frame size and a pointer to a network buffer structure (hence the addition of ipBUFFER_PADDING bytes). */ pucEthernetBuffer = ( uint8_t * ) pvPortMalloc( *pxRequestedSizeBytes + ipBUFFER_PADDING ); /* Enough space is left at the start of the buffer to place a pointer to the network buffer structure that references this Ethernet buffer. Return a pointer to the start of the Ethernet buffer itself. */ pucEthernetBuffer += ipBUFFER_PADDING; return pucEthernetBuffer; } /*-----------------------------------------------------------*/ void vEthernetBufferRelease( uint8_t *pucEthernetBuffer ) { /* There is space before the Ethernet buffer in which a pointer to the network buffer that references this Ethernet buffer is stored. Remove the space before freeing the buffer. */ if( pucEthernetBuffer != NULL ) { pucEthernetBuffer -= ipBUFFER_PADDING; vPortFree( ( void * ) pucEthernetBuffer ); } } /*-----------------------------------------------------------*/ xNetworkBufferDescriptor_t *pxNetworkBufferGet( size_t xRequestedSizeBytes, portTickType xBlockTimeTicks ) { xNetworkBufferDescriptor_t *pxReturn = NULL; if( ( xRequestedSizeBytes != 0 ) && ( xRequestedSizeBytes < sizeof( xARPPacket_t ) ) ) { /* ARP packets can replace application packets, so the storage must be at least large enough to hold an ARP. */ xRequestedSizeBytes = sizeof( xARPPacket_t ); } /* If there is a semaphore available, there is a network buffer available. */ if( xSemaphoreTake( xNetworkBufferSemaphore, xBlockTimeTicks ) == pdPASS ) { /* Protect the structure as it is accessed from tasks and interrupts. */ taskENTER_CRITICAL(); { pxReturn = ( xNetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &xFreeBuffersList ); uxListRemove( &( pxReturn->xBufferListItem ) ); } taskEXIT_CRITICAL(); /* Allocate storage of exactly the requested size to the buffer. */ configASSERT( pxReturn->pucEthernetBuffer == NULL ); if( xRequestedSizeBytes > 0 ) { /* Extra space is obtained so a pointer to the network buffer can be stored at the beginning of the buffer. */ pxReturn->pucEthernetBuffer = ( uint8_t * ) pvPortMalloc( xRequestedSizeBytes + ipBUFFER_PADDING ); if( pxReturn->pucEthernetBuffer == NULL ) { /* The attempt to allocate storage for the buffer payload failed, so the network buffer structure cannot be used and must be released. */ vNetworkBufferRelease( pxReturn ); pxReturn = NULL; } else { /* Store a pointer to the network buffer structure in the buffer storage area, then move the buffer pointer on past the stored pointer so the pointer value is not overwritten by the application when the buffer is used. */ *( ( xNetworkBufferDescriptor_t ** ) ( pxReturn->pucEthernetBuffer ) ) = pxReturn; pxReturn->pucEthernetBuffer += ipBUFFER_PADDING; iptraceNETWORK_BUFFER_OBTAINED( pxReturn ); /* Store the actual size of the allocated buffer, which may be greater than the requested size. */ pxReturn->xDataLength = xRequestedSizeBytes; } } else { iptraceNETWORK_BUFFER_OBTAINED( pxReturn ); } } if( pxReturn == NULL ) { iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER(); } return pxReturn; } /*-----------------------------------------------------------*/ void vNetworkBufferRelease( xNetworkBufferDescriptor_t * const pxNetworkBuffer ) { portBASE_TYPE xListItemAlreadyInFreeList; /* Ensure the buffer is returned to the list of free buffers before the counting semaphore is 'given' to say a buffer is available. Release the storage allocated to the buffer payload. THIS FILE SHOULD NOT BE USED IF THE PROJECT INCLUDES A MEMORY ALLOCATOR THAT WILL FRAGMENT THE HEAP MEMORY. For example, heap_2 must not be used, heap_4 can be used. */ vEthernetBufferRelease( pxNetworkBuffer->pucEthernetBuffer ); pxNetworkBuffer->pucEthernetBuffer = NULL; taskENTER_CRITICAL(); { xListItemAlreadyInFreeList = listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) ); if( xListItemAlreadyInFreeList == pdFALSE ) { vListInsertEnd( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) ); } configASSERT( xListItemAlreadyInFreeList == pdFALSE ); } taskEXIT_CRITICAL(); xSemaphoreGive( xNetworkBufferSemaphore ); iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer ); } /*-----------------------------------------------------------*/ #if( ipconfigINCLUDE_TEST_CODE == 1 ) unsigned portBASE_TYPE uxGetNumberOfFreeNetworkBuffers( void ) { return listCURRENT_LIST_LENGTH( &xFreeBuffersList ); } #endif /* ipconfigINCLUDE_TEST_CODE */
__label__pos
0.959156
Unibody Macbook Pro Ram Discussion in 'MacBook Pro' started by waloshin, Dec 1, 2008. 1. waloshin macrumors 68040 waloshin Joined: Oct 9, 2008 #1 I know the unibody Macbook pro uses ddr2 ram , but at what mhz?   2. Azagar macrumors member Azagar Joined: Nov 29, 2008 Location: San Francisco 3. Tallest Skil macrumors P6 Tallest Skil Joined: Aug 13, 2006 Location: 1 Geostationary Tower Plaza #3 It uses DDR3. Go to OWC so you don't buy the wrong thing.   4. waloshin thread starter macrumors 68040 waloshin Joined: Oct 9, 2008 5. waloshin thread starter macrumors 68040 waloshin Joined: Oct 9, 2008 #5 So the new Macbook pro supports up to 6 gigabytes, but does the os see the ram?   6. Azagar macrumors member Azagar Joined: Nov 29, 2008 Location: San Francisco #6 According to that article you're probably referring to, there is a wall on the OS at 4GB max. Who knows if Snow leopard will unlock this, but I hope not. Don't wanna spend $500~ for a 4GB module. :D   7. waloshin thread starter macrumors 68040 waloshin Joined: Oct 9, 2008 #7 So true!   8. InLikeALion macrumors 6502a Joined: Jul 18, 2007 Location: Greener places than I used to live #8 Actually, UNtrue. Read the Barefeats artical (here) it does see and use 6gigs. Also, people who say the OS can only see 4gigs or less are just silly. Remember, my 4+ year old Powermac G5 can see at least 8gigs, and today's (and yesterday's) Mac Pro's can use 32gigs of ram. Leopard has no problem seeing the ram. I think it's still up for debate exactly why the early and late 08 mbp's don't use all 8gigs, but it isn't an inherent OS X thing.   9. Ampidire macrumors 6502 Ampidire Joined: Feb 1, 2007 #9 Well, we know that OS X on a MacPro and PowerMac's can see the RAM, but they have different chipset hardware, this chipset is capable as per nVidia of using 8GB of RAM, but it's something Apple has set up that makes it incapable of using so much, the issue is then what did they do? Why does the OS behave in that fashion when on other machines with even higher amounts of RAM it works fine? Is it in their EFI/Firmware/BIOS? or is it something in OS X that prohibits these machines from working correctly? I wonder if Vista x64 or XP x64 in BootCamp would see 8GB of RAM correctly, that'd tell us if it's a firmware or OS limitation apple has in place, or even if it's intentional or not.   10. InLikeALion macrumors 6502a Joined: Jul 18, 2007 Location: Greener places than I used to live #10 That's why I said it was debatable. There are some really long threads about people trying to figure out the reason for the limitation (mostly in earlier mbp's), but I don't think anyone was able to say definitively.   11. Azagar macrumors member Azagar Joined: Nov 29, 2008 Location: San Francisco #11 Leopard sees the ram just find, but not using it at all is a whole other problem. The article you posted even they agreed that more then 4GB actually slowed down you're computer. They used the term "molasses mode". This is the same conclusion as the ifixit article posted on MacRumors a bit earlier. Here   12. Ampidire macrumors 6502 Ampidire Joined: Feb 1, 2007 #12 with 8gb, but not 6gb, 6gb ran fine, which is weird. it's 64-bit underpinnings allow it to dynamically address more than 3.3gb of ram, and 8gb is well WELL beneath the limit of a 64-bit os, the problem is there seems to be something else benefiting to this issue, seeing as nvidia states that the chipset is fully capable of 8gb ram.   Share This Page
__label__pos
0.808922
blob: 7ecb0fa057d7d72b775d4e931298e12cb393430c [file] [log] [blame] // Copyright 2010-2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "rewriter/language_aware_rewriter.h" #include <string> #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/system_util.h" #include "base/util.h" #include "composer/composer.h" #include "composer/table.h" #include "config/config.pb.h" #include "config/config_handler.h" #include "converter/conversion_request.h" #include "converter/segments.h" #ifdef MOZC_USE_PACKED_DICTIONARY #include "data_manager/packed/packed_data_manager.h" #include "data_manager/packed/packed_data_mock.h" #endif // MOZC_USE_PACKED_DICTIONARY #include "data_manager/user_pos_manager.h" #include "dictionary/dictionary_mock.h" #include "dictionary/pos_matcher.h" #include "session/commands.pb.h" #include "testing/base/public/gunit.h" #include "usage_stats/usage_stats.h" #include "usage_stats/usage_stats_testing_util.h" DECLARE_string(test_tmpdir); using mozc::dictionary::DictionaryMock; namespace mozc { namespace { void InsertASCIISequence(const string &text, composer::Composer *composer) { for (size_t i = 0; i < text.size(); ++i) { commands::KeyEvent key; key.set_key_code(text[i]); composer->InsertCharacterKeyEvent(key); } } } // namespace class LanguageAwareRewriterTest : public testing::Test { protected: // Workaround for C2512 error (no default appropriate constructor) on MSVS. LanguageAwareRewriterTest() {} virtual ~LanguageAwareRewriterTest() {} virtual void SetUp() { usage_stats::UsageStats::ClearAllStatsForTest(); #ifdef MOZC_USE_PACKED_DICTIONARY // Registers mocked PackedDataManager. scoped_ptr<packed::PackedDataManager> data_manager(new packed::PackedDataManager()); CHECK(data_manager->Init(string(kPackedSystemDictionary_data, kPackedSystemDictionary_size))); packed::RegisterPackedDataManager(data_manager.release()); #endif // MOZC_USE_PACKED_DICTIONARY SystemUtil::SetUserProfileDirectory(FLAGS_test_tmpdir); config::ConfigHandler::GetDefaultConfig(&default_config_); config::ConfigHandler::SetConfig(default_config_); dictionary_mock_.reset(new DictionaryMock); } virtual void TearDown() { config::ConfigHandler::GetDefaultConfig(&default_config_); config::ConfigHandler::SetConfig(default_config_); #ifdef MOZC_USE_PACKED_DICTIONARY // Unregisters mocked PackedDataManager. packed::RegisterPackedDataManager(NULL); #endif // MOZC_USE_PACKED_DICTIONARY dictionary_mock_.reset(NULL); usage_stats::UsageStats::ClearAllStatsForTest(); } LanguageAwareRewriter *CreateLanguageAwareRewriter() const { return new LanguageAwareRewriter( *UserPosManager::GetUserPosManager()->GetPOSMatcher(), dictionary_mock_.get()); } scoped_ptr<DictionaryMock> dictionary_mock_; usage_stats::scoped_usage_stats_enabler usage_stats_enabler_; private: config::Config default_config_; }; namespace { bool RewriteWithLanguageAwareInput(const LanguageAwareRewriter *rewriter, const string &key, string *composition, Segments *segments) { commands::Request client_request; client_request.set_language_aware_input( commands::Request::LANGUAGE_AWARE_SUGGESTION); composer::Table table; config::Config default_config; table.InitializeWithRequestAndConfig(client_request, default_config); composer::Composer composer(&table, &client_request); InsertASCIISequence(key, &composer); composer.GetStringForPreedit(composition); // Perform the rewrite command. segments->set_request_type(Segments::SUGGESTION); if (segments->conversion_segments_size() == 0) { segments->add_segment(); } Segment *segment = segments->mutable_conversion_segment(0); segment->set_key(*composition); ConversionRequest request(&composer, &client_request); return rewriter->Rewrite(request, segments); } void PushFrontCandidate(const string &data, Segment *segment) { Segment::Candidate *candidate = segment->push_front_candidate(); candidate->Init(); candidate->value = data; candidate->key = data; candidate->content_value = data; candidate->content_key = data; } } // namespace TEST_F(LanguageAwareRewriterTest, LanguageAwareInput) { dictionary_mock_->AddLookupExact("house", "house", "house", Token::NONE); dictionary_mock_->AddLookupExact("query", "query", "query", Token::NONE); dictionary_mock_->AddLookupExact("google", "google", "google", Token::NONE); dictionary_mock_->AddLookupExact("naru", "naru", "naru", Token::NONE); // "なる" dictionary_mock_->AddLookupExact("\xE3\x81\xAA\xE3\x82\x8B", "\xE3\x81\xAA\xE3\x82\x8B", "naru", Token::NONE); scoped_ptr<LanguageAwareRewriter> rewriter(CreateLanguageAwareRewriter()); const string &kPrefix = "\xE2\x86\x92 "; // "→ " const string &kDidYouMean = // "もしかして" "\xE3\x82\x82\xE3\x81\x97\xE3\x81\x8B\xE3\x81\x97\xE3\x81\xA6"; { // "python" is composed to "pyてょn", but "python" should be suggested, // because alphabet characters are in the middle of the word. string composition; Segments segments; EXPECT_TRUE(RewriteWithLanguageAwareInput(rewriter.get(), "python", &composition, &segments)); // "pyてょn" EXPECT_EQ("\xEF\xBD\x90\xEF\xBD\x99\xE3\x81\xA6\xE3\x82\x87\xEF\xBD\x8E", composition); const Segment::Candidate &candidate = segments.conversion_segment(0).candidate(0); EXPECT_EQ("python", candidate.key); EXPECT_EQ("python", candidate.value); EXPECT_EQ(kPrefix, candidate.prefix); EXPECT_EQ(kDidYouMean, candidate.description); } { // "mozuk" is composed to "もずk", then "mozuk" is not suggested. // The tailing alphabet characters are not counted. string composition; Segments segments; EXPECT_FALSE(RewriteWithLanguageAwareInput(rewriter.get(), "mozuk", &composition, &segments)); // "もずk" EXPECT_EQ("\xE3\x82\x82\xE3\x81\x9A\xEF\xBD\x8B", composition); EXPECT_EQ(0, segments.conversion_segment(0).candidates_size()); } { // "house" is composed to "ほうせ". Since "house" is in the dictionary // dislike the above "mozuk" case, "house" should be suggested. string composition; Segments segments; if (segments.conversion_segments_size() == 0) { segments.add_segment(); } Segment *segment = segments.mutable_conversion_segment(0); // Add three candidates. // => ["cand0", "cand1", "cand2"] PushFrontCandidate("cand2", segment); PushFrontCandidate("cand1", segment); PushFrontCandidate("cand0", segment); EXPECT_EQ(3, segment->candidates_size()); // "house" should be inserted as the 3rd candidate (b/w cand1 and cand2). // => ["cand0", "cand1", "house", "cand2"] EXPECT_TRUE(RewriteWithLanguageAwareInput(rewriter.get(), "house", &composition, &segments)); EXPECT_EQ(4, segment->candidates_size()); // "ほうせ" EXPECT_EQ("\xE3\x81\xBB\xE3\x81\x86\xE3\x81\x9B", composition); const Segment::Candidate &candidate = segments.conversion_segment(0).candidate(2); EXPECT_EQ("house", candidate.key); EXPECT_EQ("house", candidate.value); EXPECT_EQ(kPrefix, candidate.prefix); EXPECT_EQ(kDidYouMean, candidate.description); } { // "query" is composed to "くえry". Since "query" is in the dictionary // dislike the above "mozuk" case, "query" should be suggested. string composition; Segments segments; EXPECT_TRUE(RewriteWithLanguageAwareInput(rewriter.get(), "query", &composition, &segments)); // "くえry" EXPECT_EQ("\xE3\x81\x8F\xE3\x81\x88\xEF\xBD\x92\xEF\xBD\x99", composition); const Segment::Candidate &candidate = segments.conversion_segment(0).candidate(0); EXPECT_EQ("query", candidate.key); EXPECT_EQ("query", candidate.value); EXPECT_EQ(kPrefix, candidate.prefix); EXPECT_EQ(kDidYouMean, candidate.description); } { // "google" is composed to "google" by mode_switching_handler. // If the suggestion is equal to the composition, that suggestion // is not added. string composition; Segments segments; EXPECT_FALSE(RewriteWithLanguageAwareInput(rewriter.get(), "google", &composition, &segments)); EXPECT_EQ("google", composition); } { // The key "なる" has two value "naru" and "なる". // In this case, language aware rewriter should not be triggered. string composition; Segments segments; EXPECT_FALSE(RewriteWithLanguageAwareInput(rewriter.get(), "naru", &composition, &segments)); // "なる" EXPECT_EQ("\xE3\x81\xAA\xE3\x82\x8B", composition); EXPECT_EQ(0, segments.conversion_segment(0).candidates_size()); } } TEST_F(LanguageAwareRewriterTest, LanguageAwareInputUsageStats) { scoped_ptr<LanguageAwareRewriter> rewriter(CreateLanguageAwareRewriter()); EXPECT_STATS_NOT_EXIST("LanguageAwareSuggestionTriggered"); EXPECT_STATS_NOT_EXIST("LanguageAwareSuggestionCommitted"); const string kPyTeyoN = // "pyてょn" "\xEF\xBD\x90\xEF\xBD\x99\xE3\x81\xA6\xE3\x82\x87\xEF\xBD\x8E"; { // "python" is composed to "pyてょn", but "python" should be suggested, // because alphabet characters are in the middle of the word. string composition; Segments segments; EXPECT_TRUE(RewriteWithLanguageAwareInput(rewriter.get(), "python", &composition, &segments)); EXPECT_EQ(kPyTeyoN, composition); const Segment::Candidate &candidate = segments.conversion_segment(0).candidate(0); EXPECT_EQ("python", candidate.key); EXPECT_EQ("python", candidate.value); EXPECT_COUNT_STATS("LanguageAwareSuggestionTriggered", 1); EXPECT_STATS_NOT_EXIST("LanguageAwareSuggestionCommitted"); } { // Call Rewrite with "python" again, then call Finish. Both ...Triggered // and ...Committed should be incremented. // Note, RewriteWithLanguageAwareInput is not used here, because // Finish also requires ConversionRequest. string composition; Segments segments; commands::Request client_request; client_request.set_language_aware_input( commands::Request::LANGUAGE_AWARE_SUGGESTION); composer::Table table; config::Config default_config; table.InitializeWithRequestAndConfig(client_request, default_config); composer::Composer composer(&table, &client_request); InsertASCIISequence("python", &composer); composer.GetStringForPreedit(&composition); EXPECT_EQ(kPyTeyoN, composition); // Perform the rewrite command. segments.set_request_type(Segments::SUGGESTION); Segment *segment = segments.add_segment(); segment->set_key(composition); ConversionRequest request(&composer, &client_request); EXPECT_TRUE(rewriter->Rewrite(request, &segments)); EXPECT_COUNT_STATS("LanguageAwareSuggestionTriggered", 2); segment->set_segment_type(Segment::FIXED_VALUE); EXPECT_LT(0, segment->candidates_size()); rewriter->Finish(request, &segments); EXPECT_COUNT_STATS("LanguageAwareSuggestionCommitted", 1); } } } // namespace mozc
__label__pos
0.874851
Skip to main content menu_icon.png   x Optimizely Knowledge Base Using dynamic selectors in Optimizely X Web There are two versions of Optimizely What version do you have? X Optimizely Classic This is what the Optimizely Classic user interface looks like. Optimizely X This is what the Optimizely X user interface looks like. . If you're using Optimizely Classic, check this article out instead. relevant products: • Optimizely X Web Experimentation • Optimizely X Web Personalization THIS ARTICLE WILL HELP YOU: • Identify situations where dynamic selectors may be causing problems with your experiments • Get your Optimizely experiments to work with dynamic selectors If your company uses a click-tracking service, Optimizely will not interfere with your ability to do so. However, because some of these services add dynamic IDs to the elements on your webpage, there are a few things you should be aware of to ensure that your experiment delivers usable results.  Problems with dynamic selectors  You may have had the experience where you have successfully made changes to a page in the Editor, but upon re-loading the page or re-opening the experiment later, the changes you made are gone. These changes are also absent from any live pages. This often happens when dynamic selectors are at work. The Optimizely Editor chooses the ID of an element as the default selector, since these IDs are usually unique. When you load your page into the Editor and make changes to an element (for example, the hero image), the Editor creates a line of variation code using the current dynamic ID as a selector. You'll see the changes displayed correctly in the variation at that time. But if the ID is dynamic, the next time you load the page, the ID will change to another value. The variation code doesn't know what to change, since the initial selector no longer exists.  Often, you can also tell if you have dynamic selectors if selector names displayed in the Editor include a seemingly random value -- such as #luckyAnchor_1234891 -- instead of something more generic like #heroBanner. If you notice a selector name that includes what looks like a randomly-generated string of numbers or characters, usually that selector has been dynamically generated. A non-dynamically generated selector should have a naming convention that looks like this: To see the selector ID of any element, navigate to the Editor and click the element. The ID will be displayed in the Selector field. IDs inserted at document.ready If your click tracking service inserts IDs (dynamic or static) at document.ready, this can also prevent Optimizely's variation code from making changes as expected. Mouseflow is one commonly-used service that does exactly this. The variation changes display correctly in the Editor, because the IDs exist when the page fully loads. However, when the variation code runs on site, the variation either doesn’t work at all it will flash or flicker. This is because the IDs don't actually exist until document.ready. The Optimizely snippet executes the variation code line-by-line as selectors become available. The snippet stops looking for selectors at document.ready. Ultimately, if the selectors don’t exist on the page or aren’t available, no changes can be made, and your variation won't appear. Use Optimizely with dynamic selectors  To use Optimizely with dynamic selectors, you'll need to ensure that dynamic selectors aren't used to make changes to elements on your page. You'll need to enable jQuery in project settings or include it in your code. Check out this article to learn more about jQuery and the $ variable in Optimizely X. Start by temporarily removing dynamic selectors while working in the Editor. Place the following code in the JavaScript tab of the Variation Code Editor window: /* _optimizely_evaluate=editor_only */ $('[id^="selector"]').each(function(){ $(this).removeAttr('id'); }); /* _optimizely_evaluate=end_editor_only */ In this code block, change selector to a string of characters that your dynamic IDs have in common. For example, if all your dynamic IDs begin with abc, change selector to abc. From there, you can write your own selectors, such as $(".container h2") to avoid using the #dynamic_id. Only the selector needs to be changed. The handler can remain the same. You can also work with your developers to make a one-time fix so that your click-tracking provider isn't added when iFramed in Optimizely. Then, the Editor won't detect the dynamic IDs and different selectors are defined instead. For instructions on how to edit the variation code manually, please view our article on editing code.
__label__pos
0.637323
user428370 user428370 - 7 months ago 50 Python Question How to use ``xlrd.xldate_as_tuple()`` I am not quite sure how to use the following function: xlrd.xldate_as_tuple for the following data xldate:39274.0 xldate:39839.0 Could someone please give me an example on usage of the function for the data? msw msw Answer Quoth the documentation: Dates in Excel spreadsheets In reality, there are no such things. What you have are floating point numbers and pious hope. There are several problems with Excel dates: (1) Dates are not stored as a separate data type; they are stored as floating point numbers and you have to rely on (a) the "number format" applied to them in Excel and/or (b) knowing which cells are supposed to have dates in them. This module helps with (a) by inspecting the format that has been applied to each number cell; if it appears to be a date format, the cell is classified as a date rather than a number. Feedback on this feature, especially from non-English-speaking locales, would be appreciated. (2) Excel for Windows stores dates by default as the number of days (or fraction thereof) since 1899-12-31T00:00:00. Excel for Macintosh uses a default start date of 1904-01-01T00:00:00. The date system can be changed in Excel on a per-workbook basis (for example: Tools -> Options -> Calculation, tick the "1904 date system" box). This is of course a bad idea if there are already dates in the workbook. There is no good reason to change it even if there are no dates in the workbook. Which date system is in use is recorded in the workbook. A workbook transported from Windows to Macintosh (or vice versa) will work correctly with the host Excel. When using this module's xldate_as_tuple function to convert numbers from a workbook, you must use the datemode attribute of the Book object. If you guess, or make a judgement depending on where you believe the workbook was created, you run the risk of being 1462 days out of kilter. Reference: http://support.microsoft.com/default.aspx?scid=KB;EN-US;q180162 (3) The Excel implementation of the Windows-default 1900-based date system works on the incorrect premise that 1900 was a leap year. It interprets the number 60 as meaning 1900-02-29, which is not a valid date. Consequently any number less than 61 is ambiguous. Example: is 59 the result of 1900-02-28 entered directly, or is it 1900-03-01 minus 2 days? The OpenOffice.org Calc program "corrects" the Microsoft problem; entering 1900-02-27 causes the number 59 to be stored. Save as an XLS file, then open the file with Excel -- you'll see 1900-02-28 displayed. Reference: http://support.microsoft.com/default.aspx?scid=kb;en-us;214326 which I quote here because the answer to your question is likely to be wrong unless you take that into account. So to put this into code would be something like: import datetime import xlrd book = xlrd.open_workbook("myfile.xls") sheet = book.sheet_by_index(0) cell = sheet.cell(5, 19) # type, <class 'xlrd.sheet.Cell'> if sheet.cell(5, 19).ctype == 3: # 3 means 'xldate' , 1 means 'text' ms_date_number = sheet.cell_value(5, 19) # Correct option 1 ms_date_number = sheet.cell(5, 19).value # Correct option 2 year, month, day, hour, minute, second = xlrd.xldate_as_tuple(ms_date_number, book.datemode) py_date = datetime.datetime(year, month, day, hour, minute, nearest_second) which gives you a Python datetime in py_date that you can do useful operations upon using the standard datetime module. I've never used xlrd, and my example is completely made up, but if there is a myfile.xls and it really has a date number in cell F20, and you aren't too fussy about precision as noted above, this code should work.
__label__pos
0.776246
Hello there, I was editing an entity form and an error message popped up (sorry I cannot remember exactly what it was as I closed out of it fairly quickly - something about a database object). After that error screen popped up every time I try to load backdrop it cannot connect, it keeps trying to connect but never does. I have some other endpoints on the same server and they work fine it just appears to be everything in the backdrop directory is unresponsive. Anyone have anything they think might be the issue here? Any help is greatly appreciated. Accepted answer I figured it out, I will post the solution here for posterity: I ran out of storage space on the vm that was hosting my site, so the mysql server couldn't start. Added some space, partitioned it, extended the file space available to /tmp/ and it works like a charm now. Comments Do you terminal access with bee or drush to clear all caches? I figured it out, I will post the solution here for posterity: I ran out of storage space on the vm that was hosting my site, so the mysql server couldn't start. Added some space, partitioned it, extended the file space available to /tmp/ and it works like a charm now.
__label__pos
0.859534
Python 采用马青公式计算圆周率Pi(π) 3,339次阅读 共计 608 个字符,预计需要花费 2 分钟才能阅读完成。 马青公式:马青公式由英国天文学教授约翰·马青 (John Machin ,1686 –1751) 于 1706 年发现。马青公式每计算一项可以得到 1.4 位的十进制精度。因为它的计算过程中被乘数和被除数都不大于长整数,所以可以很容易地在计算机上编程实现。 根据提示输入要计算的长度,计算完成自动生成 pai.txt 文件,要多长有多长。 经过测试在博主笔记本上生成 10w 位大概需要 13 秒左右。 # -*- coding: utf8 -*- import time def comput(): n =int(input('请输入要计算的长度:')) start_time = time.time() w = n+10 b = 10**w x1 = b*4//5 x2 = b// -239 he = x1+x2 n *= 2 for i in range(3,n,2): x1 //= -25 x2 //= -57121 x = (x1+x2) // i he += x pai = he*4 pai //= 10**10 end_time = time.time() run_time = str(end_time - start_time) paistr=str(pai) paistr=paistr[:1] + '.' + paistr[1:] f=open('pai.txt','w') f.write(paistr) f.close() print ('运行时间:' + run_time) #print ('计算结果:',pai) print ('\n'*1) comput() comput() Python 采用马青公式计算圆周率 Pi(π) 正文完   Blood.Cold 版权声明:本站原创文章,由 Blood.Cold 2019-10-06发表,共计608字。 转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
__label__pos
0.958502
JFileChooser with extensions Mickeys Mickeys used Ask the Experts™ on I am trying to just be able to save and open files with the extenstion .rov. I have done like the code bellow. In the open is it possible to not be able to choose "All files" so only .rov will be in the choosing list? In the save list....the .rov is showing but when saving it dont save with that extenstion. Why? ....main class ----------------- else if(choice.equals("Open")) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new RovFilter()); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); FwReader rr = new FwReader(br); output.setText(rr.nextRomanAsInt()); } } else if(choice.equals("Save")) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new RovFilter()); int returnVal = fc.showSaveDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); FileWriter fw = new FileWriter(file); BufferedWriter bf = new BufferedWriter(fw); FwWriter fwW = new FwWriter(bf); fwW.write(output.getText()); fwW.close(); } } ------------------- util ------------------- public class Utils { public final static String rov = "rov"; /* * Get the extension of a file. */ public static String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { ext = s.substring(i+1).toLowerCase(); } return ext; } } ------------------- Filter ------------------- import java.io.File; import javax.swing.filechooser.*; public class RovFilter extends FileFilter { public boolean accept(File f) { if (f.isDirectory()) { return true; } String extension = Utils.getExtension(f); if (extension != null) { if (extension.equals(Utils.rov)) { return true; } else { return false; } } return false; } public String getDescription() { return ".rov"; } } Open in new window Comment Watch Question Do more with Expert Office EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE® Commented: >> In the open is it possible to not be able to choose "All files" so only .rov will be in the choosing list? >> JFileChooser fc = new JFileChooser(); >> fc.addChoosableFileFilter(new RovFilter()); After the above lines.. You need to do.. fc.setAcceptAllFileFilterUsed(false); Commented: To get the extension.. You need to use the fc.getFileFilter( ). getDescription( ) getSelectedFile( ) does not returns the extension Top Expert 2016 Commented: >>In the open is it possible to not be able to choose "All files" so only .rov will be in the choosing list? Should be automatic if your FileFilter is right - please post it Learn Ruby Fundamentals This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches. Top Expert 2016 Commented: >>Should be automatic if your FileFilter is right - please post it (Same goes for saving the file too) Author Commented: I have posted my filter in my main window. Author Commented: o I have only got help with one thing and that is in the save window that is is only possible to save .rov. What I still miss is that when I save my file I want it to add so it saves with ****.rov. No it only saves ***** and no extension. My gues is that it should be here: File file = fc.getSelectedFile();   (but how do I add the .rov to my file? Commented: >> but how do I add the .rov to my file? File file = fc.getSelectedFile(); file = new File(file.getAbsolutePath( ) + fc.getFileFilter( ). getDescription( )); then.. file will refer to the file with ".rov" extension.. Your file filter description will return the ".rov" Top Expert 2016 Commented: >> but how do I add the .rov to my file? Just add the extension. Doing that via getDescription would only work if the description only consisted of the extension, which wouldn't be much of a description: File file = fc.getSelectedFile(); file = new File(file.getAbsolutePath( ) + ".rov"; Open in new window Top Expert 2016 Commented: (Of course, you should probably check to see if .rov is *already* the extension) Top Expert 2016 Commented: >>I have posted my filter in my main window. Unfortunately it depends on code that is not here Commented: >> Doing that via getDescription would only work if the description onlyconsisted of the extension, which wouldn't be much of a description: getDescription( ) api of Filter Class in the code that is posted in the question.. According to that.. you can getDescription( ) public String getDescription() { return ".rov"; } Open in new window Top Expert 2016 Commented: >>According to that.. you can getDescription( ) Yes - i didn't see that as i'm not getting any scrollbar on the snippet window Yes, that certainly isn't "much of a description". It would probably be better to use the 'Utils.rov' thing Do more with Expert Office Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals. Start 7-Day Free Trial
__label__pos
0.6458
  Kvadratická rovnice Kvadratická funkce y=x^2 - 4x + 3 Kvadratická funkce y = x2 - 4x + 3 Kvadratická rovnice o jedné neznámé je algebraická rovnice druhého řádu ve tvaru ax^{2} + bx + c, kde a, b, c jsou reálné koeficienty. Kvadratická rovnice má v oboru reálných čísel 0, 1 nebo 2 řešení. Za předpokladu, že je koeficient a nulový, hovoříme o lineární rovnici. Kvadratická funkce je vždy popsána parabolou. Za předpokladu, že je a kladné, pak je parabola konvexní, v opačném případě je konkávní. Řešení Nejprve spočítáme diskriminant, dle vzorce D = b^{2} - 4ac Pokud je diskriminant záporný, pak rovnice nemá řešení v oboru reálných čísel. Pokud je diskriminant nulový, pak má rovnice právě jedno dvojnásobné řešení: x ={-b \\over {2a}} Pokud je diskriminant kladný, pak má rovnice dvě různá řešení: x_{1,2} = \\begin{cases} {{-b + \\sqrt D} \\over {2a}} \\\\ {{-b - \\sqrt D} \\over {2a}} \\end{cases} Příklad Zjistěte kořeny rovnice x^2 - 4x + 3 = 0. Nejprve vypočítáme diskriminant: D = b^{2} - 4ac = 4^2 - 4 \\cdot 1 \\cdot 3 = 16 - 12 = 4 Diskriminant je kladný, rovnice má dvě řešení v oboru reálných čísel. x_{1,2} = \\begin{cases} {{{-b + \\sqrt D} \\over {2a}} = {{4 + \\sqrt 4} \\over 2} = 3} \\\\ {{{-b - \\sqrt D} \\over {2a}} = {{4 - \\sqrt 4} \\over 2} = 1} \\end{cases} Kód /** * Resi kvadratickou rovnici o jedne nezname ve tvaru * ax^2 + bx + c = 0 * @param a * @param b * @param c * @return pole realnych korenu, null - pokud nema rovnice reseni v oboru * realnych cisel */ public static double[] solveQuadraticEquation(double a, double b, double c) { double d = b*b - 4*a*c; //diskriminant if(d < 0) { return null; } else if (d == 0) { double[] result = {-b/2*a}; return result; } else { double[] result = {(-b + Math.sqrt(d))/(2*a), (-b - Math.sqrt(d))/(2*a)}; return result; } } /** * Resi kvadratickou rovnici o jedne nezname ve tvaru * ax^2 + bx + c = 0 * @param a * @param b * @param c * @return pole realnych korenu, null - pokud nema rovnice reseni v oboru * realnych cisel */ public static double[] SolveQuadraticEquation(double a, double b, double c) { double d = b * b - 4 * a * c; //diskriminant if (d < 0) { return null; } else if (d == 0) { double[] result = { -b / 2 * a }; return result; } else { double[] result = { (-b + Math.Sqrt(d)) / (2 * a), (-b - Math.Sqrt(d)) / (2 * a) }; return result; } } /** Autor: Vaclav Kejr */ public Complex[] Kvadraticka(double[] polynom) { try { // Výpočet kvadratické rovnice. Complex koren1 = new Complex(); Complex koren2 = new Complex(); Complex[] koreny = new Complex[2]; double real1 = 0.0; double real2 = 0.0; double imag1 = 0.0; double imag2 = 0.0; double disc = 0.0; const double epsilon = 1E-14; if (Math.Abs(polynom[1]) > epsilon && Math.Abs(polynom[2]) > epsilon) { disc = Math.Pow(polynom[1], 2) - 4.0 * polynom[0] * polynom[2]; if (disc > 0 && disc > epsilon) { real1 = (-polynom[1] + Math.Sqrt(disc)) / (2.0 * polynom[0]); real2 = (-polynom[1] - Math.Sqrt(disc)) / (2.0 * polynom[0]); imag1 = 0.0; imag2 = imag1; koren1 = new Complex(real1, imag1); koren2 = new Complex(real2, imag2); } else if (disc < 0 && Math.Abs(disc) > epsilon) { // Reálná část komplexně sdruženého kořene. real1 = -polynom[1] / (2.0 * polynom[0]); real2 = -polynom[1] / (2.0 * polynom[0]); // Imaginární část komplexně sdruženého kořene. imag1 = Math.Sqrt(Math.Abs(disc)) / (2.0 * polynom[0]); imag2 = -Math.Sqrt(Math.Abs(disc)) / (2.0 * polynom[0]); koren1 = new Complex(real1, imag1); koren2 = new Complex(real2, imag2); } else if (disc > 0 && disc <= epsilon) { real1 = -polynom[1] / (2.0 * polynom[0]); real2 = real1; imag1 = 0.0; imag2 = imag1; koren1 = new Complex(real1, imag1); koren2 = new Complex(real2, imag2); } else if (disc < 0 && Math.Abs(disc) <= epsilon) { real1 = 0.0; real2 = real1; imag1 = -polynom[1] / (2.0 * polynom[0]); imag2 = imag1; koren1 = new Complex(real1, imag1); koren2 = new Complex(real2, imag2); } } else { throw new ArgumentException("Koeficienty polynomu jsou příliš malé !", polynom[1].ToString()); } koreny[0] = koren1; koreny[1] = koren2; return koreny; } catch (Exception ex) { Console.WriteLine(ex.ToString()); Complex[] koreny = new Complex[2]; return koreny; } } /** * Kvadraticka rovnice o jedne nezname ve tvaru ax^2 + bx + c = 0 * @param $a * @param $b * @param $c * @return pole realnych korenu, NULL - pokud nema rovnice reseni v oboru realnych cisel * @author Thomas (www.adamjak.net) */ function solve_quadratic_equation($a, $b, $c){ $d = $b*$b - 4*$a*$c; //diskriminant if($d < 0) { return NULL; } else if ($d == 0){ $result = (-$b/2*$a); return $result; } else { $result = ((-$b + sqrt($d))/(2*$a) . (-$b - sqrt($d))/(2*$a)); return $result; } } www.EuAutodily.cz SEO od společnosti Digital Pylon Online casino s algoritmem České casino online online slot-vegas.cz Zajímavé články: Jak najít práci snů? Zvolte kariéru v IT!, Češi mají rádi hrací automaty online, Jak funguje algoritmické obchodování Casino, Online výuka Algoritmus a online marketing mají svá pravidla, Automaty, Matematický vliv, Ratings, Jak fungují algoritmy hazardních her online: více znalostí, více peněz, SYPWAI - nástroj pro vědecký vývoj, Vynikají na globálním trhu: Nejlepší vývojáři softwaru pro online výherní automaty, Jak si vybrat nejlepší české online casino, Proč byste měli hrát online casino VPN revoluce
__label__pos
0.998928
Localist Community Event Platform API Overview The Localist API is a simple HTTP-based interface. Standard HTTP calls will return JSON your application can use. It stands to reason that Localist’s API is the most powerful calendar API in the world (muahahah!). Your use and access to the API is expressly conditioned on your compliance with the policies, restrictions and other provisions related to the API set forth in our API Terms of Use and the other documentation we provide you. You must also comply with the restrictions set forth in the Localist Terms of Service and the Localist Privacy Policy, in all uses of the API. If Localist believes that you have or attempted to violate any term, condition or the spirit of these policies or agreements, your right to access and use the API may be temporarily or permanently revoked. The Localist API is currently read-only. Usage All the resources described are available under http://CALENDAR-URL/api/2/. A simple HTTP GET request can be made to retrieve results. Requests that change data require a HTTP POST or HTTP PUT. Requests that remove data require a HTTP DELETE. Note: All examples need to have your calendars’s URL in place of the CALENDAR-URL placeholder. For instance, if your calendar is at http://calendar.example.edu, the API is located at http://calendar.example.edu/api/2/. Important: http://CALENDAR-URL/api/2/ is the starting point of the API. It will not return anything on its own. The API needs to know what type of content to return, which is outlined in the Resources section. Versioning The API has a version number, currently 2.1. The minor version is incremented whenever we make changes to either the parameters or output that are incompatible or may require special attention. When possible, new resources, parameters and response fields are made available to all versions. You can request a specific version of the API parameters and responses by using the full version in the path, instead of “2”. For example, to access the original API 2 release, you can use a URL of http://CALENDAR-URL/api/2.0/. Using http://CALENDAR-URL/api/2/ will give you the current version. When a new version of the API is launched, this endpoint will continue to serve the prior version for a short period of time, allowing time for clients to update. The changes in each revision can be found in the recent changes section and are also documented with the associated resources. Usage Limits There are currently no publicly defined usage limits on the API. However, be considerate when using the API and do not rapidly issue many requests, as well as caching data when possible (especially for less-frequently updated resources). Definitions of what is a “considerate” level of requests is outlined in the Localist license. We reserve the right to block offending hosts and/or applications to preserve the performance and stability of Localist. All requests should either be OAuth signed or include identifying information in the User Agent. API Terms of Use Certain terms which are capitalized herein and not otherwise defined, have the meaning set forth in the Localist Terms of Service. Your subscription to the Service enables you to access and use the API, including to develop and implement web and software services, scripts and applications (“Localist Applications”) for use in connection with your subscription to the Service for your internal business purposes in accordance with the Localist Terms of Service. Localist also permits you to publish Localist Applications and make them available to third parties subject to you entering into and complying with the Localist Application Developer and API Agreement. In order to use and access the API, you must be an active Localist Enterprise Licensee. Your agreement is the only means through which you are authorized to access the API. Except as expressly permitted pursuant to a Localist Application Developer and API Agreement to which you are a party to, you may not use or access the API to obtain access to or extract any data stored or transmitted through the Service other than Your Content or to input data from any external source into the Service other than to your Account. You may not use the API to substantially replicate products or services offered by Localist, including, without limitation, functions or clients on platforms (such as iOS or Android) where Localist offers its own client or function. Localist Applications may not use or access the API or the Service in order to monitor the availability, performance, or functionality of any of the API or Service or for any similar benchmarking purposes. You may not, under any circumstances, through a Localist Application or otherwise, repackage or resell the Service or API. You are not permitted to use or access the API in any manner that does or could potentially undermine the security of the Service, the API or any data or information stored or transmitted using the Service. You may not (i) interfere with, modify or disable any features, functionality or security controls of the Service or the API: (ii) defeat, avoid, bypass, remove, deactivate or otherwise circumvent any protection mechanisms for the Service or the API; or (iii) reverse engineer, decompile, disassemble or derive source code, underlying ideas, algorithms, structure or organizational form from the Service or the API. You are solely responsible (and Localist has no responsibility or liability of any kind), for the content, development, operation, or maintenance of Localist Applications. Without limiting the foregoing, you will be solely responsible for (i) the technical installation and operation of your Localist Applications; (ii) creating and displaying information and content on, through or within your Localist Applications; (iii) ensuring that your Localist Applications do not violate or infringe the Intellectual Property Rights of any third party; and (iv) ensuring that your Localist Applications do not contain or introduce Malicious Software into the Service, the API, or any data stored or transmitted using the Service. You must respect and comply with the technical and policy-implemented limitations of the API and the restrictions Localist designs or informs you of in accessing or using the API or designing and implementing Localist Applications. Without limiting the foregoing, you may not violate any explicit rate limitations on calling or otherwise utilizing the API. To the extent you develop or implement Localist Applications that transmit or otherwise use or access the API to transmit Your Content outside the Service, you will be responsible for any required notification to or consent of Agents or End Users that their data will be transmitted outside the Service. Localist is not responsible for the privacy, security or integrity of Your Content to the extent it is transmitted outside the Service by you or your Localist Applications using the API. Recent Changes March 14, 2018 Released API version 2.2. • Events • Changed group_id output to groups • Changed deparment_id output to departments August 14, 2017 • Added for option to the event list method July 6, 2017 • Added updated_at attribute, updated_before and updated_after parameters to attendances. February 14, 2017 • Added attendances endpoints to the API • Added authentication section October 4, 2016 • Added localist_ics_url attribute to event output March 22, 2016 • Added allows_attendance attribute to event output • Clarified start and end range behavior on event methods • Documented recurring option on event list method January 14, 2016 • Added statistics endpoints to the API October 8, 2013 Released API version 2.1. • General • Added access to places, groups, departments and photos • Made HTML descriptions available in responses (starting with version 2.1) • Increased maximum page size to 100 • Added direction parameter to control sort order • Events • Added exclude_type option to list and search methods • Added created_before and created_after options to list method • Added match option to list method • Added sort options created and updated • Added photo_id and detail_views attributes to output July 2, 2013 • Added all_custom_fields option to APIv2 event list and event search methods. June 20, 2013 • Added ticket_url and ticket_cost fields to APIv2 event output. May 8, 2013 • Added featured field to APIv2 event output. May 7, 2013 • Added featured option to APIv2 event list method. May 1, 2013 • Added all_custom_fields option to APIv2 event methods. October 1, 2012 • Added require_all option to APIv2 event list method. September 27, 2012 • Added created_by and updated_by fields to APIv2 event output. July 16, 2012 • Added group_name and department_name fields to APIv2 event output. Authentication Authentication is optional to read data from the API. However, a subset of OAuth 2 is supported for access private data. Calendar administrators must generate access tokens via the admin dashboard; there is no “authorize this app” support at this time. Most API methods support anonymous access. If authentication is required, an anonymous request will return a response with the 401 status code, with a JSON object in the body describing the error. See the response errors section for further details. Some requests require additional scopes, which grant the access token elevated permissions to access data. A list of the scopes is available below. Making an Authenticated Request All requests including an access token must be made over HTTPS. A request can provide an access token using one of two methods: 1. By using the Authorization request header, specifying the Bearer scheme and the access token: Authorization: Bearer your_access_token 2. By providing the access token as the value of the access_token request parameter: https://CALENDAR-URL/api/2/events?access_token=your_access_token Getting Access Tokens A calendar administrator must generate the access tokens via the admin dashboard, however they can be assigned to any user on the calendar. Each access token is associated with an app, which is also managed via the admin dashboard. To get an access token, you must create an app and then an access token. In the admin dashboard, app management can be accessed from the “Apps” item under the “Settings” menu. Creating an App 1. From the admin dashboard, choose “Apps” from the “Settings” menu. 2. Choose “+ Add App” 3. Provide a name and URL for the new app. Both fields are required. 4. Click “Save Changes” Creating and Viewing Access Tokens From app management, either create an app as described above or choose an existing app, and click the “Access Tokens” button in the status bar. A list of access tokens for the chosen app are shown, along with the associated user, scopes, and expiration time. Once created, an access token can only be revoked by clicking the red “X” button next to it. To create an access token, click “+ Create Access Token” above the listing. Select a user by email address, and if desired set an expiration date and appropriate scopes, then click “Create Token”. The created access token will then be displayed, and can immediately be used for the API. Authentication Scopes All access tokens have access to event data. When an access token is provided, the request acts as if a user is logged in, providing access to events marked as “Visible Only when Logged In”. To access attendance or user data, the access token must be authorized with additional scopes: Scope Description users Allows access to user information except email addresses user_emails Allows access to user email addresses attendances Allows access to attendances data and endpoints Basic Concepts Response Format All responses are in JSON format. When representing an object, it is formatted as a hash with one element, with the key of the object type, and the value being a hash of the attributes of the object. For example, a event is represented like this: { "event": { "id": 1, "name": "My Event", // other attributes } } Fields with a missing or blank value are not gauranteed to be present in the response. Your code should handle this situation, as the inclusion of empty fields in the response may change at any time. Response Codes The success or failure of the request is indicated using the HTTP status codes. In general, a 2xx code indicates success, while a 4xx code indicates failure. Code Description 200 Response succeded 400 Error handling request 401 Authentication error 403 Forbidden 404 Not found 500 Internal Localist error Response Errors Error responses (4xx status codes) contain an error hash in the body with the error message and code. For example: { "status": "error", "request": "/api/2/events/123", "error": "Not Found: Couldn't find Event with id=123", "code": "not_found" } The error attribute contains an error message. The code attribute contains a string indicating the type of error: Code Description access_denied This resource is not visible to the current user argument_error An option provided contains an invalid format or value not_found The resource requested does not exist required_argument_missing A required option was not specified authentication_required A valid access token is required to complete the request expired_access_token The access token provided has expired invalid_access_token The access token provided is not valid oauth2_not_supported Returned when an access token is used with a non-HTTPS request missing_scope The access token provided does not have the proper scope for this resource Note: Responses with codes 403, 404 and 500 may return a HTML body instead of JSON. Your client should be prepared to handle this. Geo Info Contains structured geographic information, usually representing a specific point. Any or all of these elements may be missing if the address was not recognized. { "city": "Ithaca", "country": "US", "latitude": 42.4425, "longitude": -76.4857, "state": "NY", "street": "430 College Ave", "zip": "14850" } Attribute Description city City portion of address country Country portion of address latitude Latitude of address longitude Longitude of address state State portion of address street Street portion of address zip Postal code of address Paging Contains information about result set paging, including the total number of pages. Page numbers start at 1. { "current": 1, "size": 10, "total": 1 } Attribute Description current Page number of the returned results size Number of results per page total Total number of pages Filters Represents the assigned filter items on an object. An object can have multiple filter types (such as “Event Type” or “Department”), each of which can have multiple filter items assigned. You can use the appropriate labels method on a resource to retrieve the displayed names of the filter types and custom fields. The hash’s keys represent the filter types that are assigned, with the value being an array of the assigned filters. { "departments": [ { "id": 4859, "name": "School of Continuing Education and Summer Sessions" } ], "event_types": [ { "id": 4262, "name": "Music" } ] } Attribute Description id ID of the filter item, used with the type parameter when requesting resource listings name The label of the filter item Recent Activity Recent activity covers three types of objects representing the content that can be posted by a user: comments, reviews, and photos. Not all types are available on all objects. The recent activity result is a mixed array of the three types. In addition, there are two common result attributes among the responses, user and on. User Contains information about the user who posted the item. { "id": 12345, "photo_url": "http://images.localist.com/images/main/person_huge.png", "profile_url": "http://example.localist.com/johndoe", "visible_name": "John Doe" } Attribute Description id The user’s ID photo_url URL to the user’s profile photo profile_url URL to the user’s profile page on Localist visible_name The name of the user, suitable for display On Identifies what object the review or comment was posted to. Since a photo can be associated with multiple objects, it does not contain this information. { "id": 73502, "type": "event" } Attribute Description id The ID of the object type The type of the object (event, photo, business or user) Comment Represents a comment posted by a user. { "comment": { "body": "Will this event be live on the Web?", "created_at": "2012-04-19T13:35:50Z", "id": 1422, "on": { "id": 73502, "type": "event" }, "updated_at": "2012-04-19T13:35:50Z", "user": { "id": 12345, "photo_url": "http://images.localist.com/images/main/person_huge.png", "profile_url": "http://example.localist.com/johndoe", "visible_name": "John Doe" }, "when": "2012-04-19T09:35:50Z" } } Attribute Description body The comment text id ID of the comment on Object the comment was posted on user User who posted the comment when Timestamp when the comment was posted Review Represents a review posted by a user. Identical to a comment with the addition of the rating key. { "review": { "body": "It was great fun to see Venus directly in front of the sun.", "created_at": "2012-06-06T18:50:25Z", "id": 1443, "on": { "id": 76119, "type": "event" }, "rating": 1, "updated_at": "2012-06-06T18:50:25Z", "user": { "id": 12345, "photo_url": "http://images.localist.com/images/main/person_huge.png", "profile_url": "http://example.localist.com/johndoe", "visible_name": "John Doe" }, "when": "2012-06-05T00:00:00Z" } } Attribute Description body The review text id ID of the review on Object the review was posted on rating The user’s rating: -1 for a negative review, 0 for a neutral review, or 1 for a positive review user User who posted the review when Timestamp when the review was posted Photo Represents a photo entry in a recent activity list. Since a photo can be associated with multiple objects, the on data is not provided. Note: This is a slightly different format than the photo resource returns, as it includes more context for a recent activity listing. { "photo": { "caption": "", "id": 626, "photo_url": "http://images.localist.com/photo/000/000/626/huge/jSNHHDAb_6Yp1_Li.jpg?1339699432", "updated_at": "2012-06-14T18:43:52Z", "user": { "photo_url": "http://images.localist.com/images/main/person_huge.png", "profile_url": "http://example.localist.com/johndoe", "visible_name": "John Doe" }, "when": "2012-06-14T18:43:52Z" } } Attribute Description caption The photo caption id The photo’s ID photo_url URL to the photo’s image user User who posted the photo when Timestamp when the photo was posted Resources Describes the available resources, their response formats, and associated methods. Variables in resource URLs are listed in all capital letters. Note: All output samples have been reformatted for clarity, and some responses and values have been truncated. Organizations An organization is the root level that all content is attached to. A calendar always has one organization. Format { "organization": { "id": 55, "name": "WTMD", "urlname": "wtmd", "description": null, "time_zone": "Eastern Time (US & Canada)", "photo_id": null, "localist_url": "http://events.wtmd.org/", "photo_url": "http://images-cf.localist.com/assets/main/person_huge-10cb90..." } } Attribute Description description The organization’s description id The organization’s ID (this is referenced as school_id in other resources) localist_url URL to the organization’s page on Localist name The organization’s name photo_id ID of the organization’s photo, if set photo_url URL to the organization’s photo time_zone The organization’s time zone urlname The organization’s URL slug List Resource: GET /organizations Returns a paged listing of organizations on this calendar. Parameter Type Description Default page number Page number, starting from 1 1 pp number Number of items per page (max 100) 10 Example Request: GET http://CALENDAR-URL/api/2/organizations { "organizations": [ { "organization": { "id": 55, "name": "WTMD", "urlname": "wtmd", "description": null, "time_zone": "Eastern Time (US & Canada)", "photo_id": null, "localist_url": "http://events.wtmd.org/", "photo_url": "http://images-cf.localist.com/assets/main/person_huge-10cb90..." } } ], "page": { "current": 1, "size": 10, "total": 1 } } Get Resource: GET /organizations/ORGANIZATION_ID Retrieve details about one organization. Example Request: GET http://CALENDAR-URL/api/2/organizations/55 { "organization": { "id": 55, "name": "WTMD", "urlname": "wtmd", "description": null, "time_zone": "Eastern Time (US & Canada)", "photo_id": null, "localist_url": "http://events.wtmd.org/", "photo_url": "http://images-cf.localist.com/assets/main/person_huge-10cb90..." } } Communities List Resource: GET /organizations/ORGANIZATION_ID/communities Returns a paged listing of the communities associated with this organization. Example Request: GET http://CALENDAR-URL/api/2/organziations/11/communities { "communities": [ { "community": { "id": 62, "name": "Sacramento", "urlname": "sacramento", "description": "", "time_zone": "Pacific Time (US & Canada)", "photo_id": null, "school_id": 11, "localist_url": "https://calendar.pacific.edu/sacramento", "photo_url": "https://d3e1o4bcbhmj8g.cloudfront.net/assets/main/person_hug..." } } ], "page": { "current": 1, "size": 10, "total": 1 } } Communities A community represents a separate location within an organization, such as a college campus, association chapter, or regional market. Format { "community": { "id": 62, "name": "Sacramento", "urlname": "sacramento", "description": "", "time_zone": "Pacific Time (US & Canada)", "photo_id": null, "school_id": 11, "localist_url": "https://calendar.pacific.edu/sacramento", "photo_url": "https://d3e1o4bcbhmj8g.cloudfront.net/assets/main/person_hug..." } } Attribute Description description The community’s description id The community’s ID (this is referenced as campus_id in other resources) localist_url URL to the community’s page on Localist name The community’s name photo_id ID of the community’s photo, if set photo_url URL to the community’s photo school_id The organization this community belongs to time_zone The community’s time zone urlname The community’s URL slug List Resource: GET /organizations/ORGANIZATION_ID/communities Returns a paged listing of communities in the specified organization. Parameter Type Description Default page number Page number, starting from 1 1 pp number Number of items per page (max 100) 10 Example Request: GET http://CALENDAR-URL/api/2/organizations/11/communities { "communities": [ { "community": { "id": 62, "name": "Sacramento", "urlname": "sacramento", "description": "", "time_zone": "Pacific Time (US & Canada)", "photo_id": null, "school_id": 11, "localist_url": "https://calendar.pacific.edu/sacramento", "photo_url": "https://d3e1o4bcbhmj8g.cloudfront.net/assets/main/person_hug..." } } ], "page": { "current": 1, "size": 10, "total": 1 } } Get Resource: GET /organizations/ORGANIZATION_ID/communities/COMMUNITY_ID Retrieve details about one community. Example Request: GET http://CALENDAR-URL/api/2/organizations/11/community/62 { "community": { "id": 62, "name": "Sacramento", "urlname": "sacramento", "description": "", "time_zone": "Pacific Time (US & Canada)", "photo_id": null, "school_id": 11, "localist_url": "https://calendar.pacific.edu/sacramento", "photo_url": "https://d3e1o4bcbhmj8g.cloudfront.net/assets/main/person_hug..." } } Events These resources provide access to information about events. Format { "event": { "id": 188155, "title": "Amy Sherald: Paintings", "url": "http://www.rflewismuseum.org/exhibitions/special", "updated_at": "2015-08-14T17:23:33-04:00", "created_at": "2013-08-26T02:26:44-04:00", "facebook_id": null, "first_date": "2013-09-14", "last_date": "2013-12-29", "hashtag": "", "urlname": "amy_sherald_paintings", "user_id": 52182, "directions": "", "allows_reviews": true, "allows_attendance": true, "location": "Reginald F. Lewis of Maryland African American History and C...", "room_number": "", "location_name": "Reginald F. Lewis of Maryland African American History and C...", "created_by": null, "updated_by": null, "city_id": 1, "neighborhood_id": 58, "school_id": 55, "campus_id": null, "recurring": true, "free": true, "private": false, "verified": true, "rejected": false, "sponsored": false, "venue_id": null, "ticket_url": "", "ticket_cost": "", "keywords": [ ], "tags": [ ], "description_text": "Known for her life-sized fantastical portraits of African Am...", "photo_id": 76525, "detail_views": 316, "address": "830 E. Pratt St. Baltimore, MD 21202", "description": "<p class=\"description\">Known for her life-sized fantastical ...", "featured": true, "geo": { "latitude": "39.287266", "longitude": "-76.603813", "street": "830 East Pratt Street", "city": "Baltimore", "state": "MD", "country": "US", "zip": "21202" }, "filters": { "event_types": [ { "name": "Arts & Culture", "id": 20196 } ] }, "custom_fields": { }, "localist_url": "http://events.wtmd.org/event/amy_sherald_paintings", "photo_url": "http://images-cf.localist.com/photos/76525/huge/195a2ae18388...", "venue_url": null, "event_instances": [ { "event_instance": { "id": 452831, "ranking": 0, "event_id": 188155, "start": "2013-09-14T10:00:00-04:00", "end": "2013-09-14T17:00:00-04:00", "all_day": false } } ] } } Attribute Description address The address of the event allows_attendance true if user attendance is enabled on this event, false otherwise allows_reviews true if user activity (comments, reviews and photos) is enabled on this event, false otherwise attendees Array of the event’s attendees campus_id The community the event is assigned to created_at Timestamp of the event’s creation created_by ID of the user who initially submitted this event, or null if added through an external feed or CSV custom_fields Hash of custom fields set on the event. The key is the “unique identifier” of the field, with the value being the field’s value. department_id What department group this event belongs to (for calendars with advanced department functionality only) before v2.2 department_name Name of the department group represented by department_id (for calendars with advanced department functionality only) before v2.2 departments An array of what department groups this event belongs to (for calendars with advanced department functionality only) since v2.2 description_text Plain-text version of the event’s description since v2.1 description The event’s description, including HTML since v2.1 description The event’s plain-text description before v2.1 directions Directions to the event’s location event_instances Array of instances for this event facebook_id ID of associated event on Facebook featured true if the event is featured, false otherwise filters Hash of filters set on the event. The key is the filter’s identifier, the value is an array of filter items for each assigned value. first_date The date of the earliest instance free true if the event is free geo Hash of geographical information group_id ID of group assigned to the event before v2.2 group_name Name of group assigned to the event before v2.2 groups An array of groups assigned to the event since v2.2 hashtag The event’s hashtag id ID of the event (used as event_id in other resources) keywords Array of keywords assigned to the event last_date The date of the latest instance localist_ics_url URL to the iCalendar file for the event localist_url URL to the event’s page on Localist location_name Appropriate label for showing the location (either the place name or the location field) location Custom location assigned to the event (will be blank if a place is assigned) photo_id ID of the assigned photo photo_url URL of the assigned photo private always false recurring true if the event is recurring (has more than 5 instances) rejected true if the event has been rejected room_number Room number school_id The organization this event is assigned to sponsored true if the event is marked as sponsored tags Array of tags assigned to the event ticket_cost Ticket cost ticket_url Ticket URL title Name of the event updated_at Timestamp of the event’s last update (does not necessarily indicate updates to the event’s visible details) updated_by ID of the last user to edit the event (may be null, does not necessarily indicate updates to the event’s visible details) url External URL assigned to the event urlname URL slug of the event (used in URLs) user_id ID of the event’s owner. May be null and does not necessarily represent the submitter. venue_id ID of the associated place venue_url URL of the place’s page on Localist verified true if the event is verified Event Instance Format Represents information about one specific instance of an event. The attendance and num_attending attributes may not be present. { "event_instance": { "attending": "none", "num_attending": 0, "id": 237631, "ranking": 0, "event_id": 81300, "start": "2013-09-14T21:00:00-04:00", "end": null, "all_day": false } } Attribute Description all_day true if the event is all day (has no start time) attending The current user’s attendance status (attending, watching, or none) end Timestamp of the instance’s end, or null if not specified event_id ID of event this instance belongs to id ID of this event instance num_attending Number of attendees ranking Relative ranking of the event instance’s popularity, from 0-100 start Timestamp of the instance start Note: The start timestamp always includes a time, even if none was specified on the event. The all_day flag will be true if there is no defined start time. List Resource: GET /events Returns a paged list of events. Without any additional parameters, only events occurring today are returned. The result hash includes an array of event objects in the events key, a date key describing the date range returned, and a page key with paging information. Locality Parameters These parameters restrict the results based on location. Parameter Type Description Default bounds string Return events within this bounding box The bounding box is specified as: swlat,swlng,nelat,nelng   campus_id number The community to return events for all communities near string The latitude and longitude, separated by commas, to search near   units string Units (mi or km) to use with within mi within number Return events within this many units of near 10 Date Parameters Control the range of events to return. All dates should be specified as YYYY-MM-DD (2013-09-20). The maximum date range supported is 365 days. Longer ranges will be truncated to 365 days from start. The range defined by start and end does not include the date specified in end. Parameter Type Description Default days number Return events within this many days after start Cannot be used with end 1 end date End of range   start date Start of range today Page Parameters Specifies the size and offset of the results. Parameter Type Description Default page number Page number of results to return, starting with 1 1 pp number Number of events to return per page (1-100) 10 Filter Parameters Restrict the returned events based on filter items, tags and keywords assigned. To specify multiple values for type, keyword or exclude_type, the parameter may be repeated with brackets ([]) after the name. For instance, to request both keyword kw1 and kw2, use a URL similar to: http://CALENDAR-URL/api/2/events?keyword[]=kw1&keyword[]=kw2. Parameter Type Description Default created_after date Only return events created after this date   created_before date Only return events created before this date   exclude_type number Do not return events with these filter item IDs   featured boolean Only return featured events when true false for string Apply event visibility as if the request came from the specified type of page When main, return events as if viewing the calendar homepage or “All Events” calendar When widget, return events as if viewing a widget When channel, return events as if viewing a channel or its calendar When other, return events as if viewing any other page (the default) other group_id number The group or department group to return events for all groups keyword string Limit to events with specified keywords or tags   match string Control matching requirements for venue_id, group_id, type and keyword When not specified, matches events that have at least one listed type, one listed keyword, one listed venue_id, and one listed group_id When all, matches events that have all the listed types and keywords, along with one listed venue_id and one listed group_id When any, matches events that have at least one of the listed types or keywords or venue_ids or group_ids When or, matche sevents that have at least one listed type and one listed keyword, along with one listed venue_id or group_id   recurring boolean When specified, return events which are (true) or are not (false) recurring.   require_all boolean deprecated, acts as match=all when true false sponsored boolean Only return events marked as sponsored if true false type number Limit events to filter item IDs   venue_id number The place to return events for all places Output Parameters Note: Sorting by distance is only supported when near is specified. Parameter Type Description Default all_custom_fields boolean Include all custom fields in the result when true. By default, only fields visible on the event detail page are returned. false direction string Change sort order, asc or desc varies distinct boolean Only return the first matching instance of an event when true false include_attendance boolean Include user’s attendance status in the result Must be an authenticated request false sort string Sort results by date: event start name: event name ranking: event popularity distance: distance from near created: event creation timestamp updated: event update timestamp date Example Request: GET http://CALENDAR-URL/api/2/events { "events": [ { "event": { "event_instances": [ { "event_instance": { "id": 1206819, "ranking": 0, "event_id": 428144, "start": "2015-09-30T00:00:00-04:00", "end": "2015-10-01T00:00:00-04:00", "all_day": false } } ], "id": 428144, "title": "FarmSprouts Preschool Program", "url": "http://www.marylandagriculture.org/farm-sprouts-preschool-pr...", "updated_at": "2015-09-30T06:00:18-04:00", "created_at": "2015-03-25T15:05:42-04:00", "facebook_id": null, "first_date": "2015-04-01", "last_date": "2015-11-18", "hashtag": "", "urlname": "maryland_agricultural_resource_council_presents", "user_id": 155267, "directions": "", "allows_reviews": true, "allows_attendance": true, "location": "The Ag Center in Cockeysville", "room_number": "", "location_name": "The Ag Center in Cockeysville", "created_by": null, "updated_by": null, "city_id": 1, "neighborhood_id": null, "school_id": 55, "campus_id": null, "recurring": true, "free": true, "private": false, "verified": true, "rejected": false, "sponsored": false, "venue_id": null, "ticket_url": "", "ticket_cost": "", "keywords": [ ], "tags": [ ], "description_text": "Maryland Agricultural Resource Council Presents FarmSprouts ...", "photo_id": 263898, "detail_views": 253, "address": "1114 Shawan Road, Cockeysville, MD 21030-1385", "description": "<p>Maryland Agricultural Resource Council Presents FarmSprou...", "featured": false, "geo": { "latitude": "39.50338", "longitude": "-76.685768", "street": "1114 Shawan Road", "city": "Cockeysville", "state": "MD", "country": "US", "zip": "21030" }, "filters": { "event_types": [ { "name": "Community", "id": 20053 } ] }, "custom_fields": { }, "localist_url": "http://events.wtmd.org/event/maryland_agricultural_resource_...", "photo_url": "http://images-cf.localist.com/photos/263898/huge/28d6ef0052c...", "venue_url": null } } ], "page": { "current": 1, "size": 10, "total": 27 }, "date": { "first": "2015-09-30", "last": "2015-10-30" } } Resource: GET /events/search Searches for events with the search term specified in search. Supports all parameters supported by event list, except for keyword, match, created_before, created_after, for. Keywords and tags are searched as part of search. Sorting by created and updated is not supported. Parameter Type Description Default search string required search terms   The response format is the same as for event list. Example Request: GET http://CALENDAR-URL/api/2/events/search?search=concert { "events": [ { "event": { "event_instances": [ { "event_instance": { "id": 1206819, "ranking": 0, "event_id": 428144, "start": "2015-09-30T00:00:00-04:00", "end": "2015-10-01T00:00:00-04:00", "all_day": false } } ], "id": 428144, "title": "FarmSprouts Preschool Program", "url": "http://www.marylandagriculture.org/farm-sprouts-preschool-pr...", "updated_at": "2015-09-30T06:00:18-04:00", "created_at": "2015-03-25T15:05:42-04:00", "facebook_id": null, "first_date": "2015-04-01", "last_date": "2015-11-18", "hashtag": "", "urlname": "maryland_agricultural_resource_council_presents", "user_id": 155267, "directions": "", "allows_reviews": true, "allows_attendance": true, "location": "The Ag Center in Cockeysville", "room_number": "", "location_name": "The Ag Center in Cockeysville", "created_by": null, "updated_by": null, "city_id": 1, "neighborhood_id": null, "school_id": 55, "campus_id": null, "recurring": true, "free": true, "private": false, "verified": true, "rejected": false, "sponsored": false, "venue_id": null, "ticket_url": "", "ticket_cost": "", "keywords": [ ], "tags": [ ], "description_text": "Maryland Agricultural Resource Council Presents FarmSprouts ...", "photo_id": 263898, "detail_views": 253, "address": "1114 Shawan Road, Cockeysville, MD 21030-1385", "description": "<p>Maryland Agricultural Resource Council Presents FarmSprou...", "featured": false, "geo": { "latitude": "39.50338", "longitude": "-76.685768", "street": "1114 Shawan Road", "city": "Cockeysville", "state": "MD", "country": "US", "zip": "21030" }, "filters": { "event_types": [ { "name": "Community", "id": 20053 } ] }, "custom_fields": { }, "localist_url": "http://events.wtmd.org/event/maryland_agricultural_resource_...", "photo_url": "http://images-cf.localist.com/photos/263898/huge/28d6ef0052c...", "venue_url": null } } ], "page": { "current": 1, "size": 10, "total": 27 }, "date": { "first": "2015-09-30", "last": "2015-10-30" } } Get Resource: GET /events/EVENT_ID Returns details about the event specified by event_id. If requested, attendees will be included in an attendees attribute, recent activity will be in an recent_activity attribute and attendance info will be on the event instance. Parameter Type Description Default all_custom_fields boolean Include all custom fields in the result when true. By default, only fields visible on the event detail page are returned. false include_activity boolean Include recent activity feed false include_attendance boolean Include user’s attendance status in the result Must be an authenticated request false include_attendees boolean Include attendee list in the result false Example Request: GET http://CALENDAR-URL/api/2/events/188155 { "event": { "id": 188155, "title": "Amy Sherald: Paintings", "url": "http://www.rflewismuseum.org/exhibitions/special", "updated_at": "2015-08-14T17:23:33-04:00", "created_at": "2013-08-26T02:26:44-04:00", "facebook_id": null, "first_date": "2013-09-14", "last_date": "2013-12-29", "hashtag": "", "urlname": "amy_sherald_paintings", "user_id": 52182, "directions": "", "allows_reviews": true, "allows_attendance": true, "location": "Reginald F. Lewis of Maryland African American History and C...", "room_number": "", "location_name": "Reginald F. Lewis of Maryland African American History and C...", "created_by": null, "updated_by": null, "city_id": 1, "neighborhood_id": 58, "school_id": 55, "campus_id": null, "recurring": true, "free": true, "private": false, "verified": true, "rejected": false, "sponsored": false, "venue_id": null, "ticket_url": "", "ticket_cost": "", "keywords": [ ], "tags": [ ], "description_text": "Known for her life-sized fantastical portraits of African Am...", "photo_id": 76525, "detail_views": 316, "address": "830 E. Pratt St. Baltimore, MD 21202", "description": "<p class=\"description\">Known for her life-sized fantastical ...", "featured": true, "geo": { "latitude": "39.287266", "longitude": "-76.603813", "street": "830 East Pratt Street", "city": "Baltimore", "state": "MD", "country": "US", "zip": "21202" }, "filters": { "event_types": [ { "name": "Arts & Culture", "id": 20196 } ] }, "custom_fields": { }, "localist_url": "http://events.wtmd.org/event/amy_sherald_paintings", "photo_url": "http://images-cf.localist.com/photos/76525/huge/195a2ae18388...", "venue_url": null, "event_instances": [ { "event_instance": { "id": 452831, "ranking": 0, "event_id": 188155, "start": "2013-09-14T10:00:00-04:00", "end": "2013-09-14T17:00:00-04:00", "all_day": false } } ] } } Recent Activity Resource: GET /events/EVENT_ID/activity Returns a paged result set of recent activity on the event specified by event_id. The activity key in the result is an array of activity items. The page key contains paging details. Parameter Type Description Default page number Page number of results to return, starting with 1 1 pp number Number of events to return per page (1-100) 10 Example Request: GET http://CALENDAR-URL/api/2/events/81300/activity { "activity": [ { "photo": { "caption": "", "id": 219, "photo_url": "http://images-cf.localist.com/photos/219/huge/bc33c6375295e5f1c324b3826d201c548ff52c39.jpg?1379709611", "updated_at": "2013-09-20T20:40:11Z", "user": { "id": 1, "photo_url": "http://images-cf.localist.com/photos/189/huge/fbe183f9caa62d281653b5a764e5f6e8fc1afe5f.jpg?1376942064", "profile_url": "http://example.localist.com/eric", "visible_name": "Eric" }, "when": "2013-09-20T20:40:11Z" } }, { "review": { "body": "awesome", "created_at": "2013-09-20T20:40:01Z", "id": 1473, "on": { "id": 81300, "type": "event" }, "rating": 1, "updated_at": "2013-09-20T20:40:01Z", "user": { "id": 1, "photo_url": "http://images-cf.localist.com/photos/189/huge/fbe183f9caa62d281653b5a764e5f6e8fc1afe5f.jpg?1376942064", "profile_url": "http://example.localist.com/eric", "visible_name": "Eric" }, "when": "2013-09-20T20:40:01Z" } }, { "comment": { "body": "my comment", "created_at": "2013-09-20T20:39:54Z", "id": 1470, "on": { "id": 81300, "type": "event" }, "updated_at": "2013-09-20T20:39:54Z", "user": { "id": 1, "photo_url": "http://images-cf.localist.com/photos/189/huge/fbe183f9caa62d281653b5a764e5f6e8fc1afe5f.jpg?1376942064", "profile_url": "http://example.localist.com/eric", "visible_name": "Eric" }, "when": "2013-09-20T16:39:54Z" } } ], "page": { "current": 1, "size": 10, "total": 1 } } Attendees Resource: GET /events/EVENT_ID/attendees Returns the attendees on the event specified by event_id. The attendees key will contain an array of user objects. Note that the user key for the object may also be external_attendee or private_user. Attendees from external sources (such as Facebook) are represented by external_attendee. The localist_url attribute provides the best possible profile page, but may be absent. The id is unique to external attendees. A user with privacy settings preventing details from being shown is represented by a private_user. id and localist_url are null in this case. Example Request: GET http://CALENDAR-URL/api/2/events/81300/attendees { "attendees": [ { "user": { "id": 1, "localist_url": "http://example.localist.com/eric", "photo_url": "http://images-cf.localist.com/photos/189/huge/fbe183f9caa62d281653b5a764e5f6e8fc1afe5f.jpg?1376942064", "visible_name": "Eric" } }, { "external_attendee": { "id": 297248, "localist_url": "http://www.facebook.com/111111111", "photo_url": "http://images-cf.localist.com/images/main/person_huge.png", "visible_name": "John Doe" } }, { "private_user": { "id": null, "localist_url": null, "photo_url": "http://images-cf.localist.com/images/main/person_huge.png", "visible_name": "Private" } } ] } Attendance Gets or modifies the user’s attendance status on the event. All attendance methods require a valid access token. Get Attendance Resource: GET /events/EVENT_ID/attendance Requires authentication. To retrieve attendance, perform a HTTP GET on this resource. Returns a list of event instances the user is attending in the attendances key. Example Request: GET http://CALENDAR-URL/api/2/events/81300/attendance { "attendances": [ { "event_instance": { "attending": "attending", "num_attending": 3, "id": 237632, "ranking": 0, "event_id": 81300, "start": "2013-09-20T21:00:00-04:00", "end": null, "all_day": false } } ] } Add Attendance Resource: POST /events/EVENT_ID/attendance Requires authentication. To add attendance on an event, perform a HTTP POST on this resource, with either the event_instances_id or dates parameter. Both accept multiple values with array syntax (event_instances_id[] or dates[]). The parameters may be in either the URL or as the form data. Parameter Type Description Default dates date Dates (YYYY-MM-DD) of instances to add attendance   event_instances_id number ID(s) of event instances to add attendance   Example Request: POST http://CALENDAR-URL/api/2/events/81300/attendance?dates=2013-09-20 { "status": "success" } Remove Attendance Resource: DELETE /events/EVENT_ID/attendance Requires authentication. To add attendance on an event, perform a HTTP DELETE on this resource, with either the event_instances_id or dates parameter. Both accept multiple values with array syntax (event_instances_id[] or dates[]). The parameters may be in either the URL or as the form data. Parameter Type Description Default dates date Dates (YYYY-MM-DD) of instances to add attendance   event_instances_id number ID(s) of event instances to add attendance   Example Request: DELETE http://CALENDAR-URL/api/2/events/81300/attendance?dates=2013-09-20 { "status": "success" } Filters Resource: GET /events/filters Returns the list of event filter items. The ID can be used in the type parameter to /events. The parent_id attribute represents the parent filter item, if a child filter. Example Request: GET http://CALENDAR-URL/api/2/events/filters { "event_types": [ { "id": 20050, "name": "Music", "parent_id": null } ], "departments": [ { "id": 20860, "name": "WTMD Welcomes", "parent_id": null } ] } Labels Resource: GET /events/labels Returns the display labels for filter types and custom fields. The key is the identifier (as used in other responses) and value is the user-friendly label. Example Request: GET http://CALENDAR-URL/api/2/events/labels { "custom_fields": { }, "filters": { "event_types": "Event Types", "departments": "Departments" } } Places This resource provides access to place data. Format { "place": { "id": 66194, "name": "1st Mariner Arena", "type": "Business", "neighborhood_id": 4, "city_id": "1", "campus_id": null, "school_id": 55, "created_at": "2013-04-05T14:02:52-04:00", "updated_at": "2013-04-22T13:07:32-04:00", "time_zone": "Eastern Time (US & Canada)", "photo_id": 60978, "ranking": 0, "twitter_name": null, "facebook_id": null, "foursquare_id": null, "urlname": "1stmarinerarena", "verified": true, "tags": [ ], "keywords": [ ], "description_text": "1st Mariner Arena is City-owned facility which hosts an aver...", "description": "1st Mariner Arena is City-owned facility which hosts an aver...", "geo": { "latitude": "39.288494", "longitude": "-76.618698", "street": "201 West Baltimore Street", "city": "Baltimore", "state": "MD", "country": "US", "zip": "21201" }, "url": "", "directions": null, "phone": "", "hours": "", "parking": null, "sponsored": false, "address": "201 W Baltimore St, Baltimore, MD 21201, USA", "filters": { }, "custom_fields": { }, "localist_url": "http://events.wtmd.org/1stmarinerarena", "photo_url": "http://images-cf.localist.com/photos/60978/huge/0c21bfeaedf9..." } } Attribute Description address Street address campus_id ID of the community the place belongs to city_id The ID of the place’s city created_at Timestamp of the place’s creation custom_fields Hash of custom fields set on the place. The key is the “unique identifier” of the field, with the value being the field’s value. description_text Plain-text version of the place’s description since v2.1 description The place’s description, including HTML since v2.1 description The place’s plain-text description before v2.1 directions Directions filters Hash of filters set on the place. The key is the filter’s identifier, the value is an array of filter items for each assigned value. foursquare_id ID of a related Foursquare place geo Geographical information hours Hours of operation id The place’s ID (used as venue_id or business_id in other resources) keywords Array of keywords assigned to the place localist_url URL to the place’s page on Localist name The place’s name parking Parking details phone Phone number photo_id ID of photo assigned to place photo_url URL to the place’s photo ranking Relative ranking of the place’s popularity (0-100) school_id ID of the organization the place belongs to sponsored true if the place is marked as sponsored tags Array of tags assigned to the place twitter_name The place’s twitter handle updated_at Timestamp of the place’s last update (does not necessarily indicate changes to any details) url Place’s web page URL urlname URL slug of the place (used in URLs) verified true if this place is verified List Resource: GET /places Returns a paged list of places. By default, includes all places available on a calendar, but can be limited using the locality parameters. The places can be further limited based on assigned filters. The result hash includes an array of place objects in the places key, and a page key with paging information. Locality Parameters These parameters restrict the results based on location. Parameter Type Description Default bounds string Return places within this bounding box The bounding box is specified as: swlat,swlng,nelat,nelng   campus_id number The community to return places for all communities near string The latitude and longitude, separated by commas, to search near   units string Units (mi or km) to use with within mi within number Return places within this many units of near 10 Page Parameters Specifies the size and offset of the results. Parameter Type Description Default page number Page number of results to return, starting with 1 1 pp number Number of places to return per page (1-100) 10 Filter Parameters Restrict the returned places based on filter items, tags and keywords assigned. To specify multiple values for type, keyword or exclude_type, the parameter may be repeated with brackets ([]) after the name. For instance, to request both keyword kw1 and kw2, use a URL similar to: http://CALENDAR-URL/api/2/places?keyword[]=kw1&keyword[]=kw2. Parameter Type Description Default created_after date Only return places created after this date   created_before date Only return places created before this date   exclude_type number Do not return places with these filter item IDs   keyword string Limit places with keywords or tags   sponsored boolean Only return places marked as sponsored if true false type number Limit places to filter item IDs   Output Parameters Note: Sorting by distance is only supported when near is specified. Parameter Type Description Default all_custom_fields boolean Include all custom fields in the result when true. By default, only fields visible on the place’s detail page are returned. false direction string Change sort order, asc or desc varies sort string Sort results by name: place name ranking: place popularity distance: distance from near created: timestamp of creation updated: timestamp of last update name Example Request: GET http://CALENDAR-URL/api/2/places { "places": [ { "place": { "id": 66398, "name": "Abbey Burger Bistro", "type": "Business", "neighborhood_id": 3, "city_id": "1", "campus_id": null, "school_id": 55, "created_at": "2013-04-05T14:06:14-04:00", "updated_at": "2013-04-22T13:09:16-04:00", "time_zone": "Eastern Time (US & Canada)", "photo_id": 61177, "ranking": 0, "twitter_name": null, "facebook_id": null, "foursquare_id": null, "urlname": "abbeyburgerbistro", "verified": true, "tags": [ ], "keywords": [ ], "description_text": "In need of an upscale burger joint? Look no further than The...", "description": "In need of an upscale burger joint? Look no further than The...", "geo": { "latitude": "39.27721", "longitude": "-76.612915", "street": "1041 Marshall Street", "city": "Baltimore", "state": "MD", "country": "US", "zip": "21230" }, "url": "", "directions": null, "phone": "", "hours": "", "parking": null, "sponsored": false, "address": "1041 Marshall St, Baltimore, MD 21230, USA", "filters": { }, "custom_fields": { }, "localist_url": "http://events.wtmd.org/abbeyburgerbistro", "photo_url": "http://images-cf.localist.com/photos/61177/huge/5543d0ed043d..." } } ], "page": { "current": 1, "size": 10, "total": 55 } } Resource: GET /places/search Searches for places with the search term specified in search. Supports all parameters supported by place list, except for keyword, created_before, created_after. Keywords are searched as part of search. Sorting by created and updated is not supported. Parameter Type Description Default search string required search terms   The response format is the same as for place list. Example Request: GET http://CALENDAR-URL/api/2/places/search?search=arena { "places": [ { "place": { "id": 66448, "name": "Sheraton Baltimore City Center Hotel", "type": "Business", "neighborhood_id": 4, "city_id": "1", "campus_id": null, "school_id": 55, "created_at": "2013-04-05T14:07:18-04:00", "updated_at": "2013-04-22T13:09:51-04:00", "time_zone": "Eastern Time (US & Canada)", "photo_id": 61225, "ranking": 0, "twitter_name": null, "facebook_id": null, "foursquare_id": null, "urlname": "sheratonbaltimore", "verified": true, "tags": [ ], "keywords": [ ], "description_text": "Sheraton Baltimore City Center Hotel offers a great location...", "description": "Sheraton Baltimore City Center Hotel offers a great location...", "geo": { "latitude": "39.290398", "longitude": "-76.617096", "street": "101 West Fayette Street", "city": "Baltimore", "state": "MD", "country": "US", "zip": "21201" }, "url": "", "directions": null, "phone": "", "hours": "", "parking": null, "sponsored": false, "address": "101 W Fayette St, Baltimore, MD 21201, USA", "filters": { }, "custom_fields": { }, "localist_url": "http://events.wtmd.org/sheratonbaltimore", "photo_url": "http://images-cf.localist.com/photos/61225/huge/0cd0bef9e86b..." } } ], "page": { "current": 1, "size": 10, "total": 1 } } Get Resource: GET /places/PLACE_ID Returns details about the place specified by place_id. Parameter Type Description Default all_custom_fields boolean Include all custom fields in the result when true. By default, only fields visible on the place’s detail page are returned. false Example Request: GET http://CALENDAR-URL/api/2/places/66194 { "place": { "id": 66194, "name": "1st Mariner Arena", "type": "Business", "neighborhood_id": 4, "city_id": "1", "campus_id": null, "school_id": 55, "created_at": "2013-04-05T14:02:52-04:00", "updated_at": "2013-04-22T13:07:32-04:00", "time_zone": "Eastern Time (US & Canada)", "photo_id": 60978, "ranking": 0, "twitter_name": null, "facebook_id": null, "foursquare_id": null, "urlname": "1stmarinerarena", "verified": true, "tags": [ ], "keywords": [ ], "description_text": "1st Mariner Arena is City-owned facility which hosts an aver...", "description": "1st Mariner Arena is City-owned facility which hosts an aver...", "geo": { "latitude": "39.288494", "longitude": "-76.618698", "street": "201 West Baltimore Street", "city": "Baltimore", "state": "MD", "country": "US", "zip": "21201" }, "url": "", "directions": null, "phone": "", "hours": "", "parking": null, "sponsored": false, "address": "201 W Baltimore St, Baltimore, MD 21201, USA", "filters": { }, "custom_fields": { }, "localist_url": "http://events.wtmd.org/1stmarinerarena", "photo_url": "http://images-cf.localist.com/photos/60978/huge/0c21bfeaedf9..." } } Filters Resource: GET /places/filters Returns the list of place filter items. The ID can be used in the type parameter to /places. The parent_id attribute represents the parent filter item, if a child item. Example Request: GET http://CALENDAR-URL/api/2/places/filters { "business_type": [ { "id": 2335, "name": "Bar", "parent_id": null } ] } Labels Resource: GET /places/labels Returns the display labels for filter types and custom fields. The key is the identifier (as used in other responses) and value is the user-friendly label. Example Request: GET http://CALENDAR-URL/api/2/places/labels { "custom_fields": { }, "filters": { "business_type": "Place Types" } } Groups This resource provides access to groups. Format { "group": { "id": 3948, "name": "CUWinds", "urlname": "cuwinds", "created_at": "2012-10-09T09:21:45-04:00", "updated_at": "2012-10-10T08:49:41-04:00", "photo_id": null, "school_id": 10, "campus_id": null, "url": "http://www.cuwinds.com/", "tags": [ ], "description_text": "CU WINDS unites Cornell University students who seek remarka...", "description": "CU WINDS unites Cornell University students who seek remarka...", "filters": { }, "custom_fields": { }, "localist_url": "http://events.cornell.edu/group/cuwinds", "photo_url": "http://images-cf.localist.com/assets/main/business_huge-18aa..." } } Attribute Description campus_id ID of the community the group belongs to created_at Timestamp of the group’s creation custom_fields Hash of custom fields set on the group. The key is the “unique identifier” of the field, with the value being the field’s value. description_text Plain-text version of the group’s description description The group’s description, including HTML filters Hash of filters set on the group. The key is the filter’s identifier, the value is an array of filter items for each assigned value. id The group’s ID (used as group_id in other resources) localist_url URL to the group’s page on Localist name The group’s name photo_id ID of photo assigned to group photo_url URL to the group’s photo school_id ID of the organization the group belongs to tags Array of tags assigned to the group updated_at Timestamp of the group’s last update (does not necessarily indicate changes to any details) url Group’s web page URL urlname URL slug of the group (used in URLs) List Resource: GET /groups Returns a paged list of groups. By default, includes all groups available on a calendar, but can be limited using the locality parameters. The groups can be further limited based on assigned filters. The result hash includes an array of group objects in the groups key, and a page key with paging information. Locality Parameters These parameters restrict the results based on location. Parameter Type Description Default campus_id number The community to return groups for all communities Page Parameters Specifies the size and offset of the results. Parameter Type Description Default page number Page number of results to return, starting with 1 1 pp number Number of groups to return per page (1-100) 10 Filter Parameters Restrict the returned groups based on the filter items, tags and keywords assigned. To specify multiple values for type, keyword or exclude_type, the parameter may be repeated with brackets ([]) after the name. For instance, to request both keyword kw1 and kw2, use a URL similar to: http://CALENDAR-URL/api/2/groups?keyword[]=kw1&keyword[]=kw2. Parameter Type Description Default created_after date Only return groups created after this date   created_before date Only return groups created before this date   exclude_type number Do not return groups with these filter item IDs   keyword string Limit groups with keywords or tags   type number Limit groups to filter item IDs   Output Parameters Note: Sorting by distance is only supported when near is specified. Parameter Type Description Default all_custom_fields boolean Include all custom fields in the result when true. By default, only fields visible on the group’s detail page are returned. false direction string Change sort order, asc or desc varies sort string Sort results by name: group name created: timestamp of creation updated: timestamp of last update name Example Request: GET http://CALENDAR-URL/api/2/groups { "groups": [ { "group": { "id": 4236, "name": "Cornell Minds Matter", "urlname": "cornell_minds_matter", "created_at": "2013-04-01T09:14:57-04:00", "updated_at": "2013-04-01T09:14:57-04:00", "photo_id": null, "school_id": 10, "campus_id": null, "url": "", "tags": [ ], "description_text": "", "description": "", "filters": { }, "custom_fields": { }, "localist_url": "http://events.cornell.edu/group/cornell_minds_matter", "photo_url": "http://images-cf.localist.com/assets/main/business_huge-18aa..." } } ], "page": { "current": 1, "size": 10, "total": 4 } } Get Resource: GET /groups/GROUP_ID Returns details about the group specified by group_id. Parameter Type Description Default all_custom_fields boolean Include all custom fields in the result when true. By default, only fields visible on the group’s detail page are returned. false Example Request: GET http://CALENDAR-URL/api/2/groups/3948 { "group": { "id": 3948, "name": "CUWinds", "urlname": "cuwinds", "created_at": "2012-10-09T09:21:45-04:00", "updated_at": "2012-10-10T08:49:41-04:00", "photo_id": null, "school_id": 10, "campus_id": null, "url": "http://www.cuwinds.com/", "tags": [ ], "description_text": "CU WINDS unites Cornell University students who seek remarka...", "description": "CU WINDS unites Cornell University students who seek remarka...", "filters": { }, "custom_fields": { }, "localist_url": "http://events.cornell.edu/group/cuwinds", "photo_url": "http://images-cf.localist.com/assets/main/business_huge-18aa..." } } Filters Resource: GET /groups/filters Returns the list of group filter items. The ID can be used in the type parameter to /groups. The parent_id attribute represents the parent filter item, if a child item. Example Request: GET http://CALENDAR-URL/api/2/groups/filters { } Labels Resource: GET /groups/labels Returns the display labels for filter types and custom fields. The key is the identifier (as used in other responses) and value is the user-friendly label. Example Request: GET http://CALENDAR-URL/api/2/groups/labels { "custom_fields": { }, "filters": { "group_types": "Group Types" } } Department Groups Provides access to department groups. This resource functions just like groups. See the groups API for usage details. Note: Advanced department functionality must be enabled (departments must have their own page) for these APIs to function. Format { "department": { "id": 911, "name": "African Studies Program", "urlname": "african_studies_program", "created_at": "2011-03-07T21:08:35Z", "updated_at": "2011-03-07T21:08:35Z", "photo_id": null, "school_id": 1, "campus_id": 11, "url": null, "description_text": "", "description": "", "filters": { }, "custom_fields": { }, "localist_url": "http://events.jhu.edu/department/african_studies_program", "photo_url": "http://images-cf.localist.com/images/main/business_huge.png?..." } } See the group format for attribute details. List Resource: GET /departments The result hash includes an array of department group objects in the departments key, and a page key with paging information. See /groups for details. Get Resource: GET /departments/DEPARTMENT_ID See /groups/GROUP_ID for details. Filters Resource: GET /departments/filters See /groups/filters for details. Labels Resource: GET /departments/labels See /groups/labels for details. Photos This resource provides access to photo metadata. Format { "photo": { "id": 60781, "business_id": null, "caption": "New Mosaic", "event_instance_id": null, "user_id": 0, "neighborhood_id": null, "created_at": "2013-04-05T13:59:24-04:00", "updated_at": "2013-04-05T13:59:24-04:00", "location": null, "plan_id": null, "group_id": null, "image_file_name": "4tlRZYDEoGkaf4NI.jpg", "image_content_type": "image/jpeg", "image_updated_at": "2013-04-05T13:59:24-04:00", "credit": null, "width": 576, "height": 384, "localist_url": "http://events.wtmd.org/photo/60781", "photo_url": "http://images-cf.localist.com/photos/60781/huge/a69941856ab8..." } } Attribute Description caption Photo caption created_at Timestamp of photo’s original creation credit Photo credit height Height of original image id Photo ID image_content_type Content type of original file upload image_file_name Original filename of upload image_updated_at Timestamp of last photo image update localist_url Photo’s URL on Localist (requires authentication to view) photo_url URL to the image file updated_at Timestamp of last update user_id Owner of the photo. This does not necessarily represent the original uploader. width Width of original image The following attributes are set when the photo was posted as part of the recent activity stream for an event, place, group or plan. Attribute Description business_id Relevant place ID event_instance_id Relevant event instance ID group_id Relevant group ID location Relevant location text (place name, event location) plan_id Relevant plan ID List Resource: GET /photos Returns a paged result set of all photos. The result hash includes an array of photo objects in the photos key, and a page key with paging information. Parameter Type Description Default page number Page number to return results for, starting at 1 1 pp number Number of photos to return per page, 1-100 10 Example Request: GET http://CALENDAR-URL/api/2/photos { "photos": [ { "photo": { "id": 60781, "business_id": null, "caption": "New Mosaic", "event_instance_id": null, "user_id": 0, "neighborhood_id": null, "created_at": "2013-04-05T13:59:24-04:00", "updated_at": "2013-04-05T13:59:24-04:00", "location": null, "plan_id": null, "group_id": null, "image_file_name": "4tlRZYDEoGkaf4NI.jpg", "image_content_type": "image/jpeg", "image_updated_at": "2013-04-05T13:59:24-04:00", "credit": null, "width": 576, "height": 384, "localist_url": "http://events.wtmd.org/photo/60781", "photo_url": "http://images-cf.localist.com/photos/60781/huge/a69941856ab8..." } } ], "page": { "current": 1, "size": 10, "total": 258 } } Get Resource: GET /photo/PHOTO_ID Returns details about the photo specified by photo_id. Example Request: GET http://CALENDAR-URL/api/2/photos/60781 { "photo": { "id": 60781, "business_id": null, "caption": "New Mosaic", "event_instance_id": null, "user_id": 0, "neighborhood_id": null, "created_at": "2013-04-05T13:59:24-04:00", "updated_at": "2013-04-05T13:59:24-04:00", "location": null, "plan_id": null, "group_id": null, "image_file_name": "4tlRZYDEoGkaf4NI.jpg", "image_content_type": "image/jpeg", "image_updated_at": "2013-04-05T13:59:24-04:00", "credit": null, "width": 576, "height": 384, "localist_url": "http://events.wtmd.org/photo/60781", "photo_url": "http://images-cf.localist.com/photos/60781/huge/a69941856ab8..." } } Statistics These resources provide summarized data. Common Parameters The returned data can be restricted to a date range, using the start and end parameters. For event view statistics, this restricts to views in the specified range. For attendance statistics, restricts to attendances in the specified range. For all others, restricts to items created in the specified range. By default, the data returned will cover the last 30 days. Parameter Type Description Default end date End of range (format: YYYY-MM-DD) today start date Start of range (format: YYYY-MM-DD) 30 days ago In addition, most event statistics can be restricted based on assigned event filters using the type parameter. Statistics do not support the other filter parameters (such as match, keyword, exclude_type, featured or require_all). To specify multiple values for type, the parameter should be repeated with brackets ([]) after the name. For instance, for events created with either filter ID 1 or 2, use a URL such as: http://CALENDAR-URL/api/2/events/stats/created?type[]=1&type[]=2. Parameter Type Description Default type number Limit events to filter item IDs   Approval Time Resource: GET /events/stats/approval Returns the average time between event submission and approval, in seconds. Supports limiting by creation date (using start and end) as well as assigned filters (type) as described in common parameters. Note: Events first approved before September 24, 2015 are not included in this number. Example Request: GET http://CALENDAR-URL/api/2/events/stats/approval { "average_time": 43447, "event_count": 492, "date": { "first": null, "last": null } } Attribute Description average_time Average number of seconds between event submission time and event approval time date Date range of event submission time. Can be null when using all events event_count Number of events included in average_time Events Created Resource: GET /events/stats/created Returns the number of events submitted by day for the given date range. Supports limiting by creation date (using start and end) as well as assigned filters (type) as described in common parameters. Example Request: GET http://CALENDAR-URL/api/2/events/stats/created { "created": [ { "date": "2015-12-15", "count": 50 } ], "date": { "first": "2015-12-15T00:00:00-05:00", "last": "2016-01-14T23:59:59-05:00" } } Attribute Description created Array of event submission counts by date date Date range of event submission time Event Views Resource: GET /events/EVENT_ID/stats/views Returns the number of event page views by day for the given date range. Note: Only the page views for a specific event (specified as EVENT_ID) may be requested. Total page views across an entire calendar are not available. Example Request: GET http://CALENDAR-URL/api/2/events/123/stats/views { "views": [ { "date": "2015-12-15", "count": 0 } ], "date": { "first": "2015-12-15T00:00:00-05:00", "last": "2016-01-14T23:59:59-05:00" } } Attribute Description created Array of event view counts by date date Date range of event views Users Created Resource: GET /users/stats/views Returns the number of users created by day for the given date range. Supports limiting by creation date (using start and end) as described in common parameters. Example Request: GET http://CALENDAR-URL/api/2/users/stats/created { "created": [ { "date": "2015-12-15", "count": 5 } ], "date": { "first": "2015-12-15T00:00:00-05:00", "last": "2016-01-14T23:59:59-05:00" } } Attribute Description created Array of user creation counts by date date Date range of user creation time Attendee Geographic Info Resource: GET /events/stats/attendees Resource: GET /events/EVENT_ID/stats/attendees Returns geographic information for users attending events in the given date range. The locations of attendees are returned, as well as a count of the attendees in that area. By default, attendees are aggregated roughly by postal code, this can be expanded to larger areas (city, state, or country) with the precision parameter (either city, state, country). The first resource format (/events/stats/attendees) summarizes attendees over all events on a calendar. This form supports limiting by event instance date (using start and end) as well as assigned filters (type) as described in common parameters. The second resource format (/events/EVENT_ID/stats/attendees) summarizes all attendees of the specified event. Note: Geographic information is not available for attendance entries created before September 24, 2015. Parameter Type Description Default precision string Controls how precisely attendees are grouped into areas. Can be zip, city, state or country zip Example Request: GET http://CALENDAR-URL/api/2/events/stats/attendees { "date": { "first": null, "last": null }, "meta": { "event_id": null, "precision": "zip" }, "attendance_data": [ { "count": 6, "latitude": 42.4485, "longitude": -76.4804, "country": "US", "city": "Ithaca", "state": "NY", "zip": "14853" } ] } Attribute Description attendance_data Array of locations with attendees meta event_id is the ID of the event selected for results, or null if all events. precision is the precision value in use. Format Very similar to geo info on events or places, but with lower precision. The city, state or zip fields will be omitted when precision is set to a larger value. Attribute Description city Area’s city count Number of attendees from this area country Area’s country (2 characters) latitude Latitude of center of area longitude Longitude of center of area state Area’s state (or region) zip Area’s postal code Attendances This resource provides access to the list of attendance records on the calendar. An attendance represents a person who has indicated they are going to an event. All attendance methods require a valid access token with the attendances scope. Additionally, the users scope is required for access to detailed user records, and the user_emails scope is required to access email addresses. Attendance Types There are two types of attendance to an event. The first is by using the attendance functionality built into Localist: the “I’m Interested” button on the website or “checking in” via Tailgate. This attendance record is tied to a specific event instance as well as a specific user. The type user identifies this method of attendance. These result from direct user interaction with the calendar. Additionally, Localist supports aggregating attendances from external services (currently, Facebook and Eventbrite). In these cases, the attendance is linked to the event itself, rather than a specific instance. Information other than the attendee’s name may not be available for these types. Matching these entries with a user is attempted, but this does not represent any user interaction with the calendar. These are indicated with the type facebook or eventbrite. Attendances from an external service contain a service_id value, representing the linked attendance on the external service. These values may not represent a specific user on the other service. The attendance id is unique only within the attendance type. Format { "attendance": { "id": 21978, "user_id": 1391, "event_id": 90001, "created_at": "2017-02-01T14:15:09-05:00", "updated_at": "2017-02-01T14:15:09-05:00", "event_instance_id": null, "service_id": null, "email": "[email protected]", "start": "2017-02-11T00:00:00-05:00", "type": "user", "name": "Joe Smith", "user": { }, "event": { } } } When the attendance is linked to a user (user_id is set), the email and name attributes are those of the linked user, and not any value provided by the external service. Note that some older attendances may not have creation or update timestamps. Attribute Description created_at Timestamp of the attendance’s creation (for non-user attendances, this is when we first saw the attendance, not necessarily when it was created on the other service) email Email address of the user or attendee, when available event_id ID of event being attended event_instance_id ID of the specific event instance being attended, when available event When requested, the associated event object id The attendance’s ID. This is only unique within each attendance type name Name of attendee service_id For non-user attendance types, a value representing the attendance ID on the other service. start Start date and time of the attendance type The attendance type Can be user, facebook, or eventbrite. updated_at Timestamp of the attendance’s last update user_id ID of user attending (with type user), or matched user (others) user When requested, the associated user object object List Resource: GET /attendances Requires authentication with attendances scope. Returns a paged list of attendances. By default, includes all attendances, but this can be filtered based on attendance type, creation date, or attendance date. The result hash includes an array of attendance objects in the attendances key, and a page key with paging information. This method supports result expansion with the expand parameter, allowing the full details for the associated user or event to be included in the response. Page Parameters Specifies the size and offset of the results. Parameter Type Description Default page number Page number of results to return, starting with 1 1 pp number Number of attendances to return per page (1-100) 10 Filter Parameters Restrict the returned attendances based on attendance type or date. Parameter Type Description Default created_after date Only return attendances created on or after this date   created_before date Only return attendances created on or before this date   end date Only return attendances happening on or before this date   start date Only return attendances happening on or after this date   type string Limit attendances to a specific attendance type When not specified or all, returns all attendance types. When user, returns only user attendances (direct calendar interactions). When facebook, returns only attendances retrieved from Facebook. When eventbrite, returns only attendances retrieved from Eventbrite.   updated_after date Only return attendances updated on or after this date   updated_before date Only return attendances updated on or before this date   Output Parameters Parameter Type Description Default direction string Change sort direction, either asc or desc varies expand string Comma separated list of objects to expand in the result user Expand user object (requires access token with users scope) event Expand event object none sort string Sort results by id: attendance ID created: creation timestamp updated: update timestamp date: attendance date id Example Request: GET http://CALENDAR-URL/api/2/attendances { "attendances": [ { "attendance": { "id": 21978, "user_id": 1391, "event_id": 90001, "created_at": "2017-02-01T14:15:09-05:00", "event_instance_id": null, "service_id": null, "email": "[email protected]", "start": "2017-02-11T00:00:00-05:00", "type": "user", "name": "Joe Smith" } } ], "page": { "current": 1, "size": 10, "total": 3 } }
__label__pos
0.509919
JetBrains Rider 2022.3 Help Localization refactorings JetBrains Rider provides a set of resource-related refactorings that greatly simplify internationalizing your projects. Move to Resource It is a common practice to store localizable strings in resource files when working on project internalization. JetBrains Rider detects strings to be localized and highlights them, so you can easily find and move such strings from your source code to resource files. JetBrains Rider will declare the corresponding resource entry and replace the string in the code with a resource usage. 1. Place the caret at the string that should be localized. 2. If the string is highlighted by the 'Element is localizable' inspection use the corresponding quick-fix (Alt+Enter) JetBrains Rider: A quick-fix to move string literal to resource 3. Otherwise, press F6 or choose ReSharper | Refactor | Move… from the main menu. 4. In the Move to resource dialog that appears, JetBrains Rider automatically generates the name for the resource entry and proposes a resource file. If necessary, you can change the name in the Name field and choose other resource file in the Resource File list. JetBrains Rider 'Move to Resource' refactoring 5. Optionally, you can change the resource string value in the Value text area and add a comment in the Comment text area. 6. Optionally, you can specify whether to search for identical strings and the search scope by selecting the value in the Find identical items in list. 7. By default, when the new resource is created the Localization Manager will open and display the resource. To disable this behavior, clear the Show the new resource entry in Localization Manager checkbox. 8. Click Next to apply the refactoring. 9. If you selected the Find identical items in option and JetBrains Rider finds any matching strings defined within the specified scope, you will be able to choose which of these strings should be replaced with usages of the new resource. After applying the refactoring, specified occurrences of the string are replaced with corresponding resource usages and the new resource declaration appears in the specified .resx file. After the new resource is created you can override its value for other cultures. Move Resource If your project contains multiple resource .resx files, this refactoring will help you move existing resources from one resource file to another. If there is only one .resx file in the current project, this refactoring is unavailable. 1. Set the caret at the resource usage in a code file: JetBrains Rider: Move to Resource refactoring or at the resource name in a .resx file: JetBrains Rider: Move to Resource refactoring 2. Press F6 or choose Refactor | Move... from the main menu . Alternatively, you can press Ctrl+Shift+A, start typing the command name in the popup, and then choose it there. 3. In the Move resource dialog that appears, specify a target resource file where you want to move the resource. JetBrains Rider: 'Move Resource' refactoring 4. Optionally, you can change the resource name. 5. Click Next to apply the refactoring. Rename Resource You can use the Rename refactoring to quickly rename existing resources. After applying the refactoring, all resource declarations in resource files and all resource usages in code files are updated according to the new name. 1. Set the caret at the resource usage in a code file: JetBrains Rider: Move to Resource refactoring or at the resource name in a .resx file: JetBrains Rider: Move to Resource refactoring 2. Press Shift+F6 or choose Refactor | Rename... from the main menu . Alternatively, you can press Ctrl+Shift+A, start typing the command name in the popup, and then choose it there. 3. In the Rename Resource dialog that appears, specify a new name for the resource. 4. Click Next to apply the refactoring. Inline Resource The Inline Resource refactoring substitutes resource usages with the original string and optionally deletes the corresponding resource entries from resource files. 1. Set the caret at the resource usage in a code file: JetBrains Rider: Move to Resource refactoring or at the resource name in a .resx file: JetBrains Rider: Move to Resource refactoring 2. Press Ctrl+Alt+N or choose Refactor | Inline | Inline... from the main menu . Alternatively, you can press Ctrl+Shift+A, start typing the command name in the popup, and then choose it there. 3. In the Inline Resource dialog that appears, specify refactoring options: • Inline all usages: if selected, replaces all resource usages in the project with the original string. If deselected, replaces only the resource usage where you invoked this refactoring. Note that this option works only if you invoked the refactoring from the code file. • Remove inlined resource declaration: if selected, removes resource declaration from all related resource files. If deselected, leaves declarations intact. 4. Click Next to apply the refactoring. Safe Delete Resource If you are going to delete a resource, use the Safe Delete refactoring to ensure that the delete operation is safe. If there are no resource usages found, the resource will be deleted right away. Otherwise, ReSharper will show all resource usages, allowing you to edit the corresponding code. Removing usages marked with the Themed icon error screen gray icon, will lead to compilation errors. 1. Set the caret at the resource usage in a code file: JetBrains Rider: Move to Resource refactoring or at the resource name in a .resx file: JetBrains Rider: Move to Resource refactoring 2. Press Alt+Delete or choose Refactor | Safe Delete... from the main menu . Alternatively, you can press Ctrl+Shift+A, start typing the command name in the popup, and then choose it there. • If there are no usages of this resource in code files, the refactoring is applied and resource declarations are removed from all .resx files. • If there are usages of this resource in code files, the Safe Delete Resource dialog opens showing all conflicts. JetBrains Rider: Safe Delete resource. Conflicts 3. If you have conflicts trying to safe-delete a resource, resolve them manually and click Refresh. 4. When all conflicts are resolved and disappear from the dialog, click Next to apply the refactoring. Last modified: 16 November 2021
__label__pos
0.98772