typic | Type-safe transmutations between layout-compatible types | DevOps library
kandi X-RAY | typic Summary
kandi X-RAY | typic Summary
Typic helps you transmute fearlessly. It worries about the subtleties of soundness and safety so you don't have to!.
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample of typic
typic Key Features
typic Examples and Code Snippets
Community Discussions
Trending Discussions on typic
QUESTION
In Python, is there a way to distinguish between strings and other iterables of strings?
A str
is valid as an Iterable[str]
type, but that may not be the correct input for a function. For example, in this trivial example that is intended to operate on sequences of filenames:
ANSWER
Answered 2022-Mar-29 at 06:36This issue has been discussed since at least July 2016. On a proposal to distinguish between str
and Iterable[str]
, Guido van Rossum writes:
Since
str
is a valid iterable ofstr
this is tricky. Various proposals have been made but they don't fit easily in the type system.
You'll need to list out all of the types that you want your functions to accept explicitly, using Union
(pre-3.10) or |
(3.10 and higher).
e.g. For pre-3.10, use:
QUESTION
One of the primary reasons I like using TypeScript is to check that I am passing correctly typed params to given function calls.
However, when using Next.js, I am running into the issue where params passed to a Next.js API endpoint end up losing their types when the are "demoted" to the NextApiRequest
type.
Typically, I would pull off params doing something like req.body.[param_name]
but that entire chain has type any
so I lose any meaningful type information.
Let's assume I have an API endpoint in a Next.js project at pages/api/add.ts
which is responsible for adding two numbers. In this file, we also have a typed function for adding two numbers, that the API endpoint will call.
ANSWER
Answered 2022-Jan-21 at 22:24You can create a new interface that extends NextApiRequest
and adds the typings for the two fields.
QUESTION
What's the XLA class XlaBuilder
for? The docs describe its interface but don't provide a motivation.
The presentation in the docs, and indeed the comment above XlaBuilder
in the source code
ANSWER
Answered 2021-Dec-15 at 01:32XlaBuilder
is the C++ API for building up XLA computations -- conceptually this is like building up a function, full of various operations, that you could execute over and over again on different input data.
Some background, XLA serves as an abstraction layer for creating executable blobs that run on various target accelerators (CPU, GPU, TPU, IPU, ...), conceptually kind of an "accelerator virtual machine" with conceptual similarities to earlier systems like PeakStream or the line of work that led to ArBB.
The XlaBuilder
is a way to enqueue operations into a "computation" (similar to a function) that you want to run against the various set of accelerators that XLA can target. The operations at this level are often referred to as "High Level Operations" (HLOs).
The returned XlaOp
represents the result of the operation you've just enqueued. (Aside/nerdery: this is a classic technique used in "builder" APIs that represent the program in "Static Single Assignment" form under the hood, the operation itself and the result of the operation can be unified as one concept!)
XLA computations are very similar to functions, so you can think of what you're doing with an XlaBuilder
like building up a function. (Aside: they're called "computations" because they do a little bit more than a straightforward function -- conceptually they are coroutines that can talk to an external "host" world and also talk to each other via networking facilities.)
So the fact XlaOp
s can't be used across XlaBuilder
s may make more sense with that context -- in the same way that when building up a function you can't grab intermediate results in the internals of other functions, you have to compose them with function calls / parameters. In XlaBuilder
you can Call
another built computation, which is a reason you might use multiple builders.
As you note, you can choose to inline everything into one "mega builder", but often programs are structured as functions that get composed together, and ultimately get called from a few different "entry points". XLA currently aggressively specializes for the entry points it sees API users using, but this is a design artifact similar to inlining decisions, XLA can conceptually reuse computations built up / invoked from multiple callers if it thought that was the right thing to do. Usually it's most natural to enqueue things into XLA however is convenient for your description from the "outside world", and allow XLA to inline and aggressively specialize the "entry point" computations you've built up as you execute them, in Just-in-Time compilation fashion.
QUESTION
The arithmetic mean of two unsigned integers is defined as:
...ANSWER
Answered 2022-Mar-08 at 10:54The following method avoids overflow and should result in fairly efficient assembly (example) without depending on non-standard features:
QUESTION
Suppose that I have implemented two Python types using the C extension API and that the types are identical (same data layouts/C struct
) with the exception of their names and a few methods. Assuming that all methods respect the data layout, can you safely change the type of an object from one of these types into the other in a C function?
Notably, as of Python 3.9, there appears to be a function Py_SET_TYPE
, but the documentation is not clear as to whether/when this is safe to do. I'm interested in knowing both how to use this function safely and whether types can be safely changed prior to version 3.9.
I'm writing a Python C extension to implement a Persistent Hash Array Mapped Trie (PHAMT); in case it's useful, the source code is here (as of writing, it is at this commit). A feature I would like to add is the ability to create a Transient Hash Array Mapped Trie (THAMT) from a PHAMT. THAMTs can be created from PHAMTs in O(1)
time and can be mutated in-place efficiently. Critically, THAMTs have the exact same underlying C data-structure as PHAMTs—the only real difference between a PHAMT and a THAMT is a few methods encapsulated by their Python types. This common structure allows one to very efficiently turn a THAMT back into a PHAMT once one has finished performing a set of edits. (This pattern typically reduces the number of memory allocations when performing a large number of updates to a PHAMT).
A very convenient way to implement the conversion from THAMT to PHAMT would be to simply change the type pointers of the THAMT objects from the THAMT type to the PHAMT type. I am confident that I can write code that safely navigates this change, but I can imagine that doing so might, for example, break the Python garbage collector.
(To be clear: the motivation is just context as to how the question arose. I'm not looking for help implementing the structures described in the Motivation, I'm looking for an answer to the Question, above.)
...ANSWER
Answered 2022-Mar-02 at 01:13According to the language reference, chapter 3 "Data model" (see here):
An object’s type determines the operations that the object supports (e.g., “does it have a length?”) and also defines the possible values for objects of that type. The type() function returns an object’s type (which is an object itself). Like its identity, an object’s type is also unchangeable.[1]
which, to my mind states that the type must never change, and changing it would be illegal as it would break the language specification. The footnote however states that
[1] It is possible in some cases to change an object’s type, under certain controlled conditions. It generally isn’t a good idea though, since it can lead to some very strange behaviour if it is handled incorrectly.
I don't know of any method to change the type of an object from within python itself, so the "possible" may indeed refer to the CPython function.
As far as I can see a PyObject
is defined internally as a
QUESTION
I handle a channelDelete event in my discord bot. My original intent was to do the following:
- Listen for when a channel is deleted
- Check to see if its type equals 'GUILD_CATEGORY'
- Delete all the channels under that category
I can typically access channels under a CategoryChannel
through its property called children
anywhere else except during this event...
ANSWER
Answered 2022-Feb-19 at 14:09Unfortunately, this is how CategoryChannels work in discord.js...
When the category is deleted, discord.js sends a request to the API to delete the channel. Only then, Discord sends you the event after the category is deleted.
What happens next is that the children are not located in the category anymore! So you will not be able to get the children inside the CategoryChannel object.
This is the code for the children
property
QUESTION
Please forgive me if this question is dumb.
While reading about Haskell kinds, I notice a theme:
...ANSWER
Answered 2022-Feb-13 at 00:42The most basic form of the kind language contains only *
(or Type
in more modern Haskell; I suspect we'll eventually move away from *
) and ->
.
But there are more things you can build with that language than you can express by just "counting the number of *
s". It's not just the number of *
or ->
that matter, but how they are nested. For example * -> * -> *
is the kind of things that take two type arguments to produce a type, but (* -> *) -> *
is the kind of things that take a single argumemt to produce a type where that argument itself must be a thing that takes a type argument to produce a type. data ThreeStars a b = Cons a b
makes a type constructor with kind * -> * -> *
, while data AlsoThreeStars f = AlsoCons (f Integer)
makes a type constructor with kind (* -> *) -> *
.
There are several language extensions that add more features to the kind language.
PolyKinds
adds kind variables that work exactly the same way type variables work. Now we can have kinds like forall k. (* -> k) -> k
.
ConstraintKinds
makes constraints (the stuff to the left of the =>
in type signatures, like Eq a
) become ordinary type-level entities in a new kind: Constraint
. Rather than the stuff left of the =>
being special purpose syntax fairly disconnected from the rest of the language, now what is acceptable there is anything with kind Constraint
. Classes like Eq
become type constructors with kind * -> Constraint
; you apply it to a type like Eq Bool
to produce a Constraint
. The advantage is now we can use all of the language features for manipulating type-level entities to manipulate constraints (including PolyKinds
!).
DataKinds
adds the ability to create new user-defined kinds containing new type-level things, in exactly the same way that in vanilla Haskell we can create new user-defined types containing new term-level things. (Exactly the same way; the way DataKinds
actually works is that it lets you use a data
declaration as normal and then you can use the resulting type constructor at either the type or the kind level)
There are also kinds used for unboxed/unlifted types, which must not be ever mixed with "normal" Haskell types because they have a different memory layout; they can't contain thunks to implement lazy evaluation, so the runtime has to know never to try to "enter" them as a code pointer, or look for additional header bits, etc. They need to be kept separate at the kind level so that ordinary type variables of kind *
can't be instantiated with these unlifted/unboxed types (which would allow you to pass these types that need special handling to generic code that doesn't know to provide the special handling). I'm vaguely aware of this stuff but have never actually had to use it, so I won't add any more so I don't get anything wrong. (Anyone who knows what they're talking about enough to write a brief summary paragraph here, please feel free to edit the answer)
There are probably some others I'm forgetting. But certainly the kind language is richer than the OP is imagining just with the basic Haskell features, and there is much more to it once you turn on a few (quite widely used) extensions.
QUESTION
When type annotating a variable of type dict, typically you'd annotate it like this:
...ANSWER
Answered 2022-Jan-20 at 22:49With dict[str:int]
the hint you are passing is dict
whose keys are slices, because x:y is a slice in python.
The dict[str, int]
passes the correct key and value hints, previously there also was a typing.Dict
but it has been deprecated.
QUESTION
Scrapping links should be a simple feat, usually just grabbing the src
value of the a tag.
I recently came across this website (https://sunteccity.com.sg/promotions) where the href value of a tags of each item cannot be found, but the redirection still works. I'm trying to figure out a way to grab the items and their corresponding links. My typical python selenium code looks something as such
...ANSWER
Answered 2022-Jan-15 at 19:47You are using a wrong locator. It brings you a lot of irrelevant elements.
Instead of find_elements_by_class_name('thumb-img')
please try find_elements_by_css_selector('.collections-page .thumb-img')
so your code will be
QUESTION
I have an iterable of bytes
, such as
ANSWER
Answered 2022-Jan-10 at 08:29I used yield
and re.finditer
.
The yield expression is used when defining a generator function or an asynchronous generator function and thus can only be used in the body of a function definition. Using a yield expression in a function’s body causes that function to be a generator function
Return an iterator yielding match objects over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result.
If there are no groups, return a list of strings matching the whole pattern. If there is exactly one group, return a list of strings matching that group. If multiple groups are present, return a list of tuples of strings matching the groups. Non-capturing groups do not affect the form of the result.
The regular expression ([^\r\n]*)(\r\n|\r|\n)?
can be divided into two parts to match (that is, two groups). The first group matches the data without \r
and \n
, and the second group matches \r
, \n
or \r\n
.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install typic
Rust is installed and managed by the rustup tool. Rust has a 6-week rapid release process and supports a great number of platforms, so there are many builds of Rust available at any time. Please refer rust-lang.org for more information.
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page