问:
How to fix a python "pyverbs" application with RDMA write getting a not acknowledge (NACK)
Im currently working on a RoCE (RDMA over Converged Ethernet) python application with the library pyverbs. First, i want to do a simple loopback test with an RDMA Write. I tested the setup with ib_write_bw from perftest, which worked like a charm.

This is my setup:

OS: Ubuntu 20.04.05 LTS

Kernel: 5.15.0-56-generic

NIC: Mellanox ConnectX-5 MC516A-GCA_Ax 50Gbe dual-port QSFP28

I'm developing the application with a jupyter notebook. The ports are connected together with a QSFP28 cable. I set up a "client" and "server" on the same system. Both use one port of the NIC. The client performs the "RDMA Write" action. In the future, metadata will be exchanged over tcp, but for ease of debugging i exchange metadata locally in the same notebook.

Now i was able to perform an "RDMA Write" action and capture the packets.
Captured RDMA packets

I keep getting not acknowledeges (NACK) from the "server". The RDMA Write packet look correct to me. It got the right payload and the headers are the same as i configured (i can post it if it would help).

I got three ideas in my head, why it would work.

wrong server memory adress/rkey used for rdma write

missing flags at server memory allocation

missing/wrong flags at server queue pair modification

I tried all different combinations of flags and values at the queue pair modification and memory allocation.

I start the NIC in the shi
ell with

sudo mst start
```
<p>Then i run my python application. I posted some codesnipped below, which i am not sure i implemented those right.</p>
<h2>Server and client qp modification init to RTR</h2>
<pre class="lang-py prettyprint-override"><code>gid_index = 0
port_num = 1

server_attr.qp_state = e.IBV_QPS_RTR
server_attr.path_mtu = e.IBV_MTU_4096
server_attr.rq_psn = 0
server_attr.min_rnr_timer = 12
server_attr.max_dest_rd_atomic = 10
server_attr.dest_qp_num = client_qp.qp_num
server_attr.qp_access_flags = e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_REMOTE_READ | e.IBV_ACCESS_REMOTE_WRITE
server_gr = GlobalRoute(dgid=client_ctx.query_gid(port_num=port_num,index=gid_index), sgid_index=gid_index)
server_ah_attr = AHAttr(gr=server_gr, is_global=1, port_num=1)
server_attr.ah_attr = server_ah_attr

server_qp.to_rtr(server_attr)

client_attr.qp_state = e.IBV_QPS_RTR
client_attr.path_mtu = e.IBV_MTU_4096
client_attr.rq_psn = 0
client_attr.min_rnr_timer = 12
client_attr.max_dest_rd_atomic = 10
client_attr.dest_qp_num = server_qp.qp_num
client_attr.qp_access_flags = e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_REMOTE_READ | e.IBV_ACCESS_REMOTE_WRITE
client_gr = GlobalRoute(dgid=server_ctx.query_gid(port_num=port_num,index=gid_index), sgid_index=gid_index)
client_ah_attr = AHAttr(gr=client_gr, is_global=1, port_num=port_num)
client_attr.ah_attr = client_ah_attr

client_qp.to_rtr(client_attr)

</code>```

Client qp modification RTR to RTS

client_attr.qp_state = e.IBV_QPS_RTS
client_attr.timeout = 14
client_attr.retry_cnt = 7
client_attr.rnr_retry = 7
client_attr.sq_psn = 0
client_attr.max_rd_atomic = 10

```
<h2>RDMA Write instruction to client</h2>
<pre class="lang-py prettyprint-override"><code>client_sge = SGE(client_mr.buf,len(SEND_STRING),client_mr.lkey)
send_wr = pwr.SendWR(num_sge = 1, sg = [client_sge],opcode=e.IBV_WR_RDMA_WRITE)
send_wr.set_wr_rdma(rkey = server_mr.rkey, addr = server_mr.buf)
client_qp.post_send(send_wr)

sleep(1)
print(server_mr.read(len(SEND_STRING),0))
</code>```

If there is someone with knowledge in RMDA/RoCE/Pyverbs, i would be glad for some help. I don't have any prior knowledge in those topics. This is why i have choosen to write an application in python. I have knowledge in C, but python is for me much more convient for prototyping :)

Thank for your help!

Body:
Im currently working on a RoCE (RDMA over Converged Ethernet) python application with the library pyverbs. First, i want to do a simple loopback test with an RDMA Write. I tested the setup with ib_write_bw from perftest, which worked like a charm.

This is my setup:

OS: Ubuntu 20.04.05 LTS

Kernel: 5.15.0-56-generic

NIC: Mellanox ConnectX-5 MC516A-GCA_Ax 50Gbe dual-port QSFP28

I'm developing the application with a jupyter notebook. The ports are connected together with a QSFP28 cable. I set up a "client" and "server" on the same system. Both use one port of the NIC. The client performs the "RDMA Write" action. In the future, metadata will be exchanged over tcp, but for ease of debugging i exchange metadata locally in the same notebook.

Now i was able to perform an "RDMA Write" action and capture the packets.
Captured RDMA packets

I keep getting not acknowledeges (NACK) from the "server". The RDMA Write packet look correct to me. It got the right payload and the headers are the same as i configured (i can post it if it would help).

I got three ideas in my head, why it would work.

wrong server memory adress/rkey used for rdma write

missing flags at server memory allocation

missing/wrong flags at server queue pair modification

I tried all different combinations of flags and values at the queue pair modification and memory allocation.

I start the NIC in the shi
ell with

sudo mst start

Then i run my python application. I posted some codesnipped below, which i am not sure i implemented those right.

Server and client qp modification init to RTR

gid_index = 0
port_num = 1

server_attr.qp_state = e.IBV_QPS_RTR
server_attr.path_mtu = e.IBV_MTU_4096
server_attr.rq_psn = 0
server_attr.min_rnr_timer = 12
server_attr.max_dest_rd_atomic = 10
server_attr.dest_qp_num = client_qp.qp_num
server_attr.qp_access_flags = e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_REMOTE_READ | e.IBV_ACCESS_REMOTE_WRITE
server_gr = GlobalRoute(dgid=client_ctx.query_gid(port_num=port_num,index=gid_index), sgid_index=gid_index)
server_ah_attr = AHAttr(gr=server_gr, is_global=1, port_num=1)
server_attr.ah_attr = server_ah_attr

server_qp.to_rtr(server_attr)

client_attr.qp_state = e.IBV_QPS_RTR
client_attr.path_mtu = e.IBV_MTU_4096
client_attr.rq_psn = 0
client_attr.min_rnr_timer = 12
client_attr.max_dest_rd_atomic = 10
client_attr.dest_qp_num = server_qp.qp_num
client_attr.qp_access_flags = e.IBV_ACCESS_LOCAL_WRITE | e.IBV_ACCESS_REMOTE_READ | e.IBV_ACCESS_REMOTE_WRITE
client_gr = GlobalRoute(dgid=server_ctx.query_gid(port_num=port_num,index=gid_index), sgid_index=gid_index)
client_ah_attr = AHAttr(gr=client_gr, is_global=1, port_num=port_num)
client_attr.ah_attr = client_ah_attr

client_qp.to_rtr(client_attr)

Client qp modification RTR to RTS

client_attr.qp_state = e.IBV_QPS_RTS
client_attr.timeout = 14
client_attr.retry_cnt = 7
client_attr.rnr_retry = 7
client_attr.sq_psn = 0
client_attr.max_rd_atomic = 10

RDMA Write instruction to client

client_sge = SGE(client_mr.buf,len(SEND_STRING),client_mr.lkey)
send_wr = pwr.SendWR(num_sge = 1, sg = [client_sge],opcode=e.IBV_WR_RDMA_WRITE)
send_wr.set_wr_rdma(rkey = server_mr.rkey, addr = server_mr.buf)
client_qp.post_send(send_wr)

sleep(1)
print(server_mr.read(len(SEND_STRING),0))

If there is someone with knowledge in RMDA/RoCE/Pyverbs, i would be glad for some help. I don't have any prior knowledge in those topics. This is why i have choosen to write an application in python. I have knowledge in C, but python is for me much more convient for prototyping :)

Thank for your help!


来源: stackexchange

问:
Is anyone familiar with wa_automate_client python package?
I would like to automate Whatsapp messages with the package and I haven't quite figured out how to link my input with the reply

I have tried using mongo db database to store the messages to no avail
I am trying to get different replies for each input

ContentLicense: CC BY-SA 4.0


问:
Keep indentation for array value in parsed YAML frontmatter
I am using https://github.com/waiting-for-dev/front_matter_parser to parse and update values in the frontmatter of my markdown files.

The following code removes the original indentation of two spaces for array values:

```<code>require 'front_matter_parser'

class FrontMatterUpdater
  def self.run(path)
    parsed = FrontMatterParser::Parser.parse_file(path)
    front_matter = parsed.front_matter

    front_matter['redirect_from'] = Array(front_matter['redirect_from'])
    front_matter['redirect_from'] << 'new_entry2'
    front_matter['redirect_from'].uniq!

    new_content = [YAML.dump(front_matter), '---', "\n\n", parsed.content].join

    File.write(path, new_content)
  end
end

FrontMatterUpdater.run('test.md')
</code>```

Content of my test.md file (same path):.

```<code>---
redirect_from:
  - new_entry0
  - new_entry1
---
</code>```

Script result (indentation has been removed by the parser):

```<code>---
redirect_from:
- new_entry0
- new_entry1
- new_entry2
---
</code>```

YAML indentation for array in hash confirms that both versions (indented and not) is valid YAML syntax.

But I'd love to keep the indentation for readability.

Do you see any option to keep the indentation of 2 spaces for the array values?

Body:
I am using https://github.com/waiting-for-dev/front_matter_parser to parse and update values in the frontmatter of my markdown files.

The following code removes the original indentation of two spaces for array values:

require 'front_matter_parser'

class FrontMatterUpdater
  def self.run(path)
    parsed = FrontMatterParser::Parser.parse_file(path)
    front_matter = parsed.front_matter

    front_matter['redirect_from'] = Array(front_matter['redirect_from'])
    front_matter['redirect_from'] << 'new_entry2'
    front_matter['redirect_from'].uniq!

    new_content = [YAML.dump(front_matter), '---', "\n\n", parsed.content].join

    File.write(path, new_content)
  end
end

FrontMatterUpdater.run('test.md')

Content of my test.md file (same path):.

---
redirect_from:
  - new_entry0
  - new_entry1
---

Script result (indentation has been removed by the parser):

---
redirect_from:
- new_entry0
- new_entry1
- new_entry2
---

YAML indentation for array in hash confirms that both versions (indented and not) is valid YAML syntax.

But I'd love to keep the indentation for readability.

Do you see any option to keep the indentation of 2 spaces for the array values?


问:
How to access feature attributes in feature set Arcade AGOL
i have did the same idea as this code and i have created feature set .
but i would like to get feature attributes from feature set that created at the end of code .

as example here ,i would like to show only specific column AddressCount

How could i achieve it ?

i need to continue this code to add in Arcade expression Arcgis online .

`

```<code>var portal = Portal("https://www.arcgis.com/");
var polyfs = FeatureSetByPortalItem(
    portal,
    "4dbbad3d6f694e0ebc7c3b4132ea34df",
    0,
    ["*"],
    false
);

var tablefs = FeatureSetByPortalItem(
    portal,
    "4dbbad3d6f694e0ebc7c3b4132ea34df",
    6,
    ["*"],
    false
);

// Create empty features array and feat object
var features = [];
var feat;

// Populate Feature Array
for (var t in tablefs) {
    var tableID = t["FeatureID"]
    for (var p in Filter(polyfs, "HydroID = "+tableID)){
        feat = {
            attributes: {
                FeatureID: tableID,
                Name: p["DPS_Region"],
                ModelID: t["ModelID"],                AddressCount: t["AddressCount"],
                MAX_TSTime: t["MAX_TSTime"],
            }
        }

    Push(features, feat)
    }
}

var joinedDict = {
    fields: [
        { name: "FeatureID", type: "esriFieldTypeString" },
        { name: "Name", type: "esriFieldTypeString" },
        { name: "ModelID", type: "esriFieldTypeInteger" },
        { name: "AddressCount", type: "esriFieldTypeInteger" },
        { name: "MAX_TSTime", type: "esriFieldTypeString" },
    ],
    'geometryType': '',
    'features':features
};

// Return dictionary cast as a feature set
return FeatureSet(Text(joinedDict));

`

Thanks in advance

i have converted the dictionary to feature set .
and i did

     var   item_name = joinedDict.fields[3].name;
      return item_name

but the output of this code show me only  the name of field  but i would like to get the value of contain of attributes for this field

how to access in feature attributes of nested array dictionary  to obtain values of specific column .

</code>```

Body:
i have did the same idea as this code and i have created feature set .
but i would like to get feature attributes from feature set that created at the end of code .

as example here ,i would like to show only specific column AddressCount

How could i achieve it ?

i need to continue this code to add in Arcade expression Arcgis online .

`

var portal = Portal("https://www.arcgis.com/");
var polyfs = FeatureSetByPortalItem(
    portal,
    "4dbbad3d6f694e0ebc7c3b4132ea34df",
    0,
    ["*"],
    false
);

var tablefs = FeatureSetByPortalItem(
    portal,
    "4dbbad3d6f694e0ebc7c3b4132ea34df",
    6,
    ["*"],
    false
);

// Create empty features array and feat object
var features = [];
var feat;

// Populate Feature Array
for (var t in tablefs) {
    var tableID = t["FeatureID"]
    for (var p in Filter(polyfs, "HydroID = "+tableID)){
        feat = {
            attributes: {
                FeatureID: tableID,
                Name: p["DPS_Region"],
                ModelID: t["ModelID"],                AddressCount: t["AddressCount"],
                MAX_TSTime: t["MAX_TSTime"],
            }
        }

    Push(features, feat)
    }
}

var joinedDict = {
    fields: [
        { name: "FeatureID", type: "esriFieldTypeString" },
        { name: "Name", type: "esriFieldTypeString" },
        { name: "ModelID", type: "esriFieldTypeInteger" },
        { name: "AddressCount", type: "esriFieldTypeInteger" },
        { name: "MAX_TSTime", type: "esriFieldTypeString" },
    ],
    'geometryType': '',
    'features':features
};

// Return dictionary cast as a feature set
return FeatureSet(Text(joinedDict));

`

Thanks in advance

i have converted the dictionary to feature set .
and i did

     var   item_name = joinedDict.fields[3].name;
      return item_name

but the output of this code show me only  the name of field  but i would like to get the value of contain of attributes for this field

how to access in feature attributes of nested array dictionary  to obtain values of specific column .


问:
data-dropdown-toggle does not open user-dropdown using Tailwind CSS
I have a Next.JS project and would like to create a navigation bar similar to the one on Flowbite

```<code>const NavBar = () => {
  return (

    <nav className="bg-white border-gray-200 px-2 sm:px-4 py-2.5 rounded dark:bg-gray-900">
      <div className="container flex flex-wrap items-center justify-between mx-auto">
      <a href="https://flowbite.com/" className="flex items-center">
          <img src="https://flowbite.com/docs/images/logo.svg" className="h-6 mr-3 sm:h-9" alt="Flowbite Logo" />
          <span className="self-center text-xl font-semibold whitespace-nowrap dark:text-white">Flowbite</span>
      </a>
      <div className="flex items-center md:order-2">
          <button type="button" className="flex mr-3 text-sm bg-gray-800 rounded-full md:mr-0 focus:ring-4 focus:ring-gray-300 dark:focus:ring-gray-600" id="user-menu-button" aria-expanded="false" data-dropdown-toggle="user-dropdown" data-dropdown-placement="bottom">
            <span className="sr-only">Open user menu</span>
            <img className="w-8 h-8 rounded-full" src="https://www.gravatar.com/avatar/357aeb5f4812fb9f69b0e21766c3b31b?s=48&d=identicon&r=PG&f=1" alt="user photo" />
          </button>

          <div className="z-50 hidden my-4 text-base list-none bg-white divide-y divide-gray-100 rounded shadow dark:bg-gray-700 dark:divide-gray-600" id="user-dropdown">
            <div className="px-4 py-3">
              <span className="block text-sm text-gray-900 dark:text-white">Bonnie Green</span>
              <span className="block text-sm font-medium text-gray-500 truncate dark:text-gray-400">name@flowbite.com</span>
            </div>
            <ul className="py-1" aria-labelledby="user-menu-button">
              <li>
                <a href="#" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-200 dark:hover:text-white">Dashboard</a>
              </li>
              <li>
                <a href="#" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-200 dark:hover:text-white">Settings</a>
              </li>
              <li>
                <a href="#" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-200 dark:hover:text-white">Earnings</a>
              </li>
              <li>
                <a href="#" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-200 dark:hover:text-white">Sign out</a>
              </li>
            </ul>
          </div>
          <button data-collapse-toggle="mobile-menu-2" type="button" className="inline-flex items-center p-2 ml-1 text-sm text-gray-500 rounded-lg md:hidden hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200 dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:ring-gray-600" aria-controls="mobile-menu-2" aria-expanded="false">
            <span className="sr-only">Open main menu</span>
            <svg className="w-6 h-6" aria-hidden="true" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fillRule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clipRule="evenodd"></path></svg>
        </button>
      </div>
      </div>
    </nav>

  )
}

export default NavBar
</code>```

However, clicking on user's Gravatar does not reveal the drop-down menu/list.

Body:
I have a Next.JS project and would like to create a navigation bar similar to the one on Flowbite

const NavBar = () => {
  return (

          Flowbite

          <button type="button" className="flex mr-3 text-sm bg-gray-800 rounded-full md:mr-0 focus:ring-4 focus:ring-gray-300 dark:focus:ring-gray-600" id="user-menu-button" aria-expanded="false" data-dropdown-toggle="user-dropdown" data-dropdown-placement="bottom">
            Open user menu

          </button>

              Bonnie Green
              name@flowbite.com

                Dashboard

                Settings

                Earnings

                Sign out

          <button data-collapse-toggle="mobile-menu-2" type="button" className="inline-flex items-center p-2 ml-1 text-sm text-gray-500 rounded-lg md:hidden hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200 dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:ring-gray-600" aria-controls="mobile-menu-2" aria-expanded="false">
            Open main menu
            <svg className="w-6 h-6" aria-hidden="true" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fillRule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clipRule="evenodd"></path></svg>
        </button>

  )
}

export default NavBar

However, clicking on user's Gravatar does not reveal the drop-down menu/list.


问:
Gobal Pay HPP with AVS unable to test in Sandbox? Why?
I have implemented Global Pay HPP and it's working fine with normal transactions in sandbox. Now I want to enforce the security for billing address verification and I have updated the my HPP with below line

`

```<code><!-- Begin AVS Field -->
   <input type="hidden" name="BILLING_CODE" value="46205|Test">
<!-- End AVS Feild -->
</code>```

`

As per Testing document here https://developer.authorize.net/hello_world/testing_guide.html
It should fail with ZIP Code: No Match But I am getting the Response as Matched.

Any idea what I am missing?

Body:
I have implemented Global Pay HPP and it's working fine with normal transactions in sandbox. Now I want to enforce the security for billing address verification and I have updated the my HPP with below line

`

   <input type="hidden" name="BILLING_CODE" value="46205|Test">

`

As per Testing document here https://developer.authorize.net/hello_world/testing_guide.html
It should fail with ZIP Code: No Match But I am getting the Response as Matched.

Any idea what I am missing?


问:
How do I get checkbox value in email after submit from https://formsubmit.co?
Hi I use https://formsubmit.co as form submit.
Formsubmit only returns one checkbox even if two or more checkboxes is checked.

```<code><form action="https://formsubmit.co/info@enchuga.com" method="POST">
   <input type="hidden" name="_subject" value="Snyggt!! Ny beställning av algos">
   <input type="hidden" name="_next" value="https://enchuga.com/enchugacap/thanks.html">
   Name:  <br>
   <input class="contactForm" type="text" name="Name" placeholder="Your name" required> <br>
   <br>
   Mail: <br>
   <input class="contactForm" type="email" name="Email" placeholder="Email Address" required> <br>
   <br>
   Which trading algorithms do you want to order?  <br>
   <input type="checkbox" id="LosAngeles" name="Algo" value="LosAngeles">
   <label for="LosAngeles" class="orderText"> Los Angeles 69€/year (699 SEK)</label><br>
   <input type="checkbox" id="London" name="Algo" value="London">
   <label for="London" class="orderText"> London 69€/year (699 SEK)</label><br>
   <input type="checkbox" id="Paris" name="Algo" value="Paris">
   <label for="Paris" class="orderText"> Paris 69€/year (699 SEK)</label><br>
   <input type="checkbox" id="Berlin" name="Algo" value="Berlin">
   <label for="Berlin" class="orderText"> Berlin 69€/year (699 SEK)</label><br>
   <input type="checkbox" id="NewYork" name="Algo" value="NewYork">
   <label for="NewYork" class="orderText"> New York 69€/year (699 SEK)</label><br>
   <input type="checkbox" id="allAlgos" name="Algo" value="allAlgos">
   <label for="allAlgos" class="orderText"> All five algos 260€/year (2600 SEK, 25% discount)</label><br>
   <br>
   Send a message to enchuga CAPITAL if you wondering about anything or want to ask a question: <br>
   <input class="contactForm2" type="text" name="Message"> <br>
   <br>
   <button type="submit">Send</button>
</form>
</code>```

How do I get it to return every checkbox checked?

I have tried to create checkboxes that returns the item they checked but I don't get it to work.

Body:
Hi I use https://formsubmit.co as form submit.
Formsubmit only returns one checkbox even if two or more checkboxes is checked.

<form action="https://formsubmit.co/info@enchuga.com" method="POST">
   <input type="hidden" name="_subject" value="Snyggt!! Ny beställning av algos">
   <input type="hidden" name="_next" value="https://enchuga.com/enchugacap/thanks.html">
   Name:

   <input class="contactForm" type="text" name="Name" placeholder="Your name" required>

   Mail:

   <input class="contactForm" type="email" name="Email" placeholder="Email Address" required>

   Which trading algorithms do you want to order?

   <input type="checkbox" id="LosAngeles" name="Algo" value="LosAngeles">
    Los Angeles 69€/year (699 SEK)

   <input type="checkbox" id="London" name="Algo" value="London">
    London 69€/year (699 SEK)

   <input type="checkbox" id="Paris" name="Algo" value="Paris">
    Paris 69€/year (699 SEK)

   <input type="checkbox" id="Berlin" name="Algo" value="Berlin">
    Berlin 69€/year (699 SEK)

   <input type="checkbox" id="NewYork" name="Algo" value="NewYork">
    New York 69€/year (699 SEK)

   <input type="checkbox" id="allAlgos" name="Algo" value="allAlgos">
    All five algos 260€/year (2600 SEK, 25% discount)

   Send a message to enchuga CAPITAL if you wondering about anything or want to ask a question:

   <input class="contactForm2" type="text" name="Message">

   <button type="submit">Send</button>
</form>

How do I get it to return every checkbox checked?

I have tried to create checkboxes that returns the item they checked but I don't get it to work.


问:
Java Upload file Rest Template
I need to upload a file through the spring MVC rest template for the below params shown in the image.

I have tried different approaches but it's not working giving exception 401 Unauthorized.
I need code that uploads files through spring MVC RestTemplate.
I have shared my code below which is not working.I have tried different ways to attach file but they are not working please check my code.

My Code Sample:

    @RequestMapping(value = "/uploadPEFile", method = { RequestMethod.POST},
                produces = "application/json")
        @ResponseBody
        public String uploadPEFile(@RequestParam(value = "file", required = false) MultipartFile file,
                HttpServletRequest request, HttpServletResponse httpResponse) {
            JsonResponse objResponse = null;
            String enterpriseId = "";
            String enterpriseName = "";
            String type = "";
            String productId = "";
            String userIds = "";
            String title = "";
            String description = "";
            String date = "";
            String externalUrl = "";
            String presenterName = "";
            try {

                enterpriseId = request.getParameter("enterpriseId");
                enterpriseName = request.getParameter("enterpriseName");
                type = request.getParameter("type");
                productId = request.getParameter("productId");
                userIds = request.getParameter("userIds");
                title = request.getParameter("title");
                description = request.getParameter("description");
                date = request.getParameter("date");
                if(date != null && !date.isEmpty())
                {
                    String [] dateArray = date.split(" ");
                    date = dateArray[2]+" "+getMonth(dateArray[1])+", "+dateArray[3];
                }
                externalUrl = request.getParameter("externalURL");
                presenterName = request.getParameter("presenterName");
                JsonObject jsonBody = new JsonObject();
                jsonBody.addProperty("title", title);
                jsonBody.addProperty("description", description);
                jsonBody.addProperty("date", date);
                jsonBody.addProperty("external_url", externalUrl);
                jsonBody.addProperty("presenter_name", presenterName);
                String cmsDeviceId = PortalUtil.getPropertyValue("cms.device.id");

                        if (file != null) {
                    final String filename = file.getOriginalFilename();

                    ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
                        @Override
                        public String getFilename() {
                            return filename;
                        }
                    };
                    String filePath = "/persivia edge/"+type+"/"+filename;
                    File userFile = new File(System.getProperty(PortalConstants.cdnPath) + filePath);
                    if(!userFile.exists()) {
                        userFile.mkdirs();
                    }
                    file.transferTo(userFile);
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
                    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
                    body.add("device_id",cmsDeviceId);
//                  body.add("attachment",fileAsResource);
//                  body.add("attachment",new MultipartInputStreamFileResource(file.getInputStream(), file.getOriginalFilename()));
                    body.add("attachment",new FileSystemResource(filePath));

                    body.add("source", "web");
                    body.add("filename", filename);
                    body.add("enterprise_id", enterpriseId);
                    body.add("enterpriseName", enterpriseName);
                    body.add("type", type);
                    body.add("product_id",productId);
                    body.add("userIds",userIds);
                    body.add("body", jsonBody.toString());

                    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
                    RestTemplate restTemplate = new RestTemplate();
                    String requestUrl = PortalUtil.getPropertyValue("cms.api.url")+"wp-json/wp/v2/upload_content";
                    String response = restTemplate.postForObject(requestUrl, requestEntity, String.class);
                    httpResponse.setStatus(HttpServletResponse.SC_OK);
                    JsonObject data = new JsonObject();
                    objResponse = JsonResponse.build(ResponseStatus.status200, ResponseStatus.message200,
                            "Logo info updated successfully", data);
                }

            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage(), e.getCause());

                objResponse = JsonResponse.build(ResponseStatus.status500, ResponseStatus.message500,
                        e.getMessage(), null);

                httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
            return new Gson().toJson(objResponse);
        }```

Title: Java Upload file Rest Template


问:
Url Redirect Pyhton
I want to redirect the page to another url, but it's not happening. I would appreciate your help.

```<code>headers = {
   'Accept': 'application/json',
   'Accept-Encoding': 'gzip, deflate, br',
   'Accept-Language': 'tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7',
   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 OPR/89.0.4447.64',
}
response = requests.get(ad_link, headers=headers, allow_redirects=True)
ic(response.status_code)
#ic(response.history)

if response.history:
    ic("Request was redirected")
    for resp in response.history:
        ic(resp.status_code, resp.url)
        ic('For Control')
    ic("Final destination:")
    ic(response.status_code, response.all_links)
    ic(ad_link)
else:
    ic("Request was not redirected")
    ic(response)
time.sleep(sleep_time)
</code>```

I wrote a loop like this, the content is 200 but it doesn't open the url to the screen. It doesn't run the for here at all.

I go to a url and log in and then I want it to take me to a link from the column named 'ad_link' in the database. Because I don't want to have to open that session all the time. I want to browse the links in my database with an open session.

```<code>mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="m"
)
mycursor = mydb.cursor()

urllib3.disable_warnings()

sql = "SELECT ad_link FROM test"

mycursor.execute(sql)

myresult = mycursor.fetchall()

all_links = myresult[0:]

len_all_links = len(all_links)

dataframe = pd.DataFrame(all_links, columns=['links'])

x = 0
y = 5

#def fonksiyon(i):
     #global x
     #global y

number = np.arange(x,y)

for i in tqdm(number):
    ad_link = dataframe.links[i]  #ad_link = dataframe["links"][i]

    print(ad_link)

    Display = []
    prefs = {"profile.managed_default_content_settings.images": 2} # this is to not load images

    sx = random.randint(1000, 1500)
    sn = random.randint(3000, 4500)

    options = Options()
    options = webdriver.ChromeOptions()

    time.sleep(5)

    options.add_argument('--disable-blink-features=AutomationControlled')
    options.add_experimental_option("detach", True)
    capabilities = options.to_capabilities()
    os.environ['WDM_SSL_VERIFY'] = '0'
    options.add_experimental_option("prefs", prefs)
    wsize = "--window-size=" + str(sx - 10) + ',' + str(sn - 10)
    options.add_argument(str(wsize))
    options.add_argument("prefs", )
    prefs = {"profile.managed_default_content_settings.images": 2}
    options.add_experimental_option("prefs", prefs)
    options.add_argument(['--headless', '--disable-gpu', '--window-size=1920,1080', '--no-sandbox', '--disable-dev-shm-usage'])

    service = Service(executable_path = r'C:\Users\Wiveda\chromedriver.exe')

    test = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

    sleep_time = 5

    test.get(ad_link)
    time.sleep(sleep_time)
    ad_source = test.page_source
    ad_soup = BeautifulSoup(ad_source, 'lxml')

    mainresults = ad_soup.find_all('div', {'class': 'cBox u-inherit '})

    try:
        WebDriverWait(test, timeout=10).until(
            lambda d: d.find_element(By.XPATH, "//button[@class='sc-bczRLJ-accept-btn']")).click()
        WebDriverWait(test, timeout=10).until(
            lambda d: d.find_element(By.XPATH, "//p[@class='phone-container']")).click()
        tel_number = test.find_element(By.XPATH, "//p[@class='phone-container']").text
        ic(tel_number)
    except:
        tel_number = 'Not Found Tel Number'
        ic(tel_number)
        time.sleep(1)

    search_words = ""
    try:
        web_text = test.find_element(By.XPATH, "/html/body/div[6]/div/div[2]/div[3]/div[1]")
        words = ["Import", "x", "y", "z"]
        search_words = [word for word in words if re.findall(word, web_text)]
        text_words = ''
        if search_words:
            for i, word in enumerate(search_words):
                if i < len(search_words) - 1:
                    text_words += f"{word}, "
                else:
                    text_words += f"{word}."
            ic(f"\nCannot send mail because it contains the word.Index : {text_words}")
            ic(re.findall)
            print("İf tamamlandı")
        print("Try tamamlandı")
    except Exception:
        text_words = "Not Found Words"
        ic(text_words)
        time.sleep(1)

    #mainresults = ad_soup.find_all('div', {'class': 'cBox cBox--content u-overflow-inherit '})

    try:
        brand_and_model = ad_soup.find("h1", {"class": ('h u-word')}).get_text()
    except:
        brand_and_model = ' '

    try:
        model_version = ad_soup.find("div", {"class": ('list-title')}).get_text()
    except:
        model_version = ' '

    try:
        location = ad_soup.find("p", {"class": ('seller-address')}).get_text()
    except:
        location = ' '

    try:
        url_id = ad_soup.find(" ", {"class": ('')}).get_text()
    except:
        url_id = ''

    cars_data = pd.DataFrame({
        'brand_and_model': brand_and_model,
        'model_version': model_version,
        'location': location,
        'tel_number': tel_number,
        'url_id': url_id,
    },
        index=[0])

    try:
        table_pre = ad_soup.find("div", {"class": "cBox cBox--content cBox-body"})  # 1 (6 in one)
        all_div = table_pre.findAll("div", {"class": ('key-feature__content')})  # 6 (2 in one)
        all_title = table_pre.findAll("div", {"class": ('key-feature__label')})  # 6
        all_results = table_pre.findAll("div", {"class": ('key-feature__value')})  # 6

    except:
        pass

    description_list = []
    value_list = []
    try:
        div_length = len(all_div)
    except:
        div_length = 6

    for i in range(div_length):
        try:
            description_list.append(all_title[i].text)
            description_list = list(map(lambda x: x.replace(" ", "_"), description_list))
            value_list.append(all_results[i].text)
        except:
            description_list.append('')
            value_list.append('')

    all_key = []
    all_value = []

    try:
        pdiv = ad_soup.find_all('div', {'class': 'bullet-list'})
    except:
        pass

    equipment_key = []

    try:
        equipment_key_length = len(pdiv)
    except:
        equipment_key_length = 1

    equipment_value = []

    try:
        dd_ul_li_length = len(pdiv)
    except:
        dd_ul_li_length = 1

    df3 = pd.DataFrame(list(zip(equipment_key, equipment_value)), columns=['all_key', 'all_value'])

    df2 = pd.DataFrame(list(zip(all_key, all_value)), columns=['all_key', 'all_value'])

    df1 = pd.DataFrame(list(zip(description_list, value_list)), columns=['description_list', 'value_list'])

    df1 = df1.set_index('description_list').T.reset_index(drop=True)
    df1 = df1.rename_axis(None, axis=1)
    df1['link'] = ad_link

    df1.insert(0, "brand_and_model", brand_and_model)
    df1.insert(1, "model_version", model_version)
    df1.insert(2, "location", location)
    df1.insert(5, "tel_number", tel_number)

    df2_3 = pd.concat([df2, df3])
    df2_3 = df2_3.set_index('all_key').T.reset_index(drop=True)
    df2_3 = df2_3.rename_axis(None, axis=1)

    df_last = pd.concat([df1, df2_3], axis=1)

    df_last = df_last.astype(str).groupby(df_last.columns, sort=False, axis=1).agg(
        lambda x: x.apply(','.join, 1))

    now = datetime.now()
    datetime_string = str(now.strftime("%Y%m%d_%H%M%S"))

    df_last['ad_link'] = ad_link
    df_last['download_date_time'] = datetime_string

    config = configparser.RawConfigParser()
    config.read(filenames='my.properties')

    scrap_db = pymysql.connect(host='localhost', user='root', password='', database='m',
                               charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

    cursor = scrap_db.cursor()

    sql = """CREATE TABLE CARS(
        brand_and_model VARCHAR(32),
        model_version VARCHAR(64),
        location VARCHAR(64),
        tel_number VARCHAR(32),
        mileage VARCHAR(32),
        first_registration DATE(7),
        ad_link VARCHAR(256),
        download_date_time DATE(32),
        search words VARCHAR(64)
        url_id int(9)
        )"""

    #cursor.execute(sql)   #Save data to the table

    for row_count in range(0, df_last.shape[0]):
        chunk = df_last.iloc[row_count:row_count + 1, :].values.tolist()

        brand_and_model = ""
        model_version = ""
        location = ""
        tel_number = ""
        mileage = ""
        first_registration = ""
        ad_link = ""
        download_date_time = ""
        url_id = ""

        lenght_of_chunk = len(chunk[0])

        if "brand_and_model" in cars_data:
            try:
                brand_and_model = chunk[0][0]
            except:
                brand_and_model = ""

        if "model_version" in cars_data:
            try:
                model_version = chunk[0][1]
            except:
                model_version = ""

        if "location" in cars_data:
            try:
                location = chunk[0][2]
            except:
                location = ""

        if "tel_number" in cars_data:
            try:
                tel_number = chunk[0][5]
            except:
                tel_number = ""

        if "Kilometerstand" in description_list:
            index_no = description_list.index("Kilometerstand")
            try:
                mileage = value_list[index_no]
            except:
                mileage = ""

        if "Erstzulassung" in description_list:
            index_no = description_list.index("Erstzulassung")
            try:
                first_registration = value_list[index_no]
            except:
                first_registration = ""

        if chunk[0][lenght_of_chunk - 2] != "":
            ad_link = chunk[0][lenght_of_chunk - 2]  # ad_link

        if chunk[0][lenght_of_chunk - 1] != "":
            download_date_time = chunk[0][lenght_of_chunk - 1]  # datetime_string

    if (brand_and_model == ' '):
        control = "false"
    else:
        control = "true"

    if control == "true":
        mySql_insert_query = "INSERT INTO CARS(brand_and_model,model_version,location,tel_number,mileage,first_registration,ad_link,download_date_time,url_id) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
        val = (brand_and_model, model_version, location, tel_number, mileage, first_registration, ad_link, download_date_time, url_id)

    time.sleep(5)

    cursor = scrap_db.cursor()
    cursor.execute(mySql_insert_query, val)

    scrap_db.commit()
    ic(cursor.rowcount, "Record inserted successfully into *CARS* table")

    if (tel_number == 'Not Found Tel Number') and (text_words == 'Not Found Words'):
        control = "true"
    else:
        control = "pass"

    time.sleep(10)

    if control == "true":
            ic("Mail Sending")
            test.find_element(By.XPATH, "/div[2]/div[2]/div/div[4]/div/span").click()
            test.implicitly_wait(5)
            eMl = test.find_element(By.XPATH, "/html/div[1]/form/div[1]/div/input")
            test.implicitly_wait(3)
            eMl.click()
            time.sleep(10)
            eMl.send_keys("v@gmail.com")
            time.sleep(8)
            passw = WebDriverWait(test, 20).until(EC.visibility_of_element_located((By.XPATH, "/html/body/div[2]/div[1]/form/div[2]/div/input")))
            test.implicitly_wait(3)
            passw.click()
            time.sleep(1)

            passw.send_keys('W' + Keys.ENTER)
            time.sleep(5)
            test.find_element(By.XPATH,'/html/div/div[2]/a').click()
            time.sleep(3)

            headers = {
               'Accept': 'application/json',
               'Accept-Encoding': 'gzip, deflate, br',
               'Accept-Language': 'tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7',
               'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 OPR/89.0.4447.64',
            }

            response = requests.get(ad_link, headers=headers, allow_redirects=True, timeout=2.50)
            ic(response.status_code)

            if response.history:
              for step in response.history:
                ic("Request was redirected")
                for resp in response.history:
                    ic(resp.status_code, resp.url)
                    ic('For Control')
                ic("Final destination:")
                ic(response.status_code, response.all_links)
                ic(ad_link)
            else:
                ic("Request was not redirected")
                ic(response)
            time.sleep(sleep_time)
            ic('destination_status')
</code>```

Title: Url Redirect Pyhton

Body:
I want to redirect the page to another url, but it's not happening. I would appreciate your help.

headers = {
   'Accept': 'application/json',
   'Accept-Encoding': 'gzip, deflate, br',
   'Accept-Language': 'tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7',
   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 OPR/89.0.4447.64',
}
response = requests.get(ad_link, headers=headers, allow_redirects=True)
ic(response.status_code)
#ic(response.history)

if response.history:
    ic("Request was redirected")
    for resp in response.history:
        ic(resp.status_code, resp.url)
        ic('For Control')
    ic("Final destination:")
    ic(response.status_code, response.all_links)
    ic(ad_link)
else:
    ic("Request was not redirected")
    ic(response)
time.sleep(sleep_time)

I wrote a loop like this, the content is 200 but it doesn't open the url to the screen. It doesn't run the for here at all.

I go to a url and log in and then I want it to take me to a link from the column named 'ad_link' in the database. Because I don't want to have to open that session all the time. I want to browse the links in my database with an open session.

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="m"
)
mycursor = mydb.cursor()

urllib3.disable_warnings()

sql = "SELECT ad_link FROM test"

mycursor.execute(sql)

myresult = mycursor.fetchall()

all_links = myresult[0:]

len_all_links = len(all_links)

dataframe = pd.DataFrame(all_links, columns=['links'])

x = 0
y = 5

#def fonksiyon(i):
     #global x
     #global y

number = np.arange(x,y)

for i in tqdm(number):
    ad_link = dataframe.links[i]  #ad_link = dataframe["links"][i]

    print(ad_link)

    Display = []
    prefs = {"profile.managed_default_content_settings.images": 2} # this is to not load images

    sx = random.randint(1000, 1500)
    sn = random.randint(3000, 4500)

    options = Options()
    options = webdriver.ChromeOptions()

    time.sleep(5)

    options.add_argument('--disable-blink-features=AutomationControlled')
    options.add_experimental_option("detach", True)
    capabilities = options.to_capabilities()
    os.environ['WDM_SSL_VERIFY'] = '0'
    options.add_experimental_option("prefs", prefs)
    wsize = "--window-size=" + str(sx - 10) + ',' + str(sn - 10)
    options.add_argument(str(wsize))
    options.add_argument("prefs", )
    prefs = {"profile.managed_default_content_settings.images": 2}
    options.add_experimental_option("prefs", prefs)
    options.add_argument(['--headless', '--disable-gpu', '--window-size=1920,1080', '--no-sandbox', '--disable-dev-shm-usage'])

    service = Service(executable_path = r'C:\Users\Wiveda\chromedriver.exe')

    test = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

    sleep_time = 5

    test.get(ad_link)
    time.sleep(sleep_time)
    ad_source = test.page_source
    ad_soup = BeautifulSoup(ad_source, 'lxml')

    mainresults = ad_soup.find_all('div', {'class': 'cBox u-inherit '})

    try:
        WebDriverWait(test, timeout=10).until(
            lambda d: d.find_element(By.XPATH, "//button[@class='sc-bczRLJ-accept-btn']")).click()
        WebDriverWait(test, timeout=10).until(
            lambda d: d.find_element(By.XPATH, "//p[@class='phone-container']")).click()
        tel_number = test.find_element(By.XPATH, "//p[@class='phone-container']").text
        ic(tel_number)
    except:
        tel_number = 'Not Found Tel Number'
        ic(tel_number)
        time.sleep(1)

    search_words = ""
    try:
        web_text = test.find_element(By.XPATH, "/html/body/div[6]/div/div[2]/div[3]/div[1]")
        words = ["Import", "x", "y", "z"]
        search_words = [word for word in words if re.findall(word, web_text)]
        text_words = ''
        if search_words:
            for i, word in enumerate(search_words):
                if i < len(search_words) - 1:
                    text_words += f"{word}, "
                else:
                    text_words += f"{word}."
            ic(f"\nCannot send mail because it contains the word.Index : {text_words}")
            ic(re.findall)
            print("İf tamamlandı")
        print("Try tamamlandı")
    except Exception:
        text_words = "Not Found Words"
        ic(text_words)
        time.sleep(1)

    #mainresults = ad_soup.find_all('div', {'class': 'cBox cBox--content u-overflow-inherit '})

    try:
        brand_and_model = ad_soup.find("h1", {"class": ('h u-word')}).get_text()
    except:
        brand_and_model = ' '

    try:
        model_version = ad_soup.find("div", {"class": ('list-title')}).get_text()
    except:
        model_version = ' '

    try:
        location = ad_soup.find("p", {"class": ('seller-address')}).get_text()
    except:
        location = ' '

    try:
        url_id = ad_soup.find(" ", {"class": ('')}).get_text()
    except:
        url_id = ''

    cars_data = pd.DataFrame({
        'brand_and_model': brand_and_model,
        'model_version': model_version,
        'location': location,
        'tel_number': tel_number,
        'url_id': url_id,
    },
        index=[0])

    try:
        table_pre = ad_soup.find("div", {"class": "cBox cBox--content cBox-body"})  # 1 (6 in one)
        all_div = table_pre.findAll("div", {"class": ('key-feature__content')})  # 6 (2 in one)
        all_title = table_pre.findAll("div", {"class": ('key-feature__label')})  # 6
        all_results = table_pre.findAll("div", {"class": ('key-feature__value')})  # 6

    except:
        pass

    description_list = []
    value_list = []
    try:
        div_length = len(all_div)
    except:
        div_length = 6

    for i in range(div_length):
        try:
            description_list.append(all_title[i].text)
            description_list = list(map(lambda x: x.replace(" ", "_"), description_list))
            value_list.append(all_results[i].text)
        except:
            description_list.append('')
            value_list.append('')

    all_key = []
    all_value = []

    try:
        pdiv = ad_soup.find_all('div', {'class': 'bullet-list'})
    except:
        pass

    equipment_key = []

    try:
        equipment_key_length = len(pdiv)
    except:
        equipment_key_length = 1

    equipment_value = []

    try:
        dd_ul_li_length = len(pdiv)
    except:
        dd_ul_li_length = 1

    df3 = pd.DataFrame(list(zip(equipment_key, equipment_value)), columns=['all_key', 'all_value'])

    df2 = pd.DataFrame(list(zip(all_key, all_value)), columns=['all_key', 'all_value'])

    df1 = pd.DataFrame(list(zip(description_list, value_list)), columns=['description_list', 'value_list'])

    df1 = df1.set_index('description_list').T.reset_index(drop=True)
    df1 = df1.rename_axis(None, axis=1)
    df1['link'] = ad_link

    df1.insert(0, "brand_and_model", brand_and_model)
    df1.insert(1, "model_version", model_version)
    df1.insert(2, "location", location)
    df1.insert(5, "tel_number", tel_number)

    df2_3 = pd.concat([df2, df3])
    df2_3 = df2_3.set_index('all_key').T.reset_index(drop=True)
    df2_3 = df2_3.rename_axis(None, axis=1)

    df_last = pd.concat([df1, df2_3], axis=1)

    df_last = df_last.astype(str).groupby(df_last.columns, sort=False, axis=1).agg(
        lambda x: x.apply(','.join, 1))

    now = datetime.now()
    datetime_string = str(now.strftime("%Y%m%d_%H%M%S"))

    df_last['ad_link'] = ad_link
    df_last['download_date_time'] = datetime_string

    config = configparser.RawConfigParser()
    config.read(filenames='my.properties')

    scrap_db = pymysql.connect(host='localhost', user='root', password='', database='m',
                               charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

    cursor = scrap_db.cursor()

    sql = """CREATE TABLE CARS(
        brand_and_model VARCHAR(32),
        model_version VARCHAR(64),
        location VARCHAR(64),
        tel_number VARCHAR(32),
        mileage VARCHAR(32),
        first_registration DATE(7),
        ad_link VARCHAR(256),
        download_date_time DATE(32),
        search words VARCHAR(64)
        url_id int(9)
        )"""

    #cursor.execute(sql)   #Save data to the table

    for row_count in range(0, df_last.shape[0]):
        chunk = df_last.iloc[row_count:row_count + 1, :].values.tolist()

        brand_and_model = ""
        model_version = ""
        location = ""
        tel_number = ""
        mileage = ""
        first_registration = ""
        ad_link = ""
        download_date_time = ""
        url_id = ""

        lenght_of_chunk = len(chunk[0])

        if "brand_and_model" in cars_data:
            try:
                brand_and_model = chunk[0][0]
            except:
                brand_and_model = ""

        if "model_version" in cars_data:
            try:
                model_version = chunk[0][1]
            except:
                model_version = ""

        if "location" in cars_data:
            try:
                location = chunk[0][2]
            except:
                location = ""

        if "tel_number" in cars_data:
            try:
                tel_number = chunk[0][5]
            except:
                tel_number = ""

        if "Kilometerstand" in description_list:
            index_no = description_list.index("Kilometerstand")
            try:
                mileage = value_list[index_no]
            except:
                mileage = ""

        if "Erstzulassung" in description_list:
            index_no = description_list.index("Erstzulassung")
            try:
                first_registration = value_list[index_no]
            except:
                first_registration = ""

        if chunk[0][lenght_of_chunk - 2] != "":
            ad_link = chunk[0][lenght_of_chunk - 2]  # ad_link

        if chunk[0][lenght_of_chunk - 1] != "":
            download_date_time = chunk[0][lenght_of_chunk - 1]  # datetime_string

    if (brand_and_model == ' '):
        control = "false"
    else:
        control = "true"

    if control == "true":
        mySql_insert_query = "INSERT INTO CARS(brand_and_model,model_version,location,tel_number,mileage,first_registration,ad_link,download_date_time,url_id) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
        val = (brand_and_model, model_version, location, tel_number, mileage, first_registration, ad_link, download_date_time, url_id)

    time.sleep(5)

    cursor = scrap_db.cursor()
    cursor.execute(mySql_insert_query, val)

    scrap_db.commit()
    ic(cursor.rowcount, "Record inserted successfully into *CARS* table")

    if (tel_number == 'Not Found Tel Number') and (text_words == 'Not Found Words'):
        control = "true"
    else:
        control = "pass"

    time.sleep(10)

    if control == "true":
            ic("Mail Sending")
            test.find_element(By.XPATH, "/div[2]/div[2]/div/div[4]/div/span").click()
            test.implicitly_wait(5)
            eMl = test.find_element(By.XPATH, "/html/div[1]/form/div[1]/div/input")
            test.implicitly_wait(3)
            eMl.click()
            time.sleep(10)
            eMl.send_keys("v@gmail.com")
            time.sleep(8)
            passw = WebDriverWait(test, 20).until(EC.visibility_of_element_located((By.XPATH, "/html/body/div[2]/div[1]/form/div[2]/div/input")))
            test.implicitly_wait(3)
            passw.click()
            time.sleep(1)

            passw.send_keys('W' + Keys.ENTER)
            time.sleep(5)
            test.find_element(By.XPATH,'/html/div/div[2]/a').click()
            time.sleep(3)

            headers = {
               'Accept': 'application/json',
               'Accept-Encoding': 'gzip, deflate, br',
               'Accept-Language': 'tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7',
               'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 OPR/89.0.4447.64',
            }

            response = requests.get(ad_link, headers=headers, allow_redirects=True, timeout=2.50)
            ic(response.status_code)

            if response.history:
              for step in response.history:
                ic("Request was redirected")
                for resp in response.history:
                    ic(resp.status_code, resp.url)
                    ic('For Control')
                ic("Final destination:")
                ic(response.status_code, response.all_links)
                ic(ad_link)
            else:
                ic("Request was not redirected")
                ic(response)
            time.sleep(sleep_time)
            ic('destination_status')


问:
How do I Scrape the organic traffic graph from SEMRUSH website?
I am doing a project which requires the trends in traffic volumes of various company's websites.
I am scraping data from semrush.com through a graph which the website provides.
Tried everything to scrape the data from entire graph but i need a way to automate the task so that it can get the same data for 1600! companies.

I scraped the data from this file easily but cannot do it for every 1600! companies.

I downloaded the following rpc(json) file manually
rpc file i downloaded from network section of by browser

How do i automate this task

The graph looks like this:
enter image description here


问:
Why can  be used in hyperlink tags() and not italicize anything. Does it have to do with the structure of the code
```<code>   <a href="#" class="social"><i class="fab fa-facebook-f"></i></a>
</code>```

I saw this code online.
Please, why is the  tag used here.

I searched online and found that is was used  to italicize text but it is not used in this instance.

Title: Why can <i> be used in hyperlink tags(<a>) and not italicize anything. Does it have to do with the structure of the code


问:
AWS EventBridge Pipes: Is it possible to apply enrichment input transformer on an array of events?
I'm evaluating EventBridge Pipes and I have the following setup:

Source
Filtering
Enrichment
Target

Kinesis stream →
Not configured →
Step Functions →
SNS Topic

Additionally the batch size for the kinesis stream is set > 1. In this szenario this does mean, that the Step Function retrieves an array of kinesis events.

The enrichment input transformer works fine as long as I provide a single event:

event:

{
    "kinesisSchemaVersion": "1.0",
    "partitionKey": "1",
    "sequenceNumber": "49590338271490256608559692538361571095921575989136588898",
    "data": "SGVsbG8sIHRoaXMgaXMgYSB0ZXN0Lg==",
    "approximateArrivalTimestamp": 1545084650.987,
    "eventSource": "aws:kinesis",
    "eventVersion": "1.0",
    "eventID": "shardId-000000000006:49590338271490256608559692538361571095921575989136588898",
    "eventName": "aws:kinesis:record",
    "invokeIdentityArn": "arn:aws:iam::123456789012:role/lambda-role",
    "awsRegion": "us-east-2",
    "eventSourceARN": "arn:aws:kinesis:us-east-2:123456789012:stream/lambda-stream"
  }
```
<h4><strong><code>transformer:</code></strong></h4>
<pre class="lang-json prettyprint-override"><code>{
  "data": <$.data>
}
</code>```

output:

{
  "data": "Hello, this is a test."
}
```
<p>The desired behaviour is to get base64 decoded data payload, which works fine. However if I provide an array of events this transformer is not correct anymore and provides empty value.</p>
<pre class="lang-json prettyprint-override"><code>[{
    ...
    "data": "SGVsbG8sIHRoaXMgaXMgYSB0ZXN0Lg==",
    ...
  },
  {
    ...
    "data": "SGVsbG8sIHRoaXMgaXMgYSB0ZXN0Lg==",
    ...
  }
]
</code>```

One possible transformer I figured out looks like this:

{
  "data": <$.0.data>
}
```

The problem here is I am getting only the decoded payload for the first element.
My goal is, of course, to get the decoded payload for each event in the array.

Do You have any ideas on how to approach this?

Body:
I'm evaluating EventBridge Pipes and I have the following setup:

Source
Filtering
Enrichment
Target

Kinesis stream →
Not configured →
Step Functions →
SNS Topic

Additionally the batch size for the kinesis stream is set > 1. In this szenario this does mean, that the Step Function retrieves an array of kinesis events.

The enrichment input transformer works fine as long as I provide a single event:

event:

{
    "kinesisSchemaVersion": "1.0",
    "partitionKey": "1",
    "sequenceNumber": "49590338271490256608559692538361571095921575989136588898",
    "data": "SGVsbG8sIHRoaXMgaXMgYSB0ZXN0Lg==",
    "approximateArrivalTimestamp": 1545084650.987,
    "eventSource": "aws:kinesis",
    "eventVersion": "1.0",
    "eventID": "shardId-000000000006:49590338271490256608559692538361571095921575989136588898",
    "eventName": "aws:kinesis:record",
    "invokeIdentityArn": "arn:aws:iam::123456789012:role/lambda-role",
    "awsRegion": "us-east-2",
    "eventSourceARN": "arn:aws:kinesis:us-east-2:123456789012:stream/lambda-stream"
  }

transformer:

{
  "data": <$.data>
}

output:

{
  "data": "Hello, this is a test."
}

The desired behaviour is to get base64 decoded data payload, which works fine. However if I provide an array of events this transformer is not correct anymore and provides empty value.

[{
    ...
    "data": "SGVsbG8sIHRoaXMgaXMgYSB0ZXN0Lg==",
    ...
  },
  {
    ...
    "data": "SGVsbG8sIHRoaXMgaXMgYSB0ZXN0Lg==",
    ...
  }
]

One possible transformer I figured out looks like this:

{
  "data": <$.0.data>
}

The problem here is I am getting only the decoded payload for the first element.
My goal is, of course, to get the decoded payload for each event in the array.

Do You have any ideas on how to approach this?


问:
How to connect to Windows domain controller using pysmb as user from different domain?
I am able to connect to a W2019 domain controller using python smb modules on Linux using the following type of code:

```<code>from smb.SMBConnection import SMBConnection
conn = SMBConnection('administrator', 'p@ssw0rd', 'anything', 'm1')
conn.connect(ip_address)
</code>```

However, the following doesn't work:

```<code>from smb.SMBConnection import SMBConnection
conn = SMBConnection('mydomain\\administrator', 'p@ssw0rd', 'anything', 'm1')
conn.connect(ip_address)
</code>```

I want to use this interface to connect to a Windows domain controller as a user from a different domain. How can I do that ?

PS1: 'mydomain' is the domain netbios name

PS2: I have also tried passing the 'domain' argument to the constructor. Apparently it is ignored. Authentication succeeds with any value passed in.

Body:
I am able to connect to a W2019 domain controller using python smb modules on Linux using the following type of code:

from smb.SMBConnection import SMBConnection
conn = SMBConnection('administrator', 'p@ssw0rd', 'anything', 'm1')
conn.connect(ip_address)

However, the following doesn't work:

from smb.SMBConnection import SMBConnection
conn = SMBConnection('mydomain\\administrator', 'p@ssw0rd', 'anything', 'm1')
conn.connect(ip_address)

I want to use this interface to connect to a Windows domain controller as a user from a different domain. How can I do that ?

PS1: 'mydomain' is the domain netbios name

PS2: I have also tried passing the 'domain' argument to the constructor. Apparently it is ignored. Authentication succeeds with any value passed in.


问:
Compilation error in this code - Syntax error
Console messages :

Line 16: Syntax error at input ','
Line 25: Mismatched input 'isShort' expecting 'end of line without line continuation'

Code:

```<code>This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0SI J/
JimmyKartel

- //@version=5
study("RSI JimmyKartel")

Definition of RSI indicator parameters
length = input(14, minval=1)
overbought = input(30)
oversold = input(70)

Calculate the RSI indicator
rsi = rsi(close, length)

Calculate the MACD indicator
**macdLine, macdSignal, macdHistogram := macd(close, 12, 26, 9)**

Define variables to track trading state
isLong = false
isShort = false

Trading strategy:
If RSI is above overbought level, take a short position
If RSI is below oversold level, take a long position
**if rsi > overbought**
isShort := true
isLong := false
else if rsi < oversold
isShort := false
isLong := true

Display indicators on chart
rsiLine = line.new(rsi, title="RSI", color=color.orange, linewidth=2)
overboughtLine = line.new(overbought, title="Overbought", color=color.red, linewidth=1, style=plot.style_circles)
oversoldLine = line.new(oversold, title="Oversold", color=color.red, linewidth=1, style=plot.style_circles)

line.set_data(rsiLine, rsi)
line.set_data(overboughtLine, overbought)
line.set_data(oversoldLine, oversold)

Add plots to the chart
plot(rsi, title="RSI Plot", color=color.green, linewidth=2)
plot(macdLine, title="MACD Line", color=color.blue, linewidth=2)
plot(macdSignal, title="MACD Signal", color=color.purple, linewidth=2)
plot(macdHistogram, title="MACD Histogram", color=color.red, linewidth=2)
</code>```

The syntax is correct for version 5 of the PineScript language, but I have these errors in the console of Tradinview when I want to apply to the graph.

I'm an amateur and learn on my own.

Body:
Console messages :

Line 16: Syntax error at input ','
Line 25: Mismatched input 'isShort' expecting 'end of line without line continuation'

Code:

This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0SI J/
JimmyKartel

- //@version=5
study("RSI JimmyKartel")

Definition of RSI indicator parameters
length = input(14, minval=1)
overbought = input(30)
oversold = input(70)

Calculate the RSI indicator
rsi = rsi(close, length)

Calculate the MACD indicator
**macdLine, macdSignal, macdHistogram := macd(close, 12, 26, 9)**

Define variables to track trading state
isLong = false
isShort = false

Trading strategy:
If RSI is above overbought level, take a short position
If RSI is below oversold level, take a long position
**if rsi > overbought**
isShort := true
isLong := false
else if rsi < oversold
isShort := false
isLong := true

Display indicators on chart
rsiLine = line.new(rsi, title="RSI", color=color.orange, linewidth=2)
overboughtLine = line.new(overbought, title="Overbought", color=color.red, linewidth=1, style=plot.style_circles)
oversoldLine = line.new(oversold, title="Oversold", color=color.red, linewidth=1, style=plot.style_circles)

line.set_data(rsiLine, rsi)
line.set_data(overboughtLine, overbought)
line.set_data(oversoldLine, oversold)

Add plots to the chart
plot(rsi, title="RSI Plot", color=color.green, linewidth=2)
plot(macdLine, title="MACD Line", color=color.blue, linewidth=2)
plot(macdSignal, title="MACD Signal", color=color.purple, linewidth=2)
plot(macdHistogram, title="MACD Histogram", color=color.red, linewidth=2)

The syntax is correct for version 5 of the PineScript language, but I have these errors in the console of Tradinview when I want to apply to the graph.

I'm an amateur and learn on my own.


问:
does spark driver process run on master node or one of the worker nodes assigned by the cluster manager?
Some article tells, the spark driver process(program) runs on master node and some where i can see, cluster manager launches the driver process on one of the worker nodes.

if that runs on one of the worker nodes, In master node only cluster manager process will run?

ex:
if we have 4 nodes with 1 master node and 3 worker node. if the cluster manager launches driver program in one of the worker node, ideally we will have only 2 worker nodes right?

I just want to understand the where driver program runs, master node or worker node in cluster deploy mode?


问:
sequelize eager loading for join
```<code>    Battery.belongsTo(TagType, { constraints: true, onDelete: "CASCADE" });
    Tag.belongsTo(TagType, { constraints: true, onDelete: "CASCADE" });

    const battery = sequelize.define("Battery", {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  voltage: {
    type: Sequelize.INTEGER,
    allowNull: false,
  },
  percetange: {
    type: Sequelize.INTEGER,
    allowNull: false,
  },
});

const tag = sequelize.define("Tag", {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false,
    unique: true,
  },
  battery: {
    type: Sequelize.INTEGER,
    allowNull: true,
  },
});

//api
          const percetangeAndTags = [];
              const tags = await Tag.findAll({
                include: [
                  {
                    model: TagType,
                    attributes: ["name"],
                  },
                ],
              });
              error.catchError("notFound", tags);
              await Promise.all(
                tags.map(async (tag) => {
                  const batteryVoltageValue = await Battery.findOne({
                    where: {
                      tagTypeId: tag.tagTypeId,
                      voltage: { [Op.lte]: tag.battery },
                    },
                    attributes: [
                      [Sequelize.fn("max", Sequelize.col("voltage")), "max"],
                    ],
                  });
                  const battery = await Battery.findOne({
                    where: {
                      tagTypeId: tag.tagTypeId,
                      voltage: batteryVoltageValue.dataValues.max,
                    },
                  });

                  percetangeAndTags.push({
                    id: tag.id,
                    name: tag.name,
                    tag_type: tag.tag_type.name,
                    percetange: battery?.percetange,
                  });
                })
              );
              res.status(200).json(percetangeAndTags);
</code>```

How can I write this code in the most efficient way?

Because the explanation is short, it doesn't accept the question, so I wrote a poem instead of randomly throwing it.

Keleci bilen kişinin yüzünü ağ ede bir söz
Sözü pişirip diyenin işini sağ ede bir söz

Söz ola kese savaşı söz ola bitire başı
Söz ola ağılı aşı bal ile yağ ede bir söz

Title: sequelize eager loading for join

Body:
    Battery.belongsTo(TagType, { constraints: true, onDelete: "CASCADE" });
    Tag.belongsTo(TagType, { constraints: true, onDelete: "CASCADE" });

    const battery = sequelize.define("Battery", {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  voltage: {
    type: Sequelize.INTEGER,
    allowNull: false,
  },
  percetange: {
    type: Sequelize.INTEGER,
    allowNull: false,
  },
});

const tag = sequelize.define("Tag", {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false,
    unique: true,
  },
  battery: {
    type: Sequelize.INTEGER,
    allowNull: true,
  },
});

//api
          const percetangeAndTags = [];
              const tags = await Tag.findAll({
                include: [
                  {
                    model: TagType,
                    attributes: ["name"],
                  },
                ],
              });
              error.catchError("notFound", tags);
              await Promise.all(
                tags.map(async (tag) => {
                  const batteryVoltageValue = await Battery.findOne({
                    where: {
                      tagTypeId: tag.tagTypeId,
                      voltage: { [Op.lte]: tag.battery },
                    },
                    attributes: [
                      [Sequelize.fn("max", Sequelize.col("voltage")), "max"],
                    ],
                  });
                  const battery = await Battery.findOne({
                    where: {
                      tagTypeId: tag.tagTypeId,
                      voltage: batteryVoltageValue.dataValues.max,
                    },
                  });

                  percetangeAndTags.push({
                    id: tag.id,
                    name: tag.name,
                    tag_type: tag.tag_type.name,
                    percetange: battery?.percetange,
                  });
                })
              );
              res.status(200).json(percetangeAndTags);

How can I write this code in the most efficient way?

Because the explanation is short, it doesn't accept the question, so I wrote a poem instead of randomly throwing it.

Keleci bilen kişinin yüzünü ağ ede bir söz
Sözü pişirip diyenin işini sağ ede bir söz

Söz ola kese savaşı söz ola bitire başı
Söz ola ağılı aşı bal ile yağ ede bir söz


问:
python script to automate call and play voice recording during calls
Python script that will make a phone call to a specified phone number at a specified time using an Android device and play a voice recording during the call. my code didn't work failed transaction ?

```<code>import os
import datetime

def makeCall(number):
  os.system(f"am start -a android.intent.action.CALL -d tel:{number}")

def playRecording():
  os.system("am start -a android.intent.action.VIEW -d file:///sdcard/recordings/recording.mp3")

def checkTime(hour, minute):
  currentTime = datetime.datetime.now()
  if currentTime.hour == hour and currentTime.minute == minute:
    return True
  else:
    return False

number = "1234567890"  # Replace with your desired phone number
hour = 12   # Replace with the hour (in 24-hour format) at which you want the call to be made
minute = 0  # Replace with the minute at which you want the call to be made

while True:
  if checkTime(hour, minute):
    makeCall(number)
    playRecording()
    break  # Exit the loop once the call has been made
  else:
    continue  # Check the time again after a short delay

</code>```

tried to run on my android phone can identify any mistakes and help me to fix it

Body:
Python script that will make a phone call to a specified phone number at a specified time using an Android device and play a voice recording during the call. my code didn't work failed transaction ?

import os
import datetime

def makeCall(number):
  os.system(f"am start -a android.intent.action.CALL -d tel:{number}")

def playRecording():
  os.system("am start -a android.intent.action.VIEW -d file:///sdcard/recordings/recording.mp3")

def checkTime(hour, minute):
  currentTime = datetime.datetime.now()
  if currentTime.hour == hour and currentTime.minute == minute:
    return True
  else:
    return False

number = "1234567890"  # Replace with your desired phone number
hour = 12   # Replace with the hour (in 24-hour format) at which you want the call to be made
minute = 0  # Replace with the minute at which you want the call to be made

while True:
  if checkTime(hour, minute):
    makeCall(number)
    playRecording()
    break  # Exit the loop once the call has been made
  else:
    continue  # Check the time again after a short delay

tried to run on my android phone can identify any mistakes and help me to fix it


问:
iframe check the page inside if goes into error
I have an iframe where i set an url and i want to check when the iframe is loaded the page inside goes into error or not.
I tried to check the response but it goes to 200 and it's okay for me.
But when the url of iframe is loaded it show me an Error. In that case i would like to route in another page. So i just want to check if the page inside of iframe goes to an error or not
Is it possible?
I'm working with Angular.</p>
```<code><iframe *ngIf="show" id="id" [src]="url| safeUrl">
</iframe>
</code>```


问:
global google undefined in production
i build an spotify clone in react/nodejs and made it possibale to login/signup via google, using google uauth 2.
in the dev enviorment its works perfectly fine but on production the google virable at line 29 is undefined.
been searching for a while now hope someone can help img of my code

i tried to install google apis via npm but it havent worked niether.
Also thought about adding it as env var in Render's setting (deploy site) but i dont know what is the value of the google var in line 29

Title: global google undefined in production


问:
Should i cache microservice API response or not?
I need to show some events/data inside my product. The data partially resides on my product server and partially on other micro-services. When rendering, i make call to my server which fetches my side data and make an server to server API call to those micro-services. This data is dynamic in nature but changes are not very frequent, so i have planned to cache the response in my side server for quick access. For caching i have planned to use redis. Assume the fetched data size from each micro service does not exceed 5MB(worst case scenario) and the micro service is also my another product.

My question here is, should i cache the API response from each micro service or can make the API call every time a request comes. The data is not constant for every user and varies based on the user accessing it.


问:
Drop down in nicEditor should be relative to my div
I have placed nicEditor inside a div which will have its own scroll. Once i click font size in editor the size dropdown list appears according to the window scroll bar.

I want the position of that dropdown relative to the inside scroll not outside scroll


问:
How can I generate a list of thumbnails in a local html file from a list of product codes from a website?
I'm looking for an easier way to look at product images.
Currently I individually search for them from a spreadsheet list. This feels tedious so I'm wondering if there is a way to automatically generate this list as main product images in a html file just. I'd just need to reference the website and the list of codes to crawl then.

Thanks for your help

J :)

I don't have any specific js hoping you have some cool idea
here is a screenshot of the spreadsheet


问:
iOS 16 collectionView layoutAttributesForItem return the wrong size with estimated height compositional layout
I ran into an ios 16 problem when layoutAttributesForItem returns a very small cell size if it is far beyond the scope and visibility and has not yet been seen.

I'm using compositional layout with estimated(1) and it feels like its real size is not calculated before it appears on the screen

So I set the section:

`

```<code>     func getListLayout() -> NSCollectionLayoutSection {
        let itemSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1),
            heightDimension: .estimated(1)
        )
        let item = NSCollectionLayoutItem(layoutSize: itemSize)

        let groupSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1),
            heightDimension: .estimated(1)
        )

        let group = NSCollectionLayoutGroup.horizontal(
            layoutSize: groupSize,
            subitem: item,
            count: 1
        )

        group.contentInsets = .zero

        let headerFooterSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1),
            heightDimension: .estimated(headerHeight)
        )

        let section = NSCollectionLayoutSection(group: group)
        section.contentInsets = .zero
        section.boundarySupplementaryItems = [sectionHeader]

        return section
    }
</code>```

Wrong result with:

```<code>let attributes = collectionView.layoutAttributesForItem(at: indexPath)
attributes.frame.minY
</code>```

IOS 14-15 everything works well..

I noticed that if you set a specific height for the cell (absolute), everything works as it should, but I need the height to be considered dynamically.
Example:
enter image description here

Body:
I ran into an ios 16 problem when layoutAttributesForItem returns a very small cell size if it is far beyond the scope and visibility and has not yet been seen.

I'm using compositional layout with estimated(1) and it feels like its real size is not calculated before it appears on the screen

So I set the section:

`

     func getListLayout() -> NSCollectionLayoutSection {
        let itemSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1),
            heightDimension: .estimated(1)
        )
        let item = NSCollectionLayoutItem(layoutSize: itemSize)

        let groupSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1),
            heightDimension: .estimated(1)
        )

        let group = NSCollectionLayoutGroup.horizontal(
            layoutSize: groupSize,
            subitem: item,
            count: 1
        )

        group.contentInsets = .zero

        let headerFooterSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1),
            heightDimension: .estimated(headerHeight)
        )

        let section = NSCollectionLayoutSection(group: group)
        section.contentInsets = .zero
        section.boundarySupplementaryItems = [sectionHeader]

        return section
    }

Wrong result with:

let attributes = collectionView.layoutAttributesForItem(at: indexPath)
attributes.frame.minY

IOS 14-15 everything works well..

I noticed that if you set a specific height for the cell (absolute), everything works as it should, but I need the height to be considered dynamically.
Example:
enter image description here


问:
Gitlab: How to get only the matching tag from a submodule's commit ID (Git)
I want to go into a specific submodule's commit ID and get only the tags that have a matching commit ID:

To illustrate the problem, below I put an example:

We're gonna use this specific submodule as example, clicking on its commit ID (6f955c83):

Then going into the "Tags" section:

And I get a list of all the tags. The problem is that they all don't match the submodule commit ID. Only one matches as seen below:

This is my progress so far:
I'm using this formula to sort out the tags of the submodule from newest to oldest:

```<code>git submodule foreach git tag --sort=-taggerdate -l
</code>```

The problem is that it fetches all tags, including the tags with non matching commit IDs. Here's the same AftCol submodule:

Is there a way I can improve the Git formula above so it only filters matching commit IDs tags?

Thanks!

Body:
I want to go into a specific submodule's commit ID and get only the tags that have a matching commit ID:

To illustrate the problem, below I put an example:

We're gonna use this specific submodule as example, clicking on its commit ID (6f955c83):

Then going into the "Tags" section:

And I get a list of all the tags. The problem is that they all don't match the submodule commit ID. Only one matches as seen below:

This is my progress so far:
I'm using this formula to sort out the tags of the submodule from newest to oldest:

git submodule foreach git tag --sort=-taggerdate -l

The problem is that it fetches all tags, including the tags with non matching commit IDs. Here's the same AftCol submodule:

Is there a way I can improve the Git formula above so it only filters matching commit IDs tags?

Thanks!


问:
After submitting contact form woocommerce single page download the digital products (PDF File) sending enquiry details email to admin and client
How to integrate a contact form 7 woo-commerce product single page, after submitting digital download products (PDF File) sending enquiry details email to the admin and user.

I added the form, but am not able to download the woocommerce digital download products (PDF File) and send email from woocommerce single page.


问:
Memory fault when setting potentialgroup of a Siemens IO-card through Openness with Python and Ctypes
I am making a Hardware/Software-generator for TIA portal 16 in Python 3.7. It is working pretty well but now I am running into a problem:

I want to change the potentialgroups of certain IO-cards through this program but through inspection with Openness Explorer I found out that it is set in a Uint64 variable. Some digging tought me that Python doesn't support this datatype but you can use Ctypes to use it anyway. However when I do this I get an error:

```<code>Onverwerkte uitzondering: System.Reflection.TargetInvocationException: The goal of the call created an exception. ---> System.AccessViolationException: Attempt at reading or writing of protected memory. This often points to damaged memory
   at Python.Runtime.Runtime.PyObject_GetIter(IntPtr op)
   at Python.Runtime.PyIter..ctor(PyObject iterable)
   at Python.Runtime.PyObject.GetEnumerator()
   at Siemens.Engineering.Private.Session.ViewToContract(IEnumerable items)
   at Siemens.Engineering.Private.Session.ViewToContract(Object value)
   at Siemens.Engineering.Private.Session.Siemens.Engineering.Private.IObjectSession.SetAttribute[TC](LifetimeContractHandle`1 lifetimeContractHandle, String attributeName, Object attributeValue, String fullName)
   at Siemens.Engineering.Private.InternalObject_Access`2.SetAttribute(String name, Object value)
   --- End of intern exceptionstackpad ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Python.Runtime.MethodBinder.Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, MethodInfo[] methodinfo)
   at Python.Runtime.MethodObject.Invoke(IntPtr target, IntPtr args, IntPtr kw, MethodBase info)
   at Python.Runtime.MethodBinding.tp_call(IntPtr ob, IntPtr args, IntPtr kw)
</code>```

Another small sidenote is that the code that is run is compiled and then executed from a text file.

I have tried multiple things:

```<code>import ctypes
device.DeviceItems[index + 3].SetAttribute("PotentialGroup", ctypes.c_uint64(tia.HW.PotentialGroup.LightBaseUnit))
</code>```

Shows the error above

```<code>import ctypes
PotGroup = ctypes.c_uint64(1)
device.DeviceItems[index + 3].SetAttribute("PotentialGroup", PotGroup)
</code>```

Also shows the error above

```<code>import ctypes
device.DeviceItems[index + 3].SetAttribute("PotentialGroup", 1)
</code>```

Gives an error about wrong datatype

```<code>import ctypes
device.DeviceItems[index + 3].GetAttribute("PotentialGroup")
</code>```

Gives 1 with datatype int

I am running out of ideas on what to try, so please let me know if you guys have any ideas.

Have a good one!
-Rick

Body:
I am making a Hardware/Software-generator for TIA portal 16 in Python 3.7. It is working pretty well but now I am running into a problem:

I want to change the potentialgroups of certain IO-cards through this program but through inspection with Openness Explorer I found out that it is set in a Uint64 variable. Some digging tought me that Python doesn't support this datatype but you can use Ctypes to use it anyway. However when I do this I get an error:

Onverwerkte uitzondering: System.Reflection.TargetInvocationException: The goal of the call created an exception. ---> System.AccessViolationException: Attempt at reading or writing of protected memory. This often points to damaged memory
   at Python.Runtime.Runtime.PyObject_GetIter(IntPtr op)
   at Python.Runtime.PyIter..ctor(PyObject iterable)
   at Python.Runtime.PyObject.GetEnumerator()
   at Siemens.Engineering.Private.Session.ViewToContract(IEnumerable items)
   at Siemens.Engineering.Private.Session.ViewToContract(Object value)
   at Siemens.Engineering.Private.Session.Siemens.Engineering.Private.IObjectSession.SetAttribute[TC](LifetimeContractHandle`1 lifetimeContractHandle, String attributeName, Object attributeValue, String fullName)
   at Siemens.Engineering.Private.InternalObject_Access`2.SetAttribute(String name, Object value)
   --- End of intern exceptionstackpad ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Python.Runtime.MethodBinder.Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, MethodInfo[] methodinfo)
   at Python.Runtime.MethodObject.Invoke(IntPtr target, IntPtr args, IntPtr kw, MethodBase info)
   at Python.Runtime.MethodBinding.tp_call(IntPtr ob, IntPtr args, IntPtr kw)

Another small sidenote is that the code that is run is compiled and then executed from a text file.

I have tried multiple things:

import ctypes
device.DeviceItems[index + 3].SetAttribute("PotentialGroup", ctypes.c_uint64(tia.HW.PotentialGroup.LightBaseUnit))

Shows the error above

import ctypes
PotGroup = ctypes.c_uint64(1)
device.DeviceItems[index + 3].SetAttribute("PotentialGroup", PotGroup)

Also shows the error above

import ctypes
device.DeviceItems[index + 3].SetAttribute("PotentialGroup", 1)

Gives an error about wrong datatype

import ctypes
device.DeviceItems[index + 3].GetAttribute("PotentialGroup")

Gives 1 with datatype int

I am running out of ideas on what to try, so please let me know if you guys have any ideas.

Have a good one!
-Rick