text:
Q: What should the entry point be for a pure CSS npm project? I have a CSS file that I want to upload to npm. My project's folder structure is as follows:
my-project (folder)
|
+---- css (folder)
      |
      +---- my-project.css
      |
      +---- my-project.min.css

When I try to upload my project to NPM, it asks for an entry point, where the default is set to index.js. For my case where there are only 2 files inside a folder called css, what should it be? Moreover, what is the meaning of the entry-point for an npm project?

A: Entry point is a JavaScript file that gets called when your module is needed.
By common practice, it is usually given the name "app.js" or "index.js" (your case).
The entry point is also the path that will be used to access your module.
CSS files cannot be entry points.


text:
Q: is it possible to make multiple mongo routers connected to just one shard on a mongoDB shard cluster? I'd like to make a mongo cluster with multiple mongo routers(mongos) with just one shard(mongod) like these figures.
(broken image)

(source)
So I made two mongo routers named 'mongorouter-1', 'mongorouter-2',
and also made one shard named 'mongod'.
Two config servers were made and connected to each mongo routers like the first figure(not like the second figure).
These were made as Docker container with the official Mongo Image
and these were on the same network so they are connected to each other.
In mongorouter-1 I added 'mongod' well with this command.
sh.addShard("mongod:27017")
It works well, but In mongorouter-2 this command put an error, like
mongos> sh.addShard("mongod:27017")
{
    "ok" : 0,
    "errmsg" : "E11000 duplicate key error collection: admin.system.version index: _id_ dup key: { : \"shardIdentity\" }",
    "code" : 11000,
    "codeName" : "DuplicateKey",
    "operationTime" : Timestamp(1558591937, 1),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1558591937, 1),
        "signature" : {
            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
            "keyId" : NumberLong(0)
        }
    }
}

In mongorouter-1, sh.status is this
mongos> sh.status()
--- Sharding Status ---
  sharding version: {
    "_id" : 1,
    "minCompatibleVersion" : 5,
    "currentVersion" : 6,
    "clusterId" : ObjectId("5ce6683cc490bfc9325389cb")
  }
  shards:
        {  "_id" : "shard0000",  "host" : "mongod:27017",  "state" : 1 }
  active mongoses:
        "4.0.6" : 1
  autosplit:
        Currently enabled: yes
  balancer:
        Currently enabled:  yes
        Currently running:  no
        Failed balancer rounds in last 5 attempts:  0
        Migration Results for the last 24 hours:
                No recent migrations
  databases:
        {  "_id" : "config",  "primary" : "config",  "partitioned" : true }

and in mongorouter-2, sh.status is this
mongos> sh.status()
--- Sharding Status ---
  sharding version: {
    "_id" : 1,
    "minCompatibleVersion" : 5,
    "currentVersion" : 6,
    "clusterId" : ObjectId("5ce668176a4dcc52fd230ac9")
  }
  shards:
  active mongoses:
  autosplit:
        Currently enabled: yes
  balancer:
        Currently enabled:  yes
        Currently running:  no
        Failed balancer rounds in last 5 attempts:  0
        Migration Results for the last 24 hours:
                No recent migrations
  databases:
        {  "_id" : "config",  "primary" : "config",  "partitioned" : true }

I don't know how to make multiple mongo routers connected to just one shard like the figures.
If you know the solution, help me. Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django Form with java-script misbehaving in IE I have a django form where it has name , address, zip, etc. as well as a pickup dates field for a donation service. I have it setup so that after a user enters in a zip code and leaves the field to send an ajax request to a django view to return all of the pickups that will match that zip code. Everything works fine in chrome, firefox, safari but of course IE is being a royal pain in the you know what. The $('#results').hide();below does not seem to work for some users despite having JS enabled and seeing the source code. Somehow is it all breaking?
Errors have been that no pickup dates are being returned in IE and when submitted it's giving a 403 csrf error depsite me having the tag within the form. Below is my JS for the form. Is there anything in here IE specific that would cause a problem? The main function to get the pickup dates is function get_pickup_dates
Query(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

function get_pickup_dates(zip,template)
{
    $.ajax({
        type: "POST",
        url:"/get_pickups/",
        data: {
        'zip': zip,
        'template':template
        },
        success: function(data){

                date_results = $(data).find('#results').html()
                $("#id_pickup_date").replaceWith("<span>" + date_results + "</span >");
        },
        error: function(){
            alert("Error");
        }
    })
}

$(document).ready(function()
{

template = window.location.pathname;
$('#results').hide();
$('#id_cancel').closest('div').hide()

    if (template == '/donate/')
    {
        address_fields = $("#id_address_number, #id_city, #donateForm #id_zip, #externalForm #id_zip, #id_address_street, #id_pickup_id").closest('div');
        $(address_fields).hide();

    }

    if (template == '/external/')
    {
        $("#id_zip").live('focusout',function()
        {
            zip = $(this).val()
            get_pickup_dates(zip,template)
        });
    }

    if( $("ul").hasClass('errorlist') && template == '/donate/')
    {
        address_fields.show();
    }

    $("#id_address").live('focusout',function()
    {

        var intTest = /^\d{5}$/;
        $this = $(this);
        var address = $this.val();
        var split_addr = address.split(' ');
        var find_street = address.split(',');
        var street = find_street[0];
        var trim_street = street.split(' ');

        var clean_street = trim_street.splice(1,2).join(" ");

        $('#id_address_number').val(split_addr[0]);

        // Find ZIP code in address
        for(i=0; i <= split_addr.length; i++)
        {
            if(intTest.test(split_addr[i]))
            {
                $("#id_zip").val(split_addr[i]);
                zip = split_addr[i];
                //alert(zip);
                break;
            }
        }

        //Find city
        $('#id_city').val($.trim(find_street[1]));

        // Find Street in address
        $("#id_address_street").val(clean_street);
        if(template == '/donate/')
        {
            $(address_fields).show("slow");
            $('#id_pickup_id').closest('div').hide();
        }

        get_pickup_dates(zip,template)
    });

    $("#id_address").keypress(function (e)
    {
        if (e.which == 13)
        {
          return false;
        }
        return true
    });

    $('div.field input, div.field select, div.field checkbox, div.field textarea').focus(function()
    {
        $this = $(this);
        $this.closest('div').addClass('highlight');

    });

    $('div.field input, div.field select, div.field checkbox, div.field textarea').blur(function()
    {
        $this = $(this);

        $this.closest('div').removeClass('highlight');

    });

    if ($('#id_zip').val().length > 0)
    {
        zip = $('#id_zip').val()
        get_pickup_dates(zip,template)
    }
});

A: If you are using iFrames this might be a known (and now fixed) bug in jQuery/IE compatibility. See http://bugs.jquery.com/ticket/13936


text:
Q: replaying multicast UDP packet capture via tcpreplay not being seen by client I'm having no joy in getting a replayed UDP Multicast packet to be "seen" by a client program on a different machine.
Details:
I have two machines on my local (wired) network connected through one unmanaged switch. One machine (running tcpreplay) is running Ubuntu 20.04, the other machine is running Windows 10.
On the Windows machine I have a Python program I wrote which listens for UDP multicast packets on port 5110 (this is dictated by the source of the UDP stream which is a commercial program). When I run the commercial program, my Python code correctly consumes the incoming packets and all seems to be working fine. I have a lot of work yet to do on the contents of those packets after they are received, but that isn't important for this issue.
So, moving forward, I decided it would be great to be able to work on the Python code without having the commercial program always running in the background hogging up resources. I figured if I could catch a snippet of UDP broadcasts from that program, I should be able to replay at leisure without having to run that resource hog.
So, on the Windows machine, I captured a UDP multicast packet stream using Wireshark and saved to a pcap file which I then copied to the Ubuntu machine.
I then attempted to replay that pcap file (on the Ubuntu machine) as follows:
$sudo tcpreplay -i enp5s0 single.pcap
To my disappointment, my Python program (on the Windows machine) did not receive the incoming packets.
Back on the Windows machine, I fired up Wireshark again and captured the "replayed" packet coming from the Ubuntu machine - so it appears the packet did make it out of my Ubuntu machine and into my Windows one. The contents of both the source packet (sent by tcpreplay) and the received packet (grabbed by Wireshark) appear identical - including the source and destination MAC addresses and the checksums. A diff on the byte contents of each packet yields no differences.
However, my Python program still stoically sits there waiting at:
data, address = sock.recvfrom(1024)

Here on stackoverflow, I did find this thread which seems to be an identical problem, however none of the solutions presented within helped (including changing the rp_filter parameter). I also saw mention of a Windows program, "Colasoft PacketPlayer", which I tried - running on the same machine as my Python client. This appears to have the same apparent results (i.e. no joy). I did not initially try that route as I was concerned with generating the packet on the same machine which is listening for it. (As an aside, I did also capture the replayed packet from Colasoft PacketPlayer and it too appears identical to the source packet).
At this point I'm out of ideas and am reaching out to the community for possible next steps?


text:
Q: Jsoup Could not parse query I'm converting the xpath to Jsoup
below is my xpath (which is used in my selenium webdriver)
String number = driver.findElement(By.xpath("//span[@data-dojo-attach-point='subNumber']")).getText();

equivalent jsoup
String number =  doc.select(" >span >data-dojo-attach-point=subNumber").text();
        System.out.println(number);

While executing getting below error
Could not parse query 'data-dojo-attach-point=subNumber': unexpected token at '=subNumber'

HTML:

Number

                94607506

can anyone help this.

A: This is the way you could retrieve that data with selectFirst(String cssQuery) and then html():
TestClass:
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class TestA {

    public static void main(String[] args) throws IOException {

        //this is where chromedriver.exe should be
        String driverPath = "yourDriverPath";

        System.setProperty("webdriver.chrome.driver", driverPath);

        WebDriver driver = new ChromeDriver(); ;

        driver.get("YourURL");

        WebDriverWait wait = new WebDriverWait(driver, 15);

        String cssSelector = "span[data-dojo-attach-point=subNumber]";

        wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(cssSelector)));

        Document doc = Jsoup.connect("YourURL").get();

        Element subNumber = doc.selectFirst(cssSelector);

        System.out.println(subNumber.html());
    }
}

Output:
94607506

Note: I've tried the above in my laptop and it's working.

A: Use this CSS Selector.
  div.subHeaders > div.subHeaderItem > span

  String number =  doc.select("div.subHeaders > div.subHeaderItem > span").text();

If the page has loaded then you will get the text. Use "Try Jsoup" to verify if you are able to get the text.
Click on this link. Click "Fetch URL" and input the URL of the page you are trying to parse and click "Fetch". Let me know if you are able to get the value.
If you don't mind posting the URL here, post the URL here. We will help you.


text:
Q: how to import xls to database with asp.net 4.0 with c# I just want to make xls mapping facility with asp.net 4.0 with C#. I just want to import all details from Excel sheet1 to database.
Here I am binding one repeater which have text box here user can enter specific row to table column and make it to do xls mapping.
My Code:
 protected void lbut_import_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        if (FileUpload1.HasFile)
        {
            if (FileUpload1.FileContent.Length > 0)
            {
                string Foldername;
                string Extension = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
                string filename = DateTime.Now.ToString("ddMMyyyy_HHmmss");
                if (Extension == ".XLS" || Extension == ".XLSX" || Extension == ".xls" || Extension == ".xlsx")
                {
                    Foldername = Server.MapPath("~/Files/");
                    FileUpload1.PostedFile.SaveAs(Foldername + filename + Extension);
                    String conStr = "";
                    switch (Extension)
                    {
                        case ".xls": //Excel 97-03
                            conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                            "Data Source=" + Foldername + "//" + filename + Extension + ";" +
                            "Extended Properties=Excel 8.0;";
                            break;

                        case ".xlsx": //Excel 07
                            conStr = "Provider=Microsoft.ACE.OLEDB.12.0;" +
                            "Data Source=" + Foldername + "//" + filename + Extension + ";" +
                            "Extended Properties=Excel 8.0;";
                            break;
                    }
                    OleDbConnection excelConnection = new OleDbConnection(conStr);
                    OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", excelConnection);
                    excelConnection.Open();
                    OleDbDataReader dReader;
                    dReader = cmd.ExecuteReader();
                    SqlBulkCopy sqlBulk = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["CRMConnectionString"].ToString());
                    //Give your Destination table name
                    using (DataClassesDataContext db = new DataClassesDataContext())
                    {
                        sqlBulk.DestinationTableName = "tbl_Party_master";
                        sqlBulk.ColumnMappings.Add("Name",dReader[int.Parse(txt_col.Text.Trim())].ToString());
                        sqlBulk.ColumnMappings.Add("type_id", dReader[int.Parse(txt_col1.Text.Trim())].ToString());
                        if (!string.IsNullOrEmpty(txt_col2.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("Ownername", dReader[int.Parse(txt_col2.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col3.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("Ownermob", dReader[int.Parse(txt_col3.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col4.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("Room", dReader[int.Parse(txt_col4.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col5.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("Road", dReader[int.Parse(txt_col5.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col6.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("Area", dReader[int.Parse(txt_col6.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col7.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("City", dReader[int.Parse(txt_col7.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col8.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("Mobile", dReader[int.Parse(txt_col8.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col9.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("Email", dReader[int.Parse(txt_col9.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col10.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("ContactPerson", dReader[int.Parse(txt_col10.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col11.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("ContactPersonmob", dReader[int.Parse(txt_col11.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col12.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("UserOFC", dReader[int.Parse(txt_col12.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col13.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("UserVAT", dReader[int.Parse(txt_col13.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col14.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("UserINV", dReader[int.Parse(txt_col14.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col15.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("UserNone", dReader[int.Parse(txt_col15.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col16.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("state_id", dReader[int.Parse(txt_col16.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col17.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("country_id", dReader[int.Parse(txt_col17.Text.Trim())].ToString());
                        }
                        if (!string.IsNullOrEmpty(txt_col18.Text.Trim()))
                        {
                            sqlBulk.ColumnMappings.Add("Remark",dReader[int.Parse(txt_col18.Text.Trim())].ToString());
                        }
                        sqlBulk.ColumnMappings.Add("Register_Date", System.DateTime.Now.ToString());
                        sqlBulk.ColumnMappings.Add("User_id", db.Users.Where(u => u.Username.Equals((String)Session["Username"])).Select(u => u.Ref_no).SingleOrDefault());
                        sqlBulk.WriteToServer(dReader);
                        excelConnection.Close();
                    }
                }
            }
            ibtnimexls_ModalPopupExtender.Show();
        }
    }
}

But this code is giving me one error:
there is no specific row/column at drreader[] object.
here i put complete error message from iis:
Server Error in '/CRM' Application.

No data exists for the row/column.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: No data exists for the row/column.

Source Error:

Line 3121:                        {
Line 3122:                            sqlBulk.DestinationTableName = "tbl_Party_master";
Line 3123:                            sqlBulk.ColumnMappings.Add("Name", dReader[int.Parse(((TextBox)Repeater_Column_List.Items[0].FindControl("txt_col")).Text.Trim())].ToString());
Line 3124:                            sqlBulk.ColumnMappings.Add("type_id", dReader[int.Parse(((TextBox)Repeater_Column_List.Items[1].FindControl("txt_col")).Text.Trim())].ToString());
Line 3125:                            if (!string.IsNullOrEmpty(((TextBox)Repeater_Column_List.Items[2].FindControl("txt_col")).Text.Trim()))

Source File: f:\CRM\Staff\Raise_Ticket.aspx.cs    Line: 3123

Stack Trace:

[InvalidOperationException: No data exists for the row/column.]
   System.Data.OleDb.OleDbDataReader.DoValueCheck(Int32 ordinal) +1106519
   System.Data.OleDb.OleDbDataReader.GetValue(Int32 ordinal) +12
   System.Data.OleDb.OleDbDataReader.get_Item(Int32 index) +10
   Staff_Raise_Ticket.lbut_import_Click(Object sender, EventArgs e) in f:\CRM\Staff\Raise_Ticket.aspx.cs:3123
   System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +113
   System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +9
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +176
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1

Please help me!

Update
here is my repeater html markup :

                                    Table Data Column

                                    Excel Column Number

                                    <asp:CheckBox ID="CheckBox1" runat="server" Text="Name" Enabled="false" Checked="true"/>

                                     <ajaxToolkit:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender16" runat="server" TargetControlID="txt_col" WatermarkText="Enter Row number">
                                     </ajaxToolkit:TextBoxWatermarkExtender>
                                     <ajaxToolkit:FilteredTextBoxExtender ID="FilteredTextBoxExtender7" runat="server" TargetControlID="txt_col" FilterType="Numbers"></ajaxToolkit:FilteredTextBoxExtender>
                                    <asp:TextBox ID="txt_col" runat="server" CssClass="input" MaxLength="4"></asp:TextBox>
                                     <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="Required" ControlToValidate="txt_col" ValidationGroup="ImportXLS" Enabled="true" Display="None" SetFocusOnError="True"></asp:RequiredFieldValidator>
                                     <ajaxToolkit:ValidatorCalloutExtender ID="ValidatorCalloutExtender7" runat="server" TargetControlID="RequiredFieldValidator6" WarningIconImageUrl="~/images/Warning.gif" CloseImageUrl="~/images/close.gif" >
                                     </ajaxToolkit:ValidatorCalloutExtender>

                                    ..............

A: WOW!! I'm a bit lost for words TBH. Why not write each text box onto the html and not dynamically create everything in a repeater? This is where your problem is. When you post back the repeater loses its databinding and then when you try and reference rows in the Repeater they are all null because you have no data binded to it after the postback.
This is kinda a guess, but a well informed one. Unless you have some crazy business case for doing so I urge you to not continue using the repeater and write each textbox by hand.
Now I must go find a bin to be sick in! ;-)


text:
Q: Virtual keyboard for the Pi with auto-hide functionality I am using PyGObject to create an UI that will be run on a 7" official RPi touchscreen connected to a Pi 3 running Raspbian. As part of this interface, the UI will need an on-screen keyboard. I am aware of two virtual keyboard programs for the Pi: Matchbox Keyboard and Florence.
The problem is that I want to imitate the behavior of a smartphone keyboard as much as possible, but don't know how to do so. What I want to do is similar to this, except I want the keyboard to auto-hide and to be on top of the main window. How can this be done?
EDIT: I've tried both of these programs and haven't been able to figure out how to achieve this. I can't find an auto-popup option in Matchbox Keyboard, and some people report that it has this capability (here), others say no (here). I assume that some Linux desktop managers support this feature, but not LXDE on the Pi.
Florence seems promising because it has an auto-hide option that sounds like it would do what I want, but when I selected it didn't seem to work.

A: I finally figured out how to add auto-hide behavior to Matchbox Keyboard. First I read about the --daemon command line argument here which sounded like it would work, but when I tried it the auto-hide feature worked for only some, not all, text entries.
The same README file says:

You can embed matchbox-keyboard into other applications with toolkits
  that support the XEMBED protocol ( GTK2 for example ).
See examples/matchbox-keyboard-gtk-embed.c for how its done.

I knew about this before but didn't think it would work with PyGObject, until I found out that it does. Adding these lines to my code worked:
p = subprocess.Popen(["matchbox-keyboard", "--xid"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
keyboard = Gtk.Socket()
window.add(keyboard)
keyboard.add_id(int(p.stdout.readline()))

I also created a simple subclass of Gtk.Entry which auto-hides the keyboard when the text entry gains or loses focus:
class TextEntry(Gtk.Entry):
    def __init__(self, window):
        Gtk.Entry.__init__(self)
        self.keyboard = window.keyboard

        self.connect("focus-in-event", self.on_focus_in)
        self.connect("focus-out-event", self.on_focus_out)

    def on_focus_in(self, event, data):
        self.keyboard.show()

    def on_focus_out(self, event, data):
        self.keyboard.hide()


text:
Q: Coupon code button problem! I have 1 issue confusing.
-When i am in checkout cart page. I cant click button apply coupon code.
Javascrip seems it does not work ( I try with input empty but no validate or any reaction).
But if I am in checkout onepage. I can do it.
I check template path hint and see them using 1 template default/template/checkout/cart/coupon.phtml
Someone can explain it?
Update code coupon.phtml
<form id="discount-coupon-form" action="<?php echo $this->getFormActionUrl() ?>" method="post">

            <input type="hidden" name="remove" id="remove-coupone" value="0" />

                <input class="input-text" type="text" id="coupon_code" name="coupon_code" value="<?php echo $this->escapeHtml($this->getCouponCode()) ?>" />

                    <button type="button" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Discount Codes')) ?>" class="button2" onclick="discountForm.submit(false)" value="<?php echo $this->__('Discount Codes') ?>"><?php echo $this->__('Discount Codes') ?></button>
                    <?php if(strlen($this->getCouponCode())): ?>
                        <button type="button" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Cancel')) ?>" class="button2 cancel-coupon" onclick="discountForm.submit(true)" value="<?php echo $this->__('Cancel') ?>"><?php echo $this->__('Cancel') ?>
                        </button>
                    <?php endif;?>

</form>

A: Replace coupon code button to this.
<button title="Apply Coupon" onclick="discountForm.submit(false)" value="Apply Coupon">Apply Coupon</button>


text:
Q: why "sudo -u xxx cmd" fails but "sudo -u xxx /path/to/cmd" succeeds? We recently upgraded our aws linux server instance type. It is still an SLES 12 SP1. However I am noticing some differences some of which are confounding
$ sudo -u xyz cmd ...
<it asks for password, causing old scripts to break>

$ sudo -u xyz /path/to/cmd ...
<works>

$ sudo --version
Sudo version 1.8.10p3
Sudoers policy plugin version 1.8.10p3
Sudoers file grammar version 43
Sudoers I/O plugin version 1.8.10p3

$ uname -a
Linux ovcp6hana1 3.12.69-60.64.32-default #1 SMP Wed Feb 15 08:57:04 UTC 2017 (76392c8) x86_64 x86_64 x86_64 GNU/Linux

(The sudoers config has a Cmnd_Alias and authorization for "/path/to/cmd")
The former version used to work but it does not, as if the path was being automatically expanded earlier but not any more.
Is there some way to get the old form to work? Thanks.
--EDIT
I verified that it is the exact same command, ie which xyz expands to /path/to/xyz.
--EDIT 2
I think I found the issue, but still don't have a way to stay compatible with my application. It appears the difference is between sudo versions 1.7.6 and 1.8.10. But I failed to find such a mention in the sudo release notes
I created another user with similar privileges on an older server running sudo 1.7. The specific privilege is as below. The config files in the two match in options
#added in /etc/sudoers
#userA ALL=(userABC) NOPASSWD: /bin/bash, /usr/local/bin/aws

#with both sudo versions
userA$ sudo -u userABC bash -c "echo \$PATH"
/usr/bin:/bin:/usr/sbin:/sbin

userA$ sudo -u userABC bash -c "which aws"
/usr/bin/aws <<<< but this is not reached in either of the two cases

userA$ which aws
/usr/local/bin/aws <<<<<< this is the right binary

#with sudo version 1.7.6
userA$ sudo -u userABC aws
..the right binary runs, so path must have been set between check and run

#with sudo version 1.8.10
userA$ sudo -u userABC aws
failure! sudo asks for password of userABC

The program /usr/bin/aws does some kind of wrapping. Until now I was blissfully unaware (!) of its existence but even when I momentarily removed this program, there was no impact on anything.
So I have a slightly better understanding of the problem but still don't know if there is an option other than changing the app.

A: When a user is permitted to execute a command as another user by a rule in the sudoers file that specifies a full path to an executable, then this full path needs to be used on the command line as well.
This is a security measure.
Additionally, if the command in the sudoers file is specified with command line flags, those flags need to be present when you invoke the command through sudo.

A: This is happening because your sudoers file is allowing a NOPASSWD attribute to apply when invoking the explicit path to the executable, but not when you rely on path searching; it may be hitting a different executable.


text:
Q: RQuantlib and Mac OS X 10.8.2 I'm a total newbie in Mac OS X, R and C++. Sound like a good mix, doesn't it?
I have the need to use RQuantLib, because I want to use some pricing functions part of the QuantLib package inside R, all on a Mac OS X-powered environment.
I've correctly installed QuantLib. I've already asked to the official QuantLib mailing list, and together we seem to have reached the conclusion that the problems I'm encountering are not related to my QuantLib installation, which seems ok and correctly configured.
So, I turned to R to try and solve the problem. Whenever I try to run ZeroCouponBond from within R, copying and pasting the first example provided with the official documentation, I get the following error:
"Error in DiscountCurve.default(discountCurve.param, list(flat = 0.05)) :
cannot find function errorOccured"

Now, I would rule any syntax.related problem out, since I'm copying the very same example present in the official help.
I don't know what I did wrong, but I know I need to find a solution at all costs. I've installed Rcpp, and the configuration seems really ok. Just one question I was not able to find an answert to: in my understanding, RQuantLib basically acts as a link between QuantLib and R. If that's correct, how can I tell RQuantLib where to look to find libQuantLib.a, that is, the compiled library resulting from the "make && sudo make install" commands performed while installing QuantLib itself?

A: Right, so, I've finally managed to get it to work.
First of all, I would like to say that things would have been much easier if a thorough, step-by-step installation procedure had been provided. I acknowledge I'm a total newbie, but I think other people approaching to R for the first time might encounter difficulties similar to those I had to overcome.
Anyway, this is what I did:

*

*I've downloaded the .tar.gz source packages for both Rcpp and RQuantLib from cran.r-project.org

*I've compiled them installing them from within the R environment. This is where I was making a mistake. Indeed, I was trying to compile them by invoking the configure installation script from the terminal; however, as Dirk said, the config script looks for QuantLib's quantlib-config script, and I didn't know the correct syntax to tell the configure script the correct path to QuantLib. Executing the procedure from R (by just installing the package) sorts out any problem, as all the dependencies are correctly located and loaded

So, that's pretty much it: just install the .tar.gz source package as you would do with the binary version, and everything should work ok.
Of course, I'm still curious to understand:

*

*If it is possible to compile Rcpp and RQuantLib from the terminal; and

*Why the binary version for Mac OS X will not work on my system, ie: why do I have to compile starting from the source code?

Thank you so much to anyone willing to answer my (probably naive and silly) questions. I'm eager to understand a bit more!
Thanks!

A: The RQuantLib package uses a tool called configure which determines the patch at package build-time.  It looks for the script quantlib-config from which it learns about the location of libQuantLib.a.

A: First, install boost (brew install boost) and, secondly, Quantlib (currently at 1.7.1) by following instructions at http://quantlib.org/install/macosx.shtml:
cd QuantLib-1.x.y
./configure --enable-static --with-boost-include=/opt/local/include/ \
            --with-boost-lib=/opt/local/lib/ --prefix=/opt/local/
make && sudo make install

It takes some time (~1 hour) for make.
Then in R or Rstudio, install packages Rcpp and RQuantlib. The later requires type="source" since only source package is available.
At this point, you should be able to use RQuantlib. The American Option value (SPY as of 4/1/2016, maturity 7/15/2016) can be calculated in R as
AmericanOption("put", strike=206, volatility=0.1525, underlying = 206.92, 0.021, 0.003, 73/252, engine="CrankNicolson")


text:
Q: CSS media queries not working for specific range as expected in chrome and Mozilla and didn't tested in other browsers Below example queries not working as expected and I tested in chrome(v74.0.3729.169 (Official Build) (64-bit)) and Mozilla(v66.0.2(64bit)) browsers.
@media screen and (max-width: 1199px) and (min-width: 992px) {
  div.example {
    border: 8px solid black;
    background: yellow;
  }
}

@media screen and (max-width: 991px) and (min-width: 768px) {
  div.example {
    border: 8px solid black;
    background: red;
  }
}

@media screen and (max-width: 767px) and (min-width: 480px) {
  div.example {
    border: 8px solid black;
    background: green;
  }
}

For explanation purpose I will take below one
@media screen and (max-width: 767px) and (min-width: 480px) {
  div.example {
    border: 8px solid black;
    background: green;
  }
}

Please look below screenshots for above media query:
Which is not working for 767px

Which is working for 766px

In the above media query not styling my div.example selector at 767px screen size instead it styling below 767px screen size.
In generally the above css snippet should work 767px and less then 767px to480px & above 480px screen size.
But, above css snippet is working less then 767px to 480px & above 480px screen size.
Similarly below queries also not working as expected
@media screen and (max-width: 1199px) and (min-width: 992px) {
  div.example {
    border: 8px solid black;
    background: yellow;
  }
}

@media screen and (max-width: 991px) and (min-width: 768px) {
  div.example {
    border: 8px solid black;
    background: red;
  }
}

And finally I just manually look for which range of screen sizes are not working as expected then found for these ranges 981 to 991, 1181 to 1199, 761 to 767.
Below css media queries working as expected but using different breakpoints.
@media screen and (max-width: 1200px) and (min-width: 993px) {
  div.example {
    border: 8px solid black;
    background: yellow;
  }
}

@media screen and (max-width: 992px) and (min-width: 769px) {
  div.example {
    border: 8px solid black;
    background: red;
  }
}

@media screen and (max-width: 768px) and (min-width: 480px) {
  div.example {
    border: 8px solid black;
    background: green;
  }
}

Working for specific media breakpoints link - https://codepen.io/rag7s/pen/PvrREx
Not Working for specific media breakpoints link - https://codepen.io/rag7s/pen/pmXLpv

A: Check Now
@media (max-width: 1199px) {
    div.example {
        border: 8px solid black;
        background: yellow;
    }
}

@media (max-width: 991px) {
    div.example {
        border: 8px solid black;
        background: red;
    }
}

@media (max-width: 767px) {
    div.example {
        border: 8px solid black;
        background: green;
    }
}

https://codepen.io/anon/pen/zQVaxy


text:
Q: Trying To Debug A Simple LinkedList Code I'm trying to practice my C++ and I wanted to start off creating a simple linkedlist. I'm doing this in Visual Studio and I'm having a hard time trying to debug this little program. When I run the program all I get are:
'LinkList.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Cannot find or open the PDB file.
'LinkList.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'. Cannot find or open the PDB file.
'LinkList.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'. Cannot find or open the PDB file.
'LinkList.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp120d.dll'. Cannot find or open the PDB file.
'LinkList.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcr120d.dll'. Cannot find or open the PDB file.
The program '[6016] LinkList.exe' has exited with code 0 (0x0).

Code:
#pragma once
class Node
{
public:
    Node(int);
    int data;
    Node *next;
    ~Node();
};

#include "stdafx.h"
#include "Node.h"

Node::Node(int d)
{
    data = d;
    next = NULL;
}

Node::~Node()
{
}

#pragma once
#include "Node.h"

class LinkedList
{
    Node *head;
    Node *end;
public:
    LinkedList();
    void appendAtEnd(int);
    void deleteNode(int);
    void printList();
    ~LinkedList();
};

#include "stdafx.h"
#include "LinkedList.h"
#include <iostream>

using namespace std;

LinkedList::LinkedList()
{
    head = 0;
    end = head;
}

void LinkedList::appendAtEnd(int d){
    Node* newNode = new Node(d);
    if (head == 0){
        head = newNode;
        end = newNode;
    }
    else{
        end->next = newNode;
        end = end->next;
    }
}

void LinkedList::deleteNode( int d){
    Node *tmp = head;
    if (tmp == 0){
        cout << "List is empty!\n";
    }

    while (tmp->next != 0){
        if (tmp->data == d){
            tmp = tmp->next;
        }
        tmp = tmp->next;
    }
}

void LinkedList::printList(){
    Node *tmp = head;
    if (tmp == 0){
        cout << "List is empty!\n";
    }
    if (tmp->next == 0){
        cout << tmp->data << endl;
    }
    while (tmp != 0){
        cout << tmp->data << endl;
        tmp = tmp->next;
    }

}
LinkedList::~LinkedList()
{
}

#include "stdafx.h"
#include "LinkedList.h"

int _tmain(int argc, _TCHAR* argv[])
{
    LinkedList list;
    list.appendAtEnd(1);
    list.appendAtEnd(2);
    list.printList();

}

A: The list should be printed in the console (not in debug output window), but the console is closed too quickly, so you don't see it. There's no code to wait for some input from the user. Add something like this at the end of the main function:
int _tmain(int argc, _TCHAR* argv[])
{
    ...
    cout << "Press Enter...";
    cin.get();
}


text:
Q: Kibana interface with ELK on virtual host I use this tutorial to install ELK (Elasticsearch Logstack Kibana) to analyse logs.
I use to install ELK on a virtual vmware machine running ubuntu server 14.04.
My computer using Windows 7.
Actually I have do this :

*

*Install Java 7

*Install elascticsearch

*Install kibana

*Install nginx

But now the tuto says :

Kibana is now accessible via your FQDN or the public IP address of your Logstash Server i.e. http:// logstash_server_public_ip/. If you go there in a web browser, you should see a Kibana welcome page which will allow you to view dashboards but there will be no logs to view because Logstash has not been set up yet. Let's do that now.

But I cannot connect from browser (windows real-machine) to the kibana interface (on linux machine).
I looking a lot on how configure ubuntu server but I'm probably lost.
Thanks to people that stop here to read my bad english!

A: Usually you would point your browser at http://localhost:9200/ to browse Kibana but you need to work out the IP Address of your VM Box.  You can run ifconfig on the ubuntu box to check the IP Address, which you can then hit.  As per:
https://superuser.com/questions/245156/how-can-i-connect-to-a-web-server-running-in-a-vm-when-the-vm-is-in-nat-mode


text:
Q: Запуск SVG анимации из JS Есть анимация SVG которая запускается при нажатии на кнопку SVG с id="group1":
 begin="group1.click"// тут запуск этой анимация при нажатие на кнопку group1

  <g id="group1" transform="translate(-400 0)">
  <rect id="btn" x="398" y="448" width="48" height="18" rx="5" fill="#d3d3d3"  stroke="grey" />
   <text id="txt1" x="402" y="460" font-size="10" font-weight="600" > Выстрел </text>
 </g>

Как сделать, чтобы эта анимация запускалась с помощью JS при нажатии на кнопку HTML, например:
btn115=document.createElement( 'BUTTON'); // создание кнопки

btn115.id='cmd888';
btn115.innerText = "Запуск анимации";
document.getElementById("container").appendChild(btn115); // нужно чтобы добавилось
btn115.onclick=function(){

}

A: Вариант запуска анимации SVG при клике на кнопку SVG

<svg id="svg1" version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
      width="400" height="400" viewBox="0 0 400 400" >
<!-- Рычаг, который будет вращаться -->

<rect id="rect1" x="100" y="100" width="10" height="100" rx="5" fill="#d3d3d3" />
 <!-- Ось вращения -->
 <circle cx="105" cy="105" r="2" fill="black" />

  <!-- команда анимации вращения -->
  <animateTransform
   xlink:href="#rect1"
  attributeName="transform"
   type="rotate"
   values="0 105 105;90 105 105"
   dur="2s"
   begin="group1.click"
   fill="freeze" />

    <g id="group1" transform="translate(0 0)">
  <rect id="btn" x="190" y="240" width="70" height="25" rx="5" fill="#d3d3d3"  stroke="grey" />
   <text id="txt1" x="198" y="256" font-size="14" font-weight="600" > Выстрел </text>
 </g>
</svg>

Вариант запуска анимации с помощью JS при клике на кнопку добавленную в HTML

<svg id="svg1" version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
      width="400" height="400" viewBox="0 0 400 400" >
<!-- Рычаг, который будет вращаться -->

<rect id="rect1" x="100" y="100" width="10" height="100" rx="5" fill="#d3d3d3" />
 <!-- Ось вращения -->
 <circle cx="105" cy="105" r="2" fill="black" />

  <!-- команда анимации вращения -->
  <animateTransform id="an_revolver"
   xlink:href="#rect1"
  attributeName="transform"
   type="rotate"
   values="0 105 105;90 105 105"
   dur="2s"
   begin="btn10.click"
   fill="freeze" />

</svg>
<!-- Добавляем кнопку -->
<div class="wrap">
 <button type="button" id="btn10"> Запуск анимации </button>
</div>
<script>
<!-- Запоминаем в переменную ID кнопки -->
var btn = document.getElementById('btn10');

<!-- Запоминаем в переменную ID анимации -->
var an_revolver = document.getElementById('an_revolver');

<!-- Функция запуска анимации при клике на кнопку -->
btn.onclick = function () {
an_revolver.beginElement();
}
</script>


text:
Q: What is the best way to present data from a very large resultset? I'm writing a report view of an audit trail, and I need to display this in a .jsp. What's the "best" way to get the data from the database to the screen?
We're using Spring for dependency injection, Data Access Objects, and Hibernate.
I can use hibernate or straight jdbc for this report.
If I load all the records into memory I run out of memory.
Any ideas that don't involve running the query in the jsp?

A: It seems like this is a natural place to use pagination of your Hibernate results -- run the query at the Servlet level, and paginate results in a way similar to how this person describes:
http://blog.hibernate.org/Bloggers/Everyone/Year/2004/Month/08/Day/14#pagination
This is the easiest method of implementing Hibernate pagination I've seen...

A: The Display Tag Library is very good at presenting paginated result sets in servlets or portlets. But it normally works with the whole list loaded into memory. So you will have to do a little work to get it to work with paginated result sets by implementing the org.displaytag.pagination.PaginatedList interface. There is a tutorial on the Display Tag web site. There isn't very much to the tutorial but then again implementing the interface is pretty easy.

A: Just use paging and only load a certain number of rows on the page at a time.

A: Another way to do it is to use scroll() to stream one row at the time.


text:
Q: Data table doesn't refresh I have a canvas app where on one screen I have a data table connected to a SQL server table, which pulls a list of values. When I select a value in that list, it's supposed to take me to another screen that runs a stored procedure, drops the results into a table, and displays the values from the table. Everything except "displays the values from the table" is working.
I know the stored procedure is running and dropping the results into the table, because I can see them when I query the database directly. But the data in the data table on the second screen doesn't change. In my OnVisible property for the screen I have <flowname>.Run(variable, variable); Refresh(<tablename>) but it isn't working as I hoped.
I tried moving both commands to the OnSelect of the first screen which navigates to the second, but I still get the old results in the data table.
Then I tried setting a timer so the data table didn't show until after the flow had run and after the table refresh, but that didn't work as I hoped either.
I don't have a ton of experience with PowerApps, so I suspect it's something I'm doing wrong.
Any help would be appreciated.


text:
Q: how can i implement this Type in typescript? type NeedImplement<T,K extends 'key1' | 'key2'> = {
    code: string
    K: T
}

// example should be work
const type1:NeedImplement<number,'key1'> = {
    code: '1',
    key1: 123
}

Q1:How can i implement this?
Q2:If the default key is 'key1',what else need todo?
Thank you !

A: Yes you can. You have to use two TypeScript features: mapped type and type intersection.
type NeedImplement<T, Keys extends 'key1' | 'key2'> = {
    [key in Keys]: T
} & {
    code: string
}

const type1: NeedImplement<number,'key1'> = {
    code: '1',
    key1: 123
}

Note that you have to use a type intersection because you cannot add properties to a mapped type.


text:
Q: Using Ajax to call the same page makes the body content show twice I'm making an Ajax call to the same PHP page from a link on the page.
For the final code I'll be passing some parameters but for the sake of keeping it simple, I'm not doing that in the code below. Reason I'm using Ajax is to place a "Please Wait" message as it seemed the most effective way to do it (usually you do a call from one page to another, which works perfectly fine).
I do get to see the "Please wait" message accordingly after clicking on the link but it keeps the content of THE  section below the new content being displayed by the Ajax call. So int he example, below, I basically end up with 2 links that say "Click here". How do I make it load just the new content (which in this case is identical)?
This must be simple but I'm not sure what I'm missing here.
PWAIT.PHP

    <?php sleep(3); //To allow for the message to show as I have nothing processing here ?>
    Click here

A: After our discussions, we've discovered that your code is working exactly as it should. It is doing exactly what you ask it to do.

*

*Load the page from the server

*Click button

*Loads the same page via AJAX

*Duplicates the page contents into a div on the page

*Display duplicate contents

That's what you've asked, that's what you've received.


text:
Q: Visual Studio Performance Profiling .Net Core console application shows significant CPU usage by "unwalkable" calls into nvlddmkm.sys I have a .Net Core console application that is single-threaded and CPU bound, so I'm trying to optimize performance. When I run Visual Studio 2019's Performance Profiler and choose the "CPU usage" tool, I get what you see below.
Why is 22% of all CPU time spent in the "unwalkable" calls to nvlddmkm.sys?

Here's my code:
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        var random = new Random();
        const int length = 250;
        var array = new double[length];
        for (var i = 0; i < length; ++i)
        {
            for (var j = 0; j < length; ++j)
            {
                for (var k = 0; k < length; ++k)
                {
                    var index = i + j * k;
                    index %= length;
                    array[index] = random.NextDouble() + array[length - index - 1];
                    array[index] += array.Sum();
                }
            }
        }
    }
}

I noticed that calls into nvlddmkm.sys didn't happen (or at least didn't take as much time) without the Linq Sum.
I searched for what nvlddmkm.sys is. This page says:

Nvlddmkm.sys is a kernel mode driver for the Windows Longhorn project (a codename for Windows Vista) that adds support for shader models 3.0 and 2.0.

So what would Linq have to do with graphics?

A: First of all, those stats are dumb. What you want to know is which lines of your program are responsible for the time, and those stats don't come near telling you. Here's how I do it.
OK, if I'm hazarding a guess (and the first rule of performance tuning is - don't guess),
The new double[] call might show up as a major time-taker, because memory allocation is always suspect, but in this context I doubt it.
More likely, the array.Sum() call
Most likely, the random.NextDouble() call
These last two happen 15,625,000 times.
Everything else in your program is pretty trivial.

A: Did the compiler optimize the code to use matrix operations on the GPU? That could explain the need to talk to a shader DLL.


text:
Q: How to access an attribute of a html tag in views with django I have a html page which uses jinja to display a list.
I want to be able to get the user to click a button and the list will be added to a database. I have put the button in side a form and got it to link to my url which then calls a function.
HTML:
<form method='post' action='../../accounts/myaccount/' name= '{{item}}'>
                                {% csrf_token %}
                                <button type='submit' class='btn'></button>
                            </form>

Views:
def myaccount(request):
    if request.user.is_authenticated():
        if request.method == 'POST':
            product = request.GET.get('name')
            print('product: ' , product)
            return render(request, 'signup/myaccount.html')

The function is called and it prints: product: NONE , whereas i want product to be set to the list.
I know how to add to database within my views but is there a way to actually access my list?

A: You need to use an input tag.
<input name="name" value="{{ item }}">


text:
Q: Python import from parent directory for dockerize structure I have a project with two applications. They both use a mongo-engine database model file. Also they have to start in different Docker containers, but use the same Mongo database in the fird container. Now my app structure looks like this:
app_root/
   app1/
      database/
         models.py
      main.py
   app2/
      database/
         models.py
      main.py

And it works fine, BUT I have to support two same files database/models.py. I dont want to do this and I make the next structure:
app_root/
   shared/
      database/
         models.py
   app1/
      main.py
   app2/
      main.py

Unfortunately it doesnt work for me, because when I try this in my main.py:
from ..shared.database.models import *

I get
Exception has occurred: ImportError
attempted relative import with no known parent package

And when I try
from app_root.shared.database.models import *

I get
Exception has occurred: ModuleNotFoundError No module named 'app_root'

Please, what do I do wrong?

A: In the file you perform the import, try adding this:
import os
import sys
sys.path.append(os.path.abspath('../../..'))

from app_root.shared.database.models import *


text:
Q: Context Variables in WAR file of a Talend job I have designed a job in talend to copy data from Excel sheet to SQL server tables. In my job I am using context variables for database connection and excel file location.
I am exporting my job as a Web Service (WAR) file. Now if I want to run a job with different database or with different excel file how do I change default values of context variables?

A: there are many ways to do this..you can either do context load from flat file using option of implicit context load from file, database options at job settings (Extra) tab in talend. you also have talend component to load contexts during job execution.
you can also add new context configurations to existing context groups and while export your job you can select one of those context configurations to be used...like create dev, test and prod configuration and while exporting job for test you can use test configure context..


text:
Q: Are static members slower to access than instance members in AS3? Are static members slower to access than instance members in AS3?

A: So they say...
This guy has made some benchmarks, which you might find interesting:
http://blog.controul.com/2009/04/how-slow-is-static-access-in-as3avm2-exactly/


text:
Q: d3: Animate bar chart transforming into pie chart, like Heer and Robertson do? How difficult would it be to use d3 to create animations like those found in this study?  In particular, animating a bar chart into a donut chart into a pie chart smoothly?
The idea I had was to start by replacing the "rect"s in the bar chart with "path" elements formed fromn d3.svg.arc -- using an arc with a huge radius, but only taking wedge of it, so that it was looks almost like a "rect" but slightly curved.  Once that replacement is done, then you can animate the radius and angle of the arc in the "path" element and move it into the donut shape that you want.  The final transition from donut to pie would be trivial, simply animating the innerRadius.
However, I'd like to know if there is a better way to accomplish this, or perhaps some plugins that have already been written?

A: This example has (almost) the transition that you're looking for.


text:
Q: Does Windows XP has any compression program by default? I would like to compress a database backup file on Windows.
I wonder if Windows XP has by default any program (like WinZip) that I can use.
If yes, where is it located ?
If not, could you suggest a light program that does the task ?

A: This question belongs on superuser.com, however my favorite compression program is 7zip http://www.7-zip.org/

A: Yes, XP includes a compression program.  Right click on the desktop and choose New -> Compressed (zipped) Folder.  You should be able to copy your database into that new file as if it were a folder.
However, this is pretty basic compression.  You'll do a lot better by downloading something like 7zip.


text:
Q: What test to use to compare two sets of data. One only knowing mean and quantity I have two methods that generate either a pass or a fail on input data. I want to know if statistically there is any difference between the two?
For the first method I only have the mean (0.75) and the number of data points (80k). For the second I have the complete list of data points (around 100). Each data point is either a 1 or a 0 (Pass/Fail).


text:
Q: Install ruby for all users on ubuntu I installed the ruby on rails by https://gorails.com/setup/ubuntu/18.10.
It's successfully installed on current user.
When I changed the user, for example root, ruby and rails is not installed.
How can I make ruby & rails working on all users?

A: I'm assuming you are installing Ruby using Rbenv method from the GoRails guide. Take a look at This Q/A.
I also wanted to use system-wide ruby for different user and used the above method(despite the warning that Rbenv is not suitable for system-wide configs), and it worked in some way, but I had problems using it for other projects with different users.
So the workaround I use is to install Rbenv each for a different user. It takes some disk space, but things will work smoothly. Also, DO NOT install it as a root user or in the /root folder as this will break things when you work with rails with different users.


text:
Q: Geometric interpretation of $\frac{dr}{d\theta}$ in Cartesian Coordinates You'll have to excuse me if this questions is extremely trivial; it's been years since I went back to elementary calculus and I humbly accept that I haven't really gotten deep into polar equations/coordinates during my college years.
That, or I'm going coocoo studying this at 1 AM on a Saturday night.
Suppose I'm given a polar equation $(r,\theta)$ where $r$ is a function of $\theta$. I want to know the geometric interpretation of $\frac{dr}{d\theta}$ to the slope of the curve generated by the equation.
I'm aware that $x = r(\theta)*Cos(\theta)$ and $y = r(\theta)*Sin(\theta)$ such that we can find the slope of the curve from: $$\frac{dy}{dx} = \frac{\frac{dr}{d\theta}*Sin(\theta)+r*Cos(\theta)}{\frac{dr}{d\theta}*Cos(\theta)-r*Sin(\theta)}$$

*

*Are there more geometric significance from $\frac{dr}{d\theta}$ to the curve beyond just how "fast" $r(\theta)$ shinks or expands from the origin?

*Knowing $\frac{dy}{dx}$ just from looking at the curve, are there methods to estimate $\frac{dr}{d\theta}$ beyond plugging in the equation above or converting $r(\theta)*Cos(\theta) \rightarrow x$ and $r(\theta)*Sin(\theta) \rightarrow y$

A: Draw a particle in the plane at a point with polar coordinates $(r_0,\theta_0)$, and draw the circle $x^2+y^2=r_0^2$. Now allow the particle to move along a curve $(r(t),\theta(t))$ for a small time $\Delta t$ such that from $t\rightarrow t+\Delta t$, the curve is approximately linear and the polar coordinates are now $(r_0+\Delta r,\theta_0+\Delta \theta)$.
If you do this the curve makes an angle $\alpha$ with the circle $x^2+y^2=r_0^2$ and if you draw the picture you will see that
$$\tan\alpha=\frac{\Delta r}{r_0\cdot \Delta \theta}\Rightarrow \frac{dr}{d\theta}\approx r\tan \alpha.$$
If you can't draw this picture get back to me.


text:
Q: ¿Cómo enviar archivo por Discord.py? estoy terminando de crear el bot de discord usando discord.py
Y lo que quiero que haga es que envié un archivo txt
Ejemplo

Usuario: ff!nitro
Bot: Aqui estan los codigos
(MANDA ARCHIVO)

Este es mi codigo
@client.command()
async def nitro(ctx):
   archive = "Dirección del Archivo"
   await ctx.author.send(Archive)

El problema es que envia la dirección y quiero que se envie asi como un usuario normal enviaría el mensaje de un archivo
Agradezco de ante mano su ayuda

A: La solución sería la siguiente
(EL ARCHIVO DEBE DE ESTAR EN LA MISMA CARPETA QUE EL CODIGO)
@client.command()
async def nitro(ctx):
   await ctx.author.send(file=discord.File('NOMBRE DEL ARCHIVO.txt'))

Gracias a todos


text:
Q: Android FrameLayout Views Overlapping not Working I Have the following layout and I need the favorite image to placed on the upper right corner of the itemImage using FrameLayout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ItemDetails"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingBottom="20dp">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/itemdimage"
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:scaleType="fitEnd"
                tools:srcCompat="@mipmap/ic_launcher"
                />

            <ImageView
                android:id="@+id/favorite"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="end"
                android:layout_margin="10dp"
                tools:srcCompat="@mipmap/ic_launcher_round"
                android:elevation="10dp"/>

        </FrameLayout>

But the favorite image is never show ??  what is wrong with my layout
Any help will be much appreciated

A: Maybe this layout will work. I changed tools:srcCompat to android:src. tools: attributes are only visible in AndroidStudio, they are removed from the build.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingBottom="20dp">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/itemdimage"
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:scaleType="fitEnd"
                android:src="@mipmap/ic_launcher"/>

            <ImageView
                android:id="@+id/favorite"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="end"
                android:layout_margin="10dp"
                android:elevation="10dp"
                android:src="@mipmap/ic_launcher_round" />

        </FrameLayout>
    </LinearLayout>
</ScrollView>

The result is this :


text:
Q: File API base 64 encoding for multiple images from html page to servlet Basically my requirment is that I have to upload 4 to 12 small icons(6kb) and 15-20 medium size icons (say 200kb) icons.
I have an html page that uploads multiple image using base 64 encoding to servlet using POST request. This base 64 string is converted into bytes to create image in server side code.
The POST request works fine to upload any no of small sized images(7kb) and 6-7 medium sized icons(200 kb). But when I am uploading more than 8 medium sized icons, the html page fails to carry data from html page to servlet. Even in my servlet when I do (sipReq.getParameter("name"))for other attributes the values are getting as null.
Please help for possible solution or I should look for some other alternative.

A: Apache Commons' FileUpload may well be the solution for you - I've had no problem with multiple, multi-megabyte simultaneous document uploads on Tomcat thanks to its multi-part support, as hinted at by @Sean.
If you're already using Spring MVC, it can be as simple as adding a single extra bean.


text:
Q: GIMP plugin to change ticket number and export image automatically I have designed a ticket which includes a sequential ticket number (001,002,003...500) and now I have to export each and every ticket number as a separate PNG image.
This is a lot of manual work and I'm asking if there is a plugin or script that I can use to do this automatically - something I can give the text layer to change incrementally then export the image.
EDIT
This is my ticket.
The ticket number is at the left side corner - 2014/001 -> 2014/500
Image size: 2858px by 1000px
The ticket number font is Dirt2 SoulStalker

A: I think I got it working.

The procedure is that you put the background image (named "background.png", the ticket without the number, but with 2014/) in a folder, together with the script below. Then, if you run the script (after editing the three lines in the head section):

*

*The script produces numbers from 001 to 500 (but it can be any number you define in the head section)
Subsequently , using imagemagick:

*the script creates (number by number) separate layers (files) with the number in the right position

*it copies the background layer + number layers into a new file, saved in the same folder, for each number.

*the script then removes the (temporary) additional layers

Notes

*

*You may have to install imagemagick:
sudo apt-get install imagemagick

*I used this free version of the font. It turned out that in the script, I had to set the absolute path to the font for it to work. I just copied it to ~/.fonts and used that path. In the head section of the script, set yours.
The script:
#!/usr/bin/env python3

import subprocess
import os

curr_path = os.path.dirname(os.path.abspath(__file__))

#---
number_of_tickets = 5
bg_file = curr_path+"/"+"background.png"
font = '/home/jacob/.fonts/dirt2 soulstalker.otf'
#---

def command(string, layer, position):
    return "convert -size 2858x1000 xc:None -fill black -font "+'"'+font+'"'+\
           " -stroke None -fill white -pointsize 123 -style Normal -gravity west -draw "+\
           position+"'"+string+"'"+'" '+layer

def print_tofile(string, number):
    print("creating file "+number+"."*3)
    layer_1 = curr_path+"/"+number+"_a.png"
    layer_2 = curr_path+"/"+number+"_b.png"
    cmd_1 = command(string, layer_1, '"text 497,-420 ')
    cmd_2 = command(string, layer_2, '"text 1035,-420 ')
    subprocess.call(["/bin/bash", "-c", cmd_1])
    subprocess.call(["/bin/bash", "-c", cmd_2])
    cmd_3 = "convert "+bg_file+" "+layer_1+" "+layer_2+\
            " -background None -layers merge "+curr_path+"/"+number+"_ticket.png"
    subprocess.call(["/bin/bash", "-c", cmd_3])
    os.remove(layer_1)
    os.remove(layer_2)
    print("done")

ns = [str(n) for n in range(number_of_tickets+1)][1:]

for item in ns:
    number = str(int(3-len(item))*"0")+item
    string = number
    print_tofile(string, number)

How to use
Copy it into an empty file, in th head section of the script, set:

*

*the number of tickets

*the (absolute) path to the font

*the name of the background image (ticket without numbers) if you want to change it

and save it as numbering.py, together with your background image (2858px by 1000px), named background.png in one and the same folder.
Run it by the command:
python3 /path/to/script.py


text:
Q: Submitting a JSONP to a PHP As part of my application, I want to submit a JSON object to a PHP script which returns a JSON response. The domain is not following the same-origin policy, i.e., the JSON is submitted from a different domain, so after doing some research, I understand that I need to use JSONP. After spending more than 10 hours now, I can't think of any other solution. Can anyone help me to understand where my problem is?
Javascript snippet:

var jsondata = {
        "variablA": "valueA",
        "variables": {
            "variableB": "valueB",
            "variableC": "valueC"
        };

        var encodedjson = JSON.stringify(jsondata);

        $.ajax({
            url: 'update.php',
            type: 'POST',
            contentType: 'application/json',
            dataType: "jsonp",
            data: {
                "data": encodedjson
            },
            success: function(data) {
                alert(data);
            },
            error: function(xhr, ajaxOptions, thrownError) {
                //On error do this
                $.mobile.loading('hide')
                if (xhr.status == 200) {

                    alert(ajaxOptions);
                } else {
                    alert(xhr.status);
                    alert(thrownError);
                }
            }
        });

PHP:

$array = json_decode($_REQUEST['data'], true);

$valueA = $array['variableA'];
$valueB = $array['variables']['variableB'];
$valueC = $array['variables']['variableC'];

$values = array('variableB' => $valueB, 'variableC' => $valueC);

$respencode = array('variableA' => $valueA, 'variables' => $values);

header('Content-type: application/json');
echo json_encode($respencode);

A: For Ajax to know that it is dealing with a jsonP request, You need to rewrite the url with a callback query string like So :
url: 'update.php?callback=?'


text:
Q: C# MongoDB.Driver : How to see if server is connected. GetServer Replacement GetServer is gone for good. How do i check if the server is connected or even exists?
Example code:
// This server exists
var exists = new MongoClient("mongodb://192.168.2.109:27017");

// This server does not exist
var doesNotExist = new MongoClient("mongodb://194.168.200.129:27017");

// Both states return "Discennected"
var connStateExisting = exists.Cluster.Description.State;
var connStateNotExisting = doesNotExist.Cluster.Description.State;

// GetDatabase("name") works for both without errors.

How can i check if a server can be connected?

A: The Cluster.Description.State does not update immediately. When i checked, it was updated after roughly 100+ milliseconds. The driver contains a connection pool and it seems to do quite a lot asynchronous.
However, the Cluster-property has a "DescriptionChanged"-event that is fired once the connection is done.
If someone else has any knowledge about connections and timeouts, please share it.


text:
Q: Writing a file to external storage android FileNotFoundException I want to write a file to external storage in android but get the FileNotFoundException. I have put the permission
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

in my manifest and if I do a check like
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)

it returns true. I have tried different solutions from questions from SO (Android saving file to external storage; Write a file in external storage in Android; Writing to external storage filenotfoundexception) but none seemed to work for me. Sorry for posting a duplicate question but Ive been searching for days and couldnt find an answer.
My Code is the following:
private void Writing(String erg) {

        TextView one = (TextView) findViewById(R.id.e1);

        File root = android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);

        File dir = new File (root.getAbsolutePath());
        dir.mkdirs();
        File file = new File(dir, "Test.txt");

        try {
            FileOutputStream f = new FileOutputStream(file);
            PrintWriter pw = new PrintWriter(f);
            pw.println(erg);
            pw.flush();
            pw.close();
            f.close();
            one.setText("File created");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            one.setText("Error1");
        } catch (IOException e) {
            e.printStackTrace();
            one.setText("Error2");
        }

    }

The Textview one ends up with printing Error1.
I'll appreciate any help.


text:
Q: Cannot connect to iTunes Store with newly created sandbox tester For an app that I'm making, I'm including in app purchases and when testing it in the past it always seemed to work besides this morning. I started getting the error: Cannot connect to iTunes Store. I get the error after the IAP prompts me to log in. I created a new sandbox tester and the same thing happens. I'm definitely putting in the correct username and password because when I purposely put the wrong one it tells me through a popup.
I see that its green on https://developer.apple.com/system-status/
Also, I'm testing it on a real device and I make sure that I'm logged out of iTunes before running the app. I've tried restarting my device as well.
Any idea on how I can fix this? Any help would be greatly appreciated!
Thanks in advance!

A: After a lot of searching, I was able to find the answer online:
https://forums.developer.apple.com/thread/90594
It was posted by: neilc
This is what worked for me in the end:
-Create a new iTunes Sandbox user. Do NOT verify the email address.
-Sign out of the App Store on your device.
-Begin your purchase flow.
-When prompted, tap Use Existing Account.
-Login with your new Sandbox user.
-You will be prompted to log in again—DON'T! I cannot stress that enough.
-Hit Cancel.
-Background the app.
-Foreground the app.
-Begin your purchase flow again.
-This time, you will be prompted for your Sandbox user's password (the email address will be shown in the prompt).
-Enter your password.
-Continue through the In-App Purchase flow. Purchases will succeed this time around.
If you check your App Store settings on your device, you will notice the Sandbox user is logged in. DO NOT SIGN OUT or you will invalid the Sandbox user and you will have to repeat the above steps from the beginning.

A: Apple has this poorly documented. Basically, you shouldn't log in with your sandbox user from settings. Log in when actually prompted by your test IAP.


text:
Q: Do server-side encrypted files in S3 get transitioned to AWS Glacier? Question:
Do server-side encrypted (with S3 managed or KMS managed keys) files get transitioned to Glacier ?
If yes, are they decrypted using S3 or KMS key and then encrypted again using Glacier's internal key as all objects in Glacier are encrypted using an internal AES 256 keys ?
Problem statement:
I have some files in S3 encrypted using KMS managed key. I have a lifecycle rule to archive to Glacier after 1 day, but the files still show Storage class as 'Standard' even after 3 days.

A: I checked in AWS docs and forums, but could not find a direct answer to this question.
But what I found was, even the CRR does not handle SSE-C and SSE-KMS encrypted objects (under what is not replicated section). Hence I would assume the transition rule also cannot handle SSE-C and SSE-KMS encrypted files as Glacier supports only AES-256 encryption.
Link for AWS Replication Documentation

A: There is nothing in the documentation to suggest that storage class changes from lifecycle policies are incompatible with SSE-KMS.

On archive, S3 objects are moved as is (in SSE-KMS encrypted form) to Glacier, encrypted by Glacier again.
  View Thread RSS Feed View Thread RSS Feeds
— susan@aws https://forums.aws.amazon.com/thread.jspa?messageID=786916

S3 apparently does not decrypt and re-encrypt, but rather appears to simply encrypt the encrypted version of the object again, so SSE-C should also be compatible.
Note that lifecycle policies require between up to 24 hours before they actually begin transitioning objects, and new objects will match a "1 day" rule between 24 and 48 hours after the object's initial creation.
If there is a large number of objects, you might want to use aws-cli to try to see if any objects have migrated.
aws s3api list-objects [options] --output-format=text | grep GLACIER

A: My lifecycle rules had filename-specific prefix like 'com/folder-name/Daily-'. I created new lifecycle rules so that they end with last parent folder-name and a trailing slash 'com/folder-name/'.
After this change and waiting for 24+ hours, both un-encrypted and SSE-kms encrypted files got transitioned to Amazon Glacier.
After transition, I do understand they both got encrypted internally using Glacier managed keys as documented in this FAQ. https://aws.amazon.com/glacier/faqs/#security.


text:
Q: How to test PHP socket TCP/IP Server using Terminal/PHP? I have a server up online, and I made a simple TCP/IP Server using PHP to handle a certain port. The code I use is found below:
<?php
error_reporting(E_ALL);

/* Allow the script to wait for connections. */
set_time_limit(0);

/* Activate the implicit exit dump, so we'll see what we're getting
* while messages come. */
ob_implicit_flush();

$address = '123.456.789.123';
$port = 1234;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

//clients array
$clients = array();

do {
    $read = array();
    $read[] = $sock;

    $read = array_merge($read,$clients);

    $write = NULL;
    $except = NULL;
    $tv_sec = 5;

    // Set up a blocking call to socket_select
    if(socket_select($read, $write, $except, $tv_sec) < 1)
    {
        //    SocketServer::debug("Problem blocking socket_select?");
        echo "socket continuing";
        continue;
    }

    // Handle new Connections
    if (in_array($sock, $read)) {

        if (($msgsock = socket_accept($sock)) === false) {
            echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
            break;
        }
        $clients[] = $msgsock;
        $key = array_keys($clients, $msgsock);

        $msg = "\Welcome to the PHP Test Server. \n" .
        "You are the customer number: {$key[0]}\n" .
        "To exit, type 'quit'. To close the server type 'shutdown'.\n";
        socket_write($msgsock, $msg, strlen($msg));

    }

    // Handle Input
    foreach ($clients as $key => $client) { // for each client
        if (in_array($client, $read)) {
            if (false === ($buf = socket_read($client, 2048, PHP_NORMAL_READ))) {
                echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($client)) . "\n";
                break 2;
            }
            if (!$buf = trim($buf)) {
                continue;
            }
            if ($buf == 'quit') {
                unset($clients[$key]);
                socket_close($client);
                break;
            }
            if ($buf == 'shutdown') {
                socket_close($client);
                break 2;
            }
            $talkback = "Client {$key}: You said '$buf'.\n";
            socket_write($client, $talkback, strlen($talkback));
            echo "$buf\n";
        }

    }
} while (true);

socket_close($sock);
?>

The script just basically runs and allows for more than one connection to run. After uploading the code to the server, I connected to the server, got to the directory where the file is, and then ran php filename.php. It does not show any warning or errors.
However, I need to further configure this TCP/IP Server and do things based on the input it receives. Right now, when I run php filename.php, it doesn't show anything (I'm guessing because all the outputs are written to the socket, and not echoed).
How do I test this TCP/IP Server that I made? telnet is out of the question since it's not secure. Right now I'm looking for nothing too complicated, so the Terminal or another simple PHP File would be a good choice.

A: I would try to use react/socket for your testing purposes. It allows to create clients and servers pretty fast. Try this client code just to get started:
<?php

require_once __DIR__ . "/vendor/autoload.php";

$loop = React\EventLoop\Factory::create();
$connector = new React\Socket\Connector($loop);

$connector->connect('127.0.0.1:1234')->then(function (React\Socket\ConnectionInterface $conn) use ($loop) {

    $conn->on('data', function ($data) use ($conn) {

        echo $data;

        $conn->close();
    });
});

$loop->run();

The documentation is here.


text:
Q: Find the indices of values fulfilling condition in 2d numpy array I have a 2D array of values and I'd like to find the indices at which the values are more than 60% of the maximum value.  I have tried:
: nmax, nmin = np.amax((n[:,:])),np.amin((n[:,:]))
: np.unravel_index(n[n>0.6*nmax], n.shape)

But I get the error:
TypeError: Iterator operand 0 dtype could not be cast from dtype('>f4') to dtype('int64') according to the rule 'same_kind'

Any insight would be appreciated.

A: As mentioned above use np.where() like this:
    x = np.random.randint(0,50,(20,20))
    y = np.where(x>0.6*np.max(x))

y will be given as a tuple with two arrays representing the two axes of the array and you can use y however you need to for example x[y] will return the values of x all of which will be greater than 0.6*max.


text:
Q: Best way to store large data clientside in an gwt offline application? We have written an Vaadin7/GWT application where the user can select multiple images and upload them. The application works offline, so we want to store the images clientside and only upload them when the user is pressing the sync button. The clue is that we want to keep the selected images, even when the user is closing the Tab/Browser. The clientside storage should also work with mobile browsers (Android and iOS)
We have found the following possibilities to store data on the client
Session Storage is killed when the tab/browser is closed. Not suited for our case.
Local Storage is limited to 5MB which is not enough. Is there a way to extend that limit?
IndexedDB does not work on IOS devices (http://caniuse.com/indexeddb)
WebSQL does work on IOS and Android devices (http://caniuse.com/sql-storage) but is deprecated
So the question are. Does anyone know a good Frameworks in conjunction with gwt? Which storage type/DB would you prefer and why? Or even more general, how would you solve the Problem?
Thanks for any advice, suggestion or experiences you had.

A: Unfortunately, there is no magic solution for all operating systems/browsers. I believe that you your only option for large objects is to build native apps for each platform that use a web browser for their client.


text:
Q: How terminate a thread while I using WaitForMultipleObjects I have a secondary thead (TMyWaitFor) on my application which executes a few worker threads (TFooThr) and wait for the finalization of these threads using the WaitForMultipleObjects  function
this is the relevant code
const
 nThreads=5;
//these arrays are declarated in the private section of the TMyWaitFor thread
 tArr  : Array[1..nThreads]  of TFooThr;
 hArr  : Array[1..nThreads]  of THandle;

procedure TMyWaitFor.Execute;
Var
 i     : Integer;
begin
  for i:=1  to nThreads do
   begin
     tArr[i]:=TFooThr.Create(AValue);
     hArr[i]:=tArr[i].Handle;
   end;

  WaitForMultipleObjects(nThreads, @hArr[0], True, INFINITE);
end;

All works ok , but now In some situations, I can't wait for the threads (TFooThr) and I need cancel the operation, so I need to stop (terminate) all the threads which I started in the TMyWaitFor.Execute , so the quesion is How I can terminate all TFooThr threads started the Execute method of the TMyWaitFor thread?

A: As David suggested, call Terminated on the thread and change your code to check the terminated flag regularly:
procedure TMyWaitFor.Execute;
Var
  i     : Integer;
begin
  for i:=1  to nThreads do
  begin
    tArr[i]:=TFooThr.Create(AValue);
    hArr[i]:=tArr[i].Handle;
  end;

  while not Terminated do
    //wait half a second
    if WaitForMultipleObjects(nThreads, @hArr[0], True, 500) <> WAIT_TIMEOUT then
      Break;
end;

Update 2011-08-03
David and Serg are correct I'm afraid and I am incorrect. In TFooThr.Execute you should be checking for Terminated. In the main thread of your application, you can call Terminate on all the TFooThr's to kill them, and as long as they are taking notice of the Terminated flag, then TMyWaitFor will fall through all by itself.
You should remove your acceptance of this answer.
N@


text:
Q: how to solve piecewise linear programming equation in Python? My objective function is:
f(x) =  a*500*pricecat_x + b*500*pricecat_y
where pricecat_x is
1300, where 0 < x_quantity <= 250
1400, where 251 <= x_quantity > 500
and pricecat_y is
1420, where 0 < y_quantity < 400
1390, where 401 < y_quantity <= 500
allowable range of x_quantity is (250, 400)
allowable range of y_quantity is (100, 250)
I've written my code as below.
My aim is to optimise a and b, which is the amount of x, and y.
I hit a road block when running the line below:
 problem += - a*Q_demand*pricecat_x - b*Q_demand* pricecat_y

Traceback (most recent call last):

  File "<ipython-input-120-207ebdebfbb6>", line 1, in <module>
    problem += - a*Q_demand*pricecat_x - b*Q_demand* pricecat_y

  File "C:\Anaconda\envs\tfflow\lib\site-packages\pulp\pulp.py", line 790, in __mul__
    if other != 0:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

wondering if anyone could teach how to perform piecewise linear programming in Python?
Many thanks.
import numpy as np
from pulp import *
problem = LpProblem("Volume Aportionment", LpMaximize)

## Constants
# Supplier 1

VA_xmin = 0.5   #min VA - Supplier 1
VA_xmax = 0.8   #max VA - Supplier 1

# Supplier 2
VA_ymin = 0.2   #min VA - Supplier 2
VA_ymax = 0.5   #max VA - Supplier 2

Q_demand = 500

# Pricing Tiers
P1 = np.linspace(0, 500, 51)
pricecat_x = np.piecewise(P1, [P1 <= 250, P1 >= 251], [1324.17, 1309.17])

P2 = np.linspace(0, 500, 51)
pricecat_y = np.piecewise(P2, [P2 <= 400, P2 >= 401], [1419.09, 1394.09])

#pricecat_x = 1305
#pricecat_y = 1342

# define Variables
a = LpVariable(name = "VA1", lowBound=VA_xmin, upBound=VA_xmax, cat="Continuous")
b = LpVariable(name = "VA2", lowBound=VA_ymin, upBound=VA_ymax, cat="Continuous")

# constraints
problem += (a+b)*Q_demand >=500

# objective function
#problem += - weight_x*pricecat_x - weight_y* pricecat_y
problem += - a*Q_demand*pricecat_x - b*Q_demand* pricecat_y

print(problem)

# solving
problem.solve()

for v in problem.variables():
    print(v.name, "=", v.varValue)


text:
Q: Multiple divs with the same id invalid? I am developing a wysiwyg page using javascript (no libraries) and because it has a fairly specialised application it has to be custom built rather than off-the-peg.
I have,  surprisingly,  got a long way and it is pretty much complete but I am having some difficulty getting the display right.
I have a div which contains text and images with the images floated right so the text flows around them.
In some places I need the images centred,  so I have inserted a div to contain them.
The code bellow illustrates this and it works well.
The problem arises if I have more than one div containing the centred images because the ID of those centreing divs is the same.
If I change the centreing divs to a class the images don't centre but assume the right float of the parent div.
Is there any way to overcome this?
Is there any real issue having multiple divs with the same id?
I'm not worried about supporting any browsers other than FF.
Any advice would be very greatly appreciated,  thanks for reading.
Dim Tim   :o)
#details {
    width: 698px;
    background-color: #FFC;
}

#details img {
    float: right;
}

.centreimage img {
    float: none;
}

.centreimage {
    float: none;
    text-align: center;
}

Some text here

Which flows around the image on the right

blah

blah

blah

blah

blah

blah

The next image should be centred

more text

more text

Thank you all for your help.
Even when I changed the CSS and HTML to be a class the images still failed to centre.
The answer was in the clue from Pekka and specificity was the cause.
The specificity rules give an ID a higher priority than a class.
The "details" div had an ID but the "centreimage" was a class.
I changed the CSS for "details" to a class (& the markup of course) and it now works.
Can't believe that I spent at least 10 hours trying to sort that out so thanks to everyone for their help.
(Now you know why I am "Dim Tim")  :o)

A: Yes, it's invalid to have multiple divs with the same id.
Using a class should work fine:
div.details {
    width: 698px;
    background-color: #FFC;
}

If those rules really get overridden, you probably have another rule in place that has higher  specificity. In that case, you would have to show us more of your HTML.

A: You shouldn't have more than one element with the same id. This is invalid and will give undefined results.
If you change your div id to a class, you need to change the CSS appropriately to target the class rather than the id. The purpose of CSS classes is exactly that - targetting multiple, related elements and applying the same styles.
As long as you are targetting the elements correctly, there will be no difference to the result.

A: As you should know every id should be unique. In your example output seems to be a small error. Try to set the class attribute to the div and not the image. If you don't have dome good reasons you should better everytime the class attribute.
Now is the text-align set for the children of your image e.g. that would be the alt value if the image could not be loaded.


text:
Q: Debug mode linkage fails due to unsigned int initialization in header As far as I know all integer types can be initialized in the header file.
That's why I felt that this kind of declaration was correct in one of my headers (lets call it foo.h):
class Foo {
public:
  static const unsigned int DEFAULT = 0xffffffff;
  ...
};

And it worked, when compiling and linking in release mode.
However, when I compiled the code in debug mode I got the following error:
undefined reference to `Bar::Foo::DEFAULT'
collect2: ld returned 1 exit status

When I moved the initialization to foo.cpp the problem was solved:
const unsigned int Foo::DEFAULT = 0xffffffff;

But I don't understand why. Can somebody guess?
(I use gcc 4.2.4 on Ubuntu)

A: You've initialized the member but not defined it. You still need the const unsigned int Foo::DEFAULT; in a single implementation file.
In a release build, references to the member are probably optimized away (i.e. replaced inline with the value since you're telling the compiler it isn't going to get changed) so no symbols are looked up. Debug isn't that lenient - the compiler now wants to know that your member is defined and resides somewhere in memory.


text:
Q: Forward slash in Gitignore files I came across a very weird thing about gitignore files that they happen to use forward slash for denoting a particular directory
Project/module1/cppfiles

Rather than the usual backslash normally used in command prompt  for denoting a particular directory.
Project\module1\cppfiles

Is this completely syntactical or it has some reason behind it?

A: I soonly found a windows documentation, compare here, which tells:
Windows users: All file paths in the .gitignore file use a forward slash separator and not a backslash.

git uses forward slashes in the .gitignore for compatibility with unix syntax, where you separate folders by forward and not by backward slash. This probably is related to two things:

*

*git mostly is running on linux servers, so this must not be catched on server side, only on client side

*(probably) a lot of the people using git are using unixoid systems, therefore only a few are using backward slashes - only few people have to change behaviour to work together with all others

A: It's because Git was originally written to run on Linux, and the / is the path separator for Linux.
The forward-slash paths will work fine in Windows.  In fact, in many places in Windows, if you type your paths with forward slashes, it'll correct them for you automatically.


text:
Q: Reference clock in FM receiver chips (si4735) The datasheet is mentioning a 32678 Hz "reference clock" (RCLK) input.
It appears to be a well known thing in this type of ICs because it's highlighted in the list of features.
I guess because it's obvious to everyone they don't explain what this reference clock is used for. They mention some clocking mode (besides FM mode) it's used in, but it's not clear what it is.
What is the purpose of this reference clock (RCLK) signal?
Is it a PLL reference for the heterodyne?

A: For an ultra-low-power design, only low-frequency crystals are usable, because with the frequency increase the current consumption increases significantly. The article The Strengths of 32.768 kHz Oscillators is undoubtedly a commercial, but I venture to mention it because the article excels, first of all, the technological advantages of generic tuning fork crystals.
Their chief application being RTC circuitry, the tuning fork crystals operating at 32.768kHz, due to their excellent short-term, long-term and temperature stability and low power consumption, govern also the other time-critical functions of many common devices, among those are frequency synthesizers. The frequency synthesizer is an essential component of modern radio transceiver chips.