instruction
stringlengths 0
30k
⌀ |
---|
'connections' is deprecated. The declaration was marked as deprecated here |
|connection|deprecated|peerjs| |
null |
```
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes),
provideHttpClient(),
{provide:SomeOtherService}
],
};
``` |
You can't execute **operating system** commands with `execute immediate`.
Why do you think you have to do that *dynamically*? Everything contained in command you posted is *static*, so why wouldn't you run it as designed, from operating system? If you want to schedule it, create a *batch* file and schedule it using your operating system scheduling utility (Task Scheduler on MS Windows).
On the other hand, you *can* run operating system script from PL/SQL; use `dbms_scheduler` package by specifying `job_type => 'executable'`.
Another option of performing database export (as it seems that you don't want to run *any* operating system command, but specifically `expdp`, consider using `dbms_datapump` package which is designed for such a purpose. |
Trying to send SMS to telegram group whenever we receive new SMS. I tried to run below code but when new SMS arrives, there is no activity.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONObject;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private static final String TELEGRAM_BOT_TOKEN = "1234:ABC";
private static final String TELEGRAM_CHAT_ID = "-5678";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BroadcastReceiver smsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
String messageBody = smsMessage.getMessageBody();
sendToTelegram(messageBody);
}
}
}
}
};
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver, filter);
}
private void sendToTelegram(String message) {
new Thread(() -> {
try {
URL url = new URL("https://api.telegram.org/bot" + TELEGRAM_BOT_TOKEN + "/sendMessage");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setDoOutput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("chat_id", TELEGRAM_CHAT_ID);
jsonParam.put("text", message);
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(jsonParam.toString());
wr.flush();
int responseCode = urlConnection.getResponseCode();
Log.d("TelegramResponse", "Response Code: " + responseCode);
urlConnection.disconnect();
} catch (Exception e) {
Log.e("TelegramError", "Error sending message to Telegram: " + e.getMessage());
}
}).start();
}
}
I sent a test message to the number where the app is installed but when new SMS arrives, there is no activity. Not sending anything in telegram and o Log detected in logcat |
SQL Server: this program requires a machine with at least 2000 megabytes of memory |
|sql-server|docker| |
For the Same wifi connection of computer and mobile.
All these answers are right but they did not mention that the IP address must be the wifi IP.
if you run the program locally and your wifi is from a **Wi-Fi router** then the IP should be Wi-Fi IP.
[1]
[1]: https://i.stack.imgur.com/Q1sW8.png |
Trying to apt update and I am getting this, due to this I cannot install playwright as it fails when I do so
I get this every time i do so
`
Err:13 https://download.docker.com/linux/debian jammy Release
404 Not Found [IP: 108.158.245.93 443]
...
Reading package lists... Done
E: The repository 'https://download.docker.com/linux/debian jammy Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
`
I tried changing the docker.list value but no change here. also can anybody point me to where I can change or remove `Err:13 https://download.docker.com/linux/debian jammy Release
404 Not Found [IP: 108.158.245.93 443]` |
Docker repository does not have a release file for apt-get update on jammy release |
|docker|playwright|ubuntu-22.04| |
null |
**Bundle version**: 6.1
**Symfony version**: 5.4
**PHP version**: 8
Hello,
I wish to add two-factor authentication to my project and I came across your solution which seems great to me. Initially, the installation seemed straightforward, but I must be missing something because my authentication still works with email and password as usual.
I follow the installation guide and this is a part of my security.yaml :
```
main:
lazy: true
provider: app_user_provider
remember_me:
secret: '%kernel.secret%'
token_provider: 'Symfony\Bridge\Doctrine\Security\RememberMe\DoctrineTokenProvider'
lifetime: 68400
form_login:
# "login" is the name of the login route
login_path: login
check_path: login
enable_csrf: true
logout:
path: logout
# where to redirect after logout
target: login
two_factor:
auth_form_path: 2fa_login # The route name you have used in the routes.yaml
check_path: 2fa_login_check # The route name you have used in the routes.yaml
```
My SecurityController look like this :
```
#[Route('/login', name: 'login')]
public function index(AuthenticationUtils $authenticationUtils): Response
{
if($this->isGranted('ROLE1') || $this->isGranted('ROLE2') ){
return $this->redirectToRoute('home_master_user');
}
elseif($this->isGranted('ROLE3') && $this->isGranted('ROLE')) {
return $this->redirectToRoute('home');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('login/index.html.twig', [
'last_username' => $lastUsername,
'error' => $error
]);
}
```
To be honest, I don't understand why it's not working even after following the various tutorials I've read.
Regards |
I know how to make a substitution :
```
${var//Pattern/Replacement}
```
I know how to capitalize :
```
${var^^}
```
but how can I achieve both ?
Thanks.
I tried
```
${var^^//Pattern/Replacement}
```
and
```
${var//Pattern/Replacement^^}
```
but unluckily
EDIT :
the code I have :
```
local file_name[1]="All files from ${target/\/*} folder"
```
with `target="xfce/*"`
What I want is, when I echo `${file_name[1]}`, it shows "All files from XFCE folder" |
I am trying to update an alpine x-data value with my stimulus controller
The final goal being to trigger the openDetail on a leaflet marker
My controller
```js
import {Controller} from '@hotwired/stimulus'
import L from 'leaflet'
import Alpine from 'alpinejs'
/**
*
*/
export default class extends Controller {
connect() {
Alpine.data('isOpen', false)
window.Alpine = Alpine
Alpine.start()
this.alpine = Alpine
openDetail() {
this.alpine.data('isOpen', true))
}
}
```
My template
```html
<div x-data="{ isOpen: false}" data-controller="alpine">
<button data-action="click->alpine#toggle" @click="isOpen = true">
Toggle
</button>
<p x-show="isOpen" x-cloak>Content to toggle</p>
</div>
```
Thanks |
how to change a alpinejs data value with stimulus controller |
|twig|alpine.js|stimulusjs| |
You need to delete the `vendor` folder if you already have one in your project, and run `composer install`.
Then restart your server. |
I had the same issue. You can solve this by downgrading the SentenceTransformers library. This issue is due to the new release of SentenceTransformers version 2.4.0. If you downgrade to 2.3.1 the issue is resolved. |
I'm using the extension "Custom right-click menu" to add a custom site search. When I use the context menu, it adds spaces to the search term. I need it to have a +.
```
var search = crmAPI.getSelection() || prompt('Please enter a search query');
var url = 'https://www.subetalodge.us/list_all/search/%s/mode/name';
var toOpen = url.replace(/%s/g,search);
window.open(toOpen, '_blank');
```
|
How do I add a custom delimiter to this context menu search? |
Running a shell script file marked as executable results in creating a system process executing it.
It appears to me that it is not possible to determine from within the script if the executable of the interpreter used to run the script is the executable ASSUMED to be used as interpreter.
There are ways to query some data from within the script, but if an alien executable also provides them knowing that they should be there available for queries, there is no way to know if the script is run by the assumed executable or by the alien one which somehow found a way to become executed instead.
Is there a way in Linux to determine FOR SURE which shell executable file is running a shell script?
Or is it necessary to modify the source code of the interpreter in a way which makes it then possible by the scripts to be sure they are run by the interpreter executable they were designed to be run with?
I would like to gain some deeper understanding of how a Linux system works under the hood - this is the reason why do I want to get an answer to this question in hope it would help me on the way to better understanding of the system I am using.
My question IS NOT a duplicate of [https://stackoverflow.com/questions/5166657/how-do-i-tell-what-type-my-shell-is][1] . I know how to ask in script which shell is running it. My question is about identifying FOR SURE which executable FILE was used in loading it to memory in order to execute the script file?
And the case of dash or bash depending on shebang in the script mentioned by me in the comments was only a trigger which started me on the path to deeper understanding. In between seems obvious to me that relying on usage of the in shebang put information is a bad idea ... it depends ... so better not rely on it at all.
[1]: https://stackoverflow.com/questions/5166657/how-do-i-tell-what-type-my-shell-is |
Ktor Websocket session closes by itself. Is there a way to keep the opened session active? |
|kotlin|websocket|server|ktor| |
null |
The comments should be easy enough to follow.
set.seed(688396493)
N <- 100 # coins
n <- 100 # turns
ps <- 0.5 # probability of selection
pf <- 0.4 # probability of swapping sides conditioned on a flip
pt <- ps*pf # unconditional probability of swapping sides in a turn
# Initialize the cumulative heads matrix. Turns along rows, coins along columns.
heads <- matrix(0L, n, N, 0, list(paste0("turn", 1:n), paste0("coin", 1:N)))
# state after the first turn (heads = T, tails = F)
heads[1,] <- s <- sample(!0:1, N, 1)
# pre-calculate the number of coins that will swap sides on each turn
nt <- rbinom(n, N, pt)
# complete the simulation
for (i in 2:n) {
idx <- sample(N, nt[i])
s[idx] <- !s[idx]
heads[i,] <- heads[i - 1,] + s
}
# calculate the tails
tails <- 1:n - heads
Results of the first 10 turns of the first 10 coins:
heads[1:10, 1:10]
#> coin1 coin2 coin3 coin4 coin5 coin6 coin7 coin8 coin9 coin10
#> turn1 1 1 1 1 0 1 1 0 1 1
#> turn2 2 2 1 2 0 2 2 0 2 2
#> turn3 3 3 2 3 0 3 3 0 2 2
#> turn4 4 4 3 4 0 3 3 1 2 3
#> turn5 5 5 4 5 0 3 3 2 2 3
#> turn6 5 5 5 5 0 3 4 3 2 3
#> turn7 6 5 5 5 0 3 4 4 2 3
#> turn8 7 5 5 6 0 3 4 5 2 3
#> turn9 8 5 5 7 0 3 4 6 2 3
#> turn10 9 5 6 7 0 4 5 7 2 3
tails[1:10, 1:10]
#> coin1 coin2 coin3 coin4 coin5 coin6 coin7 coin8 coin9 coin10
#> turn1 0 0 0 0 1 0 0 1 0 0
#> turn2 0 0 1 0 2 0 0 2 0 0
#> turn3 0 0 1 0 3 0 0 3 1 1
#> turn4 0 0 1 0 4 1 1 3 2 1
#> turn5 0 0 1 0 5 2 2 3 3 2
#> turn6 1 1 1 1 6 3 2 3 4 3
#> turn7 1 2 2 2 7 4 3 3 5 4
#> turn8 1 3 3 2 8 5 4 3 6 5
#> turn9 1 4 4 2 9 6 5 3 7 6
#> turn10 1 5 4 3 10 6 5 3 8 7 |
We are trying to build an add-on to automatically insert an image when user clicks on 'compose' / 'reply' / 'forward'. Unfortunatelly, we found that the only trigger available is to show a UI which the user then needs to click, and only then the image is inserted.
We need to avoid the extra click, meaning:
User goes to Gmail
User clicks Compose
Result: The compose button triggered the images insertion.
Can anyone of the experts here help me with this innovative trigger?
Thank you!
We tried to use the compose triggers like this, but as expected is showed us an extra button to insert signature, only on click the image is inserted.
We are expecting to click on compose and the images is automatically inserted.
[appscript.json](https://i.stack.imgur.com/w5tgD.png)
[code.js](https://i.stack.imgur.com/jJLeI.png) |
SMS not being sent in telegram and no log registered |
|java|android|broadcastreceiver|smsmanager| |
{"Voters":[{"Id":2357112,"DisplayName":"user2357112"},{"Id":523612,"DisplayName":"Karl Knechtel"},{"Id":1974224,"DisplayName":"Cristik"}],"SiteSpecificCloseReasonIds":[11]} |
I got the same problem and spent two whole days to solve it.<br>This is my solution: <br>
First of all you should define the coordinates(x,y) of the point around which the ellipse should rotate, this way: <br>
`ellipse.setTransformOriginPoint(QPointF(?, ?))`<br>
then you can use the `setRotation()` to rotate ellipse<br>
the whole code can be seen below:<br>
__author__ = 'shahryar_slg'
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MainWindow(QDialog):
def __init__(self):
super(QDialog, self).__init__()
self.view = QGraphicsView()
self.scene = QGraphicsScene()
self.layout = QGridLayout()
self.layout.addWidget(self.view, 0, 0)
self.view.setScene(self.scene)
self.setLayout(self.layout)
self.ellipse = QGraphicsEllipseItem(10, 20, 100, 60)
self.ellipse.setTransformOriginPoint(QPointF(100/2+10, 60/2+20))
self.ellipse.setRotation(-60)
self.scene.addItem(self.ellipse)
# I created another ellipse on the same position to show you
# that the first one is rotated around it's center:
self.ellipse2 = QGraphicsEllipseItem(20, 20, 100, 40)
self.scene.addItem(self.ellipse2)
self.update()
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
**Pay attention to the way I've calculated the center of the ellipse.** |
I am using `react-native-date-picker:^4.4.0` package. When I've updated my project's react-native version to `0.73.3` from `0.62.7` it stoped working properly. Now, when I tap the field to open picker it gives me an error both on Android and IOS.
```
ERROR TypeError: null is not an object (evaluating 'NativeModule.openPicker')
```
|
react-native-date-picker does not work after update |
|android|ios|react-native|mobile|datepicker| |
Reference Every Nth Cell
-
[![enter image description here][1]][1]
**Usage**
<!-- language: lang-vb -->
Sub Test()
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
Dim rg As Range:
Set rg = ws.Range("P2", ws.Cells(ws.Rows.Count, "P").End(xlUp))
' Names
Dim nameBank As Range: Set nameBank = RefNthCellsInColumn(rg, 3)
nameBank.Copy ws.Range("Q2")
' Numbers
Dim numberBank As Range: Set numberBank = RefNthCellsInColumn(rg, 3, 2)
numberBank.Copy ws.Range("R2")
MsgBox nameBank.Cells.Count & " cells in range """ _
& nameBank.Address(0, 0) & """.", vbInformation
End Sub
**The Function**
<!-- language: lang-vb -->
Function RefNthCellsInColumn( _
ByVal singleColumnRange As Range, _
ByVal Nth As Long, _
Optional ByVal First As Long = 1) _
As Range
Dim rg As Range, r As Long
For r = First To singleColumnRange.Cells.Count Step Nth
If rg Is Nothing Then
Set rg = singleColumnRange.Cells(r)
Else
Set rg = Union(rg, singleColumnRange.Cells(r))
End If
Next r
Set RefNthCellsInColumn = rg
End Function
[1]: https://i.stack.imgur.com/R5wwS.jpg |
Actually, after a few more tries, I realized the stages were not good. It works with:
include:
- component: gitlab.com/components/opentofu/validate-plan-apply@0.17.0
inputs:
version: 0.17.0
opentofu_version: 1.6.1
root_dir: provisioning/
state_name: iam
variables:
TF_STATE_NAME: iam
stages: [validate, build, deploy]
**But I still don't find a solution for SAST.**
=> `- template: Jobs/SAST-IaC.latest.gitlab-ci.yml` does not works. |
Does anyone know how to get rid of these thick lines from Google Maps on an Android emulator? I'm just running the default Google Maps Activity from the wizard (also see it on other projects). When I deploy to an actual device, and not an emulator, the street lines do not look like this.
[![Google Map zoomed in with thick lines][1]][1]
If I zoom out far enough, then it goes back to normal
[![Google Map zoomed out with normal thickness of lines][2]][2]
[1]: https://i.stack.imgur.com/A0Iuj.png
[2]: https://i.stack.imgur.com/F4gfR.png
Here's the code for the activity
```
private lateinit var mMap: GoogleMap
private lateinit var binding: ActivityMapsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMapsBinding.inflate(layoutInflater)
setContentView(binding.root)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
val coordinates = LatLng(39.999495, -83.012685)
mMap.addMarker(MarkerOptions().position(coordinates).title("Marker"))
mMap.moveCamera(CameraUpdateFactory.newLatLng(coordinates))
}
``` |
Google Maps on Android Emulator Thick Lines |
|android|google-maps| |
It depends on the lifetime of the variables.
If they are static variables, the initializer must be constant.
```c
int a = 1;
int b = 2;
int c = 3;
int array[] = { a, b, c }; // XXX Error
int main( void ) {
}
```
```c
const int a = 1;
const int b = 2;
const int c = 3;
int array[] = { a, b, c }; // ok
int main( void ) {
}
```
If they are automatic variables, this is allowed.
```c
int main( void ) {
int a = 1;
int b = 2;
int c = 3;
int array[] = { a, b, c }; // ok
}
``` |
You enumerate over the results, but you *return* a response from the moment you get the first item. This thus means that it returns the result from *that* item.
You thus should first collect all results, and then dump that blob:
<pre><code>def say_hello(request):
results = <b>list(</b>menu_items('https://natureshair.com.au/')<b>)</b>
return JsonResponse({'results': results})</code></pre>
or for two websites:
<pre><code>def say_hello(request):
results = list(
item
<b>for link in ('https://natureshair.com.au/', 'https://www.google.com/')</b>
for item in menu_items(link)
)
return JsonResponse({'results': results})</code></pre> |
Gmail add-on compose trigger |
|google-apps-script|gmail|gmail-api|gmail-contextual-gadgets| |
null |
I currently have an issue with `HorizontalPager` swipe behavior, when I try to swipe back the `HorizontalPager` also swipe to the next image. Here is the GIF of it. Does any one has any idea? BTW I'm using compose UI version `1.3.3`
HorizontalPager(
pageCount = pageCount,
state = pagerState,
modifier = Modifier.fillMaxSize()
) { page ->
DefaultAsyncImage(
modifier = Modifier.fillMaxSize(),
imageUrl = urls[page],
aspectRatio = PRODUCT_LAYOUT_ASPECT_RATIO
)
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/nxBh5.gif |
Compose HorizontalPager swipe conflict with swipe back event |
|android|android-jetpack-compose|horizontal-pager| |
## 2024 Update
On an Ubuntu based distro, use the following steps:
```
❯ curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
❯
❯ echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
❯
❯ sudo apt update
❯
❯ sudo apt install redis-tools
❯
``` |
I had a similar problem where auto-generated tests were failing about half the time, and I was able to figure out why. This is happening most likely because tests have to be setup similar to components, such as requiring the appropriate imports, and this was not done in my tests.
I was able to fix many problems by adding RouterTestingModule, and the Module in which the component sits (for example, Admin Module), and sometimes the very base module (which in my case was the App Module).
So for the TestBed, I had to insert imports, something like this:
```
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ // <-- include the imports
AppModule,
AdminModule,
RouterTestingModule
],
declarations: [ MappingTemplateEditComponent ]
})
.compileComponents();
});
```
For your case, add in the module in which login and header page components are in. And maybe App Module if you have that. Most likely, this will not fix all of your problems, because there will be additional things you will have to do to make the tests fully set up. But it will at least get rid of the usual suspects and get you closer to getting all tests passed. |
In Android, it's working fine.
Steps to reproduce the issue in iOS,
(pre-condition)
The iOS app should be killed
1. Lock the device
2. Receive the VoIP incoming call
At the time of ringing VoIP call we are getting a silent push notification from our server with the payload of contentAvailable: true
File name: **FLTFirebaseMessagingPlugin.m** in *firebase_messaging* plugin
As per the iOS guidelines flutter messaging package invoking the below method :
`- (BOOL)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler`
The app is terminated when the below **code** is executed.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/tqh3k.png |
scheb/2fa not detected/working on my project |
|php|symfony|yaml|two-factor-authentication|symfony5.4| |
Have you tried adding position:relative to the nested div?
[Fiddle with CSS example][1]
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.container-div {
padding: 10px 10px 0;
background-color:#c3c3c3;
width:200px;
}
.child-div {
display: inline-block;
width: 100px;
height: 60px;
position:relative;
top:-20px;
border: 1px solid #efefef;
background-color: #f5f5f5;
}
<!-- language: lang-html -->
<br><br><div class="container-div">
<div class="child-div">
This div appears to be nested.
</div>
</div>
<!-- end snippet -->
[1]: https://jsfiddle.net/S2Kaw/2/
|
I want to know what are the collation type is used for viewing emoji or accept in DB what the reason behind it and how its work?
I need a proper explain about that pls help out of this and moreover what the reason certain collation accept and other why it can't?
|
|database|collation| |
I need a function that, given two or more polygons, can divide the sides into the intersections of the sides as in the figure, how would I do it?
An example would be the meeting of two sides
[(0.0, 0.0), (0.0, 10.0)]
[(0.0, 5.0), (0.0, 7.0)]
which should result in 3 segments " [[(0.0, 0.0), (0.0, 5.0)], [(0.0, 5.0), (0.0, 7.0)], [(0.0, 7.0), (0.0, 10.0)]] "

I tried with two false polygons with only 1 side for the test, but without success.
```
from shapely.geometry import LineString
def encontrar_segmentos_de_reta(poligono1, poligono2):
segmentos = []
for i in range(len(poligono1)):
p1 = poligono1[i]
p2 = poligono1[(i + 1) % len(poligono1)]
for j in range(len(poligono2)):
q1 = poligono2[j]
q2 = poligono2[(j + 1) % len(poligono2)]
if intersecta(p1, p2, q1, q2):
intersecao = encontrar_intersecao(p1, p2, q1, q2)
if intersecao:
segmentos.append([p1, intersecao])
segmentos.append([intersecao, p2])
segmentos.append([q1, intersecao])
segmentos.append([intersecao, q2])
return segmentos
def intersecta(p1, p2, q1, q2):
line1 = LineString([p1, p2])
line2 = LineString([q1, q2])
return line1.intersects(line2)
def encontrar_intersecao(p1, p2, q1, q2):
line1 = LineString([p1, p2])
line2 = LineString([q1, q2])
intersection = line1.intersection(line2)
if intersection.is_empty:
return None
elif intersection.geom_type == 'Point':
return list(intersection.coords)
elif intersection.geom_type == 'LineString':
return list(intersection.coords)[0] # Use o primeiro ponto da linha
def RemoverRepetidos(paredes):
novo_paredes = []
for segmento in paredes:
if segmento[0]!=segmento[1]:
novo_paredes.append(segmento)
return novo_paredes
# Definindo os polígonos de entrada
poligono1 = [(0.0, 0.0), (0.0, 10.0)]
poligono2 = [(0.0, 5.0), (0.0, 7.0)]
# Encontrar segmentos de reta formados pela interseção dos lados dos polígonos
segmentos = encontrar_segmentos_de_reta(poligono1, poligono2)
segmentos = RemoverRepetidos(segmentos)
print("Segmentos de reta formados:", segmentos)
``` |
I have tables that have hundreds of rows displayed per page, and I want to send only the updated data to the backend so that not too much data will be sent. There is a "save changes" button at the top, and currently I am not using a form element
What I currently do is, I give each `<tr>` the row id from the database as a `dataset` attribute, and listen to changes on inputs, then if one of the values of a row is changed, I add this entire row and its inputs to an object that holds all the changed rows
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let updatedData = {};
let table1Form = document.querySelector('#table_1');
table1Form.addEventListener("change", (event) => {
let row = event.target.closest('tr');
let rowId = row.dataset.dbRowId;
let rowInputs = row.querySelectorAll('input');
updatedData[rowId] = {};
rowInputs.forEach((input) => {
if (input.type === "checkbox") {
updatedData[rowId][input.name] = input.checked;
} else {
updatedData[rowId][input.name] = input.value;
}
});
});
document.querySelector("#save-changes").addEventListener("click", () => {
console.log(updatedData);
});
<!-- language: lang-html -->
<button id="save-changes">Save Changes</button>
<table id="table_1">
<tr data-db-row-id="1">
<td><input type="text" name="email" value="foo@example.com" />
<td><input type="text" name="name" value="Foo" />
<td><input type="checkbox" name="show" checked="checked" />
</tr>
<tr data-db-row-id="2">
<td><input type="text" name="email" value="bar@example.com" />
<td><input type="text" name="name" value="Bar" />
<td><input type="checkbox" name="show" />
</tr>
</table>
<!-- end snippet -->
But it feels cumbersome, and I need to check for each type of input (in the above example I had to have distinction between the `checkbox` and the `text` inputs because they are evaluated differently
Perhaps there's a better way to do that (with the use of Form Data maybe as well?) |
What is a proper way to get the changed values from a table with hundreds of rows? |
|javascript|html| |
Pure-Python Kerberos implementations do exist, but it is very uncommon to use them<sup>1</sup>; the most relevant SMB client library that you might be using, `smbprotocol`, still relies on the python-gssapi and python-krb5 modules which expect system-wide GSSAPI and Kerberos libraries to be present, and I'm not aware of any drop-in replacement that would be suitable.
<sup>1</sup> (Partly this is because the easiest way to interoperate with system Kerberos is to just use system Kerberos – e.g. Java often has the issue of not being able to read tickets that system Kerberos libraries have stored, and e.g. the commonly used "native Go" Kerberos implementation doesn't even try to interoperate much at all, which largely defeats one of the main advantages of Kerberos.)
But as far as I know, however, you _can_ deploy system libraries as part of AWS Lambda functions (that is to say: I just skimmed the Lambda FAQ and it specifically says "You can launch processes using any language supported by Amazon Linux" and even "You can include your own copy of a library in order to use a different version than the default one provided by AWS Lambda"), so it should be possible to just bundle MIT Krb5 or whatever you need. |
[firebase_messaging]: iThe device has been locked and the silent push notification received at that time iOS app is getting crashed |
**[stackprotector's helpful answer](https://stackoverflow.com/a/78171751/45375) is definitely the best solution**: it wraps `Remove-Item` in _all_ aspects, including tab-completion, streaming pipeline-input support, and integration with [`Get-Help`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/get-help):
To offer a **simpler - but limited - alternative**, which is **easier to author**, however:
```
Remove-Item -ErrorAction Ignore Alias:rm # remove the built-in `rm` alias
# Simple (non-advanced) wrapper function
function rm {
<#
.SYNOPSIS
Wrapper for Remove-Item with support for -rf to mean -Recurse -Force
#>
param([switch] $rf) # Custom -rf switch
# If -rf was specified, translate it into the -Recurse -Force switches
# via a hashtable to be used for splatting.
$extraArgs = if ($rf) { @{ Recurse=$true; Force=$true } } else { @{} }
# Invoke Remove-Item with any extra arguments and all pass-through arguments.
if ($MyInvocation.ExpectingInput) { # pipeline input present
$input | Remove-Item @args @extraArgs
} else {
Remove-Item @args @extraArgs
}
}
```
Limitations:
* No tab-completion support for `Remove-Item`'s parameters (you do get it for `-rf`, and by default the files and directories in the current directory also tab-complete)
* Only simple `Get-Help` / `-?` output, focused on `-rf` only (conversely, however, forwarding the help to `Remove-Item`, as in the proxy-function approach doesn't describe the custom `-rf` parameter at all).
* While pipeline input is supported, it is collected in full up front, unlike with the proxy-function approach.
Note:
* The solution relies on [splatting](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Splatting) to pass arguments (passing arguments stored in a hashtable or array variable by prefixing that variable with `@`).
* In *non*-[advanced](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Functions_Advanced) functions, such as in this case, the [automatic `$args` variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Automatic_Variables#args) contains all arguments that weren't bound to declared parameters, and `@args` passes them through via splatting.<sup>[1]</sup>
* Splatting an _empty_ [hashtable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Hash_Tables) (`@{}`) results in _no_ arguments being passed, as desired (ditto for an empty _array_, `@()`).
* `$MyInvocation.ExpectingInput` indicates whether pipeline input is present, which can then be enumerated via the [automatic `$input` variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Automatic_Variables#input); as noted, doing so requires collecting all input objects in memory first, given that functions without a `process` block are only executed _after_ all pipeline input has been received (i.e., they execute as if their body were in an `end` block).
---
<sup>[1] Note that the automatic `$args` variable contains an _array_, and while splatting with an array - as opposed to with a [hashtable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Hash_Tables) - normally doesn't support passing _named_ arguments through (those preceded with their target parameter name, e.g. `-Path *.txt`), `$args` has magic built into it that supports that too. For the details of this magic, see the footnote of [this answer](https://stackoverflow.com/a/71037345/45375).</sup> |
first of all: I'm not a data scientist, so I might use wrong terms here and there. My apologies upfront :).
**First some details of my goal**:
I have a very complex algorithm for which I want to optimize the execution time. For my tests, I have quite a few binary switches that enable/disable a certain code path. Other parameters (e.g. integer-valued in a certain range [a,b]) are only active if a binary switch is active. Hence, if the corresponding switch is off, it doesn't make sense to permutate over the dependent parameter, as this would result in the identical code being executed.
**Optimization Script**:
I plan to use one or more optimizers available in Python. Since the problem is complex, execution times are long and there might be significant local extrema caused by certain parameter values, I started with the Bayesian optimizer implemented by `gp_minimize()` in the `scikit.optimize` package.
For contraining allowed parameter sets, I see (roughly) the following two options:
1. Provide some additional info or a callback to the optimizer that tells it, if a parameter set is valid or not. Or in different terms, which values a certain parameter can take given the currently selected value of the other binary switch parameters.
2. Penalize invalid parameter sets in the objective function, e.g. by returning a huge value. However, I'm concerned that this would push the optimizer in a wrong direction (e.g. in case that it alters several parameters at once it wouldn't know that only a single parameter lead to the penalty)
**Question**:
Could someone give me some hints how to achieve this? I guess there are packages that allow providing some callbacks, but `gp_minimize()` doesn't seem to be one of these.
Are my concerns correct with option (2)?
Many thanks in advance |
In a hyper-parameter optimization with scikit gp_minimize(), how to constrain parameters that depend on each other |
|optimization|scikit-optimize| |
I got the following error `ValueError: 4.39.0.dev0 is not valid SemVer string` in my code:
```python
from GLiNER.gliner_ner import GlinerNER
gli = GlinerNER()
```
Complete error message:
```python
File ~/.../GLiNER/gliner_ner.py:8, in GlinerNER.__init__(self, labels)
7 def __init__(self, labels = ["date","time", "club", "league"]):
----> 8 self.model = GLiNER.from_pretrained("urchade/gliner_base")
9 self.labels = labels
File /opt/conda/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py:118, in validate_hf_hub_args.<locals>._inner_fn(*args, **kwargs)
115 if check_use_auth_token:
116 kwargs = smoothly_deprecate_use_auth_token(fn_name=fn.__name__, has_token=has_token, kwargs=kwargs)
--> 118 return fn(*args, **kwargs)
File /opt/conda/lib/python3.10/site-packages/huggingface_hub/hub_mixin.py:157, in ModelHubMixin.from_pretrained(cls, pretrained_model_name_or_path, force_download, resume_download, proxies, token, cache_dir, local_files_only, revision, **model_kwargs)
154 config = json.load(f)
155 model_kwargs.update({"config": config})
--> 157 return cls._from_pretrained(
158 model_id=str(model_id),
159 revision=revision,
160 cache_dir=cache_dir,
161 force_download=force_download,
162 proxies=proxies,
163 resume_download=resume_download,
164 local_files_only=local_files_only,
165 token=token,
166 **model_kwargs,
167 )
File ~/.../GLiNER/model.py:355, in GLiNER._from_pretrained(cls, model_id, revision, cache_dir, force_download, proxies, resume_download, local_files_only, token, map_location, strict, **model_kwargs)
353 model = cls(config)
354 state_dict = torch.load(model_file, map_location=torch.device(map_location))
--> 355 model.load_state_dict(state_dict, strict=strict,
356 #assign=True
357 )
358 model.to(map_location)
359 return model
File /opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py:2027, in Module.load_state_dict(self, state_dict, strict)
2020 out = hook(module, incompatible_keys)
2021 assert out is None, (
2022 "Hooks registered with ``register_load_state_dict_post_hook`` are not"
2023 "expected to return new values, if incompatible_keys need to be modified,"
2024 "it should be done inplace."
2025 )
-> 2027 load(self, state_dict)
2028 del load
2030 if strict:
File /opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py:2015, in Module.load_state_dict.<locals>.load(module, local_state_dict, prefix)
2013 child_prefix = prefix + name + '.'
2014 child_state_dict = {k: v for k, v in local_state_dict.items() if k.startswith(child_prefix)}
-> 2015 load(child, child_state_dict, child_prefix)
2017 # Note that the hook can modify missing_keys and unexpected_keys.
2018 incompatible_keys = _IncompatibleKeys(missing_keys, unexpected_keys)
File /opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py:2015, in Module.load_state_dict.<locals>.load(module, local_state_dict, prefix)
2013 child_prefix = prefix + name + '.'
2014 child_state_dict = {k: v for k, v in local_state_dict.items() if k.startswith(child_prefix)}
-> 2015 load(child, child_state_dict, child_prefix)
2017 # Note that the hook can modify missing_keys and unexpected_keys.
2018 incompatible_keys = _IncompatibleKeys(missing_keys, unexpected_keys)
File /opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py:2009, in Module.load_state_dict.<locals>.load(module, local_state_dict, prefix)
2007 def load(module, local_state_dict, prefix=''):
2008 local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})
-> 2009 module._load_from_state_dict(
2010 local_state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs)
2011 for name, child in module._modules.items():
2012 if child is not None:
File /opt/conda/lib/python3.10/site-packages/flair/embeddings/transformer.py:1166, in TransformerEmbeddings._load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
1163 def _load_from_state_dict(
1164 self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
1165 ):
-> 1166 if transformers.__version__ >= Version(4, 31, 0):
1167 assert isinstance(state_dict, dict)
1168 state_dict.pop(f"{prefix}model.embeddings.position_ids", None)
File /opt/conda/lib/python3.10/site-packages/semver/version.py:51, in _comparator.<locals>.wrapper(self, other)
49 if not isinstance(other, comparable_types):
50 return NotImplemented
---> 51 return operator(self, other)
File /opt/conda/lib/python3.10/site-packages/semver/version.py:481, in Version.__le__(self, other)
479 @_comparator
480 def __le__(self, other: Comparable) -> bool:
--> 481 return self.compare(other) <= 0
File /opt/conda/lib/python3.10/site-packages/semver/version.py:396, in Version.compare(self, other)
394 cls = type(self)
395 if isinstance(other, String.__args__): # type: ignore
--> 396 other = cls.parse(other)
397 elif isinstance(other, dict):
398 other = cls(**other)
File /opt/conda/lib/python3.10/site-packages/semver/version.py:646, in Version.parse(cls, version, optional_minor_and_patch)
644 match = cls._REGEX.match(version)
645 if match is None:
--> 646 raise ValueError(f"{version} is not valid SemVer string")
648 matched_version_parts: Dict[str, Any] = match.groupdict()
649 if not matched_version_parts["minor"]:
ValueError: 4.39.0.dev0 is not valid SemVer string
```
That's the transformer version:
```python
Name: transformers
Version: 4.38.2
Summary: State-of-the-art Machine Learning for JAX, PyTorch and TensorFlow
Home-page: https://github.com/huggingface/transformers
Author: The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors)
Author-email: transformers@huggingface.co
License: Apache 2.0 License
Location: /opt/conda/lib/python3.10/site-packages
Requires: filelock, huggingface-hub, numpy, packaging, pyyaml, regex, requests, safetensors, tokenizers, tqdm
Required-by: flair, sentence-transformers, transformer-smaller-training-vocab
Note: you may need to restart the kernel to use updated packages.
```
I don't know, what the cause is and I hope you can help to find the cause.
Thanks in advance. |
ValueError: 4.39.0.dev0 is not valid SemVer string |
|python|pytorch|huggingface-transformers|large-language-model|huggingface| |
I've published a lua module that does this
**https://github.com/yogeshlonkar/lua-import**
It can be used via luarocks or simple copy/ paste as its single file without any dependencies.
I needed this for neovim configurations |
How should one handle javax.persistence.OptimisticLockException in a legacy Spring Hibernate application |
`[..h]` is a [collection expression][1], basically a concise syntax to create collections, arrays, and spans. The things inside the `[` and `]` are the collection's elements, e.g.
```
List<int> x = [1,2,3];
// basically:
// var x = new List<int> { 1,2,3 };
```
Since this is passed to a parameter expecting `int[]`, `[..h]` represents an `int[]`. What does this array contain then? What is `..h`? In a collection expression, `..` can be prefixed to another collection to "[spread][2]" that collection's elements.
Since `h` contains the numbers 1 to 9, this is basically `[1,2,3,4,5,6,7,8,9]`, though since a `HashSet` is not ordered, the order of the elements may be different.
Usually `..` is used when there are other elements/collections you want to put in the collection expression, as the example from the documentation shows:
```
string[] vowels = ["a", "e", "i", "o", "u"];
string[] consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "z"];
string[] alphabet = [.. vowels, .. consonants, "y"];
```
So `[..h]` is rather a odd use of collection expressions. It would be more readable to use `h.ToArray()` instead.
[1]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/collection-expressions
[2]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/collection-expressions#spread-element |
If you prefer to modify your strings by removing certain portions, then I suggest that you use the [NORMALIZE][1] function from a Google Sheets add-ons I created called [Flookup][2]. It is completely free to use, even without any registration.
Here is how to use it:
1. In a cell of your choice, like cell C2, enter a comma separated array of the strings you would like to remove i.e. `limited, ltd, group, holdings, plc, llp, sons, the`
2. In cell B2, type the following formula: `=NORMALIZE("text",$A$2:$A$4,$C$2)`
This formula will work through every item in range A2:A4 and strip any string found in cell C2.
----------
If you would like to try fuzzy lookups, you can use a function called [FLOOKUP][3]. This is its syntax and what each parameter represents:
FLOOKUP (lookup_value, table_array, lookup_col, index_num, threshold, [rank])
- **lookup_value:** the value you're looking up
- **table_array:** the table you want to search lookup_col: the column you
want to search
- **index_num:** the column you want data to be returned from
- **threshold:** the percentage similarity below which data shouldn't be returned
- **rank:** the nth best match (i.e. if the first one is not to your liking)
[1]: https://www.getflookup.com/documentation/spreadsheet-functions#h.6m0evbs0c19y
[2]: https://workspace.google.com/marketplace/app/flookup/593806014962
[3]: https://www.getflookup.com/documentation/spreadsheet-functions#h.dho9lnim1i2l |
I have 2 web platforms built with Laravel that work perfectly fine both on the development environment as well as on local environemnt.
The problem lies in the fact that after I deploy these applications on a cloud infrastructure as a service provider, the applications work for approximatelly ~ 1 / 2 hours, sometimes even less, and then, on every login request it redirects me to back to the login page, even though the credentials on the login attempt are correct.
In between the login request and the redirect response I get blank view with the XSRF token stored in the session, but only for a few miliseconds.
For a clearer view of the problem I need to give you the full context so I will briefly document the infrastructure and the architecture on which the application runs
The applications use the following technologies:
- Laravel (web platform built in the old fashioned monolith style) v10
- MariaDB v10.7.5
- Redis cache database v.6.2.7
- Melisearch v0.27.2
For each one of these technologies there is a Docker container. The communication between them is facilitated by a traefik Docker network. The applications works as in the following diagram:
[application arhitecture](https://i.stack.imgur.com/khmDe.png)
These are some of the environment configuration variables I use that I think might be relevant for the problem:
- for one of the platforms are these:
```
CACHE_DRIVER: "redis"
QUEUE_CONNECTION: "redis"
SESSION_DRIVER: "redis"
```
- for the other platfom are just the default ones:
<aside>
also for the second web platform I did’t configure the Redis and Melisearch services and I only run 2 Docker containers, for the app and database.
</aside>
```
CACHE_DRIVER: "file"
QUEUE_CONNECTION: "sync"
SESSION_DRIVER: "file"
```
The following things can be done to temporarily get the app working:
- ssh-ing into the VPS and manually restarting the container
- clearing the following cookies form the browser’s storage
[cookie one](https://i.stack.imgur.com/hKxIF.png)
[cookie nr. 2](https://i.stack.imgur.com/pVEJR.png)
<aside>
Note that the develop environment, the one on which the web applications work with no problems is on a self-hosted and maintained server that also has a DNS, CDN and revers-proxy provider on top
</aside>
Has someone else encountered this wierd behaviour? If so what’s causing it and how could it be solved? |
You asked:
>i dont understand it so if it could be provided with proper explanation
## Arrays
As shown in [The Java Tutorials][1] by Oracle Corp, a `for` loop has three parts:
```java
for ( initialization ; termination ; increment )
{
statement(s)
}
```
Take for example an array `{ "alpha" , "beta" , "gamma" }`:
```java
for ( int index = 0 ; index < myArray.length ; index ++ )
{
System.out.println( "Index: " + index + ", value: " + myArray[ index ] );
}
```
See this [code run at Ideone.com][2].
```none
------| Ascending |----------
Index: 0, Value: alpha
Index: 1, Value: beta
Index: 2, Value: gamma
```
To reverse the direction:
- The first part, *initialization*, can start at the *last* index of the array rather than at the *first* index. Ex: `int index = ( myArray.length - 1 )`. (Parentheses optional there.)
- The second part, *termination*, can test for going past the first index, into negative numbers: `index > -1` (or `index >= 0`).
- The third part, *increment*, can go downwards (negative) rather than upwards (positive):
```java
for ( int index = ( myArray.length - 1 ) ; index > -1 ; index -- )
{
System.out.println( "Index: " + index + ", value: " + myArray[ index ] );
}
```
See this [code run at Ideone.com][2].
```none
------| Descending |----------
Index: 2, value: gamma
Index: 1, value: beta
Index: 0, value: alpha
```
## Collections
The code above certainly works. And arrays tend to use less memory while executing faster. But working with arrays is limiting, cumbersome, and somewhat error-prone.
More commonly in Java, we use the [Java Collections Framework][3].
In collections, the appropriate replacement for an array is a [`SequencedCollection`][4] such as [`ArrayList`][5] (a [`List`][6]) or [`TreeSet`][7] (a [`NavigableSet`][8]).
We can easily make an [unmodifiable][9] `List` of our array by calling [`List.of`][10].
Every `List` is also a `SequencedCollection`. This means we can call the [`reversed`][11] method. This method is quite efficient in that it does *not* really create another collection. Instead the `reversed` method creates a *view* upon the original collection that presents its elements in a reversed encounter order.
```java
String[] myArray = { "alpha" , "beta" , "gamma" };
SequencedCollection < String > strings = List.of( myArray );
System.out.println( "strings.toString() = " + strings );
System.out.println( "strings.reversed().toString() = " + strings.reversed().toString() );
```
When run:
```none
strings.toString() = [alpha, beta, gamma]
strings.reversed().toString() = [gamma, beta, alpha]
```
[1]: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
[2]: https://ideone.com/EsDnUk
[3]: https://en.wikipedia.org/wiki/Java_collections_framework
[4]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/SequencedCollection.html
[5]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/ArrayList.html
[6]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/List.html
[7]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/TreeSet.html
[8]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/NavigableSet.html
[9]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/List.html#unmodifiable
[10]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/List.html#of(java.lang.Object[])
[11]: https://docs.oracle.com/en%2Fjava%2Fjavase%2F22%2Fdocs%2Fapi%2F%2F/java.base/java/util/SequencedCollection.html#reversed() |
Etherscan uses combination of its own database and ABI of the event emitting contract to decode the signature hash (`topics[0]`, e.g. value `0xbfa038b0...`) into human-readable format (e.g. `SectorCreated`).
The `Transfer` event is likely in their own database (because it's standardized ERC-20 event), but `SectorCreated` is not.
In this case, the contract that emitted the event is [0xc9986cf63eee2d04117300e1963083ccbb2ea301][1]. Its source code / ABI is not verified on Etherscan, so the site doesn't know how to decode events that the contract emits.
Solution is simple - verify the contract source code on Etherscan. I'm just not sure if it applies retroactively to already sent transactions or only new ones after the verification.
[1]: https://sepolia.etherscan.io/address/0xc9986cf63eee2d04117300e1963083ccbb2ea301 |
For this problem: https://leetcode.com/problems/search-suggestions-system/solution/, solution 1 states that for Java, "there is an additional complexity of O(m^2) due to Strings being immutable, here m is the length of searchWord." I am really scratching my head about this. Why the heck does immutability of string cause an additional runtime of O(m^2)?
--------------------------------------------------------------------- |
Why does the immutability of strings in java cause extra runtime for this problem: https://leetcode.com/problems/search-suggestions-system/solution/ |
|java|string|immutability| |
null |
I'm learning the Flutter ropes. The [tutorial](https://codelabs.developers.google.com/codelabs/flutter-codelab-first?hl=es-419#2) was great, but when I tried to replace the hardcoded sidebar switch and NavigationRail with ones generated from a list, I ran into a bunch of typing trouble. Basically, I want to generate them from this:
```dart
var appPages = [
{
'name': 'Header 1',
'icon': const Icon(Icons.cloud_upload),
'content': const PlaceholderPage(
placeholderText: '<h1>Test Header 1</h1><br/>Lorem ipsum.')
},
{
'name': 'Header 2',
'icon': const Icon(Icons.delete_sweep_outlined),
'content': const PlaceholderPage(
placeholderText: '<h2>Test Header 2</h2><br/>Lorem ipsum.')
},
{
'name': 'Bold Italics',
'icon': const Icon(Icons.bloodtype),
'content': const PlaceholderPage(
placeholderText: '<i>Test <b>Bold</b> Italics</i><br/>Lorem ipsum.')
},
];
```
Then instead of
```dart
Widget page;
switch (selectedIndex) {
case 0:
page = const PlaceholderPage(placeholderText: '<h1>Test Header 1</h1><br/>Lorem ipsum.');
break;
case 1:
page = const PlaceholderPage(placeholderText: '<h2>Test Header 2</h2><br/>Lorem ipsum.');
break;
case 2:
page = const PlaceholderPage(placeholderText: '<i>Test <b>Bold</b> Italics</i><br/>Lorem ipsum.');
break;
default:
throw UnimplementedError('no widget for $selectedIndex');
}
```
I would have:
```dart
var page = appPages[selectedIndex]['content'] as Widget?;
```
And instead of listing each NavigationRailDestination:
```dart
destinations:
const [
NavigationRailDestination(
icon: Icon(Icons.cloud_upload),
label: Text('Header 1')),
NavigationRailDestination(
icon: Icon(Icons.delete_sweep_outlined),
label: Text('Header 2')),
NavigationRailDestination(
icon: Icon(Icons.bloodtype),
label: Text('Bold Italics')),
],
```
I'd have something like:
```dart
destinations:
appPages.map((e) => {
NavigationRailDestination(
icon: e['icon'] as Widget, label: Text(e['name'] as String))
}).toList() as List<NavigationRailDestination>
```
But currently this fails with
```
_TypeError (type 'List<Set<NavigationRailDestination>>' is not a subtype of type 'List<NavigationRailDestination>' in type cast)
```
Any fix for this error, or a more elegant way to do it?
Thanks in advance!
pubspec.yaml:
```
name: sidebar_test
publish_to: 'none'
version: 0.1.0
environment:
sdk: '>=3.3.0 <4.0.0'
dependencies:
flutter:
sdk: flutter
provider: ^6.0.0
material_design_icons_flutter: ^7.0.0
styled_text: ^8.0.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.0
flutter:
uses-material-design: true
```
main.dart:
```dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:styled_text/styled_text.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
var appName = 'Sidebar Test';
var appTheme = ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0x006AAE3F)),
);
var appStyleTags = {
'h1': StyledTextTag(
style: TextStyle(
height: 2, fontSize: 50, color: appTheme.colorScheme.primary)),
'h2': StyledTextTag(
style: appTheme.textTheme.displayMedium!.copyWith(
color: appTheme.colorScheme.primary,
)),
'b': StyledTextTag(style: const TextStyle(fontWeight: FontWeight.bold)),
'i': StyledTextTag(style: const TextStyle(fontStyle: FontStyle.italic)),
};
var appPages = [
{
'name': 'Header 1',
'icon': const Icon(Icons.cloud_upload),
'content': const PlaceholderPage(
placeholderText: '<h1>Test Header 1</h1><br/>Lorem ipsum.')
},
{
'name': 'Header 2',
'icon': const Icon(Icons.delete_sweep_outlined),
'content': const PlaceholderPage(
placeholderText: '<h2>Test Header 2</h2><br/>Lorem ipsum.')
},
{
'name': 'Bold Italics',
'icon': const Icon(Icons.bloodtype),
'content': const PlaceholderPage(
placeholderText: '<i>Test <b>Bold</b> Italics</i><br/>Lorem ipsum.')
},
];
var appPagesFirst = appPages[0];
// var appPagesList = appPages.entries.toList();
void main() {
runApp(const MainApp());
}
class MainApp extends StatelessWidget {
const MainApp({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => MyAppState(),
child: MaterialApp(
title: appName,
theme: appTheme,
home: const HomePage(),
debugShowCheckedModeBanner: false,
restorationScopeId: appName,
),
);
}
}
class MyAppState extends ChangeNotifier {}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var selectedIndex = 0;
bool? navExtended;
@override
Widget build(BuildContext context) {
var colorScheme = Theme.of(context).colorScheme;
// Use appPages
var page = appPages[selectedIndex]['content'] as Widget?;
// Instead of switch:
// Widget page;
// switch (selectedIndex) {
// case 0:
// page = const PlaceholderPage(placeholderText: '<h1>Test Header 1</h1><br/>Lorem ipsum.');
// break;
// case 1:
// page = const PlaceholderPage(placeholderText: '<h2>Test Header 2</h2><br/>Lorem ipsum.');
// break;
// case 2:
// page = const PlaceholderPage(placeholderText: '<i>Test <b>Bold</b> Italics</i><br/>Lorem ipsum.');
// break;
// default:
// throw UnimplementedError('no widget for $selectedIndex');
// }
// The container for the current page, with its background color
// and subtle switching animation.
var mainArea = ColoredBox(
color: colorScheme.surfaceVariant,
child: AnimatedSwitcher(
duration: const Duration(milliseconds: 200),
child: page,
),
);
return Scaffold(
body: LayoutBuilder(
builder: (context, constraints) {
return Row(
children: [
SafeArea(
child: NavigationRail(
selectedIndex: selectedIndex,
onDestinationSelected: (value) {
setState(() {
selectedIndex = value;
});
},
extended: navExtended != null
? navExtended ?? true
: constraints.maxWidth >= 600,
leading: StyledText(
text: '<b>$appName</b>',
tags: appStyleTags,
),
trailing: Expanded(
child: Align(
alignment: Alignment.bottomLeft,
child: IconButton(
icon: Icon((navExtended ?? true)
? MdiIcons.arrowCollapseLeft
: MdiIcons.arrowExpandRight),
onPressed: () {
setState(() {
setState(
() => navExtended = !(navExtended ?? true));
});
},
),
),
),
destinations:
// Use appPages
appPages.map((e) => {
NavigationRailDestination(
icon: e['icon'] as Widget, label: Text(e['name'] as String))
}).toList() as List<NavigationRailDestination>
// Instead of
// const [
// NavigationRailDestination(
// icon: Icon(Icons.cloud_upload),
// label: Text('Header 1')),
// NavigationRailDestination(
// icon: Icon(Icons.delete_sweep_outlined),
// label: Text('Header 2')),
// NavigationRailDestination(
// icon: Icon(Icons.bloodtype),
// label: Text('Bold Italics')),
// ],
),
),
Expanded(child: mainArea),
],
);
// }
},
),
);
}
}
class PlaceholderPage extends StatelessWidget {
const PlaceholderPage({
super.key,
required this.placeholderText,
});
final String placeholderText;
@override
Widget build(BuildContext context) {
return Column(children: [
const Spacer(),
Card(
child: Padding(
padding: const EdgeInsets.all(20),
child: AnimatedSize(
duration: const Duration(milliseconds: 200),
child: StyledText(text: placeholderText, tags: appStyleTags))),
),
const Spacer(),
]);
}
}
``` |
List.map().toList() producing List<Set<Widget> instead of List<Widget> |
* Formula that could work in table please.
I have some values 1,2 in a range of 7 columns. I want to arrange the values in the order they appear. I want for example i have a1= 0, b1=1, c1=2, d1=1, e1=0, f1=0, g1=1, i want i1=1, j1=2, k1=1, l1=1, m1=0, n1=0, o1=0. You can see and the image with some examples. Thank you.
I tried with small function but it didnt work. |
I want to arrange the values in the order they appear and zeros all back |
|excel|excel-formula| |
null |
I need to convert hatanaka files (.d) to rinex (.o) for multiplle files (about 3000 files) is there fast way or script that I can use in terminal (ubuntu) or command prompt (windows)?
thank you
i hope i can convert my hatanaka files to rinex for multiple files |
convert hatanaka to rinex for multiple files |
|terminal|gps|converters|command-prompt| |
null |
Hello I am new in stackoverflow. I am currently finding a solution to solve the data importing issue. When I imported the records over 2000 with excel file, the web going down. Then I searched error log in the server found out the following. Web servers using nginx and database is mysql. The web is with python. Could any one suggest what I am missing?
Log: 2024/03/10 13:47:34 [error] 431467#431467: *5870 upstream prematurely closed connection while reading response header from upstream, client: 172.70.116.166, server: ***.com, request: "POST /upload_excelData/ HTTP/1.1", upstream: "http://unix:/***.sock:/upload_excelData/", host: "www.***.com", referrer: "https://www.***.com/doe_upload/"
I tried to edit the Nginx proxy connection timeout setting but not work.I am expecting to import large excel data which may be 10,000 or more. |
I'm new to Laravel 10, and I recently installed Jetstream. When I run `php artisan route:list` in the console, I get the following error: `Class "verified" does not exist`.
I do have `verified` in my Kernel:
```php
protected $middlewareAliases = [
...
...
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
```
in my route in `web.php` i have this
```
Route::group(['middleware' => ['verified', 'web']],function(){
Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
});
```
in `jetstream.php` there is this `'middleware' => ['auth', 'verified', 'web'],`
and this is the error i see on console
```
ReflectionException
Class "verified" does not exist
at vendor/laravel/framework/src/Illuminate/Foundation/Console/RouteListCommand.php:225
221▕ if ($this->isFrameworkController($route)) {
222▕ return false;
223▕ }
224▕
➜ 225▕ $path = (new ReflectionClass($route->getControllerClass()))
226▕ ->getFileName();
227▕ } else {
228▕ return false;
229▕ }
+3 vendor frames
4 [internal]:0
Illuminate\Foundation\Console\RouteListCommand::Illuminate\Foundation\Console\{closure}(Object(Illuminate\Routing\Route))
+16 vendor frames
21 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
```
I don't know what I'm missing or how to fix this. |
Currently i have this code
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = True ' <-- just for tests
If Not Intersect(Target, Range("C1")) Is Nothing Then
Select Case Target.Value
Case "Expander 1 eff"
CopyIncreaseRecord
Case "Expander 2 eff"
CopyIncreaseRecord
Case "Pump eff"
CopyIncreaseRecord
Case "Net Power"
CopyIncreaseRecordNetPower
End Select
End If
End Sub
under the Sheet5 (Graph1) view code.
presently i'm using one drop down in cell C1 to tell which macro to run automatically when i select an option in cell C1,
now i want to have two drop downs in cell C1 & in cell C2,
for example if C1 is selected "Expander 2 eff" and C2 is selected "Cycle eff" i want macro Expander2effvsCycleeff to run
if C1 is selected "Expander 2 eff" and C2 is selected "Massflowrate" i want macro Expander2effvsMassflowrate to run.
pls help, thanks in advance
i tried AI but it is not giving me the selection in two cells to be met |
|excel|vba| |
|windows|flutter-doctor| |
The application packaged through electron forge on the Windows 11 system failed to install on some Windows 10, with the error shown in the following figure. If the installation package for the same project can be successfully installed on this Windows 10 through electron forge, what is the reason for this?

Hope to help identify the problem |
Authentication in Laravel doesn’t work some time after the deploy in a specific environment |
|php|laravel|deployment|vps|provisioning| |
null |
**Is there a way to know if the camera is on?**
There be no straight way for an Android app to detect if another app is using the camera. Android's security model prohibit one app from accessing the resources or monitoring the behavior of another app without explicit permission and appropriate APIs.
While Android does provide APIs for accessing certain system information, such as the list of running processes or the usage statistics of other apps, these APIs have limitations and privacy considerations. They may not provide fine-grained information about whether a specific app be actively using the camera at any given moment.
Furthermore, even if ye could detect that another app be using the camera, accessing or interfering with its operation would likely be a violation of the Android platform's security principles and may lead to yer app being flagged as potentially harmful or intrusive.
If ye have concerns about privacy or resource usage related to the camera, it be best to address them within your own app's functionality and not attempt to monitor or interfere with other apps' behavior. Additionally, if ye believe an app be misbehaving or violating user privacy, ye can report it to the appropriate platform or store for investigation.
**Is there a way to disable the camera?**
Disabling the camera programmatically on Android be not a straightforward task, especially considering Android's security model, which prioritizes user privacy and app sandboxing. System-level permissions be typically required to manipulate hardware features such as the camera, and such permissions be not available to third-party apps for security reasons.
However, if ye have control over the device's firmware or system settings (for example, if ye be developing a custom ROM or managing devices in an enterprise environment), may be able to disable the camera through device policies or modifications to the system software.
Here be some potential approaches to consider:
Device Administration: Ye can use the Device Administration APIs to enforce policies on Android devices, including disabling certain features such as the camera. However, this requires the app to be designated as a device administrator, and users must grant permission for these privileges.
Custom ROMs: If ye be developing custom firmware for Android devices (e.g., custom ROMs), ye may be able to modify the system settings or firmware to disable the camera functionality. This approach requires advanced knowledge of Android system development and may not be feasible for all devices.
Enterprise Device Management: In enterprise environments, mobile device management (MDM) solutions can be used to enforce policies on managed devices, including disabling certain hardware features like the camera. MDM solutions typically provide APIs or management consoles to configure device policies remotely.
Rooting: Rooting an Android device provides superuser access, allowing for deeper system modifications. With root access, it may be possible to disable the camera through system-level changes. However, rooting voids device warranties and can compromise device security.
It be important to note that disabling critical features like the camera can have significant implications for device functionality and user experience. Additionally, any modifications made to the system software should be done carefully to avoid unintended consequences or security vulnerabilities.
As a general principle, apps developed for the Google Play Store should not attempt to disable or manipulate system features without user consent, as this violates Google's policies and may result in app removal or account suspension.
Refrence link - https://stackoverflow.com/questions/15862621/how-to-check-if-camera-is-opened-by-any-application |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.