1660216763
This is a quick package for building small networks of detailed, conductance-based neurons out of ion channels and synapses. The idea is that it's easy to use this template and add your own ion channels / synapses, with your choice of dynamics. Iteratively adding these components to a neuron is done using ModelingToolkit, which makes it scalable to any number of ion channels and synapses.
If you want a more flexible platform to build neuron models, with e.g. multiple compartments, from basic components you should check out the more comprehensive package Conductor.jl (in active development).
Installation and Usage
NeuronBuilder is available as a registered package and has a tagged release (v0.1.0)
#From Julia REPL
] add NeuronBuilder
Once you exit the package manager (ctrl+c
), type using NeuronBuilder
.
To try out the demo scripts:
git clone https://github.com/Dhruva2/NeuronBuilder.jl
cd NeuronBuilder.jl
git checkout v0.1.0
include("neuron_liu.jl")
Liu.Na(g)
or Prinz.Na(g)
if the conductance has value g
.Liu_conversion
and Prinz_conversion
to get the right units. You can see how these are specifically given in the scripts and are multiplying with the original g
value from the papers.g_values.jl
file has a small collection of conductances coming from various sources. You can copy-paste any of these into the script that simulates a single neuron.connected_STG.jl
script shows how to add synapses between neurons and reproduces the triphasic rhythm of the STG found in Prinz et. al. 2004.This work was funded by European Research Council grant 716643 FLEXNEURO, (Principal Investigator Timothy O’Leary).
Author: Dhruva2
Source Code: https://github.com/Dhruva2/NeuronBuilder.jl
License: MIT license
1660202460
PhyloNetworks is a Julia package with utilities to:
To get help, check
If you use the package, please cite
SNaQ implements the statistical inference method in Solís-Lemus and Ané (2016). The procedure involves a numerical optimization of branch lengths and inheritance probabilities and a heuristic search in the space of phylogenetic networks.
If you use SNaQ, please cite
For continuous traits, study based on the Brownian motion process, with or without transgressive evolution after reticulations:
Continuous traits, accounting for within-species variation:
For a discrete trait (influence of gene flow on the trait, ancestral state reconstruction, rates):
Author: crsl4
Source Code: https://github.com/crsl4/PhyloNetworks.jl
License: View license
1660165500
A free and ethical photo sharing platform, powered by ActivityPub federation.
Documentation for Pixelfed can be found on the Pixelfed documentation website.
Pixelfed app for YunoHost. See the package source code
The ways you can communicate on the project are below. Before interacting, please read through the Code Of Conduct.
We would like to extend our thanks to the following sponsors for funding Pixelfed development. If you are interested in becoming a sponsor, please visit the Pixelfed Patreon Page
Author: Pixelfed
Source Code: https://github.com/pixelfed/pixelfed
License: AGPL-3.0 license
1660100940
News
2.1.0
available on CRAN (in a few days...)Example
install.packages("visNetwork")
# devtools::install_github("datastorm-open/visNetwork") for development version
require(visNetwork)
?visNetwork
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
visNetwork(nodes, edges)
# vignette
vignette("Introduction-to-visNetwork")
# full javascript documentation
visDocumentation()
# shiny example
shiny::runApp(system.file("shiny", package = "visNetwork"))
Online documentation
And have a look to multiple R examples, vis.js documentation (visDocumentation
).
Author: Datastorm-open
Source Code: https://github.com/datastorm-open/visNetwork
License: View license
1660052602
This julia
package provides a common interface to analyze all types of data on ecological networks. It is designed to be general, easy to expand, and work on bipartite/unipartite as well as deterministic/quantitative/probabilistic networks. The current version is compatible with julia
version 1.0 and 0.7.
Install (from the package mode):
add EcologicalNetworks
Optionally, if you want to visualize networks, install
add EcologicalNetworksPlots
That's it. Now head over to the documentation.
Author: EcoJulia
Source Code: https://github.com/EcoJulia/EcologicalNetworks.jl
License: View license
1659553980
With Network Manager, you can now easily manage your internet requests, send and receive data.
Settings Base URL -> NetworkManager("https://jsonplaceholder.typicode.com/",debugMode: true);
.setGET() => "GET"
.setPOST() => "POST"
.setPUT() => "PUT"
.setDELETE() => "DELETE"
### Set TimeOuts:
.setSendTimeout(1000) => Default Value 3000.
### Set setReceiveTimeOut:
.setReceiveTimeOut(1000) => Default Value 3000.
### Set setQueryParameters:
.setQueryParameters({"name":"example"})
### Set setHeader:
.setHeader({"Content-Type":"example"})
#### Set setBody:
.setBody({"Content-Type":"example"})
### Set setContentType:
.setContentType("multipart-form")
#### Set setPath:
.setPath("api/v1/login")
### Set execute:
.execute<T extends BaseResponseModel, K>(
T responseModel)
T extends => Your Decode Model
T responseMode => Your Decode Model
K => Show View Model, ExampleModel, List<ExampleModel>
import 'package:network_manager/Network/Error/network_error.dart';
import 'package:network_manager/Network/Result/network_result.dart';
import '../../../client/network_client.dart';
import '../model/home_model.dart';
class HomeServices {
Result<List<HomeModel>, NetworkError> result = const Result.success([]);
Future<void> getHomeList() async {
Future.delayed(const Duration(seconds: 1));
final response = await NetworkClient.instance.networkManager
.setGET()
.setPath("posts")
.execute<HomeModel, List<HomeModel>>(HomeModel());
result = response;
}
}
import 'package:network_manager/Network/Interface/model_interface.dart';
class HomeModel extends BaseResponseModel {
HomeModel({
this.userId,
this.id,
this.title,
this.body,
});
int? userId;
int? id;
String? title;
String? body;
factory HomeModel.fromJson(Map<String, dynamic> json) => HomeModel(
userId: json["userId"],
id: json["id"],
title: json["title"],
body: json["body"],
);
Map<String, dynamic> toJson() => {
"userId": userId,
"id": id,
"title": title,
"body": body,
};
@override
fromJson(Map<String, dynamic> json) {
return HomeModel.fromJson(json);
}
}
import 'package:flutter/material.dart';
import '../services/home_services.dart';
class HomeScreen extends StatelessWidget {
HomeScreen({Key? key}) : super(key: key);
final HomeServices homeServices = HomeServices();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Example Network Manager"),
),
body: FutureBuilder(
future: homeServices.getHomeList(),
builder: (context, snapshot) => homeServices.result.when(
success: (data) {
return ListView.builder(
itemBuilder: (context, index) => ListTile(
title: Text(data[index].title ?? ""),
subtitle: Text(data[index].body ?? ""),
),
itemCount: data.length,
);
},
failure: (error) {
return Text(error.toString());
},
),
));
}
}
import 'package:network_manager/Network/network_builder.dart';
class NetworkClient {
static final NetworkClient instance = NetworkClient();
final NetworkManager networkManager = NetworkManager("https://jsonplaceholder.typicode.com/",debugMode: true);
}
ScreenShot
Run this command:
With Flutter:
$ flutter pub add flutter_network_manager
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
flutter_network_manager: ^0.0.3
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:flutter_network_manager/Network/Error/network_error.dart';
import 'package:flutter_network_manager/Network/Error/network_error.freezed.dart';
import 'package:flutter_network_manager/Network/Interface/model_interface.dart';
import 'package:flutter_network_manager/Network/Interface/network_manager_interface.dart';
import 'package:flutter_network_manager/Network/Layers/network_connectivity.dart';
import 'package:flutter_network_manager/Network/Layers/network_decoding.dart';
import 'package:flutter_network_manager/Network/Result/network_result.dart';
import 'package:flutter_network_manager/Network/Result/network_result.freezed.dart';
import 'package:flutter_network_manager/Network/network_builder.dart';
import 'package:flutter_network_manager/network_manager.dart';
example/lib/main.dart
import 'package:flutter/material.dart';
import 'screens/home/screen/home_screen.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomeScreen(),
);
}
}
Author: SercanKaya0
Source Code: https://github.com/SercanKaya0/network_manager
License: MIT license
1659287580
A Flutter plugin for network service discovery and registration (aka NSD / DNS-SD / Bonjour / mDNS).
import 'package:nsd/nsd.dart';
final discovery = await startDiscovery('_http._tcp');
discovery.addListener(() {
// discovery.services contains discovered services
});
// ...
await stopDiscovery(discovery);
or alternatively:
discovery.addServiceListener((service, status) {
if (status == ServiceStatus.found) {
// put service in own collection, etc.
}
});
import 'package:nsd/nsd.dart';
final registration = await register(
const Service(name: 'Foo', type: '_http._tcp', port: 56000));
// ...
await unregister(registration);
Add the following permissions to your manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
Add the following permissions to your Info.plist (replace service type with your own):
<key>NSLocalNetworkUsageDescription</key>
<string>Required to discover local network devices</string>
<key>NSBonjourServices</key>
<array>
<string>_http._tcp</string>
</array>
The plugin includes an example application that can be used to start multiple discoveries and register multiple services. It will discover its own services but also other services of type _http._tcp
in the local network, such as the printer in the screenshot above.
First, do you really need the IP address? If you just want to connect to the service, the host name that is supplied with the service should do just fine. In fact, connecting by host name is recommended on the Apple Developer Forums.
If you do need the IP address, you can configure automatic ip lookup for your discovery like this:
final discovery = await startDiscovery(serviceType, ipLookupType: IpLookupType.any);
Each discovered service will now have a list of IP addresses attached to it.
The current way to do this would be:
_services._dns-sd._udp
Start the discovery like this:
final discovery = await startDiscovery('_services._dns-sd._udp', autoResolve: false);
The autoResolve
flag is important because the results are not real services and cannot be resolved. The discovery.services
list will then be populated with the answers. The Service
instances returned will contain service type info, like so:
{service.type: _tcp.local, service.name: _foo, ...}
{service.type: _tcp.local, service.name: _bar, ...}
The first component of the service type (e.g. _foo
) is contained in the service name attribute, the second component of the service type (e.g. _tcp
) is contained in the service type attribute.
Even though using a service structure to represent a service type feels like a hack, it seems to be consistent on Android / macOS / iOS platform APIs. Since they are all doing it, the plugin has the same behavior.
Note: this currently doesn't function 100% on Windows platforms. While it will detect the types of services registered by other machines correctly, it will not detect types of services that were registered using the plugin.
In order to help debugging, logging can be enabled for individual topics. For example
enableLogging(LogTopic.errors);
enableLogging(LogTopic.calls);
will log errors and all calls to the native side (and their callbacks), which often yields useful information.
lxp-git - wrote the Windows prototype!
🎮 Tic Tac Toe Local Multiplayer Game for Android by Laks Castro
Run this command:
With Flutter:
$ flutter pub add nsd
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
nsd: ^2.2.3
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:nsd/nsd.dart';
Author: Sebastianhaberey
Source Code: https://github.com/sebastianhaberey/nsd/
License: MIT
1658573880
A Julia package for network learning.
NetworkLearning implements a generic framework for network classification. It could in theory be used to provide additional functionality (i.e. semi-supervised learning, regression), provided that appropriate methods for relational learning (i.e. relational variable generation) and collective inference are added. The framework is designed to make as little assumptions as possible on the elements involved in the process.
Two scenarios or usecases are covered:
Observation-based learning, in which the network structure is pertinent to the observations and consequently, estimates (i.e. class probabilities) are associated to the observations; in the estimation process, relational structures can either make use the training data (in-graph learning) or not (out-of-graph learning). For example, in the case of document classifcation, an observation would correspond to a publication that has to be classified into an arbitrary category, given a representation of its local content-based information as well on the its relational information (links to other documents, citations etc.).
Entity-based learning, in which observations are pertinent to one or more abstract entities for which estimates are calculated. In entity-based network learning, observations can modify either the local or relational information of one or more entities.
Learner type
Relational learners
Collective inference
Adjacency strucures
import DecisionTree
using NetworkLearning, MLDataPattern, MLLabelUtils, LossFunctions
# Download the CORA dataset, and return data and citing/cited papers indices (relative to order in X,y)
(X,y), cited_papers, citing_papers = NetworkLearning.grab_cora_data()
n = nobs(X)
yᵤ = sort(unique(y))
C = length(yᵤ)
# Split data
idx = collect(1:n);
shuffle!(idx)
p = 0.5
idxtr,idxts = splitobs(idx,p)
Xtr = X[:,idxtr]
ytr = y[idxtr]
Xts = X[:,idxts]
# Build adjacency matrices
Atr = NetworkLearning.generate_partial_adjacency(cited_papers, citing_papers, idxtr);
# Construct necessary arguments for training the network learner
fl_train = (X::Tuple{Matrix{Float64}, Vector{Int}})-> DecisionTree.build_tree(X[2],X[1]')
fl_exec(C) = (m,X)-> DecisionTree.apply_tree_proba(m, X', collect(1:C))'
fr_train = (X)-> DecisionTree.build_tree(X[2],X[1]')
fr_exec(C) = (m,X)-> DecisionTree.apply_tree_proba(m, X', collect(1:C))'
AV = [adjacency(Atr)]
# Train
info("Training ...")
nlmodel = NetworkLearning.fit(NetworkLearnerObs,
Xtr,
ytr,
AV,
fl_train, fl_exec(C),
fr_train, fr_exec(C);
learner = :wrn,
inference = :ic,
use_local_data = false, # use only relational variables
f_targets = x->targets(indmax,x),
normalize = true,
maxiter = 10,
α = 0.95
)
#########################
# Out-of-Graph learning #
#########################
# Add adjacency pertinent to the test data
Ats = NetworkLearning.generate_partial_adjacency(cited_papers, citing_papers, idxts);
add_adjacency!(nlmodel, [Ats])
# Make predictions
info("Predicting (out-of-graph) ...")
ŷts = predict(nlmodel, Xts)
# Squared loss
yts = convertlabel(LabelEnc.OneOfK(C), y[idxts], yᵤ)
println("\tL2 loss (out-of-graph):", value(L2DistLoss(), yts, ŷts, AvgMode.Mean()))
println("\tAverage error (out-of-graph):", mean(targets(indmax,yts).!=targets(indmax,ŷts)))
#####################
# In-Graph learning #
#####################
# Initialize output structure
Xo = zeros(C,nobs(X))
Xo[:,idxtr] = convertlabel(LabelEnc.OneOfK(C), y[idxtr] ,yᵤ)
# Add adjacency pertinent to the test data
Ats = NetworkLearning.generate_partial_adjacency(cited_papers, citing_papers, collect(1:nobs(X)));
add_adjacency!(nlmodel, [Ats])
# Make predictions
info("Predicting (in-graph) ...")
update_mask = trues(nobs(X));
update_mask[idxtr] = false # estimates for training samples will not be used
predict!(Xo, nlmodel, X, update_mask)
# Squared loss
ŷts = Xo[:,idxts]
yts = convertlabel(LabelEnc.OneOfK(C), y[idxts], yᵤ)
println("\tL2 loss (in-graph):", value(L2DistLoss(), yts, ŷts, AvgMode.Mean()))
println("\tAverage error (in-graph):", mean(targets(indmax,yts).!=targets(indmax,ŷts)))
The output of the above code is:
# % Total % Received % Xferd Average Speed Time Time Time Current
# Dload Upload Total Spent Left Speed
# 100 163k 100 163k 0 0 163k 0 0:00:01 0:00:01 --:--:-- 86695
# cora/
# cora/README
# cora/cora.content
# cora/cora.cites
# INFO: Training ...
# INFO: Predicting (out-of-graph) ...
# L2 loss (out-of-graph):0.13011389156615571
# Average error (out-of-graph):0.5310192023633677
# INFO: Predicting (in-graph) ...
# L2 loss (in-graph):0.06473003424857691
# Average error (in-graph):0.24963072378138848
import DecisionTree
using NetworkLearning, MLDataPattern, MLLabelUtils, LossFunctions
# Download the CORA dataset, and return data and citing/cited papers indices (relative to order in X,y)
(X,y), cited_papers, citing_papers = NetworkLearning.grab_cora_data()
n = nobs(X)
yᵤ = sort(unique(y))
C = length(yᵤ)
# Split data
idx = collect(1:n);
shuffle!(idx)
p = 0.5
idxtr,idxts = splitobs(idx,p)
### !!! ######
sort!(idxtr) # It is important to sort the indices,
sort!(idxts) # because of the use of the update mask
### !!! ######
Xtr = X[:,idxtr]
ytr = y[idxtr]
Xts = X[:,idxts]
############### Remove 70% of the citations to papers in the test data ##################
removed_citations = Vector{Int}() #
for (i, (ic,oc)) in enumerate(zip(cited_papers,citing_papers)) #
if ic in idxts && rand() > 0.3 #
push!(removed_citations, i) #
end #
end #
#
cited_incomplete = cited_papers[setdiff(1:nobs(cited_papers), removed_citations)] #
citing_incomplete = citing_papers[setdiff(1:nobs(citing_papers), removed_citations)] #
#
cited_removed = cited_papers[removed_citations] #
citing_removed = citing_papers[removed_citations] #
#########################################################################################
# Construct adjacencies, local model, etc
Am = sparse(NetworkLearning.generate_partial_adjacency(cited_incomplete, citing_incomplete, collect(1:n)));
AV = [adjacency(Am)]
Ml = DecisionTree.build_tree(ytr,Xtr')
# Initialize output estimates and update mask
Xo = zeros(C,n)
update = falses(n);
update[idx[findin(idx,idxts)]] = true # mark only test entities i.e. unknown as updateable
Xo[:,.!update] = convertlabel(LabelEnc.OneOfK(C), ytr ,yᵤ)
Xo[:,update] = DecisionTree.apply_tree_proba(Ml, Xts', yᵤ)'
ŷ_tree = copy(Xo[:, update])
# Construct necessary arguments for training the entity network learner
fr_train = (X)-> DecisionTree.build_tree(X[2],X[1]')
fr_exec(C) = (m,X)-> DecisionTree.apply_tree_proba(m, X', collect(1:C))'
# Train
info("Training ...")
nlmodel = NetworkLearning.fit(NetworkLearnerEnt,
Xo,
update,
AV,
fr_train, fr_exec(C);
learner = :wrn,
inference = :ic,
f_targets = x->targets(indmax,x),
normalize = true,
maxiter = 10,
α = 0.95
)
# Squared loss (with just a few citations)
ŷts = nlmodel.state.ê[:,update]
yts = convertlabel(LabelEnc.OneOfK(C), y[idxts], yᵤ)
println("\tL2 loss (few citations):", value(L2DistLoss(), yts, ŷts, AvgMode.Mean()))
println("\tAverage error (few citations):", mean(targets(indmax,yts).!=targets(indmax,ŷts)))
# Add citations (i.e. update adjacency matrices of the model)
# Function that updates an adjacency matrix given two vectors (of same length)
# of cited and citing paper; the function may be more complicated depending on
# how easy the corresponding adjacency matrix coordinates can be determined
# from the input data
function add_citations!(Am, cited, citing)
for i in 1:nobs(cited)
Am[cited[i],citing[i]] += 1
Am[citing[i],cited[i]] += 1
end
return Am
end
info("Updating adjacencies ...")
f_update(ic,oc) = x->add_citations!(x, ic, oc)
update_adjacency!(nlmodel.Adj[1], f_update(cited_removed, citing_removed))
# Run again collective inference
info("Re-running collective inference ...")
infer!(nlmodel)
# Squared loss (with all citations)
ŷts = nlmodel.state.ê[:,update]
yts = convertlabel(LabelEnc.OneOfK(C), y[idxts], yᵤ)
println("\tL2 loss (all citations):", value(L2DistLoss(), yts, ŷts, AvgMode.Mean()))
println("\tAverage error (all citations):", mean(targets(indmax,yts).!=targets(indmax,ŷts)))
The output of the above code is:
# % Total % Received % Xferd Average Speed Time Time Time Current
# Dload Upload Total Spent Left Speed
# 100 163k 100 163k 0 0 163k 0 0:00:01 0:00:01 --:--:-- 86382
# cora/
# cora/README
# cora/cora.content
# cora/cora.cites
# INFO: Training ...
# L2 loss (few citations):0.061311528508626575
# Average error (few citations):0.27843426883308714
# INFO: Updating adjacencies ...
# INFO: Re-running collective inference ...
# L2 loss (all citations):0.04990883428571481
# Average error (all citations):0.2119645494830133
The documentation is provided in Julia's native docsystem.
The package can be installed by running Pkg.add("NetworkLearning")
or, to check out the latest version, Pkg.checkout("NetworkLearning.jl")
in the Julia REPL. From v0.1.0
, only versions of Julia above 0.7 are supported. Julia v.0.6 support can be found in the support_julia_v0.6
branch (currently unmantained).
[1] S.A. Macskassy, F. Provost "Classification in networked data: A toolkit and a univariate case study", Journal of Machine learning Research 8, 2007, 935-983
[2] P. Sen, G. Namata, M. Bilgic, L. Getoor, B. Gallagher, T. Eliassi-Rad "Collective classification in network data", AI Magazine 29(3), 2008
Author: zgornel
Source Code: https://github.com/zgornel/NetworkLearning.jl
License: MIT license
1658456460
HopfieldNets.jl
NOTICE
This package is unmaintained. Its reliability is not guaranteed.
Introduction
Discrete and continuous Hopfield nets in Julia.
Usage Example
We'll restore a corrupted representation fo the letter X specified as a vector of -1's and +1's:
using HopfieldNets
include(Pkg.dir("HopfieldNets", "demo", "letters.jl"))
patterns = hcat(X, O)
n = size(patterns, 1)
net = DiscreteHopfieldNet(n)
train!(net, patterns)
settle!(net, 10, true)
Xcorrupt = copy(X)
for i = 2:7
Xcorrupt[i] = 1
end
Xrestored = associate!(net, Xcorrupt)
all(Xcorrupt .== X)
all(Xrestored .== X)
Sources
The idea for the letters demo is taken from an implementation of Hopfield nets in Ruby. The code is based on the presentation of the theory in Mackay's book and in Storkey's learning rule paper.
Author: johnmyleswhite
Source Code: https://github.com/johnmyleswhite/HopfieldNets.jl
License: View license
1658368689
Pkg.add("BackpropNeuralNet")
Pkg.clone("https://github.com/compressed/BackpropNeuralNet.jl.git")
Usage
To initialize a network of 2 inputs, 1 hidden layer with 3 neurons, and 2 outputs:
using BackpropNeuralNet
net = init_network([2, 3, 2])
# To train the network use the form `train(network, input, output)`:
train(net, [0.15, 0.7],[0.1, 0.9])
# To evaluate an input use the form `net_eval(network, inputs)`
net_eval(net, [0.15, 0.7])
History
This is a Julia implementation of a neural network based on Sergio Fierens ruby version.
Author: Compressed
Source Code: https://github.com/compressed/BackpropNeuralNet.jl
License: View license
1657934760
Depend on it
Add this to your package's pubspec.yaml file:
dependencies:
pop_network: <latest-version>
Install it You can install packages from the command line:
with Flutter:
$ flutter pub get
It is possible to perform an initial configuration using the pop_network.config
function. This function should be used when starting to build your application with some custom settings.
void main() {
await pop_network.config(baseUrl: "https:www.example.com");
runApp(const MyApp());
}
Where you can add a base url or just not configure and pass the url in Enpoint
. For more information visit the Contribution Guide
final endpoint = Endpoint(
suffixPath: 'https:www.example.com'
);
The suffixPath
can be used this way or being concatenated with a base url that is configured in the execution of the application, it doesn't have to be at the beginning but it is good to avoid errors.
void main() {
await PopNetwork.config(baseUrl: "https:www.example.com");
runApp(const MyApp());
}
final endpoint = Endpoint(
suffixPath: 'suffix/path'
);
result path: https:www.example.com/suffix/path
Some other base settings can be done like setting intectors, setting default header, etc. More details in pop_network config Guide
When the split settings are completed, just call the api:
final result = await ApiManager.request();
or
final endpoint = Endpoint(
suffixPath: 'suffix/path'
);
final result = await ApiManager.requestApi(
endpoint: endpoint,
);
It is possible to check if your device is connected to the internet using ConnectionChecker
;
final conection = await ConnectionChecker.isConnectedToInternet();
I see the gif of the operation below:
If you want to see a usage in a simple way, go to /example
folder.
It is also possible to make the request directly to the mock file that is being mapped to the functionality with ApiManager.requestMock
. For more information, go to the documentation of the Mock.
For contributes:
git checkout -b my-feature
;git commit -m 'feat: my new feature'
;git push origin my-feature
.To help maintain the chosen pattern we also create a file which is called before every commit. This file will format and pinpoint (if present) errors in the codestyle of your code. To enable this you must first copy it to git's hooks folder. If you are developing on macOS, go to the root of the project and run the command below:
cp pre-commit .git/hooks/pre-commit
After this step, it is necessary to give permission for the file to be executed. Just follow the following command:
chmod +x .git/hooks/pre-commit
Run this command:
With Flutter:
$ flutter pub add pop_network
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
pop_network: ^0.0.12
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:pop_network/pop_network.dart';
example/lib/main.dart
import 'dart:convert';
import 'package:exemple/conection_check.dart';
import 'package:exemple/data.dart';
import 'package:flutter/material.dart';
import 'package:pop_network/pop_network.dart';
Future<void> main() async {
await PopNetwork.config(
baseUrl: "https://pokeapi.co/api/v2/pokemon/",
mockedEnvironment: true,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Pokemon> list = [];
void requestApi() {
final Endpoint endpoint = Endpoint(
mockStrategy: MockCustom(),
);
ApiManager.requestApi(endpoint: endpoint).then((value) {
if (value is Success) {
final listMaps = value.data['results'] as List;
final listGenerate = List.generate(
listMaps.length, (index) => Pokemon.fromMap(listMaps[index]));
setState(() {
list.addAll(listGenerate);
});
}
});
}
List<Widget> get listWidget => list.isEmpty
? [const Text('Not request Pokemons')]
: List.generate(list.length, (index) => Text(list[index].name));
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: [
IconButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => const ConectionCheckScreen(),
));
},
icon: const Icon(Icons.connect_without_contact))
],
),
body: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: listWidget,
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: requestApi,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
class MockCustom implements MockStrategy {
@override
String? getJson() {
return jsonEncode({
"results": [
{
"name": "Pokemo",
},
{
"name": "Pokemo",
},
{
"name": "Pokemo",
},
{
"name": "Pokemo",
},
{
"name": "Pokemo",
},
{
"name": "Pokemo",
},
{
"name": "Pokemo",
},
{
"name": "Pokemo",
},
]
});
}
}
Author: PopcodeMobile
Source Code: https://github.com/PopcodeMobile/popnetwork
License: View license
1657425420
This plugin provides a CakePHP View helper for creating links to share content on numerous social networks and bookmarking sites.
The aim of the plugin is to keep things simple. It doesn't come packaged with any JavaScript and I leave design decisions up to you. You can choose whether you want to use text, images, sprites or an icon font for your links.
Social Share currently supports Delicious, Digg, Evernote, Facebook, Friend Feed, Google Bookmarks, Google+, LinkedIn, Newsvine, Pinterest, Pocket, Reddit Slashdot, simple email, StumbleUpon, Technorati, Tumblr, Twitter and WhatsApp.
Note: This branch is for CakePHP 4.x.
Install using composer: composer require drmonkeyninja/cakephp-social-share:4.*
Then add the following line to your Application.php file to load the plugin.
$this->addPlugin(\SocialShare\Plugin::class);
Also don't forget to add the helper in your AppView
:-
$this->loadHelper('SocialShare.SocialShare');
SocialShareHelper::link(string $service, string $title, mixed $url = null, array $options = [])
Returns an HTML link to share the current page for the supplied service. For example to create a link for Facebook:-
echo $this->SocialShare->link(
'facebook',
__('Share on Facebook')
);
You can easily produce a list of links to share to different social networks:-
$services = [
'facebook' => __('Share on Facebook'),
'gplus' => __('Share on Google+'),
'linkedin' => __('Share on LinkedIn'),
'twitter' => __('Share on Twitter')
];
echo '<ul>';
foreach ($services as $service => $linkText) {
echo '<li>' . $this->SocialShare->link(
$service,
$linkText
) . '</li>';
}
echo '</ul>';
Supported services:-
You can pass a URL or a routing array as the third parameter for the URL you want to share.
$options
supports the same options as HtmlHelper::link()
as well as a 'text' option for a page title you want to include when sharing the URL. For Pinterest there is an additional 'image' option for a URL to an image to share.
SocialShareHelper::href(string $service, mixed $url = null, array $options = [])
Returns an URL for sharing to the supplied service.
SocialShareHelper::fa(string $service, mixed $url = null, array $options = [])
Returns an HTML link just like SocialShare::link()
except the link text will be a relevant Font Awesome icon for the service.
For example:-
echo $this->SocialShare->fa(
'facebook',
'http://example.com'
);
Will output:-
<a href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fexample.com">
<i class="fa fa-facebook"></i>
</a>
If you need to change the icon markup output by fa()
you can override the icon class using icon_class
:-
echo $this->SocialShare->fa(
'facebook',
null,
['icon_class' => 'fa fa-facebook-square']
);
Author: Drmonkeyninja
Source Code: https://github.com/drmonkeyninja/cakephp-social-share
License: MIT license
1657225260
Expose a levelDB over the network, to be used by multiple processes, with levelUp's API.
Expose a db on the server:
var multilevel = require('multilevel');
var net = require('net');
var level = require('level');
var db = level('/my/db');
net.createServer(function (con) {
con.pipe(multilevel.server(db)).pipe(con);
}).listen(3000);
And connect to it from the client:
var multilevel = require('multilevel');
var net = require('net');
var db = multilevel.client();
var con = net.connect(3000);
con.pipe(db.createRpcStream()).pipe(con);
// asynchronous methods
db.get('foo', function () { /* */ });
// streams
db.createReadStream().on('data', function () { /* */ });
multilevel works in the browser too - via browserify - and has full support for binary data. For getting a connection between browser and server I recommend either websocket-stream, which treats binary data well, or engine.io-stream, which has websocket fallbacks.
When using a binary capable transport, require multilevel like this:
var multilevel = require('multilevel/msgpack');
This way it uses msgpack-stream instead of json-buffer which uses way less bandwidth - but needs a binary capable transport.
You can also expose custom methods and sublevels with multilevel
!
When using plugins, you must generate a manifest and require it in the client.
Here's an example:
// server.js
// create `db`
var level = require('level');
var multilevel = require('multilevel');
var db = level(PATH);
// extend `db` with a foo(cb) method
db.methods = db.methods || {};
db.methods['foo'] = { type: 'async' };
db.foo = function (cb) {
cb(null, 'bar');
};
// now write the manifest to a file
multilevel.writeManifest(db, __dirname + '/manifest.json');
// then expose `db` via shoe or any other streaming transport.
var shoe = require('shoe');
var sock = shoe(function (stream) {
stream.pipe(multilevel.server(db)).pipe(stream);
});
sock.install(http.createServer(/* ... */), '/websocket');
Manifests are generated using level-manifest, which doesn't only support async functions but e.g. streams as well. For more, check its README.
Then require the manifest on the client when bundling with browserify or in any other nodejs compatible environment.
// client.js
// instantiate a multilevel client with the `manifest.json` we just generated
var multilevel = require('multilevel');
var manifest = require('./manifest.json');
var db = multilevel.client(manifest);
// now pipe the db to the server
var stream = shoe('/websocket');
stream.pipe(db.createRpcStream()).pipe(stream);
// and you can call the custom `foo` method!
db.foo(function (err, res) {
console.log(res); // => "bar"
});
You do not want to expose every database feature to every user, you might e.g. only want to provide read-only access to some users.
Auth controls may be injected when creating the server stream.
In this example, allow read only access, unless logged in as root.
//server.js
var db = require('./setup-db'); //all your database customizations
var multilevel = require('multilevel');
//write out manifest
multilevel.writeManifest(db, __dirname + '/manifest.json');
shoe(function (stream) {
stream.pipe(multilevel.server(db, {
auth: function (user, cb) {
if (user.name == 'root' && user.pass == 'toor') {
//the data returned will be attached to the mulilevel stream
//and passed to `access`
cb(null, {name: 'root'});
} else {
cb(new Error('not authorized');
}
},
access: function (user, db, method, args) {
//`user` is the {name: 'root'} object that `auth`
//returned.
//if not a privliged user...
if (!user || user.name !== 'root') {
//do not allow any write access
if (/^put|^del|^batch|write/i.test(method)) {
throw new Error('read-only access');
}
}
})
})).pipe(stream);
});
// ...
The client authorizes by calling the auth method.
var multilevel = require('multilevel');
var shoe = require('shoe');
var stream = shoe();
var db = multilevel.client();
stream.pipe(db.createRpcStream()).pipe(stream);
db.auth({ name: 'root', pass: 'toor' }, function (err, data) {
if (err) throw err
//later, they can sign out, too.
db.deauth(function (err) {
//signed out!
});
});
The exposed DB has the exact same API as levelUp, except
db#close()
closes the connection, instead of the database.db#isOpen()
and db#isClose()
tell you if you currently have a connection to the remote db.db.on("put", ...)
are not emitted. If you need updates, you can use level-live-stream.Returns a server-stream that exposes db
, an instance of levelUp. authOpts
is optional and should be of this form:
var authOpts = {
auth: function (userData, cb) {
//call back an error, if the user is not authorized.
},
access: function (userData, db, method, args) {
//throw if this user is not authorized for this action.
}
}
It is necessary that you create one server stream per client.
Synchronoulsy write db
's manifest to path
.
Also returns the manifest as json.
Return a new client db. manifest
may optionally be provided, which will grant the client access to extensions and sublevels.
Pipe this into a server stream.
Listen for the error
event on this stream to handle / swallow reconnect events.
Authorize with the server.
Deauthorize with the server.
On my macbook pro one multilevel server handles ~15k ops/s over a local tcp socket.
∴ bench (master) : node index.js
writing "1234567890abcdef" 100 times
native : 2ms (50000 ops/s)
multilevel direct : 21ms (4762 ops/s)
multilevel network : 14ms (7143 ops/s)
writing "1234567890abcdef" 1000 times
native : 12ms (83333 ops/s)
multilevel direct : 71ms (14085 ops/s)
multilevel network : 77ms (12987 ops/s)
writing "1234567890abcdef" 10000 times
native : 88ms (113636 ops/s)
multilevel direct : 594ms (16835 ops/s)
multilevel network : 590ms (16949 ops/s)
writing "1234567890abcdef" 100000 times
native : 927ms (107875 ops/s)
multilevel direct : 10925ms (9153 ops/s)
multilevel network : 9839ms (10164 ops/s)
With npm do:
$ npm install multilevel
$ npm install
$ npm test
$ npm run test-browser
This module is proudly supported by my Sponsors!
Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my Patreon. Not sure how much of my modules you're using? Try feross/thanks!
Author: juliangruber
Source Code: https://github.com/juliangruber/multilevel
License: MIT
1657166280
Removal of stage (so CloudFormation stack deletion) that involves VPC lambda functions is very slow.
"Waiting for NetworkInterfaces associated with the Lambda Function to be cleaned up" process takes usually around 40 minutes.
While the AWS team works on improving that, the workaround for a meantime is to remove those interfaces manually, so stack deletion finalizes in reasonable time.
This plugin removes all detected network interfaces in parallel to stack deletion process.
npm install serverless-plugin-vpc-eni-cleanup
Activate plugin in serverless.yml
plugins:
- serverless-plugin-vpc-eni-cleanup
Following IAM policy needs to be ensured for plugin to work without issues
{
"Effect": "Allow",
"Action": [
"ec2:DeleteNetworkInterface",
"ec2:DetachNetworkInterface",
"ec2:DescribeNetworkInterfaces"
],
"Resource": ["*"]
}
That's it. Having that, with every sls remove
operation plugin will attempt to delete discovered network interfaces
npm test
Author: Medikoo
Source Code: https://github.com/medikoo/serverless-plugin-vpc-eni-cleanup
License: MIT license
1657093860
LevelDB-compatible module for loading p2p databases using hyperbee and hyperswarm
npm i --save networked-hyperbeedown levelup
const levelup = require('levelup')
const { once } = require('events')
const NetworkedHyperbeedown = require('networked-hyperbeedown')()
const down = new NetworkedHyperbeedown('hyper://someurlhere', {
keyEncoding: 'utf-8'
})
const db = levelup(down)
await db.open()
// Wait for an initial peer before tryinng to load data
await once(down.core, 'peer-open')
const value = await db.get('Example')
console.log('Got value from remote:', value)
const NetworkedHyperbeedown = makeNetworkedHyperbeedown({Hypercore, close, ...opts})
Creates an instance of NetworkedHyperbeeDown.
Provide a custom Hypercore
constructor and optional close
for cleaning up if you want full control.
Else you can pass in opts
which will initialize hyper-sdk
This will return a constructor for NetworkedHyperbeedown
.
const hyperbeedown = new NetworkedHyperbeedown(url)
Once you have a NetworkedHyperbeedown
reference, you can initialize storage with urls.
The hyperbeedown
instance returned can be passed to levelup
or anything else that uses abstract-leveldown
.
The url
should be a hyper://
URL which will be passed to the Hypercore
constructor.
You can pass in an actual public key in the URL if you want to load from the network (which will make it readonly) like hyper://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
.
You can also pass a custom name
for the URL which will derive a key for you like hyper://example
const url = await hyperbeedown.getURL()
If you used a custom name
for your hyperbee, you can resolve it to the actual publicly accessible URL through this.
Make sure your db has been opened before calling this.
The url
is a string.
const core = hyperbeedown.core
You can get a reference to the hypercore
with this property
Author: RangerMauve
Source Code: https://github.com/RangerMauve/networked-hyperbeedown
License: AGPL-3.0 license