text:
Q: Comparing neighbors of each element of an array with for-loop
I'm a new Python user and I'm finding the combination of Python+Numpy+Matplotlib amazing. I know a little of C and I've been asked to use Python in a work, everything was going well, Numpy has these incredible functions that can do almost everything I need. But I think I stepped on my first stone when I tried to use the "for-loop" with Numpy. I don't know what I'm doing wrong, but I believe my C logic is making me commit some mistakes.
Summarizing: I have one big array "A" (1D) made of 0 and 1 in a way that all 1 are together. I have another array "B" (256x9) with different conditions. What I want is to run trough the A array comparing all 8 neighbors of each A element with each of the first 8 columns of B and when it finds the right choice It will assign the value of column 9 to a third matrix C (Same size as A).
The problem is that I don't know how to work with index in Python, I took a look on the internet and found nothing to help me. I'm trying to access the neighbors of an element using things like (i+1,j), (i-1,j), (i-1,j+1)... I'm getting out of bound errors.
I was looking for something like this:
for i in A:
   for y in B:
     if A[i-1,j+1] == B[1,y]:
        if A[i,j+1] == B[2,y]:
          if A[i+1,j+1] == B[3,y]:
            if A[i-1,j] == B[4,y]:
              if A[i+1,j] == B[5,y]:
                if A[i-1,j-1] == B[6,y]:
                  if A[i,j-1] == B[7,y]:
                     if A[i+1,j-1] == B[8,y]:
                         C[i] = B[9,y],

Please, someone can give me some tips on what I'm doing wrong?
Thanks,
Edit:
To be more clear, let's say that both arrays A and B have the following format. No matter if the array A is 1D or 2D because I can reshape it. Each row of array B represents a neighboring condition and the ninth column is the value that should be assigned to array C if the condition on that row is met.
 A = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0           B = 1 1 1 1 1 1 1 1 0
     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0               1 1 1 1 1 1 1 0 1
     0 0 0 0 0 0 0 0 0 1 0 0 0 0 0               1 1 1 1 1 1 0 1 1
     0 0 0 0 1 1 0 0 1 1 0 0 0 0 0               .
     0 0 0 1 1 1 1 1 1 1 1 1 1 0 0               .
     0 0 1 1 1 1 1 1 1 1 1 1 1 0 0               .
     0 0 1 1 1 1 1 1 1 1 1 1 1 0 0               1 1 0 0 0 0 0 0 1
     0 0 1 1 1 1 1 1 1 1 1 1 1 0 0               1 0 0 0 0 0 0 0 1
     0 0 1 1 1 1 1 1 1 1 1 1 1 0 0               0 0 0 0 0 0 0 0 0
     0 0 0 0 1 1 1 1 1 1 1 1 1 0 0
     0 0 0 1 1 1 1 1 1 1 1 1 1 0 0
     0 0 1 1 1 1 1 1 1 1 1 1 1 0 0
     0 0 0 0 0 0 0 1 1 1 0 0 0 0 0
     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Specifically, I'm trying to find the perimeter of the shape made of 1`s.

A: for inside Python does work in little different way than in C. Running (even in shell) some simple examples could help you a little
collection = ["cat", "dog", "horse"]

for animal in colection:
    print animal

As you can see for assigns to variable animal elements of the list, not their indexes. So in your example variable i is assigned 0 or 1, depending what value given element is list have.
But still sometimes you would like to operate on indexes (as in your case), so lets change a little our example
collection = ["cat", "dog", "horse"]

for i in range(len(colection)):
    print "index: " + i
    print animal[i]

This time we also operate on elements of list, only the list if little bit different.  With function range we create list of integers, from 0 to length of our collection. In other words we create new list with indexes.  With those we can access elements in our original one.
With use of range you should  be able to move forward with your problem.


text:
Q: Generated enemies don't display properly I'm trying to add to my platformer with some PVP mechanics. The first thing I decided to do is to add a generation of enemies. After creating an Enemy class and a function to create a list with enemies' information, I started my test by trying to blit my enemies to the screen, but the problem is that sometimes they blit once, and sometimes they don't blit at all. Sometimes they blit 50% of the time. Why?
Here are all parts of the code that retouch enemies generation and display.
def generate_enemy(player, enemy_group, image_list):
    for i in range(3):
        enemy = Enemy(player, image_list)
        enemy_group.add(enemy)

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, image):
        super().__init__()
        self.image = image
        self.x = x
        self.y = y
        self.width = self.image.get_width()
        self.height = self.image.get_height()
        self.hitbox = pygame.Rect(self.x, self.y, self.width, self.height)
        self.momentum = 0
        self.speed = 7
        self.health = 100
        self.moving_left = False
        self.moving_right = False

class Enemy(pygame.sprite.Sprite):
    def __init__(self, player, image_list):
        super().__init__()
        self.image = image_list[0]
        self.spawn = []
        if random.randint(0, 1) == 1:
            self.x = player.hitbox.x + random.randint(50, 60)
            self.spawn.append(player.hitbox.x + random.randint(50, 60))
        else:
            self.x = player.hitbox.x - random.randint(50, 60)
            self.spawn.append(player.hitbox.x - random.randint(50, 60))
        self.y = player.hitbox.y
        self.width = self.image.get_width()
        self.height = self.image.get_height()
        self.hitbox = pygame.Rect(self.x, self.y, self.width, self.height)
        self.momentum = 0
        self.speed = random.randint(3,6)
        self.health = 50
        self.moving_left = False
        self.moving_right = False

WINDOW_WIDTH, WINDOW_HEIGHT = 1300, 650
FPS = 60

Enemy_animations = [pygame.transform.scale(pygame.image.load(os.path.join("images\\enemy_animation\\enemy_0.png")).convert_alpha(), (64, 47)),
                        pygame.transform.scale(pygame.image.load(os.path.join("images\\enemy_animation\\enemy_1.png")).convert_alpha(), (64, 47)),
                        pygame.transform.scale(pygame.image.load(os.path.join("images\\enemy_animation\\enemy_2.png")).convert_alpha(), (57, 90)),
                        pygame.transform.scale(pygame.image.load(os.path.join("images\\enemy_animation\\enemy_3.png")).convert_alpha(), (72, 51)),
                        pygame.transform.scale(pygame.image.load(os.path.join("images\\enemy_animation\\enemy_4.png")).convert_alpha(), (87, 57))]

Enemy_Group = pygame.sprite.Group()
Slid = Player(0, 0, Slid_Current_Image)

display.blit(Slid_Current_Image, (Slid.hitbox.x - scroll[0], Slid.hitbox.y - scroll[1]))

for enemy in Enemy_Group:
    display.blit(enemy.image, (enemy.hitbox.x, enemy.hitbox.y))

if frame_counter % 300 == 0:
    generate_enemy(Slid, Enemy_Group, Enemy_animations)

surface = pygame.transform.scale(display, (WINDOW_WIDTH, WINDOW_HEIGHT))
window.blit(surface, (0, 0))

redpajama_set_name: RedPajamaStackExchange


text:
Q: haproxy bind command to include cipher in haproxy.cfg file     I am  configuring the haproxy.cfg file for haproxy. i need to add cipher suite in this file. for that i am using bind command. My bind command is as below.

*

*bind 0.0.0.0:443 ssl crt /etc/ssl/certs/private1.pem nosslv3
prefer-server-ciphers ciphers
TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH
With bind command bind *:443 it is working fine. once i add the other arguments its throwing error.
After including this command in haproxy.cfg file and restarting the haproxy service. i am getting the error.

**
[ALERT] 164/074924 (31084) : parsing [/etc/haproxy/haproxy.cfg:80] : 'bind' only supports the 'transparent', 'defer-accept', 'name', 'id', 'mss' and 'interface' options.
        [ALERT] 164/074924 (31084) : Error(s) found in configuration file : /etc/haproxy/haproxy.cfg
        [ALERT] 164/074924 (31084) : Fatal errors found in configuration.
        Errors in configuration file, check with haproxy check.
**
    For resolving this issue i tried to install "libssl-dev" package. but i am not able to install that package also.

    **Please guide me to do this. and i need to know is it neccesary to give the pem file entry in bind, or i can directly include cipher itself like this.
    bind *:8443 ciphers TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH**

    Appending my haproxy.cfg file below.

    **#---------------------------------------------------------------------
    # Example configuration for a possible web application.  See the
    # full configuration options online.
    #
    #   http://haproxy.1wt.eu/download/1.4/doc/configuration.txt
    #
    #---------------------------------------------------------------------

    #---------------------------------------------------------------------
    # Global settings
    #---------------------------------------------------------------------
    global
        # to have these messages end up in /var/log/haproxy.log you will
        # need to:
        #
        # 1) configure syslog to accept network log events.  This is done
        #    by adding the '-r' option to the SYSLOGD_OPTIONS in
        #    /etc/sysconfig/syslog
        #
        # 2) configure local2 events to go to the /var/log/haproxy.log
        #   file. A line like the following can be added to
        #   /etc/sysconfig/syslog
        #
        #    local2.*                       /var/log/haproxy.log
        #
        log         127.0.0.1 local2

        chroot      /var/lib/haproxy
        pidfile     /var/run/haproxy.pid
        maxconn     4000
        user        haproxy
        group       haproxy
        daemon

        # turn on stats unix socket
        stats socket /var/lib/haproxy/stats

    #---------------------------------------------------------------------
    # common defaults that all the 'listen' and 'backend' sections will
    # use if not designated in their block
    #---------------------------------------------------------------------
    defaults
        mode                    http
        log                     global
        option                  httplog
        option                  dontlognull
        option http-server-close
        option forwardfor       except 127.0.0.0/8
        option                  redispatch
        retries                 3
        timeout http-request    10s
        timeout queue           1m
        timeout connect         10s
        timeout client          1m
        timeout server          1m
        timeout http-keep-alive 10s
        timeout check           10s
        maxconn                 3000

    #---------------------------------------------------------------------
    # main frontend which proxys to the backends

    frontend inbound

        mode http

        bind 0.0.0.0:443 ssl crt /etc/ssl/certs/private1.pem nosslv3 prefer-server-ciphers ciphers TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH

    # static backend for serving up images, stylesheets and such
    #---------------------------------------------------------------------
    backend postgresqlcluster1
        mode http
        balance roundrobin
        server  postgres1 192.44.9.101:8080 check**

A: You need to be using 1.5-dev19+ (current is 15.-dev26) to utilize any of the ssl functionality; based on the error and the config excerpt, it looks like you are running 1.4.


text:
Q: template-argument-reduction for return type I have this function:
std::vector<std::pair<std::vector<int>::iterator, std::vector<int>::iterator> >
split(    const std::vector<int>& vector,size_t slices){

...

}

and since it`s quite verbose, and I probably will need to split other kinds of vectors in the future, I want to make it template-based, but this tryout failed:
 template<typename T>
  std::vector<std::pair< std::vector<T>::iterator, std::vector<T>::iterator> >
  split( const std::vector<T>& vector, size_t slices)

    ...

 }

There are two problems in what I can see:
1 - I cant use vector or map or list, only vector.
2 - I don`t understand the template-reduction stuff in a good way yet.
any explanation appreciated.

A:
1 - I cant use vector or map or list, [...]

If you want to handle generically all containers, then you should not use the std::vector template in the first place (and you should not name your function argument vector either):
template<typename C>
std::vector<std::pair<typename C::iterator, typename C::iterator>>
split(C const& cont, size_t slices)
{
    ...
}

Also notice the use of the typename keyword, which is necessary when specifying a qualified, dependent type name.

A: template<typename T>
  std::vector<std::pair< typename T::iterator, typename T::iterator> >
  split( const T& vector, size_t slices)

    ...

 }

You are missing typename, and you can replace the container's type.

A: You're missing typename:
template<typename T>
std::vector<
    std::pair<
        typename std::vector<T>::iterator,
        typename std::vector<T>::iterator
    >
>
split( const std::vector<T>& vector, size_t slices)
{ /* ... */ }

See Where and why do I have to put the "template" and "typename" keywords? for more information about typename.


text:
Q: Double for loop python huge matrix - parallelizing I have to iterate over each cell of a 200x200 array in order to change the value of the cells taking into account the values of the prior-column neighbours.
Basically, what I am trying to do is to randomly place Gaussian-like distribution values on an array, with a certain probability, and I would like to reduce the time of this operation because if I increase my array it takes too long to generate this updated array.
I am doing a directed-percolation-like distribution by "hand" where if a cell (cell2) is touching a full cell (cell1) in the column before, the first (cell2) becomes full affecting its surroundings.
This is my code:
def normaldist(x, y, Nx, Ny, xp, yp, SG=1):
    """2D-mesh (Nx, Ny) with Gaussian-like distribution values."""
    z = np.exp(-0.5*(((x-xp)**2 + (y - yp)**2)/SG**2))
# / (SG*np.sqrt(np.pi*2.)))
    return z

def distributionG(Nx, Ny, xp, yp, SG=1):
    """Fill up the C0(Nx, Ny) array for the specified values and conditions."""
    mask = np.zeros((Nx, Ny))
    for j in range(0, Ny):
        for i in range(0, Nx):
            if(i <= Nx*Ny*normaldist(i, j, Nx, Ny, xp, yp, SG)):
                mask[i, j] = normaldist(i, j, Nx, Ny, xp, yp, SG)
    return mask
Nx = 200  # lattice size X
Ny = 200  # lattice size Y
distributionG2 = np.zeros((Nx, Ny))
for j in range(0, Ny):
    for i in range(1, Nx-1):
        if (j == 0):
            distributionG2 += distributionG(Nx, Ny, i, j, SG=1)
        else:
            rp = random.random()
            if(((distributionG2[i+1, j-1]>0) or (distributionG2[i, j-1]>0)
               or (distributionG2[i-1, j-1]>0)) and rp>0.05):
                if(True):
                    print(i, j, rp)
                distributionG2 += distributionG(Nx, Ny, i, j, SG=1)

Any suggestion will be welcomed.


text:
Q: Can I connect laptop to external screen with lid closed I have a Dell laptop but the screen is 14" which is sometimes small when I work with multiple CAD files etc. I am thinking of buying a 27" 4K TV to connect to as an external screen via the HDMI port on the laptop.
However, I'm wondering if I will have to keep the laptop screen open (which surely works) but is added clutter on my relatively modest sized desk.
Or is there a way to get the laptop to keep running with lid closed and still route the display signal out via the HDMI port.
I can be using a external keyboard as well which is more comfortable.

A: The easiest thing to use is a docking station. Everything plugs in to the dock and the dock has its own power button. One cable connects the dock to the laptop. When you leave, you simply unplug one cable and take your laptop with you. When you return, plug in the dock with the screen closed and push the power button on the dock and the system will turn on using the monitor only.
You can also disable "lid close" settings in power management if you don't want to get a dock. By choosing to not do anything when you close the lid on your laptop, you can close it while the laptop is on so just the external monitor continues to operate. Just remember that closing the lid does not put the laptop in to sleep or hibernate now. So, you'll need to take an extra step before packing the laptop up to travel and put it in to sleep or hibernate. My preferred setting is to set the power switch to hibernate the laptop, and a quick push of the power button will prepare it for travel.


text:
Q: JQuery doesn't work in javascript when partial is returned from controller after post I'm in visual studio making an asp.net project. I've got two controller functions [HttpGet] AccountCreate and [HttpPost] AccountCreate.
The Get returns a PartialView with model AccountCreatePageModel. Everything works here, my javascript and jquery are solid. When I submit the form I check to make sure an input is unique, if it's not I send the partial view back the same way as with the Get. But when it loads and tries to run the javascript, every place that uses $ for jquery breaks, so I guess it doesn't know what jquery is anymore. How can this be? It was all done the same way as the Get.
    [HttpGet]
    public PartialViewResult AccountCreate(Guid functionId, long? parentId)
    {
        AccountCreatePageModel model = new AccountCreatePageModel
        {
            Function = DataFactory.SystemAccess.GetFunction(functionId),
            ParentId = parentId
        };

        if (parentId != default(long?))
        {
            model.Account = DataFactory.PartyAccess.GetAccount((long)parentId);
            model.Organization = DataFactory.PartyAccess.GetOrganizationByAccountId(model.Account.Id);
            model.Person = DataFactory.PartyAccess.InitializePerson();
            model.Account.Id = (long)parentId;
        }
        else
        {
            model.Account = DataFactory.PartyAccess.InitializeAccount();
            model.Organization = DataFactory.PartyAccess.InitializeOrganization();
            model.Person = DataFactory.PartyAccess.InitializePerson();
            model.Address = DataFactory.PartyAccess.InitializeAddress();
        }

        model.PhoneNumber = new PhoneNumberModel();

        return PartialView(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult AccountCreate(AccountCreatePageModel model)
    {

        long id = 0;
        long phoneNumberParentId = 0;
        long accountId = 0;

        if (model.Account.Id > 0)
        {
            accountId = model.Account.Id;
        }
        else
        {
            accountId = DataFactory.PartyAccess.UpsertAccount(model.Account, true).Id;
            model.Function = DataFactory.SystemAccess.GetFunction(model.Function.Id);
            if (accountId == -1)     //Account.AccountId already exists, send message back to user
            {
                return PartialView(model); //this returns my partial back
            }
        }

Here is razor HTML
@using Application.Web.Extensions
@model Application.Web.Models.AccountCreatePageModel

@if ((Model.Organization.Id == 0) && (Model.Person.Id == 0))
{

}
@Html.HiddenFor(model => model.Function.Id)

    @Html.PartialFor(model => Model.Account, "_AccountEdit", new    ViewDataDictionary { { "Readonly", (Model.Account.Id > 0) } })

@Html.PartialFor(model => Model.Organization,   "_OrganizationEdit", new ViewDataDictionary { { "Readonly",   (Model.Organization.Id > 0) } })

@Html.PartialFor(model => Model.Person, "_PersonEdit")

A: I don't have the reputation to join the comment discussion so I'll post here. There are a lot of good answers here:
Javascript Runtime error: $ is undefined
I would also like to say that you are not fully leveraging the model. I would suggest that handling validation that happens in your controller within the model itself. In your controller, you can add:
        if (accountId == -1)
        {
            ModelState.AddModelError("", "Your account id already exists.")
            return PartialView(model); //this returns my partial back
        }

And you can then display that in the view with:
Html.ValidationSummary(true)

Also, I see that you are validating fields locally, this can be problematic for a number of reasons. MVC also gives us the option to add validation within the model. If you add onto your model property:
[Required]
public string MyModelProperty{get; set;}

The model will throw an error when a user tries to submit the form without any data in that field.


text:
Q: Which is a better choice for pointing domain name? An A-record or nameservers? My issues is with choosing between an A-record pointing and changing name servers.
Here's my scenario, I have a domain from GoDaddy and I'm using WordPress powered by Bitnami from the AWS Marketplace to host my WordPress blog. I have an Elastic IP associated for my instance.
Should I just point the Elastic IP through the A-record in GoDaddy or should I configure a hosted zone from Amazon Route 53 to my domain and change the nameservers on GoDaddy?
Which one is a better choice?

A: Since you have the domain at Godaddy, it is wise to configure a hostede zone from amazon route53 to your domain and change the nameservers on GoDaddy to the ones of the hosted zones at route53.
Optionally you can create a CNAME record for the domain with www or anysubdomain.


text:
Q: Why can't I pronounce the ŋ sound? (native English speaker) I was wondering why it is that I'm unable to pronounce this sound. Apparently, the reason why I pronounce the words "seen" and "sing" the exact same way (as well as "long" and "lawn", "dean" and "ding," etc.) is because I have difficulty pronouncing the ŋ at the end of words that finish off with a g. Is it common for native English speakers - I'm from Michigan, by the way - to have this sort of dialect? And why is it that someone would have difficulty saying this sound? Is it fair to judge others who aren't able to pronounce an ŋ properly?

A: This picture shows the nasal cavity http://www.zompist.com/kitcons.gif
And here is a description. The description could be much better, but that's academic style. But picture and description indicate that the air passage through the mouth is closed. The air goes through the nasal cavity and the nose. We influence this by drawing in/back the tongue as I've just found out.
http://www.pronuncian.com/Lessons/Default.aspx?Lesson=19
If you click "play" you hear the sound.
And the text also says that the vocal cords are vibrating, an important feature. The vocal cords are vibrating when you say a long vowel, e.g.
aaaa.
Added:
I had a closer look at the ng-problem, that is how we raise the back of the tongue. The description of pronunciation.com says "the back of the tongue lifts", but how? I doubt that anybody can lift the back of the tongue, the formulation is wrong. But you can bury the tip of your tongue as far down below the lower teeth as possible. This  raises the back of the tongue automatically, if you want to or not. If you do this and try to say /n/ you produce the ng-sound.

A: I have seen this problem before in a friend of mine. She consistently pronounces all /ŋ/ as /n/ in word-final positions. She's from Colorado, so it doesn't appear to be region-specific.
I'm assuming you can pronounce /g/ just fine, since you didn't mention it. If you can pronounce /n/ and /g/ separately, then there's nothing stopping you from pronouncing /ŋ/ correctly (from a technical standpoint). Perhaps the rules your brain is using to pronounce "–ng" are just wrong and are converting it to be pronounced as "–n". It's hard to say with so small a sample size.
Can you pronounce /ŋ/ inside of words? i.e. does "ringer" sound as it ought to, or does it sound like "reener"? If the latter, then your issue goes a bit deeper is all.
I don't think it's terribly detrimental. Honestly, if you're old enough to be posting things here then you probably have made it far enough in life without it affecting you too adversely. With my friend, I really didn't notice until she did it back-to-back once (by saying something like "sing a song", which came out as "seen a sonn" and we all did a double-take), and that was probably a couple months into our friendship.
Like with most phonetics, it's something you can train yourself to do. You've just got to practice combing /n/ and /g/ to make /ŋ/. (I know that might be easier said than done, but it is possible!)

A: It is ordinary for word final velar nasal to become alveolar in an unstressed syllable, as in "licking".  It happens in my speech, and I'm from Ohio originally. The vowel of the ending "-ing" is high and tense.  I consider this to be standard English.  There is a dialectal variant with lax "i" usually spelled with an apostrophe: "finger lickin'".
However, the change you report which even affects "ng" in stressed syllables, as in "sing", is not so usual.  I hadn't noticed that pronunciation.
Often in languages, fewer kinds of consonants are permitted at the ends of words than in other positions.  Many such cases are given by Trubetzkoy in Principles of Phonology.  But I don't know why word final position favors such changes.

A: The only way to get a reliable answer to your question is to consult a well-qualified speech therapist.  Your difficulty could be one related to how you hear the sounds, it could be related to abnormalities in your oral cavity, or it could be a matter of what you learned as a child (and may need specific exercises to unlearn).


text:
Q: How to drill down a report from a RDLC by clicking any where in the row In RDLC reports we can open a  drill down report only by clicking the text in a row.
How to open the drill down report by clicking any where in the Row?

A: Try this Code
 $(document).ready(function () {
        $("tr").click(function (event) {
            var a = event.target.firstChild;
             if (a != null)
                 if (a.localName == "a")
                      a.onclick();
        });
 });


text:
Q: Disable Visual Studio 2008 Conversion Wizard for VSTO Is it possible to deactivate the VS 2008 conversion wizard. I want to open a solution that contains VSTO project for Office 2003 and I don't want them to be converted when I open the solution on a PC with Office 2007.

A: Check out the VS2008 options found here...
Tools -> Options -> Office Tools -> Project Upgrade
Try clearing the option Always upgrade to the installed version of Office.
Is that what you are looking for?


text:
Q: Monitor ubuntu system metrics through grafana + telegraf I have a system configured with Telegraf + InfluxDB + Grafana on one machine.
Now I need to collect server metrics for Ubuntu servers which is deployed in the cloud and need to plot in Grafana.
My question here is :

*

*Can I collect the metrics through Telegraf itself ? if yes then do I need to install Telegraf in all the cloud servers to pull the metrics ?

*Is there any other way to pull the metrics from AWS cloud servers and store it in the central Influxdb database ?

*Is it possible to perform it through any other plugins available in Jmeter itself ?
Thanks In Advance for the valuable comments.

A: *

*Yes you can and yes you need to install the telegraf agent on each server you want to monitor

*There are other ways of collecting server performance data:

*

*JMeter PerfMon Plugin, in this case you will need to install PerfMon Server Agent onto all servers

*SSHMon Samples Collector, you will not need to install any software onto servers, however you will need to have SSH connectivity with all servers you want to monitor

*I'm not aware of any existing plugins, however you can come up with your own implementation of the AbstractBackendListenerClient which will be sending server-side performance metrics to InfluxDB


text:
Q: Shell scripts with Scala 2.12.12 broken? I have some shell scripts running with Scala 2.12.11. After updating to Scala 2.12.12 they don't do anymore.
Example:
#!/bin/bash
echo "in Bash"
exec scala "$0" "$@"
!#
object Example { def main(args: Array[String]) = println("in Scala") }

Result with Scala 2.12.11:
in Bash
in Scala

Result with Scala 2.12.12:
in Bash
fscbad option: '-Ytrack-dependencies'
  fsc -help  gives more information
error: IO error while decoding /home/marcus/-Ytrack-dependencies with UTF-8: /home/marcus/-Ytrack-dependencies (No such file or directory)
Please try specifying another one using the -encoding option
error: IO error while decoding /home/marcus/-Xscript with UTF-8: /home/marcus/-Xscript (No such file or directory)
Please try specifying another one using the -encoding option
error: IO error while decoding /home/marcus/Main with UTF-8: /home/marcus/Main (No such file or directory)
Please try specifying another one using the -encoding option
three errors found

Any idea?

A: Uninstalling Scala does not stop the compiler daemon. Thus after the update the running daemon does not match the Scala version anymore. Stopping the old daemon (once) with fsc -shutdown solves the problem.
Alternatively, you can avoid the daemon altogether by adding -nocompdaemon to the scala call. Starting with Scala 2.13.0 this is done by default (according to issue 12102).
#!/bin/bash
echo "in Bash"
exec scala -nocompdaemon "$0" "$@"
!#
object Example { def main(args: Array[String]) = println("in Scala") }


text:
Q: Get an email's SentOn date given its subject and a specified date range to copy into Excel I need to search a number of email titles given in a spreadsheet between a range specified in VBA. Then, I need to paste the SentOn time into Excel using a two way lookup.
I am able to do this for the current date only, as when I input a date before the current date, the two way lookup pastes the SentOn date for today's email. This makes me think that I have messed up searching Outlook. Here is the (truncated) code I am using:
Dim filterStr As String
filterStr = "urn:schemas:httpmail:subject = '" & EmailName & "' AND urn:schemas:httpmail:date >= '" & TDateUTC & "' AND urn:schemas:httpmail:date <= '" & TDateUTCEOD & "' "

For Each OutputType In ThisWorkbook.Worksheets("Static Data").Range("F:F")
    If OutputType.value = "Email" Then
        ProcessName = OutputType.Offset(0, -5).value
        EmailName = OutputType.Offset(0, 2).value

    On Error Resume Next
        If Not (TargetInbox.Items.AdvancedSearch(TargetInbox, filterStr, False, "criteria") Is Nothing) Then

        SLA_Completion_Tracker_FileName.Activate
        MatchFormula1 = WorksheetFunction.Match(CLng(CDate(TDate)), ActiveSheet.Range("1:1"), 0)
        MatchFormula2 = WorksheetFunction.Match(ProcessName, ActiveSheet.Range("A:A"), 0)

        EmailTime = TargetInbox.Items.Item(EmailName).SentOn
        If Not EmailTime >= TDate And EmailTime <= TDateEOD Then EmailTime = ""

        SLA_Completion_Tracker_FileName.Activate
        Set IndexFormula = WorksheetFunction.Index(ActiveSheet.Range("A1:FA60"), MatchFormula2, MatchFormula1)

        IndexFormula.value = Format(EmailTime, "ddddd ttttt")

End If

This is currently working for today's date.
However, when I set it up to search for a previous date, I replace this:
EmailTime = TargetInbox.Items.Item(EmailName).SentOn
If Not EmailTime >= TDate And EmailTime <= TDateEOD Then EmailTime = ""

With this:
EmailTime = TargetInbox.Items.AdvancedSearch(TargetInbox, filterStr, False, "criteria").Item(EmailName).SentOn

Nothing shows up. I realize this is because I am not using the AdvancedSearch function properly, so can someone help me out here? How do I use it properly for this task?
Thanks
EDIT: I have been trying Find as well, using this code:
EmailName = OutputType.Offset(0, 2).value
Dim sFilter As String
sFilter = "[Subject] = """ & EmailName & """ AND [SentOn] >= '" & Format(TDate, "ddddd h:nn AMPM") & "' AND [SentOn] <= '" & Format(TDateEOD, "ddddd h:nn AMPM") & "'"
FoundMail = TargetInbox.Items.Find(sFilter)
FoundTime = FoundMail.SentOn

But this hasn't worked either.

A: AdvancedSearch is asynchronous and you need to wait for it to finish.
Why not just use MAPIFolder.Items.Find/FindNext or Items.Restrict?

A: OP here, figured out my problem.
Here's what I ended up doing, in case anyone stumbles upon this:
Dim myolApp As Outlook.Application
Dim objNS As Outlook.Namespace
Dim objFolder As Outlook.MAPIFolder
Dim ProcessName As String
Dim EmailName As String

Set myolApp = CreateObject("Outlook.Application")
Set objNS = myolApp.GetNamespace("MAPI")
Set objFolder = objNS.Folders('your value here)
Set TargetInbox = objFolder.Folders('your value here)

Dim oItms As Outlook.Items
Dim oItm As Outlook.MailItem
Set oItms = TargetInbox.Items
Dim sFilter As String
Dim EmailTime As String

    sFilter = "[Subject] = """ & EmailName & """ AND [SentOn] >= '" & Format(TDate, "ddddd h:nn AMPM") & "' AND [SentOn] <= '" & Format(TDateEOD, "ddddd h:nn AMPM") & "'"
    Set oItm = oItms.Find(sFilter)
    EmailTime = oItm.SentOn

Turned out to be pretty simple in the end.


text:
Q: Intellij IDEA Inspection background color not appearing for certain warnings Currently experiencing an issue where the background color I have set for warnings only shows up on certain warnings.
Screenshot
The inspections/warnings for line 19 show the background color correctly in addition to the orange line on the right gutter.
However, the inspection for Unused parameter only displays in the right gutter, but does not highlight.  This doesn't seem to make sense as both are warnings and don't seem to be controlled by separate styles in Color & Fonts > General > Errors and Warnings.
Any ideas?  I tried loading my PyCharm profile (where this works as expected) but to no avail.
Version: IntelliJ IDEA 2016.1.3 Build #IU-145.1617, built on June 3, 2016 JRE: 1.8.0_76-release-b198 amd64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

A: In IJ 14 (at least) Unused symbols is controlled by a separate style under Color & Fonts > General:


text:
Q: How to pass value to bootstrap modal? I'm using Bootstrap to display my modal in my webpage. My data is stored in database. I used ng-repeat to get my array data from database. I want to pass my room.room_name into modal. How can I do that?
HTML:

    {{room.room_id}}
    {{room.room_name}}
    {{room.max_pax}}
    {{room.no_booked}}

        <button class="btn btn-warning" data-toggle="modal" data-target="#editRoom"></button>
        <button class="btn btn-danger" data-ng-click="delRoom(room.room_id)"></button>

My Modal:
I want to pass room_room.name value and insert into input text value.
I tried to use ng-value but failed.

                    <button type="button" class="close" data-dismiss="modal">×</button>

Edit Library Discussion Room

                    <form>
                        Room Name:
                        <input type="text" name="editName" data-ng-model="room.name" id="editName" data-ng-value="{{room.room_name}}" />

                        Maximum Person:
                        <input type="text" name="editMaxPax" data-ng-model="room.maxPax" id="editMaxPax" value="room.max_pax" />
                        <button type="submit" class="btn btn-default" data-ng-click="editRoom(room)">Edit</button>
                    </form>

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

AngularJS (Controller):
My get the value from database and store it into array named "data".
var app = angular.module("myApp", ['ngRoute']);

app.config(['$routeProvider', function ($routeProvider) {
"use strict";
$routeProvider
        .when("/", {
        templateUrl: "facilities.html"
    });

}]);

app.controller("myCtrl", function ($scope, $http) {
"use strict";
$scope.state = "";

$scope.addRoom = function (room) {
    $http.post("add_library_room.php", {'room_name': room.name, 'max_pax': room.maxPax})
        .then(function () {
            $scope.msg = "Room is inserted into database.";
        });
};

$scope.displayRoom = function () {
    $http.get("view_library_room.php")
        .then(function (response) {
            var data = response.data;
            $scope.data = data;
            console.log(data);
        });
};

$scope.delRoom = function (roomID) {
    $http.post("del_library_room.php", {'room_id': roomID})
        .then(function () {
            $scope.msg = "Room is deleted successfully.";
        });
};

$scope.footer = function (page) {
    if (page === "login") {
        $scope.state = page;
    } else {
        $scope.state = "";
    }
    return $scope.state;
};

});


text:
Q: Is using .after() an inefficient method compare to just put markup on the page? Let's say I have this markup that I'd like to use to for a dialog.

Alert message cannot be empty.

I have 2 solutions:

*

*add it somewhere, let's say at the end of the page

*use .after() to append it to an existing element

Then apply $('#dialog').dialog() to that element.
I'm hearing that's modifying the DOM is a very bad practice because the DOM will be modified and needs to be re-created. that's really inefficient.
Is that true? I'm not an expert in JavaScript. I didn't know that little thing would slow the whole execution down.
Thanks for helping

A: Adding markup by doing something like:
obj.innerHTML += newHTML;

is indeed bad as it recreates all the objects in the obj hierarchy and trashes all event handlers in that hierarchy.
But, programmatically adding DOM elements with functions like .after() is perfectly fine as it just adds the new elements and doesn't disturb any existing objects.
One other aspect that takes time in manipulating the DOM is doing layout.  When you add new objects to the DOM they have to be factored into the layout of the page and then it all has to be repainted.  If once is doing many sequential DOM operations, this can significantly slow down your operation.  But, in both of your cases, you're going to be making the dialog visible once (presuming it was display: none if already in the HTML of your page) so it's going to be laid out and displayed much the same either way.
In your two cases, either method would be fine - there would be no noticeable performance difference.  The advantage of having all the markup in the original page is that you can manage it all in once place more easily and won't have content mixed in with your javascript.  If you have hundreds of differently possible dialogs, then you might not want them all to be in the main page.


text:
Q: max of Corresponding Elements in a numpy.ndarray This seems like it would be a really simple problem, but i haven't been able to find a solution so far.
I have two numpy.ndarrays (say A, B) and would like to create a third one (say C) of the same shape and dimensionality, such that each element in C is the maximum value of the corresponding elements in A and B.
What I've tried so far doesn't work, though to be honest, I haven't tried much (but I'm out of ideas)
In [173]: A
Out[173]:
array([[  2.12752806e-314,   2.12752806e-314],
       [  2.16171674e-314,   6.32300944e+233]])

In [174]: B
Out[174]:
array([[  2.13899304e-314,   2.13899304e-314],
       [  2.16168421e-314,   2.78136354e-309]])

In [175]: max(A, B)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-175-c06ce068ec08> in <module>()
----> 1 max(A, B)

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

A: you're looking for np.maximum(A,B)

A: How about np.where:
In [29]: where(A>B, A, B)
Out[29]:
array([[  2.13899304e-314,   2.13899304e-314],
       [  2.16171674e-314,   6.32300944e+233]])


text:
Q: Java.lang.UnsupportedOperationException: null При попытке обновить пользователя возникло исключение unsupported operation и null, при выводе пользователя в методе, где сохраняется пользователь все нормально, пользователь не налл, все выводится корректно. Проблема при обновлении именно с ролью, когда я обновляю юзернейм все нормально.
метод из сервиса
@Override
    public ChatRoom saveChatRoom(ChatRoomDto chatRoomDto, String authorizationHeader)
            throws EntityExistException, EntityNotFoundException, JwtTokenNotFoundException {

        if(chatRoomRepository.findByChatRoomName(chatRoomDto.getChatRoomName()).isPresent())
            throw new EntityExistException(chatRoomDto.getChatRoomName());

        ChatRoomUser chatRoomUser = tokenService.findChatRoomUserByToken(authorizationHeader);

        User user = userService.findUserByUsername(chatRoomUser.getUsername());

        user.setRoles(Collections.singletonList(roleService.findRoleByName(CREATOR.name())));

        userService.saveUser(user);

        return chatRoomRepository.save(
                ChatRoom.builder()
                .chatRoomName(chatRoomDto.getChatRoomName())
                .connectedUsers(Collections.singletonList(chatRoomUser))
                .build()
        );
    }

user service
@Override
    public User saveUser(User user) {
        return userRepository.save(Objects.requireNonNull(user));
    }

ошибка в строчке с return userRepository.save(...)
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.UnsupportedOperationException] with root cause

java.lang.UnsupportedOperationException: null


text:
Q: BLOB to String, SQL Server I have a text string stored as a BLOB data type in a database. I want to extract it by an SQL select query, but I have problems converting/casting from BLOB to readable text.
I've tried e.g.
select convert(nvarchar(40),convert(varbinary(40),BLOBTextToExtract))
from [NavisionSQL$Customer]

I guess I need something similar, but I can't figure out exactly what I need to do the conversion. Can somebody please give me some directions?
Regards

A: Problem was apparently not the SQL server, but the NAV system that updates the field. There is a compression property that can be used on BLOB fields in NAV, that is not a part of SQL Server. So the custom compression made the data unreadable, though the conversion worked.
The solution was to turn off compression through the Object Designer, Table Designer, Properties for the field (Shift+F4 on the field row).
After that the extraction of data can be made with e.g.:
select convert(varchar(max), cast(BLOBFIELD as binary))
from Table
Thanks for all answers that were correct in many ways!

A: It depends on how the data was initially put into the column. Try either of these as one should work:
SELECT CONVERT(NVarChar(40), BLOBTextToExtract)
FROM [NavisionSQL$Customer];

Or if it was just varchar...
SELECT CONVERT(VarChar(40), BLOBTextToExtract)
FROM [NavisionSQL$Customer];

I used this script to verify and test on SQL Server 2K8 R2:
DECLARE @blob VarBinary(MAX) = CONVERT(VarBinary(MAX), 'test');

-- show the binary representation
SELECT @blob;

-- this doesn't work
SELECT CONVERT(NVarChar(100), @blob);

-- but this does
SELECT CONVERT(VarChar(100), @blob);

A: The accepted answer works for me only for the first 30 characters.
This works for me:
select convert(varchar(max), convert(varbinary(max),myBlobColumn)) FROM table_name

A: Can you try this:
select convert(nvarchar(max),convert(varbinary(max),blob_column)) from table_name

A: Found this...
bcp "SELECT top 1 BlobText FROM TableName" queryout "C:\DesinationFolder\FileName.txt" -T -c'
If you need to know about different options of bcp flags...
http://msdn.microsoft.com/en-us/library/ms162802.aspx

A: CREATE OR REPLACE FUNCTION HASTANE.getXXXXX(p_rowid in rowid) return VARCHAR2
  as
          l_data long;
  begin
         select XXXXXX into l_data from XXXXX where rowid = p_rowid;
         return substr( l_data, 1, 4000);
  end getlabrapor1;


text:
Q: Higher recursion theory and reverse mathematics: What is to $\Pi^1_1-CA_0$ as $RCA_0$ is to $ACA_0$? There is an extremely rich and well-understood analogy between "recursively enumerable" and "$\Pi^1_1$" - indeed, this is the starting point of metarecursion theory, and $\alpha$-recursion theory in general (see Sacks' wonderful book http://projecteuclid.org/DPubS?verb=Display&version=1.0&service=UI&handle=euclid.pl/1235422632&page=record).
I'm interested in whether there is a straightforward reverse mathematical analogy to be made here, as well. Specifically, we usually think of $RCA_0$ and $ACA_0$ as "recursive comprehension" and "recursively enumerable comprehension," respectively; I'm wondering if there is a theory $T$ such that we can - in a similar way - think of $T$ as "metarecursive comprehension" and $\Pi^1_1-CA_0$ as "metarecursively enumerable comprehension."
A natural candidate for that theory might be $\Delta^1_1-CA_0$, but that's not quite right: in the metarecursive context, $\Delta^1_1$ corresponds to finite (since intuitively everything is relative to Kleene's $\mathcal{O}$). I've been thinking that the right $T$ here is $ATR_0$, but I don't really have any serious reason to back that up.
My instinct is that this is not really the right question - metarecursion theory doesn't live on $\omega$, it lives on $\omega_1^{CK}$, so the right thing to do is formulate a version of reverse math on $\omega_1^{CK}$ (in fact, Richard Shore http://www.math.cornell.edu/~shore/papers/pdf/RMComp7.pdf has already done this for cardinals, and I don't see anything preventing his work extending to arbitrary admissible ordinals - although his theorems might not, of course, since they may require more admissiblity than $\Sigma_1$). But I'm still holding out hope that there's something neat that can happen already on $\omega$.
(I've tagged "descriptive-set-theory" because of the deep connections between higher recursion theory and descriptive set theory, but if anyone feels that that's too much of a reach here, feel free to untag.)

A: I am getting the feeling there is some slight miss-match of terminology, or perhaps application of terminology is a better way of putting it? It is true that the (lightface) $\Pi^1_1-CA_0$ sets of integers correspond to the meta-r.e. sets of integers, but as you say, the old meta-recursion theory lies on $\omega_1^{ck}$. So it should really be about sets of ordinals rather than integers.  However then one is really talking about $\Delta_1$-recursions over $(L_{\omega_1^{ck}},\in)$, and then the $\omega^{ck}_1$-r.e. sets are those $\Sigma_1(L_{\omega_1^{ck}},\in)$. Using a theorem of Kleene the restriction of the latter to sets of integers are indeed precisely the (lightface) $\Pi^1_1-CA_0$ sets of integers.
I think the link with descriptive set theory comes through Kleene Recursion - not much studied these days but arises as a higher type recursion theory on $\omega$ and $\omega^\omega$. Restricting it to integers, yields that the Kleene-r.e. sets are the $\Pi^1_1$ sets of integers (so again those defined in a $\Sigma_1(L_{\omega_1^{ck}},\in)$ way). Kleene recursive sets of integers correspond to those in $HYP$. Including the reals, and working at the higher type, then Kleene rec. sets corresponds to Borel and Kleene-r.e. to (boldface) co-analytic.
The `axioms', $T$, for Kleene recursion are his rules for an equational calculus for recursion on integers and reals, extending his equational calculus for the ordinary general recursive functions. (See, I think P. Hinman, Recursion Theoretic Hierarchies, Springer Omega Series, 1978, but also the chapter about higher type recursions in general by Dag Normann in Turing's Legacy, Ed. R. Downey, ASL Series in Math.Logic,vol 42, May 2104); in my chapter Transfinite Machine Models, in the same volume some particular facts about Kleene Recursion are summarized.)
This does not say anything about "reverse mathematics" in this context, and indeed I don't see anything resembling it here. I don't know whether Richard Shore's set-up can be made to work here.


text:
Q: python: How do i download a file from Google drive using api I would like to download a file in google drive to my system,using google drive api. How can i implement this ?
according to example given at https://developers.google.com/drive/v2/reference/files/get#examples
def print_file(service, file_id):

 """Print a file's metadata.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to print metadata for.
  """
  try:
    file = service.files().get(fileId=file_id).execute()

    print 'Title: %s' % file['title']
    print 'MIME type: %s' % file['mimeType']
  except errors.HttpError, error:
    print 'An error occurred: %s' % error

def download_file(service, drive_file):
  """Download a file's content.

  Args:
    service: Drive API service instance.
    drive_file: Drive File instance.

  Returns:
    File's content if successful, None otherwise.
  """
  download_url = drive_file.get('downloadUrl')
  if download_url:
    resp, content = service._http.request(download_url)
    if resp.status == 200:
      print 'Status: %s' % resp
      return content
    else:
      print 'An error occurred: %s' % resp

I am able to find the file , But how can i download it locally to my machine ?

A: just write the content variable to a file instead of returning the content
fo = open("foo.jpg", "wb")
fo.write(content)
fo.close()

A: I think you should probably check out this:
http://pythonhosted.org/PyDrive/
The code seems like it is easier
# Initialize GoogleDriveFile instance with file id.
file6 = drive.CreateFile({'id': file5['id']})
file6.GetContentFile('catlove.png') # Download file as 'catlove.png'.

# Initialize GoogleDriveFile instance with file id.
file7 = drive.CreateFile({'id': file4['id']})
content = file7.GetContentString()
# content: '{"firstname": "Claudio", "lastname": "Afshar"}'


text:
Q: Getting Error: TCP Provider: Error code 0x2746 while trying to install and use pyodbc on Ubuntu 20.04 for the first time I wanted to remotely connect to a sql-server database on my network in python. So I the installed pyodbc following the steps given on this page. It instructs to first "Install the Microsoft ODBC Drivers for SQL-Server" by following these instructions.
Having completed these steps (and only these steps) I identified the driver path and tried running this code in python.
import pyodbc as podbc
conn = podbc.connect("Driver=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.8.so.1.1;"
                 "Server=192.XXX.XXX.XXX;"
                 "Database=db_name;"
                 "uid=xxxx;"
                 "pwd=xxxx;")

On execution I am getting the error:
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746 (10054) (SQLDriverConnect)')

It would be helpful if you could tell me why am I getting this error and if I'm missing any steps in the installation process. Also, I am able to access the sql-server remotely through a windows machine, but whenever I'm trying to do it via an ubuntu machine I'm getting this error.


text:
Q: Two factor authentication for SSH I am looking for a 2 factor authentication system that supports;

*

*Public Keys

*SFTP logins

Right now the options I know,
Authy: Allows you to use it with Public Key authentication but it fails SFTP logins for some reason. It says that it supports SCP etc. but SFTP connection try with Filezilla fails.
Google 2 Factor: Doesn't allow Public Key auth, probably has some bypass method for SFTP.
Duosecurity : Haven't tried yet.
I am on Debian system

A: I've been playing a little with Google Authenticator. I don't have any issues using SFTP with two factor or public key on Linux command line. I have seen some strange behavior with GUI clients in Windows. I prompt for the OTP and password separately which requires Challenge Response to be enabled in sshd. You also need to watch out for SELinux on RHEL flavored Linuxes since the default location of the config file is not accessible by sshd. You can either modify the policy or move the file to .ssh for each user. If you want a more centralized solution you can consider RADIUS. That has the benefit of having fewer OTPs to deal with in your client. You could copy one key everywhere but that starts to defeats the idea of OTP without a central authority to keep track of key use.

A: So you want to do OTP authentication and SSH pub key auth?
Your bullet points are a bit misleading, because ssh pub key is an authentication mechanism and sftp is an application (or protocol).
You might also take a look at privacyIDEA, which is an OTP authentication backend for OTP tokens like the google authenticator, the yubikey and many other OTP devices.
I also started an implementation on "SSH token", to support ssh pub keys, but it is under development at the moment (see github). Do you have any input?
You would connect your SFTP via RADIUS protocol and could then use many different token types at the same time.


text:
Q: error: cannot find symbol method setAdListener() & () error: cannot find symbol method setAdListener()
error: cannot find symbol method setAdListener()
com.facebook.ads.AdView adView_banner = new com.facebook.ads.AdView(this, getString(R.string.facebook_banner_id), AdSize.BANNER_HEIGHT_50);
    // Find the Ad Container
    LinearLayout adContainer = (LinearLayout) findViewById(R.id.adView);

    // Add the ad view to your activity layout
    adContainer.addView(adView_banner);

    adView_banner.setAdListener(new com.facebook.ads.AdListener() {
        @Override
        public void onError(Ad ad, AdError adError) {
            Log.i("ERR",""+adError.getErrorMessage());
        }

A: Facebook has updated their current SDK, for your case change your code to
reference
https://developers.facebook.com/docs/audience-network/guides/ad-formats/banner/android
AdListener adListener = new AdListener() {
            @Override
            public void onError(Ad ad, AdError adError) {
                // Ad error callback
                Toast.makeText(
                        MainActivity.this,
                        "Error: " + adError.getErrorMessage(),
                        Toast.LENGTH_LONG)
                        .show();
            }

            @Override
            public void onAdLoaded(Ad ad) {
                // Ad loaded callback
            }

            @Override
            public void onAdClicked(Ad ad) {
                // Ad clicked callback
            }

            @Override
            public void onLoggingImpression(Ad ad) {
                // Ad impression logged callback
            }
        };

        // Request an ad
        adView.loadAd(adView.buildLoadAdConfig().withAdListener(adListener).build());


text:
Q: Skipping To The Next if Statement from Inside a for Loop I've been learning some Java in my spare time and I'm a beginner, so I'm very sorry if I don't understand some simple concepts. I've been trying to make a "Robot" move around an already made map. I've been trying to make lines of a text file into multiple arrays (ie. moving forward, turning left, turning right). Then, I've been trying to use values in those arrays to make the robot move. Basically, if the text file says:
1 0 0
0 1 0
0 0 1

So the first line is for moving, the second is for turning left and the third is for turning left. This is supposed to make the robot move, and then not turn. Then it moves on to the next column and doesn't move, turns left, and doesn't turn right. I'm trying to make sure it works no matter how long the code is. I'm able to put it into three arrays correctly, but I'm having trouble with this for loop. When the loop executes and the values are all 1's or above, it works perfectly. However, if any value is a 0, it completely exits the loop and the robot doesn't move. Any help or advice would be appreciated! Thank you!
Code is below:
public static void robotMove(Robot x) throws Exception {

     for (int i = 0; i < movedata.length; i++) {

        int y = movedata[i];
        int s = leftdata[i];
        int j = rightdata[i];

           for (int a = 0; a < movedata.length; a++) {

              if (y == 0) {
              //asking what to put here
              }
              else {
                 again.Move(x, y);
              }

              if (s == 0) {
              //asking what to put here
              }
              else {
                 again.Left(x, s);
              }

              if (j == 0) {
              //asking what to put here
              }
              else {
                 again.Right(x, j);
              }

           }

     }

A: Assuming that movedata, leftdata and rightdata are the 3 arrays of same size corresponding to each line of your example, without knowing what again is but assuming it is the object handling the .Move(), .Left() and Right() actions made on the Robot x, I think the following should be enough:
public static void robotMove(Robot x) throws Exception {
    for (int i = 0; i < movedata.length; i++) {
        if (y != 0) {
            again.Move(x, movedata[i]);
        }

        if (s != 0) {
            again.Left(x, leftdata[i]);
        }

        if (j != 0) {
            again.Right(x, rightdata[i]);
        }
    }
}

*

*You can loop just once through movedata, I've removed the second nested loop.

*If the value is 0, you do not want to do anything. Hence you don't need an else part for that, just put code in the if value != 0.

From a code perspesctive, it would be cleaner if instead of having some if taking care that the value is not 0, you may implement the "inaction" directly in the methods .Move(), .Left() and .Right().


text:
Q: Css Validation Problem with facebook login button I hve used one facebook login button

in my site but it give 4 W3c error in http://validator.w3.org

*

*there is no attribute "AUTOLOGOUTLINK"

*there is no attribute "SIZE"

*there is no attribute "PERMS"

*element "FB:LOGIN-BUTTON" undefined

So, how can made a error free page with this button
my site is http://www.dialindia.com

A: Frankly this shouldn't be an issue tbh...
However if it bothers you, you can use jQuery to embed the FB login code once the DOM is ready so that it isn't sent as a part of the markup to the validator
Try something like :
jQuery(document).ready(function() {
     var fbCode = "Your facebook code goes here";
     $("#forgot").prepend(fbCode);
});


text:
Q: How can I apply a function that I created to each successive row of a column in python? I have a 4 rows in a column that I want to iterate over and apply a function to.
The df is a column and the values for instance are:
a
b
c
d
I want to apply the function in this way:
function(a,b)
function(a,c)
function(a,d)
function(b,c)
function(c,d)
How can I do this in python?
I've tried using df.apply(lambda column: compare_score, axis=0)
1


text:
Q: Reduce repetitive commands in PowerShell script Im really embarrassed asking this, but I have a script which I'm trying to make it look better, and less repetetive.
It has the following lines:
$textbox41.Add_Click({if ($Box41Trigger){$textbox41.text = ""; $textbox41.ForeColor="black";$script:Box41trigger=$false}})
$textbox42.Add_Click({if ($Box42Trigger){$textbox42.text = ""; $textbox42.ForeColor="black";$script:Box42trigger=$false}})
$textbox43.Add_Click({if ($Box43Trigger){$textbox43.text = ""; $textbox43.ForeColor="black";$script:Box43trigger=$false}})

You can see those 3 lines are repetitive only changing 41, 42, 43 etc. in two locations.
How can I make it look better? it looks so bad.

A: you can do this with a loop:
In order to test it, I created 3 folders in C:\ (1Test1-Kopie,2Test2-Kopie,3Test3-Kopie)
for ($Z=1; $Z -le 3; $Z++)

{Get-item -Path "C:\${Z}Test${Z} - Kopie"}

For your code i replaced 41,42 and 43 with ...4${Z}...as only the last digit is changing...try around to figure out if it works
for ($Z=1; $Z -le 3; $Z++)

{$textbox4${Z}.Add_Click({if ($Box4${Z}Trigger){$textbox4${Z}.text = ""; $textbox4${Z}.ForeColor="black";$script:Box4${Z}trigger=$false}})}

A: $textBoxList = @(
    $textBox41,
    $textBox42,
    $textBox43
)

foreach ($textBox in $texBoxList) {
    $textBoxTrigger = 'box' + $textBox.Name.Substring($textbox.length -2) + 'Trigger'
    $textBox.Add_Click( {
        if ($textBoxTrigger) {
            $textBox.text = "";
            $textBox.ForeColor="black";
            $script:textBoxTrigger=$false
        }
    })
}

Another option for grabbing the number on that second variable. Not certain on the name of the "Name" property on a textbox in powershell, so that may need to change to whatever the objects actual name property is when pulling the substring.


text:
Q: PHP and Smarty Execution For example, I have this query in my news.php file:
$sql = 'SELECT * FROM `news` ORDER BY `id` DESC LIMIT 0, 5';
$result = mysql_query($sql) or die("Query failed : " . mysql_error());
while ($line = mysql_fetch_assoc($result)) {
    $value[] = $line;
}
// Assign this array to smarty...
$smarty->assign('news', $value);
 // Display the news page through the news template
$smarty->display('news.tpl');

However, in my news.tpl file I will not put the {$news} variables. Will the query still be executed when I browse news.php or it will just be ignored?

A: Yes, the query will still be executed because you are loading the PHP file first. Once the query is exeucted, your PHP file will load the template whether you put the {$news} or not the database query will be execute.
If you don't need the query to run, you can add a flag (for example):
http://www.domain.com/news.php?show=0

and then in your PHP:
$value = array(); // this way if the variable is not used, you create a empty array.

if(isset($_GET['show']) && $_GET['show'] == 1) {
    $sql = 'SELECT * FROM test.`name` ORDER BY 1 DESC LIMIT 0, 5';
    $result = mysql_query($sql) or die("Query failed : " . mysql_error());
    while ($line = mysql_fetch_assoc($result)) {
        $value[] = $line;
    }
}
// Assign this array to smarty...
$Smarty->assign('news', $value);

// Display the news page through the news template
$Smarty->display('news.tpl');

and in your .tpl:
{section name=loopname loop=$news}
  // your news code
{sectionelse}
  No news today!
{/section}
{$news}


text:
Q: Using javascript and PHP to develop native android apps First off, I apologise for the ambiguity of this question but it is something I am hoping you can clear up for me.
The concept is that I would have a predefined template written in Java for an app, the template would consist of Classes such as:
public class Image {

    private int _x;
    private int _y;

    Image() {
        _x = 0;
        _y = 0;
    }

    Image(Int x, Int y) {
        _x = x;
        _y = y;
    }
}

The next bit I understand how to accomplish which is using javascript to post data to PHP, but I then want PHP to use this data to build the Java app. E.g. I might have a PHP function createImage($x = 0, $y = 0), which would then add to the Java source (The PHP would have to pass variable names.etc):
Image image342 = new Image(x, y);

Which I will later want to compile to an .apk android application.
I am having trouble working out how to get PHP to modify and add to the Java source, I realise I could do this with strings and writing to a physical file .e.g
public function createImage ($x = 0, $y = 0) {
  $this->$num++;
  $string = "Image image{$this->$num} = new Image({$x}, {$y});";
  $handle = fopen("/java/source/file", "ab");
  fwrite($handle, $string);
  fclose($handle);
}

But this feels somewhat messy, and I'm wondering if there is a better way to achieve my task.
Thanks

A: Considering that the entire Android build chain (e.g., compiler, dx bytecode cross-compiler) needs files, you have no choice but to create files. Creating a project's worth of customized files based on templates is a fairly typical form of code generation. For example, when you create a new Android project from the Eclipse wizard, that's pretty much what it does.
Part of that code generation would be to create an Ant build script for the Android project (based on the one you get from the android create project command). Your server could then code-gen then project and fork a process to run Ant to give you the APK.
Whether PHP is the right solution for your code-generation problem versus using something else that already does template-driven generation of a directory's worth of files, I can't say.


text:
Q: different sys path in cmd and idle i just observed the difference in the path for the cmd and idle. I tried this:
(IN IDLE)
>>> import sys
>>> sys.path
['', 'C:\\Python27\\Lib\\idlelib', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages']
>>> sys.executable
'C:\\Python27\\pythonw.exe'

while:
(IN CMD)
>>> import sys
>>> sys.path
['', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\l
ib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27,
C:\\Python27\\lib\\site-packages']
>>> sys.executable
'C:\\Python27\\python.exe'

My question is that why there is a difference between the python executables  of cmd and idle(for idle it is pythonw.exe while for cmd it is python.exe) and  how can i permanently make the sys.path point to same paths for cmd as well as idle as using sys.path.append() will do it temporaraily.Also,i want to know what is the difference between PYTHONPATH and system path.I know ; i have asked many questions but answers will very helpful. THANKS.


text:
Q: How to set Principal in Kafka console producer/consumer? I want to experiment with ACL's in Kafka. So I have created some ACL's for a sample topic test in my Zookeeper which allows producer permission to User:Bob principal and consumer permission to User:Alice principal.
Now when I am using the kafka-console-producer or the consumer how do I mention the principal for this producer or consumer?
I tried setting a new config like principal=User:Bob inside the producer/consumer.properties file but it says it's an unrecognized config.
Can someone help me figure this out?
Or Have I understood the idea of Principal wrong? Is it something to do with Kerberos based authentication?
Thanks in advance,
Shabir

A: I was experimenting with the above scenario by means of following a blog and figured out that Principal here actually means the CN (Common Name) attribute of an SSL communication.
Kafka uses the CN of the communicating server's SSL certificate to identify the user and to do authentication and authorization accordingly.
Thus, there is no place to explicitly mention the principal when running the consumer or the producer. It is taken from the SSL certificate's CN attribute.
Thanks
Shabir


text:
Q: .NET Directory.GetFiles() different behavior in different Windows Servers GetFiles() return all files in Windows Server 2016 (and Windows 10) but in Windows Server 2019 returns only not zero byte files.
At least i start to think that different server versions could be a source of such different behavior because there is no additional configurations for reading file for environments and no physical coded Length != 0 check anywhere so difference could be in environment itself.
Reason for question is that i can't find any documentation to prove that theory.


text:
Q: 2nd call to Device.Reset in DirectX throws an InvalidCallException I've been working on a DirectX application in C#, and I noticed that when I lock the workstation, the DirectX "Device" becomes lost. After looking up the information about what to do upon when a device is lost (and when a DeviceLostException is thrown by Device.Present), I re-wrote the code to reset the Device. This simply meant that I made a call to Device.Reset.
Calling Device.Reset recovered the Device. No problem. But when I lost the device a second time (for example, when the computer was locked, went to sleep, or activated a screen-saver), an exception was thrown by Device.Reset.
The exception was InvalidCallException, which (according to the documentation) means something went wrong with the call. So I assumed it was a problem with the arguments to the function. So instead of passing the same copy of PresentParams that I used to create the Device, I created a new instance of PresentParams (at first using the copy constructor, and later by re-creating without it) and passed that to Device.Reset.
Doesn't work. Device.Reset still dies with the InvalidCallException. Oh, and the message of the exception? "Error in application." Not helpful.
Can you point me in the direction of either a solution, or some documentation about how to get more debug information out of DirectX?

A: OK, I know how silly is seems to answer my own question, but I figured someone else might need this, eh?
The answer is: there were too many calls to the Dispose method of the VertexBuffers in the scene. The reason being that the internal Device reset-handlers were calling the Dispose method. And why was that happening? Because I had neglected to read the .NET DirectX SDK documentation regarding the Pool Enumeration, and was allocating the VertexBuffers using Pool.Default instead of Pool.Managed.
So obviously, after a few thousand badly done allocate-and-release cycles, something went wrong.
Oh, and how did I discover this? I attached a listener to VertexBuffer.Dispose which incremented a counter that I displayed on-screen. Imagine my suprise when I noticed this counter kept growing as I resized the window!


text:
Q: Using Perl's rename with groups I've a set of files named in the following manner:
_9978967868768763ghjgj7598983678hjva_week1-6.pdf
_78637832bdsjh275637bkkaww786b_week12-32.pdf
8786767867868978713bkwkhjhkjqw_week1-622.pdf
867813567bdjsbgbadsyu6712353125561235_week100-6.pdf

I'm intersted in making use of rename utility to obtain names:
 week1-6.pdf
 week12-32.pdf
 week1-622.pdf
 week100-6.pdf

The regex to achieve that could be be:
(.*)(week.*)

which works fine (regex101):

Question
How do I translate this syntax into rename's expression of format:
s/expr1/expr2/[gi]

In effect, I want to delete first group.
Notes
I'm not interested in using mv or sed-based solution. I want to use rename  utility only.

A: Try this, using the proper way :) just correcting your command (you are very close...) :
rename 's/(.*)(week.*)/$2/' *.pdf

or to simplify :
rename 's/.*(week.*)/$1/' *.pdf

A: prename approach:
prename -n 's/.*_(week.*$)/$1/' *_week*.pdf

*

*$1 - points to the 1st captured group


text:
Q: How do I perform a Room DAO multi table join @Query using select fields? My Problem:
I'm struggling to eliminate the compiling error on the following Room @Query statement in a Room DAO. As you can see, the SQLite query statement is joining various fields from different tables. The missing fields identified by the error are a part of the Notes class constructor identified in the List type for the method. I think I need to change the List type identified. If I'm right, I need some guidance/suggestion on how I should resolve it. Do I need to create a new Class and DAO with just those specific fields queried? Or maybe just a class since there is not table specific to these fields only. The error is:

error: The columns returned by the query does not have the fields [commentID,questionID,quoteID,termID,topicID,deleted] in com.mistywillow.researchdb.database.entities.Notes even though they are annotated as non-null or primitive. Columns returned by the query: [NoteID,SourceID,SourceType,Title,Summary]
      List getNotesOnTopic(String topic);

@Query("SELECT n.NoteID, s.SourceID, s.SourceType, s.Title, c.Summary FROM Comments as c " +
        "LEFT JOIN Notes as n ON n.CommentID = c.CommentID " +
        "LEFT JOIN Sources as s ON n.SourceID = s.SourceID " +
        "LEFT JOIN Topics as t ON n.TopicID = t.TopicID WHERE t.Topic = :topic AND n.Deleted = 0")
List<Notes> getNotesOnTopic(String topic);

What I'm trying to do:
I'm attempting to convert and existing Java desktop app with an embedded an SQLite database. The above query does work fine in that app. I only want to pass field data from these tables.
What I've tried:
I've done some googling and visited some forums for the last few days (e.g. Android Forum, Developer.Android.com) but most of the Room @Query examples are single table full field queries (e.g. "Select * From table"). Nothing I found yet (there is probably something) quite addresses how and what to do if you are joining and querying only specific fields across tables.

A: I think I may have fixed my issue. I just created a new class called SourceTable and designated the queried fields in the constructor. The only catch was I, according to a follow up error, was that the parameters had to match the field names.
public class SourcesTable {
    private int NoteID;
    private int SourceID;
    private String SourceType;
    private String Title;
    private String Summary;

    public SourcesTable(int NoteID, int SourceID, String SourceType, String Title, String Summary){
        this.NoteID = NoteID;
        this.SourceID = SourceID;
        this.SourceType = SourceType;
        this.Title = Title;
        this.Summary = Summary;
    }
}

and then I update my list method:
List<SourcesTable> getNotesOnTopic(String topic);


text:
Q: How to get all item names in getview method in side base adapter before scorlling in Android In my application I am fetching all the images and names from a MySQL server database to the Android mobile. If the emulator screen is HVGA, only five images and names are getting displayed. In logcat also only five names are getting printed. When I scroll the screen, how many names I can see on the screen only that much names are getting printed. Instead of that, all the names have to get printed before scrolling.
This my Java code:
public class VegdishesListview extends BaseAdapter {
    String qrimage;
    Bitmap bmp, resizedbitmap;
    Bitmap[] bmps;
    Activity activity = null;
    private LayoutInflater inflater;

    private ImageView[] mImages;
    String[] itemimage;
    TextView[] tv;
    String itemname,price,desc;
    String[] itemnames;
    String[] prices;
    String[] descs;
    HashMap<String, String> map = new HashMap<String, String>();

    public VegdishesListview(Context context, JSONArray imageArrayJson) {
        //inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //  imageLoader=new ImageLoader(activity);
        inflater=LayoutInflater.from(context);
        this.mImages = new ImageView[imageArrayJson.length()];
        this.bmps = new Bitmap[imageArrayJson.length()];
        this.itemnames = new String[imageArrayJson.length()];
        this.prices=new String[imageArrayJson.length()];
        this.descs=new String[imageArrayJson.length()];
        try {
            for (int i = 0; i < imageArrayJson.length(); i++) {
                JSONObject image = imageArrayJson.getJSONObject(i);
                qrimage = image.getString("itemimage");
                itemname = image.getString("itemname");
                price=image.getString("price");
                desc=image.getString("itemdesc");

                itemnames[i] = itemname;
                prices[i]=price;
                descs[i]=desc;

                byte[] qrimageBytes = Base64.decode(qrimage.getBytes());

                bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
                                                    qrimageBytes.length);
                int width = 100;
                int height = 100;
                resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
                                                          true);
                bmps[i] = bmp;

                mImages[i] = new ImageView(context);
                mImages[i].setImageBitmap(resizedbitmap);

                mImages[i].setScaleType(ImageView.ScaleType.FIT_START);

                // tv[i].setText(itemname);
            }
            System.out.println(map);
        }
        catch (Exception e) {
            // TODO: handle exception
        }
    }

    public int getCount() {
        return mImages.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        vi = inflater.inflate(R.layout.vegdisheslistview, null);

        TextView text=(TextView)vi.findViewById(R.id.vegdishestext);
        ImageView image=(ImageView)vi.findViewById(R.id.vegdishesimage);
        TextView text1=(TextView)vi.findViewById(R.id.vegdishesprice);
        TextView text2=(TextView)vi.findViewById(R.id.vegdishesdesc);
        image.setImageBitmap(bmps[position]);
        text.setText(itemnames[position]);
        text1.setText(prices[position]);
        text2.setText(descs[position]);
        System.out.println(itemnames[position]);

        return vi;
    }

When I am scrolling means how many itemnames can view that many item I can print here. How do I print all itemnames instead of scrolling?

A: As you are actually storing the  names as a member field of your adapter class, you could print them inside the constructor, just iterating over the array.


text:
Q: SQL Syntax on using OPENROWSET for reading a flat file I have a Text file, which i am using below syntax to read.
SELECT BulkColumn
FROM OPENROWSET (BULK 'C:\MyFolder\Priceflatfile.txt', SINGLE_CLOB) Myfile

Syntax returns multiple row of records in a single row in one column.
I have three column of multiple row of records. Is it possible to read the flat file in a SQL Syntax by displaying with table of records.


text:
Q: Bootstrapping Angular CLI App with HTML script tag I have an Angular 4 app which is using SystemJS. I want to move to using Angular CLI. The problem is, I bootstrap the application in the index.html using a script tag as follows.
<script>
    var sf = $.ServicesFramework([ModuleContext:ModuleId]);
    System.import('app/main.js')
        .then(module => module.main(sf.getModuleId(), sf.getTabId(), sf.getAntiForgeryValue())
        .catch(function (err) { console.error(err); });

</script>

Here is the relevant code from my main.ts
export function main(dnnModuleId: number, dnnTabId: number, dnnAntiForgeryToken: string) {

     let appConfig: IAppConfig = {
         DNN_MODULE_ID: dnnModuleId
         ...
      }

 platformBrowserDynamic([
     {provide: APP_CONFIG_TOKEN, useValue: appconfig
     ...
 ]).bootstrapModule(AppModule);

After an extensive search, I i was only able to find an old question related to Webpack 1 and not related to Angular CLI.
In short is it possible to do this with Angular CLI?
If so, any guidance in where to begin looking would be much appreciated.


text:
Q: Android UI Design : viewpager inside coordinatorlayout I want to make awesome design like this.
but I have some questions about making it.

*

*Is it using coordinatorlayout? If is so, How can I put fragment inside it like this?

*How can I stack cards when using viewpager? (it doesn't have to be viewpager, just want to know how)


text:
Q: Get Reactive Form Values In One Go I created a Angular project where user can give inputs and validate forms as follows:
<form [formGroup]="angForm" novalidate>

        Name:
        <input class="form-control" [(ngModel)]="name" formControlName="name" type="text" />

          Name is required.

        Address:
        <input class="form-control" [(ngModel)]="address" formControlName="address" type="text" />

          email is required.

    <button type="submit" (click)="buttonClicked()" class="btn btn-success">
        Save
    </button>
</form>

So as this is a reactive form, I tried to retrieve the values from the inputs as follows, assigned ngModel property in the text fields:
<input class="form-control" [(ngModel)]="name" formControlName="name" type="text" />

In the TypeScript, I am doing something as follows:
export class SampleComponent implements OnInit {

    constructor(private fb: FormBuilder) {
       this.validateForm();
    }

    ngOnInit() {

    }

    angForm: FormGroup;
    name: string;
    address: string;

    //Retrieve value from input field on button click
    buttonClicked() {
       alert("Button works with the value: " + this.name);
    }
}

This works cool and I am getting the result as expected. But I've a model that has lot of properties. Say as an example:
export class SampleClass {
   name: string;
   address: string;
   ................
   With other lot of fields
}

So my question is can I do something like this if I've the same model properties in the ngModel defined in the frontend, so is it valid or could be possible to define as follows:
this.SampleClass = this.angForm.value; //So all properties can be retrieved in one go

Right now, what I am doing is binding all properties one by one as follows:
obj: SampleClass ;

this.obj = new SampleClass();
this.obj.name= this.name;
this.obj.address= this.address;

A: If you use the reactive form, which means you shouldn't use ngmodel you can retrive form's value using getRawValue() method.
Check this angular guide on how to create a reactive form


text:
Q: Nestjs project fails to start because it reads files outside of it's module
My Nestjs Project fails to start because it indexes other node projects out of its own project folder.

A: Seems like your configuration and thus your entity file does not recognize src/ as part of your application.
Try replacing src/directors/director.entity inside your movies.entity.ts with relative path such as ../../directors/director.entity and see what happens then.


text:
Q: Ruby on Rails: Can I route a request directly to a view? I have an admin section that has a sub-directory of the controllers directory. I.e., the directory app/controllers/admin/ holds a set of files, each containing a controller for handling a separate portion of the admin section.
Now, I want to create a very simple ''admin homepage'' that just says something a la "welcome to the admin section", but I want to avoid creating an entire controller for this purpose, or placing the "action" method for this view in some other, arbitrary controller.
So, the question is, is there a way to route ''directly to a view'' -- to route directly to an HTML file?  (And, I don't want to route to an HTML file from a requested path like /some-file.html; I need to route from a path like /admin/.)
Asking this question here is hardly worth the time it takes to create a stub controller, but I'm sure I will have such a need again in the future.

A: Like moritz says, you can't completely bypass the controller, but you do not necessarily have to create an entire controller just for this action. When I need a "dashboard" or "landing" type of page, I just add the action to my ApplicationController:
class ApplicationController < ActionController::Base
  def index
  end
end

Then put your page at app/views/application/index.html.erb
For your case, you can put an application_controller.rb in your app/controllers/admin/ directory, and do the same thing there.
I find that this is the perfect place for pages that fall outside of a resource.

A: No, you can't. Why?
Design: It's just a violation of the MVC pattern Rails enforces you to use, for your own good. There is always a controller involved. And yes, even for such stub pages, a controller is required. Anyway, a few lines of code won't hurt you, and you'll love it again when you need to perform some access control.
Hope that answered your question :-)


text:
Q: Convert a for loop from MATLAB into Python I have tried to convert a MATLAB code into Python but not getting the appropriate results. The results of MATLAB are right but the results of Python code are wrong.
My MATLAB code is:
xc =[27.6851 27.6573 27.6358 27.6499 27.6448 27.6435 27.6480 27.6418 27.6556  27.6506 27.6066 27.6004
   27.5988 27.5939 27.5892 27.5755 27.5774 27.5968 27.5907 27.5861 27.5776 27.5554 27.5509 27.5210 27.5094
   27.5109 27.4952 27.4777 27.4617 27.4298 27.4275 27.4186 27.4338 27.4247 27.4132 27.4111 27.4014 27.3751
   27.3411 27.3276 27.3043 27.2914 27.2840 27.2216 27.1806 27.1619 27.1599 27.1727 27.1644 27.1724 27.1722
   27.1741 27.1807 27.1814 27.1791 27.1720 27.1653 27.1621 27.1590 27.1598 27.1645 27.1587 27.1500 27.1573
   27.1635 27.1605 27.1503 27.1489 27.1509 27.1503 27.1454 27.1167 27.0813 27.0524 27.0040 26.9938 26.9731
   26.9935 26.9870 26.9876 26.9887 26.9920 26.9851 26.9736 26.9906 27.0207 27.0270 27.0220 27.0224 27.0241
   27.0213 27.0152 27.0182 27.0235 27.0431 27.0516 27.0493 27.0405 27.0424 27.0383 27.0353 27.0293 27.0288
   27.0333 27.0403 27.0421 27.0449 27.0723 27.1126 27.1903 27.2248 27.2522 27.2646 27.2721 27.2726 27.2959
   27.3411 27.3833 27.4242 27.4889 27.5974 27.6362 28.0603];
yc = [22.7222 22.7192 22.6895 22.6662 22.6459 22.6377 22.6498 22.6579 22.6530 22.6664 22.6903 22.6904
   22.7133 22.7365 22.7414 22.7678 22.7831 22.7956 22.8158 22.8497 22.8633 22.8916 22.9066 22.9493
   22.9893 23.0000 23.0118 23.0371 23.0545 23.0857 23.0978 23.1105 23.1083 23.1255 23.1350 23.1422
   23.1623 23.1828 23.2156 23.2344 23.2622 23.2705 23.2906 23.3335 23.4233 23.4887 23.5721 23.6112
   23.6368 23.6530 23.6813 23.7030 23.7298 23.7612 23.7900 23.8237 23.8459 23.8881 23.9266 23.9494
   23.9866 24.0173 24.0344 24.0827 24.1190 24.1501 24.1796 24.1883 24.1985 24.2336 24.3291 24.3946
   24.4475 24.4868 24.5159 24.5969 24.6645 24.7714 24.8320 24.8987 25.0400 25.1576 25.2470 25.3148
   25.4278 25.5148 25.5629 25.5927 25.6133 25.6391 25.6453 25.6630 25.6738 25.6874 25.7278 25.7371
   25.7590 25.7740 25.7956 25.8046 25.8755 25.8226 25.8929 25.8323 25.8631 25.7839 25.7516 25.7103
   25.7021 25.6988 25.7069 25.7092 25.7137 25.7180 25.7247 25.6927 25.7097 25.7337 25.7497 25.7821
    25.8509 25.9075 25.6166];

idx_start = [1,5,9,100,105,1];
idx_end = [5,9,100,105,123,123];
Length_idx=idx_end-idx_start+1;

for i=1:length(idx_start)
    if Length_idx(i)>=12 %Minimum number of points to calculate MSD
        for j=1:Length_idx(i)
            msd(j)=mean((xc(idx_start(i)+j:1:idx_end(i))-xc(idx_start(i):1:idx_end(i)-j)).^2 + (yc(idx_start(i)+j:1:idx_end(i))-yc(idx_start(i):1:idx_end(i)-j)).^2 );
        end
    end
end

msd

I have tried to convert MATLAB code into Python. My Python code is:
import numpy as np

x = np.array([[27.685125],[27.657279],[27.635751],[27.649908],[27.64476 ],[27.643473],[27.648036],[27.641835],[27.655641],[27.65061 ],[27.606618],[27.600417],
              [27.598779],[27.593865],[27.589185],[27.575496],[27.577368],[27.59679 ],[27.590706],[27.586143],[27.577602],[27.555372],[27.550926],[27.520974],
              [27.509391],[27.510912],[27.495234],[27.477684],[27.461655],[27.429831],[27.427491],[27.418599],[27.433809],[27.424683],[27.413217],[27.411111],
              [27.4014  ],[27.375075],[27.341145],[27.327573],[27.30429 ],[27.29142 ],[27.284049],[27.221571],[27.180621],[27.161901],[27.159912],[27.172665],
              [27.164358],[27.172431],[27.172197],[27.174069],[27.180738],[27.18144 ],[27.1791  ],[27.171963],[27.165294],[27.162135],[27.158976],[27.159795],
              [27.164475],[27.158742],[27.149967],[27.157338],[27.163539],[27.160497],[27.150318],[27.148914],[27.150903],[27.150318],[27.145404],[27.116739],
              [27.081288],[27.052389],[27.003951],[26.993772],[26.973063],[26.993538],[26.986986],[26.987571],[26.988741],[26.992017],[26.985114],[26.973648],
              [26.990613],[27.020682],[27.027   ],[27.021969],[27.022437],[27.024075],[27.021267],[27.015183],[27.018225],[27.02349 ],[27.043146],[27.05157 ],
              [27.049347],[27.040455],[27.042444],[27.038349],[27.035307],[27.02934 ],[27.028755],[27.033318],[27.040338],[27.042093],[27.044901],[27.072279],
              [27.112644],[27.190332],[27.224847],[27.252225],[27.264627],[27.272115],[27.272583],[27.295866],[27.341145],[27.383265],[27.424215],[27.488916],
              [27.597375],[27.636219],[28.060344]])

y = np.array([[22.722219],[22.719177],[22.689459],[22.666176],[22.645935],[22.637745],[22.649796],[22.657869],[22.652955],[22.66641 ],[22.690278],[22.690395],
              [22.713327],[22.736493],[22.741407],[22.767849],[22.783059],[22.795578],[22.815819],[22.849749],[22.863321],[22.891635],[22.906611],[22.949316],
              [22.98933 ],[22.999977],[23.011794],[23.037066],[23.054499],[23.085738],[23.097789],[23.110542],[23.108319],[23.125518],[23.134995],[23.142249],
              [23.162256],[23.182848],[23.215608],[23.234445],[23.262174],[23.270481],[23.290605],[23.333544],[23.423283],[23.488686],[23.572107],[23.611185],
              [23.636808],[23.652954],[23.681268],[23.70303 ],[23.729823],[23.761179],[23.789961],[23.823657],[23.845887],[23.888124],[23.926617],[23.949432],
              [23.986638],[24.017292],[24.034374],[24.082695],[24.118965],[24.150087],[24.179571],[24.188346],[24.198525],[24.233625],[24.329097],[24.394617],
              [24.447501],[24.486813],[24.515946],[24.59691 ],[24.664536],[24.771357],[24.831963],[24.898653],[25.039989],[25.157574],[25.246962],[25.314822],
              [25.427844],[25.514775],[25.562862],[25.592697],[25.613289],[25.639146],[25.645347],[25.663014],[25.673778],[25.68735 ],[25.727832],[25.737075],
              [25.758954],[25.774047],[25.795575],[25.804584],[25.875486],[25.822602],[25.892919],[25.832313],[25.863084],[25.783875],[25.751583],[25.710282],
              [25.702092],[25.698816],[25.706889],[25.709229],[25.713675],[25.718004],[25.724673],[25.692732],[25.709697],[25.733682],[25.749711],[25.78212 ],
              [25.850916],[25.907544],[25.616565]])

idx_start = np.array([1,5,9,100,105,1])
idx_end = np.array([5,9,100,105,123,123])
length_idx = idx_end - idx_start + 1

for i in range(0, len(idx_start)):
    msd = []
    if length_idx[i] >= 12 :
        for j in range(1, length_idx[i] + 1):
            t1 = np.power(x[idx_start[i] + j: idx_end[i] , :] -
                          x[idx_start[i]: idx_end[i] - j , :], 2)
            t2 = np.power(y[idx_start[i] + j: idx_end[i] , :] -
                          y[idx_start[i]: idx_end[i] - j , :], 2)
            msd.append(np.mean(t1 + t2, axis=0)[0])

my_formatted_list = [ '%.4f' % elem for elem in msd ]
print(my_formatted_list)

where x and y are column vectors of shape (123,1)
Expected output is:
0.0045  0.0101  0.0195  0.0313  0.0457  0.0626
0.0820  0.1037  0.1279  0.1547  0.1843  0.2165
0.2510  0.2881  0.3269  0.3679  0.4110  0.4571
0.5054  0.5567  0.6098  0.6659  0.7240  0.7849
0.8483  0.9145  0.9835  1.0555  1.1301  1.2071
1.2871  1.3702  1.4570  1.5474  1.6413  1.7388
1.8401  1.9448  2.0513  2.1604  2.2724  2.3870
2.5028  2.6187  2.7348  2.8518  2.9672  3.0842
3.2018  3.3232  3.4471  3.5734  3.7012  3.8291
3.9595  4.0931  4.2304  4.3702  4.5125  4.6570
4.8028  4.9518  5.1040  5.2577  5.4142  5.5726
5.7326  5.8968  6.0646  6.2351  6.4043  6.5733
6.7430  6.9142  7.0873  7.2593  7.4274  7.5850
7.7358  7.8770  8.0065  8.1259  8.2378  8.3426
8.4342  8.5148  8.5897  8.6610  8.7312  8.7994
8.8684  8.9370  9.0059  9.0730  9.1317  9.1890
9.2402  9.2890  9.3325  9.3662  9.3730  9.3910
9.3818  9.3880  9.3741  9.3820  9.3972  9.4253
9.4538  9.4908  9.5201  9.5433  9.5653  9.5774
9.5797  9.6126  9.6359  9.6288  9.6105  9.5703
9.3530  8.5180     NaN

But I am getting this:
['0.0045', '0.0102', '0.0196', '0.0315', '0.0460', '0.0631',
 '0.0826', '0.1046', '0.1289', '0.1560', '0.1859', '0.2184',
 '0.2533', '0.2907', '0.3298', '0.3712', '0.4148', '0.4613',
 '0.5101', '0.5619', '0.6154', '0.6720', '0.7305', '0.7919',
 '0.8560', '0.9228', '0.9923', '1.0650', '1.1401', '1.2180',
 '1.2988', '1.3830', '1.4708', '1.5622', '1.6573', '1.7558',
 '1.8581', '1.9636', '2.0714', '2.1814', '2.2948', '2.4108',
 '2.5270', '2.6427', '2.7591', '2.8762', '2.9928', '3.1109',
 '3.2302', '3.3529', '3.4784', '3.6063', '3.7356', '3.8649',
 '3.9966', '4.1318', '4.2704', '4.4115', '4.5559', '4.7019',
 '4.8495', '5.0009', '5.1545', '5.3101', '5.4686', '5.6290',
 '5.7925', '5.9603', '6.1306', '6.2997', '6.4687', '6.6380',
 '6.8089', '6.9816', '7.1532', '7.3241', '7.4885', '7.6452',
 '7.7942', '7.9251', '8.0454', '8.1575', '8.2637', '8.3568',
 '8.4395', '8.5151', '8.5871', '8.6570', '8.7247', '8.7936',
 '8.8610', '8.9297', '8.9982', '9.0597', '9.1184', '9.1722',
 '9.2206', '9.2653', '9.3070', '9.3208', '9.3411', '9.3363',
 '9.3441', '9.3384', '9.3498', '9.3692', '9.4034', '9.4409',
 '9.4806', '9.5217', '9.5574', '9.5851', '9.6120', '9.6265',
 '9.6660', '9.7075', '9.7310', '9.7276', '9.6802', '9.4572',
 '8.5573', 'nan', 'nan']


text:
Q: Copy files to Docker container using Dockerode without archiving the files I am able to copy files to docker container by archiving the files.
        var dockerode = require('dockerode');
        var docker = new dockerode();
        var dockrContainer = docker.getContainer(containername);
        dockrContainer.putArchive(srcpath, {path: destpath});

The problem is that if I have an archived file in my code repository then my company security scan gives violation. Using dockerode, is it possible to copy multiple files of a directory into docker container without archiving them?


text:
Q: Clear data when application close I need to save some data when i login to the application and once i kill the app user data and session should have to be clear.
I have tried some method in Xamarin essential but it's not working

A: Try Xamarin.Essential's SecureStorage and you can clear user data in android by overriding OnDestrory method. Clear the stored data in SecureStorage.


text:
Q: How to get the changed cells or added rows after Datagridview Sort I have a DatagridView with datasource as follows:
bindingSource = DataTable
dataGridView.DataSource = bindingSource

When the cells are edited or new rows are added I apply a different formatting style, If I sort the dataGridView clicking on one of the column headers the formatting style is lost, So my question is:
After sorting the datagridview how do I know which cells changed or were added ?, so I can re-apply the formatting style
VB .Net or C# is OK

A:
I finally achieved the desired functionality adding a new field/column to the Datatable and instead keeping just one value for the entire row in that field, I store string representing the state/style for each cell like ",,E,,,E" so this sample string would indicate that the cell at index 2 and 5 should have an edited style.
I create/change that string in the CellValueChanged event, sample:
 Private Sub DataGridView_CellValueChanged(sender As System.Object, e As DataGridViewCellEventArgs) Handles DataGridView.CellValueChanged
        If e.RowIndex = -1 Or IsNothing(DataGridView.CurrentCell) Then
            Return
        End If

        Dim cellPosition As Short = DataGridView.CurrentCell.ColumnIndex
        Dim Styles(25) As String

        Dim stylesCell = DataGridView.Rows(e.RowIndex).Cells("CellStyleDescriptor").Value

        If Not IsDBNull(stylesCell) And _
            Not IsNothing(stylesCell) Then
            Styles= Split(stylesCell, ",")
        End If

        If IsDBNull(DataGridView.Rows(e.RowIndex).Cells("Id").Value) Then
            For i As Integer = 0 To 25 'New row is being added
                Styles(i) = "N"
            Next
        Else
            Styles(cellPosition) = "E" 'Edited/Modified Cell
        End If

        DataGridView.Rows(e.RowIndex).Cells("CellStyleDescriptor").Value = String.Join(",", String)
    End Sub

and read/apply the styles in the CellFormatting event, sample:
 Private Sub DataGridView_CellFormatting(sender As System.Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView.CellFormatting
        If e.RowIndex = -1 Or e.ColumnIndex = -1 Then
            Return
        End If

        Dim styles(25) As String
        styles = Split(DataGridView.Rows(e.RowIndex).Cells("CellStyleDescriptor").Value, ",")

        Select Case styles(e.ColumnIndex)
            Case "E" 'Edited cell
                e.CellStyle.BackColor = modifiedStyle.BackColor
                e.CellStyle.ForeColor = modifiedStyle.ForeColor
            Case "N" 'New cell
                e.CellStyle.BackColor = newStyle.BackColor
                e.CellStyle.ForeColor = newStyle.ForeColor
        End Select
    End Sub

I hope this helps someone


text:
Q: How to instrument network calls in Xamarin.forms android on a physical device? I am looking for a way to instrument the api/network calls made in Xamarin android, so that I could log all the http request/response and header details for every api call. Can some one let me know is there any approach to do that or any Nuget available?
Thanks in advance.