text:
Q: Not receiving the $message variable in view from a Laravel HTML Mailable (NON Markdown)
I've read several similar questions related to this problem but all refer to Markdown mailables.
I'm trying to send inline images in the mailables but I haven't found a way to do it properly (Laravel 5.5).
The documentation says this:

Inline Attachments
Embedding inline images into your emails is typically cumbersome; however, Laravel provides a convenient way to attach images to your emails and retrieving the appropriate CID. To embed an inline image, use the embed method on the $message variable within your email template. Laravel automatically makes the $message variable available to all of your email templates, so you don't need to worry about passing it in manually:

    Here is an image:

    embed($pathToFile) }}">

But, when doing that I receive this error:

Undefined variable: message (View: /path/to/project/resources/views/mails/new_user_welcome.blade.php)

I know that this has a limitation when using a Markdown message but I'm not using one.

This are the related files:
Mail/NewUserWelcomeEmail.php
class NewUserWelcomeEmail extends Mailable
{
    use SerializesModels;

    public function build()
    {
        return $this->view('mails.new_user_welcome');
    }
}

Resources/views/mails/new_user_welcome.blade.php
@extends('layouts.mail')

@section('content')

    embed(url("storage/images/inline_image.png")) }}"
    alt="An inline image" />

@endsection

App/Http/Controllers/UserController.php
public function register(NewUserRequest $request)
{
    // some code

    Mail::to($user)->send(new NewUserWelcomeEmail($user));

    return 'done';
}

A: Well, to be honest, I haven't found a way to make this work properly. I mean, as it stands, this should work. Maybe is my Laravel installation (?)..
Anyway, I did make it work with a workaround.
1) Using Eduardokum' Laravel Mail Auto Embed package, this basically generate a CID for each of your media assets.
But after adding this package this didn't work as expected.. so I:
2) change the way I was referencing my assets, from this:

To this:

Now it works.

A: In my case (Larvel 5.5), I've managed, to modify header logo, in both html and markdown.
Laravel documentation, although really great, could be better in this regard.
Anyway, follow these steps, and you should be fine...
1 - Publish mail templates via:
php artisan vendor:publish --tag=laravel-mail

so you can easily modify your mail source files.
2 - Modify message.blade.php in resources/views/vendor/mail/html with this:
@slot('header')
    @component('mail::header', ['url' => config('app.url')])

    @endcomponent
@endslot

3 - All your emails should receive logo via CID from now.
Note:
In this example Laravel, automatically converts assets to CIDs, so you don't need to call $message->embed(... at all...
Please test extensively, with these html/markdown directories and blade directives going on. It is kinda tricky, but it definitely, does its magic...

A: if you can use like this than it can be work other wise you don't use $message variable in mail blade
Mail::send('emails.welcome', $data, function ($message) {
    $message->from('us@example.com', 'Laravel');
    $message->to('foo@example.com')->cc('bar@example.com');
});

if you don't want use this method than you can use like this
https://code.tutsplus.com/tutorials/how-to-send-emails-in-laravel--cms-30046
it can be work like this.

A: You have to define the File Path Variable in your Mailable as public property -> example $pathToFile.
If you have the file path from outside of the mailable you can pass in with the constructor.
class NewUserWelcomeEmail extends Mailable
{
    use SerializesModels;

    // Must be public
    public $pathToFile;

    /**
    * Create a new message instance.
    */
    public function __construct(string $pathToFile)
    {
        $this->pathToFile= $pathToFile;
    }

    public function build()
    {
        return $this->view('mails.new_user_welcome');
    }
}

Then it works as expected in your view like this:
@extends('layouts.mail')

@section('content')

    embed(url($pathToFile)) }}" alt="An inline image" />

@endsection

A: This way you can embed images in markdown Laravel mails (used here to eg embed a logo):
app/Mail/Demo.php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Swift_Image;

class Demo extends Mailable
{
    use Queueable, SerializesModels;

    public $image_logo_cid;

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        // Generate a CID
        $this->image_logo_cid = \Swift_DependencyContainer::getInstance()
            ->lookup('mime.idgenerator')
            ->generateId();

        return $this->withSwiftMessage(function (\Swift_Message $swift) {
            $image = Swift_Image::fromPath(resource_path('img/make-a-wish-logo-rev.gif'));
            $swift->embed($image->setId($this->image_logo_cid));
        })->subject('My awesome markdown mail with an embedded image')
            ->markdown('emails.demo');
    }
}

resources/views/emails/demo.blade.php
@component('mail::message')
    {{-- Just embedding this image in the content here --}}

@endcomponent

Alternatively you could embed the mail::layout component and put the image in your header:
resources/views/emails/demo.blade.php
@component('mail::layout')
    {{-- Header --}}
    @slot('header')
        @component('mail::header', ['url' => config('app.url')])

        @endcomponent
    @endslot

    {{-- Body --}}

    {{-- Subcopy --}}
    @slot('subcopy')
        @component('mail::subcopy')

        @endcomponent
    @endslot

    {{-- Footer --}}
    @slot('footer')
        @component('mail::footer')

        @endcomponent
    @endslot
@endcomponent

Or if you always want this header just edit the resources/views/vendor/mail/html/header.blade.php file (available after php artisan vendor:publish --tag=laravel-mail). Then of course you need to create the CID/Image with every mailable as seen in the app/Mail/Demo.php (or have a base controller for that).


text:
Q: How to mark subticks at the end of a smooth curve? \documentclass[border=10pt]{standalone}
\usepackage{pstricks-add}
\begin{document}
\begin{pspicture}[showgrid](-1,3)(2,7)
\psparametricplot[algebraic]{-1}{1.56}{t|t^2+4}%
\pscurvepoints{-1}{1.56}{t|t^2+4}{L}%
\pspolylineticks[metricInitValue=1,ticksize=-2pt 2pt,Os=1,Ds=.2]{L}{ ds }{0}{40}
\multido{\iA=0+1,\iB=1+2}{20}{\Put{6pt;(LNormal\iA)}(LTick\iA){\tiny \iB}}
\end{pspicture}
\end{document}

Question: How to mark subticks at the end of a smooth path?

A: You have to use a multiple distance of the ticks of the curve,
which is not easy to know for a curve. However:
\psparametricplot[algebraic]{-1}{1.53}{t|t^2+4}%
\pscurvepoints{-1}{1.53}{t|t^2+4}{L}%

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flutter - How check string value from sharedPreferences How check string value from sharedPreferences list is null or empty? If null or empty go to Login page else print value.
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final myStringList = sharedPreferences.getStringList('my_sharedPreferences_list') ?? [];

if ( **myStringList[0]  is null or empty**   ) {
  print('> EMAIL not found!');
  Navigator.of(context).pushReplacement(MaterialPageRoute(
      builder: (context) => Login()
  ));
}
else { print(myStringList[0].toString()); }

A: getStringList returns nullable list of String
List<String>?. You can simply check
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final myStringList =
        sharedPreferences.getStringList('my_sharedPreferences_list');

if(myStringList==null ){
 print('> EMAIL not found!');
  Navigator.of(context).pushReplacement(MaterialPageRoute(
      builder: (context) => Login()
  ));
}
else { print(myStringList[0].toString()); }

A: You can check if your list is null  or empty using this command myStringList == null || myStringList.isEmpty .
|| indicates or operator

A: You have two way to check null
The first likes Yeasin if(myStringList==null )
and the second set default value when you get like this
final myStringList =
    sharedPreferences.getStringList('my_sharedPreferences_list') ?? '';

Then check with empty or not empty
if (myStringList.isEmpty) {}
if (myStringList.isNotEmpty) {}


text: Q: Should I give my iTunes Connect credentials to my developer? so I hired a developer on an online platform and he has made for me a game and now has to upload to my iTunes Connect account. But he says that he needs my credentials, because I am an individual and I cannot add him as a developer and so he cannot make a certificate for the app….


text:
Q: Not getting the right degree of parallelism for http queries when using Parallel.foreach I am trying to perform 2000 http queries at the same time.
Tests conducted with this code (consisting mostly of responding servers) run in about 15 seconds :
    public void testTasks()
    {
        var urls = new List<string>();
        urls.AddRange(createUrls());
        var start = DateTime.Now;
        ConcurrentQueue<string> contents = new ConcurrentQueue<string>();
        Task.WaitAll(urls.Select(url =>
        {
            var client = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
            return client.GetAsync(url).ContinueWith(response =>
            {
                try
                {
                    var content = response.Result.Content.ReadAsStringAsync().Result;
                    contents.Enqueue(content);
                }
                catch (Exception e)
                {
                }
            });
        }).ToArray());
        var end = DateTime.Now;
        var time = end - start;
        Console.WriteLine("Time spent in Tasks : " + time.TotalSeconds);
        Console.WriteLine("Queue size : " + contents.Count);
    }

Now I perform the same test, with Parallel.foreach and i get a running time of 1 minute, 18 seconds :
    public void testParallelForeach()
    {
        var urls = new List<string>();
        urls.AddRange(createUrls());
        var start = DateTime.Now;
        ConcurrentQueue<string> contents = new ConcurrentQueue<string>();
        Parallel.ForEach(urls, new ParallelOptions() { MaxDegreeOfParallelism = urls.Count }, url =>
        {
            var client = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
            try
            {
                string content = client.GetStringAsync(url).Result;
                contents.Enqueue(content);
            }
            catch (Exception e)
            {

            }
        });
        var end = DateTime.Now;
        var time = end - start;
        Console.WriteLine("Time spent in ParallelForeach : " + time.TotalSeconds);
        Console.WriteLine("Queue size : " + contents.Count);
    }

As you can see, I am using a MaxDegreeOfParallelism equal to the number of servers. But it does not seeem to be enough.
EDIT
So my questions are :
-Why do I have such a difference in performance ?
-Can we achieve the same performances using parallel.foreach ?

A: I want to provide a slightly different angle than Scott Chamberlain provided. It does not matter whether you use sync or async IO. What matters is what effective DOP (degree of parallelism) is being employed to send HTTP requests.
Different web services will prefer different DOPs and you need to empirically determine the optimal DOP.
The number of CPU cores has nothing to do with the optimal IO DOP. Just making sure this is understood.
The first solution is bad because it chooses DOP = urls.Count. The second one is bad because it chooses DOP to be whatever the TPL decides (it is not equal to MaxDegreeOfParallelism = urls.Count because that is a maximum). None of these values are likely to be optimal.

*

*Use one of the well-known techniques to implement a parallel async foreach with exact DOP (e.g. http://blogs.msdn.com/b/pfxteam/archive/2012/03/05/10278165.aspx).

*Determine the optimal DOP experimentally.

This is a very simple problem to solve. You fell into the common trap of using the TPL's built-in facilities to solve the problem. The TPL lacks the required tools to appropriately solve this.
Also note that calling Result negates the benefits of async IO (which are very helpful here). Use await instead.

A:
-Why do I have such a difference in performance ?

Because there is no point in using Parallel.ForEach for IO bound work. Parallel.ForEach is designed for CPU bound work only. Also Parallel.ForEach has a "ramp up" effect, it does not start at MaxDegreeOfParallelism, it starts with 1 thread then keeps adding threads as it detects the work could use more threads until it reaches MaxDegreeOfParallelism (there is a reason it is called "MaxDegreeOfParallelism" not "DegreeOfParallelism"). Using IO bound work instead of CPU bound work greatly messes up that scheduling algorithm.

-Can we achieve the same performances using parallel.foreach ?

No you can't because you are using the wrong tool for the job, the incorrect approach will always outperform a more correct approach (which your first method is)
However using a Async method then immediately calling .Result on it is still a wrong approach, the best way would use proper async/await (also use a Stopwatch instead of a DateTime to mesure elapsed time and dispose of your disposable classes you created)
public async Task TestTasksProperly()
{
    var urls = new List<string>();
    urls.AddRange(createUrls());

    var stopwatch = Stopwatch.StartNew();
    ConcurrentQueue<string> contents = new ConcurrentQueue<string>();
    await Task.WhenAll(urls.Select(url => QueryUrl(url, contents)))).ConfigureAwait(false);

    var time = stopwatch.ElapsedMilliseconds / 1000.0;
    Console.WriteLine("Time spent in Tasks : " + time);
    Console.WriteLine("Queue size : " + contents.Count);
}

private static async Task QueryUrl(string url, ConcurrentQueue<string> contents)
{
    using (var client = new HttpClient {Timeout = TimeSpan.FromSeconds(10)})
    {
        using (var response = await client.GetAsync(url).ConfigureAwait(false))
        {
            try
            {
                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                contents.Enqueue(content);
            }
            catch (Exception e)
            {
            }
        }
    }
}


text:
Q: How to use following API with WordPress? I have an old client who wants to integrate one system on their WordPress website.
The company is fairly new called LYFSIZE which basically takes the picture of the users and provides them the exact size measurements for the apparels.
I was successfully able to achieve the steps provided in this file - https://drive.google.com/file/d/1OZN4TJasAkLNV-vbg0MZQN045tcA906l/view?usp=sharing
Now, LYFSIZE has sent me documentation on how to use their API on the WordPress site.
https://drive.google.com/file/d/1xxe7PVoJBW8PTU9FIfNLYhF2qItrX5p4/view?usp=sharing
I have never used API with the WordPress site and I am completely clueless on the procedure. I tried to follow the steps and was able to reach the final steps.
However, I am not understanding how to put this on the subdomain to actually test it on the WP site. How to initialize the API? How to use the SDK files on the WP site?
I have got SDK Files, Demo API keys.
I know this is like asking for training but it would be really nice if someone could guide me little or otherwise I don't know what I would say to the client.


text:
Q: Raising OpenURI::HTTPError caused wrong number of arguments error I am testing how a method handles a 302 HTTPError exception. I tried to stub the one method call to raise one programmatically, however it keep complaining that wrong number of arguments error (0 for 2)
the code tested this particular line:
document = Nokogiri.HTML open(source_url)

and in the spec I stubbed it like this:
subject.stub(:open).and_raise(OpenURI::HTTPError)
subject.should_receive(:ended=).with(true)
subject.update_from_remote

I don't think it is related to Nokogiri.HTML() or Open-uri.open(), so why is this happening?
Also, how would I try to make this HTTPError as a 302 redirect error? Thanks

A: I found out that OpenURI::HTTPError's constructor requires two parameters. Rspec by default will call the error class's new method with no parameter, which cause this error. So I need to manually create an error object by passing the required parameters.
exception_io = mock('io')
exception_io.stub_chain(:status,:[]).with(0).and_return('302')
subject.stub(:open).with(anything).and_raise(OpenURI::HTTPError.new('',exception_io))

A: This is a very late reply, but for others who may find this helpful: if you use the FakeWeb gem in conjunction with Nokogiri, you can do this kind of testing without having to get so involved with the internals of the code. You can register a URI with FakeWeb in your test, and tell it what to return. For example:
FakeWeb.register_uri(:get, 'http://www.google.com', :status => ['404', 'Not Found'])

The URI argument you provide needs to match the URI your method is calling. FakeWeb will then intercept the call, and return the status you provide.


text:
Q: Mute a youtube video for website background I have a website that I'd like to use a full width video on. I previously had it fully working but randomly the once muted video plays sound. I haven't touched the code at all from when it was working (no sound) until now. I checked on the tutorial I got the code from and the sound is also unmuted there, so I'm curious if its a youtube thing.
Here is the link of the tutorial:
http://bootsnipp.com/snippets/featured/ful-screen-video-background
this is where it should be muted, in the anchor tag within the data-property is mute:true

  bg

Full Width Video

Enjoy Adding Full Screen Videos to your Page Sections

I tried using muted:true instead because I can across that in a google search but it does nothing as well, all other searches say mute:true should work, can anyone see an issue with this? or know of another way to mute the sound?

A: You can try this library . It is having option for MUTE and other awesome features are also there.

A: You got this library as well. You only have to include the js file and call the function like this for example:
$(document).ready(function() {
    ytbg("vQWlNALvbhE", 0, 17, 1);
});

as an explanation:
ytbg("video link", starttime, endtime, volume).


text:
Q: For each value in a series, return value from another pandas series, if the values of series1 are a substring in series2 In the example bellow, I am trying to make a new column df1['new']. What I want is to look up the values of df1['city'], and see if they are a substring of any of the rows in df2['des']. If they are, I want df1['new'] to have the values of df2['des']: (in this example, a description of the city).
df1['city']:
    city
0   New York
1   Amsterdam
2   London
3   Karachi

df2['des']:
    des
0   London is the capital and ...
1   Amsterdam and New York are two...
2   Karachi is the capital of...

This is what I want
        city                                  new
0   New York    Amsterdam and New York are two...
1  Amsterdam    Amsterdam and New York are two...
2     London        London is the capital and ...
3    Karachi         Karachi is the capital of...

At the moment, the closest I have gotten to solve it is this:
df['new'] = df.loc[df.des.str.contains("London"), 'des']

Which outputs:
    city            new
0   New York        NaN
1  Amsterdam        NaN
2     London        London is the capital and ...
3    Karachi        NaN

What I want is to, instead of just passing in "London" in the conditional, pass in the entire series df1['city']. If I do that though, i get this error: TypeError: 'Series' objects are mutable, thus they cannot be hashed

A: Let's assume you just want one match, in the case where there are duplicate matches. Otherwise, any solution will be more complex.
With these problems, instead of iterating rows, it's often better to iterate your cities and use pd.Series.str.contains. For example, you can create a dictionary:
d = {city: df2.loc[df2['des'].str.contains(city, regex=False), 'des'].iat[0] \
     for city in df1['city']}

Then map to df1 via pd.Series.map:
df1['des'] = df1['city'].map(d).fillna('No match found!')

A: Another solution using list comprehension:
df1['new'] = [next((i for i in df2['des'] if x in i), 'Not found!') for x in df1['city']]

And another using regex and str.extractall:
matches = df2['des'].str.extractall('({})'.format('|'.join(df1['city']))).reset_index(0)
m = matches.set_index(0)['level_0'].map(df2['des'])
df1['new'] = df1['city'].map(m).fillna('No match!')


text:
Q: How do I "give up" editing mode and view a document as read-only without closing and reopening? In my SharePoint 2010 environment I currently have the document library setting "Require documents to be checked out before they can be edited?" set to no.  All of my users are on Office 2007 and Office 2010, but most are on 2007.
If one of my users opens a document (almost always an Excel or Word file) it usually opens in edit mode without a prompt because usually they aren't opening it directly from the document library.  This isn't really a problem until someone else needs to be able to edit the document at which time the first user obviously has to close the document and reopen it after the other user has opened it and claimed editing rights.
If you open a document specifically in read-only there's usually a button in the information bar that allows you to take editing rights, but is there any way to back down from editing mode to read-only from within an Office document?

A: In my experience, the answer is no. You must close the document. This will allow another user to click on the document for editing.
I would advise your users to open the document from the SharePoint site if they want to edit the document or use a link to the document to quickly grab a read only copy.

There was some other discussion in the question around the difference between check in/out and the document being locked for editing. The major differences are:

*

*Check In/Out can be disabled on the library. You are able to see in the library when someone has document checked out.

*You cannot disable the "locked for editing" SharePoint behavior. You are not able to see when someone is editing it. This sometimes results in this message: [Document] is locked for editing by [Someone].

A: Steps 1 to 4 of this might be of help, but it isn't exactly what you are after:
http://smallbusiness.chron.com/excel-prompt-opened-read-write-48685.html
I don't know if it is possible to set the "read-only recommended" option as default for all saved / newly created files.
From the linked page:
Step 1
Open the workbook you want to save with a read-only prompt.
Step 2
Click the "File" tab on the ribbon and select "Save As" from the menu to open the Save As dialog box.
Step 3
Click the "Tools" button and select "General Options" from the drop-down menu to open the General Options dialog box.
Step 4
Click the box next to the "Read-only recommended" option. When someone accesses the file, Excel will display a prompt advising the user that the workbook should be opened as read-only unless changes are necessary.

A: I (seem to) have achieved this by simply going to the 'View' tab and selecting 'Read view'. I have yet to confirm this, however, with my colleagues

A: In our environment user is notified that this document is checked out by so and so and you can open it as read only.


text:
Q: For OkHttp, Does SSLSocketFactory use SocketFactory first? I'm currently wanting to use ConnectivityManager.NetworkCallback on Android, hoping to direct all REST calls to a "good" network with OkHttp. While looking at OkHttp's API, should I implement both SocketFactory and SSLSocketFactory to redirect calls to another network, or will SocketFactory be enough?

A: Yes, OkHttp always starts with a regular socket first. You can see this in RealConnection.java.
Because connecting to an HTTPS server over an HTTP proxy requires a plaintext CONNECT request, it's unlikely that any other approach would work.


text:
Q: Splitting an N dimensional numpy array into multiple 1D arrays I have a simulation model that integrates a set of variables whose states are represented by numpy arrays of an arbitrary number of dimensions. After the simulation, I now have a list of arrays whose elements represent the variable state at a particular point in time.
In order to output the simulation results I want to split these arrays into multiple 1D arrays where the elements correspond to the same component of the state variable through time. Here is an example of a 2D state variable over a number of time steps.
import numpy as np

# Arbitrary state that is constant
arr = np.arange(9).reshape((3, 3))

# State variable through 3 time steps
state = [arr.copy() for _ in range(3)]

# Stack the arrays up to 3d. Axis could be rolled here if it makes it easier.
stacked = np.stack(state)

The output I need to get is:
[np.array([0, 0, 0]), np.array([1, 1, 1]), np.array([2, 2, 2]), ...]

I've tried doing np.split(stacked, sum(stacked.shape[:-1]), axis=...) (tried everything for axis=) but get the following error: ValueError: array split does not result in an equal division. Is there a way to do this using np.split or maybe np.nditer that will work for the general case?
I guess this would be equivalent to doing:
I, J, K = stacked.shape

result = []

for i in range(I):
    for j in range(J):
        result.append(stacked[i, j, :])

Which is also the ordering I'm hoping to get. Easy enough, however I'm hoping there is something in numpy that I can take advantage of for this that will be more general.

A: If I reshape it to a 9x3 array, then a simple list() will turn it into a list of 3 element arrays:
In [190]: stacked.reshape(-1,3)
Out[190]:
array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2],
       [3, 3, 3],
       [4, 4, 4],
       [5, 5, 5],
       [6, 6, 6],
       [7, 7, 7],
       [8, 8, 8]])
In [191]: list(stacked.reshape(-1,3))
Out[191]:
[array([0, 0, 0]),
 array([1, 1, 1]),
 array([2, 2, 2]),
 array([3, 3, 3]),
 array([4, 4, 4]),
 array([5, 5, 5]),
 array([6, 6, 6]),
 array([7, 7, 7]),
 array([8, 8, 8])]

np.split(stacked.reshape(-1,3),9) produces a list of 1x3 arrays.
np.split only works on one axis, but you want to split on the 1st 2 - hence the need for a reshape or ravel.
And forget about nditer.  That's a stepping stone to reworking code in cython.  It does not help with ordinary iteration - except that when used in ndindex it can streamline your i,j double loop:
In [196]: [stacked[idx] for idx in np.ndindex(stacked.shape[:2])]
Out[196]:
[array([0, 0, 0]),
 array([1, 1, 1]),
 array([2, 2, 2]),
 array([3, 3, 3]),
 array([4, 4, 4]),
 array([5, 5, 5]),
 array([6, 6, 6]),
 array([7, 7, 7]),
 array([8, 8, 8])]

======================
With the different state, just stack on a different axis
In [302]: state
Out[302]:
[array([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]]), array([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]]), array([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]])]
In [303]: np.stack(state,axis=2).reshape(-1,3)
Out[303]:
array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2],
       [3, 3, 3],
       [4, 4, 4],
       [5, 5, 5],
       [6, 6, 6],
       [7, 7, 7],
       [8, 8, 8]])

stack is rather like np.array, except it gives more control over where the dimension is added.  But do look at it's code.

A: You could use np.split on a flattened version and cut into appropriate number of parts as 1D lists, like so -
np.split(stacked.ravel(),np.prod(stacked.shape[:2]))

Sample run -
In [406]: stacked
Out[406]:
array([[[0, 0, 0],
        [1, 1, 1]],

       [[2, 2, 2],
        [3, 3, 3]],

       [[4, 4, 4],
        [5, 5, 5]],

       [[6, 6, 6],
        [7, 7, 7]]])

In [407]: np.split(stacked.ravel(),np.prod(stacked.shape[:2]))
Out[407]:
[array([0, 0, 0]),
 array([1, 1, 1]),
 array([2, 2, 2]),
 array([3, 3, 3]),
 array([4, 4, 4]),
 array([5, 5, 5]),
 array([6, 6, 6]),
 array([7, 7, 7])]


text:
Q: Sending credentials with JavaScript XMLHttpRequest is not working I try to send credentials with an XMLHttprequest like the following:
request.open("POST","https://myurl.com",true,"domain\\user","password");
...

This is for an Android App using Phonegap. On my mobile it does not even connect to the server when i use "domain\\user". If I only put  "user" in there, without domain,  it works just fine. And in the Browser both ways work out :-(
What am I missing, I am really new to this stuff...

A: If anyone else has the same problem: It was because in Android the backslashes are not getting encoded. After I used "encodeURIComponent()" it worked.


text:
Q: Partial Restore Is it possible to restore from a full backup or parrallel db, only certain records with original IDs?
Lets say records were deleted from a specific date, can those records be restored without restoring the entire table?
So to be clear lets say I have records 500 - 720 still in a backup or parrallel db, but the table has had new records added since the backup so dont want to lose them either. So simply want to slot records 500 - 720 back with their original IDs to the current table.

A: If you have a copy of the db, that's going to be the easiest and quickest way - create a copy of your table with just the rows you need:
CREATE TABLE table2
AS
SELECT * FROM table1
WHERE  table1.ID BETWEEN 500 AND 720

then dump table2 with mysqldump:
mysqldump -u -p thedatabase table2 > table2_dump.sql

and ship the dump to the main db, run the dump when using a temporary database, and insert the missing records using:
INSERT INTO table1
SELECT *
FROM   temp_db.table2

If you don't have a copy of the db with the missing records, just a backup, then I don't think you can do such a selective restore. If you just have a single dump file of the entire db, then you will have to restore a complete copy to a temporary db, and insert the missing records in a similar manner to the way I've described above, but with a where clause in the insert.


text:
Q: Ajax response not updating in php while loop I am having a slight problem figuring out why this ajax response isn't updating properly. I have a php while loop which lists gallerys in text format, i am using . It is getting details from the php page but only for one result so essentially when you hover over the name a qtip tooltip box pops up so you can edit the name of the gallery. The problem is it only lists one result for all results in the loop.
PHP & HTML
    <?php
            $MemberGalleriesQuery = $bapcity->query("SELECT * FROM CroMemberRetailGalleries WHERE UserID='".$_SESSION['user_id']."' ORDER BY GalleryID DESC");
            $MemberGalleriesCount = $MemberGalleriesQuery->num_rows;

            if ( $MemberGalleriesCount )
            {
                $BaseHeight = 150;
                $GalleriesBoxHeight = $BaseHeight + ( 20 * $MemberGalleriesCount );
                echo '

Manage Galleries

                Click Gallery To Edit

                ';

                while($GalleryData = $MemberGalleriesQuery->fetch_assoc())
                {
                    echo '>> '.$GalleryData['GalleryName'].' <<
';
                }

                echo '

';
            }
            $MemberGalleriesQuery->free();
            ?>

JAVASCRIPT:
    //Edit Form When Hovering Over Gallery Name
$('.EditGallery').each(function() {

    var link = $('.EditGallery').attr('href'); //Gets link url

    $.ajax({ //Make the ajax request
        url: link,
        cache: false
    }).done(function( html ) { //On complete run tooltip code

        //Display tooltip code goes here, returned text is variable html
    $('.EditGallery').qtip({
        content: {
            text: html
        },
        hide: {
            fixed: true,
            delay: 300
        },
        style: 'wiki'
    });
    $('.EditGallery').qtip('click', true);
    $(".EditGallery").page();
    });
});

CONTENTS OF Crowork.Backend/Crowork.EditGallery.php
    if ( isset( $cleanGet['action'] ) && $cleanGet['action'] == 'EditGallery' ){

    $MemberGalleriesQuery = $bapcity->query("SELECT * FROM CroMemberRetailGalleries WHERE GalleryID='".$cleanGet['gallerykey']."' AND UserID='".$SessionUserID."' ORDER BY GalleryID DESC");

    $MemberGalleriesCount = $MemberGalleriesQuery->num_rows;

    if ( $MemberGalleriesCount )
    {
        $GalleryData = $MemberGalleriesQuery->fetch_assoc();
    }?>

    <form action="Crowork.Backend/Crowork.EditGallery.php?action=DoEditGallery&gallerykey=<?php echo $GalleryData['GalleryID']?>" method="post">
        <input type="hidden" name="GalleryName" value="<?php echo $GalleryData['GalleryName']?>">
        <input type="hidden" name="GalleryID" value="<?php echo $GalleryData['GalleryID']?>">
        <input type="submit" name="DeleteGallery" value="Delete Gallery">
    </form>

    <form action="Crowork.Backend/Crowork.EditGallery.php?action=DoEditGallery&gallerykey=<?php echo $GalleryData['GalleryID']?>" method="post">

        NOTE: Letters & Numbers Only

        Name:
        <input type="text" name="GalleryName" size="30" value="<?php echo $GalleryData['GalleryName']?>">

            <input type="hidden" name="OriginalGalleryName" value="<?php echo $GalleryData['GalleryName']?>">
            <input type="hidden" name="GalleryID" value="<?php echo $GalleryData['GalleryID'] ?>">
            <input type="submit" name="EditGallery" value="Edit Gallery">

    </form>
    <?php }?>

PREVIEW:
http://www.bigjohn863.com/mini-upload-form/uploads/ajaxproblem.png
See how all three are the same results.

A: //Edit Form When Hovering Over Gallery Name
$('.EditGallery').each(function() {

var link = $('.EditGallery').attr('href'); //Gets link url
....

everytime you are calling $('.EditGallery').  $('.EditGallery'). is an array, you need to change all references to $('.EditGallery') that is within the loop to $(this):
var link = $(this).attr('href'); //Gets link url

A: You Might be need to create dynamic id so you can call proper ajax.
please modify your ajax call as below
 $gid=$GalleryData['GalleryID'];
 echo '>> '.$GalleryData['GalleryName'].' <<
';

replace this code in while loop.
function editgalary(galaryid){
   var link = $('#EditGallery_'+galaryid).attr('href');
//ajax code as it is.
}

try and let me konw

A: Try:
 $('.EditGallery').each(function()
{
        $(this).qtip({
        content:  {
            text: "Loading...",
            ajax: {
                url:$(this).attr('href'),
                type: "GET",
                success: function(data, status) {
                  this.set('content.text', data);
                }
               }

            },
        hide: {
            fixed: true,
            delay: 300
        },
        style: 'wiki'
    });
    $(this).qtip('click', true);
});

http://jsfiddle.net/st0j8nLy/


text:
Q: Is there a workaround to the Oracle Correlated Subquery Nesting Limit? I have a situation where I'm trying to use a correlated subquery but am running into the nesting limit in Oracle. I might be missing another feature that Oracle has, so I thought I'd post this question here. Does anyone know how to rewrite the below SQL without running into this nesting limit, but also staying within the below constraints?
Constraints:

*

*Only the SQL in the IN clause can be modified (Due to constraints beyond my control)

*As shown, the filtering in the parent query needs to be applied to the aggregation subquery before the aggregation occurs.

*Filter out 0 on an aggregation of colB after the parent filter is applied

The below code shows my try at this before running into the Oracle limit. Also, the Oracle version I'm on is 11.2.0.2. Any help would be appreciated. Thanks!
SELECT
  *
FROM
  table1 t1
WHERE
  t1.colA BETWEEN XXXX AND XXXX
  AND t1.pk_id IN (
    SELECT
      t2.pk_id
    FROM (
      SELECT
        t3.pk_id,
        SUM(t3.amt) OVER (PARTITION BY t3.colB) amt
      FROM table1 t3
        WHERE t3.colA = t1.colA
    ) t2
    WHERE
      t2.amt <> 0
  )

Here are some sample input/outputs of what I was looking for when running the above SQL:
Sample table1:
-----------------------------
| pk_id | colA | colB | amt |
-----------------------------
|   1   |  1   |  A   |  2  |
|   2   |  1   |  A   |  -1 |
|   3   |  1   |  B   |  1  |
|   4   |  2   |  B   |  1  |
|   5   |  2   |  A   |  -2 |
|   6   |  2   |  A   |  1  |
|   7   |  3   |  A   |  1  |

Results of SUM over t3.colB with t1.colA BETWEEN 1 And 2:
---------------
| pk_id | amt |
---------------
|   1   |  0  |
|   2   |  0  |
|   3   |  2  |
|   4   |  2  |
|   5   |  0  |
|   6   |  0  |

Results of subquery for IN clause with t1.colA BETWEEN 1 And 2:
---------
| pk_id |
---------
|   3   |
|   4   |

Result of top level query with t1.colA BETWEEN 1 And 2:
-----------------------------
| pk_id | colA | colB | amt |
-----------------------------
|   3   |  1   |  B   |  1  |
|   4   |  2   |  B   |  1  |

After working through some of the answers provided, I have a way of avoiding the nesting limit in Oracle with a simple CASE statement:
SELECT
  *
FROM
  table1 t1
WHERE
  t1.colA BETWEEN 1 AND 2
  AND t1.pk_id IN (
    SELECT
      CASE
        WHEN SUM(t2.amt) OVER (PARTITION BY t2.colB) <> 0 THEN t2.pk_id
        ELSE NULL
      END
    FROM table1 t2
    WHERE t2.colA = t1.colA
  )

Unfortunately this surfaced the real problem. Because this is a subquery, I can only iterate through one value of the t1.colA range at a time. This appears to make it impossible execute the analytic sum within that range in the subquery. Because I can only modify the SQL within the IN clause, I don't see a solution to this problem. If anyone has any suggestions please let me know. Thanks.

A: If you know what the between values are and can use those in your subquery, then you can add that to your subquery instead:
SELECT
    *
FROM
    table1 t1
WHERE
    t1.colA BETWEEN 1 AND 2
    AND t1.pk_id IN (
        SELECT
            t2.pk_id
        FROM
            (
                SELECT
                    t3.pk_id,
                    SUM(t3.amt) OVER (PARTITION BY t3.colB) amt
                FROM table1 t3
                WHERE t3.colA BETWEEN 1 AND 2
            ) t2
        WHERE
            t2.amt <> 0
    )

SQL Fiddle Demo

A: You can rewrite your query like this:
SELECT *
FROM table1 t1
WHERE t1.colA BETWEEN XXXX AND XXXX and
      t1.pk_id IN (
        SELECT t2.pk_id
        FROM (SELECT t3.pk_id, t3.ColA, SUM(t3.amt) as amt
              FROM table1 t3
              group by t3.pk_id, t3.ColA
              having sum(t3.amt) > 0
             ) t2
        WHERE t2.colA = t1.colA
      )

From here, you can rewrite it as:
select t1.*
from table1 t1 join
     (SELECT t3.pk_id, t3.ColA, SUM(t3.amt) as amt
      FROM table1 t3
      group by t3.pk_id, t3.ColA
      having sum(t3.amt) > 0
     ) t2
     on t1.pk_id = t2.pk_id and t1.ColA = t3.ColA
WHERE t1.colA BETWEEN XXXX AND XXXX


text:
Q: Implement a connection between my application (Spring integration) with IBM-MQ - High Availability I am trying to implement a connection between my application (Spring integration) with IBM-MQ,  I  did see the question spring-integration-support-for-clustered-high-availability-ibm-mq-manager, but in my case each host has different "queueManager" and "channels", it means I will have must have a configuration like follows but, the queueManager and channels properties support a String not a list values:
<bean id="connectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
        <property name="connectionNameList" value="host1(6464),host1(6464)" />
        <property name="clientReconnectTimeout" value="15000" />
        <property name="transportType" value="1" />
        <property name="queueManager" value="QM1, QM1," />
        <property name="channel" value="channel1,channel1"/>
</bean>

A: The simplest thing would be to define a channel with the same name on both hosts and let the client try host1 first and then host2 using connectionNameList.  In this setup it would always prefer host1.  You would need to specify a queueManager that is blank so that the client will accept the queue manager it connects to.  Example follows:
    <property name="queueManager" value="" />

Another option that was pointed out in a comment from Morag on the other post you linked to is to use a CCDT (Client channel definition table).
See Using a client channel definition table with IBM WebSphere MQ classes for JMS.  The property name is CCDTURL
The CCDT can have multiple CLNTCONN channel entries with different channel names all having the same QMNAME, this is called a Queue Manager Group, you would then specify the queueManager property as *QMNAME, this will allow the app to connect to which ever queue manager you are directed to with out regard to the actual queue manager name.  There are other parameters of the CLNTCONN listed at the bottom of the link I provided that can help you to control if one queue manager is preferred over the other(s) as well as which queue manager to connect to if a reconnect is required.


text:
Q: Concerting char* to string to be read into file? I am trying to read in an input from a user and I know my method needs a char* but is there anyway to make the input of cin able to be used by that char? (look at the comment at char* x.)
string y;
cout << "Enter your file: ";
cin >> y;

char * x = //here is where the string needs to go. If I type in the actual address it works, but I need it to work when the user just cin's the address//

string line,character_line;
ifstream myfile;
myfile.open (x);
while(getline(myfile,line))
{
    if (line[0] != '0' && line[0] != '1')
    {
        character_line = line;
    }

}

A: char * x = y.c_str();

A simple Google would have provided the result :)

A: You can simply use the c_str() method of the std::string class.  This works:
#include <fstream>
#include <iostream>
#include <string>

int main(void) {
  std::string y;
  std::cout << "Enter your file: ";
  std::cin >> y;
  std::string line,character_line;
  std::ifstream myfile;
  myfile.open (y.c_str(), std::ifstream::in);
  while(getline(myfile,line))
  {
    if (line[0] != '0' && line[0] != '1')
    {
      character_line = line;
    }

  }
  return 0;
}


text:
Q: Windows 10 Administrator and Linux SuperUser I understand that in Windows 10 Administrator is equivalent to the SuperUser in Linux. But I don't have the same power over my Machine as Linux gives with su or sudo
as an Example in Linux with sudo, commands like
rm -rf / --no-preserve-root

won't be a problem. But in windows I can't even delete Window.old folder even after being Administrator and taking Full Control from Security  and taking Ownership with
takeown /F Windows.old

also tried using rimraf tool from npm. Still won't completely delete the files.
So my Question is there any way in Windows 10 to take full control like sudo provides or its just that's how windows works.

A:
I understand that in Windows 10 Administrator is equivalent to the SuperUser in Linux.

It's not.
First, administrators are constrained by UAC. If you're logged in as an administrator, but aren't granted full access, first make sure you're using an elevated Command Prompt window (e.g. by holding Ctrl+Shift while opening it, and getting the UAC prompt).
(Linux recently has been moving to a different model where apps perform actions through privileged services, rather than having to run the whole app as root.)
Second, administrators have different privileges. root on Linux has CAP_FOWNER and CAP_DAC_OVERRIDE (see capabilities), allowing it to bypass all permission checks. (On other Unix-like systems, the bypass is granted to uid 0 in general.)
Administrators on Windows don't have the same; by default, they only have SeTakeOwnershipPrivilege active (similar to Linux CAP_CHOWN; see privileges). In other words, administrators can reset an object's security settings, but not bypass them.
To get a full security bypass on Windows, one would need to enable SeBackupPrivilege and SeRestorePrivilege for read & write access respectively (e.g. using this tool). Administrators are allowed to use these privileges (after UAC elevation), but they aren't active by default – a process must 'enable' them first.
(You can see the available & enabled privileges in Process Explorer's "Security" tab, or in Process Hacker's "Token" tab. It's also possible to manually enable them e.g. for a running cmd.exe process.)

A: Windows administrator is closer to Linux Super-user than root.
In windows, the system is the closest equivalent to root.
Note that Windows 10 should automatically delete the Windows.old folder one month after you performed your upgrade.
Officially, it can be deleted with 'disk cleanup'. See the exact step-by-step guide here


text:
Q: cucumber.runtime.CucumberException: Failed to instantiate stepDefinitions class I am trying to run cucumber test written in java.
Everything seems to run fine except after I implement the feature file I start getting this error : cucumber.runtime.CucumberException: Failed to instantiate stepDefinitions class.
 package runners;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "src/test/resources/FeatureFile",
        glue = {"stepDefinitions"}
)

public class TestRunner {

}

Project Structure is as follows:

StepDefinitons class is as follows. First I run the feature file, after which I got methods which I need to implement in the stepDefinitons class.
package stepDefinitions;
import cucumber.api.java.en.Given;
    import cucumber.api.java.en.Then;
    import cucumber.api.java.en.When;
    import org.junit.Assert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.Keys;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import java.util.concurrent.TimeUnit;
    public class Steps {

            private static WebDriver driver;
            WebDriverWait wait=new WebDriverWait(driver, 20);

            @Given("^I naviagte to login page$")
            public void i_naviagte_to_login_page() {
                System.setProperty("webdriver.chrome.driver", "E:\\TestingJAR\\chromedriver_win32\\chromedriver.exe");
                driver = new ChromeDriver();
                driver.manage().window().maximize();
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                driver.get("http://www.facebook.com");
            }

            @When("^I enter username as operqa(\\d+)$")
            public void i_enter_username_as_operqa(String usr) {
                WebElement username = driver.findElement(By.name("username"));
                username.sendKeys(usr);
                username.sendKeys(Keys.TAB);
            }

            @When("^I enter password as (\\d+)$")
            public void i_enter_password_as(String pass) {
                WebElement tipoValidacion;
                tipoValidacion =  wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"tipoValidacionDiv\"]/div/div/div/span[3]")));
                tipoValidacion.click();
                driver.findElement(By.xpath("//*[@id=\"tipoValidacionDiv\"]/div/div/div/span[1]")).click();

                WebElement password;
                password = wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("password")));
                password.sendKeys(pass);
            }

            @When("^I press Ingresar button$")
            public void i_press_Ingresar_button() {
                driver.findElement(By.xpath("//BUTTON[@type='submit']")).click();
            }

            @Then("^I should be able to login successfully$")
            public void i_should_be_able_to_login_successfully() {
                 WebElement loginSuccess =  driver.findElement(By.xpath("//H1[@class=''][text()='Home']"));
                 Assert.assertEquals(loginSuccess.getText(),"Home");
            }
        }

A: The instantiation fails as it's not possible to create a new object of Steps with the default constructor.
public class Steps {

    private static WebDriver driver;
    WebDriverWait wait=new WebDriverWait(driver, 20);

    ...

because driver is not yet initialized at new WebDriverWait(driver, 20).
To initialize driver you could use a @Before (executed before scenario) or @BeforeStep (executed before step) annotated method.
Have a look at the related documentation
https://docs.cucumber.io/cucumber/api/#scenario-hooks
https://docs.cucumber.io/cucumber/api/#step-hooks


text:
Q: Does $F(w(x))\leqslant C_wF(x)$ for a certain constant $C_w$ with $F$ being a distance function? This is a continuation of this other question I asked earlier.
Since @Arnaud D. proved in my previous question that the result can not hold under such weak hypothesis, I reinforced the hypothesis on the function $F$.
A function $F\colon \mathbb R^n\to \mathbb R$ is called a distance function if it verifies the three conditions:

*

*$F(x)\geqslant 0$ and $F(x)=0\iff x=0$,

*$F(tx)=\vert t\vert F(x)$,

*$F$ is continuous.
I want to prove the following result.

Let $F\colon \mathbb R^n\to \mathbb R$ be a distance function. If $w\in \mathrm{GL}_n(\mathbb R)$, then there exists a constant $C_w$ (which does not depend on $X$), such that
  $$F(w(X))\leqslant C_wF(X). \quad \forall X \in \mathbb{R}^n$$

I think I should use something like $\Vert w(W)\Vert\leqslant \Vert w\Vert \cdot \Vert X\Vert$, or try to use a matrix $W=(w_{i,j})$ for $w$ and compute the coordinates of $w(x)$ in terms of $w_{i,j}$ and $x_i$.
But I can't figure it out. Any hint or solution would be much appreciated.
Notice that the counter-example provided by @Arnaud D. in my previous question does not work here since it does not verify $F(x)=0\iff x=0$.

A: I think I finally got it, I just need to act as if $F$ is a norm. I encourage you to criticize me if this proof has flaws.
Let $$C_w:=\sup_{F(Y)=1} F(w(Y)),$$
which does not depend on $X$, and is well defined since $F$ is continuous on the compact unit sphere.
I assume $X\ne 0$. Now, set $Y:=\frac 1{F(X)} X$, which is well-defined since $F(X)\ne 0$ because $X\ne 0$ and $F$ is a distance function.
Then because of the properties of $F$:
$$F(w(X))=F(w(F(X)Y))=F(X)\underbrace{F(w(Y))}_{\leqslant C_W}.$$


text:
Q: webview lose focus after I click outside it and never zoom in or out again android I have a major problem using webview in android
I have the following layout
RelativeLayout
-- TextView
-- ImageView
-- RelativeLayout
------Webview
when I enter the webview has focus and I can zoom in and out, when I click on Textview or Imageview and back to webview I can't zoom in or zoom out
I have tried a lot of things
 - set all other view not focusable and not clickable
 - set onTouch listener to parent view and set my webview to request focus
but nothing work, can anyone help please

A: The problem happen to me because I was using view pager with DepthPageTransformer and add it one of it's fragment my webview, the problem solved when I use the default Transformer of the view pager


text:
Q: FirebaseRecyclerViewAdapter display child's from multiple refs I know that this questions has already been asked but I am looking for days and I haven't find the solution. Is there any way to display child's from multiple refs in one FirebaseRecyclerViewAdapter.I use GeoFire to find nearest places and store them in a list. The list have some uids. My database look like this.
 "Places" : {
        "yt1FNJ7CwYNnUTAjxuewwIb3eY22" : {  //uid
          "category1" : {
                 "-KXVfuOf2ZIk2ksFk7Sk" : {
                    "date" : "2016/11/28",
                    "name"  : "item1"
                  },
                  "-KXVfjzC_-_kTZqH8B1k" : {
                    "date" : "2016/11/27",
                     "name" : "item2"
                  }
                }
              }
    "Ks1FNJ7CwYNnUTAjxuewwIb3eY23" : {            //uid
          "category1" : {
                 "-KXVfuOf2ZIk2ksFk7Sk" : {
                    "date" : "2016/11/28",
                    "name"  : "item3"
                  },
                "-KXVfjzC_-_kTZqH8B1k" : {
                    "date" : "2016/11/27",
                     "name" : "item4"
                  }
                }
              }
      }

So how I display the items in the RecyclerViewer from all the GeoFire results?


text:
Q: Window not repainting itself after restoring from minimized state I'm actually facing a problem with the painting of the WinAPI.
I'm creating my controls like so:
case WM_CREATE:
        g_font = CreateFont(16, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, ANSI_CHARSET, CLIP_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FF_DONTCARE, "MS Dlg Shell");

        g_staticTextToEncrypt = CreateWindowEx(0, "STATIC", "Entrez le texte que vous voulez chiffrer:", WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, window, NULL, GetModuleHandle(NULL), NULL); SendMessage(g_staticTextToEncrypt, WM_SETFONT, (WPARAM)g_font, (LPARAM)TRUE);
        g_staticTextAlphabet = CreateWindowEx(0, "STATIC", "Entrez votre alphabet de substitution:", WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, window, NULL, GetModuleHandle(NULL), NULL); SendMessage(g_staticTextAlphabet, WM_SETFONT, (WPARAM)g_font, (LPARAM)TRUE);
        g_staticEncryptedText = CreateWindowEx(0, "STATIC", "Message chiffré:", WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, window, NULL, GetModuleHandle(NULL), NULL); SendMessage(g_staticEncryptedText, WM_SETFONT, (WPARAM)g_font, (LPARAM)TRUE);

        g_editInputMessage = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", WS_CHILD | WS_VISIBLE | ES_LEFT | ES_AUTOHSCROLL | ES_UPPERCASE, 0, 0, 0, 0, window, (HMENU)ID_EDIT_INPUT_MESSAGE, NULL, NULL); SendMessage(g_editInputMessage, WM_SETFONT, (WPARAM)g_font, (LPARAM)TRUE);
        g_editInputAlphabet = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", WS_CHILD | WS_VISIBLE | ES_LEFT | ES_AUTOHSCROLL | ES_UPPERCASE, 0, 0, 0, 0, window, (HMENU)ID_EDIT_INPUT_ALPHABET, NULL, NULL); SendMessage(g_editInputAlphabet, WM_SETFONT, (WPARAM)g_font, (LPARAM)TRUE);
        g_editOutputEncryptedText = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", WS_CHILD | WS_VISIBLE | ES_CENTER | ES_AUTOHSCROLL | ES_READONLY, 0, 0, 0, 0, window, (HMENU)ID_EDIT_OUTPUT_ENCRYPTED_TEXT, NULL, NULL); SendMessage(g_editOutputEncryptedText, WM_SETFONT, (WPARAM)g_font, (LPARAM)TRUE);

        g_buttonCopyEncryptedText = CreateWindowEx(0, "BUTTON", "Copier", WS_CHILD | WS_VISIBLE | BS_CENTER, 0, 0, 0, 0, window, ID_BUTTON_COPY_ENCRYPTED_TEXT, NULL, NULL); SendMessage(g_buttonCopyEncryptedText, WM_SETFONT, (WPARAM)g_font, (LPARAM)TRUE);

        break;

and so I can keep them centered even when the window's been resized by the user, I'm handling the WM_PAINT message:
case WM_PAINT:
        BeginPaint(window, &ps);

        hdc = GetDC(g_staticTextToEncrypt);
        SelectObject(hdc, g_font);
        GetTextMetrics(hdc, &tm);
        ReleaseDC(g_staticTextToEncrypt, hdc);

        GetWindowRect(window, &windowSize);
        setNewControlsPos(&windowSize, &tm);

        EndPaint(window, &ps);
        break;

setNewControlsPosis just performing SetWindowPos(g_staticTextToEncrypt, HWND_BOTTOM, ..., ..., ..., ..., SWP_SHOWWINDOW); for every control created in WM_CREATE
The problem is that when I minimzed the window and that I restore it, the window is white, every controls have disappeared in the wild. I think that the problem comes from me not repainting the controls in WM_PAINT but only repositionning them but I can't find out how to repaint the controls correctly.
I tried using RedrawWindow(..., NULL, NULL, RDW_ERASE | RDW_INVALIDATE); or InvalidateRect(..., NULL, FALSE); on every control but it had no effect.


text:
Q: utf-8 error in partial class In my form application, I create a partial class of the form like designer to reduce complexity of code with categorizing the methods (I could use different classes but it's not possible at this point).
I have a string value that contains several utf-8 characters.
string t = "şçıer";
if I declare this string in partial form that I created, when I try to pop up a message box to show this string something go wrong.
Result:  þçýer
But it's okay when I declare it in form1.cs

A: Encoding mismatch.
0xfe is ş in Latin-5, and þ in Latin-1, Latin-6, Latin-9, and CP-1252.
0xfd is ı in Latin-5, and ý in Latin-1, Latin-6, Latin-9, and CP-1252.
ş in UTF-8 would be 0xc5 0x9f, and ı would be 0xc4 0xb1.
So some part in your chain is either in the wrong encoding, or declaring the wrong encoding. Make sure you are actually using UTF-8 throughout, because evidence suggests you are using Latin-5 (ISO-8859-9) in your source, and interpreting it as Latin-1 (or one of the other encodings mentioned above).


text:
Q: In Pandas, does .iloc method give a copy or view? I find the result is a little bit random. Sometimes it's a copy sometimes it's a view. For example:
df = pd.DataFrame([{'name':'Marry', 'age':21},{'name':'John','age':24}],index=['student1','student2'])

df
              age   name
   student1   21  Marry
   student2   24   John

Now, Let me try to modify it a little bit.
df2= df.loc['student1']
df2 [0] = 23
df
              age   name
   student1   21  Marry
   student2   24   John

As you can see, nothing changed. df2 is a copy. However, if I add another student into the dataframe...
df.loc['student3'] = ['old','Tom']
df
               age   name
    student1   21  Marry
    student2   24   John
    student3  old    Tom

Try to change the age again..
df3=df.loc['student1']
df3[0]=33
df
               age   name
    student1   33  Marry
    student2   24   John
    student3  old    Tom

Now df3 suddenly became a view. What is going on? I guess the value 'old' is the key?

A: You are starting with a DataFrame that has two columns with two different dtypes:
df.dtypes
Out:
age      int64
name    object
dtype: object

Since different dtypes are stored in different numpy arrays under the hood, you have two different blocks for them:
df.blocks

Out:
{'int64':           age
 student1   21
 student2   24, 'object':            name
 student1  Marry
 student2   John}

If you attempt to slice the first row of this DataFrame, it has to get one value from each different block which makes it necessary to create a copy.
df2.is_copy
Out[40]: <weakref at 0x7fc4487a9228; to 'DataFrame' at 0x7fc4488f9dd8>

In the second attempt, you are changing the dtypes. Since 'old' cannot be stored in an integer array, it casts the Series as an object Series.
df.loc['student3'] = ['old','Tom']

df.dtypes
Out:
age     object
name    object
dtype: object

Now all data for this DataFrame is stored in a single block (and in a single numpy array):
df.blocks

Out:
{'object':           age   name
 student1   21  Marry
 student2   24   John
 student3  old    Tom}

At this step, slicing the first row can be done on the numpy array without creating a copy, so it returns a view.
df3._is_view
Out: True

A: In general, you can get a view if the data-frame has a single dtype, which is not the case with your original data-frame:
In [4]: df
Out[4]:
          age   name
student1   21  Marry
student2   24   John

In [5]: df.dtypes
Out[5]:
age      int64
name    object
dtype: object

However, when you do:
In [6]: df.loc['student3'] = ['old','Tom']
   ...:

The first column get's coerced to object, since  columns cannot have mixed dtypes:
In [7]: df.dtypes
Out[7]:
age     object
name    object
dtype: object

In this case, the underlying .values will always return an array with the same underlying buffer, and changes to that array will be reflected in the data-frame:
In [11]: vals = df.values

In [12]: vals
Out[12]:
array([[21, 'Marry'],
       [24, 'John'],
       ['old', 'Tom']], dtype=object)

In [13]: vals[0,0] = 'foo'

In [14]: vals
Out[14]:
array([['foo', 'Marry'],
       [24, 'John'],
       ['old', 'Tom']], dtype=object)

In [15]: df
Out[15]:
          age   name
student1  foo  Marry
student2   24   John
student3  old    Tom

On the other hand, with mixed types like with your original data-frame:
In [26]: df = pd.DataFrame([{'name':'Marry', 'age':21},{'name':'John','age':24}]
    ...: ,index=['student1','student2'])
    ...:

In [27]: vals = df.values

In [28]: vals
Out[28]:
array([[21, 'Marry'],
       [24, 'John']], dtype=object)

In [29]: vals[0,0] = 'foo'

In [30]: vals
Out[30]:
array([['foo', 'Marry'],
       [24, 'John']], dtype=object)

In [31]: df
Out[31]:
          age   name
student1   21  Marry
student2   24   John

Note, however, that a view will only be returned if it is possible to be a view, i.e. if it is a proper slice, otherwise, a copy will be made regardless of the dtypes:
In [39]: df.loc['student3'] = ['old','Tom']

In [40]: df2
Out[40]:
          name
student3   Tom
student2  John

In [41]: df2.loc[:] = 'foo'

In [42]: df2
Out[42]:
         name
student3  foo
student2  foo

In [43]: df
Out[43]:
          age   name
student1   21  Marry
student2   24   John
student3  old    Tom


text:
Q: Send message from Text I am getting Error: Please make sure that the message parameter is a string!.
How do I return an array of text from my text file and auto-send that from the loop?
    // read contents of the file
    const data = fs.readFileSync('mr_robot.txt', 'UTF-8');
    const lines = data.split(/\r?\n/);
    let n_lines = 1;
    for (let l_indx = 0; l_indx < lines.length; l_indx++) {
        var message = lines
    }
    autosend.PostLoop(message, channelID, tokenID, minimum, maximum)

Example text from .txt
Hey! Hey! Hey! Boy's not picking up.
Okay, okay, okay.
I got you, man.
I didn't know that.
All right, I got you.
All right.
Yeah, you got me confused.

A: It looks like you are assigning message to your original array lines. You are looping but not indexing anything.
I'm not exactly sure what you are trying to achieve but if you want to call PostLoop per message you need to do something like this:
const data = fs.readFileSync('mr_robot.txt', 'UTF-8');
const lines = data.split(/\r?\n/);
let n_lines = 1;
for (let l_indx = 0; l_indx < lines.length; l_indx++) {

    var message = lines[l_indx];
    autosend.PostLoop(message, channelID, tokenID, minimum, maximum);
}


text:
Q: How to save the settings from my Wordpress plugin? I'm currently making a wordpress plugin with a settings page, where the user can input images, names and URL's which will then be shown on the website using a widget and a shortcode. Of course, I want to save these settings so they can be shown on the website.
I have found this code, but I don't know if it is the (best) way:
<form method="post" action="options.php">
    <?php wp_nonce_field('update-options') ?>

One 1:

        <input type="text" placeholder="Name" name="name" size="45" value="<?php echo get_option('name'); ?>" />
        <input type="text" placeholder="Logo" name="logo" size="45" value="<?php echo get_option('logo'); ?>" />
        <input type="text" placeholder="Website" name="website" size="45" value="<?php echo get_option('website'); ?>" />

    <input type="submit" name="Submit" value="Save" />

    <input type="hidden" name="action" value="update" />
    <input type="hidden" name="page_options" value="name, logo, website" />
</form>

What do you suggest?

A: read the Settings API from Wordpress, there is all you need to create an option page.


text:
Q: Unable to post data to my API from a react form I want to post data to my API from this form. But unfortunately, there is a Server error. Could anybody tell what exactly is the problem? (I observed that the id is not being generated for the object)
This is the error that I'm getting in the console after clicking on submit button:

POST https://alert-amigo-api.herokuapp.com/products 500 (Internal
  Server Error) Response {type: "cors", url:
  "https://alert-amigo-api.herokuapp.com/products", redirected: false,
  status: 500, ok: false, …} type: "cors" url:
  "https://alert-amigo-api.herokuapp.com/products" redirected: false
  status: 500 ok: false statusText: "Internal Server Error"

This is my code:
import React, { Component } from "react";
import { Link } from 'react-router-dom';
import { Form, FormControl, FormCheck } from 'react-bootstrap';
import { FormGroup, ControlLabel, Row, Button, Checkbox, Radio, HelpBlock } from "react-bootstrap";

function FieldGroup({ id, label, help, ...props }) {
return (
    <FormGroup controlId={id}>
    <ControlLabel>{label}</ControlLabel>
    <FormControl {...props} />
    {help && <HelpBlock>{help}</HelpBlock>}
    </FormGroup>
  );
}

class Typography extends Component {
  constructor() {
    super();

    this.state = {
      productName: '',
      productPrice: '',
      productCategory: '',
      productBrand: '',
      countryOfOrigin: '',
      riskType: '',
      alertSubmittedBy: '',
      yourCity: '',
      yourAddress: '',
      productImage: '',
      description: ''
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  changeHandler = e => {
    this.setState({[e.target.id]: e.target.value})
  }

  handleSubmit(e) {
      e.preventDefault();

      console.log('The form was submitted with the following data:');
      console.log(this.state);
    fetch('https://alert-amigo-api.herokuapp.com/products',{
        method: 'POST',
        headers: {
            Accept: 'application/json',
                    'Content-Type': 'application/json',
        },
        body: JSON.stringify(this.state)
    }).then(response => {
            console.log(response)
        })
        .catch(error =>{
            console.log(error)
        });

}

  render() {
    return (
      <div className="typoForm">
  <form onSubmit={this.handleSubmit}>
    <FieldGroup
      id="productName"
      name="productName"
      type="text"
      label="Product Name"
      placeholder=""
      value={this.state.productName}
      onChange={this.changeHandler}
    />
    <FieldGroup
      id="productPrice"
      name="productPrice"
      type="number"
      label="Product Price (in Euros)"
      placeholder=""
      value={this.state.productPrice}
      onChange={this.changeHandler}
    />
    <FormGroup controlId="productCategory" name="productCategory">
      <ControlLabel>Category</ControlLabel>
      <FormControl componentClass="select" name="productCategory" placeholder="select" onChange={this.changeHandler} value={this.state.selectValue}>
        <option value="select">select the category to which the product belongs to</option>
        <option value="electronics">Electronics</option>
        <option value="cosmetics">Cosmetics</option>
        <option value="apparels">Apparels</option>
        <option value="footwear">Footwear</option>
        <option value="accessories">Watches/Accessories</option>
        <option value="handbags">Handbags/Wallets</option>
        <option value="pharmaceuticals">Pharmaceuticals/Personal Care</option>
        <option value="Toys">Toys</option>
      </FormControl>
    </FormGroup>
    <FieldGroup
      id="productBrand"
      name="productBrand"
      type="text"
      label="Product Brand"
      placeholder=""
      value={this.state.productBrand}
      onChange={this.changeHandler}
    />
    <FieldGroup
      id="countryOfOrigin"
      name="countryOfOrigin"
      type="text"
      label="Country Of Origin"
      placeholder=""
      value={this.state.countryOfOrigin}
      onChange={this.changeHandler}
    />
    <FormGroup controlId="riskType" name="riskType">
      <ControlLabel>Risk Type</ControlLabel>
      <FormControl componentClass="select" placeholder="select" name="riskType" onChange={this.changeHandler} value={this.state.selectValue}>
        <option value="select">select the level of risk</option>
        <option value="high">high</option>
        <option value="medium">medium</option>
        <option value="low">low</option>
      </FormControl>
    </FormGroup>
    <FormGroup controlId="alertSubmittedBy" name="alertSubmittedBy">
      <ControlLabel>Alert Submitted By</ControlLabel>
      <FormControl componentClass="select" onChange={this.changeHandler} name="alertSubmittedBy" placeholder="select" value={this.state.selectValue}>
        <option value="select">select</option>
        <option value="producers">producers</option>
        <option value="consumers">consumers</option>
        <option value="distributors">distributors</option>
      </FormControl>
    </FormGroup>
    <FieldGroup
      id="yourCity"
      name="yourCity"
      type="text"
      label="Your City"
      placeholder=""
      value={this.state.yourCity}
      onChange={this.changeHandler}
    />
    <FormGroup controlId="yourAddress" name="yourAddress">
      <ControlLabel>Your Address</ControlLabel>
      <FormControl componentClass="textarea" name="yourAddress" onChange={this.changeHandler} value={this.state.value} placeholder="Enter your address here" />
    </FormGroup>
    <FieldGroup
      id="productImage"
      name="productImage"
      type="file"
      label="File"
      value={this.state.value}
      onChange={this.changeHandler}
      help="Upload an image of the product."
    />
    <FormGroup controlId="description" name="description">
      <ControlLabel>Please mention the defaults of the product</ControlLabel>
      <FormControl componentClass="textarea" name="description" onChange={this.changeHandler} value={this.state.value} placeholder="" />
    </FormGroup>

    <Button type="submit">Submit</Button>
  </form>
  </div>

    );
  }
}
export default Typography;

A: A 500 error code is a server-side error.  Thus you should be debugging your API code, not your react code to get to the bottom of the problem.
With that said, the error message indicates a CORS error.  If you are not familiar with Cross-Origin Resource Sharing (CORS), I encourage you to go read and familiarize yourself with that before continuoing your troubleshooting.
This error is most likely caused by that fact that the domain that is hosting your reactjs component is not the same as where your api is hosted (alert-amigo-api.herokuapp.com), and either 1) that API is not configured for cross-origin requests, or 2) it is configured for CORS, but your reactjs client has not set the correct headers to enable the pre-flight requests necessary for CORS.
Have a look at the following for more information:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
https://cors-anywhere.herokuapp.com/
https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9
https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/cors.md


text:
Q: Making Dropbox ignore an .svn folder Want to have the benefits of both Dropbox and SVN, but annoyed that Dropbox syncs the .svn folder?
Then here's how to make Dropbox ignore a specific folder, like an .svn folder, on Windows 7:

*

*Maybe you already have a .svn folder that you want Dropbox to ignore, but if not, create the .svn folder yourself in the place where you expect SVN to place it.

*Make a zip file of the .svn folder in question.

*Click the Dropbox icon in the system tray and go to Preferences > Account > Selective Sync...

*Navigate to the .svn folder and remove the checkmark next to it. Then click Update.

*Wait for Dropbox to delete your .svn folder.

*Unzip the zip file, thus restoring your .svn folder.

Done. Your Dropbox account will now contain an empty .svn folder which will be synced to all your devices. The Windows box you did these steps on will contain the full .svn folder, and it will have a little grey mark on its icon to show that Dropbox is ignoring it. This slightly convoluted procedure was the only way I could get Dropbox to do what I wanted. Hope it helps someone else.

A: Want to have the benefits of both Dropbox and SVN, but annoyed that Dropbox syncs the .svn folder?
Then here's how to make Dropbox ignore a specific folder, like an .svn folder, on Windows 7:

*

*Maybe you already have a .svn folder that you want Dropbox to ignore, but if not, create the .svn folder yourself in the place where you expect SVN to place it.

*Make a zip file of the .svn folder in question.

*Click the Dropbox icon in the system tray and go to Preferences > Account > Selective Sync...

*Navigate to the .svn folder and remove the checkmark next to it. Then click Update.

*Wait for Dropbox to delete your .svn folder.

*Unzip the zip file, thus restoring your .svn folder.

Done. Your Dropbox account will now contain an empty .svn folder which will be synced to all your devices. The Windows box you did these steps on will contain the full .svn folder, and it will have a little grey mark on its icon to show that Dropbox is ignoring it. This slightly convoluted procedure was the only way I could get Dropbox to do what I wanted. Hope it helps someone else.


text:
Q: Reverse proxy for SSH/HTTPS on same port (443) I have an unusual problem. My home server environment has only one static IP. It has a web server that I would like to serve HTTP and HTTPS. However, most of the external networks I connect to it from block traffic over all ports except 80 and 443, thus preventing me from doing SSH over port 22. I can do SSH over 443, but that obviously conflicts with HTTPS requests.
My main question is if there is a way to set up a reverse proxy server that will forward domain.com:443 to my web server for HTTPS and allow me to redirect ssh.domain.com:443 to my web server internally on port 22 for SSH.

A: This should be possible with the help of sslh.


text:
Q: XML File Translate with SQL query I have a Swift Message encoded with SQL query using encoding="utf-16 - I used below code:
CAST(REPLACE(CAST(Content AS VARCHAR(MAX)), 'encoding="utf-16"', '')  AS XML) AS Content

Content of my XML structure looks like this:

What I want to achieve
I have a temporary table with multiple XML Files in this structure and I am trying to write a SQL query which will show me data in standard structure as a table
SELECT
    DateTimeCreated,
    t.value('(ApplicationHeaderBlock_Output/MessageType/text())[1]', 'varchar(100)') AS MessageType,
    e.value('(SequenceC/Date_C_98A/Date/text())[1]', 'DATE') AS XDTE,
    e.value('(SequenceC/Date_C_98A//Date/text())[1]', 'DATE') AS RDTE
FROM
    #MTFILE
CROSS APPLY
    Content.nodes('//SWIFTHeader') AS a(t)
CROSS APPLY
    Content.nodes('//SWIFT_CATEGORY5_MT566') AS b(e)

DROP TABLE #MTFILE

Problem and what I want to achieve
I'm not sure how to modify my current SQL query to achieve below results from XML file, because when I'm trying to specify path from XML file you can see it is same (from screenshot structure).
My point is to achieve and see result as below:
| XDTE        | RDTE           |
| --------    | -------------- |
| 20210310    | 20211012       |

If somebody could please advise?

A: Because you didn't provide a minimal reproducible example, we need to assume that your SELECT ... statement is legit.
Here is your answer.
SQL
SELECT
    DateTimeCreated,
    t.value('(ApplicationHeaderBlock_Output/MessageType/text())[1]', 'varchar(100)') AS MessageType,
    e.value('(SequenceC/Date_C_98A[Qualifier/text()="XDTE"]/Date/text())[1]', 'DATE') AS XDTE,
    e.value('(SequenceC/Date_C_98A[Qualifier/text()="RDTE"]/Date/text())[1]', 'DATE') AS RDTE
FROM
    #MTFILE
CROSS APPLY
    Content.nodes('//SWIFTHeader') AS a(t)
CROSS APPLY
    Content.nodes('//SWIFT_CATEGORY5_MT566') AS b(e);

A: Extract Qualifier and pivot. I use conditional aggregation for pivoting. Your DBMS may have  a special PIVOT tool.
select DateTimeCreated, MessageType,
     max(case when q='XDTE' then d end) as XDTE,
     max(case when q='RDTE' then d end) as RDTE
from (
    -- original query plus `Qualifier`
    -- hopefully it extracts data correctly
    Select DateTimeCreated,
       t.value('(ApplicationHeaderBlock_Output/MessageType/text())[1]', 'varchar(100)') as MessageType,
       e.value('(SequenceC/Date_C_98A/Qualifier/text())[1]', 'DATE') as q,
       e.value('(SequenceC/Date_C_98A/Date/text())[1]', 'DATE') as d
    FROM #MTFILE
    CROSS APPLY Content.nodes('//SWIFTHeader') as a(t)
    CROSS APPLY Content.nodes('//SWIFT_CATEGORY5_MT566') as b(e)
) t
group by DateTimeCreated, MessageType


text:
Q: can we use alb behind new nlb target group, so that we can use all features of REST type api gateway like Cognito, Xray in my current existed environment we have aws alb with backend APIs in ECS fargate, now I want to integrate aws API gateway and Cognito with alb. but as per AWS docs, we can only use rest API type API gateway for Cognito integration, but again as per AWS docs with rest API gateway type we can't use alb and we can only use nlb but my APIs are configured with path-based routing in alb

*

*if I replace my alb with nlb how can I achieve my path-based routing for the backend API's and is there any other way that I can use to configure Cognito, rest API and loadbalcners

*as I said can I use alb behind new nlb target group

A: You can in fact use Cognito to secure HTTP APIs in API Gateway by configuring a JWT authorizer
This example CloudFormation template will help you get it configured.


text:
Q: Recovering forgotten removed packages names After a software remove on my Debian 10.3 XFCE, apt package manager advised that a lot of packages that I really need can be removed because they was "automatically installed":
The following packages were automatically installed and are no longer required:
  cups-pk-helper espeak-ng-data exfalso fonts-font-awesome fonts-lato
  fonts-roboto-slab gir1.2-atspi-2.0 gir1.2-gst-plugins-base-1.0
  gir1.2-gstreamer-1.0 gir1.2-gtksource-3.0 gir1.2-javascriptcoregtk-4.0
  gir1.2-keybinder-3.0 gir1.2-notify-0.7 gir1.2-polkit-1.0 gir1.2-secret-1
  gir1.2-soup-2.4 gir1.2-webkit2-4.0 gir1.2-wnck-3.0 javascript-common
  libao-common libao4 libatk-adaptor libbrlapi0.6 libdotconf0 libespeak-ng1
  libjs-jquery libjs-modernizr libjs-sphinxdoc libjs-underscore liblouis-data
  liblouis17 libpcaudio0 libsonic0 libspeechd2 mlterm mlterm-common
  mlterm-tools ncurses-term orca psf-unifont python3-brlapi python3-certifi
  python3-cups python3-cupshelpers python3-feedparser python3-gst-1.0
  python3-idna python3-louis python3-musicbrainzngs python3-mutagen
  python3-pyatspi python3-pyinotify python3-requests python3-smbc
  python3-speechd python3-urllib3 quodlibet sound-icons speech-dispatcher
  speech-dispatcher-audio-plugins speech-dispatcher-espeak-ng
  sphinx-rtd-theme-common system-config-printer system-config-printer-common
  system-config-printer-udev ttf-unifont unifont x11-apps x11-session-utils
  xbitmaps xbrlapi xfonts-unifont xinit
Use 'sudo apt autoremove' to remove them.

That are really bad news because if I want to remove a package in the future with the apt --purge autoremove command (e.g.), my system could be breaked. So I just remember have been removed xserver-xorg-video-nouveau and, after reinstalling that package, the trouble persist.
The real issue was that apt have been removed more than that package, and just installing it again could be solved the dependency tree.
Solution in answers.

A: Following a comment from A.B about /var/log/apt, I found cat /var/log/apt/history.log. I re-installed the forgotten packages and that was sufficient.
Start-Date: 2020-05-06  01:50:43
Commandline: apt remove xserver-xorg-video-nouveau
Requested-By: jeanfar (1000)
Remove: xserver-xorg-video-nouveau:amd64 (1:1.0.16-1), task-desktop:amd64 (3.53), task-xfce-desktop:amd64 (3.53), xserver-xorg-video-all:amd64 (1:7.7+19)
End-Date: 2020-05-06  01:50:53

I think you would like to know that using - or *- can exclude all packages you don't really want. My use case: sudo apt install -V --show-progress task-desktop task-xfce-desktop xserver-xorg-video-all libreoffice*- firefox-esr*- speech-dispatcher*- orca*-


text:
Q: How to run a single typescript file with Nx I have a Nx Node project that uses pre-processed summary stats files. These stats files require a lot of processing and rarely need to be generated. However, once they are generated the primary Node app runs quickly.
I want a pre-processing step that can be run manually to generate these stats assets. I want to use Nx's typescript, prettier and linting support to write the code to generate these stats files. But creating a whole Node Nx library for each processing step seems like a lot of unnecessary infrastructure.
There is an option to run custom commands: https://nx.dev/latest/node/executors/run-commands-builder. I want to do this with a Typescript file but the documentation only shows shell commands or combining pre-existing Nx commands. AFAICT I can't just point this to a typescript file.
Question is:

*

*Can I run a custom command to trigger a single typescript file?

*Is it more idiomatic to just create a whole Node library for each file that generates these stats?

Thanks

A: I've came across to a similar use case as yours: I've a NX app that needs some sort of scripts to run (not always, so I can't put them in some utility in the app). Those scripts don't need to be transpiled to js, but I want to use all the utils and libs in my nx monorepo.
My solution was to create a script folder inside my app and exclude it from the build process, then on the workspace.json (or project.json) I added this target:
{
  "run-script": {
    "executor": "@nrwl/workspace:run-commands",
    "configurations": {
      "my-script": {
        "commands": [
          "ts-node apps/path/to/my/script.ts"
        ]
      }
    }
  }
}

and I can run it using the command:
nx run my-project:run-script:my-script

A: Executing the compiled version of the script avoids a lot of pain if you have specialized tsconfig files and dependent libraries used by the script. Executing the following:
nx g @nrwl/workspace:run-commands run-script --project my-project --command 'node dist/apps/my-project/main.js'

Creates a command that uses the javascript compilation of the script bypassing all of the typescript configuration.  It produces the following in apps/my-project/project.json
    "run-script": {
      "executor": "@nrwl/workspace:run-commands",
      "outputs": [],
      "options": {
        "command": "node dist/apps/my-project/main.js"
      }
    }

Which can then be executed by:
nx run my-project:run-script

Thanks to alessiopremoli and Dharman for pointing me in the right direction.

A: You don't have to create a separate library for each. If they all fit within the category of "generate my preprocessed stats" then they can (maybe should) go together.
As for triggering a single TypeScript file, TypeScript files are not meant to be triggered. Instead, we compile them into JS and run the JS files using Node. In general, this translates to the following commands:

*

*Run tsc to compile your TypeScript files.

*Run node <your-main-file>.js to execute your JS file(s).

Compilation

Command
Description

tsc index.ts
Compile a single file named index.ts in the current directory.

tsc *.ts
Compile all TypeScript files in the current directory.

tsc --project tsconfig.stats-type1.json ortsc --project tsconfig.stats-type2.json or...
Compile according to the specified config file from the current directory.

The last example shows how you could have several tsconfig.json files in your library, one for each stats type, in order to create different variations of your compilation according to your needs.

See tsc CLI options for more info.

Execution
After that, depending on where you told tsc to output your files to, pass the created file to node.
In case you want to run more than one file in a single command, there are a few ways to do that. One would be creating a main file which imports and calls functions from all other files.
Good luck.

A: I had a similar situation where I wanted to run a nx node app once to perform a task and output the result. I appended this to my app's targets:
// project.json

{
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "apps/app-name/src",
  "projectType": "application",
  "targets": {
    ...
    "run": {
      "executor": "@nrwl/workspace:run-commands",
      "options": {
        "commands": [
          "nx run app-name:build:production",
          "node dist/apps/app-name/main.js"
        ]
      }
    }
  },
  "tags": []
}

Then to run the app once: nx run app-name:run

A: Add the following to project.json:
"targets": {
        "check": {
            "executor": "nx:run-commands",
            "options": {
                "command": "ts-node scriptPath/check.ts",
                "parallel": false
            }
        },

        // ...other targets: build, serve, test, ...

And then:
npx nx run YOUR_PROJECT_NAME:check

Official documentation: run-commands and  run-scripts

A: After six months I'm back to this issue and both my old answer and the other added in the meantime don't work for my (new) case: I have to run a script with specific imports from the nx monorepo. After digging through the updates I've come up with a new solution.
The main idea is to store your app / lib related scripts in a sub-folder of the project folder to which they're related and then add to the workspace.json or project.json a specific build command for this folder, something like:
{
    "_build_scripts": {
        "executor": "@nrwl/node:build",
        "outputs": [
            "{options.outputPath}"
        ],
        "options": {
            "outputPath": "dist/libs/my-project-path",
            "tsConfig": "libs/my-project-path/tsconfig.lib.json",
            "packageJson": "libs/my-project-path/package.json",
            "main": "libs/my-project-path/scripts/myscript.ts",
            "assets": ["if needed"]
        }
    }
}

then you can set up your run script command, always in the workspace.json or project.json:
{
  "run-script": {
    "executor": "@nrwl/workspace:run-commands",
    "configurations": {
      "my-script": {
        "commands": [
          "./node_modules/.bin/nx run my-project:_build_script",
          "node dist/my-project-path/main.js"
        ],
        "parallel": false
      }
    }
  }
}

Two things to keep in mind: parallel set to false is mandatory, you need the build step before executing the script; in my case, before the node main.js I had to cd in the directory since fs was reading some files resolving paths incompatible with the monorepo root.
In the end you can run:
npx nx run my-project:run-script:my-script


text:
Q: Extend (Lie) group action from the boundary to the entire manifold Let $M$ and $W$ be smooth manifolds such that $\partial W=M$. Let $G$ be a group acting on $M$.
Can one generally extend the action of $G$ to $W$? If not, under which conditions on $W$ and/or $G$ does it work? How do you construct such an extension?
EDIT: suppose in addition that $G$ is a connected Lie group acting smoothly and that the extension should be smooth as well.
EDIT: suppose furthermore that the Lie group is acting by isometries if a Riemannian metric is given on $M$ and the extension should again be acting isometrically.

A: Edit: I might have misinterpreted the question, which asks whether the action on $M$ extends to a specific bounding manifold $W$. The answer below concerns whether the action extends to some bounding manifold.
Your question can be rephrased in the language of algebraic topology as: If $M$ is a null-bordant manifold with a $G$-action, is $M$ equivariantly null-bordant? Equivariant (co)bordism was a very active subject in the 1960s and 70s, dating back at least as far as the monograph by Conner and Floyd:
Conner, P. E.; Floyd, E. E., Differentiable periodic maps, Ergebnisse der Mathematik und ihrer Grenzgebiete. Neue Folge. 33, Reihe: Moderne Topologie. Berlin-Göttingen-Heidelberg: Springer-Verlag. VII, 148 p. (1964). ZBL0125.40103.
Part I gives an introduction to bordism theory, and Part II studies $G$-equivariant bordism with $G=\mathbb{Z}/p$. Some of the results apply to general Lie groups $G$. For example: if $G$ acts freely on a closed manifold $M$ of dimension $m$, the bordism class of the pair $(M/G,f)$ in the bordism group $\Omega_m(BG)$, where $f:M/G\to BG$ classifies the principal $G$-bundle $M\to M/G$, provides an obstruction to extending the action to a free action on an $(m+1)$-dimensional manifold with boundary. This can be studied using characteristic numbers.

A: Here is an example of a connected Lie group acting on $M$, such that the action does not extend to $W$ but extends to some $W'$ with $\partial W'=M$. All the existing actions are analytic isometric, and all obstructions are continuous, so the problem is not regularity.
Take $G=M=\mathbb T^1$ the 1-torus, acting on itself in the obvious fashion, by translations. Clearly, if $M$ is seen as the boundary of the disc $W'=\mathbb D^2$, then the action on $M$ extends to an action on $W'$, again by rotations. (In the following I prefer to think of $\mathbb T^1$ as $\mathbb R/\mathbb Z$.)
However, let $W$ be a 2-torus with a disc removed, and identify $M$ with the boundary of $W$. Assume by contradiction that the induced action on $\partial W$ is the restriction of an action on $W$.
Let $Z$ be the manifold constructed as the gluing of $[0,1]\times M$ with $W$ along $\lbrace1\rbrace\times M$ and $\partial W$. Define an action of $\mathbb R$ on $Z$ in such a way that the boundary of $Z$ (which corresponds to $\lbrace0\rbrace\times M$) is fixed, and the restriction to $W$ is the action induced by that of $\mathbb T^1$ on $W$. On $[0,1]\times M$, we have to continuously Dehn-twist the collar to match the rotation of $\lbrace1\rbrace\times M$.
Now the action $f$ at time $1$ is homotopic to the identity of $Z$ relative to its boundary (in the strong sense), but $f$ is just a Dehn twist of $[0,1]\times M$, since $f$ is the identity in $W$ (1 has image 0 in $\mathbb T^1$). It is probably classical that this Dehn twist is not homotopic to the identity relatively to the boundary, personally I convinced myself on a picture that the induced map $f_*$ on $\pi_1(M,x)$ for $x$ on the boundary is not the identity; in any case, this is a contradiction.


text:
Q: GeoPandas - grid scattered data and reproject I need to grid scattered data in a GeoPandas dataframe to a regular grid (e.g. 1 degree) and get the mean values of the individual grid boxes and secondly plot this data with various projections.
The first point I managed to achieve using the gpd_lite_toolbox.
This result I can plot on a simple lat lon map, however trying to convert this to any other projection fails.
Here is a small example with some artificial data showing my issue:
import gpd_lite_toolbox as glt
import geopandas as gpd
import matplotlib.pyplot as plt
import pandas as pd
from shapely import wkt

# creating the artificial df
df = pd.DataFrame(
{'data': [20, 15, 17.5, 11.25, 16],
 'Coordinates': ['POINT(-58.66 -34.58)', 'POINT(-47.91 -15.78)',
                 'POINT(-70.66 -33.45)', 'POINT(-74.08 4.60)',
                 'POINT(-66.86 10.48)']})

# converting the df to a gdf with projection
df['Coordinates'] = df['Coordinates'].apply(wkt.loads)
crs = {'init': 'epsg:4326'}
gdf = gpd.GeoDataFrame(df, crs=crs, geometry='Coordinates')

# gridding the data using the gridify_data function from the toolbox and setting grids without data to nan
g1 = glt.gridify_data(gdf, 1, 'data', cut=False)
g1 = g1.where(g1['data'] > 1)

# simple plot of the gridded data
fig, ax = plt.subplots(ncols=1, figsize=(20, 10))
g1.plot(ax=ax, column='data', cmap='jet')

# trying to convert to (any) other projection
g2 = g1.to_crs({'init': 'epsg:3395'})

# I get the following error
---------------------------------------------------------------------------

AttributeError: 'float' object has no attribute 'is_empty'

I would also be happy to use different gridding function if this solves the problem

A: Your g1 conatin too much NaN value.
g1 = g1.where(g1['data'] > 1)
print(g1)

                                               geometry   data
0                                                   NaN    NaN
1                                                   NaN    NaN
2                                                   NaN    NaN
3                                                   NaN    NaN
4                                                   NaN    NaN
5     POLYGON ((-74.08 5.48, -73.08 5.48, -73.08 4.4...  11.25
...

You should use g1[g1['data'] > 1] instead of g1.where(g1['data'] > 1).
g1 = g1[g1['data'] > 1]
print(g1)

                                               geometry   data
5     POLYGON ((-74.08 5.48, -73.08 5.48, -73.08 4.4...  11.25
181   POLYGON ((-71.08 -32.52, -70.08 -32.52, -70.08...  17.50
322   POLYGON ((-67.08 10.48, -66.08 10.48, -66.08 9...  16.00
735   POLYGON ((-59.08 -34.52, -58.08 -34.52, -58.08...  20.00
1222  POLYGON ((-48.08 -15.52, -47.08 -15.52, -47.08...  15.00

g2 = g1.to_crs({'init': 'epsg:3395'})
print(g2)
                                               geometry   data
5     POLYGON ((-8246547.877965705 606885.3761893312...  11.25
181   POLYGON ((-7912589.405585884 -3808795.10464339...  17.50
322   POLYGON ((-7467311.442412791 1165421.424891677...  16.00
735   POLYGON ((-6576755.516066602 -4074627.00861716...  20.00
1222  POLYGON ((-5352241.117340593 -1737775.44359649...  15.00


text:
Q: Flutter - refresh single element in ListView on ListTile tap Here is flow I want to achieve:

*

*get list of items and put it in ListView as ListTile

*on item tap update item status in Firebase (from unread to read)

*refresh single one item in List

*navigate to other

*on click back button get list with updated element - marked as readed

Is there any possibility to refresh single one element in ListView on tap? By now I tried to use  setState() method but It didn't work - item is updated in Firebase but change doesn't appears in list until I refresh page manually.
onTap function
onTap: () {
  setState(() {
    _notifications[index].data['viewed'] = true;
  });

  _userService.setNotificationAsClicked(_notifications[index].data['id']);
  Navigator.of(context).pushNamed(_notifications[index].data['routing']);
},

BackButton:
return Container(
  child: BackButton(
    onPressed: () {
      Navigator.pop(context);
    },
  ),
);

EDIT:
It works when in back button I use Navigator.of(context).pushNamed(...) instead of Navigator.pop(), but in this case I need to scroll down and reload again all elements...
I FOUND SOLUTION!!!
All I need to do was change storing List with DocumentSnapshot to List with data from DocumentSnapshot.


text:
Q: Can a gauge transformation eliminate singularity of gauge potential? Suppose I have a gauge potential $A$ which goes to infinity at some point $x_0$. Can I use a gauge transformation
\begin{equation}
A'=U^{-1}AU+U^{-1}dU,~~~U=\exp\{-i\alpha^a(x)T^a\}
\end{equation}
to kill the singularity, i.e, $A'$ is non-singular? I have seen somewhere that for the physical gauge transformation, the functions in $U$ should be non-singular and vanish at infinity. Is this right? If two gauge potentials differ by a singular $U$(i.e., $\alpha^a$'s are singular somewhere), are they "gauge-eqivalent"?

A: We can identify two cases here.
Case 1: The gauge potential has a singularity which produces a singularity in the physical field too.
Given that the physical field is invariant under gauge transformations, it follows that you won't be able to cure this by making a gauge transformation. We can make a trivial example of this by considering a $U(1)$ theory in two dimensions. Take the gauge field to be $A=(x^{-1},0)$. The physical field is $F_{01}=(\mathrm d A)_{01}= x^{-2}$. These are both singular at the origin. I can try to remove the singularity in the $0$-component of $A$ by performing a gauge transformation $\Lambda=-tx^{-1}$. The new gauge field is $A+\mathrm d \Lambda=(0,tx^{-2})$. So I have only managed to move the singularity to a different component of the gauge field.
Case 2: The gauge potential has a singularity but the physical field is regular.
In this case there is no singular behavior in the physical field, so it should be possible to remove this behavior from the gauge field. Consider the gauge field $A=(x^{-1},-tx^{-2})$. This is singular at the origin, but the physical field is $F_{01}=(\mathrm d A)_{01}=0$. Under the same gauge transformation as above, we can obtain $A=0$.
Commentary: In general, singularities in physical fields are undesirable and indicate a deficiency in the theory, like for example the singular field of a point charge in classical EM or the singularity in a black hole in GR. The point charge in classical EM has both a singular electric field and a singular scalar potential, and there is nothing that can be done about this within the context of the classical theory. However, as long as we are only interested in phenomena sufficiently far away from the charge, there's no reason to worry about it. This is the situation in Case 1 above. In Case 2, the singular potential is artificial: this is really a vacuum solution. So really we should never have written a singular potential at all. Indeed, the potential I gave is not even really defined at the origin, but yet the physical field at the origin is perfectly normal and in fact just zero. But if for some reason someone gave you a singular potential for a non-singular field, you could undo it with a singular gauge transformation. I would view this as just "undoing" the improper step of writing down a singular potential to begin with.