Jude: Julia Development Extensions

Jude

JUlia Development Extensions

Jude statically parses your codebase in javascript to provide IDE like capabilities for Atom:

  • non-fuzzy autocomplete
  • jump to definition
  • forward/back cursor history
  • highlights incorrect name errors and some parsing errors

In the future, this may include tools to find usages of a function, limited static type checking, and some refactoring/renaming.

Jude demo gif

Getting started

julia should be on your PATH. You can customize the exact path to julia in the Jude package settings.

Autocomplete is triggered by typing. Only names available in the scope (eg try block, for loop, function scope) are shown. To get function signatures, press ctrl-space after the ...(. You can tab through the arg list.

Jump to defintion is also triggered by ctrl-space when the cursor is on any word. You can jump to function definitions, type defintions, or variable declarations for files in your workspace. You can even jump to some function declarations in files not in your workspace, such as in the base library. Your jump history is tracked, and you can go back/forward using ctrl-alt-left/ctrl-alt-right.

Syntax errors are highlighted as lint warnings. Jude shows these when it cannot parse your code or resolve a name. You can customize the linter to hide the error message panel that pops up at the bottom of the screen by going to the Linter package options and unselecting Show Error Panel.

How it works

Jude performs a full syntax parse of all the Julia files in your workspace in Javascript, and does scoping analysis statically to resolve names. Names are resolved specific to the scope where they are used, not using fuzzy matching over the entire project. Your project files are not loaded into Julia or executed to run the analysis.

Jude reparses some or all of your code as you type. This is done in <50 ms for small to medium sized codebases, especially if it is broken into modules. If you are editing a file that has no "module" declarations (maybe it is just included in another file that does), the reparse can be <5 ms.

This is a parser written in Javascript (actually Typescript) separate from the Julia compiler, so there are some gaps in its coverage. Currently, most Julia syntax should be parsed correctly, but this is a work in progress! Please help make it better by reporting any parsing problems or even submitting pull requests. The goal is not necessarily to be a full syntax checker for Julia, but just to be able to resolve names properly. Many errors are shown in the Chromium Dev Tools console, which can be opened with the command Window: Toggle Dev Tools.

For imported modules that are not in the workspace, Jude starts up a short lived child Julia process and queries it for the module contents. It will import type definitions, function signatures, macros, and variables at the module level. During the first run with Jude newly installed, it may take a minute to retrieve the Base library and any modules you have imported into your files. Afterwards, the results are cached. The path to Julia is configurable in the Jude options.

Limitations

Julia is a very flexible language, but for Jude to provide these capabilities, some restrictions are in place.

  • Jude can only follow include("...") calls where the string is a constant literal.
  • include("...") can only be present at the module level, not inside a function.
  • Binary operators cannot be overridden to not be binary, eg: + = 5
  • Anonymous functions have no signature information.
    • foo = (a, b) -> a + b has no signature information because foo is treated as a variable.
    • foo(a,b) = a + b is recognized.
  • Jude can jump to function definitions not in your workspace, but Julia reflection doesn't provide the locations for type definitions or macro definitions.

Parsing should be very fast, but if it starts to cause noticable slow down in the GUI, you can reduce the parsing intervals by changing the lint delay in the Linter package (Lint As You Type Interval, which defaults to 300 ms).

Julia is a dynamic language, so autocomplete currently only works for functions/types/variables, not for fields on types. This is because the type of the object often cannot be determined statically, so the fields are unknown. There is no fuzzy matching currently for fields. In the future, there may be some flow analysis that allows types to be inferred such as from function arg list signatures or type assertions. If Julia eventually allows return type declarations, these can be leveraged too.

Known issues

  • The bodies of macro definitions are not parsed.
  • Code quotes are not parsed, eg :(a + b), quote ... end
  • Jump to definition for overloaded functions currently leverages Autocomplete+ for the GUI to select the overload. When you jump, Autocomplete+ will insert the function signature you selected, and Jude will then undo the change. This clears any redos on your undo stack. Eventually, a separate GUI will be created, along with a separate shortcut from ctrl-space.

Roadmap

  • Testing.
  • Indicators to show when running julia in background or a running a long parse.
  • Fix gaps in syntax coverage.
  • Use own GUI for jump to function definitions.
  • Refactor capability for variable and type names.
  • Perhaps factor into service that can be plugged into other editors.
  • Simple flow analysis to allow autocomplete of some fields.

Download Details:

Author: jamesdanged
Source Code: https://github.com/jamesdanged/Jude 

#julia #extensions 

Jude: Julia Development Extensions
Hunter  Krajcik

Hunter Krajcik

1660453020

List_ext: Dart Extension Method for Iterable and List

list_ext 

Dart extension method for Iterable and List.

Usage

To use this plugin, add list_ext as a dependency in your pubspec.yaml file.

Than add import 'package:list_ext/list_ext.dart'; to the file for use extension methods.

Example

import 'package:list_ext/list_ext.dart';

void main() {
  final list = [1, 2, 5];
  final sum = list.sum();
  print('Sum: $sum');
  // Output: Sum: 8
}

Methods classifier

Common

  • countWhere() - returns count of elements that satisfy the predicate.
  • containsAll() - returns true if the collection contains all elements from the given collection.

Equality

  • isNullOrEmpty/isNotNullOrEmpty - check for null or empty.
  • isUnorderedEquivalent() - check equality of the elements of two iterables without considering order.

Search

  • firstWhereOrNull() - return the first found element or null if no element found.

Safe elements access

  • firstOrNull - returns the first element or null if collection is empty.
  • tryElementAt() - returns the element at the index if exists or orElse if it is out of range.

Transformation

  • reduceValue() - reduces values of elements in a collection to a single value by iteratively combining its using the provided function.

Iterables

  • chunks() - splits into chunks of the specified size.
  • intersperse() - adds an element between elements of the iterable.

String

  • joinOf() - get string value for each element and concatenates it with passed separator.

Map

  • toMap() - creates a Map instance from the iterable.

Math

  • maxOf() - returns max of values by elements.
  • minOf() - returns min of values by elements.
  • sumOf()/sumOfDouble() - returns sum of values by elements.
  • avgOf()/avgOfDouble() - returns the average value of values by elements.

There are specific version of methods for Iterables of num (int and double):

  • max().
  • min().
  • sum().
  • avg().

List specific methods

Common

Get an element

  • random - returns a random element from the list.

Modification

Element

  • replace() - Remove all element occurrences and replace its with another element.
  • replaceWhere() - Replace all elements of list that satisfy given predicate.
  • addIfNotNull() - Adds element to the end of this list if this element is not null.

Sorting

  • sortBy() - Sorts the list in ascending order of the object's field value.
  • sortByDescending() - Sorts the list in descending order of the object's field value.

Transformation

List

  • copyWith() - Copy current list with adding element.
  • copyWithAll() - Copy current list with adding all elements from another list.
  • copyWithReplace() - Copy current list, replacing all element occurrences with another element.
  • copyWithReplaceWhere() - Copy current list, replacing elements of list that satisfy given predicate with another element.
  • copyWithInsertAll() - Copy current list with adding all elements at the provided position of new list.

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add list_ext

With Flutter:

 $ flutter pub add list_ext

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  list_ext: ^1.0.4

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:list_ext/list_ext.dart';

example/main.dart

import 'package:list_ext/list_ext.dart';

void main() {
  final list = [1, 2, 5, 1];
  final sum = list.sum();
  print('Sum: $sum');

  final sumSquare = list.sumOf((v) => v * v);
  print('Sum of squares: $sumSquare');

  final count = list.countWhere((v) => v == 1);
  print('Count of 1: $count');
}

Download Details:

Author: Innim
Source Code: https://github.com/Innim/dart_list_extensions 
License: BSD-3-Clause license

#flutter #dart #list #extensions 

List_ext: Dart Extension Method for Iterable and List
Lawson  Wehner

Lawson Wehner

1660320960

Dart_extensions: Extentions for Dart

What New

  • Responsive UI tools 💪🏻💪🏻💪🏻
  • flatJson -> Flatten a nested Map into a single level map
  • Iterables -> all -> Returns true if all elements match the given
  • isVideo - Checks if string is an video file.
  • isAudio - Checks if string is an audio file.
  • isImage - Checks if string is an image file.
  • isNumericOnly - Check if the string has any number in it.
  • isAlphabetOnly - Checks if string consist only Alphabet. (No Whitespace)
  • hasCapitalletter - Checks if string contains at least one Capital Letter.
  • isHTML - Checks if string is an html file.
  • isEmail - Checks if string is email..
  • isPhoneNumber - Checks if string is phone number, good for login checks.
  • isUsername - Checks if string is a valid username, good for login checks.
  • isCurrency - Checks if string is Currency.
  • isPalindrom - Checks if string is Palindrome. (good to know for interviews

as well) Why Method Extensions? When you’re using someone else’s API or when you implement a library that’s widely used, it’s often impractical or impossible to change the API. But you might still want to add some functionality.

let me know if you want something specific or you found a bug at bar.idan@gmail.com

Let get started 💪🏻

  1. Go to pubspec.yaml
  2. add a dart_extensions and replace [version] with the latest version:
dependencies:  
 dart_extensions: ^[version]
  1. click the packages get button or flutter pub get

Responsive UI

Very common way to calculate size in percentage is using the MediaQuery like so:

MediaQuery.of(context).size.width * 0.1

Flatten a nested Map into a single level map

response.flatJson({
  'key1': {'keyA': 'valueI'},
  'key2': {'keyB': 'valueII'},
  'key3': {
    'a': {
      'b': {'c': 2}
    }
  }
});

The result you can also specify max depth, its the maximum number of nested objects to flatten.

// { // 'key1.keyA': 'valueI', // 'key2.keyB': 'valueII', // 'key3.a.b.c': 2 // };

Instead of the boilerplate we can use this awesome extension and get the same results.

Wrap your Application with:

ResponsiveApp(
      builder: (BuildContext context, Orientation orientation, DeviceType deviceType) {
        return YourAppWidget()
)
AnimatedList(
              key: chatListKey,
              reverse: true,
              padding: EdgeInsets.only(top: 10.textSizeResponsive),
              shrinkWrap: true,

Also the text should be responsive, no problem

Text(
  'Note added by ${message.from ?? ''}',
  style: avanirBook.copyWith(fontSize: 8.responsiveText),
),

Iterable Extensions

.any()

Returns true if at least one element matches the given predicate.

final users = [User(22, "Kasey"), User(23, "Jadn")]; 
users.any((u) => u.name == 'Kasey') // true

.groupBy()

Groups the elements in values by the value returned by key.

final users = [User(22, "Kasey"), User(23, "Jadn"), User(22, "Rene"), User(32, "Aden")]; 

users.groupBy((u) => u.age); 

Sort the users by age:

{  
  22: [User:22, Kasey, User:22, Rene], 
  23: [User:23, Jadn], 
  32: [User:32, Aden]
}

.sortBy()

Sorts elements in the array in-place according to natural sort order of the value returned by specified selector function.

final users = [User(22, "Kasey"), User(16, "Roni"), User(23, "Jadn")]; 
users.sortBy((u) => u.age) ///  [User(16, "Roni"), [User(22, "Kasey"), User(23, "Jadn")]

.find()

Returns the first element matching the given predicate, or null if element wasn't found.

final users = [User(22, "Kasey"), User(23, "Jadn"), User(22, "Rene"), User(32, "Aden")]; 

users.find((u) => u.name == "Rene") // User(22, "Rene")

.chunks()

Splits the Iterable into chunks of the specified size

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].chunks(3)) 

result

([1, 2, 3], [4, 5, 6], [7, 8, 9], [10])

.filter()

Returns a list containing only elements matching the given predicate, the return type will be List, unlike the where operator that return Iterator, also it filters null.

final users = [User(22, "Kasey"), User(23, "Jadn"), User(22, "Rene"), User(32, "Aden")]; 
final filtered = users.filter((u) => u.name == "Kasey"); // [User(22, "Kasey")] <- Type List<User>

final listWithNull = [null, User(23, "Jadn"), User(22, "Rene"), User(32, "Aden")];
final filtered = listWithNull.filter((u) => u.name == "Jadn"); // [User(23, "Jadn")]

.intersect()

Returns a set containing all elements that are contained by both this set and the specified collection.

Set.from([1, 2, 3, 4]).intersect(Set.from([3, 4, 5, 6]) // 1,2,3,4,5,6

.filterNot()

Returns a list containing only not the elements matching the given predicate, the return type will be List, unlike the where operator that return Iterator, also it filters null.

final users = [User(22, "Kasey"), User(23, "Jadn"), User(22, "Rene"), User(32, "Aden")]; 
final filtered = users.filterNot((u) => u.name == "Kasey"); // [User(23, "Jadn"), User(22, "Rene"), User(32, "Aden")] <- Type List<User>

final listWithNull = [null, User(23, "Jadn"), User(22, "Rene"), User(32, "Aden")];
final filtered = listWithNull.filterNot((u) => u.name == "Jadn"); // [User(22, "Rene"), User(32, "Aden")]

.takeOnly()

Returns a list containing first [n] elements.

[1, 2, 3, 4].takeOnly(1) // [1]

.drop()

Returns a list containing all elements except first [n] elements.

[1, 2, 3, 4].drop(1) // [2, 3, 4]

.forEachIndexed()

Performs the given action on each element on iterable, providing sequential index with the element.

["red","green","blue"].forEachIndexed((item, index) { 
	print("$item, $index"); 
}); // 0: red // 1: green // 2: blue```  

.sortedDescending()

Returns a new list with all elements sorted according to descending natural sort order.

var list = [1,2,3,4,5];  
final descendingList = list.sortedDescending();  
print(descendingList); // [5, 4, 3, 2, 1]

.count()

Return a number of the existing elements by a specific predicate

final users = [User(33, "Miki"), User(45, "Anna"), User(19, "Amit")];  
  
final aboveAgeTwenty = users.count((user) => user.age > 20);  
print(aboveAgeTwenty); // 2

.associate()

Creates a Map instance in which the keys and values are computed from the iterable.

final users = [User(33, "Miki"), User(45, "Anna"), User(19, "Amit")];  

users.associate((k) => k.name, (e) => e.age) // 'Miki': 33, 'Anna': 45, 'Amit': 19}

.concatWithMultipleList()

Return a list concatenates the output of the current list and multiple iterables.

  final listOfLists = [
        [5, 6, 7],
        [8, 9, 10]
      ];
  [1, 2, 3, 4].concatWithMultipleList(listOfLists); 
  
  // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

.distinctBy()

Returns a list containing only the elements from given collection having distinct keys.

// example 1
final users = ["Zack", "Ian", "Ronit"];  
users.distinctBy((u) => u.toLowerCase().startsWith("z")); // Zack 

// example 2
final users = [User(11, 'idan'), User(12, 'ronit'), User(11, 'asaf')];
	
final dist = users.distinctBy((u) => u.age);    
dist.forEach((u) => print(u.age)); //  11, 12

.zip()

Zip is used to combine multiple iterables into a single list that contains the combination of them two.


final soldThisMonth = [Motorcycle(2020, 'BMW R1200GS'), Motorcycle(1967, 'Honda GoldWing')];
final soldLastMonth = [Motorcycle(2014, 'Honda Transalp'), Motorcycle(2019, 'Ducati Multistrada')];    
  
final sales = soldThisMonth.zip(soldLastMonth).toList();  
  				
print(sales); // [
  [brand: BMW R1200GS year: 2020, brand: Honda Transalp year: 2014], // first pair from this month and last
  [brand: Honda GoldWing year: 1967, brand: Ducati Multistrada year: 2019] // second pair from last month 
]

See iterable.dart for more examples.

Flutter Extensions

Context extensions

Are you not tired from typing MediaQuery.of(context).size... to get height or width? here's a cool extension

  context.mq  // returns the MediaQuery
  context isLandscape // returns if Orientation is landscape
context.sizePx // returns same as MediaQuery.of(context).size
context.widthPx // returns same as MediaQuery.of(context).size.width
context.heightPx // returns same as MediaQuery.of(context).height

Text Extensions

final text = Text('hello')
     .bold()
     .fontSize(25)
     .italic();

List

    final someWidgetList = [
      Text('hello'),
      Text('world'),
    ].toColumnWidget();  // toRowWidget(), toStackWidget()

Widget extensions

So now we can just add round corners, shadows, align, and added gestures to our Widgets without the crazy water-fall effect. awesome! That's just the tip of the iceberg, expect to see very cool stuff soon.

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Stack(
          children: <Widget>[
            Container(
              height: 100,
              width: 100,
            )   .withRoundCorners(backgroundColor: Colors.grey)
                .withShadow()
                .alignAtCenter()
                .toCenter()
                .withTooltip('just a tooltip')
                .paddingOnly(left: 10)
                .paddingAll(20)
                .onTap(() => print('tap'))
                .onLongPress(() => print('long press'))
          ],
        ),
      ),
    );
  }
}

Navigation

We can navigate from every widget by calling these methods

    navigateTo(route: MaterialPageRoute(builder: (c) => Login()));
    navigateByRouteName(Routes.home, );
    final result = navigateBack();

Http Extensions

.httpGet()

Sends an HTTP GET request with the given headers to the given URL

final json = await "https://jsonplaceholder.typicode.com/posts".httpGet();

result:

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere",
    "body": "quia et suscipit"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "dolor beatae ea dolores neque"
  },
]

usage with then:

"https://jsonplaceholder.typicode.com/posts".httpGet().then((result) {
          print(result);
       }).catchError((e) => print(e));

.httpPost()

Sends an HTTP POST request with the given headers and body to the given URL which can be a [Uri] or a [String].

String json = '{"title": "Hello", "body": "body text", "userId": 1}';
final json = await "https://jsonplaceholder.typicode.com/posts".httpPost(json);

for more examples (put, delete) See http.dart

Range Extensions

.until()

Returns a sequence of integer, starting from the current number until the [end] number. [step] is optional, it will step number if given

for(final num in 1.until(10)) {
  numbers.add(num); 
}

result

[1, 2, 3, 4, 5, 6, 7, 8, 9]

with step:

for(final num in 1.until(10, step: 2)) {
  numbers.add(num); 
}

result

[1, 3, 5, 7, 9]

String Extensions

.asBool()

Returns true if this string is any of these values: "true", "yes", "1", or if the string is a number and greater than 0, false if less than 1. This is also case insensitive.

'true'.asBool  // true
'True'.asBool  // true
'false'.asBool //  false
'False'.asBool //  false
'yes'.asBool   // true
'YES'.asBool   // true
'no'.asBool    // false
'NO'.asBool    // false

.insert()

Returns a new string in which a specified string is inserted at a specified index position in this instance.

'test'.insert(1, 't') // 'ttest'
'123456890'.insert(6, '7') // '1234567890'
'dart cool'.insert(4, ' is') // 'dart is cool'

.isNullOrWhiteSpace()

Indicates whether a specified string is null, empty, or consists only of white-space characters.

'test'.isNullOrWhiteSpace // false
'   '.isNullOrWhiteSpace, // true
null.isNullOrWhiteSpace, // true
'  te  st  '.isNullOrWhiteSpace // false

.replaceAfter()

Replace part of string after the first occurrence of given delimiter.

print("myemail@".replaceAfter("@", "gmail.com")); // myemail@gmail.com 

.replaceBefore()

Replace part of string before the first occurrence of given delimiter.

print('@domain.com'.replaceBefore('@', "name")); // "name@domain.com"

.anyChar()

Returns true if at least one element matches the given predicate

'test'.anyChar((c) => c == 't'); // true;
'test'.anyChar((c) => c == 'd'); // false;

.ifEmpty()

If the string is empty perform an action.

"".ifEmpty(() => print("do any action here")); // do any action here

.toDoubleOrNull()

Parses the string as an integer or returns null if it is not a number.

var number = '12345'.toDoubleOrNull(); // 12345  
var notANumber = '123-45'.toDoubleOrNull(); // null  

.limitFromEnd()

Limit the string to a maximum length, taking from the end of the string.

var longString = "0123456789";
var noMoreThanThree = longString.limitFromEnd(3); // "789"

.limitFromStart()

Limit the string to a maximum length, taking from the start of the string.

var longString = "0123456789";
var noMoreThanThree = longString.limitFromStart(3); // "012"

int Extensions

.inRangeOf()

Return the min if this number is smaller then minimum Return the max if this number is bigger the the maximum Return this number if it's between the range

1.inRangeOf(0, 3) // 1 number in range so will return the number
2.inRangeOf(3, 4) // 3 number is smaller then the range so will return min
5.inRangeOf(3, 4) // 4 number is bigger then the range so will return max

Flutter Extensions Full List

Flutter

  • Tooltip
  • algin
  • center
  • container
  • padding
  • navigation
  • Context
  • Text
  • List<Widget>
  • Icon

Http Extensions

  • httpGet
  • httpPost
  • httpPut
  • httpDelete

Iterables Extensions

  • sortBy
  • toMutableSet
  • intersect
  • groupBy
  • find
  • filter
  • filterNot
  • isEmptyOrNull
  • chunks
  • zip
  • half
  • takeOnly
  • drop
  • firstHalf
  • secondHalf
  • swap
  • getRandom
  • firstOrNull
  • firstOrNullWhere
  • firstOrDefault
  • lastOrNull
  • lastOrDefault
  • forEachIndexed
  • sortedDescending
  • containsAll
  • count
  • distinctBy
  • subtract
  • concatWithSingleList
  • concatWithMultipleList
  • associate

Range Extensions

  • until

Strings Extensions

  • validateEmail
  • removeSurrounding
  • isNullOrEmpty
  • replaceAfter
  • replaceBefore
  • orEmpty
  • ifEmpty
  • lastIndex
  • printThis
  • equalsIgnoreCase
  • toDoubleOrNull
  • toIntOrNull
  • anyChar
  • removeAllWhiteSpace
  • isNotBlank
  • toCharArray
  • insert
  • isNullOrWhiteSpace
  • asBool

DateTime Extensions

  • toMilliseconds
  • toSeconds
  • toMinutes
  • toHours
  • toDays
  • isToday
  • addOrRemoveYears
  • addOrRemoveMonth
  • addOrRemoveDay
  • addOrRemoveMinutes
  • addOrRemoveSeconds
  • startOfDay
  • startOfMonth
  • startOfYear
  • operator to add dates
  • operator to subtract dates
  • tomorrow
  • yesterday
  • min
  • max
  • isLeapYear
  • limitFromEnd
  • limitFromStart

Integers Extensions

  • inRangeOf
  • absolute
  • isEven
  • isOdd
  • isPositive
  • isNegative
  • tenth
  • fourth
  • third
  • half
  • doubled
  • tripled
  • quadrupled
  • squared
  • asBool

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add dart_extensions

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  dart_extensions: ^2.2.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:dart_extensions/dart_extensions.dart';

example/lib/main.dart

/*
 * Copyright 2020 Idan Ayalon. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'package:dart_extensions/dart_extensions.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {"/login": (_) => Login()},
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Home(),
      ),
    );
  }
}

class Routes {
  static final login = "/login";
}

class Home extends StatefulWidget {
  
  
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    
    print([1,2,3,4].mapList((f) => f.toDouble()));
    return Scaffold(
      body: Container(
        child: Stack(
          children: <Widget>[
            Container(height: 100, width: 100)
                .withRoundCorners(backgroundColor: Colors.grey)
                .withShadow()
                .alignAtCenter()
                .toCenter()
                .paddingOnly(left: 10)
                .paddingAll(20)
                .onTap(
                  () async {
                    final result = await navigateByRouteName(Routes.login);
                    print(result);
                  },
                )  .withTooltip('just a tooltip')
                .onLongPress(() => print('long press'))

          ],
        ),
      ),
    );
  }
}

class Login extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.grey,
      child: Center(
        child: MaterialButton(
          child: Text('Go Back'),
          onPressed: () => Navigator.pop(context),
        ),
      ),
    );
  }
}

Contributing

If you have read up till here, then 🎉🎉🎉. There are couple of ways in which you can contribute to the growing community of dart_extensions.dart.

  • Propose any feature, enhancement
  • Report a bug
  • Fix a bug
  • Participate in a discussion and help in decision making
  • Write and improve some documentation. Documentation is super critical and its importance cannot be overstated!
  • Send in a Pull Request :-)

Download Details:

Author: Droididan
Source Code: https://github.com/droididan/dart_extensions 
License: BSD-3-Clause license

#flutter #dart #extensions 

Dart_extensions: Extentions for Dart

DocStringExtensions.jl: Extensions for Julia's Docsystem

DocStringExtensions

Extensions for Julia's docsystem.

Installation

The package can be added using the Julia package manager. From the Julia REPL, type ] to enter the Pkg REPL mode and run

pkg> add DocStringExtensions

Documentation

  • STABLEmost recently tagged version of the documentation.
  • LATESTin-development version of the documentation.

Project Status

The package is tested and developed against Julia 0.7 and 1.0 on Linux, OS X, and Windows, but there are versions of the package that works on older versions of Julia.

Contributing and Questions

Contributions are very welcome, as are feature requests and suggestions. Please open an issue if you encounter any problems. If you have a question then feel free to ask for help in the Gitter chat room.

Download Details:

Author: JuliaDocs
Source Code: https://github.com/JuliaDocs/DocStringExtensions.jl 
License: View license

#julia #extensions #string 

DocStringExtensions.jl: Extensions for Julia's Docsystem
Lawson  Wehner

Lawson Wehner

1658963640

Pure_extensions: It Adds Utility Extensions to The Dart Classes

Dart Extensions

Adds several extensions

classDescription
GeoPointDefines a geographical point.
GeoBoundsA latitude/longitude aligned rectangle.
CompositeMapSubscriptionActs as a map for multiple subscriptions that can be canceled at once.
ReadableFileImplement a multi platform interface to be able to read a file.
DurationBuilderBuilder for [Duration]
DateTimeBuilderBuilder for [DateTime]
UriBuilderBuilder for [Uri]

- Color

Extensions color code we thank "TinyColor"

- String

See recase for many other extensions

CommandDescription
ifEmptyif string is empty returns a 'text' otherwise return string
isBlankif string is empty or contains only space returns true otherwise returns false
ifBlank(() => 'text')if string is empty or contains only space returns 'text' otherwise returns string
more methods... please complete this list... 

- num

They are extended with the methods of the 'math' package

- Iterable< T > (BUILT)

See collection for many others extensions

CommandDescription
nullIfEmptyreturns null or if it is empty returns true.
replacesreplace the old elements contained in the map with new ones.
whereNotContainsReturns a iterable without bad elements.
joinByConcatenates the elements given by function.
joinElementConcatenates the elements.
containsEveryChecks whether every element of this iterable is in [other] iterable.
containsAnyChecks whether any element of this iterable is in [other] iterable.
groupBySplits a list into sub-lists stored in an object, based on the result.
generateMapGenerate the map by collection.
elementAtOrNullReturns the [index]th element or null if it not exist.

- Iterable< num/int/double/BigInt/Rational >

See collection for many others extensions

CommandDescription
sumCalculate the sum of all numbers in the collection
averageCalculate the average of all numbers in the collection
subtractCalculate the subtraction of all numbers in the collection
divideCalculate the division of all numbers in the collection
multiplyCalculate the multiplication of all numbers in the collection
sumAllBySum [number] to all items in the collection
subtractAllBySubtract [number] to all items in the collection
divideAllByDivide [number] to all items in the collection
multiplyAllByMultiply [number] to all items in the collection

- Iterable< MapEntry< K, V > > (BUILT)

CommandDescription
toMapConvert the collection of entries into a [Map].
toMapListGrouping the results in list according to key.
keysReturns only the keys.
valuesReturns only the values.

- Iterable< Future< T > >

CommandDescription
waitFuturessame as [Future.wait] method
anyFuturessame as [Future.any] method

- Iterable< GeoPoint >

CommandDescription
centerCalculate a center.
northeastCalculate the northeast corner.
southwestCalculate the southwest corner.
internalBoundsCalculate the internal corners.
externalBoundsCalculate the external corners.

- Map< K, V > (BUILT)

CommandDescription
whereNotNullReturns [Map] without null keys and values.
generateIterable<K, V>(T Function(K key, V value) generator)returns a List from entries
whereReturns a new map with all entries that satisfy [test].
firstWhereReturns the first entry that satisfies [test].
lastWhereReturns the last entry that satisfies [test].
singleWhereReturns the single element that satisfies [test].
firstOrNullReturns the first entry if it exists otherwise null.
lastOrNullReturns the last entry if it exists otherwise null.
singleOrNullReturns the single entry if it exists otherwise null.
reduceReduces a map to a single value by iteratively combining entries.
everyChecks whether every entry of this map satisfies [test].
anyChecks whether any entry of this map satisfies [test].
foldReduces a map to a single value by iteratively combining entries.
getReturns the value [key].
getOrNullReturns the value [key] or null if it not exist.

- DateTime (DateTimeBuilder)

See time for many others extensions

CommandDescription
DateTime.copyWithPosition 

- Duration (DurationBuilder)

See time for many others extensions

CommandDescription
daysHuman days representation (0 -> ...)
hoursHuman hours representation (0 -> 24)
minutesHuman minutes representation (0 -> 59)
secondsHuman seconds representation (0 -> 59)
millisecondsHuman milliseconds representation (0 -> 999)
microsecondsHuman microseconds representation (0 -> 999)
copyWithCopy this with new values
toBuilderConverts this in builder
rebuildUpdate this by [DurationBuilder]

- Stream< T >

CommandDescription
asStreamreturns itself with the [Stream] type.
asBroadcastreturns a broadcast stream without wrapping it unnecessarily.
onTrackedErrorResumeIt is similar to [Rx.OnErrorExtensions.onErrorResume] but with [StackTrace].
onTrackedErrorReturnWithIt is similar to [Rx.OnErrorExtensions.onErrorReturnWith] but with [StackTrace].
distinctRuntimeTypeStream.distinct] by [T.runtimeType].
distinctRuntimeTypeStream.distinct] by [T.runtimeType].
listenValueChangesHear how the specified value changes over time from its previous value.
whereNotNull 

Built

ClassDescription
GeoPointSerializerSerializer for [GeoPoint] Type
RationalSerializerSerializer for the [Rational] type
ByPassSerializerSerializer that does not serialize and deserialize the specified type [T]

- Serializers

CommandDescription
serializeAllSerialize the collection of objects
serializeAllWithSerialize the collection of objects using [Serializer].
deserializeAllDeserialize the collection of objects.
deserializeAllWithDeserialize the collection of objects using [Serializer].

Installing

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add pure_extensions

With Flutter:

 $ flutter pub add pure_extensions

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  pure_extensions: ^4.2.0

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:pure_extensions/pure_extensions.dart';

Author: BreX900
Source Code: https://github.com/BreX900/dart_extensions 
License: MIT

#flutter #dart #extensions 

Pure_extensions: It Adds Utility Extensions to The Dart Classes
Diego  Elizondo

Diego Elizondo

1654277100

4 Extensiones De Google Chrome Que Mejoran Mi Flujo De Trabajo De Code

Si es como yo, es probable que tenga una colección de extensiones de codificación de Google Chrome favoritas que lo ayuden a hacer mejor su trabajo. Con el tiempo, descubrí que estas 4 extensiones de Chrome son especialmente útiles para mi flujo de trabajo de codificación. ¡Lo ayudarán a ser más eficiente, ahorrar tiempo y simplemente brindarle una mejor experiencia de codificación en general!

Puedo animarte a que las revises y te asegures de comentar cuáles son tus extensiones favoritas.

1. YouCode ( You.com )

YouCode es un nuevo tipo de motor de búsqueda creado para desarrolladores. Le permite copiar fragmentos de codificación de StackOverflow, W3 Schools o Geeks for Geeks directamente desde la página de resultados de búsqueda y ver el contenido en los paneles laterales, lo que ha sido un cambio absoluto para mí. YouCode es compatible con más de 20 sitios web de codificación populares (incluidos Github y Towards Data Science) y también tiene un validador JSON y un selector de colores integrados. Esta extensión es un ahorro de tiempo absoluto para mí.

Enlace a la extensión de Chrome:

https://chrome.google.com/webstore/detail/youcom/afiglppdonkdbkkaghbnpklddbemkbpj

2. Desarrollador web

Esta extensión agrega una barra de herramientas completa con varias herramientas de desarrollo web a su navegador y es imprescindible para cualquiera que se dedique al desarrollo web. Mostrar dimensiones div, ver JavaScript, deshabilitar estilos CSS, mostrar atributos alt o ver información de etiquetas meta son solo una pequeña fracción de lo que esta herramienta puede hacer.

Enlace a la extensión:

https://chrome.google.com/webstore/detail/web-developer/bfbameneiokkgbdmiekhjnmfkcnldhhm

3. Cambiar el tamaño de la ventana para desarrolladores

Para asegurarse de que su trabajo se vea bien en todos los tamaños de pantalla, esta extensión le permite cambiar rápidamente entre diferentes resoluciones de pantalla y ver si sus puntos de interrupción de medios funcionan como se espera.

Enlace a la extensión:

https://chrome.google.com/webstore/detail/window-resizer/kkelicaakdanhinjdeammmilcgefonfh/related

4. Wappalizador

Wappalyzer facilita descubrir con qué CRM, marcos, plataformas de comercio electrónico, bibliotecas Javascript, software de servidor, herramientas de análisis, procesadores de pago, herramientas de marketing y más sitios web están construidos. Comprenda mejor cómo funcionan los sitios web y qué tecnologías también podrían ser útiles para su propio trabajo.

Enlace a la extensión:

https://chrome.google.com/webstore/detail/wappalyzer-technology-pro/gppongmhjkpfnbhagpmjfkannfbllamg/related?hl=en

Puedo recomendarle encarecidamente que consulte estas extensiones y espero que pueda encontrar valor usándolas. ¡Me encantaría escuchar tu opinión y asegurarme de compartir tus extensiones favoritas en los comentarios también! 

Esta historia se publicó originalmente en https://hackernoon.com/4-google-chrome-extensions-that-improve-my-coding-workflow

#google-chrome #extensions #coding #workflow 

4 Extensiones De Google Chrome Que Mejoran Mi Flujo De Trabajo De Code

コーディングワークフローを改善する4つのGoogleChrome拡張機能

あなたが私のようなら、あなたはおそらくあなたがあなたの仕事をより良くするのを助けるお気に入りのグーグルクロームコーディング拡張のコレクションを持っているでしょう。時間が経つにつれて、これらの4つのChrome拡張機能がコーディングワークフローに特に役立つことがわかりました。彼らはあなたがより効率的になり、時間を節約し、そしてあなたに全体的に良いコーディング体験を与えるのを助けます!

それらをチェックして、お気に入りの拡張機能についてコメントすることをお勧めします。

1. YouCode(You.com

YouCodeは、開発者向けに構築された新しいタイプの検索エンジンです。StackOverflow、W3 Schools、またはGeeks for Geeksのコーディングスニペットを検索結果ページから直接コピーして、サイドパネルにコンテンツを表示できます。これは、私にとって絶対的なゲームチェンジャーです。YouCodeは、20を超える人気のあるコーディングWebサイト(GithubやTowards Data Scienceを含む)をサポートし、JSONバリデーターとカラーピッカーが組み込まれています。この拡張機能は、私にとって絶対的な時間の節約になります。

Chrome拡張機能へのリンク:

https://chrome.google.com/webstore/detail/youcom/afiglppdonkdbkkaghbnpklddbemkbpj

2.Web開発者

この拡張機能は、さまざまなWeb開発ツールを備えたツールバー全体をブラウザーに追加します。これは、Web開発を行うすべての人にとって必須です。divディメンションの表示、JavaScriptの表示、CSSスタイルの無効化、alt属性の表示、またはメタタグ情報の表示は、このツールで実行できることのほんの一部にすぎません。

拡張機能へのリンク:

https://chrome.google.com/webstore/detail/web-developer/bfbameneiokkgbdmiekhjnmfkcnldhhm

3.開発者向けウィンドウリサイザー

すべての画面サイズで作業が適切に表示されるようにするために、この拡張機能を使用すると、さまざまな画面解像度をすばやく切り替えて、メディアブレークポイントが期待どおりに機能しているかどうかを確認できます。

拡張機能へのリンク:

https://chrome.google.com/webstore/detail/window-resizer/kkelicaakdanhinjdeammmilcgefonfh/related

4.ワッパライザー

Wappalyzerを使用すると、CRM、フレームワーク、eコマースプラットフォーム、Javascriptライブラリ、サーバーソフトウェア、分析ツール、支払い処理業者、マーケティングツール、その他のWebサイトがどのように構築されているかを簡単に見つけることができます。Webサイトがどのように機能するか、およびどのテクノロジーが自分の作業にも役立つ可能性があるかをよりよく理解します。

拡張機能へのリンク:

https://chrome.google.com/webstore/detail/wappalyzer-technology-pro/gppongmhjkpfnbhagpmjfkannfbllamg/related?hl=en

これらの拡張機能をチェックして、それらを使用して価値を見つけることができるようになることを強くお勧めします。私はあなたの意見を聞いて、コメントでもあなたのお気に入りの拡張機能を共有することを忘れないでください! 

このストーリーは、もともとhttps://hackernoon.com/4-google-chrome-extensions-that-improve-my-coding-workflowで公開されました

#google-chrome #extensions #coding #workflow 

コーディングワークフローを改善する4つのGoogleChrome拡張機能
Diego  Elizondo

Diego Elizondo

1654137720

Las 6 Mejores Extensiones De Google Chrome Para Desarrolladores

¡Estas extensiones lo ayudarán a desarrollarse de manera más eficiente y aumentar su nivel de habilidad más rápido!

1. Desarrollador web

Captura de pantalla del autor

Web Developer es una extensión completa con muchas características. Puede cambiar el estilo, buscar CSS, deshabilitar las ejecuciones de JavaScript, habilitar (y modificar) campos de formulario ocultos y mucho más.

Captura de pantalla del autor

2. Tampermonkey

Captura de pantalla del autor

Tampermonkey es una extensión del navegador que le permite personalizar la apariencia y el funcionamiento de las páginas web. Puede usar Tampermonkey para agregar características y funcionalidades a los sitios web o para cambiar la forma en que se ven y se sienten. Hay muchos scripts públicos disponibles para Tampermonkey (como nuevas funciones para GitHub, Game Bots, etc.) y también puede crear los suyos propios.

3. GitHub refinado

Captura de pantalla del autor

GitHub refinado es imprescindible si hace mucho en GitHub. Tiene un total de más de 200 funciones que puede activar o desactivar según sus preferencias personales. Las funciones incluyen la vinculación de referencias de problemas/PR y direcciones URL en el código, hacer que los caracteres de espacio en blanco sean visibles, reducir el tamaño de las pestañas a cuatro espacios, solucionadores de conflictos de combinación con un solo clic, avatares de reacción, un ícono de estado de compilación/CI, un botón para ver la fuente de Archivos Markdown y mucho más.

4. Wappalyzer - Perfilador de tecnología

Captura de pantalla del autor

Wappalyzer es una herramienta que analiza páginas web y te dice qué tecnologías están utilizando. Esto puede ser muy útil si te gusta una característica de un sitio web y quieres saber cómo lo hicieron.

Captura de pantalla del autor

5. Shodan

Captura de pantalla del autor

Shodan.io es un motor de búsqueda para el "Internet de las cosas" (IoT). Su extensión de Chrome muestra dónde está alojado el servidor y sus puertos abiertos.

6. Notificador para GitHub

Esta extensión muestra un pequeño ícono con el número de tus notificaciones de GitHub. Esto es extremadamente útil cuando trabajas con muchos proyectos de código abierto y/o tienes tus propios repositorios en GitHub.

Captura de pantalla del autor

¡Gracias por leer!

Si tiene una extensión que debería estar en esta lista, no dude en poner su nombre en los comentarios :). 

Fuente del artículo original en: https://betterprogramming.pub/top-6-google-chrome-extensions-for-developers-968e22c343dd

#google-chrome  #extensions 

Las 6 Mejores Extensiones De Google Chrome Para Desarrolladores
高橋  花子

高橋 花子

1654137540

開発者向けのトップ6のGoogleChrome拡張機能

これらの拡張機能は、より効率的に開発し、スキルレベルをより速く向上させるのに役立ちます!

1.Web開発者

著者によるスクリーンショット

Web Developerは、多くの機能を備えた万能の拡張機能です。スタイリングの変更、CSSのルックアップ、JavaScriptの実行の無効化、非表示のフォームフィールドの有効化(および変更)などを行うことができます。

著者によるスクリーンショット

2.タンパーモンキー

著者によるスクリーンショット

Tampermonkeyは、Webページの外観と機能をカスタマイズできるブラウザ拡張機能です。Tampermonkeyを使用して、Webサイトに機能を追加したり、Webサイトの外観や雰囲気を変更したりできます。Tampermonkeyで利用できる公開スクリプトは多数あり(GitHub、ゲームボットなどの新機能など)、独自のスクリプトを作成することもできます。

3.洗練されたGitHub

著者によるスクリーンショット

洗練されたGitHubは、GitHubで多くのことを行う場合に必須です。それはあなたがあなたの個人的な好みによってオンまたはオフにすることができる合計200以上の機能を持っています。機能には、コード内の問題/ PR参照とURLのリンク、空白文字の表示、タブのサイズの4つのスペースへの縮小、ワンクリックマージ競合修正プログラム、リアクションアバター、ビルド/ CIステータスアイコン、ソースを表示するボタンが含まれます。マークダウンファイル、その他多数。

4.Wappalyzer-テクノロジープロファイラー

著者によるスクリーンショット

Wappalyzerは、Webページを分析し、それらが使用しているテクノロジーを通知するツールです。これは、Webサイトの機能が好きで、それらがどのように機能したかを知りたい場合に非常に役立ちます。

著者によるスクリーンショット

5.将段

著者によるスクリーンショット

Shodan.ioは、「モノのインターネット」(IoT)の検索エンジンです。Chrome拡張機能は、サーバーがホストされている場所と開いているポートを示します。

6.GitHubの通知機能

この拡張機能は、GitHub通知の番号を示す小さなアイコンを表示します。これは、多くのオープンソースプロジェクトで作業する場合や、GitHubに独自のリポジトリがある場合に非常に役立ちます。

著者によるスクリーンショット

読んでくれてありがとう!

このリストに含めるべき拡張子がある場合は、コメントにその名前を入れてください:)。 

元の記事のソース:https ://betterprogramming.pub/top-6-google-chrome-extensions-for-developers-968e22c343dd

#google-chrome #extensions 

開発者向けのトップ6のGoogleChrome拡張機能
Diego  Elizondo

Diego Elizondo

1653556380

16 Extensiones Útiles Para SwiftUI

A medida que nos acercamos a la WWDC 2022 y posiblemente a la versión 4.0 de SwiftUI, un marco con el que tuve la suerte de haber jugado casi todo el tiempo que existe, pensé que podría publicar una pequeña colección de extensiones que uso una y otra vez. . Espero que algunos de estos lleguen a la próxima versión.

1. Ocultar

Este es un modificador de vista que le permite mostrar u ocultar vistas que normalmente no podría ver. Vale la pena mencionar que un modificador de vista es un patrón muy útil que haría bien en memorizar.

struct Show: ViewModifier {
    let isVisible: Bool

    @ViewBuilder
    func body(content: Content) -> some View {
        if isVisible {
            content
        } else {
            content.hidden()
        }
    }
}

Esto lo usa simplemente como un modificador en su vista, la variable de condición es simplemente un bool.

.modifier(Show(isVisible: condition))

Esto funciona bien, pero como notará, libera espacio en el viewy obliga a volver a dibujar, por lo que afecta el rendimiento. Alternativamente, siempre puede usar la opacitypestaña para obtener un efecto similar. Se ejecutará más rápido pero no liberará el espacio que usó.

2. Sucursal

Este modificador que encontré es una solución perfecta para controlar la inclusión/exclusión de atributos.

extension View {
  @ViewBuilder
  func `if`<Transform: View>(_ condition: Bool, transform: (Self) ->  Transform) -> some View {
    if condition { transform(self) }
    else { self }
  }
}

Código que usa así, nuevamente con una variable allí, coloreada en este ejemplo.

.if(colored) { view in
  view.background(Color.blue)
}

3. Imprimir

Si es nuevo en SwiftUI, una de las primeras cosas que lo atraparán es print. Puede ser el dinosaurio de las técnicas de depuración, pero todavía lo están enseñando en las clases, y es doloroso encontrarse incapaz de usarlo en las vistas de SwiftUI. Por lo tanto, este fragmento de código es invaluable.

extension View {
    func Print(_ vars: Any...) -> some View {
        for v in vars { print(v) }
        return EmptyView()
    }
}

Le permite usar una declaración como esta en su código.

self.Print("Inside ForEach", varOne, varTwo ...)

4. Retraso

Esto acaba de cambiar en iOS15 y, aunque no es SwiftUI per se, definitivamente es algo que te encuentras haciendo dentro de tu código.

extension Task where Success == Never, Failure == Never {
  static func sleep(seconds: Double) async throws {
  let duration = UInt64(seconds * 1000_000_000)
  try await sleep(nanoseconds: duration)
  }
}

Por supuesto, el código que desea ejecutar después del retraso debe seguir el Taskque crea un retraso en sí mismo.

Task { try! await Task.sleep(seconds: 0.5) }

5. Pasar a través de sujetos

Cuando comencé a usar CombineSwiftUI, encontré PassThroughSubjectsuna forma súper útil de vincular lo antiguo con lo nuevo. Escribí un artículo sobre cómo usarlos con compras dentro de la aplicación, pero no son perfectos y con frecuencia disparo más de una vez cuando los envías. Este código puede ayudarlo a detectar ese problema.

let changeColor = PassthroughSubject<Int,Never>()

El código que usas se ve así:

.onReceive(signalButton
  .eraseToAnyPublisher()
  .throttle(for: .milliseconds(10), scheduler: RunLoop.main, latest: true))
{ value in
  if value == 2 {
    button2 = true
    levelColor = Color.red
  }
}

Con la callingrutina, en este caso, el número aquí solía permitirme nombrar un solo tema para poder activar varias ramas en el mismo código de SwiftUI.

changeColor.send(3)

6. Suscripciones

Otra alternativa para iniciar el código, aunque no SwiftUI nuevamente, es un elemento invaluable que utilicé repetidamente dentro de mi código SwiftUI. Lo configuras usando este código:

let cameraGesture = PassthroughSubject<cameraActions,Never>()
var cameraSubscription:AnyCancellable? = nil

combineEntonces se usan dos declaraciones así:

cameraSubscription = cameraGesture
  .eraseToAnyPublisher()
  .throttle(for: .milliseconds(10), scheduler: RunLoop.main, latest: true)
   .sink(receiveValue: { value in   
  // do something with the value                 
})

Enviando un combinemensaje como antes.

cameraGesture.send(._1orbitTurntable)

7. Temporizador

A publisheres una gran manera de crear un temporizador. Encuentro que lo estoy usando en casi todos los proyectos que pienso.

let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

Aquí está el código.

Nota : tengo el valor del tiempo en la _ unusedvariable. Esto, a diferencia de send, funciona de manera más confiable, ya que envía un mensaje, no un montón.

.onReceive(timer) { _ in
  // do something
}

8. Coordenadas/Tamaño

Nunca puedo recordar exactamente cómo quise decir esto, así que aquí hay un ejemplo. También es un poco complicado porque el tamaño que devuelve es el padre, no el hijo en el que lo usas.

struct returnSize: View {
  var body: some View {
  GeometryReader { geometry in
    Color.clear
      .onAppear(perform: {
        print("geo \(geometry.size)")
      })
    }
  }
}

Por lo tanto, normalmente lo usa como una vista de fondo. Aquí se explica cómo devolver el tamaño de la vista con este comando:

.background(returnSize())

9. Cadenas de atributos

Una extensión súper útil que encontré en Stack Overflow; se aplica a los atributos en los Textobjetos de iOS 15.

extension Text {
  init(_ string: String, configure: ((inout AttributedString) -> Void)) {
   var attributedString = AttributedString(string) /// create an `AttributedString`
   configure(&attributedString) 
   self.init(attributedString) 
  }
}

Puede usar los fragmentos anteriores de esta manera:

Text("GAME OVER") { $0.kern = CGFloat(2) }

Con este tipo de parámetros, puede agregar en detalle en este artículo .

10. Cualquier Vista

Lo siguiente es una solución para ese mensaje de SwiftUI que se queja de las vistas que no coinciden. Aunque generalmente desaconsejo el uso AnyViewde , a veces no parece haber otra solución.

extension View {
    func eraseToAnyView() -> AnyView {
        AnyView(self)
    }
}

Aquí hay un ejemplo de una extensión en la que quiero devolver un elemento de texto o una imagen:

struct returnDifferentViews: View {
@State var means:Bool
var body: some View {
  if means {
    return Image("1528")
     .eraseToAnyView()
  } else {
    return Text("1528")
      .eraseToAnyView()
  }
 }
}

11. Subíndice

Esta extensión le permite suscribir una cadena; utiliza un estándar que existe desde hace mucho tiempo

extension String {
  var length: Int {
  return count
}
subscript (i: Int) -> String {
  return self[i ..< i + 1]
}
func substring(fromIndex: Int) -> String {
  return self[min(fromIndex, length) ..< length]
}
func substring(toIndex: Int) -> String {
  return self[0 ..< max(0, toIndex)]
}
subscript (r: Range<Int>) -> String {
  let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
upper: min(length, max(0, r.upperBound))))
  let start = index(startIndex, offsetBy: range.lowerBound)
  let end = index(start, offsetBy: range.upperBound - range.lowerBound)
  return String(self[start ..< end])
  }
}

Puede usar el código como lo haría en otros idiomas.

let word = "Start"
  for i in 0..<word.length {
    print(word[i])
}

12. Detecta un batido

Este código de Google es uno que me encuentro buscando todo el tiempo. ¿Quién puede recordar esta secuencia?

extension NSNotification.Name {
  public static let deviceDidShakeNotification =   NSNotification.Name("MyDeviceDidShakeNotification")
}
extension UIWindow {
  open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
  super.motionEnded(motion, with: event)
  NotificationCenter.default.post(name: .deviceDidShakeNotification, object: event)
}
}
extension View {
  func onShake(perform action: @escaping () -> Void) -> some View {
  self.modifier(ShakeDetector(onShake: action))
  }
}
struct ShakeDetector: ViewModifier {
  let onShake: () -> Void
func body(content: Content) -> some View {
  content
    .onAppear() // this has to be here because of a SwiftUI bug
    .onReceive(NotificationCenter.default.publisher(for:
    .deviceDidShakeNotification)) { _ in
    onShake()
    }
  }
}

Puedes crear una extensión como esta:

.onShake {
  print("stop it shaking")
}

13. Instantánea de una vista

Esta joya proviene del sitio web de HWS ; es una fuente excelente de todas las cosas veloces.

extension View {
    func snapshot() -> UIImage {
        let controller = UIHostingController(rootView: self)
        let view = controller.view

        let targetSize = controller.view.intrinsicContentSize
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .clear

        let renderer = UIGraphicsImageRenderer(size: targetSize)

        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }
    }
}

Puedes usarlo así:

let image = textView.snapshot().ignoresSafeArea

14. Guardar/cargar imágenes

Si encuentra este en el portal de desarrolladores de Apple; viene muy bien

extension URL {
  func loadImage(_ image: inout UIImage) {
  if let loaded = UIImage(contentsOfFile: self.path) {
    image = loaded
  }
}
func saveImage(_ image: UIImage) {
  if let data = image.jpegData(compressionQuality: 1.0) {
    try? data.write(to: self)
    }
  }
}
https://developer.apple.com/forums/thread/661144

En una extensión, puedes usar el código así:

@State private var image = UIImage(systemName: "xmark")!
private var url: URL {  let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)  return paths[0].appendingPathComponent("image.jpg")}var body: some View { 
Image(uiImage: image)  
  .onAppear {   url.load(&image)  }  
  .onTapGesture {   url.save(image)  }
}

15. Lista de fuentes

Casi al final. Este siguiente es útil.

let fontFamilyNames = UIFont.familyNames
for familyName in fontFamilyNames {
  print("Font Family Name = [\(familyName)]")
  let names = UIFont.fontNames(forFamilyName: familyName)
  print("Font Names = [\(names)]")
}

Con el código SwiftUI, puedes encontrar fuentes como esta:

struct Fonts {
  static func avenirNextCondensedBold (size: CGFloat) -> Font {
  return Font.custom("AvenirNextCondensed-Bold", size: size)
}

Llamarás a esta construcción para usar el código:

.font(Fonts.avenirNextCondensedBold(size: 12))

16. Operador Ternario

Esta última extensión se puede usar en muchas áreas de SwiftUI, pero nunca recuerdo la sintaxis.

Aquí, el operador ternario evalúa conditiony

  • si conditiones true, expression1se ejecuta.
  • si conditiones false, expression2se ejecuta.

El operador ternario toma tres operandos ( condition, expression1y expression2). De ahí el nombre de operador ternario.

flipColor = flipColor == .blue ? .green : .blue

Entonces, si flipColores blue, vuelvo green, y si flipColores green, vuelvo blue.

Todo lo cual me lleva al final de esta lista. Espero que hayas encontrado algunos fragmentos útiles aquí.

¡Gracias por leer!

Fuente: https://betterprogramming.pub/16-useful-extensions-for-swiftui-88aae6ff8909

#swiftui #extensions

16 Extensiones Útiles Para SwiftUI
坂本  篤司

坂本 篤司

1653552000

SwiftUIの16の便利な拡張機能

WWDC 2022とおそらくバージョン4.0のSwiftUIに近づくにつれ、私がこれまでずっと使ってきたフレームワークは幸運だったので、何度も使用している拡張機能の小さなコレクションを公開するかもしれないと思いました。 。これらのいくつかが次のリリースに組み込まれることを願っています。

1.非表示

これは、通常は表示できない可能性のあるビューを表示または非表示にできるビュー修飾子です。ビュー修飾子は、メモリにコミットするのに適した非常に便利なパターンであることに言及する価値があります。

struct Show: ViewModifier {
    let isVisible: Bool

    @ViewBuilder
    func body(content: Content) -> some View {
        if isVisible {
            content
        } else {
            content.hidden()
        }
    }
}

これは、ビューの修飾子として単純に使用します。条件変数は単純にブール値です。

.modifier(Show(isVisible: condition))

これはうまく機能しますが、お気づきのように、はスペースを解放しview、再描画を強制します。そのため、パフォーマンスが低下します。または、いつでもopacityタブを使用して同様の効果を得ることができます。実行速度は速くなりますが、使用したスペースが解放されることはありません。

2.ブランチ

私が出会ったこの修飾子は、属性の包含/除外を制御するための完璧なソリューションです。

extension View {
  @ViewBuilder
  func `if`<Transform: View>(_ condition: Bool, transform: (Self) ->  Transform) -> some View {
    if condition { transform(self) }
    else { self }
  }
}

このように使用するコードは、この例では色付きの変数が含まれています。

.if(colored) { view in
  view.background(Color.blue)
}

3.印刷

SwiftUIを初めて使用する場合、最初に気付くのはですprint。それはデバッグ技術の恐竜かもしれませんが、彼らはまだクラスでそれを教えており、SwiftUIビューでそれを使用できないことに気付くのは苦痛です。したがって、このコードスニペットは非常に貴重です。

extension View {
    func Print(_ vars: Any...) -> some View {
        for v in vars { print(v) }
        return EmptyView()
    }
}

これにより、コードでこのようなステートメントを使用できます。

self.Print("Inside ForEach", varOne, varTwo ...)

4.遅延

これはiOS15で変更されたばかりであり、SwiftUI自体ではありませんが、コード内で実行していることは間違いありません。

extension Task where Success == Never, Failure == Never {
  static func sleep(seconds: Double) async throws {
  let duration = UInt64(seconds * 1000_000_000)
  try await sleep(nanoseconds: duration)
  }
}

もちろん、遅延後に実行するコードTaskは、遅延自体を作成するコードに従う必要があります。

Task { try! await Task.sleep(seconds: 0.5) }

5. PassThruSubjects

CombineSwiftUIを使い始めたときPassThroughSubjects、古いものと新しいものをリンクする非常に便利な方法を見つけました。アプリ内購入での使用についての記事を書きましたが、完璧ではなく、送信するときに何度も起動することがよくあります。このコードは、その問題を見つけるのに役立ちます。

let changeColor = PassthroughSubject<Int,Never>()

使用するコードは次のようになります。

.onReceive(signalButton
  .eraseToAnyPublisher()
  .throttle(for: .milliseconds(10), scheduler: RunLoop.main, latest: true))
{ value in
  if value == 2 {
    button2 = true
    levelColor = Color.red
  }
}

ルーチンではcalling、この場合、同じSwiftUIコードで複数のブランチをトリガーできるように、ここでの番号を使用して1つのサブジェクトに名前を付けました。

changeColor.send(3)

6.サブスクリプション

コードを開始するもう1つの方法は、SwiftUIではありませんが、SwiftUIコード内で繰り返し使用した非常に貴重な要素です。次のコードを使用して設定します。

let cameraGesture = PassthroughSubject<cameraActions,Never>()
var cameraSubscription:AnyCancellable? = nil

次に、次のように2つのcombine宣言が使用されます。

cameraSubscription = cameraGesture
  .eraseToAnyPublisher()
  .throttle(for: .milliseconds(10), scheduler: RunLoop.main, latest: true)
   .sink(receiveValue: { value in   
  // do something with the value                 
})

combine以前と同じようにメッセージを送信します。

cameraGesture.send(._1orbitTurntable)

7.タイマー

Apublisherはタイマーを作成するための優れた方法です。私が考えるほとんどすべてのプロジェクトでそれを使用していることがわかります。

let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

これがコードです。

:変数に時間値があり_ unusedます。これは、とは異なり、send大量ではなく1つのメッセージを送信するため、より確実に機能します。

.onReceive(timer) { _ in
  // do something
}

8.座標/サイズ

これがどういう意味だったのかよく思い出せないので、ここに例を示します。また、返されるサイズは親であり、使用する子ではないため、少し注意が必要です。

struct returnSize: View {
  var body: some View {
  GeometryReader { geometry in
    Color.clear
      .onAppear(perform: {
        print("geo \(geometry.size)")
      })
    }
  }
}

したがって、通常は背景ビューとして使用します。このコマンドを使用してビューのサイズを返す方法は次のとおりです。

.background(returnSize())

9.属性文字列

StackOverflowで見つけた非常に便利な拡張機能。iOS15のTextオブジェクトの属性に適用されます。

extension Text {
  init(_ string: String, configure: ((inout AttributedString) -> Void)) {
   var attributedString = AttributedString(string) /// create an `AttributedString`
   configure(&attributedString) 
   self.init(attributedString) 
  }
}

上記のスニペットは次のように使用できます。

Text("GAME OVER") { $0.kern = CGFloat(2) }

これらの種類のパラメーターを使用して、この記事で詳細に追加できます。

10. AnyView

次は、一致しないビューについて不平を言うそのSwiftUIメッセージの修正です。私は通常、を使用するAnyViewことをお勧めしませんが、他の解決策がないように見える場合もあります。

extension View {
    func eraseToAnyView() -> AnyView {
        AnyView(self)
    }
}

テキストアイテムまたは画像を返したい拡張機能の例を次に示します。

struct returnDifferentViews: View {
@State var means:Bool
var body: some View {
  if means {
    return Image("1528")
     .eraseToAnyView()
  } else {
    return Text("1528")
      .eraseToAnyView()
  }
 }
}

11.下付き文字

この拡張機能を使用すると、文字列に添え字を付けることができます。古くからある規格を採用しています

extension String {
  var length: Int {
  return count
}
subscript (i: Int) -> String {
  return self[i ..< i + 1]
}
func substring(fromIndex: Int) -> String {
  return self[min(fromIndex, length) ..< length]
}
func substring(toIndex: Int) -> String {
  return self[0 ..< max(0, toIndex)]
}
subscript (r: Range<Int>) -> String {
  let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
upper: min(length, max(0, r.upperBound))))
  let start = index(startIndex, offsetBy: range.lowerBound)
  let end = index(start, offsetBy: range.upperBound - range.lowerBound)
  return String(self[start ..< end])
  }
}

他の言語と同じようにコードを使用できます。

let word = "Start"
  for i in 0..<word.length {
    print(word[i])
}

12.揺れを検出します

このGoogleコードは、私がいつも調べているものです。誰がこのシーケンスを覚えていますか?

extension NSNotification.Name {
  public static let deviceDidShakeNotification =   NSNotification.Name("MyDeviceDidShakeNotification")
}
extension UIWindow {
  open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
  super.motionEnded(motion, with: event)
  NotificationCenter.default.post(name: .deviceDidShakeNotification, object: event)
}
}
extension View {
  func onShake(perform action: @escaping () -> Void) -> some View {
  self.modifier(ShakeDetector(onShake: action))
  }
}
struct ShakeDetector: ViewModifier {
  let onShake: () -> Void
func body(content: Content) -> some View {
  content
    .onAppear() // this has to be here because of a SwiftUI bug
    .onReceive(NotificationCenter.default.publisher(for:
    .deviceDidShakeNotification)) { _ in
    onShake()
    }
  }
}

次のような拡張機能を作成できます。

.onShake {
  print("stop it shaking")
}

13.ビューのスナップショット

この宝石はHWSのウェブサイトから来ています。それは迅速なすべてのものの優れた情報源です。

extension View {
    func snapshot() -> UIImage {
        let controller = UIHostingController(rootView: self)
        let view = controller.view

        let targetSize = controller.view.intrinsicContentSize
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .clear

        let renderer = UIGraphicsImageRenderer(size: targetSize)

        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }
    }
}

次のように使用できます。

let image = textView.snapshot().ignoresSafeArea

14.画像の保存/読み込み

これがAppleDevelopersポータルで見つかった場合。重宝します。

extension URL {
  func loadImage(_ image: inout UIImage) {
  if let loaded = UIImage(contentsOfFile: self.path) {
    image = loaded
  }
}
func saveImage(_ image: UIImage) {
  if let data = image.jpegData(compressionQuality: 1.0) {
    try? data.write(to: self)
    }
  }
}
https://developer.apple.com/forums/thread/661144

拡張機能では、次のようなコードを使用できます。

@State private var image = UIImage(systemName: "xmark")!
private var url: URL {  let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)  return paths[0].appendingPathComponent("image.jpg")}var body: some View { 
Image(uiImage: image)  
  .onAppear {   url.load(&image)  }  
  .onTapGesture {   url.save(image)  }
}

15.フォントの一覧表示

ほぼ終わりです。この次のものは便利です。

let fontFamilyNames = UIFont.familyNames
for familyName in fontFamilyNames {
  print("Font Family Name = [\(familyName)]")
  let names = UIFont.fontNames(forFamilyName: familyName)
  print("Font Names = [\(names)]")
}

SwiftUIコードを使用すると、次のようなフォントを見つけることができます。

struct Fonts {
  static func avenirNextCondensedBold (size: CGFloat) -> Font {
  return Font.custom("AvenirNextCondensed-Bold", size: size)
}

このコンストラクトを呼び出して、コードを使用します。

.font(Fonts.avenirNextCondensedBold(size: 12))

16.三項演算子

この最後の拡張機能はSwiftUIの多くの領域で使用できますが、構文を思い出せません。

ここで、三項演算子は評価conditionし、

  • の場合、conditionが実行されます。trueexpression1
  • の場合、conditionが実行されます。falseexpression2

三項演算子は、3つのオペランド(、、、conditionおよびexpression1)を取りますexpression2。したがって、名前の三項演算子。

flipColor = flipColor == .blue ? .green : .blue

したがって、の場合flipColorblue戻りgreen、の場合flipColorgreen戻りblueます。

これらすべてが私をこのリストの最後に導きます。ここで便利なスニペットを見つけていただければ幸いです。

読んでくれてありがとう!

ソース:https ://betterprogramming.pub/16-useful-extensions-for-swiftui-88aae6ff8909

#swiftui #extensions

SwiftUIの16の便利な拡張機能
Hunter  Krajcik

Hunter Krajcik

1653223680

Xcontext: Predictable Static Extension Methods on BuildContext

xcontext

This simple package adds static extension methods and getters to the BuildContext context object from the widgets, material, and cupertino libraries.

xcontext makes it easy for you to add static extensions methods and getters to your context from Flutter's widgets, material, and cupertino libraries. You have total control over which methods and getters you want to add to your context, with all the type safety guarantees Dart provides, while keeping your code concise and clean.

Important links

About this package

This package is an experiment to get rid of the SomeClass.of(context).someMethod calls in a codebase. The package also simplifies other function calls that require the context to be passed in.

Using the package will hopefully make your code easier to type, read and understand.

I wrote the package in a way that is easy to customize to your needs and selectively add or hide extensions.

If you like the .of static methods, please feel free to continue using it!

Usage

// Add all methods and getters to BuildContext
import 'package:xcontext/xcontext.dart';

BuildContext context;
// then...
context.navigator.pushNamed('/other');
context.scaffold;
context.mediaQuery.platformBrightness;
context.theme;
context.dividerTheme;
context.cupertinoLocalizations;
context.cupertinoTheme;
context.showCupertinoDialog(builder: b, useRootNavigator: true); // Don't forget to define the builder.
context.showTimePicker(initialTime: TimeOfDay.now());

If you prefer to be even more concise, use the "tiny" version:

// tiny_xcontext uses shorter names and does not add all getters
import 'package:xcontext/tiny_xcontext.dart';

BuildContext context;
// then...
context.nav.pushNamed('/other');
context.scaf;
context.mq.platformBrightness;
context.theme; // Not all getters are shortened. Theme is short enough already
// context.dividerTheme; // Not all getters are available in "tiny" mode
context.cupL10n;
context.cuptheme;
context.showCupDialog(builder: builder, useRootNavigator: true); // Don't forget to define the builder.
context.showTP(initialTime: TimeOfDay.now());

The libraries of this package

// Add all methods and getters to BuildContext
import 'package:xcontext/xcontext.dart';

// Alternatively, if you want to extend only from some libraries:
import 'package:xcontext/cupertino.dart';
import 'package:xcontext/material.dart';
import 'package:xcontext/widgets.dart';

// Add some methods and getters to BuildContext, some are shortened
import 'package:xcontext/tiny_xcontext.dart';

// Alternatively, if you want to extend only from some libraries with the short version
import 'package:xcontext/tiny_cupertino.dart';
import 'package:xcontext/tiny_material.dart';
import 'package:xcontext/tiny_widgets.dart';

See all libraries: xcontext, cupertino, material, widgets, tiny_xcontext, tiny_cupertino, tiny_material, tiny_widgets

From Navigator.of(context) to context.navigator

The xcontext package lets you access Something.of(context).someMethod directly on the context as context.something.someMethod. It adds all the .of static methods from the official widgets, material, and cupertino libraries' return value as getters.

So after you imported 'package:xcontext/xcontext.dart', you will be able to write:

import 'package:xcontext/xcontext.dart';

class Example extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Instead of Theme.of(context), just write: 
    final theme = context.theme;
    // ...and use the theme as usual:
    print('Current brightness is ${theme.brightness}');
    return RaisedButton(
      onPressed: () {
        // Instead of Navigator.of(context), use context.navigator
        context.navigator.pushNamed('/other');
      },
      child: Text('Navigator push'),
    );
  }
}

In case the .of static method accepts extra parameters, those values are exposed in a different getter, such as:

// Navigator.of(context, rootNavigator: true)
context.rootNavigator;
// Theme.of(this, shadowThemeOnly: true);
context.shadowTheme;

Show this, show that!

All showXYZ (date and time pickers, modal bottom sheet, about dialog) methods are added, as well, so now you can write:

import 'package:xcontext/xcontext.dart';

context.showAboutDialog(
  applicationName: 'xcontext example app',
  applicationIcon: FlutterLogo(),
  applicationLegalese: 'Copyright 2020',
  applicationVersion: '1.2.3',
  children: [
    Text('Thank you for using this package!'),
    Text('❤️'),
  ],
);

hide/show

While the extensions might improve the discoverability, seeing tens of extra methods popping up in your IDE whenever you type "context." can be annoying. For this reason, every getter and method is added as a separate extension, so you can hide or show them as you like.

/*** hide ***/
// If one or more extensions annoy you, hide them.
import 'package:xcontext/material.dart' hide XContextNavigationRailTheme;

/*** show ***/
// If you only need some extensions, show them, and hide all others.
// Only show context.navigator and context.rootNavigator
import 'package:xcontext/widgets.dart' show XContextNavigator, XContextRootNavigator;

export only what you need

You might conclude that, while using some extensions from the package is great, the other extensions are less great, so you want see only a subset of the extensions everywhere.

Just create a new your_favorite_extensions.dart file , export the extensions you like, and import this file in the rest of your codebase to stay consistent.

// your_favorite_extensions.dart
export 'package:xcontext/xcontext.dart'
    show XContextShowGeneralDialog,  // context.showGeneralDialog
         XContextNavigator, // context.navigator
         XContextRootNavigator, // context.rootNavigator
         XContextScaffold,  // context.scaffold
         XContextMediaQuery; // context.mediaQuery

// You may even write your own context extensions here.
// Some other file...
import 'package:your_awesome_app/your_favorite_extensions.dart';

The tiny variation

This package also has a tiny variation of the extensions. The tiny version is great is you prefer brevity. 'package:xcontext/tiny_xcontext.dart' does not include all the possible getters and methods, and some getters were renamed so that you can write less code while keeping everything straightforward:

import 'package:xcontext/tiny_xcontext.dart';

// then...
context.nav.pop();
final isLight = context.mq.platformBrightness == Brightness.light;

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add xcontext

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  xcontext: ^1.0.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:xcontext/xcontext.dart';

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:xcontext/xcontext.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('xcontext'),
        ),
        body: Example(),
      ),
    );
  }
}

class Example extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final TextDirection textDirection = context.textDirection;
    print('Text direction: $textDirection}');
    return Wrap(
      children: [
        for (final button in [
          ElevatedButton(
            onPressed: () {
              context.showDatePicker(
                initialDate: DateTime.now(),
                firstDate: DateTime.now(),
                lastDate: DateTime.now().add(Duration(days: 7)),
              );
            },
            child: Text('Date picker'),
          ),
          ElevatedButton(
            onPressed: () {
              context.navigator
                  .push(MaterialPageRoute(builder: (_) => ExampleRoute()));
            },
            child: Text('Navigator push'),
          ),
          ElevatedButton(
            onPressed: () {
              context.showModalBottomSheet(
                builder: (_) => BottomSheet(
                  builder: (_) => Padding(
                    padding: const EdgeInsets.all(28.0),
                    child: Popper(),
                  ),
                  onClosing: () {},
                ),
              );
            },
            child: Text('Show Modal Bottom Sheet'),
          ),
          ElevatedButton(
            onPressed: () {
              final time = context.showTimePicker(initialTime: TimeOfDay.now());
              print('selected time is $time');
            },
            child: Text('Show Time Picker'),
          ),
          ElevatedButton(
            onPressed: () {
              context.showAboutDialog(
                applicationName: 'xcontext example app',
                applicationIcon: FlutterLogo(),
                applicationLegalese: 'Copyright 2020',
                applicationVersion: '1.2.3',
                children: [
                  Text('Thank you for using this package!'),
                  Text('❤️'),
                ],
              );
            },
            child: Text('Show About Dialog'),
          ),
        ])
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            child: button,
          )
      ],
    );
  }
}

class ExampleRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Popper(),
      ),
    );
  }
}

class Popper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        context.navigator.pop();
      },
      child: Text('pop!'),
    );
  }
}

Author: Dartsidedev
Source Code: https://github.com/dartsidedev/xcontext 
License: BSD-3-Clause license

#dart #flutter #extensions 

Xcontext: Predictable Static Extension Methods on BuildContext

Mimemagic: Pure Go Ultra Performant MIME Sniffing Library/utility

mimemagic

Powerful and versatile MIME sniffing package using pre-compiled glob patterns, magic number signatures, xml document namespaces, and tree magic for mounted volumes, generated from the XDG shared-mime-info database.

Features

  • All in native go, no outside dependencies/C library bindings
  • 1003 MIME types, with a description, an acronym (where available), common aliases, extensions, icons, and subclasses
  • 493 magic signature tests (comprising of 1147 individual patterns), featuring range searches and bit masks, as per the xdg specification
  • 1099 glob patterns, for filename-based matching
  • 11 Tree Magic signatures and 28 XML namespace/local name pairs, offered for completeness' sake.
  • Included is the xml file parser to generate your own MIME definitions
  • Also included is a CLI based on this library that is fully featured and blazing-fast, beating the native 'file' and KDE's 'kmimetypefinder' in performance
  • Cross-platform support

Installation

The library:

go get github.com/zRedShift/mimemagic/v2

The CLI:

go get github.com/zRedShift/mimemagic/v2/cmd/mimemagic

API

See the Godoc reference, and cmd/mimemagic for an example implementation.

Usage

The library:

package main

import (
    "fmt"
    "github.com/zRedShift/mimemagic/v2"
    "strings"
)

func main() {
    // Ignoring Read errors that might arise
    mimeType, _ := mimemagic.MatchFilePath("sample.svgz", -1)

    // image/svg+xml-compressed
    fmt.Println(mimeType.MediaType())

    // compressed SVG image
    fmt.Println(mimeType.Comment)

    // SVG (Scalable Vector Graphics)
    fmt.Printf("%s (%s)\n", mimeType.Acronym, mimeType.ExpandedAcronym)

    // application/gzip
    fmt.Println(strings.Join(mimeType.SubClassOf, ", "))

    // .svgz
    fmt.Println(strings.Join(mimeType.Extensions, ", "))

    // This is an image.
    switch mimeType.Media {
    case "image":
        fmt.Println("This is an image.")
    case "video":
        fmt.Println("This is a video file.")
    case "audio":
        fmt.Println("This is an audio file.")
    case "application":
        fmt.Println("This is an application.")
    default:
        fmt.Printf("This is a(n) %s.", mimeType.Media)
    }

    // true
    fmt.Println(mimeType.IsExtension(".svgz"))
}

The CLI:

Usage: mimemagic [options] <file> ...
Determines the MIME type of the given file(s).

Options:
  -c    Determine the MIME type of the file(s) using only its content.
  -f    Determine the MIME type of the file(s) using only the file name. Does
        not check for the file's existence. The -c
         flag takes precedence.
  -i    Output the MIME type in a human readable format.
  -l int
        The number of bytes from the beginning of the file mimemagic will
        examine. Reads the entire file if set to a negative value. By default
        mimemagic will only read the first 512 from stdin, however setting this
        flag to a non-default negative value will override this. (default -1)
  -t    Determine the MIME type of the directory/mounted volume using tree
        magic. Can't be used in conjunction with with -c, -f or -x.
  -x    Determine the MIME type of the xml file(s) using the local names and
        namespaces within. Can't be used in conjunction with -c, -f or -t.

Arguments:
  file
        The file(s) to test. '-' to read from stdin. If '-' is set, all other
        inputs will be ignored.

Examples:
  $ mimemagic -c sample.svgz
        application/gzip
  $ mimemagic *.svg*
        Olympic_rings_with_transparent_rims.svg: image/svg+xml
        Piano.svg.png: image/png
        RAID_5.svg: image/svg+xml
        sample.svgz: image/svg+xml-compressed
  $ cat /dev/urandom | mimemagic -
        application/octet-stream
  $ ls software; mimemagic -i -t software/
        autorun
        UNIX software

Benchmarks

See Benchmarks. For Match(), the average across over 400 completely different files (representing a unique MIME type each) is 13 ± 7 μs/op. For MatchGlob() it's 900 ± 200 ns/op, and for 12 ± 7 μs/op MatchMagic().

Author: zRedShift
Source Code: https://github.com/zRedShift/mimemagic 
License: GPL-2.0 license

#go #golang #extensions 

Mimemagic: Pure Go Ultra Performant MIME Sniffing Library/utility
Elian  Harber

Elian Harber

1652970840

Filetype: Fast, Dependency-free Go Package to infer Binary File

filetype 

Small and dependency free Go package to infer file and MIME type checking the magic numbers signature.

For SVG file type checking, see go-is-svg package. Python port: filetype.py.

Features

  • Supports a wide range of file types
  • Provides file extension and proper MIME type
  • File discovery by extension or MIME type
  • File discovery by class (image, video, audio...)
  • Provides a bunch of helpers and file matching shortcuts
  • Pluggable: add custom new types and matchers
  • Simple and semantic API
  • Blazing fast, even processing large files
  • Only first 262 bytes representing the max file header is required, so you can just pass a slice
  • Dependency free (just Go code, no C compilation needed)
  • Cross-platform file recognition

Installation

go get github.com/h2non/filetype

API

See Godoc reference.

Subpackages

Examples

Simple file type checking

package main

import (
  "fmt"
  "io/ioutil"

  "github.com/h2non/filetype"
)

func main() {
  buf, _ := ioutil.ReadFile("sample.jpg")

  kind, _ := filetype.Match(buf)
  if kind == filetype.Unknown {
    fmt.Println("Unknown file type")
    return
  }

  fmt.Printf("File type: %s. MIME: %s\n", kind.Extension, kind.MIME.Value)
}

Check type class

package main

import (
  "fmt"
  "io/ioutil"

  "github.com/h2non/filetype"
)

func main() {
  buf, _ := ioutil.ReadFile("sample.jpg")

  if filetype.IsImage(buf) {
    fmt.Println("File is an image")
  } else {
    fmt.Println("Not an image")
  }
}

Supported type

package main

import (
  "fmt"

  "github.com/h2non/filetype"
)

func main() {
  // Check if file is supported by extension
  if filetype.IsSupported("jpg") {
    fmt.Println("Extension supported")
  } else {
    fmt.Println("Extension not supported")
  }

  // Check if file is supported by extension
  if filetype.IsMIMESupported("image/jpeg") {
    fmt.Println("MIME type supported")
  } else {
    fmt.Println("MIME type not supported")
  }
}

File header

package main

import (
  "fmt"
  "io/ioutil"

  "github.com/h2non/filetype"
)

func main() {
  // Open a file descriptor
  file, _ := os.Open("movie.mp4")

  // We only have to pass the file header = first 261 bytes
  head := make([]byte, 261)
  file.Read(head)

  if filetype.IsImage(head) {
    fmt.Println("File is an image")
  } else {
    fmt.Println("Not an image")
  }
}

Add additional file type matchers

package main

import (
  "fmt"

  "github.com/h2non/filetype"
)

var fooType = filetype.NewType("foo", "foo/foo")

func fooMatcher(buf []byte) bool {
  return len(buf) > 1 && buf[0] == 0x01 && buf[1] == 0x02
}

func main() {
  // Register the new matcher and its type
  filetype.AddMatcher(fooType, fooMatcher)

  // Check if the new type is supported by extension
  if filetype.IsSupported("foo") {
    fmt.Println("New supported type: foo")
  }

  // Check if the new type is supported by MIME
  if filetype.IsMIMESupported("foo/foo") {
    fmt.Println("New supported MIME type: foo/foo")
  }

  // Try to match the file
  fooFile := []byte{0x01, 0x02}
  kind, _ := filetype.Match(fooFile)
  if kind == filetype.Unknown {
    fmt.Println("Unknown file type")
  } else {
    fmt.Printf("File type matched: %s\n", kind.Extension)
  }
}

Supported types

Image

  • jpg - image/jpeg
  • png - image/png
  • gif - image/gif
  • webp - image/webp
  • cr2 - image/x-canon-cr2
  • tif - image/tiff
  • bmp - image/bmp
  • heif - image/heif
  • jxr - image/vnd.ms-photo
  • psd - image/vnd.adobe.photoshop
  • ico - image/vnd.microsoft.icon
  • dwg - image/vnd.dwg

Video

  • mp4 - video/mp4
  • m4v - video/x-m4v
  • mkv - video/x-matroska
  • webm - video/webm
  • mov - video/quicktime
  • avi - video/x-msvideo
  • wmv - video/x-ms-wmv
  • mpg - video/mpeg
  • flv - video/x-flv
  • 3gp - video/3gpp

Audio

  • mid - audio/midi
  • mp3 - audio/mpeg
  • m4a - audio/mp4
  • ogg - audio/ogg
  • flac - audio/x-flac
  • wav - audio/x-wav
  • amr - audio/amr
  • aac - audio/aac
  • aiff - audio/x-aiff

Archive

  • epub - application/epub+zip
  • zip - application/zip
  • tar - application/x-tar
  • rar - application/vnd.rar
  • gz - application/gzip
  • bz2 - application/x-bzip2
  • 7z - application/x-7z-compressed
  • xz - application/x-xz
  • zstd - application/zstd
  • pdf - application/pdf
  • exe - application/vnd.microsoft.portable-executable
  • swf - application/x-shockwave-flash
  • rtf - application/rtf
  • iso - application/x-iso9660-image
  • eot - application/octet-stream
  • ps - application/postscript
  • sqlite - application/vnd.sqlite3
  • nes - application/x-nintendo-nes-rom
  • crx - application/x-google-chrome-extension
  • cab - application/vnd.ms-cab-compressed
  • deb - application/vnd.debian.binary-package
  • ar - application/x-unix-archive
  • Z - application/x-compress
  • lz - application/x-lzip
  • rpm - application/x-rpm
  • elf - application/x-executable
  • dcm - application/dicom

Documents

  • doc - application/msword
  • docx - application/vnd.openxmlformats-officedocument.wordprocessingml.document
  • xls - application/vnd.ms-excel
  • xlsx - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
  • ppt - application/vnd.ms-powerpoint
  • pptx - application/vnd.openxmlformats-officedocument.presentationml.presentation

Font

  • woff - application/font-woff
  • woff2 - application/font-woff
  • ttf - application/font-sfnt
  • otf - application/font-sfnt

Application

  • wasm - application/wasm
  • dex - application/vnd.android.dex
  • dey - application/vnd.android.dey

Benchmarks

Measured using real files.

Environment: OSX x64 i7 2.7 Ghz

BenchmarkMatchTar-8    1000000        1083 ns/op
BenchmarkMatchZip-8    1000000        1162 ns/op
BenchmarkMatchJpeg-8   1000000        1280 ns/op
BenchmarkMatchGif-8    1000000        1315 ns/op
BenchmarkMatchPng-8    1000000        1121 ns/op

Author: H2non
Source Code: https://github.com/h2non/filetype 
License: MIT license

#go #golang #extensions 

Filetype: Fast, Dependency-free Go Package to infer Binary File

3 Simple Ways to Connect Gumroad with WordPress Site

Are you looking for an easy solution to connect your Gumroad Page to your WordPress Site? Don’t look any further! In this blog, we will show you the top 3 simple ways to connect Gumroad with the WordPress site. But first, for those who are unfamiliar with Gumroad, let us define it simply.

Gumroad is a platform where virtually anyone can sell almost anything. The process is pleasantly simple and transparent, with none of the headaches associated with some of the more popular platforms.

There are more than 98,994 creators who have sold their works on this platform for over $500 million. These creators work in a variety of fields, including education, IT, music, sports, and comedy. On Gumroad, even dance and theater fans can find a home.

Read more… 👇😊

 

#wordpress #woocommerce #extensions #opensource #plugin #wordpressplugins #gumroad

3 Simple Ways to Connect Gumroad with WordPress Site