Id
int64 1.68k
75.6M
| PostTypeId
int64 1
2
| AcceptedAnswerId
int64 1.7k
75.6M
⌀ | ParentId
int64 1.68k
75.6M
⌀ | Score
int64 -60
3.16k
| ViewCount
int64 8
2.68M
⌀ | Body
stringlengths 1
41.1k
| Title
stringlengths 14
150
⌀ | ContentLicense
stringclasses 3
values | FavoriteCount
int64 0
1
⌀ | CreationDate
stringlengths 23
23
| LastActivityDate
stringlengths 23
23
| LastEditDate
stringlengths 23
23
⌀ | LastEditorUserId
int64 -1
21.3M
⌀ | OwnerUserId
int64 1
21.3M
⌀ | Tags
sequence |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
74,476,107 | 2 | null | 25,146,474 | 13 | null | I found the solution. The SSMS version was older. I uninstalled SSMS from the server, went to the microsoft website and downloaded a more current version and now the Database Diagrams works ok.

| null | CC BY-SA 4.0 | null | 2022-11-17T13:14:25.397 | 2022-11-20T19:51:55.993 | 2022-11-20T19:51:55.993 | 3,025,856 | 7,194,464 | null |
74,476,368 | 2 | null | 74,476,170 | 0 | null | Please use this code
```
function show1(){
document.getElementById('div1').style.display ='block'; document.getElementById('div2').style.display ='none';
}
function show2(){
document.getElementById('div1').style.display = 'none';
document.getElementById('div2').style.display = 'block';
}
```
```
body {
font-family: arial;
}
.hide {
display: none;
}
p {
font-weight: bold;
}
```
```
<p>How many check boxes do you want when clicked on a radio button?</p>
<input type="radio" name="tab" value="igotnone" onclick="show1();" />
First
<input type="radio" name="tab" value="igottwo" onclick="show2();" />
Second
<div id="div1" class="hide">
<hr><p>First div</p>
</div>
<div id="div2" class="hide">
<hr><p>Second div</p>
</div>
```
| null | CC BY-SA 4.0 | null | 2022-11-17T13:33:10.847 | 2022-11-17T13:33:10.847 | null | null | 7,578,743 | null |
74,476,581 | 2 | null | 74,373,121 | 0 | null | I needed a console app, but I had a console app.
And to create a console app I needed , but I had .
This fixed everything for me.
| null | CC BY-SA 4.0 | null | 2022-11-17T13:48:00.263 | 2022-11-17T13:48:00.263 | null | null | 20,458,019 | null |
74,476,735 | 2 | null | 74,267,936 | 2 | null |
The issue you are facing is due to the dependency of Clarifai JS on axios for requests. Throughout the development of the Clarifai, the library has accepted multiple versions of axios but haven't really configured compatibility on these versions.
Ex.
Clarifai is familiar with axios v1.1.2 but there is no compatibility for it to work in a good condition and perform well with the library.
1. In your package.json file, update "axios" under "dependencies" to "0.27.2" (The compatible version as of now).
2. Add an "overrides" section and include the code below (Overrides Section).
3. Reinstall your node_modules folder (run 'npm install')
(in 'package.json')
```
"dependencies": {
...
"axios": "0.27.2",
"clarifai": "^2.9.1",
...
},
"overrides": {
"clarifai": {
"axios": "$axios"
}
},
...
```
| null | CC BY-SA 4.0 | null | 2022-11-17T13:58:51.083 | 2022-11-17T13:58:51.083 | null | null | 20,365,757 | null |
74,476,769 | 2 | null | 74,476,465 | 0 | null | If you want to have a Range variable containing the three cells, you have several options.
```
With ActiveSheet
Dim MergedRange As Range
' Simple
Set MergedRange = .Range("A1:A3")
' Use From and To Cell to Define the Range
Set MergedRange = .Range(.Range("A1"), .Range("A3"))
' Or
Set MergedRange = .Range(.Cells(1, 1), .Cells(3, 1))
' Use Resize
Set MergedRange = .Range("A1").Resize(3, 1)
' Use Union (usefull if cells are not next to each other)
Set MergedRange = Union(.Range("A1"), .Range("A2"), .Range("A3"))
End If
```
Be aware that a Range is an Object and in VBA you have to use `Set` to assign an Object. And be aware that you can't do something like `MsgBox MergedRange` when `MergedRange` contains more than one cell. This is because for a command like `MsgBox MergedRange`, VBA will look to the content of the Range (property `Value`), and for a Range with more than one cell, this is an (2-dimensional) array.
| null | CC BY-SA 4.0 | null | 2022-11-17T14:01:17.080 | 2022-11-17T14:09:29.653 | 2022-11-17T14:09:29.653 | 7,599,798 | 7,599,798 | null |
74,476,823 | 2 | null | 74,476,753 | 0 | null | Use `Str` and text values, as `Join` always returns text:
```
Join(Array(Str(Val / 100), "0.021", "2")
```
| null | CC BY-SA 4.0 | null | 2022-11-17T14:04:49.273 | 2022-11-17T14:04:49.273 | null | null | 3,527,297 | null |
74,476,940 | 2 | null | 73,283,733 | -2 | null | You should try linking the two sources directly through the date's, and not choose any other dimension, only as metrics! This worked for me, but unfortunately I can't replicate it for another project.
It is worth a try anyway.
Looks like this:
[enter image description here](https://i.stack.imgur.com/yArBN.png)
| null | CC BY-SA 4.0 | null | 2022-11-17T14:12:26.030 | 2022-11-17T14:12:26.030 | null | null | 20,530,883 | null |
74,477,025 | 2 | null | 33,647,330 | 0 | null | First of all I've tried to use `app:tabMinWidth="0dp"`
Then I've tried dcanbatman's answer.
And it started to work only with both of these solutions:
```
app:tabPaddingStart="0dp"
app:tabPaddingEnd="0dp"
app:tabMinWidth="0dp"
```
| null | CC BY-SA 4.0 | null | 2022-11-17T14:19:10.983 | 2022-11-17T14:19:10.983 | null | null | 7,041,761 | null |
74,477,525 | 2 | null | 74,477,057 | 0 | null | You have `points_from_xy(df.latitude , df.longitude)`. [points_from_xy](https://geopandas.org/en/stable/docs/reference/api/geopandas.points_from_xy.html) expects `(x, y)` not `(y, x)`. You need to switch the lat/lon order to lon, lat
| null | CC BY-SA 4.0 | null | 2022-11-17T14:54:40.887 | 2022-11-17T14:54:40.887 | null | null | 3,888,719 | null |
74,477,693 | 2 | null | 22,398,767 | 0 | null | I changed to Any CPU and it worked for me.
| null | CC BY-SA 4.0 | null | 2022-11-17T15:06:12.963 | 2022-11-17T15:06:12.963 | null | null | 20,531,377 | null |
74,477,739 | 2 | null | 70,448,183 | 0 | null | In your example you import `TimesSeries` from `alpha_vantage.timeseries`.
Please note that you have an extra `s` in TimeSeries.
-
Here is an example from their [website](https://github.com/RomelTorres/alpha_vantage)
```
from alpha_vantage.timeseries import TimeSeries
```
| null | CC BY-SA 4.0 | null | 2022-11-17T15:09:13.780 | 2022-11-17T15:09:13.780 | null | null | 20,174,226 | null |
74,477,779 | 2 | null | 69,140,391 | -1 | null | The max length of youtube channel is 24.
I found out the maximum length from about 20k youtube channel IDs.
| null | CC BY-SA 4.0 | null | 2022-11-17T15:11:21.673 | 2022-11-17T15:31:37.000 | 2022-11-17T15:31:37.000 | 2,227,743 | 12,335,616 | null |
74,477,973 | 2 | null | 74,477,168 | 1 | null | I would try `debug.print(a2 a3)` to test the output. It could be that there is a type conflict `1.00``1`
| null | CC BY-SA 4.0 | null | 2022-11-17T15:23:49.973 | 2022-11-17T15:24:14.420 | 2022-11-17T15:24:14.420 | 20,530,430 | 20,530,430 | null |
74,478,033 | 2 | null | 11,483,978 | 0 | null | To adjusting Gridview to screen size
In `onCreate` take rowHeight :
//Get root view
```
root = binding.root
```
// Or you can use `findviewbyid(R.id.root)`
```
view.onGlobalLayout {
rowHeight =
root.measuredHeight / currentPageNumberOfRow
fillView(appsList)
}
```
In adapter:
```
override fun getView(position: Int, ConvertView: View?, parent: ViewGroup?): View? {
var mConvertView = ConvertView
if (layoutInflater == null) {
layoutInflater =
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as
layoutInflater!!.inflate(R.layout.item_app_shortcut, null)
}
if (mConvertView == null) {
mConvertView =
layoutInflater!!.inflate(R.layout.item_child_launcher_app, null)
//Add this:
mConvertView.layoutParams = AbsListView.LayoutParams(GridView.AUTO_FIT, rowHeight)
}
```
Dont forget set row image:
```
android:layout_width="0dp"
android:layout_height="0dp"
```
To fit on screen
| null | CC BY-SA 4.0 | null | 2022-11-17T15:27:53.443 | 2022-11-17T15:27:53.443 | null | null | 6,046,829 | null |
74,478,376 | 2 | null | 13,881,548 | 0 | null | According to your question the height of your footer is 65px, So lets make a tailor made solution for your problem
Wrap the body content within a div
Select that particular div within the css and add `margin-bottom: 65px;` (you can replace 65px with a higher value if you need some more space at the bottom)
| null | CC BY-SA 4.0 | null | 2022-11-17T15:51:06.443 | 2022-11-17T16:18:52.563 | 2022-11-17T16:18:52.563 | 18,617,343 | 18,617,343 | null |
74,479,494 | 2 | null | 74,474,982 | 0 | null | I copy/pasted the code from [your docussaurus reference](https://docusaurus.io/tests/pages/diagrams#mermaid-in-tabs), so I can see the problem.
I believe that is a indeed...
---
This is how I managed to work-around:
```
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
# Mermaid in tabs
<!-- [start] add this to avoid the possible bug. Note: the empty line before [```] is necessary -->
```mermaid
flowchart TD
```
<!-- [end] add this to avoid the possible bug -->
<Tabs>
<TabItem value="tab-a">
```mermaid
graph LR
a ---> c(10)
b ---> c(10)
```
</TabItem>
<TabItem value="tab-b">
```mermaid
graph LR
d ---> z(42)
e ---> z(42)
```
</TabItem>
</Tabs>
```
---
1. I downloaded the page that worked, from docusaurus;
2. I trimmed all code, until it broke;
3. I tested until I found a way to render the "wanted" result, without any extra "artifacts";
4. Now we have a working code, but it is a workaround one.
| null | CC BY-SA 4.0 | null | 2022-11-17T17:12:00.170 | 2022-11-18T12:10:20.450 | 2022-11-18T12:10:20.450 | 5,734,097 | 5,734,097 | null |
74,479,511 | 2 | null | 74,477,773 | 0 | null | The issue is how you are iterating in `for item_id, adult_quantity in bag.items():`. I see that `bag` is a dictionary, and I that it's a dictionary like:
```
{
'item_id': 1,
'quantity': 10,
'ticket': ticket,
'adult_ticket': True,
}
```
this is correct, then why do you need to iterate through a `bag` in contexts.py? Would this not work:
```
def bag_contents(request):
bag_items = []
'''Empty list for bag items to live in'''
total = 0
ticket_count = 0
bag = request.session.get('bag', {})
if 'item_id' in bag:
item_id = bag.item_id
else:
item_id = None
ticket = get_object_or_404(Ticket, pk=item_id)
if bag.adult_ticket:
total += bag.quantity * ticket.adult_price
bag_items.append({
'item_id': item_id,
'quantity': bag.quantity,
'ticket': ticket,
'adult_ticket': True,
})
if bag.child_ticket:
total += bag.quantity * ticket.child_price
bag_items.append({
'item_id': item_id,
'quantity': bag.quantity,
'ticket': ticket,
'child_ticket': True,
})
ticket_count += bag.quantity
grand_total = total
context = {
'bag_items': bag_items,
'total': total,
'ticket_count': ticket_count,
'grand_total': grand_total,
}
'''Make dictionary available to all templates across the enitire application'''
return context
```
| null | CC BY-SA 4.0 | null | 2022-11-17T17:13:32.840 | 2022-11-18T12:45:32.463 | 2022-11-18T12:45:32.463 | 10,951,070 | 10,951,070 | null |
74,479,847 | 2 | null | 73,062,682 | 0 | null | *
The user_id has been purposefully removed from the Audience Builder due to privacy concerns.
Also, Analytics is not the best tool for tracking individual users, as it is made for analyzing users in aggregate.
You might want to consider using BigQuery export and query for the user_id value. You could visit this [link](https://support.google.com/analytics/answer/9213390) for your reference. Also, you can find BigQuery's export schema in this [article](https://support.google.com/analytics/answer/7029846).
| null | CC BY-SA 4.0 | null | 2022-11-17T17:40:45.833 | 2022-11-21T20:35:13.790 | 2022-11-21T20:35:13.790 | 20,393,543 | 20,393,543 | null |
74,480,318 | 2 | null | 11,169,554 | 0 | null | You can add a class to the element being dragged, therefore allowing you to style it however you want. Like so:
```
element.addEventListener("dragstart", (event) => {
event.currentTarget.classList.add("dragging");
});
```
Checkout [https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/setData](https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/setData)
| null | CC BY-SA 4.0 | null | 2022-11-17T18:20:28.817 | 2022-11-17T18:20:28.817 | null | null | 18,454,989 | null |
74,481,131 | 2 | null | 66,607,099 | 1 | null | The perfect way for me was add this code to your css file:
```
.MuiDataGrid-root .MuiDataGrid-columnHeader,
.MuiDataGrid-root .MuiDataGrid-cell {
outline: none !important;
}
```
I found that if we set it just for :focus, then if we click to a button of cell, outline still visible
| null | CC BY-SA 4.0 | null | 2022-11-17T19:32:20.927 | 2022-11-17T19:32:20.927 | null | null | 19,844,723 | null |
74,481,133 | 2 | null | 68,185,660 | 0 | null | I avoid issues like that by listing all of your subscriptions you have access to, filter those for the one you want, and set that as your active context.
```
Get-AzContext -ListAvailable | Where{$_.Name -match 'MySub1'} | Set-AzContext
```
You just need to fill in the name of the subscription or something. You can also run `Get-AzContext -ListAvailable` to see what subscriptions are available to you.
| null | CC BY-SA 4.0 | null | 2022-11-17T19:32:30.603 | 2022-11-17T19:32:30.603 | null | null | 3,245,749 | null |
74,481,152 | 2 | null | 2,044,752 | 0 | null |
1. Truncate the table dept_details
2. Display the structure of the table emp_details
3. Convert the first letter of emp_name into capitals.
| null | CC BY-SA 4.0 | null | 2022-11-17T19:34:10.297 | 2022-11-21T10:29:52.683 | 2022-11-21T10:29:52.683 | 12,263,543 | 20,450,315 | null |
74,481,586 | 2 | null | 22,001,952 | 0 | null | if you want to get the Original Price from the Discounted Price and Discount Value. you can use this code
```
using System;
public class Program
{
public static void Main()
{
decimal discountedPrice = 280;
decimal discount = (decimal)0.20;
decimal originalPrice = discountedPrice / (decimal)(1-discount);
Console.WriteLine(originalPrice);
}
}```
```
| null | CC BY-SA 4.0 | null | 2022-11-17T20:16:39.170 | 2022-11-17T20:16:39.170 | null | null | 10,793,838 | null |
74,481,750 | 2 | null | 74,466,996 | 0 | null | As a result I changed TXT format to XML. So now I have an XSLT file that groups tasks with a selected date into categories.:
```
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" exclude-result-prefixes="xsl" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8" indent="yes""
xslt:indent-amount="3" xmlns:xslt="http://xml.apache.org/xslt"/>
<xsl:key name="group" match="Task" use="@category"/>
<xsl:template match="TaskInfo/TaskList">
<xsl:text>
</xsl:text>
<Tasks>
<xsl:attribute name="date">
<xsl:text>17.11.2022</xsl:text>
</xsl:attribute>
<xsl:apply-templates select="Task[generate-id(.) = generate-id(key('group',@category))]" />
</Tasks>
</xsl:template>
<xsl:template match="Task">
<Category>
<xsl:attribute name="value">
<xsl:value-of select = "@category"/>
</xsl:attribute>
<xsl:for-each select="key('group',@category)">
<xsl:if test="@date='17.11.2022'">
<TaskText><xsl:value-of select="@taskText"/></TaskText>
</xsl:if>
</xsl:for-each>
</Category>
</xsl:template>
</xsl:stylesheet>
```
Where 17.11.2022 date can be changed to the selected one.
| null | CC BY-SA 4.0 | null | 2022-11-17T20:32:21.687 | 2022-11-17T20:32:21.687 | null | null | 20,523,711 | null |
74,483,069 | 2 | null | 74,482,800 | 1 | null | Three issues I can see with your code:
1/
`MeteoriteData$lat <- as.factor(MeteoriteData$lat)`
Do you need to convert your lat and long data to factors? I've never seen that done before and I suspect it will only lead to trouble.
2/
`geom_point(data = MeteoriteData, aes(x = lat, y = long)`
Looks like you've got your x/y and long/lat around the wrong way. x should be long and y should be lat.
3/
As r2evans says, you need a closing parenthesis on this line:
`geom_point(data = MeteoriteData, aes(x = lat, y = long)`
Try this code:
```
require('sf')
# Read in data from .csv file
MeteoriteData <- read.csv("C:/Users/ChaseDickson_/Desktop/College/AERO 689/Semester Project/Meteorite Landings.csv")
# Convert these points to an SF object, specifying the X and Y
# column names, and supplying the CRS as 4326 (which is WGS84)
MeteoriteData <- st_as_sf(MeteoriteData, coords=c('long', 'lat'), crs=4326)
# Read in the world shape file and convert it to the same CRS
world <- st_read("C:/Users/ChaseDickson_/Desktop/College/AERO 689/Semester Project/TM_WORLD_BORDERS_SIMPL-0.3/TM_WORLD_BORDERS_SIMPL-0.3.shp")
world <- st_transform(world, crs = 4326)
# Plot it
ggplot() +
geom_sf(data = world) +
geom_sf(data = MeteoriteData) +
theme_bw()
```
Note: I don't have access to your data files so this code is from memory and untested but should get you on the right path.
| null | CC BY-SA 4.0 | null | 2022-11-17T22:58:54.257 | 2022-11-17T22:58:54.257 | null | null | 2,269,574 | null |
74,483,252 | 2 | null | 41,994,485 | 0 | null | In my situation, I did everything listed above and on other forum post:
1. Copying and pasting files
2. Adding system variables
3. Uninstalling, downloading, and reinstalling programs
4. Restarting the computer
5. Enabling debugging mode
6. Running the source code instead of the compiled program
7. Running sfc /scannow
All of this did not work.
In my case, the solution was to update Windows.
The computer was apparently running a very outdated version of Windows (10?)
After 2-3 hours of installing the update, problem solved.
Source/Inspiration: [https://www.partitionwizard.com/clone-disk/no-qt-platform-plugin-could-be-initialized.html](https://www.partitionwizard.com/clone-disk/no-qt-platform-plugin-could-be-initialized.html)
| null | CC BY-SA 4.0 | null | 2022-11-17T23:20:38.587 | 2022-11-17T23:20:38.587 | null | null | 4,868,954 | null |
74,483,307 | 2 | null | 74,479,039 | 1 | null | By default pyinstaller compiles executables in console mode... which means that unless you tell it otherwise when the application is run outside of the command line, e.g. by double clicking the `.exe` a console window will always appear.
To avoid this simply use the windowed mode of pyinstaller with the `-w` flag when compiling.
`pyinstaller -w myapp.py`
| null | CC BY-SA 4.0 | null | 2022-11-17T23:27:19.940 | 2022-11-17T23:27:19.940 | null | null | 17,829,451 | null |
74,483,330 | 2 | null | 74,483,178 | 0 | null | The result of a `get()` call is a [DataSnapshot object](https://pub.dev/documentation/firebase_database/latest/firebase_database/DataSnapshot-class.html), which has a `children` property that has all the child snapshots. That's what you do in the second code snippet, and it looks fine to me.
If you then want to get a child property of that snapshot, you can call `child("lat").value`.
```
ref.get().then((snapshot) {
for (final hospital in snapshot.children) {
print(hospital.child("lat").value);
}
}, onError: (error) {
..
});
```
| null | CC BY-SA 4.0 | null | 2022-11-17T23:30:05.433 | 2022-11-17T23:30:05.433 | null | null | 209,103 | null |
74,483,459 | 2 | null | 74,482,997 | 1 | null | Given `one` and the `other`, try replacing `one` with `conjugate(other)`:
```
>>> one = x; other = y
>>> p = one*other; q = p.subs(one, conjugate(other); im(q),re(q)
(Abs(y)**2, 0)
```
If you want to get back the original symbol after the simplifications wrought by the first replacement, follow up with a second replacement:
```
>>> p.sub(one, conjugate(other)).subs(conjugate(other), one)
x*y
```
| null | CC BY-SA 4.0 | null | 2022-11-17T23:51:19.087 | 2022-11-18T03:12:58.090 | 2022-11-18T03:12:58.090 | 1,089,161 | 1,089,161 | null |
74,483,711 | 2 | null | 29,766,827 | -1 | null | If you want to make the axis labels bold automatically (i.e. without having to add \textbf every time), you could do the following
```
from matplotlib.axes import Axes
from matplotlib import pyplot as plt
plt.rcParams['text.usetex'] = True
def get_new_func(axis_name): # returns a modified version of the Axes.set_xlabel (or y) methods
orig_func = getattr(Axes, f'set_{axis_name}label')
def add_bold(self, *args, **kwargs):
new_args = list(args)
new_args[0] = fr"\textbf{{{new_args[0]}}}" # modify the argument
return orig_func(self, *new_args, **kwargs)
return add_bold
for x in ['x', 'y']:
setattr(Axes, f'set_{x}label', get_new_func(x)) # modify the methods of the Axis class
x = np.linspace(0, 2 * 3.14, 20)
y = np.sin(x)
ax = plt.gca()
ax.plot(x, y)
ax.set_xlabel("Theta")
ax.set_ylabel("Amp")
plt.show()
```
This makes use of the fact that the `Axis.set_xlabel` and `Axis.set_ylabel` methods are attributes (in this case function objects) that can be modified by the user. The modification is done in `add_bold`, which simply calls the original function object but with a modified argument. `orig_func` and `add_bold` are defined inside of `get_new_func` in order to correctly preserve the reference to the original method (i.e. i'm forming a closure).
| null | CC BY-SA 4.0 | null | 2022-11-18T00:33:50.670 | 2022-11-18T00:33:50.670 | null | null | 13,120,841 | null |
74,483,909 | 2 | null | 56,726,663 | 0 | null | I created a swift package, [swift-ui-accompanist](https://github.com/wycliffw/swift-ui-accompanist) that has a product that you can add to your project and use as below.
```
import AccompanistAlert
import SwiftUI
struct ContentView: View {
@State var showingAddBookUI = false
@State var newBookName = ""
var body: some View {
VStack {
Button(action: { showingAddBookUI.toggle() }) {
Image(systemName: "plus")
}
}
.accompanist.alert("Add Book", isPresented: $showingAddBookUI) {
TextField("Book Name", text: $newBookName)
Button("Save", action: {
// TODO: Save book to database
newBookName = ""
})
.disabled(newBookName.count < 3)
Button("Cancel", role: .cancel, action: {
newBookName = ""
})
}
}
```
Notice that the Alert is constructed using the Swift UI DSL you are familiar with and the API is similar to that provided by Apple.
| null | CC BY-SA 4.0 | null | 2022-11-18T01:08:31.323 | 2022-11-18T11:51:36.307 | 2022-11-18T11:51:36.307 | 20,535,001 | 20,535,001 | null |
74,484,054 | 2 | null | 59,492,958 | 0 | null | I know this is kind of an old question, but I'll answer it anyway for future people interested. The way I solved this problem was by taking a section of the signal from one array and cross-correlating the other arrays with the section. I chose the max correlation and subtracted the max index of the subarray to get the offset. Subtracting the mean of the subarray for cross-correlation is important to get the right answer. This example will confirm
```
a = np.concatenate((np.random.normal(size=100),np.random.normal(size=100)-10))
b = np.concatenate((np.random.normal(size=45),np.random.normal(size=155)-10))
max_ind = 150
min_ind = 50
small_sect = a[min_ind:max_ind]
cc = scipy.signal.correlate(b-np.mean(small_sect),small_sect-np.mean(small_sect))
offset = np.argmax(cc) - max_ind + 1
```
| null | CC BY-SA 4.0 | null | 2022-11-18T01:38:23.820 | 2022-11-18T01:38:23.820 | null | null | 17,763,339 | null |
74,484,417 | 2 | null | 29,766,827 | 0 | null | this is another example for you
```
import matplotlib.pyplot as plt
places = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
literacy_rate = [100, 98, 90, 85, 75, 50, 30, 45, 65, 70]
female_literacy = [95, 100, 50, 60, 85, 80, 75, 99, 70, 30]
plt.xlabel("Places")
plt.ylabel("Percentage")
plt.plot(places, literacy_rate, color='blue',
linewidth=6, label="Literacy rate")
plt.plot(places, female_literacy, color='fuchsia',
linewidth=4, label="Female Literacy rate")
plt.legend(loc='lower left', ncol=1)
```
and the youtput will be like this:
[](https://i.stack.imgur.com/8j2tN.png)
| null | CC BY-SA 4.0 | null | 2022-11-18T02:54:19.357 | 2022-11-18T02:54:19.357 | null | null | 20,505,208 | null |
74,485,154 | 2 | null | 74,485,127 | 2 | null | An integer is stored in memory in different ways on different architectures. Most commons ways are called little-endian and big-endian byte ordering.
See [Endianness](https://en.wikipedia.org/wiki/Endianness)
```
(long long)p+1
|
v
Your memory: [0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, ...]
```
You increment p not like pointer but as a long long number, so it does not point to next integer but the next byte. So you will get 0x00, 0x00, 0x00, 0x01 which translates to 0x1000000 (decimal 16777216) in a little-endian arch.
| null | CC BY-SA 4.0 | null | 2022-11-18T05:05:43.850 | 2022-11-18T06:02:35.597 | 2022-11-18T06:02:35.597 | 5,106,317 | 5,106,317 | null |
74,485,160 | 2 | null | 74,484,978 | 0 | null | MySQL supports aliased column names to be used inside a `HAVING` clause, PostgreSQL does not. So for your Postgres query, write `sum(rate)` again instead of `total_rate`:
```
select
name,
sum(rate) as total_rate
from
gross
group by
name
having
sum(rate) > 10 -- call the aggregation again
;
```
| null | CC BY-SA 4.0 | null | 2022-11-18T05:07:59.530 | 2022-11-18T05:08:53.487 | 2022-11-18T05:08:53.487 | 17,106,278 | 17,106,278 | null |
74,485,352 | 2 | null | 74,476,740 | 1 | null | This is a known bug in the current version of VS Code:
[https://github.com/microsoft/vscode/issues/165352](https://github.com/microsoft/vscode/issues/165352)
| null | CC BY-SA 4.0 | null | 2022-11-18T05:40:29.503 | 2022-11-18T05:40:29.503 | null | null | 131,948 | null |
74,485,489 | 2 | null | 71,526,164 | 2 | null | I couldn't figure out how to use Beni's answer to specify which colour I wanted to apply to specific features on the map.
Turns out that `colorFactor` returns a function. You need to supply the field you want to use to colour the features:
```
library('sf')
library('leaflet')
library('mapview')
# Read in shapefile and keep the first three features
ncShp <- st_read(system.file("shape/nc.shp", package="sf"))[1:3, ]
ncShp
# Simple feature collection with 3 features and 14 fields
# Geometry type: MULTIPOLYGON
# Dimension: XY
# Bounding box: xmin: -81.74107 ymin: 36.23388 xmax: -80.43531 ymax: 36.58965
# Geodetic CRS: NAD27
# AREA PERIMETER CNTY_ CNTY_ID NAME FIPS FIPSNO CRESS_ID BIR74 SID74 NWBIR74 BIR79 SID79 NWBIR79 geometry
# 1 0.114 1.442 1825 1825 Ashe 37009 37009 5 1091 1 10 1364 0 19 MULTIPOLYGON (((-81.47276 3...
# 2 0.061 1.231 1827 1827 Alleghany 37005 37005 3 487 0 10 542 3 12 MULTIPOLYGON (((-81.23989 3...
# 3 0.143 1.630 1828 1828 Surry 37171 37171 86 3188 5 208 3616 6 260 MULTIPOLYGON (((-80.45634 3...
cols <- c('red', 'green', 'blue')
# Colour our features sequentially based on the NAME field
ncShp$NAME
# [1] "Ashe" "Alleghany" "Surry"
# Ashe will be red, Alleghany will be green, Surry will be blue
colPal <- leaflet::colorFactor(palette = cols, levels = ncShp$NAME)
# Note: use levels(ncShp$NAME) if it's already a factor
# Send it to mapview
mapview::mapview(ncShp, zcol='NAME', col.regions=colPal(ncShp$NAME))
```
[](https://i.stack.imgur.com/GODMF.png)
| null | CC BY-SA 4.0 | null | 2022-11-18T06:03:45.607 | 2022-11-18T06:23:07.167 | 2022-11-18T06:23:07.167 | 2,269,574 | 2,269,574 | null |
74,485,546 | 2 | null | 74,485,127 | 0 | null | `p = (long long)p + 1;` is bad code ( UB (e.g. bus fault and re-booted machine)) as it is not specified to work in C. The attempted assigned of the newly formed address is not certainly aligned to `int *` needs.
Don`t do that.
---
To look at the bytes of `a[]`
```
#include <stdio.h>
#include <stdlib.h>
void dump(size_t sz, const void *ptr) {
const unsigned char *byte_ptr = (const unsigned char *) ptr;
for (size_t i = 0; i < sz; i++) {
printf("%p %02X\n", (void*) byte_ptr, *byte_ptr);
byte_ptr++;
}
}
int main(void) {
unsigned int a[3] = {1, 1, 0x7f7f0501u};
dump(sizeof a, a);
}
```
As this is wiki, feel open to edit.
| null | CC BY-SA 4.0 | null | 2022-11-18T06:11:13.570 | 2022-11-18T06:19:58.663 | 2022-11-18T06:19:58.663 | 2,410,359 | 2,410,359 | null |
74,485,796 | 2 | null | 74,485,127 | 0 | null | There are multiple instances of undefined behavior in your code:
- in `printf("%d %p\n", *p, p)` you should cast `p` as `(void *)p` to ensure `printf` receives a `void *` as it expects. This is unlikely to pose a problem on most current targets but some ancien systems had different representations for `int *` and `void *`, such as early Cray systems.- in `p = (long long)p + 1`, you have implementation defined behavior converting a pointer to an integer and implicitly converting the integral result of the addition back to a pointer. More importantly, this may create a pointer with incorrect alignment for accessing `int` in memory, resulting in undefined behavior when you dereference `p`. This would cause a bus error on many systems, eg: most RISC architectures, but by chance not on intel processors. It would be safer to compute the pointer as `p = (void *)((intptr_t)p + 1);` or `p = (void *)((char *)p + 1);` albeit this would still have undefined behavior because of alignment issues.
> is the number 1 stored in memory as 00000001 00000000 00000000 00000000?
Yes, your system seems to use little endian representation for `int` types. The least significant 8 bits are stored in the byte at the address of `a`, then the next least significant 8 bits, and so on. As can be seen in the output, `1` is stored as `01 00 00 00` and `0x7f7f0501` stored as `01 05 7f 7f`.
> Why is 16777216 printed in the output?
The second instance of `printf("%d %p\n", *p, p)` as undefined behavior. On your system, `p` points to the second byte of the array `a` and `*p` reads 4 bytes from this address, namely `00 00 00 01` (the last 3 bytes of `1` and the first byte of the next array element, also `1`), which is the representation of the `int` value `16777216`.
To dump the contents of the array as bytes, you should access it using a `char *` as you do in the last loop. Be aware that `char` may be signed on some systems, causing for example `printf("%x\n", *p3);` to output `ffffff80` if `p3` points to the byte with hex value `80`. Using `unsigned char *` is recommended for consistent and portable behavior.
| null | CC BY-SA 4.0 | null | 2022-11-18T06:42:06.783 | 2022-11-20T16:59:38.453 | 2022-11-20T16:59:38.453 | 4,593,267 | 4,593,267 | null |
74,485,820 | 2 | null | 74,485,779 | 0 | null | it's possible using body::after content "text" and style it
| null | CC BY-SA 4.0 | null | 2022-11-18T06:45:20.913 | 2022-11-18T06:45:20.913 | null | null | 15,875,774 | null |
74,485,825 | 2 | null | 74,485,779 | 2 | null |
### You can add the CSS properties inside a class. Then add the class to an HTML element with text-decoration: none; property as follows:
```
.pure_css_button {
display: inline-block;
width: 165px;
text-align: center;
color: #fff;
text-decoration: none;
background: linear-gradient(180deg, #4b3529 21%, #4c2e1a 100%);
border-radius: 5px;
border: 1px solid #ffffff;
font-family: Arial;
font-weight: normal;
border-left: 2px solid #e5ccaf;
border-image: linear-gradient(to bottom, #ffd400, rgba(0, 0, 0, 0)) 0 100%;
border-top: 1px solid #ffd400;
}
```
```
<a href="#" class="pure_css_button">
Button</a>
```
| null | CC BY-SA 4.0 | null | 2022-11-18T06:45:43.523 | 2022-11-18T07:50:24.057 | 2022-11-18T07:50:24.057 | 8,188,682 | 8,188,682 | null |
74,486,181 | 2 | null | 74,485,779 | 1 | null | ```
button {
cursor: pointer;
font-size: x-large;
padding: 0.6rem 2rem;
font-weight: bold;
overflow: hidden;
color: #fff;
background: linear-gradient(180deg, #4b3529 21%, #4c2e1a 100%);
border:0;
border-radius: .3rem;
position: relative;
border-top: 2px solid hsl(24, 49%, 15%);
border-bottom: 2px solid hsl(24, 49%, 15%);
}
button::after,button::before{
content: '';
height: 100%;
width: .15rem;
position: absolute;
top:0;
background:linear-gradient(to bottom, #ffd400, rgba(0, 0, 0, 0)) ;
}
button::before{
left: 0;
}
button::after{
right: 0;
}
```
```
<button>
Pure Css</button>
```
| null | CC BY-SA 4.0 | null | 2022-11-18T07:23:26.413 | 2022-11-18T07:23:26.413 | null | null | 18,046,485 | null |
74,486,481 | 2 | null | 74,398,075 | 0 | null | i think you should use Ajax to get the data from controller to view without refreshing the whole page
| null | CC BY-SA 4.0 | null | 2022-11-18T07:53:34.287 | 2022-11-18T07:53:34.287 | null | null | 15,448,229 | null |
74,486,485 | 2 | null | 74,484,945 | 0 | null | your AM looks OK to me I see no frequency change and the formula is OK (if your `amplitude(time) = 200.0*time`). However I see one problem and that is that you "increment" the `y+=` axis which is wrong and should be `y=` , for the x value its OK.
The FM is wrong, I would expect at least linear interpolation, You need some constrains/constants first:
```
f0 - min output frequency
f1 - max output frequency
a0 - min value of input signal
a1 - max value of input signal
A(t) - input signal you want to modulate with
B - output amplitude
t - time
```
then:
```
// constants
B = 200.0
a0 = 0.0
a1 = amplitude * time_duration
f0 = 1500.0
f1 = 2500.0
---------------------
t += delta
A = amplitude*time
f = f0 + (f1-f0)*(A-a0)/(a1-a0)
point.y = B * cos(f * t) * delta
point.x += 100.0 * delta
```
You might also want to add clamping of `f` to `<f0,f1>` ...
| null | CC BY-SA 4.0 | null | 2022-11-18T07:54:09.907 | 2022-11-18T07:54:09.907 | null | null | 2,521,214 | null |
74,486,497 | 2 | null | 35,512,975 | 1 | null | Addition to the accepted answer - for me solution didn't work, the reason behind this was no proper viewbox in svg
Adding
```
if (svg.documentViewBox == null)
svg.setDocumentViewBox(0f, 0f, svg.documentWidth, svg.documentHeight)
```
before changing svg width/height fixed scaling finally
| null | CC BY-SA 4.0 | null | 2022-11-18T07:54:56.317 | 2022-11-18T07:54:56.317 | null | null | 16,359,536 | null |
74,486,560 | 2 | null | 74,485,127 | 2 | null | Something to play with (assuming `int` is 32 bits wide):
```
#include <stdio.h>
#include <stdbool.h>
typedef union byte_rec {
struct bit_rec {
bool b0 : 1;
bool b1 : 1;
bool b2 : 1;
bool b3 : 1;
bool b4 : 1;
bool b5 : 1;
bool b6 : 1;
bool b7 : 1;
} bits;
unsigned char value;
} byte_t;
typedef union int_rec {
struct bytes_rec {
byte_t b0;
byte_t b1;
byte_t b2;
byte_t b3;
} bytes;
int value;
} int_t;
void printByte(byte_t *b)
{
printf(
"%d %d %d %d %d %d %d %d ",
b->bits.b0,
b->bits.b1,
b->bits.b2,
b->bits.b3,
b->bits.b4,
b->bits.b5,
b->bits.b6,
b->bits.b7
);
}
void printInt(int_t *i)
{
printf("%p: ", i);
printByte(&i->bytes.b0);
printByte(&i->bytes.b1);
printByte(&i->bytes.b2);
printByte(&i->bytes.b3);
putchar('\n');
}
int main()
{
int_t i1, i2;
i1.value = 0x00000001;
i2.value = 0x80000000;
printInt(&i1);
printInt(&i2);
return 0;
}
```
Possible output:
```
0x7ffea0e30920: 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0x7ffea0e30924: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
```
---
(based on the comment of @chqrlie):
I've previously used the `unsigned char` type, but the C Standard allows only 3 - and since C99 - 4 types. Additional implementation-defined types may be acceptable by the C Standard and it seems that gcc was ok with the `unsigned char` type for the bit field, but i've changed it nevertheless to the allowed type `_Bool` (since C99).
: The order of bit fields within an allocation unit (on some platforms, bit fields are packed left-to-right, on others right-to-left) are undefined (see section in the reference).
Reference to bit fields: [https://en.cppreference.com/w/c/language/bit_field](https://en.cppreference.com/w/c/language/bit_field)
| null | CC BY-SA 4.0 | null | 2022-11-18T08:01:29.950 | 2022-11-18T13:22:35.743 | 2022-11-18T13:22:35.743 | 11,867,590 | 11,867,590 | null |
74,486,813 | 2 | null | 72,508,876 | 0 | null | There might be a reason for mamba forcing you to install it in base environment. But in most cases, installing packages in base environment to avoid a test issue sounds dimishing the point of having conda environments...
I ran into the same issue but with other packages.
In my case, the issue is an open [VSCode bug](https://github.com/microsoft/vscode-python/issues/4300). See the replies for workarounds that don't require you to stick to the base environment.
This works for me:
1. Activate the conda environment in command line and the also launch the VSCode from there.
2. Create a launch.json file in VSCode to tell the debugger to use the integrated terminal:
```
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug file",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
},
{
"name": "Debug tests",
"type": "python",
"request": "test",
"console": "integratedTerminal",
}
]
}
```
Also, if you have Anaconda Navigate, you can launch the bundled VSCode in the correct environment from the UI. That should launch a VSCode that has everything already configured for the environment.
| null | CC BY-SA 4.0 | null | 2022-11-18T08:29:08.340 | 2022-11-18T08:29:08.340 | null | null | 4,342,167 | null |
74,487,000 | 2 | null | 69,655,474 | 0 | null | Extending to Amir's answer
Running on a Pixel 5 API 32 device and targetSdkVersion to 31.
The children of TextInputEditText are shown as below:
[](https://i.stack.imgur.com/qZZ3Z.png)
So we might use following code to set this view's alpha by:
```
id_of_text_input_layout.findViewById<View>(R.id.text_input_end_icon)?.alpha = 1f
```
| null | CC BY-SA 4.0 | null | 2022-11-18T08:47:06.643 | 2022-11-18T08:47:06.643 | null | null | 1,083,128 | null |
74,487,018 | 2 | null | 30,585,879 | 1 | null | In PyCharm 2022.2.3, this is noinspection comment when I select "Suppress for a statement".
[](https://i.stack.imgur.com/ERE2A.png)
So if you select "Disable inspection" by mistake
[](https://i.stack.imgur.com/Nd3ks.png)
Then turn on the option "Unresolved references".
(Settings > Inspections > Python > Unresolved references)
[](https://i.stack.imgur.com/yUwsP.png)
And then you can enable again like below screenshot.
[](https://i.stack.imgur.com/43ko3.png)
| null | CC BY-SA 4.0 | null | 2022-11-18T08:47:56.443 | 2022-11-18T08:47:56.443 | null | null | 3,703,341 | null |
74,487,794 | 2 | null | 72,137,839 | 0 | null | try [https://pypi.org/project/c3d/](https://pypi.org/project/c3d/)
or [https://github.com/pyomeca/pyomeca](https://github.com/pyomeca/pyomeca)
its easier with them than with btk toolkit. You will need to see docs to get it done. I am using those to read only, then switch to numpy or pandas.
| null | CC BY-SA 4.0 | null | 2022-11-18T09:52:23.773 | 2022-11-18T09:52:23.773 | null | null | 11,559,034 | null |
74,488,141 | 2 | null | 74,477,210 | 0 | null | found the solution,the miliseconds i received had 6 digits, but the value stored in the server is 3 digits. so by removing the miliseconds the problem was solved
| null | CC BY-SA 4.0 | null | 2022-11-18T10:19:44.477 | 2022-11-18T10:19:44.477 | null | null | 15,185,140 | null |
74,488,639 | 2 | null | 74,488,554 | 2 | null | The [latest source code](https://github.com/serilog/serilog/blob/dev/src/Serilog/Log.cs#L477) uses the same arguments and won't generate any nullability warnings :
```
[MessageTemplateFormatMethod("messageTemplate")]
public static void Debug(string messageTemplate, params object?[]? propertyValues)
{
Logger.Debug(messageTemplate, propertyValues);
}
```
Github's Blame shows that this line was last modified in August 2022. The fix should be included in Serilog 2.12 which was released in September 2022
| null | CC BY-SA 4.0 | null | 2022-11-18T10:59:28.757 | 2022-11-18T10:59:28.757 | null | null | 134,204 | null |
74,488,671 | 2 | null | 70,792,553 | 0 | null | Windows terminal supports ANSI escape sequences but not in default. You have to set up in some cases. This is the solution:
Windows Start --> run regedit --> add new variable to HKEY_CURRENT_USER/Console (name: VirtualTerminalLevel type: double word value type: decimal value: 1)
| null | CC BY-SA 4.0 | null | 2022-11-18T11:02:52.637 | 2022-11-18T11:02:52.637 | null | null | 20,538,896 | null |
74,488,824 | 2 | null | 52,169,440 | 0 | null | You need to install extension for programming language you use, If extension is already installed then it may require "Reload". You can search extension and check whether if requires "Reload" or not. After reload the formatting will be fine.
| null | CC BY-SA 4.0 | null | 2022-11-18T11:14:36.673 | 2022-11-18T11:14:36.673 | null | null | 9,624,615 | null |
74,488,871 | 2 | null | 62,157,071 | 0 | null | I am using material UI. also it has taken a lot of time to figure it out how to remove it after clicking the border. I found a way to remove the border using the below code it will help.
```
"&.MuiDataGrid-cell:focus-within": {
outline: "none",
},
```
| null | CC BY-SA 4.0 | null | 2022-11-18T11:18:36.770 | 2022-11-18T11:18:36.770 | null | null | 20,539,000 | null |
74,489,303 | 2 | null | 74,467,793 | 0 | null | Here is script you can start with, I suggest you read the user guide first to understand it and further develop it to your needs.
```
//@version=5
indicator("outside bar",overlay=true)
var float inside_bar_high = high
var float inside_bar_low = low
var float outside_bar_high = high
var float outside_bar_low = low
inside_bar = high<= outside_bar_high and low>= outside_bar_low
if (inside_bar) // If there is a new inside bar, update the high and low price
inside_bar_high := high
inside_bar_low := low
if not(inside_bar)
outside_bar_high := high
outside_bar_low := low
last_bar_outside=inside_bar
plotshape(last_bar_outside, shape=shape.arrowdown,location=location.abovebar,offset=-1,color=color.red)
```
| null | CC BY-SA 4.0 | null | 2022-11-18T11:56:20.220 | 2022-11-18T11:56:20.220 | null | null | 15,248,529 | null |
74,489,427 | 2 | null | 74,489,306 | 0 | null | It seems like that you're looking for this: [Find mouse position relative to element](https://stackoverflow.com/questions/3234256/find-mouse-position-relative-to-element). ([getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect))
But there are plenty options that you can use for example [<map>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map).
| null | CC BY-SA 4.0 | null | 2022-11-18T12:05:27.117 | 2022-11-18T12:05:27.117 | null | null | 19,147,494 | null |
74,489,708 | 2 | null | 40,419,770 | 0 | null | To elaborate on @torek's comment using [git merge-file](https://git-scm.com/docs/git-merge-file): Suppose we have our merge conflict (I recreated the setup just like the OP's, see below), first restore the previous versions of our file `test1.csv` as temporary files...
```
% git show :1:test1.csv > common
% git show :2:test1.csv > ours
% git show :3:test1.csv > theirs
```
...then do the merge "by hand" (`-p` is for stdout): Add the merged file as `test1.csv`, clean the temporary files and commit the merge:
```
% git merge-file -p ours common theirs --union > test1.csv
% git add test1.csv
% git clean # remove ours, common, theirs
```
This could be easily scripted. For comparison, here is the output for the other "merge"-options, `--ours` and `--theirs`, respectively:
```
% git merge-file -p ours common theirs --ours
old-entry
old-entry
old-entry
test1-a
test1-b
% git merge-file -p ours common theirs --theirs
old-entry
old-entry
old-entry
test2-c
% git merge-file -p ours common theirs --union
old-entry
old-entry
old-entry
test1-a
test1-b
test2-c
```
The `--union` is exactly what the OP wants!
I find this kind of merge conflict , especially when merging auto-generated files. I agree with @Tim Biegeleisen that git should not merge this , but why it does not have some sort of merge strategy to resolve this is a really good question.
---
### (the setup)
```
[test1] % git show test1
...
@@ -1,3 +1,5 @@
old-entry
old-entry
old-entry
+test1-a
+test1-b
[test1] % git show test2
...
@@ -1,3 +1,4 @@
old-entry
old-entry
old-entry
+test2-c
[test1] % git merge test2
Auto-merging test1.csv
CONFLICT (content): Merge conflict in test1.csv
Automatic merge failed; fix conflicts and then commit the result.
```
| null | CC BY-SA 4.0 | null | 2022-11-18T12:29:00.453 | 2022-11-28T17:23:45.897 | 2022-11-28T17:23:45.897 | 9,257,878 | 9,257,878 | null |
74,489,896 | 2 | null | 9,132,826 | 2 | null | I'm on macOS Ventura and receive
[](https://i.stack.imgur.com/N11H7.png)
## TL;DR
`sudo dscl . append /Groups/_developer GroupMembership <username>`
As per [https://stackoverflow.com/a/1837935/5506988](https://stackoverflow.com/a/1837935/5506988)
## What was tried
`sudo /usr/sbin/DevToolsSecurity --enable` says it's already enabled.
After entering my username and password, it works but then I have to do this every time I launch the debugger.
If I run `sudo security authorizationdb write system.privilege.taskport allow` it prevents the prompt
I tried following the existing answers that ask you to update `/etc/authorization` - which has been deprecated since macOS mavericks and is now `/System/Library/Security/authorization.plist` but I couldn't edit this file (I even tried [this](https://apple.stackexchange.com/questions/68646/how-do-i-unlock-a-plist-file-so-that-i-can-change-it)) but since my `$USER` isn't an owner of the file so I can't force overwrite it even with sudo.
I tried
```
sudo /usr/libexec/PlistBuddy -c "Set :rights:system.privilege.taskport:class allow" authorization.plist
```
But of course, the same applies but instead this fails silently.
If I run `id -a` it returns `204(_developer)` so I am part of the developer group even before running the `dcsl` command
What fixed it for me was
```
sudo dscl . append /Groups/_developer GroupMembership <username>
```
| null | CC BY-SA 4.0 | null | 2022-11-18T12:45:23.857 | 2022-11-21T23:06:13.023 | 2022-11-21T23:06:13.023 | 5,506,988 | 5,506,988 | null |
74,489,932 | 2 | null | 74,489,742 | 1 | null | I think that the problem here is that you cant align different boxes in different directions simultaniously.
What I think could help is moving the `<section>` blocks in a separate flexbox, and aligning them in there differently.
The HTML code will look like this:
```
<div class="footer__main__div">
<div class="footer__left__div">
</div>
<div class="footer__right__div">
<section class="footer__list__section">
</section>
<section class="footer__list__section">
</section>
<section class="footer__list__section">
</section>
</div>
</div>
```
| null | CC BY-SA 4.0 | null | 2022-11-18T12:48:38.460 | 2022-11-18T12:48:38.460 | null | null | 20,539,572 | null |
74,490,123 | 2 | null | 74,489,742 | 0 | null | To achieve the intended layout, you need to add `width: 100%` to the div that should contain the text. and define a width for the sections:
```
.footer__main__div {
display: flex;
margin-left: auto;
margin-right: auto;
max-width: 1280px;
flex-wrap: wrap;
justify-content: space-between;
padding-top: 2.5rem;
padding-bottom: 2.5rem;
padding-left: 1.25rem;
padding-right: 1.25rem;
}
.footer__left__div {
box-sizing: border-box;
border: 2px dashed blue;
width: 100%;
}
section {
box-sizing: border-box;
width: 25%;
border: 2px dashed green;
}
```
```
<div class="footer__main__div">
<div class="footer__left__div">
text
</div>
<section class="footer__list__section">
services
</section>
<section class="footer__list__section">
social
</section>
<section class="footer__list__section">
support
</section>
</div>
```
| null | CC BY-SA 4.0 | null | 2022-11-18T13:03:53.267 | 2022-11-18T13:03:53.267 | null | null | 14,072,420 | null |
74,490,148 | 2 | null | 74,484,945 | 1 | null | - `2 * PI * F * T`- - - [https://upload.wikimedia.org/wikipedia/commons/a/a4/Amfm3-en-de.gif](https://upload.wikimedia.org/wikipedia/commons/a/a4/Amfm3-en-de.gif)- [https://www.researchgate.net/figure/a-The-mathematical-equation-for-Frequency-Modulation-and-definition-of-terms_fig9_243778275](https://www.researchgate.net/figure/a-The-mathematical-equation-for-Frequency-Modulation-and-definition-of-terms_fig9_243778275)
```
extends Control
var time: float = 0.0
var frequency: float = 4.0
var carrier_amplitude : float = 1.0
var carrier_frequency : float = 0.2
const pixels_per_x = 100; # zoom on x
const pixels_per_y = 100; # zoom on y
func _physics_process(delta):
var point : Vector2
time += delta
var _signal = cos(2 * PI * frequency * time)
var modulating_signal = carrier_amplitude * cos(2 * PI * carrier_frequency * time)
point.y = pixels_per_y * (_signal * modulating_signal)
point.x = pixels_per_x * (time)
$Line2D.add_point(point)
```
[](https://i.stack.imgur.com/J4kwT.png)
```
extends Control
var time: float = 0.0
var frequency: float = 2
var modulation_index : float = 4
var modulation_frequency : float = 0.2
const pixels_per_x = 100; # zoom on x
const pixels_per_y = 100; # zoom on y
func _physics_process(delta):
var point : Vector2
time += delta
var fm_signal = cos( (2 * PI * frequency * time) + modulation_index*sin(2 * PI * modulation_frequency * time) ) # this is another method that adds offset onto phase
point.y = pixels_per_y * (fm_signal)
point.x = pixels_per_x * (time)
$Line2D.add_point(point)
```
[](https://i.stack.imgur.com/wNa6j.png)
| null | CC BY-SA 4.0 | null | 2022-11-18T13:07:17.427 | 2022-11-18T13:07:17.427 | null | null | 2,368,681 | null |
74,490,929 | 2 | null | 74,490,397 | 1 | null | You could achieve your desired result by assigning the same name to the `color` and `shape` legends or by removing both as I do in my code below using `labs`.
Using a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) based on the `gapminder` dataset:
```
library(gapminder)
library(tidyverse)
# Create example data
data <- gapminder |>
select(Year = year, continent, value = lifeExp) |>
group_by(Year, continent) |>
summarise(value = mean(value), .groups = "drop") |>
pivot_wider(names_from = continent, values_from = value) |>
select(Year, Temperature = 2, y2 = 3, y3 = 4, y4 = 5)
ggplot(data, aes(x = Year)) +
geom_point(aes(y = Temperature, colour = "Africa", shape = "Africa")) +
geom_point(aes(y = y2, colour = "Asia", shape = "Asia")) +
geom_point(aes(y = y3, colour = "Europe", shape = "Europe")) +
geom_point(aes(y = y4, colour = "Australia", shape = "Australia")) +
labs(color = NULL, shape = NULL)
```

| null | CC BY-SA 4.0 | null | 2022-11-18T14:10:36.987 | 2022-11-18T14:10:36.987 | null | null | 12,993,861 | null |
74,490,969 | 2 | null | 11,682,216 | 0 | null | The final resolution for me, after 3 days of trying all the other answers I could find here, was setting Enable 32-bit Applications to True in my IIS application pool advanced settings, then recreating the Temporary ASP.NET Files directory and adding Modify and Write permissions for my IIS_IUSRS group.
Steps I tried:
- - - - - - `AnyCPU`- `bin/`- - - - - - - - - - `Codebehind="Global.asax.cs"``Codefile="Global.asax.cs"`- -
I was able to cobble enough information together from the myriad answers I found all over the Internet. After finding this answer after searching for [iis not finding referenced .net dlls](https://stackoverflow.com/q/7996263/1307074), I tried the final couple steps that got me working again, on the beginning of my 4th day wrestling with this incredibly vague problem.
This would have gone a lot faster if there were some way to diagnose the Global.asax was unable to be loaded instead of the too-generic `Could not load type` error with no detail.
Moral of this story: when cleaning the Temporary ASP.NET Files directories, delete the contents of the directories, not the directories themselves. Otherwise, permissions can be lost.
| null | CC BY-SA 4.0 | null | 2022-11-18T14:13:51.330 | 2022-12-16T15:53:42.883 | 2022-12-16T15:53:42.883 | 1,307,074 | 1,307,074 | null |
74,491,369 | 2 | null | 74,491,174 | 1 | null | You cannot (at least not without going a long way using a separate splash screen activity).
That's a limitation of Android: [https://developer.android.com/develop/ui/views/launch/splash-screen](https://developer.android.com/develop/ui/views/launch/splash-screen)
The picture also needs to fit into the frame and should be squared. You can set the base size for that in the `<MauiSplashSceen>` build action in your `.csproj` file.
You may also be interested in this: [Custom NET MAUI Splash screen](https://stackoverflow.com/questions/73465373/custom-net-maui-splash-screen)
There currently also is a bug in MAUI's resizetizer which requires giving the SVG file an entirely new name each time you want to change it: [https://stackoverflow.com/a/74336491/4308455](https://stackoverflow.com/a/74336491/4308455)
I've written a blog post about the Splash Screen in MAUI, which might also be of interest: [https://ewerspej.hashnode.dev/lets-customize-the-splash-screen-of-a-maui-app](https://ewerspej.hashnode.dev/lets-customize-the-splash-screen-of-a-maui-app)
| null | CC BY-SA 4.0 | null | 2022-11-18T14:43:37.187 | 2022-11-18T14:51:18.930 | 2022-11-18T14:51:18.930 | 4,308,455 | 4,308,455 | null |
74,491,529 | 2 | null | 74,482,626 | 0 | null | You can find some great examples of how to create a heatmap from [matplotlib website](https://matplotlib.org/stable/gallery/images_contours_and_fields/image_annotated_heatmap.html).
Here is a basic code with some random data:
```
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
index_labels = np.arange(0,24)
column_labels = pd.date_range(start='1/1/2022', end='1/31/2022').strftime('%m/%d')
#random data
np.random.seed(12345)
data = np.random.randint(0,60, size=(len(index_labels), len(column_labels)))
df = pd.DataFrame(data=data, columns=column_labels, index=index_labels)
#heatmap function
def heatmap(df, ax, cbarlabel="", cmap="Greens", label_num_dec_place=0):
df = df.copy()
# Ploting a blank heatmap
im = ax.imshow(df.values, cmap)
# create a customized colorbar
cbar = ax.figure.colorbar(im, ax=ax, fraction=0.05, extend='both', extendfrac=0.05)
cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom", fontsize=14)
# Setting ticks
ax.set_xticks(np.arange(df.shape[1]), labels=df.columns, fontsize=12)
ax.set_yticks(np.arange(df.shape[0]), labels=list(df.index), fontsize=12)
# proper placement of ticks
ax.tick_params(axis='x', top=True, bottom=False,
labeltop=True, labelbottom=False)
ax.spines[:].set_visible(False)
ax.grid(which="both", visible="False", color="white", linestyle='solid', linewidth=2)
ax.grid(False)
# Rotation of tick labels
plt.setp(ax.get_xticklabels(), rotation=-60,
ha="right", rotation_mode=None)
plt.setp(ax.get_yticklabels(), rotation=30)
#plotting and saving
fig, ax = plt.subplots(facecolor=(1,1,1), figsize=(20,8), dpi=200)
heatmap(df=df, ax=ax, cbarlabel="time (min)", cmap="Greens", label_num_dec_place=0)
plt.savefig('time_heatmap.png',
bbox_inches='tight',
facecolor=fig.get_facecolor(),
transparent=True,
)
```
Output:
[](https://i.stack.imgur.com/Jvddb.png)
| null | CC BY-SA 4.0 | null | 2022-11-18T14:56:12.167 | 2022-11-18T14:56:12.167 | null | null | 17,658,327 | null |
74,491,544 | 2 | null | 74,491,000 | 0 | null | You are explicitly excluding the main post from the `$related_posts` data - as per the `AND icinde_id != $icinde_id` in the WHERE clause of your second query.
Unless you really to keep the "related posts" data separate for some other purpose in another part of your script, you could get it to just output the main post in the same dataset.
I can't see your database obviously, but I think
```
SELECT * FROM
icindekiler
WHERE
icinde_kitap_id = $icinde_kitap_id
OR icinde_id = $icinde_id
```
would work for that
** Obviously please adjust the above to prevent SQL injection and related problems by parameterising the input variables.
| null | CC BY-SA 4.0 | null | 2022-11-18T14:57:19.750 | 2022-11-18T14:57:19.750 | null | null | 5,947,043 | null |
74,492,237 | 2 | null | 74,492,067 | 0 | null | Modules don't create global variables. They have their own scope.
The script `main.js` doesn't have access to the variables defined by the module.
1. Move the module to its own file.
2. export the values you want that module to share.
3. Make main.js a module
4. Inside main.js, import the values from step 2 from the module module at step 1
| null | CC BY-SA 4.0 | null | 2022-11-18T15:55:52.630 | 2022-11-18T16:12:45.037 | 2022-11-18T16:12:45.037 | 19,068 | 19,068 | null |
74,495,394 | 2 | null | 74,495,313 | 0 | null | A `full join` will return all records where there is a match on either side of the `join`. This is causes SQL to return multiple copies of the data for Andy.
Change the query to use an `INNER JOIN`, which will only produce matching records:
```
SELECT junction1.Name1,
SUM(test1.Amount) AS Grocery1,
SUM(test2.Amount) AS Grocery2
FROM test1
INNER JOIN junction1 ON test1.ID1 = junction1.ID1
INNER JOIN test2 ON test2.ID2 = junction1.ID2
GROUP BY junction1.Name1
```
| null | CC BY-SA 4.0 | null | 2022-11-18T21:16:12.813 | 2022-11-18T21:16:12.813 | null | null | 47,580 | null |
74,495,431 | 2 | null | 74,495,346 | 0 | null | > I was expecting the query to return weeks 1 and 2 only but for some reason I am getting 53
The [documentation](https://www.postgresql.org/docs/current/functions-datetime.html) does a good job explaining the ISO rules for weeks - which Postgres follows:
> The number of the ISO 8601 week-numbering week of the year. . In other words, the first Thursday of a year is in week 1 of that year.
Using your dataset:
```
SELECT r.*,
extract(week from registration_date) AS week_num,
extract(isodow from registration_date) as day_of_week
FROM runners r
ORDER BY registration_date;
```
| runner_id | registration_date | week_num | day_of_week |
| --------- | ----------------- | -------- | ----------- |
| 1 | 2021-01-01 | 53 | 5 |
| 2 | 2021-01-03 | 53 | 7 |
| 3 | 2021-01-08 | 1 | 5 |
| 4 | 2021-01-15 | 2 | 5 |
It turns out that January 3rd, 2021 was a Sunday (day of week `7`). January 4st, 2021 was a Monday, and according to the ISO rules this is when the first week of that year began. Previous dates (January 3rd, 2nd, 1st, and so on) belong to the last week of 2020 (week 53), although the dates belong to year 2021.
| null | CC BY-SA 4.0 | null | 2022-11-18T21:21:42.567 | 2022-11-18T21:21:42.567 | null | null | 10,676,716 | null |
74,495,661 | 2 | null | 74,495,614 | 0 | null | Simply (force) delete the other branches, then rename your branch:
```
git branch -D master main
git checkout rework
git branch -m main
```
NB. commits of your "pink" branches will be unreachable and are basically lost. You will not have access to them anymore via normal means.
This will only affect your local repository. If the branches already exist in a remote repository, be aware that you have rewritten your repository's history. This could be bad, if it were shared between several developers. If that's okay, then you can force-push your local branch state to the remote repository.
| null | CC BY-SA 4.0 | null | 2022-11-18T21:47:41.187 | 2022-11-18T22:00:11.060 | 2022-11-18T22:00:11.060 | 112,968 | 112,968 | null |
74,495,724 | 2 | null | 74,495,113 | 0 | null | I suppose you're using [Gaussian Mixture Model](https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html#sklearn.mixture.GaussianMixture) from .
In that case from the docs
```
import numpy as np
from sklearn.mixture import GaussianMixture
X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])
gm = GaussianMixture(n_components=2, random_state=0).fit(X)
```
The attributes `gm.means_` are the means of each mixture component.
And `gm.covariances_` are the covariance (or variance for 1D) of each mixture component.
With those (using a `for`) you can easily plot each component using, for example, something like bellow for the first component:
```
from scipy.stats import norm
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(...) # your x space sampled
p = norm.pdf(x, gm.means_[0], gm.covariances_[0])
plt.plot(x, p)
```
And you can even sum them up, as you wish, to make a combined plot of their pdf's.
| null | CC BY-SA 4.0 | null | 2022-11-18T21:55:26.790 | 2022-12-01T10:32:45.957 | 2022-12-01T10:32:45.957 | 1,207,193 | 1,207,193 | null |
74,495,861 | 2 | null | 74,495,313 | 1 | null | I don't think you want a full join. You would if both tables could be joined together directly, but the fact that we need to to through the junction table changes the situation.
We can start from the junction table, then `union` both grocery tables (while separating the original columns) and bring them with a `left join` on both possibles matches. The last step is aggregation:
```
select j.name1, sum(t.amount1) as grocery1, sum(t.amount2) as grocery2
from junction1 j
left join (
select id1, null as id2, amount as amount1, null as amount2 from test1
union all select null, id2, null, amount from test2
) t on t.id1 = j.id1 or t.id2 = j.id2
group by j.name1
```
Using `union` avoids the "row multiplication" issue that you are seeing. On the other hand, the `left join` ensures that records from tables are preserved, regardless of whether or not the same person actually shopped at both locations.
| null | CC BY-SA 4.0 | null | 2022-11-18T22:17:10.797 | 2022-11-18T22:17:10.797 | null | null | 10,676,716 | null |
74,496,242 | 2 | null | 66,875,624 | 0 | null | Slack needs the `sensitive_lables` option for tokens. There is an example in the [docs](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/monitoring_notification_channel#example-usage---notification-channel-sensitive)
```
resource "google_monitoring_notification_channel" "default" {
display_name = "Test Slack Channel"
type = "slack"
labels = {
"channel_name" = "#foobar"
}
sensitive_labels {
auth_token = "...."
}
}
```
| null | CC BY-SA 4.0 | null | 2022-11-18T23:17:47.387 | 2022-11-18T23:17:47.387 | null | null | 191,140 | null |
74,496,543 | 2 | null | 74,495,754 | 1 | null | You can make a stacked bar plot with an invisible lower bar. Suppose your data is like this:
```
df <- data.frame(Study = paste("Study", 1:7),
Low = c(0, 64, 0, 200, 152, 0, 180),
High = c(218, 64, 180, 352, 152, 84, 400))
df
#> Study Low High
#> 1 Study 1 0 218
#> 2 Study 2 64 64
#> 3 Study 3 0 180
#> 4 Study 4 200 352
#> 5 Study 5 152 152
#> 6 Study 6 0 84
#> 7 Study 7 180 400
```
Then you can do:
```
library(tidyverse)
df %>%
mutate(High = High - Low,
Study = fct_rev(Study)) %>%
pivot_longer(Low:High) %>%
ggplot(aes(value, Study, fill = name, color = name)) +
geom_hline(yintercept = 1:6 + 0.5, col = "lightblue", alpha = 0.3, size = 2) +
coord_cartesian(expand = FALSE) +
scale_x_continuous(limits = c(0, 500), position = "top",
name = "Fertilizer Application Rate (Kg / ha)") +
scale_y_discrete(name = NULL) +
geom_col(size = 2, width = 0.95) +
geom_text(data = df, inherit.aes = FALSE, size = 6, hjust = 0,
aes(x = 420, y = Study,
label = ifelse(Low == High, Low, paste(Low, High, sep = " - ")))) +
scale_fill_manual(values = c( "#3634bd", "#00000000"), breaks = "High",
na.value = "#00000000", guide = "none") +
scale_color_manual(values = c( "#3634bd", "#00000000"), breaks = "High",
na.value = "#00000000", guide = "none") +
theme_classic(base_size = 20) +
theme(panel.border = element_rect(fill = NA, linewidth = 1.5),
plot.margin = margin(30, 30, 30, 30),
axis.title.x.top = element_text(margin = margin(0, 0, 30, 00)))
```
[](https://i.stack.imgur.com/IbnpZ.png)
[reprex v2.0.2](https://reprex.tidyverse.org)
| null | CC BY-SA 4.0 | null | 2022-11-19T00:12:26.897 | 2022-11-19T00:12:26.897 | null | null | 12,500,315 | null |
74,496,754 | 2 | null | 74,496,613 | 6 | null | The `enumerator` method of `FileManager` that you are using performs a deep enumeration of the file tree. You don't want a deep enumeration, just a top-level enumeration. Use the version of the `enumerator` method that has the `options` parameter and pass in `.skipsSubdirectoryDescendants`.
Here's an updated version of your function getting a `URL` directly from `FileManager` for the Applications folder and then doing a shallow enumeration to get the list of apps.
```
func enumerateAppsFolder() -> [String] {
var appNames = [String]()
let fileManager = FileManager.default
if let appsURL = fileManager.urls(for: .applicationDirectory, in: .localDomainMask).first {
if let enumerator = fileManager.enumerator(at: appsURL, includingPropertiesForKeys: nil, options: .skipsSubdirectoryDescendants) {
while let element = enumerator.nextObject() as? URL {
if element.pathExtension == "app" { // checks the extension
appNames.append(element.deletingPathExtension().lastPathComponent)
}
}
}
}
return appNames
}
print(enumerateAppsFolder())
```
Sample output when run from a Swift Playground:
> "Numbers", "Dropbox", "Xcode", "Apple Configurator 2", "iMovie"
| null | CC BY-SA 4.0 | null | 2022-11-19T00:50:06.067 | 2022-11-19T00:50:06.067 | null | null | 20,287,183 | null |
74,496,764 | 2 | null | 74,482,626 | 0 | null | One way to do it is to use sampling. Choose how many samples you want to take in a given interval (the precision, for example 288 samples per day) and split each interval by that number of samples and count how many sessions are within this sample. The downside to this is that it can't be 100% precise and increasing the precision increases the time it takes to generate (for me, it takes several minutes to generate a second-precise image, though this level of precision makes little to no difference to the result).
Here is some code which can produce both a heatmap and a line graph
```
# Configuration options
precisionPerDay = 288
timeTicksPerDay = 24
timeTickRotation = 60
timeTickFontSize = 6
heatmap = True
# Constants
hoursInDay = 24
secondsInHour = 3600
secondsInDay = hoursInDay*secondsInHour
xInterval = secondsInDay/precisionPerDay
timeTickSecondInterval = precisionPerDay/timeTicksPerDay
timeTickHourInterval = hoursInDay/timeTicksPerDay
# Calculating x-axis (time) ticks
xAxis = range(precisionPerDay)
timeTickLabels = []
timeTickLocations = []
for timeTick in range(timeTicksPerDay):
timeTickLocations.append(int(timeTick*timeTickSecondInterval))
hours = timeTick/timeTicksPerDay*hoursInDay
hour = int(hours)
minute = int((hours-hour)*60)
timeTickLabels.append(f"{hour:02d}:{minute:02d}")
# Calculating y-axis (height)
heights = []
for dayX in xAxis:
rangeStart = dayX*xInterval
rangeEnd = rangeStart+xInterval
y = 0
for date,sessions in sessions.items():
for session in sessions:
if session[0] < rangeEnd and session[0]+session[1] > rangeStart:
y += 1
heights.append(y)
# Plotting data
if heatmap:
plt.yticks([])
plt.imshow([heights], aspect="auto")
else:
plt.plot(xAxis,heights)
plt.ylim(ymin=0)
plt.xlim(xmin=0,xmax=len(heights))
plt.xlabel("Time of day")
plt.ylabel("How often I've coded at that time")
plt.xticks(timeTickLocations,timeTickLabels,
fontsize=timeTickFontSize,rotation=timeTickRotation)
plt.show()
```
And here are some sample results
Graph produced by same configuration options shown in above code

Same data but as a line graph with a lower precision (24 per day) and more time ticks (48)

| null | CC BY-SA 4.0 | null | 2022-11-19T00:52:44.153 | 2022-11-19T00:52:44.153 | null | null | 17,168,710 | null |
74,496,782 | 2 | null | 10,990,347 | 0 | null | Drag and drop your table from the left side menu into a worksheet and you will get a list of options. Pick "Insert" and then apply, and then done.
| null | CC BY-SA 4.0 | null | 2022-11-19T00:58:04.210 | 2022-11-19T00:58:04.210 | null | null | 2,888,009 | null |
74,497,152 | 2 | null | 74,491,620 | 1 | null | The arguments to `ax.plot()` should not be the individual points, but the individual dimensions: first a list of all the x-values, then all the y-values, and then all the z-values. You can use the same syntax for `ax.scatter()`.
```
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits import mplot3d
data = {'red': ([0] * 4,
range(4),
[100, 128, 30, 15]),
'blue': ([1] * 4,
range(4),
[100, 45, 13, 6]),
'green': ([2] * 4,
range(4),
[100, 55, 27, 26])}
ax = plt.axes(projection='3d')
for color, points in data.items():
ax.scatter(*points, color=color)
ax.plot(*points, color=color)
plt.show()
```
[](https://i.stack.imgur.com/9RlDq.png)
However, the fact that these lines lie in parallel planes strongly suggests that you don't actually need a 3-dimensional plot. The third dimension is already encoded by the colors, so the 2-dimensional plot loses no information while making it much easier to compare the lines.
```
data = {'red': (range(4),
[100, 128, 30, 15]),
'blue': (range(4),
[100, 45, 13, 6]),
'green': (range(4),
[100, 55, 27, 26])}
ax = plt.axes()
for color, points in data.items():
ax.scatter(*points, color=color)
ax.plot(*points, color=color)
plt.show()
```
[](https://i.stack.imgur.com/uf7vK.png)
| null | CC BY-SA 4.0 | null | 2022-11-19T02:32:13.790 | 2022-11-19T02:53:30.503 | 2022-11-19T02:53:30.503 | 13,014,172 | 13,014,172 | null |
74,497,162 | 2 | null | 74,496,335 | 2 | null | Unextended GLSL for OpenGL does not have the ability to directly use 64-bit integer values. And even [the fairly widely supported ARB extension](http://opengl.gpuinfo.org/listreports.php?extension=GL_ARB_gpu_shader_int64) that allows for the use of 64-bit integers within shaders doesn't actually allow you to use them as vertex shader attributes. That requires [an NVIDIA extension supported only by... NVIDIA](http://opengl.gpuinfo.org/listreports.php?extension=GL_NV_vertex_attrib_integer_64bit).
However, you can send 32-bit integers, and a 64-bit integer is just two 32-bit integers. You can put 64-bit integers into the buffer and pass them as 2 32-bit unsigned integers in your vertex attribute format:
```
glVertexAttribIFormat(0, 2, GL_UNSIGNED_INT, <byte_offset>);
```
Your shader will retrieve them as a `uvec2` input:
```
layout(location = 0) in uvec2 vertexPosition_modelspace;
```
The x component of the vector will have the first 4 bytes and the y component will store the second 4 bytes. But since "first" and "second" are determined by your CPU's endian, you'll need to know whether your CPU is little endian or big endian to be able to use them. Since most desktop GL implementations are paired with little endian CPUs, we'll assume that is the case.
In this case, `vertexPosition_modelspace.x` contains the low 4 bytes of the 64-bit integer, and `vertexPosition_modelspace.y` contains the high 4 bytes.
So your code could be adjusted as follows (with some cleanup):
```
const vec3 BLOCK_SIZE(0.1, 0.1, 0.1);
//Get the three axes all at once.
uvec3 getAxes(in uvec2 p)
{
return uvec3(
(p.y >> 27) & 0xF),
(p.x >> 23) & 0xFF),
(p.y >> 23) & 0xF)
);
}
//Get the indices
uvec2 getIndices(in uvec2 p)
{
return p & 0x807FFFFF; //Performs component-wise bitwise &
}
void main()
{
uvec3 iPos = getAxes(vertexPosition_modelspace);
uvec2 indices = getIndices(vertexPosition_modelspace);
vec3 pos = vec3(
iPos.x + (indices.x * CHUNK_SIZE),
iPos.y,
iPos.z + (indices.x * CHUNK_SIZE) //You used index 3 in your code, so I used .x here, but I think you meant index 4.
);
pos *= BLOCK_SIZE;
...
}
```
| null | CC BY-SA 4.0 | null | 2022-11-19T02:35:08.437 | 2022-11-19T02:35:08.437 | null | null | 734,069 | null |
74,497,332 | 2 | null | 30,800,428 | 0 | null | admin/controller/sale/order.php
find :
```
public function shipping() {
```
and before
```
$data['orders'][] = array(
```
add
```
$total_data = array();
$totals = $this->model_sale_order->getOrderTotals($order_id);
foreach ($totals as $total) {
$total_data[] = array(
'title' => $total['title'],
'text' => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value'])
);
}
```
Then after
```
$data['orders'][] = array(
```
add
```
'total' => $total_data,
```
Next step, open admin/view/template/sale/order_shipping and add
```
{% set last_total = order.total|last %}{{ last_total.text }}
```
| null | CC BY-SA 4.0 | null | 2022-11-19T03:26:26.877 | 2022-11-19T03:26:47.057 | 2022-11-19T03:26:47.057 | 20,544,719 | 20,544,719 | null |
74,497,522 | 2 | null | 74,497,439 | 0 | null | You can do this with search:
```
d/}<Enter>
```
| null | CC BY-SA 4.0 | null | 2022-11-19T04:18:42.613 | 2022-11-19T04:18:42.613 | null | null | 20,297,231 | null |
74,497,570 | 2 | null | 74,497,541 | 2 | null | NextJS now differentiates b/w server components and client components.
All components inside the app directory are React Server Components by default. To use `useRef` you have to mark the component as client side.
On the file where you are using `useRef`, add `'use client'` at the beginning of your code. This will ensure the component can run on client side.
```
'use client';
import { useEffect, useRef } from "react";
..
```
I think where you are using the `useDraw` hook could also need this `use client` declaration.
Reference:
1. https://beta.nextjs.org/docs/rendering/server-and-client-components#client-components
| null | CC BY-SA 4.0 | null | 2022-11-19T04:34:16.257 | 2022-11-19T04:51:53.443 | 2022-11-19T04:51:53.443 | 7,679,903 | 7,679,903 | null |
74,497,615 | 2 | null | 60,441,736 | 0 | null | change input type number to text in "CustomerProductsNew.jsp"
" class="border-0" size="1" readonly>
```
<td width="5%"><input id="randomno" type="number" name="quantity" size="1"></td>
```
above input type is wrong because you trying to store integer in string
" class="border-0" size="1" readonly>
```
<td width="5%"><input id="randomno" type="text" name="quantity" size="1"></td>
```
| null | CC BY-SA 4.0 | null | 2022-11-19T04:45:52.500 | 2022-11-19T04:45:52.500 | null | null | 20,545,078 | null |
74,497,690 | 2 | null | 74,497,672 | 0 | null | That sounds like a 2-step process:
1. Store the value as a number rather than as a string like you now have it.
2. Then use the atomic increment operation to increment it by 5.
| null | CC BY-SA 4.0 | null | 2022-11-19T05:06:37.713 | 2022-11-19T05:06:37.713 | null | null | 209,103 | null |
74,497,766 | 2 | null | 74,497,444 | 1 | null | I think this is a valid bug and I noticed it happens only when you do it instantly.
If you type something and wait for sometime and close the dialog it doesn't happens.
To get around I have used a `setTimeout` so there's a delay while setting the `setOpen` to `false`
```
const handleClose = () => {
setTimeout(() => {
setOpen(false);
}, 0);
};
```
```
<Modal
open={open}
onClose={handleClose}
title="Create a Backup"
description="Creating a backup will take a copy of your server files. This can take a while depending on the size of your server."
>
...
</Modal>
```
| null | CC BY-SA 4.0 | null | 2022-11-19T05:27:29.410 | 2022-11-19T05:27:29.410 | null | null | 7,679,903 | null |
74,497,933 | 2 | null | 74,076,140 | 0 | null | I faced the same problem,and I have solved it.
You need to open Run/Debug Configurations of Pycharm.
Then find Parameters of your py file, Copy and delete the parameters, and then fill in the parameters as they are
| null | CC BY-SA 4.0 | null | 2022-11-19T06:16:20.093 | 2022-11-19T06:16:20.093 | null | null | 20,545,439 | null |
74,498,266 | 2 | null | 74,497,297 | 2 | null | I made an over simplified example, hopefully can help finding a good solution.
This one uses a cross delay approach to make the transition smooth when opening and closing the drawer.
There is a state `open` controls the drawer. On the drawer container:
```
open ? "w-52 delay-0" : "w-12 delay-300"
```
And the inside element uses a reversed delay value, something like:
```
open ? "opacity-100 delay-300" : "opacity-0 delay-0"
```
This way, during both opening and closing transition, parent and child elements will have properly ordered animation.
Live demo is here: [stackblitz](https://stackblitz.com/edit/vitejs-vite-jlnl7x?file=src/App.jsx)
```
import React, { useState } from "react";
import "./App.css";
const list = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"];
const ListItem = ({ open, text, index }) => {
return (
<li className={`bg-teal-100 h-12 flex justify-end`}>
<div
className={`${
open ? "w-24" : "w-12"
} flex justify-center align-center p-3 transition-all duration-300 ease-in-out`}
>
{index + 1}
</div>
<div
className={`${
open ? "opacity-100 delay-300" : "opacity-0 delay-0"
} flex justify-center align-center p-3 flex-1 transition-all duration-300 ease-in-out`}
>
{text}
</div>
</li>
);
};
const SlideDrawer = ({ open }) => {
return (
<div
className={`${
open ? "w-52 delay-0" : "w-12 delay-300"
} absolute left-0 top-0 bottom-0 transition-all duration-300 ease-in-out overflow-hidden flex justify-start bg-pink-200`}
>
<div className={`w-52 flex flex-col justify-start align-end`}>
<div
className={`${
open ? "w-52 p-6 delay-300" : "w-12 p-3 delay-0"
} h-72 flex flex-col justify-start align-center transition-all duration-300 ease-in-out `}
>
<figure
className={`${
open ? "w-40 h-40 delay-300" : "w-6 h-6 delay-0"
} transition-all bg-teal-100 rounded-full duration-300 ease-in-out`}
></figure>
</div>
<ul className="w-full flex flex-col list-none">
{list.map((item, index) => (
<ListItem key={item} open={open} index={index} text={item} />
))}
</ul>
</div>
</div>
);
};
function App() {
const [drawerOpen, setDrawerOpen] = useState(false);
return (
<>
<div className="w-full flex justify-end">
<button
className="m-6 p-3 rounded-lg bg-slate-300"
onClick={() => setDrawerOpen((prev) => !prev)}
>
Open drawer
</button>
</div>
<SlideDrawer open={drawerOpen} />
</>
);
}
export default App;
```
| null | CC BY-SA 4.0 | null | 2022-11-19T07:30:35.683 | 2022-11-19T07:41:33.200 | 2022-11-19T07:41:33.200 | 20,436,957 | 20,436,957 | null |
74,498,312 | 2 | null | 74,498,254 | 0 | null | You need to do some manipulation to generate `count` that is in your chart. Is it from 'EDUCATION-NUM'?
Once generated:
`x = 'Education level'`
`y = 'count'`
to segment, you use `hue = 'SALARY'`
documentation is here: [https://seaborn.pydata.org/generated/seaborn.barplot.html](https://seaborn.pydata.org/generated/seaborn.barplot.html)
| null | CC BY-SA 4.0 | null | 2022-11-19T07:43:34.153 | 2022-11-19T07:48:58.027 | 2022-11-19T07:48:58.027 | 9,650,095 | 9,650,095 | null |
74,498,422 | 2 | null | 62,606,907 | 2 | null | I came with a bit different approach that works fine on macOS. Instead of using `.onDrag` and `.onDrop` Im using `.gesture(DragGesture)` with a helper class and modifiers.
[](https://i.stack.imgur.com/5N2D3.gif)
Here are helper objects (just copy this to the new file):
```
// Helper class for dragging objects inside LazyVGrid.
// Grid items must be of the same size
final class DraggingManager<Entry: Identifiable>: ObservableObject {
let coordinateSpaceID = UUID()
private var gridDimensions: CGRect = .zero
private var numberOfColumns = 0
private var numberOfRows = 0
private var framesOfEntries = [Int: CGRect]() // Positions of entries views in coordinate space
func setFrameOfEntry(at entryIndex: Int, frame: CGRect) {
guard draggedEntry == nil else { return }
framesOfEntries[entryIndex] = frame
}
var initialEntries: [Entry] = [] {
didSet {
entries = initialEntries
calculateGridDimensions()
}
}
@Published // Currently displayed (while dragging)
var entries: [Entry]?
var draggedEntry: Entry? { // Detected when dragging starts
didSet { draggedEntryInitialIndex = initialEntries.firstIndex(where: { $0.id == draggedEntry?.id }) }
}
var draggedEntryInitialIndex: Int?
var draggedToIndex: Int? { // Last index where device was dragged to
didSet {
guard let draggedToIndex, let draggedEntryInitialIndex, let draggedEntry else { return }
var newArray = initialEntries
newArray.remove(at: draggedEntryInitialIndex)
newArray.insert(draggedEntry, at: draggedToIndex)
withAnimation {
entries = newArray
}
}
}
func indexForPoint(_ point: CGPoint) -> Int {
let x = max(0, min(Int((point.x - gridDimensions.origin.x) / gridDimensions.size.width), numberOfColumns - 1))
let y = max(0, min(Int((point.y - gridDimensions.origin.y) / gridDimensions.size.height), numberOfRows - 1))
return max(0, min(y * numberOfColumns + x, initialEntries.count - 1))
}
private func calculateGridDimensions() {
let allFrames = framesOfEntries.values
let rows = Dictionary(grouping: allFrames) { frame in
frame.origin.y
}
numberOfRows = rows.count
numberOfColumns = rows.values.map(\.count).max() ?? 0
let minX = allFrames.map(\.minX).min() ?? 0
let maxX = allFrames.map(\.maxX).max() ?? 0
let minY = allFrames.map(\.minY).min() ?? 0
let maxY = allFrames.map(\.maxY).max() ?? 0
let width = (maxX - minX) / CGFloat(numberOfColumns)
let height = (maxY - minY) / CGFloat(numberOfRows)
let origin = CGPoint(x: minX, y: minY)
let size = CGSize(width: width, height: height)
gridDimensions = CGRect(origin: origin, size: size)
}
}
struct Draggable<Entry: Identifiable>: ViewModifier {
@Binding
var originalEntries: [Entry]
let draggingManager: DraggingManager<Entry>
let entry: Entry
@ViewBuilder
func body(content: Content) -> some View {
if let entryIndex = originalEntries.firstIndex(where: { $0.id == entry.id }) {
let isBeingDragged = entryIndex == draggingManager.draggedEntryInitialIndex
let scale: CGFloat = isBeingDragged ? 1.1 : 1.0
content.background(
GeometryReader { geometry -> Color in
draggingManager.setFrameOfEntry(at: entryIndex, frame: geometry.frame(in: .named(draggingManager.coordinateSpaceID)))
return .clear
}
)
.scaleEffect(x: scale, y: scale)
.gesture(
dragGesture(
draggingManager: draggingManager,
entry: entry,
originalEntries: $originalEntries
)
)
}
else {
content
}
}
func dragGesture<Entry: Identifiable>(draggingManager: DraggingManager<Entry>, entry: Entry, originalEntries: Binding<[Entry]>) -> some Gesture {
DragGesture(coordinateSpace: .named(draggingManager.coordinateSpaceID))
.onChanged { value in
// Detect start of dragging
if draggingManager.draggedEntry?.id != entry.id {
withAnimation {
draggingManager.initialEntries = originalEntries.wrappedValue
draggingManager.draggedEntry = entry
}
}
let point = draggingManager.indexForPoint(value.location)
if point != draggingManager.draggedToIndex {
draggingManager.draggedToIndex = point
}
}
.onEnded { value in
withAnimation {
originalEntries.wrappedValue = draggingManager.entries!
draggingManager.entries = nil
draggingManager.draggedEntry = nil
draggingManager.draggedToIndex = nil
}
}
}
}
extension View {
// Allows item in LazyVGrid to be dragged between other items.
func draggable<Entry: Identifiable>(draggingManager: DraggingManager<Entry>, entry: Entry, originalEntries: Binding<[Entry]>) -> some View {
self.modifier(Draggable(originalEntries: originalEntries, draggingManager: draggingManager, entry: entry))
}
}
```
Now to use it in view you have to do few things:
- Create a draggingManager that is a `StateObject`- Create a var that exposes either real array you are using or temporary array used by draggingManager during dragging.- Apply `coordinateSpace` from draggingManager to the container (LazyVGrid)
That way draggingManager only modifies its copy of the array during the process, and you can update the original after dragging is done.struct VirtualMachineSettingsDevicesView: View {```
@ObservedObject
var vmEntity: VMEntity
@StateObject
private var devicesDraggingManager = DraggingManager<VMDeviceInfo>()
// Currently displaying devices - different during dragging.
private var displayedDevices: [VMDeviceInfo] { devicesDraggingManager.entries ?? vmEntity.config.devices }
var body: some View {
Section("Devices") {
LazyVGrid(columns: [.init(.adaptive(minimum: 64, maximum: 64))], alignment: .leading, spacing: 20) {
Group {
ForEach(displayedDevices) { device in
Button(action: { configureDevice = device }) {
device.label
.draggable(
draggingManager: devicesDraggingManager,
entry: device,
originalEntries: $vmEntity.config.devices
)
}
}
Button(action: { configureNewDevice = true }, label: { Label("Add device", systemImage: "plus") })
}
.labelStyle(IconLabelStyle())
}
.coordinateSpace(name: devicesDraggingManager.coordinateSpaceID)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.buttonStyle(.plain)
}
```
}
| null | CC BY-SA 4.0 | null | 2022-11-19T08:08:16.167 | 2022-11-24T06:38:37.443 | 2022-11-24T06:38:37.443 | 4,528,716 | 4,528,716 | null |
74,498,522 | 2 | null | 74,498,354 | 0 | null | Adding h2 fixed the problem
```
.elementor-element-4756de9 h2:after {
visibility:visible;
position: absolute;
top: 0;
left: 0;
content: "We are closed for the season";
}
```
| null | CC BY-SA 4.0 | null | 2022-11-19T08:23:40.483 | 2022-11-21T02:22:42.623 | 2022-11-21T02:22:42.623 | 19,439,458 | 19,439,458 | null |
74,498,538 | 2 | null | 74,498,354 | 1 | null | ```
.elementor-element-4756de9 {
visibility: hidden;
position: relative;
}
.elementor-element-4756de9 :after {
visibility: visible;
position: absolute;
top: 0;
left: 0;
content: "We are closed for the season";
}
.elementor-element-4756de9 .elementor-heading-title {
display: none;
}
```
```
<div class="elementor-element elementor-element-4756de9 elementor-widget elementor-widget-heading" data-id="4756de9" data-element_type="widget" data-widget_type="heading.default">
<div class="elementor-widget-container">
<h2 class="elementor-heading-title elementor-size-default">We are now open for the 2022 Season</h2>
</div>
</div>
```
| null | CC BY-SA 4.0 | null | 2022-11-19T08:26:24.313 | 2022-11-19T08:26:24.313 | null | null | 5,385,381 | null |
74,498,869 | 2 | null | 10,349,206 | 1 | null | Another option using `scale_color_identity`. The key is to specify the color name in each `aes` of each `geom_line`. In the `scale_color_identity` you can mention each color as `breaks` and add the `labels` you want. Here is a reproducible example:
```
library(ggplot2)
temp = ggplot(data = datos, aes(x = fecha)) +
geom_line(aes(y = TempMax, colour = "red")) +
geom_line(aes(y = TempMedia, colour = "green")) +
geom_line(aes(y = TempMin, colour = "blue")) +
labs(title="TITULO") +
ylab("Temperatura (C)") +
xlab(" ") +
scale_y_continuous(limits = c(-10,40)) +
scale_color_identity(name = '',
breaks = c('red', 'green', 'blue'),
labels = c("TempMax", "TempMedia", "TempMin"),
guide = 'legend')
temp
```

[reprex v2.0.2](https://reprex.tidyverse.org)
| null | CC BY-SA 4.0 | null | 2022-11-19T09:28:30.293 | 2022-11-19T09:28:30.293 | null | null | 14,282,714 | null |
74,498,880 | 2 | null | 70,631,204 | 0 | null | Had the same in Visual studio code. Removed Pylance extention and got it back.
| null | CC BY-SA 4.0 | null | 2022-11-19T09:29:59.657 | 2022-11-19T09:29:59.657 | null | null | 18,579,094 | null |
74,499,025 | 2 | null | 74,498,955 | 2 | null | The relationship between `Student` and `Course` has to be modeled somehow. One possibility is to give each `Student` a field `Collection<Course> courses` (and expose it through a getter). Traversing this relationship means to get this field, by e.g. calling the getter.
| null | CC BY-SA 4.0 | null | 2022-11-19T09:58:09.427 | 2022-11-19T23:35:09.230 | 2022-11-19T23:35:09.230 | 4,216,641 | 4,216,641 | null |
74,499,038 | 2 | null | 74,497,439 | 1 | null | The notion of "motion" comes from vi but the notion of "text object" came later and, while text objects are for all intent and purpose a special kind of motions, there is no 1-1 relationship to expect between regular, motions and special text objects. So yes, there is a two-way "inner braces" text object but there is no built-in one-way counterpart.
The classic approach is to:
1. visually select the text object ("scope" is not a Vim concept),
2. go back to normal mode, which leaves the cursor at the end of the desired text object,
3. use the desired operator from the cursor to the last position.
In concrete terms:
```
viB<C-c>d''
```
That is basically the best we have if we constrain ourselves to the built-ins. I think it is fine and gets the job done but you might find it too verbose. If that's the case, one approach would be to make a dedicated pair of visual mode and operator-pending mode mappings:
```
xnoremap EB iB<C-c>v''
onoremap EB <Cmd>normal vEB<CR>
```
which would allow you to do `dEB` to cut the text from the cursor to the end of the "inner braces text" object.
Notes:
- - -
See the sadly under-developed `:help omap-info`, and [this great article](https://vimways.org/2018/transactions-pending/).
| null | CC BY-SA 4.0 | null | 2022-11-19T10:00:41.447 | 2022-11-19T10:00:41.447 | null | null | 546,861 | null |
74,499,176 | 2 | null | 74,497,390 | 0 | null | Add to each div -> `class="carousel-item"` and main div `class="carousel slide" data-bs-ride="carousel"` . Before asking check docs. [https://getbootstrap.com/docs/5.2/components/carousel/#how-it-works](https://getbootstrap.com/docs/5.2/components/carousel/#how-it-works)
| null | CC BY-SA 4.0 | null | 2022-11-19T10:21:04.577 | 2022-11-19T10:21:04.577 | null | null | 15,005,332 | null |
74,499,283 | 2 | null | 64,063,986 | 0 | null |
##### On the UI (User Interface) of Jupyter Lab you see
```
Build failed with 524, please run 'jupyter lab build' on the server for full output
```
##### You open a console and run
```
jupyter lab build
```
##### Which ends with
```
An error occurred.
RuntimeError: JupyterLab failed to build
See the log file for details: /tmp/jupyterlab-debug-2znox977.log
```
##### Inside the log you see
```
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
```
##### Run again
```
jupyter lab build --minimize=False
```
This completes successfully.
> Explanation:- `dev-build`: This option controls whether a `dev` or a more streamlined `production` build is used. This option will default to
`False` (i.e., the `production` build) for most users. However, if you
have any labextensions installed from local files, this option will
instead default to `True`. Explicitly setting `dev-build` to `False`
will ensure that the `production` build is used in all circumstances.- `minimize`: This option controls whether your JS bundle is minified during the Webpack build, which helps to improve JupyterLab's overall
performance. However, the minifier plugin used by Webpack is very
memory intensive, so turning it off may help the build finish
successfully in low-memory environments.
In my case, the VM (Virtual Machine) had 3.75GB RAM and before crashing it was using ~3GB (you can see with `htop` in another console/terminal [image below]).
[](https://i.stack.imgur.com/4HQfu.png)
| null | CC BY-SA 4.0 | null | 2022-11-19T10:36:04.930 | 2022-11-19T10:36:04.930 | null | null | 4,752,223 | null |
74,499,903 | 2 | null | 74,465,073 | 0 | null | As this question has generated a lot of "Chatter" amongst some of the main Blazor category answering group, this sets out a heavily refactored version of the original code in a "Minimal Reproducable Example" format. If it's wide of the mark, I'll update it.
First some liberties I've taken in the revised code:
1. category.Id suggests an Id type field and therefore an int, long or a Guid. Not normally a string, so I've coded it as a int. Wrong conclusion?
2. I've dropped the interfaces. You should use interfaces, but they complicate the example code.
3. Nullable is enabled. Rather important in the light of various commentaries.
4. I've made a stab at the data classes, and the functionality in ProductService.
5. I've used the Continent/Country context as your Categories/Products.
6. I've replaced lists with IEnumerable in properties.
7. I've replaced API calls with generic methods that emulate getting data asynchronously using Task.Delay.
First the data classes and services. I believe in immutablility, hense the records - exactly how you handle `ctor` depends on what version of C# you are using - see the `Required` keyword.
#### Categories
```
public record Category
{
public int Id { get; init; }
public string Name { get; init; } = "No Category Set";
}
public class CategoryService
{
public IEnumerable<Category> Categories { get; set; } = Enumerable.Empty<Category>();
public async Task GetAllCategories()
{
// emulate an async call into the API
await Task.Delay(100);
this.LoadCategories();
}
private void LoadCategories()
{
this.Categories = new List<Category>() {
new Category { Id=1, Name="Oceania" },
new Category { Id=2, Name="Europe" },
};
}
}
```
#### Products
```
public record Product
{
public int Id { get; init; }
public int CategoryId { get; init; }
public string Name { get; init; } = "No Category Set";
}
public class ProductService
{
public IEnumerable<Product> Products { get; set; } = Enumerable.Empty<Product>();
public async Task<IEnumerable<string>> GetProductSearchSugestions(string search, int categoryId)
{
await Task.Delay(100);
return categoryId == 0
? Products.Where(item => item.Name.ToLower().Contains(search.ToLower())).Select(item => item.Name).AsEnumerable()
: Products.Where(item => item.Name.ToLower().Contains(search.ToLower()) && item.CategoryId == categoryId).Select(item => item.Name).AsEnumerable();
}
public ProductService()
=> this.Load();
private void Load()
{
this.Products = new List<Product>() {
new Product { Id=1, CategoryId = 1, Name="New Zealand" },
new Product { Id=2, CategoryId = 1, Name="Australia" },
new Product { Id=3, CategoryId = 1, Name="Cook Islands" },
new Product { Id=4, CategoryId = 2, Name="UK" },
new Product { Id=5, CategoryId = 2, Name="France" },
new Product { Id=6, CategoryId = 2, Name="Spain" },
new Product { Id=6, CategoryId = 2, Name="Andorra" },
new Product { Id=6, CategoryId = 2, Name="Austria" },
};
}
}
```
#### Registered Services
```
builder.Services.AddScoped<CategoryService>();
builder.Services.AddScoped<ProductService>();
```
#### Demo Page (Test.razor)
And the page. I've refactored the code and removed stuff that isn't directly related to answering the question.
1. The page gets the Category list in OnInitializedAsync.
2. categoryId is a classic old style property and includes calling an event when it changes. We need this to update the datalist if it currently contains values.
3. I've separated out the actual value from SearchText (updated by OnChange in the bind) from the value used to filter the datalist driven by an event handler on @ininput.
4. The logic on the data list filter ignores case and uses contains.
5. I've included a debounce throttler which throttles the type ahead speed to what the backend can keep up with plus a backoff period. The code is at the bottom of this answer. This is initialised in the page ctor.
```
@page "/"
@inject NavigationManager _navmenager;
@inject ProductService _ProductService;
@inject CategoryService _CategoryService;
<div class="input-group">
<input @bind-value="this.searchText"
type="search"
list="products"
@oninput="HandleSearchAsync"
class="form-control"
placeholder="Search..."
@ref="this.searchInput" />
<datalist id="products">
@foreach (var item in this.suggestions)
{
<option>@item</option>
}
</datalist>
<select @bind=this.categoryId class="form-select">
<option value="0">All</option>
@foreach (var category in _CategoryService.Categories)
{
<option value="@category.Id">@category.Name</option>
}
</select>
<div class="input-group-append">
<button class="btn btn-primary" @onclick="SearchProducts">
<span class="oi oi-magnifying-glass"></span>
</button>
</div>
</div>
@code
{
private InputThrottler<string> inputTextThrottler;
private string searchText = string.Empty;
private int _categoryId = 0;
private int categoryId
{
get => _categoryId;
set
{
_categoryId = value;
InvokeAsync(async () => await this.CategoryChangedAsync());
}
}
private IEnumerable<string> suggestions = Enumerable.Empty<string>();
private ElementReference searchInput;
public Test()
=> inputTextThrottler = InputThrottler<string>.Create(this.GetProducts, 100);
// this loads the service
protected override async Task OnInitializedAsync()
=> await _CategoryService.GetAllCategories();
protected override async void OnAfterRender(bool firstRender)
{
if (firstRender)
await this.searchInput.FocusAsync();
}
private void SearchProducts()
{
// what you want to do
}
public async Task HandleSearchAsync(ChangeEventArgs e)
=> await inputTextThrottler.QueueRequestAsync(e.Value?.ToString() ?? string.Empty);
public async Task CategoryChangedAsync()
=> await inputTextThrottler.QueueRequestAsync(searchText);
private async Task GetProducts(string search)
{
this.suggestions = await _ProductService.GetProductSearchSugestions(search, this.categoryId);
await this.InvokeAsync(StateHasChanged);
}
}
```
#### The debounce class:
```
public class InputThrottler<T>
{
// Debounce task and private properties
private bool _queued = false;
private int _backOff = 0;
private Func<T, Task> _taskToRun;
private InputThrottler(Func<T, Task> toRun, int backOff)
{
_backOff = backOff;
_taskToRun = toRun;
}
public static InputThrottler<T> Create(Func<T, Task> toRun, int backOff)
=> new InputThrottler<T>(toRun, backOff);
// This method only runs _taskToRun when it isn't already running, plus the backoff
// If you need to update the UI call StateHasChanged at the end of _taskToRun
public async Task<bool> QueueRequestAsync(T value)
{
// If we're currently running the async task then exit
if (_queued)
return false;
_queued = true;
// run the task
await _taskToRun.Invoke(value);
// apply our backoff period
await Task.Delay(_backOff);
_queued = false;
return true;
}
}
```
#### Select and Integers
Note that the `select` is mapped directly to the `int`. No need to switch to a `string`. The Razor compiler handles this for you with it's `BindConverter`. Here's the source code the compiler generates:
```
__builder.AddAttribute(19, "value", global::Microsoft.AspNetCore.Components.BindConverter.FormatValue(this.categoryId));
__builder.AddAttribute(20, "onchange", global::Microsoft.AspNetCore.Components.EventCallback.Factory.CreateBinder(this, __value => this.categoryId = __value, this.categoryId));
```
[](https://i.stack.imgur.com/43Xc2.png)
| null | CC BY-SA 4.0 | null | 2022-11-19T12:16:05.717 | 2022-11-19T12:16:05.717 | null | null | 13,065,781 | null |
74,500,093 | 2 | null | 49,634,751 | 1 | null | I'm a bit late to the party, but I just ran into the same problem. In my case, I needed to generate a tree structure for presentation purposes from a set of columns in a database. Since the columns used for this needed to be selectable at run-time, any sort of fixed table structure was out of the question.
I came up with the following algorithm (C# 10) to create the tree structure.
It's not as efficient as it could be; it's kind of a brute-force approach and there's room for improvement. I assumed that all the fields in the table are strings and that the table might be jagged, that is the right-most values in each row may be `null` values.
To Use it you create a `CollectionTreeBuilder` object and then repeatedly call the `AddRecord` member with each record in your table. Once that's done the `Root` property will contain the corresponding tree structure.
Going from a tree to a table representation is pretty simple. You traverse the tree recursively and output a row at each leaf node. The `CollectionNode.ToString` method is a good example of this. It generates an S-Expression style string (great for unit testing) but could be modified to generate some other format.
```
public class CollectionNode {
public string Value { get; set; } = string.Empty;
public List<string> Key { get; set; } = new List<string>();
public List<CollectionNode>? Children { get; set; } = null;
public override string ToString() =>
Children == null
? $"({Value})"
: $"({Value} {Children.Aggregate("", (a, b) => a.ToString() + b.ToString())})";
}
public class CollectionTreeBuilder {
public void AddRecord(IEnumerable<string?> record) {
var current = Root;
var key = new List<String> { };
foreach (var value in record.TakeWhile(v => v != null)) {
if (current.Children == null)
current.Children = new List<CollectionNode> { };
var child = current.Children.FirstOrDefault(c => c.Value == value);
if (child == null) {
current.Children.Add(new CollectionNode { Value = value! });
current = current.Children.Last();
} else {
current = child;
}
key.Add(value!);
}
current.Key = key;
}
public override string ToString() => Root.ToString();
public CollectionNode Root { get; private set; } = new CollectionNode { Value = "root" };
}
```
| null | CC BY-SA 4.0 | null | 2022-11-19T12:42:36.193 | 2022-11-19T12:42:36.193 | null | null | 4,086 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.