text:
Q: extracting specific data from a table I have table which looks like this (tab separated):
Ron  Rob  rock bammy
m    f   m  f
florida  Atlanta  florida texas

This table is of order 5*512 and based on row 3 data, I want to extract the values in row1.
 for example: I want to have names of all person living in florida and texas, in a table of 2 columns and n number of rows.
Florida  Ron
Florida  Rock
Texas BAmmy

and so on.
any suggestions for a bash or PERL liners...
Thank you in advance.

A: awk 'NR==1{for(i=1;i<=NF;i++)n[i]=$i}; NR==3{for(i=1;i<=NF;i++){if($i~/florida|texas/)print $i"\t"n[i];}}' yourFile

see the test below:
kent$  echo "Ron Rob rock bammy
m f m f
florida Atlanta florida texas"|awk 'NR==1{for(i=1;i<=NF;i++)n[i]=$i}; NR==3{for(i=1;i<=NF;i++){if($i~/florida|texas/)print $i"\t"n[i];}}'

output
florida Ron
florida rock
texas   bammy

EDIT
kent$  echo "Ron  Rob  rock bammy
m    f   m  f
florida(8)  Atlanta  florida(8) texas(2;7)"|awk 'NR==1{for(i=1;i<=NF;i++)n[i]=$i}; NR==3{for(i=1;i<=NF;i++){if($i~/florida\(8\)|texas\(2;7\)/)print $i"\t"n[i];}}'

output:
florida(8)      Ron
florida(8)      rock
texas(2;7)      bammy

A: Yet another Perl solution:
perl -ane 'push@c,@F}{print grep{/^(florida|atlanta)\t/i}map{"$c[$_+$#c/3*2+1]\t$c[$_]\n"}0..$#c/3'

Or as a script
#!/usr/bin/perl

use strict;
use warnings;

my (@data, @rows);

push @data, split/\s+/ while (<>);

for (0 .. $#data/3) {
    my $name = $data[$_];
    my $location = $data[$_+$#data/3*2+1];
    push @rows, "$location\t$name\n" if $location =~ /^(florida|atlanta)$/i;
}

print join("", @rows);

with an if condition inside the loop instead of the separate grep.
My approach is to flatten all three lines into a single array and use for (0 .. $#data/3) to loop over the indexes corresponding to the names from the first line and get the location from the matching column with $data[$_+$#data/3*2+1].

A: Here's a Perl solution that works, but it's a bit more convoluted that I'd like. You'd probably be better off putting this data into a database.
#!/usr/bin/env perl

use strict;
use warnings;
use 5.010;

my %rows = (
  name => 1,
  location => 3,
);

my %location = map { $_ => 1 } qw[florida texas];

my @names;

while (<DATA>) {
  next unless grep { $_ == $. } values %rows;

  chomp;

  if ($. == $rows{name}) {
    @names = split;
  }

  if ($. == $rows{location}) {
    my @locs = split;

    for my $x (0 .. $#locs) {
      if ($location{lc $locs[$x]}) {
        say ucfirst $locs[$x]. "\t$names[$x]";
      }
    }
    last;
  }
}

__END__
Ron     Rob     rock    bammy
m       f       m       f
florida         Atlanta florida texas

A: #!/usr/bin/env perl
use strict;
use warnings;

my $pat = shift;

sub interleave($$){
    my ($foo,$bar) = @_;
    return map { ( $_ , shift @{$bar} ) } @{$foo};
}

my $n=0;
my(@p,%h);
while(<>){
    chomp;
    if($n%3==0){
            @p = split /\t/, $_;
    } elsif($n%3==2){
            my @l = split /\t/, $_;
            my %kv = interleave(\@p, \@l);
            foreach my $k (keys %kv){
                    push(@{$h{$kv{$k}}}, $k);
            }
    }
    $n++;
}

foreach my $loc (keys %h){
    if(!defined $pat || $loc =~ /$pat/i){
            foreach my $name (@{$h{$loc}}){
                    print ucfirst($loc), "\t", ucfirst($name), "\n";
            }
    }
}

And then call it
perl extract.pl 'texas|florida' < data

"Oneliner" form:
perl -ne 'BEGIN{$p=shift||"^";}chomp;if($n++%3!=1){unless(@p){@p=split/\t/,$_;next;}my %kv = map { ( $_ , shift @p ) } split(/\t/, $_);map { push(@{$h{$_}}, $kv{$_}); } keys %kv;}END{map{for my$nm(@{$h{$_}}){print ucfirst($_),"\t",ucfirst($nm),"\n";}}grep{/$p/i}keys%h;}' 'florida|texas' < data

A: Sounds to me like this is a job for Text::CSV_XS. It is not a good idea to split on whitespace, as many seem to be suggesting, as that will fail for anything but simplified data.
Code:
use strict;
use warnings;
use Text::CSV_XS;

my $csv = Text::CSV_XS->new( {
        sep_char    => "\t",
        binary      => 1,
    });

# get array refs to each row, with appropriate name
# For larger data sets, using an array to hold the array refs would be better
my $name       = $csv->getline(*DATA);
my $gender     = $csv->getline(*DATA);
my $city       = $csv->getline(*DATA);

for (keys @$city) {   # lists the column numbers
    if ($city->[$_] =~ /florida|texas/i) {
        print "$city->[$_]\t$name->[$_]\n";
    }
}

__DATA__
Ron Rob rock    bammy
m   f   m   f
florida Atlanta florida texas

Output:
florida Ron
florida rock
texas   bammy


text:
Q: Why does my newly installed Django project only display the welcome page? Right up front: I'm pretty new to python and django, but I've done the tutorial and some other basic stuff on a local install.
I recently started a django project on a live server (hostgator.com, with fastcgi) to the point where it shows that "It worked! Congratulations on your first Django-powered page." message. Next, I uncommented the appropriate lines in urls.py in order to enable the built-in django admin. I also figured out how to restart the fastcgi on my server just in case.
Upon going to /admin, it still displayed the welcome page. In fact, no matter what I put after the /, it displays the welcome page no matter what. I have also tried creating a blog app and getting that to display, but that also didn't work.
I get the feeling I've missed something painfully obvious, or there's something horribly wrong with my setup.
It is worth mentioning that my django project is set up in a subdomain. Thinking this was the problem, I tried writing a middleware that overwrote process_request from a tutorial here: http://djangosnippets.org/snippets/1119/. Still, the welcome page is the only thing that displays.
Any help would be greatly appreciated.
UPDATE:
I guess it would help if I put up some code, which you think I would have thought before.
Here is my urls.py:
from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^/$', 'blog.views.index'),
    (r'^admin/', include(admin.site.urls)),
)

Here are the INSTALLED_APPS in settings.py
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    'blog',
)

I haven't added anything to any views.py just yet.
I have run syndb, and here is the list of the db tables:
auth_group
auth_group_permissions
auth_message
auth_permission
auth_user
auth_user_groups
auth_user_user_permissions
django_admin_log
django_content_type
django_session
django_site

A: Are you sure you have restarted the server properly? Try putting some text in urls.py to provoke a syntax error to make sure the restart did in fact work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is it necessary to use module name twice when creating an angular app? var demoApp = angular.module( 'demoApp', [] );

Why didn't the angular team simply choose to do:
var demoApp = angular.module ([]);

instead?

A: You don't have to if you don't want to. You can write any of the following and they're the same thing
var demoApp = angular.module('demoApp', []);
var diffApp = angular.module('demoApp', []);
angular.module('demoApp', []);

The variable you assign it to can be named whatever you want it to be, but the name you pass in to the module function is the name that angular will give it internally. That name must be the same name you use to retrieve it later. So for instance, you could do the following
angular.module('demoApp', []);
angular.module('demoApp').controller('ctrl', function(){ ... });

And that is exactly the same as doing
var myApp = angular.module('demoApp', []);
myApp.controller('ctrl', function() { ... });

When you provide the module function a second parameter, you are defining a new module. If you just provide it with a string, you are asking angular to retrieve you a module.


text:
Q: How to sign setup with .crt file? I've got a Comodo certificate to sign my application files with the appropriate publisher (that'll be me).
But how do I sign my installation to prevent those triple "are you sure?" UAC dialogs?
Am using the Visual Studio (2008) setup project, no third party tools.

A: I dont think you can disable UAC dialogs. For installer signing, I think signtool in the Windows SDK will do what you need.


text:
Q: Tannakian fundamental group of automorphic representations Let $\mathcal{C}_{\mathrm{aut}}(G, F)$ be the category of automorphic representations of a connected reductive group $G$ over a number field $F$.
If this is a Tannakian category, it has an associated Tannakian fundamental group $G^{\mathrm{aut}}_F$. What is it and how is it related to $G$ itself (for example, for $G = \operatorname{GL}_n$)? In other words, what does Tannakian duality recover in this case?
EDIT: In light of Bugs Bunny's answer below, if we consider the group of endomorphisms of the forgetful functor from $\mathcal{C}_{\mathrm{aut}}(G, F)$ (with completed tensor product) to the category of Hilbert spaces, how is the group related to $G$?

A: It is not a tannakian category. The issue is the tensor product. Let $V$ and $W$ be automorphic representations. The algebraic tensor product $V\otimes W$ is no longer automorphic. You need some kind of completion $V\widehat{\otimes}W$ but, according to David Loeffler, the completion is too big to be automorphic.


text:
Q: Sharing Localhost on Network in Windows 7 Basically - I am producing a website and I am trying to share the "localhost" port on 2 computers.
Basically, when I build the project I just want to also be able to access it on both computers via the same port.
Currently, I cant seem to be able to do this ? Anyone can help with step-by-step ?
Thx

A: If I'm understanding you right you want localhost on machines A and B to point to the same place -- This is simultaneously exactly what's happening and completely impossible :-)
localhost by convention always points to 127.0.0.1, the magic loopback IP of the local machine (i.e. 127.0.0.1 on machine A always means machine A; 127.0.0.1 on machine B always means machine B).  It's not an address that can be shared between multiple machines (in fact the entire 127.0.0.0/8 network is reserved for loopback use).
To do what you want you need to connect both machines over a network, assign them non-loopback IPs (private addresses out of 10.0.0.0/8, 172.16.0.0/12 or 192.168.0.0/16) & run your service over those addresses.

Consult a good networking book for more details...


text:
Q: How to remove formatting from mysql query in python I'm working on a discord bot in python and so far I've got it to connect and fetch queries from the database and send it to the discord server. But the output is formatted still, how do I remove the brackets/commas.
Code:
@bot.command()
    async def mtop(ctx, arg1):
    db = pymysql.connect(host=config.db_host, port=3306, user=config.db_user, passwd=config.db_passwd, db=config.db_name)
    cur = db.cursor()
    cur.execute("SELECT name FROM ck_playertimes WHERE mapname = %s AND runtimepro > -1.0 AND style = 0", (arg1,))
    name = cur.fetchone()
    await ctx.send(name)
    cur.close()
    db.close()

It outputs like this:
('Evan',)

Thank you.

A: The brackets and commas indicate that "Evan" is inside of a tuple. So if your tuple will only have one element, then you can do ("Evan",)[0] in order to get the first element. If there are several elements in your tuple, then you will need to iterate through each one using a for loop. Like this:
for element in tup:
    # do something with element


text:
Q: Set maximum execution time I have a function in jquery where there is a while loop which can take a few seconds to finish. In Chrome th script runs fast, but in Firefox the same script blocks the UI thread too long. So I would like to set a timeout to this function, if it's not finished in one second then I exit it. Is is possible to do it in jQuery?

A: var count = 1;
var counter = setInterval(timer, 1000); //1000 will  run it every 1 second

function timer() {
    if (count <= 0) {
        clearInterval(counter);
        return;
    }
    count = count - 1;
   //Runs code
}

below code will timeout after 1000 milisecond.
(i understand mistake)

A: Ok so I've solved it by doing this :
var n = 0;

setTimeout(function() {
    n = 1;
}, 1000);

And in my while loop I check if n == 0


text:
Q: CMake [build] stuck on one percentage throughout build yet still builds When building with cmake no longer getting increasing percentages, just stuck at 40%. The build still works.
[build] [ 40%] ...
[build] [ 40%] ...
[build] [ 40%] ...

A: This was a permissions issue. Solved by changing the build/CMakeFiles/Progress directory to have correct ownership, e.g. using chown or chmod.
Same issue spotted in 2006: https://cmake.org/pipermail/cmake/2006-October/011544.html


text:
Q: Trouble writing NDEF record to NTAG213 using external NFC reader (but writing to memory works) I am using the sample provided by Michael Roland in this answer and modified the bytes command structure to match this answer.
After I scan the tag, I receive 90 00 responses from the reader. When I then scan the tag using NFC Tools though, I don't see that it has an NDEF record (photo). If I examine the memory I can see my data written starting at block 4 as follows here.
Meanwhile, if I use the Write Tag feature of NFC Tools to write an NDEF message and then scan the tag again, it does work. The memory in the blocks other than those starting at block 4 appear to be identical (photo).
I don't believe it's a capability container issue as the memory is identical in block 3 after writing to the tag from my reader vs. NFC Tools.
Do I need to do any other kind of NDEF read / check command prior to writing to block 4?
My code below:
                         byte[] ndefMessage = new byte[] {
                                (byte)0xD1, (byte)0x01, (byte)0x0C, (byte)0x55, (byte)0x01, (byte)0x65, (byte)0x78, (byte)0x61, (byte)0x6D, (byte)0x70, (byte)0x6C, (byte)0x65, (byte)0x2E, (byte)0x63, (byte)0x6F, (byte)0x6D, (byte)0x2F
                        };

                        // wrap into TLV structure
                        byte[] tlvEncodedData = null;
                        Log.e("length",String.valueOf(ndefMessage.length));
                        if (ndefMessage.length < 255) {
                            tlvEncodedData = new byte[ndefMessage.length + 3];
                            tlvEncodedData[0] = (byte)0x03;  // NDEF TLV tag
                            tlvEncodedData[1] = (byte)(ndefMessage.length & 0x0FF);  // NDEF TLV length (1 byte)
                            System.arraycopy(ndefMessage, 0, tlvEncodedData, 2, ndefMessage.length);
                            tlvEncodedData[2 + ndefMessage.length] = (byte)0xFE;  // Terminator TLV tag
                        } else {
                            tlvEncodedData = new byte[ndefMessage.length + 5];
                            tlvEncodedData[0] = (byte)0x03;  // NDEF TLV tag
                            tlvEncodedData[1] = (byte)0xFF;  // NDEF TLV length (3 byte, marker)
                            tlvEncodedData[2] = (byte)((ndefMessage.length >>> 8) & 0x0FF);  // NDEF TLV length (3 byte, hi)
                            tlvEncodedData[3] = (byte)(ndefMessage.length & 0x0FF);          // NDEF TLV length (3 byte, lo)
                            System.arraycopy(ndefMessage, 0, tlvEncodedData, 4, ndefMessage.length);
                            tlvEncodedData[4 + ndefMessage.length] = (byte)0xFE;  // Terminator TLV tag
                        }

                        // fill up with zeros to block boundary:
                        tlvEncodedData = Arrays.copyOf(tlvEncodedData, (tlvEncodedData.length / 4 + 1) * 4);

                        for (int i = 0; i < tlvEncodedData.length; i += 4) {
                            byte[] command = new byte[] {
                                    (byte)0xFF, // WRITE
                                    (byte)0xD6,
                                    (byte)0x00,
                                    (byte)((4 + i / 4) & 0x0FF), // block address
                                    (byte)0x04,
                                    0, 0, 0, 0
                            };

                            System.arraycopy(tlvEncodedData, i, command, 5, 4);

                            ResponseAPDU answer = cardChannel.transmit(new CommandAPDU(command));
                            byte[] response = answer.getBytes();
                            writeLogWindow("response: "+ byteArrayToHexString(response));
                        }

A: I believe that the problem is that Michael Roland's answer has a bug in it.
D1 01 0C 55 01 65 78 61 6D 70 6C 65 2E 63 6F 6D 2F is not a valid Ndef message.
If you look at the various specs for Ndef at https://github.com/haldean/ndef/tree/master/docs (specifically the NFCForum-TS-RTD_URI_1.0.pdf and NFCForum-TS-NDEF_1.0.pdf) his example of "http://www.example.com/" is actually made up of "http://www." which has a type code of 01 and 12 characters or the rest of the URL.
Thus the payload length is 13 (1 + 12) bytes so OD where as his message:-
D1 01 0C 55 01 65 78 61 6D 70 6C 65 2E 63 6F 6D 2F
only specifies the length of the second part of the URL and not the prefix, so is one byte too short.
This is confirmed if you try and write a record for that URL using the NFC Tools App or NXP's TagWriter App both generate a message of
D1 01 0D 55 01 65 78 61 6D 70 6C 65 2E 63 6F 6D 2F
So try using in your code
byte[] ndefMessage = new byte[] {
    (byte)0xD1, (byte)0x01, (byte)0x0D, (byte)0x55, (byte)0x01, (byte)0x65, (byte)0x78,
    (byte)0x61, (byte)0x6D, (byte)0x70, (byte)0x6C, (byte)0x65, (byte)0x2E, (byte)0x63,
    (byte)0x6F, (byte)0x6D, (byte)0x2F
};


text:
Q: WCF - An error occurred while receiving the HTTP response to http://xxxxx/Service/ I am making this call in my WCF service:
public User GetStudentRecord(string userName)
    {
        try
        {
            return new DashboardFacade().GetStudentRecord(userName);
        }
        catch (Exception ex)
        {
            ServiceFault fault = new ServiceFault();
            fault.Operation = "GetStudentRecord";
            fault.Reason = "Who knows...";
            fault.Message = ex.Message;
            throw new FaultException<ServiceFault>(fault, fault.Message, new FaultCode(fault.Reason), fault.Operation);
        }
    }

DashboardFacade().GetStudentRecord(..) is defined like this:
public User GetStudentRecord(string userName)
{
    User user = ctx.Users.Where(x => x.ADUserName == userName).SingleOrDefault();
    return user;
}

ctx is my DbContext. I am using Entity Framework Code First. The User object looks like this:
public class User
{
    public User()
    {
        //UserDetails = new UserDetail();
    }
    [Key]
    public Guid MasterKey { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string ADUserName { get; set; }
    public string UserType { get; set; }
    public virtual UserDetail UserDetails { get; set; }
    public Nullable<DateTime> LastModifiedDate { get; set; }
}

And finally, you probably need to see the web.config on the WCF Application:
<?xml version="1.0"?>
    <configuration>
      <connectionStrings>
        <add name="NotMyDBContextDB" connectionString="[omitted]" providerName="System.Data.SqlClient"/>
        <add name="ApplicationContext" connectionString="Data Source=.;Initial Catalog=MyApp;Integrated Security=True;Pooling=False" providerName="System.Data.SqlClient"/>
      </connectionStrings>
   <system.web>
     <compilation debug="true" targetFramework="4.0"/>
   </system.web>
   <system.serviceModel>
     <behaviors>
       <serviceBehaviors>
          <behavior>
             <serviceMetadata httpGetEnabled="true"/>
             <serviceDebug includeExceptionDetailInFaults="true"/>
          </behavior>
        </serviceBehaviors>
      </behaviors>
      <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>

Can anyone point me to where I am going wrong here?
This is the exact error I am getting:
An error occurred while receiving the HTTP response to http://localhost:5843/MyService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

Inner Exception:
The underlying connection was closed: An unexpected error occurred on a receive.

Inner Exception:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Inner Exception:
An existing connection was forcibly closed by the remote host

A: I had this problem and in my case, the issue was the WCF service was returning a class that had a property with only a getter and no setter. I was trying to prevent the property from being modified by the receiver. To get around this, see this...
WCF Services and Object Constructors

A: I had the same error.
In my case I have a table with an int column called OEM.
In the model layer I have a class (DTO) with that column represented by an Enum.
There was a row in the table which value in OEM colum was not valid.
When I was trying to bring all data using LINQ, there was an error that wasn't captured by VisualStudio.
That error raised when WCF tried to retrieve the message.

A: Found the root cause after a lot of swearing and thinking of how nice the weather is outside. I remove the virtual keyword from the UserDetails object that is inside the User object.
Now it works!
As far as why this caused an issue, my assumptions are serialization or DbContext issues, but I will have to look more into it, not sure.
I'm going outside now.
So for reference, if you wound up here and have no idea what is going on, among all the other things you should look at (size, timeout, etc):
Check to see if your object has virtual keyword on it.

A: I had the same Exception but none of the answers above gave me a solution.
I figured out the error by defining a trace in web.config :
<system.diagnostics>
<sources>
  <source propagateActivity="true" name="System.ServiceModel" switchValue="Information, ActivityTracing">
    <listeners>
      <add type="System.Diagnostics.DefaultTraceListener" name="Default">
        <filter type="" />
      </add>
      <add initializeData="C:/temp/tracelog.svclog" type="System.Diagnostics.XmlWriterTraceListener" name="traceListener">
        <filter type="" />
      </add>
    </listeners>
  </source>
</sources>
</system.diagnostics>

I ran the website locally, fired a few failing calls and the opened the tracelog selecting the failed entry, inside that entry I saw this exception :
The entity or complex type 'Person' cannot be constructed in a LINQ to Entities query.
Constructing the person outside of the query fixed the issue so instead of :
 var persons = (from p in db.Persons
                  select new Person
                  {
                      Id = p.Id,
                      Name = p.Name,
                      LastName = p.LastName,
                      Email = p.Email
                  }
              ).AsEnumerable();

  return persons;

I had to do :
var persons = (from p in db.Persons
                  select new
                  {
                      Id = p.Id,
                      Name = p.Name,
                      LastName = p.LastName,
                      Email = p.Email
                  }
              ).AsEnumerable()
                //construct the complex type outside of DB  (to prevent the exception that model cannot be constructed in linq to entities)
                .Select(item =>

                    new Person
                    {
                        Id = item.Id,
                        Name = item.Name,
                        LastName = item.LastName,
                        Email = item.Email
                    }).ToList();

            return persons;

I could have saved alot of time if the exception message was more comprehensive, judging by all the different causes outlined in this topic I guess people will agree with me.
Anyway, this is how I figured out the issue, hopefully this will help someone else to

A: None of the methods worked for me. What I did was to debug the service while running from the WCF Test Client and I was able to find my issue. It was to do with the service library missing the connection string in the app.config.
Just posting if anyone has tried all the other methods and still unable to find the issue.

A: Maybe you need to disable lazyloading and proxycreation, like this:
  db.LazyLoadingEnabled = false;
  db.ProxyCreationEnabled = false;

Doing this your wcf service should work.

A: I had a worse case with the Webservice.
I returned a simple POCO object with an Enum property.
The numeric value returned in the property was not in the set of Enum values, and because of that, I got that misleading error.
This is not the 1st time I had an issue related to an Enum value in .NET ....
So in short, make sure your response in your WebService doesn't do this:
enum exampleEnum
    {
        A = 1
    }

    class webService
    {
        public object foo() // Suppose WebService method
        {
            // Bad, make sure the Enum value is in the list defined!
            return new { age = 12, A = (exampleEnum)2 };
        }
    }


text:
Q: Why is my output intermittent? I recently got an Altera DE0 nano board and have successfully implemented basic things such as counters and state machines. I'm now trying to implement a 1D Game of Life on the board's built in LEDs, which works correctly, but with a problem.
I want the game state to update at 1Hz (or arbitrarily fast), which this program does, except it also flashes the LEDs at the same frequency, so the LEDs blank for half a second before displaying the next state. I don't see what is wrong with the code but I suspect it's how I'm handling the 1Hz clock edge that's causing this problem.
Here is the current version of code:
----------------------------------
--      Library Declaration     --
----------------------------------
-- Like any other programming language, we should declare libraries

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

----------------------------------
--      Entity Declaration      --
----------------------------------
-- Here we specify all input/output ports

entity blinking_led is
    port(
        clk_50mhz : in std_logic ;
        reset_btn : in std_logic;
        green_leds : out unsigned(7 downto 0) := "11111111"
    );
end entity;

----------------------------------
--  Architecture Declaration    --
----------------------------------
--  here we put the description code of the design

architecture behave of blinking_led is

-- signal declaration

constant CLK_SPD : integer := 50000000;
constant N : integer := 8;

signal LED_init : unsigned(7 downto 0) := "00100100";
signal clk_1hz : std_logic ;
signal scaler : integer range 0 to 25000000 ;
signal out_register : unsigned(7 downto 0) := LED_init;
signal out_register_old : unsigned(7 downto 0) := "00000000";

begin

-- this process is used to scale down the 50mhz frequency
-- In reality, clk_1hz is not periodic but i used it to get 2 clock cycle by second ( 2 rising edge ).
-- 50 mhz means 50 000 000 cycle in one second :
-- by using the scaler , i will have 2 cycle by second so that led will be on 1/2 s and off 1/2 s

    clk_1hz_process : process( clk_50mhz , reset_btn )
    begin
        if (reset_btn = '0') then
            clk_1hz <= '0';
            scaler <= 0;
        elsif(rising_edge(clk_50mhz)) then
            if (scaler < CLK_SPD/2) then
                scaler <= scaler + 1 ;
                clk_1hz <= '0';
            else
                scaler <= 0;
                clk_1hz <= '1';
            end if;
        end if;
    end process clk_1hz_process;

    next_gen : process (clk_1hz,reset_btn, out_register, out_register_old)
    variable neighbours : std_logic_vector(1 downto 0);
    variable rand_temp : std_logic_vector(N-1 downto 0) := (N-1 => '1',others => '0');
    variable temp : std_logic := '0'; --(others => '0');

    begin
        --green_leds <= LED_init;
        if (reset_btn = '0') then
            --green_leds <= LED_init;
            elsif clk_1hz'event and clk_1hz = '1' then

                out_register_old <= out_register;

                --Game rules:
                --Cells are connected on a N-entry long ring, so the first entry has its last as a neighbor and v/v
                --0 neighbors: no action
                --1 neighbor:  cell is born/stays alive
                --2 neighbors: cell dies

                for I in 0 to (N-1) loop
                    if(I = 0) then
                        neighbours := out_register_old(N-1) & out_register_old(I+1);
                    elsif(I > 0 and I < (N-1)) then
                        neighbours := out_register_old(I-1) & out_register_old(I+1);
                    elsif(I = N-1) then
                        neighbours := out_register_old(I-1) & out_register_old(0);
                    end if;

                    case neighbours is
                        when "00" => out_register(I) <= out_register_old(I);
                        when "01" => out_register(I) <= '1';
                        when "10" => out_register(I) <= '1';
                        when "11" => out_register(I) <= '0';
                        when others => report "unreachable" severity failure;
                    end case;
                end loop;

                --PRNG for game reset logic
                temp := rand_temp(N-1) xor rand_temp(N-2);
                rand_temp(N-1 downto 1) := rand_temp(N-2 downto 0);
                rand_temp(0) := temp;
--
--              if(out_register = 0) then
--                  --reset to random vector
--                  --out_register <= unsigned(rand_temp);
--                  out_register <= LED_init;
--              end if;
--
--              if(out_register = out_register_old) then
--                  --stalemate, prepare to reset
--                  out_register <= "00000000";
--              end if;
--
            end if;
            green_leds <= out_register;
    end process next_gen;

    end behave;

I'm rusty with my VHDL so any help is appreciated.

A: As far as I understand the code, the clk_1hz actually has two high pulses within one second (scaler < CLK_SPD/2), hence it should be clk_2hz. And the line
   green_leds <= out_register;

seems to be at a wrong place.

A: Although it may work, you shouldn't use a derived signal as clock, instead use the clk_50mhz through out and use clk_1hz as gating signal. Also you use the reset_btn once asynchronously (in clk_1hz_process) and once synchronosly (in next_gen) which may also lead to some funny effects.
next_gen : process
-- ...
begin
    if(rising_edge(clk_50mhz)) then
        if (reset_btn = '0') or (out_register = 0) then
            -- synchronous reset and check for empty state in one
            out_register <= ...;
        elsif (clk_1hz = '1') then
             -- the main logic here
            out_register <= ...;
        else
            -- nothing happens here
        end if;
    end if;
end process;

-- output assignment
green_leds  <= out_register;

But most importantly, you are trying to use out_register_old in the same cycle where you also assign it (out_register_old <= out_register) , therefore it should be a variable (out_register_old := out_register); or it can just be replaced with out_register itself, since that will keep its old value until the end of the process.


text:
Q: RAILS 4 First argument in form cannot contain nil or be empty Hi I've got a problem with: "First argument in form cannot contain nil or be empty". Since I am Rails newbie its hard for me to use existing answers (still cant find my mistake) Please, take a look:
Showing /home/ubuntu/workspace/app/views/admin/categories/_form.html.haml where line #1 raised:

First argument in form cannot contain nil or be empty
Extracted source (around line #1):

= simple_form_for [:admin, @category], :html => {class: "form-horizontal"} do |f|
  .form-group
    = f.label :name, class: "col-sm-2 control-label"
    .col-sm-10
      = f.input_field :name, label: false, class: "form-control"
  - if @category.id.present?

Render :
= render 'form', :url => admin_categories_path(@category)

Controller:
class Admin::CategoriesController < AdminController

before_action :set_category, :only =>[:show, :edit, :destroy, :update]

  def index
    @categories = Category.all
    respond_to do |format|
        format.html
        format.json {render json: @categories}
    end
  end

  def show
    respond_to do |format|
       format.html
       format.json { render json: @category }
    end
  end

  def new
    @category = Category.new
  end

  def create
    @category = Category.new(category_params)

    respond_to do |format|
        if @category.save
            format.html {redirect_to admin_categories_path, notice: 'Category created'}
        else
            format.html {render action: 'new', alert: 'Error while creating'}
        end
    end
  end

  def edit
  end

  def update

    respond_to do |format|
        if @category.update{post_params}
            format.html {redirect_to admin_post_path, notice: "Category updated"}
        else
            format.html {render action: 'edit', alert: "Error while editing"}
        end
    end

  end

  def destroy
    @category.destroy
    respond_to do |format|
        format.html {redirect_to admin_categories_path, notice "#{Category.title} deleted"}
    end
  end

  protected

  def get_category
    @category = Category.find(params[:id])
  end

  def category_params
    params.require(:category).permit(:title, :body)
  end
end

A: In your before_action, make sure the you have :new in the array. Right now you don't, so @category is not being set when you go to /admin/categories/new

A: OK, I got it.
Got a little new view on it:
So - It rendered categories controller in admin directory - which was empty


text:
Q: Does android-support-v4 jar will be bundled with the android application in which it is referred while compilation? I have created an application on android, referring the "android-support-v4.jar" while compiling my application, so I want to know whether the generated apk will be bundled with the "android-support-v4.jar" or not?, If it gets bundled with the jar file then how can I ensure whether it is bundled or not?

A: Yes it will be bundled.
The classes you use from android-support-v4.jar have to be part of your .apk in the end. If they are not your app will crash because it refers to code that does not exist. If the app works you have successfully included it.
Edit: there is no .jar in the apk. The support classes are directly embedded with your classes into classes.dex.


text:
Q: ¿Cómo sumo con numpy enteros a tuplas dentro de una lista manteniendo en el output la misma estructura original? Tengo la siguiente lista:
a = [[(1, 2), (3, 4)],
    [(1, 3), (2, 4)]

¿Cómo obtengo la suma de (e.g. +4) a cada valor de la tupla?
Resultado esperado:
a = [[(5, 6), (7, 8)],
    [(5, 7), (6, 8)]

He hecho lo siguiente con numpy, pero no sé si es la manera más eficiente:
import numpy as np

a = np.array([(1,2), (3,4)])
b = np.array([(4,4)])

c = a + b

print c

Al obtener c, se obtiene una matriz de datos:
>>>[[5 6]
    [7 8]]

Me gustaría saber cómo se obtiene la misma estructura original (tuplas dentro de una lista) utilizando numpy. También deseo saber cuál es la manera más eficiente para realizar este tipo de operación.

A: Entiendo que tu pregunta se resuelve con lo que se conoce como array estructurado, de esta forma los array tendrán la estructura que quieras darle:
import numpy as np

a = np.array([(1,2), (3,4)])
b = np.array([(4,4)])

c = a + b

Ahora podemos convertir c a un array estructurado tal como lo queremos, por ejemplo una tupla de enteros, usando la función np.core.records.fromarrays que convierte un array plano en uno estructurado y transpose() para rotar el array.
c = np.core.records.fromarrays(c.transpose(),
                                   names='col1, col2',
                                   formats = 'i4, i4')

print(c)

La salida:
[(5, 6) (7, 8)]

Nuestro array c ahora es del tipo estructurado, tiene 2 "registros" y 2 columnas llamadas col1 y col2, y los datos son del tipo int4. Podremos hacer algunas cosas interesantes:
print c[1].col1      # Acceder por nombre a una "celda"
print c["A"]         # Acceder a toda una columna
print c.col1         # También de esta forma
print c[1]           # Acceder a un registro
print c.dtype.fields # Obtener la estructura
print c.dtype.names  # o los nombres de cada columna

Los arrays estructurados, también llamados registros, tienen varias ventajas pero no son muy cómodos para toda la matemática que se puede aplicar a un array común (Por ej, el c = a + b no funciona), lo habitual sería trabajar con array comunes y dejar los estructurados para necesidades específicas o para visualización.

A: Esto también mantendría la estructura interna de tu lista de tuplas, las operaciones map() son frecuentemente usadas por su eficiencia.
import numpy as np

a = np.array([(1,2), (3,4)])
b = np.array([(4,4)])

list(map(tuple,np.add(a,b)))
Out[1]:[(5, 6), (7, 8)]

Otra alternativa sería uso de map, funcion lambda y compresion de listas:
[tuple(map(lambda x:x+4,i)) for i in a]
Out[1]:[(5, 6), (7, 8)]

# granularizando te explico:
# [ i for i in a] recorre cada tupla de la lista
# map aplica a cada elemento de i(el vector) una funcion
# tuple convierte la lista en tupla
# lambda x:x+4  es una funcion que suma 4 a un numero

EDITO:
Para lista de listas, añado una variante que podría ser de utilidad:
a = np.array([[(1, 2), (3, 4), (5, 6), (7, 8)], [(1, 3), (2, 4), (5, 7), (6, 8)]])
b = np.array([(4,4)])

fun = lambda x,y: list(map(tuple,np.add(x,y).tolist()))

[fun(i,b) for i in a]

Out[1]:
[[(5, 6), (7, 8), (9, 10), (11, 12)], [(5, 7), (6, 8), (9, 11), (10, 12)]]


text:
Q: Android: How to sync application data stored in Room database between devices of the same user? I am working on an app that stores user's data locally. I have used the Room database to store the user-created data in an Android device. Now if the user has more then one device then the data should be available on all their (Android) devices without any central database or web services.
Note: for the iOS side I used CloudKit to sync data between iOS devices. Is there any way to do the same for Android devices? Please note I don't want to store the data on any central database or webserver or any central cloud storage. It should be owned by the user only. (i.e. it should be synced via the user's Google account).
Note: I want a native android solution and cross-platform (Android to iOS) sync is not required.
Update: Till now I found some options like Firestore and Realtime database and some AWS services also provide the sync facility but the issue with all these is that they all store the user data at a central cloud location.
So my question still remains the same - Is there a way to sync data between android devices using Google Drive or something similar where we can utilize the user's own cloud storage rather than storing user data in a central database.

A: Edit
There is no native/default/out of the box mechanism to sync data in real time on Android
There are surrogates though.
In context of Android two major options appear:

*

*Sockets with some persistent storage - you may implement backend server with support of sockets and add this support for your android(ios/web/desktop) app. This is the most common and pretty low level mechanism to implement real time sync between devices. Pros : Universal across platforms, industry standard, a lot of info online. Cons: as it is relatively low level thing a lot of code is required, may be quite complex and complicated if there are a lot of sync evens, needs backend, needs separate persistence. Major implementations: Socket.io

*Firebase Realtime Database/ Cloud Firestore - basically wrapper around sockets in conjunction with some database. "Pros": Doesn't require neither backend nor database, free for prototype/low-load apps, pretty straight forward implementation, cross platform, works pretty well. Cons : A lot of boilerplate if you want to go "clean way", you have no control over the inner processes, not very obvious payment calculation on high loads, you link yourself with a third party backend with specific API - well defined architecture required if you will want to move from it somewhere else without complete app remake. comparison: firebase cloud firestore vs realtime database
I will not get into details with the implementation because the official documentation is quite straightforward in this case(unlike with google drive)
Cloud Firestore documentation
Realtime Database documentation
Edit end
Yes. There is a possibility to privately store data using Google Drive. It will be accessible only by your application. Moreover it won't occupy any space in users Google Drive which is pretty handy. Cross platform in this case possible but it needs to be implemented separately for iOs and Android(not supported out of the box by SDK).
So the solution is based on Google Drive API and more specifically on Store application-specific data part of it.
The only visible for the user action regarding this will be google login prompt.
Here is a detailed quickstart for Java
So in order to do it you will need:

*

*Add dependencies;

*Implement google auth like described here and here

*Very important Authenticate users with drive.appdata and drive.file scopes. Also enable Google Drive API in your Google Cloud Console. All this is described here

*Figure out where your Room SQLite file is situated like this: String currentDBPath = context.getDatabasePath("your_database_name.db").getAbsolutePath();

*Upload file to the Google Drive App Folder like it is described here
Basically it will look like this

*

*Enable Google Dive API in Console

*Add dependencies(maybe need to be updated to relevant versions)
implementation 'com.google.android.gms:play-services-auth:17.0.0'// for google sign in

// for drive integration
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.http-client:google-http-client-gson:1.26.0'
implementation('com.google.api-client:google-api-client-android:1.26.0') {
exclude group: 'org.apache.httpcomponents'
}
implementation('com.google.apis:google-api-services-drive:v3-rev136-1.25.0')
{
exclude group: 'org.apache.httpcomponents'
}

*

*In android gradle tag

packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/notice.txt'
exclude 'META-INF/ASL2.0'
}

*

*Manifest

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

*

*Google auth with required scopes

       val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(
                 Scope(Scopes.DRIVE_FILE),
                 Scope(Scopes.DRIVE_APPFOLDER)
            )
            .requestEmail()
            .build()
        googleSingInClient = GoogleSignIn.getClient(this, gso)
        val signInIntent = googleSingInClient.signInIntent
        startActivityForResult(signInIntent, RC_SIGN_IN)
        ... // handle sign in result

*

*Set up google drive client service(where context is)

        val mAccount = GoogleSignIn.getLastSignedInAccount(this)

        val credential =
            GoogleAccountCredential.usingOAuth2(
                applicationContext, Collections.singleton(Scopes.DRIVE_FILE)
            )
        credential.setSelectedAccount(mAccount.getAccount())
        val googleDriveService =
            Drive.Builder(
                AndroidHttp.newCompatibleTransport(),
                GsonFactory(),
                credential
            )
                .setApplicationName("Your app name")
                .build()

*

*Create and send file

        val fileMetadata = File()
        fileMetadata.setName("your_database_name.db")
        fileMetadata.setParents(Collections.singletonList("appDataFolder"))
        val databasePath = context.getDatabasePath("your_database_name.db").absolutePath
        val filePath = File(databasePath)
        val mediaContent = FileContent("application/sqlite", filePath)
        val file = driveService.files().create(fileMetadata, mediaContent)
            .setFields("id")
            .execute()

*

*Search file on other device

        val files = driveService.files().list()
            .setSpaces("appDataFolder")
            .setFields("nextPageToken, files(id, name)")
            .setPageSize(10)
            .execute()
        for (file in files.getFiles()) {
            // get file here
        }

A bit more info you may get here
Hope it helps.

A: You can use Cloud FireStore from Firebase for this
https://firebase.google.com/docs/firestore
This is scalabe and Google Drive API has been deprecated. i personally have used FireStore for one of the app and it works pretty good. Bharat


text:
Q: domain.com is currently unable to handle this request. HTTP ERROR 500 Good day guy, please i am having issues with my laravel5.5 site online. with this error
domain.com is currently unable to handle this request.
HTTP ERROR 500.
I will appreciate any help or suggestion.
Thanks
Kel

A: This comes up if you are using Laravel 5.4+ (default database character set changed to utf8mb4) with mySQL version under MySQL v5.7.7.
Edit your AppServiceProvider.php file and inside the boot method set a default string length:
use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

After that everything should work as normal.
From: https://laravel-news.com/laravel-5-4-key-too-long-error


text:
Q: Why not Fourier Transform spectroscopy in the VIS? There is large amount of scientific and industrial research regarding Fourier Transform spectroscopy (FTS) in the infrared region. However the isn't much about FTS in the visible light spectrum?
Is there an intrinsic physical or technical limitation?
Thanks.


text:
Q: iOS 6 Developer Preview 4 vs official iOS update I have had iOS DP4 installed since it was released on my iPhone. Now that the official update is released, I go in to Settings to check for updates but it says my OS is up to date. Is this expected?

A: Download iOS6: http://osxdaily.com/2012/09/19/ios-6-ipsw-direct-download-links/
Upgrade iTunes to at least 10.7
Connect your iPhone to iTunes
(backup your device)
Shift+click the update button, specify the update file manually (the one that you downloaded in step 1)
Click Go.


text:
Q: Finding point in two parallel lines in 3d? The line $L_1$ that goes through the point $A(4,3,-2)$ and its parallel to the line $(x=1+3t, y=2-4t, z= 3-t)$, if $P(m,n,-5)$ belongs to $L_1$, determine the values for $m$ and $n$
I really don't know what to do help me

A: A line can be specified by two things:
-a direction
-a point that the line passes through
we want to separate the line you've been given into these parts, and then pick out the directional part. the line is given by
$$(1+3t,2-4t,3-t)$$
and we get various $(x,y,z)$ points one the line by substituting various values for $t$. But since vectors add we can separate this into two parts:
$$(1+3t,2-4t,3-t)=(1,2,3)+(3t,-4t,-t)=(1,2,3)+(3,-4,-1)t$$
Now look at what this last description says: to construct the line, start out at $(1,2,3)$ and then go various distances (i.e., $t$ values) in the direction $(3,-4,-1)$. So the line hits $(1,2,3)$ and then travels in the direction $(3,-4,-1)$. This is the part we want. For our line to be parallel to this one, it must also travel in this direction. So our new line is of the form
$$(4,3,-2)+(3,-4,-1)t$$
It has the same direction (i.e. is parallel), but passes through a different starting point. What you want to find out is at what point this line hits a $z$ value of $-5$. The equation for the $z$ coordinates is simply
$$z=-2-t$$
For some $t$ value, $z=-5$. From the equation above we see that this happens when $t=3$. When $t=3$ the equation of the line becomes
$$(4,3,-2)+3*(3,-4,-1)$$
$$(4,3,-2)+(9,-12,-3)$$
$$(13,-9,-5)$$
And so we see that $m=13$ and $n=-9$.
The overall method here is:
-find the equation of the line we're being asked about. Here we used the fact that it was parallel to some other line and passed through the given point, which is all we need to know.
-we now have the line in terms of a parameter $t$, but want information about its coordinates. Use the equations to solve for the appropriate $t$ value.
-find out where the line is at that particular $t$ value and read off the wanted information.


text:
Q: HTML-I'm trying to centre an input slider while keeping the text around it normal I'm a new user on this platform and English is not my main language so excuse my mistakes. I'll start by first attaching the code.
HTML code image
CSS code image

.container_beta
{
  text-align: center;
}
.container_beta input
{
  width:500px;
}

          Easy
          <input type="range" name="difficulty" id="difficulty" min="0" max="5" step="1">
          Hard

What I'm trying to achieve is to center the input while keeping the words to the right and the left as close as possible to the slider. Problem is that with this code , if I change the length of the words , the center is moved , which I don't want. I want to keep the center as it is, while being able to change the words.
So my question for today is what changes do I make to the code so that it behaves as I want ?

A: Using flex makes this easier. Use flex instead of text-center to center main contents and add an additional wrapper around the input and labels to centre its content with flex too.
I added a red background so you can easily see its all centred as expected

.container_beta {
  display: flex;
  justify-content: center;
  background-color: red;
}
.container_inner {
  display: flex;
  justify-content: center;
}
.container_beta input {
  width:500px;
  margin: 0;
}

        Easy <input id="difficulty" max="5" min="0" name="difficulty" step="1" type="range"> Hard

Alternative solution

.container_beta {
  display: flex;
  justify-content: center;
  background-color: red;
  padding: 20px
}
.labels {
  display:flex;
  width: 100%;
  justify-content: space-between;
}
.container_inner {
  display: flex;
  justify-content: center;
}
.container_beta input {
  width:500px;
  margin: 0;
}

      Easier Label
      Hard

        <input id="difficulty" max="5" min="0" name="difficulty" step="1" type="range">


text:
Q: Show specific data based on the role of the user I am making an MVC application and as an Admin I choose what information I should show to the users.
So I have a menu button  to create some categories. Sometimes I want this option to be available to the users sometimes not and based on that I hide it.
When  I dont want the create option to be available, in the view it will be hidden so the users cant see it.But on the bottom of the view  I have a created button which has same function.
How Can I hide this button when my menu button is hidden.
Can I do it in the view somehow.

A: You can give some class to button in view like in menu
 <button class="btnCreateView"></button>

 In Footer
 Give the same button with other class name
 <button class="btnCreateFooter" style="display:none;"></button>

 Now in the view not footer
 Add this jquery
 <script>
  $(document).ready(function(){
     if( $('.btnCreateView').length > 0 )
     {
        $('.btnCreateFooter').show();
     }
  });
 <script>


text:
Q: Command Not working in separate thread in J2me I am creating a bluetooth application.
I created a simple midlet with a exit command and I create a thread for finding the service and discovering the device. While doing so it displays a animated screen on which I added the parent commandListener for exit command. After successful connection both user is represented with greetings(Current screen calls the parent Display method setCurrent for displaying itself). This screen also have CommandListener set to the parent. Now I want to add few more commands. I Implemented the CommandLIstener Interface in this class, added few commands but the commands are not working. I don't know what's wrong. I am giving you Code snippets to fully describe my issue:
package name
Imports here

public class MyMidlet extends MIDlet implements
CommandListener {

public CommandListener theListener;

public Display theDisplay;
public Command exitCommand;

public MyMidlet() {
    // Retrieve the display for this MIDlet
    //Create the initial screen
}

public void startApp() throws MIDletStateChangeException {
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {

    // Determine if the exit command was selected
    if (c == exitCommand) {
        //End application here
        notifyDestroyed();
    } else {
        //Start the new thread here
    }
}
}

Now here is the code for the class which is invoked by the above midlet in a separate thread;
package here;
imports here
public class MyService implements Runnable, CommandListener {

private MyMidlet parent;
private StreamConnection conn;
private OutputStream output;
private InputStream input;

public Command sendCommand;

private TextField messageToSend
Form form;

public BChatService(boolean isServer, BChatMidlet parent) {
   //some stuff here
this.parent = parent;
}

public void run() {
    //function for showing animation here

try {
input = conn.openInputStream();
output = conn.openOutputStream();
} catch (IOException e) {
displayError("IO Error",
"An error occurred while opening " +
"the input and output streams" +
"(IOException: " + e.getMessage() + ")");
try {
conn.close();
} catch (Exception ex) {
}
return;
}
// Create the Form here when service is discoverd and greets the users

    Command sendCommand = new Command("Send", Command.ITEM, 2);
    exitCommand = new Command("Exit", Command.EXIT, 1);
    form.addCommand(exitCommand);
    form.addCommand(sendCommand);

parent.theDisplay.setCurrent(form);

form.setCommandListener(this);

     public void commandAction(Command c, Displayable d) {
        if (c == exitCommand) {
            // End the game
            parent.destroyApp(true);
            parent.notifyDestroyed();
        }
        if(c == sendCommand)  {
          form.append("SOme text here");

        }

    }
}

When I select the Send command, the string doesn't append in form neither exit command works.
What can be the possible cause for it?
I need to implement this functionality... Is there any other way to achieve this?

A: Are you sure the problem is with the command? What i know is that the call openInputStream blocks the entire program until it gets an answer or reachs the timeout, even if you run them on diferent threads (dont know why). Is the connection realy established?


text:
Q: How can you create a reactive & non-reactive Meteor template? I'm struggling with an odd problem. As soon as a document gets updated with a certain attribute, it no longer matches the publish query. Meteor rips it out of the DOM and removes it from the clientside collection.
I need the listings to stay in place so the user can still go back and undo their choice. However I need them to not show up on the next page load.
I can simulate what i'm after if I send the entire collection to the client and then make reactive false if it returns more than 0 results. On refresh only listings that have not been chosen show up. Obviously this is not good for performance.
My publish query basically just filters out the correct type of listing and also pulls
in listings that the user hasn't chose like/dislike. It was incrementing the limit but I couldn't make
it work without losing the previously chosen listings
Meteor.publish('listings', function(type, limit, ulid) {
  var query, options;

  query = {
    type:      type,
    completed: true,
    'public':  true
  };

  options = {
    sort:  {title: 1},
    limit: 1000        // debugging, should be param
  };

  // if user is logged in, get their listing id
  if (ulid) {
    query.likedBy    = { $ne: ulid };
    query.dislikedBy = { $ne: ulid };
  }

  return Listings.find(query, options);
});

// client, simulates the effect I need, but doesn't work if you increase limit

Template.listings.helpers({
  listings: function() {
    var listType, results;

    listType = Session.get('listingType');

    results = Listings.find({type: listType }, {reactive: false}).fetch();

    // prevents race condition where sometimes listings come through anyway
    if (Meteor.user()) {
      var ul = Session.get('userListing')._id;
      results.likedBy =    { $ne: ul };
      results.dislikedBy = { $ne: ul };
    }

    // if results haven't arrived fetch again with reactivity
    if (!results.length) {
      results = Listings.find({ type: listType }).fetch();
    }

    // append a 'no listings avail.' card to the end of results
    // If no results are found, user only sees not found card
    results.push({type: 'empty'});
    return results;
  }
});

For visual, each document is displayed one at a time and the user swipes right
to get new listings and left to go back and see/undo old one.
-----------------------
|                     |
| |-----------------| |
| |                 | |
| |                 | |
| |                 | |
| |    listing #1   | |
| |                 | |
| |                 | |
| |                 | |
| |                 | |
| |                 | |
| |                 | |
| |                 | |
| |                 | |
| |-----------------| |
|                     |
-----------------------

A: This is an interesting problem. You're not really looking to make the template reactive and non-reactive, but find a way to keep certain documents published during a user "session" even though a field has changed which would normally cause the document to be un-published.
One solution that came to mind would be to have a second publication that keeps those documents that have been liked or disliked published if the like or dislike was added during the current session. Two publications can publish from the same Collection and the result is that the Collection on the client is the union of these two publications.
So when a user clicks "like" or "dislike" you would add the _id of that document to a session variable which is an array of documents to keep published. Using a subscription within a deps.autorun you could reactively send this list of _ids to the server and tell it to publish those documents along side your normal publication.
One issue would be the order of the documents in the collection changing as they are taken out of one subscription/publication and put into another. You might need use a sort on the
Listings.find() inside your helper to keep the order from changing. Also depending on latency the list might still "flicker" as the document is removed from one publication and added to another.
Here's what the code might look like:
//Server side publish
Meteor.publish('listingsForSession', function(listingIds) {
check(listingIds, [String]);
  if(listingIds.length > 0){
      return Listings.find({_id: {$in: listingIds}});
  }
});

//Client side subscription
Deps.autorun(function () {
    if(Meteor.userId()){
        Meteor.subscribe("listingsForSession", Session.get("listingIdsToKeep"));
    }
});

//Click handler to keep track of documents that have been liked/disliked
Template.listings.events({
    'click .like, click .dislike': function(event){
        event.preventDefault();
        var listingId = $(event.currentTarget).data("id"); //Or however you get the document _id
        var listingIdsToKeep = Session.get("listingIdsToKeep");
        listingIdsToKeep.push(listingId);
        Session.set('listingIdsToKeep', listingIdsToKeep);
    }
});

Not sure if this is the best solution, but it could work.


text:
Q: Retrieve id after .commit() I am trying to pick up SQLalchemy and run constantly run into the following problem:
is there a way to retrieve some sort of a metadata string from session.commit(), which contains the current primary id SQLalchemy just created ?

A: You can simply get it from the SQLA object following its commit:
my_record= MyTable(id=None, FieldA='testing')
cs.add(myTable)
cs.commit()
print(my_record.id)  # will be the primary id assuming it is autoincrement


text:
Q: Random selection from a sub-list to fill an empty sub-list I have two list of lists,
A = [['a'],[],['l'],[]]
B = [['m','n'],['p'],[],['q','r','s']]

I needed the output to be
c = [['a'],['p'],['l'],['s']]

Whenever there is a empty sublist in A I want to append a random selection from the corresponding sublist from B.
my approach for this is not working
import random

c = [x+random.sample(y,1) for x,y in zip(A,B) if len(x)==0 and len(y)>=1]

A: you can use a conditional expression to decide what element to store in your list:
from random import choice

[a if a else [choice(b)] for a, b in zip(A, B)]

A: You can use the or operator to fall back to a random selection from B using random.choices:
from random import choices
[a or choices(b) for a, b in zip(A, B)]

A: You need to use the if like this:
import random

A = [['a'],[],['l'],[]]
B = [['m','n'],['p'],[],['q','r','s']]

C = [
    a_sub_list if a_sub_list else [random.choice(b_sub_list)] for a_sub_list, b_sub_list in zip(A,B)
]
print(C)
>>> [['a'], ['p'], ['l'], ['q']]


text:
Q: a problem with the proof that if a function has a derivative it is continuous I have seen the proof done so:
$$\lim_{(x-c)\to 0} (f(x)-f(c))$$
$$=\lim_{(x-c)\to 0} [(x-c)\frac{f(x)-f(c)}{x-c}]$$
$$=\lim_{(x-c)\to 0} (x-c)\lim_{(x-c)\to 0} \frac{f(x)-f(c)}{x-c}$$$$=0\cdot f'(x)=0$$
my problem with this is that according to this, we can prove that any function approaches zero when x approaches zero:
$$\lim_{x\to 0}f(x)=$$
$$\lim_{x\to 0}x\frac{f(x)}x$$
then we say that as x approaches zero so to does the value of x and therefore:$$ \lim_{x\to 0}x\frac{f(x)}x=0$$
so: $$\lim_{x\to 0}f(x)=0$$
which is obviously not true for every function.(?!)

A: $$\lim_{x\to 0}f(x)=\lim_{x\to 0} x\cdot \lim_{x\to 0}\frac{f(x)}{x}=0$$
is true only whenever $\frac{f(x)}{x}$ is bounded in a neighborhood of $0$, which is true only if $f(0)=0$.
Method 1
If $f$ is derivable at $a\in\mathbb R$, then $$f(a+h)=f(a)+f'(a)h+o(h),$$ and thus $$\lim_{h\to 0}f(a+h)=f(a),$$
i.e. it's continuous at $a$.
Method 2
\begin{align*}
\left|f(a+h)-f(a)\right|&=\left|\frac{f(a+h)-f(a)}{h}h\right|\\
&\leq \underbrace{\left|\frac{f(a+h)-f(a)}{h}\right|}_{\to f'(a)}|h|\underset{h\to 0}{\longrightarrow }0.
\end{align*}
Therefore, $$\lim_{h\to 0}f(a+h)=f(a).$$

A: It seems you are mixing something up. They were able to make the conclusion that the product goes to zero because the other limit exist which is f'.
Generally if you have a sequence (xn) goes to zero and another sequence (yn). The product sequence will go to zero iff (yn)  is bounded. In this case the other limit exist so it implies boundedness hence the conclusion is valid
Just like you said, we don't have in general that (xn)  goes to zero then it's product with any sequence goes to zero. A simple counter example is (xn) =(1/n) which goes to zero and (yn) =n. You can easily see that (yn) isn't bounded and their product goes to one not zero.
I hope this help

A: Without stating it explicitly, you believe that you can use
$$\lim_{x\to0}x\frac{f(x)}x=\lim_{x\to0}x\cdot\lim_{x\to0}\frac{f(x)}x$$
like is done in the proof.
But you forget an essential ingredient: this holds when the limits exist. In the proof, this is known to be true. But in the general case
$$\lim_{x\to0}\frac{f(x)}x$$ may very well fail to be defined.

The lesson is: always expand the reasoning with enough details, and check the validity conditions.

A: What you are trying to prove may be informally referred to as the 'differentiability implies continuity theorem, which is exactly what it sounds like (i.e if $f$ is differentiable on an open interval $I'$, then $f$ is continuous on the closed interval $I$ including the endpoints).
Your statement that
\begin{align*}
\lim_{x \to 0}f(x) &= \lim_{x \to 0}x \cdot \frac{f(x)}{x} \\
&= 0
\end{align*}
does not hold since you are assuming that the limit $\lim_{x \to 0} \frac{f(x)}{x}$ exists in the first place. An example:
Let $f(x) = x \sin(\frac{1}{x})$. Then
\begin{align*}
\lim_{x \to 0} x \sin\left(\frac{1}{x}\right) = \lim_{x \to 0} x \cdot \lim_{x \to 0} \sin\left(\frac{1}{x}\right)
\end{align*}
for which $\lim_{x \to 0} \sin\left(\frac{1}{x}\right)$ does not exist.


text:
Q: Vue 3 nested transition not working, no error I have this Vue3 Root component, showing a list of groups where each group can have n entries.

<template>

    <transition-group name="groups" tag="div" enter-active-class="bounceInDown" leave-active-class="slideOutRight">
      <li
        v-for="(item, index) in groups"
        class="my-2 px-4 py-2 rounded shadow"
        :key="`root_${item.name}`">

{{ item.name }}

 0">
          <transition-group name="entries" tag="div" enter-active-class="bounceInDown" leave-active-class="slideOutRight">
            <EntryItem v-for="entry in item.entries" :key="`entry_${entry.name}`" :entry="entry" />
          </transition-group>

    </transition-group>

</template>

EntryItem Component renders the entries for each group.
This should also slide out to the right, after deleting an entry.

<template>

      {{ entry.name }}

</template>

If I delete a Group it slides out to the right.
However, deleting an Entry doesn't animate. It just get's removed.
Any idea what's going wrong?

A: There is an ul that just removes the entire  transition-group
so when you delete the last element, you don't see the transition  because
 0">   removes the entire group.
You could just delete the v-if="item.entries.length > 0" part and have it transtion-group render 0 items.
<template>

    <transition-group
      appear
      name="groups"
      tag="div"
      enter-active-class="bounceInDown"
      leave-active-class="slideOutRight"
    >
      <li
        v-for="(item, index) in groups"
        class="my-2 px-4 py-2 rounded shadow"
        :key="`root_${item.name}`"
      >

{{ item.name }}

          <transition-group
            name="entries"
            tag="div"
            enter-active-class="bounceInDown"
            leave-active-class="slideOutRight"
          >
            <EntryItem
              v-for="entry in item.entries"
              :key="`entry_${entry.name}`"
              :entry="entry"
            />
          </transition-group>

    </transition-group>

</template>


text:
Q: how to close the page reload notification after changing permissions to media devices (with js) I am implementing forced reloading of the page after changing the camera permissions , but after that the native google chrome banner appears.
How can it be closed?
my code for forced reloading
navigator.permissions.query({ name: 'camera' }).then((permissionStatus) => {
  console.log(`camera permission status is ${permissionStatus.state}`);
  permissionStatus.onchange = () => {
   document.location.reload();
  };
});

natibe banner google chrome


text:
Q: How do you access underlying PowerShell runspace from C# Cmdlet? I am building some PowerShell cmdlets using the C#/.NET APIs and have a cmdlet that needs access to all the currently imported modules. If I run Get-Module in the terminal I can see 10+ modules loaded, but when my cmdlet runs:
using(var ps = PowerShell.Create(RunspaceMode.Current))
{
    var modules = ps.AddCommand("Get-Module").Invoke<PSModuleInfo[]>();
    /// ...
}

modules here is empty. Its almost like a scoping problem, but I thought RunspaceMode.Current would allow you to access that underlying runspace that was opened with you first open the pwsh shell.
I must be missing something or misunderstanding exactly how runspaces work.

A: You're not supposed to mess around with the invoking runspace directly from inside a cmdlet - it's already busy executing your cmdlet. You also cannot invoke a PSCmdlet directly from another, for the same reason.
Instead, you'll want to use PSCmdlet.InvokeCommand.InvokeScript() to have the runtime execute a script for you (just like if you had a Get-Module statement in a PowerShell function):
[Cmdlet(VerbsCommon.Get, "ModuleProxy")]
public class GetModuleProxyCommand : PSCmdlet
{
    // ...

    protected override void EndProcessing()
    {
        foreach(var module in InvokeCommand.InvokeScript("Get-Module"))
        {
            WriteObject(module);
        }
    }
}

That being said, if what you're doing affects the environment in a way that requires you to execute Remove-Module or clean stuff up in the callers context, you're probably much better off doing your work in a separate runspace anyway :)


text:
Q: How to push docker image from local to azure environment? I have a docker image and I can run the docker image as a container. But I have to bind two folders local to the docker container. And I do it like this:
 docker run -d -p 80:80 --name cntr-apache2

and then I go to: localhost:80. And the app is running.
But now I want to deploy it to the azure environment.
So Logged in in the azure portal: azure login.
and in docker I logged in: docker login webadres.azurecr.io.
and then I did a push: docker push webaddres.azurecr.io/webaddress:latest.
And I got this response:
latest: digest: sha256:7eefd5631cbe8907afb4cb941f579a7e7786ab36f52ba7d3eeadb4524fc5dddd size: 4909

And I made a web app for docker.
But now if I go to the url: https://docker-webaddress.azurewebsites.net
the index is empty. And that is logical. Because I didnt bind the two directories to the docker container in azure.
So my question is:
How now to bind the two direcories with azure docker?
Thank you
And this is my dockerfile:
FROM php:7.3-apache

# Copy virtual host into container
COPY 000-default.conf /etc/apache2/sites-available/000-default.conf

# Enable rewrite mode
RUN a2enmod rewrite

# Install necessary packages
RUN apt-get update && \
    apt-get install \
    libzip-dev \
    wget \
    git \
    unzip \
    -y --no-install-recommends

# Install PHP Extensions
RUN docker-php-ext-install zip pdo_mysql

COPY ./install-composer.sh ./

COPY ./php.ini /usr/local/etc/php/

EXPOSE 80

# Cleanup packages and install composer
RUN apt-get purge -y g++ \
    && apt-get autoremove -y \
    && rm -r /var/lib/apt/lists/* \
    && rm -rf /tmp/* \
    && sh ./install-composer.sh \
    && rm ./install-composer.sh

WORKDIR /var/www

RUN chown -R www-data:www-data /var/www

CMD ["apache2-foreground"]

A: One option is to use App Service persistent storage.
You need to enable the functionality first:
az webapp config appsettings set --resource-group <group-name> --name <app-name> --settings WEBSITES_ENABLE_APP_SERVICE_STORAGE=TRUE

Then create a mapping in a Docker Compose file even if you have a single container to deploy. The {WEBAPP_STORAGE_HOME} environment variable will point to /home in the App Service VM. You can use the Advanced Tools (Kudu) to create the folders and copy the needed files.
Wordpress:
  image: <image name:tag>
  volumes:
  - ${WEBAPP_STORAGE_HOME}/folder1:/etc/apache2/sites-enabled/
  - ${WEBAPP_STORAGE_HOME}/folder2:/var/www/html/ docker_webcrawler2

Documentation
Another option is to mount Azure Storage.
Note that mounts using Blobs are read-only and File Share are read-write.
Start by creating a storage account and a File Share.
Create the mount. I find that it's easier using the Portal. See how in the doc link below.
az storage share-rm create \
--resource-group $resourceGroupName \
--storage-account $storageAccountName \
--name $shareName \
--quota 1024 \
--enabled-protocols SMB \
--output none

Documentation


text:
Q: Validating password with Regular Expression A task I'm working on requires a password to be validated with the following rules:

*

*Must start with a capital letter (A-Z)

*Have eight characters (minimum)

*One of these characters must be a ! ^ or &

*And password must end with a number.

This is the Regular Expression I have so far:
'/^\p{Lu}(?=.*[!^&])\d$.{8,}$/';
// Start with a capital letter: ^\p{Lu}
// At least 8 characters: .{8,}
// One of these characters must be a: (?=.*[!^&])
// Must end with a number: \d$

The expression for eight characters and a number work but the special character and capital letter doesn't work so I'm turning to the experts for this who could push me in the right direction.

A: The pattern already matches an uppercase char at the start, so it should be followed by 7 or more chars to make it at least 8 or more chars.
You can also match a digit at the end, and then you can match 6 or more chars before it.
If the pattern should have 8 characters minimum, you can use:
^\p{Lu}(?=[^!^&]*[!^&]).{6,}\d$

*

*^ Start of string

*\p{Lu} Match any uppercase letter

*(?=[^!^&]*[!^&]) Positive lookahead, assert one of ! ^ &

*.{6,} Match any char 6 or more times

*\d$ Match a digit at the end of the string

Regex demo
Note that the . matches any char, including spaces.


text:
Q: How to put some data into stream from outside? Situation: have a few clients that want to join to server. AkkaStreamServerTCP (actor) manages connections and creates handlers (TcpSession, actor) for each connection. Due GraphStage i can create a really complicated logic for managing data, for example, can add BidiFlow for coding data.
But i didn't understand how I can put bunch of data, that i receive from another actor, into stream?
For example, in akka.io.Tcp we have Events and Commands, such as Write, Read. But what about streams?
Any help would be appreciated!


text:
Q: Ambiguity when writing TStringList to TStream I'm working on a project that sends data between clients using streams. It implements a bunch of stream operators to support this. It worked fine in C++ Builder 2010 but now that I'm moving the project to C++ Builder 10 Seattle I get a weird error.
In one function a TStream is created and data written to it
*pStream >>
        Version >>
        m_iPortNumber >>
        m_iHeartBeatTimeout >>
        m_iMaxToRead >>
        m_pIPAddressFilter >>
        m_iRetries;

m_pIPAddressFilter here is a TStringList and the error is related to that. It reads

[bcc32 Error] E2015 Ambiguity between '>>(System::Classes::TStream
  &,bool &) at Common\Streams.h:28' and '>>(System::Classes::TStream
  &,System::Classes::TStrings *) at Common\Streams.h:42'

The implemented stream operators it's referring to look like this
PACKAGE TStream & operator <<(TStream &Stream, bool b)
{
    Stream.WriteBuffer(&b, sizeof(b));

    return Stream;
}

PACKAGE TStream & operator >>(TStream &Stream, bool &b)
{
    Stream.ReadBuffer(&b, sizeof(b));

    return Stream;
}

PACKAGE TStream & operator <<(TStream &Stream, TStrings *pList)
{
    int Count;
    int i;

    Stream << (Count=pList->Count);
    for (i=0; i<Count; i++)
        Stream << static_cast<WideString> (pList->Strings[i]);

    return Stream;
}

PACKAGE TStream & operator >>(TStream &Stream, TStrings *pList)
{
    AnsiString s;
    int Count;

    pList->Clear();
    Stream >> Count;
    while (Count--)
    {
        Stream >> s;
        pList->Add(s);
    }

    return Stream;
}

How can the compiler be confused by this and feel that it's ambiguous if the version taking a bool or the version taking TStrings should be used. TStrings is even a parent class of TStringList that is what is being written to the stream. As said, this worked fine in C++ Builder 2010.

A: You don't have an >> operator defined specifically for TStringList*, so the compiler has to look for matching candidates to convert a TStringList* pointer to. Any pointer is implicitly convertible to a bool, and it would seem that the compiler considers a compiler-created temporary bool variable is a viable overload candidate, thus an ambiguity since TStringList* is convertible to both TStrings* and bool& (via a temp).
Change your TStrings* operators to take TStrings& parameter instead (which you should do anyway, don't pass object pointers to streaming operators), and then change m_pIPAddressFilter to *m_pIPAddressFilter when invoking the operators.  Then there will not be any ambiguity.
*pStream >>
    ...
    *m_pIPAddressFilter
    ...;

On a separate note, your TStrings operators seem to be inconsistent.  << is streaming out UnicodeString values using an intermediate WideString (Why? And why are you using static_cast?).  Your >> operator is streaming in UnicodeString values using an intermediate AnsiString instead.  Those are different data conversions, so you are likely to corrupt data when non-ASCII characters are present.  You need to use consistent string types for both operators.  You should be streaming the TStrings values as-is using String variables, and then implement String operators to handle the actual streaming using a consistent format, like UTF-8, eg:
PACKAGE TStream & operator <<(TStream &Stream, String s)
{
    UTF8String utf = s;
    int Count = utf.Length();
    Stream << Count;
    Stream.WriteBuffer(utf.c_str(), Count);
    return Stream;
}

PACKAGE TStream & operator >>(TStream &Stream, String &s)
{
    UTF8String utf;
    int Count;
    Stream >> Count;
    s.SetLength(Count);
    Stream.ReadBuffer(utf.c_str(), Count);
    s = utf;
    return Stream;
}

PACKAGE TStream & operator <<(TStream &Stream, TStrings &pList)
{
    int Count = pList.Count;
    Stream << Count;
    for (int i = 0; i < Count; ++i)
        Stream << pList.Strings[i];
    return Stream;
}

PACKAGE TStream & operator >>(TStream &Stream, TStrings &pList)
{
    pList.BeginUpdate();
    try
    {
        pList.Clear();

        String s;
        int Count;

        Stream >> Count;
        while (Count--)
        {
            Stream >> s;
            pList.Add(s);
        }
    }
    __finally {
        pList.EndUpdate();
    }

    return Stream;
}


text:
Q: Android Button setOnClickListener Design I am building an Android Application. I've noticed that I am creating many repetitions of code similar to this in each of my classes:
Button buttonX = (Button)findViewById(R.id.buttonXName);
// Register the onClick listener with the implementation above
buttonX.setOnClickListener(new OnClickListener() {
    public void onClick(View v)
    {
        //DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}
    }
});

I now have fifteen buttons and this is making my code ugly. Does anyone have a class or some examples on how I can turn all these codes into something more efficient, so I can:

*

*Create the button object {Button buttonX (Button)findViewById(R.id.buttonXName);}

*Set the listener {buttonX.setOnClickListener(new OnClickListener()}

*Determine if it was clicked {public void onClick(View v)}

*Then run specific code for each button?

If anyone knows anything, I'd appreciate it.

A: You can use array to handle several button click listener in android like this:
here i am setting button click listener for n buttons by using array as:
Button btn[] = new Button[n];

NOTE: n is a constant positive integer
Code example:
//class androidMultipleButtonActions
package a.b.c.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class androidMultipleButtonActions extends Activity implements OnClickListener{
    Button btn[] = new Button[3];

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn[0] = (Button) findViewById(R.id.Button1);
        btn[1] = (Button) findViewById(R.id.Button2);
        btn[2] = (Button) findViewById(R.id.Button3);
        for(int i=0; i<3; i++){
            btn[i].setOnClickListener(this);
        }
    }

    public void onClick(View v) {
        if(v == findViewById(R.id.Button1)){
            //do here what u wanna do.
        }
        else if(v == findViewById(R.id.Button2)){
            //do here what u wanna do.
        }
        else if(v == findViewById(R.id.Button3)){
            //do here what u wanna do.
        }
    }
}

Note: First write an main.xml file if u dont know how to write please mail to:
wesagnd@yahoo.com

A: If you're targeting 1.6 or later, you can use the android:onClick xml attribute to remove some of the repetitive code. See this blog post by Romain Guy.
<Button
   android:height="wrap_content"
   android:width="wrap_content"
   android:onClick="myClickHandler" />

And in the Java class, use these below lines of code:
class MyActivity extends Activity {
    public void myClickHandler(View target) {
        // Do stuff
    }
}

A: I think you can usually do what you need in a loop, which is much better than many onClick methods if it can be done.
Check out this answer for a demonstration of how to use a loop for a similar problem. How you construct your loop will depend on the needs of your onClick functions and how similar they are to one another. The end result is much less repetitive code that is easier to maintain.

A: Implement OnClickListener() on your Activity...
public class MyActivity extends Activity implements View.OnClickListener {
}

For each button use...
buttonX.setOnClickListener(this);

In your Activity onClick() method test for which button it is...
@Override
public void onClick(View view) {
    if (View.equals(buttonX))
        // Do something
}

Also in onClick you could use view.getId() to get the resource ID and then use that in a switch/case block to identify each button and perform the relevant action.

A: Implement Activity with View.OnClickListener like below.
public class MyActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_options);

        Button button = findViewById(R.id.button);
        Button button2 = findViewById(R.id.button2);

        button.setOnClickListener(this);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        int id = view.getId();

        switch (id) {

            case R.id.button:

                  // Write your code here first button

                break;

             case R.id.button2:

                  // Write your code here for second button

                break;

        }

    }

}

A: public class MyActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_options);

        Button button = findViewById(R.id.button);
        Button button2 = findViewById(R.id.button2);

        button.setOnClickListener(this);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        int id = view.getId();

        switch (id) {

            case R.id.button:

                  // Write your code here first button

                break;

             case R.id.button2:

                  // Write your code here for second button

                break;

        }

    }

}

A: Android lambada solution
public void registerButtons(){
    register(R.id.buttonName1, ()-> {/*Your code goes here*/});
    register(R.id.buttonName2, ()-> {/*Your code goes here*/});
    register(R.id.buttonName3, ()-> {/*Your code goes here*/});
}

private void register(int buttonResourceId, Runnable r){
    findViewById(buttonResourceId).setOnClickListener(v -> r.run());
}

Switch case solution solution
public void registerButtons(){
    register(R.id.buttonName1);
    register(R.id.buttonName2);
    register(R.id.buttonName3);
}

private void register(int buttonResourceId){
    findViewById(buttonResourceId).setOnClickListener(buttonClickListener);
}

private OnClickListener buttonClickListener = new OnClickListener() {

    @Override
    public void onClick(View v){
        switch (v.getId()) {
            case R.id.buttonName1:
                // TODO Auto-generated method stub
                break;
            case R.id.buttonName2:
                // TODO Auto-generated method stub
                break;
            case View.NO_ID:
            default:
                // TODO Auto-generated method stub
                break;
        }
    }
};

A: Since setOnClickListener is defined on View not Button, if you don't need the variable for something else, you could make it a little terser like this:
findViewById(R.id.buttonXName).setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    //DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}
    }
});

A: public class MainActivity extends AppCompatActivity  implements View.OnClickListener{

    Button b1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b1=(Button)findViewById(R.id.button);
        b1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(),"Button is Working",Toast.LENGTH_LONG).show();
    }

}


text:
Q: DateTime to string format in c# I am having some trouble converting a DateTime variable to string.
I want to display the time using a 12-hour clock including the AM/PM
With the following code:
string timeStr = PaymentDate.ToString("hh:mm tt");

I will get "11:39" but the PM/AM is not showing. Any guess?

A: You can use CultureInfo.InvariantCulture to force the AM/PM designator even if your current culture doesn't use it:
PaymentDate.ToString("hh:mm tt", CultureInfo.InvariantCulture);

You can check what your current culture's designator is by (mine is also "" in "de-DE"):
DateTimeFormatInfo.CurrentInfo.AMDesignator  // and .PMDesignator

A: DateTime.ToString(string) method uses your CurrentCulture by default.
I think your DateTimeFormat's AMDesignator is empty string. That's why you can't print it with your CurrentCulture.
As an alternative, you can use InvariantCulture (which has "AM" as a AMDesignator) as a second parameter in  DateTime.ToString overload.
string timeStr = PaymentDate.ToString("hh:mm tt", CultureInfo.InvariantCulture);

Inspector Gadget mode on: Your profile page says you are from Ireland and I assume your CurrentCulture is en-IE. And it's AMDesignator property value is empty string.
CultureInfo.GetCultureInfo("en-IE").DateTimeFormat.AMDesignator;
// Prints empty string


text:
Q: calling fscanf in assembly using nasm I am trying to read 3 values from a file with a format as integer character whitespace integer. For example:
5, 3
In that exact format i.e: no whitespace after the 5, a whitespace after the comma and no whitespace after the 3.
I successfully called fopen to open the file and I used fgetc to access the same file and print its contents. Now I am trying to use fscanf()
I read that to call a C function from assembly you have to push the parameters in reverse order onto the stack, below is my code to do this
    lea eax, [xValue]
    push eax
    lea eax, [comma]
    push eax
    lea eax, [yValue]
    push eax
    mov eax, [format] ;defined as [format db "%d %c %d", 0] in the data section
    push eax
    mov eax, ebx ; move handle to file into eax
    push eax
    call _fscanf

At this point I am assuming the above is equivalent to:
fscanf(fp, "%d %c %d", &yValue, &comma, &xValue);

If it is equivalent to the above, how do I access the values read? I know I'm accessing the file correctly since I was able to print out the individual characters by calling fgetc, but for clarity below is my code to open the file
    mov eax, fileMode
    push eax
    mov eax, fileName
    push eax
    call _fopen
    mov ebx, eax ;store file pointer

Any help/advice is much appreciated. Thanks.
Edited to add…
The answer provided the solution. Posting the code below for anyone else who has this problem.
section .data

    fname db "data.txt",0
    mode db "r",0                                ;;set file mode for reading
    format db "%d%c %d", 0

;;--- end of the data section -----------------------------------------------;;

section .bss
    c resd 1
    y resd 1
    x resd 1
    fp resb 1

section .text
    extern _fopen
    global _main

_main:
    push ebp
    mov ebp,esp

    mov eax, mode
    push eax
    mov eax, fname
    push eax
    call _fopen
    mov [fp] eax ;store file pointer

    lea eax, [y]
    push eax
    lea eax, [c]
    push eax
    lea eax, [x]
    push eax
    lea eax, [format]
    push eax
    mov eax, [fp]
    push eax
    call _fscanf

    ;at this point x, y and c has the data

    mov eax,0
    mov esp,ebp
    pop ebp
    ret

A: I think your scanf() format string is wrong.  Should be "%d%c %d".  Why do you care about the comma anyway?  Why not just use "%d, %d" and ditch the comma variable.
Also, you are trying to load eax with a value from the first bytes of [format], you need to push the pointer to format.
Finally, you don't want the brackets around the memory addresses, unless your assembler is weird you are pushing the wrong addresses.
lea eax, xvalue
push eax
lea eax, yValue
push eax
lea eax, format
push eax
call _fscanf

Now you should have the values you want in xvalue and yvalue


text:
Q: help with grammar! Ever since scientists discovered that the fingerprints of each person on earth was unique, fingerprinting has played an important role in law enforcement.
Is the usage of was correct in this sentence,or should it be is/are?

A: Depending on whether you want this sentence as a printed content or in verbal usage, we can rephrase it as below:
Print use:
Ever since that it was discovered that fingerprints are unique for each person on Planet Earth, fingerprinting has played an important role in law enforcement.
Verbal use:
Fingerprinting has played a crucial role in law enforcement. Especially, ever since that it was discovered that the fingerprints are unique for each person.
Apart from Grammatical correction or going by the rule-book, see if you can rephrase the content according to need and usage.


text:
Q: Reading from a XML file with LINQ I am trying to read from a XML file and save information into a Dictionary.
This is how my XML looks like :
<?xml version="1.0" encoding="utf-8" ?>
<testUI_root>

  <!--Information for the first coded UI Test-->
  <codedUITest name ="CodedUITestMethod1">

    <description name ="Entering username from CSV" key = "1"/>
    <description name ="Entering password from CSV" key = "2"/>
    <description name ="Clicking exit" key ="3"/>

  </codedUITest>

</testUI_root>

So I am trying to read and save to a Dictionary, this is how I have tried :
            //Load xml
            //StringBuilder description = new StringBuilder();
            int key;
            Dictionary<int, string> valDic = new Dictionary<int, string>();
            XDocument xdoc = XDocument.Load("XMLFile1.xml");

            //Run query
            var lv1s = from lv1 in xdoc.Descendants("codedUITest")
                       where lv1.Attribute("name").Value.Contains("CodedUITestMethod1")
                       select new
                       {
                           key = lv1.Descendants("key"),
                           value = lv1.Descendants("name")
                       };
            //loop
            foreach (var lv1 in lv1s)
            {
                foreach (var lv2_k in lv1.key)
                {
                   //it's not entering into this loop
                    foreach (var lv2_v in lv1.value)
                    {
                        // isn't entering here either
                        key = Convert.ToInt32(lv2_k.Attribute("key").ToString());
                        valDic.Add(key, lv2_v.Attribute("name").ToString());
                    }
                }
            }

            foreach (KeyValuePair<int, string> abc in valDic)
            {
                MessageBox.Show("Value: " + abc.ToString());
            }

There is no syntax error, it's a logical one.
So this is how my dictionary is supposed to look like.
/*
1.Entering Username from CSV
2.Entering password from CSV
3.Clicking exit
*/

Saved the xml to output directory. ( from vs )
Tried the code in LinqPad, "query is successful" but no output.
I barely have any experience with Linq, I apologize in advance if this matter/error was a simple one.
Thanks

A: You are looking for ToDictionary method
xdoc.Descendants("codedUITest")
.Where(x => x.Attribute("name").Value.Contains("CodedUITestMethod1"))
.Elements("description")
.ToDictionary(x => (int)x.Attribute("key"), x => (string)x.Attribute("name"));

A: use XML serialization instead.  using xsd.exe that comes with visual studio, you can represent your XML code as the following c# business object:
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class testUI_root {

    private testUI_rootCodedUITest[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("codedUITest", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public testUI_rootCodedUITest[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class testUI_rootCodedUITest {

    private testUI_rootCodedUITestDescription[] descriptionField;

    private string nameField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("description", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public testUI_rootCodedUITestDescription[] description {
        get {
            return this.descriptionField;
        }
        set {
            this.descriptionField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class testUI_rootCodedUITestDescription {

    private string nameField;

    private string keyField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string key {
        get {
            return this.keyField;
        }
        set {
            this.keyField = value;
        }
    }
}

then from there, you can read the XML into a business object:
testUI_root theReturn = null;
System.Xml.Serialization.XmlSerializer s = null;
using (System.IO.FileStream fs = new System.IO.FileStream(thePath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
    if (fs.Length > 0) {
        using (System.Xml.XmlTextReader r = new XmlTextReader(fs)) {
            s = new System.Xml.Serialization.XmlSerializer(typeof(testUI_root));
            theReturn = (testUI_root)s.Deserialize(r);
        }
    }
}
return theReturn;

and there you have a business object representation of your XML!  From there it should be pretty easy to use link to search through the object to find values you want.  This is just a quick mock up of how to do what you want, so i haven't tested it, but hopefully it'll lead you down the right path.


text:
Q: sftp put file in mbox with R I need to use sftp and put .txt files into a MFT server. Is it possible using R?
I have seen examples on how to get a file using sftp using RCurl.
Can someone guide me on this?

A: I could do it using ftpUpload function.
ftpUpload(<file_to_be_uploaded>,
        "sftp://SFTPServer/Destination",
        userpwd = "login:password"
      )


text: Q: Will revoking .p8 key invalidate existing FCM tokens? I have an app in production that's heavily dependent on push notifications, and I'm worrying that revoking the old .p8 key will invalidate the existing FCM tokens. Unfortunately I can't get the old .p8 key from previous developer, so revoking is the only option. I couldn't find the answer in Firebase documentation. Any ideas?