instruction stringlengths 0 30k ⌀ |
|---|
try and run
npm install -g yarn
then
yarn --version
If the above version command is not running, locate yarn.ps1 and delete it, if you are under Windows it should be located here:
C:\Users\<username>\AppData\Roaming\npm |
How can I iterate over rows in a Pandas DataFrame? |
On error view, Change Show issues generated to "Build Only"
[![Change Show issues generated][1]][1]
[1]: https://i.stack.imgur.com/lxheB.jpg |
I am using a datadog terraform to write alert monitors.
The query is:
```
sum(last_30m):sum:my_metric.count{field_1:val_1 AND field_2:val_2 AND field_3:val_3} by {field_1}.as_count() > 100
```
Now My target is to run this query for 3 day ago. Lets say current datetime is 5-March-2024_10:00AM, so this query will give me the result for the timeperiod of 5-March-2024_09:30AM to 5-March-2024_10:00AM.\
Now my target is to write a query which will give me data for 2-March-2024_09:30AM to 2-March-2024_10:00AM (i.e. 3 day ago). \
Is there something like timeshift in datadog terraform query?
I have seen timeshift in datadog but while using it in terraform ,it is not working. |
Datadog Terraform Timeshift Query |
|datadog|terraform-provider-datadog| |
null |
i'm facing some issues with my clone app. now i'm trying to create a clone messenger app. the problem is when user successful log in to the app, the main screen didn't show up as i expected how it look like when i run simulator on that view. Is there anyone can help me out with this ?
i was create a log in view and a messages view which is showing all user chat. this messages view is also include a side menu view too and i have succeeded to make the animation for it. i also import the search bar on messages view too. but the problem is when user log in successfully, the search bar didn't show up and the side menu has overlay to the navigation bar like the first image[](https://i.stack.imgur.com/ktUsW.png) which is far from what i expected like the second image [](https://i.stack.imgur.com/finBK.png).
i have used NavigationLink in order to navigate from login view to messages views. when i ran the simulator on the messages view, the view've shown up as i expected ( the navigation bar didn't overlay the side menu view and the search bar showed up when the messages view loaded. but when i run the app or try to run the simulator from the login view, when i click the button log in which is a navigation link, i've moved to the messages view but it didn't show the search bar from the beginning and the navigation bar was overlay the side menu view. how can i fix that ?
```
struct LoginView: View {
var body: some View {
NavigationStack {
...
//MARK: Log in button
NavigationLink {
MessagesView()
//.navigationBarBackButtonHidden()
} label: {
Text("log in")
.textCase(.uppercase)
.font(.headline)
.foregroundStyle(Color(.white))
.frame(width: UIScreen.main.bounds.width - 32, height: 48)
}
.background(Color(.systemBlue))
.clipShape(.buttonBorder)
}
...
}
}
}
```
and here is the code for messages view
```
struct MessagesView: View {
@State var showSideMenu: Bool = false
@State var searchText = ""
@State var offset: CGFloat = 0
@State var lastStoredOffset: CGFloat = 0
@GestureState var gestureOffset: CGFloat = 0
let names = ["Holly", "Josh", "Rhonda", "Ted","1", "2", "3", "4","5", "6", "7", "8"]
var body: some View {
let sideWidth = getRect().width - 90
//MARK: Bar title and searchbar
HStack(spacing: 0) {
SideMenuView(showSideMenu: $showSideMenu)
NavigationStack {
VStack {
ScrollView {
ForEach(searchResults, id: \.self) { name in
NavigationLink {
ChatView()
.navigationBarBackButtonHidden()
} label: {
ChatLogView()
.padding(.horizontal)
}
}
}
}
.navigationTitle("PMe!")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItemGroup(placement: .topBarLeading) {
Button {
withAnimation{showSideMenu.toggle()}
} label: {
Image(systemName: "line.3.horizontal")
.font(.title2)
.fontWeight(.bold)
}
}
ToolbarItemGroup(placement: .topBarTrailing) {
NavigationLink {
NewChatView()
.navigationBarBackButtonHidden()
} label: {
Image(systemName: "square.and.pencil")
.font(.title2)
.fontWeight(.bold)
}
}
}
.overlay(
Rectangle()
.fill(
Color.primary.opacity(Double(offset / sideWidth) / 5)
)
.ignoresSafeArea(.container, edges: .vertical)
.onTapGesture {
withAnimation {
showSideMenu.toggle()
}
}
)
.searchable(text: $searchText, placement : .navigationBarDrawer(displayMode: .automatic))
}
.frame(width: getRect().width)
}
.frame(width: getRect().width + sideWidth)
.offset(x: -sideWidth / 2)
.offset(x: offset > 0 ? offset : 0)
.gesture(
DragGesture()
.updating($gestureOffset, body: { value, out, _ in
out = value.translation.width
})
.onEnded(onEnd(value: ))
)
.navigationBarBackButtonHidden()
.navigationBarTitleDisplayMode(.inline)
.animation(.easeInOut, value: offset == 0)
.onChange(of: showSideMenu) {
if showSideMenu && offset == 0 {
offset = sideWidth
lastStoredOffset = offset
}
if !showSideMenu && offset == sideWidth {
offset = 0
lastStoredOffset = 0
}
}
.onChange(of: gestureOffset) {
onChange()
}
var searchResults: [String] {
if searchText.isEmpty {
return names
} else {
return names.filter { $0.contains(searchText) }
}
}
}
func onEnd(value: DragGesture.Value) {
let sideWidth = getRect().width - 90
let translation = value.translation.width
withAnimation {
if translation > 0 {
if translation > (sideWidth / 2) {
offset = sideWidth
showSideMenu = true
}
else {
if offset == sideWidth {
return
}
offset = 0
showSideMenu = false
}
} else {
if -translation > (sideWidth / 2) {
offset = 0
showSideMenu = false
} else {
if offset == 0 || !showSideMenu {
return
}
offset = sideWidth
showSideMenu = true
}
}
}
lastStoredOffset = offset
}
func onChange() {
let sideWidth = getRect().width - 90
offset = (gestureOffset != 0) ? (gestureOffset + lastStoredOffset < sideWidth ? gestureOffset + lastStoredOffset : offset) : offset
}
}
```
|
The [handle class](https://www.mathworks.com/help/matlab/handle-classes.html) and its copy-by-reference behavior is the natural way to implement linkage in Matlab.
It is, however, possible to implement a linked list in Matlab without OOP. And an abstract list which does *not* splice an existing array in the middle to insert a new element -- as complained in [this comment](https://stackoverflow.com/questions/1413860/matlab-linked-list#comment23877880_1422443).
(Although I do have to use a Matlab data type somehow, and adding new element to an existing Matlab array requires memory allocation somewhere.)
The reason of this availability is that we can model linkage in ways other than pointer/reference. The reason is *not* [closure](https://en.wikipedia.org/wiki/Closure_(computer_programming)) with [nested functions](https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html).
I will nevertheless use closure to encapsulate a few *persistent* variables. At the end, I will include an example to show that closure alone confers no linkage. And so [this answer](https://stackoverflow.com/a/1421186/3181104) as written is incorrect.
At the end of the day, linked list in Matlab is only an academic exercise. Matlab, aside from aforementioned handler class and classes inheriting from it (called subclasses in Matlab), is purely copy-by-value. Matlab will optimize and automate how copying works under the hood. It will avoid deep copy whenever it can. That is probably the better take-away for OP's question.
The absence of reference in its core functionality is also why linked list is not obvious to make in Matlab.
-------------
##### Example Matlab linked list:
```lang-matlab
function headNode = makeLinkedList(value)
% value is the value of the initial node
% for simplicity, we will require initial node; and won't implement insert before head node
% for the purpose of this example, we accommodate only double as value
% we will also limit max list size to 2^31-1 as opposed to the usual 2^48 in Matlab vectors
m_id2ind=containers.Map('KeyType','int32','ValueType','int32'); % pre R2022b, faster to split than to array value
m_idNext=containers.Map('KeyType','int32','ValueType','int32');
%if exist('value','var') && ~isempty(value)
m_data=value; % stores value for all nodes
m_id2ind(1)=1;
m_idNext(1)=0; % 0 denotes no next node
m_id=1; % id of head node
m_endId=1;
%else
% m_data=double.empty;
% % not implemented
%end
headNode = struct('value',value,... % note: this field is for convenince; but is access only
'get',@getValue,...
'set',@set,...
'next',@next,...
'head',struct.empty,...
'push_back',@addEnd,...
'addAfter',@addAfter,...
'deleteAt',@deleteAt,...
'nodeById',@makeNode,...
'id',m_id);
function value=getValue(node)
if isempty(node)
warning("Node is empty.")
value=double.empty;
else
value=id2val(node.id.);
end
end
function set(node,val)
if isempty(node)
warning("Node is empty.")
else
m_data(m_id2ind(node.id))=val;
end
end
function nextNode=next(node)
if m_idNext(node.id)==0
warning('There is no next node.')
nextNode=struct.empty;
else
nextNode=makeNode(m_idNext(node.id));
end
end
function node=makeNode(id)
if isKey(m_id2ind,id)
node=struct('value',id2val(id),... % note: this field is for convenince; but is access only
'get',@getValue,...
'set',@set,...
'next',@next,...
'head',headNode,...
'push_back',@addEnd,...
'addAfter',@addAfter,...
'deleteAt',@deleteAt,...
'nodeById',@makeNode,...
'id',id);
else
warning('No such node!')
node=struct.empty;
end
end
function temp=id2val(id)
temp=m_data(m_id2ind(id));
end
function addEnd(value)
addAfter(value,m_endId);
end
function addAfter(value,id)
m_data(end+1)=value;
temp=numel(m_data);% new id will be new list length
if (id==m_endId)
m_idNext(temp)=0;
else
m_idNext(temp)=temp+1;
end
m_id2ind(temp)=temp;
m_idNext(id)=temp;
m_endId=temp;
end
function deleteAt(id)
%delete to free memory does not make sense with the chosen data type. But can work if m_data had been a cell array by setting a particular element empty
end
end
```
With the above .m file, the following runs:
```lang-matlab
>> clear all % remember to clear all before making new lists
>> headNode = makeLinkedList(1);
>> node2=headNode.next(headNode);
Warning: There is no next node.
> In makeLinkedList/next (line 33)
>> headNode.push_back(2);
>> headNode.push_back(3);
>> node2=headNode.next(headNode);
>> node3=node2.next(node2);
>> node3=node3.next(node3);
Warning: There is no next node.
> In makeLinkedList/next (line 33)
>> node0=node2.head;
>> node2=node0.next(node0);
>> node2.value
ans =
2
>> node3=node2.next(node2);
>> node3.value
ans =
3
>> node2.set(node2,222);
>> nodeNot4=headNode.next(headNode);
>> nodeNot4.value
ans =
222
>> node2.set(node2,2222);
>> nodeNot4.get(nodeNot4)
ans =
2222
```
No
`.next()`, `.get()`, `.set()` etc in the above can take any valid node
`struct` as input -- not limited to itself. Similarly, `.push_back()` etc can be done from any node. But what relative node to get next node or value from etc needs to be passed manually in because a non-OOP [`struct`](https://www.mathworks.com/help/matlab/ref/struct.html) in Matlab cannot reference itself implicitly and automatically. It does not have a `this` pointer or `self` reference.
In the above example, nodes are given unique IDs, a dictionary is used to map ID to data (index) and to map ID to next ID. (With pre-R2022 `containers.Map()`, it's more efficient to have 2 dictionaries even though we have the same key and same value type across the two.) So when inserting new node, we simply need to update the relevant next ID. (Double) array was chosen to store the node values (which are doubles) and that is the data type Matlab is designed to work with and be efficient at. As long as no new allocation is required to append an element, insertion is constant time. Matlab automates the management of memory allocation. Since we are not doing array operations on the underlying array, Matlab is unlikely to take extra step to make copies of new contiguous arrays every time there is a resize. [Cell array](https://www.mathworks.com/help/matlab/ref/cell.html) may incur less re-allocation but with some trade-offs.
Since [dictionary](https://www.mathworks.com/help/matlab/ref/dictionary.html) is used, I am not sure if this solution qualifies as purely [functional](https://en.wikipedia.org/wiki/Functional_programming).
------------
##### re: closure vs linkage
In short, closure does not confer linkage. Matlab's nested functions have access to variables in parent functions directly -- as long as they are not shadowed by local variables of the same names. But there is no variable passing. And thus there is no pass-by-reference. And thus we can't model linkage with this non-existent referencing.
I did take advantage of closure above to make a few variables persistent and shared, since scope (called [workspace](https://www.mathworks.com/help/matlab/matlab_prog/base-and-function-workspaces.html) in Matlab) being referred to means all variables in the scope will persist. That said, Matlab also has a [persistent](https://www.mathworks.com/help/matlab/ref/persistent.html) specifier. Closure is not the only way.
To showcase this distinction, the example below will not work because every time there is passing of `previousNode`, `nextNode`, they are passed-by-value. There is no way to access the original `struct` across function boundaries. And thus, even with nested function and closure, there is no linkage!
```lang-matlab
function newNode = SOtest01(value,previousNode,nextNode)
if ~exist('previousNode','var') || isempty(previousNode)
i_prev=m_prev();
else
i_prev=previousNode;
end
if ~exist('nextNode','var') || isempty(nextNode)
i_next=m_next();
else
i_next=nextNode;
end
newNode=struct('value',m_value(),...
'prev',i_prev,...
'next',i_next);
function out=m_value
out=value;
end
function out=m_prev
out=previousNode;
end
function out=m_next
out=nextNode;
end
end
```
```lang-matlab
>> newNode=SOtest01(1,[],[]);
>> newNode2=SOtest01(2,newNode,[]);
>> newNode2.prev.value=2;
>> newNode.value
ans =
1
```
But we tried to set prev node of node 2 to be have value 2! |
I agree with @David Browne
You can try the below query:
In Databricks SQL, you can use the REGEXP function to find all the records where a column has characters other than alphanumeric.
**1st syntax:**
%sql
SELECT *
FROM part_details
WHERE NOT part_number rlike '^[a-zA-Z0-9]+$';
**2nd syntax:**
%sql
SELECT *
FROM part_details
WHERE part_number REGEXP '[^a-zA-Z0-9]'
This query uses the `REGEXP` function with a regular expression pattern **[^a-zA-Z0-9]** to match any character that is not alphanumeric.
***Note: that the regular expression pattern **[^a-zA-Z0-9]** matches any character that is not an uppercase letter, lowercase letter, or a digit.***
**Results:**
```
id part_number
4 JKL!012
``` |
null |
Need to get a number using only one loop for and `charCodeAt()`
We can't use native methods and concatenations, parseInt, parseFloat, Number, +str, 1 * str, 1 / str, 0 + str, etcc
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const text = "In this market I lost 0,0000695 USDT, today is not my day";
const getAmount = (str) => {
const zero = "0".charCodeAt(0);
const nine = "9".charCodeAt(0);
const coma = ",".charCodeAt(0);
let num = 0,
factor = 1;
for (let i = str.length - 1; i >= 0; i--) {
const char = str.charCodeAt(i);
if (char >= zero && char <= nine) {
num += (char - 48) * factor;
factor *= 10;
}
}
return num;
};
console.log(getAmount(text));
<!-- end snippet -->
Need result: `0,0000695`
My current result is `695`
Tell me how to correct the formula for writing zeros |
|pine-script|pine-script-v5| |
I am following the examples online when trying to select elements of that array but something very weird happens.
When I run
```.issuesData.issues[] ``` it displays the array as expected. Fine.
Then I try to select only the nodes with `statusId == 10270`. this would give me, as expected result, just the last node.
But the result is the array of the 2 objects having all elements assigned with `statusId = 10270`.
```.issuesData.issues[].statusId="10270" ```
If I try a slightly different approach like that
```.issuesData.issues[].statusId=="10270" ```
I get an array
```
false
true
```
and this makes sense because only the second elements fits he criteria. But what I am trying to get is just the element itself or at least the "key"
The JSON object is like below.
```
{
"issuesData": {
"issues": [
{
"id": 3619364,
"key": "AIG-1992",
"hidden": false,
"typeId": "1",
"summary": "XXXXXX",
"priorityId": "2",
"done": false,
"assignee": "XXXX",
"assigneeName": "XXXX",
"hasCustomUserAvatar": false,
"autoUserAvatar": {
"letter": "B",
"color": "#d39c3f"
},
"color": "#ff0000",
"epicId": "3557134",
"epic": "AIG-1",
"estimateStatisticRequired": false,
"statusId": "10370",
"fixVersions": [
120044
],
"projectId": 49202
},
{
"id": 3617950,
"key": "AIG-1938",
"hidden": false,
"typeId": "1",
"summary": "YYYYYY",
"priorityId": "2",
"done": false,
"assignee": "YYYY",
"assigneeName": "YYY",
"hasCustomUserAvatar": false,
"autoUserAvatar": {
"letter": "F",
"color": "#7bc1a1"
},
"color": "#ff0000",
"epicId": "3658470",
"epic": "AIG-574",
"estimateStatisticRequired": false,
"statusId": "10270",
"fixVersions": [],
"projectId": 49202
}
]
}
}
```
What I am doing wrong here? |
There Some doubts about used RDBMS.
I will offer a solution without using regexp.
```
select id,words
,string_agg(w,'-' order by rn) newWords
from(
select *
,row_number()over(partition by id order by (select null)) rn
,count(*)over(partition by id order by (select null)) cnt
from(select *,string_to_table(words,'-') w from test )t
)t2
where rn>3 and rn<=(cnt-2)
group by id,words
```
Output is
|id| words| newwords|
|-:|:-----------------|:-----------|
|1| GLOBE-WORLD-AIRPORT-Azerbaijan-country-SECRET-ABORT| Azerbaijan-country|
|2| GLOBE-WORLD-AIRPORT-Azerbaijan-country-SECRET| Azerbaijan|
from test data
|id| words|
|-:|:---------|
|1| GLOBE-WORLD-AIRPORT-Azerbaijan-country-SECRET-ABORT|
|2| GLOBE-WORLD-AIRPORT-Azerbaijan-country-SECRET|
|3| GLOBE-WORLD-AIRPORT-Azerbaijan-country|
|4| GLOBE-WORLD-AIRPORT-Azerbaijan|
|5| GLOBE-WORLD-AIRPORT|
|6| GLOBE-WORLD|
string_to_table actual from postgresql 14. |
## Function to reset all data fields to their initial values
```javascript
function resetAll() {
// Set data fields to their initial values
setData({
name: "", // Reset name field to empty string
email: "", // Reset email field to empty string
password: "", // Reset password field to empty string
about: "", // Reset about field to empty string
});
}
```
### And here's the button component calling the resetAll function:
```html
<button onClick={resetAll}>
Reset
</button>
``` |
|javascript|regex|validation| |
null |
|php|mysql|oop|pdo| |
You can create a client component importing and initializing `@axe-core/react` and include this component in your root layout file.
This is how I implemented the component `Axe.tsx`:
```tsx
'use client';
import React from 'react';
const Axe: React.FC = () => {
if (typeof window !== 'undefined' && process.env.NODE_ENV !== 'production') {
Promise.all([import('@axe-core/react'), import('react-dom')]).then(
([axe, ReactDOM]) => axe.default(React, ReactDOM, 1000)
);
}
return null;
};
export default Axe;
```
Then simply use `Axe` component in your main `app/layout.tsx` file:
```tsx
import React from 'react';
import Axe from '@/components/a11y/Axe';
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html>
<body>
<Axe />
{children}
</html>
);
}
``` |
I'm using vscode on a very large python project (more than 100K files).
pylance server keeps crashing on OOM.
Only thing that helps is limiting the number of indexed files.
I've traced the issue to "Code Helper (Plugin)" process of vscode that cannot go above 4GB.
I saw many posts about v8 pointer compression limiting memory to 4GB and that is the cause of this issue.
1. Can the memory usage of indexing be reduced to fit in the 4GB limit? I still want to index all files and unfortunately there are no directories that can be excluded.
2. If not, I saw some post describing the option to have viscose use external node which is compiled without v8 pointer compression. Can someone point me to explanation on how to accomplish that?
I've searched for an answer to this for quite some time and there is a lot of confusing info. Sorry if this has been asked/answered before. |
vscode pylance memory limit |
|node.js|visual-studio-code|electron| |
I wanna use the pretrained model in the zoo
but when I want to make a new environment like:env = gym.make('LunarLander-v2')
I
```
Intel MKL WARNING: Support of Intel(R) Streaming SIMD Extensions 4.2 (Intel(R) SSE4.2) enabled only processors has been deprecated. Intel oneAPI Math Kernel Library 2025.0 will require Intel(R) Advanced Vector Extensions (Intel(R) AVX) instructions.
Intel MKL WARNING: Support of Intel(R) Streaming SIMD Extensions 4.2 (Intel(R) SSE4.2) enabled only processors has been deprecated. Intel oneAPI Math Kernel Library 2025.0 will require Intel(R) Advanced Vector Extensions (Intel(R) AVX) instructions.
Traceback (most recent call last):
File "/Users/tcliang/anaconda3/envs/pytorch/lib/python3.8/site-packages/gym/envs/box2d/bipedal_walker.py", line 14, in <module>
import Box2D
ModuleNotFoundError: No module named 'Box2D'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/tcliang/code/py/graduation/rl-baselines3-zoo/train_try.py", line 10, in <module>
env = gym.make('LunarLander-v2')
File "/Users/tcliang/anaconda3/envs/pytorch/lib/python3.8/site-packages/gym/envs/registration.py", line 581, in make
env_creator = load(spec_.entry_point)
File "/Users/tcliang/anaconda3/envs/pytorch/lib/python3.8/site-packages/gym/envs/registration.py", line 61, in load
mod = importlib.import_module(mod_name)
File "/Users/tcliang/anaconda3/envs/pytorch/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 843, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/tcliang/anaconda3/envs/pytorch/lib/python3.8/site-packages/gym/envs/box2d/__init__.py", line 1, in <module>
from gym.envs.box2d.bipedal_walker import BipedalWalker, BipedalWalkerHardcore
File "/Users/tcliang/anaconda3/envs/pytorch/lib/python3.8/site-packages/gym/envs/box2d/bipedal_walker.py", line 24, in <module>
raise DependencyNotInstalled("box2D is not installed, run `pip install gym[box2d]`")
gym.error.DependencyNotInstalled: box2D is not installed, run `pip install gym[box2d]`
```
solve the problem which in the stable-lines3 |
I have a list of audio tracks of different length. My goal is to use `pydub` to concantenate the audio tracks and make sure that each one of them starts at a give timestamp.
For example:
- track1 starts at 0s and ends after 9s
- track2 starts at 11s and ends after 4s
- track3 starts at 16s and ends after 5s
and so on. Of course the audio track is shorter than the time required for the next audio track to start in order to avoid cuts.
Could you please suggest me a smart and elegant way to do so using the `pydub` library in Python? |
How to concatenate audio tracks and make them start a certain moment using Python? |
|python|audio|pydub| |
I have an issue with the default month calendar control on Windows and Delphi 2007.
By default, my dev environnemet is in French.
I need to translate the texts into Flemish:
- Dutch (Belgium), `nl-BE`, `$0813`
No worries, I use the *“Localizer”* tool and it’s ok.
On the other hand, with the [**TMonthCalendar** component][1], I have the character string *“aujourd'hui”* which is not displayed in Flemish; remaining in French as picture below :

If you already noticed these behaviour, how did you fix the problem?
[1]: https://docwiki.embarcadero.com/Libraries/Alexandria/en/Vcl.ComCtrls.TMonthCalendar |
When I try to convert this code to exe file it runs a cmd window with the title `C:\Windows\system32\cmd.exe`:
```
path = 'supported_languages.txt'
os.system(f'notepad.exe {path}')
```
Here is the code I use for convert it to exe file:
```
pyinstaller --noconfirm --onedir --windowed --icon "[ICON PATH]" "[FILE PATH]"
``` |
When I try to convert this code to exe file it runs a cmd window |
|python|pyinstaller| |
When running `npm run build` my pictures under src/assets/... are not available in the dist directory / production build. So not shown on the site. In dev mode it works for sure.
Any ideas on how to make them available after building?
Also, in my VSCode terminal, i get the the error that
> "GET /src/assets/store2.webp" Error (404): "Not found"
>
> <div className= "Deal-two">
<div className="onah">
<img src="src/assets/Deal-2.webp"
I have attached some screenshots for a better understanding. I even had to configure my vite.config[![screenshot][1]][1]
[![Screenshot2][2]][2]
[1]: https://i.stack.imgur.com/pOSLA.png
[2]: https://i.stack.imgur.com/XAlSm.png |
Assets not showing after build process in Vite and React |
|css|reactjs|build|vite|assets| |
**UPDATE3**: [Clang issue submitted][1] as I am now confident that this is a previously unreported compiler bug. (There are many somewhat similar but distinct issues in the LLVM bug tracker.) Thanks to all who genuinely tried to help.
**UPDATE2**: It turns out this bug does **NOT** require the use of `-n` (`--nmagic`) option. The same crashes occur on binaries just built without using the C library (`-nostdlib` Clang option). So building NMAGIC binaries apparently has nothing to do with the problem.
**UPDATE**: LLVM's own linker, LLD, supports the `-n` (`--nmagic`) option so I installed it and gave it a try. The exact same segfault occurs. Since LLVM's own linker supports building NMAGIC binaries that strongly suggests that that it **should** work when user their compiler (Clang) too. I'll file a bug report.
**Original Post**:
I've come across a C++ issue where instantiating some objects in programs compiled by Clang segfaults. Thanks in advance to anyone who can help shed light on the issue.
Debugging suggests that Clang is generating SSE `movaps` instructions to initialize some char arrays and it's these instructions that appear to cause segfaults in some circumstances.
I've tested on multiple Linux systems with the binutils linker with both Clang 16 and Clang 17 with the same results. I'm not sure if the same problem occurs under other x86-64 operating systems or with other linkers. The problem does **not** occur when using versions of the GCC compiler instead of Clang.
The segfaults occur for some objects under the following minimum set of conditions:
- x86-64 code generation
- Optimization is enabled (-O1 or above)
- [**EDIT** - This was incorrect. The segfaults do **not** require the `-n` (`--nmagic`) linker option. All that's necessary is to build a binary without the standard C library (`-nstdlib` option to Clang). I should also point out here that use of the `-fno-builtin` option makes no difference.]
Here is minimal code to reproduce. Compile with the following on an x86-64 Linux system [**EDIT**: removed unnecessary linker option]:
```
$ clang -O1 -nostdlib -fno-stack-protector -static clang_segv.s clang_segv.cc -o clang_segv
```
clang_segv.cc:
```
struct SegV
{
void set(const char *s) { char *b = buf; while ( *s ) { *b++ = *s++; } *b = '\0'; }
char buf[128] = "";
char *cursor = buf; // needed for segfault
};
int
main()
{
SegV v;
v.set("aa");
return 0;
}
```
clang_segv.s
```
.intel_syntax noprefix
.global _start
_start:
xor rbp,rbp # Zero stack base pointer
xor r9,r9
pop rdi # Pop argc off stack -> rdi for 1st arg to main()
mov rsi,rsp # Argv @top of stack -> rsi for 2nd arg to main()
call main # Call main()... return result ends up in rax
xor r9,r9
mov rdi,rax # Move main()'s return to 1st argument for exit()
mov rax,231 # exit_group() syscall
syscall # Tell kernel to exit program
```
This example is the minimum reproducer I could come up with and has no resemblance to the original code where I noticed the problem save that both have objects with char arrays. Changing the code around can mask or unmask the issue which usually suggests a coding error but I'm at a loss to find one in this simple example.
My debugger seems to think that the problems are the instructions that Clang is generating to initialize the 'buf' char array:
[Image of debugger suggesting issue with movaps instructions](https://i.stack.imgur.com/LuDiX.png).
My Debugger says that Clang generates the following code for the initialization of `char buf[128]`:
```
0x400171 xorps %xmm0,%xmm0
0x400174 movaps %xmm0,-0x10(%rsp)
0x400179 movaps %xmm0,-0x20(%rsp)
0x40017e movaps %xmm0,-0x30(%rsp)
0x400183 movaps %xmm0,-0x40(%rsp)
0x400188 movaps %xmm0,-0x50(%rsp)
0x40018d movaps %xmm0,-0x60(%rsp)
0x400192 movaps %xmm0,-0x70(%rsp)
0x400197 movaps %xmm0,-0x80(%rsp)
0x40019c lea -0x80(%rsp),%rax
```
and that the segfault is generated by the first movapps instruction.
Obviously, I expect that the initialization of the array shouldn't segfault.
It doesn't matter if in-class initialization is used as I do here in this example or if initializer-list initialization is used. Both methods suffer from the same problem.
I believe the problem might be a mismatch in how the code generated by clang **thinks** the members of the object are (should be) aligned versus how the members are **actually** aligned. I might be wrong about that but if I add alignas(32) to the structure or to the char array the problem goes away. I don't know why I'd need to align at 32 bytes. Perplexingly (to me), aligning at 16 bytes does not mask the problem.
The problem also goes away if I just tell Clang not to generate any SSE instructions with `-mno-sse` but I'd rather not lose those optimizations. In this case Clang uses `movq` instructions to initialize the array instead of `movaps`.
The problem also goes away if I forgo initialization of the char array member and do it manually in the constructor but of course that is less efficient.
At this point to me this looks like a compiler bug. Or am I just using it wrong?
Thanks!
[1]: https://github.com/llvm/llvm-project/issues/86895 |
I have a .NET 8 Blazor project using the new Auto rendering mode. I have this page that simply retrieves a forum's data from the `ForumsService`, a gRPC service client, and shows a simple loading screen when the request is being processed:
```html
@page "/Forum/{ForumPermalink}"
@inject ForumsProto.ForumsProtoClient ForumsService
@rendermode InteractiveAuto
<h3>Forum @@ @ForumPermalink</h3>
@if(_forum is not null)
{
<p>@_forum.Name</p>
}
else
{
<Loading/> @* A simple component with only a p tag *@
}
@code {
[Parameter]
public string ForumPermalink { get; init; } = null!;
private ForumReply? _forum;
protected override async Task OnInitializedAsync()
{
try
{
_forum = await ForumsService.GetForumByPermalinkAsync(new()
{
Permalink = ForumPermalink
});
}
catch(RpcException exception)
{
if(exception.StatusCode == StatusCode.NotFound)
{
NotFoundService.NotifyNotFound();
return;
}
throw;
}
}
}
```
The `Loading` component:
```html
<p>Please Wait...</p>
```
As of my knowledge, Blazor Auto render mode also has a feature called "Prerendering", that processes and sends an initial HTML to the client before any interaction starts, to improve the initial page load experience and also be bot-friendly, so Google and other bots can crawl the site.
My problem is simple, it doesn't work properly. When I "View Source" the page, this is what is displayed:
```html
...
<body>
<header>
<--- prerendered correctly -->
</header>
<h3>Forum @ {permalink value is fine}</h3>
<div class="search-overlay" b-5zir38ipii>
...
</div>
<footer b-5zir38ipii>
<--- prerendered correctly -->
</footer>
<script src="/_framework/blazor.web.js"></script>
</body>
</html>
```
Neither the `<p>@_forum.Name</p>`, nor the `<Loading/>` component is even included in the HTML. Again, the page works fine when opened in a normal browser; But I want the forum name (and not even the loading component) to be included in the prerendering so that the site can be indexed as it should.
So my question is, how can I tell the prerenderer to wait for the forum in the `OnInitializedAsync()` method and include the `_forum.Name`, so the page is completely displayed to bots? |
null |
I am trying to send a welcome message when a user adds the bot for the first time in Microsoft Teams. I am unable to do that. These are the steps for adding the bot:
[![][1]][1]
[![][2]][2]
This is what I want the app to do:
[![enter image description here][3]][3]
This is the code I am using:
import { TeamsActivityHandler, TurnContext, ChannelAccount, ActivityTypes } from "botbuilder";
export class TeamsBot extends TeamsActivityHandler {
constructor() {
super();
const card = {
contentType: 'application/vnd.microsoft.card.adaptive',
content: {
type: 'AdaptiveCard',
body: [
{
type: 'TextBlock',
text: 'Thank you for installing me!',
weight: 'bolder',
size: 'medium'
}
]
}
};
// Bind the overridden onMembersAdded method
this.onMembersAdded(this.onMembersAddedActivity.bind(this));
// Bind the overridden onConversationUpdate method
this.onConversationUpdate(this.onConversationUpdateActivity.bind(this));
}
/**
* Overrides the onMembersAdded method from TeamsActivityHandler.
* @param membersAdded List of members added to the conversation.
* @param context The context object for this turn.
*/
protected async onMembersAddedActivity(membersAdded: ChannelAccount[], context: TurnContext): Promise<void> {
await context.sendActivity('Thank you for installing me!');
console.log('onMembersAddedActivity')
// Create a adaptive card and send it to the conversation when the bot is added to the conversation.
const card = {
contentType: 'application/vnd.microsoft.card.adaptive',
content: {
type: 'AdaptiveCard',
body: [
{
type: 'TextBlock',
text: 'Thank you for installing me!',
weight: 'bolder',
size: 'medium'
}
]
}
};
await context.sendActivity({ attachments: [card] });
}
protected async onConversationUpdateActivity(context: TurnContext): Promise<void> {
const card = {
contentType: 'application/vnd.microsoft.card.adaptive',
content: {
type: 'AdaptiveCard',
body: [
{
type: 'TextBlock',
text: 'Thank you for installing me!',
weight: 'bolder',
size: 'medium'
}
]
}
};
await context.sendActivity({ attachments: [card] });
console.log('onConversationUpdateActivity')
if (context.activity.type === ActivityTypes.ConversationUpdate) {
// Check if the bot is the only member added
if (context.activity.membersAdded?.length === 1 && context.activity.membersAdded[0].id === context.activity.recipient.id) {
await context.sendActivity('Thank you for installing me!');
}
}
}
}
Any recommendation on how I can achieve this or anything I am missing here? Thank you.
[1]: https://i.stack.imgur.com/FMbud.png
[2]: https://i.stack.imgur.com/NLus2.png
[3]: https://i.stack.imgur.com/A0DzV.png |
Welcome message Microsoft teams extension |
printing list and variable names in triple nested for loop in R does not behave as expected |
|r|dataframe|list|for-loop|nested| |
I'm in the process of developing an npm package tailored for React, integrating Redux Toolkit within its architecture. Prior to its publication, everything functioned seamlessly. However, subsequent to its release, I've encountered the following error.
`itemSlice.js`
import { createSlice } from "@reduxjs/toolkit";
const itemSlice = createSlice({
name: "item",
initialState: {
item: 10,
page: 1,
},
reducers: {
addItemPerPage: (state, actions) => {
state.item = actions.payload;
state.page = 1;
},
addPage: (state, actions) => {
state.page = actions.payload;
},
},
});
export const { addPage, addItemPerPage } = itemSlice.actions;
export default itemSlice.reducer;
`Store.js`
import { configureStore } from "@reduxjs/toolkit";
import itemReducer from "./slices/itemSlice";
const store = configureStore({
reducer: {
item: itemReducer,
},
});
export default store;
`error`
itemSlice.js:8 Uncaught TypeError: (0 , _toolkit.createSlice) is not a function
at ../npm packages/package-name/lib/Redux/slices/itemSlice.js (itemSlice.js:8:1)
at options.factory (react refresh:6:1)
at __webpack_require__ (bootstrap:22:1)
at fn (hot module replacement:61:1)
at ../npm packages/package-name/lib/components/Component.js (Component.js:11:1)
at options.factory (react refresh:6:1)
at __webpack_require__ (bootstrap:22:1)
at fn (hot module replacement:61:1)
at ../npm packages/package-name/lib/index.js (index.js:18:1)
at options.factory (react refresh:6:1)
|
Uncaught TypeError: (0 , _toolkit.createSlice) is not a function |
|npm|redux|react-redux|redux-toolkit| |
null |
I am currently working on scaffolding a database to make a Data Access Layer.
I found out that I can modify the EFCore default templates (DBContext.t4, EntityType.t4 and EntityTypeConfiguration.t4) to alter the generation
I now want to generate an Interface for each entities, which should simplify the creation of DTO's and the testing, but I cannot find a way to make the command Scaffold-DbContext generate files based on another template (IEntityType.t4).
I tried to create the template and place it in the CodeTemplates/EFCore folder where the others are, hoping that the scaffolding would take every templates in this folder, without success.
I saw some solutions using System.IO and the TextTransformation.GenerationEnvironment Property, where you add the template to an already existing one, then create the file, clear GenerationEnvironment and generate the original, and while it should work, I dont want to depend on this method for each templates I may want to add.
Is there a method or a property I could specify in the Scaffold-DbContext command to make it generate my templates ? |
Using Scaffold-DbContext with Entity FrameworkCore 8.21, how do I add a new t4 template to generate to the default ones? |
when I run the code "env = gym.make('LunarLander-v2')" in stable_baselines3 zoo |
|pytorch|reinforcement-learning| |
null |
Use non-breaking space ` ` HTML character, where you want to avoid braking.
C31C636363-Thermal,80mm, ReStick,Serial,A/C,PSIncluded,EDG |
ERROR Invariant Violation: requireNativeComponent: "RNSScreenStackHeaderConfig" was not found in the UIManager.
This error is located at:
in RNSScreenStackHeaderConfig (created by HeaderConfig)
in HeaderConfig (created by SceneView)
in RNSScreen
in Unknown (created by InnerScreen)
in Suspender (created by Freeze)
in Suspense (created by Freeze)
in Freeze (created by DelayedFreeze)
in DelayedFreeze (created by InnerScreen)
in InnerScreen (created by Screen)
in Screen (created by SceneView)
in SceneView (created by NativeStackViewInner)
in Suspender (created by Freeze)
in Suspense (created by Freeze)
in Freeze (created by DelayedFreeze)
in DelayedFreeze (created by ScreenStack)
in RNSScreenStack (created by ScreenStack)
in ScreenStack (created by NativeStackViewInner)
in NativeStackViewInner (created by NativeStackView)
in RNCSafeAreaProvider (created by SafeAreaProvider)
in SafeAreaProvider (created by SafeAreaProviderCompat)
in SafeAreaProviderCompat (created by NativeStackView)
in NativeStackView (created by NativeStackNavigator)
in PreventRemoveProvider (created by NavigationContent)
in NavigationContent
in Unknown (created by NativeStackNavigator)
in NativeStackNavigator (created by App)
in EnsureSingleNavigator
in BaseNavigationContainer
in ThemeProvider
in NavigationContainerInner (created by App)
in RCTView (created by View)
in View (created by App)
in App
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in Igttaskk(RootComponent), js engine: hermes
resolve this error asap |
Invariant Violation: requireNativeComponent: "RNSScreenStackHeaderConfig" was not found in the UIManager. in react native |
|reactjs|react-native| |
null |
Here is the query, one point here is that this will consume less memory and will be fast as compared to creating duck db tables as given in original question but consume more cpu cores.
COPY(
select
CASE WHEN a.id is NULL THEN b.id ELSE a.id END as id,
CASE WHEN b.id is NOT NULL THEN b.name ELSE a.name END as name,
CASE WHEN b.id is NOT NULL THEN b.city ELSE a.city END as city
from (SELECT * FROM 'main.parquet') a full outer join (SELECT *
FROM 'updates.parquet') b on a.id=b.id
)
TO '/tmp/output.parquet' (FORMAT 'PARQUET', CODEC 'ZSTD');
|
s3://trd-data-lake-landing-zone/fetched_projects/project_65e34c4352faff00017fc8a2/locations/location_65e34c4352faff00017fc835/design_65e34c4352faff00017fc832/analysis_65e34c4352faff00017fc8a3/
look at this file structure. under fetched_projects I see a project_<id> folder which has some files and a folder called locations.under locations folder I have another folder with location<id> which has few folders inside as design<id> which has few more folder as analysis<id> which has some json files in it. If you notice none of these <id>s are same.
```
s3://trd-data-lake-landing-zone/
└── fetched_projects
└── project_<id>
├── files...
└── locations
└── location_<id>
└── design_<id>
└── analysis_<id>
└── json files...
```
at the end of the analysis bucket I get some json files called result_<ids>.json. I want to use only those to run another transformation pipeline which flattens the json structure. how do I tackle this problem dynamically? I am trying this on my local machine.
I tried to get the list of all the ids and then creating one format key like f'{projects_path}project_{project_id}/result_{project_id}.json' but that did not work |
|microsoft-teams|teams-toolkit| |
```
export class TimeSeriesDB {
private static inst: TimeSeriesDB;
public static db: InfluxDB;
public static connected: Promise<boolean>;
constructor() {
const url = Settings.get('INFLUX2_URL');
const token = Settings.get('INFLUX2_TOKEN');
TimeSeriesDB.db = new InfluxDB({
url,
token,
});
}
static async connect() {
return true;
}
static disconnect() {
// delete this.instance.db
}
static get instance(): TimeSeriesDB {
if (this.inst === undefined) {
this.inst = new TimeSeriesDB();
this.connected = this.connect();
}
return this.connected;
}
}
export default TimeSeriesDB.instance
```
`instance` getter function should return `TimeSeriesDB` type but it returns `Promise<boolean>`.
this code works perfectly fine. Can someone tell me what is happening here?
I expected the code above not to be compilable. |
typescript getter function in class returns different type than one specified |
|javascript|typescript| |
null |
I am working on an ASP.NET core web application and I want to get the user idle time. if the user is not working / interacting with the application more than 20 minutes I want to throw a message "User is idle for 20 min".
How do I achieve this? |
How to check for user idle time in C# and display a message |
|c#|asp.net-core|time| |
Keeping your original code as much the same as possible, this should do what you're looking for.
To explain it a little, when sorting, you want to return which direction you want the object to move. 1/-1 shift is left or right, and 0 keeps the order the same. Taking the difference of the indices is not going to produce the desired sorting effect.
```javascript
export function orderDialogNodes(nodes) {
// Create a mapping of dialog_node to its corresponding index in the array
const nodeIndexMap = {};
nodes.forEach((node, index) => {
nodeIndexMap[node.dialog_node] = index;
});
// Sort the array based on the previous_sibling property
nodes.sort((a, b) => {
const indexA = nodeIndexMap[a.previous_sibling];
const indexB = nodeIndexMap[b.previous_sibling];
if (indexA < indexB) {
return 1;
} else if (!indexA || indexA > indexB) {
return -1;
}
return 0;
});
return nodes;
}
const inputArray = [
{
type: "folder",
dialog_node: "node_3_1702794877277",
previous_sibling: "node_2_1702794723026",
}, {
type: "folder",
dialog_node: "node_2_1702794723026",
previous_sibling: "node_9_1702956631016",
},
{
type: "folder",
dialog_node: "node_9_1702956631016",
previous_sibling: "node_7_1702794902054",
},
];
const orderedArray = orderDialogNodes(inputArray);
console.log(orderedArray);
``` |
This worked for me:
```
Sub AppendTxtFiles2()
Dim rootFolder As String, sourceFolder As String, destinationFile As String
Dim fileName As String, lineData As String
Dim outNumber As Integer, inNumber As Integer
Dim isFirstFile As Boolean
' Specify the source folder and destination file
rootFolder = "C:\Temp\VBA\Folder1\"
sourceFolder = rootFolder & "TextFiles\"
destinationFile = rootFolder & "Combined.txt"
'open the output file
outNumber = FreeFile
Open destinationFile For Output As #outNumber
isFirstFile = True
fileName = Dir(sourceFolder & "*.txt") ' Get the first .txt file
While fileName <> ""
inNumber = FreeFile
Open sourceFolder & fileName For Input As #inNumber
Do While Not EOF(inNumber)
Line Input #inNumber, lineData
If isFirstFile Or Not Trim(lineData) Like "Col1|Col2|*" Then
Print #outNumber, lineData
End If
Loop
Close #inNumber
fileName = Dir() ' Get the next .txt file
isFirstFile = False
Wend
Close #outNumber 'close output file
End Sub
``` |
I'm currently looking to migrate from SVN to a Git solution on Bitbucket Cloud.
Actually, to build and deploy the app in our environment, we have a `Deploy.cmd` script that we manually launch on the server. Basically this script triggers some build an deployment of our .NET app. It works since the SVN Server is the same as this server, so it has access directly to the code.
With Git and Bitbucket Cloud, the code is also directly available on this server (git clone and git pull). Now the question is how we can automatize this `Deploy.cmd` call to remove the fact someone has to connect to the server and start the script.
Using Bitbucket Pipeline, I found that you can connect to your server through SSH (https://community.atlassian.com/t5/Bitbucket-questions/Trigger-a-build-on-a-local-machine-for-CI-CD/qaq-p/1675163) but is it the best way ?
The server is an intern server, opening it from the outside would cause some security concerns.
I found ohter alternative, like a script which regularly do a `git push` and when there is something new it triggers `Deploy.cmd` but this isn't really using the benefits of Bitbucket CI/CD.
So I'm asking for you guys experience and ideas on **how to trigger a .cmd script on local server from Bitbucket Cloud Pipeline ?** |
What would be the best way to trigger a .cmd script on a in-house server from a CI/CD Pipeline ? |
|batch-file|bitbucket|pipeline| |
These 2 lines
admin_ie_options.add_argument("--ignore-zoom-setting")
admin_ie_options.add_argument("--ignore-protected-mode-settings")
should be changed into
admin_ie_options.ignore_protected_mode_settings = True
admin_ie_options.ignore_zoom_level = True
because they are not the valid arguments for Microsoft Edge.
=================
If the issue still occurs, you can simply replace the initial start page with your URL:
admin_ie_options.initial_browser_url = 'url'
and `d.get(url)` can be removed in this way. |
I found answer to my question:
git log --format="%H" HEAD --not --remotes
This will give me hashes of all commmits that are on my local branch, but on on remote.
I just need diff between most recent commit and parent of the first commit:
git diff <first_commit>~ <last_commit> --name-only
And this will output list of files that will be pushed to the remote |
Just wondering if the current stable version Cassandra 4.1.4 support Java17?
I am currently using java11 works fine.
I try to change JAVA_HOME to openjdk@17 but get the JavaClassNotFound error when try to run it, also saw apache cassandra website says support java 17, so just wondering if it only support cassandra 5.x. |
Does Cassandra 4.1.4 support Java17? Or only Cassandra 5.x |
|cassandra|cassandra-4.0| |
null |
I have a small code which accepts .txt files and process it and returns statement saying that process completed
Also, another button which on click should show the output folder path.
Strangely this is not working. Here is my code.
```
import streamlit as st
def main():
st.title(":blue[Keyword Replacement] :twisted_rightwards_arrows:")
activity1 = ["Keyword Replacement"]
choice = st.sidebar.selectbox("What do you want to do?",activity1)
if choice == 'Keyword Replacement':
st.subheader("Please upload the file")
uploaded_file = st.file_uploader("Upload file", type={"txt"})
if uploaded_file is not None:
if st.button("Submit"):
st.write("Process completed")
output_path = r"C:\Users\Myname\directory"
if st.button('Show output folder path'):
st.markdown(f"**Outpul folder is located at:** {output_path}") ## NOT WORKING
if __name__ == '__main__':
main()
```
Here is the screenshot of the app, the highlighted yellow button should print the output path after clicking, but nothing happens.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/LoZrM.png
Am I missing something here.
I came across session state but couldn't understand it. Is it because of that I'm not able to get the desired output on clicking the nested button.
Any leads would be helpful |
I'm trying to animate a sine wave made out of a Shape struct. To do this, I need to animate the phase of the wave as a continuous looping animation - and then animate the frequency and strength of the wave based on audio input.
As far as I understand it, the `animatableData` property on the Shape seems unable to handle multiple animation transactions. I've tried using `AnimatablePair` to be able set/get more values than one, but it seems they need to come from the same animation instance (and for my case I need two different instances).
The code goes something like this:
<!-- language: swiftui -->
```
@Binding var externalInput: Double
@State private var phase: Double = 0.0
@State private var strength: Double = 0.0
struct MyView: View {
var body: some View {
MyShape(phase: self.phase, strength: self.strength)
.onAppear {
/// The first animation (that needs to be continuous)
withAnimation(.linear(duration: 1).repeatForever()) {
self.phase = .pi * 2
}
}
.onChange(self.externalInput) {
/// The second animation (that is reactive)
withAnimation(.default) {
self.strength = self.externalInput
}
}
}
}
```
<!-- language: swiftui -->
```
struct MyShape: Shape {
var phase: Double
var strength: Double
var animatableData: AnimatablePair<Double, Double> {
get { .init(phase, strength) }
set {
phase = newValue.first
strength = newValue.second
}
}
/// Drawing the bezier curve that integrates the animated values
func path(in rect: CGRect) -> Path {
...
}
}
```
This approach however seems to only animate the value from the last animation transaction that's been initialised. I am guessing both animated values goes in, but when the second animation transaction fires, it sets the first value to the target value (without any animations) - as those animated values are part of the first transaction (that gets overridden by the second one).
My solution right now is to use an internal `Timer`, in a wrapper View for the Shape struct, to take care of updating the value of the `phase` value - but this is far from optimal, and quite ugly.
When setting the values in `animatableData`, is there a way to access animated values from other transactions - or is there another way to solve this?
I've also tried with implicit animations, but that seems to only render the last set animation as well - and with a lot of other weird things happening (like the whole view zooming across the screen on a repeated loop...). |
I have inherited a ReactNative app, that i need to get up and running in dev.
I am completely a noob.
I think i am close.
When I run
npm run ios
I get the error
> CompileC /Users/me/Library/Developer/Xcode/DerivedData/tpp-cdzrkyfpwzsixefrnjryzmdnucct/Build/Intermediates.noindex/Pods.build/Debug-iphoneos/FlipperKit.build/Objects-normal/arm64/FlipperPlatformWebSocket.o /Users/me/Projects/tpp/ios/Pods/FlipperKit/iOS/FlipperKit/FlipperPlatformWebSocket.mm normal arm64 objective-c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'FlipperKit' from project 'Pods')
After some googling i have added in the project root the file react-native.config.js with the contents
module.exports = {
dependencies: {
...(process.env.CI // or `process.env.NO_FLIPPER` for RN@0.71.x and above
? { 'react-native-flipper': { platforms: { ios: null } } }
: {}),
},
project: {
ios: {},
android: {},
},
};
The last thing the article said i needed to do was
> You can specify NO_FLIPPER=1 when installing your iOS pods, to instruct React Native not to install Flipper. Typically, the command would look like this:
>
>
>
> from the root folder of the react native project
>
> bundle exec pod install --project-directory=ios
This is where i am getting in the weeds.
Where does this command "bundle exec pod install --project-directory=ios" go, since i am running "npm run ios" ?? |
ReactNative App build failing with Flipper error |
|react-native| |
It's not possible to deploy content to a specific path in Firebase Hosting and manage it separately. All of the content for the entire site must be deployed together as a single unit. |
null |
**SOLVED**: In _start the stack is _already_ aligned so by popping 8 bytes off in my startup code I was actually _misaligning_ it before the call to main(). The SysV x86-64 ABI requires the stack be aligned prior to any calls so it is perfectly reasonable for Clang to assume that the stack is aligned a certain way upon entry to main() and to generate code accordingly. In other words: **This is not a bug**. (And, again, it has nothing to do with using the `--nmagic` linker option which is perfectly fine to use.)
|
You can do it manually, we check if our text has doubls stars, if it has, we bold it otherwise we show it like normal texts.
Use below code to bold texts that are covered with 2 stars in beginning and end like ****
import 'package:flutter/material.dart';
// It uses a [RichText] widget to display
a [text] with a [style] and a
// [TextStyle.fontWeight] of [FontWeight.bold] for the bold texts
// The bold texts are the ones between two asterisks, for example:
// "This is a **bold text**"
class BoldableText extends StatelessWidget {
final String text;
final TextStyle? style;
final TextAlign? textAlign;
final bool isSelectable;
const BoldableText(this.text,
{super.key, this.isSelectable = false, this.style, this.textAlign});
@override
Widget build(BuildContext context) {
final List<TextSpan> children = [];
final List<String> split = text.split('**');
for (int i = 0; i < split.length; i++) {
if (i % 2 == 0) {
children.add(TextSpan(text: split[i], style: style));
} else {
children.add(TextSpan(
text: split[i],
style: (style ?? const TextStyle())
.copyWith(fontWeight: FontWeight.bold)));
}
}
if (isSelectable) {
return SelectableText.rich(
TextSpan(children: children),
style: style,
textAlign: textAlign,
);
}
return Text.rich(
TextSpan(children: children),
style: style,
textAlign: textAlign,
);
}
}
**Happy Coding :)** |
|firebase|firebase-hosting| |
null |
Convert your inputs to vectors and then you can do this:
```
## direct replacement
data[data %in% data_to_replace] = replacement[match(data, data_to_replace)]
## or with `ifelse` if you want to save it as a new name
## and keep `data` unmodified
ifelse(data %in% data_to_replace, replacement[match(data, data_to_replace)], data)
``` |
Why are SST-2, CoLA and models trained on both commonly used for measuring bias and subesequent debiasing? Does it correlate with GLUE benchmark being widely accepted and used for research purposes? As SST-2 in particular consists of movie reviews, what is the expected gain from debiasing such data? Would it not be reasonable to debias datasets with more inherent bias (although it is not obvious at first which datasets are biased I assume)?
My current understanding is, that without regard of whether a trained model and or dataset does exhibit biases or not, debiasing is an important step to strive for more fairness. SST-2 and CoLA thereby provide general datasets with a wide range of biases and interface to be researched on.
Someone basically told me, that SST-2 and CoLA does not make sense for debiasing, despite it being used in plenty of papers which made me question it.... |
getting ids from nested bucket structure in s3 |
|amazon-s3|boto3| |
null |
[enter image description here][1]System and OS : Apple Silicon Mac M3, Sonoma OS
Trying to install neo4j with docker and getting below errors:
ERROR Failed to start Neo4j: Starting Neo4j failed: Component 'org.neo4j.server.database.LifecycleManagingDatabase@2b037cfc' was successfully initialized, but failed to start. Please see the attached cause exception "Some jar procedure files are invalid, see log for details."
Attaching a log file for more reference.
I tried googling and found a few solutions for the problem, but none of them worked for me. Can someome please help me out here?
[1]: https://i.stack.imgur.com/WtIf2.jpg |
How to get Notification to admin Using Rest Api |
I am creating MLM (multi-level marketing) system in PHP and MYSQL database. I want to fetch the child user ID based on the parent ID. I have found a solution
https://stackoverflow.com/questions/45444391/how-to-count-members-in-15-level-deep-for-each-level-in-php
but getting errors-
I have created a class -
```
<?php Class Team extends Database {
private $dbConnection;
function __construct($db)
{
$this->dbConnection = $db;
}
public function getDownline($id, $depth=5) {
$stack = array($id);
for($i=1; $i<=$depth; $i++) {
// create an array of levels, each holding an array of child ids for that level
$stack[$i] = $this->getChildren($stack[$i-1]);
}
return $stack;
}
public function countLevel($level) {
// expects an array of child ids
settype($level, 'array');
return sizeof($level);
}
private function getChildren($parent_ids = array()) {
$result = array();
$placeholders = str_repeat('?,', count($parent_ids) - 1). '?';
$sql="select id from users where pid in ($placeholders)";
$stmt=$this->dbConnection->prepare($sql);
$stmt->execute(array($parent_ids));
while($row=$stmt->fetch()) {
$results[] = $row->id;
}
return $results;
}
}
```
Ans using a class like that -
```
$id = 4;
$depth = 2; // get the counts of his downline, only 2 deep.
$downline_array = $getTeam->getDownline($id, $depth=2);
```
I am getting errors -
Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, int given in
and second
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in
I want to fetch the child user ID in 5 levels
|
Remove absolute style for the component, sometimes that also break the automation. |
use `alloc_pages(gfp_t gfp_mask, unsigned int order)` and then make them executable manually using `set_memory_x`.
``` c
void *allocate_physically_contiguous(size_t size, void * data_copy)
{
void *ret;
struct page *page;
unsigned int order = get_order(size);
flags |= __GFP_COMP;
page = alloc_pages(GFP_KERNEL, order);
ret = page ? page_address(page) : NULL;
if(!ret)
return NULL;
memcpy(ret, data_copy, size);
// set_memory_x makes the pages executable, and also read-only, and in some archs, they won't even be readable.
BUG_ON(set_memory_x(ret, 1 << (order - PAGE_SHIFT)));
return ret;
}
// to free, just call `kfree(...)` on the returned pointer
``` |
Why are SST-2 and CoLA commonly used datasets for debiasing? |
|stanford-nlp|bert-language-model|corpus| |
null |