1656963300
Psst — looking for a more complete solution? Check out SvelteKit and its package command which gives you more built-in features like TypeScript transpilation, type definition generation and a built-in playground to test your library.
Looking for an app template instead? Go here --> sveltejs/template
A base for building shareable Svelte components. Clone it with degit:
npx degit sveltejs/component-template my-new-component
cd my-new-component
npm install # or yarn
Your component's source code lives in src/Component.svelte
.
You can create a package that exports multiple components by adding them to the src
directory and editing src/index.js
to reexport them as named exports.
TODO
degit
so that it automates some of the setup worknpm init
(or yarn init
)Your package.json has a "svelte"
field pointing to src/index.js
, which allows Svelte apps to import the source code directly, if they are using a bundler plugin like rollup-plugin-svelte or svelte-loader (where resolve.mainFields
in your webpack config includes "svelte"
). This is recommended.
For everyone else, npm run build
will bundle your component's source code into a plain JavaScript module (dist/index.mjs
) and a UMD script (dist/index.js
). This will happen automatically when you publish your component to npm, courtesy of the prepublishOnly
hook in package.json.
Download Details:
Author: sveltejs
Source Code: https://github.com/sveltejs/component-template
License:
#svelte #javascript
1656963300
Psst — looking for a more complete solution? Check out SvelteKit and its package command which gives you more built-in features like TypeScript transpilation, type definition generation and a built-in playground to test your library.
Looking for an app template instead? Go here --> sveltejs/template
A base for building shareable Svelte components. Clone it with degit:
npx degit sveltejs/component-template my-new-component
cd my-new-component
npm install # or yarn
Your component's source code lives in src/Component.svelte
.
You can create a package that exports multiple components by adding them to the src
directory and editing src/index.js
to reexport them as named exports.
TODO
degit
so that it automates some of the setup worknpm init
(or yarn init
)Your package.json has a "svelte"
field pointing to src/index.js
, which allows Svelte apps to import the source code directly, if they are using a bundler plugin like rollup-plugin-svelte or svelte-loader (where resolve.mainFields
in your webpack config includes "svelte"
). This is recommended.
For everyone else, npm run build
will bundle your component's source code into a plain JavaScript module (dist/index.mjs
) and a UMD script (dist/index.js
). This will happen automatically when you publish your component to npm, courtesy of the prepublishOnly
hook in package.json.
Download Details:
Author: sveltejs
Source Code: https://github.com/sveltejs/component-template
License:
#svelte #javascript
1605576444
If you are coming from the background of working with angularjs, it was quite straight forward to access and manipulate the DOM there. You had access to the DOM node through element
injected in the link
function of the directive.
function link(scope, element, attrs) {
}
Or through angular.element
which was an AngularJS’s built in subset of jQuery. But this approach had its drawbacks. It made your code tightly coupled with Browser’s API.
The new Angular (2 onwards) works on multiple platforms: mobile, web workers etc. So, they have introduced a number of APIs to work as an abstraction layer between your code and platform APIs. These APIs come in the form of different reference types likeElementRef
, TemplateRef
, ViewRef
, ComponentRef
and ViewContainerRef
.
In this blog, we will see some examples of how these reference types can be used to manipulate DOM in angular. But before that let’s look at the ways to access these reference types within a Component/Directive.
DOM Queries
Angular has provided two ways to query/access various reference types within a Component/Directive. These are
These are decorators which can be used within a Component/Directive as @ViewChild
(returns a single reference) or @ViewChildren
(returns a list of references in the form of a QueryList
). These will assign the values of reference types from template to the component fields they are applied to. The basic usage is as follow:
@ViewChild(selector, {read: ReferenceType}) fieldName;
A selector can be a string representing a template reference variable, or a Component/Directive class, or a TemplateRef or a provider defined in the child component tree.
@ViewChild("myElem") template: ElementRef;
The second parameter is optional and is only required to query some reference types which can’t be inferred easily by Angular like ViewContainerRef
.
@ViewChild("myContainer", {read: ViewContainerRef}) container: ViewContainerRef;
The usage is pretty much similar to that of ViewChild/ViewChildren. The only difference is that it queries within the <ng-content>
projected elements of the component while the @ViewChild
queries within the template of the component. This will be explained better in the examples of upcoming sections.
DOM access via ElementRef
ElementRef
is a very basic abstraction layer on a DOM element in Angular. It’s an angular wrapper around the native element.
You can get hold of ElementRef in a Component or Directive in following ways:
Host element of a Component or Directive can be accessed via direct DI in the constructor.
@Component({
selector: 'app-test',
template: '<div>I am a test component</div>'
})
export class TestComponent implements OnInit {
constructor(private element: ElementRef) { }
ngOnInit() {
console.log(this.element.nativeElement);
}
}
/*
* Output:
* <app-test>
* <div>I am a test component</div>
* </app-test>
* */
@Component({
selector: 'app-test',
template: `
<div #child1>First Child</div>
<div>Second Child</div>
`
})
export class TestComponent implements OnInit {
@ViewChild("child1") firstChild: ElementRef;
constructor() { }
ngOnInit() {
console.log(this.firstChild.nativeElement);
}
}
/*
* Output: <div>First Child</div>
* */
Works in a similar manner as that of @ViewChild
, but for <ng-content>
projected elements.
// Child Component
@Component({
selector: "component-a",
template: `<ng-content></ng-content>`
})
export class ComponentA {
@ContentChild("contentChild") contentChild: ElementRef;
ngOnInit() {
console.log(this.contentChild.nativeElement);
}
}
// Parent Component
@Component({
selector: 'app-test',
template: `
<component-a>
<div #contentChild>Content Child 1</div>
<div>Content Child 2</div>
</component-a>
`
})
export class TestComponent implements OnInit {}
/*
* Output: <div>Content Child 1</div>
* */
It looks pretty straight forward that you can easily access a DOM element via ElementRef
and then manipulate the DOM by accessing the nativeElement
. Something like this:
@Component({
selector: 'app-test-component',
template: `
<div class="header">I am a header</div>
<div class="body" #body>
</div>
<div class="footer">I am a footer</div>
`
})
export class TestComponent implements AfterContentInit {
@ViewChild("body") bodyElem: ElementRef;
ngAfterContentInit(): void {
this.bodyElem.nativeElement.innerHTML = `<div>Hi, I am child added by directly calling the native APIs.</div>`;
}
}
However, the direct usage of ElementRef is discouraged by Angular Team because it directly provides the access to DOM which can make your application vulnerable to XSS attacks. It also creates tight coupling between your application and rendering layers which makes is difficult to run an app on multiple platforms.
Everything is a ‘View’ in Angular
A view is the smallest building block of an angular app’s UI. Every component has its own view. You can consider it as a group of elements which can be created and destroyed together.
A view can be classified into two types:
Displaying a view in UI can be broken down into two steps:
Embedded Views
Embedded views are created from templates defined using <ng-template>
element.
First a template needs to be accessed within a component as TemplateRef
using @ViewChild
and template reference variable. Then, an embedded view can be created from a TemplateRef
by passing a data-binding context.
const viewRef = this.template.createEmbeddedView({
name: "View 1"
});
This context is being consumed by the template in<ng-template>
.
<ng-template #template let-viewName="name">
<div>Hi, My name is {{viewName}}. I am a view created from a template</div>
</ng-template>
You can also use the $implicit
property in the context if you have only a single property to bind.
const viewRef = this.template.createEmbeddedView({
$implicit: "View 1"
});
In this case, you can skip assigning values to template variables.
<ng-template #template let-viewName>
<div>Hi, My name is {{viewName}}. I am a view created from a template</div>
</ng-template>
Till now, we have created only an instance of ViewRef
. This view is still not visible in the UI. In order to see it in the UI, we need a placeholder (a view container) to render it. This placeholder is being provided by ViewContainerRef
.
Any element can serve as a view container, however <ng-container>
is a better candidate as it is rendered as a comment and doesn’t leave any redundant element in the html DOM.
@Component({
selector: 'app-test-component',
template: `
<div class="header">I am a header</div>
<div class="body">
<ng-container #container></ng-container>
</div>
<div class="footer">I am a footer</div>
<ng-template #template let-viewName="name">
<div>Hi, My name is {{viewName}}. I am a view created from a template</div>
</ng-template>
`,
})
export class TestComponent implements AfterContentInit {
@ViewChild("template") template: TemplateRef;
@ViewChild("container", {read: ViewContainerRef}) container: ViewContainerRef;
constructor() { }
ngAfterContentInit(): void {
const viewRef = this.template.createEmbeddedView({
name: "View 1"
});
this.container.insert(viewRef);
}
}
Both <ng-container>
and <ng-template>
elements will be rendered as comments leaving the html DOM neat and clean.
The above 2 steps process of creating a view and adding it into a container can further be reduced by using the createEmbeddedView
method available in the ViewContainerRef
itself.
this.container.createEmbeddedView(this.template, {
name: "View 1"
});
This can be further simplified by moving the whole view creation logic from component class to the template using ngTemplateOutlet
and ngTemplateOutletContext
.
@Component({
selector: 'app-test-component',
template: `
<div class="header">I am a header</div>
<div class="body">
<ng-container [ngTemplateOutlet]="template" [ngTemplateOutletContext]="{name: 'View 1'}"></ng-container>
</div>
<div class="footer">I am a footer</div>
<ng-template #template let-viewName="name">
<div>Hi, My name is {{viewName}}. I am a view created from a template</div>
</ng-template>
`
})
export class TestComponent {}
Host Views
Host Views are quite similar to Embedded View. The only difference is that the Host Views are created from components instead of templates.
In order to create a host view, first you need to create a ComponentFactory
of the component you want to render using ComponentFactoryResolver
.
constructor(
private componentFactoryResolver: ComponentFactoryResolver
) {
this.someComponentFactory = this.componentFactoryResolver.resolveComponentFactory(SomeComponent);
}
Then, a dynamic instance of the component is created by passing an Injector
instance to the factory. Every component should be bound to an instance of Injector
. You can use the injector of the parent component for the dynamically created components.
const componentRef = this.someComponentFactory.create(this.injector);
const viewRef = componentRef.hostView;
Rendering a host view is almost similar to rendering an embedded view. You can directly insert it into a view container.
@Component({
selector: 'app-test-component',
template: `
<div class="header">I am a header</div>
<div class="body">
<ng-container #container></ng-container>
</div>
<div class="footer">I am a footer</div>
`,
})
export class TestComponentComponent implements AfterContentInit {
@ViewChild("container", {read: ViewContainerRef}) container: ViewContainerRef;
private someComponentFactory: ComponentFactory<SomeComponent>;
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector
) {
this.someComponentFactory = this.componentFactoryResolver.resolveComponentFactory(SomeComponent);
}
ngAfterContentInit(): void {
const componentRef = this.someComponentFactory.create(this.injector);
const viewRef = componentRef.hostView;
this.container.insert(viewRef);
}
}
Or by directly calling the createComponent
method of ViewContainerRef
and passing the component factory instance.
this.container.createComponent(this.someComponentFactory);
Now, similar to embedded view, we can also shift the whole logic of host view creation in template itself using ngComponentOutlet
.
@Component({
selector: 'app-test-component',
template: `
<div class="header">I am a header</div>
<div class="body">
<ng-container [ngComponentOutlet]="comp"></ng-container>
</div>
<div class="footer">I am a footer</div>
`
})
export class TestComponent {
comp = SomeComponent;
}
Don’t forget to store the reference of the component class in parent component’s field. The template has access only to the fields of the components.
Here we come to an end. Let’s conclude what we have understood till now.
ElementRef
, TemplateRef
, ViewRef
, ComponentRef
and ViewContainerRef
.@ViewChild
and @ContentChild
.ElementRef
. However, manipulating this element directly is discouraged because of security reasons.So, that’s it for today about understanding DOM manipulation in Angular.
Originally published by medium
1624653660
A useful tool several businesses implement for answering questions that potential customers may have is a chatbot. Many programming languages give web designers several ways on how to make a chatbot for their websites. They are capable of answering basic questions for visitors and offer innovation for businesses.
With the help of programming languages, it is possible to create a chatbot from the ground up to satisfy someone’s needs.
Before building a chatbot, it is ideal for web designers to determine how it will function on a website. Several chatbot duties center around fulfilling customers’ needs and questions or compiling and optimizing data via transactions.
Some benefits of implementing chatbots include:
Some programmers may choose to design a chatbox to function through predefined answers based on the questions customers may input or function by adapting and learning via human input.
#chatbots #latest news #the best way to build a chatbot in 2021 #build #build a chatbot #best way to build a chatbot
1571046022
Cryptocurrency is a decentralized digital currency that uses encryption techniques to regulate the generation of currency units and to verify the transfer of funds. Anonymity, decentralization, and security are among its main features. Cryptocurrency is not regulated or tracked by any centralized authority, government, or bank.
Blockchain, a decentralized peer-to-peer (P2P) network, which is comprised of data blocks, is an integral part of cryptocurrency. These blocks chronologically store information about transactions and adhere to a protocol for inter-node communication and validating new blocks. The data recorded in blocks cannot be altered without the alteration of all subsequent blocks.
In this article, we are going to explain how you can create a simple blockchain using the Python programming language.
Here is the basic blueprint of the Python class we’ll use for creating the blockchain:
class Block(object):
def __init__():
pass
#initial structure of the block class
def compute_hash():
pass
#producing the cryptographic hash of each block
class BlockChain(object):
def __init__(self):
#building the chain
def build_genesis(self):
pass
#creating the initial block
def build_block(self, proof_number, previous_hash):
pass
#builds new block and adds to the chain
@staticmethod
def confirm_validity(block, previous_block):
pass
#checks whether the blockchain is valid
def get_data(self, sender, receiver, amount):
pass
# declares data of transactions
@staticmethod
def proof_of_work(last_proof):
pass
#adds to the security of the blockchain
@property
def latest_block(self):
pass
#returns the last block in the chain
Now, let’s explain how the blockchain class works.
Here is the code for our initial block class:
import hashlib
import time
class Block(object):
def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
self.index = index
self.proof_number = proof_number
self.previous_hash = previous_hash
self.data = data
self.timestamp = timestamp or time.time()
@property
def compute_hash(self):
string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
return hashlib.sha256(string_block.encode()).hexdigest()
As you can see above, the class constructor or initiation method ( init()) above takes the following parameters:
self
— just like any other Python class, this parameter is used to refer to the class itself. Any variable associated with the class can be accessed using it.
index
— it’s used to track the position of a block within the blockchain.
previous_hash
— it used to reference the hash of the previous block within the blockchain.
data—it
gives details of the transactions done, for example, the amount bought.
timestamp—it
inserts a timestamp for all the transactions performed.
The second method in the class, compute_hash , is used to produce the cryptographic hash of each block based on the above values.
As you can see, we imported the SHA-256 algorithm into the cryptocurrency blockchain project to help in getting the hashes of the blocks.
Once the values have been placed inside the hashing module, the algorithm will return a 256-bit string denoting the contents of the block.
So, this is what gives the blockchain immutability. Since each block will be represented by a hash, which will be computed from the hash of the previous block, corrupting any block in the chain will make the other blocks have invalid hashes, resulting in breakage of the whole blockchain network.
The whole concept of a blockchain is based on the fact that the blocks are “chained” to each other. Now, we’ll create a blockchain class that will play the critical role of managing the entire chain.
It will keep the transactions data and include other helper methods for completing various roles, such as adding new blocks.
Let’s talk about the helper methods.
Here is the code:
class BlockChain(object):
def __init__(self):
self.chain = []
self.current_data = []
self.nodes = set()
self.build_genesis()
The init() constructor method is what instantiates the blockchain.
Here are the roles of its attributes:
self.chain — this variable stores all the blocks.
self.current_data — this variable stores information about the transactions in the block.
self.build_genesis() — this method is used to create the initial block in the chain.
The build_genesis()
method is used for creating the initial block in the chain, that is, a block without any predecessors. The genesis block is what represents the beginning of the blockchain.
To create it, we’ll call the build_block()
method and give it some default values. The parameters proof_number
and previous_hash
are both given a value of zero, though you can give them any value you desire.
Here is the code:
def build_genesis(self):
self.build_block(proof_number=0, previous_hash=0)
def build_block(self, proof_number, previous_hash):
block = Block(
index=len(self.chain),
proof_number=proof_number,
previous_hash=previous_hash,
data=self.current_data
)
self.current_data = []
self.chain.append(block)
return block
The confirm_validity
method is critical in examining the integrity of the blockchain and making sure inconsistencies are lacking.
As explained earlier, hashes are pivotal for realizing the security of the cryptocurrency blockchain, because any slight alteration in an object will result in the creation of an entirely different hash.
Thus, the confirm_validity
method utilizes a series of if statements to assess whether the hash of each block has been compromised.
Furthermore, it also compares the hash values of every two successive blocks to identify any anomalies. If the chain is working properly, it returns true; otherwise, it returns false.
Here is the code:
def confirm_validity(block, previous_block):
if previous_block.index + 1 != block.index:
return False
elif previous_block.compute_hash != block.previous_hash:
return False
elif block.timestamp <= previous_block.timestamp:
return False
return True
The get_data
method is important in declaring the data of transactions on a block. This method takes three parameters (sender’s information, receiver’s information, and amount) and adds the transaction data to the self.current_data list.
Here is the code:
def get_data(self, sender, receiver, amount):
self.current_data.append({
'sender': sender,
'receiver': receiver,
'amount': amount
})
return True
In blockchain technology, Proof of Work (PoW) refers to the complexity involved in mining or generating new blocks on the blockchain.
For example, the PoW can be implemented by identifying a number that solves a problem whenever a user completes some computing work. Anyone on the blockchain network should find the number complex to identify but easy to verify — this is the main concept of PoW.
This way, it discourages spamming and compromising the integrity of the network.
In this article, we’ll illustrate how to include a Proof of Work algorithm in a blockchain cryptocurrency project.
Finally, the latest_block() helper method is used for retrieving the last block on the network, which is actually the current block.
Here is the code:
def latest_block(self):
return self.chain[-1]
Now, this is the most exciting section!
Initially, the transactions are kept in a list of unverified transactions. Mining refers to the process of placing the unverified transactions in a block and solving the PoW problem. It can be referred to as the computing work involved in verifying the transactions.
If everything has been figured out correctly, a block is created or mined and joined together with the others in the blockchain. If users have successfully mined a block, they are often rewarded for using their computing resources to solve the PoW problem.
Here is the mining method in this simple cryptocurrency blockchain project:
def block_mining(self, details_miner):
self.get_data(
sender="0", #it implies that this node has created a new block
receiver=details_miner,
quantity=1, #creating a new block (or identifying the proof number) is awarded with 1
)
last_block = self.latest_block
last_proof_number = last_block.proof_number
proof_number = self.proof_of_work(last_proof_number)
last_hash = last_block.compute_hash
block = self.build_block(proof_number, last_hash)
return vars(block)
Here is the whole code for our crypto blockchain class in Python:
import hashlib
import time
class Block(object):
def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
self.index = index
self.proof_number = proof_number
self.previous_hash = previous_hash
self.data = data
self.timestamp = timestamp or time.time()
@property
def compute_hash(self):
string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
return hashlib.sha256(string_block.encode()).hexdigest()
def __repr__(self):
return "{} - {} - {} - {} - {}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
class BlockChain(object):
def __init__(self):
self.chain = []
self.current_data = []
self.nodes = set()
self.build_genesis()
def build_genesis(self):
self.build_block(proof_number=0, previous_hash=0)
def build_block(self, proof_number, previous_hash):
block = Block(
index=len(self.chain),
proof_number=proof_number,
previous_hash=previous_hash,
data=self.current_data
)
self.current_data = []
self.chain.append(block)
return block
@staticmethod
def confirm_validity(block, previous_block):
if previous_block.index + 1 != block.index:
return False
elif previous_block.compute_hash != block.previous_hash:
return False
elif block.timestamp <= previous_block.timestamp:
return False
return True
def get_data(self, sender, receiver, amount):
self.current_data.append({
'sender': sender,
'receiver': receiver,
'amount': amount
})
return True
@staticmethod
def proof_of_work(last_proof):
pass
@property
def latest_block(self):
return self.chain[-1]
def chain_validity(self):
pass
def block_mining(self, details_miner):
self.get_data(
sender="0", #it implies that this node has created a new block
receiver=details_miner,
quantity=1, #creating a new block (or identifying the proof number) is awared with 1
)
last_block = self.latest_block
last_proof_number = last_block.proof_number
proof_number = self.proof_of_work(last_proof_number)
last_hash = last_block.compute_hash
block = self.build_block(proof_number, last_hash)
return vars(block)
def create_node(self, address):
self.nodes.add(address)
return True
@staticmethod
def get_block_object(block_data):
return Block(
block_data['index'],
block_data['proof_number'],
block_data['previous_hash'],
block_data['data'],
timestamp=block_data['timestamp']
)
blockchain = BlockChain()
print("GET READY MINING ABOUT TO START")
print(blockchain.chain)
last_block = blockchain.latest_block
last_proof_number = last_block.proof_number
proof_number = blockchain.proof_of_work(last_proof_number)
blockchain.get_data(
sender="0", #this means that this node has constructed another block
receiver="LiveEdu.tv",
amount=1, #building a new block (or figuring out the proof number) is awarded with 1
)
last_hash = last_block.compute_hash
block = blockchain.build_block(proof_number, last_hash)
print("WOW, MINING HAS BEEN SUCCESSFUL!")
print(blockchain.chain)
Now, let’s try to run our code to see if we can generate some digital coins…
Wow, it worked!
That is it!
We hope that this article has assisted you to understand the underlying technology that powers cryptocurrencies such as Bitcoin and Ethereum.
We just illustrated the basic ideas for making your feet wet in the innovative blockchain technology. The project above can still be enhanced by incorporating other features to make it more useful and robust.
Thanks for reading !
Do you have any comments or questions? Please share them below.
#python #cryptocurrency
1603597204
I recently looked at Svelte as I’d been hearing a lot about it and was curious to see how it measured up against Vue, which I use for pretty much all my frontend work. In particular, I was curious if it would be a better fit for building web components, as it seemed to have some major advantages compared to Vue. I decided to write this article because I think Svelte could be the perfect framework for building web components, but currently there are some things which are holding it back, and if you are considering using it, you should probably know about them, and the possible workarounds before you make your decision about which framework to use.
In theory, all you need to do to convert your existing Svelte app into a web component, is add the <svelte:options tag="component-name">
somewhere in your .svelte file with whatever you want that component to be named, and enable the customElement: true
option in the compiler. That’s it! Once that compiles down, all you need to do is include the built bundle, and you can start using your shiny new web component.
That looks way too easy, so where do the problems start? Well, as usual, the “Hello World” works as expected, but as soon as you try to do anything else, you start running into issues. I will list all the issues I have encountered so far here, including any workarounds and I will try to link to the relevant Github issues where I can.
https://github.com/sveltejs/svelte/issues/3594
So you’ve made it past the “Hello World” web component, and want to start making something a bit more advanced, and you’ve created another svelte component. You don’t want to export it as a web component, you just want to use it inside your main component, but that won’t work.
// App.svelte
<svelte:options tag="my-awesome-component" />
<script>
import OtherComponent from './OtherComponent.svelte';
</script>
<OtherComponent />
And in a separate file we have:
// OtherComponent.svelte
<p>Hello World!</p>
Builds fine, but when you try to use it:
TypeError: new.target does not define a custom element
The way you can fix this is to add <svelte:options tag="some-name">
to every component that you use. This forces you to create a web component out of every single svelte element that you use in your code.
#web-components #frontend-development #web-development #svelte #javascript