instruction
stringlengths
0
30k
Android kernel error: undefined reference to `get_hw_version_platform'
|android|linux|linux-kernel|android-kernel|
null
That is not a "something"-delimited file, it's fixed width. ```r readLines(unz("~/Downloads/2018029_ascii.zip", "FRSS108PUF.dat"), n=3) # [1] "100011331 1 1 1 1 2 1 2 2 2 2 2 4 1 1 1 1 1 1 2 1 2 3 3 3 3 3 2 2 3 3 3 2 3 2 1 2 3 2 2 2 1 1 1 1 2 1 1 2 1 1 1 1 2 5 3 3 3 3 3 3 3 5 1 5 4 4 4 4 4 4 4 4 12000000000000000000000000000000000000000000000000000000000000000000000000017.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.303822938 18.5837245717.927828408 18.5837245718.02058140118.02058140117.92782840818.471095936 0 18.5837245718.471095936 18.5837245718.47109593617.92782840818.36509251618.47109593617.92782840818.47109593618.36509251617.927828408" # [2] "100022331 2 1 2 2 2 1 2 2 2 2 2 4 1 1 2 1 1 1 2 2 1 4 3 3 2 3 3 4 2 3 4 4 3 2 1 4 1 2 2 2 2 2 1 4 2 2 1 1 3 1 2 1 2 4 4 4 4 4 3 3 2 4 1 4 3 4 3 3 3 2 2 3 1200000000000000000000000000000000000000000000000000000000000000000000000005.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.4137039431 5.318726681 5.3187266815.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.4137039431 5.318726681 5.3187266815.33290239175.33290239175.4137039431 0 5.318726681 5.3187266815.41370394315.4137039431 5.3187266815.22702449685.41370394315.41370394315.41370394315.41370394315.41370394315.39811066135.39811066135.39811066135.41370394315.41370394315.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.2292535051" # [3] "100032331 2 1 1 1 2 1 2 2 2 2 2 4 1 1 1 2 2 1 1 1 3 5 4 4 4 3 4 5 5 5 5 4 4 5 4 4 3 5 2 2 5 1 1 4 1 1 1 1 3 1 1 1 2 3 4 4 5 2 2 1 1 3 1 4 3 4 5 2 2 1 1 2 1200000000000000000000000000000000000000000000000000000000000000000000000005.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.4137039431 5.318726681 5.3187266815.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.4137039431 5.318726681 5.3187266815.33290239175.33290239175.41370394315.4137039431 5.318726681 5.3187266815.41370394315.4137039431 5.3187266815.22702449685.41370394315.4137039431 05.41370394315.41370394315.39811066135.39811066135.39811066135.41370394315.41370394315.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.2292535051" ``` The hard part about fixed-width formats is determining the widths of each field. Fortunately (somewhat), the documentation zip has `LayoutPUF.pdf` that contains each field and the columns for each. The widths for that file should total 1441, since that's what we're getting from the file: ```r nchar(readLines(unz("~/Downloads/2018029_ascii.zip", "FRSS108PUF.dat"), n=3)) # [1] 1441 1441 1441 ``` Counting up the columns, we can use ```r widths <- c(5, rep(1, 4), rep(2, 73), rep(1, 74), rep(12, 101)) out <- read.fwf(unz("~/Downloads/2018029_ascii.zip", "FRSS108PUF.dat"), widths = widths) # Warning in readLines(file, n = thisblock) : # incomplete final line found on '~/Downloads/2018029_ascii.zip:FRSS108PUF.dat' str(out) # 'data.frame': 1527 obs. of 253 variables: # $ V1 : int 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 ... # $ V2 : int 1 2 2 3 2 2 1 1 2 3 ... # $ V3 : int 3 3 3 2 2 2 4 4 3 2 ... # $ V4 : int 3 3 3 1 1 1 2 4 4 2 ... # $ V5 : int 1 1 1 1 1 1 1 1 1 1 ... # $ V6 : int 1 2 2 2 2 1 2 2 2 2 ... # $ V7 : int 1 1 1 1 1 2 1 1 1 1 ... # $ V8 : int 1 2 1 2 2 2 2 1 2 1 ... # $ V9 : int 1 2 1 2 2 2 2 2 2 2 ... # [list output truncated] ``` Over to you to name all 253 columns ...
null
I am plotting some lines with Seaborn: ```python import matplotlib.pyplot as plt import seaborn as sns import pandas as pd # dfs: dict[str, DataFrame] fig, ax = plt.subplots() for label, df in dfs.items(): sns.lineplot( data=df, x="Time step", y="Loss", errorbar="sd", label=label, ax=ax, ) ax.set(xscale='log', yscale='log') ``` The result looks like [this](https://i.stack.imgur.com/FanHR.png). Note the clipped negative values in the `effector_final_velocity` curve, since the standard deviation of the loss between runs is larger than its mean, in this case. However, if `ax.set(xscale='log', yscale='log')` is called *before* the looped calls to `sns.lineplot`, the result looks like [this](https://i.stack.imgur.com/JVGG4.png). I'm not sure where the unclipped values are arising. Looking at the source of `seaborn.relational`: at the end of `lineplot`, the `plot` method of a `_LinePlotter` instance is called. It plots the error bands by passing the already-computed standard deviation bounds to `ax.fill_between`. Inspecting the values of these bounds right before they are passed to `ax.fill_between`, the negative values (which would be clipped) are still present. Thus I had assumed that the "unclipping" behaviour must be something matplotlib is doing during the call to `ax.fill_between`, since `_LinePlotter.plot` appears to do no other relevant post-transformations of any data before it returns, and `lineplot` returns immediately. However, consider a small example that calls `fill_between` where some of the lower bounds are negative: ```python import numpy as np fig, ax = plt.subplots(1, 1, figsize=(5, 5)) np.random.seed(5678) ax.fill_between( np.arange(10), np.random.random((10,)) - 0.2, np.random.random((10,)) + 0.75, ) ax.set_yscale('log') ``` Then it makes no difference if `ax.set_yscale('log')` is called before `ax.fill_between`; in both cases the result is [this](https://i.stack.imgur.com/ctRUi.png). I've spent some time searching for answers about this in the Seaborn and matplotlib documentation, and looked for answers on SA and elsewhere, but I haven't found any information about what is going on here.
Jmix framework throws error building WAR file
|war|jmix|
null
I am creating a memoization example with a function that adds up / averages the elements of an array and compares it with the cached ones to retrieve them in case they are already stored. In addition, I want to store only if the result of the function differs considerably (passes a threshold e.g. 5000 below). I created an example using a decorator to do so, the results using the decorator is slightly slower than without the memoization which is not OK, also is the logic of the decorator correct ? My code is attached below: import time import random from collections import OrderedDict def memoize(f): cache = {} def g(*args): if args[1] == 'avg': sum_key_arr = sum(args[0])/ len(list(args[0])) elif args[1] == 'sum': sum_key_arr = sum(args[0]) print(sum_key_arr) if sum_key_arr not in cache: for key, value in OrderedDict(sorted(cache.items())).items():# key in dict cannot be an array so I use the sum of the array as the key if abs(sum_key_arr - key) <= 5000:#threshold is great here so that all values are approximated! #print('approximated') return cache[key] else: #print('not approximated') cache[sum_key_arr] = f(args[0],args[1]) return cache[sum_key_arr] return g @memoize def aggregate(dict_list_arr,operation): if operation == 'avg': return sum(dict_list_arr) / len(list(dict_list_arr)) if operation == 'sum': return sum(dict_list_arr) return None t = time.time() for i in range(200,150000): res = aggregate(list(range(i)),'avg') elapsed = time.time() - t print(res) print(elapsed) UPDATE: in this update I change the input to become a dict while I search for keys of them in the caching strategy : import time import random from collections import OrderedDict def memoize(f): cache = {} def g(*args): key_arr = list(args[0].keys())[0] arr_val = list(args[0].values())[0] if key_arr not in cache: for key, value in OrderedDict(sorted(cache.items())).items():# key in dict cannot be an array so I use the sum of the array as the key if abs(value - arr_val) <= 5000:#threshold is great here so that all values are approximated! return cache[key] cache[key_arr] = f(args[0],args[1]) return cache[key_arr] return g #@memoize def aggregate(dict_list_arr,operation): if operation == 'avg': return sum(list(dict_list_arr.values())[0]) / len(list(dict_list_arr.values())[0]) if operation == 'sum': return sum(list(dict_list_arr.values())[0]) return None t = time.time() for i in range(200,5500): res = aggregate({'1':list(range(10000))},'avg')#for each different array I set a different key! elapsed = time.time() - t print(res) print(elapsed) The time elapsed is lower in decorated call which makes sense, now does this solve my question?
If i have two NextJS project, a product.company.me site, and the docs hosted on docs.another.me, and I want in product.company.me/docs to render the docs.another.me site, how do I do it with cloudflare workers
Rewrite subdomain to subpath of another subdomain
|next.js|cloudflare|
I expect nesting parallel structures to not yield any additional speed-up. You can assign a number of workers to the outer parallellisation, which doesn't leave any room to use even more workers from outside the current, already parallel, outer level. In any case, [it's recommended to parallelise the *outermost* loop][1] in case of nested loops, I expect the same to hold true for nesting other parallellisation structures. In case your outer structure only contains two elements (i.e. your `idx` is `2`), you might be better off by serially evaluating that loop and using parallellisation on the reading, since you've already verified that that does indeed use more workers and thus reduces execution time. There's a bunch of background links on how and when to leverage parallellisation in [this answer of mine][2] as well as [this one][3]. There's an example in the [`parfeval` docs][4] that updates a UI, that might be worth a try. Alternatively, you could try [`spmd()`][5] to parallellise your reading and assign a limited number of workers to each SPMD. Given you have two sockets with 6 workers each, I'd set the number of workers to 6, leaving a single socket for the main thread: ```lang-matlab parpool(6) spmd your_code() end ``` [1]:https://mathworks.com/help/parallel-computing/nested-parfor-loops-and-for-loops.html [2]:https://stackoverflow.com/a/72527420/5211833 [3]:https://stackoverflow.com/a/32146700/5211833 [4]:https://ch.mathworks.com/help/parallel-computing/parallel.pool.parfeval.html;jsessionid=f754d31761563b9c189c8970882b#mw_56da3b6f-532f-45bf-bd30-4b01f5f64bf3 [5]:https://mathworks.com/help/parallel-computing/spmd.html
I'm making an app with the Qt framework using Qt Creator and CMake (not qmake, because I want the full project to be buildable from other IDEs, but that's not relevant for this topic). In this project, I need the pffft library which is a compact and convenient alternative of fftw. This library has a .h header, and a .c file for the implementation. But when I try to build the project and run it, I get the LNK2019 error for EVERY function I use from this library, although I added the .h and .c files in the CMakeLists.txt, and included the .h file in every source file that uses it (checked that around 10 times now haha) Note : everything worked fine before implementing pffft, so I'm pretty sure it's this library that creates the problem. Here is the part of my CMakeLists.txt where I tell CMake to compile all the files I need (the .ico and .png files are also in the list I know, this file is automatically generated by Qt so I don't touch it that much) : ``` set(PROJECT_SOURCES main.cpp mainwindow.cpp mainwindow.h mainwindow.ui ) if(${QT_VERSION_MAJOR} GREATER_EQUAL 6) qt_add_executable(IR_Maker MANUAL_FINALIZATION ${PROJECT_SOURCES} pffft.c pffft.h about.h about.cpp about.ui add.qrc img/irmaker.ico sweepgenerator.h sweepgenerator.cpp sweepgenerator.ui img/branch-closed2.png img/branch-open2.png qcustomplot.cpp qcustomplot.h ) ``` Finally, my config is : - Windows 10 - Qt 6.6.2 - Qt Creator 12.0.1 - MSVC 2019 compiler Since the pffft library has a .c source file and not a .cpp, I modified the `project(IR_Maker VERSION 0.1 LANGUAGES CXX)` to `project(IR_Maker VERSION 0.1 LANGUAGES CXX C)`, and the LNK2019 errors disappreared but I have a "C1189 error : Error in C++ Standrad Library usage" in a .h file inside of the compiler directory, so I don't know if that gets me any closer from a solution. Same thing happends if I simply remove the `LANGUAGES CXX` in the project() arguments. I also changed the compiler from MSVC 2019 to MinGW because I heard about pffft not being msvc friendly (or the opposite haha), and the errors also disappeared but now it's another problem where it doesn't find my qcustomplot.h file in the autogenerated .h file made from the .ui file of the mainwindow (where qcustomplot.h is used), even if I have the qcustomplot.h file in my project directory. I checked for the `extern "C"` command in the .h file, and it is as shows this code. I'm not sure about the ordrer of the rest so it'll maybe be useful. #ifndef PFFFT_H #define PFFFT_H #include <stddef.h> // for size_t #ifdef __cplusplus extern "C" { #endif // all the header contents are there #ifdef __cplusplus } #endif #endif // PFFFT_H
Backpack for roblox simulator game
|lua|roblox|roblox-studio|
null
After installing the [Hack Nerd Font][1], I managed to resolve the issue by adjusting the terminal settings in Visual Studio. The key step involves specifying the font to be used by the **terminal**. Here's how you can do the same: 1. Navigate to `Tools` > `Options`. 2. Select the `Terminal` section. 3. Under `Font and Colors`, choose `Hack Nerd Font` from the dropdown menu for the font. This configuration ensures that Visual Studio Code's terminal uses the Hack Nerd Font, which includes a wide range of glyphs and symbols needed for proper display. Below is a screenshot that illustrates where these settings are located: [![Settings image][2]][2] By following these steps, you should be able to use the Hack Nerd Font in Visual Studio Code's terminal, improving legibility and access to various font glyphs necessary for development tasks. [1]: https://github.com/ryanoasis/nerd-fonts/releases/download/v3.0.2/Hack.zip [2]: https://i.stack.imgur.com/UBnWu.png
I am writing this solution because you mentioned you are open to using `SQLAlchemy`. As you mentioned, you need association proxy but you also need ["Unique Objects"](https://github.com/sqlalchemy/sqlalchemy/wiki/UniqueObject#). I have adapted it to function with asynchronous queries (instead of synchronous), aligning with my individual preferences, all without altering the logic significantly. ``` import asyncio from sqlalchemy import UniqueConstraint, ForeignKey, select, text, func from sqlalchemy.orm import DeclarativeBase, mapped_column, Mapped, relationship from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.ext.associationproxy import AssociationProxy, association_proxy class Base(DeclarativeBase): pass class UniqueMixin: cache = {} @classmethod async def as_unique(cls, session: AsyncSession, *args, **kwargs): cache = getattr(session, "_cache", None) if cache is None: session._cache = cache = {} key = cls, cls.unique_hash(*args, **kwargs) if key in cache: return cache[key] with session.no_autoflush: statement = select(cls).where(cls.unique_filter(*args, **kwargs)).limit(1) obj = (await session.scalars(statement)).first() if obj is None: obj = cls(*args, **kwargs) session.add(obj) cache[key] = obj return obj @classmethod def unique_hash(cls, *args, **kwargs): raise NotImplementedError("Implement this in subclass") @classmethod def unique_filter(cls, *args, **kwargs): raise NotImplementedError("Implement this in subclass") class Location(UniqueMixin, Base): __tablename__ = "location" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column() type: Mapped[str] = mapped_column() house_associations: Mapped[list["HouseLocationLink"]] = relationship(back_populates="location") __table_args = (UniqueConstraint(type, name),) @classmethod def unique_hash(cls, name, type): # this is the key for the dict return type, name @classmethod def unique_filter(cls, name, type): # this is how you want to establish the uniqueness # the result of this filter will be the value in the dict return (cls.type == type) & (cls.name == name) class House(Base): __tablename__ = "house" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column() location_associations: Mapped[list["HouseLocationLink"]] = relationship(back_populates="house") locations: AssociationProxy[list[Location]] = association_proxy( "location_associations", "location", # you need this so you can directly add ``Location`` objects to ``House`` creator=lambda location: HouseLocationLink(location=location), ) class HouseLocationLink(Base): __tablename__ = "houselocationlink" house_id: Mapped[int] = mapped_column(ForeignKey(House.id), primary_key=True) location_id: Mapped[int] = mapped_column(ForeignKey(Location.id), primary_key=True) location: Mapped[Location] = relationship(back_populates="house_associations") house: Mapped[House] = relationship(back_populates="location_associations") engine = create_async_engine("sqlite+aiosqlite:///test.sqlite") async def main(): data = [ { "name": "red", "locations": [ {"type": "country", "name": "Netherlands"}, {"type": "municipality", "name": "Amsterdam"}, ], }, { "name": "green", "locations": [ {"type": "country", "name": "Netherlands"}, {"type": "municipality", "name": "Amsterdam"}, ], }, ] async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) async with AsyncSession(engine) as session, session.begin(): for item in data: house = House( name=item["name"], locations=[await Location.as_unique(session, **location) for location in item["locations"]] ) session.add(house) async with AsyncSession(engine) as session: statement = select(func.count(text("*")), Location) assert await session.scalar(statement) == 2 statement = select(func.count(text("*")), House) assert await session.scalar(statement) == 2 statement = select(func.count(text("*")), HouseLocationLink) assert await session.scalar(statement) == 4 asyncio.run(main()) ``` You can notice that the asserts do pass with no violation of unique constraint and no multiple inserts. I have left some inline comments which mention the "key" aspects of this code. If you run this code multiple times, you will notice that only new `House` objects and corresponding `HouseLocationLink` are added, no new `Location` objects are added. There will be only one query made to cache this behavior per key - value pair.
|python|keras|tensorflow2.0|
I am in the process of creating a React component library, and I have a function within one of my library components that I would like to export. The function, addParticle, is intended to allow users of the library to dynamically add particles to a container by passing props. Here's the code snippet of my component: ``` import React, { useState } from "react"; import Particle from "../Particle"; import "./ParticleContainer.css"; export interface AddParticleProps { src: string; height: string; width: string; animationDuration: number; } interface ParticleContainerProps { height?: string; width?: string; position?: "relative" | "absolute"; } function ParticleContainer({ height = "40px", width = "40px", position, }: ParticleContainerProps) { const [particleDetails, setParticleDetails] = useState<AddParticleProps[]>( [] ); const addParticle = ({ src, height, width, animationDuration, }: AddParticleProps) => { setParticleDetails([ ...particleDetails, { src, height, width, animationDuration }, ]); }; return ( <div className="particlesContainer" style={{ height, width, position }}> {particleDetails.map((props, index) => { return <Particle key={index} id={index} {...props} />; })} </div> ); } export { addParticle }; // How to properly export this function? export default ParticleContainer; ```
How can I export a function within a React functional component to build a library?
|javascript|reactjs|typescript|npm|export|
`from keras.layers.core import Dense, Activation` when trying to import above line i was facing error. The answer would be `from keras.layers import Dense, Activation` as core module do not contain Activation.
The way FTP works is to have a constant connection on a control channel, port 21, and to set up and tear down connections to pass data over, on some random channel decided by the server or the client In PORT (active) mode the client decides what port it will open, it tells the server and the server connects to the client. This isn't very good these days because most clients are likely being some NAT device that won't forward the connection on In PASV (passive) mode the server decides what port to open, and the client conents into it. This is much more compatible with the majority of client side NAT devices, and the range of ports the server will open is typically configured by the network admin responsible for the server who is also responsible for the firewall on the server's network (so they can configure the forwarding rules to work out) This split was originally pretty useful for transferring large files between two servers on fast connections, controlled by a client on a slow connection - the client could connect to each server simultaneously, tell one server to expect a connection, and the other to make a connection and cause the servers to connect directly so the data didn't flow though the client. --- You're using `quote` a lot in your log - this sends a raw command to the server but the client won't necessarily take any further interest in it - just because you `quote PASV` to request the server go to passive mode doesn't mean it will switch the client over to knowing it has to operate in passively so even when the server does switch to expecting a connection, the client won't connect. If you're using windows FTP command line client with a server that requires passive connections I'm afraid you're sunk - the client doesn't suport passive operation. I recommend seeking an alternative client with a command line version that does support passive. nb, SFTP is an entirely different beast that just happens to share part of an acronym. SFTP doesn't have this "control channel + multiple random data channels" idea so it's often more reliable and easier for network admin to permit because everything goes over the one channel; that may be your solution and one that is perhaps preferable because it's more secure all round. With FTP you don't really have any good guarantees that the data is from the actual same source that was instructed to send it
I'm programming a simple 'game' that is just a block that can jump around. I placed a wall, but now the character phases through when moving to the right, but the collision works when going to the right. The collision in question: ``` function willImpactMovingRight(a, b){ var docA = document.getElementById(a); var docB = document.getElementById(b[0]); for(var i=0;i<b.length;i++){ docB = document.getElementById(b[i]); if((docA.offsetTop>docB.offsetTop&&docA.offsetTop<docB.offsetTop+docB.offsetHeight)||(docA.offsetTop+docA.offsetHeight>docB.offsetTop&&docA.offsetTop+docA.offsetHeight<docB.offsetTop+docB.offsetHeight)){//vertical check, not broken if(docA.offsetLeft>docB.offsetWidth+docB.offsetLeft-runSpeed){//also fine //below this is the problem if(docA.offsetLeft+docA.offsetWidth+runSpeed<=docB.offsetLeft){ CUBE.textContent = "WIMR"; return docB.offsetLeft-docA.offsetWidth; } //all syntax is fine but the if statement never returns as true. } } } return false; } ``` it looks like a lot, but the only problem is the last if statement. Even when the condition is true, it still skips the return number and returns false. Any idea why? P.S. **I CANNOT USE THE CONSOLE, I AM ON A MANAGED COMPUTER** I'm also locked out of my github account and have a link to a code.org page (just copy the code) https://studio.code.org/projects/applab/iFUpHIl-Vq3nQ4PYxY8Y1tMkIIgh9tAl95RexkDQUh8
maybe the problem is that: ```python class MoneyManager(QMainWindow): def __init__(self): //....other code self.ui.DeleteTransButton.clicked.connect(self.delete_current_transaction()) ``` Remove the parentheses at the end of delete_current_transaction, we just want to pass the method, not call it. ```python self.ui.DeleteTransButton.clicked.connect(self.delete_current_transaction) ```
For some reason my /etc/fonts/fonts.conf keeps reloading back to an initial version loosing my changes. It happens almost immediately. It is on my Ubuntu wsl2 in windows. Any tips or tricks to fix? How do I fix? I've used vi and pico both with sudo.
Ubuntu wsl2 in windows, my /etc/fonts/fonts.conf keeps reloading
|ubuntu|fonts|configuration|
null
The issue is with the `onSubmit` function itself. In your `onSubmit` function, you're logging the values and then calling `await addProduct(values)`. However, the addProduct function is a server-side function, and you're trying to call it directly from the client-side component. To fix this, you need to move the call to `addProduct` to a separate server-side action, which can be done using the Next.js `action` function. Create a new file inside the `app/admin/products` directory, let's call it `addProduct.tsx`, ```js import { NextResponse } from "next/server"; import { z } from "zod"; import { NewProductSchema } from "@/zod/schemas"; import { addProduct } from "@/app/admin/_actions/products"; export async function POST(request: Request) { const formData = await request.formData(); const result = NewProductSchema.safeParse(Object.fromEntries(formData)); if (result.success === false) { return NextResponse.json(result.error.formErrors.fieldErrors, { status: 400, }); } const data = result.data; await addProduct(data); return NextResponse.redirect("/admin/products"); } ``` Above code creates a new server-side action that can be triggered by a POST request. It validates the form data using the `NewProductSchema`, and if the data is valid, it calls the `addProduct` function from the server-side action file. Then, inside your `ProductForm` component, update the `onSubmit` function to use the new server-side action: ```js async function onSubmit(values: z.infer<typeof NewProductSchema>) { const formData = new FormData(); Object.entries(values).forEach(([key, value]) => { formData.append(key, value); }); await fetch("/admin/products/addProduct", { method: "POST", body: formData, }); } ```
How define permission on Firebase
|flutter|firebase|authentication|google-cloud-firestore|firebase-authentication|
null
I am trying to get my laravel app to work. It works locally, I deployed the app with BitBucket pipeline, I can `php artisan serve` (shows it starts the server), but when reaching the server, I get `Bad Gateway 502`, what am I doing wrong? I run on Debian 12 nginx `error.log` is showing the following message: > 2024/03/22 15:40:43 [error] 249350#249350: *3 directory index of "/var/www/html/laravel/current/" is forbidden, client: 80.**.**.**, server: <server_name>, request: "GET / HTTP/1.1", host: "85.**.**.**:8000" This is my nginx.conf: pid /run/nginx.pid; error_log /var/log/nginx/error.log; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; include /etc/nginx/sites-available/*; } This is my conf file: /etc/nginx/sites-available/filename.conf server { listen 80; server_name server_domain_or_IP; root /var/www/html/laravel/current/public; add_header X-Frame-Options "SAMEORIGIN"; add_header X-XSS-Protection "1; mode=block"; add_header X-Content-Type-Options "nosniff"; index index.html index.htm index.php; charset utf-8; location / { try_files $uri $uri/ /index.php?$query_string; } location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; } error_page 404 /index.php; location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; include fastcgi_params; } location ~ /\.(?!well-known).* { deny all; } } running the server does not do anything either: [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/fG0NS.png but also tring to add the port does not do anything
To display the legend outside of the plot in matplotlib, you can use the bbox_to_anchor papameter along with the loc parameter of the legend function, here's how you can modify your code to achieve that: `df3.iloc[0:30].plot.area(alpha=0.4) plt.legend(loc='upper left', bbox_to_anchor=(1, 1)) plt.show()`
Here is one way, where a custom type is used to hold the state. ``` //@version=5 library("MyLib", overlay=true) export type MyLib int i export init() => MyLib.new(0) export foo(MyLib this) => this.i += 1 ``` Usage example: ``` if barstate.isfirst: state = MyLib.init() log.info("{0}", MyLib.foo(state)) ```
### A solution ### A cycloid that conforms to the description of the question is given by the parametric coordinates: ```lang-js const r = 0.3107954365513382, dr = 0.22339354437585907; const sin45deg = Math.sqrt(2)/2; const x = t => r * sin45deg * (1 - t + Math.sin(t) - Math.cos(t) + Math.PI) + dr, y = t => - r * sin45deg * (1 + t - Math.sin(t) - Math.cos(t) - Math.PI) - dr, ``` I'll describe later how I derived those equations and computed the parameters. Now, regardless of the actual curve that is used, if it defined parametrically, the <i>mathematics</i> involved for determining the parameters of the distributions involve getting the value of `y` that corresponds to a certain `x` on the curve - it means solve the equation `y(t) = y` to get the parameter `t` and then use that parameter to compute `x(t)`. For the case of the cycloid, as well as most other curves, the solution of the equation `y(t) = y` cannot be derived in closed form, so it has to be computed numerically. The numerical method I have chosen is [Newton's method](https://mathworld.wolfram.com/NewtonsMethod.html); it requires the derivative of `y(t)`, `y'(t)`, which I implemented in the function `yd(t)`. With these, the solution to the problem in question is this: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const r = 0.3107954365513382, dr = 0.22339354437585907; const sin45deg = Math.sqrt(2)/2; const x = t => r * sin45deg * (1 - t + Math.sin(t) - Math.cos(t) + Math.PI) + dr, y = t => r * sin45deg * (1 + t - Math.sin(t) - Math.cos(t) - Math.PI) + dr, yd = t => r * sin45deg * (1 - Math.cos(t) + Math.sin(t)); const getXForY = y0 => { let t = Math.PI, yt = y(t) - y0; for(let i = 0; i < 10; i++){ const tNext = t - yt / yd(t); yt = y(tNext) - y0; const dt = tNext - t; t = tNext; if(Math.abs(yt) < 1e-20 || Math.abs(dt) < 1e-15){ break; } } return x(t); } const paretoDistributionPredictionFor = (numberOfPeople, personAtIndex) => { if(personAtIndex < 1 || personAtIndex > numberOfPeople){ return null; } const fracInStart = (personAtIndex - 1)/numberOfPeople, fracInEnd = personAtIndex/numberOfPeople; const fracOutStart = 1 - getXForY(1 - fracInStart), fracOutEnd = 1 - getXForY(1 - fracInEnd), fracOutDiff = -fracOutEnd + fracOutStart; return (fracOutDiff * 100).toFixed(2).replace(/\.0+$/, '')+'%'; } console.log('f(2, 1) = ' + paretoDistributionPredictionFor(2, 1)); console.log('f(2, 1) = ' + paretoDistributionPredictionFor(2, 2)); console.log(Array(30).fill('-').join('')); console.log('f(3, 1) = ' + paretoDistributionPredictionFor(3, 1)); console.log('f(3, 2) = ' + paretoDistributionPredictionFor(3, 2)); console.log('f(3, 3) = ' + paretoDistributionPredictionFor(3, 3)); console.log(Array(30).fill('-').join('')); console.log('f(4, 1) = ' + paretoDistributionPredictionFor(4, 1)); console.log('f(4, 2) = ' + paretoDistributionPredictionFor(4, 2)); console.log('f(4, 3) = ' + paretoDistributionPredictionFor(4, 3)); console.log('f(4, 4) = ' + paretoDistributionPredictionFor(4, 4)); <!-- end snippet --> also as [jsFiddle](https://jsfiddle.net/ep9q40z6/) -------- ### The cycloid ### The standard equation of the [cycloid](https://mathworld.wolfram.com/Cycloid.html) is ```lang-js x = t => r * (t - Math.sin(t)); y = t => r * (1 - Math.cos(t)); ``` These equations give a cycloid that passes through the point `(0, 0)`, `(PI*r, 2*r)` - the maximum, `(2*PI*r, 0)`. To make it symmetrical with respect to the origin (more precisely with respect to the `y` axis), we have to subtract `PI * r` from `x` ```lang-js x = t => r * (t - Math.sin(t) - Math.PI); y = t => r * (1 - Math.cos(t)); ``` This curve passes through `(-PI*r, 0)`, `(0, 2*r)` - the maximum, and `(PI*r, 0)`. The next step is to [rotate](https://mathworld.wolfram.com/RotationMatrix.html) the cycloid by `-3*PI/4`, that is 145 degrees clockwise. This gives the equations: ```lang-js const sin45deg = Math.sqrt(2)/2; const x = t => r * sin45deg * (1 - t + Math.sin(t) - Math.cos(t) + Math.PI), y = t => - r * sin45deg * (1 + t - Math.sin(t) - Math.cos(t) - Math.PI), ``` These would allow one to compute `r` such that the cycloid passes through the points (1, 0) and (0, -1); due to symmetry, only one condition has to be verified. This gives `r = 0.43077140606812125` (see below on how I computed `r` and `dr`, for an outline of the method to derive `r`). The problem with this curve is that it doesn't pass through the point `(0.8, -0.5)`, which would make it verify the 80:20 ratio of Pareto fame. The `x` value that corresponds to `y = -0.5` (50%) is `x = 0.7094`, which would make it 71:29. This can be seen in the snippet below (get the cursor near the cycloid to get other ratio values). <!-- begin snippet: js hide: false console: false babel: false --> <!-- language: lang-js --> const r = 0.43077140606812125; const sin45deg = Math.sqrt(2)/2; const x = t => r * sin45deg * (1 - t + Math.sin(t) - Math.cos(t) + Math.PI), y = t => r * sin45deg * (1 + t - Math.sin(t) - Math.cos(t) - Math.PI), yd = t => r * sin45deg * (1 - Math.cos(t) + Math.sin(t)); const getXForY = y0 => { let t = Math.PI, yt = y(t) - y0; for(let i = 0; i < 10; i++){ const tNext = t - yt / yd(t); yt = y(tNext) - y0; const dt = tNext - t; t = tNext; if(Math.abs(yt) < 1e-20 || Math.abs(dt) < 1e-15){ break; } } return x(t); } const linspace = function(x1, x2, n){ return Array.from({length: n}, (_, i) => x1 + (x2 - x1) * i / (n - 1)); } const N = 100; const cycloidPoints = (() => { const ta = linspace(0, 2 * Math.PI, N); return ta.map(t => ({x: x(t), y: -y(t)})); })(); const cycloidXAxis = [cycloidPoints[0], cycloidPoints[N-1]]; const squarePoints = [{x:0, y: 0}, {x: 1, y: 0}, {x: 1, y: -1}, {x: 0, y: -1}, {x: 0, y: 0}]; const pareto = getXForY(0.5); const paretoPoints = [{x: 1, y: -0.5}, {x: pareto, y: -0.5}, {x: pareto, y: -1}]; const data = { datasets: [ { label: 'Cycloid', data: cycloidPoints, borderColor: 'rgba(255, 26, 104, 1)', }, { label: 'Cycloid x-axis', data: cycloidXAxis, borderColor: 'rgba(70, 140, 40, 1)', borderDash: [5, 4], borderWidth: 2 }, { label: 'square', data: squarePoints, borderColor: 'rgba(0, 0, 0, 1)', }, { data: paretoPoints, borderColor: 'rgba(40, 70, 140, 1)', }] } const config = { type: 'line', data, options: { responsive: true, maintainAspectRatio: false, pointRadius: 0, borderWidth: 1, tension: 0, scales: { x: { type: 'linear', } }, interaction: { intersect: false, mode: "nearest" }, plugins: { tooltip: { filter({datasetIndex, parsed: {x, y}}){ return datasetIndex === 0 && x >= 0 && x <= 1 && -y >= 0 && -y <= 1; }, callbacks: { title(){ return ''; }, label(context){ if(context.datasetIndex !== 0){ return null; } const {x, y} = context.parsed; if(x < 0 || x > 1 || -y < 0 || -y > 1){ return '' } return `${(-y*100).toFixed(0)}% => ${(x*100).toFixed(0)}%`; } } }, legend: { labels: { usePointStyle: true, pointStyle: 'line', filter(a){ return a.text; } } }, annotation: { annotations: { label1: { type: "label", xValue: pareto, yValue: -0.5, position: 'end', borderWidth: 1, borderDash: [4, 6], content: `50% => ${(pareto * 100).toFixed(0)}%` } } } } } }; const chart = new Chart( document.getElementById('chart'), config ); // set approx equal scales const containerEl = document.getElementById('container'); const xRange = chart.scales.x.max - chart.scales.x.min, yRange = chart.scales.y.max - chart.scales.y.min, xg = chart.chartArea.width, yg = chart.chartArea.height, dx = containerEl.offsetWidth - xg, dy = containerEl.offsetHeight - yg, scaleX = xg/xRange, scaleY = yg/yRange; const reScaleX = scaleX / Math.min(scaleX, scaleY), reScaleY = scaleY / Math.min(scaleX, scaleY); containerEl.style.width = (containerEl.offsetWidth / reScaleX + dx * (1 - 1/reScaleX))+"px"; containerEl.style.height = (containerEl.offsetHeight / reScaleY + dy * (1 - 1/reScaleY))+"px"; <!-- language: lang-html --> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@3.0.1/dist/chartjs-plugin-annotation.min.js"></script> <div style="height:500px" id="container"> <canvas id="chart"></canvas> </div> <!-- end snippet --> also as [jsFiddle](https://jsfiddle.net/pd1v0x6q/) To address this issue, I added a translation of the cycloid, after the rotation. To keep symmetry, the translation has to be along the `x = -y` line; this would add a `dr` to x, while, `y = y - dr`. With this new parameter, the equations of the cycloid are: ```lang-js x = t => r * sin45deg * (1 - t + Math.sin(t) - Math.cos(t) + Math.PI) + dr; y = t => - r * sin45deg * (1 + t - Math.sin(t) - Math.cos(t) - Math.PI) - dr; ``` Now we have two equations to solve for the two unknowns, `r` and `dr`: the first equation comes again from the condition that the cycloid passes through the point `x=1, y=0`, while the second is to verify the 80:20 ration, that is that the cycloid passes through the point `x=0.8, y=-0.5`. With these, we get the values of the parameters `r = 0.3107954365513382, dr = 0.22339354437585907` (see below how). Here's the cycloid in this case: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const r = 0.3107954365513382, dr = 0.22339354437585907; const sin45deg = Math.sqrt(2)/2; const x = t => r * sin45deg * (1 - t + Math.sin(t) - Math.cos(t) + Math.PI) + dr, y = t => r * sin45deg * (1 + t - Math.sin(t) - Math.cos(t) - Math.PI) + dr, yd = t => r * sin45deg * (1 - Math.cos(t) + Math.sin(t)); const getXForY = y0 => { let t = Math.PI, yt = y(t) - y0; for(let i = 0; i < 10; i++){ const tNext = t - yt / yd(t); yt = y(tNext) - y0; const dt = tNext - t; t = tNext; if(Math.abs(yt) < 1e-20 || Math.abs(dt) < 1e-15){ break; } } return x(t); } const linspace = function(x1, x2, n){ return Array.from({length: n}, (_, i) => x1 + (x2 - x1) * i / (n - 1)); } const N = 100; const cycloidPoints = (() => { const ta = linspace(0, 2 * Math.PI, N); return ta.map(t => ({x: x(t), y: -y(t)})); })(); const cycloidXAxis = [cycloidPoints[0], cycloidPoints[N-1]]; const squarePoints = [{x:0, y: 0}, {x: 1, y: 0}, {x: 1, y: -1}, {x: 0, y: -1}, {x: 0, y: 0}]; const pareto = getXForY(0.5); const paretoPoints = [{x: 1, y: -0.5}, {x: pareto, y: -0.5}, {x: pareto, y: -1}]; const data = { datasets: [ { label: 'Cycloid', data: cycloidPoints, borderColor: 'rgba(255, 26, 104, 1)', }, { label: 'Cycloid x-axis', data: cycloidXAxis, borderColor: 'rgba(70, 140, 40, 1)', borderDash: [5, 4], borderWidth: 2 }, { label: 'square', data: squarePoints, borderColor: 'rgba(0, 0, 0, 1)', }, { data: paretoPoints, borderColor: 'rgba(40, 70, 140, 1)', }] } const config = { type: 'line', data, options: { responsive: true, maintainAspectRatio: false, pointRadius: 0, borderWidth: 1, tension: 0, scales: { x: { type: 'linear', } }, interaction: { intersect: false, mode: "nearest" }, plugins: { tooltip: { filter({datasetIndex, parsed: {x, y}}){ return datasetIndex === 0 && x >= 0 && x <= 1 && -y >= 0 && -y <= 1; }, callbacks: { title(){ return ''; }, label(context){ if(context.datasetIndex !== 0){ return null; } const {x, y} = context.parsed; if(x < 0 || x > 1 || -y < 0 || -y > 1){ return '' } return `${(-y*100).toFixed(0)}% => ${(x*100).toFixed(0)}%`; } } }, legend: { labels: { usePointStyle: true, pointStyle: 'line', filter(a){ return a.text; } } }, annotation: { annotations: { label1: { type: "label", xValue: pareto, yValue: -0.5, position: 'end', borderWidth: 1, borderDash: [4, 6], content: `50% => ${(pareto * 100).toFixed(0)}%` } } } } } }; const chart = new Chart( document.getElementById('chart'), config ); // set approx equal scales const containerEl = document.getElementById('container'); const xRange = chart.scales.x.max - chart.scales.x.min, yRange = chart.scales.y.max - chart.scales.y.min, xg = chart.chartArea.width, yg = chart.chartArea.height, dx = containerEl.offsetWidth - xg, dy = containerEl.offsetHeight - yg, scaleX = xg/xRange, scaleY = yg/yRange; const reScaleX = scaleX / Math.min(scaleX, scaleY), reScaleY = scaleY / Math.min(scaleX, scaleY); containerEl.style.width = (containerEl.offsetWidth / reScaleX + dx * (1 - 1/reScaleX))+"px"; containerEl.style.height = (containerEl.offsetHeight / reScaleY + dy * (1 - 1/reScaleY))+"px"; <!-- language: lang-html --> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@3.0.1/dist/chartjs-plugin-annotation.min.js"></script> <div style="height:500px" id="container"> <canvas id="chart"></canvas> </div> <!-- end snippet --> also as [jsFiddle](https://jsfiddle.net/1ygLobas/) -------- ### Computing `r` and `dr` ### This is of little consequence for the rest of the discussion, but I'll give the code and description for the sake of completeness. I computed the values of `r` and `dr`, from the equations `x(t) = 0, y(t) = 1` and `x(t) = 0.5` and `y(t) = -0.8` as described in the previous section. For any pair of values for `r` and `dr` we can compute four values of `t` that the four equations above: `x(t1) = 0`, `y(t2) = 1`, `x(t3) = 0.5`, `y(t4) = -0.8`. Computing the four `t`s is done as described in the first section, by using Newton's method. Now, the first two equations of the four above should come together, that is *for the same `t`*: `t1 = t2`; the same goes for the last two, we intend to find the `r` and `dr` that give `t3 = t4`. This means we have our two equations as: ```lang-js t1(r, dr) - t2(r, dr) = 0 t3(r, dr) - t4(r, dr) = 0 ``` This system is also solved using Newton's method, with the difference that the differentials are computed numerically. For the method to be convergent, one has to start with good initial values; fortunately, there is the cycloid graphic above, where we could play with the values of parameters with visual feedback, such that we obtained good initial values. Here's the code: <!-- begin snippet: js hide: true console: true babel: false --> <!-- language: lang-js --> const sin45deg = Math.sqrt(2)/2; const xr = (r, dr) => (t => r * sin45deg * (1 - t + Math.sin(t) - Math.cos(t) + Math.PI) + dr), xdr = (r, dr) => (t => r * sin45deg * (-1 + Math.cos(t) + Math.sin(t))), yr = (r, dr) => (t => r * sin45deg * (1 + t - Math.sin(t) - Math.cos(t) - Math.PI) + dr), ydr = (r, dr) => (t => r * sin45deg * (1 - Math.cos(t) + Math.sin(t))); const getTForX = (r, dr, x0, nMax = 100) => { const x = xr(r, dr), xd = xdr(r, dr); let t = Math.PI, xt = x(t) - x0; const a_dt = [], a_xt = []; for(let i = 0; i < nMax; i++){ const tNext = t - xt / xd(t); xt = x(tNext) - x0; const dt = tNext - t; t = tNext; a_dt.push(dt); a_xt.push(xt); if(Math.abs(xt) < 1e-20 || Math.abs(dt) < 1e-12){ break; } else if(i === nMax-1){ console.error({r, dr, x0}, {a_xt, a_dt}); throw 'not converging on x; choose different initial values'; } } return t; } const getTForY = (r, dr, y0, nMax = 100) => { const y = yr(r, dr), yd = ydr(r, dr); let t = Math.PI, yt = y(t) - y0; const a_dt = [], a_yt = []; for(let i = 0; i < nMax; i++){ const tNext = t - yt / yd(t); yt = y(tNext) - y0; const dt = tNext - t; a_dt.push(dt); a_yt.push(yt); t = tNext; if(Math.abs(yt) < 1e-20 || Math.abs(dt) < 1e-12){ break; } else if(i === nMax-1){ console.error({r, dr, y0}, {a_yt, a_dt}); throw 'not converging on x; choose different initial values'; } } return t; } const x0 = 1, y0 = 0; const x1 = 0.8, y1 = 0.5; const eq0 = (r, dr) => /*Math.abs*/(getTForX(r, dr, x0) - getTForY(r, dr, y0)); const eq1 = (r, dr) => /*Math.abs*/(getTForX(r, dr, x1) - getTForY(r, dr, y1)); const eps_diff = 1e-3; const J0 = (r, dr) => { const v0 = eq0(r, dr); return [(eq0(r+eps_diff, dr)-v0)/eps_diff, (eq0(r, dr+eps_diff)-v0)/eps_diff]; } const J1 = (r1, dr1) => { const v1 = eq1(r1, dr1); return [(eq1(r1+eps_diff, dr1)-v1)/eps_diff, (eq1(r1, dr1+eps_diff)-v1)/eps_diff]; } const solveMain = (r0, dr0, nMax = 20) => { let r = r0, dr = dr0; let df0 = eq0(r, dr), df1 = eq1(r, dr); for(let i = 0; i < nMax; i++){ const [J00, J01] = J0(r, dr), [J10, J11] = J1(r, dr); const det = J00 * J11 - J01 * J10; const delta_r = -(df0 * J11 - df1 * J01) / det, delta_dr = -(-J10 * df0 + J00 * df1) / det; r = r + delta_r; dr = dr + delta_dr; df0 = eq0(r, dr); df1 = eq1(r, dr); if(Math.max(Math.abs(df0), Math.abs(df1)) < 1e-20 || Math.max(Math.abs(delta_r), Math.abs(delta_dr)) < 1e-12){ break; } else if(i === nMax-1){ throw 'not converging globally; choose different initial values'; } } return ({r, dr}); } // initial values can be obtained by playing with these params on the graphic console.log(solveMain(0.3, 0.25)); <!-- end snippet --> also as [jsFiddle](https://jsfiddle.net/twed05qc/) **Note** In the code in the first section, I used `-y` instead of `y`, to simplify computation. Graphically it would mean flipping the chart along x axis, or moving the action from quadrant 4 to quadrant 1.
I'm not at a proper machine to test this on, but I think it's simpler if you use a two-stage approach. First, generate each of the images with its label, then pipe all those into a second `montage` command to lay them all out together. In simple terms, that will look like this: for f in *.jpg; do # Generate a single, labelled image on stdout in MIFF format magick "$f" ... MIFF:- done | magick montage MIFF:- ... result.jpg I use `MIFF` as the intermediate format because it can preserve and propagate any bit-depth, any transparency and all meta-data. So, your actual command will look more like this: for f in $(ls -rt *.jpg) ; do # Take first 8 characters, no need to invoke external process like "cut" label="${f:0:8}" magick "$f" -label "$label" -font Arial -pointsize 16 \ -auto-orient -resize 200x200 -background black \ -fill grey MIFF:- done | magick montage -background black MIFF:- -geometry +2+2 -tile 8x result.jpg --- Remember not to put any debug code inside the `for` loop that writes on `stdout` because it will get sent to the final `montage` command and confuse it. So, if you want debug statements inside the `for` loop, use `stderr` like this: >&2 echo DEBUG: Processing file $f --- Note that you may want to add `-extent 200x200` to the command inside the `for` loop to ensure smaller, or different aspect-ratio images are padded up to a full 200x200. --- If, during the debug stage, you want to see the individual images that are getting sent through the pipe, you can write them to the filesystem as well by changing the `magick` command in the `for` loop to write an extra copy: for ... ; do magick "$f" ... -write "DEBUG-${label}.jpg" MIFF:- done | magick montage MIFF:- ...
My device is Xiaomi 11 Lite 5G NE (lisa) and I am using the defconfig from ./arch/arm64/configs/vendor/lahaina-qgki_defconfig. I am using clang as CC and aarch64-linux-gnu- as CLANG_TRIPLE (both from proton-clang) while using aarch64-linux-android- as CROSS_COMPILE (from here https://github.com/ibnudz/aarch64-linux-android-4.9) I am trying to build a kernel of that device but I faced some errors (https://github.com/renoir-development/android_kernel_xiaomi_sm8350/tree/lineage-19.1) During the compilation, I got undefined error for these functions `get_hw_country_version, get_hw_version_platform, get_hw_version_build, get_hw_version_major, get_hw_version_minor` in ./drivers/soc/qcom/icnss2/qmi.o By doing `grep -r "get_hw_country_version"`, I was able to locate the function was declared in ./drivers/misc/hwid.c while the header file is located in ./include/linux/hwid.h I found that qmi.c (mentioned above) already has hwid.h included and some defined values in hwid.h successfully be used by qmi.c, but I am still getting the undefined reference error for those functions. How do I fix this issue?
As of 6/7/2023 this is now possible. https://learn.microsoft.com/en-us/azure/databricks/sql/admin/sql-execution-tutorial Full API reference here: https://docs.databricks.com/api/workspace/statementexecution/executestatement
I’m trying to send string of 13 ascii characters from js to php session using ajax, but up on receving string is not the same as i send it, using json.stringyfy and jsondecode does nothing. ``` console.log(plik_T[click]) jQuery.ajax({ type: "POST", url: './Setyb.php', dataType: 'text', data: {send: plik_T[click]}, success: function (obj) { console.log(obj) } }); ``` ``` <?php var_dump($_POST['send']); ?> ``` [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/4AvsC.png i tried using json.stringify or changing meta UTF-8 to older versions non of this resolved my problem. Then i tried checking type of variables witch both were string, so that lead my to nothing. what i'm trying to accomplish is to set my Session variable up on user click and use it in next php page
Js variable to php using a
|javascript|php|ajax|
null
If you revert all changes related to FastCGI and start cleanly with HttpPlatformHandler, you will see how smooth the experience is, ``` xml <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" requireAccess="Script" /> </handlers> <httpPlatform stdoutLogEnabled="true" stdoutLogFile=".\python.log" startupTimeLimit="20" processPath="C:\Users\<user name>\AppData\Local\Programs\Python\Python310\python.exe" arguments=".\mysite\manage.py runserver %HTTP_PLATFORM_PORT%"> </httpPlatform> </system.webServer> </configuration> ``` Python/Django still takes care of everything including static files, and IIS/HttpPlatformHandler just passes requests on. More details can be found from [my blog post](https://docs.lextudio.com/blog/running-django-web-apps-on-iis-with-httpplatformhandler/).
I'm trying to add a dropdown menu inside a navigation bar. I'm using the code provided by https://www.w3schools.com/css/css_dropdowns.asp, but when I try to fix the bar at the top of the page, the dropdown menu doesn't show anymore. This is the code with a working dropdown menu: ``` <!DOCTYPE html> <html lang="it"> <head> <meta charset="UTF-8"> <style> body {margin:0;} ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; } li { float: left; } li a, .dropbtn { display: inline-block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover, .dropdown:hover .dropbtn { background-color: red; } li.dropdown { display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; text-align: left; } .dropdown-content a:hover {background-color: #f1f1f1;} .dropdown:hover .dropdown-content { display: block; } </style> </head> <body> <ul> <li><a href="#home">Home</a></li> <li><a href="#news">News</a></li> <li class="dropdown"> <a href="#" class="dropbtn">Dropdown</a> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </li> </ul> <div style="margin:20px;"> <h3>Dropdown Menu inside a Navigation Bar</h3> <p style="height:3000px;">This should be a simple responsive webpage with a fixed navbar and a dropdown menu.</p> </div> </body> </html> ``` But if I add ``` ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; position: fixed; width: 100%; top: 0; } ``` ...the dropdown menu disappears. What should I do? Thanks.
Django's `BaseFormSet` defines a `delete_widget` attribute that can be overridden in a subclass: ```python from django.forms.formsets import BaseFormSet, BaseInlineFormSet from django.forms.widgets import HiddenInput, CheckboxInput class CustomFormSet(BaseFormSet): delete_widget = HiddenInput class CustomCheckboxInput(CheckboxInput): template_name = "my/custom/checkbox.html" class CustomInlineFormset(BaseInlineFormSet): delete_widget = CustomCheckboxInput ``` If the details of the DELETE field need to be modified, such as the label, or type of field, then `BaseFormSet.add_fields` can be extended or overridden: ```python from django.forms.formsets import BaseFormSet, DELETION_FIELD_NAME from django.forms.fields import BooleanField class CustomBooleanField(BooleanField): # ... class CustomFormSet(BaseFormSet): def add_fields(self, form, index): super().add_fields(form, index) if form.fields.get(DELETION_FIELD_NAME, None) is not None: form.fields[DELETION_FIELD_NAME] = CustomBooleanField( # ... ) ```
I need to write a program to convert any .tiff Image into a .DCM in C++. I implemented the DCMTK correctly but in my solution i cant open the .dcm after converting :( ``` bool convertTiffToDicom(const std::string& tiffFilename, const std::string& dicomFilename) { // TIFF-Bild laden cv::Mat tiffImage = cv::imread(tiffFilename, cv::IMREAD_UNCHANGED); if (tiffImage.empty()) { std::cerr << "Fehler beim Laden des TIFF-Bildes." << std::endl; return false; } // DICOM-Dataset erstellen DcmFileFormat dcmFileFormat; DcmDataset* dcmDataset = dcmFileFormat.getDataset(); // Größe des Bildes setzen dcmDataset->putAndInsertUint16(DCM_Rows, tiffImage.rows); dcmDataset->putAndInsertUint16(DCM_Columns, tiffImage.cols); // Pixelwerte setzen DcmElement* pixelData = nullptr; dcmDataset->findAndGetElement(DCM_PixelData, pixelData); if (!pixelData) { pixelData = new DcmPixelData(DCM_PixelData); dcmDataset->insert(pixelData, true); } pixelData->putUint16Array((Uint16*)tiffImage.data, tiffImage.rows * tiffImage.cols); // Zusätzliche Metadaten hinzufügen (Beispiel) dcmDataset->putAndInsertString(DCM_PatientName, "John Doe"); dcmDataset->putAndInsertString(DCM_PatientID, "12345"); // DICOM-Bild speichern OFCondition status = dcmFileFormat.saveFile(dicomFilename.c_str(), EXS_LittleEndianExplicit); if (status.good()) { std::cout << "Konvertierung von TIFF zu DICOM erfolgreich abgeschlossen." << std::endl; return true; } else { std::cerr << "Fehler beim Speichern des DICOM-Bildes: " << status.text() << std::endl; return false; } } ```
Convert .TIFF Image to .DCM with DCMTK in C++
|tiff|dicom|dcmtk|
null
|r|amazon-ec2|dplyr|apache-arrow|dbplyr|
I'm encountering an issue with the ```insertSlidesFromBase64``` method in PowerPoint. When I insert slides using this method, the embedded fonts in the slides are not being carried over. Specifically, I'm looking to ensure that the embedded font is applied correctly when inserting slides from base64. The font I'm trying to embed is Arimo. I've confirmed that it's properly embedded in the original slide, but it doesn't seem to carry over when inserted using insertSlidesFromBase64.
|flutter|dart|pagination|
|node.js|artificial-intelligence|chatbot|google-generativeai|
I am trying to write a personal project in JavaScript. So I started with an empty folder with two files: card.js constants.js and in `card.js`, I used on the first line: import { SUIT } from "./constants.js"; and run it using `node card.js`. It doesn't work, giving the error: > (node:91577) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. If I look at the [docs for import][1], it has: import { myExport } from "/modules/my-module.js"; So I used `mkdir modules` and moved that `constants.js` in there. And then I used: import { SUIT } from "/modules/constants.js" and it still has the same error. I am wonder if this `import` is the same as `import` in the context of NodeJS (and so it may be different in Deno). How is it done? [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
How do I have a personal project in JavaScript and use `import`?
|javascript|
I am working on configuring a multi-tenant web application. Each tenant will have their own User Pool in AWS Cognito, along with their own Idp configurations. In some cases we’ll use the Cognito User Pool as the primary Idp, and in other cases we’ll use a federated Idp, likely using SAML. My question is: are there any safety concerns with directly integrating a 3rd party tenant’s designated User Pool with an Idp that they own and manage? Or is it preferable for us to manage an Idp on their behalf, but for which we provide a UI to add users and adjust permissions? Regardless of who owns the Idp, we will integrate the User Pool with AWS Verified Permissions on our end to handle authorization.
AWS Cognito Multi-tenant Integration | Ok to use Client’s Idp?
|amazon-web-services|amazon-cognito|saml|identity-provider|
I found this exact question before [here](https://stackoverflow.com/questions/24126920/how-to-print-a-jtable-with-a-image-in-the-header) but the only answer on it did not work for me, the solution suggested (that linked to [this](https://stackoverflow.com/questions/10250772/append-text-for-printing-before-and-after-a-jtable/10251531#10251531) other answer) appended each element that I wanted (Image, title/header and table) to a different pages, while I want them all on he same page. I managed to get the image, the header and the date on the same pintable so the only thing left is appending the JTable to this page. Here's the print function: ``` public void printDay(){ Paper p1 = new Paper(); p1.setImageableArea(0, 0, p1.getWidth(), p1.getHeight()); PageFormat pf1 = new PageFormat(); pf1.setPaper(p1); PrinterJob pj = PrinterJob.getPrinterJob(); Book book = new Book(); book.append(new header(date,table), pf1); book.append(table.getPrintable(JTable.PrintMode.FIT_WIDTH,null,null), pf1); pj.setPageable(book); try{ pj.print(); } catch(PrinterException e){ JOptionPane.showMessageDialog(null,"Printer Error","Error",JOptionPane.ERROR_MESSAGE); } } ``` And here's the printable header ``` public class header implements Printable { Font font = new Font("SansSerif", Font.PLAIN, 30); Font font1 = new Font("SansSerif", Font.PLAIN, 10); ImageIcon icon = new ImageIcon("headerLogo.png"); Image image = icon.getImage(); String date; JTable table; public header(String t,JTable T){ date=t; table=T; } @Override public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException { Graphics2D g2d = (Graphics2D) g; g2d.translate(pf.getImageableX(), pf.getImageableY()); g2d.setColor(Color.BLACK); g2d.drawImage(image, 0, 0, null); g2d.setFont(font); g2d.setColor(Color.black); g2d.drawString("Big Title here", 165, 190); g2d.setColor(Color.gray); g2d.setFont(font1); g2d.drawString(date, 450, 210); return Printable.PAGE_EXISTS; } } ``` this is roughly how the pdf comes out after running the code: [![](https://i.stack.imgur.com/u4G4H.png)](https://i.stack.imgur.com/u4G4H.png) I have tried a different approach where I made the JTable a bufferedImage and made it part of the printable, but it had a lot of problems like resizing the image ruining it's resolution making it unreadable (especially in the intended language). So I went back to trying to get the `table.getPrintable()` to work. this is all I'm looking for in my result: [![](https://i.stack.imgur.com/hzV2N.png)](https://i.stack.imgur.com/hzV2N.png)
Assuming that there is equal number of rows in `field_values` for each id in `fields`. That is to say that this query returns a `1`: ``` SELECT CASE WHEN EXISTS( SELECT 1 FROM( SELECT COUNT(*) AS cnt FROM field_values GROUP BY field_id ) subq HAVING MAX(subq.cnt) <> MIN(subq.cnt) ) THEN 0 ELSE 1 END AS test; ``` Otherwise, the solution will require a bunch of FULL JOINS and it will get messy. Especially since MySQL doesn't have a FULL JOIN, so you'd have to UNION ALL a LEFT/RIGHT ANTI JOIN with a RIGHT/LEFT JOIN (respectively). Create the tables an populate with your sample data ``` -- Create your tables DROP TABLE IF EXISTS fields; CREATE TABLE fields (id BIGINT NOT NULL , name VARCHAR(100) NOT NULL ); INSERT INTO fields(id , name ) VALUES(19, 'Finished') , (20, 'Faculty') , (21, 'Characteristic') , (27, 'Photo'); DROP TABLE IF EXISTS field_values; CREATE TABLE field_values(id BIGINT NOT NULL , field_id BIGINT NOT NULL , `value` VARCHAR(100) ); INSERT INTO field_values(id , field_id , `value` ) VALUES(1, 20, 'Math') , (2, 21, 'Good') , (3, 19, '1') , (4, 27, NULL) , (5, 20, 'Biology') , (6, 21, 'Not good') , (7, 19, '0') , (8, 27, NULL); ``` JOIN fields with field_values, keeping track of the order of the id from field_values. As I am also assuming that you want to use this value to determine the final display order. JOIN this result with itself for as many columns as you want in your final result, matching on the appropriate ordinal position. ``` WITH base AS ( SELECT fv.id , fv.`value` , f.name , ROW_NUMBER() OVER(PARTITION BY f.id ORDER BY fv.id ASC) AS rn FROM fields f INNER JOIN field_values fv ON f.id = fv.field_id ) SELECT col1.`value` AS Finished , col2.`value` AS Faculty , col3.`value` AS Characteristic , col4.`value` AS Photo FROM( SELECT `value` , rn FROM base WHERE name = 'Finished' ) col1 INNER JOIN ( SELECT `value` , rn FROM base WHERE name = 'Faculty' ) col2 ON col1.rn = col2.rn INNER JOIN ( SELECT `value` , rn FROM base WHERE name = 'Characteristic' ) col3 ON col2.rn = col3.rn INNER JOIN ( SELECT `value` , rn FROM base WHERE name = 'Photo' ) col4 ON col3.rn = col4.rn; ``` Try it yourself: [db<>fiddle][1] [1]: https://dbfiddle.uk/RQQ2XFzM
change to `pq.StringArray` type, also include `"github.com/lib/pq"` ```go type Conditions struct { gorm.Model ADID uint AgeStart int `json:"ageStart" gorm:"default:0;type:integer"` AgeEnd int `json:"ageEnd" gorm:"default:100;type:integer"` Gender pq.StringArray `json:"gender" gorm:"type:text[]"` Country pq.StringArray `json:"country" gorm:"type:text[]"` Platform pq.StringArray `json:"platform" gorm:"type:text[]"` } ```
I'm using the LAG() function in SQL to calculate the difference between the current month's tips sum and the previous month's tips sum for each taxi driver. However, the LAG() function is returning 0 for every row, even though there should be previous rows to reference. This is the example of the query I am using now: ```sql SELECT td.taxi_id, td.year, td.month, td.tips_sum, (td.tips_sum - LAG(td.tips_sum, 1, 0) OVER (PARTITION BY td.taxi_id ORDER BY td.year, td.month) / NULLIF(LAG(td.tips_sum, 1, 0) OVER (PARTITION BY td.taxi_id ORDER BY td.year, td.month), 0) AS tips_change FROM tips_data td ORDER BY td.tips_sum DESC LIMIT 3 ``` [1]: https://i.stack.imgur.com/IpMkl.png [Example of the result I get right now][1]
For me [Mulli's comment](https://stackoverflow.com/questions/70835066/command-git-hist-error-fatal-option-graph-must-come-before-non-option-arg/78220279#comment134763957_70845491) solved the issue as well: > The removal of the space after format was what fixed this error for me. I left the graph and date options at the end.
I am attempting to implement authentication in Blazor 8 WASM, but I encountered the following error: *InvalidOperationException: JavaScript interop calls cannot be issued during server-side static rendering, because the page has not yet loaded in the browser. Statically-rendered components must wrap any JavaScript interop calls in conditional logic to ensure those interop calls are not attempted during static rendering* In my `App.razor`, I have defined `<Routes @rendermode="InteractiveWebAssembly" />`, and my `Routes.razor` file looks like this:: ``` <Router AppAssembly="@typeof(Program).Assembly"> <Found Context="routeData"> <AuthorizeRouteView RouteData="routeData" DefaultLayout="@typeof(Layout.MainLayout)"> <NotAuthorized> <h1>Sorry!!</h1> <p> You dont have access </p> </NotAuthorized> </AuthorizeRouteView> </Found> <NotFound> <LayoutView Layout="@typeof(Layout.MainLayout)"> <p>Sorry, there's nothing at this address.</p> </LayoutView> </NotFound> </Router> ``` This is my first attempt at implementing authentication in Blazor 8. Previously, I successfully implemented it in Blazor 6 without encountering any issues. In the project setup, I chose 'Interactivity location: Global'. Could this possibly be the source of the problem? I attempted changing the render mode to InteractiveAuto, but this resulted in another error:: *InvalidOperationException: A component of type '<ProjectName>.Client.Routes' has render mode 'InteractiveAutoRenderMode', but the required endpoints are not mapped on the server. When calling 'MapRazorComponents', add a call to 'AddInteractiveServerRenderMode'. For example, 'builder.MapRazorComponents<...>.AddInteractiveServerRenderMode()'* I then added InteractiveServerRenderMode in Program.cs, but the error persisted. Update: I had to make some changes in the project: 1. In `App.razor` change HeadOutlet and Routes to `@rendermode="InteractiveAuto"` 2. In `Program.cs` ``` builder.Services.AddRazorComponents() .AddInteractiveServerComponents() .AddInteractiveWebAssemblyComponents(); ``` and ``` app.MapRazorComponents<App>() .AddInteractiveServerRenderMode() .AddInteractiveWebAssemblyRenderMode() .AddAdditionalAssemblies(typeof(TerraCloud.Client._Imports).Assembly); ``` 3. And of course i had to add my custom AuthenticationStateProvider
You need to proppelly include the url start different ways URL://www Www.skaj.dom HTTP://www etc.
I have this search box which is expanding when activated. However, I would like to make the search box overflow other content on the page. The search box is inside a Bootstrap column - how can I make it expand break out of it? Should be simple, but I can't make it work. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-css --> .search-area { transition: all .3s ease-in; width: 3rem } .search-area:focus-within, .search-area:hover { width: 100%; } .page-searchform { position: relative } .header-search { padding-right: 2rem; border: 0; background-color: #fff; } .header-search-btn { position: absolute; top: 50%; right: 0; transform: translateY(-50%); display: flex; align-items: center; justify-content: center; } /* Presentation onæly */ .row { background: #f8f9fa; margin-top: 20px; } .col { padding: 10px; border: 1px solid #ccc; } <!-- language: lang-html --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"> <div class="container"> <div class="row"> <div class="col col-10"> Column 1 - Make search input overflow me! </div> <div class="col d-flex justify-content-end align-self-center"> <div class="search-area"> <form class="page-searchform" action="" method="get"> <label for="headerSearch" class="visually-hidden"></label> <input name="" id="headerSearch" class="header-search form-control" type="search" placeholder="Search..."> <button class="btn header-search-btn" type="submit" id="headerSearchBtn">Go </button> </form> </div> </div> </div> </div> <!-- end snippet --> [JsFiddle here][1]. [1]: https://jsfiddle.net/965rdbtc/1/
Dropdown menu in a fixed navbar
|drop-down-menu|css-position|navbar|
null
I’m trying to send string of 13 ascii characters from js to php session using ajax, but up on receving string is not the same as i send it, using json.stringyfy and jsondecode does nothing. ``` console.log(plik_T[click]) jQuery.ajax({ type: "POST", url: './Setyb.php', dataType: 'text', data: {send: plik_T[click]}, success: function (obj) { console.log(obj) } }); ``` ``` <?php var_dump($_POST['send']); ?> ``` [enter image description here][1] i tried using json.stringify or changing meta UTF-8 to older versions non of this resolved my problem. Then i tried checking type of variables witch both were string, so that lead my to nothing. what i'm trying to accomplish is to set my Session variable up on user click and use it in next php page [1]: https://i.stack.imgur.com/evOMn.png
I don't believe so. The reason why this is bad in Pandas is that it can trigger consolidation within [BlockManager](https://uwekorn.com/2020/05/24/the-one-pandas-internal.html). If you're inserting N columns, consolidation can cause that to take O(N^2) time due to repeated copying of the blocks. Polars lacks an equivalent of BlockManager. I don't believe there's any situation where it stores two columns within the same backing Arrow array.
I'm going to try to explain this as best as I can with a simplified version of my function: I have this function where I fetch data from a third-party API. Based on the 'single' prop the returned value will either be an a single table object or an array of table objects. I put a generic value on table prop and single prop. But it seems like this doesn't work with how the function is set up at the moment. My goal is to explain that when single is true, it will just return an object of a table and when single is false it will be an array of table objects. What should be changed? function useData<T extends TableNames, S extends boolean>({ query: { table, select = [], filters = [], single = false, limit }, }: UseDataProps<T, S>): UseDataReturn<T, S> { const { data } = getData(); return { data: data[table], }; } interface UseDataProps<T, S> { query: { table: T; select?: string[]; filters?:string[]; single?: S; limit?: number; }; } interface UseDataReturn<T, S> { data: S extends true ? Table<T> : Table<T>[]; } On the single prop I currently get an error like this: Type 'boolean' is not assignable to type 'S'. 'boolean' is assignable to the constraint of type 'S', but 'S' could be instantiated with a different subtype of constraint 'boolean'.
Typescript: returnType based on value 'single' prop
|javascript|reactjs|typescript|typescript-generics|
Can you programmatically generate a link to open a Word document and navigate to a particular location within it (preferably a comment)? Eseentially I want to reproduce the "Create link" feature that is available on comments in the UI, and use a hyperlink. I have inspected the link that is created by "Create link" and it contains a parameter like this: `nav=eyJjIjo2OTk2Njg1ODd9`. I inspected the OpenXML in the Word document and the value isn't in it. I've also tried using bookmarks including their name as an anchor in the url, but that did not work.
Difficulty Embedding Fonts in PowerPoint Slides via insertSlidesFromBase64 Method
|powerpoint|office-js|
|javascript|html|printing|
I have a project that consists in displaying a datamodel using qtreeview from a folder that contains several files. I displayed a treeview of a single file but i couldn't display several treeviews one under the other of several files. here is my main.py : ``` import sys from PyQt5.QtWidgets import * from start_window import StartWindow def main(): app = QApplication(sys.argv) start_window = StartWindow() start_window.show() sys.exit(app.exec_()) if __name__ == '__main__': main() ``` my start_window.py where I need to implement the choose folder function to reach the goal : ``` from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from table_view import Table from odl_parser import ODLParser class StartWindow(QDialog): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle('Open ODL File or Folder') self.resize(600, 400) main_layout = QHBoxLayout(self) self.image_label = QLabel(self) self.image_label.setPixmap(QPixmap('ACLViewer.jpg').scaled(300, 300, Qt.KeepAspectRatio)) main_layout.addWidget(self.image_label) buttons_layout = QVBoxLayout() self.choose_file_button = QPushButton('Choose File', self) self.choose_file_button.clicked.connect(self.choose_file) buttons_layout.addWidget(self.choose_file_button) self.choose_folder_button = QPushButton('Choose Folder', self) self.choose_folder_button.clicked.connect(self.choose_folder) buttons_layout.addWidget(self.choose_folder_button) main_layout.addLayout(buttons_layout) def choose_file(self): file_path, _ = QFileDialog.getOpenFileName(self, "Open ODL File", "", "ODL Files (*.odl)") if file_path: self.open_table_view(file_path) def choose_folder(self): folder_path = QFileDialog.getExistingDirectory(self, "Open Folder Containing ODL Files") if folder_path: # code for the folder def open_table_view(self, file_path): parser = ODLParser(file_path) window = Table(parser) window.setWindowTitle('DM Parsing - ' + file_path) window.show() ``` [I displayed one tree view of a single parsed file , but when I click on choose folder i want to display all the treeviews of all the files in this folder](https://i.stack.imgur.com/PcTT8.png)
displaying several treeviews one below the other
|python|pyqt5|qtreeview|
null
As all the other answers refer to the deprecated (imperative) style of the gradle build files, I try to give an answer that applies to the current situation (as of March 2024, after migrating to the [declarative style][1]), having spent almost a day fixing the build files of our mobile app. First some general hints: * In flutter these errors appear when you run either `flutter build apk` or `flutter build appbundle`, but they are gone (due to caching some intermediate artifacts) when you invoke the command subsequently. You have to invoke `flutter clean` to get them back * Android Studio Iguana has an [AGP Upgrade assistant][2] that may work automatically in some situations, but at least it delivers som hints on why and how to fix things * If you have a flutter project, you may open the android part either using a menu entry or using the file system if the menu entry doesn't show up, giving you some more non-flutter functionality or easier access to gradle sync The error imo is the result of a mismatch of the android gradle plugin and the kotlin standard lib. Now, the current android gradle plugin versions (7.x/8.x for some x) ***do not need to have an explicit dependency on the kotlin standard lib any more***, as they automatically add a matching one. Therefore you can remove the line `implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7"` (or similar - version suffixes don't solve the problem) from dependencies section in `android/app/build.gradle`. When you create a new project using flutter (v 3.19.4, as of now) by invoking `flutter create myproject`, it creates an empty dependencies section in the app module build file (android/app/build.gradle). After migration from the imperative build style, it is recommended to have this plugins section in `android/settings.gradle`: plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" id "com.android.application" version "{agpVersion}" apply false id "org.jetbrains.kotlin.android" version "{kotlinVersion}" apply false } with values for `agpVersion` and `kotlinVersion` set to `7.3.0`and `1.7.10` respectively - current values as of now are `8.3.1` and `1.9.23` (tested with java 17). [1]: https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply [2]: https://developer.android.com/build/agp-upgrade-assistant
Just set the major unit to 1 so the axis counts 1 - 8 by 1s. Add to the x-axis setting ``` chart.set_x_axis({'name': 'X Axis'}) ``` ``` chart.set_x_axis({ 'name': 'X Axis', 'major_unit': 1, # set major unit to 1 }) ``` [![Chart with major unit set to 1][1]][1] <br> You could also add a label to the Trend Line like; ``` # Add line series to the chart chart.add_series({ 'categories': '=Sheet1!$C$1:$C$2', # Adjusted for new data range 'values': '=Sheet1!$D$1:$D$2', # Adjusted for new data range 'line': {'type': 'linear'}, # Adding linear trendline 'data_labels': {'value': False, # Add Data Label 'position': 'below', 'category': True, } }) ``` All this is doing is labeling your trend line, with the lower label sitting on the X-Axis.<br> You'll notice the value is set at start and end points but I don't think there is any means to remove the top textbox using Xlsxwriter. It can be removed manually however simply by clicking the textbox twice and then use the delete key.<br> And for that matter you could manually move the bottom textbox to align with the other numbers too if you like [![enter image description here][2]][2] [1]: https://i.stack.imgur.com/cZLFl.png [2]: https://i.stack.imgur.com/wvyu6.png <br> You could add a verical line using Error Bars but I doesn't give you any addition features. In fact you would have to use the major unit change to see the x-axis value since it has no data label.<br> Apart from that I suppose you could just add a drawing line/textbox on to the Chart.
{"OriginalQuestionIds":[47551528],"Voters":[{"Id":14868997,"DisplayName":"Charlieface","BindingReason":{"GoldTagBadge":"sql-server"}}]}
The game works fine, but its using rectangle shapes and I want to render the snake parts using Sprites. Here is the code (Yeah It's not that clean I just wanted to get this working): ``` #include <SFML/Graphics.hpp> // Graphics module #include <SFML/Audio.hpp> // Sound module #include <iostream> // Basic input/output (for errors) #include <vector> // Dynamic arrays (for snake body) #include <random> // For random food positions class Game { private: sf::Vector2u windowSize; // Size of the game window int a, b; // Length and width of a block sf::RenderWindow window; // Window object for drawing sf::Font font; // Text font sf::Clock clock; // For time measurement std::vector<sf::Vector2i> body; // Snake body (segments as coordinates) sf::Vector2i food; // Food position sf::Vector2i direction; // Snake direction int score; // Player's score bool gameOver; // Game state: finished or not int n, m; // Number of rows and columns float delay, timer; // Update delay and elapsed time sf::Music eat; // Sound effect for eating public: Game(unsigned short x, unsigned short y); // Constructor void start(); // Start the game private: void loop(); // Main game loop void events(); // Process events (keyboard, etc.) void update(); // Update game logic void render(); // Render elements on screen void gameOverScreen(); // Show "Game Over" screen sf::Vector2i getFoodPosition(); // Generate new food position }; int WinMain() { Game game(800, 600); game.start(); } int main() { Game game(800, 600); // Create object with window size 800x600 game.start(); // Call the start function } Game::Game(uint16_t x, uint16_t y) { windowSize = { x, y }; // Save window width and height window.create(sf::VideoMode(windowSize.x, windowSize.y, 1), "Snake"); // Create the window a = 50; // Set block width b = 50; // Set block height n = windowSize.x / a; // Calculate number of horizontal blocks m = windowSize.y / b; // Calculate number of vertical blocks font.loadFromFile("resources/Fonts/sfpro_bold.OTF"); // Load font for text eat.openFromFile("resources/Audio/eating_apple.mp3"); } void Game::start() { body.clear(); // Clear the snake body body.push_back({ 5,3 }); // Head body.push_back({ 4,3 }); // Body segment body.push_back({ 3,3 }); // Tail direction = { 0, 0 }; // Direction food = { getFoodPosition() }; // Initial food position gameOver = false; // Game not over (false) score = 0; // Start score from 0 loop(); // Main loop } void Game::loop() { timer = 0.f; // Accumulated time delay = 0.125f; // Game update delay while (window.isOpen()) { events(); // Handle user inputs (keyboard and mouse) timer += clock.getElapsedTime().asSeconds(); // Add elapsed time in seconds to the timer if (timer > delay) { update(); // Update the game (move snake, etc.) render(); // Render the screen (blocks, snake, food, text, etc.) timer = 0; // Reset timer } clock.restart(); // Restart the clock for the next cycle } } void Game::events() { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Escape) window.close(); else if (event.key.code == sf::Keyboard::Up && (direction.y != 1)) direction = { 0, -1 }; else if (event.key.code == sf::Keyboard::Down && (direction.y != -1)) direction = { 0, 1 }; else if (event.key.code == sf::Keyboard::Left && (direction.x != 1)) direction = { -1, 0 }; else if (event.key.code == sf::Keyboard::Right && (direction.x != -1)) direction = { 1, 0 }; else if (event.key.code == sf::Keyboard::R) /*if (gameOver)*/ start(); } } } void Game::update() { if (gameOver || direction == sf::Vector2i{ 0,0 }) return; sf::Vector2i newHead = body[0] + direction; for (size_t i = 1; i < body.size(); i++) { if (newHead == body[i]) { gameOver = true; return; } } if (newHead.x > n - 1 || newHead.x < 0 || newHead.y > m - 1 || newHead.y < 0) { gameOver = true; return; } if (newHead == food) { body.insert(body.begin(), newHead); food = getFoodPosition(); score++; eat.play(); } else { body.insert(body.begin(), newHead); body.pop_back(); } } void Game::render() { window.clear(); sf::RectangleShape block(sf::Vector2f(a, b)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { block.setPosition(i * a, j * b); int p = (i + j) % 2; block.setFillColor(sf::Color(172 - p * 7, 214 - p * 7, 67 - p * 7, 255)); window.draw(block); } } block.setPosition(food.x * a, food.y * b); block.setFillColor(sf::Color::Red); window.draw(block); for (int i = 0; i < body.size(); i++) { if (i == 0) block.setFillColor(sf::Color::Magenta); else block.setFillColor(sf::Color(0, 71, 181)); block.setPosition(body[i].x * a, body[i].y * b); window.draw(block); } sf::Text scr("Score: " + std::to_string(score), font, 32); scr.setFillColor(sf::Color::White); scr.setPosition(4, 0); window.draw(scr); if (gameOver) gameOverScreen(); window.display(); } void Game::gameOverScreen() { eat.stop(); sf::RectangleShape screen({ float(windowSize.x), float(windowSize.y) }); screen.setPosition({ 0,0 }); screen.setFillColor(sf::Color(0, 0, 0, 100)); sf::Text gameOverText(" Game over!\nPress R to restart", font, 38); gameOverText.setFillColor(sf::Color::White); gameOverText.setPosition((windowSize.x / 2) - 150, (windowSize.y / 2) - 20); window.draw(screen); window.draw(gameOverText); } sf::Vector2i Game::getFoodPosition() { std::random_device randomDevice; std::mt19937 randomNumberGenerator(randomDevice()); std::uniform_int_distribution<int> distX(0, n - 1); std::uniform_int_distribution<int> distY(0, m - 1); sf::Vector2i position; do { position.x = distX(randomNumberGenerator); position.y = distY(randomNumberGenerator); if (std::find(body.begin(), body.end(), position) == body.end()) { return position; } } while (true); } ``` The code above does not have sprites functionality currently, but here is an approach I have tried (which worked for the rendering the sprites): Created a map of Textures and Sprites, loaded the textures from the files, mapped them to the Sprites, and then I had a map of Sprites ready. This part was not that hard I had flaws in my rendering logic most likely. Code was taken from when I had the sprite logic, Im basically using a string to determine which sprite I should load. ``` sf::Vector2i prev = body[i + 1]; // sf::Vector2i next = body[i - 1]; //because i pop the tail and insert new part at the beginning if (next.position.x == prev.position.x) { spriteName = "body_vertical"; //vertical sprite | } else if (next.position.y == prev.position.y) { spriteName = "body_horizontal"; // horizontal -- } else { if (prev.position.x < next.position.x) { if (prev.position.y > next.position.y) { if (current.direction == RIGHT) spriteName = "body_topright"; // start top curve right downwards else if(current.direction == DOWN) spriteName = "body_bottomleft"; // bottom -> left } else if (prev.position.y < next.position.y) { if (current.direction == UP) { spriteName = "body_topleft"; // top -> left } else if(current.direction == RIGHT){ spriteName = "body_bottomright"; // bottom -> right } } } else{ if (prev.position.y > next.position.y) { if (current.direction == LEFT) { spriteName = "body_topleft"; // top -> left } else if(current.direction == DOWN){ spriteName = "body_bottomright"; // bottom -> right } } else if (prev.position.y < next.position.y) { if (current.direction == DOWN) spriteName = "body_topright"; // top -> right else if(current.direction == LEFT) spriteName = "body_bottomleft"; // bottom -> left } } } ``` Link for sprites: [opengameart.org/content/snake-game-assets](https://opengameart.org/content/snake-game-assets). Basically, what I want is some feedback on how to choose the correct sprite to load and for which situation (head and tail would be appreciated too ). Thanks!
How to render sprites for a snake game using SFML and C++
|c++|logic|rendering|sprite|sfml|
null
An easy way to do what you are asking is with [`QtConcurrent::run`][1] and an object. The way it goes is: 1. Start a function in a separate thread using `QtConcurrent::run`. What you get from that is a [`QFuture`][2] that you can inquire to get the execution status.<br/>As you will see in the documentation, you can make that work with a thread pool created beforehand. 2. You have 2 ways to detect the execution has ended: - Call `QFuture::waitForFinished`: it will block your thread until the execution is done.<br/>This can be useful if you are already in a worker thread, starting tasks in other worker threads; however, it is safe to say you should never want to call it in the main thread and block it. - Have an object send a signal from the worker thread, caught in the main thread. In that case, the main thread does not get blocked. Here is a quick example that runs 5x a function in worker threads. A `taskNo` (from 1 to 5) is passed from the main thread to the worker thread in `QtConcurrent::run` and back in signals.<br/> The tasks basically consist in printing the id of the thread executing them. There are also a number of lines that print what is executed in the main thread. For illustration's sake, this example works with a single worker object.<br/> You can work with separate worker objects though, but you'll need to create pointers inside the `for` loop, change their thread affinity in `QtConcurrent::run` (instead of just printing to the screen like I did), do the connection and only then start the work. In any case, always explicitly mark your connection with `Qt::QueuedConnection`. That may be what `QObject::connect` will do by default but at least, it makes your intention clear. In the `main` function, I have put comments in 3 places for illustration: - 1<sup>st</sup> comment: you may set up your connection so that it disconnects after the first `taskCompleted` signal is emitted. - 2<sup>nd</sup> comment: a thread pool is created in `main`. I have made it so that it is **not** used though, that is unless you uncomment it.<br/>BTW, pay close attention to the thread that executes `QtConcurrent::run` vs `QFuture::then` and how tasks won't start until the `QFuture` chain is over. - 3<sup>rd</sup> comment: This is an illustration of what `QFuture::waitForFinished` does. If you were to uncomment it, work would still be done in the worker thread but with no parallelism: since it is blocking the main thread before it can create the next worker thread (see my comment above). `Worker.h` ```c++ #include <QObject> class Worker : public QObject { Q_OBJECT public: void run(int taskNo); signals: void taskCompleted(Qt::HANDLE, int); }; ``` `Worker.cpp` ```c++ #include "Worker.h" #include <QtCore/QDebug> #include <QtCore/QThread> void Worker::run(int taskNo) { qDebug() << "Executing task" << taskNo << "in worker thread" << QThread::currentThreadId(); emit taskCompleted(QThread::currentThreadId(), taskNo); } ``` `main.cpp` ```c++ #include <QtCore/QFuture> #include <QtCore/QThread> #include <QtCore/QThreadPool> #include <QtConcurrent/QtConcurrentRun> #include "Worker.h" int main(int argc, char* argv[]) { QApplication a(argc, argv); QThreadPool pool; pool.setMaxThreadCount(2); QObject catchObject; Worker worker; QObject::connect(&worker, &Worker::taskCompleted, &catchObject, [](Qt::HANDLE workerThreadId, int taskNo) { qDebug() << "Message from main thread" << QThread::currentThreadId() << ": Task" << taskNo << "completed in thread" << workerThreadId; } , static_cast<Qt::ConnectionType>(Qt::QueuedConnection /*| Qt::SingleShotConnection*/) //Uncomment to catch only the first task to complete. ); qDebug() << "Tasks will now be created from main thread" << QThread::currentThreadId(); for (int taskNo = 1; taskNo <= 5; ++taskNo) { QtConcurrent::run( /*&pool,*/ //Uncomment to work with the 2 threads of the thread pool. [](int taskNo) -> int { qDebug() << "Hello from worker thread" << QThread::currentThreadId() << ", starting task" << taskNo; return taskNo; }, taskNo ).then( [&worker](int taskNo) { worker.run(taskNo); } )/*.waitForFinished()*/; //Uncomment to make the main thread wait for the task to finish before resuming the loop. } return a.exec(); } ``` [1]: https://doc.qt.io/qt-6/qtconcurrentrun.html [2]: https://doc.qt.io/qt-6/qfuture.html [3]: https://doc.qt.io/qt-6/qobject.html#thread-affinity
I try three methods to get sum of floats. one method is pandas sum, another one is use for loop, the last one is using math.fsum. It looks like the last method get the right results. but the first and second method get different values. ``` import pandas as pd import math def main(): data = [ 61.1, 19.3, 15.7, 3.07, .255, .158, .102, .072, .0608, .0048, .0416, .0368, .0288, .0128, .0112, .0096, .0096, .008, .0048, .004, .004, .0032, .0024, .0006 ] df = pd.DataFrame(data,columns=['value']) print(df['value'].sum()) sum = 0 for x in data: sum += x print(sum) print(math.fsum(data)) main() ``` Current results: ``` 99.99999999999999 100.00000000000004 100.0 ``` Expected results: ``` 100.0 100.0 100.0 ```
calculate sum of floats behavior werid
|python|pandas|
null