text:
Q: jQuery Form plugin ASP.NET MVC 3 handling PartialView I am writing a ASP.NET MVC page for adding products.  The page will display the form with an Add button and also the list of products.  When the user clicks Add, I want the new product added to the list, and the form reset.  I am trying to do this using the jQuery form plugin and without using Ajax.BeginForm etc.  I have put the list of products into a partial view.
The Product class is as follows:
public class Product
{
    public int Id { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
}

I am using a viewmodel:
public class ProductViewModel
{
    public ProductViewModel()
    {
    }

    public ProductViewModel(AjaxDataEntryContext db)
    {
        Products = db.Products.ToList();
        NewProduct = new Product();
    }
    public List<Product> Products { get; set;}
    public Product NewProduct { get; set;}
}

The controller does this:
public class ProductController : Controller
{
    private AjaxDataEntryContext db = new AjaxDataEntryContext();

    [HttpGet]
    public ViewResult AjaxForm()
    {
        return View(new ProductViewModel(db));
    }

    [HttpPost]
    public ActionResult AjaxForm(ProductViewModel viewModel)
    {
        db.Products.Add(viewModel.NewProduct);
        db.SaveChanges();
        return PartialView("_ProductList", db.Products.ToList());
    }
}

My cshtml is as follows:
@model AjaxDataEntry.ViewModels.ProductViewModel
@{
    ViewBag.Title = "Index";
}
@Html.Partial("_ProductList", Model.Products)
@using (Html.BeginForm("AjaxForm", "Product", null, FormMethod.Post, new { id = "myForm1" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Product</legend>

            @Html.LabelFor(model => model.NewProduct.Description)

            @Html.EditorFor(model => model.NewProduct.Description)
            @Html.ValidationMessageFor(model => model.NewProduct.Description)

            @Html.LabelFor(model => model.NewProduct.Price)

            @Html.EditorFor(model => model.NewProduct.Price)
            @Html.ValidationMessageFor(model => model.NewProduct.Price)

            <input type="submit" value="Create" />

    </fieldset>
}

And finally the _ProductList partial as referenced in the above page (and the Controller):
@model IEnumerable<AjaxDataEntry.Models.Product>

                Description

                Price

        @foreach (var item in Model)
        {

                    @Html.DisplayFor(modelItem => item.Description)

                    @Html.DisplayFor(modelItem => item.Price)

                    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                    @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.Id })

        }

My problem is that when i click Add, the product is added correctly, I see the showRequest message, but when the screen refreshes, all I see is the list i.e. the partial, not the full view.  I also don't see the showResponse message.
Anybody know what I'm doing wrong?

A: ShowResponse is not called because you are submitting the whole page, instead of using Html.BeginForm(..., you should use Ajax.BeginForm(....


text:
Q: how can I open a webpage in a webview from a fragment? I have a fragment with name "FragmentA".
I have another "fragment" that is a WebView, with name "ShowWebFragment".
i want make a link on an imageView in FragmentA with url "adobe.com", that be opened in ShowWeb.
I write this code. where i should enter the url?
ImageView myImageView_Start =(ImageView) View.findViewById(R.id.imageView2);
    myImageView_Start.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View V) {

        FragmentManager fragmentManager = getActivity().getFragmentManager();
        FragmentTransaction t = fragmentManager.beginTransaction();
        Fragment myFragment = new ShowWebFragment();
        t.replace(R.id.frame_container, myFragment);
        t.commit();
    }
});

A: This is the way I had done it in one of my projects:
Fragment Class:
public class EventFragment extends Fragment {

    private Dialog WebDialog;
    private WebView Ticketline;
    private Button btnWeb;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_event, container, false);

        btnWeb = (Button) rootView.findViewById(R.id.btnWeb);
        btnWeb.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                WebDialog = new Dialog(getActivity());
                WebDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                WebDialog.setContentView(R.layout.fragment_cashier);
                WebDialog.setCancelable(true);

                Ticketline = (WebView) WebDialog.findViewById(R.id.ticketline);
                Ticketline.setWebViewClient(new WebConn());
                Ticketline.setScrollbarFadingEnabled(true);
                Ticketline.setHorizontalScrollBarEnabled(false);
                //Ticketline.getSettings().setJavaScriptEnabled(true);
                Ticketline.getSettings().setUserAgentString("Ticketline");
                Ticketline.loadUrl("//url goes here");

                WebDialog.show();

                Button btnDone = (Button) WebDialog.findViewById(R.id.btnDone);
                btnDone.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        WebDialog.dismiss();
                    }
                });
            }
        });
        return rootView;
    }

Layout xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_black" >

    <Button
        android:id="@+id/btnWeb"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="117dp"
        android:background="@drawable/checkout"
        android:text="Buy Tickets"
        android:textColor="#000000" />

</RelativeLayout>

Webview xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/rl_relativeLayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dip"
        android:layout_weight="0.82" >

        <TextView
            android:id="@+id/Title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:gravity="center"
            android:text="Buy your Tickets:" />

        <WebView
            android:id="@+id/ticketline"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_below="@id/Title"
            android:layout_marginTop="5dip" />
    </RelativeLayout>

    <Button
        android:id="@+id/btnDone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Back to App" />

</LinearLayout>

Hope this helps :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Texts and imessage appearing on Mac I want texts and iMesssages from my iPhone to stop appearing on my home Mac. They currently get copied between the 2 devices, I have tried deleting iCloud but this does not stop the messages.

A: In your iPhone: Settings > Messages > Text Message Forwarding: you should see your Mac. Just uncheck it.
In your Mac: Messages > Preferences > Accounts: Just uncheck "Enable this account" or just "Sign out".
Be careful that you can attach iPhone and Mac also with an Apple ID different from the iCloud one, so you have to figure out what is the shared account and sign out from it.


text:
Q: Enumerate lines while printing to to file .CSV PYTHON I have a simple list of lists.  4 lists each with 3 values in each
with open('test2.csv', 'w',) as f2:
 f = csv.writer(f2, delimiter= '\t')
 header = ["SENSOR", "h1", "h2", "h3"]
 f.writerow(header)
 for idx, lists in final_list:

        f.writerow(lists)
        print "IDX:",idx, "LISTS:", lists

errors occur with "for idx, lists in final_list:" and it says:
ValueError: too many values to unpack

A: You were not far :-) you just need :
for idx, lists in enumerate(final_list):
    f.writerow(lists)
    print "IDX:",idx, "LISTS:", lists


text:
Q: How to keep a Karma server running, but not run tests only until I manually tell it to? I would like run Karma without having to shut down the server on every single run. I know that you can turn off single run and have watch running. However, I don't want my tests to re-run on every single save and would like to trigger them manually.
Is it possible to keep a live Karma server but prevent it from running my tests on every single save?

A: Figured it out. I can turn autoWatch in the config file, which I knew how to do before. After that, if you are running tests through Chrome, you can simply refresh the debug page.


text:
Q: Django Streaming Videos from Mobile Devices not Working Properly Django server does not play videos properly on mobile devices. Video seek options are not available. It works fine if we use media files from another domains but files from own server are not working correctly. Forward, rewind and seek options are not accessible
<video id='main-video' controls style="width:100%;">
<source src='{{ video_format.url }}' title='{{ name }}' type='video/mp4' />
</video>

Should I change any Django core settings?
I have built the server using Nginx + Django + Gunicorn.

A: I found out the issue on my own. Django is not good at serving static files. So, I created a location block in Nginx config to server media files too along with the static files. It solved the issue. I hope it will be useful for other people building video sites.
location /media/ {
    root /home/django-site/root-folder;
}


text:
Q: Implementing cancellable syscalls in userspace I'm working on implementing pthread cancellation on Linux without any of the "unpleasant behavior" (some might say bugs) discussed in some of my other recent questions. The Linux/glibc approach to pthread cancellation so far has been to treat it as something that doesn't need kernel support, and that can be handled at the library level purely by enabling asynchronous cancellation before making a syscall, and restoring the previous cancellation state after the syscall returns. This has at least 2 problems, one of them extremely serious:

*

*Cancellation can act after the syscall has returned from kernelspace, but before userspace saves the return value. This results in a resource leak if the syscall allocated a resource, and there is no way to patch over it with cancellation handlers.

*If a signal is handled while the thread is blocked at a cancellable syscall, the entire signal handler runs with asynchronous cancellation enabled. This could be extremely dangerous, since the signal handler may call functions which are async-signal-safe but not async-cancel-safe.

My first idea for fixing the problem was to set a flag that the thread is at a cancellation point, rather than enabling async cancellation, and when this flag is set, have the cancellation signal handler check the saved instruction pointer to see if it points to a syscall instruction (arch-specific). If so, this indicates the syscall was not completed and would be restarted when the signal handler returns, so we can cancel. If not, I assumed the syscall had already returned, and deferred cancellation. However, there is also a race condition - it's possible that the thread had not yet reached the syscall instruction at all, in which case, the syscall could block and never respond to the cancellation. Another small problem is that non-cancellable syscalls performed from a signal handler wrongly became cancellable, if the cancellation point flag was set when the signal handler was entered.
I'm looking at a new approach, and looking for feedback on it. The conditions that must be met:

*

*Any cancellation request received prior to completion of the syscall must be acted upon before the syscall blocks for any significant interval of time, but not while it is pending restart due to interruption by a signal handler.

*Any cancellation request received after completion of the syscall must be deferred to the next cancellation point.

The idea I have in mind requires specialized assembly for the cancellable syscall wrapper. The basic idea would be:

*

*Push the address of the upcoming syscall instruction onto the stack.

*Store the stack pointer in thread-local storage.

*Test a cancellation flag from thread-local storage; jump to cancel routine if it is set.

*Make the syscall.

*Clear the pointer saved in thread-local storage.

The cancel operation would then involve:

*

*Set the cancellation flag in the target thread's thread-local storage.

*Test the pointer in the target thread's thread-local storage; if it's not null, send a cancellation signal to the target thread.

The cancellation signal handler would then:

*

*Check that the saved stack pointer (in the signal context) is equal to the saved pointer in the thread-local storage. If not, then the cancellation point was interrupted by a signal handler and there's nothing to do right now.

*Check that the program counter register (saved in the signal context) is less than or equal to the address saved at the saved stack pointer. If so, this means the syscall is not yet complete, and we execute cancellation.

The only problem I see so far is in step 1 of the signal handler: if it decides not to act, then after the signal handler returns, the thread could be left blocking on the syscall, ignoring the pending cancellation request. For this, I see two potential solutions:

*

*In this case, install a timer to deliver signals to the specific thread, essentially retrying every millisecond or so until we get lucky.

*Raise the cancellation signal again, but return from the cancellation signal handler without unmasking the cancellation signal. It will automatically get unmasked when the interrupted signal handler returns, and then we can try again. This might interfere with behavior of cancellation points within the signal handler, though.

Any thoughts on which approach is best, or if there are other more fundamental flaws I'm missing?

A: Solution 2 feels like less of a hack.  I don't think it would cause the problem you suggest, because cancellable syscalls called within the syscall handler will check the cancellation flag in TLS, which must have already been set if the cancellation signal handler has run and monkeyed with the signal mask anyway.
(It seems like it would be much easier for implementers if every blocking syscall took a sigmask parameter a la pselect()).


text:
Q: Separate Subnet for IoT: Suggestions and Feedback My home network is growing with IoT devices and I think I'd like to put the IoT devices in a separate subnet.  I have a Linux box that I use as my firewall/server and then all of my clients are behind it.  The Linux box is running Debian Buster/10 and has two NIC's: eth0 is WAN/Internet and eth1 is my internal LAN.
From what I have been reading, it seems like the most efficient solution is to use VLAN's (other suggestions are definitely welcome).
I have been reading about VLAN setup and so far everything I'm reading says the VLAN setup requires managed switches.  As a quick experiment, I set up a VLAN in my home and was not able to access nor ping devices on that subnet, so it looks like managed switches are indeed required (but it's entirely possible I did something wrong if it should work with unmanaged switches).
I'm re-thinking my infrastructure.  All of the switches and wireless routers will be handling traffic for multiple LAN subnets in my updated design.  I have multiple Ethernet switches in the house and none of them are managed.  I can certainly replace those, but my question is about the wireless routers.  I am using a mesh setup from Asus and I see nothing in their documentation to indicate managed or unmanaged, so I will assume that means they are unmanaged.  Given the fact that I'd like to set up VLAN's at home and route multiple subnets, which hardware should I be using for my wireless routers, or is that even a concern?  Should I just focus on updating the Ethernet switches to managed?
Thank you for your time and feedback!

A:
everything I'm reading says the VLAN setup requires managed switches

Yes, but that's not the only thing.
"Managed" simply means it has a configuration interface of some sort, "unmanaged" does not. So unmanaged switches can't do VLAN setup simply because there's no way to configure it. If the switch had a settings screen (or even a serial port), that would by definition make it a managed one.
However, the opposite isn't always true – "managed" does not imply having VLAN support. These days most managed switches support 802.1Q VLAN tagging, but that is not a 100% guarantee. (Old switches from early 2000s would often omit this feature; they'd still be "managed" because you could configure other things...just not VLANs.)

As a quick experiment, I set up a VLAN in my home and was not able to access nor ping devices on that subnet, so it looks like managed switches are indeed required (but it's entirely possible I did something wrong if it should work with unmanaged switches).

There are two things that fully make a switch VLAN-capable:

*

*Ability to carry VLAN-tagged traffic as-is. Most switches, even unmanaged ones, can do this just fine (the only requirement is slightly higher MTU limit).

*Ability to add/remove VLAN tags, or specify which ports can receive which VLANs. This is something you configure, so by definition it requires a managed device. (But not necessarily a switch: many routers can tag/untag VLANs too, as can Linux/BSD systems.)
So if you have two devices with VLAN configuration (whether it's two managed switches, or whether it's a router and a WiFi AP), it shouldn't matter if you connect them directly or if you connect them through a reasonably recent unmanaged switch: all VLAN tags will just go through as-is.
Again, what unmanaged switches cannot do is add/remove VLAN tags, or specify which ports can receive which VLANs. All ports are equivalent on an unmanaged switch. Therefore managed switches are required at any spot where different ports need different VLAN rights.
But in practice, if all your IoT things are wireless, and the only wired devices are a) LAN devices and b) multi-SSID (VLAN-capable) Wi-Fi access points, then you can get away with only unmanaged switches most of the time. That's because the Wi-Fi access points themselves will enforce VLAN tags (they have to), and PCs will just ignore the tagged packets.
(Mostly. Windows PCs with Intel Ethernet cards will treat tagged packets as if they were untagged. This causes problems when trying to deploy IPv6 on a tagged VLAN.)

but my question is about the wireless routers. I am using a mesh setup from Asus and I see nothing in their documentation to indicate managed or unmanaged, so I will assume that means they are unmanaged

They're probably just access points; not routers. (The name "wireless router" originally meant a wired router that also had Wi-Fi access-point capabilities.)
They're managed devices, because they provide some means to change the Wi-Fi settings (e.g. change the SSID or PSK). But once again, "managed" does not imply "VLAN-capable", and from a quick search it seems that ASUS AiMesh devices do not support VLANs at all. (You could still put them all in a single VLAN and they'd work the same as always... but you cannot have multiple SSIDs with different VLANs.)

So in conclusion, if you want separation for Wi-Fi PCs and Wi-Fi IoT stuff, you will at minimum need either:
a) one set of Wi-Fi access points with VLAN tagging and multi-SSID capabilities (which will enforce the separation themselves), or
b) two sets of "normal" (non-VLAN) Wi-Fi access points, one for each SSID, and a
managed VLAN-capable switch to enforce the VLAN separation everywhere the Wi-Fi APs are connected.
Option a) would be cleaner, IMHO.


text:
Q: how to get values From a scanned ECG image? In my project, I have to digitize an ECG image taken with a normal camera (jpeg). For example, I have the following camera captured image:
i'm using c# to implement this

Then i convert this image to greyscale image and then apply threshold to seperate the wave from the grid.
Finally remove unnecessary things from the image  and final output is like this

now i want to fetch the values which are mention on bellow image using pixel count between those segments.what is the best way to do that?

main things i want to get are height of QR wave and length between two Q waves.(pixel values)
how to implement bellow code to get those values and store them in arrays
public void black(Bitmap bmp)
{
            Color[,] results = new Color[bmp.Width, bmp.Height];
            for (int i = 0; i < bmp.Height; i++)
            {
                for (int j = 0; j < bmp.Width; j++)
                {
                    Color col = bmp.GetPixel(j, i);
                    if (col.R == 0)
                    {
                        results[j, i] = bmp.GetPixel(j, i);

                    }
           }
      }
}

A: For a theoretical (i.e. no source code) overview of the problem, read Section III of Syeda-Mahmood, Beymer, and Wang "Shaped-based Matching of ECG Recordings.
Basically, your black & white image is an array of datapoints: the x axis is simply the width of the image in pixels, and the y axis is obtained by averaging the y-position of the black pixels at each x-position (not needed if the black line is only one pixel high).
To make the data more manageable, you can down-sample by selecting every nth x-position from the image. You probably want to stick with a standard ECG sampling rate to ensure that you do not miss important data; modern ECG hardware often samples at 1000Hz, while the data in MIT's QRS database on Physionet is at 250Hz or 360Hz. Using one of these rates would mean reading 1000, 250, or 360 pixels for every second of data (25mm) in the scanned image.


text:
Q: VPN Wireguard - handshake ok but no internet and LAN access I have a problem with wireguard setup. After setup up I can connect to my device. Handshake is ok but I cannot accesss internet and lan.
Device: raspberry pi 4b 8gb ram
OS: Ubuntu server ARM x64 20.04 LTS
My wg0.conf file contents
[Interface]
Address = 10.0.0.1/24
ListenPort = 51820
PrivateKey = (hidden)
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

[Peer]
PublicKey = oqL4CC4Y572iOvVtpDbASiajjgJPAjJhDODffMezcxA=
PresharedKey = (hidden)
AllowedIPs = 10.0.0.2/32

[Peer]
PublicKey = a6z779DYdezo/TMLbC7AJuenHpseaIqUr/gRx97D4Rw=
PresharedKey = (hidden)
AllowedIPs = 10.0.0.3/32

[Peer]
PublicKey = Fe4Nv3Ef8T5bc1p7sDCfNkLO/pTv5cIgHMJ0XCMa8Gg=
PresharedKey = (hidden)
AllowedIPs = 10.0.0.4/32

[Peer]
PublicKey = IdKkIYDctdHYwMx+ULlgntVllaBkIP8G8eIRxEQ9QWQ=
PresharedKey = (hidden)
AllowedIPs = 10.0.0.5/32

[Peer]
PublicKey = qdpWjwlnUuwVxqKnCfta+W/B4XyxZT868aOPtmSOek8=
PresharedKey = (hidden)
AllowedIPs = 10.0.0.6/32

First client config file:
  [Interface]
Address = 10.0.0.2/24
ListenPort = 51820
PrivateKey = OPgCJeBSPevFR+oleTbDqVCNyn+7G0mhSA0QRHqnklg=

[Peer]
PublicKey = W6B77KxgOpshDLX7gc0Jz10Z/WfUl4zVCLrIL/luoR4=
PresharedKey = tI3YFvK195G257yQBAYx+bS9S1j2qkZZOgsdoN3/yPI=
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = {my_external_ip_address}:51820

My router setup explanation.
I have a UPC Connect Box device which has IP: 192.168.0.1. UPC Connect Box is my gateway.
To this UPC Connect Box I have connected my other router. IP address: 192.168.1.1. I can access other subnets from all my routers. I can also access all computers inside my lan in any subnet. I can also access everything on my net and subnet from the device which has wireguard installed but it does not work when I am connected as a client.
Port forwarding is setup correctly on my upc connect box with port 51820 to my other router 192.168.1.1 and from this device to my raspberry pi ubuntu device with internal ip: 192.168.1.12.
What I did ?
Allowed ipv4 port forwading using:
sudo sysctl -w net.ipv4.ip_forward=1

Also did:
sudo ufw allow 51820/tcp
sudo ufw allow 51820/udp
sudo ufw allow in on wg0 to any
sudo ufw allow out on wg0 to any

ufw status:
Status: active

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       Anywhere
51820                      ALLOW       Anywhere
51820/tcp                  ALLOW       Anywhere
51820/udp                  ALLOW       Anywhere
OpenSSH                    ALLOW       Anywhere
51821/udp                  ALLOW       Anywhere
51821/tcp                  ALLOW       Anywhere
446/tcp                    ALLOW       Anywhere
993/tcp                    ALLOW       Anywhere
8080/tcp                   ALLOW       Anywhere
443/tcp                    ALLOW       Anywhere
5900/tcp                   ALLOW       Anywhere
Anywhere on wg0            ALLOW       Anywhere
22/tcp (v6)                ALLOW       Anywhere (v6)
51820 (v6)                 ALLOW       Anywhere (v6)
51820/tcp (v6)             ALLOW       Anywhere (v6)
51820/udp (v6)             ALLOW       Anywhere (v6)
OpenSSH (v6)               ALLOW       Anywhere (v6)
51821/udp (v6)             ALLOW       Anywhere (v6)
51821/tcp (v6)             ALLOW       Anywhere (v6)
446/tcp (v6)               ALLOW       Anywhere (v6)
993/tcp (v6)               ALLOW       Anywhere (v6)
8080/tcp (v6)              ALLOW       Anywhere (v6)
443/tcp (v6)               ALLOW       Anywhere (v6)
5900/tcp (v6)              ALLOW       Anywhere (v6)
Anywhere (v6) on wg0       ALLOW       Anywhere (v6)

22/tcp                     ALLOW OUT   Anywhere
Anywhere                   ALLOW OUT   Anywhere on wg0
22/tcp (v6)                ALLOW OUT   Anywhere (v6)
Anywhere (v6)              ALLOW OUT   Anywhere (v6) on wg0

I can connect from my iOS, Android or macOS device but no internet and lan access. I cannot ping anything after successfull connection. Cannot ping even devices on subnets and current net. Cannot ping anything external for example: 8.8.8.8 or 1.1.1.1
Everything seems fine - handshake is ok. Please guide me where is the mistake.
I need LAN and internet accesss through wireguard VPN.

A: SOLVED!
Seems that this not correct. Replacing "%i" with "wg0" solved the problem.
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

Should be:
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

LAN access works. Internet access works !
THanks to this guy from this video:
https://www.youtube.com/watch?v=bVKNSf1p1d0

A: Make sure you create the following file using a text editor too:
vim /etc/sysctl.d/10-wireguard.conf
Add the following text:
`
net.ipv4.ip_forward=1

net.ipv6.conf.all.forwarding=1

Reload all changes and turn on NAT routing:
sysctl -p /etc/sysctl.d/10-wireguard.conf

systemctl restart wg-quick@wg0.service

`


text:
Q: Detecting when TinyMCE is "ready" I'm trying to add some custom JS functionality to the default "post" editing screen that depends upon TinyMCE being instantiated and ready to rock.  If I try to make the changes before TinyMCE is set up, I (obviously) receive JS errors.
Without needing to modify any core files, and ideally using JS/jQuery events alone (i.e. not PHP/WP hooks/filters or polling with JS' setInterval()), is there a way to detect when TinyMCE is ready?

A: Unless your WP version is truly ancient, you should be able to use the tinymce-editor-init event triggered on editor init by "wp-includes/js/tinymce/plugins/wordpress/plugin.js", eg (assuming your script is loading after jQuery):
jQuery( document ).on( 'tinymce-editor-init', function( event, editor ) {
    // Blah.
});

A: I have not tested this, but it should work:
is_tinyMCE_active = false;
if ( typeof( tinyMCE) != "undefined" ) {
    if ( tinyMCE.activeEditor == null || tinyMCE.activeEditor.isHidden() != false ) {
        is_tinyMCE_active = true;
    }
}


text:
Q: How to convert curl call with "-i --upload-file" into java Unirest or any other http request? The example below uses cURL to upload image file included as a binary file.
curl -i --upload-file /path/to/image.png --header "Authorization: Token" 'https://url....'

It works fine. I need to make this request from my Java application.
I have tried next code
URL image_url = Thread.currentThread().getContextClassLoader().getResource("jobs_image.jpg");
String path = image_url.getFile();
HttpResponse<String> response = Unirest.post(uploadUrl)
  .header("cache-control", "no-cache")
  .header("X-Restli-Protocol-Version", "2.0.0")
  .header("Authorization", "Bearer " + token + "")
  .field("file", new File(path))
  .asString();

However, it returns status 400 Bad Request.
Is there any way to call such request from Java?
This is a request from LinkedIn v2 API:
https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin?context=linkedin/consumer/context#upload-image-binary-file

A: After several hours of banging my head against the wall, I finally figured out how to convert the curl call into a RestClient one (I'm using Ruby on Rails).
I think the problem you're having is that you have to pass the MIME type as the Content-Type in the request headers.
I'm using MiniMagick to figure out the MIME type of the image I'm uploading to LinkedIn. MiniMagick can also give you the binary string of the image that LinkedIn requires, so it's a win-win situation.
This is the call that finally worked:
file = MiniMagick::Image.open(FILE_PATH)
RestClient.post(UPLOAD_URL, file.to_blob, { 'Authorization': 'Bearer TOKEN', 'Content-Type': file.mime_type })

A: Below method will upload the image to linkedIn
Reference : https://learn.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/vector-asset-api#upload-the-image
private void uploadMedia(String uploadUrl,String accessToken) throws IOException {
           RestTemplate restTemplate = new RestTemplate();
           HttpHeaders headers = new HttpHeaders();
           headers.add("Authorization","Bearer "+accessToken);
           byte[] fileContents = Files.readAllBytes(new
           File("path_to_local_file").toPath());
           HttpEntity<byte[]> entity = new HttpEntity<>(fileContents, headers);
           restTemplate.exchange(uploadUrl,HttpMethod.PUT, entity, String.class);
      }

A: I think the curl command
curl -i --upload-file /path/to/image.png --header "Authorization: Token" 'https://url....'
uses PUT while your Java client uses POST
Source: The man page of curl.
       -T, --upload-file <file>
              This  transfers  the  specified local file to the remote URL. If
              there is no file part in the specified URL, Curl will append the
              local file name. NOTE that you must use a trailing / on the last
              directory to really prove to Curl that there is no file name  or
              curl will think that your last directory name is the remote file
              name to use. That will most likely cause the upload operation to
              fail. If this is used on an HTTP(S) server, the PUT command will
              be used.

Not sure if this is the actual problem though. Your API doc link actually specifies POST.


text:
Q: how to add a 3rd party library to magento? The library doesn't need to integrate with magento, it's mostly a wrapper that communicates with an API.
I would like to be able to use this library and make these API calls from within a controller or model.
Where can I put the library? How do I add them to the autoloader?

A: As a solution that works perfectly:
you can extend the varien_event_observer, create your own autoloader function and and by using the controller_front_init_before event you push this autoloader in front of the __autoload stack.
this example of integrating solarium and symphony event dispatcher can explain it :
class JeroenVermeulen_Solarium_Model_Observer_Autoloader extends Varien_Event_Observer {

    /**
     * This an observer function for the event 'controller_front_init_before'.
     * It prepends our autoloader, so we can load the extra libraries.
     *
     * @param Varien_Event_Observer $event
     */
    public function controllerFrontInitBefore( $event ) {
        spl_autoload_register( array($this, 'load'), true, true );
    }

    /**
     * This function can autoloads classes starting with:
     * - Solarium
     * - Symfony\Component\EventDispatcher
     *
     * @param string $class
     */
    public static function load( $class )
    {
        if ( preg_match( '#^(Solarium|Symfony\\\\Component\\\\EventDispatcher)\b#', $class ) ) {
            $phpFile = Mage::getBaseDir('lib') . '/' . str_replace( '\\', '/', $class ) . '.php';
            require_once( $phpFile );
        }
    }

}

and surely your libraries shoud be in the lib pool !
 this solution is provided by @Jeroen Vermeulen, and i thank him :)

A: Look into /lib folder in your website root directory. From Magento Base Directories:

Magento's library folder is where
  non-module based Magento code lives.
  This include a large amount of the
  system code which allows Magento to
  run, as well as a number of third
  party libraries (including the Zend
  Framework). The library is also the
  last code pool Magento will search
  when attempting to autoload a file.

So, in other words, if your library supports zend file naming convention - library classes will be found and loaded by magento autoloader. Otherwise you can get path of your /lib directory with Mage::getBaseDir('lib') and write something like
require_once(Mage::getBaseDir('lib') . '/EZComponents/Base/src/base.php');


text:
Q: Showing $\int_{0}^{\infty} \frac{\sin(x^{3})}{x}\,dx = \frac{\pi}{6}$ $$\int_{0}^{\infty} \frac{\sin(x^{3})}{x}\,dx = \frac{\pi}{6}$$
How to derive the above equality?
Looking for non complex analysis methods.

A: Hint:
$$\int\frac{\sin(x^3)}{x}dx=\int\frac{\sin(t^{3\alpha})}{t^\alpha}d(t^\alpha).$$

$$\int\frac{\sin(x^3)}{x}dx=\int\frac{\sin(t^{3\alpha})}{t^\alpha}d(t^\alpha)=\alpha\int\frac{\sin(t^{3\alpha})}tdt.$$


text:
Q: Property of Derivative in a local field Let $K$ be a charateristic $p$ global field. For each place $P$ we let $K_P$ to be the completion at $P$ (which is a local field) and let $t_P$ be their prime.
Let $t$ be a separating element of $K$ (which means $K/F(t)$ is a separable extension where $F$ is the constant field over $K$).
Then Artin-Tate claims that $\frac{dt}{dt_P}$ is almost always a local unit. ie for almost all $P$ $v_P(\frac{dt}{dt_P})=0$.
It is clear that $v_P(t)=0$ for almost all $t$ so I just need to verify that for each expansion of $t$ at $k_P$, say
$$t=\sum_{i\geq0}a_i t_P^{i},$$ $a_1$ is almost always non zero.
But I have absolutely no clue how to prove it.
The book refers to chapter 17-4 of Algebraic numbers and algebraic functions but I couldn't get anything out of it.
Any help would be great!


text:
Q: TP-Link TL-WN823N v3 wifi dongle not detected I'm trying to install drivers for TP-Link TL-WN823N v3 wifi dongle on Ubuntu 16.04, without success.
At present it's not being detected at all.
Edit: It seems to be Bus 002 Device 005: ID 2357:0109
lsusb
Bus 002 Device 005: ID 2357:0109
Bus 002 Device 003: ID 148f:2573 Ralink Technology, Corp. RT2501/RT2573 Wireless Adapter
Bus 002 Device 002: ID 0644:0200 TEAC Corp. All-In-One Multi-Card Reader CA200/B/S
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 007 Device 002: ID 046d:c52b Logitech, Inc. Unifying Receiver
Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 004: ID 1058:25a2 Western Digital Technologies, Inc.
Bus 001 Device 003: ID 1058:25a1 Western Digital Technologies, Inc.
Bus 001 Device 002: ID 0bc2:2321 Seagate RSS LLC Expansion Portable
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub


text:
Q: Why is it "bad" to use cin for numeric variables? My current professor states on his syllabus:
"Never use cin >> to read directly into a numeric variable, like int or double or float. Read as a string (C or C++) and convert to a number using atoi or atof."
Is there a reason for this? At first I thought it is to avoid fail flags but if you just add input validation code isn't it fine to "cin >> myInt"?
Using his method, if they entered "4a5" and I did atoi wouldn't it still throw an error?
Thanks~

A: In general, there is nothing wrong with it at all. This advice would seem to be wrong.
In fact, by relying solely on stoi and friends, you lose any ability to control the conversion process. You might want to use these in some very domain-specific cases where you want to extract a specific number of characters and then attempt to convert them, but that's down to business logic.
Certainly, relying on antiquated code like atoi is even worse, what with its undefined behaviour on encountering many failure cases.

A: It is not bad, but it is unsafe: if the stream gets invalid data it will end up in a "fail" state. This means the programmer needs to check if the stream is still working, then process the data. If not, everything after the fail is lost when resetting the stream.
Getline is better for these situations because it doesn't work the same way, it will just accept all input as a string.

A: Although this is valid code...
int num;
cin >> num;

... problems will arise if the user inputs a character that can't be interpreted as an int.
That's why it's safer to use string variables with cin and do the data extraction programmatically.


text:
Q: Replacing HTML Document error We have a html document which we're using in SF Community and I'm trying to replace it. But I get the following error:

Error: The branding document folder where the logo image is stored is
  Private. You must change it to Public.

I just don't get what's that mean, the doc itself is in public folder, images referenced by the html is also in a public folder. I'm not sure where to look next. Searching for this error didn't help.

A: This is because you are already using the HTML in the branding header of your community. So it is locked out. Remove it first from the community and the do the replacement and add it back to the com.. At least that worked for me.

A: One additional suggestion if the answer does not work for you (as was my case)

*

*If the file you used under Community Management | Administration | Branding wasn't originally in the Document folder Communities Shared Document Folder then..

*Add the file to Communities Shared Document Folder and remove it from any other folder (so you don't have duplicates to worry about in the future)

*Then you can replace and alter as needed over time


text:
Q: Convert This String to return Double public static String formulaCalcularRenda = "(Loja.getRendaFixa()*(1+super.getArea()/100)+super.getReceita()/100)";

@Override
    public double calcularRenda(){
        return (Loja.getRendaFixa()*(1+super.getArea()/100)+super.getReceita()/100);
    }

My main objective is to reuse the code, while being the formula altered by order of the user itself. I've tried something similar before, but I was uncapable to succeed, because the string has letters.
@Override
        public double calcularRenda(){
            return Double.parseDouble(Loja.formulaCalcularRenda);
        }

Can someone help me?

A: As others are commenting, this is not an easy or generally wise thing to do.  But if you are committed to this task, a scripting language is a much better choice for the expression evaluation.  Scripting language support is built into Java and is relatively easy to use.
The Java javascript programmer guide would be a good place to start.  It has examples that you should be able to adapt to your needs.

A: If you think about it, it doen't make too much sense for the user to write the code. So, in your opinion, what would be the best way for me, not to repeat the same code, over and over again?


text: Q: Is it possible to render several DEMs simulatneously with QGIS2threejs? I'd like to know if anyone knows a way of including several DEMs in one representation using QGIS2threejs. If I have two separate DEMs, each representing one modeled surface, both from the same location (so, one is above the other), how can I get a visualisation where both surfaces are included, one "floating" above the other?


text:
Q: npm not installing properly when brew install node Im getting the following error, which I beleive is a permission error when trying to do brew install node. npm is not being installed properly. Any ideas?
⚙  /usr/local/bin
 ⚙ /usr/local/bin   master  brew install node
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/node-0.10.33_1
Already downloaded: /Library/Caches/Homebrew/node-0.10.33_1.yosemite.bottle.10.tar.gz
==> Pouring node-0.10.33_1.yosemite.bottle.10.tar.gz
==> Caveats
If you update npm itself, do NOT use the npm update command.
The upstream-recommended way to update npm is:
  npm install -g npm@latest
==> make uninstall
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     /usr/local/Cellar/node/0.10.33_1/libexec/npm/npm-debug.log
make: *** [uninstall] Error 3
Warning: The post-install step did not complete successfully
You can try again using `brew postinstall node`
==> Summary
  /usr/local/Cellar/node/0.10.33_1: 2081 files, 21M
 ✘ /usr/local/bin   master  brew postinstall node
==> make uninstall
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     /usr/local/Cellar/node/0.10.33_1/libexec/npm/npm-debug.log
make: *** [uninstall] Error 3

A: As the error says: npm ERR! Please try running this command again as root/Administrator.
Try: $sudo brew install node


text:
Q: Visual Studio, Asp.net connection string In the Visual Studio, it will generate datasource like this :
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
        ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString1 %>"
        SelectCommand="SELECT top 10 * FROM [Address]">
    </asp:SqlDataSource>

when run it, it will say 'invalid object'. then I found it out, it should be
[AdventureWorks].[Person].[Address]

The connection string is
 <connectionStrings>
        <add name="AdventureWorksConnectionString1" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>

Then how to config in VS to use this format ?

A: The default schema for the logged in database user is probably [dbo], not [Person]. You need to qualify the schema name in such a case.
Your select command should be:
SELECT top 10 * FROM [Person].[Address]


text:
Q: Weighted randomness based on current values (Not sure how else to explain it) Need some help with some code (Java)
I have a script which runs every few mins
This script creates and deletes objects
For the sake of this example I want to have an average of 10 objects at any time
But a random probability of it creating and deleting objects based on how far it is from that 10 goal with hard limits, eg +- 3
I have gotten it to create objects till it reaches 7, and then delete once it goes past 13
But I cant figure out how to do the randomness between
If there is say 8 objects then it would have a higher probability of creating rather than deleting, if there are 10 then its a 50/50 split
and if there is 12 then its more likely to delete then create
and im not asking for code, im happy to figure that out myself
I just need a push in the right direction
Edit for update with what I currently have, I dont have the full code as there is alot of other things going on, but this is the part i need help with
This runs every min
int limit = F_Config.get().getInt("Limit");
int avg = F_Config.get().getInt("Average");
int current = P_Player.ReturnList().size();
int min = avg - limit;
int max = avg + limit;

//below min
if(current < min) {
    Main.sendConsole("Min");
    P_Player.LoginPlayer();
}

//above Max
else if(current > max) {
    Main.sendConsole("Max");
    P_Player.LogoutPlayer();
}

//Between min and Max
else{
    //Stuff here
}

A: First you have to clarify the algorithm, after how to implement (java) is something else.
There are 2 operations : [add] and [delete] and you have to define based on some criteria the probability.
Say:
[Objects,AddP,DeleteP]

*

*[0,1,0] -> only option is to add

*[1 up to n, a, 1-a] , eg: [1-9, 0.75, 0.25]

*[n+1, m, b, 1-b] , eg: [10-15. 0.3, 0.7]

*[m+1, 0, 1] , eg: [16, 0, 1] -> only option is to delete

On [2] and [3] just generate a random number and compare with a,b probability and choose an operation.
Eg: [2] random = 0.60<0.75 => add, etc
Note: 0 < a < 1 (same with b)
import java.util.ArrayList;
import java.util.List;

public class Prob
{
    List<PSet> l = new ArrayList<PSet>();
    List<MyObj> obj = new ArrayList<MyObj>();
    @SuppressWarnings("unchecked")
    public static void main(String args[])
    {
        Prob p = new Prob();
        PSet ps1 = p.new PSet(0,0,1,0);
        PSet ps2 = p.new PSet(1,3,0.8,0.2);
        PSet ps3 = p.new PSet(4,5,0.3,0.7);
        PSet ps4 = p.new PSet(6,6,0,1);
        p.l.add(ps1);
        p.l.add(ps2);
        p.l.add(ps3);
        p.l.add(ps4);

        //loop 20 times
        for(int i=0;i<20;i++)
        {
            int counter = p.obj.size();
            for(int j=0;j<p.l.size();j++)
            {
                PSet ps = p.l.get(j);
                if(counter == 0 && counter == ps.start)
                {
                    System.out.println(i+"_only_add, counter="+counter);
                    p.obj.add(p.new MyObj(String.valueOf(i)));

                }
                else if(counter > 0 && counter == ps.start && counter == ps.end)
                {
                    System.out.println(i+"_only_del, counter="+counter);
                    p.obj.remove(0);
                }

                else if(counter>=ps.start && counter<=ps.end)
                {
                    double rand = Math.random();
                    if(rand<ps.pAdd)
                    {
                        System.out.println(i+"_add, counter="+counter);
                        p.obj.add(p.new MyObj(String.valueOf(i)));
                    }
                    else
                    {
                        System.out.println(i+"_del, counter="+counter);
                        p.obj.remove(0);
                    }
                }

            }
        }
    }
    class MyObj
    {
        String name;
        MyObj(String name)
        {
            this.name = name;
        }
    }
    class PSet
    {
        public int getStart() {
            return start;
        }
        public int getEnd() {
            return end;
        }
        public double getpAdd() {
            return pAdd;
        }
        public double getpDel() {
            return pDel;
        }
        int start;
        int end;
        double pAdd;
        double pDel;
        PSet(int start, int end, double pAdd, double pDel)
        {
            this.start = start;
            this.end = end;
            this.pAdd = pAdd;
            this.pDel = pDel;
        }
    }
}

Output:
0_only_add, counter=0
1_add, counter=1
2_add, counter=2
3_add, counter=3
4_del, counter=4
5_add, counter=3
6_del, counter=4
7_add, counter=3
8_del, counter=4
9_add, counter=3
10_del, counter=4
11_add, counter=3
12_del, counter=4
13_add, counter=3
14_add, counter=4
15_add, counter=5
16_only_del, counter=6
17_del, counter=5
18_del, counter=4
19_del, counter=3


text:
Q: In Python with sqlite is it necessary to close a cursor? Here is the scenario.  In your function you're executing statements using a cursor, but one of them fails and an exception is thrown.  Your program exits out of the function before closing the cursor it was working with.  Will the cursor float around taking up space?  Do I have to close the cursor?
Additionally, the Python documentation has an example of cursor use and says: "We can also close the cursor if we are done with it."  The keyword being "can," not "must."  What do they mean precisely by this?

A: Interestingly, the Python 3.0 doc says "We can also close the cursor if we are done with it", while the Python 2.7 and 3.6 doc says "We can also close the connection if we are done with it".
The Python 2.7 and 3.0-3.4 docs don't describe the cursor .close() method. But the Python 3.5 and 3.6 docs describe the cursor .close() method:

Close the cursor now (rather than whenever __del__ is called).
The cursor will be unusable from this point forward; a ProgrammingError exception will be raised if any operation is attempted with the cursor.

A: This code will automatically close the Cursor. It will also automatically close and commit the Connection.
import sqlite3
import contextlib

def execute_statement(statement):
    with contextlib.closing(sqlite3.connect(path_to_file)) as conn: # auto-closes
        with conn: # auto-commits
            with contextlib.closing(conn.cursor()) as cursor: # auto-closes
                cursor.execute(statement)

A: I haven't seen any effect for the sqlite3.Cursor.close() operation yet.
After closing, you can still call fetch(all|one|many) which will return the remaining results from the previous execute statement. Even running Cursor.execute() still works ...

A: It's probably a good idea (although it might not matter much with sqlite, don't know there, but it'll make your code more portable).  Further, with recent Python (2.5+), it's easy:
from __future__ import with_statement
from contextlib import closing

with closing(db.cursor()) as cursor:
    # do some stuff

A: Looking at the code snippet and ideas given by stackoverflowuser2010 and Peer, gracefully handling cursors is easier using Python contextmanager.
from contextlib import contextmanager

@contextmanager
def OpenCursor(conn):
    cursor = conn.cursor()
    try:
        yield (cursor)
    except Exception as e:
        cursor.close()
        raise e
    else:
        cursor.close()

Usage without OpenCursor:
def get(conn, key, default=None):
    cursor = conn.cursor()
    cursor.execute(f'SELECT value FROM table WHERE key=?', (key,))
    row = cursor.fetchone()
    if row:
        return (True)
    else:
        return (default)

Usage with OpenCursor as context manager:
def get(conn, key, default=None):
    with OpenCursor(conn) as cursor:
        cursor.execute(f'SELECT value FROM table WHERE key=?', (key,))
        row = cursor.fetchone()
        if row:
            return (True)
        else:
            return (default)

A: You're not obliged to call close() on the cursor; it can be garbage collected like any other object.
But even if waiting for garbage collection sounds OK, I think it would be good style still to ensure that a resource such as a database cursor gets closed whether or not there is an exception.

A: All,
I was experiencing a gradual memory leak with my code (Python 3.8) using sqlite3.  I traced the likely cause to my database classes.  As it turns out, I would open and use a cursor but never closed it. The database remained open during the life of the program (a Windows Service) and would be closed on exit.
Once I began closing the cursors in all of my db operations which used them, my memory leak stopped, and the memory footprint became steady.
I would therefore suggest that you take the time to close your cursors.  It makes the code more consistent and apparently, helps control memory consumed.
Here's an example of how I close the cursor:
def write_to_db(self, cache_item:CacheEntry):
        '''Write a single cache entry to the database'''
        crsr = self._db_con.cursor()

        # Load some data elements
        fax_line_path = cache_item._dir_part
        phone_line = cache_item._phone_line
        sub_folder = cache_item._subfolder
        fname = cache_item._fname
        work_done = cache_item.get_workdone()

        try:
            crsr.execute(FilenameCacheDB.INSERT_CACHE,
                             (fax_line_path,
                              phone_line,
                              sub_folder,
                              fname,
                              work_done))

        except Exception as e:
            LOG.warning(f"Could not write {cache_item} to db because {e}")
            raise e

        finally:
            #
            # I was *not* closing the cursor prior
            #
            crsr.close()
            self._db_con.commit()

A: Yes, we should close our cursor. I once encountered an error when I used my cursor to configure my connection object: 'PRAGMA synchronous=off' and 'PRAGMA journal_mode=off' for faster insertion. Once I closed the cursor, the error went away. I forgot what type of error I encountered.

A: First, what is a python sqlite3.Cursor? The
code
shows it is essentially a holder for a sqlite3_stmt structure, a prepared
statement handle which is passed to
sqlite3_step to iterate through
result rows.
As far as I can tell, there's no benefit to creating your own cursor object
with conn.cursor() over just using the one automatically created for you
and returned by
conn.execute().
Skip conn.cursor() and save yourself the extra line of code each time.
(This is sqlite-specific advice; there may be reasons to create your own
cursors with other DB-API drivers for other database systems, I don't
know.)
What does cursor.close() do?
static PyObject *
pysqlite_cursor_close_impl(pysqlite_Cursor *self)
{
    ⋮
    if (self->statement) {
    (void)stmt_reset(self->statement);
    Py_CLEAR(self->statement);
    ⋮
}

The sqlite
docs
give a short description of sqlite3_reset, which is what stmt_reset calls:

6. Binding Parameters and Reusing Prepared Statements
… SQLite allows the same prepared statement to be evaluated multiple
times. This is accomplished using the following routines:

*

*sqlite3_reset()

*sqlite3_bind()
After a prepared statement has been evaluated by one or more calls to
sqlite3_step(), it can be reset in order to be evaluated again by a call
to sqlite3_reset(). Think of sqlite3_reset() as rewinding the
prepared statement program back to the beginning.

Closing a cursor causes Python to tell the underlying sqlite library to
discard the associated result set. But Python still keeps the
sqlite3_stmt structure around, because Python internally maintains a
cache of prepared statements.
Code like the following is generally fine on CPython:
for row in conn.execute("SELECT …"):
    do_stuff_with(r)

This is because:

*

*When iteration gets to the end of the result set, python will
automatically call stmt_reset to discard the result
set.
This happens with both standard python iteration protocols like for … in …, and the
sqlite3.Cursor.fetch* methods.

*If the loop exits early, e.g., because an exception was raised,
CPython's reference-counting will trigger finalization of the anonymous cursor
object, again calling stmt_reset. Other python implementations may differ.
Given the above, while it is unlikely that you will ever run into a memory leak by not
closing your cursors, it is definitely possible if you have cursors that
are both:

*

*only partially-iterated, and

*kept in scope for long periods of time.

Thus for portability and explicitness you may want to write:
from contextlib import closing

with closing(conn.execute("SELECT …")) as cursor:
    for row in cursor:
        …


text:
Q: How to list all the Node.js modules I have linked with npm I am looking for a command that will list the names of global modules that I have npm link'd to local copies, also listing the local path.
In fact, a list of all globally installed modules would be even better, with the npm link'd ones flagged somehow.

A: Did you try just listing the node_modules directory contents (e.g., ls -l node_modules | grep ^l)? They're normal symbolic links.
If you really need to find all symbolic links, you could try something like find / -type d -name "node_modules" 2>/dev/null | xargs -I{} find {} -type l -maxdepth 1 | xargs ls -l.

A: I made a Node.js module, symlinked, that uses fs to check for symbolic links made by npm link or otherwise.
var symlinked = require("symlinked")

console.log(symlinked.names())

A: I found this question after I also wrote my own tool, and here it is for completeness: npm-list-linked.
It will recursively follow all linked packages down in the hierarchy as well. At my work we sometimes may have npm link 2-3 levels deep and this way you can see exactly which are local and which ones are not. It avoids surprises.
npm-list-linked

Output:
Linked packages in /home/user/projects/some-project/
    @prefix/package 0.2.7
        other-package 0.1.2

A: Use
find `npm root -g` -maxdepth 2 -type l

to show global links, including namespaced packages.
Andrew's answer works some of the time:
npm ls -g --depth=0 --link=true

But it blew up on peer dependency errors for me on some occasions.

A: To list all globally linked modules, this works (documentation https://docs.npmjs.com/cli/ls):
npm ls -g --depth=0 --link=true

I had to update the version of npm on my machine first, though:
npm install npm@latest -g

A: A better alternative to parsing ls is to use find like this:
find . -type l

You can use -maxdepth 1 to only process the first directory level:
find . -maxdepth 1 -type l

You can use -ls for additional information.
For instance, for finding Node.js modules that are npm linked:
find node_modules -maxdepth 1 -type l -ls

Here's an article why parsing ls is not the best idea.

A: These commands are simpler as of npm 7:

*

*Global modules: npm ls --link --global

*Local modules: npm ls --link
Credit to Andrew for finding the --link flag

A: If you want a nice colored output from npm list, you may like:
\ls -F node_modules | sed -n 's/@$//p' | xargs npm ls -g --depth 0

which gives in my current playground directory:
+-- color@0.11.1
+-- grunt@0.4.5
+-- http-server@0.8.5
+-- jsdom@8.0.2
+-- jsonfile@2.2.3
+-- underscore@1.8.3
+-- xmlserializer@0.3.3
`-- zombie@4.2.1

It makes a few assumptions, but it should work in most cases, or be easy to adapt with the explanations below.

*

*use \ls to bypass possible aliases on your ls command

*the -F option adds an '@' indicator for links

*the sed command selects those links and removes the indicator

*the xargs part passes previous output as arguments to npm ...

*npm is invoked with

*

*list or ls to list modules with versions

*replace with ll to get details about each listed module.

*-g for the global modules and

*--depth 0 for a shallow listing (optional)

*--long false (default with 'list').

Issue: for some reason npm gives extraneous entries for me at the moment (non colored). They would be those I had "npm unlink"ed.
For "a list of all globally installed modules" in current npm path, you just do
npm list -g

For further needs you may want to have a look at
npm help folders

You cannot follow symlinks backwards unless you scan your whole filesystem and (then that's not a npm specific question).
For quickly finding files and directories by name, I use locate which works on an index rebuilt usually once a day.
locate '*/node_modules'

and start working from there (you may want to refine the search with --regexp option.

A: I see myself and others having this same question a lot. I wrote a small CLI for myself called link-status to display this info, and it may help others out too! Check it out here!

A: On Windows you can just look at the directory:
C:\Users\[username]\AppData\Roaming\npm\node_modules

You should see any of the symbolic linked libraries listed there, along side any global library installs.


text:
Q: Hive Dynamic Partition table issue with altering partition I Have table with dynamic partition  "campaign" and static partitions year and month(that means I am giving there value while inserting/creating partitions).
'ABC' Partition by (year='2011', month='08', campaign)
As dynamic partition is only supported when its followed by static partitions namesly year and month. But my use case is opposite
I want something like this -->
  'ABC' Partition by (campaign, year='2011', month='08')
So that i can see for campaigns results per year and month.
By any chance, OR any other option by which I can do that? something like this??
ALTER TABLE ABC PARTITION (y='2011', m='08',campaign) RENAME/ALTER PARTITIONs (campaign,y='2011', m='08');

A: A partition isn't defined as static or dynamic in the metastore; Just INSERT/LOAD queries define partitions as static or dynamic. You can run an insertion that uses all-dynamic partitions by using SET hive.exec.dynamic.partition=nonstrict.
See: https://cwiki.apache.org/confluence/display/Hive/Tutorial

A: if you set your partition to strict mode you can perform it
SET hive.exec.dynamic.partition=strict

BUT IF you set to nonstrict mode and perform dynamically then
SET hive.exec.dynamic.partition=nonstrict

We cannot perform ALTER on the Dynamic partition.


text:
Q: My keyboard types some letters twice Why does my keyboard sometimes type letters twice when am typing for example i may mean to type dont but i get donnt (The "n" was typed twice).
This happenns on most of the keys.
Please Note that am using a brand New llapptop (laptop) - DELL
I recently upgraded from Windows 7 professional to Windows 10
Also Note tthat I went to the Keyboard settings under Control panel and adjusted the Repeat rate and Repeat Delay to the lowest value possible but that didn't help.
I have the Integrated PS/2 Keyboard drivers (I tried installing the HID Keyboard Device driver but I failed)
I need help please bbecause this thing can be very annoying...


text:
Q: In Model find method for Mongoose is not working properly with filter condition Can someone help me understand why the Model find method for Mongoose is not working properly with a filter condition?

*

*We have sample loaded dataset and we are using the 'sample_mflix' database
https://www.mongodb.com/docs/atlas/sample-data/sample-mflix/

*We are applying a find query with the filter condition {title:'Show People'} at mongoDB but it is giving all records from data base instead of giving only results for the particular condition.

*I would expect only results where {title:'Show People'}, but it is giving all records from database instead.

Reference Code
Index.js
const express = require("express");
const app = express();
const mongoose = require('mongoose');
const moviemodel = require('./moviemodel');

const username = process.env.MONGO_USERNAME || 'userdefined username';
const password = process.env.MONGO_PASSWORD || 'userdefine password';
const database = "sample_mflix";

const connectionLink = `mongodb+srv://${username}:${password}@cluster0.qvteq.mongodb.net/${database}?retryWrites=true&w=majority`;

mongoose.connect(connectionLink,{
        useNewUrlParser: true,
        useUnifiedTopology: true,
      }, () => {
          if(mongoose.connection.readyState === 1) {
            console.log('Server Started');
          } else {
              console.log('Not Connected');
          }
      }
  );

  mongoose.Promise = global.Promise;

app.get('/getmovie',(req,res,next)=>{
  moviemodel.movieList.find({title:'Show People',required:true},function(err,list){
     res.status(200).send(list);
  })
});
app.listen(3000, () => {
    console.log('Server is started');
});

moviemodel.js
const mongoose =require('mongoose');
const movieSchema = require('./movieschema');

const movieList = mongoose.model('movies',movieSchema);

module.exports={
    movieList
}

movieschema.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const movieSchema = new Schema({
    title : String,
    type : String,
    cast :  [String],
    rated : String,
    directors : [String],
    fullplot : String,
    released: Date
});

module.exports = {
    movieSchema
};

package.json
{
  "name": "projectprep",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.3",
    "mongoose": "^6.2.8"
  }
}

And here is the output:output


text:
Q: How to pass a string with spaces in it as start arguments for a program I have a console project which I want to start with some parameters argc. I want to pass to it a path from my computer, let's say C:\\My Folder. How can I pass the spaces?
When I try to read it I obtain something like C:\\My. I've read that I can pass them by using ". If so, how can I pass those to a string ("C:\My Folder") because I am start this program by using the Process.Start and ProcessStartInfo commands?

A: Wrap the argument in double quotes:
"c:\My Folder\some.exe" /a="this is an argument"

As a string passed to Process.Start:
process.StartInfo.Aguments = "\"this is an argument\"";

Check out this post & answer for more details.

A: You can use delimited string. Using delimited string  you can pass space, new line, or any other characters like slash , backslash etc.
  example:      string path = @"\"C:\\My Folder\"";

          string name = @" sudhansu    sekhar";


text:
Q: Connection to MYSQL Database Using JDBC I am trying to connect to a new database using JDBC for a project I am working on which will allow me to output a whole load of statistics on sports game. But I am running into some trouble whilst trying to connect to the database. I receive the following error below.
com.mysql.jdbc.CommunicationsException: Communications link failure due      to underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.ConnectException
MESSAGE: Connection refused

STACKTRACE:

java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:244)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:271)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2771)
at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at JDBC.main(JDBC.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

** END NESTED EXCEPTION **

Last packet sent to the server was 0 ms ago.
    at com.mysql.jdbc.Connection.createNewIO(Connection.java:2847)
    at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at JDBC.main(JDBC.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

This error is produced from my code which is as followed:
//STEP 1. Import required packages
import java.sql.*;

public class JDBC {
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/";

    //  Database credentials
    static final String USER = "username";
    static final String PASS = "password";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            //STEP 2: Register JDBC driver
            Class.forName("com.mysql.jdbc.Driver");

            //STEP 3: Open a connection
            System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            //STEP 4: Execute a query
            System.out.println("Creating database...");
            stmt = conn.createStatement();

            String sql = "CREATE DATABASE PREDICTOR";
            stmt.executeUpdate(sql);
            System.out.println("Database created successfully...");
        }catch(SQLException se){
            //Handle errors for JDBC
            se.printStackTrace();
        }catch(Exception e){
            //Handle errors for Class.forName
            e.printStackTrace();
        }finally{
            //finally block used to close resources
            try{
                if(stmt!=null)
                    stmt.close();
            }catch(SQLException se2){
            }// nothing we can do
            try{
                if(conn!=null)
                    conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }//end finally try
        }//end try
        System.out.println("Goodbye!");
    }//end main
}

I have disabled my firewall and looked on previous posts on stack overflow trying to amend my problem but alas connection is being refused. Any help appreciated.

A:
Connection refused

This means that the TCP communication to the server was actively rejected - this was done at the TCP layer, the connection never made it to your service - your code is irrelevant at this point.
This can be caused by a few different issues:

*

*The SQL server is not actually running

*There is a firewall in place blocking the connections

*You are connecting to a different port than the server is listening to.

A: I think your SQL server is not running .
Please check the server status.
or You should reinstall the server. It may solve your problem.

A: Your  DB_URL is incorrect. It should
DB_URL = "jdbc:mysql://localhost/databaseName";

or you can also use port number in your url if the database server is not using the default port
DB_URL = "jdbc:mysql://localhost:portNumber/databaseName";

For detail information please visit this site


text:
Q: How to Find History Tracking or Audit Log field in Custom object I have a custom object and I have enabled the checkbox Tract Field History my question is, how can you show your tracking field histroy in Visualforce Page?
I need a way to show the customer what has been changed Username, DateTime etc...
I just need a way to know what is involved in order to display this data.

A: You don't need Visualforce at all to display them in the Page Layout. You can look at the Related Lists for your object, search Hist... and you should see something like Account History.
If you're trying to add it to an existing Visualforce Page instead of a Page Layout, simply use the <apex:relatedList> tag:
<apex:page standardController="Account">
    <apex:relatedList list="Histories" />
</apex:page>

A: @Nick Kahn,
If you intend to use an apex:component, then you might have to query AccountHistory object that you could use in the component.
AccountHistory Query example:
SELECT AccountId, Account.Name, CreatedBy.Name, CreatedDate, Field, OldValue, NewValue
FROM AccountHistory


text:
Q: Bibliography not showing citations.bib contains:
@Book{hicks2001,
 author    = "von Hicks, III, Michael",
 title     = "Design of a Carbon Fiber Composite Grid Structure for the GLAST
              Spacecraft Using a Novel Manufacturing Technique",
 publisher = "Stanford Press",
 year      =  2001,
 address   = "Palo Alto",
 edition   = "1st",
 isbn      = "0-69-697269-4"
}

The tex file:
\documentclass[a4paper, 11pt, notitlepage]{report}
\usepackage[backend=bibtex]{biblatex}
\addbibresource{citations.bib}
\begin{document}

\nocite{*}
\printbibliography

\end{document}

This command will not print the bibliography, although there is no compiling error. What's the problem? I'm using TeXstudio in Windows 8.1. I have tried using XeLatex + Biber, PdfLatex + Biber, PdfLatex + BibTeX.
Update: Now, I included
\usepackage[backend=bibtex]{biblatex}

and I got error:
No file untitled.bbl

A: Judging from some of the information provided among the comments, it may be the case that you (i) can't invoke biber from within TeXstudio and (ii) don't know how to open a command window to run biber "by hand". I take it you do know how to execute bibtex from within TeXstudio.
If that's the case, and if your bibliographic entries don't contain any special, i.e., non-7bit-ASCII characters that will create problems under BibTeX, you could proceed by specifying the option backend=bibtex when loading the biblatex package. Then, as usual, run latex, bibtex, and latex twice more to get all references and all citation callouts fully updated.

\documentclass[a4paper, 11pt, notitlepage]{report}
\usepackage{filecontents}  % create "citations.bib" on-the-fly
\begin{filecontents*}{citations.bib}
@Book{hicks2001,
   author    = "von Hicks, III, Michael",
   title     = "Design of a Carbon Fiber Composite Grid Structure for the
                GLAST Spacecraft Using a Novel Manufacturing Technique",
   publisher = "Stanford Press",
   year      =  2001,
   address   = "Palo Alto",
   edition   = "1st",
   isbn      = "0-69-697269-4"
}
\end{filecontents*}
\usepackage[backend=bibtex,style=numeric]{biblatex}
\addbibresource{citations.bib}
\begin{document}
\nocite{*}
\printbibliography
\end{document}


text:
Q: Open attached spreadsheet in a ppt file with LibreOffice I have a presentation file created in Microsoft PowerPoint and one of the slides contains a attached spreadsheet created in Microsoft Excel.
I'm using the presentation file with LibreOffice Impress and all works fine, except for the attached file.
The slide with the file looks like the figure below:

When I click in the "file", I just have a icon and if I right-click, my options are just image options (copy,cut,save figure, etc...see the image below). In PowerPoint, a simple double-click opens the file, but the same not occurs in LibreOffice and I don't found any other menu option to get the file.

A: It looks like Impress doesn't have the ability to insert an object as an icon, and so doesn't know what to do with objects that are represented as icons (instead of looking like Excel, in this case).
Options I can think of:

*

*Getting someone with Office to save the object as a file and send it to you

*Getting the document's author to insert it the regular way instead of as an icon, since Impress would then give you "Edit" and "Save Copy as..." choices

*Using the free PowerPoint Viewer, if you're running Windows (assuming it handles these objects correctly—can someone confirm?)

A: *.pptx is actually a standard ZIP file with certain directory structure that contains some XML and attachments as files. Those embedded objects are attached as files, too.
You can rename (or copy, or link) it to something.zip and just unpack the contents to find embedded files:
$ ln -s "IT Department.pptx" "IT Department.pptx.zip"
$ unzip "IT Department.pptx.zip"
$ ls -1 ppt/embeddings
Microsoft_PowerPoint_Presentation.pptx
Microsoft_PowerPoint_Presentation1.pptx
Microsoft_PowerPoint_Presentation2.pptx
oleObject1.bin
oleObject2.bin

(I suggest to create and work in a subdirectory to make cleaning the mess easier afterwards.)
In this case three embedded files are obvious PowerPoint documents, for the remaining bin files you may determine what they are with the file tool:
$ file oleObject1.bin
..., Name of Creating Application: Microsoft Office Word, ...
$ file oleObject2.bin
..., Name of Creating Application: Microsoft Office PowerPoint, ...

(or you may look inside and infer the right application from it).
Then, you can rename them to e.g. oleObject1.doc and oleObject2.ppt and open with LibreOffice.
What is left is to determine "which one is where in the presentation".  It should be possible by examining the main xml document (ppt/presentation.xml), but that's very cumbersome. In my case I found that from the context.
It's a pity the LibreOffice still lacks this feature, though!


text:
Q: Video card does not work in server I want to install a video card into a server. When it is inserted, server does not boot up and there is no video signal coming from video card. 4 LEDs at the back of the motherboard show pattern G-R-R-A which means "Disabling the console controller" (see Appendix C in manual). There was another (older) video card in that PCI slot and it worked fine. The card which I want to install works too (I tested it in another computer). Both On-board Video and Dual Monitor Video options are turned off in BIOS (when I turn on one or both options, both new and old video cards dont work). What should I try to do? Thanks.
Video card: 339PCI-HLP (2 x DVI + HDMI)
Server board: Intel S5000PAL - http://download.intel.com/support/motherboards/server/s5000pal/sb/s5000pal_s5000xal_tps_r2_0.pdf

A: See here, http://www.jaton.com/vga/graphics_card_detail.php?pid=199 I verified your card is a PCI card.
Your motherboard supports,
One low profile riser slot supporting 1U or 2U PCIe* riser cards
One full height riser slot supporting 1U or 2U PCI-X* and PCIe* riser cards
I'm not sure if your card is a 3.3v PCI card to be supported in the adaptive PCI-X slot. You have to plug-in your card only on the adaptive slot since it is both PCI-X and PCI-E
You could damage both your graphics card and your serverboard if you plug in into the wrong slot (PCIe).  Try a PCIe card in the PCIe slot if you have one around.
Also, are you using any riser cards to plug the PCI card into?

A: Yay, I made it! There was an option in BIOS which determines amount of memory available to PCI cards. It was set to 3.50Gb-4Gb, so old card with 256Mb of memory fit in that 512Mb space well. But new 1Gb card did not. So I had to change that option to 2.50-4Gb so new card could it into 1.5Gb space.


text:
Q: Stress testing Cassandra from C# consumes all network resources and fails after ~100K inserts We are currently evaluating a Windows Cassandra deployment and I have managed to write a pretty straight-forward stress test. The test attempts to insert 1 million rows with various data into a single local node (to/from localhost, no replication, only one node on the cluster).
This test works fine for the first 100k rows (or so, it does NOT always block on exactly the same row). The inserted rows can be read from the database correctly and everything works fine. Then the test seems to consume every available sockets/buffer/some network resource on the machine and the test fails to connect to Cassandra and stops inserting rows. Even refreshing a completely independent web page from a browser fails for a little while.
I first accused the test, but killing it and restarting it does not work. I need to wait about one minute for new connections to be available (timeout?). Then I may resume the test and keep pumping data. I wrote the test using both the Fluent Cassandra and Cassandra-Sharp clients with the same outcome.
Is there some setting that I need to set in Cassandra or in the C# clients like a maximum number of concurrent connections?
Alternatively, does anyone have a link to the sources of a working stress test which inserts a few million rows from C# so I may compare it with my test and figure out my mistake?

A: My guess is that you aren't leaving the socket connection open.  You can leave the connection open in FluentCassandra by wrapping the context in a session.  If you don't do this, each request executed is on a new socket.

A: I used the Thrift API directly instead of the Cassandra Sharp or Fluent Cassandra APIs. It showed that this code works.
socket = new TSocket("127.0.0.1", 9160);
socket.Open();
client = new Cassandra.Client(new TBinaryProtocol(new TFramedTransport(socket)));
client.set_keyspace("Test");

foreach (Data data in myData) {
    Write(client, data);
}

socket.Close();

While the following code eventually reproduces the problem the higher level APIs encounter on "socket.Open()".
foreach (Data data in myData) {
    socket = new TSocket("127.0.0.1", 9160);
    socket.Open();
    client = new Cassandra.Client(new TBinaryProtocol(new TFramedTransport(socket)));
    client.set_keyspace("Test");

    Write(client, data);

    socket.Close();
}

The socket.Close() method does not release all of the socket's resources which is probably a bug.


text:
Q: Scan QRcode with inverted colors using Vision API After struggling a few hours on making my app detect this QRCode:
I realized that the problem was the in the QRCode appearance. After inverting the colors, the detection was working perfectly..
Is there a way to make Vision API detect the first QRCode? I tried to enable all symbologies but it did not work. I guess it is possible because the app QR Code Reader detects it.

A: I improved googles example app "barcode-reader" to detect both inverted colored barcodes and regular ones.
here is a link to googles example app:
https://github.com/googlesamples/android-vision/tree/master/visionSamples/barcode-reader
I did so by editing "CameraSource" class,
package: "com.google.android.gms.samples.vision.barcodereader.ui.camera".
I added a parameter: private boolean isInverted = false;
and changed function void setNextFrame(byte[] data, Camera camera):
void setNextFrame(byte[] data, Camera camera) {
            synchronized (mLock) {
                if (mPendingFrameData != null) {
                    camera.addCallbackBuffer(mPendingFrameData.array());
                    mPendingFrameData = null;
                }

                if (!mBytesToByteBuffer.containsKey(data)) {
                    Log.d(TAG,
                            "Skipping frame.  Could not find ByteBuffer associated with the image " +
                                    "data from the camera.");
                    return;
                }

                mPendingTimeMillis = SystemClock.elapsedRealtime() - mStartTimeMillis;
                mPendingFrameId++;
                if (!isInverted){
                    for (int y = 0; y < data.length; y++) {
                        data[y] = (byte) ~data[y];
                    }
                    isInverted = true;
                } else {
                    isInverted = false;
                }
                mPendingFrameData = mBytesToByteBuffer.get(data);

                // Notify the processor thread if it is waiting on the next frame (see below).
                mLock.notifyAll();
            }
        }

A: I think this is still an open issue, please see link for details. One workaround for this as stated by a developer:

Right, the barcode API generally doesn't support color-inverted codes. There's no parameter or option to control this at the moment. Though some APIs support them, I don't believe it's a common feature.
For a workaround, you could preprocess the colors in the bitmap before passing them to the barcode API (perhaps inverting colors on alternate frames).

Hope this helps.


text:
Q: Не работает вызов jquery функции с помощью onChange Не работает вызов функции с помощью onChange="calculate()". В консоли никаких ошибок вообще нет. До того как добавил консрукцию jQuery(document).ready(function($) выдавало $ is not a function
jQuery(document).ready(function($) {
    function calculate(){
         //тут код функции
    }
})

A: Можете обращаться по классу или по id элемента.
В функцию либо передавайте параметр, либо оставляйте пустым.
Не стоит передавать символ $
Пример, как это работает:

    $('#bum').on('click', function () {
        function calculate(){
            //тут код функции
        }
        console.log('123');
    })

Парам Пам Пам

A: За неимением подробностей в тексте вопроса, побробуем телепатию. Итак: сначала ругалось на $, потом просто не стало вызываться.
Пока вывод такой: jQuery подключен c noConflict() (Wordpress?). В функции calculate() есть вызовы методов $.
Как решить
Малой кровью:

*

*Убираем jQuery(document).ready(function ($) {})

*В начало фнукции calculate() пишем let $ = jQuery; (или var $ = jQuery; если браузер очень старый)

Правильным способом:

*

*Оставляем jQuery(document).ready(function ($) {}) (можно написать короче jQuery(function($) {}))

*Устанавливаем обработчик через $(селектор).on('change', calculate);. Эта строка должна быть после определения функции calculate().

Нужно еще учитывать, вы устанавливаете обработчик на элементе, который постоянно присутствует на странице или появляется там как результат других функций. В первом случае указанные изменения должны помочь. Во втором случае правильный способ потребует установки обработчика после появления элемента на странице


text:
Q: Как сделать 2 колонки в listbox через mvvm на Avalonia Мне нужно вывести два списка List в две колонки ListBox, но так что-бы это была одна строка, через патерн MVVM.
Я уже пол интернета облазил но так и не нашёл ничего.
Я только учусь возможно из-за этого что-то пропустил,
если у кого-то есть возможность обяснить, или хотя б пример какой-то, был бы очень рад.
ViewModel:
private List<string> _artists = new();
private List<string> _names = new();
private List<Song> _songs = new();

     public List<string> Artists
    {
        get
        {
            return _artists;
        }
        set { _artists = value; OnProopertyChanged(); }
    }

     public List<string> Names
    {
        get
        {
            return _names;
        }
        set { _names = value; OnProopertyChanged(); }
    }

     public List<Song> Songs
    {
        get
        {
            return _songs;
        }
        set { _songs = value; OnProopertyChanged(); }
    }

        for (int counterForList = 1; counterForList < 41; counterForList++)
        {
            HtmlMethod(counterForList,2, out Artist);
            HtmlMethod(counterForList,3, out Name);

            Song song = new Song(Name, Artist);
            Songs.Add(song);
        }

        foreach (var song in Songs)
        {
            Artists.Add(song.Artist);
            Names.Add(song.Name);
        }

Model:
public class Song
{
    public string Name { get; set; }
    public string Artist { get; set; }

и сам MainWindow:
<Window xmlns="https://github.com/avaloniaui"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="using:AvaloniaApplication1.ViewModels"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="600" d:DesignHeight="350"
    x:Class="AvaloniaApplication1.Views.MainWindow"
    Icon="/Assets/avalonia-logo.ico"
    Title="AvaloniaApplication1"
    Width="600"
    Height="350">

<Design.DataContext>
    <vm:MainWindowViewModel/>
</Design.DataContext>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <TextBlock Text="{Binding Title}" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="1"/>
    <ListBox Items="{Binding Songs}" Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="3" Grid.RowSpan="2">
        <ListBox.ItemTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
            </Grid>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

Вот есть код, я не понимаю как вывести Artists и Names в разные колонки, или может Song можно поделить.
В документалке по avalonia написано что уних нету ItemSource у них только Item.

A: Очень просто, вы почти всё сделали
<ListBox.ItemTemplate>
    <DataTemplate>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <TextBlock Margin="5" Text="{Binding Name}"/>
            <TextBlock Margin="5" Grid.Column="1" Text="{Binding Artist}"/>
        </Grid>
    </DataTemplate>
<ListBox.ItemTemplate>

Либо еще так можно
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <TextBlock Margin="5" Text="{Binding Name}"/>
            <TextBlock Margin="5 0" Text="-"/>
            <TextBlock Margin="5" Text="{Binding Artist}"/>
        </StackPanel>
    </DataTemplate>
<ListBox.ItemTemplate>

Документация