Lawrence  Lesch

Lawrence Lesch

1664480460

Twit: Twitter API Client for Node (REST & Streaming API)

Twit

Twitter API Client for node

Supports both the REST and Streaming API.

Installing

npm install twit

Usage:

var Twit = require('twit')

var T = new Twit({
  consumer_key:         '...',
  consumer_secret:      '...',
  access_token:         '...',
  access_token_secret:  '...',
  timeout_ms:           60*1000,  // optional HTTP request timeout to apply to all requests.
  strictSSL:            true,     // optional - requires SSL certificates to be valid.
})

//
//  tweet 'hello world!'
//
T.post('statuses/update', { status: 'hello world!' }, function(err, data, response) {
  console.log(data)
})

//
//  search twitter for all tweets containing the word 'banana' since July 11, 2011
//
T.get('search/tweets', { q: 'banana since:2011-07-11', count: 100 }, function(err, data, response) {
  console.log(data)
})

//
//  get the list of user id's that follow @tolga_tezel
//
T.get('followers/ids', { screen_name: 'tolga_tezel' },  function (err, data, response) {
  console.log(data)
})

//
// Twit has promise support; you can use the callback API,
// promise API, or both at the same time.
//
T.get('account/verify_credentials', { skip_status: true })
  .catch(function (err) {
    console.log('caught error', err.stack)
  })
  .then(function (result) {
    // `result` is an Object with keys "data" and "resp".
    // `data` and `resp` are the same objects as the ones passed
    // to the callback.
    // See https://github.com/ttezel/twit#tgetpath-params-callback
    // for details.

    console.log('data', result.data);
  })

//
//  retweet a tweet with id '343360866131001345'
//
T.post('statuses/retweet/:id', { id: '343360866131001345' }, function (err, data, response) {
  console.log(data)
})

//
//  destroy a tweet with id '343360866131001345'
//
T.post('statuses/destroy/:id', { id: '343360866131001345' }, function (err, data, response) {
  console.log(data)
})

//
// get `funny` twitter users
//
T.get('users/suggestions/:slug', { slug: 'funny' }, function (err, data, response) {
  console.log(data)
})

//
// post a tweet with media
//
var b64content = fs.readFileSync('/path/to/img', { encoding: 'base64' })

// first we must post the media to Twitter
T.post('media/upload', { media_data: b64content }, function (err, data, response) {
  // now we can assign alt text to the media, for use by screen readers and
  // other text-based presentations and interpreters
  var mediaIdStr = data.media_id_string
  var altText = "Small flowers in a planter on a sunny balcony, blossoming."
  var meta_params = { media_id: mediaIdStr, alt_text: { text: altText } }

  T.post('media/metadata/create', meta_params, function (err, data, response) {
    if (!err) {
      // now we can reference the media and post a tweet (media will attach to the tweet)
      var params = { status: 'loving life #nofilter', media_ids: [mediaIdStr] }

      T.post('statuses/update', params, function (err, data, response) {
        console.log(data)
      })
    }
  })
})

//
// post media via the chunked media upload API.
// You can then use POST statuses/update to post a tweet with the media attached as in the example above using `media_id_string`.
// Note: You can also do this yourself manually using T.post() calls if you want more fine-grained
// control over the streaming. Example: https://github.com/ttezel/twit/blob/master/tests/rest_chunked_upload.js#L20
//
var filePath = '/absolute/path/to/file.mp4'
T.postMediaChunked({ file_path: filePath }, function (err, data, response) {
  console.log(data)
})

//
//  stream a sample of public statuses
//
var stream = T.stream('statuses/sample')

stream.on('tweet', function (tweet) {
  console.log(tweet)
})

//
//  filter the twitter public stream by the word 'mango'.
//
var stream = T.stream('statuses/filter', { track: 'mango' })

stream.on('tweet', function (tweet) {
  console.log(tweet)
})

//
// filter the public stream by the latitude/longitude bounded box of San Francisco
//
var sanFrancisco = [ '-122.75', '36.8', '-121.75', '37.8' ]

var stream = T.stream('statuses/filter', { locations: sanFrancisco })

stream.on('tweet', function (tweet) {
  console.log(tweet)
})

//
// filter the public stream by english tweets containing `#apple`
//
var stream = T.stream('statuses/filter', { track: '#apple', language: 'en' })

stream.on('tweet', function (tweet) {
  console.log(tweet)
})

twit API:

var T = new Twit(config)

Create a Twit instance that can be used to make requests to Twitter's APIs.

If authenticating with user context, config should be an object of the form:

{
    consumer_key:         '...'
  , consumer_secret:      '...'
  , access_token:         '...'
  , access_token_secret:  '...'
}

If authenticating with application context, config should be an object of the form:

{
    consumer_key:         '...'
  , consumer_secret:      '...'
  , app_only_auth:        true
}

Note that Application-only auth will not allow you to perform requests to API endpoints requiring a user context, such as posting tweets. However, the endpoints available can have a higher rate limit.

T.get(path, [params], callback)

GET any of the REST API endpoints.

path

The endpoint to hit. When specifying path values, omit the '.json' at the end (i.e. use 'search/tweets' instead of 'search/tweets.json').

params

(Optional) parameters for the request.

callback

function (err, data, response)

  • data is the parsed data received from Twitter.
  • response is the [http.IncomingMessage](http://nodejs.org/api/http.html# http_http_incomingmessage) received from Twitter.

T.post(path, [params], callback)

POST any of the REST API endpoints. Same usage as T.get().

T.postMediaChunked(params, callback)

Helper function to post media via the POST media/upload (chunked) API. params is an object containing a file_path key. file_path is the absolute path to the file you want to upload.

var filePath = '/absolute/path/to/file.mp4'
T.postMediaChunked({ file_path: filePath }, function (err, data, response) {
  console.log(data)
})

You can also use the POST media/upload API via T.post() calls if you want more fine-grained control over the streaming; [see here for an example](https://github.com/ttezel/twit/blob/master/tests/rest_chunked_upload.js# L20).

T.getAuth()

Get the client's authentication tokens.

T.setAuth(tokens)

Update the client's authentication tokens.

T.stream(path, [params])

Use this with the Streaming API.

path

Streaming endpoint to hit. One of:

  • 'statuses/filter'
  • 'statuses/sample'
  • 'statuses/firehose'
  • 'user'
  • 'site'

For a description of each Streaming endpoint, see the Twitter API docs.

params

(Optional) parameters for the request. Any Arrays passed in params get converted to comma-separated strings, allowing you to do requests like:

//
// I only want to see tweets about my favorite fruits
//

// same result as doing { track: 'bananas,oranges,strawberries' }
var stream = T.stream('statuses/filter', { track: ['bananas', 'oranges', 'strawberries'] })

stream.on('tweet', function (tweet) {
  //...
})

Using the Streaming API

T.stream(path, [params]) keeps the connection alive, and returns an EventEmitter.

The following events are emitted:

event: 'message'

Emitted each time an object is received in the stream. This is a catch-all event that can be used to process any data received in the stream, rather than using the more specific events documented below. New in version 2.1.0.

stream.on('message', function (msg) {
  //...
})

event: 'tweet'

Emitted each time a status (tweet) comes into the stream.

stream.on('tweet', function (tweet) {
  //...
})

event: 'delete'

Emitted each time a status (tweet) deletion message comes into the stream.

stream.on('delete', function (deleteMessage) {
  //...
})

event: 'limit'

Emitted each time a limitation message comes into the stream.

stream.on('limit', function (limitMessage) {
  //...
})

event: 'scrub_geo'

Emitted each time a location deletion message comes into the stream.

stream.on('scrub_geo', function (scrubGeoMessage) {
  //...
})

event: 'disconnect'

Emitted when a disconnect message comes from Twitter. This occurs if you have multiple streams connected to Twitter's API. Upon receiving a disconnect message from Twitter, Twit will close the connection and emit this event with the message details received from twitter.

stream.on('disconnect', function (disconnectMessage) {
  //...
})

event: 'connect'

Emitted when a connection attempt is made to Twitter. The http request object is emitted.

stream.on('connect', function (request) {
  //...
})

event: 'connected'

Emitted when the response is received from Twitter. The http response object is emitted.

stream.on('connected', function (response) {
  //...
})

event: 'reconnect'

Emitted when a reconnection attempt to Twitter is scheduled. If Twitter is having problems or we get rate limited, we schedule a reconnect according to Twitter's reconnection guidelines. The last http request and response objects are emitted, along with the time (in milliseconds) left before the reconnect occurs.

stream.on('reconnect', function (request, response, connectInterval) {
  //...
})

event: 'warning'

This message is appropriate for clients using high-bandwidth connections, like the firehose. If your connection is falling behind, Twitter will queue messages for you, until your queue fills up, at which point they will disconnect you.

stream.on('warning', function (warning) {
  //...
})

event: 'status_withheld'

Emitted when Twitter sends back a status_withheld message in the stream. This means that a tweet was withheld in certain countries.

stream.on('status_withheld', function (withheldMsg) {
  //...
})

event: 'user_withheld'

Emitted when Twitter sends back a user_withheld message in the stream. This means that a Twitter user was withheld in certain countries.

stream.on('user_withheld', function (withheldMsg) {
  //...
})

event: 'friends'

Emitted when Twitter sends the ["friends" preamble](https://dev.twitter.com/streaming/overview/messages-types# user_stream_messsages) when connecting to a user stream. This message contains a list of the user's friends, represented as an array of user ids. If the stringify_friend_ids parameter is set, the friends list preamble will be returned as Strings (instead of Numbers).

var stream = T.stream('user', { stringify_friend_ids: true })
stream.on('friends', function (friendsMsg) {
  //...
})

event: 'direct_message'

Emitted when a direct message is sent to the user. Unfortunately, Twitter has not documented this event for user streams.

stream.on('direct_message', function (directMsg) {
  //...
})

event: 'user_event'

Emitted when Twitter sends back a User stream event. See the Twitter docs for more information on each event's structure.

stream.on('user_event', function (eventMsg) {
  //...
})

In addition, the following user stream events are provided for you to listen on:

  • blocked
  • unblocked
  • favorite
  • unfavorite
  • follow
  • unfollow
  • mute
  • unmute
  • user_update
  • list_created
  • list_destroyed
  • list_updated
  • list_member_added
  • list_member_removed
  • list_user_subscribed
  • list_user_unsubscribed
  • quoted_tweet
  • retweeted_retweet
  • favorited_retweet
  • unknown_user_event (for an event that doesn't match any of the above)

Example:

stream.on('favorite', function (event) {
  //...
})

event: 'error'

Emitted when an API request or response error occurs. An Error object is emitted, with properties:

{
  message:      '...',  // error message
  statusCode:   '...',  // statusCode from Twitter
  code:         '...',  // error code from Twitter
  twitterReply: '...',  // raw response data from Twitter
  allErrors:    '...'   // array of errors returned from Twitter
}

stream.stop()

Call this function on the stream to stop streaming (closes the connection with Twitter).

stream.start()

Call this function to restart the stream after you called .stop() on it. Note: there is no need to call .start() to begin streaming. Twit.stream calls .start() for you.


What do I have access to?

Anything in the Twitter API:


Go here to create an app and get OAuth credentials (if you haven't already): https://apps.twitter.com/app/new

Advanced

You may specify an array of trusted certificate fingerprints if you want to only trust a specific set of certificates. When an HTTP response is received, it is verified that the certificate was signed, and the peer certificate's fingerprint must be one of the values you specified. By default, the node.js trusted "root" CAs will be used.

eg.

var twit = new Twit({
  consumer_key:         '...',
  consumer_secret:      '...',
  access_token:         '...',
  access_token_secret:  '...',
  trusted_cert_fingerprints: [
    '66:EA:47:62:D9:B1:4F:1A:AE:89:5F:68:BA:6B:8E:BB:F8:1D:BF:8E',
  ]
})

Contributing

  • Make your changes
  • Make sure your code matches the style of the code around it
  • Add tests that cover your feature/bugfix
  • Run tests
  • Submit a pull request

How do I run the tests?

Create two files: config1.js and config2.js at the root of the twit folder. They should contain two different sets of oauth credentials for twit to use (two accounts are needed for testing interactions). They should both look something like this:

module.exports = {
    consumer_key: '...'
  , consumer_secret: '...'
  , access_token: '...'
  , access_token_secret: '...'
}

Then run the tests:

npm test

You can also run the example:

node examples/rtd2.js

iRTD2

The example is a twitter bot named RTD2 written using twit. RTD2 tweets about github and curates its social graph.


FAQ


License

(The MIT License)

Copyright (c) by Tolga Tezel tolgatezel11@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Changelog

2.2.11

  • Fix media_category used for media uploads (thanks @BooDoo)

2.2.10

  • Update maximum Tweet characters to 280 (thanks @maziyarpanahi)
  • For streaming requests, use request body for sending params (thanks @raine)
  • Fix getBearerToken endpoint (thanks @williamcoates)
  • Shared Parameter Feature For Media Upload (thanks @haroonabbasi)
  • Don't include params in path for jsonpayload paths (thanks @egtoney)
  • Add support for strictSSL request option (thanks @zdoc01)

2.2.9

  • Use JSON payload in request body for new DM endpoints.

2.2.8

  • Add support for HTTP DELETE; you can now T.delete(...).

2.2.7

  • Don't attempt to reconnect to Twitter API when receiving HTTP status code 413 - request entity too large.

2.2.6

  • Fix zlib error when streaming

2.2.4

  • Fix 401 Unauthorized error on streaming connection reconnect after not being connected for some time (eg. due to > 1min loss of network).

2.2.2

  • Emit parser-error instead of error event if Twitter sends back an uncompressed HTTP response body.

2.2.1

  • Add promise support to Twit REST API calls.

2.2.0

  • Allow omission of new keyword; var t = Twit(config) works, and var t = new Twit(config) works too.
  • Allow setting an array of trusted certificate fingerprints via config.trusted_cert_fingerprints.
  • Automatically adjust timestamp for OAuth'ed HTTP requests by recording the timestamp from Twitter HTTP responses, computing our local time offset, and applying the offset in the next HTTP request to Twitter.

2.1.7

  • Add mime as a dependency.

2.1.6

  • Emit friends event for friends_str message received when a user stream is requested with stringify_friend_ids=true.
  • Handle receiving "Exceeded connection limit for user" message from Twitter while streaming. Emit error event for this case.
  • Emit retweeted_retweet and favorited_retweet user events.
  • Add MIT license to package.json (about time!)

2.1.5

  • Support config-based request timeout.

2.1.4

  • Support POST media/upload (chunked) and add T.postMediaChunked() to make it easy.

2.1.3

  • Fix bug in constructing HTTP requests for account/update_profile_image and account/update_profile_background_image paths.

2.1.2

  • Enable gzip on network traffic
  • Add quoted_tweet event

2.1.1

  • Strict-mode fixes (Twit can now be run with strict mode)
  • Fix handling of disconect message from Twitter
  • If Twitter returns a non-JSON-parseable fragment during streaming, emit 'parser-error' instead of 'error' (to discard fragments like "Internal Server Error")

2.1.0

  • Add message event.

2.0.0

  • Implement Application-only auth
  • Remove oauth module as a dependency

1.1.20

  • Implement support for POST /media/upload
  • Reconnect logic fix for streaming; add stall abort/reconnect timeout on first connection attempt.

1.1.14

  • Emit connected event upon receiving the response from twitter

1.0.0

  • now to stop and start the stream, use stream.stop() and stream.start() instead of emitting the start and stop events
  • If twitter sends a disconnect message, closes the stream and emits disconnect with the disconnect message received from twitter

0.2.0

  • Updated twit for usage with v1.1 of the Twitter API.

0.1.5

  • BREAKING CHANGE to twit.stream(). Does not take a callback anymore. It returns immediately with the EventEmitter that you can listen on. The Usage section in the Readme.md has been updated. Read it.

0.1.4

  • twit.stream() has signature function (path, params, callback)

Download Details:

Author: ttezel
Source Code: https://github.com/ttezel/twit 

#javascript #twitter #api #client #node 

Twit: Twitter API Client for Node (REST & Streaming API)
Lawrence  Lesch

Lawrence Lesch

1664464320

PDFmake: Client/server Side PDF Printing in Pure JavaScript

pdfmake 

PDF document generation library for server-side and client-side in pure JavaScript.

Features

  • line-wrapping,
  • text-alignments (left, right, centered, justified),
  • numbered and bulleted lists,
  • tables and columns
    • auto/fixed/star-sized widths,
    • col-spans and row-spans,
    • headers automatically repeated in case of a page-break,
  • images and vector graphics,
  • convenient styling and style inheritance,
  • page headers and footers:
    • static or dynamic content,
    • access to current page number and page count,
  • background-layer,
  • page dimensions and orientations,
  • margins,
  • custom page breaks,
  • font embedding,
  • support for complex, multi-level (nested) structures,
  • table of contents,
  • helper methods for opening/printing/downloading the generated PDF,
  • setting of PDF metadata (e.g. author, subject).

Building from sources

using npm:

git clone https://github.com/bpampuch/pdfmake.git
cd pdfmake
npm install
npm run build

using yarn:

git clone https://github.com/bpampuch/pdfmake.git
cd pdfmake
yarn
yarn run build

Documentation

Documentation URL: https://pdfmake.github.io/docs/

Source of documentation: https://github.com/pdfmake/docs Improvements are welcome!


Check out the playground and examples.

This is unstable master branch for version 0.3.x, for stable use version 0.2.x see branch 0.2 or older version 0.1.x see branch 0.1.


Download Details:

Author: bpampuch
Source Code: https://github.com/bpampuch/pdfmake 
License: View license

#javascript #pdf #make #client #server 

PDFmake: Client/server Side PDF Printing in Pure JavaScript
Lawrence  Lesch

Lawrence Lesch

1664338680

Spacebro-client: Easily Share Event Between Application

Spacebro client

🌟 Connect easily to a spacebro server.

🌍 Installation

yarn add spacebro-client
# or
npm i -S spacebro-client

πŸ‘‹ Usage

First, you need to start a spacebro server.

$ npm i -g spacebro # or yarn global add spacebro
$ spacebro

Then, write the following client code:

const { SpacebroClient } = require('spacebro-client')

const client = new SpacebroClient({
  host: '127.0.0.1',
  port: 36000,
  channelName: 'bar',
  client: {
    name: 'foo',
    description: "a foo tool",
    in: {
      inFoo: {
        eventName: "inFoo",
        description: "Input foo",
        type: "all"
      }
    },
    out: {
      outBar: {
        eventName: "outBar",
        description: "Output bar",
        type: "all"
      }
    }
  },
  connection: "bar/outBar => bar/inFoo"
})

client.on('inFoo', (data) => console.log('inFoo', data))
client.emit('outBar', { do: stuff})

The connection string was sent to the spacebro server, that will then connects every event named outBar from client bar to a new event named inFoo sent to client bar

πŸš€ API

class SpacebroClient([options], [connect])

Look for a server, and return a handle to the connection.

// For more details about possible options, see below.
const client = new SpacebroClient({
  host: '127.0.0.1',
  port: 8888,
  client: {name: 'foo'},
  channelName: 'bar'
})

options:

namedefaultrequireddescription
host-requiredThe spacebro server's address. Ignored if connect is false.
port-requiredThe spacebro server's address. Ignored if connect is false.
client.namenullrecommendedYour client's name. Can be useful to perform targeted events and for monitoring.
channelNamenullrecommendedThe channel your app will communicate in. This is especially usefull if you have multiple apps using the same server.
verbosetrueoptionalShould spacebro-client display logs (connection / emission / reception)?
sendBacktrueoptionalShould this client receive the events it sent?

connect

If the connect parameter is false, then the options are saved and a disconnected handle is returned; you have to call its connect method later before you can emit or receive events.

Default value: true

const client = new SpacebroClient({
  client: {name: 'myClient'},
  channelName: 'someChannel'
}, false)

// ...

client.connect('127.0.0.1', 8888)

create([options])

Look for a server, and creates a handle to the connection. Takes the same options as new SpacebroClient. Returns a Promise like client.connect.

setDefaultSettings(options, [verbose])

Overwrite the default options of new SpacebroClient with the given options.

If standard-settings is installed in your module, spacebro-client will call this function with the contents of services.spacebro from your settings file.

client.connect(address, port)

Look for a server, and connect client to this server. Returns a Promise that resolves to client when the connection is established, or throws an error if the connection fails.

client.emit(eventName[, data])

Broadcast a specific event to all the clients in the channel. data must be a JSON object.

client.sendTo(eventName, target[, data])

Send an event to a specific target in the channel. data must be a JSON object.

client.on(eventName, handler)

Listen to a specific event.

client.once(eventName, handler)

Listen to a specific event only once.

client.off(eventName)

Remove a specific event listener.

client.disconnect()

Close the connection.

Socket.io callbacks (acknowledgments)

Spacebro now works with acknowlegdments too !

const { SpacebroClient } = require('spacebro-client')

const client = new SpacebroClient({
  host: '127.0.0.1',
  port: 36000,
  channelName: 'bar',
  client: {
    name: 'foo',
    description: "a foo tool",
    in: {
      inFoo: {
        eventName: "inFoo",
        description: "Input foo",
        type: "all"
      }
    },
    out: {
      outBar: {
        eventName: "outBar",
        description: "Output bar",
        type: "all"
      }
    }
  },
  connection: "bar/outBar => bar/inFoo"
})

client.on('inFoo', (data, fn) => {
  console.log('inFoo', data)
  fn('thank you')
})

client.emit('outBar', { do: stuff}, function (data) {
  console.log('Received from callback: ' + data)
})

πŸ–₯ Browser

You can use spacebro-client in the browser. You will need the following dependencies:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.0/socket.io.js"></script>
<script src="https://wzrd.in/standalone/socketio-wildcard@latest"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-signals/1.0.0/js-signals.min.js"></script>

After adding these dependencies, you can include the spacebro-client lib like any script:

<script src="./dist/spacebro-client.js"></script>

Then use the window.spacebroClient object.

βš› Electron

Spacebro-client also works in Electron. You just require('spacebro-client') in your electron main process and use ipc or web-contents to forward events to the renderer process.

From the example/electron/ folder of this repository:

// In the main process.
const { app, BrowserWindow } = require('electron')
const { SpacebroClient } = require('../../dist/spacebro-client')

let win = null

const client = new SpacebroClient({
  host: '127.0.0.1',
  port: 8888,
  client: {name: 'foo'},
  channelName: 'bar'
})

app.on('ready', () => {
  win = new BrowserWindow({ width: 800, height: 600 })
  win.loadURL(`file://${__dirname}/index.html`)

  for (const eventName of ['hello', 'world']) {
    client.on(eventName, (data) => {
      win.webContents.send(eventName, data)
    })
  }

  win.webContents.on('did-finish-load', () => {
    setTimeout(() => { client.emit('hello', { hello: 'world' }) }, 3000)
    setTimeout(() => { client.emit('world', { world: 'hello' }) }, 5000)
  })
})
<!-- index.html -->
<html>
<body>
  <script>
    require('electron').ipcRenderer.on('hello', (event, message) => {
      console.log(message)
    })
    require('electron').ipcRenderer.on('world', (event, message) => {
      console.log(message)
    })
  </script>
</body>
</html>

Examples

You can find many real life examples in the example/ folder of this repository.

πŸ•³ Troubleshooting

newClient event πŸ‘‹

The Spacebro server automatically broadcasts a newClient event when a client connects. Thus, you should avoid using that event name. See the example/simple-node script for more details.

Using native modules in Electron πŸŒ€

If you want to use spacebro-client in an Electron app, you'll have to use electron-rebuild in order to rebuild MDNS according to the version of Node.js embedded with Electron.

Use the following commands:

$ npm i --save-dev electron-rebuild # or yarn
$ ./node_modules/.bin/electron-rebuild # call the executable every time you add a new native module

You can also add "rebuild": "./node_modules/.bin/electron-rebuild" to your package.json and run npm run rebuild for convenience.

source

yarn and node-gyp issue (i.e not compiling) πŸ€–

You need to use at least yarn version 0.17.8. You might have similar problems with outdated versions of npm, simply try to update it.

source

https

If the spacebro server is on https, use following settings:

  'service': {
    'spacebro': {
      'host': 'https://example.com'
      'port': 0
    }
  }

subdir on server

If the server url is something like https://example.com/subdir. You can use this url as host. Spacebro will process subdir as a path, contrary to socket.io that would process subdir as a namespace.

That means the requested urls will look like https://example.com/subdir/?EIO=3&transport=polling&sid=<id>

ping pong πŸ“

Do not try to test with 'ping' and 'pong' events, those are reserved.

- `ping`. Fired when a ping packet is written out to the server.
- `pong`. Fired when a pong is received from the server.

source

❀️ Contribute

Please follow Standard JS conventions.

The package has lint testing and unit testing baked-in. Please use npm run test to run both sets of tests before making a pull request. Use npm run build to transpile the project.

The project's release versions are named after stars in Andromeda . The current version is named Sirrah.

Enjoy !

Download Details:

Author: Spacebro
Source Code: https://github.com/spacebro/spacebro-client 
License: MIT license

#javascript #client #websocket #socket #realtime 

Spacebro-client: Easily Share Event Between Application
Royce  Reinger

Royce Reinger

1662604440

6 Popular React Client Markdown Rendering Libraries

In today's post we will learn about 6 Popular React Client Markdown Rendering Libraries.

Markdown is a lightweight markup language for creating formatted text using a plain-text editor. It’s a common way of creating and formatting dynamic rich text content on a website, blog, or an e-commerce platform.

A Markdown file is saved with a .md or .markdown extension, and examples of Markdown usage include writing a readme.md file for a Github repository and adding new article content in a content management system (CMS).

1 - React-markdown

Markdown component for React

Install

This package is ESM only. In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm:

npm install react-markdown

In Deno with esm.sh:

import ReactMarkdown from 'https://esm.sh/react-markdown@7'

In browsers with esm.sh:

<script type="module">
  import ReactMarkdown from 'https://esm.sh/react-markdown@7?bundle'
</script>

Use

A basic hello world:

import React from 'react'
import ReactMarkdown from 'react-markdown'
import ReactDom from 'react-dom'

ReactDom.render(<ReactMarkdown># Hello, *world*!</ReactMarkdown>, document.body)

View on Github

2 - React-markdown-editor-lite

A light-weight Markdown editor based on React

Install

npm install react-markdown-editor-lite --save
# or
yarn add react-markdown-editor-lite

Basic usage

Following steps:

  • Import react-markdown-editor-lite
  • Register plugins if required
  • Initialize a markdown parser, such as markdown-it
  • Start usage
// import react, react-markdown-editor-lite, and a markdown parser you like
import React from 'react';
import * as ReactDOM from 'react-dom';
import MarkdownIt from 'markdown-it';
import MdEditor from 'react-markdown-editor-lite';
// import style manually
import 'react-markdown-editor-lite/lib/index.css';

// Register plugins if required
// MdEditor.use(YOUR_PLUGINS_HERE);

// Initialize a markdown parser
const mdParser = new MarkdownIt(/* Markdown-it options */);

// Finish!
function handleEditorChange({ html, text }) {
  console.log('handleEditorChange', html, text);
}
export default props => {
  return (
    <MdEditor style={{ height: '500px' }} renderHTML={text => mdParser.render(text)} onChange={handleEditorChange} />
  );
};

View on Github

3 - Commonmark-react-renderer

React renderer for CommonMark (rationalized Markdown)

Installing

npm install --save commonmark-react-renderer

Basic usage

var CommonMark = require('commonmark');
var ReactRenderer = require('commonmark-react-renderer');

var parser = new CommonMark.Parser();
var renderer = new ReactRenderer();

var input = '# This is a header\n\nAnd this is a paragraph';
var ast = parser.parse(input);
var result = renderer.render(ast);

// `result`:
[
    <h1>This is a header</h1>,
    <p>And this is a paragraph</p>
]

View on Github

4 - React-remarkable

A React component for rendering Markdown with remarkable

npm install --save react-remarkable

Usage

var React = require('react');
var Markdown = require('react-remarkable');

var MyComponent = React.createClass({

  render() {
    return (
      <div>
        {/* Pass Markdown source to the `source` prop */}
        <Markdown source="**Markdown is awesome!**" />

        {/* Or pass it as children */}
        {/* You can nest React components, too */}
        <Markdown>{`
          ## Reasons React is great

          1. Server-side rendering
          2. This totally works:

          <SomeOtherAmazingComponent />

          Pretty neat!
        `}</Markdown>
      </div>
    );
  }

});

View on Github

5 - React-markdown-renderer

Simple React component that renders Markdown

Installing

npm install react-markdown-renderer --save

Basic Usage

import React from 'react';
import ReactDOM from 'react-dom';
import MarkdownRenderer from 'react-markdown-renderer';

const markdown = '# This is a H1  \n## This is a H2  \n###### This is a H6';

ReactDOM.render(
  <MarkdownRenderer markdown={markdown} />,
  document.getElementById('content')
);

View on Github

6 - React-markings

Markdown in components, components in markdown

Embed React components inside your markdown (in any paragraph position) like this:

import * as React from 'react';
import md from 'react-markings';

function Example() {
  return (
    <pre>
      <code>...</code>
    </pre>
  );
}

export default function ReadMe() {
  return md`
    # react-markings

    > Markdown in components, components in markdown

    - Allows you to write markdown using [commonmark.js](https://github.com/commonmark/commonmark.js)
    - Renders markdown as React elements using [commonmark-react-renderer](https://github.com/rexxars/commonmark-react-renderer)
    - Embed React components inside your markdown (in any paragraph position) like this:

    ${<Example/>}
  `;
}

View on Github

Thank you for following this article. 

#react #client #markdown 

6 Popular React Client Markdown Rendering Libraries
Mike  Kozey

Mike Kozey

1661930220

Provide a quick way to publish & consume messages on Mercure

The features

Provide a quick way to consume messages on Mercure.

Consuming messages

import 'package:mercure_client/mercure_client.dart';

main() async {
  final Mercure mercure = Mercure(
    url: 'http://example.com/.well-known/mercure', // your mercure hub url
    topics: ['/books/{id}'], // your mercure topics
    token: 'your_jwt_token', // Bearer authorization
    lastEventId: 'last_event_id', // in case your stored last recieved event
  );

  final subscription = mercure.listen((event) {
    print(event.data);
  });
}

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add mercure_client

With Flutter:

 $ flutter pub add mercure_client

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

dependencies:
  mercure_client: ^1.1.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:mercure_client/mercure_client.dart';

example/lib/main.dart

import 'dart:io';

import 'package:example/src/presentation/app/app.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

void main() {
  HttpOverrides.runWithHttpOverrides(
    () => runApp(const ProviderScope(child: MercureChat())),
    HandshakeOverride(),
  );
}

class HandshakeOverride extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)
      ..badCertificateCallback = (cert, host, port) => true;
  }
}

Download Details:

Author: HerveGuigoz
Source Code: https://github.com/herveGuigoz/mercure_client 
License: MIT license

#flutter #dart #client 

Provide a quick way to publish & consume messages on Mercure

InfluxFlux: Minimal Julia InfluxDB Client Based on V2 API and Flux QL

InfluxFlux

A simple Julia client to access InfluxDB based on the Flux query language.

Only supports read access

Install

] add https://github.com/tallakt/InfluxFlux#main

Usage

using Dates
using InfluxFlux

api_key = "...."
srv = influx_server("https://some.influxdb.endpoint.influxdata.com", "some@organization.com", api_token)

# raw query to string
raw = flux(srv, "buckets()") |> String

# raw query to dataframe, note only one table supported
table = flux_to_dataframe(srv, """
  from(bucket: "example-bucket")
    |> range(start: -1d)
    |> filter(fn: (r) => r._field == "foo")
    |> group(columns: ["sensorID"])
    |> mean()
  """)

# get all data for a measurement as a DataFrame
dataframe1 = measurement(srv, "example_bucket", "sensors", now(UTC) - Hour(1), now())

# get measurements with a reduced sample rate 1 minute
dataframe2 = aggregate_measurement(srv, "example_bucket", "sensors", now(UTC) - Hour(1), now(), Minute(1))

Download Details:

Author: Tallakt
Source Code: https://github.com/tallakt/InfluxFlux 
License: MIT license

#julia #influxdb #client 

InfluxFlux: Minimal Julia InfluxDB Client Based on V2 API and Flux QL

Redis.jl: Pure Julia Implementation Of A Redis Client

Redis.jl

Pure Julia implementation of a Redis client, largely based on redis-py.

Usage

using Redis
client = redis(host="localhost", port=6379, db=0)

# server info commands
info(client)
info(client, "clients")
ping(client)
dbsize(client)
time(client)
save(client)
bgrewriteaof(client)
bgsave(client)
echo(client, "Hello!")
flushall(client)
flushdb(client)

# basic key commands
set(client, "pi", 3.14)
exists(client, "pi")
get(client, "pi")
restore(client, "picopy", dump(client, "pi"))
append(client, "pi", 159)
incr(client, "one")
decr(client, "one")
del(client, "one")

# many more to come...

Please refer to test/test_{lists, sets, hashes}.jl for documentation on list, set, and hash operations.

Download Details:

Author: Msainz
Source Code: https://github.com/msainz/Redis.jl 
License: View license

#julia #client #redis 

Redis.jl: Pure Julia Implementation Of A Redis Client

Accumulo.jl: Apache Accumulo Client

Accumulo.jl

Apache Accumulo is a database based on Google’s BigTable

Accumulo.jl is a client library for Apache Accumulo, built using the Accumulo Thrift Proxy API.

Connecting

To connect to the server, create an instance of AccumuloSession.

session = AccumuloSession()

Without any parameters, this attempts to connect to a server running on localhost port 42424. A remote server can be connected to by specifying the hostname and port number.

session = AccumuloSession("localhost", 42424)

As of now only SASL-Plain authentication is supported, without any qop. The default implementation authenticates with the same user-id as that of the login shell. That can be overridden by providing an appropriate instance of AccumuloAuth.

session = AccumuloSession("localhost", 42424, AccumuloAuthSASLPlain("uid", "pwd", "zid"))

The thrift TCompactProtocol is used by default, which is also the default for the server setup. Other protocols can be used by specifying the optional named parameter tprotocol. As of now, :binary and :compact protocols are supported.

session = AccumuloSession("localhost", 10000; tprotocol=:compact)

Tables

All tables in a setup can be listed with a call to tables(session).

Existence of a particular table can be checked with table_exists(session, tablename)

Row/column identifiers and cell data are treated as raw bytes. Any type that can be converted to bytes can be used wherever row/column identifiers or values are expected in the APIs. Since Julia already includes this convert method for strings, they can be used as it is. Any other type can also get the same treatment by defining either of the following two methods:

  • convert(Vector{UInt8}, r)
  • bytes(r)

Creating / Deleting

A table can be created, deleted or renamed by calling the corresponding function passing the table name.

table_create(session, tablename; versioning=true, logical_timestamp=false)
table_delete(session, tablename)
table_rename(session, tablename)

By default, tables are configured to use the VersioningIterator and keep one version. The version policy can be changed by changing the VersioningIterator options with the table_config! function.

Using logical timestamps ensures timestamps always move forward. Though the actual millisecond time will not be used anymore, with this, tablet servers need not be time synchronized pefectly and multile updates at the same millisecond do not cause any issue.

Cloning

A table can be cloned with:

table_clone(session, tablename, newtablename; flush=true, 
            set_properties=Dict(), exclude_properties=())

If the flush option is not enabled, then any data the source table currently has in memory will not exist in the clone. A cloned table copies the configuration of the source table. However the permissions of the source table are not copied to the clone. After a clone is created, only the user that created the clone can read and write to it.

Configuration

To get or set table specific properties:

table_config(session, tablename)
table_config!(session, tablename, property::AbstractString, value::AbstractString)

table_versions! changes the number of versions the VersioningIterator keeps.

table_versions!(session, tablename, nversions::Integer)

table_du prints how much space, in bytes, is used by files referenced by a table. When multiple tables are specified it prints how much space, in bytes, is used by files shared between tables, if any.

table_du(session, tables::AbstractString...)

Constraints

Constraints are applied on mutations at insert time and only those that satify them are allowed. Constraints must be implemented as a Java class and included in Accumulo classpath.

# list constraints as a map of the class name and an integer ID
constraints(session, tablename)

# add and remove constraints
add_constraints(session, tablename, names::AbstractString...)
remove_constraints(session, tablename, ids::Integer...)

Splits

Tablets constituting a table are automatically split based on a size threshold configurable per table. Tablets can also be manually split or merged through the following APIs to tweak performance. Split points are specified as row values.

# list current splits (upto max_splits)
table_splits(session, tablename, max_splits=1024)

# manually split / merge tablets
table_split(session, tablename, splits...)
table_merge(session, tablename, start_split, end_split)

Exporting / Importing

Tables can be moved across clusters by exporting them from the source, copying them via the hadoop distcp command, and importing them at the destination. Exporting and importing tables preserves the tables configuration, splits, and logical time.

table_export(session, tablename, export_dir::AbstractString)
table_import(session, tablename, import_dir::AbstractString)

Table must be kept offline during an export while discp runs (to prevent files from being deleted). A table can be cloned and the clone taken offline to be able to access the table during an export.

table_offline(session, tablename; wait=true)
table_online(session, tablename; wait=true)

Iterators

Iterators are executed by Accumulo while scanning or compacting tables. They are a way of doing distributed operations on tables. Iterators must be implemented as a Java class and included in Accumulo classpath. They can be configured to be used during scanning or compaction events. The IteratorScope enum lists allowed scopes.

# list all iterators as a dict of class name and the scopes registered
iters(session, tablename)

# retrieve a single matching iterator with its setting
iter(session, tablename, itername::AbstractString, scope::Integer)

The below APIs allow configuring iterators for a table.

# create an iterator setting
iter(name, class, priority::Integer, properties::Dict=Dict())

# verify whether the iterator settings will be valid when applied on a table
check_iter(session, tablename, iter_setting::IteratorSetting, scopes)

# add or remote iterators configured on a table
add_iter(session, tablename, iter_setting::IteratorSetting, scopes; check=true)
remove_iter(session, tablename, iter_setting::IteratorSetting, scopes)
remove_iter(session, tablename, iter_name::AbstractString, scopes)

Writing

Data is written to tables as batches of updates.

# initialize a batch
updates = batch()

# add mutations to the batch
update(updates, row, col_family, col_qualifier, col_visibility, value, timestamp::Integer=time_ms())
delete(updates, row, col_family, col_qualifier)

# update table
update(session, tablename, updates)

Updates can also be conditional. A condition is created using where.

# initialize a conditional batch
updates = conditional_batch()

# add a condition; comparing values, timestamps and also running additional iterators to evaluate complex conditions
where(updates, row, col_family, col_qualifier, col_visibility; value=nothing, timestamp=-1, iterators=IteratorSetting[])

# add mutations
update(updates, row, col_family, col_qualifier, col_visibility, value, timestamp::Integer=time_ms())
delete(updates, row, col_family, col_qualifier)

# update the table
update(session, tablename, updates)

Multiple batch updates can be applied by first obtaining a table writer.

batch_writer(session, tablename) do writer
    for i in 1:10
        updates = batch()
        for rownum in 1:N
            update(upd, "row$rownum", "colf", "colq", "", "value$rownum")
        end
        update(writer, upd)
        flush(writer)
    end
end

And similarly for conditional updates:

conditional_batch_writer(session, tablename) do writer
    for i in 1:10
        upd = conditional_batch()
        for rownum in 1:N
            row = "row$rownum"
            val = "value$rownum"
            update(where(upd, row, "colf", "colq"; value=val), "colf", "colq", "", "newvalue$rownum")
        end
        update(writer, upd)
        flush(writer)
    end
end

Reading

Data can be read from tables using a scanner and iterating over the records.

# create a scanner
scanner(session, tablename) do scan
    # iterate over the records
    for rec in records(scan)
        # each record has key and value
        key = rec.key
        val = rec.value

        # the key consists of the row and column identifiers
        row = key.row
        colfam = key.colFamily
        colqual = key.colQualifier
        colvis = key.colVisibility

        # ...
    end
end

Only a subset of the columns can be fetched by specifying the list of columns as:

scanner(session, tablename; columns=[("colfam1","colqual1"), ("colfam2","colqual2")])

Additional iterators can be specified to be used with the scanner:

# iterator settings
iter1 = iter(name, class, priority::Integer, properties::Dict=Dict())
iter2 = iter(name, class, priority::Integer, properties::Dict=Dict())

# specify additional iterators to be used
scanner(session, tablename; iterators=[iter1, iter2])

The scanner can be restricted to only a single row or a subset of matching rows by specifying a range of keys to iterate over.

# assign appropriate key or range of keys to rng
scanner(session, tablename; rng=:())

A scanner key can be created using:

scanner_key(row; col_family="", col_qualifier="", col_visibility="", timestamp=0x7FFFFFFFFFFFFFFF)

A range of keys can be specified as expressions of the form k1 <= x < k2 where:

  • k1 and k2 are the bounds. They can either be just the row value, or a key created using scanner_key
  • <=, <, >, >= help specify the lower and upper bounds and their inclusivity
  • x is just any symbol to complete the expression syntax

The range bounds (k1 and k2 above) can be one of the following:

  • just the row (bytes or type that can be converted to bytes)
  • a key created by scanner_key
  • an expression that evaluates to one of the above

TODO:

  • suppport for
    • table compactions
    • locality groups
    • namespaces
  • additional authentication methods
  • nicer API

Download Details:

Author: JuliaDatabases
Source Code: https://github.com/JuliaDatabases/Accumulo.jl 
License: View license

#julia #database #client 

Accumulo.jl: Apache Accumulo Client

Memcache.jl: Julia Memcached Client

Julia Memcache Client

A pure Julia client for memcached servers. All memcached commands as of memcached version 1.4.17 are implemented.

Both numbers and strings are stored in plain string format so as to be interoperable with other memcached client libraries. Other Julia types are stored in their serialized form.

Type MemcacheClient represents a connection to a single memcached server instance.

Type MemcacheClients wraps over multiple MemcacheClient instances to provide distributed cache across more than one memcached server instances. Operations are routed to appropriate server based on key hash value.

Methods

  • Setting and getting data: set, cas, add, replace, append, prepend, incr, decr, get, touch
  • Administration: stats, version, flush_all, close, slabs_reassign, slabs_automove, quit

All methods are supported for both MemcacheClient and MemcacheClients, but results of administration commands would return and array of responses from all servers. See memcached command documentation for details of administration commands.

Below is an illustration of using the most common commands.

julia> using Memcache

julia> # create a client connection

julia> mc = MemcacheClient("localhost", 11211);

julia> 

julia> # simple set and get

julia> set(mc, "key1", "val1")

julia> set(mc, "key2", 2)

julia> get(mc, "key1")
"val1"

julia> 

julia> # multi get

julia> get(mc, "key1", "key2")
["key1"=>"val1","key2"=>2]

julia> 

julia> # increment, decrement

julia> incr(mc, "key2", 8)
10

julia> decr(mc, "key2", 3)
7

julia> 

julia> # append, prepend

julia> append(mc, "key1", "--")

julia> prepend(mc, "key1", "--")

julia> get(mc, "key1")
"--val1--"

julia> 

julia> # cas

julia> res = get(mc, "key1", cas=true)
["key1"=>("--val1--",40)]

julia> val,casval = res["key1"]
("--val1--",40)

julia> cas(mc, "key1", 2, casval)

julia> get(mc, "key1")
2

TODO

  • compression
  • optimize multi get for MemcacheClients

Download Details:

Author: tanmaykm
Source Code: https://github.com/tanmaykm/Memcache.jl 
License: View license

#julia #client #memcached 

Memcache.jl: Julia Memcached Client
Lawson  Wehner

Lawson Wehner

1661637360

Ory_hydra_client: Documentation for All Of Ory Hydra's APIs

ory_hydra_client

Documentation for all of Ory Hydra's APIs.

This Dart package is automatically generated by the OpenAPI Generator project:

  • API version: v1.11.8
  • Build package: org.openapitools.codegen.languages.DartDioClientCodegen

Requirements

Dart 2.7.0 or later OR Flutter 1.12 or later

Installation & Usage

Github

If this Dart package is published to Github, please include the following in pubspec.yaml

name: ory_hydra_client
version: 1.11.8
description: OpenAPI API client
dependencies:
  ory_hydra_client:
    git: https://github.com/ory/sdk.git
      version: 'any'

Local

To use the package in your local drive, please include the following in pubspec.yaml

dependencies:
  ory_hydra_client:
    path: /path/to/ory_hydra_client

Getting Started

Please follow the installation procedure and then run the following:

import 'package:ory_hydra_client/api.dart';


final api = AdminApi();
final consentChallenge = consentChallenge_example; // String | 
final acceptConsentRequest = AcceptConsentRequest(); // AcceptConsentRequest | 

try {
    final response = await api.acceptConsentRequest(consentChallenge, acceptConsentRequest);
    print(response);
} catch (e) {
    print("Exception when calling AdminApi->acceptConsentRequest: $e\n");
}

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add ory_hydra_client

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

dependencies:
  ory_hydra_client: ^1.11.8

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

Import it

Now in your Dart code, you can use:

import 'package:ory_hydra_client/api.dart';
import 'package:ory_hydra_client/api/admin_api.dart';
import 'package:ory_hydra_client/api/metadata_api.dart';
import 'package:ory_hydra_client/api/public_api.dart';
import 'package:ory_hydra_client/api_util.dart';
import 'package:ory_hydra_client/auth/api_key_auth.dart';
import 'package:ory_hydra_client/auth/auth.dart';
import 'package:ory_hydra_client/auth/basic_auth.dart';
import 'package:ory_hydra_client/auth/oauth.dart';
import 'package:ory_hydra_client/model/accept_consent_request.dart';
import 'package:ory_hydra_client/model/accept_login_request.dart';
import 'package:ory_hydra_client/model/completed_request.dart';
import 'package:ory_hydra_client/model/consent_request.dart';
import 'package:ory_hydra_client/model/consent_request_session.dart';
import 'package:ory_hydra_client/model/flush_inactive_o_auth2_tokens_request.dart';
import 'package:ory_hydra_client/model/flush_login_consent_request.dart';
import 'package:ory_hydra_client/model/generic_error.dart';
import 'package:ory_hydra_client/model/health_not_ready_status.dart';
import 'package:ory_hydra_client/model/health_status.dart';
import 'package:ory_hydra_client/model/inline_response200.dart';
import 'package:ory_hydra_client/model/inline_response2001.dart';
import 'package:ory_hydra_client/model/inline_response503.dart';
import 'package:ory_hydra_client/model/json_error.dart';
import 'package:ory_hydra_client/model/json_web_key.dart';
import 'package:ory_hydra_client/model/json_web_key_set.dart';
import 'package:ory_hydra_client/model/json_web_key_set_generator_request.dart';
import 'package:ory_hydra_client/model/login_request.dart';
import 'package:ory_hydra_client/model/logout_request.dart';
import 'package:ory_hydra_client/model/o_auth2_client.dart';
import 'package:ory_hydra_client/model/o_auth2_token_introspection.dart';
import 'package:ory_hydra_client/model/oauth2_token_response.dart';
import 'package:ory_hydra_client/model/oauth_token_response.dart';
import 'package:ory_hydra_client/model/open_id_connect_context.dart';
import 'package:ory_hydra_client/model/patch_document.dart';
import 'package:ory_hydra_client/model/previous_consent_session.dart';
import 'package:ory_hydra_client/model/refresh_token_hook_request.dart';
import 'package:ory_hydra_client/model/refresh_token_hook_response.dart';
import 'package:ory_hydra_client/model/reject_request.dart';
import 'package:ory_hydra_client/model/request_was_handled_response.dart';
import 'package:ory_hydra_client/model/trust_jwt_grant_issuer_body.dart';
import 'package:ory_hydra_client/model/trusted_json_web_key.dart';
import 'package:ory_hydra_client/model/trusted_jwt_grant_issuer.dart';
import 'package:ory_hydra_client/model/userinfo_response.dart';
import 'package:ory_hydra_client/model/version.dart';
import 'package:ory_hydra_client/model/well_known.dart';
import 'package:ory_hydra_client/serializers.dart';

Documentation for API Endpoints

All URIs are relative to http://localhost

ClassMethodHTTP requestDescription
AdminApiacceptConsentRequestPUT /oauth2/auth/requests/consent/acceptAccept a Consent Request
AdminApiacceptLoginRequestPUT /oauth2/auth/requests/login/acceptAccept a Login Request
AdminApiacceptLogoutRequestPUT /oauth2/auth/requests/logout/acceptAccept a Logout Request
AdminApicreateJsonWebKeySetPOST /keys/{set}Generate a New JSON Web Key
AdminApicreateOAuth2ClientPOST /clientsCreate an OAuth 2.0 Client
AdminApideleteJsonWebKeyDELETE /keys/{set}/{kid}Delete a JSON Web Key
AdminApideleteJsonWebKeySetDELETE /keys/{set}Delete a JSON Web Key Set
AdminApideleteOAuth2ClientDELETE /clients/{id}Deletes an OAuth 2.0 Client
AdminApideleteOAuth2TokenDELETE /oauth2/tokensDelete OAuth2 Access Tokens from a Client
AdminApideleteTrustedJwtGrantIssuerDELETE /trust/grants/jwt-bearer/issuers/{id}Delete a Trusted OAuth2 JWT Bearer Grant Type Issuer
AdminApiflushInactiveOAuth2TokensPOST /oauth2/flushFlush Expired OAuth2 Access Tokens
AdminApigetConsentRequestGET /oauth2/auth/requests/consentGet Consent Request Information
AdminApigetJsonWebKeyGET /keys/{set}/{kid}Fetch a JSON Web Key
AdminApigetJsonWebKeySetGET /keys/{set}Retrieve a JSON Web Key Set
AdminApigetLoginRequestGET /oauth2/auth/requests/loginGet a Login Request
AdminApigetLogoutRequestGET /oauth2/auth/requests/logoutGet a Logout Request
AdminApigetOAuth2ClientGET /clients/{id}Get an OAuth 2.0 Client
AdminApigetTrustedJwtGrantIssuerGET /trust/grants/jwt-bearer/issuers/{id}Get a Trusted OAuth2 JWT Bearer Grant Type Issuer
AdminApiintrospectOAuth2TokenPOST /oauth2/introspectIntrospect OAuth2 Tokens
AdminApilistOAuth2ClientsGET /clientsList OAuth 2.0 Clients
AdminApilistSubjectConsentSessionsGET /oauth2/auth/sessions/consentLists All Consent Sessions of a Subject
AdminApilistTrustedJwtGrantIssuersGET /trust/grants/jwt-bearer/issuersList Trusted OAuth2 JWT Bearer Grant Type Issuers
AdminApipatchOAuth2ClientPATCH /clients/{id}Patch an OAuth 2.0 Client
AdminApirejectConsentRequestPUT /oauth2/auth/requests/consent/rejectReject a Consent Request
AdminApirejectLoginRequestPUT /oauth2/auth/requests/login/rejectReject a Login Request
AdminApirejectLogoutRequestPUT /oauth2/auth/requests/logout/rejectReject a Logout Request
AdminApirevokeAuthenticationSessionDELETE /oauth2/auth/sessions/loginInvalidates All Login Sessions of a Certain User Invalidates a Subject's Authentication Session
AdminApirevokeConsentSessionsDELETE /oauth2/auth/sessions/consentRevokes Consent Sessions of a Subject for a Specific OAuth 2.0 Client
AdminApitrustJwtGrantIssuerPOST /trust/grants/jwt-bearer/issuersTrust an OAuth2 JWT Bearer Grant Type Issuer
AdminApiupdateJsonWebKeyPUT /keys/{set}/{kid}Update a JSON Web Key
AdminApiupdateJsonWebKeySetPUT /keys/{set}Update a JSON Web Key Set
AdminApiupdateOAuth2ClientPUT /clients/{id}Update an OAuth 2.0 Client
MetadataApigetVersionGET /versionReturn Running Software Version.
MetadataApiisAliveGET /health/aliveCheck HTTP Server Status
MetadataApiisReadyGET /health/readyCheck HTTP Server and Database Status
PublicApidisconnectUserGET /oauth2/sessions/logoutOpenID Connect Front-Backchannel Enabled Logout
PublicApidiscoverOpenIDConfigurationGET /.well-known/openid-configurationOpenID Connect Discovery
PublicApidynamicClientRegistrationCreateOAuth2ClientPOST /connect/registerRegister an OAuth 2.0 Client using the OpenID / OAuth2 Dynamic Client Registration Management Protocol
PublicApidynamicClientRegistrationDeleteOAuth2ClientDELETE /connect/register/{id}Deletes an OAuth 2.0 Client using the OpenID / OAuth2 Dynamic Client Registration Management Protocol
PublicApidynamicClientRegistrationGetOAuth2ClientGET /connect/register/{id}Get an OAuth 2.0 Client using the OpenID / OAuth2 Dynamic Client Registration Management Protocol
PublicApidynamicClientRegistrationUpdateOAuth2ClientPUT /connect/register/{id}Update an OAuth 2.0 Client using the OpenID / OAuth2 Dynamic Client Registration Management Protocol
PublicApioauth2TokenPOST /oauth2/tokenThe OAuth 2.0 Token Endpoint
PublicApioauthAuthGET /oauth2/authThe OAuth 2.0 Authorize Endpoint
PublicApirevokeOAuth2TokenPOST /oauth2/revokeRevoke OAuth2 Tokens
PublicApiuserinfoGET /userinfoOpenID Connect Userinfo
PublicApiwellKnownGET /.well-known/jwks.jsonJSON Web Keys Discovery

Documentation For Models

Documentation For Authorization

basic

  • Type: HTTP basic authentication

oauth2

  • Type: OAuth
  • Flow: accessCode
  • Authorization URL: https://hydra.demo.ory.sh/oauth2/auth
  • Scopes:
  • offline: A scope required when requesting refresh tokens (alias for offline_access)
  • offline_access: A scope required when requesting refresh tokens
  • openid: Request an OpenID Connect ID Token

Author

hi@ory.sh

Original article source at: https://pub.dev/packages/ory_hydra_client 

#flutter #dart #client 

Ory_hydra_client: Documentation for All Of Ory Hydra's APIs
Hunter  Krajcik

Hunter Krajcik

1661203440

Rest_client: A Dart Implementation Of The A REST Client That Supports

rest_client

A Dart and Flutter compatible library to simplify creating REST based API calls.

For Flutter based applications, this will offload the JSON decoding to a separate Isolate to avoid janking the UI thread on large JSON responses. For Dart Web / AngularDart based applications, this processes the JSON on the main thread because Isolates are not supported.

Using the library

Add the repo to your Flutter pubspec.yaml file.

dependencies:
  rest_client: <<version>> 

Then run...

flutter packages get

Authorizers

The API Client offers the following two built in authorizers.

  • BasicAuthorizer -- To authenticate against an API using the BASIC username / password security models.
  • TokenAuthorizer -- To authorize against an API using Bearer token based authorization.

Example

import 'package:rest_client/rest_client.dart' as rc;

...

var client = rc.Client();

var request = rc.Request(
  url: 'https://google.com',
);

var response = client.execute(
  authorizor: rc.TokenAuthorizer(token: 'my_token_goes_here'),
  request: request, 
);

var body = response.body;
// do further processing here...

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add rest_client

With Flutter:

 $ flutter pub add rest_client

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

dependencies:
  rest_client: ^2.1.4+8

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:rest_client/rest_client.dart';

 

Download Details:

Author: Peiffer-innovations
Source Code: https://github.com/peiffer-innovations/rest_client 
License: MIT license

#flutter #dart #rest #client 

Rest_client: A Dart Implementation Of The A REST Client That Supports
Nat  Grady

Nat Grady

1661188500

Git2r: R Bindings to The Libgit2 Library

Introduction

The git2r package gives you programmatic access to Git repositories from R. Internally the package uses the libgit2 library which is a pure C implementation of the Git core methods. For more information about libgit2, check out libgit2's website (http://libgit2.github.com).

Suggestions, bugs, forks and pull requests are appreciated. Get in touch.

Installation

To install the version available on CRAN:

install.packages("git2r")

To install the development version of git2r, it's easiest to use the devtools package:

# install.packages("devtools")
library(devtools)
install_github("ropensci/git2r")

Another alternative is to use git and make

$ git clone https://github.com/ropensci/git2r.git
$ cd git2r
$ make install

Usage

Repository

The central object in the git2r package is the S3 class git_repository. The following three methods can instantiate a repository; init, repository and clone.

Create a new repository

Create a new repository in a temporary directory using init

library(git2r)
#> Loading required package: methods

## Create a temporary directory to hold the repository
path <- tempfile(pattern="git2r-")
dir.create(path)

## Initialize the repository
repo <- init(path)

## Display a brief summary of the new repository
repo
#> Local:    /tmp/Rtmp7CXPlx/git2r-1ae2305c0e8d/
#> Head:     nothing commited (yet)

## Check if repository is bare
is_bare(repo)
#> [1] FALSE

## Check if repository is empty
is_empty(repo)
#> [1] TRUE

Create a new bare repository

## Create a temporary directory to hold the repository
path <- tempfile(pattern="git2r-")
dir.create(path)

## Initialize the repository
repo <- init(path, bare=TRUE)

## Check if repository is bare
is_bare(repo)
#> [1] TRUE

Clone a repository

## Create a temporary directory to hold the repository
path <- file.path(tempfile(pattern="git2r-"), "git2r")
dir.create(path, recursive=TRUE)

## Clone the git2r repository
repo <- clone("https://github.com/ropensci/git2r", path)
#> cloning into '/tmp/Rtmp7CXPlx/git2r-1ae27d811539/git2r'...
#> Receiving objects:   1% (24/2329),   12 kb
#> Receiving objects:  11% (257/2329),   60 kb
#> Receiving objects:  21% (490/2329),  100 kb
#> Receiving objects:  31% (722/2329),  125 kb
#> Receiving objects:  41% (955/2329),  237 kb
#> Receiving objects:  51% (1188/2329),  574 kb
#> Receiving objects:  61% (1421/2329), 1014 kb
#> Receiving objects:  71% (1654/2329), 1350 kb
#> Receiving objects:  81% (1887/2329), 1733 kb
#> Receiving objects:  91% (2120/2329), 2614 kb
#> Receiving objects: 100% (2329/2329), 2641 kb, done.

## Summary of repository
summary(repo)
#> Remote:   @ origin (https://github.com/ropensci/git2r)
#> Local:    master /tmp/Rtmp7CXPlx/git2r-1ae27d811539/git2r/
#>
#> Branches:          1
#> Tags:              0
#> Commits:         320
#> Contributors:      3
#> Ignored files:     0
#> Untracked files:   0
#> Unstaged files:    0
#> Staged files:      0

## List all references in repository
references(repo)
#> $`refs/heads/master`
#> [6fb440] master
#>
#> $`refs/remotes/origin/master`
#> [6fb440] origin/master

## List all branches in repository
branches(repo)
#> [[1]]
#> [6fb440] (Local) (HEAD) master
#>
#> [[2]]
#> [6fb440] (origin @ https://github.com/ropensci/git2r) master

Open an existing repository

## Open an existing repository
repo <- repository(path)

## Workdir of repository
workdir(repo)
#> [1] "/tmp/Rtmp7CXPlx/git2r-1ae27d811539/git2r/"

## List all commits in repository
commits(repo)[[1]] # Truncated here for readability
#> Commit:  6fb440133765e80649de8d714eaea17b114bd0a7
#> Author:  Stefan Widgren <stefan.widgren@gmail.com>
#> When:    2014-04-22 21:43:19
#> Summary: Fixed clone progress to end line with newline

## Get HEAD of repository
repository_head(repo)
#> [6fb440] (Local) (HEAD) master

## Check if HEAD is head
is_head(repository_head(repo))
#> [1] TRUE

## Check if HEAD is local
is_local(repository_head(repo))
#> [1] TRUE

## List all tags in repository
tags(repo)
#> list()

Configuration

config(repo, user.name="Git2r Readme", user.email="git2r.readme@example.org")

## Display configuration
config(repo)
#> global:
#>         core.autocrlf=input
#> local:
#>         branch.master.merge=refs/heads/master
#>         branch.master.remote=origin
#>         core.bare=false
#>         core.filemode=true
#>         core.logallrefupdates=true
#>         core.repositoryformatversion=0
#>         remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
#>         remote.origin.url=https://github.com/ropensci/git2r
#>         user.email=git2r.readme@example.org
#>         user.name=Git2r Readme

Commit

## Create a new file
writeLines("Hello world!", file.path(path, "test.txt"))

## Add file and commit
add(repo, "test.txt")
commit(repo, "Commit message")
#> Commit:  0a6af48cedf43208bde34230662280514e0956eb
#> Author:  Git2r Readme <git2r.readme@example.org>
#> When:    2014-04-22 21:44:57
#> Summary: Commit message

Included software

The C library libgit2. See inst/AUTHORS for the authors of libgit2.

The libgit2 library has been modified, e.g. to use the R printing and error routines, and to use runif instead of rand.


Download Details:

Author: ropensci
Source Code: https://github.com/ropensci/git2r 
License: GPL-2.0 license

#r #git #client 

Git2r: R Bindings to The Libgit2 Library
Lawson  Wehner

Lawson Wehner

1660917240

Uni_ocr_client: A Universal Ocr Client

uni_ocr_client

A universal ocr client.

Installing

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add uni_ocr_client

With Flutter:

 $ flutter pub add uni_ocr_client

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

dependencies:
  uni_ocr_client: ^0.1.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:uni_ocr_client/uni_ocr_client.dart';

Part of uni_ocr

Download Details:

Author: Biyidev
Source Code: https://github.com/biyidev/uni_ocr/
License: MIT

#flutter #dart #client 

Uni_ocr_client: A Universal Ocr Client

Kuber.jl: Julia Kubernetes Client

Kuber

A Julia Kubernetes Client.

An easy to use API to access Kubernetes clusters from Julia. The Kuber.ApiImpl.Kubernetes submodule has the complete set of low level APIs and entities.

Most of the low level APIs fit into a common usage pattern. Kuber.jl makes it possible to use all of them with only a few intuitive verb based APIs. Verbs act on entities. Entities can be identified by names or selector patterns, or otherwise can apply to all entities of that class. Verbs can take additional parameters, e.g. when creating or updating entities.

API and Entity naming convention follows the standard Kubernetes API and Model naming conventions.

Here are a few helpful resources:

  • Tutorial on using Kuber.jl.
  • Article on using metrics and custom metrics with Kuber.jl

Entities:

Any Kubernetes entity supported. APIs identify an entity by symbol named as per Kubernetes naming convention.

  • :Namespace
  • :Pod
  • :ReplicationController
  • :Service
  • :PersistentVolume
  • :Job
  • ...

Methods/Verbs:

Kubernetes APIs are mapped to these easy to use verbs, familiar to Julia users.

  • get: list or fetch entities
  • list: list entities
  • put!: create entities
  • update!: update existing entities
  • delete!: delete existing entities
  • sel: creates a label selector to use with other verbs

All verbs have the signature:

verb(ctx::KuberContext, T::Symbol, args...; kwargs...)

Kubernetes also provides efficient change notifications on resources via "watches". Certain entities have the special watch APIs defined for them and that can be invoked with the watch verb. The watch API accepts a Channel through which it streams events.

watch(ctx::KuberContext, T::Symbol, outstream::Channel, args...; kwargs...)

In addition, verbs like get and list also support watches, and those can be invoked as:

watch(ctx, verb, args...; kwargs...) do stream
    for event in stream
        # process event
    end
end

E.g.:

watch(ctx, list, :Pod; resourceVersion=19451) do stream
    for event in stream
        @info("got event", event)
    end
end

Helper methods:

A Kubernetes context can be manipulated with:

  • set_server: Set the API server location ("http://localhost:8001" if not set)
  • set_ns: Set the namespace to deal with (default namespace is not set)
  • set_retries: Set the number of times an API call should be retried on a retriable error (5 if not set) and whether all APIs should be retried (only non mutating APIs are retried by default)

Other convenience methods:

  • kuber_type: identify the Julia object corresponding to the Kubernetes specification
  • kuber_obj: instantiate a Julia object from for the supplied Kubernetes specification
  • Helper methods for accessing metrics

References:

Download Details:

Author: JuliaComputing
Source Code: https://github.com/JuliaComputing/Kuber.jl 
License: View license

#julia #kubernetes #client 

Kuber.jl: Julia Kubernetes Client

Neovim.jl: Neovim Client for Julia

Neovim client for Julia

Neovim.jl is a Neovim API client and plugin host for Julia. It supports:

  • Embedding a nvim process in Julia
  • Acting as a child process to nvim
  • Connecting to external instances over a socket

Requirements

  • Julia β‰₯ 1.0
  • Neovim β‰₯ 0.4 (this package assumes nvim is in $PATH)

Installation

Add this package to your current Julia environment:

using Pkg
Pkg.add(url="https://github.com/bfredl/Neovim.jl")

Usage

As an embedded process

The simplest way to test the API client is to spawn an embedded instance:

using Neovim
nvim, proc = nvim_spawn()

or connecting to an external instance:

nvim = nvim_connect("/socket/address")

(this address can be found by :echo $NVIM_LISTEN_ADDRESS in nvim)

As a shortcut, nvim = nvim_env() will use the address in $NVIM_LISTEN_ADDRESS. This is useful to connect to the "parent" nvim instance when running the Julia REPL in a nvim terminal window.

All API methods defined in the Neovim metadata (see :h api-metadata) are defined as corresponding Julia functions on the Neovim module (these functions are not exported, use import syntax), except that the vim_/buffer_ prefix is dropped (as the receiver type is identified by the first argument anyway), except for vim_eval as eval is not overloadable. For instance:

import Neovim: get_buffers, set_line, vim_eval
buf = get_buffers(nvim)[1]
set_line(buf, 1, "some text")
@assert vim_eval(nvim, "2+2") == 4

A high level interface is work in progress. For the moment Buffer supports simple array operations, please see test/runtests.jl for examples.

The module exports a low-level interface for handling asynchronous events (notifications and requests). A prototype (read: ugly hack) implementation of Vim bindings for the Julia REPL is included as an example, see src/repl.jl.

As a plugin host

This package also includes a remote plugin host, similar to the one in the Python client pynvim. To use it, add this repo root to runtimepath in init.vim:

set rtp+=~/.julia/packages/Neovim/

A Julia plugin can then be defined in a rplugin/julia/ subdirectory inside a directory in your runtimepath (See :h remote-plugin and :h runtimepath) or inside a plugin directory (see :h packages or your package manager's docs).

Functions defined at the top-level of your script can be exported using the macros: @fn, @command, @autocmd, as well as variants ending with sync.

For example:

# In MyPlugin/rplugin/julia/MyPlugin.jl

module MyPlugin
using Neovim

@Neovim.fn function AsyncFun(nvim, args)
    # "args" is Vector of arguments passed to ":call AsyncFun(args...)".
end

@Neovim.fnsync function SyncFun(nvim, args)
    # This will block neovim while SyncFun is running.
end

@Neovim.fnsync OneLiner(nvim, args) = "expression"

# Add some options. -> is required to define function on next line.
@Neovim.commandsync (nargs="*", range="") ->
function JLCommand(nvim, args, range)
end

# The name of the function/command can also be defined on the macro.
# This is equivalent to the above.
@Neovim.commandsync JLCommand(nargs="*", range="") ->
function (nvim, args, range)
end

end

After writing your Julia script, you should call :UpdateRemotePlugins to register these functions and make them callable from Vimscript and Lua.

Download Details:

Author: Bfredl
Source Code: https://github.com/bfredl/Neovim.jl 
License: MIT license

#julia #neovim #client 

Neovim.jl: Neovim Client for Julia