text:
Q: In mlflow, is it possible to track an artifact without having mlflow store it separately? I am new to mlflow. I am trying to track/log some artifacts (a directory of images output by my model) such that they are affiliated with the run that generated them, and so that I can view them in the mlflow UI along with all the other tracked information.
This directory of images is generated in a custom folder path location (with a unique identifier for each run). My goal is to point mlflow to this directory so that it can recognize that these images are artifacts to track.
Is this possible? From my understanding, the mlflow.log_artifact() function will simply create a duplicate of this image and store it within mlflow's default artifact path (ie, something like mydrive1/mlflow/0//artifacts/). I do not want to create a duplicate; I want to keep these images where I originally saved them.
Example of file tree:
mydrive1/
--/train.py
--/mlflow/
----/0/
------/meta.yaml
------/[random char sequence]
--------/artifacts/
--------/meta.yaml
mydrive2/
--/output/
----/my_experiment0/
------/images/
--------/image1.png
--------/image2.png
I have found that if I manually edit the artifact_uri variable (in the meta.yaml file of the relevant run) to point to the relevant directory of images (ie, mydrive2/my_experiment0/images/), all those images will show up in the artifact viewer in the mlflow UI. Is there a way to edit the artifact_uri variable via the mlflow API (or some other principled way)?


text:
Q: getHeight for View which has visibility=gone I have a LinearLayout whose visibility is set to "Gone" by default,
I need to get the height of this view to do a slide-out animation when it will be visible.
How do i get the total heigh of the visible state, because the
View.getHeight returns zero when the layout is not called.
<LinearLayout
    android:id="@+id/card_checkin_layout_termsconditionsconfirmation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="4dp"
    android:gravity="center_horizontal"
    android:background="#d0d0d0"
    android:visibility="invisible"
    android:orientation="vertical" >

    <Button
        android:id="@+id/card_checkin_button_confirmdetails"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:background="@drawable/shape_checkin_buttons2"
        android:text=">   Confirm your details"
        android:paddingLeft="8dp"
        android:gravity="left|center_vertical"
        android:textColor="@color/card_checkin_button_textcolor_blue"
        />

    <Button
        android:id="@+id/card_checkin_button_termsandconditions"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:paddingLeft="8dp"
        android:background="@drawable/shape_checkin_buttons2"
        android:text=">   Terms and Conditions"
        android:gravity="left|center_vertical"
        android:textColor="@color/card_checkin_button_textcolor_blue"
        />

</LinearLayout>

A: Initially set the visibility of the view to be visible or invisible to start with, so that the height is calculated. Later change the visibility to gone.
FYI : removeGlobalOnLayoutListener() is deprecated since API level 16, it's replaced by removeOnGlobalLayoutListener().
You can try this:
// onCreate or onResume or onStart ...
mView = findViewByID(R.id.someID);
mView.getViewTreeObserver().addOnGlobalLayoutListener(
    new OnGlobalLayoutListener(){

        @Override
        public void onGlobalLayout() {
            // gets called after layout has been done but before display
            // so we can get the height then hide the view

            mHeight = mView.getHeight();

            mView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            mView.setVisibility(View.GONE);
        }

});

redpajama_set_name: RedPajamaStackExchange


text:
Q: In Python using multiprocessing pipe to share data between 2 process. But after some data is transmitted the data transmission is halt why? def send(parent_proc):
    serialPort = serial.Serial(port='COM4', baudrate=1000000, bytesize=8, timeout= 1)
    while True:
        data_string = serialPort.readline()
        parent_proc.send(data_string)
def recv():
    global child_proc
    a = child_proc.recv()
    print(a)
if __name__ == "__main__":
   child_proc, parent_proc = Pipe()
    send_th = Process(target=send,args=[parent_proc,])
    send_th.start()
    recv_th = threading.Thread(target=recv,args=[])
    recv_th.start()

#for the above code i receive data for sometime and later data receiving will be paused. I'm new to multiprocessing please help. Thank u


text:
Q: GroupLayout error: can't find the wrong line in my code I'm trying to make a GroupLayout, but every time I compile I get errors. I can't find the wrong line in my code, it seems to me to be correct. Why do I get these errors?
The code in the constructor (extends JFrame):
mem_settings = new JPanel();

    lbl_mem_settings = new JLabel("Memory settings");
    lbl_mem_select = new JLabel("Type");
    cb_mem_select = new JComboBox(new String[] {"24C01","24C02","24C04"});

    // Layout
    GroupLayout GL = new GroupLayout(mem_settings);
    mem_settings.setLayout(GL);
    GL.setAutoCreateGaps(true);
    GL.setAutoCreateContainerGaps(true);

    GL.setHorizontalGroup(GL.createSequentialGroup()
        .addGroup(GL.createParallelGroup(LEADING)
            .addComponent(lbl_mem_settings)
            .addComponent(lbl_mem_select))
        .addGroup(GL.createParallelGroup(LEADING)
            .addComponent(cb_mem_select))
    );
    GL.setVerticalGroup(GL.createSequentialGroup()
        .addGroup(GL.createParallelGroup(BASELINE)
            .addComponent(lbl_mem_settings))
        .addGroup(GL.createParallelGroup(BASELINE)
            .addComponent(lbl_mem_settings)
            .addComponent(cb_mem_select))
    );

    add(mem_settings);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    pack();
    setVisible(true);

and the error I get:
run:
Exception in thread "main" java.lang.IllegalStateException: javax.swing.JLabel[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=8388608,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=Type,verticalAlignment=CENTER,verticalTextPosition=CENTER] is not attached to a vertical group
    at javax.swing.GroupLayout.checkComponents(GroupLayout.java:1090)
    at javax.swing.GroupLayout.prepare(GroupLayout.java:1040)
    at javax.swing.GroupLayout.preferredLayoutSize(GroupLayout.java:878)
    at java.awt.Container.preferredSize(Container.java:1794)
    at java.awt.Container.getPreferredSize(Container.java:1778)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1661)
    at java.awt.BorderLayout.preferredLayoutSize(BorderLayout.java:719)
    at java.awt.Container.preferredSize(Container.java:1794)
    at java.awt.Container.getPreferredSize(Container.java:1778)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1661)
    at javax.swing.JRootPane$RootLayout.preferredLayoutSize(JRootPane.java:920)
    at java.awt.Container.preferredSize(Container.java:1794)
    at java.awt.Container.getPreferredSize(Container.java:1778)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1661)
    at java.awt.BorderLayout.preferredLayoutSize(BorderLayout.java:719)
    at java.awt.Container.preferredSize(Container.java:1794)
    at java.awt.Container.getPreferredSize(Container.java:1778)
    at java.awt.Window.pack(Window.java:809)
    at memcryp.GUI.<init>(GUI.java:46)
    at memcryp.MEMCRYP.main(MEMCRYP.java:20)
BUILD STOPPED (total time: 6 minutes 39 seconds)

A: The error message is clear though. Your JLabel called lbl_mem_select is only attached to a horizontal group:
GL.setHorizontalGroup(GL.createSequentialGroup()
        .addGroup(GL.createParallelGroup(LEADING)
            .addComponent(lbl_mem_settings)
            .addComponent(lbl_mem_select)) //here you attach the label
        .addGroup(GL.createParallelGroup(LEADING)
            .addComponent(cb_mem_select))
    );

However, in your vertical group you did not include the label. Changing the code for the vertical group to
GL.setVerticalGroup(GL.createSequentialGroup()
        .addGroup(GL.createParallelGroup(BASELINE)
            .addComponent(lbl_mem_settings)
            .addComponent(lbl_mem_select)) //add this line
        .addGroup(GL.createParallelGroup(BASELINE)
            .addComponent(lbl_mem_settings)
            .addComponent(cb_mem_select))
    );

should do it.
That being said ... do you really want to use the GroupLayout to hand-code a UI. A quote from the GroupLayout tutorial

GroupLayout is a layout manager that was developed for GUI builders such as Matisse, the GUI builder provided with the NetBeans IDE

While it is possible to hand-code a layout with it, it requires quite a lot of (unreadable imho) code to do it. There are other (third party) layout managers which are better suited for handcoding a layout.


text:
Q: Recuperar valor em localstorage Boa tarde! Estou criando uma aplicação em JavaScript utilizando localstorage para o armazenamento de dados. A aplicação é simples, estou apenas praticando alguns conceitos, e nela envolve alguns dados pessoais e um campo composto de 10 números como identificação única, gerada ao cadastrar. O que estou com dificuldades em criar é uma função que busque por essa identificação única em meio aos dados salvos no localstorage.
function pesquisarAluno(){
let matriculas = Array()
let id = localStorage.getItem('id')
for(let i = 1; i <= id; i++){
    let recuperar_matricula = JSON.parse(localStorage.getItem(i))
    if(recuperar_matricula === null){
        continue
    }
    recuperar_matricula.id = i
    matriculas.push(recuperar_matricula)
}
console.log(matriculas)

}

A: Para se trabalhar com Storage você precisa definir seu no seu Storage os dados e em seguida poderá recuperar os dados.
para se definir um local Storage você pode fazer como abaixo:
localStorage.setItem("alunos", JSON.stringify(DADOS));

para recuperar você pode utilizar
localStorage.getItem("alunos")

sua pergunta não foi bem definida, tenta descrever melhor seu problema.
um exemplo de um código de trabalho com storage, eu apliquei dentro de um arquivo html para ter condições de executar em um navegador.
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0"
 />
 <title>Document</title>
</head>
<body>
<script>
  // defino um array de obetos
  const alunos = [
    {
      id: 1,
      nome: "Fulano de Tal Tal Tal",
    },
    {
      id: 2,
      nome: "Beltrado de Tal Tal Tal",
    },
    {
      id: 3,
      nome: "Melano de Tal Tal Tal",
    },
  ];

  // defino o storage
  const defineStorage = () => {
    localStorage.setItem("alunos", JSON.stringify(alunos));
  };

  // executo a função
  defineStorage();

  // defino uma função de recuperação do storage
  const recebeStorage = () => {
    return JSON.parse(localStorage.getItem("alunos"));
  };
  // converto em um array para trabalhar com map, filter ou outros ajudadores dos arrays
  const storage = Array.from(recebeStorage());

  // função para filtro
  const id = (id) => id.id === 2;

  // aplicando a função e imprimindo no console
  console.log(storage.filter(id));

</script>


text: Q: why to use getDerivedStateFromProps and shouldComponentUpdate why to use getDerivedStateFromProps and shouldComponentUpdate ? Both serves the same purpose restrict user from re-rendering the component on conditional basis so why React gives two functions for this


text:
Q: Regex to match multitple conditions in sentence I need a regular expression to match ${xyz} in a sentence. I tried this expression \$\{[^\s]+\} it worked for me. But I have more scenario like the  matching word(${xyz}) should not have space in it and it should not be like this ${xyz and $xyz} and ${xy z} .
Accept

*

*Hi ${xyz}, Thanks for your visit.

Not accept

*

*Hi ${xy z}, Thanks for your visit.

*Hi ${xyz }, Thanks for your visit.

*Hi ${xyz, Thanks for your visit.

*Hi $xyz}, Thanks for your visit.

*Hi {xyz}, Thanks for your visit.
Note : It should match the entire sentence.

A: [\s]*([^.!?]*\$\{[^\s]+\}[^.!?]*[.!?])

A group match of the above regex will give you the sentence, without any leading space characters.
I have matched a sentence by checking for strings that end with characters ".","!" or "?".
You can check the meaning of the regex here


text:
Q: Performances on rails I have a problem of performances with rails. When i do an ajax call to a controller like this :
def test
    @hotels = Hotel.all
    render :json => ['hotels' => @hotels ], :include=> [:country, :city]
end

It takes maybe 2-5 seconds to finish. I only have 40 hotels in my database. I think it very long... for example, the same request on Django will take 400ms
Did i forgot to configure well my environement?
I use Rails entreprise version and passenger.
EDIT : My log file :
     Started GET "/hotels/test.json" for 172.16.81.1 at Wed Oct 12 22:11:06 +0200 2011
    [paperclip] Duplicate URL for image with /system/:attachment/:id/:style/:filename. This will clash with attachment defined in HotelImage class
    [paperclip] Duplicate URL for thumbnail with /system/:attachment/:id/:style/:filename. This will clash with attachment defined in Hotel class
    [paperclip] Duplicate URL for map with /system/:attachment/:id/:style/:filename. This will clash with attachment defined in Hotel class
    [paperclip] Duplicate URL for thumbnail with /system/:attachment/:id/:style/:filename. This will clash with attachment defined in DestinationAlbumPhoto class
    [paperclip] Duplicate URL for map with /system/:attachment/:id/:style/:filename. This will clash with attachment defined in Destination class
    [paperclip] Duplicate URL for image with /system/:attachment/:id/:style/:filename. This will clash with attachment defined in Continent class
    [paperclip] Duplicate URL for thumbnail with /system/:attachment/:id/:style/:filename. This will clash with attachment defined in Destination class
    [paperclip] Duplicate URL for image with /system/:attachment/:id/:style/:filename. This will clash with attachment defined in Event class
    [paperclip] Duplicate URL for thumbnail with /system/:attachment/:id/:style/:filename. This will clash with attachment defined in HotelAlbumPhoto class
    [paperclip] Duplicate URL for map with /system/:attachment/:id/:style/:filename. This will clash with attachment defined in Event class
      Processing by HotelController#test as JSON
      [1m[36mHotel Load (0.2ms)[0m  [1mSELECT `hotels`.* FROM `hotels`[0m
      [1m[35mCountry Load (0.1ms)[0m  SELECT `countries`.* FROM `countries` WHERE (`countries`.`id` = 3)
      [1m[36mCity Load (0.1ms)[0m  [1mSELECT `cities`.* FROM `cities` WHERE (`cities`.`id` = 2)[0m
    Completed 200 OK in 405ms (Views: 366.1ms | ActiveRecord: 0.3ms)

It's writen 405ms but firefox tell me 3,7sec.
My hotel model :
class Hotel < ActiveRecord::Base
  cattr_reader :per_page
  @@per_page = 16

  belongs_to :hotel_type
  belongs_to :hotel_theme
  belongs_to :country
  belongs_to :city
  belongs_to :destination
  belongs_to :continent

  has_many :hotel_comments, :dependent => :destroy

  has_many :hotel_album_photos, :dependent => :destroy

  has_many :hotel_activity_values

  has_many :hotel_service_values

  accepts_nested_attributes_for :hotel_album_photos

  has_attached_file :thumbnail, :styles => { :medium => "300x300>", :thumb => "191x134>"} , :default_url => '/images/default/missing.png'
  has_attached_file :map, :styles => { :medium => "300x300>", :thumb => "191x134>"} , :default_url => '/images/default/missing.png'

  scope :country, lambda { |country_id|
     self.scoped.where('country_id IN ( ? )', country_id) unless country_id.blank?
  }

  scope :selection, lambda { |selection|
     self.scoped.where('selection = ? ', 1) unless selection.blank?
  }

  scope :city, lambda { |city_id|
      self.scoped.where('city_id IN ( ? )', city_id) unless city_id.blank?
  }

  scope :hoteltype, lambda { |type|
      self.scoped.where('hotel_type_id IN ( ? )', type) unless type.blank?
   }

  scope :theme, lambda { |theme|
      self.scoped.where('hotel_theme_id IN ( ? )', theme) unless theme.blank?
   }

  scope :prices, lambda { |prices|
      condition = []
      prices.each do |price|
        pricesArray = price.split('-')
        condition.push '(price BETWEEN ' + pricesArray[0] + ' AND ' + pricesArray[1] + ')'
      end
      self.scoped.where(condition.join(' OR '))
   }

   scope :order_by_price, lambda { |direction|
     self.scoped.order('price ' + direction)
   }

   scope :order_by_rate, lambda { |rate|
     self.scoped.order('global_rate ' + rate)
   }

   scope :services, lambda { |services|
      {:joins => [:hotel_service_values ]  , :conditions => { :hotel_service_values => {:hotel_service_id  => services}}}
   }

  scope :limiter, lambda { |limiter|
      self.scoped.limit(limiter)
   }

end

Thank you for help.

A: Looking at you code, my guess is you have a simple "N+1" problem.
Namely you load @hotels into an array, but when you come to produce the json
you load the country and cityfor eachhotel.
So for your 40 hotels, you have to do a total of 81 database queries.
This can simply be improved by doing an include when you load.
In the old style
Hotel.all(:include => [:country, :city])

In Rails 3 style
Hotel.includes(:country, :city).all

With this change you should only be making 3 database calls in total.
See the Rails Guide on Eager Loading for more info.

A: Looking at the Log, Rails seems to be thinking it got the response out in 405 ms. This leaves rest of the stack to consider:

*

*Rails (✓)

*Passenger

*Apache

*Network

*DNS resolving

*Browser rendering

First, see how other browsers fare. I have seen occasional issues on one of our (non-rails) sites with Firefox, while Webkit-based browsers (Safari, Chrome) are OK. Maybe Firefox chokes up for some reason (e.g. DNS resolving issues or something other).
If all browsers are the same (or especially, if Firefox is the culprit), then open Firebug and take look at the Net tab, especially the XHR (AJAX) tab under that. Hover your mouse over one of the queries' time bar to see breakdown of where the time went: DNS, Connecting, Sending, Waiting, Receiving.
If Firebug indicates that the time is spent on the request itself (Sending, Waiting, Receiving), then take a look at Apache log - turn on CustomLog time reporting (add %D - see documentation) and see how long Apache thinks these requests take.
This should narrow down your problem to further analyze causes.

A: I was using VMWare to make my web server running. My performances problems was about that. I find my solution here :
Webrick is very slow to respond. How to speed it up?


text:
Q: Git pull origin master issues and local repository Running
git pull origin master

outputs
fatal: 'origin' does not appear to be a git repository
fatal: The remote end hung up unexpectedly.

I've tried running
git remote add origin username@host:/var/www/public/git-test/.git
git pull origin master

and it seemed to work, but it output Already up-to-date and the file was not updated; committing and pushing from my localhost was successfull, though.
The .git files and the file I am trying to update are in the same directory and I have no bare repository, if that matters.
Why wasn't the file updated?
Am I doing git remote add origin correctly? Is there a way to add this repository as local?

A: when adding a remote, don't put the ".git" directory in the url. Add you remote origin like this:
git remote add origin username@host:/var/www/public/git-test/

A: Found the answer in git force push current working directory.

*

*manually perform a git checkout -f to update the working dir

*make a git post-receive hook to do it automatically.

To add local repository to git:
git add remote origin /var/www/public/git/test


text:
Q: Stop or break window snapping to left or right with another window When I have a window on the left, using Windows+← and I use my mouse or keyboard to snap another window to the right it joins the two windows at the centre.  Now moving the centre resizes both windows.  How do I stop that? I want them to be independent so I can overlap the windows slightly.

A: When you have the 2 windows left and right, grab the top title bar of the left window and drag it to the right and back to the left.  It will now be bigger and the its right edge will no longer be connected to the left edge of the second window.  At this point either window can be made wider without affecting the other.

A: It's tedious, but there is a workaround:

*

*Super+→ (move right within group)

*Super+→ (maximize)

*Super+→ (create new group)

*Super+← (move left within group)

Indeed it would still be preferable to prevent grouping in the first place.


text:
Q: Let $X$ be a finite set such that for all $x \in X$, $x$ is finite. Then, $\bigcup X$ is finite. Let $X$ be a finite set such that for all $x \in X$, $x$ is finite. Then, $\bigcup X$ is finite.
We define the natural numbers $\omega$ as $0 = \emptyset, 1 = \{0\}, 2 = \{0,1 \}, n = \{0,1,...,n-1\}$.
I'm with difficult to formalize this argument. My attempt:
By hypothesis, exists a bijection between $X$ and some natural number $n \in \omega$. Then, $X = \{ x_0,...,x_{n-1} \}$. Besides this, for each $i \in n$, exists some $m_i \in \omega$ such that $x_i = \{ x_i^{0},..., x_i^{m_i-1} \}$.
Since $y \in \bigcup X \iff \exists x \in X, \, y \in x$,
$$ y \in \bigcup X \iff \exists i \in n, \exists j \in m_i, \, y = x_i^{j}. $$
Hence, $\bigcup X = \{ x_i^{j}: \, i \in n,  j \in m_i  \}$.
How can I define a bijection from $\bigcup X$ and some $m \in \omega$?
Thank you!

A: $X$ is a finite set means it has $N$ elements $x_1,...,x_N$ for some integer $N$. Each $x_k\in X$ is finite means each $x_k$ has $n_k$ elements, where $n_k$ is some integer for each $k$. Let $M=\max_{k\in\{1,...,N\}}n_k$. Then $\cup X$ has at most $NM$ elements.

A: Without loss of generality, assume the elements of $X$ are disjoint. Let $m = \max \{m_0,...,m_{n-1}\}$. Then for each $i\in n$, there exists an injective $f_i: x_i\to m$. It would suffice to find an injection $g: \bigcup X \to nm$. In fact, given $x\in x_i \in X$, let $g(x) = im+f_i(x)$. Can you show that $g$ is injective?


text:
Q: BFS traversal on multi-way trees? I've seen samples, codes and references on bfs, however, all of them seems to focus on traversing through binary trees. I want to know if bfs traversal is possible for multi-way trees, if so where can I find coding references for it?

A: if you clearly understand how BFS works, it doesn't matter what kind of tree (or graph more specifically) you are dealing with, you can always find a way.
if you are really not clear with how to do BFS in multy-nodes tree, here is my pseudocode for you:
     Queue queue; // a de-queue typed data-structure.
     queue.add(root); // root of the tree.

     while -> queue is not empty() :  // traversed untill queue become empty

          tempNode := queue.peek();   // process the peeked item from queue
              queue.pop();

          process -> tempNode.item;

          while -> tempNode.childnode is not null:
                   queue.add(tempNode.childnode)
                   tempNode := tempNode.childnode;

          end of while;

     end of while;

A: Indeed, I searched too, and bfs aren't focus in multi-way trees.
But, references on bfs with graph exists. Because multi-way trees are a subset of graphs, you may find your happiness there.

A: BFS is indeed a traversal that is not specific for binary trees, but can be used on any graph. Wikipedia has an entry on Breadth-first search, and it even offers pseudo code that is intended to work with any graph.

Input: A graph G and a starting vertex root of G
Output: Goal state. The parent links trace the shortest path back to
root
 1  procedure BFS(G, root) is
 2      let Q be a queue
 3      label root as discovered
 4      Q.enqueue(root)
 5      while Q is not empty do
 6          v := Q.dequeue()
 7          if v is the goal then
 8              return v
 9          for all edges from v to w in G.adjacentEdges(v) do
10              if w is not labeled as discovered then
11                  label w as discovered
12                  Q.enqueue(w)


text:
Q: Lost space in tag hover popup There was a space between the actual number and the text "followers" in tag hover popup. The poor space character is now gone. Is that intentional?
Current popup:

A: Some localization code went wonky and was collapsing the space when it shouldn't have.
I blame him:

Fixed.


text:
Q: wxPython - Manually resizing panels with unexpected/undesired visual results I'm working on my own alternative for the wx.Sizer class which allows me to basically treat the interface like a table (or more accurately, a series of nested tables).
Basically, there are two parts to it-- my names for them make more sense in the context of the problem, so we'll just call them sections and cells.
A section is basically a column OR a row, depending on how it is oriented, and the cells are the items in said column or row.  It has its own definitions for margins, alignment, and spacing between cells, and rules for how the cells are to be sized.  A section can be a frame, a panel, or just a logical construct.  A cell can itself be a a section, with its own orientation, alignment, margins, and spacing, or just a panel, button, etc.  A cell can override the sizing or the alignment of the section.
Functionally it goes like this:

*

*Frame resizes, wx.EVT_SIZE triggers the adjust() function.

*At the frame level, "adjust" pulls GetClientSize() and does the math using those numbers.

*adjust() uses the size to determine the size and placement of its cells, then calls adjust() on those cells, providing the size and position for those cells to be.

*if the cell is a panel, adjust() will resize and reposition the panel accordingly.

*If the cell is also a section, adjust() will repeat step 3, using the provided numbers, and invoking adjust() on its own cells.

And it works.  Well, mostly.  For example:

The above consists of:

*

*a horizontally aligned section/frame (black background)

*a vertically aligned section/panel (grey) with three panel/cells (blue, white, and red)

*a vertically aligned section/panel (grey) with four panel/cells (blue, white, white, and red)

And everything is exactly where and how I want it.  And if I resize it, everything will stay exactly how and where I want it.
Except.
Sometimes I get a weird thing.

That little white bar in the blue bar should NOT be there.  (The grey line at the top of column A is unwanted, but I know why it's there.)
It doesn't seem to happen consistently, and it only happens when increasing the size, usually rapidly.  This includes (sometimes) maximizing the window.  Unfortunately, once it happens, the error remains when it is resized until it's sized small enough that the part with the glitch goes away.
That is just the example I got for that screenshot-- sometimes it's a bar, sometimes it's lines. (The lines are usually white (assuming from the panel) but ocassionally black (frame background).

A: Solved it.
The adjust() function now calls Refresh() on the panels it's adjusting.  (This marking the first time Refresh() has helped me with anything I've tried it on.)


text:
Q: Laravel domain routes Is there any specific benefit or reason one might have specified domain in routes file?
Route::group(['domain' => iConfig::get('session.my_domain')], function () {...

Instead of omitting it completely?
I am working on an app which is already live and I am wondering if I might break something on live server if I remove this group?
There are also subdomain routes present.

A: Route::domain (Used in Laravel 5.4)or Route::group(['domain' => 'xyz.com'])? are is used when you have a sub domain which can be either dynamic or statc for example:
Route::domain('{account}.myapp.com')->group(function () {
    Route::get('user/{id}', function ($account, $id) {
    //
    });
});


text:
Q: ¿Como sincronizar las bases de datos de mysql en varios ordenadores? En mi caso tengo un servidor principal con 3 bases de datos: bdA, bdB, bdC. Después tengo 3 servidores secundarios: sA, sB, sC.
El servidor sA solo tiene la bdA y solo debe sincronizarse con esta. Los cambios del sA deben verse reflejados en la bdA del servidor principal de igual forma que los cambios realizados en la bdA del servidor principal deben reflejarse en el sA. Del mismo modo el sB solo debe sincronizarse con la base de datos bdB y el sC solo debe sincronizarse con la base de datos bdC.
Es posible utilizar la replicación circular del mysql para este fin? Si no es así hay alguna otra forma de lograr este objetivo?
Gracias


text:
Q: How to setup webpack for @import ~stylus in vue component? I try to import my variables.stylus in my vue component, but when i use @import "~@themes/variables.stylus", webpack throw error: failed to locate @import file ~@themes/variables.stylus.styl
webpack config
alias: {
      'vue$': 'vue/dist/vue.esm.js',
       themes: path.resolve(__dirname, './src/themes'),
       '@': resolve('src'),
 }

 {
     test: /\.styl$/,
     loader: ['style-loader', 'css-loader', 'autoprefixer-loader?browsers=last 5 version', 'stylus-loader']
 }

A: I believe it should be like this:
@import '~@/themes/variables.stylus';

Webpack replaces the alias @ with the path you have in the configuration, in this case src. So the import becomes src/themes/variables.stylus.


text:
Q: How does Apple notify iOS apps of refunds of in-app purchases (IAP)? I have Apple iOS IAP successfully implemented in my app and tested in the sandbox. Works great.
I'm concerned that users could buy something with IAP, download it into my app, then complain to Apple and get a refund. There's no obvious way that refunds are reported to my app. Are they simply left out of the list of products I receive during a "restore" operation? Is there some undocumented transaction type that will asynchronously show up in my SKPaymentTransactionObserver when a refund occurs?
Right now I'm operating on the assumption that I need to delete the user's IAP transactions before doing a restore, and that anything refunded will just not be in the list of restored transactions. Is this the right way to do it? Is there any way to test this in the sandbox?
Has anyone seen refunds in a production environment and can explain how they work?

A: The strategy is:

*

*You save the latest_receipt ("MIIUJgYJKoZIhvc..." base64) field in your DB, associated with the user account.

*Every day you query apple to validate all the receipts, by sending them the base64 receipt from saved latest_receipt field.

*In the receipt you check if there is a cancellation_date field. If you find it, treat it according to documentation:

Treat a canceled receipt the same as if no purchase had ever been made.

Same way you also checking subscription renewals (check expires_date_ms field).

A: Refunds are given, but your app gets no notification of them at all. Whether it's an In-App Purchase, an app download or any other iTunes content, the user can still use the content even if they have asked for a refund.

A: In iOS 14 a new method is added to the SKPaymentTransactionObserver protocol that is called when the user is no longer entitled to one or more in-app purchases  https://developer.apple.com/documentation/storekit/skpaymenttransactionobserver/3564804-paymentqueue
Although the documentation doesn't tell in which situation this method is called, Apple does tell this in this WWDC2020 video at 26:55  https://developer.apple.com/videos/play/wwdc2020/10661/

A: Update June 24, 2020:
At WWDC 2020, a new notification was introduced that informs you of refunds: https://developer.apple.com/documentation/storekit/in-app_purchase/handling_refund_notifications

Original answer:
I received a response from Apple Developer Relations today (Dec 6, 2018):

Hello Johannes,
In response to your question, unfortunately, there is no supported means to detect that the user has contacted Apple Care and received a refund for the In-App Purchase of a consumable item. The only option which I can refer you to is to submit an API enhancement request for an API to be made available for an app to detect that a refund was provided to a user of an In-App Purchase. Currently, this support is realistically only available to apps which offer auto-renewable subscription In-App Purchase.
You can submit the enhancement request using the Apple Developer Bug Report web page - http//bugreport.apple.com
As this is an enhancement request type issue, I'm going to arrange for this incident to be unbilled from your account for use on a future issue.

So there we have it.

A: The in-app purchasing guide discusses the concept of "cancellation" of subscriptions. This is the only place I've seen discussing the subject.
Further details about the cancellation date field can also be found in the App Store receipt validation documentation.
cancellation_date

After decoding a receipt, you can get the cancellation date which will tell you the following:

For a transaction that was canceled by Apple customer support, the time and date of the cancellation.

A: According to latest documentation, server to server notification with type CANCEL is now handling cancel scenario by Apple customer support.

A: Starting October 21, 2021, App Store Server Notification Version 2 became available and the notificationType in the notification payload will be returned with REFUND when the App Store refund process is completed.
See below for more information.
https://developer.apple.com/documentation/appstoreservernotifications/app_store_server_notifications_v2


text:
Q: How to create a pop up contact form that return success message in the place of the send button? I have HTML pop up a contact form that I need help with to return a success message on the page or in the place of the send button.

   <form id="myForm" action="action_page.php" method="post" enctype="multipart/form-data" class="form-container">

Contact

      <input type="text" placeholder="Name" name="name" required>
      <input type="text" placeholder="Email" name="email" required>
      <textarea rows="4" cols="33.5" placeholder="Your message..." name="message" required tabindex="35"></textarea>
      <button type="submit" class="btn">Send</button>
      <button type="button" class="btn cancel" onclick="closeForm()">Close</button>
   </form>

  <?php
    $name = $_POST['Name'];
    $email = $_POST['Email'];
    $message = $_POST['Message'];
    $from = 'From: mywebsite.com';
    $to = 'sk@gmail.com';
    $subject = 'Message from MyWebsite';

    $headers = 'From: mywebsite.com' . "\r\n" .
    'Reply-To: ' . $email . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

    $body = "Name: $name\n Email: $email\n Message:\n $message";

?>

//please refer to my PHP code below that communicates with my HTML file.
currently after PHP submits my form it redirects to the homepage. I want

it to stay on same page and display Message sent Successfully in the send button.
<?php
if ($_POST['submit']) {
    if (mail ($to, $subject, $body, $headers)) {

        header("Location: http://www.mywebsite.com");

    } else {
        echo '
Oops! An error occurred. Try sending your message again.
';
    }
}
?>

A: This solution requies JQuery to run!

$('#myForm').submit(function(e){
//DO YOUR STUFF
e.preventDefault()//Remove this line if you want to submit the form
$('#send').hide();
$('.success').show();
});

        <form id="myForm" action="action_page.php" method="post" enctype="multipart/form-data" class="form-container">

Contact

        <input type="text" placeholder="Name" name="name" required>
        <input type="text" placeholder="Email" name="email" required>
        <textarea rows="4" cols="33.5" placeholder="Your message..." name="message" required tabindex="35"></textarea>

      SUCCESS MESSAGE

      <button type="submit" class="btn" id="send">Send</button>
      <button type="button" class="btn cancel" onclick="closeForm()">Close</button>

UPDATE for author:

        <form id="myForm" action="action_page.php" method="post" enctype="multipart/form-data" class="form-container">

Contact

        <input type="text" placeholder="Name" name="name" required>
        <input type="text" placeholder="Email" name="email" required>
        <textarea rows="4" cols="33.5" placeholder="Your message..." name="message" required tabindex="35"></textarea>

  SUCCESS MESSAGE

  <button type="submit" class="btn" id="send">Send</button>
  <button type="button" class="btn cancel" onclick="closeForm()">Close</button>

A: You should place php code above html and check if the request is POST or GET. the header("Location: http://www.mywebsite.com"); is redirecting to the home page. Instead of that create the variable that storing message(success or error) and if the request is POST show it on your form

<?php
$showMsg = false;
if ($_POST['submit']) {
    $name = $_POST['Name'];
    $email = $_POST['Email'];
    $message = $_POST['Message'];
    $from = 'From: mywebsite.com';
    $to = 'sk@gmail.com';
    $subject = 'Message from MyWebsite';

    $headers = 'From: mywebsite.com' . "\r\n" .
    'Reply-To: ' . $email . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

    $body = "Name: $name\n Email: $email\n Message:\n $message";
   if (mail ($to, $subject, $body, $headers)) {

    $showMsg = "SUCCESS";

 } else {
     $showMsg = "ERROR";
    }
 }

?>

   <form id="myForm" action="action_page.php" method="post" enctype="multipart/form-data" class="form-container">

Contact

      <input type="text" placeholder="Name" name="name" required>
      <input type="text" placeholder="Email" name="email" required>
      <textarea rows="4" cols="33.5" placeholder="Your message..." name="message" required tabindex="35"></textarea>
 <?php if( $showMsg) {?>
     <?= $showMsg ?>
 <?php } else { ?>
      <button type="submit" name="submit" class="btn">Send</button>
 <?php } ?>
      <button type="button" class="btn cancel" onclick="closeForm()">Close</button>
   </form>


text:
Q: C# enumeration property null vs. 0 I'm using IIS/asmx to support a Flash client.  Some of my service layer data transfer objects have properties that are enumeration values.  There are cases where these properties should be null.
When an object with a null value for such an enumeration property is rendered to soap, I receive this error:
System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: Instance validation error: '0' is not a valid value for NameSpaceX.Model.NodeType.
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write1_NodeType(NodeType v)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write4_PackageDTO(String n, String ns, PackageDTO o, Boolean isNullable, Boolean needType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write15_ArrayOfPackageDTO(Object o)
   at Microsoft.Xml.Serialization.GeneratedAssembly.ListOfPackageDTOSerializer1.Serialize(Object objectToSerialize, XmlSerializationWriter writer)
   at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
   at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)
   at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
   at System.Web.Services.Protocols.XmlReturnWriter.Write(HttpResponse response, Stream outputStream, Object returnValue)
   at System.Web.Services.Protocols.HttpServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream)
   at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues)
   at System.Web.Services.Protocols.WebServiceHandler.Invoke()

Is there a better solution then to create an enumeration member with value 0 (e.g. [0, "null"]?  I suspect that I'm lacking basic knowledge here.
Thanks.

A: My first inclination was to point you to the Nullable<T> type.  However, after looking around for documentation on Nullable<T> and SOAP, it appears that it might not be supported.  You might want to explore this further.
That said, it is very common for Enums to declare a NotSet = 0 member.


text:
Q: Efficient way to change a 3d map to point cloud matlab I have a 3d map or matrix and I want to construct the point cloud from it. I've already done that using this code:
function [pcloud, distance] = depthToCloud(depth, topleft)
% depthToCloud.m - Convert depth image into 3D point cloud
% Author: Liefeng Bo and Kevin Lai
%
% Input:
% depth - the depth image
% topleft - the position of the top-left corner of depth in the original depth image. Assumes depth is uncropped if this is not provided
%
% Output:
% pcloud - the point cloud, where each channel is the x, y, and z euclidean coordinates respectively. Missing values are NaN.
% distance - euclidean distance from the sensor to each point
%

if nargin < 2
    topleft = [1 1];
end

depth= double(depth);
depth(depth == 0) = nan;

% RGB-D camera constants
center = [320 240];
[imh, imw] = size(depth);
constant = 570.3;
MM_PER_M = 1000;

% convert depth image to 3d point clouds
pcloud = zeros(imh,imw,3);
xgrid = ones(imh,1)*(1:imw) + (topleft(1)-1) - center(1);
ygrid = (1:imh)'*ones(1,imw) + (topleft(2)-1) - center(2);
pcloud(:,:,1) = xgrid.*depth/constant/MM_PER_M;
pcloud(:,:,2) = ygrid.*depth/constant/MM_PER_M;
pcloud(:,:,3) = depth/MM_PER_M;
%distance = sqrt(sum(pcloud.^2,3));

but I'm asking if there is any more efficient way?
Also after constructing the point cloud I want to get the normal of each point and I used the built-in matlab function surfnorm but its takes a lot of processing time. So if anyone could assist me do this a better and more efficient way.


text:
Q: How do I only set a state variable in a Store if it has not already been set? I am using Hyperstack Stores and in the before_mount of my component I want to do:
before_mount do
  BridgeStore.show_card_sample ||= true
end

And in the store:
class BridgeStore < HyperStore
  class << self
    state_accessor :show_card_sample
  end
end

But the conditional assignment ||= is being triggered each time a component of this type is rendered.
I know I can get around this by setting a state variable in the store state_accessor :is_set and only set the other variables if that has not been set, but I was wondering if there is a better way round this?

A: You should move the logic around initialization into your store.  Remember that in Ruby your class instance variables can be initialized as the class is defined:
class BridgeStore < HyperStore
  @show_card_sample = true
  class << self
    state_accessor :show_card_sample
  end
end


text:
Q: A Sentence in Lost Series I was watching Lost (again) yesterday and someone said:
" - Well, then. I guess I won't have to convince you after all."
" - I'm not going to kill -spoiler-, Ben. You are."
My question is: I was expecting the end of the sentence not with a "You are", but with "You will". Why they say "You are"? Is "You will" incorrect?
Thanks!

A: The quote, if you take out the contraction is:

I am not going to kill -spoiler-, Ben. You are.

This is correct and idiomatic.
It's echoing... am --- are
If it had read:

I will not kill -spoiler-, Ben.

Then it would read:

You will.


text:
Q: List of Dictionary to List of another Dictionary I have a huge list of Dictionary like
List<Dictionary<String,SomeType>> Dict = new List<Dictionary<string,SomeType>>();

I need to convert to the list of dictionary of some other type like below:
List<Dictionary<String,SomeOtherType>> AnotherDict;

Is there a better approach than foreach on the 'Dict' List.

A: Yes, you can use LINQ:
AnotherDict = Dict.Select(d => d.ToDictionary(pair => pair.Key,
                                              pair => Convert(pair.Value)))
                  .ToList();

Where Convert is whatever conversion you want to apply to SomeType to construct a SomeOtherType.
EDIT: As noted in comments, this is no more efficient than using nested foreach loops yourselves. It's just simpler.


text:
Q: onLoad IBAction SubmitB i got a problem... i have a button.. when i click on the button, the function
-(IBAction)SubmitB;
{
        self.String = textdata.text;
        NSString *nameString = String;

        NSString* AUrl = [NSString stringWithFormat:@"%@", nameString];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:AUrl]];

}

will be activate.
It sounds dump... but i want to activate it without pressing the button... in this example you click on a button and the textfield sends the data to the String variable... but he have to send the data if the app is loaded
Thanks

A: ... well from what I understand, why don't you put your code into didFinishLaunchingWithOptions? Something like:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    NSString *nameString = @"whatever";

    NSString* AUrl = [NSString stringWithFormat:@"%@", nameString];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:AUrl]];
}


text:
Q: Calculating the difference between two fields within a table in Django I have a model which stores the opening and closing balances of a petrol station. I have an additional third column which is basically the difference between the opening and reading values.
class DailySales(models.Model):
    PUMP_NAMES = (
    ...
    )
    Pump_name = models.CharField(max_length = 5, choices = PUMP_NAMES)
    Opening_reading = models.IntegerField()
    Closing_reading = models.IntegerField()
    Gross_sales = models.IntegerField(null = True)
    Date = models.DateField(auto_now_add= True)

    def Calc_gross(self):
        self.Gross_sales = self.Opening_reading - self.Closing_reading
        super(DailySales,self).save()

the Calc_gross method works when i'm saving only one instance at a time.
But i want to add multiple opening and closing values to the model at once for which i'm using formsets.
SalesForm = modelformset_factory(DailySales, extra = 7, exclude=('Date','Gross_sales'))

This is where the logic falters. Django isnt able to calculate the gross values for each row.
Exception Value:

'list' object has no attribute 'Calc_gross'

I was thinking since its a list , I could iterate over each and invoke the Calc_gross method. What will be the name of the list?
Is there a better way to do this? Would it be logical to use Prefixes (how would u assign a prefix to each form?)

A: Turns out i could just loop over the formset.
if request.method == 'POST':
        sale_Form = SalesForm(data = request.POST)
    for Form in sale_Form:

        if Form.is_valid():

            gross = Form.save()

            gross.Calc_gross()
            gross.save()
        else:
            print(sale_Form.errors)


text:
Q: Symmetricds : solution synchronization from MySQL Slave DB to SQL Server DB? I have 2 node
node master : connect to MySQL Slave
node client : connect to SQL Server
Is there a solution to use symmetricds for synchronization from MySQL Slave DB to SQL Server DB ?


text:
Q: What distinguished the Möbius strip from the cylinder as fibre bundles? I'm a physicist trying to understand fibre bundles, and I think I'm pretty happy with the wikipedia definition "a space that is locally a product space, but globally may have a different topological structure". I think I also have a grasp, in the general and tangent cases, on the different objects in the fibre bundle: $(E, \pi, M, F, G)$ taken singularly and abstractly. However, I'm having trouble seeking what tells apart two fibre bundles $E$, the Möbius strip and the cylinder. Both have base $M=S^1$ and fibre $F=$ (a segment), so what's different in the two of them? Is it the projection $\pi$, the structure group $G$ or maybe trivially just the total space $E$?

A: The cylinder, as a fiber bundle, has a section which is never zero.
On the moebius band, such a section does not exist: if you parametrize the segment $F$, which is the fiber, with $(-1,1)$, then if a never-vanishing section starts positive, after one turn it becomes negative.
In terms of fiber bundles a section is a continuous map from the base to the fiber, that is to say a map $$s:M\to E$$ such that $\pi(s(x))=x$ for evey $x\in M$ (so $s(x)$ is in the fiber of $x$).

EDIT following a comment:
To be precise, one should make a difference between fiber bundles and vector bundles: In the case of fiber bundles, the fiber has no vectorial sturcture, so it is not defined who is the zero of the fiber, so the zero section is not defined. So, to be coherent with terminology of fiber bundles, one should say that the Moebius strip, as a fiber bundle, has not two sections that are everywhere different from each other, while the cylinder has plenty of that.

A: The direct answer to your question about the difference in the tuple you considered is the following: usually the fibre bundle is not defined as the tuple of objects you wrote. The fiber bundle usually is defined to be just $\pi$, and the other objects are named "total space", "basis" and "fibre". But what is fundamental here is the map $\pi$. Indeed in the definition of fibration one has conditions on that particular map. So, yes, the main difference stands in how the map $\pi$ is defined, giving rise to different total spaces even with the same base and the same fiber.
Even topologically, they are different objects: we cannot find an homeomorphism between them. For example notice that one is orientable while the other is not (recalling that orientability of a manifold is a property that is preserved under homeomorphisms; like compactness: if $X$ is compact and $X$ is homeomorphic to $Y$, then $Y$ must be compact as well).
Locally they can be considered the same, but notice that their difference is topological, which means a difference in their global structure. Indeed, this is the same difference there is between a cartesian product of the base and the fiber and the whole structure of fiber bundle.


text:
Q: d3.js - draw ellipse shape with 4 points by svg path I would like to draw a ellipse shape by svg path. I use below code but the shape looks like a round corner rectangle.
How can I adjust the parameter to get a eclipse path!

demo()
function demo() {
    var width = 400
    var height = 200

    var margin = {left:20,top:20,right:20,bottom:20}
    var svg = d3.select('body').append("svg")
    .attr('width',width + margin.left + margin.right)
    .attr('height',height + margin.top + margin.bottom)
    .style('border','2px solid red')

    var g = svg.append("g")
    .attr("transform", `translate(${margin.left},${margin.top})`)

    var data = [[0,0,400,100]]
    g.selectAll('node')
    .data(data)
    .enter()
    .append('path')
    .attr('class','node')
    .attr('stroke','black')
    .attr('stroke-width',2)
    .attr('fill','none')
    .attr('d',function(d) {
        var w = d[2]
        var h = d[3]

        var ax = d[0]
        var ay = d[1] + h/2
        var bx = ax + w/2
        var by = ay + h/2
        var cx = ax + w
        var cy = ay
        var dx = bx
        var dy = d[1]
        add_dot(g,[[ax,ay],[bx,by],[cx,cy],[dx,dy]])

        var path = ['M',ax,ay,'C',ax,by,ax,by,bx,by,
            cx,by,cx,by,cx,cy,
            cx,dy,cx,dy,dx,dy,
            ax,dy,ax,dy,ax,ay]

        return path.join(' ')
    })
    function add_dot(g,data) {
        g.selectAll('dots')
        .data(data)
        .join('circle')
        .attr('class','dots')
        .attr('cx',d => d[0])
        .attr('cy',d => d[1])
        .attr('r',5)
        .attr('fill','red')

    }
  }
<script src="https://d3js.org/d3.v6.min.js"></script>

A: The path C command draws a cubic bezier segment, which can approximate an ellipse, but is not exact. The A command draws an arc segment, a sector of an ellipse.

demo()
function demo() {
    var width = 400
    var height = 200

    var margin = {left:20,top:20,right:20,bottom:20}
    var svg = d3.select('body').append("svg")
    .attr('width',width + margin.left + margin.right)
    .attr('height',height + margin.top + margin.bottom)
    .style('border','2px solid red')

    var g = svg.append("g")
    .attr("transform", `translate(${margin.left},${margin.top})`)

    var data = [[0,0,400,100]]
    g.selectAll('node')
    .data(data)
    .enter()
    .append('path')
    .attr('class','node')
    .attr('stroke','black')
    .attr('stroke-width',2)
    .attr('fill','none')
    .attr('d',function(d) {
        var w = d[2]/2
        var h = d[3]/2

        var ax = d[0]
        var ay = d[1] + h
        var bx = ax + w
        var by = ay + h
        var cx = ax + w*2
        var cy = ay
        var dx = bx
        var dy = d[1]
        add_dot(g,[[ax,ay],[bx,by],[cx,cy],[dx,dy]])

    var path = ['M',ax,ay,'A',w,h,0,0,0,bx,by,
        w,h,0,0,0,cx,cy,
        w,h,0,0,0,dx,dy,
        w,h,0,0,0,ax,ay]

        return path.join(' ')
    })
    function add_dot(g,data) {
        g.selectAll('dots')
        .data(data)
        .join('circle')
        .attr('class','dots')
        .attr('cx',d => d[0])
        .attr('cy',d => d[1])
        .attr('r',5)
        .attr('fill','red')

    }
  }
<script src="https://d3js.org/d3.v6.min.js"></script>

A:

demo()
function demo() {
    var width = 400
    var height = 200

    var margin = {left:20,top:20,right:20,bottom:20}
    var svg = d3.select('body').append("svg")
    .attr('width',width + margin.left + margin.right)
    .attr('height',height + margin.top + margin.bottom)
    .style('border','2px solid red')

    var g = svg.append("g")
    .attr("transform", `translate(${margin.left},${margin.top})`)

    var data = [[0,0,400,100]]
    g.selectAll('node')
    .data(data)
    .enter()
    .append('path')
    .attr('class','node')
    .attr('stroke','black')
    .attr('stroke-width',2)
    .attr('fill','none')
    .attr('d',function(d) {
        var w = d[2]
        var h = d[3]

        var ax = d[0]
        var ay = d[1] + h/2
        var bx = ax + w/2
        var by = ay + h/2
        var cx = ax + w
        var cy = ay
        var dx = bx
        var dy = d[1]
        add_dot(g,[[ax,ay],[bx,by],[cx,cy],[dx,dy]])

    var path = ['M',ax,ay,'C',ax,(ay+by)/2,(ax+bx)/2,by,bx,by,
        (bx+cx)/2,by,cx,(by+cy)/2,cx,cy,
        cx,(cy+dy)/2,(cx+dx)/2,dy,dx,dy,
        (dx+ax)/2,dy,ax,(dy+ay)/2,ax,ay]

        return path.join(' ')
    })
    function add_dot(g,data) {
        g.selectAll('dots')
        .data(data)
        .join('circle')
        .attr('class','dots')
        .attr('cx',d => d[0])
        .attr('cy',d => d[1])
        .attr('r',5)
        .attr('fill','red')

    }
  }
<script src="https://d3js.org/d3.v6.min.js"></script>


text:
Q: How Do I Add A Maven Repository Other Than Central? I am trying to add the "selenium standalone server jar" to my maven project. I found this:
https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-server-standalone/2.53.0
Copying the dependency is giving me a missing artifact error which probably mean my current maven settings isn't pointing to the repo that has this jar file. The url is http://repo.jenkins-ci.org/releases/org/seleniumhq/selenium/selenium-server-standalone/2.53.0/  How to I update my pom file so that I can add this dependency?

A: Check maven documentation:
https://maven.apache.org/guides/mini/guide-multiple-repositories.html
 <project>
...
  <repositories>
    <repository>
      <id>my-repo1</id>
      <name>your custom repo</name>
      <url>http://jarsm2.dyndns.dk</url>
    </repository>
    <repository>
      <id>my-repo2</id>
      <name>your custom repo</name>
      <url>http://jarsm2.dyndns.dk</url>
    </repository>
  </repositories>
...
</project>


text:
Q: Isotope after jquery.load()
I'm trying to using ajax on wordpress ( properly jQuery .load() function ) but I have a problem because after the page load isotope doesn't work.
Does anyone have an idea how to solve that?
Thanks!
Here is the entire of my code:
var $j = jQuery.noConflict();

//Isotope
$j(document).ready(function($){
    $j('#container').isotope({
          itemSelector: '.thumbportfolio',
          layoutMode: 'fitRows'
          });
    });

$j(document).ready(function(){
    $j('#filters a').click(function(){
      var selector = $j(this).attr('data-filter');
      $j('#container').isotope({ filter: selector });
      return false;
});
});

/* AJAX */
$j(function() {
    var $mainContent = $j("#content"),
    URL = '',
    siteURL = "http://" + top.location.host.toString(),
    $internalLinks = $j("a[href^='"+siteURL+"']"),
    hash = window.location.hash,
    $ajaxSpinner = $j("#content"),
    $el, $allLinks = $j("a");

    $internalLinks.each(function(){
        $j(this).attr("href", "#" + this.pathname);
    }).click(function($){
        $ajaxSpinner.fadeIn();
        $mainContent.animate({"opacity": "0.1"});
        $el = $j(this);
        $j(".current_page_item").removeClass("current_page_item");
        URL = $el.attr("href").substring(1);
        URL = URL + " #content";
        $allLinks.removeClass("current_link");
        $mainContent.load(URL, function(){
            $el.addClass("current_link").parent().addClass(".current_page_item");
            /*$ajaxSpinner.fadeOut();*/
            $mainContent.animate({ opacity: "1"});
        });
    });
});

A: I solved in this way:

/* AJAX */
$j(function() {
    var $mainContent = $j("#content"),
    URL = '',
    siteURL = "http://" + top.location.host.toString(),
    $internalLinks = $j("a[href^='"+siteURL+"']"),
    hash = window.location.hash,
    $ajaxSpinner = $j("#content"),
    $el, $allLinks = $j("a");

    $internalLinks.each(function(){
        $j(this).attr("href", "#" + this.pathname);
    }).click(function($){
        $ajaxSpinner.fadeIn();
        $mainContent.animate({"opacity": "0.1"});
        $el = $j(this);
        $j(".current_page_item").removeClass("current_page_item");
        URL = $el.attr("href").substring(1);
        URL = URL + " #content";
        $allLinks.removeClass("current_link");
        $mainContent.load(URL, function(){
            $el.addClass("current_link").parent().addClass(".current_page_item");
            /*$ajaxSpinner.fadeOut();*/
            $mainContent.animate({ opacity: "1"});
            $j('#container').isotope({
                  itemSelector: '.thumbportfolio',
                  layoutMode: 'fitRows'
             });
            $j('#filters a').click(function(){
              var selector = $j(this).attr('data-filter');
              $j('#container').isotope({ filter: selector });
              return false;
            });
        });
    });
});


text:
Q: How do I enter a special character in SQL connection I am trying to connect to a SQL Server in Jupyter Notebook. I receive this error because of the '@' in the password. Specific login changed for obvious reasoning.

(pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

%sql mssql+pyodbc://dbadmin:myP@ssword@Foray64

How can I format this without changing the password? This isn't my software. The vendor has this password hardcoded everywhere.


text:
Q: Php curl problem <?php
set_time_limit(0);
$php_userid = "my yahoo id";
$php_password = "my yahoo password";
$agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
$reffer = "http://mail.yahoo.com/";
$LOGINURL = "https://login.yahoo.com/config/login?";
$POSTFIELDS = ".tries=1&.src=ym&.intl=us&.u=3jtlosl6ju4sc.v=0&.challenge=NZYhS1spj7zunoVhpd6KRNqaF5Kz&hasMsgr=0&.chkP=Y&.done=http://mail.yahoo.com&.pd=ym_ver=0&c=&ivt=&sg=&pad=3&aad=3&login".$php_userid."&passwd".$php_password."";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$LOGINURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$POSTFIELDS);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_REFERER, $reffer);
$result = curl_exec ($ch);
curl_close ($ch);
echo $result;
?>

Is there any error? I'm doing something wrong, but i can not find it. please let me know if you can see where is my error? i need to set up this curl class.

A: The POST data is malformed, it should be :
[...]  "login=" . urlencode($php_userid). "&passwd=" . urlencode($php_password) . ""

Instead of
[...]  "login".$php_userid."&passwd".$php_password.""

You should use urlencode to ensure that the data passed in POST data is properly sent and you where missing an = for the login and passwd value.

A: You should use curl_error to determine what is failing during the cURL process. You can see a list of cURL error codes here: http://curl.haxx.se/libcurl/c/libcurl-errors.html
$result = curl_exec($ch);
$error = curl_error($ch);
print $error;
curl_close ($ch);

A: I assume the .challenge field gets dynamically generated. Your curl request uses an invalid challenge and so the server blocks it.

A: *

*$cookie  = cookie.txt";

*Insert after: curl_setopt($ch, CURLOPT_POSTFIELDS,$POSTFIELDS); this:     curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);


text:
Q: How to move a UI GameObject using Mouse Position in 3D World Space? I have been trying to experiment with moving UI Elements using the position of the mouse, Trying to make it behave like a cursor. I was able to move the Element when the Canvas Render Mode was set to "Screen Space". I was able to clamp it within the Canvas as well.
But I want it to work when the Canvas Render Mode is "World Space" as well. If I use the same code that I used for the Screen Space, the Element leaves its boundaries and gets messed up as the angles are being varied.
I really need help. Any clue how to do it?
You can view how the scene looks in this image below. : https://img.techpowerup.org/200624/screen.png
If Raycasting is the solution, can someone please help me out and provide a snippet of code or something.

A: What you are looking for is probably RectTransformUtility.ScreenPointToWorldPointInRectangle

Transform a screen space point to a position in world space that is on
the plane of the given RectTransform.
The cam parameter should be the camera associated with the screen
point. For a RectTransform in a Canvas set to Screen Space - Overlay
mode, the cam parameter should be null.
When ScreenPointToWorldPointInRectangle is used from within an event
handler that provides a PointerEventData object, the correct camera
can be obtained by using PointerEventData.enterEventData (for hover
functionality) or PointerEventData.pressEventCamera (for click
functionality). This will automatically use the correct camera (or
null) for the given event.

You didn't post your code but you could probably use it in a GraphicRaycaster.Raycast. Something like
GraphicRaycaster m_Raycaster;
PointerEventData m_PointerEventData;
EventSystem m_EventSystem;
Canvas canvas;

void Start()
{
    //Fetch the Raycaster from the GameObject (the Canvas)
    m_Raycaster = GetComponent<GraphicRaycaster>();
    //Fetch the Event System from the Scene
    m_EventSystem = GetComponent<EventSystem>();
    canvas = GetComponnet<Canvas>();

    //Set up the new Pointer Event
    m_PointerEventData = new PointerEventData(m_EventSystem);
}

void Update()
{
    //Check if the left Mouse button is clicked
    if (Input.GetKey(KeyCode.Mouse0))
    {
        //Set the Pointer Event Position to that of the mouse position
        m_PointerEventData.position = Input.mousePosition;

        //Create a list of Raycast Results
        List<RaycastResult> results = new List<RaycastResult>();

        //Raycast using the Graphics Raycaster and mouse click position
        m_Raycaster.Raycast(m_PointerEventData, results);

        //For every result returned, output the name of the GameObject on the Canvas hit by the Ray
        foreach (RaycastResult result in results)
        {
            Debug.Log("Hit " + result.gameObject.name);

            // until here it was the API example for GraphicRaycaster.Raycast
            // Now get the first hit object
            var rect = result.gameObject.GetComponent<RectTransform>();
            if(rect)
            {
                // check which camera to get (main or null for ScreenSpace Overlay)
                var camera = canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : Camera.main;
                if(RectTransformUtility.ScreenPointToWorldPointInRectangle(rect, result.screenPosition, camera, out var worldPosition))
                {
                    cursor3D.transform.position = worldPosition;
                    cursor3D.transform.rotation = result.gameObject.transform.rotation;
                    break;
                }
            }
        }
    }
}

Especially note also

*

*Attach this script to your Canvas GameObject.

*Also attach a GraphicsRaycaster component to your canvas by clicking the Add Component button in the Inspector window.

*Also make sure you have an EventSystem in your hierarchy.


text:
Q: Use next-i18next translations inside of a node.js I am using next-i18next package for my next.js project. Right now I am sending out creating email functionality which takes places server-side and I would like to consume the same translation files that I already use for the frontend.
Does next-i18next provide any functionality that would allow me to consume the translations similar to how I do it on frontend?

A: If you've set up next-i18next properly, you are able to use req.i18n.t;
const nextI18NextMiddleware = require('next-i18next/middleware').default;
...

server.use(nextI18NextMiddleware(nextI18next));

server.get('/custom', (req, res) => {
  ...
  res.json({
    text: req.i18n.t('Text here'),
    lng: req.i18n.language,
  });
});


text:
Q: 2 div covering each other what i have is this:

what i need is to be able to move the user image around, but it will be covered with the cover div that will mask my other one. is there a way for that?
in addition i need to know if it is possible to have the div#cover only with the png file in it but where the size of the image is not as big as the id#main so the rest of the cover div will be background color white - without getting a white color in the image area?
update:
i want to have a layer (div#cover) that will cover another layer(div#image). in the first one i will have a circle  that the inner of it is transparent and the outer is white so i will be able to see the bottom layer img within the cover layer
i will have jquery dragable to the second layer but it wont work becuase of the top layer that will block it from being draged with the mouse
my question was - is it possible to have the bottom layer to be draged when there is a cover layer on top of it?

A: If you want to cover a div with another div, use z-index property:
#cover{position:absolute;z-index:101;}
#image{position:absolute;z-index:100;}

I can't answer to your second question, because I don't understand it. Can you explain it more precisely?
Edit: after your edit I understand what you mean: you want to move an image that is under some kind of cropping frame. I think it's more complicated than using 2 divs and CSS...

A: Very difficult to answer a question one can't understand.
How to make a image/container draggable : http://jsfiddle.net/cNtfM/
Using jQuery/jQuery-UI is the easiest way in my eyes.
Your CoverImage will be above the other image coz you are writing it to the page before the main image. [renders from top to bottom]
I have know idea if this answers your question.


text:
Q: What is a quantum simulator? What is the idea behind of quantum simulator aimed to study properties of matter, such as using quantum dots to study the exotic quantum states?

A: Although we typically think of the laws of quantum mechanics as governing phenomena only at the smallest length scales, there are situations in which we can measure quantum effects at reasonable experimental sizes. Superconductivity is a great example of this insofar as a macroscopic piece of superconducting material can have a quantum coherence length of the same scale as itself. Crystalline nanoparticles, such as those of CdSe which are grown with little difficulty in chemistry laboratories across the world, are another great example since their macroscopic properties (e.g., color) are intimately tied up with quantum effects due to their small size. These are not simulators, per se, but systems in which quantum effects manifest themselves at a human scale.
True quantum simulators are experimental systems which are constructed to follow the same mathematical laws as a particular quantum phenomenon that defies (or at least frustrates) experimental investigation. These simulators display non-classical behavior themselves, but can be modified so that their time evolution mimics that of some other quantum system. Examples include optical quantum simualtors and the quantum dots you describe. As noted by Richard Feynman, such a simualtor can act as a quantum computer and (as was determined later) vice versa.


text:
Q: Elasticsearch text match percentage I have an Elasticsearch database with saved movie titles.
What I'm trying to achieve is select the closest possible match from this database to see if I already have a similar title.
At the moment I am using a combination of phrase_matching and word matching to try and achieve this. What I struggle with is the following:
In Database:
It Comes At Night
Search:
It
This will match obviously as it is within the slop parameter and matches 100% of the words with the one in the database...
But what I want is that this search fails because my search contains only 25% of the whole sentence in elasticsearch. (Almost like a reversed match).
The reason is that 'It' and 'It comes at night' are actually 2 different titles that may/may not have been indexed already when this search takes place.
The reason I'm not simply using terms queries is for cases like:
Guardians of the Galaxy 2, The
vs
The Guardians of the Galaxy 2
vs
The Guardians of the Galaxy Vol 2
Does anyone have any idea if this can be achieved in Elasticsearch?

A: For now I've used a combination of the following:

*

*A match query alongside minimum_should_match to check the amount of words that need to match

*MatchPhrase to check the position of the matched words with some headroom using slop

*A custom script that checks the doc['_source']['field'].value.length property to check if it is between certain character lengths

This gives me what I would expect.

A: Have you tried experimenting with configuring the similarity of the field? I think combining a more traditional statistical approach with some shingle boosting could offer you more robust solution. You could filter by score to limit the set of results.
See: https://www.elastic.co/guide/en/elasticsearch/reference/current/index-modules-similarity.html


text:
Q: Determine $a, b, c$ such that $\lim_{x\to0}\frac{1}{x^5}\int_0^x{a + b\cos t+c\cos 2t}\,dt=\frac{1}{5}$ Determine $a, b, c$ such that $$\lim_{x\to0}\frac{1}{x^5}\int_0^x{a + b\cos t+c\cos 2t}\,dt=\frac{1}{5}$$
I tried something. I realize the bounds are the same for the integral so regardless of the terms inside the integral will be equal to $0$. Then we apply L'hospital and the equality becomes:
$$\lim_{x\to 0}\frac{1}{5x^4}(a+b\cos x + c\cos 2x) = \frac{1}{5}$$
$$\lim_{x\to 0}\frac{(a+b\cos x + c\cos 2x)}{x^4} = 1$$
Now when I plug in $x = 0$ the limit will be equal to $\frac{a + b + c}{0}$ which is equal to $+/-\infty$ based on numerator's sign. This does not satisfy the equality. Do I need to assume $a + b + c = 0$ and keep applying L'hospitals or is this complete non-sense? I don't know I tried, help meeeee.


text:
Q: Why is my "character" going inside of the rect? I'm pretty new to programming, especially with python. I have a small game that I'm making, and the "character" is going inside of the object I'm trying to make it stay on top of.
Here's a link to the display:
https://academy.cs.cmu.edu/sharing/limeGreenAnt7762
Here's my code:
app.background = gradient('midnightBlue','midnightblue','midnightBlue','dodgerBlue',start='top')

#Ground
Rect(0,320,400,400,fill='lightgreen')

character = Circle(200,50,10)
character.verticalSpeed = 0.05

def onMousePress(x,y):
    character.centerY -=1
    character.verticalSpeed = -7

def onStep():
    if(character.centerY >= 310):
        character.verticalSpeed = 0
    character.centerY += character.verticalSpeed
    character.verticalSpeed += 0.5

I kept messing with the velocity seeing if it was somehow too high for it to register it hitting the point I wanted it to stay at.


text:
Q: how to match a string from a list of strings and ignoring regex special characters? I have this string:
d = {'col1': ['Digital Forms - how to spousal information on DF 2,0']}

I turned it into a dataframe :
df = pd.DataFrame(d)

From this dataframe, I want to match this list of words:
wordlist = ['Digital Forms', 'how', 'spousal', 'DF 2.0']

I used the findall function with some regex to return my list:
words =  df['col1'].str.findall(r"\b("+'|'.join(wordlist)+r")\b", flags=re.IGNORECASE)

This was the result:
[Digital Forms, how, spousal, DF 2,0]

I want to get rid of DF 2,0 as it is not supposed to be part of the result. I know in regex the dot (.) is a special character used to match any character. In this case the dot in DF 2.0 is used to match DF 2,0. I tried to modify my script and include something like '\\.'  to ignore the special character of the dot. Nothing worked for me.
Can someone help me modify the following so it ignores the special character of the dot?
'df['col1'].str.findall(r"\b("+'|'.join(wordlist)+r")\b", flags=re.IGNORECASE)'

A: You may form a regex alternation from your word list using re.escape to escape the metacharacters:
wordlist = ['Digital Forms', 'how', 'spousal', 'DF 2.0']
regex = r'\b(' + '|'.join([re.escape(x) for x in wordlist]) + r')\b'
words = df['col1'].str.findall(regex, flags=re.IGNORECASE)


text:
Q: Function returns a wrong number? Can anybody help me with this? It gives me a wrong number. matrix[i][j].spath is filled with the correct values but when i return the shortest path between any two nodes it gives me a wrong number. The compiler gives me this

warning: control reaches end of non-void function

But the if-statement where i check whether the end is reached will always perform so the return statement, because i set up the end coordinates in main(). But i noticed when i add return 1 or return anything at the end of the function it gives the correct result. Is this a kind of a rule or what? I have written a functions like this where i had an if-statement and the only return statement in it and it worked without problems. Thanks :)
#include <iostream>
#include <queue>

using namespace std;

struct node
{
    int x,y,spath,val;
}v,c;

node mat[100][100];
int dy[] = {-1,1,0,0}, dx[] = {0,0,-1,1}, n, m;

void input()
{
    cin >> n >> m;
    for (int i=0; i<n; i++) {
        for (int j=0; j<m; j++) {
            cin >> mat[i][j].val;
            mat[i][j].spath = 0;
        }
    }
}

int shortest_path(node start, node end)
{
    queue<node> q;
    q.push(start);
    mat[start.y][start.x].val = 1;

    while (!q.empty())
    {
        v = q.front();
        q.pop();

        for (int i=0; i<4; i++) {
            c.y = v.y + dy[i];
            c.x = v.x + dx[i];

            if (c.y == end.y && c.x == end.x) {
                return mat[v.y][v.x].spath + 1;
            }
            else if (c.y >=0 && c.y < n && c.x >=0 && c.x < m && mat[c.y][c.x].val == 0)
                {
                    mat[c.y][c.x].val = 1;
                    mat[c.y][c.x].spath = mat[v.y][v.x].spath + 1;
                    q.push(c);
                }
        }
    }
}

int main()
{
    node start,end;
    start.x = start.y = 0;
    end.y = end.x = 4;
    input();
    cout << shortest_path(start,end) << endl;

    return 0;
}

A: About the warning :
Your code is not protected against bad input : if end is outside your n x m grid, or is on a "wall", or if there is no path from start to end your function will exit without executing a return statement.
The compiler has no way of predicting what input will be fed to the function.

A: As you noticed, the problem is that it misses a return statement. You may know that it will always go through the return in the if statement, but the compiler doesn't, hence the warning.
You supposed the input was correct, but you should "never trust user input". Never Ever.
There should always be a return statement for all routes the execution might take in your non-void function.

A: It seems that you are writing BFS.Here's my code:
#include"stdio.h"
#include"string.h"
#include"queue"
using namespace std;
#define N 200
int n,m;
int move[][2]={{0,1},{1,0},{0,-1},{-1,0}};
struct node
{
    node(int _x=0,int _y=0)
    {
        x=_x,y=_y;
    }
    int x,y;    //mark the Coord of the node
};
int data[N][N];//store data.
bool map[N][N]; //mark whether the node is visited.
int input()//input & initialize the array
{
    memset(map,false,sizeof(map));
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
    {
        int t;
        scanf("%d",&t);
        data[i][j]=t;
        map[i][j]=false;
    }
    return 0;
}
bool judge(node x)
{
    if(x.x<n&&x.x>=0&&x.y<m&&x.y>=0) return true;
    return false;
}
int shortest_path(node s,node e)
{
    queue<int>dist;//means  'spath' in your code.
    int dst=0;
    queue<node>q;
    q.push(s);
    map[s.x][s.y]=true;
    dist.push(0);
    node v,c;
    while(!q.empty())
    {
        v=q.front();
        q.pop();
        dst=dist.front();
        dist.pop();
        for(int i=0;i<4;i++)
        {
            c.x=v.x+move[i][0];
            c.y=v.y+move[i][1];
            if(judge(c)&&!map[c.x][c.y])
            {
                dist.push(dst+1);
                q.push(c);
                map[c.x][c.y]=true;
                if(c.x==e.x&&c.y==e.y)
                    return dst+1;
            }
        }
    }
    return -1;//if the path not found return -1;
};
int main()
{
    input();
    node s(0,0),e(4,4);
    printf("%d\n",shortest_path(s,e));
    return 0;
}

the input should be:
n>=5 m>=5 because end point is(4,4).
and an n*m matrix.


text:
Q: Need to switch my app to background after a phone restart or power on I need my android app to be in background mode after a phone restart/power on.
Currently I am using the following code, so that my app successfully gets launched after a phone restart/power on.
AndroidManifest.xml:
<receiver android:enabled="true" android:name="my_package.BootUpReceiver" android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

BootUpReceiver.java:
public class BootUpReceiver extends BroadcastReceiver
{
    private static SharedPreferences aSharedSettings;

    @Override
    public void onReceive(Context context, Intent intent)
    {
        aSharedSettings = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
        boolean isUserLoggedIn = aSharedSettings.getBoolean(Key.AUTHENTICATED, false);
        if(isUserLoggedIn)
        {
            Intent aServiceIntent = new Intent(context, MyHomeView.class);
                    aServiceIntent.addCategory(Intent.CATEGORY_HOME);
            aServiceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(aServiceIntent);
        }
    }
}

As I said above, my app successfully gets launched after a phone restart/power on.
However, after the phone restart/power on, my app was in foreground mode. But I need my app to be in background mode.
Can anyone please say, how to make an app to be in background mode after a phone restart or power on.
I even tried by changing the intent category to
<category android:name="android.intent.category.HOME" />

But no use in it. Can anyone please help me?
Thanks.

A:
I need my app to be just running in background after the phone restart, so that users can select from the minimized app

I think your approach is wrong. All you are trying to do now is to add icon of your app to recent apps list. Your app won't run in background and I think you don't really want it. Am I right?
Recent apps list managed by android and IMHO forcing your app to be in recent apps list is not a very good idea. User will start you app when he wants from launcher or icon on his desktop.

A: If your broadcast receiver is working fine and app is starting successfully then you can use the below code in your MyHomeView activity's onCreate method to go to the home screen.

Trick is to click HOME button programmatically when app starts.

Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);

you can pass some variable from the BroadcastReceiver to differentiate a normal request and BroadcastReceiver's request to make the above code conditional.
But if you want to execute it always in background then it would be better to use Service.
It is recommended to change your code to the service to run it in background.

A: The suggestion which Leonidos replied is correct.
However, Just a workaround for this:
In my BootUpReceiver, I had a seperate boolean flag for this! (Its a bad way. but just a workaround)
SharedPreferences.Editor aPrefEditor = aSharedSettings.edit();
aPrefEditor.putBoolean(Key.IS_DEVICE_RESTARTED, true);
aPrefEditor.commit();

In Oncreate method of MyHomeView:
boolean isDeviceRestarted = aSharedSettings.getBoolean(Key.IS_DEVICE_RESTARTED, false);
if(isDeviceRestarted)
{
    SharedPreferences.Editor aPrefEditor = aSharedSettings.edit();
    aPrefEditor.putBoolean(MamaBearKey.IS_DEVICE_RESTARTED, false);
    aPrefEditor.commit();
    moveTaskToBack(true);
}

Thanks


text:
Q: Flutter: Add box shadow to a transparent Container I'm trying to make a widget that renders one of the circles shown in this image. It is a transparent circle with a box-shadow. The circle should show whichever color or background image that is applied to the parent container. The circle is transparent but what I see is this: a black box shadow and not the background color of the parent. Any suggestions?
Here is what I have so far:
class TransParentCircle extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
        child: new Center(
          child: new Container(
            decoration: new BoxDecoration(
              border: new Border.all(width: 1.0, color: Colors.black),
              shape: BoxShape.circle,
              color: Colors.transparent,
              boxShadow: <BoxShadow>[
                BoxShadow(
                  color: Colors.black,
                  offset: Offset(1.0, 6.0),
                  blurRadius: 40.0,
                ),
              ],
            ),
            padding: EdgeInsets.all(16.0),
          ),
        ),
        width: 320.0,
        height: 240.0,
        margin: EdgeInsets.only(bottom: 16.0));
  }
}

A: Container(
height: 200.0,
decoration: BoxDecoration(
    boxShadow: [
      BoxShadow(
        color: Colors.black,
        blurRadius: 10.0, // soften the shadow
        spreadRadius: 7.0, //extend the shadow
        offset: Offset(
          5.0, // Move to right 10  horizontally
          5.0, // Move to bottom 5 Vertically
        ),
      )
    ],
),
child: Text(" ", style:TextStyle(fontSize:30)),

);

A: As you can see in the BoxShadow class, they subclass the toPaint() method like this :
Paint toPaint() {
  final Paint result = Paint()
    ..color = color
    ..maskFilter = MaskFilter.blur(BlurStyle.normal, blurSigma);
  assert(() {
    if (debugDisableShadows)
      result.maskFilter = null;
    return true;
  }());
  return result;
}

... with BlurStyle.normal instead of BlurStyle.outer as we wanted.
Let's just create a custom BoxShadow that takes the BlurStyle as parameter.
import 'package:flutter/material.dart';

class CustomBoxShadow extends BoxShadow {
  final BlurStyle blurStyle;

  const CustomBoxShadow({
    Color color = const Color(0xFF000000),
    Offset offset = Offset.zero,
    double blurRadius = 0.0,
    this.blurStyle = BlurStyle.normal,
  }) : super(color: color, offset: offset, blurRadius: blurRadius);

  @override
  Paint toPaint() {
    final Paint result = Paint()
      ..color = color
      ..maskFilter = MaskFilter.blur(this.blurStyle, blurSigma);
    assert(() {
      if (debugDisableShadows)
        result.maskFilter = null;
      return true;
    }());
    return result;
  }
}

Now we can use it like this :
new CustomBoxShadow(
  color: Colors.black,
  offset: new Offset(5.0, 5.0),
  blurRadius: 5.0,
  blurStyle: BlurStyle.outer
)

A: This is working for everyone
  Container(
    height: 210.0,
    decoration: BoxDecoration(
        boxShadow: [
          new BoxShadow(
            color: Colors.grey,
            blurRadius: 10.0,
          ),],

    ),
  child: ClipPath(
    clipper: ShapeBorderClipper(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(10))
        )
    ),
    child: Container(
      height: 200.0,
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
                left: BorderSide(
                    color: Theme.of(context).primaryColor,
                    width: 7.0
                )
            )
        ),
      child: Text("kokoko"),
    ),
  ),
);

A: Container(
  height: 380,
  decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(20),
    boxShadow: [
      CustomBoxShadow(
          color: Colors.black.withOpacity(0.25),
          blurRadius: 5,
          blurStyle: BlurStyle.outer
          ),
    ],
  ),
  child: Container(
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(20),
    ),
    child: Container(
      decoration: BoxDecoration(
        color : Colors.white.withOpacity(.25),
        borderRadius: BorderRadius.circular(20),
      ),
    ),
  ),

On ios there were black box behind of my transparent gradient widget. I think it uses that box to render the shadow. So, I had to add extra layer to container to ovverride that box. Result is
this


text:
Q: PHP - Problems creating an image containg text I'm trying to create an image containing text.
I've tried several examples I've found on the web, among them are:
http://php.net/manual/en/function.imagettftext.php
http://www.daftlogic.com/projects-text-to-image.htm
http://www.phpro.org/examples/Text-to-Image-with-GD.html
but I've tried others.
Let's take the one from daftlogic.com - http://www.daftlogic.com/projects-text-to-image.htm
I'm not using the large, main example on that page, but rather the short test shown, about 1/3 of the way down the page, after the line of text that reads:
"(1) Please test this example to ensure imagecreate works on your server..."
Search for that text and you'll find the code I'm testing.
I have tried the main example and it has failed with almost the same results.
I added the GD support test, just to see if it was really there. The error is not triggered - and phpinfo() run on the server shows GD support.
The PHP code: is
<?php
error_reporting(E_ALL);
// check for GD support if(!function_exists('ImageCreate')) {
fatal_error('Error: Server does not support PHP image generation') ;
}
header("Content-type: image/png");
$im = @imagecreate(110, 20)
   or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>

I have that code in a file named daftlogic.php in a directory named PHP which is right off my testing root on my server. I tried this on the copy of Abyss server I have installed on my system for PHP and other testing but the GD library is not included in the PHP installed for Abyss and if I ever get this working on the server (which does have GD) I'll go figure out how to include GD support on my system.
Okay -
Here's the directory structure:
\testing -
      \phpmodules
      \rootfolder

"testing" is a directory below the root directory for my real world site on this sever.
Basically I've emulating the structure of the actual web site directories and "testing" takes the place of the "httpdoc" directory which is not real world accessible.
"phpmodules" contains the files containing PHP code, no HTML, just PHP.
"rootfolder" is where the "pages" are, the HTML pages with extensions like HTML, SHTML, and PHP.
In my actual web site, there is a comparable directory which is the "root" directory and nothing above that, such as the directory in which I put the PHP code, is visible to the world.
daftlogic.php is in \testing\PHP
A file named "testinanotherone.php" is in \testing\rootfolder
The contents of that file are:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Try yet another sample</title>

<?php include("../phpmodules/daftlogic.php"); php?>

BY THE WAY - the directory structure is as I have shown you but the directory names have been changed to protect the .. well, I don't want any links to my actual test directories escaping the lab - that is, I don't want there to be links to my test directories.
If I use Firefox (3.6.24) to view the file testinanotherone.php, all that is displayed is an error message from Firefox which reads:

The image "http://bobnovell.com/testing/rootfolder/testanotherone.php'
  can't be displayed because it contains errors.

Now, the interesting thing is that there is no page source - if I right click on the page, and the "View Page Source" menu item grayed out.
If I right click on the message, the contextual menu I get is that for an image file. If I then select "View Image Info" I get:
Under "General"
testanotherone.php (PNG Image):
Address:   http://www.bobnovell.com/testing/rootfolder/testanotherone.php (again, I've modified that to conceal the real directory names)
Type:  image/png
Render Mode: Quirks mode
Encoding: ISO-8859-1
Size: 0.42 KB (433 bytes)
Modified: Monday, April 02, 2012 10:35:17 PM
Under "Media"
Location: http://www.bobnovell.com/testing/rootfolder/testanotherone.php (again, I've modified that to conceal the real directory names)
Type: Image
Size: 0.42 KB (433 bytes
Dimensions: 0px × 0px (scaled to 740px × 19px)
I'll skip "Permissions" and "Security"

This what I.E. shows when I view the page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>create image</title>

‰PNG

IHDRnV,šPLTEé[an÷fIDAT•c` `fxÄÀÃ`Ç ÀçÀä²41ƒ'€˜Ë–Ý'Àq²@੤;{á0—
œi
<n+²
Já-8Û4˜B8ÕAŠ»ñp¼Q'Uγ…v@¯×Ò¥kAIEND®B`'

The "View Source" menu item IS available and the source is:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>create image</title>

PNG

Now - since Firefox was reporting errors in the image, I decided to comment out the header statement in daftlogic.php and see what I could see.
In Firefox I get:
‰PNG  ��� IHDR���n������V,š���PLTE���é[an÷���fIDAT•c` `fxÄÀÃ`Ç ÀçÀä²41ƒ'€˜Ë–Ý'Àq²@੤;{á0— œi

In I.E. I get:
‰PNG  IHDRnV,šPLTEé[an÷fIDAT•c` `fxÄÀÃ`Ç ÀçÀä²41ƒ'€˜Ë–Ý'Àq²@੤;{á0— œi

The source in Firefox (with the header statement commented out in the code) is:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>create image</title>

‰PNG

���
IHDR���n������V,š���PLTE���é[an÷���fIDAT•c` `fxÄÀÃ`Ç ÀçÀä²41ƒ'€˜Ë–Ý'Àq²@੤;{á0—
œi

The source in I.E. (without the header statement) is:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>create image</title>

PNG

Which is, as far as I can tell, the same source shown when the header statemnt is in the code.
Does anyone have any idea how to make this work?
The only thing I'm wondering about is that I've see references to a package name FreeImage that is used in some of the samples I've found.
I don't think it comes into play with the code I'm trying but hey, you never know.
I began this trip through Wonderland because I want to add some math tests to pages instead of CAPTCHAs (as the OCR software gets better, the CAPTCHAs are being made harder and harder and I find I have trouble with them myself and I don't want to lose user input because the CAPTCHA stumps them) and I wanted to show the equation using an image.
I'm about ready to drop back and punt and manually make up a bunch of small images containing single digits and then "paste" them together to make the equation I want the user to solve.
I've wasted enough time spinning my wheels on this that I could have had single digit images (and plus, minus, division, and multiplication signs) finished by now and probably most of the code to stitch them together.
Any one have any suggestions to get this code (or any such example) to actually work for me.
Any assistance will be GREATLY appreciated.
Bob
_______________ Edited 2012-04-03 2334 CST
It does not matter whether I have a header statement, to define the type of the contents, or not - The image is displayed.
Here's the code I'm now using:
<?php

if(!function_exists('imagettftext')) {
    fatal_error('Error: Server does not support PHP image generation') ;
}
// from php.net/manual/en/function.imagejpeg.php
// Create a blank image and add some text and send to browser
$im = imagecreatetruecolor(200, 60);
//$text_color = imagecolorallocate($im, 233, 14, 91);
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 200, 60, $white);
imagestring($im, 5, 5, 5,  'A Simple Text String without header', $black);

// Set the content type header - in this case image/jpeg
//header('Content-Type: image/jpeg');

// Output the image
imagejpeg($im);

// Free up memory
imagedestroy($im);
?>

Here is the HTML which invokes it:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>Test Create JPG</title>

Here's the source displayed by Firefox:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>Test Create JPG</title>

If I un-comment the header statement, I get the same output as when it is commented out:
Here's the source with the header un-commented and the text changed:
<?php

if(!function_exists('imagettftext')) {
    fatal_error('Error: Server does not support PHP image generation') ;
}
// from php.net/manual/en/function.imagejpeg.php
// Create a blank image and add some text and send to browser
$im = imagecreatetruecolor(200, 60);
//$text_color = imagecolorallocate($im, 233, 14, 91);
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 200, 60, $white);
imagestring($im, 5, 5, 5,  'A Simple Text String with header', $black);

// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');

// Output the image
imagejpeg($im);

// Free up memory
imagedestroy($im);

I use the same HTML file to invoke and the source is the same.
I get the same results with I.E. 8
I have double and triple, quadrupole checked - actually I've lost count of how many times I've tested with and without the header statement - the results are the same.
The image is displayed regardless of whether not I have a header statement or not.
Any thoughts on this?

A: daftlogic.php directly outputs png image. So you need to put this in an img tag.

Here /web/path/to/daftlogic.php means the browser accessible path of daftlogic.php.
Note:

*

*Width and height is necessary to prevent the browser from rendering the page again after loading the image to fix the image layout.

*Always use meaningful alt tag. This tag is mandatoryspec

It does not matter whether I have a header statement, to define the type of the contents, or not - The image is displayed.

For the update part of your question
As long as you are putting the source in an image tag, no matter what the Content-type it sends browser will try to render it as an image. If you put a html file as src in an image tag, browser will treat it as a damaged image. It also preserves the space but doesn't display it.

But image content type has advantage. If you directly load an image browser will obey the content type. Load daftlogic.php in browser. If you used content-type browser will show according to to content type. Otherwise browser will show it as text/html which is default content type of PHP.