text:
Q: Rest Cannot be resolved to a type I'm trying to write my Rest Interface with restygwt therefore I inherit
<inherits name='org.fusesource.restygwt.RestyGWT' />

and also added the dependency into my pom file.
import java.awt.PageAttributes.MediaType;

import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.RestService;

@Path("/user")
public interface UserRestService extends RestService {

    @GET
    @Path("/users")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public void getUsers(MethodCallback<List<User>> callback);
}

All my Annotations cannot be resolved to a type. Is there also another library necessary or what am I missing?

A: You can use JAX-RS 2.0 annotations
<dependency>
  <groupId>javax.ws.rs</groupId>
  <artifactId>javax.ws.rs-api</artifactId>
  <version>2.0</version>
</dependency>

A: Added the JAX-RS dependency, know it works fine.
    <!-- JAX-RS -->
    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>jsr311-api</artifactId>
        <version>1.1</version>
        <scope>provided</scope>
    </dependency>

A: You should add these jars to your project.

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.19.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-server -->
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-server</artifactId>
    <version>2.26</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-servlet -->
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-servlet</artifactId>
    <version>1.19.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.ws.rs/jsr311-api -->
<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>jsr311-api</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
  <groupId>javax.ws.rs</groupId>
  <artifactId>javax.ws.rs-api</artifactId>
  <version>2.0</version>
</dependency>


text:
Q: Trying an If Statement with the Connection Open I am trying to make an if statement in case I could not open a connection to SQL Server, to display a label, and alternatively to display another form. The code is as follows:
private void button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection("Data Source=xxx.ac.uk;Initial Catalog=XXXX;User ID=xxxx;Password=xxxxx");

    try
    {
       // string sql = "SELECT * FROM datatable";
        SqlCommand mycommand = new SqlCommand("SELECT * FROM datatable", conn);
        try
        {
            conn.Open();
            mycommand.ExecuteNonQuery();
        }
        finally
        {
                if (mycommand != null)
                label1.Visible = true;
                label1.Text = "Failed to Access Database! Please log into VPN Using The Link Below.";
        }
    }
    finally
    {
        if (conn != null)

            this.Hide();
        Form1 form = new Form1();
        form.Show();

    }

    }

}

}

Whenever I run the file offline, I get a timeout issue and I am unable to use the app as I get an exception. I want an if statement to check if there is a connection then to go to the form and if there is not, then show the label.
Regards, any help appreciated.

A: I think your method is trying to do a bit too much. You shouldn't have to query a table. Simply opening the connection should be enough.
var canAccessDB = false;

try
{
    conn.Open();
    canAccessDB = true; // Will only get here if Open() is successful
}
catch
{
    // nothing needed here
}
finally
{
    if (conn != null)
        conn.Dispose(); // Safely clean up conn
}

if (!canAccessDB)
{
    label1.Visible = true;
    label1.Text = "Failed to Access Database! Please log into VPN Using The Link Below.";
}
else
{
    this.Hide();
}

Form1 form = new Form1();
form.Show();

A: A finally block will run every time.  You need a catch block with code to execute in case there is a problem with what is in the try block.

A: You could catch the SqlException if the connection fails and display the message to the user
using (SqlCommand mycommand = new SqlCommand("SELECT * FROM datatable", conn))
{
    try
    {
        conn.Open();
        mycommand.ExecuteNonQuery();
    }
    catch (SqlException ex)
    {
        label1.Visible = true;
        label1.Text = string.Format("Failed to Access Database! Please log into VPN Using The Link Below.\r\n\r\nError: {0}", ex.Message);
        return;
    }

    if (conn != null)
    {
        this.Hide();
        Form1 form = new Form1();
        form.Show();
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: What happen when I add iPhone 6+ launch image but without @3x icon image? I tried to add iPhone 6+ launch image to project but without @3x icon images in xcode 6.1 iOS 8.
Actually it seems work fine to me.
Does that mean the scaled @2x image is used on iPhone 6+ if without @3x in image asset?
and is it true app without 3x image will be rejected?

A: Yes, @2x scaled will be used (as you can see by running in simulator or on your device). But remember that adding @3x icon required to distribute your app to the App Store.


text:
Q: React Mobile Safari - iOS - spell check stores previously typed text into keyboard I have an <input type="text"> element. The user types a string and hits enter which clears the element via $('input').val(''). The problem apparently is that iOS still has the previous input string in its autocorrect buffer, so when you begin to type a new word and hit space, it sees the last word from the previous string and the first word from the new string as one 'word' and attempts to autocorrect it. Example:
I realize this may just be a bug in mobile safari below is an example
any help would be highly appreciate


text:
Q: How can I get the value of this variable? In logout function, I need to get the value of $time. This variable was declared in other function, when user logged in.
Broadcast::channel('chat', function ($user) {
        $ip = Request::ip();
        $time = now();
        if (auth()->check() && !session()->has('name'))  {
            UserInfo::storeUser();
            session()->put('name',$user->name);
            return [
                'id' => $user->id,
                'ip' => $ip,
                'name' => $user->name,
                'joined' => $time,
            ];
        }
    });

When user logged out, I have to check his 'id' and value of 'joined'. How can I do this?
public function logout() {
       $id = auth()->id();
       $info = \App\UserInfo::where('id', $id)
                             -> where('joined', $time)
                             ->update(['left' => now()]);
        auth()->logout();
        session()->forget('name');
        session()->put('left',now());
        return redirect('/');
    }

A: You must use a primary unique key as id and make a column 'user_id' for storing the auth()->id in the table. While joining/starting log in session, store the 'id' in application as 'session_id'.
You can get the 'joined' value by using id as follows,
$joined = \App\UserInfo::where('id', auth()->session_id)
          ->select('joined')
          ->first()
          ->joined;

At end of session, update the left details with the id as follows,
 $info = \App\UserInfo::where('id', auth()->session_id)
            ->update(['left' => now()]);


text:
Q: Windows enterprise sideloading domain group policy I'd like to sideload my Windows Store App to a Windows 8 Enterprise PC. The PC is domain-joined but now I am a little bit stuck.
As it says in the Documentation, the Group Policy on the domain controller must be set:

You must join the device running Windows 8 Enterprise or Windows Server 2012 to an Active Directory domain that has the Allow all trusted applications to install Group Policy setting enabled.

How do I set this Group Policy on my Windows Server 2008? There is no such policy. Does this mean that I need the newest Windows Server 2012 for this? I did set this group policy on the client as well, but anyway I need to activate a developer account. I don't want to do this because a developer account expires after 1 month...

A: Ok, apparently you can add Windows 8 group policies to a Windows Server 2008.
Administrative Templates (.admx) for Windows 8 and Windows Server 2012
If you dowloaded and installed this file you then can take the needed files and copy them to %systemroot%\PolicyDefinitions. Then you can activate the policy. I did this, but I still had to activate my MS developer account on the Windows 8 Enterprise machine. I don't know how to avoid this.


text:
Q: Program is not accessible from the command-line I am trying to use BUSCO program for bioinformatic analysis. BUSCO need to Agustus program as dependency. According to BUSCO's user guide I must add Augustus to path and I did it as following:
export PATH=$PATH:/home/dr/augustus-3.2.2/bin
export PATH=$PATH:/home/dr/augustus-3.2.2/script
export AUGUSTUS_CONFIG_PATH=/home/dr/augustus-3.2.2/config/

to ensure that adding is in correct way I ran augustus in command line and it worked well, but when I ran BUSCO I get following ERROR:
"Augustus is not accessible from the command-line, please add it to environment"
What is wrong that I get this error and how can fix it?
thanks in advance


text:
Q: Getting current_user undefined method while using devise gem - Ruby on Rails 4.1.5 I'm following tutorial: https://www.youtube.com/watch?v=7-1HCWbu7iU
I already did Pintrest clone using devise gem and had no issue. When I try to add current_user to links controller I get "undefined method current_user". I tried everything... even redoing the app from scratch, defining current_user, resetting the database. I guess the gem should handle the method automatically, right?
Here are my steps:
1. Generate new app - rails new raddit
2. Generate scaffold: rails g scaffold link title:string url:string
3. rake db:migrate
4. add gem 'devise', '~> 3.3.0' to gem file and run bundle install
5. run rails g devise:install
6. add file to development.rb - config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
7. add alerts to layout/application.html (as per devise documentation)
8. generate view file - rails g devise:views
9. generate user - rails g devise User
10. rake db:migrate
11. rails s
12. go to localhost:3000/users/sign_up (works ok)
13. Add relation to models: user.rb - has_many :links ; link.rb -   belongs_to :user
14. Create migration: rails generate migration add_user_id_to_links user_id:integer:index
15. rake db:migrate
16. go to rails console and save assocation between user and links.
17. Add current_user to links controller - Getting undefined 'curren_user method' once I go to localhost:3000/links/new

Here is my code:
  class LinksController < ApplicationController
  before_action :set_link, only: [:show, :edit, :update, :destroy]

  def index
     @links = Link.all
  end

  def show
  end

  def new
    @link = Link.current_user.links.build
  end

  def edit
  end

  def create
    @link = current_user.build(link_params)

    respond_to do |format|
      if @link.save
        format.html { redirect_to @link, notice: 'Link was       successfully created.' }
         format.json { render :show, status: :created, location:  @link }
      else
         format.html { render :new }
         format.json { render json: @link.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @link.update(link_params)
        format.html { redirect_to @link, notice: 'Link was successfully updated.' }
        format.json { render :show, status: :ok, location: @link }
      else
        format.html { render :edit }
        format.json { render json: @link.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
       @link.destroy
       respond_to do |format|
       format.html { redirect_to links_url, notice: 'Link was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_link
      @link = Link.find(params[:id])
    end

   def link_params
      params.require(:link).permit(:title, :url)
   end
   end

My models: link.rb
class Link < ActiveRecord::Base
    belongs_to :user
end

My models: user.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :links
end

A: You are getting the undefined method 'current_user' in the new action where you are calling Link.current_user.
def new
  @link = Link.current_user.links.build
end

should be
def new
  @link = current_user.links.build
end

Link does not have a current_user method, that is the problem.  current_user is defined in the context of the controller and should be used as you do in the create action.

A: it should be
@link = current_user.links.build
in new action
if you have more problem than just type exit in new action and check the current_user in console..  You can get errors from console.. so every time check your console first.
use better_errors gem.. for more info about the particular error


text:
Q: NavMeshNavigation - Load Failed: Object reference not set to an instance of an object EDIT: This is different from other questions because the code is much more specific to NavMesh code. I haven't found any questions specific to my code. (also other question seems to involve null?)
I'm trying to learn NavMeshAgent for use in point and click movement for a game using RTS style movement. I keep getting errors. The first issue is "Load Failed: Object reference not set to an instance of an object" - my code is below.
using UnityEngine;
using System.Collections;

public class PlayerNavigation : MonoBehaviour {

    public Camera cam;
    public NavMeshAgent navMeshAgent;

    void Start () {
        cam = Camera.main;
        navMeshAgent = GetComponent<NavMeshAgent>();
    }

    void Update () {
        if(Input.GetKeyDown  (KeyCode.Mouse0)){
            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
            RaycastHit hit;

            if(Physics.Raycast( ray, out hit)){
                navMeshAgent.SetDestination ( hit.point );
        }
    }
 }
}

My next issue, seems to be compiling error. I'm hoping fixing the above code will fix it. When I press play, it says "All compiler errors have to be fixed before you can enter playmode"
Any help would be greatly appreciated.


text:
Q: How is Starkiller Base's beam visible from Takodana in The Force Awakens? On Takodana,

 the main characters and various bar patrons can see the planet Hosnian Prime being destroyed by Starkiller Base with their (respective) naked eyes. How did they see this? Is the Hosnian system close enough to see? If it's not very close and they could just see the explosion, how did the light from it reach them so quickly?

A: This is likely among the biggest logistical problems in regard to space physics in the Star Wars film universe thus far (up there with the visibly-spinning "galaxy" at the end of Episode V).
I didn't have the benefit of the novelization's explanation at the time of my viewing; as a moviegoer, here's how I reconciled the events at the time I watched the film from a scientific perspective:
All orbs in the "Hosnian System" were so close together visibly that it strained credulity (at least for me) to think that they were all individual planets, but instead a "system" of celestial bodies that included a main planet and natural satellites within a larger star system (like how we call Jupiter and its moons the "Jovian System").  It would seem to me that the best retcon to fix this plot hole would be to have "Hosnian Prime" and its satellites lie within the same star system as Takodana.  That way, the propagation delay between its destruction and the visibility thereof from Takodana could be a matter of minutes rather than millennia.
That would be an elegant retcon that would only require the filmmakers to rewrite a map, but it appears as though the novelization's explanation (mentioned above) is the most official answer offered thus far.

A: This is explained in the film's Junior Novelisation. The super-weapon is capable of firing a beam that travels faster than light. Evidently it also creates an effect that can be seen faster than light, explaining why people in other systems can see it in realtime:

Outside the castle with Chewbacca, Han surveyed a section of
  Takodana's sky through a compact ponipin telescope. He'd heard many
  theories about the origin of the star that had recently blinked into
  existence. None made any sense. New stellar bodies didn't just
  brighten the sky all of a sudden.
Han's ponipin measured that the new star was also many, many
  light-years away, which under normal astronomical circumstances meant
  that it had actually blazed to life years before. Moreover, if the
  calculations proved correct, the stellar coordinates happened to be
  the same as those of the Hosnian system, where the capital of the New
  Republic was located.
Could the Hosnian system have gone nova? Could it—dare he even
  consider—have been destroyed? And if so, how had it happened so
  quickly?

This was confirmed in a tweet by the film's Creative Executive, Pablo Hidalgo
Apparently the explosions were...

... Some weird-ass hyperspace-rip seen-across-the-cosmos kinda shit.

A: To answer your first question: it is NOT very close at all.
TFA Visual dictionary includes a map of the Galaxy, and Takodana looks to be about 1/4 of a galaxy diameter away from Hosnian Prime (sorry, no image yet to prove that).
In-universe answer: technical mumbo-jumbo. MAYBE.
The novelization by Alan Dean Foster provides a possible explanation, from a certain point of view (the quoted paragraph was describing the operation of Starkiller weapon):

Traveling faster than anything ever generated by artificial means, through a torn portion of space-time whose properties were not fully understood, the concentrated glowing ball of energy lit the night sky above Republic City. Leia's envoy Korr Sella was among those who gazed uncomprehendingly at the inexplicable phenomenon. Disturbed space was energized and lit up by its passage. It was as if a minuscule sun had suddenly appeared from nowhere, heading directly for the world on which she stood.

So, there's a possible somewhat "lasers make sounds in a vacuum" explanation, that somehow, that "not fully understood" space-time tear managed to allow people on Takodana to see the explosion of Hosnia Prime. Despite being (according to Visual Dictionary map) not only something like a quarter of a Galaxy away, but also not even on a direct path from Starkiller to Hosnian (sorry - I don't have a digital map yet, so you'll have to trust me at my word for now).
That, or Midichlorians made them see it.
Out of universe answer:
J.J. Abrams is hiding under a table ever since I asked him that question. I overheard him mumbling something about lens flares.
There's a chance that they'll retcon that in one of 17,214 new Disney revenue sources canon books/comics/stories they planned. Always in motion, the future is.

A: It's clear that spacetime just works differently in Star Wars. The millennium falcon can jump from system to system just by jumping to light speed. So either light moves faster, time moves faster (as seen from our perspective, it explains the visibly rotating galaxy somewhat) or the Galaxy far far away is just very small.
Same can be said of other things. Putting the mass of a sun in a rocky planet?
It's a fantasy universe. There is even magic in it (the force). So trying to put it into a scientific perfection is not relevant. This is the reason the midi chlorians sucked. The force is not scientific. Nothing is Star Wars is!
Furthermore the New Order wanted people to see and fear the destruction. So the projection of that destruction in other systems could be intentional.

A: From all I can see, it's chalked up to artistic license. The systems are not so close that they would see the attack; it was shown purely for dramatic effect.

A: Because its during the day. Its a big explosion in the sky. Its night time on the other hemisphere of Takadona.

A: Happy Star Wars Day!
I think I figured it out! Bear with me here.
Blaster bolts and Death Star beams are actually not lasers, nor made of light at all, but seem to be high energy solitons (much like ball lightning) that are folded over themselves into bolts or blades or what-have-you. You can see the structure of the bolt when Kylo Ren snags one out of the air.
Now an unguided soliton can't navigate through hyperspace on it's own, but it can't get to it's target on the other side of the galaxy in anyone's lifetime  (not even Maz Kanada's) without cutting through hyperspace.
My conjecture is that there are a number of relay stations along the way with big hyperspace rings or portals that swoop up the beams and pass them along to a partner station where they blaze out. The beam leapfrogs it's way to target.
If this is true, it explains everything--why people can see it coming at them, why Finn can see a segment of it directed past the planet he's on, why Starkiller base doesn't seem to have to move its space gun around to readjust it's aim to hit different targets. It seems to fit most of the facts. It's where I'd put my betting money.


text:
Q: Calling method from inside Javascript constructor I'm trying to call a method from inside a Javascript contructor. Here's an example:
function team(team_id) {
    this.team_id = team_id;
    init();

    this.init = function () {
        alert('testing this out: ' + this.team_id);
    };
}

var my_team = new team(15);

Also: http://jsfiddle.net/N8Rxt/2/
This doesn't work. The alert is never displayed. Any ideas? Thanks.

A: You need to place your call to the init() method, underneath the definition.
Also call it using this.init();
function team(team_id) {
    this.team_id = team_id;

    this.init = function () {
        alert('testing this out: ' + this.team_id);
    };

    this.init();
}

var my_team = new team(15);

A: Prepending the call to init() with this and moving it to the end of the object helps:
function team(team_id) {
    this.team_id = team_id;

    this.init = function () {
        alert('testing this out: ' + this.team_id);
    };

    this.init();
}

var my_team = new team(15);

http://jsfiddle.net/N8Rxt/3/


text:
Q: Closing Bootstrap 2 popover I have Bootstrap 2 app that displays a SVG, when I click on any path element I get the Bootstrap 2 popover as expected.
$('body').popover
    'selector': 'path'
    'container': 'body'
    'html': true
    'width': '360px'
    'title': () ->
        item = LOOKUP[this.id]
        '' + item['device'] + '/' + item['physical_port'] + '' + '<button type="button" id="close" class="close">×</button>'
    'content': () ->
        this.id
        item = LOOKUP[this.id]
        url = '/graphs.horizon/utilisation/'+item['device']+'/'+item['physical_port']+'?layout=naked'
        ''
    'trigger': 'click'
    'placement': 'right'

So I naively add a general click event like the following:
$(document).on 'click', '.popover .close', () ->
  console.log 'hello %o', $(this).parents('.popover')
  $(this).parents('.popover').popover('hide')

However, it doesn't seem to work. I get the debug hello message, however the .popover('hide') doesn't seem to do anything except print the debug message.
In the console I also try $('.popover').popover('hide') and that doesn't do anything either but using just the selector shows a list of the div objects as I would expect.

A: this worked:
$(document).on 'click', '.popover .close', () ->
  console.log 'hello %o', $(this).parents('.popover')
  $(this).parents('.popover').hide()


text:
Q: NGINX serve static files - django project has no styling I managed to deploy my Django app but I can not pass the static files with Nginx. I have followed all the instructions for deploying to production. When I inspect the page all I see is empty static folder
Can anyone spot the mistake?
Thanks a lot
nginx.conf
 10 upstream app_upstream {
  9     server app:8080;
  8 }
  7
  6 server {
  5     listen 80;
  4     listen 443;
  1     server_name #######;
  2
  3     location /static/ {
  4         alias /static/;
  5     }
  6
  7     location /media/ {
  8         alias /media/;
  9     }
 10
 11     location / {
 12         proxy_set_header Host $host;
 13         proxy_pass http://app_upstream;
 14     }
 15 }

settings.py
14
 13 STATIC_URL = '/static/'
 12 STATIC_ROOT = '/static/'

docker-compose.yml
....
 12   app:
 13     build: .
 14     ports:
 15       - 8000:8000
 16       - 8080:8080
 17     env_file:
 18       - db_${RTE}.env
 19     volumes:
 20       - .:/app/
 21       - static:/static/
 22       - media:/media/
 23     depends_on:
 24       - db
 25
 26   nginx:
 27     build: nginx/
 28     ports:
 29       - 443:443
 30       - 80:80
 31     volumes:
 32       - ./nginx/${RTE}/conf.d/:/etc/nginx/conf.d/
 34       - static:/static/
 35       - media:/media/
 36     depends_on:
 37       - app
 38
 39 volumes:
 40   static:
...

Error message when I docker-compose:
nginx_1  | 2022/01/10 16:26:17 [error] 10#10: *8 open() "/static/custom.css" failed (2: No such--More
--More--

A: Having had a similar issue (but NOT using Docker), perhaps this might help.
If you have a static folder in your root project for project level static files, and if you also have a command to run python manage.py collectstatic --noinput in your docker-compose or Dockerfile, which not understanding Docker too well, I think you'd still need in production, then perhaps renaming the STATIC_URL and STATIC_ROOT in settings.py can help since that command will try to collect all static files from all your apps into one folder.  Try something like this:
    STATIC_URL = '/staticfiles/'
    STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles'))
    STATICFILES_DIRS = [str(BASE_DIR.joinpath('static'))]

Note that you would also have to update your Nginx file, i.e.,
    server {
            ...
            location /staticfiles/ {
            ...
           }


text:
Q: Retrieving cookies from another HTML page - link based option select firstly thanks for anyone taking the time to read this.
I've spent quite a bit of time trying to work this out for myself with little success. I have created a script to store cookies from a user input - here's a public link to what I've got so far jsfiddle .
If I wanted to retrieve the user information on another html page on the same site - what would I have to do? (I'm using cookie.js to handle the script)
Is it possible for the user to be diverted to another page based on a selection in the drop down, but still collecting the cookies.
The end result would be for - user enters personal info and selects from drop down menu, then click go - go links to a page specified by user selection on drop down menu - new page contains user info  from cookies.
FYI the .container div in the fiddle is just to test the cookies
Thanks in advance
<input id="firstName" type="text">
 <select id="service">
  <option value="plumbing">Plumbing</option>
  <option value="Handyman">Handyman</option>
  <option value="odd-jobs">Odd Jobs</option>
  <option value="electrical">Electricale</option>
 </select>

 <button id="go">go</button>

$("#go").on("click", function(e) {
name = $("#firstName").val();
service = $("#service").val();
Cookies.set('Name', name);
Cookies.set('Service', service)
var Uname = Cookies.get('Name');var Uservice = Cookies.get('Service');

$("div.container").html("
Hello " + Uname + ".

You would like to book " + Uservice + "!
");});

A: Cookies are stored by domain (or subdomain).
So the cookies you set on one page - will be available on another page of the same website.


text:
Q: Show that any direct sum of free $R$-modules is free. ($R$ has a $1$, of course.)
I have a few questions regarding my partial proof so far, as well as on how to finish the proof.
Let $\{F_i\}_{i\in I}$ be a collection of free $R$-modules.  For each $F_i$, there exists some basis $A_i= \{a_{i,j}\}_{j\in J}$. Let $A:= \bigcup_I A_i$. There is an $R$-module  $F(A)$ which is free on $A$. We may assume WLOG that  $\{F_i\}_{i\in I}$ is pairwise disjoint. (Is this true? I need it for $f$ below to be well-defined.) Define the function $f: A\rightarrow \bigoplus_I F_i$ by $a_{i,j} \mapsto (s_t)_{t\in I}$ where $s_t =1$ if $t= i$ and $0$ otherwise. By the universal property of free modules, there exists a unique $R$-module homomorphism $g: F(A)\rightarrow \bigoplus_I F_i$ defined by $\sum_{i,j=1}^{k}r_{i,j}a_{i,j} =\sum_{i,j=1}^{k} r_{i,j}f(a_{i,j})$. (I don't think I defined this correctly. Do I need a double sum over $i$ and $j$?).
Now, I want to show that $g$ is bijective. I think this should be true, but I'm really lost here in the formal technicalities. How can I do this?
(Also, as a secondary question, how does one prove that module isomorphisms preserve free-ness? I'm actually just taking it for granted right now.)
I'd appreciate some help.

A: Let me first adress the two details you ask about :

*

*When taking the direct sum $\bigoplus_I F_i$, you are not so much assuming that the $F_i$ are pairwise disjoint than considering that it is the case; by this I mean that even if some of them are really the same (for example if you have something like $R^2\oplus R^2$), you will consider them as different, and have different generators for each (so that the sum $\bigcup_I A_i$ is disjoint).

*In your definition of $g$, you should consider a sum of the form $\sum_{i\in I,j\in J_i}r_{i,j}a_{i,j}$, where all but finitely many of the $r_{i,j}$ are zero. Note that I replaced $J$ by $J_i$, because the $F_i$ could have different number of elements in their respective basis (you could very well have something like $R^2\oplus R^3$.

There is a also a problem with your definition of $f$. What you should do is define it as $f(a_{i,j})=(s_ta_{i,j})_{t\in I}$ (with the same $s_t$). This way you put every generator in the corresponding module.
Now to show bijectivity, you can do it in two steps :

*

*Injectivity : assume $g\left(\sum_{i\in I,j\in J_i}r_{i,j}a_{i,j}\right)=0$. Now
$$g\left(\sum_{i\in I,j\in J_i}r_{i,j}a_{i,j}\right)=\sum_{i\in I}\sum_{j\in J_i}r_{i,j}a_{i,j},$$where the right-hand side is seen as a sum over $i$ of elements of the form $\sum_{j\in J_i}r_{i,j}a_{i,j}\in F_i$. If this is zero, then (by definition of the direct sum) every $\sum_{j\in J_i}r_{i,j}a_{i,j}$ has to be $0$, and since every $F_i$ is free on $A_{J_i}$, every $r_{i,j}$ has to be $0$; hence $\sum_{i\in I,j\in J_i}r_{i,j}a_{i,j}=0$.

*Surjectivity : an element $y\in \bigoplus_I F_i$ must be of the form $y=\sum_i x_i$, where $x_i\in F_i$ and all but finitely many of the $x_i$ are $0$. Now in every $F_i$ we must have $x_i=\sum_{j\in J_i} r_{i,j}a_{i,j}$, again with all but finitely many of $r_{i,j}$ equal to $0$. Thus we have
$$y=\sum_{i\in I}\sum_{j\in J_i} r_{i,j}a_{i,j}=g\left(\sum_{i\in I,j\in J_i} r_{i,j}a_{i,j}\right),$$and thus $g$ is surjective.

All this being said, it is (in my opinion) easier to simply prove that the direct sum $\bigoplus_I F_i$ satisfies the universal property of free modules using the universal property of the direct sum :

For all $R$-module $M$ and all collection of $R$-module homomorphisms $f_i:F_i\to M$, there exists a unique $R$-module homomorphism $f:\bigoplus F_i\to M$ such that $f\circ \sigma_i=f_i$ for all $i\in I$ (where $\sigma_i:F_i\to \bigoplus_{t\in I} F_t$ is defined by $\sigma_i(a)=(s_ta)_{t\in I}$).

Now to prove that the direct sum is a free-module : suppose you are given $h:A\to M$, and denote by $h_i:A_i\to M$ the restrictions of $h$ to each $A_i$. Since every $F_i$ is free, you have for all $i$ a unique $R$-module homomorphism $f_i:F_i\to M$ whose restriction to $A_i$ is $h_i$, and by the universal property of the direct sum this gives you a unique homomorphism $f:\bigoplus_I F_i\to M$. Now $f$ restricted to $A$ is $h$, because every restriction to $A_i$ is given by $h_i$.


text:
Q: Need to create a delay between two effects in Wpf I am new to WPF. I am creating a animation for sample online test result. Where I like to show No of attended question, No of correct answer as animation. I need to create small delay between  AttendedQuestionEffect() and RightAnswerEffect();
CodeBehind code here
        public int TotalNoQuestion { get; set; }
        public int NoOfQuestionAttended { get; set; }
        public int NoOfRightAnswer { get; set; }

    public Window1()
    {
        InitializeComponent();

        TotalNoQuestion = 100;
        NoOfQuestionAttended = 18;
        NoOfRightAnswer = 10;

        stkpnl.Background = CreateLinearGradientBrush();

        Storyboard strBrd = new Storyboard();
        strBrd.Completed += new EventHandler(strBrd_Completed);
        DoubleAnimation myDoubleAnimation = new DoubleAnimation();
        myDoubleAnimation.From = 10;
        myDoubleAnimation.To = (TotalNoQuestion *15);
        myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(2));
        Storyboard.SetTargetName(myDoubleAnimation, stkpnl.Name);
        Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(StackPanel.HeightProperty));
        strBrd.Children.Add(myDoubleAnimation);
        strBrd.Begin(stkpnl);

    }

    void strBrd_Completed(object sender, EventArgs e)
    {

        for (int i = 1; i < TotalNoQuestion; i++)
        {
            Border brd = new Border();
            brd.BorderBrush = Brushes.Black;
            brd.BorderThickness = new Thickness(1.0);
            TextBlock txt = new TextBlock();
            txt.Text = i.ToString();
            txt.Height = 15;
            txt.Width = 200;
            brd.Child = txt;
            txt.FontSize = 12;
            txt.Foreground = Brushes.Black;
            stkpnl.Children.Add(brd);
            txt.Background = CreateLinearGradientBrush();
            txt.Tag = i.ToString();
        }

        AttendedQuestionEffect();
        // Here i need to create delay.
        RightAnswerEffect();
    }
    void AttendedQuestionEffect()
    {
        int index = 1;
        UIElementCollection ulCollection = stkpnl.Children;
        foreach (UIElement uiElement in ulCollection)
        {
            if (index <= NoOfQuestionAttended)
            {
                Border brd = (Border)uiElement;
                TextBlock txt = (TextBlock)brd.Child;
                txt.Background = BlinkEffect(Colors.Blue, Colors.SteelBlue, 3000);
                brd.Child = txt;
            }
            index++;
        }

    }

    void RightAnswerEffect()
    {
        int index = 1;
        UIElementCollection ulCollection = stkpnl.Children;
        foreach (UIElement uiElement in ulCollection)
        {
            if (index <= NoOfRightAnswer)
            {
                Border brd = (Border)uiElement;
                TextBlock txt = (TextBlock)brd.Child;
                txt.Background = BlinkEffect(Colors.Red, Colors.Blue, 1500);
                brd.Child = txt;
            }
            index++;
        }

    }

    private LinearGradientBrush CreateLinearGradientBrush()
    {
        LinearGradientBrush brush = new LinearGradientBrush();
        brush.StartPoint = new Point(0, 0);
        brush.EndPoint = new Point(1, 1);
        brush.GradientStops.Add(new GradientStop(Colors.LightCoral, 0.1));
        brush.GradientStops.Add(new GradientStop(Colors.YellowGreen, 0.35));
        brush.GradientStops.Add(new GradientStop(Colors.Yellow, 0.86));
        return brush;
    }

    private SolidColorBrush BlinkEffect(Color startColor, Color endColor,int time)
    {
        ColorAnimation myColorAnimation = new ColorAnimation();
        myColorAnimation.From = startColor;
        myColorAnimation.To = endColor;
        myColorAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(time));
        myColorAnimation.AutoReverse = true;
        myColorAnimation.RepeatBehavior = RepeatBehavior.Forever;
        SolidColorBrush myBrush = new SolidColorBrush();
        myBrush.BeginAnimation(SolidColorBrush.ColorProperty, myColorAnimation);
        return myBrush;
    }

**Xaml code here..**

<Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Border BorderBrush="Black" Grid.Column="1" BorderThickness="1" Width="200" VerticalAlignment="Bottom" HorizontalAlignment="Left">
        <StackPanel x:Name="stkpnl" Grid.Column="1" VerticalAlignment="Bottom" HorizontalAlignment="Left" Background="BlueViolet" Width="200" MaxHeight="450" >
        </StackPanel>
            </Border>
    </Grid>

`

A: Your should look up storyboard animations using KeyFrames e.g. here.
In Xaml this could look like the following ... you just have to translate it to code and adjust it to your needes:
<Storyboard>
    <DoubleAnimationUsingKeyFrames BeginTime="0:0:0" Storyboard.TargetProperty="Opacity">
        <SplineDoubleKeyFrame KeyTime="0:0:0.5" Value="0"/>
    </DoubleAnimationUsingKeyFrames>
    <ObjectAnimationUsingKeyFrames BeginTime="0:0:0.5" Storyboard.TargetProperty="Visibility">
        <DiscreteObjectKeyFrame KeyTime="0:0:0.5" Value="{x:Static Visibility.Collapsed}"/>
    </ObjectAnimationUsingKeyFrames>
</Storyboard>

This sample tfirst fades out an control and then hides it. You can ad a delay by modifying the BeginTime attribute.


text:
Q: Receiving a "module not found" and "field 'browser' doesn't contain a valid alias configuration" deploying my site to Netlify My GatsbyJS site runs fine locally but does not produce a successful build when deploying to Netlify. I've researched the error I'm receiving and haven't had any luck. Changing the case of the file name or changing the file path doesn't work.

Link to repository

A: On your local machine, run the command gatsby build will result in the error you show in the images.
You will notice the error lines:
Error: ./src/components/header.js
... Can't resolve 'components/variables.css' in ...

opt/build/repo/node_modules/components/variables.css doesn't exist

tells you it is trying to resolve the components/variables.css as a module in your project.
Solution
Change the import line for variables.css in header.js:
src/components/header.js
import styled from 'styled-components'
import 'components/variables.css'
...

to the following:
src/components/header.js
import styled from 'styled-components'
import './variables.css'
...

A: Make sure netlify knows what version of node you need to build your app.
https://www.netlify.com/docs/build-settings/#build-environment-variables
Also make sure your project is able to build from scratch. Clone the repository into a new directory and try to build it.


text:
Q: Using date and seconds from midnight columns to convert a data.frame to an xts object (R) Suppose I have data that looks like this:
        DATE  TIME   Col1   Col2
1 1993-01-04 34538 10.250 10.000
2 1994-01-05 34541 10.250 10.111
3 1997-03-16 34546 10.250 10.222
4 2017-11-10 34561 10.251 10.333
5 2001-08-28 34565 10.251 10.444
6 2006-04-20 34807 10.251 10.555

The 'TIME' column is formatted as seconds from midnight. How would I combine the 'DATE' and 'TIME' columns to get an xts object that looks something like this:
                       Col1   Col2
X1993.01.04.09.35.38 10.250 10.000
X1994.01.05.09.35.41 10.250 10.111
X1997.03.16.09.35.46 10.250 10.222
X2017.11.10.09.36.01 10.251 10.333
X2001.08.28.09.36.05 10.251 10.444
X2006.04.20.09.40.07 10.251 10.555

A: We can convert the 'DATE', 'TIME' column to Datetime class and convert the dataset to xts by specifying the order.by
library(xts)
library(lubridate)
xts(df1[-(1:2)], order.by = as.POSIXct(paste(df1$DATE,
             hms::hms(seconds_to_period(df1$TIME)))))
#                      Col1   Col2
#1993-01-04 09:35:38 10.250 10.000
#1994-01-05 09:35:41 10.250 10.111
#1997-03-16 09:35:46 10.250 10.222
#2001-08-28 09:36:05 10.251 10.444
#2006-04-20 09:40:07 10.251 10.555
#2017-11-10 09:36:01 10.251 10.333

NOTE: The index of xts needs a Datetime class object and not a formatted character class vector
data
df1 <- structure(list(DATE = c("1993-01-04", "1994-01-05", "1997-03-16",
"2017-11-10", "2001-08-28", "2006-04-20"), TIME = c(34538L, 34541L,
34546L, 34561L, 34565L, 34807L), Col1 = c(10.25, 10.25, 10.25,
10.251, 10.251, 10.251), Col2 = c(10, 10.111, 10.222, 10.333,
10.444, 10.555)), class = "data.frame", row.names = c("1", "2",
"3", "4", "5", "6"))

A: I'm not an xts officionado, but I think the first step is to convert those two columns into a POSIXt object.
as.POSIXct(dat$DATE, tz = "UTC", format = "%Y-%m-%d") + dat$TIME
# [1] "1993-01-04 09:35:38 UTC" "1994-01-05 09:35:41 UTC"
# [3] "1997-03-16 09:35:46 UTC" "2017-11-10 09:36:01 UTC"
# [5] "2001-08-28 09:36:05 UTC" "2006-04-20 09:40:07 UTC"

(BTW: assuming a "%H.%M.%S" format, I don't think you have have 36 minutes 61 seconds ... )


text:
Q: Jquery datepicker remove onclick and onchange and add default attributes When I try to create jquery-datepicker(with month and year menu) and inspect month/year menu using firebug or chrome developer tool I am getting following
<select class="ui-datepicker-year"
     onclick="DP_jQuery_1378903097959.datepicker._clickMonthYear('#dp1378903097961');"
     onchange="DP_jQuery_1378903097959.datepicker._selectMonthYear('#dp1378903097961', this,                'Y');
">

Normally when we create jquery-datepicker data should be
<select data-event="change" data-handler="selectYear" class="ui-datepicker-year">

So, problem is that those additional "onChange" and "onclick" are causing weird behavior for month and year dropdown
I tried to debug whole jquery creation of datepicker but find my self unable to understand how those attributes are getting added
Can anybody please guide me how I can remove those and add default things like data-event and data-handler ?
also I found similar question here, but I don't want to add onChange event
Thanks a lot

A: Seems like an old question but not answered. I had the same problem and used the solution here
It worked all right for me. Hope it helps.
Also I think this is tracked as a bug
But not clear which version has the fix.


text:
Q: InputAccessoryView not removed I'm making an iOS app, in which i use the inputaccessoryview to the UIViewController,
the problem is
Controller A
   class  ControllerA: UIViewController {

    override var inputAccessoryView: UIView? {
        return saveView
    }

    override var canBecomeFirstResponder: Bool {
        return true
    }

    @IBAction func openVCB(_ sender: UIButton) {

    let controllerB = controllerB.instantiate(fromAppStoryboard: .main)
        let navigationController = UINavigationController(rootViewController: controllerB)
        navigationController.navigationBar.isTranslucent = false
        self.present(navigationController, animated: true)
    }
}

Controller B
   class  ControllerB: UIViewController {

    override var inputAccessoryView: UIView? {
        return nil
    }

    override var canBecomeFirstResponder: Bool {
        return false
    }

}

in the controller A the view is working as expected, but in controller B if i opened a keyboard and closed it the AccossoryView it will be visible, and it supposed not to be visible, any ideas?
Full Project  InpoutViewTest

A: Follow this approach:
var shouldBecomeFirstResponder:Bool = false

override var canBecomeFirstResponder: Bool {
return shouldBecomeFirstResponder
}

and don't forget to set this flag to false in viewWillDisappear as well
 shouldBecomeFirstResponder = false

A: I've run into this problem too. Try putting this in your viewWillDisappear(_ animated: Bool) function:
override func viewWillDisappear(_ animated: Bool) {
   if let myInputAccessoryView = saveView {
      myInputAccessoryView.removeFromSuperview()
   }
}

It should remove the input accessory view before transitioning to controller B. Just remember to add the input accessory view back when returning to controller A. You could also try myInputAccessoryView.isHidden = true instead of removeFromSuperview() if you prefer.


text:
Q: Installing Tensorflow for Python 2.7 for Keras and CoreML conversion on Windows 10 I am currently working on an artificial neural network model with Keras for image recognition and I want to convert it using CoreML.
Unfortunately, I have been working with Python3 and CoreML only works with Python 2.7 at the moment. Moreover, Tensorflow for Python 2.7 does not seem to be supported by Windows... So my only hope is to find a way to install it.
I saw some tips using Docker Toolbox but I did not catch it and I failed when trying this solution, even though it looks like the only thing that works.
So, is there any quite simple way to install Tensorflow for Python 2.7 on Windows 10?
Thank you very much!

A: A non-optimal solution (the only one I found) in my opinion, is to install a Linux virtual machine. I used VitualBox for it.
Then, it is very easy to download Anaconda and Python 2, as well as the right versions of the packages. For example, you can download Tensorflow 1.1.0 using the following command $ pip install -I tensorflow==1.1.0.


text:
Q: index error with lists while using del, cant figure it out I am new to programming so this code is probable fairly junky. Anyhow what i am trying to do is take two lists(xy1,xy2), which hold the corners of a rectangle and see if they overlap with other rectangles. The format i used for it is x1,y1 are in array xy1 and x2,y2 are in array xy2. So far i am only working with the x axis so every other entry in both of the arrays. My problem is that when i find the ones that are overlapping and delete them i get an index error. I believe the problem is something to do with using del and my for loops max which i get using the len of the array. The code also works sometimes if nothing overlaps and triggers the removed calls. Any suggestions are appreciated. Thanks
#1,3 are x cords for first rect, 5 and 8 are x cords for second rect
xy1=[1,6,5,12,1,17]
xy2=[3,9,8,16,4,19]
def make(xy1,xy2):
    count0=0
    for count1 in range(count0,len(xy1),2):
        for count2 in range(count0,len(xy2),2):
            if xy1[count1] in range(xy1[count2],xy2[count2]) and not (count1==count2):
                xy1=removed(xy1,count1)
                xy2=removed(xy2,count1)
    return xy1,xy2

def removed(xy1,count1):
    #removes the x,y that was overlapped along with the other 2 corners of the rect
    del xy1[count1:count1+2]
    return xy1

make(xy1,xy2)

print xy1,xy2

A: Your problem is that every time you delete something, the length of your array xy1 is shrinking.  But your count iterators keep increasing without taking that into account.  You could see the behavior more clearly if you print xy1 and count1 each time right before you do del

A: Like TJD said you have an array that is shrinking so you will get an index out of range error.
Without changing your code much, you can solve this by going through the list backwards. If you change the first three lines of your procedure, you should get the result you want and no longer get an error.
def make(xy1,xy2):
count0=-1
for count1 in range(len(xy1)-2,count0,-2):
    for count2 in range(len(xy2)-2,count0,-2):
        if xy1[count1] in range(xy1[count2],xy2[count2]) and not (count1==count2):
            xy1=removed(xy1,count1)
            xy2=removed(xy2,count1)
return xy1,xy2


text:
Q: Django NoReverseMatch at /services/ 'services' is not a registered namespace I'm trying to display a group of images classified by category. When the user clicks on a category name, the page should display the images that belongs to that category. I'm getting the the next browser error:
NoReverseMatch at /services/
'services' is not a registered namespace

. . .

Error during template rendering

The models belongs to different apps, one (that contains the Category model) works fine, and this other (That contains the Services model) just works if I delete the html content that I need. Help me please.
Here are my files:
home_app/models.py
from django.db import models
from django.urls import reverse

class Category(models.Model):
    name=models.CharField(primary_key=True, max_length=50)
    slug=models.SlugField(unique=True, blank=True, null=True)
    image=models.ImageField(upload_to='category_home')
    description=models.CharField(max_length=100)
    content=models.TextField(max_length=500, default="Service")
    created=models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('services:services_by_category', args=[self.slug])

services_app/models.py
from django.db import models
from home_app.models import Category

class Services(models.Model):
    category=models.ForeignKey(Category, on_delete=models.CASCADE)
    title=models.CharField(max_length=50)
    completed=models.DateField(auto_now_add=False, null=True, blank=True)
    content=models.CharField(max_length=50, null=True, blank=True)
    image=models.ImageField(upload_to='services_services')
    created=models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Service'
        verbose_name_plural = 'Services'

    def __str__(self):
        return '%s de %s' % (self.category, self.title)

services_app/views.py
from django.shortcuts import render, get_object_or_404
from .models import Services
from home_app.models import Category

def service_list(request,category_slug=None):
    category = None
    categories = Category.objects.all()
    services = Services.objects.all()
    if category_slug:
        category = get_object_or_404(Category,slug=category_slug)
        services = services.filter(category=category)
    return render(request, 'services_app/services.html', {'categories':categories, 'category':category, 'services':services,})

services_app/urls.py
from django.urls import path
from services_app import views

urlpatterns = [
    path('', views.service_list, name='Services'),
    path('<slug:category_slug>', views.service_list, name='services_by_category'),
]

services_app/templates/services_app/services.html
    {% extends "home_app/base.html" %}
    {% load static %}
    {% block content %}

Categories

            {% for c in categories %}

{{ c.name }}

            {% endfor %}

{% if category %}{{ category.name }}{% endif %}

        {% for service in services %}

        {% endfor %}

{% endblock %}

Also my main urls:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('home_app.urls')),
    path('services/', include('services_app.urls')),
    path('contact/', include('contact_app.urls')),
]

A: Just change en models.py the following:
def get_absolute_url(self):
    return reverse('services_by_category', args=[self.slug])

'cause you have not defined the namespace services.


text:
Q: A generating function related to the Delannoy numbers What is the generating function of $f_{m,n}$?
$ f_{m,n} = \begin{cases} 0   , & \text{if $m<0 $ or $ n<0$ }; \\
 f_{n,m} ,  & \text{ if $n<m$};  \\
  1, & \text{ if $0=m$ and $ n\in\{0,1\} $};  \\
    f_{0 ,n-1}+  f_{1,n-1}, & \text{ if $0=m$ and $ n>1 $};  \\ f_{m-1 ,n}+   f_{m ,n-1}+  f_{m-1,n-1}, & \text{ if $0<m\in \{n,n-1\} $};  \\
      f_{m-1 ,n}+   f_{ m ,n-1}+  f_{m-1,n-1} +  f_{m+1,n-1},& \text{ if $0<m<n-1$}.
\end{cases}
$

A: Consider the following generating function:
$$F(x,y) := \sum_{n=0}^\infty \sum_{m=0}^n f_{m,n} x^n y^m$$
and its diagonal
$$D(z) := \sum_{n=0}^\infty f_{n,n} z^n.$$
Then the recurrence implies the following functional equation:
$$2(1-x-y-xy)F(x,y) - 2x\frac{F(x,y)-F(x,0)}y = 1 + (1-xy-2y)D(xy).$$
I'm not yet sure if it can be solved explicitly.

It's also worth to mention a couple of boundary properties for $F(x,y)$:
$$[y^1]\ F(x,y) = \left.\frac{F(x,y)-F(x,0)}y\right|_{y=0} = \frac{(1-x)F(x,0)-1}x$$
and
$$\sum_{n=1}^\infty f_{n-1,n} z^n = \frac{(1-z)D(z)-1}2.$$

ADDED. Introducing another generating function:
$$G(x,y) := F(x,\frac{y}{x}) = \sum_{n=0}^\infty \sum_{m=0}^n f_{m,n} x^{n-m} y^m$$
we get a self-contained functional equation:
$$2(y-xy-y^2-xy^2-x) G(x,xy) = y + (y-2y^2-xy^2) G(0,xy) – 2x G(x,0).$$


text:
Q: VNC client(only) in Ubuntu 18.04 headless server So basically I'm trying to setup a configuration line Qubes os but based on Ubuntu and KVM. I used Ubuntu 18.04 but it's still too heavy and I'm thinking of using headless Ubuntu for KVM installation. But problem is, most guides out there on the subject assumes setup on 2 different machines, one for server and one with VNC client to access VMs. What I want to do is to install VNC client right into headless Ubuntu server, preferably without installing any desktop env(and very minimal one if I have to). Any suggestions please?

A: you can install only libvirt-daemon-system on the server which will not pull in any UI components.
I'd assume you already have a SSH key based setup to reach your server, if not I'd set one up before the next step.
On the client install virt-manager - if you want even without recommends (as you don't want to virtualize on the client).
You now can connect the libvirt on the server as a remote via the menu "File -> Add Connection".
You can now either use virt-manager to install from an ISO, or use any other commandline tool on the server to create your initial guest. Later on you can start/stop/view that remote guest from virt-manager as needed.
I quickly checked, and while a bit dated this doc seems to cover the basics still.


text:
Q: What is the need of registering a COM component? I am a .NET developer new to COM. I'd like to know what is the need of registering a COM component? What happens during registration.

A:
In order for the OS to find a
  component when a program needs it, it
  must be registered with the system.
  The system then records it in the
  Registry.
Usually a component is registered by
  running the program REGSVR32.EXE,
  which assumes that the component has
  been properly coded to support the
  DLLRegisterServer() public method.
  Executing regsvr32.exe
   should
  respond with a dialog box indicating
  success or failure of the
  registration.

Read
Understanding COM Component Registration

A: To instantiate a COM component the consumer calls CoCreateInstance() (either directly or it is called by some wrapper class - doesn't matter) providing it two GUIDs - class id and interface id. Then COM subsystem automagically finds what library or executable to load knowing just the class id provided. To do so it uses information in the registry that is written there during component registration.
Other infromation can be written as well. So-called ProgID can be used by the consumer to discover the class id given a symbolic name. It first calls CLSIDFromProgID() to translate the ProgID to a class id, then CoCreateInstance() again. The translation is done using the information in the registry.

A: COM uses the registry to map ProgIDs and CLSIDs to your component.  This allows someone to Co-Create your COM component without needing to load your .dll manually, etc.

A: COM objects can be created from any process on the system without knowing anything more that the name of the component eg.  Word.Application .  Since the creating application doesnt have to know where the dll or exe that contains the code resides something else must.  The registry holds all this information

*

*The physical location of the file that implements the COM object.

*All the classes and Interfaces the COM object has.

*Other important information.

Without registration the calling application would need to know a lot more about where the dlls etc were, what methods they expose, how to call them etc.  Infact you might as well be calling a good old fashioned DLL.
All registration is is a few entries in the registry but it makes lots of stuff simpler.


text:
Q: How can I set Bias and change Sigmoid to ReLU function in ANN? I'm trying to create a data prediction model through artificial neural networks. The following code is part of the Python-based ANN code created through many books. Also, the error rate between the predicted value and the actual value doesn't meet below 19%. I tried to increase the number of hidden layers, but it did not tremendously affect the error rate. I think this is probably a limitation of Sigmoid function and not considering Bias. I looked around for a month and found out how to build ReLU and Bias, but I could not find the range of Bias and ReLU.
Q1 = How do I convert Sigmoid to ReLU and Q2 = how to add Bias to my code?
Q3 = Also, If I change Sigmoid to ReLU, do I have to make my dataset 0.0~1.0 range? This is because Sigmoid function accepts 0.0~1.0 range of data, but I don't know what range ReLU allows.
I'm sorry to ask an elementary question.
class neuralNetwork:
# initialize the neural network
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):

#
    self.inodes = input_nodes
    self.hnodes = hidden_nodes
    self.onodes = output_nodes

    # link weight matrices, wih and who
    self.wih = numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.hnodes, self.inodes))
    self.who = numpy.random.normal(0.0, pow(self.onodes, -0.5), (self.onodes, self.hnodes))

    # learning rate
    self.lr = learning_rate

    # activation function is the sigmoid function
    self.activation_function = lambda x: scipy.special.expit(x)

    pass

# train the neural network
def train(self, inputs_list, targets_list):
    # convert inputs list to 2d array
    inputs = numpy.array(inputs_list, ndmin=2).T
    targets = numpy.array(targets_list, ndmin=2).T

    # calculate signals into hidden layer
    hidden_inputs = numpy.dot(self.wih, inputs)
    # calculate the signals emerging from hidden layer
    hidden_outputs = self.activation_function(hidden_inputs)

    # calculate signals into final output layer
    final_inputs = numpy.dot(self.who, hidden_outputs)
    # calculate the signals emerging from final output layer
    final_outputs = self.activation_function(final_inputs)

    # output layer error is the (target - actual)
    output_errors = targets - final_outputs
    # hidden layer error is the output_errors, split by weights, recombined at hidden nodes
    hidden_errors = numpy.dot(self.who.T, output_errors)

    # update the weights for the links between the hidden and output layers
    self.who += self.lr*numpy.dot((output_errors*final_outputs*(1.0-final_outputs)), numpy.transpose(hidden_outputs))
    # update the weights for the links between the input and output layers
    self.wih += self.lr*numpy.dot((hidden_errors*hidden_outputs*(1.0-hidden_outputs)), numpy.transpose(inputs))

    pass

# query the neural network
def query(self, inputs_list) :

    inputs = numpy.array(inputs_list, ndmin=2).T

    # convert hidden list to 2d array
    hidden_inputs = numpy.dot(self.wih, inputs)
    # calculate signals into hidden layer
    hidden_outputs = self.activation_function(hidden_inputs)

    final_inputs = numpy.dot(self.who, hidden_outputs)
    final_outputs = self.activation_function(final_inputs)
    return final_outputs
    pass

A: Your question is too broad and there are lots of concept behind ReLU vs sigmoid.
But in short:
Sigmoid Saturate and kill gradients (look at Gradient descent) sigmoid are not zero centered because output of sigmoid is 0<output<1. I can see for sigmoid you are using
scipy but for ReLU its easy. Relu is defined by the following function
f(x) = max(0,x)

This means if the input is greater then zero return input else return 0. And ReLU is prefered for hidden layers and other like softmax for output layers.
I would say, look different activation function and why we need activation functions on neural net. How sigmoid kills gradients and why they slow converge.
Q1 = How do I convert Sigmoid to ReLU and Q2 = how to add Bias to my code?
simply write a method on your own based on the ReLU function above and update the following line
self.activation_function = max(0,x) # instead of lambda x: scipy.special.expit(x)

Q3 = Also, If I change Sigmoid to ReLU, do I have to make my dataset 0.0~1.0 range? This is because Sigmoid function accepts 0.0~1.0 range of data, but I don't know what range ReLU allows.
Answer of this question depends on your network and your data, but yes you normalize the data. And there is no such range that you need to make your data in. Because for ReLU: If the input is less than zero, it will return 0 and if input is >= 0, it will return the input. So no such range like in sigmoid. Answer of this question
If you wanna look at how ReLU works and can be used, following detailed example will help though these examples are written using framework (PyTorch) to build the network and train.

*

*PyTorch Basic Projects Link

*ReLU vs sigmoid vs TanH Video


text:
Q: Convert string to int in VBA SQL query I would like to import a dbf table (FoxPro) into a temporary MS Access table and copy 2 coloumns into a final one before deleting the temp one.
My code looks like this
'read all data into temp table
DoCmd.TransferDatabase acImport, "ODBC Database", DSNCONNECTIONSTRING, acTable, "BEL_PLZ", "Belegungsplaetze_Temp", False
'update table
With CurrentDb
    .Execute "INSERT INTO Belegungsplaetze (Belegungsplatznr,Bezeichnung) " & _
            "SELECT NR,BEZ FROM Belegungsplaetze_Temp t " & _
            "WHERE NOT EXISTS(SELECT 1 FROM Belegungsplaetze s " & _
            "WHERE t.NR = s.Belegungsplatznr) "
     .Execute "UPDATE Belegungsplaetze SET Belegungsplatznr = Trim([Belegungsplatznr]);"
End With

The problem I'm facing is that the field "NR" from "Belegungsplaetze_Temp" is a string and I would like to have it as an integer in my final table (final table has 2 coloumns Belegungsplatznr = Int and Bezeichnung = short text)

A: This answer's credit belongs entirely to serakfalcon, as they provide a completely valid anwser in the comments of the question.
Use the Val(NR) function to convert Text values into numbers. Microsoft documentation. And some Type Conversion Functions.


text:
Q: Invoice year format YYYY to YY I'm not able to change second year format (REPPL/20/2021/00004) ==> (REPPL/20/21/00004)
DATE_FORMAT(@dt, '%y'),(@dt+1)
when i add  DATE_FORMAT(@dt, '%y'),(@dt+1,'%y') its throwing error
PLEASE HELP THANKS
INSERT INTO sales_invoice(
invoice_no,
date_invoiced,
order_num
) SELECT
CONCAT_WS('/','REPPL',DATE_FORMAT(@dt, '%y'),(@dt +1),
    COALESCE(
        LPAD(
            CASE WHEN @dt > DATE_FORMAT(@dt, '%Y-04-01') THEN SUM(date_invoiced >
 DATE_FORMAT(@dt,'%Y-04-01')) ELSE SUM(date_invoiced BETWEEN DATE_FORMAT(@dt, '%Y-04-01') - INTERVAL
 1 YEAR AND DATE_FORMAT(@dt, '%Y-04-01'))END +1,5,0),LPAD(1, 5, 0))),@dt,"132132"FROM sales_invoice;

A: Well you are just passing @dt +1 You are not formatting it at all. You need to add DATE_FORMAT for each argument in CONCAT, not just first, first will format first one only, the first ()...
Try this, add one year interval and then format:
DATE_FORMAT(DATE_ADD(@dt, INTERVAL 1 YEAR), '%y')

Example:
CONCAT_WS('/','REPPL',DATE_FORMAT(@dt, '%y'),DATE_FORMAT(DATE_ADD(@dt, INTERVAL 1 YEAR), '%y')),

FIDDLE:
**Schema (MySQL v5.7)**

---

**Query #1**

    select CONCAT_WS('/','REPPL',DATE_FORMAT('2020/08/16', '%y'),DATE_FORMAT(DATE_ADD('2020/08/16', INTERVAL 1 YEAR), '%y')) AS ConcatenatedString;

| ConcatenatedString |
| ------------------ |
| REPPL/20/21        |

---

View on DB Fiddle


text:
Q: Do I need to protect data structures on iPhone from callbacks and timers? Do I need mutexes to protect my data structures across UI related callbacks and timer events?

A: What's accessing your data structures from cocoa touch?  If you set data for a view, it's retained there and it's own copy is used.  You really only have to worry about your own code.

A: All UI-related callbacks are on the main thread. Threads generated by UIKit and other iOS frameworks are generally hidden from the caller. As long as you don't generate threads of your own, you will seldom need to worry about this kind of locking when developing for iOS.


text:
Q: Android Support Library v7 missing appcompat So when I import the Android Support Library v7 (appcompat JAR), I see that I get a noclassdeferror when trying to use it. This is because the package android.support.v7.appcompat is not being found as it is not even there in appCompat.JAR. I confirmed this by extracting the contents of the JAR file. I tried reinstalling the JAR with SDK Manager, however I am missing the same package every time. Can someone tell me what's going wrong?
Thanks

A: You have to import the appcompat library in to your project...please check the following link for getting how to setup appcompat in your project..
https://developer.android.com/tools/support-library/setup.html
thank you

A: Also had this problem.  Yes, I knew I need to use the SDK Manager dialog to download the support library from the extras folder, as per the Support Library Set-up link, but it wasn't listed there - there is only the "support repository".
The problem is that it is hidden by default, as it has been deprecated.  You need to check the "show: obsolete" checkbox. And then it's available to download.

A: You need to import support
dependencies {
    ...
    implementation "com.android.support:support-core-utils:28.0.0"
}


text:
Q: Conceptual data model for a billing system I am working on an existing MySQL database. My task is to create a new data model for a billing system on that existing application.
I have created a conceptual data model (click to enlarge):

##Requirements

*

*Multiple Payment types (such as Recurring, One-time, Instalment).

*Multiple Payment modes (cash, cheque, internet banking).

*Contract between Vendors (Company) and our company (Marketing executive)

*Vendor can add amounts to their accounts by recharging from their page (similar to prepaid recharge).

*Different packages are used, depending on the packages. Vendor total balance will be divided by the value of (package value / 365).

*If balance becomes 0, they will not use their service, such as the following:
set  t1 = package_value / 365
if
total_balance / t1 > 0
set
        service = active
else
set
        service = inactive

##SQL Code
use database_name;
/*==============================================================*/
/* table: company_account                                       */
/*==============================================================*/
create table company_account
(
   account_id           int not null auto_increment,
   company_id           int not null,
   date_created         date not null default now(),
   date_replaced        date not null default '9999-12-31',
   created_by           int not null,
   is_active            bit(1) default 1,
   primary key (account_id)
);

/*==============================================================*/
/* table: contract                                              */
/*==============================================================*/

create table contract
(
   contract_id          int not null auto_increment,
   account_id           int not null,
   contract_number      int(6) not null default '0',
   contract_date        date not null default '9999-12-31',
   initial_payment      float(5,2) not null default '0.00',
   date_created         date not null default now(),
   date_effective       date not null default '9999-12-31',
   date_replaced        date not null default '9999-12-31',
   created_by           int not null,
   is_active            bit(1) default 1,
   primary key (contract_id)
);

/*==============================================================*/
/* table: packages                                              */
/*==============================================================*/
create table packages
(
   package_id           int not null,
   package_name         varchar(30) not null default "No Packages Selected",
   package_value        float(5,2) not null default '0',
   date_created         date not null default now(),
   date_replaced        date not null default '9999-12-31',
   created_by           int not null,
   is_active            bit(1) not null default 1,
   primary key (package_id)
);

/*==============================================================*/
/* table: payment_mode                                          */
/*==============================================================*/
create table payment_mode
(
   payment_mode_id      int not null,
   payment_mode         varchar(30) not null default "No Mode Selected",
   description          varchar(100) not null default "No Description Available",
   date_created         date not null default now(),
   date_replaced        date not null default '9999-12-31',
   created_by           int not null,
   is_active            bit(1) not null default 1,
   primary key (payment_mode_id)
);

/*==============================================================*/
/* table: payment_status                                        */
/*==============================================================*/
create table payment_status
(
   payment_status_id    int not null,
   payment_status       varchar(30) not null default "No Status Selected",
   description          varchar(100) not null default "No Description Available",
   date_created         date not null default now(),
   date_replaced        date not null default '9999-12-31',
   created_by           int not null,
   is_active            bit(1) not null default 1,
   primary key (payment_status_id)
);

/*==============================================================*/
/* table: payment_type                                          */
/*==============================================================*/
create table payment_type
(
   payment_type_id      int not null auto_increment,
   payment_type         varchar(30) not null default "No Type Selected",
   decription           varchar(100) not null default " No Description Available",
   date_created         date not null default now(),
   date_replaced        date not null default '9999-12-31',
   created_by           int not null,
   is_active            bit(1) not null default 1,
   primary key (payment_type_id)
);

/*==============================================================*/
/* table: payments                                              */
/*==============================================================*/

create table payments
(
   payment_id           int not null auto_increment,
   payment_type_id      int not null,
   payment_mode_id      int not null,
   payment_status_id    int not null,
   package_id           int not null,
   contract_id          int not null,
   payment_date_time    timestamp not null default current_timestamp,
   payment_amount       float(5,2) not null default '0.00',
   date_created         date not null default now(),
   date_replaced        date not null default '9999-12-31',
   created_by           int not null,
   is_active            bit(1) not null default 1,
   primary key (payment_id)
);

/*==============================================================*/
/* table: transaction                                           */
/*==============================================================*/
create table transactions
(
   transaction_id       int not null,
   payment_id           int not null,
   transaction_number   char(15) not null default '000000000000000',
   date_created         date not null default now(),
   date_replaced        date not null default '9999-12-31',
   created_by           int not null,
   is_active            bit(1) not null default 1,
   primary key (transaction_id, payment_id)
);

/*==============================================================*/
/* table: vendor_invoice                                        */
/*==============================================================*/
create table vendor_invoice
(
   invoice_id           int not null auto_increment,
   transaction_id       int not null,
   payment_id           int not null,
   invoice_date_time    timestamp not null default current_timestamp,
   date_created         date not null default now(),
   date_replaced        date not null default '9999-12-31',
   created_by           int not null,
   is_active            bit(1) not null default 1,
   primary key (invoice_id, transaction_id, payment_id)
);

/*==============================================================*/
/* table: vendor_basket                                         */
/*==============================================================*/
create table vendor_basket
(
   v_basket_id          int not null,
   account_id           int not null,
   date_created         date not null default now(),
   date_replaced        date not null default '9999-12-31',
   created_by           int not null,
   is_active            bit(1) not null default 1,
   primary key (v_basket_id, account_id)
);

/*==============================================================*/
/* table: payment_basket                                        */
/*==============================================================*/
create table payment_basket
(
   basket_id            int not null,
   v_basket_id          int not null,
   account_id           int not null,
   last_credited_value  float(5,2) not null default '0',
   last_credited_date   date not null default '9999-12-31',
   amount_utilized      float(5,2) not null default '0.00',
   total_balance        float(5,2) not null default '0.00',
   days_remaining       smallint not null default '0',
   date_created         date not null default now(),
   date_replaced        date not null default '9999-12-31',
   created_by           int not null,
   is_active            bit(1) not null default 1,
   primary key (basket_id)
);

alter table company_account
add constraint fk_company_account
foreign key (company_id)
references company (company_id)
on delete restrict
on update restrict;

alter table contract
add constraint fk_company_contract
foreign key (account_id)
references company_account (account_id)
on delete restrict
on update restrict;

alter table payment
add constraint fk_contract_payment
foreign key (contract_id)
references contract (contract_id)
on delete restrict
on update restrict;

alter table payment
add constraint fk_payment_mode
foreign key (payment_mode_id)
references payment_mode (payment_mode_id)
on delete restrict
on update restrict;

alter table payment
add constraint fk_payment_packages
foreign key (package_id)
references packages (package_id)
on delete restrict
on update restrict;

alter table payment
add constraint fk_payment_status
foreign key (payment_status_id)
references payment_status (payment_status_id)
on delete restrict
on update restrict;

alter table payment
add constraint fk_payment_type
foreign key (payment_type_id)
references payment_type (payment_type_id)
on delete restrict
on update restrict;

alter table payment_basket
add constraint fk_company_paymaent_basket
foreign key (v_basket_id, account_id)
references vendor_basket (v_basket_id, account_id)
on delete restrict
on update restrict;

alter table transactions
add constraint fk_payment_transaction
foreign key (payment_id)
references payment (payment_id)
on delete restrict
on update restrict;

alter table user
add constraint fk_user_company
foreign key (company_id)
references company (company_id)
on delete restrict
on update restrict;

alter table vendor_basket
add constraint fk_company_basket
foreign key (account_id)
references company_account (account_id)
on delete restrict
on update restrict;

alter table vendor_invoice
add constraint fk_transaction_invoice
foreign key (transaction_id, payment_id)
references transactions (transaction_id, payment_id)
on delete restrict
on update restrict;

Note: I have skipped some tables already present in the existing database.
##Questions

*

*How to perform calculations on the records without using external programming languages?

*How to set the logic in stored procedures, while inserting and updating the payment_basket table?

*Does my conceptual data model satisfy my requirements?

*What are things required for me (DBA - beginner) to implement these kinds of tasks in the future?

I am a beginner, so some references will be useful.

A: I'm probably stating the obvious but you are missing a lot of foreign keys from the Payment table (ContractID, PaymentTypeID, PaymentModeID, PaymentStatusID, PackageID) and avoid putting the actual text/values in the Payment table which slows the response of the database.


text:
Q: Плывёт вёрстка сцены есть код который запускается при открытии формы логина и при логауте
public static void showLoginScene(){
    primaryStage.setMinWidth(400);
    primaryStage.setMinHeight(300);
    primaryStage.setWidth(400);
    primaryStage.setHeight(300);
    Scene scene = new Scene(new LoginStage(primaryStage),400,300);
    primaryStage.setScene(scene);
    primaryStage.show();
}

Собственно проблема в том, что при запуске программы форма отображается по центру как и нужно. Далее сцена меняется на 600*800 и там показывается другая сцена. А при нажатии логаута снова вызывается этот метод. Размер окна меняется на нужные 400*300 но панель логина центрируется так, как будто она всё ещё 800*600. Если потянуть окно для ресайза всё снова перерисовывается корректно. Есть предположение, то установка размера primaryStage не устанавливает размер сразу, и нужен какой-то метод перерисовки. Подскажите как пофиксить.

A: Нашел в чём была проблема. При получении панели у меня для неё ставился padding, и это каким-то образом всё ломало. Не очень понимаю почему внутренний отступ портит расположение самой панели, но это так.


text:
Q: How to call an outside function from button in cell I use a main class call newsFeedCointroller as UICollectionViewController.
1. In cell inside I have a newsfeed with a like button (to populate the cell I use a class called "FeedCell")
2. Out from cells (in mainview) I have a label (labelX) used for "splash message" with a function called "messageAnimated"
How can I call the "messageAnimated" function from the button inside the cells.
I want to to change the label text to for example: "you just liked it"...
Thanks for helping me

A: In your FeedCell you should declare a delegate (Read about delegate pattern here)
protocol FeedCellDelegate {
    func didClickButtonLikeInFeedCell(cell: FeedCell)
}

In your cell implementation (suppose that you add target manually)
var delegate: FeedCellDelegate?

override func awakeFromNib() {
    self.likeButton.addTarget(self, action: #selector(FeedCell.onClickButtonLike(_:)), forControlEvents: .TouchUpInside)
}

func onClickButtonLike(sender: UIButton) {
        self.delegate?.didClickButtonLikeInFeedCell(self)
}

In your View controller
extension FeedViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("feedCell", forIndexPath: indexPath) as! FeedCell
        // Do your setup.
        // ...
        // Then here, set the delegate
        cell.delegate = self
        return cell
    }

    // I don't care about other delegate functions, it's up to you.
}

extension FeedViewController: FeedCellDelegate {
    func didClickButtonLikeInFeedCell(cell: FeedCell) {
        // Do whatever you want to do when click the like button.
        let indexPath = collectionView.indexPathForCell(cell)
        print("Button like clicked from cell with indexPath \(indexPath)")
        messageAnimated()
    }
}


text:
Q: 'Unprecedented achievement': who received the first billion COVID vaccinations? The use of "who" appears to be odd to me. According to the content, it seems to mean "the people around the world."  What does "who" mean exactly?

'Unprecedented achievement': who received the first billion COVID vaccinations?
It took just four months to reach this global milestone, and hitting to the two-billion mark could happen even faster, say scientists.
The world has reached the milestone of administering one billion doses of COVID-19 vaccines, just four months after the World Health Organization (WHO) approved the first vaccine for emergency use, and roll-outs began in countries such as the United States and the United Kingdom. The speed at which they have been administered is remarkable, but unequal distribution of the vaccinations highlights global disparities, say researchers.

Source:  Nature

A: Since the vaccine requires two doses to be effective, it means it's around half as many people that have been vaccinated around the world.
From the article:

As of 27 April, 1.06 billion doses had been given to 570 million people, which means that about 7.3% of the world's population of 7.79 billion have received at least one dose.


text:
Q: Need Help Configuring NSTimer and UIButton I have the following code for a stopwatch function.
I have 2 UIButtons. One is for start/stop, the other is for reset.
I want to combine these 2 into just 1 button, that functions as a start button, then while the timer is running, it will be a stop button, that when pushed, resets the timer.
How can I modify this code to reflect this?
- (IBAction)startStop:(UIButton *)sender
{
    if ( self.myTimer )
    {
        [self.myTimer invalidate];
        self.myTimer = nil;

        [sender setTitle:@"Start" forState:UIControlStateNormal];
    }
    else
    {
        self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES];
        [sender setTitle:@"Stop" forState:UIControlStateNormal];
    }
}

- (void)handleTimer:(NSTimer *)timer
{
    self.counter--;
    self.timerLabel.text = [NSString stringWithFormat:@"%ld", self.counter];

    if ( self.counter <= 0 )
    {
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        [self.myTimer invalidate];
        self.myTimer = nil;
        self.timerButton.enabled = NO;
    }
}

- (IBAction)reset:(id)sender
{
    self.timerButton.enabled = YES;
    self.counter = self.counterSegment;
    self.timerLabel.text = timerCount;
    self.timerButton.titleLabel.text = @"Start";
    self.timerButton.titleLabel.adjustsFontSizeToFitWidth = YES;
}
- (void)segmentedControl:(SVSegmentedControl*)segmentedControl didSelectIndex:(NSUInteger)index
{
    if ( self.myTimer )
    {
        [self.myTimer invalidate];
        self.myTimer = nil;
        self.timerButton.titleLabel.text = @"Start";
        self.timerButton.titleLabel.adjustsFontSizeToFitWidth = YES;
    }
    else
    {
        self.timerButton.enabled = YES;
        self.counter = self.counterSegment;
        self.timerLabel.text = timerCount;
        self.timerButton.titleLabel.text = @"Start";
        self.timerButton.titleLabel.adjustsFontSizeToFitWidth = YES;
    }
    if (index == 0)
    {
        NSLog(@"15 sec");
        self.timerCount = @"15";
        self.counterSegment = 15;
    }
    else if (index == 1)
    {
        NSLog(@"30 sec");
        self.timerCount = @"30";
        self.counterSegment = 30;
    }
}

A: Steps you could do:

*

*remove the reset button from you UI;

*modify the startStop method so that when pressed while the timer is already running, it will send a reset message to itself:
I think it should be enough. Have a look at this code:
- (IBAction)startStop:(UIButton *)sender
{
if ( self.myTimer )
{
    [self.myTimer invalidate];
    self.myTimer = nil;

    [self reset:sender];   //-- LINE ADDED

    [sender setTitle:@"Start" forState:UIControlStateNormal];
}
else
{
    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES];
    [sender setTitle:@"Stop" forState:UIControlStateNormal];
}
}

Since in reset you are not using the sender argument, you can remove it and have:
- (void)reset
{
self.timerButton.enabled = YES;
self.counter = self.counterSegment;
self.timerLabel.text = timerCount;
self.timerButton.titleLabel.text = @"Start";
self.timerButton.titleLabel.adjustsFontSizeToFitWidth = YES;
}

In this way you will be able to use this method in a more generic way.


text:
Q: I am trying to install psycopg2 in windows and getting error I am firing following command and it's showing the same for psycopg2-binary
(demo) C:\Users\Lenovo\Desktop\Django>pip install psycopg2
Collecting psycopg2
  Using cached psycopg2-2.8.6.tar.gz (383 kB)
    ERROR: Command errored out with exit status 1:
     command: 'c:\users\lenovo\desktop\django\demo\scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-pq1_j08j\\psycopg2\\setup.py'"'"'; __file__='"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-pq1_j08j\\psycopg2\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Lenovo\AppData\Local\Temp\pip-pip-egg-info-a33qt0v5'
         cwd: C:\Users\Lenovo\AppData\Local\Temp\pip-install-pq1_j08j\psycopg2\
    Complete output (23 lines):
    running egg_info
    creating C:\Users\Lenovo\AppData\Local\Temp\pip-pip-egg-info-a33qt0v5\psycopg2.egg-info
    writing C:\Users\Lenovo\AppData\Local\Temp\pip-pip-egg-info-a33qt0v5\psycopg2.egg-info\PKG-INFO
    writing dependency_links to C:\Users\Lenovo\AppData\Local\Temp\pip-pip-egg-info-a33qt0v5\psycopg2.egg-info\dependency_links.txt
    writing top-level names to C:\Users\Lenovo\AppData\Local\Temp\pip-pip-egg-info-a33qt0v5\psycopg2.egg-info\top_level.txt
    writing manifest file 'C:\Users\Lenovo\AppData\Local\Temp\pip-pip-egg-info-a33qt0v5\psycopg2.egg-info\SOURCES.txt'

    Error: pg_config executable not found.

    pg_config is required to build psycopg2 from source.  Please add the directory
    containing pg_config to the $PATH or specify the full executable path with the
    option:

        python setup.py build_ext --pg-config /path/to/pg_config build ...

    or with the pg_config option in 'setup.cfg'.

    If you prefer to avoid building psycopg2 from source, please install the PyPI
    'psycopg2-binary' package instead.

    For further information please check the 'doc/src/install.rst' file (also at
    <https://www.psycopg.org/docs/install.html>).

    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

A: Maybe this will help(pip install psycopg2). As I understand, there is kind of answer (pg_config executable not found).Maybe I'm wrong (99% guarantee, that I'm wrong, just because I'm new one in programming).


text:
Q: Задание: Нужно разработать приложение, которое будет обрабатывать Excel таблицу, а после вычислять корреляцию
*

*Создал форму

*расположил на ней menuStrip и в меню кнопку открыть

*написал алгоритм выбора и обработки Excel таблицы(код ниже)

*надо написать алгоритм для кнопки, который будет вычислять корреляцию полученных данных из Excel таблицы

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using OfficeOpenXml;
namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        private double[,] excelTable;
        private int totalRows = 0;
        private int totalColumns = 0;
        public Form1()
        {

            InitializeComponent();
        }

        private void открытьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult res = openFileDialog1.ShowDialog();

                if (res == DialogResult.OK)
                {
                    ExcelPackage excelFile = new ExcelPackage(new FileInfo(openFileDialog1.FileName));

                    ExcelWorksheet worksheet = excelFile.Workbook.Worksheets[1];
                    totalRows = worksheet.Dimension.End.Row;
                    totalColumns = worksheet.Dimension.End.Column;
                    excelTable = new double[totalRows, totalColumns];
                    for (int rowIndex = 1; rowIndex <= totalRows; rowIndex++)
                    {
                        IEnumerable<string> row = worksheet.Cells[rowIndex, 1, rowIndex, totalColumns].Select(c => c.Value == null ? string.Empty : c.Value.ToString());
                        List<string> list = row.ToList<string>();

                        for (int i = 0; i < list.Count; i++)
                        {
                            excelTable[rowIndex - 1, i] = Convert.ToDouble(list[i].Replace('-', ','));

                        }
                    }
                    for (int i = 0; i < totalRows; i++)
                    {
                        for(int j = 0; j < totalColumns; j++)
                        {
                            richTextBox1.Text += Convert.ToString(excelTable[i, j]) + "     ";

                        }
                        richTextBox1.Text += "\n";
                    }
                }
                else
                {
                    throw new Exception("Файл не выбран");
                }

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }

этот код считывает данные таблицы.


text:
Q: How to retrieve child controls in Xamarin StackLayout `
<StackLayout
                        x:Name="xGrpTabBtns"
                        Grid.Row="0"
                        HorizontalOptions="StartAndExpand"
                        Orientation="Horizontal"
                        Spacing="0">

                        <!--#region Tab Button Gerneral-->
                        <Grid ColumnSpacing="0" RowSpacing="0">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*" />
                                <RowDefinition Height="1" />
                            </Grid.RowDefinitions>

                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="1" />
                            </Grid.ColumnDefinitions>

                            <controls:CtrlButton
                                Grid.Row="0"
                                Grid.Column="0"
                                BorderColor="Transparent"
                                BorderRadius="0"
                                BorderWidth="0"
                                Clicked="BtnTabBtnClicked"
                                Style="{StaticResource GuoupStyle}"
                                Text="Gerneral"
                                WidthRequest="180" />

                            <!--#region Bottom-->
                            <BoxView
                                x:Name="xBtnGerneralBotBorder"
                                Grid.Row="1"
                                Grid.Column="0"
                                Grid.ColumnSpan="2"
                                BackgroundColor="{StaticResource ColorBorder000}" />
                            <!--  Endregion  -->

                            <!--#region Right-->
                            <BoxView
                                Grid.Row="0"
                                Grid.RowSpan="2"
                                Grid.Column="1"
                                BackgroundColor="{StaticResource ColorBorder000}" />
                            <!--  Endregion  -->

                        </Grid>
                        <!--#endregion-->

                        <!--#region Tab Button Information-->
                        <Grid ColumnSpacing="0" RowSpacing="0">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*" />
                                <RowDefinition Height="1" />
                            </Grid.RowDefinitions>

                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="1" />
                            </Grid.ColumnDefinitions>

                            <controls:CtrlButton
                                Grid.Row="0"
                                Grid.Column="0"
                                BorderColor="Transparent"
                                BorderRadius="0"
                                BorderWidth="0"
                                Clicked="BtnTabBtnClicked"
                                Style="{StaticResource GuoupStyle}"
                                Text="Information"
                                WidthRequest="180" />

                            <!--#region Bottom-->
                            <BoxView
                                x:Name="xBtnInformBotBorder"
                                Grid.Row="1"
                                Grid.Column="0"
                                Grid.ColumnSpan="2"
                                BackgroundColor="{StaticResource ColorBorder000}" />
                            <!--  Endregion  -->

                            <!--#region Right-->
                            <BoxView
                                Grid.Row="0"
                                Grid.RowSpan="2"
                                Grid.Column="1"
                                BackgroundColor="{StaticResource ColorBorder000}" />
                            <!--  Endregion  -->

                        </Grid>
                        <!--#endregion-->
                    </StackLayout>

`
I want to retrieve a CtrlButton from the grid.
var buttons = this.xGrpTabBtns.Children.Where(x => x is CtrlButton);
I used it like this, but I couldn't get the button to work.
Is there a way to get all the CtrlButtons inside a stack layout?
var buttons = this.xGrpTabBtns.Children.Where(x => x is CtrlButton);
I tried this, but it was null.
The effect I was expecting is to get all the CtrlButtons inside the Stacklayout.

A: Just as Jason said, your buttons are children of the Grid, and the Grid is a child of the StackLayout.
You can get the Button with following code:
        var children = this.xGrpTabBtns.Children.Where(x => x is Grid);

        foreach (var child in children) {
            if (child is Grid) {
                var grid = (Grid)child;

                var inerChildren = grid.Children.Where(x => x is Button);
                foreach (var innerchild in inerChildren) {

                    if (innerchild is Button) {

                       System.Diagnostics.Debug.WriteLine("find one button here " + ((Button)innerchild).Text);

                    }
                }
            }
        }