instruction stringlengths 0 30k ⌀ |
|---|
My task is to create a tool that, based on (specific) input data, will generate a 'grid' of employees' working hours and spit out specific shifts 6-14; 7-15; 10-20 etc etc.
The general operation of such a macro, let's say I have one, the problem begins when the macro must have a requirement that in a given row (the row is one employee) the sum cannot be greater than 10.
Below I paste the code I managed to create, which fills in the values accordingly based on the input data, but without this requirement (row sum not greater than 10).
```
Sub AutoFill()
Dim ws As Worksheet
Dim col As Integer
Dim row As Integer
Dim suma As Integer
Dim liczba_osob As Integer
' Ustaw arkusz, na którym chcesz działać
Set ws = ThisWorkbook.Sheets("01")
' Wyczyść zakres G5:AD36
ws.Range("G5:AD36").ClearContents
' Iteruj przez kolumny od G do Y
For col = 7 To 30
' Pobierz liczbę osób w pracy w danej godzinie
liczba_osob = ws.Cells(2, col).Value
' Ustaw sumę kolumny na 0
suma = 0
' Uzupełnij komórki wartością 1 do momentu, gdy suma wiersza będzie równa liczbie osób w pracy
For row = 5 To 36
' Sprawdź, czy suma nie przekracza liczby osób w pracy
If suma < liczba_osob Then
ws.Cells(row, col).Value = 1
suma = suma + 1
Else
' Jeśli suma przekroczyła liczbę osób w pracy, zostaw komórkę pustą
If Not IsEmpty(ws.Cells(row, col)) Then
ws.Cells(row, col).ClearContents
End If
End If
Next row
Next col
End Sub
```
There are also screenshots below in the attachments - in one there is the addition of "1" by the macro, in the other the addition of "1" by me in the way the macro should be supplemented.
Yes, as part of the implementation, the number of employees in each hour is given in the G2:AD2 range, and the hours are listed in G1:AD1.
Can anyone help me or guide me somehow to make it work?
Unless it is possible to completely omit all these "1"s and directly generate individual changes 6-14, 7-15, etc. based on the demand given in G2:AD2...
[![1]][1]
[1]:https://i.stack.imgur.com/5SoVk.jpg
[![2]][2]
[2]:https://i.stack.imgur.com/7hKUC.jpg
I need solution for filling like in screenshot. |
I'm building my first React-Native app that I would like to monetize.
The app will expect users' input. This input will be used as a parameter for API calls to ChatGPT.
Short app configuration description:
- make API calls to ChatGPT and store the response (in DB)
- Display stored data
- Sign in/Sign Up
I come from the web-development world so I'm not familiar with the best practices in mobile app development. My goal is to roll out something simple with minimum costs but still usable in the first stage. So I need to find a balance. I expect about 50-100 users per day in the beginning, having maybe not more than 300 API calls to ChatGPT.
In my ideal world, I would use the following architecture:
- React Native
- FastApi for backend
- DynamoDb for storing data (or something similar)
- AWS for running the backend
Questions:
- Is it mandatory to have a backend for such kind of app or everything can be handled from the front end part?
- Will it be fast enough and operational?
- What would you recommend? |
Add this to your container in `docker-compose.yml`.
```
extra_hosts:
- "host.docker.internal:host-gateway"
```
If you keep getting errors, change listen_addresses in `postgresql.conf`
```
listen_addresses = '*'
```
And add these lines to your `pg_hba.conf`
```
host all all 0.0.0.0/0 scram-sha-256
host all all ::/0 scram-sha-256
```
After this, restart the postgresql service.
```
sudo systemctl restart postgresql
```
|
I had a try with *Google Sheets* and used "*search and replace*" with
`^(.{2,})\1(.*)$` and it worked.
I tested `(.*)\1` and also `(.*?)\1` as you mentioned, and effectively
it doesn't work.
It should also work with `^(.+?)\1`. So the problem was just that
`*` would match zero times and `+` would force at least to match one
char.
So up to you to decide, but I think that a first name should be
probably more than 2 characters, so this is why I would prefer using
`.{2,}` or even `\S{2,}` to be sure to match non-spaces.
**Search**: `^(\S{2,})\1(.*)$`
**Replace**: `$1` |
4 years later and this issue arises for a different reason. Leaving this answer here to help others.
If you encounter "Bad File Descriptor" when using Python, Pip or Poetry on Windows:
It is possible that Windows Security is blocking access to your files. It may do this as part of Controlled Folder Access, as part of Virus & Threat Protection. If this is the cause of the problem, the solution is to allow Python to access your documents. (The solution is _not_ to turn off virus and threat protection. You can solve this without having to give up on anti-virus.)
Steps:
1. Open Windows Security
2. Go to Virus & Threat Protection
3. Go to Virus & Threat Protection Settings (by clicking Manage Settings)
4. Scroll down to find Controlled Folder Access
5. Click Manage Controlled folder access
6. Is is turned on? If no, stop here as this can't be the cause of the issue. If yes, proceed.
7. Open the Block History
8. Inspect the list of blocked folder accesses. Do you see a recent entry for `python.exe` trying to access the folder you were working in? If no, stop here as controlled folder access is not the cause of the issue. If yes, proceed.
9. Go back to Manage Controlled folder access
10. Click "Allow an app through Controlled folder access"
11. Click "Add an allowed app"
12. Click "Recently blocked apps"
13. You should see Python in the list. Click on it and allow it through. (If not, click "Add an allowed app" then use "Browse all apps" to manually find python.exe -- from a command prompt (not powershell), use `where python.exe` to discover Python's location.)
14. You're done. Retry using python/pip/poetry.
Good luck!
---
Footnote:
This is not the only possible cause of Bad File Descriptor. The above steps tell you to stop if you don't find the logs which tell you if Controlled Folder Access is the cause of your problem. Please don't add Python to your exclusion list if it's not the cause of your problem as that just risks opening you up to viruses in the future. |
I wait until the page is loaded and use the "DOMContentLoaded" method to add eventhandlers on some p tags. This works until I open and close the modal, then the page/js freezes. Why does it freeze?
```
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="div_1">
<p>One</p>
<p>Two</p>
<p>Three</p>
</div>
<p id="open_modal">open the modal</p>
<script>
document.addEventListener("DOMContentLoaded", () => {
let test = document.querySelector("#div_1")
for (let i = 0; i < test.children.length; i++) {
test.children[i].addEventListener("click", () => {
console.log(test.children[i].innerHTML)
});
};
});
document.querySelector("#open_modal").addEventListener("click", () => {
if (!document.querySelector("#modal")) {
document.body.innerHTML += `
<div id="modal" style="display: block; position: fixed; padding-top: 200px; left: 0; top: 0; width: 100%; height: 100%;
background-color: rgba(0,0,0,0.4)">
<div id="modal_content">
<span id="modal_close">×</span>
<p style="color: green;">Some text in the Modal..</p>
</div>
</div>
`;
document.querySelector("#modal_close").addEventListener("click", () => {
document.querySelector("#modal").style.display = "none";
});
} else {
document.querySelector("#modal").style.display = "block";
};
});
</script>
</body>
</html>
``` |
function insertDash(str)
str = string.gsub(str, "(%d)(%a)", "%1-%2") -- digit-letter
str = string.gsub(str, "(%a)(%d)", "%1-%2") -- letter-digit
str = string.gsub(str, "(%a)(%a)(%a)(%a)", "%1%2-%3%4") -- 4 letters to 2 letters and 2 letters
return str
end
Examples:
print(insertDash("aa11")) -- aa-11
print(insertDash("11aa")) -- 11-aa
print(insertDash("123abc")) -- 123-abc
print(insertDash("abc123")) -- abc-123
print(insertDash("abcd123")) -- ab-cd-123
print(insertDash("abcd1234")) -- ab-cd-1234 |
My drawables are on the folder drawable-xxhdpi and the background size is 1080 x 1920.
For the screens with this resolution, all is OK.
But when I test on a samsung A34 for example with the resolution 1080 X 2340, I have a black strip under my screen game and I don't know how to scale my background and the position of the other graphics elements to this specfic screen.
Thank you
Gigi
```
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
// Affichage du background
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.backgame), 0, 0, paint);
```
[enter image description here][1]
[1]: https://i.stack.imgur.com/rWpbM.png |
There are quite interesting and accurate answers. Using switch seems to be the most beautiful approach as long as it uses the new java 14+ syntax.
One recommendation with that one is to keep switches small. There's no any rule of thumb to say it should only have 3 or 5 cases, but keep them small enough for you and your team understand them, as well as to follow domain/business logic.
This is a good article to read https://www.baeldung.com/java-switch#switch-expressions
One important thing is, as I mentioned before, having in mind Domain/Business Logic.
If you see switch is growing and is getting larger, one question could be if that could be split into different switch statements, creating different helper methods or creating abstraction. Whatever fits better. There are different refactoring techniques as stated here
- https://refactoring.guru/replace-conditional-with-polymorphism
- https://refactoring.guru/extract-method
After all this, if you are still not sure about which approach to follow, there's another option, that may increase the space complexity (memory usage) but will look quite nice to me. See below pseudocode example:
var map = {
"obj1": function() { new Obj1() },
"obj2": function() { new Obj2() },
"obj3": function() { new Obj3() }
}
/* For you to create the object you only need to pass the id to the map.
That will get you the function that belongs that id and you just need
to execute it. That's why you need the last two parenthesis */
map.get("obj1")()
With this approach you can also make the values of your map, rather than a function the Object itself using an abstraction as return type.
|
I've changed `thymeleaf-spring5:3.1.2.RELEASE` to `thymeleaf:3.1.2.RELEASE` library because I hadn't found any solution for that problem. And it now works as expected. |
I have code which executes a large number of summarise and it takes ages to run.
eg:
library(dplyr)
df <- data.frame(Letter = letters, Num = c(1 : (26*10) ))
for (x in 1:10000){
df_sum_Tot = summarise(df, Sum_Num = sum(Num) )
df_sum_Letter = summarise(df, Sum_Num = sum(Num) , .by = Letter )
}
Is there a more efficient alternative to summarise I could use to speed it up? |
Should I set Back-End for my React Native application? |
|react-native|mobile-application| |
You can remove by using the following command and try!
pnpm remove @types/mime |
|spring-boot|spring-cloud|spring-cloud-kubernetes| |
I have a list of dfs:
my_list <- list(structure(list(col1 = c("v1", "v2", "v3", "V2", "V1"), col2 = c("wood", NA, "water", NA, "water"), col3 = c("cup", NA, "fork", NA, NA), col4 = c(NA, "pear", "banana", NA, "apple")), class = "data.frame", row.names = c(NA, -5L)), structure(list(col1 = c("v1", "v2"), col2 = c("wood", NA), col4 = c(NA, "pear")), class = "data.frame", row.names = c(NA, -2L)), structure(list(col1 = c("v1", "v2", "v3", "V3"), col3 = c("cup", NA, NA, NA), col4 = c(NA, "pear", "banana", NA)), class = "data.frame", row.names = c(NA, -4L)))
my_list
[[1]]
col1 col2 col3 col4
1 v1 wood cup <NA>
2 v2 <NA> <NA> pear
3 v3 water fork banana
4 v2 <NA> <NA> <NA>
5 v1 water <NA> apple
[[2]]
col1 col2 col4
1 v1 wood <NA>
2 v2 <NA> pear
[[3]]
col1 col3 col4
1 v1 cup <NA>
2 v2 <NA> pear
3 v3 <NA> banana
4 v3 <NA> <NA>
I want to replace NA with "VAL" in col3 only, **and** only if col1 is v2 **or** v3.
I found solutions to replace NA in certain columns, but not in certain columns and other conditions (or only for a single df, not for a list of dfs.)
Note that col2 or col3 do not necessarily exist in all dfs.
I need a solution with `lapply(list, function)`, ideally.
Desired output:
[[1]]
col1 col2 col3 col4
1 v1 wood cup <NA>
2 v2 <NA> VAL pear
3 v3 water fork banana
4 v2 <NA> VAL <NA>
5 v1 water <NA> apple
[[2]]
col1 col2 col4
1 v1 wood <NA>
2 v2 <NA> pear
[[3]]
col1 col3 col4
1 v1 cup <NA>
2 v2 VAL pear
3 v3 VAL banana
4 v3 VAL <NA>
|
I came up with a query myself. Not sure if a simpler solution exists.
```
SELECT DISTINCT *
FROM (
SELECT group_concat(v2_id ORDER BY v2_sort_me ASC)
FROM (
SELECT v1.id AS v1_id, v2.id AS v2_id, v1.sort_me AS v1_sort_me, v2.sort_me AS v2_sort_me
FROM t v1
JOIN t v2
ON abs(v1.value - v2.value) < 20
)
GROUP BY v1_id HAVING COUNT(*) > 1
ORDER BY v1_sort_me ASC
)
```
Note: The `ORDER BY` clause inside `group_concat()` is only supported since SQLite [3.44.0](https://www.sqlite.org/changes.html#version_3_44_0). |
You need to center your [`rolling`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html) windows with `center=True`:
```
window = 12
hourly = df.resample(rule="h").median()
hourly["ma"] = hourly["TEC"].rolling(window=window, center=True).mean()
hourly["hour"] = hourly.index.hour
hourly["std_err"] = hourly["TEC"].rolling(window=window, center=True).std()
hourly["ub"] = hourly["ma"] + (1.67* hourly["std_err"])
hourly["lb"] = hourly["ma"] - (1.67* hourly["std_err"])
hourly["sig2"] = hourly["TEC"].rolling(window=window, center=True).var()
hourly["kur"] = hourly["TEC"].rolling(window=window, center=True).kurt()
hourly["pctChange"] = hourly.TEC.pct_change(12, fill_method="bfill")
hourly = hourly.dropna()
dTEC = hourly[(hourly["TEC"] > hourly["ub"])]
```
Alternatively, what you tried to do should have been done with [`shift`](https://pandas.pydata.org/docs/reference/api/pandas.Series.shift.html):
```
# your original code
# ...
# then shift
ax.fill_between(x=hourly.index, y1=hourly["ub"].shift(-window//2),
y2=hourly["lb"].shift(-window//2),
color="red", label="Conf Interval", alpha=.4)
```
Output:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/aYJm3.png |
{"OriginalQuestionIds":[13704315],"Voters":[{"Id":205233,"DisplayName":"Filburt"},{"Id":20643658,"DisplayName":"Black cat"},{"Id":4961700,"DisplayName":"Solar Mike"}]} |
This XPath expression will return text of all "u" tags excluding the text of any "desc" or "anchor" tags within them:
TEI//u//text()[not(ancestor::desc) and not(ancestor::anchor)] |
What worked for me was this. Under selenium 4.18.1.
options = webdriver.FirefoxOptions()
options.add_argument("-profile")
options.add_argument(profile_path)
driver = webdriver.Firefox(options=options)
|
I have an HTML/CSS/JS website where I'm embedding facebook posts, and adding some text (with various info and action buttons) to the top of each post. I'm adding the text that goes above each post dynamically in Javascript, so that the embedded post (iframe) is in a separate container than the text that goes above it.
As you can see in the image below, the text is positioned as `absolute` so that it appears above the post, and not next to it. However, I can't seem to get the post to move *down* nor the text to move up in order to create some separation between them. Any help or ideas would be greatly appreciated!!
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/33joo.jpg |
CSS / Add margin-top to embedded facebook post |
|html|css| |
A more concise version of the code would be to use the `to*Part()` functions on a `Duration`, e.g.
```
val duration = java.time.Duration.ofMillis(delta)
val hours = duration.toHours()
val minutes = duration.toMinutesPart()
val seconds = duration.toSecondsPart()
return if (hours == 0L) {
String.format("%02d:%02d", minutes, seconds)
} else {
String.format("%02d:%02d:%02d", hours, minutes, seconds)
}
``` |
I have this JSON expression
`'{"uid":false,"token":null,"ma":null,"question":[{"questionId":47599,"answerId":190054,"answer":1}],"iframe":true,"ref":"<SOMEREFERRER>","ts":1711214476}'`
that a webclient (in this case, Google Chrome and Firefox on iOS) wants to send to a webserver. It is a reply on a survey form another server (SOMEREFERRER) has sent. I am rather unfamiliar with JSON and wondering what this string is exactly doing when posted to the target server.
I have found that the survey server is accepting this string multiple times and counts it as a "vote". This is not supposed to happen.
More details are available on request. |
C: Shared variable read from low priority thread in preemptive scheduling |
|c|multithreading|embedded|mutex|critical-section| |
I have some python code:
```
class Meta(type):
def __new__(cls, name, base, attrs):
attrs.update({'name': '', 'email': ''})
return super().__new__(cls, name, base, attrs)
def __init__(cls, name, base, attrs):
super().__init__(name, base, attrs)
cls.__init__ = Meta.func
def func(self, *args, **kwargs):
setattr(self, 'LOCAL', True)
class Man(metaclass=Meta):
login = 'user'
psw = '12345'
```
How do I write this statement as OOP-true (Meta.func)? In the row: `cls.__init__ = Meta.func`
I tried `cls.__init__ = cls.func`, but it doesn't create local variables for the Man class object. |
More Efficient Summarise / Summarize in R |
|r|dplyr| |
My drawables are on the folder drawable-xxhdpi and the background size is 1080 x 1920.
For the screens with this resolution, all is OK.
But when I test on a samsung A34 for example with the resolution 1080 X 2340, I have a black strip under my screen game and I don't know how to scale my background and the position of the other graphics elements to this specfic screen.
Thank you
Gigi
```
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
// Affichage du background
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.backgame), 0, 0, paint);
```
[Screenshot][1]
[1]: https://i.stack.imgur.com/rWpbM.png |
{"Voters":[{"Id":10141885,"DisplayName":"halt9k"}]} |
1)I need to perform a filtered search using a custom filter object that contains the query parameters supported by my API. I have devised a solution that works, but I'm not sure if it's the best way to implement it.
Let's assume that my API accepts 10 different query parameters, while my ContractDto only has a few fields.
In this case, I can't use the default filterBy implemented by DataTable, so I need to perform some actions inside my load method.
2)I need to be able to reset the page value to 0 when clicking on the search button so that I can perform the correct query.
I have come up with two solutions, but I don't like either of them very much.
# Question 1
# My view
```
@Component
@ViewScoped
public class Contracts {
@Autowired
private Service service;
private LazyDataModel<ContractDto> lazyModel;
private ContractFilter filter = new ContractFilter();
private Selections selections;
@PostConstruct
public void init() {
selections = service.loadSelections();
search();
}
public void search() {
lazyModel = new LazyContractDto(service, filter);
}
//GETTERS AND SETTERS
}
```
# LazyDataModel
```
@SuppressWarnings("serial")
public class LazyContractDto extends LazyDataModel<ContractDto> {
private Service service;
private ContractFilter filter;
Map<String, String> filterMap;
public LazyContractDto(Service service, ContractFilter filter) {
this.service = service;
this.filter = filter;
}
@Override
public int count(Map<String, FilterMeta> filterBy) {
// TODO Auto-generated method stub
return 0;
}
@Override
public List<ContractDto> load(int first, int pageSize, Map<String, SortMeta> sortBy,
Map<String, FilterMeta> filterBy) {
Optional<Pageable> optionalPageable = createPageable(first, pageSize, sortBy);
LazyResponseHolder<ContractDto> lazyResponseHolder = service.findAllContracts(optionalPageable);
this.setRowCount(lazyResponseHolder.getRowCount() != null ? lazyResponseHolder.getRowCount() : 0);
return lazyResponseHolder.getLazyList();
}
private Optional<Pageable> createPageable(int first, int pageSize, Map<String, SortMeta> sortBy) {
filterMap = contractFilter.createFilterMap();
Pageable pageable = new Pageable();
pageable.setPage(first / pageSize);
pageable.setSize(pageSize);
// Return di optional empty
if (sortBy.isEmpty() && filterMap.isEmpty()) {
return Optional.of(pageable);
}
// add filters to custom Pageable object
filterMap.forEach(pageable::addFilterItem);
if (sortBy != null) {
sortBy.entrySet().stream().map(entry -> {
SortMeta sortMeta = entry.getValue();
String order = sortMeta.getOrder() == SortOrder.ASCENDING ? "asc" : "desc";
return sortMeta.getField() + "," + order;
}).forEach(sortString -> pageable.addSortItem(sortString));
}
return Optional.of(pageable);
}
}
```
# Filter
```
public class ContrattoFilter {
private String id;
private String state;
private String revision;
more...
public Map<String, String> createFilterMap() {
Map<String, String> filterMap = new HashMap<>();
if (id != null && !id.isBlank()) {
filterMap.put("id", id);
}
if (stato != null && !stato.isBlank()) {
filterMap.put("state", state);
}
if (revisione != null && !revisione.isBlank()) {
filterMap.put("revision", revision);
}
// add more if needed..
return filterMap;
}
//getters and setters
}
```
# xhtml
```
<h:form id="filterForm">
<ui:param name="filter" value="#{contratti.filter}" />
<div class="ui-fluid formgrid grid">
<div class="field col-12 md:col-1">
<p:outputLabel for="@next" value="ID" />
<p:inputText id="id" value="#{filter.id}"
placeholder="CTR00" styleClass="uppercase">
</p:inputText>
</div>
<div class="field col-12 md:col-1">
<p:outputLabel for="@next" value="STATE" />
<p:inputText id="state" value="#{filter.state}" placeholder="ID"
styleClass="uppercase">
</p:inputText>
</div>
<div class="field col-12 md:col-1">
<p:outputLabel for="@next" value="REVISION" />
<p:selectOneMenu id="revision" value="#{filter.revision}"
styleClass="uppercase" panelStyleClass="uppercase">
<f:selectItem itemLabel="--" itemValue="#{null}" />
<f:selectItems
value="#{contracts.selections.revisionList}"
var="item" itemLabel="#{item.description}"
itemValue="#{item.description}" />
</p:selectOneMenu>
</div>
...more fields
<div class="field col-12 md:col-1">
<p:outputLabel for="@next" value=" " />
<p:commandButton value="Search" icon="pi pi-search"
styleClass="ui-button-success" action="#{contracts.search()}"
process="filterForm" update=":contracts:contractsTable" />
</div>
</div>
</h:form>
<br />
<h:form id="contracts">
<p:dataTable id="contractsTable" var="item"
value="#{contracts.lazyModel}" lazy="true" size="small" widgetVar="contractsTable"
paginator="true" rows="10" allowUnsorting="true"
paginatorPosition="top"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
currentPageReportTemplate="{startRecord}-{endRecord} of {totalRecords} results"
rowsPerPageTemplate="2,5,10,20" showGridlines="true">
<p:column headerText="value 1" sortBy="#{item.value1}">
<h:outputText value="#{item.value1}" />
</p:column>
<p:column headerText="value2" sortBy="#{item.value2}">
<h:outputText value="#{item.value1}" />
</p:column>
</p:dataTable>
</h:form>
```
# Question 2
# solution 1: LazyDataModel init
In this solution, I achieve the correct behavior. Let's say I load the table without any filters applied. I get 100 results, then I navigate to page 2.
When I perform a search, I get a new instance of LazyDataModel with the page set to 0, ensuring that the correct query is performed.
What I dislike about this solution is that I have to "hardcode" the form name and table name in my init method. If I change the form name, everything stops working.
```
public LazyContractDto(Service service, ContractFilter filter) {
this.service = service;
this.contractFilter = contractFilter;
DataTable dataTable = (DataTable) FacesContext.getCurrentInstance().getViewRoot().findComponent("contracts:contractsTable");
dataTable.setFirst(0);
}
```
# solution 2: xhtml, onclick pfWidget
In my search button, I perform an action onclick. The issue in this case is that the load method is invoked twice, resulting in the query being performed twice.
The first time, I get no results because my API will perform this query:`/contract/search?id=84&page=2&size=10`. However, the second time, I get the correct result because the page size is set to 0 after the first load, and I'll perform this query: `/contract/search?id=84&page=0&size=10`, retrieving the few contracts that my API returns.
`onclick="PF('contractsTable').getPaginator().setPage(0);"`
|
LazyDataModel, custom filter with search button |
|jsf|primefaces| |
null |
It's a simple project localhost in spring Boot, Java 11 Correto and everything is configured automatically using the spring-boot-starter-data-redis module. It has a postGres database. But I get failure when running the spring boot app.
dependency project pom.xml
```
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/>
</parent>
<properties>
<java.version>11</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<apache-cxf-version>3.4.4</apache-cxf-version>
<org.apache.tiles.version>2.2.2</org.apache.tiles.version>
<log4j2.version>2.17.1</log4j2.version>
<org.hibernate-jpamodelgen.version>4.3.11.Final</org.hibernate-jpamodelgen.version>
<jasperreports.version>6.3.0</jasperreports.version>
<batik-bridge.version>1.8</batik-bridge.version>
<xmlgraphics-commons.version>2.1</xmlgraphics-commons.version>
<jasperreports-plugin.version>2.3</jasperreports-plugin.version>
</properties>
<dependencies>
<!-- Spring depencencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<!-- boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
```
redis configuration
```
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration;
@Configuration
public class RedisConfig extends RedisHttpSessionConfiguration{
@Bean
public ConfigureRedisAction configureRedisAction() {
return ConfigureRedisAction.NO_OP;
}
}
```
Properties file:
```
spring:
data:
redis:
host: master.des-upf-redis-cluster.wvvha4.euw1.cache.amazonaws.com
username: ${redis.server.user}
password: ${redis.server.password}
port: 6379
timeout: 3600
ssl:
enabled: true
```
Locally it does not start due to a Redis configuration problem
when I run spring boot app, I get this following runtime error:
```
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.6)
2024-03-21 17:17:05.565 INFO 7508 --- [ main] edu.upf.CarrecsApplication : Starting CarrecsApplication using Java 11.0.16 on WS142676 with PID 7508 (C:\workspacesAWS\uac-gid-carrecsj2ee\target\classes started by u89047 in C:\workspacesAWS\uac-gid-carrecsj2ee)
2024-03-21 17:17:05.569 INFO 7508 --- [ main] edu.upf.CarrecsApplication : The following 1 profile is active: "DES"
2024-03-21 17:17:07.028 INFO 7508 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2024-03-21 17:17:07.031 INFO 7508 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2024-03-21 17:17:07.723 INFO 7508 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 682 ms. Found 12 JPA repository interfaces.
2024-03-21 17:17:07.736 INFO 7508 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2024-03-21 17:17:07.738 INFO 7508 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode.
2024-03-18 12:26:30.932 INFO 11416 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data Redis - Could not safely identify store assignment for repository candidate interface edu.upf.unipersonals.repository.AbsenciaRepository. If you want this repository to be a Redis repository, consider annotating your entities with one of these annotations: org.springframework.data.redis.core.RedisHash (preferred), or consider extending one of the following types with your repository: org.springframework.data.keyvalue.repository.KeyValueRepository.
2024-03-21 17:17:07.801 INFO 7508 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 54 ms. Found 0 Redis repository interfaces.
2024-03-21 17:17:08.253 INFO 7508 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.ws.config.annotation.DelegatingWsConfiguration' of type [org.springframework.ws.config.annotation.DelegatingWsConfiguration$$EnhancerBySpringCGLIB$$bdcba1f9] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2024-03-21 17:17:08.328 INFO 7508 --- [ main] .w.s.a.s.AnnotationActionEndpointMapping : Supporting [WS-Addressing August 2004, WS-Addressing 1.0]
2024-03-21 17:17:08.657 INFO 7508 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2024-03-21 17:17:08.671 INFO 7508 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2024-03-21 17:17:08.671 INFO 7508 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.60]
2024-03-21 17:17:09.106 INFO 7508 --- [ main] org.apache.jasper.servlet.TldScanner : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2024-03-21 17:17:09.129 INFO 7508 --- [ main] o.a.c.c.C.[.[localhost].[/carrecs] : Initializing Spring embedded WebApplicationContext
2024-03-21 17:17:09.129 INFO 7508 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3472 ms
2024-03-21 17:17:09.836 INFO 7508 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2024-03-21 17:17:10.776 INFO 7508 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2024-03-21 17:17:10.859 INFO 7508 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2024-03-21 17:17:10.935 INFO 7508 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.7.Final
2024-03-21 17:17:11.165 INFO 7508 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2024-03-21 17:17:11.418 INFO 7508 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL10Dialect
2024-03-21 17:17:12.689 INFO 7508 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2024-03-21 17:17:12.882 INFO 7508 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2024-03-21 17:17:12.921 WARN 7508 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2024-03-21 17:17:13.677 WARN 7508 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :
Using generated security password: 39b68c00-b423-4f90-84fe-2915b4ed1819
This generated password is for development use only. Your security configuration must be updated before running your application in production.
2024-03-21 17:17:13.791 INFO 7508 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 1 endpoint(s) beneath base path '/actuator'
2024-03-21 17:17:13.813 INFO 7508 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will not secure any request
2024-03-21 17:17:15.185 WARN 7508 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'enableRedisKeyspaceNotificationsInitializer' defined in class path resource [org/springframework/boot/autoconfigure/session/RedisSessionConfiguration$SpringBootRedisHttpSessionConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.data.redis.RedisSystemException: Error in execution; nested exception is io.lettuce.core.RedisCommandExecutionException: ERR unknown command `CONFIG`, with args beginning with: `GET`, `notify-keyspace-events`,
2024-03-21 17:17:15.188 INFO 7508 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2024-03-21 17:17:15.191 INFO 7508 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2024-03-21 17:17:15.436 INFO 7508 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2024-03-21 17:17:15.579 INFO 7508 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2024-03-21 17:17:15.594 INFO 7508 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2024-03-21 17:17:15.612 ERROR 7508 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'enableRedisKeyspaceNotificationsInitializer' defined in class path resource [org/springframework/boot/autoconfigure/session/RedisSessionConfiguration$SpringBootRedisHttpSessionConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.data.redis.RedisSystemException: Error in execution; nested exception is io.lettuce.core.RedisCommandExecutionException: ERR unknown command `CONFIG`, with args beginning with: `GET`, `notify-keyspace-events`,
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.18.jar:5.3.18]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.18.jar:5.3.18]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.18.jar:5.3.18]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.18.jar:5.3.18]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.18.jar:5.3.18]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.18.jar:5.3.18]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.18.jar:5.3.18]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953) ~[spring-beans-5.3.18.jar:5.3.18]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.18.jar:5.3.18]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.18.jar:5.3.18]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.6.jar:2.6.6]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740) ~[spring-boot-2.6.6.jar:2.6.6]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) ~[spring-boot-2.6.6.jar:2.6.6]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-2.6.6.jar:2.6.6]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.6.jar:2.6.6]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.6.jar:2.6.6]
at edu.upf.CarrecsApplication.main(CarrecsApplication.java:16) ~[classes/:na]
Caused by: org.springframework.data.redis.RedisSystemException: Error in execution; nested exception is io.lettuce.core.RedisCommandExecutionException: ERR unknown command `CONFIG`, with args beginning with: `GET`, `notify-keyspace-events`,
at org.springframework.data.redis.connection.lettuce.LettuceExceptionConverter.convert(LettuceExceptionConverter.java:54) ~[spring-data-redis-2.6.3.jar:2.6.3]
at org.springframework.data.redis.connection.lettuce.LettuceExceptionConverter.convert(LettuceExceptionConverter.java:52) ~[spring-data-redis-2.6.3.jar:2.6.3]
at org.springframework.data.redis.connection.lettuce.LettuceExceptionConverter.convert(LettuceExceptionConverter.java:41) ~[spring-data-redis-2.6.3.jar:2.6.3]
at org.springframework.data.redis.PassThroughExceptionTranslationStrategy.translate(PassThroughExceptionTranslationStrategy.java:44) ~[spring-data-redis-2.6.3.jar:2.6.3]
at org.springframework.data.redis.FallbackExceptionTranslationStrategy.translate(FallbackExceptionTranslationStrategy.java:42) ~[spring-data-redis-2.6.3.jar:2.6.3]
at org.springframework.data.redis.connection.lettuce.LettuceConnection.convertLettuceAccessException(LettuceConnection.java:272) ~[spring-data-redis-2.6.3.jar:2.6.3]
at org.springframework.data.redis.connection.lettuce.LettuceConnection.await(LettuceConnection.java:1063) ~[spring-data-redis-2.6.3.jar:2.6.3]
at org.springframework.data.redis.connection.lettuce.LettuceConnection.lambda$doInvoke$4(LettuceConnection.java:920) ~[spring-data-redis-2.6.3.jar:2.6.3]
at org.springframework.data.redis.connection.lettuce.LettuceInvoker$Synchronizer.invoke(LettuceInvoker.java:673) ~[spring-data-redis-2.6.3.jar:2.6.3]
at org.springframework.data.redis.connection.lettuce.LettuceInvoker$DefaultSingleInvocationSpec.get(LettuceInvoker.java:589) ~[spring-data-redis-2.6.3.jar:2.6.3]
at org.springframework.data.redis.connection.lettuce.LettuceServerCommands.getConfig(LettuceServerCommands.java:177) ~[spring-data-redis-2.6.3.jar:2.6.3]
at org.springframework.data.redis.connection.DefaultedRedisConnection.getConfig(DefaultedRedisConnection.java:1674) ~[spring-data-redis-2.6.3.jar:2.6.3]
at org.springframework.session.data.redis.config.ConfigureNotifyKeyspaceEventsAction.getNotifyOptions(ConfigureNotifyKeyspaceEventsAction.java:74) ~[spring-session-data-redis-2.6.2.jar:2.6.2]
at org.springframework.session.data.redis.config.ConfigureNotifyKeyspaceEventsAction.configure(ConfigureNotifyKeyspaceEventsAction.java:55) ~[spring-session-data-redis-2.6.2.jar:2.6.2]
at org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration$EnableRedisKeyspaceNotificationsInitializer.afterPropertiesSet(RedisHttpSessionConfiguration.java:333) ~[spring-session-data-redis-2.6.2.jar:2.6.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.18.jar:5.3.18]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.18.jar:5.3.18]
... 16 common frames omitted
Caused by: io.lettuce.core.RedisCommandExecutionException: ERR unknown command `CONFIG`, with args beginning with: `GET`, `notify-keyspace-events`,
at io.lettuce.core.internal.ExceptionFactory.createExecutionException(ExceptionFactory.java:147) ~[lettuce-core-6.1.8.RELEASE.jar:6.1.8.RELEASE]
at io.lettuce.core.internal.ExceptionFactory.createExecutionException(ExceptionFactory.java:116) ~[lettuce-core-6.1.8.RELEASE.jar:6.1.8.RELEASE]
at io.lettuce.core.protocol.AsyncCommand.completeResult(AsyncCommand.java:120) ~[lettuce-core-6.1.8.RELEASE.jar:6.1.8.RELEASE]
at io.lettuce.core.protocol.AsyncCommand.complete(AsyncCommand.java:111) ~[lettuce-core-6.1.8.RELEASE.jar:6.1.8.RELEASE]
at io.lettuce.core.protocol.CommandWrapper.complete(CommandWrapper.java:63) ~[lettuce-core-6.1.8.RELEASE.jar:6.1.8.RELEASE]
at io.lettuce.core.protocol.CommandHandler.complete(CommandHandler.java:746) ~[lettuce-core-6.1.8.RELEASE.jar:6.1.8.RELEASE]
at io.lettuce.core.protocol.CommandHandler.decode(CommandHandler.java:681) ~[lettuce-core-6.1.8.RELEASE.jar:6.1.8.RELEASE]
at io.lettuce.core.protocol.CommandHandler.channelRead(CommandHandler.java:598) ~[lettuce-core-6.1.8.RELEASE.jar:6.1.8.RELEASE]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1372) ~[netty-handler-4.1.75.Final.jar:4.1.75.Final]
at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1235) ~[netty-handler-4.1.75.Final.jar:4.1.75.Final]
at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1284) ~[netty-handler-4.1.75.Final.jar:4.1.75.Final]
at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:510) ~[netty-codec-4.1.75.Final.jar:4.1.75.Final]
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:449) ~[netty-codec-4.1.75.Final.jar:4.1.75.Final]
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:279) ~[netty-codec-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:722) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496) ~[netty-transport-4.1.75.Final.jar:4.1.75.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986) ~[netty-common-4.1.75.Final.jar:4.1.75.Final]
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.75.Final.jar:4.1.75.Final]
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.75.Final.jar:4.1.75.Final]
at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]
```
My by I need some custom redis configuration to avoid calling CONFIG command? Or my be some other solution? |
I am currently trying to extract cells' background color from a xlsx file:
[image](https://i.stack.imgur.com/LP3nn.png)
I've tried two ways obtained from other stackoverflow posts:
1)
```
wb = load_workbook(excel_file, data_only = True)
sh = wb[wb.sheetnames[0]]
rows = sh.max_row
cols = sh.max_column
bckg_color = np.empty(shape=(rows, cols), dtype=object)
for i in range(1,rows+1):
for j in range(1,cols+1):
cell = sh.cell(column=j, row=i)
color_in_hex = cell.fill.start_color.index
bckg_color[i-1, j-1] = str(color_in_hex)
pd.DataFrame(bckg_color)
```
2)
```
sf = StyleFrame.read_excel(excel_file, read_style=True, use_openpyxl_styles=False, header=None)
bckg_color = StyleFrame(sf.applymap(lambda cell: cell.style.bg_color)).data_df.astype(str)
bckg_color
```
Both of them give the same result:
[df screenshot](https://i.stack.imgur.com/r91bv.png)
The expected result was the same color on the 4th row, but it's not because of merged cells in that row. Is there a robust way (expect using bfill on the color dataframe) to get the colors so that the whole row would have the color I see on the screenshot? I suspect it can be done with getting information about merged cells from openpyxl, but I would not like to resort to that.
|
Get correct background color for merged cells in xlsx file |
|python|excel|openpyxl|cell|background-color| |
null |
null |
You mean something like this?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const addLargeNumbers = (strNum1, strNum2) => {
// Start from the end of both strings
let result = '';
let carry = 0;
let i = strNum1.length - 1;
let j = strNum2.length - 1;
while (i >= 0 || j >= 0 || carry > 0) {
const digit1 = i >= 0 ? parseInt(strNum1.charAt(i), 10) : 0;
const digit2 = j >= 0 ? parseInt(strNum2.charAt(j), 10) : 0;
const sum = digit1 + digit2 + carry;
result = (sum % 10) + result;
carry = Math.floor(sum / 10);
i--;
j--;
}
return result;
};
console.log(addLargeNumbers("19007199254740991","29007199254740991"))
const compareLargeNumbers = (strNum1, strNum2) => {
strNum1 = strNum1.replace(/^0+/, '');
strNum2 = strNum2.replace(/^0+/, '');
if (strNum1.length > strNum2.length) return 1;
if (strNum1.length < strNum2.length) return -1;
for (let i = 0; i < strNum1.length; i++) {
if (strNum1[i] > strNum2[i]) return 1;
if (strNum1[i] < strNum2[i]) return -1;
}
return 0;
};
console.log(compareLargeNumbers("19007199254740991","19007199254740991") !== -1)
console.log(compareLargeNumbers("19007199254740991","29007199254740991") !== -1)
<!-- end snippet -->
|
It's looks like work, the only is filter the value when you received the new values
this.filterInput$
.pipe(
debounceTime(300),
distinctUntilChanged(),
filter((query) => query?.length >= 3),
)
.subscribe((filterValue) => {
this.adminUserService.filterPermission(filterValue).subscribe((res) => {
this.permissions = res.map(x=>({label:x,value:x}));
//here you filter the "selectedPermisions"
if (this.selectedPermission)
this.selectedPermission=this.selectedPermission
.filter(x=>res.includes(x.label))
//this.cdr.detectChanges(); <--it's not necessary
});
});
NOTE: you can also define an observable like
permissions$=this.filterInput$
.pipe(
debounceTime(300),
distinctUntilChanged(),
filter((query) => query?.length >= 3),
switchMap((query)=>
this.adminUserService.filterPermission(query).pipe(
map((res:string[])=>{
if (this.selectedPermission)
this.selectedPermission=this.selectedPermission
.filter(x=>res.includes(x.label))
return res.map(x=>({label:x,value:x}))
})))
)
And use
<p-multiSelect
class="add-more-permission-modal__container__filter"
[options]="(permissions$|async) || undefined"
...
</p-multiSelect>
See [stackblitz][1]
[1]: https://stackblitz.com/edit/stackblitz-starters-dclr9f?file=src%2Fmain.ts,src%2Fadmin-user-api.service.ts
|
When a class has been specified in a use statement, it can be referred to by the final element of the fully namespaced class name. Evidently PHP knows from the short name the identity of the class. Is there a way to obtain this information?
Or is there any other way to deal with the issue - I want to know if the class exists. Obviously it is possible to write the fully namespaced name of the class and call class_exists() but this means that information is duplicated between the use statement and the call to class_exists(), which is a bad principle.
A somewhat similar question is at https://stackoverflow.com/questions/45677923/get-full-class-name-from-short-class-name but differs significantly because there is no use statement to give the required information in that case.
Searched, found nothing relevant.
EDIT: I'm grateful for the link to the earlier answer, although I'm not deleting my question because I think the way the question is phrased is more likely to be found by someone looking for what I was looking for. |
Practically, there is no difference, especially since you are using immutable `Map`s (as opposed to `MutableMap`). I used Amazon's `corretto-18` to compile your code and inspected the bytecode. Those are the conclusions I got from doing so:
`println(mappings["PL"]!!)` compiles to the following bytecode:
```bytecode
LINENUMBER 19 L0
GETSTATIC MainKt.mappings : Ljava/util/Map;
LDC "PL"
INVOKEINTERFACE java/util/Map.get (Ljava/lang/Object;)Ljava/lang/Object; (itf)
DUP
INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkNotNull (Ljava/lang/Object;)V
ASTORE 0
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
ALOAD 0
INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
```
So it:
1. Accesses the global `mappings` object.
2. Invokes `.get()` on it.
3. Checks if the result is not `null`.
4. Accesses the global `System.out` object.
5. Invokes `.println()` on it by passing the `String` gotten from the map.
In case of `println(mappingsFunc("US")!!)`, we have:
```bytecode
LINENUMBER 20 L1
LDC "US"
INVOKESTATIC MainKt.mappingsFunc (Ljava/lang/String;)Ljava/lang/String;
DUP
INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkNotNull (Ljava/lang/Object;)V
ASTORE 0
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
ALOAD 0
INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
```
which differs only in the first two operations. Instead of accessing any object and calling its method, it simply invokes the `mappingsFunc()` method. Let us inspect what it does exactly:
```bytecode
public final static mappingsFunc(Ljava/lang/String;)Ljava/lang/String;
@Lorg/jetbrains/annotations/NotNull;() // invisible
// annotable parameter count: 1 (invisible)
@Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
L0
ALOAD 0
LDC "code"
INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkNotNullParameter (Ljava/lang/Object;Ljava/lang/String;)V
L1
LINENUMBER 9 L1
ALOAD 0
ASTORE 1
ALOAD 1
INVOKEVIRTUAL java/lang/String.hashCode ()I
LOOKUPSWITCH
2177: L2
2217: L3
2556: L4
2718: L5
default: L6
L2
LINENUMBER 12 L2
FRAME APPEND [java/lang/String]
ALOAD 1
LDC "DE"
INVOKEVIRTUAL java/lang/String.equals (Ljava/lang/Object;)Z
IFEQ L6
GOTO L7
L3
LINENUMBER 11 L3
FRAME SAME
ALOAD 1
LDC "EN"
INVOKEVIRTUAL java/lang/String.equals (Ljava/lang/Object;)Z
IFEQ L6
GOTO L8
L4
LINENUMBER 10 L4
FRAME SAME
ALOAD 1
LDC "PL"
INVOKEVIRTUAL java/lang/String.equals (Ljava/lang/Object;)Z
IFEQ L6
GOTO L9
L5
LINENUMBER 13 L5
FRAME SAME
ALOAD 1
LDC "US"
INVOKEVIRTUAL java/lang/String.equals (Ljava/lang/Object;)Z
IFEQ L6
GOTO L10
L9
LINENUMBER 10 L9
FRAME SAME
LDC "Poland"
GOTO L11
L8
LINENUMBER 11 L8
FRAME SAME
LDC "England"
GOTO L11
L7
LINENUMBER 12 L7
FRAME SAME
LDC "Germany"
GOTO L11
L10
LINENUMBER 13 L10
FRAME SAME
LDC "United States of America"
GOTO L11
L6
LINENUMBER 14 L6
FRAME SAME
LDC "Unknown"
L11
LINENUMBER 9 L11
FRAME SAME1 java/lang/String
ARETURN
L12
LOCALVARIABLE code Ljava/lang/String; L0 L12 0
MAXSTACK = 2
MAXLOCALS = 2
```
Lots of code, so let us inspect the only relevant part that we should pay attention to:
```bytecode
L1
LINENUMBER 9 L1
ALOAD 0
ASTORE 1
ALOAD 1
INVOKEVIRTUAL java/lang/String.hashCode ()I
LOOKUPSWITCH
2177: L2
2217: L3
2556: L4
2718: L5
default: L6
L2
LINENUMBER 12 L2
FRAME APPEND [java/lang/String]
ALOAD 1
LDC "DE"
INVOKEVIRTUAL java/lang/String.equals (Ljava/lang/Object;)Z
IFEQ L6
GOTO L7
```
Before analyzing it further, it's worth to note that branches `L3`, `L4` and `L5` are basically identical to `L2` - they just differ in a given String literal.
The above bytecode invokes `String::hashCode()` and then `String::equals` to pick the correct branch.
Which is... basically the same thing as what `Map::get()` does.
In conclusion, those constructs are almost equivalent, with a single exception that the memory consumption and initial creation of the `mapping` object takes some time and memory. A negligible amount, though. |
I try to have a button to add ppl to the enlistment of a game. i have a function in another cog that updates the enlistment. so once someone press the button i want it to run that function it adds the person to a mySQL database and then the enlistment cog runs it and displays it on an message in the discord.
```
class reserve(commands.Cog):
def __init__(self, client):
self.client = client
class MyView(discord.ui.View):
@discord.ui.button(style=discord.ButtonStyle.success, label="Enlist me")
async def on_button_one_click(self, interaction: discord.Interaction, button: discord.ui.Button):
enlistment = self.client.get_cog("Embed") #This part is not working
await enlistment.enlistment(self) #This part is not working
```
This is the error I get
File "f:\SeaWolf\pythonbot\cogs\reserves.py", line 31, in on_button_one_click
enlistment = self.client.get_cog("Embed")
^^^^^^^^^^^
AttributeError: 'MyView' object has no attribute 'client'
I can load the function from other cogs doing the same thing but with a slash command instead of a button but i wanted to make it a bit easier with a button.
|
I have a column in excel open in power query that has dates. the format is m/d/yy hh:mm;@. example :1/3/2023 6:00:00 AM. this is considered as January 3rd. I want to change it to be march, meaning I want the 3 to be the month and 1 to be the day, so it becomes 1st march.
I made sure the column is of type date, I went to "text to column" and switched it from MDY to DMY and I also tried to switch the text formats with this : =TEXT(A2, "dd/m/yy hh:mm;@") and then converting it to date type, but nothing worked |
change date in excel from MDY to DMY |
|excel| |
null |
Just chain up your 2 queries with `$unionWith`
```js
db.collection.aggregate([
{
"$sort": {
"insertedAt": 1
}
},
{
$limit: 1
},
{
"$unionWith": {
"coll": "collection",
"pipeline": [
{
"$sort": {
"insertedAt": -1
}
},
{
$limit: 1
}
]
}
}
])
```
[Mongo Playground](https://mongoplayground.net/p/5bboUHwymd3) |
*Adequate block deployment is not working html/css. Blocks do not work properly. There are blocks, and if you click on one block, the next block expands, this happens on the tablet version, what to do?* **Example: in the picture, when one block is expanded, another block is expanded behind it.I want to make sure that when you click on one block, the second does not open**[
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.team{
width: 688px;
margin: 0 auto;
margin-top: 29px;
margin-bottom: 29px;
display: flex;
flex-direction: column;
}
.container_team{
width: 744px;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.input{
display: none;
}
.input:checked ~ .p {
max-width: 100vw;
max-height: 100vh;
position: relative;
white-space: normal;
clip-path: none;
margin-top: 15px;
}
.input:checked + .item_label::after {
transform: rotate(315deg);
}
.h3{
font-family: 'Inter';
font-size: 18px;
font-weight: 700;
line-height: 25px;
letter-spacing: 0em;
text-align: center;
}
.im{
margin-top: 20px;
margin-bottom: 20px;
}
.team{
max-width: 743px;
}
.team h3{
font-size: 18px;
font-weight: 700;
font-family: 'Inter';
line-height: 25px;
}
.team picture{
width: 330px;
height: 203px;
}
.team .le{
width: 550px;
display: flex;
flex-direction: column;
align-items: center;
}
.team .lea{
display: flex;
flex-direction: column;
align-items: center;
}
.team .pZ{
width: 550px;
display: flex;
flex-direction: column;
align-items: center;
}
.team .zp{
width: 550px;
display: flex;
align-items: center;
flex-direction: column;
}
.team label{
display: flex;
justify-content: space-between;
align-items: center;
padding-left: 10px;
padding-right: 10px;
}
.team label::after{
content: '+';
width: 30px;
height: 30px;
font-size: 30px;
font-weight: bolder;
}
.team input:checked ~ label::after{
transform: rotateZ(315deg);
}
.team .men{
width: 300px;
font-size: 18px;
}
.team .buzne{
width: 300px;
}
.team .tele{
width: 300px;
margin-top: 10px;
background: #F5FFD9;
}
.team .Ar{
width: 300px;
margin-top: 10px;
}
.team .Di{
width: 300px;
margin-top: 10px;
}
.team .ro{
width: 300px;
margin-top: 10px;
}
.team .te{
width: 300px;
margin-top: 10px;
}
.team .su{
width: 300px;
margin-top: 10px;
}
.team .container_team .p{
position: absolute;
max-width: 1px;
max-height: 1px;
margin: -1px;
border: 0;
padding: 0;
white-space: nowrap;
clip-path: inset(100%);
clip: rect(0 0 0 0);
overflow: hidden;
padding: 20px;
}
.team picture{
order: 1;
margin-left: 190px;
}
.team picture img{
width: 330px;
height: 203px;
}
.h2{
margin-left: 190px;
}
.team .container_team .input:checked ~ .p{
max-height: 100vh;
max-width: 100vw;
position: relative;
white-space: normal;
clip-path: none;
}
.Ar > .team input:checked {
z-index: 1;
}
<!-- language: lang-html -->
<section class="team">
<h2 class="h2">Команда розробників</h2>
<div class="container_team">
<div class="men">
<input class="input" type="checkbox" name="" id="checks1">
<label for="checks1">
<h3 class="h3">Менеджер проекту</h3>
</label>
<p class="p">Менеджер проекту розподіляє завдання між командою, планує хід роботи, мотивує команду, контролює процес та координує спільні дії. Також він несе відповідальність за тайм-менеджмент, управління ризиками та дії у разі непередбачених ситуацій. Основний обов’язок і відповідальність PM – довести ідею замовника до реалізації у встановлений термін, використовуючи наявні ресурси. В рамках цієї задачі PM’у необхідно створити план розробки, організувати команду, налаштувати процес роботи над проектом, забезпечити зворотній зв’язок між командами та замовником, усувати перешкоди для команд, контролювати якість і виконання термінів. Його основне завдання полягає в управлінні проектом. Як і бізнес-аналітик, менеджер проекту також може бути включений у комунікацію з клієнтом, проте головним завданням PM є робота безпосередньо з командою розробників програмного забезпечення. Середній вік в Україні- 30 років. Вирізняються високим рівнем освіти (тільки 6% не мають вищої освіти). Зарплата 1700-2500$.</p>
</div>
<div class="buzne">
<input class="input" type="checkbox" name="" id="checks2">
<label for="checks2">
<h3 class="h3">Бізнес аналітик</h3>
</label>
<p class="p">Це фахівець, який досліджує проблему замовника, шукає рішення і оформлює його концепцію в формі вимог, на які надалі будуть орієнтуватися розробники при створенні продукту. Середньому українському бізнес-аналітику 28 років, він має зарплату $ 1300-2500 і досвід роботи 3 роки.</p>
</div>
<div class="tele">
<input type="checkbox" name="" id="checks3">
<label for="checks3">
<h3 class="h3">Team Lead</h3>
</label>
<p class="p">Це IT-фахівець, який керує своєю командою розробників, володіє технічною стороною, бере участь у роботі над архітектурою проекту, займається рев'ю коду, а також розробкою деяких складних завдань на проекті. За статистикою ДНЗ, середній вік українських тімлідів – 28 років, середній досвід роботи – 6,5 років, середня зарплата – $2800.</p>
</div>
<div class="Ar">
<input type="checkbox" id="checks4">
<label for="checks4">
<h3 class="h3">Архітектор ПЗ</h3>
</label>
<p class="p">
Приймає рішення щодо внутрішнього устрою і зовнішніх інтерфейсів програмного комплексу з урахуванням проектних вимог і наявних ресурсів.Головна задача архітектора – пошук оптимальних (простих, зручних, дешевих) рішень, які будуть максимально відповідати потребам замовника і можливостям команди. За статистикою ДОУ, середньому українському архітектору 30 років, він має 9-річний досвід роботи і отримує $ 4000.</p>
</div>
<div class="Di">
<input type="checkbox" name="" id="checks5">
<label class="label_comamnd" for="checks5">
<h3 class="h3">Дизайнер</h3>
</label>
<p class="p">Спеціаліст, який займається проектуванням інтерфейсів користувача. В середньому українському дизайнеру – 26 років, він має досвід роботи від півроку (джуніор) до 5 років (сеньйор) і отримує зарплату $ 1000-200</p>
</div>
<picture>
<source media="(min-width:1280px)" srcset="img/team1x.png 1x,img/team2x.png 2x,img/team3x.png 3x">
<img class="im" src="https://picsum.photos/200" alt="Проект">
</picture>
<div class="ro">
<input type="checkbox" name="" id="checks6">
<label for="checks6">
<h3 class="h3">Розробник</h3>
</label>
<p class="p">Фахівець, який пише вихідний код програм і в кінцевому результаті створює технології. Програмісти також мають різні галузі експертизи, вони пишуть різними мовами та працюють з різними платформами. Тому і існує така “різноманітність” розробників, залучених до одного проекту. На одному проекті переважно завжди є як мінімум два програмісти- перший, який займається back-end розробкою та інший, відповідальний за front-end. Існує два напрямки програмування - системне та прикладне. Системні програмісти мають справу з ОС, інтерфейсами баз даних, мережами. Прикладні – з сайтами, програмним забезпеченням, програмами, редакторами, соцмережами, іграми тощо. Програміст розробляє програми за допомогою математичних алгоритмів. Перед початком роботи йому необхідно скласти алгоритм або знайти оптимальний спосіб вирішення конкретного завдання. В середньому українському програмісту 27 років, його зарплата в середньому дорівнює $ 1500-2500, а досвід роботи становить 4,5 років.</p>
</div>
<div class="te">
<input type="checkbox" name="" id="checks7">
<label for="checks7">
<h3 class="h3">Тестувальник</h3>
</label>
<p class="p">Фахівець, необхідний для кожного процесу розробки для забезпечення високої якості продукту. Вони тестують його, проходять через усі додатки та визначають баги та помилки з подальшим наданням звіту команді розробки, яка проводить їх виправлення За даними ДОУ, середньому українському QA-інженеру 26 років. Він має досвід роботи від півроку (джуніор) до 5 років (сеньйор) і отримує зарплату $ 600-2700.</p>
</div>
<div class="su">
<input type="checkbox" name="" id="checks8">
<label for="checks8">
<h3 class="h3">Support</h3>
</label>
<p class="p">Ключове завдання support-фахівця (або Customer Support Representative) — відповідати на запитання і допомагати клієнтам у телефонному режимі, поштою або у чаті. Решта завдань залежать від процесів у конкретній компанії.</p>
</div>
</div>
</section>
<!-- end snippet -->
I still haven't found out the problem I looked on the Internet, no solution!
I'm studying html/css/js at a computer school and they haven't solved this problem yet. I hope you can help us) |
null |
The problem below is from book: "Modern compiler implementation in C", chapter03, 3.3.(d)
> Write an unambiguous grammar for balanced parentheses and brackets,
where a closing bracket also closes any outstanding open parentheses
(up to the previous open bracket).
>
> Example: [([](()[(][])].
>
> Hint: First, make the language of balanced parentheses and brackets,
where extra open parentheses are allowed; then make sure this
nonterminal must appear within brackets.
I have tried many times to find no way to solve it entirely, with a closest answer below(in Yacc):
```
S : /* empty */
| '[' LP ']' S
| '(' S ')' S
;
LP : B
| '(' LP
;
B : /* empty */
| '[' LP ']' B
| '(' B ')' B
;
```
This version handles strings such as the example perfectly, but fails to handle strings like: ```[()(]```, where inner ```LP``` of ```S``` is only one instance of "***balanced parentheses and brackets, where extra open parentheses are allowed***", rather a list(which is required).
Another ambiguous but totally right(maybe) one, only with 1 reduce/reduce conflicts is:
```
S : /* empty */
| '[' B ']' S
| '(' S ')' S
;
B : P
| '[' B ']' B
| '(' B ')' B
;
P : /* empty */
| '(' P
;
```
If any one who can handle this problem, please give me a totally right solution. Thx! |
I'm deleting your post because this seems like a programming-specific question, rather than a conversation starter. With more detail added, this may be better as a Question rather than a Discussions post. Please see [this page](https://stackoverflow.com/help/how-to-ask) for help on asking a question on Stack Overflow. If you are interested in starting a more general conversation about how to approach a technical issue or concept, feel free to make another Discussion post. |
null |
Whether a type is considered statically or dynamically sized type depends on whether we know its size at _compile_ time. For example, we know that an `i32` is 4 bytes in size, and we know this at compile time, so this is a statically sized type.
We _do_ know the size of a slice when we produce it, but that happens at _run_ time. The exact same code can produce different sizes of slice, so we have to consider it dynamically sized, since we can't know how much space to allocate for it when we're compiling.
Dynamically sized types are allocated on the heap and are stored behind a pointer, which allows the compiler to allocate an appropriate amount of space at compile time (for the pointer). The compiler allocates space for the pointer, and then the memory the pointer points to (the memory for the dynamically sized type) is allocated at runtime. |
Super new to JS and could use some help when it comes to using outside sources in my workflow, specifically, the date range slider at the top of this page https://ghusse.github.io/jQRangeSlider/ The site does a good job of explaining how to get started but I cannot seem to get the slider into my file.
How can I go about extracting the date range slider in order to use in my current working file? I assume there is some moving of files into my current working directory and changing file paths but cannot seem to get it to work.
Thanks!
I have used these imports as shown here https://ghusse.github.io/jQRangeSlider/documentation.html
and moved the JavaScript files into my JavaScripts folder and moved the CSS files into my stylesheets folder but still have no luck in getting the slider to display.
```
<link rel="stylesheet" href="css/iThing.css" type="text/css" />
<script src="jquery.js"></script>
<script src="jquery-ui.custom.js"></script>
<script src="jQDateRangeSlider-min.js"></script>
```
I then initialized the slider
`$("#slider").dateRangeSlider();`
I would appreciate help getting the slider up and running!
|
Using JQuery Date Slider |
|javascript|jquery|date|slider| |
null |
I am trying to add https://github.com/coffee-and-fun/google-profanity-words to my website, but the only option I see is using Node.js which is not option for me since I need to install it on server and using from there(correct me if I am wrong)
I found some cdn like this one - https://www.skypack.dev/view/@coffeeandfun/google-profanity-words But didn't manage to get it to work.
I tried it like this -
import { ProfanityEngine } from '@coffeeandfun/google-profanity-words';
let profanity = new ProfanityEngine();
profanity.all(); // returns all bad words as an array.
profanity.search('bad word'); // returns true if the word is found in the list.
But getting an error that ProfanityEngine is not defined.
Can you please provide an example that this works on web page?
|
Adding google-profanity-words to web page |
|javascript|node.js|web| |
Here is one possible option using [`cKDTree.query`][1] from [tag:scipy]:
```py
from scipy.spatial import cKDTree
def knearest(gdf, **kwargs):
notna = gdf["PPM_P"].notnull()
arr_geom1 = np.c_[
gdf.loc[notna, "geometry"].x,
gdf.loc[notna, "geometry"].y,
]
arr_geom2 = np.c_[
gdf.loc[~notna, "geometry"].x,
gdf.loc[~notna, "geometry"].y,
]
dist, idx = cKDTree(arr_geom1).query(arr_geom2, **kwargs)
k = kwargs.get("k")
_ser = pd.Series(
gdf.loc[notna, "PPM_P"].to_numpy()[idx].tolist(),
index=(~notna)[lambda s: s].index,
)
gdf.loc[~notna, "PPM_P"] = _ser[~notna].map(np.mean)
return gdf
N = 2 # feel free to make it 5, or whatever..
out = knearest(gdf.to_crs(3662), k=range(1, N + 1))#.to_crs(4326)
```
Output (*with `N=2`*):
***NB**: Each red point (an FID having a null PPM_P), is associated with the N nearest green points)*.
[![enter image description here][2]][2]
Final GeoDataFrame (*with intermediates*):
```py
# I filled some random FID with a PPM_P value to make the input meaningful
FID PPM_P (OP) PPM_P (INTER) PPM_P geometry
0 0 34.919571 NaN 34.919571 POINT (842390.581 539861.877)
1 1 NaN 37.480218 37.480218 POINT (842399.476 539861.532)
2 2 NaN 35.567003 35.567003 POINT (842408.370 539861.187)
3 3 NaN 35.567003 35.567003 POINT (842420.229 539860.726)
4 4 36.214436 NaN 36.214436 POINT (842429.124 539860.381)
5 5 NaN 38.127651 38.127651 POINT (842438.018 539860.036)
6 6 NaN 40.431946 40.431946 POINT (842446.913 539859.691)
7 7 40.823028 NaN 40.823028 POINT (842458.913 539862.868)
8 8 NaN 37.871299 37.871299 POINT (842378.298 539851.425)
9 9 40.823028 NaN 40.823028 POINT (842390.158 539850.965)
10 10 40.040865 NaN 40.040865 POINT (842399.052 539850.620)
11 11 36.214436 NaN 36.214436 POINT (842407.947 539850.275)
12 12 34.919571 NaN 34.919571 POINT (842419.947 539853.452)
13 13 NaN 38.127651 38.127651 POINT (842428.841 539853.107)
14 14 40.040865 NaN 40.040865 POINT (842437.736 539852.761)
15 15 NaN 40.431946 40.431946 POINT (842449.595 539852.301)
16 16 NaN 40.431946 40.431946 POINT (842458.489 539851.956)
17 17 NaN 40.431946 40.431946 POINT (842467.384 539851.611)
18 18 NaN 40.431946 40.431946 POINT (842476.278 539851.266)
19 19 NaN 37.871299 37.871299 POINT (842368.981 539840.859)
```
[1]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.query.html
[2]: https://i.stack.imgur.com/KefCq.png |
In a desktop application (written in Electron), I'm trying to implement a feature that will allow the user to open the application in full screen or return it to the reverse state (initially the application does not open in full screen).
I already have working functionality.
What I've done:
main.ts
ipcMain.handle(IPCChannels.CheckMax, () => {
let result = '';
if (mainWindow.isMaximized()) {
mainWindow.unmaximize();
result = 'unmaximize';
return result;
}
mainWindow.maximize();
result = 'maximize';
return result;
});
TitleBar.tsx
function TitleBar() {
const [checkMax, setCheckMax] = useState('');
function maximize() {
window.electron.ipcRenderer
.invoke(IPCChannels.CheckMax)
.then((res) => setCheckMax(res))
.catch((err) => {
console.error(err);
});
}
return (
<nav>
<div/>
<button onClick={maximize}>
{checkMax === 'maximize' ? (
<MaxIcon />
) : (
<MinIcon />
)}
</button>
</nav>
);
}
That is, what happens from our code: I click on the button to change the screen size, the screen becomes maximum and the icon changes. Or vice versa, the screen appears with the previous sizes, and the icon changes again.
However, the problem is that the **result** variable (and the icons accordingly) only changes when I click on the button. In all applications, and you can verify this, you can exit the maximum screen size by pulling the TitleBar (try the example of Google Chrome or any browser or any application).
Please tell me how I can change the value of the **result** variable, including when I pull the TitleBar |
Very Simple
Go to nav.html
replace the logout button class with the following code :
<li class="nav-item">
<form method="post" action="{% url 'user-logout' %}">
{% csrf_token %}
<button type="submit" class="nav-link text-white" style="background: none; border: none; cursor: pointer;">
Logout
</button>
</form>
</li>
This error will be resolved |
using float and clear properties. Set the dimensions in compliance with the proportions in the figure, but keep in mind that this composition represents the layout of a web page, so
blocks should not overlap each other;
blocks should occupy the entire width of the page (regardless of screen resolution and browser window size).
Place red elements using the margin property.
For red elements, adjust the borders and fillets according to your choice.
Add text in red blocks, adjust the indentation and horizontal alignment of the text according to your choice. Allow for instances of excess text so that it does not extend beyond the block.
Text generation link: Lorem Ipsum.
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>sdf</title>
<link rel="stylesheet" href="block.css">
</head>
<body>
<header>
<div></div>
<div></div>
</header>
<div class="content">
<nav></nav>
<main></main>
<aside>
<section class="red_sjit">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</section>
<section class="red border">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</section>
</aside>
</div>
<footer></footer>
</body>
</html>
*, *::before, *::after {
box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
display: flex;
flex-direction: column;
font-size: smaller;
}
header {
display: grid;
grid-template-columns: repeat(2, 1fr);
height: 4rem;
}
header div:first-child {
background: purple;
}
header div:last-child {
background: orange;
}
.content {
display: flex;
flex-direction: row;
flex: 1;
}
nav {
width: 10rem;
background: blue;
}
main {
flex: 1;
background: yellowgreen;
}
aside {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 10rem;
gap: 1rem;
padding: 0.5rem;
background: yellow;
}
aside > section {
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 3;
line-clamp: 3;
-webkit-box-orient: vertical;
}
.red_sjit {
background-color: rgb(255, 255, 255);
text-align: center;
margin: 5px;
border-top-right-radius: 10px;
border-bottom-left-radius: 10px;
position: relative;
padding: 5px;
flex: auto;
max-height: max-content;
}
.red_sjit::before {
content: '';
position: absolute;
bottom: 0;
right: 0;
width: 100%;
height: 100%;
border-top: 2px dashed black;
border-right: 2px dashed black;
border-radius: 10px;
}
.red {
background-color: red;
text-align: center;
margin: 5px;
border-radius: 10px;
padding: 5px;
flex: auto;
max-height: max-content;
}
.red.border {
border: solid blue 2px;
}
footer {
height: 2rem;
background: pink;
}
```
|
How to write this OOP true? (Python, metaclass) |
|python-3.x|oop|metaclass| |
null |
How to avoid being struct column name written to a json file? While writing the df to the json file?
Using databricks pyspark write method.
```Df.write.option("header", "false").mode("overwrite).json(path)```
Tried option("header", "false")
Sample json file:
```{"struct_col_name":{"actual_struct_data_col":"values"....}}```
Need to avoid first root key column struct_col_name.
Sample dataframe/ schema [Sample dataframe picture][1]
[PrintSchema picture][2]
[2]: https://i.stack.imgur.com/74Mu2.jpg |
It's a bit ugly, but we can do something like this if you are OK defining the pattern for a limited number of locales and set a sensible default for the other locales.
```php
$formatter = match ($lang) {
'en' => new \IntlDateFormatter($lang, pattern: "MMMM d 'at' h:mm a"),
'es' => new \IntlDateFormatter($lang, pattern: "d 'de' MMMM, H:mm"),
'ja' => new \IntlDateFormatter($lang, pattern: "M月d日 H:mm"),
default => new \IntlDateFormatter($lang, \IntlDateFormatter::LONG, \IntlDateFormatter::NONE),
};
$date = $formatter->format($datetime);
``` |
You can try changing **`data-bs-spy="scroll"`** into **`data-spy="scroll"`**.
Here is a link to an example from the bootstrap documentation that shows the use of `data-spy="scroll"`
https://getbootstrap.com/docs/4.0/components/scrollspy/#example-in-navbar |
null |
IN MbedTls with RSA in a C-programm encryption/decryption works when using separate buffers (for plainText, cipherText, and decryptedText, i.e. the content of plainText and decryptedText is the same), but not when using just one buffer to perform in-place encryption/decryption as i get gibberish/not correctly encrypted data.
Is that just a general limitation or is my code wrong?
Background:
I'm trying to use in-place encryption and decryption with RSA in MbedTls in a C-programm. [Here](https://forums.mbed.com/t/in-place-encryption-decryption-with-aes/4531) it says that "In place cipher is allowed in Mbed TLS, unless specified otherwise.", although I'm not sure if they are also talking about AES. From my understanding i didn't see any specification saying otherwise for mbedtls_rsa_rsaes_oaep_decrypt Mbed TLS API documentation.
Code:
```
size_t sizeDecrypted;
unsigned char plainText[15000] = "yxcvbnm";
unsigned char cipherText[15000];
unsigned char decryptedText[15000];
rtn = mbedtls_rsa_rsaes_oaep_encrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, sizeof("yxcvbnm"), &plainText, &cipherText);
rtn = mbedtls_rsa_rsaes_oaep_decrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, &sizeDecrypted, &cipherText, &decryptedText, 15000);
//decryptedText afterwards contains the correctly decrypted text just like plainText
unsigned char text[15000] = "yxcvbnm";
rtn = mbedtls_rsa_rsaes_oaep_encrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, sizeof("yxcvbnm"), &text, &text);
rtn = mbedtls_rsa_rsaes_oaep_decrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, &sizeDecrypted, &text, &text, 15000);
//someText afterwards doesn't contain the correctly decrypted text/has a different content than plainText
//rtn is always 0, i.e. no error is returned
``` |
how to use only block layout in this css code? |
|html|css| |
null |
If you upload an image, try these steps:
- Convert your image into DataURI.
- Then this string insert to GIST as a text file
If you want to convert back, there are several options. For example, this:
https://stackoverflow.com/questions/17591148/converting-data-uri-to-image-data |
I have a problem with `drop_na()` function. I wanted to clean the dataset and erase the "NA" values, but when I entered the code, all datas are disseapperad. I do not understand why it happens.
You can see clearly what my codes are in this picture:
[![enter image description here][1]][1]
```
library(tidyverse)
WDI_GNI<read_csv("C:/Users/sudes/Downloads/P_Data_Extract_From_World_Development_Indicators/a7b778c6-9827-4c45-91b7-8f497087ca17_Data.csv")WDI_GNI <- WDI_GNI %>%
mutate(across(contains("[YR"),~na_if(.x, ".."))) %>%
mutate(across(contains("[YR"), as.numeric)) WDI_GNI <- drop_na(WDI_GNI)
```
[1]: https://i.stack.imgur.com/lbgDg.png |
|r| |
If you have a venv folder, you need to activate it before running the Flask server. To do this, use the [preLaunchTask][1] option. The task is declared inside `.vscode/tasks.json`.
`.vscode/launch.json`:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Flask",
"type": "debugpy",
"request": "launch",
"module": "flask",
"env": {
"FLASK_APP": "app.py",
"FLASK_ENV": "development",
"FLASK_DEBUG": "1"
},
"preLaunchTask": "activate_venv",
"args": [
"run"
],
"jinja": true,
"python": "${workspaceFolder}/venv/bin/python"
}
],
}
`.vscode/task.json`:
{
"version": "2.0.0",
"tasks": [
{
"label": "activate_venv",
"type": "shell",
"command": "source ./venv/bin/activate",
}
]
}
[1]: https://code.visualstudio.com/docs/editor/tasks#_can-a-background-task-be-used-as-a-prelaunchtask-in-launchjson |
i tried new thing as shown below and it works.
using new_t = map<string,int> ;
map<string,new_t> easy_map;
easy_map.insert(make_pair("A",map<string,int>()));
easy_map.insert(make_pair("B",map<string,int>()));
easy_map["A"].insert(make_pair("A",2));
easy_map["B"].insert(make_pair("B",2));
for (auto &&i : easy_map)
{
for (auto &&j : i.second)
{
cout << i.first << " " << j.first << " " << j.second << endl;
}
}
|
--Remove Duplciates[SKR]
--Option A:
select *
--delete t
from(
select rowNumber=row_number() over (partition by SomeKey order by SomeKey), SomeKey from YourTable m
)t where rowNumber > 1
--Option B:
with cte as (
select rowNumber=row_number() over (partition by SomeKey order by SomeKey), SomeKey from YourTable m
)
--delete from cte where rowNumber > 1
select * from cte where rowNumber > 1 |
I have a json like
[
{
"url": "https://drive.google.com/file/d/1tO-qVknlH0PLK9CblQsyd568ZiptdKff/view?usp=share_link",
"title": "– Flexibility"
},
{
"url": "https://drive.google.com/open?id=11_sR8X13lmPcvlT3POfMW3044f3wZdra",
"title": "– Pronouns"
}
]
I got it using `curl -Lfs "https://motivatedsisters.com/2019/07/08/arabic-review-sr-rahat-basit/" | rg -o '<li>.*?href="(.*?)".*?</a> (.*?)<\/li>' -r '{"url": "$1", "title": "$2"}' | jq -s '.'`.
I have a command in my machine named `unescape_html`, a python scipt to unescape the html (replace – with appropriate character).
How can I apply this function on each of the titles using `jq`.
For example:
I want to run:
unescape_html "– Flexibility"
unescape_html "– Pronouns"
The expected output is:
[
{
"url": "https://drive.google.com/file/d/1tO-qVknlH0PLK9CblQsyd568ZiptdKff/view?usp=share_link",
"title": "– Flexibility"
},
{
"url": "https://drive.google.com/open?id=11_sR8X13lmPcvlT3POfMW3044f3wZdra",
"title": "– Pronouns"
}
]
**Update 1:**
If `jq` doesn't have that feature, then i am also fine that the command is applied on `rg`.
I mean, can i run `unescape_html` on `$2` on the line:
rg -o '<li>.*?href="(.*?)".*?</a> (.*?)<\/li>' -r '{"url": "$1", "title": "$2"}'
Any other bash approach to solve this problem is also fine. The point is, i need to run `unescape_html` on `title`, so that i get the expected output.
**Update 2:**
The following command:
curl -Lfs "https://motivatedsisters.com/2019/07/08/arabic-review-sr-rahat-basit/" | rg -o '<li>.*?href="(.*?)".*?</a> (.*?)<\/li>' -r '{"url": "$1", "title": "$2"}' | jq -s '.' | jq 'map(.title |= @sh "unescape_html \(.)")'
gives:
[
{
"url": "https://drive.google.com/file/d/1tO-qVknlH0PLK9CblQsyd568ZiptdKff/view?usp=share_link",
"title": "unescape_html '– Flexibility'"
},
{
"url": "https://drive.google.com/open?id=11_sR8X13lmPcvlT3POfMW3044f3wZdra",
"title": "unescape_html '– Pronouns'"
}
]
Just not evaluating the commands.
The following command works:
curl -Lfs "https://motivatedsisters.com/2019/07/08/arabic-review-sr-rahat-basit/" | rg -o '<li>.*?href="(.*?)".*?</a> (.*?)<\/li>' -r '{"url": "$1", "title": "$2"}' | jq -s '.' | jq 'map(.title |= sub("–"; "–"))'
But it only works for `–`. It will not work for other reserved characters.
**Update 3:**
The following command:
curl -Lfs "https://motivatedsisters.com/2019/07/08/arabic-review-sr-rahat-basit/" | rg -o '<li>.*?href="(.*?)".*?</a> (.*?)<\/li>' -r '{"url": "$1", "title": "$2"}' | jq -s '.' | jq -r '.[] | "unescape_html \(.title | @sh)"' | bash
is giving:
– Flexibility
– Pronouns
So, it is applying the bash function. Now I need to format is so that the urls are come with the title in json format. |
Since i updated 2FA in order to put trusted device, i have this error after the log in and security code entered:
**Key provided is shorter than 256 bits, only 64 bits provided**
What i do ? i update my User.php to add :
/**
* @ORM\Column(type="integer")
*/
private int $trustedVersion;
...
public function getTrustedTokenVersion(): int
{
return $this->trustedVersion;
}
I update my database to put the new column trusted_version and update security.yaml in order to use **scheb/2fa-trusted-device**
I don't think the problem is about 2fa-trusted-device but i'm a begginer with symfony and i don't find the solution about the problem. Do you have any idea ?
Thanks
Regards |
I am working on a project in the Node.js environment that via dbus-native interfaces with Connman. What I need to do is create some code that allows it to connect to a secure wifi network. I went to implement the Agent and the RequestInput function and from another file I go to call the Connect(), but once it is called it goes the loop and won't connect. I pass the passphrase statically from the code. Has anyone done something similar before?
Agent implementation:
```
const dbus = require('dbus-native');
const systemBus = dbus.systemBus();
const passphrase = '123passwordExample';
const agent = {
Release: function() {
console.log('Agent released');
},
ReportError: function(path, error){
console.log('Agent error reported: ', path, error);
},
RequestBrowser: function(path){
console.log('Agent requests browser:', path);
},
RequestInput: function(path, fields, callback){
console.log('Agent requests input:', path, fields);
let response = {};
console.log('fields[0][0]:', fields[0][0]);
console.log('Ingresso if...');
console.log(fields[0][0].toString() === 'Passphrase');
if(fields[0][0].toString() === 'Passphrase'){
console.log(fields[0]);
response["Passphrase"] = passphrase;
console.log(response);
callback(response);
}
else{
console.log('If scartato');
callback({});
}
//return response;
},
Cancel: function(){
console.log('Agent cancelled');
}
};
systemBus.exportInterface(agent, '/net/connman/Agent', {
name: 'net.connman.Agent',
methods: agent,
signals: {},
properties: {}
});
const managerService = systemBus.getService('net.connman');
managerService.getInterface('/', 'net.connman.Manager', (err, manager) => {
if(err){
console.log('Error getting manager interfce:', err);
return;
}
manager.RegisterAgent('/net/connman/Agent', function(err){
if(err){
console.log('Error registering agent:', err);
}
else{
console.log('Agent registered');
}
});
});
```
Connect() call:
```
const dbus = require('dbus-native');
const systemBus = dbus.systemBus();
const wifiService = systemBus.getService('net.connman');
async function wifiConnect(){
try{
const wifiProps = await new Promise((resolve, reject) => {
wifiService.getInterface('/net/connman/service/wifi_ssid12345', 'net.connman.Service', (err, wifiProps) => {
if(err){
console.log('Error getting wifi service interface:',err);
reject(err);
return;
}
resolve(wifiProps);
});
});
const props = await new Promise((resolve, reject) => {
wifiProps.GetProperties((err, props) => {
if(err){
console.log('Error getting properties:', err);
reject(err);
return;
}
resolve(props);
});
});
const state = props[2][1][1][0].toString();
console.log(state);
if(state === 'idle'){
await new Promise((resolve, reject) => {
wifiProps.Connect(err => {
if(err){
console.log('Error connecting to wifi', err); reject(err);
return;
}
resolve();
});
});
return 'Connected';
}
else{
throw new Error('Already connect');
}
}
catch(error){
throw error;
}
}
wifiConnect()
.then(result => console.log(result))
.catch(error => console.error(error));
```
This is the output error:
```
Error connecting to wifi [ 'Operation timeout' ]
```
|
After some testing I found the superblock of a file system can be accessed from block_device using below cod:
struct super_block *sb = bdev->bd_holder;
I've confirmed this with vfst, ext2,3,4, xfs file systems. |
Make suitable changes as needed
```
import psycopg2
def create_function(sql_query):
try:
# Connect to your PostgreSQL database
conn = psycopg2.connect(
dbname="your_database",
user="your_username",
password="your_password",
host="your_host",
port="your_port"
)
# Create a cursor object
cur = conn.cursor()
# Execute the SQL query to create the function
cur.execute(sql_query)
# Commit the transaction
conn.commit()
# Close the cursor and connection
cur.close()
conn.close()
print("Function created successfully")
except psycopg2.Error as e:
print("Error:", e)
# Example usage: Define the SQL query for the function
sql_query = """
Select * from customers", "your_database","your_user","your_password","your_host","your_port
"""
# Call the function to create the function
create_function(sql_query)
``` |
I try to use Symfony/Messenger with a web service. I don't understand why the queue don't retry 3 times when I have a critical error.
This is my messenger configuration:
framework:
messenger:
# Uncomment this (and the failed transport below) to send failed messages to this transport for later handling.
# failure_transport: failed
transports:
# https://symfony.com/doc/current/messenger.html#transport-configuration
# async: '%env(MESSENGER_TRANSPORT_DSN)%'
# failed: 'doctrine://default?queue_name=failed'
# sync: 'sync://'
async_sms:
dsn: 'doctrine://default?auto_setup=0&table_name=ec2_messenger_messages'
options:
queue_name: 'async_sms'
retry_strategy:
max_retries: 3
delay: 30000
multiplier: 2
max_delay: 0
routing:
# Route your messages to the transports
# 'App\Message\YourMessage': async
'App\Message\Sms': async_sms
Basically, I have define the default configuration to force to retry when it fails.
This is my Message object (very basic implementation) :
namespace App\Message;
class Sms
{
/**
* @param string $content
* @param int $addresseeId
* @param int $companyDivisionId
*/
public function __construct(
private string $content,
private int $addresseeId,
private int $companyDivisionId
)
{}
/**
* @return string
*/
public function getContent(): string
{
return $this->content;
}
/**
* @return int
*/
public function getAddresseeId(): int
{
return $this->addresseeId;
}
/**
* @return int
*/
public function getCompanyDivisionId(): int
{
return $this->companyDivisionId;
}
}
This is my MessageHandler (call the manager which use the web service & Doctrine service):
class SmsHandler
{
/**
* @param UserRepository $userRepository
* @param CompanyDivisionRepository $companyDivisionRepository
* @param OvhClientManager $ovhClientManager
*/
public function __construct(
private UserRepository $userRepository,
private CompanyDivisionRepository $companyDivisionRepository,
private OvhClientManager $ovhClientManager
) {}
/**
* @param Sms $sms
* @return void
*/
public function __invoke(Sms $sms): void
{
$user = $this->userRepository->findOneBy(['id' => $sms->getAddresseeId()]);
$companyDivision = $this->companyDivisionRepository->findOneBy(['id' => $sms->getCompanyDivisionId()]);
$this->ovhClientManager->sendSms($sms->getContent(), $user, $companyDivision);
}
}
Do you have an explanation about this problem ? |
Symfony - Key provided is shorter than 256 bits, only 64 bits provided |
|php|symfony|base64|symfony5|symfony5.4| |
{"OriginalQuestionIds":[10526995],"Voters":[{"Id":3959875,"DisplayName":"wOxxOm","BindingReason":{"GoldTagBadge":"google-chrome-extension"}}]} |
You can define the event handler within your initialization. For example, with your code:
<!-- begin snippet: js hide: true console: true babel: false -->
<!-- language: lang-js -->
var mySwiper = new Swiper('.swiper-container', {
loop: true,
slidesPerView: 1,
autoplay: {
delay: 5000,
},
effect: 'fade',
fadeEffect: {
crossFade: true
},
pagination: {
el: '.swiper-pagination',
clickable: 'true',
type: 'bullets',
renderBullet: function (index, className) {
return '<span class="' + className + '">' + '<i class="progress-bar-bg"></i>' + '<b class="progress-bar-cover"></b>' + '</span>';
},
},
/* this is new */
on: {
'slideChange': function() {
const previousIndex = this.previousIndex;
//const currentIndex = this.activeIndex;
const bullets = document.querySelectorAll('.swiper-pagination-bullet');
if(bullets && bullets.length > 0) {
bullets[previousIndex].classList.add("visited");
}
}
}
/* */
})
<!-- language: lang-css -->
:root {
--swiper-pagination-bullet-border-radius: 0;
--swiper-pagination-bullet-width: 40px;
--swiper-pagination-bullet-height: 2px;
}
body {
font-family: Helvetica;
color: #000;
}
.swiper-container {
width: 100%; height: 100vh;
}
.swiper-wrapper {
width: 100%; height: 100%;
}
.swiper-slide {
font-size: 100px; text-align: center;
line-height:100vh;
}
.swiper-pagination-bullet {
position: relative;
height: auto;
opacity: 1;
margin-right: 20px;
background-color: transparent;
.progress-bar-bg {
position: absolute;
bottom: 0;
left: 0;
z-index: 1;
width: 100%;
height: 2px;
background-color: #DDD;
}
.progress-bar-cover {
position: absolute;
bottom: 0;
left: 0;
z-index: 2;
width: 0%;
height: 2px;
background-color: #000;
}
}
.swiper-pagination-bullet-active {
background-color: transparent;
b {
animation-name: countingBar;
animation-duration: 3s;
animation-timing-function: ease-in;
animation-iteration-count: 1;
animation-direction: alternate ;
animation-fill-mode:forwards;
}
}
@keyframes countingBar {
0% {width: 0;}
100% {width:100%;}
}
/* this is new */
.swiper-pagination-bullet.visited > i {
background-color: #000;
}
/* */
<!-- language: lang-html -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
<!-- Slider main container -->
<div class="swiper-container">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
<!-- Slides -->
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
...
</div>
<!-- If we need pagination -->
<div class="swiper-pagination"></div>
</div>
<!-- end snippet -->
---
First, I used this CSS to mark the visited slides:
```
.swiper-pagination-bullet.visited > i {
background-color: #DDD;
}
```
Next, I added an event handler to do something once the slide changes:
```
var mySwiper = new Swiper('.swiper-container', {
/* ... other options ... */
on: {
'slideChange': function() {
const previousIndex = this.previousIndex;
// const currentIndex = this.activeIndex;
const bullets = document.querySelectorAll('.swiper-pagination-bullet');
if(bullets && bullets.length > 0) {
bullets[previousIndex].classList.add("visited");
}
}
}
})
```
From the official documentation regarding [`slideChange` event](https://swiperjs.com/types/interfaces/types_swiper_events.SwiperEvents#slideChange):
> Event will be fired when currently active slide is changed
which is what we want. The good thing about this is that we can capture both the previous slide, and the newly activated slide (btw, we don't need this right now, but I left it in the comments in case you need to use it for something else later on), or, rather, we can capture their *indices*.
Since we can know what the previous slide was, and since the number of the bullets matches the number of the slides, we can query the DOM for the bullets, and change the background for the one whose index matches the index of our previous slide. |
Although it's difficult to describe, there's a really good explanation in this YouTube video.
https://youtu.be/T6IvImk66m8?si=N1D0IA2Irx9-_CyX |
```
INCLUDE Irvine32.inc
INCLUDELIB Irvine32.lib
INCLUDELIB kernel32.lib
INCLUDELIB user32.lib
.data
A SBYTE 10d ; A is an 8-bit signed integer
B SBYTE 2d ; B is an 8-bit signed integer
cc SBYTE 20d ; C is an 8-bit signed integer
D SBYTE 5d ; D is an 8-bit signed integer
.code
main PROC
mov EAX, 0
mov EDX, 0
mov al, A ; Load A into AL register
imul B
movsx bx, cc
imul bx
movsx bx, D
imul bx
call DumpRegs ;
exit
main ENDP
END main
```
I have this code and I want to modify it to print output for this (A % B) % (C % D) but when I use `idiv` the code doesn't give any outputs. |