问:
Why does this error state my class does not implement this interface method?
I have a class that implements an interface and legacy from other class.

I don't know why my code is bad.

The error I get is:

CS0738 'SizeTypeService' does not implement interface member 'IGenericService<ItemType>.GetAll()'.

'GenericService<SizeType>.GetAll()' cannot implement 'IGenericService<ItemType>.GetAll()' because it does not have the matching return type of 'Task<List<ItemType>>'.
```
<p>I think that my interface and class are ok. I don't know why VS is throwing an error.</p>
<pre class="lang-csharp prettyprint-override"><code>public interface IGenericService<TEntity> where TEntity : class
{
    Task<List<TEntity>> GetAll();
    Task<TEntity> GetById(int id);
    Task<TEntity> Insert(TEntity entity);
    Task<TEntity> Update(TEntity entity);
    Task Delete(int id);
}

public class GenericService<TEntity> : IGenericService<TEntity> where TEntity : class
{
    private IGenericRepository<TEntity> genericRepository;

    public GenericService(IGenericRepository<TEntity> genericRepository)
    {
        this.genericRepository = genericRepository;
    }

    public async Task Delete(int id)
    {
        await genericRepository.Delete(id);
    }

    public async Task<List<TEntity>> GetAll()
    {
        return await genericRepository.GetAll();
    }

    public async Task<TEntity> GetById(int id)
    {
        return await genericRepository.GetById(id);
    }

    public async Task<TEntity> Insert(TEntity entity)
    {
        return await genericRepository.Insert(entity);
    }

    public async Task<TEntity> Update(TEntity entity)
    {
        return await genericRepository.Update(entity);
    }
}

public interface ISizeTypeService : IGenericService<ItemType>
{
    Task<List<SizeType>> GetAllSizeTypeActives(int id);
    Task LogicDelete(int id);
}

public class SizeTypeService : GenericService<SizeType>, ISizeTypeService
{
    private ISizeTypeRepository sizeTypeRepository;

    public SizeTypeService(ISizeTypeRepository sizeTypeRepository) : base(sizeTypeRepository)
    {
        this.sizeTypeRepository = sizeTypeRepository;
    }

    public Task<List<SizeType>> GetAllSizeTypeActives(int id)
    {
        return sizeTypeRepository.GetAllSizeTypeActives(id);
    }

    public Task LogicDelete(int id)
    {
        return sizeTypeRepository.LogicDelete(id);
    }
}
</code>```

答:
You have defined your ServiceTypeClass as

```<code>public class SizeTypeService : GenericService<SizeType>, ISizeTypeService
{
   ...
}
</code>```

So you are telling the compiler that ServiceTypeService uses the base class GenericService with TEntity defined as SizeType. BUT, the ISizeTypeService interface it also derives from is telling the compiler that this class also implements the IGenericService interface where TEntity is a ItemType class. But nowhere in the code is class that implements the method GenericService<ItemType>.GetAll().

So, the error is saying "hey - I found the method matching GenericService<SizeType>.GetAll() - where TEntity is SizeType, but I cannot find one that matches IGenericService<ItemType>.GetAll()"

To fix you need to change the ISizeTypeService definition to use the same class as GenericService for TEntity

e.g.

```<code>public interface ISizeTypeService : IGenericService<SizeType>
{
   ...
}
</code>```

NOTE: The generic parameter is now SizeType which matches the GenericService<SizeType> base class that SizeTypeService derives from.

Body:
I have a class that implements an interface and legacy from other class.

I don't know why my code is bad.

The error I get is:

CS0738 'SizeTypeService' does not implement interface member 'IGenericService<ItemType>.GetAll()'.

'GenericService<SizeType>.GetAll()' cannot implement 'IGenericService<ItemType>.GetAll()' because it does not have the matching return type of 'Task<List<ItemType>>'.

I think that my interface and class are ok. I don't know why VS is throwing an error.

public interface IGenericService<TEntity> where TEntity : class
{
    Task<List<TEntity>> GetAll();
    Task<TEntity> GetById(int id);
    Task<TEntity> Insert(TEntity entity);
    Task<TEntity> Update(TEntity entity);
    Task Delete(int id);
}

public class GenericService<TEntity> : IGenericService<TEntity> where TEntity : class
{
    private IGenericRepository<TEntity> genericRepository;

    public GenericService(IGenericRepository<TEntity> genericRepository)
    {
        this.genericRepository = genericRepository;
    }

    public async Task Delete(int id)
    {
        await genericRepository.Delete(id);
    }

    public async Task<List<TEntity>> GetAll()
    {
        return await genericRepository.GetAll();
    }

    public async Task<TEntity> GetById(int id)
    {
        return await genericRepository.GetById(id);
    }

    public async Task<TEntity> Insert(TEntity entity)
    {
        return await genericRepository.Insert(entity);
    }

    public async Task<TEntity> Update(TEntity entity)
    {
        return await genericRepository.Update(entity);
    }
}

public interface ISizeTypeService : IGenericService<ItemType>
{
    Task<List<SizeType>> GetAllSizeTypeActives(int id);
    Task LogicDelete(int id);
}

public class SizeTypeService : GenericService<SizeType>, ISizeTypeService
{
    private ISizeTypeRepository sizeTypeRepository;

    public SizeTypeService(ISizeTypeRepository sizeTypeRepository) : base(sizeTypeRepository)
    {
        this.sizeTypeRepository = sizeTypeRepository;
    }

    public Task<List<SizeType>> GetAllSizeTypeActives(int id)
    {
        return sizeTypeRepository.GetAllSizeTypeActives(id);
    }

    public Task LogicDelete(int id)
    {
        return sizeTypeRepository.LogicDelete(id);
    }
}

Body:
You have defined your ServiceTypeClass as

public class SizeTypeService : GenericService<SizeType>, ISizeTypeService
{
   ...
}

So you are telling the compiler that ServiceTypeService uses the base class GenericService with TEntity defined as SizeType. BUT, the ISizeTypeService interface it also derives from is telling the compiler that this class also implements the IGenericService interface where TEntity is a ItemType class. But nowhere in the code is class that implements the method GenericService<ItemType>.GetAll().

So, the error is saying "hey - I found the method matching GenericService<SizeType>.GetAll() - where TEntity is SizeType, but I cannot find one that matches IGenericService<ItemType>.GetAll()"

To fix you need to change the ISizeTypeService definition to use the same class as GenericService for TEntity

e.g.

public interface ISizeTypeService : IGenericService<SizeType>
{
   ...
}

NOTE: The generic parameter is now SizeType which matches the GenericService<SizeType> base class that SizeTypeService derives from.


来源: stackexchange

问:
Inserting values to table using text file in Oracle SQL
I tried to do following task

First I created a table

```<code>CREATE TABLE my_table(
order_id Int,
id_number VARCHAR(50),
con_number VARCHAR(50),
action_code VARCHAR(50)
);

</code>```

I have a text file called index.txt. The contents of the text file are as follows

```<code>[ 2022-01-24 00:38:12 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28950294"
[ 2022-01-24 00:38:12 ]|[ LOG_PARAMS ]|{"order_id":28450294,"id_number":"466054543","con_number":"344354501983","action_code":"verifier_approved"}
[ 2022-01-24 00:38:12 ]|[ RESPONSE ]|"Success\n202"
[ 2022-01-24 01:15:32 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28948509"
[ 2022-01-24 01:15:32 ]|[ LOG_PARAMS ]|{"order_id":28945509,"id_number":"46653156V","con_number":"117546476356","action_code":"verifier_approved"}
[ 2022-01-24 01:15:32 ]|[ RESPONSE ]|"Success\n202"
[ 2022-01-24 01:15:45 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28951964"
[ 2022-01-24 01:15:45 ]|[ LOG_PARAMS ]|{"order_id":28948964,"id_number":"14896103756","con_number":"345434353024","action_code":"verifier_approved"}
[ 2022-01-24 01:15:45 ]|[ RESPONSE ]|"Success\n202"
[ 2022-01-24 01:16:02 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28952134"
[ 2022-01-24 01:16:02 ]|[ LOG_PARAMS ]|{"order_id":289745834,"id_number":"1187402899","con_number":"45445946461","action_code":"verifier_rejected"}
[ 2022-01-24 01:16:02 ]|[ RESPONSE ]|"Success\n202"

</code>```

I want to insert value to table (order_id ,id_number,con_number,action_code) using index.txt file.

Any one can help me

Thank you

答:
Using sqlldr with a control file like this will parse your text file:

```<code>LOAD DATA INFILE 'dat.data'
APPEND INTO TABLE my_table WHEN (27:36) = 'LOG_PARAMS'
fields terminated by ','
(
order_id char "substr(:order_id,instr(:order_id, ':', 40)+1)" ,
id_number char "substr(:id_number,instr(:id_number, ':', 9)+2)" ,
con_number char "substr(:con_number,instr(:con_number, ':', 9)+2)" ,
action_code char "substr(:action_code, instr(:action_code, ':', 9)+2)"
)

</code>```

However it does not get rid of trailing quote and enclosing curly bracket from the string columns. You could subsequently remove it via a post processing operation like this

```<code>update my_table set id_number = substr(id_number, 1, length(id_number) -1),
con_number = substr(con_number, 1, length(con_number) -1),
action_code = substr(action_code, 1, length(action_code) -2);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried to do following task

First I created a table

CREATE TABLE my_table(
order_id Int,
id_number VARCHAR(50),
con_number VARCHAR(50),
action_code VARCHAR(50)
);

I have a text file called index.txt. The contents of the text file are as follows

[ 2022-01-24 00:38:12 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28950294"
[ 2022-01-24 00:38:12 ]|[ LOG_PARAMS ]|{"order_id":28450294,"id_number":"466054543","con_number":"344354501983","action_code":"verifier_approved"}
[ 2022-01-24 00:38:12 ]|[ RESPONSE ]|"Success\n202"
[ 2022-01-24 01:15:32 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28948509"
[ 2022-01-24 01:15:32 ]|[ LOG_PARAMS ]|{"order_id":28945509,"id_number":"46653156V","con_number":"117546476356","action_code":"verifier_approved"}
[ 2022-01-24 01:15:32 ]|[ RESPONSE ]|"Success\n202"
[ 2022-01-24 01:15:45 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28951964"
[ 2022-01-24 01:15:45 ]|[ LOG_PARAMS ]|{"order_id":28948964,"id_number":"14896103756","con_number":"345434353024","action_code":"verifier_approved"}
[ 2022-01-24 01:15:45 ]|[ RESPONSE ]|"Success\n202"
[ 2022-01-24 01:16:02 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28952134"
[ 2022-01-24 01:16:02 ]|[ LOG_PARAMS ]|{"order_id":289745834,"id_number":"1187402899","con_number":"45445946461","action_code":"verifier_rejected"}
[ 2022-01-24 01:16:02 ]|[ RESPONSE ]|"Success\n202"

I want to insert value to table (order_id ,id_number,con_number,action_code) using index.txt file.

Any one can help me

Thank you

Body:
Using sqlldr with a control file like this will parse your text file:

LOAD DATA INFILE 'dat.data'
APPEND INTO TABLE my_table WHEN (27:36) = 'LOG_PARAMS'
fields terminated by ','
(
order_id char "substr(:order_id,instr(:order_id, ':', 40)+1)" ,
id_number char "substr(:id_number,instr(:id_number, ':', 9)+2)" ,
con_number char "substr(:con_number,instr(:con_number, ':', 9)+2)" ,
action_code char "substr(:action_code, instr(:action_code, ':', 9)+2)"
)

However it does not get rid of trailing quote and enclosing curly bracket from the string columns. You could subsequently remove it via a post processing operation like this

update my_table set id_number = substr(id_number, 1, length(id_number) -1),
con_number = substr(con_number, 1, length(con_number) -1),
action_code = substr(action_code, 1, length(action_code) -2);


问:
Python logging in modules not working as expected
I am sure I am just misunderstanding how this works but I cannot seem to have log formatting propagate to logging in modules unless the module "knows" the name of the module that called it.

The following code demonstrates the issue. The code below works but I have to hard code the name of the module that called it for the formatting to apply.

app.py

```<code>import logging
import mymodule

logger = logging.getLogger('app')
log_formatter = logging.Formatter(f'%(asctime)s %(name)s[%(process)d]: %(levelname)s - %(message)s\n')
log_handler_console = logging.StreamHandler()
log_handler_console.setFormatter(log_formatter)
log_handler_console.terminator = ''
logger.addHandler(log_handler_console)

logger.error('testing 1')
mymodule.dosomething()
</code>```

module.py

```<code>import logging
logger = logging.getLogger('app.module')
def dosomething():
    logger.error('testing 2')
</code>```

As per code above I get this:

```<code>2022-01-09 19:01:53,986 app[46541]: ERROR - testing 1
2022-01-09 19:01:53,987 app.module[46541]: ERROR - testing 2
</code>```

but if I change the name of the logger to eg 'test' I get:

```<code>2022-01-09 19:21:07,590 app[46580]: ERROR - testing 1
testing 2
</code>```

If I change the name of the logger in line 2 of module.py to anything other than 'app' or 'app.something' then the formatting no longer applies. I get how the inheritance works (I think) but how can I know the calling module name without hard coding it? I did see a few examples here on SO but with cautions that its a bad idea.

Essentially what I am trying to do is define a log format in the main app and have any module that the main app calls use the same format. I am I crazy? Seems like an obvious thing to want?

答:
What you expect, "Essentially what I am trying to do is define a log format in the main app and have any module that the main app calls use the same format.", is totally reasonable.

"how can I know the calling module name without hard coding it?"
You can use the below code to set up logger name hierarchy analogous to your Python package hierarchy.

```<code>logger = logging.getLogger(__name__)
</code>```

With propagation enabled by default on all children loggers, all filtered messages will be propagated up through the hierarchical structure, and finally to the root logger, and then handled by its handler in its specified format.

For more detailed explanation of those practices of using Python logging, you may refer to Good Practices of using Python Logging

Body:
I am sure I am just misunderstanding how this works but I cannot seem to have log formatting propagate to logging in modules unless the module "knows" the name of the module that called it.

The following code demonstrates the issue. The code below works but I have to hard code the name of the module that called it for the formatting to apply.

app.py

import logging
import mymodule

logger = logging.getLogger('app')
log_formatter = logging.Formatter(f'%(asctime)s %(name)s[%(process)d]: %(levelname)s - %(message)s\n')
log_handler_console = logging.StreamHandler()
log_handler_console.setFormatter(log_formatter)
log_handler_console.terminator = ''
logger.addHandler(log_handler_console)

logger.error('testing 1')
mymodule.dosomething()

module.py

import logging
logger = logging.getLogger('app.module')
def dosomething():
    logger.error('testing 2')

As per code above I get this:

2022-01-09 19:01:53,986 app[46541]: ERROR - testing 1
2022-01-09 19:01:53,987 app.module[46541]: ERROR - testing 2

but if I change the name of the logger to eg 'test' I get:

2022-01-09 19:21:07,590 app[46580]: ERROR - testing 1
testing 2

If I change the name of the logger in line 2 of module.py to anything other than 'app' or 'app.something' then the formatting no longer applies. I get how the inheritance works (I think) but how can I know the calling module name without hard coding it? I did see a few examples here on SO but with cautions that its a bad idea.

Essentially what I am trying to do is define a log format in the main app and have any module that the main app calls use the same format. I am I crazy? Seems like an obvious thing to want?

Body:
What you expect, "Essentially what I am trying to do is define a log format in the main app and have any module that the main app calls use the same format.", is totally reasonable.

"how can I know the calling module name without hard coding it?"
You can use the below code to set up logger name hierarchy analogous to your Python package hierarchy.

logger = logging.getLogger(__name__)

With propagation enabled by default on all children loggers, all filtered messages will be propagated up through the hierarchical structure, and finally to the root logger, and then handled by its handler in its specified format.

For more detailed explanation of those practices of using Python logging, you may refer to Good Practices of using Python Logging


问:
Flutter: How to deobfuscate a stack trace?
I am trying to deobfuscate a flutter stack trace using the command, where err.txt is my stack trace file -

```<code>flutter symbolize -i err.txt -d /out/android/app.android-arm64.symbols
</code>```

However, on running I get an error, I require a file called app.android-arm64.symbols to deobfuscate my stack trace but I don't know where to find this file, as this isn't mentioned clearly in the Flutter documentation. This is the error I get:

```<code> /out/android/app.android-arm64.symbols does not exist
</code>```

Can someone help me out on how to do this?

答:
```<code>Firstly for obfuscation you need to run this command - >
flutter build apk --obfuscate --split-debug-info=/<project-name>/<directory>
https://docs.flutter.dev/deployment/obfuscate

With this command the symbol files will be generated in the path which you have mentioned in the obfuscated command,
Then Create a txt file in your project and copy the obfuscated stacktrace in that file..

then follow this -> https://github.com/FirebaseExtended/flutterfire/issues/2644 , Which says Remove (.java) and add 4 spaces
Then Run this command - >
flutter symbolize -i <stack trace file> -d /out/android/app.android-arm64.symbols
</code>```

Body:
I am trying to deobfuscate a flutter stack trace using the command, where err.txt is my stack trace file -

flutter symbolize -i err.txt -d /out/android/app.android-arm64.symbols

However, on running I get an error, I require a file called app.android-arm64.symbols to deobfuscate my stack trace but I don't know where to find this file, as this isn't mentioned clearly in the Flutter documentation. This is the error I get:

 /out/android/app.android-arm64.symbols does not exist

Can someone help me out on how to do this?


问:
Declaring functions inside a loop in php
Suppose, I've a function like this -

function something() {

}
```
<p>Now, I need to loop this function by changing the function name like this -</p>
<pre class="lang-php prettyprint-override"><code>function something1() {

}

function something2() {

}

function something3() {

}

function something4() {

}
</code>```

Is it possible to declare functions by loop ?? There are some other code staffs which is already looping inside of the for loop. But I can't change function names dynamically. Most importantly, I can't declare functions separately. I must do it inside a loop.

Can you help me to figure out that how can I do it??

Thanks.

答:
I Suppose you need to MASS Declare functions. but that may not be performant and is probably not the right way. you can use FUNCTION ARGUMENTS instead.

```<code>function something ($number) {
     // Do Something With The Number you got.
}

for($i = 0; $i <= 10; $i++) {
    something($i); // pass the number to the function.
}
</code>```

This is one of the ways of achieving this performantly.
You Can Learn more about it here: Function Arguments

EDIT

Although, this is not the best practice, but you can declare dynamic functions, but not in the form of functions really:

```<code><?php
for ($i = 0; $i <= 10; $i++) {
    $func_name = "something$i";
    $$func_name = function ($i) {
        echo "Hello the number is: $i";
    };
    // And call it like
    print_r($$func_name($i));
}
</code>```

The double $$ is not a typo but a feature provided by PHP.

So for example:

```<code>$a = "b";
</code>```

Then

```<code>$$a = "Hello";
</code>```

Will evaluate to

```<code>$"b"
</code>```

which would be processed by PHP like this: $b = "Hello"

And we are using that feature with functions instead.

Body:
Suppose, I've a function like this -

function something() {

}

Now, I need to loop this function by changing the function name like this -

function something1() {

}

function something2() {

}

function something3() {

}

function something4() {

}

Is it possible to declare functions by loop ?? There are some other code staffs which is already looping inside of the for loop. But I can't change function names dynamically. Most importantly, I can't declare functions separately. I must do it inside a loop.

Can you help me to figure out that how can I do it??

Thanks.

Body:
I Suppose you need to MASS Declare functions. but that may not be performant and is probably not the right way. you can use FUNCTION ARGUMENTS instead.

function something ($number) {
     // Do Something With The Number you got.
}

for($i = 0; $i <= 10; $i++) {
    something($i); // pass the number to the function.
}

This is one of the ways of achieving this performantly.
You Can Learn more about it here: Function Arguments

EDIT

Although, this is not the best practice, but you can declare dynamic functions, but not in the form of functions really:

<?php
for ($i = 0; $i <= 10; $i++) {
    $func_name = "something$i";
    $$func_name = function ($i) {
        echo "Hello the number is: $i";
    };
    // And call it like
    print_r($$func_name($i));
}

The double $$ is not a typo but a feature provided by PHP.

So for example:

$a = "b";

Then

$$a = "Hello";

Will evaluate to

$"b"

which would be processed by PHP like this: $b = "Hello"

And we are using that feature with functions instead.


问:
Duplicate records fetching in SQL Server while joining
I am joining three tables to get the data, but after joining the result set shows duplicate records.

Even if we are add the distinct  key word also getting the multiple records.

This result is 2 times A even after using distinct. My expected result will have only one .

We are provide the table name and structure, after join the first 2 table we are getting the no duplicate records, after join the third table getting the duplicate records.

We are getting the output like this attached the image check it ones

Tables are

[dbo].[t_Oed_followupDetails] tefd

[dbo].[t_vehiclenotreachedworkshop_remarks] tvnrw

[dbo].[t_vehicleEstimationNotRaised_remarks]

Table structure:

```<code>CREATE TABLE [dbo].[t_Oed_followupDetails]
(
    [id] [int] IDENTITY(1,1) NOT NULL,
    [breakdownID] [bigint] NULL,
    [vehicleNumber] [varchar](50) NULL,
    [offroadDate] [datetime] NULL,
    [workshopreachedtime] [datetime] NULL,
    [estimationRaisedTime] [datetime] NULL,
    [estimationApprovedtime] [datetime] NULL,
    [workstartTime] [datetime] NULL,
    [workendTime] [datetime] NULL,
    [PilotReachedToWs] [datetime] NULL,
    [vehiclereachedtoBacktoBase] [datetime] NULL,
    [VehicleOnroad] [datetime] NULL,
    [lastFollowupTime] [datetime] NULL,
    [progress] [int] NULL,
    [pagetoLoad] [varchar](500) NULL,
    [nextFolloupdate] [datetime] NULL
)

CREATE TABLE [dbo].[t_vehiclenotreachedworkshop_remarks]
(
    [id] [int] IDENTITY(1,1) NOT NULL,
    [breakdownid] [bigint] NULL,
    [vehicleno] [varchar](30) NULL,
    [callto] [varchar](30) NULL,
    [Reason] [varchar](100) NULL,
    [remarks] [varchar](200) NULL,
    [createdby] [varchar](30) NULL,
    [createdtime] [datetime] NULL DEFAULT (getdate()),
    [popupDate] [datetime] NULL,
    [ReasonID] [int] NULL
)

CREATE TABLE [dbo].[t_vehicleEstimationNotRaised_remarks]
(
    [id] [int] IDENTITY(1,1) NOT NULL,
    [breakdownid] [bigint] NULL,
    [vehicleno] [varchar](30) NULL,
    [callto] [varchar](30) NULL,
    [Reason] [varchar](100) NULL,
    [remarks] [varchar](200) NULL,
    [createdby] [varchar](30) NULL,
    [createdtime] [datetime] NULL DEFAULT (getdate()),
    [popupDate] [datetime] NULL,
    [ReasonID] [int] NULL
)

</code>```

After joining the 3 tables showing the result but getting the duplicate records.

My join query:

SELECT DISTINCT
    (tefd.breakdownID),
    tefd.vehicleNumber,
    tefd.offroadDate,
    tvnrw.Reason AS Reasonwnr,
    tvnrw.popupDate AS startTimewnr,
    tvnrw.createdtime AS endTimewnr,
    CAST(tvnrw.createdtime - tvnrw.popupDate AS time) AS AHTwnr,
    tvenr.Reason AS ReasonEastNotRaised,
    tvenr.popupDate AS startTimeEastNotRaised,
    tvenr.createdtime AS endTimeEastNotRaised,
    CAST(tvenr.createdtime - tvenr.popupDate AS time) AS AHTEastNotRaised
FROM
    [dbo].[t_Oed_followupDetails] tefd
LEFT JOIN
    [dbo].[t_vehiclenotreachedworkshop_remarks] tvnrw ON tefd.breakdownID = tvnrw.breakdownid
LEFT JOIN
    [dbo].[t_vehicleEstimationNotRaised_remarks] tvenr ON tvenr.breakdownid = tefd.breakdownID
WHERE
    tefd.breakdownid = 415450;
```

答:
The rows aren't duplicate. What is happening is when you join first two tables they are related to each other by 1:1 relationship meaning each record in Table A has exactly 1 record in table B. So there is no redundency. But when you join the third one, it has 1:M relation with Table (A Join B).

Now consider a student registering for multiple subjects. Your join of student with subjects will return data where student columns will have redundant values while subect columns will have distinct values. DISTINCT() wont work here because overall the row is unique even if a single column has different value.

What You can do is Use Group by. It will group your columns from A,B and Aggregate columns from C like SUM(), Count() etc. But SQL can't magically remove data just to show you single records. You will have to query your way into getting single records on the cost of data loss

Body:
I am joining three tables to get the data, but after joining the result set shows duplicate records.

Even if we are add the distinct  key word also getting the multiple records.

This result is 2 times A even after using distinct. My expected result will have only one .

We are provide the table name and structure, after join the first 2 table we are getting the no duplicate records, after join the third table getting the duplicate records.

We are getting the output like this attached the image check it ones

Tables are

[dbo].[t_Oed_followupDetails] tefd

[dbo].[t_vehiclenotreachedworkshop_remarks] tvnrw

[dbo].[t_vehicleEstimationNotRaised_remarks]

Table structure:

CREATE TABLE [dbo].[t_Oed_followupDetails]
(
    [id] [int] IDENTITY(1,1) NOT NULL,
    [breakdownID] [bigint] NULL,
    [vehicleNumber] [varchar](50) NULL,
    [offroadDate] [datetime] NULL,
    [workshopreachedtime] [datetime] NULL,
    [estimationRaisedTime] [datetime] NULL,
    [estimationApprovedtime] [datetime] NULL,
    [workstartTime] [datetime] NULL,
    [workendTime] [datetime] NULL,
    [PilotReachedToWs] [datetime] NULL,
    [vehiclereachedtoBacktoBase] [datetime] NULL,
    [VehicleOnroad] [datetime] NULL,
    [lastFollowupTime] [datetime] NULL,
    [progress] [int] NULL,
    [pagetoLoad] [varchar](500) NULL,
    [nextFolloupdate] [datetime] NULL
)

CREATE TABLE [dbo].[t_vehiclenotreachedworkshop_remarks]
(
    [id] [int] IDENTITY(1,1) NOT NULL,
    [breakdownid] [bigint] NULL,
    [vehicleno] [varchar](30) NULL,
    [callto] [varchar](30) NULL,
    [Reason] [varchar](100) NULL,
    [remarks] [varchar](200) NULL,
    [createdby] [varchar](30) NULL,
    [createdtime] [datetime] NULL DEFAULT (getdate()),
    [popupDate] [datetime] NULL,
    [ReasonID] [int] NULL
)

CREATE TABLE [dbo].[t_vehicleEstimationNotRaised_remarks]
(
    [id] [int] IDENTITY(1,1) NOT NULL,
    [breakdownid] [bigint] NULL,
    [vehicleno] [varchar](30) NULL,
    [callto] [varchar](30) NULL,
    [Reason] [varchar](100) NULL,
    [remarks] [varchar](200) NULL,
    [createdby] [varchar](30) NULL,
    [createdtime] [datetime] NULL DEFAULT (getdate()),
    [popupDate] [datetime] NULL,
    [ReasonID] [int] NULL
)

After joining the 3 tables showing the result but getting the duplicate records.

My join query:

SELECT DISTINCT
    (tefd.breakdownID),
    tefd.vehicleNumber,
    tefd.offroadDate,
    tvnrw.Reason AS Reasonwnr,
    tvnrw.popupDate AS startTimewnr,
    tvnrw.createdtime AS endTimewnr,
    CAST(tvnrw.createdtime - tvnrw.popupDate AS time) AS AHTwnr,
    tvenr.Reason AS ReasonEastNotRaised,
    tvenr.popupDate AS startTimeEastNotRaised,
    tvenr.createdtime AS endTimeEastNotRaised,
    CAST(tvenr.createdtime - tvenr.popupDate AS time) AS AHTEastNotRaised
FROM
    [dbo].[t_Oed_followupDetails] tefd
LEFT JOIN
    [dbo].[t_vehiclenotreachedworkshop_remarks] tvnrw ON tefd.breakdownID = tvnrw.breakdownid
LEFT JOIN
    [dbo].[t_vehicleEstimationNotRaised_remarks] tvenr ON tvenr.breakdownid = tefd.breakdownID
WHERE
    tefd.breakdownid = 415450;


问:
flutter how to compare two different format phone numbers
I am trying to find if two phone numbers are same or not (Two same phone number may not be in the same format, as +919998245345 is same as 9998245345 and 99982 45345)

答:
I think this is the simple and best solution to chnage format of phone</p>
```<code>String changeFormat(String phone) {
    phone = phone.replaceAll(" ", "");
    if (phone.startsWith("+")) {
      return "0" + phone.substring(3);
    } else {
      return phone;
    }
  }
</code>```

Body:
I think this is the simple and best solution to chnage format of phone

String changeFormat(String phone) {
    phone = phone.replaceAll(" ", "");
    if (phone.startsWith("+")) {
      return "0" + phone.substring(3);
    } else {
      return phone;
    }
  }


问:
How can I prevent my function from treating "0" as empty?
I have a lottery search form which concatenate six input fields into a single value and returns the ticket results based on the position. My form works correctly for numbers 1-9, but it is unable to display results when I search for 0.

I believe this is because within my get_numbers() function, the value of '0' is being treated as empty: https://www.php.net/manual/en/function.empty.php

How can I fix my if else statement to stop it treating 0 as empty?

```<code>    add_filter('wp_ajax_nopriv_get_numbers', 'get_numbers', 10);
add_filter('wp_ajax_get_numbers', 'get_numbers', 10);

function get_numbers(){
    $str = '';
    if(!empty($_POST['n_1'])){
        $str .= $_POST['n_1'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_2'])){
        $str .= $_POST['n_2'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_3'])){
        $str .= $_POST['n_3'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_4'])){
        $str .= $_POST['n_4'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_5'])){
        $str .= $_POST['n_5'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_6'])){
        $str .= $_POST['n_6'];
    }else{
        $str .= '.';
    }

    $atts = array(
        'numberposts'   => -1,
        'posts_per_page' => -1,
        'post_type'     => 'product',
        'meta_query'    => array(
            array(
                'key'       => 'product_overlay_text',
                'value'     => $str,
                'compare'   => 'REGEXP',
            ),
        ),
    );
    $the_query = new WP_Query( $atts );

    ob_start();
    if($the_query->have_posts()) :
        woocommerce_product_loop_start();
        while($the_query->have_posts()) : $the_query->the_post();
            wc_get_template_part( 'content', 'product' );
        endwhile;
        woocommerce_product_loop_end();
        $content['tickets_data'] = ob_get_clean();
    else:
        $content['tickets_data'] = 'เลขที่ท่านต้องการไม่มีในแผง';
    endif;
</code>```

答:
You're correct that empty() returns TRUE for 0.

You could instead use filter_input() with the FILTER_VALIDATE_INT filter applied.

You could even simplify the whole thing with a range map...

$str = implode("", array_map(function($i) {
    $val = filter_input(
        INPUT_POST,
        "n_$i",
        FILTER_VALIDATE_INT
    );

    return $val === null || $val === false
        ? '.'
        : $val;
}, range(1, 6)));
```

Body:
I have a lottery search form which concatenate six input fields into a single value and returns the ticket results based on the position. My form works correctly for numbers 1-9, but it is unable to display results when I search for 0.

I believe this is because within my get_numbers() function, the value of '0' is being treated as empty: https://www.php.net/manual/en/function.empty.php

How can I fix my if else statement to stop it treating 0 as empty?

    add_filter('wp_ajax_nopriv_get_numbers', 'get_numbers', 10);
add_filter('wp_ajax_get_numbers', 'get_numbers', 10);

function get_numbers(){
    $str = '';
    if(!empty($_POST['n_1'])){
        $str .= $_POST['n_1'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_2'])){
        $str .= $_POST['n_2'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_3'])){
        $str .= $_POST['n_3'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_4'])){
        $str .= $_POST['n_4'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_5'])){
        $str .= $_POST['n_5'];
    }else{
        $str .= '.';
    }
    if(!empty($_POST['n_6'])){
        $str .= $_POST['n_6'];
    }else{
        $str .= '.';
    }

    $atts = array(
        'numberposts'   => -1,
        'posts_per_page' => -1,
        'post_type'     => 'product',
        'meta_query'    => array(
            array(
                'key'       => 'product_overlay_text',
                'value'     => $str,
                'compare'   => 'REGEXP',
            ),
        ),
    );
    $the_query = new WP_Query( $atts );

    ob_start();
    if($the_query->have_posts()) :
        woocommerce_product_loop_start();
        while($the_query->have_posts()) : $the_query->the_post();
            wc_get_template_part( 'content', 'product' );
        endwhile;
        woocommerce_product_loop_end();
        $content['tickets_data'] = ob_get_clean();
    else:
        $content['tickets_data'] = 'เลขที่ท่านต้องการไม่มีในแผง';
    endif;


问:
Optimizing Left Join With Group By and Order By (MariaDb)
I am attempting to optimize a query in MariaDb that is really bogged down by its ORDER BY clause. I can run it in under a tenth of a second without the ORDER BY clause, but it takes over 25 seconds with it. Here is the gist of the query:

```<code>SELECT u.id, u.display_name, u.cell_phone, u.email,
uv.year, uv.make, uv.model, uv.id AS user_vehicle_id
FROM users u
LEFT JOIN user_vehicles uv ON uv.user_id = u.id AND uv.current_owner=1
WHERE u.is_deleted = 0
GROUP BY u.id
ORDER BY u.display_name
LIMIT 0, 10;
</code>```

I need it to be a left join because I want to include users that aren't linked to a vehicle.

I need the group by because I want only 1 result per user (and display_name is not guaranteed to be unique).

users table has about 130K rows, while user_vehicles has about 230K rows.

Here is the EXPLAIN of the query:

```<code>id  select_type table   type    possible_keys   key      key_len  ref           rows    Extra
1   SIMPLE      u       index   dms_cust_idx    PRIMARY  4        null          124825  Using where; Using temporary; Using filesort
1   SIMPLE      uv      ref     user_idx        user_idx 4        awscheduler.u.id  1   Using where

</code>```

I have tried these two indices to speed things up, but they don't seem to do much.

```<code>CREATE INDEX idx_display_speedy ON users(display_name);

CREATE INDEX idx_display_speedy2 ON users(id, display_name, is_deleted, dms_cust_id);
</code>```

I am looking for ideas on how to speed this up. I attempted using nested queries, but since the order by is the bottleneck & order within the nested query is ignored, I believe that attempt was in vain.

答:
I suspect it's not actually the ordering that is causing the problem...  If you remove the limit, I bet the ordered and un-ordered versions will end up performing pretty close to the same.

Depending on if your actual query is as simple as the one you posted, you may be able to get good performance in a single query by using RowNum() as described here:

```<code>SELECT u.id, u.display_name, u.cell_phone, u.email,
uv.year, uv.make, uv.model, uv.id AS user_vehicle_id
FROM (
    SELECT iu.id, iu.display_name, iu.cell_phone, iu.email
    FROM users iu
    WHERE iu.is_deleted = 0
    ORDER BY iu.display_name) as u
LEFT JOIN user_vehicles uv ON uv.user_id = u.id AND uv.current_owner=1
WHERE ROWNUM() < 10
GROUP BY u.id
ORDER BY u.display_name
</code>```

If that doesn't work, you probably need to select the users in one select and then select their vehicles in a second Select

Body:
I am attempting to optimize a query in MariaDb that is really bogged down by its ORDER BY clause. I can run it in under a tenth of a second without the ORDER BY clause, but it takes over 25 seconds with it. Here is the gist of the query:

SELECT u.id, u.display_name, u.cell_phone, u.email,
uv.year, uv.make, uv.model, uv.id AS user_vehicle_id
FROM users u
LEFT JOIN user_vehicles uv ON uv.user_id = u.id AND uv.current_owner=1
WHERE u.is_deleted = 0
GROUP BY u.id
ORDER BY u.display_name
LIMIT 0, 10;

I need it to be a left join because I want to include users that aren't linked to a vehicle.

I need the group by because I want only 1 result per user (and display_name is not guaranteed to be unique).

users table has about 130K rows, while user_vehicles has about 230K rows.

Here is the EXPLAIN of the query:

id  select_type table   type    possible_keys   key      key_len  ref           rows    Extra
1   SIMPLE      u       index   dms_cust_idx    PRIMARY  4        null          124825  Using where; Using temporary; Using filesort
1   SIMPLE      uv      ref     user_idx        user_idx 4        awscheduler.u.id  1   Using where

I have tried these two indices to speed things up, but they don't seem to do much.

CREATE INDEX idx_display_speedy ON users(display_name);

CREATE INDEX idx_display_speedy2 ON users(id, display_name, is_deleted, dms_cust_id);

I am looking for ideas on how to speed this up. I attempted using nested queries, but since the order by is the bottleneck & order within the nested query is ignored, I believe that attempt was in vain.

Body:
I suspect it's not actually the ordering that is causing the problem...  If you remove the limit, I bet the ordered and un-ordered versions will end up performing pretty close to the same.

Depending on if your actual query is as simple as the one you posted, you may be able to get good performance in a single query by using RowNum() as described here:

SELECT u.id, u.display_name, u.cell_phone, u.email,
uv.year, uv.make, uv.model, uv.id AS user_vehicle_id
FROM (
    SELECT iu.id, iu.display_name, iu.cell_phone, iu.email
    FROM users iu
    WHERE iu.is_deleted = 0
    ORDER BY iu.display_name) as u
LEFT JOIN user_vehicles uv ON uv.user_id = u.id AND uv.current_owner=1
WHERE ROWNUM() < 10
GROUP BY u.id
ORDER BY u.display_name

If that doesn't work, you probably need to select the users in one select and then select their vehicles in a second Select


问:
method chaining in python
(not to be confused with itertools.chain)

I was reading the following:
http://en.wikipedia.org/wiki/Method_chaining

My question is: what is the best way to implement method chaining in python?

Here is my attempt:

```<code>class chain():
    def __init__(self, my_object):
        self.o = my_object

    def __getattr__(self, attr):
        x = getattr(self.o, attr)
        if hasattr(x, '__call__'):
            method = x
            return lambda *args: self if method(*args) is None else method(*args)
        else:
            prop = x
            return prop

list_ = chain([1, 2, 3, 0])
print list_.extend([9, 5]).sort().reverse()

"""
C:\Python27\python.exe C:/Users/Robert/PycharmProjects/contests/sof.py
[9, 5, 3, 2, 1, 0]
"""
</code>```

One problem is if calling method(*args) modifies self.o but doesn't return None. (then should I return self or return what method(*args) returns).

Does anyone have better ways of implementing chaining? There are probably many ways to do it.

Should I just assume a method always returns None so I may always return self.o ?

答:
What about

```<code>def apply(data, *fns):
    return data.__class__(map(fns[-1], apply(data, *fns[:-1]))) if fns else data

>>> print(
...   apply(
...     [1,2,3],
...     str,
...     lambda x: {'1': 'one', '2': 'two', '3': 'three'}[x],
...     str.upper))
['ONE', 'TWO', 'THREE']
>>>
</code>```

?

.. even keeps the type :)

ContentLicense: CC BY-SA 3.0

Title: method chaining in python

Body:
(not to be confused with itertools.chain)

I was reading the following:
http://en.wikipedia.org/wiki/Method_chaining

My question is: what is the best way to implement method chaining in python?

Here is my attempt:

class chain():
    def __init__(self, my_object):
        self.o = my_object

    def __getattr__(self, attr):
        x = getattr(self.o, attr)
        if hasattr(x, '__call__'):
            method = x
            return lambda *args: self if method(*args) is None else method(*args)
        else:
            prop = x
            return prop

list_ = chain([1, 2, 3, 0])
print list_.extend([9, 5]).sort().reverse()

"""
C:\Python27\python.exe C:/Users/Robert/PycharmProjects/contests/sof.py
[9, 5, 3, 2, 1, 0]
"""

One problem is if calling method(*args) modifies self.o but doesn't return None. (then should I return self or return what method(*args) returns).

Does anyone have better ways of implementing chaining? There are probably many ways to do it.

Should I just assume a method always returns None so I may always return self.o ?

Body:
What about

def apply(data, *fns):
    return data.__class__(map(fns[-1], apply(data, *fns[:-1]))) if fns else data

>>> print(
...   apply(
...     [1,2,3],
...     str,
...     lambda x: {'1': 'one', '2': 'two', '3': 'three'}[x],
...     str.upper))
['ONE', 'TWO', 'THREE']
>>>

?

.. even keeps the type :)


问:
how to access snapshot.data inside Listview.builder inside futurebuilder
I am getting error The method '[]' can't be unconditionally invoked because the receiver can be 'null'.

Mydata inside _categoriesList future

```<code>[
        {
            "business_category_id": 1,
            "business_category": "Manufacturer",
            "business_category_image": "164423936662011a06c450d.png"
        },
        {
            "business_category_id": 2,
            "business_category": "Distributor",
            "business_category_image": "164423937762011a11033aa.png"
        },
        {
            "business_category_id": 3,
            "business_category": "Wholesaler",
            "business_category_image": "164423938762011a1bb2e3c.png"
        },
        {
            "business_category_id": 4,
            "business_category": "Retailer",
            "business_category_image": "164423940062011a28189e5.png"
        },
        {
            "business_category_id": 5,
            "business_category": "Reseller",
            "business_category_image": "164423941362011a3554148.png"
        },
        {
            "business_category_id": 6,
            "business_category": "Service Provider",
            "business_category_image": "164423942462011a4096996.png"
        }
    ]
</code>```

my code inside futurebuilder. I am having problem accessing snapshot.data[index]

```<code>FutureBuilder(
      future: _categoriesList,
      builder: (_, snapshot) {
        if (snapshot.hasData) {

          return ListView.builder(
              itemCount: 6,
              itemBuilder: (_, index) {
                return Text(snapshot.data[index]); // error The method '[]' can't be unconditionally invoked because the receiver can be 'null'
              });
        }
      },
)
</code>```

答:
Here is the example for ListView.builder:</p>
```<code>import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future <List<Data>> fetchData() async {
  final response =
      await http.get('https://jsonplaceholder.typicode.com/albums');
  if (response.statusCode == 200) {
    List jsonResponse = json.decode(response.body);
      return jsonResponse.map((data) => new Data.fromJson(data)).toList();
  } else {
    throw Exception('Unexpected error occured!');
  }
}

class Data {
  final int userId;
  final int id;
  final String title;

  Data({this.userId, this.id, this.title});

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Future <List<Data>> futureData;

  @override
  void initState() {
    super.initState();
    futureData = fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter API and ListView Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter ListView'),
        ),
        body: Center(
          child: FutureBuilder <List<Data>>(
            future: futureData,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List<Data> data = snapshot.data;
                return
                ListView.builder(
                itemCount: data.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    height: 75,
                    color: Colors.white,
                    child: Center(child: Text(data[index].title),
                  ),);
                }
              );
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }
              // By default show a loading spinner.
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}
</code>```

Body:
I am getting error The method '[]' can't be unconditionally invoked because the receiver can be 'null'.

Mydata inside _categoriesList future

[
        {
            "business_category_id": 1,
            "business_category": "Manufacturer",
            "business_category_image": "164423936662011a06c450d.png"
        },
        {
            "business_category_id": 2,
            "business_category": "Distributor",
            "business_category_image": "164423937762011a11033aa.png"
        },
        {
            "business_category_id": 3,
            "business_category": "Wholesaler",
            "business_category_image": "164423938762011a1bb2e3c.png"
        },
        {
            "business_category_id": 4,
            "business_category": "Retailer",
            "business_category_image": "164423940062011a28189e5.png"
        },
        {
            "business_category_id": 5,
            "business_category": "Reseller",
            "business_category_image": "164423941362011a3554148.png"
        },
        {
            "business_category_id": 6,
            "business_category": "Service Provider",
            "business_category_image": "164423942462011a4096996.png"
        }
    ]

my code inside futurebuilder. I am having problem accessing snapshot.data[index]

FutureBuilder(
      future: _categoriesList,
      builder: (_, snapshot) {
        if (snapshot.hasData) {

          return ListView.builder(
              itemCount: 6,
              itemBuilder: (_, index) {
                return Text(snapshot.data[index]); // error The method '[]' can't be unconditionally invoked because the receiver can be 'null'
              });
        }
      },
)

Body:
Here is the example for ListView.builder:

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future <List<Data>> fetchData() async {
  final response =
      await http.get('https://jsonplaceholder.typicode.com/albums');
  if (response.statusCode == 200) {
    List jsonResponse = json.decode(response.body);
      return jsonResponse.map((data) => new Data.fromJson(data)).toList();
  } else {
    throw Exception('Unexpected error occured!');
  }
}

class Data {
  final int userId;
  final int id;
  final String title;

  Data({this.userId, this.id, this.title});

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Future <List<Data>> futureData;

  @override
  void initState() {
    super.initState();
    futureData = fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter API and ListView Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter ListView'),
        ),
        body: Center(
          child: FutureBuilder <List<Data>>(
            future: futureData,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List<Data> data = snapshot.data;
                return
                ListView.builder(
                itemCount: data.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    height: 75,
                    color: Colors.white,
                    child: Center(child: Text(data[index].title),
                  ),);
                }
              );
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }
              // By default show a loading spinner.
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}


问:
Wireshark PCAP file to csv
Looking for an module in python which could read PCAP file and write it to csv format.
Have explored pyshark module - unable to get output in required form</p>
```<code>capture = pyshark.FileCapture(r"C:\Temp\wireshark\data.pcap")
for pkt in capture:
    pkt = str(pkt)
    out.write(pkt)
</code>```

答:
try module rdpcap

read here for more info - https://medium.com/@vworri/extracting-the-payload-from-a-pcap-file-using-python-d938d7622d71

```<code>pkts = rdpcap('example.pcap')

with open("Pcap/test.csv", "w") as f:
    for pkt in pkts:

        if IP in pkt:
            ip_src=pkt[IP].src
            ip_dst=pkt[IP].dst
        if TCP in pkt:
            tcp_dport=pkt[TCP].dport

            csv_header = "IP_src,IP_drc,dst_port\n"

            s = ""
            for scr in str(ip_src):
                s+=str(scr)
            csv_header += s + ','

            s_ = ''
            for dst in str(ip_dst) :
                s_+=str(dst)
            csv_header += s_ + ','

            s_1 = ''
            for dst_tcp in str(tcp_dport):
                s_1 += str(dst_tcp)
            csv_header += s_1

            f.write(csv_header)
</code>```

Title: Wireshark PCAP file to csv

Body:
Looking for an module in python which could read PCAP file and write it to csv format.
Have explored pyshark module - unable to get output in required form

capture = pyshark.FileCapture(r"C:\Temp\wireshark\data.pcap")
for pkt in capture:
    pkt = str(pkt)
    out.write(pkt)

Body:
try module rdpcap

read here for more info - https://medium.com/@vworri/extracting-the-payload-from-a-pcap-file-using-python-d938d7622d71

pkts = rdpcap('example.pcap')

with open("Pcap/test.csv", "w") as f:
    for pkt in pkts:

        if IP in pkt:
            ip_src=pkt[IP].src
            ip_dst=pkt[IP].dst
        if TCP in pkt:
            tcp_dport=pkt[TCP].dport

            csv_header = "IP_src,IP_drc,dst_port\n"

            s = ""
            for scr in str(ip_src):
                s+=str(scr)
            csv_header += s + ','

            s_ = ''
            for dst in str(ip_dst) :
                s_+=str(dst)
            csv_header += s_ + ','

            s_1 = ''
            for dst_tcp in str(tcp_dport):
                s_1 += str(dst_tcp)
            csv_header += s_1

            f.write(csv_header)


问:
Is it possible to show alert in `clickedButtonAtIndex` method of alertview
In delegate method ofUIalerview I am trying to show another alert after finishing the process on clicking button index. Is it possible to do so?  Also I want to call a method on button click of alert. How can I do that?

I am trying in this way. Is is correct?

```<code>- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        inappPurchaseViewController  = [[InAppPurchaseViewController alloc] init];
        [inappPurchaseViewController Upgrade:nil];
        [inappPurchaseViewController release];

        UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [purchasedone show];
        [purchasedone release];
    }
}
</code>```

答:
put the following line on top of your .m file</p>

```<code>`#define PREVIOUS_ALERT 101`
`#define NEW_ALERT 102`

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    //you need to make a condition here for checking the alert else it will go into infinite loom of showing alert after alert
    //you can do it by setting tag to alert something like this
    if(alertView.tag == PREVIOUS_ALERT) //sot the previous alert tag to this where you created it
    {
        if(buttonIndex == 1)
        {

            inappPurchaseViewController  = [[InAppPurchaseViewController alloc] init];
            [inappPurchaseViewController Upgrade:nil];
            [inappPurchaseViewController release];

            UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            purchasedone.tag = NEW_ALERT;
            [purchasedone show];
            [purchasedone release];
        }
    }
    else
    {
        //code for your second alert
    }
}
</code>```

Body:
In delegate method ofUIalerview I am trying to show another alert after finishing the process on clicking button index. Is it possible to do so?  Also I want to call a method on button click of alert. How can I do that?

I am trying in this way. Is is correct?

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        inappPurchaseViewController  = [[InAppPurchaseViewController alloc] init];
        [inappPurchaseViewController Upgrade:nil];
        [inappPurchaseViewController release];

        UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [purchasedone show];
        [purchasedone release];
    }
}

Body:
put the following line on top of your .m file

`#define PREVIOUS_ALERT 101`
`#define NEW_ALERT 102`

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    //you need to make a condition here for checking the alert else it will go into infinite loom of showing alert after alert
    //you can do it by setting tag to alert something like this
    if(alertView.tag == PREVIOUS_ALERT) //sot the previous alert tag to this where you created it
    {
        if(buttonIndex == 1)
        {

            inappPurchaseViewController  = [[InAppPurchaseViewController alloc] init];
            [inappPurchaseViewController Upgrade:nil];
            [inappPurchaseViewController release];

            UIAlertView *purchasedone = [[UIAlertView alloc] initWithTitle:@"Enable Ads" message:@"You can Enable Ads from Settings Option" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            purchasedone.tag = NEW_ALERT;
            [purchasedone show];
            [purchasedone release];
        }
    }
    else
    {
        //code for your second alert
    }
}


问:
Heroku deployment: How can I point my app to app/client/build?
How can I point my app to app/client/build?

I get the error: "Error: ENOENT: no such file or directory, stat '/app/server/build/index.html'" when deploying my app to Heroku. I added my package.json, server.js and my app structure.

App ->

->Client

-build

-public

-src

-components

-App.js

-index.js

->Server

-db

-routes

-server.js

-package.json

-Procfile

etc....

It needs to point to app/client/build/index.html.

I don't know where heroku is getting the app/server part in app/server/build/index.html from, I know it is getting build/index.html part from the below code found in server.js:

'''

```<code>// server static in prod env
if(process.env.NODE_ENV === 'production') {
//   Set static folder
  app.use(express.static('build'));

  app.get('*', (req,res) => {
  res.sendFile(path.resolve(__dirname, 'build', 'index.html'))
  });
}
</code>```

'''
Full server.js file
'''

```<code>const express = require("express");
const app = express();
const path = require('path');
const cors = require("cors");
require("dotenv").config({ path: "config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));
// get driver connection
const dbo = require("./db/conn");

// server static in prod env
if(process.env.NODE_ENV === 'production') {
//   Set static folder
  app.use(express.static('build'));

  app.get('*', (req,res) => {
  res.sendFile(path.resolve(__dirname, 'build', 'index.html'))
  });
}

app.listen(port, () => {
  // perform a database connection when server starts
  dbo.connectToServer(function (err) {
    if (err) console.error(err);

  });
  console.log(`Server is running on port: ${port}`);
});
</code>```

'''

I suspect 'app/server/' part might be coming from the way npm builds the app but I just a suspicion.
package.json:

'''

```<code>    {
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "cd server && node server.js",
    "heroku-post-build": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client",
    "server": "cd server && node server.js",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\"",
    "test": "echo \"Error: no test specified\" && exit 1"
    },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "concurrently": "^7.0.0",
    "cors": "^2.8.5",
    "dotenv": "^14.2.0",
    "express": "^4.17.2",
    "mongodb": "^4.3.1"
  }
}
</code>```

'''

Please let me know if I should add other files that may help troubleshoot this. This community is amazing btw! So glad for everything I'm learning on this platform.

答:
I added client/build to the static and resolve statements and the app now points to the build folder on heroku:

'''

```<code>app.use(express.static('client/build'));

  app.get('*', (req,res) => {
  res.sendFile(path.resolve(__dirname, 'client/build', 'index.html'))
  });
</code>```

'''

Body:
How can I point my app to app/client/build?

I get the error: "Error: ENOENT: no such file or directory, stat '/app/server/build/index.html'" when deploying my app to Heroku. I added my package.json, server.js and my app structure.

App ->

->Client

-build

-public

-src

-components

-App.js

-index.js

->Server

-db

-routes

-server.js

-package.json

-Procfile

etc....

It needs to point to app/client/build/index.html.

I don't know where heroku is getting the app/server part in app/server/build/index.html from, I know it is getting build/index.html part from the below code found in server.js:

'''

// server static in prod env
if(process.env.NODE_ENV === 'production') {
//   Set static folder
  app.use(express.static('build'));

  app.get('*', (req,res) => {
  res.sendFile(path.resolve(__dirname, 'build', 'index.html'))
  });
}

'''
Full server.js file
'''

const express = require("express");
const app = express();
const path = require('path');
const cors = require("cors");
require("dotenv").config({ path: "config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));
// get driver connection
const dbo = require("./db/conn");

// server static in prod env
if(process.env.NODE_ENV === 'production') {
//   Set static folder
  app.use(express.static('build'));

  app.get('*', (req,res) => {
  res.sendFile(path.resolve(__dirname, 'build', 'index.html'))
  });
}

app.listen(port, () => {
  // perform a database connection when server starts
  dbo.connectToServer(function (err) {
    if (err) console.error(err);

  });
  console.log(`Server is running on port: ${port}`);
});

'''

I suspect 'app/server/' part might be coming from the way npm builds the app but I just a suspicion.
package.json:

'''

    {
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "cd server && node server.js",
    "heroku-post-build": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client",
    "server": "cd server && node server.js",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\"",
    "test": "echo \"Error: no test specified\" && exit 1"
    },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "concurrently": "^7.0.0",
    "cors": "^2.8.5",
    "dotenv": "^14.2.0",
    "express": "^4.17.2",
    "mongodb": "^4.3.1"
  }
}

'''

Please let me know if I should add other files that may help troubleshoot this. This community is amazing btw! So glad for everything I'm learning on this platform.

Body:
I added client/build to the static and resolve statements and the app now points to the build folder on heroku:

'''

app.use(express.static('client/build'));

  app.get('*', (req,res) => {
  res.sendFile(path.resolve(__dirname, 'client/build', 'index.html'))
  });

'''


问:
how can i display this data from an api which is in format of json and array
What i want to achieve is to display this data in a dashboard for example risk name how many they are etc i using laravel
how can i fetch it and display it to the blade

```<code>https://portal.zebratop.co.ke/api/v1/powerbi/dashboards/risk
</code>```

this what i a have tried

```<code>    public function index()
    {
        $Total_users = User::all();

        $response = Http::acceptJson()
            ->get('https://portal.zebratop.co.ke/api/v1/powerbi/dashboards/risk');

        if($response->failed()){
            // Handle failure here
        }

        // Data was fetched successfully
        $data = collect($response->json());

        $data = $data->mapToDictionary(function($data, $key){
            $key = $data[0]['Business Unit'];
            //$key = $data[1]['Risk Name'];
            return [$key => $data];
        });

        $count = 0;

        $data = $data->map(function($data) use ($count){
            $count += count($data[0]);
            return $data[0];
        });
        //dd($data);

        // Pass the data to view
        return view('home',compact('Total_users','data'));
        //return view('view.name', compact('data'));
    }
</code>```

this the blade

```<code>
<tr>
    <th class="text-center" colspan="2"><h5 align ="center"><b>Business Unit</b>:{{$data->count()}}</h5></th>
</tr>
<tr>
     <th><h6><b>{{$data[Risk Name]}}</b></h6></th>
</tr>
</code>```

答:
Try using curl to fetch the data from the endpoint.

```<code>$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://portal.zebratop.co.ke/api/v1/powerbi/dashboards/risk',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'Cookie: XSRF-TOKEN=eyJpdiI6Im5sb0JHVTFjZUhkQ2xrRTl1Nlp5RFE9PSIsInZhbHVlIjoiSC9oYXZUMHZMSlpHa0sxbnBrUW12a2o2K014S25Ba2dmSzY3cDIwWWF5M2lwWXdDRnAvbHVmYXZMbnM4SitNeEtrdXQ2V2pucUxzdWFwa2dJWGZ5c2hHZ0I0L0NrV1hTZjNTRWZvOVRidzZ2SE5wbVFRcVhsenF4b3A4NFA3VUIiLCJtYWMiOiI2Y2EyM2ZjZDQzNWFjNjYzYjU1NTg0ZjI3Y2UwYjdhYzM1NmUwYmNhZGExZjViMmRlMTBiMTAyM2ViMDFmMzZhIn0%3D; risk_management_system_session=eyJpdiI6IkpKK215cktjWlc0Q1VWbnVxNmN4UUE9PSIsInZhbHVlIjoiZU9YbXhRUTdIQ2t5OEV5dWw2ZVJXT2lHMnBGSXhBMk9WSFhuS3pTbVhRTWRPZTFrUHRLMGo0Z1Y0aGMrZ25tZ2JkeXRrRi92WTUzMFRYTXhxVG9pWDQwN3JzQiszcnVkUTFzVGk3RDNJSHB3UWpjV1VPTEF6Zk54VDhxRGdDSEsiLCJtYWMiOiJlZmQ4MGM0NmI2M2YwN2FmOTkyODcxYTliY2RjZjI4ZWZlY2ZjYWIzZjE0ODBjY2M1MzM5MzNmNjU0MjRjNjJiIn0%3D'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
</code>```

Then use json_decode($response) to convert into php array.

Body:
What i want to achieve is to display this data in a dashboard for example risk name how many they are etc i using laravel
how can i fetch it and display it to the blade

https://portal.zebratop.co.ke/api/v1/powerbi/dashboards/risk

this what i a have tried

    public function index()
    {
        $Total_users = User::all();

        $response = Http::acceptJson()
            ->get('https://portal.zebratop.co.ke/api/v1/powerbi/dashboards/risk');

        if($response->failed()){
            // Handle failure here
        }

        // Data was fetched successfully
        $data = collect($response->json());

        $data = $data->mapToDictionary(function($data, $key){
            $key = $data[0]['Business Unit'];
            //$key = $data[1]['Risk Name'];
            return [$key => $data];
        });

        $count = 0;

        $data = $data->map(function($data) use ($count){
            $count += count($data[0]);
            return $data[0];
        });
        //dd($data);

        // Pass the data to view
        return view('home',compact('Total_users','data'));
        //return view('view.name', compact('data'));
    }

this the blade

Business Unit:{{$data->count()}}

{{$data[Risk Name]}}

Body:
Try using curl to fetch the data from the endpoint.

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://portal.zebratop.co.ke/api/v1/powerbi/dashboards/risk',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'Cookie: XSRF-TOKEN=eyJpdiI6Im5sb0JHVTFjZUhkQ2xrRTl1Nlp5RFE9PSIsInZhbHVlIjoiSC9oYXZUMHZMSlpHa0sxbnBrUW12a2o2K014S25Ba2dmSzY3cDIwWWF5M2lwWXdDRnAvbHVmYXZMbnM4SitNeEtrdXQ2V2pucUxzdWFwa2dJWGZ5c2hHZ0I0L0NrV1hTZjNTRWZvOVRidzZ2SE5wbVFRcVhsenF4b3A4NFA3VUIiLCJtYWMiOiI2Y2EyM2ZjZDQzNWFjNjYzYjU1NTg0ZjI3Y2UwYjdhYzM1NmUwYmNhZGExZjViMmRlMTBiMTAyM2ViMDFmMzZhIn0%3D; risk_management_system_session=eyJpdiI6IkpKK215cktjWlc0Q1VWbnVxNmN4UUE9PSIsInZhbHVlIjoiZU9YbXhRUTdIQ2t5OEV5dWw2ZVJXT2lHMnBGSXhBMk9WSFhuS3pTbVhRTWRPZTFrUHRLMGo0Z1Y0aGMrZ25tZ2JkeXRrRi92WTUzMFRYTXhxVG9pWDQwN3JzQiszcnVkUTFzVGk3RDNJSHB3UWpjV1VPTEF6Zk54VDhxRGdDSEsiLCJtYWMiOiJlZmQ4MGM0NmI2M2YwN2FmOTkyODcxYTliY2RjZjI4ZWZlY2ZjYWIzZjE0ODBjY2M1MzM5MzNmNjU0MjRjNjJiIn0%3D'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

Then use json_decode($response) to convert into php array.


问:
When div is visible on screen add .active class to li
I am trying to build a page:
Like This

When a div gets into the view on the screen, then a class gets added to the right side of the "table of contents", then when it's scrolled off the screen and another div shows up the class gets moved to the next "title" of the content.

So far I have a list of divs stacked on the top of each other and some basic JS but it does not work. I am not even sure if this is a good approach to get this done?

```<code>$(window).scroll(function(){
  if ( $('#field-wrap1').offset().top <= 100 ) {
    $('#slide-li1').addClass("active");
  }else{
    $('#slide-li1').removeClass("active");
  }
});
</code>```

JSFiddle

答:
section_1

section_2

section_3

section_4

section_5

section_1

section_2

section_3

section_4

section_5

```

Body:
I am trying to build a page:
Like This

When a div gets into the view on the screen, then a class gets added to the right side of the "table of contents", then when it's scrolled off the screen and another div shows up the class gets moved to the next "title" of the content.

So far I have a list of divs stacked on the top of each other and some basic JS but it does not work. I am not even sure if this is a good approach to get this done?

$(window).scroll(function(){
  if ( $('#field-wrap1').offset().top <= 100 ) {
    $('#slide-li1').addClass("active");
  }else{
    $('#slide-li1').removeClass("active");
  }
});

JSFiddle

Body:
<!---
With this code it doesn't require editing the JavaScript
at all, only the HTML/CSS, it will apply the class .qqq_menu_active
to the active menu item and .qqq_section_active to the active section.
--->

<style>
* {
    font-family: Arial;
    margin: 0;
    padding: 0;
}
body {
    font-size: 10pt;
}
.qqq_container {
    padding: 50px;
}
.qqq_menu {
    position: fixed;
    width: 200px;
    left: 750px;
    top: 50px;
}
.qqq_menu_item {
    color: #333;
}
.qqq_menu_active {
    font-size: 14pt;
    font-weight: bold;
    color: #000;
}
.qqq_section {
    width: 600px;
    padding: 25px;
    color: #676767;
    background-color: #fff;
}
.qqq_section_active {
    color: #281c96;
    background-color: #bdb6ff;
}
h1 {
    padding-bottom: 20px;
}
</style>

<div class="qqq_menu">
<div class='qqq_menu_item'>section_1</div>
<div class='qqq_menu_item'>section_2</div>
<div class='qqq_menu_item'>section_3</div>
<div class='qqq_menu_item'>section_4</div>
<div class='qqq_menu_item'>section_5</div>
</div>

<div class='qqq_container'>
<div class='qqq_section'>
<h1>section_1</h1>
<p class='text_fill'></p>
</div>
<div class='qqq_section'>
<h1>section_2</h1>
<p class='text_fill'></p>
</div>
<div class='qqq_section'>
<h1>section_3</h1>
<p class='text_fill'></p>
</div>
<div class='qqq_section'>
<h1>section_4</h1>
<p class='text_fill'></p>
</div>
<div class='qqq_section'>
<h1>section_5</h1>
<p class='text_fill'></p>
</div>
</div>

<script>
// note: have tried editing .repeat to 3000 to make it a lot of text and 150 to make it a little text and still works right. also added a bunch of space with <br /> above and below the .qqq_container element and still works right.
asdf_text = "asdf ".repeat(750);
document.querySelectorAll(".text_fill").forEach(function (element) {
    element.innerHTML = asdf_text;
});
container = document.querySelectorAll(".qqq_container")[0];
sections = document.querySelectorAll(".qqq_section");
menu = document.querySelectorAll(".qqq_menu_item");

percentage = 0;
function qqq_menu_highlight() {
    active = 0;
    ttt = window.innerHeight / 100;
    lll = ttt * percentage;
    zzz = window.scrollY + lll;
    sections.forEach(function (v, k, l) {
        if (zzz > v.offsetTop) {
            active = k;
        }
    });
    menu.forEach(function (v, k, l) {
        if (active === k) {
            v.classList.add('qqq_menu_active');
        } else {
            v.classList.remove('qqq_menu_active');
        }
    });
    sections.forEach(function (v, k, l) {
        if (active === k) {
            v.classList.add('qqq_section_active');
        } else {
            v.classList.remove('qqq_section_active');
        }
    });
}
function element_scroll_percentage(element) {
    //inc = (document.body.scrollHeight - window.innerHeight) / 100;
    //console.log(active);
    rect = element.getBoundingClientRect();
    if (Math.sign(rect.top) == -1) {
        value = Math.abs(rect.top);
        inc = (rect.height - window.innerHeight) / 100;
        percentage = value / inc;
        if (percentage > 100) {
            percentage = 100;
        }
    } else {
        percentage = 0;
    }
    return percentage;
}
document.onscroll = function() {
    percentage = element_scroll_percentage(container);
    qqq_menu_highlight();
    //console.log(percentage);
}
document.onscroll();
</script>


问:
Only 1 item is showed in recyclerView and it doesn't even scroll down
I'm starting android development and i was creating a simple recyclerview.
I think code is completely fine but when i run the app only one item is displayed and it isn't even scrolling down.

Here is my main xml file.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="0dp"
        android:layout_height="60dp"
        android:layout_marginTop="4dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.494"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

And this is my main java file.

```<code>package com.example.creatingrecyclerview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    RecyclerView r;
    String arr[]={"1","2","3","4","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        r=findViewById(R.id.rv);
        r.setLayoutManager(new LinearLayoutManager(this));
        CustomAdapter c=new CustomAdapter(arr);
        r.setAdapter(c);
    }
}
</code>```

This is my customadapter class and its xml file.

```<code>package com.example.creatingrecyclerview;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private String[] localDataSet;

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView = (TextView) view.findViewById(R.id.textView2);
        }

        public TextView getTextView() {
            return textView;
        }
    }

    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used
     * by RecyclerView.
     */
    public CustomAdapter(String[] dataSet) {
        localDataSet = dataSet;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.mylayout, viewGroup, false);

        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // Get element from your dataset at this position and replace the
        // contents of the view with that element
        viewHolder.getTextView().setText(localDataSet[viewHolder.getAdapterPosition()]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return localDataSet.length;
    }
}
</code>```

And it's xml file.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="124dp"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:layout_weight="1"
            android:text="TextView" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Any help will be appreciated:)

答:
I think you are missing orientation of  recycle view

```<code> r.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
</code>```

if you want Horizontal scroll set

```<code>LinearLayoutManager.Horizontal
</code>```

Body:
I'm starting android development and i was creating a simple recyclerview.
I think code is completely fine but when i run the app only one item is displayed and it isn't even scrolling down.

Here is my main xml file.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="0dp"
        android:layout_height="60dp"
        android:layout_marginTop="4dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.494"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

And this is my main java file.

package com.example.creatingrecyclerview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    RecyclerView r;
    String arr[]={"1","2","3","4","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        r=findViewById(R.id.rv);
        r.setLayoutManager(new LinearLayoutManager(this));
        CustomAdapter c=new CustomAdapter(arr);
        r.setAdapter(c);
    }
}

This is my customadapter class and its xml file.

package com.example.creatingrecyclerview;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private String[] localDataSet;

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView = (TextView) view.findViewById(R.id.textView2);
        }

        public TextView getTextView() {
            return textView;
        }
    }

    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used
     * by RecyclerView.
     */
    public CustomAdapter(String[] dataSet) {
        localDataSet = dataSet;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.mylayout, viewGroup, false);

        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // Get element from your dataset at this position and replace the
        // contents of the view with that element
        viewHolder.getTextView().setText(localDataSet[viewHolder.getAdapterPosition()]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return localDataSet.length;
    }
}

And it's xml file.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="124dp"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:layout_weight="1"
            android:text="TextView" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Any help will be appreciated:)

Body:
I think you are missing orientation of  recycle view

 r.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));

if you want Horizontal scroll set

LinearLayoutManager.Horizontal


问:
How to get an absolute file path in Python
Given a path such as "mydir/myfile.txt", how do I find the file's absolute path in Python? E.g. on Windows, I might end up with:

```<code>"C:/example/cwd/mydir/myfile.txt"
</code>```

答:
Given a path such as mydir/myfile.txt, how do I find the file's absolute path relative to the current working directory in Python?

I would do it like this,

import os.path
os.path.join( os.getcwd(), 'mydir/myfile.txt' )
```

That returns '/home/ecarroll/mydir/myfile.txt'

OwnerDisplayName: izb

Body:
Given a path such as "mydir/myfile.txt", how do I find the file's absolute path in Python? E.g. on Windows, I might end up with:

"C:/example/cwd/mydir/myfile.txt"

Body:
Given a path such as mydir/myfile.txt, how do I find the file's absolute path relative to the current working directory in Python?

I would do it like this,

import os.path
os.path.join( os.getcwd(), 'mydir/myfile.txt' )

That returns '/home/ecarroll/mydir/myfile.txt'


问:
While syncing or executing PAF scripts to ALM if an error occurs with the following keywords <link> or
 .How to resolve this issue?
While syncing or executing PAF scripts to ALM if an error occurs with the following keywords **<link>** or **
** .How to resolve this issue?

答: Check whether we have special characters in the activity files and flow files.</p>

Title: While syncing or executing PAF scripts to ALM if an error occurs with the following keywords <link> or </hr> .How to resolve this issue?


问:
How to correctly refresh auth token in the background google-apis using flutter
Right now I use the method clientViaUserConsent, to authenticate my user and thus be able to use the Google API, in this case, calendar api, the problem is that the way it is built now requests this permission every time the user enters the app, this it is a problem since it is annoying for the user,

Is there a way to do this automatically by refreshing the authentication token in the background every time the user enters the app?

I understand the idea of storing the token and the refresh token but I don't know how to implement it

here is my code:

var _clientID = new ClientId(Secret.getId(), "");
    const _scopes = const [cal.CalendarApi.calendarScope];
    await clientViaUserConsent(_clientID, _scopes, Prompt.prompt).then((AuthClient client) async {
      CalendarClient.calendar = cal.CalendarApi(client);
      print(client);
    });
```

答:
Yes, the credentials are stored in the client variable.

```<code>AccessToken: client.credentials.accessToken.data
RefreshToken: client.credentials.refreshToken
Expiration: client.credentials.accessToken.expiry
IDToken: client.credentials.idToken
</code>```

You can then store these and build a new request later when they sign in as such:

```<code>void getEventsPastAuth() async {
  var client = Client();
  AccessCredentials credentials = await _calendarCredentials.getCredetial();
  AccessCredentials refreshedCred =
      await refreshCredentials(_credentialsID, credentials, client);

  client = autoRefreshingClient(_credentialsID, credentials, client);
  var calendar = CalendarApi(client);
  var now = DateTime.now();
  var calEvents = calendar.events.list('primary',
      maxResults: 100,
      timeMin: now,
      timeMax: DateTime(now.year, now.month + 1, now.day));
  calEvents.then((Events events) {
    events.items!.forEach((Event event) {
      debugPrint(event.summary);
    });
  });
}
</code>```

The variable credentials is the stored variables as an AccessCredential

```<code>AccessCredentials(
      AccessToken("Bearer", accessToken, DateTime.parse(expiration)),
      refreshToken,
      _scopes,
      idToken: idToken);
</code>```

If you figure out how to have access to multiple user's calendars simultaneously, let me know. I'm currently struggling on figuring out how I can search multiple users' calendars after user consent in Flutter.

Body:
Yes, the credentials are stored in the client variable.

AccessToken: client.credentials.accessToken.data
RefreshToken: client.credentials.refreshToken
Expiration: client.credentials.accessToken.expiry
IDToken: client.credentials.idToken

You can then store these and build a new request later when they sign in as such:

void getEventsPastAuth() async {
  var client = Client();
  AccessCredentials credentials = await _calendarCredentials.getCredetial();
  AccessCredentials refreshedCred =
      await refreshCredentials(_credentialsID, credentials, client);

  client = autoRefreshingClient(_credentialsID, credentials, client);
  var calendar = CalendarApi(client);
  var now = DateTime.now();
  var calEvents = calendar.events.list('primary',
      maxResults: 100,
      timeMin: now,
      timeMax: DateTime(now.year, now.month + 1, now.day));
  calEvents.then((Events events) {
    events.items!.forEach((Event event) {
      debugPrint(event.summary);
    });
  });
}

The variable credentials is the stored variables as an AccessCredential

AccessCredentials(
      AccessToken("Bearer", accessToken, DateTime.parse(expiration)),
      refreshToken,
      _scopes,
      idToken: idToken);

If you figure out how to have access to multiple user's calendars simultaneously, let me know. I'm currently struggling on figuring out how I can search multiple users' calendars after user consent in Flutter.


问:
(Tradingview - Pine Script) Convert iff Function to v5 error
I tried to convert pine v2 iff function to v5 but I kept getting this error:

```<code>line 32: Undeclared identifier 'vwapsum';
line 33: Undeclared identifier 'volumesum';
line 34: Undeclared identifier 'v2sum'
</code>```

this one is original v2 script:

```<code>newSession = iff(change(start), 1, 0)
vwapsum = iff(newSession, hl2*volume, vwapsum[1]+hl2*volume)
volumesum = iff(newSession, volume, volumesum[1]+volume)
v2sum = iff(newSession, volume*hl2*hl2, v2sum[1]+volume*hl2*hl2)
myvwap = vwapsum/volumesum
dev = sqrt(max(v2sum/volumesum - myvwap*myvwap, 0))
</code>```

and this is one v5 that I tried to create but give an error

```<code>newSession = ta.change(start) ? 1 : 0
vwapsum     = newSession    ?   hl2*volume      : vwapsum[1]+hl2*volume
volumesum   = newSession    ?   volume          : volumesum[1]+volume
v2sum       = newSession    ?   volume*hl2*hl2  : v2sum[1]+volume*hl2*hl2
myvwap      = vwapsum/volumesum
dev         = math.sqrt(math.max(v2sum/volumesum - myvwap*myvwap, 0))
</code>```

答:
Your conversion is correct, however, there is one more change you need to know when upgrading from v2. That is, you cannot use any variable in calculations while you are declaring that variable. So, you need to declare it first then give it a new value.</p>
```<code>float vwapsum = 0.0
vwapsum := newSession ? hl2*volume : vwapsum[1]+hl2*volume
</code>```

Body:
I tried to convert pine v2 iff function to v5 but I kept getting this error:

line 32: Undeclared identifier 'vwapsum';
line 33: Undeclared identifier 'volumesum';
line 34: Undeclared identifier 'v2sum'

this one is original v2 script:

newSession = iff(change(start), 1, 0)
vwapsum = iff(newSession, hl2*volume, vwapsum[1]+hl2*volume)
volumesum = iff(newSession, volume, volumesum[1]+volume)
v2sum = iff(newSession, volume*hl2*hl2, v2sum[1]+volume*hl2*hl2)
myvwap = vwapsum/volumesum
dev = sqrt(max(v2sum/volumesum - myvwap*myvwap, 0))

and this is one v5 that I tried to create but give an error

newSession = ta.change(start) ? 1 : 0
vwapsum     = newSession    ?   hl2*volume      : vwapsum[1]+hl2*volume
volumesum   = newSession    ?   volume          : volumesum[1]+volume
v2sum       = newSession    ?   volume*hl2*hl2  : v2sum[1]+volume*hl2*hl2
myvwap      = vwapsum/volumesum
dev         = math.sqrt(math.max(v2sum/volumesum - myvwap*myvwap, 0))

Body:
Your conversion is correct, however, there is one more change you need to know when upgrading from v2. That is, you cannot use any variable in calculations while you are declaring that variable. So, you need to declare it first then give it a new value.

float vwapsum = 0.0
vwapsum := newSession ? hl2*volume : vwapsum[1]+hl2*volume


答:
Please change

```<code>return view('home',compact('Total_users','data'));
</code>```

To

```<code>return view('home', ['data' => $data]);
</code>```

Now you can access $data in blade file.
eg. $data["Risk Name"].
if data is array of object then $data[0]["Risk Name"]

Title: how can i display this data from an api which is in format of json and array

Body:
Please change

return view('home',compact('Total_users','data'));

To

return view('home', ['data' => $data]);

Now you can access $data in blade file.
eg. $data["Risk Name"].
if data is array of object then $data[0]["Risk Name"]


问:
sharing dictionary data between callbacks in plotly-dash
I'd like to share dictionary data between callbacks. so I am using dcc.Store() from below tutorial

https://dash.plotly.com/sharing-data-between-callbacks

However I got an error of AttributeError: 'dict' object has no attribute 'to_json'. so it looks like I cannot use to_json with dictionary data.

```<code>
@app.callback(
    [
    Output("well-table", "data"),
    Output('stored-shared-data-time-dict','data'),
    Output('stored-shared-data-prod-trajectory-dict','data'),
    Output('stored-shared-data-cross-section-list','data'),
    Output('stored-shared-data-conformance-trajectory-dict','data'),
    ],
    [
    Input('load-area-data','n_clicks'),
    ],
    [
     State("select-area-dropdown", "value"),
     State('read-existing-data-radio','value'),
    ],
)

def change_area_data(n_clicks,area,read_existing_radio):

...
    return (datatable_thisarea,
            df_timedata_dict.to_json(date_format='iso', orient='split'),
            df_prod_trajectory_dict.to_json(date_format='iso', orient='split'),
            df_cross_section_dict_list.to_json(date_format='iso', orient='split'),
            df_conformance_trajectory_dict.to_json(date_format='iso', orient='split'),
           )

     52
     53     return (datatable_thisarea,
---> 54             df_timedata_dict.to_json(date_format='iso', orient='split'),
        df_timedata_dict.to_json = undefined
        global date_format = undefined
        global orient = undefined
     55             df_prod_trajectory_dict.to_json(date_format='iso', orient='split'),
     56             df_cross_section_dict_list.to_json(date_format='iso', orient='split'),

AttributeError: 'dict' object has no attribute 'to_json

</code>```

In the above website, it did mention:

Example 1 - Storing Data in the Browser with dcc.Store
To save data in the user's browser's session:

The data has to be converted to a string like JSON or base64 encoded binary data for storage

so I change to_json to use base64 encode, then I got another error of TypeError: a bytes-like object is required, not 'dict'.

```<code>
import base64

def change_area_data(n_clicks,area,read_existing_radio):

...
    return (datatable_thisarea,
            base64.b64encode(df_timedata_dict),
            base64.b64encode(df_prod_trajectory_dict),
            base64.b64encode(df_cross_section_dict_list),
            base64.b64encode(df_conformance_trajectory_dict)
           )

TypeError: a bytes-like object is required, not 'dict'

</code>```

so so how to share the dictionary data between callback?  I have to use dictionary which contains lots of dataframe with keys. Thanks

答:
To convert the python dictionary to json, try using:

import json
json.dumps(name_of_dictionary)
```

Storing data with dcc.Store should then function as intended.

Body:
I'd like to share dictionary data between callbacks. so I am using dcc.Store() from below tutorial

https://dash.plotly.com/sharing-data-between-callbacks

However I got an error of AttributeError: 'dict' object has no attribute 'to_json'. so it looks like I cannot use to_json with dictionary data.

@app.callback(
    [
    Output("well-table", "data"),
    Output('stored-shared-data-time-dict','data'),
    Output('stored-shared-data-prod-trajectory-dict','data'),
    Output('stored-shared-data-cross-section-list','data'),
    Output('stored-shared-data-conformance-trajectory-dict','data'),
    ],
    [
    Input('load-area-data','n_clicks'),
    ],
    [
     State("select-area-dropdown", "value"),
     State('read-existing-data-radio','value'),
    ],
)

def change_area_data(n_clicks,area,read_existing_radio):

...
    return (datatable_thisarea,
            df_timedata_dict.to_json(date_format='iso', orient='split'),
            df_prod_trajectory_dict.to_json(date_format='iso', orient='split'),
            df_cross_section_dict_list.to_json(date_format='iso', orient='split'),
            df_conformance_trajectory_dict.to_json(date_format='iso', orient='split'),
           )

     52
     53     return (datatable_thisarea,
---> 54             df_timedata_dict.to_json(date_format='iso', orient='split'),
        df_timedata_dict.to_json = undefined
        global date_format = undefined
        global orient = undefined
     55             df_prod_trajectory_dict.to_json(date_format='iso', orient='split'),
     56             df_cross_section_dict_list.to_json(date_format='iso', orient='split'),

AttributeError: 'dict' object has no attribute 'to_json

In the above website, it did mention:

Example 1 - Storing Data in the Browser with dcc.Store
To save data in the user's browser's session:

The data has to be converted to a string like JSON or base64 encoded binary data for storage

so I change to_json to use base64 encode, then I got another error of TypeError: a bytes-like object is required, not 'dict'.

import base64

def change_area_data(n_clicks,area,read_existing_radio):

...
    return (datatable_thisarea,
            base64.b64encode(df_timedata_dict),
            base64.b64encode(df_prod_trajectory_dict),
            base64.b64encode(df_cross_section_dict_list),
            base64.b64encode(df_conformance_trajectory_dict)
           )

TypeError: a bytes-like object is required, not 'dict'

so so how to share the dictionary data between callback?  I have to use dictionary which contains lots of dataframe with keys. Thanks

Body:
To convert the python dictionary to json, try using:

import json
json.dumps(name_of_dictionary)

Storing data with dcc.Store should then function as intended.


问:
I didnt get the desired result with wampserver in the <? syntax.Why?
I am using wamp server 2.0 on windows XP with PHP version 5.2.5 when I am using the following code

```<code><?
  echo "hai";
?>
</code>```

I am not getting the output. But when I am using

```<code><?php
  echo "hai";
?>
</code>```

Got the result.If I am using the first one in Linux server I got the output.One of my large project like the first one in all php pages.I want to configure with wamp.SO if first coding needs to work what can I do?

答:
i'm not using wamp now, maybe you can test solution from http://www.wampserver.com/phorum/read.php?2,50473,50474#msg-50474.
Wish this can help you. :)</p>

Body:
I am using wamp server 2.0 on windows XP with PHP version 5.2.5 when I am using the following code

<?
  echo "hai";
?>

I am not getting the output. But when I am using

<?php
  echo "hai";
?>

Got the result.If I am using the first one in Linux server I got the output.One of my large project like the first one in all php pages.I want to configure with wamp.SO if first coding needs to work what can I do?