text:
Q: How to set the views in linear layout so that it fits in from start to end screen with a certain number of elements that are in a one row? I have 14 (views) horizontal lines in LinearLayout and it should fit in any screen, so is there any idea how to set width between lines to fit from start to end at any screen size?
See the image how it looks:
screenshots

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:orientation="horizontal">

        <View
            android:id="@+id/one"
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="@color/blueTextColor" />

        <View
            android:id="@+id/two"
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:layout_marginStart="27dp"
            android:background="@color/blueTextColor"/>
        <View/>
        <View/>
        <View/>
        <View/>
        <View/>
        <View/>
        <View/>
        <View/>
        <View/>
        <View/>
        <View
            android:id="@+id/fourteen"
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:layout_marginStart="27dp"
            android:background="@color/blueTextColor" />

    </LinearLayout>

I try this but it not work

A: I am not sure but I think @GuseeMofiddin answer doesn't work as You want because it expands the view to the full width and You want it to be just 1dp. You can Use constraint layout and chains to do it. Example:

*

*Create Your layout like this:

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:orientation="horizontal">

    <View
        android:id="@+id/one"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="#0000AA" />

    <View
        android:id="@+id/two"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="#0000AA" />

    <View
        android:id="@+id/three"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="#0000AA" />

    <View
        android:id="@+id/four"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="#0000AA" />

</androidx.constraintlayout.widget.ConstraintLayout>

*Now You have to create horizontal chains.

First, select them all (click on one, hold Shift and then click on four)

Next right-click and select this:

Your XML file should look like this:
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:orientation="horizontal">

    <View
        android:id="@+id/one"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="#0000AA"
        app:layout_constraintEnd_toStartOf="@+id/two"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent" />

    <View
        android:id="@+id/two"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="#0000AA"
        app:layout_constraintEnd_toStartOf="@+id/three"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/one" />

    <View
        android:id="@+id/three"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="#0000AA"
        app:layout_constraintEnd_toStartOf="@+id/four"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/two" />

    <View
        android:id="@+id/four"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="#0000AA"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/three" />

</androidx.constraintlayout.widget.ConstraintLayout>

The result on two different devices:

(this method doesn't create a view on the left and right edge. To do it just add one of the left and right edge and then create chain but don't include them)

Edit to answer comment: To add the bottom and top margin to specific view You have to set height to 0dp and set top and bottom constraint to top and bottom of the parent. The view should look like this:
<View
    android:id="@+id/two"
    android:layout_width="1dp"
    android:layout_height="0dp"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:background="#0000AA"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/three"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/one"
    app:layout_constraintTop_toTopOf="parent"
    />

A: You only have to set
android:weightSum="14"

to your parent LinearLayout and
android:layout_weight="1"

to your child views, Please try this,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:orientation="horizontal"
        android:weightSum="14">

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#fff" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#fff" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#fff" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000" />

    </LinearLayout>

</RelativeLayout>


text:
Q: OpenGL light direction reversed while drawing into a framebuffer texture I've got an iPhone (OpenGL ES 1.1) app that does some rendering into textures. I'm setting up a framebuffer object and using glFramebufferTexture2D to attach the texture to it.
Everything works fine except that the light directions are reversed when drawing into this framebuffer object. I'm specifying light directions like this:
float theDirection[4] = { x, y, z, 0 }
glLightf( lightIndex, GL_POSITION, theDirection )

When rendering without the framebuffer object, all my light directions are correct. When rendering with the framebuffer object, I have to negate theDirection for things to look the same.
As a side note, the light directions are also reversed (with or without a framebuffer object) when I'm running on an iPhone 3G with iOS 3.2. If I'm running on an iPhone or iPad on 4.x, the light directions are not reversed.
Any ideas?

A: Strangely, the solution here was to enable GL_CULL_FACE. If GL_CULL_FACE is disabled in a MonoTouch project using OpenGL ES 1.1, then the GL lighting direction (for a directional GL_LIGHT0) will be negated on some of the devices or OS versions, I'm not sure which.
xcode-based C++ projects do not have this problem. OpenGL ES 1.1 xcode projects light consistently across all devices and OS versions that I've tested regardless of your GL_CULL_FACE setting.
As compared to the result of identical GL code in a C++ xcode project (which is consistent across devices regardless of GL_CULL_FACE), here are the devices that I see inverted lighting happening on in MonoTouch:

*

*iPad running iOS 4.2.1

*iOS simulator running iOS 4.2

*iPhone4 running iOS 4.2.1

The lighting is correct on my iPhone 3G running iOS 3.1.2.
I posted a bug report to Novell: https://bugzilla.novell.com/show_bug.cgi?id=679896

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to specify more than one option in jQuery datepicker I am using jQuery Datepicker. I am using follwing script to attach the datepicker to all controls whose class is datepicker.
<script type="text/javascript">
  $(document).ready(function(){
    $(".datepicker").datepicker({ showButtonPanel: true});
  });
  </script>

Now, is it possible to use more than one option while creating the datepicker, like this
$(".datepicker").datepicker({ showButtonPanel: true}, {showOtherMonths: true });

It doesn't seems to work.

A: You need to write:
$(".datepicker").datepicker({ showButtonPanel: true, showOtherMonths: true });

This is a common idiom in jQuery, to use a JSON object (hash) for the options.

A: One of the parameters to most jQuery plugins accepts an object as the argument, for example { option1: 'optionValue'}. This allows the user to pass in whichever options that they want to change from the defaults. In most plugins, this options object is then merged with the default options using $.extend(), overriding any of the default options with properties from the options object if they are defined.
One of the usual ways a plugin is written is as follows
(function($) {

    $.fn.myPlugin = function(options) {

    var settings = $.extend({  // these are the default properties
                               option1: 'default value',
                               option2: true,
                               option3: 5437
                            },
                            // merge with the options object passed in
                            // or an empty object
                            options || {});

    // now we can use the settings object in our plugin, which will have
    // property values from the settings object and the options object passed in

    }

})(jQuery);

the options || {} part in $.extend() guards against a false value being passed for options. The order of the objects in $.extend() determines which properties take precendence- a property defined on an object will have it's value replaced (use the term roughly here) by the same property name declared on a later object.


text:
Q: How to incorporate standard security forms and logic into many projects I have got a standard security package using own controllers and views and other classes
(for example Authorization filters) in asp.net MVC.
I will need to incorporate the same into multiple projects .
What would be the best approach for incorporating these -I can copy the controllers and views and other classes into each project -I can make library but unsure how to handle controllers/views


text:
Q: Windows 8 OEM. Direct Windows 10 installation I have a OEM Windows 8 Laptop, which I updated to 8.1.
Unfortunately I had a SSD crash. I want to use the opportunity and install Windows 10.
The way of work often described is to first install Windows 8 using e.g. recovery media.  Then upgrade to 8.1 and finally upgrade to Windows 10 using MCT tool from Microsoft.
What I know though,  Windows 10 is accepting Windows 8 keys recently. My question is: will it also be possible to install Windows 10 directly (without first installing Windows 8) on my laptop? Will Windows 10 activate itself? I do not know the key since it is stored in BIOS and I cannot read it since no OS is installed on the PC right now.
This question was raised before.  But now Microsoft has changed the acceptance of old keys. Will it also change the situation described above?

A: The 'free' win10 key works by upgrading the existing installation, not by installing from scratch.
Once you've established the key by this method, then any clean install will still work, as the key is 'remembered' by Microsoft as being associated with that machine,


text:
Q: Is it enough to forbid single quotes in input to avoid SQL injection? I inherited an old piece of software and the code checks user input for containing a single quote character ' before construction an SQL statement using the string concatenation.
Is this sufficient to avoid SQL injection (besides being bad style) or do I have to take immediate action and change it to parameter usage?

A: Nope, it is not enough.
Yes, you have to take immediate action and change it to parameter usage where applicable.
Just a few guidelines for you to get it straight:

*

*Never take care of any injections. But make sure you have formatted your SQL literals properly. A properly formatted literal is error-proof and - just as a side effect - also invulnerable.

*Discover the fact that SQL query consists of literals of several different types. Each require distinct formatting, incompatible and useless for all others.

*Make sure such a formatting applied unconditionally. A prepared statement is the only way to be sure of.

A: Using the blacklist approach (i.e. block single quotes) may help prevent specific cases but it's generally better to use parameterized queries because it'll be difficult to blacklist all vectors.
SQL injection is still possible without quotes as described here so whilst blocking a single quote may prevent the 'easy' SQL injection, it's not foolproof. (And that example is one that's been made public but there could be other less well-known exploits being used).

A: Yes, in SQL Server, filtering ' or replacing ' with '' stops SQL injection.
As Daniel Hilgarth mentions in the comments, you should not pass a C# string as a SQL integer.
(I'm aware this is not a popular position, but as far as I know, it's correct.)


text:
Q: How to take care of Brew Doctor warning As I was not able to change python version via pyenv global, I have re-install pyenv and python. And now I am getting this warning. Earlier I have fixed this issue by referring other articles, though I assume setting something wrong in .bash_profile making pyenv global not working. I am total new to this. Any help make me understand the warning and resolve the issue would be greatly appreciated. Thanks
Macbooks-MacBook-Pro:~ macbookpro$ brew doctor

Having additional
scripts in your path can confuse software installed via Homebrew if the config script overrides a system or Homebrew provided script of the same name. We found the following "config" scripts:
/Users/macbookpro/.pyenv/shims/python-config
/Users/macbookpro/.pyenv/shims/python2-config
/Users/macbookpro/.pyenv/shims/python2.7-config
/Users/macbookpro/.pyenv/shims/python3-config
/Users/macbookpro/.pyenv/shims/python3.6-config
/Users/macbookpro/.pyenv/shims/python3.6m-config

Macbooks-MacBook-Pro:~ macbookpro$ which pyenv    /usr/local/bin/pyenv
Macbooks-MacBook-Pro:~ macbookpro$ which brew   /usr/local/bin/brew
Macbooks-MacBook-Pro:~ macbookpro$ pyenv versions
 system
  2.7.15
* 3.6.5 (set by /Users/macbookpro/.python-version)

Macbooks-MacBook-Pro:~ macbookpro$ open -e .bash_profile
if which pyenv > /dev/null; then
  eval "$(pyenv init -)";
  fi   export PYENV_ROOT="$HOME/.pyenv"   export
  PATH="$PYENV_ROOT/bin:$PATH"   eval "$(pyenv init -)"

Macbooks-MacBook-Pro:~ macbookpro$ python --version   Python 3.6.5
Macbooks-MacBook-Pro:~ macbookpro$ pyenv global 2.7.15
Macbooks-MacBook-Pro:~ macbookpro$ pyenv global
2.7.15 .
Macbooks-MacBook-Pro:~ macbookpro$ python --version
Python 3.6.5
Macbooks-MacBook-Pro:~ macbookpro$ which python                     /Users/macbookpro/.pyenv/shims/python

A: The alias can be improved:
alias brew='env PATH="${PATH//$(pyenv root)\/shims:/}" brew'

Just in case $PATH contains spaces.

A: Try adding the following alias to your source file
alias brew='env PATH=${PATH//$(pyenv root)/shims:/} brew'


text:
Q: ListView selected item highlight I'm working on a GridView with setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL). By default, rows are not getting highlighted (with the blue highlight you see on WhatsApp or Gallery apps), so I am wondering, does the Android API already takes care of highlighting the selected items and I am missing something (if so, what am I missing?)  or do I have to take care of highlighting selected rows by myself (if so, how to highlight, not just change the background)?
Here's my code:
gridView.setOnItemClickListener(this);
gridView.setEmptyView(view.findViewById(R.id.empty));
gridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);

// multiChoiceModeListener is a subclass of AbsListView.MultiChoiceModeListener
// with no particular code on its abstracts methods.
gridView.setMultiChoiceModeListener(multiChoiceModeListener);

A: Use this for your ListItem background (XML layout)
android:background="?android:attr/activatedBackgroundIndicator"

It's basically only a selector, you can also build yourself: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/drawable/activated_background.xml
EDIT:
Given your comment, this solves it:
android:foreground="?android:attr/activatedBackgroundIndicator" with a FrameLayout
Also related question: How to set foreground attribute to other non FrameLayout view


text:
Q: 2D-array as a class property - how to create them the C# way? I am trying to create a class with a property that is a two-dimensional array. The array will hold various x,y coordinates on a grid (e.g. 0,1 or 3,7) and the size of the array is dependent on a class property called size.
How would you go about creating this array in C#? I have given my solution below, but having very little C# experience and coming from a Python background with some javascript knowledge, it feels like that there is a better solution to this problem.
Could one of you C# wizards enlighten me, please?
Thanks in advance for your help.
Here is my code:
public class Obj
{
    int Size;  // Defines length of array
    int[,] Pos;

    // constructor
    public Obj(int size)
    {
        this.Size = size;
        this.Pos = new int[size, 2];
    }

    public void set_coord(int index, int x, int y)
    {
        if (index >= this.Size) {
            Console.WriteLine("Catch OutOfRangeException");
        }
        else
        {
            this.Pos[index, 0] = x;
            this.Pos[index, 1] = y;
        }
    }

A: You could create a List instead of a class, and have an internal sub class to represent your points.
Like this
    public class Obj{
      int Size;
      List<Point> Pos = new List<Point>();

      public Obj(int size){
        this.Size = size;
      }

      public set_coord(int index, int x, int y){
        if(index >= this.Size){
          Console.Writeline("Catch OutOfRangeException")
        }else{
          this.Pos.Add(new Point(x,y));
        }
      }
    }

    class Point{
      int x = 0;
      int y = 0;
      public Point(int xCor, int yCor){
        this.x = xCor;
        this.y = yCor;
      }
    }

A: A struct is the ideal approach for this. A full blown class may not be necessary, but it depends.
https://msdn.microsoft.com/en-us/library/ah19swz4.aspx
public struct Coordinates
{
    public int coordX;
    public int coordY;
}

The property then in your class could be set like this:
var Obj = new Obj();
List<Coordinates> listOfCoords = new List<Coordinates>();
var coord = new Coordinates();
coord.X = 20;
coord.Y = 15
listOfCoords.Add(coord);
Obj.Pos = listOfCoords

Keep in mind that Structs cannot be inherited from, or inherit, other classes or structs, as well as a few other gotchas. If you need these features, or the data in your struct is prone to modification after it is created (in other words, the data is NOT immutable), consider a small class instead.
https://msdn.microsoft.com/en-us/library/0taef578.aspx


text:
Q: pg_jit_available showing 'false' and jit not working, but config file seems set up properly I am trying to turn on JIT for testing purposes on a Postgresql 12 server, it was off before.
My postgresql.conf has the following properties activated (basically all default values):

*

*jit = on

*jit_above_cost = 100000

*jit_inline_above_cost=500000

*jit_optimize_above_cost=500000

*jit_provider = 'llvmjit'

I have also restarted the Postgres server service after editing the config.
Now when I run show jit I get on, however running SELECT pg_jit_available() returns false.
From the test queries I made it does not seem to include any JIT stuff happening in the query plan neither.
The documentation is a bit scarce on how configuration is done properly - is there anything I have missed about my setup?
Thanks!


text:
Q: C4996 System Cannot Find The File Specified #include "Time.h"

void Time::timerStart()
{
    tBegin = clock();
}

double Time::timerStop()
{
    tEnd = clock();
    double elapsed_secs = double(tEnd - tBegin) / CLOCKS_PER_SEC;
    return elapsed_secs;
}

string Time::getDate(char delimiter)
{
    time_t t = time(0);   //now
    struct tm *now = localtime(&t);

    ostringstream ss; //use iss or oss and NOT ss (bulkier)
    ss << now->tm_mday << delimiter << (now->tm_mon + 1)
        << delimiter << (now->tm_year + 1900);

    return ss.str();
}

string Time::getTime(char delimiter)
{
    time_t t = time(0);
    struct tm *now = localtime(&t);

    ostringstream ss;
    ss << now->tm_hour << delimiter << now->tm_min << delimiter << now->tm_sec;

    return ss.str();
}

Basically I keep getting Error Code C4966 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable depreciation, use _CRT_SECURE_NO_WARNINGS.
I used _CRT_SECURE_NO_WARNINGS in the preprocessor definitions and it still gives me the same error. Im so lost on how to run this program and I've spent literally hours looking for solutions online and trying to figure it out myself.

A: First of all, add _CRT_SECURE_NO_WARNINGS to Preprocessor works for me, if not for you, try other solutions below:
Solution 1:
Define _CRT_SECURE_NO_WARNINGS at the beginning of your file:
#define _CRT_SECURE_NO_WARNINGS
#include <time.h>

Solution 2:
Add 4996 to :
YourProject->Properties->Configuration Properties->C/C++->Advanced->Disable Specific Warnings


text:
Q: error: failed to push some refs tentando fazer um push para o repositorio e esta sendo rejeitado
$ git push origin master
To https://github.com/me/myproject
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/me/myproject'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

A: Seu repositório local não está compatível com o repositório online.
Primeiro de tudo: retire os arquivos modificados por você e coloque-os em um diretório qualquer.
Depois de feito isso rode o comando:
git remote update #vai atualizar os branches locais com as copias do repositório online

Em seguida rode:
git reset upstream/master

Pronto, seu repô está atualizado. Agora volte com os seus arquivos modificados para o diretório onde você deseja e rede o comando:
git pull -r upstream master

Isso vai trazer tudo de novo do master e colocar a sua mudança em cima. Daí é só mandar o push pro seu origin/<branchname> com --force.

A: O problema acontece pois você está tentando subir commits para um git remoto, mas existem commits que você não tem no seu repositório local. Antes de fazer o push, você precisa puxar/pull os commits de lá:
git checkout <sua-branch>    # troca de branch
git pull origin <sua-branch> # puxa as alterações da branch no remoto origin

Se algum arquivo no remoto foi alterado por você no repositório local, você terá que resolver conflitos de merge antes de empurrar/push pro remoto.

Leia com atenção: se você não quer os commits que estão no remoto, e quer sobrescrever tudo que está lá com o seu repositório local, use o comando destrutivo abaixo:

 git push origin <sua-branch> --force


text:
Q: Adding new column to dataframe with month extracted from date Spark
I am trying to add a new column to a dataframe in Spark. I have a clean dataset (dfClean) with a column called "Fecha ingreso" that has a date and I want to extract the month from this column and add a new column that only has the month.
I tried
from pyspark.sql.functions import month

dfCleanMonth = dfClean.withColumn('Month',month('Fecha ingreso'))
dfCleanMonth.display()

but it's not adding any columns, even though it is not giving any errors. Does anybody know how I can fix it? I have looked online but can't seem to find the error.
Thank you!


text:
Q: Linux boots to recovery mode, mounting /home and loging out brings up lightdm I am having an odd problem when i boot.
It brings me to the recovery mode and tells me to press Ctrl-D or enter my root password.
When I enter the root password, I mount my /dev/mapper/sdc1_crypt which is my /home drive. if I log out of the root shell it then launches lightdm and I can sign into my user account as if nothing happened.
How can I fix it so i dont have to do this each time I boot?
I'm using Debian.

A: Solved by using fsck on the diskdrive in question


text:
Q: What does `tfms_from_model()` exactly do? I've been trying to follow a code which uses fastai v0.7.0 with the conv_learner methods. There's a piece where the author uses tfms_from_model() for transforming inputs.
My question here is, what exactly does tfms_from_model() produce?
model = vgg16(pre=True).cuda().eval()
set_trainable(model, False)

sz = 224
train_tfms, val_tfms = tfms_from_model(vgg16, sz)

I'm asking the question because I can't use fastai 0.7.0 because there's no pytorch support for it anymore. So I'm just guessing and manually implementing the things that tfms_from_model() does. Here's the implementation I found
picture = PIL.Image.open("test/206px-Wattledcranethumb.jpg")
plt.imshow(picture)

transformed = val_tfms(np.array(picture)/255)
plt.imshow(transformed.transpose(1,2,0))

So what exactly is val_tfms doing? Is it just normalizing images for the model as per the model's expected inputs? (For e.g. VGG16 requires channel wise mean being subtracted from it and then dividing by the sd for it's normalization)
What would happen if I put something like this?
sz = 56
train_tfms, val_tfms = tfms_from_model(vgg16, sz)

Is this also equivalent to doing this:
def normalize(x):
    # Some arbitrary normalization
    return normalized_x

picture = normalize(picture)
picture = torch.tensor(picture)


text:
Q: PHP $_post array always follow a number "1" <form  name="form1" method="post" action="test2.php">
    <input type="checkbox" name="checkbox1">
    <input type="text" name="textbox1">
    <input type="submit" name="submit">
</form>

 <?php
    echo print_r($_POST);
 ?>

The code shows Array () 1 or Array ( [checkbox1] => on [textbox1] => asf [submit] => submit ) 1.
I don't understand why does the array always follows the number 1.
When I change POST method to GET method, the same thing happen.
When I use another Array to store the value of $_POST, the same thing happen again!
<?php
    $temp = $_POST;
    if (isset($_POST['textbox1']))
    $temp = "textbox1='{$temp['textbox1']}'";

    textbox1='asdf'1
    Array ( [textbox1] => asdf [submit] => submit) 1
?>

A: echo and print are similar, this is like doing echo echo ($_POST); to give you an example (which would give you an error). Remove echo and leave only print_r($_POST);.
Also, check this link on differences between echo, print and print_r.

A: <form  name="form1" method="post" action="test2.php">
    <input type="checkbox" name="checkbox1">
    <input type="text" name="textbox1">
    <input type="submit" name="submit">
</form>

 <?php
    print_r($_POST);  // Remove echo
 ?>


text:
Q: What is difference between this two Cookie configurations for cookie based authentication? What is difference between this two variants of Cookie configurations for cookie based authentication?

*

*variant 1:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    // Configure cookie based authentication:
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(opt =>
            {
                /* validation rules */
            });
}

*

*variant 2:

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity<AppUser, AppRole>(opt =>
    {
        /* validation rules */
    });

    services.ConfigureApplicationCookie(options =>
    {
        options.LoginPath = new PathString("/User/Login");

        options.Cookie = new CookieBuilder
        {
            Name = "AspNetCoreIdentityExampleCookie",
            HttpOnly = false,
            SameSite = SameSiteMode.Lax,
            SecurePolicy = CookieSecurePolicy.Always
        };

        options.ExpireTimeSpan = TimeSpan.FromMinutes(2);
        options.SlidingExpiration = true;
    });
}

cant understand the difference, i will be glad for hearing any help.


text:
Q: Push notifications-Android Studio I am planning to do small project which involves notification's widely but I have no idea where to start from, I need a particular type of notification's which is used in news paper app's.
In this process the app will not be updated but still notify a user of new messages or events and I want to make the message appear in the status bar.

A: You'll need to learn about Google Cloud Messaging GCM tutorial
And you'll have to learn about Android NotificationManager Notification Manager tutorial.  Good luck


text:
Q: Add character after each fourth symbol of the string I have string like that "blabllabnsdfsdfsd"
I want to make it "blab-llab-nsdf-sdfs"
Is it doable with Regex.Replace somehow?
What is the best way of doing this?

A: string bla = "blabllabnsdfsdfsd";

bla = Regex.Replace(bla, ".{4}", "$0-");
bla = bla.Remove(bla.Length - 1);

A: The easiest way would be to make another string copy this string into that one character by character and add a - after each 4 characters.
string a = "abcdefghijklmn";
List<char> b= new List<char>();
int j = 0;

for (int i = 0; i < a.Length; i++)
{
    if (i % 4 == 0)
    b.Add('-');
    b.Add(a[i]);
}

String result = new String(b.ToArray()) ;

A: I would say a for loop.
for( i = 0 ; i < string.length ; i+4){
   string.addAtPosition(i , "-");
}

the function name depends on the language.

A: for(int i = 0; i < str.Length; ++i)
{
    if(i % 4 == 0 && i != 0)
        newStr += "-" + str[i];
    else
        newStr += str[i];
 }

Here you go.
You take the modulo from the division to conclude it is the 4th char.

A: One way to do it would be :
string s = "blabllabnsdfsdfsd";
StringBuilder sb = new StringBuilder();
int position = 0;
// add a `-` every 4 chars
while (position < s.Length -4) // the (-4) is to avoid the last `-`
{
    sb.Append(s.Substring(position, 4));
    sb.Append("-");
    position += 4;
}
sb.Append(s.Substring(position)); // Adds the last part of the string
Console.Out.WriteLine("out" + sb.ToString());

Output: blab-llab-nsdf-sdfs-d
you could play around with it ... You could run the loop with a while (position <s.Length) (without the -4, and then just trim the string to remove the last -, and so on.
Hehe, just noticed i have an extra d in my input, so hence, the extra -d in the output.

A: Tried and tested
List<String> str = new List<String>();

String myString = "blabllabnsdfsdfsd";
int index = 0;

for (int i = 0; i < myString.Length; i = i + 4)
{
    index = i;
    if (myString.Length >= index + 4)
        str.Add(myString.Substring(index, 4));
}

myString = String.Join("-", str.ToArray());

Here is proof

A: The question seems simple however looking at the range of answers there is a lot of different ways to implement this. Here's my take on it assuming that you want to keep the last characters after the final dash -
var value = "blabllabnsdfsdfsd";

const int lengthOfSeperator = 4;

for (var i = 0; i <= Math.Floor(value.Length / (decimal)lengthOfSeperator); i++)
{
    if (lengthOfSeperator + (lengthOfSeperator * i) + i > value.Length) continue;
    value = value.Insert(lengthOfSeperator + (lengthOfSeperator * i) + i, "-");
}

Returns blab-llab-nsdf-sdfs-d

A: A quick one-liner:
        string blab = "blabllabnsdfsdfsd";
        string blab2 = String.Join("-", Regex.Matches(blab, ".{1,4}").OfType<Match>().Select(s => s.ToString()).ToArray());
        Console.WriteLine(blab);
        Console.WriteLine(blab2);

As a String Extension:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string blab = "blabllabnsdfsdfsd";
        string blab2 = blab.Chunk("-", 4);
        Console.WriteLine(blab);
        Console.WriteLine(blab2);
    }
}

public static class Extensions
{
    public static string Chunk(this String str, string separator, int groupsOf)
    {
        string[] chunks = System.Text.RegularExpressions.Regex
            .Matches(str, ".{1," + groupsOf.ToString() + "}")
            .OfType<System.Text.RegularExpressions.Match>()
            .Select(s => s.ToString())
            .ToArray();
        return String.Join(separator, chunks);
    }
}


text:
Q: Runing python script in NodeJS I have a python script :
    #!/usr/bin/env python
# -*- coding: utf8 -*-

import time

continue_reading = True

# Welcome message
print "Launching..."
print "Press Ctrl-C to stop."

while continue_reading:
     print "Message inside loop"
     time.sleep(2)

If I launch this script with python Test.py it's OK :
Launching...
Press Ctrl-C to stop.
Message inside loop
Message inside loop

But if I use the python-shell module with NodeJS to run my Test.py inside a NodeJS app it not OK just because of :
time.sleep(2)

If I suppress it's work !
Something wrong with blocking thread in python and NodeJS ?
EDIT :
Here the app.js
var PythonShell = require('python-shell');
var pyshell = new PythonShell('myFolder/myScript.py');

// sends a message to the Python script via stdin
//pyshell.send('hello');

pyshell.on('message', function (message) {
  console.log(message);
});

pyshell.end(function (err) {
  if (err) throw err;
  console.log('finished');
});


text:
Q: Xbox One Controller not detected (loading gamepad.h from DirectXTK without library) I am using the DirectXTK library for the gamepad class. I compiled the library with only this class inside it and it works.
If I would only add the source files to my project, without the library, the size would be ~50KB instead of ~500KB.
However, the Xbox One Controller is not detected using the source    files without the library.
Any ideas on how to resolve this so my executable would be smaller in size?


text:
Q: Are tail-recursive functions ALWAYS to be avoided? If I recall correctly, tail recursive functions always have an easy non-recursive equivalent.
Since recursion involves unnecessary function call overhead, it's better to do it the non-recursive way.
Is this assumption always true? Are there any other arguments for/against tail-recursion?

A: If you are using a language with a good compiler then these types of recursion can be optimised away, so in those cases if it improves readability to use recursion, I'd say to stick with it.

A: No, it's not always true. Many languages and/or compilers can easily optimize a tail recursive call , and rewrite it to an iterative version, or in some way reuse the stack frame for subsequent calls.
The Scheme language mandates that implementation employ tail call optimization
gcc can optimize tail calls as well, consider a function for freeing all the nodes in a linked list:
void free_all(struct node *n)
{
    if(n != NULL) {
        struct node *next = n->next;
        free(n);
        free_all(next);
    }
}

compiles to, with optimization:
free_all:
        pushl   %ebp
        movl    %esp, %ebp
        pushl   %ebx
        subl    $20, %esp
        movl    8(%ebp), %eax
        testl   %eax, %eax
        je      .L4
        .p2align 4,,7
        .p2align 3
.L5:
        movl    4(%eax), %ebx
        movl    %eax, (%esp)
        call    free
        testl   %ebx, %ebx
        movl    %ebx, %eax
        jne     .L5
.L4:
        addl    $20, %esp
        popl    %ebx
        popl    %ebp
        ret

That is, a simple jump instead of recursivly calling free_all

A: No.
Go for readability. Many computations are better expressed as recursive (tail or otherwise) functions. The only other reason to avoid them would be if your compiler does not do tail call optimizations and you expect you might blow the call stack.

A: It depends on language, but often the overhead isn't that big. It may be subjective, but recursive functions tend be much easier to comprehend. Most of the time you wouldn't notice the performance difference.
I would go for tail recursion unless my platform was very bad at dealing with it (i.e. not doing it at all, but always pushing onto stack).


text:
Q: How do I determine the name of the client machine logged into Remote Destop? I can use GetSystemMetrics(SM_REMOTESESSION) Windows API function to determine if the current user is running via Remote Desktop.  Once I've verified that, is there any way for me to determine his machine name?

A: I found the solution:
WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE,
                           WTS_CURRENT_SESSION,
                           WTSClientName,
                           BufPtr,
                           BytesReturned);


text:
Q: Mysql if exist update else insert I Sql server i use this command to insert value and if the id already exist update the vale
string commandLine = "IF NOT EXISTS(SELECT clientid FROM Rating WHERE clientid = " + clientId + " AND userid = " + userid + ") " +
            "INSERT INTO Rating VALUES(@clientId,@userid,@rating) " +
            "ELSE " +
            "UPDATE Rating SET rating=@rating WHERE clientid = " + clientId + " AND userid = " + userid + ";";

And i now move to MySQL and this command won't work. there is any thing same in MySQL?

A: The INSERT ... ON DUPLICATE KEY UPDATE provides an easier syntax in MySQL and also gives you feedback as to what was happening via the affected-rows API call. Few people realise in my experience how handy it can come in your program logic to know that:

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if
the row is inserted as a new row, 2 if an existing row is updated, and
0 if an existing row is set to its current values.

A: If you have unique constraint or primary key on  clientid, userid you can use INSERT ... ON DUPLICATE KEY UPDATE Syntax
INSERT INTO Rating VALUES(@clientId,@userid,@rating)
ON DUPLICATE KEY
UPDATE Rating SET rating=@rating


text:
Q: Resolving loss of internet bandwidth in home network Recently, I've decided to connect my laptop at home to my modem/router through Ethernet cables built into my apartment. As these built-in Ethernet cables are usable via plugs built into the walls (called powerline adapters), I use some additional cabling (STP CAT6 cables) from my laptop/router to the plugs. In addition, I don't know any technical details about these built-in cables (as they're not visible), only the maximal bandwidth (1 GBit => Cat6?) that they're supporting. The built-in cables are Cat. 5e Ethernet cables.
The problem is now that when I set up the connection, I cannot use the full bandwidth that my internet connection is actually offering (100 Mbit/s), only about 85 Mbit/s between 85 - 88 Mbit/s, despite the fact that all cables involved should support the maximal bandwidth. In addition, my network card only reports a connection speed of 100 Mbit/s. I know from other tests with one of the Ethernet cables in use that I can use almost 99 Mbit/s when I connect my laptop directly to the router/modem using only this one cable. In this test, my network card also reports a connection speed of 1 Gbit/s. In addition, it is very unlikely that the length of the resulting cable connection from my laptop to my router involving the built-in cables exceeds 100 m.
So, what possible reasons for this loss of bandwidth exist? And how I can fix this issue?

I hope this might help resolve the issue: The built-in cables appear to be Cat. 5e Ethernet cables. So, is there any problem when I connect Cat6 Ethernet cables directly to Cat5e Ethernet cables via the plugs?

A: Each powerline adpater has a fixed MPS. The smallest I think is 85MBPS up to 500 MBPS.
I would guess you have the 85MBPS.
Plus, even the good quality powerline adapters typically suggest to not go above 20 meters.

A: Since the it's the house's built-in cabling limiting the speed to 100 Mbps and not your own cabling, router or modem, there's nothing you can do short of rewiring the house.
It's also probably not Cat5e since gigabit Ethernet will happily run over such cables.


text:
Q: Using DI with ninject when interface has signature of other interfaces I have an interface called IXmlStrategy which has declared another Interface like this:
namespace IceServices.Business.Interfaces.Strategies
{
    public interface IXmlStrategy
    {
        IGetPersonNameXmlStrategy GetPersonNameXmlStrategy { get; }
    }
}

I expect there to be many strategy interfaces and I want to put all of them in once interface so I don't have to inject 10-20 IXmlStrategy variants.
This is my class using DI:
using System.Linq;
using IceServices.Business.Interfaces.Commands;
using IceServices.Business.Interfaces.Configurations;
using IceServices.Business.Interfaces.Deserializers;
using IceServices.Business.Interfaces.Mappers;
using IceServices.Business.Interfaces.Services;
using IceServices.Business.Interfaces.Strategies;
using IceServices.DomainObjects.ResponseObjects;

namespace IceServices.Business.Commands
{
    public class IpdCommands : IIpdCommands
    {
        private readonly ISoapService _soapService;
        private readonly IUrlConfigurations _urlConfigurations;
        private readonly IXmlDeserializer _xmlDeserializer;
        private readonly IDomainObjectMapper _domainObjectMapper;
        private readonly IXmlStrategy _xmlStrategy;

        public IpdCommands(ISoapService soapService, IUrlConfigurations urlConfigurations, IXmlDeserializer xmlDeserializer, IDomainObjectMapper domainObjectMapper, IXmlStrategy xmlStrategy)
        {
            _soapService = soapService;
            _urlConfigurations = urlConfigurations;
            _xmlDeserializer = xmlDeserializer;
            _domainObjectMapper = domainObjectMapper;
            _xmlStrategy = xmlStrategy;
        }

        public PersonNameResponse GetPersonName(int id)
        {
            var webServiceXmlString = _xmlStrategy.GetPersonNameXmlStrategy.GetXml(id.ToString());
            var listOfProperties = typeof(PersonNameResponse).GetProperties().Select(expr => expr.Name);

            var xmlStringResponse = _soapService.CallWebService(_urlConfigurations.GetPersonFirstname, webServiceXmlString);
            var stringArrayOfProperties = listOfProperties as string[] ?? listOfProperties.ToArray();
            var dictionaryData = _xmlDeserializer.DeserializeXmlToDictionary(stringArrayOfProperties, xmlStringResponse);
            return _domainObjectMapper.MapDictionaryToObject<PersonNameResponse>(dictionaryData, stringArrayOfProperties);
        }
    }
}

as you can see I'm calling GetPersonNameXmlStrategy.GetXml(id) like this:
  var webServiceXmlString = _xmlStrategy.GetPersonNameXmlStrategy.GetXml(id.ToString());

However I get a runtime error because IOC doesn't understand how to resolve it's dependency:

{"Message":"An error has occurred.","ExceptionMessage":"An error occurred when trying to create a controller of type 'IpdController'. Make sure that the controller has a parameterless public constructor.","ExceptionType":"System.InvalidOperationException","StackTrace":"   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Error activating IXmlStrategy using binding from IXmlStrategy to XmlStrategy\r\nNo constructor was available to create an instance of the implementation type.\r\n\r\nActivation path:\r\n  3) Injection of dependency IXmlStrategy into parameter xmlStrategy of constructor of type IpdCommands\r\n  2) Injection of dependency IIpdCommands into parameter ipdCommands of constructor of type IpdController\r\n  1) Request for IpdController\r\n\r\nSuggestions:\r\n  1) Ensure that the implementation type has a public constructor.\r\n  2) If you have implemented the Singleton pattern, use a binding with InSingletonScope() instead.\r\n","ExceptionType":"Ninject.ActivationException","StackTrace":"   at Ninject.Activation.Providers.StandardProvider.Create(IContext context)\r\n   at Ninject.Activation.Context.ResolveInternal(Object scope)\r\n   at Ninject.Activation.Context.Resolve()\r\n   at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()\r\n   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source)\r\n   at System.Linq.Enumerable.WhereSelectArrayIterator2.MoveNext()\r\n   at System.Linq.Buffer1..ctor(IEnumerable1 source)\r\n   at System.Linq.Enumerable.ToArray[TSource](IEnumerable1 source)\r\n   at Ninject.Activation.Providers.StandardProvider.Create(IContext context)\r\n   at Ninject.Activation.Context.ResolveInternal(Object scope)\r\n   at Ninject.Activation.Context.Resolve()\r\n   at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()\r\n   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source)\r\n   at System.Linq.Enumerable.WhereSelectArrayIterator2.MoveNext()\r\n   at System.Linq.Buffer1..ctor(IEnumerable1 source)\r\n   at System.Linq.Enumerable.ToArray[TSource](IEnumerable1 source)\r\n   at Ninject.Activation.Providers.StandardProvider.Create(IContext context)\r\n   at Ninject.Activation.Context.ResolveInternal(Object scope)\r\n   at Ninject.Activation.Context.Resolve()\r\n   at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()\r\n   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"}}

This is my IOC setup in Ninject.WebCommon:
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IIpdCommands>().To<IpdCommands>();
    kernel.Bind<IUrlConfigurations>().To<UrlConfigurations>();
    kernel.Bind<IXmlDeserializer>().To<XmlDeserializer>();
    kernel.Bind<IXmlDocumentFactory>().To<XmlDocumentFactory>();
    kernel.Bind<IDomainObjectMapper>().To<DomainObjectMapper>();
    kernel.Bind<ISoapService>().To<SoapService>();

    kernel.Bind<IXmlStrategy>().To<XmlStrategy>();
    kernel.Bind<IGetPersonNameXmlStrategy>().To<GetPersonNameXmlStrategy>();
}

I need to change how the binding works for IGetPersonNameXmlStrategy but I'm not sure how. Does anyone know how I can get Ninject to resolve the depedency through IXmlStrategy.IGetPersonNameXmlStrategy ?

A:
I expect there to be many strategy interfaces and I want to put all of them in once interface so I don't have to inject 10-20 IXmlStrategy variants.

Don't do this. What you are doing is described as a code smell here:

Service abstractions should not expose other service abstractions in their definition

In your case, your IXmlStrategy service abstraction exposes the IGetPersonNameXmlStrategy abstraction from its definition.

put all of them in once interface so I don't have to inject 10-20 IXmlStrategy variants.

This is a Interface Segregation Principle (ISP) violation. ISP states that:

no client should be forced to depend on methods it does not use.

Having such wide interface will cause a few things:

*

*The interface will keep growing, which forces you to update the existing implementations as well.

*It complicates unit testing, because it becomes unclear what dependencies a class under test uses.

*When you keep adding services to that interface, the interface becomes a form of a Service Locator.

Instead you should simply let a consumer depend on the service that it requires. Not on the abstraction over the abstraction. In your specific case, inject the IGetPersonNameXmlStrategy directly into the consumer that requires it.
The most likely reason for you to have this Service Locator-like abstraction is because you are violating the Single Responsibility Principle (SRP). This principle states that classes should be focussed on one particular job, and only one requirement should cause them to change. When a class has many dependencies, it is a good indication that SRP is violated.
Classes that violate SRP tend to have constructors with many dependencies. This is called constructor over-injection. Constructor over-injection however is a symptom. You can fix over-injection by grouping dependencies, but that won't solve the root cause. The root problem is that the class is too complex and grouping together those dependencies won't fix this problem.
Instead a refactoring should take place. For instance, you can extract all the code that you have in a single method into a class of its own. This leaves you with just one dependency that can be injected in the original class. When you do this with all methods, you might even be able to remove the original class altogether, because it might now have lost its meaning.


text:
Q: Jenkins Using checkout scm to clone repo from Github Overview:

*

*I am trying to checkout the github code in my multi-configuration jenkins pipeline:
package checkout
void call() {
    println "checkout stage ..."
    node {
        deleteDir()
        checkout scm
    }
}

*I am using JTE (Jenkins Template Engine)
ISSUE:
But jenkins complains error Step checkout from the library checkout does not have the method call(GitSCM) after building the pipeline. Please find the stacktrace below:
hudson.remoting.ProxyException: org.boozallen.plugins.jte.binding.TemplateException: Step checkout from the library checkout does not have the method call(GitSCM)
    at org.boozallen.plugins.jte.binding.injectors.StepWrapper.invoke(script1596520065305271654461.groovy:98)
    at org.boozallen.plugins.jte.binding.injectors.StepWrapper.call(script1596520065305271654461.groovy:60)
    at checkout.script15965200672531305703678.call(script15965200672531305703678.groovy:19)
    at ___cps.transform___(Native Method)
    at sun.reflect.GeneratedConstructorAccessor515.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:83)
    at org.codehaus.groovy.reflection.CachedConstructor.doConstructorInvoke(CachedConstructor.java:77)
    at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrap.callConstructor(ConstructorSite.java:84)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:60)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:235)
    at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.constructorCall(DefaultInvoker.java:25)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:97)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor632.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:107)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor632.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:89)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:113)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor632.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)

As I am new in groovy and Jenkins, I would appreciate it if you could share any genuine solution or idea.

A: I found my issues and will post it here to be used by newbies like me:
I needed to do following changes and rerun the jenkins build to fix the issue:

*

*Move the node keyword to the template jenkinsfile in /templates/jenkinsfile
node('<executer node>') {
 scm_checkout()
}

*Update the pipeline_config.groovy file in /templates/directory:
libraries {
  merge = true
  scm_checkout
}

*Update the library directory name to scm_checkout. the directory and file name should be different form checkout to avoid referring the checkout(scm) to the wrong lib.

*The checkout lib should in libraries/scm_checkout/scm_checkout.groovy and the content is like below:
void call() {
    println "checkout stage ..."

    deleteDir()

    def checkout = checkout(scm)

}


text:
Q: Como hacer un switch en javascript Tengo varios if-else que necesito simplificar:
var color = "";
if (tipo == "0") {
   color = "FF0000";
 } else if (tipo == "1") {
   color = "CC9900";
 } else if (tipo == "2") {
   color = "AA0000";
 ....
 } else {
   color = "000000";
 }

Hay manera de hacer un switch en javascript?

A: Para ello puedes usar un switch, aunque dependiendo de donde venga la variable a identificar deberás trimearla o convertir el String en int primero o para que no de problemas:
var color = "";
var typeInt = parseInt(type)
alert(typeInt);
switch(typeInt) {
    case 0:
        color = "#FF0000"
        break;
    case 1:
        color = "#CC9900"
        break;
    case 2:
        color = "#AA0000"
        break;
    default:
        color = "#000000"
}

A: También se puede utilizar la función corta de un switch case de la siguiente manera:

var color = "";
var miTipo = prompt("Ingrese un numero");
var casos = {
    0: "#FF0000",
    1: "#CC9900",
    2: "#AA0000"
};
//si hay condicion cumplida
if (casos[miTipo]) {
  color = casos[miTipo];
}else{
  //Aqui lo que seria el default de un switch case tradicional
  color = "#000000";
}
alert('El color es: ' + color);

A: Un switch es básicamente una simplificación de una comparación estricta === en javascript con algunos valores añadidos.
Tomando como partida la siguiente comparación
if (variable === valor1) {
    // bloque 1 de código
} else if (variable === valor2) {
    // bloque 2 de código
} else if (variable === valor3) {
    // bloque 3 de código
} else {
   // bloque de código si las demás condiciones no se cumplen
}

Se traduce en
switch(variable) {
    case valor1:
        // bloque 1 de código
        break;
    case valor2:
        // bloque 2 de código
        break;
    case valor3:
        // bloque 3 de código
        break;
    default:
        // bloque de código si las demás condiciones no se cumplen
}

Recuerda que comparación relajada == y comparación estricta === no se comportan igual todo el tiempo por lo que no debes usar switch si tu código depende de alguna conversión de datos (o debes convertir antes de ejecutar el switch) ya que este siempre usará comparación estricta.
Cuales son los valores añadidos que se pueden obtener con un switch que pueden ser más complicados de obtener usando if?

*

*Con el switch se puede ejecutar más de un bloque a la vez dependiendo de la condición. Para esto solo hay que quitar la instrucción break y esta continuará a los siguientes bloques de código
switch(variable) {
    case valor1:
        // bloque 1 de código
    case valor2:
        // bloque 2 de código
        break;
    case valor3:
        // bloque 3 de código
        break;
    default:
        // bloque de código si las demás condiciones no se cumplen
}

En este caso si la variable es igual a valor1 se ejecutarán tanto el código en el bloque 1 como en el bloque 2. Esto en algunas ocasiones puede ayudar a simplificar código. Esto es lo que se conoce como código común o caída. (Ten mucho cuidado con esto ya que este truco vuelve el código menos legible).

*Debido a que switch usa comparación estricta se puede usar para simplificar código cuando se quiere hacer una comprobación de identidad.

Dos objetos distintos nunca son iguales tanto en la comparación estricta como relajada.
Una expresión comparando objetos es true sólo si los operandos referencian exactamente el mismo objeto.

Considera el siguiente caso

function fn() {
  // Bloque de código
}

var arr = [1, 2, 3];

var foo = {};

var obj = {
  prop: fn
}

switch (obj.prop) {
  case foo:
    console.log('Es el objeto foo');
    break;
  case fn:
    console.log('Es la funcion fn');
    break;
  case arr:
    console.log('Es el arreglo arr');
    break;
  default:
    console.log('No se lo que es');
}

El switch funciona con cualquier tipo de referencia, incluso funciones. Si mantienes una referencia a varios objetos que quieras identificar es muy sencillo usar un switch para saber de cual de ellos se trata ya que en javascript un objeto sólo es igual a si mismo (un objeto no es lo mismo que un primitivo).
Para convertir tu código a switch

var color = "";
var tipo = prompt("Ingrese un numero");

switch (tipo) {
  case "0":
    color = "FF0000";
    break;
  case "1":
    color = "CC9900";
    break;
  case "2":
    color = "AA0000";
    break;
  default:
    color = "000000";
}
alert('El color es: ' + color);

A: Según la referencia de la instrucción switch de W3Schools, puedes adaptar tu código de la siguiente manera:
var color = "";

switch (color) {
    case "0":
        color = "FF0000";
        break;
    case "1":
        color = "CC9900";
        break;
    case "2":
        color = "AA0000";
        break;
    default:
        // Establece algún valor por defecto
        // "en caso de que ninguna condición aplique a las opciones anteriores".
        color = "000000";
        break;
}


text:
Q: Github reusable workflow with schedule as trigger does not work I have a simple workflow that calls a reusable workflow to build a container image. In my case the job won't start as scheduled at all. I know the trigger schedule will only work from the master branch on the repo executing the workflow and we have indeed both caller workflow and reusable workflow in the master/default branch.
name: build image

on:
  push:
    branches: [ 'master' ]
  pull_request:
  schedule:
    - cron: "0 8 * * 1-5"
jobs:
  build_container_dateTag:
    uses: MyOrganizationName/my-workflows/.github/workflows/workflow-build.yaml@master
    with:
      staticTag: true
      ImageName: 'myimage'
      ImageTag: 'mytag'

Just wondering if someone has had the same experience. The job was working fine previously without the reusable workflow and all container build steps within this workflow and it works fine on push to master.
We are running on GHES 3.4.7

A: Update to this problem. An update to GHES 3.5.6 fixed it.
I had to remove and re-add my workflow from the default branch though


text:
Q: JavaScript function not giving the right output This is a section of my view in which I want the result to show.
Can any one solve this problem?
When this.waitlist works, it should return the container like div#sntq-waitlist but it gives object[ ] instead.
Can anyone tell me why this is?
JavaScript
initLiveWaitList: function() {
  this.waitlist_ = $('sntq-waitlist');
  this.daily_status_ = $('sntq-daily_status');
  this.waiting_ = $('sntq-waiting');
  this.seated_ = $('sntq-seated');
  this.oneFour_ = $('sntq-one-four');
  this.fiveSix_ = $('sntq-five-six');
  this.seven_ = $('sntq-seven');

  this.running_ = true;

  this.loadWaitList_();
  this.intervalId_ = this.loadWaitList_.periodical(1200000, this);

  window.addEventListener('focus', function() {
      if (!this.running_) {
        this.loadWaitList_();
        this.intervalId_ = this.loadWaitList_.periodical(1200000, this);
      }
     }.bind(this));

    window.addEventListener('blur', function() {
        clearInterval(this.intervalId_);
        this.running_ = false;
      }  .bind(this));
  },

View

A: I don´t think I completely understood your question, but to me it looks like you are using jQuery to get the containers at the top of your code.
If this is the case you are probably just missing the ID selector.
Try to change the code to
this.waitlist_ = $('#sntq-waitlist');
this.daily_status_ = $('#sntq-daily_status');
//[...]

(note the "#" selector if you want to look for elements by ID, which seems to be the case in your example).


text:
Q: cant import pygame using vscode , python 3.8 , pygame installed from powershell so im using visual code,
have python 3.8 installed and i installed the pygame package from powershell,
yet when im writing pygame code it gives me the next error:
" ModuleNotFoundError: No module named 'pygame' "
tried everything for hours cant get it to work
help will be apriciated <3
images:

A: What you also can do is to download pygame to your folder and than run the command python setup.py. This should install everythin correctly. If you still have trouble using pygame you can use the files in src_py from the download:
import init #instead of pygame.init()

I hope I was able to help.


text:
Q: Implementing IPermission I'm considering writing a custom IPermission implementation but am not clear as to how it should work. I've already implemented IPrincipal and IIdentity. What I would like to accomplish is to be able to check permissions vis a vis the current IPrincipal's authorizations rather than its roles. Generally, authorizations are read/add-delete/update/none for a given type. So I would like to write something like this:
[CustomPermission(SecurityAction.Demand, Type = typeof(Foo), MinimumAuthorization = AuthorizationFlags.Read)]
public void SomeMethod(){}

Is this possible? I've looked over the code at http://msdn.microsoft.com/en-us/library/system.security.ipermission.aspx. This shows how to implement the interface, but I don't understand how the above pseudo-code would be able to check against the IPrincipal's authorizations for the type.

A: Your CustomPermission implementation of IPermission.Demand should be able to look at the Thread.Current.CurrentPrincipal, cast that to your custom principal and from there investigate your authorization data.


text:
Q: What are some other options for generating bit grids of size N As is well known, permutations for square bit grids can be calculated using a brute force algorithm where an integer loop from 0...((2^cells)-1) can be converted into each grid permutation using a bit mask. A few examples:
Grid size 2 (4 cells): 0-->15

Grid size 3 (9 cells): 0-->511

This works well for grids up to a certain size, but for grids of size 7 and greater the sheer number of loop operations gets into the trillions.
What other options are there?
I already have working code for grids up to size 6 but a quick Fermi estimate has a size 7 grid coming out at about 76 years on my workstation with all CPUs at maximum... :-(
Target application
Re the actual application of said grids, this would be pretty much the same as for a Nurikabe puzzle but I'm only interested in grids that can be mirrored across their X or Y axis (preferably both). So some suitable patterns might be a diamond (X & Y), the letter D (Y) or letter A (X).
Existing efficiencies
Due the vagaries of the target application there are many candidates that can be discarded:

*

*Those that don't create a cell on the edges of the grid

*Those that cannot be mirrored across the X or Y axis

*Those where cells are isolated

Sample output (N=4)
Current value is : 28662
 ##
####
####
 ##

Current value is : 40953
#  #
####
####
#  #

Current value is : 63087
####
 ##
 ##
####

Current value is : 63903
####
#  #
#  #
####

Current value is : 65535
####
####
####
####

Grid size 4, done in 22 milliseconds

A: There are 2^n bit masks of size n. You can not possibly hope to generate them all in complexity less than 2^n. You either need an alternative solution to your problem where you don't generate all bit masks, or you will not be able to improve this value.

A: Conservation of information dictates there is no way to generate all array patterns in better than O(2^cells) - you have to consider each case at least once.
However you can optimise it by parallelizing the generation of each array pattern, by using packed bit-sets and maybe SIMD.
There is a technique of systematically generating bit patterns called Maximum Length Sequence. The crucial feature of the generation algorithm is that every possible bit pattern (for a certain number of cells) is generated EXACTLY ONCE. It uses XOR to iteratively calculate successive values, which can be optimised (up to reasonable sizes) with SSE/MMX.
Link: http://web.iitd.ac.in/~saifkm/docs/EEL319/Practical/expt3_319.pdf

A: If you are only interested in grids that can be mirrored then just generate a quarter or a half of the grid, and mirror it.
For a 7x7:
X and Y mirroring: Generate all possible X and Y axis permutations 2^(7 + 7 - 1) times all possible 3x3 permutations 2^(3 * 3). Since the 3x3 will be mirrored on the 4 corners thats only 2^13 * 2^9 permutationes 4,194,304 to generate.
X or Y mirroring: Generate permutations for 1 axis 2^7 and permutatins for a 3x7 grid 2^21, which is a total of 268,435,456
For a 8x8:
X and Y mirroring: All of the 4x4 permutationes 2^16 or 65536.
X or Y mirroring: All of the 4x8 permutationes 2^32 ~4billion (a modern computers should be able to do this in under a minute).


text:
Q: fetching embedded documents on search criteria of another embedded document I have a collection HostelTbl which has many documents one of the document is like
    {
    "_id": ObjectId("5ae69fb4d2ccda0e70005551"),
    "Name": "Hostel-MGL-02",
     ...
    "RoomsDetails": [
     {
       "RoomId": "9a21e427-16fd-7a9e-bc16-537dc55093bb",
       "FloorNumber": "1",
       "RoomNumber": "101",
        ...
     },
     {
       "RoomId": "050c65ab-355e-9bec-00a0-2999e75bcdc4",
       "FloorNumber": "1",
       "RoomNumber": "104",
       ...
     },
     {
       "RoomId": "f197c635-a6fb-b4d6-9cf5-ed53177edd47",
       "FloorNumber": "2",
       "RoomNumber": "109",
       ...
     },
     ...
     {
       ...
     }
    ],
   "AllotmentsDetails": [
   {
      "AllotmentId": "5eb05e1d-2690-afad-747a-ef29450ae3f3",
      "StudentId": ObjectId("5ab8d5d4ff24ae120400085e"),
      "RoomId": "9a21e427-16fd-7a9e-bc16-537dc55093bb",
      "FromDate": ISODate("2018-06-12T22:00:00.0Z"),
      "ToDate": ISODate("2018-07-04T22:00:00.0Z"),
      ...
     },
     {
      "AllotmentId": "40d73d84-0f94-48d8-823c-2255fd2ae0ed",
      "StudentId": ObjectId("5ab8d5bcff24ae120400085d"),
      "RoomId": "050c65ab-355e-9bec-00a0-2999e75bcdc4",
      "FromDate": ISODate("2018-01-21T22:00:00.0Z"),
      "ToDate": ISODate("2018-02-06T22:00:00.0Z"),
      ...
       },
       {
      "AllotmentId": "40d73564-0f94-48d8-823c-2255fd2440428",
      "StudentId": ObjectId("5ab8d5bc4624ae1204000855),
      "RoomId": "f197c635-a6fb-b4d6-9cf5-ed53177edd47",
      "FromDate": ISODate("2018-03-21T22:00:00.0Z"),
      "ToDate": ISODate("2018-05-04T22:00:00.0Z"),
      ...
       }
     ]
  }

I have two embedded documents inside one documents. One is storing rooms information and another storing rooms allotments to a student information.
Now I want to fetch those available rooms from RoomsDetails if their allotments detail's "ToDate" field contains the dates in past from today inside AllotmentsDetails Embedded document. Like in the above case the rooms with ids
"050c65ab-355e-9bec-00a0-2999e75bcdc4", f197c635-a6fb-b4d6-9cf5-ed53177edd47 contains ToDate dates in the past inside AllotmentsDetails embedded documents. It should fetch those two rooms only.
I am not able to find such queries. Please help!!!
I am trying to tweak the below lines of code
public function fetchAllAvailableRooms()
{
   $cursor = $this->collection->aggregate(array(
             array(
                   '$match' => array(
                                "_id" => new MongoDB\BSON\ObjectID($this->id)
                                )
                  ),
             array(
                  '$project' => array(
                  'RoomsDetails' => array(
                  '$filter' => array(
                  'input' => '$AllotmentsDetails',
                  'as' => 'allot',
                  'cond' => array(
                  '$lt' => array('$$allot.FromDate', $this->Today)
                   )
                  )
                 ),
               'Name' => 1
                )
              )
            ))->toArray();

    return $cursor;
   }

A: You can use the $map and $filter aggregation operators for that.

*

*$map - for AllotmentsDetails transformation into final list
of the room ids

*$filter - for RoomsDetails filtering by the
final list of the room ids
Example:
public function fetchAllAvailableRooms()
{
    $cursor = $this->collection->aggregate([
        ['$match' => ["_id" => new MongoDB\BSON\ObjectID($this->id)]],
        [
            '$addFields' => [
                'filteredIds' => [
                    '$map' => [
                        'input' => '$AllotmentsDetails',
                        'as' => 'item',
                        'in' => [
                            '$cond' => [
                                ['$lt' => ['$$item.ToDate', $this->Today]],
                                '$$item.RoomId',
                                false
                            ]
                        ]
                    ]
                ]
            ]
        ],
        [
            '$project' => [
                'RoomsDetails' => [
                    '$filter' => [
                        'input' => '$RoomsDetails',
                        'as' => 'item',
                        'cond' => ['$in' => ['$$item.RoomId', '$filteredIds']]
                    ]
                ]
            ]
        ]
    ])->toArray();

    return $cursor;
}

/* Result example
{
    "_id" : ObjectId("5ae69fb4d2ccda0e70005551"),
    "RoomsDetails" : [
        {
            "RoomId" : "050c65ab-355e-9bec-00a0-2999e75bcdc4",
            "FloorNumber" : "1",
            "RoomNumber" : "104"
        },
        {
            "RoomId" : "f197c635-a6fb-b4d6-9cf5-ed53177edd47",
            "FloorNumber" : "2",
            "RoomNumber" : "109"
        }
    ]
}
*/

P.S. PHP code is not tested, so i'm not 100% sure if it is working.
P.P.S. The final solution is strongly depends on the details of your project.


text:
Q: SELECT 0 for multiple rows of join I have an invoices and a payments table.
For each invoice record (which contains an OriginalInvoiceValue field), there can be multiple payments associated in the payments table.  In a select that joins the two tables, each invoice record is of course repeated for each occurrence of an associated payment record.
What I would like though, is to have the OriginalInvoiceValue field returned only once per invoice, and then have it return 0 (or NULL) for each additional occurrence of an associated payment record. (Such that if I were to export the data to excel and sum the OriginalInvoiceValue column, I actually get the real total of all invoices, instead of getting it multiplied by each additional occurrence of a payment).
Is this possible in T-SQL?

A: If Sql Server 2005 or newer, you might assign row numbers to individual payments of an invoice, and left join to invoices selecting actual invoice record for first payment only. Put order by you require in row_number() part; I've chosen PaymentID, but payment date is probably more appropriate.
; with p as (
  select *,
         row_number() over (partition by InvoiceID
                            order by PaymentID) rn
    from payments
)
select *
  from p
  left join invoices i
    on p.InvoiceID = i.InvoiceID
   and p.rn = 1
order by p.InvoiceID, rn

And here is SQL FIDDLE with example.


text:
Q: Using redux-promise-middleware with web component tester I have an import called redux-scripts
<link rel="import" href="../config.html">
<script src="../../node_modules/redux/dist/redux.min.js"></script>
<script src="../../bower_components/amazon-cognito-identity-js/dist/aws-cognito-sdk.min.js"></script>
<script src="../../bower_components/amazon-cognito-identity-js/dist/amazon-cognito-identity.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-promise-middleware/4.4.1/redux-promise-middleware.min.js"></script>
<script src="./redux-promises.js"></script>

Which I import at the top of redux-mixin.html
<link rel="import" href="../../bower_components/polymer-redux/polymer-redux.html">
<script src="../../bower_components/aws-sdk/dist/aws-sdk.min.js"></script>
<link rel="import" href="redux-scripts.html">

<script type="module" src="./index.js"></script>
<script nomodule src="./bundle.js"></script>

Runs like a charm in Chrome and firefox, but when it comes to web component tester:
redux-store.js:22 Uncaught ReferenceError: ReduxPromiseMiddleware is not defined
at redux-store.js:22

Which is referring to
import programs from './programs/programsReducer.js';
import videos from './videos/videosReducer.js';
import video from './video/videoReducer.js';

const rootReducer = Redux.combineReducers({
  programs,
  videos,
  video,
});

// Setup a Redux store
const initialState = {
  viewSpecificToolbar: 'videos',
};

const store = Redux.createStore(
  rootReducer,
  initialState,

  // The best part 8)
  Redux.compose(
    Redux.applyMiddleware(ReduxPromiseMiddleware.default()),
    window.devToolsExtension ? window.devToolsExtension() : (v) => v
  )
);

export {store};

I've implemented a partial workaround by adding this to the top of redux-store.js
const scripts = Polymer.ResolveUrl.resolveUrl('./redux-scripts.html');
Polymer.importHref(scripts, null, null, false);

But it's not super satisfying, as it causes many errors when running tests, and not all of the test suites run.

A: Another solution was to add the redux-scripts.html import to all test files, however, a better solution was attained by altering the redux-promise-middleware library. In version 4.4.2, the import statement in index.js now points to the relative path ./isPromise.js with file extension. With that in place, I can import promiseMiddleware from '../../node_modules/redux-promise-middleware/dist/es/index.js' in redux-store.js and we're golden.


text:
Q: Angular dropdown changing other dropdowns I have a situation when i select the drop down it changes the value in other dropdowns on the page as well.
I tried to figure out what was causing the issue and i notice that it goes away if i remove the trackBy in ngFor.
Unfortunately, i need the trackBy to improve performance.
Any clue why this is happening ? Here is a stackblitz demonstrating the problem :
https://stackblitz.com/edit/angular-27snjx


text:
Q: Calling parse javascript function from HTML form event I've been trying to call a simple javascript login function from an html form submission and it doesn't seem to be calling the method. I have tried moving the method to an external .js class and the function still is not working. The java script function is in the header called Login() uses the variables from the form to pass them into the web service and login. I've tried calling other functions from an external homepage.js script too and they are not firing the event. My intention is to push to the index.html page if login is successful. Thanks.
Code:

      <button onclick="WarningSigns()" class="btn btn-danger" type="button">Warning signs</button>

Bronchiectasis

Self-management action plan

Login

          <form name="loginForm" action="javascript:Login()">
            <fieldset>

                <input name="uname" type="text" placeholder="Username">

                <input name="pword" type="password" placeholder="Password">

              <button class="btn primary" type="submit">Sign in</button>
            </fieldset>
          </form>

A: The logIn function from the Parse API requires string values for its username and password arguments. You are passing in HTML elements.
Change the call to this:
  Parse.User.logIn(document.loginForm.uname.value, document.loginForm.pword.value,
  {
    success: function(user)
    {
      window.location="/index.html";
    },
    error: function(user, error)
    {
      alert('error '+error);
      // The login failed. Check error to see why.
    }
  });

And you should get further.
Updated Fiddle: http://jsfiddle.net/JYsZe/1/


text:
Q: How to style SVG > Image code (no path) via CSS? We exported a .eps file in Photoshop to SVG via Export As... the resulting SVG code (when opened in a text editor) is:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="208" height="208" viewBox="0 0 208 208"><image x="6" y="18" width="196" height="172" xlink:href="data:img/png;base64,[encoded data, 12472 characters]"/></svg>

We're trying to alter the color of the svg via fill: #000000 !important; but no luck. I know that when you have a path you can alter the path via CSS fill but we're having trouble figuring out how to either export this in the correct format via PS or how to style this svg > image output via CSS.
We've also tried inserting the svg via <img src="cart.svg" /> and styling with no luck there either. Any advice/help/direction greatly appreciated!

A: Unfortunately what you're trying to do isn't possible.

SVG files displayed with  are treated as an image: external resources aren't loaded, :visited styles aren't applied, and they cannot be interactive.

MDN Web Docs: SVG element reference
Do you have any access to the SVGs themselves and the code that calls them? Also, if you can open the EPS in Illustrator instead, you may have better luck.

A: Consider using CSS filters to change svg coloration instead of fill
For example, red color can be obtained with this combination of CSS filters:
 filter: invert(21%) sepia(93%) saturate(7500%) hue-rotate(358deg) brightness(110%) contrast(119%);
You can get the desired combination of filters for a specific color using the utility
https://codepen.io/sosuke/pen/Pjoqqp

Hover to change color

 .img {
 filter: invert(0%) sepia(0%) saturate(0%) hue-rotate(151deg) brightness(106%) contrast(104%);
 }
  .img:hover {
 filter: invert(21%) sepia(93%) saturate(7500%) hue-rotate(358deg) brightness(110%) contrast(119%);
  }
 <svg class="img" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="208" height="208" viewBox="0 0 208 208">

  <image  x="6" y="18" width="196" height="172" xlink:href="data:img/png;base64,[encoded data, 12472 characters]"/></svg>

A: This is not a vector image, you can't alter its color using fill or stroke, but you can use filter to achieve it as a workaround:
style="filter: brightness(0);"

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="208" height="208" viewBox="0 0 208 208" style="filter: brightness(0);"><image x="6" y="18" width="196" height="172" xlink:href="data:img/png;base64,[encoded data, 12472 characters]"/></svg>

style="filter: sepia(1) brightness(1.3) contrast(2) hue-rotate(-45deg);"

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="208" height="208" viewBox="0 0 208 208" style="filter: sepia(1) brightness(1.3) contrast(2) hue-rotate(-45deg);"><image x="6" y="18" width="196" height="172" xlink:href="data:img/png;base64,[encoded data, 12472 characters]"/></svg>


text:
Q: how to rotate an UIImageview under the finger with constant 5 degrees rotation? I am making a clock that can be controlled by the user.I have a UIImagview with a name minhandview(minute hand needle of the clock). I want to rotate it under my finger(it should track the finger movement) with a constant rotation of 5 degrees when the user keep on rotating it.I am using the following code for it
- (void) touchesMoved:(NSSet *)_touches withEvent:(UIEvent *)_event

{
UITouch *touch=[[_event allTouches]anyObject];
CGPoint pt = [touch locationInView:self.view];

if([touch view]==minhandview)
{

    minhandview.transform = CGAffineTransformRotate(minhandview.transform, Degrees2Radians(5));
}

}
the image is rotating fine 5 degrees everytime this method is called but it is not following my finger(rotating to fast) how can I correct it? Please help. thanks


text:
Q: How to extract anchor class using beautifulsoup? Can anyone help me to resolve the error. My head is paining, I have wasted my 1 hour in solving this problem. Actually I am getting query_links as null(I should get all the classes values), but not so.
from flask import Flask, jsonify, request
# from markupsafe import escape
from bs4 import BeautifulSoup
import requests

app = Flask(__name__)

@app.route('/api/',methods=['GET'])
def API():
    if request.method == 'GET':
        url = 'https://www.brainyquote.com/'
        query = str(request.args['query'])

        if " " in query:
            query = str(query).replace(" ","+")
        else:
            pass

        search = '/search_results?q=' + query
        ready_url = url + search
        content = requests.get(ready_url).content
        soup =  BeautifulSoup(content, 'html.parser')
        quotes_links = soup.find_all("a", class_= "b-qt")
        print("hello")
        print(quotes_links)
        list = []
        for i in quotes_links:
            d = {}
            quote_url = url + i.get('href')
            quote_content = requests.get(quote_url).content
            quote_soup = BeautifulSoup(quote_content, 'html.parser')
            d['quote'] = quote_soup.find('p', class_= "b-qt").text
            d['author'] = str(quote_soup.find('p', class_= "bq-aut").text).strip()
            list.append(d)

        return jsonify(list)

if __name__ == "__main__":
    app.run(debug=True)

Please help me. Why I am not getting any value in json. My list is empty. And also Query_links is null. Is there any syntax mistake or anything else?

A: Your ready_url variable ends up having a double slash in it (i.e. https://www.brainyquote.com//search_results?q=testing). If you test that in a browser or with curl, you'll see that yields no results. If you fix the definition of url so it doesn't have the trailing slash (i.e. url='https://www.brainyquote.com'), your code will work.


text:
Q: how to transfer header for soap request in soapui? I have 2 requests
Request1 will generate a unique id every time and then I want to use this id  in Request2 Header
How can I transfer this automatically?
Thanks

A: var1=YourUniqueID
Then add header to your request like this or use a variation of this
getAllHttpSteps=testRunner.testCase.getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep)
    for (step in getAllHttpSteps){
        def headers = new StringToStringMap() //Use StringToStringMap Object to store headers key/value.
         headers.put("header field","$var1")
        //add more header fields if require
         step.testRequest.setRequestHeaders(headers) //setting header in request
    }

A: Groovy Script : I have store unique id as response and (use getdata from response of Request 1) . testRunner.testCase.setPropertyValue("GValue", response) and
in Request2 : Header name UniqueId and Header Value : ${#TestCase#GValue}


text:
Q: Complex Order By Queries using Rails 3.0 + Postgres Does rails have any way to have complex sorting at the database query level?
Ie/
Posts.order(up / down).all ?
What would be the best way to implement this on a database level (in postgres) without having to sort through a result in ruby using sort (which will slow down pagination etc).

A: If you use the wonderful meta_where gem, you can also do something like
Post.order(:create_at.asc)

To sort by a function of two or more columns you can do something like
Post.select("*, (up / down) as ratio").order("ratio asc")

You will have what you want and moreover every Post object in that array will have a ratio method for you to know the exact value.

A: Post.order("created_at DESC").all
Post.order("title ASC").all

See here, for more details.

A: Post.select("*, (up / greatest(down, 1)) as ratio").order("ratio asc")


text:
Q: Problem with using a Class in complex numbers calculator project I am Thomas and I am a computer science student. For my latest OOP project in Python I've been trying to do a simple complex numbers calculator.
My task involves making a 2- class project in Python
First is the class has 3 methods:
1st - create a complex number
2nd - display a complex number
3rd - erase the complex number
Second class has four methods: add, subtract, multiply and divide.
I've made first class and it's methods and I think they work fine on a basic level ( of course the code is primitive and it needs a lot of work :( )
I've stumbled upon a problem with the second class. I can't properly use methods: add, subtract, multiply and divide.
I'd like mathematical methods to use previously created two complex numbers, but i can't find the way to correctly finish my task.
Any help is appreaciated. Thank you !
My code:
class Complex (object):
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary

    def create_number(self):
        self.real = (float(input("Enter a real part of the complex number")))
        self.imaginary = (float(input("Enter an imaginary part of the complex number")))
        return Complex(self.real, self.imaginary)

    def display_number(self):
        print(f"Your complex number is: {Complex(self.real, self.imaginary)}")

    def erase_number(self):
        (self.real, self.imaginary) = (0, 0)
        print(f"Number is erased: {(self.real, self.imaginary)}")

    def __str__(self):
        if type(self.real) == int and type(self.imaginary) == int:
            if self.imaginary >= 0:
                return '%d+%di' % (self.real, self.imaginary)
            elif self.imaginary < 0:
                return '%d%di' % (self.real, self.imaginary)
        else:
            if self.imaginary >= 0:
                return '%f+%fi' % (self.real, self.imaginary)
            elif self.imaginary < 0:
               return '%f%fi' % (self.real, self.imaginary)

class Calculator(object):
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary

    def __add__(self, other):
        result_real = self.real+other.real
        result_imaginary = self.imaginary+other.imaginary
        result = Complex(result_real, result_imaginary)
        return result

    def __sub__(self, other):
        result_real = self.real-other.real
        result_imaginary = self.imaginary-other.imaginary
        result = Complex(result_real, result_imaginary)
        return result

    def __mul__(self, other):
        result_real = (self.real*other.real-self.imaginary*other.imaginary)
        result_imaginary = (self.real*other.imaginary+other.real*self.imaginary)
        result = Complex(result_real, result_imaginary)
        return result

    def __truediv__(self, other):
        result_real = float(float(self.real*other.real+self.imaginary*other.imaginary)/float(other.real*other.real+other.imaginary*other.imaginary))
        result_imaginary = float(float(other.real*self.imaginary-self.real*other.imaginary)/float(other.real*other.real+other.imaginary*other.imaginary))
        result = Complex(result_real, result_imaginary)
        return result

c1 = Complex(0, 0)
c2 = Complex(0, 0)

calc1 = Calculator(0, 0)
calc2= Calculator(0, 0)

choice = 1
while choice != 0:
    print("0. Exit")
    print("1. Construction of a complex number 1")
    print("2. Construction of a complex number 2")
    print("3. Display complex number 1")
    print("4. Display complex number 2")
    print("5. Erase complex number 1")
    print("6. Erase complex number 2")
    print("7. Addition")
    print("8. Subtraction")
    print("9. Multiplication")
    print("10. Division")
    choice = int(input("Enter choice: "))

    if choice == 1:
        print("Result: ", c1.create_number())
    elif choice == 2:
        print("Result: ", c2.create_number())
    elif choice == 3:
        print("Result: ", c1.display_number())
    elif choice == 4:
        print("Result: ", c2.display_number())
    elif choice == 5:
        print("Result: ", c1.erase_number())
    elif choice == 6:
        print("Result: ", c2.erase_number())
    elif choice == 7:
        print("Result: ", calc1.__add__(calc2))
    elif choice == 8:
        print("Result: ", calc1.__sub__(calc2))
    elif choice == 9:
        print("Result: ", calc1.__mul__(calc2))
    elif choice == 10:
        print("Result: ", calc1.__truediv__(calc2))
    elif choice == 0:
        print("Exiting!")
    else:
        print("Invalid choice!!")

A: This may not answer your question, but is valid knowledge either way.
The __add__ family of methods ('magic methods') are intended for python's internal use only.
When you write a + b, python will check if a happens to have an __add__ method, and use that, or if not use b's __radd__ method.
So one should simply 'use' the methods indirectly: print("Result: ", calc1 + calc2).

A: There is no relationship between Calculator and Complex objects at the moment. The real/imaginary attributes of the Calculator are initialized to 0, but never updated.
One approach to fix this would be to initialize the Calculator with a reference to the Complex object:
class Calculator(object):
    def __init__(self, complex_number):
        self.complex_number = complex_number

    def __add__(self, other):
        result_real = self.complex_number.real+other.complex_number.real
        result_imaginary = self.complex_number.imaginary+other.complex_number.imaginary
        result = Complex(result_real, result_imaginary)
        return result
    # other methods should be modified as appropriate..

c1 = Complex(0, 0)
c2 = Complex(0, 0)

calc1 = Calculator(c1)
calc2= Calculator(c2)

The user will update c1 when calling create_number, and the Calculator will have a reference to that (now updated) Complex object when the user calls add.


text:
Q: Html/Css flickering when i hover over a button i've been looking for some solutions here but i seem to stupid to change it the way i need to, so i decided to make a post.
Following problem:

button {
  font-family: custom-bold;
  width: 100%;
  font-size: 1.1rem;
  outline: none;
  padding: 10px;
  background-color: rgba(0, 0, 0, 0.322);
  border: none;
  border-radius: 5px;
  color: white;
  box-shadow: 3px 3px 3px 3px rgba(0, 0, 0, 0.5);
  text-shadow: 3px 3px 3px 3px rgba(0, 0, 0, 0.5);
}

button:hover {
  background-color:rgb(255, 255, 255);
  display: inline-block;
  transform: perspective(1px) translateZ(0);
  transform: perspective(1px) translateZ(0);
  box-shadow: 0 0 1px rgba(0, 0, 0, 0);
  position: relative;
  overflow: hidden;
  transition-property: color;
  transition-duration: 0.5s;

  color:rgb(0, 0, 0);

}
<button>thatsabutton</button>

when u hover over it, it flickers. When for example i add a margin-top to it with 1%, i would prevent the flickering but it would fk over with the other things i've made. Any idea what i can do it to prvent it with out adding margin to it? Regards!

A: You are only transitioning the color, change it to 'all' and you're OK.
Also add it to the button class for the reverse action.

button {
  font-family: custom-bold;
  width: 100%;
  font-size: 1.1rem;
  outline: none;
  padding: 10px;
  background-color: rgba(0, 0, 0, 0.322);
  border: none;
  border-radius: 5px;
  color: white;
  box-shadow: 3px 3px 3px 3px rgba(0, 0, 0, 0.5);
  text-shadow: 3px 3px 3px 3px rgba(0, 0, 0, 0.5);
    transition-property: all;
  transition-duration: 0.5s;
}

button:hover {
  background-color:rgb(255, 255, 255);
  display: inline-block;
  transform: perspective(1px) translateZ(0);
  transform: perspective(1px) translateZ(0);
  box-shadow: 0 0 1px rgba(0, 0, 0, 0);
  position: relative;
  overflow: hidden;
  transition-property: all;
  transition-duration: 0.5s;

  color:rgb(0, 0, 0);

}
<button>thatsabutton</button>


text:
Q: Multiple instances of an aurora mysql db. Only one of them does not use the possible index I ran into a performance issue with a large query, and broke it down with explain.
Dev and production are fine but the QA DB is having trouble.
Here is a sanitized explain
EXPLAIN SELECT COUNT(*)
FROM  table1 t1
LEFT OUTER JOIN table2 t2 ON t2.correlation_id = t1.correlation_id
WHERE t2.request_id = '<varchar(100) here>';

In one developer instance of the db I get
select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, extra
SIMPLE,t2,,ref,request_id,request_id,1022,const,3753,100,Using where
SIMPLE,t1,,eq_ref,"correlationIdUniqueConstraint,idx_correlation_id",correlationIdUniqueConstraint,402,dev_db.t2.correlation_id,1,100,Using index

Production is very similar / identical.
So everything seems fine so far.
However in the QA db I'm getting
select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, extra
SIMPLE,t2,,ref,request_id,request_id,1022,const,1176,100, <null>
SIMPLE,t1,,ALL,"correlationIdUniqueConstraint,idx_correlation_id",,,,3271577,10,Range checked for each record (index map: 0x40000004)

Using the schema compare tool in datagrip I made the Developer & QA dbs match.
The only difference would be the exact rows/counts. However in terms of rows Production > QA > Dev and yet Production & Dev are fine.
Schema info if relevant:
request_id has an index
correlation_id is varchar(100) in both t1 & t2.
The correlation_id unique constraint & index exist on t1

I confirmed with
SELECT CHAR_LENGTH(correlation_id)
FROM merchant_analysis
WHERE CHAR_LENGTH(correlation_id) > 90;

That no correlation_ids even exceed 90 chars much less 100.
Some DB info:
5.7.mysql_aurora.2.07.2
QA & Production Ram > Dev RAM
I'm hoping someone has seen a gotcha like this before, and I don't have to recreate the QA db.

A: This composite (and covering) INDEX would make the query more efficient on all machines:
table2:  INDEX(request_id, correlation_id)

And drop the current INDEX(request_id) since it would be in the way of picking this better index.
PS; it is not a LEFT join, but a normal INNER JOIN.  (This because of the demand WHERE t2... = ...)
As for why it might use a different query plan -- is the data different?  The Optimizer dynamically picks the plan based on probes into the data.  Even if the data is identical, the 'random' probes could come to different conclusions.