d3 | Bring data to life with SVG , Canvas and HTML | Data Visualization library
kandi X-RAY | d3 Summary
Support
Quality
Security
License
Reuse
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
d3 Key Features
d3 Examples and Code Snippets
private Map toD3Format(Iterator> result) { List> nodes = new ArrayList<>(); List> rels = new ArrayList<>(); int i = 0; while (result.hasNext()) { Map row = result.next(); nodes.add(map("title", row.get("movie"), "label", "movie")); int target = i; i++; for (Object name : (Collection) row.get("cast")) { Map actor = map("title", name, "label", "actor"); int source = nodes.indexOf(actor); if (source == -1) { nodes.add(actor); source = i++; } rels.add(map("source", source, "target", target)); } } return map("nodes", nodes, "links", rels); }
julia> function simulation(n_experiments=100)
chains = rand.(fill(DiscreteUniform(1, 6), 3), n_experiments)
return (1/n_experiments) * mapreduce(+, chains...) do d1, d2, d3
(d1 == 6 && d2 != 6 && d3 != 6 && d2 != d3) || (d1 != 6 && d2 == 6 && d3 != 6 && d1 != d3) || (d1 != 6 && d2 != 6 && d3 == 6 && d1 != d2)
end
end
simulation (generic function with 1 method)
julia> simulation(10_000)
0.279
julia> count(Iterators.product(1:6, 1:6, 1:6)) do (d1, d2, d3)
(d1 == 6 && d2 != 6 && d3 != 6 && d2 != d3) || (d1 != 6 && d2 == 6 && d3 != 6 && d1 != d3) || (d1 != 6 && d2 != 6 && d3 == 6 && d1 != d2)
end
60
julia> 60 / 6^3
0.2777777777777778
julia> @generated function condition(xs::NTuple{N,<:Any}) where {N}
offdiagonals = ((i, j) for i = 1:N for j = (i+1):N)
names = Symbol.(:xs, 1:N)
assignments = [:($(names[i]) = xs[$i]) for i = 1:N]
comparisons = [:($(names[i]) != $(names[j])) for (i, j) in offdiagonals]
condition = Expr(:&&, :(maximum(xs) == 6), comparisons...)
return quote
$(assignments...)
$condition
end
end
condition (generic function with 1 method)
julia> @code_warntype condition((1,2,3))
MethodInstance for condition(::Tuple{Int64, Int64, Int64})
from condition(xs::Tuple{Vararg{var"#s17", N}} where var"#s17") where N in Main at REPL[71]:1
Static Parameters
N = 3
Arguments
#self#::Core.Const(condition)
xs::Tuple{Int64, Int64, Int64}
Locals
xs3::Int64
xs2::Int64
xs1::Int64
Body::Bool
1 ─ (xs1 = Base.getindex(xs, 1))
│ (xs2 = Base.getindex(xs, 2))
│ (xs3 = Base.getindex(xs, 3))
│ %4 = Main.maximum(xs)::Int64
│ %5 = (%4 == 6)::Bool
└── goto #7 if not %5
2 ─ %7 = (xs1 != xs2)::Bool
└── goto #6 if not %7
3 ─ %9 = (xs1 != xs3)::Bool
└── goto #5 if not %9
4 ─ %11 = (xs2 != xs3)::Bool
└── return %11
5 ─ return false
6 ─ return false
7 ─ return false
julia> function simulation(n_experiments=100)
(1/n_experiments) * sum(1:n_experiments) do _
dice = (rand(1:6), rand(1:6), rand(1:6))
condition(dice)
end
end
simulation (generic function with 2 methods)
julia> @time simulation(10_000_000)
0.157303 seconds
0.2777498
for(int i = 0; i < rank.length; i++){
for (int j = 0; j < suit.length; j++){
System.out.println(suit[j] + rank[i]);
}
}
CA
DA
SA
HA
C2
D2
S2
H2
C3
D3
S3
H3
C4
D4
S4
H4
C5
D5
S5
H5
C6
D6
S6
H6
C7
D7
S7
H7
C8
D8
S8
H8
C9
D9
S9
H9
C10
D10
S10
H10
CJ
DJ
SJ
HJ
CQ
DQ
SQ
HQ
CK
DK
SK
HK
for(int i = 0; i < rank.length; i++){
for (int j = 0; j < suit.length; j++){
deck[4 * i + j] = suit[j] + rank[i];
}
}
treeData:any={...}
margin = { top: 0, right: 30, bottom: 0, left: 30 };
duration = 750;
width: number;
height: number;
svg: any;
root: any;
i = 0;
treemap: any;
update(source:any){
...
}
collapse(d: any) {
if (d.children) {
d._children = d.children;
d._children.forEach((d:any)=>this.collapse(d));
d.children = null;
}
}
click(d: any) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
this.update(d);
}
diagonal(s: any, d: any) {
const path = `M ${s.y} ${s.x}
C ${(s.y + d.y) / 2} ${s.x},
${(s.y + d.y) / 2} ${d.x},
${d.y} ${d.x}`;
return path;
}
//in stead of use
.attr('transform', function (d: any) {
return 'translate(' + source.y0 + ',' + source.x0 + ')';
})
//we use
.attr('transform', (d: any) => {
return 'translate(' + source.y0 + ',' + source.x0 + ')';
})
ngOnInit(){
this.svg = d3
.select('#d3noob')
.append('svg')
.attr('viewBox','0 0 900 500')
.append('g')
.attr(
'transform',
'translate(' + (this.margin.left+inc) + ',' + this.margin.top + ')'
);
// declares a tree layout and assigns the size
this.treemap = d3.tree().size([this.height, this.width]);
// Assigns parent, children, height, depth
this.root = d3.hierarchy(this.treeData, (d: any) => {
return d.children;
});
this.root.x0 = this.height / 2;
this.root.y0 = 0;
// Collapse after the second level
this.root.children.forEach((d:any) => {
this.collapse(d);
});
this.update(this.root);
}
update(source: any) {
// Assigns the x and y position for the nodes
const treeData = this.treemap(this.root);
// Compute the new tree layout.
const nodes = treeData.descendants();
const links = treeData.descendants().slice(1);
// Normalize for fixed-depth.
nodes.forEach((d: any) => {
d.y = d.depth * 180;
});
// ****************** Nodes section ***************************
// Update the nodes...
const node = this.svg.selectAll('g.node').data(nodes, (d: any) => {
return d.id || (d.id = ++this.i);
});
// Enter any new modes at the parent's previous position.
const nodeEnter = node
.enter()
.append('g')
.attr('class', 'node')
.attr('transform', (d: any) => {
return 'translate(' + source.y0 + ',' + source.x0 + ')';
})
.on('click', (_, d) => this.click(d));
// Add Circle for the nodes
nodeEnter
.append('circle')
.attr('class', (d:any)=> d._children?'node fill':'node')
.attr('r', 1e-6)
// Add labels for the nodes
nodeEnter
.append('text')
.attr('dy', '.35em')
.attr('x', (d) => {
return d.children || d._children ? -13 : 13;
})
.attr('text-anchor', (d: any) => {
return d.children || d._children ? 'end' : 'start';
})
.text((d) => {
return d.data.name;
});
// UPDATE
const nodeUpdate = nodeEnter.merge(node);
// Transition to the proper position for the node
nodeUpdate
.transition()
.duration(this.duration)
.attr('transform', (d: any) => {
return 'translate(' + d.y + ',' + d.x + ')';
});
// Update the node attributes and style
nodeUpdate
.select('circle.node')
.attr('r', 10)
.attr('class', (d:any)=> d._children?'node fill':'node')
.attr('cursor', 'pointer');
// Remove any exiting nodes
const nodeExit = node
.exit()
.transition()
.duration(this.duration)
.attr('transform', (d: any) => {
return 'translate(' + source.y + ',' + source.x + ')';
})
.remove();
// On exit reduce the node circles size to 0
nodeExit.select('circle').attr('r', 1e-6);
// On exit reduce the opacity of text labels
nodeExit.select('text').style('fill-opacity', 1e-6);
// ****************** links section ***************************
// Update the links...
const link = this.svg.selectAll('path.link').data(links, (d: any) => {
return d.id;
});
// Enter any new links at the parent's previous position.
const linkEnter = link
.enter()
.insert('path', 'g')
.attr('class', 'link')
.attr('d', (d: any) => {
const o = { x: source.x0, y: source.y0 };
return this.diagonal(o, o);
});
// UPDATE
const linkUpdate = linkEnter.merge(link);
// Transition back to the parent element position
linkUpdate
.transition()
.duration(this.duration)
.attr('d', (d: any) => {
return this.diagonal(d, d.parent);
});
// Remove any exiting links
const linkExit = link
.exit()
.transition()
.duration(this.duration)
.attr('d', (d: any) => {
const o = { x: source.x, y: source.y };
return this.diagonal(o, o);
})
.remove();
// Store the old positions for transition.
nodes.forEach((d: any) => {
d.x0 = d.x;
d.y0 = d.y;
});
}
this.svg = d3
.select('#d3noob')
.append('svg')
.attr('viewBox','0 0 960 500')
.append('g')
.attr(
'transform',
'translate(' + (this.margin.left+inc) + ',' + this.margin.top + ')'
);
@Input()treeData:any={}
@Input()margin = { top: 0, right: 30, bottom: 0, left: 30 };
@Input()duration = 750;
fontSize=fromEvent(window,'resize').pipe(
startWith(null),
map(_=>{
return window.innerWidth>960?'14px':14*960/window.innerWidth+'px'
}),
updateSize() {
this.width = this.wrapper.nativeElement.getBoundingClientRect().width
this.svg
.attr('preserveAspectRatio', 'xMidYMid meet')
.attr('width', '100%')
.attr('height', this.height + 'px')
.attr('viewBox', ''+(-this.margin.left)+' 0 ' + this.width + ' ' + this.height);
}
// Normalize for fixed-depth.
nodes.forEach((d: any) => {
d.y = (d.depth * (this.width-this.margin.left-this.margin.right))
/ this.maxDepth;
});
this.maxDepth = this.depthOfTree(this.treeData);
depthOfTree(ptr: any, maxdepth: number = 0) {
if (ptr == null || !ptr.children) return maxdepth;
for (let it of ptr.children)
maxdepth = Math.max(maxdepth, this.depthOfTree(it));
return maxdepth + 1;
}
margin = { top: 0, right: 130, bottom: 0, left: 80 };
const w = 1078;
const h = 666;
const padding = 70;
const svg = d3
.select("#svg-container")
.append("svg")
.attr("width", w)
.attr("height", h);
const months = Array(12)
.fill(0)
.map((v, i) => new Date(2021, i, 1));
const yScale = d3
.scaleTime()
.domain([months[11], months[0]])
.range([h - padding, padding]);
const yAxis = d3
.axisLeft(yScale)
.tickValues(months)
.tickFormat(d3.timeFormat("%B %d"));
svg
.append("g")
.attr("transform", "translate(" + padding + ", -20)")
.attr("id", "y-axis")
.call(yAxis);
body {
background: gray;
}
svg {
background: white;
}
function beforeOrAfter() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const [hA,...vs] = sh.getDataRange().getValues();
let idx = {};
hA.forEach((h,i) => {idx[h]=i;});
vs.forEach((r,i) => {
let d1 = new Date(r[idx['Date 1']]).valueOf();
let d3 = new Date(r[idx['Date 3']]).valueOf();
let ba = r[idx['Before or After']];
if(d1 > d3 && ba != 'After') {
sh.getRange(i+2,idx['Before or After'] + 1).setValue("AFTER").setBackground('#ffff00');
}
if(d1 < d3 && ba != 'Before') {
sh.getRange(i+2,idx['Before or After'] + 1).setValue("BEFORE").setBackground('#ffff00');
}
});
}
print d1 = dynamic({"B0": "Standard", "B12": "Standard1", "B13": "Standard5"}),
d2 = dynamic({"B1":"Basic0", "B5": "Basic09", "B19": "Basic12"})
| project d3 = bag_merge(d1, d2)
let d1 = toscalar(
cluster('mycluster').database('my_database').Sizes
| distinct Name, Size, External
| where isempty(Size)
| extend p = pack(Name, External)
| summarize dict=make_bag(p)
);
let d2 = toscalar(
cluster('mycluster').database('my_database').Sizes
| distinct Name, Size, External
| where not(isempty(Size))
| extend o = pack(Name, Parent)
| summarize dict=make_bag(o)
);
print d = bag_merge(d1, d2)
SELECT p.id
FROM project p
JOIN project_data d ON p.id = d.project_id AND ((d.field_id = 1 AND d.value != "") OR (d.field_id = 3 AND d.value > 100))
GROUP BY p.id
HAVING COUNT(DISTINCT d.field_id) = 2
SELECT p.id
FROM project p
LEFT JOIN project_data d1 ON p.id = d1.project_id AND d1.field_id = 3
LEFT JOIN project_data d2 ON p.id = d2.project_id AND d2.field_id = 1
LEFT JOIN project_data d3 ON p.id = d3.project_id AND d3.field_id = 11
WHERE (d1.value < 110 AND d1.value > 100) AND (d2.value <> '') AND (d3.value = '' OR d3.value IS NULL);
d1 = {'DE': [1, 2, 3], 'BE': [3, 4, 5], 'AT': [5, 6, 7]}
df1 = pd.DataFrame(data=d1)
df1['technology'] = 'solar'
d2 = {'DE': [5, 7, 9], 'BE': [4, 6, 2], 'AT': [3, 5, 2]}
df2 = pd.DataFrame(data=d2)
df2['technology'] = 'wind_onshore'
d3 = {'DE': [1, 5, 4], 'BE': [5, 2, 1], 'AT': [3, 6, 1]}
df3 = pd.DataFrame(data=d3)
df3['technology'] = 'wind_offshore'
combined_df = pd.concat((df1,df2,df3))
wide_df = combined_df.pivot(
values='DE',
columns='technology',
)
wide_df
Sub FindPersonsData()
Dim PN As Variant
Dim AN As Variant
Dim ws2 As Worksheet
Dim ws1 As Worksheet
Dim RowCalc As Range
Dim Source As Range, arrDays, d, d3, rowDay, hrs
Set ws1 = Sheets("Input_Form")
Set ws2 = Sheets("DoNotDelete_Source")
PN = ws1.Range("Person_Num").Value
AN = ws1.Range("Assignment_Num").Value
Set Source = ws2.Range("Source")
arrDays = Array("Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
'set all cells to default zero hrs
For Each d In arrDays
d3 = Left(d, 3) 'short day name
ws1.Range(d3 & "RegHr").Value = 0
ws1.Range(d3 & "OTHr").Value = 0
Next d
'loop data and find any existing data
For Each RowCalc In Source.Rows 'must specify `Rows` here, otherwise it will be `Cells`
'no point in reading a bunch of cells if the first value match fails...
If RowCalc.Cells(1).Value = PN Then
If RowCalc.Cells(2).Value = AN Then
rowDay = RowCalc.Cells(5).Value
For Each d In arrDays
If rowDay = d Then
d3 = Left(d, 3)
hrs = RowCalc.Cells(8).Value
Select Case RowCalc.Cells(7).Value
Case "Regular Hours": ws1.Range(d3 & "RegHr").Value = hrs
Case "Overtime": ws1.Range(d3 & "OTHr").Value = hrs
End Select
End If
Next d
End If
End If
Next
End Sub
Trending Discussions on d3
Trending Discussions on d3
QUESTION
I'm trying to install eth-brownie using 'pipx install eth-brownie' but I get an error saying
pip failed to build package: cytoolz
Some possibly relevant errors from pip install:
build\lib.win-amd64-3.10\cytoolz\functoolz.cp310-win_amd64.pyd : fatal error LNK1120: 1 unresolved externals
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.29.30133\\bin\\HostX86\\x64\\link.exe' failed with exit code 1120
I've had a look at the log file and it shows that it failed to build cytoolz. It also mentions "ALERT: Cython not installed. Building without Cython.". From my limited understanding Cytoolz is apart of Cython so i think the reason why the installation for eth-brownie failed is because it could not build cytoolz as it was trying to build it without Cython. The thing is I already have cython installed:
C:\Users\alaiy>pip install cython
Requirement already satisfied: cython in c:\python310\lib\site-packages (0.29.24)
Extract from the log file (I can paste the whole thing but its lengthy):
Building wheels for collected packages: bitarray, cytoolz, lru-dict, parsimonious, psutil, pygments-lexer-solidity, varint, websockets, wrapt
Building wheel for bitarray (setup.py): started
Building wheel for bitarray (setup.py): finished with status 'done'
Created wheel for bitarray: filename=bitarray-1.2.2-cp310-cp310-win_amd64.whl size=55783 sha256=d4ae97234d659ed9ff1f0c0201e82c7e321bd3f4e122f6c2caee225172e7bfb2
Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\1d\29\a8\5364620332cc833df35535f54074cf1e51f94d07d2a660bd6d
Building wheel for cytoolz (setup.py): started
Building wheel for cytoolz (setup.py): finished with status 'error'
Running setup.py clean for cytoolz
Building wheel for lru-dict (setup.py): started
Building wheel for lru-dict (setup.py): finished with status 'done'
Created wheel for lru-dict: filename=lru_dict-1.1.7-cp310-cp310-win_amd64.whl size=12674 sha256=6a7e7b2068eb8481650e0a2ae64c94223b3d2c018f163c5a0e7c1d442077450a
Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\47\0a\dc\b156cb52954bbc1c31b4766ca3f0ed9eae9b218812bca89d7b
Building wheel for parsimonious (setup.py): started
Building wheel for parsimonious (setup.py): finished with status 'done'
Created wheel for parsimonious: filename=parsimonious-0.8.1-py3-none-any.whl size=42724 sha256=f9235a9614af0f5204d6bb35b8bd30b9456eae3021b5c2a9904345ad7d07a49d
Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\b1\12\f1\7a2f39b30d6780ae9f2be9a52056595e0d97c1b4531d183085
Building wheel for psutil (setup.py): started
Building wheel for psutil (setup.py): finished with status 'done'
Created wheel for psutil: filename=psutil-5.8.0-cp310-cp310-win_amd64.whl size=246135 sha256=834ab1fd1dd0c18e574fc0fbf07922e605169ac68be70b8a64fb90c49ad4ae9b
Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\12\a3\6d\615295409067d58a62a069d30d296d61d3ac132605e3a9555c
Building wheel for pygments-lexer-solidity (setup.py): started
Building wheel for pygments-lexer-solidity (setup.py): finished with status 'done'
Created wheel for pygments-lexer-solidity: filename=pygments_lexer_solidity-0.7.0-py3-none-any.whl size=7321 sha256=46355292f790d07d941a745cd58b64c5592e4c24357f7cc80fe200c39ab88d32
Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\36\fd\bc\6ff4fe156d46016eca64c9652a1cd7af6411070c88acbeabf5
Building wheel for varint (setup.py): started
Building wheel for varint (setup.py): finished with status 'done'
Created wheel for varint: filename=varint-1.0.2-py3-none-any.whl size=1979 sha256=36b744b26ba7534a494757e16ab6e171d9bb60a4fe4663557d57034f1150b678
Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\39\48\5e\33919c52a2a695a512ca394a5308dd12626a40bbcd288de814
Building wheel for websockets (setup.py): started
Building wheel for websockets (setup.py): finished with status 'done'
Created wheel for websockets: filename=websockets-9.1-cp310-cp310-win_amd64.whl size=91765 sha256=a00a9c801269ea2b86d72c0b0b654dc67672519721afeac8f912a157e52901c0
Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\79\f7\4e\873eca27ecd6d7230caff265283a5a5112ad4cd1d945c022dd
Building wheel for wrapt (setup.py): started
Building wheel for wrapt (setup.py): finished with status 'done'
Created wheel for wrapt: filename=wrapt-1.12.1-cp310-cp310-win_amd64.whl size=33740 sha256=ccd729b6e3915164ac4994aef731f21cd232466b3f6c4823c9fda14b07e821c3
Stored in directory: c:\users\alaiy\appdata\local\pip\cache\wheels\8e\61\d3\d9e7053100177668fa43216a8082868c55015f8706abd974f2
Successfully built bitarray lru-dict parsimonious psutil pygments-lexer-solidity varint websockets wrapt
Failed to build cytoolz
Installing collected packages: toolz, eth-typing, eth-hash, cytoolz, six, pyparsing, eth-utils, varint, urllib3, toml, rlp, pyrsistent, pycryptodome, py, pluggy, parsimonious, packaging, netaddr, multidict, iniconfig, idna, hexbytes, eth-keys, colorama, charset-normalizer, certifi, base58, attrs, atomicwrites, yarl, typing-extensions, requests, python-dateutil, pytest, multiaddr, jsonschema, inflection, eth-rlp, eth-keyfile, eth-abi, chardet, bitarray, async-timeout, websockets, wcwidth, tomli, sortedcontainers, semantic-version, regex, pywin32, pytest-forked, pyjwt, pygments, protobuf, platformdirs, pathspec, mythx-models, mypy-extensions, lru-dict, ipfshttpclient, execnet, eth-account, dataclassy, click, asttokens, aiohttp, wrapt, web3, vyper, vvm, tqdm, pyyaml, pythx, python-dotenv, pytest-xdist, pygments-lexer-solidity, py-solc-x, py-solc-ast, psutil, prompt-toolkit, lazy-object-proxy, hypothesis, eth-event, eip712, black, eth-brownie
Running setup.py install for cytoolz: started
Running setup.py install for cytoolz: finished with status 'error'
PIP STDERR
----------
WARNING: The candidate selected for download or install is a yanked version: 'protobuf' candidate (version 3.18.0 at https://files.pythonhosted.org/packages/74/4e/9f3cb458266ef5cdeaa1e72a90b9eda100e3d1803cbd7ec02f0846da83c3/protobuf-3.18.0-py2.py3-none-any.whl#sha256=615099e52e9fbc9fde00177267a94ca820ecf4e80093e390753568b7d8cb3c1a (from https://pypi.org/simple/protobuf/))
Reason for being yanked: This version claims to support Python 2 but does not
ERROR: Command errored out with exit status 1:
command: 'C:\Users\alaiy\.local\pipx\venvs\eth-brownie\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\alaiy\\AppData\\Local\\Temp\\pip-install-d1bskwa2\\cytoolz_f765f335272241adba2138f1920a35cd\\setup.py'"'"'; __file__='"'"'C:\\Users\\alaiy\\AppData\\Local\\Temp\\pip-install-d1bskwa2\\cytoolz_f765f335272241adba2138f1920a35cd\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\alaiy\AppData\Local\Temp\pip-wheel-pxzumeav'
cwd: C:\Users\alaiy\AppData\Local\Temp\pip-install-d1bskwa2\cytoolz_f765f335272241adba2138f1920a35cd\
Complete output (70 lines):
ALERT: Cython not installed. Building without Cython.
running bdist_wheel
running build
running build_py
creating build
creating build\lib.win-amd64-3.10
creating build\lib.win-amd64-3.10\cytoolz
copying cytoolz\compatibility.py -> build\lib.win-amd64-3.10\cytoolz
copying cytoolz\utils_test.py -> build\lib.win-amd64-3.10\cytoolz
Any help would be appreciated!
Edit: Found a solution. Cython appears to not be supported on Python 3.10 (ref https://github.com/eth-brownie/brownie/issues/1300 and https://github.com/cython/cython/issues/4046). I downgraded to Python 3.9.7 and eth-brownie installation worked!)
ANSWER
Answered 2022-Jan-02 at 09:59I used pip install eth-brownie and it worked fine, I didnt need to downgrade. Im new to this maybe I could be wrong but it worked fine with me.
QUESTION
Context
I have a char
variable on which I need to apply a transformation (for example, add an offset). The result of the transformation may or may not overflow.
I don't really care of the actual value of the variable after the transformation is performed.
The only guarantee I want to have is that I must be able to retrieve the original value if I perform the transformation again but in the opposite way (for example, substract the offset).
Basically:
char a = 42;
a += 140; // overflows (undefined behaviour)
a -= 140; // must be equal to 42
Problem
I know that signed
types overflow is undefined behaviour but it's not the case for unsigned
types overflows. I have then chosen to add an intermediate step in the process to perform the conversion.
It would then become:
char
->unsigned char
conversion- Apply the tranformation (resp. the reversed transformation)
unsigned char
->char
conversion
This way, I have the garantee that the potential overflow will only occur for an unsigned
type.
Question
My question is, what is the proper way to perform such a conversion ?
Three possibilities come in my mind. I can either:
- implicit conversion
static_cast
reinterpret_cast
Which one is valid (not undefined behaviour) ? Which one should I use (correct behaviour) ?
My guess is that I need to use reinterpret_cast
since I don't care of actual value, the only guarantee I want is that the value in memory remains the same (i.e. the bits don't change) so that it can be reversible.
On the other hand, I'm not sure if the implicit conversion or the static_cast
won't trigger undefined behaviour in the case where the value is not representable in the destination type (out of range).
I couldn't find anything explicitly stating it is or is not undefined behaviour, I just found this Microsoft documentation where they did it with implicit conversions without any mention of undefined behaviour.
Here is an example, to illustrate:
char a = -4; // out of unsigned char range
unsigned char b1 = a; // (A)
unsigned char b2 = static_cast(a); // (B)
unsigned char b3 = reinterpret_cast(a); // (C)
std::cout << (b1 == b2 && b2 == b3) << '\n';
unsigned char c = 252; // out of (signed) char range
char d1 = c; // (A')
char d2 = static_cast(c); // (B')
char d3 = reinterpret_cast(c); // (C')
std::cout << (d1 == d2 && d2 == d3) << '\n';
The output is:
true
true
Unless undefined behaviour is triggered, the three methods seem to work.
Are (A) and (B) (resp. (A') and (B')) undefined behaviour if the value is not representable in the destination type ?
Is (C) (resp. (C')) well defined ?
ANSWER
Answered 2022-Mar-21 at 15:37I know that signed types overflow is undefined behaviour,
True, but does not apply here.
a += 140;
is not signed integer overflow, not UB. That is like a = a + 140;
a + 140
does not overflow when a
is 8-bit signed char
or unsigned char
.
The issue is what happens when the sum a + 140
is out of char
range and assigned to a char
.
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised. C17dr § 6.3.1.3 3
It is implementation defined behavior, when char
is signed and 8-bit - to assign a value outside the char
range.
Usually the implementation defined behavior is a wrap and fully defined so a += 140;
is fine as is.
Alternatively the implementation defined behavior might have been to cap the value to the char
range when char
is signed.
char a = 42;
a += 140;
// Might act as if
a = max(min(a + 140, CHAR_MAX), CHAR_MIN);
a = 127;
To avoid implementation defined behavior, perform the +
or -
on a
accessed as a unsigned char
*((unsigned char *)&a) += small_offset;
Or just use unsigned char a
and avoid all this. unsigned char
is defined to wrap.
QUESTION
I am trying to render the world map with elevation data using D3.
For this I use Natural Earth 50m land geojson : https://github.com/martynafford/natural-earth-geojson/tree/master/50m/physical
And Natural Earth elevation raster data : https://www.naturalearthdata.com/downloads/50m-raster-data/50m-shaded-relief/
I am using this tutorial : https://datawanderings.com/2020/08/08/raster-backgrounds/
So I first found the bounds of the geojson :
ogrinfo ne_50m_land.json -so -al | grep Extent
Extent: (-180.000000, -89.998926) - (180.000000, 83.599609)
I then cut the TIF file :
gdal_translate -projwin -180.000000 83.599609 180.000000 -89.998926 SR_50M.tif SR_50M-box.tif
And project into Mercator projection :
gdalwarp -overwrite -s_srs "+proj=longlat +datum=WGS84 +no_defs" -t_srs EPSG:3395 SR_50M-box.tif SR_50M-proj.tif
Finally I export to PNG :
gdal_translate -of PNG SR_50M-proj.tif SR_50M.png
Then I render everything using D3
this.projection = d3.geoMercator()
.translate([0, 0])
.scale(1)
this.rasterImage = new Image();
this.rasterImage.src = raster;
this.path = d3.geoPath(this.projection, this.ctx);
this.bb = this.path.bounds(this.land);
const s = 1 / Math.max((this.bb[1][0] - this.bb[0][0]) / this.getWidth(), (this.bb[1][1] - this.bb[0][1]) / this.getHeight());
// transform
const t = [(this.getWidth() - s * (this.bb[1][0] + this.bb[0][0])) / 2, (this.getHeight() - s * (this.bb[1][1] + this.bb[0][1])) / 2];
// update projection
this.projection
.scale(s)
.translate(t);
this.raster_width = (this.bb[1][0] - this.bb[0][0]) * s;
this.raster_height = (this.bb[1][1] - this.bb[0][1]) * s;
this.rtranslate_x = (this.getWidth() - this.raster_width) / 2;
this.rtranslate_y = (this.getHeight() - this.raster_height) / 2;
this.ctx.beginPath();
this.path(this.land);
this.ctx.fill();
this.ctx.save();
this.ctx.globalAlpha = 0.8;
this.ctx.translate(this.rtranslate_x, this.rtranslate_y);
this.ctx.drawImage(this.rasterImage, 0, 0, this.raster_width, this.raster_height);
this.ctx.restore();
ANSWER
Answered 2022-Mar-20 at 08:06A Mercator is usually clipped at roughly 85 degrees North/South (~85.05113 N/S) - as further than this you get a map that is taller than it is wide, and one that gets much much taller for every extra degree north/south included in the extent..
D3 clips features using this limit:
The spherical Mercator projection. Defines a default projection.clipExtent such that the world is projected to a square, clipped to approximately ±85° latitude.
The northern bounds are fine, but the southern bounds of the geojson is -89.998926
degrees which you use to cut the image. But as D3 clips the geojson, your stretching the image by a different amount as compared with the geojson, hence the issue you see.
The solution should be to clip the image to a bounds that is representative of the limits of what D3 will render for a Mercator (85.05113
degrees south) not the limits of the data itself.
I haven't looked up how faithfully gdal implements EPSG:3395 as the definition provides for a projected bounds of 80 degrees south and 84 degrees north - though looking at the image, this doesn't appear to be an issue.
You can also use the cleaner fitSize methods for D3 projections (d3v4+):
projection.fitSize([width,height],geojsonObject)
Which will set scale and translate for you given a provided width/height.
QUESTION
I am trying to plot two different regression lines (with the formula: salary = beta0 + beta1D3 + beta2spending + beta3*(spending*D3) + w) into one scatter plot by deviding the data I have into two subsets as seen in the following code:
salary = data$salary
spending = data$spending
D1 = data$North
D2 = data$South
D3 = data$West
subsetWest = subset(data, D3 == 1)
subsetRest = subset(data, D3 == 0)
abab = lm(salary ~ 1 + spending + 1*spending, data=subsetWest) #red line
caca = lm(salary ~ 0 + spending + 0*spending, data=subsetRest) #blue line
plot(spending,salary)
points(subsetWest$spending, subsetWest$salary, pch=25, col = "red")
points(subsetRest$spending, subsetRest$salary, pch=10, col = "blue")
abline(abab, col = "red")
abline(caca, col = "blue")
This is a sample of my data table: [enter image description here][1] [1]: https://i.stack.imgur.com/LowYo.png
And this is the plot I get when running the code:
[enter image description here][2] [2]: https://i.stack.imgur.com/It8ai.png
My problem is that the intercept for my second regression is wrong, in fact I do not even get an intercept when looking at the summary, unlike with the first regression.
Does anybody see where my problem is or does anybody know an alternative way of plotting the two regression lines?
Help would be much appreciated. Thank you very much!
This is the whole table:
structure(list(salary = c(39166L, 40526L, 40650L, 53600L, 58940L,
53220L, 61356L, 54340L, 51706L, 49000L, 48548L, 54340L, 60336L,
53050L, 54720L, 43380L, 43948L, 41632L, 36190L, 41878L, 45288L,
49248L, 54372L, 67980L, 46764L, 41254L, 45590L, 43140L, 44160L,
44500L, 41880L, 43600L, 45868L, 36886L, 39076L, 40920L, 42838L,
50320L, 44964L, 41938L, 54448L, 51784L, 45288L, 49280L, 44682L,
51220L, 52030L, 51576L, 58264L, 51690L), spending = c(6692L,
6228L, 7108L, 9284L, 9338L, 9776L, 11420L, 11072L, 8336L, 7094L,
6318L, 7242L, 7564L, 8494L, 7964L, 7136L, 6310L, 6118L, 5934L,
6570L, 7828L, 9034L, 8698L, 10040L, 7188L, 5642L, 6732L, 5840L,
5960L, 7462L, 5706L, 5066L, 5458L, 4610L, 5284L, 6248L, 5504L,
6858L, 7894L, 5018L, 10880L, 8084L, 6804L, 5658L, 4594L, 5864L,
7410L, 8246L, 7216L, 7532L), North = c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), South = c(0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L), West = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA,
-50L))
ANSWER
Answered 2022-Mar-19 at 14:50My problem is that the intercept for my second regression is wrong, in fact I do not even get an intercept when looking at the summary, unlike with the first regression.
That is because your second model specifies no intercept, since you use ... ~ 0 + ...
Also, your first model doesn't make sense because it includes spending
twice. The second entry for spending
will be ignored by lm
QUESTION
I'm trying to build a doughnut chart with rounded edges only on one side. My problem is that I have both sided rounded and not just on the one side. Also can't figure out how to do more foreground arcs not just one.
const tau = 2 * Math.PI; // http://tauday.com/tau-manifesto
const arc = d3.arc()
.innerRadius(80)
.outerRadius(100)
.startAngle(0)
.cornerRadius(15);
const svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
Background arc, but I'm not sure if this is even needed?
const background = g.append("path")
.datum({endAngle: tau})
.style("fill", "#ddd")
.attr("d", arc);
const data = [ .51];
const c = d3.scaleThreshold()
.domain([.200,.205,.300,.310, .501, 1])
.range(["green","#ddd", "orange","#ddd", "red"]);
Const pie = d3.pie()
.sort(null)
.value(function(d) {
return d;
});
Only have one foreground, but need to be able to have multiple:
const foreground = g.selectAll('.arc')
.data(pie(data))
.enter()
.append("path")
.attr("class", "arc")
.datum({endAngle: 3.8})
.style("fill", function(d) {
return c(d.value);
})
.attr("d", arc)
What am I doing wrong?
var tau = 2 * Math.PI; // http://tauday.com/tau-manifesto
// An arc function with all values bound except the endAngle. So, to compute an
// SVG path string for a given angle, we pass an object with an endAngle
// property to the `arc` function, and it will return the corresponding string.
var arc = d3.arc()
.innerRadius(80)
.outerRadius(100)
.startAngle(0)
.cornerRadius(15);
// Get the SVG container, and apply a transform such that the origin is the
// center of the canvas. This way, we don’t need to position arcs individually.
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Add the background arc, from 0 to 100% (tau).
var background = g.append("path")
.datum({endAngle: tau})
.style("fill", "#ddd")
.attr("d", arc);
var data = [ .51];
var c = d3.scaleThreshold()
.domain([.200,.205,.300,.310, .501, 1])
.range(["green","#ddd", "orange","#ddd", "red"]);
var pie = d3.pie()
.sort(null)
.value(function(d) {
return d;
});
// Add the foreground arc in orange, currently showing 12.7%.
var foreground = g.selectAll('.arc')
.data(pie(data))
.enter()
.append("path")
.attr("class", "arc")
.datum({endAngle: 3.8})
.style("fill", function(d) {
return c(d.value);
})
.attr("d", arc)
ANSWER
Answered 2022-Feb-28 at 08:52The documentation states, that the corner radius is applied to both ends of the arc. Additionally, you want the arcs to overlap, which is also not the case.
You can add the one-sided rounded corners the following way:
- Use arcs
arc
with no corner radius for the data. - Add additional
path
objectscorner
just for the rounded corner. These need to be shifted to the end of eacharc
. - Since
corner
has rounded corners on both sides, add aclipPath
that clips half of this arc. TheclipPath
contains apath
for everycorner
. This is essential for arcs smaller than two times the length of the rounded corners. raise
all elements ofcorner
to the front and thensort
them descending by index, so that they overlap the right way.
const arc = d3.arc()
.innerRadius(50)
.outerRadius(70);
const arc_corner = d3.arc()
.innerRadius(50)
.outerRadius(70)
.cornerRadius(10);
const svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
const clipPath = g.append("clipPath")
.attr("id", "clip_corners");
const c = d3.scaleQuantile()
.range(["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#08589e"]);
const pie = d3.pie().value(d => d);
function render(values) {
c.domain(values);
const arcs = pie(values);
const corners = pie(values).map(d => {
d.startAngle = d.endAngle - 0.2;
d.endAngle = d.endAngle + 0.2;
return d;
});
const clip = pie(values).map(d => {
d.startAngle = d.endAngle - 0.01;
d.endAngle = d.endAngle + 0.2;
return d;
});
g.selectAll(".arc")
.data(arcs)
.join("path")
.attr("class", "arc")
.style("fill", d => c(d.value))
.attr("d", arc);
clipPath.selectAll("path")
.data(clip)
.join("path")
.attr("d", arc);
g.selectAll(".corner")
.data(corners)
.join("path")
.raise()
.attr("class", "corner")
.attr("clip-path", "url(#clip_corner)")
.style("fill", d => c(d.value))
.attr("d", arc_corner)
.sort((a, b) => b.index - a.index);
}
function randomData() {
const num = Math.ceil(8 * Math.random()) + 2;
const values = Array(num).fill(0).map(d => Math.random());
render(values);
}
d3.select("#random_data")
.on("click", randomData);
randomData();
Random data
I changed the dependency to the current version of d3.
QUESTION
In d3
, we may change the order of elements in a selection, for example by using raise
.
Yet, when we rebind the data and use join
, this order is discarded.
This does not happen when we use "the old way" of binding data, using enter
and merge
.
See following fiddle where you can click a circle (for example the blue one) to bring it to front. When you click "redraw", the circles go back to their original z-ordering when using join
, but not when using enter
and merge
.
Can I achive that the circles keep their z-ordering and still use join
?
const data = [{
id: 1,
v: 10,
c: 'red'
}, {
id: 2,
v: 30,
c: 'blue'
}, {
id: 3,
v: 60,
c: 'green'
}]
let nDrawCall = 0
function redraw() {
nDrawCall++
//svg1 with old enter-merge pattern that works
const circles = d3.select('#svg1')
.selectAll('circle')
.data(data, d => d.id)
circles
.enter()
.append('circle')
.on('click', function() {
d3.select(this).raise()
})
.merge(circles)
.attr('cx', d => d.v * nDrawCall)
.attr('cy', d => d.v)
.attr('r', d => d.v)
.attr('fill', d => d.c)
//svg2 with new join pattern that sadly reorders
d3.select('#svg2')
.selectAll('circle')
.data(data, d => d.id)
.join(enter => enter
.append('circle')
.on('click', function() {
d3.select(this).raise()
})
)
.attr('cx', d => d.v * nDrawCall)
.attr('cy', d => d.v)
.attr('r', d => d.v)
.attr('fill', d => d.c)
}
function reset() {
nDrawCall = 0
redraw()
}
redraw()
/*
while (true) {
iter++
console.log(iter)
sleepFor(500)
}
*/
svg {
height: 100px;
width: 100%;
}
Redraw
Reset
ANSWER
Answered 2022-Feb-18 at 23:13join
does an implicit order
after merging the enter- and update-selection, see https://github.com/d3/d3-selection/blob/91245ee124ec4dd491e498ecbdc9679d75332b49/src/selection/join.js#L14.
The selection order after the data binding in your example is still red, blue, green even if the document order is changed. So the circles are reordered to the original order using join
.
You can get around that by changing the data binding reflecting the change in the document order. I did that here, by moving the datum of the clicked circle to the end of the data array.
let data = [{
id: 1,
v: 10,
c: 'red'
}, {
id: 2,
v: 30,
c: 'blue'
}, {
id: 3,
v: 60,
c: 'green'
}]
let nDrawCall = 0
function redraw() {
nDrawCall++
d3.select('#svg2')
.selectAll('circle')
.data(data, d => d.id)
.join(enter => enter
.append('circle')
.on('click', function() {
const circle = d3.select(this).raise();
data.push(data.splice(data.indexOf(circle.datum()), 1)[0]);
})
)
.attr('cx', d => d.v * nDrawCall)
.attr('cy', d => d.v)
.attr('r', d => d.v)
.attr('fill', d => d.c)
}
function reset() {
nDrawCall = 0
redraw()
}
redraw()
svg {
height: 100px;
width: 100%;
}
Redraw
Reset
QUESTION
I have df1
:
Account Score1 Score2 Score3 Score4 Score5 Score6 Random Random2
23 F30 G1 G5 H10 J18 NULL 3 4
42 NULL NULL NULL NULL NULL NULL 5 6
56 D10 D11 NULL NULL NULL NULL 6 2
59 X14 D3 F4 A11 A12 A13 8 2
41 D11 D12 NULL NULL NULL NULL 7 7
45 C3 C10 R4 T5 NULL NULL 1 1
30 C4 NULL NULL NULL NULL NULL 1 5
33 D2 D3 NULL NULL NULL NULL 3 4
I would like to make a new data frame that takes the values from the 6 score columns and puts them into a single column named Score
. If there are multiple scores, then I would want multiple rows of data.
I would like the output df2
to look like:
Account Score
23 F30
23 G1
23 G5
23 H10
23 J18
56 D10
56 D11
59 X14
59 D3
59 F4
59 A11
59 A12
59 A13
41 D11
41 D12
45 C3
45 C10
45 R4
45 T5
30 C4
33 D2
33 D3
ANSWER
Answered 2022-Jan-30 at 21:02If the values are "NULL"
, then we can select
the columns of interest, convert to long format with pivot_longer
and filter
out the "NULL"
elements
library(dplyr)
library(tidyr)
df1 %>%
select(Account, starts_with("Score")) %>%
pivot_longer(cols = -Account, names_to = NULL, values_to = "Score") %>%
filter(Score != "NULL")
-output
# A tibble: 22 × 2
Account Score
1 23 F30
2 23 G1
3 23 G5
4 23 H10
5 23 J18
6 56 D10
7 56 D11
8 59 X14
9 59 D3
10 59 F4
# … with 12 more rows
df1 <- structure(list(Account = c(23L, 42L, 56L, 59L, 41L, 45L, 30L,
33L), Score1 = c("F30", "NULL", "D10", "X14", "D11", "C3", "C4",
"D2"), Score2 = c("G1", "NULL", "D11", "D3", "D12", "C10", "NULL",
"D3"), Score3 = c("G5", "NULL", "NULL", "F4", "NULL", "R4", "NULL",
"NULL"), Score4 = c("H10", "NULL", "NULL", "A11", "NULL", "T5",
"NULL", "NULL"), Score5 = c("J18", "NULL", "NULL", "A12", "NULL",
"NULL", "NULL", "NULL"), Score6 = c("NULL", "NULL", "NULL", "A13",
"NULL", "NULL", "NULL", "NULL"), Random = c(3L, 5L, 6L, 8L, 7L,
1L, 1L, 3L), Random2 = c(4L, 6L, 2L, 2L, 7L, 1L, 5L, 4L)),
class = "data.frame", row.names = c(NA,
-8L))
QUESTION
When I try to run command ng lint --fix
cli throws this error:
An unhandled exception occurred: Cannot find builder "@angular-devkit/build-angular:tslint".
See "C:\Users\MOE89A~1.ZAR\AppData\Local\Temp\ng-Ijc3an\angular-errors.log" for further details.
My lint confing in angular.json
:
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"projects/wepod-app/tsconfig.app.json",
"projects/wepod-app/tsconfig.spec.json",
"projects/wepod-app/e2e/tsconfig.json"
],
"exclude": [
"**/node_modules/**"
]
}
},
My package.json
:
{
"name": "wepod-clients",
"version": "3.2.3",
"scripts": {
"ng": "ng",
"start": "node patch.js && ng serve",
"build": "node patch.js && node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng run wepod-app:app-shell:production && ng run wepod-app:auth-standalone:production",
"server": "npm run build && http-server -p 9090 -c-1 dist",
"test": "ng test",
"lint": "ng lint --fix",
"e2e": "ng e2e",
"postinstall": "node patch.js && ngcc",
"postbuild": "node post-build.js",
"prepare": "husky install",
"build-latest": "git pull origin production && npm run build"
},
"private": true,
"dependencies": {
"@angular/animations": "^13.0.0",
"@angular/cdk": "^13.0.0",
"@angular/cli": "^13.0.1",
"@angular/common": "^13.0.0",
"@angular/compiler": "^13.0.0",
"@angular/core": "^13.0.0",
"@angular/forms": "^13.0.0",
"@angular/localize": "^13.0.0",
"@angular/platform-browser": "^13.0.0",
"@angular/platform-browser-dynamic": "^13.0.0",
"@angular/platform-server": "^13.0.0",
"@angular/router": "^13.0.0",
"@angular/service-worker": "^13.0.0",
"@types/video.js": "^7.3.27",
"animate.css": "^4.1.1",
"assert": "^2.0.0",
"bowser": "^2.11.0",
"buffer": "^6.0.3",
"bundle-loader": "^0.5.6",
"compare-version": "^0.1.2",
"constants-browserify": "^1.0.0",
"crypto-browserify": "^3.12.0",
"crypto-js": "^4.1.1",
"d3": "^6.5.0",
"hammerjs": "^2.0.8",
"https-browserify": "^1.0.0",
"jalali-moment": "^3.3.10",
"lottie-web": "^5.7.13",
"lzutf8": "^0.6.0",
"net": "^1.0.2",
"ng-gallery": "^5.1.1",
"ng2-jalali-date-picker": "^2.4.2",
"ngx-device-detector": "^1.5.2",
"ngx-doughnut-chart": "0.0.4",
"ngx-infinite-scroll": "^8.0.2",
"ngx-lottie": "^7.0.4",
"ngx-owl-carousel-o": "^3.1.1",
"ngx-skeleton-loader": "^2.10.1",
"ngx-toastr": "^12.1.0",
"os-browserify": "^0.3.0",
"podchat-browser": "^10.14.13",
"rxjs": "^6.6.7",
"stream-browserify": "^3.0.0",
"stream-http": "^3.2.0",
"tls": "0.0.1",
"tslib": "^2.0.0",
"uuid": "^8.3.2",
"video.js": "^7.15.4",
"videojs-record": "^4.5.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "^13.0.1",
"@angular-devkit/core": "^13.0.1",
"@angular/compiler-cli": "^13.0.0",
"@angular/language-service": "^13.0.0",
"@egjs/hammerjs": "^2.0.17",
"@types/hammerjs": "^2.0.40",
"@types/jasmine": "~3.6.0",
"@types/jasminewd2": "^2.0.10",
"@types/node": "^12.20.36",
"codelyzer": "^6.0.0",
"colors": "^1.4.0",
"git-tag-version": "^1.3.1",
"gulp": "^4.0.2",
"gulp-gzip": "^1.4.2",
"http-server": "^14.0.0",
"husky": "^7.0.4",
"jasmine-core": "~3.6.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "^6.3.7",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "^2.1.0",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"protractor": "^7.0.0",
"ts-node": "^8.10.2",
"tslint": "^6.1.3",
"typescript": "4.4.4",
"zip-dir": "^2.0.0"
},
"browser": {
"fs": false,
"path": false,
"os": false
}
}
ANSWER
Answered 2021-Nov-28 at 10:34From v13 angular doesn't use tslint
anymore due to deprecation.
Run ng add @angular-eslint/schematics
to add eslint
to your application.
It will use tslint-to-eslint-config to migrate you to eslint
automatically.
It will generate a .eslintrc.json
file and migrate tslint.json
to it.
Nothing else is needed to be done.
QUESTION
My issue is that the animation works fine when the images have no content to them as below, but once they are loaded I get the following error: Error: attribute x: Expected length, "NaN".
Here is a code snippet:
var data = ['https://cdn.britannica.com/60/8160-050-08CCEABC/German-shepherd.jpg', 'https://cdn.britannica.com/60/8160-050-08CCEABC/German-shepherd.jpg', 'https://cdn.britannica.com/60/8160-050-08CCEABC/German-shepherd.jpg', 'https://cdn.britannica.com/60/8160-050-08CCEABC/German-shepherd.jpg', 'https://cdn.britannica.com/60/8160-050-08CCEABC/German-shepherd.jpg'];
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
wid = 400
y = 400;
var svg = d3.select("body").append("svg")
.attr("width", wid)
.attr("height", "400")
.on('mousemove', () => {
let x = event.x - 20;
d3.selectAll('.content')
.attr('x', (d, i) => fisheye(d, x))
})
.on('mouseleave', () => {
d3.selectAll('.content').transition().attr(
'x', (d, i) => xScale(i))
})
var chart = svg.append('g')
.classed('group', true)
let xScale = d3.scaleBand().domain(d3.range(5)).range([0, wid]).padding(0)
let rects = svg.selectAll('content')
.data(
d3.range(5)
//data //(uncomment this, and comment line above to try loading images)
)
rects.exit().remove();
rects.enter()
.append("svg:image")
.attr("xlink:href", d => d)
.attr("class", "content")
.attr("y", 0)
.attr("x", (d, i) => xScale(i))
.attr("width", "300px")
.style("opacity", 1)
.attr("stroke", "white")
.style('fill', 'rgb(81, 170, 232)')
.attr("height", 400);
let distortion = 10;
function fisheye(_, a) {
let x = xScale(_),
left = x < a,
range = d3.extent(xScale.range()),
min = range[0],
max = range[1],
m = left ? a - min : max - a;
if (m === 0) m = max - min;
return (left ? -1 : 1) * m * (distortion + 1) / (distortion + (m / Math.abs(x - a))) + a;
}
I'm trying to make something that looks like this: https://www.nytimes.com/newsgraphics/2013/09/13/fashion-week-editors-picks/index.html
I would really appreciate some help on getting that snippet to work and if possible as smoothly as this website link! That was made by the Bosstock himself and I'm a d3 newbie so I'm quite out of my depth.
ANSWER
Answered 2021-Dec-05 at 16:55I figured out my issue-
let xScale = d3.scaleBand().domain(data).range([0,wid]).padding(0)
The domain was d3.range(5)
rather than my data
variable.
QUESTION
I have two collections.defaultdict
and trying to remove values from d1
that are also in d2
.
from collections import Counter, defaultdict
d1 = Counter({'hi': 22, 'bye': 55, 'ok': 33})
d2 = Counter({'hi': 10, 'hello': 233, 'nvm': 96})
Ideal result:
d3 = set()
d3 = ({'bye':55, 'ok':33})
So far I have tried:
d3 = set()
d3 = d1 - d2
print(d3)
Counter({'bye': 55, 'ok': 33, 'hi': 12})
But this keeps the same value of 'hi'
even though I want to remove all similar ones.
ANSWER
Answered 2021-Oct-20 at 15:20Use a dictionary comprehension
d3 = {k: v for k, v in d1.items() if k not in d2}
print(d3)
Result:
{'bye': 55, 'ok': 33}
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install d3
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page