text:
Q: How to get the values picked from angularjs modal in textbox? In Angularjs I want to show the values in textbox picked from modal in ng-repeat. How can I do this?

A: In html view:
<input ng-model="batchno_qty[$index]">

In controller:
$scope.show_qty=function(item_id,index){
$scope.current_index=index;
$scope.batchno_qty1=[];
var modalInstance = $modal.open({
            templateUrl: 'opportunities/show_qty_popup.php',
        controller: pick_supplier,
        scope: $scope,
        resolve: {current_index: function () {
                    return $scope.current_index;
                  }
                }
    });
    modalInstance.result.then(function (response) {
        $scope.response=response;
        $scope.batchno_qty=[];
     });
    }

    function pick_supplier($scope, $modalInstance,current_index)
    {
     $scope.batch_select=[];
     $scope.selected_qty=[];
    $scope.pick_qty = function (itemid) {
        $scope.array_qty=[];
        $scope.pick={};
        if($scope.batch_select.length==0)
        {
            Notification.error("No Batch no. is selected.");
        }
        else
        {
            for (var i = 0; i < $scope.batch_select.length; i++)
            {
                if($scope.batch_select[i]==undefined)
                {
                    //Notification("your Batch no. is undefined.");
                }
                else
                {
                    if($scope.selected_qty[i]==undefined)
                    {
                        Notification("Please enter quantity.");
                    }
                    else
                    {
                $scope.pick[$scope.batch_select[i]]
                  =$scope.selected_qty[i];

                    }
                }
            }
        }
                    $scope.total_pick=0;

        $scope.set=1;
        supplier_result.itemid=itemid
        $modalInstance.close($scope.pick);
      }
     }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I echo out table  horizontally instead of vertically with while-loop? My code echoing the table vertically and thats not what I want.
I have been trying to get it to work the way I want it to but I find it very hard to find a solution becasue of the while loop forcing the table to be vertically.

<?php
            while($row = mysqli_fetch_array($result)){

              echo "
$row['user']
";
             }
?>

A: As the comment says, a
 is a Table Row, which means it will create a new row vertically when displayed. The code below puts everything in one row, which will display it horizontally.

<?php
            while($row = mysqli_fetch_array($result)){

              echo "$row['user'] 	";
             }
?>

A: As Subin Thomas stated in the comment, tr is used for rows, so basically, they will be vertical. The tds inside the row will be horizontal. So, to achieve what you want, you may use this code:

        <?php
            while($row = mysqli_fetch_array($result)){
                echo "$row['user'] 	";
            }
        ?>

What we did, is move the tr out of the loop, and loop only the tds.


text:
Q: How to prompt android users to save the contact details directly into their Android device from a vCard file (vcf) I am trying to create a digital card system and trying to save a vcf file into an Android phone which should prompt the user to save contact details directly into their Android device. The following code is working on iPhone but not on Android devices.
<script>
  var saveBtn = document.getElementById("save-btn");
  saveBtn.addEventListener("click", function() {

    var contact = {
      name: "<?php echo $row["fullname"]; ?>",
      phone: "<?php echo $row["phone"]; ?>",
      email: "<?php echo $row["email"]; ?>",
      company: "<?php echo $row["company"]; ?>",
      socialpro: "<?php echo $row["city"]; ?>"
    };

    var vcard = "BEGIN:VCARD\nVERSION:4.0\nFN:" + contact.name + "\nTEL;TYPE=work,voice:" + contact.phone + "\nEMAIL:" + contact.email + "\nEND:VCARD";

    var blob = new Blob([vcard], {
      type: "text/vcard"
    });
    var url = URL.createObjectURL(blob);

    const newLink = document.createElement('a');
    newLink.download = contact.name + ".vcf";
    newLink.textContent = contact.name;
    newLink.href = url;

    newLink.click();

  });
</script>

My work so far
Please click on this link and you can able to save the contact on iPhone but it's not working on Android (http://mycontacts.unaux.com/displaycontact1.php?employee_id=1&genlist=list&i=4)
Working website
Please see the sample website (https://digicard.ae/oksana) and when you will click on Save to Contacts it's working for both Android and iPhone.

A: The issue you're encountering with this code on Android devices may be related to the way that Android handles the download and saving of vCard files.
A possible solution is to trigger a download of the vCard file, but instead of directly opening the file, let the user decide where to save it. You can achieve this by using the "download" attribute on the link element and setting its value to the desired filename.
Try using this code and see if it worked:
<script>
  var saveBtn = document.getElementById("save-btn");
  saveBtn.addEventListener("click", function() {

    var contact = {
      name: "<?php echo $row["fullname"]; ?>",
      phone: "<?php echo $row["phone"]; ?>",
      email: "<?php echo $row["email"]; ?>",
      company: "<?php echo $row["company"]; ?>",
      socialpro: "<?php echo $row["city"]; ?>"
    };

    var vcard = "BEGIN:VCARD\nVERSION:4.0\nFN:" + contact.name + "\nTEL;TYPE=work,voice:" + contact.phone + "\nEMAIL:" + contact.email + "\nEND:VCARD";

    var blob = new Blob([vcard], {
      type: "text/vcard;charset=utf-8"
    });

    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = contact.name + ".vcf";
    link.click();

  });
</script>

This should allow the user to download the vCard file and choose where to save it on their Android device.


text:
Q: fadeIn issues with with scrolling I'm trying to have my content fade in when reaching a certain proximity to to respective ends of the page. The fade works fine when the trigger is set to the very top and bottom but when I set a distance (200px) the fade no longer works and the content simply appears.
$(window).scroll(function(){
        if($(window).scrollTop()<=200){
            $('#about .content').stop(true,true).fadeIn("5s");
        }
        else {
            $('#about .content').stop(true,true).fadeOut("10s");
        }

     if ($(window).scrollTop() + $(window).height() >= $(document).height() - 200) {
            $('#work .content').stop(true,true).fadeIn("5s");
        } else {
            $('#work .content').stop(true,true).fadeOut("5s");
        }
    });

A: What is happening is that you have two functions working against each other:
The first function has an "if-else" statement and the second function as well.
That means that each function does something EVERYTIME you scroll.
There are multiple ways of solving this.
The way I would solve it is using a variable and updating the constraints.
Let's say we have a variable onScreen that has value 1 if the paragraph is on the screen and value 0 if it isn't:
For example:

Example of scroll with fadeIn, fadeOut.

These paragraphs will go away when you have scrolled
 more than 10 pixels from the top. They will appear again when you have scrolled
to a proximity of 50 pixels from the bottom. They will also appear if you go
within a proximity of 10 pixels of the top again.

Now for the jQuery code:
var $onScreen = 1;

$(window).scroll(function(){
if($(window).scrollTop() < 10){
      if ($onScreen == 0)
      {
        $("p:first").stop(true,true).fadeIn("slow", "linear");
        $onScreen = 1;
      }
    }

if($(window).scrollTop() <= 20 && $(window).scrollTop() >= 10){
      if ($onScreen == 1)
      {
        $("p:first").stop(true,true).fadeOut("slow", "linear");
        $onScreen = 0;
      }
    }

 if ($(window).scrollTop() + $(window).height() >= $(document).height() - 50) {
     if ($onScreen == 0)
     {
         $("p:first").stop(true,true).fadeIn("slow", "linear");
         $onScreen = 1;
     }
    }
 });

Now this is not the most concise way of doing it and I didn't mean to do so: by making the code a bit more extensive I hope you can follow why it works now and didn't work before (such that you actually learn from it).
I prepared a live example for you on Fiddle: http://jsfiddle.net/ycCAb/4/
I hope this answers your question. Good luck!


text:
Q: What is the correct way of freeing dynamically allocated memory if the program can exit early because of errors? I have always learned that it is good to be generous with error checks in your code, and to provide an error message in case certain conditions are met. Consider a program of the following structure:
int main(const int argc, const char *argv[]) {

// read two integers M and N from input file 1 provided in argv[]
// read two integers K and L from input file 2 provided in argv[]

if (M*N < 1000000) {
    allocate array A
} else {
    printf("With your input values, the matrix will be too large!");
    return 1;
}

if (K*L < 1000000) {
    allocate array B
} else {
    printf("With your input values, the matrix will be too large!");
    return 1;
}

// multiply arrays elementwise
// free memory
return 0;
}

Ignore for the moment that this code could be reorganised, such that the validity of the input arguments is checked before allocations take place (which would be the straightforward solution in this simple example). My actual problem will be elaborated on down below for those who are interested.
If in the pseudocode above A is successfully allocated, but B is not because K*L exceeds the limit, the memory free statements at the end of the program are not reached, and a memory leak is associated with A. What would be the best way to avoid this issue if the code cannot be reorganised as described above? Removing the return 1; might cause other errors further down the line. The other two options I could think of are using the notorious goto statement (I did not dare), or indeed including all free calls inside the conditional as;
if (K*L < 1000000) {
    allocate array B
} else {
    printf("With your input values, the matrix will be too large!");
    free(A);
    return 1;
}

, but that would mean a lot of code repetition when one deals with a large number of dynamically allocated arrays. So: what program structure is recommended for a combination of intermediate error-checking and memory handling?
My actual case:
I am working with CUDA, which (for those that are unfamiliar with it) allows one to write code to be executed on a GPU. All (or most) code associated with this API returns an error flag, and which it is recommended that it is checked before the program proceeds. In my case, at some point in my program I am allocating memory on the GPU like such (should be readable for those familiar with C):
double *dev_I;
cudaError_t err;
err = cudaMalloc(&dev_I, N*M, sizeof(*dev_I)); // note: cudaMalloc takes a double pointer
if (err != cudaSuccess) { printf("Error allocating dev_I.\n"); return 1; }

Here comes the important part: the next step is to copy memory from the host to a place where the GPU can access it. This looks somewhat like this:
err = cudaMemcpy(dev_I, host_I, M*N * sizeof(*host_I), cudaMemcpyHostToDevice);
if (err != cudaSuccess) { printf("Error copying dev_I"); return 1; }

And this is the part I am concerned about. Should the allocation be successful but the memory copy fail, the program will (should) exit, and I will be left with a memory leak. Hence my question how this is best dealt with.

A: General structured programming in C requires goto, as follows:
int f() {
  void *p = alloc_resource();
  if (p == NULL) goto error_1;

  void* q = alloc_resource();
  if (q == NULL) goto error_2;

  return g(p, q);  // g takes ownership

error_2:
  dealloc_resource(p);
error_1:
  return -1;  // some error code
}

You can see how this pattern generalizes to arbitrary numbers or ownership acquisitions: you basically have to keep a list of cleanup operations around and jump to the appropriate one when your control flow hits an error and all state that you've build up so far needs to be unwound.
Usually, one would try to avoid excessively complex functions by keeping each function small so that the cleanup can be done in a more ad-hoc way without gotos, but sometimes you need something structured like this (e.g. when you are composing multiple bits of ownership).
(Other languages offer language-level support for multiple exits, e.g. in C++ this logic is provided by so-called "destructors". They pretty much effect the same thing only in a more composable and reusable way with all the jumps generated by the compiler.)

A: In addition to @Kerrek SB good answer, another approach is to assign/initialize all objects to some valid state,  test the validity of all resources, use if ok, then free.
The key idea is at declaration of the object (e.g. bar *A = NULL), the object A is immediately given a valid value - some valid value.
int foo(void) {
  bar *A = NULL;
  bar *B = NULL;
  int error = 0;

  if (M*N < 1000000) {
    A = allocate(M, N);
  } else {
    printf("With your input values, the matrix will be too large!");
    error = 1;
  }

  if (K*L < 1000000) {
    B = allocate(K, L);
  } else {
    printf("With your input values, the matrix will be too large!");
    error = 1;
  }

  // Was resource allocation successful?
  if (A && B) {
   // multiply arrays
   mul(A,B);
  }

  // free resources
  free(A);
  free(B);
  return error;
}

A pseudo-code outline
Get resources for A
Get resources for B
Get resources for C
If (OK(A) && OK(B) && OK(C)) {
  Perform the operation(A,B,C)
}
Return resources(C)
Return resources(B)
Return resources(A)

I find this approach easier to test.


text:
Q: Postgresql: set default psql client encoding When I connect to a Postgresql DB using psql, I often get these messages:
=> SELECT * FROM question_view ;
ERROR:  character with byte sequence 0xd7 0x9e in encoding "UTF8" has no equivalent in encoding "LATIN1"

Following this SO answer, I understand that I should change the client encoding accordingly:
SET client_encoding = 'UTF8';

Changing the client_encoding every time I connect to the DB is cumbersome. Is there a way to permanently configure this setting, either in the .pgpass file or anywhere else?

A:
Is there a way to permanently configure this setting, either in the .pgpass file or anywhere else

Yes there is: it's ~/.psqlrc (or %APPDATA%\postgresql\psqlrc.conf in Windows)
See the manual for details: http://www.postgresql.org/docs/current/static/app-psql.html#AEN88713

A: I was facing the same error but changing from ANSI(X64) to Unicode(x64) in my ODBC conn fixed my issue.


text:
Q: JavaScript Function within a function undefined Can someone explain to me why the second function within the first function is undefined?
var a = 1

function abc () {
    alert(a);
        function xyz () {
            alert(a);
        }
}

https://jsfiddle.net/kp950/yLs73cth/

A: xyz  is an inner function which is private to abc function.
You cannot call xyz unless you make it public

A: This is due to the scope at which you are trying to execute xyz() (globally). xyz() can only be run inside of abc() - where it is defined in the local scope.


text:
Q: What does (idle) mean in Google Chrome DevTools Profiler? Probably it's obvious but I can't find an answer..
What's the exact meaning of idle in this case?
Is there really nothing going on? Or just no JavaScript getting parsed/executed?

A: The meaning of "idle" is really obvious: "(idle)" means the time spent on doing nothing.
Go to about:blank, and get a new CPU profile. The result is probably a value for (idle) close to 100% and a bit of (program) next question: Chrome debugger - What is "(program)" in the profiler?.


text:
Q: $G$-set terminology When a group action $G \times X \rightarrow X$ is defined with a group $G$ and a set $X$, why is there not a special name for the set $X$? I know that this is referred to as a $G$-set, but the set $X$ itself does not seem to have a special name without the "$G$" specification.
To illustrate the point: when we have the appropriate action of a ring $R$ on a set $M$ such that $R \times M \rightarrow M$, then the set $M$ is a "module" without specification of the "$R$", and then we can refer to the $R$-module if we want to be more specific. But we cannot refer to the "set" in the same way, it has to be "$G$-set". So I am wondering is there such a name that was used in this case?

A: If $G$ is a semigroup then one use names "polygon" [Kilp M., Knauer U., Mikhalev A.V., Monoids, acts and categories] or "operand" [A. H. Clifford, G. B. Preston, The algebraic theory of semigroups] for $G$-sets (i.e. for the sets on which $G$ acts). So you can use them also, if you would like.

A: The language of monoidal categories offers a unification of various notions spread out over mathematics. $G$-sets and $R$-modules are really the same notions. In every monoidal category, there is the notion of a monoid object, namely an object $G$ equipped with morphisms $1 \to G$ and $G \otimes G \to G$, satisfying unitality and associativity. Besides, there is the notion of a module object over that monoid object, namely an object $X$ equipped with a morphism $G \otimes X \to X$ satisfying unitality and associativity in a certain sense. For the cartesian monoidal category of sets, the monoid objects are precisely the monoids $G$ in the usual sense, and $G$-modules are usually called $G$-sets. But really, you could just stick to the general formalism and call them $G$-modules$^{(1)}$. For the monoidal category of abelian groups with the usual tensor product, the monoid objects are the rings in the usual sense, and $R$-modules in the general sense above are precisely the $R$-modules in the usual sense.
Back to the general case: For a $G$-module $(X,G \otimes X \xrightarrow{a} X)$ I would call $X$ the underlying object. It is not good to call it a module, because the action $a$ has been forgotten.
$^{(1)}$ You might object that this contradicts with the common meaning of $G$-modules as $R[G]$-modules, where $R$ is a ring which is understood. But in my opinion this only shows that this usual usage is not good. Why does one say $G$, the monoid (or often group) object in the category of sets, where one actually means the induced monoid object $R[G]$ in the category of $R$-algebras? It is important and also quite useful to distinguish objects of different categories. When $G$ is a monoid, it is understood to be a monoid object in the category of sets, and nothing else, so that every construction, in particular the definition of a module, refers to the category of sets. Therefore "$G$-modules" is not ambiguous.


text:
Q: R Keeps Downloading Packages to tmp Directory I am using R Studio on a 2103 MacBook Pro.  I had no problems before downloading and installing packages, but recently all my packages are being downloaded and then fail to install:
trying URL 'http://cran.rstudio.com/bin/macosx/mavericks/contrib/3.1/manipulate_1.0.1.tgz'
Content type 'application/x-gzip' length 33770 bytes (32 Kb)
opened URL
==================================================
downloaded 32 Kb

The downloaded binary packages are in
/var/folders/yl/7q0_4h3j60d5pp52vmz0b06r0000gn/T//Rtmpa4oYSr/downloaded_packages

.libPath() returns the correct location of my R libraries (not this)
I can install manually from the downloaded package, but this extra step is Very Annoying, and I would like to restore the correct behavior.
Someone seems to have had the same problem here.  The solution was to add more swap space.  This does not seem to be my issue as ample swap and RAM appear to be available on my machine.
Has anyone had and resolved this issue?

A: Posting the Answer from the user so as not to lose info:
When you download r Packages,R shows the temp path where the files are downloaded like below...

The downloaded binary packages are in
  /var/folders/yl/7q0_4h3j60d5pp52vmz0b06r0000gn/T//Rtmpa4oYSr/downloaded_packages

But R deletes these files in Temp folders and install them in .libpath() path once the installation is done..


text:
Q: Deriving the logarithm of negative numbers is this approach correct?
$$\log_a b = \frac{\ln b}{\ln a} \tag{1}$$
but from the famous formula $e^{i\pi} = -1$ we can extend the domain of the natural logarithm and have $i\pi = \ln (-1)$ therefore for all real and non-zero a we can have:
$$\ln(a) = \ln(|a|\frac{a}{|a|}) = \ln(|a|) + \ln(\frac{a}{|a|}) $$
for example for negative a we have:
$$\ln (a) = \ln(|a|) + i\pi$$
and with the formula (1) we can extend this to all real numbers of a and b that are non-zero and the base non-equal to 1.
And how can we extend this to quaternions?

A:
$$\log_a b = \frac{\ln b}{\ln a} \tag{1}$$
but from the famous formula $$e^{i\pi} = -1$$ we have $$i\pi = \ln (-1)$$

Rather than using formula $(1),$ aren't you just applying $\ln$ on both sides then applying the formula $$\ln e^z=z\,?$$ Unfortunately, this formula is not generally applicable for complex $z;$  in fact, $$\ln (-1)=i\pi +i2k\pi.$$

therefore for all real and non-zero a we can have:
$$\ln(|a|\frac{a}{|a|}) = \ln(|a|) + \ln(\frac{a}{|a|}) $$

Unfortunately, the formula $$\ln z_1z_2=\ln z_1+\ln z_2$$ is also not generally applicable for complex $z.$

for example for negative a we have:
$$\ln (a) = \ln(|a|) + i\pi$$

In fact, by the general definition of $\log,$ for $a<0,$ $$\ln (a)=\ln(-a) + i\pi +i2k\pi.$$

OP's comment:

yes i did not pay attention to that. in fact since $\exp(iz)=\exp(i(z+2π))$ it can have infinitely values!

Actually, $\exp(z)$ typically denotes a single-valued function, while $e^z$ is either single-valued or multivalued depending on the context; in Euler's formula above, it is strongly conventional to read $e^{i\pi}$ as single-valued.


text: Q: Change language of exceptions that pop up in the screen visual studio In Visual studio 2015 I get the exception messages that pops up on the screen (while debugging) in french I want to change it to English do you have an idea of how I can do that?


text:
Q: Unwanted Autofills I am having a problem in my web application. I seem to have been experiencing auto-fill in  my username and password field. It is ok when I do a log in, the problem is it still does the auto-fill even in the create account page, even though I named my textFields(InputText) different from the other. I have tried this in both chrome and firefox, it still the same.
Here are some screenshots of the application and codes.
For the create account page

        <f:ajax
            listener="#{marketingPersonController.checkUsernameIfAvailable()}"/>

        <f:validateLength minimum="6" />

For my log in

Here is my code for log in:

A: Here (MDN)
you can find some recomended workarounds if the solution with autocomplete="off" won't work.

A: You need to turn off the autocomplete,but jsf  does not have an autocomplete attribute. So that means you have to turn it off on a per-input basis or write a custom renderer for the UIForm.
There's currently an open issue which requests to add this attribute to the : JSF spec issue 418. Currently, it's scheduled for JSF 2.2.
In the meanwhile, you can use OmniFaces Html5RenderKit to get support for autocomplete="off" on the  component.


text:
Q: var .htaccess not activating - cacheleak vulnerability I recently ran a magereport.com scan on one of our magento sites and it reported a cacheleak vulnerability.
In my var folder, there is an .htaccess file but it is not activating and the vulnerability is still reported.
I am running the following:
Magento 1.8.1.0
CentOS release 6.3 (Final)
PHP 5.3.3
FCGI
Apache 2.2.15

Contents of my var/.htaccess folder is:
Order Deny,Allow
Deny from all

Can someone shed some light why I am still able to access folders in my var folder?

A: while .htaccess is bad in many cases, you can add this in to your apache vhost config:
<LocationMatch ^/(app|downloader|pkginfo|includes|var)/>
    Deny from all
</LocationMatch>

just make sure you pass manual test, open app and var folder in your browser.
also read this: https://stackoverflow.com/questions/11823915/htaccess-not-being-read


text:
Q: How do you get the corners of the screen as geographical coordinates for Google Maps using Flutter I'm trying to get the corners of my screen, transform them into Points and pass them to my backend to then receive all the markers that fit my screen and place them on my map. The part I'm interested about is on how to get the corners of the screen.
I'm currently calculating corners onMapCreated: and after calculating that I place the markers
  void _onMapCreated(GoogleMapController controller) {
double screenWidth = MediaQuery.of(context).size.width *
    MediaQuery.of(context).devicePixelRatio;
double screenHeight = MediaQuery.of(context).size.height *
    MediaQuery.of(context).devicePixelRatio;

ScreenCoordinate northEast = ScreenCoordinate(x: screenWidth.round(), y: 0);
ScreenCoordinate southWest =
    ScreenCoordinate(x: 0, y: screenHeight.round());
LatLng northEastPoint = await controller.getLatLng(northEast);
LatLng southWestPoint = await controller.getLatLng(southWest);
  }

I think my issue right now is that I'm not taking into account the center of the map, regardless of my center the corners always are
latMin: -25.27, latMax: -25.61, longMin: -57.566 and longMax: -57.560
my widget build so you can test
  static final CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(-25.265620626519592, -57.5632423825354),
    zoom: 16.5,
  );
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Test'),
          ),
          body: GoogleMap(
            initialCameraPosition: _kGooglePlex,
            markers: _markers,
            myLocationEnabled: true,
            onMapCreated: _onMapCreated,
          ),
          floatingActionButton: FloatingActionButton.extended(
            elevation: 0,
            onPressed: () {print('pressed')},
            backgroundColor: Color(0xE6FDBE83),
            label: Text('Report'),
            icon: Icon(Icons.add),
          ),
          floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
        );
      }


text:
Q: LightSwitch Desktop Application Installation failing: "Strong name signature not valid for this assembly vslshost.exe" I've created a LighSwitch desktop application in Visual Studio 2013 which installs perfectly fine on my development machine but fails during installation on my client's machine with the following error message:
Strong name signature not valid for this assembly vslshost.exe
I found a similar issue that was also raised on the MSDN forum:
http://social.msdn.microsoft.com/Forums/en-US/28736d83-db94-4d0b-adb9-2ff2e6d0ba95/installation-failing-strong-name-signature-not-valid-for-this-assembly-vslshostexe?forum=lightswitch
One person replied stating that other people have previously given solutions to this error but neither I nor the original poster could find these solutions.
I've followed the How to: Deploy a Two-tier LightSwitch Application guide found here:
http://msdn.microsoft.com/en-us/library/ff852056.aspx
However, the problem persists for my client but not for me.
Can anyone help with this?
Here are some details from the error log:
PLATFORM VERSION INFO
    Windows             : 6.1.7601.65536 (Win32NT)
    Common Language Runtime     : 4.0.30319.1022
    System.Deployment.dll       : 4.0.30319.245 (RTMGDR.030319-2400)
    clr.dll             : 4.0.30319.1022 (RTMGDR.030319-1000)
    dfdll.dll           : 4.0.30319.1 (RTMRel.030319-0100)
    dfshim.dll          : 4.0.31106.0 (Main.031106-0000)

IDENTITIES
    Deployment Identity     : [APPLICATION], Version=1.0.7.0, Culture=neutral, PublicKeyToken=0000000000000000, processorArchitecture=x86
    Application Identity        : [APPLICATION_EXE], Version=1.0.7.0, Culture=neutral, PublicKeyToken=0000000000000000, processorArchitecture=x86, type=win32

ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of [APPLICATION] resulted in exception. Following failure messages were detected:
        + Strong name signature not valid for this assembly vslshost.exe.

COMPONENT STORE TRANSACTION FAILURE SUMMARY
    No transaction error was detected.

WARNINGS
    * The manifest for this application does not have a signature. Signature validation will be ignored.
    * The manifest for this application does not have a signature. Signature validation will be ignored.
    * The file named default.htm does not have a hash specified in the manifest. Hash validation will be ignored.
    * The file named web.config does not have a hash specified in the manifest. Hash validation will be ignored.

OPERATION PROGRESS STATUS
    * [25/02/2014 8:11:42 AM] : Activation of [APPLICATION] has started.
    * [25/02/2014 8:11:42 AM] : Processing of deployment manifest has successfully completed.
    * [25/02/2014 8:11:42 AM] : Installation of the application has started.
    * [25/02/2014 8:11:42 AM] : Processing of application manifest has successfully completed.
    * [25/02/2014 8:11:45 AM] : Found compatible runtime version 4.0.30319.
    * [25/02/2014 8:11:45 AM] : Request of trust and detection of platform is complete.

ERROR DETAILS
    Following errors were detected during this operation.
    * [25/02/2014 8:11:46 AM] System.Deployment.Application.InvalidDeploymentException (SignatureValidation)
        - Strong name signature not valid for this assembly vslshost.exe.
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Application.ComponentVerifier.VerifyStrongNameAssembly(String filePath, AssemblyManifest assemblyManifest)
            at System.Deployment.Application.ComponentVerifier.StrongNameAssemblyComponent.Verify()
            at System.Deployment.Application.ComponentVerifier.VerifyComponents()
            at System.Deployment.Application.DownloadManager.DownloadDependencies(SubscriptionState subState, AssemblyManifest deployManifest, AssemblyManifest appManifest, Uri sourceUriBase, String targetDirectory, String group, IDownloadNotification notification, DownloadOptions options)
            at System.Deployment.Application.ApplicationActivator.DownloadApplication(SubscriptionState subState, ActivationDescription actDesc, Int64 transactionId, TempDirectory& downloadTemp)
            at System.Deployment.Application.ApplicationActivator.InstallApplication(SubscriptionState& subState, ActivationDescription actDesc)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)

COMPONENT STORE TRANSACTION DETAILS
    No transaction information is available.

Any help with this would be greatly appreciated. Please let me know if further information would be useful in diagnosing the issue.


text:
Q: Same offset and partition record is getting consumed twice causing duplicates I am trying to consume records using application written in spring-kafka. I am facing very unique condition and not able to understand why this is happening ?
My consumer application is running with 2 concurrency meaning 2 consumer thread subscribed to topic having two partitions.I am consuming records and placing it into table using upsert with offset, partitions and insert timestamp.
I am seeing duplicate values with same offset and partition in the table which should not occur. There is no difference in the timestamp value, means insert occurred at the same time. I am not sure how is it possible? I don't see any issue in the log as well. I am not sure what is happening at the Producer end but we can't have 2 values at the same offset anyway, so not sure whether this is an issue at consumer end of producer end.Any suggestion or thought which would help me to triage this issue?

Kafka log :
I don't see anything unusual in the log as well.
14:29:56.318 [main] INFO  org.apache.kafka.common.utils.AppInfoParser - Kafka version: 2.4.0
14:29:56.318 [main] INFO  org.apache.kafka.common.utils.AppInfoParser - Kafka commitId: 77a89fcf8d7fa018
14:29:56.318 [main] INFO  org.apache.kafka.common.utils.AppInfoParser - Kafka startTimeMs: 1604154596318
14:29:56.319 [main] INFO  org.apache.kafka.clients.consumer.KafkaConsumer - [Consumer clientId=consumer-csp-prov-emerald-test-2, groupId=csp-prov-emerald-test] Subscribed to topic(s): kaas.pe.enrollment.csp.ts2
14:29:57.914 [org.springframework.kafka.KafkaListenerEndpointContainer#0-1-C-1] INFO  org.apache.kafka.clients.Metadata - [Consumer clientId=consumer-csp-prov-emerald-test-2, groupId=csp-prov-emerald-test] Cluster ID: 6cbv7QOaSW6j1vXrOCE4jA
14:29:57.914 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO  org.apache.kafka.clients.Metadata - [Consumer clientId=consumer-csp-prov-emerald-test-1, groupId=csp-prov-emerald-test] Cluster ID: 6cbv7QOaSW6j1vXrOCE4jA
14:29:57.915 [org.springframework.kafka.KafkaListenerEndpointContainer#0-1-C-1] INFO  org.apache.kafka.clients.consumer.internals.AbstractCoordinator - [Consumer clientId=consumer-csp-prov-emerald-test-2, groupId=csp-prov-emerald-test] Discovered group coordinator apslp1563.uhc.com:9093 (id: 2147483574 rack: null)
14:29:57.915 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO  org.apache.kafka.clients.consumer.internals.AbstractCoordinator - [Consumer clientId=consumer-csp-prov-emerald-test-1, groupId=csp-prov-emerald-test] Discovered group coordinator apslp1563.uhc.com:9093 (id: 2147483574 rack: null)
14:29:57.923 [org.springframework.kafka.KafkaListenerEndpointContainer#0-1-C-1] INFO  org.apache.kafka.clients.consumer.internals.AbstractCoordinator - [Consumer clientId=consumer-csp-prov-emerald-test-2, groupId=csp-prov-emerald-test] (Re-)joining group
14:29:57.924 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO  org.apache.kafka.clients.consumer.internals.AbstractCoordinator - [Consumer clientId=consumer-csp-prov-emerald-test-1, groupId=csp-prov-emerald-test] (Re-)joining group
14:29:58.121 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO  org.apache.kafka.clients.consumer.internals.AbstractCoordinator - [Consumer clientId=consumer-csp-prov-emerald-test-1, groupId=csp-prov-emerald-test] (Re-)joining group
14:29:58.125 [org.springframework.kafka.KafkaListenerEndpointContainer#0-1-C-1] INFO  org.apache.kafka.clients.consumer.internals.AbstractCoordinator - [Consumer clientId=consumer-csp-prov-emerald-test-2, groupId=csp-prov-emerald-test] (Re-)joining group
14:30:13.127 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO  org.apache.kafka.clients.consumer.internals.ConsumerCoordinator - [Consumer clientId=consumer-csp-prov-emerald-test-1, groupId=csp-prov-emerald-test] Finished assignment for group at generation 23: {consumer-csp-prov-emerald-test-1-19d92ba5-5dc3-433d-b967-3cf1ce1b4174=org.apache.kafka.clients.consumer.ConsumerPartitionAssignor$Assignment@d7e2a1f, consumer-csp-prov-emerald-test-2-5833c212-7031-4ab1-944b-7e26f7d7a293=org.apache.kafka.clients.consumer.ConsumerPartitionAssignor$Assignment@53c3aad3}
14:30:13.131 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO  org.apache.kafka.clients.consumer.internals.AbstractCoordinator - [Consumer clientId=consumer-csp-prov-emerald-test-1, groupId=csp-prov-emerald-test] Successfully joined group with generation 23
14:30:13.131 [org.springframework.kafka.KafkaListenerEndpointContainer#0-1-C-1] INFO  org.apache.kafka.clients.consumer.internals.AbstractCoordinator - [Consumer clientId=consumer-csp-prov-emerald-test-2, groupId=csp-prov-emerald-test] Successfully joined group with generation 23
14:30:13.134 [org.springframework.kafka.KafkaListenerEndpointContainer#0-1-C-1] INFO  org.apache.kafka.clients.consumer.internals.ConsumerCoordinator - [Consumer clientId=consumer-csp-prov-emerald-test-2, groupId=csp-prov-emerald-test] Adding newly assigned partitions: kaas.pe.enrollment.csp.ts2-1
14:30:13.134 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO  org.apache.kafka.clients.consumer.internals.ConsumerCoordinator - [Consumer clientId=consumer-csp-prov-emerald-test-1, groupId=csp-prov-emerald-test] Adding newly assigned partitions: kaas.pe.enrollment.csp.ts2-0
14:30:13.143 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO  org.apache.kafka.clients.consumer.internals.ConsumerCoordinator - [Consumer clientId=consumer-csp-prov-emerald-test-1, groupId=csp-prov-emerald-test] Setting offset for partition kaas.pe.enrollment.csp.ts2-0 to the committed offset FetchPosition{offset=500387, offsetEpoch=Optional.empty, currentLeader=LeaderAndEpoch{leader=apslp1559.uhc.com:9093 (id: 69 rack: null), epoch=37}}
14:30:13.143 [org.springframework.kafka.KafkaListenerEndpointContainer#0-1-C-1] INFO  org.apache.kafka.clients.consumer.internals.ConsumerCoordinator - [Consumer clientId=consumer-csp-prov-emerald-test-2, groupId=csp-prov-emerald-test] Setting offset for partition kaas.pe.enrollment.csp.ts2-1 to the committed offset FetchPosition{offset=499503, offsetEpoch=Optional.empty, currentLeader=LeaderAndEpoch{leader=apslp1562.uhc.com:9093 (id: 72 rack: null), epoch=36}}

Code :
@KafkaListener(topics = "${app.topic}", groupId = "${app.group_id_config}")
    public void run(ConsumerRecord<String, GenericRecord> record, Acknowledgment acknowledgement) throws Exception {

        try {
                prov_tin_number         = record.value().get("providerTinNumber").toString();
                prov_tin_type           = record.value().get("providerTINType").toString();
                enroll_type             = record.value().get("enrollmentType").toString();
                vcp_prov_choice_ind     = record.value().get("vcpProvChoiceInd").toString();
                error_flag              = "";

                dataexecutor.peStremUpsertTbl(prov_tin_number, prov_tin_type, enroll_type, vcp_prov_choice_ind, error_flag,
                    record.partition(), record.offset());

                acknowledgement.acknowledge();

        }catch (Exception ex) {
            System.out.println(record);
            System.out.println(ex.getMessage());
        }

    }


text:
Q: Error: HDL-Complier-661 Non-net port cannot be mode of input I'm trying to develop a Verilog code for right shifting as a part of Floating Point ALU. I'm getting the following error in line 7:
Error: HDL-Complier-661 .... Non net port cannot be mode of input
Please tell me what my error is and provide me with corrected code.

        `timescale 1ns / 1ps

    module right_shifter(small_mant, shift_amt, shifted_mant);

    input [3:0] small_mant;
    input [2:0] shift_amt;
    output [5:0] shifted_mant;
    reg [3:0] small_mant;
    reg [5:0] shifted_mant;

    always@(small_mant or shift_amt)
    case (shift_amt)
    3'b000: shifted_mant <= {2'b01, small_mant[3:0]};
    3'b001: shifted_mant <= {3'b001, small_mant[3:1]};
    3'b010: shifted_mant <= {4'b0001, small_mant[3:2]};
    3'b011: shifted_mant <= {5'b00001, small_mant[3]};
    3'b100: shifted_mant <= 6'b000001;
    default: shifted_mant <= 6'b000000;
    endcase

    endmodule

A: Verilog does not allow input ports declared as a variable with a data type (SystemVerilog does).You can remove that line. I also suggest using a simpler form of port declarations that only mentions each port name once instead of up to three times (called ANSI style in the IEEE LRM)
module right_shifter(
    input [3:0] small_mant,
    input [2:0] shift_amt,
    output reg [5:0] shifted_mant
);

A: You've declared your port as input [3:0] small_mant; - this means you are declaring an input to the module, which must be of a net type (a.k.a. a wire).
However you then re-declare your input port as reg [3:0] small_mant; which is a variable data type (reg), and therefore not a net type.
You cannot, and in fact never need to, declare an input as a reg, so simply remove that line.

A: The corrected code :-
`timescale 1ns / 1ps

//Module: Shifts a given numner to the right by an amount (shift_amt)

module right_shifter(
    input [3:0] small_mant,
    input [2:0] shift_amt,
    output reg [5:0] shifted_mant
);

always@(small_mant or shift_amt)
case (shift_amt)
3'b000: shifted_mant <= {2'b01, small_mant[3:0]};
3'b001: shifted_mant <= {3'b001, small_mant[3:1]};
3'b010: shifted_mant <= {4'b0001, small_mant[3:2]};
3'b011: shifted_mant <= {5'b00001, small_mant[3]};
3'b100: shifted_mant <= 6'b000001;
default: shifted_mant <= 6'b000000;
endcase

endmodule


text:
Q: Multiplicative order and primitive roots Let $p$ be an odd prime and r an integer coprime to $p$. I am trying to show that if $r^{p-1}/q$ is not equal to $1$ for all primes $q$ dividing $p$, then $r$ is a primitive root modulo $p$. The hard part is that we only need consider the primes $q$ dividing $p$ for some reason. Thanks for any help you can give.

A: If $r$ is not a primitive root, then $r$ has order $m$ where $m$ is a proper divisor of $p-1$. But then  $m$ divides $\frac{p-1}{q}$ for some prime divisor of $q-1$.
If this does not seem obvious, note that $\frac{p-1}{m}$ is divisible by some prime $q$. Thus $\frac{p-1}{m}=kq$ for some $k$. But then $km=\frac{p-1}{q}$, so $m$ divides $\frac{m-1}{q}$.
It follows that $r^{(p-1)/q}\equiv 1\pmod{p}$. But the problem specified that
$r^{(p-1)/q}\not \equiv 1\pmod{p}$.

A: Lagrange's theorem tells us, that the smallest $k$ satisfying $r^k=1$ in $\mathbb Z_p^*$ divides $|\mathbb Z_p^*|=p-1$. So there is some $a$, such that $ka=p-1$ for this $k$.
Assume, $r$ is not primitive, then $a>1$, so you can write $a=qb$, where $q$ is a prime. Now $kqb=p-1$. Then $r^k=1$ implies $r^{kb}=1$ and
$$1=r^{kb}=r^{\frac{p-1}{q}}$$
is a contradiciton to your precondition.


text:
Q: Python3 Tkinter - multiple frames in their own classes and handling resizing I am trying to understand how resizing works. The basic demos for resizing show how an application with a single frame and a single button in that frame.  I am trying to expand on this by having some prebuilt frames as a class that I can reuse over and over in the main frame of the application. This is where I get lost on how to get them to resize with the main window resizing. Sorry for the crappy code ahead of time, I am actually pretty confused about setting all this GUI stuff up coming from pure script based programs before this.
import tkinter as tk

# reusable class of a frame that will create a single row with 4 columns containing a label, entry, label, and button
class FrameWithEntryAndLabelAndErrorAndButton(tk.Frame):
    def __init__(self, parent, row_text):
        tk.Frame.__init__(self, parent)
        self.grid(sticky=tk.NSEW)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=10)
        self.columnconfigure(2, weight=1)
        self.columnconfigure(3, weight=1)
        self.rowconfigure(0, weight=1)
        self.create_widgets(row_text)

    def create_widgets(self, row_text):
        self.label_entry = tk.Label(self, text=f'{row_text} Dir')
        self.label_entry.grid(column=0, row=0, sticky=tk.EW)
        self.entry_box = tk.Entry(self, width = 100)
        self.entry_box.grid(column=1, row=0, sticky=tk.EW)
        self.label_error = tk.Label(self, text=f'{row_text} ErrorMessage')
        self.label_error.grid(column=2, row=0, sticky=tk.EW)
        self.directory_search_button = tk.Button(self, text=f'{row_text} OpenDir')
        self.directory_search_button.grid(column=3, row=0, sticky=tk.EW)

class Application(tk.Frame):
    def __init__(self, parent=None):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.parent.resizable(1, 1)
        self.parent.rowconfigure(0, weight=1)
        self.parent.rowconfigure(1, weight=1)
        self.parent.columnconfigure(0, weight=1)
        self.grid(sticky=tk.NSEW)
        self.create_widgets()

    def create_widgets(self):
        self.inputframe = FrameWithEntryAndLabelAndErrorAndButton(self, 'row0')
        self.inputframe.grid(column=0, row=0, sticky=tk.NSEW)
        self.inputframe2 = FrameWithEntryAndLabelAndErrorAndButton(self, 'row1')
        self.inputframe2.grid(column=0, row=1, sticky=tk.NSEW)

root = tk.Tk()
app = Application(root)
app.master.title('Sample application')
app.mainloop()

initial run:

after resize:

If possible, I would like the entry box to grow the most (I thought that Is what the weight was supposed to do for that column in the custom class), and the labels to maybe grow less, etc.
Edit to add:
Thanks to a reddit poster who noticed in my Application class, I never had a columnconfigure call on itself to set the weight on column 0

A: You cannot use tkinter. You will have to use TTK. I also removed tk. It is straight forward for you. I changed it using the same code as yours.
from tkinter import ttk
from tkinter import *

class FrameWithEntryAndLabelAndErrorAndButton(Frame):
    def __init__(self, parent, row_text):
        Frame.__init__(self, parent)
        self.grid(sticky=NSEW)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=10)
        self.columnconfigure(2, weight=1)
        self.columnconfigure(3, weight=1)
        self.rowconfigure(0, weight=1)
        self.create_widgets(row_text)

    def create_widgets(self, row_text):
        self.label_entry = Label(self, text=f'{row_text} Dir')
        self.label_entry.grid(column=0, row=0, sticky=EW)
        self.entry_box = Entry(self, width = 100)
        self.entry_box.grid(column=1, row=0, sticky=EW)
        self.label_error = Label(self, text=f'{row_text} ErrorMessage')
        self.label_error.grid(column=2, row=0, sticky=EW)
        self.directory_search_button = Button(self, text=f'{row_text} OpenDir')
        self.directory_search_button.grid(column=3, row=0, sticky=EW)

class Application(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.resizable(1, 1)
        self.parent.rowconfigure(0, weight=1)
        self.parent.rowconfigure(1, weight=1)
        self.parent.columnconfigure(0, weight=1)
        self.grid(sticky=NSEW)
        self.create_widgets()

    def create_widgets(self):
        self.inputframe = FrameWithEntryAndLabelAndErrorAndButton(self, 'row0')
        self.inputframe.grid(column=0, row=0, sticky=NSEW)
        self.inputframe2 = FrameWithEntryAndLabelAndErrorAndButton(self, 'row1')
        self.inputframe2.grid(column=0, row=1, sticky=NSEW)

root = Tk ()
app = Application(root)
app.master.title('Sample application')
root.resizable (False, False)
mainloop ()


text:
Q: Valgrind indicates memory leak with shared_ptr c++11 I've implemented a Linked list using C++11 smart pointers. This implementation uses shared_ptr to store the internal data struct, which is used to implement implicit-sharing of it. I provide the relevant part of the source code bellow:
namespace Algos {

template <typename T>
struct LinkedListData{
    struct Node {
        std::unique_ptr<Node> next;
        Node *prev = nullptr;
        T data;
    };

    std::unique_ptr<Node> root;
    Node *last = nullptr;
    int size = 0;

    LinkedListData() {
        root = std::make_unique<Node>();
        root->prev = nullptr; //last virtual element
        root->next = std::make_unique<Node>();
        last = root->next.get();
        last->prev = root.get();
        last->next = nullptr;
    }

    //deferr pointers manually to avoid stackoverflow due to
    //recursion explosion
    static void cleanup(LinkedListData<T> *data) {
        #ifdef DEBUG_TXT
            int nodeCount=0;
        #endif
        Node *n = data->last;
        if(n==nullptr) { return; }
        while(n) {
            #ifdef DEBUG_TXT
                if(n->next.get())
                    std::cout << "Release {n->next()} [" << ++nodeCount  <<
                    "]: "<< n->next.get() << std::endl;
            #endif
            n->next.release();
            ALGO_ASSERT(n->next.get() == nullptr, "Node reference not deferred");
            n = n->prev;
        }
        data->size = 0;
        #ifdef DEBUG_TXT
            std::cout << "Release {Root} [" << ++nodeCount  << "]: "<< data->root.get() << std::endl;
        #endif
        data->root.release();
    }
};

template <class T>
class LinkedList {

    typedef typename LinkedListData<T>::Node node_type;
    std::shared_ptr<LinkedListData<T> > d;

    public:

        LinkedList() : d(new LinkedListData<T>(), LinkedListData<T>::cleanup){}

/* Code omitted .... */

};

}

The following code is triggering memory leak error on valgrind in the shared_pointer constructor due to the use of new:
#include <iostream>
#include <string>
#include <unistd.h>

// #define DEBUG_TXT

#include "global/assert.h"

#include "linked_list/linkedlist.h"

#define TEST_SIZE 5000

struct DataTest {
   int integer;
   bool boolean;
   std::string txt;
   DataTest& operator=(const DataTest& other) {
      integer = other.integer;
      boolean = other.boolean;
      txt = other.txt;
      return (*this);
   }

   bool operator==(const DataTest& other) const {
      return (
         integer == other.integer &&
         boolean == other.boolean &&
         txt == other.txt
      );
    }
};

struct Data {
    DataTest data[TEST_SIZE];
    const int n = TEST_SIZE;

    static void initDataSample(Data &d) {
        for(int i=0; i<d.n; i++) {
            d.data[i].integer = i;
            d.data[i].boolean = (i%2 == 0);
            d.data[i].txt = "abc";
        }
    }
};

void appendElements(Algos::LinkedList<DataTest> &l, const Data& d){
    for(int i=0; i<d.n; i++) {
        l.append(d.data[i]);
    }
}

void prependElements(Algos::LinkedList<DataTest> &l, const Data& d) {
    for(int i=d.n-1; i>=0; i--) {
        l.prepend(d.data[i]);
    }
}

int main(int argv, char* argc[]) {

   Data d;
    Data::initDataSample(d);

    Algos::LinkedList<DataTest> l1;
    {
        Algos::LinkedList<DataTest> l2;
        l1 = l2;
    }

    sleep(2);

    appendElements(l1, d);

    int removeSize = l1.size()/2;

    for(int i=0; i<removeSize; i++)
        l1.takeFirst();

    prependElements(l1, d);

    removeSize = l1.size()/2;
    for(int i=0; i<removeSize; i++)
        l1.takeLast();

   return 0;
}

This is the message I'm getting in the valgrind console:
> ==8897== HEAP SUMMARY:
==8897==     in use at exit: 282,976 bytes in 3,757 blocks
==8897==   total heap usage: 10,009 allocs, 6,252 frees, 633,040 bytes allocated
==8897==
==8897== 136 (24 direct, 112 indirect) bytes in 1 blocks are definitely lost in loss record 5 of 8
==8897==    at 0x4C2E216: operator new(unsigned long) (vg_replace_malloc.c:334)
==8897==    by 0x407C1C: Algos::LinkedList<DataTest>::LinkedList() (linkedlist.h:74)
==8897==    by 0x4074B4: main (insert_delete_rounds.cpp:63)
==8897==
==8897== 210,136 (24 direct, 210,112 indirect) bytes in 1 blocks are definitely lost in loss record 8 of 8
==8897==    at 0x4C2E216: operator new(unsigned long) (vg_replace_malloc.c:334)
==8897==    by 0x407C1C: Algos::LinkedList<DataTest>::LinkedList() (linkedlist.h:74)
==8897==    by 0x4074C3: main (insert_delete_rounds.cpp:65)
==8897==
==8897== LEAK SUMMARY:
==8897==    definitely lost: 48 bytes in 2 blocks
==8897==    indirectly lost: 210,224 bytes in 3,754 blocks
==8897==      possibly lost: 0 bytes in 0 blocks
==8897==    still reachable: 72,704 bytes in 1 blocks
==8897==         suppressed: 0 bytes in 0 blocks
==8897== Reachable blocks (those to which a pointer was found) are not shown.
==8897== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==8897==
==8897== For counts of detected and suppressed errors, rerun with: -v
==8897== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

As far as I know there is no other way to initiate a shared_ptr with custom Deleter without using new in C++11. After reading the documentation and different threads on stackoverflow, I noticed that std::make_shared() doesn't support passing a custom Deleter. So, my question is: Is this memory leak warning legit ? If yes, is it possible to avoid it ?
Dev tools setup:

*

*gcc: 5.4.0

*Valgrind: 3.13.0

*OS: Linux Ubuntu 16.04

A: To answer your questions:

*

*You make use allocate_shared to allow the use of a custom memory allocator. The signature is identical, except it takes a const reference to an allocator as the first argument.

*Although you may clean up the internals of LinkedListData, you never delete the allocated pointer in your cleanup method. cleanup should be called from the LinkedListData destructor, and you should use the regular deleter (or a custom deleter if using a custom allocator) to call delete on the LinkedListData pointer.
In short, this line will always lead to a memory leak:
LinkedList() : d(new LinkedListData<T>(), LinkedListData<T>::cleanup){}

A: You create a new LinkedListData<T>(), but you don't call delete on it inside cleanup.

A: Since you are using smart pointers internally you should not specify LinkedListData::cleanup as a custom deleter and just use default one. If you are trying to stick with smart pointers it may be a good idea to avoid using new calls if you are not explicitly calling delete. So, d member may be initialized with just d(std::make_shared<LinkedListData<T>>()). Also, it maybe can be declared just as LinkedListData<T> d; without any smart pointers there.
Then, you should not call release in LinkedListData::cleanup. This method detaches raw pointer from the smart pointer wrapper and does not deallocate associated object. You probably want reset instead. But once again, this method should not be necessary at all since all your pointers are smart and associated data should be automatically cleaned up when the parent destructor is called.


text:
Q: Determining \$I_{peak}\$ and \$f_{min}\$ and \$f_{max}\$ for MP4569 buck IC Trying to figure out what inductance value is needed for my application of MP4569.
They give the minimum inductance value in terms of \$I_{peak}\$ (page 12):
\$L_{MIN}={{V_{IN(MAX)}{\times}t_{ON(MIN)}}\over{I_{peak}}}\$
and the datasheet says "the Ipeak is fixed, for given input voltage and output voltage"
I understand that \$I_{OUT}\$ cannot be more than half \$I_{peak}\$ with this converter because it always waits for the \$I_{L}\$ to drop to zero before each new cycle, but I don't understand how to determine this fixed \$I_{peak}\$ value based on \$V_{IN}-V_{OUT}\$.
The datasheet also doesn't give the switching frequency range, just one clue in the "Steady State, \$I_{OUT}=0.3A\$" figure on page 7 where the switching frequency is 100 KHz.
How do I determine the fixed \$I_{peak}\$ value based on my \$V_{IN}-V_{OUT}\$ value for this IC?
(I've selected the part based on the high input voltage range and availability from LCSC)

A:
but I don't understand how to determine this fixed Ipeak

Try this: -

And this: -


text:
Q: C: prime factoring How do you test for primes with the IsPrime method below? I cannot seem to get the printf to work in my IsPrime method and no errors were thrown.
#include <stdlib.h>
#include <stdio.h>
int IsPrime(unsigned int number) {
   if (number <= 1) {
      return 0; // zero and one are not prime
      printf("zero and one are not prime.");
      }
   unsigned int i;
   for (i=2; i*i<=number; i++) {
      if (number % i == 0) {
         return 0;
         printf("not a prime.");
      }
   }
   return 1;
   printf("You've found a prime!");
   }

int main(void) {
   int a;

   printf("Please input an integer value: ");
   scanf("%d", &a);
   if(a >= 1 && a <= 1000) {
      printf("You entered: %d\n", a);
      IsPrime(a);
   }
   else {
      printf("Error! Please enter a value between 1 and 1000.");
   }
}

A: You're return-ing from function before printf

A: You wrote printf statement after return; It's an easy fix, just swap the two instructions.


text:
Q: Exception of RuntimeBinder Facebook SDK c# I am writing facebookc# Sdk program but the issue is that this strange exception occurs
'Facebook.JsonObject' does not contain a definition for 'data' and says that
'wall.data' threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' dynamic {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException}

even orignal samples from website are giving errors. Am I missing something?
I have also added reference to Microsoft.CSharp and Using dot net framework 4.0
I loked at various links but did not helped
   dynamic wall = fb.Get("me/feed");
 List<dynamic> WALL = new List<dynamic>(wall.data);

and string in wall is something like (too long pasting short)

A: By Mistake I had included the 3.5 version of SDK it should be 4.0 for dynamic usage

A: this is because the cast that you are trying to make is invalid...
 dynamic wall_data = wall.data

then you can go through wall_data and get what you want
this appears to be JSON , why not just use a JSON library like JSON.net and keep it that way !!!


text:
Q: Adding custom input not working I created a .inputplugin file per Apple's guide to use with a custom font I have. When I try to install it, it does nothing and doesn't appear in my input menu. Any ideas? Thanks in advance!

A: I was using UTF-8 instead of UTF-16 and didn't space between entries (I should have double-spaced). Changing those fixed my issue.


text:
Q: In backpropogation, what does it mean when the error of a neural network converges to 0.5? I've been trying to learn the math behind neural networks and have implemented (in Octave) a version of the following equations which include bias terms.
Back-propagation equations matrix form:

Visual representation of the problem and Network:

clear;  clc;  close all;
#Initialize weights and bias from input to hidden layer
W1 = rand(3,4)
b1 = ones(3,1)
#Initialize weights from hidden to output
W2 = rand(2,3)
b2 = ones(2,1)

#define sigmoid function
s = @(z) 1./(1 + exp(-z));
ds = @(z) s(z).*(1-s(z));

data = csvread("data.txt");

for j = 1 : 100
  for i = 1 : length(data)
      x0 = data(i,2:5)';

      #Find the truth
      if data(i,6) == 1 ;
        t = [1;0]   ;
      else
        t = [0;1];
      end

      #Forward propagate
      x1 = s(W1*x0 + b1);
      x2 = s(W2*x1 + b2);
      iter = (j-1)*length(data) + i;
      E((j-1)*length(data) + i) = norm(x2-t)^2;
      E(length(E))

      #Back propagate
      delta2 = (x2-t).*ds(W2*x1+b2);
      delta1 = W2'*delta2.*ds(W1*x0+b1);

      dedw2 = delta2*x1';
      dedw1 = delta1*x0';

      alpha = 0.001*(40000-iter)/40000;
      W2 = W2 - alpha*dedw2;
      W1 = W1 - alpha*dedw1;
      b2 = b2 - alpha*delta2;
      b1 = b1 - alpha*delta1;
  end
end
plot(E)
title('Gradient Descent')
xlabel('Iteration')
ylabel('Error')

When I run this, I converge on weights that give an constant error of 0.5 rather than 0.0. The error plot looks something like this depending on the initial samples of W1 and W2:

The resulting weights W1 and W2 yield output ~[0.5,0.5] for the whole set rather than [1,0](isStairs = true) or [0,1](isStairs = False)
Other information:

*

*If I loop over a single data point instead of the entire learning set, it does converge to zero error for that particular case. (like 20 iterations or so), so I assume my derivatives are correct?

*For the model to converge the learning rate has to be insanely small. Not sure what this means.

Is this neural network valid to solve the described problem? If so, what does it mean to converge to an error of 0.5?

A: The NN learns from data. If there is only one example, it will learn this example by heard and you have zero error. But if you have more examples, they will likely not lie on a nice curve, but are noisy instead. So it is harder to learn the data by heard for the network (it also depends on the number of free parameters that the NN has but you get the idea)... However, you don't want the NN to learn everything in detail. You want it to learn the overall trend (so not the noise). But this also means, that your error won't converge to zero as there is noise, which your NN should not learn... So don't worry if you have a (small) error at the end.
But what about the learning rate? Well, imagine you have 10 examples. Eight of them describe a perfect line but two exhibit noise. One sightly to the right (lets say +1) and the other slightly to the left (-1). If the NN estimates one of those points and updates to minimize the error drawn from it. The update will jump from + to - or vice versa. Depending on your learning rate, this jumping may eventually converge to the middle (which is the correct function) or may go on forever... This is essentially what the learning rate does: it determines how much impact an estimation error has on the update/learning of the network. So a good idea is to choose a larger learning rate the the beginning (where the network has a really bad performance due to its random initialization) and decrease the rate when it already learned something. You can achieve the same thing with a small learning rate but you will need longer time for it;)


text:
Q: Why Monitor.Wait and PulseAll in .NET 4.0 is not working In our Legacy project we were using following code for asynchronous operations:
public interface IAsyncOperation
{
    OperationToken Token { get; }
    bool IsCompleted { get; }
    Exception Exception { get; }
    bool Wait(int timeout);
}

/// <summary>
/// Asynchronous operation that may be executed on a separate thread.
/// IsCompleted and Exception would be synchronized after invoking Wait.
/// </summary>
public abstract class AsyncOperation : IAsyncOperation
{
    protected readonly object CompletionLock = new object();
    private volatile bool isCompleted; // volatile in order not to change the order of writing Exception and Result

    protected AsyncOperation(bool isCompleted = false)
    {
        IsCompleted = isCompleted;
        Token = OperationToken.New();
    }

    public OperationToken Token { get; protected set; }

    public bool IsCompleted
    {
        get { return isCompleted; }
        protected set { isCompleted = value; }
    }

    public Exception Exception { get; protected set; }

    public bool Wait(int timeout)
    {
        if (!IsCompleted)
        {
            lock (CompletionLock)
            {
                if (!IsCompleted)
                {
                    Monitor.Wait(CompletionLock, timeout);
                }
            }
        }

        return IsCompleted;
    }

    protected void Complete()
    {
        RequireNotCompleted();
        lock (CompletionLock)
        {
            RequireNotCompleted();
            IsCompleted = true;
            Monitor.PulseAll(CompletionLock);
        }
    }

    protected void RequireNotCompleted()
    {
        if (IsCompleted)
        {
            throw new InvalidOperationException("The operation was already completed");
        }
    }

    protected void Complete(Exception exception)
    {
        RequireNotCompleted();
        lock (CompletionLock)
        {
            RequireNotCompleted();
            Exception = exception;
            IsCompleted = true;
            Monitor.PulseAll(CompletionLock);
        }
    }
}

It was always working fine. After migrating the project to .NET 4.5.1 it looks like we have following problems:

*

*We made a Wait(Timeout.Inifinte) and we know that an operation has completed but the thread with Wait is waiting forever... if we set a timeout than it always leave the method after the timeout

*In profiler we see that probably Complete() waits to enter the lock - is Monitor.Wait not giving back the lock?

Here is also the implementation of AsyncCommand which is executed in a worker thread:
internal class AsyncCommand : AsyncOperation
{
    private readonly Action<OperationToken> command;

    public AsyncCommand(Action<OperationToken> command)
    {
        command.ThrowIfNull("command");
        this.command = command;
    }

    public void Execute()
    {
        RequireNotCompleted();
        try
        {
            command(Token);
            Complete();
        }
        catch (Exception ex)
        {
            Complete(ex);
        }
    }
}

Do you see any problem with the following code?
What can cause these problems?
Closed
The above implementation is correct. We had some problems connected with .NET remoting...


text:
Q: Sample k random permutations without replacement in O(N) I need a number of unique random permutations of a list without replacement, efficiently. My current approach:
total_permutations = math.factorial(len(population))
permutation_indices = random.sample(xrange(total_permutations), k)
k_permutations = [get_nth_permutation(population, x) for x in permutation_indices]

where get_nth_permutation does exactly what it sounds like, efficiently (meaning O(N)). However, this only works for len(population) <= 20, simply because 21! is so mindblowingly long that xrange(math.factorial(21)) won't work:
OverflowError: Python int too large to convert to C long

Is there a better algorithm to sample k unique permutations without replacement in O(N)?

A: Up to a certain point, it's unnecessary to use get_nth_permutation to get permutations. Just shuffle the list!
>>> import random
>>> l = range(21)
>>> def random_permutations(l, n):
...     while n:
...         random.shuffle(l)
...         yield list(l)
...         n -= 1
...
>>> list(random_permutations(l, 5))
[[11, 19, 6, 10, 0, 3, 12, 7, 8, 16, 15, 5, 14, 9, 20, 2, 1, 13, 17, 18, 4],
 [14, 8, 12, 3, 5, 20, 19, 13, 6, 18, 9, 16, 2, 10, 4, 1, 17, 15, 0, 7, 11],
 [7, 20, 3, 8, 18, 17, 4, 11, 15, 6, 16, 1, 14, 0, 13, 5, 10, 9, 2, 19, 12],
 [10, 14, 5, 17, 8, 15, 13, 0, 3, 16, 20, 18, 19, 11, 2, 9, 6, 12, 7, 4, 1],
 [1, 13, 15, 18, 16, 6, 19, 8, 11, 12, 10, 20, 3, 4, 17, 0, 9, 5, 2, 7, 14]]

The odds are overwhelmingly against duplicates appearing in this list for len(l) > 15 and n < 100000, but if you need guarantees, or for lower values of len(l), just use a set to record and skip duplicates if that's a concern (though as you've observed in your comments, if n gets close to len(l)!, this will stall). Something like:
def random_permutations(l, n):
    pset = set()
    while len(pset) < n:
        random.shuffle(l)
        pset.add(tuple(l))
    return pset

However, as len(l) gets longer and longer, random.shuffle becomes less reliable, because the number of possible permutations of the list increases beyond the period of the random number generator! So not all permutations of l can be generated that way. At that point, not only do you need to map get_nth_permutation over a sequence of random numbers, you also need a random number generator capable of producing every random number between 0 and len(l)! with relatively uniform distribution. That might require you to find a more robust source of randomness.
However, once you have that, the solution is as simple as Mark Ransom's answer.
To understand why random.shuffle becomes unreliable for large len(l), consider the following. random.shuffle only needs to pick random numbers between 0 and len(l) - 1. But it picks those numbers based on its internal state, and it can take only a finite (and fixed) number of states. Likewise, the number of possible seed values you can pass to it is finite. This means that the set of unique sequences of numbers it can generate is also finite; call that set s. For len(l)! > len(s), some permutations can never be generated, because the sequences that correspond to those permutations aren't in s.
What are the exact lengths at which this becomes a problem? I'm not sure. But for what it's worth, the period of the mersenne twister, as implemented by random, is 2**19937-1. The shuffle docs reiterate my point in a general way; see also what Wikipedia has to say on the matter here.

A: Instead of using xrange simply keep generating random numbers until you have as many as you need. Using a set makes sure they're all unique.
permutation_indices = set()
while len(permutation_indices) < k:
    permutation_indices.add(random.randrange(total_permutations))

A: I had one implementation of nth_permutation (not sure from where I got it) which I modified for your purpose. I believe this would be fast enough to suit your need
>>> def get_nth_permutation(population):
    total_permutations = math.factorial(len(population))

    while True:
        temp_population = population[:]
        n = random.randint(1,total_permutations)
        size = len(temp_population)
        def generate(s,n,population):
            for x in range(s-1,-1,-1):
                fact = math.factorial(x)
                d = n/fact
                n -= d * fact
                yield temp_population[d]
                temp_population.pop(d)
        next_perm = generate(size,n,population)
        yield [e for e in next_perm]

>>> nth_perm = get_nth_permutation(range(21))
>>> [next(nth_perm) for k in range(1,10)]

A: You seem to be searching for the Knuth Shuffle! Good luck!

A: You could use itertools.islice instead of xrange():

CPython implementation detail: xrange() is intended to be simple and
  fast Implementations may impose restrictions to achieve this.  The C
  implementation of Python restricts all arguments to native C longs
  ("short" Python integers), and also requires that the number of
  elements fit in a native C long. If a larger range is needed, an
  alternate version can be crafted using the itertools module:
  islice(count(start, step), (stop-start+step-1+2*(step<0))//step).


text:
Q: Why doesn't changing the "bottom" value of the div to "0" work? Why doesn't changing the "bottom" value of the div to "0" work?
I have top:0 in the css and replace it by bottom:0 in the javascript.
(If I just change the "top" value then it does work...) -
Here is the code:

  window.onload = function() {
    document.getElementById("main").style.top = "";
    document.getElementById("main").style.bottom = "0";
  };
body {
  margin: 0;
  border: 0;
  padding: 0;
}

#all {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  border: 0;
  padding: 0;
  background-color: yellow;
}

#main {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 70%;
  margin: 0;
  border: 0;
  padding: 0;
  background-color: green;
}

A: The top property is still zero - unset it using top: unset at the same time - see demo below:

(function() {
  window.onload = function() {
    document.getElementById("main").style.top = "unset"; /* changed */
    document.getElementById("main").style.bottom = "0";
  }
}());
body {
  margin: 0;
  border: 0;
  padding: 0;
}

#all {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  border: 0;
  padding: 0;
  background-color: yellow;
}

#main {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 70%;
  margin: 0;
  border: 0;
  padding: 0;
  background-color: green;
}

A: Set top to "auto", to eliminate any previous specifications

A: Here is the relevant part from the specification:

For absolutely positioned elements, the used values of the vertical dimensions must satisfy this constraint:
'top' + 'margin-top' + 'border-top-width' + 'padding-top' + 'height' + 'padding-bottom' + 'border-bottom-width' + 'margin-bottom' + 'bottom' = height of containing block
If all three of 'top', 'height', and 'bottom' are auto, set 'top' to the static position and apply rule number three below.
If none of the three are 'auto': If both 'margin-top' and 'margin-bottom' are 'auto', solve the equation under the extra constraint that the two margins get equal values. If one of 'margin-top' or 'margin-bottom' is 'auto', solve the equation for that value. If the values are over-constrained, ignore the value for 'bottom' and solve for that value.

So basically, if you set all the values (top, bottom, height) the browser will decide to ignore the bottom one.
You need to make the top value auto

document.getElementById("main").style.top = "auto";
document.getElementById("main").style.bottom = "0";
body {
  margin: 0;
  border: 0;
  padding: 0;
}

#all {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  border: 0;
  padding: 0;
  background-color: yellow;
}

#main {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 70%;
  margin: 0;
  border: 0;
  padding: 0;
  background-color: green;
}

'top' is 'auto', 'height' and 'bottom' are not 'auto', then set 'auto' values for 'margin-top' and 'margin-bottom' to 0, and solve for 'top'

A:

document.getElementById("main").style.top = "initial";
document.getElementById("main").style.bottom = "0";
body {
  margin: 0;
  border: 0;
  padding: 0;
}

#all {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  border: 0;
  padding: 0;
  background-color: yellow;
}

#main {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 70%;
  margin: 0;
  border: 0;
  padding: 0;
  background-color: green;
}


text:
Q: Vertex Multipartition in Hypergraphs An elementary research question concerning a $k$-regular (finite) hypergraph $H$:
I'm looking for a characterization (and the pre-existing name) of the property that the vertices of $H$ split into $k$ classes such that every hyperedge contains a vertex from each class. Many thanks.

A: "$k$-uniform, $k$-partite"
$k$-uniform means that each edge has $k$ vertices. $k$-partite means there is a vertex partition such that no edge has more than one vertex in each part.


text:
Q: Is there a way to factorize this search code? I have created a code that allows the registration to fill in Country Region District and City fields. I created a model for everyone. I made the relations between the tables (see the code below).
I created the different model because then I have a search form that is populated by the database of countries, region, district and city that are registered at the registration of users.
Do you think there is a method to do this more neatly?
User_model :
belongs_to :country
  belongs_to :region
  belongs_to :district
  belongs_to :city
  # sert à trouver la longitude et la latitude en fonction de l'adresse
  after_validation :geocode
  geocoded_by :full_address
  def full_address
    [self.country.name, self.region.name,self.district.name,self.city.name].compact.join(', ')
  end

  after_initialize do
    self.address ||= Address.new if self.new_record?
  end

# sert à créer les coordonées d'un membre ou d'un partenaire en fonction des champs country_name dans la table Country etc..
  attr_accessor :country_name, :region_name, :district_name, :city_name
  before_validation do
    self.country_id = Country.find_or_create_by(name: self.country_name).id if self.country_name.present?
    self.region_id = Region.find_or_create_by(name:self.region_name,country_id: self.country_id).id if self.region_name.present?
    self.district_id = District.find_or_create_by(name: self.district_name,region_id: self.region_id).id if self.district_name.present?
    self.city_id = City.find_or_create_by(name: self.city_name,district_id: self.district_id).id if self.city_name.present?
  end

Country.rb
class Country < ApplicationRecord
  has_many :users
  has_many :regions
end

Region.rb
class Region < ApplicationRecord
  belongs_to :country
  has_many :districts
  has_many :users
end

District.rb
class District < ApplicationRecord
  belongs_to :region
  has_many :users
  has_many :cities
end

City.rb
class City < ApplicationRecord
  belongs_to :district
  has_many :address
  has_many :users
end

User_controller
def search
    if params[:search].present? || params[:country].present? || params[:city].present? || params[:district].present? || params[:postalCode].present?
      if !params[:region].present?
        @result = Partner.where({country_id:params[:country]})
      elsif !params[:district].present?
        @result = Partner.where({country_id:params[:country],region_id:params[:district]})
      elsif !params[:city].present?
        @result = Partner.where({country_id:params[:country],region_id:params[:district],district_id:params[:district]})
      elsif !params[:postalCode].present?
        @result = Partner.where({country_id:params[:country],region_id:params[:region],district_id:params[:district],city_id:params[:city]})
      else
        @result = @partner_with_address.where(addresses:{city:params[:city],district:params[:district],country:params[:country],postal_code:params[:postalCode]})
      end
    else
      @result = Partner.all
    end
    respond_to do |format|
      format.js
    end
  end

search_form :
<%= form_tag(search_url, method: :get, :remote => true) do %>

          <%= text_field_tag :search,nil,placeholder:t('search_form.type_your_keywords'), id:"search", type:"text" %>

            <svg class="svg-inline--fa fa-search fa-w-16" fill="#ccc" aria-hidden="true" data-prefix="fas" data-icon="search" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
              <path d="M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z"></path>
            </svg>

        <%= t('search_form.advanced_search').upcase%>

              <%=select_tag :country, options_for_select(Country.all.collect{|p| [p.name, p.id]}, selected: params[:country]), prompt:t('search_form.country'), id:"country",class:"countries order-alpha",style:"height:50px" %>

              <%=select_tag :region,options_from_collection_for_select(Region.order(:name),:id,:name, params[:region]), prompt:t('search_form.district'),id:"region",class:"states order-alpha", style:"height:50px" %>

              <%=select_tag :district,options_from_collection_for_select(District.order(:name),:id,:name,params[:district]),  prompt:t('search_form.district'),id:"district",class:"states order-alpha", style:"height:50px" %>

              <%=select_tag :city,options_from_collection_for_select(City.order(:name),:id,:name,params[:city]), prompt:t('search_form.city'), id:"city",class:"cities order-alpha",style:"height:50px" %>

              <%= text_field_tag :postal_code,params[:postal_code], placeholder:t('search_form.postalCode'), id:"search", type:"text",style:"height:50px" %>

              <button class="button ripple-effect"><%= t('search_form.search').upcase%></button>

  <%end%>

A: You could separate the logic in your models into concerns and include them where needed.
https://www.sitepoint.com/dry-off-your-rails-code-with-activesupportconcerns/
More importantly, you could create some query objects for your searches, that params[:search] logic could be refactored to use a PartnerQuery for example, and in your controller you'd do @result = PartnerQuery.new(...).call(params).
https://mkdev.me/en/posts/how-to-use-query-objects-to-refactor-rails-sql-queries - there are some nice examples here
The form can go into partials, one or multiple depending on how/what components can be reused. Possibly look into thoughtbot's cells if you want to get more involved. Only do it on an as-needed basis (eg when you find yourself writing the same view component more than twice just separate into partials) to avoid overengineering.


text:
Q: SQL Native Client 11 - SQL Server 2017 We currently connect to SQL Server 2014 with the Native Client without any issues.
However, the SQL Server is being upgraded to SQL 2017. I have been told that SQL Native Client will no longer work for connecting, and we need to install the OLE DB driver instead.
Is this correct? I have not found much online other than the Native Client is deprecated and also this article on the lifecycle.
What impact would this have on existing .Net applications and SSIS packages that connect to the database.
Here is a sample connection from an application...
connectionString="metadata=res://*/LoggingModel.csdl|res://*/LoggingModel.ssdl|res://*/LoggingModel.msl;provider=System.Data.SqlClient;provider connection string="data source=myServer;initial catalog=DBLogging;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"

A: Microsoft has deprecated the SQL Server Native Client (NCLI) driver, however SQL Server itself uses a wire-protocol, TDS that is independent of the driver used by the client.
NCLI will continue to work for the forseable future, however no new work will be conducted by Microsoft on the NCLI driver.
Pedro Lopez talks about the announcement, and subtle un-deprecation here.  Also included are some sample connection string changes that will help migrate over to the MSOLEDBSQL driver.

A: I just installed the ODBC client for SQL 2017 for a python process yesterday. It seems to be working just fine. MS has stated the ODBC driver would be deprecated for at least 7 years now. I'm not convinced it's ever going away, but who knows. edit: Just tested connecting to SQL Server 2017 using the driver... seems to work just fine. – Jacob H


text:
Q: How can i upload multiple files into a CELL? I tried uploading multiple files into my database but I keep getting just one file, Am using laravel 5.5 all files show on my file directory path but store only one file into my database. Here is my code
my view
<label for="image">{{ __(' image') }}</label>
 <input type="file" name="image[]" class="form-control" value="{{ $employee['image'] }}" multiple>

my route
Route::post('/people/employees/test/{id}', 'EmplController@test');

my controller
if($request->hasfile('image')){
        foreach ($request->image as $image) {
            $path = $image->getClientOriginalName();
            $filename = time() . '-' . $path;
$image->storeAs('employees', $employee->id . '/' . $filename);
            $image->move(public_path('employees'),$filename);
i inserted image here->$employee->image = $filename;
  $employee->save();

  }
}

A: Make an array, and implode it before insert to table, like  :
$files = []; // an empty array
foreach($a as $b) {
   $files[] = $b->name; // insert name to array
}

$files = implode(",", $files); // insert $files into your table

So you need to change on your code :
if($request->hasfile('image')){
        $files = []; // make an array
        foreach ($request->image as $image) {
            $path = $image->getClientOriginalName();
            $filename = time() . '-' . $path;
            $files[] = $filename; // insert to array
$image->storeAs('employees', $employee->id . '/' . $filename);
            $image->move(public_path('employees'), $filename);
         }
         $files = implode(",", $files); // insert $files into your table
}


text:
Q: settext to edit text in android I have an activity and it has theme as dialog .
inthis activity, 10 edit text's are there. for one edit box  i am unable to set text to the edit box.
public void onCreate(Bundle savedInstanceState) {
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    is_tablet=SharedVariables.sharedPrefDate.getBoolean("isTablet", false);
    if(!is_tablet){
        super.setTheme(android.R.style.Theme_Black_NoTitleBar);
    }
    //overridePendingTransition(R.anim.slide_bottom_to_top,0);
    super.onCreate(savedInstanceState);
    activity=UpdateCasePersonAddressScreen.this;
    setContentView(R.layout.update_person_address_screen);

    //allocating memory to objBLAddCasePersonScreenOperations
    objBLAddPersonAddressScreenOperations=new BLAddUpdatePersonAddressScreenOperations();
    objBLCommonOperations=new BLCommonOperations();
    getAllIds();

    //objPersonAddress=new clsPersonAddress();
    bundle = getIntent().getExtras();

    //code to get all objects using Bundle from previous activity
    if(bundle!=null){

        objPersonAddress = (clsPersonAddress) bundle.getParcelable("clsPersonAddress");
        System.out.println("from Extras");
        bundle=null;
    }

    initTextFields();
    inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    /* if (inputMethodManager != null) {
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }*/
}
public void initTextFields(){

    updatePersonAddressTitleEditText.setText(objPersonAddress.getAddressTitle());
    updatePersonAddressMemoEditText.setText(objPersonAddress.getAddressMemo());
    updatePersonAddressNameEditText.setText(objPersonAddress.getAddressName());
    updatePersonAddressBusinessNameEditText.setText(objPersonAddress.getAddressBusinessName());
    updatePersonAddressWorkPhoneEditText.setText(objPersonAddress.getAddressWorkPhone());
    updatePersonAddressHomePhoneEditText.setText(objPersonAddress.getAddressHomePhone());
    updatePersonAddressMobilePhoneEditText.setText(objPersonAddress.getAddressMobilePhone());
    updatePersonAddressAddressLine1EditText.setText(objPersonAddress.getAddressLine1());
    updatePersonAddressAddressLine2EditText.setText(objPersonAddress.getAddressLine2());
    updatePersonAddressCityEditText.setText(objPersonAddress.getAddressCity());

    System.out.println("objPersonAddress.getAddressState()))))))))))))))))))))))))))))))))))"+objPersonAddress.getAddressState());

    updatePersonAddressStateEditText.setText(objPersonAddress.getAddressState().toString());//setText(objPersonAddress.getAddressState(), TextView.BufferType.EDITABLE);
    System.out.println("updatePersonAddressStateEditText text is now is:"+updatePersonAddressStateEditText.getText().toString()+"null check:"+updatePersonAddressStateEditText.toString());
    System.out.println("below objPersonAddress.getAddressState()))))))))))))))))))))))))))))))))))"+objPersonAddress.getAddressState());

    updatePersonAddressZipEditText.setText(objPersonAddress.getAddressZip());
    updatePersonAddressCountryEditText.setText(objPersonAddress.getAddressCountry());
}

can any body help me in this issue.For any help thanks in Advance.

A: EditText edit;// define it before onCreate

edit=(EditText)findViewById(R.id.edittext); //get it from xml

String value="123";
//simply use

edit.setText(value);

A: Android native:
String text = "Example";
EditText edtText = (EditText) findViewById(R.id.edtText);
edtText.setText(text);`

Look! EditText accept only String values, if necessary convert to String.
if int, double, long value, do:
String.value(value);

Exemple:
int i = 5;
edtText.setText(String.value(i));

Android annotations:
@ViewById
EditText edtText;

To set:
@UiTread
void setText(){
    edtText.setText("Text");
}

To call:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setText();
}

A: just write down like this
EditText editText=(EditText)findViewById(R.id.editText1);
        editText.setText("abc");


text: Q: Aligning multiple images with different spatial resolutions I am using 2 different satellite images that have different spatial resolutions. One of them has 1 degree and other has 0.25 degree resolution. I want to subtract one image from another. So I should resample 0.25 to 1 degree resolution. When I do that, it is resampled to 1 degree but not overlay with other image. It is shifting below. Am I doing something wrong ? The both data have same projections and datum.


text:
Q: document.cookie work around in Chrome The following code writes a cookie. However, in chrome document.cookie does not seem to work. Is there any work arounds? I need to set this cookie in all browsers.
Do I  have anyother options?
//Cookie Functions
function createCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    var cookie_string = name + "=" + value + expires;
    //document.cookie =  + "; path=/";
    cookie_string += "; path=" + (cookiePath.length ? cookiePath : '/');
    cookie_string += "; domain=" + (cookieDomain.length ? cookieDomain : window.location.hostname);
    if ( cookieSecure ) {
        cookie_string += "; secure";
    }
    document.cookie = cookie_string;
    alert("Your Cookie : " + document.cookie);
}

A: When you access this script from local which does not work in chrome, eg:-
c:\yourFolder\yourScript

If you access this script from remote server then it does work. eg:-
loalhost\yourFolder\yourScript

Here localhost is remote server / web server.
You can put your script into htdocs of xampp folder for experiment.
XAMPP is a software package of php, mysql, apache server. Which is work as remote/web server in your case.


text:
Q: Is it possible to use IPC inside of a IE8 Browser Helper Object? I need to communicate with a Service using IPC from inside of a Browser Helper Object (registered with IE8).  Unfortunately, all of this communication is done through an Assembly API that I have no control over.  Whenever this API starts up I get the following error:

ExceptionSystem.Runtime.Remoting.RemotingException: Failed to connect to an IPC Port: The system cannot find the file specified.

I realize that it is difficult to discern what the issue is without source.  However I am curious if anyone knows of anything sort of permissions or DLL issues that would prevent IPC from working in this case.

A: It looks like this issue can be caused by a number of things.
UAC, as always, can be an issue and should be disabled to make sure it isn't causing problems.
The other issue is that IE allocates a process for the main frame as well as individual tabs.  This means that there is no guarantee that your BHO is in the main frame process.  If you set the following registry key, IE will prevent the browser from allocating extra tab processes:
[HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main]"TabProcGrowth"=dword:00000000
In general, neither of these solutions are ideal though.  I ended up backing away from this entire attempt as it seems very problematic from a number of angles.


text:
Q: RESTHeart filtering and sorting by sub documents property I m working with mongodb and restheart.
In my nosql db i have a unique document with this structure:
{
"_id": "docID",
"users": [
            {
             "userID": "12",
             "elements": [
                           {
                            "elementID": "1492446877599",
                             "events": [
                                         {
                                          "id": 1,
                                          "date": 356
                                         },
                                         {
                                           "id": 2,
                                           "date": 123
                                          }
                                       ]
                            }
                        ]
               },
              {
                "userID": "11",
                "elements": [
                              {
                                "elementID": "14924",
                                "events": [
                                           {
                                            "id": 1,
                                            "date": 123
                                            },
                                            {
                                             "id": 2,
                                             "date": 356
                                             }
                                           ]
                               },
                               {
                                "elementID": "14925",
                                "events": [
                                           {
                                            "id": 1,
                                            "date": 12
                                            },
                                            {
                                             "id": 2,
                                             "date": 36
                                             }
                                           ]
                               }
                         ]
              }

i need to filter the user with userID = 11 and i need to order his events by ascending date.
i was trying with:
http://myhost:port/myCollection?keys={"users":{"$elemMatch":{"userID":"11"}}}&sort_by={"users.elements.events.date":-1}
but it doesn t work.

A: db.v.aggregate([
    { $unwind : '$users'},
    { $match : { 'users.userID' : '11' }} ,
    { $unwind : '$users.elements'},
    { $unwind : '$users.elements.events'},
    { $sort : {'users.elements.events.date': 1}},
    { $group : {
        _id : '$_id',
        elementID : { $first : '$users.elements.elementID' },
        userID : { $first : '$users.userID' },
        events : { $push : '$users.elements.events'}
        }
    },
    { $project : {
        _id : 1,
        userID : 1,
        'elements.elementID' : '$elementID',
        'elements.events' : '$events'
        }
    }

]);

This will give you following :
{
    "_id" : ObjectId("5911ba55f0d9c285c561ea33"),
    "userID" : "11",
    "elements" : {
        "elementID" : "14924",
        "events" : [
            {
                "id" : 1,
                "date" : 123
            },
            {
                "id" : 2,
                "date" : 356
            }
        ]
    }
}