instruction
stringlengths 0
30k
β |
---|
You're assigning your list incorrectly in your child component. It should be `this.props.suggestionsList`
```jsx
class GoogleSuggestions extends Component {
state = {suggestionsList: this.props.suggestionsList, searchInput: ''}
}
``` |
I have used the mentioned script 2 times earlier to send email reminders based on a condition based on a specific text in a column. But when I am trying to modify the condition in terms of date then its not working.There is next follow up date in col T, which is 19th col. I want to check if nextfollowup date matches today's date,if yes then combined the relevant rows and send reminder through email. Executive Email is in K column which is 6th col. Filled by Executive column is in F which is 6th.
I tried different methods but got no result. Hence requesting your help.
Below is the script and column names
**Existing Script
function nextFollowup() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheetByName("TGE Next Follow up");
var lastRow = dataSheet.getLastRow();
var dataRange = dataSheet.getRange("A1:BL" + lastRow);
var dataValues = dataRange.getValues();
var headers = dataValues[0];
// Calculate today's date
var today = new Date().toLocaleDateString;
//var formattedDate = Utilities.formatDate(today, Session.getScriptTimeZone(), "yyyy-MM-dd");
// Group data by sales executives
var groupedData = {};
for (var i = 1; i < dataValues.length; i++) {
var row = dataValues[i];
var salesExecEmail = row[6]; // Assuming sales executives' emails are in column G
var execName = row[5]; // Assuming sales executives' names are in column F
var condition1 = row[19].toLocaleString; // Assuming column T is 19th column
var condition2 = row[1] ? new Date(row[1]).toLocaleDateString() : ""; // Assuming column B is
var condition3 = row[3]; // Assuming column D is 4th column
var condition4 = row[8]; // Assuming column I is 9th column
var condition5 = row[9]; // Assuming column J is 10th column
var condition6 = row[16]; // Assuming column Q is 17th column
var condition7 = row[20]; // Assuming column U is 21st column
var condition8 = row[25]; // Assuming column Z is 26th column
var condition9 = row[26]; // Assuming column AA is 27th column
if (condition1 === today) {
if (!groupedData[salesExecEmail]) {
groupedData[salesExecEmail] = { name: execName, data: [] };
}
groupedData[salesExecEmail].data.push([condition2, condition3,condition4,condition5,
condition6,condition7,condition8,condition9]);
//Logger.log(condition1);
}
}
// Sending reminder emails
for (var execEmail in groupedData) {
var execName = groupedData[execEmail].name;
var execData = groupedData[execEmail].data;
var emailBody = "<html><body><p>Dear " + execName + ",</p>";
emailBody += "<p>Here are your pending leads for " + formattedDate + ":</p>";
emailBody += "<table border='1'><tr>";
// Add headers
emailBody += "<th>" + headers[1] + "</th><th>" + headers[3] + "</th><th>" + headers[8] + "
</th> <th>" + headers[9] + "</th><th>" + headers[16] + "</th><th>" + headers[20] + "
</th><th>" + headers[25] + "</th><th>" + headers[26] + "</th></tr>";
// Add data rows
for (var j = 0; j < execData.length; j++) {
var rowData = execData[j];
emailBody += "<tr>";
for (var k = 0; k < rowData.length; k++) {
emailBody += "<td>" + rowData[k] + "</td>";
}
emailBody += "</tr>";
}
emailBody += "</table></body></html>";
// Send email
MailApp.sendEmail({
to: execEmail,
//cc: "", // Add the email address(es) you want to include in CC
subject: "Pending Leads for " + execName + " For - " ,
htmlBody: emailBody
});
}
Logger.log("Recipient email address: " + execEmail);
Logger.log("Recipient email address: " + salesExecEmail);
}
**Column Names
Record
Timestamp (This sheet)
Timestamp
Type of Inquiry
Total Inquiry
Filled by Executive
Executive Email
Executive Mobile
Person / Customer / Agent Name
Business Name
Email ID
Mobile No
Alternate Number
Location
Business Type
Company Address
Lead Type
Date of Visit
Call Type
Next Follow Up Date
Sales Stage
Comment / Remarks
No. of Adult
No. of Kids
No. of Sr. Citizens
|
To match today's Date as Condition for sending email reminders |
|google-apps-script| |
null |
[enter image description here](https://i.stack.imgur.com/mPdLJ.jpg)
I hello everyone, above given image is from trading. i tried to code for conditions given in image but i am unable to effecienty code for it. so, give it a try to solve this problem it would be helpfull..bellow are code
|
I am trying to make a container that has children Horizontally and moves from left to right
Each of those children , when it reach the end of the container =\> goes to the start of the container
let's imagine that it contain 4 children:
```lang-none
0% : ..1 | 2 | 3 | 4..
25% : ..4 | 1 | 2 | 3..
50% : ..3 | 4 | 1 | 2..
75% : ..2 | 3 | 4 | 1..
100% : ..1 | 2 | 3 | 4..
```
not like the carousel, but like the ring rolling (smooth )
for infinite time
Below
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.container {
height: 200px;
width: 800px;
border: 1px solid #333;
overflow: hidden;
margin: 25px auto;
}
.box {
background: orange;
height: 180px;
margin: 10px;
animation-name: move;
animation-duration: 10s;
animation-iteration-count: infinite;
animation-direction: right;
animation-timing-function: linear;
display: flex;
}
.card {
background: #fff;
height: 150px;
min-width: 100px;
margin: 15px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.box:hover {
animation-play-state: paused;
}
@keyframes move {
0% {
margin-left: 000px;
}
25% {
margin-left: 100px;
}
50% {
margin-left: 200px;
}
75% {
margin-left: 300px;
}
100% {
margin-left: 400px;
}
}
<!-- language: lang-html -->
<div class="container">
<div class="box">
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
</div>
</div>
<!-- end snippet -->
is the code I have tried:
may use JavaScript. |
If I understand correctly, you need to wait for the downloading/buffering panel to complete before you action you next click, so we can do this a few ways.
1. We can simply check when the buffering panel is done. This can be done in several ways but an easy one is something like:
const bufferingElement = page.locator('<your locator for buffering panel>');
await expect(bufferingElement).toHaveCount(0);
This will find the buffering element, whatever that is for your site, and then wait until it disappears, i.e. loading complete. You can easily extend that to look for specific text such as 'loading' or whatever you need. As I don't know your HTML, I am keeping it generic here, but the logic is the same.
If you wanted to conditionally check for it, its very similar. Something like:
const bufferingElement = page.locator('<your locator for buffering panel>');
//If there is a buffering job, wait for it to complete
if(await bufferingElement.count() > 0){
//Do whatever you need to do while job is buffering
await expect(bufferingElement).toHaveCount(0);
}
2. If we know what the endpoint is that controls this buffering, we can wait until it is done, before moving on. Something like this could work for that:
const responsePromise = page.waitForResponse(response =>
response.url() === '<endpoint url>' && response.status() === 200
);
await page.getByRole('<role>', { name: '<name>' }).click();
const response = await responsePromise;
This code block creates a promise (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), then you should replace the 'getByRole' line with the action that performs the load, which is presumably just opening the page under test. Then, we resolve the promise, at which point the response is returned and buffering complete, then you can move on.
3. If you want to use a more precise locator than getting text that contains 'a' I would recommend using the getByRole locator. This is the best way to go as it uses a user-centric way to gather your locators. Essentially you would find your elements role, and its name value, and use that. It is much nicer than using a text contains type of approach. This link explains a nice easy way to find those things - https://www.smashingmagazine.com/2020/08/accessibility-chrome-devtools/ |
|javascript|playwright|playwright-test| |
I want to display chart data based on the results sum(value) as total_value from my query. why can't the total_value attribute be displayed on the chart?
query:
$rooms2 = Room::query()
->join('notifications', 'notifications.room_id', '=', 'rooms.id')
->join('watt_histories', 'watt_histories.notification_id', '=', 'notifications.id')
->where('rooms.user_id', 1)
->whereIn('notifications.id', function ($query) {
$query->selectRaw('MAX(id)')
->from('notifications')
->groupBy('room_id');
})
->select([
'rooms.*',
'notifications.*',
'watt_histories.*',
DB::raw('(SELECT SUM(wh.value) FROM watt_histories AS wh INNER JOIN notifications AS n ON wh.notification_id=n.id WHERE n.room_id=notifications.room_id) as total_value'),
DB::raw('(SELECT SUM(wh.cost) FROM watt_histories AS wh INNER JOIN notifications AS n ON wh.notification_id=n.id WHERE n.room_id=notifications.room_id) as total_cost')
])
->groupBy('notifications.room_id')
->orderBy('watt_histories.created_at', 'desc')
->get();
how can I display the total value if I use a Laravel chart like this?
code:
$charts = [];
foreach ($rooms2 as $room) {
$conditions = [];
$conditions[] = [
'condition' => "notification_id = {$room->notification_id}",
'color' => '',
'fill' => true,
];
$chart1 = [
'conditions' => $conditions,
'chart_title' => 'Energy Used ' . $room->room_name . ' by months',
'report_type' => 'group_by_date',
'model' => 'App\Models\WattHistory',
'group_by_field' => 'created_at',
'group_by_period' => 'day',
'aggregate_function' => 'sum',
'aggregate_field' => 'total_value',
'chart_type' => 'line',
'filter_field' => 'created_at',
'continuous_time' => true,
];
$chart2 = [
'conditions' => $conditions,
'chart_title' => 'Average Energy Used ' . $room->room_name . ' by months',
'report_type' => 'group_by_date',
'model' => 'App\Models\WattHistory',
'group_by_field' => 'created_at',
'group_by_period' => 'day',
'aggregate_function' => 'avg',
'aggregate_field' => 'total_value',
'chart_type' => 'line',
'filter_field' => 'created_at',
'continuous_time' => true,
];
$charts[$room->id] = new LaravelChart($chart1, $chart2);
}
for now this is the result.
[current result][1]
[1]: https://i.stack.imgur.com/PsvbP.png |
Laravel Chart can't show attribute value from query |
|laravel|charts|laravel-charts| |
Consider replacing the default `ts-jest` runner with [SWC Jest](https://swc.rs/docs/usage/jest). It seems to be a drop-in replacement, but much faster. In my case, the execution time dropped from 5 seconds to 1 ms for a trivial test.
First install SWC Jest:
```
npm i -D jest @swc/core @swc/jest
```
Then use it in your `jest.config.js`:
```
module.exports = {
transform: {
"^.+\\.(t|j)sx?$": "@swc/jest",
},
};
```
Unlike the `isolatedModules: true` trick, this actually works without messing around with `module` and `moduleResolution` (see [here](https://stackoverflow.com/questions/68724389/jest-takes-10s-to-run-two-trivial-typescript-tests-how-do-i-determine-why-its#comment137600249_75442408)). |
I am writing an app using WebView to load my html, css, js and get some problems when loading the html.
Here is the MainActivity
```
public class MainActivity extends AppCompatActivity
{
HTMLDataBase myDB1;
ContentTableDataBase myDB2;
CloudTableDataBase myDB3;
InterviewDataBase myDB4;
Context context;
boolean check;
private WebView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB1 = new HTMLDataBase(this);
myDB2 = new ContentTableDataBase(this);
myDB3 = new CloudTableDataBase(this);
myDB4 = new InterviewDataBase(this);
display_html();
Javascript_Android_Communication();
}
public void display_html()
{
WebView view = (WebView) findViewById(R.id.WebView);
view.getSettings().setJavaScriptEnabled(true);
Cursor res = myDB1.getAllData();
if (res.getCount() > 0) {
StringBuffer buffer = new StringBuffer();
while (res.moveToNext())
{
buffer.append(res.getString(0) + ",");
buffer.append(res.getString(1) + ",");
buffer.append(res.getString(2) + ",");
}
String[] result = buffer.toString().substring(0, buffer.toString().trim().length() - 1).split(",", -2);
if (result[2].equals("block"))
{
view.loadUrl("file:///android_asset/index.html");
}
if (!result[2].equals("block"))
{
view.loadUrl("file:///android_asset/index2.html"); // Problem occurs when loading this html
};
}
}
public void Javascript_Android_Communication()
{
WebView view = (WebView) findViewById(R.id.WebView);
view.setWebChromeClient(new WebChromeClient() {});
WebSettings settings = view.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
view.addJavascriptInterface(new JavaScriptInterface(this), "Android");
view.addJavascriptInterface(new WebViewJavaScriptInterface(this), "app");
}
}
```
Javascript requests information from DataBase and imports them to:
```
document.getElementById("").style.display = "";
```
The problem is data can be extracted but the html is never completely loaded and thus errors occurs when I change the html element. When I open the logcat, it said "Uncaught TypeError: Cannot read property 'style' of null".
Whenever I use alert method to call
```
document.getElementById("").style.display
```
It simply returns me empty.
I try to use
```
document.addEventListener("load",function(){alert(document.getElementById().style.display);});
```
but the page is never completely loaded so it just waa waste of time. What shall I do so that I can change the html with data I have extracted. |
Visual Studio edit view corrupt for xaml and Winforms design views |
|c#|wpf|visual-studio|winforms|xaml| |
Which approach is more better use of httpclient in .Net Framework 4.7 among the following two
in terms of socket exhaustion and thread safe?
Both are reusing httpclient instance.Right?
I can't implement ihttpclientfactory right now.It is difficult to us implement dependency injection
**First Code : -**
```
class Program
{
private static HttpClient httpClient;
static void Main(string[] args)
{
httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("your base url");
// add any default headers here also
httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minute timeout
MainAsync().Wait();
}
static async Task MainAsync()
{
await new MyClass(httpClient).StartAsync();
}
}
public class MyClass
{
private Dictionary<string, string> myDictionary;
private readonly HttpClient httpClient;
public MyClass(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task StartAsync()
{
myDictionary = await UploadAsync("some file path");
}
public async Task<Dictionary<string, string>> UploadAsync(string filePath)
{
byte[] fileContents;
using (FileStream stream = File.Open(filePath, FileMode.Open))
{
fileContents = new byte[stream.Length];
await stream.ReadAsync(fileContents, 0, (int)stream.Length);
}
HttpRequestMessage requestMessage = new HttpRequestMessage();
// your request stuff here
HttpResponseMessage httpResponse = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
// parse response and return the dictionary
}
}
```
**Second Code:-**
```
class Program
{
static void Main(string[] args)
{
MainAsync().Wait();
}
static async Task MainAsync()
{
await new MyClass().StartAsync();
}
}
public class MyClass
{
private Dictionary<string, string> myDictionary;
private static readonly HttpClient httpClient= = new HttpClient() { BaseAddress = new Uri("your base url"), Timeout = new TimeSpan(0, 2, 0) };
public async Task StartAsync()
{
myDictionary = await UploadAsync("some file path");
}
public async Task<Dictionary<string, string>> UploadAsync(string filePath)
{
byte[] fileContents;
using (FileStream stream = File.Open(filePath, FileMode.Open))
{
fileContents = new byte[stream.Length];
await stream.ReadAsync(fileContents, 0, (int)stream.Length);
}
HttpRequestMessage requestMessage = new HttpRequestMessage();
// your request stuff here
HttpResponseMessage httpResponse = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
// parse response and return the dictionary
}
}
```
I'm expecting resolve socket exhaustion problem. |
|c#|httpclient|dotnet-httpclient|sendasync| |
Android Load WebView and Javascript |
|javascript|android| |
null |
If you are building a react application then you can use "[react-pdftotext][1]" package to extract text from pdfs on browsers. For detail on how to use this package you can refer to this [article][2].
[1]: https://www.npmjs.com/package/react-pdftotext
[2]: https://dev.to/utkarsh212/how-to-extract-plain-text-from-pdf-in-react-2afl |
You have to rewrite the logic a bit, as you cannot update each row 'one by one'. First check for HS2:
df.withColumn("testValveOpened", f.when(f.col("sourceName" == "GS2"), f.lit(1)).otherwise(0))
then do a cumulative sum and comparison to see if a GS2 was present before:
df.withColumn("testValveOpened", f.sum("testValveOpened").over(window) > 1)
|
I encountered a similar `Didn't find class "androidx.core.app.CoreComponentFactory"` issue using dynamic feature modules (SplitInstallManagerFactory) on a newer project.
The issue occurred during the install of dynamic feature modules only when obfuscation was enabled (i.e., `isMinifyEnabled = true`). This keep rule fixed it when added to my base app module's `proguard-rules.pro`:
```text
-keep class androidx.core.app.CoreComponentFactory { *; }
```
Tom's [suggestion](https://stackoverflow.com/a/59296304/11321246) of falling back to java 1.8 also resolved the issue for me, but this keep rule allowed me to stay on the java 17 LTS.
Looking into the android/openjdk source, the `BaseDexClassLoader.findClass` function appears to be inherited from `java.lang.ClassLoader`. This deals with classes as strings, so my best guess is that R8 was obfuscating the androidx.core.app.CoreComponentFactory class. I can't guess as to why falling back to java 1.8 would also resolve the issue. |
Is there a way to automatically generate points of coordinates for the contour of islands using existing map ?
For instance using directly the points of the map of openstreetmap (or other), let say with a certain number of datapoints ?
I need to generate a geojson file with a certain number of islands.
There are some websites like https://geojson.io/#map=10.01/15.3855/-61.289 where we can build polygon it by clicking manually, but it is clearly too time consuming for the number of islands I have to do...
I have already tried searching the data on the net but what I find is usually bad quality, so I want to use directly the data from the maps.
Thanks a lot !
|
This playbook will copy all the gather fact content in `/tmp/ansible_facts_details.json` file on the host machine. You can run it from location where inventory file is located in the control machine (where Ansible is installed).
1. Command to run playbook is `ansible-playbook playbooks/gatherfacts_playbook.yaml`
2. Command to check playbook syntax is `ansible-playbook playbooks/gatherfacts_playbook.yaml --syntax-check`
3. Command to do runtime debug `ansible-playbook -vvv playbooks/gatherfacts_playbook.yaml`
> - name: Play to get the gathre facts content
> hosts: DEV1
> tasks:
> - name: print ansible_facts
> debug:
> var: ansible_facts["kernel"]
> - name: Copy ansible facts to a file.
> copy:
> content: "{{ ansible_facts }}"
> dest: /tmp/ansible_facts_details.json
|
Module parse failed: Unexpected token (2:9801) in jwplayer-react.js |
|reactjs|jwplayer| |
I'm trying to create a dot indicator for a carousel slider. No idea why it's not rebuilding at all. Simple carousel of images with a dot indicator at the bottom that rebuilds when based on index of image on the carousel.
CODE:
class Testhome extends StatelessWidget {
const Testhome({super.key});
@override
Widget build(BuildContext context) {
CarouselController homepagecontroller = CarouselController();
final SliderController slidercontrollerinstance = SliderController();
return Scaffold(
appBar: AppBar(
title: Text('Welcome Alexander',
style: ttextthemes.darktheme.headlineMedium),
automaticallyImplyLeading: false,
actions: [
// Search icon button
IconButton(
color: Colors.black,
icon: const Icon(Icons.search),
onPressed: () {
// Show modal search bar using a package or custom implementation
})
]),
body: SingleChildScrollView(
child: Column(children: [
const SizedBox(height: Tsizes.spacebtwitems),
//search bar
const Tsearchbar(text: 'Search in Store'),
//spacing
const SizedBox(height: Tsizes.spacebtwitems),
//heading
const Theadingbar(
text: 'Popular categories',
showbutton: true,
),
//spacing
const SizedBox(height: Tsizes.spacebtwitems),
//category icons
const Homecategories(),
Padding(
padding: const EdgeInsets.all(Tsizes.spacebtwitems),
child: Column(children: [
CarouselSlider(
items: const [
CarouselImages(imageurl: Timages.onboardingimage2),
CarouselImages(imageurl: Timages.onboardingimage),
CarouselImages(imageurl: Timages.onboardingimage3)
],
options: CarouselOptions(
viewportFraction: 1,
autoPlay: true,
onPageChanged: (index, reason) {
slidercontrollerinstance.updateController(index);
},
)),
const SizedBox(height: Tsizes.spacebtwitems),
Consumer<SliderController>(
builder: (context, slidercontrollerinstance, _) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for (int i = 0; i < picturescarousel.length; i++)
Tcircularwidget(
hieght: 4,
colour: slidercontrollerinstance.currentIndex == i
? const Color.fromARGB(255, 15, 74, 104)
: Colors.grey)
]);
})
]))
]
// carousel
)));
}
}
final List picturescarousel = [
const CarouselImages(imageurl: Timages.onboardingimage2),
const CarouselImages(imageurl: Timages.onboardingimage),
const CarouselImages(imageurl: Timages.onboardingimage3)
];
class SliderController extends ChangeNotifier {
int _currentIndex = 0;
int get currentIndex => _currentIndex;
void updateController(int index) {
_currentIndex = index;
notifyListeners();
}
}
class Tcircularwidget extends StatelessWidget {
const Tcircularwidget(
{super.key,
this.colour = const Color.fromARGB(255, 15, 74, 104),
this.hieght = 10,
this.width = 10,
this.borderradius = Tsizes.boarderradiusLG,
this.padding = 5,
this.margin});
final Color colour;
final double width, hieght;
final double borderradius;
final double padding;
final EdgeInsets? margin;
@override
Widget build(BuildContext context) {
return Container(
width: width,
height: hieght,
padding: EdgeInsets.all(padding),
margin: EdgeInsets.only(right: padding),
decoration: BoxDecoration(
color: colour,
borderRadius: BorderRadius.circular(Tsizes.boarderradiusLG)));
}
}
I don't see why it's not rebuilding. It's only a simple dot indicator. Should be very simple, all the resources im using say im doing things properly
|
Dot indicator not working- Flutter -Should rebuild indicator on page change |
|flutter|provider| |
I am trying to update the value of an object in a deeply nested array in mongoose, but havn't been able to come up with the correct syntax.
I have tried both atomic updates and the conventional way of updating items in mongodb still with no luck.
**I want to update 'history[index].rideConfirmations[index].rideComplete.driverConfirmed**
```
//driverHistorySchema.js
const mongoose = require("mongoose");
const DriversRideHistorySchema = new mongoose.Schema(
{
driverId: mongoose.Schema.ObjectId,
driverName: String,
history: [
{
date: String,
rideConfirmations: [
{
riderConfirmationTime: String,
driverConfirmationTime: String,
riderName: String,
riderId: mongoose.Schema.ObjectId,
rideComplete: {
riderConfirmed: Boolean,
driverConfirmed: Boolean,
},
},
],
},
],
},
{ timestamps: true, collection: "driversRideHistory" }
);
module.exports = mongoose.model("DriversRideHistory", DriversRideHistorySchema);
```
**I want to update 'history[index].rideConfirmations[index].rideComplete.driverConfirmed**
```
router.put("/rideHistory/completeRide", async (req, res) => {
try {
const { driverId, dateIndex, riderIndex } = req.body;
await DriversHistoryModel.findOneAndUpdate(
{
driverId: driverId,
},
{
$set: {
"history.$[dateIndex].rideConfirmations.$[riderIndex].rideComplete.driverConfirmed": true,
},
},
{ arrayFilters: [{ dateIndex: dateIndex }, { riderIndex: riderIndex }] }
);
return res.status(200).send("Ride Completed Successfully");
} catch (err) {
console.log(err);
return res
.status(404)
.send("An error occured while processing this request");
}
});
module.exports = router;
``` |
How do I update an object in a deeply nested array of objects with mongoose? |
|javascript|node.js|mongodb|mongoose|mongoose-schema| |
null |
Lua doesn't have classes, where you can use a constructor to create a new instance of a type. But, being a flexible language, we can achieve something _like_ classes through clever use of metatables. So let's talk for a moment about how the `__index` [metamethod](https://www.lua.org/pil/13.4.1.html) works.
When you ask a table for a key that doesn't exist, it will return `nil`. But, if you set the `__index` property to another table, the lookup will fall-through to that table.
```lua
local a = {
foo = "hello"
}
local b = {
bar = "world"
}
-- ask b for "foo" which isn't defined on 'b'
print(b.foo, b.bar) -- returns nil, "world"
-- set the lookup table to 'a'
setmetatable(b, { __index = a })
-- ask again for b, which still isn't defined on 'b'
print(b.foo, b.bar) -- returns "hello", "world"
```
In this example, `b` did not become a clone of `a` with all of its properties, it is still a table with only `bar` defined. If you were to ask for `foo`, since it does not find it in `b` it then checks `a` to see if it can find it there. So `b` is not `a`, but it can act like it.
Let's look at what your code is doing :
```lua
-- create a table with some fields already defined
local Cell = {
index = nil,
coordinates = Vector2.zero,
wasVisited = false
}
-- create a "new" function that will pass the in original Cell object as the `self` variable
function Cell:new(index: number, coordinates: Vector2)
-- create an empty table that will reference the original Cell table
-- note - the first time this is called, the __index metamethod hasn't been set yet
local instance = setmetatable({}, self)
-- set Cell's __index metamethod to itself
self.__index = self
-- overwrite the original Cell's index to the passed in index
self.index = index
-- overwrite the original Cell's coordinates to the passed in coordinates
self.coordinates = coordinates
-- return an empty table that will reference all of these new values
return instance
end
```
As you can see, your code is struggling to define copies of Cells because your constructor is constantly overwriting the values in the original Cell table, not assigning them to the newly created instance. Each new instance is able to access these fields and not fail, but they are always referencing the last values set.
So, to fix it, here's what I would do :
- **change Cell.new to a period function, not a colon function.** This is a style preference, but a constructor shouldn't need access to instance variables. But it does mean that you need to update the code that calls `Cell:new` and change them all to `Cell.new`
- **define your class properties on the instance.** This means that each new instance technically has its own copy of those keys and they never have to reference Cell for them.
```lua
-- create a new table named Cell
local Cell = {}
-- set Cell's __index to itself to allow for future copies to access its functions
Cell.__index = Cell
-- set the "new" key in Cell to a function
function Cell.new(index: number, coordinates: Vector2)
-- create a new table and set the lookup table to be the Cell table
-- since no functions are defined on this new table, they will fall through to access Cell's functions
local instance = setmetatable({
-- set some properties on the new instance table
index = index,
coordinates = coordinates,
wasVisited = false,
}, Cell)
-- return the new table
return instance
end
-- set the "markAsVisited" key in Cell to a function
function Cell:markAsVisited()
-- here "self" is referring to the new instance table, not some field on Cell
self.wasVisited = true
end
return Cell
``` |
All answers provided so far are correct. Adding my version, in an attempt to make it bit easier for those who still need further clarification.
**Task Role:**
The ECS set up will have some containers. These containers will perform some tasks for which we are being created. To perform these tasks **containers** need to call other AWS services. Which services can be called is defined by the **Task Role**. So, this is ***container's role*** required for a task.
**Task Execution Role:**
To set up the containers and maintain these, some tasks are performed. **Container Agent** performs these tasks. So, the role required & assumed by Container Agent is Task Execution Role.
|
I'm trying to make a web browser but i cant find a good tutorial for bookmarks and tabs in my web browser called **RadonNet** I'm using `PySide6` because i want my software to be open source
I also use `QWebEngineView` which makes it harder to find tutorials for my browser
Sure. Theres Bookmarks and Tabs Tutorials but they will not work with `QWebEngineView`
Anything to solve this?
```
import sys
from PySide6.QtCore import QUrl
from PySide6.QtWidgets import QApplication, QMainWindow, QLineEdit, QToolBar
from PySide6.QtGui import QAction # Corrected import for QAction
from PySide6.QtWebEngineWidgets import QWebEngineView
class Browser(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('RadonNet')
`your text` self.browser = QWebEngineView()
self.browser.setUrl(QUrl('http://www.google.com'))
# Navigation toolbar
self.nav_bar = QToolBar("Navigation")
self.addToolBar(self.nav_bar)
# Back button
back_btn = QAction('Back', self)
back_btn.triggered.connect(self.browser.back)
self.nav_bar.addAction(back_btn)
# Forward button
forward_btn = QAction('Forward', self)
forward_btn.triggered.connect(self.browser.forward)
self.nav_bar.addAction(forward_btn)
# Refresh button
refresh_btn = QAction('Refresh', self)
refresh_btn.triggered.connect(self.browser.reload)
self.nav_bar.addAction(refresh_btn)
# Home button
home_btn = QAction('Home', self)
home_btn.triggered.connect(self.navigate_home)
self.nav_bar.addAction(home_btn)
# URL bar
self.url_bar = QLineEdit()
self.url_bar.returnPressed.connect(self.navigate_to_url)
self.nav_bar.addWidget(self.url_bar)
self.setCentralWidget(self.browser)
def navigate_home(self):
self.browser.setUrl(QUrl('http://www.google.com'))
def navigate_to_url(self):
url = self.url_bar.text()
self.browser.setUrl(QUrl(url))
if __name__ == '__main__':
app = QApplication(sys.argv)
QApplication.setApplicationName('RadonNet')
window = Browser()
window.show()
sys.exit(app.exec_())
```
I tried tutorials but none of them are compatible with `QWebEngineView`.
There are very few posts about bookmarks and tabs for `PySides`/`QT` `WebEngineView`
And none of them work.
So I'm forced to ask stack overflow |
I am newbie in Delphi, but I need to fix Delphi code in order to make network disks to be mounted when "Service start" is executed. By default when my application is started by Windows Service network disks are not accessible for application, so the solution is to insert UNC mapping script in my service. Can you help me with this issue? |
|python|pytorch|computer-vision|anaconda| |
I have faced with such issue i am opening project that placed in my desktop (mac 14 pro m3 pro) I can see the folder where is my script:

After running and stoping the script (i am getting some error) The folder is disappear:

And it returns when switch window to safari or any app and return again or click `Reload all from disk1`

I have tried to delete or clear cache , nothing works |
null |
Because type variable type are not the same
enter code herevar1 = int(input("enter a number:"))
num = str(var1)[::-1]
var2 = int(num)
if var1 == var2:
print("its a palindrome")
else:
print("its not a palindrome")
you need convert to integer type
or there is another way
var1 = input("enter a number:")
var2 = var1[::-1]
if var1 == var2:
print("its a palindrome")
else:
print("its not a palindrome")
|
This may help you: https://developer.hashicorp.com/terraform/cli/commands/show
terraform show -json
*The terraform show command is used to provide human-readable output from a state or plan file. This can be used to inspect a plan to ensure that the planned operations are expected, or to inspect the current state as Terraform sees it.
Machine-readable output is generated by adding the -json command-line flag.*
Alternatively: https://developer.hashicorp.com/terraform/cli/commands/plan
terraform plan - json
*-json - Enables the machine readable JSON UI output. This implies -input=false, so the configuration must have no unassigned variable values to continue.*
|
Initially multiSelect is filled with 100 values, if the search string is not listed in the initial list then server side search is implemented on enter event.
```
<p-multiSelect
[options]="options"
class="multi-select-dropdown"
[maxSelectedLabels]="0"
resetFilterOnHide="true"
[(ngModel)]="selectedValues"
(onChange)="onChange($event)"
(keyup.enter)="onSearchFilter($event)"
[defaultLabel]="placeholder"
[virtualScroll]="true"
itemSize="25"
[style]="{'min-width':'100%', 'max-width':'100%'}">
</p-multiSelect>
```
**Issue**:
When user search for string like 'W101', if it's not available in the list then in the multiSelect "No results found" displayed".
When user hits enter, the filtered result is fetched but multiSelect is not getting updated with new values. It still shows "No results found".
But if I click the close icon(x) beside the search-box and open the drop-down then it displays the filtered list.
PrimeNG v12 is used.
|
null |
X A cryptographic error occurred while checking "https://github.com/": Handshake error in client
You may be experiencing a man-in-the-middle attack, your network may be compromised, or you may have [](https://i.stack.imgur.com/d7WuZ.png)malware installed on your computer.
I have attempted all the solutions found on the internet, such as setting the date and time and turning off Windows Defender, but I am still facing the same issue. |
Here is another method, using a custom function named `fnDecimalDuration`
**Custom Function Code**<br>*Paste into blank query and rename*
```
(durationString as text)=>
let
//split on space
split = Text.Split(durationString," "),
//convert values to numbers
values = List.Transform(List.Alternate(split,1,1,1), each Number.From(_)),
//trim the terminal 's' from plurals
unitNames = List.Transform(List.Alternate(split,1,1,0),each Text.TrimEnd(_,"s")),
//translation table
unitTable = Table.FromColumns({
{"Day","Hour","Minute","Second"},
{1,1/24,1/1440,1/86400}},
type table [Name=text, Factor=number]),
unitMultipliers = Table.Join(unitTable,"Name", Table.FromColumns({unitNames}),"Column1", JoinKind.RightOuter)[Factor],
combine = List.Zip({values, unitMultipliers})
in
List.Sum(List.Transform(combine, each List.Product(_)))
```
You can use this in your native query to either Transform or to Add a new column:
***Transform Code***
```
#"Transform Decimal Durations" = Table.TransformColumns(#"Previous Step", {"Column1", each fnDecimalDuration(_), type number}),
```
***Add Custom Column Code***
```
#"Added Custom" = Table.AddColumn(#"Previous Step", "Duration", each fnDecimalDuration([Column1]), type number)
```
You would add those steps into your code. An example for adding a custom column is shown below
```
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}}),
//Commented out but could use this instead
// #"Transform Decimal Durations" = Table.TransformColumns(#"Changed Type", {"Column1", each fnDecimalDuration(_), type number}),
#"Added Custom" = Table.AddColumn(#"Changed Type", "Duration", each fnDecimalDuration([Column1]), type number)
in
#"Added Custom"
```
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/TS8tn.png |
You can use Docker [Volumes](https://docs.docker.com/storage/volumes/)
> Volumes can be more safely shared among multiple containers.
You can define Volumes on `dockerfile`, `docker-compose` file or on `cli`
But to share volumes, you should define named volumes.
You can do so using `cli` or `docker-compose` file.
cli
```bash
docker volume create --name shared-volume
docker run -d --name container1 -v shared-volume:/path/in/container1 my-image1
docker run -d --name container2 -v shared-volume:/path/in/container2 my-image2
```
docker-compose file
```docker
services:
service1:
image: my-image1
volumes:
- shared-volume:/path/in/container1
service2:
image: my-image2
volumes:
- shared-volume:/path/in/container2
volumes:
shared-volume
```
A named volume is declared for the path /home/python/lib.
Docker will create a volume, named shared-volume, (folder on your pc) and mount it to /path/in/container(1/2) inside the container. This means that any data written to /path/in/container(1/2) inside the container will be stored in the volume and persist even after the container is stopped or removed.

_image from docker docs [link](https://docs.docker.com/storage/volumes/)_
Beware containers might overwrite each other's data stored on the volume. |
I'm starting gettting my hands dirty with antlr4 and I don't unserstand the difference between **Getting started the easy way using antlr4-tools** and **Installation** decribed in the [Getting started guide][1].
- Can I choose either one?
- Does antlr4 (easy start) correspond to antlr4 alias (installation)?
- Does antlr4-parse (easy start) correspond to grun alias (installation)?
[1]: https://github.com/antlr/antlr4/blob/master/doc/getting-started.md |
We tried this with both VS 2022 17.8.3, 17.9.0 and 17.9.1 which is currently the latest.
**Symptom:**
When running XUnit test and hitting a breakpoint and we try to inspect properties of an object it just hangs for a while with a message "Busy" then in the Watch window if we expand the object it just shows three ellipsis. This happens only if the object has at least one property with a Type defined in a NuGet package.
XUnit test with breakpoint, goint to inspect variable **s**:
[![XUnit test with breakpoint][1]][1]
Watch window shows nothing when expanding variable, just "...":
[![Watch window shows nothing when expanding variable][2]][2]
---
**"Workaround":**
A "workaround" is to instantiate an object of a Type from the NuGet package before inspecting.
[![Workaround][3]][3]
It now works to inspect the variable "s".
---
It is pretty obvious that the problem occurs because the dll from the NuGet is not yet loaded when we inspect the object. Is there any setting in VS we might have missed, or could it be something in our codebase?
[1]: https://i.stack.imgur.com/PovM5.png
[2]: https://i.stack.imgur.com/hrRie.png
[3]: https://i.stack.imgur.com/MJksT.png |
Visual Studio 2022, XUnit test project, cannot inspect object properties if the class has a property of a Type from NuGet |
|visual-studio|debugging|visual-studio-2022|xunit| |
I have a data resolver for specific cms block. The configuration of the cms block stores the IDs of chosen property groups. It means that:
```
$config = $slot->getFieldConfig();
if (! $selectedProperties = $config->get('selectedProperties')) {
return null;
}
var_dump($selectedProperties->getValue()); //This will return the ids of the property group chosen in the configuration of the block.
```
Now, How can I build the specific criteria to get property groups with options for specific categories?
I tried something like:
```
$criteria = ($selectedProperties->getValue()) ? new Criteria($selectedProperties->getValue()) : new Criteria();
$criteria->addAssociation('options');
$criteria->getAssociation('options.productProperties.categories')->addFilter(new EqualsFilter('id', '16561f02419949feb5ac61a4ee6c6211'));
$criteria->getAssociation('options')->addSorting(new FieldSorting('name', FieldSorting::ASCENDING));
```
but this is not working.
I need this because I have a menu with a submenu showing after hover. E.g (In the menu we have item `Wine` and after hover we want to have the submenu with subcategories country - Germany, Usa, Swiss, type -pink, white, red etc(property group and options). |
How can I get property groups with options for specific categories? |
|shopware|shopware6| |
null |
I am using Raspberry4 , i have USB camera module that have 2 device ports (video0 - Raw video , video2 - H264 video) . I using gstreamer pipeline as capture device
```
cam = cv2.VideoCapture('gst-launch-1.0 v4l2src device=/dev/video2 ! video/x-h264,width=640,height=480,framerate=10/1 ! x264enc ! h264parse ! videoconvert ! appsink', cv2.CAP_GSTREAMER)
```
I am reading frames from it , and writing to serial port.
In another device i am trying to read sent bytes , and convert them back to np array to use in cv2.imshow().
When i print received bytes and bytes in sender code , i see that they are different (received bytes are changed , i see it when print np.array ) and i can not show received frame.
I surfed many sites looking for the answer, but couldn't .
What do you think about it? |
Difference between antlr4-tools and installation |
|antlr|antlr4| |
If tick stuck on the some code, this point on architecture problem, like inner infinite loop, or operations, which consume a lot of CPU, or blocking operations, like a syncronously reading of a huge file. JS have not waiting operations, or pause logic. You can understand that, using next diagram from [here][1]:
βββββββββββββββββββββββββββββ
ββ>β timers β
β βββββββββββββββ¬ββββββββββββββ
β βββββββββββββββ΄ββββββββββββββ
β β pending callbacks β
β βββββββββββββββ¬ββββββββββββββ
β βββββββββββββββ΄ββββββββββββββ
β β idle, prepare β
β βββββββββββββββ¬ββββββββββββββ βββββββββββββββββ
β βββββββββββββββ΄ββββββββββββββ β incoming: β
β β poll β<ββββββ€ connections, β
β βββββββββββββββ¬ββββββββββββββ β data, etc. β
β βββββββββββββββ΄ββββββββββββββ βββββββββββββββββ
β β check β
β βββββββββββββββ¬ββββββββββββββ
β βββββββββββββββ΄ββββββββββββββ
ββββ€ close callbacks β
βββββββββββββββββββββββββββββ
Each phase of event loop means that node.js (by fact libuv) just a looking up, is some timer expired?, is some condition for pending callback satisfied?, and so on, and every thats phases checks are non blocking, unlike some havy, or blocking logic, which can be started in a result of that check
If some stuck happence, I recommend next solutions:
For infinite loops, try to refactor code to avoid them, because, by fact, you code allready works in the infinite event loop, so, use nextTick, or setImmediate for go away from blocking code style
For blocking operations (working with network, filesystem, databases, etc), refactor logic to asyncronouse code style
For operations, which consume a lot of CPU, use child_process and move havy logic in a separate threads
[1]: https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick |
I am trying to do a transparent background for my MatDialog component. Here is the code:
*parent.component.html*
openDialog(){
const dialogConfig = new MatDialogConfig();
dialogConfig.width = '340px';
dialogConfig.height = '476px';
dialogConfig.autoFocus = false;
dialogConfig.panelClass = "dialogClass";
dialogConfig.data = this.item;
this.dialog.open(ChildComponent, dialogConfig)
}
*styles.css (global file, not the parent component one)*
.dialogClass{
background-color: pink; //pink to see if it works
}
This code works (I can see pink for a second every time I open the dialog), but it gets instantly covered with a white layer. All I have in my ChildComponent is displayed *over* this layer:
**MatDialog background -> White layer -> ChildComponent**
If ChildComponent *.css* and *.html* files are empty, it still appears.
Setting a block with transparent background doesn't help either.
How do I delete this white layer from a dialog?
|
How do I delete white layer over dialog background in Angular? |
|angular|angular-material|mat-dialog| |
You can suggest last value if you have a loop:
while [[ $continue != "y" ]]
do
echo ""
read -p " - Enter the name : " -e -i "$name" name
echo ""
echo " - Chosen name is: $name "
read -p " - continue (yes) ou retry (no) (y/n): " continue
done
echo " - We continue... "
echo " - Chosen name is: $name "
|
I have a file called debian. I have made a flag of -d. Which turns on the termux-x11 server and the pulse audio server. To make a display I then have to type a different command I created called display which turns on xfce4. Is there any way to pass the command to the pd shell directly?
This is the debian file inside /data/data/com.termux/usr/bin:
```
#!/bin/bash
if [ "$1" == "-d" ]; then
# Start PulseAudio with specific configuration
pulseaudio --start --load="module-native-protocol-tcp auth-ip-acl=127.0.0.1 auth-anonymous=1" --exit-idle-time=-1
# Start X11 server in the background
termux-x11 :1 &
# Login to Debian using pd with shared tmp
pd login --shared-tmp debian --user mrdual
else
pd login --shared-tmp debian --user mrdual
fi
```
This is the display file inside /bin of the debian distro:
```
#creating variables
export DISPLAY=:1 PULSE_SERVER=127.0.0.1
#turning on the xfce server
xfce4-session
```
|
How to give command to a different proot distro shell in termux? |
|termux| |
null |
I am trying to derive some analytics for a set of data that I have on a csv file. The csv file has the following format[sniped from csv](https://i.stack.imgur.com/xdAnd.png)
The first column contains an ID/schema, each other column represents time/generations. This happens N number of Runs.
I want to be able to the occurrence of each ID/schema at each point of time/generations. So that I can have a final count of each ID, a final average, and a final standard deviation from the N number of runs.
So far I am able to extract the data, and remove the rows that contain 'R'. I don't really care about the runs because I want to add them together.
First step is to at least sum all the runs per each ID and generation but I can't seem to get the hang of pandas.
```
import pandas as pd
def main():
filename = 'out/outputs.csv' # Replace with the actual filename
rdata = read_csv(filename)
data = pd.DataFrame(rdata)
data = data[~data[0].str.contains('R')]
sums = data.groupby(data[0],axis=1) # here is where I want to sum by schema/ID and generation
sums = sums.sum()
if __name__ == "__main__":
main()
```
At the end my goal is to have something like the following matrices
sums
| Schema | gen1 | gen2 | genN|
|--------|------|------|-----|
| 11**** | 5 | 10 | 100|
| ***111 | 0 | 3 | 12 |
averages
|Schema | gen1 | gen2 | genN |
|-------|------|------|------|
|11**** | 6.0 | 12.1 | 120.2|
|***111 | 0.0 | 10.0 | 30.0 |
standard deviations
|Schema | gen1 | gen2 | genN |
|-------|------|------|------|
|11**** | 0.2 | 1.0| 0.1 |
|***111 | 0.0 | 0.3| 0.12|
|
Here is my Unit Test
```
import { render } from '@testing-library/react';
import { ChartCard } from '@/views/Dashboard/Reports/ChartCard';
import { ChartDataType } from '../types';
describe('ChartCard', () => {
const mockData: ChartDataType = {
xData: [
{ total_count: 30, success_count: 20, failed_count: 10, time_slice: '2022-01-01T00:00:00Z' },
{ total_count: 30, success_count: 20, failed_count: 10, time_slice: '2022-01-01T00:00:00Z' },
],
yDataPoints: ['total_count'],
xDataPoints: ['time_slice'],
yLabels: { success_count: 'Label 1', failed_count: 'Label 2' },
yData: [
{ total_count: 30, success_count: 20, failed_count: 10, time_slice: '2022-01-01T00:00:00Z' },
{ total_count: 30, success_count: 20, failed_count: 10, time_slice: '2022-01-01T00:00:00Z' },
],
backgroundColors: { success_count: 'red', failed_count: 'blue' },
};
it('renders chart card with correct data', () => {
const { getByText } = render(
<ChartCard
data={mockData}
tooltipLabel='Tooltip Label'
cardTitle='Card Title'
tooltipPosition='top'
chartEmptyText='No Data found'
/>,
);
expect(getByText('Card Title'));
});
```
and while testing with Jest, I get this error:
β ChartCard βΊ renders chart card with correct data
TypeError: (0 , moment_1.default) is not a function
This is part of my code:
```
import moment from 'moment';
moment(run.time_slice).format('ddd hh:mm');
```
I don't get the error while testing if I change the original import in the component to ```import * as moment from 'moment';``` but, React throws a ```Uncaught TypeError: moment is not a function``` if i change the import. |
H264 data changing after serial communication in Python |
|python|camera|h.264| |
null |
The class `material-symbols-outlined` to `mat-icon` like this.
```
<mat-icon class="material-symbols-outlined">expand_content</mat-icon>
```
[There's notes on this in this issue](https://github.com/angular/components/issues/24845).
[Also there's an NPM package](https://www.npmjs.com/package/material-symbols) with more detailed instructions for Material Symbols use in general. |
Hi Co-programmers, let's share some ideas on what make programming so enjoyable to Us, for me, it is just the ability to discover new line of code and then build, it makes me feel like a Hero who contributes to the growth of Tech globally. |
What makes programming so cool and enjoyable to you? |
|css|html|javascript|python| |
I have two lists, one with vehicle IDs (column A) and dates they were used (Column B), another one with IDs (Column E) and all dates maintenance was performed on them (Column F). In Column C I would like a formula to return for each usage, the last time date when that specific vehicle was serviced.
[enter image description here](https://i.stack.imgur.com/Ux5H3.png)
I'm really bad at Gsheet so all I managed to do until now is to get the latest day a vehicle was serviced with this formula =MAX(FILTER(E$2:F, E$2:E=A2)). I'd need some way to add a condition where D<B. I tried a MAXIFS formula but I just don't have the knowledge to get the syntax right. Can anyone help?
Here's the expected result:
[enter image description here][1]
[1]: https://i.stack.imgur.com/YKuE8.png |
I've updated my Kotlin Android app, which uses Firebase Auth, Database, and Storage, increasing targetSdkVersion and dependencies to current versions. While everything operates as expected when deployed from Android Studio, downloading the app from the Play Store, or generating signed APK and deploying manually, results in all sign-in methods failing - despite working previously.
Discussions on Stack Overflow ([1][1], [2][2], [3][3]), suggest issues often stem from incorrect SHA certificate fingerprints, particularly the mix-up between the upload and the App Signing key from Google Play Console. My Firebase project, however, already includes both SHA-1 & SHA-256 of the App Signing key. Temporarily removing these fingerprints confirmed their significance by altering app behavior, for example: OTPs for phone sign-ins are received only while fingerprints are set (but sign-in fails).
Thus, I'm at a loss for what could be causing the sign-in methods to fail only in the signed version, and how to investigate it, as the problem does not occur in a debuggable version. Has anyone encountered a similar issue or can offer insights into potential causes and solutions?
**AuthUI screen behavior for clicking each Auth provider in release versions:**
- **Google**: The app freezes on the AuthUI screen with a progress bar showing indefinitely.
- **Twitter**: Successfully opens the browser for authentication and indicates success, but causes the app to close upon redirection back.
- **Email**: No email is received.
- **Phone**: Upon receiving the OTP, the 'Phone Number' field turns red, displaying an "An unknown error occurred." message.
**Google Smart lock pop-up behavior in different versions:**
- **Debug version**: Shows Gmail based account options with their current profile photo set in the app (saved in Firebase).
- **Local signed APK**: Pop-up does not show at all.
- **Play Store version**: Shows Gmail based account options with no photos.
[1]: https://stackoverflow.com/questions/48439480/firebase-google-authentication-not-working-in-release-mode/50868434#50868434
[2]: https://stackoverflow.com/questions/64360590/firebase-authentication-works-only-on-debug-version
[3]: https://stackoverflow.com/questions/50664680/google-authentication-is-not-working-after-publishing-in-play-store |
I have a webpage with two <picture> elements that each have <a> in front of them. The images are inline, next to each other. Whitespace is between these two elements (not sure why, but I'm fine with the small gap between them) and the whitespace itself has a little underscore or bottom-border type of characteristic to it. I don't want this little underscore to be visible.
Page viewable here: https://nohappynonsense.net/writtte
If I remove the <a> from each picture the little line goes away. But I want these images to have a link, so I'm not sure what else to try. |
Whitespace in document has a bottom border remnant or some other line at the bottom of the whitespace |
|html|css|image| |
null |
|arrays|c|pointers|multidimensional-array|implicit-conversion| |
I have written a code for finding prime numbers using sieve of Erasthenes algorithm, but the problem is my wcode as it is but for only some numbers. It shows like "entering upto-value infinitely" as the error and for some numbers it works perfectly. As I started recently studying C in-depth I couldn't find what is going wrong. I request the code-ies to help me in this case.
Here's the code:
```
#include <stdio.h>
int main()
{
int n;
printf("enter number: ");
scanf("%d",&n);
int arr[n],pr=2,i=0;
for(i=0;pr<=n;i++)
{
arr[i]=pr;
pr++;
}
int j,k;
while(arr[k]<=n)
{
for(j=2;j<n;j++)
{
for(k=0;k<n;k++)
{
if(arr[k]%j==0 && arr[k]>j)
arr[k]=0;
}
}
}
for(i=0;arr[i]<=n;i++)
{
if(arr[i]!=0)
printf(" %d",arr[i]);
}
printf("\n");
return 0;
}
``` |
Error checking for my C code for finding prime numbers |
|arrays|c|primes|sieve-of-eratosthenes| |
null |
I have written a code for finding prime numbers using sieve of Erasthenes algorithm, but the problem is my code as it is but for only some numbers. It shows like "entering upto-value infinitely" as the error and for some numbers it works perfectly. As I started recently studying C in-depth I couldn't find what is going wrong. I request the code-ies to help me in this case.
Here's the code:
```
#include <stdio.h>
int main()
{
int n;
printf("enter number: ");
scanf("%d",&n);
int arr[n],pr=2,i=0;
for(i=0;pr<=n;i++)
{
arr[i]=pr;
pr++;
}
int j,k;
while(arr[k]<=n)
{
for(j=2;j<n;j++)
{
for(k=0;k<n;k++)
{
if(arr[k]%j==0 && arr[k]>j)
arr[k]=0;
}
}
}
for(i=0;arr[i]<=n;i++)
{
if(arr[i]!=0)
printf(" %d",arr[i]);
}
printf("\n");
return 0;
}
``` |
AG Grid is a client-side grid that is designed to be framework **ag**nostic. It is not dependent on any framework, allowing it to be easily integrated with any of them.
When posting, describe the problem, add some screenshots/code samples.
Don't forget to specify if you integrate it with frameworks like Angular v1, Angular v2, or other frameworks or if you're using it with native JavaScript or TypeScript.
[Documentation and forum][1]
[GitHub repository][2]
### Related tags:
- [tag:ag-grid-react] for AG Grid questions using a [React][3] implementation.
- [tag:ag-grid-angular] for AG Grid questions using an [Angular][4] implementation.
- [tag:ag-grid-vue] for AG Grid questions using a [Vue.js][5] implementation.
- [tag:ag-grid-solid] for AG Grid questions using a [Solid][6] implementation.
[1]: http://www.ag-grid.com
[2]: https://github.com/ag-grid/ag-grid
[3]: https://en.wikipedia.org/wiki/React_(JavaScript_library)
[4]: https://en.wikipedia.org/wiki/Angular_(web_framework)
[5]: https://en.wikipedia.org/wiki/Vue.js
[6]: https://www.solidjs.com/tutorial/introduction_basics
|
run flutter doctor command facing Network resources issue |
|android|flutter|dart|android-studio|flutter-doctor| |
null |
<!-- language-all: lang-js -->
There's a way to allow a content script heavy extension to continue functioning after an upgrade, and to make it work immediately upon installation.
# Install/upgrade
The install method is to simply iterate through all tabs in all windows, and inject some scripts programmatically into tabs with matching URLs.
### ManifestV3
manifest.json:
```json
"background": {"service_worker": "background.js"},
"permissions": ["scripting"],
"host_permissions": ["<all_urls>"],
```
These host_permissions should be the same as the content script's `matches`.
background.js:
```js
chrome.runtime.onInstalled.addListener(async () => {
for (const cs of chrome.runtime.getManifest().content_scripts) {
for (const tab of await chrome.tabs.query({url: cs.matches})) {
if (tab.url.match(/(chrome|chrome-extension):\/\//gi)) {
continue;
}
chrome.scripting.executeScript({
files: cs.js,
target: {tabId: tab.id, allFrames: cs.all_frames},
injectImmediately: cs.run_at === 'document_start',
// world: cs.world, // uncomment if you use it in manifest.json in Chrome 111+
});
}
}
});
```
This is a simplified example that doesn't handle frames. You can use [getAllFrames][3] API and match the URLs yourself, see the documentation for [matching patterns][4].
#### Caveats & Notes
- If you still have old tabs open you may get an error: `Cannot access contents of the page. Extension manifest must request permission to access the respective host.` You will need to refresh those tabs so that they now have the new extension code that will auto-reload them.
- You may now get a new error or still get `Error: Extension context invalidated.` If you are still receiving this you will need to remove any old event handlers on the page for the content script see: <https://stackoverflow.com/questions/57468219/chrome-extension-how-to-remove-orphaned-script-after-chrome-extension-update>
### ManifestV2
Obviously, you have to do it in a [background page][1] or [event page][2] script declared in manifest.json:
"background": {
"scripts": ["background.js"]
},
background.js:
// Add a `manifest` property to the `chrome` object.
chrome.manifest = chrome.runtime.getManifest();
var injectIntoTab = function (tab) {
// You could iterate through the content scripts here
var scripts = chrome.manifest.content_scripts[0].js;
var i = 0, s = scripts.length;
for( ; i < s; i++ ) {
chrome.tabs.executeScript(tab.id, {
file: scripts[i]
});
}
}
// Get all windows
chrome.windows.getAll({
populate: true
}, function (windows) {
var i = 0, w = windows.length, currentWindow;
for( ; i < w; i++ ) {
currentWindow = windows[i];
var j = 0, t = currentWindow.tabs.length, currentTab;
for( ; j < t; j++ ) {
currentTab = currentWindow.tabs[j];
// Skip chrome:// and https:// pages
if( ! currentTab.url.match(/(chrome|https):\/\//gi) ) {
injectIntoTab(currentTab);
}
}
}
});
#### Historical trivia
In ancient Chrome 26 and earlier content scripts could restore connection to the background script. It was fixed http://crbug.com/168263 in 2013. You can see an example of this trick in the earlier revisions of this answer.
[1]: https://developer.chrome.com/extensions/background_pages
[2]: https://developer.chrome.com/extensions/event_pages
[3]: https://developer.chrome.com/docs/extensions/reference/webNavigation/#method-getAllFrames
[4]: https://developer.chrome.com/extensions/match_patterns |
Moment gives a TypeError when testing with Jest |
|reactjs|typescript|jestjs|react-typescript| |
The while loop only continues as long as `__atomic_compare_exchange_n` fails. It'll only fail if the value of `count` doesn't match the value of `_M_use_count`. After it does fail the value of `count` will be updated to the current value of `_M_use_count`.
See https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html#index-_005f_005fatomic_005fcompare_005fexchange_005fn |
I am trying to derive some analytics for a set of data that I have on a csv file. The csv file has the following format[sniped from csv](https://i.stack.imgur.com/xdAnd.png)
The first column contains an ID/schema, each other column represents time/generations. This happens N number of Runs.
I want to be able to the occurrence of each ID/schema at each point of time/generations. So that I can have a final count of each ID, a final average, and a final standard deviation from the N number of runs.
So far I am able to extract the data, and remove the rows that contain 'R'. I don't really care about the runs because I want to add them together.
First step is to at least sum all the runs per each ID and generation but I can't seem to get the hang of pandas.
```
import pandas as pd
def main():
filename = 'out/outputs.csv' # Replace with the actual filename
rdata = read_csv(filename)
data = pd.DataFrame(rdata)
data = data[~data[0].str.contains('R')]
sums = data.groupby(data[0],axis=1) # here is where I want to sum by schema/ID and generation
sums = sums.sum()
if __name__ == "__main__":
main()
```
At the end my goal is to have something like the following matrices
sums
| Schema | gen1 | gen2 | genN|
|--------|------|------|-----|
| 11**** | 5 | 10 | 100|
| ***111 | 0 | 3 | 12 |
averages
|Schema | gen1 | gen2 | genN |
|-------|------|------|------|
|11**** | 6.0 | 12.1 | 120.2|
|***111 | 0.0 | 10.0 | 30.0 |
standard deviations
|Schema | gen1 | gen2 | genN |
|-------|------|------|------|
|11**** | 0.2 | 1.0| 0.1 |
|***111 | 0.0 | 0.3| 0.12|
EDIT:
[matrices loose their form but here is the example result I would like to get][1]
[1]: https://i.stack.imgur.com/ca4Kd.png |
I wanted to install [react-scheduler][1] npm package to my react.ts project.
I runed next command: ```D:\University\Degree project\TestingSchedule1\my-app>npm install '@bitnoi.se/react-scheduler'```
And got next error:
```
npm ERR! code 128
npm ERR! An unknown git error occurred
npm ERR! command git --no-replace-objects ls-remote ssh://git@github.com/bitnoi.se/react-scheduler'.git
npm ERR! fatal: remote error:
npm ERR! is not a valid repository name
npm ERR! Visit https://support.github.com/ for help
npm ERR! A complete log of this run can be found in: C:\Users\koten\AppData\Local\npm-cache\_logs\2024-03-10T09_02_58_820Z-debug-0.log
```
Chat gpt said it can be problrm with SSH Key when I'm trying to install my private package, but this is not mine repository and this is public/
[1]: https://github.com/Bitnoise/react-scheduler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.