text:
Q: Running MapProxy 1.15.1 on Ubuntu 22.04 I am trying to install MapProxy 1.15.1 on Ubuntu 22.04. I have roughly followed the install documentation from mapproxy.org with seems to be not fully compatible and slightly out of date.
To sum things up, it does not work. I get
# mapproxy-util --version
Traceback (most recent call last):
  File "/root/mapproxy/bin/mapproxy-util", line 5, in <module>
    from mapproxy.script.util import main
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/script/util.py", line 29, in <module>
    from mapproxy.script.conf.app import config_command
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/script/conf/app.py", line 32, in <module>
    from .sources import sources
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/script/conf/sources.py", line 17, in <module>
    from mapproxy.srs import SRS
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/srs.py", line 26, in <module>
    from mapproxy.proj import USE_PROJ4_API
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/proj.py", line 282, in <module>
    res = try_import()
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/proj.py", line 155, in try_libproj_import
    libproj = init_libproj()
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/proj.py", line 58, in init_libproj
    libproj = load_library('libproj')
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/util/lib.py", line 65, in load_library
    lib = load_library_(lib_name, locations_conf)
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/util/lib.py", line 69, in load_library_
    lib_path = find_library(lib_name)
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/util/lib.py", line 93, in find_library
    lib = _find_library(lib_name)
  File "/usr/lib/python3.10/ctypes/util.py", line 341, in find_library
    _get_soname(_findLib_gcc(name)) or _get_soname(_findLib_ld(name))
  File "/usr/lib/python3.10/ctypes/util.py", line 147, in _findLib_gcc
    if not _is_elf(file):
  File "/usr/lib/python3.10/ctypes/util.py", line 99, in _is_elf
    with open(filename, 'br') as thefile:
FileNotFoundError: [Errno 2] No such file or directory: b'liblibproj.a'

What I get from util.py seems to be that it is intended to first try the parameter with prepended "lib" and then without. However, for some reason, it stops with an exception instead of continuing to try. This is also mentioned on Github, but without response.
I tried various methods to get around this, e.g. patching the code and placing a symbolic link. All of them worked partly. I ran into the next error:
# mapproxy-util --version
Found libproj >=5. Using this library without pyproj is deprecated and not fully supported. Please install pyproj >= 2.
Traceback (most recent call last):
  File "/root/mapproxy/bin/mapproxy-util", line 5, in <module>
    from mapproxy.script.util import main
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/script/util.py", line 29, in <module>
    from mapproxy.script.conf.app import config_command
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/script/conf/app.py", line 32, in <module>
    from .sources import sources
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/script/conf/sources.py", line 17, in <module>
    from mapproxy.srs import SRS
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/srs.py", line 26, in <module>
    from mapproxy.proj import USE_PROJ4_API
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/proj.py", line 282, in <module>
    res = try_import()
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/proj.py", line 155, in try_libproj_import
    libproj = init_libproj()
  File "/root/mapproxy/lib/python3.10/site-packages/mapproxy/proj.py", line 66, in init_libproj
    libproj.pj_init_plus.argtypes = [c_char_p]
  File "/usr/lib/python3.10/ctypes/__init__.py", line 387, in __getattr__
    func = self.__getitem__(name)
  File "/usr/lib/python3.10/ctypes/__init__.py", line 392, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: /lib/x86_64-linux-gnu/libproj.so.22: undefined symbol: pj_init_plus

In sum, several packages on Ubuntu 22.04 seem to be incompatible with MapProxy. I am currently running out of ideas how to solve this. Probably I would need an older version of libproj, but my knowledge does not suffice to install parallel versions of POSIX libraries. Is there some better/easy solution to this?
Addendum: I would appreciate some user to create a tag mapproxy and add it here. I cannot do it.

A: if mapproxy-util --version gives an error, try
pip install pyproj


text:
Q: ¿Cómo actualizar datos de un usuario sin que se modifique la password en django rest framework? Tengo un inconveniente con una 'api' que estoy creando.
Tengo el siguiente modelo de  Personas:
class Personas(User):
#Definicion de datos
ADMINISTRADOR = 'AD'
PROFESIONAL = 'PR'
USUARIO = 'US'

#DEFINICION DE ENUM TYPE
ACCESO_PERSONA = [
    (ADMINISTRADOR,'ADIMINISTRADOR'),
    (PROFESIONAL,'PROFESIONAL'),
    (USUARIO,'USUARIO'),
]

"""Model definition for Personas."""
idPersona = models.AutoField(primary_key = True)
Nombre = models.CharField(max_length = 60, blank = False, null = False)
Apaterno = models.CharField(max_length = 60, blank = False, null = False)
Amaterno = models.CharField(max_length = 60, blank = False, null = False)
fNacimiento = models.DateField(auto_now = False, blank = False, null = False)
idFacebook = models.CharField(max_length = 15, blank = True, null = True)
srcFoto = models.ImageField(upload_to = path_and_rename('imgs/perfiles/') , height_field = None , width_field = None , max_length = 250, blank = False, null = False)
idCiudad = models.ForeignKey('Ciudades', on_delete = models.CASCADE)
Acceso = models.CharField(max_length = 2, choices = ACCESO_PERSONA)

Como lo pueden notar este modelo hereda los atributos del modelo User propio de django, por tanto también dentro de sus atributos tiene los campos email y password. Cuando hago un post para guardar en este modelo, todo funciona de maravilla, sin embargo cuando hago un put o un patch actualizando cualquier campo del modelo se modifica el campo password; generando un problema al momento de la autenticación pues la contraseña se pierde.
La vista que uso para hacer la inserción es la siguiente:
class PersonasViewSet(viewsets.ModelViewSet):
queryset = Personas.objects.all()
serializer_class = PersonasSerializer

El serializador que tengo es el siguiente:
class PersonasSerializer(serializers.ModelSerializer):
class Meta:
    model = Personas
    fields = ('idPersona','Nombre','Apaterno', 'Amaterno','email', 'password', 'fNacimiento', 'idFacebook', 'srcFoto', 'idCiudad','Acceso')
    extra_kwargs = {'password': {'write_only': True}}
    read_only_fields = ['srcFoto']

def create(self, validated_data):

    validated_data['username']= validated_data['email']
    validated_data['is_active']= False
    user = super(PersonasSerializer, self).create(validated_data)
    user.set_password(validated_data['password'])
    user.save()
    Token.objects.create(user=user)

    return user

¿Cómo se pueden dar cuenta de que sobrescribo el método create para poder encriptar la contraseña? El error ocurre cuando hago un put o un patch, y según lo que veo es porque primero no se pasa una nueva contraseña puesto que el campo password queda vacío y al sobrescribirlo la contraseña cambia de valor; y lo segundo porque en teoría solo necesito sobreescribir el campo password cuando el usuario modifique la contraseña. Entonces lo que le pido a uds son ideas de como puedo hacer que esta parte solo modifique el campo password, solo si la contraseña actual se modifica.

A: Te quiero dar una alternativa mas facil y menos complicada. Ademas de que considero de mala practica lo que estas intentando hacer.
En ves de crear el modelo Persona y heredar de User, creo que es mejor extender el modelo de User con AbstractUser.
De la siguiente manera:
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    # Aqui añade los campos que quieras, que en tu caso serian fNacimiento, etc

    # Si es necesario tambien modifica los campos de Django que vienen por defecto

De esta manera cada usuario ya vendra con dichos campos por defecto, sin necesidad de crear otro modelo y acceder a dichos datos por relaciones, etc.
Para decirle a Django que ese sera el modelo de usuario como tal, en tu settings.py añade la constante AUTH_USER_MODEL:
AUTH_USER_MODEL = 'app_name.User'

Despues solo has las respectivas migraciones y listo.
Para mas informacion echale un vistaso a la doc: https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#extending-the-existing-user-model

Desde ahora en adelante al momento de importar el modelo User no debe ser de la forma convencional, debe ser asi:
from app_donde_esta_el_modelo.models import User

Otra forma mas profesional y de buena practica seria el get_user_model():

get_user_model() - Documentacion
En lugar de referirse a User directamente, debe hacer referencia al
  modelo de usuario utilizando django.contrib.auth.get_user_model().
  Este método devolverá el modelo de usuario actualmente activo: el
  modelo de usuario personalizado si se especifica uno, o User de lo
  contrario.

Para modificar los valores que necesites de un usuario, que es donde tienes problemas, seria de esta manera:
from django.contrib.auth.forms import UsernameField
from django.contrib.auth import get_user_model

User = get_user_model()

class UserChangeForm(forms.ModelForm):
    username = UsernameField(widget = forms.TextInput(attrs = {'class': 'form-control form-control-sm'}))

    class Meta:
        model = User
        # Aqui añades los campos a modificar, etc. Excepto "password" obiamente.
        fields = [...]

De esta manera no habra problemas con contraseñas ni nada de eso, que es donde ocurren los problemas.
Si quieres crear un formulario de registro personalisado debido a los campos añadidos, te recomiendo que el formulario para crear dicho usuario herede del form UserCreationForm.
Espero haberte ayudado de alguna manera.

redpajama_set_name: RedPajamaStackExchange


text:
Q: pandas.io.sql.execute is not autocommiting I'm trying to delete some rows before inserting new data in my table (the past 30 days have to be updated daily to get accurate numbers).
I'm executing this:
from datetime import date, datetime, timedelta
import pandas as pd from sqlalchemy import create_engine

conn = create_engine("insert here string for connection")
conn.execution_options(autocommit = True)
start_date = datetime.strftime(date.today() - timedelta(days = 30),'%Y-%m-%d')
end_date = datetime.strftime(date.today(),'%Y-%m-%d')

delete_query = "delete from table where date between %s and %s" %(start_date,end_date)

pd.io.sql.execute(delete_query, conn)

Although I get no error, I can see in the database that the table is just always being duplicated. Any ideas?

A: We just need to add instance.autocommit=True, that will look like:
cnxn.autocommit=True

A: Try setting autoflush and expire_on_commit to False:
conn.execution_options(autocommit=True, autoflush=False, expire_on_commit=False)

In the absence of a demarcated transaction, the Session cannot make
  appropriate decisions as to when autoflush should occur nor when
  auto-expiration should occur, so these features should be disabled
  with autoflush=False, expire_on_commit=False.

For additional details:
http://docs.sqlalchemy.org/en/latest/orm/session_transaction.html?highlight=autocommit#autocommit-mode


text:
Q: Customize JetBrains Rider to open a link when you click on class/function name in a file I am not sure if this can be done but what I am trying to achieve here is that when I click on a  method name in JetBrains Rider, I want it to open a browser, append the namespace, class name and method name to a URL like www.myrepo.com for me. So if I click on method z(on line #n) in class y on namepsace abc.lmn.x, then I want it to open www.myrepo.com/abc.lmn.x/y#n.html
Why? When I want to point another developer to a piece of code, the way I do it right now is to open the internal tool we developed on a browser, lookup for the classname on it and share.

A: I use action "Open on github" a lot, when project is on github (either github.com or private github server).


text:
Q: Use the Mean Value Theorem to prove a limit I want to prove that
$$\lim_{x\to \infty}\frac{x^n}{e^x}=0,$$
where $n\in \mathbb{N}$. I already tried to pick some interval as $[0,x]$ or $[x,x+a]$ and let $x$ tend to infinity, but without success...


text:
Q: Gentle introduction to non-autonomous dynamical systems I've been spoiled by Strogatz' Nonlinear Dynamics and Chaos book. It's really pleasant to read, intuitive, light on the formalism, with a friendly, personable tone that focuses on intuition and concepts over rigor.
However it only covers autonomous systems; the course I'm taking has moved to non-autonomous systems, and all the resources I find are extremely heavy on the formalism and much more difficult to extract intuition from.
Does anyone have a beginner-friendly resource similar to Strogatz that covers non-autonomous dynamical systems?

A: I found my favorite so far. The conversational tone is from the viewpoint of robotics, and it has a fairly understandable, logical build up that keeps formalism minimal and practical. As nonautonomous is a smaller niche than autonomous, I think this is probably as good as it gets: http://www.cds.caltech.edu/~murray/courses/cds101/fa02/caltech/mls93-lyap.pdf
However some of the definitions on "local" vs "global" are missing details that should be supplemented with https://engineering.purdue.edu/~byao/Research/Supplements/Lyapunov.pdf


text:
Q: Find percentage value in a nested arrays of object in javascript In a nested object of arrays , the percentage value should be mapped to an object which has greater count .
The data object has two arrays "distinctCount" and "groupByAndCount" .
The distinctCount contains an object .
     {
        "key": "total",
        "value": 7
      }

The "groupByAndCount" based on the key name the objects should be grouped and the value with highest count should be fetched and divided by value obtained in "distinctCount" and multiplied by 100 to get the percentage
Example:
In key "marital_status" the "Single" value has the highest count "6" compared to the value "Married" which has low count "1"
       {
          "key": "marital_status",
          "value": "Single",
          "count": 6/7*100 = 85.7%
        }

I am a beginner in reduce function , I think reducer function is required in getting the reduced object with percentage
const result = data.groupByAndCount.map(e => e.reduce((a, { key, value, count }) =>
(a['key'] = key,a['value'] = value,a['count'] = count, a), {}));

const data = {
    distinctCount : [
      {
        "key": "total",
        "value": 7
      },
      {
        "key": "member_total",
        "value": 7
      }
    ]
    ,
    groupByAndCount : [
      [
        {
          "key": "marital_status",
          "value": "Married",
          "count": 1
        },
        {
          "key": "marital_status",
          "value": "Single",
          "count": 6
        }
      ],
      [
        {
          "key": "payment",
          "value": "POST",
          "count": 7
        }
      ],
      [
        {
          "key": "customer_code",
          "value": "ABC",
          "count": 1
        },
        {
          "key": "customer_code",
          "value": "DEF",
          "count": 6
        }
      ]
    ]
};

The expected result :
const result = {
    distinctCount : [
      {
        "key": "total",
        "value": 7
      },
      {
        "key": "member_total",
        "value": 7
      }
    ]
    ,
    groupByAndCount : [
      [
        {
          "key": "marital_status",
          "value": "Single",
          "count": 85.71
        }
      ],
      [
        {
          "key": "payment",
          "value": "POST",
          "count": 100
        }
      ],
      [
        {
          "key": "customer_code",
          "value": "DEF",
          "count": 85.71
        }
      ]
    ]
};

A: First your total count is unique so you can take it out in variable to make calculation easy. You can do that using a simple search on array of objects(data.distinctCount).
function search(array, value){
    for (var i=0; i < array.length; i++) {
        if (array[i].key === value) {
            return array[i].value;
        }
    }
}

const total_value = search(data.distinctCount, 'total');

Output:
7

Second, you want object with max count from each array only(array inside data.groupByAndCount).
const maxGroupByAndCount = data.groupByAndCount.map(function(arr){
                               return [arr.sort((a,b)=>b.count-a.count)[0]];
                           });

Output:
[
    [{key: "marital_status", value: "Single", count: 6}],
    [{key: "payment", value: "POST", count: 7}],
    [{key: "customer_code", value: "DEF", count: 6}]
]

Now, just convert each count in percentage by comparing with total_value;
maxGroupByAndCount.map(function(arr){
  arr[0].count = (arr[0].count/ total_value) * 100;
});

console.log(maxGroupByAndCount);

Output:
[
   [{key: "marital_status", value: "Single", count: 85.71428571428571}],
   [{key: "payment", value: "POST", count: 100}],
   [{key: "customer_code", value: "DEF", count: 85.71428571428571}]
]

Now you can do object assign to make it one.
const result = {
                  'distinctCount' : data.distinctCount,
                  'groupByAndCount': maxGroupByAndCount
               };

You can definitely improve my answer to make it more optimized.


text:
Q: Enum type constraints in C#
Possible Duplicate:
Anyone know a good workaround for the lack of an enum generic constraint?

What is the reason behind C# not allowing type constraints on Enum's? I'm sure there is a method behind the madness, but I'd like to understand why it's not possible.
Below is what I would like to be able to do (in theory).
public static T GetEnum<T>(this string description) where T : Enum
{
...
}

A: This is an occasionally requested feature.
As I'm fond of pointing out, ALL features are unimplemented until someone designs, specs, implements, tests, documents and ships the feature. So far, no one has done that for this one. There's no particularly unusual reason why not; we have lots of other things to do, limited budgets, and this one has never made it past the "wouldn't this be nice?" discussion in the language design team.
The CLR doesn't support it, so in order to make it work we'd need to do runtime work in addition to the language work.  (see answer comments)
I can see that there are a few decent usage cases, but none of them are so compelling that we'd do this work rather than one of the hundreds of other features that are much more frequently requested, or have more compelling and farther-reaching usage cases.  (If we're going to muck with this code, I'd personally prioritize delegate constraints way, way above enum constraints.)

A: IL Weaving using ExtraConstraints
Your Code
public static T GetEnum<[EnumConstraint] T>(this string description)
{
    ...
}

What gets compiled
public static T GetEnum<T>(this string description) where T : Enum
{
    ...
}

A: Here's a VB.NET version of SLaks excellent ugly trick, with Imports as a "typedef":
(Type inference works as expected, but you can't get extension methods.)
'Base namespace "EnumConstraint"
Imports Enums = EnumConstraint.Enums(Of System.Enum)

Public NotInheritable Class Enums(Of Temp As Class)
Private Sub New()
End Sub

Public Shared Function Parse(Of TEnum As {Temp, Structure})(ByVal Name As String) As TEnum
    Return DirectCast([Enum].Parse(GetType(TEnum), Name), TEnum)
End Function

Public Shared Function IsDefined(Of TEnum As {Temp, Structure})(ByVal Value As TEnum) As Boolean
    Return [Enum].IsDefined(GetType(TEnum), Value)
End Function

Public Shared Function HasFlags(Of TEnum As {Temp, Structure})(ByVal Value As TEnum, ByVal Flags As TEnum) As Boolean
    Dim flags64 As Long = Convert.ToInt64(Flags)
    Return (Convert.ToInt64(Value) And flags64) = flags64
End Function

End Class

Module Module1

Sub Main()

    Dim k = Enums.Parse(Of DateTimeKind)("Local")
    Console.WriteLine("{0} = {1}", k, CInt(k))
    Console.WriteLine("IsDefined({0}) = {1}", k, Enums.IsDefined(k))
    k = DirectCast(k * 2, DateTimeKind)
    Console.WriteLine("IsDefined({0}) = {1}", k, Enums.IsDefined(k))

    Console.WriteLine(" {0} same as {1} Or {2}: {3} ", IO.FileAccess.ReadWrite, IO.FileAccess.Read, IO.FileAccess.Write, _
                      Enums.HasFlags(IO.FileAccess.ReadWrite, IO.FileAccess.Read Or IO.FileAccess.Write))

    ' These fail to compile as expected:
    'Console.WriteLine(Enums.HasFlags(IO.FileAccess.ReadWrite, IO.FileOptions.RandomAccess))
    'Console.WriteLine(Enums.HasFlags(Of IO.FileAccess)(IO.FileAccess.ReadWrite, IO.FileOptions.RandomAccess))

    If Debugger.IsAttached Then _
        Console.ReadLine()
End Sub

End Module

Output:
Local = 2
IsDefined(Local) = True
IsDefined(4) = False
 ReadWrite same as Read Or Write: True

A: One quirky thing here is that there are a fair number of generic Enum methods you might want to write whose implementation depends on the "base" type of the enumeration.
By the "base" type of an enumeration, E, I mean the type in the System namespace whose name is the same as the name of the member of System.TypeCode enumeration obtained by calling System.Type.GetTypeCode(System.Type) for the type E. If the enumeration was declared in C#, this is the same type that it was declared to "inherit" from (I'm not sure what this is officially called in the spec). For example, the base type of the Animal enumeration below is System.Byte:
public enum Animal : byte
{
    Moose,
    Squirrel
}

It's possible to write such methods using switch statements, but it sure is ugly, you can't get strongly typed parameters or return types whose type is the base type of the enumeration, and you have to either repeat the metadata lookup or do some caching (e.g. in the static constructor for the generic type containing the method).

A: public static T GetEnum<T>(this string description) where T : struct
{
    return (T)Enum.Parse(typeof(T), description);
}

Does it answer your question?

A: Actually, it is possible, with an ugly trick.
However, it cannot be used for extension methods.
public abstract class Enums<Temp> where Temp : class {
    public static TEnum Parse<TEnum>(string name) where TEnum : struct, Temp {
        return (TEnum)Enum.Parse(typeof(TEnum), name);
    }
}
public abstract class Enums : Enums<Enum> { }

Enums.Parse<DateTimeKind>("Local")

If you want to, you can give Enums<Temp> a private constructor and a public nested abstract inherited class with Temp as Enum, to prevent inherited versions for non-enums.
Note that you can't use this trick to make extension methods.


text:
Q: Problemas com predições usando predict.gam() e geom_smooth(method="gam") Olá, estou com dificuldades em reproduzir, os valores preditos, usando ggplot()+geom_smooth(method="gam"), quando eu executo o comando para o gráfico, ele plota uma linha de predição,como base na formula y~s(x,bs="cs") que não consigo reproduzir (linha vermelha no gráfico), fora do geom_smooth(), mesmo usando o mesmo modelo dentro de mgcv::gam().
obs: (Caso alguém saiba, como eu consigo extrair,os coeficientes do geom_smooth(), também ajuda!)
Pacotes:
if(!require(mgcv)){install.packages("mgcv")}
if(!require(ggplot2)){install.packages("ggplot2")}

Base de dados:
df1<-structure(list(DPV = c(0.169588512068197, 6.60924993787097, 4.37116533225157,
4.37129352740955, 4.57339006292512, 3.93536341833839, 3.76271410392057,
3.26551988605637, 2.4787752577947, 2.28091267538682, 1.73048300284362,
1.19127874414706, 0.968141363824768, 0.764284138998533, 0.616728558189974,
0.171375694966221, 0.179804007833412, 0.363981171574738, 0.370268251348895,
0.371401138906212, 0.363023669607576, 0.331513639442854, 0.288665648284206,
0.290418935686061, 0.26249403802394, 0.169313505243621, 0.176994570211015,
1.2146312010229), sensor = c(-0.000159222666482162, 0.0445601456650822,
0.0588390881373274, 0.040017863662116, 0.0418070272408576, 0.0453330551651008,
0.0391963630515521, 0.0388152374396356, 0.0415685621502633, 0.0271445811178297,
0.0216203118363865, 0.0126880366976767, 0.023905571882946, 0.0136972820275635,
0.0126598143467643, 6.11060437898381e-05, 0.00132364926440975,
0.0019403961429687, -0.00140294059163659, 0.0071700692264608,
0.0026218420268862, -0.00299733368456168, -0.00404093945108464,
0.007232270758184, -0.00692198800281052, 0.00268303823216987,
-0.000430772976242833, -0.00350247523338876), est = structure(c(2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("\"Est:1 - 50%\"",
"\"Est:2 - 50%\"", "\"Est:4 - 80%\"", "\"Est:5 - 80%\""), class = c("ordered",
"factor")), V4 = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L), .Label = c("1", "2", "3", "4", "5"), class = c("ordered",
"factor")), V1 = structure(c(18609, 18609, 18609, 18609, 18609,
18609, 18609, 18609, 18609, 18609, 18609, 18609, 18609, 18609,
18609, 18609, 18609, 18609, 18609, 18609, 18609, 18609, 18609,
18609, 18609, 18609, 18609, 18609), class = "Date"), fit = structure(c(-2.89993153907674e-05,
0.0445352556312924, 0.0458550388335889, 0.0458553487655575, 0.0462640503224621,
0.0444187105431725, 0.0436382564372395, 0.0407214700549528, 0.0334918541240277,
0.0308666909704694, 0.0210953384333099, 0.0109469279230599, 0.0106415890107558,
0.0130006493691816, 0.0132696416861763, -6.91423280688966e-05,
-0.000255950908192044, 0.00282104490971744, 0.00331947443697299,
0.00340943155227354, 0.00274667240522935, 0.000717561959731334,
-0.000831055182848491, -0.000793002471147874, -0.00117014079921287,
-2.28191732036982e-05, -0.000194393591947948, 0.0111801359106033
), .Dim = 28L)), row.names = c(494L, 499L, 502L, 507L, 509L,
514L, 519L, 520L, 525L, 531L, 535L, 537L, 541L, 547L, 549L, 553L,
557L, 561L, 564L, 569L, 575L, 576L, 581L, 587L, 591L, 594L, 597L,
602L), class = "data.frame")

Valores preditos:
df1$fit=predict.gam(gam(sensor~s(DPV,bs="cs"),data=df1),newdata = df1,interval="confidence")

Gráfico:
  ggplot(df1,aes(x=DPV,y=sensor))+
  geom_point()+
  geom_smooth(formula=y~s(x,bs="cs"),method="gam")+geom_line(aes(y=fit),color="red")

exemplo do gráfico:

A: Veja, a resposta para a sua pergunta está na documentação do geom_smooth():

For method = NULL the smoothing method is chosen based on the size of
the largest group (across all panels). stats::loess() is used for less
than 1,000 observations; otherwise mgcv::gam() is used with formula =
y ~ s(x, bs = "cs") with method = "REML". Somewhat anecdotally, loess
gives a better appearance, but is O(N2) in memory, so does not work
for larger datasets.

Então o que está faltando para você reproduzir a curva é usar o tal do método "REML" no gam():
library(mgcv)
df1$fit = predict.gam(gam(sensor~s(DPV,bs="cs"),method = "REML",data=df1),newdata = df1)

O que gerou essa figura aqui:

Há uma pequena distorção só no final, mas creio que deve ser algum detalhe do ggplot2. De qualquer forma é uma região que só tem um ponto.


text:
Q: How to hide a jsf element when page is loading I am new to JSF and doing some sample login application. I need username,password only with tooltips.
I have added below extra jsf element rich:toolTip element added as below and my question is, how to hide this extra element.
I want to hide this element without removing from jsp.
When I inspected the source code from browser, UI is getting broken and added some extra space.
sample.jsp
 <h:panelGrid>
    <h:outputText value="username"/>
    <h:inputText value="username">
       <rich:toolTip value="enter uname" event="onmouseover"
                     direction="bottom-right" layout="block"/>
    </h:inputText>

   <h:outputText value="password"/>
     <h:inputText value="password">
     <rich:toolTip value="enter password" event="onmouseover"
                   direction="bottom-right" layout="block"/>
    </h:inputText>

   <rich:toolTip value="how to hide this element" event="onmouseover"
                 direction="bottom-right" layout="block"/>
 </h:panelGrid>

Could anyone help on this?


text:
Q: Bootstrap Popover performance I am trying to use the Bootstrap popover on a razor form. I have a list of things on the page that can be of any number of rows. One of the items in the row I want to have a popover show up when you mouse over it. (not my requirement)
I have the popover code working just fine except it is EXTREMELY slow. it there were 50 items in the list, it will lock up the browser for 30 seconds as it add the popover functionality to each of the items.
This is my reduced function to load each thing:
$("[name=pop]").each(function () {
        $(this).popover({
            trigger: "hover",
            html: true,
            animation: false,
            content: getContent($(this).prop("title"))
        });
    });

this is what is VERY SLOW. I don't think I've seen jquery do a looping of an each this bad before. Does the popover try to pre-populate the contents? I have it calling a function to get a partial view for the contents when the pop over is loading. It doesn't call my getContent so I assume it is not trying to pre-load.
Is there any way to speed this up or is there a better way to do this?

A: Change the title attribute to data-content and use the below code.
$("[name=pop]").popover({
            trigger: "hover",
            html: true,
            animation: false
        });

Update:
To load contents dynamically, try something like this
$("[name=pop]").hover(function() {
   $(this).popover({
                trigger: "hover",
                html: true,
                animation: false,
                content: getContent($(this).prop("title"))
            }).popover('show');
});


text:
Q: PHPmailer - failing to send if variable $file1 for attachment does not have a value I have an HTML form that passes indexes to another form, which creates the necessary variables which are then inserted into PHPMailer. One of the options is to browse to a file which is then attached to the email.
The problem that I am having is that if there is no file to attach, (then the $file1 variable has "no value") PHPMailer returns the eoor that the message cannot be sent as below - pointing to the directory where the files are stored.
Message could not be sent. Mailer Error: Could not access file:C:/wamp64/www/CIA/PODS/
$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
//Server settings
//$mail->SMTPDebug = 2;                                 // Enable verbose debug output
$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'mail.smtp2go.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'xxx@xx-xxxxxx.co.za';              // SMTP username
$mail->Password = 'xxxxxxxx';                         // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 2525;                                    // TCP port to connect to
//Recipients
$mail->AllowEmpty = true;
$mail->setFrom('admin@ic-express.co.za', 'ICExpress Waybill Updates');
$mail->addAddress('xxxx@xx.co.za');
$mail->addAddress($email);
$mail->addReplyTo('xxxx@xx.co.za');
$mail->addCC($addemail);
$mail->addCC($addemail2);

echo $file1;
$path=$_SERVER['DOCUMENT_ROOT'].'/CIA/PODS/'.$file1;
$name=$file1;
$mail->AddAttachment($path,$name,$encoding ='base64',$type = 'application/octet-stream');
$mail->AllowEmpty = true;
$mail->isHTML(true);                      // Set email format to HTML
$mail->Subject = $subject ;
$mail->Body    = <<<END

A: You can simply add the attachment if it is available. In case there is no file attachment don't try to add the attachment:
$path = $_SERVER['DOCUMENT_ROOT'].'/CIA/PODS/'.$file1;

if (is_dir($path) === false && file_exists($path)) {
    $name = $file1;
    $mail->AddAttachment($path, $name, $encoding = 'base64', $type = 'application/octet-stream');
}

As IncredibleHat also mentioned in the comments you can also use the condition is_file($path) to check the file path like PHPMailer itself:
if (is_file($path)) {
    $mail->AddAttachment($path, '', $encoding = 'base64', $type = 'application/octet-stream');
}

You also don't need to specify the name if you want to use the same as specified on path. PHPMailer is using the basename of the path if name parameter is a empty string.


text:
Q: Copy Lucene indexes between Jackrabbit repositories I have two Jackrabbit instances containing the same content. Rebuilding the Lucene index is slow, 30+ hours, and the down-time needed in the cluster is risky. Is it possible to instead just re-index one Jackrabbit then copy the Lucene index from that instance to the other?
Naively copying the Lucene index files beneath the workspace directory doesn't work. The issue appears to be that the content is indexed by document number which maps to a UUID which maps to the JCR path for the indexed node, but these UUIDs are not stable for a given path between Jackrabbit instances. (Both are actually Day CQ publisher instances populated by replication from a CQ author instance.)
I've managed to find the UUID-to-path mapping in the repository under /jcr:system/jcr:versionStorage/ but I can't see an easy way to copy this between repositories along with the Lucene index. And then I can't find the UUID->document ID mapping anywhere in the files - is this part of the Lucene index too?
Thanks for any help. I'm leaning towards just re-indexing the second instance separately and accepting the downtime but any ideas to reduce risk or the elapsed time of reindexing the cluster appreciated!

In the end we're going the re-index-them-both route: we've managed to repurpose a test instance as an extra live instance that we can drop into the farm temporarily whilst we take the other two out in turn to re-index. However I'd still be interested in hearing better ways to do this!

A: That seems like a scary idea, honestly. I'm not sure there is any way to guarantee that you've got the same underlying data, even with identical content and hardware configuration.
If your performance numbers look like ours, the time to copy the entire repository is less than the time it takes to reindex. Have you considered just reindexing one repository, doing a backup/copy, and then configuring the backup/copy to be your second instance?


text:
Q: Как показать авторизацию админки в yii2 в main layout есть такой код
    if (Yii::$app->controller->action->id === 'login') {
    /**
     * Do not use this code in your template. Remove it.
     * Instead, use the code  $this->layout = '//main-login'; in your controller.
     */
        echo $this->render(
            'main-login',
            ['content' => $content]
        );
    } else {
....
}

Когда я закрываю доступ к админке не авторизованного пользователя в МОдуле
public function behaviors()
    return [
        'access'    =>  [
            'class' =>  AccessControl::className(),
            'denyCallback'  =>  function($rule, $action)
            {
                //return Yii::$app->response->redirect(['/admin/login/index']);
                throw new \yii\web\NotFoundHttpException('Нет доступа');
            },
            'rules' =>  [
                [
                    'allow' =>  true,
                    'matchCallback' =>  function($rule, $action)
                    {
                        return Yii::$app->user->identity->isAdmin;
                    }
                ]
            ]
        ]
    ];

меня автоматические перенаправляют меня на auth/login. Мне бы хотелось чтобы перенаправили если в строке веду http://site.ru/admin перенаправляли на страницу авторизации админа, например: http://site.ru/admin/login. А если это простой пользователь и он хочется авторизоваться перенаправляли его на страницу http://site.ru/auth/login.
как мне добиться такого результата? Шаблон админки AdminLte

A: Если у вас админка представлена в виде отдельного модуля, то можно в главном классе модуля(обычно это файл Module.php в корне модуля) задать url для авторизации при инициализации модуля:
public function init()
{
    parent::init();
    \Yii::$app->user->loginUrl = '/admin/login';
}

То же самое можно добавить в любой контроллер, если нужно отдельно от модуля, или вообще если модули не используются


text:
Q: ERROR: Failed to get navigation preload state: The user denied permission to use Service Worker I have a service worker running in production, lately I have started seeing increase in error Failed to get navigation preload state: The user denied permission to use Service Worker. This error was always logged on our end but the amount has been quadrupled in past 3 weeks. I am not sure what causes this error at the first place, and I have tried multiple ways but could not able to reproduce. Most of these errors are coming from recently released Chrome 105, but I did not saw any policy change in the new release which can trigger this.
I am looking for more details about the error? What causes it? How it can be reproduced?


text:
Q: Does use useState inside useEffect doesn't works? I have this function getting called inside useEffect. The output that I am getting is user idddd is null 616830f1491ef15dc0ba5a6a .While id variable is giving me proper value in console.log statement but userId is still null. I am not sure why is it happening.
function Component() {
const [userId, setuserId]= useState(null);

useEffect(()=>{
   getUserId()
        .then((id)=>{
          setuserId(id);
          console.log("user idddd is", userId, id);

        })
},[])

  function getUserId() {
    let id = localStorage.getItem("userId");
    return new Promise((resolve, reject)=>{
      if(id){
        resolve(id);
      }
      reject();
    })
  }
.
.
.
}

A: Even though you set the state in useEffect, it will only update on the next render of the component. This is why it is null when you console.log() right after you set it.

A: you cant expect javascript to executesetuserId to update the value then come back to console.log your updated userId
  setuserId(id);
  console.log("user idddd is", userId, id);

setUserId will update the value right after your whole .then() finishes


text:
Q: Foreign key is not assigned using sequelize in 1:1 association I have 3 models User, Question and Video

*

*A video belongs to one user and to also one question

*user has many questions, while a question has only 1 video

*I have got the association between user and video models done, however for video-question one not yet. The foreign keys are created successfully but on create method the questionId is not assigned.

Hers is a snap shot of how the models and the create function looks like.
Video Model
'use strict';
module.exports = (sequelize, DataTypes) => {
  var Video = sequelize.define('Video', {
    transcription: {
      type: DataTypes.TEXT
    },
  });

  Video.associate = (models) => {
   Video.belongsTo (models.Question,
   {foreignKeyContraint : true , foreignKey: "questionId" });
  }

  Video.associate = (models) => {
    Video.belongsTo(models.User, {
      onDelete: "CASCADE",
      foreignKey: 'userId'
    });
  }
return Video;};

Question model:
module.exports = (sequelize, DataTypes) => {
 var Question = sequelize.define('Question', {
  text: {
  type: DataTypes.TEXT,
  allowNull: false,
  }
});
Question.associate = (models) => {
 Question.belongsTo(models.Script, {
   onDelete: "CASCADE",
   foreignKey: 'scriptId'
 });
}
Question.associate = (models) => {
 Question.hasMany(models.Questionvariation,
 {
  foreignKey: 'questionId',
  as: 'questions',
 });

}return Question;};
For the create function
create(req, res) {
 return Video
  .create({
    userId: req.body.user_id,
    questionId: req.body.question_id,
    transcription: req.body.transcription
  })
  .then(video =>
    res.status(201).send(video))
  .catch(error =>
    res.status(400).send(error));
 }

The video is created however it neglects completely the existence of questionId.

A: Okay I have solved it, the problem is that I have to add a hasOne association in Question model


text:
Q: C# WPF - large custom mouse cursor sizes I am using code I found to render text as my cursor
Here's the website with the code
I copied the code below just in case:
public class CursorHelper
{
    private static class NativeMethods
    {
        public struct IconInfo
        {
            public bool fIcon;
            public int xHotspot;
            public int yHotspot;
            public IntPtr hbmMask;
            public IntPtr hbmColor;
        }

        [DllImport("user32.dll")]
        public static extern SafeIconHandle CreateIconIndirect(ref IconInfo icon);

        [DllImport("user32.dll")]
        public static extern bool DestroyIcon(IntPtr hIcon);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);
    }

    [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
    private class SafeIconHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        public SafeIconHandle()
            : base(true)
        {
        }

        override protected bool ReleaseHandle()
        {
            return NativeMethods.DestroyIcon(handle);
        }
    }

    private static Cursor InternalCreateCursor(System.Drawing.Bitmap bmp)
    {
        var iconInfo = new NativeMethods.IconInfo();
        NativeMethods.GetIconInfo(bmp.GetHicon(), ref iconInfo);

        iconInfo.xHotspot = 0;
        iconInfo.yHotspot = 0;
        iconInfo.fIcon = false;

        SafeIconHandle cursorHandle = NativeMethods.CreateIconIndirect(ref iconInfo);
        return CursorInteropHelper.Create(cursorHandle);
    }

    public static Cursor CreateCursor(string cursorText)
    {
        // Text to render
        FormattedText fmtText = new FormattedText(cursorText,
                new CultureInfo("en-us"),
                FlowDirection.LeftToRight,
                new Typeface(new FontFamily("Arial"), FontStyles.Normal, FontWeights.Normal, new FontStretch()),
                12.0,  // FontSize
                Brushes.Black);

        // The Visual to use as the source of the RenderTargetBitmap.
        DrawingVisual drawingVisual = new DrawingVisual();
        DrawingContext drawingContext = drawingVisual.RenderOpen();
        drawingContext.DrawText(fmtText, new Point());
        drawingContext.Close();

        // The BitmapSource that is rendered with a Visual.
        RenderTargetBitmap rtb = new RenderTargetBitmap(
            (int)drawingVisual.ContentBounds.Width,
            (int)drawingVisual.ContentBounds.Height,
            96,   // dpiX
            96,   // dpiY
            PixelFormats.Pbgra32);
        rtb.Render(drawingVisual);

        // Encoding the RenderBitmapTarget into a bitmap (as PNG)
        PngBitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(rtb));

        using (var ms = new MemoryStream())
        {
            encoder.Save(ms);
            using (var bmp = new System.Drawing.Bitmap(ms))
            {
                return InternalCreateCursor(bmp);
            }
        }
    }
}

The problem I'm running into is when the size is too large, the cursor fails to render. From what I've seen, once a dimension of the text exceeds 96, this will happen.
Is this a limitation of the size of a cursor? Is there any way to bypass this? I know I could make a canvas and render an image and have it follow my mouse position or something like that, but I'm curious of an actual solution using the WPF Cursor class.


text:
Q: Error imporing tensorflow in python 3.4 "Failed to load the native TensorFlow runtime" Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/init.py", line 61, in
    from tensorflow.python import pywrap_tensorflow
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in
    _pywrap_tensorflow = swig_import_helper()
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
  File "/usr/lib/python3.4/imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
ImportError: /opt/Xilinx/Vivado/2015.1/lib/lnx64.o/libstdc++.so.6: version `GLIBCXX_3.4.19' not found (required by /usr/local/lib/python3.4/dist-packages/tensorflow/python/_pywrap_tensorflow.so)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "image_resize.py", line 10, in
    import tensorflow as tf
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/init.py", line 24, in
    from tensorflow.python import *
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/init.py", line 72, in
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/init.py", line 61, in
    from tensorflow.python import pywrap_tensorflow
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in
    _pywrap_tensorflow = swig_import_helper()
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
  File "/usr/lib/python3.4/imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
ImportError: /opt/Xilinx/Vivado/2015.1/lib/lnx64.o/libstdc++.so.6: version `GLIBCXX_3.4.19' not found (required by /usr/local/lib/python3.4/dist-packages/tensorflow/python/_pywrap_tensorflow.so)
Failed to load the native TensorFlow runtime.
See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#import_error
for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
i am using ubuntu 14.4
and python version 3.4

A: It looks like you installed Xilinx which includes an older version of libstdc++. If you remove it from your LD_LIBRARY_PATH, that should solve the issue.

A: I'm using Ubuntu 14.4 with python 3.5. I run the following and the python3 shell imported tensorflow perfectly fine.
sudo -H pip3 install tensorflow


text:
Q: When should i use more than one Pool for multithreading/multiprocessing in Python? Belows example works fine but when should you start using more than one pool for multithreading/processing in Python and why or is it okay to always use the same pool.
from concurrent.futures import ThreadPoolExecutor, as_completed

def func_one():
    print("does something")

def func_two(some_results):
    print("does something related to func_one")

def func_three():
    print("does something totally diffrent")

some_list = ["foo", "bar", "baz"]
thread_lst_one = []
thread_lst_two = []
thread_lst_three = []

with ThreadPoolExecutor() as executor:
    for foo in some_list:
        thread_lst_one.append(executor.submit(func_one))

    while True:
        for thread in as_completed(thread_lst_one):
            thread_lst_two.append(executor.submit(func_two, thread.result()))

        if True:
            executor.submit(func_three)


text:
Q: Передача данных клиенту Как осуществляется передача данных клиенту от сервера?
Например, ВКонтакте, когда запроса нет, а уведомление приходит о новом сообщении.
Или каждую секунду, например, отправляется запрос серверу проверить, не появилось ли новое сообщение?
A: Вероятно через AJAX-запросы, но я не проверял, обычно именно так. В фейсбуке на AJAX, я проверял.
Есть ещё "технологии COMET" - образуют стримобразные потоки. Они куда лучше AJAX, но затратнее по коду, браузерам (надо же и старьё учить этому, а это очень сложно, если вообще возможно), простоте.


text:
Q: iterating array of objects which is present inside array of objects children.BallAdequacy is an array of objects.Inside that playerRank is an array of objects.
From each playerRank array I need to display Ball and playerHeight value seprately in console.
I used map and filter methods but still I am not able to print the ball and playerHeight for each object.
 Can you tell me how to fix it.
Providing my code snippet and data below
example for each object  it should print 222--->HEIGHT,ww22w22--->HEIGHT, etc

let children = {
  BallAdequacy: [{
      "flight": "dd",

      "specialty": "ff",

      "playerRank": [{
          "Ball": "222",
          "playerHeight": "HEIGHT"
        },
        {
          "Ball": "ddeeeew",
          "playerHeight": "NON-HEIGHT"
        },
      ],
      "hospitalPrivilege": []
    },
    {
      "flight": "kkk",
      "specialty": "ff",

      "playerRank": [{
          "Ball": "kfkf",
          "playerHeight": "HEIGHT"
        },
        {
          "Ball": "All",
          "playerHeight": "NON-HEIGHT"
        }
      ],
      "hospitalPrivilege": []
    }
  ]
};

children.BallAdequacy.map(status => {
  console.log("status.playerRank--->", status.playerRank);
  status.playerRank.filter(game => {
    //console.log("game.playerHeight--->", game.playerHeight);
    if (game.playerHeight === 'HEIGHT') {
      console.log("after if --->", game);
      console.log("after if --->", game.Ball);

    }
    // (game.playerHeight === 'HEIGHT')
    //console.log("outsidei f--->", game);
  });
  console.log("after filter status.playerRank--->", status.playerRank);
  //BallList = getBalls(status.playerRank);
});

A: Follow the definition of map() and filter()

The map() method creates a new array with the results of calling a provided function on every element in the calling array.
The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Both methods return a new array, It must clone a new object, but you don't need that. All you need is just console.log something and didn't change the data. You should use forEach instead. And remove some unnecessary console.

let children = {
  BallAdequacy: [{
      "flight": "dd",

      "specialty": "ff",

      "playerRank": [{
          "Ball": "222",
          "playerHeight": "HEIGHT"
        },
        {
          "Ball": "ww22w22",
          "playerHeight": "HEIGHT"
        },

        {
          "Ball": "wwwww",
          "playerHeight": "NON-HEIGHT"
        },
        {
          "Ball": "ddeeeew",
          "playerHeight": "NON-HEIGHT"
        },

        ,
        {
          "Ball": "All",
          "playerHeight": "NON-HEIGHT"
        }
      ],
      "hospitalPrivilege": []
    },
    {
      "flight": "kkk",
      "specialty": "ff",

      "playerRank": [{
          "Ball": "kfkf",
          "playerHeight": "HEIGHT"
        },

        {
          "Ball": "iioioo",
          "playerHeight": "HEIGHT"
        },
        {
          "Ball": "24jk",
          "playerHeight": "NON-HEIGHT"
        },

        {
          "Ball": "All",
          "playerHeight": "NON-HEIGHT"
        }
      ],
      "hospitalPrivilege": []
    }
  ]
};

children.BallAdequacy.forEach(status => {
  status.playerRank.forEach(game => {
    if (game.playerHeight === 'HEIGHT') {
      console.log(`${game.Ball} ---> ${game.playerHeight}`);
    }
  });
});

A: Something like this maybe? Does this work?

let children = {
  BallAdequacy: [{
      "flight": "dd",

      "specialty": "ff",

      "playerRank": [{
          "Ball": "222",
          "playerHeight": "HEIGHT"
        },
        {
          "Ball": "ww22w22",
          "playerHeight": "HEIGHT"
        },

        {
          "Ball": "wwwww",
          "playerHeight": "NON-HEIGHT"
        },
        {
          "Ball": "ddeeeew",
          "playerHeight": "NON-HEIGHT"
        },
        {
          "Ball": "All",
          "playerHeight": "NON-HEIGHT"
        }
      ],
      "hospitalPrivilege": []
    },
    {
      "flight": "kkk",
      "specialty": "ff",

      "playerRank": [{
          "Ball": "kfkf",
          "playerHeight": "HEIGHT"
        },

        {
          "Ball": "iioioo",
          "playerHeight": "HEIGHT"
        },
        {
          "Ball": "24jk",
          "playerHeight": "NON-HEIGHT"
        },

        {
          "Ball": "All",
          "playerHeight": "NON-HEIGHT"
        }
      ],
      "hospitalPrivilege": []
    }
  ]
};

let output = children.BallAdequacy.map(s => s.playerRank.map((a) => `${a.Ball}-->${a.playerHeight}`).join());

output.forEach(c => console.log(c));


text:
Q: issue with list TableView in Corona Am trying to do an App in Corona that will display list of topics/items in table view but i have been on it for over 2 weeks now, i cant get the list displayed on the App but its showing the last item on the list instead of listing all on the tableView
i have tried "listRec[event.index].name" in place of "listRec.name" but am getting an error, please help me
See my code below
    local widget = require( "widget" )
    listRec = {}
    local nameData =            {"System1","System2","System3","System4","System5","System6"
    ,"System7","System8","System9"}
    local list = nil

    local function loadData()
     for x=1, #nameData do
        listRec[x] = {}
        listRec.name = nameData[x]
        end
    end

    local function onRowRender( event )

        -- Get reference to the row group
        local row = event.row
        local rowGroup = event.view

        -- Cache the row "contentWidth" and "contentHeight" because the row bounds can change       as children objects are added
        local rowHeight = row.contentHeight
        local rowWidth = row.contentWidth

        local rowTitle = display.newText(row, listRec.name, 0, 0, nil, 35 )
        rowTitle:setFillColor( 0 )

     -- Align the label left and vertically centered
        rowTitle.anchorX = 0
        rowTitle.x = 10
     rowTitle.y = rowHeight * 0.5

    end --onRowRender

    local function pageup()

    -- Create the widget
        tableView = widget.newTableView
    {
            top = 50,
            height = screenHeightSB,
            width = screenWidth,
            onRowRender = onRowRender,
            onRowTouch = onRowTouch,
            listener = scrollListener
    }

    --Heading Outline
        local heading = display.newText("Course Outline", 0,0, "Helvetica" or       "native.systemFont", 40)
        heading.x = centerX
    heading.y = 25
    end ---pageup

    local function showRec()
        -- Insert 40 rows
        for i = 1, #listRec do
        local rowHeight = 60
         -- Insert a row into the tableView
         tableView:insertRow{
        rowHeight = rowHeight
        }
        end
    end --- showRec

    loadData()
    pageup()
    showRec()

A: You can modify your code as the following:
local function loadData()
     for x=1, #nameData do
        listRec[x] = {
        name = nameData[x]
        }
        end
    end

then inside the rowRender function you add
 local idx = row.index
 local rowTitle = display.newText(row, listRec[idx].name, 0, 0, nil, 35 )

That should do it I guess


text:
Q: Yocto tensorflow 2.0 I am looking for a yocto recipe to build it including its python packages with the availability of Tensorflow 2.0.
There are instructions on building from source for Linux/MacOS systems but is there anything available like a Tensorflow 2.0 yocto recipe (meta-tf maybe)?


text:
Q: How does COM work? I have a dll that is allegedly a COM object. I'm trying to understand how exactly is the CLR able to figure out which function to call when no export function is available in the dll (I checked using depends).
  [Guid("DEADBEEF....")]
  [TypeLibType(...)]
  [ComImport]
  public interface ISomething
  {
    [DispId(1)]
    [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
    [return: MarshalAs(UnmanagedType.IDispatch)]
    object DoSomething([MarshalAs(UnmanagedType.IDispatch), In] object something);

}
In here and I checked the MSIL there is no information about what address or function name, or offset it is located at.
Furthermore, there seems to be no information about how an object is layed out so its vtable pointer is passed, etc.
What magic is this?

A: From (unmanaged) code, one would use LoadTypeLib/LoadTypeLibEx on the "type library" file associated with the COM object. Quite commonly, that's the EXE or DLL registered for the COM object itself (but it could also be a standalone TLB file, a foreign type library etc). The documentation for LoadTypeLib has further pointers at https://msdn.microsoft.com/en-us/library/windows/desktop/ms221027(v=vs.85).aspx.
Once the ITypeLib/ITypeLib2 type library interface is obtained, it provides all the COM object info, including interfaces, vtable layout, prototypes etc. Full documentation is at https://msdn.microsoft.com/en-us/library/windows/desktop/ms221549(v=vs.85).aspx.
An example of LoadTypeLib in action is the OLE/COM Object Viewer provided with most versions of Visual Studio, which can essentially decompile a given type library back to an IDL. I can't post more than 2 URLs, but lookup https-//msdn.microsoft.com/en-us/library/d0kh9f4c.aspx.
In managed code, the compiler does the importing of the type library transparently, though behind the scenes it's doing basically the same work as the OLE/COM Viewer, plus adding the necessary managed wrappers. See https-//msdn.microsoft.com/en-us/library/xwzy44e4(v=vs.110).aspx for more details.


text:
Q: Использование вложенных Media queries css Подскажите пожалуйста, корректно ли использовать медиа запросы таким образом?Вроде все работает, но смущает правильность использования вложенных запросов.Спасибо!
@media all and (min-width:320px) and (max-width: 480px){
    @media all and (orientation: portrait){
           .header{
               visibility: hidden;
           }
       }
    @media all and (orientation: landscape){
        .header {
            color: #6ABD97;
        }
    }
}


text:
Q: Limit characters of cells to certain bytes in Worksheet_Change applicable for all languages I know the code which can restrict a cell value to certain lengths as follows, but how do I restrict it to certain bytes for example let's say 240 bytes as well as truncate it within the limit? Also, the Charset would be "shift-jis" i.e., Japanese + English.
If Not Intersect(Target, Range("A2:B200")) Is Nothing Then
    For Each cell In Intersect(Target, Columns("A:B"))
        If (cell.Value) > 20 Then
            cell.Value = VBA.Left(cell.Value, 20)
            cell.Select
            MsgBox "Character limit for the cell is 20." & vbNewLine & "Truncated to 20 characters."
        End If
    Next cell
End If

Help is appreciated!

A: If I understand the question correctly, what you ultimately need to do is determine if a character falls into the ANSI character range (can be represented by one byte - 0 to 255). Excel doesn't make this easy as noted in the comments.  Neither does VBA, which represents all strings internally as UTF-16. This is compounded by the problem that the behaviour of the VBA Len and LenB changed after VB4.  Prior to that change, they would have returned different results for Unicode or ANSI input. Now, they will both return the same result because LenB returns the in-memory length of the string which is always 2 bytes per character. What distinguishes the ANSI range is that the 2nd byte will always be zero.
The StrConv function does provide a way to check whether a string contains non-ANSI characters - you can convert to a Byte array and check to see if any of the high bytes are set. For example, the string "ABCD" is stored in VBA's memory as:
65  0   66  0   67  0   68  0

You can use a quirk of VBA's "Unicode conversion" to expand these to 2 bytes again with StrConv("ABCD", vbUnicode), which results in this:
65  0   0   0   66  0   0   0   67  0   0   0   68  0   0   0

For comparison, if you picked up the string "ΑΒΓΔ" from somewhere (which you would have to because there's no way to type it in the IDE), it could result in this depending on the encoding:
24  32  3   0   25  32  3   0   28  32  3   0   29  32  3   0

So, once you have a byte array, all you need to do is check every other byte - if you find a non-zero value, it can't be narrowed to ANSI:
Private Function IsANSI(test As String) As Boolean
    Dim bytes() As Byte, i As Long
    bytes = StrConv(test, vbUnicode)
    For i = 1 To UBound(bytes) Step 2
        If bytes(i) <> 0 Then
            IsANSI = False
            Exit Function
        End If
    Next i
    IsANSI = True
End Function

If all you care about is UTF-16 v ANSI, you can grab the "byte length" easily after you determine it can be narrowed to 8 bits:
Private Function ByteLength(test As String) As Long
    If IsANSI(test) Then
        ByteLength = Len(test)
    Else
        ByteLength = LenB(test)
    End If
End Function

Note that byte length always depends on the encoding. If you need the length of the string in a specific encoding, VBA isn't going to help you much natively unless it's a fixed width encoding (i.e. UTF-32, which VBA likely already butchered), you'll have to reach into the Windows API and explicitly convert it with WideCharToMultiByte and see what you get back. You can find a VBA example here.

A: You can use ADODB.Stream ActiveX to get a string of limited length of bytes represented in certain charset. Since you didn't specified any charset, I chose UTF-8 for an example. I modified your code and added LeftUTF8() function, the below code placed in Worksheet module:
Private Sub Worksheet_Change(ByVal Target As Range)

    Application.EnableEvents = False
    If Not Intersect(Target, Range("A2:B200")) Is Nothing Then
        For Each cell In Intersect(Target, Columns("A:B"))
            cell.Value = LeftUTF8(cell.Value, 240)
        Next cell
    End If
    Application.EnableEvents = True

End Sub

Private Function LeftUTF8(strCont As String, lngLenght As Long) As String

    Dim i As Long
    Dim arrCont() As Byte
    ' add reference to Microsoft ActiveX Data Objects Library (2.5 or later)
    Static objStream As New ADODB.Stream

    i = lngLenght
    With objStream
        .Type = adTypeText
        .Open
        .Charset = "utf-8"
        .WriteText strCont ' convert string to UTF-8 with BOM
        .Position = 0
        .Type = adTypeBinary
        If .Size > i + 3 Then ' size in bytes greater then limit + 3 bytes UTF-8 BOM
            For i = i To 1 Step -1 ' if last multibyte char is split then reduce output
                .Position = i + 3 ' next byte after the last + BOM
                If AscB(.Read(1)) And 192 <> 128 Then Exit For ' next byte is first byte of next char
            Next
        End If
        .Position = 0
        arrCont = .Read(i + 3) ' read bytes with BOM corresponding the limit
        .Close ' clear stream
        .Open
        .Type = adTypeBinary
        .Write arrCont ' write bytes
        .Position = 0
        .Type = adTypeText
        LeftUTF8 = .ReadText ' read string
        .Close
    End With

End Function

UPDATE
Here is the code to get a string of 240 bytes represented in shift-jis charset:
Private Sub Worksheet_Change(ByVal Target As Range)

    Application.EnableEvents = False
    If Not Intersect(Target, Range("A2:B200")) Is Nothing Then
        For Each cell In Intersect(Target, Columns("A:B"))
            cell.Value = LeftShiftJis(cell.Value, 240)
        Next cell
    End If
    Application.EnableEvents = True

End Sub

Private Function LeftShiftJis(strCont As String, lngLenght As Long) As String

    Dim i As Long
    Dim arrCont() As Byte
    ' add reference to Microsoft ActiveX Data Objects Library (2.5 or later)
    Static objStream As New ADODB.Stream

    i = lngLenght
    With CreateObject("ADODB.Stream")
        .Type = adTypeText
        .Open
        .Charset = "shift-jis"
        .WriteText strCont ' convert string to shift-jis binary representation
        .Position = 0
        .Type = adTypeBinary
        arrCont = .Read(i) ' read limited number of bytes
        .Close ' clear stream
        .Open
        .Type = adTypeBinary
        .Write arrCont  ' write all content, if second byte of last two-byte char is cut off, then zero will be added instead of the missing byte
        .Position = 0
        .Type = adTypeText
        LeftShiftJis = .ReadText ' if last char is two-byte and has second byte cut off, then it is trimmed
        .Close
    End With

End Function


text:
Q: Gitlab CI - composer install on private repo I'm trying to setup Gitlab CI for a project I'm working on (PHP - Symfony 4 / MySQL). I've got the .gitlab-ci.yml file created with the necessary steps to prepare a Docker image. One of the steps is to run composer install - this should normally install a bunch of linked code, a few of which come from private repositories (also stored on Gitlab).
I'm trying to work out the current best practice for allowing the Gitlab CI runner to clone this code from it's private repo. I see reference in other Stack Overflow posts to the ${CI_JOB_TOKEN} variable, but seem to be missing the connecting bits of information to make it work - for example, do I need to modify the private repos to access this variable as a deploy token somehow, or does this happen automatically as Gitlab is cloning code from it's own servers?
Does anyone have a complete example of a .gitlab-ci.yml file that can clone code from a private repo using composer? If it's relevant, there are 4 private repos I need to clone, and will need to have the same CI setup for many projects that rely on these based libraries.

A: I managed to resolve this after reading this page a few more times - https://docs.gitlab.com/ee/user/project/new_ci_build_permissions_model.html
It mentions that the user that pushes the code is the user that runs the CI task as. Using this knowledge and the CI_JOB_TOKEN variable that is automatically available, I added the following to my before_script:
git config --global url."https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.com/".insteadOf "git@gitlab.com:"

...and then in my composer.json, added the list of repositories I wanted to use (using the "repositories": [] keys, as this allowed me to force them to use https to checkout instead of ssh that I use locally.
This combination now allows me to run the CI tasks and pull code from the private repositories without permissions issues - no need for deploy keys or tokens.

A: has any of you managed to get to the bottom of this?
I managed to get git to replace the url for the repo set in composer.json (with the git config --global url... command) but now I get an auth error:
remote: HTTP Basic: Access denied
  fatal: Authentication failed for 'https://xxx.xxxx.xx:4043/xxxx/repo-shared.git/'

I just can't help noticing that the gitlab-ci-token:${CI_JOB_TOKEN}@ is missing in the error... any idea?


text:
Q: My body width is so high and I cant figure why? https://i.stack.imgur.com/jbeyI.png
Okay so I ran into antoher problem.
My body width is so high and I cant figure why??
I will paste code down bellow.
I tried reducing margins but it didnt work.
Tried looking for other answers but nothing.
https://i.stack.imgur.com/jbeyI.png

@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap');

#header {
    background-color: #0f0f0f;
    border-radius: 80px;
    height: 100px;
    margin: 5px;
}

body {
    background-color: #080808;
}

nav {
    word-spacing: 15px;
    transform: translate(1200px,-50px);
}

ul {
    list-style-type: none;
    padding-right: 20px;
}

li {
    display: inline;
    padding: 7px;
}

li, p, h1, #footer{
    font-family: "Montserrat", sans serif;
    color: aliceblue;
}

h1{
 padding-left: 40px;
 padding-top: 30px;
}

p {
    padding-left: 5px;
    padding-right: 5px;
    margin-top: 30px;
}

a:visited {
    text-decoration: none;
    color: aliceblue;
}

a:active {
    text-decoration: none;
    color: aliceblue;
}

a:hover {
    text-decoration: none;
    border-color: black;
    border-style: solid;
    border-width: 2px;
    border-spacing: 100px;
}

a {
    text-decoration: none;
}

#left {
    width: 700px;
}

#right {
    float: right;
    width: 700px;
    transform: translate(0px, -258px);
}

#footer {
    clear: both;
    text-align: right;
    padding: 10px;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Learning</title>

Filip Moslavac

Home

Contact

Projects

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vulputate feugiat nulla ut aliquam. Cras condimentum vestibulum justo, nec blandit dui convallis non. Quisque gravida cursus odio, id porta diam molestie et. Ut dignissim enim blandit, volutpat neque non, ultrices lorem. Suspendisse potenti. Sed pulvinar ligula ut hendrerit pellentesque. Donec accumsan justo velit, nec auctor dui interdum non. Donec sem neque, pellentesque eu dignissim vitae, iaculis vel erat. Donec ante urna, maximus in ullamcorper a, rutrum in velit. Curabitur vulputate diam nec metus dictum, vel posuere nulla dapibus. Fusce arcu tortor, fringilla a vehicula nec, gravida vel libero. Nam at placerat ex, eget feugiat metus. Vestibulum a hendrerit orci. Sed convallis, mauris sed vulputate tempor, diam enim gravida dolor, sit amet commodo tortor erat in mi.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vulputate feugiat nulla ut aliquam. Cras condimentum vestibulum justo, nec blandit dui convallis non. Quisque gravida cursus odio, id porta diam molestie et. Ut dignissim enim blandit, volutpat neque non, ultrices lorem. Suspendisse potenti. Sed pulvinar ligula ut hendrerit pellentesque. Donec accumsan justo velit, nec auctor dui interdum non. Donec sem neque, pellentesque eu dignissim vitae, iaculis vel erat. Donec ante urna, maximus in ullamcorper a, rutrum in velit. Curabitur vulputate diam nec metus dictum, vel posuere nulla dapibus. Fusce arcu tortor, fringilla a vehicula nec, gravida vel libero. Nam at placerat ex, eget feugiat metus. Vestibulum a hendrerit orci. Sed convallis, mauris sed vulputate tempor, diam enim gravida dolor, sit amet commodo tortor erat in mi.

Copyright © 2021 Filip Moslavac

A: If you inspect your code, you will detect that it's your nav bar that is too width
So remove this line in your nav CSS property transform: translate(1200px,-50px);
EDIT : how to put nav bar in top right corner
You can use the flexbox.
Commented code is your code that wasn't correct. I commented it such that you can simply see the modifications.

@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap');

header {
    background-color: #0f0f0f;
    border-radius: 80px;
    /*height: 100px;*/
    margin: 5px;
}

body {
    background-color: #080808;
}

nav {
    word-spacing: 15px;
    display: flex; /*add*/
    justify-content: flex-end; /*add*/
}

ul {
    list-style-type: none;
    padding-right: 20px;
}

li {
    display: inline;
    padding: 7px;
}

li, p, h1, #footer{
    font-family: "Montserrat", sans serif;
    color: aliceblue;
}

h1{
 padding-left: 40px;
 padding-top: 30px;
}

p {
    padding-left: 5px;
    padding-right: 5px;
    margin-top: 30px;
}

a:visited {
    text-decoration: none;
    color: aliceblue;
}

a:active {
    text-decoration: none;
    color: aliceblue;
}

a:hover {
    text-decoration: none;
    border-color: black;
    border-style: solid;
    border-width: 2px;
    border-spacing: 100px;
}

a {
    text-decoration: none;
}
#content{
  display: flex; /*add*/
}
/*#left {
    width: 700px;
}*/

/*#right {
    float: right;
    width: 700px;
    transform: translate(0px, -258px);
}*/

#footer {
    /*clear: both;
    text-align: right;
    padding: 10px;*/
    display: flex; /*add*/
    justify-content: flex-end; /*add*/
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Learning</title>

Filip Moslavac

Home

Contact

Projects

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vulputate feugiat nulla ut aliquam. Cras condimentum vestibulum justo, nec blandit dui convallis non. Quisque gravida cursus odio, id porta diam molestie et. Ut dignissim enim blandit, volutpat neque non, ultrices lorem. Suspendisse potenti. Sed pulvinar ligula ut hendrerit pellentesque. Donec accumsan justo velit, nec auctor dui interdum non. Donec sem neque, pellentesque eu dignissim vitae, iaculis vel erat. Donec ante urna, maximus in ullamcorper a, rutrum in velit. Curabitur vulputate diam nec metus dictum, vel posuere nulla dapibus. Fusce arcu tortor, fringilla a vehicula nec, gravida vel libero. Nam at placerat ex, eget feugiat metus. Vestibulum a hendrerit orci. Sed convallis, mauris sed vulputate tempor, diam enim gravida dolor, sit amet commodo tortor erat in mi.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vulputate feugiat nulla ut aliquam. Cras condimentum vestibulum justo, nec blandit dui convallis non. Quisque gravida cursus odio, id porta diam molestie et. Ut dignissim enim blandit, volutpat neque non, ultrices lorem. Suspendisse potenti. Sed pulvinar ligula ut hendrerit pellentesque. Donec accumsan justo velit, nec auctor dui interdum non. Donec sem neque, pellentesque eu dignissim vitae, iaculis vel erat. Donec ante urna, maximus in ullamcorper a, rutrum in velit. Curabitur vulputate diam nec metus dictum, vel posuere nulla dapibus. Fusce arcu tortor, fringilla a vehicula nec, gravida vel libero. Nam at placerat ex, eget feugiat metus. Vestibulum a hendrerit orci. Sed convallis, mauris sed vulputate tempor, diam enim gravida dolor, sit amet commodo tortor erat in mi.

Copyright © 2021 Filip Moslavac


text:
Q: Eventlet - ImportError: No module named dnskeybase I can't import eventlet on my production system. It's saying no module named dnskeybase.
# python scraper.py
Traceback (most recent call last):
  File "scraper.py", line 7, in <module>
    import eventlet
  File "/usr/lib/python2.7/site-packages/eventlet/__init__.py", line 10, in <module>
    from eventlet import convenience
  File "/usr/lib/python2.7/site-packages/eventlet/convenience.py", line 7, in <module>
    from eventlet.green import socket
  File "/usr/lib/python2.7/site-packages/eventlet/green/socket.py", line 21, in <module>
    from eventlet.support import greendns
  File "/usr/lib/python2.7/site-packages/eventlet/support/greendns.py", line 67, in <module>
    setattr(dns.rdtypes, pkg, import_patched('dns.rdtypes.' + pkg))
  File "/usr/lib/python2.7/site-packages/eventlet/support/greendns.py", line 59, in import_patched
    return patcher.import_patched(module_name, **modules)
  File "/usr/lib/python2.7/site-packages/eventlet/patcher.py", line 120, in import_patched
    *additional_modules + tuple(kw_additional_modules.items()))
  File "/usr/lib/python2.7/site-packages/eventlet/patcher.py", line 94, in inject
    module = __import__(module_name, {}, {}, module_name.split('.')[:-1])
ImportError: No module named dnskeybase

So I tried to install it...
# pip install dnskeybase
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Collecting dnskeybase
  Could not find a version that satisfies the requirement dnskeybase (from versions: )
No matching distribution found for dnskeybase

and:
# pip install dnspython
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Requirement already satisfied: dnspython in /usr/lib/python2.7/site-packages (1.16.0)

and the eventlet version/installation:
# pip install eventlet
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Collecting eventlet
  Using cached https://files.pythonhosted.org/packages/86/7e/96e1412f96eeb2f2eca9342dcc4d5bc9305880a448b603b0a8e54439b71c/eventlet-0.24.1-py2.py3-none-any.whl
Requirement already satisfied: monotonic>=1.4 in /usr/lib/python2.7/site-packages (from eventlet) (1.5)
Requirement already satisfied: six>=1.10.0 in /usr/lib/python2.7/site-packages (from eventlet) (1.12.0)
Requirement already satisfied: dnspython>=1.15.0 in /usr/lib/python2.7/site-packages (from eventlet) (1.16.0)
Requirement already satisfied: greenlet>=0.3 in /usr/lib64/python2.7/site-packages (from eventlet) (0.4.15)
Requirement already satisfied: enum34; python_version < "3.4" in /usr/lib/python2.7/site-packages (from eventlet) (1.1.6)
Installing collected packages: eventlet
Successfully installed eventlet-0.24.1

Any idea?

A: Your local dnspython package installation is broken, or being masked by an incomplete dns.rdtypes package in a different location. It is missing (at least) the dns.rdtypes.dnskeybase module; it's just another pure-Python module, nothing special.
The exception message may look a little confusing, because it doesn't name the full path. The moral equivalent of the following Python expression is being executed:
module_name = 'dns.rdtypes.dnskeybase'
__import__(module_name, {}, {}, module_name.split('.')[:-1])

which uses the __import__ function to dynamically import the dnskeybase module from the dns.rdtypes package. When it is missing, however, the ImportError: No module named dnskeybase exception raised doesn't include the dns.rdtypes component, even though that's the only location that the import was attempted from. The eventlet.support.greendns module has, by this stage, already imported dns.rdtypes itself, so we know that for your installation, that package at least is present and importable.
A normal full install of the package adds a site-packages/dns directory with the following files (plus corresponding .pyc byte-cache files):
lib/python2.7/site-packages/dns
├── __init__.py
├── _compat.py
├── dnssec.py
├── e164.py
├── edns.py
├── entropy.py
├── exception.py
├── flags.py
├── grange.py
├── hash.py
├── inet.py
├── ipv4.py
├── ipv6.py
├── message.py
├── name.py
├── namedict.py
├── node.py
├── opcode.py
├── py.typed
├── query.py
├── rcode.py
├── rdata.py
├── rdataclass.py
├── rdataset.py
├── rdatatype.py
├── rdtypes
│   ├── ANY
│   │   ├── AFSDB.py
│   │   ├── AVC.py
│   │   ├── CAA.py
│   │   ├── CDNSKEY.py
│   │   ├── CDS.py
│   │   ├── CERT.py
│   │   ├── CNAME.py
│   │   ├── CSYNC.py
│   │   ├── DLV.py
│   │   ├── DNAME.py
│   │   ├── DNSKEY.py
│   │   ├── DS.py
│   │   ├── EUI48.py
│   │   ├── EUI64.py
│   │   ├── GPOS.py
│   │   ├── HINFO.py
│   │   ├── HIP.py
│   │   ├── ISDN.py
│   │   ├── LOC.py
│   │   ├── MX.py
│   │   ├── NS.py
│   │   ├── NSEC.py
│   │   ├── NSEC3.py
│   │   ├── NSEC3PARAM.py
│   │   ├── OPENPGPKEY.py
│   │   ├── PTR.py
│   │   ├── RP.py
│   │   ├── RRSIG.py
│   │   ├── RT.py
│   │   ├── SOA.py
│   │   ├── SPF.py
│   │   ├── SSHFP.py
│   │   ├── TLSA.py
│   │   ├── TXT.py
│   │   ├── URI.py
│   │   ├── X25.py
│   │   └── __init__.py
│   ├── CH
│   │   ├── A.py
│   │   └── __init__.py
│   ├── IN
│   │   ├── A.py
│   │   ├── AAAA.py
│   │   ├── APL.py
│   │   ├── DHCID.py
│   │   ├── IPSECKEY.py
│   │   ├── KX.py
│   │   ├── NAPTR.py
│   │   ├── NSAP.py
│   │   ├── NSAP_PTR.py
│   │   ├── PX.py
│   │   ├── SRV.py
│   │   ├── WKS.py
│   │   └── __init__.py
│   ├── __init__.py
│   ├── dnskeybase.py
│   ├── dsbase.py
│   ├── euibase.py
│   ├── mxbase.py
│   ├── nsbase.py
│   └── txtbase.py
├── renderer.py
├── resolver.py
├── reversename.py
├── rrset.py
├── set.py
├── tokenizer.py
├── tsig.py
├── tsigkeyring.py
├── ttl.py
├── update.py
├── version.py
├── wiredata.py
└── zone.py

A properly installed dnspython version 1.16.0 produces the following MD5 checksum for the Python source files in the file tree:
$ ( cd /lib/python2.7/site-packages/dns; export LC_ALL=C; find . -name \*.py -exec md5sum {} \; | sort -k 2 | md5sum )
28e20d8474f4f07287c305dbd5dae8b8  -

If you run the same command and you get a different output then your local installation is incomplete.
I recommend you reinstall the package; this is trivially done with pip install --ignore-installed:
$ pip install --ignore-installed dnspython
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Collecting dnspython
  Using cached https://files.pythonhosted.org/packages/ec/d3/3aa0e7213ef72b8585747aa0e271a9523e713813b9a20177ebe1e939deb0/dnspython-1.16.0-py2.py3-none-any.whl
Installing collected packages: dnspython
Successfully installed dnspython-1.16.0

If you still experience issues even after reinstalling, or you got the same MD5 checksum of the file tree, then you have a different dns.rdtypes package on your python module search path that is masking the proper version.
You can find that package by adding:
import dns.rdtypes
print(dns.rdtypes.__file__)

at the top of your scraper.py script, before the import eventlet line. Feel free to use import sys; sys.exit() right after to prevent the full traceback. The file printed should tell you where to look for the rogue package that is interfering. Once you find it, rename that dns directory, or adjust your PYTHONPATH environment variable to not include the directory that the dns directory is located in, or delete it entirely.


text:
Q: Angular 2 modify router prams not getting added to URL If url contains ?edit= "true" orfalse, I need to append that value to my router link.
Based on the below feedback I've modified my code.
But i'm this error ?edit=%5Bobject%20Object%5D . value of the edit is not getting appended to the URL.
Please tell me what i'm doing wrong here.

urlValue: any;
ngOnInit() {
  this.urlValue = {
    edit: this.activatedRoute.queryParamMap.map((params) => params.get('edit'))
  };
}

  View Production Plan

A: Use queryParamMap  from Activated route as per query parameters documentation as below :
import { Router, ActivatedRoute, ParamMap } from '@angular/router';

constructor(
  private route: ActivatedRoute,
  private router: Router
) {}

ngOnInit() {
  const value = this.route.queryParamMap.map(params => params.get('edit') || false ) ;
  this.urlValue = {
    edit: value
  };
}

and use it as below
View Production Plan


text:
Q: How to Authenticate a client created in Windows Form with an ASP.NET MVC website? I would like to create a Windows Forms client where users write Username and Password and gets authenticated with my website. Users that should authenticate on client should have already an account on my website.
How can i do that? Where should i start? Can't find any guide about that.

A: Within your WinForms project use the HttpClient / WebRequest method to setup a request to send a POST with the credentials (ideally over the HTTPS protocol).  You should be able to analyse the response back to determine if authentication was successful.  This might help for this approach https://lookonmyworks.co.uk/2011/08/22/making-a-post-request-in-c-with-basic-authentication/
Another method is to setup a RESTful API on your website which is easier IMHO to work with for specific tasks that you setup in your end point: How to get HttpClient to pass credentials along with the request?


text:
Q: Undefined symbols for architecture i386: i am integrating CHartBoost, and while integrating i am getting few issue.
I have attached a screenshot.
Undefined symbols for architecture i386:
Is it something, with missing libraries?

Many Thanks

A: Add QuartzCore to your target's linked libraries, as explained in this answer.


text:
Q: begin typing from middle of text area Not work for ionic I am creating some ionic3 small application.  I tried to create like as whats app status page. I added ionic text area for that. but text input cursor not in a  begin typing in middle. Does anyone know how to do that correctly?
Html
<ion-content>
  <textarea #myInput id="myInput" rows="7" maxLength="300" (keyup)="resize()" [(ngModel)]="myStuff" text-center placeholder="Notifictaion here..."></textarea>
</ion-content>

css.

#myInput {
    width: calc(100%);
    border: 0;textAlignVertical: 'center';
    border-radius: 0; font-size: 2rem;
    background: #3e50b4; color: white;
  }

you can understand my issue look at my attached  image
Issue

I want to like this

A: Finally i do that , i put hsome padding for my css  padding: 100px 10px 100px 10px; now its work for me
before
#myInput {
    width: calc(100%);
    border: 0;textAlignVertical: 'center';
    border-radius: 0; font-size: 2rem;
    background: #3e50b4; color: white;
  }

then
#myInput {
    width: calc(100%);
    border: 0;textAlignVertical: 'center';
    border-radius: 0; font-size: 2rem;
    background: #3e50b4; color: white;
   padding: 100px 10px 100px 10px;
  }


text:
Q: How to update MSSQL DB schema during deployment in HA enviroment without any downtime I spend a lot of time trying to figure out what MSSQL provide to update MSSQL schema without loosing the sync, but I find it hard to find a solution.
Does any of you faced the some problem ?
I found two solutions and both are not an option :

*

*move to NoSQL DB

*halt calls to DB until update finish.
The most simple scenarios is you have either 1 DB or 2 DBs in sync

A: Despite the restriction, I will recommend this. :-)
"halt calls to DB until update finish"
The schema change will likely finish in seconds (test this on a test copy of the database!), so users will not even notice the pause. The pausing part can be implemented on a proxy so that there's no need to make application changes. This allows your application code to be changed at the same time so that it never needs to support both schema versions at once.
Let's assume that all URLs in your application can be classified as either fast (less than 10 seconds) or slow (10-60 seconds).
1) Proxy starts pausing all slow requests and waiting 10-60 seconds for already in progress slow requests to finish.
2) Proxy starts pausing all requests and waiting 0-10 seconds for already in progress fast requests to finish.
3) Run the schema migration and switch to new application code that uses the new version of the schema. With no load on the database, the schema migration should be very fast.
4) Proxy lets all paused requests through.
Users who were waiting for slow requests are not surprised that their typically 60 second requests took 130 seconds instead. Users who were waiting for fast requests might notice that their 10 second request took 30 seconds instead. Anyone who notices the slight lag will probably forget a minute later.

A: You can update the DB Schema without switching databases, turning off replication or losing data if you structure your queries correctly and use transactions.
Instead of a simple drop table, create table you must plan out the change, moving the data to a temporary table and transferring it back all within the same transaction.
There are several tools which will generate the migration statements for you. Visual Studio Enterprise, Entity Framework Migrations and various third party software.


text:
Q: Can you use Azure Key Vault Generated Certificates to Authenticate Azure IoT Hub devices? So apart from SAS-Keys I can choose Self-Signed and CA-Signed Certificates as an authentication method and the Azure Key Vault can no also generate Certificates.
I did not find a way to use the generated certificates from the Azure Key Vault to authenticate my Azure IoT Hub Devices. Is / should this be possible?

A: Azure IOT devices support only three authentication type with IOT hub

*

*Symmetric key authentication

*X.509 self-signed authentication

*X.509 CA-signed authentication

You can store the root CA certificate and device primary and Secondary certificate and Key generated by above authentication in Azure Key Vault for the security purpose, but you cannot use the certificate that is self generated by Key Vaul and even you cannot directly use certificate from Key Vault you have to put or download and update them in a folder of your IOT Edge. From IOT Edge you can use in your IOT devices.
You can refer this GITHUB discussion for more clarification: https://github.com/MicrosoftDocs/azure-docs/issues/48565


text:
Q: Find Total Mins Between Multiple Swipe In/Swipe Out Timestamps - Select multiple records from vertical row and transform horizontal row I am working on a SQL Server query to fetch the Badge Out Time - Bade In Time of the list of users who will be working on multiple task codes.
task_mgmt - tablename
Table Columns as follows

Task_Sn
UserName
Task_Code
Action
Badge_IN_OUT_TIME

1
Andy
BLOG
START
2021-07-20 08:11:45.000

2
Andy
BLOG
END
2021-07-20 10:11:45.000

3
Becky
ACCTS
START
2021-07-20 11:11:45.000

4
Becky
ACCTS
END
2021-07-20 12:11:45.000

5
Andy
BLOG
START
2021-07-20 12:15:45.000

6
Andy
BLOG
END
2021-07-20 12:25:45.000

7
Andy
BLOG
START
2021-07-20 12:25:00.000

8
Becky
ACCTS
START
2021-07-20 13:00:00.000

9
Becky
ACCTS
END
2021-07-20 13:30:00.000

I am excepting the result

UserName
Task_Code
Badge_IN_TIME
Badge_OUT_TIME
TOTAL_MINS_SPENT

Andy
BLOG
2021-07-20 12:25:55.000

135

Becky
ACCTS
2021-07-20 13:00:00.000
2021-07-20 13:30:00.000
90

I really couldn't come up with any query for this. I am a beginner in SQL and I know CRUD operations. This seems to be super complex for me.
Select UserName,
       Task_Code,
       Badge_In_Time,
       Badge_Out_Time,
       (Badge_Out_Time - Badge_In_Time) as TOTAL_TIME_SPENT
from task_mgmt
order by Badge_IN_OUT_TIME desc

Since Andy is currently badge-in and not badge-out yet, so the latest badge-out timestamp is being calculated as [ getdate() - badge-in ] as LastTransaction Mins (5 mins)

A: In your sample data the last start time for Andy was earlier than his last end time, therefore creating an overlap.  I am making the assumption this is incorrect given how you described your logic for calculating total minutes. Therefore in my sample table I have adjusted accordingly.
Consider the following:
I used a derived table with the LEAD() function to capture what the next date and action where.  I Used this in my outer query to determine the minutes used based on what my next action was going to be.
I used a CROSS APPLY to determine what the MAX Start and End dates where for the username and task.
CREATE TABLE #tmp(Task_Sn int,  UserName varchar(20),Task_Code varchar(10), Action varchar(10), Badge_IN_OUT_TIME datetime)
INSERT INTO #tmp
VALUES
(1,'Andy','BLOG','START','2021-07-20 08:11:45.000'),
(2,'Andy','BLOG','END','2021-07-20 10:11:45.000'),
(3,'Becky','ACCTS','START','2021-07-20 11:11:45.000'),
(4,'Becky','ACCTS','END','2021-07-20 12:11:45.000'),
(5,'Andy','BLOG','START','2021-07-20 12:15:45.000'),
(6,'Andy','BLOG','END','2021-07-20 12:25:45.000'),
(7,'Andy','BLOG','START','2021-07-20 12:35:00.000'),
(8,'Becky','ACCTS','START','2021-07-20 13:00:00.000'),
(9,'Becky','ACCTS','END','2021-07-20 13:30:00.000')

SELECT X.UserName,X.Task_Code ,Y.ST_TIME Badge_IN_TIME
    ,CASE WHEN Y.ST_TIME > Y.ED_TIME THEN NULL ELSE Y.ED_TIME END Badge_OUT_TIME
    ,SUM(CASE WHEN Action = 'START' AND NX_ACTION= 'END' THEN DATEDIFF(minute,Badge_IN_OUT_TIME, NX_TIME)
         WHEN ACTION = 'START' AND NX_ACTION IS NULL THEN DATEDIFF(minute,Badge_IN_OUT_TIME, GETDATE())
         END) TotalMinutesSpent
FROM(
    select *,
    LEAD(Badge_IN_OUT_TIME,1) OVER(Partition by UserName,Task_Code  ORDER BY  Badge_IN_OUT_TIME) NX_TIME,
    LEAD(ACTION,1) OVER(Partition by UserName,Task_Code ORDER BY  Badge_IN_OUT_TIME) NX_ACTION
    from #tmp
    ) X
CROSS APPLY(SELECT UserName,
                MAX(CASE WHEN Action = 'START' THEN Badge_IN_OUT_TIME END) ST_TIME,
                MAX(CASE WHEN Action = 'END' THEN Badge_IN_OUT_TIME END) ED_TIME
                FROM #tmp t1
                    WHERE t1.UserName = X.UserName
                            and t1.Task_Code = X.Task_Code
                GROUP BY UserName, Task_Code
            ) Y
GROUP BY X.USERNAME,X.Task_Code ,Y.ST_TIME,Y.ED_TIME

A: This seems to work:
SELECT UserName,
       Task_Code,
       task_in.Task_Sn as Task_In_Sn,
       TOUT.Task_Out_Sn,
       task_in.Badge_IN_OUT_TIME as Time_In_Raw,
       FORMAT(task_in.Badge_IN_OUT_TIME, 'hh\:mm') as Task_In_Time,
       FORMAT(TOUT.Task_Out_Time, 'hh\:mm') as Task_Out_Time,
       DATEDIFF(minute, task_in.Badge_IN_OUT_TIME,
                 ISNULL(TOUT.Task_Out_Time, GETDATE())) as LengthOfTime
FROM task_mgmt task_in
    OUTER APPLY (
       SELECT TOP 1
            task_out.Task_Sn as Task_Out_Sn,
            task_out.Badge_IN_OUT_TIME as Task_Out_Time
        FROM task_mgmt task_out
        WHERE task_out.Action = 'END' AND
              task_out.UserName = task_in.UserName AND
              task_out.Task_Sn > task_in.Task_Sn
        ORDER BY Task_Sn
    ) TOUT
WHERE task_in.Action = 'START'
ORDER BY Task_Sn

Note that the OUTER APPLY looks for the first record with a larger Task_Sn that matches the other criteria (I could have used Badge_IN_OUT_TIME instead of Task_Sn, but integers are a little nicer and possibly more efficient).
Note also the ISNULL in the DATEDIFF that substitutes GETDATE when the date is NULL.
If you need to sum multiple intervals, you can use GROUP BY.

A: I provided the answer but I know there is two columns missing in the expected result.
Note: These two columns Badge_IN_TIME    Badge_OUT_TIME are missing as I am not sure about the what you want to retrieve for these two columns, If you can clarify the result and expected values for these tow columns as the way you showed for the TOTAL_TIME_SPENT I can edit the Question and add these two columns derivation as well.
After adding the logic to the above mentioned columns This is what my query returns. I think The expected answer is also haveing some issue as it should in line with the logic.
SELECT
  DISTINCT
  UserName
  , Task_Code
  ,( SELECT  MAX(Badge_IN_OUT_Time ) from  task_mgmt E where E.UserName =  A.UserName   and A.Task_code =  E.Task_Code and    [Action] ='Start'  )  Badge_IN_TIME
   ,( SELECT  MIN(Badge_IN_OUT_Time ) from  task_mgmt E where E.UserName =  A.UserName   and A.Task_code =  E.Task_Code and    [Action] ='END'  )  Badge_OUT_TIME
  , SUM( [DATEDIFF] ) OVER (PARTITION BY  UserName, Task_Code, [Action]  order by  UserName ) as  Total_MinsSpend
 FROM
  (
   SELECT
   Task_sn
 , UserName
 , Task_Code
 , [Action]
 , Badge_IN_OUT_Time
 , ISNULL( LEAD(Badge_IN_OUT_Time) over  (Partition by UserName, Task_Code order by UserName ), '2021-07-20 12:30:00.000') as [StartTime_Lead]
 ,  DATEDIFF ( MINUTE,Badge_IN_OUT_Time ,iSNULL( LEAD(Badge_IN_OUT_Time) over  (Partition by UserName, Task_Code order by UserName ), '2021-07-20 12:30:00.000')  ) as [DATEDIFF] --Get the date dfference
  FROM  task_mgmt
  )
 AS A Where A.[Action]  in ('Start')


text:
Q: Why can't I use @ to replace the long relative path in my __tests__ folder?
I initialed my vue project via vue-cli.
I can use @ in my src folder, but it doesn't work in my __tests__ folder.
I've already added config in my tsconfig.json file, but I'm not sure whether it's for this situation.
"paths": {
  "@/*": ["src/*"]
},

A: The test framework needs to be configured with the path aliases as well. It's not automatically configured with tsconfig.json or vue.config.js (or any other config).
To configure the path alias in Jest, use the moduleNameMapper option:
// <projectRoot>/jest.config.js
module.exports = {
  moduleNameMapper: [
    '^@/(.*)$': '<rootDir>/src/$1'
  ]
}

This is normally configured for you if using @vue/cli-plugin-unit-jest, but if you've setup Jest on your own without the plugin, you would need the config mentioned above.


text:
Q: Oracle pl/sql: Encountered the symbol "" So I am trying to create this trigger that checks whether the number of availabletickets is greater than 0 and if it isn't, it throws an error while booking but while creating the trigger, i am getting the following error
PLS-00103: Encountered the symbol ""

here is my code:
create or replace trigger booked_ticket before insert OR UPDATE on booking for each row
declare
    v_available NUMBER;
begin
  SELECT AVAILABLETICKETS into v_available from HALLSEAT WHERE HALLSEAT .STAGEID=:NEW.STAGEID;
IF v_available<1 THEN
 Raise_Application_Error(-20343, 'You cant book');
END IF;
end;

A: Actually, it compiles OK (I've created dummy tables, just to make the trigger compile). I didn't modify your code at all, simply copy/pasted it into my SQL*Plus session.
Though, I'd suggest you to

*

*learn how to format code and make it easier to read.

*edit your question and copy/paste your SQL*Plus session so that we could see what you exactly did and how Oracle responded. It'll indicate the place where you get the error, as just saying that there's one doesn't help much

SQL> create table booking (stageid number);

Table created.

SQL> create table hallseat (availabletickets number, stageid number);

Table created.

SQL> create or replace trigger booked_ticket before insert OR UPDATE on booking for each row
  2  declare
  3      v_available NUMBER;
  4  begin
  5    SELECT AVAILABLETICKETS into v_available from HALLSEAT WHERE HALLSEAT .STAGEID=:NEW.STAGEID;
  6  IF v_available<1 THEN
  7   Raise_Application_Error(-20343, 'You cant book');
  8  END IF;
  9  end;
 10  /

Trigger created.

SQL>

[EDIT]
Though, yes - GUI (SQL Developer) reports the error in line 7 + column 7. It is this line:
 Raise_Application_Error(-20343, 'You cant book');
      ^
      here

As if there's some "unrecognized" character. I reviewed that code in Notepad++, set it to display all characters, but none (except CR/LF) appeared, so I'm not sure what is the real reason for that error.
The simplest way to "fix" it is to delete everything you have (I mean, that trigger) and write (type) it once again. Should be OK (was when I tried it, at least).

A: Very sketchy error: you have an invisible character ASCII(8203) after your line 9 "end;" statement. Copy and paste this trigger instead and you'll be fine.
create or replace trigger booked_ticket before insert OR UPDATE on booking for each row
declare
    v_available NUMBER;
begin
  SELECT AVAILABLETICKETS into v_available from HALLSEAT
  WHERE HALLSEAT .STAGEID=:NEW.STAGEID;
IF v_available<1 THEN
 Raise_Application_Error(-20343, 'You cant book');
END IF;
end;