text
stringlengths
1
22.8M
Leonine facies is a facies that resembles that of a lion. It is seen in multiple conditions and has been classically described for lepromatous leprosy as well as Paget's disease of bone. It is a dermatological symptom, with characteristic facial features that are visible on presentation, and is useful for focusing on differential diagnosis. Associated conditions Differential diagnoses include the following: Lepromatous leprosy Paget's disease of bone Mycosis fungoides Polyostotic fibrous dysplasia Amyloidosis Actinic reticuloid Cutaneous T cell lymphoma Leishmaniasis Lipoid proteinosis Progressive nodular histiocytosis Mastocytosis Hyperimmunoglobulin E syndrome, also known as Job's syndrome See also Facies Leontiasis ossea References Symptoms and signs: Skin and subcutaneous tissue
```smalltalk // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.TemplateEngine.Authoring.CLI.Commands { internal class ValidateCommandArgs { public ValidateCommandArgs(string templateLocation) { TemplateLocation = templateLocation; } public string TemplateLocation { get; } } } ```
John Cushing (1719-1790) was a British stage actor. He appeared at a variety of London fairs during the early 1740s, before joining the company at Goodman's Fields Theatre in 1744 along with his wife. He then spent many years as part of the company at the Covent Garden Theatre. His final appearance there came in 1782 and died in Liverpool in 1790. References Bibliography Highfill, Philip H, Burnim, Kalman A. & Langhans, Edward A. A Biographical Dictionary of Actors, Actresses, Musicians, Dancers, Managers, and Other Stage Personnel in London, 1660-1800: Volume 4. SIU Press, 1975. 18th-century English people 18th-century British actors English male stage actors British male stage actors 18th-century English male actors 18th-century British male actors 1719 births 1790 deaths
Joseph McFarland (February 9, 1868 - 1945) was an American physician known for his work in bacteriology, toxinology, and pathology. He was the curator of the Mutter Museum between 1936 and his death in 1945. References Physicians from Philadelphia 1868 births 1945 deaths American curators
The 1996–97 National Football League, also known as the Philips National League for sponsorship reasons, was the inaugural season of the National Football League. The tournament began on 17 December 1996 and concluded on 16 March 1997. Before the commencement, the All India Football Federation maintained that it would be a semi-professional tournament for the first two years. Philips India was the main sponsor for the tournament and a total prize money of 1.5 crore was announced; 35 lakh to the winner. Twelve teams took part in the competition, which was played in two round robin stages: a preliminary group stage featuring two groups of six teams each played in Calcutta and Goa, and a main stage featuring the top four from each group played after a gap of three weeks following the first. East Bengal were the favorites to win the competition by virtue of their victories in the Federation Cup and the Calcutta League earlier that season. However, in a closely fought second stage mostly between JCT Mills and Churchill Brothers, the former sealed the title on the final day with a win over Dempo, courtesy a hat trick by Bhaichung Bhutia. Air India's Godfrey Pereira was named the best player of the league and JCT Mills' Sukhwinder Singh, the best manager. JCT Mills also won the Fairplay Trophy, which carried a purse of 2.5 lakh. The bottom two clubs in each group would not take part in the next edition, although Mohun Bagan would play the following season. Overview The first match of the inaugural season of the National Football League kicked off at around 5:45 p.m. (IST), an hour after the scheduled time, on 17 December 1996 between East Bengal and Mohammedan Sporting at the Salt Lake Stadium in Calcutta. It was inaugurated by then India's Prime Minister H. D. Deve Gowda. East Bengal defeated Mohammedan Sporting 2–1 with Raman Vijayan scoring a brace for his team; the first goal coming in the 10th minute. Teams Stadia and locations Group stage Top four advance to the Championship stage. Group A Group B Championship stage Season statistics Hat-tricks 5 Player scored five goals Note: (H) – Home; (A) – Away 1996-97 Season Roll of Honour References External links Philips National League at Rec.Sport.Soccer Statistics Foundation National Football League (India) seasons 1996–97 in Indian football India
```php <?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\CssSelector\Parser\Handler; use Symfony\Component\CssSelector\Parser\Reader; use Symfony\Component\CssSelector\Parser\TokenStream; /** * CSS selector handler interface. * * This component is a port of the Python cssselect library, * which is copyright Ian Bicking, @see path_to_url * * @author Jean-Franois Simon <jeanfrancois.simon@sensiolabs.com> */ interface HandlerInterface { /** * @param Reader $reader * @param TokenStream $stream * * @return bool */ public function handle(Reader $reader, TokenStream $stream); } ```
```java /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oracle.truffle.object.basic.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import org.junit.Ignore; import org.junit.Test; import com.oracle.truffle.api.object.DynamicObject; import com.oracle.truffle.api.object.DynamicObjectLibrary; import com.oracle.truffle.api.object.Shape; import com.oracle.truffle.api.test.AbstractLibraryTest; public class CachedFallbackTest extends AbstractLibraryTest { @Test public void testMixedReceiverTypeSameShape() { Shape shape = Shape.newBuilder().build(); DynamicObject o1 = new TestDynamicObjectMinimal(shape); DynamicObject o2 = new TestDynamicObjectDefault(shape); String key = "key"; String val = "value"; CachedPutNode writeNode = adopt(CachedPutNodeGen.create()); writeNode.execute(o1, key, val); writeNode.execute(o2, key, val); assertSame("expected same shape", o1.getShape(), o2.getShape()); CachedGetNode readNode = adopt(CachedGetNodeGen.create()); assertEquals(val, readNode.execute(o1, key)); assertEquals(val, readNode.execute(o2, key)); } @Test public void testTransition() { Shape shape = Shape.newBuilder().build(); DynamicObject o1 = new TestDynamicObjectDefault(shape); DynamicObject o2 = new TestDynamicObjectDefault(shape); String key1 = "key1"; String val1 = "value1"; String key2 = "key2"; String val2 = "value2"; DynamicObjectLibrary library = adopt(DynamicObjectLibrary.getFactory().create(o1)); assertTrue(library.accepts(o1)); assertTrue(library.accepts(o2)); library.put(o1, key1, val1); library.put(o2, key1, val1); library.put(o1, key2, val2); library.put(o2, key2, val2); assertSame("expected same shape", o1.getShape(), o2.getShape()); CachedGetNode readNode = adopt(CachedGetNodeGen.create()); assertEquals(val1, readNode.execute(o1, key1)); assertEquals(val1, readNode.execute(o2, key1)); assertEquals(val2, readNode.execute(o1, key2)); assertEquals(val2, readNode.execute(o2, key2)); } @Ignore @Test public void testMixedReceiverTypeSameShapeWithFallback() { Shape shape = Shape.newBuilder().build(); DynamicObject o1 = new TestDynamicObjectMinimal(shape); DynamicObject o2 = new TestDynamicObjectDefault(shape); String key1 = "key1"; String val1 = "value1"; String key2 = "key2"; String val2 = "value2"; DynamicObjectLibrary library1 = adopt(DynamicObjectLibrary.getFactory().create(o1)); library1.put(o1, key1, val1); library1.put(o2, key1, val1); DynamicObjectLibrary library2 = adopt(DynamicObjectLibrary.getFactory().create(o1)); library2.put(o1, key2, val2); library2.put(o2, key2, val2); assertSame("expected same shape", o1.getShape(), o2.getShape()); CachedGetNode readNode = adopt(CachedGetNodeGen.create()); assertEquals(val1, readNode.execute(o1, key1)); assertEquals(val1, readNode.execute(o2, key1)); assertEquals(val2, readNode.execute(o1, key2)); assertEquals(val2, readNode.execute(o2, key2)); } } ```
Kisa or KISA may refer to: People Janet Kisa (born 1992), Kenyan runner Kisa Gotami, disciple of Buddha Rostislav Kiša (born 1978), Czech footballer Places Khisa, also known as Kisa, a village in Botswana Kisa, Hiroshima, a former town in Hiroshima Prefecture, Japan, now merged with Miyoshi Kisa Station, a train station in Miyoshi Kisa, Iran, a village in Hormozgan Province, Iran Kisa, Sweden, a town in Östergötland County, Sweden Organizations Kisa BK, a Swedish football club KISA-LD, a low-power television station (channel 22, virtual 40) licensed to serve San Antonio, Texas, United States KISA (NGO), the Movement for Equality, Support, Anti-Racism (Greek: Κίνηση για Ισότητα, Στήριξη, Αντιρατσισμό, abbreviated to ΚΙΣΑ), a Cypriot non-governmental organization established in 1998 KISA Phone, an Australian telecommunications services provider founded in 2013 The Korea Internet & Security Agency Other uses Kisa Sohma, a character in the manga and anime Fruits Basket "Kisa the Cat", an Icelandic fairy tale Kisa tribe (Luhya), an indigenous tribe of Kenya
The William E. Simon Prize for Philanthropic Leadership is an annual award given by the William E. Simon Foundation in honor of its founder, former Secretary of the Treasury and financier William E. Simon, and administered by the Philanthropy Roundtable. The award was created in 2000, first awarded in 2001, and is given to "highlight the power of philanthropy to promote positive change and to inspire others to support charities that achieve genuine results." The prize is given to living donors who have "shown exemplary leadership through their own charitable giving, either directly or through foundations they have created." Donors who receive the prize are expected to exemplify Simon's ideals, which include "personal responsibility, resourcefulness, volunteerism, scholarship, individual freedom, faith in God, and helping people to help themselves." The Simon Prize carries a $250,000 purse, which is awarded to the charity or charities of the recipient's choice. The Simon Prize is presented at the Philanthropy Roundtable's Annual Meeting. List of recipients External links Information about and list of winners of the William E. Simon Prize References American awards Charity in the United States
```objective-c // // FavIconResultTableCellView.h // Strongbox // // Created by Mark on 21/12/2019. // #import <Cocoa/Cocoa.h> #import "ClickableImageView.h" NS_ASSUME_NONNULL_BEGIN @interface FavIconResultTableCellView : NSTableCellView @property (weak) IBOutlet NSImageView *icon; @property (weak) IBOutlet NSTextField *title; @property (weak) IBOutlet NSTextField *subTitle; @property BOOL checkable; @property BOOL checked; @property BOOL showIconChooseButton; @property (copy, nullable) void (^onClickChooseIcon)(void); @property (copy, nullable) void (^onCheckChanged)(void); @end NS_ASSUME_NONNULL_END ```
William "Jamie" Leach (born August 25, 1969) is a Canadian-born American former National Hockey League right wing. He is the son of former NHLer Reggie Leach. He was included on both Stanley Cup winning pictures with Pittsburgh in 1991 and 1992. Leach grew up in Cherry Hill, New Jersey and played hockey at Cherry Hill High School East. Leach did not qualify for a Cup inscription in 1991 as he had played too few NHL games that season (seven regular season games). He played enough games with the Pittsburgh Penguins in 1992 to get his name on the Stanley Cup. Career statistics References External links 1969 births Living people Canadian ice hockey right wingers Cherry Hill High School East alumni Cincinnati Cyclones (IHL) players Cleveland Lumberjacks players Florida Panthers players Hamilton Steelhawks players Hartford Whalers players Ice hockey players from New Jersey Ice hockey people from Winnipeg Muskegon Lumberjacks players New Westminster Bruins players Niagara Falls Thunder players Nottingham Panthers players Sportspeople from Cherry Hill, New Jersey Pittsburgh Penguins draft picks Pittsburgh Penguins players Rochester Americans players San Diego Gulls (IHL) players Sheffield Steelers players South Carolina Stingrays players Springfield Indians players Stanley Cup champions First Nations sportspeople Canadian expatriate ice hockey players in England
```yaml # this file should contain all periodic jobs that use the k8s-triage-robot token periodics: - name: ci-k8s-triage-robot interval: 1h cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: Adds API review process description to kind/api-change PRs testgrid-tab-name: api-review-help spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: # pull requests against master branches in the kubernetes org labeled kind/api-change # exclude PRs that are in progress, held, or need rebase (typically aren't ready for API review). # exclude PRs already labeled api-review or tracked in the API review project # exclude PRs that already have the comment text - |- --query=org:kubernetes is:pr base:master label:kind/api-change -label:do-not-merge/work-in-progress -label:do-not-merge/hold -label:needs-rebase -label:api-review -project:kubernetes/169 NOT "complete the pre-review checklist and request an API review" - --updated=5m - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=This PR [may require API review](path_to_url#what-apis-need-to-be-reviewed). If so, when the changes are ready, [complete the pre-review checklist and request an API review](path_to_url#mechanics). Status of requested reviews is tracked in the [API Review project](path_to_url - --ceiling=10 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: ci-k8s-triage-robot-stable-metrics interval: 1h cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: Adds stable metrics review documentation to area/stable-metrics PRs testgrid-tab-name: stable-metrics-help spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: # pull requests against master branches in the kubernetes org labeled area/stable-metrics # exclude PRs that already have the comment text - |- --query=org:kubernetes is:pr base:master label:area/stable-metrics NOT "documentation for the requirements and lifecycle of stable metrics" - --updated=5m - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=This PR [may require stable metrics review](path_to_url Stable metrics are guaranteed to **not change**. Please review the documentation for the requirements and lifecycle of stable metrics and ensure that your metrics meet these guidelines. - --ceiling=10 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: ci-k8s-triage-robot-cla interval: 10m cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: A sample job to make sure things work testgrid-tab-name: cla spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: - |- --query=org:kubernetes org:kubernetes-sigs org:kubernetes-client org:kubernetes-csi is:pr is:open -label:"cncf-cla: no" -label:"cncf-cla: yes" - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=Unknown CLA label state. Rechecking for CLA labels. Send feedback to sig-contributor-experience at [kubernetes/community](path_to_url /check-cla /easycla - --template - --ceiling=10 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: ci-k8s-triage-robot-close-issues interval: 1h cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: Closes rotten issues after 30d of inactivity testgrid-tab-name: close-issues spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: - |- --query=org:kubernetes org:kubernetes-sigs org:kubernetes-client org:kubernetes-csi is:issue -repo:kubernetes-sigs/kind -repo:kubernetes/kubectl -repo:kubernetes/steering -label:lifecycle/frozen -label:"help wanted" -label:"good first issue" -label:triage/accepted -label:priority/critical-urgent,priority/important-soon,priority/important-longterm label:lifecycle/rotten - --updated=720h - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=The Kubernetes project currently lacks enough active contributors to adequately respond to all issues and PRs. This bot triages issues according to the following rules: - After 90d of inactivity, `lifecycle/stale` is applied - After 30d of inactivity since `lifecycle/stale` was applied, `lifecycle/rotten` is applied - After 30d of inactivity since `lifecycle/rotten` was applied, the issue is closed You can: - Reopen this issue with `/reopen` - Mark this issue as fresh with `/remove-lifecycle rotten` - Offer to help out with [Issue Triage][1] Please send feedback to sig-contributor-experience at [kubernetes/community](path_to_url /close not-planned [1]: path_to_url - --template - --ceiling=10 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: ci-k8s-triage-robot-close-prs interval: 1h cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: Closes rotten PRs after 30d of inactivity testgrid-tab-name: close-prs spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: - |- --query=org:kubernetes org:kubernetes-sigs org:kubernetes-client org:kubernetes-csi is:pr -repo:kubernetes-sigs/kind -repo:kubernetes/ingress-nginx -repo:kubernetes/steering -label:lifecycle/frozen label:lifecycle/rotten - --updated=720h - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=The Kubernetes project currently lacks enough active contributors to adequately respond to all issues and PRs. This bot triages PRs according to the following rules: - After 90d of inactivity, `lifecycle/stale` is applied - After 30d of inactivity since `lifecycle/stale` was applied, `lifecycle/rotten` is applied - After 30d of inactivity since `lifecycle/rotten` was applied, the PR is closed You can: - Reopen this PR with `/reopen` - Mark this PR as fresh with `/remove-lifecycle rotten` - Offer to help out with [Issue Triage][1] Please send feedback to sig-contributor-experience at [kubernetes/community](path_to_url /close [1]: path_to_url - --template - --ceiling=10 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: ci-k8s-triage-robot-retester interval: 20m # Retest at most 1 PR per 20m, which should not DOS the queue. cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot testgrid-tab-name: retester description: Automatically /retest for approved PRs that are failing tests spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: - |- --query=is:pr -label:do-not-merge -label:do-not-merge/blocked-paths -label:do-not-merge/cherry-pick-not-approved -label:do-not-merge/contains-merge-commits -label:do-not-merge/hold -label:do-not-merge/invalid-commit-message -label:do-not-merge/invalid-owners-file -label:do-not-merge/needs-sig -label:do-not-merge/needs-kind -label:do-not-merge/release-note-label-needed -label:do-not-merge/work-in-progress label:lgtm label:approved label:"cncf-cla: yes" status:failure -label:needs-rebase -label:needs-ok-to-test -label:"cncf-cla: no" repo:kubernetes/kops repo:kubernetes/kubernetes repo:kubernetes/test-infra - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=The Kubernetes project has merge-blocking tests that are currently too flaky to consistently pass. This bot retests PRs for certain kubernetes repos according to the following rules: - The PR does have any `do-not-merge/*` labels - The PR does not have the `needs-ok-to-test` label - The PR is mergeable (does not have a `needs-rebase` label) - The PR is approved (has `cncf-cla: yes`, `lgtm`, `approved` labels) - The PR is failing tests required for merge You can: - Review the [full test history](path_to_url{{.Org}}&repo={{.Repo}}&pr={{.Number}}) for this PR - Prevent this bot from retesting with `/lgtm cancel` or `/hold` - Help make our tests less flaky by following our [Flaky Tests Guide][1] /retest [1]: path_to_url - --template - --ceiling=1 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: ci-k8s-triage-robot-rotten-issues interval: 1h cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: Adds lifecycle/rotten to stale issues after 30d of inactivity testgrid-tab-name: rotten-issues spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: - |- --query=org:kubernetes org:kubernetes-sigs org:kubernetes-client org:kubernetes-csi is:issue -repo:kubernetes-sigs/kind -repo:kubernetes/ingress-nginx -repo:kubernetes/steering -label:lifecycle/frozen -label:lifecycle/rotten -label:"help wanted" -label:"good first issue" -label:"triage/accepted" label:lifecycle/stale - --updated=720h - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=The Kubernetes project currently lacks enough active contributors to adequately respond to all issues. This bot triages un-triaged issues according to the following rules: - After 90d of inactivity, `lifecycle/stale` is applied - After 30d of inactivity since `lifecycle/stale` was applied, `lifecycle/rotten` is applied - After 30d of inactivity since `lifecycle/rotten` was applied, the issue is closed You can: - Mark this issue as fresh with `/remove-lifecycle rotten` - Close this issue with `/close` - Offer to help out with [Issue Triage][1] Please send feedback to sig-contributor-experience at [kubernetes/community](path_to_url /lifecycle rotten [1]: path_to_url - --template - --ceiling=10 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: ci-k8s-triage-robot-rotten-prs interval: 1h cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: Adds lifecycle/rotten to stale PRs after 30d of inactivity testgrid-tab-name: rotten-prs spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: - |- --query=org:kubernetes org:kubernetes-sigs org:kubernetes-client org:kubernetes-csi is:pr -repo:kubernetes-sigs/kind -repo:kubernetes/ingress-nginx -repo:kubernetes/steering -label:lifecycle/frozen -label:lifecycle/rotten label:lifecycle/stale - --updated=720h - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=The Kubernetes project currently lacks enough active contributors to adequately respond to all PRs. This bot triages PRs according to the following rules: - After 90d of inactivity, `lifecycle/stale` is applied - After 30d of inactivity since `lifecycle/stale` was applied, `lifecycle/rotten` is applied - After 30d of inactivity since `lifecycle/rotten` was applied, the PR is closed You can: - Mark this PR as fresh with `/remove-lifecycle rotten` - Close this PR with `/close` - Offer to help out with [Issue Triage][1] Please send feedback to sig-contributor-experience at [kubernetes/community](path_to_url /lifecycle rotten [1]: path_to_url - --template - --ceiling=10 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: ci-k8s-triage-robot-stale-issues interval: 1h cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: Adds lifecycle/stale to issues after 90d of inactivity testgrid-tab-name: stale-issues spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: - |- --query=org:kubernetes org:kubernetes-sigs org:kubernetes-client org:kubernetes-csi is:issue -repo:kubernetes-sigs/kind -repo:kubernetes/ingress-nginx -repo:kubernetes/steering -label:lifecycle/frozen -label:lifecycle/stale -label:lifecycle/rotten -label:"help wanted" -label:"good first issue" -label:"triage/accepted" - --updated=2160h - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=The Kubernetes project currently lacks enough contributors to adequately respond to all issues. This bot triages un-triaged issues according to the following rules: - After 90d of inactivity, `lifecycle/stale` is applied - After 30d of inactivity since `lifecycle/stale` was applied, `lifecycle/rotten` is applied - After 30d of inactivity since `lifecycle/rotten` was applied, the issue is closed You can: - Mark this issue as fresh with `/remove-lifecycle stale` - Close this issue with `/close` - Offer to help out with [Issue Triage][1] Please send feedback to sig-contributor-experience at [kubernetes/community](path_to_url /lifecycle stale [1]: path_to_url - --template - --ceiling=10 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: ci-k8s-triage-robot-stale-prs interval: 1h cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: Adds lifecycle/stale to PRs after 90d of inactivity testgrid-tab-name: stale-prs spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: - |- --query=org:kubernetes org:kubernetes-sigs org:kubernetes-client org:kubernetes-csi is:pr -repo:kubernetes-sigs/kind -repo:kubernetes/ingress-nginx -repo:kubernetes/steering -label:lifecycle/frozen -label:lifecycle/stale -label:lifecycle/rotten - --updated=2160h - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=The Kubernetes project currently lacks enough contributors to adequately respond to all PRs. This bot triages PRs according to the following rules: - After 90d of inactivity, `lifecycle/stale` is applied - After 30d of inactivity since `lifecycle/stale` was applied, `lifecycle/rotten` is applied - After 30d of inactivity since `lifecycle/rotten` was applied, the PR is closed You can: - Mark this PR as fresh with `/remove-lifecycle stale` - Close this PR with `/close` - Offer to help out with [Issue Triage][1] Please send feedback to sig-contributor-experience at [kubernetes/community](path_to_url /lifecycle stale [1]: path_to_url - --template - --ceiling=10 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: ci-k8s-triage-robot-thaw-prs interval: 1h cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: Removes lifecycle/frozen from PRs testgrid-tab-name: thaw-prs spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: - |- --query=org:kubernetes org:kubernetes-sigs org:kubernetes-client org:kubernetes-csi label:lifecycle/frozen is:pr - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=The `lifecycle/frozen` label can not be applied to PRs. This bot removes `lifecycle/frozen` from PRs because: - Commenting `/lifecycle frozen` on a PR has not worked since March 2021 - PRs that remain open for >150 days are unlikely to be easily rebased You can: - Rebase this PR and attempt to get it merged - Close this PR with `/close` Please send feedback to sig-contributor-experience at [kubernetes/community](path_to_url /remove-lifecycle frozen - --template - --ceiling=10 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: ci-k8s-triage-robot-retriage interval: 1h cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: Removes the triage/accepted label after 1 year of inactivity testgrid-tab-name: re-triage spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: - |- --query=org:kubernetes org:kubernetes-sigs org:kubernetes-client org:kubernetes-csi -repo:kubernetes-sigs/kind -repo:kubernetes/steering label:triage/accepted -label:priority/important-soon -label:priority/critical-urgent is:issue - --updated=8760h - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=This issue has not been updated in over 1 year, and should be re-triaged. You can: - Confirm that this issue is still relevant with `/triage accepted` (org members only) - Close this issue with `/close` For more details on the triage process, see path_to_url /remove-triage accepted - --template - --ceiling=10 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: ci-k8s-triage-robot-retriage-important interval: 1h cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: Removes the triage/accepted label on important issues after 3 months of inactivity testgrid-tab-name: re-triage-important spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: - |- --query=org:kubernetes org:kubernetes-sigs org:kubernetes-client org:kubernetes-csi -repo:kubernetes-sigs/kind -repo:kubernetes/steering label:triage/accepted label:priority/important-soon is:issue - --updated=2160h - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=This issue is labeled with `priority/important-soon` but has not been updated in over 90 days, and should be re-triaged. Important-soon issues must be staffed and worked on either currently, or very soon, ideally in time for the next release. You can: - Confirm that this issue is still relevant with `/triage accepted` (org members only) - Deprioritize it with `/priority important-longterm` or `/priority backlog` - Close this issue with `/close` For more details on the triage process, see path_to_url /remove-triage accepted - --template - --ceiling=10 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: ci-k8s-triage-robot-retriage-critical interval: 1h cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: Removes the triage/accepted label on critical issues after 1 month of inactivity testgrid-tab-name: re-triage-critical spec: containers: - image: gcr.io/k8s-staging-test-infra/commenter:v20240801-a5d9345e59 command: - commenter args: - |- --query=org:kubernetes org:kubernetes-sigs org:kubernetes-client org:kubernetes-csi -repo:kubernetes-sigs/kind -repo:kubernetes/steering label:triage/accepted label:priority/critical-urgent is:issue - --updated=720h - --token=/etc/github-token/token - --endpoint=path_to_url - |- --comment=This issue is labeled with `priority/critical-urgent` but has not been updated in over 30 days, and should be re-triaged. Critical-urgent issues must be actively worked on as someone's top priority right now. You can: - Confirm that this issue is still relevant with `/triage accepted` (org members only) - Deprioritize it with `/priority {important-soon, important-longterm, backlog}` - Close this issue with `/close` For more details on the triage process, see path_to_url /remove-triage accepted - --template - --ceiling=10 - --confirm volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token - name: issue-creator interval: 24h cluster: k8s-infra-prow-build-trusted labels: preset-service-account: "true" decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: Creates github issues based on data from various 'IssueSource's. spec: containers: - image: gcr.io/k8s-staging-test-infra/issue-creator:v20240801-a5d9345e59 command: - issue-creator args: - --dry-run=false - --alsologtostderr - --org=kubernetes - --project=kubernetes - --token-file=/etc/github-token/token - --triage-window=1 - --triage-count=10 - --flakyjob-count=3 volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token # periodically file / close bugs for repos based on presence of SECURITY_CONTACTS - name: secping interval: 24h cluster: k8s-infra-prow-build-trusted decorate: true annotations: testgrid-dashboards: sig-contribex-k8s-triage-robot description: files bugs for SECURITY_CONTACTS testgrid-tab-name: secping extra_refs: - base_ref: main org: justaugustus repo: secping spec: containers: - command: - go - run - . - -d - --confirm - --token-path=/etc/github-token/token - --skip-emails env: - name: GO111MODULE value: "on" image: golang:latest volumeMounts: - name: token mountPath: /etc/github-token volumes: - name: token secret: secretName: k8s-triage-robot-github-token ```
Syed Baqar Askary fondly known as Dr. Askary is the Founder Trustee and CEO of Fatima Jinnah Dental College (FJDC), Karachi. Baqar Askary is a medical graduate of 1966, of Dow Medical College, Karachi Pakistan. Baqar Askary a senior medical practitioner and an educationist. FJDC founded in 1992 is a pioneer institution devoted to the teaching of dentistry, independently and not as a department of any medical college. The college is named "Fatima Jinnah Dental College" after Mohtarma Fatima Jinnah one of the pioneers of Pakistan and sister of Mohammad Ali Jinnah, the founder of Pakistan. It was quickly made clear that neither the federal government nor the Sindh Government had any plans to set up a Dental College in Karachi, in 1989 Federal Government of Pakistan, however, as a consolation, announced that it will allow such an institution to be established in the private sector. On 20 February 1993, which was the centenary year of the birth of the Mohtarma, to mark the occasion Baqak Askary addressing a press conference, announced that the establishment of this College was a gift to the Nation. With intimation to the Federal and Provincial Ministers of Health, the Pakistan Medical & Dental Council and the University of Karachi, Fatima Jinnah Dental College was founded. Fatima Jinnah Dental College and Hospital Trust The Fatima Jinnah Dental College was established and is being run and managed by a duly registered Fatima Jinnah Dental College & Hospital Trust. It is a public charitable Trust, Syed Hashim Raza, a civil servant and the administrator of the Estate of Mohammad Ali Jinnah, was its first chairman. Baqar Askary came to be known as the founder Trustee and Chief Executive of Fatima Jinnah Dental College and Hospital Trust. Services to public health He was also elected by the registered medical practitioners of Sindh Province as Member, Pakistan Medical & Dental Council (PM & DC) in the year 2000. Appointed in January 2005, by the Federal Ministry of Health, on a six-member Committee, for Amendments to the PM & DC Ordinance 1962 and Act of 1973. He is actively associated with the formulation of health policy and its implementation for health delivery program in Pakistan. Early professional life He was elected President of Dow Medical College Student's Union-1962-63, and President, National Student Federation, Pakistan for the period – 1963–65, during which he successfully led students' movement for the achievement of better facilities and for raising the standard of education in the country. Successful student's movements provided Karachi with a second medical college – Sindh Medical College at Jinnah Post Graduate Medical Centre, in the public sector and Dawood Engineering College in the private sector. The University of Karachi allowed degree courses in city colleges, etc. As a result of an agreement reached between the then Governor of West Pakistan, Nawab Amir Mohammad of Kalabagh and the students in 1963 at Lahore reforms and improvements were brought about in the educational policies of the Government. Baqar Askary motivated and brought Mohtarma Fatima Jinnah into national politics and persuaded her to contest the general elections during the first martial law. References External links Fjdc.edu.pk Pakistani dentists Muhajir people Living people Year of birth missing (living people)
```objective-c // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #ifndef V8TestInterface3_h #define V8TestInterface3_h #include "bindings/core/v8/ScriptWrappable.h" #include "bindings/core/v8/ToV8.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8DOMWrapper.h" #include "bindings/core/v8/WrapperTypeInfo.h" #include "core/CoreExport.h" #include "platform/heap/Handle.h" namespace blink { class V8TestInterface3 { public: CORE_EXPORT static bool hasInstance(v8::Local<v8::Value>, v8::Isolate*); static v8::Local<v8::Object> findInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*); CORE_EXPORT static v8::Local<v8::FunctionTemplate> domTemplate(v8::Isolate*); static TestInterface3* toImpl(v8::Local<v8::Object> object) { return toScriptWrappable(object)->toImpl<TestInterface3>(); } CORE_EXPORT static TestInterface3* toImplWithTypeCheck(v8::Isolate*, v8::Local<v8::Value>); CORE_EXPORT static const WrapperTypeInfo wrapperTypeInfo; static void refObject(ScriptWrappable*); static void derefObject(ScriptWrappable*); template<typename VisitorDispatcher> static void trace(VisitorDispatcher visitor, ScriptWrappable* scriptWrappable) { } static void visitDOMWrapper(v8::Isolate*, ScriptWrappable*, const v8::Persistent<v8::Object>&); static void indexedPropertyGetterCustom(uint32_t, const v8::PropertyCallbackInfo<v8::Value>&); static void indexedPropertySetterCustom(uint32_t, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&); static void indexedPropertyDeleterCustom(uint32_t, const v8::PropertyCallbackInfo<v8::Boolean>&); static void namedPropertyGetterCustom(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&); static void namedPropertySetterCustom(v8::Local<v8::Name>, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&); static void namedPropertyQueryCustom(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Integer>&); static void namedPropertyDeleterCustom(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Boolean>&); static void namedPropertyEnumeratorCustom(const v8::PropertyCallbackInfo<v8::Array>&); static const int internalFieldCount = v8DefaultWrapperInternalFieldCount + 0; static void installConditionallyEnabledProperties(v8::Local<v8::Object>, v8::Isolate*) { } static void preparePrototypeObject(v8::Isolate*, v8::Local<v8::Object> prototypeObject, v8::Local<v8::FunctionTemplate> interfaceTemplate) { } }; template <> struct V8TypeOf<TestInterface3> { typedef V8TestInterface3 Type; }; } // namespace blink #endif // V8TestInterface3_h ```
Jacob Tyson (October 8, 1773July 16, 1848) was an American lawyer and politician from New York. Life Tyson attended public school in his youth. He studied law, was admitted to the bar, and practiced law. He was Supervisor of the Town of Castleton, Staten Island from 1811 to 1821. He was First Judge of the Richmond County Court from 1822 to 1840. Tyson was elected as a Crawford Democratic-Republican to the 18th United States Congress, holding office from March 4, 1823, to March 3, 1825. He was a member of the New York State Senate in 1828. He was buried at the Reformed Protestant Dutch Church Cemetery in Port Richmond, Staten Island. Sources The New York Civil List compiled by Franklin Benjamin Hough (pages 71, 127, 146 and 364; Weed, Parsons and Co., 1858) 1773 births 1848 deaths New York (state) state senators Politicians from Staten Island Town supervisors in New York (state) New York (state) state court judges Democratic-Republican Party members of the United States House of Representatives from New York (state)
```javascript exports.apiConfig = function () { 'use strict'; return { version: 4, routes: { echo: { 'GET': { authorizationType: 'BOOM' } }} }; }; exports.proxyRouter = function (event, context) { 'use strict'; context.succeed(event); }; ```
```xml import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import React from "react"; import { Link, MemoryRouter, Outlet, Route, Routes } from "react-router-dom"; import { STYLE_WRAPPER } from "../../util/test-utils"; import { MainNavPageInfo } from "./mainNavContext"; import { MainNavLayout } from "./MainNavLayout"; const TestPageA = () => { return ( <div> <MainNavPageInfo pageInfo={{ title: "breadcrumb-a1", id: "a1", path: "/a1" }} /> Page A1 <Link to="a2">go-a2</Link> <Outlet /> </div> ); }; const TestChildPageA = () => { return ( <div> <MainNavPageInfo pageInfo={{ title: "breadcrumb-a2", id: "a2", path: "/a1/a2" }} /> Page A2 <Link to="a3">go-a3</Link> <Outlet /> </div> ); }; const TestGrandChildPageA = () => { return ( <div> <MainNavPageInfo pageInfo={{ title: "breadcrumb-a3", id: "a3", path: "/a1/a2/a3" }} /> Page A3 <Link to="/b1/b2">go-b2</Link> </div> ); }; const TestPageB = () => { return ( <div> <MainNavPageInfo pageInfo={{ title: "breadcrumb-b1", id: "b1", path: "/b1" }} /> Page B1 <Outlet /> </div> ); }; const TestChildNonMainNavPageB = () => { return ( <div> {/* Not a Main Nav page */} Page B2 <Link to="b3">go-b3</Link> <Outlet /> </div> ); }; const TestGrandChildPageB = () => { return ( <div> <MainNavPageInfo pageInfo={{ title: "breadcrumb-b3", id: "b3", path: "/b1/b2/b3" }} /> Page B3 <Link to="/c">go-c</Link> </div> ); }; const TestPageC = () => { return ( <div> <MainNavPageInfo pageInfo={{ title: "breadcrumbc", id: "c", path: "/c" }} /> Page C </div> ); }; const TestApp = ({ location = "/" }: { location?: string }) => { return ( <STYLE_WRAPPER> <MemoryRouter initialEntries={[location]}> <Routes> <Route element={<MainNavLayout />}> <Route element={<TestPageA />} path="a1"> <Route element={<TestChildPageA />} path="a2"> <Route element={<TestGrandChildPageA />} path="a3" /> </Route> </Route> <Route element={<TestPageB />} path="b1"> <Route element={<TestChildNonMainNavPageB />} path="b2"> <Route element={<TestGrandChildPageB />} path="b3" /> </Route> </Route> <Route element={<TestPageC />} path="c" /> </Route> </Routes> </MemoryRouter> </STYLE_WRAPPER> ); }; describe("MainNavLayout", () => { it("navigates and renders breadcrumbs correctly", async () => { const user = userEvent.setup(); render(<TestApp location="/a1" />); await screen.findByText(/Page A1/); // No breadcrumbs when there is only 1 page expect(screen.queryByText(/breadcrumb-a1/)).not.toBeInTheDocument(); await user.click(screen.getByText(/go-a2/)); await screen.findByText(/Page A2/); expect(screen.getByText(/breadcrumb-a1/)).toBeInTheDocument(); expect(screen.getByText(/breadcrumb-a2/)).toBeInTheDocument(); await user.click(screen.getByText(/go-a3/)); await screen.findByText(/Page A3/); expect(screen.getByText(/breadcrumb-a1/)).toBeInTheDocument(); expect(screen.getByText(/breadcrumb-a2/)).toBeInTheDocument(); expect(screen.getByText(/breadcrumb-a3/)).toBeInTheDocument(); await user.click(screen.getByText(/go-b2/)); await screen.findByText(/Page B2/); // No breadcrumbs because only one of the pages is a main nav page expect(screen.queryByText(/breadcrumb-b1/)).not.toBeInTheDocument(); expect(screen.queryByText(/breadcrumb-b3/)).not.toBeInTheDocument(); await user.click(screen.getByText(/go-b3/)); await screen.findByText(/Page B3/); expect(screen.getByText(/breadcrumb-b1/)).toBeInTheDocument(); expect(screen.getByText(/breadcrumb-b3/)).toBeInTheDocument(); // Test that single non-parent pages work as well await user.click(screen.getByText(/go-c/)); await screen.findByText(/Page C/); expect(screen.queryByText(/breadcrumb-c/)).not.toBeInTheDocument(); }); }); ```
```javascript import React from 'react' import ReactTooltip from 'react-tooltip' import TextField, { enterKeyCode } from 'components/common/TextField' import { mount } from 'enzyme' describe('TextField', () => { const generateProps = () => { return { onChange: sinon.spy(), onEnterKey: sinon.spy(), label: 'label', text: 'text', rows: 1 } } it('should render the text field', () => { const props = generateProps() const textField = mount(<TextField {...props} />) assert(textField.find('label').text() === props.label) assert(textField.find('input').exists()) assert(textField.find('input').prop('value') === props.text) }) it('should render the text field using the textarea element if rows are > 2', () => { const props = generateProps() props.rows = 2 const textField = mount(<TextField {...props} />) assert(textField.find('textarea').exists()) assert(textField.find('textarea').prop('value') === props.text) }) it('should call onChange if there is some input', () => { const props = generateProps() const textField = mount(<TextField {...props} />) textField.find('input').simulate('change', {target: {value: 'input'}}) assert(props.onChange.calledOnce) }) it('should call onEnterKey if the enter key is pressed', () => { const props = generateProps() const textField = mount(<TextField {...props} />) textField.find('input').simulate('keydown', {keyCode: enterKeyCode, target: {value: ''}}) assert(props.onEnterKey.calledOnce) }) it('should not call onEnterKey if the other key is pressed', () => { const props = generateProps() const textField = mount(<TextField {...props} />) textField.find('input').simulate('keydown', {keyCode: 0, target: {value: ''}}) assert(props.onEnterKey.notCalled) }) it('should show the tooltip if there is information prop', () => { const props = generateProps() props.information = 'info' const textField = mount(<TextField {...props} />) assert(textField.find(ReactTooltip).exists()) }) }) ```
```jsx import React, { Component } from "react"; import PropTypes from "prop-types"; import { TransitionMotion, spring } from "react-motion"; import stripStyle from "react-motion/lib/stripStyle"; import shallowEqual from "shallowequal"; import omit from "lodash.omit"; import { buildTransform, positionToProperties } from "../utils/transformHelpers"; import { commonPropTypes, commonDefaultProps } from "../utils/commonProps"; import assertIsElement from "../utils/assertIsElement"; export default class extends Component { static propTypes = { ...commonPropTypes, springConfig: PropTypes.shape({ stiffness: PropTypes.number, damping: PropTypes.number, precision: PropTypes.number }) }; static defaultProps = { ...commonDefaultProps, springConfig: { stiffness: 60, damping: 14, precision: 0.1 } }; constructor(props) { super(props); this.state = this.doLayout(props); } componentWillReceiveProps(nextProps) { if (!shallowEqual(nextProps, this.props)) { this.setState(this.doLayout(nextProps)); } } doLayout(props) { const items = React.Children.toArray(props.children).map(element => { assertIsElement(element); return { key: element.key, data: { element } }; }); const { positions, gridWidth, gridHeight } = props.layout( items.map(item => ({ ...item.data.element.props, key: item.data.element.key })), props ); const styles = positions.map((position, i) => ({ ...items[i], style: { ...items[i].style, zIndex: 2, ...springify( props.entered(items[i].data.element.props, props, { gridWidth, gridHeight }), props.springConfig ), ...springify(positionToProperties(position), props.springConfig) } })); return { styles, gridWidth, gridHeight }; } willEnter = transitionStyle => { const { gridWidth, gridHeight } = this.state; const { enter } = this.props; return { ...stripStyle(transitionStyle.style), zIndex: 1, ...enter(transitionStyle.data.element.props, this.props, { gridWidth, gridHeight }) }; }; willLeave = transitionStyle => { const { exit, springConfig } = this.props; const { gridWidth, gridHeight } = this.state; const exitStyle = exit(transitionStyle.data.element.props, this.props, { gridWidth, gridHeight }); return { ...transitionStyle.style, zIndex: 0, ...springify(exitStyle, springConfig) }; }; render() { const { component: Parent, style, perspective, lengthUnit, angleUnit, ...rest } = omit(this.props, [ "itemHeight", "measured", "columns", "columnWidth", "gutterWidth", "gutterHeight", "layout", "enter", "entered", "exit", "springConfig", "duration", "easing" ]); const { styles, gridWidth, gridHeight } = this.state; return ( <TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave} > {interpolatedStyles => ( <Parent style={{ position: "relative", ...style, width: `${gridWidth}${lengthUnit}`, height: `${gridHeight}${lengthUnit}` }} {...rest} > {interpolatedStyles.map(config => { const { style: { opacity, zIndex }, data } = config; const Child = data.element.type; const transform = buildTransform(config.style, perspective, { length: lengthUnit, angle: angleUnit }); const itemProps = omit(data.element.props, [ "itemRect", "itemHeight" ]); return ( <Child key={data.element.key} {...itemProps} style={{ ...itemProps.style, position: "absolute", top: 0, left: 0, zIndex, opacity, transform, WebkitTransform: transform, msTransform: transform }} /> ); })} </Parent> )} </TransitionMotion> ); } } function springify(style, springConfig) { return Object.keys(style).reduce((obj, key) => { obj[key] = spring(style[key], springConfig); return obj; }, {}); } ```
Gregory David Massialas (born May 20, 1956) is an American foil fencer and fencing coach. Career A reserve for the 1976 Summer Olympics in Montreal, he was set to make his Olympic début at the Moscow Games in 1980, but did not compete due to the 66-team boycott of the games. He was one of 461 athletes to receive a Congressional Gold Medal the same year. He competed at the 1984 and 1988 Summer Olympics. He is the founder and head coach of the Massialas Foundation (MTEAM), a fencing club in San Francisco. Since 2012 he is the national coach of the United States senior foil team, which includes his own son Alexander. He brought the club to a No.1 world ranking, with each of its four members ranking individually in the Top 10 and Miles Chamley-Watson winning the 2013 World Fencing Championships. Massialas' daughter Sabrina, now a senior, is also a high-level foil fencer. See also List of USFA Division I National Champions References External links the Massialas Foundation official website 1956 births Living people American male foil fencers American fencing coaches American people of Greek descent Olympic fencers for the United States Fencers at the 1984 Summer Olympics Fencers at the 1988 Summer Olympics Cornell University alumni San Jose State University alumni Pan American Games medalists in fencing Pan American Games gold medalists for the United States Pan American Games silver medalists for the United States Pan American Games bronze medalists for the United States Congressional Gold Medal recipients Fencers at the 1979 Pan American Games Fencers at the 1983 Pan American Games Fencers at the 1987 Pan American Games
Shot in the Night (French: Coup de feu dans la nuit) is a 1943 French crime drama film directed by Robert Péguy and starring Mary Morgan, Henri Rollan, Jean Debucourt and Raymond Aimos. It is based on the 1922 play L’Avocat by Eugène Brieux. The film's sets were designed by the art director Marcel Mary. Synopsis An attractive young wife, unhappily married to a domineering husband is suspected of his murder when he discovered shot dead one night outside his country house. She is defended in court by an old friend who she has secretly loved for many years. Cast Mary Morgan as Lise du Coudrais Henri Rollan as Maître Martigny Jean Debucourt as Le juge d'instruction Raymond Aimos as Fortin - Le greffier Nane Germon as Pauline Charles Lemontier as Arnaud Monette Dinay as Toinette Jeanne Marie-Laurent as Madame Martigny mère Coutan-Lambert as Madame du Coudrais Solange Varenne as Marton Jeanne Stora as Mademoiselle du Coudrais Lise Donat as La cabaretière Jacques Grétillat as Monsieur du Coudrais Jean Meyer as Le baron Guy Parzy as Claude Lemercier Robert Allard as Billaud Jean-Louis Allibert as Un avocat Maurice Dorléac as Fronsac Marcel Vibert as L'avocat général André Carnège as Le président des Assises Marcel Pérès as Un contrebandier Rivers Cadet as Un contrebandier References Bibliography Bessy, Maurice & Chirat, Raymond. Histoire du cinéma français: encyclopédie des films, 1940–1950. Pygmalion, 1986 Burch, Noël & Sellier, Geneviève. The Battle of the Sexes in French Cinema, 1930–1956. Duke University Press, 2013. Rège, Philippe. Encyclopedia of French Film Directors, Volume 1. Scarecrow Press, 2009. External links 1943 films French drama films 1943 drama films French crime films 1943 crime films 1940s French-language films Films directed by Robert Péguy French black-and-white films 1940s French films French films based on plays fr:Coup de feu dans la nuit
```yaml name: SpaceEye description: Live satellite imagery for your desktop background. website: path_to_url category: Utilities repository: path_to_url keywords: - taskbar - toolbar - space - satellite - desktop wallpaper - live - earth - open source license: MIT ```
```python import random import emoji import pytest from _pytest.outcomes import Failed from appium.webdriver.connectiontype import ConnectionType from selenium.common.exceptions import TimeoutException, NoSuchElementException from tests import marks, run_in_parallel, transl from tests.base_test_case import MultipleSharedDeviceTestCase, create_shared_drivers from views.base_element import Button from views.sign_in_view import SignInView @pytest.mark.xdist_group(name="new_one_2") @marks.nightly class TestOneToOneChatMultipleSharedDevicesNewUi(MultipleSharedDeviceTestCase): def prepare_devices(self): self.drivers, self.loop = create_shared_drivers(2) self.device_1, self.device_2 = SignInView(self.drivers[0]), SignInView(self.drivers[1]) self.username_1, self.username_2 = 'sender', 'receiver' self.loop.run_until_complete(run_in_parallel(((self.device_1.create_user, {'enable_notifications': True, 'username': self.username_1}), (self.device_2.create_user, {'enable_notifications': True, 'username': self.username_2})))) self.home_1, self.home_2 = self.device_1.get_home_view(), self.device_2.get_home_view() self.homes = (self.home_1, self.home_2) self.profile_1, self.profile_2 = (home.get_profile_view() for home in self.homes) self.public_key_2 = self.home_2.get_public_key() self.profile_1.just_fyi("Sending contact request via Profile > Contacts") for home in (self.home_1, self.home_2): home.navigate_back_to_home_view() home.chats_tab.click() self.home_1.add_contact(self.public_key_2) self.home_2.just_fyi("Accepting contact request from activity centre") self.home_2.handle_contact_request(self.username_1) self.profile_1.just_fyi("Sending message to contact via Messages > Recent") self.chat_1 = self.home_1.get_chat(self.username_2).click() self.chat_1.send_message('hey') self.home_2.navigate_back_to_home_view() self.chat_2 = self.home_2.get_chat(self.username_1).click() self.message_1, self.message_2, self.message_3, self.message_4 = \ "Message 1", "Message 2", "Message 3", "Message 4" @marks.testrail_id(702730) def test_1_1_chat_message_reaction(self): message_from_sender = "Message sender" self.device_1.just_fyi("Sender start 1-1 chat, set 'thumbs-up' emoji and check counter") self.chat_1.send_message(message_from_sender) self.chat_1.chat_element_by_text(message_from_sender).wait_for_sent_state(120) self.chat_1.set_reaction(message_from_sender) message_sender = self.chat_1.chat_element_by_text(message_from_sender) message_sender.emojis_below_message().wait_for_element_text(1) self.device_2.just_fyi( "Receiver also sets 'thumbs-up' emoji and verifies counter on received message in 1-1 chat") message_receiver = self.chat_2.chat_element_by_text(message_from_sender) message_receiver.emojis_below_message(emoji="thumbs-up").wait_for_element_text(1, 90) self.chat_2.add_remove_same_reaction(message_from_sender) message_receiver.emojis_below_message(emoji="thumbs-up").wait_for_element_text(2) message_sender.emojis_below_message(emoji="thumbs-up").wait_for_element_text(2, 90) self.device_2.just_fyi( "Receiver removes 'thumbs-up' emoji and verify that counter will decrease for both users") self.chat_2.add_remove_same_reaction(message_from_sender) message_receiver.emojis_below_message(emoji="thumbs-up").wait_for_element_text(1) message_sender.emojis_below_message(emoji="thumbs-up").wait_for_element_text(1, 90) self.device_2.just_fyi("Receiver sets another reaction ('love'). Check it's shown for both sender and receiver") self.chat_2.set_reaction(message_from_sender, emoji="love") message_receiver.emojis_below_message(emoji="thumbs-up").wait_for_element_text(1) message_sender.emojis_below_message(emoji="thumbs-up").wait_for_element_text(1, 90) message_receiver.emojis_below_message(emoji="love").wait_for_element_text(1) message_sender.emojis_below_message(emoji="love").wait_for_element_text(1, 90) self.device_1.just_fyi("Sender votes for 'love' reaction. Check reactions counters") self.chat_1.add_remove_same_reaction(message_from_sender, emoji="love") message_receiver.emojis_below_message(emoji="thumbs-up").wait_for_element_text(1) message_sender.emojis_below_message(emoji="thumbs-up").wait_for_element_text(1) message_receiver.emojis_below_message(emoji="love").wait_for_element_text(2, 90) message_sender.emojis_below_message(emoji="love").wait_for_element_text(2) self.device_1.just_fyi("Check emojis info") message_sender.emojis_below_message(emoji="love").long_press_until_element_is_shown( self.chat_1.authors_for_reaction(emoji="love")) if not self.chat_1.user_list_element_by_name( self.username_1).is_element_displayed() or not self.chat_1.user_list_element_by_name( self.username_2).is_element_displayed(): self.errors.append("Incorrect users are shown for 'love' reaction.") self.chat_1.authors_for_reaction(emoji="thumbs-up").click() if not self.chat_1.user_list_element_by_name( self.username_1).is_element_displayed() or self.chat_1.user_list_element_by_name( self.username_2).is_element_displayed(): self.errors.append("Incorrect users are shown for 'thumbs-up' reaction.") self.chat_1.driver.press_keycode(4) self.errors.verify_no_errors() @marks.testrail_id(702782) def test_1_1_chat_emoji_send_reply_and_open_link(self): self.chat_1.navigate_back_to_chat_view() self.chat_2.navigate_back_to_chat_view() self.home_1.just_fyi("Check that can send emoji in 1-1 chat") emoji_name = random.choice(list(emoji.EMOJI_UNICODE)) emoji_unicode = emoji.EMOJI_UNICODE[emoji_name] self.chat_1.send_message(emoji.emojize(emoji_name)) for chat in self.chat_1, self.chat_2: if not chat.chat_element_by_text(emoji_unicode).is_element_displayed(): self.errors.append('Message with emoji was not sent or received in 1-1 chat') self.chat_1.quote_message(emoji_unicode) actual_text = self.chat_1.quote_username_in_message_input.text if actual_text != "You": self.errors.append( "'You' is not displayed in reply quote snippet replying to own message, '%s' instead" % actual_text) self.chat_1.just_fyi("Clear quote and check there is not snippet anymore") self.chat_1.cancel_reply_button.click() if self.chat_1.cancel_reply_button.is_element_displayed(): self.errors.append("Message quote kept in public chat input after it was cancelled") self.chat_1.just_fyi("Send reply") self.chat_1.quote_message(emoji_unicode) reply_to_message_from_sender = "hey, reply" self.chat_1.send_message(reply_to_message_from_sender) self.chat_1.just_fyi("Receiver verifies received reply...") if self.chat_2.chat_element_by_text(reply_to_message_from_sender).replied_message_text != emoji_unicode: self.errors.append("No reply received in 1-1 chat") else: self.chat_2.just_fyi("Device 2 sets a reaction on the message reply. Device 1 checks the reaction") self.chat_1.set_reaction(reply_to_message_from_sender) try: self.chat_1.chat_element_by_text( reply_to_message_from_sender).emojis_below_message().wait_for_element_text(1) except Failed: self.errors.append("Reply message reaction is not shown for the sender") self.home_1.just_fyi("Check that link can be opened and replied from 1-1 chat") reply = 'reply to link' url_message = 'Test with link: path_to_url here should be nothing unusual.' self.chat_1.send_message(url_message) self.chat_2.chat_element_by_text(url_message).wait_for_element(20) self.chat_2.chat_element_by_text(url_message).long_press_element_by_coordinate(rel_x=0.8, rel_y=0.8) self.chat_2.reply_message_button.click() self.chat_2.send_message(reply) replied_message = self.chat_1.chat_element_by_text(reply) if replied_message.replied_message_text != url_message: self.errors.append("Reply for '%s' not present in message received in public chat" % url_message) self.chat_2.just_fyi("Device 2 sets a reaction on the message with a link. Device 1 checks the reaction") self.chat_2.set_reaction(url_message) try: self.chat_1.chat_element_by_text(url_message).emojis_below_message().wait_for_element_text(1) except (Failed, NoSuchElementException): self.errors.append("Link message reaction is not shown for the sender") self.home_2.just_fyi("Check 'Open in Status' option") # url_to_open = 'path_to_url url_to_open = 'path_to_url self.chat_1.send_message(url_to_open) chat_element = self.chat_2.chat_element_by_text(url_to_open) if chat_element.is_element_displayed(120): chat_element.click_on_link_inside_message_body() web_view = self.chat_2.open_in_status_button.click() text_element = web_view.element_by_text("a free (libre) open source, mobile OS for Ethereum") sign_in_button = Button(self.chat_2.driver, xpath="//android.view.View[@content-desc='Sign in']") if not text_element.is_element_displayed(30) or not sign_in_button.is_element_displayed(30): self.errors.append('URL was not opened from 1-1 chat') else: self.errors.append("Message with URL was not received") self.errors.verify_no_errors() @marks.testrail_id(702731) def test_1_1_chat_pin_messages(self): self.home_1.just_fyi("Check that Device1 can pin own message in 1-1 chat") self.chat_2.navigate_back_to_home_view() self.home_2.chats_tab.click() self.home_2.get_chat(self.username_1).click() self.chat_1.send_message(self.message_1) self.chat_1.send_message(self.message_2) self.chat_1.chat_element_by_text(self.message_1).wait_for_status_to_be("Delivered") self.chat_1.pin_message(self.message_1, 'pin-to-chat') if not self.chat_1.chat_element_by_text(self.message_1).pinned_by_label.is_element_displayed(): self.drivers[0].fail("Message is not pinned!") self.home_1.just_fyi("Check that Device2 can pin Device1 message in 1-1 chat and two pinned " "messages are in Device1 profile") self.chat_2.pin_message(self.message_2, 'pin-to-chat') for chat_number, chat in enumerate([self.chat_1, self.chat_2]): chat.pinned_messages_count.wait_for_element_text(text="2", message="Pinned messages count is not 2 as expected!") chat.just_fyi("Check pinned messages are visible in Pinned panel for user %s" % (chat_number + 1)) chat.pinned_messages_count.click() for message in self.message_1, self.message_2: pinned_by = chat.pinned_messages_list.get_message_pinned_by_text(message) if pinned_by.is_element_displayed(): text = pinned_by.text.strip() if chat_number == 0: expected_text = "You" if message == self.message_1 else self.username_2 else: expected_text = "You" if message == self.message_2 else self.username_1 if text != expected_text: self.errors.append( "Pinned by '%s' doesn't match expected '%s' for user %s" % ( text, expected_text, chat_number + 1) ) else: self.errors.append( "Message '%s' is missed on Pinned messages list for user %s" % (message, chat_number + 1) ) chat.click_system_back_button() self.home_1.just_fyi("Check that Device1 can not pin more than 3 messages and 'Unpin' dialog appears") for message in (self.message_3, self.message_4): self.chat_1.send_message(message) self.chat_1.chat_element_by_text(message).wait_for_status_to_be("Delivered") self.chat_1.pin_message(message, 'pin-to-chat') # if not self.chat_1.pin_limit_popover.is_element_displayed(): # self.errors.append("Pin limit popover is not displayed when pinning more than 3 messages") self.chat_1.view_pinned_messages_button.click_until_presence_of_element(self.chat_1.pinned_messages_list) if self.chat_1.pinned_messages_list.get_pinned_messages_number() > 3 \ or self.chat_1.pinned_messages_list.message_element_by_text(self.message_4).is_element_displayed(): self.errors.append("Can pin more than 3 messages in chat") else: self.chat_1.pinned_messages_list.message_element_by_text(self.message_2).long_press_element() self.home_1.just_fyi("Unpin one message so that another could be pinned") unpin_element = self.chat_1.element_by_translation_id('unpin-from-chat') unpin_element.click_until_absense_of_element(desired_element=unpin_element) self.chat_1.pin_message(self.message_4, 'pin-to-chat') if not (self.chat_1.chat_element_by_text(self.message_4).pinned_by_label.is_element_displayed(30) and self.chat_2.chat_element_by_text(self.message_4).pinned_by_label.is_element_displayed(30)): self.errors.append("Message 4 is not pinned in chat after unpinning previous one") self.home_1.just_fyi("Check pinned messages are visible in Pinned panel for both users") for chat_number, chat in enumerate([self.chat_1, self.chat_2]): count = chat.pinned_messages_count.text if count != '3': self.errors.append("Pinned messages count is %s but should be 3 for user %s" % (count, chat_number + 1)) self.home_1.just_fyi("Unpin one message and check it's unpinned for another user") self.chat_2.tap_by_coordinates(500, 100) self.chat_1.view_pinned_messages_button.click_until_presence_of_element(self.chat_1.pinned_messages_list) pinned_message = self.chat_1.pinned_messages_list.message_element_by_text(self.message_4) unpin_element = self.chat_1.element_by_translation_id("unpin-from-chat") pinned_message.long_press_until_element_is_shown(unpin_element) unpin_element.click_until_absense_of_element(unpin_element) # try: # self.chat_2.chat_element_by_text(self.message_4).pinned_by_label.wait_for_invisibility_of_element() # except TimeoutException: # self.errors.append("Message_4 is not unpinned!") for chat_number, chat in enumerate([self.chat_1, self.chat_2]): try: chat.pinned_messages_count.wait_for_element_text(text='2', wait_time=20) except Failed: self.errors.append( "Pinned messages count is not 2 after unpinning the last pinned message for user %s" % ( chat_number + 1) ) self.errors.verify_no_errors() @marks.testrail_id(702745) @marks.smoke def test_1_1_chat_non_latin_messages_stack_update_profile_photo(self): self.home_1.navigate_back_to_home_view() self.home_1.profile_button.click() self.profile_1.edit_profile_picture(image_index=2) self.chat_2.just_fyi("Send messages with non-latin symbols") self.home_1.click_system_back_button() self.home_1.chats_tab.click() self.home_1.get_chat(self.username_2).click() self.chat_1.send_message("just a text") # Sending a message here so the next ones will be in a separate line self.home_2.navigate_back_to_home_view() self.home_2.chats_tab.click() self.home_2.get_chat(self.username_1).click() messages = ['hello', 'Cmo ests tu ao?', ', ', ' '] for message in messages: self.chat_2.send_message(message) if not self.chat_1.chat_element_by_text(message).is_element_displayed(30): self.errors.append("Message with text '%s' was not received" % message) self.chat_2.just_fyi("Checking updated member photo, timestamp and username on message") self.chat_2.hide_keyboard_if_shown() try: timestamp = self.chat_2.chat_element_by_text(messages[0]).timestamp sent_time_variants = self.chat_2.convert_device_time_to_chat_timestamp() if timestamp not in sent_time_variants: self.errors.append( 'Timestamp on message %s does not correspond expected %s' % (timestamp, sent_time_variants)) except NoSuchElementException: self.errors.append("No timestamp on message %s" % messages[0]) for message in [messages[1], messages[2]]: if self.chat_2.chat_element_by_text(message).member_photo.is_element_displayed(): self.errors.append('%s is not stack to 1st(they are sent in less than 5 minutes)!' % message) self.chat_1.just_fyi("Sending message") message = 'profile_photo' self.chat_1.send_message(message) self.chat_2.chat_element_by_text(message).wait_for_visibility_of_element(30) self.chat_1.just_fyi("Go back to chat view and checking that profile photo is updated") if not self.chat_2.chat_message_input.is_element_displayed(): self.home_2.get_chat(self.username_1).click() if self.chat_2.chat_element_by_text(message).member_photo.is_element_differs_from_template("member3.png", diff=7): self.errors.append("Image of user in 1-1 chat is too different from template!") self.errors.verify_no_errors() @marks.testrail_id(702813) def test_1_1_chat_push_emoji(self): message_no_pn, message = 'No PN', 'Text push notification' self.home_1.navigate_back_to_home_view() self.home_2.navigate_back_to_home_view() self.home_2.profile_button.click() self.home_1.chats_tab.click() self.device_2.just_fyi("Device 2 puts app on background being on Profile view to receive PN with text") app_package = self.device_2.driver.current_package self.device_2.put_app_to_background() self.device_2.open_notification_bar() if not self.chat_1.chat_message_input.is_element_displayed(): self.home_1.get_chat(self.username_2).click() self.chat_1.send_message(message) self.device_1.just_fyi("Device 1 puts app on background to receive emoji push notification") self.device_1.navigate_back_to_home_view() self.device_1.profile_button.click() self.device_2.just_fyi("Check text push notification and tap it") if not self.home_2.get_pn(message): self.device_2.click_system_back_button() self.device_2.driver.activate_app(app_package) self.device_2.driver.fail("Push notification with text was not received") chat_2 = self.device_2.click_upon_push_notification_by_text(message) self.device_2.just_fyi("Send emoji message to Device 1 while it's on background") self.device_1.put_app_to_background() self.device_1.open_notification_bar() emoji_message = random.choice(list(emoji.EMOJI_UNICODE)) emoji_unicode = emoji.EMOJI_UNICODE[emoji_message] chat_2.send_message(emoji.emojize(emoji_message)) self.device_1.just_fyi("Device 1 checks PN with emoji") if not self.device_1.element_by_text_part(emoji_unicode).is_element_displayed(120): self.device_1.click_system_back_button() self.device_1.driver.activate_app(app_package) self.device_1.driver.fail("Push notification with emoji was not received") chat_1 = self.device_1.click_upon_push_notification_by_text(emoji_unicode) self.device_1.just_fyi("Check Device 1 is actually on chat") if not (chat_1.element_by_text_part(message).is_element_displayed(15) and chat_1.element_by_text_part(emoji_unicode).is_element_displayed()): self.device_1.driver.fail("Failed to open chat view after tap on PN") self.device_1.just_fyi("Checks there are no PN after message was seen") [home.open_notification_bar() for home in self.homes] if (self.device_2.element_by_text_part(message).is_element_displayed() or self.device_1.element_by_text_part(emoji_unicode).is_element_displayed()): self.errors.append("PN are keep staying after message was seen by user") self.errors.verify_no_errors() @marks.testrail_id(702855) def test_1_1_chat_edit_message(self): for home in self.homes: home.navigate_back_to_home_view() home.chats_tab.click() self.home_2.get_chat(self.username_1).click() self.home_1.get_chat(self.username_2).click() self.device_2.just_fyi( "Device 2 sends text message and edits it in 1-1 chat. Device 2 checks edited message is shown") message_before_edit_1_1, message_after_edit_1_1 = "Message before edit 1-1", "AFTER" self.chat_2.send_message(message_before_edit_1_1) self.chat_2.chat_element_by_text(message_before_edit_1_1).wait_for_status_to_be("Delivered") self.chat_2.edit_message_in_chat(message_before_edit_1_1, message_after_edit_1_1) message_text_after_edit = message_after_edit_1_1 + ' (Edited)' chat_element = self.chat_1.chat_element_by_text(message_text_after_edit) if not chat_element.is_element_displayed(30): self.errors.append('No edited message in 1-1 chat displayed') else: self.device_1.just_fyi("Device 1 sets a reaction on the edited message. Device 2 checks the reaction") self.chat_1.set_reaction(message_text_after_edit) try: self.chat_1.chat_element_by_text( message_text_after_edit).emojis_below_message().wait_for_element_text(1) except Failed: self.errors.append("Message reaction is not shown for the sender") self.errors.verify_no_errors() @marks.testrail_id(703391) def test_1_1_chat_send_image_save_and_share(self): if not self.chat_2.chat_message_input.is_element_displayed(): self.chat_2.navigate_back_to_home_view() self.home_2.chats_tab.click() self.home_2.get_chat(self.username_1).click() if not self.chat_1.chat_message_input.is_element_displayed(): self.chat_1.navigate_back_to_home_view() self.home_1.chats_tab.click() self.home_1.get_chat(self.username_2).click() self.chat_1.just_fyi("Device 1 sends an image") image_description = "test image" self.chat_1.send_images_with_description(description=image_description, indexes=[2]) self.chat_2.just_fyi("Device 2 checks image message") if not self.chat_2.chat_element_by_text(image_description).is_element_displayed(30): self.chat_2.hide_keyboard_if_shown() self.chat_2.chat_element_by_text(image_description).wait_for_visibility_of_element(30) if not self.chat_2.chat_element_by_text( image_description).image_in_message.is_element_image_similar_to_template('saucelabs_sauce_chat.png'): self.errors.append("Not expected image is shown to the receiver.") for chat in self.chat_1, self.chat_2: chat.just_fyi("Open the image and share it") if not chat.chat_element_by_text(image_description).image_in_message.is_element_displayed(): chat.hide_keyboard_if_shown() chat.chat_element_by_text(image_description).image_in_message.click() chat.share_image_icon_button.click() chat.element_starts_with_text("Drive").click() try: chat.wait_for_current_package_to_be('com.google.android.apps.docs') except TimeoutException: self.errors.append( "%s can't share an image via Gmail." % ("Sender" if chat is self.chat_1 else "Receiver")) chat.navigate_back_to_chat_view() for chat in self.chat_1, self.chat_2: chat.just_fyi("Open the image and save it") device_name = "sender" if chat is self.chat_1 else "receiver" chat.chat_element_by_text(image_description).image_in_message.click() chat.view_image_options_button.click() chat.save_image_icon_button.click() toast_element = chat.toast_content_element if toast_element.is_element_displayed(): toast_element_text = toast_element.text if toast_element_text != chat.get_translation_by_key("photo-saved"): self.errors.append( "Shown message '%s' doesn't match expected '%s' after saving an image for %s." % ( toast_element_text, chat.get_translation_by_key("photo-saved"), device_name)) else: self.errors.append("Message about saving a photo is not shown for %s." % device_name) chat.navigate_back_to_chat_view() for chat in self.chat_1, self.chat_2: chat.just_fyi("Check that image is saved in gallery") chat.show_images_button.click() chat.allow_all_button.click_if_shown() if not chat.get_image_by_index(0).is_element_image_similar_to_template("saucelabs_sauce_gallery.png"): self.errors.append( "Image is not saved to gallery for %s." % ("sender" if chat is self.chat_1 else "receiver")) chat.click_system_back_button() self.errors.verify_no_errors() @marks.testrail_id(702733) def test_1_1_chat_text_message_delete_push_disappear(self): if not self.chat_2.chat_message_input.is_element_displayed(): self.chat_2.navigate_back_to_home_view() self.home_2.chats_tab.click() self.home_2.get_chat(self.username_1).click() if not self.chat_1.chat_message_input.is_element_displayed(): self.chat_1.navigate_back_to_home_view() self.home_1.chats_tab.click() self.home_1.get_chat(self.username_2).click() app_package = self.chat_1.driver.current_package self.device_2.just_fyi("Verify Device1 can not edit and delete received message from Device2") message_after_edit_1_1 = 'smth I should edit' message_to_delete_for_me = 'message to delete for me' self.chat_2.send_message(message_after_edit_1_1) self.chat_2.chat_element_by_text(message_after_edit_1_1).wait_for_status_to_be("Delivered") chat_1_element = self.chat_1.chat_element_by_text(message_after_edit_1_1) chat_1_element.long_press_element() for action in ("edit", "delete-for-everyone"): if self.chat_1.element_by_translation_id(action).is_element_displayed(): self.errors.append('Option to %s someone else message available!' % action) self.home_1.tap_by_coordinates(500, 100) self.device_2.just_fyi("Delete message for me and check it is only deleted for the author") self.chat_2.send_message(message_to_delete_for_me) try: timeout = 60 self.chat_2.chat_element_by_text(message_to_delete_for_me).wait_for_status_to_be("Delivered", timeout) self.chat_2.delete_message_in_chat(message_to_delete_for_me, everyone=False) except TimeoutException: self.errors.append("Message status was not changed to 'Delivered' after %s s" % timeout) else: if not self.chat_2.chat_element_by_text(message_to_delete_for_me).is_element_disappeared(20): self.errors.append("Deleted for me message is shown in chat for the author of message") if not self.chat_2.element_by_translation_id('message-deleted-for-you').is_element_displayed(20): self.errors.append("System message about deletion for you is not displayed") if not self.chat_1.chat_element_by_text(message_to_delete_for_me).is_element_displayed(20): self.errors.append("Deleted for me message is deleted for both users") self.device_2.just_fyi("Delete message for everyone and check it is not shown in chat preview on home") self.chat_2.delete_message_in_chat(message_after_edit_1_1) for chat in (self.chat_2, self.chat_1): if chat.chat_element_by_text(message_after_edit_1_1).is_element_displayed(30): self.errors.append("Deleted message is shown in chat view for 1-1 chat") self.chat_1.navigate_back_to_home_view() if self.home_1.element_by_text(message_after_edit_1_1).is_element_displayed(30): self.errors.append("Deleted message is shown on chat element on home screen") self.device_2.just_fyi("Send one more message and check that PN will be deleted with message deletion") message_to_delete = 'DELETE ME' self.home_1.put_app_to_background() self.home_1.open_notification_bar() self.chat_2.send_message(message_to_delete) self.chat_2.chat_element_by_text(message_to_delete).wait_for_sent_state() if not self.home_1.get_pn(message_to_delete): self.home_1.click_system_back_button() self.device_2.driver.activate_app(app_package) self.errors.append("Push notification doesn't appear") self.chat_2.delete_message_in_chat(message_to_delete) pn_to_disappear = self.home_1.get_pn(message_to_delete) if pn_to_disappear: if not pn_to_disappear.is_element_disappeared(90): self.errors.append("Push notification was not removed after initial message deletion") self.errors.verify_no_errors() @pytest.mark.xdist_group(name="new_six_2") @marks.nightly class TestOneToOneChatMultipleSharedDevicesNewUiTwo(MultipleSharedDeviceTestCase): def prepare_devices(self): self.drivers, self.loop = create_shared_drivers(2) self.device_1, self.device_2 = SignInView(self.drivers[0]), SignInView(self.drivers[1]) self.username_1, self.username_2 = 'sender', 'receiver' self.loop.run_until_complete(run_in_parallel(((self.device_1.create_user, {'enable_notifications': True, 'username': self.username_1}), (self.device_2.create_user, {'enable_notifications': True, 'username': self.username_2})))) self.home_1, self.home_2 = self.device_1.get_home_view(), self.device_2.get_home_view() self.homes = (self.home_1, self.home_2) self.profile_1, self.profile_2 = (home.get_profile_view() for home in self.homes) self.public_key_2 = self.home_2.get_public_key() self.profile_1.just_fyi("Sending contact request via Profile > Contacts") for home in (self.home_1, self.home_2): home.navigate_back_to_home_view() home.chats_tab.click() self.home_1.add_contact(self.public_key_2) self.home_2.just_fyi("Accepting contact request from activity centre") self.home_2.handle_contact_request(self.username_1) self.profile_1.just_fyi("Sending message to contact via Messages > Recent") self.chat_1 = self.home_1.get_chat(self.username_2).click() self.chat_1.send_message('hey') self.home_2.navigate_back_to_home_view() self.chat_2 = self.home_2.get_chat(self.username_1).click() self.message_1, self.message_2, self.message_3, self.message_4 = \ "Message 1", "Message 2", "Message 3", "Message 4" @marks.skip # ToDo: can't be implemented with current SauceLabs emulators screen resolution def test_1_1_chat_send_image_with_camera(self): self.chat_1.just_fyi("Device 1 sends a camera image") image_description = "camera test" self.chat_1.send_image_with_camera(description=image_description) for chat in self.chat_1, self.chat_2: chat_name = "sender" if chat.driver.number == 0 else "receiver" chat.just_fyi("%s checks image message" % chat_name.capitalize()) chat_element = chat.chat_element_by_text(image_description) if chat_element.is_element_displayed(30): if not chat_element.image_in_message.is_element_image_similar_to_template('saucelabs_camera_image.png'): self.errors.append("Not expected image is shown to the %s." % chat_name) else: self.errors.append("Message with camera image is not shown in chat for %s" % chat_name) self.errors.verify_no_errors() @marks.testrail_id(702783) def test_1_1_chat_is_shown_message_sent_delivered_from_offline(self): self.home_1.just_fyi('Turn on airplane mode and check that offline status is shown on home view') for home in self.homes: home.driver.set_network_connection(ConnectionType.AIRPLANE_MODE) # Not implemented yet # self.home_1.connection_offline_icon.wait_and_click(20) # for element in self.home_1.not_connected_to_node_text, self.home_1.not_connected_to_peers_text: # if not element.is_element_displayed(): # self.errors.append( # 'Element "%s" is not shown in Connection status screen if device is offline' % element.locator) # self.home_1.click_system_back_button() message_1 = 'test message' self.home_2.just_fyi('Device2 checks "Sending" status when sending message from offline') if not self.chat_2.chat_message_input.is_element_displayed(): self.home_2.chats_tab.click() self.home_2.get_chat(self.username_1).click() self.chat_2.send_message(message_1) status = self.chat_2.chat_element_by_text(message_1).status if not (status == 'Sending' or status == 'Sent'): self.errors.append('Message status is not "Sending", it is "%s"!' % status) self.home_2.just_fyi('Device2 goes back online and checks that status of the message is changed to "delivered"') for home in self.homes: home.driver.set_network_connection(ConnectionType.ALL_NETWORK_ON) self.home_1.just_fyi('Device1 goes back online and checks that 1-1 chat will be fetched') if not self.chat_1.chat_element_by_text(message_1).is_element_displayed(120): self.errors.append("Message was not delivered after resending from offline") self.home_2.just_fyi('Device1 goes back online and checks that 1-1 chat will be fetched') try: self.chat_2.chat_element_by_text(message_1).wait_for_status_to_be(expected_status='Delivered', timeout=120) except TimeoutException as e: self.errors.append('%s after back up online!' % e.msg) self.errors.verify_no_errors() @marks.testrail_id(703496) def test_1_1_chat_mute_chat(self): self.home_1.navigate_back_to_home_view() self.home_1.chats_tab.click() self.home_1.just_fyi("Mute chat") self.home_1.mute_chat_long_press(self.username_2) muted_message = "should be muted" self.chat_2.send_message(muted_message) chat = self.home_1.get_chat(self.username_2) if chat.new_messages_counter.is_element_displayed(30) or self.home_1.chats_tab.counter.is_element_displayed(10): self.errors.append("New messages counter is shown after mute") if not chat.chat_preview.text.startswith(muted_message): self.errors.append("Message text '%s' is not shown in chat preview after mute" % muted_message) chat.click() if not self.chat_1.chat_element_by_text(muted_message).is_element_displayed(30): self.errors.append("Message '%s' is not shown in chat for receiver after mute" % muted_message) self.chat_1.just_fyi("Unmute chat") self.chat_1.navigate_back_to_home_view() chat.long_press_element() if self.home_1.mute_chat_button.text != transl["unmute-chat"]: self.errors.append("Chat is not muted") expected_text = "Muted until you turn it back on" if not self.home_1.element_by_text(expected_text).is_element_displayed(): self.errors.append("Text '%s' is not shown for muted chat" % expected_text) self.home_1.mute_chat_button.click() unmuted_message = "after unmute" self.chat_2.send_message(unmuted_message) if not chat.new_messages_counter.is_element_displayed( 30) or not self.home_1.chats_tab.counter.is_element_displayed(10): self.errors.append("New messages counter is not shown after unmute") if not chat.chat_preview.text.startswith(unmuted_message): self.errors.append("Message text '%s' is not shown in chat preview after unmute" % unmuted_message) chat.click() if not self.chat_1.chat_element_by_text(unmuted_message).is_element_displayed(30): self.errors.append("Message '%s' is not shown in chat for receiver after unmute" % unmuted_message) self.errors.verify_no_errors() @marks.testrail_id(702784) def test_1_1_chat_delete_via_long_press_relogin(self): self.home_2.navigate_back_to_home_view() self.home_2.chats_tab.click() self.home_2.get_chat(self.username_1).click() self.chat_2.chat_message_input.wait_for_visibility_of_element() self.home_2.just_fyi("Getting chat history") chat_history = list() for element in self.chat_2.chat_element_by_text(text='').message_text_content.find_elements(): chat_history.append(element.text) if not chat_history: self.errors.append("No chat history was loaded") self.home_2.just_fyi("Deleting chat via delete button and check it will not reappear after relaunching app") self.home_2.navigate_back_to_home_view() self.home_2.chats_tab.click() self.home_2.delete_chat_long_press(username=self.username_1) chat = self.home_2.get_chat_from_home_view(self.username_1) if chat.is_element_displayed(): self.errors.append("Deleted '%s' chat is shown, but the chat has been deleted" % self.username_1) self.home_2.reopen_app() if chat.is_element_displayed(15): self.errors.append( "Deleted chat '%s' is shown after re-login, but the chat has been deleted" % self.username_1) chat.click() else: self.home_2.contacts_tab.click() chat.click() self.chat_2.profile_send_message_button.click() lost_messages = list() for message_text in chat_history: if not self.chat_2.chat_element_by_text(message_text).is_element_displayed(): lost_messages.append(message_text) if lost_messages: self.errors.append("Message(s) missed in 1-1 chat after deleting the chat and relogin: %s" % lost_messages) self.errors.verify_no_errors() ```
Pisti Q'asa (Aymara and Quechua pisti influenca, a common cold or plague, Quechua q'asa mountain pass, Hispanicized spelling Pistijasa) is a mountain in the Wansu mountain range in the Andes of Peru. It is located in the Arequipa Region, La Unión Province, Huaynacotas District. Pisti Q'asa lies southwest of Puka Urqu and northwest of P'umpu Q'asa. References Mountains of Peru Mountains of Arequipa Region
```smalltalk using Microsoft.AspNetCore.Identity; namespace Northwind.Infrastructure.Identity { public class ApplicationUser : IdentityUser { } } ```
Legal Mavericks (; literally “Crossing the Line") is a Legal, Crime, Detective television drama created by Lam Chi-wah and TVB. It began principal photography in October 2016. It aired concurrently on TVB Jade, and iQiyi. It stars Vincent Wong, Sisley Choi, Ali Lee, Owen Cheung, Pal Sinn, Tracy Chu, Gilbert Lam, Quinn Ho and Hugo Wong in the first season. The second season of this drama aired in 2020. Synopsis Since losing his eyesight in an accident, Man Sun-Hop has been continually harassed and despised. But instead, his determination and perseverance are so reinforced that he has qualified as a barrister. He has also developed an acute sense beyond sight which helps him to gain the status of Blind Legal Knight in the legal profession. However, nobody really knows his true character. Fortunately, Kuk Yat-Ha, his flatmate and private detective, and Chiu Ching-Mui, a legal executive with mob connections, are two buddies he can always rely on. The trio is known as the "Three Sword Fighters" who defy the powerful and are always ready to seek justice for the underprivileged. Sun-Hop’s provocative style has aroused the fancy of judge Wong Lai-Fan, which leads to her flirting unabashedly at him. Expanded to a quartet, their fate encounters turbulent changes while handling challenging legal cases. The reappearance of Sun-Hop’s father, Man Gun-Ying, and Tai Tin-Yan, his ex-girlfriend from college, further complicates the situation, which Sun-Hop may not be able to unravel with his legal mastery. Cast and characters Vincent Wong as Hope Man San-hap (), a blind barrister who strives for justice for the disadvantaged, using his other heightened senses and legally controversial methods to seek truths behind his court cases. Sisley Choi as Deanie "Dino" Chiu Ching-mui (), a legal executive working for Hope, who has a heroic spirit due to her mafia family background. In addition to being a law clerk, she also owns a bar called Pledge. Ali Lee as Cherry "Never" Wong Lai-fan (), a district court judge who is unafraid to challenge the conservative nature of the legal system. Owen Cheung as Gogo Kuk Yat-ha (), an ex-policeman turned private investigator due to an accident whilst investigating T.Y.. He becomes Hope Man's roommate. Pal Sinn as T.Y. Tai Tak-yan (), a cruel and ruthless businessman who has terrible relations with his two children due to his hunger for power. He is Yanice's father. Tracy Chu as Yanice Tai Tin-yan (), an ophthalmologist who is constantly at heads with her father due to his problematic parenting methods. She is Hope Man's ex-girlfriend from university. Gilbert Lam, as Gotham Wei Gwok-haam (), a famous and arrogant lawyer. He is one of Hope Man's major recurring opponents in court. Former mentor of Never and Walter Quinn Ho as Luk Ka Yat (), a friend of Gogo working at the police station. Hugo Wong as Walter Wa Ye (), a prosecutor who is skeptical of Hope Man's questionable methods of treating court cases. Jack Hui as Tai Tin-yau (), T.Y.'s son and Yanice's older brother. He was mentally and physical abuse by his father , Tai Tak-yan . He turn himself to police in episode 7 for illegal detention and mentally abusing of Suki . Law Lok-lam as Man Gan-ying (), Hope's father, who abandoned Hope at the age of 6 not long after he went blind. He is diagnosed with ALS. Chun Wong as Chiu Cheong-Fung (), Dino's father, an ex prominent member of the mafia. William Chak as Aiden Ching Lap-Kiu (), Yanice's ex-fiancé. Toby Chan as Annie (Poon On) (), a male-to-female transgender. Kindergarten Teacher , Friend of Deanie. client of Hope Man , defence of the Transgender sexual assault case ( Episode 10-13) Li Fung Bob Cheung as Lau Chi-Sum (), a mentally-disabled person framed for giving poison to dogs. A client of Hope Man , defence of the Mentally handicapped poison dog case (Episode 1 - 2) Raymond Chiu as Henry (Ah Chun), Friend of Gogo Ho Chun-hin as Liu Ting, gang leader who works for Tai Tak-yan. Zoie Tam as Ngai Yu-Chun (), a client of Hope Man, defence of the Female performance artist assaulting case (Episode 2 - 3 ) Fung So-bor as Mrs. Lau , mother of Lau Chi-sim Fanny Lee as Bo Bui-yee (), Hope Man's landlord and Gogo's aunt. Tong Chun-ming as Dragon , employee of Pledge bar Tse Ho-yat as Tiger , employee of Pledge bar Virginia Lau as Zhu , employee of Pledge bar Hebe Chan as Hillary, Poon On's ex girlfriend before Poon On undergoes gender transformation. Initially, refuses to help female transgender, Poon On testify in a sexual assault case because Hillary does not want her current fiancé to find out she dated a transgender. Poon Fong-fong as Kindergarten principal , Former supervisor of Annie (Poon On) Nicole Wan as Mrs.Wu , mother of David was a student of Annie. She accused Annie of alleged indecent in tennis court female locker room because her husband is a homosexual and she targeted discriminate against them. Otto Chan (actor) as Hilton , husband of Mrs.Wu and secretly a homosexual who has an affair with a physical trainer , Mountain Man Yeung as Fong Kin Chung , Husband of Yeung Mei Ling and father of Sing , client of Hope Man , defence of the Neglect of child care case (Episode 7-10) Janice Shum as Yeung Mei Ling , Stepmother of Sing , client of Hope Man , defence of the Neglect of child care case (Episode 7-10) Kimmi Tsui as Lee Wai Sze , Biological mother of Sing. Scheme and framed both Fong Kin Chung and Yeung Mei Ling for neglecting and child abuse to gain back the custody of kid Sing Chiu Lok-yin as Rivet , lackey of Liu Ting Aaryn Cheung as Wu , employee of Pledge bar Critical reception Legal Mavericks received positive responses. On Douban, a Chinese media database, the drama received a rating of 7.9 out of 10 based on 5000+ votes. The cast of Legal Mavericks won numerous awards the 2017 StarHub TVB Awards: FAVOURITE TVB ACTOR - Vincent Wong FAVOURITE TVB ACTRESS - Ali Lee FAVOURITE TVB SUPPORTING ACTOR - Owen Cheung FAVOURITE TVB FEMALE TV CHARACTERS - Sisley Choi and Tracy Chu Vincent Wong won the Best Actor award at the 2017 TVB Anniversary Awards, and Sisley Choi won the Most Popular Female Character award with her role as Deanie Chiu. In 2018, New York Festivals awarded Legal Mavericks as finalists in Best Screenplay and in Best Entertainment Program Open & Titles. References TVB dramas Hong Kong action television series 2010s Hong Kong television series Hong Kong crime television series
```objective-c /** * @file lv_examples.h * */ #ifndef LV_EXAMPLES_H #define LV_EXAMPLES_H #ifdef __cplusplus extern "C" { #endif /********************* * INCLUDES *********************/ #include "../lvgl.h" #include "anim/lv_example_anim.h" #include "event/lv_example_event.h" #include "get_started/lv_example_get_started.h" #include "layouts/lv_example_layout.h" #include "libs/lv_example_libs.h" #include "others/lv_example_others.h" #include "porting/osal/lv_example_osal.h" #include "scroll/lv_example_scroll.h" #include "styles/lv_example_style.h" #include "widgets/lv_example_widgets.h" /********************* * DEFINES *********************/ /********************** * TYPEDEFS **********************/ /********************** * GLOBAL PROTOTYPES **********************/ /********************** * MACROS **********************/ #ifdef __cplusplus } /*extern "C"*/ #endif #endif /*LV_EXAMPLES_H*/ ```
```protocol buffer /* path_to_url Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ // This file was autogenerated by go-to-protobuf. Do not edit it manually! syntax = "proto2"; package k8s.io.api.discovery.v1beta1; import "k8s.io/api/core/v1/generated.proto"; import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto"; import "k8s.io/apimachinery/pkg/runtime/generated.proto"; import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; // Package-wide variables from generator "generated". option go_package = "v1beta1"; // Endpoint represents a single logical "backend" implementing a service. message Endpoint { // addresses of this endpoint. The contents of this field are interpreted // according to the corresponding EndpointSlice addressType field. Consumers // must handle different types of addresses in the context of their own // capabilities. This must contain at least one address but no more than // 100. // +listType=set repeated string addresses = 1; // conditions contains information about the current status of the endpoint. optional EndpointConditions conditions = 2; // hostname of this endpoint. This field may be used by consumers of // endpoints to distinguish endpoints from each other (e.g. in DNS names). // Multiple endpoints which use the same hostname should be considered // fungible (e.g. multiple A values in DNS). Must be lowercase and pass DNS // Label (RFC 1123) validation. // +optional optional string hostname = 3; // targetRef is a reference to a Kubernetes object that represents this // endpoint. // +optional optional k8s.io.api.core.v1.ObjectReference targetRef = 4; // topology contains arbitrary topology information associated with the // endpoint. These key/value pairs must conform with the label format. // path_to_url // Topology may include a maximum of 16 key/value pairs. This includes, but // is not limited to the following well known keys: // * kubernetes.io/hostname: the value indicates the hostname of the node // where the endpoint is located. This should match the corresponding // node label. // * topology.kubernetes.io/zone: the value indicates the zone where the // endpoint is located. This should match the corresponding node label. // * topology.kubernetes.io/region: the value indicates the region where the // endpoint is located. This should match the corresponding node label. // This field is deprecated and will be removed in future api versions. // +optional map<string, string> topology = 5; // nodeName represents the name of the Node hosting this endpoint. This can // be used to determine endpoints local to a Node. This field can be enabled // with the EndpointSliceNodeName feature gate. // +optional optional string nodeName = 6; } // EndpointConditions represents the current condition of an endpoint. message EndpointConditions { // ready indicates that this endpoint is prepared to receive traffic, // according to whatever system is managing the endpoint. A nil value // indicates an unknown state. In most cases consumers should interpret this // unknown state as ready. For compatibility reasons, ready should never be // "true" for terminating endpoints. // +optional optional bool ready = 1; // serving is identical to ready except that it is set regardless of the // terminating state of endpoints. This condition should be set to true for // a ready endpoint that is terminating. If nil, consumers should defer to // the ready condition. This field can be enabled with the // EndpointSliceTerminatingCondition feature gate. // +optional optional bool serving = 2; // terminating indicates that this endpoint is terminating. A nil value // indicates an unknown state. Consumers should interpret this unknown state // to mean that the endpoint is not terminating. This field can be enabled // with the EndpointSliceTerminatingCondition feature gate. // +optional optional bool terminating = 3; } // EndpointPort represents a Port used by an EndpointSlice message EndpointPort { // The name of this port. All ports in an EndpointSlice must have a unique // name. If the EndpointSlice is dervied from a Kubernetes service, this // corresponds to the Service.ports[].name. // Name must either be an empty string or pass DNS_LABEL validation: // * must be no more than 63 characters long. // * must consist of lower case alphanumeric characters or '-'. // * must start and end with an alphanumeric character. // Default is empty string. optional string name = 1; // The IP protocol for this port. // Must be UDP, TCP, or SCTP. // Default is TCP. optional string protocol = 2; // The port number of the endpoint. // If this is not specified, ports are not restricted and must be // interpreted in the context of the specific consumer. optional int32 port = 3; // The application protocol for this port. // This field follows standard Kubernetes label syntax. // Un-prefixed names are reserved for IANA standard service names (as per // RFC-6335 and path_to_url // Non-standard protocols should use prefixed names such as // mycompany.com/my-custom-protocol. // +optional optional string appProtocol = 4; } // EndpointSlice represents a subset of the endpoints that implement a service. // For a given service there may be multiple EndpointSlice objects, selected by // labels, which must be joined to produce the full set of endpoints. message EndpointSlice { // Standard object's metadata. // +optional optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // addressType specifies the type of address carried by this EndpointSlice. // All addresses in this slice must be the same type. This field is // immutable after creation. The following address types are currently // supported: // * IPv4: Represents an IPv4 Address. // * IPv6: Represents an IPv6 Address. // * FQDN: Represents a Fully Qualified Domain Name. optional string addressType = 4; // endpoints is a list of unique endpoints in this slice. Each slice may // include a maximum of 1000 endpoints. // +listType=atomic repeated Endpoint endpoints = 2; // ports specifies the list of network ports exposed by each endpoint in // this slice. Each port must have a unique name. When ports is empty, it // indicates that there are no defined ports. When a port is defined with a // nil port value, it indicates "all ports". Each slice may include a // maximum of 100 ports. // +optional // +listType=atomic repeated EndpointPort ports = 3; } // EndpointSliceList represents a list of endpoint slices message EndpointSliceList { // Standard list metadata. // +optional optional k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; // List of endpoint slices repeated EndpointSlice items = 2; } ```
```shell Let's play the blame game Interactive staging Create a new branch from a stash Show history of a function Debug using binary search ```
```javascript /** * @license Apache-2.0 * * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ 'use strict'; // MODULES // var bench = require( '@stdlib/bench' ); var randu = require( '@stdlib/random/base/randu' ); var isnanf = require( '@stdlib/math/base/assert/is-nanf' ); var pow = require( '@stdlib/math/base/special/pow' ); var Float32Array = require( '@stdlib/array/float32' ); var Uint8Array = require( '@stdlib/array/uint8' ); var pkg = require( './../package.json' ).name; var snanmskrange = require( './../lib/snanmskrange.js' ); // FUNCTIONS // /** * Creates a benchmark function. * * @private * @param {PositiveInteger} len - array length * @returns {Function} benchmark function */ function createBenchmark( len ) { var mask; var x; var i; x = new Float32Array( len ); mask = new Uint8Array( len ); for ( i = 0; i < x.length; i++ ) { if ( randu() < 0.2 ) { mask[ i ] = 1; } else { mask[ i ] = 0; } x[ i ] = ( randu()*20.0 ) - 10.0; } return benchmark; function benchmark( b ) { var v; var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { v = snanmskrange( x.length, x, 1, mask, 1 ); if ( isnanf( v ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnanf( v ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); } } // MAIN // /** * Main execution sequence. * * @private */ function main() { var len; var min; var max; var f; var i; min = 1; // 10^min max = 6; // 10^max for ( i = min; i <= max; i++ ) { len = pow( 10, i ); f = createBenchmark( len ); bench( pkg+':len='+len, f ); } } main(); ```
```java package com.yahoo.messagebus; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; /** * <p>A reply is a response to a message that has been sent throught the messagebus. No reply will ever exist without a * corresponding message. There are no error-replies defined, as errors can instead piggyback any reply by the {@link * #errors} member variable.</p> * * @author Simon Thoresen Hult */ public abstract class Reply extends Routable { private double retryDelay = -1.0; private Message msg = null; private List<Error> errors = new ArrayList<>(); @Override public void swapState(Routable rhs) { super.swapState(rhs); if (rhs instanceof Reply) { Reply reply = (Reply)rhs; double retryDelay = this.retryDelay; this.retryDelay = reply.retryDelay; reply.retryDelay = retryDelay; Message msg = this.msg; this.msg = reply.msg; reply.msg = msg; List<Error> errors = this.errors; this.errors = reply.errors; reply.errors = errors; } } /** * <p>Returns the message to which this is a reply.</p> * * @return The message. */ public Message getMessage() { return msg; } /** * <p>Sets the message to which this is a reply. Although it might seem very bogus to allow such an accessor, it is * necessary since we allow an empty constructor.</p> * * @param msg The message to which this is a reply. */ public void setMessage(Message msg) { this.msg = msg; } /** * <p>Returns whether or not this reply contains any errors.</p> * * @return True if there are errors, false otherwise. */ public boolean hasErrors() { return errors.size() > 0; } /** * <p>Returns whether or not this reply contains any fatal errors.</p> * * @return True if it contains fatal errors. */ public boolean hasFatalErrors() { for (Error error : errors) { if (error.getCode() >= ErrorCode.FATAL_ERROR) { return true; } } return false; } /** * <p>Returns the error at the given position.</p> * * @param i The index of the error to return. * @return The error at the given index. */ public Error getError(int i) { return errors.get(i); } /** * <p>Returns the number of errors that this reply contains.</p> * * @return The number of replies. */ public int getNumErrors() { return errors.size(); } /** * <p>Add an error to this reply. This method will also trace the error as long as there is any tracing * enabled.</p> * * @param error The error object to add. */ public void addError(Error error) { errors.add(error); getTrace().trace(TraceLevel.ERROR, error.toString()); } /** * <p>Returns the retry request of this reply. This can be set using {@link #setRetryDelay} and is an instruction to * the resender logic of message bus on how to perform the retry. If this value is anything other than a negative * number, it instructs the resender to disregard all configured resending attributes and instead act according to * this value.</p> * * @return The retry request. */ public double getRetryDelay() { return retryDelay; } /** * <p>Sets the retry delay request of this reply. If this is a negative number, it will use the defaults configured * in the source session.</p> * * @param retryDelay The retry request. */ public void setRetryDelay(double retryDelay) { this.retryDelay = retryDelay; } /** * Retrieves a (read only) stream of the errors in this reply */ public Stream<Error> getErrors() { return errors.stream(); } /** * Retrieves a set of integer error codes */ public Set<Integer> getErrorCodes() { Set<Integer> errorCodes = new HashSet<>(); for (Error error : errors) { errorCodes.add(error.getCode()); } return errorCodes; } } ```
Ahamed is a surname. Notable people with the surname include: E. Ahamed, Indian politician Emajuddin Ahamed (1933–2020), Bangladeshi academic Liaquat Ahamed, American writer M.C. Ahamed (died 2008), Sri Lankan politician Mohammed Ahamed (born 1985), Norwegian-Somali footballer Salim Ahamed (born 1970), Indian film director, producer and screenwriter
```java package org.lognet.springboot.grpc; import io.grpc.Metadata; import io.grpc.ServerCall; import io.grpc.ServerCall.Listener; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; import io.grpc.examples.GreeterGrpc; import org.junit.Assert; import org.junit.Before; import org.junit.runner.RunWith; import org.lognet.springboot.grpc.OrderedInterceptorsTest.TheConfiguration; import org.lognet.springboot.grpc.demo.DemoApp; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * Created by 310242212 on 11-Sep-16. */ @RunWith(SpringRunner.class) @SpringBootTest(classes = {DemoApp.class, TheConfiguration.class}, webEnvironment = WebEnvironment.NONE, properties = {"grpc.port=7778", "grpc.shutdownGrace=-1"}) @ActiveProfiles("disable-security") public class OrderedInterceptorsTest extends GrpcServerTestBase { private static List<Integer> calledInterceptors = new ArrayList<>(); @Before public void setup() { calledInterceptors.clear(); } @Override protected GreeterGrpc.GreeterFutureStub beforeGreeting(GreeterGrpc.GreeterFutureStub stub) { Assert.assertEquals(7778, runningPort); Assert.assertEquals(getPort(), runningPort); return stub; } @Override protected void afterGreeting() { assertThat(calledInterceptors).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 10, 10, 100,100); } @TestConfiguration public static class TheConfiguration { static class OrderAwareInterceptor implements ServerInterceptor { private final int order; public OrderAwareInterceptor(int order) { this.order = order; } @Override public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { calledInterceptors.add(order); return next.startCall(call, headers); } } @Bean @GRpcGlobalInterceptor public ServerInterceptor mySixthInterceptor() { return new MySixthInterceptor(); } class MySixthInterceptor implements ServerInterceptor, Ordered { @Override public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { calledInterceptors.add(getOrder()); return next.startCall(call, headers); } @Override public int getOrder() { return 6; } } @GRpcGlobalInterceptor @Order(2) static class SecondInterceptor extends OrderAwareInterceptor { public SecondInterceptor() { super(2); } } @GRpcGlobalInterceptor @Order(4) static class FourthInterceptor extends OrderAwareInterceptor { public FourthInterceptor() { super(4); } } @GRpcGlobalInterceptor @Order(3) static class ThirdInterceptor extends OrderAwareInterceptor { public ThirdInterceptor() { super(3); } } @GRpcGlobalInterceptor @Order(1) static class FirstInterceptor extends OrderAwareInterceptor { public FirstInterceptor() { super(1); } } @GRpcGlobalInterceptor @Order // no value means lowest priority amongst all @Ordered, but higher priority than interceptors without the annotation static class DefaultOrderedInterceptor extends OrderAwareInterceptor { public DefaultOrderedInterceptor() { super(10); } } // interceptors without any annotation will always be executed last, losing to any defined @Order @GRpcGlobalInterceptor static class UnorderedInterceptor extends OrderAwareInterceptor { public UnorderedInterceptor() { super(100); } } @Bean @GRpcGlobalInterceptor @Order(7) public ServerInterceptor mySeventhInterceptor() { return new OrderAwareInterceptor(7); } @Bean @GRpcGlobalInterceptor @Order public ServerInterceptor myOrderedMethodFactoryBeanInterceptor() { return new OrderAwareInterceptor(10); } @Bean @GRpcGlobalInterceptor public ServerInterceptor myUnOrderedMethodFactoryBeanInterceptor() { return new OrderAwareInterceptor(100); } @Bean @GRpcGlobalInterceptor public ServerInterceptor myInterceptor() { return new MyInterceptor(); } class MyInterceptor implements ServerInterceptor, Ordered { @Override public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { calledInterceptors.add(5); return next.startCall(call, headers); } @Override public int getOrder() { return 5; } } @Bean @Order(8) @GRpcGlobalInterceptor public ServerInterceptor my8thInterceptor() { return new My8Interceptor(); } static class My8Interceptor implements ServerInterceptor { @Override public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { calledInterceptors.add(8); return next.startCall(call, headers); } } } } ```
Marcos Antonio Menezes Godoi (born December 18, 1966) is a former Brazilian football player. Club statistics References External links 1966 births Living people Brazilian men's footballers Japan Soccer League players J1 League players Cerezo Osaka players Gamba Osaka players Brazilian expatriate men's footballers Expatriate men's footballers in Japan Men's association football midfielders
The Cameron Files: Secret at Loch Ness (known as Loch Ness in Europe) is an adventure video game released in 2001, developed by Galiléa and published by Wanadoo Edition and DreamCatcher Interactive. It was followed in 2002 by a sequel, The Cameron Files: Pharaoh's Curse. Story The detective Alan Parker Cameron is investigating the secret case of the monster of Loch Ness, he is sent to “Devil's Ridge Manor” (A mansion located at the shore of the lake) because people claim to see ghosts and paranormal activity around the house. Alan is sent there to resolve this weird case. Gameplay As the detective you must explore this haunted house, full of labyrinths and traps. You will also have to visit the depths of the lake in order to complete the game. Reception The game received "average" reviews according to video game review aggregator Metacritic. Sequels The Cameron Files series continued, and another game was released for the PC in 2002: The Cameron Files: Pharaoh's Curse. In 2013, the software developer Microids made a mobile version of "Secret at Loch Ness" for the iPhone, iPad, and iPod Touch, optimized for the iPhone 5. When asked if there would be a Pharaoh's Curse mobile version, there was no response from Microids. See also Necronomicon: The Dawning of Darkness The Mystery of the Druids References External links The Cameron Files: Secret at Loch Ness at Microïds 2001 video games Windows games Windows-only games Microïds games Adventure games Detective video games Fiction set in 1932 Fiction set in 1933 Video games set in Scotland The Adventure Company games DreamCatcher Interactive games The Cameron Files Video games developed in France
```java /* * * This file is part of LibreTorrent. * * LibreTorrent is free software: you can redistribute it and/or modify * (at your option) any later version. * * LibreTorrent 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 * * along with LibreTorrent. If not, see <path_to_url */ package org.proninyaroslav.libretorrent.service; import android.content.Context; import android.text.TextUtils; import android.util.Log; import androidx.annotation.NonNull; import androidx.work.Data; import androidx.work.OneTimeWorkRequest; import androidx.work.WorkManager; import androidx.work.Worker; import androidx.work.WorkerParameters; import org.proninyaroslav.libretorrent.core.FeedParser; import org.proninyaroslav.libretorrent.core.RepositoryHelper; import org.proninyaroslav.libretorrent.core.model.data.entity.FeedChannel; import org.proninyaroslav.libretorrent.core.model.data.entity.FeedItem; import org.proninyaroslav.libretorrent.core.settings.SettingsRepository; import org.proninyaroslav.libretorrent.core.storage.FeedRepository; import org.proninyaroslav.libretorrent.core.utils.Utils; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /* * The worker for fetching items from RSS/Atom channels. */ public class FeedFetcherWorker extends Worker { private static final String TAG = FeedFetcherWorker.class.getSimpleName(); public static final String ACTION_FETCH_CHANNEL = "org.proninyaroslav.libretorrent.service.FeedFetcherWorker.ACTION_FETCH_CHANNEL"; public static final String ACTION_FETCH_CHANNEL_LIST = "org.proninyaroslav.libretorrent.service.FeedFetcherWorker.ACTION_FETCH_CHANNEL_LIST"; public static final String ACTION_FETCH_ALL_CHANNELS = "org.proninyaroslav.libretorrent.service.FeedFetcherWorker.ACTION_FETCH_ALL_CHANNELS"; public static final String TAG_ACTION = "action"; public static final String TAG_NO_AUTO_DOWNLOAD = "no_download"; public static final String TAG_CHANNEL_ID = "channel_url_id"; public static final String TAG_CHANNEL_ID_LIST = "channel_id_list"; private Context context; private FeedRepository repo; private SettingsRepository pref; public FeedFetcherWorker(@NonNull Context context, @NonNull WorkerParameters params) { super(context, params); } @NonNull @Override public Result doWork() { context = getApplicationContext(); repo = RepositoryHelper.getFeedRepository(context); pref = RepositoryHelper.getSettingsRepository(context); long keepTime = pref.feedItemKeepTime(); long keepDateBorderTime = (keepTime > 0 ? System.currentTimeMillis() - keepTime : 0); deleteOldItems(keepDateBorderTime); Data data = getInputData(); String action = data.getString(TAG_ACTION); boolean noAutoDownload = data.getBoolean(TAG_NO_AUTO_DOWNLOAD, false); if (action == null) return Result.failure(); switch (action) { case ACTION_FETCH_CHANNEL: return fetchChannel(data.getLong(TAG_CHANNEL_ID, -1), keepDateBorderTime, noAutoDownload); case ACTION_FETCH_CHANNEL_LIST: return fetchChannelsByUrl(data.getLongArray(TAG_CHANNEL_ID_LIST), keepDateBorderTime, noAutoDownload); case ACTION_FETCH_ALL_CHANNELS: return fetchChannels(repo.getAllFeeds(), keepDateBorderTime, noAutoDownload); default: return Result.failure(); } } private Result fetchChannelsByUrl(long[] ids, long acceptMinDate, boolean noAutoDownload) { if (ids == null) return Result.failure(); ArrayList<Result> results = new ArrayList<>(); for (long id : ids) results.add(fetchChannel(id, acceptMinDate, noAutoDownload)); for (Result result : results) if (result instanceof Result.Failure) return result; return Result.success(); } private Result fetchChannels(List<FeedChannel> channels, long acceptMinDate, boolean noAutoDownload) { if (channels == null) return Result.failure(); ArrayList<Result> results = new ArrayList<>(); for (FeedChannel channel : channels) { if (channel == null) continue; results.add(fetchChannel(channel.id, acceptMinDate, noAutoDownload)); } for (Result result : results) if (result instanceof Result.Failure) return result; return Result.success(); } private Result fetchChannel(long id, long acceptMinDate, boolean noAutoDownload) { if (id == -1) return Result.failure(); FeedChannel channel = repo.getFeedById(id); if (channel == null) return Result.failure(); FeedParser parser; try { parser = new FeedParser(getApplicationContext(), channel); } catch (Exception e) { channel.fetchError = e.getMessage(); repo.updateFeed(channel); return Result.failure(); } List<FeedItem> items = parser.getItems(); filterItems(id, items, acceptMinDate); if (pref.feedRemoveDuplicates()) filterItemDuplicates(items); repo.addItems(items); channel.fetchError = null; if (TextUtils.isEmpty(channel.name)) { channel.name = parser.getTitle(); if (TextUtils.isEmpty(channel.name)) channel.name = channel.url; } channel.lastUpdate = System.currentTimeMillis(); repo.updateFeed(channel); if (!noAutoDownload && channel.autoDownload) sendFetchedItems(channel, items); return Result.success(); } private void filterItems(long id, List<FeedItem> items, long acceptMinDate) { List<String> existingItemsId = repo.getItemsIdByFeedId(id); /* Also filtering the items that we already have in db */ items.removeIf(item -> item != null && (item.pubDate > 0 && item.pubDate <= acceptMinDate || existingItemsId.contains(item.id))); } private void filterItemDuplicates(List<FeedItem> items) { List<String> titles = new ArrayList<>(); for (FeedItem item : items) titles.add(item.title); List<String> existingTitles = repo.findItemsExistingTitles(titles); items.removeIf(item -> item != null && existingTitles.contains(item.title)); } private void deleteOldItems(long keepDateBorderTime) { if (keepDateBorderTime > 0) repo.deleteItemsOlderThan(keepDateBorderTime); } private void sendFetchedItems(FeedChannel channel, List<FeedItem> items) { ArrayList<String> ids = new ArrayList<>(); for (FeedItem item : items) { if (item == null || item.read) continue; if (isMatch(item, channel.filter, channel.isRegexFilter)) { ids.add(item.id); repo.markAsRead(item.id); } } if (ids.isEmpty()) return; Data data = new Data.Builder() .putString(FeedDownloaderWorker.TAG_ACTION, FeedDownloaderWorker.ACTION_DOWNLOAD_TORRENT_LIST) .putStringArray(FeedDownloaderWorker.TAG_ITEM_ID_LIST, ids.toArray(new String[0])) .build(); OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(FeedDownloaderWorker.class) .setInputData(data) .build(); WorkManager.getInstance(context).enqueue(work); } private boolean isMatch(FeedItem item, String filters, boolean isRegex) { if (filters == null || TextUtils.isEmpty(filters)) return true; for (String filter : filters.split(Utils.NEWLINE_PATTERN)) { if (TextUtils.isEmpty(filter)) continue; if (isRegex) { Pattern pattern; try { pattern = Pattern.compile(filter); } catch (PatternSyntaxException e) { /* TODO: maybe there is an option better? */ Log.e(TAG, "Invalid pattern: " + filter); return true; } return pattern.matcher(item.title).matches(); } else { String[] words = filter.split(repo.getFilterSeparator()); for (String word : words) if (item.title.toLowerCase().contains(word.toLowerCase().trim())) return true; } } return false; } } ```
```java package org.schemaspy.view; import java.util.Collection; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import org.schemaspy.cli.NoRowsConfigCli; import org.schemaspy.cli.TemplateDirectoryConfigCli; import org.schemaspy.model.Table; import org.schemaspy.util.markup.Asciidoc; import org.schemaspy.util.markup.Markdown; import org.schemaspy.util.markup.Markup; import org.schemaspy.util.markup.MarkupFromString; import org.schemaspy.util.markup.PageRegistry; import org.schemaspy.util.markup.WithReferenceLinks; @Parameters(resourceBundle = "htmlconfigcli") public class HtmlConfigCli implements HtmlConfig { @Parameter( names = { "-desc", "--description", "schemaspy.desc", "schemaspy.description" }, descriptionKey = "desc" ) private String description; @Parameter( names = { "-nopages", "--no-pages", "schemaspy.nopages", "schemaspy.no-pages" }, descriptionKey = "nopages" ) private boolean noPages = false; @Parameter( names = { "-asciidoc", "--asciidoc", "schemaspy.asciidoc" }, descriptionKey = "asciidoc" ) private boolean useAsciiDoc = false; private final NoRowsConfigCli noRowsConfigCli; private final TemplateDirectoryConfigCli templateDirectoryConfigCli; private final PageRegistry pageRegistry = new PageRegistry(); public HtmlConfigCli( NoRowsConfigCli noRowsConfigCli, TemplateDirectoryConfigCli templateDirectoryConfigCli ) { this.noRowsConfigCli = noRowsConfigCli; this.templateDirectoryConfigCli = templateDirectoryConfigCli; } @Override public String getDescription() { return description; } @Override public String getTemplateDirectory() { return templateDirectoryConfigCli.getTemplateDirectory(); } @Override public boolean isPaginationEnabled() { return !noPages; } @Override public boolean isNumRowsEnabled() { return noRowsConfigCli.isNumRowsEnabled(); } @Override public void registryPage(final Collection<Table> tables) { pageRegistry.register(tables); } @Override public Markup markupProcessor(final String markupText, final String rootPath) { if (useAsciiDoc) { return new Asciidoc( new WithReferenceLinks( new MarkupFromString(markupText), pageRegistry, rootPath, Asciidoc.LINK_FORMAT ) ); } else { return new Markdown( new WithReferenceLinks( new MarkupFromString(markupText), pageRegistry, rootPath, Markdown.LINK_FORMAT ) ); } } } ```
{{Infobox scientist | name = Earl Stadtman | image=Thressa & Earl Stadtman (30850367433) (cropped).jpg| caption= Earl Reece and Thressa Stadtman, 2004 | birth_name = Earl Reece Stadtman | birth_date = | birth_place = Carrizozo, New Mexico, USA | death_date = | death_place = Derwood, Maryland, USA | fields = Biochemistry | workplaces = Georgetown University, Washington, DC; University of Maryland, College Park, Maryland; Johns Hopkins University; National Heart Institute, Bethesda, Maryland; many visiting appointments | patrons = | education = University of California, Berkeley (Ph.D. 1949) | thesis_title = 'Mechanisms of Fatty Acid Synthesis by Clostridium kluyveri | academic_advisors = Horace Barker | doctoral_students = | notable_students = | known_for = Fatty aid biosynthesis, glutamine dehydrogenase, cycles of interconvertible enzymes | influences = | awards = Pfizer Award in Enzyme Chemistry, American Academy of Arts and Sciences, National Academy of Sciences, National Medal of Science, many others | spouse = Thressa Campbell Stadtman | children = None | parents = | father = | mother = }} Earl Reece Stadtman NAS (November 15, 1919 – January 7, 2008) was an American biochemist,The Stadtman Way: A Tale of two biochemists at NIH notable for his research on enzymes and anaerobic bacteria. Career Stadtman started his career as a research assistant in the Division of Plant Nutrition of the University of California. Subsequently he was an Atomic Energy Commission Fellow with Fritz Lipmann in the Massachusetts General Hospital, but after 1960 he worked at the National Heart Institute, where he became chief of the Laboratory of Biochemistry. In addition, he spent sabbatical periods at the Max Planck Institute in Munich and the Pasteur Institute in Paris. Personal life In 1944 Earl Stadtman married Thressa Campbell, also a distinguished scientist, the discoverer of selenocysteine. They had no children during their marriage of more than sixty years. Research Stadtman's research covered a wide field. Early in his career he worked with Horace Barker on bacterial fatty-acid synthesis, with a series of four papers. In the same period he collaborated with Fritz Lipmann on the function of coenzyme A. Later his work took on a more enzymological character, with investigation of, for example, aldehyde dehydrogenase, aspartate kinase, work carried out during a period in the laboratory of Georges Cohen in France and, most notably, glutamine synthetase, an enzyme that will always be associated with his name. From the 1970s onwards Stadtman published many papers with P. Boon Chock on the capacity of cycles of interconvertible enzymes, based especially on his results with glutamine synthetase, to generate very high sensitivity to effectors. Editorial work Stadtman was active as an editor of numerous prominent journals, including the Journal of Biological Chemistry, 1960–1965, Archives of Biochemistry and Biophysics, 1960–1969; Annual Review of Biochemistry, 1972–2000; Biochemistry, 1969–1976; Proceedings of the National Academy of Sciences, 1974–1981; Trends in Biochemical Sciences, 1975–1978. He was (with Bernard Horecker) founding editor of Current Topics in Cellular Regulation,'' a major series in the subject, and continued in the role up to volume 23 (1984). Awards and honours 1953: Pfizer Award in Enzyme Chemistry 1966: Medallion of the University of Pisa, Italy 1969: elected to the American Academy of Arts and Sciences 1969: elected to the National Academy of Sciences 1970: awarded Selman A. Waksman Award in Microbiology 1972: Medallion of the University of Camerino, Italy 1979: National Medal of Science 1983: President, American Society of Biological Chemists 1983: ASBC-Merck Award 1987: Honorary Doctor of Science, University of Michigan 1988: Honorary Ph.D., Weizmann Institute of Science, Israel 1991: Welch Award in Chemistry 1999: Honorary Ph.D., University of Pennsylvania References External links 1919 births 2008 deaths University of California, Berkeley alumni Members of the United States National Academy of Sciences National Medal of Science laureates People from Lincoln County, New Mexico Scientists from New Mexico 20th-century American biochemists National Institutes of Health people
Thrithala is a town and a village in Pattambi taluk in Palakkad District of Kerala state, South India. The town is located along the banks of Bharathapuzha and is famed for its Shiva temple. History The legend of 'Parayi petta panthirukulam' is centred on Trithala. According to this story, a Brahmin named Vararuchi, married a lower caste woman without knowing her true identity(?). After the marriage, they set out on a long journey. During the course of the journey, the woman became pregnant several times, and every time she delivered a baby, the husband asked her to leave it there itself. Each of the babies was taken up by people of different castes (totally 12), thus they grew up in that caste, making the legendary 'Panthirukulam'. They all became famous in their lives and many tales are attributed to them. The eldest was Agnihothri, a Brahmin, whose place is Mezhathur in Trithala. The others are Pakkanar (basket weaver), Perumthachan (Master carpenter), Naranathu Bhranthan (an eccentric but divine person), Vayillakunnilappan (a child without mouth, whom the mother wanted to keep with her) and so on. Their stories are mentioned in the well known book 'Eithihyamala' by Kottarathil Sankunni. The Siva temple, probably built during the 9th and 10th century, marks the transition from the Chola to the Pandya style of architecture. According to a legend, the child Agnihotri was bathing in the river along with his mother. He heaped the sand in the form of a mound on a plate ('thalam' in Malayalam). When the mother tried to remove the sand, she found that it has solidified in the form of a 'Siva Lingam'. Thus the deity is known as 'Thalathilappan', meaning God in a plate. The idol is said to have the constitution of sand. It is believed that the sharp bend in the river in the area was formed due to the river changing its course on its own, to give space for the temple to be built. Notable residents V. T. Bhattathiripad, Dramatist and a prominent freedom fighter Maha Kavi Akkitham Achuthan Namboothiri Thrithala Kesava Poduval, Thayambaka Maestro M. T. Vasudevan Nair, Malayalam Writer & Jnanpit Award Winner E. Sreedharan, Former managing director of DMRC Ammu Swaminathan, Courageous freedom fighter and a prominent leader Captain Lakshmi Sahgal, Activist of the Indian independence movement Major Ravi, Malayalam film director Politics It belongs to Ponnani Loksabha Constituency current MP is E. T. Mohammed Basheer. Thrithala is the 49th legislative assembly constituency, current MLA is M B Rajesh of CPIM. Major political parties are the Indian National Congress (INC), the Communist Party of India (Marxist) (CPM), Communist Party of India (CPI), Bharatiya Janata Party (BJP), Social Democratic Party of India (SDPI) and the Indian Union Muslim League (IUML). Suburbs and Villages Mudavannur, Mezhathur Njangattiri, Kalyanappadi and Kannannoor Ullanoor, V.K.Kadavu and K.R.Narayan Nagar Athani, Chittappuram, Pattithara and Malamakkavu othalur Pattithara Navayuga Pattithara Pooleri Aloor Chittapuram United Kundkad Important Landmarks Velliyamkallu park Pakkanar Colony Vaidyamadham, Mezhathur Vemanchery Mana, House of Agnihothri Yajneswaram Shiva Temple Thrithala Juma Masjid Kannannoor Bhagavathy Temple V.K.Kadavu Juma Masjidh President of India road in honour of T.K. Subramanian who worked in Rashtrapathi Bhawan Thrithala Shiva Temple Mudavannur Shiva Temple Ullanur Juma Masjid Govt Arts and Science College, Thrithala References External links Story about 'Parayi petta panthirukulam' Stories about Pakkanar Kudallur Village Villages in Palakkad district ml:തൃത്താല ഗ്രാമപഞ്ചായത്ത്
```javascript import { test } from '../../test'; export default test({ html: ` <div> Hello <p slot='bar'>bar</p> <p slot='foo'>foo</p> </div> ` }); ```
Robert Joseph Murphy, Jr. (born February 14, 1943) is an American professional golfer who was formerly a member of the PGA Tour and currently plays on the Champions Tour. Murphy has won 21 tournaments as a professional. Early years Murphy was born in Brooklyn, New York. He was a standout pitcher in his youth, and as a teen led his high school baseball team to the state championship in 1960. After suffering a football injury (which also ended his baseball career), Murphy got started in golf. College career Murphy attended the University of Florida in Gainesville, Florida, where he was a member of Sigma Alpha Epsilon Fraternity (Florida Upsilon Chapter). While he was an undergraduate, he played for coach Buster Bishop's Florida Gators men's golf team in National Collegiate Athletic Association (NCAA) competition from 1964 to 1966. While he was a college student, he won the 1965 U.S. Amateur and the 1966 individual NCAA championship, and was recognized as an All-American in 1966. He graduated from the University of Florida with a bachelor's degree in health and human performance in 1966, and was later inducted into the University of Florida Athletic Hall of Fame as a "Gator Great" in 1971. Professional career Murphy turned professional in 1967, and won five tournaments on the PGA Tour. He was a member of the victorious U.S. team in the 1975 Ryder Cup competition. His best finish in a major tournament was a second-place tie at the 1970 PGA Championship. Murphy won 11 times on the Senior PGA Tour (now the Champions Tour). Murphy first got into broadcasting while still playing. He joined CBS Sports as a tower announcer in 1984, working for CBS through 1991. He then joined ESPN as a color commentator, where he stayed through 1994. After a break from TV to play on the Senior PGA Tour, he joined NBC Sports in November 1999, and was a tower announcer for the PGA Tour on NBC through 2009, at which point he retired. He was inducted into the Florida Sports Hall of Fame in 2011. Personal life Murphy lives in Delray Beach, Florida with his wife, Gail. Amateur wins (2) 1965 U.S. Amateur 1966 NCAA championship (individual) Professional wins (23) PGA Tour wins (5) PGA Tour playoff record (1–5) Australian wins (1) 1972 Wills Masters Other wins (3) 1967 Florida Open 1979 Jerry Ford Invitational 1980 South Florida PGA Championship Senior PGA Tour wins (11) *Note: Tournament shortened to 36 holes due to weather. Senior PGA Tour playoff record (2–1) Other senior wins (3) 1995 Diners Club Matches (with Jim Colbert) 1996 Diners Club Matches (with Jim Colbert) 2013 Liberty Mutual Insurance Legends of Golf - Demaret Division (with Jim Colbert) Results in major championships LA = Low amateur CUT = missed the half-way cut "T" indicates a tie for a place Summary Most consecutive cuts made – 11 (1971 PGA – 1976 Masters) Longest streak of top-10s – 1 (three times) Results in The Players Championship CUT = missed the halfway cut "T" indicates a tie for a place U.S. national team appearances Amateur Walker Cup: 1967 (winners) Eisenhower Trophy: 1966 Professional Ryder Cup: 1975 (winners) See also 1967 PGA Tour Qualifying School graduates List of American Ryder Cup golfers List of Florida Gators men's golfers on the PGA Tour List of golfers with most PGA Tour Champions wins List of Sigma Alpha Epsilon members List of University of Florida alumni List of University of Florida Athletic Hall of Fame members References External links American male golfers Florida Gators men's golfers PGA Tour golfers PGA Tour Champions golfers Ryder Cup competitors for the United States Golf writers and broadcasters Golfers from New York (state) Golfers from Florida Mulberry High School (Mulberry, Florida) alumni Sportspeople from Brooklyn Sportspeople from Delray Beach, Florida 1943 births Living people Sigma Alpha Epsilon members
```c++ /* * * This program is free software: you can redistribute it and/or modify * the Free Software Foundation, either version 2 or (at your option) * * 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 * * along with this program. If not, see <path_to_url */ #include "AutoTypeMatchModel.h" #include <QFont> #include "core/Entry.h" #include "core/Global.h" #include "core/Group.h" #include "core/Metadata.h" #include "gui/DatabaseIcons.h" #include "gui/Icons.h" AutoTypeMatchModel::AutoTypeMatchModel(QObject* parent) : QAbstractTableModel(parent) { } AutoTypeMatch AutoTypeMatchModel::matchFromIndex(const QModelIndex& index) const { Q_ASSERT(index.isValid() && index.row() < m_matches.size()); return m_matches.at(index.row()); } QModelIndex AutoTypeMatchModel::indexFromMatch(const AutoTypeMatch& match) const { int row = m_matches.indexOf(match); Q_ASSERT(row != -1); return index(row, 1); } QModelIndex AutoTypeMatchModel::closestIndexFromMatch(const AutoTypeMatch& match) const { int row = -1; for (int i = m_matches.size() - 1; i >= 0; --i) { const auto& currentMatch = m_matches.at(i); if (currentMatch.first == match.first) { row = i; if (currentMatch.second == match.second) { break; } } } return (row > -1) ? index(row, 1) : QModelIndex(); } void AutoTypeMatchModel::setMatchList(const QList<AutoTypeMatch>& matches) { beginResetModel(); severConnections(); m_allGroups.clear(); m_matches = matches; QSet<Database*> databases; for (AutoTypeMatch& match : m_matches) { databases.insert(match.first->group()->database()); } for (Database* db : asConst(databases)) { Q_ASSERT(db); for (const Group* group : db->rootGroup()->groupsRecursive(true)) { m_allGroups.append(group); } if (db->metadata()->recycleBin()) { m_allGroups.removeOne(db->metadata()->recycleBin()); } } for (const Group* group : asConst(m_allGroups)) { makeConnections(group); } endResetModel(); } int AutoTypeMatchModel::rowCount(const QModelIndex& parent) const { if (parent.isValid()) { return 0; } return m_matches.size(); } int AutoTypeMatchModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return 4; } QVariant AutoTypeMatchModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) { return {}; } AutoTypeMatch match = matchFromIndex(index); if (role == Qt::DisplayRole) { switch (index.column()) { case ParentGroup: if (match.first->group()) { return match.first->group()->name(); } break; case Title: return match.first->resolveMultiplePlaceholders(match.first->title()); case Username: return match.first->resolveMultiplePlaceholders(match.first->username()); case Sequence: return match.second; } } else if (role == Qt::DecorationRole) { switch (index.column()) { case ParentGroup: if (match.first->group()) { return Icons::groupIconPixmap(match.first->group()); } break; case Title: return Icons::entryIconPixmap(match.first); } } else if (role == Qt::FontRole) { QFont font; if (match.first->isExpired()) { font.setStrikeOut(true); } return font; } return {}; } QVariant AutoTypeMatchModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { switch (section) { case ParentGroup: return tr("Group"); case Title: return tr("Title"); case Username: return tr("Username"); case Sequence: return tr("Sequence"); } } return {}; } void AutoTypeMatchModel::entryDataChanged(Entry* entry) { for (int row = 0; row < m_matches.size(); ++row) { AutoTypeMatch match = m_matches[row]; if (match.first == entry) { emit dataChanged(index(row, 0), index(row, columnCount() - 1)); } } } void AutoTypeMatchModel::entryAboutToRemove(Entry* entry) { for (int row = 0; row < m_matches.size(); ++row) { AutoTypeMatch match = m_matches[row]; if (match.first == entry) { beginRemoveRows(QModelIndex(), row, row); m_matches.removeAt(row); endRemoveRows(); --row; } } } void AutoTypeMatchModel::entryRemoved() { } void AutoTypeMatchModel::severConnections() { for (const Group* group : asConst(m_allGroups)) { disconnect(group, nullptr, this, nullptr); } } void AutoTypeMatchModel::makeConnections(const Group* group) { connect(group, SIGNAL(entryAboutToRemove(Entry*)), SLOT(entryAboutToRemove(Entry*))); connect(group, SIGNAL(entryRemoved(Entry*)), SLOT(entryRemoved())); connect(group, SIGNAL(entryDataChanged(Entry*)), SLOT(entryDataChanged(Entry*))); } ```
```xml import { Component, OnDestroy, OnInit } from "@angular/core"; import { ActivatedRoute } from "@angular/router"; import { BehaviorSubject, Subject, switchMap, takeUntil, tap } from "rxjs"; import { SafeProvider, safeProvider } from "@bitwarden/angular/platform/utils/safe-provider"; import { OrganizationAuthRequestApiService } from "@bitwarden/bit-common/admin-console/auth-requests/organization-auth-request-api.service"; import { OrganizationAuthRequestService } from "@bitwarden/bit-common/admin-console/auth-requests/organization-auth-request.service"; import { PendingAuthRequestView } from "@bitwarden/bit-common/admin-console/auth-requests/pending-auth-request.view"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { OrganizationUserService } from "@bitwarden/common/admin-console/abstractions/organization-user/organization-user.service"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { TableDataSource, NoItemsModule } from "@bitwarden/components"; import { Devices } from "@bitwarden/web-vault/app/admin-console/icons"; import { LooseComponentsModule } from "@bitwarden/web-vault/app/shared"; import { SharedModule } from "@bitwarden/web-vault/app/shared/shared.module"; @Component({ selector: "app-org-device-approvals", templateUrl: "./device-approvals.component.html", standalone: true, providers: [ safeProvider({ provide: OrganizationAuthRequestApiService, deps: [ApiService], }), safeProvider({ provide: OrganizationAuthRequestService, deps: [OrganizationAuthRequestApiService, CryptoService, OrganizationUserService], }), ] satisfies SafeProvider[], imports: [SharedModule, NoItemsModule, LooseComponentsModule], }) export class DeviceApprovalsComponent implements OnInit, OnDestroy { tableDataSource = new TableDataSource<PendingAuthRequestView>(); organizationId: string; loading = true; actionInProgress = false; protected readonly Devices = Devices; private destroy$ = new Subject<void>(); private refresh$ = new BehaviorSubject<void>(null); constructor( private organizationAuthRequestService: OrganizationAuthRequestService, private route: ActivatedRoute, private platformUtilsService: PlatformUtilsService, private i18nService: I18nService, private logService: LogService, private validationService: ValidationService, private configService: ConfigService, ) {} async ngOnInit() { this.route.params .pipe( tap((params) => (this.organizationId = params.organizationId)), switchMap(() => this.refresh$.pipe( tap(() => (this.loading = true)), switchMap(() => this.organizationAuthRequestService.listPendingRequests(this.organizationId), ), ), ), takeUntil(this.destroy$), ) .subscribe((r) => { this.tableDataSource.data = r; this.loading = false; }); } async approveRequest(authRequest: PendingAuthRequestView) { await this.performAsyncAction(async () => { try { await this.organizationAuthRequestService.approvePendingRequest( this.organizationId, authRequest, ); this.platformUtilsService.showToast( "success", null, this.i18nService.t("loginRequestApproved"), ); } catch (error) { this.platformUtilsService.showToast( "error", null, this.i18nService.t("resetPasswordDetailsError"), ); } }); } async approveAllRequests() { if (this.tableDataSource.data.length === 0) { return; } await this.performAsyncAction(async () => { await this.organizationAuthRequestService.approvePendingRequests( this.organizationId, this.tableDataSource.data, ); this.platformUtilsService.showToast( "success", null, this.i18nService.t("allLoginRequestsApproved"), ); }); } async denyRequest(requestId: string) { await this.performAsyncAction(async () => { await this.organizationAuthRequestService.denyPendingRequests(this.organizationId, requestId); this.platformUtilsService.showToast("error", null, this.i18nService.t("loginRequestDenied")); }); } async denyAllRequests() { if (this.tableDataSource.data.length === 0) { return; } await this.performAsyncAction(async () => { await this.organizationAuthRequestService.denyPendingRequests( this.organizationId, ...this.tableDataSource.data.map((r) => r.id), ); this.platformUtilsService.showToast( "error", null, this.i18nService.t("allLoginRequestsDenied"), ); }); } private async performAsyncAction(action: () => Promise<void>) { if (this.actionInProgress) { return; } this.actionInProgress = true; try { await action(); this.refresh$.next(); } catch (err: unknown) { this.logService.error(err.toString()); this.validationService.showError(err); } finally { this.actionInProgress = false; } } ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); } } ```
```c++ // // write.cpp // // // Defines _write(), which writes a buffer to a file. // #include <corecrt_internal_lowio.h> #include <corecrt_internal_mbstring.h> #include <ctype.h> #include <locale.h> #include <stdlib.h> #include <string.h> #include <wchar.h> namespace { struct write_result { DWORD error_code; DWORD char_count; DWORD lf_count; }; } // This is the normal size of the LF => CRLF translation buffer. The default // buffer is 4K, plus extra room for LF characters. Not all buffers are exactly // this size, but this is used as the base size. static size_t const BUF_SIZE = 5 * 1024; // Writes a buffer to a file. The way in which the buffer is written depends on // the mode in which the file was opened (e.g., if the file is a text mode file, // linefeed translation will take place). // // On success, this function returns the number of bytes actually written (note // that "bytes" here is "bytes from the original buffer;" more or fewer bytes // may have actually been written, due to linefeed translation, codepage // translation, and other transformations). On failure, this function returns 0 // and sets errno. extern "C" int __cdecl _write(int const fh, void const* const buffer, unsigned const size) { _CHECK_FH_CLEAR_OSSERR_RETURN(fh, EBADF, -1); _VALIDATE_CLEAR_OSSERR_RETURN((fh >= 0 && (unsigned)fh < (unsigned)_nhandle), EBADF, -1); _VALIDATE_CLEAR_OSSERR_RETURN((_osfile(fh) & FOPEN), EBADF, -1); __acrt_lowio_lock_fh(fh); int result = -1; __try { if ((_osfile(fh) & FOPEN) == 0) { errno = EBADF; _doserrno = 0; _ASSERTE(("Invalid file descriptor. File possibly closed by a different thread",0)); __leave; } result = _write_nolock(fh, buffer, size); } __finally { __acrt_lowio_unlock_fh(fh); } return result; } static bool __cdecl write_requires_double_translation_nolock(int const fh) throw() { // Double translation is required if both [a] the current locale is not the C // locale or the file is open in a non-ANSI mode and [b] we are writing to the // console. // If this isn't a TTY or a text mode screen, then it isn't the console: if (!_isatty(fh)) return false; if ((_osfile(fh) & FTEXT) == 0) return false; // Get the current locale. If we're in the C locale and the file is open // in ANSI mode, we don't need double translation: __acrt_ptd* const ptd = __acrt_getptd(); bool const is_c_locale = ptd->_locale_info->locale_name[LC_CTYPE] == nullptr; if (is_c_locale && _textmode(fh) == __crt_lowio_text_mode::ansi) return false; // If we can't get the console mode, it's not the console: DWORD mode; if (!GetConsoleMode(reinterpret_cast<HANDLE>(_osfhnd(fh)), &mode)) return false; // Otherwise, double translation is required: return true; } static write_result __cdecl write_double_translated_ansi_nolock( int const fh, _In_reads_(buffer_size) char const* const buffer, unsigned const buffer_size ) throw() { HANDLE const os_handle = reinterpret_cast<HANDLE>(_osfhnd(fh)); char const* const buffer_end = buffer + buffer_size; UINT const console_cp = GetConsoleCP(); _LocaleUpdate _loc_update(nullptr); const bool is_utf8 = _loc_update.GetLocaleT()->locinfo->_public._locale_lc_codepage == CP_UTF8; write_result result = { 0 }; for (char const* source_it = buffer; source_it < buffer_end; ) { char const c = *source_it; // We require double conversion, to convert from the source multibyte // to Unicode, then from Unicode back to multibyte, but in the console // codepage. // // Here, we have to take into account that _write() might be called // byte-by-byte, so when we see a lead byte without a trail byte, we // have to store it and return no error. When this function is called // again, that byte will be combined with the next available character. wchar_t wc[2] = { 0 }; int wc_used = 1; if (is_utf8) { _ASSERTE(!_dbcsBufferUsed(fh)); const int mb_buf_size = sizeof(_mbBuffer(fh)); int mb_buf_used; for (mb_buf_used = 0; mb_buf_used < mb_buf_size && _mbBuffer(fh)[mb_buf_used]; ++mb_buf_used) {} if (mb_buf_used > 0) { const int mb_len = _utf8_no_of_trailbytes(_mbBuffer(fh)[0]) + 1; _ASSERTE(1 < mb_len && mb_buf_used < mb_len); const int remaining_bytes = mb_len - mb_buf_used; if (remaining_bytes <= (buffer_end - source_it)) { // We now have enough bytes to complete the code point char mb_buffer[MB_LEN_MAX]; for (int i = 0; i < mb_buf_used; ++i) { mb_buffer[i] = _mbBuffer(fh)[i]; } for (int i = 0; i < remaining_bytes; ++i) { mb_buffer[i + mb_buf_used] = source_it[i]; } // Clear out the temp buffer for (int i = 0; i < mb_buf_used; ++i) { _mbBuffer(fh)[i] = 0; } mbstate_t state{}; const char* str = mb_buffer; if (mb_len == 4) { wc_used = 2; } if (__crt_mbstring::__mbsrtowcs_utf8(wc, &str, wc_used, &state) == -1) return result; source_it += (remaining_bytes - 1); } else { // Need to add some more bytes to the buffer for later const auto bytes_to_add = buffer_end - source_it; _ASSERTE(mb_buf_used + bytes_to_add < mb_buf_size); for (int i = 0; i < bytes_to_add; ++i) { _mbBuffer(fh)[i + mb_buf_used] = source_it[i]; } // Pretend we wrote the bytes, because this isn't an error *yet*. result.char_count += static_cast<DWORD>(bytes_to_add); return result; } } else { const int mb_len = _utf8_no_of_trailbytes(*source_it) + 1; const auto available_bytes = buffer_end - source_it; if (mb_len <= (available_bytes)) { // We have enough bytes to write the entire code point mbstate_t state{}; const char* str = source_it; if (mb_len == 4) { wc_used = 2; } if (__crt_mbstring::__mbsrtowcs_utf8(wc, &str, wc_used, &state) == -1) return result; source_it += (mb_len - 1); } else { // Not enough bytes for this code point _ASSERTE(available_bytes <= sizeof(_mbBuffer(fh))); for (int i = 0; i < available_bytes; ++i) { _mbBuffer(fh)[i] = source_it[i]; } // Pretend we wrote the bytes, because this isn't an error *yet*. result.char_count += static_cast<DWORD>(available_bytes); return result; } } } else if (_dbcsBufferUsed(fh)) { // We already have a DBCS lead byte buffered. Take the current // character, combine it with the lead byte, and convert: _ASSERTE(isleadbyte(_dbcsBuffer(fh))); char mb_buffer[MB_LEN_MAX]; mb_buffer[0] = _dbcsBuffer(fh); mb_buffer[1] = *source_it; _dbcsBufferUsed(fh) = false; if (mbtowc(wc, mb_buffer, 2) == -1) return result; } else { if (isleadbyte(*source_it)) { if ((source_it + 1) < buffer_end) { // And we have more bytes to read, just convert... if (mbtowc(wc, source_it, 2) == -1) return result; // Increment the source_it to accomodate the DBCS character: ++source_it; } else { // And we ran out of bytes to read, so buffer the lead byte: _dbcsBuffer(fh) = *source_it; _dbcsBufferUsed(fh) = true; // We lie here that we actually wrote the last character, to // ensure we don't consider this an error: ++result.char_count; return result; } } else { // single character conversion: if (mbtowc(wc, source_it, 1) == -1) return result; } } ++source_it; // Translate the Unicode character into Multibyte in the console codepage // and write the character to the file: char mb_buffer[MB_LEN_MAX]; DWORD const size = static_cast<DWORD>(__acrt_WideCharToMultiByte( console_cp, 0, wc, wc_used, mb_buffer, sizeof(mb_buffer), nullptr, nullptr)); if(size == 0) return result; DWORD written; if (!WriteFile(os_handle, mb_buffer, size, &written, nullptr)) { result.error_code = GetLastError(); return result; } // When we are converting, some conversions may result in: // // 2 MBCS characters => 1 wide character => 1 MBCS character. // // For example, when printing Japanese characters in the English console // codepage, each source character is transformed into a single question // mark. Therefore, we want to track the number of bytes we converted, // plus the linefeed count, instead of how many bytes we actually wrote. result.char_count = result.lf_count + static_cast<DWORD>(source_it - buffer); // If the write succeeded but didn't write all of the characters, return: if (written < size) return result; // If the original character that we read was an LF, write a CR too: // CRT_REFACTOR TODO Doesn't this write LFCR instead of CRLF? if (c == LF) { wchar_t const cr = CR; if (!WriteFile(os_handle, &cr, 1, &written, nullptr)) { result.error_code = GetLastError(); return result; } if (written < 1) return result; ++result.lf_count; ++result.char_count; } } return result; } static write_result __cdecl write_double_translated_unicode_nolock( _In_reads_(buffer_size) char const* const buffer, _In_ _Pre_satisfies_((buffer_size % 2) == 0) unsigned const buffer_size ) throw() { // When writing to a Unicode file (UTF-8 or UTF-16LE) that corresponds to // the console, we don't actually need double translation. We just need to // print each character to the console, one-by-one. (This function is // named what it is because its use is guarded by the double translation // check, and to match the name of the corresponding ANSI function.) write_result result = { 0 }; // Needed for SAL to clarify that buffer_size is even. _Analysis_assume_((buffer_size/2) != ((buffer_size-1)/2)); char const* const buffer_end = buffer + buffer_size; for (char const* pch = buffer; pch < buffer_end; pch += 2) { wchar_t const c = *reinterpret_cast<wchar_t const*>(pch); if (_putwch_nolock(c) == c) { result.char_count += 2; } else { result.error_code = GetLastError(); return result; } // If the character was a carriage return, also emit a line feed. // CRT_REFACTOR TODO Doesn't this print LFCR instead of CRLF? if (c == LF) { if (_putwch_nolock(CR) != CR) { result.error_code = GetLastError(); return result; } ++result.char_count; ++result.lf_count; } } return result; } static write_result __cdecl write_text_ansi_nolock( int const fh, _In_reads_(buffer_size) char const* const buffer, unsigned const buffer_size ) throw() { HANDLE const os_handle = reinterpret_cast<HANDLE>(_osfhnd(fh)); char const* const buffer_end = buffer + buffer_size; write_result result = { 0 }; for (char const* source_it = buffer; source_it < buffer_end; ) { char lfbuf[BUF_SIZE]; // The LF => CRLF translation buffer // One-past-the-end of the translation buffer. Note that we subtract // one to account for the case where we're pointing to the last element // in the buffer and we need to write both a CR and an LF. char* const lfbuf_end = lfbuf + sizeof(lfbuf) - 1; // Translate the source buffer into the translation buffer. Note that // both source_it and lfbuf_it are incremented in the loop. char* lfbuf_it = lfbuf; while (lfbuf_it < lfbuf_end && source_it < buffer_end) { char const c = *source_it++; if (c == LF) { ++result.lf_count; *lfbuf_it++ = CR; } *lfbuf_it++ = c; } DWORD const lfbuf_length = static_cast<DWORD>(lfbuf_it - lfbuf); DWORD written; if (!WriteFile(os_handle, lfbuf, lfbuf_length, &written, nullptr)) { result.error_code = GetLastError(); return result; } result.char_count += written; if (written < lfbuf_length) return result; // The write succeeded but didn't write everything } return result; } static write_result __cdecl write_text_utf16le_nolock( int const fh, _In_reads_(buffer_size) char const* const buffer, unsigned const buffer_size ) throw() { HANDLE const os_handle = reinterpret_cast<HANDLE>(_osfhnd(fh)); wchar_t const* const buffer_end = reinterpret_cast<wchar_t const*>(buffer + buffer_size); write_result result = { 0 }; wchar_t const* source_it = reinterpret_cast<wchar_t const*>(buffer); while (source_it < buffer_end) { wchar_t lfbuf[BUF_SIZE / sizeof(wchar_t)]; // The translation buffer // One-past-the-end of the translation buffer. Note that we subtract // one to account for the case where we're pointing to the last element // in the buffer and we need to write both a CR and an LF. wchar_t const* lfbuf_end = lfbuf + BUF_SIZE / sizeof(wchar_t) - 1; // Translate the source buffer into the translation buffer. Note that // both source_it and lfbuf_it are incremented in the loop. wchar_t* lfbuf_it = lfbuf; while (lfbuf_it < lfbuf_end && source_it < buffer_end) { wchar_t const c = *source_it++; if (c == LF) { result.lf_count += 2; *lfbuf_it++ = CR; } *lfbuf_it++ = c; } // Note that this length is in bytes, not wchar_t elemnts, since we need // to tell WriteFile how many bytes (not characters) to write: DWORD const lfbuf_length = static_cast<DWORD>(lfbuf_it - lfbuf) * sizeof(wchar_t); // Attempt the write and return immediately if it fails: DWORD written; if (!WriteFile(os_handle, lfbuf, lfbuf_length, &written, nullptr)) { result.error_code = GetLastError(); return result; } result.char_count += written; if (written < lfbuf_length) { return result; // The write succeeded, but didn't write everything } } return result; } static write_result __cdecl write_text_utf8_nolock( int const fh, _In_reads_(buffer_size) char const* const buffer, unsigned const buffer_size ) throw() { HANDLE const os_handle = reinterpret_cast<HANDLE>(_osfhnd(fh)); wchar_t const* const buffer_end = reinterpret_cast<wchar_t const*>(buffer + buffer_size); write_result result = { 0 }; wchar_t const* source_it = reinterpret_cast<wchar_t const*>(buffer); while (source_it < buffer_end) { // The translation buffer. We use two buffers: the first is used to // store the UTF-16 LF => CRLF translation (this is that buffer here). // The second is used for storing the conversion to UTF-8 (defined // below). The sizes are selected to handle the worst-case scenario // where each UTF-8 character is four bytes long. wchar_t utf16_buf[BUF_SIZE / 6]; // One-past-the-end of the translation buffer. Note that we subtract // one to account for the case where we're pointing to the last element // in the buffer and we need to write both a CR and an LF. wchar_t const* utf16_buf_end = utf16_buf + (BUF_SIZE / 6 - 1); // Translate the source buffer into the translation buffer. Note that // both source_it and lfbuf_it are incremented in the loop. wchar_t* utf16_buf_it = utf16_buf; while (utf16_buf_it < utf16_buf_end && source_it < buffer_end) { wchar_t const c = *source_it++; if (c == LF) { // No need to count the number of line-feeds translated; we // track the number of written characters by counting the total // number of characters written from the UTF8 buffer (see below // where we update the char_count). *utf16_buf_it++ = CR; } *utf16_buf_it++ = c; } // Note that this length is in characters, not bytes. DWORD const utf16_buf_length = static_cast<DWORD>(utf16_buf_it - utf16_buf); // This is the second translation, where we translate the UTF-16 text to // UTF-8, into the UTF-8 buffer: char utf8_buf[(BUF_SIZE * 2) / 3]; DWORD const bytes_converted = static_cast<DWORD>(__acrt_WideCharToMultiByte( CP_UTF8, 0, utf16_buf, utf16_buf_length, utf8_buf, sizeof(utf8_buf), nullptr, nullptr)); if (bytes_converted == 0) { result.error_code = GetLastError(); return result; } // Here, we need to make every attempt to write all of the converted // characters to avoid corrupting the stream. If, for example, we write // only half of the bytes of a UTF-8 character, the stream may be // corrupted. // // This loop will ensure that we exit only if either (a) all of the // bytes are written, ensuring that no partial MBCSes are written, or // (b) there is an error in the stream. for (DWORD bytes_written = 0; bytes_written < bytes_converted; ) { char const* const current = utf8_buf + bytes_written; DWORD const current_size = bytes_converted - bytes_written; DWORD written; if (!WriteFile(os_handle, current, current_size, &written, nullptr)) { result.error_code = GetLastError(); return result; } bytes_written += written; } // If this chunk was committed successfully, update the character count: result.char_count = static_cast<DWORD>(reinterpret_cast<char const*>(source_it) - buffer); } return result; } static write_result __cdecl write_binary_nolock( int const fh, _In_reads_(buffer_size) char const* const buffer, unsigned const buffer_size ) throw() { HANDLE const os_handle = reinterpret_cast<HANDLE>(_osfhnd(fh)); // Compared to text files, binary files are easy... write_result result = { 0 }; if (!WriteFile(os_handle, buffer, buffer_size, &result.char_count, nullptr)) result.error_code = GetLastError(); return result; } extern "C" int __cdecl _write_nolock(int const fh, void const* const buffer, unsigned const buffer_size) { // If the buffer is empty, there is nothing to be written: if (buffer_size == 0) return 0; // If the buffer is null, though... well, that is not allowed: _VALIDATE_CLEAR_OSSERR_RETURN(buffer != nullptr, EINVAL, -1); __crt_lowio_text_mode const fh_textmode = _textmode(fh); // If the file is open for Unicode, the buffer size must always be even: if (fh_textmode == __crt_lowio_text_mode::utf16le || fh_textmode == __crt_lowio_text_mode::utf8) _VALIDATE_CLEAR_OSSERR_RETURN(buffer_size % 2 == 0, EINVAL, -1); // If the file is opened for appending, seek to the end of the file. We // ignore errors because the underlying file may not allow seeking. if (_osfile(fh) & FAPPEND) (void)_lseeki64_nolock(fh, 0, FILE_END); char const* const char_buffer = static_cast<char const*>(buffer); // Dispatch the actual writing to one of the helper routines based on the // text mode of the file and whether or not the file refers to the console. // // Note that in the event that the handle belongs to the console, WriteFile // will generate garbage output. To print to the console correctly, we need // to print ANSI. Also note that when printing to the console, we need to // convert the characters to the console codepge. write_result result = { 0 }; if (write_requires_double_translation_nolock(fh)) { switch (fh_textmode) { case __crt_lowio_text_mode::ansi: result = write_double_translated_ansi_nolock(fh, char_buffer, buffer_size); break; case __crt_lowio_text_mode::utf16le: case __crt_lowio_text_mode::utf8: _Analysis_assume_((buffer_size % 2) == 0); result = write_double_translated_unicode_nolock(char_buffer, buffer_size); break; } } else if (_osfile(fh) & FTEXT) { switch (fh_textmode) { case __crt_lowio_text_mode::ansi: result = write_text_ansi_nolock(fh, char_buffer, buffer_size); break; case __crt_lowio_text_mode::utf16le: result = write_text_utf16le_nolock(fh, char_buffer, buffer_size); break; case __crt_lowio_text_mode::utf8: result = write_text_utf8_nolock(fh, char_buffer, buffer_size); break; } } else { result = write_binary_nolock(fh, char_buffer, buffer_size); } // Why did we not write anything? Lettuce find out... if (result.char_count == 0) { // If nothing was written, check to see if it was due to an OS error: if (result.error_code != 0) { // An OS error occurred. ERROR_ACCESS_DENIED should be mapped in // this case to EBADF, not EACCES. All other errors are mapped // normally: if (result.error_code == ERROR_ACCESS_DENIED) { errno = EBADF; _doserrno = result.error_code; } else { __acrt_errno_map_os_error(result.error_code); } return -1; } // If this file is a device and the first character was Ctrl+Z, then // writing nothing is the expected behavior and is not an error: if ((_osfile(fh) & FDEV) && *char_buffer == CTRLZ) { return 0; } // Otherwise, the error is reported as ENOSPC: errno = ENOSPC; _doserrno = 0; return -1; } // The write succeeded. Return the adjusted number of bytes written: return result.char_count - result.lf_count; } ```
```javascript 'use strict'; const { OrBase } = require('./orBase'); /** * @typedef {import('screwdriver-models/lib/build')} Build * @typedef {import('screwdriver-models/lib/event')} Event */ class OrTrigger extends OrBase { /** * Trigger the next jobs of the current job * @param {Event} event * @param {Number} pipelineId * @param {String} nextJobName * @param {Number} nextJobId * @param {import('./helpers').ParentBuilds} parentBuilds * @param {Boolean} isNextJobVirtual * @return {Promise<Build|null>} */ async execute(event, pipelineId, nextJobName, nextJobId, parentBuilds, isNextJobVirtual) { return this.trigger(event, pipelineId, nextJobName, nextJobId, parentBuilds, isNextJobVirtual); } } module.exports = { OrTrigger }; ```
```yaml {{- /* */}} apiVersion: v1 kind: Service metadata: name: {{ template "grafana-loki.query-frontend.fullname" . }} namespace: {{ .Release.Namespace | quote }} labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }} app.kubernetes.io/part-of: grafana-loki app.kubernetes.io/component: query-frontend {{- if or .Values.commonAnnotations .Values.queryFrontend.service.annotations }} {{- $annotations := include "common.tplvalues.merge" ( dict "values" ( list .Values.queryFrontend.service.annotations .Values.commonAnnotations ) "context" . ) }} annotations: {{- include "common.tplvalues.render" ( dict "value" $annotations "context" $) | nindent 4 }} {{- end }} spec: type: {{ .Values.queryFrontend.service.type }} {{- if .Values.queryFrontend.service.sessionAffinity }} sessionAffinity: {{ .Values.queryFrontend.service.sessionAffinity }} {{- end }} {{- if .Values.queryFrontend.service.sessionAffinityConfig }} sessionAffinityConfig: {{- include "common.tplvalues.render" (dict "value" .Values.queryFrontend.service.sessionAffinityConfig "context" $) | nindent 4 }} {{- end }} {{- if .Values.queryFrontend.service.clusterIP }} clusterIP: {{ .Values.queryFrontend.service.clusterIP }} {{- end }} {{- if (or (eq .Values.queryFrontend.service.type "LoadBalancer") (eq .Values.queryFrontend.service.type "NodePort")) }} externalTrafficPolicy: {{ .Values.queryFrontend.service.externalTrafficPolicy | quote }} {{- end }} {{ if eq .Values.queryFrontend.service.type "LoadBalancer" }} loadBalancerSourceRanges: {{ .Values.queryFrontend.service.loadBalancerSourceRanges }} {{ end }} {{- if (and (eq .Values.queryFrontend.service.type "LoadBalancer") (not (empty .Values.queryFrontend.service.loadBalancerIP))) }} loadBalancerIP: {{ .Values.queryFrontend.service.loadBalancerIP }} {{- end }} publishNotReadyAddresses: true ports: - name: http port: {{ .Values.queryFrontend.service.ports.http }} targetPort: http protocol: TCP {{- if (and (or (eq .Values.queryFrontend.service.type "NodePort") (eq .Values.queryFrontend.service.type "LoadBalancer")) (not (empty .Values.queryFrontend.service.nodePorts.http))) }} nodePort: {{ .Values.queryFrontend.service.nodePorts.http }} {{- else if eq .Values.queryFrontend.service.type "ClusterIP" }} nodePort: null {{- end }} - name: grpc port: {{ .Values.queryFrontend.service.ports.grpc }} targetPort: grpc protocol: TCP {{- if (and (or (eq .Values.queryFrontend.service.type "NodePort") (eq .Values.queryFrontend.service.type "LoadBalancer")) (not (empty .Values.queryFrontend.service.nodePorts.grpc))) }} nodePort: {{ .Values.queryFrontend.service.nodePorts.grpc }} {{- else if eq .Values.queryFrontend.service.type "ClusterIP" }} nodePort: null {{- end }} {{- if .Values.queryFrontend.service.extraPorts }} {{- include "common.tplvalues.render" (dict "value" .Values.queryFrontend.service.extraPorts "context" $) | nindent 4 }} {{- end }} {{- $podLabels := include "common.tplvalues.merge" ( dict "values" ( list .Values.queryFrontend.podLabels .Values.commonLabels ) "context" . ) }} selector: {{- include "common.labels.matchLabels" ( dict "customLabels" $podLabels "context" $ ) | nindent 4 }} app.kubernetes.io/part-of: grafana-loki app.kubernetes.io/component: query-frontend ```
```cython # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # # path_to_url # # Unless required by applicable law or agreed to in writing, # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # specific language governing permissions and limitations # distutils: language = c++ # cython: embedsignature = True include "config.pxi" from libcpp.string cimport string from libcpp cimport bool as c_bool from libcpp.map cimport map cimport cpython from cython.operator cimport dereference as deref from libkudu_client cimport * from kudu.compat import tobytes, frombytes, dict_iter from kudu.schema cimport Schema, ColumnSchema, ColumnSpec, KuduValue, KuduType from kudu.errors cimport check_status from kudu.util import to_unixtime_micros, from_unixtime_micros, \ from_hybridtime, to_unscaled_decimal, from_unscaled_decimal, \ unix_epoch_days_to_date, date_to_unix_epoch_days from errors import KuduException import six # True if this python client was compiled with a # compiler that supports __int128 which is required # for decimal type support. This is generally true # except for EL6 environments. IF PYKUDU_INT128_SUPPORTED == 1: CLIENT_SUPPORTS_DECIMAL = True ELSE: CLIENT_SUPPORTS_DECIMAL = False try: import pandas CLIENT_SUPPORTS_PANDAS = True except ImportError: CLIENT_SUPPORTS_PANDAS = False # Replica selection enums LEADER_ONLY = ReplicaSelection_Leader CLOSEST_REPLICA = ReplicaSelection_Closest FIRST_REPLICA = ReplicaSelection_First cdef dict _replica_selection_policies = { 'leader': ReplicaSelection_Leader, 'closest': ReplicaSelection_Closest, 'first': ReplicaSelection_First } # Read mode enums READ_LATEST = ReadMode_Latest READ_AT_SNAPSHOT = ReadMode_Snapshot READ_YOUR_WRITES = ReadMode_ReadYourWrites cdef dict _read_modes = { 'latest': ReadMode_Latest, 'snapshot': ReadMode_Snapshot, 'read_your_writes': ReadMode_ReadYourWrites } ENCRYPTION_OPTIONAL = EncryptionPolicy_Optional ENCRYPTION_REQUIRED_REMOTE = EncryptionPolicy_RequiredRemote ENCRYPTION_REQUIRED = EncryptionPolicy_Required cdef dict _encryption_policies = { 'optional': EncryptionPolicy_Optional, 'required_remote': EncryptionPolicy_RequiredRemote, 'required': EncryptionPolicy_Required } cdef dict _type_names = { KUDU_INT8 : "KUDU_INT8", KUDU_INT16 : "KUDU_INT16", KUDU_INT32 : "KUDU_INT32", KUDU_INT64 : "KUDU_INT64", KUDU_STRING : "KUDU_STRING", KUDU_BOOL : "KUDU_BOOL", KUDU_FLOAT : "KUDU_FLOAT", KUDU_DOUBLE : "KUDU_DOUBLE", KUDU_BINARY : "KUDU_BINARY", KUDU_UNIXTIME_MICROS : "KUDU_UNIXTIME_MICROS", KUDU_DECIMAL : "KUDU_DECIMAL", KUDU_VARCHAR : "KUDU_VARCHAR", KUDU_DATE : "KUDU_DATE" } # Range Partition Bound Type enums EXCLUSIVE_BOUND = PartitionType_Exclusive INCLUSIVE_BOUND = PartitionType_Inclusive cdef dict _partition_bound_types = { 'exclusive': PartitionType_Exclusive, 'inclusive': PartitionType_Inclusive } def _check_convert_range_bound_type(bound): # Convert bounds types to constants and raise exception if invalid. def invalid_bound_type(bound_type): raise ValueError('Invalid range partition bound type: {0}' .format(bound_type)) if isinstance(bound, int): if bound >= len(_partition_bound_types) \ or bound < 0: invalid_bound_type(bound) else: return bound else: try: return _partition_bound_types[bound.lower()] except KeyError: invalid_bound_type(bound) def _correct_pandas_data_type(dtype): """ This method returns the correct Pandas data type for some data types that are converted incorrectly by Pandas. Returns ------- pdtype : type """ import numpy as np if dtype == "int8": return np.int8 if dtype == "int16": return np.int16 if dtype == "int32": return np.int32 if dtype == "float": return np.float32 else: return None cdef class TimeDelta: """ Wrapper interface for kudu MonoDelta class, which is used to specify timedeltas for timeouts and other uses. """ cdef: MonoDelta delta def __cinit__(self): pass @staticmethod def from_seconds(seconds): """ Construct a new TimeDelta from fractional seconds. Parameters ---------- seconds : double Returns ------- delta : TimeDelta """ cdef TimeDelta result = TimeDelta() result.init(MonoDelta.FromSeconds(seconds)) return result @staticmethod def from_millis(int64_t ms): """ Construct a new TimeDelta from integer milliseconds. Parameters ---------- ms : int Returns ------- delta : TimeDelta """ cdef TimeDelta result = TimeDelta() result.init(MonoDelta.FromMilliseconds(ms)) return result @staticmethod def from_micros(int64_t us): """ Construct a new TimeDelta from integer microseconds. Parameters ---------- us : int Returns ------- delta : TimeDelta """ cdef TimeDelta result = TimeDelta() result.init(MonoDelta.FromMicroseconds(us)) return result @staticmethod def from_nanos(seconds): """ Construct a new TimeDelta from integer nanoseconds. Parameters ---------- ns : int Returns ------- delta : TimeDelta """ cdef TimeDelta result = TimeDelta() result.init(MonoDelta.FromNanoseconds(seconds)) return result cpdef double to_seconds(self): """ Return timedelta as fractional seconds. """ return self.delta.ToSeconds() cpdef int64_t to_millis(self): """ Return timedelta as exact milliseconds. """ return self.delta.ToMilliseconds() cpdef int64_t to_micros(self): """ Return timedelta as exact microseconds. """ return self.delta.ToMicroseconds() cpdef int64_t to_nanos(self): """ Return timedelta as exact nanoseconds. """ return self.delta.ToNanoseconds() cdef init(self, const MonoDelta& val): self.delta = val def __repr__(self): cdef object as_string if self.delta.Initialized(): as_string = self.delta.ToString() return 'kudu.TimeDelta({0})'.format(as_string) else: return 'kudu.TimeDelta()' def __richcmp__(TimeDelta self, TimeDelta other, int op): if op == cpython.Py_EQ: return self.delta.Equals(other.delta) elif op == cpython.Py_NE: return not self.delta.Equals(other.delta) elif op == cpython.Py_LT: return self.delta.LessThan(other.delta) elif op == cpython.Py_LE: return not self.delta.MoreThan(other.delta) elif op == cpython.Py_GT: return self.delta.MoreThan(other.delta) elif op == cpython.Py_GE: return not self.delta.LessThan(other.delta) else: raise ValueError('invalid operation: {0}'.format(op)) cdef class Client: """ The primary class for interacting with a Kudu cluster. Can connect to one or more Kudu master servers. Do not instantiate this class directly; use kudu.connect instead. """ def __cinit__(self, addr_or_addrs, admin_timeout_ms=None, rpc_timeout_ms=None, sasl_protocol_name=None, require_authentication=False, encryption_policy=ENCRYPTION_OPTIONAL, jwt=None, trusted_certificates=None): cdef: string c_addr vector[string] c_addrs KuduClientBuilder builder TimeDelta timeout # Python programs will often have already imported _ssl, which # has the side effect of initializing OpenSSL. So, we detect # whether _ssl is present, and if we can import it, we disable # Kudu's initialization to avoid a conflict. try: import _ssl except: pass else: check_status(DisableOpenSSLInitialization()) if isinstance(addr_or_addrs, six.string_types): addr_or_addrs = [addr_or_addrs] elif not isinstance(addr_or_addrs, list): addr_or_addrs = list(addr_or_addrs) # Raise exception for empty iters, otherwise the connection call # will hang if not addr_or_addrs: raise ValueError("Empty iterator for addr_or_addrs.") self.master_addrs = addr_or_addrs for addr in addr_or_addrs: c_addrs.push_back(tobytes(addr)) builder.master_server_addrs(c_addrs) if admin_timeout_ms is not None: timeout = TimeDelta.from_millis(admin_timeout_ms) builder.default_admin_operation_timeout(timeout.delta) if rpc_timeout_ms is not None: timeout = TimeDelta.from_millis(rpc_timeout_ms) builder.default_rpc_timeout(timeout.delta) if sasl_protocol_name is not None: builder.sasl_protocol_name(sasl_protocol_name) if require_authentication: builder.require_authentication(require_authentication) if jwt is not None: builder.jwt(tobytes(jwt)) if trusted_certificates is not None: for c in trusted_certificates: builder.trusted_certificate(tobytes(c)) builder.encryption_policy(encryption_policy) check_status(builder.Build(&self.client)) # A convenience self.cp = self.client.get() def __dealloc__(self): self.close() property is_multimaster: def __get__(self): return self.cp.IsMultiMaster() cpdef close(self): # Nothing yet to clean up here pass def latest_observed_timestamp(self): """ Get the highest timestamp observed by the client in UTC. This is intended to gain external consistency across clients. Note: The latest observed timestamp can also be used to start a snapshot scan on a table which is guaranteed to contain all data written or previously read by this client. This should be treated as experimental as it this method will change or disappear in a future release. Additionally, note that 1 must be added to the value to be used in snapshot reads (this is taken care of in the from_hybridtime method). Returns ------- latest : datetime.datetime """ return from_hybridtime(self.cp.GetLatestObservedTimestamp()) def create_table(self, table_name, Schema schema, partitioning, n_replicas=None, owner=None, comment=None): """ Creates a new Kudu table from the passed Schema and options. Parameters ---------- table_name : string schema : kudu.Schema Create using kudu.schema_builder partitioning : Partitioning object n_replicas : int Number of replicas to set. This should be an odd number. If not provided (or if <= 0), falls back to the server-side default. """ cdef: KuduTableCreator* c Status s c = self.cp.NewTableCreator() try: c.table_name(tobytes(table_name)) c.schema(schema.schema) self._apply_partitioning(c, partitioning, schema) if n_replicas: c.num_replicas(n_replicas) if owner: c.set_owner(tobytes(owner)) if comment: c.set_comment(tobytes(comment)) s = c.Create() check_status(s) finally: del c cdef _apply_partitioning(self, KuduTableCreator* c, part, Schema schema): cdef: vector[string] v PartialRow lower_bound PartialRow upper_bound PartialRow split_row KuduRangePartition* range_partition # Apply hash partitioning. for col_names, num_buckets, seed in part._hash_partitions: v.clear() for n in col_names: v.push_back(tobytes(n)) if seed: c.add_hash_partitions(v, num_buckets, seed) else: c.add_hash_partitions(v, num_buckets) # Apply range partitioning if part._range_partition_cols is not None: v.clear() for n in part._range_partition_cols: v.push_back(tobytes(n)) c.set_range_partition_columns(v) if part._range_partitions_with_custom_hash_schemas: for p in part._range_partitions_with_custom_hash_schemas: if not isinstance(p.lower_bound, PartialRow): lower_bound = schema.new_row(p.lower_bound) else: lower_bound = p.lower_bound lower_bound._own = 0 if not isinstance(p.upper_bound, PartialRow): upper_bound = schema.new_row(p.upper_bound) else: upper_bound = p.upper_bound upper_bound._own = 0 range_partition = new KuduRangePartition( lower_bound.row, upper_bound.row, p.lower_bound_type, p.upper_bound_type) for col_names, num_buckets, seed in p.hash_dimensions: v.clear() for n in col_names: v.push_back(tobytes(n)) range_partition.add_hash_partitions(v, num_buckets, seed if seed else 0) c.add_custom_range_partition(range_partition) if part._range_partitions: for partition in part._range_partitions: if not isinstance(partition[0], PartialRow): lower_bound = schema.new_row(partition[0]) else: lower_bound = partition[0] lower_bound._own = 0 if not isinstance(partition[1], PartialRow): upper_bound = schema.new_row(partition[1]) else: upper_bound = partition[1] upper_bound._own = 0 c.add_range_partition( lower_bound.row, upper_bound.row, _check_convert_range_bound_type(partition[2]), _check_convert_range_bound_type(partition[3]) ) if part._range_partition_splits: for split in part._range_partition_splits: if not isinstance(split, PartialRow): split_row = schema.new_row(split) else: split_row = split split_row._own = 0 c.add_range_partition_split(split_row.row) def delete_table(self, table_name): """ Delete/drop a Kudu table without reserving. Raises KuduNotFound if the table does not exist. Notes ----- The deleted table may turn to soft-deleted status with the flag default_deleted_table_reserve_seconds set to nonzero on the master side. The delete operation or drop operation means that the service will directly delete the table after receiving the instruction. Which means that once we delete the table by mistake, we have no way to recall the deleted data. We have added a new API @soft_delete_table to allow the deleted data to be reserved for a period of time, which means that the wrongly deleted data may be recalled. In order to be compatible with the previous versions, this interface will continue to directly delete tables without reserving the table. Refer to soft_delete_table for detailed usage examples. Parameters ---------- table_name : string """ check_status(self.cp.DeleteTable(tobytes(table_name))) def soft_delete_table(self, table_name, reserve_seconds=None): """ Soft delete/drop a table. Notes ----- Usage Example1: Equal to delete_table(table_name) and the table will not be reserved. client.soft_delete_table(table_name) Usage Example2: The table will be reserved for 600s after delete operation. We can recall the table in time after the delete. client.soft_delete_table(table_name, 600) client.recall_table(table_id) Parameters ---------- table_name : string Name of the table to drop. reserve_seconds : int Reserve seconds after being deleted. """ if reserve_seconds is not None: check_status(self.cp.SoftDeleteTable(tobytes(table_name), reserve_seconds)) else: check_status(self.cp.SoftDeleteTable(tobytes(table_name))) def recall_table(self, table_id, new_table_name=None): """ Recall a deleted but still reserved table. Parameters ---------- table_id : string ID of the table to recall. new_table_name : string New table name for the recalled table. The recalled table will use the original table name if the parameter is empty string (i.e. ""). """ if new_table_name is not None: check_status(self.cp.RecallTable(tobytes(table_id), tobytes(new_table_name))) else: check_status(self.cp.RecallTable(tobytes(table_id))) def table_exists(self, table_name): """Return True if the indicated table exists in the Kudu cluster. Parameters ---------- table_name : string Returns ------- exists : bool """ cdef: string c_name = tobytes(table_name) c_bool exists check_status(self.cp.TableExists(c_name, &exists)) return exists def deserialize_token_into_scanner(self, serialized_token): """ Deserializes a ScanToken using the client and returns a scanner. Parameters ---------- serialized_token : String Serialized form of a ScanToken. Returns ------- scanner : Scanner """ token = ScanToken() return token.deserialize_into_scanner(self, serialized_token) def table(self, table_name): """ Construct a kudu.Table and retrieve its schema from the cluster. Raises KuduNotFound if the table does not exist. Parameters ---------- table_name : string Returns ------- table : kudu.Table """ table_name = tobytes(table_name) cdef Table table = Table(table_name, self) check_status(self.cp.OpenTable(table_name, &table.table)) table.init() return table def list_tables(self, match_substring=None): """ Retrieve a list of non-soft-deleted table names in the Kudu cluster with an optional substring filter. Parameters ---------- match_substring : string, optional If passed, the string must be exactly contained in the table names Returns ------- tables : list[string] Table names returned from Kudu """ cdef: vector[string] tables string c_match size_t i if match_substring is not None: c_match = tobytes(match_substring) check_status(self.cp.ListTables(&tables, c_match)) else: check_status(self.cp.ListTables(&tables)) result = [] for i in range(tables.size()): result.append(frombytes(tables[i])) return result def list_soft_deleted_tables(self, match_substring=None): """ Retrieve a list of soft-deleted table names in the Kudu cluster with an optional substring filter. Parameters ---------- match_substring : string, optional If passed, the string must be exactly contained in the table names Returns ------- tables : list[string] Table names returned from Kudu """ cdef: vector[string] tables string c_match size_t i if match_substring is not None: c_match = tobytes(match_substring) check_status(self.cp.ListSoftDeletedTables(&tables, c_match)) else: check_status(self.cp.ListSoftDeletedTables(&tables)) result = [] for i in range(tables.size()): result.append(frombytes(tables[i])) return result def list_tablet_servers(self): """ Retrieve a list of tablet servers currently running in the Kudu cluster Returns ------- tservers : list[TabletServer] List of TabletServer objects """ cdef: vector[KuduTabletServer*] tservers size_t i check_status(self.cp.ListTabletServers(&tservers)) result = [] for i in range(tservers.size()): ts = TabletServer() ts._own = 1 result.append(ts._init(tservers[i])) return result def new_session(self, flush_mode='manual', timeout_ms=5000, **kwargs): """ Create a new KuduSession for applying write operations. Parameters ---------- flush_mode : {'manual', 'sync', 'background'}, default 'manual' See Session.set_flush_mode timeout_ms : int, default 5000 Timeout in milliseconds mutation_buffer_sz : Size in bytes of the buffer space. mutation_buffer_watermark : Watermark level as percentage of the mutation buffer size, this is used to trigger a flush in AUTO_FLUSH_BACKGROUND mode. mutation_buffer_flush_interval : The duration of the interval for the time-based flushing, in milliseconds. In some cases, while running in AUTO_FLUSH_BACKGROUND mode, the size of the mutation buffer for pending operations and the flush watermark for fresh operations may be too high for the rate of incoming data: it would take too long to accumulate enough data in the buffer to trigger flushing. I.e., it makes sense to flush the accumulated operations if the prior flush happened long time ago. This parameter sets the wait interval for the time-based flushing which takes place along with the flushing triggered by the over-the-watermark criterion. By default, the interval is set to 1000 ms (i.e. 1 second). mutation_buffer_max_num : The maximum number of mutation buffers per KuduSession object to hold the applied operations. Use 0 to set the maximum number of concurrent mutation buffers to unlimited Returns ------- session : kudu.Session """ cdef Session result = Session() result.s = self.cp.NewSession() result.set_flush_mode(flush_mode) result.set_timeout_ms(timeout_ms) if "mutation_buffer_sz" in kwargs: result.set_mutation_buffer_space(kwargs["mutation_buffer_sz"]) if "mutation_buffer_watermark" in kwargs: result.set_mutation_buffer_flush_watermark(kwargs["mutation_buffer_watermark"]) if "mutation_buffer_flush_interval" in kwargs: result.set_mutation_buffer_flush_interval(kwargs["mutation_buffer_flush_interval"]) if "mutation_buffer_max_num" in kwargs: result.set_mutation_buffer_max_num(kwargs["mutation_buffer_max_num"]) return result def new_table_alterer(self, Table table): """ Create a TableAlterer object that can be used to apply a set of steps to alter a table. Parameters ---------- table : Table Table to alter. NOTE: The TableAlterer.alter() method will return a new Table object with the updated information. Examples -------- table = client.table('example') alterer = client.new_table_alterer(table) table = alterer.rename('example2').alter() Returns ------- alterer : TableAlterer """ return TableAlterer(table) #your_sha256_hash------ # Handle marshalling Python values to raw values. Since range predicates # require a const void*, this is one valid (though a bit verbose) # approach. Note that later versions of Cython handle many Python -> C type # casting problems (and integer overflows), but these should all be tested # rigorously in our test suite cdef class RawValue: cdef: void* data def __cinit__(self): self.data = NULL cdef class Int8Val(RawValue): cdef: int8_t val def __cinit__(self, obj): self.val = <int8_t> obj self.data = &self.val cdef class Int16Val(RawValue): cdef: int16_t val def __cinit__(self, obj): self.val = <int16_t> obj self.data = &self.val cdef class Int32Val(RawValue): cdef: int32_t val def __cinit__(self, obj): self.val = <int32_t> obj self.data = &self.val cdef class Int64Val(RawValue): cdef: int64_t val def __cinit__(self, obj): self.val = <int64_t> obj self.data = &self.val cdef class DoubleVal(RawValue): cdef: double val def __cinit__(self, obj): self.val = <double> obj self.data = &self.val cdef class FloatVal(RawValue): cdef: float val def __cinit__(self, obj): self.val = <float> obj self.data = &self.val cdef class BoolVal(RawValue): cdef: c_bool val def __cinit__(self, obj): self.val = <c_bool> obj self.data = &self.val cdef class StringVal(RawValue): cdef: # Python "str" object that was passed into the constructor. # We hold a reference to this so that the underlying data # doesn't go out of scope. object py_str # Heap-allocated Slice object, owned by this instance, # which points to the data in 'py_str' cdef Slice* val def __cinit__(self, obj): self.py_str = obj self.val = new Slice(<char*>self.py_str, len(self.py_str)) # The C++ API expects a Slice* to be passed to the range predicate # constructor. self.data = self.val def __dealloc__(self): del self.val cdef class UnixtimeMicrosVal(RawValue): cdef: int64_t val def __cinit__(self, obj): self.val = to_unixtime_micros(obj) self.data = &self.val cdef class DateVal(RawValue): cdef: int32_t val def __cinit__(self, obj): self.val = date_to_unix_epoch_days(obj) self.data = &self.val #your_sha256_hash------ cdef class TabletServer: """ Represents a Kudu tablet server, containing the uuid, hostname and port. Create a list of TabletServers by using the kudu.Client.list_tablet_servers method after connecting to a cluster """ cdef: const KuduTabletServer* _tserver public bint _own cdef _init(self, const KuduTabletServer* tserver): self._tserver = tserver self._own = 0 return self def __dealloc__(self): if self._tserver != NULL and self._own: del self._tserver def __richcmp__(TabletServer self, TabletServer other, int op): if op == 2: # == return ((self.uuid(), self.hostname(), self.port()) == (other.uuid(), other.hostname(), other.port())) elif op == 3: # != return ((self.uuid(), self.hostname(), self.port()) != (other.uuid(), other.hostname(), other.port())) else: raise NotImplementedError def uuid(self): return frombytes(self._tserver.uuid()) def hostname(self): return frombytes(self._tserver.hostname()) def port(self): return self._tserver.port() cdef class Table: """ Represents a Kudu table, containing the schema and other tools. Create by using the kudu.Client.table method after connecting to a cluster. """ def __cinit__(self, name, Client client): self._name = name self.parent = client # Users should not instantiate directly self.schema = Schema() cdef init(self): # Called after the refptr has been populated self.schema.schema = &self.ptr().schema() self.schema.own_schema = 0 self.schema.parent = self self.num_replicas = self.ptr().num_replicas() def __len__(self): # TODO: is this cheaply knowable? raise NotImplementedError def __getitem__(self, key): spec = self.schema[key] return Column(self, spec) property name: """Name of the table.""" def __get__(self): return frombytes(self.ptr().name()) property id: """Identifier string for the table.""" def __get__(self): return frombytes(self.ptr().id()) # XXX: don't love this name property num_columns: """Number of columns in the table's schema.""" def __get__(self): return len(self.schema) property owner: """Name of the owner of the table.""" def __get__(self): return frombytes(self.ptr().owner()) property comment: """Comment on the table.""" def __get__(self): return frombytes(self.ptr().comment()) def rename(self, new_name): raise NotImplementedError def drop(self): raise NotImplementedError def new_insert(self, record=None): """ Create a new Insert operation. Pass the completed Insert to a Session. If a record is provided, a PartialRow will be initialized with values from the input record. The record can be in the form of a tuple, dict, or list. Dictionary keys can be either column names, indexes, or a mix of both names and indexes. Parameters ---------- record : tuple/list/dict Returns ------- insert : Insert """ return Insert(self, record) def new_insert_ignore(self, record=None): """ Create a new InsertIgnore operation. Pass the completed InsertIgnore to a Session. If a record is provided, a PartialRow will be initialized with values from the input record. The record can be in the form of a tuple, dict, or list. Dictionary keys can be either column names, indexes, or a mix of both names and indexes. Parameters ---------- record : tuple/list/dict Returns ------- insertIgnore : InsertIgnore """ return InsertIgnore(self, record) def new_upsert(self, record=None): """ Create a new Upsert operation. Pass the completed Upsert to a Session. If a record is provided, a PartialRow will be initialized with values from the input record. The record can be in the form of a tuple, dict, or list. Dictionary keys can be either column names, indexes, or a mix of both names and indexes. Parameters ---------- record : tuple/list/dict Returns ------- upsert : Upsert """ return Upsert(self, record) def new_upsert_ignore(self, record=None): """ Create a new UpsertIgnore operation. Pass the completed UpsertIgnore to a Session. If a record is provided, a PartialRow will be initialized with values from the input record. The record can be in the form of a tuple, dict, or list. Dictionary keys can be either column names, indexes, or a mix of both names and indexes. Parameters ---------- record : tuple/list/dict Returns ------- upsertIgnore : UpsertIgnore """ return UpsertIgnore(self, record) def new_update(self, record=None): """ Create a new Update operation. Pass the completed Update to a Session. If a record is provided, a PartialRow will be initialized with values from the input record. The record can be in the form of a tuple, dict, or list. Dictionary keys can be either column names, indexes, or a mix of both names and indexes. Parameters ---------- record : tuple/list/dict Returns ------- update : Update """ return Update(self, record) def new_update_ignore(self, record=None): """ Create a new UpdateIgnore operation. Pass the completed UpdateIgnore to a Session. If a record is provided, a PartialRow will be initialized with values from the input record. The record can be in the form of a tuple, dict, or list. Dictionary keys can be either column names, indexes, or a mix of both names and indexes. Parameters ---------- record : tuple/list/dict Returns ------- updateIgnore : UpdateIgnore """ return UpdateIgnore(self, record) def new_delete(self, record=None): """ Create a new Delete operation. Pass the completed Update to a Session. If a record is provided, a PartialRow will be initialized with values from the input record. The record can be in the form of a tuple, dict, or list. Dictionary keys can be either column names, indexes, or a mix of both names and indexes. Parameters ---------- record : tuple/list/dict Returns ------- delete : Delete """ return Delete(self, record) def new_delete_ignore(self, record=None): """ Create a new DeleteIgnore operation. Pass the completed DeleteIgnore to a Session. If a record is provided, a PartialRow will be initialized with values from the input record. The record can be in the form of a tuple, dict, or list. Dictionary keys can be either column names, indexes, or a mix of both names and indexes. Parameters ---------- record : tuple/list/dict Returns ------- deleteIgnore : DeleteIgnore """ return DeleteIgnore(self, record) def scanner(self): """ Create a new scanner for this table for retrieving a selection of table rows. Examples -------- scanner = table.scanner() scanner.add_predicate(table['key'] > 10) scanner.open() batch = scanner.read_all() tuples = batch.as_tuples() Returns ------- scanner : kudu.Scanner """ cdef Scanner result = Scanner(self) result.scanner = new KuduScanner(self.ptr()) return result def scan_token_builder(self): """ Create a new ScanTokenBuilder for this table to build a series of scan tokens. Examples -------- builder = table.scan_token_builder() builder.set_fault_tolerant().add_predicate(table['key'] > 10) tokens = builder.build() for token in tokens: scanner = token.into_kudu_scanner() scanner.open() tuples = scanner.read_all_tuples() Returns ------- builder : ScanTokenBuilder """ return ScanTokenBuilder(self) cdef class Column: """ A reference to a Kudu table column intended to simplify creating predicates and other column-specific operations. Write arithmetic comparisons to create new Predicate objects that can be passed to a Scanner. Examples -------- scanner.add_predicate(table[col_name] <= 10) """ cdef readonly: Table parent ColumnSchema spec str name def __cinit__(self, Table parent, ColumnSchema spec): self.name = spec.name self.parent = parent self.spec = spec def __repr__(self): result = ('Column({0}, parent={1}, type={2})' .format(self.name, self.parent.name, self.spec.type.name)) return result def __richcmp__(Column self, value, int op): cdef: KuduPredicate* pred KuduValue val Slice col_name_slice ComparisonOp cmp_op Predicate result object _name = tobytes(self.name) col_name_slice = Slice(<char*> _name, len(_name)) if op == 0: # < cmp_op = KUDU_LESS elif op == 1: # <= cmp_op = KUDU_LESS_EQUAL elif op == 2: # == cmp_op = KUDU_EQUAL elif op == 4: # > cmp_op = KUDU_GREATER elif op == 5: # >= cmp_op = KUDU_GREATER_EQUAL else: raise NotImplementedError val = self.spec.type.new_value(value) pred = (self.parent.ptr() .NewComparisonPredicate(col_name_slice, cmp_op, val._value)) result = Predicate() result.init(pred) return result def in_list(Column self, values): """ Creates a new InListPredicate for the Column. If a single value is provided, then an equality comparison predicate is created. Parameters ---------- values : list Examples -------- scanner.add_predicate(table['key'].in_list([1, 2, 3]) Returns ------- pred : Predicate """ cdef: KuduPredicate* pred KuduValue kval vector[C_KuduValue*] vals Slice col_name_slice Predicate result object _name = tobytes(self.name) col_name_slice = Slice(<char*> _name, len(_name)) try: for val in values: kval = self.spec.type.new_value(val) vals.push_back(kval._value) except TypeError: while not vals.empty(): _val = vals.back() del _val vals.pop_back() raise pred = (self.parent.ptr() .NewInListPredicate(col_name_slice, &vals)) result = Predicate() result.init(pred) return result def is_not_null(Column self): """ Creates a new IsNotNullPredicate for the Column which can be used for scanners on this table. Examples -------- scanner.add_predicate(table[col_name].is_not_null()) Returns ------- pred : Predicate """ cdef: KuduPredicate* pred Slice col_name_slice Predicate result object _name = tobytes(self.name) col_name_slice = Slice(<char*> _name, len(_name)) pred = (self.parent.ptr() .NewIsNotNullPredicate(col_name_slice)) result = Predicate() result.init(pred) return result def is_null(Column self): """ Creates a new IsNullPredicate for the Column which can be used for scanners on this table. Examples -------- scanner.add_predicate(table[col_name].is_null()) Returns ------- pred : Predicate """ cdef: KuduPredicate* pred Slice col_name_slice Predicate result object _name = tobytes(self.name) col_name_slice = Slice(<char*> _name, len(_name)) pred = (self.parent.ptr() .NewIsNullPredicate(col_name_slice)) result = Predicate() result.init(pred) return result class RangePartition(object): """ Argument to Client.add_custom_range_partition(...) to contain information on the range bounds and range-specific hash schema. """ def __init__(self, lower_bound=None, upper_bound=None, lower_bound_type='inclusive', upper_bound_type='exclusive'): """ Parameters ---------- lower_bound : PartialRow/list/tuple/dict upper_bound : PartialRow/list/tuple/dict lower_bound_type : {'inclusive', 'exclusive'} or constants kudu.EXCLUSIVE_BOUND and kudu.INCLUSIVE_BOUND upper_bound_type : {'inclusive', 'exclusive'} or constants kudu.EXCLUSIVE_BOUND and kudu.INCLUSIVE_BOUND """ self.lower_bound = lower_bound self.upper_bound = upper_bound self.lower_bound_type = _check_convert_range_bound_type(lower_bound_type) self.upper_bound_type = _check_convert_range_bound_type(upper_bound_type) self.hash_dimensions = [] def add_hash_partitions(self, column_names, num_buckets, seed=None): """ Adds a dimension with the specified parameters to the custom hash schema for this range partition. Parameters ---------- column_names : list of string column names on which to compute hash function num_buckets : the number of buckets for the hash function seed : int - optional; the seed for the hash function mapping rows to buckets Returns ------- self: this object """ if isinstance(column_names, str): column_names = [column_names] self.hash_dimensions.append( (column_names, num_buckets, seed) ) return self class Partitioning(object): """ Argument to Client.create_table(...) to describe table partitioning. """ def __init__(self): self._hash_partitions = [] self._range_partition_cols = None self._range_partitions = [] self._range_partitions_with_custom_hash_schemas = [] self._range_partition_splits = [] def add_hash_partitions(self, column_names, num_buckets, seed=None): """ Adds a set of hash partitions to the table. For each set of hash partitions added to the table, the total number of table partitions is multiplied by the number of buckets. For example, if a table is created with 3 split rows, and two hash partitions with 4 and 5 buckets respectively, the total number of table partitions will be 80 (4 range partitions * 4 hash buckets * 5 hash buckets). Optionally, a seed can be used to randomize the mapping of rows to hash buckets. Setting the seed may provide some amount of protection against denial of service attacks when the hashed columns contain user provided values. Parameters ---------- column_names : list of string column names on which to partition num_buckets : the number of buckets to create seed : int - optional Hash: seed for mapping rows to hash buckets. Returns ------- self: this object """ if isinstance(column_names, str): column_names = [column_names] self._hash_partitions.append( (column_names, num_buckets, seed) ) return self def set_range_partition_columns(self, column_names): """ Sets the columns on which the table will be range-partitioned. Every column must be a part of the table's primary key. If not set, the table will be created with the primary-key columns as the range-partition columns. If called with an empty vector, the table will be created without range partitioning. Parameters ---------- column_names : list of string column names on which to partition Returns ------- self: this object """ if isinstance(column_names, str): column_names = [column_names] self._range_partition_cols = column_names return self def add_range_partition(self, lower_bound=None, upper_bound=None, lower_bound_type='inclusive', upper_bound_type='exclusive'): """ Add a range partition to the table. Multiple range partitions may be added, but they must not overlap. All range splits specified by add_range_partition_split must fall in a range partition. The lower bound must be less than or equal to the upper bound. If this method is not called, the table's range will be unbounded. Parameters ---------- lower_bound : PartialRow/list/tuple/dict upper_bound : PartialRow/list/tuple/dict lower_bound_type : {'inclusive', 'exclusive'} or constants kudu.EXCLUSIVE_BOUND and kudu.INCLUSIVE_BOUND upper_bound_type : {'inclusive', 'exclusive'} or constants kudu.EXCLUSIVE_BOUND and kudu.INCLUSIVE_BOUND Returns ------- self : Partitioning """ if self._range_partition_cols: self._range_partitions.append( (lower_bound, upper_bound, lower_bound_type, upper_bound_type) ) else: raise ValueError("Range Partition Columns must be set before " + "adding a range partition.") return self def add_custom_range_partition(self, range_partition): """ Parameters ---------- range_partition : range partition with custom hash schema to add Returns ------- self : Partitioning """ if self._range_partition_cols is None: raise ValueError("Range Partition Columns must be set before " + "adding a range partition.") self._range_partitions_with_custom_hash_schemas.append(range_partition) return self def add_range_partition_split(self, split_row): """ Add a range partition split at the provided row. Parameters ---------- split_row : PartialRow/list/tuple/dict Returns ------- self : Partitioning """ if self._range_partition_cols: self._range_partition_splits.append(split_row) else: raise ValueError("Range Partition Columns must be set before " + "adding a range partition split.") return self cdef class Predicate: """ Wrapper for a KuduPredicate. Pass to Scanner.add_predicates """ cdef: KuduPredicate* pred def __cinit__(self): self.pred = NULL def __dealloc__(self): if self.pred != NULL: del self.pred cdef init(self, KuduPredicate* pred): self.pred = pred FLUSH_AUTO_SYNC = FlushMode_AutoSync FLUSH_AUTO_BACKGROUND = FlushMode_AutoBackground FLUSH_MANUAL = FlushMode_Manual cdef dict _flush_modes = { 'manual': FlushMode_Manual, 'sync': FlushMode_AutoSync, 'background': FlushMode_AutoBackground } cdef class Session: """ Wrapper for a client KuduSession to build up write operations to interact with the cluster. """ def __cinit__(self): pass def set_flush_mode(self, flush_mode='manual'): """ Set the session operation flush mode Parameters ---------- flush_mode : {'manual', 'sync', 'background'}, default 'manual' You can also use the constants FLUSH_MANUAL, FLUSH_AUTO_SYNC, and FLUSH_AUTO_BACKGROUND """ cdef Status status cdef FlushMode fmode if isinstance(flush_mode, int): # todo: validation fmode = <FlushMode> flush_mode else: try: fmode = _flush_modes[flush_mode.lower()] except KeyError: raise ValueError('Invalid flush mode: {0}' .format(flush_mode)) status = self.s.get().SetFlushMode(fmode) check_status(status) def set_timeout_ms(self, int64_t ms): """ Set the session timeout in milliseconds """ self.s.get().SetTimeoutMillis(ms) def set_mutation_buffer_space(self, size_t size_bytes): """ Set the amount of buffer space used by this session for outbound writes. The effect of the buffer size varies based on the flush mode of the session: AUTO_FLUSH_SYNC: since no buffering is done, this has no effect. AUTO_FLUSH_BACKGROUND: if the buffer space is exhausted, then write calls will block until there is space available in the buffer. MANUAL_FLUSH: if the buffer space is exhausted, then write calls will return an error By default, the buffer space is set to 7 MiB (i.e. 7 * 1024 * 1024 bytes). Parameters ---------- size_bytes : Size of the buffer space to set (number of bytes) """ status = self.s.get().SetMutationBufferSpace(size_bytes) check_status(status) def set_mutation_buffer_flush_watermark(self, double watermark_pct): """ Set the buffer watermark to trigger flush in AUTO_FLUSH_BACKGROUND mode. This method sets the watermark for fresh operations in the buffer when running in AUTO_FLUSH_BACKGROUND mode: once the specified threshold is reached, the session starts sending the accumulated write operations to the appropriate tablet servers. The flush watermark determines how much of the buffer space is taken by newly submitted operations. Setting this level to 100% results in flushing the buffer only when the newly applied operation would overflow the buffer. By default, the buffer flush watermark is set to 50%. Parameters ---------- watermark_pct : Watermark level as percentage of the mutation buffer size """ status = self.s.get().SetMutationBufferFlushWatermark(watermark_pct) check_status(status) def set_mutation_buffer_flush_interval(self, unsigned int millis): """ Set the interval for time-based flushing of the mutation buffer. In some cases, while running in AUTO_FLUSH_BACKGROUND mode, the size of the mutation buffer for pending operations and the flush watermark for fresh operations may be too high for the rate of incoming data: it would take too long to accumulate enough data in the buffer to trigger flushing. I.e., it makes sense to flush the accumulated operations if the prior flush happened long time ago. This method sets the wait interval for the time-based flushing which takes place along with the flushing triggered by the over-the-watermark criterion. By default, the interval is set to 1000 ms (i.e. 1 second). Parameters ---------- millis : The duration of the interval for the time-based flushing, in milliseconds. """ status = self.s.get().SetMutationBufferFlushInterval(millis) check_status(status) def set_mutation_buffer_max_num(self, unsigned int max_num): """ Set the maximum number of mutation buffers per Session object. A Session accumulates write operations submitted via the Apply() method in mutation buffers. A Session always has at least one mutation buffer. The mutation buffer which accumulates new incoming operations is called the current mutation buffer. The current mutation buffer is flushed using the Session.flush() method or it's done by the Session automatically if running in AUTO_FLUSH_BACKGROUND mode. After flushing the current mutation buffer, a new buffer is created upon calling Session.apply(), provided the limit is not exceeded. A call to Session.apply() blocks if it's at the maximum number of buffers allowed; the call unblocks as soon as one of the pending batchers finished flushing and a new batcher can be created. The minimum setting for this parameter is 1 (one). The default setting for this parameter is 2 (two). Parameters ---------- max_num : The maximum number of mutation buffers per Session object to hold the applied operations. Use 0 to set the maximum number of concurrent mutation buffers to unlimited. """ status = self.s.get().SetMutationBufferMaxNum(max_num) check_status(status) def apply(self, WriteOperation op): """ Apply the indicated write operation Examples -------- # Executes a single Insert operation session = client.new_session() op = table.new_insert() op['key'] = 0 op['value1'] = 5 op['value2'] = 3.5 session.apply(op) session.flush() """ return op.add_to_session(self) def flush(self): """ Flush pending operations """ check_status(self.s.get().Flush()) def get_pending_errors(self): """ Returns a list of buffered Kudu errors. A second value is returned indicating if there were more errors than could be stored in the session's error buffer (i.e. False means there was no error overflow) Returns ------- errors, overflowed : list, bool """ cdef: KuduError error vector[C_KuduError*] v_errors c_bool overflowed size_t i self.s.get().GetPendingErrors(&v_errors, &overflowed) result = [] for i in range(v_errors.size()): error = KuduError() error.error = v_errors[i] result.append(error) return result, overflowed def get_write_op_metrics(self): """ Return the cumulative write operation metrics since the beginning of the session. Returns ------- metrics : Dictionary """ _map = self.s.get().GetWriteOpMetrics().Get() # Convert map to python dictionary result = {} for it in _map: result[frombytes(it.first)] = it.second return result cdef class Row: """ A single row from a row batch """ cdef: RowBatch parent # This object is owned by the parent RowBatch KuduRowPtr row def __cinit__(self, batch): self.parent = batch def __dealloc__(self): pass cpdef tuple as_tuple(self): """ Return the row as a Python tuple """ cdef: int i, k tuple tup k = self.parent.batch.projection_schema().num_columns() tup = cpython.PyTuple_New(k) for i in range(k): val = None if not self.is_null(i): val = self.get_slot(i) cpython.Py_INCREF(val) cpython.PyTuple_SET_ITEM(tup, i, val) return tup cdef inline get_bool(self, int i): cdef c_bool val check_status(self.row.GetBool(i, &val)) # The built-in bool is masked by the libcpp typedef return bool(val) cdef inline get_int8(self, int i): cdef int8_t val check_status(self.row.GetInt8(i, &val)) return val cdef inline get_int16(self, int i): cdef int16_t val check_status(self.row.GetInt16(i, &val)) return val cdef inline get_int32(self, int i): cdef int32_t val check_status(self.row.GetInt32(i, &val)) return val cdef inline get_int64(self, int i): cdef int64_t val check_status(self.row.GetInt64(i, &val)) return val cdef inline get_double(self, int i): cdef double val check_status(self.row.GetDouble(i, &val)) return val cdef inline get_float(self, int i): cdef float val check_status(self.row.GetFloat(i, &val)) return val cdef inline get_string(self, int i): cdef Slice val check_status(self.row.GetString(i, &val)) return cpython.PyBytes_FromStringAndSize(<char*> val.mutable_data(), val.size()) cdef inline get_binary(self, int i): cdef Slice val check_status(self.row.GetBinary(i, &val)) return cpython.PyBytes_FromStringAndSize(<char*> val.mutable_data(), val.size()) cdef inline get_unixtime_micros(self, int i): cdef int64_t val check_status(self.row.GetUnixTimeMicros(i, &val)) return val cdef inline __get_unscaled_decimal(self, int i): IF PYKUDU_INT128_SUPPORTED == 1: cdef int128_t val check_status(self.row.GetUnscaledDecimal(i, &val)) return val ELSE: raise KuduException("The decimal type is not supported when GCC version is < 4.6.0" % self) cdef inline get_decimal(self, int i): scale = self.parent.batch.projection_schema().Column(i).type_attributes().scale() return from_unscaled_decimal(self.__get_unscaled_decimal(i), scale) cdef inline get_varchar(self, int i): cdef Slice val check_status(self.row.GetVarchar(i, &val)) return cpython.PyBytes_FromStringAndSize(<char*> val.mutable_data(), val.size()) cdef inline get_date(self, int i): cdef int32_t val check_status(self.row.GetDate(i, &val)) return unix_epoch_days_to_date(val) cdef inline get_slot(self, int i): cdef: Status s DataType t = self.parent.batch.projection_schema().Column(i).type() if t == KUDU_BOOL: return self.get_bool(i) elif t == KUDU_INT8: return self.get_int8(i) elif t == KUDU_INT16: return self.get_int16(i) elif t == KUDU_INT32: return self.get_int32(i) elif t == KUDU_INT64: return self.get_int64(i) elif t == KUDU_DOUBLE: return self.get_double(i) elif t == KUDU_FLOAT: return self.get_float(i) elif t == KUDU_STRING: return frombytes(self.get_string(i)) elif t == KUDU_BINARY: return self.get_binary(i) elif t == KUDU_UNIXTIME_MICROS: return from_unixtime_micros(self.get_unixtime_micros(i)) elif t == KUDU_DECIMAL: return self.get_decimal(i) elif t == KUDU_VARCHAR: return frombytes(self.get_varchar(i)) elif t == KUDU_DATE: return self.get_date(i) else: raise TypeError("Cannot get kudu type <{0}>" .format(_type_names[t])) cdef inline bint is_null(self, int i): return self.row.IsNull(i) cdef class RowBatch: """ Class holding a batch of rows from a Scanner """ # This class owns the KuduScanBatch data cdef: KuduScanBatch batch def __len__(self): return self.batch.NumRows() def __getitem__(self, i): return self.get_row(i).as_tuple() def __iter__(self): cdef int i = 0 for i in range(len(self)): yield self.get_row(i).as_tuple() def as_tuples(self): """ Return RowBatch as a list of Python tuples To simplify testing for the moment. """ cdef list tuples = [] for i in range(self.batch.NumRows()): tuples.append(self.get_row(i).as_tuple()) return tuples cdef Row get_row(self, i): # TODO: boundscheck # For safety, we need to increment the parent reference count and hold # on to a reference internally so that if the RowBatch goes out of # scope we won't end up with orphaned Row objects. This isn't the best, # but an intermediate solution until we can do something better.. cdef Row row = Row(self) row.row = self.batch.Row(i) return row cdef class Scanner: """ A class for defining a selection of data we wish to scan out of a Kudu table. Create a scanner using Table.scanner. """ cdef: Table table KuduScanner* scanner bint is_open def __cinit__(self, Table table = None): self.table = table self.scanner = NULL self.is_open = 0 def __dealloc__(self): # We own this one if self.scanner != NULL: del self.scanner cdef inline ensure_open(self): if not self.is_open: self.open() def add_predicates(self, preds): """ Add a list of scan predicates to the scanner. Select columns from the parent table and make comparisons to create predicates. Returns a reference to itself to facilitate chaining. Examples -------- c = table[col_name] preds = [c >= 0, c <= 10] scanner.add_predicates(preds) Parameters ---------- preds : list of Predicate Returns ------- self : scanner """ for pred in preds: self.add_predicate(pred) return self cpdef add_predicate(self, Predicate pred): """ Add a scan predicates to the scanner. Select columns from the parent table and make comparisons to create predicates. Returns a reference to itself to facilitate chaining. Examples -------- pred = table[col_name] <= 10 scanner.add_predicate(pred) Parameters ---------- pred : kudu.Predicate Returns ------- self : scanner """ cdef KuduPredicate* clone # We clone the KuduPredicate so that the Predicate wrapper class can be # reused clone = pred.pred.Clone() check_status(self.scanner.AddConjunctPredicate(clone)) return self def set_projected_column_names(self, names): """ Sets the columns to be scanned. Parameters ---------- names : list of string Returns ------- self : Scanner """ if isinstance(names, str): names = [names] cdef vector[string] v_names for name in names: v_names.push_back(tobytes(name)) check_status(self.scanner.SetProjectedColumnNames(v_names)) return self def set_selection(self, replica_selection): """ Set the replica selection policy while scanning. Parameters ---------- replica_selection : {'leader', 'closest', 'first'} You can also use the constants LEADER_ONLY, CLOSEST_REPLICA, and FIRST_REPLICA Returns ------- self : Scanner """ cdef ReplicaSelection selection def invalid_selection_policy(): raise ValueError('Invalid replica selection policy: {0}' .format(replica_selection)) if isinstance(replica_selection, int): if 0 <= replica_selection < len(_replica_selection_policies): check_status(self.scanner.SetSelection( <ReplicaSelection> replica_selection)) else: invalid_selection_policy() else: try: check_status(self.scanner.SetSelection( _replica_selection_policies[replica_selection.lower()])) except KeyError: invalid_selection_policy() return self def set_projected_column_indexes(self, indexes): """ Sets the columns to be scanned. Parameters ---------- indexes : list of integers representing column indexes Returns ------- self : Scanner """ cdef vector[int] v_indexes = indexes check_status(self.scanner.SetProjectedColumnIndexes(v_indexes)) return self def set_read_mode(self, read_mode): """ Set the read mode for scanning. Parameters ---------- read_mode : {'latest', 'snapshot', 'read_your_writes'} You can also use the constants READ_LATEST, READ_AT_SNAPSHOT, READ_YOUR_WRITES Returns ------- self : Scanner """ cdef ReadMode rmode def invalid_selection_policy(): raise ValueError('Invalid read mode: {0}' .format(read_mode)) if isinstance(read_mode, int): if 0 <= read_mode < len(_read_modes): check_status(self.scanner.SetReadMode( <ReadMode> read_mode)) else: invalid_selection_policy() else: try: check_status(self.scanner.SetReadMode( _read_modes[read_mode.lower()])) except KeyError: invalid_selection_policy() return self def set_snapshot(self, timestamp, format=None): """ Set the snapshot timestamp for this scanner. Parameters --------- timestamp : datetime.datetime or string If a string is provided, a format must be provided as well. NOTE: This should be in UTC. If a timezone aware datetime object is provided, it will be converted to UTC, otherwise, all other input is assumed to be UTC. format : Required if a string timestamp is provided Uses the C strftime() function, see strftime(3) documentation. Returns ------- self : Scanner """ # Confirm that a format is provided if timestamp is a string if isinstance(timestamp, six.string_types) and not format: raise ValueError( "To use a string timestamp you must provide a format. " + "See the strftime(3) documentation.") snapshot_micros = to_unixtime_micros(timestamp, format) if snapshot_micros >= 0: check_status(self.scanner.SetSnapshotMicros( <uint64_t> snapshot_micros)) else: raise ValueError( "Snapshot Timestamps be greater than the unix epoch.") return self def set_limit(self, limit): """ Set a limit on the number of rows returned by this scanner. Must be a positive value. Parameters ---------- limit : the maximum number of rows to return Returns ------- self : Scanner """ if limit <= 0: raise ValueError("Limit must be positive.") check_status(self.scanner.SetLimit(<int64_t> limit)) def set_fault_tolerant(self): """ Makes the underlying KuduScanner fault tolerant. Returns a reference to itself to facilitate chaining. Returns ------- self : Scanner """ check_status(self.scanner.SetFaultTolerant()) return self def new_bound(self): """ Returns a new instance of a PartialRow to be later set with add_lower_bound()/add_exclusive_upper_bound(). Returns ------- bound : PartialRow """ return self.table.schema.new_row() def add_lower_bound(self, bound): """ Sets the (inclusive) lower bound of the scan. Returns a reference to itself to facilitate chaining. Parameters ---------- bound : PartialRow/tuple/list/dictionary Returns ------- self : Scanner """ cdef: PartialRow row # Convert record to bound if not isinstance(bound, PartialRow): row = self.table.schema.new_row(bound) else: row = bound check_status(self.scanner.AddLowerBound(deref(row.row))) return self def add_exclusive_upper_bound(self, bound): """ Sets the (exclusive) upper bound of the scan. Returns a reference to itself to facilitate chaining. Parameters ---------- bound : PartialRow/tuple/list/dictionary Returns ------- self : Scanner """ cdef: PartialRow row # Convert record to bound if not isinstance(bound, PartialRow): row = self.table.schema.new_row(bound) else: row = bound check_status(self.scanner.AddExclusiveUpperBound(deref(row.row))) return self def get_projection_schema(self): """ Returns the schema of the projection being scanned Returns ------- schema : kudu.Schema """ result = Schema() # Had to instantiate a new schema to return a pointer since the # GetProjectionSchema method does not cdef KuduSchema* schema = new KuduSchema(self.scanner. GetProjectionSchema()) result.schema = schema return result def get_resource_metrics(self): """ Return the cumulative resource metrics since the scan was started. Returns ------- metrics : Dictionary """ _map = self.scanner.GetResourceMetrics().Get() # Convert map to python dictionary result = {} for it in _map: result[frombytes(it.first)] = it.second return result def open(self): """ Returns a reference to itself to facilitate chaining Returns ------- self : Scanner """ if not self.is_open: check_status(self.scanner.Open()) self.is_open = 1 return self def has_more_rows(self): """ Returns True if there are more rows to be read. """ return self.scanner.HasMoreRows() def read_all_tuples(self): """ Compute a RowBatch containing all rows from the scan operation (which hopefully fit into memory, probably not handled gracefully at the moment). """ cdef list tuples = [] cdef RowBatch batch self.ensure_open() while self.has_more_rows(): batch = self.next_batch() tuples.extend(batch.as_tuples()) return tuples def xbatches(self): """ This method acts as a generator to enable more effective memory management by yielding batches of tuples. """ self.ensure_open() while self.has_more_rows(): yield self.next_batch().as_tuples() def read_next_batch_tuples(self): return self.next_batch().as_tuples() cpdef RowBatch next_batch(self): """ Retrieve the next batch of rows from the scanner. Returns ------- batch : RowBatch """ if not self.has_more_rows(): raise StopIteration cdef RowBatch batch = RowBatch() check_status(self.scanner.NextBatch(&batch.batch)) return batch def set_cache_blocks(self, cache_blocks): """ Sets the block caching policy. Returns a reference to itself to facilitate chaining. Parameters ---------- cache_blocks : bool Returns ------- self : Scanner """ check_status(self.scanner.SetCacheBlocks(cache_blocks)) return self def keep_alive(self): """ Keep the current remote scanner alive. Keep the current remote scanner alive on the Tablet server for an additional time-to-live (set by a configuration flag on the tablet server). This is useful if the interval in between NextBatch() calls is big enough that the remote scanner might be garbage collected (default ttl is set to 60 secs.). This does not invalidate any previously fetched results. Returns ------- self : Scanner """ check_status(self.scanner.KeepAlive()) return self def get_current_server(self): """ Get the TabletServer that is currently handling the scan. More concretely, this is the server that handled the most recent open() or next_batch() RPC made by the server. Returns ------- tserver : TabletServer """ cdef: TabletServer tserver = TabletServer() KuduTabletServer* tserver_p = NULL check_status(self.scanner.GetCurrentServer(&tserver_p)) tserver._own = 1 tserver._init(tserver_p) return tserver def close(self): """ Close the scanner. Closing the scanner releases resources on the server. This call does not block, and will not ever fail, even if the server cannot be contacted. Note: The scanner is reset to its initial state by this function. You'll have to re-add any projection, predicates, etc if you want to reuse this object. Note: When the Scanner object is garbage collected, this method is run. This method call is only needed if you want to explicitly release the resources on the server. """ self.scanner.Close() def to_pandas(self, index=None, coerce_float=False): """ Returns the contents of this Scanner to a Pandas DataFrame. This is only available if Pandas is installed. Note: This should only be used if the results from the scanner are expected to be small, as Pandas will load the entire contents into memory. Parameters ---------- index : string, list of fields Field or list of fields to use as the index coerce_float : boolean Attempt to convert decimal values to floating point (double precision). Returns ------- dataframe : DataFrame """ import pandas as pd self.ensure_open() # Here we are using list comprehension with the batch generator to avoid # doubling our memory footprint. dfs = [ pd.DataFrame.from_records(batch, index=index, coerce_float=coerce_float, columns=self.get_projection_schema().names) for batch in self.xbatches() if len(batch) != 0 ] df = pd.concat(dfs, ignore_index=not(bool(index))) types = {} for column in self.get_projection_schema(): pandas_type = _correct_pandas_data_type(column.type.name) if pandas_type is not None and \ not(column.nullable and df[column.name].isnull().any()): types[column.name] = pandas_type for col, dtype in types.items(): df[col] = df[col].astype(dtype, copy=False) return df cdef class ScanToken: """ A ScanToken describes a partial scan of a Kudu table limited to a single contiguous physical location. Using the KuduScanTokenBuilder, clients can describe the desired scan, including predicates, bounds, timestamps, and caching, and receive back a collection of scan tokens. """ cdef: KuduScanToken* _token def __cinit__(self): self._token = NULL def __dealloc__(self): if self._token != NULL: del self._token cdef _init(self, KuduScanToken* token): self._token = token return self def into_kudu_scanner(self): """ Returns a scanner under the current client. Returns ------- scanner : Scanner """ cdef: Scanner result = Scanner() KuduScanner* _scanner = NULL check_status(self._token.IntoKuduScanner(&_scanner)) result.scanner = _scanner return result def tablet(self): """ Returns the Tablet associated with this ScanToken Returns ------- tablet : Tablet """ tablet = Tablet() return tablet._init(&self._token.tablet()) def serialize(self): """ Serialize token into a string. Returns ------- serialized_token : string """ cdef string buf check_status(self._token.Serialize(&buf)) return buf def deserialize_into_scanner(self, Client client, serialized_token): """ Returns a new scanner from the serialized token created under the provided Client. Parameters ---------- client : Client serialized_token : string Returns ------- scanner : Scanner """ cdef: Scanner result = Scanner() KuduScanner* _scanner check_status(self._token.DeserializeIntoScanner(client.cp, serialized_token, &_scanner)) result.scanner = _scanner return result cdef class ScanTokenBuilder: """ This class builds ScanTokens for a Table. """ cdef: KuduScanTokenBuilder* _builder Table _table def __cinit__(self, Table table): self._table = table self._builder = new KuduScanTokenBuilder(table.ptr()) def __dealloc__(self): if self._builder != NULL: del self._builder def set_projected_column_names(self, names): """ Sets the columns to be scanned. Returns a reference to itself to facilitate chaining. Parameters ---------- names : list of strings Returns ------- self : ScanTokenBuilder """ if isinstance(names, str): names = [names] cdef vector[string] v_names for name in names: v_names.push_back(tobytes(name)) check_status(self._builder.SetProjectedColumnNames(v_names)) return self def set_projected_column_indexes(self, indexes): """ Sets the columns to be scanned. Returns a reference to itself to facilitate chaining. Parameters ---------- indexes : list of integers representing column indexes Returns ------- self : ScanTokenBuilder """ cdef vector[int] v_indexes = indexes check_status(self._builder.SetProjectedColumnIndexes(v_indexes)) return self def set_batch_size_bytes(self, batch_size): """ Sets the batch size in bytes. Returns a reference to itself to facilitate chaining. Parameters ---------- batch_size : Size of batch in bytes Returns ------- self : ScanTokenBuilder """ check_status(self._builder.SetBatchSizeBytes(batch_size)) return self def set_read_mode(self, read_mode): """ Set the read mode for scanning. Parameters ---------- read_mode : {'latest', 'snapshot'} You can also use the constants READ_LATEST, READ_AT_SNAPSHOT Returns ------- self : ScanTokenBuilder """ cdef ReadMode rmode def invalid_selection_policy(): raise ValueError('Invalid read mode: {0}' .format(read_mode)) if isinstance(read_mode, int): if 0 <= read_mode < len(_read_modes): check_status(self._builder.SetReadMode( <ReadMode> read_mode)) else: invalid_selection_policy() else: try: check_status(self._builder.SetReadMode( _read_modes[read_mode.lower()])) except KeyError: invalid_selection_policy() return self def set_snapshot(self, timestamp, format=None): """ Set the snapshot timestamp for this ScanTokenBuilder. Parameters --------- timestamp : datetime.datetime or string If a string is provided, a format must be provided as well. NOTE: This should be in UTC. If a timezone aware datetime object is provided, it will be converted to UTC, otherwise, all other input is assumed to be UTC. format : Required if a string timestamp is provided Uses the C strftime() function, see strftime(3) documentation. Returns ------- self : ScanTokenBuilder """ # Confirm that a format is provided if timestamp is a string if isinstance(timestamp, six.string_types) and not format: raise ValueError( "To use a string timestamp you must provide a format. " + "See the strftime(3) documentation.") snapshot_micros = to_unixtime_micros(timestamp, format) if snapshot_micros >= 0: check_status(self._builder.SetSnapshotMicros( <uint64_t> snapshot_micros)) else: raise ValueError( "Snapshot Timestamps be greater than the unix epoch.") return self def set_timeout_millis(self, millis): """ Sets the scan request timeout in milliseconds. Returns a reference to itself to facilitate chaining. Parameters ---------- millis : int64_t timeout in milliseconds Returns ------- self : ScanTokenBuilder """ check_status(self._builder.SetTimeoutMillis(millis)) return self def set_timout_millis(self, millis): """ See set_timeout_millis(). This method is deprecated due to having a typo in the method name and will be removed in a future release. """ return self.set_timeout_millis(millis) def set_fault_tolerant(self): """ Makes the underlying KuduScanner fault tolerant. Returns a reference to itself to facilitate chaining. Returns ------- self : ScanTokenBuilder """ check_status(self._builder.SetFaultTolerant()) return self def set_selection(self, replica_selection): """ Set the replica selection policy while scanning. Parameters ---------- replica_selection : {'leader', 'closest', 'first'} You can also use the constants LEADER_ONLY, CLOSEST_REPLICA, and FIRST_REPLICA Returns ------- self : ScanTokenBuilder """ cdef ReplicaSelection selection def invalid_selection_policy(): raise ValueError('Invalid replica selection policy: {0}' .format(replica_selection)) if isinstance(replica_selection, int): if 0 <= replica_selection < len(_replica_selection_policies): check_status(self._builder.SetSelection( <ReplicaSelection> replica_selection)) else: invalid_selection_policy() else: try: check_status(self._builder.SetSelection( _replica_selection_policies[replica_selection.lower()])) except KeyError: invalid_selection_policy() return self def add_predicates(self, preds): """ Add a list of scan predicates to the ScanTokenBuilder. Select columns from the parent table and make comparisons to create predicates. Examples -------- c = table[col_name] preds = [c >= 0, c <= 10] builder.add_predicates(preds) Parameters ---------- preds : list of Predicate """ for pred in preds: self.add_predicate(pred) cpdef add_predicate(self, Predicate pred): """ Add a scan predicates to the scan token. Select columns from the parent table and make comparisons to create predicates. Examples -------- pred = table[col_name] <= 10 builder.add_predicate(pred) Parameters ---------- pred : kudu.Predicate Returns ------- self : ScanTokenBuilder """ cdef KuduPredicate* clone # We clone the KuduPredicate so that the Predicate wrapper class can be # reused clone = pred.pred.Clone() check_status(self._builder.AddConjunctPredicate(clone)) def new_bound(self): """ Returns a new instance of a PartialRow to be later set with add_lower_bound()/add_upper_bound(). Returns ------- bound : PartialRow """ return self._table.schema.new_row() def add_lower_bound(self, bound): """ Sets the lower bound of the scan. Returns a reference to itself to facilitate chaining. Parameters ---------- bound : PartialRow/list/tuple/dict Returns ------- self : ScanTokenBuilder """ cdef: PartialRow row # Convert record to bound if not isinstance(bound, PartialRow): row = self._table.schema.new_row(bound) else: row = bound check_status(self._builder.AddLowerBound(deref(row.row))) return self def add_upper_bound(self, bound): """ Sets the upper bound of the scan. Returns a reference to itself to facilitate chaining. Parameters ---------- bound : PartialRow/list/tuple/dict Returns ------- self : ScanTokenBuilder """ cdef: PartialRow row # Convert record to bound if not isinstance(bound, PartialRow): row = self._table.schema.new_row(bound) else: row = bound check_status(self._builder.AddUpperBound(deref(row.row))) return self def set_cache_blocks(self, cache_blocks): """ Sets the block caching policy. Returns a reference to itself to facilitate chaining. Parameters ---------- cache_blocks : bool Returns ------- self : ScanTokenBuilder """ check_status(self._builder.SetCacheBlocks(cache_blocks)) return self def build(self): """ Build the set of scan tokens. The builder may be reused after this call. Returns a list of ScanTokens to be serialized and executed in parallel with seperate client instances. Returns ------- tokens : List[ScanToken] """ cdef: vector[KuduScanToken*] tokens size_t i check_status(self._builder.Build(&tokens)) result = [] for i in range(tokens.size()): token = ScanToken() result.append(token._init(tokens[i])) return result cdef class Tablet: """ Represents a remote Tablet. Contains the tablet id and Replicas associated with the Kudu Tablet. Retrieved by the ScanToken.tablet() method. """ cdef: const KuduTablet* _tablet vector[KuduReplica*] _replicas cdef _init(self, const KuduTablet* tablet): self._tablet = tablet return self def id(self): return frombytes(self._tablet.id()) def replicas(self): cdef size_t i result = [] _replicas = self._tablet.replicas() for i in range(_replicas.size()): replica = Replica() result.append(replica._init(_replicas[i])) return result cdef class Replica: """ Represents a remote Tablet's replica. Retrieve a list of Replicas with the Tablet.replicas() method. Contains the boolean is_leader and its respective TabletServer object. """ cdef const KuduReplica* _replica cdef _init(self, const KuduReplica* replica): self._replica = replica return self def is_leader(self): return self._replica.is_leader() def ts(self): ts = TabletServer() return ts._init(&self._replica.ts()) cdef class KuduError: """ Wrapper for a C++ KuduError indicating a client error resulting from applying operations in a session. """ cdef: C_KuduError* error def __cinit__(self): self.error = NULL def __dealloc__(self): # We own this object if self.error != NULL: del self.error def failed_op(self): """ Get debug string representation of the failed operation. Returns ------- op : str """ return frombytes(self.error.failed_op().ToString()) def was_possibly_successful(self): """ Check if there is a chance that the requested operation was successful. In some cases, it is possible that the server did receive and successfully perform the requested operation, but the client can't tell whether or not it was successful. For example, if the call times out, the server may still succeed in processing at a later time. Returns ------- result : bool """ return self.error.was_possibly_successful() def __repr__(self): return "KuduError('%s')" % (self.error.status().ToString()) cdef class PartialRow: def __cinit__(self, Schema schema): # This gets called before any subclass cinit methods self.schema = schema self._own = 1 def __dealloc__(self): if self._own and self.row != NULL: del self.row def __setitem__(self, key, value): if isinstance(key, basestring): self.set_field(key, value) else: if 0 <= key < len(self.schema): self.set_loc(key, value) else: raise IndexError("Column index {0} is out of bounds." .format(key)) def from_record(self, record): """ Initializes PartialRow with values from an input record. The record can be in the form of a tuple, dict, or list. Dictionary keys can be either column names or indexes. Parameters ---------- record : tuple/list/dict Returns ------- self : PartialRow """ if isinstance(record, (tuple, list)): for indx, val in enumerate(record): self[indx] = val elif isinstance(record, dict): for key, val in dict_iter(record): self[key] = val else: raise TypeError("Invalid record type <{0}> for " + "PartialRow.from_record." .format(type(record).__name__)) return self cpdef set_field(self, key, value): cdef: int i = self.schema.get_loc(key) self.set_loc(i, value) cpdef set_loc(self, int i, value): cdef: DataType t = self.schema.loc_type(i) Slice slc if value is None: check_status(self.row.SetNull(i)) return # Leave it to Cython to do the coercion and complain if it doesn't # work. Cython will catch many casting problems but we should verify # with unit tests. if t == KUDU_BOOL: check_status(self.row.SetBool(i, <c_bool> value)) elif t == KUDU_INT8: check_status(self.row.SetInt8(i, <int8_t> value)) elif t == KUDU_INT16: check_status(self.row.SetInt16(i, <int16_t> value)) elif t == KUDU_INT32: check_status(self.row.SetInt32(i, <int32_t> value)) elif t == KUDU_INT64: check_status(self.row.SetInt64(i, <int64_t> value)) elif t == KUDU_FLOAT: check_status(self.row.SetFloat(i, <float> value)) elif t == KUDU_DOUBLE: check_status(self.row.SetDouble(i, <double> value)) elif t == KUDU_STRING: if isinstance(value, unicode): value = value.encode('utf8') slc = Slice(<char*> value, len(value)) check_status(self.row.SetStringCopy(i, slc)) elif t == KUDU_BINARY: if isinstance(value, unicode): raise TypeError("Unicode objects must be explicitly encoded " + "before storing in a Binary field.") slc = Slice(<char*> value, len(value)) check_status(self.row.SetBinaryCopy(i, slc)) elif t == KUDU_VARCHAR: if isinstance(value, unicode): value = value.encode('utf8') slc = Slice(<char*> value, len(value)) check_status(self.row.SetVarchar(i, slc)) elif t == KUDU_UNIXTIME_MICROS: check_status(self.row.SetUnixTimeMicros(i, <int64_t> to_unixtime_micros(value))) elif t == KUDU_DATE: val = date_to_unix_epoch_days(value) check_status(self.row.SetDate(i, <int32_t>val)) elif t == KUDU_DECIMAL: IF PYKUDU_INT128_SUPPORTED == 1: check_status(self.row.SetUnscaledDecimal(i, <int128_t>to_unscaled_decimal(value))) ELSE: raise KuduException("The decimal type is not supported when GCC version is < 4.6.0" % self) else: raise TypeError("Cannot set kudu type <{0}>.".format(_type_names[t])) cpdef set_field_null(self, key): pass cpdef set_loc_null(self, int i): pass cdef add_to_session(self, Session s): pass cdef class WriteOperation: cdef: # Whether the WriteOperation has been applied. # Set by subclasses. bint applied KuduWriteOperation* op PartialRow py_row def __cinit__(self, Table table, record=None): self.applied = 0 self.py_row = PartialRow(table.schema) self.py_row._own = 0 cdef add_to_session(self, Session s): if self.applied: raise Exception check_status(s.s.get().Apply(self.op)) self.op = NULL self.applied = 1 def __setitem__(self, key, value): # Since the write operation is no longer a sub-class of the PartialRow # we need to explicitly retain the item setting functionality and API # style. self.py_row[key] = value cdef class Insert(WriteOperation): def __cinit__(self, Table table, record=None): self.op = table.ptr().NewInsert() self.py_row.row = self.op.mutable_row() if record: self.py_row.from_record(record) def __dealloc__(self): del self.op cdef class InsertIgnore(WriteOperation): def __cinit__(self, Table table, record=None): self.op = table.ptr().NewInsertIgnore() self.py_row.row = self.op.mutable_row() if record: self.py_row.from_record(record) def __dealloc__(self): del self.op cdef class Upsert(WriteOperation): def __cinit__(self, Table table, record=None): self.op = table.ptr().NewUpsert() self.py_row.row = self.op.mutable_row() if record: self.py_row.from_record(record) def __dealloc__(self): del self.op cdef class UpsertIgnore(WriteOperation): def __cinit__(self, Table table, record=None): self.op = table.ptr().NewUpsertIgnore() self.py_row.row = self.op.mutable_row() if record: self.py_row.from_record(record) def __dealloc__(self): del self.op cdef class Update(WriteOperation): def __cinit__(self, Table table, record=None): self.op = table.ptr().NewUpdate() self.py_row.row = self.op.mutable_row() if record: self.py_row.from_record(record) def __dealloc__(self): del self.op cdef class UpdateIgnore(WriteOperation): def __cinit__(self, Table table, record=None): self.op = table.ptr().NewUpdateIgnore() self.py_row.row = self.op.mutable_row() if record: self.py_row.from_record(record) def __dealloc__(self): del self.op cdef class Delete(WriteOperation): def __cinit__(self, Table table, record=None): self.op = table.ptr().NewDelete() self.py_row.row = self.op.mutable_row() if record: self.py_row.from_record(record) def __dealloc__(self): del self.op cdef class DeleteIgnore(WriteOperation): def __cinit__(self, Table table, record=None): self.op = table.ptr().NewDeleteIgnore() self.py_row.row = self.op.mutable_row() if record: self.py_row.from_record(record) def __dealloc__(self): del self.op cdef inline cast_pyvalue(DataType t, object o): if t == KUDU_BOOL: return BoolVal(o) elif t == KUDU_INT8: return Int8Val(o) elif t == KUDU_INT16: return Int16Val(o) elif t == KUDU_INT32: return Int32Val(o) elif t == KUDU_INT64: return Int64Val(o) elif t == KUDU_DOUBLE: return DoubleVal(o) elif t == KUDU_FLOAT: return FloatVal(o) elif t == KUDU_STRING: return StringVal(o) elif t == KUDU_UNIXTIME_MICROS: return UnixtimeMicrosVal(o) elif t == KUDU_BINARY: return StringVal(o) elif t == KUDU_VARCHAR: return StringVal(o) elif t == KUDU_DATE: return DateVal(o) else: raise TypeError("Cannot cast kudu type <{0}>".format(_type_names[t])) cdef class TableAlterer: """ Alters an existing table based on the provided steps. """ def __cinit__(self, Table table): self._table = table self._new_name = None self._init(self._table.parent.cp .NewTableAlterer(tobytes(self._table.name))) def __dealloc__(self): if self._alterer != NULL: del self._alterer cdef _init(self, KuduTableAlterer* alterer): self._alterer = alterer def rename(self, table_name): """ Rename the table. Returns a reference to itself to facilitate chaining. Parameters ---------- table_name : str The new name for the table. Return ------ self : TableAlterer """ self._alterer.RenameTo(tobytes(table_name)) self._new_name = table_name return self def add_column(self, name, type_=None, nullable=None, compression=None, encoding=None, default=None): """ Add a new column to the table. When adding a column, you must specify the default value of the new column using ColumnSpec.default(...) or the default parameter in this method. Parameters ---------- name : string type_ : string or KuduType Data type e.g. 'int32' or kudu.int32 nullable : boolean, default None New columns are nullable by default. Set boolean value for explicit nullable / not-nullable compression : string or int One of kudu.COMPRESSION_* constants or their string equivalent. encoding : string or int One of kudu.ENCODING_* constants or their string equivalent. default : obj Use this to set the column default value Returns ------- spec : ColumnSpec """ cdef: ColumnSpec result = ColumnSpec() result.spec = self._alterer.AddColumn(tobytes(name)) if type_ is not None: result.type(type_) if nullable is not None: result.nullable(nullable) if compression is not None: result.compression(compression) if encoding is not None: result.encoding(encoding) if default: result.default(default) return result def alter_column(self, name, rename_to=None): """ Alter an existing column. Parameters ---------- name : string rename_to : str If set, the column will be renamed to this Returns ------- spec : ColumnSpec """ cdef: ColumnSpec result = ColumnSpec() result.spec = self._alterer.AlterColumn(tobytes(name)) if rename_to: result.rename(rename_to) return result def drop_column(self, name): """ Drops an existing column from the table. Parameters ---------- name : str The name of the column to drop. Returns ------- self : TableAlterer """ self._alterer.DropColumn(tobytes(name)) return self def add_range_partition(self, lower_bound=None, upper_bound=None, lower_bound_type='inclusive', upper_bound_type='exclusive'): """ Add a range partition to the table with the specified lower bound and upper bound. Multiple range partitions may be added as part of a single alter table transaction by calling this method multiple times on the table alterer. This client may immediately write and scan the new tablets when Alter() returns success, however other existing clients may have to wait for a timeout period to elapse before the tablets become visible. This period is configured by the master's 'table_locations_ttl_ms' flag, and defaults to 5 minutes. Parameters ---------- lower_bound : PartialRow/list/tuple/dict upper_bound : PartialRow/list/tuple/dict lower_bound_type : {'inclusive', 'exclusive'} or constants kudu.EXCLUSIVE_BOUND and kudu.INCLUSIVE_BOUND upper_bound_type : {'inclusive', 'exclusive'} or constants kudu.EXCLUSIVE_BOUND and kudu.INCLUSIVE_BOUND Returns ------- self : TableAlterer """ cdef: PartialRow lbound PartialRow ubound if not isinstance(lower_bound, PartialRow): lbound = self._table.schema.new_row(lower_bound) else: lbound = lower_bound lbound._own = 0 if not isinstance(upper_bound, PartialRow): ubound = self._table.schema.new_row(upper_bound) else: ubound = upper_bound ubound._own = 0 self._alterer.AddRangePartition( lbound.row, ubound.row, _check_convert_range_bound_type(lower_bound_type), _check_convert_range_bound_type(upper_bound_type) ) def add_custom_range_partition(self, range_partition): """ Add a range partition with custom hash schema. Multiple range partitions may be added as part of a single alter table transaction by calling this method multiple times on the table alterer. This client may immediately write and scan the new tablets when Alter() returns success, however other existing clients may have to wait for a timeout period to elapse before the tablets become visible. This period is configured by the master's 'table_locations_ttl_ms' flag, and defaults to 5 minutes. Parameters ---------- range_partition : RangePartition Returns ------- self : TableAlterer """ cdef: vector[string] v KuduRangePartition* p PartialRow lower_bound PartialRow upper_bound if not isinstance(range_partition.lower_bound, PartialRow): lower_bound = self._table.schema.new_row(range_partition.lower_bound) else: lower_bound = range_partition.lower_bound lower_bound._own = 0 if not isinstance(range_partition.upper_bound, PartialRow): upper_bound = self._table.schema.new_row(range_partition.upper_bound) else: upper_bound = range_partition.upper_bound upper_bound._own = 0 p = new KuduRangePartition( lower_bound.row, upper_bound.row, range_partition.lower_bound_type, range_partition.upper_bound_type) for col_names, num_buckets, seed in range_partition.hash_dimensions: v.clear() for n in col_names: v.push_back(tobytes(n)) p.add_hash_partitions(v, num_buckets, seed if seed else 0) self._alterer.AddRangePartition(p) def drop_range_partition(self, lower_bound=None, upper_bound=None, lower_bound_type='inclusive', upper_bound_type='exclusive'): """ Drop the range partition from the table with the specified lower bound and upper bound. The bounds must match an existing range partition exactly, and may not span multiple range partitions. Multiple range partitions may be dropped as part of a single alter table transaction by calling this method multiple times on the table alterer. Parameters ---------- lower_bound : PartialRow/list/tuple/dict upper_bound : PartialRow/list/tuple/dict lower_bound_type : {'inclusive', 'exclusive'} or constants kudu.EXCLUSIVE_BOUND and kudu.INCLUSIVE_BOUND upper_bound_type : {'inclusive', 'exclusive'} or constants kudu.EXCLUSIVE_BOUND and kudu.INCLUSIVE_BOUND Returns ------- self : TableAlterer """ cdef: PartialRow lbound PartialRow ubound if not isinstance(lower_bound, PartialRow): lbound = self._table.schema.new_row(lower_bound) else: lbound = lower_bound lbound._own = 0 if not isinstance(upper_bound, PartialRow): ubound = self._table.schema.new_row(upper_bound) else: ubound = upper_bound ubound._own = 0 self._alterer.DropRangePartition( lbound.row, ubound.row, _check_convert_range_bound_type(lower_bound_type), _check_convert_range_bound_type(upper_bound_type) ) def set_owner(self, new_owner): """ Set the owner of the table. Parameters ---------- new_owner : string Returns ------- self : TableAlterer """ self._alterer.SetOwner(tobytes(new_owner)) return self def set_comment(self, new_comment): """ Set the comment on the table. Parameters ---------- new_comment : string Returns ------- self : TableAlterer """ self._alterer.SetComment(tobytes(new_comment)) return self def alter(self): """ Alter table. Returns a new table object upon completion of the alter. Returns ------- table :Table """ check_status(self._alterer.Alter()) return self._table.parent.table(self._new_name or self._table.name) ```
```c++ ///////////////////////////////////////////////////////////////////////////// // // // (See accompanying file LICENSE_1_0.txt or copy at // path_to_url // // See path_to_url for documentation. // ///////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTRUSIVE_LIST_NODE_HPP #define BOOST_INTRUSIVE_LIST_NODE_HPP #ifndef BOOST_CONFIG_HPP # include <boost/config.hpp> #endif #if defined(BOOST_HAS_PRAGMA_ONCE) # pragma once #endif #include <boost/intrusive/detail/workaround.hpp> #include <boost/intrusive/pointer_rebind.hpp> namespace boost { namespace intrusive { // list_node_traits can be used with circular_list_algorithms and supplies // a list_node holding the pointers needed for a double-linked list // it is used by list_derived_node and list_member_node template<class VoidPointer> struct list_node { typedef typename pointer_rebind<VoidPointer, list_node>::type node_ptr; node_ptr next_; node_ptr prev_; }; template<class VoidPointer> struct list_node_traits { typedef list_node<VoidPointer> node; typedef typename node::node_ptr node_ptr; typedef typename pointer_rebind<VoidPointer, const node>::type const_node_ptr; BOOST_INTRUSIVE_FORCEINLINE static node_ptr get_previous(const const_node_ptr & n) { return n->prev_; } BOOST_INTRUSIVE_FORCEINLINE static node_ptr get_previous(const node_ptr & n) { return n->prev_; } BOOST_INTRUSIVE_FORCEINLINE static void set_previous(const node_ptr & n, const node_ptr & prev) { n->prev_ = prev; } BOOST_INTRUSIVE_FORCEINLINE static node_ptr get_next(const const_node_ptr & n) { return n->next_; } BOOST_INTRUSIVE_FORCEINLINE static node_ptr get_next(const node_ptr & n) { return n->next_; } BOOST_INTRUSIVE_FORCEINLINE static void set_next(const node_ptr & n, const node_ptr & next) { n->next_ = next; } }; } //namespace intrusive } //namespace boost #endif //BOOST_INTRUSIVE_LIST_NODE_HPP ```
```javascript import axios from 'axios'; axios.defaults.baseURL = process.env.VUE_APP_API_URL; export default (app) => { app.axios = axios; app.$http = axios; app.config.globalProperties.axios = axios; app.config.globalProperties.$http = axios; } ```
```php <?php namespace Psalm\Internal\Algebra; use PhpParser; use Psalm\Codebase; use Psalm\FileSource; use Psalm\Internal\Algebra; use Psalm\Internal\Analyzer\Statements\Expression\AssertionFinder; use Psalm\Internal\Analyzer\StatementsAnalyzer; use Psalm\Internal\Clause; use Psalm\Node\Expr\BinaryOp\VirtualBooleanAnd; use Psalm\Node\Expr\BinaryOp\VirtualBooleanOr; use Psalm\Node\Expr\VirtualBooleanNot; use Psalm\Storage\Assertion\Truthy; use function count; use function spl_object_id; use function substr; /** * @internal */ final class FormulaGenerator { /** * @return list<Clause> */ public static function getFormula( int $conditional_object_id, int $creating_object_id, PhpParser\Node\Expr $conditional, ?string $this_class_name, FileSource $source, ?Codebase $codebase = null, bool $inside_negation = false, bool $cache = true ): array { if ($conditional instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd || $conditional instanceof PhpParser\Node\Expr\BinaryOp\LogicalAnd ) { $left_assertions = self::getFormula( $conditional_object_id, spl_object_id($conditional->left), $conditional->left, $this_class_name, $source, $codebase, $inside_negation, $cache, ); $right_assertions = self::getFormula( $conditional_object_id, spl_object_id($conditional->right), $conditional->right, $this_class_name, $source, $codebase, $inside_negation, $cache, ); return [...$left_assertions, ...$right_assertions]; } if ($conditional instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr || $conditional instanceof PhpParser\Node\Expr\BinaryOp\LogicalOr ) { $left_clauses = self::getFormula( $conditional_object_id, spl_object_id($conditional->left), $conditional->left, $this_class_name, $source, $codebase, $inside_negation, $cache, ); $right_clauses = self::getFormula( $conditional_object_id, spl_object_id($conditional->right), $conditional->right, $this_class_name, $source, $codebase, $inside_negation, $cache, ); return Algebra::combineOredClauses($left_clauses, $right_clauses, $conditional_object_id); } if ($conditional instanceof PhpParser\Node\Expr\BooleanNot) { if ($conditional->expr instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr) { $and_expr = new VirtualBooleanAnd( new VirtualBooleanNot( $conditional->expr->left, $conditional->getAttributes(), ), new VirtualBooleanNot( $conditional->expr->right, $conditional->getAttributes(), ), $conditional->expr->getAttributes(), ); return self::getFormula( $conditional_object_id, $conditional_object_id, $and_expr, $this_class_name, $source, $codebase, $inside_negation, false, ); } if ($conditional->expr instanceof PhpParser\Node\Expr\Isset_ && count($conditional->expr->vars) > 1 ) { $anded_assertions = null; if ($cache && $source instanceof StatementsAnalyzer) { $anded_assertions = $source->node_data->getAssertions($conditional->expr); } if ($anded_assertions === null) { $anded_assertions = AssertionFinder::scrapeAssertions( $conditional->expr, $this_class_name, $source, $codebase, $inside_negation, $cache, ); if ($cache && $source instanceof StatementsAnalyzer) { $source->node_data->setAssertions($conditional->expr, $anded_assertions); } } $clauses = []; foreach ($anded_assertions as $assertions) { foreach ($assertions as $var => $anded_types) { $redefined = false; if ($var[0] === '=') { /** @var string */ $var = substr($var, 1); $redefined = true; } foreach ($anded_types as $orred_types) { $mapped_orred_types = []; foreach ($orred_types as $orred_type) { $mapped_orred_types[(string)$orred_type] = $orred_type; } $clauses[] = new Clause( [$var => $mapped_orred_types], $conditional_object_id, spl_object_id($conditional->expr), false, true, $orred_types[0]->hasEquality(), $redefined ? [$var => true] : [], ); } } } return Algebra::negateFormula($clauses); } if ($conditional->expr instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd) { $and_expr = new VirtualBooleanOr( new VirtualBooleanNot( $conditional->expr->left, $conditional->getAttributes(), ), new VirtualBooleanNot( $conditional->expr->right, $conditional->getAttributes(), ), $conditional->expr->getAttributes(), ); return self::getFormula( $conditional_object_id, spl_object_id($conditional->expr), $and_expr, $this_class_name, $source, $codebase, $inside_negation, false, ); } return Algebra::negateFormula( self::getFormula( $conditional_object_id, spl_object_id($conditional->expr), $conditional->expr, $this_class_name, $source, $codebase, !$inside_negation, ), ); } if ($conditional instanceof PhpParser\Node\Expr\BinaryOp\Identical || $conditional instanceof PhpParser\Node\Expr\BinaryOp\Equal ) { $false_pos = AssertionFinder::hasFalseVariable($conditional); $true_pos = AssertionFinder::hasTrueVariable($conditional); if ($false_pos === AssertionFinder::ASSIGNMENT_TO_RIGHT && ($conditional instanceof PhpParser\Node\Expr\BinaryOp\Equal || $conditional->left instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd || $conditional->left instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr || $conditional->left instanceof PhpParser\Node\Expr\BooleanNot) ) { return Algebra::negateFormula( self::getFormula( $conditional_object_id, spl_object_id($conditional->left), $conditional->left, $this_class_name, $source, $codebase, !$inside_negation, $cache, ), ); } if ($false_pos === AssertionFinder::ASSIGNMENT_TO_LEFT && ($conditional instanceof PhpParser\Node\Expr\BinaryOp\Equal || $conditional->right instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd || $conditional->right instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr || $conditional->right instanceof PhpParser\Node\Expr\BooleanNot) ) { return Algebra::negateFormula( self::getFormula( $conditional_object_id, spl_object_id($conditional->right), $conditional->right, $this_class_name, $source, $codebase, !$inside_negation, $cache, ), ); } if ($true_pos === AssertionFinder::ASSIGNMENT_TO_RIGHT && ($conditional instanceof PhpParser\Node\Expr\BinaryOp\Equal || $conditional->left instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd || $conditional->left instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr || $conditional->left instanceof PhpParser\Node\Expr\BooleanNot) ) { return self::getFormula( $conditional_object_id, spl_object_id($conditional->left), $conditional->left, $this_class_name, $source, $codebase, $inside_negation, $cache, ); } if ($true_pos === AssertionFinder::ASSIGNMENT_TO_LEFT && ($conditional instanceof PhpParser\Node\Expr\BinaryOp\Equal || $conditional->right instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd || $conditional->right instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr || $conditional->right instanceof PhpParser\Node\Expr\BooleanNot) ) { return self::getFormula( $conditional_object_id, spl_object_id($conditional->right), $conditional->right, $this_class_name, $source, $codebase, $inside_negation, $cache, ); } } if ($conditional instanceof PhpParser\Node\Expr\BinaryOp\NotIdentical || $conditional instanceof PhpParser\Node\Expr\BinaryOp\NotEqual ) { $false_pos = AssertionFinder::hasFalseVariable($conditional); $true_pos = AssertionFinder::hasTrueVariable($conditional); if ($true_pos === AssertionFinder::ASSIGNMENT_TO_RIGHT && ($conditional instanceof PhpParser\Node\Expr\BinaryOp\NotEqual || $conditional->left instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd || $conditional->left instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr || $conditional->left instanceof PhpParser\Node\Expr\BooleanNot) ) { return Algebra::negateFormula( self::getFormula( $conditional_object_id, spl_object_id($conditional->left), $conditional->left, $this_class_name, $source, $codebase, !$inside_negation, $cache, ), ); } if ($true_pos === AssertionFinder::ASSIGNMENT_TO_LEFT && ($conditional instanceof PhpParser\Node\Expr\BinaryOp\NotEqual || $conditional->right instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd || $conditional->right instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr || $conditional->right instanceof PhpParser\Node\Expr\BooleanNot) ) { return Algebra::negateFormula( self::getFormula( $conditional_object_id, spl_object_id($conditional->right), $conditional->right, $this_class_name, $source, $codebase, !$inside_negation, $cache, ), ); } if ($false_pos === AssertionFinder::ASSIGNMENT_TO_RIGHT && ($conditional instanceof PhpParser\Node\Expr\BinaryOp\NotEqual || $conditional->left instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd || $conditional->left instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr || $conditional->left instanceof PhpParser\Node\Expr\BooleanNot) ) { return self::getFormula( $conditional_object_id, spl_object_id($conditional->left), $conditional->left, $this_class_name, $source, $codebase, $inside_negation, $cache, ); } if ($false_pos === AssertionFinder::ASSIGNMENT_TO_LEFT && ($conditional instanceof PhpParser\Node\Expr\BinaryOp\NotEqual || $conditional->right instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd || $conditional->right instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr || $conditional->right instanceof PhpParser\Node\Expr\BooleanNot) ) { return self::getFormula( $conditional_object_id, spl_object_id($conditional->right), $conditional->right, $this_class_name, $source, $codebase, $inside_negation, $cache, ); } } if ($conditional instanceof PhpParser\Node\Expr\Cast\Bool_) { return self::getFormula( $conditional_object_id, spl_object_id($conditional->expr), $conditional->expr, $this_class_name, $source, $codebase, $inside_negation, $cache, ); } $anded_assertions = null; if ($cache && $source instanceof StatementsAnalyzer) { $anded_assertions = $source->node_data->getAssertions($conditional); } if ($anded_assertions === null) { $anded_assertions = AssertionFinder::scrapeAssertions( $conditional, $this_class_name, $source, $codebase, $inside_negation, $cache, ); if ($cache && $source instanceof StatementsAnalyzer) { $source->node_data->setAssertions($conditional, $anded_assertions); } } $clauses = []; foreach ($anded_assertions as $assertions) { foreach ($assertions as $var => $anded_types) { $redefined = false; if ($var[0] === '=') { /** @var string */ $var = substr($var, 1); $redefined = true; } foreach ($anded_types as $orred_types) { $mapped_orred_types = []; foreach ($orred_types as $orred_type) { $mapped_orred_types[(string)$orred_type] = $orred_type; } $clauses[] = new Clause( [$var => $mapped_orred_types], $conditional_object_id, $creating_object_id, false, true, $orred_types[0]->hasEquality(), $redefined ? [$var => true] : [], ); } } } if ($clauses) { return $clauses; } /** @psalm-suppress MixedOperand */ $conditional_ref = '*' . $conditional->getAttribute('startFilePos') . ':' . $conditional->getAttribute('endFilePos'); return [ new Clause( [$conditional_ref => ['truthy' => new Truthy()]], $conditional_object_id, $creating_object_id, ), ]; } } ```
```java package com.haulmont.cuba.gui.components; import com.haulmont.chile.core.model.MetaClass; import com.haulmont.cuba.core.app.LockService; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.*; import com.haulmont.cuba.gui.ComponentsHelper; import com.haulmont.cuba.gui.components.actions.CreateAction; import com.haulmont.cuba.gui.components.actions.EditAction; import com.haulmont.cuba.gui.components.actions.RemoveAction; import com.haulmont.cuba.gui.data.CollectionDatasource; import com.haulmont.cuba.gui.data.Datasource; import com.haulmont.cuba.gui.data.impl.AbstractDatasource; import com.haulmont.cuba.security.entity.EntityOp; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Base class for controllers of combined browser/editor screens. */ public class EntityCombinedScreen extends AbstractLookup { /** * Indicates that a new instance of entity is being created. */ protected boolean creating; /** * Indicates that the screen is in editing mode. */ protected boolean editing; /** * Indicates that edited entity is pessimistically locked. */ protected boolean justLocked; /** * Returns the left container with browse components. Override if the container id differs from "lookupBox". */ protected ComponentContainer getLookupBox() { return (ComponentContainer) getComponentNN("lookupBox"); } /** * Returns the browse table. Override if the table id differs from "table". */ protected ListComponent getTable() { return (ListComponent) getComponentNN("table"); } /** * Returns the right container with edit components. Override if the container id differs from "editBox". */ protected ComponentContainer getEditBox() { return (ComponentContainer) getComponentNN("editBox"); } /** * Returns the tab sheet with edit components. Can be null if the screen contains a field group only. * Override if the tab sheet id differs from "tabSheet". */ @Nullable protected TabSheet getTabSheet() { return (TabSheet) getComponent("tabSheet"); } /** * Returns the field group. Override if the field group id differs from "fieldGroup". */ protected FieldGroup getFieldGroup() { return (FieldGroup) getComponentNN("fieldGroup"); } /** * Returns the container with edit actions (save, cancel). Override if the container id differs from "actionsPane". */ protected ComponentContainer getActionsPane() { return (ComponentContainer) getComponentNN("actionsPane"); } @Override public void init(Map<String, Object> params) { initBrowseItemChangeListener(); initBrowseCreateAction(); initBrowseEditAction(); initBrowseRemoveAction(); initShortcuts(); disableEditControls(); } /** * Adds a listener that reloads the selected record with the specified view and sets it to editDs. */ @SuppressWarnings("unchecked") protected void initBrowseItemChangeListener() { CollectionDatasource browseDs = getTable().getDatasource(); Datasource editDs = getFieldGroup().getDatasource(); browseDs.addItemChangeListener(e -> { if (e.getItem() != null) { Entity reloadedItem = getDsContext().getDataSupplier().reload( e.getDs().getItem(), editDs.getView(), null, e.getDs().getLoadDynamicAttributes()); editDs.setItem(reloadedItem); } }); } /** * Adds a CreateAction that removes selection in table, sets a newly created item to editDs * and enables controls for record editing. */ protected void initBrowseCreateAction() { ListComponent table = getTable(); table.addAction(new CreateAction(table) { @SuppressWarnings("unchecked") @Override protected void internalOpenEditor(CollectionDatasource datasource, Entity newItem, Datasource parentDs, Map<String, Object> params) { initNewItem(newItem); table.setSelected(Collections.emptyList()); getFieldGroup().getDatasource().setItem(newItem); refreshOptionsForLookupFields(); enableEditControls(true); } }); } /** * Hook to be implemented in subclasses. Called when the screen turns into editing mode * for a new entity instance. Enables additional initialization of the new entity instance * before setting it into the datasource. * @param item new entity instance */ protected void initNewItem(Entity item) { } /** * Adds an EditAction that enables controls for editing. */ protected void initBrowseEditAction() { ListComponent table = getTable(); table.addAction(new EditAction(table) { @Override public void actionPerform(Component component) { if (table.getSelected().size() == 1) { if (lockIfNeeded((Entity) table.getSelected().iterator().next())) { super.actionPerform(component); } } } @Override protected void internalOpenEditor(CollectionDatasource datasource, Entity existingItem, Datasource parentDs, Map<String, Object> params) { refreshOptionsForLookupFields(); enableEditControls(false); } @Override public void refreshState() { if (target != null) { CollectionDatasource ds = target.getDatasource(); if (ds != null && !captionInitialized) { setCaption(messages.getMainMessage("actions.Edit")); } } super.refreshState(); } @Override protected boolean isPermitted() { CollectionDatasource ownerDatasource = target.getDatasource(); boolean entityOpPermitted = security.isEntityOpPermitted(ownerDatasource.getMetaClass(), EntityOp.UPDATE); if (!entityOpPermitted) { return false; } return super.isPermitted(); } }); } /** * Pessimistic lock before start of editing, if it is configured for the entity. */ protected boolean lockIfNeeded(Entity entity) { MetaClass metaClass = getMetaClassForLocking(entity); LockInfo lockInfo = AppBeans.get(LockService.class).lock(metaClass.getName(), entity.getId().toString()); if (lockInfo == null) { justLocked = true; } else if (!(lockInfo instanceof LockNotSupported)) { showNotification( messages.getMainMessage("entityLocked.msg"), String.format(messages.getMainMessage("entityLocked.desc"), lockInfo.getUser().getLogin(), AppBeans.get(DatatypeFormatter.class).formatDateTime(lockInfo.getSince()) ), Frame.NotificationType.HUMANIZED ); return false; } return true; } /** * Release pessimistic lock if it was applied. */ protected void releaseLock() { if (justLocked) { Datasource ds = getFieldGroup().getDatasource(); Entity entity = ds.getItem(); if (entity != null) { MetaClass metaClass = getMetaClassForLocking(entity); AppBeans.get(LockService.class).unlock(metaClass.getName(), entity.getId().toString()); } } } protected MetaClass getMetaClassForLocking(Entity item) { // lock original metaClass, if any, because by convention all the configuration is based on original entities MetaClass metaClass = AppBeans.get(ExtendedEntities.class).getOriginalMetaClass(item.getMetaClass()); if (metaClass == null) { metaClass = getTable().getDatasource().getMetaClass(); } return metaClass; } /** * Adds AfterRemoveHandler for table's Remove action to reset the record contained in editDs. */ @SuppressWarnings("unchecked") protected void initBrowseRemoveAction() { ListComponent table = getTable(); Datasource editDs = getFieldGroup().getDatasource(); RemoveAction removeAction = (RemoveAction) table.getAction(RemoveAction.ACTION_ID); if (removeAction != null) removeAction.setAfterRemoveHandler(removedItems -> editDs.setItem(null)); } /** * Adds ESCAPE shortcut that invokes cancel() method. */ protected void initShortcuts() { ComponentContainer editBox = getEditBox(); if (editBox instanceof ShortcutNotifier) { ((ShortcutNotifier) editBox).addShortcutAction( new ShortcutAction(new KeyCombination(KeyCombination.Key.ESCAPE), shortcutTriggeredEvent -> cancel())); } } protected void refreshOptionsForLookupFields() { for (Component component : getFieldGroup().getOwnComponents()) { if (component instanceof LookupField) { CollectionDatasource optionsDatasource = ((LookupField) component).getOptionsDatasource(); if (optionsDatasource != null) { optionsDatasource.refresh(); } } } } /** * Enables controls for editing. * @param creating indicates that a new instance is being created */ protected void enableEditControls(boolean creating) { this.editing = true; this.creating = creating; initEditComponents(true); getFieldGroup().requestFocus(); } /** * Disables edit controls. */ protected void disableEditControls() { this.editing = false; initEditComponents(false); ((Focusable) getTable()).focus(); } /** * Initializes edit controls, depending on if they should be enabled or disabled. * @param enabled if true - enables edit controls and disables controls on the left side of the splitter * if false - vice versa */ protected void initEditComponents(boolean enabled) { TabSheet tabSheet = getTabSheet(); if (tabSheet != null) { ComponentsHelper.walkComponents(tabSheet, (component, name) -> { if (component instanceof FieldGroup) { ((FieldGroup) component).setEditable(enabled); } else if (component instanceof Table) { ((Table) component).getActions().forEach(action -> action.setEnabled(enabled)); } else if (!(component instanceof ComponentContainer)) { component.setEnabled(enabled); } }); } getFieldGroup().setEditable(enabled); getActionsPane().setVisible(enabled); getLookupBox().setEnabled(!enabled); } /** * Validates editor fields. * * @return true if all fields are valid or false otherwise */ protected boolean validateEditor() { FieldGroup fieldGroup = getFieldGroup(); List<Validatable> components = new ArrayList<>(); for (Component component: fieldGroup.getComponents()) { if (component instanceof Validatable) { components.add((Validatable)component); } } return validate(components); } /** * Method that is invoked by clicking Ok button after editing an existing or creating a new record. */ @SuppressWarnings("unchecked") public void save() { if (!editing) return; if (!validateEditor()) { return; } getDsContext().commit(); ListComponent table = getTable(); CollectionDatasource browseDs = table.getDatasource(); Entity editedItem = getFieldGroup().getDatasource().getItem(); if (creating) { browseDs.includeItem(editedItem); } else { browseDs.updateItem(editedItem); } table.setSelected(editedItem); releaseLock(); disableEditControls(); } /** * Method that is invoked by clicking Cancel button, discards changes and disables controls for editing. */ @SuppressWarnings("unchecked") public void cancel() { CollectionDatasource browseDs = getTable().getDatasource(); Datasource editDs = getFieldGroup().getDatasource(); Entity selectedItem = browseDs.getItem(); if (selectedItem != null) { Entity reloadedItem = getDsContext().getDataSupplier().reload( selectedItem, editDs.getView(), null, editDs.getLoadDynamicAttributes()); browseDs.setItem(reloadedItem); } else { editDs.setItem(null); } for (Datasource dataSource : getDsContext().getAll()) { if (AbstractDatasource.class.isAssignableFrom(dataSource.getClass())) { ((AbstractDatasource) dataSource).clearCommitLists(); } } releaseLock(); disableEditControls(); } } ```
```java /* * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package org.apache.carbondata.sdk.file.arrow; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.nio.charset.Charset; import org.apache.carbondata.core.constants.CarbonCommonConstants; import org.apache.arrow.vector.BigIntVector; import org.apache.arrow.vector.BitVector; import org.apache.arrow.vector.DateDayVector; import org.apache.arrow.vector.DecimalVector; import org.apache.arrow.vector.Float4Vector; import org.apache.arrow.vector.Float8Vector; import org.apache.arrow.vector.IntVector; import org.apache.arrow.vector.SmallIntVector; import org.apache.arrow.vector.TimeStampMicroTZVector; import org.apache.arrow.vector.TinyIntVector; import org.apache.arrow.vector.ValueVector; import org.apache.arrow.vector.VarBinaryVector; import org.apache.arrow.vector.VarCharVector; import org.apache.arrow.vector.complex.ListVector; import org.apache.arrow.vector.complex.StructVector; public abstract class ArrowFieldWriter { private ValueVector valueVector; protected int count; public ArrowFieldWriter(ValueVector valueVector) { this.valueVector = valueVector; } public abstract void setNull(); public abstract void setValue(Object data, int ordinal); public void write(Object data, int ordinal) { if (data == null) { setNull(); } else { setValue(data, ordinal); } count += 1; } public void finish() { valueVector.setValueCount(count); } public void reset() { valueVector.reset(); count = 0; } } class BooleanWriter extends ArrowFieldWriter { private BitVector bitVector; public BooleanWriter(BitVector bitVector) { super(bitVector); this.bitVector = bitVector; } @Override public void setNull() { bitVector.setNull(count); } @Override public void setValue(Object data, int ordinal) { bitVector.setSafe(count, (Boolean) data ? 1 : 0); } } class ByteWriter extends ArrowFieldWriter { private TinyIntVector tinyIntVector; public ByteWriter(TinyIntVector tinyIntVector) { super(tinyIntVector); this.tinyIntVector = tinyIntVector; } @Override public void setNull() { this.tinyIntVector.setNull(count); } @Override public void setValue(Object data, int ordinal) { this.tinyIntVector.setSafe(count, (byte) data); } } class ShortWriter extends ArrowFieldWriter { private SmallIntVector smallIntVector; public ShortWriter(SmallIntVector smallIntVector) { super(smallIntVector); this.smallIntVector = smallIntVector; } @Override public void setNull() { this.smallIntVector.setNull(count); } @Override public void setValue(Object data, int ordinal) { this.smallIntVector.setSafe(count, (short) data); } } class IntWriter extends ArrowFieldWriter { private IntVector intVector; public IntWriter(IntVector intVector) { super(intVector); this.intVector = intVector; } @Override public void setNull() { this.intVector.setNull(count); } @Override public void setValue(Object data, int ordinal) { this.intVector.setSafe(count, (int) data); } } class LongWriter extends ArrowFieldWriter { private BigIntVector bigIntVector; public LongWriter(BigIntVector bigIntVector) { super(bigIntVector); this.bigIntVector = bigIntVector; } @Override public void setNull() { this.bigIntVector.setNull(count); } @Override public void setValue(Object data, int ordinal) { this.bigIntVector.setSafe(count, (long) data); } } class FloatWriter extends ArrowFieldWriter { private Float4Vector float4Vector; public FloatWriter(Float4Vector float4Vector) { super(float4Vector); this.float4Vector = float4Vector; } @Override public void setNull() { this.float4Vector.setNull(count); } @Override public void setValue(Object data, int ordinal) { this.float4Vector.setSafe(count, (float) data); } } class DoubleWriter extends ArrowFieldWriter { private Float8Vector float8Vector; public DoubleWriter(Float8Vector float8Vector) { super(float8Vector); this.float8Vector = float8Vector; } @Override public void setNull() { this.float8Vector.setNull(count); } @Override public void setValue(Object data, int ordinal) { this.float8Vector.setSafe(count, (double) data); } } class DateWriter extends ArrowFieldWriter { private DateDayVector dateDayVector; public DateWriter(DateDayVector dateDayVector) { super(dateDayVector); this.dateDayVector = dateDayVector; } @Override public void setNull() { this.dateDayVector.setNull(count); } @Override public void setValue(Object data, int ordinal) { this.dateDayVector.setSafe(count, (int)data); } } class TimeStampWriter extends ArrowFieldWriter { private TimeStampMicroTZVector timeStampMicroTzVector; public TimeStampWriter(TimeStampMicroTZVector timeStampMicroTZVector) { super(timeStampMicroTZVector); this.timeStampMicroTzVector = timeStampMicroTZVector; } @Override public void setNull() { this.timeStampMicroTzVector.setNull(count); } @Override public void setValue(Object data, int ordinal) { this.timeStampMicroTzVector.setSafe(count, (long)data); } } class StringWriter extends ArrowFieldWriter { private VarCharVector varCharVector; public StringWriter(VarCharVector varCharVector) { super(varCharVector); this.varCharVector = varCharVector; } @Override public void setNull() { this.varCharVector.setNull(count); } @Override public void setValue(Object data, int ordinal) { byte[] bytes = (String.valueOf(data)).getBytes(Charset.forName(CarbonCommonConstants.DEFAULT_CHARSET)); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); this.varCharVector.setSafe(count, byteBuffer, byteBuffer.position(), bytes.length); } } class BinaryWriter extends ArrowFieldWriter { private VarBinaryVector varBinaryVector; public BinaryWriter(VarBinaryVector varBinaryVector) { super(varBinaryVector); this.varBinaryVector = varBinaryVector; } @Override public void setNull() { this.varBinaryVector.setNull(count); } @Override public void setValue(Object data, int ordinal) { byte[] bytes = (byte[]) data; varBinaryVector.setSafe(count, bytes, 0, bytes.length); } } class DecimalWriter extends ArrowFieldWriter { private final int precision; private final int scale; private DecimalVector decimalVector; public DecimalWriter(DecimalVector decimalVector, int precision, int scale) { super(decimalVector); this.decimalVector = decimalVector; this.precision = precision; this.scale = scale; } @Override public void setNull() { this.decimalVector.setNull(count); } @Override public void setValue(Object data, int ordinal) { BigDecimal decimal = (BigDecimal) data; decimalVector.setSafe(count, decimal); } } class ArrayWriter extends ArrowFieldWriter { private ListVector listVector; private ArrowFieldWriter elementWriter; public ArrayWriter(ListVector listVector, ArrowFieldWriter elementWriter) { super(listVector); this.listVector = listVector; this.elementWriter = elementWriter; } @Override public void setNull() { } @Override public void setValue(Object data, int ordinal) { Object[] array = (Object[]) data; int i = 0; listVector.startNewValue(count); while (i < array.length) { elementWriter.write(array, i); i += 1; } listVector.endValue(count, array.length); } @Override public void finish() { super.finish(); elementWriter.finish(); } @Override public void reset() { super.reset(); elementWriter.reset(); } } class StructWriter extends ArrowFieldWriter { private StructVector structVector; private ArrowFieldWriter[] children; public StructWriter(StructVector structVector, ArrowFieldWriter[] children) { super(structVector); this.structVector = structVector; this.children = children; } @Override public void setNull() { int i = 0; while (i < children.length) { children[i].setNull(); children[i].count += 1; i += 1; } structVector.setNull(count); } @Override public void setValue(Object data, int ordinal) { Object[] struct = (Object[]) data; int i = 0; while (i < struct.length) { children[i].write(struct[i], i); i += 1; } structVector.setIndexDefined(count); } @Override public void finish() { super.finish(); for (int i = 0; i < children.length; i++) { children[i].finish(); } } @Override public void reset() { super.reset(); for (int i = 0; i < children.length; i++) { children[i].reset(); } } } ```
Roger Rosenblatt (born 1940) is an American memoirist, essayist, and novelist. He was a long-time essayist for Time magazine and PBS NewsHour. Career Roger Rosenblatt began writing professionally in his mid-30s, when he became literary editor and a columnist for The New Republic. Before that, he taught at Harvard, where he earned his Ph.D. In 1965–66 he was a Fulbright Scholar in Ireland, where he played on the Irish international basketball team. At age 25, he became the director of Harvard's freshman writing department. At age 28, he held the Briggs–Copeland appointment in the teaching of writing, and was Allston–Burr Senior Tutor, and later, Master of Dunster House. At age 29 he was the youngest House Master in Harvard's history. At Harvard, apart from creative writing, he taught Irish drama, modern poetry, and the university's first course in African American literature. In 2005 he was the Edward R. Murrow visiting professor at Harvard. In 2010 he was selected for the Robert Foster Cherry Award as one of the three most gifted university teachers in the country. In 1975 he became Literary Editor and a columnist at The New Republic. After that, and before turning solely to literary work, he was a columnist on The Washington Post, during which time Washingtonian Magazine named him Best Columnist in Washington, and an essayist for the NewsHour on PBS. With Jim Lehrer and Robert MacNeil, he created the first essays ever done on television. In 1979 he became an essayist for Time magazine, a post that he held on and off until 2006. He continued to do TV essays for the NewsHour until that same year. His essays for Time won two George Polk Awards, awards from the Overseas Press Club, the American Bar Association, and others. His NewsHour essays won the Peabody Award and the Emmy. His Time cover essay, "A Letter to the Year 2086" was chosen for the time capsule placed inside the Statue of Liberty at its centennial. In 1985, he was on the short list for NASA's Journalist in Space before the program was ended by the Challenger shuttle tragedy. He argued in a 1999 article for Time that guns should be banned. As Senior Writer at Time he became the first to report his own stories—the functions of reporting and writing having been separate previously. "Here you had a superstar writer becoming a superstar reporter," wrote executive editor Jason McManus. Under managing editor Ray Cave, Rosenblatt also wrote the magazine's first "tone poems," brief interpretive essays introducing cover stories. His essay "The Man in the Water," on the self-sacrificing hero of the Air Florida plane crash in 1981, was read by President Reagan at a ceremony honoring the man. Besides Rosenblatt's essays, his other prominent pieces included covers on the 40th anniversary of Hiroshima, on the Los Angeles Olympics, on a family services organization in Brooklyn, and the essay accompanying the photographs in "A Day in the Life of the Soviet Union." Rosenblatt's 25,000-word "Children of War," on the thoughts and lives of children in the war zones of Northern Ireland, Israel, Lebanon, Cambodia, and Vietnam was "one of the most poignant stories Time ever published" and was noted worldwide. Later, he wrote about wars in Sudan (for Vanity Fair), and Rwanda (for New York Times Magazine). In 2006 Rosenblatt left his positions at Time and the NewsHour and gave up journalism to devote his time to the writing of memoirs, novels and extended essays. His first novel, Lapham Rising, was a national bestseller, adapted as Angry Neighbors (2022) and filmed around Waseca, Minnesota and Excelsior, Minnesota. Making Toast was a New York Times bestseller. The memoir was a book-length version of an essay he wrote for the New Yorker magazine, on the death of his daughter, in 2008. The L.A. Times called Making Toast "sad, funny, brave and luminous. A rare and generous book." The Washington Post described it as "a textbook on what constitutes perfect writing and how to be a class act." He followed Making Toast with Unless It Moves the Human Heart, a book on the art and craft of writing, which was also a New York Times bestseller, as was Kayak Morning, a meditation on grief. The Boy Detective: A New York Childhood was published in 2013. The Book of Love: Improvisations on That Crazy Little Thing was published in January 2015. His novel, Thomas Murphy, was published in January, 2016. His two most recent books are Cold Moon: On Life, Love, and Responsibility (2020) and Cataract Blues: Running the Keyboard (2023). Of Cold Moon, The Washington Post wrote: "In this deceptively short book, the celebrated author and essayist takes us on a tour of his 'weathered mind.' His memories of his life summon ours, without warning or apology. Line by line, he helps us find softer landings... He never mentions [the pandemic], and yet he does... 'Everybody grieves.' So many lost, with many more to die... Let us abide by Rosenblatt's No. 3. We are responsible for each other." Kirkus Reviews wrote: "In brief passages connected by associations and the improvisational feel of jazz [Rosenblatt] moves fluidly among memoir, philosophy, natural history and inspiration... A tonic for tough times filled with plain spoken lyricism, gratitude, and good humor." Of Cataract Blues, Garry Trudeau wrote: "While everyone around you is seeing red, along comes a happy outpatient who's just nuts about the color blue. Prompted by his wildly successful eye surgery, Roger Rosenblatt celebrates his new favorite wavelength by letting it wash over everything that matters — nature, history, music, memory, laughter, loss, and love. This is a master, at work and at play." In total, he is the author of 21 books, which have been published in 14 languages. They include the national bestseller Rules for Aging; three collections of essays; and Children of War, based on his story in Time, which won the Robert F. Kennedy Book Prize and was a finalist for the National Book Critics Circle Award. He has also written six off-Broadway plays, including Ashley Montana Goes Ashore in the Caicos, and The Oldsmobiles, both produced at the Flea Theater. His comic one-man show, Free Speech in America, which he performed at the American Place Theater, was cited by the New York Times as one of the 10 best plays of 1991. His most recent play, performed at the Bay Street Theater in Sag Harbor (2019), was “Lives in the Basement, Does Nothing,” a musical monologue on the art of writing, for which he sang and played piano. William Safire of the New York Times wrote that Roger Rosenblatt’s work represents “some of the most profound and stylish writing in America today.” Vanity Fair said that he “set new standards of thought and compassion” in journalism. The Philadelphia Inquirer cited his essays for “unparalleled elegance and wit.” Kirkus Reviews noted, "He has excelled in nearly every literary form." UPI (United Press International) called him “a national treasure.” In his recent books, Rosenblatt has experimented with a form of narrative that connects section to section, without chapter demarcations, dismissing chronological time, and mixing fact and fiction. The effect he seeks is akin to movements in music. In his review of The Boy Detective in the New York Times Book Review, Pete Hamill compared Rosenblatt's style to that of "a great jazz musician...moving from one emotion to another, playing some with a dose of irony, others with joy, and a few with pain and melancholy (the blues, of course). Alone with the instrument of his art, he seems to be hoping only to surprise himself." The Kirkus Review of The Book of Love said, "His wanderings with the subject of love are like Coltrane at the Village Vanguard. When you hear it, you know." In November, 2015, Rosenblatt received the 2015 Kenyon Review Award for Literary Achievement. In June, 2016, he was awarded the President's Medal of the Chautauqua Institution for the artistic and moral quality of his body of work. In April, 2023, he received a Guggenheim Fellowship. In June, 2023, he received the NYU College of Arts and Science Alumni Achievement Award. Seven universities have awarded him honorary doctorates. In 2018, he launched a podcast: Word for Word with Roger Rosenblatt. In 2021, he was honored by the Fulbright Association on its 75th Anniversary. Also in 2021, he founded Write America, a national reading series broadcast weekly by writers devoted to healing divisions in the country. Works Black Fiction (1974) Children of War (1983) Witness: The World Since Hiroshima (1985) Life Itself: Abortion in the American Mind (1992) The Man In The Water (1994) Coming Apart: A Memoir of the Harvard Wars of 1969 (1997) Consuming Desires: Consumption, Culture and the Pursuit of Happiness (1999) Rules for Aging (2000) Where We Stand: 30 Reasons for Loving Our Country (2002) Anything Can Happen (2004) Lapham Rising (2006) Beet (2008) Making Toast (2010) Unless it Moves the Human Heart: The Art and Craft of Writing (2011) Kayak Morning (2012) The Boy Detective: A New York Childhood (2013) The Book of Love (2015) Thomas Murphy (2016) The Story I Am (2020) Cold Moon (2020) Cataract Blues (2023) References External links Living people Harvard University alumni Harvard University faculty Stony Brook University faculty The American Spectator people The New Republic people Time (magazine) people 1940 births American male journalists
Mixogaster is a genus of hoverflies native to North America and South America, with 21 known species. Mixogaster is distinct by lacking an appendix on vein R4+5, having a reduced and bare metasternum, an unarmed scutellum, and usually an appendix on vein M extending in cell R4+5. Larvae are found in ant nests. Species References Hoverfly genera Diptera of North America Diptera of South America Microdontinae Taxa named by Pierre-Justin-Marie Macquart
```python # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """Tests for official.nlp.projects.lra.mega_encoder.""" import numpy as np import tensorflow as tf, tf_keras from official.projects.lra import mega_encoder class MegaEncoderTest(tf.test.TestCase): def test_encoder(self): sequence_length = 1024 batch_size = 2 vocab_size = 1024 network = mega_encoder.MegaEncoder( num_layers=1, vocab_size=1024, max_sequence_length=4096, ) word_id_data = np.random.randint( vocab_size, size=(batch_size, sequence_length) ) mask_data = np.random.randint(2, size=(batch_size, sequence_length)) type_id_data = np.random.randint(2, size=(batch_size, sequence_length)) outputs = network({ "input_word_ids": word_id_data, "input_mask": mask_data, "input_type_ids": type_id_data, }) self.assertEqual( outputs["sequence_output"].shape, (batch_size, sequence_length, 128), ) if __name__ == "__main__": tf.test.main() ```
```go package css_parser import ( "fmt" "testing" "github.com/evanw/esbuild/internal/ast" "github.com/evanw/esbuild/internal/compat" "github.com/evanw/esbuild/internal/config" "github.com/evanw/esbuild/internal/css_printer" "github.com/evanw/esbuild/internal/logger" "github.com/evanw/esbuild/internal/test" ) func expectPrintedCommon(t *testing.T, name string, contents string, expected string, expectedLog string, loader config.Loader, options config.Options) { t.Helper() t.Run(name, func(t *testing.T) { t.Helper() log := logger.NewDeferLog(logger.DeferLogNoVerboseOrDebug, nil) tree := Parse(log, test.SourceForTest(contents), OptionsFromConfig(loader, &options)) msgs := log.Done() text := "" for _, msg := range msgs { text += msg.String(logger.OutputOptions{}, logger.TerminalInfo{}) } test.AssertEqualWithDiff(t, text, expectedLog) symbols := ast.NewSymbolMap(1) symbols.SymbolsForSource[0] = tree.Symbols result := css_printer.Print(tree, symbols, css_printer.Options{ MinifyWhitespace: options.MinifyWhitespace, }) test.AssertEqualWithDiff(t, string(result.CSS), expected) }) } func expectPrinted(t *testing.T, contents string, expected string, expectedLog string) { t.Helper() expectPrintedCommon(t, contents, contents, expected, expectedLog, config.LoaderCSS, config.Options{}) } func expectPrintedLocal(t *testing.T, contents string, expected string, expectedLog string) { t.Helper() expectPrintedCommon(t, contents+" [local]", contents, expected, expectedLog, config.LoaderLocalCSS, config.Options{}) } func expectPrintedLower(t *testing.T, contents string, expected string, expectedLog string) { t.Helper() expectPrintedCommon(t, contents+" [lower]", contents, expected, expectedLog, config.LoaderCSS, config.Options{ UnsupportedCSSFeatures: ^compat.CSSFeature(0), }) } func expectPrintedLowerUnsupported(t *testing.T, unsupportedCSSFeatures compat.CSSFeature, contents string, expected string, expectedLog string) { t.Helper() expectPrintedCommon(t, contents+" [lower]", contents, expected, expectedLog, config.LoaderCSS, config.Options{ UnsupportedCSSFeatures: unsupportedCSSFeatures, }) } func expectPrintedWithAllPrefixes(t *testing.T, contents string, expected string, expectedLog string) { t.Helper() expectPrintedCommon(t, contents+" [prefixed]", contents, expected, expectedLog, config.LoaderCSS, config.Options{ CSSPrefixData: compat.CSSPrefixData(map[compat.Engine]compat.Semver{ compat.Chrome: {Parts: []int{0}}, compat.Edge: {Parts: []int{0}}, compat.Firefox: {Parts: []int{0}}, compat.IE: {Parts: []int{0}}, compat.IOS: {Parts: []int{0}}, compat.Opera: {Parts: []int{0}}, compat.Safari: {Parts: []int{0}}, }), }) } func expectPrintedMinify(t *testing.T, contents string, expected string, expectedLog string) { t.Helper() expectPrintedCommon(t, contents+" [minify]", contents, expected, expectedLog, config.LoaderCSS, config.Options{ MinifyWhitespace: true, }) } func expectPrintedMangle(t *testing.T, contents string, expected string, expectedLog string) { t.Helper() expectPrintedCommon(t, contents+" [mangle]", contents, expected, expectedLog, config.LoaderCSS, config.Options{ MinifySyntax: true, }) } func expectPrintedLowerMangle(t *testing.T, contents string, expected string, expectedLog string) { t.Helper() expectPrintedCommon(t, contents+" [lower, mangle]", contents, expected, expectedLog, config.LoaderCSS, config.Options{ UnsupportedCSSFeatures: ^compat.CSSFeature(0), MinifySyntax: true, }) } func expectPrintedMangleMinify(t *testing.T, contents string, expected string, expectedLog string) { t.Helper() expectPrintedCommon(t, contents+" [mangle, minify]", contents, expected, expectedLog, config.LoaderCSS, config.Options{ MinifySyntax: true, MinifyWhitespace: true, }) } func expectPrintedLowerMinify(t *testing.T, contents string, expected string, expectedLog string) { t.Helper() expectPrintedCommon(t, contents+" [lower, minify]", contents, expected, expectedLog, config.LoaderCSS, config.Options{ UnsupportedCSSFeatures: ^compat.CSSFeature(0), MinifyWhitespace: true, }) } func TestSingleLineComment(t *testing.T) { expectPrinted(t, "a, // a\nb // b\n{}", "a, // a b // b {\n}\n", "<stdin>: WARNING: Comments in CSS use \"/* ... */\" instead of \"//\"\n"+ "<stdin>: WARNING: Comments in CSS use \"/* ... */\" instead of \"//\"\n") expectPrinted(t, "a, ///// a /////\n{}", "a, ///// a ///// {\n}\n", "<stdin>: WARNING: Comments in CSS use \"/* ... */\" instead of \"//\"\n") } func TestEscapes(t *testing.T) { // TIdent expectPrinted(t, "a { value: id\\65nt }", "a {\n value: ident;\n}\n", "") expectPrinted(t, "a { value: \\69 dent }", "a {\n value: ident;\n}\n", "") expectPrinted(t, "a { value: \\69dent }", "a {\n value: \u69DEnt;\n}\n", "") expectPrinted(t, "a { value: \\2cx }", "a {\n value: \\,x;\n}\n", "") expectPrinted(t, "a { value: \\,x }", "a {\n value: \\,x;\n}\n", "") expectPrinted(t, "a { value: x\\2c }", "a {\n value: x\\,;\n}\n", "") expectPrinted(t, "a { value: x\\, }", "a {\n value: x\\,;\n}\n", "") expectPrinted(t, "a { value: x\\0 }", "a {\n value: x\uFFFD;\n}\n", "") expectPrinted(t, "a { value: x\\1 }", "a {\n value: x\\\x01;\n}\n", "") expectPrinted(t, "a { value: x\x00 }", "a {\n value: x\uFFFD;\n}\n", "") expectPrinted(t, "a { value: x\x01 }", "a {\n value: x\x01;\n}\n", "") // THash expectPrinted(t, "a { value: #0h\\61sh }", "a {\n value: #0hash;\n}\n", "") expectPrinted(t, "a { value: #\\30hash }", "a {\n value: #0hash;\n}\n", "") expectPrinted(t, "a { value: #\\2cx }", "a {\n value: #\\,x;\n}\n", "") expectPrinted(t, "a { value: #\\,x }", "a {\n value: #\\,x;\n}\n", "") // THashID expectPrinted(t, "a { value: #h\\61sh }", "a {\n value: #hash;\n}\n", "") expectPrinted(t, "a { value: #\\68 ash }", "a {\n value: #hash;\n}\n", "") expectPrinted(t, "a { value: #\\68ash }", "a {\n value: #\u068Ash;\n}\n", "") expectPrinted(t, "a { value: #x\\2c }", "a {\n value: #x\\,;\n}\n", "") expectPrinted(t, "a { value: #x\\, }", "a {\n value: #x\\,;\n}\n", "") // TFunction expectPrinted(t, "a { value: f\\6e() }", "a {\n value: fn();\n}\n", "") expectPrinted(t, "a { value: \\66n() }", "a {\n value: fn();\n}\n", "") expectPrinted(t, "a { value: \\2cx() }", "a {\n value: \\,x();\n}\n", "") expectPrinted(t, "a { value: \\,x() }", "a {\n value: \\,x();\n}\n", "") expectPrinted(t, "a { value: x\\2c() }", "a {\n value: x\\,();\n}\n", "") expectPrinted(t, "a { value: x\\,() }", "a {\n value: x\\,();\n}\n", "") // TString expectPrinted(t, "a { value: 'a\\62 c' }", "a {\n value: \"abc\";\n}\n", "") expectPrinted(t, "a { value: 'a\\62c' }", "a {\n value: \"a\u062C\";\n}\n", "") expectPrinted(t, "a { value: '\\61 bc' }", "a {\n value: \"abc\";\n}\n", "") expectPrinted(t, "a { value: '\\61bc' }", "a {\n value: \"\u61BC\";\n}\n", "") expectPrinted(t, "a { value: '\\2c' }", "a {\n value: \",\";\n}\n", "") expectPrinted(t, "a { value: '\\,' }", "a {\n value: \",\";\n}\n", "") expectPrinted(t, "a { value: '\\0' }", "a {\n value: \"\uFFFD\";\n}\n", "") expectPrinted(t, "a { value: '\\1' }", "a {\n value: \"\x01\";\n}\n", "") expectPrinted(t, "a { value: '\x00' }", "a {\n value: \"\uFFFD\";\n}\n", "") expectPrinted(t, "a { value: '\x01' }", "a {\n value: \"\x01\";\n}\n", "") // TURL expectPrinted(t, "a { value: url(a\\62 c) }", "a {\n value: url(abc);\n}\n", "") expectPrinted(t, "a { value: url(a\\62c) }", "a {\n value: url(a\u062C);\n}\n", "") expectPrinted(t, "a { value: url(\\61 bc) }", "a {\n value: url(abc);\n}\n", "") expectPrinted(t, "a { value: url(\\61bc) }", "a {\n value: url(\u61BC);\n}\n", "") expectPrinted(t, "a { value: url(\\2c) }", "a {\n value: url(,);\n}\n", "") expectPrinted(t, "a { value: url(\\,) }", "a {\n value: url(,);\n}\n", "") // TAtKeyword expectPrinted(t, "a { value: @k\\65yword }", "a {\n value: @keyword;\n}\n", "") expectPrinted(t, "a { value: @\\6b eyword }", "a {\n value: @keyword;\n}\n", "") expectPrinted(t, "a { value: @\\6beyword }", "a {\n value: @\u06BEyword;\n}\n", "") expectPrinted(t, "a { value: @\\2cx }", "a {\n value: @\\,x;\n}\n", "") expectPrinted(t, "a { value: @\\,x }", "a {\n value: @\\,x;\n}\n", "") expectPrinted(t, "a { value: @x\\2c }", "a {\n value: @x\\,;\n}\n", "") expectPrinted(t, "a { value: @x\\, }", "a {\n value: @x\\,;\n}\n", "") // TDimension expectPrinted(t, "a { value: 10\\65m }", "a {\n value: 10em;\n}\n", "") expectPrinted(t, "a { value: 10p\\32x }", "a {\n value: 10p2x;\n}\n", "") expectPrinted(t, "a { value: 10e\\32x }", "a {\n value: 10\\65 2x;\n}\n", "") expectPrinted(t, "a { value: 10e-\\32x }", "a {\n value: 10\\65-2x;\n}\n", "") expectPrinted(t, "a { value: 10E\\32x }", "a {\n value: 10\\45 2x;\n}\n", "") expectPrinted(t, "a { value: 10E-\\32x }", "a {\n value: 10\\45-2x;\n}\n", "") expectPrinted(t, "a { value: 10e1e\\32x }", "a {\n value: 10e1e2x;\n}\n", "") expectPrinted(t, "a { value: 10e1e-\\32x }", "a {\n value: 10e1e-2x;\n}\n", "") expectPrinted(t, "a { value: 10e1E\\32x }", "a {\n value: 10e1E2x;\n}\n", "") expectPrinted(t, "a { value: 10e1E-\\32x }", "a {\n value: 10e1E-2x;\n}\n", "") expectPrinted(t, "a { value: 10E1e\\32x }", "a {\n value: 10E1e2x;\n}\n", "") expectPrinted(t, "a { value: 10E1e-\\32x }", "a {\n value: 10E1e-2x;\n}\n", "") expectPrinted(t, "a { value: 10E1E\\32x }", "a {\n value: 10E1E2x;\n}\n", "") expectPrinted(t, "a { value: 10E1E-\\32x }", "a {\n value: 10E1E-2x;\n}\n", "") expectPrinted(t, "a { value: 10\\32x }", "a {\n value: 10\\32x;\n}\n", "") expectPrinted(t, "a { value: 10\\2cx }", "a {\n value: 10\\,x;\n}\n", "") expectPrinted(t, "a { value: 10\\,x }", "a {\n value: 10\\,x;\n}\n", "") expectPrinted(t, "a { value: 10x\\2c }", "a {\n value: 10x\\,;\n}\n", "") expectPrinted(t, "a { value: 10x\\, }", "a {\n value: 10x\\,;\n}\n", "") // This must remain unescaped. See path_to_url expectPrinted(t, "@font-face { unicode-range: U+0e2e-0e2f }", "@font-face {\n unicode-range: U+0e2e-0e2f;\n}\n", "") // RDeclaration colorWarning := "<stdin>: WARNING: \",olor\" is not a known CSS property\nNOTE: Did you mean \"color\" instead?\n" expectPrintedMangle(t, "a { c\\6flor: #f00 }", "a {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { \\63olor: #f00 }", "a {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { \\2color: #f00 }", "a {\n \\,olor: #f00;\n}\n", colorWarning) expectPrintedMangle(t, "a { \\,olor: #f00 }", "a {\n \\,olor: #f00;\n}\n", colorWarning) // RUnknownAt expectPrinted(t, "@unknown;", "@unknown;\n", "") expectPrinted(t, "@u\\6eknown;", "@unknown;\n", "") expectPrinted(t, "@\\75nknown;", "@unknown;\n", "") expectPrinted(t, "@u\\2cnknown;", "@u\\,nknown;\n", "") expectPrinted(t, "@u\\,nknown;", "@u\\,nknown;\n", "") expectPrinted(t, "@\\2cunknown;", "@\\,unknown;\n", "") expectPrinted(t, "@\\,unknown;", "@\\,unknown;\n", "") // RAtKeyframes expectPrinted(t, "@k\\65yframes abc { from {} }", "@keyframes abc {\n from {\n }\n}\n", "") expectPrinted(t, "@keyframes \\61 bc { from {} }", "@keyframes abc {\n from {\n }\n}\n", "") expectPrinted(t, "@keyframes a\\62 c { from {} }", "@keyframes abc {\n from {\n }\n}\n", "") expectPrinted(t, "@keyframes abc { \\66rom {} }", "@keyframes abc {\n from {\n }\n}\n", "") expectPrinted(t, "@keyframes a\\2c c { \\66rom {} }", "@keyframes a\\,c {\n from {\n }\n}\n", "") expectPrinted(t, "@keyframes a\\,c { \\66rom {} }", "@keyframes a\\,c {\n from {\n }\n}\n", "") // RAtNamespace namespaceWarning := "<stdin>: WARNING: \"@namespace\" rules are not supported\n" expectPrinted(t, "@n\\61mespace ns 'path';", "@namespace ns \"path\";\n", namespaceWarning) expectPrinted(t, "@namespace \\6es 'path';", "@namespace ns \"path\";\n", namespaceWarning) expectPrinted(t, "@namespace ns 'p\\61th';", "@namespace ns \"path\";\n", namespaceWarning) expectPrinted(t, "@namespace \\2cs 'p\\61th';", "@namespace \\,s \"path\";\n", namespaceWarning) expectPrinted(t, "@namespace \\,s 'p\\61th';", "@namespace \\,s \"path\";\n", namespaceWarning) // CompoundSelector expectPrinted(t, "* {}", "* {\n}\n", "") expectPrinted(t, "*|div {}", "*|div {\n}\n", "") expectPrinted(t, "\\2a {}", "\\* {\n}\n", "") expectPrinted(t, "\\2a|div {}", "\\*|div {\n}\n", "") expectPrinted(t, "\\2d {}", "\\- {\n}\n", "") expectPrinted(t, "\\2d- {}", "-- {\n}\n", "") expectPrinted(t, "-\\2d {}", "-- {\n}\n", "") expectPrinted(t, "\\2d 123 {}", "\\-123 {\n}\n", "") // SSHash expectPrinted(t, "#h\\61sh {}", "#hash {\n}\n", "") expectPrinted(t, "#\\2chash {}", "#\\,hash {\n}\n", "") expectPrinted(t, "#\\,hash {}", "#\\,hash {\n}\n", "") expectPrinted(t, "#\\2d {}", "#\\- {\n}\n", "") expectPrinted(t, "#\\2d- {}", "#-- {\n}\n", "") expectPrinted(t, "#-\\2d {}", "#-- {\n}\n", "") expectPrinted(t, "#\\2d 123 {}", "#\\-123 {\n}\n", "") expectPrinted(t, "#\\61hash {}", "#ahash {\n}\n", "") expectPrinted(t, "#\\30hash {}", "#\\30hash {\n}\n", "") expectPrinted(t, "#0\\2chash {}", "#0\\,hash {\n}\n", "<stdin>: WARNING: Unexpected \"#0\\\\2chash\"\n") expectPrinted(t, "#0\\,hash {}", "#0\\,hash {\n}\n", "<stdin>: WARNING: Unexpected \"#0\\\\,hash\"\n") // SSClass expectPrinted(t, ".cl\\61ss {}", ".class {\n}\n", "") expectPrinted(t, ".\\2c class {}", ".\\,class {\n}\n", "") expectPrinted(t, ".\\,class {}", ".\\,class {\n}\n", "") // SSPseudoClass expectPrinted(t, ":pseudocl\\61ss {}", ":pseudoclass {\n}\n", "") expectPrinted(t, ":pseudo\\2c class {}", ":pseudo\\,class {\n}\n", "") expectPrinted(t, ":pseudo\\,class {}", ":pseudo\\,class {\n}\n", "") expectPrinted(t, ":pseudo(cl\\61ss) {}", ":pseudo(class) {\n}\n", "") expectPrinted(t, ":pseudo(cl\\2css) {}", ":pseudo(cl\\,ss) {\n}\n", "") expectPrinted(t, ":pseudo(cl\\,ss) {}", ":pseudo(cl\\,ss) {\n}\n", "") // SSAttribute expectPrinted(t, "[\\61ttr] {}", "[attr] {\n}\n", "") expectPrinted(t, "[\\2c attr] {}", "[\\,attr] {\n}\n", "") expectPrinted(t, "[\\,attr] {}", "[\\,attr] {\n}\n", "") expectPrinted(t, "[attr\\7e=x] {}", "[attr\\~=x] {\n}\n", "") expectPrinted(t, "[attr\\~=x] {}", "[attr\\~=x] {\n}\n", "") expectPrinted(t, "[attr=\\2c] {}", "[attr=\",\"] {\n}\n", "") expectPrinted(t, "[attr=\\,] {}", "[attr=\",\"] {\n}\n", "") expectPrinted(t, "[attr=\"-\"] {}", "[attr=\"-\"] {\n}\n", "") expectPrinted(t, "[attr=\"--\"] {}", "[attr=--] {\n}\n", "") expectPrinted(t, "[attr=\"-a\"] {}", "[attr=-a] {\n}\n", "") expectPrinted(t, "[\\6es|attr] {}", "[ns|attr] {\n}\n", "") expectPrinted(t, "[ns|\\61ttr] {}", "[ns|attr] {\n}\n", "") expectPrinted(t, "[\\2cns|attr] {}", "[\\,ns|attr] {\n}\n", "") expectPrinted(t, "[ns|\\2c attr] {}", "[ns|\\,attr] {\n}\n", "") expectPrinted(t, "[*|attr] {}", "[*|attr] {\n}\n", "") expectPrinted(t, "[\\2a|attr] {}", "[\\*|attr] {\n}\n", "") } func TestString(t *testing.T) { expectPrinted(t, "a:after { content: 'a\\\rb' }", "a:after {\n content: \"ab\";\n}\n", "") expectPrinted(t, "a:after { content: 'a\\\nb' }", "a:after {\n content: \"ab\";\n}\n", "") expectPrinted(t, "a:after { content: 'a\\\fb' }", "a:after {\n content: \"ab\";\n}\n", "") expectPrinted(t, "a:after { content: 'a\\\r\nb' }", "a:after {\n content: \"ab\";\n}\n", "") expectPrinted(t, "a:after { content: 'a\\62 c' }", "a:after {\n content: \"abc\";\n}\n", "") expectPrinted(t, "a:after { content: '\r' }", "a:after {\n content: '\n ' }\n ;\n}\n", `<stdin>: WARNING: Unterminated string token <stdin>: WARNING: Expected "}" to go with "{" <stdin>: NOTE: The unbalanced "{" is here: <stdin>: WARNING: Unterminated string token `) expectPrinted(t, "a:after { content: '\n' }", "a:after {\n content: '\n ' }\n ;\n}\n", `<stdin>: WARNING: Unterminated string token <stdin>: WARNING: Expected "}" to go with "{" <stdin>: NOTE: The unbalanced "{" is here: <stdin>: WARNING: Unterminated string token `) expectPrinted(t, "a:after { content: '\f' }", "a:after {\n content: '\n ' }\n ;\n}\n", `<stdin>: WARNING: Unterminated string token <stdin>: WARNING: Expected "}" to go with "{" <stdin>: NOTE: The unbalanced "{" is here: <stdin>: WARNING: Unterminated string token `) expectPrinted(t, "a:after { content: '\r\n' }", "a:after {\n content: '\n ' }\n ;\n}\n", `<stdin>: WARNING: Unterminated string token <stdin>: WARNING: Expected "}" to go with "{" <stdin>: NOTE: The unbalanced "{" is here: <stdin>: WARNING: Unterminated string token `) expectPrinted(t, "a:after { content: '\\1010101' }", "a:after {\n content: \"\U001010101\";\n}\n", "") expectPrinted(t, "a:after { content: '\\invalid' }", "a:after {\n content: \"invalid\";\n}\n", "") } func TestNumber(t *testing.T) { for _, ext := range []string{"", "%", "px+"} { expectPrinted(t, "a { width: .0"+ext+"; }", "a {\n width: .0"+ext+";\n}\n", "") expectPrinted(t, "a { width: .00"+ext+"; }", "a {\n width: .00"+ext+";\n}\n", "") expectPrinted(t, "a { width: .10"+ext+"; }", "a {\n width: .10"+ext+";\n}\n", "") expectPrinted(t, "a { width: 0."+ext+"; }", "a {\n width: 0."+ext+";\n}\n", "") expectPrinted(t, "a { width: 0.0"+ext+"; }", "a {\n width: 0.0"+ext+";\n}\n", "") expectPrinted(t, "a { width: 0.1"+ext+"; }", "a {\n width: 0.1"+ext+";\n}\n", "") expectPrinted(t, "a { width: +.0"+ext+"; }", "a {\n width: +.0"+ext+";\n}\n", "") expectPrinted(t, "a { width: +.00"+ext+"; }", "a {\n width: +.00"+ext+";\n}\n", "") expectPrinted(t, "a { width: +.10"+ext+"; }", "a {\n width: +.10"+ext+";\n}\n", "") expectPrinted(t, "a { width: +0."+ext+"; }", "a {\n width: +0."+ext+";\n}\n", "") expectPrinted(t, "a { width: +0.0"+ext+"; }", "a {\n width: +0.0"+ext+";\n}\n", "") expectPrinted(t, "a { width: +0.1"+ext+"; }", "a {\n width: +0.1"+ext+";\n}\n", "") expectPrinted(t, "a { width: -.0"+ext+"; }", "a {\n width: -.0"+ext+";\n}\n", "") expectPrinted(t, "a { width: -.00"+ext+"; }", "a {\n width: -.00"+ext+";\n}\n", "") expectPrinted(t, "a { width: -.10"+ext+"; }", "a {\n width: -.10"+ext+";\n}\n", "") expectPrinted(t, "a { width: -0."+ext+"; }", "a {\n width: -0."+ext+";\n}\n", "") expectPrinted(t, "a { width: -0.0"+ext+"; }", "a {\n width: -0.0"+ext+";\n}\n", "") expectPrinted(t, "a { width: -0.1"+ext+"; }", "a {\n width: -0.1"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: .0"+ext+"; }", "a {\n width: 0"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: .00"+ext+"; }", "a {\n width: 0"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: .10"+ext+"; }", "a {\n width: .1"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: 0."+ext+"; }", "a {\n width: 0"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: 0.0"+ext+"; }", "a {\n width: 0"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: 0.1"+ext+"; }", "a {\n width: .1"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: +.0"+ext+"; }", "a {\n width: +0"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: +.00"+ext+"; }", "a {\n width: +0"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: +.10"+ext+"; }", "a {\n width: +.1"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: +0."+ext+"; }", "a {\n width: +0"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: +0.0"+ext+"; }", "a {\n width: +0"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: +0.1"+ext+"; }", "a {\n width: +.1"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: -.0"+ext+"; }", "a {\n width: -0"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: -.00"+ext+"; }", "a {\n width: -0"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: -.10"+ext+"; }", "a {\n width: -.1"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: -0."+ext+"; }", "a {\n width: -0"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: -0.0"+ext+"; }", "a {\n width: -0"+ext+";\n}\n", "") expectPrintedMangle(t, "a { width: -0.1"+ext+"; }", "a {\n width: -.1"+ext+";\n}\n", "") } } func TestURL(t *testing.T) { expectPrinted(t, "a { background: url(foo.png) }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url('foo.png') }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url(\"foo.png\") }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url(\"foo.png\" ) }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url(\"foo.png\"\t) }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url(\"foo.png\"\r) }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url(\"foo.png\"\n) }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url(\"foo.png\"\f) }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url(\"foo.png\"\r\n) }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url( \"foo.png\") }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url(\t\"foo.png\") }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url(\r\"foo.png\") }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url(\n\"foo.png\") }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url(\f\"foo.png\") }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url(\r\n\"foo.png\") }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url( \"foo.png\" ) }", "a {\n background: url(foo.png);\n}\n", "") expectPrinted(t, "a { background: url(\"foo.png\" extra-stuff) }", "a {\n background: url(\"foo.png\" extra-stuff);\n}\n", "") expectPrinted(t, "a { background: url( \"foo.png\" extra-stuff ) }", "a {\n background: url(\"foo.png\" extra-stuff);\n}\n", "") } func TestHexColor(t *testing.T) { // "#RGBA" expectPrinted(t, "a { color: #1234 }", "a {\n color: #1234;\n}\n", "") expectPrinted(t, "a { color: #123f }", "a {\n color: #123f;\n}\n", "") expectPrinted(t, "a { color: #abcd }", "a {\n color: #abcd;\n}\n", "") expectPrinted(t, "a { color: #abcf }", "a {\n color: #abcf;\n}\n", "") expectPrinted(t, "a { color: #ABCD }", "a {\n color: #ABCD;\n}\n", "") expectPrinted(t, "a { color: #ABCF }", "a {\n color: #ABCF;\n}\n", "") expectPrintedMangle(t, "a { color: #1234 }", "a {\n color: #1234;\n}\n", "") expectPrintedMangle(t, "a { color: #123f }", "a {\n color: #123;\n}\n", "") expectPrintedMangle(t, "a { color: #abcd }", "a {\n color: #abcd;\n}\n", "") expectPrintedMangle(t, "a { color: #abcf }", "a {\n color: #abc;\n}\n", "") expectPrintedMangle(t, "a { color: #ABCD }", "a {\n color: #abcd;\n}\n", "") expectPrintedMangle(t, "a { color: #ABCF }", "a {\n color: #abc;\n}\n", "") // "#RRGGBB" expectPrinted(t, "a { color: #112233 }", "a {\n color: #112233;\n}\n", "") expectPrinted(t, "a { color: #122233 }", "a {\n color: #122233;\n}\n", "") expectPrinted(t, "a { color: #112333 }", "a {\n color: #112333;\n}\n", "") expectPrinted(t, "a { color: #112234 }", "a {\n color: #112234;\n}\n", "") expectPrintedMangle(t, "a { color: #112233 }", "a {\n color: #123;\n}\n", "") expectPrintedMangle(t, "a { color: #122233 }", "a {\n color: #122233;\n}\n", "") expectPrintedMangle(t, "a { color: #112333 }", "a {\n color: #112333;\n}\n", "") expectPrintedMangle(t, "a { color: #112234 }", "a {\n color: #112234;\n}\n", "") expectPrinted(t, "a { color: #aabbcc }", "a {\n color: #aabbcc;\n}\n", "") expectPrinted(t, "a { color: #abbbcc }", "a {\n color: #abbbcc;\n}\n", "") expectPrinted(t, "a { color: #aabccc }", "a {\n color: #aabccc;\n}\n", "") expectPrinted(t, "a { color: #aabbcd }", "a {\n color: #aabbcd;\n}\n", "") expectPrintedMangle(t, "a { color: #aabbcc }", "a {\n color: #abc;\n}\n", "") expectPrintedMangle(t, "a { color: #abbbcc }", "a {\n color: #abbbcc;\n}\n", "") expectPrintedMangle(t, "a { color: #aabccc }", "a {\n color: #aabccc;\n}\n", "") expectPrintedMangle(t, "a { color: #aabbcd }", "a {\n color: #aabbcd;\n}\n", "") expectPrinted(t, "a { color: #AABBCC }", "a {\n color: #AABBCC;\n}\n", "") expectPrinted(t, "a { color: #ABBBCC }", "a {\n color: #ABBBCC;\n}\n", "") expectPrinted(t, "a { color: #AABCCC }", "a {\n color: #AABCCC;\n}\n", "") expectPrinted(t, "a { color: #AABBCD }", "a {\n color: #AABBCD;\n}\n", "") expectPrintedMangle(t, "a { color: #AABBCC }", "a {\n color: #abc;\n}\n", "") expectPrintedMangle(t, "a { color: #ABBBCC }", "a {\n color: #abbbcc;\n}\n", "") expectPrintedMangle(t, "a { color: #AABCCC }", "a {\n color: #aabccc;\n}\n", "") expectPrintedMangle(t, "a { color: #AABBCD }", "a {\n color: #aabbcd;\n}\n", "") // "#RRGGBBAA" expectPrinted(t, "a { color: #11223344 }", "a {\n color: #11223344;\n}\n", "") expectPrinted(t, "a { color: #12223344 }", "a {\n color: #12223344;\n}\n", "") expectPrinted(t, "a { color: #11233344 }", "a {\n color: #11233344;\n}\n", "") expectPrinted(t, "a { color: #11223444 }", "a {\n color: #11223444;\n}\n", "") expectPrinted(t, "a { color: #11223345 }", "a {\n color: #11223345;\n}\n", "") expectPrintedMangle(t, "a { color: #11223344 }", "a {\n color: #1234;\n}\n", "") expectPrintedMangle(t, "a { color: #12223344 }", "a {\n color: #12223344;\n}\n", "") expectPrintedMangle(t, "a { color: #11233344 }", "a {\n color: #11233344;\n}\n", "") expectPrintedMangle(t, "a { color: #11223444 }", "a {\n color: #11223444;\n}\n", "") expectPrintedMangle(t, "a { color: #11223345 }", "a {\n color: #11223345;\n}\n", "") expectPrinted(t, "a { color: #aabbccdd }", "a {\n color: #aabbccdd;\n}\n", "") expectPrinted(t, "a { color: #abbbccdd }", "a {\n color: #abbbccdd;\n}\n", "") expectPrinted(t, "a { color: #aabcccdd }", "a {\n color: #aabcccdd;\n}\n", "") expectPrinted(t, "a { color: #aabbcddd }", "a {\n color: #aabbcddd;\n}\n", "") expectPrinted(t, "a { color: #aabbccde }", "a {\n color: #aabbccde;\n}\n", "") expectPrintedMangle(t, "a { color: #aabbccdd }", "a {\n color: #abcd;\n}\n", "") expectPrintedMangle(t, "a { color: #abbbccdd }", "a {\n color: #abbbccdd;\n}\n", "") expectPrintedMangle(t, "a { color: #aabcccdd }", "a {\n color: #aabcccdd;\n}\n", "") expectPrintedMangle(t, "a { color: #aabbcddd }", "a {\n color: #aabbcddd;\n}\n", "") expectPrintedMangle(t, "a { color: #aabbccde }", "a {\n color: #aabbccde;\n}\n", "") expectPrinted(t, "a { color: #AABBCCDD }", "a {\n color: #AABBCCDD;\n}\n", "") expectPrinted(t, "a { color: #ABBBCCDD }", "a {\n color: #ABBBCCDD;\n}\n", "") expectPrinted(t, "a { color: #AABCCCDD }", "a {\n color: #AABCCCDD;\n}\n", "") expectPrinted(t, "a { color: #AABBCDDD }", "a {\n color: #AABBCDDD;\n}\n", "") expectPrinted(t, "a { color: #AABBCCDE }", "a {\n color: #AABBCCDE;\n}\n", "") expectPrintedMangle(t, "a { color: #AABBCCDD }", "a {\n color: #abcd;\n}\n", "") expectPrintedMangle(t, "a { color: #ABBBCCDD }", "a {\n color: #abbbccdd;\n}\n", "") expectPrintedMangle(t, "a { color: #AABCCCDD }", "a {\n color: #aabcccdd;\n}\n", "") expectPrintedMangle(t, "a { color: #AABBCDDD }", "a {\n color: #aabbcddd;\n}\n", "") expectPrintedMangle(t, "a { color: #AABBCCDE }", "a {\n color: #aabbccde;\n}\n", "") // "#RRGGBBFF" expectPrinted(t, "a { color: #112233ff }", "a {\n color: #112233ff;\n}\n", "") expectPrinted(t, "a { color: #122233ff }", "a {\n color: #122233ff;\n}\n", "") expectPrinted(t, "a { color: #112333ff }", "a {\n color: #112333ff;\n}\n", "") expectPrinted(t, "a { color: #112234ff }", "a {\n color: #112234ff;\n}\n", "") expectPrinted(t, "a { color: #112233ef }", "a {\n color: #112233ef;\n}\n", "") expectPrintedMangle(t, "a { color: #112233ff }", "a {\n color: #123;\n}\n", "") expectPrintedMangle(t, "a { color: #122233ff }", "a {\n color: #122233;\n}\n", "") expectPrintedMangle(t, "a { color: #112333ff }", "a {\n color: #112333;\n}\n", "") expectPrintedMangle(t, "a { color: #112234ff }", "a {\n color: #112234;\n}\n", "") expectPrintedMangle(t, "a { color: #112233ef }", "a {\n color: #112233ef;\n}\n", "") expectPrinted(t, "a { color: #aabbccff }", "a {\n color: #aabbccff;\n}\n", "") expectPrinted(t, "a { color: #abbbccff }", "a {\n color: #abbbccff;\n}\n", "") expectPrinted(t, "a { color: #aabcccff }", "a {\n color: #aabcccff;\n}\n", "") expectPrinted(t, "a { color: #aabbcdff }", "a {\n color: #aabbcdff;\n}\n", "") expectPrinted(t, "a { color: #aabbccef }", "a {\n color: #aabbccef;\n}\n", "") expectPrintedMangle(t, "a { color: #aabbccff }", "a {\n color: #abc;\n}\n", "") expectPrintedMangle(t, "a { color: #abbbccff }", "a {\n color: #abbbcc;\n}\n", "") expectPrintedMangle(t, "a { color: #aabcccff }", "a {\n color: #aabccc;\n}\n", "") expectPrintedMangle(t, "a { color: #aabbcdff }", "a {\n color: #aabbcd;\n}\n", "") expectPrintedMangle(t, "a { color: #aabbccef }", "a {\n color: #aabbccef;\n}\n", "") expectPrinted(t, "a { color: #AABBCCFF }", "a {\n color: #AABBCCFF;\n}\n", "") expectPrinted(t, "a { color: #ABBBCCFF }", "a {\n color: #ABBBCCFF;\n}\n", "") expectPrinted(t, "a { color: #AABCCCFF }", "a {\n color: #AABCCCFF;\n}\n", "") expectPrinted(t, "a { color: #AABBCDFF }", "a {\n color: #AABBCDFF;\n}\n", "") expectPrinted(t, "a { color: #AABBCCEF }", "a {\n color: #AABBCCEF;\n}\n", "") expectPrintedMangle(t, "a { color: #AABBCCFF }", "a {\n color: #abc;\n}\n", "") expectPrintedMangle(t, "a { color: #ABBBCCFF }", "a {\n color: #abbbcc;\n}\n", "") expectPrintedMangle(t, "a { color: #AABCCCFF }", "a {\n color: #aabccc;\n}\n", "") expectPrintedMangle(t, "a { color: #AABBCDFF }", "a {\n color: #aabbcd;\n}\n", "") expectPrintedMangle(t, "a { color: #AABBCCEF }", "a {\n color: #aabbccef;\n}\n", "") } func TestColorFunctions(t *testing.T) { expectPrinted(t, "a { color: color(display-p3 0.5 0.0 0.0%) }", "a {\n color: color(display-p3 0.5 0.0 0.0%);\n}\n", "") expectPrinted(t, "a { color: color(display-p3 0.5 0.0 0.0% / 0.5) }", "a {\n color: color(display-p3 0.5 0.0 0.0% / 0.5);\n}\n", "") // Check minification of tokens expectPrintedMangle(t, "a { color: color(display-p3 0.5 0.0 0.0%) }", "a {\n color: color(display-p3 .5 0 0%);\n}\n", "") expectPrintedMangle(t, "a { color: color(display-p3 0.5 0.0 0.0% / 0.5) }", "a {\n color: color(display-p3 .5 0 0% / .5);\n}\n", "") // Check out-of-range colors expectPrintedLower(t, "a { before: 0; color: color(display-p3 1 0 0); after: 1 }", "a {\n before: 0;\n color: #ff0f0e;\n color: color(display-p3 1 0 0);\n after: 1;\n}\n", "") expectPrintedLowerMangle(t, "a { before: 0; color: color(display-p3 1 0 0); after: 1 }", "a {\n before: 0;\n color: #ff0f0e;\n color: color(display-p3 1 0 0);\n after: 1;\n}\n", "") expectPrintedLower(t, "a { before: 0; color: color(display-p3 1 0 0 / 0.5); after: 1 }", "a {\n before: 0;\n color: rgba(255, 15, 14, .5);\n color: color(display-p3 1 0 0 / 0.5);\n after: 1;\n}\n", "") expectPrintedLowerMangle(t, "a { before: 0; color: color(display-p3 1 0 0 / 0.5); after: 1 }", "a {\n before: 0;\n color: rgba(255, 15, 14, .5);\n color: color(display-p3 1 0 0 / .5);\n after: 1;\n}\n", "") expectPrintedLower(t, "a { before: 0; background: color(display-p3 1 0 0); after: 1 }", "a {\n before: 0;\n background: #ff0f0e;\n background: color(display-p3 1 0 0);\n after: 1;\n}\n", "") expectPrintedLowerMangle(t, "a { before: 0; background: color(display-p3 1 0 0); after: 1 }", "a {\n before: 0;\n background: #ff0f0e;\n background: color(display-p3 1 0 0);\n after: 1;\n}\n", "") expectPrintedLower(t, "a { before: 0; background: color(display-p3 1 0 0 / 0.5); after: 1 }", "a {\n before: 0;\n background: rgba(255, 15, 14, .5);\n background: color(display-p3 1 0 0 / 0.5);\n after: 1;\n}\n", "") expectPrintedLowerMangle(t, "a { before: 0; background: color(display-p3 1 0 0 / 0.5); after: 1 }", "a {\n before: 0;\n background: rgba(255, 15, 14, .5);\n background: color(display-p3 1 0 0 / .5);\n after: 1;\n}\n", "") expectPrintedLower(t, "a { before: 0; box-shadow: 1px color(display-p3 1 0 0); after: 1 }", "a {\n before: 0;\n box-shadow: 1px #ff0f0e;\n box-shadow: 1px color(display-p3 1 0 0);\n after: 1;\n}\n", "") expectPrintedLowerMangle(t, "a { before: 0; box-shadow: 1px color(display-p3 1 0 0); after: 1 }", "a {\n before: 0;\n box-shadow: 1px #ff0f0e;\n box-shadow: 1px color(display-p3 1 0 0);\n after: 1;\n}\n", "") expectPrintedLower(t, "a { before: 0; box-shadow: 1px color(display-p3 1 0 0 / 0.5); after: 1 }", "a {\n before: 0;\n box-shadow: 1px rgba(255, 15, 14, .5);\n box-shadow: 1px color(display-p3 1 0 0 / 0.5);\n after: 1;\n}\n", "") expectPrintedLowerMangle(t, "a { before: 0; box-shadow: 1px color(display-p3 1 0 0 / 0.5); after: 1 }", "a {\n before: 0;\n box-shadow: 1px rgba(255, 15, 14, .5);\n box-shadow: 1px color(display-p3 1 0 0 / .5);\n after: 1;\n}\n", "") // Don't insert a fallback after a previous instance of the same property expectPrintedLower(t, "a { color: red; color: color(display-p3 1 0 0) }", "a {\n color: red;\n color: color(display-p3 1 0 0);\n}\n", "") expectPrintedLower(t, "a { color: color(display-p3 1 0 0); color: color(display-p3 0 1 0) }", "a {\n color: #ff0f0e;\n color: color(display-p3 1 0 0);\n color: color(display-p3 0 1 0);\n}\n", "") // Check case sensitivity expectPrintedLower(t, "a { color: color(srgb 0.87 0.98 0.807) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "A { Color: Color(Srgb 0.87 0.98 0.807) }", "A {\n Color: #deface;\n}\n", "") expectPrintedLower(t, "A { COLOR: COLOR(SRGB 0.87 0.98 0.807) }", "A {\n COLOR: #deface;\n}\n", "") // Check in-range colors in various color spaces expectPrintedLower(t, "a { color: color(a98-rgb 0.9 0.98 0.81) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(a98-rgb 90% 98% 81%) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(display-p3 0.89 0.977 0.823) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(display-p3 89% 97.7% 82.3%) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(prophoto-rgb 0.877 0.959 0.793) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(prophoto-rgb 87.7% 95.9% 79.3%) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(rec2020 0.895 0.968 0.805) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(rec2020 89.5% 96.8% 80.5%) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(srgb 0.87 0.98 0.807) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(srgb 87% 98% 80.7%) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(srgb-linear 0.73 0.96 0.62) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(srgb-linear 73% 96% 62%) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(xyz 0.754 0.883 0.715) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(xyz 75.4% 88.3% 71.5%) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(xyz-d50 0.773 0.883 0.545) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(xyz-d50 77.3% 88.3% 54.5%) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(xyz-d65 0.754 0.883 0.715) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: color(xyz-d65 75.4% 88.3% 71.5%) }", "a {\n color: #deface;\n}\n", "") // Check color functions with unusual percent reference ranges expectPrintedLower(t, "a { color: lab(95.38 -15 18) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: lab(95.38% -15 18) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: lab(95.38 -12% 18) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: lab(95.38% -15 14.4%) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: lch(95.38 23.57 130.22) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: lch(95.38% 23.57 130.22) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: lch(95.38 19% 130.22) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: lch(95.38 23.57 0.362turn) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: oklab(0.953 -0.045 0.046) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: oklab(95.3% -0.045 0.046) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: oklab(0.953 -11.2% 0.046) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: oklab(0.953 -0.045 11.5%) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: oklch(0.953 0.064 134) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: oklch(95.3% 0.064 134) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: oklch(0.953 16% 134) }", "a {\n color: #deface;\n}\n", "") expectPrintedLower(t, "a { color: oklch(0.953 0.064 0.372turn) }", "a {\n color: #deface;\n}\n", "") // Test alpha expectPrintedLower(t, "a { color: color(srgb 0.87 0.98 0.807 / 0.5) }", "a {\n color: rgba(222, 250, 206, .5);\n}\n", "") expectPrintedLower(t, "a { color: lab(95.38 -15 18 / 0.5) }", "a {\n color: rgba(222, 250, 206, .5);\n}\n", "") expectPrintedLower(t, "a { color: lch(95.38 23.57 130.22 / 0.5) }", "a {\n color: rgba(222, 250, 206, .5);\n}\n", "") expectPrintedLower(t, "a { color: oklab(0.953 -0.045 0.046 / 0.5) }", "a {\n color: rgba(222, 250, 206, .5);\n}\n", "") expectPrintedLower(t, "a { color: oklch(0.953 0.064 134 / 0.5) }", "a {\n color: rgba(222, 250, 206, .5);\n}\n", "") } func TestColorNames(t *testing.T) { expectPrinted(t, "a { color: #f00 }", "a {\n color: #f00;\n}\n", "") expectPrinted(t, "a { color: #f00f }", "a {\n color: #f00f;\n}\n", "") expectPrinted(t, "a { color: #ff0000 }", "a {\n color: #ff0000;\n}\n", "") expectPrinted(t, "a { color: #ff0000ff }", "a {\n color: #ff0000ff;\n}\n", "") expectPrintedMangle(t, "a { color: #f00 }", "a {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: #f00e }", "a {\n color: #f00e;\n}\n", "") expectPrintedMangle(t, "a { color: #f00f }", "a {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: #ff0000 }", "a {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: #ff0000ef }", "a {\n color: #ff0000ef;\n}\n", "") expectPrintedMangle(t, "a { color: #ff0000ff }", "a {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: #ffc0cb }", "a {\n color: pink;\n}\n", "") expectPrintedMangle(t, "a { color: #ffc0cbef }", "a {\n color: #ffc0cbef;\n}\n", "") expectPrintedMangle(t, "a { color: #ffc0cbff }", "a {\n color: pink;\n}\n", "") expectPrinted(t, "a { color: white }", "a {\n color: white;\n}\n", "") expectPrinted(t, "a { color: tUrQuOiSe }", "a {\n color: tUrQuOiSe;\n}\n", "") expectPrintedMangle(t, "a { color: white }", "a {\n color: #fff;\n}\n", "") expectPrintedMangle(t, "a { color: tUrQuOiSe }", "a {\n color: #40e0d0;\n}\n", "") } func TestColorRGBA(t *testing.T) { expectPrintedMangle(t, "a { color: rgba(1 2 3 / 0.5) }", "a {\n color: #01020380;\n}\n", "") expectPrintedMangle(t, "a { color: rgba(1 2 3 / 50%) }", "a {\n color: #0102037f;\n}\n", "") expectPrintedMangle(t, "a { color: rgba(1, 2, 3, 0.5) }", "a {\n color: #01020380;\n}\n", "") expectPrintedMangle(t, "a { color: rgba(1, 2, 3, 50%) }", "a {\n color: #0102037f;\n}\n", "") expectPrintedMangle(t, "a { color: rgba(1% 2% 3% / 0.5) }", "a {\n color: #03050880;\n}\n", "") expectPrintedMangle(t, "a { color: rgba(1% 2% 3% / 50%) }", "a {\n color: #0305087f;\n}\n", "") expectPrintedMangle(t, "a { color: rgba(1%, 2%, 3%, 0.5) }", "a {\n color: #03050880;\n}\n", "") expectPrintedMangle(t, "a { color: rgba(1%, 2%, 3%, 50%) }", "a {\n color: #0305087f;\n}\n", "") expectPrintedLowerMangle(t, "a { color: rgb(1, 2, 3, 0.4) }", "a {\n color: rgba(1, 2, 3, .4);\n}\n", "") expectPrintedLowerMangle(t, "a { color: rgba(1, 2, 3, 40%) }", "a {\n color: rgba(1, 2, 3, .4);\n}\n", "") expectPrintedLowerMangle(t, "a { color: rgb(var(--x) var(--y) var(--z)) }", "a {\n color: rgb(var(--x) var(--y) var(--z));\n}\n", "") } func TestColorHSLA(t *testing.T) { expectPrintedMangle(t, ".red { color: hsl(0, 100%, 50%) }", ".red {\n color: red;\n}\n", "") expectPrintedMangle(t, ".orange { color: hsl(30deg, 100%, 50%) }", ".orange {\n color: #ff8000;\n}\n", "") expectPrintedMangle(t, ".yellow { color: hsl(60 100% 50%) }", ".yellow {\n color: #ff0;\n}\n", "") expectPrintedMangle(t, ".green { color: hsl(120, 100%, 50%) }", ".green {\n color: #0f0;\n}\n", "") expectPrintedMangle(t, ".cyan { color: hsl(200grad, 100%, 50%) }", ".cyan {\n color: #0ff;\n}\n", "") expectPrintedMangle(t, ".blue { color: hsl(240, 100%, 50%) }", ".blue {\n color: #00f;\n}\n", "") expectPrintedMangle(t, ".purple { color: hsl(0.75turn 100% 50%) }", ".purple {\n color: #7f00ff;\n}\n", "") expectPrintedMangle(t, ".magenta { color: hsl(300, 100%, 50%) }", ".magenta {\n color: #f0f;\n}\n", "") expectPrintedMangle(t, "a { color: hsl(30 25% 50% / 50%) }", "a {\n color: #9f80607f;\n}\n", "") expectPrintedMangle(t, "a { color: hsla(30 25% 50% / 50%) }", "a {\n color: #9f80607f;\n}\n", "") expectPrintedLowerMangle(t, "a { color: hsl(1, 2%, 3%, 0.4) }", "a {\n color: rgba(8, 8, 7, .4);\n}\n", "") expectPrintedLowerMangle(t, "a { color: hsla(1, 2%, 3%, 40%) }", "a {\n color: rgba(8, 8, 7, .4);\n}\n", "") expectPrintedLowerMangle(t, "a { color: hsl(var(--x) var(--y) var(--z)) }", "a {\n color: hsl(var(--x) var(--y) var(--z));\n}\n", "") } func TestLowerColor(t *testing.T) { expectPrintedLower(t, "a { color: rebeccapurple }", "a {\n color: #663399;\n}\n", "") expectPrintedLower(t, "a { color: ReBeCcApUrPlE }", "a {\n color: #663399;\n}\n", "") expectPrintedLower(t, "a { color: #0123 }", "a {\n color: rgba(0, 17, 34, .2);\n}\n", "") expectPrintedLower(t, "a { color: #1230 }", "a {\n color: rgba(17, 34, 51, 0);\n}\n", "") expectPrintedLower(t, "a { color: #1234 }", "a {\n color: rgba(17, 34, 51, .267);\n}\n", "") expectPrintedLower(t, "a { color: #123f }", "a {\n color: #112233;\n}\n", "") expectPrintedLower(t, "a { color: #12345678 }", "a {\n color: rgba(18, 52, 86, .47);\n}\n", "") expectPrintedLower(t, "a { color: #ff00007f }", "a {\n color: rgba(255, 0, 0, .498);\n}\n", "") expectPrintedLower(t, "a { color: rgb(1 2 3) }", "a {\n color: rgb(1, 2, 3);\n}\n", "") expectPrintedLower(t, "a { color: hsl(1 2% 3%) }", "a {\n color: hsl(1, 2%, 3%);\n}\n", "") expectPrintedLower(t, "a { color: rgba(1% 2% 3%) }", "a {\n color: rgb(1%, 2%, 3%);\n}\n", "") expectPrintedLower(t, "a { color: hsla(1deg 2% 3%) }", "a {\n color: hsl(1, 2%, 3%);\n}\n", "") expectPrintedLower(t, "a { color: hsla(200grad 2% 3%) }", "a {\n color: hsl(180, 2%, 3%);\n}\n", "") expectPrintedLower(t, "a { color: hsla(6.28319rad 2% 3%) }", "a {\n color: hsl(360, 2%, 3%);\n}\n", "") expectPrintedLower(t, "a { color: hsla(0.5turn 2% 3%) }", "a {\n color: hsl(180, 2%, 3%);\n}\n", "") expectPrintedLower(t, "a { color: hsla(+200grad 2% 3%) }", "a {\n color: hsl(180, 2%, 3%);\n}\n", "") expectPrintedLower(t, "a { color: hsla(-200grad 2% 3%) }", "a {\n color: hsl(-180, 2%, 3%);\n}\n", "") expectPrintedLower(t, "a { color: rgb(1 2 3 / 4) }", "a {\n color: rgba(1, 2, 3, 4);\n}\n", "") expectPrintedLower(t, "a { color: RGB(1 2 3 / 4) }", "a {\n color: rgba(1, 2, 3, 4);\n}\n", "") expectPrintedLower(t, "a { color: rgba(1% 2% 3% / 4%) }", "a {\n color: rgba(1%, 2%, 3%, 0.04);\n}\n", "") expectPrintedLower(t, "a { color: RGBA(1% 2% 3% / 4%) }", "a {\n color: RGBA(1%, 2%, 3%, 0.04);\n}\n", "") expectPrintedLower(t, "a { color: hsl(1 2% 3% / 4) }", "a {\n color: hsla(1, 2%, 3%, 4);\n}\n", "") expectPrintedLower(t, "a { color: HSL(1 2% 3% / 4) }", "a {\n color: hsla(1, 2%, 3%, 4);\n}\n", "") expectPrintedLower(t, "a { color: hsla(1 2% 3% / 4%) }", "a {\n color: hsla(1, 2%, 3%, 0.04);\n}\n", "") expectPrintedLower(t, "a { color: HSLA(1 2% 3% / 4%) }", "a {\n color: HSLA(1, 2%, 3%, 0.04);\n}\n", "") expectPrintedLower(t, "a { color: rgb(1, 2, 3, 4) }", "a {\n color: rgba(1, 2, 3, 4);\n}\n", "") expectPrintedLower(t, "a { color: rgba(1%, 2%, 3%, 4%) }", "a {\n color: rgba(1%, 2%, 3%, 0.04);\n}\n", "") expectPrintedLower(t, "a { color: rgb(1%, 2%, 3%, 0.4%) }", "a {\n color: rgba(1%, 2%, 3%, 0.004);\n}\n", "") expectPrintedLower(t, "a { color: hsl(1, 2%, 3%, 4) }", "a {\n color: hsla(1, 2%, 3%, 4);\n}\n", "") expectPrintedLower(t, "a { color: hsla(1deg, 2%, 3%, 4%) }", "a {\n color: hsla(1, 2%, 3%, 0.04);\n}\n", "") expectPrintedLower(t, "a { color: hsl(1deg, 2%, 3%, 0.4%) }", "a {\n color: hsla(1, 2%, 3%, 0.004);\n}\n", "") expectPrintedLower(t, "a { color: hwb(90deg 20% 40%) }", "a {\n color: #669933;\n}\n", "") expectPrintedLower(t, "a { color: HWB(90deg 20% 40%) }", "a {\n color: #669933;\n}\n", "") expectPrintedLower(t, "a { color: hwb(90deg 20% 40% / 0.2) }", "a {\n color: rgba(102, 153, 51, .2);\n}\n", "") expectPrintedLower(t, "a { color: hwb(1deg 40% 80%) }", "a {\n color: #555555;\n}\n", "") expectPrintedLower(t, "a { color: hwb(1deg 9000% 50%) }", "a {\n color: #aaaaaa;\n}\n", "") expectPrintedLower(t, "a { color: hwb(1deg 9000% 50% / 0.6) }", "a {\n color: rgba(170, 170, 170, .6);\n}\n", "") expectPrintedLower(t, "a { color: hwb(90deg, 20%, 40%) }", "a {\n color: hwb(90deg, 20%, 40%);\n}\n", "") // This is invalid expectPrintedLower(t, "a { color: hwb(none 20% 40%) }", "a {\n color: hwb(none 20% 40%);\n}\n", "") // Interpolation expectPrintedLower(t, "a { color: hwb(90deg none 40%) }", "a {\n color: hwb(90deg none 40%);\n}\n", "") // Interpolation expectPrintedLower(t, "a { color: hwb(90deg 20% none) }", "a {\n color: hwb(90deg 20% none);\n}\n", "") // Interpolation expectPrintedMangle(t, "a { color: hwb(90deg 20% 40%) }", "a {\n color: #693;\n}\n", "") expectPrintedMangle(t, "a { color: hwb(0.75turn 20% 40% / 0.75) }", "a {\n color: #663399bf;\n}\n", "") expectPrintedLowerMangle(t, "a { color: hwb(90deg 20% 40%) }", "a {\n color: #693;\n}\n", "") expectPrintedLowerMangle(t, "a { color: hwb(0.75turn 20% 40% / 0.75) }", "a {\n color: rgba(102, 51, 153, .75);\n}\n", "") } func TestBackground(t *testing.T) { expectPrinted(t, "a { background: #11223344 }", "a {\n background: #11223344;\n}\n", "") expectPrintedMangle(t, "a { background: #11223344 }", "a {\n background: #1234;\n}\n", "") expectPrintedLower(t, "a { background: #11223344 }", "a {\n background: rgba(17, 34, 51, .267);\n}\n", "") expectPrinted(t, "a { background: border-box #11223344 }", "a {\n background: border-box #11223344;\n}\n", "") expectPrintedMangle(t, "a { background: border-box #11223344 }", "a {\n background: border-box #1234;\n}\n", "") expectPrintedLower(t, "a { background: border-box #11223344 }", "a {\n background: border-box rgba(17, 34, 51, .267);\n}\n", "") } func TestGradient(t *testing.T) { gradientKinds := []string{ "linear-gradient", "radial-gradient", "conic-gradient", "repeating-linear-gradient", "repeating-radial-gradient", "repeating-conic-gradient", } for _, gradient := range gradientKinds { var code string // Different properties expectPrinted(t, "a { background: "+gradient+"(red, blue) }", "a {\n background: "+gradient+"(red, blue);\n}\n", "") expectPrinted(t, "a { background-image: "+gradient+"(red, blue) }", "a {\n background-image: "+gradient+"(red, blue);\n}\n", "") expectPrinted(t, "a { border-image: "+gradient+"(red, blue) }", "a {\n border-image: "+gradient+"(red, blue);\n}\n", "") expectPrinted(t, "a { mask-image: "+gradient+"(red, blue) }", "a {\n mask-image: "+gradient+"(red, blue);\n}\n", "") // Basic code = "a { background: " + gradient + "(yellow, #11223344) }" expectPrinted(t, code, "a {\n background: "+gradient+"(yellow, #11223344);\n}\n", "") expectPrintedMangle(t, code, "a {\n background: "+gradient+"(#ff0, #1234);\n}\n", "") expectPrintedMinify(t, code, "a{background:"+gradient+"(yellow,#11223344)}", "") expectPrintedLowerUnsupported(t, compat.HexRGBA, code, "a {\n background: "+gradient+"(yellow, rgba(17, 34, 51, .267));\n}\n", "") // Basic with positions code = "a { background: " + gradient + "(yellow 10%, #11223344 90%) }" expectPrinted(t, code, "a {\n background: "+gradient+"(yellow 10%, #11223344 90%);\n}\n", "") expectPrintedMangle(t, code, "a {\n background: "+gradient+"(#ff0 10%, #1234 90%);\n}\n", "") expectPrintedMinify(t, code, "a{background:"+gradient+"(yellow 10%,#11223344 90%)}", "") expectPrintedLowerUnsupported(t, compat.HexRGBA, code, "a {\n background: "+gradient+"(yellow 10%, rgba(17, 34, 51, .267) 90%);\n}\n", "") // Basic with hints code = "a { background: " + gradient + "(yellow, 25%, #11223344) }" expectPrinted(t, code, "a {\n background:\n "+gradient+"(\n yellow,\n 25%,\n #11223344);\n}\n", "") expectPrintedMangle(t, code, "a {\n background:\n "+gradient+"(\n #ff0,\n 25%,\n #1234);\n}\n", "") expectPrintedMinify(t, code, "a{background:"+gradient+"(yellow,25%,#11223344)}", "") expectPrintedLowerUnsupported(t, compat.HexRGBA, code, "a {\n background:\n "+gradient+"(\n yellow,\n 25%,\n rgba(17, 34, 51, .267));\n}\n", "") expectPrintedLowerUnsupported(t, compat.GradientMidpoints, code, "a {\n background:\n "+gradient+"(\n #ffff00,\n #f2f303de,\n #eced04d0 6.25%,\n "+ "#e1e306bd 12.5%,\n #cdd00ba2 25%,\n #a2a8147b,\n #6873205d,\n #11223344);\n}\n", "") // Double positions code = "a { background: " + gradient + "(green, red 10%, red 20%, yellow 70% 80%, black) }" expectPrinted(t, code, "a {\n background:\n "+gradient+"(\n green,\n red 10%,\n "+ "red 20%,\n yellow 70% 80%,\n black);\n}\n", "") expectPrintedMangle(t, code, "a {\n background:\n "+gradient+"(\n green,\n "+ "red 10% 20%,\n #ff0 70% 80%,\n #000);\n}\n", "") expectPrintedMinify(t, code, "a{background:"+gradient+"(green,red 10%,red 20%,yellow 70% 80%,black)}", "") expectPrintedLowerUnsupported(t, compat.GradientDoublePosition, code, "a {\n background:\n "+gradient+"(\n green,\n red 10%,\n red 20%,\n "+ "yellow 70%,\n yellow 80%,\n black);\n}\n", "") // Double positions with hints code = "a { background: " + gradient + "(green, red 10%, red 20%, 30%, yellow 70% 80%, 85%, black) }" expectPrinted(t, code, "a {\n background:\n "+gradient+"(\n green,\n red 10%,\n red 20%,\n "+ "30%,\n yellow 70% 80%,\n 85%,\n black);\n}\n", "") expectPrintedMangle(t, code, "a {\n background:\n "+gradient+"(\n green,\n red 10% 20%,\n "+ "30%,\n #ff0 70% 80%,\n 85%,\n #000);\n}\n", "") expectPrintedMinify(t, code, "a{background:"+gradient+"(green,red 10%,red 20%,30%,yellow 70% 80%,85%,black)}", "") expectPrintedLowerUnsupported(t, compat.GradientDoublePosition, code, "a {\n background:\n "+gradient+"(\n green,\n red 10%,\n red 20%,\n 30%,\n "+ "yellow 70%,\n yellow 80%,\n 85%,\n black);\n}\n", "") // Non-double positions with hints code = "a { background: " + gradient + "(green, red 10%, 1%, red 20%, black) }" expectPrinted(t, code, "a {\n background:\n "+gradient+"(\n green,\n red 10%,\n 1%,\n "+ "red 20%,\n black);\n}\n", "") expectPrintedMangle(t, code, "a {\n background:\n "+gradient+"(\n green,\n red 10%,\n "+ "1%,\n red 20%,\n #000);\n}\n", "") expectPrintedMinify(t, code, "a{background:"+gradient+"(green,red 10%,1%,red 20%,black)}", "") expectPrintedLowerUnsupported(t, compat.GradientDoublePosition, code, "a {\n background:\n "+gradient+"(\n green,\n red 10%,\n 1%,\n red 20%,\n black);\n}\n", "") // Out-of-gamut colors code = "a { background: " + gradient + "(yellow, color(display-p3 1 0 0)) }" expectPrinted(t, code, "a {\n background: "+gradient+"(yellow, color(display-p3 1 0 0));\n}\n", "") expectPrintedMangle(t, code, "a {\n background: "+gradient+"(#ff0, color(display-p3 1 0 0));\n}\n", "") expectPrintedMinify(t, code, "a{background:"+gradient+"(yellow,color(display-p3 1 0 0))}", "") expectPrintedLowerUnsupported(t, compat.ColorFunctions, code, "a {\n background:\n "+gradient+"(\n #ffff00,\n #ffe971,\n #ffd472 25%,\n "+ "#ffab5f,\n #ff7b45 75%,\n #ff5e38 87.5%,\n #ff5534,\n #ff4c30,\n "+ "#ff412c,\n #ff0e0e);\n "+ "background:\n "+gradient+"(\n #ffff00,\n color(xyz 0.734 0.805 0.111),\n "+ "color(xyz 0.699 0.693 0.087) 25%,\n color(xyz 0.627 0.501 0.048),\n "+ "color(xyz 0.556 0.348 0.019) 75%,\n color(xyz 0.521 0.284 0.009) 87.5%,\n "+ "color(xyz 0.512 0.27 0.006),\n color(xyz 0.504 0.256 0.004),\n "+ "color(xyz 0.495 0.242 0.002),\n color(xyz 0.487 0.229 0));\n}\n", "") // Whitespace code = "a { background: " + gradient + "(color-mix(in lab,red,green)calc(1px)calc(2px),color-mix(in lab,blue,red)calc(98%)calc(99%)) }" expectPrinted(t, code, "a {\n background: "+gradient+ "(color-mix(in lab, red, green)calc(1px)calc(2px), color-mix(in lab, blue, red)calc(98%)calc(99%));\n}\n", "") expectPrintedMangle(t, code, "a {\n background: "+gradient+ "(color-mix(in lab, red, green) 1px 2px, color-mix(in lab, blue, red) 98% 99%);\n}\n", "") expectPrintedMinify(t, code, "a{background:"+gradient+ "(color-mix(in lab,red,green)calc(1px)calc(2px),color-mix(in lab,blue,red)calc(98%)calc(99%))}", "") expectPrintedLowerUnsupported(t, compat.GradientDoublePosition, code, "a {\n background:\n "+gradient+ "(\n color-mix(in lab, red, green) calc(1px),\n color-mix(in lab, red, green) calc(2px),"+ "\n color-mix(in lab, blue, red) calc(98%),\n color-mix(in lab, blue, red) calc(99%));\n}\n", "") expectPrintedLowerMangle(t, code, "a {\n background:\n "+gradient+ "(\n color-mix(in lab, red, green) 1px,\n color-mix(in lab, red, green) 2px,"+ "\n color-mix(in lab, blue, red) 98%,\n color-mix(in lab, blue, red) 99%);\n}\n", "") // Color space interpolation expectPrintedLowerUnsupported(t, compat.GradientInterpolation, "a { background: "+gradient+"(in srgb, red, green) }", "a {\n background: "+gradient+"(#ff0000, #008000);\n}\n", "") expectPrintedLowerUnsupported(t, compat.GradientInterpolation, "a { background: "+gradient+"(in srgb-linear, red, green) }", "a {\n background:\n "+gradient+"(\n #ff0000,\n #fb1300,\n #f81f00 6.25%,\n "+ "#f02e00 12.5%,\n #e14200 25%,\n #bc5c00,\n #897000 75%,\n #637800 87.5%,\n "+ "#477c00 93.75%,\n #317e00,\n #008000);\n}\n", "") expectPrintedLowerUnsupported(t, compat.GradientInterpolation, "a { background: "+gradient+"(in lab, red, green) }", "a {\n background:\n "+gradient+"(\n #ff0000,\n color(xyz 0.396 0.211 0.019),\n "+ "color(xyz 0.38 0.209 0.02) 6.25%,\n color(xyz 0.35 0.205 0.02) 12.5%,\n "+ "color(xyz 0.294 0.198 0.02) 25%,\n color(xyz 0.2 0.183 0.022),\n "+ "color(xyz 0.129 0.168 0.024) 75%,\n color(xyz 0.101 0.161 0.025) 87.5%,\n "+ "color(xyz 0.089 0.158 0.025) 93.75%,\n color(xyz 0.083 0.156 0.025),\n #008000);\n}\n", "") // Hue interpolation expectPrintedLowerUnsupported(t, compat.GradientInterpolation, "a { background: "+gradient+"(in hsl shorter hue, red, green) }", "a {\n background:\n "+gradient+"(\n #ff0000,\n #df7000,\n "+ "#bfbf00,\n #50a000,\n #008000);\n}\n", "") expectPrintedLowerUnsupported(t, compat.GradientInterpolation, "a { background: "+gradient+"(in hsl longer hue, red, green) }", "a {\n background:\n "+gradient+"(\n #ff0000,\n #ef0078,\n "+ "#df00df,\n #6800cf,\n #0000c0,\n #0058b0,\n "+ "#00a0a0,\n #009048,\n #008000);\n}\n", "") } } func TestDeclaration(t *testing.T) { expectPrinted(t, ".decl {}", ".decl {\n}\n", "") expectPrinted(t, ".decl { a: b }", ".decl {\n a: b;\n}\n", "") expectPrinted(t, ".decl { a: b; }", ".decl {\n a: b;\n}\n", "") expectPrinted(t, ".decl { a: b; c: d }", ".decl {\n a: b;\n c: d;\n}\n", "") expectPrinted(t, ".decl { a: b; c: d; }", ".decl {\n a: b;\n c: d;\n}\n", "") expectPrinted(t, ".decl { a { b: c; } }", ".decl {\n a {\n b: c;\n }\n}\n", "") expectPrinted(t, ".decl { & a { b: c; } }", ".decl {\n & a {\n b: c;\n }\n}\n", "") // See path_to_url expectPrinted(t, ".selector { (;property: value;); }", ".selector {\n (;property: value;);\n}\n", "<stdin>: WARNING: Expected identifier but found \"(\"\n") expectPrinted(t, ".selector { [;property: value;]; }", ".selector {\n [;property: value;];\n}\n", "<stdin>: WARNING: Expected identifier but found \"[\"\n") expectPrinted(t, ".selector, {}", ".selector, {\n}\n", "<stdin>: WARNING: Unexpected \"{\"\n") expectPrinted(t, ".selector\\ {}", ".selector\\ {\n}\n", "") expectPrinted(t, ".selector { property: value\\9; }", ".selector {\n property: value\\\t;\n}\n", "") expectPrinted(t, "@media \\0screen\\,screen\\9 {}", "@media \uFFFDscreen\\,screen\\\t {\n}\n", "") } func TestSelector(t *testing.T) { expectPrinted(t, "a{}", "a {\n}\n", "") expectPrinted(t, "a {}", "a {\n}\n", "") expectPrinted(t, "a b {}", "a b {\n}\n", "") expectPrinted(t, "a/**/b {}", "ab {\n}\n", "<stdin>: WARNING: Unexpected \"b\"\n") expectPrinted(t, "a/**/.b {}", "a.b {\n}\n", "") expectPrinted(t, "a/**/:b {}", "a:b {\n}\n", "") expectPrinted(t, "a/**/[b] {}", "a[b] {\n}\n", "") expectPrinted(t, "a>/**/b {}", "a > b {\n}\n", "") expectPrinted(t, "a+/**/b {}", "a + b {\n}\n", "") expectPrinted(t, "a~/**/b {}", "a ~ b {\n}\n", "") expectPrinted(t, "[b]{}", "[b] {\n}\n", "") expectPrinted(t, "[b] {}", "[b] {\n}\n", "") expectPrinted(t, "a[b] {}", "a[b] {\n}\n", "") expectPrinted(t, "a [b] {}", "a [b] {\n}\n", "") expectPrinted(t, "[] {}", "[] {\n}\n", "<stdin>: WARNING: Expected identifier but found \"]\"\n") expectPrinted(t, "[b {}", "[b] {\n}\n", "<stdin>: WARNING: Expected \"]\" to go with \"[\"\n<stdin>: NOTE: The unbalanced \"[\" is here:\n") expectPrinted(t, "[b]] {}", "[b]] {\n}\n", "<stdin>: WARNING: Unexpected \"]\"\n") expectPrinted(t, "a[b {}", "a[b] {\n}\n", "<stdin>: WARNING: Expected \"]\" to go with \"[\"\n<stdin>: NOTE: The unbalanced \"[\" is here:\n") expectPrinted(t, "a[b]] {}", "a[b]] {\n}\n", "<stdin>: WARNING: Unexpected \"]\"\n") expectPrinted(t, "[b]a {}", "[b]a {\n}\n", "<stdin>: WARNING: Unexpected \"a\"\n") expectPrinted(t, "[|b]{}", "[b] {\n}\n", "") // "[|b]" is equivalent to "[b]" expectPrinted(t, "[*|b]{}", "[*|b] {\n}\n", "") expectPrinted(t, "[a|b]{}", "[a|b] {\n}\n", "") expectPrinted(t, "[a|b|=\"c\"]{}", "[a|b|=c] {\n}\n", "") expectPrinted(t, "[a|b |= \"c\"]{}", "[a|b|=c] {\n}\n", "") expectPrinted(t, "[a||b] {}", "[a||b] {\n}\n", "<stdin>: WARNING: Expected identifier but found \"|\"\n") expectPrinted(t, "[* | b] {}", "[* | b] {\n}\n", "<stdin>: WARNING: Expected \"|\" but found whitespace\n") expectPrinted(t, "[a | b] {}", "[a | b] {\n}\n", "<stdin>: WARNING: Expected \"=\" but found whitespace\n") expectPrinted(t, "[b=\"c\"] {}", "[b=c] {\n}\n", "") expectPrinted(t, "[b=\"c d\"] {}", "[b=\"c d\"] {\n}\n", "") expectPrinted(t, "[b=\"0c\"] {}", "[b=\"0c\"] {\n}\n", "") expectPrinted(t, "[b~=\"c\"] {}", "[b~=c] {\n}\n", "") expectPrinted(t, "[b^=\"c\"] {}", "[b^=c] {\n}\n", "") expectPrinted(t, "[b$=\"c\"] {}", "[b$=c] {\n}\n", "") expectPrinted(t, "[b*=\"c\"] {}", "[b*=c] {\n}\n", "") expectPrinted(t, "[b|=\"c\"] {}", "[b|=c] {\n}\n", "") expectPrinted(t, "[b?=\"c\"] {}", "[b?=\"c\"] {\n}\n", "<stdin>: WARNING: Expected \"]\" to go with \"[\"\n<stdin>: NOTE: The unbalanced \"[\" is here:\n") expectPrinted(t, "[b = \"c\"] {}", "[b=c] {\n}\n", "") expectPrinted(t, "[b ~= \"c\"] {}", "[b~=c] {\n}\n", "") expectPrinted(t, "[b ^= \"c\"] {}", "[b^=c] {\n}\n", "") expectPrinted(t, "[b $= \"c\"] {}", "[b$=c] {\n}\n", "") expectPrinted(t, "[b *= \"c\"] {}", "[b*=c] {\n}\n", "") expectPrinted(t, "[b |= \"c\"] {}", "[b|=c] {\n}\n", "") expectPrinted(t, "[b ?= \"c\"] {}", "[b ?= \"c\"] {\n}\n", "<stdin>: WARNING: Expected \"]\" to go with \"[\"\n<stdin>: NOTE: The unbalanced \"[\" is here:\n") expectPrinted(t, "[b = \"c\" i] {}", "[b=c i] {\n}\n", "") expectPrinted(t, "[b = \"c\" I] {}", "[b=c I] {\n}\n", "") expectPrinted(t, "[b = \"c\" s] {}", "[b=c s] {\n}\n", "") expectPrinted(t, "[b = \"c\" S] {}", "[b=c S] {\n}\n", "") expectPrinted(t, "[b i] {}", "[b i] {\n}\n", "<stdin>: WARNING: Expected \"]\" to go with \"[\"\n<stdin>: NOTE: The unbalanced \"[\" is here:\n") expectPrinted(t, "[b I] {}", "[b I] {\n}\n", "<stdin>: WARNING: Expected \"]\" to go with \"[\"\n<stdin>: NOTE: The unbalanced \"[\" is here:\n") expectPrinted(t, "[b s] {}", "[b s] {\n}\n", "<stdin>: WARNING: Expected \"]\" to go with \"[\"\n<stdin>: NOTE: The unbalanced \"[\" is here:\n") expectPrinted(t, "[b S] {}", "[b S] {\n}\n", "<stdin>: WARNING: Expected \"]\" to go with \"[\"\n<stdin>: NOTE: The unbalanced \"[\" is here:\n") expectPrinted(t, "|b {}", "|b {\n}\n", "") expectPrinted(t, "|* {}", "|* {\n}\n", "") expectPrinted(t, "a|b {}", "a|b {\n}\n", "") expectPrinted(t, "a|* {}", "a|* {\n}\n", "") expectPrinted(t, "*|b {}", "*|b {\n}\n", "") expectPrinted(t, "*|* {}", "*|* {\n}\n", "") expectPrinted(t, "a||b {}", "a||b {\n}\n", "<stdin>: WARNING: Expected identifier but found \"|\"\n") expectPrinted(t, "a+b {}", "a + b {\n}\n", "") expectPrinted(t, "a>b {}", "a > b {\n}\n", "") expectPrinted(t, "a+b {}", "a + b {\n}\n", "") expectPrinted(t, "a~b {}", "a ~ b {\n}\n", "") expectPrinted(t, "a + b {}", "a + b {\n}\n", "") expectPrinted(t, "a > b {}", "a > b {\n}\n", "") expectPrinted(t, "a + b {}", "a + b {\n}\n", "") expectPrinted(t, "a ~ b {}", "a ~ b {\n}\n", "") expectPrinted(t, "::b {}", "::b {\n}\n", "") expectPrinted(t, "*::b {}", "*::b {\n}\n", "") expectPrinted(t, "a::b {}", "a::b {\n}\n", "") expectPrinted(t, "::b(c) {}", "::b(c) {\n}\n", "") expectPrinted(t, "*::b(c) {}", "*::b(c) {\n}\n", "") expectPrinted(t, "a::b(c) {}", "a::b(c) {\n}\n", "") expectPrinted(t, "a:b:c {}", "a:b:c {\n}\n", "") expectPrinted(t, "a:b(:c) {}", "a:b(:c) {\n}\n", "") expectPrinted(t, "a: b {}", "a: b {\n}\n", "<stdin>: WARNING: Expected identifier but found whitespace\n") expectPrinted(t, ":is(a)b {}", ":is(a)b {\n}\n", "<stdin>: WARNING: Unexpected \"b\"\n") expectPrinted(t, "a:b( c ) {}", "a:b(c) {\n}\n", "") expectPrinted(t, "a:b( c , d ) {}", "a:b(c, d) {\n}\n", "") expectPrinted(t, "a:is( c ) {}", "a:is(c) {\n}\n", "") expectPrinted(t, "a:is( c , d ) {}", "a:is(c, d) {\n}\n", "") // These test cases previously caused a hang (see path_to_url expectPrinted(t, ":x(", ":x() {\n}\n", "<stdin>: WARNING: Unexpected end of file\n") expectPrinted(t, ":x( {}", ":x({}) {\n}\n", "<stdin>: WARNING: Expected \")\" to go with \"(\"\n<stdin>: NOTE: The unbalanced \"(\" is here:\n") expectPrinted(t, ":x(, :y() {}", ":x(, :y() {}) {\n}\n", "<stdin>: WARNING: Expected \")\" to go with \"(\"\n<stdin>: NOTE: The unbalanced \"(\" is here:\n") expectPrinted(t, "#id {}", "#id {\n}\n", "") expectPrinted(t, "#--0 {}", "#--0 {\n}\n", "") expectPrinted(t, "#\\-0 {}", "#\\-0 {\n}\n", "") expectPrinted(t, "#\\30 {}", "#\\30 {\n}\n", "") expectPrinted(t, "div#id {}", "div#id {\n}\n", "") expectPrinted(t, "div#--0 {}", "div#--0 {\n}\n", "") expectPrinted(t, "div#\\-0 {}", "div#\\-0 {\n}\n", "") expectPrinted(t, "div#\\30 {}", "div#\\30 {\n}\n", "") expectPrinted(t, "#0 {}", "#0 {\n}\n", "<stdin>: WARNING: Unexpected \"#0\"\n") expectPrinted(t, "#-0 {}", "#-0 {\n}\n", "<stdin>: WARNING: Unexpected \"#-0\"\n") expectPrinted(t, "div#0 {}", "div#0 {\n}\n", "<stdin>: WARNING: Unexpected \"#0\"\n") expectPrinted(t, "div#-0 {}", "div#-0 {\n}\n", "<stdin>: WARNING: Unexpected \"#-0\"\n") expectPrinted(t, "div::before::after::selection::first-line::first-letter {color:red}", "div::before::after::selection::first-line::first-letter {\n color: red;\n}\n", "") expectPrintedMangle(t, "div::before::after::selection::first-line::first-letter {color:red}", "div:before:after::selection:first-line:first-letter {\n color: red;\n}\n", "") // Make sure '-' and '\\' consume an ident-like token instead of a name expectPrinted(t, "_:-ms-lang(x) {}", "_:-ms-lang(x) {\n}\n", "") expectPrinted(t, "_:\\ms-lang(x) {}", "_:ms-lang(x) {\n}\n", "") expectPrinted(t, ":local(a, b) {}", ":local(a, b) {\n}\n", "<stdin>: WARNING: Unexpected \",\" inside \":local(...)\"\n"+ "NOTE: Different CSS tools behave differently in this case, so esbuild doesn't allow it. Either remove "+ "this comma or split this selector up into multiple comma-separated \":local(...)\" selectors instead.\n") expectPrinted(t, ":global(a, b) {}", ":global(a, b) {\n}\n", "<stdin>: WARNING: Unexpected \",\" inside \":global(...)\"\n"+ "NOTE: Different CSS tools behave differently in this case, so esbuild doesn't allow it. Either remove "+ "this comma or split this selector up into multiple comma-separated \":global(...)\" selectors instead.\n") } func TestNestedSelector(t *testing.T) { sassWarningWrap := "NOTE: CSS nesting syntax does not allow the \"&\" selector to come before " + "a type selector. You can wrap this selector in \":is(...)\" as a workaround. " + "This restriction exists to avoid problems with SASS nesting, where the same syntax " + "means something very different that has no equivalent in real CSS (appending a suffix to the parent selector).\n" sassWarningMove := "NOTE: CSS nesting syntax does not allow the \"&\" selector to come before " + "a type selector. You can move the \"&\" to the end of this selector as a workaround. " + "This restriction exists to avoid problems with SASS nesting, where the same syntax " + "means something very different that has no equivalent in real CSS (appending a suffix to the parent selector).\n" expectPrinted(t, "& {}", "& {\n}\n", "") expectPrinted(t, "& b {}", "& b {\n}\n", "") expectPrinted(t, "&:b {}", "&:b {\n}\n", "") expectPrinted(t, "&* {}", "&* {\n}\n", "<stdin>: WARNING: Cannot use type selector \"*\" directly after nesting selector \"&\"\n"+sassWarningWrap) expectPrinted(t, "&|b {}", "&|b {\n}\n", "<stdin>: WARNING: Cannot use type selector \"|b\" directly after nesting selector \"&\"\n"+sassWarningWrap) expectPrinted(t, "&*|b {}", "&*|b {\n}\n", "<stdin>: WARNING: Cannot use type selector \"*|b\" directly after nesting selector \"&\"\n"+sassWarningWrap) expectPrinted(t, "&a|b {}", "&a|b {\n}\n", "<stdin>: WARNING: Cannot use type selector \"a|b\" directly after nesting selector \"&\"\n"+sassWarningWrap) expectPrinted(t, "&[a] {}", "&[a] {\n}\n", "") expectPrinted(t, "a { & {} }", "a {\n & {\n }\n}\n", "") expectPrinted(t, "a { & b {} }", "a {\n & b {\n }\n}\n", "") expectPrinted(t, "a { &:b {} }", "a {\n &:b {\n }\n}\n", "") expectPrinted(t, "a { &* {} }", "a {\n &* {\n }\n}\n", "<stdin>: WARNING: Cannot use type selector \"*\" directly after nesting selector \"&\"\n"+sassWarningWrap) expectPrinted(t, "a { &|b {} }", "a {\n &|b {\n }\n}\n", "<stdin>: WARNING: Cannot use type selector \"|b\" directly after nesting selector \"&\"\n"+sassWarningWrap) expectPrinted(t, "a { &*|b {} }", "a {\n &*|b {\n }\n}\n", "<stdin>: WARNING: Cannot use type selector \"*|b\" directly after nesting selector \"&\"\n"+sassWarningWrap) expectPrinted(t, "a { &a|b {} }", "a {\n &a|b {\n }\n}\n", "<stdin>: WARNING: Cannot use type selector \"a|b\" directly after nesting selector \"&\"\n"+sassWarningWrap) expectPrinted(t, "a { &[b] {} }", "a {\n &[b] {\n }\n}\n", "") expectPrinted(t, "a { && {} }", "a {\n & {\n }\n}\n", "") expectPrinted(t, "a { & + & {} }", "a {\n & + & {\n }\n}\n", "") expectPrinted(t, "a { & > & {} }", "a {\n & > & {\n }\n}\n", "") expectPrinted(t, "a { & ~ & {} }", "a {\n & ~ & {\n }\n}\n", "") expectPrinted(t, "a { & + c& {} }", "a {\n & + c& {\n }\n}\n", "") expectPrinted(t, "a { .b& + & {} }", "a {\n &.b + & {\n }\n}\n", "") expectPrinted(t, "a { .b& + c& {} }", "a {\n &.b + c& {\n }\n}\n", "") expectPrinted(t, "a { & + & > & ~ & {} }", "a {\n & + & > & ~ & {\n }\n}\n", "") // CSS nesting works for all tokens except identifiers and functions expectPrinted(t, "a { .b {} }", "a {\n .b {\n }\n}\n", "") expectPrinted(t, "a { #b {} }", "a {\n #b {\n }\n}\n", "") expectPrinted(t, "a { :b {} }", "a {\n :b {\n }\n}\n", "") expectPrinted(t, "a { [b] {} }", "a {\n [b] {\n }\n}\n", "") expectPrinted(t, "a { * {} }", "a {\n * {\n }\n}\n", "") expectPrinted(t, "a { |b {} }", "a {\n |b {\n }\n}\n", "") expectPrinted(t, "a { >b {} }", "a {\n > b {\n }\n}\n", "") expectPrinted(t, "a { +b {} }", "a {\n + b {\n }\n}\n", "") expectPrinted(t, "a { ~b {} }", "a {\n ~ b {\n }\n}\n", "") expectPrinted(t, "a { b {} }", "a {\n b {\n }\n}\n", "") expectPrinted(t, "a { b() {} }", "a {\n b() {\n }\n}\n", "<stdin>: WARNING: Unexpected \"b(\"\n") // Note: CSS nesting no longer requires each complex selector to contain "&" expectPrinted(t, "a { & b, c {} }", "a {\n & b,\n c {\n }\n}\n", "") expectPrinted(t, "a { & b, & c {} }", "a {\n & b,\n & c {\n }\n}\n", "") // Note: CSS nesting no longer requires the rule to be nested inside a parent // (instead un-nested CSS nesting refers to ":scope" or to ":root") expectPrinted(t, "& b, c {}", "& b,\nc {\n}\n", "") expectPrinted(t, "& b, & c {}", "& b,\n& c {\n}\n", "") expectPrinted(t, "b & {}", "b & {\n}\n", "") expectPrinted(t, "b &, c {}", "b &,\nc {\n}\n", "") expectPrinted(t, "a { .b & { color: red } }", "a {\n .b & {\n color: red;\n }\n}\n", "") expectPrinted(t, "a { .b& { color: red } }", "a {\n &.b {\n color: red;\n }\n}\n", "") expectPrinted(t, "a { .b&[c] { color: red } }", "a {\n &.b[c] {\n color: red;\n }\n}\n", "") expectPrinted(t, "a { &[c] { color: red } }", "a {\n &[c] {\n color: red;\n }\n}\n", "") expectPrinted(t, "a { [c]& { color: red } }", "a {\n &[c] {\n color: red;\n }\n}\n", "") expectPrintedMinify(t, "a { .b & { color: red } }", "a{.b &{color:red}}", "") expectPrintedMinify(t, "a { .b& { color: red } }", "a{&.b{color:red}}", "") // Nested at-rules expectPrinted(t, "a { @media screen { color: red } }", "a {\n @media screen {\n color: red;\n }\n}\n", "") expectPrinted(t, "a { @media screen { .b { color: green } color: red } }", "a {\n @media screen {\n .b {\n color: green;\n }\n color: red;\n }\n}\n", "") expectPrinted(t, "a { @media screen { color: red; .b { color: green } } }", "a {\n @media screen {\n color: red;\n .b {\n color: green;\n }\n }\n}\n", "") expectPrinted(t, "html { @layer base { block-size: 100%; @layer support { & body { min-block-size: 100%; } } } }", "html {\n @layer base {\n block-size: 100%;\n @layer support {\n & body {\n min-block-size: 100%;\n }\n }\n }\n}\n", "") expectPrinted(t, ".card { aspect-ratio: 3/4; @scope (&) { :scope { border: 1px solid white } } }", ".card {\n aspect-ratio: 3/4;\n @scope (&) {\n :scope {\n border: 1px solid white;\n }\n }\n}\n", "") // Minify an implicit leading "&" expectPrintedMangle(t, "& { color: red }", "& {\n color: red;\n}\n", "") expectPrintedMangle(t, "& a { color: red }", "a {\n color: red;\n}\n", "") expectPrintedMangle(t, "& a, & b { color: red }", "a,\nb {\n color: red;\n}\n", "") expectPrintedMangle(t, "& a, b { color: red }", "a,\nb {\n color: red;\n}\n", "") expectPrintedMangle(t, "a, & b { color: red }", "a,\nb {\n color: red;\n}\n", "") expectPrintedMangle(t, "& &a { color: red }", "& &a {\n color: red;\n}\n", "<stdin>: WARNING: Cannot use type selector \"a\" directly after nesting selector \"&\"\n"+sassWarningMove) expectPrintedMangle(t, "& .x { color: red }", ".x {\n color: red;\n}\n", "") expectPrintedMangle(t, "& &.x { color: red }", "& &.x {\n color: red;\n}\n", "") expectPrintedMangle(t, "& + a { color: red }", "+ a {\n color: red;\n}\n", "") expectPrintedMangle(t, "& + a& { color: red }", "+ a& {\n color: red;\n}\n", "") expectPrintedMangle(t, "&.x { color: red }", "&.x {\n color: red;\n}\n", "") expectPrintedMangle(t, "a & { color: red }", "a & {\n color: red;\n}\n", "") expectPrintedMangle(t, ".x & { color: red }", ".x & {\n color: red;\n}\n", "") expectPrintedMangle(t, "div { & a { color: red } }", "div {\n & a {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div { & .x { color: red } }", "div {\n .x {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div { & .x, & a { color: red } }", "div {\n .x,\n a {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div { .x, & a { color: red } }", "div {\n .x,\n a {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div { & a& { color: red } }", "div {\n & a& {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div { & .x { color: red } }", "div {\n .x {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div { & &.x { color: red } }", "div {\n & &.x {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div { & + a { color: red } }", "div {\n + a {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div { & + a& { color: red } }", "div {\n + a& {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div { .x & { color: red } }", "div {\n .x & {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "@media screen { & div { color: red } }", "@media screen {\n div {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "a { @media screen { & div { color: red } } }", "a {\n @media screen {\n & div {\n color: red;\n }\n }\n}\n", "") // Reorder selectors to enable removing "&" expectPrintedMangle(t, "reorder { & first, .second { color: red } }", "reorder {\n .second,\n first {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "reorder { & first, & .second { color: red } }", "reorder {\n .second,\n first {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "reorder { & first, #second { color: red } }", "reorder {\n #second,\n first {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "reorder { & first, [second] { color: red } }", "reorder {\n [second],\n first {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "reorder { & first, :second { color: red } }", "reorder {\n :second,\n first {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "reorder { & first, + second { color: red } }", "reorder {\n + second,\n first {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "reorder { & first, ~ second { color: red } }", "reorder {\n ~ second,\n first {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "reorder { & first, > second { color: red } }", "reorder {\n > second,\n first {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "reorder { & first, second, .third { color: red } }", "reorder {\n .third,\n second,\n first {\n color: red;\n }\n}\n", "") // Inline no-op nesting expectPrintedMangle(t, "div { & { color: red } }", "div {\n color: red;\n}\n", "") expectPrintedMangle(t, "div { && { color: red } }", "div {\n color: red;\n}\n", "") expectPrintedMangle(t, "div { zoom: 2; & { color: red } }", "div {\n zoom: 2;\n color: red;\n}\n", "") expectPrintedMangle(t, "div { zoom: 2; && { color: red } }", "div {\n zoom: 2;\n color: red;\n}\n", "") expectPrintedMangle(t, "div { &, && { color: red } zoom: 2 }", "div {\n zoom: 2;\n color: red;\n}\n", "") expectPrintedMangle(t, "div { &&, & { color: red } zoom: 2 }", "div {\n zoom: 2;\n color: red;\n}\n", "") expectPrintedMangle(t, "div { a: 1; & { b: 4 } b: 2; && { c: 5 } c: 3 }", "div {\n a: 1;\n b: 2;\n c: 3;\n b: 4;\n c: 5;\n}\n", "") expectPrintedMangle(t, "div { .b { x: 1 } & { x: 2 } }", "div {\n .b {\n x: 1;\n }\n x: 2;\n}\n", "") expectPrintedMangle(t, "div { & { & { & { color: red } } & { & { zoom: 2 } } } }", "div {\n color: red;\n zoom: 2;\n}\n", "") // Cannot inline no-op nesting with pseudo-elements (path_to_url expectPrintedMangle(t, "div, span:hover { & { color: red } }", "div,\nspan:hover {\n color: red;\n}\n", "") expectPrintedMangle(t, "div, span::before { & { color: red } }", "div,\nspan:before {\n & {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div, span:before { & { color: red } }", "div,\nspan:before {\n & {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div, span::after { & { color: red } }", "div,\nspan:after {\n & {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div, span:after { & { color: red } }", "div,\nspan:after {\n & {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div, span::first-line { & { color: red } }", "div,\nspan:first-line {\n & {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div, span:first-line { & { color: red } }", "div,\nspan:first-line {\n & {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div, span::first-letter { & { color: red } }", "div,\nspan:first-letter {\n & {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div, span:first-letter { & { color: red } }", "div,\nspan:first-letter {\n & {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div, span::pseudo { & { color: red } }", "div,\nspan::pseudo {\n & {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div, span:hover { @layer foo { & { color: red } } }", "div,\nspan:hover {\n @layer foo {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div, span:hover { @media screen { & { color: red } } }", "div,\nspan:hover {\n @media screen {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "div, span::pseudo { @layer foo { & { color: red } } }", "div,\nspan::pseudo {\n @layer foo {\n & {\n color: red;\n }\n }\n}\n", "") expectPrintedMangle(t, "div, span::pseudo { @media screen { & { color: red } } }", "div,\nspan::pseudo {\n @media screen {\n & {\n color: red;\n }\n }\n}\n", "") // Lowering tests for nesting nestingWarningIs := "<stdin>: WARNING: Transforming this CSS nesting syntax is not supported in the configured target environment\n" + "NOTE: The nesting transform for this case must generate an \":is(...)\" but the configured target environment does not support the \":is\" pseudo-class.\n" nesting := compat.Nesting everything := ^compat.CSSFeature(0) expectPrintedLowerUnsupported(t, nesting, ".foo { .bar { color: red } }", ".foo .bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo { &.bar { color: red } }", ".foo.bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo { & .bar { color: red } }", ".foo .bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo .bar { .baz { color: red } }", ".foo .bar .baz {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo .bar { &.baz { color: red } }", ".foo .bar.baz {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo .bar { & .baz { color: red } }", ".foo .bar .baz {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo .bar { & > .baz { color: red } }", ".foo .bar > .baz {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo .bar { .baz & { color: red } }", ".baz :is(.foo .bar) {\n color: red;\n}\n", "") // NOT the same as ".baz .foo .bar expectPrintedLowerUnsupported(t, nesting, ".foo .bar { & .baz & { color: red } }", ".foo .bar .baz :is(.foo .bar) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo, .bar { .baz & { color: red } }", ".baz :is(.foo, .bar) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".foo, .bar { .baz & { color: red } }", ".baz .foo,\n.baz .bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo, [bar~='abc'] { .baz { color: red } }", ":is(.foo, [bar~=abc]) .baz {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".foo, [bar~='abc'] { .baz { color: red } }", ".foo .baz,\n[bar~=abc] .baz {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo, [bar~='a b c'] { .baz { color: red } }", ":is(.foo, [bar~=\"a b c\"]) .baz {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".foo, [bar~='a b c'] { .baz { color: red } }", ".foo .baz,\n[bar~=\"a b c\"] .baz {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".baz { .foo, .bar { color: red } }", ".baz :is(.foo, .bar) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".baz { .foo, .bar { color: red } }", ".baz .foo,\n.baz .bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".baz { .foo, & .bar { color: red } }", ".baz :is(.foo, .bar) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".baz { .foo, & .bar { color: red } }", ".baz .foo,\n.baz .bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".baz { & .foo, .bar { color: red } }", ".baz :is(.foo, .bar) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".baz { & .foo, .bar { color: red } }", ".baz .foo,\n.baz .bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".baz { & .foo, & .bar { color: red } }", ".baz :is(.foo, .bar) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".baz { & .foo, & .bar { color: red } }", ".baz .foo,\n.baz .bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".baz { .foo, &.bar { color: red } }", ".baz .foo,\n.baz.bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".baz { &.foo, .bar { color: red } }", ".baz.foo,\n.baz .bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".baz { &.foo, &.bar { color: red } }", ".baz:is(.foo, .bar) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".baz { &.foo, &.bar { color: red } }", ".baz.foo,\n.baz.bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo { color: blue; & .bar { color: red } }", ".foo {\n color: blue;\n}\n.foo .bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo { & .bar { color: red } color: blue }", ".foo {\n color: blue;\n}\n.foo .bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo { color: blue; & .bar { color: red } zoom: 2 }", ".foo {\n color: blue;\n zoom: 2;\n}\n.foo .bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".a, .b { .c, .d { color: red } }", ":is(.a, .b) :is(.c, .d) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".a, .b { .c, .d { color: red } }", ".a .c,\n.a .d,\n.b .c,\n.b .d {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".a, .b { & > & { color: red } }", ":is(.a, .b) > :is(.a, .b) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".a, .b { & > & { color: red } }", ".a > .a,\n.a > .b,\n.b > .a,\n.b > .b {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".a { color: red; > .b { color: green; > .c { color: blue } } }", ".a {\n color: red;\n}\n.a > .b {\n color: green;\n}\n.a > .b > .c {\n color: blue;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "> .a { color: red; > .b { color: green; > .c { color: blue } } }", "> .a {\n color: red;\n}\n> .a > .b {\n color: green;\n}\n> .a > .b > .c {\n color: blue;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo, .bar, .foo:before, .bar:after { &:hover { color: red } }", ":is(.foo, .bar):hover {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".foo, .bar, .foo:before, .bar:after { &:hover { color: red } }", ".foo:hover,\n.bar:hover {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo, .bar:before { &:hover { color: red } }", ".foo:hover {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo, .bar:before { :hover & { color: red } }", ":hover .foo {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".bar:before { &:hover { color: red } }", ":is():hover {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".bar:before { :hover & { color: red } }", ":hover :is() {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo { &:after, & .bar { color: red } }", ".foo:after,\n.foo .bar {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo { & .bar, &:after { color: red } }", ".foo .bar,\n.foo:after {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".xy { :where(&.foo) { color: red } }", ":where(.xy.foo) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "div { :where(&.foo) { color: red } }", ":where(div.foo) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".xy { :where(.foo&) { color: red } }", ":where(.xy.foo) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "div { :where(.foo&) { color: red } }", ":where(div.foo) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".xy { :where([href]&) { color: red } }", ":where(.xy[href]) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "div { :where([href]&) { color: red } }", ":where(div[href]) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".xy { :where(:hover&) { color: red } }", ":where(.xy:hover) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "div { :where(:hover&) { color: red } }", ":where(div:hover) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".xy { :where(:is(.foo)&) { color: red } }", ":where(.xy:is(.foo)) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "div { :where(:is(.foo)&) { color: red } }", ":where(div:is(.foo)) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".xy { :where(.foo + &) { color: red } }", ":where(.foo + .xy) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "div { :where(.foo + &) { color: red } }", ":where(.foo + div) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".xy { :where(&, span:is(.foo &)) { color: red } }", ":where(.xy, span:is(.foo .xy)) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "div { :where(&, span:is(.foo &)) { color: red } }", ":where(div, span:is(.foo div)) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "&, a { color: red }", ":scope,\na {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "&, a { .b { color: red } }", ":is(:scope, a) .b {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, "&, a { .b { color: red } }", ":scope .b,\na .b {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "&, a { .b { .c { color: red } } }", ":is(:scope, a) .b .c {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, "&, a { .b { .c { color: red } } }", ":scope .b .c,\na .b .c {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "a { > b, > c { color: red } }", "a > :is(b, c) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, "a { > b, > c { color: red } }", "a > b,\na > c {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "a { > b, + c { color: red } }", "a > b,\na + c {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "a { & > b, & > c { color: red } }", "a > :is(b, c) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, "a { & > b, & > c { color: red } }", "a > b,\na > c {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "a { & > b, & + c { color: red } }", "a > b,\na + c {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "a { > b&, > c& { color: red } }", "a > :is(a:is(b), a:is(c)) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, "a { > b&, > c& { color: red } }", "a > a:is(b),\na > a:is(c) {\n color: red;\n}\n", nestingWarningIs+nestingWarningIs) expectPrintedLowerUnsupported(t, nesting, "a { > b&, + c& { color: red } }", "a > a:is(b),\na + a:is(c) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "a { > &.b, > &.c { color: red } }", "a > :is(a.b, a.c) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, "a { > &.b, > &.c { color: red } }", "a > a.b,\na > a.c {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "a { > &.b, + &.c { color: red } }", "a > a.b,\na + a.c {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".a { > b&, > c& { color: red } }", ".a > :is(b.a, c.a) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".a { > b&, > c& { color: red } }", ".a > b.a,\n.a > c.a {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".a { > b&, + c& { color: red } }", ".a > b.a,\n.a + c.a {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".a { > &.b, > &.c { color: red } }", ".a > :is(.a.b, .a.c) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".a { > &.b, > &.c { color: red } }", ".a > .a.b,\n.a > .a.c {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".a { > &.b, + &.c { color: red } }", ".a > .a.b,\n.a + .a.c {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "~ .a { > &.b, > &.c { color: red } }", "~ .a > :is(.a.b, .a.c) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, "~ .a { > &.b, > &.c { color: red } }", "~ .a > .a.b,\n~ .a > .a.c {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, "~ .a { > &.b, + &.c { color: red } }", "~ .a > .a.b,\n~ .a + .a.c {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".foo .bar { > &.a, > &.b { color: red } }", ".foo .bar > :is(.foo .bar.a, .foo .bar.b) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, everything, ".foo .bar { > &.a, > &.b { color: red } }", ".foo .bar > :is(.foo .bar).a,\n.foo .bar > :is(.foo .bar).b {\n color: red;\n}\n", nestingWarningIs+nestingWarningIs) expectPrintedLowerUnsupported(t, nesting, ".foo .bar { > &.a, + &.b { color: red } }", ".foo .bar > :is(.foo .bar).a,\n.foo .bar + :is(.foo .bar).b {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".demo { .lg { &.triangle, &.circle { color: red } } }", ".demo .lg:is(.triangle, .circle) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".demo { .lg { .triangle, .circle { color: red } } }", ".demo .lg :is(.triangle, .circle) {\n color: red;\n}\n", "") expectPrintedLowerUnsupported(t, nesting, ".card { .featured & & & { color: red } }", ".featured .card .card .card {\n color: red;\n}\n", "") // These are invalid SASS-style nested suffixes expectPrintedLower(t, ".card { &--header { color: red } }", ".card {\n &--header {\n color: red;\n }\n}\n", "<stdin>: WARNING: Cannot use type selector \"--header\" directly after nesting selector \"&\"\n"+sassWarningWrap) expectPrintedLower(t, ".card { &__header { color: red } }", ".card {\n &__header {\n color: red;\n }\n}\n", "<stdin>: WARNING: Cannot use type selector \"__header\" directly after nesting selector \"&\"\n"+sassWarningWrap) expectPrintedLower(t, ".card { .nav &--header { color: red } }", ".card {\n .nav &--header {\n color: red;\n }\n}\n", "<stdin>: WARNING: Cannot use type selector \"--header\" directly after nesting selector \"&\"\n"+sassWarningMove) expectPrintedLower(t, ".card { .nav &__header { color: red } }", ".card {\n .nav &__header {\n color: red;\n }\n}\n", "<stdin>: WARNING: Cannot use type selector \"__header\" directly after nesting selector \"&\"\n"+sassWarningMove) expectPrinted(t, ".card { &__header { color: red } }", ".card {\n &__header {\n color: red;\n }\n}\n", "<stdin>: WARNING: Cannot use type selector \"__header\" directly after nesting selector \"&\"\n"+sassWarningWrap) expectPrinted(t, ".card { .nav &__header { color: red } }", ".card {\n .nav &__header {\n color: red;\n }\n}\n", "<stdin>: WARNING: Cannot use type selector \"__header\" directly after nesting selector \"&\"\n"+sassWarningMove) expectPrinted(t, ".card { .nav, &__header { color: red } }", ".card {\n .nav, &__header {\n color: red;\n }\n}\n", "<stdin>: WARNING: Cannot use type selector \"__header\" directly after nesting selector \"&\"\n"+sassWarningMove) // Check pseudo-elements (those coming through "&" must be dropped) expectPrintedLower(t, "a, b::before { &.foo { color: red } }", "a.foo {\n color: red;\n}\n", "") expectPrintedLower(t, "a, b::before { & .foo { color: red } }", "a .foo {\n color: red;\n}\n", "") expectPrintedLower(t, "a { &.foo, &::before { color: red } }", "a.foo,\na::before {\n color: red;\n}\n", "") expectPrintedLower(t, "a { & .foo, & ::before { color: red } }", "a .foo,\na ::before {\n color: red;\n}\n", "") expectPrintedLower(t, "a, b::before { color: blue; &.foo, &::after { color: red } }", "a,\nb::before {\n color: blue;\n}\na.foo,\na::after {\n color: red;\n}\n", "") // Test at-rules expectPrintedLower(t, ".foo { @media screen {} }", "", "") expectPrintedLower(t, ".foo { @media screen { color: red } }", "@media screen {\n .foo {\n color: red;\n }\n}\n", "") expectPrintedLower(t, ".foo { @media screen { &:hover { color: red } } }", "@media screen {\n .foo:hover {\n color: red;\n }\n}\n", "") expectPrintedLower(t, ".foo { @media screen { :hover { color: red } } }", "@media screen {\n .foo :hover {\n color: red;\n }\n}\n", "") expectPrintedLower(t, ".foo, .bar { @media screen { color: red } }", "@media screen {\n .foo,\n .bar {\n color: red;\n }\n}\n", "") expectPrintedLower(t, ".foo, .bar { @media screen { &:hover { color: red } } }", "@media screen {\n .foo:hover,\n .bar:hover {\n color: red;\n }\n}\n", "") expectPrintedLower(t, ".foo, .bar { @media screen { :hover { color: red } } }", "@media screen {\n .foo :hover,\n .bar :hover {\n color: red;\n }\n}\n", "") expectPrintedLower(t, ".foo { @layer xyz {} }", "@layer xyz;\n", "") expectPrintedLower(t, ".foo { @layer xyz { color: red } }", "@layer xyz {\n .foo {\n color: red;\n }\n}\n", "") expectPrintedLower(t, ".foo { @layer xyz { &:hover { color: red } } }", "@layer xyz {\n .foo:hover {\n color: red;\n }\n}\n", "") expectPrintedLower(t, ".foo { @layer xyz { :hover { color: red } } }", "@layer xyz {\n .foo :hover {\n color: red;\n }\n}\n", "") expectPrintedLower(t, ".foo, .bar { @layer xyz { color: red } }", "@layer xyz {\n .foo,\n .bar {\n color: red;\n }\n}\n", "") expectPrintedLower(t, ".foo, .bar { @layer xyz { &:hover { color: red } } }", "@layer xyz {\n .foo:hover,\n .bar:hover {\n color: red;\n }\n}\n", "") expectPrintedLower(t, ".foo, .bar { @layer xyz { :hover { color: red } } }", "@layer xyz {\n .foo :hover,\n .bar :hover {\n color: red;\n }\n}\n", "") expectPrintedLower(t, "@media screen { @media (min-width: 900px) { a, b { &:hover { color: red } } } }", "@media screen {\n @media (min-width: 900px) {\n a:hover,\n b:hover {\n color: red;\n }\n }\n}\n", "") expectPrintedLower(t, "@supports (display: flex) { @supports selector(h2 > p) { a, b { &:hover { color: red } } } }", "@supports (display: flex) {\n @supports selector(h2 > p) {\n a:hover,\n b:hover {\n color: red;\n }\n }\n}\n", "") expectPrintedLower(t, "@layer foo { @layer bar { a, b { &:hover { color: red } } } }", "@layer foo {\n @layer bar {\n a:hover,\n b:hover {\n color: red;\n }\n }\n}\n", "") expectPrintedLower(t, ".card { @supports (selector(&)) { &:hover { color: red } } }", "@supports (selector(&)) {\n .card:hover {\n color: red;\n }\n}\n", "") expectPrintedLower(t, "html { @layer base { color: blue; @layer support { & body { color: red } } } }", "@layer base {\n html {\n color: blue;\n }\n @layer support {\n html body {\n color: red;\n }\n }\n}\n", "") // path_to_url#issuecomment-1549874958 expectPrinted(t, "@media screen { a { x: y } x: y; b { x: y } }", "@media screen {\n a {\n x: y;\n }\n x: y;\n b {\n x: y;\n }\n}\n", "") expectPrinted(t, ":root { @media screen { a { x: y } x: y; b { x: y } } }", ":root {\n @media screen {\n a {\n x: y;\n }\n x: y;\n b {\n x: y;\n }\n }\n}\n", "") } func TestBadQualifiedRules(t *testing.T) { expectPrinted(t, "$bad: rule;", "$bad: rule; {\n}\n", "<stdin>: WARNING: Unexpected \"$\"\n") expectPrinted(t, "$bad: rule; div { color: red }", "$bad: rule; div {\n color: red;\n}\n", "<stdin>: WARNING: Unexpected \"$\"\n") expectPrinted(t, "$bad { color: red }", "$bad {\n color: red;\n}\n", "<stdin>: WARNING: Unexpected \"$\"\n") expectPrinted(t, "a { div.major { color: blue } color: red }", "a {\n div.major {\n color: blue;\n }\n color: red;\n}\n", "") expectPrinted(t, "a { div:hover { color: blue } color: red }", "a {\n div:hover {\n color: blue;\n }\n color: red;\n}\n", "") expectPrinted(t, "a { div:hover { color: blue }; color: red }", "a {\n div:hover {\n color: blue;\n }\n color: red;\n}\n", "") expectPrinted(t, "a { div:hover { color: blue } ; color: red }", "a {\n div:hover {\n color: blue;\n }\n color: red;\n}\n", "") expectPrinted(t, "! { x: y; }", "! {\n x: y;\n}\n", "<stdin>: WARNING: Unexpected \"!\"\n") expectPrinted(t, "! { x: {} }", "! {\n x: {\n }\n}\n", "<stdin>: WARNING: Unexpected \"!\"\n<stdin>: WARNING: Expected identifier but found whitespace\n") expectPrinted(t, "a { *width: 100%; height: 1px }", "a {\n *width: 100%;\n height: 1px;\n}\n", "<stdin>: WARNING: Expected identifier but found \"*\"\n") expectPrinted(t, "a { garbage; height: 1px }", "a {\n garbage;\n height: 1px;\n}\n", "<stdin>: WARNING: Expected \":\"\n") expectPrinted(t, "a { !; height: 1px }", "a {\n !;\n height: 1px;\n}\n", "<stdin>: WARNING: Expected identifier but found \"!\"\n") } func TestAtRule(t *testing.T) { expectPrinted(t, "@unknown", "@unknown;\n", "<stdin>: WARNING: Expected \"{\" but found end of file\n") expectPrinted(t, "@unknown;", "@unknown;\n", "") expectPrinted(t, "@unknown{}", "@unknown {}\n", "") expectPrinted(t, "@unknown x;", "@unknown x;\n", "") expectPrinted(t, "@unknown{\na: b;\nc: d;\n}", "@unknown { a: b; c: d; }\n", "") expectPrinted(t, "@unknown", "@unknown;\n", "<stdin>: WARNING: Expected \"{\" but found end of file\n") expectPrinted(t, "@", "@ {\n}\n", "<stdin>: WARNING: Unexpected \"@\"\n") expectPrinted(t, "@;", "@; {\n}\n", "<stdin>: WARNING: Unexpected \"@\"\n") expectPrinted(t, "@{}", "@ {\n}\n", "<stdin>: WARNING: Unexpected \"@\"\n") expectPrinted(t, "@viewport { width: 100vw }", "@viewport {\n width: 100vw;\n}\n", "") expectPrinted(t, "@-ms-viewport { width: 100vw }", "@-ms-viewport {\n width: 100vw;\n}\n", "") expectPrinted(t, "@document url(\"path_to_url") { h1 { color: green } }", "@document url(path_to_url {\n h1 {\n color: green;\n }\n}\n", "") expectPrinted(t, "@-moz-document url-prefix() { h1 { color: green } }", "@-moz-document url-prefix() {\n h1 {\n color: green;\n }\n}\n", "") expectPrinted(t, "@media foo { bar }", "@media foo {\n bar {\n }\n}\n", "<stdin>: WARNING: Unexpected \"}\"\n") expectPrinted(t, "@media foo { bar {}", "@media foo {\n bar {\n }\n}\n", "<stdin>: WARNING: Expected \"}\" to go with \"{\"\n<stdin>: NOTE: The unbalanced \"{\" is here:\n") expectPrinted(t, "@media foo {", "@media foo {\n}\n", "<stdin>: WARNING: Expected \"}\" to go with \"{\"\n<stdin>: NOTE: The unbalanced \"{\" is here:\n") expectPrinted(t, "@media foo", "@media foo {\n}\n", "<stdin>: WARNING: Expected \"{\" but found end of file\n") expectPrinted(t, "@media", "@media {\n}\n", "<stdin>: WARNING: Expected \"{\" but found end of file\n") // path_to_url#syntax-page-selector expectPrinted(t, ` @page :first { margin: 0 } @page { @top-left-corner { content: 'tlc' } @top-left { content: 'tl' } @top-center { content: 'tc' } @top-right { content: 'tr' } @top-right-corner { content: 'trc' } @bottom-left-corner { content: 'blc' } @bottom-left { content: 'bl' } @bottom-center { content: 'bc' } @bottom-right { content: 'br' } @bottom-right-corner { content: 'brc' } @left-top { content: 'lt' } @left-middle { content: 'lm' } @left-bottom { content: 'lb' } @right-top { content: 'rt' } @right-middle { content: 'rm' } @right-bottom { content: 'rb' } } `, `@page :first { margin: 0; } @page { @top-left-corner { content: "tlc"; } @top-left { content: "tl"; } @top-center { content: "tc"; } @top-right { content: "tr"; } @top-right-corner { content: "trc"; } @bottom-left-corner { content: "blc"; } @bottom-left { content: "bl"; } @bottom-center { content: "bc"; } @bottom-right { content: "br"; } @bottom-right-corner { content: "brc"; } @left-top { content: "lt"; } @left-middle { content: "lm"; } @left-bottom { content: "lb"; } @right-top { content: "rt"; } @right-middle { content: "rm"; } @right-bottom { content: "rb"; } } `, "") // path_to_url#font-palette-values expectPrinted(t, ` @font-palette-values --Augusta { font-family: Handover Sans; base-palette: 3; override-colors: 1 rgb(43, 12, 9), 2 #000, 3 var(--highlight) } `, `@font-palette-values --Augusta { font-family: Handover Sans; base-palette: 3; override-colors: 1 rgb(43, 12, 9), 2 #000, 3 var(--highlight); } `, "") // path_to_url#container-rule expectPrinted(t, ` @container my-layout (inline-size > 45em) { .foo { color: skyblue; } } `, `@container my-layout (inline-size > 45em) { .foo { color: skyblue; } } `, "") expectPrintedMinify(t, `@container card ( inline-size > 30em ) and style( --responsive = true ) { .foo { color: skyblue; } }`, "@container card (inline-size > 30em) and style(--responsive = true){.foo{color:skyblue}}", "") expectPrintedMangleMinify(t, `@supports ( container-type: size ) { @container ( width <= 150px ) { #inner { background-color: skyblue; } } }`, "@supports (container-type: size){@container (width <= 150px){#inner{background-color:#87ceeb}}}", "") // path_to_url#defining-before-change-style-the-starting-style-rule expectPrinted(t, ` @starting-style { h1 { background-color: transparent; } @layer foo { div { height: 100px; } } } `, `@starting-style { h1 { background-color: transparent; } @layer foo { div { height: 100px; } } } `, "") expectPrintedMinify(t, `@starting-style { h1 { background-color: transparent; } }`, "@starting-style{h1{background-color:transparent}}", "") // path_to_url#the-counter-style-rule expectPrinted(t, ` @counter-style box-corner { system: fixed; symbols: ; suffix: ': ' } `, `@counter-style box-corner { system: fixed; symbols: ; suffix: ": "; } `, "") // path_to_url#font-feature-values expectPrinted(t, ` @font-feature-values Roboto { font-display: swap; } `, `@font-feature-values Roboto { font-display: swap; } `, "") expectPrinted(t, ` @font-feature-values Bongo { @swash { ornate: 1 } } `, `@font-feature-values Bongo { @swash { ornate: 1; } } `, "") // path_to_url#at-ruledef-position-try expectPrinted(t, `@position-try --foo { top: 0 }`, `@position-try --foo { top: 0; } `, "") expectPrintedMinify(t, `@position-try --foo { top: 0; }`, `@position-try --foo{top:0}`, "") } func TestAtCharset(t *testing.T) { expectPrinted(t, "@charset \"UTF-8\";", "@charset \"UTF-8\";\n", "") expectPrinted(t, "@charset 'UTF-8';", "@charset \"UTF-8\";\n", "") expectPrinted(t, "@charset \"utf-8\";", "@charset \"utf-8\";\n", "") expectPrinted(t, "@charset \"Utf-8\";", "@charset \"Utf-8\";\n", "") expectPrinted(t, "@charset \"US-ASCII\";", "@charset \"US-ASCII\";\n", "<stdin>: WARNING: \"UTF-8\" will be used instead of unsupported charset \"US-ASCII\"\n") expectPrinted(t, "@charset;", "@charset;\n", "<stdin>: WARNING: Expected whitespace but found \";\"\n") expectPrinted(t, "@charset ;", "@charset;\n", "<stdin>: WARNING: Expected string token but found \";\"\n") expectPrinted(t, "@charset\"UTF-8\";", "@charset \"UTF-8\";\n", "<stdin>: WARNING: Expected whitespace but found \"\\\"UTF-8\\\"\"\n") expectPrinted(t, "@charset \"UTF-8\"", "@charset \"UTF-8\";\n", "<stdin>: WARNING: Expected \";\" but found end of file\n") expectPrinted(t, "@charset url(UTF-8);", "@charset url(UTF-8);\n", "<stdin>: WARNING: Expected string token but found \"url(UTF-8)\"\n") expectPrinted(t, "@charset url(\"UTF-8\");", "@charset url(UTF-8);\n", "<stdin>: WARNING: Expected string token but found \"url(\"\n") expectPrinted(t, "@charset \"UTF-8\" ", "@charset \"UTF-8\";\n", "<stdin>: WARNING: Expected \";\" but found whitespace\n") expectPrinted(t, "@charset \"UTF-8\"{}", "@charset \"UTF-8\";\n {\n}\n", "<stdin>: WARNING: Expected \";\" but found \"{\"\n") } func TestAtImport(t *testing.T) { expectPrinted(t, "@import\"foo.css\";", "@import \"foo.css\";\n", "") expectPrinted(t, "@import \"foo.css\";", "@import \"foo.css\";\n", "") expectPrinted(t, "@import \"foo.css\" ;", "@import \"foo.css\";\n", "") expectPrinted(t, "@import url();", "@import \"\";\n", "") expectPrinted(t, "@import url(foo.css);", "@import \"foo.css\";\n", "") expectPrinted(t, "@import url(foo.css) ;", "@import \"foo.css\";\n", "") expectPrinted(t, "@import url( foo.css );", "@import \"foo.css\";\n", "") expectPrinted(t, "@import url(\"foo.css\");", "@import \"foo.css\";\n", "") expectPrinted(t, "@import url(\"foo.css\") ;", "@import \"foo.css\";\n", "") expectPrinted(t, "@import url( \"foo.css\" );", "@import \"foo.css\";\n", "") expectPrinted(t, "@import url(\"foo.css\") print;", "@import \"foo.css\" print;\n", "") expectPrinted(t, "@import url(\"foo.css\") screen and (orientation:landscape);", "@import \"foo.css\" screen and (orientation:landscape);\n", "") expectPrinted(t, "@import;", "@import;\n", "<stdin>: WARNING: Expected URL token but found \";\"\n") expectPrinted(t, "@import ;", "@import;\n", "<stdin>: WARNING: Expected URL token but found \";\"\n") expectPrinted(t, "@import \"foo.css\"", "@import \"foo.css\";\n", "<stdin>: WARNING: Expected \";\" but found end of file\n") expectPrinted(t, "@import url(\"foo.css\" extra-stuff);", "@import url(\"foo.css\" extra-stuff);\n", "<stdin>: WARNING: Expected URL token but found \"url(\"\n") expectPrinted(t, "@import url(\"foo.css\";", "@import url(\"foo.css\";);\n", "<stdin>: WARNING: Expected URL token but found \"url(\"\n<stdin>: WARNING: Expected \")\" to go with \"(\"\n<stdin>: NOTE: The unbalanced \"(\" is here:\n") expectPrinted(t, "@import noturl(\"foo.css\");", "@import noturl(\"foo.css\");\n", "<stdin>: WARNING: Expected URL token but found \"noturl(\"\n") expectPrinted(t, "@import url(foo.css", "@import \"foo.css\";\n", `<stdin>: WARNING: Expected ")" to end URL token <stdin>: NOTE: The unbalanced "(" is here: <stdin>: WARNING: Expected ";" but found end of file `) expectPrinted(t, "@import \"foo.css\" {}", "@import \"foo.css\" {}\n", "<stdin>: WARNING: Expected \";\"\n") expectPrinted(t, "@import \"foo\"\na { color: red }\nb { color: blue }", "@import \"foo\" a { color: red }\nb {\n color: blue;\n}\n", "<stdin>: WARNING: Expected \";\"\n") expectPrinted(t, "a { @import \"foo.css\" }", "a {\n @import \"foo.css\";\n}\n", "<stdin>: WARNING: \"@import\" is only valid at the top level\n<stdin>: WARNING: Expected \";\"\n") } func TestLegalComment(t *testing.T) { expectPrinted(t, "/*!*/@import \"x\";", "/*!*/\n@import \"x\";\n", "") expectPrinted(t, "/*!*/@charset \"UTF-8\";", "/*!*/\n@charset \"UTF-8\";\n", "") expectPrinted(t, "/*!*/ @import \"x\";", "/*!*/\n@import \"x\";\n", "") expectPrinted(t, "/*!*/ @charset \"UTF-8\";", "/*!*/\n@charset \"UTF-8\";\n", "") expectPrinted(t, "/*!*/ @charset \"UTF-8\"; @import \"x\";", "/*!*/\n@charset \"UTF-8\";\n@import \"x\";\n", "") expectPrinted(t, "/*!*/ @import \"x\"; @charset \"UTF-8\";", "/*!*/\n@import \"x\";\n@charset \"UTF-8\";\n", "<stdin>: WARNING: \"@charset\" must be the first rule in the file\n"+ "<stdin>: NOTE: This rule cannot come before a \"@charset\" rule\n") expectPrinted(t, "@import \"x\";/*!*/", "@import \"x\";\n/*!*/\n", "") expectPrinted(t, "@charset \"UTF-8\";/*!*/", "@charset \"UTF-8\";\n/*!*/\n", "") expectPrinted(t, "@import \"x\"; /*!*/", "@import \"x\";\n/*!*/\n", "") expectPrinted(t, "@charset \"UTF-8\"; /*!*/", "@charset \"UTF-8\";\n/*!*/\n", "") expectPrinted(t, "/*! before */ a { --b: var(--c, /*!*/ /*!*/); } /*! after */\n", "/*! before */\na {\n --b: var(--c, );\n}\n/*! after */\n", "") } func TestAtKeyframes(t *testing.T) { expectPrinted(t, "@keyframes {}", "@keyframes {}\n", "<stdin>: WARNING: Expected identifier but found \"{\"\n") expectPrinted(t, "@keyframes name{}", "@keyframes name {\n}\n", "") expectPrinted(t, "@keyframes name {}", "@keyframes name {\n}\n", "") expectPrinted(t, "@keyframes name{0%,50%{color:red}25%,75%{color:blue}}", "@keyframes name {\n 0%, 50% {\n color: red;\n }\n 25%, 75% {\n color: blue;\n }\n}\n", "") expectPrinted(t, "@keyframes name { 0%, 50% { color: red } 25%, 75% { color: blue } }", "@keyframes name {\n 0%, 50% {\n color: red;\n }\n 25%, 75% {\n color: blue;\n }\n}\n", "") expectPrinted(t, "@keyframes name{from{color:red}to{color:blue}}", "@keyframes name {\n from {\n color: red;\n }\n to {\n color: blue;\n }\n}\n", "") expectPrinted(t, "@keyframes name { from { color: red } to { color: blue } }", "@keyframes name {\n from {\n color: red;\n }\n to {\n color: blue;\n }\n}\n", "") // Note: Strings as names is allowed in the CSS specification and works in // Firefox and Safari but Chrome has strangely decided to deliberately not // support this. We always turn all string names into identifiers to avoid // them silently breaking in Chrome. expectPrinted(t, "@keyframes 'name' {}", "@keyframes name {\n}\n", "") expectPrinted(t, "@keyframes 'name 2' {}", "@keyframes name\\ 2 {\n}\n", "") expectPrinted(t, "@keyframes 'none' {}", "@keyframes \"none\" {}\n", "") expectPrinted(t, "@keyframes 'None' {}", "@keyframes \"None\" {}\n", "") expectPrinted(t, "@keyframes 'unset' {}", "@keyframes \"unset\" {}\n", "") expectPrinted(t, "@keyframes 'revert' {}", "@keyframes \"revert\" {}\n", "") expectPrinted(t, "@keyframes None {}", "@keyframes None {}\n", "<stdin>: WARNING: Cannot use \"None\" as a name for \"@keyframes\" without quotes\n"+ "NOTE: You can put \"None\" in quotes to prevent it from becoming a CSS keyword.\n") expectPrinted(t, "@keyframes REVERT {}", "@keyframes REVERT {}\n", "<stdin>: WARNING: Cannot use \"REVERT\" as a name for \"@keyframes\" without quotes\n"+ "NOTE: You can put \"REVERT\" in quotes to prevent it from becoming a CSS keyword.\n") expectPrinted(t, "@keyframes name { from { color: red } }", "@keyframes name {\n from {\n color: red;\n }\n}\n", "") expectPrinted(t, "@keyframes name { 100% { color: red } }", "@keyframes name {\n 100% {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "@keyframes name { from { color: red } }", "@keyframes name {\n 0% {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "@keyframes name { 100% { color: red } }", "@keyframes name {\n to {\n color: red;\n }\n}\n", "") expectPrinted(t, "@-webkit-keyframes name {}", "@-webkit-keyframes name {\n}\n", "") expectPrinted(t, "@-moz-keyframes name {}", "@-moz-keyframes name {\n}\n", "") expectPrinted(t, "@-ms-keyframes name {}", "@-ms-keyframes name {\n}\n", "") expectPrinted(t, "@-o-keyframes name {}", "@-o-keyframes name {\n}\n", "") expectPrinted(t, "@keyframes {}", "@keyframes {}\n", "<stdin>: WARNING: Expected identifier but found \"{\"\n") expectPrinted(t, "@keyframes name { 0% 100% {} }", "@keyframes name { 0% 100% {} }\n", "<stdin>: WARNING: Expected \",\" but found \"100%\"\n") expectPrinted(t, "@keyframes name { {} 0% {} }", "@keyframes name { {} 0% {} }\n", "<stdin>: WARNING: Expected percentage but found \"{\"\n") expectPrinted(t, "@keyframes name { 100 {} }", "@keyframes name { 100 {} }\n", "<stdin>: WARNING: Expected percentage but found \"100\"\n") expectPrinted(t, "@keyframes name { into {} }", "@keyframes name {\n into {\n }\n}\n", "<stdin>: WARNING: Expected percentage but found \"into\"\n") expectPrinted(t, "@keyframes name { 1,2 {} }", "@keyframes name { 1, 2 {} }\n", "<stdin>: WARNING: Expected percentage but found \"1\"\n") expectPrinted(t, "@keyframes name { 1, 2 {} }", "@keyframes name { 1, 2 {} }\n", "<stdin>: WARNING: Expected percentage but found \"1\"\n") expectPrinted(t, "@keyframes name { 1 ,2 {} }", "@keyframes name { 1, 2 {} }\n", "<stdin>: WARNING: Expected percentage but found \"1\"\n") expectPrinted(t, "@keyframes name { 1%, {} }", "@keyframes name { 1%, {} }\n", "<stdin>: WARNING: Expected percentage but found \"{\"\n") expectPrinted(t, "@keyframes name { 1%, x {} }", "@keyframes name {\n 1%, x {\n }\n}\n", "<stdin>: WARNING: Expected percentage but found \"x\"\n") expectPrinted(t, "@keyframes name { 1%, ! {} }", "@keyframes name { 1%, ! {} }\n", "<stdin>: WARNING: Expected percentage but found \"!\"\n") expectPrinted(t, "@keyframes name { .x {} }", "@keyframes name { .x {} }\n", "<stdin>: WARNING: Expected percentage but found \".\"\n") expectPrinted(t, "@keyframes name { {} }", "@keyframes name { {} }\n", "<stdin>: WARNING: Expected percentage but found \"{\"\n") expectPrinted(t, "@keyframes name { 1% }", "@keyframes name { 1% }\n", "<stdin>: WARNING: Expected \"{\" but found \"}\"\n") expectPrinted(t, "@keyframes name { 1%", "@keyframes name { 1% }\n", "<stdin>: WARNING: Expected \"{\" but found end of file\n") expectPrinted(t, "@keyframes name { 1%,,2% {} }", "@keyframes name { 1%,, 2% {} }\n", "<stdin>: WARNING: Expected percentage but found \",\"\n") expectPrinted(t, "@keyframes name {", "@keyframes name {}\n", "<stdin>: WARNING: Expected \"}\" to go with \"{\"\n<stdin>: NOTE: The unbalanced \"{\" is here:\n") expectPrinted(t, "@keyframes x { 1%, {} } @keyframes z { 1% {} }", "@keyframes x { 1%, {} }\n@keyframes z {\n 1% {\n }\n}\n", "<stdin>: WARNING: Expected percentage but found \"{\"\n") expectPrinted(t, "@keyframes x { .y {} } @keyframes z { 1% {} }", "@keyframes x { .y {} }\n@keyframes z {\n 1% {\n }\n}\n", "<stdin>: WARNING: Expected percentage but found \".\"\n") expectPrinted(t, "@keyframes x { x {} } @keyframes z { 1% {} }", "@keyframes x {\n x {\n }\n}\n@keyframes z {\n 1% {\n }\n}\n", "<stdin>: WARNING: Expected percentage but found \"x\"\n") expectPrinted(t, "@keyframes x { {} } @keyframes z { 1% {} }", "@keyframes x { {} }\n@keyframes z {\n 1% {\n }\n}\n", "<stdin>: WARNING: Expected percentage but found \"{\"\n") expectPrinted(t, "@keyframes x { 1% {}", "@keyframes x { 1% {} }\n", "<stdin>: WARNING: Expected \"}\" to go with \"{\"\n<stdin>: NOTE: The unbalanced \"{\" is here:\n") expectPrinted(t, "@keyframes x { 1% {", "@keyframes x { 1% {} }\n", "<stdin>: WARNING: Expected \"}\" to go with \"{\"\n<stdin>: NOTE: The unbalanced \"{\" is here:\n") expectPrinted(t, "@keyframes x { 1%", "@keyframes x { 1% }\n", "<stdin>: WARNING: Expected \"{\" but found end of file\n") expectPrinted(t, "@keyframes x {", "@keyframes x {}\n", "<stdin>: WARNING: Expected \"}\" to go with \"{\"\n<stdin>: NOTE: The unbalanced \"{\" is here:\n") } func TestAnimationName(t *testing.T) { // Note: Strings as names is allowed in the CSS specification and works in // Firefox and Safari but Chrome has strangely decided to deliberately not // support this. We always turn all string names into identifiers to avoid // them silently breaking in Chrome. expectPrinted(t, "div { animation-name: 'name' }", "div {\n animation-name: name;\n}\n", "") expectPrinted(t, "div { animation-name: 'name 2' }", "div {\n animation-name: name\\ 2;\n}\n", "") expectPrinted(t, "div { animation-name: 'none' }", "div {\n animation-name: \"none\";\n}\n", "") expectPrinted(t, "div { animation-name: 'None' }", "div {\n animation-name: \"None\";\n}\n", "") expectPrinted(t, "div { animation-name: 'unset' }", "div {\n animation-name: \"unset\";\n}\n", "") expectPrinted(t, "div { animation-name: 'revert' }", "div {\n animation-name: \"revert\";\n}\n", "") expectPrinted(t, "div { animation-name: none }", "div {\n animation-name: none;\n}\n", "") expectPrinted(t, "div { animation-name: unset }", "div {\n animation-name: unset;\n}\n", "") expectPrinted(t, "div { animation: 2s linear 'name 2', 3s infinite 'name 3' }", "div {\n animation: 2s linear name\\ 2, 3s infinite name\\ 3;\n}\n", "") } func TestAtRuleValidation(t *testing.T) { expectPrinted(t, "a {} b {} c {} @charset \"UTF-8\";", "a {\n}\nb {\n}\nc {\n}\n@charset \"UTF-8\";\n", "<stdin>: WARNING: \"@charset\" must be the first rule in the file\n"+ "<stdin>: NOTE: This rule cannot come before a \"@charset\" rule\n") expectPrinted(t, "a {} b {} c {} @import \"foo\";", "a {\n}\nb {\n}\nc {\n}\n@import \"foo\";\n", "<stdin>: WARNING: All \"@import\" rules must come first\n"+ "<stdin>: NOTE: This rule cannot come before an \"@import\" rule\n") } func TestAtLayer(t *testing.T) { expectPrinted(t, "@layer a, b;", "@layer a, b;\n", "") expectPrinted(t, "@layer a {}", "@layer a {\n}\n", "") expectPrinted(t, "@layer {}", "@layer {\n}\n", "") expectPrinted(t, "@layer a, b {}", "@layer a, b {\n}\n", "<stdin>: WARNING: Expected \";\"\n") expectPrinted(t, "@layer;", "@layer;\n", "<stdin>: WARNING: Unexpected \";\"\n") expectPrinted(t, "@layer , b {}", "@layer , b {\n}\n", "<stdin>: WARNING: Unexpected \",\"\n") expectPrinted(t, "@layer a", "@layer a;\n", "<stdin>: WARNING: Expected \";\" but found end of file\n") expectPrinted(t, "@layer a { @layer b }", "@layer a {\n @layer b;\n}\n", "<stdin>: WARNING: Expected \";\"\n") expectPrinted(t, "@layer a b", "@layer a b;\n", "<stdin>: WARNING: Unexpected \"b\"\n<stdin>: WARNING: Expected \";\" but found end of file\n") expectPrinted(t, "@layer a b ;", "@layer a b;\n", "<stdin>: WARNING: Unexpected \"b\"\n") expectPrinted(t, "@layer a b {}", "@layer a b {\n}\n", "<stdin>: WARNING: Unexpected \"b\"\n") expectPrinted(t, "@layer a, b;", "@layer a, b;\n", "") expectPrinted(t, "@layer a {}", "@layer a {\n}\n", "") expectPrinted(t, "@layer {}", "@layer {\n}\n", "") expectPrinted(t, "@layer foo { div { color: red } }", "@layer foo {\n div {\n color: red;\n }\n}\n", "") // Check semicolon error recovery expectPrinted(t, "@layer", "@layer;\n", "<stdin>: WARNING: Expected \";\" but found end of file\n") expectPrinted(t, "@layer a", "@layer a;\n", "<stdin>: WARNING: Expected \";\" but found end of file\n") expectPrinted(t, "@layer a { @layer }", "@layer a {\n @layer;\n}\n", "<stdin>: WARNING: Expected \";\"\n") expectPrinted(t, "@layer a { @layer b }", "@layer a {\n @layer b;\n}\n", "<stdin>: WARNING: Expected \";\"\n") expectPrintedMangle(t, "@layer", "@layer;\n", "<stdin>: WARNING: Expected \";\" but found end of file\n") expectPrintedMangle(t, "@layer a", "@layer a;\n", "<stdin>: WARNING: Expected \";\" but found end of file\n") expectPrintedMangle(t, "@layer a { @layer }", "@layer a {\n @layer;\n}\n", "<stdin>: WARNING: Expected \";\"\n") expectPrintedMangle(t, "@layer a { @layer b }", "@layer a.b;\n", "<stdin>: WARNING: Expected \";\"\n") // Check mangling expectPrintedMangle(t, "@layer foo { div {} }", "@layer foo;\n", "") expectPrintedMangle(t, "@layer foo { div { color: yellow } }", "@layer foo {\n div {\n color: #ff0;\n }\n}\n", "") expectPrintedMangle(t, "@layer a { @layer b {} }", "@layer a.b;\n", "") expectPrintedMangle(t, "@layer a { @layer {} }", "@layer a {\n @layer {\n }\n}\n", "") expectPrintedMangle(t, "@layer { @layer a {} }", "@layer {\n @layer a;\n}\n", "") expectPrintedMangle(t, "@layer a.b { @layer c.d {} }", "@layer a.b.c.d;\n", "") expectPrintedMangle(t, "@layer a.b { @layer c.d {} @layer e.f {} }", "@layer a.b {\n @layer c.d;\n @layer e.f;\n}\n", "") expectPrintedMangle(t, "@layer a.b { @layer c.d { e { f: g } } }", "@layer a.b.c.d {\n e {\n f: g;\n }\n}\n", "") // Invalid layer names should not be merged, since that causes the rule to // become invalid. It would be a change in semantics if we merged an invalid // rule with a valid rule since then the other valid rule would be invalid. initial := "<stdin>: WARNING: \"initial\" cannot be used as a layer name\n" inherit := "<stdin>: WARNING: \"inherit\" cannot be used as a layer name\n" unset := "<stdin>: WARNING: \"unset\" cannot be used as a layer name\n" expectPrinted(t, "@layer foo { @layer initial; }", "@layer foo {\n @layer initial;\n}\n", initial) expectPrinted(t, "@layer foo { @layer inherit; }", "@layer foo {\n @layer inherit;\n}\n", inherit) expectPrinted(t, "@layer foo { @layer unset; }", "@layer foo {\n @layer unset;\n}\n", unset) expectPrinted(t, "@layer initial { @layer foo; }", "@layer initial {\n @layer foo;\n}\n", initial) expectPrinted(t, "@layer inherit { @layer foo; }", "@layer inherit {\n @layer foo;\n}\n", inherit) expectPrinted(t, "@layer unset { @layer foo; }", "@layer unset {\n @layer foo;\n}\n", unset) expectPrintedMangle(t, "@layer foo { @layer initial { a { b: c } } }", "@layer foo {\n @layer initial {\n a {\n b: c;\n }\n }\n}\n", initial) expectPrintedMangle(t, "@layer initial { @layer foo { a { b: c } } }", "@layer initial {\n @layer foo {\n a {\n b: c;\n }\n }\n}\n", initial) // Order matters here. Do not drop the first "@layer a;" or the order will be changed. expectPrintedMangle(t, "@layer a; @layer b; @layer a;", "@layer a;\n@layer b;\n@layer a;\n", "") // Validate ordering with "@layer" and "@import" expectPrinted(t, "@layer a; @import url(b);", "@layer a;\n@import \"b\";\n", "") expectPrinted(t, "@layer a; @layer b; @import url(c);", "@layer a;\n@layer b;\n@import \"c\";\n", "") expectPrinted(t, "@layer a {} @import url(b);", "@layer a {\n}\n@import url(b);\n", "<stdin>: WARNING: All \"@import\" rules must come first\n<stdin>: NOTE: This rule cannot come before an \"@import\" rule\n") expectPrinted(t, "@import url(a); @layer b; @import url(c);", "@import \"a\";\n@layer b;\n@import url(c);\n", "<stdin>: WARNING: All \"@import\" rules must come first\n<stdin>: NOTE: This rule cannot come before an \"@import\" rule\n") expectPrinted(t, "@layer a; @charset \"UTF-8\";", "@layer a;\n@charset \"UTF-8\";\n", "<stdin>: WARNING: \"@charset\" must be the first rule in the file\n<stdin>: NOTE: This rule cannot come before a \"@charset\" rule\n") } func TestEmptyRule(t *testing.T) { expectPrinted(t, "div {}", "div {\n}\n", "") expectPrinted(t, "@media screen {}", "@media screen {\n}\n", "") expectPrinted(t, "@page { @top-left {} }", "@page {\n @top-left {\n }\n}\n", "") expectPrinted(t, "@keyframes test { from {} to {} }", "@keyframes test {\n from {\n }\n to {\n }\n}\n", "") expectPrintedMangle(t, "div {}", "", "") expectPrintedMangle(t, "@media screen {}", "", "") expectPrintedMangle(t, "@page { @top-left {} }", "", "") expectPrintedMangle(t, "@keyframes test { from {} to {} }", "@keyframes test {\n}\n", "") expectPrinted(t, "$invalid {}", "$invalid {\n}\n", "<stdin>: WARNING: Unexpected \"$\"\n") expectPrinted(t, "@page { color: red; @top-left {} }", "@page {\n color: red;\n @top-left {\n }\n}\n", "") expectPrinted(t, "@keyframes test { from {} to { color: red } }", "@keyframes test {\n from {\n }\n to {\n color: red;\n }\n}\n", "") expectPrinted(t, "@keyframes test { from { color: red } to {} }", "@keyframes test {\n from {\n color: red;\n }\n to {\n }\n}\n", "") expectPrintedMangle(t, "$invalid {}", "$invalid {\n}\n", "<stdin>: WARNING: Unexpected \"$\"\n") expectPrintedMangle(t, "@page { color: red; @top-left {} }", "@page {\n color: red;\n}\n", "") expectPrintedMangle(t, "@keyframes test { from {} to { color: red } }", "@keyframes test {\n to {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "@keyframes test { from { color: red } to {} }", "@keyframes test {\n 0% {\n color: red;\n }\n}\n", "") expectPrintedMangleMinify(t, "$invalid {}", "$invalid{}", "<stdin>: WARNING: Unexpected \"$\"\n") expectPrintedMangleMinify(t, "@page { color: red; @top-left {} }", "@page{color:red}", "") expectPrintedMangleMinify(t, "@keyframes test { from {} to { color: red } }", "@keyframes test{to{color:red}}", "") expectPrintedMangleMinify(t, "@keyframes test { from { color: red } to {} }", "@keyframes test{0%{color:red}}", "") expectPrinted(t, "invalid", "invalid {\n}\n", "<stdin>: WARNING: Expected \"{\" but found end of file\n") expectPrinted(t, "invalid }", "invalid } {\n}\n", "<stdin>: WARNING: Unexpected \"}\"\n") } func TestMarginAndPaddingAndInset(t *testing.T) { for _, x := range []string{"margin", "padding", "inset"} { xTop := x + "-top" xRight := x + "-right" xBottom := x + "-bottom" xLeft := x + "-left" if x == "inset" { xTop = "top" xRight = "right" xBottom = "bottom" xLeft = "left" } expectPrinted(t, "a { "+x+": 0 1px 0 1px }", "a {\n "+x+": 0 1px 0 1px;\n}\n", "") expectPrinted(t, "a { "+x+": 0 1px 0px 1px }", "a {\n "+x+": 0 1px 0px 1px;\n}\n", "") expectPrintedMangle(t, "a { "+xTop+": 0px }", "a {\n "+xTop+": 0;\n}\n", "") expectPrintedMangle(t, "a { "+xRight+": 0px }", "a {\n "+xRight+": 0;\n}\n", "") expectPrintedMangle(t, "a { "+xBottom+": 0px }", "a {\n "+xBottom+": 0;\n}\n", "") expectPrintedMangle(t, "a { "+xLeft+": 0px }", "a {\n "+xLeft+": 0;\n}\n", "") expectPrintedMangle(t, "a { "+xTop+": 1px }", "a {\n "+xTop+": 1px;\n}\n", "") expectPrintedMangle(t, "a { "+xRight+": 1px }", "a {\n "+xRight+": 1px;\n}\n", "") expectPrintedMangle(t, "a { "+xBottom+": 1px }", "a {\n "+xBottom+": 1px;\n}\n", "") expectPrintedMangle(t, "a { "+xLeft+": 1px }", "a {\n "+xLeft+": 1px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 0 1px 0 0 }", "a {\n "+x+": 0 1px 0 0;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 0 1px 2px 1px }", "a {\n "+x+": 0 1px 2px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 0 1px 0 1px }", "a {\n "+x+": 0 1px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 0 0 0 0 }", "a {\n "+x+": 0;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 0 0 0 0 !important }", "a {\n "+x+": 0 !important;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 0 1px 0px 1px }", "a {\n "+x+": 0 1px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 0 1 0px 1px }", "a {\n "+x+": 0 1 0px 1px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 1px 2px 3px 4px; "+xTop+": 5px }", "a {\n "+x+": 5px 2px 3px 4px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 1px 2px 3px 4px; "+xRight+": 5px }", "a {\n "+x+": 1px 5px 3px 4px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 1px 2px 3px 4px; "+xBottom+": 5px }", "a {\n "+x+": 1px 2px 5px 4px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 1px 2px 3px 4px; "+xLeft+": 5px }", "a {\n "+x+": 1px 2px 3px 5px;\n}\n", "") expectPrintedMangle(t, "a { "+xTop+": 5px; "+x+": 1px 2px 3px 4px }", "a {\n "+x+": 1px 2px 3px 4px;\n}\n", "") expectPrintedMangle(t, "a { "+xRight+": 5px; "+x+": 1px 2px 3px 4px }", "a {\n "+x+": 1px 2px 3px 4px;\n}\n", "") expectPrintedMangle(t, "a { "+xBottom+": 5px; "+x+": 1px 2px 3px 4px }", "a {\n "+x+": 1px 2px 3px 4px;\n}\n", "") expectPrintedMangle(t, "a { "+xLeft+": 5px; "+x+": 1px 2px 3px 4px }", "a {\n "+x+": 1px 2px 3px 4px;\n}\n", "") expectPrintedMangle(t, "a { "+xTop+": 1px; "+xTop+": 2px }", "a {\n "+xTop+": 2px;\n}\n", "") expectPrintedMangle(t, "a { "+xRight+": 1px; "+xRight+": 2px }", "a {\n "+xRight+": 2px;\n}\n", "") expectPrintedMangle(t, "a { "+xBottom+": 1px; "+xBottom+": 2px }", "a {\n "+xBottom+": 2px;\n}\n", "") expectPrintedMangle(t, "a { "+xLeft+": 1px; "+xLeft+": 2px }", "a {\n "+xLeft+": 2px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 1px; "+x+": 2px !important }", "a {\n "+x+": 1px;\n "+x+": 2px !important;\n}\n", "") expectPrintedMangle(t, "a { "+xTop+": 1px; "+xTop+": 2px !important }", "a {\n "+xTop+": 1px;\n "+xTop+": 2px !important;\n}\n", "") expectPrintedMangle(t, "a { "+xRight+": 1px; "+xRight+": 2px !important }", "a {\n "+xRight+": 1px;\n "+xRight+": 2px !important;\n}\n", "") expectPrintedMangle(t, "a { "+xBottom+": 1px; "+xBottom+": 2px !important }", "a {\n "+xBottom+": 1px;\n "+xBottom+": 2px !important;\n}\n", "") expectPrintedMangle(t, "a { "+xLeft+": 1px; "+xLeft+": 2px !important }", "a {\n "+xLeft+": 1px;\n "+xLeft+": 2px !important;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 1px !important; "+x+": 2px }", "a {\n "+x+": 1px !important;\n "+x+": 2px;\n}\n", "") expectPrintedMangle(t, "a { "+xTop+": 1px !important; "+xTop+": 2px }", "a {\n "+xTop+": 1px !important;\n "+xTop+": 2px;\n}\n", "") expectPrintedMangle(t, "a { "+xRight+": 1px !important; "+xRight+": 2px }", "a {\n "+xRight+": 1px !important;\n "+xRight+": 2px;\n}\n", "") expectPrintedMangle(t, "a { "+xBottom+": 1px !important; "+xBottom+": 2px }", "a {\n "+xBottom+": 1px !important;\n "+xBottom+": 2px;\n}\n", "") expectPrintedMangle(t, "a { "+xLeft+": 1px !important; "+xLeft+": 2px }", "a {\n "+xLeft+": 1px !important;\n "+xLeft+": 2px;\n}\n", "") expectPrintedMangle(t, "a { "+xTop+": 1px; "+xTop+": }", "a {\n "+xTop+": 1px;\n "+xTop+":;\n}\n", "") expectPrintedMangle(t, "a { "+xTop+": 1px; "+xTop+": 2px 3px }", "a {\n "+xTop+": 1px;\n "+xTop+": 2px 3px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 1px 2px 3px 4px; "+xLeft+": -4px; "+xRight+": -2px }", "a {\n "+x+": 1px -2px 3px -4px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 1px 2px; "+xTop+": 5px }", "a {\n "+x+": 5px 2px 1px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 1px; "+xTop+": 5px }", "a {\n "+x+": 5px 1px 1px;\n}\n", "") // This doesn't collapse because if the "calc" has an error it // will be ignored and the original rule will show through expectPrintedMangle(t, "a { "+x+": 1px 2px 3px 4px; "+xRight+": calc(1px + var(--x)) }", "a {\n "+x+": 1px 2px 3px 4px;\n "+xRight+": calc(1px + var(--x));\n}\n", "") expectPrintedMangle(t, "a { "+xLeft+": 1px; "+xRight+": 2px; "+xTop+": 3px; "+xBottom+": 4px }", "a {\n "+x+": 3px 2px 4px 1px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 1px 2px 3px 4px; "+xRight+": 5px !important }", "a {\n "+x+": 1px 2px 3px 4px;\n "+xRight+": 5px !important;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 1px 2px 3px 4px !important; "+xRight+": 5px }", "a {\n "+x+": 1px 2px 3px 4px !important;\n "+xRight+": 5px;\n}\n", "") expectPrintedMangle(t, "a { "+xLeft+": 1px !important; "+xRight+": 2px; "+xTop+": 3px !important; "+xBottom+": 4px }", "a {\n "+xLeft+": 1px !important;\n "+xRight+": 2px;\n "+xTop+": 3px !important;\n "+xBottom+": 4px;\n}\n", "") // This should not be changed because "--x" and "--z" could be empty expectPrintedMangle(t, "a { "+x+": var(--x) var(--y) var(--z) var(--y) }", "a {\n "+x+": var(--x) var(--y) var(--z) var(--y);\n}\n", "") // Don't merge different units expectPrintedMangle(t, "a { "+x+": 1px; "+x+": 2px; }", "a {\n "+x+": 2px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 1px; "+x+": 2vw; }", "a {\n "+x+": 1px;\n "+x+": 2vw;\n}\n", "") expectPrintedMangle(t, "a { "+xLeft+": 1px; "+xLeft+": 2px; }", "a {\n "+xLeft+": 2px;\n}\n", "") expectPrintedMangle(t, "a { "+xLeft+": 1px; "+xLeft+": 2vw; }", "a {\n "+xLeft+": 1px;\n "+xLeft+": 2vw;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 0 1px 2cm 3%; "+x+": 4px; }", "a {\n "+x+": 4px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 0 1px 2cm 3%; "+x+": 4vw; }", "a {\n "+x+": 0 1px 2cm 3%;\n "+x+": 4vw;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 0 1px 2cm 3%; "+xLeft+": 4px; }", "a {\n "+x+": 0 1px 2cm 4px;\n}\n", "") expectPrintedMangle(t, "a { "+x+": 0 1px 2cm 3%; "+xLeft+": 4vw; }", "a {\n "+x+": 0 1px 2cm 3%;\n "+xLeft+": 4vw;\n}\n", "") expectPrintedMangle(t, "a { "+xLeft+": 1Q; "+xRight+": 2Q; "+xTop+": 3Q; "+xBottom+": 4Q; }", "a {\n "+x+": 3Q 2Q 4Q 1Q;\n}\n", "") expectPrintedMangle(t, "a { "+xLeft+": 1Q; "+xRight+": 2Q; "+xTop+": 3Q; "+xBottom+": 0; }", "a {\n "+xLeft+": 1Q;\n "+xRight+": 2Q;\n "+xTop+": 3Q;\n "+xBottom+": 0;\n}\n", "") } // "auto" is the only keyword allowed in a quad, and only for "margin" and "inset" not for "padding" expectPrintedMangle(t, "a { margin: 1px auto 3px 4px; margin-left: auto }", "a {\n margin: 1px auto 3px;\n}\n", "") expectPrintedMangle(t, "a { inset: 1px auto 3px 4px; left: auto }", "a {\n inset: 1px auto 3px;\n}\n", "") expectPrintedMangle(t, "a { padding: 1px auto 3px 4px; padding-left: auto }", "a {\n padding: 1px auto 3px 4px;\n padding-left: auto;\n}\n", "") expectPrintedMangle(t, "a { margin: auto; margin-left: 1px }", "a {\n margin: auto auto auto 1px;\n}\n", "") expectPrintedMangle(t, "a { inset: auto; left: 1px }", "a {\n inset: auto auto auto 1px;\n}\n", "") expectPrintedMangle(t, "a { padding: auto; padding-left: 1px }", "a {\n padding: auto;\n padding-left: 1px;\n}\n", "") expectPrintedMangle(t, "a { margin: inherit; margin-left: 1px }", "a {\n margin: inherit;\n margin-left: 1px;\n}\n", "") expectPrintedMangle(t, "a { inset: inherit; left: 1px }", "a {\n inset: inherit;\n left: 1px;\n}\n", "") expectPrintedMangle(t, "a { padding: inherit; padding-left: 1px }", "a {\n padding: inherit;\n padding-left: 1px;\n}\n", "") expectPrintedLowerMangle(t, "a { top: 0; right: 0; bottom: 0; left: 0; }", "a {\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n}\n", "") // "inset" should be expanded when not supported expectPrintedLower(t, "a { inset: 0; }", "a {\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n}\n", "") expectPrintedLower(t, "a { inset: 0px; }", "a {\n top: 0px;\n right: 0px;\n bottom: 0px;\n left: 0px;\n}\n", "") expectPrintedLower(t, "a { inset: 1px 2px; }", "a {\n top: 1px;\n right: 2px;\n bottom: 1px;\n left: 2px;\n}\n", "") expectPrintedLower(t, "a { inset: 1px 2px 3px; }", "a {\n top: 1px;\n right: 2px;\n bottom: 3px;\n left: 2px;\n}\n", "") expectPrintedLower(t, "a { inset: 1px 2px 3px 4px; }", "a {\n top: 1px;\n right: 2px;\n bottom: 3px;\n left: 4px;\n}\n", "") // When "inset" isn't supported, other mangling should still work expectPrintedLowerMangle(t, "a { top: 0px; }", "a {\n top: 0;\n}\n", "") expectPrintedLowerMangle(t, "a { right: 0px; }", "a {\n right: 0;\n}\n", "") expectPrintedLowerMangle(t, "a { bottom: 0px; }", "a {\n bottom: 0;\n}\n", "") expectPrintedLowerMangle(t, "a { left: 0px; }", "a {\n left: 0;\n}\n", "") expectPrintedLowerMangle(t, "a { inset: 0px; }", "a {\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n}\n", "") // When "inset" isn't supported, whitespace minifying should still work expectPrintedLowerMinify(t, "a { top: 0px; }", "a{top:0px}", "") expectPrintedLowerMinify(t, "a { right: 0px; }", "a{right:0px}", "") expectPrintedLowerMinify(t, "a { bottom: 0px; }", "a{bottom:0px}", "") expectPrintedLowerMinify(t, "a { left: 0px; }", "a{left:0px}", "") expectPrintedLowerMinify(t, "a { inset: 0px; }", "a{top:0px;right:0px;bottom:0px;left:0px}", "") expectPrintedLowerMinify(t, "a { inset: 1px 2px; }", "a{top:1px;right:2px;bottom:1px;left:2px}", "") expectPrintedLowerMinify(t, "a { inset: 1px 2px 3px; }", "a{top:1px;right:2px;bottom:3px;left:2px}", "") expectPrintedLowerMinify(t, "a { inset: 1px 2px 3px 4px; }", "a{top:1px;right:2px;bottom:3px;left:4px}", "") } func TestBorderRadius(t *testing.T) { expectPrinted(t, "a { border-top-left-radius: 0 0 }", "a {\n border-top-left-radius: 0 0;\n}\n", "") expectPrintedMangle(t, "a { border-top-left-radius: 0 0 }", "a {\n border-top-left-radius: 0;\n}\n", "") expectPrintedMangle(t, "a { border-top-left-radius: 0 0px }", "a {\n border-top-left-radius: 0;\n}\n", "") expectPrintedMangle(t, "a { border-top-left-radius: 0 1px }", "a {\n border-top-left-radius: 0 1px;\n}\n", "") expectPrintedMangle(t, "a { border-top-left-radius: 0; border-radius: 1px }", "a {\n border-radius: 1px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 1px 2px 3px 4px }", "a {\n border-radius: 1px 2px 3px 4px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 1px 2px 1px 3px }", "a {\n border-radius: 1px 2px 1px 3px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 1px 2px 3px 2px }", "a {\n border-radius: 1px 2px 3px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 1px 2px 1px 2px }", "a {\n border-radius: 1px 2px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 1px 1px 1px 1px }", "a {\n border-radius: 1px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 0/1px 2px 3px 4px }", "a {\n border-radius: 0 / 1px 2px 3px 4px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 0/1px 2px 1px 3px }", "a {\n border-radius: 0 / 1px 2px 1px 3px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 0/1px 2px 3px 2px }", "a {\n border-radius: 0 / 1px 2px 3px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 0/1px 2px 1px 2px }", "a {\n border-radius: 0 / 1px 2px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 0/1px 1px 1px 1px }", "a {\n border-radius: 0 / 1px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 1px 2px; border-top-left-radius: 3px; }", "a {\n border-radius: 3px 2px 1px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 1px; border-top-left-radius: 3px; }", "a {\n border-radius: 3px 1px 1px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 0/1px; border-top-left-radius: 3px; }", "a {\n border-radius: 3px 0 0 / 3px 1px 1px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 0/1px 2px; border-top-left-radius: 3px; }", "a {\n border-radius: 3px 0 0 / 3px 2px 1px;\n}\n", "") for _, x := range []string{"", "-top-left", "-top-right", "-bottom-left", "-bottom-right"} { y := "border" + x + "-radius" expectPrintedMangle(t, "a { "+y+": 1px; "+y+": 2px }", "a {\n "+y+": 2px;\n}\n", "") expectPrintedMangle(t, "a { "+y+": 1px !important; "+y+": 2px }", "a {\n "+y+": 1px !important;\n "+y+": 2px;\n}\n", "") expectPrintedMangle(t, "a { "+y+": 1px; "+y+": 2px !important }", "a {\n "+y+": 1px;\n "+y+": 2px !important;\n}\n", "") expectPrintedMangle(t, "a { "+y+": 1px !important; "+y+": 2px !important }", "a {\n "+y+": 2px !important;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 1px; "+y+": 2px !important; }", "a {\n border-radius: 1px;\n "+y+": 2px !important;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 1px !important; "+y+": 2px; }", "a {\n border-radius: 1px !important;\n "+y+": 2px;\n}\n", "") } expectPrintedMangle(t, "a { border-top-left-radius: ; border-radius: 1px }", "a {\n border-top-left-radius:;\n border-radius: 1px;\n}\n", "") expectPrintedMangle(t, "a { border-top-left-radius: 1px; border-radius: / }", "a {\n border-top-left-radius: 1px;\n border-radius: /;\n}\n", "") expectPrintedMangleMinify(t, "a { border-radius: 1px 2px 3px 4px; border-top-right-radius: 5px; }", "a{border-radius:1px 5px 3px 4px}", "") expectPrintedMangleMinify(t, "a { border-radius: 1px 2px 3px 4px; border-top-right-radius: 5px 6px; }", "a{border-radius:1px 5px 3px 4px/1px 6px 3px 4px}", "") // These should not be changed because "--x" and "--z" could be empty expectPrintedMangle(t, "a { border-radius: var(--x) var(--y) var(--z) var(--y) }", "a {\n border-radius: var(--x) var(--y) var(--z) var(--y);\n}\n", "") expectPrintedMangle(t, "a { border-radius: 0 / var(--x) var(--y) var(--z) var(--y) }", "a {\n border-radius: 0 / var(--x) var(--y) var(--z) var(--y);\n}\n", "") // "inherit" should not be merged expectPrintedMangle(t, "a { border-radius: 1px; border-top-left-radius: 0 }", "a {\n border-radius: 0 1px 1px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: inherit; border-top-left-radius: 0 }", "a {\n border-radius: inherit;\n border-top-left-radius: 0;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 0; border-top-left-radius: inherit }", "a {\n border-radius: 0;\n border-top-left-radius: inherit;\n}\n", "") expectPrintedMangle(t, "a { border-top-left-radius: 0; border-radius: inherit }", "a {\n border-top-left-radius: 0;\n border-radius: inherit;\n}\n", "") expectPrintedMangle(t, "a { border-top-left-radius: inherit; border-radius: 0 }", "a {\n border-top-left-radius: inherit;\n border-radius: 0;\n}\n", "") // Don't merge different units expectPrintedMangle(t, "a { border-radius: 1px; border-radius: 2px; }", "a {\n border-radius: 2px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 1px; border-top-left-radius: 2px; }", "a {\n border-radius: 2px 1px 1px;\n}\n", "") expectPrintedMangle(t, "a { border-top-left-radius: 1px; border-radius: 2px; }", "a {\n border-radius: 2px;\n}\n", "") expectPrintedMangle(t, "a { border-top-left-radius: 1px; border-top-left-radius: 2px; }", "a {\n border-top-left-radius: 2px;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 1rem; border-radius: 1vw; }", "a {\n border-radius: 1rem;\n border-radius: 1vw;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 1rem; border-top-left-radius: 1vw; }", "a {\n border-radius: 1rem;\n border-top-left-radius: 1vw;\n}\n", "") expectPrintedMangle(t, "a { border-top-left-radius: 1rem; border-radius: 1vw; }", "a {\n border-top-left-radius: 1rem;\n border-radius: 1vw;\n}\n", "") expectPrintedMangle(t, "a { border-top-left-radius: 1rem; border-top-left-radius: 1vw; }", "a {\n border-top-left-radius: 1rem;\n border-top-left-radius: 1vw;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 0; border-top-left-radius: 2px; }", "a {\n border-radius: 2px 0 0;\n}\n", "") expectPrintedMangle(t, "a { border-radius: 0; border-top-left-radius: 2rem; }", "a {\n border-radius: 0;\n border-top-left-radius: 2rem;\n}\n", "") } func TestBoxShadow(t *testing.T) { expectPrinted(t, "a { box-shadow: inset 0px 0px 0px 0px black }", "a {\n box-shadow: inset 0px 0px 0px 0px black;\n}\n", "") expectPrintedMangle(t, "a { box-shadow: 0px 0px 0px 0px inset black }", "a {\n box-shadow: 0 0 inset #000;\n}\n", "") expectPrintedMangle(t, "a { box-shadow: 0px 0px 0px 0px black inset }", "a {\n box-shadow: 0 0 #000 inset;\n}\n", "") expectPrintedMangle(t, "a { box-shadow: black 0px 0px 0px 0px inset }", "a {\n box-shadow: #000 0 0 inset;\n}\n", "") expectPrintedMangle(t, "a { box-shadow: inset 0px 0px 0px 0px black }", "a {\n box-shadow: inset 0 0 #000;\n}\n", "") expectPrintedMangle(t, "a { box-shadow: inset black 0px 0px 0px 0px }", "a {\n box-shadow: inset #000 0 0;\n}\n", "") expectPrintedMangle(t, "a { box-shadow: black inset 0px 0px 0px 0px }", "a {\n box-shadow: #000 inset 0 0;\n}\n", "") expectPrintedMangle(t, "a { box-shadow: yellow 1px 0px 0px 1px inset }", "a {\n box-shadow: #ff0 1px 0 0 1px inset;\n}\n", "") expectPrintedMangle(t, "a { box-shadow: yellow 1px 0px 1px 0px inset }", "a {\n box-shadow: #ff0 1px 0 1px inset;\n}\n", "") expectPrintedMangle(t, "a { box-shadow: rebeccapurple, yellow, black }", "a {\n box-shadow:\n #639,\n #ff0,\n #000;\n}\n", "") expectPrintedMangle(t, "a { box-shadow: 0px 0px 0px var(--foo) black }", "a {\n box-shadow: 0 0 0 var(--foo) #000;\n}\n", "") expectPrintedMangle(t, "a { box-shadow: 0px 0px 0px 0px var(--foo) black }", "a {\n box-shadow: 0 0 0 0 var(--foo) #000;\n}\n", "") expectPrintedMangle(t, "a { box-shadow: calc(1px + var(--foo)) 0px 0px 0px black }", "a {\n box-shadow: calc(1px + var(--foo)) 0 0 0 #000;\n}\n", "") expectPrintedMangle(t, "a { box-shadow: inset 0px 0px 0px 0px 0px magenta; }", "a {\n box-shadow: inset 0 0 0 0 0 #f0f;\n}\n", "") expectPrintedMangleMinify(t, "a { box-shadow: rebeccapurple , yellow , black }", "a{box-shadow:#639,#ff0,#000}", "") expectPrintedMangleMinify(t, "a { box-shadow: rgb(255, 0, 17) 0 0 1 inset }", "a{box-shadow:#f01 0 0 1 inset}", "") } func TestMangleTime(t *testing.T) { expectPrintedMangle(t, "a { animation: b 1s }", "a {\n animation: b 1s;\n}\n", "") expectPrintedMangle(t, "a { animation: b 1.s }", "a {\n animation: b 1s;\n}\n", "") expectPrintedMangle(t, "a { animation: b 1.0s }", "a {\n animation: b 1s;\n}\n", "") expectPrintedMangle(t, "a { animation: b 1.02s }", "a {\n animation: b 1.02s;\n}\n", "") expectPrintedMangle(t, "a { animation: b .1s }", "a {\n animation: b .1s;\n}\n", "") expectPrintedMangle(t, "a { animation: b .01s }", "a {\n animation: b .01s;\n}\n", "") expectPrintedMangle(t, "a { animation: b .001s }", "a {\n animation: b 1ms;\n}\n", "") expectPrintedMangle(t, "a { animation: b .0012s }", "a {\n animation: b 1.2ms;\n}\n", "") expectPrintedMangle(t, "a { animation: b -.001s }", "a {\n animation: b -1ms;\n}\n", "") expectPrintedMangle(t, "a { animation: b -.0012s }", "a {\n animation: b -1.2ms;\n}\n", "") expectPrintedMangle(t, "a { animation: b .0001s }", "a {\n animation: b .1ms;\n}\n", "") expectPrintedMangle(t, "a { animation: b .00012s }", "a {\n animation: b .12ms;\n}\n", "") expectPrintedMangle(t, "a { animation: b .000123s }", "a {\n animation: b .123ms;\n}\n", "") expectPrintedMangle(t, "a { animation: b .01S }", "a {\n animation: b .01S;\n}\n", "") expectPrintedMangle(t, "a { animation: b .001S }", "a {\n animation: b 1ms;\n}\n", "") expectPrintedMangle(t, "a { animation: b 1ms }", "a {\n animation: b 1ms;\n}\n", "") expectPrintedMangle(t, "a { animation: b 10ms }", "a {\n animation: b 10ms;\n}\n", "") expectPrintedMangle(t, "a { animation: b 100ms }", "a {\n animation: b .1s;\n}\n", "") expectPrintedMangle(t, "a { animation: b 120ms }", "a {\n animation: b .12s;\n}\n", "") expectPrintedMangle(t, "a { animation: b 123ms }", "a {\n animation: b 123ms;\n}\n", "") expectPrintedMangle(t, "a { animation: b 1000ms }", "a {\n animation: b 1s;\n}\n", "") expectPrintedMangle(t, "a { animation: b 1200ms }", "a {\n animation: b 1.2s;\n}\n", "") expectPrintedMangle(t, "a { animation: b 1230ms }", "a {\n animation: b 1.23s;\n}\n", "") expectPrintedMangle(t, "a { animation: b 1234ms }", "a {\n animation: b 1234ms;\n}\n", "") expectPrintedMangle(t, "a { animation: b -100ms }", "a {\n animation: b -.1s;\n}\n", "") expectPrintedMangle(t, "a { animation: b -120ms }", "a {\n animation: b -.12s;\n}\n", "") expectPrintedMangle(t, "a { animation: b 120mS }", "a {\n animation: b .12s;\n}\n", "") expectPrintedMangle(t, "a { animation: b 120Ms }", "a {\n animation: b .12s;\n}\n", "") expectPrintedMangle(t, "a { animation: b 123mS }", "a {\n animation: b 123mS;\n}\n", "") expectPrintedMangle(t, "a { animation: b 123Ms }", "a {\n animation: b 123Ms;\n}\n", "") // Mangling times with exponents is not currently supported expectPrintedMangle(t, "a { animation: b 1e3ms }", "a {\n animation: b 1e3ms;\n}\n", "") expectPrintedMangle(t, "a { animation: b 1E3ms }", "a {\n animation: b 1E3ms;\n}\n", "") } func TestCalc(t *testing.T) { expectPrinted(t, "a { b: calc(+(2)) }", "a {\n b: calc(+(2));\n}\n", "<stdin>: WARNING: \"+\" can only be used as an infix operator, not a prefix operator\n") expectPrinted(t, "a { b: calc(-(2)) }", "a {\n b: calc(-(2));\n}\n", "<stdin>: WARNING: \"-\" can only be used as an infix operator, not a prefix operator\n") expectPrinted(t, "a { b: calc(*(2)) }", "a {\n b: calc(*(2));\n}\n", "") expectPrinted(t, "a { b: calc(/(2)) }", "a {\n b: calc(/(2));\n}\n", "") expectPrinted(t, "a { b: calc(1 + 2) }", "a {\n b: calc(1 + 2);\n}\n", "") expectPrinted(t, "a { b: calc(1 - 2) }", "a {\n b: calc(1 - 2);\n}\n", "") expectPrinted(t, "a { b: calc(1 * 2) }", "a {\n b: calc(1 * 2);\n}\n", "") expectPrinted(t, "a { b: calc(1 / 2) }", "a {\n b: calc(1 / 2);\n}\n", "") expectPrinted(t, "a { b: calc(1+ 2) }", "a {\n b: calc(1+ 2);\n}\n", "<stdin>: WARNING: The \"+\" operator only works if there is whitespace on both sides\n") expectPrinted(t, "a { b: calc(1- 2) }", "a {\n b: calc(1- 2);\n}\n", "<stdin>: WARNING: The \"-\" operator only works if there is whitespace on both sides\n") expectPrinted(t, "a { b: calc(1* 2) }", "a {\n b: calc(1* 2);\n}\n", "") expectPrinted(t, "a { b: calc(1/ 2) }", "a {\n b: calc(1/ 2);\n}\n", "") expectPrinted(t, "a { b: calc(1 +2) }", "a {\n b: calc(1 +2);\n}\n", "<stdin>: WARNING: The \"+\" operator only works if there is whitespace on both sides\n") expectPrinted(t, "a { b: calc(1 -2) }", "a {\n b: calc(1 -2);\n}\n", "<stdin>: WARNING: The \"-\" operator only works if there is whitespace on both sides\n") expectPrinted(t, "a { b: calc(1 *2) }", "a {\n b: calc(1 *2);\n}\n", "") expectPrinted(t, "a { b: calc(1 /2) }", "a {\n b: calc(1 /2);\n}\n", "") expectPrinted(t, "a { b: calc(1 +(2)) }", "a {\n b: calc(1 +(2));\n}\n", "<stdin>: WARNING: The \"+\" operator only works if there is whitespace on both sides\n") expectPrinted(t, "a { b: calc(1 -(2)) }", "a {\n b: calc(1 -(2));\n}\n", "<stdin>: WARNING: The \"-\" operator only works if there is whitespace on both sides\n") expectPrinted(t, "a { b: calc(1 *(2)) }", "a {\n b: calc(1 *(2));\n}\n", "") expectPrinted(t, "a { b: calc(1 /(2)) }", "a {\n b: calc(1 /(2));\n}\n", "") } func TestMinifyCalc(t *testing.T) { expectPrintedMangleMinify(t, "a { b: calc(x + y) }", "a{b:calc(x + y)}", "") expectPrintedMangleMinify(t, "a { b: calc(x - y) }", "a{b:calc(x - y)}", "") expectPrintedMangleMinify(t, "a { b: calc(x * y) }", "a{b:calc(x*y)}", "") expectPrintedMangleMinify(t, "a { b: calc(x / y) }", "a{b:calc(x/y)}", "") } func TestMangleCalc(t *testing.T) { expectPrintedMangle(t, "a { b: calc(1) }", "a {\n b: 1;\n}\n", "") expectPrintedMangle(t, "a { b: calc((1)) }", "a {\n b: 1;\n}\n", "") expectPrintedMangle(t, "a { b: calc(calc(1)) }", "a {\n b: 1;\n}\n", "") expectPrintedMangle(t, "a { b: calc(x + y * z) }", "a {\n b: calc(x + y * z);\n}\n", "") expectPrintedMangle(t, "a { b: calc(x * y + z) }", "a {\n b: calc(x * y + z);\n}\n", "") // Test sum expectPrintedMangle(t, "a { b: calc(2 + 3) }", "a {\n b: 5;\n}\n", "") expectPrintedMangle(t, "a { b: calc(6 - 2) }", "a {\n b: 4;\n}\n", "") // Test product expectPrintedMangle(t, "a { b: calc(2 * 3) }", "a {\n b: 6;\n}\n", "") expectPrintedMangle(t, "a { b: calc(6 / 2) }", "a {\n b: 3;\n}\n", "") expectPrintedMangle(t, "a { b: calc(2px * 3 + 4px * 5) }", "a {\n b: 26px;\n}\n", "") expectPrintedMangle(t, "a { b: calc(2 * 3px + 4 * 5px) }", "a {\n b: 26px;\n}\n", "") expectPrintedMangle(t, "a { b: calc(2px * 3 - 4px * 5) }", "a {\n b: -14px;\n}\n", "") expectPrintedMangle(t, "a { b: calc(2 * 3px - 4 * 5px) }", "a {\n b: -14px;\n}\n", "") // Test negation expectPrintedMangle(t, "a { b: calc(x + 1) }", "a {\n b: calc(x + 1);\n}\n", "") expectPrintedMangle(t, "a { b: calc(x - 1) }", "a {\n b: calc(x - 1);\n}\n", "") expectPrintedMangle(t, "a { b: calc(x + -1) }", "a {\n b: calc(x - 1);\n}\n", "") expectPrintedMangle(t, "a { b: calc(x - -1) }", "a {\n b: calc(x + 1);\n}\n", "") expectPrintedMangle(t, "a { b: calc(1 + x) }", "a {\n b: calc(1 + x);\n}\n", "") expectPrintedMangle(t, "a { b: calc(1 - x) }", "a {\n b: calc(1 - x);\n}\n", "") expectPrintedMangle(t, "a { b: calc(-1 + x) }", "a {\n b: calc(-1 + x);\n}\n", "") expectPrintedMangle(t, "a { b: calc(-1 - x) }", "a {\n b: calc(-1 - x);\n}\n", "") // Test inversion expectPrintedMangle(t, "a { b: calc(x * 4) }", "a {\n b: calc(x * 4);\n}\n", "") expectPrintedMangle(t, "a { b: calc(x / 4) }", "a {\n b: calc(x / 4);\n}\n", "") expectPrintedMangle(t, "a { b: calc(x * 0.25) }", "a {\n b: calc(x / 4);\n}\n", "") expectPrintedMangle(t, "a { b: calc(x / 0.25) }", "a {\n b: calc(x * 4);\n}\n", "") // Test operator precedence expectPrintedMangle(t, "a { b: calc((a + b) + c) }", "a {\n b: calc(a + b + c);\n}\n", "") expectPrintedMangle(t, "a { b: calc(a + (b + c)) }", "a {\n b: calc(a + b + c);\n}\n", "") expectPrintedMangle(t, "a { b: calc((a - b) - c) }", "a {\n b: calc(a - b - c);\n}\n", "") expectPrintedMangle(t, "a { b: calc(a - (b - c)) }", "a {\n b: calc(a - (b - c));\n}\n", "") expectPrintedMangle(t, "a { b: calc((a * b) * c) }", "a {\n b: calc(a * b * c);\n}\n", "") expectPrintedMangle(t, "a { b: calc(a * (b * c)) }", "a {\n b: calc(a * b * c);\n}\n", "") expectPrintedMangle(t, "a { b: calc((a / b) / c) }", "a {\n b: calc(a / b / c);\n}\n", "") expectPrintedMangle(t, "a { b: calc(a / (b / c)) }", "a {\n b: calc(a / (b / c));\n}\n", "") expectPrintedMangle(t, "a { b: calc(a + b * c / d - e) }", "a {\n b: calc(a + b * c / d - e);\n}\n", "") expectPrintedMangle(t, "a { b: calc((a + ((b * c) / d)) - e) }", "a {\n b: calc(a + b * c / d - e);\n}\n", "") expectPrintedMangle(t, "a { b: calc((a + b) * c / (d - e)) }", "a {\n b: calc((a + b) * c / (d - e));\n}\n", "") // Using "var()" should bail because it can expand to any number of tokens expectPrintedMangle(t, "a { b: calc(1px - x + 2px) }", "a {\n b: calc(3px - x);\n}\n", "") expectPrintedMangle(t, "a { b: calc(1px - var(x) + 2px) }", "a {\n b: calc(1px - var(x) + 2px);\n}\n", "") // Test values that can't be accurately represented as decimals expectPrintedMangle(t, "a { b: calc(100% / 1) }", "a {\n b: 100%;\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 2) }", "a {\n b: 50%;\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 3) }", "a {\n b: calc(100% / 3);\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 4) }", "a {\n b: 25%;\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 5) }", "a {\n b: 20%;\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 6) }", "a {\n b: calc(100% / 6);\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 7) }", "a {\n b: calc(100% / 7);\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 8) }", "a {\n b: 12.5%;\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 9) }", "a {\n b: calc(100% / 9);\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 10) }", "a {\n b: 10%;\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 100) }", "a {\n b: 1%;\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 1000) }", "a {\n b: .1%;\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 10000) }", "a {\n b: .01%;\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 100000) }", "a {\n b: .001%;\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / 1000000) }", "a {\n b: calc(100% / 1000000);\n}\n", "") // This actually ends up as "100% * (1 / 1000000)" which is less precise expectPrintedMangle(t, "a { b: calc(100% / -1000000) }", "a {\n b: calc(100% / -1000000);\n}\n", "") expectPrintedMangle(t, "a { b: calc(100% / -100000) }", "a {\n b: -.001%;\n}\n", "") expectPrintedMangle(t, "a { b: calc(3 * (2px + 1em / 7)) }", "a {\n b: calc(3 * (2px + 1em / 7));\n}\n", "") expectPrintedMangle(t, "a { b: calc(3 * (2px + 1em / 8)) }", "a {\n b: calc(3 * (2px + .125em));\n}\n", "") // Non-finite numbers expectPrintedMangle(t, "a { b: calc(0px / 0) }", "a {\n b: calc(0px / 0);\n}\n", "") expectPrintedMangle(t, "a { b: calc(1px / 0) }", "a {\n b: calc(1px / 0);\n}\n", "") expectPrintedMangle(t, "a { b: calc(-1px / 0) }", "a {\n b: calc(-1px / 0);\n}\n", "") expectPrintedMangle(t, "a { b: calc(nan) }", "a {\n b: calc(nan);\n}\n", "") expectPrintedMangle(t, "a { b: calc(infinity) }", "a {\n b: calc(infinity);\n}\n", "") expectPrintedMangle(t, "a { b: calc(-infinity) }", "a {\n b: calc(-infinity);\n}\n", "") expectPrintedMangle(t, "a { b: calc(1px / nan) }", "a {\n b: calc(1px / nan);\n}\n", "") expectPrintedMangle(t, "a { b: calc(1px / infinity) }", "a {\n b: 0px;\n}\n", "") expectPrintedMangle(t, "a { b: calc(1px / -infinity) }", "a {\n b: -0px;\n}\n", "") } func TestTransform(t *testing.T) { expectPrintedMangle(t, "a { transform: matrix(1, 0, 0, 1, 0, 0) }", "a {\n transform: scale(1);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix(2, 0, 0, 1, 0, 0) }", "a {\n transform: scaleX(2);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix(1, 0, 0, 2, 0, 0) }", "a {\n transform: scaleY(2);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix(2, 0, 0, 3, 0, 0) }", "a {\n transform: scale(2, 3);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix(2, 0, 0, 2, 0, 0) }", "a {\n transform: scale(2);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix(1, 0, 0, 1, 1, 2) }", "a {\n transform:\n matrix(\n 1, 0,\n 0, 1,\n 1, 2);\n}\n", "") expectPrintedMangle(t, "a { transform: translate(0, 0) }", "a {\n transform: translate(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translate(0px, 0px) }", "a {\n transform: translate(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translate(0%, 0%) }", "a {\n transform: translate(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translate(1px, 0) }", "a {\n transform: translate(1px);\n}\n", "") expectPrintedMangle(t, "a { transform: translate(1px, 0px) }", "a {\n transform: translate(1px);\n}\n", "") expectPrintedMangle(t, "a { transform: translate(1px, 0%) }", "a {\n transform: translate(1px);\n}\n", "") expectPrintedMangle(t, "a { transform: translate(0, 1px) }", "a {\n transform: translateY(1px);\n}\n", "") expectPrintedMangle(t, "a { transform: translate(0px, 1px) }", "a {\n transform: translateY(1px);\n}\n", "") expectPrintedMangle(t, "a { transform: translate(0%, 1px) }", "a {\n transform: translateY(1px);\n}\n", "") expectPrintedMangle(t, "a { transform: translate(1px, 2px) }", "a {\n transform: translate(1px, 2px);\n}\n", "") expectPrintedMangle(t, "a { transform: translate(40%, 60%) }", "a {\n transform: translate(40%, 60%);\n}\n", "") expectPrintedMangle(t, "a { transform: translateX(0) }", "a {\n transform: translate(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translateX(0px) }", "a {\n transform: translate(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translateX(0%) }", "a {\n transform: translate(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translateX(1px) }", "a {\n transform: translate(1px);\n}\n", "") expectPrintedMangle(t, "a { transform: translateX(50%) }", "a {\n transform: translate(50%);\n}\n", "") expectPrintedMangle(t, "a { transform: translateY(0) }", "a {\n transform: translateY(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translateY(0px) }", "a {\n transform: translateY(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translateY(0%) }", "a {\n transform: translateY(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translateY(1px) }", "a {\n transform: translateY(1px);\n}\n", "") expectPrintedMangle(t, "a { transform: translateY(50%) }", "a {\n transform: translateY(50%);\n}\n", "") expectPrintedMangle(t, "a { transform: scale(1) }", "a {\n transform: scale(1);\n}\n", "") expectPrintedMangle(t, "a { transform: scale(100%) }", "a {\n transform: scale(1);\n}\n", "") expectPrintedMangle(t, "a { transform: scale(10%) }", "a {\n transform: scale(.1);\n}\n", "") expectPrintedMangle(t, "a { transform: scale(99%) }", "a {\n transform: scale(99%);\n}\n", "") expectPrintedMangle(t, "a { transform: scale(1, 1) }", "a {\n transform: scale(1);\n}\n", "") expectPrintedMangle(t, "a { transform: scale(100%, 1) }", "a {\n transform: scale(1);\n}\n", "") expectPrintedMangle(t, "a { transform: scale(10%, 0.1) }", "a {\n transform: scale(.1);\n}\n", "") expectPrintedMangle(t, "a { transform: scale(99%, 0.99) }", "a {\n transform: scale(99%, .99);\n}\n", "") expectPrintedMangle(t, "a { transform: scale(60%, 40%) }", "a {\n transform: scale(.6, .4);\n}\n", "") expectPrintedMangle(t, "a { transform: scale(3, 1) }", "a {\n transform: scaleX(3);\n}\n", "") expectPrintedMangle(t, "a { transform: scale(300%, 1) }", "a {\n transform: scaleX(3);\n}\n", "") expectPrintedMangle(t, "a { transform: scale(1, 3) }", "a {\n transform: scaleY(3);\n}\n", "") expectPrintedMangle(t, "a { transform: scale(1, 300%) }", "a {\n transform: scaleY(3);\n}\n", "") expectPrintedMangle(t, "a { transform: scaleX(1) }", "a {\n transform: scaleX(1);\n}\n", "") expectPrintedMangle(t, "a { transform: scaleX(2) }", "a {\n transform: scaleX(2);\n}\n", "") expectPrintedMangle(t, "a { transform: scaleX(300%) }", "a {\n transform: scaleX(3);\n}\n", "") expectPrintedMangle(t, "a { transform: scaleX(99%) }", "a {\n transform: scaleX(99%);\n}\n", "") expectPrintedMangle(t, "a { transform: scaleY(1) }", "a {\n transform: scaleY(1);\n}\n", "") expectPrintedMangle(t, "a { transform: scaleY(2) }", "a {\n transform: scaleY(2);\n}\n", "") expectPrintedMangle(t, "a { transform: scaleY(300%) }", "a {\n transform: scaleY(3);\n}\n", "") expectPrintedMangle(t, "a { transform: scaleY(99%) }", "a {\n transform: scaleY(99%);\n}\n", "") expectPrintedMangle(t, "a { transform: rotate(0) }", "a {\n transform: rotate(0);\n}\n", "") expectPrintedMangle(t, "a { transform: rotate(0deg) }", "a {\n transform: rotate(0);\n}\n", "") expectPrintedMangle(t, "a { transform: rotate(1deg) }", "a {\n transform: rotate(1deg);\n}\n", "") expectPrintedMangle(t, "a { transform: skew(0) }", "a {\n transform: skew(0);\n}\n", "") expectPrintedMangle(t, "a { transform: skew(0deg) }", "a {\n transform: skew(0);\n}\n", "") expectPrintedMangle(t, "a { transform: skew(1deg) }", "a {\n transform: skew(1deg);\n}\n", "") expectPrintedMangle(t, "a { transform: skew(1deg, 0) }", "a {\n transform: skew(1deg);\n}\n", "") expectPrintedMangle(t, "a { transform: skew(1deg, 0deg) }", "a {\n transform: skew(1deg);\n}\n", "") expectPrintedMangle(t, "a { transform: skew(0, 1deg) }", "a {\n transform: skew(0, 1deg);\n}\n", "") expectPrintedMangle(t, "a { transform: skew(0deg, 1deg) }", "a {\n transform: skew(0, 1deg);\n}\n", "") expectPrintedMangle(t, "a { transform: skew(1deg, 2deg) }", "a {\n transform: skew(1deg, 2deg);\n}\n", "") expectPrintedMangle(t, "a { transform: skewX(0) }", "a {\n transform: skew(0);\n}\n", "") expectPrintedMangle(t, "a { transform: skewX(0deg) }", "a {\n transform: skew(0);\n}\n", "") expectPrintedMangle(t, "a { transform: skewX(1deg) }", "a {\n transform: skew(1deg);\n}\n", "") expectPrintedMangle(t, "a { transform: skewY(0) }", "a {\n transform: skewY(0);\n}\n", "") expectPrintedMangle(t, "a { transform: skewY(0deg) }", "a {\n transform: skewY(0);\n}\n", "") expectPrintedMangle(t, "a { transform: skewY(1deg) }", "a {\n transform: skewY(1deg);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2) }", "a {\n transform:\n matrix3d(\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 2);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 3, 4, 1) }", "a {\n transform:\n matrix3d(\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 2, 3, 4, 1);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix3d(1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1) }", "a {\n transform:\n matrix3d(\n 1, 0, 1, 0,\n 0, 1, 0, 0,\n 1, 0, 1, 0,\n 0, 0, 0, 1);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) }", "a {\n transform: scaleZ(1);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix3d(2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) }", "a {\n transform: scale3d(2, 1, 1);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix3d(1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) }", "a {\n transform: scale3d(1, 2, 1);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix3d(2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) }", "a {\n transform: scale3d(2, 2, 1);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix3d(2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) }", "a {\n transform: scale3d(2, 3, 1);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1) }", "a {\n transform: scaleZ(2);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix3d(1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 1) }", "a {\n transform: scale3d(1, 2, 3);\n}\n", "") expectPrintedMangle(t, "a { transform: matrix3d(2, 3, 0, 0, 4, 5, 0, 0, 0, 0, 1, 0, 6, 7, 0, 1) }", "a {\n transform:\n matrix3d(\n 2, 3, 0, 0,\n 4, 5, 0, 0,\n 0, 0, 1, 0,\n 6, 7, 0, 1);\n}\n", "") expectPrintedMangle(t, "a { transform: translate3d(0, 0, 0) }", "a {\n transform: translateZ(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translate3d(0%, 0%, 0) }", "a {\n transform: translateZ(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translate3d(0px, 0px, 0px) }", "a {\n transform: translateZ(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translate3d(1px, 0px, 0px) }", "a {\n transform: translate3d(1px, 0, 0);\n}\n", "") expectPrintedMangle(t, "a { transform: translate3d(0px, 1px, 0px) }", "a {\n transform: translate3d(0, 1px, 0);\n}\n", "") expectPrintedMangle(t, "a { transform: translate3d(0px, 0px, 1px) }", "a {\n transform: translateZ(1px);\n}\n", "") expectPrintedMangle(t, "a { transform: translate3d(1px, 2px, 3px) }", "a {\n transform: translate3d(1px, 2px, 3px);\n}\n", "") expectPrintedMangle(t, "a { transform: translate3d(1px, 0, 3px) }", "a {\n transform: translate3d(1px, 0, 3px);\n}\n", "") expectPrintedMangle(t, "a { transform: translate3d(0, 2px, 3px) }", "a {\n transform: translate3d(0, 2px, 3px);\n}\n", "") expectPrintedMangle(t, "a { transform: translate3d(1px, 2px, 0px) }", "a {\n transform: translate3d(1px, 2px, 0);\n}\n", "") expectPrintedMangle(t, "a { transform: translate3d(40%, 60%, 0px) }", "a {\n transform: translate3d(40%, 60%, 0);\n}\n", "") expectPrintedMangle(t, "a { transform: translateZ(0) }", "a {\n transform: translateZ(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translateZ(0px) }", "a {\n transform: translateZ(0);\n}\n", "") expectPrintedMangle(t, "a { transform: translateZ(1px) }", "a {\n transform: translateZ(1px);\n}\n", "") expectPrintedMangle(t, "a { transform: scale3d(1, 1, 1) }", "a {\n transform: scaleZ(1);\n}\n", "") expectPrintedMangle(t, "a { transform: scale3d(2, 1, 1) }", "a {\n transform: scale3d(2, 1, 1);\n}\n", "") expectPrintedMangle(t, "a { transform: scale3d(1, 2, 1) }", "a {\n transform: scale3d(1, 2, 1);\n}\n", "") expectPrintedMangle(t, "a { transform: scale3d(1, 1, 2) }", "a {\n transform: scaleZ(2);\n}\n", "") expectPrintedMangle(t, "a { transform: scale3d(1, 2, 3) }", "a {\n transform: scale3d(1, 2, 3);\n}\n", "") expectPrintedMangle(t, "a { transform: scale3d(2, 3, 1) }", "a {\n transform: scale3d(2, 3, 1);\n}\n", "") expectPrintedMangle(t, "a { transform: scale3d(2, 2, 1) }", "a {\n transform: scale3d(2, 2, 1);\n}\n", "") expectPrintedMangle(t, "a { transform: scale3d(3, 300%, 100.00%) }", "a {\n transform: scale3d(3, 3, 1);\n}\n", "") expectPrintedMangle(t, "a { transform: scale3d(1%, 2%, 3%) }", "a {\n transform: scale3d(1%, 2%, 3%);\n}\n", "") expectPrintedMangle(t, "a { transform: scaleZ(1) }", "a {\n transform: scaleZ(1);\n}\n", "") expectPrintedMangle(t, "a { transform: scaleZ(100%) }", "a {\n transform: scaleZ(1);\n}\n", "") expectPrintedMangle(t, "a { transform: scaleZ(2) }", "a {\n transform: scaleZ(2);\n}\n", "") expectPrintedMangle(t, "a { transform: scaleZ(200%) }", "a {\n transform: scaleZ(2);\n}\n", "") expectPrintedMangle(t, "a { transform: scaleZ(99%) }", "a {\n transform: scaleZ(99%);\n}\n", "") expectPrintedMangle(t, "a { transform: rotate3d(0, 0, 0, 0) }", "a {\n transform: rotate3d(0, 0, 0, 0);\n}\n", "") expectPrintedMangle(t, "a { transform: rotate3d(0, 0, 0, 0deg) }", "a {\n transform: rotate3d(0, 0, 0, 0);\n}\n", "") expectPrintedMangle(t, "a { transform: rotate3d(0, 0, 0, 45deg) }", "a {\n transform: rotate3d(0, 0, 0, 45deg);\n}\n", "") expectPrintedMangle(t, "a { transform: rotate3d(1, 0, 0, 45deg) }", "a {\n transform: rotateX(45deg);\n}\n", "") expectPrintedMangle(t, "a { transform: rotate3d(0, 1, 0, 45deg) }", "a {\n transform: rotateY(45deg);\n}\n", "") expectPrintedMangle(t, "a { transform: rotate3d(0, 0, 1, 45deg) }", "a {\n transform: rotate3d(0, 0, 1, 45deg);\n}\n", "") expectPrintedMangle(t, "a { transform: rotateX(0) }", "a {\n transform: rotateX(0);\n}\n", "") expectPrintedMangle(t, "a { transform: rotateX(0deg) }", "a {\n transform: rotateX(0);\n}\n", "") expectPrintedMangle(t, "a { transform: rotateX(1deg) }", "a {\n transform: rotateX(1deg);\n}\n", "") expectPrintedMangle(t, "a { transform: rotateY(0) }", "a {\n transform: rotateY(0);\n}\n", "") expectPrintedMangle(t, "a { transform: rotateY(0deg) }", "a {\n transform: rotateY(0);\n}\n", "") expectPrintedMangle(t, "a { transform: rotateY(1deg) }", "a {\n transform: rotateY(1deg);\n}\n", "") expectPrintedMangle(t, "a { transform: rotateZ(0) }", "a {\n transform: rotate(0);\n}\n", "") expectPrintedMangle(t, "a { transform: rotateZ(0deg) }", "a {\n transform: rotate(0);\n}\n", "") expectPrintedMangle(t, "a { transform: rotateZ(1deg) }", "a {\n transform: rotate(1deg);\n}\n", "") expectPrintedMangle(t, "a { transform: perspective(0) }", "a {\n transform: perspective(0);\n}\n", "") expectPrintedMangle(t, "a { transform: perspective(0px) }", "a {\n transform: perspective(0);\n}\n", "") expectPrintedMangle(t, "a { transform: perspective(1px) }", "a {\n transform: perspective(1px);\n}\n", "") } func TestMangleAlpha(t *testing.T) { alphas := []string{ "0", ".004", ".008", ".01", ".016", ".02", ".024", ".027", ".03", ".035", ".04", ".043", ".047", ".05", ".055", ".06", ".063", ".067", ".07", ".075", ".08", ".082", ".086", ".09", ".094", ".098", ".1", ".106", ".11", ".114", ".118", ".12", ".125", ".13", ".133", ".137", ".14", ".145", ".15", ".153", ".157", ".16", ".165", ".17", ".173", ".176", ".18", ".184", ".19", ".192", ".196", ".2", ".204", ".208", ".21", ".216", ".22", ".224", ".227", ".23", ".235", ".24", ".243", ".247", ".25", ".255", ".26", ".263", ".267", ".27", ".275", ".28", ".282", ".286", ".29", ".294", ".298", ".3", ".306", ".31", ".314", ".318", ".32", ".325", ".33", ".333", ".337", ".34", ".345", ".35", ".353", ".357", ".36", ".365", ".37", ".373", ".376", ".38", ".384", ".39", ".392", ".396", ".4", ".404", ".408", ".41", ".416", ".42", ".424", ".427", ".43", ".435", ".44", ".443", ".447", ".45", ".455", ".46", ".463", ".467", ".47", ".475", ".48", ".482", ".486", ".49", ".494", ".498", ".5", ".506", ".51", ".514", ".518", ".52", ".525", ".53", ".533", ".537", ".54", ".545", ".55", ".553", ".557", ".56", ".565", ".57", ".573", ".576", ".58", ".584", ".59", ".592", ".596", ".6", ".604", ".608", ".61", ".616", ".62", ".624", ".627", ".63", ".635", ".64", ".643", ".647", ".65", ".655", ".66", ".663", ".667", ".67", ".675", ".68", ".682", ".686", ".69", ".694", ".698", ".7", ".706", ".71", ".714", ".718", ".72", ".725", ".73", ".733", ".737", ".74", ".745", ".75", ".753", ".757", ".76", ".765", ".77", ".773", ".776", ".78", ".784", ".79", ".792", ".796", ".8", ".804", ".808", ".81", ".816", ".82", ".824", ".827", ".83", ".835", ".84", ".843", ".847", ".85", ".855", ".86", ".863", ".867", ".87", ".875", ".88", ".882", ".886", ".89", ".894", ".898", ".9", ".906", ".91", ".914", ".918", ".92", ".925", ".93", ".933", ".937", ".94", ".945", ".95", ".953", ".957", ".96", ".965", ".97", ".973", ".976", ".98", ".984", ".99", ".992", ".996", } for i, alpha := range alphas { expectPrintedLowerMangle(t, fmt.Sprintf("a { color: #%08X }", i), "a {\n color: rgba(0, 0, 0, "+alpha+");\n}\n", "") } // An alpha value of 100% does not use "rgba(...)" expectPrintedLowerMangle(t, "a { color: #000000FF }", "a {\n color: #000;\n}\n", "") } func TestMangleDuplicateSelectors(t *testing.T) { expectPrinted(t, "a, a { color: red }", "a,\na {\n color: red;\n}\n", "") expectPrintedMangle(t, "a, a { color: red }", "a {\n color: red;\n}\n", "") expectPrintedMangle(t, "a, b { color: red }", "a,\nb {\n color: red;\n}\n", "") expectPrintedMangle(t, "a, a.foo, a.foo, a.bar, a { color: red }", "a,\na.foo,\na.bar {\n color: red;\n}\n", "") expectPrintedMangle(t, "@media screen { a, a { color: red } }", "@media screen {\n a {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "@media screen { a, b { color: red } }", "@media screen {\n a,\n b {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "@media screen { a, a.foo, a.foo, a.bar, a { color: red } }", "@media screen {\n a,\n a.foo,\n a.bar {\n color: red;\n }\n}\n", "") } func TestMangleDuplicateSelectorRules(t *testing.T) { expectPrinted(t, "a { color: red } b { color: red }", "a {\n color: red;\n}\nb {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } b { color: red }", "a,\nb {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } div {} b { color: red }", "a,\nb {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } div { color: red } b { color: red }", "a,\ndiv,\nb {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } div { color: red } a { color: red }", "a,\ndiv {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } div { color: blue } b { color: red }", "a {\n color: red;\n}\ndiv {\n color: #00f;\n}\nb {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } div { color: blue } a { color: red }", "a {\n color: red;\n}\ndiv {\n color: #00f;\n}\na {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red; color: red } b { color: red }", "a,\nb {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } b { color: red; color: red }", "a,\nb {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } b { color: blue }", "a {\n color: red;\n}\nb {\n color: #00f;\n}\n", "") // Do not merge duplicates if they are "unsafe" expectPrintedMangle(t, "a { color: red } unknown { color: red }", "a {\n color: red;\n}\nunknown {\n color: red;\n}\n", "") expectPrintedMangle(t, "unknown { color: red } a { color: red }", "unknown {\n color: red;\n}\na {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } video { color: red }", "a {\n color: red;\n}\nvideo {\n color: red;\n}\n", "") expectPrintedMangle(t, "video { color: red } a { color: red }", "video {\n color: red;\n}\na {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } a:last-child { color: red }", "a {\n color: red;\n}\na:last-child {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } a[b=c i] { color: red }", "a {\n color: red;\n}\na[b=c i] {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } & { color: red }", "a {\n color: red;\n}\n& {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } a + b { color: red }", "a {\n color: red;\n}\na + b {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } a|b { color: red }", "a {\n color: red;\n}\na|b {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } a::hover { color: red }", "a {\n color: red;\n}\na::hover {\n color: red;\n}\n", "") // Still merge duplicates if they are "safe" expectPrintedMangle(t, "a { color: red } a:hover { color: red }", "a,\na:hover {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } a[b=c] { color: red }", "a,\na[b=c] {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } a#id { color: red }", "a,\na#id {\n color: red;\n}\n", "") expectPrintedMangle(t, "a { color: red } a.cls { color: red }", "a,\na.cls {\n color: red;\n}\n", "") // Skip over comments expectPrintedMangle(t, "c { color: green } a { color: red } /*!x*/ /*!y*/ b { color: blue }", "c {\n color: green;\n}\na {\n color: red;\n}\n/*!x*/\n/*!y*/\nb {\n color: #00f;\n}\n", "") expectPrintedMangle(t, "c { color: green } a { color: red } /*!x*/ /*!y*/ b { color: red }", "c {\n color: green;\n}\na,\nb {\n color: red;\n}\n/*!x*/\n/*!y*/\n", "") expectPrintedMangle(t, "c { color: green } a { color: red } /*!x*/ /*!y*/ a { color: red }", "c {\n color: green;\n}\na {\n color: red;\n}\n/*!x*/\n/*!y*/\n", "") } func TestMangleAtMedia(t *testing.T) { expectPrinted(t, "@media screen { @media screen { a { color: red } } }", "@media screen {\n @media screen {\n a {\n color: red;\n }\n }\n}\n", "") expectPrintedMangle(t, "@media screen { @media screen { a { color: red } } }", "@media screen {\n a {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "@media screen { @media not print { a { color: red } } }", "@media screen {\n @media not print {\n a {\n color: red;\n }\n }\n}\n", "") expectPrintedMangle(t, "@media screen { @media not print { @media screen { a { color: red } } } }", "@media screen {\n @media not print {\n a {\n color: red;\n }\n }\n}\n", "") expectPrintedMangle(t, "@media screen { a { color: red } @media screen { a { color: red } } }", "@media screen {\n a {\n color: red;\n }\n}\n", "") expectPrintedMangle(t, "@media screen { a { color: red } @media screen { a { color: blue } } }", "@media screen {\n a {\n color: red;\n }\n a {\n color: #00f;\n }\n}\n", "") expectPrintedMangle(t, "@media screen { .a { color: red; @media screen { .b { color: blue } } } }", "@media screen {\n .a {\n color: red;\n .b {\n color: #00f;\n }\n }\n}\n", "") expectPrintedMangle(t, "@media screen { a { color: red } } @media screen { b { color: red } }", "@media screen {\n a {\n color: red;\n }\n}\n@media screen {\n b {\n color: red;\n }\n}\n", "") } func TestFontWeight(t *testing.T) { expectPrintedMangle(t, "a { font-weight: normal }", "a {\n font-weight: 400;\n}\n", "") expectPrintedMangle(t, "a { font-weight: bold }", "a {\n font-weight: 700;\n}\n", "") expectPrintedMangle(t, "a { font-weight: 400 }", "a {\n font-weight: 400;\n}\n", "") expectPrintedMangle(t, "a { font-weight: bolder }", "a {\n font-weight: bolder;\n}\n", "") expectPrintedMangle(t, "a { font-weight: var(--var) }", "a {\n font-weight: var(--var);\n}\n", "") expectPrintedMangleMinify(t, "a { font-weight: normal }", "a{font-weight:400}", "") } func TestFontFamily(t *testing.T) { expectPrintedMangle(t, "a {font-family: aaa }", "a {\n font-family: aaa;\n}\n", "") expectPrintedMangle(t, "a {font-family: serif }", "a {\n font-family: serif;\n}\n", "") expectPrintedMangle(t, "a {font-family: 'serif' }", "a {\n font-family: \"serif\";\n}\n", "") expectPrintedMangle(t, "a {font-family: aaa bbb, serif }", "a {\n font-family: aaa bbb, serif;\n}\n", "") expectPrintedMangle(t, "a {font-family: 'aaa', serif }", "a {\n font-family: aaa, serif;\n}\n", "") expectPrintedMangle(t, "a {font-family: '\"', serif }", "a {\n font-family: '\"', serif;\n}\n", "") expectPrintedMangle(t, "a {font-family: 'aaa ', serif }", "a {\n font-family: \"aaa \", serif;\n}\n", "") expectPrintedMangle(t, "a {font-family: 'aaa bbb', serif }", "a {\n font-family: aaa bbb, serif;\n}\n", "") expectPrintedMangle(t, "a {font-family: 'aaa bbb', 'ccc ddd' }", "a {\n font-family: aaa bbb, ccc ddd;\n}\n", "") expectPrintedMangle(t, "a {font-family: 'aaa bbb', serif }", "a {\n font-family: \"aaa bbb\", serif;\n}\n", "") expectPrintedMangle(t, "a {font-family: 'aaa serif' }", "a {\n font-family: \"aaa serif\";\n}\n", "") expectPrintedMangle(t, "a {font-family: 'aaa bbb', var(--var) }", "a {\n font-family: \"aaa bbb\", var(--var);\n}\n", "") expectPrintedMangle(t, "a {font-family: 'aaa bbb', }", "a {\n font-family: \"aaa bbb\", ;\n}\n", "") expectPrintedMangle(t, "a {font-family: , 'aaa bbb' }", "a {\n font-family: , \"aaa bbb\";\n}\n", "") expectPrintedMangle(t, "a {font-family: 'aaa',, 'bbb' }", "a {\n font-family:\n \"aaa\",,\n \"bbb\";\n}\n", "") expectPrintedMangle(t, "a {font-family: 'aaa bbb', x serif }", "a {\n font-family: \"aaa bbb\", x serif;\n}\n", "") expectPrintedMangleMinify(t, "a {font-family: 'aaa bbb', serif }", "a{font-family:aaa bbb,serif}", "") expectPrintedMangleMinify(t, "a {font-family: 'aaa bbb', 'ccc ddd' }", "a{font-family:aaa bbb,ccc ddd}", "") expectPrintedMangleMinify(t, "a {font-family: 'initial', serif;}", "a{font-family:\"initial\",serif}", "") expectPrintedMangleMinify(t, "a {font-family: 'inherit', serif;}", "a{font-family:\"inherit\",serif}", "") expectPrintedMangleMinify(t, "a {font-family: 'unset', serif;}", "a{font-family:\"unset\",serif}", "") expectPrintedMangleMinify(t, "a {font-family: 'revert', serif;}", "a{font-family:\"revert\",serif}", "") expectPrintedMangleMinify(t, "a {font-family: 'revert-layer', 'Segoe UI', serif;}", "a{font-family:\"revert-layer\",Segoe UI,serif}", "") expectPrintedMangleMinify(t, "a {font-family: 'default', serif;}", "a{font-family:\"default\",serif}", "") } func TestFont(t *testing.T) { expectPrintedMangle(t, "a { font: caption }", "a {\n font: caption;\n}\n", "") expectPrintedMangle(t, "a { font: normal 1px }", "a {\n font: normal 1px;\n}\n", "") expectPrintedMangle(t, "a { font: normal bold }", "a {\n font: normal bold;\n}\n", "") expectPrintedMangle(t, "a { font: 1rem 'aaa bbb' }", "a {\n font: 1rem aaa bbb;\n}\n", "") expectPrintedMangle(t, "a { font: 1rem/1.2 'aaa bbb' }", "a {\n font: 1rem/1.2 aaa bbb;\n}\n", "") expectPrintedMangle(t, "a { font: normal 1rem 'aaa bbb' }", "a {\n font: 1rem aaa bbb;\n}\n", "") expectPrintedMangle(t, "a { font: normal 1rem 'aaa bbb', serif }", "a {\n font: 1rem aaa bbb, serif;\n}\n", "") expectPrintedMangle(t, "a { font: italic small-caps bold ultra-condensed 1rem/1.2 'aaa bbb' }", "a {\n font: italic small-caps 700 ultra-condensed 1rem/1.2 aaa bbb;\n}\n", "") expectPrintedMangle(t, "a { font: oblique 1px 'aaa bbb' }", "a {\n font: oblique 1px aaa bbb;\n}\n", "") expectPrintedMangle(t, "a { font: oblique 45deg 1px 'aaa bbb' }", "a {\n font: oblique 45deg 1px aaa bbb;\n}\n", "") expectPrintedMangle(t, "a { font: var(--var) 'aaa bbb' }", "a {\n font: var(--var) \"aaa bbb\";\n}\n", "") expectPrintedMangle(t, "a { font: normal var(--var) 'aaa bbb' }", "a {\n font: normal var(--var) \"aaa bbb\";\n}\n", "") expectPrintedMangle(t, "a { font: normal 1rem var(--var), 'aaa bbb' }", "a {\n font: normal 1rem var(--var), \"aaa bbb\";\n}\n", "") expectPrintedMangleMinify(t, "a { font: italic small-caps bold ultra-condensed 1rem/1.2 'aaa bbb' }", "a{font:italic small-caps 700 ultra-condensed 1rem/1.2 aaa bbb}", "") expectPrintedMangleMinify(t, "a { font: italic small-caps bold ultra-condensed 1rem / 1.2 'aaa bbb' }", "a{font:italic small-caps 700 ultra-condensed 1rem/1.2 aaa bbb}", "") // See: path_to_url expectPrinted(t, "a { font: 10px'foo' }", "a {\n font: 10px\"foo\";\n}\n", "") expectPrinted(t, "a { font: 10px'123' }", "a {\n font: 10px\"123\";\n}\n", "") expectPrintedMangle(t, "a { font: 10px'foo' }", "a {\n font: 10px foo;\n}\n", "") expectPrintedMangle(t, "a { font: 10px'123' }", "a {\n font: 10px\"123\";\n}\n", "") expectPrintedMangleMinify(t, "a { font: 10px'foo' }", "a{font:10px foo}", "") expectPrintedMangleMinify(t, "a { font: 10px'123' }", "a{font:10px\"123\"}", "") } func TestWarningUnexpectedCloseBrace(t *testing.T) { expectPrinted(t, ".red {\n color: red;\n}\n}\n.blue {\n color: blue;\n}\n.green {\n color: green;\n}\n", `.red { color: red; } } .blue { color: blue; } .green { color: green; } `, `<stdin>: WARNING: Unexpected "}" `) } func TestPropertyTypoWarning(t *testing.T) { expectPrinted(t, "a { z-idnex: 0 }", "a {\n z-idnex: 0;\n}\n", "<stdin>: WARNING: \"z-idnex\" is not a known CSS property\nNOTE: Did you mean \"z-index\" instead?\n") expectPrinted(t, "a { x-index: 0 }", "a {\n x-index: 0;\n}\n", "<stdin>: WARNING: \"x-index\" is not a known CSS property\nNOTE: Did you mean \"z-index\" instead?\n") // CSS variables should not be corrected expectPrinted(t, "a { --index: 0 }", "a {\n --index: 0 ;\n}\n", "") // Short names should not be corrected ("alt" is actually valid in WebKit, and should not become "all") expectPrinted(t, "a { alt: \"\" }", "a {\n alt: \"\";\n}\n", "") } func TestParseErrorRecovery(t *testing.T) { expectPrinted(t, "x { y: z", "x {\n y: z;\n}\n", "<stdin>: WARNING: Expected \"}\" to go with \"{\"\n<stdin>: NOTE: The unbalanced \"{\" is here:\n") expectPrinted(t, "x { y: (", "x {\n y: ();\n}\n", "<stdin>: WARNING: Expected \")\" to go with \"(\"\n<stdin>: NOTE: The unbalanced \"(\" is here:\n") expectPrinted(t, "x { y: [", "x {\n y: [];\n}\n", "<stdin>: WARNING: Expected \"]\" to go with \"[\"\n<stdin>: NOTE: The unbalanced \"[\" is here:\n") expectPrinted(t, "x { y: {", "x {\n y: {\n }\n}\n", "<stdin>: WARNING: Expected identifier but found whitespace\n<stdin>: WARNING: Expected \"}\" to go with \"{\"\n<stdin>: NOTE: The unbalanced \"{\" is here:\n") expectPrinted(t, "x { y: z(", "x {\n y: z();\n}\n", "<stdin>: WARNING: Expected \")\" to go with \"(\"\n<stdin>: NOTE: The unbalanced \"(\" is here:\n") expectPrinted(t, "x { y: z(abc", "x {\n y: z(abc);\n}\n", "<stdin>: WARNING: Expected \")\" to go with \"(\"\n<stdin>: NOTE: The unbalanced \"(\" is here:\n") expectPrinted(t, "x { y: url(", "x {\n y: url();\n}\n", "<stdin>: WARNING: Expected \")\" to end URL token\n<stdin>: NOTE: The unbalanced \"(\" is here:\n<stdin>: WARNING: Expected \"}\" to go with \"{\"\n<stdin>: NOTE: The unbalanced \"{\" is here:\n") expectPrinted(t, "x { y: url(abc", "x {\n y: url(abc);\n}\n", "<stdin>: WARNING: Expected \")\" to end URL token\n<stdin>: NOTE: The unbalanced \"(\" is here:\n<stdin>: WARNING: Expected \"}\" to go with \"{\"\n<stdin>: NOTE: The unbalanced \"{\" is here:\n") expectPrinted(t, "x { y: url(; }", "x {\n y: url(; };\n}\n", "<stdin>: WARNING: Expected \")\" to end URL token\n<stdin>: NOTE: The unbalanced \"(\" is here:\n<stdin>: WARNING: Expected \"}\" to go with \"{\"\n<stdin>: NOTE: The unbalanced \"{\" is here:\n") expectPrinted(t, "x { y: url(abc;", "x {\n y: url(abc;);\n}\n", "<stdin>: WARNING: Expected \")\" to end URL token\n<stdin>: NOTE: The unbalanced \"(\" is here:\n<stdin>: WARNING: Expected \"}\" to go with \"{\"\n<stdin>: NOTE: The unbalanced \"{\" is here:\n") expectPrinted(t, "/* @license */ x {} /* @preserve", "/* @license */\nx {\n}\n", "<stdin>: ERROR: Expected \"*/\" to terminate multi-line comment\n<stdin>: NOTE: The multi-line comment starts here:\n") expectPrinted(t, "a { b: c; d: 'e\n f: g; h: i }", "a {\n b: c;\n d: 'e\n f: g;\n h: i;\n}\n", "<stdin>: WARNING: Unterminated string token\n") expectPrintedMinify(t, "a { b: c; d: 'e\n f: g; h: i }", "a{b:c;d:'e\nf: g;h:i}", "<stdin>: WARNING: Unterminated string token\n") } func TestPrefixInsertion(t *testing.T) { // General "-webkit-" tests for _, key := range []string{ "backdrop-filter", "box-decoration-break", "clip-path", "font-kerning", "initial-letter", "mask-image", "mask-origin", "mask-position", "mask-repeat", "mask-size", "print-color-adjust", "text-decoration-skip", "text-emphasis-color", "text-emphasis-position", "text-emphasis-style", "text-orientation", } { expectPrintedWithAllPrefixes(t, "a { "+key+": url(x.png) }", "a {\n -webkit-"+key+": url(x.png);\n "+key+": url(x.png);\n}\n", "") expectPrintedWithAllPrefixes(t, "a { before: value; "+key+": url(x.png) }", "a {\n before: value;\n -webkit-"+key+": url(x.png);\n "+key+": url(x.png);\n}\n", "") expectPrintedWithAllPrefixes(t, "a { "+key+": url(x.png); after: value }", "a {\n -webkit-"+key+": url(x.png);\n "+key+": url(x.png);\n after: value;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { before: value; "+key+": url(x.png); after: value }", "a {\n before: value;\n -webkit-"+key+": url(x.png);\n "+key+": url(x.png);\n after: value;\n}\n", "") expectPrintedWithAllPrefixes(t, "a {\n -webkit-"+key+": url(x.png);\n "+key+": url(y.png);\n}\n", "a {\n -webkit-"+key+": url(x.png);\n "+key+": url(y.png);\n}\n", "") expectPrintedWithAllPrefixes(t, "a {\n "+key+": url(y.png);\n -webkit-"+key+": url(x.png);\n}\n", "a {\n "+key+": url(y.png);\n -webkit-"+key+": url(x.png);\n}\n", "") expectPrintedWithAllPrefixes(t, "a { "+key+": url(x.png); "+key+": url(y.png) }", "a {\n -webkit-"+key+": url(x.png);\n "+key+": url(x.png);\n -webkit-"+key+": url(y.png);\n "+key+": url(y.png);\n}\n", "") } // Special-case tests expectPrintedWithAllPrefixes(t, "a { appearance: none }", "a {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { background-clip: not-text }", "a {\n background-clip: not-text;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { background-clip: text !important }", "a {\n -webkit-background-clip: text !important;\n -ms-background-clip: text !important;\n background-clip: text !important;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { background-clip: text }", "a {\n -webkit-background-clip: text;\n -ms-background-clip: text;\n background-clip: text;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { hyphens: auto }", "a {\n -webkit-hyphens: auto;\n -moz-hyphens: auto;\n -ms-hyphens: auto;\n hyphens: auto;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { position: absolute }", "a {\n position: absolute;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { position: sticky !important }", "a {\n position: -webkit-sticky !important;\n position: sticky !important;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { position: sticky }", "a {\n position: -webkit-sticky;\n position: sticky;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { tab-size: 2 }", "a {\n -moz-tab-size: 2;\n -o-tab-size: 2;\n tab-size: 2;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { text-decoration-color: none }", "a {\n -webkit-text-decoration-color: none;\n -moz-text-decoration-color: none;\n text-decoration-color: none;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { text-decoration-line: none }", "a {\n -webkit-text-decoration-line: none;\n -moz-text-decoration-line: none;\n text-decoration-line: none;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { text-size-adjust: none }", "a {\n -webkit-text-size-adjust: none;\n -ms-text-size-adjust: none;\n text-size-adjust: none;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { user-select: none }", "a {\n -webkit-user-select: none;\n -khtml-user-select: none;\n -moz-user-select: -moz-none;\n -ms-user-select: none;\n user-select: none;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { mask-composite: add, subtract, intersect, exclude }", "a {\n -webkit-mask-composite:\n source-over,\n source-out,\n source-in,\n xor;\n mask-composite:\n add,\n subtract,\n intersect,\n exclude;\n}\n", "") // Check that we insert prefixed rules each time an unprefixed rule is // encountered. This matches the behavior of the popular "autoprefixer" tool. expectPrintedWithAllPrefixes(t, "a { before: value; mask-image: a; middle: value; mask-image: b; after: value }", "a {\n before: value;\n -webkit-mask-image: a;\n mask-image: a;\n middle: value;\n -webkit-mask-image: b;\n mask-image: b;\n after: value;\n}\n", "") // Test that we don't insert duplicated rules when source code is processed // twice. This matches the behavior of the popular "autoprefixer" tool. expectPrintedWithAllPrefixes(t, "a { before: value; -webkit-text-size-adjust: 1; -ms-text-size-adjust: 2; text-size-adjust: 3; after: value }", "a {\n before: value;\n -webkit-text-size-adjust: 1;\n -ms-text-size-adjust: 2;\n text-size-adjust: 3;\n after: value;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { before: value; -webkit-text-size-adjust: 1; text-size-adjust: 3; after: value }", "a {\n before: value;\n -webkit-text-size-adjust: 1;\n -ms-text-size-adjust: 3;\n text-size-adjust: 3;\n after: value;\n}\n", "") expectPrintedWithAllPrefixes(t, "a { before: value; -ms-text-size-adjust: 2; text-size-adjust: 3; after: value }", "a {\n before: value;\n -ms-text-size-adjust: 2;\n -webkit-text-size-adjust: 3;\n text-size-adjust: 3;\n after: value;\n}\n", "") } func TestNthChild(t *testing.T) { for _, nth := range []string{"nth-child", "nth-last-child"} { expectPrinted(t, ":"+nth+"(x) {}", ":"+nth+"(x) {\n}\n", "<stdin>: WARNING: Unexpected \"x\"\n") expectPrinted(t, ":"+nth+"(1e2) {}", ":"+nth+"(1e2) {\n}\n", "<stdin>: WARNING: Unexpected \"1e2\"\n") expectPrinted(t, ":"+nth+"(-n-) {}", ":"+nth+"(-n-) {\n}\n", "<stdin>: WARNING: Expected number but found \")\"\n") expectPrinted(t, ":"+nth+"(-nn) {}", ":"+nth+"(-nn) {\n}\n", "<stdin>: WARNING: Unexpected \"-nn\"\n") expectPrinted(t, ":"+nth+"(-n-n) {}", ":"+nth+"(-n-n) {\n}\n", "<stdin>: WARNING: Unexpected \"-n-n\"\n") expectPrinted(t, ":"+nth+"(-2n-) {}", ":"+nth+"(-2n-) {\n}\n", "<stdin>: WARNING: Expected number but found \")\"\n") expectPrinted(t, ":"+nth+"(-2n-2n) {}", ":"+nth+"(-2n-2n) {\n}\n", "<stdin>: WARNING: Unexpected \"-2n-2n\"\n") expectPrinted(t, ":"+nth+"(+) {}", ":"+nth+"(+) {\n}\n", "<stdin>: WARNING: Unexpected \")\"\n") expectPrinted(t, ":"+nth+"(-) {}", ":"+nth+"(-) {\n}\n", "<stdin>: WARNING: Unexpected \"-\"\n") expectPrinted(t, ":"+nth+"(+ 2) {}", ":"+nth+"(+ 2) {\n}\n", "<stdin>: WARNING: Unexpected whitespace\n") expectPrinted(t, ":"+nth+"(- 2) {}", ":"+nth+"(- 2) {\n}\n", "<stdin>: WARNING: Unexpected \"-\"\n") expectPrinted(t, ":"+nth+"(0) {}", ":"+nth+"(0) {\n}\n", "") expectPrinted(t, ":"+nth+"(0 ) {}", ":"+nth+"(0) {\n}\n", "") expectPrinted(t, ":"+nth+"( 0) {}", ":"+nth+"(0) {\n}\n", "") expectPrinted(t, ":"+nth+"(00) {}", ":"+nth+"(0) {\n}\n", "") expectPrinted(t, ":"+nth+"(01) {}", ":"+nth+"(1) {\n}\n", "") expectPrinted(t, ":"+nth+"(0n) {}", ":"+nth+"(0n) {\n}\n", "") expectPrinted(t, ":"+nth+"(n) {}", ":"+nth+"(n) {\n}\n", "") expectPrinted(t, ":"+nth+"(-n) {}", ":"+nth+"(-n) {\n}\n", "") expectPrinted(t, ":"+nth+"(1n) {}", ":"+nth+"(n) {\n}\n", "") expectPrinted(t, ":"+nth+"(-1n) {}", ":"+nth+"(-n) {\n}\n", "") expectPrinted(t, ":"+nth+"(2n) {}", ":"+nth+"(2n) {\n}\n", "") expectPrinted(t, ":"+nth+"(-2n) {}", ":"+nth+"(-2n) {\n}\n", "") expectPrinted(t, ":"+nth+"(odd) {}", ":"+nth+"(odd) {\n}\n", "") expectPrinted(t, ":"+nth+"(odd ) {}", ":"+nth+"(odd) {\n}\n", "") expectPrinted(t, ":"+nth+"( odd) {}", ":"+nth+"(odd) {\n}\n", "") expectPrinted(t, ":"+nth+"(even) {}", ":"+nth+"(even) {\n}\n", "") expectPrinted(t, ":"+nth+"(even ) {}", ":"+nth+"(even) {\n}\n", "") expectPrinted(t, ":"+nth+"( even) {}", ":"+nth+"(even) {\n}\n", "") expectPrinted(t, ":"+nth+"(n+3) {}", ":"+nth+"(n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"(n-3) {}", ":"+nth+"(n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"(n +3) {}", ":"+nth+"(n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"(n -3) {}", ":"+nth+"(n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"(n+ 3) {}", ":"+nth+"(n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"(n- 3) {}", ":"+nth+"(n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"( n + 3 ) {}", ":"+nth+"(n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"( n - 3 ) {}", ":"+nth+"(n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"(+n+3) {}", ":"+nth+"(n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"(+n-3) {}", ":"+nth+"(n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"(-n+3) {}", ":"+nth+"(-n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"(-n-3) {}", ":"+nth+"(-n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"( +n + 3 ) {}", ":"+nth+"(n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"( +n - 3 ) {}", ":"+nth+"(n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"( -n + 3 ) {}", ":"+nth+"(-n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"( -n - 3 ) {}", ":"+nth+"(-n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"(2n+3) {}", ":"+nth+"(2n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"(2n-3) {}", ":"+nth+"(2n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"(2n +3) {}", ":"+nth+"(2n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"(2n -3) {}", ":"+nth+"(2n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"(2n+ 3) {}", ":"+nth+"(2n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"(2n- 3) {}", ":"+nth+"(2n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"( 2n + 3 ) {}", ":"+nth+"(2n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"( 2n - 3 ) {}", ":"+nth+"(2n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"(+2n+3) {}", ":"+nth+"(2n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"(+2n-3) {}", ":"+nth+"(2n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"(-2n+3) {}", ":"+nth+"(-2n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"(-2n-3) {}", ":"+nth+"(-2n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"( +2n + 3 ) {}", ":"+nth+"(2n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"( +2n - 3 ) {}", ":"+nth+"(2n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"( -2n + 3 ) {}", ":"+nth+"(-2n+3) {\n}\n", "") expectPrinted(t, ":"+nth+"( -2n - 3 ) {}", ":"+nth+"(-2n-3) {\n}\n", "") expectPrinted(t, ":"+nth+"(2n of + .foo) {}", ":"+nth+"(2n of + .foo) {\n}\n", "<stdin>: WARNING: Unexpected \"+\"\n") expectPrinted(t, ":"+nth+"(2n of .foo, ~.bar) {}", ":"+nth+"(2n of .foo, ~.bar) {\n}\n", "<stdin>: WARNING: Unexpected \"~\"\n") expectPrinted(t, ":"+nth+"(2n of .foo) {}", ":"+nth+"(2n of .foo) {\n}\n", "") expectPrinted(t, ":"+nth+"(2n of.foo+.bar) {}", ":"+nth+"(2n of .foo + .bar) {\n}\n", "") expectPrinted(t, ":"+nth+"(2n of[href]) {}", ":"+nth+"(2n of [href]) {\n}\n", "") expectPrinted(t, ":"+nth+"(2n of.foo,.bar) {}", ":"+nth+"(2n of .foo, .bar) {\n}\n", "") expectPrinted(t, ":"+nth+"(2n of .foo, .bar) {}", ":"+nth+"(2n of .foo, .bar) {\n}\n", "") expectPrinted(t, ":"+nth+"(2n of .foo , .bar ) {}", ":"+nth+"(2n of .foo, .bar) {\n}\n", "") expectPrintedMinify(t, ":"+nth+"(2n of [foo] , [bar] ) {}", ":"+nth+"(2n of[foo],[bar]){}", "") expectPrintedMinify(t, ":"+nth+"(2n of .foo , .bar ) {}", ":"+nth+"(2n of.foo,.bar){}", "") expectPrintedMinify(t, ":"+nth+"(2n of #foo , #bar ) {}", ":"+nth+"(2n of#foo,#bar){}", "") expectPrintedMinify(t, ":"+nth+"(2n of :foo , :bar ) {}", ":"+nth+"(2n of:foo,:bar){}", "") expectPrintedMinify(t, ":"+nth+"(2n of div , span ) {}", ":"+nth+"(2n of div,span){}", "") expectPrintedMangle(t, ":"+nth+"(even) { color: red }", ":"+nth+"(2n) {\n color: red;\n}\n", "") expectPrintedMangle(t, ":"+nth+"(2n+1) { color: red }", ":"+nth+"(odd) {\n color: red;\n}\n", "") expectPrintedMangle(t, ":"+nth+"(0n) { color: red }", ":"+nth+"(0) {\n color: red;\n}\n", "") expectPrintedMangle(t, ":"+nth+"(0n+0) { color: red }", ":"+nth+"(0) {\n color: red;\n}\n", "") expectPrintedMangle(t, ":"+nth+"(1n+0) { color: red }", ":"+nth+"(n) {\n color: red;\n}\n", "") expectPrintedMangle(t, ":"+nth+"(0n-2) { color: red }", ":"+nth+"(-2) {\n color: red;\n}\n", "") expectPrintedMangle(t, ":"+nth+"(0n+2) { color: red }", ":"+nth+"(2) {\n color: red;\n}\n", "") } for _, nth := range []string{"nth-of-type", "nth-last-of-type"} { expectPrinted(t, ":"+nth+"(2n of .foo) {}", ":"+nth+"(2n of .foo) {\n}\n", "<stdin>: WARNING: Expected \")\" to go with \"(\"\n<stdin>: NOTE: The unbalanced \"(\" is here:\n") expectPrinted(t, ":"+nth+"(+2n + 1) {}", ":"+nth+"(2n+1) {\n}\n", "") } } func TestComposes(t *testing.T) { expectPrinted(t, ".foo { composes: bar; color: red }", ".foo {\n composes: bar;\n color: red;\n}\n", "") expectPrinted(t, ".foo .bar { composes: bar; color: red }", ".foo .bar {\n composes: bar;\n color: red;\n}\n", "") expectPrinted(t, ".foo, .bar { composes: bar; color: red }", ".foo,\n.bar {\n composes: bar;\n color: red;\n}\n", "") expectPrintedLocal(t, ".foo { composes: bar; color: red }", ".foo {\n color: red;\n}\n", "") expectPrintedLocal(t, ".foo { composes: bar baz; color: red }", ".foo {\n color: red;\n}\n", "") expectPrintedLocal(t, ".foo { composes: bar from global; color: red }", ".foo {\n color: red;\n}\n", "") expectPrintedLocal(t, ".foo { composes: bar from \"file.css\"; color: red }", ".foo {\n color: red;\n}\n", "") expectPrintedLocal(t, ".foo { composes: bar from url(file.css); color: red }", ".foo {\n color: red;\n}\n", "") expectPrintedLocal(t, ".foo { & { composes: bar; color: red } }", ".foo {\n & {\n color: red;\n }\n}\n", "") expectPrintedLocal(t, ".foo { :local { composes: bar; color: red } }", ".foo {\n color: red;\n}\n", "") expectPrintedLocal(t, ".foo { :global { composes: bar; color: red } }", ".foo {\n color: red;\n}\n", "") expectPrinted(t, ".foo, .bar { composes: bar from github }", ".foo,\n.bar {\n composes: bar from github;\n}\n", "") expectPrintedLocal(t, ".foo { composes: bar from github }", ".foo {\n}\n", "<stdin>: WARNING: \"composes\" declaration uses invalid location \"github\"\n") badComposes := "<stdin>: WARNING: \"composes\" only works inside single class selectors\n" + "<stdin>: NOTE: The parent selector is not a single class selector because of the syntax here:\n" expectPrintedLocal(t, "& { composes: bar; color: red }", "& {\n color: red;\n}\n", badComposes) expectPrintedLocal(t, ".foo& { composes: bar; color: red }", "&.foo {\n color: red;\n}\n", badComposes) expectPrintedLocal(t, ".foo.bar { composes: bar; color: red }", ".foo.bar {\n color: red;\n}\n", badComposes) expectPrintedLocal(t, ".foo:hover { composes: bar; color: red }", ".foo:hover {\n color: red;\n}\n", badComposes) expectPrintedLocal(t, ".foo[href] { composes: bar; color: red }", ".foo[href] {\n color: red;\n}\n", badComposes) expectPrintedLocal(t, ".foo .bar { composes: bar; color: red }", ".foo .bar {\n color: red;\n}\n", badComposes) expectPrintedLocal(t, ".foo, div { composes: bar; color: red }", ".foo,\ndiv {\n color: red;\n}\n", badComposes) expectPrintedLocal(t, ".foo { .bar { composes: foo; color: red } }", ".foo {\n .bar {\n color: red;\n }\n}\n", badComposes) } ```
Caloptilia syngenica is a moth of the family Gracillariidae. It is known from South Africa. References Endemic moths of South Africa syngenica Moths of Africa Moths described in 1961
I Love Lucy is an American television sitcom that originally aired on CBS from October 15, 1951, to May 6, 1957, with a total of 180 half-hour episodes, spanning six seasons. The show starred Lucille Ball, her husband, Desi Arnaz, along with Vivian Vance and William Frawley. The series follows the life of Lucy Ricardo (Ball), a young, middle-class housewife living in New York City, who often concocts plans with her best friends and landlords, Ethel and Fred Mertz (Vance and Frawley), to appear alongside her bandleader husband, Ricky Ricardo (Arnaz), in his nightclub. Lucy is depicted trying numerous schemes to mingle with and be a part of show business. After the series ended in 1957, a modified version of the show continued for three more seasons, with 13 one-hour specials, which ran from 1957 to 1960. It was first known as The Lucille Ball–Desi Arnaz Show, and later, in reruns, as The Lucy–Desi Comedy Hour. I Love Lucy became the most-watched show in the United States in four of its six seasons and it was the first to end its run at the top of the Nielsen ratings. As of 2011, episodes of the show have been syndicated in dozens of languages across the world and remain popular with an American audience of 40 million each year. A colorized version of its Christmas episode attracted more than eight million viewers when CBS aired it in prime time in 2013, 62 years after the show premiered. CBS has aired two to three colorized episodes each year since then, once at Christmas and again in the spring. The show – which was the first scripted television program to be filmed on 35 mm film in front of a studio audience, by cinematographer Karl Freund – won five Emmy Awards and received many nominations and honors. It was the first show to feature an ensemble cast. As such, it is often regarded as both one of the greatest and most influential sitcoms in history. In 2012, it was voted the 'Best TV Show of All Time' in a survey conducted by ABC News and People magazine. In 2013, the Writers Guild of America ranked it #12 on their list of the 101 Best Written TV Series. Premise Originally set in an apartment building in New York City, I Love Lucy centers on Lucy Ricardo (Lucille Ball) and her singer/bandleader husband, Ricky Ricardo (Desi Arnaz), along with their best friends and landlords, Fred Mertz (William Frawley) and Ethel Mertz (Vivian Vance). During the second season, Lucy and Ricky have a son named Ricky Ricardo Jr. ("Little Ricky"), whose birth was timed to coincide with the real-life birth of Ball's son, Desi Arnaz Jr. Lucy is naïve and ambitious, with a zealotry for stardom and a knack for getting both herself and her husband into trouble whenever she yearns to make it big in show business. The Ricardos' best friends, Fred and Ethel, are former vaudevillians. The Mertz's history in entertainment only strengthens Lucy's resolve to prove herself as a performer, though she often feels excluded, as her industry involvement is limited, relative to that of Ricky, Fred, and Ethel. Though charismatic, throughout the series, she is depicted as having few marketable performance skills, and she is often portrayed as being tone deaf, struggling to sing anything other than off-key renditions of songs such as "Glow Worm" on the saxophone, and many of her performances end in disaster. However, to say she is completely without talent would be untrue, as on occasion, she is shown to be a good dancer and a competent singer. She is also at least twice offered contracts by television or film companies—first in the season 1 episode "The Audition", when she replaces an injured clown in Ricky's act at the Tropicana nightclub, and later in the season 5 episode "Lucy and the Dummy", when she dances in Hollywood for a studio party using a rubber Ricky dummy as her dancing partner. Little information was offered about Lucy's past. A few episodes mentioned that she was born in Jamestown, New York (Ball's real-life home town), later specified to be West Jamestown, that she graduated from Jamestown High School, that her maiden name was "McGillicuddy" (indicating a Scottish or Irish ethnicity, at least on her father's side, though she once mentioned her grandmother was Swedish), and that she met Ricky on a boat cruise with her friend from an agency she once worked for. Her family was absent, other than occasional appearances by her scatter-brained mother Mrs. McGillicuddy (Kathryn Card), who could never get Ricky's name right. Lucy was also secretive about her age and true hair color, and tended to be careless with money, in addition to being somewhat materialistic, insisting on buying new dresses and hats for every occasion and telling old friends that she and Ricky were wealthy. She was also depicted as a devoted housewife, adept cook, and attentive mother. As part of Lucy's role was to care for her husband, she stayed at home and took care of the household chores, while her husband Ricky went to work. During the post war era, Lucy took jobs outside of the home, but in these jobs, the show portrayed her as being inept outside of her usual domestic duties. Lucy's husband, Ricky Ricardo, is an up-and-coming Cuban American singer and bandleader with an excitable personality. His patience is frequently tested by his wife's antics trying to get into showbiz, along with her exorbitant spending on clothes and furniture. When exasperated, he often reverts to speaking rapidly in Spanish. As with Lucy, not much is revealed about his past or family. Ricky's mother (played by actress Mary Emery) appears in two episodes; in another, Lucy mentions that he has five brothers. Ricky also mentions that he had been "practically raised" by his Uncle Alberto (who was seen during a family visit to Cuba), and that he had attended the University of Havana. An extended flashback segment in the 1957 episode "Lucy Takes a Cruise to Havana" of The Lucille Ball–Desi Arnaz Show filled in numerous details of how Lucy and Ricky met and how Ricky came to the United States. The story, at least insofar as related to newspaper columnist Hedda Hopper, is that the couple met in Havana when Lucy and the Mertzes vacationed there in 1940. Despite his being a university graduate and proficient in English, Ricky is portrayed as a driver of a horse-drawn cab who waits for fares at a pier where tourists arrive by ship. Ricky is hired to serve as one of Lucy's tour guides, and the two fall in love. Having coincidentally also met popular singer, Rudy Vallée, on the cruise ship, Lucy arranges an audition for Ricky, who is hired to be in Vallée's orchestra, thus allowing him to emigrate to the United States on the very ship on which Lucy and the Mertzes were returning. Lucy later states that Ricky played for Vallée only one night before being traded to Xavier Cugat's orchestra. The extended flashback segment "Lucy Takes a Cruise to Havana" and the story of how Lucy and Ricky met is inconsistent with the season 4 episode "Don Juan and the Starlets". At one point in that episode, Lucy, after finding out that she was not invited to join Ricky at a movie premiere, bemoans that she made a mistake fifteen years before when her friend Marion Strong asked her if she would like to go on a blind date with a Cuban drummer, to which she said "yes." Throughout the series, Lucy is usually found with her best friend, Ethel. A former model from Albuquerque, New Mexico, Ethel tries to relive her glory days in vaudeville. Ricky is more inclined to include Ethel in performances at his nightclub because, unlike Lucy, she can sing and dance rather well. The show mentions that Ethel's husband, Fred, served in World War I, and lived through the Great Depression. As such, in the series, Fred is depicted as being very stingy with money and as being an irascible, no-nonsense type. However, he also reveals that he can be a soft touch, especially when it comes to Little Ricky, to whom Fred is both godfather and honorary "uncle." Fred can also sing and dance, and he often performs duets with Ethel. The Manhattan building they all lived in before their move to Westport, Connecticut during the sixth season, was addressed at a fictional 623 East 68th Street, at first in apartment 4A, then moving to the larger apartment 3B (subsequently re-designated 3D; the Mertzes’ apartment is then numbered 3B), on the Upper East Side of Manhattan. In actuality, however, the addresses go up only to the 500s before the street terminates at the East River. Cast Lucille Ball as Lucille Esmeralda "Lucy" McGillicuddy Ricardo Desi Arnaz as Enrique Alberto Fernando y de Acha "Ricky" Ricardo III Vivian Vance as Ethel Mae Potter Mertz (alternately "Ethel Louise" and "Ethel Roberta") William Frawley as Frederick "Fred" Eedee Hobart Mertz Richard Keith as Enrique Alberto Fernando y de Acha Ricardo IV ("Ricky Ricardo Jr.") Twins Mike Mayer and Joe Mayer played "Little Ricky" as a toddler Kathryn Card as Lucy's mother Mrs. McGillicuddy (also Minnie Finch in the earlier episode "Fan Magazine Interview") Mary Jane Croft as Betty Ramsey and various characters Frank Nelson as Freddie Fillmore and various characters Jerry Hausner as Ricky's agent Jerry (also Joe in "Lucy Does a TV Commercial") Doris Singleton as Carolyn Appleby (she was originally named Lillian; but after Singleton's first appearance in "The Club Election", her name was changed to Carolyn) Shirley Mitchell as Marion Strong, a role originated by Margie Liszt Elizabeth Patterson as Mrs. Matilda Trumbull (also Mrs. Willoughby in the earlier episode "The Marriage License") Bob Jellison as Bobby the Bellboy in the Hollywood episodes (also Milkman in the earlier episode "The Gossip") Ross Elliott as Ricky's Publicity Man in the Hollywood episodes (also The Director in the earlier episode "Lucy Does a TV Commercial") Gale Gordon and Bea Benaderet, supporting cast members on My Favorite Husband, were originally approached for the roles of Fred and Ethel, but neither could accept, owing to previous commitments. Gordon did appear as a guest star in three episodes, playing Ricky's boss, Mr. Littlefield, in two episodes, and later in an episode of The Lucille Ball–Desi Arnaz Show as a civil court judge. Gordon was a veteran from the classic radio days in which he perfected the role of the exasperated character, as in Fibber McGee and Molly and Our Miss Brooks. He would go on to co-star with Ball in all of her post–I Love Lucy series (The Lucy Show, Here's Lucy and Life with Lucy). Benaderet was a guest star in one episode as elderly Miss Lewis, a neighbor of the Ricardos. Barbara Pepper (later featured as Doris Ziffel in the series Green Acres) was also considered to play Ethel, but Pepper had been drinking very heavily after the death of her husband, Craig W. Reynolds. Her friendship with Ball dated back to the film Roman Scandals (1933), in which both appeared as Goldwyn Girls. She did, however, turn up in at least nine episodes of I Love Lucy in bit parts. Many of the characters in the series were named after Ball's family members or close friends. For example, Marion Strong was one of her best friends and a roommate for a time in New York, and she also set Ball and Arnaz up on their first date. Lillian Appleby was a teacher of Ball's when she was in an amateur production on the stage. Additionally, Pauline Lopus was a childhood friend, while Fred was the name of both her brother and grandfather. Ball and Arnaz had a business manager by the name of Mr. Andrew Hickox, and in the first episode of season 4, called "The Business Manager,” Lucy and Ricky hire a man named Mr. Hickox. Primary production team Directors: Marc Daniels (33 episodes, 1951–53); William Asher (101 episodes, 1952–57); James V. Kern (39 episodes, 1955–57) Producers: Jess Oppenheimer (153 episodes, 1951–56); Desi Arnaz (exec. producer—124 episodes, 1952–56; producer—26 episodes, 1956–57) Writers: Jess Oppenheimer (head writer, seasons 1–5), Madelyn Pugh Davis and Bob Carroll Jr. (All Seasons including Lucy-Desi Comedy Hour), Bob Schiller and Bob Weiskopf (Seasons 5–6 and Lucy-Desi Comedy Hour) Original Music: Wilbur Hatch (33 episodes, 1951–54); Eliot Daniel (135 episodes, 1952–57); Marco Rizo (1951–1957) Cinematography: Karl Freund (149 episodes, 1951–56) Costume design: Elois Jenssen (57 episodes, 1953–55), Edward Stevenson (66 episodes, 1955–60) Editors: Dann Cahn, Bud Molin Background and development Lucille Ball came to Hollywood after a successful stint as a New York model. She was chosen by Samuel Goldwyn to be one of 16 Goldwyn Girls to co-star in the picture Roman Scandals (1933), with film star Eddie Cantor. Enthusiastic and hard-working, Ball had been able to secure film work briefly at the Samuel Goldwyn Studio and Columbia Pictures and then eventually at RKO Radio Pictures. It was at RKO that Ball received steady film work, first as an extra and bit player and eventually working her way up to co-starring roles in feature films and starring roles in second rate B pictures, collectively earning her the nickname "Queen of the B's". During her run at RKO, Ball gained the reputation for doing physical comedy and stunts that most other actresses avoided, keeping her steadily employed. In 1940, Ball met Desi Arnaz, a Cuban bandleader who had just come off a successful run in the 1939–40 Broadway show Too Many Girls. RKO, after purchasing film rights to the show, cast Ball as Arnaz's love interest in the picture. The duo began a whirlwind courtship, leading to their elopement in Connecticut in November 1940. Despite their marriage, however, their careers kept them separated, with Ball's film work keeping her anchored in Hollywood, while Arnaz's nightclub engagements with his orchestra kept him on the road. Despite steadily working in pictures, Ball's movie career never advanced to the level of a headlining feature-film actress. Nevertheless, she remained popular with film audiences. Ball came to the attention of Metro-Goldwyn-Mayer after receiving critical acclaim for her starring role in the 1942 Damon Runyon film The Big Street, which bought out her contract. It was under contract with MGM, however, that Ball, who had previously been a blonde, dyed her hair red to complement the Technicolor features that MGM planned to use her in. MGM cast Ball in a variety of films, but it was her work with fellow comedian Red Skelton in the 1943 film DuBarry Was a Lady that brought Ball's physical comedy to the forefront, earning her the reputation as "that crazy redhead,” which Ricky would later call her on the show. Nonetheless, Ball's striking beauty was in sharp contrast to the physical antics she performed in her films. Throughout her career, MGM tried to utilize her in multiple different film genres that did little to highlight her skills. Given their difficulties in casting her, MGM chose not to renew her contract when it expired in 1946. Ball began working as a freelance artist in films and also began to explore other venues. Before and during World War II, Ball made several notable and successful guest appearances on several radio programs, including both Jack Haley's radio show and bandleader Kay Kyser's radio program. These appearances brought Ball to the attention of CBS, which, in 1948, enlisted her to star in one of two new half-hour situation comedies in development, Our Miss Brooks and My Favorite Husband. Choosing the latter, Ball portrayed Liz Cugat (later anglicized to Cooper), the frustrated and scheming housewife of a Minneapolis banker, played originally by actor Lee Bowman in the series pilot, and later by actor Richard Denning. Based on the novel, Mr. and Mrs. Cugat, by Isabel Scott Rorick, My Favorite Husband was produced by Jess Oppenheimer and written by Oppenheimer, plus scribes Madelyn Pugh and Bob Carroll Jr. Premiering on July 23, 1948, and sponsored by General Foods, Husband became a hit for CBS. During the run of the radio program, Ball also appeared in two feature films with Bob Hope, Sorrowful Jones in 1949, and Fancy Pants in 1950. Both films were box office and critical successes, further cementing Ball's reputation as a top notch, first-rate comedian. They also highlighted her growing popularity with audiences, enticing CBS to further use her skills. In 1950, CBS asked Ball to take My Favorite Husband to television with co-star Richard Denning. Ball saw a television show as a great opportunity to work with Arnaz, however, and she insisted that he play her husband, much to the dismay of CBS, which was reluctant to cast Arnaz in that role, as he was Cuban. CBS executives did not think audiences would buy into a marriage between an all-American girl and a Latin man. To prove CBS wrong, the couple developed a vaudeville act, written by Carroll and Pugh, that they performed at Newburgh NY's historic Ritz Theater with Arnaz's orchestra. The act was a hit and convinced CBS executive Harry Ackerman that a Ball-Arnaz pairing would be a worthwhile venture. At the same time, rival networks NBC, ABC, and DuMont were showing interest in a Ball-Arnaz series, which Ackerman used to convince CBS to sign the duo. A pilot was ordered and kinescoped in Hollywood in March 1951, which coincided with Ball's first pregnancy, and the ending of Husband, which aired its last radio show on March 31, 1951. Ball and Arnaz used the same radio team of Oppenheimer, Pugh, and Carroll to create the television series that was named I Love Lucy. The couple's agent, Don Sharpe, brought the pilot to several advertising agencies with little luck but finally succeeded with the Milton H. Biow agency. Biow's agency presented the pilot to its clients and was able to convince cigarette giant Philip Morris to sponsor the show. Production During the spring and summer of 1951, I Love Lucy moved into production. Oppenheimer, Pugh, and Carroll began fine-tuning the premise of the show and writing the series' first scripts. The trio chose to adapt many storylines for television using the backlog of episodes of My Favorite Husband. In addition, the series' ensemble cast and crew were assembled. Arnaz retained his orchestra, which was used in the series musical numbers and to score the show's background and transitional music. Arnaz's childhood friend Marco Rizo arranged the music and played the piano for the show, while Wilbur Hatch was used to conduct the orchestra. Two problems arose after Philip Morris signed on to sponsor the show, that would ultimately change the fate of I Love Lucy. Ball and Arnaz had originally decided that the series would air on a biweekly basis, much like The George Burns and Gracie Allen Show. Philip Morris, however, was insistent that the show air weekly, thus diminishing the possibility of Ball continuing her film career alongside a television show. Another problem lay in the fact that Philip Morris wanted the series to originate from New York rather than Hollywood. At the time, most television shows were produced from New York with live broadcasts of the show airing for eastern and Midwest audiences. West Coast viewers were able to view live programs only through low-quality kinescopes, which derived their images by using a 35 mm or 16 mm film camera to record the show from a television monitor. Although the pilot film shown to Philip Morris had been a kinescope, the sponsor did not want the lucrative East Coast market, accustomed to quality broadcasts, to see a low-quality kinescope film. Owing to the impending birth of their first child, both Ball and Arnaz insisted on staying in Hollywood and producing the show on film, something a few Hollywood-based series had begun to do. Both CBS and Philip Morris initially balked at the idea, because of the higher cost that filming the show would incur, yet acquiesced only after the couple offered to take a $1,000 a week pay cut in order to cover the additional expense. In exchange, Ball and Arnaz demanded, and were given, 80% ownership in the I Love Lucy films (the other 20% went to Oppenheimer who then gave 5% to Pugh and 5% to Carroll). Shooting the show on film, however, would require that Ball and Arnaz become responsible for producing the series themselves. Union agreements at the time stipulated that any production filmed in a studio use film studio employees. CBS staff were television and radio employees and thus fell under different union agreements. Thus, Arnaz reorganized the company he created to manage his orchestra bookings and used it as the corporation that would produce the I Love Lucy shows. The company was named Desilu, from the combination of both their first names "Desi" and "Lucille". Though some television series were already being filmed in Hollywood, most used the single-camera format familiar from movies, with a laugh track added to comedies to simulate audience response. Ball wanted to work in front of a live audience to create the kind of comic energy she had displayed on radio. The idea of a film studio that could accommodate an audience was a new one for the time, as fire safety regulations made it difficult to allow an audience in a studio. Arnaz and Oppenheimer found the financially struggling General Service Studios located on Las Palmas Avenue in Hollywood. Studio owner Jimmy Nasser was eager to accommodate the Desilu company and allowed them, with financial backing of CBS, to renovate two of his studios so that they could accommodate an audience and be in compliance with local fire laws. Another component to filming the show came when it was decided to use three 35 mm film cameras to simultaneously film the show. The idea had been pioneered by Jerry Fairbanks, and had been used on the live anthology series The Silver Theater, and on the game show Truth or Consequences, as well as subsequently Amos 'n' Andy as a way to save money, though Amos n' Andy did not use an audience. Edwards's assistant Al Simon was hired by Desilu to help perfect the new technique for the series. The process lent itself to the Lucy production as it eliminated the problem of requiring an audience to view and react to a scene three or four times in order for all necessary shots to be filmed. Multiple cameras would also allow scenes to be performed in sequence, as a play would be, which was unusual at the time for filmed series. Retakes were rare and dialogue mistakes were often played off for the sake of continuity. Ball and Arnaz enlisted the services of Karl Freund, a cinematographer who had worked on such films as Metropolis (1927), Dracula (1931), The Good Earth (1937) and DuBarry Was a Lady (1943) (which also starred Ball), as well as directing The Mummy (1932), to be the series cinematographer. Although at first Freund did not want anything to do with television, it was the personal plea of the couple that convinced him to take the job. Freund was instrumental in developing a way to uniformly light the set so that each of the three cameras would pick up the same quality of image. Freund noted that a typical episode (20–22 min.) was shot in about 60 minutes, with one constant concern being the shades-of-gray contrast in the final print, as each stage of transmission and broadcast would exaggerate the contrast. Freund also pioneered "flat lighting," in which everything is brightly lit to eliminate shadows and the need for endless relighting. Audience reactions were live, which created a more authentic laugh than the canned laughter used on most filmed sitcoms of the time. Regular audience members were sometimes heard from episode to episode, and Arnaz's distinctive laugh could be heard in the background during scenes in which he did not perform, as well as Ball's mother, DeDe, whose distinctive "uh oh" could be heard in many of the episodes. In later years, CBS would devise a laugh track from several I Love Lucy audiences and use them for canned laughter on shows done without a live audience. I Love Lucys pioneering use of three cameras led to it becoming the standard technique for the production of most sitcoms filmed in front of an audience. Single-camera setups remained the technique of choice for sitcoms that did not use audiences. This led to an unexpected benefit for Desilu during the series' second season when it was discovered that Ball was pregnant. Not being able to fulfill the show's 39-episode commitment, both Desi and Oppenheimer decided to rebroadcast popular episodes of the series' first season to help give Ball the necessary rest she needed after she gave birth, effectively allowing fewer episodes to be filmed that season. Unexpectedly, the rebroadcasts proved to be ratings winners, effectively giving birth to the rerun, which would later lead to the profitable development of the rerun syndication market. The show's original opening and commercial bumpers were animated caricatures of Ball and Arnaz. They were designed and animated by MGM character designer and future "Flintstones" cartoonist, Gene Hazelton (1917–2005) and were produced under a contract producer William Hanna had secured privately. The program sponsor, Philip Morris cigarettes was incorporated into many of these sequences, so when I Love Lucy went into repeats, they were replaced by the now familiar heart logo. However Hazelton's original animation survives, and can be seen in the DVD boxed set as originally presented. Desilu Productions, jointly owned by Ball and Arnaz, would gradually expand to produce and lease studio space for many other shows. For seasons 1 and 2 (1951–1953), Desilu rented space and filmed I Love Lucy at General Service Studios, which eventually became known as Hollywood Center Studios. In 1953, it leased the Motion Picture Center at 846 Cahuenga Blvd. in Hollywood, renaming it Desilu Studios, to shoot seasons 3–6 (1953–1957) of I Love Lucy. After 1956, it became known as Desilu-Cahuenga Studios to avoid confusion with other acquired Desilu locations. In an effort to keep up with the studio's growth, and need for additional sound stages, Arnaz and Ball purchased RKO Radio Pictures from General Tire in 1957 for over $6 million, effectively owning the studio where they had started as contract players. Desilu acquired RKO's two studio complexes located on Gower Street in Hollywood, and in Culver City (now part of the Paramount lot and Culver Studios respectively), along with the Culver City back lot nicknamed "Forty Acres". The sale was achieved by the duo selling their ownership of the once-thought-worthless I Love Lucy films back to CBS for over four million dollars. In 1962, two years after their marriage dissolved, Ball bought out Arnaz's shares of Desilu, becoming the studio's sole owner. She eventually sold off Desilu in 1967 to Gulf+Western, owners of Paramount Pictures. After the sale, Desilu-Cahuenga became a private production company and was known as Ren-Mar Studios till 2010, when it was acquired by the Red Digital Cinema Camera Company and renamed Red Studios – Hollywood. The Mertzes As with My Favorite Husband, Lucy writers decided that the Ricardos needed an older couple to play off of. While performing in Husband, veteran character actors Gale Gordon and Bea Benaderet had played Rudolph and Iris Atterbury, an older, more financially stable couple as Mr. Atterbury had been George Cooper's boss. Ball had initially wanted both actors to reprise their roles on television; however, both were unavailable at the time the show went into production as Benaderet was already playing Blanche Morton on The Burns and Allen Show, and Gordon was under contract by CBS to play Mr. Conklin on both the radio and television versions of Our Miss Brooks. Casting the Mertzes, as they were now called (the surname taken from a doctor that Lucy scriptwriter Madelyn Pugh knew as a child in Indianapolis), proved to be a challenge. Ball had initially wanted character actor James Gleason, with whom she appeared in the Columbia Pictures film Miss Grant Takes Richmond (1949), to play Fred Mertz. However, Gleason wanted nearly $3,500 per episode to play the role, a price that was far too high to sustain. Sixty-four-year-old William Frawley, a seasoned vaudevillian and movie character actor with nearly 100 film credits to his name, was a long shot to play Fred Mertz and only came into consideration after he telephoned Ball personally to ask if there was a role for him on her new show. Ball, who had only briefly known Frawley from her days at RKO, suggested him to both Arnaz and CBS. The network objected to the idea of casting Frawley, fearing that his excessive drinking—which was well known in Hollywood—would interfere with a commitment to a live show. Arnaz nonetheless liked Frawley and lobbied hard for him to have the role, even to the point of having Lucy scribes re-tailor the role of Fred Mertz to be a less financially successful and more curmudgeonly (in contrast to Gordon's Mr. Atterbury) character to fit Frawley's persona. CBS relented only after Arnaz contractually bound Frawley to complete sobriety during the production of the show, and reportedly told the veteran actor that if he ever appeared on-set more than once in an intoxicated state he would be fired. Not once during Lucy'''s nine seasons did Frawley's drinking ever interfere with his performance, and over time Arnaz became one of Frawley's few close friends. The Ethel Mertz character also took quite some time to pin down an actress suitable for the role. Since Lucy's Husband co-star Bea Benaderet was not available, Mary Wickes, a longtime friend was offered the role, but declined because she did not want to strain her friendship with Ball. Actress Barbara Pepper, who was a close friend of Ball, was also considered for the role. The two had a long history together, as Pepper had been one of the Goldwyn Girls who came to Hollywood with Lucy in 1933. Pepper was ruled out by Ball and Arnaz because she too had a drinking problem like Frawley. Vivian Vance became a consideration on the recommendation of Lucy director Marc Daniels. Daniels had worked with Vance in New York on Broadway in the early 1940s. Vance had already been a successful stage star performing on Broadway for nearly 20 years in a variety of plays, and in addition, after relocating to Hollywood in the late 1940s, had two film roles to her credit. Nonetheless, by 1951, she was still a relatively unknown actress in Hollywood. Vance was performing in a revival of the play The Voice of the Turtle in La Jolla, California. Arnaz and Jess Oppenheimer went to see her in the play and hired her on the spot. Vance was reluctant about giving up her film and stage work for a television show, yet was convinced by Daniels that it would be a big break in her career. Ball, however, had many misgivings about hiring Vance, who was younger and far more attractive than the concept of Ethel as an older, somewhat homely woman (Vance was just 2 years older than Ball). Ball was also a believer in the Hollywood adage at the time that there should be only one pretty woman on the set and Ball, being the star of the show, was it. Arnaz, however, was impressed by Vance's work and hired her. The decision was then made to dress Vance in frumpier clothing to tone down her attractiveness. Ball and Vance's relationship during the series' early beginnings was lukewarm at best. Eventually realizing that Vance was no threat and was very professional, Ball began to warm to her. In 1954, Vance became the first actress to win an Emmy Award for Outstanding Supporting Actress. Vance and Ball developed a close, lifelong friendship with Ball frequently listening to Vance's input during episode productions. In 1962, after the end of I Love Lucy, Ball would ask Vance to co-star in her new series The Lucy Show. Vance and Frawley's off-screen relationship was less successful. In spite of this, they were always professional and exhibited exceptional chemistry while performing on the show. Frawley derisively described Vance's appearance as "a sack of doorknobs." It was reported that Vance, who was 22 years younger than Frawley, was not really keen on the idea that her character Ethel was married to a man that was old enough to be her father. Vance also complained that Frawley's song-and-dance skills were not what they once were. Frawley and Vance had an adversarial relationship during the entire run of the show. In 1957, I Love Lucy was re-tailored into an hour-long show originally titled The Lucille Ball-Desi Arnaz Show that was to be part of an anthology series called the Westinghouse Desilu Playhouse. The hour-long Lucy-Desi show was to alternate on a monthly basis with other hour long Playhouse shows. The new series put a much heavier emphasis on big name guest stars as being part of the plot and although the Mertz characters continued into the new series, their roles became somewhat diminished. Although a lighter workload was welcomed by Frawley, Vance came to somewhat resent the change. Arnaz, in an effort to please Vance, for whom he had much respect, proposed doing a spin-off from I Love Lucy called The Mertzes. Seeing a lucrative opportunity and the chance to star in his own show, Frawley was enthused. Vance, however, declined for a number of reasons, the biggest factor being that she felt she and Frawley could barely work together on the ensemble show they were doing at the time, so it would be much less likely the two could work together on their own series. Vance also felt that the Mertz characters would not be as successful without the Ricardos to play off of, and despite being her biggest success, she was becoming interested in playing more glamorous roles rather than Ethel. During the thirteen-episode run of the Lucy-Desi hour-long shows, Vance was given a lot more latitude to look more attractive as Ethel Mertz, something she was denied during the run of the I Love Lucy episodes. Frawley's resentment of Vance intensified after she declined to do the spin-off show and the two rarely talked to each other outside of their characters' dialogue with one another. Pregnancy and Little Ricky Just before filming the show, Ball and Arnaz learned that she was once again pregnant (after multiple miscarriages earlier in their marriage) with their first child, Lucie Arnaz. They filmed the original pilot while Lucy was "showing", but did not include any references to the pregnancy in the episode. This was because CBS thought that talk of pregnancy might be in bad taste and because an ad agency told Arnaz not to show a pregnant woman. Later, during the second season, Ball was pregnant again with second child Desi Arnaz Jr., and this time the pregnancy was incorporated into the series' storyline. (Contrary to popular belief, Ball's pregnancy was not television's first on-screen pregnancy, a distinction belonging to Mary Kay Stearns on the late 1940s sitcom Mary Kay and Johnny.) CBS would not allow I Love Lucy to use the word "pregnant", so "expecting" was used instead. In addition, sponsor Philip Morris made the request that Ball not be seen smoking during the pregnancy episodes. The episode "Lucy Is Enceinte" first aired on December 8, 1952 ("enceinte" being French for "expecting" or "pregnant"). One week later, on December 15, 1952, the episode titled "Pregnant Women Are Unpredictable" was aired (although the show never displayed episode titles on the air). The episode in which Lucy Ricardo gives birth, "Lucy Goes to the Hospital", first aired on January 19, 1953, which was the day before the inauguration of Dwight Eisenhower as President of the United States. To increase the publicity of this episode, the original air date was chosen to coincide with Ball's real-life delivery of Desi Jr. by Caesarean section. "Lucy Goes to the Hospital" was watched by more people than any other television program up to that time, with 71.7% of all American television sets tuned in, topping the 67.7 rating for the inauguration coverage the following morning. Unlike some programs that advance the age of a newborn over a short period, I Love Lucy at first allowed the Ricardos' son Little Ricky to grow up in real time. America saw Little Ricky as an infant in the 1952–53 season and a toddler from 1953 to 1956. However, for the 1956–57 season, Little Ricky suddenly aged by two years, becoming a young school-age boy from 1956 to 1960. Five actors played the role, two sets of twins and later Keith Thibodeaux, whose stage name when playing Ricky Ricardo Jr. was Richard Keith. (In "Lucy and Superman", Little Ricky is mentioned as being five years old but it had been less than four years since the airing of "Lucy Goes to the Hospital".) Jess Oppenheimer stated in his memoir, Laughs, Luck...and Lucy: How I Came to Create the Most Popular Sitcom of All Time, that the initial plan was to match the sex of the Ricardo's baby with Ball's real baby, inserting one of two alternate endings into the broadcast print at the last minute. When logistical difficulties convinced Oppenheimer to abandon this plan, he advised Desi Arnaz that as head writer, he would have Lucy Ricardo give birth to a boy. Desi Arnaz agreed, telling Oppenheimer that Ball had already given him one girl, and might give him another—this might be his only chance to get a son. When the baby boy was born, Desi Arnaz immediately called Oppenheimer and told him, "Lucy followed your script. Ain't she something?", to which Oppenheimer replied "Terrific! That makes me the greatest writer in the world!" Opening The opening familiar to most viewers, featuring the credits superimposed over a "heart on satin" image, was created specifically for the 1959–67 CBS daytime network rebroadcasts, and subsequent syndication. As originally broadcast, the episodes opened with animated matchstick figures of Arnaz and Ball making reference to whoever the particular episode's sponsor was. These sequences were created by the animation team of William Hanna and Joseph Barbera, who declined screen credit because they were technically under exclusive contract to MGM at the time. The original sponsor was cigarette maker Philip Morris, so the program opened with a cartoon of Lucy and Ricky climbing down a pack of Philip Morris cigarettes. In the early episodes, Lucy and Ricky, as well as Ethel and Fred on occasion, were shown smoking Philip Morris cigarettes. Lucy even went so far as to parody Johnny Roventini's image as the Philip Morris "bellhop" in the May 5, 1952, episode, "Lucy Does a TV Commercial". Since the original sponsor references were no longer appropriate when the shows went into syndication, a new opening was needed, which resulted in the classic "heart on satin" opening. Other sponsors, whose products appeared during the original openings, were Procter & Gamble for Cheer and Lilt Home Permanent (1954–57), General Foods for Sanka (1955–57), and Ford Motor Company (1956–57). The later Lucille Ball-Desi Arnaz Show was sponsored by Ford Motor Company (1957–58) and Westinghouse Electric Corporation (1958–60), as part of the Westinghouse Desilu Playhouse. The original openings, with the sponsor names edited out, were revived on TV Land showings, with a TV Land logo superimposed to obscure the original sponsor's logo. However, this has led some people to believe that the restored introduction was created specifically for TV Land as an example of kitsch. The animated openings, along with the middle commercial introductory animations, are included, fully restored, in the DVDs. However, the openings are listed as special features within the disks with the "heart on satin" image opening the actual episodes. The complete original broadcast versions of Seasons 1 and 2, as seen in 1951–1953 with intros, closings, and all commercials, are included on their respective Ultimate Season Blu-ray editions. Theme song The I Love Lucy theme song was written by two-time Oscar-nominee Eliot Daniel. Lyrics were later written by five-time Oscar-nominee Harold Adamson, for Desi Arnaz to sing in the 1953 episode "Lucy's Last Birthday": I love Lucy and she loves me. We're as happy as two can be. Sometimes we quarrel but then How we love making up again. Lucy kisses like no one can. She's my missus and I'm her man, And life is heaven you see, 'Cause I love Lucy, Yes I love Lucy, and Lucy loves me! "I Love Lucy," sung by Desi Arnaz with Paul Weston and the Norman Luboff Choir, was released as the B-side of "There's A Brand New Baby (At Our House)" by Columbia Records (catalog number 39937) in 1953. The song was covered by Michael Franks on the album Dragonfly Summer (1993). In 1977, the Wilton Place Street Band had a Top 40 hit with a disco version of the theme, "Disco Lucy". Episodes Broadcast historyI Love Lucy aired Mondays from 9:00 to 9:30 PM ET on CBS for its entire first run. Each year during its summer hiatus its timeslot was occupied by various summer replacement series. Beginning in April 1955 CBS added reruns from the show's early years to its early evening weekend schedule. This would be the first of several occasions when I Love Lucy reruns would become part of CBS's evening, prime time, and (later on) daytime schedules. In fall 1967, CBS began offering the series in off-network syndication; , the reruns air on the Hallmark Channel and MeTV networks, and scores of television stations in the U.S. and around the world, including Fox's KTTV/KCOP in Los Angeles until December 31, 2018. It is currently on Paramount+. In addition, CBS has run numerous specials, including a succession of annual specials which feature episodes which have been newly colorized. On February 14, 2023, Pluto TV launched a 24-hour I Love Lucy channel in the United States. Nielsen ratings The episode "Lucy Goes to the Hospital", which first aired on Monday, January 19, 1953, garnered a then-record rating of 71.7, meaning that 71.7% of all households with television sets were tuned to the program, the equivalent of some 44 million viewers. That record is surpassed only by Elvis Presley's first of three appearances on The Ed Sullivan Show, which aired on September 9, 1956 (82.6% share, 60.710 million viewers and a 57.1 rating ). The overall rating of 67.3 for the entire 1952 season of I Love Lucy continues to be the highest average rating for any single season of a TV show. Primetime Emmy Awards and nominations 1952 Best Comedy Show—Nominated (Winner: The Red Skelton Hour) 1953 Best Situation Comedy—Won Best Comedienne: Lucille Ball—Won 1954 Best Female Star of a Regular Series: Lucille Ball—Nominated (Winner: Eve Arden for Our Miss Brooks) Best Series Supporting Actor: William Frawley—Nominated (Winner: Art Carney for The Jackie Gleason Show) Best Series Supporting Actress: Vivian Vance—Won Best Situation Comedy—Won 1955 Best Actress Starring in a Regular Series: Lucille Ball—Nominated (Winner: Loretta Young for The Loretta Young Show) Best Situation Comedy Series—Nominated (Winner: The Danny Thomas Show) Best Supporting Actor in a Regular Series: William Frawley—Nominated (Winner: Art Carney for The Jackie Gleason Show) Best Supporting Actress in a Regular Series: Vivian Vance—Nominated (Winner: Audrey Meadows for The Jackie Gleason Show) Best Written Comedy Material: Jess Oppenheimer, Bob Carroll Jr. and Madelyn Davis—Nominated (Winners: James B. Allardice, Jack Douglas, Hal Kanter and Harry Winkler for The George Gobel Show) 1956 Best Actor in a Supporting Role: William Frawley—Nominated (Winner: Art Carney for The Honeymooners) Best Actress—Continuing Performance: Lucille Ball—Won Best Comedy Writing: Jess Oppenheimer, Madelyn Davis, Bob Carroll Jr., Bob Schiller and Bob Weiskopf for "L.A. at Last"—Nominated (Winners: Nat Hiken, Barry E. Blitzer, Arnold M. Auerbach, Harvey Orkin, Vin Bogert, Arnie Rosen, Coleman Jacoby, Tony Webster and Terry Ryan for The Phil Silvers Show: "You'll Never Get Rich") 1957 Best Continuing Performance by a Comedienne in a Series: Lucille Ball—Nominated (Winner: Nanette Fabray for Caesar's Hour) Best Supporting Performance by an Actor: William Frawley—Nominated (Winner: Carl Reiner for Caesar's Hour) Best Supporting Performance by an Actress: Vivian Vance—Nominated (Winner: Pat Carroll for Caesar's Hour) 1958 Best Continuing Performance (Female) in a Series by a Comedienne, Singer, Hostess, Dancer, M.C., Announcer, Narrator, Panelist, or any Person who Essentially Plays Herself: Lucille Ball—Nominated (Winner: Dinah Shore for The Dinah Shore Show) Best Continuing Supporting Performance by an Actor in a Dramatic or Comedy Series: William Frawley—Nominated (Winner: Carl Reiner for Caesar's Hour) Best Continuing Supporting Performance by an Actress in a Dramatic or Comedy Series: Vivian Vance—Nominated (Winner: Ann B. Davis for The Bob Cummings Show) In other media Radio There was some thought about creating an I Love Lucy radio show to run in conjunction with the television series as was being done at the time with the CBS hit show Our Miss Brooks. On February 27, 1952, a sample I Love Lucy radio show was produced, but it never aired. This was a pilot episode, created by editing the soundtrack of the television episode "Breaking the Lease", with added Arnaz narration (in character as Ricky Ricardo). It included commercials for Philip Morris, which sponsored the television series. While it never aired on radio at the time in the 1950s (Philip Morris eventually sponsored a radio edition of My Little Margie instead), copies of this radio pilot episode have been circulating among "old time radio" collectors for years, and this radio pilot episode has aired in more recent decades on numerous local radio stations that air some "old time radio" programming. Merchandise Ball and Arnaz authorized various types of I Love Lucy merchandise. Beginning in November 1952, I Love Lucy dolls, manufactured by the American Character Doll Company, were sold. Adult-size I Love Lucy pajamas and a bedroom set were also produced; all of these items appeared on the show. Comic book and comic strip Dell Comics published 35 issues of an I Love Lucy comic book between 1954 and 1962 including two try-out Four Color issues (#535 and #559). King Features syndicated a comic strip (written by Lawrence Nadel and drawn by Bob Oksner, jointly credited as "Bob Lawrence") from 1952 to 1955. Eternity Comics in the early 1990s issued comic books that reprinted the strip and Dell comic book series. After I Love Lucy Hour-long format After the conclusion of the sixth season of I Love Lucy, the Arnazes decided to cut down on the number of episodes that were filmed. Renamed The Lucille Ball-Desi Arnaz Show, also known as The Lucy-Desi Comedy Hour, the program was extended to an hour and included guest stars in each episode. Thirteen episodes aired from 1957 to 1960. The main cast, Lucille Ball, Desi Arnaz, Vivian Vance, William Frawley and Little Ricky/Richard Keith (birth name Keith Thibodeaux) were all in the show. The Lucy-Desi Comedy Hour is available on DVD, released as I Love Lucy: The Final Seasons 7, 8, & 9. On March 2, 1960, Arnaz's birthday, the day after the last hour-long episode was filmed, Ball filed for divorce from Arnaz. Vivian Vance and William Frawley As previously mentioned, Vance and Frawley were offered a chance to take their characters to their own spin-off series. Frawley was willing, but Vance refused to ever work with Frawley again since the two did not get along. Frawley did appear once more with Lucille Ball — in an episode of The Lucy Show in 1965, which did not include Vance (who by then had ceased to be a regular on that show). This was his last screen appearance with Ball. Frawley died in Hollywood on March 3, 1966, of a heart attack at age 79. Lucille Ball's subsequent network shows In 1962, Ball began a six-year run with The Lucy Show, followed immediately in 1968 by six more years on a third sitcom, Here's Lucy, ending her regular appearances on CBS in 1974. Both The Lucy Show and Here's Lucy included Vance as recurring characters named Viv (Vivian Bagley Bunson on The Lucy Show and Vivian Jones on Here's Lucy), so named because she was tired of being recognized on the street and addressed as "Ethel". Vance was a regular during the first three seasons of The Lucy Show but continued to make guest appearances through the years on The Lucy Show, and on Here's Lucy. In 1977, Vance and Ball were reunited one last time in the CBS special, Lucy Calls the President, which co-starred Gale Gordon (whom Ball had known for very many years by 1977 and who had appeared as a regular on her television shows since 1963; becoming even more prominent once Vance left The Lucy Show in 1965.) In 1986, Ball tried another sitcom, Life with Lucy. The series debuted on ABC to solid ratings, landing in Nielsen's Top 25 for the week. Its ratings quickly declined, however, and resulted in a cancellation after eight episodes. Legacy, critical acclaim and other honors In 1989, the never-seen pilot episode was discovered and revealed in a CBS television special, hosted by Lucie Arnaz, becoming the highest rated program of the season. In 2012, Emily VanDerWerff of The A.V. Club wrote retrospectively:I Love Lucy […] is one of the two foundational texts of American TV comedy, along with The Honeymooners. The series is legitimately the most influential in TV history, pioneering so many innovations and normalizing so many others that it would be easy to write an appreciation of simply, say, the show’s accidental invention of the TV rerun.I Love Lucy continues to be held in high esteem by television critics, and remains perennially popular. It was one of the first American programs seen on British television — which became more open to commerce with the September 1955 launch of ITV, a commercial network that aired the series; in 1982, the launch of a second terrestrial TV station devoted to advertising funded broadcasting (Channel 4) saw the show introduced to a new generation of fans in the UK, with the Channel 4 network repeating the program several times between 1983 and 1994. As of January 2015, meanwhile, it remains the longest-running program to air continuously in the Los Angeles area, almost 60 years after production ended. However, the series is currently aired on KTTV on weekends and now KCOP on weekdays because both stations are a duopoly. KTTV was the original CBS affiliated station in Los Angeles until 1951, just before I Love Lucy premiered on KNXT Channel 2 (now KCBS-TV) when CBS bought that station the same year. In the US, reruns have aired nationally on TBS (1980s–1990s), Nick at Nite (1994–2001) and TV Land (2001–2008) in addition to local channels. TV Land ended its run of the series by giving viewers the opportunity to vote on the show's top 25 greatest episodes on December 31, 2008, through the network's website. Unlike some shows to which a cable channel is given exclusive rights to maximize ratings, I Love Lucy has been consistently broadcast on multiple channels simultaneously. Hallmark Channel is now the home for I Love Lucy in the United States, with the show having moved to the network on January 2, 2009, while the national version of Weigel Broadcasting's MeTV digital subchannel network has carried the program since its debut on December 15, 2010, depending on the market (in markets where another station holds the rights, The Lucy Show is substituted). The show is seen on Fox Classics in Australia. In addition to Primetime Emmy Awards and nominations, I Love Lucy's many honors include the following: The Lucille Ball-Desi Arnaz Center in Jamestown, New York is a museum memorializing Lucy and I Love Lucy, including replicas of the NYC apartment set (located in the Desilu Playhouse facility in the Rapaport Center). In 1990, I Love Lucy became the first television show to be inducted into the Television Hall of Fame. In 1997, the episodes "Lucy Does a TV Commercial" and "Lucy's Italian Movie" were respectively ranked No. 2 and No. 18 on TV Guides list of the 100 Greatest Episodes of All Time. In 1999, Entertainment Weekly ranked the birth of Little Ricky as the fifth greatest moment in television history. In 2002, TV Guide ranked I Love Lucy No. 2 on its list of the 50 greatest shows, behind Seinfeld and ahead of The Honeymooners (According to TV Guide columnist Matt Roush, there was a "passionate" internal debate about whether I Love Lucy should have been first instead of Seinfeld. He stated that this was the main source of controversy in putting together the list.) In 2007, Time magazine placed the show on its unranked list of the 100 best television shows. In 2012, I Love Lucy was ranked the Best TV Comedy and the Best TV Show in Best in TV: The Greatest TV Shows of Our Time. In 2013, TV Guide ranked I Love Lucy as the third greatest show of all time. A 2015 The Hollywood Reporter survey of 2,800 actors, producers, directors, and other industry people named I Love Lucy as their #8 favorite show. Documentaries and dramatizations On April 28, 1990, CBS aired a television movie titled I Love Lucy: The Very First Show hosted by Lucie Arnaz, daughter of Lucille Ball and Desi Arnaz, with commentary that showed the original unaired pilot episode of I Love Lucy that was produced by Ball and Desi Arnaz themselves and found after 40 years. The movie was nominated for a Primetime Emmy Award as an "Outstanding Informational Special". On February 10, 1991, CBS aired a television movie titled Lucy & Desi: Before the Laughter, about the lives of Ball and Desi Arnaz. The movie recreated a number of scenes from classic I Love Lucy episodes, including "Lucy Thinks Ricky Is Trying to Murder Her" and "Lucy Does a TV Commercial". Frances Fisher starred as Ball and Maurice Benard as Desi Arnaz. On May 4, 2003, CBS aired a television movie titled Lucy, portraying the life of Ball and recreating a number of scenes from classic I Love Lucy episodes, including "Lucy Does a TV Commercial", "Lucy Is Enceinte", and "Job Switching". Near the end of the movie, a selection of TV Guide covers is seen in a hallway, showing I Love Lucy franchises on their covers. Also included is close-up of a New York Post article about the birth of Little Ricky. Rachel York starred as Ball and Danny Pino as Desi Arnaz. In October 2011, the stage play I Love Lucy Live on Stage premiered to sold-out houses at the Greenway Court Theatre in Los Angeles. Staged and directed by Rick Sparks, the show featured the performance of two I Love Lucy episodes – "The Benefit" and "Lucy Has Her Eyes Examined", presented to the theatre audience as though they were attending a filming at the Desilu Playhouse in the 1950s. In 2012, the show began a national tour which lasted until 2015. In July 2018, I Love Lucy: A Funny Thing Happened on the Way to the Sitcom, a behind-the-scenes comedy about I Love Lucy by Gregg Oppenheimer (son of series creator Jess Oppenheimer), had its world premiere in a Los Angeles production by L.A. Theatre Works. Recorded before a live audience at the James Bridges Theater, UCLA, the production, directed by Michael Hackett, aired on public radio and was released on Audio CD and as a downloadable mp3 in September of that year. The performance starred Sarah Drew as Ball, Oscar Nuñez as Desi Arnaz, and Seamus Dever as Oppenheimer. A serialized version, titled LUCY LOVES DESI: A Funny Thing Happened on the Way to the Sitcom, was produced in August 2020 by Jarvis & Ayres Productions and aired in the UK on BBC Radio 4, starring Anne Heche as Ball, Wilmer Valderamma as Desi Arnaz, Jared Harris as Oppenheimer, Stacy Keach as William Frawley, and Alfred Molina as CBS Executive Harry Ackerman. In January 2023, L.A. Theatre Works mounted a 22-city U.S. national tour of the play as LUCY LOVES DESI: A Funny Thing Happened on the Way to the Sitcom.In the spring of 2020, NBC's sitcom Will & Grace paid tribute to I Love Lucy with a special episode titled "We Love Lucy". During the episode Lucy and Ricky Ricardo, along with Ethel and Fred Mertz, appear in dream sequences based on scenes from the 1951 CBS series. Lucie Arnaz made a cameo in the episode in the role originated in the "Job Switching" episode by actress Elvia Allman as the Factory Foreperson. In 2021, Being the Ricardos, a film written and directed by Aaron Sorkin, about the relationship between I Love Lucy stars Ball and Desi Arnaz was released. Nicole Kidman and Javier Bardem star as Ball and Desi Arnaz, while J. K. Simmons, Nina Arianda, Tony Hale, Alia Shawkat, Jake Lacy, and Clark Gregg are featured in supporting roles. It received a limited theatrical release by Amazon Studios in the United States on December 10, 2021, prior to streaming worldwide on Prime Video on December 21, 2021. In 2022, Amazon Prime Video released the documentary Lucy and Desi. Directed by Amy Poehler, it was nominated for a Primetime Emmy Award for Outstanding Directing for a Documentary/Nonfiction Program. In color Several classic episodes of I Love Lucy have been colorized. Star and producer Desi Arnaz had expressed interest in airing the show in color as early as 1955, but the cost of such a presentation was prohibitive at the time. The first episode to be colorized was the Christmas special, which had been feared to be lost for many years, as it was not included in the regular syndication package with the rest of the series. A copy was discovered in 1989 in the CBS vaults and was aired by CBS during December of that year in its original black-and-white format. In 1990, this episode was again aired in the days prior to Christmas, but this time the framing sequence was in color, while the clips from earlier episodes remained in black and white. The special performed surprisingly well in the ratings during both years, and aired on CBS each December until 1994. In 2007, as the "Complete Series" DVD set was being prepared for release, DVD producer Gregg Oppenheimer decided to have the episode "Lucy Goes to Scotland" digitally colorized (referencing color publicity stills and color "home movies" taken on the set during production), making it the first I Love Lucy episode to be fully colorized. Four years later, Time Life released the "Lucy's Italian Movie" episode for the first time in full color as part of the "Essential 'I Love Lucy'" collection. The colorized "Lucy Goes to Scotland" episode has never aired on television, but that episode, along with the Christmas special and "Lucy's Italian Movie", were packaged together on the 2013 "I Love Lucy Colorized Christmas" DVD. In 2014, Target stores sold an exclusive version of the DVD that also included "Job Switching". Annual colorized specials On December 20, 2013, CBS revived an annual holiday tradition when it reaired the Christmas special for the first time in nearly two decades. The Christmas special's framing sequence was colorized anew. The network paired this special with the color version of "Lucy's Italian Movie" episode. This special attracted 8.7 million people. Nearly a year later, on December 7, 2014, the Christmas special was again aired on CBS, but this time paired with the popular episode "Job Switching", which was newly colorized for that broadcast. That episode appeared on the "I Love Lucy: The Ultimate Season 2" Blu-ray edition released on August 4, 2015. CBS aired the Christmas special again on December 23, 2015, with the flashback scenes being colorized for the first time, and with a colorized "Lucy Does a TV Commercial" replacing "Job Switching". CBS next aired the Christmas special on December 2, 2016, this time paired with the newly colorized "Lucy Gets in Pictures". On December 22, 2017, the Christmas episode was followed by a newly colorized episode, "The Fashion Show". On December 14, 2018, the Christmas episode was paired with a newly colorized episode, "Pioneer Women". On May 17, 2015, CBS began a new springtime tradition when it aired two newly colorized episodes in an "I Love Lucy Superstar Special" consisting of "L.A. at Last" and "Lucy and Superman", which attracted 6.4 million viewers. A DVD of this special was released on October 4, 2016. A second "Superstar Special" containing the newly colorized two-part episode "Lucy Visits Grauman's" and "Lucy and John Wayne" aired on May 20, 2016 and was released on DVD on January 17, 2017. A third "Superstar Special" aired on May 19, 2017, featuring two more newly colorized Hollywood-based episodes: "The Dancing Star" featuring Van Johnson, and "Harpo Marx". A two-episode "Funny Money Special" was introduced on April 19, 2019, featuring the episodes "The Million-Dollar Idea" and "Bonus Bucks", both from early 1954. On December 20, 2019, CBS aired its annual I Love Lucy Christmas episode along with a new colorized episode, "Paris At Last". The I Love Lucy Christmas Special scored a 4.9 million in the ratings, becoming the night's most-watched show on television. Colorized feature film On August 6, 2019, Ball's would-be 108th birthday, a one-night-only event took place in movie theaters around the United States, I Love Lucy: A Colorized Celebration, a feature film consisting of five colorized episodes, three of which contain never-before-seen content. The episodes included are: "The Million Dollar Idea" (1954), "Lucy Does a TV Commercial" (1952), "Pioneer Women" (1952), "Job Switching" (1952) and "L.A. at Last!" (1955). A short documentary on the colorization process of the episodes was also included. The film proved to be very successful, grossing $777,645 from 660 theaters across the country, coming in at #6 at the domestic box office and beating Disney's Aladdin. Home media Beginning in the summer of 2001, Columbia House Television began releasing I Love Lucy on DVD in chronological order. They began that summer with the pilot and the first three episodes on a single DVD. Every six weeks, another volume of four episodes would be released on DVD in chronological order. During the summer of 2002, each DVD would contain between five and seven episodes on a single DVD. They continued to release the series very slowly and would not even begin to release any season 2 episodes until the middle of 2002. By the spring of 2003, the third season on DVD began to be released with about six episodes released every six weeks to mail order subscribers. All these DVDs have the identical features as the DVDs eventually released in the season box sets in retail. By the fall of 2003, season four episodes began to be offered by mail. By the spring of 2004 season five DVDs with about six episodes each began to be released gradually. Columbia House ended the distribution of these mail order DVDs in the Winter of 2005. They began releasing complete season sets in the summer of 2004 every few months. They stated that Columbia House Subscribers would get these episodes through mail before releasing any box sets with the same episodes. They finally ended gradual subscriptions in 2005, several months before season 5 became available in retail. Columbia House then began to make season box sets available instead of these single volumes. CBS DVD (distributed by Paramount) has released all six seasons of I Love Lucy on DVD in Region 1, as well as all 13 episodes of The Lucy and Desi Comedy Hour (as I Love Lucy: The Final Seasons – 7, 8, & 9). Bonus features include rare on-set color footage and the "Desilu/Westinghouse" promotional film, as well as deleted scenes, original openings and interstitials (before they were altered or replaced for syndication) and on-air flubs. These DVDs offered identical features and identical content to the mail order single sets formerly available until 2005. In December 2013, the first high-definition release of I Love Lucy was announced, with the Blu-ray edition of the first season, scheduled for May 5, 2014. The Second Season Ultimate Blu-ray was released on August 4, 2015. Other releases I Love Lucy's Zany Road Trip: California Here We Come!, a compilation of 27 episodes, released by CBS/FOX Video on VHS in 1992 "I Love Lucy – Season 1" (9 separate discs labeled "Volumes", the first volume released July 2, 2002, final volume released September 23, 2003) "I Love Lucy – Season 1" (9 Volumes in a box set, released September 23, 2003) "I Love Lucy – 50th Anniversary Special" (1 disc, released October 1, 2002) "I Love Lucy: The Movie and Other Great Rarities" (1 disc, released April 27, 2010) (Also included as a bonus disc in the complete series set.) "The Best of I Love Lucy" (2 discs: 14 episodes, released in June 2011 in conjunction with the 60th anniversary of the series and Lucille Ball's 100th birthday; sold exclusively through Target.) The DVD releases feature the syndicated heart-opening and offer the original broadcast openings as bonus features. Season 6 allows viewers to choose whether to watch the episodes with the original opening or the syndicated opening. The TV Land openings are not on these DVDs. Initially, the first season was offered in volumes, with four episodes per disc. After the success of releasing seasons 2, 3, and 4 in slim packs, the first season was re-released as a seven-disc set, requiring new discs to be mastered and printed to include more episodes per disc so there would be fewer discs in the set. For the complete series box set, the first season would be redone again, this time to six DVDs, retaining all bonus features. The individual volume discs for the first season are still in print, but are rare for lack of shelf space and because the slim packs are more popular. In 2012, all-season sets were reissued in slipcovered clear standard-sized Amaray DVD cases, with season 1 being the 6-disc version as opposed to the 7-disc version. Episodes feature English closed-captioning, but only Spanish subtitles. In Australia and the UK, the first three seasons were finally released in Region 2 & Region 4 on August 3, 2010, by CBS, distributed by Paramount. Season 1 includes the pilot and all 35 Season 1 episodes in a 7-disc set. Season 2 includes all 31 Season 2 episodes in a 5-disc set. Season 3 includes all 31 Season 3 episodes in a 5-disc set. Season 2 and 3 are in a slimline pack. All three seasons have been restored and digitally remastered. All episodes appear in order of their original air dates, although it states that some episodes may be edited from their original network versions. It is unknown if the remaining seasons will be released individually. A complete series box set titled I Love Lucy: Complete Collection was scheduled for release on April 6, 2016, and in the UK on May 30, 2016. This collection contains 34 DVDs with all six seasons of I Love Lucy and all 13 episodes of The Lucy-Desi Comedy Hour. In September 2018, Time-Life released a DVD, Lucy: The Ultimate Collection, which collected 76 episodes of I Love Lucy, The Lucy-Desi Comedy Hour, The Lucy Show, Here's Lucy, and the short-lived ABC-TV series Life with Lucy (which had at the time never before been released to home media), plus a wide variety of bonus features. A DVD collection, I Love Lucy: Colorized Collection was released on August 13, 2019. It contains every colorized episode of I Love Lucy aired to date of the set's release date. Due to a delay or possible all out cancellation of any future colorized releases, this means that "Paris at Last", which aired as part of the December 2019 edition of the Christmas Special after the colorized DVD collection had been released, is the only colorized episode currently not to be available on home media. See also Statue of Lucille Ball Ricky (song) Notes References Further reading Garner, Joe (2002). Stay Tuned: Television's Unforgettable Moments (Andrews McMeel Publishing) Andrews, Bart (1976). The 'I Love Lucy' Book (Doubleday & Company, Inc.) Sanders, Coyne Steven; Gilbert, Tom (1993). Desilu: The Story of Lucille Ball and Desi Arnaz (William Morrow & Company, Inc.) McClay, Michael (1995). I Love Lucy: The Complete Picture History of the Most Popular TV Show Ever (Kensington Publishing Corp.) Oppenheimer, Jess; with Oppenheimer, Gregg (1996). Laughs, Luck...and Lucy: How I Came to Create the Most Popular Sitcom of All Time (Syracuse Univ. Press) Pérez Firmat, Gustavo. "I Love Ricky," in Life on the Hyphen: The Cuban-American Way. Austin: The University of Texas Press, 1994. Rpt. 1996, 1999. Revised and expanded edition, 2012. Pérez Firmat, Gustavo. "Cuba in Apt. 3-B," in The Havana Habit. New Haven and London: Yale University Press, 2010. Karol, Michael; (2008). Lucy A to Z: The Lucille Ball Encyclopedia (iUniverse) Edelman; Rob; Kupferberg, Audrey (1999). Meet the Mertzes'' (Renaissance Books) External links 1950s American sitcoms 1951 American television series debuts 1957 American television series endings American comedy radio programs Black-and-white American television shows CBS original programming English-language television shows Hispanic and Latino American sitcoms Nielsen ratings winners Primetime Emmy Award for Outstanding Comedy Series winners Television series about marriage Television series about show business Television series based on radio series Television series by CBS Studios Television series by Desilu Productions Television shows adapted into comics Television shows filmed in Los Angeles Television shows set in Connecticut Television shows set in Manhattan Television shows set in Los Angeles Television shows set in Europe Television shows set in Florida
```swift import Foundation import Shared class OnboardingAuthDetails: Equatable { var url: URL var scheme: String var exceptions: SecurityExceptions = .init() init(baseURL: URL) throws { guard var components = URLComponents(url: baseURL.sanitized(), resolvingAgainstBaseURL: false) else { throw OnboardingAuthError(kind: .invalidURL) } let redirectURI: String let scheme: String let clientID: String if Current.appConfiguration == .debug { clientID = "path_to_url" redirectURI = "homeassistant-dev://auth-callback" scheme = "homeassistant-dev" } else if Current.appConfiguration == .beta { clientID = "path_to_url" redirectURI = "homeassistant-beta://auth-callback" scheme = "homeassistant-beta" } else { clientID = "path_to_url" redirectURI = "homeassistant://auth-callback" scheme = "homeassistant" } components.path += "/auth/authorize" components.queryItems = [ URLQueryItem(name: "response_type", value: "code"), URLQueryItem(name: "client_id", value: clientID), URLQueryItem(name: "redirect_uri", value: redirectURI), ] guard let authURL = components.url else { throw OnboardingAuthError(kind: .invalidURL) } self.url = authURL self.scheme = scheme } static func == (lhs: OnboardingAuthDetails, rhs: OnboardingAuthDetails) -> Bool { lhs.url == rhs.url && lhs.scheme == rhs.scheme && lhs.exceptions == rhs.exceptions } } ```
```shell SSH tunneling made easy Quick port test with `netcat` Disable `IPv6` Useful ssh client optimizations Make use of `netstat` ```
```go package jwk import ( "crypto" "crypto/ecdsa" "crypto/elliptic" "fmt" "math/big" "github.com/lestrrat-go/blackmagic" "github.com/lestrrat-go/jwx/internal/base64" "github.com/lestrrat-go/jwx/internal/ecutil" "github.com/lestrrat-go/jwx/jwa" "github.com/pkg/errors" ) func init() { ecutil.RegisterCurve(elliptic.P256(), jwa.P256) ecutil.RegisterCurve(elliptic.P384(), jwa.P384) ecutil.RegisterCurve(elliptic.P521(), jwa.P521) } func (k *ecdsaPublicKey) FromRaw(rawKey *ecdsa.PublicKey) error { k.mu.Lock() defer k.mu.Unlock() if rawKey.X == nil { return errors.Errorf(`invalid ecdsa.PublicKey`) } if rawKey.Y == nil { return errors.Errorf(`invalid ecdsa.PublicKey`) } xbuf := ecutil.AllocECPointBuffer(rawKey.X, rawKey.Curve) ybuf := ecutil.AllocECPointBuffer(rawKey.Y, rawKey.Curve) defer ecutil.ReleaseECPointBuffer(xbuf) defer ecutil.ReleaseECPointBuffer(ybuf) k.x = make([]byte, len(xbuf)) copy(k.x, xbuf) k.y = make([]byte, len(ybuf)) copy(k.y, ybuf) var crv jwa.EllipticCurveAlgorithm if tmp, ok := ecutil.AlgorithmForCurve(rawKey.Curve); ok { crv = tmp } else { return errors.Errorf(`invalid elliptic curve %s`, rawKey.Curve) } k.crv = &crv return nil } func (k *ecdsaPrivateKey) FromRaw(rawKey *ecdsa.PrivateKey) error { k.mu.Lock() defer k.mu.Unlock() if rawKey.PublicKey.X == nil { return errors.Errorf(`invalid ecdsa.PrivateKey`) } if rawKey.PublicKey.Y == nil { return errors.Errorf(`invalid ecdsa.PrivateKey`) } if rawKey.D == nil { return errors.Errorf(`invalid ecdsa.PrivateKey`) } xbuf := ecutil.AllocECPointBuffer(rawKey.PublicKey.X, rawKey.Curve) ybuf := ecutil.AllocECPointBuffer(rawKey.PublicKey.Y, rawKey.Curve) dbuf := ecutil.AllocECPointBuffer(rawKey.D, rawKey.Curve) defer ecutil.ReleaseECPointBuffer(xbuf) defer ecutil.ReleaseECPointBuffer(ybuf) defer ecutil.ReleaseECPointBuffer(dbuf) k.x = make([]byte, len(xbuf)) copy(k.x, xbuf) k.y = make([]byte, len(ybuf)) copy(k.y, ybuf) k.d = make([]byte, len(dbuf)) copy(k.d, dbuf) var crv jwa.EllipticCurveAlgorithm if tmp, ok := ecutil.AlgorithmForCurve(rawKey.Curve); ok { crv = tmp } else { return errors.Errorf(`invalid elliptic curve %s`, rawKey.Curve) } k.crv = &crv return nil } func buildECDSAPublicKey(alg jwa.EllipticCurveAlgorithm, xbuf, ybuf []byte) (*ecdsa.PublicKey, error) { var crv elliptic.Curve if tmp, ok := ecutil.CurveForAlgorithm(alg); ok { crv = tmp } else { return nil, errors.Errorf(`invalid curve algorithm %s`, alg) } var x, y big.Int x.SetBytes(xbuf) y.SetBytes(ybuf) return &ecdsa.PublicKey{Curve: crv, X: &x, Y: &y}, nil } // Raw returns the EC-DSA public key represented by this JWK func (k *ecdsaPublicKey) Raw(v interface{}) error { k.mu.RLock() defer k.mu.RUnlock() pubk, err := buildECDSAPublicKey(k.Crv(), k.x, k.y) if err != nil { return errors.Wrap(err, `failed to build public key`) } return blackmagic.AssignIfCompatible(v, pubk) } func (k *ecdsaPrivateKey) Raw(v interface{}) error { k.mu.RLock() defer k.mu.RUnlock() pubk, err := buildECDSAPublicKey(k.Crv(), k.x, k.y) if err != nil { return errors.Wrap(err, `failed to build public key`) } var key ecdsa.PrivateKey var d big.Int d.SetBytes(k.d) key.D = &d key.PublicKey = *pubk return blackmagic.AssignIfCompatible(v, &key) } func makeECDSAPublicKey(v interface { makePairs() []*HeaderPair }) (Key, error) { newKey := NewECDSAPublicKey() // Iterate and copy everything except for the bits that should not be in the public key for _, pair := range v.makePairs() { switch pair.Key { case ECDSADKey: continue default: //nolint:forcetypeassert key := pair.Key.(string) if err := newKey.Set(key, pair.Value); err != nil { return nil, errors.Wrapf(err, `failed to set field %q`, key) } } } return newKey, nil } func (k *ecdsaPrivateKey) PublicKey() (Key, error) { return makeECDSAPublicKey(k) } func (k *ecdsaPublicKey) PublicKey() (Key, error) { return makeECDSAPublicKey(k) } func ecdsaThumbprint(hash crypto.Hash, crv, x, y string) []byte { h := hash.New() fmt.Fprint(h, `{"crv":"`) fmt.Fprint(h, crv) fmt.Fprint(h, `","kty":"EC","x":"`) fmt.Fprint(h, x) fmt.Fprint(h, `","y":"`) fmt.Fprint(h, y) fmt.Fprint(h, `"}`) return h.Sum(nil) } // Thumbprint returns the JWK thumbprint using the indicated // hashing algorithm, according to RFC 7638 func (k ecdsaPublicKey) Thumbprint(hash crypto.Hash) ([]byte, error) { k.mu.RLock() defer k.mu.RUnlock() var key ecdsa.PublicKey if err := k.Raw(&key); err != nil { return nil, errors.Wrap(err, `failed to materialize ecdsa.PublicKey for thumbprint generation`) } xbuf := ecutil.AllocECPointBuffer(key.X, key.Curve) ybuf := ecutil.AllocECPointBuffer(key.Y, key.Curve) defer ecutil.ReleaseECPointBuffer(xbuf) defer ecutil.ReleaseECPointBuffer(ybuf) return ecdsaThumbprint( hash, key.Curve.Params().Name, base64.EncodeToString(xbuf), base64.EncodeToString(ybuf), ), nil } // Thumbprint returns the JWK thumbprint using the indicated // hashing algorithm, according to RFC 7638 func (k ecdsaPrivateKey) Thumbprint(hash crypto.Hash) ([]byte, error) { k.mu.RLock() defer k.mu.RUnlock() var key ecdsa.PrivateKey if err := k.Raw(&key); err != nil { return nil, errors.Wrap(err, `failed to materialize ecdsa.PrivateKey for thumbprint generation`) } xbuf := ecutil.AllocECPointBuffer(key.X, key.Curve) ybuf := ecutil.AllocECPointBuffer(key.Y, key.Curve) defer ecutil.ReleaseECPointBuffer(xbuf) defer ecutil.ReleaseECPointBuffer(ybuf) return ecdsaThumbprint( hash, key.Curve.Params().Name, base64.EncodeToString(xbuf), base64.EncodeToString(ybuf), ), nil } ```
Rumania Montevideo is a Japanese pop band under the Giza Studio label. They were active from 1998 to 2002 and reformed in 2019. The band name comes from the combination of the Latin spelling of Romania and Montevideo, the capital of Uruguay. Members Mami Miyoshi (三好真美): vocalist, drummer, lyricist (1998–2002, 2019–) Makoto Miyoshi (三好誠): guitarist, composer, arranger (1998–2002, 2019–) Akiko Matsuda (松田明子): saxophonist, keyboardist (1998–2002) Satomi Makoshi (麻越さとみ): bassist (1998–2002) Kazunobu Mashima (間島和伸): guitarist (1998–2002) Supporting members Naoya Shima: drummer (2019–) Tom: bass (2019–) Rerere: guitar (2019–) Cherry: keyboard and backing vocals (2019–) History 1998: Band formation and first demo tapes In the autumn of 1998, the Miyoshi siblings, Mami and Makoto, sent a demo tape to Giza Studio and formed their own band, with members Akiko Matsuda, Satomi Makoshi and Kazunobu Mashima joining in later. During that time, they started recording their first mini album Jet Plane. In December they released limited two-cassette tapes Half Moon and Picnic, sold at the store Time Bomb in Shinsaibashi for one week. 1999: Success of debut single "Still for your love" On 25 January 1999, the on-air version of their debut single, "Still for your love", aired as an ending theme for the anime television series Detective Conan. In February, the Miyoshi siblings participated in the recording of the album Eien by the Japanese group Zard. Mami provided backing vocals and Makoto composed the song "I Feel Fine, Yeah". On 5 March 1999, they released two LP records, Half Moon and Picnic. At the same time, the first mini album Jet Plane was released under indie label Garage Indies Zapping Association. On 29 March they released a second mini studio album . On 14 April 1999, they made a major debut with the single "Still for your love". The single ranked #9 in its first week in the Oricon rankings. On 28 April, they released their third LP record Still for your love. Side A contains the same music as the debut single and side B includes a demo tape of the song "Still for your love" and the solo song "Headphones" by Makoto Miyoshi. The LP record Still for your love was released on April 24, including an original version of the song from the single and demo-tape version, with singing in English and guitar acoustic arrangement. The LP also includes Makoto's unreleased solo track "Headphones". On 27 May, they made an appearance on the music program Music Station as the first Giza Studio artist. During an interview with Tamori, Makoto explained the meaning behind the name of the band. On 16 June 1999, they released their studio album Rumaniamania. The album ranked #9 in its first week in the Oricon rankings. On 24 July 1999, the on-air version of "Digital Music Power" aired as an ending theme for the anime television series Monster Rancher. The original release schedule was planned sometime in August, but it was postponed due to production issues. In September they released their second single "Digital Music Power". The lyrics were completely changed from the on-air version. On 3 November 1999, they released their third single "Picnic". The song is performed in Japanese, unlike the version of "Picnic" which was released as a cassette and the LP record Picnic which were originally performed in English. The on-air version of this single started broadcast three days after its release, on 6 November 1999. It aired as an opening theme for the anime television series Monster Rancher. 2000: Sales decline and first stage performances On January 10, they released their fourth single "Koisuru Betty". It aired as a theme song for the TBS television program Express. On January 26, they released their second studio album Girl, Girl, Boy, Girl, Boy. In July, the Miyoshi siblings, without the other members, held an acoustic live performance "UNDOWN vol.4" as part of the live session at Shibuya Club Quattro. They performed four songs from indie albums and one song from Rumaniamania. This was their first and last live performance. In August, they released their fifth single "Start All Over Again". It was aired as an ending theme for the TV Asahi program Mokugeki Dokyun! It was their final single which ranked on Oricon Weekly charts. On 18 November, three members of the band, Matsuda, Makoshi and Mashima, formed the new alternative band Ramjet Pulley and released a major single "Hello...good bye". 2001–2002: Unannounced disband and hiatus In April 2001, after more than half a year, they released their sixth single "Hard Rain". In the media it was promoted as an ending theme for the Tokyo Broadcasting System Television program Kinniku Banzuke. The single was included in the compilation album Giza Studio Masterpiece Blend 2001. In December 2001, they released their final single "Tender Rain". In the media it was promoted as an ending theme for the Tokyo Broadcasting System Television program CDTV. Both of these singles failed to debut on the Oricon Weekly Singles Chart. In the same month, Mami Miyoshi and Matsuda participated in the R&B cover album Giza Studio R&B Respect Vol.1: Six Sisters Selection covering "Killing Me Softly with His Song" by Lori Lieberman and "Free" by Deniece Williams. In February 2002, after the release of the third studio album Mo' Better Tracks their activities stopped. It is not known whether they disbanded or took a hiatus as no public announcement was published on their official website. 2003–2007: Separate activities In May 2003, Mami Miyoshi appeared as a guest singer at Hills Pankojou at Keiko Utoku's event "Oldies Night" performing a cover of Gazebo's "I Like Chopin". Later, she composed the album track "Ikitakuwanai Bokura" for Japanese singer Azumi Uehara. She was active until 2006. Makoto Miyoshi continued writing songs for various Giza artists such as The Tambourines, Uura Saeka, Aiko Kitahara and U-ka Saegusa. He officially left Giza Studio in 2007. The alternative band Ramjet Pulley also unofficially disbanded and went into indefinite hiatus in autumn 2003. Makoshi quit public activity in January 2003 after releasing the final album of Ramjet Pulley. Mashima represented himself in production credits as both a former Rumania Montevideo and Ramjet Pulley member. He continued writing songs for various Giza artists such as Aiko Kitahara and U-ka Saegusa in dB as composer and arranger until 2007. In June 2003, Matsuda appeared at Hill Pankoujou's Thursday Live: Acoustic Night as a guest singer. In August, she released a cover of Yumi Arai's "Ame no Machi wo", which was arranged and produced by Tak Matsumoto, the song was included as a B-side of the cover of "Ihoujin" by Zard. After September 2003, she quit public activity. In 2006, Rina Aiuchi and Saegusa Yuuka covered "Still for your love", which appeared as a B-side to their single "100 Mono Tobira" with re-arrangement by Takeshi Hayama. 2019: Band reunion and Osaka Live On 6 March 2019, Makoto Miyoshi launched an official Twitter account with the announcement of a return to band activities along with his sister Mami Miyoshi. Later Makototo announced that Mami would provide only vocals, not drums. On 7 March, Makoto shared on his YouTube channel a demo tape of the unreleased song "anytime" with Makoto as lead vocalist and Mami doing background vocals. The original upload of a demo tape is from 2011. On the same day it was announced on Twitter that Naoya Shimai from indie band Spaghetti Vabune! would support the group on drums. On 15 March, "Tom" was announced on Twitter as the new bass player to the band. On 1 April, a practice video of the song "Dare mo Shiranai Yoake" was uploaded on Makoto Miyoshi's Twitter account. The video footage shows two guitarists, one bassist, one drummer and vocalist Mami Miyoshi. On 8 July a new keyboard and backing vocals support member, "Cherry", and a guitar support member, "Rerere", were announced through Twitter. The new band consisted of former members, the Miyoshi siblings and four new support members. On 14 July, Mami Miyoshi launched a Twitter account. On 1 December the band performed live in the Ohsaka venue Hills Pankoujou. Former members of the sub-band Ramjet Pulley arrived as audience guests as well. 2020: New demo-tapes and canceled first Tokyo Live In January, Makoto published three interview videos on his YouTube channel with guitarist Shimal, who answered questions about Rumania Montevideo's past. In February, Makoto started launching short demo tapes on his YouTube channel. In March, a second reunion live performance was scheduled in Tokyo in the venue Daikanyama Unit. All supporting band members planned to reprise their roles., however on 9 March, the event was cancelled due to the worldwide pandemic situation of the coronavirus. After the conclusion, Mami's activities has been decreased and Miyoshi continues release monthly new song or demo tapes on his YouTube channel. On 20 August, Makoto has confessed his wish to collaborate once again in the band with his childhood friend and former member, Kazunobu Mashima. Discography During their career, the band released three studio albums, two indie albums, three LP records, two cassette tapes, and seven singles. All lyrics were written by Mami Miyoshi, and all music was composed and arranged by Makoto Miyoshi. Singles Studio albums Indie albums Cassette tapes LP records Demo tapes The titles come from the official YouTube channel of Makoto Miyoshi. Anytime (March 2011) - Makoto lead vocals, Mami back-vocals 0208 (August 2019) Unknown (September 2019) Sunset (January 2020) Dance (February 2020) Smile Again (February 2020) - Mami lead vocals Opinion No.5 (26 April 2020) The Motion (15 May 2020) Uroncha(烏龍茶) (17 May 2020) Outer Space (28 August 2020) aquablue2020 (28 August 2020) electro harmonix (28 August 2020) Catch Up (28 August 2020) - Mami lead vocals Obrien (28 August 2020) Barcelona (28 August 2020) Fade Away (28 August 2020) Gravity (28 August 2020) Anybody Else (6 September 2020) Television performances CDTV Still for your love (1999/04/10) Picnic (1999/11/06) Music Station (1999/05/27) Still for your love NHK Seishun Message 2000 (2000/01/10) Still for your love, Koisuru Betty Pop-Jam Koisuru Betty (2000/01/15) Live performances Shibuya Club Quattro: Undown Vol.4 (14 July 2000) - stage appearance of Miyoshi siblings Hills Pan Koujou: GIZA studio R&B PARTY (15 December 2001) - only Mami and Akiko Hills Pan Koujou: Oldies Night (8 May 2003) - only Mami Hills Pan Koujou: Acoustic Night (12 June 2003) - only Akiko Hills Pan Koujou: Rumania Montevideo Live 2019: Boku wo Motsu Kimi he (1 December 2019) - Miyoshi siblings with four new support members References External links Official website Official website by Being (in Japanese) Official Giza USA profile (scroll down till Rumania Montevideo section) Oricon profile (in Japanese)() Musing profile (in Japanese) () Authority Musicbrainz.org page Anime musicians Being Inc. artists Japanese pop music groups Japanese pop rock music groups Japanese rock music groups Musical groups established in 1998 Female-fronted musical groups
Alexandra Louise Kuczynski (born December 6, 1970) is a Peruvian reporter, who has written for the New York Times and the New York Times Magazine, and is the author of the award-winning 2006 book Beauty Junkies about the cosmetic surgery industry. The book was translated into ten languages. Biography Her father, Pedro Pablo Kuczynski of Lima, is an economist and politician, who was the 66th President of Peru. Her mother is Jane Dudley Casey, daughter of Joseph E. Casey, member of the U.S. House for Massachusetts's 3rd congressional district. Kuczynski's paternal grandfather was physician specializing in tropical diseases Maxime Hans Kuczyński, a Jewish emigrant from Germany, who founded the first leper colony in South America. Her maternal uncle is novelist and translator John Casey and her paternal first cousin once removed is French film director and screenwriter Jean-Luc Godard. After graduating from Barnard College in 1990, she became a journalist with the New York Observer and then the New York Times. On September 10, 2001, she was transferred by Howell Raines from media reporter to the style section, where Kuczynski would write "the sort of pop-feature pieces that would appeal to the Times national audience." She has been described as "a giddy blast. She always would have 10 ideas at story meetings and eight of them would be terrible and two would be brilliant." Under her byline, the word "horny" first appeared in the Times, in reference to a story about female Viagra; she later said, "I wear that as a badge of honor." Kuczynski married investor Charles Porter Stevenson Jr. in 2002, with whom she has two children. He initiated divorce proceedings against her in 2019. She is estimated to have a net worth of $75 million. In 2006, she authored a book about the growth of the cosmetic surgery business: Beauty Junkies: Inside Our $15 Billion Obsession with Plastic Surgery (). Reviewers have noted that readers of the book "may take a pass after reading this exposé about extreme makeovers." Kuczynski concluded, "Looks are the new feminism, an activism of aesthetics. As vulgar and shallow as it sounds, looks matter more than they ever have—especially for women. When Eleanor Roosevelt was asked if she had any regrets in life, she said that she had one: she wished she had been prettier." References External links Barnard College alumni The New York Times columnists Living people 1967 births American people of German-Jewish descent American people of Polish-Jewish descent Mass media people from Lima Peruvian emigrants to the United States 20th-century American journalists 20th-century American women journalists 20th-century American women writers 21st-century American journalists 21st-century American women journalists 21st-century American women writers American women columnists Peruvian women journalists Peruvian women columnists Kuczynski family Children of presidents of Peru
```xml /** * Get pathname from absolute path. * * @param absolutePath the absolute path * @returns the pathname */ export function getPathnameFromAbsolutePath(absolutePath: string) { // Remove prefix including app dir let appDir = '/app/' if (!absolutePath.includes(appDir)) { appDir = '\\app\\' } const [, ...parts] = absolutePath.split(appDir) const relativePath = appDir[0] + parts.join(appDir) // remove extension const pathname = relativePath.split('.').slice(0, -1).join('.') return pathname } ```
```html <!DOCTYPE html> <html lang="zh-TW"> <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> - </title> <meta property="og:title" content=" - "> <meta property="og:type" content="website"> <meta property="og:url" content="path_to_url"> <meta property="og:image" content="path_to_url"> <meta property="og:description" content=""> <meta property="og:locale" content="zh-TW"> <link rel="canonical" href="path_to_url"> <link rel="alternate" href="path_to_url" hreflang="en"> <link rel="alternate" href="path_to_url" hreflang="pl"> <link rel="alternate" href="path_to_url" hreflang="zh-CN"> <link rel="alternate" href="path_to_url" hreflang="zh-TW"> <link rel="stylesheet" href="../../thirdparty/bootstrap-3.3.7/bootstrap.min.css"> <link rel="stylesheet" href="gallery.css"> <link rel="icon" href="../../icon128.png" type="image/png"> </head> <body> <div class="navbar navbar-fixed-top container" style="background-color:white;max-height:90px;overflow:hidden"> <a href="path_to_url" class="navbar-left brand"> <img src="../../icon128.png" alt="" style="width:18pt; height:18pt"> </a> <div class="navbar-right"> <span class="navul"> <a href="path_to_url"></a> <a href="path_to_url" class="active"></a> <a href="path_to_url"></a> </span> <span class="github-button-container"> <a class="github-button" href="path_to_url" data-show-count="true" aria-label="Star ricktu288/ray-optics on GitHub">Star</a> </span> </div> </div> <div class="container"> <center> <h1><b><span></span></b></h1> <p> Yi-Ting Tu </p> <div class="description"> <p></p> </div> <p> <a href="path_to_url#../tw/gallery/chromatic-dispersion" target="_blank" class="btn btn-success btn-lg"></a> </p> <img src="chromatic-dispersion.png" alt="" style="width:100%"> </center> <div style="float: right; padding-top: 10px;"> <div class="dropup"> <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown"> <span id="language"></span> <span class="caret"></span></button> <ul class="dropdown-menu"> <li><a href="path_to_url">English</a></li><li><a href="path_to_url">polski</a></li><li><a href="path_to_url"></a></li><li><a href="path_to_url"></a></li> </ul> </div> </div> </div> </div> <script src="../../thirdparty/jquery.min.js"></script> <script src="../../thirdparty/bootstrap-3.3.7/bootstrap.min.js"></script> <script async defer src="path_to_url"></script> <script src="path_to_url"></script> <script id="MathJax-script" async src="path_to_url"></script> </body> </html> ```
Amy Nicole Langville (born 1975) is an American mathematician and operations researcher, and is also a former star basketball player at the high school and college levels. One of the main topics in her research is ranking systems such as the PageRank system used by Google for ranking web pages. She has also applied her ranking expertise to basketball bracketology. She is a professor of mathematics at the College of Charleston. Education and career Langville grew up in Arnold, Maryland, and was a star basketball player for Archbishop Spalding High School, becoming the top player on the Academic All-Maryland women's basketball team. She also played on the school's volleyball team, was president of the school branch of the National Honor Society, graduated at the top of her class, and was listed by the Maryland Higher Education Commission as a Maryland Distinguished Scholar. After being "recruited by more than 50 colleges", she became an undergraduate at Mount St. Mary's College and a player for the Mount St. Mary's Mountaineers women's basketball team, on a full basketball scholarship; she was Northeast Conference Women's Basketball Player of the Year for 1995–1996. She earned a bachelor's degree in mathematics at Mount St. Mary's in 1997, as the school valedictorian, and was named to the 1997 GTE academic all-American women's basketball first team. She earned a Ph.D. in operations research at North Carolina State University in 2002. Her dissertation, Preconditioning techniques, was supervised by William J. Stewart. She remained at North Carolina State University for postdoctoral research, following which she joined the College of Charleston faculty in 2005. She was promoted to full professor in 2015. Books Langville is the co-author with Carl D. Meyer of two books on ranking, both published by the Princeton University Press. The first, Google's PageRank and Beyond: The Science of Search Engine Rankings, concerns search engines and the PageRank method used by Google's search engine for ranking web pages in search results; it was published in 2006. The second, Who's #1? — The Science of Rating and Ranking (published in 2012) extends her study to ranking systems more generally. The Basic Library List Committee of the Mathematical Association of America has suggested that it be included in undergraduate mathematics libraries. References 1975 births Living people People from Anne Arundel County, Maryland Basketball players from Maryland 21st-century American mathematicians American women mathematicians Operations researchers Mount St. Mary's Mountaineers women's basketball players North Carolina State University alumni College of Charleston faculty 21st-century American women academics
```php <?php /* * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the */ namespace Google\Service\DataCatalog; class GoogleCloudDatacatalogV1BigQueryTableSpec extends \Google\Model { /** * @var string */ public $tableSourceType; protected $tableSpecType = GoogleCloudDatacatalogV1TableSpec::class; protected $tableSpecDataType = ''; protected $viewSpecType = GoogleCloudDatacatalogV1ViewSpec::class; protected $viewSpecDataType = ''; /** * @param string */ public function setTableSourceType($tableSourceType) { $this->tableSourceType = $tableSourceType; } /** * @return string */ public function getTableSourceType() { return $this->tableSourceType; } /** * @param GoogleCloudDatacatalogV1TableSpec */ public function setTableSpec(GoogleCloudDatacatalogV1TableSpec $tableSpec) { $this->tableSpec = $tableSpec; } /** * @return GoogleCloudDatacatalogV1TableSpec */ public function getTableSpec() { return $this->tableSpec; } /** * @param GoogleCloudDatacatalogV1ViewSpec */ public function setViewSpec(GoogleCloudDatacatalogV1ViewSpec $viewSpec) { $this->viewSpec = $viewSpec; } /** * @return GoogleCloudDatacatalogV1ViewSpec */ public function getViewSpec() { return $this->viewSpec; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(GoogleCloudDatacatalogV1BigQueryTableSpec::class, your_sha256_hashSpec'); ```
```python # # This software may be used and distributed according to the terms of the """ integration with a native debugger like lldb Check path_to_url for APIs. This file runs standalone by lldb's Python interperter. It does not have access to `bindings` or other Sapling modules. Do not import Sapling modules here. There are 2 ways to use this feature, - Use `debugbt` command. - Use `lldb -p <pid>`, then run `command script import ./dbgutil.py`, then use the `bta` command. """ import functools import struct import subprocess import sys def backtrace_all(ui, pid: int): """write backtraces of all threads of the given pid. Runs inside Sapling Python environment. """ import inspect import os import tempfile import bindings python_source = inspect.getsource(sys.modules["sapling.dbgutil"]) with tempfile.TemporaryDirectory(prefix="saplinglldb") as dir: python_script_path = os.path.join(dir, "dbgutil.py") if ui.formatted: out_path = "" else: # Buffer output so we out_path = os.path.join(dir, "bta_output.txt") with open(python_script_path, "wb") as f: f.write(python_source.encode()) args = [ ui.config("ui", "lldb") or "lldb", "-b", "--source-quietly", "-o", f"command script import {python_script_path}", "-o", f"bta {pid}{out_path and ' ' + out_path}", ] subprocess.run(args, stdout=(subprocess.DEVNULL if out_path else None)) if out_path: with open(out_path, "rb") as f: data = f.read() ui.writebytes(data) def _lldb_backtrace_all_attach_pid(pid, write): """Attach to a pid and write its backtraces. Runs inside lldb Python environment, outside Sapling environment. """ import lldb debugger = lldb.debugger target = debugger.CreateTarget("") process = target.AttachToProcessWithID(lldb.SBListener(), pid, lldb.SBError()) try: _lldb_backtrace_all_for_process(target, process, write) finally: if sys.platform == "win32": # Attempt to resume the suspended process. "Detach()" alone does not # seem to resume it... debugger.SetAsync(True) process.Continue() process.Detach() def _lldb_backtrace_all_for_process(target, process, write): """Write backtraces for the given lldb target/process. Runs inside lldb Python environment, outside Sapling environment. """ import lldb if target.addr_size != 8: write("non-64-bit (%s) architecture is not yet supported\n" % target.addr_size) return def read_u64(address: int) -> int: """read u64 from an address""" return struct.unpack("Q", process.ReadMemory(address, 8, lldb.SBError()))[0] def resolve_frame(frame) -> str: """extract python stack info from a frame. The frame should be a Sapling_PyEvalFrame function call. """ # Sapling_PyEvalFrame(PyThreadState* tstate, PyFrameObject* f, int exc) # # x64: # pushq %rbp # movq %rsp, %rbp ; FP # subq $0x20, %rsp ; SP = FP - 0x20 # movq %rdi, -0x8(%rbp) # movq %rsi, -0x10(%rbp) ; PyFrame f at FP - 0x10, or SP + 0x10 # movl %edx, -0x14(%rbp) # movq -0x8(%rbp), %rdi # movq -0x10(%rbp), %rsi # movl -0x14(%rbp), %edx # callq 0x1034bddee ; symbol stub for: _PyEval_EvalFrameDefault # addq $0x20, %rsp # popq %rbp # retq # # arm64 (x29 is FP): # sub sp, sp, #0x30 # stp x29, x30, [sp, #0x20] # add x29, sp, #0x20 ; FP = SP + 0x20 # stur x0, [x29, #-0x8] ; x0 is 1st arg (tstate) # str x1, [sp, #0x10] ; x1 is 2nd arg, `f`, at SP + 0x10 # str w2, [sp, #0xc] # ldur x0, [x29, #-0x8] # ldr x1, [sp, #0x10] # ldr w2, [sp, #0xc] # bl 0x1046b6140 ; symbol stub for: _PyEval_EvalFrameDefault # ldp x29, x30, [sp, #0x20] # add sp, sp, #0x30 # ret # # x64 MSVC: # ; Sapling_PyEvalFrame(PyThreadState* tstate, PyFrame* f, int exc) { # push rbp # sub rsp,40h # lea rbp,[rsp+40h] # mov dword ptr [rbp-4],r8d # mov qword ptr [rbp-18h],rdx ; FP - 0x18 # mov qword ptr [rbp-10h],rcx # ; return _PyEval_EvalFrameDefault(tstate, f, exc); # mov r8d,dword ptr [exc] # mov rdx,qword ptr [f] # mov rcx,qword ptr [tstate] # call qword ptr [__imp__PyEval_EvalFrameDefault (07FF748CDDF40h)] # nop # add rsp,40h # pop rbp # ret fp: int = frame.fp sp: int = frame.sp ptr_addr = None if fp - sp == 0x40 and sys.platform == "win32": ptr_addr = fp - 0x18 elif fp - sp == 0x20: ptr_addr = fp - 0x10 if ptr_addr is not None: try: python_frame_address = read_u64(ptr_addr) return resolve_python_frame(python_frame_address) except Exception as e: return f"<error {e} {ptr_addr}>" return "" def resolve_python_frame(python_frame_address: int) -> str: # NOTE: `sapling_cext_evalframe_resolve_frame` needs the Python GIL # to be "safe". However, it is likely just reading a bunch of # objects (ex. frame, code, str) and those objects are not being # GC-ed (since the call stack need them). So it is probably okay. value = target.EvaluateExpression( f"(char *)(sapling_cext_evalframe_resolve_frame((size_t){python_frame_address}))" ) return (value.GetSummary() or "").strip('"') for thread in process.threads: write(("%r\n") % thread) frames = [] # [(frame | None, line)] has_resolved_python_frame = False for i, frame in enumerate(thread.frames): name = frame.GetDisplayFunctionName() if name == "Sapling_PyEvalFrame": resolved = resolve_frame(frame) if resolved: has_resolved_python_frame = True # The "frame #i" format matches the repr(frame) style. frames.append((None, f" frame #{i}: {resolved}\n")) continue if name: frames.append((frame, f" {repr(frame)}\n")) if has_resolved_python_frame: # If any Python frame is resolved, strip out noisy frames like _PyEval_EvalFrameDefault. frames = [ (frame, line) for frame, line in frames if not _is_cpython_function(frame) ] write("".join(line for _frame, line in frames)) write("\n") def _is_cpython_function(frame) -> bool: return frame is not None and "python" in (frame.module.file.basename or "").lower() def _lldb_backtrace_all_command(debugger, command, exe_ctx, result, internal_dict): """lldb command: bta [pid] [PATH]. Write Python+Rust traceback to stdout or PATH.""" args = command.split(" ", 1) if len(args) >= 1 and args[0]: pid = int(args[0]) impl = functools.partial(_lldb_backtrace_all_attach_pid, pid) else: target = exe_ctx.target process = exe_ctx.process impl = functools.partial(_lldb_backtrace_all_for_process, target, process) path = args[1].strip() if len(args) >= 2 else None if path: with open(path, "w", newline="\n") as f: impl(f.write) f.flush() else: impl(sys.stdout.write) def __lldb_init_module(debugger, internal_dict): # When imported by lldb 'command script import', this function is called. # Add a 'bta' command to call _lldb_backtrace_all. debugger.HandleCommand( f"command script add -f {__name__}._lldb_backtrace_all_command bta" ) ```
D. J. James (born March 5, 2001) is an American football cornerback for the Auburn Tigers. He previously played at Oregon. Early life and high school James grew up in Mobile, Alabama and attended Spanish Fort High School. He was rated a three-star recruit and initially committed to play college football at Mississippi State. James later flipped his commitment to Oregon. College career James began his college career at Oregon. He had 46 tackles, two interceptions, and four passes broken up as a junior. Following the season, James entered the NCAA transfer portal. James ultimately chose to transfer to Auburn. He was named second-team All-Southeastern Conference (SEC) in his first season with the Tigers after making 37 tackles with one interception and eight passes broken up. References External links Oregon Ducks bio Auburn Tigers bio 2001 births Living people Players of American football from Mobile, Alabama American football cornerbacks Auburn Tigers football players Oregon Ducks football players
Quzhd (, also Romanized as Qūzhd) is a village in, and the capital of Bala Velayat Rural District of the Central District of Kashmar County, Razavi Khorasan province, Iran. At the 2006 National Census, its population was 4,024 in 1,087 households. The following census in 2011 counted 4,344 people in 1,281 households. The latest census in 2016 showed a population of 4,650 people in 1,435 households; it was the largest village in its rural district. Historical sites, ancient artifacts and tourism Grave of Pir Quzhd Grave of Pir Quzhd is a historical Grave related to the Before the 11th century AH and is located in Quzhd, Razavi Khorasan Province. Rig Castle Rig castle is a Castle related to the Seljuq dynasty and is located in the Kashmar County, Quzhd village. Talaabad Watermill Talaabad Watermill is a Watermill related to the late Safavid period and is located in Kashmar County, Central District, Quzhd village. Qanats of Quzhd The Qanats of Quzhd is a historical Qanat is located in Quzhd in Kashmar County. References Kashmar County Populated places in Kashmar County
Emily Rooney (born January 17, 1950) is an American journalist, TV talk show and radio host and former news producer. She hosted the weekly program Beat the Press on WGBH-TV. until its cancellation on August 13, 2021. Career In the mid-to-late 1970s, Rooney worked at the CBS affiliate in Hartford, Connecticut, WFSB as an assignment editor among other positions at the station. From 1979 to 1993, she worked at WCVB-TV in Boston as assistant news director, and then a news director for three years. For about one year, from 1993 to 1994, she was executive producer of World News Tonight with Peter Jennings, ABC's nightly news program. Following her tenure with ABC and WCVB, Rooney was director of political coverage and special events at the Fox Network in New York, from 1994 to 1997. From 1997 to 2014, she was also the creator, executive editor, and moderator of Greater Boston, which was later rebroadcast on the Boston-based WGBH radio station, where she also hosted the Emily Rooney Show. During that same period, Rooney moderated a weekly media analysis TV show, Beat the Press. On May 29, 2014, WGBH announced Emily Rooney would be stepping down from her host position on the Greater Boston TV show to become a special correspondent for the program. After 18 years as host, her final Greater Boston show aired on December 18 of that year. She continued to host Beat the Press until its cancellation on August 13, 2021. Controversy On March 29, 2021, a public letter signed by over 700 filmmakers was sent to PBS President Paula Kerger titled, "A letter to PBS from Viewers like Us". It was organized by Beyond Inclusion, BIPOC-led collective of non-fiction filmmakers, executives, and field builders.." The letter was in response to recent conversations sparked by Grace Lee’s essay for the Ford Foundation’s Creative Futures series and Kerger’s public response to it. That letter raised questions about how much funding and airtime filmmaker Ken Burns has received over the years in comparison to BIPOC filmmakers, and demanded access to specific data about equity across the board. On April 2, 2021, during a Beat the Press episode discussing the PBS letter, the six-hour documentary Hemingway by Ken Burns, and the five-hour documentary Asian Americans from Renee Tajima-Peña, Emily Rooney remarked, "I didn’t see Asian Americans but there’s a possibility it wasn’t as good as some of Ken Burns’ films." At the end of the show, she stated, "regardless of what this group says, it’s resentment that a white guy [Burns] is getting all this time. On April 14, a letter was sent to WGBH from a New England group of filmmakers that grew out of the Documentary Producers Alliance-Northeast in solidarity with Beyond Inclusion, also condemning Rooney’s comments. In reply, WGBH General Manager Pam Johnston "rebuked the comments" in a statement: "Emily Rooney’s comments on the April 2 edition of Beat the Press did not meet WGBH’s standards for opinion journalism, or our commitment to being an anti-racist organization that respects all people." In a follow-up letter dated April 16, the regional group now referred to as Filmmakers in Solidarity, pointed out the urgent need to address the lack of diverse voices in public media locally, as well as nationally. Among other requests, they demanded Rooney apologize for relying on "derision, racist tropes and more ignorance than fact" when discussing the lack of diverse filmmakers on PBS. On April 16, she issued a pre-recorded apology at the start of her WGBH show, Beat the Press. In it, Rooney said her remarks were "uninformed, dismissive, and disrespectful" and while her "intention was to offer further balance to the discussion" she acknowledged "my comments did not accomplish that and instead I crossed a line." Asian Americans, from Series Producer Renee Tajima-Peña, won a Peabody Award in June 2021. Personal life Emily Rooney is the daughter of noted CBS 60 Minutes correspondent and humorist Andy Rooney. She has an identical twin sister, Martha, who is Chief of the Public Services Division at the United States National Library of Medicine in Bethesda, Maryland. Her brother Brian Rooney was a correspondent for ABC News for 23 years. Rooney has one daughter, Alexis. Rooney's husband, WCVB-TV reporter Kirby Perkins, died suddenly of heart failure July 1997. Rooney lived in the metro west suburb of Newton for many years and now resides in Boston's Back Bay neighborhood. Education She is a graduate of American University in Washington and holds honorary doctoral degrees from the University of Massachusetts Boston and Westfield State College. Honors Emily Rooney has been awarded the National Press Club's Arthur Rowse Award for Press Criticism, a series of New England Emmy Awards, and Associated Press recognition for Best News/Talk Show. Rooney's WGBH news program, Greater Boston, has received two Regional Edward R. Murrow broadcast journalism awards and five New England Emmy awards. Rooney has also received a New England Emmy in the category of Outstanding Achievement in Commentary/Editorial. References External links American talk radio hosts American University alumni American women radio hosts 1950 births Living people Identical twins American twins WGBH Educational Foundation
Cirujeda () is a village in Teruel, Aragón, Spain. It is part of the municipality of Aliaga. References Towns in Spain Populated places in the Province of Teruel Province of Teruel
Nils Skog (16 December 1877 – 28 April 1964) was a Swedish sports shooter. He competed in the 300m free rifle, three positions event at the 1912 Summer Olympics. References External links 1877 births 1964 deaths Swedish male sport shooters Olympic shooters for Sweden Shooters at the 1912 Summer Olympics Sportspeople from Gävleborg County
The Diocese of Sessa Aurunca () is a Latin diocese of the Catholic Church in southern Italy. Since 1979 it has been a suffragan of the Archdiocese of Naples. History The inhabitants of Sessa Aurunca venerate as patron saint their Bishop, St. Castus, a martyr at the end of the third century. Scholars, however, reject the notion that he was a bishop of Sessa. There still remain ruins of the ancient basilica dedicated to him, with which catacombs are still connected. The first bishop of certain date was Fortunatus (499); but until the end of the tenth century the names of the bishops are unknown. It is likely that Sessa Aurunca became the suffragan (subordinate) of Capua, when that diocese was raised to metropolitan status in 966 by Pope John XIII. It was certainly the case in March 1032, however, when Archbishop Atenulf of Capua consecrated Bishop Benedict of Sessa Aurunca, and confirmed him in the possession of the diocese, just as his predecessors had done. In the twelfth century, under the Normans, Suessa was part of the ecclesiastical province of Capua. The new cathedral was consecrated in 1113. Cathedral The ancient cathedral of Sessa, dedicated to the Virgin Mary, was outside the city, next to the walls. In 1113 the seat of the bishop was transferred to a new cathedral in the center of the city, which was dedicated on 14 July to the Virgin Mary and Saint Peter. The cathedral is staffed and administered by a corporation, the Chapter, which is composed of four dignities (the Archdeacon, the Dean, and two Primicerii) and sixteen Canons. In 1757, there were twenty-five Canons. Concordat of 1818 Following the extinction of the Napoleonic Kingdom of Italy, the Congress of Vienna authorized the restoration of the Papal States and the Kingdom of Naples. Since the French occupation had seen the abolition of many Church institutions in the Kingdom, as well as the confiscation of most Church property and resources, it was imperative that Pope Pius VII and King Ferdinand IV reach agreement on restoration and restitution. Ferdinand, however, was not prepared to accept the pre-Napoleonic situation, in which Naples was a feudal subject of the papacy. Lengthy, detailed, and acrimonious negotiations ensued. In 1818, a new concordat with the Kingdom of the Two Sicilies committed the pope to the suppression of more than fifty small dioceses in the kingdom. The ecclesiastical province of Naples was spared from any suppressions, but the province of Capua was affected. Pope Pius VII, in the bull "De Utiliori" of 27 June 1818, chose to suppress the diocese of Carinola (which is only five miles from Sessa) completely, and assign its people and territory to the diocese of Sessa. In the same concordat, the King was confirmed in the right to nominate candidates for vacant bishoprics, subject to the approval of the pope. That situation persisted down until the final overthrow of the Bourbon monarchy in 1860. New ecclesiastical province Following the Second Vatican Council, and in accordance with the norms laid out in the Council's decree, Christus Dominus chapter 40, major changes were made in the ecclesiastical administrative structure of southern Italy. Wide consultations had taken place with the bishops and other prelates who would be affected. Action, however, was deferred, first by the death of Pope Paul VI on 6 August 1978, then the death of Pope John Paul I on 28 September 1978, and the election of Pope John Paul II on 16 October 1978. Pope John Paul II issued a decree, "Quamquam Ecclesia," on 30 April 1979, ordering the changes. Three ecclesiastical provinces were abolished entirely: those of Conza, Capua, and Sorrento. A new ecclesiastical province was created, to be called the Regio Campana, whose Metropolitan was the Archbishop of Naples. The dioceses formerly members of the suppressed Province of Capua (Gaeta, Calvi and Teano, Caserta, and Sessa Arunca) became suffragans of Naples. Bishops of Sessa (Suessa) to 1100 Fortunatus (ca. 499–501) [Risus] [Jacobus] Joannes (ca. 998) ... Benedictus (attested 1032–1059) Milo, O.S.B. (c.1071) Benedictus (1092) ... 1100 to 1400 Jacobus, O.S.B. (first decade of 12th cent.) Joannes, O.S.B. (attested 1113) Gregorius, O.S.B. (attested 1120) Godofredus (attested 1126) Robertus ? Risus Hervaeus (Erveo) (attested 1171–1197) ... Pandulfus (1224) Joannes (1259–1283) Robertus d'Asprello (1284–1297) Guido (1297–1301) [Deodatus Peccini, O.P.] Robertus (1301–1309) Bertrand (1309–1326) Jacques Matrizio (1326–ca. 1330) Joannes de Paulo (1330– ) Hugo de S. Francisco, O. Min. (1340–ca. 1344) Alexander de Miro (1344–1350) Giacomo Petrucci, O.F.M. (24 May 1350 – 1356 Died) Enrico de Grandonibus de Florentia, O.P. (1356–1363) Matteo Bruni, O.P. (1363–ca. 1383) Filippo Toraldi (1383–1392) Antonio, O.Cist. (1392–1402) ... 1400 to 1700 Angelo Gherardini (15 Apr 1463 – 1486) Pietro Ajosa (4 Aug 1486 – 1492) Martino Zapata (27 Nov 1499 – 1505) Francesco Guastaferro (22 Nov 1505 – 11 May 1543) Tiberio Crispo (6 Jul 1543 – 7 Jun 1546 Resigned) Bartolomeo Albani (7 Jun 1546 –1552) Galeazzo Florimonte (22 Oct 1552 – 1565 Resigned) Tiberio Crispo (1565 – 27 Jun 1566 Resigned) Giovanni Placido (27 Jun 1566 – 20 Jan 1591) Alessandro Riccardi (6 Mar 1591 – 16 May 1604 Died) Faustus Rebaglio (30 Aug 1604 – Feb 1624 Died) Ulysses Gherardini della Rosa (1 Jul 1624 – 9 Jan 1670 Died) Tommaso d'Aquino, C.R. (1670–1705) 1700 to 1900 Raffaele Maria Filamondo, O.P. (14 Dec 1705 – 15 Aug 1706) Francesco Gori (4 Oct 1706 – 1708) Luigi Maria Macedonio, C.M. (8 Jun 1718 – 9 Dec 1727) Francesco Caracciolo, O.F.M. (24 Apr 1728 – 11 Aug 1757) Francesco Antonio Granata (26 Sep 1757 – 11 Jan 1771) Baldassarre Vulcano, O.S.B. (29 Jul 1771 – 20 Mar 1773) Antonio de Torres, O.S.B. (14 Jun 1773 – 29 Oct 1779) Emanuele Maria Pignone del Carretto, O.S.A. (27 Feb 1792 – 27 Sep 1796 Died) Pietro De Felice (18 Dec 1797 – Nov 1814 Died) Bartolomeo Varrone (6 Apr 1818 – 27 Feb 1832) Paolo Garzilli (2 Jul 1832 – 24 Jul 1845) Giuseppe Maria d'Alessandro (24 Nov 1845 – 15 Mar 1848) Ferdinando Girardi, C.M. (11 Sep 1848 – 8 Dec 1866) Raffaele Gagliardi (23 Feb 1872 – 18 Aug 1880) Carlo de Caprio (13 Dec 1880 – 14 Dec 1887) Giovanni Maria Diamare (1 Jun 1888 – 9 Jan 1914) Since 1900 Fortunato de Santa (15 Apr 1914 – 22 Feb 1938 Died) Gaetano De Cicco (30 Jan 1939 – 22 Mar 1962 Retired) Vittorio Maria Costantini, O.F.M. Conv. (28 May 1962 – 25 Oct 1982 Retired) Raffaele Nogaro (25 Oct 1982 – 20 Oct 1990 Appointed, Bishop of Caserta) Agostino Superbo (18 May 1991 – 19 Nov 1994 Appointed, Bishop of Altamura-Gravina-Acquaviva delle Fonti) Antonio Napoletano, C.SS.R. (19 Nov 1994 – 25 Jun 2013 Retired) Orazio Francesco Piazza (25 Jun 2013 – ) References Books Reference works p. 921-922. (Use with caution; obsolete) p. 467-468. (in Latin) p. 243. (in Latin) p. 305. (in Latin) p. 324. (in Latin) p. 365. p. 388. Studies Kamp, Norbert (2002), "The bishops of southern Italy in the Norman and Staufen Periods," in: Graham A. Loud and Alex Metcalfe (edd.), The society of Norman Italy (Leiden/Boston/Köln, 2002), pp. 185–209. Kehr, Paul Fridolin (1925). Italia pontificia Vol. VIII (Berlin: Weidmann 1925), pp. 268–270. Lanzoni, Francesco (1927). Le diocesi d'Italia dalle origini al principio del secolo VII (an. 604). Faenza: F. Lega, pp. 178–185. Acknowledgment Sessa Sessa Aurunca
```smalltalk using System; using Android.Runtime; namespace Android.App { public partial class Instrumentation { public void RunOnMainSync (Action runner) { RunOnMainSync (new Java.Lang.Thread.RunnableImplementor (runner)); } public void WaitForIdle (Action recipient) { WaitForIdle (new Java.Lang.Thread.RunnableImplementor (recipient)); } } } ```
```java /* * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package org.apache.beam.io.requestresponse; /** * Extends {@link UserCodeQuotaException} to allow the user custom code to specifically signal a * Quota or API overuse related error. */ public class UserCodeQuotaException extends UserCodeExecutionException { public UserCodeQuotaException(String message) { super(message); } public UserCodeQuotaException(String message, Throwable cause) { super(message, cause); } public UserCodeQuotaException(Throwable cause) { super(cause); } public UserCodeQuotaException( String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } /** Reports that quota errors should be repeated. */ @Override public boolean shouldRepeat() { return true; } } ```
```css `currentColor` improves code reusability Use pseudo-classes to describe a special state of an element Adjacent sibling selector Debug with `*` selector Conditional comments ```
```javascript var withBase64 = require('./source-map-base64.js'); var withMap = require('./source-map-external.js'); console.log(withBase64()); console.log(withMap.default()); console.log("Hello") ```
```html <!DOCTYPE html> <html class="writer-html5" lang="en" > <head> <meta charset="utf-8" /><meta name="generator" content="Docutils 0.18.1: path_to_url" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Deploying Web Applications in the Cloud &mdash; Ring 1.21 documentation</title> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="_static/css/theme.css" type="text/css" /> <link rel="stylesheet" href="_static/css/custom.css" type="text/css" /> <!--[if lt IE 9]> <script src="_static/js/html5shiv.min.js"></script> <![endif]--> <script src="_static/jquery.js"></script> <script src="_static/_sphinx_javascript_frameworks_compat.js"></script> <script data-url_root="./" id="documentation_options" src="_static/documentation_options.js"></script> <script src="_static/doctools.js"></script> <script src="_static/sphinx_highlight.js"></script> <script src="_static/js/theme.js"></script> <link rel="index" title="Index" href="genindex.html" /> <link rel="search" title="Search" href="search.html" /> <link rel="next" title="Graphics and 2D Games programming using RingAllegro" href="allegro.html" /> <link rel="prev" title="Web Development (CGI Library)" href="web.html" /> </head> <body class="wy-body-for-nav"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-scroll"> <div class="wy-side-nav-search" > <a href="index.html"> <img src="_static/ringdoclogo.jpg" class="logo" alt="Logo"/> </a> <div role="search"> <form id="rtd-search-form" class="wy-form" action="search.html" method="get"> <input type="text" name="q" placeholder="Search docs" aria-label="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div><div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu"> <ul class="current"> <li class="toctree-l1"><a class="reference internal" href="ringapps.html">Applications developed in a few hours</a></li> <li class="toctree-l1"><a class="reference internal" href="introduction.html">Introduction</a></li> <li class="toctree-l1"><a class="reference internal" href="ringnotepad.html">Using Ring Notepad</a></li> <li class="toctree-l1"><a class="reference internal" href="getting_started.html">Getting Started - First Style</a></li> <li class="toctree-l1"><a class="reference internal" href="getting_started2.html">Getting Started - Second Style</a></li> <li class="toctree-l1"><a class="reference internal" href="getting_started3.html">Getting Started - Third Style</a></li> <li class="toctree-l1"><a class="reference internal" href="variables.html">Variables</a></li> <li class="toctree-l1"><a class="reference internal" href="operators.html">Operators</a></li> <li class="toctree-l1"><a class="reference internal" href="controlstructures.html">Control Structures - First Style</a></li> <li class="toctree-l1"><a class="reference internal" href="controlstructures2.html">Control Structures - Second Style</a></li> <li class="toctree-l1"><a class="reference internal" href="controlstructures3.html">Control Structures - Third Style</a></li> <li class="toctree-l1"><a class="reference internal" href="getinput.html">Getting Input</a></li> <li class="toctree-l1"><a class="reference internal" href="functions.html">Functions - First Style</a></li> <li class="toctree-l1"><a class="reference internal" href="functions2.html">Functions - Second Style</a></li> <li class="toctree-l1"><a class="reference internal" href="functions3.html">Functions - Third Style</a></li> <li class="toctree-l1"><a class="reference internal" href="programstructure.html">Program Structure</a></li> <li class="toctree-l1"><a class="reference internal" href="lists.html">Lists</a></li> <li class="toctree-l1"><a class="reference internal" href="strings.html">Strings</a></li> <li class="toctree-l1"><a class="reference internal" href="dateandtime.html">Date and Time</a></li> <li class="toctree-l1"><a class="reference internal" href="checkandconvert.html">Check Data Type and Conversion</a></li> <li class="toctree-l1"><a class="reference internal" href="mathfunc.html">Mathematical Functions</a></li> <li class="toctree-l1"><a class="reference internal" href="files.html">Files</a></li> <li class="toctree-l1"><a class="reference internal" href="systemfunc.html">System Functions</a></li> <li class="toctree-l1"><a class="reference internal" href="evaldebug.html">Eval() and Debugging</a></li> <li class="toctree-l1"><a class="reference internal" href="demo.html">Demo Programs</a></li> <li class="toctree-l1"><a class="reference internal" href="odbc.html">ODBC Functions</a></li> <li class="toctree-l1"><a class="reference internal" href="mysql.html">MySQL Functions</a></li> <li class="toctree-l1"><a class="reference internal" href="sqlite.html">SQLite Functions</a></li> <li class="toctree-l1"><a class="reference internal" href="postgresql.html">PostgreSQL Functions</a></li> <li class="toctree-l1"><a class="reference internal" href="secfunc.html">Security and Internet Functions</a></li> <li class="toctree-l1"><a class="reference internal" href="oop.html">Object Oriented Programming (OOP)</a></li> <li class="toctree-l1"><a class="reference internal" href="fp.html">Functional Programming (FP)</a></li> <li class="toctree-l1"><a class="reference internal" href="metaprog.html">Reflection and Meta-programming</a></li> <li class="toctree-l1"><a class="reference internal" href="declarative.html">Declarative Programming using Nested Structures</a></li> <li class="toctree-l1"><a class="reference internal" href="natural.html">Natural language programming</a></li> <li class="toctree-l1"><a class="reference internal" href="naturallibrary.html">Using the Natural Library</a></li> <li class="toctree-l1"><a class="reference internal" href="scope.html">Scope Rules for Variables and Attributes</a></li> <li class="toctree-l1"><a class="reference internal" href="scope2.html">Scope Rules for Functions and Methods</a></li> <li class="toctree-l1"><a class="reference internal" href="syntaxflexibility.html">Syntax Flexibility</a></li> <li class="toctree-l1"><a class="reference internal" href="typehints.html">The Type Hints Library</a></li> <li class="toctree-l1"><a class="reference internal" href="debug.html">The Trace Library and the Interactive Debugger</a></li> <li class="toctree-l1"><a class="reference internal" href="ringemb.html">Embedding Ring Language in Ring Programs</a></li> <li class="toctree-l1"><a class="reference internal" href="stdlib.html">Stdlib Functions</a></li> <li class="toctree-l1"><a class="reference internal" href="stdlibclasses.html">Stdlib Classes</a></li> <li class="toctree-l1"><a class="reference internal" href="qt.html">Desktop, WebAssembly and Mobile development using RingQt</a></li> <li class="toctree-l1"><a class="reference internal" href="formdesigner.html">Using the Form Designer</a></li> <li class="toctree-l1"><a class="reference internal" href="qt3d.html">Graphics Programming using RingQt3D</a></li> <li class="toctree-l1"><a class="reference internal" href="ringqtobjects.html">Objects Library for RingQt Application</a></li> <li class="toctree-l1"><a class="reference internal" href="multilanguage.html">Multi-language Applications</a></li> <li class="toctree-l1"><a class="reference internal" href="qtmobile.html">Building RingQt Applications for Mobile</a></li> <li class="toctree-l1"><a class="reference internal" href="qtwebassembly.html">Building RingQt Applications for WebAssembly</a></li> <li class="toctree-l1"><a class="reference internal" href="web.html">Web Development (CGI Library)</a></li> <li class="toctree-l1 current"><a class="current reference internal" href="#">Deploying Web Applications in the Cloud</a><ul> <li class="toctree-l2"><a class="reference internal" href="#introduction">Introduction</a></li> <li class="toctree-l2"><a class="reference internal" href="#usage">Usage</a></li> <li class="toctree-l2"><a class="reference internal" href="#ring-source-code-files-and-permissions">Ring source code files and permissions</a></li> <li class="toctree-l2"><a class="reference internal" href="#hello-world-program">Hello World program</a></li> <li class="toctree-l2"><a class="reference internal" href="#application-database">Application Database</a></li> <li class="toctree-l2"><a class="reference internal" href="#deploying-after-updates">Deploying after updates</a></li> <li class="toctree-l2"><a class="reference internal" href="#local-tests">Local Tests</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="allegro.html">Graphics and 2D Games programming using RingAllegro</a></li> <li class="toctree-l1"><a class="reference internal" href="gameengine.html">Demo Project - Game Engine for 2D Games</a></li> <li class="toctree-l1"><a class="reference internal" href="gameengineandorid.html">Building Games For Android</a></li> <li class="toctree-l1"><a class="reference internal" href="ringraylib.html">Developing Games using RingRayLib</a></li> <li class="toctree-l1"><a class="reference internal" href="usingopengl.html">Using RingOpenGL and RingFreeGLUT for 3D Graphics</a></li> <li class="toctree-l1"><a class="reference internal" href="usingopengl2.html">Using RingOpenGL and RingAllegro for 3D Graphics</a></li> <li class="toctree-l1"><a class="reference internal" href="goldmagic800.html">Demo Project - The Gold Magic 800 Game</a></li> <li class="toctree-l1"><a class="reference internal" href="tilengine.html">Using RingTilengine</a></li> <li class="toctree-l1"><a class="reference internal" href="performancetips.html">Performance Tips</a></li> <li class="toctree-l1"><a class="reference internal" href="compiler.html">Command Line Options</a></li> <li class="toctree-l1"><a class="reference internal" href="distribute.html">Distributing Ring Applications (Manual)</a></li> <li class="toctree-l1"><a class="reference internal" href="distribute_ring2exe.html">Distributing Ring Applications using Ring2EXE</a></li> <li class="toctree-l1"><a class="reference internal" href="ringpm.html">The Ring Package Manager (RingPM)</a></li> <li class="toctree-l1"><a class="reference internal" href="zerolib.html">ZeroLib Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="foxringfuncsdoc.html">FoxRing Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="bignumber.html">BigNumber Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="csvlib.html">CSVLib Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="jsonlib.html">JSONLib Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="httplib.html">HTTPLib Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="tokenslib.html">TokensLib Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="libcurl.html">Using RingLibCurl</a></li> <li class="toctree-l1"><a class="reference internal" href="ringlibcurlfuncsdoc.html">RingLibCurl Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="socket.html">Using RingSockets</a></li> <li class="toctree-l1"><a class="reference internal" href="threads.html">Using RingThreads</a></li> <li class="toctree-l1"><a class="reference internal" href="libui.html">Using RingLibui</a></li> <li class="toctree-l1"><a class="reference internal" href="ringzip.html">Using RingZip</a></li> <li class="toctree-l1"><a class="reference internal" href="ringlibzipfuncsdoc.html">RingLibZip Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="ringmurmurhashfuncsdoc.html">RingMurmurHash Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="ringconsolecolorsfuncsdoc.html">RingConsoleColors Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="usingrogueutil.html">Using RingRogueUtil</a></li> <li class="toctree-l1"><a class="reference internal" href="ringallegrofuncsdoc.html">RingAllegro Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="libsdl.html">Using RingLibSDL</a></li> <li class="toctree-l1"><a class="reference internal" href="ringlibsdlfuncsdoc.html">RingLibSDL Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="libuv.html">Using Ringlibuv</a></li> <li class="toctree-l1"><a class="reference internal" href="ringlibuvfuncsdoc.html">RingLibuv Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="ringfreeglutfuncsdoc.html">RingFreeGLUT Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="ringstbimage.html">RingStbImage Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="ringopengl32funcsdoc.html">RingOpenGL (OpenGL 3.2) Functions Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="qtclassesdoc.html">RingQt Classes and Methods Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="usingfastpro.html">Using FastPro Extension</a></li> <li class="toctree-l1"><a class="reference internal" href="usingref.html">Using References</a></li> <li class="toctree-l1"><a class="reference internal" href="lowlevel.html">Low Level Functions</a></li> <li class="toctree-l1"><a class="reference internal" href="extension_tutorial.html">Tutorial: Ring Extensions in C/C++</a></li> <li class="toctree-l1"><a class="reference internal" href="extension.html">Extension using the C/C++ languages</a></li> <li class="toctree-l1"><a class="reference internal" href="embedding.html">Embedding Ring Language in C/C++ Programs</a></li> <li class="toctree-l1"><a class="reference internal" href="codegenerator.html">Code Generator for wrapping C/C++ Libraries</a></li> <li class="toctree-l1"><a class="reference internal" href="ringbeep.html">Create your first extension using the Code Generator</a></li> <li class="toctree-l1"><a class="reference internal" href="languagedesign.html">Release Notes: Version 1.0</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew.html">Release Notes: Version 1.1</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew2.html">Release Notes: Version 1.2</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew3.html">Release Notes: Version 1.3</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew4.html">Release Notes: Version 1.4</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew5.html">Release Notes: Version 1.5</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew6.html">Release Notes: Version 1.6</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew7.html">Release Notes: Version 1.7</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew8.html">Release Notes: Version 1.8</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew9.html">Release Notes: Version 1.9</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew10.html">Release Notes: Version 1.10</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew11.html">Release Notes: Version 1.11</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew12.html">Release Notes: Version 1.12</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew13.html">Release Notes: Version 1.13</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew14.html">Release Notes: Version 1.14</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew15.html">Release Notes: Version 1.15</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew16.html">Release Notes: Version 1.16</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew17.html">Release Notes: Version 1.17</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew18.html">Release Notes: Version 1.18</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew19.html">Release Notes: Version 1.19</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew20.html">Release Notes: Version 1.20</a></li> <li class="toctree-l1"><a class="reference internal" href="whatisnew21.html">Release Notes: Version 1.21</a></li> <li class="toctree-l1"><a class="reference internal" href="codeeditors.html">Using Other Code Editors</a></li> <li class="toctree-l1"><a class="reference internal" href="faq.html">Frequently Asked Questions (FAQ)</a></li> <li class="toctree-l1"><a class="reference internal" href="sourcecode.html">Building From Source Code</a></li> <li class="toctree-l1"><a class="reference internal" href="contribute.html">How to contribute?</a></li> <li class="toctree-l1"><a class="reference internal" href="reference.html">Language Specification</a></li> <li class="toctree-l1"><a class="reference internal" href="resources.html">Resources</a></li> </ul> </div> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"><nav class="wy-nav-top" aria-label="Mobile navigation menu" > <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="index.html">Ring</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="Page navigation"> <ul class="wy-breadcrumbs"> <li><a href="index.html" class="icon icon-home" aria-label="Home"></a></li> <li class="breadcrumb-item active">Deploying Web Applications in the Cloud</li> <li class="wy-breadcrumbs-aside"> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="path_to_url"> <div itemprop="articleBody"> <section id="deploying-web-applications-in-the-cloud"> <span id="index-0"></span><h1>Deploying Web Applications in the Cloud<a class="headerlink" href="#deploying-web-applications-in-the-cloud" title="Permalink to this heading"></a></h1> <p>In this chapter we will learn about deploying Ring Web Applications in the Cloud using Heroku</p> <section id="introduction"> <span id="index-1"></span><h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this heading"></a></h2> <p>We created a new project and tutorial to explain how to deploy Ring web applications in the Cloud using Heroku</p> <p>Project : <a class="reference external" href="path_to_url">path_to_url <p>Heroku Website : <a class="reference external" href="path_to_url">path_to_url <img alt="Ring Web Application in the Cloud" src="_images/ringincloud.png" /> </section> <section id="usage"> <span id="index-2"></span><h2>Usage<a class="headerlink" href="#usage" title="Permalink to this heading"></a></h2> <p>To use this project and deploy it on Heroku</p> <ol class="arabic simple"> <li><p>Create Heroku account</p></li> <li><p>Open your Heroku account and create new application</p></li> </ol> <p>Example : testring</p> <p>Note (You have to select a unique name for your application)</p> <ol class="arabic simple" start="3"> <li><p>Open the command prompt, Create new folder : MyApp</p></li> </ol> <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>md MyApp </pre></div> </div> <ol class="arabic simple" start="4"> <li><p>Open the application folder</p></li> </ol> <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>cd MyApp </pre></div> </div> <ol class="arabic simple" start="5"> <li><p>Clone this project using Git (Dont forget the dot in the end to clone in the current directory)</p></li> </ol> <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>git clone path_to_url . </pre></div> </div> <ol class="arabic simple" start="6"> <li><p>Login to Heroku (Enter your Email and Password)</p></li> </ol> <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>heroku login </pre></div> </div> <ol class="arabic simple" start="7"> <li><p>Add heroku (remote) to your Git project</p></li> </ol> <p>change testring to your application name</p> <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>heroku git:remote -a testring </pre></div> </div> <ol class="arabic simple" start="8"> <li><p>Set the buildpacks (So Heroku can know how to support your project)</p></li> </ol> <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>heroku buildpacks:add --index 1 path_to_url heroku buildpacks:add --index 2 path_to_url </pre></div> </div> <ol class="arabic simple" start="9"> <li><p>Now build your project and deploy it</p></li> </ol> <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>git push heroku master </pre></div> </div> <ol class="arabic simple" start="10"> <li><p>Test your project (In the browser)</p></li> </ol> <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>heroku open </pre></div> </div> </section> <section id="ring-source-code-files-and-permissions"> <span id="index-3"></span><h2>Ring source code files and permissions<a class="headerlink" href="#ring-source-code-files-and-permissions" title="Permalink to this heading"></a></h2> <p>To be able to run your new Ring scripts, Set the permission of the file to be executable using Git</p> <p>For example, if you created a file : myscript.ring</p> <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>git update-index --chmod=+x myscript.ring git commit -m &quot;Update file permission&quot; </pre></div> </div> <p>If you are using TortoiseGit, From windows explorer, select the file</p> <p>Right click &gt; Properties &gt; Git &gt; Executable (+x)</p> <p>Then commit and deploy!</p> </section> <section id="hello-world-program"> <span id="index-4"></span><h2>Hello World program<a class="headerlink" href="#hello-world-program" title="Permalink to this heading"></a></h2> <p>file : ringapp/helloworld.ring</p> <div class="highlight-ring notranslate"><div class="highlight"><pre><span></span><span class="c">#!/app/runring.sh -cgi</span> <span class="k">see</span> <span class="s">&quot;content-type: text/html&quot;</span> <span class="o">+</span><span class="n">nl</span><span class="o">+</span><span class="n">nl</span> <span class="k">see</span> <span class="s">&quot;Hello, World!&quot;</span> <span class="o">+</span> <span class="n">nl</span> </pre></div> </div> <p>file : ringapp/helloworld2.ring</p> <div class="highlight-ring notranslate"><div class="highlight"><pre><span></span><span class="c">#!/app/runring.sh -cgi</span> <span class="k">load</span> <span class="s">&quot;weblib.ring&quot;</span> <span class="k">import</span> <span class="n">System</span><span class="p">.</span><span class="n">Web</span> <span class="k">new</span> <span class="n">page</span> <span class="p">{</span> <span class="n">text</span><span class="p">(</span><span class="s">&quot;Hello, World!&quot;</span><span class="p">)</span> <span class="p">}</span> </pre></div> </div> </section> <section id="application-database"> <span id="index-5"></span><h2>Application Database<a class="headerlink" href="#application-database" title="Permalink to this heading"></a></h2> <p>When you deploy the application, Everything will works directly!</p> <p>No change is required, but in practice, You will need to update the next files to use your database</p> <p>There are two scripts to interact with the database (We are using PostgreSQL in the cloud)</p> <p>You will need to update the connection string in these files if you will use another database</p> <ul class="simple"> <li><p>file: ringapp/database/newdb.ring (We run it using the browser for one time to create the tables)</p></li> <li><p>file: ringapp/datalib.ring (Class: Database)</p></li> </ul> <p>In your practical projects, You can write better code (To be able to change the database)</p> <p>Also you can create configuration file (To write the connection string in one place)</p> <p>Database service : <a class="reference external" href="path_to_url">path_to_url </section> <section id="deploying-after-updates"> <span id="index-6"></span><h2>Deploying after updates<a class="headerlink" href="#deploying-after-updates" title="Permalink to this heading"></a></h2> <p>Just use Git and commit then push to heroku</p> <p>file: build.bat contains the next commands for quick tests</p> <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>git add . git commit -m &quot;Update RingWebAppOnHeroku&quot; git push heroku master heroku open </pre></div> </div> </section> <section id="local-tests"> <span id="index-7"></span><h2>Local Tests<a class="headerlink" href="#local-tests" title="Permalink to this heading"></a></h2> <p>Local tests using Ring Notepad on Windows (Using local Apache Web Server)</p> <p>Replace the first line in the file : ringapp/index.ring with</p> <div class="highlight-ring notranslate"><div class="highlight"><pre><span></span><span class="c">#!ring -cgi</span> </pre></div> </div> <p>Then run it from Ring Notepad (Ctrl+F6)</p> </section> </section> </div> </div> <footer><div class="rst-footer-buttons" role="navigation" aria-label="Footer"> <a href="web.html" class="btn btn-neutral float-left" title="Web Development (CGI Library)" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left" aria-hidden="true"></span> Previous</a> <a href="allegro.html" class="btn btn-neutral float-right" title="Graphics and 2D Games programming using RingAllegro" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right" aria-hidden="true"></span></a> </div> <hr/> <div role="contentinfo"> </div> Built with <a href="path_to_url">Sphinx</a> using a <a href="path_to_url">theme</a> provided by <a href="path_to_url">Read the Docs</a>. </footer> </div> </div> </section> </div> <script> jQuery(function () { SphinxRtdTheme.Navigation.enable(false); }); </script> </body> </html> ```
```objective-c /* $OpenBSD: if_ralreg.h,v 1.14 2019/01/13 14:27:15 mpi Exp $ */ /*- * Damien Bergamini <damien.bergamini@free.fr> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #define RAL_RX_DESC_SIZE (sizeof (struct ural_rx_desc)) #define RAL_TX_DESC_SIZE (sizeof (struct ural_tx_desc)) #define RAL_CONFIG_NO 1 #define RAL_IFACE_NO 0 #define RAL_WRITE_MAC 0x02 #define RAL_READ_MAC 0x03 #define RAL_WRITE_MULTI_MAC 0x06 #define RAL_READ_MULTI_MAC 0x07 #define RAL_READ_EEPROM 0x09 /* * MAC registers. */ #define RAL_MAC_CSR0 0x0400 /* ASIC Version */ #define RAL_MAC_CSR1 0x0402 /* System control */ #define RAL_MAC_CSR2 0x0404 /* MAC addr0 */ #define RAL_MAC_CSR3 0x0406 /* MAC addr1 */ #define RAL_MAC_CSR4 0x0408 /* MAC addr2 */ #define RAL_MAC_CSR5 0x040a /* BSSID0 */ #define RAL_MAC_CSR6 0x040c /* BSSID1 */ #define RAL_MAC_CSR7 0x040e /* BSSID2 */ #define RAL_MAC_CSR8 0x0410 /* Max frame length */ #define RAL_MAC_CSR9 0x0412 /* Timer control */ #define RAL_MAC_CSR10 0x0414 /* Slot time */ #define RAL_MAC_CSR11 0x0416 /* IFS */ #define RAL_MAC_CSR12 0x0418 /* EIFS */ #define RAL_MAC_CSR13 0x041a /* Power mode0 */ #define RAL_MAC_CSR14 0x041c /* Power mode1 */ #define RAL_MAC_CSR15 0x041e /* Power saving transition0 */ #define RAL_MAC_CSR16 0x0420 /* Power saving transition1 */ #define RAL_MAC_CSR17 0x0422 /* Power state control */ #define RAL_MAC_CSR18 0x0424 /* Auto wake-up control */ #define RAL_MAC_CSR19 0x0426 /* GPIO control */ #define RAL_MAC_CSR20 0x0428 /* LED control0 */ #define RAL_MAC_CSR22 0x042c /* XXX not documented */ /* * Tx/Rx Registers. */ #define RAL_TXRX_CSR0 0x0440 /* Security control */ #define RAL_TXRX_CSR2 0x0444 /* Rx control */ #define RAL_TXRX_CSR5 0x044a /* CCK Tx BBP ID0 */ #define RAL_TXRX_CSR6 0x044c /* CCK Tx BBP ID1 */ #define RAL_TXRX_CSR7 0x044e /* OFDM Tx BBP ID0 */ #define RAL_TXRX_CSR8 0x0450 /* OFDM Tx BBP ID1 */ #define RAL_TXRX_CSR10 0x0454 /* Auto responder control */ #define RAL_TXRX_CSR11 0x0456 /* Auto responder basic rate */ #define RAL_TXRX_CSR18 0x0464 /* Beacon interval */ #define RAL_TXRX_CSR19 0x0466 /* Beacon/sync control */ #define RAL_TXRX_CSR20 0x0468 /* Beacon alignment */ #define RAL_TXRX_CSR21 0x046a /* XXX not documented */ /* * Security registers. */ #define RAL_SEC_CSR0 0x0480 /* Shared key 0, word 0 */ /* * PHY registers. */ #define RAL_PHY_CSR2 0x04c4 /* Tx MAC configuration */ #define RAL_PHY_CSR4 0x04c8 /* Interface configuration */ #define RAL_PHY_CSR5 0x04ca /* BBP Pre-Tx CCK */ #define RAL_PHY_CSR6 0x04cc /* BBP Pre-Tx OFDM */ #define RAL_PHY_CSR7 0x04ce /* BBP serial control */ #define RAL_PHY_CSR8 0x04d0 /* BBP serial status */ #define RAL_PHY_CSR9 0x04d2 /* RF serial control0 */ #define RAL_PHY_CSR10 0x04d4 /* RF serial control1 */ /* * Statistics registers. */ #define RAL_STA_CSR0 0x04e0 /* FCS error */ #define RAL_DISABLE_RX (1 << 0) #define RAL_DROP_CRC_ERROR (1 << 1) #define RAL_DROP_PHY_ERROR (1 << 2) #define RAL_DROP_CTL (1 << 3) #define RAL_DROP_NOT_TO_ME (1 << 4) #define RAL_DROP_TODS (1 << 5) #define RAL_DROP_VERSION_ERROR (1 << 6) #define RAL_DROP_MULTICAST (1 << 9) #define RAL_DROP_BROADCAST (1 << 10) #define RAL_SHORT_PREAMBLE (1 << 2) #define RAL_RESET_ASIC (1 << 0) #define RAL_RESET_BBP (1 << 1) #define RAL_HOST_READY (1 << 2) #define RAL_ENABLE_TSF (1 << 0) #define RAL_ENABLE_TSF_SYNC(x) (((x) & 0x3) << 1) #define RAL_ENABLE_TBCN (1 << 3) #define RAL_ENABLE_BEACON_GENERATOR (1 << 4) #define RAL_RF_AWAKE (3 << 7) #define RAL_BBP_AWAKE (3 << 5) #define RAL_BBP_WRITE (1 << 15) #define RAL_BBP_BUSY (1 << 0) #define RAL_RF1_AUTOTUNE 0x08000 #define RAL_RF3_AUTOTUNE 0x00040 #define RAL_RF_2522 0x00 #define RAL_RF_2523 0x01 #define RAL_RF_2524 0x02 #define RAL_RF_2525 0x03 #define RAL_RF_2525E 0x04 #define RAL_RF_2526 0x05 /* dual-band RF */ #define RAL_RF_5222 0x10 #define RAL_BBP_VERSION 0 #define RAL_BBP_TX 2 #define RAL_BBP_RX 14 #define RAL_BBP_ANTA 0x00 #define RAL_BBP_DIVERSITY 0x01 #define RAL_BBP_ANTB 0x02 #define RAL_BBP_ANTMASK 0x03 #define RAL_BBP_FLIPIQ 0x04 #define RAL_JAPAN_FILTER 0x08 struct ural_tx_desc { uint32_t flags; #define RAL_TX_RETRY(x) ((x) << 4) #define RAL_TX_MORE_FRAG (1 << 8) #define RAL_TX_NEED_ACK (1 << 9) #define RAL_TX_TIMESTAMP (1 << 10) #define RAL_TX_OFDM (1 << 11) #define RAL_TX_NEWSEQ (1 << 12) #define RAL_TX_IFS_MASK 0x00006000 #define RAL_TX_IFS_BACKOFF (0 << 13) #define RAL_TX_IFS_SIFS (1 << 13) #define RAL_TX_IFS_NEWBACKOFF (2 << 13) #define RAL_TX_IFS_NONE (3 << 13) uint16_t wme; #define RAL_LOGCWMAX(x) (((x) & 0xf) << 12) #define RAL_LOGCWMIN(x) (((x) & 0xf) << 8) #define RAL_AIFSN(x) (((x) & 0x3) << 6) #define RAL_IVOFFSET(x) (((x) & 0x3f)) uint16_t reserved; uint8_t plcp_signal; uint8_t plcp_service; #define RAL_PLCP_LENGEXT 0x80 uint8_t plcp_length_lo; uint8_t plcp_length_hi; uint32_t iv; uint32_t eiv; } __packed; struct ural_rx_desc { uint32_t flags; #define RAL_RX_CRC_ERROR (1 << 5) #define RAL_RX_OFDM (1 << 6) #define RAL_RX_PHY_ERROR (1 << 7) uint8_t rate; uint8_t rssi; uint16_t reserved; uint32_t iv; uint32_t eiv; } __packed; #define RAL_RF_LOBUSY (1 << 15) #define RAL_RF_BUSY (1U << 31) #define RAL_RF_20BIT (20 << 24) #define RAL_RF1 0 #define RAL_RF2 2 #define RAL_RF3 1 #define RAL_RF4 3 #define RAL_EEPROM_MACBBP 0x0000 #define RAL_EEPROM_ADDRESS 0x0004 #define RAL_EEPROM_TXPOWER 0x003c #define RAL_EEPROM_CONFIG0 0x0016 #define RAL_EEPROM_BBP_BASE 0x001c /* * Default values for MAC registers; values taken from the reference driver. */ #define RAL_DEF_MAC \ { RAL_TXRX_CSR5, 0x8c8d }, \ { RAL_TXRX_CSR6, 0x8b8a }, \ { RAL_TXRX_CSR7, 0x8687 }, \ { RAL_TXRX_CSR8, 0x0085 }, \ { RAL_MAC_CSR13, 0x1111 }, \ { RAL_MAC_CSR14, 0x1e11 }, \ { RAL_TXRX_CSR21, 0xe78f }, \ { RAL_MAC_CSR9, 0xff1d }, \ { RAL_MAC_CSR11, 0x0002 }, \ { RAL_MAC_CSR22, 0x0053 }, \ { RAL_MAC_CSR15, 0x0000 }, \ { RAL_MAC_CSR8, 0x0780 }, \ { RAL_TXRX_CSR19, 0x0000 }, \ { RAL_TXRX_CSR18, 0x005a }, \ { RAL_PHY_CSR2, 0x0000 }, \ { RAL_TXRX_CSR0, 0x1ec0 }, \ { RAL_PHY_CSR4, 0x000f } /* * Default values for BBP registers; values taken from the reference driver. */ #define RAL_DEF_BBP \ { 3, 0x02 }, \ { 4, 0x19 }, \ { 14, 0x1c }, \ { 15, 0x30 }, \ { 16, 0xac }, \ { 17, 0x48 }, \ { 18, 0x18 }, \ { 19, 0xff }, \ { 20, 0x1e }, \ { 21, 0x08 }, \ { 22, 0x08 }, \ { 23, 0x08 }, \ { 24, 0x80 }, \ { 25, 0x50 }, \ { 26, 0x08 }, \ { 27, 0x23 }, \ { 30, 0x10 }, \ { 31, 0x2b }, \ { 32, 0xb9 }, \ { 34, 0x12 }, \ { 35, 0x50 }, \ { 39, 0xc4 }, \ { 40, 0x02 }, \ { 41, 0x60 }, \ { 53, 0x10 }, \ { 54, 0x18 }, \ { 56, 0x08 }, \ { 57, 0x10 }, \ { 58, 0x08 }, \ { 61, 0x60 }, \ { 62, 0x10 }, \ { 75, 0xff } /* * Default values for RF register R2 indexed by channel numbers. */ #define RAL_RF2522_R2 \ { \ 0x307f6, 0x307fb, 0x30800, 0x30805, 0x3080a, 0x3080f, 0x30814, \ 0x30819, 0x3081e, 0x30823, 0x30828, 0x3082d, 0x30832, 0x3083e \ } #define RAL_RF2523_R2 \ { \ 0x00327, 0x00328, 0x00329, 0x0032a, 0x0032b, 0x0032c, 0x0032d, \ 0x0032e, 0x0032f, 0x00340, 0x00341, 0x00342, 0x00343, 0x00346 \ } #define RAL_RF2524_R2 \ { \ 0x00327, 0x00328, 0x00329, 0x0032a, 0x0032b, 0x0032c, 0x0032d, \ 0x0032e, 0x0032f, 0x00340, 0x00341, 0x00342, 0x00343, 0x00346 \ } #define RAL_RF2525_R2 \ { \ 0x20327, 0x20328, 0x20329, 0x2032a, 0x2032b, 0x2032c, 0x2032d, \ 0x2032e, 0x2032f, 0x20340, 0x20341, 0x20342, 0x20343, 0x20346 \ } #define RAL_RF2525_HI_R2 \ { \ 0x2032f, 0x20340, 0x20341, 0x20342, 0x20343, 0x20344, 0x20345, \ 0x20346, 0x20347, 0x20348, 0x20349, 0x2034a, 0x2034b, 0x2034e \ } #define RAL_RF2525E_R2 \ { \ 0x2044d, 0x2044e, 0x2044f, 0x20460, 0x20461, 0x20462, 0x20463, \ 0x20464, 0x20465, 0x20466, 0x20467, 0x20468, 0x20469, 0x2046b \ } #define RAL_RF2526_HI_R2 \ { \ 0x0022a, 0x0022b, 0x0022b, 0x0022c, 0x0022c, 0x0022d, 0x0022d, \ 0x0022e, 0x0022e, 0x0022f, 0x0022d, 0x00240, 0x00240, 0x00241 \ } #define RAL_RF2526_R2 \ { \ 0x00226, 0x00227, 0x00227, 0x00228, 0x00228, 0x00229, 0x00229, \ 0x0022a, 0x0022a, 0x0022b, 0x0022b, 0x0022c, 0x0022c, 0x0022d \ } ```
```haskell -- editorconfig-checker-disable-file {-# LANGUAGE BlockArguments #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NumericUnderscores #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE ViewPatterns #-} -- | Various analyses of events in mainnet script dumps. module Main (main) where import LoadScriptEvents (eventsOf, loadEvents) import PlutusCore.Data as Data (Data (..)) import PlutusCore.Default (DefaultUni (DefaultUniData), Some (..), ValueOf (..)) import PlutusCore.Evaluation.Machine.CostStream (sumCostStream) import PlutusCore.Evaluation.Machine.ExMemoryUsage (ExMemoryUsage, flattenCostRose, memoryUsage) import PlutusCore.Pretty (display) import PlutusLedgerApi.Common import PlutusLedgerApi.Test.EvaluationEvent import PlutusLedgerApi.V1 qualified as V1 import PlutusLedgerApi.V2 qualified as V2 import PlutusLedgerApi.V3 qualified as V3 import PlutusTx.AssocMap qualified as M import UntypedPlutusCore as UPLC import Control.Exception (throwIO) import Control.Lens hiding (List) import Control.Monad.Primitive (PrimState) import Control.Monad.Writer.Strict import Data.Int (Int64) import Data.List (find, intercalate) import Data.Primitive.PrimArray qualified as P import System.Directory.Extra (listFiles) import System.Environment (getArgs, getProgName) import System.FilePath (isExtensionOf, takeFileName) import System.IO (stderr) import Text.Printf (hPrintf, printf) -- | The type of a generic analysis function type EventAnalyser = EvaluationContext -> [Int64] -- cost parameters -> ScriptEvaluationEvent -> IO () -- Analyse values in ScriptContext -- Script purpose: this is the same for V1 and V2, but changes in V3 stringOfPurposeV1 :: V1.ScriptPurpose -> String stringOfPurposeV1 = \case V1.Minting _ -> "V1 Minting" -- Script arguments are [redeemer, context] V1.Spending _ -> "V1 Spending" -- Script arguments are [datum, redeemer, context] V1.Rewarding _ -> "V1 Rewarding" -- Script arguments appear to be [redeemer, context] V1.Certifying _ -> "V1 Certifying" -- Script arguments appear to be [redeemer, context] stringOfPurposeV2 :: V2.ScriptPurpose -> String stringOfPurposeV2 = \case V2.Minting _ -> "V2 Minting" V2.Spending _ -> "V2 Spending" V2.Rewarding _ -> "V2 Rewarding" V2.Certifying _ -> "V2 Certifying" stringOfPurposeV3 :: V3.ScriptInfo -> String stringOfPurposeV3 = \case V3.MintingScript{} -> "V3 Minting" V3.SpendingScript{} -> "V3 Spending" V3.RewardingScript{} -> "V3 Rewarding" V3.CertifyingScript{} -> "V3 Certifying" V3.VotingScript{} -> "V3 Voting" V3.ProposingScript{} -> "V3 Proposing" shapeOfValue :: V1.Value -> String shapeOfValue (V1.Value m) = let l = M.toList m in printf "[%d: %s]" (length l) (intercalate "," (fmap (printf "%d" . length . M.toList . snd) l)) analyseValue :: V1.Value -> IO () analyseValue v = do putStr $ shapeOfValue v printf "\n" analyseOutputs :: [a] -> (a -> V1.Value) -> IO () -- Luckily V1.Value is the same as V2.Value analyseOutputs outputs getValue = case outputs of [] -> putStrLn "No outputs" -- This happens in 0000000046344292-*.event l -> do putStr $ printf "Outputs %d " (length l) putStrLn $ intercalate ", " (fmap (shapeOfValue . getValue) l) analyseTxInfoV1 :: V1.TxInfo -> IO () analyseTxInfoV1 i = do putStr "Fee: " analyseValue $ V1.txInfoFee i putStr "Mint: " analyseValue $ V1.txInfoMint i analyseOutputs (V1.txInfoOutputs i) V1.txOutValue analyseTxInfoV2 :: V2.TxInfo -> IO () analyseTxInfoV2 i = do putStr "Fee: " analyseValue $ V2.txInfoFee i putStr "Mint: " analyseValue $ V2.txInfoMint i analyseOutputs (V2.txInfoOutputs i) V2.txOutValue analyseTxInfoV3 :: V3.TxInfo -> IO () analyseTxInfoV3 i = do putStr "Fee: " print $ V3.txInfoFee i putStr "Mint: " analyseValue $ V3.txInfoMint i analyseOutputs (V3.txInfoOutputs i) V3.txOutValue analyseScriptContext :: EventAnalyser analyseScriptContext _ctx _params ev = case ev of PlutusEvent PlutusV1 ScriptEvaluationData{..} _expected -> case dataInputs of [_,_,c] -> analyseCtxV1 c [_,c] -> analyseCtxV1 c l -> error $ printf "Unexpected number of V1 script arguments: %d" (length l) PlutusEvent PlutusV2 ScriptEvaluationData{..} _expected -> case dataInputs of [_,_,c] -> analyseCtxV2 c [_,c] -> analyseCtxV2 c l -> error $ printf "Unexpected number of V2 script arguments: %d" (length l) PlutusEvent PlutusV3 ScriptEvaluationData{..} _expected -> case dataInputs of [_,_,c] -> analyseCtxV3 c [_,c] -> analyseCtxV3 c l -> error $ printf "Unexpected number of V3 script arguments: %d" (length l) where analyseCtxV1 c = case V1.fromData @V1.ScriptContext c of Just p -> printV1info p Nothing -> do -- This really happens: there are V1 events in 0000000103367139-*.event with a V2 context putStrLn "\n* Failed to decode V1 ScriptContext for V1 event: trying V2" case V2.fromData @V2.ScriptContext c of Nothing -> putStrLn "* Failed to decode V2 ScriptContext for V1 event: giving up\n" Just p -> do putStrLn "* Successfully decoded V2 ScriptContext for V1 event" printV2info p analyseCtxV2 c = case V2.fromData @V2.ScriptContext c of Just p -> printV2info p Nothing -> do putStrLn "\n* Failed to decode V2 ScriptContext for V2 event: trying V1" case V1.fromData @V1.ScriptContext c of Nothing -> putStrLn "* Failed to decode V1 ScriptContext for V2 event: giving up\n" Just p -> do putStrLn "* Successfully decoded V1 ScriptContext for V2 event" printV1info p analyseCtxV3 c = case V3.fromData @V3.ScriptContext c of Just p -> printV3info p Nothing -> do putStrLn "\n* Failed to decode V3 ScriptContext for V3 event: trying V2" case V2.fromData @V2.ScriptContext c of Just p -> do putStrLn "* Successfully decoded V2 ScriptContext for V3 event" printV2info p Nothing -> putStrLn "* Failed to decode V3 ScriptContext for V2 event: trying V1\n" case V1.fromData @V1.ScriptContext c of Just p -> do putStrLn "* Successfully decoded V1 ScriptContext for V3 event" printV1info p Nothing -> putStrLn "* Failed to decode V1 ScriptContext for V3 event: giving up\n" printV1info p = do putStrLn "----------------" putStrLn $ stringOfPurposeV1 $ V1.scriptContextPurpose p analyseTxInfoV1 $ V1.scriptContextTxInfo p printV2info p = do putStrLn "----------------" putStrLn $ stringOfPurposeV2 $ V2.scriptContextPurpose p analyseTxInfoV2 $ V2.scriptContextTxInfo p printV3info p = do putStrLn "----------------" putStrLn $ stringOfPurposeV3 $ V3.scriptContextScriptInfo p analyseTxInfoV3 $ V3.scriptContextTxInfo p -- Data object analysis -- Statistics about a Data object data DataInfo = DataInfo { _memUsage :: Integer , _numNodes :: Integer , _depth :: Integer , _numInodes :: Integer , _maxIsize :: Integer -- Maximum memoryUsage of integers in I nodes , _totalIsize :: Integer -- Total memoryUsage of integers in I nodes , _numBnodes :: Integer , _maxBsize :: Integer -- Maximum memoryUsage of bytestrings in B nodes , _totalBsize :: Integer -- Total memoryUsage of bytestrings in B nodes , _numLnodes :: Integer , _maxLlen :: Integer -- Maximum list length , _numCnodes :: Integer , _maxClen :: Integer -- Maximum number of constructor arguments , _numMnodes :: Integer , _maxMlen :: Integer -- Maximum map length } deriving stock (Show) makeLenses ''DataInfo emptyInfo :: DataInfo emptyInfo = DataInfo 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -- Memory usage as an Integer (in units of 64 bits / 8 bytes) memU :: ExMemoryUsage a => a -> Integer memU = fromSatInt . sumCostStream . flattenCostRose . memoryUsage -- Header (useful for R) printDataHeader :: IO () printDataHeader = printf "memUsage numNodes depth numI maxIsize totalIsize numB maxBsize totalBsize numL maxL numC maxC numM maxM\n" printDataInfo :: DataInfo -> IO () printDataInfo DataInfo{..} = printf "%4d %4d %4d %4d %4d %4d %4d %4d %4d %4d %4d %4d %4d %4d %4d\n" _memUsage _numNodes _depth _numInodes _maxIsize _totalIsize _numBnodes _maxBsize _totalBsize _numLnodes _maxLlen _numCnodes _maxClen _numMnodes _maxMlen -- Traverse a Data object collecting information getDataInfo :: Data -> DataInfo getDataInfo d = let ilen = fromIntegral . length info = go d emptyInfo go x i = case x of I n -> i & numInodes +~ 1 & maxIsize %~ max s & totalIsize +~ s where s = memU n B b -> i & numBnodes +~ 1 & maxBsize %~ max s & totalBsize +~ s where s = memU b List l -> foldr go i' l where i' = i & numLnodes +~ 1 & maxLlen %~ max (ilen l) Data.Constr _ l -> foldr go i' l where i' = i & numCnodes %~ (+1) & maxClen %~ max (ilen l) Map l -> let (a,b) = unzip l in foldr go (foldr go i' a) b where i' = i & numMnodes +~ 1 & maxMlen %~ max (ilen l) getDepth = \case I _ -> 1 B _ -> 1 List l -> 1 + depthList l Data.Constr _ l -> 1 + depthList l Map l -> let (a,b) = unzip l in 1 + max (depthList a) (depthList b) depthList = foldl (\n a -> max n (getDepth a)) 0 totalNodes = sum $ info ^.. (numInodes <> numBnodes <> numLnodes <> numCnodes <> numMnodes) in info & memUsage .~ memU d & numNodes .~ totalNodes & depth .~ getDepth d printDataInfoFor :: Data -> IO () printDataInfoFor = printDataInfo <$> getDataInfo -- Analyse a redeemer (as a Data object) from a script evaluation event analyseRedeemer :: EventAnalyser analyseRedeemer _ctx _params ev = do case ev of PlutusEvent ledgerLanguage ScriptEvaluationData{..} _expected -> case dataInputs of [_d, r, _c] -> printDataInfoFor r [r, _c] -> printDataInfoFor r l -> printf "* Unexpected number of %s script arguments: %d" (show ledgerLanguage) (length l) -- Analyse a datum (as a Data object) from a script evaluation event analyseDatum :: EventAnalyser analyseDatum _ctx _params ev = do case ev of PlutusEvent ledgerLanguage ScriptEvaluationData{..} _expected -> case dataInputs of [d, _r, _c] -> printDataInfoFor d [_r, _c] -> pure () l -> printf "* Unexpected number of %s script arguments: %d" (show ledgerLanguage) (length l) -- Print statistics about Data objects in a Term analyseTermDataObjects :: Term NamedDeBruijn DefaultUni DefaultFun () -> IO () analyseTermDataObjects = go where go = \case Var _ _ -> pure () LamAbs _ _ t -> go t Apply _ t1 t2 -> go t1 >> go t2 Force _ t -> go t Delay _ t -> go t Constant _ c -> case c of Some (ValueOf DefaultUniData d) -> printDataInfoFor d _ -> pure () Builtin _ _ -> pure () Error _ -> pure () UPLC.Constr _ _ ts -> mapM_ go ts Case _ t1 t2 -> go t1 >> mapM_ go t2 -- Counting builtins type BuiltinCounts = P.MutablePrimArray (PrimState IO) Int countBuiltinsInTerm :: BuiltinCounts -> Term NamedDeBruijn DefaultUni DefaultFun () -> IO () countBuiltinsInTerm counts = go where go = \case Var _ _ -> pure () LamAbs _ _ t -> go t Apply _ t1 t2 -> go t1 >> go t2 Force _ t -> go t Delay _ t -> go t Constant _ _ -> pure () Builtin _ b -> incrCount $ fromEnum b Error _ -> pure () UPLC.Constr _ _ ts -> mapM_ go ts Case _ t1 t2 -> go t1 >> mapM_ go t2 incrCount i = do c <- P.readPrimArray counts i P.writePrimArray counts i (c+1) -- The other analyses just print out results as they proceed. It's a little -- more complicated here because we have to accumulate the results and print -- them out at the end. countBuiltins :: [FilePath] -> IO () countBuiltins eventFiles = do let numBuiltins = fromEnum (maxBound :: DefaultFun) - fromEnum (minBound :: DefaultFun) + 1 counts :: BuiltinCounts <- P.newPrimArray numBuiltins P.setPrimArray counts 0 numBuiltins 0 mapM_ (analyseOneFile (analyseUnappliedScript (countBuiltinsInTerm counts))) eventFiles finalCounts <- P.freezePrimArray counts 0 numBuiltins P.itraversePrimArray_ printEntry finalCounts where printEntry i = printf "%-35s %12d\n" (show (toEnum i :: DefaultFun)) data EvaluationResult = OK ExBudget | Failed | DeserialisationError -- Convert to a string for use in an R frame toRString :: EvaluationResult -> String toRString = \case OK _ -> "T" Failed -> "F" DeserialisationError -> "NA" -- Print out the actual and claimed CPU and memory cost of every script. analyseCosts :: EventAnalyser analyseCosts ctx _ ev = case ev of PlutusEvent PlutusV1 ScriptEvaluationData{..} _ -> let result = case deserialiseScript PlutusV1 dataProtocolVersion dataScript of Left _ -> DeserialisationError Right script -> case V1.evaluateScriptRestricting dataProtocolVersion V1.Quiet ctx dataBudget script dataInputs of (_, Left _) -> Failed (_, Right cost) -> OK cost in printCost result dataBudget PlutusEvent PlutusV2 ScriptEvaluationData{..} _ -> let result = case deserialiseScript PlutusV2 dataProtocolVersion dataScript of Left _ -> DeserialisationError Right script -> case V2.evaluateScriptRestricting dataProtocolVersion V2.Quiet ctx dataBudget script dataInputs of (_, Left _) -> Failed (_, Right cost) -> OK cost in printCost result dataBudget PlutusEvent PlutusV3 ScriptEvaluationData{..} _ -> do dataInput <- case dataInputs of [input] -> pure input _ -> throwIO $ userError "PlutusV3 script expects exactly one input" let result = case deserialiseScript PlutusV3 dataProtocolVersion dataScript of Left _ -> DeserialisationError Right script -> do case V3.evaluateScriptRestricting dataProtocolVersion V3.Quiet ctx dataBudget script dataInput of (_, Left _) -> Failed (_, Right cost) -> OK cost printCost result dataBudget where printCost :: EvaluationResult -> ExBudget -> IO () printCost result claimedCost = let (claimedCPU, claimedMem) = costAsInts claimedCost in case result of OK cost -> let (actualCPU, actualMem) = costAsInts cost in printf "%15d %15d %15d %15d %2s\n" actualCPU claimedCPU actualMem claimedMem (toRString result) -- Something went wrong; print the cost as "NA" ("Not Available" in R) so that R can -- still process it. _ -> printf "%15s %15d %15s %15d %2s\n" "NA" claimedCPU "NA" claimedMem (toRString result) costAsInts :: ExBudget -> (Int, Int) costAsInts (ExBudget (V2.ExCPU cpu) (V2.ExMemory mem)) = (fromSatInt cpu, fromSatInt mem) -- Extract the script from an evaluation event and apply some analysis function analyseUnappliedScript :: (Term NamedDeBruijn DefaultUni DefaultFun () -> IO ()) -> EventAnalyser analyseUnappliedScript analyse _ctx _params (PlutusEvent plutusLedgerLanguage ScriptEvaluationData{..} _expected) = case deserialiseScript plutusLedgerLanguage dataProtocolVersion dataScript of Left err -> print err Right (deserialisedScript -> ScriptNamedDeBruijn (Program _ _ t)) -> analyse t -- | Run some analysis function over the events from a single event dump file analyseOneFile :: EventAnalyser -> FilePath -> IO () analyseOneFile analyse eventFile = do events <- loadEvents eventFile printf "# %s\n" $ takeFileName eventFile -- Print the file in the output so we can narrow down the location of -- interesting/anomalous data. This may not be helpful for some of the -- analyses. case ( mkContext V1.mkEvaluationContext (eventsCostParamsV1 events) , mkContext V2.mkEvaluationContext (eventsCostParamsV2 events) , mkContext V3.mkEvaluationContext (eventsCostParamsV2 events) ) of (Right ctxV1, Right ctxV2, Right ctxV3) -> mapM_ (runSingleEvent ctxV1 ctxV2 ctxV3) (eventsOf events) (Left err, _, _) -> error $ display err (_, Left err, _) -> error $ display err (_, _, Left err) -> error $ display err where mkContext f = \case Nothing -> Right Nothing Just costParams -> Just . (,costParams) . fst <$> runWriterT (f costParams) runSingleEvent :: Maybe (EvaluationContext, [Int64]) -> Maybe (EvaluationContext, [Int64]) -> Maybe (EvaluationContext, [Int64]) -> ScriptEvaluationEvent -> IO () runSingleEvent ctxV1 ctxV2 ctxV3 event = case event of PlutusEvent PlutusV1 _ _ -> case ctxV1 of Just (ctx, params) -> analyse ctx params event Nothing -> putStrLn "*** ctxV1 missing ***" PlutusEvent PlutusV2 _ _ -> case ctxV2 of Just (ctx, params) -> analyse ctx params event Nothing -> putStrLn "*** ctxV2 missing ***" PlutusEvent PlutusV3 _ _ -> case ctxV3 of Just (ctx, params) -> analyse ctx params event Nothing -> putStrLn "*** ctxV3 missing ***" main :: IO () main = let analyses = [ ( "values" , "analyse shapes of Values" , doAnalysis analyseScriptContext ) , ( "redeemers" , "print statistics about redeemer Data objects" , printDataHeader `thenDoAnalysis` analyseRedeemer ) , ( "datums" , "print statistics about datum Data objects" , printDataHeader `thenDoAnalysis` analyseDatum ) , ( "script-data" , "print statistics about Data objects in validator scripts" , printDataHeader `thenDoAnalysis` analyseUnappliedScript analyseTermDataObjects ) , ( "count-builtins" , "count the total number of occurrences of each builtin in validator scripts" , countBuiltins ) , ( "costs" , "print actual and claimed costs of scripts" , putStrLn " cpuActual cpuClaimed memActual memClaimed status" `thenDoAnalysis` analyseCosts ) ] doAnalysis analyser = mapM_ (analyseOneFile analyser) (prelude `thenDoAnalysis` analyser) files = prelude >> doAnalysis analyser files usage = do getProgName >>= hPrintf stderr "Usage: %s <analysis> [<dir>]\n" hPrintf stderr "Analyse the .event files in <dir> (default = current directory)\n" hPrintf stderr "Avaliable analyses:\n" mapM_ printDescription analyses where printDescription (n,h,_) = hPrintf stderr " %-16s: %s\n" n h go name dir = case find (\(n, _, _) -> n == name) analyses of Nothing -> printf "Unknown analysis: %s\n" name >> usage Just (_, _, analysis) -> do files <- listFiles dir case filter ("event" `isExtensionOf`) files of [] -> printf "No .event files in %s\n" dir eventFiles -> analysis eventFiles in getArgs >>= \case [name] -> go name "." [name, dir] -> go name dir _ -> usage ```
Daniel Dunglas Home (pronounced Hume; 20 March 183321 June 1886) was a Scottish physical medium with the reported ability to levitate to a variety of heights, speak with the dead, and to produce rapping and knocks in houses at will. His biographer Peter Lamont opines that he was one of the most famous men of his era. Harry Houdini described him as "one of the most conspicuous and lauded of his type and generation" and "the forerunner of the mediums whose forte is fleecing by presuming on the credulity of the public." Home conducted hundreds of séances, which were attended by many eminent Victorians. There have been eyewitness accounts by séance sitters describing conjuring methods and fraud that Home may have employed. Family Daniel Home's mother, Elizabeth ("Betsy") Home (née McNeill) was known as a seer in Scotland, as were many of her predecessors, like her great uncle Colin Uruqhart, and her uncle Mr. McKenzie. The gift of second sight was often seen as a curse, as it foretold instances of tragedy and death. Home's father, William Home, was the illegitimate son of Alexander, the 10th Earl of Home. Evidence supports the elder Home's illegitimacy, as various payments meant for William were made by the 10th Earl. Elizabeth and William were married when he was 19 years old, and found employment at the Balerno paper mill. The Homes moved into one of small houses built in the mill for the workforce, in Currie (six miles south-west of Edinburgh). William was described as a "bitter, morose and unhappy man" who drank, and was often aggressive towards his wife. Elizabeth had eight children while living in the mill house: six sons and two daughters, although their lives were not fully recorded. The eldest, John, later worked in the Balerno mill and eventually managed a paper mill in Philadelphia, Mary drowned in a stream at the age of 12 years in 1846, and Adam died at sea at the age of 17 while en route to Greenland, which Home says he saw in a vision and reportedly confirmed five months later. Early life Daniel Home was Elizabeth's third child, and was born on 20 March 1833. He was baptised by the Reverend Mr. Somerville three weeks after his birth at Currie Parish Church on 14 April 1833. The one-year-old Home was deemed a delicate child, having a "nervous temperament", and was passed to Elizabeth's childless sister, Mary Cook. She lived with her husband in the coastal town of Portobello, east of Edinburgh. According to Home, his cradle rocked by itself at the Cooks' house, and he had a vision of a cousin's death, who lived in Linlithgow, to the west of Edinburgh. United States Sometime between 1838 and 1841, Home's aunt and uncle decided to emigrate to the United States with their adopted son, sailing in the cheapest class of steerage as they could not afford a cabin. After landing in New York, the Cooks travelled to Greeneville, near Norwich, Connecticut. The red-haired and freckled Home attended school in Greeneville, where he was known as "Scotchy" by the other students. The 13-year-old Home did not join in sports games with other boys, preferring to take walks in the local woods with a friend called Edwin. The two boys read the Bible to each other and told stories, and made a pact stating that if one or the other were to die, they would try to make contact after death. Home and his aunt soon moved to Troy, New York, which is about from Greeneville, although Home in his own book stated it was away. Home lost contact with Edwin until one night when Home, according to Lamont, saw a brightly lit vision of him standing at the foot of the bed, which gave Home the feeling that his friend was dead. Edwin made three circles in the air before disappearing, and a few days later a letter arrived stating that Edwin had died of malignant dysentery three days before Home's vision. A few years later Home and his aunt returned to Greeneville, and Elizabeth Home emigrated from Scotland to America with the surviving members of the family to live in Waterford, Connecticut, which was away from the Cook's house. Home and his mother's reunion was short-lived, as Elizabeth appeared to foretell her own death in 1850. Home said he saw his mother in a vision saying, "Dan, 12 o'clock", which was the time of her death. After Elizabeth's death Home turned to religion. His aunt was a Presbyterian, and held the Calvinist view that one's fate has been decided, so Home embraced the Wesleyan faith, which believed that every soul can be saved. Home's aunt resented Wesleyans so much that she forced Home to change to Congregationalist, which was not to her liking, either, but was more in line with her own religion. The house was reportedly disturbed by rappings and knocking similar to those that had occurred two years earlier at the home of the Fox sisters. Ministers were called to the Cooks' house: a Baptist, a Congregationalist, and even a Wesleyan minister, who all believed that Home was possessed by the Devil, although Home believed it was a gift from God. According to Home, the knocking did not stop, and a table started to move by itself, even though Home's aunt put a bible on it and then placed her full body weight on it. According to Lamont, the noises did not stop and were attracting the unwanted attention of Cook's neighbours, so Home was told to leave the house. Fame The 18-year-old Home stayed with a friend in Willimantic, Connecticut, and later Lebanon, Connecticut. Home held his first séance in March 1851, which was reported in a Hartford newspaper managed by W. R. Hayden, who wrote that the table moved without anyone touching it, and kept moving when Hayden physically tried to stop it. After the newspaper report, Home became well known in New England, travelling around healing the sick and communicating with the dead, although he wrote that he was not prepared for this sudden change in his life because of his supposed shyness. Home never directly asked for money, although he lived very well on gifts, donations and lodging from wealthy admirers. He felt that he was on a "mission to demonstrate immortality", and wished to interact with his clients as one gentleman to another, rather than as an employee. In 1852, Home was a guest at the house of Rufus Elmer in Springfield, Massachusetts, giving séances six or seven times a day, which were visited by crowds of people, including a Harvard professor, David Wells, and the poet and editor of the New York Evening Post, William Cullen Bryant. They were all convinced of Home's credibility and wrote to the Springfield Republican newspaper stating that the room was well lit, full inspections were allowed, and said, "We know that we were not imposed upon nor deceived". It was also reported that at one of Home's demonstrations five men of heavy build (with a combined weight of 850 pounds) sat on a table, but it still moved, and others saw "a tremulous phosphorescent light gleam over the walls". Home was investigated by numerous people, such as Professor Robert Hare, the inventor of the oxy-hydrogen blowpipe, and John W. Edmonds, a trial court judge, who were sceptical, but later said they believed Home was not fraudulent. In his book, "Incidents in My Life", Home claims that in August 1852, in South Manchester, Connecticut, at the house of Ward Cheney, a successful silk manufacturer, he was reportedly seen to levitate twice and then rise to up to the ceiling, with louder rappings and knocking than ever before, more aggressive table movements and the sounds of a ship at sea in a storm, although persons present said that the room was badly lit so as to see the spirit lights. New York was now interested in Home's abilities, so he moved to an apartment at Bryant Park on 42nd street. His most verbal critic in New York was William Makepeace Thackeray, the author of Vanity Fair. Thackeray dismissed Home's abilities as "dire humbug", and "dreary and foolish superstition", although Thackeray had been impressed when he saw a table turning. Home thought that Thackeray was "the most sceptical inquirer" he had ever met, and as Thackeray made his thoughts public, Home faced public scepticism and further scrutiny. Home travelled between Hartford, Springfield, and Boston during the next few months, and settled in Newburgh by the Hudson River in the summer of 1853. He resided at the Theological Institute, but took no part in any of the theological discussions held there, as he wanted to take a course in medicine. Dr. Hull funded Home's studies, and offered to pay Home five dollars a day for his séances, but Home refused, as always. His idea was to fund his work with a legitimate salary by practicing medicine, but he became ill in early 1854, and stopped his studies. Home was diagnosed with Tuberculosis, and his doctors recommended recuperation in Europe. His last séance in America was in March 1855, in Hartford, Connecticut, before he travelled to Boston and sailed to England on board the Africa, at the end of March. Europe Home's name was originally Daniel Home, but by the time he arrived in Europe he had lengthened it to Daniel Dunglas Home, in reference to the Scottish house of Home, of which his father claimed to be a part. In London, Home found a believer in spiritualism, William Cox, who owned a large hotel at 53, 54 and 55 Jermyn Street, London. As Cox was so enamoured of Home's abilities, he let him stay at the hotel without payment. Robert Owen, an 83-year-old social reformer, was also staying at the hotel, and introduced Home to many of his friends in London society. At the time Home was described as "tall and thin, with blue eyes and auburn hair, fastidiously dressed but seriously ill with consumption". Nevertheless, he held sittings for notable people in full daylight, moving objects that were some distance away. Some early guests at Home's sittings included the scientist Sir David Brewster (who remained unconvinced), the novelists Sir Edward Bulwer-Lytton and Thomas Adolphus Trollope, and the Swedenborgian James John Garth Wilkinson. As well as Brewster, fellow scientists Michael Faraday and Thomas Huxley were prominent contemporary critics of Home's claims. It was the poet Robert Browning however, who proved to be one of Home's most adamant critics. After attending a séance of Home's, Browning wrote in a letter to The Times that: 'the whole display of hands, spirit utterances etc., was a cheat and imposture'. Browning gave his unflattering impression of Home in the poem, "Sludge the Medium" (1864). His wife, Elizabeth Barrett Browning, was convinced that the phenomena she witnessed were genuine and their discussions about Home were a constant source of disagreement. Frank Podmore writes of a Mr Merrifield's first-hand account of experiencing Home's fraudulence during a séance. Home's fame grew, fuelled by his ostensible feats of levitation. William Crookes claimed Home could levitate five to seven feet above the floor. Crookes wrote "We all saw him rise from the ground slowly to a height of about six inches, remain there for about ten seconds, and then slowly descend." In the following years Home travelled across continental Europe, and always as a guest of wealthy patrons. In Paris, he was summoned to the Tuileries to perform a séance for Napoleon III. He also performed for Queen Sophia of the Netherlands, who wrote: "I saw him four times...I felt a hand tipping my finger; I saw a heavy golden bell moving alone from one person to another; I saw my handkerchief move alone and return to me with a knot... He himself is a pale, sickly, rather handsome young man but without a look or anything which would either fascinate or frighten you. It is wonderful. I am so glad I have seen it..." In 1866, Mrs Jane Lyon, a wealthy widow, adopted Home as her son, giving him £60,000 in an attempt to gain introduction into high society. Finding that the adoption did not change her social situation, Lyon changed her mind, and brought a suit for the return of her money from Home on the grounds that it had been obtained by spiritual influence. Under British law, the defendant bears the burden of proof in such a case, and proof was impossible since there was no physical evidence. The case was decided against Home, Mrs Lyon's money was returned, and the press pilloried Home's reputation. Home's high society acquaintances thought that he behaved like a complete gentleman throughout the ordeal, and he did not lose a single important friend. Sir Arthur Conan Doyle, a spiritualist who supported the mediumship of Home, stated that he was unusual in that he had four different types of mediumship: direct voice (the ability to let spirits audibly speak); trance speaker (the ability to let spirits speak through oneself); clairvoyant (ability to see things that are out of view); and physical medium (moving objects at a distance, levitation, etc., which was the type of mediumship in which he had no equal). According to Eric Dingwall, a lady acted as a medium and used to help Home during the séances attended by Henrietta Ada Ward. Alleged levitations A feat of low levitation by Daniel Dunglas Home was recorded by paranormal historian Frank Podmore. "We all saw him rise from the ground slowly to a height of about six inches, remain there for about ten seconds, and then slowly descend." The Balducci levitation is a levitation illusion first described by Ed Balducci. Its inventor is unknown. The performer stands at an angle facing away from the spectators. The performer appears to levitate a few inches above the ground. The effect generally does not last for more than five seconds. The performer's feet return to the ground, and the effect is complete. Home met one of his future closest friends in 1867; the young Lord Adare (later the 4th Earl of Dunraven). Adare was fascinated by Home, and began documenting the séances they held. The following year, Home was said to have levitated out of the third storey window of one room, and back in through the window of the adjoining room in front of three witnesses (Adare, Captain Wynne, and Lord Lindsay). Lord Adare stated that Home "swung out and in" of a window in a horizontal position. However, John Sladek has pointed out that all three witnesses gave contradictory information about the levitation, even contradicting themselves about specific details: The incident took place at 5 Buckingham Gate, Kensington (Adare); at Ashley Place, Westminster (Adare); at Victoria Street, Westminster (Lindsay). There was a ledge 4 inches wide below the windows (Adare); a ledge 1½ inches wide (Lindsay); no foothold at all (Lindsay); balconies 7 feet apart (Adare); no balconies at all (Lindsay). The windows were 85 feet from the street (Lindsay); 70 feet (Lindsay); 80 feet (Home); on the third floor (Adare); on the first floor (Adare). It was dark (Adare); there was a bright moonlight (Lindsay). Home was asleep in one room and the witnesses went into the next (Adare); Home left the witnesses in one room and went himself into the next (Adare). Trevor H. Hall who researched the case in detail established that the levitation took place at Ashley Place in Westminster at a height of 35 feet and suggested rather than levitating Home had stepped across a gap of four feet between two iron balconies. Gordon Stein also noted that the gap between the two balconies was only four feet making passing between them entirely feasible. Joseph McCabe wrote regarding the alleged levitation: No one professes to have seen Home carried from window to window. Home told the three men who were present that he was going to be wafted, and he thus set up a state of very nervous expectation... Both Lord Crawford and Lord Adare say that they were warned. Then Lord Crawford says that he saw the shadow on the wall of Home entering the room horizontally; and as the moon, by whose light he professes to have seen the shadow, was at the most only three days old, his testimony is absolutely worthless. Lord Adare claims only that he saw Home, in the dark, "standing upright outside our window." In the dark—it was an almost moonless December night—one could not, as a matter of fact, say very positively whether Home was outside or inside; but, in any case, he acknowledges that there was a nineteen-inch window-sill outside the window, and Home could stand on that. A few days before the levitation, scaring Lord Lindsay, Home had opened the same window, stepped out and stood on the outside ledge in the presence of two witnesses. Ivor Lloyd Tuckett argued that Home did this to provide "a rough sketch of the picture which he aimed at producing". Another possible natural explanation for Home's famous levitation was proposed by the psychical researcher Guy William Lambert who suggested he had attached a rope to the chimneys on the roof of the building, and hung the rope down unseen to the third floor. During the alleged levitation Home "swung out and in" the room by using a double rope maneuver. Lambert's rope hypothesis was supported by the magician John Booth. Arthur Conan Doyle said there were many cases on record of Home levitating, but skeptics assert the alleged levitations occurred in darkened conditions susceptible to trickery. Science historian Sherrie Lynne Lyons has stated that a possible explanation for Home's alleged levitation phenomena was revealed in the twentieth century by Clarence E. Willard (1882–1962). Willard revealed his technique in 1958 to members of the Society of American Magicians. He demonstrated how he could add two inches to his height by stretching. According to Lyons "it is quite likely that [Home] used a similar technique to the one that Willard used decades later". Author Donald Serrell Thomas has asserted that Jean Eugène Robert-Houdin, the French stage magician was refused admission to Home's séances. In opposition to this, spiritualists have said that Houdin was unable to explain the phenomena at a Home séance. Regarding both these claims, Peter Lamont has noted: It is probably worth noting, if only to avoid confusion, that such claims (much like those made by spiritualists that conjurors were unable to explain the phenomena) were often unfounded. For example, spiritualists claimed that Robert-Houdin had been unable to explain what happened at a Home seance, and critics claimed that Home had refused an invitation to perform in front of Robert-Houdin. There is, however, not a shred of evidence for either of these claims. Historian Simon During has suggested the levitation of Home was a magic trick, influenced by Robert-Houdin. Critical reception Allegations of fraud It is often claimed in parapsychology and spiritualist books that Home was never caught in fraud. However, skeptics have stated that this claim does not hold up to scrutiny as Home was caught utilizing tricks by different witnesses on different occasions. Gordon Stein has noted that "While the statement that Home was never caught in fraud has been made many times, it simply is not true... It is simply that Home was never publicly exposed in fraud. Privately, he was caught in fraud several times. In addition, there are natural explanations both possible and likely for each of his phenomena." At a séance in the house of the solicitor John Snaith Rymer in Ealing in July 1855, a sitter (Frederick Merrifield) observed that a "spirit-hand" was in fact a false limb attached on the end of Home's arm. Merrifield also claimed to have observed Home use his foot in the séance room. The poet Robert Browning and his wife Elizabeth attended a séance on 23, July 1855 in Ealing with the Rymers. In 1895, after the deaths of Robert and Elizabeth, the journalist Frederick Greenwood alleged that Browning had told him that during the séance he had taken hold of a luminous object that appeared above the edge of the table, which turned out to be Home's naked foot. Later Browning's son Robert, in a letter to the London Times, 5 December 1902, also referred to the incident, saying that Browning had caught hold of Home's foot under the table. The allegation was repeated by Harry Houdini and later writers. But detailed descriptions of the séance written soon afterwards by Robert and Elizabeth make no mention of any such incident. Browning's account states that, although he was promised that he would be allowed to hold a "spirit-hand," the promise was not kept. Writing in the journal for the Society for Psychical Research, Count Perovsky-Petrovo-Solovovo described a letter by Dr. Barthez, a physician in the court of Empress Eugenie, which claimed a sitter Morio de l'lle caught Home using his foot to fake supposed spirit effects during a séance in Biarritz in 1857. Home wore thin shoes, easy to take off and draw on, and also cut socks that left the toes free. "At the appropriate moment he takes off one of his shoes and with his foot pulls a dress here, a dress there, rings a bell, knocks one way and another, and, the thing done, quickly puts his shoe on again." Home positioned himself between the empress and Napoleon III. One of the séance sitters known as General Fleury also suspected that Home was utilizing trickery and asked to leave but returned unobserved to watch from another door behind Home. He saw Home slip his foot from his shoe and touch the arm of the Empress, who believed it to be one of her dead children. The observer stepped forward and revealed the fraud, and Home was conducted out of the country: "The order was to keep the incident secret." The allegations described by Dr. Barthez and General Fleury are second hand and have caused dispute between psychical researchers and skeptics. The journalist Delia Logan who attended a séance with Home in London claimed that Home had used a phosphorus trick. During the séance luminous hands were observed and the host told Logan that had seen Home place a small bottle upon the mantle piece. The host slipped the bottle into his pocket and when examined the next day, it was found to contain phosphorus oil. The neoclassical sculptor Hiram Powers who was a convinced spiritualist attended a séance with Home, but wrote a letter to Elizabeth Browning claiming Home had faked the table-turning movements. Speculations on trickery The researchers Frank Podmore (1910), Milbourne Christopher (1970), Trevor H. Hall (1984) and Gordon Stein (1993) were convinced that Home was a fraud and have provided a source of speculation on the ways in which he could have duped his séance sitters. Skeptics have criticized the lighting conditions of Home's séances. Home and his followers claimed that some of the séances took place in "light" but this was nothing more than a few candles, or some glow from a fireplace or open window. Home would adjust the lighting to his needs with no objections from his séance sitters. For example, there is this report from a witness: "The room was very dark ... Home's hands were visible only as a faint white heap". Home selected the séance sitters who sat next to him, his hands and feet were not controlled and according to Frank Podmore "no precautions were taken against trickery." Home was never searched before or after his séances. Science historian Sherrie Lynne Lyons wrote that the glowing or light-emitting hands in his séances could easily be explained by the rubbing of oil of phosphorus on his hands. It has been suggested that the "spirit hands" in the séances of Home were made of gloves stuffed with a substance. Robert Browning believed they were attached to Home's feet. Home was a sculptor and his studio in Rome contained sculpted hands. Lyons has speculated that he may have substituted the sculptor hands, leaving his real hands free to perform phenomena in the séance room. Home was known for his alleged feat of handling a heated lump of coal taken from a fire. The magician Henry Evans speculated that this was a juggling trick, performed by a hidden piece of platinum. Hereward Carrington described Evans hypothesis as "certainly ingenious" but pointed out William Crookes an experienced chemist was present at a séance whilst Home performed the feat and would have known how to distinguish the difference between coal and platinum. Frank Podmore wrote that most of the fire feats could have easily be performed by conjuring tricks and sleight of hand but hallucination and sense-deception may have explained Crookes' claim about observing flames from Home's fingers. William Crookes investigation Between 1870 and 1873, chemist and physicist William Crookes conducted experiments to determine the validity of the phenomena produced by three mediums: Florence Cook, Kate Fox, and Home. Crookes' final report in 1874 concluded that the phenomena produced by all three mediums were genuine, a result which was roundly derided by the scientific establishment. Crookes recorded that he controlled and secured Home by placing his feet on the top of Home's feet. Crookes' method of foot control later proved inadequate when used with Eusapia Palladino, as she merely slipped her foot out and into her sturdy shoe. In addition, Crookes' motives, methods, and conclusions with regard to Florence Cook were called into question, both at the time and subsequently, casting doubt on his conclusions about Home. In a series of experiments in London at the house of Crookes in February 1875, the medium Anna Eva Fay managed to fool Crookes into believing she had genuine psychic powers. Fay later confessed to her fraud and revealed the tricks she had used. Home was investigated by Crookes in a self-built laboratory at the rear of his house at Mornington Road, North London in 1871. No plans of the laboratory have been found and there is no contemporary description of it. Crookes wrote the board and spring balance experiment was a success with Home and had proven "beyond doubt" the existence of a "psychic force." However, the experiment could be easily dismissed as the result of vibrations caused by the passage of Euston trains in the large railway cutting near his house in London. The experiment was not repeatable and sometimes failed to produce any phenomena. The experiment was rejected and ridiculed by the scientific community for lack of scientific controls. In the experiment Home refused for Crookes to be near him and would draw attention to something on the other side of the room, or make conversation for diversionary signals. In 1871, Balfour Stewart in an article for Nature noted that the experiments were not conducted in broad daylight before a large unbiased audience and the results were inconclusive. Stewart suspected the phenomena observed were "subjective, rather than objective, occurring in the imaginations of those present rather than in the outward physical world." In the same year, J. P. Earwaker wrote a science review that heavily criticized the Crookes' experiments for their poor design concluding they were pseudoscientific. According to Earwaker "For in truth they are the very opposite of scientific. Even to call them unscientific is not strong enough; clumsy and futile are much nearer the truth." The engineer Coleman Sellers questioned the origin and weight of the board used with the balance spring apparatus. Sellers wrote that a standard mahogany board weighs around thirteen and half pounds but the one used in Crookes' experiment may have been at fault at only six pounds. Crookes responded to Sellers claiming the board weighed six pounds and this was not a mistake, he also stated he had the board for about sixteen years and it was originally cut in a lumber yard. P. H. Vanderweyde noted that Crookes was already a believer in psychic powers before he obtained the results of the experiments. Vanderweyde stated the spring balance used in Crookes' experiment was unreliable as it was easy to manipulate by deception and suggested he should repeat the experiment by using a chemical balance. According to Barry Wiley during the board and spring balance experiment, Home refused for Crookes to sit near him and he was occupied by writing notes. Wiley suspected Home used resin on his finger tips to tamper with the apparatus which managed to fool Crookes into believing a psychic force was being displayed. Regarding Crookes, the magician Harry Houdini wrote: There is not the slightest doubt in my mind that this brainy man was hoodwinked, and that his confidence was betrayed by the so-called mediums that he tested. His powers of observation were blinded and his reasoning faculties so blunted by his prejudice in favor of anything psychic or occult that he could not, or would not, resist the influence. Historian Ruth Brandon in an article for the New Scientist noted that William Huggins, Serjeant Cox, Crooke's wife and daughter, his laboratory assistant, and a Mrs Humphrey were all present during the Crookes experiments with Home. However, Barry Wiley has written that when Crookes published his report on the experiments in the Quarterly Journal of Science in 1871 he did not mention all the names of the observers present in the room. Wiley has stated that four females were present during the experiments as was Crookes' brother and the original report by Crookes did not refer to any spirits but many years later in 1889 he revealed in his Notes of séances with D. D. Home the names of the observers and claimed Home was in communication with spirits. Crookes' assistant was the glass blower Charles Henry Gimingham (1853–1890) who had built the experimental apparatus. Wiley suspected that Gimingham worked as a secret accomplice for Anna Eva Fay in her experiments with Crookes. Wiley noted that "Gimingham had free and open access to Crookes' laboratory and frequently worked there unsupervised with Crookes' full trust." Joseph McCabe criticized the Crookes experiments for lack of scientific controls and wrote Home was "daily in and out of Crookes's laboratory, and it appears that he closely watched the development of the tests and was prepared in advance." Before the experiments, Crookes was present with Home whilst he changed dress but Frank Podmore noted this would not have prevented Home from slipping into his pocket apparatus to cheat on the experiments. Edward Clodd wrote that Home chose his séance sitters and "if test experiments were suggested, he imposed the conditions." The physicist Victor Stenger commented that the experiments were poorly controlled; he gave the example of Home requesting all hands to be removed from the table whilst all those present complied. Stenger noted that "Crookes gullibly swallowed ploys such as this and allowed Home to call the shots... his desire to believe blinded him to the chicanery of his psychic subjects." Accordion experiment In the accordion experiment, Home sat at a table, with Crookes and another observer on either side of him, each with a foot on one of Home's feet. Home inserted his hand inside a wire cage that was pushed under the table. One of Home's hands was placed on the top of the table, and the other inside the cage which held an accordion on the non-key side, so the keyed end was hanging downwards. The accordion was reported to have played musical sounds. However, the amount of light in the room was not stated, and the accordion was not observed in good light. According to Frank Podmore there was no evidence the accordion played at all, as the keys were not observed to have moved. Podmore suggested the musical sounds could have come from an automatic instrument that Home had concealed. In 1871, William Benjamin Carpenter wrote a critical evaluation of the Crookes experiments with Home in the Quarterly Review. Carpenter wrote that although Crookes, his assistant and Sergeant Cox claimed to have observed the accordion float in the cage; Dr. Huggins did not testify to this, and no information was given to whether the keys and bellows were seen to move. According to Carpenter no solid explanation could be given until the experiment is repeated, however, he suggested that the accordion feat that Home performed may have been a conjuring trick achieved with one hand. Carpenter concluded that Crookes should repeat the experiment in open daylight without the cage in the presence of other witnesses. J. P. Earwaker heavily criticized the design of the accordion experiment as it took place under a dining room table. Earwaker who read Crookes' report noted that "no reason for this strangest of all strange positions is even hinted at." He also wrote "it never occurred to [Crookes] to notice whether the keys were depressed or not... it would be obvious that if the keys were not pressed down, it was impossible for the music really to have come from the accordion, and its true source must have been looked for elsewhere." The magician John Nevil Maskelyne also criticized the design of the experiment for taking place under a table. The psychologist Millais Culpin wrote the experiment was not scientific and questioned why the experiment was done under the table instead of in a more convenient position on top of it. Before the accordion experiment with Crookes, Home had performed the accordion feat for over fifteen years under various conditions but always under his control. It was reported by sitters and Crookes that Home's accordion played only two pieces, Home Sweet Home and The Last Rose of Summer. Both contain only one-octave. The psychical researcher Hereward Carrington and spiritualism expert Herbert Thurston have claimed the accordion experiment was not the result of deliberate fraud. This is in opposition to magicians and skeptical researchers who evaluated Crookes' reports from the experiment. The magician Henry Evans suggested the accordion feat was Home playing a musical box, attached to his leg. Skeptic Joseph McCabe wrote that Home may have placed a musical box in his pocket or on the floor. According to McCabe "the opening and shutting of the accordion could be done by hooks, or loops of black silk. So with the crowning miracle, when Home withdrew his hand, and the accordion was seen suspended in the air, moving about in the cage (under the dark table). It was probably hooked on to the table." The 19th-century British medium Francis Ward Monck was caught using a music box in his séances that he had hidden in his trousers. The fraudulent medium Henry Slade also played an accordion while held with one hand under a table. Slade and Home played the same pieces. They had at one time lived near each other in the U.S.A. The magician Chung Ling Soo exposed how Slade had performed the trick. The writer Amos Norton Craft suggested a false keyboard: The trick has since been often repeated and explained. The medium must have the semblance of key-board, made of some light material, concealed in his coat sleeve or about his person. This he attaches to the bottom of the accordion which he holds in his hand. Then when unobserved, while the learned professor is "taking down his notes" for the public press, he reverses the accordion, and attaching the false keyboard on the bottom by means of a small hook attached to it, fastens it to the side of the basket; having now the real keyboard in his hand he is able to produce musical sounds. Afterward the accordion floated about in the basket under the table, without the contact of Mr. Home's hand. This subsequent phenomenon was given to avoid immediate examination of the first by keeping Professor Crookes in suspense, and giving the medium time to reverse the instrument and conceal in his clothing the false key-board which had been on the bottom of the instrument. The accordion was suspended by means of a small hook fastened to dark thread, which would be invisible in the gas-light. Researcher Ronald Pearsall in his book The Table-Rappers (1972) suggested that a loop of catgut was attached to the accordion so Home could turn it round. Paul Kurtz wrote that other mediums had used a loop of catgut to obtain a similar effect with the accordion. Other researchers have suspected that a secret accomplice was involved. The magician Carlos María de Heredia claimed to have replicated the accordion feat of Home and suggested it was a trick performed by an accomplice playing a hidden accordion. Ruth Brandon considered the possibility of an accomplice playing a concertina, or Home playing a hidden music box. However, Brandon dismissed the accomplice hypothesis as unlikely. Skeptic James Randi stated that Home was caught cheating on a few occasions, but the episodes were never made public, and that the accordion feat was a one-octave mouth organ that Home concealed under his large moustache. Randi writes that one-octave mouth organs were found in Home's belongings after his death. According to Randi, "around 1960", William Lindsay Gresham told Randi he had seen these mouth organs in the Home collection at the Society for Psychical Research. Gordon Stein wrote: Home could easily have produced the sound of the accordion (concertina) by the use of a small harmonica concealed in his mouth. The up and down movement of the accordion could easily have been produced by catching the bottom of the accordion in a loop of black thread, or on a hook. The claim that the accordion feat was performed by Home using a small harmonica was originally suggested by J. M. Robertson in 1891. The psychical researcher Eric Dingwall who catalogued Home's collection on its arrival at the SPR did not record the presence of the mouth organs, and Lamont speculates that it is unlikely Dingwall would have missed these or not made them public. The accordion in the SPR collection is not the actual one Home used. They display a duplicate. Personal life Home married twice. In 1858, he married Alexandria de Kroll ("Sacha"), the 17-year-old daughter of a noble Russian family, in Saint Petersburg. His Best Man was the writer Alexandre Dumas. They had a son, Gregoire ("Grisha"), but Alexandria fell ill with tuberculosis, and died in 1862. In October 1871, Home married for the second, and last time, to Julie de Gloumeline, a wealthy Russian, whom he also met in St Petersburg. In the process, he converted to the Greek Orthodox faith. In 1869 Lord Adare revealed in his diaries under the title Experiences in Spiritualism with D. D. Home that he had slept in the same bed with Home. Many of the diary entries contain erotic homosexual overtones between Adare and Home. Death Home retired due to ill health; the tuberculosis, from which he had suffered for much of his life, was advancing and he said his powers were failing. He died on 21 June 1886 at the age of 53 and was buried in the Russian cemetery of St. Germain-en-Laye, in Paris. Notes References Christopher, Milbourne (1971) ESP, Seer & Psychics: What the Occult Really Is. Thomas Y. Crowell Company ASIN: B000O8Z6AC Further reading Ruth Brandon. (1983). The Spiritualists: The Passion for the Occult in the Nineteenth and Twentieth Centuries. Weidenfeld and Nicolson. Jean Burton. (1944). Heyday of a Wizard: Daniel Home, The Medium. Alfred A. Knopf. Milbourne Christopher. (1975). Mediums, Mystics and the Occult. Thomas Crowell. Edward Clodd. (1917). The Question: A Brief History and Examination of Modern Spiritualism. Grant Richards, London. J. P. Earwaker. (1871). Mr. Crookes' New Psychic Force. The Popular Science Review 10: 356–365. J. P. Earwaker. (1872). Psychic Force and Psychic Media. The Popular Science Review 11: 32–42. Henry Evans. (1897). Hours With the Ghosts Or Nineteenth Century Witchcraft. Chicago: Laird & Lee. Trevor H. Hall. (1984). The Enigma of Daniel Home: Medium Or Fraud?. Prometheus Books. Guy William Lambert. (1976). D. D. Home and the Physical World. Journal of the Society for Psychical Research 48: 298–314. John Nevil Maskelyne. (1876). Modern Spiritualism: A Short Account of its Rise and Progress, with Some Exposures of So-Called Spirit Media. Frederick Warne & Co. Joseph McCabe. (1920). Is Spiritualism Based On Fraud? The Evidence Given By Sir A. C. Doyle and Others Drastically Examined. London: Watts & Co. Georgess McHargue. (1972). Facts, Frauds, and Phantasms: A Survey of the Spiritualist Movement. Doubleday. Walter Mann. (1919). The Follies and Frauds of Spiritualism. Rationalist Association. London: Watts & Co. Frank Podmore. (1911). The Newer Spiritualism. Henry Holt and Company. Harry Price and Eric Dingwall. (1975). Revelations of a Spirit Medium. Arno Press. Reprint of 1891 edition by Charles F. Pidgeon. This rare, overlooked, and forgotten, book gives the "insider's knowledge" of 19th century deceptions. Coleman Sellers. (1871). Some Remarks On Experimental Investigations Of A New Force, By William Crookes, F. R. S. Journal of the Franklin Institute 92: 211–214. Gordon Stein. (1993). The Sorcerer of Kings: The Case of Daniel Dunglas Home and William Crookes. Prometheus Books. P. H. Vanderweyde. (1871). On Mr. Crookes' Further Experiments On Psychic Force. Journal of the Franklin Institute 92: 423–426. Horace Wyndham. (1937). Mr. Sludge, the Medium. Geoffrey Bles. External links Experiences In Spiritualism with D. D. Home – Lord Adare's report of Home's seances, in PDF format Home, Daniel Dunglas – An Encyclopedia of Claims, Frauds and Hoaxes of the Occult and Supernatural James Randi The Strange Case of Daniel Dunglas Home Andrew Lang, Chapter 8 of Historical Mysteries (1904) 1833 births 1886 deaths Telekinetics Entertainers from Edinburgh Scottish spiritual mediums
```smalltalk // // This file has been generated automatically by MonoDevelop to store outlets and // actions made in the Xcode designer. If it is removed, they will be lost. // Manual changes to this file may not be handled correctly. // using Foundation; namespace Container { [Register ("ViewController")] partial class ViewController { void ReleaseDesignerOutlets () { } } } ```
```shell Let's play the blame game Locate a commit by its hash Specify a commit by its ancestry Interactively stage patches Stashing changes ```
```java // // // path_to_url // // Unless required by applicable law or agreed to in writing, software // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. package google.registry.dns.writer.dnsupdate; import static com.google.common.io.BaseEncoding.base16; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.common.base.VerifyException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.InputStream; import java.net.InetAddress; import java.net.Socket; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import java.util.Arrays; import javax.net.SocketFactory; import org.joda.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.xbill.DNS.ARecord; import org.xbill.DNS.DClass; import org.xbill.DNS.Flags; import org.xbill.DNS.Message; import org.xbill.DNS.Name; import org.xbill.DNS.Opcode; import org.xbill.DNS.Rcode; import org.xbill.DNS.Record; import org.xbill.DNS.Type; import org.xbill.DNS.Update; /** Unit tests for {@link DnsMessageTransport}. */ class DnsMessageTransportTest { private static final String UPDATE_HOST = "127.0.0.1"; private final SocketFactory mockFactory = mock(SocketFactory.class); private final Socket mockSocket = mock(Socket.class); private Message simpleQuery; private Message expectedResponse; private DnsMessageTransport resolver; @BeforeEach @SuppressWarnings("AddressSelection") void beforeEach() throws Exception { simpleQuery = Message.newQuery(Record.newRecord(Name.fromString("example.com."), Type.A, DClass.IN)); expectedResponse = responseMessageWithCode(simpleQuery, Rcode.NOERROR); when(mockFactory.createSocket(InetAddress.getByName(UPDATE_HOST), DnsMessageTransport.DNS_PORT)) .thenReturn(mockSocket); resolver = new DnsMessageTransport(mockFactory, UPDATE_HOST, Duration.ZERO); } @Test void testSentMessageHasCorrectLengthAndContent() throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream(messageToBytesWithLength(expectedResponse)); when(mockSocket.getInputStream()).thenReturn(inputStream); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(mockSocket.getOutputStream()).thenReturn(outputStream); resolver.send(simpleQuery); ByteBuffer sentMessage = ByteBuffer.wrap(outputStream.toByteArray()); int messageLength = sentMessage.getShort(); byte[] messageData = new byte[messageLength]; sentMessage.get(messageData); assertThat(messageLength).isEqualTo(simpleQuery.toWire().length); assertThat(base16().encode(messageData)).isEqualTo(base16().encode(simpleQuery.toWire())); } @Test void testReceivedMessageWithLengthHasCorrectContent() throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream(messageToBytesWithLength(expectedResponse)); when(mockSocket.getInputStream()).thenReturn(inputStream); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); Message actualResponse = resolver.send(simpleQuery); assertThat(base16().encode(actualResponse.toWire())) .isEqualTo(base16().encode(expectedResponse.toWire())); } @Test void testEofReceivingResponse() throws Exception { byte[] messageBytes = messageToBytesWithLength(expectedResponse); ByteArrayInputStream inputStream = new ByteArrayInputStream(Arrays.copyOf(messageBytes, messageBytes.length - 1)); when(mockSocket.getInputStream()).thenReturn(inputStream); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); assertThrows(EOFException.class, () -> resolver.send(new Message())); } @Test @Disabled("This test hangs and causes OOM when using Java 21") // This test should never have passed. The socket is mocked and calling setSoTimeout() has no // effect whatsoever. We should consider removing it. void testTimeoutReceivingResponse() throws Exception { InputStream mockInputStream = mock(InputStream.class); when(mockInputStream.read()).thenThrow(new SocketTimeoutException("testing")); when(mockSocket.getInputStream()).thenReturn(mockInputStream); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); Duration testTimeout = Duration.standardSeconds(1); DnsMessageTransport resolver = new DnsMessageTransport(mockFactory, UPDATE_HOST, testTimeout); Message expectedQuery = new Message(); assertThrows(SocketTimeoutException.class, () -> resolver.send(expectedQuery)); verify(mockSocket).setSoTimeout((int) testTimeout.getMillis()); } @Test void testSentMessageTooLongThrowsException() throws Exception { Update oversize = new Update(Name.fromString("tld", Name.root)); for (int i = 0; i < 2000; i++) { oversize.add( ARecord.newRecord( Name.fromString("test-extremely-long-name-" + i + ".tld", Name.root), Type.A, DClass.IN)); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(mockSocket.getOutputStream()).thenReturn(outputStream); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> resolver.send(oversize)); assertThat(thrown).hasMessageThat().contains("message larger than maximum"); } @Test void testResponseIdMismatchThrowsException() throws Exception { expectedResponse.getHeader().setID(1 + simpleQuery.getHeader().getID()); when(mockSocket.getInputStream()) .thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse))); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); VerifyException thrown = assertThrows(VerifyException.class, () -> resolver.send(simpleQuery)); assertThat(thrown) .hasMessageThat() .contains( "response ID " + expectedResponse.getHeader().getID() + " does not match query ID " + simpleQuery.getHeader().getID()); } @Test void testResponseOpcodeMismatchThrowsException() throws Exception { simpleQuery.getHeader().setOpcode(Opcode.QUERY); expectedResponse.getHeader().setOpcode(Opcode.STATUS); when(mockSocket.getInputStream()) .thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse))); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); VerifyException thrown = assertThrows(VerifyException.class, () -> resolver.send(simpleQuery)); assertThat(thrown) .hasMessageThat() .contains("response opcode 'STATUS' does not match query opcode 'QUERY'"); } private Message responseMessageWithCode(Message query, int responseCode) { Message message = new Message(query.getHeader().getID()); message.getHeader().setOpcode(query.getHeader().getOpcode()); message.getHeader().setFlag(Flags.QR); message.getHeader().setRcode(responseCode); return message; } private byte[] messageToBytesWithLength(Message message) { byte[] bytes = message.toWire(); ByteBuffer buffer = ByteBuffer.allocate(bytes.length + DnsMessageTransport.MESSAGE_LENGTH_FIELD_BYTES); buffer.putShort((short) bytes.length); buffer.put(bytes); return buffer.array(); } } ```
In international relations, the term smart power refers to the combination of hard power and soft power strategies. It is defined by the Center for Strategic and International Studies as "an approach that underscores the necessity of a strong military, but also invests heavily in alliances, partnerships, and institutions of all levels to expand one's influence and establish legitimacy of one's action." Joseph Nye, former Assistant Secretary of Defense for International Security Affairs under the Clinton administration and author of several books on smart power strategy, suggests that the most effective strategies in foreign policy today require a mix of hard and soft power resources. Employing only hard power or only soft power in a given situation will usually prove inadequate. Nye utilizes the example of terrorism, arguing that combatting terrorism demands smart power strategy. He advises that simply utilizing soft power resources to change the hearts and minds of the Taliban government would be ineffective and requires a hard power component. In developing relationships with the mainstream Muslim world, however, soft power resources are necessary and the use of hard power would have damaging effects. According to Chester A. Crocker, smart power "involves the strategic use of diplomacy, persuasion, capacity building, and the projection of power and influence in ways that are cost-effective and have political and social legitimacy"essentially the engagement of both military force and all forms of diplomacy. Origin The origin of the term "smart power" is under debate and has been attributed to both Suzanne Nossel and Joseph Nye. Suzanne Nossel, Deputy to Ambassador Holbrooke at the United Nations during the Clinton administration, is credited with coining the term in an article in Foreign Affairs entitled, "Smart Power: Reclaiming Liberal Internationalism", in 2004. In a more recent article for CNN, she has criticized the Trump administration for its "tunnel-vision" foreign policy that neglects both soft power and smart power. She writes: "..Trump seems oblivious toward the brand value of what Joseph Nye has called the 'soft power' that comes from projecting appealing aspects of American society and character abroad. He is also indifferent to my own concept of 'smart power,'or the imperative to engage a broad range of tools of statecraft, from diplomacy to aid to private sector engagement to military intervention." Joseph Nye, however, claims that smart power is a term he introduced in 2003 "to counter the misperception that soft power alone can produce effective foreign policy." He created the term to name an alternative to the hard power-driven foreign policy of the Bush administration. Nye notes that smart power strategy denotes the ability to combine hard and soft power depending on whether hard or soft power would be more effective in a given situation. He states that many situations require soft power; however, in stopping North Korea's nuclear weapons program, for instance, hard power might be more effective than soft power. In the words of the Financial Times, "to win the peace, therefore, the US will have to show as much skill in exercising soft power as it has in using hard power to win the war." Smart power addresses multilateralism and enhances foreign policy. A successful smart power narrative for the United States in the twenty-first century, Nye argues, will not obsess over power maximization or the preservation of hegemony. Rather, it will find "ways to combine resources into successful strategies in the new context of power diffusion and the 'rise of the rest.'" A successful smart power strategy will provide answers to the following questions: 1) What goals or outcomes are preferred? 2) What resources are available and in which contexts? 3) What are the positions and preferences of the targets of attempts at influence? 4) Which forms of power behavior are most likely to succeed? 5) What is the probability of success? History United Kingdom Since the period of Pax Britannica (1815–1914) the foreign relations of the United Kingdom has employed a combination of influence and coercion in international relations. United States The term smart power emerged in the past decade, but the concept of smart power has much earlier roots in the history of the United States and is a popular notion in international relations today. 1901 President Theodore Roosevelt proclaims: "Speak softly and carry a big stick." 1948 The United States initiates major peacetime soft power programs under the authority of the Smith-Mundt Act, including broadcasting, exchange and information world wide to combat the outreach of the Soviet Union. 1991 The end of the Cold War was marked by the collapse of the Berlin Wall, which fell as a result of a combination of hard and soft power. Throughout the Cold War, hard power was used to deter Soviet aggression and soft power was used to erode faith in Communism. Joseph Nye said: "When the Berlin Wall finally collapsed, it was destroyed not by artillery barrage but by hammers and bulldozers wielded by those who had lost faith in communism." 2004 Joseph S. Nye introduces the term "smart power" in his book, "Soft Power: The Means to Success in World Politics". "Smart power is neither hard nor soft. It is both," he writes. In an article in "Foreign Affairs", analyst Suzanne Nossel uses the term "smart power". For Nossel, "Smart power means knowing that the United States' own hand is not always its best tool: U.S. interests are furthered by enlisting others on behalf of U.S. goals." 2007 In light of 9/11 and the war in Iraq, the Bush administration was criticized for placing too much emphasis on a hard power strategy. To counter this hard power strategy, the Center for Strategic and International Studies released the "Commission on Smart Power" to introduce the concept of smart power into discussion on which principles should guide the future of U.S. foreign policy in light of 9/11 and the war in Iraq. The report identifies five critical areas of focus for the U.S.: Alliances, Global Development, Public Diplomacy, Economic Integration, and Technology and Innovation. According to the report, these five goals constitute smart foreign policy and will help the United States achieve the goal of "American preeminence as an agent of good." 2009 The Center for Strategic and International Studies, released a second report, "Investing in a New Multilateralism", to address the concept of smart power in international releases. This report addressed the United Nations as an instrument of U.S. smart power. By collaborating with the UN, the U.S. can lead the way in reinvigorating multilateralism within the international community in the 21st century. 2009 Under the Obama administration, smart power became a core principle of his foreign policy strategy. It was popularized by Hillary Clinton during her Senate confirmation hearing on January 13, 2009 for the position of Secretary of State: We must use what has been called smart power---the full range of tools at our disposal---diplomatic, economic, military, political, legal, and cultural---picking the right tool, or combination of tools, for each situation. With smart power, diplomacy will be the vanguard of foreign policy. Both Suzanne Nossel and Joseph Nye were supportive of Clinton's encouragement of smart power, since it would popularize the use of smart power in U.S. foreign policy. That popularization has been accompanied by more frequent use of the term, and David Ignatius describes it as an "overused and vapid phrase meant to connote the kind of power between hard and soft". 2010 The "First Quadrennial Diplomacy and Development Review (QDDR)" entitled, "Leading through Civilian Power", called for the implementation of a smart power strategy through civilian leadership. 2011 Obama's "2011 May Speech on the Middle East and North Africa" called for a smart power strategy, incorporating development, in addition to defense and diplomacy, as the third pillar of his foreign policy doctrine. Contemporary application United Kingdom The UK government Strategic Defence and Security Review 2015 was based on a combination of hard power and soft power strategies. Following the Poisoning of Sergei and Yulia Skripal in 2018, the National Security Review described a "fusion doctrine", that will combine resources from British intelligence agencies, the British Armed Forces, foreign relations and economic considerations to defeat the UK's enemies. United States In recent years, some scholars have sought to differentiate smart power further from soft power, while also including military posture and other tools of statecraft as part of a broad smart power philosophy. Christian Whiton, a State Department official during the George W. Bush administration, recalled U.S. political influence activities from the Cold War, including CIA-backed programs like the Congress for Cultural Freedom, and called for adapting these to contemporary challenges to the U.S. posed by China, Iran, and Islamists. Challenges in the application of smart power According to "Dealing with Today's Asymmetric Threat to U.S. and Global Security", a symposium sponsored by CACI, an effective smart power strategy faces multiple challenges in transitioning from smart power as a theory to smart power in practice. Applying smart power today requires great difficulty, since it operates in an environment of asymmetric threats, ranging from cybersecurity to terrorism. These threats exist in a dynamic international environment, adding yet another challenge to the application of smart power strategy. In order to effectively address asymmetric threats arising in a dynamic international environment, the symposium suggests addressing the following factors: rule of law, organizational roadblocks, financing smart power, and strategic communications. Rule of law In order to implement smart power approaches on both a domestic and international level, the United States must develop a legal framework for the use of smart power capabilities. Developing a legal foundation for smart power, however, demands a clear concept of these asymmetric threats, which is often difficult. The cyber domain, for instance, presents an extremely nebulous concept. Hence, the challenge will be conceptualizing asymmetric threats before formulating a legal framework. Organizational roadblocks The inability to promote smart power approaches because of organizational failures within agencies presents another obstacle to successful smart power implementation. Agencies often lack either the appropriate authority or resources to employ smart power. The only way to give smart power long-term sustainability is to address these organizational failures and promote the coordination and accessibility of hard and soft power resources. Financing smart power With the ongoing financial crisis, the dire need for financial resources presents a critical obstacle to the implementation of smart power. According to Secretary Gates, 'there is a need for a dramatic increase in spending on the civilian instruments of national security---diplomacy, strategic communications, foreign assistance, civic action, and economic reconstruction and development." In order to successfully implement smart power, the U.S. budget needs to be rebalanced so that non-military foreign affairs programs receive more funding. Sacrificing defense spending will, however, be met with stalwart resistance. Strategic communications "Asymmetries of perception," according to the report, are a major obstacle to strategic communications. A long-term smart power strategy will mitigate negative perceptions by discussing the nature of these threats and making a case for action using smart power strategy. The report states that the central theme of our strategic communications campaign should be education of our nation in our values as a democratic nation and in the nature of the threats our nation faces today. United Nations as an instrument of smart power Of all the tools at the disposal of smart power strategists in the United States, experts suggest that the U.N. is the most critical. The Center for Strategic and International Studies issued a report, Investing in a New Multilateralism, in January 2009 to outline the role of the United Nations as an instrument of U.S. smart power strategy. The report suggests that in an increasingly multipolar world, the UN cannot be discarded as outdated and must be regarded as an essential tool to thinking strategically about the new multilateralism that our nation faces. An effective smart power strategy will align the interests of the U.S. and the UN, thereby effectively addressing threats to peace and security, climate change, global health, and humanitarian operations. Global perspectives on smart power U.S.-China relations As announced by Secretary of State Hillary Clinton in November 2011, the United States will begin to shift its attention to the Asia-Pacific region, making the strategic relationship between the U.S. and China of supreme importance in determining the future of international affairs in the region. The Center for Strategic and International Studies, in "Smart Power in U.S.-China Relations," offers recommendations for building a cooperative strategic relationship between the U.S. and China through smart power strategy. Rather than relying on unilateral action, the U.S. and China should combine their smart power resources to promote the global good and enhance the peace and security of the region. The report recommends the following policy objectives: implement an aggressive engagement agenda, launch an action agenda on energy and climate, and institute a new dialogue on finance and economics. Overall, the report suggests that U.S.-Sino relations should be pursued without the black-and-white view of China as either benign or hostile, but rather, as a partner necessary in serving the interests of the U.S. and the region while promoting the global good. U.S-Turkish Relations The Obama administration continually stresses the importance of smart power strategy in relations with the Middle East and especially Turkey due to its increasing leadership role as a regional soft power. As not only an Islamic democratic nation but also the only Muslim member of NATO, Turkey's leverage in the region could inspire other nations to follow in its footsteps. By establishing a cooperative relationship with Turkey and working to clarify misunderstandings through smart power, Turkey could eventually become the bridge between the East and the West. A smart power approach to U.S.-Turkish relations will expand the leadership role of Turkey in the region and increases its strategic importance to NATO. Debate surrounding smart power Transformational diplomacy versus smart power strategy Condoleezza Rice, Bush's Secretary of State, coined the term "Transformational Diplomacy" to denote Bush's policy to promote democracy through a hard power driven strategy. "Transformational diplomacy" stands at odds with "smart power," which utilizes hard and soft power resources based on the situation. The Obama administration's foreign policy was based on smart power strategy, attempting to strike a balance between defense and diplomacy. Smart power as an instrument of American imperialism In an interview with the Boston Globe, interviewer Anna Mundow, questioned Joseph Nye over the criticism that smart power is the friendly face of American imperialism. By the same token, the Bush doctrine has also been criticized for being "imperialistic," by focusing on American power over partnerships with the rest of the world. Joseph Nye defends smart power by noting that criticism often stems from a misunderstanding of the smart power theory. Nye himself designed the theory to apply to any nation of any size, not just the United States. It was meant to be a more sophisticated method of thinking about power in the context of the information age and post-9/11 world.19 President Obama defined his vision for U.S. leadership as "not in the spirit of a patron but the spirit of a partner." Ineffective use of smart power Ken Adelman, in an article entitled "Not-So-Smart Power," argues that there is no correlation between U.S. aid and the ability of America to positively influence events abroad. He points out that the nations who receive the most foreign aid, such as Egypt and Pakistan, are no more in tune with American values than those who receive less or no U.S. foreign aid. Overall, he criticizes the instruments of smart power, such as foreign aid and exchange programs, for being ineffective in achieving American national interests. Questioning old institutions and alliances In the application of smart power in U.S. strategy, Ted Galen Carpenter, author of the work Smart Power', criticizes U.S. foreign policy for failing to question outdated alliances, such as NATO. Carpenter articulated his disapproval of interventionist foreign policy, saying, "America does not need to be — and should not aspire to be — a combination global policeman and global social worker." Rather than utilizing antiquated institutions, the U.S. should rethink certain alliances in arriving at a new vision for the future of American foreign policy. Carpenter fears that America's domestic interests will be sacrificed in favor of global interests through smart power. Essentially, interventionist foreign policies advocated by U.S. smart power strategies undercut domestic liberties. See also Cold war Cultural diplomacy Soft power Engagement (diplomacy) Public diplomacy Noopolitik Carrot and stick approach Progressive realism Transformational diplomacy References External links Soft Power, Smart Power and Intelligent Power A lecture in honor of Joseph Nye Smart-Intelligent Power and Conflict management at State Level Paper presented during ICCTSS 2014, held at University of Karachi Soft Power Committee 'Persuasion and Power' report UK Parliament Strategic Defence and Security Review 2015 UK Government International relations terminology Power (social and political) concepts Political science terminology
```yaml description: | STM32 DMA controller (V2bis) for the stm32F0, stm32F1 and stm32L1 soc families This DMA controller includes several channels with different requests. All the requests ar ORed before entering the DMA, so that only one request must be enabled at a time. DMA clients connected to the STM32 DMA controller must use the format described in the dma.txt file, using a 2-cell specifier for each channel: a phandle to the DMA controller plus the following four integer cells: 1. channel: the dma stream from 1 to <dma-requests> 2. channel-config: A 32bit mask specifying the DMA channel configuration A name custom DMA flags for channel configuration is used which is device dependent see stm32_dma.h: -bit 5 : DMA cyclic mode config 0x0: STM32_DMA_MODE_NORMAL 0x1: STM32_DMA_MODE_CYCLIC -bit 6-7 : Direction (see dma.h) 0x0: STM32_DMA_MEMORY_TO_MEMORY: MEM to MEM 0x1: STM32_DMA_MEMORY_TO_PERIPH: MEM to PERIPH 0x2: STM32_DMA_PERIPH_TO_MEMORY: PERIPH to MEM 0x3: reserved for PERIPH to PERIPH -bit 9 : Peripheral Increment Address 0x0: STM32_DMA_PERIPH_NO_INC: no address increment between transfers 0x1: STM32_DMA_PERIPH_INC: increment address between transfers -bit 10 : Memory Increment Address 0x0: STM32_DMA_MEM_NO_INC: no address increment between transfers 0x1: STM32_DMA_MEM_INC: increment address between transfers -bit 11-12 : Peripheral data size 0x0: STM32_DMA_PERIPH_8BITS: Byte (8 bits) 0x1: STM32_DMA_PERIPH_16BITS: Half-word (16 bits) 0x2: STM32_DMA_PERIPH_32BITS: Word (32 bits) 0x3: reserved -bit 13-14 : Memory data size 0x0: STM32_DMA_MEM_8BITS: Byte (8 bits) 0x1: STM32_DMA_MEM_16BITS: Half-word (16 bits) 0x2: STM32_DMA_MEM_32BITS: Word (32 bits) 0x3: reserved -bit 15: Reserved -bit 16-17 : Priority level 0x0: STM32_DMA_PRIORITY_LOW: low 0x1: STM32_DMA_PRIORITY_MEDIUM: medium 0x2: STM32_DMA_PRIORITY_HIGH: high 0x3: STM32_DMA_PRIORITY_VERY_HIGH: very high Example of dma usual combination for peripheral transfer #define STM32_DMA_PERIPH_TX (STM32_DMA_MEMORY_TO_PERIPH | STM32_DMA_MEM_INC) #define STM32_DMA_PERIPH_RX (STM32_DMA_PERIPH_TO_MEMORY | STM32_DMA_MEM_INC) Example of dma node for stm32f103 dma1: dma-controller@40020400 { compatible = "st,stm32-dma-v2bis"; ... dma-requests = <7>; status = "disabled"; }; For the client part, example for stm32f103 on DMA1 instance Tx using channel 3 Rx using channel 2 spi1 { compatible = "st,stm32-spi"; dmas = <&dma1 3 (STM32_DMA_PERIPH_TX | STM32_DMA_PRIORITY_HIGH)>, <&dma1 2 (STM32_DMA_PERIPH_RX | STM32_DMA_PRIORITY_HIGH)>; dma-names = "tx", "rx"; }; compatible: "st,stm32-dma-v2bis" include: - name: st,stm32-dma.yaml properties: "#dma-cells": const: 2 # Parameter syntax of stm32 follows the dma client dts syntax # in the Linux kernel declared in # path_to_url dma-cells: - channel - channel-config ```
```html <div class="widgets"> <div class="row"> <div class="col-md-12"> <div ba-panel ba-panel-title="Form Wizard" ba-panel-class="with-scroll"> <ba-wizard> <ba-wizard-step title="Personal info" form="vm.personalInfoForm"> <form name="vm.personalInfoForm" novalidate> <div class="row"> <div class="col-md-6"> <div class="form-group has-feedback" ng-class="{'has-error': vm.personalInfoForm.username.$invalid && (vm.personalInfoForm.username.$dirty || vm.personalInfoForm.$submitted)}"> <label for="exampleUsername1">Username</label> <input type="text" class="form-control" id="exampleUsername1" name="username" placeholder="Username" ng-model="vm.personalInfo.username" required> <span class="help-block error-block basic-block">Required</span> </div> <div class="form-group" ng-class="{'has-error': vm.personalInfoForm.email.$invalid && (vm.personalInfoForm.email.$dirty || vm.personalInfoForm.$submitted)}"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" name="email" placeholder="Email" ng-model="vm.personalInfo.email" required> <span class="help-block error-block basic-block">Proper email required</span> </div> </div> <div class="col-md-6"> <div class="form-group" ng-class="{'has-error': vm.personalInfoForm.password.$invalid && (vm.personalInfoForm.password.$dirty || vm.personalInfoForm.$submitted)}"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" name="password" placeholder="Password" ng-model="vm.personalInfo.password" required> <span class="help-block error-block basic-block">Required</span> </div> <div class="form-group" ng-class="{'has-error': !vm.arePersonalInfoPasswordsEqual() && (vm.personalInfoForm.confirmPassword.$dirty || vm.personalInfoForm.$submitted)}"> <label for="exampleInputConfirmPassword1">Confirm Password</label> <input type="password" class="form-control" id="exampleInputConfirmPassword1" name="confirmPassword" placeholder="Confirm Password" ng-model="vm.personalInfo.confirmPassword" required> <span class="help-block error-block basic-block">Passwords should match</span> </div> </div> </div> </form> </ba-wizard-step> <ba-wizard-step title="Product Info" form="vm.productInfoForm"> <form name="vm.productInfoForm" novalidate> <div class="row"> <div class="col-md-6"> <div class="form-group has-feedback" ng-class="{'has-error': vm.productInfoForm.productName.$invalid && (vm.productInfoForm.productName.$dirty || vm.productInfoForm.$submitted)}"> <label for="productName">Product name</label> <input type="text" class="form-control" id="productName" name="productName" placeholder="Product name" ng-model="vm.productInfo.productName" required> <span class="help-block error-block basic-block">Required</span> </div> <div class="form-group" ng-class="{'has-error': vm.productInfoForm.productId.$invalid && (vm.productInfoForm.productId.$dirty || vm.productInfoForm.$submitted)}"> <label for="productId">Product id</label> <input type="text" class="form-control" id="productId" name="productId" placeholder="productId" ng-model="vm.productInfo.productId" required> <span class="help-block error-block basic-block">Required</span> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="productName">Category</label> <select class="form-control" title="Category" selectpicker> <option selected>Electronics</option> <option>Toys</option> <option>Accessories</option> </select> </div> </div> </div> </form> </ba-wizard-step> <ba-wizard-step title="Shipment" form="vm.addressForm"> <form name="vm.addressForm" novalidate> <div class="row"> <div class="col-md-6"> <div class="form-group has-feedback" ng-class="{'has-error': vm.addressForm.address.$invalid && (vm.addressForm.address.$dirty || vm.addressForm.$submitted)}"> <label for="productName">Shipment address</label> <input type="text" class="form-control" id="address" name="address" placeholder="Shipment address" ng-model="vm.shipment.address" required> <span class="help-block error-block basic-block">Required</span> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="productName">Shipment method</label> <select class="form-control" title="Category" selectpicker> <option selected>Fast & expensive</option> <option>Cheap & free</option> </select> </div> </div> </div> <div class="checkbox"> <label class="custom-checkbox"> <input type="checkbox"> <span>Save shipment info</span> </label> </div> </form> </ba-wizard-step> <ba-wizard-step title="Finish"> <form class="form-horizontal" name="vm.finishForm" novalidate> Congratulations! You have successfully filled the form! </form> </ba-wizard-step> </ba-wizard> </div> </div> </div> </div> ```
The Scout and Guide movement in the Cook Islands is served by two organisations The Girl Guides Cook Islands Association, member of the World Association of Girl Guides and Girl Scouts Cook Islands Boy Scout Association References
The Vanwall 254 is a four-stroke DOHC naturally-aspirated straight-four engine, designed, developed and built by British manufacturer Vanwall, for the Vanwall Grand Prix series of cars, between 1954 and 1960. References Straight-four engines Formula One engines
I, the Divine: A Novel in First Chapters is a 2001 novel by American writer Rabih Alameddine. References 2001 American novels Novels by Rabih Alameddine Novels set in Lebanon
```php <?php /* * This file is part of PhpSpec, A php toolset to drive emergent * design by specification. * * (c) Marcello Duarte <marcello.duarte@gmail.com> * (c) Konstantin Kudryashov <ever.zet@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PhpSpec\Exception\Fracture; /** * Class ClassNotFoundException holds information about class not found exception */ class ClassNotFoundException extends FractureException { /** * @var string */ private $classname; /** * @param string $message * @param string $classname */ public function __construct($message, $classname) { parent::__construct($message); $this->classname = $classname; } /** * @return string */ public function getClassname() { return $this->classname; } } ```
```python import tensorly as tl # Authors: Hratch Baghdassarian <hmbaghdassarian@gmail.com>, Erick Armingol <earmingol14@gmail.com> # similarity metrics for tensor decompositions def correlation_index( factors_1: list, factors_2: list, tol: float = 5e-16, method: str = "stacked" ) -> float: """CorrIndex implementation to assess tensor decomposition outputs. From [1] Sobhani et al 2022 (path_to_url Metric is scaling and column-permutation invariant, wherein each column is a factor. Parameters ---------- factors_1 : list The loading/factor matrices [A_1 ... A_N] for a low-rank tensor from its factors, output from first decomposition factors_2 : list The loading/factor matrices [A_1 ... A_N] for a low-rank tensor from its factors, output from second decomposition tol : float, optional Precision threshold below which to call the CorrIndex score 0, by default 5e-16 method : str, optional Method to obtain the CorrIndex by comparing the A matrices from two decompositions, by default 'stacked'. Possible options are: - 'stacked' : The original method implemented in [1]. Here all A matrices from the same decomposition are vertically concatenated, building a big A matrix for each decomposition. - 'max_score' : This computes the CorrIndex for each pair of A matrices (i.e. between A_1 in factors_1 and factors_2, between A_2 in factors_1 and factors_2, and so on). Then the max score is selected (the most conservative approach). In other words, it selects the max score among the CorrIndexes computed dimension-wise. - 'min_score' : Similar to 'max_score', but the min score is selected (the least conservative approach). - 'avg_score' : Similar to 'max_score', but the avg score is selected. Returns ------- score : float CorrIndex metric [0,1]; lower score indicates higher similarity between matrices """ # check input factors shape for factors in [factors_1, factors_2]: if len({tl.shape(A)[1] for A in factors}) != 1: raise ValueError( "Factors should be a list of loading matrices of the same rank" ) # check method options = ["stacked", "max_score", "min_score", "avg_score"] if method not in options: raise ValueError(f"The `method` must be either option among {options}") if method == "stacked": # vertically stack loading matrices -- shape sum(tensor.shape)xR) X_1 = [tl.concatenate(factors_1, 0)] X_2 = [tl.concatenate(factors_2, 0)] else: X_1 = factors_1 X_2 = factors_2 for x1, x2 in zip(X_1, X_2): if tl.shape(x1) != tl.shape(x2): raise ValueError("Factor matrices should be of the same shapes") # normalize columns to L2 norm - even if ran decomposition with normalize_factors=True col_norm_1 = [tl.norm(x1, axis=0) for x1 in X_1] col_norm_2 = [tl.norm(x2, axis=0) for x2 in X_2] for cn1, cn2 in zip(col_norm_1, col_norm_2): if tl.any(cn1 == 0) or tl.any(cn2 == 0): raise ValueError("Column norms must be non-zero") X_1 = [x1 / cn1 for x1, cn1 in zip(X_1, col_norm_1)] X_2 = [x2 / cn2 for x2, cn2 in zip(X_2, col_norm_2)] corr_idxs = [ _compute_correlation_index(x1, x2, tol=tol) for x1, x2 in zip(X_1, X_2) ] if method == "stacked": score = corr_idxs[0] elif method == "max_score": score = tl.max(corr_idxs) elif method == "min_score": score = tl.min(corr_idxs) elif method == "avg_score": score = tl.mean(corr_idxs) else: score = 1.0 return score def _compute_correlation_index(x1: list, x2: list, tol: float = 5e-16) -> float: """Computes the CorrIndex from the L2-normalized A matrices. Parameters ---------- x1 : list A list containing normalized A matrix(ces) from the first tensor decomposition. x2 : list A list containing normalized A matrix(ces) from the first tensor decomposition. tol : float, optional Precision threshold below which to call the CorrIndex score 0, by default 5e-16 Returns ------- score : float CorrIndex metric [0,1]; lower score indicates higher similarity between matrices """ # generate the correlation index input c_prod_mtx = tl.abs(tl.matmul(tl.conj(tl.transpose(x1)), x2)) # correlation index scoring n_elements = tl.shape(c_prod_mtx)[1] + tl.shape(c_prod_mtx)[0] score = (1 / (n_elements)) * ( tl.sum(tl.abs(tl.max(c_prod_mtx, 1) - 1)) + tl.sum(tl.abs(tl.max(c_prod_mtx, 0) - 1)) ) if score < tol: score = 0 return score ```
Dennis Roberts may refer to: Dennis Roberts (footballer) (1918–2001), English footballer Dennis J. Roberts (1903–1994), American politician in Rhode Island
Magra is a rural residential locality in the local government areas (LGA) of Brighton (7%), Southern Midlands (9%) and Derwent Valley (84%) in the Hobart, Central and South-east LGA regions of Tasmania. The locality is about west of the town of Brighton. The 2016 census recorded a population of 699 for the state suburb of Magra. It is in the Derwent Valley a few kilometres north of New Norfolk. Location and features Magra is just over the hill from New Norfolk. It consists mainly of dwelling houses and farmland. Accommodation is also available as the area is popular with tourists. Notable features of Magra itself include the surrounding hills and the plantation of Lombardy Poplars. The site of the grave of Betty King, believed to be the first European white woman to set foot on Australian soil, is located in the vicinity of Magra. History Magra was gazetted as a locality in 1970. It was previously known as Black River; the name was changed about 1912. It is believed to be an Aboriginal word for “day”. Stanton Farmhouse, built in 1817 is located in Magra on Back River Road. Magra Post Office opened on 1 June 1911 and closed in 1968. Geography Most of the boundaries are survey lines. Road infrastructure Route C184 (Black Hills Road) passes through the south-west corner. See also References External links https://web.archive.org/web/20130212154059/http://www.australiaforeveryone.com.au/places_newnorfolk.htm Towns in Tasmania Localities of Derwent Valley Council Localities of Southern Midlands Council Localities of Brighton Council (Tasmania)
Dick DeGuerin (born February 16, 1941 in Austin, Texas) is an American criminal defense attorney based in Houston, most notable for defending Tom DeLay, Allen Stanford, David Koresh and Robert Durst. In 1994, DeGuerin was named Outstanding Criminal Defense Lawyer of the Year by the State Bar of Texas Criminal Justice Section. Education He earned a law degree in 1965 from the University of Texas at Austin and that same year, he was admitted to the State Bar. Career Early in his career (1971–1982), he was an associate with Percy Foreman. In 2005, he defended former House Majority Leader Tom DeLay in DeLay's defense against indictments for money laundering and conspiracy, brought by Texas prosecutor Ronnie Earle. DeGuerin, a Democrat, previously prevailed over Earle in a case involving misconduct charges against U.S. Senator Kay Bailey Hutchison. DeLay was found guilty, but the conviction was overturned on appeal. He also represented bankers involved in fraud cases tied to the Enron collapse. He represented Waco, Texas leader David Koresh during Koresh's standoff with the FBI and the ATF agents. DeGuerin used a self-defense argument, and won, when he represented New York real estate heir Robert Durst, who admitted to killing and then dismembering the body of Durst's 71-year-old neighbor Morris Black, bagging the body parts and tossing them into Galveston Bay. DeGuerin once again represented Durst at his arraignment in New Orleans on March 16, 2015 for the murder of Susan Berman in 2000 (which arose out of the HBO miniseries special The Jinx: The Life and Deaths of Robert Durst). Other cases include participating in the Congressional impeachment hearing of U.S. District Court Judge Samuel B. Kent. He represented Celeste Beard, Senator Kay Bailey Hutchison, David Mark Temple, convicted of killing his wife, who was 8 months pregnant, Allen Stanford, and Billy Joe Shaver. In early June 2023, the Texas House committee investigating Texas attorney general Ken Paxton announced the hiring of DeGuerin and fellow high-profile attorney Rusty Hardin as impeachment prosecutors. He is an adjunct professor at The University of Texas School of Law, teaching criminal law. Personal life DeGuerin is the older brother of attorney Mike DeGeurin, despite the different way they spell their last names. A 2008 Houston Chronicle article about the brothers mentioned that Dick DeGuerin is married to his third wife. References External links DeGuerin & Dickson law practice homepage Dick DeGuerin's campaign contributions "Dream Team Shattered," Las Vegas CityLife 6 June 2004 Profile Roundtop Register Interview 1941 births Lawyers from Austin, Texas Living people Criminal defense lawyers Lawyers from Houston
```objective-c // This is a part of the Microsoft Foundation Classes C++ library. // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #pragma once #include "afxcontrolbarutil.h" #ifdef _AFX_PACKING #pragma pack(push, _AFX_PACKING) #endif #ifdef _AFX_MINREBUILD #pragma component(minrebuild, off) #endif class CMFCFontInfo; /*============================================================================*/ // CMFCFontComboBox window class CMFCFontComboBox : public CComboBox { // Construction public: CMFCFontComboBox(); // Attributes public: AFX_IMPORT_DATA static BOOL m_bDrawUsingFont; protected: CImageList m_Images; BOOL m_bToolBarMode; // Operations public: BOOL Setup(int nFontType = DEVICE_FONTTYPE | RASTER_FONTTYPE | TRUETYPE_FONTTYPE, BYTE nCharSet = DEFAULT_CHARSET, BYTE nPitchAndFamily = DEFAULT_PITCH); BOOL SelectFont(CMFCFontInfo* pDesc); BOOL SelectFont(LPCTSTR lpszName, BYTE nCharSet = DEFAULT_CHARSET); CMFCFontInfo* GetSelFont() const; protected: void Init(); void CleanUp(); // Overrides public: int DeleteString(UINT nIndex); virtual int CompareItem(LPCOMPAREITEMSTRUCT lpCompareItemStruct); virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); virtual void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct); virtual BOOL PreTranslateMessage(MSG* pMsg); protected: virtual void PreSubclassWindow(); // Implementation public: virtual ~CMFCFontComboBox(); protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnDestroy(); afx_msg LRESULT OnInitControl(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() }; #ifdef _AFX_MINREBUILD #pragma component(minrebuild, on) #endif #ifdef _AFX_PACKING #pragma pack(pop) #endif ```
```scss @import url('path_to_url @import '../../node_modules/bootstrap/scss/functions'; @import '_variables'; @import '../../node_modules/bootstrap/scss/bootstrap'; @import '../../node_modules/glyphicons-halflings/scss/glyphicons-halflings'; @import '../../node_modules/awesome-bootstrap-checkbox/awesome-bootstrap-checkbox'; @import '../../node_modules/font-awesome/css/font-awesome.min.css'; @import '_mixins'; @import '_overrides'; @import '_general'; @import '_utils'; ```
```go package units import ( "fmt" "regexp" "strconv" "strings" ) // See: path_to_url const ( // Decimal KB = 1000 MB = 1000 * KB GB = 1000 * MB TB = 1000 * GB PB = 1000 * TB // Binary KiB = 1024 MiB = 1024 * KiB GiB = 1024 * MiB TiB = 1024 * GiB PiB = 1024 * TiB ) type unitMap map[string]int64 var ( decimalMap = unitMap{"k": KB, "m": MB, "g": GB, "t": TB, "p": PB} binaryMap = unitMap{"k": KiB, "m": MiB, "g": GiB, "t": TiB, "p": PiB} sizeRegex = regexp.MustCompile(`^(\d+(\.\d+)*) ?([kKmMgGtTpP])?[iI]?[bB]?$`) ) var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"} func getSizeAndUnit(size float64, base float64, _map []string) (float64, string) { i := 0 unitsLimit := len(_map) - 1 for size >= base && i < unitsLimit { size = size / base i++ } return size, _map[i] } // CustomSize returns a human-readable approximation of a size // using custom format. func CustomSize(format string, size float64, base float64, _map []string) string { size, unit := getSizeAndUnit(size, base, _map) return fmt.Sprintf(format, size, unit) } // HumanSizeWithPrecision allows the size to be in any precision, // instead of 4 digit precision used in units.HumanSize. func HumanSizeWithPrecision(size float64, precision int) string { size, unit := getSizeAndUnit(size, 1000.0, decimapAbbrs) return fmt.Sprintf("%.*g%s", precision, size, unit) } // HumanSize returns a human-readable approximation of a size // capped at 4 valid numbers (eg. "2.746 MB", "796 KB"). func HumanSize(size float64) string { return HumanSizeWithPrecision(size, 4) } // BytesSize returns a human-readable size in bytes, kibibytes, // mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB"). func BytesSize(size float64) string { return CustomSize("%.4g%s", size, 1024.0, binaryAbbrs) } // FromHumanSize returns an integer from a human-readable specification of a // size using SI standard (eg. "44kB", "17MB"). func FromHumanSize(size string) (int64, error) { return parseSize(size, decimalMap) } // RAMInBytes parses a human-readable string representing an amount of RAM // in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and // returns the number of bytes, or -1 if the string is unparseable. // Units are case-insensitive, and the 'b' suffix is optional. func RAMInBytes(size string) (int64, error) { return parseSize(size, binaryMap) } // Parses the human-readable size string into the amount it represents. func parseSize(sizeStr string, uMap unitMap) (int64, error) { matches := sizeRegex.FindStringSubmatch(sizeStr) if len(matches) != 4 { return -1, fmt.Errorf("invalid size: '%s'", sizeStr) } size, err := strconv.ParseFloat(matches[1], 64) if err != nil { return -1, err } unitPrefix := strings.ToLower(matches[3]) if mul, ok := uMap[unitPrefix]; ok { size *= float64(mul) } return int64(size), nil } ```
The Radio Suisse Romande (RSR) was an enterprise unit within public-broadcasting corporation SRG SSR. It is responsible for the production and transmission of French-language radio programmes in Switzerland. RSR's headquarters are situated in Lausanne. Radio Suisse Romande and Télévision Suisse Romande merged in 2010 to create Radio Télévision Suisse. Broadcasting RSR broadcasts on four radio channels: La 1ère – news, talk, and general programming Espace 2 – culture and classical music Couleur 3 – youth-oriented programming Option Musique – music ("the hits of yesterday and today") These channels are broadcast on FM as well as via Digital Audio Broadcasting and satellite (DVB-S). Up until 5 December 2010, Option Musique was also available on AM at 765 kHz from the Sottens transmitter. External links RSR's listeners' website French-language mass media in Switzerland Radio in Switzerland Swiss Broadcasting Corporation