Tuesday, June 15, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Go: internal package resolution/importation

Posted: 15 Jun 2021 08:14 AM PDT

Context

I am an absolute noob with go and I am trying to write a toy project for learning purpose. I find internal imports quite tricky, feeling that I am missing something important. Say my project is structured this way:

cmd/      consistency/          main.go  pkg/      cli/          cli.go  go.mod    
package cli    import (      "fmt"  )    func welcome() {      fmt.Println("Welcome guys")  }  

And here is go.mod

module github.com/zar3bski/consistency    go 1.16  

Problem

How to properly import pkg/cli in main.go to execute welcome(). It might look dump, but both my IDE (VSCode) and my go compiler are freaking out, no matter what I try

package main    import (      "../../pkg/cli" //does not work  )    func main() {        }  

Based on go.mod, isn't my cli package github.com/zar3bski/consistency/pkg/cli? (which doesn't work either, for that matter: I end up on a web page with a 404). Should I put cli.go in /pkg/consistency/cli for import to automagically occur? Is it a matter of env setup rather than project setup?

syntax error at or near "DECLARE" in PostgreSQL Stored Procedure

Posted: 15 Jun 2021 08:14 AM PDT

I am creating a stored Procedure in PostgreSQL9.6 but I am getting syntax error . I am new to PostgreSQL . is there more syntax error ?

CREATE OR REPLACE FUNCTION DBO.Proc_Activity()    DECLARE  a_sActivityName TYPE  VARCHAR(30);   a_sActivityDescription TYPE  VARCHAR(2000);    a_sUserName TYPE  VARCHAR(30);    a_sErrDesc TYPE  VARCHAR(500);         RETURNS VOID AS $$    BEGIN              insert into Activity_Log (sActivityName,sActivityDescription,sError,dCreatedDate,sCreatedBy)values( a_sActivityName ,a_sActivityDescription, a_sErrDesc ,NOW(),a_sUserName)         END;  $$ LANGUAGE plpgsql;  

and Also how can I call this procedure to test if its working ? Thanks

Tablayout Title donsen't appear

Posted: 15 Jun 2021 08:14 AM PDT

I have a Tablayout to show three fragments via ViewPager and adapter, the problem is that the titles doesn't appear: MainActivity.java:

package com.asd.tab3;    import android.os.Bundle;    import androidx.appcompat.app.AppCompatActivity;  import androidx.viewpager.widget.ViewPager;    import com.google.android.material.tabs.TabLayout;    public class MainActivity extends AppCompatActivity {  TabLayout tb;  ViewPager vp;      @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          tb=findViewById(R.id.tab1);          vp=findViewById(R.id.viwp);          final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(), tb.getTabCount());          vp.setAdapter(adapter);         tb.setupWithViewPager(vp);      }    }  

MyAdapter.java

package com.asd.tab3;  import android.content.Context;    import androidx.fragment.app.Fragment;  import androidx.fragment.app.FragmentManager;  import androidx.fragment.app.FragmentPagerAdapter;    public class MyAdapter extends FragmentPagerAdapter {        private Context myContext;      int totalTabs;        public MyAdapter(Context context, FragmentManager fm, int totalTabs) {          super(fm);          myContext = context;          this.totalTabs = totalTabs;      }        // this is for fragment tabs      @Override      public Fragment getItem(int position) {          switch (position) {              case 0:                  BlankFragment homeFragment = new BlankFragment();                  return homeFragment;              case 1:                  BlankFragment2 sportFragment = new BlankFragment2();                  return sportFragment;              case 2:                  BlankFragment3 movieFragment = new BlankFragment3();                  return movieFragment;              default:                  return null;          }      }      // this counts total number of tabs      @Override      public int getCount() {          return totalTabs;      }  }    

Rem: my problem is different from this post: (Titles in TabLayout donsen't appear)

Write to remote MySQL server

Posted: 15 Jun 2021 08:13 AM PDT

I am trying to learn about how programs and apps communicate with servers. I have Ubuntu server set up with MySQL server. I have adjusted the bind-address and port 3306 with ufw allow. When I run a python program on a different machine to update the MySQL database I get an interface 2003 and 10060 error for no communication response. I am new to this sort of thing I have intermediate experience with programming and I am having trouble finding answers. I am 99% sure I missed something small or just did something stupid or possibly didn't do something. Any ideas?

Calling a class activity implementing asynctask via Intent on mainActivity doesn't work

Posted: 15 Jun 2021 08:13 AM PDT

I'm having trouble calling a browser class implementing asynctask from Main activity using intent in the format below;

MainActivity.java

Intent intent=new Intent(get application context(), Browser.class);  

StartActivity(intent);

And in my browser class I have the following code;

public class Browser extends Activity{  

//* AsyncTask and Java URL class in background *// }

The problem in whole here is, on start of the mainactivity I needed to call another class activity having AsyncTask, like the subclass Http from

  • List item

MainActivity. How do I go about this? Browser activity is also declared in the Android manifest. When I go about in the format above the app crashes on runtime. Your help is highly appreciated.

My program keeps increasing its memory usage and i dont know why

Posted: 15 Jun 2021 08:13 AM PDT

I have a vb.net aplication that connects to several devices via TCP connection. The problem is that i should be able to keep the memory usage under 100 MB but it keeps increasing and increasing non stop. I am using GC and disposing manualy all objects created. The problem happens because i have to keep the aplication running for days and i cant keep increasing the memory usage. Can anyone help pls?

Tinymce upload image with no url

Posted: 15 Jun 2021 08:13 AM PDT

Im wondering if theres a way to upload an image into the tinymce editor without having to use a URL. The issue being with security we dont allow foreign URLS into our servers as it may pose a risk without being verified. I want to be able to allow the user to upload the image directly into the editor from their PC folder.

Pandas - replace NaN with previous row value

Posted: 15 Jun 2021 08:13 AM PDT

Given the following dataframe:

   valid  0  False  1  NaN  2  True  3  Nan  

How do I replace the NaN value with the previous column value, ending up with:

   valid  0  False  1  False  2  True  3  True  

Cython function keeps spawning new processes

Posted: 15 Jun 2021 08:13 AM PDT

I have some C++ code that I wrapped in Cython. It works exactly as expected if I execute it just once. However, I need to call it in a for loop many times with different parameter combinations. And this is where I noticed the additional spawned processes.

In the beginning, there is only one process called "python exec_test.py" which uses 100% of one of my CPU cores and some RAM. Over time, new processes spawn which do not use any CPU capacity but reserve some RAM. Interestingly, it does not spawn a new process on every execution of the Cython function, but there are always four or five additional processes active.

I guess I am asking how multiple function calls to external code are handled by python (or cython?). I looked at the cython documentation, but couldn't find any information about this.

I think, I know that external variables are reused in some way if there are multiple function calls. In the beginning, I had a global variable, like so

# main.cpp    double glob_var = 1.0;    double func_to_be_exposed(double in_var1, double in_var2){       // perform some calculations and change the global variable        glob_var = glob_var * in_var1 + in_var2;      return in_var1 / in_var2;  }  

and on subsequent calls to func_to_be_exposed the global variable glob_var would still have the value of the previous evaluation. This was easily fixed by putting glob_var = 1.0; at the top of the function body.

I would be glad if someone could point me to some documentation or articles about this. Also, are the additional processes expected behavior?

Thanks for the help!

Sequence id is not properly inserted

Posted: 15 Jun 2021 08:13 AM PDT

I have created a sequence but its not inserting ids in sequence order.

For Ex:

-> First I have created one set of record seq number generated as 1 , 2 , 3 , 4

-> Again I have created another set of records seq started from 8 , 9 , 10

-> For 3rd time I have created another set of records seq id got generated as 5 , 6 , 7 (which is not correct, I want the seq id to be continued as 11 , 12 , 13 )

So 5 , 6 , 7 is wrong, I need 11 , 12 , 13 to be generated

What's wrong in my below sequence create query

Kindly assist

Create Query:

CREATE SEQUENCE "LEASE_REPAYMENT_SEQ" MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 146724 CACHE 20 NOORDER NOCYCLE NOKEEP NOSCALE GLOBAL ;  

Spring Data Jpa: union all two unrelated tables

Posted: 15 Jun 2021 08:14 AM PDT

I have two tables which are not related to each but have some common column names.

@Entity  class ABC {      private String abcName;      private String abcCity;      private String abcSomeColumn;  }    @Entity  class XYZ {      private String xyzName;      private String xyzCity;      private String xyzSomeColumn;  }  

I want to pull records from both tables for a city and using union all doing a ntive query

public interface AbcEntityRepository extends PagingAndSortingRepository < ABC, Long > {      @Query(value = "select namedto.* from (select abc_name as name, 'ABC' as fromTable from abc " +          "union all " +          "select xyz_name as name, 'XYZ' as fromTable from xyz) namedto " +          "where (:city is null or namedto.city = city)", nativeQuery = true)      Page < NameDto > findByCity(@Param("city") String city,          Pageable pageable);  }  

Here NameDto is just a model class

class NameDto {      private String name;      private String fromTable;  }  

Getting

org.springframework.core.convert.ConverterNotFoundException:       No converter found capable of converting from type    [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.model.NameDto]  

WARNING: This is a development server. Do not use it in a production deployment [closed]

Posted: 15 Jun 2021 08:13 AM PDT

code is herei m using Jupyter notebook and i m doing project on fake news detection. using flask web framework i want to open index.html page but i get this error:

SystemExit Traceback (most recent call last) in 19 20 if name=='main': ---> 21 app.run(debug=True,host="localhost")

c:\users\admin\appdata\local\programs\python\python39\lib\site-packages\flask\app.py in run(self, host, port, debug, load_dotenv, **options) 920 921 try: --> 922 run_simple(t.cast(str, host), port, self, **options) 923 finally: 924 # reset the first request information if the development server

c:\users\admin\appdata\local\programs\python\python39\lib\site-packages\werkzeug\serving.py in run_simple(hostname, port, application, use_reloader, use_debugger, use_evalex, extra_files, exclude_patterns, reloader_interval, reloader_type, threaded, processes, request_handler, static_files, passthrough_errors, ssl_context) 998 from ._reloader import run_with_reloader as _rwr 999 -> 1000 _rwr( 1001 inner, 1002 extra_files=extra_files,

c:\users\admin\appdata\local\programs\python\python39\lib\site-packages\werkzeug_reloader.py in run_with_reloader(main_func, extra_files, exclude_patterns, interval, reloader_type) 426 reloader.run() 427 else: --> 428 sys.exit(reloader.restart_with_reloader()) 429 except KeyboardInterrupt: 430 pass

SystemExit: 1

understrap child theme - scss changes are not appied/visible

Posted: 15 Jun 2021 08:13 AM PDT

I am having problems with "creating" an Understrap Child theme.

I am using Visual Studio Code and I have a plug in Live Sass Compiler.

The problem I am facing is that when I change/create the variables in _theme.scss and save it, no changes are shown on the website.

My child theme structure:

-understrap-child     *functions.php     *index.php     *style.css     -sass       -theme          *_theme.scss          *_theme_variables.scss  

My understanding is that a scss file with an underline is a partial scss file, and as such is not a stand alone file. If I save a regular scss file, without an underline it creates a regular file.

So my questions comes down to, do I need another .scss / .css file where the values from _theme.scss would be applied?

If I can provide any additional information, please let me know.

How to create an array from three comma separated strings in PHP? [duplicate]

Posted: 15 Jun 2021 08:13 AM PDT

I can do this with one string, but having trouble with combaining 3 different strings into one array. I have three comma separated strings e.g. like:

$ids = "A1,A2,A3";  $names = "apple,banana,mandarine";  $colors = "green,yellow,orange";  

I would need to create an array from these so it would look like this:

[0]=>  {     ["id"] => "A1"     ["name"]=> "apple"     ["color"] => "green"  }  [1]=>  {     ["id"] => "A2"     ["name"]=> "banana"     ["color"] => "yellow"  }  [2]=>  {     ["id"] => "A3"     ["name"]=> "mandarine"     ["color"] => "orange"  }  

How could I achieve that with three separate strings? Thanks in advance!

Sql server 2014 slow remote insert

Posted: 15 Jun 2021 08:13 AM PDT

I have several linked servers and I want insert a value into each of those linked servers. On first try executing, I've waited too long for the INSERT using CURSOR. It's done for about 17 hours. But I'm curious for those INSERT queries, and I checked a single line of my INSERT query using Display Estimation Execution Plan, it took Cost 46% on Remote Insert and Constant Scan for 54%.

Below of my code snippets I worked before

DECLARE @Linked_Servers varchar(100)  DECLARE CSR_STAGGING CURSOR FOR SELECT [Linked_Servers] FROM MyTable_Contain_Lists_of_Linked_Server  OPEN CSR_STAGGING  FETCH NEXT FROM CSR_STAGGING INTO @Linked_Servers  WHILE @@FETCH_STATUS = 0  BEGIN      BEGIN TRY          EXEC('              INSERT INTO ['+@Linked_Servers+'].[DB].[Schema].[Table] VALUES (''bla'',''bla'',''bla'')          ')  END TRY      BEGIN CATCH          DECLARE @ERRORMSG as varchar(8000)          SET @ERRORMSG = ERROR_MESSAGE()      END CATCH      FETCH NEXT FROM CSR_STAGGING INTO @Linked_Servers  END  CLOSE CSR_STAGGING  DEALLOCATE CSR_STAGGING  

Also below, figure of how I check my estimation execution plan of my query

enter image description here

I check only INSERT query, not all queries.

How can I get best practice and best performance using Remote Insert?

Separating whole date and time in VBA

Posted: 15 Jun 2021 08:13 AM PDT

I only can separate date and time to one column.

How can i separate date and time to all columns?

Dim DateTime As Date  DateTime = Range("D2").Value    'get date  Range("E2").Value = Int(DateTime)  Range("E2").NumberFormat = "DD/MM/YYYY"    'get time  Range("F2").Value = DateTime - Int(DateTime)  Range("F2").NumberFormat = "hh:mm"  

[Image of my separate date and time column

How do I deploy a website to Netlify that doesn't use React?

Posted: 15 Jun 2021 08:13 AM PDT

I'm trying to deploy a website to Netlify but the only problem is that it doesn't use React. The website can only be opened on my computer by typing in the folder location in the browser.

How do I deploy such a site to Netlify? I tried looking for answers online but it doesn't give me any.

Edit: I forgot to create a package.json. Apologies

Flask Admin Nested Inline_models

Posted: 15 Jun 2021 08:13 AM PDT

I am looking for the ability to have one inline model contain another inline model. If this behaviour was possible I was assuming this would accomplish that:

inline_models = (      (          SomeModel,          {              'form_columns': ('id', 'another_model_attribute', 'some_attribute'),              'inline_models': (                  (                      AnotherModel,                      {                          'form_columns': ('id', 'some_other_attribute'),                      },                  ),              )          },      ),  )  

Unfortunately this appears to do nothing. Does anyone know if this is possible in flask-admin? Or maybe there is another solution to accomplish this behaviour?

In this github post one user made it seem like it was possible with the screenshots they provided, but no code was ever linked.

How to round a decimal number to whole number in android studio?

Posted: 15 Jun 2021 08:13 AM PDT

Let's say the decimal numbers are 1.12, 8.23, 2.35, 9.44 & 5.14 What I want is I want to round all the numbers whose decimal is less than 0.3 to the lesser whole number and the remaining to the greater whole number.

For example

1.12 would become 1

8.23 would become 8

2.35 would become 3

9.44 would become 10

5.14 would become 5

How do I do that? Please help

How to open an app in splitview content area?

Posted: 15 Jun 2021 08:13 AM PDT

I basially want to open an app within my project directory into the splitview content area. XAML

        <SplitView x:Name="MainPanel" DisplayMode="Inline" IsPaneOpen="True">              <SplitView.Pane>                  <NavigationView x:Name="Navigation" SelectionChanged="Navigation_Navigate">                      <NavigationView.MenuItems>                          <NavigationViewItem x:Name="Home" Icon="Home" Content="Home"/>                          <NavigationViewItem x:Name="Colours" Icon="Edit" Content="Colours"/>                          <NavigationViewItem Icon="Admin" Content="Security"/>                          <NavigationViewItem Icon="World" Content="Translate"/>                      </NavigationView.MenuItems>                  </NavigationView>              </SplitView.Pane>                            <SplitView.Content>                  <Button Background="Green"/>              </SplitView.Content>          </SplitView>  

XAML.CS

private async void NavigateToApp()          {              var NextPage = CoreApplication.CreateNewView();              int NewViewID = 0;                            if (!IsOpen)              {                  await NextPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>                  {                      Frame NewFrame = new Frame();                      NewFrame.Navigate(typeof(Colours), null);                          Window.Current.Content = NewFrame;                                            Window.Current.Activate();                        MainPanel.Content = NewFrame;                        NewViewID = ApplicationView.GetForCurrentView().Id;                  });                                    await ApplicationViewSwitcher.TryShowAsStandaloneAsync(NewViewID, ViewSizePreference.UseMinimum);                    IsOpen = true;              }                                //IsOpen = false;                            //await ApplicationViewSwitcher.TryShowAsViewModeAsync(NewViewID, ApplicationViewMode.CompactOverlay);                        }          #region Test                    private void Navigation_Navigate(NavigationView sender, NavigationViewSelectionChangedEventArgs args)          {                NavigationViewItem item = args.SelectedItem as NavigationViewItem;                if (item != null)              {                  switch (item.Content)                  {                      case "Home":                          Frame.Navigate(typeof(MainPage));                          break;                        case "Colours":                          NavigateToApp();                          break;                        case "Translate":                          Frame.Navigate(typeof(Translate));                          break;                  }              }            }  

This is how i intended for the app to work: -User click button on Navigation menu item(s), e.g. Colours -Then colours page is loaded into a new frame, then new frame into window, then window into splitview.content

CRUD Typescript cancel edit

Posted: 15 Jun 2021 08:14 AM PDT

I have a project in Angular 11 and Spring Boot where I am developing a button editable table. I am missing a function with which I am having problems, cancel the edition, I do not know how to keep the data when pressing the Discard button.

This is my component.ts:

export class ClientsComponent implements OnInit {      @ViewChild(MatTable) table: MatTable<any>;      public formNew: FormGroup;    public formFilt: FormGroup;    public displayedColumns: string[] = ['id', 'name', 'phone', 'act'];    public isNew: boolean;    public clientId: number;    public client: Client;    public clients: Client[];    public editdisabled: boolean;    public editIndex = -1;    public oldValue: any;      constructor(      public fb: FormBuilder,      private clientService: ClientService,      private location: Location,      private route: ActivatedRoute,    ) { }      ngOnInit() {        this.getClients();        this.formNew = this.fb.group({        name: [],        phone: []      });        this.route.params.subscribe(params => {        this.clientId = +params['clientId'];        this.isNew = !this.clientId;        if (!this.isNew) {          this.clientService.get(this.clientId).subscribe(c => {            this.client = c;            this.formNew.patchValue(this.client);          });        }      });      }      edit(i, client: Client) {      this.oldValue = {...client};      this.editIndex = i;    }      saveEdit(client: Client) {      this.editIndex = -1;      this.clientService.edit(client).subscribe();    }      cancel(){      this.editIndex = -1;    }  }  

This is my component.html:

<ng-container matColumnDef="act">          <mat-header-cell *matHeaderCellDef> Actions </mat-header-cell>          <mat-cell *matCellDef="let element;let i = index">            <button *ngIf="editIndex != i" mat-icon-button matTooltip="Edit" (click)="edit(i, element)">              <mat-icon class="icon_edit_button">edit</mat-icon>            </button>            <button *ngIf="editIndex == i" mat-icon-button matTooltip="Update" (click)="saveEdit(element)">              <mat-icon class="icon_update_button">save</mat-icon>            </button>            <button *ngIf="editIndex == i" mat-icon-button matTooltip="Discard" (click)="cancel()">              <mat-icon class="icon_discard_button">undo</mat-icon>            </button>          </mat-cell>        </ng-container>  

How to make a part of ListHeaderComponent sticky on React Native FlatList

Posted: 15 Jun 2021 08:13 AM PDT

I have a React Native FlatList with a ListHeaderComponent with 2 internal Text. The structure is:

  • header
    • section 1 - non sticky
    • section 2 - sticky
  • list items

This means that as the list scrolls up, Section 1 should disappear (non-sticky) whereas section 2 should stay at the top of the list (sticky).

This is the code:

<FlatList    data={ items }    renderItem={ renderItem }    ListHeaderComponent={       <View>           <Text>Section 1</Text>           <Text>Section 2</Text>       </View>    }    stickyHeaderIndices={[0]}  />  

I have to set the indices to [0] so it picks the header but there is no way to select the second within the header. Any ideas?

BTW - I thought of capturing the vertical offset as the list scrolls and then put on the HeaderComponent main <View style={{marginTop: -offset }}> so it simulates a scroll. But my understanding is that Android does not support negative margins.

BTW-2 - I am using react-native-draggable-flatlist so I wouldn't like to put the Text in the list itself as it would complicated the logic of the list items. Thanks!

Bootstrap 4 modal cancel

Posted: 15 Jun 2021 08:13 AM PDT

In pure jQuery I can do this:

$(".confirmClick").click(function() {    if (!confirm("Are you sure?")) {      return false;    }  });    

...so by just adding a class "confirmClick" to a link, clicking the link now requires the user to confirm the action before carrying it out.

I would like to do the same with a bootstrap 4 modal, because it just looks better.

I am perfectly happy to add two attributes to a link, like:

data-toggle="modal" data-target="#confirmClickModal"  

...in which case I would make sure ot have a modal with id confirmClickModal always available.

The problems in cancelling/proceeding with the click depending on the user action.

Thanks in advance.

Having to destinations to select for state design pattern

Posted: 15 Jun 2021 08:13 AM PDT

I am implementing a state pattern, my cause when the pause state is reached, I have two states that the user can back tow, that depends on the button the user click.

  • if the user clicks on the Play button (start to selected)

  • if the user clicks on the back button (died start selected)

Currently, the code

class PauseState : State {        override fun handleClick(locationUIController: LocationUIController,             deliveryType: DeliveryType){                     if(deliveryType == DeliveryType.PlayButton ){                         }              if(deliveryType == DeliveryType.backButton ){                           }       }  }  

but I know there is something wrong because switch statement breaks the benefits of state pattern that encapsulate behaviours , the code above shows ugly of switch statement

states graph

Why comparing a small floating-point number with zero yields random result?

Posted: 15 Jun 2021 08:13 AM PDT

I am aware that floating-point numbers are tricky. But today I encountered a case that I cannot explain (and cannot reproduce using a standalone C++ code).

The code within a large project looks like this:

int i = 12;    // here goes several function calls passing the value i around,   // but using different types (due to unfortunate legacy code)  ...     float f = *((float*)(&i)); // f=1.681558e-44    if (f == 0) {      do something;  } else {      do something else;  }  

This piece of code causes a random behavior. Using gdb, it's identified that the random behavior is due to the comparison f == 0 which gives random results, i.e., sometimes true, sometimes false. The bug in the code was that, before using f, it should check whether or not the 4-bytes should be interpreted as integer (using other aux information). The fix is to first cast it back to integer, and then compare the integer with 0. Then problem solved.

Also in case a floating number comparison is needed (in such case, the floating number is not casted from integer as shown above), I also changed the comparison to abs(f) < std::numeric_limits<float>::epsilon(), to be on the safer side.

After that, I also wanted to reproduce it using a simple test program, but it seems I cannot reproduce it. (The compiler used for the project is different from what I am using for compiling the test program though). The following is the test program:

#include <stdio.h>    int main(void){      int i = 12;      float f = *(float*)(&i);        for (int i = 0; i < 5; ++i) {          printf("f=%e %s\n", f, (f == 0)? "=0": "!=0");      }      return 0;  }  

I am wondering, what could be the reason for the random behavior of the comparison with zero?

transaction underpriced in BEP-20 Token transaction

Posted: 15 Jun 2021 08:14 AM PDT

I had do some transaction in Binance Smart Chain in Binance-Peg BUSD-T and it worked successfully. But after 5 transactions. I face to a problem that said Returned error: transaction underpriced ! This is my code:

const web3 = new Web3('https://bsc-dataseed1.binance.org:443');    const contract = new web3.eth.Contract(abi, usdtContractAddr, {    from: 'SENDER_ADDRESS', // default from address    gasPrice: '200000000' // default gas price in wei, 20 gwei in this case  });    web3.eth.accounts.wallet.add('SENDER_PRIVATE_KEY');  const receipt = await contract.methods.transfer('TO_ADDRESS', '1000000000000000000').send({      from: 'SENDER_ADDRESS',      gas: 100000  });  

I have increased my gas 10% and add a nonce more than the value which was given to me by calling web3.eth.getTransactionCount('ADDRESS'). But non of them works. I used to do a lot of transactions in Binance-Peg BUSD-T and so it is a big problem for me. Is there a way to solve this problem ???

Import tasks or playbooks with a boolean condition in Ansible

Posted: 15 Jun 2021 08:14 AM PDT

Effectively I need something like this:

- hosts: localhost          tasks:      - name: Perforce template        import_tasks: ./../vsphere-client/perforce/template_to_vm.yml        when: new_server_type == "perforce"            - name: Gitlab Pgbouncer template        import_tasks: ./../vsphere-client/gitlab-pgbouncer/template_to_vm.yml        when: new_server_type == "gitlab-pgbouncer"            - name: Gitlab Postgres template        import_tasks: ./../vsphere-client/gitlab-postgres/template_to_vm.yml        when: new_server_type == "gitlab-postgres"            - name: Build API template        import_tasks: ./../vsphere-client/build-api/template_to_vm.yml        when: new_server_type == "build-api"  

But it gives an error like:

ERROR! unexpected parameter type in action: <type 'bool'>  

I understand this is not supported but is there any way to do this?

Create a presigned S3 URL for get_object with custom logging information using Boto3?

Posted: 15 Jun 2021 08:13 AM PDT

I am using Boto3 and s3_client.generate_presigned_url to create a presigned get_object url, i.e.

response = s3_client.generate_presigned_url('get_object',                                              Params={'Bucket': bucket_name,                                                      'Key': object_name},                                              ExpiresIn=expiration)  

in accordance with the Boto 3 documentation.

I need to add the identity of the user requesting the URL into the presigned URL itself, so that it will be immediately apparent whose credentials had been used to generate it! Now the AWS Documentation says that it is possible to include custom query string parameters in the URL:

You can include custom information to be stored in the access log record for a request by adding a custom query-string parameter to the URL for the request. Amazon S3 ignores query-string parameters that begin with "x-", but includes those parameters in the access log record for the request, as part of the Request-URI field of the log record. For example, a GET request for s3.amazonaws.com/awsexamplebucket/photos/2019/08/puppy.jpg?x-user=johndoe works the same as the same request for s3.amazonaws.com/awsexamplebucket/photos/2019/08/puppy.jpg, except that the x-user=johndoe string is included in the Request-URI field for the associated log record. This functionality is available in the REST interface only.

The Javascript SDK library has the following recipe in Github issues:

var req = s3.getObject({Bucket: 'mybucket', Key: 'mykey'});  req.on('build', function() { req.httpRequest.path += '?x-foo=value'; });  console.log(req.presign());  

for creating a presigned url with ?x-foo=value embedded into the URL. Judging from the comments it seems to work too!

How do I achieve the same in Python (3), preferably (but not necessarily) using Boto 3?

P.S. please do note that I am not asking how to force the client to pass a header or anything such - in fact I cannot control the client, I just give the URL to it.

How to use settimeout with vue.js watchers?

Posted: 15 Jun 2021 08:13 AM PDT

I have custom watcher for search field in my application:

watch: {    search (query) {      if(query.length > 2) {        axios.post(url, query)          .then(res => {            console.log(res)          })          .catch(error => {            console.log(error)          })      }    }  }  

Here as you see I've send request to server on everey change value of search var in my case. I tired paste my code inside setTimeout but when user typing 3 time then requests too sent 3 times instead of one time. I need to wait when user is typing and after stop typing send one request to server.

setTimeout(function () {       // request code here  }, 3000);  

How I can do it correctly inside vue.js watchers?

How to fix Error: laravel.log could not be opened?

Posted: 15 Jun 2021 08:13 AM PDT

I'm pretty new at laravel, in fact and I'm trying to create my very first project. for some reason I keep getting this error (I haven't even started coding yet)

Error in exception handler: The stream or file "/var/www/laravel/app/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied in /var/www/laravel/bootstrap/compiled.php:8423  

I've read this has something to do with permissions but chmod -R 775 storage didn't help at all.

Permissions

No comments:

Post a Comment