text:
Q: ¿Cómo estructurar un contenido según esta imagen? Tengo este auto reto y quisiera saber qué creen en esta comunidad sobre cuál sería mejor estructurar o maquetar el HTML y CSS para un diseño como el de la siguiente imagen:

Teniendo en cuenta, además, las siguientes condiciones:

*

*Código HTML con el menor número de elementos o anidaciones.

*Usando técnicas CSS modernas y sin tantas líneas de código.

*No usar JavaScript como reto.

Estuve tratando de lograrlo usando grid, pero aún no tengo tan claro cómo funciona y no sé cómo centrar el contenido al centro en pantallas superiores a los 1080px. Otra cosa, cuando decida seguir agregando más bloques a la columna 1 se sitúa en la misma fila que el elemento C y no entiendo por qué, además que no se si haya alguna forma de alterar el orden de los elementos para lograr la el diseño "SM":

*{
  box-sizing: border-box;
}

body{
  background: #f1f2f2;
}

.principal_container{
  background: white;
  display: grid;
  padding: 10px;
  grid-gap: 10px;
}

.section{
  border: 5px solid blue;
  padding: 5px;
}

.content_01,
.content_03{
  max-width: 960px;
}

@media (min-width: 720px){

  .principal_container{
    grid-template-columns:
      [col1-start] calc(100% - 10em - 10px)
      [col2-end] 10em;
    grid-template-rows:
      [row1-start] auto
      [row2-start] auto
      [row2-end];
  }

  .content_01 {
    grid-column: col1-start;
    grid-row: row1-start ;
  }
  .content_02 {
    grid-column: col2-end ;
    grid-row: row1-start / row2-end;
  }
  .content_03 {
    grid-column: col1-start;
    grid-row: row2-start ;
  }

}

      A

      B

      C

Por lo que después opte por flex y usar calc para lograr mi objetivo. Lo consideré un poco más fácil de usar, pero no sé cómo hacer para que el bloque B se estire hasta la base del contenedor, sin embargo si decido colocar más elementos a la columna 1, si puedo hacerlo sin producir errores. Ejemplo:

*{
  box-sizing: border-box;
}

body{
  background: #f1f2f2;
  font-family: arial;
}

.principal_container{
  display: inline-block;
  background: white;
  display: flex;
  flex-wrap: wrap;
  padding: 5px;
  justify-content: left;
}

.section{
  border: 5px solid blue;
  margin: 5px;
  padding: 5px;
  color: purple;
  width: 100%;
  order: 2;
}

.content_02{
  order: 3;
}

@media (min-width: 720px){
  .content_01, .content_03{
    width: calc(100% - 10em - 20px);
    max-width: 960px;
  }

  .content_02{
    width: 10em;
    order: 2;
  }
}

      A

      B

      C

Pero, pienso que no es la solución más óptima, ya que creo que grid podría ser la mejor opción, lo único es que no se como solucionar el inconveniente de agregar más elementos posteriores a la columna 1 o alinear al centro en pantallas "XL".
Otra solución que se me ocurrio, es usar position: absolute y jugar con el padding del principal_container, pero quisiera lograrlo sin alterar el flujo de los elementos.
¿Como lo solucionarían ustedes?

A: Alinear al centro en pantallas XL es simple (y todas en general). Al contenedor principal principal_container le debes indicar que es un elemento de bloque (como es un div es automático, así que simplemente le quito el inline-block), poner un ancho máximo y luego indicar que los márgenes sean auto. El navegador centrará automáticamente el contenedor.
Aquí lo puedes ver funcionando (las secciones las veremos abajo):

* {
  box-sizing: border-box;
}

body {
  background: #f1f2f2;
  font-family: arial;
}

.principal_container {
  background: white;
  padding: 5px;
  margin: auto auto;
  max-width: 1024px;
}

    A

    B

    C

En tu caso, el ancho máximo no sería 1024px, sino 960px (el máximo de A/C) + 10em de B + 20px de los márgenes de las secciones. De ese modo estarías imponiendo un ancho máximo efectivo de 960px a A y C, sin especificarlo de manera explicita.
Ahora, para lo que quieres de maquetar las secciones, puedes usar un grid. Y para ser sincero: lo tenías básicamente hecho, lo único que he cambiado con respecto a tu ejemplo ha sido un valor y ya funciona. Quita el calc del ancho de la columna en grid-template-columns y dale el valor auto para que A y C siempre ocupen el espacio disponible.
Puedes dejar el order: 3 para el bloque B, porque se seguirá aplicando con grid también. Y si no especificas columnas, entonces automáticamente ocuparán todo el ancho (al ser secciones) y harás que B aparezca al final sin afectar a su posicionamiento cuando la pantalla sea más grande de 720px.
Aquí lo puedes ver funcionando:

* {
  box-sizing: border-box;
}

body {
  background: #f1f2f2;
  font-family: arial;
}

.principal_container {
  display: grid;
  background: white;
  padding: 5px;
  margin: auto auto;
  max-width: calc(960px + 10em + 20px);
}

.section {
  border: 5px solid blue;
  padding: 5px;
  margin: 5px;
}

.content_02 {
  order: 3;
}

@media all and (min-width: 720px) {
  .principal_container {
    grid-template-columns: [col1-start] auto [col2-end] 10em;
    grid-template-rows: [row1-start] auto [row2-start] auto [row2-end];
  }
  .content_01 {
    grid-column: col1-start;
    grid-row: row1-start;
  }
  .content_02 {
    grid-column: col2-end;
    grid-row: row1-start / row2-end;
  }
  .content_03 {
    grid-column: col1-start;
    grid-row: row2-start;
  }
}

    A

    B

    C

Sobre añadir nuevos elementos: si añades nuevos bloques a tu estructura, estos elementos van a afectar el tamaño y la estructura del grid y tendrías que cambiar el CSS porque ahora mismo es específico para 3 elementos.
Lo que podrías hacer sería especificar que va a haber dos columnas (1 auto y la otra de 10em) y que todas las filas van a ser auto. Para todas las secciones, la columna será la 1, y no hace falta especificar un row, que será auto por defecto. Luego para .content_02 especificar que su columna va a ser la 2 y para la fila lo que puedes hacer es especificar que va a empezar en la primera y terminar en un número muy grande (más grande que el número de nuevos elementos que se vayan a añadir), de ese modo crecerá automáticamente hasta ocupar todo el espacio disponible (tiene que haber un modo mejor de hacerlo, esto es demasiado hacky).

* {
  box-sizing: border-box;
}

body {
  background: #f1f2f2;
  font-family: arial;
}

.principal_container {
  display: grid;
  background: white;
  padding: 5px;
  margin: auto auto;
  max-width: calc(960px + 10em + 20px);
}

.section {
  border: 5px solid blue;
  padding: 5px;
  margin: 5px;
}

.content_02 {
  order: 3;
}

@media all and (min-width: 720px) {
  .principal_container {
    grid-template-columns: auto 10em;
  }
  section {
    grid-column: 1;
  }
  .content_02 {
    grid-column: 2;
    grid-row: 1 / 999999;
  }
}

    A

    B

    C

    D

    E


text:
Q: Operator 'op ' cannot be applied to operands of type 'dynamic' and 'lambda expression' I can't seem to apply binary operations to lambda expressions, delegates and method groups.
dynamic MyObject = new MyDynamicClass();
MyObject >>= () => 1 + 1;

The second line gives me error: Operator '>>=' cannot be applied to operands of type 'dynamic' and 'lambda expression'
Why?
Isn't the operator functionality determined by my custom TryBinaryOperation override?

A: dynamic MyObject = new MyDynamicClass();
MyObject >>= new Func<int>(() => 1 + 1);

A: It's not an issue with MyDynamicClass, the problem is that you can't have a lambda expression as a dynamic. This however, does appear to work:
dynamic MyObject = new MyDynamicClass();
Func<int> fun = () => 1 + 1;
var result = MyObject >>= fun;

If the TryBinaryOperation looks like this:
result = ((Func<int>) arg)();
return true;

Then result will be 2. You can use binder.Operation to determine which binary operation this is.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular2+ не рендерится модалка с iframe, пока не двинется мышь Всем привет, Такая проблема:
Angular, есть компонент (модалка) - кредитная карта. Есть сервис, который запускает библиотеку (платёжная система, получает пропсы, генерирует токен, устанавливает соединение с api, генерирует html-страницу в iframe).
Ответ с подтверждением оплат и OTP-ключем приходит в iframe, который лежит в отдельной модалке.
Эта модалка не запускается, пока пользователь не сделает что-то в браузере, тоже самое и после свершения платежей - окно автоматически должно закрываться, но пока пользователь не шевельнется - все остается статичным.
модалка iframe.html
<iframe name="authentication-3ds-frame" id="xendit-three-ds-container"style="width: 100%; height: 370px;" ></iframe>

модалка iframe.ts
export class Authentication3DSComponent {
    @Input() modalData: any;
    globalEventsSubscription;

    constructor(
      private eventService: EventService, private modal: Modal) {
        this.globalEventsSubscription = this.eventService.emitter.subscribe(
            (event) => {
                this.handleGlobalEvents(event);
            }
        );
    }

    ngOnInit() {
        let payer_authentication_url = this.modalData.payer_authentication_url;
        window.open(payer_authentication_url, "authentication-3ds-frame");
    }

    ngOnDestroy() {
        this.globalEventsSubscription.unsubscribe();
    }

    handleGlobalEvents(event) {
        if (event.type === 'payment-service:xendit-token-status-verified') {
            this.close();
        }
    }

    close() {
        this.modal.close({
            id: "Authentication3DS"
        })
    }
}

A: вопрос решен отключением zone.js и "ручным" запуском ChangeDetection в интервале 100мс


text:
Q: Typescript on Kendo UI - typed datasource definition I am starting to migrate an application into Typescript that uses Kendo UI.
One of the first items that I believe I am not using typescript full potential is for the definition of the Datasource. While writing the datasource definition, I didn´t get any of the typed properties of the "transport" object (e.g. read, parameterMap, etc.).
Am I doing something wrong, or is there a better way to define a datasource on typescript?
I went on Kendo's documentation but couldn't find any example that was written differently.
See my code below:
class ViewModel extends kendo.data.ObservableObject {
    dadosGrid = new kendo.data.DataSource({
        type: "jsonp",
        transport: {
            read: {
                url: '/Controller/Action',
                contentType: "application/json",
                type: "POST"
            },
            parameterMap: function (options) {
                return kendo.stringify(options);
            }
        },
        schema: {
            total: "Total",
            data: "Data",
            model: {
                id: "Id",
                fields: {
                    Name: { type: "string" },
                    Surname: { type: "string" },
                }
            }
        },
        pageSize: 10,
        serverPaging: true,
        serverFiltering: true,
        serverSorting: true
    });

    //#endregion
}

Thanks

A: Did you reference the Kendo definitions file at the top of your TypeScript file?
/// <reference path="kendo.all.d.ts" />

http://docs.telerik.com/kendo-ui/howto/typescript/overview

A: I hit this as well.  This question is old, so just adding for anyone else.  I'm guessing they need to update their definition.  For now, I'm just doing something like this:
var dataSource: any = this._scheduler.dataSource;
   dataSource.transport.options.read.url = schedulerOptions.readUrl;

A: Probably a bit late, but still
You can use separate interface for it and use it like on screenshot


text:
Q: 2023 Everybody! We made it. I want to update my form, but my details are not pulling through to the form I want to Update/Edit my details on my form. I want to pull the existing details from the database and have them populate on the form, without having the user start from the beginning.
Views.py
def Client_Update(request, Client_id):
    ClientUpdate = TestModel.objects.get(pk=Client_id)
    ClientUpdates = TestForm(request.POST or None, instance=ClientUpdate)
    if request.method == 'POST':
       if ClientUpdates.is_valid():
        ClientUpdates.save()
        return redirect('/Client_Details')
    return render(request, 'GymApp/ClientUpdate.html',
    {'ClientUpdate':ClientUpdate,
    'ClientUpdates':ClientUpdates})

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

urlpatterns = [
    path('', views.Home, name='Home'),
    path('ClientList/', views.Client_list, name='Client_list'),
    path('ClientDetails/<int:Client_id>', views.Client_Details, name='Client_Details'),
    path('ClientUpdate/<int:Client_id>', views.Client_Update, name='Client_Update'),
    path('ClientDelete/<int:Client_id>', views.Client_Delete, name='Client_Delete'),
    path('DownloadingCSV/', views.DownloadingCSV, name='DownloadingCSV'),
    path('Search/', views.Search, name='Search'),

]

HTML Page
{% extends 'GymApp/Layout.html' %}
{% block content %}

Updating status

    <form action="" method="POST">
        {% csrf_token %}

            <input type="text" class="form-control"
             name="Name" placeholder="Client's Name">

            <input type="text" class="form-control"
              name="Surname"placeholder="Client's Surname">

            <select name="Gender" class="form-control">
                <option selected disabled>
                    Open this select menu
                </option>
                <option value="Male">Male</option>

                <option value="Female">Female</option>
            </select>

            <input type="text" class="form-control"  name="Weight" id="Weight" placeholder="Client's Weight">

            <input type="text" class="form-control"  name="Height" id="Height" placeholder="Client's Height">

            <button type="button" onclick="calculation()">Calculation update</button>

            <input type="text" class="form-control"  name="Outcome" id="Outcome" placeholder="BMI Outcome">

            <select name="Activity_log" class="form-control">

                <option selected disabled>Open this select menu</option>
                <option value="Not Active">Not Active</option>

                <option value="Active">Active</option>
            </select>

            <button type="submit">Finalising update!</button>

    </form>

{% endblock %}

And the outcome when i press the Update button is the following:
As you can the form is empty
How to i pull the existing details on my form? Please help.
from django.db import models

# Create your models here.
class TestModel(models.Model):
    Name = models.CharField(max_length=30, blank=True)
    Surname = models.CharField(max_length=30, blank=True)
    Weight = models.CharField(max_length=30, blank=True)
    Height = models.CharField(max_length=30,blank=True)
    Gender = models.CharField(max_length=6, blank=True, null=True)
    Outcome = models.CharField(max_length=30,blank=True)
    Activity = models.CharField(max_length=30, blank=True)

    def __str__(self):
        return self.Name

And this is my updated HTML
<form action="" method="POST">
        {% csrf_token %}

            <input type="text" class="form-control" name="Name" value={{Name}}>

            <input type="text" class="form-control" name="Surname" value={{Surname}}>

            <select name="Gender" class="form-control">
                <option selected disabled>
                    Open this select menu
                </option>
                <option value="Male" value={{Gender}}>Male</option>

                <option value="Female" value={{Gender}}>Female</option>
            </select>

            <input type="text" class="form-control" id="Weight" value={{Weight}} >

            <input type="text" class="form-control" id="Height" value={{Height}} >

            <button type="button" onclick="calculation()">Calculation update</button>

            <input type="text" class="form-control"  name="Outcome" id="Outcome" placeholder="BMI Outcome">

            <select name="Activity_log" class="form-control">

                <option selected disabled>Open this select menu</option>
                <option value="Not Active">Not Active</option>

                <option value="Active">Active</option>
            </select>

            <button type="submit">Finalising update!</button>

    </form>

All my views.py
from django.shortcuts import render, redirect
from . models import TestModel
from . forms import TestForm
from django.http import HttpResponse
import csv

# Create your views here.
def Search(request):
    if request.method == "POST":
        Searching = request.POST['Searching']
        Results_query = TestModel.objects.filter(Name__contains=Searching)
        {'Searching':Searching,
        'Results_query':Results_query}
    return render(request, 'GymApp/Searching.html',
    {'Searching':Searching,
        'Results_query':Results_query})

def DownloadingCSV(request):
        response = HttpResponse(content_type='text/csv')
        response['content-disposition'] = 'attachment; filename=Client_list.csv'

        writer = csv.writer(response)
        Downloading_all = TestModel.objects.all()
        writer.writerow(['Name','Surname',
                        'Weight','Height',
                        'Outcome','Gender',
                        'Activity'])
        for download in Downloading_all:
            writer.writerow([download.Name,
                        download.Surname,
                        download.Weight,
                        download.Height,
                        download.Outcome,
                        download.Gender,
                        download.Activity])
        return response

def Client_Delete(request, Client_id):
    ClientUpdate = TestModel.objects.get(pk=Client_id)
    ClientUpdate.delete()
    return redirect('Home')

def Client_Update(request, Client_id):
    ClientUpdate = TestModel.objects.get(pk=Client_id)
    ClientUpdates = TestForm(request.POST or None, instance=ClientUpdate)
    if request.method == 'POST':
       if ClientUpdates.is_valid():
        ClientUpdates.save()
        return redirect('/Client_Details')
    return render(request, 'GymApp/ClientUpdate.html',
    {'ClientUpdate':ClientUpdate,
    'ClientUpdates':ClientUpdates})

def Client_list(request):
    Clients = TestModel.objects.all()
    return render(request, 'GymApp/ClientList.html',
    {'Clients':Clients})

def Client_Details(request, Client_id):
    ClientDetails = TestModel.objects.get(pk=Client_id)
    return render(request, 'GymApp/ClientDetails.html',
    {'ClientDetails':ClientDetails})

def Home(request):
    Forms = TestForm
    if request.method == 'POST':
        Forms = TestForm(request.POST or None)
        if Forms.is_valid():
            Forms.save()
            return redirect('Client_list')
    return render(request, 'GymApp/Home.html',{})

A: ### You have not given value
 <input type="text" class="form-control"
             name="Name" value={{ClientUpdates.Name}} placeholder="Client's Name">

###{{Name}} --> your model field name


text:
Q: why doesn't work docker-compose build ? why he failed show error? => ERROR [video-chat-chat2 internal] load metadata for docker.io/library/node:8.6                                                                          31.3s

[video-chat-chat2 internal] load metadata for docker.io/library/node:8.6:

failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to create LLB definition: failed to do request: Head "https://registry-1.docker.io/v2/library/node/manifests/8.6": proxyconnect tcp: dial tcp: lookup http.docker.internal on 192.168.65.5:53: read udp 192.168.65.4:34041->192.168.65.5:53: i/o timeout


text:
Q: Binary mask from tf.nn.top_k indices for 4-D tensor in Tensorflow? I have a 4-D tensor of shape (10, 32, 32, 128). I want to generate a binary mask for all top N elements.
arr = tf.random_normal(shape=(10, 32, 32, 128))
values, indices = tf.nn.top_k(arr, N=64)

My question is how to get a binary mask of same shape as arr using the indices returned by tf.nn.top_k

A: If someone is looking for the answer: here it goes.
K = 64
arr = tf.random_normal(shape=(10, 32, 32, 128))
values, indices = tf.nn.top_k(arr, k=K, sorted=False)

temp_indices = tf.meshgrid(*[tf.range(d) for d in (tf.unstack(
       tf.shape(arr)[:(arr.get_shape().ndims - 1)]) + [K])], indexing='ij')
temp_indices = tf.stack(temp_indices[:-1] + [indices], axis=-1)
full_indices = tf.reshape(temp_indices, [-1, arr.get_shape().ndims])
values = tf.reshape(values, [-1])

mask_st = tf.SparseTensor(indices=tf.cast(
      full_indices, dtype=tf.int64), values=tf.ones_like(values), dense_shape=arr.shape)
mask = tf.sparse_tensor_to_dense(tf.sparse_reorder(mask_st))


text:
Q: Android-Java detect when the Output-Stream has finished to write the bytes My code is working fine, I just want to show some toast when the writing the bytes are completed. I know I can add toast when I'm  done with reading the file after while loop in.read(buf) == 0, so the while-loop is finished. I can show toast after while, or after closing your streams. When I add toast at the end of the while loop, the files did not show exactly the same time as the toast is shown. It show itself after a few minutes. How would I know writing the bytes are completed or the close() tell its finished?
File newfile;
FileInputStream in = new FileInputStream(new File(path));
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File dir = new File(root + "/" + "Pictures");
if (!dir.exists()) {
    dir.mkdirs();
}
newfile = new File(dir, "status_" + System.currentTimeMillis() + ".mp4");
if (newfile.exists()) newfile.delete();
OutputStream out = new FileOutputStream(newfile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
    out.write(buf, 0, len);
}
in.close();
out.close();

A: Their is no way to track down the OutputStream has finished to write the bytes, just you can add toast or something after close().


text:
Q: Logo in navbar not properly centered in Internet Explorer I have a navber with a logo being centered using flexbox but in IE it is not properly centered. Does anyone know why this might be?
The dev build is at etc.lukesmedia.com
Thanks!

A: IE doesn't like margin:auto.
You can use IE-specific css rule to remove it:
@media screen and (min-width:0\0) {
   .navbar .content{
      margin:none
   }

}

A: In line 298 of your main.css file, you're using text-align: unset, but IE doesn't seem to like that. Try changing to text-align: left and that should work for everything.
Original
@media screen and (min-width: 700px) {
    .navbar .content {
        text-align: unset;
    }
}

Modified
@media screen and (min-width: 700px) {
    .navbar .content {
        text-align: left;
    }
}

A: I try to visit the site using the IE 11 and Google Chrome browser.
I found that in the IE 11 browser the logo appears a little bit left from the center when the screen is bigger than 700px.
In the Chrome browser, When the screen is bigger than 700px then the logo appears on the left side, and when the screen is smaller than 700px then the logo appears in the center.
So it looks like you want to get similar results in the IE 11 browser.
I try to modify your CSS code to get similar results.
Below is the modified example:
<!doctype html>

<title>demo</title>

Note: I suggest you save the above code to the HTML file and modify the path for the logo and try to run it in the IE 11 browser.
Output in the IE 11:

After testing it with the IE 11 browser you can try to implement it in your original code to fix the issue. Further, you can try to modify the code based on your own requirements.

A: Try using a different browser like chrome or firefox. IE is not good for HTML. Once you get to chrome or firefox in css of the object you should have text-align: center; and top: 50%;


text:
Q: The Jar file ../android-8/android.jar has no source attachment I came across this no source attachment problem when I was debugging the project, but when I run the android program without debugging enabled, the program would run without any trouble.  Even after I attached the jar file manually, it still reported that properties.class could not be found! What should I do with this problem? What is the reason for this? thanks!!!
Daniel

A: In the debug mode your application try to go through all the sources. Some of these sources are come from parts of Android framework system (Android SDK) which has been built. Thus, they come to your system as a built files (there are no source files) and thus, when you try to step through a function from Android framework the system cannot find the sources of this function (but still you have binaries of this function).
To avoid this problem during the debug you can download and attach the sources of Android system or you can use Android Sources plugin (http://code.google.com/p/adt-addons/)


text:
Q: Calculating long expressions using Numpy (coordinate transform)? In Pythons Numpy module, is there a function that can calculate long/advanced math expressions on an array? I heard of the numexp module but want to stay clear of further dependencies.
Better yet, can I limit these expressions to only say the first or second element of the sub arrays within my array, without having to unpack them as separate arrays?
Here is my specific problem. I have an array of arrays containing geographic point coordinates looking like this: [[x1,y1],[x2,y2],[x3,y3],etc...]. What I want is to transform these geocoords to pixel coordinates so they can be drawn on an image. I therefore want to run the following expression/calculation on the first element of each subarray, ie the xs:
((180+X)/360)*screenwidthpixels
And on the second element, ie the ys:
((-90+Y)/180)*-screenheightpixels
These expressions would work in a python for-loop but is too slow, which is why I'm turning to Numpy. I know I can and have tried to just link numpys single math operator functions after each other but still too slow, and besides, to do that I first had to unpack all the xs and ys to separate arrays and repack them together after the calculation making it even slower.
So I guess I'm looking for a more direct Numpy way using less steps to transform my coordinate array using the expressions above. Any ideas?

A: I'm a little confused because I'm not sure exactly what you're saying you already tried, or what the speed condition for success is.
Are you saying you already tried something like the following, but it is too slow?
arr = whatever
arr[:,0] = (arr[:,0] + 180) / (360 * screenwidthpixels)
arr[:,1] = 180 - (arr[:,1] - 90) / (180 * screenheightpixels)

A: I'm not sure what you mean by "having to unpack" to X and Y. Here's how you avoid unpacking (if i understand...)
arr = np.array([ [x1,y1], [x2,y2], [x3,y3] ])
arr.shape
=> (3, 2)
X = arr[:,0]  # fast, creates a view
Y = arr[:,1]  # fast too
((X+180)/360)/screenwidthpixels

Further speed up can be achieved by rewriting/simplifying your expressions.
((X+180)/360)/s       =>  (X+180)/(360*s)
(180-((Y+90)/180))/s  =>  (180/s-1/(2*s)) - y/(180*s)

In the first rewrite, you get 2 traverses of the array, instead of 3, and in the second, the array is only traversed twice, instead of 4 times.

A: import numpy as np
points = np.random.rand(10,2)
translation = np.array([180,-90])
scaling = np.array([1024, -768]) / np.array([360,180])
transformed_points = (points + translation) * scaling

This will do what you are looking for. It relies on numpy broadcasting rules to achieve expressiveness and performance.
But rather than explaining exactly how that works, I think you are better off finding yourself a good numpy primer, and starting at the top. numpy is one of the best things about python, and you cant go wrong learning a little more about it. Suffice to say, numpy is certainly up to the kind of task you are facing.

A: In [235]: xs=arange(1000)

In [236]: ys=arange(1, 1001)

In [237]: a=array([xs, ys]).T

In [238]: a
Out[238]:
array([[   0,    1],
       [   1,    2],
       [   2,    3],
       ...,
       [ 997,  998],
       [ 998,  999],
       [ 999, 1000]])

In [240]: a[:, 0]=(a[:, 0]+180)/360/1024

the a[:, 0] offers a view of the first column of a, it's fast and memory saving. docs for numpy here


text:
Q: Error after clicking the 'save the alarm' button I was trying to create a alarm gui using tkinter. I cant update my mainwindow for more than one class object in the list.The problem that i am facing is that after setting the alarm and clicking the save, the alarm object should be seen in the main window [mw()]. This updation is seen only for the first alarm object after that it is not working. The error is only after clicking the save button. But i can assure that the alarm notification [gialarm()] is working on the specific time. Its just my first gui project.
from tkinter import *
import tkinter.font as tkfont
from datetime import datetime
import winsound

pw=[]
al=[]
i=0
alarml=[]

class alarm:
    onof=1
    def __init__(self,ahour,amin,addon,label):
        self.ahour=ahour
        self.amin=amin
        self.addon=addon
        self.label=label

def gialarm(i,alarml):
    def notification(i,alarml):
        if alarml[i].addon==1:
            ampm='PM'
        elif alarml[i].addon==0:
            ampm='AM'
        notify=Tk()
        notify.geometry('400x250')
        time=IntVar()
        ftime=tkfont.Font(size=40)
        nl1=Label(notify,textvariable=time,width=100,font=ftime).pack()
        lab=IntVar()
        flab=tkfont.Font(size=30)
        nl2=Label(notify,textvariable=lab,width=100,font=flab).pack()
        time.set(f'{alarml[i].ahour}:{alarml[i].amin} {ampm}')
        lab.set(alarml[i].label)
        notify.mainloop()

    while alarml:
        if alarml[i].addon==1:
            h=alarml[i].ahour+12
        elif alarml[i].addon==0:
            h=alarml[i].ahour
        if datetime.now().hour==h and datetime.now().minute==alarml[i].amin:
            winsound.Beep(1000,1000)
            notification(i,alarml)
            break

def mw():

Then i tried creating a update function using 'after' function of tkinter. But it only worked for only first object. Then it dont work for the next saved objects.
    def update_mw():
        global i
        if alarml:
            if alarml[i].addon==1:
                ampm='PM'
            elif alarml[i].addon==0:
                ampm='AM'
            pw.append(PanedWindow(orient=VERTICAL,borderwidth=10,bd=10,bg='green'))
            onof=IntVar()
            al.append(Checkbutton(alarmgui,text=f'{alarml[i].ahour}:{alarml[i].amin} {ampm}{alarml[i].label}',variable=onof,onvalue=1,offvalue=0))
            pw[i].pack(fill=X)
            pw[i].add(al[i])
            alarmgui.mainloop()
            if onof.get()==1:
                alarml[i].onof=1
            elif onof.get()==0:
                alarml[i].onof=0
            i+=1
        else:
            alarmgui.after(100,update_mw)
            return None
    def save_alarm(add,ahour,amin,addon,label,alarmgui):
        global alarml
        r=alarm(ahour.get(),amin.get(),addon.get(),label.get())
        alarml.append(r)
        add.destroy()
        ahour.set(None)
        amin.set(None)
        addon.set(None)
        label.set(None)

    def set_alarm(alarmgui):
        add=Toplevel()
        add.geometry('300x400')
        lf1=LabelFrame(add,text='Add your alarm').pack(fill='both',expand='yes')
        l1=Label(add,text='Time:').place(x=10,y=30)

        ahour=IntVar()
        sb1=Spinbox(add,from_=1,to=12,textvariable=ahour,width=5).place(x=140,y=30)
        l2=Label(add,text=':').place(x=190,y=30)
        amin=IntVar()
        sb1=Spinbox(add,from_=0,to=59,textvariable=amin,width=5).place(x=200,y=30)

        addon=IntVar()
        r1=Radiobutton(add,text='AM',variable=addon,value=0).place(x=140,y=60)
        r2=Radiobutton(add,text='PM',variable=addon,value=1).place(x=190,y=60)

        label=StringVar()
        e1=Entry(add,textvariable=label).place(x=130,y=100,width=150)
        l3=Label(add,text='Alarm label:').place(x=10,y=100)
        b2=Button(add,text='Save Alarm',width=30,height=2,command=lambda: save_alarm(add,ahour,amin,addon,label,alarmgui)).pack(side='bottom')
        add.mainloop()

    alarmgui=Tk()
    alarmgui.geometry('500x500')
    b1=Button(alarmgui,text='ADD ALARM',width=30,height=2,command=lambda: set_alarm(alarmgui)).place(x=150,y=450)
    alarmgui.after(1,update_mw)
    alarmgui.mainloop()

mw()

for i in range(len(alarml)):
        if alarml[i].onof:
            gialarm(i,alarml)


text:
Q: Cant send response when in apt.get() body have function with while loop im struggling with this issue for couple of hours, so ive decided to ask You for some help. Here is my nodejs code:
var SSE = require('sse-nodejs');

var express = require('express');

var app = express();

var httpsServer = require('https').createServer();

var fs = require('fs');

app.get('/berskik/sse/notification/:usrDir', function (req,res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    var app = SSE(res);
    var path = "../static/resources/users_files/" + req.params["usrDir"];
    var fileName = "";
    fileName = waitAndReturnUploadedFileName(path);
    sendEvent(app, fileName, res);
});

app.listen(4650, function () {
    console.log('Notification SSE Server has succesfully started at port 4650.');
});

function msleep(n) {
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, n);
}

function readDir(path){
    return fs.readdirSync(path);
}

function sendEvent(app, fileName, res){
    console.log("Sending notification.");
    app.send({"notify": fileName});
    console.log("Notification has been sent.");
}

function waitAndReturnUploadedFileName(path) {
    var newFile = "";
    var breakFlag = false;
    var oldItems = readDir(path);
    while(!breakFlag){
        var items = readDir(path);
        console.log(items.length + "  " + oldItems.length);
        if(items.length > oldItems.length){
            for(var i = 0; i < items.length; i++){
                console.log(!oldItems.includes(items[i]));
                if(!oldItems.includes(items[i])){
                    newFile = items[i];
                    breakFlag = true;
                }
            }
        }
        oldItems = items;
        msleep(1800);
    }
    console.log("New file has been found.");
    return newFile
}

And my problem is that when I comment or delete
fileName = waitAndReturnUploadedFileName(path);

that is actually whole-logic function, app.send() works perfectly, but when i have got this function in my code then nothing is being sent, even if all the other functions (including console.log()) are executing.
I'll appreciate every answer.


text:
Q: Simple cronjob to print time and variable from Linux .bashrc "raise KeyError(key) from None" I have a cronjob to run a Python program, test.py, and save its output to test.log.
Output of sudo crontab -l:
* * * * * python3 /path/to/test.py/ >> /path/to/test.log 2>&1

Contents of test.py:
import os
import datetime
NOW = datetime.datetime.now()
print(NOW)
print(os.environ['some_var_in_bashrc']) # export some_var_in_bashrc="99999"

Contents of ~/.bashrc:
...

export some_var_in_bashrc="99999"

When running from terminal, output is as expected...
$ python3 test.py
2021-02-01 15:49:02.165106
99999

When the cronjob runs I get this in test.log:
2021-02-01 15:49:01.341941
Traceback (most recent call last):
  File "/path/to/test.py/", line 8, in <module>
    print(os.environ['some_var_in_bashrc'])
  File "/usr/lib/python3.6/os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'some_var_in_bashrc'

Why does this happen?
I am on Ubuntu 18.04.

A: The problem is that cron doesn't have access to shell's Env var by default. So try adding your cronjob like this:
* * * * * some_var_in_bashrc="99999" python3 /path/to/test.py/ >> /path/to/test.log 2>&1


text:
Q: Plotting/Visualization in Workbench? I would like to ask a question with Mathematica Workbench.
The workbench is based on Eclipse. Of course, it would have no problem to add breakpoints and debug, but I wonder if it is possible to provide the advanced plotting/visualization as in a Mathematica notebook?
I remember once reading in the Mathematica documentation which said a significant portion of code needs to be rewritten for each platform (Windows, Linux, OS X) for the graphics frontend (i.e., to implement interactive notebooks), and I suspect that it will never be possible to have such support in Eclipse.
So what is the typical workflow when using Workbench? Perhaps it was never intended to provide the level of visualization as a Mathematica notebook, and WRI actually wishes users to

*

*Debug/test individual modules in a Mathematica  notebook, and then
wrap it, exposing certain functions/interfaces like the standard
software engineering procedure.

*Workbench is intended to be organize projects, like Wolfram Alpha, containing dozens or more such complex modules.

A: I do not know where you got the idea that interactive notebooks are platform-specific. This simply isn't true.
The way the Workbench projects work is that you develop packages (.m files) in the Eclipse editor, but you can include notebooks (.nb files) in the project for testing, visualisation, interactive use of the front end or whatever.
So if you want plotting, visualisation or interactive features such as the Manipulate function, you need a notebook file, but you can include these files in a Workbench project and launch the Mathematica front end from the Eclipse-based interface.


text:
Q: UWP c# read XML from StreamSocket I'm trying to communicate with an XMPP (Jabber) server via a TCP network socket (StreamSocket) and I'm using the following code to read what the server has send to me:
StreamSocket tcpSocket;
StreamReader reader;
int BUFFER_SIZE = 4096;

// Connecting to a remote XMPP server ....

reader = new StreamReader(tcpSocket.InputStream.AsStreamForRead());
string result;
while (true)
{
    result = "";
    while (true)
    {
        char[] buffer = new char[BUFFER_SIZE];
        await reader.ReadAsync(buffer, 0, BUFFER_SIZE);
        string data = new string(buffer);

        // Detecting if all elements in the buffer array got replaced => there is more to read
        if (data.IndexOf("\0") >= 0 || reader.EndOfStream)
        {
            result + data.Substring(0, data.IndexOf("\0"));
            break;
        }
        result += data;
    }
    Debug.WriteLine(result);
}

My Code works just fine for strings with a length < 4096 chars, but as soon as the string gets longer than 4096 chars it fails (won't detect the message end). It waits until it receives a new string < 4096 chars, concatenates both strings and returns them as one string.
Is there a way to get the actual length of a string and read them successively?

A: You have set 4096 to the BUFFER_SIZE and it is be set to the count parameter in StreamReader.ReadAsync and the char Array. When the string contain more than 4096 chars, it will fails.
You should be able to get the actual length in the Stream, we can use Stream.Length to get the length of the stream in bytes. The last char of Array is "\0". When you create the char Array, you should be able to set the Stream.Length plus one to the char Array.
For example:
StreamSocket socket;
StreamSocket tcpSocket;
StreamReader reader;

reader = new StreamReader(tcpSocket.InputStream.AsStreamForRead());
var  BUFFER_SIZE=(int)(tcpSocket.InputStream.AsStreamForRead()).Length;
string result;
while (true)
{
    result = "";
    while (true)
    {
        char[] buffer = new char[BUFFER_SIZE+1];
        await reader.ReadAsync(buffer, 0, BUFFER_SIZE);
        string data = new string(buffer);
        if (data.IndexOf("\0") >= 0 || reader.EndOfStream)
        {
            result = data.Substring(0, data.IndexOf("\0"));
            break;
        }
        result += data;
    }
    Debug.WriteLine(result);
}

If you want to reads all characters from the current position to the end of the stream, you can use StreamReader.ReadToEnd or StreamReader.ReadToEndAsync method.

A: I finally figured out to read long messages:
I had to user DataReader and DataWriter instead of StreamReader and StreamWriter.
/// <summary>
/// How many characters should get read at once max.
/// </summary>
private static readonly int BUFFER_SIZE = 4096;

private StreamSocket socket;
private DataReader dataReader;
private DataWriter dataWriter;

public string readNextString() {
    string result = "";
    readingCTS = new CancellationTokenSource();

    try {
        uint readCount = 0;

        // Read the first batch:
        Task < uint > t = dataReader.LoadAsync(BUFFER_SIZE).AsTask();
        t.Wait(readingCTS.Token);
        readCount = t.Result;

        if (dataReader == null) {
            return result;
        }

        while (dataReader.UnconsumedBufferLength > 0) {
            result +=dataReader.ReadString(dataReader.UnconsumedBufferLength);
        }

        // If there is still data left to read, continue until a timeout occurs or a close got requested:
        while (!readingCTS.IsCancellationRequested && readCount >= BUFFER_SIZE) {
            t = dataReader.LoadAsync(BUFFER_SIZE).AsTask();
            t.Wait(100, readingCTS.Token);
            readCount = t.Result;
            while (dataReader.UnconsumedBufferLength > 0) {
                result += dataReader.ReadString(dataReader.UnconsumedBufferLength);
            }
        }
    }
    catch(AggregateException) {}
    catch(NullReferenceException) {}

    return result;
}


text:
Q: How to consider datetime in outlier detection with pandas rolling in Python Considering the following dataframe:
         Temperature     Datetime
1        24.72           2021-01-01 10:00:00
2        25.76           2021-01-01 11:00:00
3        40              2021-01-01 12:00:00
4        25.31           2021-01-01 13:00:00
5        26.21           2021-01-01 14:00:00
6        26.59           2021-01-01 15:00:00
7        26.64           2021-01-01 20:00:00
8        26.38           2021-01-01 21:00:00
9        45              2021-01-01 22:00:00
10       26.23           2021-01-01 23:00:00
...      ...             ...

What we want to achieve is to remove outliers, as for example, in id 3 the temperature is 40 and it is clearly an outlier. We  want to remove the whole row of id 3. We have already read this thread: Outlier detection based on the moving mean in Python.
In the thread it is described, that the outliers can be removed with the following code:
# Import Libraries
import pandas as pd
import numpy as np

# Create DataFrame
df = pd.DataFrame({
    'Temperatura': [24.72, 25.76, 40, 25.31, 26.21, 26.59],
    'Date':[2.3,4.6,7.0,9.3,15.6,17.9]
})

# Set threshold for difference with rolling median
upper_threshold = 1
lower_threshold = -1

# Calculate rolling median
df['rolling_temp'] = df['Temperatura'].rolling(window=3).median()

# Calculate difference
df['diff'] = df['Temperatura'] - df['rolling_temp']

# Flag rows to be dropped as `1`
df['drop_flag'] = np.where((df['diff']>upper_threshold)|(df['diff']<lower_threshold),1,0)

# Drop flagged rows
df = df[df['drop_flag']!=1]
df = df.drop(['rolling_temp', 'rolling_temp', 'diff', 'drop_flag'],axis=1)

But we want to extend it even further, so that the median restarts whenever there is a missing value. So when considering the dataframe we have illustrated, we see an example where values are missing:
         Temperature     Datetime
1        24.72           2021-01-01 10:00:00
2        25.76           2021-01-01 11:00:00
3        40              2021-01-01 12:00:00
4        25.31           2021-01-01 13:00:00
5        26.21           2021-01-01 14:00:00
6        26.59           2021-01-01 15:00:00
7        26.64           2021-01-01 20:00:00 <-- Reset due to missing data between this point and the one before
8        26.38           2021-01-01 21:00:00
9        45              2021-01-01 22:00:00
10       26.23           2021-01-01 23:00:00
...      ...             ...

And what we want is that the code that removes the outliers also considers datetime, so that in id 7, we do notice that the datetime is 5 hours after id 6, and we can therefore conclude that data is missing, and we therefore want to reset the median, as we dont want a rolling median/mean that uses data not relevant in the outlier detection. We might have examples where data is missing for hours or maybe even days, and if the rolling median doesn't consider this, it will provide a bad data cleaning. An ideal threshold for this would be 1 hour, so if row two is not exactly one hour after row 1, then reset the median. Is this possible?

A: In my opinion, you should use the datetime capabilities to compute your moving average. Something like computing the average temperature of the n hours around the given time, then compare your current temperature using a threshold.
Something like:
df['Datetime'] = pd.to_datetime(df['Datetime'])
s = (df
 .rolling('5h', center=True, on='Datetime')
 ['Temperature'].mean()
)

# 10° diff, absolute threshold
df['outlier'] = df['Temperature'].sub(s).abs().gt(10)

df.loc[mask, 'outlier'] = True

# to drop the rows:
# df = df.loc[~mask]

output:
    Temperature            Datetime  outlier
1         24.72 2021-01-01 10:00:00    False
2         25.76 2021-01-01 11:00:00    False
3         40.00 2021-01-01 12:00:00     True
4         25.31 2021-01-01 13:00:00    False
5         26.21 2021-01-01 14:00:00    False
6         26.59 2021-01-01 15:00:00    False
7         26.64 2021-01-01 20:00:00    False
8         26.38 2021-01-01 21:00:00    False
9         45.00 2021-01-01 22:00:00     True
10        26.23 2021-01-01 23:00:00    False


text:
Q: Can my project(react 15) use a dependency that using react 16? Can a project using react 15 depend on a package which is using react 16?
For example:
Project A uses React 16
Project B uses React 15 and Project A, can that work?

A: The simple answer: no. Project A pulls in React 16 as requirement and Project B pulls in React 15 as requirement. You can't load two different react instances, the solution is simple; bump the React dependency of Project B, or make React a peerDependency and support 15 and 16.


text:
Q: Angular 10 upgrade introduces ExperimentalWarning: Conditional exports is an experimental feature error Ever since I upgraded to Angular 10, I have started getting this warning when I run ng serve
(node:22740) ExperimentalWarning: Conditional exports is an experimental feature. This feature could change at any time

My package.json is as follows:
{
  "name": "test-web",
  "version": "1.0.13",
  "scripts": {
    "ng": "ng",
    "start": "node server.js",
    "serve": "ng serve --no-warnings",
    "build": "ng build",
    "postinstall": "ng build --prod --configuration=staging",
    "test": "ng test --configuration=staging",
    "test-headless": "ng test --watch=false --configuration=staging --progress=false",
    "e2e": "ng e2e",
    "cy:run": "cypress run",
    "cy:open": "cypress open",
    "cy:verify": "cypress verify",
    "eslint-check": "eslint './src/app/{modules,shared}/**/*.ts' --max-warnings=0",
    "eslint-fix": "eslint --fix './src/app/{modules,shared}/**/*.ts'",
    "stylelint-fix": "stylelint ./src/{app,environments,assets}/**/*.css --fix",
    "stylelint-check": "stylelint ./src/{app,environments,assets}/**/*.css --formatter verbose",
    "prettier-fix": "prettier --write ./.prettierrc \"{src,cypress}/{app,environments,assets,integration}/**/*{.ts,.js,.json,.css,.scss}\"",
    "prettier-check": "prettier --config --check ./.prettierrc \"{src,cypress}/{app,environments,assets,scss}/**/*{.ts,.js,.json,.css,.scss}\"",
    "check-rules": "npm run prettier-check && npm run eslint-check && npm run stylelint-check"
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm run check-rules",
      "pre-push": "npm run check-rules"
    }
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^10.0.2",
    "@angular/cdk": "^10.0.1",
    "@angular/common": "^10.0.2",
    "@angular/compiler": "^10.0.2",
    "@angular/core": "^10.0.2",
    "@angular/fire": "^6.0.2",
    "@angular/forms": "^10.0.2",
    "@angular/localize": "^10.0.2",
    "@angular/platform-browser": "^10.0.2",
    "@angular/platform-browser-dynamic": "^10.0.2",
    "@angular/platform-server": "^10.0.2",
    "@angular/router": "^10.0.2",
    "@fortawesome/angular-fontawesome": "0.6.1",
    "@fortawesome/fontawesome-svg-core": "1.2.28",
    "@fortawesome/free-brands-svg-icons": "5.13.0",
    "@fortawesome/free-regular-svg-icons": "5.13.0",
    "@fortawesome/free-solid-svg-icons": "5.13.0",
    "@m0t0r/ngx-slider": "^1.0.0",
    "@ng-bootstrap/ng-bootstrap": "^6.1.0",
    "@ngrx/effects": "^9.2.0",
    "@ngrx/router-store": "^9.2.0",
    "@ngrx/store": "^9.2.0",
    "@types/uuid": "^8.0.0",
    "angular-shepherd": "^0.6.0",
    "body-parser": "^1.19.0",
    "bootstrap": "^4.5.0",
    "core-js": "^3.6.5",
    "date-fns": "^2.14.0",
    "express": "^4.17.1",
    "file-saver": "^2.0.2",
    "firebase": "^7.15.5",
    "idb": "5.0.4",
    "jquery": "^3.5.1",
    "ng-recaptcha": "^5.0.0",
    "ngx-color-picker": "^9.1.0",
    "ngx-image-cropper": "^3.1.9",
    "ngx-infinite-scroll": "^9.0.0",
    "ngx-logger": "^4.1.9",
    "ngx-sortablejs": "^3.1.4",
    "ngx-toastr": "^12.1.0",
    "ngx-ui-loader": "^9.1.1",
    "rxjs": "^6.6.0",
    "rxjs-compat": "^6.6.0",
    "sortablejs": "^1.10.2",
    "tslib": "^2.0.0",
    "unsplash-js": "^6.0.0",
    "zone.js": "^0.10.3"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.1000.1",
    "@angular-eslint/eslint-plugin": "0.0.1-alpha.32",
    "@angular/cli": "^10.0.1",
    "@angular/compiler-cli": "^10.0.2",
    "@angular/language-service": "^10.0.2",
    "@rckeller/cypress-unfetch": "^1.0.1",
    "@types/jasmine": "^3.5.11",
    "@types/jasminewd2": "^2.0.8",
    "@types/node": "^14.0.14",
    "@types/stripe-checkout": "^1.0.3",
    "@types/stripe-v3": "^3.1.19",
    "@typescript-eslint/eslint-plugin": "^3.5.0",
    "@typescript-eslint/eslint-plugin-tslint": "^3.5.0",
    "@typescript-eslint/parser": "^3.5.0",
    "chai-colors": "^1.0.1",
    "codelyzer": "^5.2.2",
    "cypress": "^4.9.0",
    "cypress-firebase": "^1.3.0",
    "cypress-plugin-retries": "^1.5.2",
    "eslint": "^7.3.1",
    "eslint-config-prettier": "^6.11.0",
    "eslint-plugin-cypress": "^2.11.1",
    "eslint-plugin-html": "^6.0.2",
    "eslint-plugin-import": "^2.22.0",
    "eslint-plugin-jsdoc": "^27.1.2",
    "eslint-plugin-prettier": "^3.1.4",
    "firebase-tools": "^8.4.3",
    "html-dnd": "^1.2.1",
    "husky": "^4.2.5",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~5.0.2",
    "karma": "^5.1.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "^3.0.3",
    "karma-jasmine": "~3.3.1",
    "karma-jasmine-html-reporter": "^1.5.4",
    "prettier": "2.0.5",
    "protractor": "^7.0.0",
    "puppeteer": "^3.3.0",
    "stylelint": "^13.6.1",
    "stylelint-config-standard": "^20.0.0",
    "ts-node": "~8.10.2",
    "tslint": "^6.1.2",
    "typescript": "^3.9.6",
    "webpack-dev-server": "^3.11.0"
  }
}

How do I get rid of this warning?

A: Use diffrent NodeJS version
% nvm list

       v12.18.3
       v12.18.4
->      v13.9.0
       v14.17.1
       v14.17.3
        v16.5.0

% nvm use 14.17.3
Now using node v14.17.3 (npm v7.20.3)


text:
Q: How to add nodes and relationship into named graph with neo4j? Guys I have created my graph using gds.graph.project command and this command will make my graph in-memory and it's create a named graph for me.
is there any way to add some nodes or relationship into named (in-memory) graph?
thanks for helping!


text:
Q: Delete all lines in file until line with string I'm writting a script for editing a file.txt. I have a string name:
str_name = 'abcd'

My file has a lot of lines. I delete all the lines before str_name, and left in the file line with str_name and all below.

A: file = open(local_filename, "r")
lines = file.readlines()
for line in lines:
    if str_name in line:
        print("Find")
        start = lines.index(line)
        lines = lines[start::1]
        break
    else:
        print("Not found")
file.close()
file = open(local_filename, "wt")
for line in lines:
    file.write(f"{line}")
file.close()

A: To avoid reading all of the file into memory, you can do
with open(local_filename, "r") as f, open(local_filename + ".new", "w") as outf:
    found = False
    for line in f:
        if str_name in line:
            found = True
        if found:
            outf.write(line)

– i.e. keep track whether you've found the line you need, and if you have, begin writing them into another file.
If you want, you can do an os.rename() at the end to replace the new file into place.


text:
Q: How to achieve multi-line strings in C#; an alternative to VB's XML Literals? I had a project in vb.net that used XML Literals to process large blocks of SQL like so:
Dim SQL As String = <a> Use test

alter table BarFoo alter column CouponName nvarchar(328)
alter table Foo alter column IngredientName nvarchar(328)
alter table Bar alter column IngredientShortDescription nvarchar(328)
alter table FooBar alter column ItemName nvarchar(328) </a>.Value

But cant seem to find its equivalent for C#
Any suggestions?

A: You can prefix a string constant with @ to span multiple lines.  The only thing that would need to be escaped is quotes (using the double quote).
string SQL = @"Use test
  alter table BarFoo alter column CouponName nvarchar(328)
  alter table Foo alter column IngredientName nvarchar(328)
  alter table Bar alter column IngredientShortDescription nvarchar(328)
  alter table FooBar alter column ItemName nvarchar(328)";

A: It seems you are trying to mimic the behavior of a verbatim string in C#.  These literals start with a leadin @ before the string to let the compiler to not process character escapes.  The only character escape you need is to escape a " with "" instead.
So your query would look like
string query = @"
Use test

alter table BarFoo alter column CouponName nvarchar(328)
alter table Foo alter column IngredientName nvarchar(328)
alter table Bar alter column IngredientShortDescription nvarchar(328)
alter table FooBar alter column ItemName nvarchar(328)";

This includes the newline characters \n as well as any leading spacing.  In SQL whitespace is just for readability anyway, but it's good to remember that the white space is completely preserved with these literals.

A: First –
Use multiline string literals like
String sql = @"Use test
alter table BarFoo alter column CouponName nvarchar(328)
alter table Foo alter column IngredientName nvarchar(328)
alter table Bar alter column IngredientShortDescription nvarchar(328)
alter table FooBar alter column ItemName nvarchar(328)"

*

*note that all line breaks inside the string and whitespace at the beginning of each line is retained

Second – Let string interpolation work for you if you need any parametrization of string:
String databaseName = "test"
String tableName = "BarFoo"

String sql = @"Use \{databaseName}
alter table \{tablaName} alter column CouponName nvarchar(328)"

*

*no more puzzles like String.Format("Use {0}; alter table {1}", databaseName, tableName)

Third –
Visual Basic already has multiline string literals, too. No more XML workarounds please.
In VB, use
Dim sql As String = "Use test

alter table BarFoo alter column CouponName nvarchar(328)
alter table Foo alter column IngredientName nvarchar(328)
alter table Bar alter column IngredientShortDescription nvarchar(328)
alter table FooBar alter column ItemName nvarchar(328)"

'and with interpolated strings:
Dim when As String = "since Visual Studio 2015"
Dim note As String = $"String interpolation works {when}, see this VB-specific syntax!"


text:
Q: VBA: How to click a drop down in a web page with the help of HREF and CLASS HTML tag avilable I am trying to automate one of my website working on a secured server, the code which help me to log into the web page but after that I have to click a dropdown from a menu bar where the HTML tag available is CLASS and HREF only.
HTML

Logs

A part of my VBA code is
Dim MyHTML_Element as IHTMLElement
Set HTMLDoc = MyBrowser.document

For Each MyHTML_Element In HTMLDoc.getElementsByClassName ("childmenu")
If MyHTML_Element.href = "./1713363899/ViewLogsPage" Then MyHTML_Element.Click:
Exit For
Next

but this code not working and Skip after executing this line ".....ClassName ("childmenu")" and jump to END sub, when i run my code in Debug mode.

A: Try
If Instr(MyHTML_Element.href, "1713363899/ViewLogsPage") Then MyHTML_Element.Click

If not works, add debug.print MyHTML_Element.href before line with If. It is possible that link is generated while page is being download.

A: Use a CSS selector of .childmenu[href='./1713363899/ViewLogsPage']. Which reads as the elements with classname childmenu having attribute href with value './1713363899/ViewLogsPage'

CSS selector in action:

VBA:
You apply the CSS selector with the .querySelector method of the .document
MyBrowser.document.querySelector(".childmenu[href='./1713363899/ViewLogsPage']").Click

Info on:

*

*CSS selectors

*.querySelector method
Bonus track:
Feast on CSS selectors to home your CSS ninja skills - I have no affiliation with this. Found it today and it was fun.
Or try the tester via this: CSS Selector Reference


text:
Q: Blobstore Python API Download URL using Django HTML template I'm creating a dropbox service using BlobStore, however I can't find a good way to implement the file download option from my Django HTML template.
Here is my app.yaml
application: my_application
version: 1
runtime: python27
api_version: 1
threadsafe: false

handlers:
- url: /favicon\.ico
  static_files: favicon.ico
  upload: /favicon\.ico

- url: (/.*)*
  script: main.app

libraries:
- name: django
  version: latest

Here is the main.py
#!/usr/bin/env python
from django.core.management import setup_environ
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext import blobstore
from google.appengine.ext.blobstore import BlobInfo
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
import django
import webapp2
import wsgiref.handlers

class UserUpload(db.Model):
    blob_key =      blobstore.BlobReferenceProperty(required=True)
    user =          db.UserProperty(required=True)
    user_id =       db.StringProperty(required=True)
    creation =      db.DateTimeProperty(required=True, auto_now_add=True)
    filename =      db.StringProperty()
    content_type =  db.StringProperty()
    size =          db.IntegerProperty()
    MD5 =           db.StringProperty()

# Start Dumpbox login
class MainPage(webapp2.RequestHandler):
    @util.login_required
    def get(self):
        logout_url = users.create_logout_url('/')
        upload_url = blobstore.create_upload_url('/upload')
        user = users.get_current_user()
        q = UserUpload.all()
        q.filter('user_id =', users.get_current_user().user_id())
        q.order('-creation')
        if user:
            html = template.render('templates/header.html', {'title': 'Dumpbox', 'nickname': user.nickname(), 'url': upload_url})
            html = html + template.render('templates/table.html', { 'file_name': 'File Name',
                                                                    'content_type': 'Content Type',
                                                                    'size': 'Size',
                                                                    'timestamp': 'Creation Date',
                                                                    'q': q
                                                                    })
            html = html + template.render('templates/footer.html', {'logout_link': logout_url})
            self.response.out.write(html)
        else:
            self.redirect(users.create_login_url(self.request.uri))

class LogoutHandler(webapp2.RequestHandler):
    def get(self):
        self.auth.unset_session()
        self.redirect(self.uri_for('home'))

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
        blob_info = upload_files[0]
        user_upload = UserUpload(   user=users.get_current_user(),
                                    user_id=users.get_current_user().user_id(),
                                    blob_key=blob_info.key(),
                                    filename=blob_info.filename,
                                    content_type=blob_info.content_type,
                                    size=blob_info.size,
                                    creation=blob_info.creation,
                                    MD5=blob_info.md5_hash
                                    )
        db.put(user_upload)
        self.redirect('/')

class DownloadHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        resource = str(urllib.unquote(resource))
        blob_info = blobstore.BlobInfo.get(resource)
        self.send_blob(blob_info)

app = webapp2.WSGIApplication([('/', MainPage),('/upload', UploadHandler),('/download([^/]+)?', DownloadHandler)],debug=True)
wsgiref.handlers.CGIHandler().run(app)

def main():
    run_wsgi_app(app)

if __name__ == '__main__':
    main()

The Django template uses a table with a checkbox to select file to be downloaded, but I can't find a good way to implement it.
How can tick the checkbox and submit a form to download a blobstore file?
<form method="GET" action="">

                <input type="checkbox"  onclick="checkAll(this)"/>
                {{file_name}}
                {{content_type}}
                {{size}}
                {{timestamp}}

                {% for file in q %}
                {% if file.size > 0 %}

                    <input id="{{file.blob_key}}" type="checkbox"/>
                    {{file.filename}}
                    {{file.content_type}}
                    {{file.size}} Bytes
                    {{file.creation}}

                {% endif %}
                {% endfor %}

<input type="submit" value="Download">

</form>

Appreciate any help.

A: Here's my solution:
In your template change to line
{{file.filename}}

into
{{file.filename}}

In your views add two method:
def download(request,client):
    if 'key' in request.GET:
        blob_key_str = request.GET['key']
    if not blob_key_str:
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

    blob_key = str(urllib.unquote(blob_key_str))
    blob = blobstore.BlobInfo.get(blob_key)

    try:
        return send_blob(blob, save_as=True)
    except ValueError, error:
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

and
import cgi
import logging
import urllib
def send_blob(blob_key_or_info, content_type=None, save_as=None):

    CONTENT_DISPOSITION_FORMAT = 'attachment; filename="%s"'
    if isinstance(blob_key_or_info, blobstore.BlobInfo):
      blob_key = blob_key_or_info.key()
      blob_info = blob_key_or_info
    else:
      blob_key = blob_key_or_info
      blob_info = None

    logging.debug(blob_info)
    response = HttpResponse()
    response[blobstore.BLOB_KEY_HEADER] = str(blob_key)

    if content_type:
      if isinstance(content_type, unicode):
        content_type = content_type.encode('utf-8')
        response['Content-Type'] = content_type
      else:
        del response['Content-Type']

    def send_attachment(filename):
      if isinstance(filename, unicode):
        filename = filename.encode('utf-8')
        response['Content-Disposition'] = (CONTENT_DISPOSITION_FORMAT % filename)

    if save_as:
      if isinstance(save_as, basestring):
        send_attachment(save_as)
      elif blob_info and save_as is True:
        send_attachment(blob_info.filename)
      else:
        if not blob_info:
          raise ValueError('The specified file is not found.')
        else:
          raise ValueError(
              'Unexpected value for the name in which file is '
              'expected to be downloaded')

    return response

Change this code according to your needs :)


text:
Q: windows form app sending strings I made a tcp/ip chat windows form application and it works just fine but I want to make the application to send the text automatically I don't want the user to click the send button like a live streaming!
and I am using Asynchronous connection.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;

namespace Chat
{
    public partial class Form1 : Form
    {
        Socket sck;
        EndPoint epLocal, epRemote;

        public Form1()
        {
            InitializeComponent();

            sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            textBox1.Text = GetLocalIP();//this is where the application is running IP address
            //textBox5.Text = GetLocalIP();
        }

        private string GetLocalIP()
        {
            IPHostEntry host;
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if(ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }

            return "127.0.0.1"; //here we put the android device's IP

        }

        private void MessageCallBack(IAsyncResult aResult)
        {
            try {

                int size = sck.EndReceiveFrom(aResult, ref epRemote);

                if(size>0)
                {
                    byte[] receivedData = new byte[1464];
                    receivedData = (byte[])aResult.AsyncState;

                    ASCIIEncoding eEncoding = new ASCIIEncoding();
                    string receivedMessage = eEncoding.GetString(receivedData);
                    //b3deen bntba3 el msg bs b7aletna bdna n5li el touch active.
                    listBox1.Items.Add("Sender:" + receivedMessage);
                }

                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);

            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

                try
                {
                    //binding the message
                    epLocal = new IPEndPoint(IPAddress.Parse("192.168.1.9"), Convert.ToInt32("80"));
                    sck.Bind(epLocal);
                    //hoon el address ta3 el mobile
                    epRemote = new IPEndPoint(IPAddress.Parse("192.168.1.9"), Convert.ToInt32("81"));//texbox5 bn7at el ip ta3 el android wl txt el tani ta3 le port
                    //hoon bn3ml connect network
                    sck.Connect(epRemote);

                    byte[] buffer = new byte[1500];
                    sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);

                    button1.Text = "Connected";
                    button1.Enabled = false;
                    button2.Enabled = true;
                    textBox3.Focus();

                    //trying to live sending

                }

                catch (Exception exp)
                {
                    MessageBox.Show(exp.ToString());
                }

        }
       private void button2_Click(object sender, EventArgs e)
        {
          try
            {
                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                byte[] msg = new byte[1500];
                msg = enc.GetBytes(textBox3.Text);

                sck.Send(msg);
                listBox1.Items.Add("YOU:" + textBox3.Text);

            }catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
           // Close();

        }
    }
}

A: I assume that you want to send the text the user entered as he finished to type it. Even if I'd say this is a bad idea because it will confuse your users, you could add a timer which is counting the time since the user's last key stroke and if a given time was passed (let's say 5 secs), it invokes the method your button click is invoking as well to send the string.

A: Hey all I just find out what to do I wanted to send each string when its written so what i did I just handled the event for the textbox it self so when ever its changed it will send it right away :D good luck all :)


text:
Q: Add view as a parameter to a custom ViewModifier This is more of a syntactic question. I am trying to pass a view into a ViewModifier initialiser without using AnyView.
Currently I have something running using AnyView, but I would like to use the generic view syntax as you would then passing a "some view" to a view outlined in this answer here:
How to pass one SwiftUI View as a variable to another View struct
I cant seem to get it working with a ViewModifier.
The intention (as shown in the sample) is for the modifier to pass in a computed value into the innerView. I would also be happy with using @ViewBuilder somehow to specify the innerView property as this would probably have the same effect.
Here is the sample modifier:
struct SampleModifier: ViewModifier {

    let param1: CGFloat
    let innerView:  (CGFloat, CGFloat) -> AnyView

    // Assume these are calculated states
    let calculatedParam1: CGFloat = 100
    let calculatedParam2: CGFloat = 100

    func body(content: Content) -> some View {
        ZStack {
            HStack {
                Spacer()

                innerView(self.calculatedParam1, self.calculatedParam2)
                    .padding(.leading, 10)
                    .frame(width: param1)
            }

            content.frame(width: 100, height: 100)
        }

    }
}

And its use:
struct SampleView: View {
    var body: some View {
        Rectangle()
            .modifier(SampleModifier(param1: 150, innerView: { param1, param2 in
                return AnyView(
                    Text("Inner View: \(param1) - \(param2)")
                )
            }))
    }
}

A: You can use generics, i.e., make innerView returning some view:
struct SampleModifier<V>: ViewModifier where V: View {
    let param1: CGFloat
    let innerView: (CGFloat, CGFloat) -> V

    ...
}

Then you don't need AnyView anymore:
struct SampleView: View {
    var body: some View {
        Rectangle()
            .modifier(SampleModifier(param1: 150, innerView: { param1, param2 in
                Text("Inner View: \(param1) - \(param2)")
            }))
    }
}

Alternatively, you can create a View extension:
extension View {
    func sampleModifier<V>(
        param1: CGFloat,
        innerView: @escaping (CGFloat, CGFloat) -> V
    ) -> some View where V: View {
        modifier(SampleModifier(param1: param1, innerView: innerView))
    }
}

and use it like this:
struct SampleView: View {
    var body: some View {
        Rectangle()
            .sampleModifier(param1: 150, innerView: { param1, param2 in
                Text("Inner View: \(param1) - \(param2)")
            })
    }
}


text:
Q: Connecting with Win 2008r2 to Mac OS Our main server in the operations of one of my clients in on a IMac Pro (Mac Mojave) We run a specific financial program on said machine.
A new version of the financial program is getting ready for testing on our systems. It is not OS dependent. We have 2 test Win Machines, one standalone and one virtual (Using VMware) on the Mac . They run 2008 server R2. No matter what I can do I cannot get the Win machines to see the Mac. The Mac sees the Win machines fine and can access anything I want on them, but the reverse is not true. One of our Win 10 laptops has no issue with see back and forth to the Mac machine.
What gives and any suggestions of how to get the Win 2008 machies to see and access the Mac?
Thanks for your help.
Tom in Dallas/Plano

A: The Server 2008 machine is running SMBv1 which is the main cause of connection issues with newer machines not using SMBv1 (SMBv2 or greater instead).
Server 2008 SMB version
Server 2008 is well out of support and no upgrades for it.
There is a registry key to check version, but I do not see any way to upgrade the SMB version.
I do not recommend it but you can consider downgrading SMB on newer machines. This is a security risk and I do not recommend it.
You could consider a good strong Windows 10 machine as a "Server" for testing purposes.


text:
Q: Not following what's happening with the exponents in this proof by mathematical induction. I'm not understanding what's happening in this proof. I understand induction, but not why $2^{k+1}=2*2^{k}$, and how that then equals $k^{2}+k^{2}$. Actually, I really don't follow any of the induction step - what's going on with that algebra? Thanks!
Let $P(n)$ be the statement
$2^n > n^2$, if $n$ is an integer greater than 4.
Basis step:
$~~~~~P(5)$ is true because $2^5 = 32 > 5^2 = 25$
Inductive step:
$~~~~~~$Assume that $P(k)$ is true, i.e. $2^k > k^2$.
We have to prove that $P(k+1)$ is true. Now
$$\begin{aligned}
2^{k+1} & = 2 \cdot 2^k\\
& > 2 \cdot k^2\\
& = k^2 + k^2\\
& > k^2 + 4k\\
& \geq k^2 +2k+1\\
& = (k+1)^2
\end{aligned}$$
$~~~~~$ because $k>4$
$~~~~~$ Therfore $P(k+1)$ is true
Hence from the principle of mathematical induction the given statement is true.

A: Perhaps writing shortly a justification for each step can help. Let us denote
$$\begin{align*}&2^k>k^2=\color{red}{I.H.} =\text{ Inductive Hypothesis. This is what you assume after showing for k = 5}\\&k^2=k\cdot k>4k=\color{blue}{B.A.}=\text{Basic Assumption. From here we start}\\&4k\ge 2k+1=\color{green}{S.A.}=\text{Simple Algebra:}\;\;4k\ge 2k+1\Longleftrightarrow 2k\ge 1\end{align*}$$
So now your proof can look as follows:
$$2^{k+1}\stackrel{\text{exponents law}}=2\cdot 2^k\stackrel{\color{red}{I.H.}}>2\cdot k^2=k^2+k^2\stackrel{\color{blue}{B.A.}}>k^2+4k\stackrel{\color{green}{S.A.}}\ge k^2+2k+1=(k+1)^2$$

A: I have copied the induction step table format from your question and will reformat it as I had to do in my high school geometry class. I find it very helpful to get away from the table as you gave it.
Set $P(n)$ equal to the statement that 2^n>n^2 for all n>4. Note the basis step 2^4>4^2 is true.
$~~~~~~$Assume that $P(k)$ is true, i.e. $2^k > k^2$.
We have to prove that $P(k+1)$ is true. Now
\begin{array}[10,2]{}
STATEMENT & REASON \\
2^{k+1}  = 2 \cdot 2^k & \text{Induction step  of  the  definition  of }2^n \\
2^k > k^2  & \text{This is the induction hypothesis.} \\
2 \cdot 2^k > 2 \cdot k^2= k^2 + k^2 & \text{Multiplying by a positive number preserves inequalities} \\ & \text{ and the distributive law.} \\
k^2 + k^2 > k^2 + 4k & k>4\text{ by hypothesis, so } k^2 >4k \text{ and then } k^2 + 4k > k^2 + 2k +2\\ & \text{and the standard rules of inequalities used above apply.} \\
k^2 + 4k \geq k^2 +2k+1 & 4k > 2k+1 \text{ since  }2k-1>0 \\
k^2 +4k +1 =(k+1)^2 & \text{Multiplication distributes over addition.} \\
\end{array}
$~~~~~~$
This shows $P(k)\implies P(k+1)$, and the principle of finite induction completes the proof that $P(n)$ is true for all $n>4$ .

A: You ask two questions:
(1) By definition, $$2^{k+1} = \underbrace{2 \quad \textrm{...} \quad 2}_{\textrm{ (k+1 times)}} = 2 \cdot \underbrace{2 \quad \textrm{...} \quad 2}_{\textrm{ (k times)}} = 2 \cdot 2^k.$$ As others have pointed, it's the usual rule to calculate an exponential: $a^x \cdot a^y = a^{x+y}$.
(2) The step immediately before $k^2 + k^2$ is that it equal $2k^2$. I assume that is clear (?) - you obviously always have $2a = a+a$. These two are equal; they are not equal to $2 \cdot 2^k$ (as you write, but probably don't mean). So I assume you ask why is the step before true, the one going $2 \cdot 2^k > 2 \cdot k^2$. This is using the induction assumption, assumed to be true for $k$ (as you write yourself earlier in "Let P(n) be the statement..."): if $2^k > k^2$, then obviously also $2 \cdot 2^k > 2 \cdot k^2$

A: The arithmetic has already been explained, but not the intuition motivating the induction. We desire to prove by induction that the function $\rm\ \color{#C00}{2^n - n^2 =\, f(n)}\,$ is positive for $\rm\:n \ge 5.\:$ Notice
$$\begin{eqnarray}\rm f(n\!+\!1) &=&\rm\ 2\cdot \color{#C00}{2^n} - (n\!+\!1)^2 =\, 2\,(\color{#C00}{f(n)+n^2})-(n\!+\!1)^2\\
\rm \Rightarrow\ \ f(n\!+\!1) &=&\rm\ 2\: f(n) + (n\!-\!1)^2\! - 2\end{eqnarray}$$
Now the induction step is clear: $\rm\ f(n)> 0\,\Rightarrow\, f(n\!+\!1) > 0\,$ since $\rm\,f(n\!+\!1)\,$ is a sum of terms $\,> 0,$ namely, the first rhs summand $\rm\,2\,f(n)>0\:$ since $\rm\:f(n)>0\:$ by the induction hypothesis; $ $ further, the second rhs summand $\rm\:(n\!-\!1)^2\!-2 > 0\:$ for $\rm\:n \ge 3\ $ (by $\rm\,x^2\,$ is increasing, or by induction).
More generally one can easily prove by induction that if a function on $\,\Bbb N\,$ satisfies a recurrence of the form $\rm\: f(n\!+\!1) =\, a(n)\, f(n) + b(n)\:$ and $\rm\,f(n_0)> 0\:$ then $\rm\,f\,$ remains positive for all $\rm\:n \ge n_0,\:$ assuming that both $\rm\:a(n)>0\,$ and $\rm\,b(n) > 0$ for $\rm\:n > n_0.\:$ It's really nothing more than the obvious induction that an increasing function stays larger than its initial value, which amount essentially to iterating the transitivity law for inequalities $\rm\:f_{n+1} > f_n > \cdots > f_{0}\:\Rightarrow\: f_{n+1} > f_{0}.$
Many induction proofs can be cast in this form. For example, products and exponentials of polynomials satisfy such recurrences. The method often succeeds because it replaces hairy exponential arithmetic by much simpler polynomial arithmetic (verifying positivity of the polynomials $\rm\:a(n),b(n),\:$ which requires no insight since there is a simple algorithm).
This is a simple generalization of telescopy - about which much has been written here.


text:
Q: Creative IP/subnet/dns schemes I've only administered rather small networks (<=25 nodes). Usually I put the gateway .1, dns/proxy as .10, mail at .20, printers at .30-39 and so on and so forth. I never directly use IP addresses as DNS hostnames are clearly the better way, but I like to have a clear pattern/layout/design when building a network from scratch.
My DNS mapping also has a simple naming pattern/layout as well. For example, all of my devices have two names; one formal name based on role (dc01, mail02, etc.) and an informal name. Nothing fancy, but real simple and manageable.
I'm trying to figure out a more intuitive/creative IP/Subnet/DNS scheme (if there is something better). I'm sure others have more intuitive schemes depending on the network objectives and such. My network that I'm working on is still small, but I have numerous devices  to contend with.
I'm looking for a general pattern or methodology to assign IP address (ranges/classes), dns names and subnet networks that encompasses 4-5 major points:

*

*Network services (mail, file, proxy, etc.)

*Software development (environments - dev/staging/prod,

*Media (streaming, large file transfers, archiving)

*Virtual servers/desktops

*VoIP

I've never worked directly with VoIP but it's something to take into consideration for the future.

Overall I got some really good ideas from everyone. Wish I could give out more votes/accepted answers. Thanks for the responses!

A: Keep it simple. As simple as possible, but still allowing for security and flexibility. Design abstraction into things, which sounds like it's not simple, but in fact is the pathway to simplicity itself.
As for subnets, this is fairly common:

*

*Users on one subnet

*Guests on another

*Servers on their own subnet

*VOIP on its own too.

Filter traffic through each subnet as necessary. Possibly use VLANs. I hope you are intimately familiar with the CLI of your network device vendor of choice.
As for DNS, you're not going to like this but... use whatever works for you. Personally, I like to give servers a totally abstract hostname with no ties to its services. I then CNAME services to the hostname. That way migrating services don't cause DNS change headaches. Or at least, not as many. I also prefer to name virtual servers with a v prepended to the hostname.
Examples:

*

*New Database server is named Athena. It will be named Athena forever.

*Athena is CNAMED for what it does: SQL08ENT-CRM, SQL08ENT-AEGIS (the security system), SQL08ENT-DOCMAN. Perhaps also CNAMED based on geography. Or perhaps the hostname will have geography in it. Athena-ATL. Athena-Sydney. Whatever works.

*The server is on the server subnet that has a default deny policy. It has the proper traffic included to it from the proper subnets.

Keep. It. Simple. (but functional)

A: I worked at an organisation of a similar size (we had a /26), that for reasons beyond me, the powers-that-be felt that a finely grained IP allocation scheme was paramount to operational integrity. The gateway had to be .1, the printers had to be between .2 and .12, the servers between .13 and .20 and so on. We even kept documentation on individual hosts.
This is a huge pain in the ass. No matter how diligent I was I could never seem to keep any documentation current. It didn't help that we did not have any DNS services, so using this IP allocation scheme documentation was the only "naming" services we had (which in a strange way, made it seem more indispensable than it really was).
For a network of your size I would recommend a few things (most of which you have already done):

*

*Simple - You're not managing hundreds of hosts. The complexity of your solution should reflect the complexity of environment. Resist the temptation to be overly clever. You will thank yourself later.

*

*Take your available IP space and give 60% to your clients via DHCP.    Setup up some kind Dynamic DNS services so you never have to look at    a damn IP address again. Forget about keeping track of them. Profit.

*Reserve the other 30% for IP addresses you manage: servers, printers, network devices, testing services. etc. USE DNS TO DOCUMENT THIS. In my opinion, there is no bigger waste of time than studiously keeping track of all these "administrator-managed" IP addresses (as opposed to DHCP managed IP addresses) by using an Excel spreadsheet (which you have to constantly refer to and maintain), when you could be putting that effort into supporting a self documenting and far more useful DNS solution.

*Keep the last 10% of your address at the top of your IP addressing space unused. A little reserve never hurts.

*Adjust the ratios as you see fit for your environment. Some    environments will have more clients, some will be "server" (i.e., "administrator-managed") heavy.

*

*Network services (mail, file, proxy, etc.)

*Software development (environments - dev/staging/prod,

These both fall into the category of "administrator-managed" IP space.

*

*Media (streaming, large file transfers, archiving)

In my opinion this has little to do with subnetting and everything to do with network monitoring.

*

*Virtual servers/desktops

Servers are "administrator-managed", desktops (i.e. client machines) should be "DHCP-managed".

*

*VoIP

A physically discrete network would be ideal... but that's unrealistic. The next best thing would be a separate VLAN and subnet. This is about the only point in small network where I'd really feel the need to segregate traffic (except for things that are publically accessible).

A: For IP allocations
My advice is to place everything under the 10.0.0.0/8 subnet, using the following structure: 10.site.division.device

*

*site is a physical location or logical equivalent (e.g. NY office, NJ office, DR facility, Development
environment).

*division is a logical subdivision that makes sense to you. e.g.
0 => Switches/Routers
1 => Admins, 2 => Users
3 => VOIP
4=> Guests

*devices are individual devices (PCs, servers, phones, switches, etc.)

The idea here is that you can easily determine what a device is and where it is by its address: 10.2.1.100 is an administrator's workstation at "Site #2".
This model is derived from class-based IP assignments: the Class A (/8) is your enterprise. Each location gets a Class B (/16), and each logical division at a location gets a Class C (/24) for their devices.
It is possible (and sometimes desirable) to use something larger than a /24 for the "division" level, and you can certainly do so: Anything from a /17 to a /24 is generally fair game with this scheme.

For DNS Names
My advice is to follow a similar scheme to the IP assignment I described above:

*

*Everything is rooted at mycompany.com

*Each site (/16) has its own sitename.mycompany.com subdomain.

*Logical divisions may have one (or more) subdomains within the site, for example:

*

*voip.mycompany.com (with devices like tel0000.voip.mycompany.com, tel0001.voip.mycompany.com, etc.)

*switches.mycompany.com

*workstations.mycompany.com (possibly subdivided further into admin, user & guest)

*Devices should have meaningful names.  For example:

*

*Name phones so that you can see the extension they ring based on the DNS name.

*Name workstations based on their primary user.

*Clearly identify "guest" IP addresses.

*Name servers so that you can tell what they are / what they do.
This can be accomplished by using "boring" names (www01, www02, db01, db02, mail, etc.) or by promulgating a naming scheme and sticking to it (for example: Mail servers are named after rocks, web servers are named after trees, database servers are named after painters).
Boring names are easier for a new person to learn, cool naming schemes are more fun.  Take your pick.

Misc Notes
Regarding virtual servers:
Consider these the same as if they were physical machines (segregate them by division/purpose rather than by the fact that they're "virtual".  Have a separate division for the Hypervisor/VM Administration network.
It may seem important to you now to know if a box is virtual or physical, but when your monitoring system says "Hey, Email is down!" the question you'll be asking is "Which machines are related to email?", not "Which machines are virtual and which are physical?".
Note that you DO need a practical way of identifying whether a machine is virtual or physical in case a hypervisor host blows up, but this is a challenge for your monitoring system, not your network architecture.
Regarding VOIP:
VOIP (asterisk in particular) is a synonym for "Security Hole".  Shove all your VOIP stuff off onto its own subnet, and its own VLAN, and don't let it near anything sensitive.
Every VOIP phone I've seen in the last year supports VLAN segregation (in fact they all support both voice and data VLANs, so you can still use the phone as a pass-thru for desktop ethernet connections).  Take advantage of this - You will be glad you did if/when your VOIP environment gets hacked.
Regarding Planning and Documentation:
Draw your network on paper before you start assigning addresses and DNS names.  In fact, draw it in pencil on a BIG sheet of paper first.
Make lots of mistakes.
Erase liberally.
Curse fluently.
Once you stop cursing and erasing for at least 10 days it's time to put the diagram into Visio/Graffle/Some other electronic format as your official network diagram.  Safeguard this diagram.  Maintain it in its Most Holy Correctness as you add and remove devices, grow your organization, and modify your network structure.
This network diagram will be your best friend when you have to make changes, explain the network to new admins, or troubleshoot a mysterious failure.


text:
Q: issues with min one in Protege I have a homework to do for my studies that requires to use Protégé.
I am pretty new with the language OWL and with this software.
We need to create an ontology on hiking trails.
I have multiple classes like Hikers, Trails, Restaurants, Hotels, Equipements, and Places.
This last class (Places) has 2 subclasses: StartEndPoint and PicnicArea.
The class StartEndPoint correspond to the places where a trails start and end. So for my Trails class I have the axiome: (startingPoint exactly 1 Places) and (endingPoint exactly 1 Places) to symbolise that a trail starts and end at exactly one starting and ending point.
Similarly, i would like to create the axiom: each starting and ending place has at least one restaurant near this point.
To do so, i have added the axiom: "eatingPlace min 1 Restaurants" in the class StartEndPoint.
But when I run the reasoner, it says no error. I did create some instances from all classes but for the instances from the class StartEndPoint, it should say that there is no restaurant as I didn't add any property "eatingPlace" to those instances (see screenshots below).
I wanted to try if the minimum one were working well and so it should have returned me an error i guess. But I got nothing.
Is it normal ? If yes why ?
And if no, how could I resolve this ?
thanks a lot for your help

A: The reasoner is not finding any errors because of the Open World Assumption. You are stating that each endpoint has at least one restaurant near it, but this does not place any obligation on the ontology to list which restaurant is near to your endpoints - i.e., if you ask the reasoner if there is a restaurant near endpoint X, the reasoner will say yes; but, if you ask it to list the restaurants near endpoint X, the list might be empty because the information is not included in the ontology. This is expected behaviour for OWL ontologies.


text:
Q: What is the difference between lm(offense$R ~ offense$OBP) and lm(R ~ OBP)? I am trying to use R to create a linear model and use that to predict some values.  The subject matter is baseball stats.  If I do this:
obp <- lm(offense$R ~ offense$OBP)
predict(obp, newdata=data.frame(OBP=0.5), interval="predict")

I get the error: Warning message: 'newdata' had 1 row but variables found have 20 rows.
However, if I do this:
attach(offense)
obp <- lm(R ~ OBP)
predict(obp, newdata=data.frame(OBP=0.5), interval="predict")

It works as expected and I get one result.  What is the difference between the two?  If I just print OBP and offense$OBP, they look the same.

A: In the first case, you get this if you print the model:
Call:
lm(formula = offense$R ~ offense$OBP)

Coefficients:
(Intercept)  offense$OBP
    -0.1102       0.5276

But in the second, you get this:
Call:
lm(formula = R ~ OBP)

Coefficients:
(Intercept)          OBP
    -0.1102       0.5276

Look at the name of the coefficients. When you create your newdata with newdata=data.frame(OBP=0.5), that not really make sense for the first model, so newdata is ignored and you only get the predicted values with the training data. When you use offense$R ~ offense$OBP, the formula has just two vectors at each side, with no names associated to a data.frame.
The best way to do it is:
obp = lm(R ~ OBP, data=offense)
predict(obp, newdata=data.frame(OBP=0.5), interval="predict")

And you'll get the proper result, the prediction for OBP=0.5.

A: There is no difference---you get the same coefficients.
But some programming styles are better than others -- and attach is to be avoided, as is the more verbose first form.
Most experienced users do
 lm(R ~ OBP, offense)

instead.


text:
Q: My React/NodeJS shopping cart won't render the "quantity" defined I'm stuck on an issue that I hope is simple to resolve or perhaps because I'm using LTS nodeJS
But simply, when loading my Checkout page of my shopping cart => the quantity per item does not show up / not rendered
You can see in my CheckoutProduct.js source code that I try to call {quantity} and defined the prop above it as "const quantity = props.quantity"
I called every other variable such as id, title, price and they all work! It's only the quantity value causing me grief...any ideas? Many thanks in advance
    import Image from "next/image"
import Currency from 'react-currency-formatter'
import { Form } from "react-bootstrap";
import { StarIcon } from "@heroicons/react/solid"
import { useDispatch } from 'react-redux'
import { removeFromBasket } from '../slices/basketSlice'
import { updateItemQuantity, removeItem } from "../slices/cartSlice";

function CheckoutProduct(props) {
    const dispatch = useDispatch();

    const id = props.id;
    const title = props.title;
    const rating = props.rating;
    const price = props.price;
    const description = props.description;
    const category = props.category;
    const image = props.image;
    const quantity = props.quantity;
    const total = price * quantity;

        const updateQuantity = (e) => {
            const itemQuantity = e.target.value;
              dispatch(updateItemQuantity({ id, quantity: parseInt(itemQuantity) }));
          };

    function removeItemFromBasket () {
        dispatch(removeFromBasket({ id }))
    }

    return (

            <Image
                src={image}
                height={200}
                width={200}
                objectFit="contain"
            />

            {/* Middle */}

{title}

                        {Array(rating)
                            .fill()
                            .map((_, i) => (
                                <StarIcon key={i} className="h-5 text-yellow-500" />
                            ))}

{description}

                        <Currency quantity={price} currency="USD" />

                          <Form>
                            <Form.Group>
                                <Form.Control
                                 className="border-solid border-2"
                                 type="number"
                                 size="sm"
                                 value={quantity}
                                 onChange={updateQuantity}
                                />
                            </Form.Group>
                         </Form>

                     |
                        Delete

    );
}

export default CheckoutProduct


text:
Q: How do I use structs declared in other modules in main.rs? Here is the situation. I have a project named project_name and it has this file hierarchy:
project_name
|-- src
|   |-- main.rs
|   |-- lib.rs
|   `-- tree_node.rs

I declared struct TreeNode in tree_node.rs.
pub struct TreeNode { ... }

There is method using TreeNode in lib.rs:
mod tree_node;

use tree_node::TreeNode;

pub struct Solution {}

impl Solution {
    pub fn invert_tree(root: TreeNode) -> TreeNode { ... }
}

But when I try to use method invert_tree in main.rs like this:
use project_name::Solution;
use tree_node::TreeNode;

mod tree_node;

fn main() {
    let tree = TreeNode::new(1);
    let result = Solution::invert_tree(tree);
}

I got an error:
expected struct `project_name::tree_node::TreeNode`, found struct
`tree_node::TreeNode`

Maybe I use incorrectly term method but I hope the main point is clear. What is wrong?

A: main.rs and lib.rs are effectively different crates that are compiled separately, and so mod creates separate modules for each when using in both lib and main. Generally you want to only use mod in lib.rs unless some module is only for private use of the application.
Therefore, replace mod tree_node from main.rs with use project_name::tree_node::TreeNode;.
In lib.rs you must change mod tree_node to pub mod tree_node, or pub(crate) mod tree_node if it's only intended for this crate and not outside users.


text:
Q: Compiler warning for unused immutable sink, but using _ causes test to fail I have a test which verifies that a message is being published when a new device is available:
let deviceConnectedPublisher = NotificationCenter.default.publisher(for: .deviceAdded)
            .compactMap { $0.object as AnyObject as? ConnectableDevice }

let sink = deviceConnectedPublisher.sink { _ in
    expectation.fulfill()
}

this works just fine but I have a compiler warning:

Initialization of immutable value 'sink' was never used; consider replacing with assignment to '_' or removing it

However if I take the compiler's advice and change it to
let _ = deviceConnectedPublisher.sink { _ in
    expectation.fulfill()
}

then my test times out, and subsequently fails. Is there a better way to be declaring my sink? Is there some way to tell the compiler it's wrong? Should this be filed as a bug? I understand why the compiler thinks that the variable is unused, but it seems like there should be a way to disable the warning in this case --or more likely-- I'm doing something not-as-intended.

A: What the compiler is hinting to you is that the sink needs to be stored. The usual thing is to write
deviceConnectedPublisher.sink { _ in
    expectation.fulfill()
}.store(in: &self.storage)

...where storage is a Set<AnyCancellable> or [AnyCancellable] instance property. This keeps the pipeline alive and gives it a lifetime automatically tied to the surrounding object (e.g. the view controller).

A: In the code where you store the AnyCancellable in a local property named sink, the compiler issues the warning that you never used the variable. This means that the compiler is allowed to optimize away the variable and destroy the AnyCancellable immediately.
However, you are probably running your tests in a Debug build configuration. The default settings for a Debug configuration disable optimization. So the compiler does not optimize away the sink variable and only destroys it at the end of the scope. By then, I assume, you have already posted the notification you're expecting.
In the code where you use _, the compiler destroys the returned AnyCancellable immediately. This cancels your subscription to the notification publisher, so the notification is never delivered to your sink closure.
You can silence the warning, and indeed guarantee that the local property's value isn't destroyed until later, using the withExtendedLifetime function:
let sink = deviceConnectedPublisher.sink { _ in
    expectation.fulfill()
}

// post notification here

withExtendedLifetime(sink) { }
// Only now can sink be destroyed.