text:
Q: Numpy and Generator code has lower performance than naive append approach. How to improve? I have written a random_walk simulation using numpy to allocate the data and Generators to execute the simulation steps. This random_walk is just a MWE from original code (that is not related at all with random walks but is a stochastic mathematical model too large and complex to use as an example. Nevertheless the random_walk MWE simulates the core components.
The reason I'm using generators is related to the simulation. I will run the simulation for a infinite time and I only dump the data in some corner cases. I can measure the probability of corner cases occurs hence I'm able to allocate the numpy array beforehand with high degree of precision (never mised), but that is a upper bound, hence I need to count how many times the corner cases occurred then slice the dataset (tha is "emulated" in the simulation).
For sake of comparison I have also written a similar naive approach using plain append to lists to store simulation data where I append only when corner cases occurs.
It's important to know that corner cases will occurs a billion times (will take a huge part of memory), but the final simulation will run for "infinite time" that is a VERY large number of steps. The corner cases are like 1e-10 prob to occurs.
And the final code has a stop condition that I emulated here using distance and the classical simulation time.
To my surprise, I noticed that append approach has a better performance than numpy+generators. As we can see in outputs below
For small datasets:
%timeit random_walk_naive(max_distance=1e5, simul_time=1e4)
5.35 ms ± 190 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit random_walk_simul(max_distance=1e5, simul_time=1e4)
16.3 ms ± 567 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

For larger datasets
%timeit random_walk_naive(max_distance=1e12, simul_time=1e7)
12.2 s ± 760 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit random_walk_simul(max_distance=1e12, simul_time=1e7)
36 s ± 102 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Running cProfile over the calls, I noticed the generator calls has similar execution time as the naive approach and all additional time was spent in random_walk_simul it self. Evaluating the np.empty and the slicing operation I noticed that time to create the empty dataset and slice it in return is minimal. Not contributing at all with the time spent in operations. Besides that the code is almost the same, except that in generator approach I first allocate the data to local variables then "flush" them to numpy.array, that was shown faster than flush directly, since I will use the values in while loop to evaluate the stop condition.
I need to understand why this behavior is showing up and if is expected; if don't how to fix it?
The full source code is pasted below
import numpy as np
from random import random

def clip(value, lower, upper):
    return lower if value < lower else upper if value > upper else value

def random_walk(s_0, a_0, pa, pb):
    """Initial position (often 0), acceleration, 0 < pa < pb < 1"""
    # Time, x-position, Velocity, Acceleration
    t, x, v, a = 0, s_0, 0, a_0
    yield (t, x, v, a)

    while True:
        # Roll the dices
        god_wishes = random()

        if god_wishes <= pa:
                # Increase acceleration
                a += .005
        elif god_wishes <= pb:
                # Reduce acceleration
                a -= .005

        # Lets avoid too much acceleration
        a = clip(a, -.2, .2)

        # How much time has passed, since last update?
        dt = random()
        v += dt*a
        x += dt*v
        t += dt

        yield (t, x, v, a)

def random_walk_simul(initial_position = 0, acceleration = 0,
                      prob_increase=0.005, prob_decrease=0.005,
                      max_distance=10000, simul_time=1000):
    """Runs a random walk simulation given parameters

    Particle initial state (initial position and acceleration)
    State change probability (prob_increase, prob_decrease)
    Stop criteria (max_distance, simul_time)

    Returns a random_walk particle data
    """
    assert (0 < prob_increase+prob_decrease < 1), "Total probability should be in range [0, 1]"

    rw = random_walk(initial_position, acceleration, prob_increase, prob_decrease+prob_increase)

    # Over estimated given by law of large numbers expected value of a
    # uniform distribution
    estimated_N = int(simul_time * 2.2)

    data = np.empty((estimated_N, 4))

    # Runs the first iteraction
    n = 0
    (t, x, v, a) = rw.__next__()
    data[n] = (t, x, v, a)

    # While there is simulation time or not too far away
    while (t < simul_time) and (np.abs(x) < max_distance):
        n += 1
        (t, x, v, a) = rw.__next__()
        data[n] = (t, x, v, a)

    return data[:n]

def random_walk_naive(initial_position = 0, acceleration = 0,
                      prob_increase=0.005, prob_decrease=0.005,
                      max_distance=10000, simul_time=1000):
    """Emulates same behavior as random_walk_simul, but use append instead numpy and generators"""
    T = []
    X = []
    V = []
    A = []

    T.append(0)
    X.append(initial_position)
    V.append(0)
    A.append(acceleration)

    a = A[-1]
    t = T[-1]
    v = V[-1]
    x = X[-1]

    while (T[-1] < simul_time) and (abs(X[-1]) < max_distance):
        god_wishes = random()
        if god_wishes <= prob_increase:
            # Increase acceleration
            a += .005
        elif god_wishes <= prob_increase+prob_decrease:
            # Reduce acceleration
            a -= .005

        # Lets avoid too much acceleration
        a = clip(a, -.2, .2)

        dt = random()
        t += dt
        v += dt*a
        x += dt*v

        # Storing next simulation step
        T.append(t)
        X.append(x)
        V.append(v)
        A.append(a)

    return np.array((T, X, V, A)).transpose()

def main():
    random_walk_naive(max_distance=1e9, simul_time=1e6)
    random_walk_simul(max_distance=1e9, simul_time=1e6)

if __name__ == '__main__':
    main()

A: This may be a good situation for using numba:
import numpy as np
from random import random
from numba import njit

# Baseline
%timeit random_walk_naive(max_distance=1e9, simul_time=1e6)
1.28 s ± 277 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# Few adjustments for numba

@njit
def random_walk_numba(initial_position = 0, acceleration = 0,
                      prob_increase=0.005, prob_decrease=0.005,
                      max_distance=10000, simul_time=1000):

    T, X, V, A = [0], [initial_position], [0], [acceleration]

    t, x, v, a = T[-1], X[-1], V[-1], A[-1]

    while (T[-1] < simul_time) and (abs(X[-1]) < max_distance):
        god_wishes = random()
        if god_wishes <= prob_increase:
            # Increase acceleration
            a += .005
        elif god_wishes <= prob_increase+prob_decrease:
            # Reduce acceleration
            a -= .005

        # Lets avoid too much acceleration
        lower, upper = -0.2, 0.2

        a = lower if a < lower else upper if a > upper else a

        dt = random()
        t += dt
        v += dt*a
        x += dt*v

        # Storing next simulation step
        T.append(t)
        X.append(x)
        V.append(v)
        A.append(a)

    return np.array((T, X, V, A)).transpose()

%timeit random_walk_numba(max_distance=1e9, simul_time=1e6)
172 ms ± 32.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Notice that you cannot call clip but luckily that is easy to re-implement inside.


text:
Q: How to implement SVGs with Openlayers 7 in react? I am trying to figure out, how to implement an svg file as Layer in Openlayers with react. I tried Imagelayer and Vectorlayer. The example in the docs from ol doesn`t works for my case. The svg is located below src/assets/example.svg
Anyone who can help me?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get notified about activity's lifecycle I'm writing a helper class for my activity, which uses an external service. Like in a standard design pattern regarding bound services, I want to bind on activity creation and unbind on activity destruction. However, I want to isolate this logic to my helper class, so that activity would only use an instance of that helper and don't call bind and unbind explicitly.
I can pass the activity to the helper class, but I cannot find any way to schedule a callback on activity's lifecycle's events - there's just no such methods in Activity class. While this most probably means that I cannot achieve what I want to, and also that it's probably not a good idea, I still want to ask the community about this. Is it possible? Is it a good idea? Is it possible to achieve similar results with some other classes (not the Activity)?
I'm new to Android development and I'm seeking for the best practices. Any ideas are appreciated.
Thanks!
EDIT: Basically, I want to be notified on activity creation and destruction. I want to be able to schedule a callback on onCreate and onDestroy methods, but from outside of the Activity. Those methods are protected and therefore inaccessible from other classes.

A: You can use the Application.ActivityLifecycleCallbacks class. Keep in mind that the class was introduced in API level 14. For lower versions you could make hook methods in your library and require that the target Activity will call the appropriate hook method from its corresponding lifecycle method. Of course, this would be a very fragile implementation.

A: Lifecycle methods are the means to implement behaviour which will be executed when DalvikVM decides to do something with Activity (pause/resume/create/destroy), not to invoke that behaviour artificially.
If you want to externalise logic in helper/controller of some sort and be able to use service connection do initialization within ServiceConnection handler.
private ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className,IBinder service) {
        ...init helper here...
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        ...shutdown helper here...
    }
};

then handle connections as usual.


text:
Q: alternateIconName keeps returning nil I'm trying to set an alternative icon for my app but from some reason fail to do so. [UIApplication sharedApplication].alternateIconName keeps returning nil, although the plist structure looks correct:
<key>CFBundleIcons</key>
<dict>
    <key>CFBundleAlternateIcons</key>
    <dict>
        <key>AlternateIcon</key>
        <dict>
            <key>CFBundleIconFiles</key>
            <array>
                <string>AlternateIcon</string>
            </array>
            <key>UIPrerenderedIcon</key>
            <false/>
        </dict>
    </dict>
    <key>CFBundlePrimaryIcon</key>
    <dict>
        <key>CFBundleIconFiles</key>
        <array>
            <string></string>
        </array>
        <key>UIPrerenderedIcon</key>
        <false/>
    </dict>
</dict>

The code:
NSLog(@"Icon = %@",[[UIApplication sharedApplication] alternateIconName]);
prints:
Icon = (null)

A: [[UIApplication sharedApplication] alternateIconName] returns nil UNLESS an alternative icon has been set.


text:
Q: R: How are factor labels mapped to the correct values in a data.frame? EDIT: Included my reading of the documentation that I am still not clear on
I'm new to R and playing around with the RStudio pre-loaded mtcars data.frame. I am converting the cyl variable to factors and labeling them. My code is:
df <- mtcars
str(df)
df$cyl <- factor(df$cyl, labels = c('Four cylinder', 'Six Cylinder', 'Eight Cylinder'))
str(df)

Which outputs:
> df <- mtcars
> str(df)
'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...
> df$cyl <- factor(df$cyl, labels = c('Four cylinder', 'Six Cylinder', 'Eight Cylinder'))
> str(df)
'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : Factor w/ 3 levels "Four cylinder",..: 2 2 1 2 3 2 3 1 1 2 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

My question is: How is the factor section of code assigning the labels properly (i.e. 'Four cylinder', represented as 1 after the transformation, is being correctly assigned the the 4s in the original df). Is it simply applying the labels in ascending order as the default behavior? What if I have a field with, say, 10 unique values that I want to convert to factors. How can I be sure my labels and replacement values are corresponding to the correct original values?
The documentation accessed by ?factor states:

levels: an optional vector of the values (as character strings) that x might have taken. The default is the unique set of values taken by as.character(x), sorted into increasing order of x.

This appears to be stating that the labels are to be applied in ascending order by original variable value, but I just want to make sure I'm understanding correctly.

A: It knows in this example, because it converts the numeric values in mtcars$cyl into a character vector c(4, 6, 8, 6, ...) -> c("4", "6", "8", ...), the levels are selected by alphnumerical sorting ('4' then '6', then '8'; since you haven't specified the levels in your call to factor), then the numeric values stored in df$cyl are found by matching the values against the levels. The labels don't really affect the factor ordering: you could, perversely, match the label "six cylinders" with the level "4".

as.numeric(factor(c(4, 6, 8, 6, 6, 4)))
  [1] 1 2 3 2 2 1


text:
Q: Change Highchart's pie chart .xls file category column name I am using Pie Chart of Highcharts and I want to download the generated .xls file with custom columns names. By default the columns are name 'Category' and 'You series name' (in my case it's 'Percentage (%)'.
Mainly I want to change the Category name, but couldn't find a way.
this is the javascript code of the chart:
janChart = Highcharts.chart('January', {
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false,
                type: 'pie'
            },
            title: {
                text: 'Applications BW Usage in January, 2019'
            },
            tooltip: {
                pointFormat: '{series.name}: {point.percentage:.1f}%'
            },
            plotOptions: {
                pie: {
                    size:'80%',
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        format: '{point.name}: {point.percentage:.1f} %',
                        style: {
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                        },
                        connectorColor: 'silver'
                    }
                }
            },
            series: [{
                name: 'Percentage (%)',
                data: [
                ]
            }]
        });

.xls file image
the chart

A: Use columnHeaderFormatter function:
exporting: {
    csv: {
        columnHeaderFormatter: function(item, key) {
            if (!key) {
                return 'custom title'
            }
            return false
        }
    }
},

Live demo: https://jsfiddle.net/BlackLabel/n6oLmyw3/
API Reference: https://api.highcharts.com/highcharts/exporting.csv.columnHeaderFormatter


text:
Q: How to import Routes in the Spec I have the following route defined in app-routes.ts as a separate module
import {NgModule} from '@angular/core';
import {RouterModule, Routes} from "@angular/router";
import {AppComponent} from "./app.component";
...

const routes:Routes = [
  {
    path: 'new',
    component: New
    canActivate:[AuthGuard]
  },
  {
    path:'list',
    component:List
  },
  {
    path: 'signup',
    component: SignupComponentComponent
  },
  {
    path: '',
    redirectTo: 'home',
    pathMatch:'full'
  },
  {
    path: 'home',
    component:HomepageContentComponentComponent
  },
  { path: '**',
    component: PageNotFoundComponent }
];

@NgModule({
  imports:[RouterModule.forRoot(routes)], //
  exports: [RouterModule],
  providers:[]
})

export class AppRoutingModule{}

I am using the route in the HomePageComponent. How do I test the routing? I know I need to use RouterTestingModule. like follows:
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports:[RouterTestingModule.withRoutes(routes)], //routes is undefined here
      declarations: [ HomepageContentComponentComponent,
      ]
    })
    .compileComponents();
  }));

But the routes variable defined as const routes:Routes = ... in AppRoutingModule isn't available here.
Question 1) How in my current setup, I can make routes visible in the specs
Question 2)I thought to create a separate file myroutes.ts which contains only the routes array so that I can use it in the specs but even that doesn't work. Why? ( something like the following)
my-route.ts
  const routes:Routes = [
    {...      ];

Why am I note able to use routes in imports:[RouterTestingModule.withRoutes(routes)] when I created it in a sepafrate file?

A: I should have exported the routes as export const routes:Routes


text:
Q: How to implement couchbase lite on android? what I am trying to do is implement couchbase lite. I am using the official documentation but do not quite get it
I used
implementation 'com.couchbase.lite:couchbase-lite-android:2.0.0'

but for some reason, on the databasemanager class, gives me an error
// tag::initCouchbaseLite[]
public void initCouchbaseLite(Context context) {
    CouchbaseLite.init(context);
}
// end::initCouchbaseLite[]

the "CouchBaseLite" is highlighted and says cannot resolve reference. I cannot seem to get it to work
Any help or suggestion on what to look for would be great, thanks

A: Use version 2.8.0 this should work. Also support for down to API-21 was deprecated in release 2.6 So if your app has minimum API version > 21 then its fine otherwise you might have to change it later.
implementation "com.couchbase.lite:couchbase-lite-android:2.8.0"


text:
Q: How to change level of counters in animation for Tecplot360 I am working on a transient heat transfer problem. The problem that I have is as the time goes the range of temperature is changing but Tecplot only use one sort of levels for contour for all of time steps. Therefore the change in temperature is not very sensible at the end of the time which transient diminishes.
I am wondering if there is anyway to change the levels of contours as time goes forward? (Could I specify a contour for any specific time step?)

A: You would need to write a macro to do that and save the animation. Have a look at the tecplot macro scripting guide Tecplot Scripting Guide. You can record the macro, then load your data cycle through a few time steps and change the level of contour manually. Then you can edit the recorded macro to suit your self. The following macro file should be helpful for starting guideline
#!MC 1410
$!EXPORTSETUP
  EXPORTFNAME="movie.avi"
  EXPORTFORMAT=AVI
  EXPORTREGION = CURRENTFRAME
$!EXPORTSTART
$Loop 20
  $!GLOBALTIME |LOOP| # assuming your time varies as 1, 2, 3, ... 20
  $!CONTOURLEVELS RESETTONICE
  $!EXPORTNEXTFRAME
$!ENDLOOP
$!EXPORTEND


text: Q: Send packet to BLE HID Device I built a bluetooth keyboard macro, and connected it normally to my linux machine, however I need to send custom packets from Central to the device (in python), as information of which window is currently focused among other things. Is there a way to do this? A two-way communication between device and machine, without needing a dedicated BLE HID client?


text:
Q: How can I compile Opencv API on gcc I am trying to compile an an .C file which contains API from Opencv library.
It seems the compiler doesn't find the API. I use the normal command for compilation
   gcc new.c -c
   gcc new.o -o new1 -l highgui

highgui is a .h file which is calling other .h files from Opencv lib
I think I have the same problem as the thread below as I get almost same error.
GCC: How can I make this compiling and linking work?

A: You can use pkg-config command to get the compiler/linker options. Like this
gcc `pkg-config --cflags opencv` `pkg-config --libs opencv` new.c

Please note the above punctuation is ` not '.
Or you can use CMake. Write a CMakeLists.txt like this
cmake_minimum_required (VERSION 2.6)
project (new1)
find_package (OpenCV REQUIRED)
include_directories (${OpenCV_INCLUDE_DIRS})
add_executable (new1 new.c)
target_link_libraries (new1 ${OpenCV_LIBS})

then you can build like this
mkdir build
cd build
cmake -DOpenCV_DIR=<the-directory-contating-OpenCVConfig.cmake> ..
make

A: Try below command
gcc -I/usr/local/include/opencv -I/usr/local/include/opencv2 -L/usr/local/lib/ -g -o binary  main.c -lopencv_core -lopencv_imgproc -lopencv_highgui

Assumes OpenCV installed on /usr/local directory.

A: Try the command Harris wrote.
It tells Your compiler to look for header files additionally in /usr/local/include/opencv and /usr/local/include/opencv2 directories (-I switch), and look for libraries in /usr/local/lib/ (-L). Next it tells the linker with -l switch to link libraries opencv_core and etc...
When You will encounter this type of problem, You need to find library files, tell compiler the path to them and tell him which libraries to link, OMITTING THE LIB PART IN NAME, for example opencv_core instead of libopencv_core.


text:
Q: Images from database column not loading CODE:
<?php
    $page = $_GET['page'];
    $category = $_GET['cat'];
    $your_db = @ new mysqli("database","name","password");
    if (mysqli_connect_errno())
    {
    echo 'ERROR!
    '.mysqli_connect_errno()
    .' - Not connected : '.mysqli_connect_error().'
    ';
    die;
    }
    else
    {
    $db_connect = $your_db->select_db("databasename");
    if (!$db_connect)
    {
    echo 'ERROR CONNECT DATA BASE';
    die;
    }
    }
    echo '
';
    $query = "select distinct fldCity from info order by fldCity";
    $result = $your_db->query($query);
    $number_of_records = $result->num_rows;
    for ($i = 0; $i < $number_of_records; $i++)
    {
    $row = $result->fetch_assoc();
    echo '';
    echo stripslashes($row['fldCity']);
    echo ' / ';
    }
    echo '
';
    if ($category)
    {
    $query = "select fldCompanyLogo, fldCompanyName, fldAddress, fldCity, fldProvince, fldPostalCode, fldMenuLink
    from info where fldCity = '$category' and length(fldCompanyLogo) > 0 order by fldCity";
    }
    else
    {
    $query = "select fldCompanyLogo, fldCompanyName, fldAddress, fldCity, fldProvince, fldPostalCode, fldMenuLink
    from info where length(fldCompanyLogo) > 0 order by fldCity";
    }

    $result = $your_db->query($query);
    $number_of_records = $result->num_rows;
    $num_pages = $number_of_records / 7;
    if (($number_of_records % 7) > 0 )
    {
    $num_pages++;
    }
    if (strlen($page) == 0)
    {
    $page = 0;
    }
    else
    {
    $page = $page * 4;
    }
    echo '
';
    $row_num = 4;
    $result->data_seek($page);
    for ($i = $page; $i < $number_of_records; $i++)
    {
    if ($row_num <= 4)
    {
    echo '
';
    for ($col_num = 0; $col_num < 4; $col_num++)
    {
    $row = $result->fetch_assoc();
    echo '';
    show_image(stripslashes($row['fldCompanyLogo']),stripslashes($row['fldCompanyName']));
    echo '
    ';
    echo '';
    echo '';
    echo stripslashes($row['fldCompanyName']);
    echo '';
    echo '
    ';
    echo stripslashes($row['fldCity']);
    echo '
    ';
    echo stripslashes($row['fldProvince']);
    echo '
    ';
    echo stripslashes($row['fldPostalCode']);
    echo '	';
    }
    $row_num++;
    echo '
';
    }
    else
    {
    break;
    }
    }
    echo '
';
    for ($j = 0; $j < $num_pages; $j++)
    {
    $page_link = $j + 1;
    echo ''.$page_link.' ';
    }
    echo ' '.$number_of_records;
    function show_image($image_name)
    {
    if (file_exists("'$image_name'"))
    {
    $dim_img = getimagesize('/images/'.$image_name);
    echo '';
    }
    else
    echo 'Add your image here!';
    }
    ?>

I am totally lost and I can't find the error to why the images from the database isn't loading with the  script. I highlighted the area in blue where I believe the error is to be. I just can't find any errors in that particular spot! All I want is the images from a column I have in my database to be fetched and connected to 'echo '

No images are being displayed, and I can't find the error as to why the images aren't showing up

A: try Convert Image to Base64 String and Base64 String to Image
also why   echo ''; you use this its makes no sense


text:
Q: Find which solutions are periodic for a given system Given the differential equations:
$$
\begin{cases}
\frac{dx}{dt} = y-1 \\
\frac{dy}{dt} = -xy
\end{cases}
$$
I'm trying to find out which solutions are periodic. So I tried to find the solutions $y(x)$ and tried to prove that for some startvalues $x_0$ and $y_0$ we find that $y(x_0) = y(x_0 + p)$, where $p$ is the period.
The solution, $y(x)$, that I found is the following:
$$y(x)-\ln{y(x)} = -\frac{1}{2}x^2+\frac{1}{2}x_0^2+y_0-\ln{y_0}$$
Or rewritten as a function of $x(y)$:
$$x(y) = \pm(2\ln{y}-2y+2(\frac{1}{2}x_0^2+y_0-\ln{y_0}))^{\frac{1}{2}}$$
I've plotted the solutions and found the following

So the periodic solutions are only found when $y_0 > 0$ and $x_0$ is in some range. If $x_0$ is too large or too small the solution goes to $y(x) = -\infty$. But how can I show this correctly?

A: I don't think you need Poincare Bendixson here. This is an integrable system, it has a first integral. Here is what you do.
Observe that all curves $\{(x_0 - t, 0) : t \in \mathbb{R}\}$ starting from a point $(x_0, 0)$ on the $x-$axis trace the $x-$axis, so your phase space, after removal of the orbit $\{(x,y) \, \in  \, \mathbb{R}^2 \, : \,\,  y=0\}$, is divided into an upper half-plane and a lower half plane.
Next, for $y>0$ (upper half-plane) change the variables as follows: $x = x \, , \,\,\, y = e^z$. Then
$\dot{y} = e^z \, \dot{z} = -x \, y = - x \, e^z$ which after canceling out the term $e^z$ on both sides of the latter equality, leads to the system
$$
\begin{align}
\dot{x} &= e^z - 1\\
\dot{z} &= -x
\end{align}
$$ Then you cast this system in the form of a second order (Newton's type) equation
$$\ddot{z} = - \dot{x} = 1 - e^{z}$$ i.e.
$$\ddot{z} = 1-e^z$$
This has a conservation of energy integral of motion
$$\frac{\dot{z}^2}{2} + e^z - z = E_0$$ for a constant $E_0$. Here $\frac{\dot{z}^2}{2}$ is the kinetic energy term and $U(z) = e^z-z$ is the potential energy term. Then when you draw the graph of the $U(z) = e^z-z$ you see that it is a convex function with exactly one minimum, equal to $1$ when $z=0$, and growing to $+\,\infty$ when $z \to \pm \, \infty$. The latter means that for each energy level $E_0 > 1$ we have a periodic orbit circling round the equilibrium $x=0, z = 0$ which is the equilibrium $x=0, y=1$ in the original coordinates. Hence, the whole upper half-plane is filled with periodic solutions.
For the lower half-plane $y<0$, change the variables as follows: $x=x\, , \,\, \, y= - e^{z}$. Then proceed analogously. You end up with the second order equation
$$\ddot{z} = e^{z} + 1$$ with a conserved total energy
$$\frac{\dot{z}^2}{2} - \big(z + e^{z}\big) = E_0$$ If you draw the graph of the potential $U(z) = - \big(z + e^{z}\big)$ you observe that it is a strictly decreasing function so the energy level for each $E_0$ are semi-open trajectories (open on one side, going to infinity). In particular they are never periodic solution.

A: This was a special equation to me as it formed part of my phd.
$$
\ddot{x} -x\dot{x} + \mu x = 0
$$
it was found that you get autosave behaviour (periodic) entered about the shift which for you is 1 (for me it was $\mu$)
I used Bendixson Theorem to prove periodic solutions existed.

$$H_x = \dot{x}\\H_y = \dot{y}$$ $\nabla\cdot \mathbf{H}$ does not contain a change in sign for some element in $(x,y)$ then we find a periodic solution.

Which for you implies you need a domain where $x=0$ you can then determine which side of the phase-transition you will have periodic solutions (it is based on $y$)
For the above equation you always have the same form, and there is a relationship between the asymptotic region and bounded solution (it depends on $\mu$ and $\dot{x}$ ). Also, for any parameter in the periodic domain we have closed solutions.
Note that you can transform your equation
$$
\ddot{x} + x\dot{x} + x = 0
$$
To my original equation by $t\to -t$
$$
\ddot{x} -x\dot{x} + x = 0
$$
since the solutions are similar in phase space.


text:
Q: C# - WebBrower [ActiveX] PLUGIN? We are an international company and our Customer Relationship Management tool works only from Internet Explorer with Active X activated.
I've created in Visual Studio a simple navigator in WindowsForm C#
I want to know if somebody knows how to activate the ACTIVEX Plugin when a page loads by clicking on a button?
Can you please someone help?


text:
Q: Batch file: save & load I have one big problem. This app SHOULD ASK user for his name ONCE. It saves username and then when he run this app again 1st stage should be skipped and variable "name" should has his name from file with extension .user, but it does not work :/ Please Help!
@echo off
If NOT EXIST .settings md .settings
cd .settings
If NOT EXIST *.user goto abc
pause

If EXIST *.user set name=*.user
cd ..
pause
goto welcome
pause
:abc
cd ..
echo Hi! Welcome in my program!
set /p name=Tell me your name!
If NOT EXIST .settings md .settings
cd .settings
echo >>%name%.user
pause

:welcome
cls
echo Welcome %name%
pause

Other commands

EDIT: Pauses are only for me :)

A: You're just setting name to the string *.user. You need to parse the filename and extract just the first part.
Try:
If EXIST *.user (
  for /f %%a in ('dir /b *.user') do (set name=%%~fa)
)
cd ..

Also, to just create a blank file, you can use
Type nul > %name%.user

A: It's not particularly clear what you are trying to do.
If fred has entered his name, this line:
echo >>%name%.user

will send the ECHO status (Echo is on/off) to the file fred.user
If you want the file .user to contain "fred" then you'd need one of
echo %name%>.user
>.user echo %name%

(personally, I'd use the second)
If you then want to read the user's name from the file .user then
set /p name=<.user

So all together, I'd try
@ECHO OFF
SETLOCAL
IF EXIST .user (SET /p name=<.user) ELSE (SET /p name=Your name ?)
 >.user ECHO %name%

 ECHO name is %name%

(I'll leave you to do the directory-manipulation)
Note that I've used > which means 'start a brand new filewhereas>>means 'append to an existing file or create a new file


text:
Q: Maximize a function Resolve the following problem. Let $\alpha, \beta > 0, p_{1},p_{2} > 0$ fixed. Maximize $x^{\alpha}y^{\beta}$ subject to $p_{1}x + p_{2}y = 10$ $x,y > 0$.

A: This is a geometric programming problem, a type of convex optimization problem. There are efficient solvers available.
However, if you are looking for an analytical solution for this particular variant, then we use a log transform and substitution to get:
$$x=\frac{10-p_2y}{p_1} \implies z:= \ln\left(x^{\alpha}y^{\beta}\right)= \alpha \ln(x) + \beta\ln(y) = \alpha\ln\left(\frac{10-p_2y}{p_1}\right) + \beta\ln(y)$$
We can further simplify this by pulling out $p_1$:
$$z:= \alpha\ln\left(10-p_2y\right) - \alpha\ln(p_1) + \beta\ln(y)$$
We can now apply the usual calculus to get the stationary point:
$$\text{Find }y:\frac{dz}{dy} = \frac{\beta}{y}-\frac{\alpha p_2}{10-p_2y}=0$$
Setting both sides equal to each other we get:
$$\frac{\beta}{y}=\frac{\alpha p_2}{10-p_2y} \implies \beta\left(10-p_2y\right)=\alpha p_2 y \implies 10\beta=(\alpha+\beta)p_2y \implies y=\frac{10\beta}{(\alpha+\beta)p_2}$$
Since $\alpha, \beta, p_2 > 0$ we know that $y>0$
Taking the second derivative of $z$ wrt $y$, we get:
$$\frac{d^2z}{dy^2} = -\frac{\alpha p_2^2}{(10 - p_2y)^2} - \frac{\beta}{y^2}$$
Plugging in our optimal $y$ (i.e, $y^*$) and simplifying we get:
$$\left.\frac{d^2z}{dy^2}\right|_{y=y^*}=-\frac{p_2^2}{100}\left(\frac{\alpha }{\left(1- \frac{\beta}{\alpha+\beta}\right)^2} + \frac{\beta }{\left(\frac{\beta}{\alpha+\beta}\right)^2}\right) < 0 \;\;\;\forall \alpha,\beta > 0$$
Therefore, $y^*$ is a occurs at the maximum. Since $y^*$ is unique, it is the global maximum.
From our substitution, we get:
$$x=\frac{10-p_2y}{p_1} \implies x = \frac{10-p_2\frac{10\beta}{(\alpha+\beta)p_2}}{p_1} = \frac{10-\frac{10\beta}{(\alpha+\beta)}}{p_1} = 10\left(\frac{1-\frac{\beta}{(\alpha+\beta)}}{p_1}\right)$$
Again, since $\alpha,\beta>0$ we will have $0<\frac{\beta}{(\alpha+\beta)} < 1 \implies x>0$.
Since $\ln(w)$ is monotonic increasing in $w$,
$$\arg\limits_{x,y} \max z = \arg\limits_{x,y} \max e^z = x^{\alpha}y^{\beta}$$
Therefore, the values $x^*,y^*$ that optimize the original problem are given by:
$$y=\frac{10\beta}{(\alpha+\beta)p_2}, \;\;\;x= 10\left(\frac{1-\frac{\beta}{(\alpha+\beta)}}{p_1}\right)$$
We have shown that $\alpha,\beta,p_1,p_2> 0 \implies x^*,y^*>0$


text:
Q: FlatList only visible if there is at least 2 items In my Expo app I have created a flatlist that takes info from symbols
The value of symbols is just hard coded as below
constructor(props) {
        super(props)
        this.state = {
            symbols: [{"symbol": "1816ABC","Name": "Some data","icon": "md-star-outline"}],
        }
    }

Here is my render function
render() {
        if (!this.state.fontLoaded) {
            return <Expo.AppLoading />;
          }
        return (
            <View style={styles.mainContainer}>
                <View style={{paddingVertical: padding.med,alignItems: 'center'}}>
                    <Text style={styles.headerText}>
                        ALERTS
                    </Text>
                </View>

                <FlatList
                    data={this.state.symbols}
                    extraData={this.state.symbols}
                    keyExtractor={(item, index) => item.symbol}
                    ItemSeparatorComponent={this.renderListSeparator}
                    renderItem={this.renderListItem}
                    onRefresh={() => this.onPullToRefresh()}
                    refreshing={this.state.isFetching}
                />
            </View>
        );
    }

When symbols only has 1 item, the list does not render and the screen is blank, just the word ALERTS appears
When I hard code in a few more items to the symbols list, it displays all of the items no problem.
Not sure if this is a problem with my code or the FlatList component
EDIT
renderListItem = ({ item, index }) => {
        return (
            <TouchableOpacity
                onPress={() => this.onPressListItem(index)}
            >
                <MyListItem
                    item={item}
                />
            </TouchableOpacity>
        )
    }

EDIT 2
Live code avaliable here
https://snack.expo.io/@zoonosis/ranting-pudding

A: render() {    console.log(this.state.symbols)
        return (
           <FlatList
                    data={this.state.symbols}
                    extraData={this.state.symbols}
                    keyExtractor={(item, index) => item.symbol}
                    ItemSeparatorComponent={this.renderListSeparator}
                    renderItem={(value,index)=>{
                      return(
                        console.log(value.item.symbol,'hel')
                      )
                    }}

                />

        );
    }

A: This is the answer to this problem provided by breadboxio on the expo forums
"So I took a look at your code, and your item is being rendered, just with no width so you can't see it. By adding width: dimensions.fullWidth to your top level View on the MyListItem, it fixes this issue."
"your separator item has a width on it. for one item, there is no separator item rendered, but for more than one, there is. So once a separator item was rendered, it would stretch the flatlist to the width of that separator item."


text:
Q: getting vs being in passive voice sentences Can getting and being be interchanged in passive voice sentences?  For example:

*

*My computer getting stopped.

*My computer being stopped.

Which is correct? If neither, then how can I form this sentence?

A: As a learner, I should say, unfortunately, both examples are wrong in formal English.
getting and being are present participles; they participate in sentences and take on several roles. However, they cannot be used as a main verb.
If you want to imply that your computer shows signs that it will stop in the following seconds, I will suggest that you construct a sentence as below:

My computer is going to stop.

Passive present participles are usually used to focus on the object which is receiving something at the moment. For example:

Please wait, OS is being installed.
This is one sailor who remembers our ship being hit by shrapnel (Google Search)


text:
Q: Passing CVarArg in inner func I need a wrapper for default func String.init(format: String, arguments: CVarArg...) -> func custom(someParam: String, arguments: CVarArg...)
But when I tested it, I have found, that passed arguments were wrapped in Array and can't be used in init(format:) bcs of different format - Array<CVarArg> instead of queue arg1, arg2, ...
Is there any way to direct transfer passed CVarArg value to inner func?

A: There is also a String initialiser with the function signature init(format: String, arguments: [CVarArg]), so you can simply pass your arguments to that one.
func custom(someParam: String, arguments: CVarArg...) {
    String(format: someParam, arguments: arguments)
}

Compiles just fine.


text:
Q: FTP Username and password in html link I just go through Google search before posting this question here but I am not happy with my Google results. I hope someone can help me here.
I have an eCommerce site. All the images are stored in a different ftp server. I need to show all the images on my webpage. When page laods it ask for FTP username and password. I can avoid it by giving username and password in FTP URL. But I do not think it is secure. My password will be accessible to every user of my site.
Is there any other way?

A: You really should create an FTP account that only has access to the folder with the images on your FTP server. Do that as soon as possible.
For a better overall solution, either synchronize the images to your webserver, or write an HTTP handler that will fetch the image server-side and streams the bytes to the client as if the image was on your server. Have a look at System.Net.FtpWebRequest for the second solution.
If you have write access to disk on the web server, you could implement both parts of the solution. So if an image is fetched the first time, write it to disk before sending it to the client. The next time it's requested, simply redirect the request to the image on disk (or dynamically change the URL of the <img> tag for that product). This way, you build a cache of the images on your web server as time passes. Of course, you need to be able to invalidate the cache in case an image is updated.


text:
Q: SpringBoot src [main] issue Does anyone know why this would be happening? Other projects I have show src -> main as bolded.
[g
I have tried unmarked directories and recreating the source directory as java as I was having a separate issue.

A: I mistakenly set src as the main in my gradle and its now fixed.
sourceSets {
    main {
        java {
            srcDirs = ["main"]
        }
    }
}


text:
Q: How do I share an entire bookmarks folder between two firefox sync users? I am trying to share a folder of bookmarks I use at work in firefox, so that this specific folder is available at home.
I am using Firefox Sync to synchronise among diferent instances of firefox in different computers and I am also using XMarks to share those bookmarks with Chrome.
This is the setup:

*

*Work computer: Firefox with my.name@company.domain profile both in firefox sync and xamrks. Folder Work@company is to be shared.

*Home computer: Firefox with my.name@gmail.com where the Work@company folder is meant to be shared

Xmarks only allows sharing of folders as webpages and Firefox Sync seems to be all or nothing from the options I have seen and tried.
Has anyone figured  out a way to share a bookmark folder with another computer?
Note that I am ok with unidirectional sync (Work -> Home) but I would prefer for it to be bidirectional.


text:
Q: Maven JAXB 2 Plugin - how to setup to use cross scheme dependencies Using maven-jaxb2-plugin to generate JAXB classes for two WSDL schemas that are related to each other.
The classes generated like this:
com - accounts
   |- payments
   |- other

maven-jaxb2-plugin is set up like this:
<plugin>
   <groupId>org.jvnet.jaxb2.maven2</groupId>
       <artifactId>maven-jaxb2-plugin</artifactId>
       <version>0.13.1</version>
       <executions>
           <execution>
               <id>unipayments</id>
               <goals>
                   <goal>generate</goal>
               </goals>
               <configuration>
                    <schemaLanguage>WSDL</schemaLanguage>
                    <args>
                        <arg>-npa</arg>
                    </args>
                    <schemas>
                        <schema>
                            <url>http://...accounts?wsdl</url>
                        </schema>
                    </schemas>
               </configuration>
            </execution>
            <execution>
                <id>accounts</id>
                <goals>
                   <goal>generate</goal>
                </goals>
                <configuration>
                   <schemaLanguage>WSDL</schemaLanguage>
                   <args>
                       <arg>-npa</arg>
                   </args>
                   <schemas>
                       <schema>
                          <url>http://...payments?wsdl</url>
                       </schema>
                    </schemas>
                </configuration>
             </execution>
    </executions>
</plugin>

The annotations of the one of the generated classes (almost the same anywhere):
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "inputTemplate", namespace = "http://...payments", propOrder = {})
public class InputTemplate {...}

The issue is SOAP accounts JAXB classes have the nested element of the class specified above which came from another payments scheme. So, Marshaller throws the exception like this when I query to the object of accounts service that has payment's inputTemplate as child:
unexpected element (uri:"http://...payments", local:"inputTemplate").
Expected elements are <{}inputTemplate>

Don't know why it happens though, the each class has namespace specified.
So, how to let JAXB classes with cross scheme dependency work using this plugin?

A: This:

unexpected element (uri:"http://...payments", local:"inputTemplate").
  Expected elements are <{}inputTemplate>

Actually points not to a problem with schema dependencies but rather to a problem with namespaces. The inputTemplate element is known but it is expected in the default namespace. Probably wrong elementFormDefault or something like this.
To answer your question, inter-schema dependencies are best handled if you compile your schemas separately (separate Maven modules) and the include dependencies as episodes.
https://github.com/highsource/maven-jaxb2-plugin/wiki/Using-Episodes


text:
Q: Testing Kafka producer throughput We have a Kafka cluster consists of 3 nodes each with 32GB of RAM and 6 core 2.5 CPU.
We wrote a kafka producer that receive tweets from twitter and send it to Kafka in batches of 5000 tweets.
In the Producer we uses producer.send(list<KeyedMessages>) method.
The avg size of the tweet is 7KB.
Printing the time in milliseconds before and after the send statement to measure the time taken to send 5000 messages we found that it takes about 3.5 seconds.
Questions
Is the way we test the Kafka performance correct?
Is using the send method that takes list of keyed messages the correct way to send batch of messages to Kafka? Is there any other way?
What are the important configurations that affects the producer performance?

A: You're measuring only the producer side? That metric tells you only how much data you can store in a unit of time.
Maybe that's what you wanted to measure, but since the title of your question is "Kafka performance", I would think that you'd actually want to measure the throughput, i.e. how long does it take for a message to go though Kafka (usually referred to as end-to-end latency).
You'd achieve that by measuring the difference in time between sending a message and receiving that message on the other side, by a consumer.
If the cluster is configured correctly (default configuration will do), you should see latency ranging from only a couple of ms (less than 10ms), up to 50ms (few tens of milliseconds).
Kafka is able to do that because messages you read by the consumer don't even touch the disk, cuz' they are still in RAM (page cache and socket buffer cache). Keep in mind that this only works while you're able to "catch up" with your consumers, i.e. don't have a large consumer lag. If a consumer lags behind producers, the messages will eventually be purged from cache (depending on the rate of messages - how long it takes for the cache to fill up with new messages), and will thus have to be read from disk. Even that is not the end of the world (order of magnitude slower, in the range of low 100s of ms), because messages are written consecutively, one by one is a straight line, which is a single disk seek.
BTW you'd want to give Kafka only a small percentage of those 32GB, e.g. 5 to 8GB (even G1 garbage collector slows down with bigger sizes) and leave everything else unassigned so OS can use it for page and buffer cache.


text:
Q: how to insert bulk data using PLSQL in mysql with dynamic value I need to insert dynamic values to a table and insert some data to its child tables also. Tables contains some unique field also. For unique field, it should be inserted as temp1, temp2, temp3...., I will be thankful if somebody shows a sample code to insert 100 records dynamically to the parent and its child table as I am new to the PLSQL.

A: You cannot do this as PLSQL isn't support by MySQL. plsql is a language for Oracle database handling.

PL/SQL is a procedural language designed specifically to embrace SQL statements within its syntax. PL/SQL program units are compiled by the Oracle Database server and are stored inside the database. And at run-time, both PL/SQL and SQL run within the same server process, bringing optimal efficiency. PL/SQL automatically inherits the robustness, security, and portability of the Oracle Database.

What you could do is use either php, java or any other programming language to do your inserts.


text:
Q: Return the url of the generated image in PHP I am trying to draw something on a image    , I  have done it by the code below
$image = imagecreatefromjpeg('img.jpg');

$ellipseColor = imagecolorallocate($image, 0, 0, 255);
imagefilledellipse($image, 100, 100, 6, 6, $ellipseColor);
header("Content-type: image/jpeg");
imagejpeg($image);

This code successfully draw the image , and I can see this on browser  . The generated html  for this code like

But I want to display that image in my own styled way   , like

Is there any way I just can return an url for the generated image , and destroy it after using .

A: There is no need to return the URL of the generated image any differently than your first example. Just remove the style-attribute and the the class-attribute you used in your second example:

Now the image will be formatted as described by the city_map CSS class definition (instead of the definition provided by the style-attribute)
To make the image similar as the first one you could use the following CSS:
.city_map {
  -webkit-user-select: none;
  cursor: zoom-in;
  width: 786px;
  height: 413px;
}


text:
Q: Double DirectX Matrix Transformation? I am creating a 2D game. The view is from directly above my character, with him being stationary in the middle of the screen and the world moving (and rotating) around him. I do this by calling D3DXMatrixTransformation2D and putting in the (constant) position of my character and the rotation of him.
That works pretty well for my character and the background. For the bullets and enemies, even though it works, it's not what I want. I want the enemies to rotate on their own axis along with the overall axis of my character. Currently, when I rotate 180 degrees, the enemy is upside down, in the same manner as the background. That's ok, but I want him the ability to turn around to shoot me (that, or rotate the same degree so that we are always facing up; I haven't decided yet, but I believe it's the same problem).
The bullets are the same story. My first bullet design was a long skinny energy type beam. No matter in which direction I shot it, it would always face "north", even though it was heading in a different (correct) direction. I sidestepped this problem for now by creating a round bullet, but it doesn't solve the real problem.
So is there anyway to call D3DXMatrixTransformation2D twice? I've tried doing that with one matrix and one SetTransform() call, two matricies and two SetTransform() calls, and with one matrix and two SetTransform() calls, but it either doesn't change anything, or it makes the bullet/enemy texture the rotation center and doesn't recognize my rotation. I can provide some code if needed, but there's nothing much to the code that's giving me this problem. Thank you!
EDIT: Here's the code I have now, but it seems to work the same way as before:
    D3DXVECTOR2* center =  new D3DXVECTOR2(position.x,position.y);

D3DXMatrixTransformation2D(&mat,NULL,0.0,NULL, center, this->rotation,NULL);
sprite->SetTransform(&this->mat);
D3DXMatrixTransformation2D(&this->mat, NULL, NULL, NULL, &this->spriteCenter, *player::getInstance()->getRotation(), NULL);

sprite->SetTransform(&this->mat);

sprite->Draw(bullet, NULL, NULL, &this->position, 0xFFFFFFFF);

The "position" variable is a D3DXVECTOR3 variable that is the screen posiiton of the current bullet object. The "this->rotation" is the rotation of the bullet. The spriteCenter variable is the position of the center of the player texture, which is (408, 316, 0).


text:
Q: CSS validation failure: "Value Error : background-image no-repeat is not a background-image value" I am validating my CSS on w3c.org and am receiving the following error message:
Value Error : background-image no-repeat is not a background-image value : url(http://d20m4dvzhiuv61.cloudfront.net/assets/bg-body-3a1d6e7921cb2e11584ad84371a73188.jpg),no-repeat
What does this mean?


text:
Q: Required field in custom component with template driven form does not mark the form as invalid I am using template driven form in angular 7.
I created a custom component.
the custom component has required directive.
When the value is empty/null the mat-error appears correctly, but the parent form that contains it is not marked as invalid.
I have added a simple example to show this behavior
custom component with required
Any idea?

A: After investigation, I understand that the requierd handling within the custom component take care of the display validation error,
In order to mark the form invalid in case of error, adding of requierd directive in the custom component using also needed.
<app-radio-button-list name="examinationTypeCtrl"
                        [(ngModel)]="id"
                        #rd="ngModel"
                        required>
</app-radio-button-list>

fixed example
I found this link,
Its perfect explanation about custom component with ControlValueAccessor implementation .


text:
Q: check how many elements are equal in two numpy arrays python I have two numpy arrays with number (Same length), and I want to count how many elements are equal between those two array (equal = same value and position in array)
A = [1, 2, 3, 4]
B = [1, 2, 4, 3]

then I want the return value to be 2 (just 1&2 are equal in position and value)

A: As long as both arrays are guaranteed to have the same length, you can do it with:
np.count_nonzero(A==B)

A: Using numpy.sum:
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4])
>>> b = np.array([1, 2, 4, 3])
>>> np.sum(a == b)
2
>>> (a == b).sum()
2


text:
Q: Плавная прокрутка через перетаскивание Имею такой код HTML

    <?php
    for ($i = 0; $i != 44; $i++) {

    echo '
';
        for ($c = 0; $c != 44; $c++) {
        echo '

';
        }
    echo '
';

    }
    ?>

CSS:
.ner {
width: 100%; overflow: hidden; height: 100%;
-webkit-user-select: none;
-moz-user-select: none;
}

.cat {
position: relative;
width: 2202px; height: 2202px;
}

.cat > ul {
display: block;
list-style: none;
width: 100%;
margin: 0px;
padding: 0px;
}

.cat > ul > li {
display: inline-block;
width: 50px;
height: 50px;
border: solid 1px black;
box-sizing: border-box;
margin: 0px;
padding: 0px;
position: relative;
}

это просто контейнер в кнтейнере с сеткой из клеток - содержимое контейнера не влезает в его рамки и уходит в скрытую прокрутку через overflow: hidden;
вот таким скриптом я это проматываю через drag scroll (прокрутка переаскиванием)
$(function() {

  var isDragging = false;

  var mouseIsDown = false;
  var curSX = 0;
  var curSY = 0;

  $control = $("#controll > ul > li");

  $control.mousedown(function(e) {
    mouseIsDown = true;

    curSX = e.clientX;
    curSY = e.clientY;

  });

  $control.mouseup(function(e) {
    isDragging = false;
    mouseIsDown = false;
  });

  $(document).mousemove(function(e) {
     if (mouseIsDown) {
       isDragging = true;

       //$("#ner").scrollLeft(curSX - e.pageX); $("#ner").scrollTop(curSY - e.pageY); 1 вариант

     //document.getElementById('ner').scrollBy(curSX - e.pageX, curSY - e.pageY); 2 вариант

     }
  });

});

в последних строках скрипта есть 2 закомментированных варианта скроллинга которые я использую

*

*вариант через jquery - перетаскивает плавно есть ощущение что ты "укхватил" и тянешь НО каждый новый раз когда начинаешь перетаскивать начальная позиция содержимого сбрасывается на нулевые координаты X-Y т.е. каждый раз перетаскивание начинается контента с дефолтной позиции левого верхнего угла

*вариант без jquery - там не сбрасываются координаты как в первом - т.е. ты один раз перетащил и когда перетаскиваешь второй раз ничего не соскакивает, но ощущения перетаскивания нет - мотается очень быстро и нет ощущения "ухватил" - вариант без jq я взял  отсюда
подскажите пожалуйста как совместить плюсы(плавно) обоих вариантов без минусов(соскакивает в угол и резко) что я сделал тут не так ведь в примере по ссылке пусть вид кода немного и другой но там работает как надо?

A: В обоих вариантах идет работа со смещением. То есть вычисляется количество пикселей, на которое нужно сместиться.
При этом чтобы не сбрасывался первый вариант, нужно прибавлять полученное значение смещения к текущему положению.
.scrollBy и так принимает смещение, поэтому для второго варианта не нужно дополнительно ничего прибавлять.
Чтобы корректно рассчитывалось, в конце каждого обработчика нужно сохранить текущее значение координат мышки, чтобы смещение считалось уже от них.

$(function() {
  var isDragging = false;
  var mouseIsDown = false;
  var curSX = 0;
  var curSY = 0;
  var ner = document.getElementById('ner');
  $control = $("#controll");
  $control.mousedown(function(e) {
    mouseIsDown = true;
    curSX = e.pageX;
    curSY = e.pageY;
  });
  $control.mouseup(function(e) {
    isDragging = false;
    mouseIsDown = false;
  });
  $(document).mousemove(function(e) {
    if (mouseIsDown) {
      isDragging = true;
      //$("#ner").scrollLeft($("#ner").scrollLeft() + curSX - e.pageX);
      //$("#ner").scrollTop($("#ner").scrollTop() + curSY - e.pageY); //1 вариант
      ner.scrollBy(curSX - e.pageX, curSY - e.pageY);
      curSX = e.pageX;
      curSY = e.pageY;
    }
  });
});
.ner {
  width: 100%;
  overflow: hidden;
  height: 100%;
  -webkit-user-select: none;
  -moz-user-select: none;
}

.cat {
  position: relative;
  width: 2202px;
  height: 2202px;
}

.cat>ul {
  display: block;
  list-style: none;
  width: 100%;
  margin: 0px;
  padding: 0px;
}

.cat>ul>li {
  display: inline-block;
  width: 50px;
  height: 50px;
  border: solid 1px black;
  box-sizing: border-box;
  margin: 0px;
  padding: 0px;
  position: relative;
}


text:
Q: Reverse the given string I'm writing a program to print the reverse of a given string. I am able to write the function to reverse the string but not able to take as many inputs as given in the test cases.
I've tried using "while" loop but I'm not able to get all the test cases as input. Maybe the syntax is wrong. I'm a newbie.
def rev(sample_string):
    return sample_string[::-1]

t_case = int(input())   #No. of testcases
i = 0

while i < t_case:
    sample_string = str(input(""))    #take as many inputs as no. of
                                      #testcases
    i =+ 1

print(rev(sample_string))

for sample input: 2, ab, aba --------
output should be: ba, aba           //(in separate lines)

A: If you want to save and print multiple strings, you need a datatype to do so.
List would do that job:
def rev(sample_string):
    return sample_string[::-1]

t_case = int(input())   #No. of testcases
i = 0
string_list = []  # List to store the strings

while i < t_case:
    string_list.append(str(input("")))    #take as many inputs as no. of
                                      #testcases
    i += 1

for string in string_list:  # iterate over the list and print the reverse strings
    print(rev(string))


text:
Q: Selenium/Python can't find input I'm using Selenium and Python to test my website and i found a problem. After clicking an anchor tag, i'm not able to find an input on the page.
I've found two "solutions" for this problem here in StackOverflow but they don't work for me.
This is my Python code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Inicia chrome > ingresa al host local > verifica que el título del sitio coincide con el de mi proyecto
driver = webdriver.Chrome('./chromedriver')
driver.get("http://localhost:8000")
assert "ArtStick" in driver.title

def main():

    # Ubica todos los HTML anchor  que estén dentro de un div
    anchors = driver.find_elements_by_css_selector('div a')
    # Recorre la lista creada
    for anc in anchors:

        # Obtiene el texto del anchor
        a_tag = anc.get_attribute("text")

        # Evalúa el texto de un anchor
        if 'Registrarse' in a_tag:

            # Envía el elemento () si su texto es igual a "Registrarse"
            vista_registro(anc)

def vista_registro(anc):

    # Hace click en el anchor para ir a la vista de registro
    anc.click()

    element = WebDriverWait(driver, 120).until(
        EC.presence_of_element_located((By.ID, "firstname"))
    )

    print(element)

main()

The problems appears at the "vista_registro" function. I'm clicking over the anchor tag > changing the actual window (not opening a new one) > trying to get my input by its ID: "firstname".
This is the register.blade.php file (Register view)
@extends('layouts.app')

@section('content')

      <form class="ui large form" method="POST" action="{{ route('register') }}">
        {{ csrf_field() }}

              Registrarse

ArtStick — Comunidad Artística

                <input type="text" name="firstname" id="firstname" placeholder="Nombre" value="{{ old('firstname') }}" required>

                <input type="text" name="lastname" id="lastname" placeholder="Apellido" value="{{ old('lastname') }}" required>

              <input type="text" name="username" id="username" placeholder="Usuario" value="{{ old('username') }}" required>

              <input type="email" name="email" id="email" placeholder="Correo elctrónico" value="{{ old('email') }}" required>

              <input type="password" name="password" id="password" placeholder="Contraseña" required>

              <input type="password" name="password_confirmation" id="password-confirmation" placeholder="Confirmar Contraseña" required>

              <input type="checkbox" tabindex="0" class="hidden" id="terms-input">
              Acepto los Términos y Condiciones

          <button class="daltong ui fluid large green submit button" type="submit">Enviar</button>

                ¿Posees una cuenta? Inicia sesión

¡No pierda ni un segundo más!

      </form>

            Desafíos

Participa en eventos mensuales de la comunidad.

            Álbumes

Organiza todos tus diseños.

            Críticas

Recibe o proporciona ánalisis.

            Favoritos

Agrega diseños a tu lista de recuerdos.

@endsection

Console LOG:
DevTools listening on ws://127.0.0.1:12629/devtools/browser/d2d7dc4e-b125-451f-88ee-bce85811d701
[372:5204:0313/203153.450:ERROR:gpu_process_transport_factory.cc(1009)] Lost UI shared context.
Traceback (most recent call last):
  File "selecode.py", line 39, in <module>
    main()
  File "selecode.py", line 21, in main
    a_tag = anc.get_attribute("text")
  File "C:\Users\Félix Bejarano\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 143, in get_attribute
    resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name})
  File "C:\Users\Félix Bejarano\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 628, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\Félix Bejarano\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Félix Bejarano\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=64.0.3282.186)
  (Driver info: chromedriver=2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91),platform=Windows NT 10.0.16299 x86_64)

driver.page_source CONSOLE LOG for the homepage:
<!DOCTYPE html>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

          <meta name="authUsername" content="guest" />
      <meta name="authUserID" content="0" />
      <meta name="authUserAvatar" content="public/defaults/avatars/default.jpg" />

    <meta name="csrf-token" content="Wn5vzZtSr8wadeJTRyZ9A0VsSkDDYFrfTmZ92FOD" />

    <title>ArtStick</title>

    <link href="http://localhost:8000/css/app.css" rel="stylesheet" />

    <link rel="stylesheet" type="text/css" href="http://localhost:8000/css/semantic.min.css" />

    <link rel="icon" href="http://localhost:8000/images/logo.png" />

      Indice

<input type="text" name="busqueda" placeholder="Búsqueda..." />

          Ingresar

          Registrarse

        Opciones

            Términos & Condiciones

            Ayuda

ArtStick 0.1.0

            Ver notas de la versión

¿Necesitas ayuda?

Registro

Cupcake ipsum dolor sit amet donut sugar plum. Sesame snaps pie bear claw biscuit. Toffee dessert macaroon I love. Chocolate caramels lollipop. Lollipop sweet cotton candy chocolate cake lemon drops gummi bears. Gummi bears dragée donut. Cookie cheesecake lemon drops. Cookie brownie fruitcake sesame snaps powder.

Ingreso

Tootsie roll sesame snaps caramels. Lemon drops brownie cheesecake sweet gummies. Pudding lollipop candy I love. Tiramisu cotton candy bonbon bonbon cupcake I love sugar plum. Ice cream icing halvah gummi bears tootsie roll jelly-o. Tootsie roll gingerbread jelly-o bonbon sweet fruitcake I love chocolate bar jujubes. Marzipan fruitcake carrot cake oat cake chocolate bar chocolate.

Perfil & Edición

Chocolate icing bear claw bear claw dragée fruitcake. I love croissant cookie caramels fruitcake danish gummies. Cake halvah cookie icing. Chocolate pie topping cupcake candy bonbon bear claw. Carrot cake jelly beans caramels liquorice soufflé cotton candy. Lemon drops cake biscuit apple pie chocolate cake jelly-o marzipan biscuit carrot cake. Chocolate cake marshmallow bear claw I love.

Administrar álbumes

Candy canes cookie cake cake. Icing jelly-o candy sweet roll jelly beans lollipop muffin cake marzipan. Apple pie ice cream brownie lollipop topping I love candy chocolate bar. Jelly-o topping gummi bears I love muffin marshmallow sweet cheesecake. Soufflé jujubes candy croissant cotton candy I love gummi bears macaroon.

Seguidos & Seguidores

Candy canes cookie cake cake. Icing jelly-o candy sweet roll jelly beans lollipop muffin cake marzipan. Apple pie ice cream brownie lollipop topping I love candy chocolate bar. Jelly-o topping gummi bears I love muffin marshmallow sweet cheesecake. Soufflé jujubes candy croissant cotton candy I love gummi bears macaroon.

A: The problem isn't with the registration form. The problem is with the outer loop you use to find and click the link to the registration page.
The CSS selector div a matches 7 elements—the 4th of which is the link to the registration page. After you click the 4th link, the browser navigates to the registration page and your vista_registro() function is excecuted—successfully.
After the function completes, it returns to the loop, where you attempt to click the 5th link. Because the browser is no longer on the home page, the elements you're looping over are "stale"—that is, they no longer exist on the page (they belonged to the previous page). Hence, a StaleElementReferenceException is raised.
A naive solution
You likely want to stop looping over the links after you click the link to the registration page. The quickest way to do that is to add a break after your call to vista_registro().
A far better solution
But there's a much simpler way to find a link with some particular text in Selenium: find_element_by_link_text.
link = driver.find_element_by_link_text("Registrarse")
link.click()

With this, you don't need a loop or a break.


text:
Q: Linkbutton click event not firing in master page I have the following in my master page:

<asp:LinkButton ID="lbtnSubmitLeaveRequest" runat="server" OnClick="lbtnSubmitLeaveRequest_Click" CausesValidation="false">Submit Leave Request</asp:LinkButton>

And in the code-behind:
  protected void lbtnSubmitLeaveRequest_Click(object sender, EventArgs e)
        {
            lbtnLeaveHidden_ModalPopupExtender.Show();
        }

But the click event is not firing.
EDIT: If I use a normal Button it works, but the linkbutton is not working.


text:
Q: Leaving margin at bottom of print (JSP, CSS) Could anyone please tell how shall I leave a margin at the bottom of the page even when the table is extending over a page (Please see the image). While printing I am missing the one or two rows at the bottom.
I have tried using @page{ body {margin-bottom:2cm;}} but it does not seem to work for me.


text:
Q: ¿Como desactivar el click de un botón con Thymeleaf? Tengo un botón que tengo desactivado mientras no tengo los datos del formulario guardado.
Esto lo hago con Thymeleaf:

Y me aparece el botón desactivado pero me permite hacer click en el igualmente.
Alguna solución para hacerlo por thymeleaf sin necesidad de usar javascript o jquery.
Muchas gracias por la ayuda

A: th:disabled no funciona en mi caso porque tengo un enlace , si fuera un  funcionaria correctamente.
La solución para desactivar el click de un botón es haciendo un condición para el th:href
Mi código queda de la siguiente manera


text:
Q: Peculiar properties of metric spaces V. Bogachev in his "Real and Functional Analysis" (page 6) makes the following remark:
"Although all the definitions given above coincide with those introduced in elementary calculus for sets on the real line, general metric spaces can substantially diffeer by their properties from the real line and $\mathbb{R}^n$ and their subsets. We shall have many occasions to see this below, but now we only observe that even subsets of the plane with the usual Euclidean metric can have rather peculiar properties. For example, if we take three points $a, b$ and $c$ on the plane such that $|a-b| = 1, |b-c|=2$ and $|a-c| = 5/2$, then in the obtained metric space the ball of radius $2$ centered at $b$ strictly contains the ball of the larger radius $9/4$ centered at $a$."
First question: is he using the standard euclidean metric here? If so, then how do we know that there exist three such points with the given properties?
Second question: Let $B(b, 2)$ and $B(a, 9/4)$ be the balls of radius $2$ and $9/4$ centered at $a$ and $b$ respectively. We want to show that $$B(a, 9/4) \subset B(b, 2).$$ Let $x \in B(a, 9/4)$. We want to show that $x \in B(b, 2)$ or $|x-b|<2$. However, $$|x-b| \leq |x-a|+|a-b| < 9/4 + 1 = 13/4 >2.$$ Clearly, this triangle inequality method fails. Do you guys know any way to show this claim?
I would appreciate any help. Thank you in advance.


text:
Q: Hot to handle an overwrite error in lua due to "file in use" I'm running a simple chunk in lua copy function that overwrite a file:
function copyFile(old, new)
  local i = io.open(old, "r")
  local o = io.open(new, "w")
  if i then
    o:write(i:read("*a"))
    o:close()
    i:close()
  end
end

Sometimes the "new" paths is "in use" and result in a VFS overwrite issue and prevent my code to run further.
How can I add an error handler that:
1. let the code go on if needed;
2. postpone copyFile function execution to let the "new" path to be no more in use
PS
I'm not a professional programmer and I know only Lua.. i'm more like a modder.


text:
Q: Terminating decimal #include<iostream>
#include<string>
#include<cstdlib>
using namespace std;

int main()
{
double a,b,res;

while(cin>>a>>b)
{
    res = a/b;

    if((res*b) == a)
        cout<<"Terminates"<<endl;
    else
        cout<<"Does not terminate"<<endl;
}

return 0;
}

So, here is my code to see if a/b results in terminating decimal or not. Some input is generating correct output, like:

1/3 : Does not terminates,
1/9 : Does not terminates,
1/7 : Does not terminates,
22/7 : Does not terminates,
1/2 : Terminates.

Except for 1/5 which should show: 1/5 : Terminates, but the output is: Does not terminates.
I know there are many issues for C++ floating points,tried google but it's like a puzzle.

A: There is an easy way to ask whether a ratio has an exact, terminating representation in a given radix, in your case 10.
Step 1 is to reduce it to its lowest terms. Divide top and bottom by their highest common factor.
Now only the denominator matters. If every one of its prime factors is also a prime factor of the radix, the fraction will terminate in that radix. 5 is a prime factor of 10, so 1/5 terminates in decimal. 5 is not a prime factor of 2, so 1/5 does not terminate in binary.

A: Only fractions like 1/2, 1/4, 1/8 and so on (or sum of such) are represented precisely in double. All others are approximations. So as a results 1/5 * 5 could equal 0.9999999999.
That's why one should never ever compare floating point numbers for equality (at least not without required precision, like testedValue - num < precision).


text:
Q: Cover/Landing page text position display I am creating a new website via Squarespace platform. The template is Brine Family 7.0.
https://kazoo-bulldog-snp5.squarespace.com/
Password to access is: 1234
I am trying to change to some text display that I am not able to do with the out of the box feature of Squarespace, but I can access some code sections to do some custom.
On the cover/landing page, I have some text displayed on the top of the page, above the logo that is centered. I want to display it on the bottom of the page, just like that:
https://ibb.co/fN1V5th
Do you have any code suggestion for that?
Thanks a lot for your kind help!

A: Use this code with your content. (Assuming content is placed in h1 tag)
h1{
    position: relative;
    bottom: 20%;
}

And, this community is not for suggestions. If you find problems or errors in your project code, you can ask in this community. Hope it helps!!.. Happy Coding!!


text:
Q: How to get numeric day in week? Android How do you get the numeric day of the week? For instance, Sunday is day 1 in the Gregorian calendar. Using SimpleDateFormat, d gets the day in month. Any solution for the numeric day of week?

A: It should be "F" : http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
new SimpleDateFormat("F").format(new Date());


text:
Q: does cpu core count matter for code compiling? I'm about to buy a laptop specifically for software development and want to be sure I don't end up with something I'm unhappy with, as I have experienced the pain of waiting 2+ minutes when compiling code on an old i3 laptop.
I'm looking at something with an i7-7500u cpu and 256GB ssd which I thought would do the job admirably, but then I saw that the cpu only has 2 cores / 4 threads.
 (https://www.intel.co.uk/content/www/uk/en/products/processors/core/i7-processors/i7-7500u.html)
Is compiling (C# MVC web application)  mainly based on single thread performance or is it likely that I'll see significant improvement spending a bit more and going for a 4 core / 8 thread cpu?

A: If the compiler would schedule all the CPU threads to build the program then it matters. If not, then I think there is not much benefit in increasing the CPU core/thread number.
I think you may check the CPU usage when you compile the program and check if the usage of CPU is high enough. If it is below 50%, then I think it only uses one or two CPU thread to build the program, and increasing CPU core/thread count will not give you much benefit.
Also, if you use the hdd, not the ssd in your old laptop, then I think the bottleneck of the performance would probably be the read/write to disk drive, not the CPU. The usage of ssd would help a lot to improve the performance.


text:
Q: What is the best drop-in replacement for numpy.interp if I want the null interpolation (piecewise constant)? numpy.interp is very convenient and relatively fast.  In certain contexts I'd like to compare its output against a non-interpolated variant where the sparse values are propagated (in the "denser" output) and the result is piecewise constant between the sparse inputs.  The function I want could also be called a "sparse -> dense" converter that copies the latest sparse value until it finds a later value (a kind of null interpolation as if zero time/distance has ever elapsed from the earlier value).
Unfortunately, it's not easy to tweak the source for numpy.interp because it's just a wrapper around a compiled function.  I can write this myself using Python loops, but hope to find a C-speed way to solve the problem.
Update: the solution below (scipy.interpolate.interp1d with kind='zero') is quite slow and takes more than 10 seconds per call (e.g. input 500k in length that's 50% populated).  It implements kind='zero' using a zero-order spline and the call to spleval is very slow.  However, the source code for kind='linear' (i.e. default interpolation) gives an excellent template for solving the problem using straight numpy (minimal change is to set slope=0).  That code shows how to use numpy.searchsorted to solve the problem and the runtime is similar to calling numpy.interp, so problem is solved by tweaking the scipy.interpolate.interp1d implementation of linear interpolation to just skip the interpolation step (slope != 0 blends the adjacent values).

A: The scipy.interpolate.interp1d can do all kinds of interpolation: 'linear','nearest', 'zero', 'slinear', 'quadratic, 'cubic'.
Please check the document: http://docs.scipy.org/doc/scipy-0.10.1/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d

A: Just for completion: The solution to the question is the following code which I was able to write with the help of the hints given in the updated answer:
def interpolate_constant(x, xp, yp):
    indices = np.searchsorted(xp, x, side='right')
    y = np.concatenate(([0], yp))
    return y[indices]

A: I totally agree that kind='zero' is extremely slow; for a large data set of million rows it can take literally 1000 times slower than 'linear' method. For "left-constant" interpolation - using the latest value - the following code works:
def approx(x, y, xout, yleft=np.nan, yright=np.nan):
    xoutIdx     = np.searchsorted(x, xout, side='right')-1
    return (np.where(xout<x[0], yleft, np.where(xout>x[-1], yright, y[xoutIdx])))

Coming from R background, this is equivalent to R's approx with f=0. I haven't found a clean way to do this for "right-constant" interpolation because python's np.searchsorted with side='right' pushes one index back if an xout value matches exactly with a value in x...


text:
Q: How to record mpeg2ts video with camera I have tried to generate MPEG2TS via MediaRecorder with camera.
My code is following.
mMediaRecorder.setOutputFormat(8); // OUTPUT_FORMAT_MPEG2TS
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setOutputFile("/sdcard/rec1.ts");

But, after recoding is finished, generated file(rec1.ts) is always 0 byte.
For other OutputFormat like "OUTPUT_FORMAT_MPEG_4", it works fine.
I don't know why it does not work..


text:
Q: Hidekazu Yukawa in Shenmue? The former Senior Managing Director of Sega, Hidekazu Yukawa (aka. "Mr. SEGA") appears in What's Shenmue?.
I heard that he also appears in Shenmue (apart from his face on the battery boxes in the Tomato Convenience Store).
Is this true? How and where can you meet him?

A: There are two situations where you can meet Hidekazu Yukawa in Shenmue.
You need the two toys Mr. Yukawa Happi and Mr. Yukawa Suit.
You can win them at the raffle (2nd and 3rd prize) in the Abe Store in Sakuragaoka. (This gameplay video (0:00 to 0:50) shows how Ryo wins these two figures.)
Takara Sushi
On the 9th of any month, between 8-9 pm, visit Takara Sushi in Dobuita. You'll see Mr. Yukawa standing behind the bar.
In the Japanese version, you can speak with him, after which he'll run away:

Ryo says something like "You are Mr. Yukawa, aren't you?", and Yukawa answers "Impossible!" and runs away.
In this version (I'm not sure if it's the EU/NA version or if it's the JP "US Shenmue") there is no dialogue:

If you leave and reenter the sushi bar, he will be standing there again.
Bar Yokosuka
(Maybe this only works in the Japanese versions.)
On the day after Nozomi tells Ryo how she feels about him, visit Bar Yokosuka in Dobuita (which triggers the cutscene where Ryo is told that friends are waiting for him at his home).
If you visit the bar after 11 pm, you'll see Mr. Yukawa having a drink in this cutscene.
You can see him in this video (from 0:17 on):

Sources:

*

*Thread in the Shenmue Dojo: Say Hello to Mr. Yukawa at Takara Sushi!!

*Shenmua Wikia: Hidekazu Yukawa

*Shenmue Neoseeker Wiki: Takara Sushi


text:
Q: Baffled by Multi-part identifier cannot be bound I am using a linked server to run a bunch of complicated queries. I had an issue I tracked down and simplified for testing.  The first 2 queries below work, but the third does not.
select top 10 AccountNumber
FROM S900PVXBIDWS01.FinancialEDW.MBFI.Dim_Account

select top 10 A.AccountNumber
FROM S900PVXBIDWS01.FinancialEDW.MBFI.Dim_Account A

select top 10 S900PVXBIDWS01.FinancialEDW.MBFI.Dim_Account.AccountNumber
FROM S900PVXBIDWS01.FinancialEDW.MBFI.Dim_Account

I need to use the last version for reasons I won't go into (lots of limitations).  Why won't it work when it clearly should?
The max for length identifiers is 128 I thought and I am under that. I am using SQL Server 2012.

A: Column references don't use four-part naming (which would then be five parts). Just use Dim_Account.AccountNumber, that should work fine.


text:
Q: Creating an array from a text file to call each line individually I've looked at multiple other similar questions but none of them worked with my code, and I gave up trying to look things up.
I'm trying to create a program that takes each line, which has a book title, from a file into a character array, because I need to call each book later, so book[1], book[2], etc. However, I cannot figure out how to create the array with my struct.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#define Num_Book 9

typedef struct book {
  char *book_name;
  size_t length;
  ssize_t title;
}BOOK;

int main(int argc, char* argv[])
{
  BOOK *Book;
  Book = (BOOK *) malloc (sizeof(BOOK));

  (*Book).book_name = NULL;
  (*Book).length = 0;
  char title_arr[Num_Book][50];
  //this is the array that I tried creating,
  //but it kept giving me warnings when I tried to compile

//opening my file
FILE *f_books;
f_books = fopen("books.txt", "r");

if (f_books == NULL)
{
    printf("Cannot open file for reading.\n");
}
printf("Book list\n");

while (((*Book).title = getline(&(*Book).book_name, &(*Book).length, f_books)) != -1)
{
    printf("%s", (*Book).book_name);
}

If anyone has any ideas, it is greatly appreciated. Thank you!

A: The simplest approach is to declare an array of structs in main(), using the Num_Book macro that you defined in the preprocessor directives. Since you are using getline(), you do not even need to manually allocate memory to store the strings; instead you can let the getline() function do the work. Note that getline() is not a Standard C function, but it is POSIX, and also a GNU extension. On some systems you may need to enable this function using a feature test macro, which is included in the code below.
To take advantage of the automatic memory allocation capability of getline(), you need to pass in a null pointer for the first argument, and the second argument should be a pointer to a size_t variable containing a value of zero.
In the loop that reads the data into the structs, temporary variables are used instead of directly assigning to the struct fields. This allows the current string to be inspected before the final assignment, so that empty lines are not stored as book records.
Remember that getline() keeps the \n character, so if the current line is non-empty, the terminating newline is replaced with a \0 terminator. Then the values held by the temporary variables are assigned to the appropriate fields of the current BOOK struct, temp_name and temp_length are reset to NULL and 0, and i is incremented.
You still need to free memory allocated by getline(), so this should be done before ending the program.
Note that in the original code, while you were checking to be certain that the file books.txt was successfully opened, you did not exit() here. This would lead to problems in the event that the file failed to open, when the program went on as if it had opened. You could handle the error differently; for example, it may be appropriate to instead ask the user for a different filename.
#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>

#define Num_Book  9

typedef struct book {
    char *book_name;
    size_t length;
    ssize_t title;
} BOOK;

int main(void)
{
    BOOK books[Num_Book];

    FILE *f_books;
    f_books = fopen("books.txt", "r");

    if (f_books == NULL)
    {
        fprintf(stderr, "Cannot open file for reading.\n");
        exit(EXIT_FAILURE);
    }

    printf("Book list\n");

    char *temp_name = NULL;
    size_t temp_length = 0;
    ssize_t temp_title;
    char *find;
    size_t i = 0;
    while ((temp_title = getline(&temp_name, &temp_length, f_books))
           != -1 && temp_name[0] != '\n') {

        /* Replace newline with '\0' */
        if ((find = strchr(temp_name, '\n')) != NULL) {
            *find = '\0';
        }

        books[i].book_name = temp_name;
        books[i].length = temp_length;
        books[i].title = temp_title;
        temp_name = NULL;
        temp_length = 0;

        printf("%s\n", books[i].book_name);
        ++i;
    }

    /* Still need to free allocated memory */
    for (size_t j = 0; j < i; j++) {
        free(books[j].book_name);
    }
    if (temp_name) {
        free(temp_name);
    }

    if (fclose(f_books) != 0) {
        fprintf(stderr, "Unable to close file\n");
        exit(EXIT_FAILURE);
    }

    return 0;
}

Program output:
Book list
The Sound and the Fury
So Long, and Thanks for All the Fish
Gargantua and Pantagruel
Foundation

If you need to dynamically allocate space for the books, you can modify the above code. Below is a version that does this, first by initializing a variable max_books to a reasonable starting value. Space is allocated and assigned to a pointer to BOOK, and when a new book is added the space is reallocated if necessary.
After all books have been added, the allocation can be trimmed to exact size. Note the use of identifiers instead of explicit types in the sizeof arguments. This is less error-prone and easier to maintain if types change in future iterations of the code. Also note that realloc() will return a null pointer in the event of an allocation error. Here, direct assignment to books would result in the loss of previously stored data, and a memory leak. For this reason, the address of the new allocation is first stored in temp; the value of temp is assigned to books only if it is not NULL.
The same allocations must be freed as before, but in addition, the dynamically allocated array must also be freed.
#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>

typedef struct book {
    char *book_name;
    size_t length;
    ssize_t title;
} BOOK;

int main(void)
{

    FILE *f_books;
    f_books = fopen("books.txt", "r");

    if (f_books == NULL)
    {
        fprintf(stderr, "Cannot open file for reading.\n");
        exit(EXIT_FAILURE);
    }

    char *temp_name = NULL;
    size_t temp_length = 0;
    ssize_t temp_title;
    char *find;
    size_t i = 0;
    BOOK *books;
    BOOK *temp;
    size_t max_books = 10;
    size_t num_books = 0;

    if ((books = malloc((sizeof *books) * max_books)) == NULL) {
        fprintf(stderr, "Unable to allocate books\n");
        exit(EXIT_FAILURE);
    }

    while ((temp_title = getline(&temp_name, &temp_length, f_books))
           != -1 && temp_name[0] != '\n') {

        ++num_books;

        /* Replace newline with '\0' */
        if ((find = strchr(temp_name, '\n')) != NULL) {
            *find = '\0';
        }

        /* Reallocate books if more space is needed */
        if (num_books == max_books) {
            max_books *= 2;
            if ((temp = realloc(books, (sizeof *books) * max_books)) == NULL) {
                fprintf(stderr, "Unable to reallocate books\n");
                exit(EXIT_FAILURE);
            }
            books = temp;
        }

        /* Store book data */
        books[i].book_name = temp_name;
        books[i].length = temp_length;
        books[i].title = temp_title;
        temp_name = NULL;
        temp_length = 0;

        ++i;
    }

    /* If you need books to be trimmed to minimum size */
    if ((temp = realloc(books, (sizeof *books) * num_books)) == NULL) {
        fprintf(stderr, "Unable to trim books allocation\n");
        exit(EXIT_FAILURE);
    }
    books = temp;

    /* Display list of books */
    printf("Book list\n");
    for (i = 0; i < num_books; i++) {
        printf("%s\n", books[i].book_name);
    }

    /* Still need to free allocated memory */
    for (i = 0; i < num_books; i++) {
        free(books[i].book_name);
    }
    free(books);
    if (temp_name) {
        free(temp_name);
    }

    if (fclose(f_books) != 0) {
        fprintf(stderr, "Unable to close file\n");
        exit(EXIT_FAILURE);
    }

    return 0;
}


text:
Q: Server IP Change Screen not shown in Android Nexus 7 I have used Mobilfirst 6.3 and using connectonstarup feature.

*

*When the application can't connect to the server

*The dialog box appears with 3 buttons

*There we click details to modify the settings of the Server IP

It works fine in all the tabs and mobile except the Google Nexus 7(Android 5.0). After i click the details screen the application stucks and i can't do anything.

A: The below was tested using WL.Client.connect(), because connectOnStartup is deprecated (no longer maintained and tested) and should no longer be used.
I cannot confirm this.
I've created the same scenario using a Nexus 7 (running Android OS 5.0.2).
After the application failed to connect to the MFP Server, I tapped on the Details button.
In the App Diagnostics screen you can do two things:

*

*Reload in order to try to connect again

*Copy the details that you see in the table

Tapping on the Reload button indeed reloads the app (and again shows me the dialog to either close the dialog, reload the app or view the app diagnostics table.
Copying the details copies the details and you can then paste them in an email screen or some other text editing window.
Both actions work for me.


text:
Q: How to optimize huge left join in mysql? I have two tables in my mysql database:
1) Videos
+----+--------+----------+------+----------+
| id | title  | category | year | director |
+----+--------+----------+------+----------+
|  1 | Title1 | Cat1     | 2021 | A.K.     |
|  2 | Title2 | Cat2     | 2020 | B.C.     |
|  3 | Title3 | Cat3     | 2000 | E.A.     |
+----+--------+----------+------+----------+

2) Videos_insights
+----------+------------+-------+-------+----------+--------+
| video_id |    date    | views | likes | dislikes | shares |
+----------+------------+-------+-------+----------+--------+
|        1 | 2021-03-20 |    13 |     2 |        3 |      1 |
|        1 | 2021-03-19 |    35 |     1 |        3 |      3 |
|        1 | 2021-03-18 |    68 |     5 |        6 |      5 |
|        1 | 2021-03-15 |    86 |     3 |        0 |      1 |
|        2 | 2021-02-13 |   234 |    15 |        1 |     34 |
|        2 | 2021-02-12 |    55 |    15 |        2 |      4 |
|        2 | 2021-02-10 |   331 |   255 |        0 |      0 |
+----------+------------+-------+-------+----------+--------+

And I want to get videos that had between watched 2021-03-01 to 2021-03-31. So the result table should look like this:
+--------+-------------------------------------------+
| title  |                date_range                 |
+--------+-------------------------------------------+
| Title1 | ["2021-03-20 - 2021-03-18", "2021-03-15"] |
+--------+-------------------------------------------+

In my MySQL database, I have about 100 000 videos and each video has about 100 video_insight.

*

*What is the best way to achieve the result table?

*How to optimize? I mean I do not want to make every GET request left join? It would take too long and my server will burn out.

A: I would express the dates individually:
select v.id, v.title,
       group_concat(date) as dates
from videos v join
     video_insights vi
     on vi.video_id = v.id
where vi.date >= '2021-03-01' and
      vi.date < '2021-04-01'
group by v.id;

Note that a left join is not appropriate because you are filtering the values.
If you really want to get the ranges, then you can use window functions with a gaps-and-islands approach:
select v.id, v.title, group_concat(date_range)
from videos v join
     (select vi.video_id,
             concat_ws(' - ', min(vi.date), nullif(max(date), min(date))) as date_range
      from (select vi.*,
                   dense_rank() over (partition by vi.video_id order by vi.date) as seqnum
            from video_insights vi
            where vi.date >= '2021-03-01' and
                  vi.date < '2021-04-01'
           ) vi
      group by vi.video_id, date - interval seqnum day
     ) vi
     on vi.video_id = v.id
group by v.id;


text:
Q: How do I set all program data and downloads to a separate drive? I have a 120GB SSD and a 1 TB HDD. I would like to dual boot Ubuntu alongside Windows 10. I installed Ubuntu on a partition of the HDD, but Windows 10 was installed on the SSD so using a boot manager wouldn't work and I'd have to change which drive to boot up in every time I start my computer. Is it possible for me to install Ubuntu on a small partition of my SSD, but only the actual OS itself, with all other data on the HDD?

A: Yes, it is possible, and supported.
The general way people split their installation is to put / (the root) on the smaller partition and /home (where most of the data is stored) on a larger partition. However, you can also put just /boot on the SSD and the rest of your OS on the HDD.
However*2, you can install Ubuntu completely on the HDD without worrying about split drives and double bootloaders and all that, which is what I recommend you do. When you install Ubuntu, it will install GRUB to the EFI partition on your primary hard drive, which should be the SSD. GRUB will be able to boot into both Ubuntu and the Windows bootloader, even if they are on separate drives. All you need to do is install Ubuntu, and it should configure everything for you.
I recommend choosing the Something Else... option in setup when prompted and manually telling Ubuntu to install to the partition you want there. While in this setup, also make sure that the EFI partition is going to mount as /boot/efi.
If you need any more details, comment, and I'll help out.


text:
Q: How to show Form when button is clicked in react? I am learning react and trying to create a car portal where on the basis of the availability of a car the user can book a car by clicking on the button. But when I click  the button it shows the form for all available cars, how do I show the form only for the car whose button is clicked?.
Below is my App.js file
import React from "react";

const cars = [
  {
    id: 1,
    name: "Mruti",
    price: 5.2,
    available: false,
    rental_price: 5000,
    type: "Hatchback",
  },
  {
    id: 2,
    name: "Rnault",
    price: 5.2,
    available: true,
    rental_price: 3000,
    type: "SUV",
  },
  {
    id: 3,
    name: "Adi",
    price: 5.2,
    available: false,
    rental_price: 5000,
    type: "SUV",
  },
  {
    id: 4,
    name: "Hundai",
    price: 209,
    available: false,
    rental_price: 100000,
    type: "Luxury",
  },
  {
    id: 5,
    name: "Aton",
    price: 500,
    available: true,
    rental_price: 500000,
    type: "Luxury",
  },
  {
    id: 6,
    name: "Ercedes",
    price: 35,
    available: false,
    rental_price: 50000,
    type: "Sedan",
  },
  {
    id: 7,
    name: "BMW",
    price: 32,
    available: false,
    rental_price: 50000,
    type: "Hatchback",
  },
];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { showForm: false };
  }

  showForm = () => {

    return (

        <form id="add-app">
          Price :
          <input type="text" />

           Hours :
          <input type="text" />

          <button>Book</button>
        </form>

    );
  };

  render() {

    return (

        {cars.map((car) => (

{car.name}

{car.price}

              {car.available === true ? (
                <>

Available

                  <button
                    onClick={() => {
                      this.setState({showForm:true})
                    }}

                  >
                    Rent car
                  </button>
                  {this.state.showForm ? this.showForm() : null}
                </>
              ) : (

Unavailable

              )}

        ))}

    );
  }
}

export default App;

A: Instead of using a boolean state (this.setState({ showForm: true })) you might want to store the car object itself in state (this.setState({ car })).
Then you can check if the car in state is not null rather than checking if showForm is true, and your showForm() method can have access to the currently selected car through the state.

A: This will work:
{this.state.showForm && (<this.showForm />)}

Btw, is there any specific reason you're using a functional component inside a class component?
If not I think it's inefficient to have it inside the App class since it'll be creating new showForm components for each App instance.


text:
Q: Need to place code inside a function I need to place this code inside a function within functions.php
How do I go about doing this?
EDIT: This is in regards to an answer I received about a problem with Headers.
"isn't inside a function. So it's being called as soon as the file loads. This means all output is sent to the screen immediately This stuff should be inside a function which is then called at the right time (like the other bits)."
The problem is, I don't know how to put this code inside a function.
    add_shortcode("snap", "wpr_snap");
$user_ej = wp_get_current_user();
if ($user_ej->roles[0] == 'contributor')
{ ?>
  <style type="text/css">
    #menu-dashboard, #toplevel_page_wpcf7, #menu-tools
    {
        display:none;
    }
</style>
<?php }
add_filter(  'gettext',  'change_post_to_portfolio'  );
add_filter(  'ngettext',  'change_post_to_portfolio'  );

A: Based on the content of your code you should probably rewrite it like this:
    add_shortcode("snap", "wpr_snap");
function add_extra_css() {
$user_ej = wp_get_current_user();
if ($user_ej->roles[0] == 'contributor')
{ ?>
  <style type="text/css">
    #menu-dashboard, #toplevel_page_wpcf7, #menu-tools
    {
        display:none;
    }
</style>
<?php }
}
}
add_action( 'wp_head', 'add_extra_css' );
add_filter(  'gettext',  'change_post_to_portfolio'  );
add_filter(  'ngettext',  'change_post_to_portfolio'  );