text:
Q: Django auto populate author field in admin panel In my django project i have a model.py with a class like this:
class temp_main(models.Model):
    descr = models.CharField(max_length=200, verbose_name="Description")
    notes = models.TextField(null=True, blank=True, verbose_name="Note")
    dt = models.DateTimeField(auto_now=True)
    #Fields for API permissions
    owner = models.ForeignKey('auth.User', related_name='tmain_owner', on_delete=models.CASCADE, verbose_name="API Owner")

    class Meta:
       verbose_name = '1-Main Template'
       verbose_name_plural = '1-Main Templates'

    def __str__(self):
        return self.descr

i would that in my admin panel the owner field was auto-populated with the current login user.
In my admin.py i write:
admin.site.register(temp_main, )

How can i set my owner field with logged in user?
Thanks in advance

A: I think what you need is the save_model method. Here's how it is used (from the documentation):
from django.contrib import admin
from myproject.myapp.models import Article

class ArticleAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.user = request.user
        super().save_model(request, obj, form, change)

admin.site.register(Article, ArticleAdmin)

I think you could change obj.user to obj.owner in your case. Does that work?
Also, I think you would want to change the name of the temp_main class to TempMain and then name the class in the admin.py file TempMainAdmin. Django will use this naming scheme to know which Admin Model goes with which model.


text:
Q: (Server) cache problems with jquerymobile site I've got a problem with too much caching on my first jquerymobile site (http://backpocketgrower.com/).  I upload new versions of pages but only old versions are displayed; I can physically remove pages from the server, yet subsequent browser visits display them.  I've used totally "virgin" machines/browsers on the site and still get old versions of the pages displayed.  I've deleted cache/history from all my browsers (FF, Chrome, Dolphin, Opera, Safari), have added querystrings to the a-tag links to new pages - yet continue to only get old versions of pages presented.
Any ideas of where next I should start looking for a solution?
Thanks/Bruce

A: It seems you can programatically disable the cache. Check out this documentation at this link
As per the link above you should be able to do something like below
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));

or you can do the below in your page itself
<%@ OutputCache Duration="60" VaryByParam="None" %>

From another link you I learned that you can do as below
// Stop Caching in IE
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

// Stop Caching in Firefox
Response.Cache.SetNoStore();

Hope this will give you a head start.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to debug apk file I want to debug apk file(android).
However, target apk file is encrypted by specific apk protector.
So, classes is not located in classses.dex (class encryption)
Therefore, I can't use apk re-compile for debugging mode using apktool.
Is there another debugging way in this situation ?

A: Encrypted files may restrict you debugging


text:
Q: Existe um seletor css que eu consiga selecionar um input do tipo submit apenas quando ele for acionado/clicado minha dúvida é a seguinte:
Existe alguma forma de selecionar apenas com css uma tag <input type="submit">apenas quando ele for clicada/acionada.

A: Quando você clica no input, ele recebe o estado de :focus:
input[type=submit]:focus {
  color: red;
}

Edição: conforme informado na resposta do Hugo, o :active ocorre quando botão é clicado. O :focus pode ocorrer
  quando o botão for clicado, via tecla TAB ou via script.

Quando o foco é retirado ele volta ao estado original.
Exemplo:

input[type=submit]:focus {
  color: red;
}
<input type="submit">

A: Eu acho que entendi a pergunta de outra forma, acredito que ele queira "disparar" alguma propriedade no clique. E nesse casso seria com o :active

Segue código referente a imagem acima:

[type="submit"]:active {
    box-shadow: none;
    transition: box-shadow 100ms;
}
[type="submit"]:active {
    box-shadow: 0 0 20px red;
}
<input type="submit" value="Clique aqui">

OBS
Qualquer elemento pode receber um :active

The :active pseudo-class is also typically matched when using the keyboard tab key. It is frequently used on <a> and <button> HTML elements, but may not be limited to just those.

PORTUGUÊS "A pseudo-classe :active também é normalmente usada quando se usa a tecla tab do teclado. É freqüentemente usado em elementos HTML <a> e <button>, mas pode não estar limitado apenas a eles."
Fonte: https://developer.mozilla.org/pt-BR/docs/Web/CSS/:active


text:
Q: How can I find the greatest value of this expression? This is my problem. Find the greatest of the expression
$$P = x^3 + 2y^3 +2x-y-1,$$
knowing that
$$x^2 + y^2 -x-y=0. $$
I tried. We have
$$x^2 + y^2 -x-y=0 \Leftrightarrow \left (x-\dfrac{1}{2}\right )^2 + \left(y-\dfrac{1}{2}\right )^2 = \dfrac{1}{2}. $$
Put
$$x-\dfrac{1}{2} =\dfrac{1}{\sqrt{ 2}} \sin \alpha, \quad  y-\dfrac{1}{2} =\dfrac{1}{\sqrt{2}} \cos \alpha, \quad \alpha \in [0, 2\pi].$$
But I think, It is not simple.

A: The maximum equals $3$ achieved at $(x,y) = (1,1)$. You could use the trig substitution or Lagrange multipliers. It is not a trivial problem since, say, the minimum is not a nice expression


text:
Q: Rails will_paginage i am using will_paginate for pagination,
When i reach the last page and then click on Next link its again taking me to first page,
Actually i want to disable the Next button when i reach the last page.
please advise me how to solve this..
this is the code i used for pagination

<%= will_paginate @users,
                  :prev_label => "Preevious",
                  :next_label => "Next",
                  :page_links =>true,
                  :renderer => PaginationListLinkRenderer
      %>

A: Controller:
@users = User.paginate :per_page => 5,
    :page => params[:page],
    :order => 'name ASC',
    :conditions => ""

View:
<%= will_paginate @users,
    :previous_label => "Previous",
    :next_label => "Next",
    :inner_window => "2",
    :outer_window => "0" %>

Above is all my code and it works for me in will_paginate. Once reached down the last page, the "Next" link change to bolded text, so as the last page number (see image below).

A: I am using
<%= will_paginate @users %>

and it is working fine. It disables the next link when i reach the last page.


text:
Q: Recovered .ssh/authorized_keys file, but still get Permission Denied (Public Key) message I Lost public key access to my Ubuntu 12.04 instance. I'm using the correct login credentials "ubuntu@myip-address", and I tried launching a new instance (attaching the key in question to it) and it works with the new instance. I then realized, after reading other possible causes suggesting it could have something to do with the .ssh/authorized_keys file, that I accidentally deleted all the files in my ubuntu home folder (forgetting about the hidden files at the time).
I tried attaching and mounting my "corrupt" volume to the new instance I launched, and recursively copied the new instance's Ubuntu directory into my corrupt volumes home directory, so my corrupt /home/ubuntu directory contains:
.  ..  .bash_history  .bash_logout  .bashrc  .cache  .profile  .ssh  .sudo_as_admin_successful
Just like new (I think). After attaching and mounting it back to my original instance, even though all the files I deleted are restored, including the proper public key info in the .ssh/authorized_keys file, I still get Permission Denied (Public Key) message. Should this have worked?
I tried reattaching the corrupt volume to my new instance just to double check that my work was still intact. Not sure what else to try.

A: You might have neglected -p or -a when copying. Make sure the permissions are correct:
chmod 700 .ssh/
chmod 600 .ssh/authorized_keys


text:
Q: Error message when I try to run pdflatex with movie15 package I am trying to use package movie15 to include videos in my PDF produced by the command pdflatex, however all the time I use this command the followed part of massage rises:
(/usr/share/texmf-texlive/tex/latex/fancybox/fancybox.sty
Style option: `fancybox' v1.3 <2000/09/19> (tvz)
) (./movie15.sty (/usr/share/texmf-texlive/tex/latex/oberdiek/ifdraft.sty)
(/usr/share/texmf-texlive/tex/latex/ms/everyshi.sty)

! LaTeX Error: Command \hyperlinkmovie already defined.
               Or name \end... illegal, see p.192 of the manual.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.4380 }

How should I proceed to avoid it?
Cheers!
PS: I have downloaded the file movie15.sty and place it in the same directory I run the command pdflatex mylatexfile

A: Without a MWE, I think the comment from Gonzalo Medina is the closest that can be got to an answer:

Just a wild guess: it seems that both the packages multimedia and
  movie15 are being loaded; that will cause the error mentioned.


text:
Q: How to find records by comparing two tables in oracle I have two tables A and B.Both tables are foreingkeyed by Psslno which is primary key in B and foreign key in A.Here what i want is, i need the records from table B
where Pid should not suffix with character S and same time all the records coming under table B for Pssslno, is having working status(greater than 100).how to get get this
sample given below ,from table B Psslno 1000 fails because one of records in table A is having status 80.Pssslno 1100  satisfies since Pid doesnot suffix S and
all are wokring in table A (>100).Pssslno 1200 fails because Pid 101S suffixes S ,and Psslno 1300 satisfies
Table A shown below
Sslno   Sid   tech     status    height     Psslno

100     89    G        80        11          1000

101 91    U        110        11         1000

102     93    L        110        11         1000
-------------------------------

106     98    G        110        34         1100

107     99    U        118        34         1100
--------------------------------

109     101   G        110        54         1200

110     102   U        110        54         1200

111     103   L        118        54         1200
--------------------------------

112     105   G        110        54         1300

113     106   U        110        54         1300

114     107   L        118        54         1300

Table B shown below
 Psslno   Pid     Location    Type

 1000      89    AJM         Mic
 1100      98    SHJ         MAC
 1200      101S   DBB         LAC
 1300      105    ABB         SAC

What query i did is
SELECT a.*
  FROM B a
  INNER JOIN A b
  ON a.Psslno   =b.Psslno
  WHERE b.status>100
  AND a.Pid NOT LIKE'%S%'

Does that okey??

A: What you need here is an anti-join. It could be written a bit more simply, with a NOT IN condition, if column psslno was not nullable in table A.
select psslno
from   b
where  pid not like '%S'
  and  not exists (
                    select *
                    from   a
                    where  psslno  = b.psslno
                      and  status <= 100
                  )
;

EDIT Based on OP clarification - he needs to retrieve all the information from both tables where psslno is returned by the query above...
One (efficient) way to do this is to use the analytic function MIN() for status, partitioned by psslno:
with
  a ( sslno, sid, tech, status, height, psslno ) as (
    select 100,  89, 'G',  80, 11, 1000 from dual union all
    select 101,  91, 'U', 110, 11, 1000 from dual union all
    select 102,  93, 'L', 110, 11, 1000 from dual union all
    select 106,  98, 'G', 110, 34, 1100 from dual union all
    select 107,  99, 'U', 118, 34, 1100 from dual union all
    select 109, 101, 'G', 110, 54, 1200 from dual union all
    select 110, 102, 'U', 110, 54, 1200 from dual union all
    select 111, 103, 'L', 118, 54, 1200 from dual union all
    select 112, 105, 'G', 110, 54, 1300 from dual union all
    select 113, 106, 'U', 110, 54, 1300 from dual union all
    select 114, 107, 'L', 118, 54, 1300 from dual
  ),
  b ( psslno, pid, location, type ) as (
    select 1000, '89'  , 'AJM', 'Mic' from dual union all
    select 1100, '98'  , 'SHJ', 'MAC' from dual union all
    select 1200, '101S', 'DBB', 'LAC' from dual union all
    select 1300, '105' , 'ABB', 'SAC' from dual
  )
-- End of input data FOR TESTING ONLY (not part of the solution).
-- SQL query begins BELOW THIS LINE; use your actual table and column names.
select   q.sslno, q.sid, q.tech, q.status, q.height, q.psslno,
         b.pid, b.location, b.type
from     ( select a.*, min(status) over (partition by psslno) as min_status
           from   a
         ) q
         inner join b on q.psslno = b.psslno
where    q.min_status > 100
  and    b.pid not like '%S'
order by q.sslno    -- If needed.
;

Output:
SSLNO SID TECH STATUS HEIGHT PSSLNO PID  LOCATION TYPE
----- --- ---- ------ ------ ------ ---- -------- ----
  106  98 G       110     34   1100 98   SHJ      MAC
  107  99 U       118     34   1100 98   SHJ      MAC
  112 105 G       110     54   1300 105  ABB      SAC
  113 106 U       110     54   1300 105  ABB      SAC
  114 107 L       118     54   1300 105  ABB      SAC


text:
Q: Why is EIT needed to story memory using rydberg atoms? I was going through a paper explaining how the write-in and read-out efficiencies can be increased using cold atoms where they used Rydberg atoms, and mentioned that they were probed using EIT(Electromagnetically Induced Tranparency).
I have a brief idea about EIT, that it can be used to make a system transparent, which would otherwise be opaque.
I also know that the three states are used here, those are

*

*The ground state

*An excited state

*A rydberg state

Can anyone explain how EIT is used here?
The DOI of the paper is: 10.1109/PHOSST.2017.8012667

A: EIT is not needed. It's just something that helps to make whatever the process better.
Also, it makes me feel that your question does not make sense by itself. EIT (three-level system coupled by two lights where one of them is extremely weak) is used for two scenarios: to store single-photon level photonic information, or to enhance interaction strength. The former one is developed as quantum memory so that the final state is metastable ($\lambda$-scheme), and the latter one is for the nonlinear quantum optics (photonic gate, ladder-scheme), which recently developed to use the Rydberg levels to further increase the interaction strength. These different applications seem to confuse you.


text:
Q: SQL query not returning results when expected I am having trouble with my queries not returning any results.  There are no errors in the query but i expect to see a result and i don't get any
Here is my table structure
CREATE TABLE IF NOT EXISTS `boards` (
  `boardid` int(2) NOT NULL auto_increment,
  `boardname` varchar(255) NOT NULL default '',
  `boarddesc` varchar(255) NOT NULL default '',
  PRIMARY KEY  (`boardid`)
);

CREATE TABLE IF NOT EXISTS `messages` (
  `messageid` int(6) NOT NULL auto_increment,
  `boardid` int(2) NOT NULL default '0',
  `topicid` int(4) NOT NULL default '0',
  `message` text NOT NULL,
  `author` varchar(255) NOT NULL default '',
  `postdate` datetime default NULL,
  PRIMARY KEY  (`messageid`)
);

CREATE TABLE IF NOT EXISTS `topics` (
  `topicid` int(4) NOT NULL auto_increment,
  `boardid` int(2) NOT NULL default '0',
  `topicname` varchar(255) NOT NULL default '',
  `author` varchar(255) NOT NULL default '',
  `counter` int(5) NOT NULL default '0',
  `sticky` char(1) NOT NULL default 'n',
  `locked` char(1) NOT NULL default 'n',
  PRIMARY KEY  (`topicid`)
);

CREATE TABLE IF NOT EXISTS `users` (
  `userid` int(25) NOT NULL auto_increment,
  `first_name` varchar(25) NOT NULL default '',
  `email` varchar(255) NOT NULL default '',
  `username` varchar(25) NOT NULL default '',
  `password` varchar(32) NOT NULL default '',
  `salt` char(3) NOT NULL default '',
  `sex` varchar(6) NOT NULL default '',
  `user_level` enum('0','1','2','3') NOT NULL default '0',
  `signup_date` datetime NOT NULL default '0000-00-00 00:00:00',
  `last_login` datetime NOT NULL default '0000-00-00 00:00:00',
  `activated` enum('0','1') NOT NULL default '0',
  PRIMARY KEY  (`userid`)
)

and here is my query
SELECT  b.boardid
        , b.boardname
        , t.topicid
        , t.topicname as topic
        , m.author as mauthor
        , m.message as message
        , DATE_FORMAT(m.postdate, '%M %d, %Y, %r') as postdate
        , tm.post_count as posts
        , u.user_level
        , DATE_FORMAT(signup_date, '%b %Y') as joindate
        , ms.avatar
        , ms.signature
    FROM topics t
INNER
    JOIN boards b
        ON t.boardid = b.boardid
INNER
    JOIN messages m
        ON t.topicid = m.topicid
INNER
    JOIN users u
        ON m.author = u.username
INNER
    JOIN misc ms
        ON ms.userid = u.userid
INNER
    JOIN (SELECT author
               , COUNT(*) as post_count
            FROM messages
          GROUP
            BY author) as tm
        ON tm.author = m.author
    WHERE t.topicname = 'Honeylands Respite' AND b.boardname = (SELECT boardname FROM boards WHERE boardname='General Chit Chat')

I think it's becuase i'm using inner joins and maybe i should be using outer joins

A: The final subquery-based condition
b.boardname = (SELECT boardname FROM boards WHERE boardname='General Chit Chat')

can be simplified to
b.boardname = 'General Chit Chat'

Some questions:

*

*Are you sure that topic 'Honeylands
Respite' exists?

*Are you sure that
board 'General Chit Chat' exists?

*Are
you sure that topic 'Honeylands
Respite' is on board 'General Chit
Chat'?

*Are you sure that there are
any messages on topic 'Honeylands
Respite'?

*What is the structure (and
the purpose) of table misc?

*Should
the join to table misc be an outer
join?

A: Are you 100% sure that your WHERE clause actually has a results set?
Also what is the format of table 'users'?


text:
Q: different link and load library paths using cmake I have two versions of the same library libabc.so, I have to link my program to one version, and load another version when it's executed (loader should load another library when executable is run).
I place the two versions in different paths, how can I specify that using cmake?
I hope I have made myself clear, thank you.

A: @Tsyvarev's comments basically gives the answer, here's a bit more detail.
Say the two versions for link and load are placed in link_path/libabc.so  and load_path/libabc.so, the CMakeLists.txt should be like
...
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_INSTALL_RPATH load_path;${CMAKE_INSTALL_RPATH})  # load path

...
target_link_libraries(xxx link_path/libabc.so)  # link path


text:
Q: Angular 2: How to add dynamically html attributes (aria-hidden = "true") to all elements directly under the body? I have made a custom Modal implementation and want also to ensure accessibility. So when a modal window pops up (modal element is added directly to the document body), all the other elements in body (direct children of body) should have aria-hidden = "true". How can i add this dynamically to all body children?

A: probably the easiest way would be to mark the parent element, which will in turn mark all children as aria-hidden as well. Something like this:
<my-modal></my-modal>

 // All of these will be affected by the aria-hidden of the parent element

      .....

   ....

Apart from that, there is no magical way to just mark all other elements as aria-hidden (that I know of). You'll have to implement the logic yourself.

A: I wrote this one. I don't know how bad/good is using document directly within an Angular App, but it works.
I also save those modified elements in arrays, in order to reverse the changes, after modal is closed.
  // Add aria-hidden="true" to all direct children of the body element (unless the element does not have already)
  Array.from(document.body.children).forEach(function(item) {
    if(!item.hasAttribute('aria-hidden')) {
      this.elementsWithoutAriaHidden.push(item);
      this.renderer.setAttribute(item, 'aria-hidden', true);
    } else if(item.getAttribute('aria-hidden') === 'false') {
      this.elementsWithAriaHiddenFalse.push(item);
      this.renderer.setAttribute(item, 'aria-hidden', true);
    }
  }, this);

*renderer is initialized this way (I have Angular 5):
  constructor(private rendererFactory: RendererFactory2) {
    this.renderer = rendererFactory.createRenderer(null, null);
  }


text:
Q: Android - Encoding image and sending it to the server I am working on encoding the selected image from the gallery and want to send it to the server.
I succeeded to send name and description of the product which is text form.
but, I don't know how to encode image and send it to string form.
On the server side, I need to decode it with php.
My code is...
public class AddEditWishlists extends Activity {

// Client-Server - Start //////////////////////

JSONParser jsonParser = new JSONParser();

// url to create new product
private static String url_create_product = "http://10.56.43.91/android_connect/create_product.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
InputStream is;
// Client-Server - End //////////////////////

//Define Variables
private EditText inputname;
private EditText inputnote;
private Button upload;
private Bitmap yourSelectedImage;
private ImageView inputphoto;
private Button save;
private int id;
private byte[] blob=null;
byte[] image=null;

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

private void setUpViews() {

    inputname = (EditText) findViewById(R.id.inputname);
    inputnote = (EditText) findViewById(R.id.inputnote);
    inputphoto = (ImageView) findViewById(R.id.inputphoto);

    Bundle extras = getIntent().getExtras();

    if (extras != null) {
        id=extras.getInt("id");
        inputname.setText(extras.getString("name"));
        inputnote.setText(extras.getString("note"));

        image = extras.getByteArray("blob");

        String encodedImage = Base64.encodeToString(image , Base64.DEFAULT);

        if (image != null) {
            if (image.length > 3) {
                inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
            }
        }
    }

    //Image Upload Button
    upload = (Button) findViewById(R.id.upload);
    upload.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, 0);
        }
    });

    // Save the data
    save = (Button) findViewById(R.id.save);

    // Save하면 발생되는 이벤트
    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (inputname.getText().length() != 0) {
                AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() {
                    @Override
                    protected Object doInBackground(Object... params) {
                        saveContact();

                        // Client-Server - Start //////////////////////////////////////
                        String name = inputname.getText().toString();
                        String description = inputnote.getText().toString();
                        //String photo = inputphoto.getContext().toString();
                        encodedImage = yourSelectedImage.toString();

                        // Building Parameters
                        List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                        params1.add(new BasicNameValuePair("name", name));
                        params1.add(new BasicNameValuePair("description", description));
                        params1.add(new BasicNameValuePair("photo", encodedImage));

                        Log.v("log_tag", System.currentTimeMillis()+".jpg");

                        // getting JSON Object
                        // Note that create product url accepts POST method
                        JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params1);

                        // check log cat fro response
                        Log.d("Create Response", json.toString());

                        // check for success tag
                        try {
                            int success = json.getInt(TAG_SUCCESS);

                            Log.v("log_tag", "In the try Loop" );

                            if (success == 1) {
                                // closing this screen
                                finish();
                            } else {
                                // failed to create product
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        return null;
                    }

                    @Override
                    protected void onPostExecute(Object result) {
                        finish();
                    }
                };

                saveContactTask.execute((Object[]) null);

            } else {
                AlertDialog.Builder alert = new AlertDialog.Builder(
                        AddEditWishlists.this);
                alert.setTitle("Error In Save Wish List");
                alert.setMessage("You need to Enter Name of the Product");
                alert.setPositiveButton("OK", null);
                alert.show();
            }
        }
    });
}

// If users save data, this will act (data -> db)
private void saveContact() {

    if(yourSelectedImage!=null){
        ByteArrayOutputStream outStr = new ByteArrayOutputStream();
        yourSelectedImage.compress(CompressFormat.JPEG, 100, outStr);
        blob = outStr.toByteArray();
    }

    else{blob=image;}

    // Change Text type to string type to save in the DB
    SQLiteConnector sqlCon = new SQLiteConnector(this);

    if (getIntent().getExtras() == null) {
        sqlCon.insertWishlist(inputname.getText().toString(), inputnote.getText().toString(), blob);
    }

    else {
        sqlCon.updateWishlist(id, inputname.getText().toString(), inputnote.getText().toString(), blob);
    }

}

@Override
protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
    super.onActivityResult(requestCode, resultCode, resultdata);
    switch (requestCode) {
    case 0:
        if (resultCode == RESULT_OK) {
            Uri selectedImage = resultdata.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);

            cursor.close();
            // Convert file path into bitmap image using below line.
            yourSelectedImage = BitmapFactory.decodeFile(filePath);
            inputphoto.setImageBitmap(yourSelectedImage);
        }

    }
}

what I am working on is the part here
if (extras != null) {
        id=extras.getInt("id");
        inputname.setText(extras.getString("name"));
        inputnote.setText(extras.getString("note"));

        image = extras.getByteArray("blob");

        //Here..I encoded the image ***********Is it correct?**********
        String encodedImage = Base64.encodeToString(image , Base64.DEFAULT);

        if (image != null) {
            if (image.length > 3) {
                inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
            }
        }
    }

and...
                        // Client-Server - Start //////////////////////////////////////
                        String name = inputname.getText().toString();
                        String description = inputnote.getText().toString();

// this line should be modified i guess....
String encodedImage = yourSelectedImage.toString();

                        // Building Parameters
                        List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                        params1.add(new BasicNameValuePair("name", name));
                        params1.add(new BasicNameValuePair("description", description));

// This line should be modified i guess..
params1.add(new BasicNameValuePair("photo", encodedImage));

                        Log.v("log_tag", System.currentTimeMillis()+".jpg");

                        // getting JSON Object
                        // Note that create product url accepts POST method
                        JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params1);

                        // check log cat fro response
                        Log.d("Create Response", json.toString());

I wrote annotation where should be corrected....
I think that part makes error..
and one more question is that on the server side, how format should it be to receive the encoded photo? Varchar? char?..
Thank you in advance.


text:
Q: XPath Param Value Is Not Evaluating In Expression The @Value='1' Does not seem to be evaluating in this expression below as it returns both nodes of SEventData instead of only one that has a @Value of '1'. What am I missing?
Source:
<CData>
<SData SKey="006" >

<SEventData SEventOID="UNS" SEventRepeatKey="2">
<FData FOID="REQUIRED" FRepeatKey="1">
<ItemGroupData ItemGroupOID="REQUIRED" ItemGroupRepeatKey="0"
TransactionType="Upsert">
<ItemData ItemOID="REQ" Value="0"  />
</ItemGroupData>
</FData>
</SEventData>

<SEventData SEventOID="UNS" SEventRepeatKey="3">
<FData FOID="REQUIRED" FRepeatKey="1">
<ItemGroupData ItemGroupOID="REQUIRED" ItemGroupRepeatKey="0"
TransactionType="Upsert">
<ItemData ItemOID="REQ" Value="1"  />
</ItemGroupData>
</FData>
</SEventData>

</SData>
</CData>

with expression
//CData[.//SData[@SKey='006']/SEventData/FData/ItemGroupData/ItemData[@ItemOID='REQ' and @Value='1']]//SEventData

returns both instead of one
Element='<SEventData SEventOID="UNS" SEventRepeatKey="2">
  <FData FOID="REQUIRED" FRepeatKey="1">
     <ItemGroupData ItemGroupOID="REQUIRED"
                 ItemGroupRepeatKey="0"
                 TransactionType="Upsert">
        <ItemData ItemOID="REQ" Value="0"/>
     </ItemGroupData>
  </FData>
</SEventData>'
Element='<SEventData SEventOID="UNS" SEventRepeatKey="3">
  <FData FOID="REQUIRED" FRepeatKey="1">
     <ItemGroupData ItemGroupOID="REQUIRED"
                 ItemGroupRepeatKey="0"
                 TransactionType="Upsert">
        <ItemData ItemOID="REQ" Value="1"/>
     </ItemGroupData>
  </FData>
</SEventData>'

A: You can use this XPath in order to locate what you are looking for:
//SEventData[.//FData/ItemGroupData/ItemData[@ItemOID='REQ' and @Value='1']]

Your current XPath expression returns the root node //CData containing in it the following condition: .//SData[@SKey='006']/SEventData/FData/ItemGroupData/ItemData[@ItemOID='REQ' and @Value='1'].
So yes, //CData has inside it the condition as above and when you trying to locate //SEventData inside that //CData it returns you both //SEventData nodes.
What you should do here is to locate //SEventData node itself based on your condition as I wrote at the beginning:
//SEventData[.//FData/ItemGroupData/ItemData[@ItemOID='REQ' and @Value='1']]


text:
Q: how to pass an argument/parameter to an angular application at deploy time I have an angular application and it has some configuration parameters that it reads from a config file, the application loads and the configuration parameters are read and the app is ready to do its work.
Lets simplify and think there is only one parameter.
I want to change that and instead of hard coding the parameter, i want to pass that parameter to the angular app at run time, when the application first gets loaded.
Any thoughts on how to do this?


text:
Q: How to make sure that android view did full layout? I am calling inputView.draw(drawCanvas) in order to save my view to bitmap.
  Bitmap resultBitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
  Canvas drawCanvas = new Canvas(resultBitmap);
  inputView.draw(drawCanvas);

The bitmap does not contain complete view image (my view has custom drawing on canvas- pie chart with legend). The saved bitmap has just part of legend.
Reading javadoc of View.draw(android.graphics.Canvas)

The view must have already done a full layout before this function is called.

How to be sure that view did full layout?
When calling inputView.draw(drawCanvas) my view is rendered and visible on the screen.

A: I think you can check with Layout params.
LayoutParams layoutParams = layout.getLayoutParams();

Then check if is it full (I don't understand what do you mean with "full").

A: Resolved by adding following code
 int measuredWidth = View.MeasureSpec.makeMeasureSpec(viewWidth, View.MeasureSpec.EXACTLY);
 int measuredHeight = View.MeasureSpec.makeMeasureSpec(viewHeight, View.MeasureSpec.EXACTLY);
 inputView.measure(measuredWidth, measuredHeight);
 inputView.layout(0, 0, inputView.getMeasuredWidth(), inputView.getMeasuredHeight());

before drawing to my bitmap.
What is strange, everything worked fine in two of three screens that I have. Saved bitmap was always complete.


text:
Q: WiFi automatically gets disconnected in Ubuntu 20.10 and starts again only on a reboot Whenever I start my Linux system, the WiFi works fine for 20-25 minutes and then abruptly gets disconnected. Then it is not able to detect any hotspots nearby and the wifi symbol becomes like this: WiFi symbol
In the settings, it shows "unavailable"
WiFi Settings
On running lshw -C network, I got this:
ankur@ankurkh1:~$ sudo lshw -C network
[sudo] password for ankur:
  *-generic DISABLED
       description: Wireless interface
       product: RTL8822BE 802.11a/b/g/n/ac WiFi adapter
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:02:00.0
       logical name: wlo1
       version: ff
       serial: 80:91:33:4e:75:e9
       width: 32 bits
       clock: 66MHz
       capabilities: bus_master vga_palette cap_list ethernet physical wireless
       configuration: broadcast=yes driver=rtw_8822be driverversion=5.8.0-48-generic firmware=N/A latency=255 link=no maxlatency=255 mingnt=255 multicast=yes wireless=IEEE 802.11
       resources: irq:140 ioport:3000(size=256) memory:b1200000-b120ffff
  *-network
       description: Ethernet interface
       physical id: 1
       bus info: usb@1:3
       logical name: usb0
       serial: 32:3b:de:72:d8:4a
       capabilities: ethernet physical
       configuration: broadcast=yes driver=rndis_host driverversion=22-Aug-2005 firmware=RNDIS device ip=192.168.42.223 link=yes multicast=yes

The output of rfkill list all is as follows:
ankur@ankurkh1:~$ rfkill list all
0: asus-wlan: Wireless LAN
    Soft blocked: no
    Hard blocked: no
1: asus-bluetooth: Bluetooth
    Soft blocked: no
    Hard blocked: no
2: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no
3: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no

I also tried service NetworkManager restart, but that didn't work as well.


text:
Q: QNAP FTP users cannot login (admin login does work) - not network related This question pertains to a QNAP model TVS-1282T (Version: 4.4.1.1117).
We've been having issues connecting to our FTP over WAN. The admin user is able to connect just fine, but any other user (that does have RW access to the FTP share) cannot.
This is the client (FileZilla) output (personal information is obfuscated).
Status: Resolving address of ftp.<our_domain>
Status: Connecting to <our_wan_ip>:21...
Status: Connection established, waiting for welcome message...
Status: Initializing TLS...
Status: Verifying certificate...
Status: TLS connection established.
Command:    USER ftpuser
Response:   331 Password required for ftpuser
Command:    PASS ********
Response:   530 Login incorrect.
Error:  Critical error: Could not connect to server

I've confirmed the following:

*

*Definitely not a credential typo - I've reset the password multiple times to make sure.

*This is not network related - given that the admin user can connect + the error also happens over LAN.

*Error is not VPN related. I've made sure to test with it off whenever I changed a setting.

*FTP correctly uses the /FTP share.

*ftpuser has RW access on the FTP share.

*Enabling anonymous logins did not seem to help.

The threads I've found from googling have either mentioned outdated firmware (several years ago) or the OP was doing something with SFTP, which is supposed to be admin only. These were not relevant to our case unfortunately.
Did I overlook a setting somewhere? I'm not familiar with the FTP server that QNAP uses so not sure where to start looking on the terminal.
Any help is greatly appreciated!

A: You can try to reboot it.
If the issue persist you can upgrate firmware to lastest version(currently is 4.5.2.1566 build 20210202 of 2021-02-02), you can download it automatically on QNAP or https://www.qnap.com/en/download?model=tvs-1282t&category=firmware

A: Unfortunately I couldn't figure out how to configure the FTP of the QNAP directly so instead I've setup vsftpd (on a VM) and mounted the FTP share via NFS.
Configuration of vsftpd is relatively straightforward through a combination of vsftpd.conf + standard UNIX file permissions. One thing to keep in mind is to keep the UID (and GID if you use those) in sync between the QNAP and the FTP server.
In my case, I created an ftproot user on the QNAP and checked it's ID in the terminal (id ftproot). I then created an ftproot user on the VM with the same UID. All other users and groups I've then set on the FTP machine (as you would in any other case).


text:
Q: How to put an html  inside a json object? I'm creating a json object. How to make this :
{
  "paragraphe_with_link"  : "hello, click here to visit my page"
}

I want to have a simple sentence with clickable "here" in blue standard color, how to do that with json object please ?
Thank you


text:
Q: .htaccess rewrite for for localhost port mapping? I am trying to catch a route some_path on my website and redirect it to a different port on the same server. The following code works on the server, but not on my localhost box. I'm using Ubuntu
<IfModule mod_rewrite.c>

    Options +FollowSymLinks -Indexes
    RewriteEngine on
    RewriteBase /

    # Works on the server
    RewriteRule ^some_path/(.*)$ http://remoteserver.com:1337/$1 [P,L]

    # Does not work on the localhost
    RewriteRule ^some_local_path/(.*)$ http://localhost:1337/$1 [P,L]

</IfModule>

A: I suspect 2 things:

*

*You don't have mod_proxy enabled on local Ubuntu

*You may not have anything running on port # 1337

A: Make sure to have mod_proxy loaded. If mod_proxy isn't loaded, the P flag won't proxy, it'll simply redirect.


text:
Q: Flutter ADB error: ADB exited with exit code 1 performing streamed install Launching lib\main.dart on SM G955F in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\flutter-apk\app-debug.apk.
error: closed
Installing build\app\outputs\flutter-apk\app.apk...
Error: ADB exited with exit code 1
Performing Streamed Install
adb: connect error for write: closed
Error launching application on SM G955F.
This is just the default stuff. I haven't changed anything

A: Check this thread: Error: ADB exited with exit code 1 Performing Streamed Install
It has multiple solutions that cover lots of the cases. Are you using emulator or physical device?
Was it working before? Have you installed any other apps successfully?


text:
Q: How to determine if MySQL collation is case sensitive or not? I know most MySQL instances out there 'act' case-insensitive by default. But I know that you can use a case sensitive collation if you want to.
Know would there be a function to check if the collation is case sensitive or not?
The problem I want to fix is that if you use LOWER in queries, MySQL can't use an index, even though it might not be needed at all to LOWER because of said case insensitivity.
Regards,
Michiel.

A: Usually the case sensitive collations end in "bin" as in "binary".
As it seems you want to check upfront and then build your queries accordingly with or without a function call, you could simply check the collation of your table/column and if it ends in "bin" you have a case sensitive one at hand.


text:
Q: Phase-space average equal to the quantum mechanical average in the early universe I was reading  Mukhanov's book of cosmology http://www.amazon.com/Physical-Foundations-Cosmology-Viatcheslav-Mukhanov/dp/0521563984 , specifically about symmetry restoration in the early universe where he is calculating the vacuum and thermal contributions to the effective potential of a hypothetical scalar fied  and, at the end of page 167 he does the following affirmation:
In a homogeneous and isotropic universe the spatial average can be replaced by the quantum average.
As far as I know from quantum statistical mechanics, the unique way to make sense to this affirmation is to consider

*

*the spatial average as the phase-space average and

*that the state (vector) of the system is precisely known, meaning that this state is a pure state.

I suspect that this is indeed the case since but I am not sure about it. Can anyone explain this?


text:
Q: Should the website main page be cached? To my knwoledge, caching should be ONLY enabled for static contents of website, and we use no-cache for dynamic pages. The website main page is the most dynamic page as contents are regularly updated. Strangely, I found that major websites set a short cache maxage for the main page too. Google set 3 seconds, stackoverflow 21 seconds.
More strangely (to me), when analyzing the performance by WebPageTest.org, it considers the main page as a static content, and expects a long cache lifetime. For example, you'll receive a FAILED notice for short 21s cache lifetime of stackoverflow.com. Check HERE. Even for 2 hours, you'll receive WARNING.
How the main page and other dynamic pages should be cached?

A: Any page should be cached if it's useful to do so - whether static or dynamic. Not caching dynamic pages becomes suicidal when running a high-traffic site, as the unnecessary repeated requests will bring the site to its knees.
Of course, it all depends on the expected update frequency, which will differ not only from site to site, but also from page to page: if your "about us" page might change once a week, there is no point in making it expire in 1 minute; OTOH, if the frontpage changes every second, it may be useful to set its expiration time to 21 seconds, as the update latency <1 min is acceptable, yet the 20 seconds where a refresh doesn't necessarily send a HTTP request are quite useful for lowering load.
In other words, there is no hard rule, handed down on stone tablets from Mount Sinai, saying "Thou Shalt Cache The Front Page For One Day", nor "Thou Shalt Not Cache Dynamic Content" - it depends very much on the specific situation of a site.

A: Ideally, you should cache everything including the dynamic pages as well. Static pages/resources can be cached with a very high max-age as generally they wouldn't change that often and even if they do change, you could change the request url (by adding QS) to avoid the cache entry.
Caching dynamic pages is a bit tricky as the content changes quite frequently. If possible you should try implementing If-Modified-Since for the dynamic pages, where in the If-Modified-Since is the timestamp of the last time your page or the sub-section was changed. Generally, If-Modified-Since would be a DateModified timestamp column in your database for that particular entity. If your page is being composed of multiple db entities, then If-Modified-Since would be the min of DateModified for those entries. Implementing If-Modified-Since is actually a bit of hassle so a lot of people just leave their dynamic pages as is but do keep in mind it is really helpful if your page/site is pretty popular and crawled by SEs quite often.

A: Cache whatever you can on the server - menus, header and footer regions, banners. On the client-side, cache the HTTP resources (JavaScript, CSS and images).
If the page is dynamic then of course you can't cache it for 7 days, and yes, this would make it slower than a site that was doing that. However, these are examples of the trade-off between features and speed.
As the owner of the site, you need to make the call where the optimum user experience is - no automated test is going to tell you that.


text:
Q: Cannot set baud rate on USB serial port for Ubuntu 12.04 I just upgraded from Ubuntu 10.04 on a project that connects an embedded device through a USB serial port at 115,200 baud. After upgrading this, it did not work, but I rebooted and was able to connect. Since shutting down and restarting my system I have not been able to connect. The serial line looks like it is connected at the wrong baud rate (fast string of characters like looking like:
"'''''''''''''''''ppppp'''''''''''''''pppppp'''''''''''"...

The USB device is being recognized and set up as /dev/ttyUSB0. When I try setting the baud rate with stty I get:
$ sudo stty -F /dev/ttyUSB0 115200
stty: /dev/ttyUSB0: unable to perform all requested operations

If I try setting to 9600 it seems to work:
$ sudo stty -F /dev/ttyUSB0 9600

But anything else fails:
$ sudo stty -F /dev/ttyUSB0 4800
stty: /dev/ttyUSB0: unable to perform all requested operations

Here is what stty sees:
$ stty -F /dev/ttyUSB0
speed 9600 baud; line = 0;
min = 1; time = 0;
-brkint -icrnl -imaxbel
-opost -onlcr
-isig -icanon -iexten -echo -echoe -echok -echoctl -echoke

I can change other values using stty (echo, echoe, etc.), but not the baud rate.
I saw a comment online that someone could set baud with Minicom, but not from the command line, so I got Minicom and tried it, but I get the same result (what appears to be the wrong baud rate).
I also tried setserial, but that also refuses to accept the /dev/ttyUSB devices:
$ sudo setserial  /dev/ttyUSB0 -a
Cannot get serial info: Invalid argument
$ sudo setserial  /dev/ttyS0 -a
/dev/ttyS0, Line 0, UART: 16550A, Port: 0x03f8, IRQ: 4
    Baud_base: 115200, close_delay: 50, divisor: 0
    closing_wait: 3000
    Flags: spd_normal skip_test

Finally, here are the devices, and their setup from dmesg:
$ ls -l /dev/ttyUSB*
crw-rw-rw- 1 root dialout 188, 0 Nov 19 15:53 /dev/ttyUSB0
crw-rw-rw- 1 root dialout 188, 1 Nov 19 16:00 /dev/ttyUSB1
$ dmesg | grep ttyUSB
[   32.444445] usb 4-1: generic converter now attached to ttyUSB0
[   32.444549] usb 8-2: generic converter now attached to ttyUSB1

I had been working with this device under Ubuntu 10.04 for a few months and was able to use them last week, but since shutting down and rebooting I have not been able to. I've looked online and found a few people with a similar problem, but none with solutions. How can I fix this problem?

A: I still don't know what happened, but it is working now. For anyone who runs into the same problem, I tried "modprobe -r usbserial" (my thought was to see if the old driver could be loaded with modprobe -f; it couldn't), and then reloaded the module "modprobe usbserial". This time the serial worked correctly - I don't know why.
Now when I do stty it reports:
~$ stty -F /dev/ttyUSB0
speed 115200 baud; line = 0;
min = 1; time = 0;
-brkint -icrnl -imaxbel
-opost
-isig -icanon -iexten -echo

and I can change the baud rate (I changed it to 9600 and then back to 115200).
So there is no satisfactory answer, but apparently playing with it can make it work - just like it started working the first time after a reboot.

A: Write permission to the device file is required to change the settings. You can control it
with simple listing. Eg.
$ ls -l
crw-rw-r-T 1 root dialout 188, 0 jan    9 16:16 /dev/ttyUSB0

In the case above everybody have read permission (r) the superuser root
and the dialout group have write permission too (rw).
If you are member of the dialout group you can change the speed
without any extra thing by the above mentioned stty -F /dev/ttyUSB0 115200
command otherwise you need use sudo.
You can control your membership status with the id command.


text:
Q: Django: how can I a create categories field/dropdown menu? This is a very simple question, how can I create dropdown field in Django with only specific categories(something similar to the countries dropdown, but not with countries).

A: With the choice attribute of a Field if it is for fixed values. Or with a ForeignKey field if the Categories should be created dynamicly.
For the ForeignKey field you would do the following:
from django.db import models

class Category(models.Model):
    name = models.Charfield(max_length=255)
    # ...

    def __str__(self):
        return self.name

class Item(models.Model):
    category = models.ForeignKey(Category)
    # ...

A: Django's most powerful feature is to offer you direct forms.
It's a broad question but you want to define a model that can be paired with a form that you can put in a template.
Take a look here: https://docs.djangoproject.com/en/1.8/topics/forms/ and here:
Django options field with categories and here Creating a dynamic choice field


text:
Q: Percentile rank over multiple partitions averages Assume I have a table like this

id
cnt
tier

1
100
gold

2
200
silver

3
300
bronze

4
400
bronze

5
500
bronze

6
600
gold

7
700
silver

8
800
silver

9
900
silver

10
1000
silver

and if I want percentile rank over cnt within each tier (e.g.
For tier 'gold', I have 2 rows, cnt = 100 and cnt = 600, so they're ranked at 0.0 percentile and 1.0 percentile respectively.)
I can easily do PERCENT_RANK() OVER(PARTITION BY tier ORDER BY cnt) AS percentile1, thus

id
cnt
tier
percentile1

1
100
gold
0.0

2
200
silver
0.0

3
300
bronze
0.0

4
400
bronze
0.5

5
500
bronze
1.0

6
600
gold
1.0

7
700
silver
0.25

8
800
silver
0.5

9
900
silver
0.75

10
1000
silver
1.0

Now what if I want a percentile rank over cnt but among all tiers' averages? To better illustrate, we have gold's avg = 350, silver's avg = 720, and bronze's avg = 400, so to get cnt's percentile rank among [350, 400, 720] for each row. i.e.

id
cnt
tier
percentile2

1
100
gold
0.0

2
200
silver
0.0

3
300
bronze
0.0

4
400
bronze
0.333

5
500
bronze
0.666

6
600
gold
0.666

7
700
silver
0.666

8
800
silver
1.0

9
900
silver
1.0

10
1000
silver
1.0

How should I write the (Hive) SQL? Thanks

A: I'd compute the averages and join it to the original table. To rank with respect to the averages, I added a placeholder row to hold the original row.
select * from (
  select *, PERCENT_RANK() OVER(PARTITION BY id order by avg_cnt) AS percentile1 from (
    select
        t2.*,
        t1.avg_tier,
        case t1.avg_tier == "original_row" when true
            then t2.cnt else t1.avg_cnt end as avg_cnt
    from YOUR_TABLE t2
    join (
      -- find averages and add a placeholder row
      select tier as avg_tier, avg(cnt) as avg_cnt from YOUR_TABLE group by 1
      union
      select "original_row", -1 as avg_cnt  -- placeholder row
    ) t1
  ) t3
) t4
where avg_tier="original_row"; -- filter the original row

Before using PERCENT_RANK(), this is what the joined table looks like.

t2.id
t2.cnt
t2.tier
t1.avg_tier
avg_cnt

1
100
gold
original_row
100

1
100
gold
bronze
400

1
100
gold
gold
350

1
100
gold
silver
720

...

A: Try something like this. First you use CTE to compute averages, then use it to obtain the desired percentile ranks.
Update: I also added a correction to deal with ties.
with cte as
(
select tier, avg(cnt) avg_cnt
from mytable
group by tier
)
select id,cnt,tier,
((select cast(count(*) as double) from cte where t.cnt > avg_cnt)
+ (select cast(count(*)/2 as double) from cte where t.cnt = avg_cnt)
)
/ (select cast(count(*) as double) from cte)
from mytable t

A: I don't have hive in my machine. do we have crossapply in Hive or equivalent.
Can try something like this and apply rant on avg percentage.
select t1.*, 1.00*t1.cnt/a.avg_cnt
from test t1
cross apply (select tier, avg(cnt) avg_cnt
             from test t2
             where t1.tier=t2.tier
             group by tier) A

A: Here's a solution with one CTE, and one Window. I've named the main table tests.
with ranks as (
  select
    avg(cnt) as t1,
    lead(avg(cnt)) over w as t2,
    percent_rank() over w as percentile2
  from (select * from tests union select null, -1, null) as n
  group by tier
  window w as (order by avg(cnt))
)
select tests.*, percentile2
from tests
join ranks
  on (tests.cnt > t1 and (tests.cnt <= t2 or t2 is null))

Results:
| id  | cnt  | tier   | percentile2        |
| --- | ---- | ------ | ------------------ |
| 1   | 100  | gold   | 0                  |
| 2   | 200  | silver | 0                  |
| 3   | 300  | bronze | 0                  |
| 4   | 400  | bronze | 0.3333333333333333 |
| 5   | 500  | bronze | 0.6666666666666666 |
| 6   | 600  | gold   | 0.6666666666666666 |
| 7   | 700  | silver | 0.6666666666666666 |
| 8   | 800  | silver | 1                  |
| 9   | 900  | silver | 1                  |
| 10  | 1000 | silver | 1                  |

This SQL is using Postgres syntax, but it should still work in Hive.
The idea is that you first create your ranks by averaging the tier counts and adding an additional dummy row so that it creates 4 ranks instead of 3. That's the union. The lead makes it so that each row in the CTE contains the lower and upper bounds of the rank (t1 and t2).
Then it's just a matter of joining on that CTE where the cnt falls between t1 and t2.


text:
Q: Enable / Disable Swipe on radlistview I'm building an app using nativescript, javascript and telerik ui.
I need need to know how crate a function to enable / disable the swipaction on radlistview by code.
Best regards

A: When using the swipeActions="true" of RadListView from the nativescript-telerik-ui plugin in order to implement an enable/disable solution all that you need to do is:

*

*Attach an handle for the itemSwiping event as shown here

*In the handler set the returnValue of the arguments to the desired boolean value, as shown here
The same example is available in the official nativescript-telerik-ui sdk repository for Angular here and for Vanila {N} here (look for the files with swipe-disable in their name)


text:
Q: What is the base of the logarithm in Log Transformation in image processing? I am reading gonzales image processing book and as you know the log transformation has been defined like the following in the book:
s = c*log(1+r)

Now I have one question:
Is the logarithm based on 10 or it is a natural logarithm which is based on napier number?

A: The log transform is used for dark pixels enhancement. The dark pixels in an image are expanded as compare to the higher pixel values. So the base can be any number depending on the visualization effect of image.
I think log10 is often used because it is related to the decibel scale in signal processing, such as what is used in signal to noise definition.

A: If this is log() from math.h, then it's the natural logarithm.
That is, it's base is e, which is approximately 2.71828.


text:
Q: Tumblr API PHP Array response into usable code in HTML and PHP Array (
    [meta] => Array (
    [status] => 200 [msg] => OK )
    [response] => Array (
        [user] => Array (
            [name] => paulkin360
            [likes] => 0
            [following] => 2
            [default_post_format] => html
            [blogs] => Array (
                [0] => Array (
                    [name] => paulkin360
                    [url] => http://paulkin360.tumblr.com/ [
                    [followers] => 0
                    [primary] => 1
                    [title] => Untitled
                    [description] =>
                    [admin] => 1
                    [updated] => 1379175176
                    [posts] => 2
                    [messages] => 0
                    [queue] => 0
                    [drafts] => 0
                    [share_likes] => 1
                    [ask] =>
                    [tweet] => auto
                    [facebook] => auto
                    [facebook_opengraph_enabled] => Y [type] => public
                )
            )
        )
    )
)

So far that is what I have but I would want to reorganise this in html

A: This is an example of usage to get you started, you'll need to build the actual HTML yourself.
<?php
$user = $your_array['response']['user'];
?>

Name: <?php echo $user['name']; ?>

Likes: <?php echo $user['likes']; ?>

Following: <?php echo $user['following']; ?>

<?php foreach($user['blogs'] as $blog): ?>

Name: <?php echo $blog['name']; ?>

URL: <?php echo $blog['url']; ?>

Followers: <?php echo $blog['followers']; ?>

Title: <?php echo $blog['title']; ?>

<?php endforeach; ?>


text:
Q: Can I slice a flex cable to reduce its width? I have a cable for my raspberry Pi camera that is bulky in its current wide state. While tricky, is there any downside to slicing it length wise, and stacking the pieces on top of each other? Would there be too much interference?
I also have a thicker cable that feeds a display that I would like to make narrower (see picture)

A: Yes, you can separate two parts of the ribbon cable relatively easy. You could just fold it in half too. If you separate them there may be interference if you separate a high frequency signal from its matching ground wire, or if you put the wrong one on top of each other. But this is highly dependent on the application of the wire. It wouldn't hurt to test it out.


text:
Q: How do I take multiple slices of a dataframe based on the value in single cells (row/column intersection)? I am trying to analyse a time series of stock prices and want to take slices of the dataframe where the value in a column meet a certain criteria.
For the purpose of illustration, consider the following:
I have a time series dataframe of the stock price of Musgrave Minerals and am looking for occassions on which the share price increased by 20% or more within three days. That part is simple and I have the following code to achieve that:
import pandas_datareader.data as web
df = web.DataReader('MGV.AX', 'yahoo' )
df_20 = df[df.pct_change(periods = 3)['Adj Close'] >= 0.2]
df_20
    High    Low Open    Close   Volume  Adj Close
Date
2018-10-28  0.081   0.064   0.064   0.075   11177031    0.075
2018-10-29  0.081   0.074   0.074   0.079   4327736 0.079
2018-10-30  0.079   0.074   0.078   0.078   1273789 0.078
2019-07-04  0.068   0.066   0.067   0.068   3431060 0.068
2019-12-02  0.100   0.083   0.086   0.096   12055640    0.096
2020-05-19  0.135   0.125   0.125   0.130   1947179 0.130
2020-05-20  0.160   0.130   0.130   0.155   8608597 0.155
2020-05-21  0.180   0.150   0.150   0.175   8580197 0.175
2020-05-22  0.170   0.150   0.165   0.165   10210411    0.165
2020-06-03  0.290   0.215   0.270   0.260   36446028    0.260
2020-06-04  0.270   0.225   0.245   0.235   14611718    0.235
2020-06-05  0.265   0.235   0.250   0.240   10751744    0.240
2020-06-10  0.435   0.330   0.345   0.415   37203724    0.415
2020-06-11  0.465   0.380   0.420   0.380   42022170    0.380
2020-06-12  0.425   0.350   0.350   0.420   15112508    0.420
2021-05-19  0.430   0.390   0.390   0.420   5093006 0.420

So there were 16 occassions on which the criteria were met.
Now for each occurrence, I want to take a slice that extends 5 rows (trading days) before the event and 5 rows after the event. I can't find anything online that would assist me. Is there a way of doing this using Pandas?
Whilst I could export the dataframe to Excel and perform the analysis there, I'm sure that Python can provide a quicker and better solution.


text:
Q: Crear una curva de Berzier con N puntos Canvas Estuve investigando bastante y no encontré en ninguna parte alguna forma de hacer una Curva de Berzier libremente, siempre condicionado con funciones, de estar en lo contrario, agradecería que me corrigiera en mi error. Y al menos con canvas se encuentran varias formas predeterminadas para hacerlo.
Como por ejemplo:
context.quadraticCurveTo(130,5,180,160);

context.bezierCurveTo(10,40,120,-30,190,190);

Y según Wikipedia:
La formula para las Curvas lineales de Bézier.

La formula para las Curvas cuadráticas de Bézier.

Y por último, la formula para las Curvas cúbicas de Bézier.

Como yo lo veo en las tres funciones siempre hay un patrón, el cual es marcada por la generalización.

A: Tomando en cuenta eso, se me ocurrió este pequeño ejemplo que realiza lo que la generalización indica

(function () {
    'use strict'
    var canvas, context, Sx, Sy, x, y, scale; // Estas son declaraciones de variables

    canvas = document.getElementById('canvas');
    context = canvas.getContext('2d');
    Sx = (window.innerWidth - (window.innerWidth * .011));
    canvas.width = Sx;
    Sy = (window.innerHeight - (window.innerHeight * .15));
    canvas.height = Sy;
    x = Sx / 2;
    y = Sy / 2;
    scale = 5;

    function clear() { // Función para limpiar canvas
        context.clearRect(0, 0, Sx, Sy);
    }

    function grid() { // Función para crear el background
        context.lineWidth = .5;
        context.strokeStyle = '#00ffee';
        context.beginPath();
        for (let i = x; i < Sx; i += scale) {
            context.moveTo(i, 0);
            context.lineTo(i, Sy);
        }
        for (let i = x; i > 0; i -= scale) {
            context.moveTo(i, 0);
            context.lineTo(i, Sy);
        }
        for (let i = y; i < Sy; i += scale) {
            context.moveTo(0, i);
            context.lineTo(Sx, i);
        }
        for (let i = y; i > 0; i -= scale) {
            context.moveTo(0, i);
            context.lineTo(Sx, i);
        }
        context.stroke();
        context.closePath();
    }

    function calPoint([nx, ny]) {

// Esta función es para poder transformar las coordenadas en coordenadas según canvas,
// ya que canvas solo cuenta un cuadro que inicia con la parte superior izquierda
// Por lo que  requiere una conversión

        return [x + nx * scale, y - ny * scale];
    }

    function berzierPoints(Points, t) {

// Esta función es la encargada de transformar todos los puntos en puntos de berzier según *t*

        let val = Points.length - 1;
        let x = 0, y = 0; // Ya que los puntos son el resultados de la suma del seguimiento, se inicializan a cero
        for (let i = 0; i < Points.length; i++) {
            if (i == 0) { // La primera coordenada siempre recibirá este parámetro
                x += Points[i].x * Math.pow(1 - t, val);
                y += Points[i].y * Math.pow(1 - t, val);
            } else if (i == val) { // Al igual que el último
                x += Points[i].x * Math.pow(t, i);
                y += Points[i].y * Math.pow(t, i);
            } else { // Los demás siempre serán la multiplicación de la cantidad de puntos sin contar el primero
// Después t se elevará según su posición y se multiplicará
// Y por último (1 - t) se elevará a la cantidad de puntos (sin contar el primero) menos su posición
                x += Points[i].x * val * Math.pow(t, i) * Math.pow(1 - t, val - i);
                y += Points[i].y * val * Math.pow(t, i) * Math.pow(1 - t, val - i);
            }
        }
        return calPoint([x, y]);
    }

    function berzier(Points) {
// Lo siguiente es para poder ubicar los puntos en el plano a través de cirulos rojos
        for (let i = 0; i < Points.length; i++) {
            context.strokeStyle = 'red';
            context.beginPath();
            let [x, y] = calPoint([Points[i].x, Points[i].y]);
            context.arc(x, y, scale, 0, 2 * Math.PI, false);
            context.stroke();
            context.closePath();
        }
        context.strokeStyle = 'purple';
        context.beginPath();
        let [x, y] = berzierPoints(Points, 0.001);
// Se debe iniciar con la parte más pequeña de una centésima ingresandola cono *t*
        context.moveTo(x, y);
// De ahí avanza el recorrimiento en 0.001 cada ciclo hasta llegar a 1
        for (let i = 0.002; i <= 1; i += 0.001) {
            let [x, y] = berzierPoints(Points, i);
            context.lineTo(x, y);
        }
        context.stroke();
        context.closePath();
    }

    function xy() { // Función para dibujar lineas de X & Y
        context.strokeStyle = '#000';
        context.beginPath();
        context.moveTo(0, y);
        context.lineTo(Sx, y);
        context.stroke();
        context.moveTo(x, 0);
        context.lineTo(x, Sy);
        context.stroke();
        context.closePath();
        context.font = "20px Arial";
        context.fillStyle = "red";
        context.fillText("Y", x - 20, 20);
        context.fillText("X", Sx - 20, y + 20);
    }

    function draw() {
        grid();
        xy();
    }

    document.getElementById('draw').addEventListener('click', e => {
        let x = document.querySelectorAll('[id^=X]'), // Busca todos los inputs que inicien con X
            y = document.querySelectorAll('[id^=Y]'), // Buscan todos los inputs que inicien con Y
            Points = new Array(), // Crea el arreglo de los puntos de coordeadas
            cont = 0; // Ya que posiblemente no se llenarán todos los inputs se busca llenarlos según sean aceptados
        for (let i = 0; i < x.length; i++) {
            if (!isNaN(x[i].value) && x[i].value != '' && !isNaN(y[i].value) && y[i].value != '') {
                Points[cont] = {
                    x: parseFloat(x[i].value),
                    y: parseFloat(y[i].value)
                }
                cont++;
            }
        }
        clear();
        grid();
        berzier(Points);  // Y lo introduce en la función Berzier
        xy();
    });

    draw();
})();
canvas {
  border: solid black;
}

input {
  width: 50px;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Berzier</title>
    <link rel="stylesheet" href="./styles.css">
</head>

<body>
    <canvas id="canvas"></canvas>
    <input type="number" id="X" placeholder="x">
    <input type="number" id="Y" placeholder="y">
    ||
    <input type="number" id="X1" placeholder="x1">
    <input type="number" id="Y1" placeholder="y1">
    ||
    <input type="number" id="X2" placeholder="x2">
    <input type="number" id="Y2" placeholder="y2">
    ||
    <input type="number" id="X3" placeholder="x3">
    <input type="number" id="Y3" placeholder="y3">
    ||
    <input type="number" id="X4" placeholder="x4">
    <input type="number" id="Y4" placeholder="y4">
    ||
    <input type="number" id="X5" placeholder="x5">
    <input type="number" id="Y5" placeholder="y5">
    ||
    <input type="number" id="X6" placeholder="x6">
    <input type="number" id="Y6" placeholder="y6">
    ||
    <input type="number" id="X7" placeholder="x7">
    <input type="number" id="Y7" placeholder="y7">
    ||
    <input type="number" id="X8" placeholder="x8">
    <input type="number" id="Y8" placeholder="y8">
    ||
    <input type="number" id="X9" placeholder="x9">
    <input type="number" id="Y9" placeholder="y9">
    ||
    <input type="number" id="X10" placeholder="x10">
    <input type="number" id="Y10" placeholder="y10">
    ||
    <input type="number" id="X11" placeholder="x11">
    <input type="number" id="Y11" placeholder="y11">
    ||
    <input type="number" id="X12" placeholder="x12">
    <input type="number" id="Y12" placeholder="y12">
    ||
    <input type="number" id="X13" placeholder="x13">
    <input type="number" id="Y13" placeholder="y13">
    <hr />
    <button id="draw">Draw</button>
    <script src="./main.js"></script>
</body>

</html>


text:
Q: Quiero un formulario en RoR donde se coloca un departamento las ciudades se cambien es decir si coloco amazonas se coloquen las ciudades de este <%= form_for(@usuario) do |f| %>

    <% if @usuario.errors.any? %>

<%=pluralize(@usuario.errors.count, "error") %>

                <% @usuario.errors.full_messages.each do |msg| %>

<%= msg %>

                <% end %>

    <% end %>

        <%= f.label :nombre%>

        <%= f.text_field :nombre%>

        <%= f.label :apellido%>

        <%= f.text_field :apellido%>

        <%= f.label :genero%>

        <%= f.select :genero, ["Seleccione uno","H","M","Otro","Prefiero no decirlo"],selected:"Seleccione uno" %>

        <%= f.label :tipo_de_identificacion%>

        <%= f.select :tipo_de_identificacion, ["Seleccione uno","T.I","C.C","C.E"],selected:"Seleccione uno" %>

        <%= f.label :numero_de_identifacion%>

        <%= f.text_field :numero_de_identifacion%>

        <%= f.label :email%>

        <%= f.text_field :email%>

        <%= f.label :password %>

        <%= f.text_field :password%>

        <%= f.label :password_confirmation, "Confirmacion" %>

        <%= f.text_field :password_confirmation%>

        <%= f.label :fecha_de_nacimiento%>

        <%= f.date_field :fecha_de_nacimiento%>

                Departamento
                Ciudad o Municipio
                Barrio

                <%= f.select :departamento, ["","Amazonas","Antioquia","Arauca","Atlántico","Bogotá","Bolívar","Boyacá","Caldas","Caquetá","Casanare","Cauca","Cesar","Chocó","Córdoba","Cundinamarca","Guainía","Guaviare","Huila","La Guajira","Magdalena","Meta","Nariño","Norte de Santander","Putumayo","Quindío","Risaralda","San Andrés y Providencia","Santander","Sucre","Tolima","Valle del Cauca","Vaupés","Vichada"],selected:"" %>
#aqui trate de colocar un if para ver si se actualizaban pero se cambia
<% if :departamento == "Amazonas"%>
                    <%= f.select :ciudad, ["","Amazonas1","Antioquia","Arauca","Atlántico"],selected:"" %>
                <% elsif :departamento == "Antioquia"%>
                    <%= f.select :ciudad, ["","Amazonas2","Antioquia","Arauca","Atlántico"],selected:"" %>
                <% end %>
                <%= f.text_field :barrio %>

        <%= f.label :direccion %>

        <%= f.text_field :direccion%>

        <%= f.label :codigo_postal%>

        <%= f.text_field :codigo_postal%>

        <%= f.submit 'Guardar'%>

<% end %>


text:
Q: Django display radio button choice i want to display vaule_fields of my User model as selectable choice radiobuttons, any idea how to do this?
...

template.html
....

currently they are displayed as input fields?!

A: Here is an example of gender choices displayed as radio buttons.
MODELS.PY ********************************************************
#GENDER CHOICES OPTIONS
    GENDER_COICES = (
    ('M', 'Male'),
    ('F', 'Female'),
    ('O', 'Other'),
   )

gender = models.CharField(max_length=3, choices=GENDER_COICES,
 default="N/A")
*****************************************************************

FORMS.PY ********************************************************
class UserQForm(UserCreationForm):
    """ This is a form used to create a user. """

    # Form representation of an image
    QUserPictureProfile = forms.ImageField(label="Profile Picture",
     allow_empty_file=True, required=False)

    password1 = forms.CharField(label="Password", max_length=255,
     widget=forms.PasswordInput())

    password2 = forms.CharField(label="Confirmation", max_length=255,
     widget=forms.PasswordInput())

    #GENDER CHOICES OPTIONS
    GENDER_COICES = (
      ('M', 'Male'),
      ('F', 'Female'),
      ('O', 'Other'),
    )

    gender = forms.ChoiceField(widget=forms.RadioSelect(), choices=GENDER_COICES)

    class Meta:

        model = QUser

        fields = ('QUserPictureProfile', 'gender',
        'email', 'first_name', 'last_name', 'date_of_birth', 'password1',
         'password2','phone_number',)

    def clean(self):
        """ Clean form fields. """

        cleaned_data = super(UserQForm, self).clean()

        password1 = cleaned_data.get("password1")
        password2 = cleaned_data.get("password2")

        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords do not match!")


text:
Q: error with openCV2 I am new in coding. Using this script:
from PIL import Image
from PIL.ImageChops import subtract
import numpy, math, time, glob, sys, os, logging, requests, random

def GreenScreen(infile, inbg ,outfile='output.png', keyColor=None,tolerance=None):
    """
    http://gc-films.com/chromakey.html
    http://www.cs.utah.edu/~michael/chroma/
    :param infile:      Greenscreen image location
    :param inbg:        Background image location
    :param outfile:     Output file location
    :param keyColor:    greenscreen color; it can be any singular color
    :param tolerance:   tolerance of cleaning
    :return:
    """

    if not keyColor:
        keyColor = [151,44,21] #Y,Cb, and Cr values of the greenscreen

    if not tolerance:
        tolerance = [100,130] #Allowed Distance from Values

    #open files
    inDataFG = Image.open('/home/leonardo/Scrivania/in/KVfnt.png').convert('YCbCr')
    Path = '/home/leonardo/Scrivania/background/'
    FullPath = os.path.join(Path, random.choice(os.listdir(Path)))
    BG = Image.open(FullPath).convert('RGB')
    [Y_key, Cb_key, Cr_key] = keyColor
    [tola, tolb]= tolerance

    (x,y) = inDataFG.size #get dimensions
    foreground = numpy.array(inDataFG.getdata()) #make array from image
    maskgen = numpy.vectorize(colorclose) #vectorize masking function

    alphaMask = maskgen(foreground[:,1],foreground[:,2] ,Cb_key, Cr_key, tola, tolb) #generate mask
    alphaMask.shape = (y,x) #make mask dimensions of original image
    imMask = Image.fromarray(numpy.uint8(alphaMask))#convert array to image
    invertMask = Image.fromarray(numpy.uint8(255-255*(alphaMask/255))) #create inverted mask with extremes

    #create images for color mask
    colorMask = Image.new('RGB',(x,y),tuple([0,0,0]))
    allgreen = Image.new('YCbCr',(x,y),tuple(keyColor))

    colorMask.paste(allgreen,invertMask) #make color mask green in green values on image
    inDataFG = inDataFG.convert('RGB') #convert input image to RGB for ease of working with
    cleaned = subtract(inDataFG,colorMask) #subtract greens from input
    BG.paste(cleaned,imMask)#paste masked foreground over background

    # BG.show() #display cleaned image
    BG.save(outfile, "JPEG") #save cleaned image

def colorclose(Cb_p,Cr_p, Cb_key, Cr_key, tola, tolb):
    temp = math.sqrt((Cb_key-Cb_p)**2+(Cr_key-Cr_p)**2)
    if temp < tola:
        z = 0.0
    elif temp < tolb:
        z = ((temp-tola)/(tolb-tola))
    else:
        z = 1.0
    return 255.0*z

def check_folders(logger):
    if not os.path.exists('out/'):
        os.mkdir('out/')
    if not os.path.exists('background/'):
        os.mkdir('background/')
        logger.error("Place background images in background/")
        sys.exit()
    if not os.path.exists('in/'):
        os.mkdir('in/')
        logger.error("Place input files in in/")
        sys.exit()

def begin_greenbox(logger):
    """
    For all backgrounds loop through all input files into the out file
    """
    for bg in glob.glob('background/*'):
            continue
    bg_name = bg.split('/')[-1].lower().strip('.jpg').strip('.png').strip('.jpeg')
    for picture in glob.glob('in/*'):
                continue
    pic_name = picture.split('/')[-1].lower().strip('.JPG').strip('.png').strip('.jpeg')
    output_file = 'out/' + bg_name + ' ' + pic_name + '.jpg'

    one_pic = time.time()
    GreenScreen(infile=picture ,inbg=bg, outfile=output_file)
    one_pic_time_done = time.time()

    time_arr.append(one_pic_time_done-one_pic)
    logger.info(time_arr)
    logger.info('done : %s' % pic_name)

def start_logging():
    logging.basicConfig()
    logger = logging.getLogger('greenbox')
    logger.setLevel(logging.INFO)
    return logger

if __name__ == '__main__':
    time_start = time.time()
    time_arr = []
    logger = start_logging()
    logger.info("Start time: %s" % time_start)
    check_folders(logger)
    begin_greenbox(logger)
    time_end = time.time()
    logger.info("End time: %s" % time_end)

Everything is okay and the image is saved in the /out folder. Using this code:
from cv2 import *
# initialize the camera
cam = VideoCapture(0)   # 0 -> index of camera
s, img = cam.read()
if s:    # frame captured without any errors
    namedWindow("cam-test",WINDOW_AUTOSIZE)
    imwrite('/home/leonardo/Scrivania/in/KVfnt.png',img) #save image

Everything is okay and the image is captured from the camera and saved in /in folder. If I add the second code to the first one:
from PIL import Image
from PIL.ImageChops import subtract
import numpy, math, time, glob, sys, os, logging, requests, random
from cv2 import *

# initialize the camera
cam = VideoCapture(0)   # 0 -> index of camera
s, img = cam.read()
if s:    # frame captured without any errors
    namedWindow("cam-test",WINDOW_AUTOSIZE)
    imwrite('/home/leonardo/Scrivania/in/KVfnt.png',img) #save image
def GreenScreen(infile, inbg ,outfile='output.png', keyColor=None,tolerance=None):
    """
    http://gc-films.com/chromakey.html
    http://www.cs.utah.edu/~michael/chroma/
    :param infile:      Greenscreen image location
    :param inbg:        Background image location
    :param outfile:     Output file location
    :param keyColor:    greenscreen color; it can be any singular color
    :param tolerance:   tolerance of cleaning
    :return:
    """

    if not keyColor:
        keyColor = [151,44,21] #Y,Cb, and Cr values of the greenscreen

    if not tolerance:
        tolerance = [100,130] #Allowed Distance from Values

    #open files
    inDataFG = Image.open('/home/leonardo/Scrivania/in/KVfnt.png').convert('YCbCr')
    Path = '/home/leonardo/Scrivania/background/'
    FullPath = os.path.join(Path, random.choice(os.listdir(Path)))
    BG = Image.open(FullPath).convert('RGB')
    [Y_key, Cb_key, Cr_key] = keyColor
    [tola, tolb]= tolerance

    (x,y) = inDataFG.size #get dimensions
    foreground = numpy.array(inDataFG.getdata()) #make array from image
    maskgen = numpy.vectorize(colorclose) #vectorize masking function

    alphaMask = maskgen(foreground[:,1],foreground[:,2] ,Cb_key, Cr_key, tola, tolb) #generate mask
    alphaMask.shape = (y,x) #make mask dimensions of original image
    imMask = Image.fromarray(numpy.uint8(alphaMask))#convert array to image
    invertMask = Image.fromarray(numpy.uint8(255-255*(alphaMask/255))) #create inverted mask with extremes

    #create images for color mask
    colorMask = Image.new('RGB',(x,y),tuple([0,0,0]))
    allgreen = Image.new('YCbCr',(x,y),tuple(keyColor))

    colorMask.paste(allgreen,invertMask) #make color mask green in green values on image
    inDataFG = inDataFG.convert('RGB') #convert input image to RGB for ease of working with
    cleaned = subtract(inDataFG,colorMask) #subtract greens from input
    BG.paste(cleaned,imMask)#paste masked foreground over background

    # BG.show() #display cleaned image
    BG.save(outfile, "JPEG") #save cleaned image

def colorclose(Cb_p,Cr_p, Cb_key, Cr_key, tola, tolb):
    temp = math.sqrt((Cb_key-Cb_p)**2+(Cr_key-Cr_p)**2)
    if temp < tola:
        z = 0.0
    elif temp < tolb:
        z = ((temp-tola)/(tolb-tola))
    else:
        z = 1.0
    return 255.0*z

def check_folders(logger):
    if not os.path.exists('out/'):
        os.mkdir('out/')
    if not os.path.exists('background/'):
        os.mkdir('background/')
        logger.error("Place background images in background/")
        sys.exit()
    if not os.path.exists('in/'):
        os.mkdir('in/')
        logger.error("Place input files in in/")
        sys.exit()

def begin_greenbox(logger):
    """
    For all backgrounds loop through all input files into the out file
    """
    for bg in glob.glob('background/*'):
            continue
    bg_name = bg.split('/')[-1].lower().strip('.jpg').strip('.png').strip('.jpeg')
    for picture in glob.glob('in/*'):
                continue
    pic_name = picture.split('/')[-1].lower().strip('.JPG').strip('.png').strip('.jpeg')
    output_file = 'out/' + bg_name + ' ' + pic_name + '.jpg'

    one_pic = time.time()
    GreenScreen(infile=picture ,inbg=bg, outfile=output_file)
    one_pic_time_done = time.time()

    time_arr.append(one_pic_time_done-one_pic)
    logger.info(time_arr)
    logger.info('done : %s' % pic_name)

def start_logging():
    logging.basicConfig()
    logger = logging.getLogger('greenbox')
    logger.setLevel(logging.INFO)
    return logger

if __name__ == '__main__':
    time_start = time.time()
    time_arr = []
    logger = start_logging()
    logger.info("Start time: %s" % time_start)
    check_folders(logger)
    begin_greenbox(logger)
    time_end = time.time()
    logger.info("End time: %s" % time_end)

I obtain this error:
  File "chromakey+upload.py", line 116, in <module>
    begin_greenbox(logger)
  File "chromakey+upload.py", line 97, in begin_greenbox
    GreenScreen(infile=picture ,inbg=bg, outfile=output_file)
  File "chromakey+upload.py", line 56, in GreenScreen
    cleaned = subtract(inDataFG,colorMask) #subtract greens from input
TypeError: src1 is not a numpy array, neither a scalar

What is the problem? Thank you for your answers.

A: As the error says:

src1 is not a numpy array, neither a scalar

Perhaps, you should try:
cleaned = subtract(numpy.array(inDataFG.getdata()),numpy.array(colorMask.getdata()))

Edit
There is a 'conflict' on subtract:
from PIL.ImageChops import subtract # first subtract
from cv2 import * # OpenCV has a subtract too

This is one of the reasons to use namespaces on your calls.
If your main image lib is PIL, maybe you should do import cv2 and use cv2.* when needed.


text:
Q: How to dispose of my Stateful Widget completely? I call my stateful widget page and get some info from the server. If no info found it warns the user that there isn't any info.
From the drawer back button, I go back to the previous page. If I keep repeat back and forth very fast I get an error on console message in my IntelliJ IDE as;
E/flutter (22681): [ERROR:flutter/shell/common/shell.cc(181)] Dart Error: Unhandled exception:
E/flutter (22681): setState() called after dispose(): _BillsPayWaterState#66be5(lifecycle state: defunct, not mounted)
E/flutter (22681): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback. The preferred solution is to cancel the timer or stop listening to the animation in the dispose of the () callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter (22681): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose of ().
E/flutter (22681): #0      State.setState.<anonymous closure>

In my statefull widget I have @override void initState() and I also have @override void dispose()
My question is when I use the drawer back button, How can I dispose of my Stateful Widget completely?
This is the call for widget
onTap: () {
Navigator.push(
  context,
  SlideRightRoute(widget: new BillsWaterPay("S02")),
);
}

And this the BillsWaterPay widget
List<List<dynamic>> _userAskBills;

// TODO: KURUM KODU - SABIT TELEFON
String _kurumKodu = "";
String _noDataText = "";

class BillsWaterPay extends StatefulWidget {
  final String title;

  BillsWaterPay(this.title);

  @override
  _BillsWaterPayState createState() =>
      _BillsWaterPayState();
}

class _BillsWaterPayState extends State<BillsWaterPay> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _kurumKodu = widget.title;
    _userAskBills;
    _noDataText;
    _loadEverything();
}

Future _loadEverything() async {
    await _getDataFromServer();
}

Future _getDataFromServer() async() {
    …
    …
    if no data
        setState
            _noDataText = "No Data";  // In here I get an error setState called after dispose

}

@override
void dispose() {
  super.dispose();
      _kurumKodu = widget.title;
    _userAskBills;
    _noDataText;
}

A: The above exception is shown when we call setState() after we dispose of the widget due to async.
Handle this by using the property of flutter => mounted
mounted tells about the availability of the widget.
...
if (mounted) {
    setState(() {
        ...
    });
}
...

A: I assume the problem is caused by the response from the server arrives after the widget is disposed.
Check if the widget is mounted before you call setState. This should prevent the error you are seeing:
// Before calling setState check if the state is mounted.
if (mounted) {
  setState (() => _noDataText = 'No Data');
}


text:
Q: Layout expand on button press What I want to do is have two 'frames'. Left and Right. At application start, the left frame takes up the majority of the space while the right frame is just barely visible.
I want to be able to 'animate' and expand the right frame on button press or on swipe.
Currently, I have the layout set using weightSum and layout_weight, so my issue is mainly the expanding / animating.
This is similar to how you can pull down the notifications bar in android or in the Facebook app, except from left to right.

A: If you want to do something like the Facebook app, I suggest you look at the Sliding Drawer class. It allows for both vertical and horizontal configurations.


text:
Q: How to determine the Boost version on a system? Is there a quick way to determine the version of the Boost C++ libraries on a system?

A: Include #include <boost/version.hpp>
std::cout << "Using Boost "
          << BOOST_VERSION / 100000     << "."  // major version
          << BOOST_VERSION / 100 % 1000 << "."  // minor version
          << BOOST_VERSION % 100                // patch level
          << std::endl;

Possible output: Using Boost 1.75.0
Tested with Boost 1.51.0 to 1.63, 1.71.0 and 1.76.0 to 1.81.0

A: Boost installed on OS X using homebrew has desired version.hpp file in /usr/local/Cellar/boost/<version>/include/boost/version.hpp (note, that the version is already mentioned in path).
I guess the fastest way to determine version on any UNIX-like system will be to search for boost in /usr:
find /usr -name "boost"

A: If you only need to know for your own information, just look in /usr/include/boost/version.hpp (Ubuntu 13.10) and read the information directly

A: As to me, you can first(find version.hpp the version variable is in it, if you know where it is(in ubuntu it usually in /usr/include/boost/version.hpp by default install)):
 locate `boost/version.hpp`

Second show it's version by:
 grep BOOST_LIB_VERSION /usr/include/boost/version.hpp

or
  grep BOOST_VERSION /usr/include/boost/version.hpp.

As to me, I have two version boost installed in my system. Output as below:
xy@xy:~$ locate boost/version.hpp |grep boost

/home/xy/boost_install/boost_1_61_0/boost/version.hpp
/home/xy/boost_install/lib/include/boost/version.hpp
/usr/include/boost/version.hpp

xy@xy:~$ grep BOOST_VERSION /usr/include/boost/version.hpp
#ifndef BOOST_VERSION_HPP
#define BOOST_VERSION_HPP
//  BOOST_VERSION % 100 is the patch level
//  BOOST_VERSION / 100 % 1000 is the minor version
//  BOOST_VERSION / 100000 is the major version
#define BOOST_VERSION 105800
//  BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION

# or this way more readable
xy@xy:~$ grep BOOST_LIB_VERSION /usr/include/boost/version.hpp
//  BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
#define BOOST_LIB_VERSION "1_58"

Show local installed version:
xy@xy:~$ grep BOOST_LIB_VERSION /home/xy/boost_install/lib/include/boost/version.hpp
//  BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
#define BOOST_LIB_VERSION "1_61"

A: @Vertexwahns answer, but written in bash. For the people who are lazy:
boost_version=$(cat /usr/include/boost/version.hpp | grep define | grep "BOOST_VERSION " | cut -d' ' -f3)
echo "installed boost version: $(echo "$boost_version / 100000" | bc).$(echo "$boost_version / 100 % 1000" | bc).$(echo "$boost_version % 100 " | bc)"

Gives me installed boost version: 1.71.0

A: I stugeled to find out the boost version number in bash.
Ended up doing following, which stores the version code in a variable, supressing the errors. This uses the example from maxschlepzig in the comments of the accepted answer. (Can not comment, don't have 50 Rep)
I know this has been answered long time ago. But I couldn't find how to do it in bash anywhere. So I thought this might help someone with the same problem. Also this should work no matter where boost is installed, as long as the comiler can find it. And it will give you the version number that is acutally used by the comiler, when you have multiple versions installed.
{
VERS=$(echo -e '#include <boost/version.hpp>\nBOOST_VERSION' | gcc -s -x c++ -E - | grep "^[^#;]")
} &> /dev/null

A: #include <boost/version.hpp>
#include <iostream>
#include <iomanip>

int main()
{
    std::cout << "Boost version: "
          << BOOST_VERSION / 100000
          << "."
          << BOOST_VERSION / 100 % 1000
          << "."
          << BOOST_VERSION % 100
          << std::endl;
    return 0;
}

Update: the answer has been fixed.

A: Another way to get current boost version (Linux Ubuntu):
~$ dpkg -s libboost-dev | grep Version
Version: 1.58.0.1ubuntu1

Ref:
https://www.osetc.com/en/how-to-install-boost-on-ubuntu-16-04-18-04-linux.html

A: cat /usr/local/include/boost/version.hpp  | grep BOOST_LIB_VERSION

A: Depending on how you have installed boost and what OS you are running you could also try the following:
dpkg -s libboost-dev | grep 'Version'

A: Boost Informational Macros. You need: BOOST_VERSION

A: If one installed boost on macOS via Homebrew, one is likely to see the installed boost version(s) with:
ls /usr/local/Cellar/boost*

A: Might be already answered, but you can try this simple program to determine if and what installation of boost you have :
#include<boost/version.hpp>
#include<iostream>
using namespace std;
int main()
{
cout<<BOOST_VERSION<<endl;
return 0;
}


text:
Q: Working with empty objects in javascript array I have an array of arrays that I am trying to pull values from. The problem is that I get an undefined error when it hits an empty array.
Here is the array I'm working with:
 data = [[Object { myvar=null}], [Object { myvar="testval"}], [], [], []]

Here is the javascript I'm using to get all myvar values:
myarr = [];
for (var i = 0; i < data.length; i++) {
    console.log(data[i][0].myvar);
    if (data[i][0].myvar) {
        dep = data[i][0].myvar;
        if (dep != null) {
            myarr.push(dep);
        }
    }
}

The console.log looks like:
   null
   testval
   Error: data[i][0] is undefined

So it breaks when it reaches the first []. How could I remove all the empty arrays before the for loop? Or have the for loop not die when it hits an empty array? Any help appreciated. Thanks.

A: You  can simply check whether the current item is empty:
if (data[i].length === 0) continue;

A: Just wanted to add this as an answer..  In javascript, I believe null == false.  So you can also do something like this:
if(data[i][0])
   //it's not null or undefined, do some work

A: You need to make sure data[i] is an array and it has at least 1 item first :
var i, item, myarr = [],
    isNotEmptyArray = function(a) {
        return Object.prototype.toString.call(a) === '[object Array]' && a.length > 0;
    };

for (i = 0; i < data.length; i++) {
    item = data[i];
    if (isNotEmptyArray(item) && item[0].myvar) {
        console.log(item[0].myvar);
        dep = item[0].myvar;
        if (dep != null) {
            myarr.push(dep);
        }
    }
}

A: for (var i = 0; i < data.length; i++) {
    if (data[i].length !== 0) continue;
    if (data[i][0].myvar) {
        dep = data[i][0].myvar;
        if (dep != null) {
            myarr.push(dep);
        }
    }
}

A: This is the best and cleanest way to do it.
data.forEach(function(e){
    if(Object.keys(e).length) myarr.push(e);
});

take a look http://jsfiddle.net/8zfZd/ open console to see object.
Object.keys()
forEach
to make it even shorter...
data.forEach(function(e){ (e[0]) && myarr.push(e); });

http://jsfiddle.net/cgg6j/

A: Add this loop before your loop to clear the empty arrays:
var i = 0;
while (true) {
    if (i == data.length)
        break;
    if (data[i].length == 0)
        data.splice(i, 1);
    else
        ++i;
}


text:
Q: Probability of a similar sub-sequence of length X in two sequences of length Y and Z Say we have two random sequences of length $y=3300$ and length $z=26$, where the sequences are made out of a combination of $k=4$ four letters ACGT.

*

*the letter in each position of the sequence is independent from the other letters

*the letter in each position in the sequence and can have equal probability for A, C, G or T. That is, every possible sequence has equal probability.

(Note:this relates to RNA sequences where the nucleotides are completely random iid and with equal probability for each of the four nucleotides)
What is the probability that both these two sequences contain a same subsequence of length $x=19$? Or what is an approximation of this probability?
A related problem is: A fair die is rolled 1,000 times. What is the probability of rolling the same number 5 times in a row?
but here we are not looking for the probability of rolling a specific sequence (like the same number five times in a row) but instead for any possible subsequence that occurs in another random sequence of some length.

A: An approximation.

*

*Step 1: Compute the expectation value for the number of similar sub sequences.
There are $y-x+1$ and $z-x+1$ subsequences. The probability for a match between two subsequences is $(1/4)^x$, then the expectation value for the number of matches $n$ is $$E[n] = (y-x+1)(z-x+1)(1/4)^x$$

*Step 2 (a dead end, wrong step that will be adjusted in step 3): If we are naive, then we consider the distribution of the number of matches to be Poisson distributed. Then we put the expectation value of the step 1 approximately equal to the probability of having at least 1 or more sub sequence matches by using the Poisson distribution.
$$P(n \geq 1) \approx 1-e^{-E[n]}$$
But this is false. See for instance the linked question A fair die is rolled 1,000 times. What is the probability of rolling the same number 5 times in a row? where the probability of 5 times at least the same number in a row is not $1- \exp \left(-(1000-5+1)\left(\frac{1}{6^4}\right) \right)\approx 0.536$ and instead it is approximately $0.474$
The reason that it is false, is because when we already have one matching subsequence, then the probability of another matching subsequence becomes more likely. The distribution of the number of matches $n$ is not a Poisson distribution.

*Step 3 (adjustment for error in step 2): we need to figure out an estimate for the relative probabilities of 1 match, 2 matches, etc. and use this along with the expectation.
Say that we already have one matching subsequence of length $x$, then
another match is found when either on the left or right of the
subsequences we can find another matching letter.
If we ignore the situations where the subsequences are found at the boundary (if we assume that we can extend the subsequences indefinitely), say we have a 19 length sub-sequence like CTACGTGCCCGCCGAGGAG in both two sequences, as below where the * are wild cards and can be with 1/4-th probability any letter A, C, G or T.
sequence 1: *******CTACGTGCCCGCCGAGGAG******
sequence 2: *******CTACGTGCCCGCCGAGGAG******

There is a 1/4 probability that the match extends with another pair on the right. There is a 1/4 probability that the match extends with another pair on the left. So the distribution of additional matches, $S$, will be geometric distributed, or more precisely the sum of two geometric distributions (on both sides). Then the expectation value can be expressed approximately as:
$$E[n_{true}] \approx E[n_{naive}] \cdot (1+2\cdot E[S])$$
where $E[S] = 1/(k-1)$ is the expectation value of the geometric distributed number of extensions $S$ (and $k$ is the number of options).
Then we can use the approximation
$$P(n \geq 1) \approx 1-e^{-E[n]/(1+2\cdot E[S])}$$

*Step 4 (adjustment for error in step 3)
When we apply the last expression to the dice roll situation, then we get the estimate $$1- \exp \left(-(1000-5+1)\left(\frac{1}{6^4}\right) /1.4 \right)\approx 0.422$$ and we get problems of over-compensating. Interrestingly when we do $$1- \exp \left(-(1000-5+1)\left(\frac{1}{6^4}\right) /1.2 \right)\approx 0.473$$ then we get very close to the right answer.
We can see that the correction from step 3 is counting the cases multiple times. For instance, some subsequence in position $i$ is extended to the right and some subsequence in position $i+1$ is extended to the left are the same cases.
So when we do the extension only to one single side, and use only a factor 1 instead of 2, then we get a better approximation because we are not counting cases multiple times. So the final result is: $$\begin{array}{rcl}
P(n \geq 1) &\approx& 1-e^{-E[n]/(1+1\cdot E[S])} \\
E[n] &=& (y-x+1)(z-x+1)(1/4)^x \\
E[S] &=& \frac{1}{k-1}
\end{array}$$
Where $x$ is the length of the sub-sequence, $y$ and $z$ are the random sequences among which we search for a matching subsequence of length $x$, $k$ is the number of different types of letters out of which the sequences can be composed (e.g. $k=6$ for six-sided dice rolls, or $k=4$ for RNA/DNA-sequences), $n$ is the number of sub-sequence matches, $S$ is the length by which the sequence of length $x$ is extended (finding more matches).
Conclusion
$$P \approx 1- e^\frac{3275 \cdot 8 \cdot 0.25^{19}}{1+1/3} \approx 7.14 \cdot 10^{-8}$$
Comparison with simulation
Below we use $x = 9$, $y=200$, $z=180$, $k=4$ and compare the formula with a simulation of one million pairs of sequences.
The differences are small with 0.09015627 for the estimate from the formula and 0.090055 for the estimate from the simulation.
sim = function(n1=100,n2=100, l = 9){
  ### create two sequences
  s1 = sample(c("a","c","g","t"), n1, replace=TRUE)
  s2 = sample(c("a","c","g","t"), n2, replace=TRUE)

  ### perform a loop that searches with grepl for every possible substring from s1 in the string made from s2
  count = 0
  string2 = paste0(s2, collapse = "")
  for (i in 1:(n1-l+1)) {
    substring = paste0(s1[c(1:l)+i-1], collapse = "")
    if (grepl(substring, string2)) {
      count = 1
    }
  }
  return (count)
}

x = 9
y = 180
z = 200
k = 4

### this returns 0.09015627
1-exp(-(z-x+1)*(y-x+1)*(1/k)^x*(k-1)/k)

### this returns 0.090055
set.seed(1)
nt = 10^6
sum(replicate(nt,sim(y,z,x)))/nt