问:
Parent view model that contains both models
I have two separate child models which I have created and I want to be able to create a parent model which would allow me to use both child models in one View.

The problem that I am running into is that I keep getting errors from my View which is informing me that Parent Model isn't accessing the variable.
"MainPageModel does not contain a defintion..."

My end goal from this is to be able to have a form that uses input and has the ability to upload an image all in one model. This creates a simple profile with an image. On submission, you would be brought to another View, with what your profile would look like.

MODEL 1:

```<code>namespace Profile.Models
{
    public class Profiler
    {
        public string FName { get; set; }
        public string Address { get; set; }
        public string BirthDate { get; set; }
        public string PhoneNumber { get; set; }
        public string Comments { get; set; }
    }
}
</code>```

Model 2:

```<code>namespace Profile.Models
{
    public interface IFormFile
    {
        string ContentType { get; }
        string ContentDisposition { get; }
        IHeaderDictionary Headers { get; }
        long Length { get; }
        string Name { get; }
        string FileName { get; }
        Stream OpenReadStream();
        void CopyTo(Stream target);
        Task CopyToAsync(Stream target, CancellationToken cancellationToken);
    }
}
</code>```

Parent Model:

```<code>namespace Profile.Models
{
    public class MainPageModel
    {
        public Profiler Profiler { get; set; }
        public IFormFile IFormFile { get; set; }

        public MainPageModel(Profiler Profiler)
        {
            Profiler = Profiler;
        }
    }
}
</code>```

View:

```<code>@model Profile.Models.MainPageModel
@{
    ViewData["Title"] = "Profiler";
}
<h2>Create your Profile using the form below</h2>
<h3>On Submission, your profile will be created for you to see.</h3>

<form asp-action="Profiler" >
    <label asp-for="FName"></label>
    <input asp-for="FName" /> <br /><br />
    <label asp-for="Address"></label>
    <input asp-for="Address" /> <br /><br />
    <label asp-for="BirthDate"></label>
    <input asp-for="BirthDate" /> <br /><br />
    <label asp-for="PhoneNumber"></label>
    <input asp-for="PhoneNumber" /> <br /><br />
    <label asp-for="Comments"></label>
    <input asp-for="Comments" /> <br /><br />
    <input type="submit" value="Submit" />
</form>

<form method="post" enctype="multipart/form-data">
    <input type="file" name="files" multiple />
    <input type="submit" value="Upload" />
</form>
</code>```

HomeController:

```<code>public IActionResult Profiler([Bind("FName,Address,BirthDate,PhoneNumber,Comments")] Profiler Profiles)
    {
        return View(new MainPageModel (Profiles));
    }
</code>```

答:
First, why do you have an interface for IFormFile? There is already such an interface built-in to ASP.NET Core. At the least, it's redundant and unnecessary, and at the most you're going to end up causing conflicts. Get rid of it, and use the built-in IFormFile.

Then, your action is accepting only a Profiler instance. Your action needs to accept the same view model you're passing to your view or you're going to end up with all kinds of problems. In other words, if you want a combined view model like this, then you need to post that as well.

However, you don't need that at all if you actually set this up properly in the first place. First, you should never bind to an entity directly. An entity class is and should be a simple DTO class, and should be designed only with an eye to the needs of the database, since that's its purpose. The view has different concerns and needs, which are totally inappropriate to be handled by your entity class. This is the purpose of view models, so you should have one like ProfilerViewModel. Your Profiler entity should have some way of persisting your file uploads, whether that be byte[] properties or simple string properties that merely point to URL or file path where the uploaded file can be found. Your view model, meanwhile, would have your IFormFile property. When mapping from your view model to your entity, you would then save the uploaded file and fill the appropriate propert(ies) on your entity.

This also allows you to get rid of the god-forsaken Bind attribute, which should really never be used. Seriously, it's horrible in every facet. It only exists to pave over the glaring security vulnerability caused by using entities directly, instead of actually encouraging developers to design their applications correctly in the first place.

With your action accepting a correct view model, you can then fix the issue of having two separate forms on the page, which is going to severely piss your users off, since submitting the first form will not post any uploaded files and submitting the second form will not post any profile changes they made. Basically, either way, you're discarding user input. Move the file input into the first form and get rid of the second. And, of course, bring the enctype attribute over as well.

Finally, you're allowing multiple files to be uploaded, but all you have is a property that accepts a single IFormFile. You need a List<IFormFile>.

Long and short:

```<code>public class ProfilerViewModel
{
    public string FName { get; set; }
    public string Address { get; set; }
    public string BirthDate { get; set; }
    public string PhoneNumber { get; set; }
    public string Comments { get; set; }

    public List<IFormFile> Files { get; set; }
}
</code>```

Then:

```<code>public async Task<IActionResult> Profiler(ProfilerViewModel model)
{
    if (ModelState.IsValid)
    {
        var profile = new Profiler
        {
            FName = model.FName,
            Address = model.Address,
            BirthDate = model.BirthDate,
            PhoneNumber = model.PhoneNumber
            Comments = model.Comments
        };

        foreach (var file in model.Files)
        {
            // handle your file uploads
        }

        db.Profiles.Add(profile);
        await db.SaveChangesAsync();

        return RedirectToAction("Somewhere");
    }

    return View(model);
}
</code>```

And in your view:

```<code>@model Profile.Models.ProfilerViewModel
@{
    ViewData["Title"] = "Profiler";
}
<h2>Create your Profile using the form below</h2>
<h3>On Submission, your profile will be created for you to see.</h3>

<form asp-action="Profiler" method="post" enctype="multipart/form-data">
    <label asp-for="FName"></label>
    <input asp-for="FName" /> <br /><br />
    <label asp-for="Address"></label>
    <input asp-for="Address" /> <br /><br />
    <label asp-for="BirthDate"></label>
    <input asp-for="BirthDate" /> <br /><br />
    <label asp-for="PhoneNumber"></label>
    <input asp-for="PhoneNumber" /> <br /><br />
    <label asp-for="Comments"></label>
    <input asp-for="Comments" /> <br /><br />
    <input asp-for="Files" />
    <input type="submit" value="Submit" />
</form>
</code>```

Then, everything should work just fine.

Body:
I have two separate child models which I have created and I want to be able to create a parent model which would allow me to use both child models in one View.

The problem that I am running into is that I keep getting errors from my View which is informing me that Parent Model isn't accessing the variable.
"MainPageModel does not contain a defintion..."

My end goal from this is to be able to have a form that uses input and has the ability to upload an image all in one model. This creates a simple profile with an image. On submission, you would be brought to another View, with what your profile would look like.

MODEL 1:

namespace Profile.Models
{
    public class Profiler
    {
        public string FName { get; set; }
        public string Address { get; set; }
        public string BirthDate { get; set; }
        public string PhoneNumber { get; set; }
        public string Comments { get; set; }
    }
}

Model 2:

namespace Profile.Models
{
    public interface IFormFile
    {
        string ContentType { get; }
        string ContentDisposition { get; }
        IHeaderDictionary Headers { get; }
        long Length { get; }
        string Name { get; }
        string FileName { get; }
        Stream OpenReadStream();
        void CopyTo(Stream target);
        Task CopyToAsync(Stream target, CancellationToken cancellationToken);
    }
}

Parent Model:

namespace Profile.Models
{
    public class MainPageModel
    {
        public Profiler Profiler { get; set; }
        public IFormFile IFormFile { get; set; }

        public MainPageModel(Profiler Profiler)
        {
            Profiler = Profiler;
        }
    }
}

View:

@model Profile.Models.MainPageModel
@{
    ViewData["Title"] = "Profiler";
}

Create your Profile using the form below

On Submission, your profile will be created for you to see.

<form asp-action="Profiler" >

    <input asp-for="FName" />

    <input asp-for="Address" />

    <input asp-for="BirthDate" />

    <input asp-for="PhoneNumber" />

    <input asp-for="Comments" />

    <input type="submit" value="Submit" />
</form>

<form method="post" enctype="multipart/form-data">
    <input type="file" name="files" multiple />
    <input type="submit" value="Upload" />
</form>

HomeController:

public IActionResult Profiler([Bind("FName,Address,BirthDate,PhoneNumber,Comments")] Profiler Profiles)
    {
        return View(new MainPageModel (Profiles));
    }

Body:
First, why do you have an interface for IFormFile? There is already such an interface built-in to ASP.NET Core. At the least, it's redundant and unnecessary, and at the most you're going to end up causing conflicts. Get rid of it, and use the built-in IFormFile.

Then, your action is accepting only a Profiler instance. Your action needs to accept the same view model you're passing to your view or you're going to end up with all kinds of problems. In other words, if you want a combined view model like this, then you need to post that as well.

However, you don't need that at all if you actually set this up properly in the first place. First, you should never bind to an entity directly. An entity class is and should be a simple DTO class, and should be designed only with an eye to the needs of the database, since that's its purpose. The view has different concerns and needs, which are totally inappropriate to be handled by your entity class. This is the purpose of view models, so you should have one like ProfilerViewModel. Your Profiler entity should have some way of persisting your file uploads, whether that be byte[] properties or simple string properties that merely point to URL or file path where the uploaded file can be found. Your view model, meanwhile, would have your IFormFile property. When mapping from your view model to your entity, you would then save the uploaded file and fill the appropriate propert(ies) on your entity.

This also allows you to get rid of the god-forsaken Bind attribute, which should really never be used. Seriously, it's horrible in every facet. It only exists to pave over the glaring security vulnerability caused by using entities directly, instead of actually encouraging developers to design their applications correctly in the first place.

With your action accepting a correct view model, you can then fix the issue of having two separate forms on the page, which is going to severely piss your users off, since submitting the first form will not post any uploaded files and submitting the second form will not post any profile changes they made. Basically, either way, you're discarding user input. Move the file input into the first form and get rid of the second. And, of course, bring the enctype attribute over as well.

Finally, you're allowing multiple files to be uploaded, but all you have is a property that accepts a single IFormFile. You need a List<IFormFile>.

Long and short:

public class ProfilerViewModel
{
    public string FName { get; set; }
    public string Address { get; set; }
    public string BirthDate { get; set; }
    public string PhoneNumber { get; set; }
    public string Comments { get; set; }

    public List<IFormFile> Files { get; set; }
}

Then:

public async Task<IActionResult> Profiler(ProfilerViewModel model)
{
    if (ModelState.IsValid)
    {
        var profile = new Profiler
        {
            FName = model.FName,
            Address = model.Address,
            BirthDate = model.BirthDate,
            PhoneNumber = model.PhoneNumber
            Comments = model.Comments
        };

        foreach (var file in model.Files)
        {
            // handle your file uploads
        }

        db.Profiles.Add(profile);
        await db.SaveChangesAsync();

        return RedirectToAction("Somewhere");
    }

    return View(model);
}

And in your view:

@model Profile.Models.ProfilerViewModel
@{
    ViewData["Title"] = "Profiler";
}
<h2>Create your Profile using the form below</h2>
<h3>On Submission, your profile will be created for you to see.</h3>

<form asp-action="Profiler" method="post" enctype="multipart/form-data">
    <label asp-for="FName"></label>
    <input asp-for="FName" /> <br /><br />
    <label asp-for="Address"></label>
    <input asp-for="Address" /> <br /><br />
    <label asp-for="BirthDate"></label>
    <input asp-for="BirthDate" /> <br /><br />
    <label asp-for="PhoneNumber"></label>
    <input asp-for="PhoneNumber" /> <br /><br />
    <label asp-for="Comments"></label>
    <input asp-for="Comments" /> <br /><br />
    <input asp-for="Files" />
    <input type="submit" value="Submit" />
</form>

Then, everything should work just fine.


来源: stackexchange

问:
Azure AD B2C - Is there a way to configure single email address instead of multiple email address
We are trying to use Azure AD B2C using the Application claims. In the application claims we find the email address claim type as Emails and with value 'String Array'. We need to configure single email address instead of multiple email address having the claim type as string and claim as email instead of extended_email claim type.

Does there exist a way to configure this type of claim?

答:
This is currently not possible in B2C with standard policies. There are multiple email addresses on the user object, and if they all have values, they can all be sent in the token. Hence, the emails claim is an array.

In the future, this may be solved by emitting a claim that represents the email address or username the user used to sign in as preferred_username claim. However, there is no timeline for that yet.

On the other hand, if you are using custom policies, then you can certainly add a specific email address in the token. All you need to do is find the claim that holds the value you are seeking (e.g. signInNames.emailAddress) and put it as an OutputClaim of the TechnicalProfile in RelyingParty section. You can provide a PartnerClaimType which will be the claim type used in the token.

ContentLicense: CC BY-SA 3.0


问:
Symfony 1 create a view cache files before user visits the page
After clearing the cache, is there any way to create a view cache files before user visits the page? Currently we are using the below command which creates a few of the cache files but not the view ones.</p>

```<code>symfony cache:prime --env=qa frontend
</code>```

答:
Yes there is a way to generate cache files before a user visits the page.  You need to create a cache warm-up script.  A simple curl command to each URL will create the cache files:

```<code>curl http://myapp.example.com/user/action/
</code>```

Another option is to create a PHP script, and using Symfony's built-in browser that is normally used for testing, you can use it for warming up your cache, like this example:

```<code>require_once(dirname(__FILE__).'/../config/ProjectConfiguration.class.php');
$configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'staging', false);
sfContext::createInstance($configuration);

// Array of URLs to browse
$pages = array(
  '/foo/index',
  '/foo/bar/id/1',
  ...
);

$b = new sfBrowser();
foreach ($pages as $page)
{
  $b->get($page);
}
</code>```

There is more information here http://symfony.com/legacy/doc/gentle-introduction/1_4/en/18-Performance under the Generating Cached Pages section and more information about caching is here http://symfony.com/legacy/doc/gentle-introduction/1_4/en/12-Caching

Body:
After clearing the cache, is there any way to create a view cache files before user visits the page? Currently we are using the below command which creates a few of the cache files but not the view ones.

symfony cache:prime --env=qa frontend

Body:
Yes there is a way to generate cache files before a user visits the page.  You need to create a cache warm-up script.  A simple curl command to each URL will create the cache files:

curl http://myapp.example.com/user/action/

Another option is to create a PHP script, and using Symfony's built-in browser that is normally used for testing, you can use it for warming up your cache, like this example:

require_once(dirname(__FILE__).'/../config/ProjectConfiguration.class.php');
$configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'staging', false);
sfContext::createInstance($configuration);

// Array of URLs to browse
$pages = array(
  '/foo/index',
  '/foo/bar/id/1',
  ...
);

$b = new sfBrowser();
foreach ($pages as $page)
{
  $b->get($page);
}

There is more information here http://symfony.com/legacy/doc/gentle-introduction/1_4/en/18-Performance under the Generating Cached Pages section and more information about caching is here http://symfony.com/legacy/doc/gentle-introduction/1_4/en/12-Caching


问:
Hiding a message in a JPEG image
I am working on a writing a program that embeds data in a photo (steganography). This worked completely fine when I was using png lossless compression however I would like this to work in JPEG file format. Previously I would read in my image file and replace the last two bits in every color channel with a part of my message. Then I would compress it and output it. With lossy compression however I am assuming I cannot embed a message pre compression because without a doubt, the message would be unreadable.

My question is, do I need to embed the message post compression/encoding somewhere in the SOS YCbCr data? If not there then where must I store the message? Thank you in advance.

答: The best place to hide a message in JPEG is in the blocks that extend beyond the edge of the image (unless the image dimensions are multiples of 8).</p>

Title: Hiding a message in a JPEG image


问:
laravel 5.4 embed image in mail
I have just upgraded my 5.2 install of laravel to 5.3 and then to 5.4 following the official upgrading methods.

I am now trying to use one of the new features, to create a markdown formated email.

According to the documentation found at: https://laravel.com/docs/5.4/mail#view-data

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:

However, this:

```<code><img src="{{ $message->embed(public_path().'/img/official_logo.png') }}">
</code>```

will produce the following error:

Undefined variable: message

Am I missing something? Or is there something undocumented in the upgrading guides?

Later edit:

I am calling the email function with:

\Mail::to($user)->send(new WelcomeCandidate($user, $request->input('password')));

And WelcomeCandidate looks like:

```<code><?php

namespace App\Mail;

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

use App\Models\User;

class WelcomeCandidate extends Mailable
{

    use Queueable, SerializesModels;

    public $user;
    public $password;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(User $user, $password)
    {
        //
        $this->user = $user;
        $this->password = $password;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $this->subject('Welcome!');
        return $this->markdown('emails.welcome-candidate');
    }
}
</code>```

答:
Solved my issue!

```<code>  <img src="{{ $message->embed(base_path() . '/img/logo.png') }}" />
Controller:

\Mail::send(['html' =>'mail'],
        array(
            'name' => $r->name,
            'email' => $r->email,
            'user_message' => $r->message,
           // 'telephone'=>$r->telephone,
           // 'subject'=>$r->subject
        ), function($message) use ($r)  {

            $message->to('abc@gmail.com')->subject('Contact Form || abc.com');
            $message->from($r->email);
            // ->setBody($r->user_message); // assuming text/plain

        });
</code>```

If you are in localhost , you can use public_path instead of base_path function

Title: laravel 5.4 embed image in mail

Body:
I have just upgraded my 5.2 install of laravel to 5.3 and then to 5.4 following the official upgrading methods.

I am now trying to use one of the new features, to create a markdown formated email.

According to the documentation found at: https://laravel.com/docs/5.4/mail#view-data

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:

However, this:

embed(public_path().'/img/official_logo.png') }}">

will produce the following error:

Undefined variable: message

Am I missing something? Or is there something undocumented in the upgrading guides?

Later edit:

I am calling the email function with:

\Mail::to($user)->send(new WelcomeCandidate($user, $request->input('password')));

And WelcomeCandidate looks like:

<?php

namespace App\Mail;

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

use App\Models\User;

class WelcomeCandidate extends Mailable
{

    use Queueable, SerializesModels;

    public $user;
    public $password;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(User $user, $password)
    {
        //
        $this->user = $user;
        $this->password = $password;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $this->subject('Welcome!');
        return $this->markdown('emails.welcome-candidate');
    }
}

Body:
Solved my issue!

  <img src="{{ $message->embed(base_path() . '/img/logo.png') }}" />
Controller:

\Mail::send(['html' =>'mail'],
        array(
            'name' => $r->name,
            'email' => $r->email,
            'user_message' => $r->message,
           // 'telephone'=>$r->telephone,
           // 'subject'=>$r->subject
        ), function($message) use ($r)  {

            $message->to('abc@gmail.com')->subject('Contact Form || abc.com');
            $message->from($r->email);
            // ->setBody($r->user_message); // assuming text/plain

        });

If you are in localhost , you can use public_path instead of base_path function


问:
detail about javascript callbacks
I am curious about something, imagine a link that closes the window. See the code below, and read the comments:

```<code>var a = document.querySelector('a');

//
// Since a.onclick requires a callback I have the following code:
//

a.onclick = function() { window.close() }; // This works fine.
a.onclick = function() { close() }; // This works as well.
a.onclick = () => { close() }; // This also work.
a.onclick = () => close(); // This works.

// But...

a.onclick = window.close; // This doesn't work.
a.onclick = close; // Neither this.

// But, why not?? Since onclick requires a function, and window.close is a
// function and close is just the shorten way to call window.close?

// However...

a.onclick = close.bind(); // This works fine....
</code>```

So fellows, since onclick receives a function, why to set just "close" does not do the job? It should "register" the function close (window.close) as the "callback" for that action, and call it when the event was triggered (like close.call());

I really don't understand this behavior

答:
This is a bit tricky.

We are so used to seeing window holding all global variables that we have forgotten that window itself is an object. That's right - it's the object that represent the browser window.

And close is not merely a function but a method of the window object (see: https://developer.mozilla.org/en-US/docs/Web/API/Window/close).

Thus when you convert close to a function reference it loses it's binding to this (which should point to window).

The others work by happenstance:

a.onclick = function() { window.close() };

This is obvious. You're calling the method directly so it gets the correct this.

a.onclick = function() { close() };

A function that does not belong to any object will have it's this either pointing to the global object (window) or undefined if in strict mode. So when not in strict mode this will work.

a.onclick = () => { close() };

Same explanation as number 2.

a.onclick = () => close();

Same explanation as 3 but not using the optional {}.

Note: One may be tempted to think that 2, 3 and 4 are different mechanisms but while arrow functions affect how this behave you're not calling this.close(). Thus only the this value in close is important. The arrow functions don't change that.

Note that when not in strict mode the following should also work:

```<code>a.onclick = () => { this.close() }
</code>```

I think it's fairly obvious from my previous explanations why the above should work.

Title: detail about javascript callbacks

Body:
I am curious about something, imagine a link that closes the window. See the code below, and read the comments:

var a = document.querySelector('a');

//
// Since a.onclick requires a callback I have the following code:
//

a.onclick = function() { window.close() }; // This works fine.
a.onclick = function() { close() }; // This works as well.
a.onclick = () => { close() }; // This also work.
a.onclick = () => close(); // This works.

// But...

a.onclick = window.close; // This doesn't work.
a.onclick = close; // Neither this.

// But, why not?? Since onclick requires a function, and window.close is a
// function and close is just the shorten way to call window.close?

// However...

a.onclick = close.bind(); // This works fine....

So fellows, since onclick receives a function, why to set just "close" does not do the job? It should "register" the function close (window.close) as the "callback" for that action, and call it when the event was triggered (like close.call());

I really don't understand this behavior

Body:
This is a bit tricky.

We are so used to seeing window holding all global variables that we have forgotten that window itself is an object. That's right - it's the object that represent the browser window.

And close is not merely a function but a method of the window object (see: https://developer.mozilla.org/en-US/docs/Web/API/Window/close).

Thus when you convert close to a function reference it loses it's binding to this (which should point to window).

The others work by happenstance:

a.onclick = function() { window.close() };

This is obvious. You're calling the method directly so it gets the correct this.

a.onclick = function() { close() };

A function that does not belong to any object will have it's this either pointing to the global object (window) or undefined if in strict mode. So when not in strict mode this will work.

a.onclick = () => { close() };

Same explanation as number 2.

a.onclick = () => close();

Same explanation as 3 but not using the optional {}.

Note: One may be tempted to think that 2, 3 and 4 are different mechanisms but while arrow functions affect how this behave you're not calling this.close(). Thus only the this value in close is important. The arrow functions don't change that.

Note that when not in strict mode the following should also work:

a.onclick = () => { this.close() }

I think it's fairly obvious from my previous explanations why the above should work.


问:
onTouch not working on listview
Am creating an application where I have a fragment, the xml for the fragment is given below

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cvCalendar"
        android:layout_below="@+id/toolbar"
        android:orientation="vertical"/>

    <ListView
        android:id="@+id/lvList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/Calendar"
        android:divider="#cecece"
        android:dividerHeight="2dp"
        android:background="#e4c966" />

    </RelativeLayout>
</code>```

I have a Linearlayout on top, which is used to display a calendar, and the events of the calendar are shown in below list.
I want to have a feature that on swipe up, calendar gets hidden and on swipe down, it shows back the calendar.
The java code is given below

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
        {
        View rootView = inflater.inflate(R.layout.layout, container, false);
        cala=(LinearLayout)rootView.findViewById(R.id.Calendar);
        rootView.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_MOVE){

            onTouchEvent(event);
          }
        return true;
           }
        });
          return rootView;
         }
public boolean onTouchEvent(MotionEvent touchevent)
    {
       switch (touchevent.getAction())
        {
         case MotionEvent.ACTION_DOWN:
            {
                x1 = touchevent.getX();
                y1 = touchevent.getY();
                break;
              }
            case MotionEvent.ACTION_UP:
            {
                x2 = touchevent.getX();
                y2 = touchevent.getY();

                if (y1 < y2)
                {
                    Toast.makeText(getActivity(), "UP to Down Swap Performed", Toast.LENGTH_SHORT).show();
                    if ((cala.getVisibility())== View.GONE){
                       cala.setVisibility(View.VISIBLE); }
                  }

                if (y1 > y2)
                {
                    Toast.makeText(getActivity(), "Down to UP Swap Performed",Toast.LENGTH_SHORT).show();
                   if ((cala.getVisibility())== View.VISIBLE){
                       cala.setVisibility(View.GONE); }
                   }
                break;
               }
          }
       return false;
}
</code>```

答:
This worked for me:
--onCreate() </p>

```<code>lvListObject.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            onTouchEvent(motionEvent);
            return false;
        }
    });
</code>```

Title: onTouch not working on listview

Body:
Am creating an application where I have a fragment, the xml for the fragment is given below

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cvCalendar"
        android:layout_below="@+id/toolbar"
        android:orientation="vertical"/>

    <ListView
        android:id="@+id/lvList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/Calendar"
        android:divider="#cecece"
        android:dividerHeight="2dp"
        android:background="#e4c966" />

    </RelativeLayout>

I have a Linearlayout on top, which is used to display a calendar, and the events of the calendar are shown in below list.
I want to have a feature that on swipe up, calendar gets hidden and on swipe down, it shows back the calendar.
The java code is given below

public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
        {
        View rootView = inflater.inflate(R.layout.layout, container, false);
        cala=(LinearLayout)rootView.findViewById(R.id.Calendar);
        rootView.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_MOVE){

            onTouchEvent(event);
          }
        return true;
           }
        });
          return rootView;
         }
public boolean onTouchEvent(MotionEvent touchevent)
    {
       switch (touchevent.getAction())
        {
         case MotionEvent.ACTION_DOWN:
            {
                x1 = touchevent.getX();
                y1 = touchevent.getY();
                break;
              }
            case MotionEvent.ACTION_UP:
            {
                x2 = touchevent.getX();
                y2 = touchevent.getY();

                if (y1 < y2)
                {
                    Toast.makeText(getActivity(), "UP to Down Swap Performed", Toast.LENGTH_SHORT).show();
                    if ((cala.getVisibility())== View.GONE){
                       cala.setVisibility(View.VISIBLE); }
                  }

                if (y1 > y2)
                {
                    Toast.makeText(getActivity(), "Down to UP Swap Performed",Toast.LENGTH_SHORT).show();
                   if ((cala.getVisibility())== View.VISIBLE){
                       cala.setVisibility(View.GONE); }
                   }
                break;
               }
          }
       return false;
}

Body:
This worked for me:
--onCreate()

lvListObject.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            onTouchEvent(motionEvent);
            return false;
        }
    });


问:
how do i make labels list manually for my imported images in tensorflow
```<code>fq=glob.glob("*.jpg") # ['0.jpg','1.jpg','2.jpg','3.jpg','4.jpg'],labels for images=[1,1,1,0,0]
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=onehot))
</code>```

assuming that there is  just  2 classes and batch size is 2 and logits are [2,2] tensor,how do i make "onehot" variable list which contains one hot encoded labels like [1,0] for image 0,1,2  .jpg and [0,1] for image 3,4 .jpg. much thanks :)

答:
If you know you want labels = [1, 1, 1, 0, 0], just use

tf.one_hot(labels, depth=2)
```

<p>Results in a tensor of one-hot labels:</p>

<pre class="lang-py prettyprint-override"><code>array([[ 0.,  1.],
       [ 0.,  1.],
       [ 0.,  1.],
       [ 1.,  0.],
       [ 1.,  0.]], dtype=float32)
</code>```

Note tf.one_hot puts the 1 in whatever index is indicated by the first input you give it. Also note that this is a tensor, so if you run this in a notebook and then try to print the tensor, you will get something like:

<tf.Tensor 'one_hot:0' shape=(5, 2) dtype=float32>
```

<p>It's not until it is evaluated that it takes on the values shown above, but that's just how TensorFlow do.</p>

<p>So if you have a batch size of two, you are feeding two labels per training step to your network and then converting those labels (either in the training step or in your network) to one-hot. I would do something like:</p>

<pre class="lang-py prettyprint-override"><code>labels = tf.placeholder(tf.int32, [None])  # 'None' means it has one dimension that is determined by your batch size
# ... define your network ...
loss_op = tf.nn.softmax_cross_entropy_with_logits(logits=logits,
                                                  labels=tf.one_hot(labels))
loss_op = tf.reduce_mean(loss_op)
</code>```

Then in your training process:

for _ in range(num_iter):
    d = # generate data batch
    t = # generate label batch, e.g. [1, 1] for the first two images
    _, batch_loss = sess.run([train_op, loss_op],
                             feed_dict={data: d, labels: t})
```

Body:
fq=glob.glob("*.jpg") # ['0.jpg','1.jpg','2.jpg','3.jpg','4.jpg'],labels for images=[1,1,1,0,0]
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=onehot))

assuming that there is  just  2 classes and batch size is 2 and logits are [2,2] tensor,how do i make "onehot" variable list which contains one hot encoded labels like [1,0] for image 0,1,2  .jpg and [0,1] for image 3,4 .jpg. much thanks :)

Body:
If you know you want labels = [1, 1, 1, 0, 0], just use

tf.one_hot(labels, depth=2)

Results in a tensor of one-hot labels:

array([[ 0.,  1.],
       [ 0.,  1.],
       [ 0.,  1.],
       [ 1.,  0.],
       [ 1.,  0.]], dtype=float32)

Note tf.one_hot puts the 1 in whatever index is indicated by the first input you give it. Also note that this is a tensor, so if you run this in a notebook and then try to print the tensor, you will get something like:

<tf.Tensor 'one_hot:0' shape=(5, 2) dtype=float32>

It's not until it is evaluated that it takes on the values shown above, but that's just how TensorFlow do.

So if you have a batch size of two, you are feeding two labels per training step to your network and then converting those labels (either in the training step or in your network) to one-hot. I would do something like:

labels = tf.placeholder(tf.int32, [None])  # 'None' means it has one dimension that is determined by your batch size
# ... define your network ...
loss_op = tf.nn.softmax_cross_entropy_with_logits(logits=logits,
                                                  labels=tf.one_hot(labels))
loss_op = tf.reduce_mean(loss_op)

Then in your training process:

for _ in range(num_iter):
    d = # generate data batch
    t = # generate label batch, e.g. [1, 1] for the first two images
    _, batch_loss = sess.run([train_op, loss_op],
                             feed_dict={data: d, labels: t})


问:
What happens in TFS when merging 2 different branches where same file is modified in 2 branches.

There is Main branch

I created a new branch from Main called 'PBI'

There is a file called 'publisher' which is modified in Main and it is also modified in 'PBI'

I want to make sure all the changes in Main are reflected in PBI, so I decided to merge main onto PBI so that PBI is upto date with Main.

When I did the merge, in pending changes it showed publisher[merge]

So what happens now when I checkin the pending change which is publisher[merge]

My changes for 'publisher' in PBI remain? ; If this happens it is a disaster, whats the point of merge

The new changes in Main overwrite the content in PBI branch for 'publisher'; If this happens, it is a disaster too

A conflict arises and I need to choose which one remains. This makes sense

答: Depends. Git can auto-merge most of the time, meaning you'll keep the changes for both. When Git can't figure out how to auto-merge your changes (For example, if both branches modified the same line when compared), then a merge conflict will arise, and you'll have to go in there manually and resolve it</p>


问:
Input string to a char pointer member of an array of structure
I'm trying to input a string of characters to a pointer member of char type of an array of structure. The program is terminating after it receives the string for the member name of emp[0]. My code:

```<code>#include<stdio.h>
struct Employee
{
    char *name;
    int salary;
};

int main()
{
    struct Employee emp[3];

    int i;
    for(i=0;i<3;i++)
    {
        scanf("%s%d",emp[i].name,&emp[i].salary);
    }
    printf("\nOutput:");
    for(i=0;i<3;i++)
    {
        printf("\n%s%d",emp[i].name,emp[i].salary);
    }

    return 0;
}
</code>```

When without array, the following code for some variable emp is working fine:

```<code>scanf("%s%d",emp.name,&emp.salary);
</code>```

Any suggestions? Thanks in advance.

答:
Or you can allocate something to name before passing it to scanf.

```<code>emp[i].name = malloc(sizeof*emp[i].name*MAX_LEN);
if( !emp[i].name )
// error in malloc.
</code>```

What happens in your code?

scanf tries to write the characters read to the address contained by name. The address contained by name is indeterminate (some garbage value). Accessing it calls for undefined behavior.

When without array, the following code for some variable emp is working fine!

It works but it is an undefined behavior. The very next time you run the same code it may throw error.

What is that if after malloc?

In case malloc fails to provide with the requested memory it returns NULL. You are checking that to be sure that memory is allocated otherwise you won't access it because it invokes undefined behavior.

Is there anything else??

yes there are couple of things apart from all this

Don't cast the return type of malloc. It's unnecessary.

Free the dynamically allocated memory after you are done working with it. (using free()).

Check the scanf return value to be sure about whether the scanf call succedes.

Reply to user's comment:

If you have name[4] inside struct then you should write
  scanf("%3s",emp[i].name). This 3s limits the characters read by
  scanf to 3 avoiding buffer overflow. The thing is if you enter
  more than 3 characters you will read only 3 characters and rest of
  them will be in input stream.

Note: The question starts with an OR because the other way is what is answered by dbush. I didn't want to repeat it.

Body:
I'm trying to input a string of characters to a pointer member of char type of an array of structure. The program is terminating after it receives the string for the member name of emp[0]. My code:

#include<stdio.h>
struct Employee
{
    char *name;
    int salary;
};

int main()
{
    struct Employee emp[3];

    int i;
    for(i=0;i<3;i++)
    {
        scanf("%s%d",emp[i].name,&emp[i].salary);
    }
    printf("\nOutput:");
    for(i=0;i<3;i++)
    {
        printf("\n%s%d",emp[i].name,emp[i].salary);
    }

    return 0;
}

When without array, the following code for some variable emp is working fine:

scanf("%s%d",emp.name,&emp.salary);

Any suggestions? Thanks in advance.

Body:
Or you can allocate something to name before passing it to scanf.

emp[i].name = malloc(sizeof*emp[i].name*MAX_LEN);
if( !emp[i].name )
// error in malloc.

What happens in your code?

scanf tries to write the characters read to the address contained by name. The address contained by name is indeterminate (some garbage value). Accessing it calls for undefined behavior.

When without array, the following code for some variable emp is working fine!

It works but it is an undefined behavior. The very next time you run the same code it may throw error.

What is that if after malloc?

In case malloc fails to provide with the requested memory it returns NULL. You are checking that to be sure that memory is allocated otherwise you won't access it because it invokes undefined behavior.

Is there anything else??

yes there are couple of things apart from all this

Don't cast the return type of malloc. It's unnecessary.

Free the dynamically allocated memory after you are done working with it. (using free()).

Check the scanf return value to be sure about whether the scanf call succedes.

Reply to user's comment:

If you have name[4] inside struct then you should write
  scanf("%3s",emp[i].name). This 3s limits the characters read by
  scanf to 3 avoiding buffer overflow. The thing is if you enter
  more than 3 characters you will read only 3 characters and rest of
  them will be in input stream.

Note: The question starts with an OR because the other way is what is answered by dbush. I didn't want to repeat it.


问:
UIAlertView show when app loads, open
How show a alertview just when the app open, load...

Like everytime that the user open the app, he see the alert ....

答:
write the alert statment in the following appDelegate method,</p>

```<code>    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
      UIAlertView *alert_View = [[[UIAlertView alloc] initWithTitle:@"Your Title" message:@"Your Message" delegate:self cancelButtonTitle:nil otherButtonTitles:@"YES",@"NO",nil] autorelease];
    [alert_View show];
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: UIAlertView show when app loads, open

Body:
write the alert statment in the following appDelegate method,

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
      UIAlertView *alert_View = [[[UIAlertView alloc] initWithTitle:@"Your Title" message:@"Your Message" delegate:self cancelButtonTitle:nil otherButtonTitles:@"YES",@"NO",nil] autorelease];
    [alert_View show];
}


问:
Could not make tesseract works on Centos7
I'm working on an app using Java Sprint with Maven in Eclipse.

I make tesseract works on my dev machine in Windows (yeah, I know...) but when I tried to deploy the app in the server which is a Centos 7, I get some errors and the app stop working...

pom.sml

```<code><dependency>
    <groupId>org.bytedeco.javacpp-presets</groupId>
    <artifactId>tesseract-platform</artifactId>
    <version>3.04.01-1.3</version>
</dependency>
</code>```

My code:

```<code>BytePointer outText;
                TessBaseAPI api = new TessBaseAPI();

                if (api.Init(ResourcesLocation.getTestData(), "spa") != 0) {
                    System.err.println("Could not initialize tesseract.");
                    response.setSuccess(false);
                    response.setCode(CodeList.EXCEPTION);
                }
                else{
                    // Open input image with leptonica library
                    PIX image = pixRead(file);
                    api.SetImage(image);
                    // Get OCR result
                    outText = api.GetUNLVText();

                    data = this.cleanData(outText.getString().split("\\r?\\n"));
                    // Destroy used object and release memory
                    api.End();
                    outText.deallocate();
                    pixDestroy(image);
                }
                api.close();
</code>```

And during runtime I get:

```<code>Estado HTTP 500 â€“ Internal Server Error

Tipo Informe de ExcepciÃ³n

mensaje Handler processing failed; nested exception is java.lang.ExceptionInInitializerError

descripciÃ³n El servidor encontrÃ³ un error interno que hizo que no pudiera rellenar este requerimiento.

excepciÃ³n

org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.ExceptionInInitializerErrororg.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1302)org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:977)org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)javax.servlet.http.HttpServlet.service(HttpServlet.java:661)org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)javax.servlet.http.HttpServlet.service(HttpServlet.java:742)org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)com.invoicebox.security.JWTTokenAuthFilter.doFilterInternal(JWTTokenAuthFilter.java:157)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
causa raÃz

java.lang.ExceptionInInitializerErrorjava.lang.Class.forName0(Native Method)java.lang.Class.forName(Class.java:348)org.bytedeco.javacpp.Loader.load(Loader.java:585)org.bytedeco.javacpp.Loader.load(Loader.java:530)org.bytedeco.javacpp.tesseract$TessBaseAPI.<clinit>(tesseract.java:3648)com.invoicebox.services.InvoiceServiceImpl.importInvoice(InvoiceServiceImpl.java:350)com.invoicebox.services.InvoiceServiceImpl.save(InvoiceServiceImpl.java:1422)sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)java.lang.reflect.Method.invoke(Method.java:498)org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)com.sun.proxy.$Proxy1573.save(Unknown Source)com.invoicebox.controller.InvoiceController.save(InvoiceController.java:138)sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)java.lang.reflect.Method.invoke(Method.java:498)org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)javax.servlet.http.HttpServlet.service(HttpServlet.java:661)org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)javax.servlet.http.HttpServlet.service(HttpServlet.java:742)org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)com.invoicebox.security.JWTTokenAuthFilter.doFilterInternal(JWTTokenAuthFilter.java:157)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
causa raÃz

java.lang.NullPointerExceptionorg.bytedeco.javacpp.Loader.cacheResource(Loader.java:334)org.bytedeco.javacpp.Loader.loadLibrary(Loader.java:772)org.bytedeco.javacpp.Loader.load(Loader.java:604)org.bytedeco.javacpp.Loader.load(Loader.java:530)org.bytedeco.javacpp.lept.<clinit>(lept.java:10)java.lang.Class.forName0(Native Method)java.lang.Class.forName(Class.java:348)org.bytedeco.javacpp.Loader.load(Loader.java:585)org.bytedeco.javacpp.Loader.load(Loader.java:530)org.bytedeco.javacpp.tesseract$TessBaseAPI.<clinit>(tesseract.java:3648)com.invoicebox.services.InvoiceServiceImpl.importInvoice(InvoiceServiceImpl.java:350)com.invoicebox.services.InvoiceServiceImpl.save(InvoiceServiceImpl.java:1422)sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)java.lang.reflect.Method.invoke(Method.java:498)org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)com.sun.proxy.$Proxy1573.save(Unknown Source)com.invoicebox.controller.InvoiceController.save(InvoiceController.java:138)sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)java.lang.reflect.Method.invoke(Method.java:498)org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)javax.servlet.http.HttpServlet.service(HttpServlet.java:661)org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)javax.servlet.http.HttpServlet.service(HttpServlet.java:742)org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)com.invoicebox.security.JWTTokenAuthFilter.doFilterInternal(JWTTokenAuthFilter.java:157)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
nota La traza completa de la causa de este error se encuentra en los archivos de diario del servidor.
</code>```

I installed Tesseract and Leptonica following this example (but I changed the lenguage for spanish)

What I can get from there is that the app is crashing when doing:

```<code>TessBaseAPI api = new TessBaseAPI();
</code>```

答:
the final solution for this, was to run a command from the Java app in order to execute tesseract including the dessire params, and write the result on a text file. After that, the java app read the text file and that's all!

No API, no external libraries, no more problems...

Body:
I'm working on an app using Java Sprint with Maven in Eclipse.

I make tesseract works on my dev machine in Windows (yeah, I know...) but when I tried to deploy the app in the server which is a Centos 7, I get some errors and the app stop working...

pom.sml

<dependency>
    <groupId>org.bytedeco.javacpp-presets</groupId>
    <artifactId>tesseract-platform</artifactId>
    <version>3.04.01-1.3</version>
</dependency>

My code:

BytePointer outText;
                TessBaseAPI api = new TessBaseAPI();

                if (api.Init(ResourcesLocation.getTestData(), "spa") != 0) {
                    System.err.println("Could not initialize tesseract.");
                    response.setSuccess(false);
                    response.setCode(CodeList.EXCEPTION);
                }
                else{
                    // Open input image with leptonica library
                    PIX image = pixRead(file);
                    api.SetImage(image);
                    // Get OCR result
                    outText = api.GetUNLVText();

                    data = this.cleanData(outText.getString().split("\\r?\\n"));
                    // Destroy used object and release memory
                    api.End();
                    outText.deallocate();
                    pixDestroy(image);
                }
                api.close();

And during runtime I get:

Estado HTTP 500 â€“ Internal Server Error

Tipo Informe de ExcepciÃ³n

mensaje Handler processing failed; nested exception is java.lang.ExceptionInInitializerError

descripciÃ³n El servidor encontrÃ³ un error interno que hizo que no pudiera rellenar este requerimiento.

excepciÃ³n

org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.ExceptionInInitializerErrororg.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1302)org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:977)org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)javax.servlet.http.HttpServlet.service(HttpServlet.java:661)org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)javax.servlet.http.HttpServlet.service(HttpServlet.java:742)org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)com.invoicebox.security.JWTTokenAuthFilter.doFilterInternal(JWTTokenAuthFilter.java:157)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
causa raÃz

java.lang.ExceptionInInitializerErrorjava.lang.Class.forName0(Native Method)java.lang.Class.forName(Class.java:348)org.bytedeco.javacpp.Loader.load(Loader.java:585)org.bytedeco.javacpp.Loader.load(Loader.java:530)org.bytedeco.javacpp.tesseract$TessBaseAPI.<clinit>(tesseract.java:3648)com.invoicebox.services.InvoiceServiceImpl.importInvoice(InvoiceServiceImpl.java:350)com.invoicebox.services.InvoiceServiceImpl.save(InvoiceServiceImpl.java:1422)sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)java.lang.reflect.Method.invoke(Method.java:498)org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)com.sun.proxy.$Proxy1573.save(Unknown Source)com.invoicebox.controller.InvoiceController.save(InvoiceController.java:138)sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)java.lang.reflect.Method.invoke(Method.java:498)org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)javax.servlet.http.HttpServlet.service(HttpServlet.java:661)org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)javax.servlet.http.HttpServlet.service(HttpServlet.java:742)org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)com.invoicebox.security.JWTTokenAuthFilter.doFilterInternal(JWTTokenAuthFilter.java:157)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
causa raÃz

java.lang.NullPointerExceptionorg.bytedeco.javacpp.Loader.cacheResource(Loader.java:334)org.bytedeco.javacpp.Loader.loadLibrary(Loader.java:772)org.bytedeco.javacpp.Loader.load(Loader.java:604)org.bytedeco.javacpp.Loader.load(Loader.java:530)org.bytedeco.javacpp.lept.<clinit>(lept.java:10)java.lang.Class.forName0(Native Method)java.lang.Class.forName(Class.java:348)org.bytedeco.javacpp.Loader.load(Loader.java:585)org.bytedeco.javacpp.Loader.load(Loader.java:530)org.bytedeco.javacpp.tesseract$TessBaseAPI.<clinit>(tesseract.java:3648)com.invoicebox.services.InvoiceServiceImpl.importInvoice(InvoiceServiceImpl.java:350)com.invoicebox.services.InvoiceServiceImpl.save(InvoiceServiceImpl.java:1422)sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)java.lang.reflect.Method.invoke(Method.java:498)org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)com.sun.proxy.$Proxy1573.save(Unknown Source)com.invoicebox.controller.InvoiceController.save(InvoiceController.java:138)sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)java.lang.reflect.Method.invoke(Method.java:498)org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)javax.servlet.http.HttpServlet.service(HttpServlet.java:661)org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)javax.servlet.http.HttpServlet.service(HttpServlet.java:742)org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)com.invoicebox.security.JWTTokenAuthFilter.doFilterInternal(JWTTokenAuthFilter.java:157)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
nota La traza completa de la causa de este error se encuentra en los archivos de diario del servidor.

I installed Tesseract and Leptonica following this example (but I changed the lenguage for spanish)

What I can get from there is that the app is crashing when doing:

TessBaseAPI api = new TessBaseAPI();


问:
Finding a key in an object that’s true AND matches en entry in an array
I have an array like this:

```<code>baseBreakpoints: [
    'xLarge',
    'large',
    'largeMedium',
    'medium',
    'smallMedium',
    'small',
    'xSmall'
]
</code>```

… and I have an object like this:

```<code>breakpoints = {
    "gtMedium": true,
    "xLarge": true,
    "gtLargeMedium": true,
    "giant": false,
    "small": false,
    "ltLargeMedium": false,
    "gtLarge": true,
    "xSmall": false,
    "largeMedium": false,
    "medium": false,
    "gtSmall": true,
    "large": false,
    "smallMedium": false
}
</code>```

I need to find the key in the object that’s true and exists in the array. For example, in this example above the value would be xLarge since xLarge === true in the object and exists in the breakpoints array.

Any suggestions? Lodash is already a dependency in the project, if that helps.

答:
Fairly simple lookup

var baseBreakpoints = [
    'xLarge',
    'large',
    'largeMedium',
    'medium',
    'smallMedium',
    'small',
    'xSmall'
];

var breakpoints = {
    "gtMedium": true,
    "xLarge": true,
    "gtLargeMedium": true,
    "giant": false,
    "small": false,
    "ltLargeMedium": false,
    "gtLarge": true,
    "xSmall": false,
    "largeMedium": false,
    "medium": false,
    "gtSmall": true,
    "large": false,
    "smallMedium": false
}
var res = [];
for (bp of baseBreakpoints) {
  if (breakpoints[bp] != undefined && breakpoints[bp]) res.push(bp)
}
console.log(res)```

Body:
I have an array like this:

baseBreakpoints: [
    'xLarge',
    'large',
    'largeMedium',
    'medium',
    'smallMedium',
    'small',
    'xSmall'
]

… and I have an object like this:

breakpoints = {
    "gtMedium": true,
    "xLarge": true,
    "gtLargeMedium": true,
    "giant": false,
    "small": false,
    "ltLargeMedium": false,
    "gtLarge": true,
    "xSmall": false,
    "largeMedium": false,
    "medium": false,
    "gtSmall": true,
    "large": false,
    "smallMedium": false
}

I need to find the key in the object that’s true and exists in the array. For example, in this example above the value would be xLarge since xLarge === true in the object and exists in the breakpoints array.

Any suggestions? Lodash is already a dependency in the project, if that helps.


问:
Textview size needs to change according to user's given value in EditText
Dynamically change the TextView size based on user input. If user changes the value, textview needs to change

```<code>     et0=(EditText)findViewById(R.id.EditText0);
     bt = (Button)findViewById(R.id.btn);

     bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String text = ((et.getText().toString()));
                    float i=et0.getTextSize();

                    tv.setText(text);
                    tv.setTextSize(i) ;
        }
    }

//problem is value is changing one time if edit again text size is not changing
any help advance thanks
</code>```

答:
To change the textView text size equal to the editText input value, use this:

```<code> bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String text = ((et.getText().toString()));  //number input

                    Float f= Float.parseFloat(text);  // setting the input number as textview text size
                    tv.setText(text);
                    tv.setTextSize(f) ;
        }
    }
</code>```

Note: editText input value must be a number

Body:
Dynamically change the TextView size based on user input. If user changes the value, textview needs to change

     et0=(EditText)findViewById(R.id.EditText0);
     bt = (Button)findViewById(R.id.btn);

     bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String text = ((et.getText().toString()));
                    float i=et0.getTextSize();

                    tv.setText(text);
                    tv.setTextSize(i) ;
        }
    }

//problem is value is changing one time if edit again text size is not changing
any help advance thanks

Body:
To change the textView text size equal to the editText input value, use this:

 bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String text = ((et.getText().toString()));  //number input

                    Float f= Float.parseFloat(text);  // setting the input number as textview text size
                    tv.setText(text);
                    tv.setTextSize(f) ;
        }
    }

Note: editText input value must be a number


问:
Remove All Styles and Indent from Ordered List
How do I remove the indent and style of an ordered list, so that it behaves like regular text?

Example:

```<code>   1. Item
   1. Item
   [...]
1000. Item
</code>```

Should look like this:

```<code>1. Item
2. Item
[...]
1000. Item 100
</code>```

Code:

```<code><ol>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ol>
</code>```

Thanks!

答:
You would unset the vendor/user-agent padding and margin property values on the containing list element (ol or ul), essentially normalizing the element styles.

You would still need to account for the space required to see the list-item display type, you can do this by declaring a margin property on the nested list-items and adjusting the value to suit requirements.

```<code>ol {
    margin: 0;
    padding: 0;
}

li {
    margin-left: 10px; /* Adjust accordingly */
}
</code>```

ol.normalized {
    margin: 0;
    padding: 0;
}

ol.normalized li {
    margin-left: 10px; /* Adjust accordingly */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h4>Normalized</h4>

<ol class="normalized">
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ol>

<h4>Initial</h4>

<ol>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ol></code>```

Body:
How do I remove the indent and style of an ordered list, so that it behaves like regular text?

Example:

   1. Item
   1. Item
   [...]
1000. Item

Should look like this:

1. Item
2. Item
[...]
1000. Item 100

Code:

Item

Item

Item

Thanks!

Body:
You would unset the vendor/user-agent padding and margin property values on the containing list element (ol or ul), essentially normalizing the element styles.

You would still need to account for the space required to see the list-item display type, you can do this by declaring a margin property on the nested list-items and adjusting the value to suit requirements.

ol {
    margin: 0;
    padding: 0;
}

li {
    margin-left: 10px; /* Adjust accordingly */
}

ol.normalized {
    margin: 0;
    padding: 0;
}

ol.normalized li {
    margin-left: 10px; /* Adjust accordingly */
}

<h4>Normalized</h4>

<ol class="normalized">
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ol>

<h4>Initial</h4>

<ol>
  <li>Item</li>
  <li>Item</li>
  <li>Item</li>
</ol>


问:
Windows API functions
Are they standard code c or c++ code? what are they?</p>

答:
Windows API is langugage neutral. It is neither C nor C++. Microsoft says that Windows itself is written mainly in C++, but you don't need any classes for vast majority of the API and even classes in API (e.g. in Direct X) can be used in pure C without classes.

Although some C programmers think it is a C library, compiler of a programming language must support proprietary Windows calling model, it is not a classic C calling convention. (Obviously almost each real world C compiler supports it nowadays.)

Title: Windows API functions


问:
apostrophe in word not being recognized for string replace
I am having a problem replacing the word "you're" with regexp.

All of the other words are changing correctly just the word "you're".
I think it is not parsing after the apostrophe.

I have to replace the word "you" to "I" and "you're" to "I'm".
It will change "you" to "I" but "you're" becomes "I're" because it is not going past the apostrophe and it thinks that is the end of the word for some reason. I have to escape the apostrophe somehow.

Please see below for the code in question.

```<code>package main

import (
    "fmt"
    "math/rand"
    "regexp"
    "strings"
    "time"
)

//Function ElizaResponse to take in and return a string
func ElizaResponse(str string) string {

    //  replace := "How do you know you are"

    /*Regex MatchString function with isolation of the word "father"
    *with a boundry ignore case regex command.
     */
    if matched, _ := regexp.MatchString(`(?i)\bfather\b`, str);
    //Condition to replace the original string if it has the word "father"
    matched {
        return "Why don’t you tell me more about your father?"
    }
    r1 := regexp.MustCompile(`(?i)\bI'?\s*a?m\b`)

    //Match the words "I am" and capture for replacement
    matched := r1.MatchString(str)

    //condition if "I am" is matched
    if matched {

        capturedString := r1.ReplaceAllString(str, "$1")
        boundaries := regexp.MustCompile(`\b`)
        tokens := boundaries.Split(capturedString, -1)

        // List the reflections.
        reflections := [][]string{
            {`I`, `you`},
            {`you're`, `I'm`},
            {`your`, `my`},
            {`me`, `you`},
            {`you`, `I`},
            {`my`, `your`},
        }

        // Loop through each token, reflecting it if there's a match.
        for i, token := range tokens {
            for _, reflection := range reflections {
                if matched, _ := regexp.MatchString(reflection[0], token); matched {
                    tokens[i] = reflection[1]
                    break
                }
            }
        }

        // Put the tokens back together.
        return strings.Join(tokens, ``)

    }

    //Get random number from the length of the array of random struct
    //an array of strings for the random response
    response := []string{"I’m not sure what you’re trying to say. Could you explain it to me?",
        "How does that make you feel?",
        "Why do you say that?"}
    //Return a random index of the array
    return response[rand.Intn(len(response))]

}

func main() {
    rand.Seed(time.Now().UTC().UnixNano())

    fmt.Println("Im supposed to just take what you're saying at face value?")
    fmt.Println(ElizaResponse("Im supposed to just take what you're saying at face value?"))

}
</code>```

答:
Note that the apostrophe character creates a word boundary, so your use of \b in regular expressions is probably tripping you up.  That is, the string "I'm" has four word boundaries, one before and after each character.

┏━┳━┳━┓
┃I┃'┃m┃
┗━┻━┻━┛
│ │ │ └─ end of line creates a word boundary
│ │ └─── after punctuation character creates a word boundary
│ └───── before punctuation character creates a word boundary
└─────── start of line creates a word boundary
```

<p>There is no way to change the behavior of the word boundary metacharacter so you might be better off mapping regexes that include the full word with punctuation to the desired replacement, e.g.:</p>

```type Replacement struct {
  rgx *regexp.Regexp
  rpl string
}

replacements := []Replacement{
  {regexp.MustCompile("\\bI\\b"), "you"},
  {regexp.MustCompile("\\byou're\\b"), "I'm"},
  // etc...
}
```

<p>Note also that one of your examples contains a UTF-8 "right single quotation mark" (U+2019, 0xe28099), not to be confused with the UTF-8/ASCII apostrophe (U+0027, 0x27)!</p>

```fmt.Sprintf("% x", []byte("'’")) // => "27 e2 80 99"
```

ContentLicense: CC BY-SA 4.0

Body:
I am having a problem replacing the word "you're" with regexp.

All of the other words are changing correctly just the word "you're".
I think it is not parsing after the apostrophe.

I have to replace the word "you" to "I" and "you're" to "I'm".
It will change "you" to "I" but "you're" becomes "I're" because it is not going past the apostrophe and it thinks that is the end of the word for some reason. I have to escape the apostrophe somehow.

Please see below for the code in question.

package main

import (
    "fmt"
    "math/rand"
    "regexp"
    "strings"
    "time"
)

//Function ElizaResponse to take in and return a string
func ElizaResponse(str string) string {

    //  replace := "How do you know you are"

    /*Regex MatchString function with isolation of the word "father"
    *with a boundry ignore case regex command.
     */
    if matched, _ := regexp.MatchString(`(?i)\bfather\b`, str);
    //Condition to replace the original string if it has the word "father"
    matched {
        return "Why don’t you tell me more about your father?"
    }
    r1 := regexp.MustCompile(`(?i)\bI'?\s*a?m\b`)

    //Match the words "I am" and capture for replacement
    matched := r1.MatchString(str)

    //condition if "I am" is matched
    if matched {

        capturedString := r1.ReplaceAllString(str, "$1")
        boundaries := regexp.MustCompile(`\b`)
        tokens := boundaries.Split(capturedString, -1)

        // List the reflections.
        reflections := [][]string{
            {`I`, `you`},
            {`you're`, `I'm`},
            {`your`, `my`},
            {`me`, `you`},
            {`you`, `I`},
            {`my`, `your`},
        }

        // Loop through each token, reflecting it if there's a match.
        for i, token := range tokens {
            for _, reflection := range reflections {
                if matched, _ := regexp.MatchString(reflection[0], token); matched {
                    tokens[i] = reflection[1]
                    break
                }
            }
        }

        // Put the tokens back together.
        return strings.Join(tokens, ``)

    }

    //Get random number from the length of the array of random struct
    //an array of strings for the random response
    response := []string{"I’m not sure what you’re trying to say. Could you explain it to me?",
        "How does that make you feel?",
        "Why do you say that?"}
    //Return a random index of the array
    return response[rand.Intn(len(response))]

}

func main() {
    rand.Seed(time.Now().UTC().UnixNano())

    fmt.Println("Im supposed to just take what you're saying at face value?")
    fmt.Println(ElizaResponse("Im supposed to just take what you're saying at face value?"))

}

Body:
Note that the apostrophe character creates a word boundary, so your use of \b in regular expressions is probably tripping you up.  That is, the string "I'm" has four word boundaries, one before and after each character.

┏━┳━┳━┓
┃I┃'┃m┃
┗━┻━┻━┛
│ │ │ └─ end of line creates a word boundary
│ │ └─── after punctuation character creates a word boundary
│ └───── before punctuation character creates a word boundary
└─────── start of line creates a word boundary

There is no way to change the behavior of the word boundary metacharacter so you might be better off mapping regexes that include the full word with punctuation to the desired replacement, e.g.:

type Replacement struct {
  rgx *regexp.Regexp
  rpl string
}

replacements := []Replacement{
  {regexp.MustCompile("\\bI\\b"), "you"},
  {regexp.MustCompile("\\byou're\\b"), "I'm"},
  // etc...
}

Note also that one of your examples contains a UTF-8 "right single quotation mark" (U+2019, 0xe28099), not to be confused with the UTF-8/ASCII apostrophe (U+0027, 0x27)!

fmt.Sprintf("% x", []byte("'’")) // => "27 e2 80 99"


问:
Top only corner radius for UIImage in UIStackView
I'm facing a very strange problem right now where the same code produces different results on a UIView and a UIImageView.

I have a custom UITableViewCell. To add a shadow and also got some separation between the cells. I've used a container view that contains the shadow and the rounded corners. Everything works as expected.

One layer below I use a UIStackView so I can easily remove the image of the cell if the post has no image at all. This stack view contains one image and another stack view. The corner radius on top of the outer container view doesn't work because the image has no rounded corners. So I've tried to implement this for the image and also for a view above that image that is used as an overlay.

The overlay is outside of the stack view. Now, I've written some code to also add the corner radius to these both views and it works perfectly on the overlay but not on the UIImageView. Even when I pull out the image out of the stack views.

Here is what it looks like:

I've used a slightly bigger corner radius to visualize it and added a border to the image.

What I expect to happen: The image has exactly the same width and corner radius on the correct sides like the overlay (grey).

Here is the code for the custom UIImageView class:

```<code>import UIKit

@IBDesignable
class RoundedImageView: UIImageView {

    @IBInspectable var cornerRadius: CGFloat = 0.0 { didSet { setUpView() } }
    @IBInspectable var isOnlyTop: Bool = false { didSet { setUpView() } }

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func draw(_ rect: CGRect) {
        setUpView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setUpView()
    }

    func setUpView() {
        self.clipsToBounds = true
        self.layer.borderColor = UIColor.green.cgColor
        self.layer.borderWidth = 2.0

        if isOnlyTop {
            setTopCornerRadius()
        } else {
            self.layer.cornerRadius = cornerRadius
        }
    }

    func setTopCornerRadius() {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners:[.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = path.cgPath
        self.layer.mask = maskLayer
        self.layer.masksToBounds = true
    }
}
</code>```

I've copied the code from the rounded view. However, for completion I will add it below:

```<code>import UIKit

@IBDesignable
class RoundedView: UIView {

    @IBInspectable var cornerRadius: CGFloat = 0.0 { didSet { setUpView() } }
    @IBInspectable var isOnlyTop: Bool = false { didSet { setUpView() } }

    override func awakeFromNib() {
        super.awakeFromNib()
        setUpView()
    }

    override func draw(_ rect: CGRect) {
        setUpView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setUpView()
    }

    func setUpView() {
        self.clipsToBounds = true
        self.layer.borderColor = UIColor.red.cgColor
        //self.layer.borderWidth = 2.0

        if isOnlyTop {
            setTopCornerRadius()
        } else {
            self.layer.cornerRadius = cornerRadius
        }
    }

    private func setTopCornerRadius() {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners:[.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = path.cgPath
        self.layer.mask = maskLayer
    }
}
</code>```

Here is the whole view tree of the cell:

I know, that I am violating the DRY principle here, but I just have written the same code for UIView and UIImageView so I can verify why it doesn't work.

Hint: Notice that I have two times the same UIImage in this cell (Post Image and Image out of stack view) as I thought it is maybe caused by Constraints or the stack view. So the image outside of the stack view has exactly the same constraints as the Overlay View.

So long story short: Do you know why my UIImageView has the wrong size and also doesn't apply the corner radius that works perfectly on the Overlay View (UIView). Thanks in advance!

EDIT: The expected result should look like this. Unless the top corners of the image should also be rounded (you see that little difference at the top corners of the image? That's caused by the overlay. It has the correct corner radius but the image doesn't).

EDIT 2: I was asked to add the code of the view controller. However, I don't change anything here.

```<code>import UIKit

protocol PostListDisplayLogic: class {
}

class PostListViewController: UIViewController, PostListDisplayLogic, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    var interactor: PostListBusinessLogic?
    var router: (NSObjectProtocol & PostListRoutingLogic & PostListDataPassing)?

    // MARK: Object lifecycle

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    // MARK: Setup

    private func setup() {
       let viewController = self
       let interactor = PostListInteractor()
       let presenter = PostListPresenter()
       let router = PostListRouter()
       viewController.interactor = interactor
       viewController.router = router
       interactor.presenter = presenter
       presenter.viewController = viewController
       router.viewController = viewController
       router.dataStore = interactor
   }

   // MARK: Routing

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let scene = segue.identifier {
            let selector = NSSelectorFromString("routeTo\(scene)WithSegue:")
            if let router = router, router.responds(to: selector) {
                router.perform(selector, with: segue)
            }
        }
   }

   // MARK: View lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.delegate = self
        self.tableView.dataSource = self
        tableView.register(UINib(nibName: "PostCell", bundle: nil), forCellReuseIdentifier: "PostCell")
    }

    // MARK: TableView DataSource & Delegate
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell {
            return cell
            }

        return UITableViewCell()
    }
}
</code>```

答:
Try call super in 'draw' function:</p>

```<code> override func draw(_ rect: CGRect) {
      super.draw(rect)
      setUpView()
 }
</code>```

Body:
I'm facing a very strange problem right now where the same code produces different results on a UIView and a UIImageView.

I have a custom UITableViewCell. To add a shadow and also got some separation between the cells. I've used a container view that contains the shadow and the rounded corners. Everything works as expected.

One layer below I use a UIStackView so I can easily remove the image of the cell if the post has no image at all. This stack view contains one image and another stack view. The corner radius on top of the outer container view doesn't work because the image has no rounded corners. So I've tried to implement this for the image and also for a view above that image that is used as an overlay.

The overlay is outside of the stack view. Now, I've written some code to also add the corner radius to these both views and it works perfectly on the overlay but not on the UIImageView. Even when I pull out the image out of the stack views.

Here is what it looks like:

I've used a slightly bigger corner radius to visualize it and added a border to the image.

What I expect to happen: The image has exactly the same width and corner radius on the correct sides like the overlay (grey).

Here is the code for the custom UIImageView class:

import UIKit

@IBDesignable
class RoundedImageView: UIImageView {

    @IBInspectable var cornerRadius: CGFloat = 0.0 { didSet { setUpView() } }
    @IBInspectable var isOnlyTop: Bool = false { didSet { setUpView() } }

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func draw(_ rect: CGRect) {
        setUpView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setUpView()
    }

    func setUpView() {
        self.clipsToBounds = true
        self.layer.borderColor = UIColor.green.cgColor
        self.layer.borderWidth = 2.0

        if isOnlyTop {
            setTopCornerRadius()
        } else {
            self.layer.cornerRadius = cornerRadius
        }
    }

    func setTopCornerRadius() {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners:[.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = path.cgPath
        self.layer.mask = maskLayer
        self.layer.masksToBounds = true
    }
}

I've copied the code from the rounded view. However, for completion I will add it below:

import UIKit

@IBDesignable
class RoundedView: UIView {

    @IBInspectable var cornerRadius: CGFloat = 0.0 { didSet { setUpView() } }
    @IBInspectable var isOnlyTop: Bool = false { didSet { setUpView() } }

    override func awakeFromNib() {
        super.awakeFromNib()
        setUpView()
    }

    override func draw(_ rect: CGRect) {
        setUpView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setUpView()
    }

    func setUpView() {
        self.clipsToBounds = true
        self.layer.borderColor = UIColor.red.cgColor
        //self.layer.borderWidth = 2.0

        if isOnlyTop {
            setTopCornerRadius()
        } else {
            self.layer.cornerRadius = cornerRadius
        }
    }

    private func setTopCornerRadius() {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners:[.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = path.cgPath
        self.layer.mask = maskLayer
    }
}

Here is the whole view tree of the cell:

I know, that I am violating the DRY principle here, but I just have written the same code for UIView and UIImageView so I can verify why it doesn't work.

Hint: Notice that I have two times the same UIImage in this cell (Post Image and Image out of stack view) as I thought it is maybe caused by Constraints or the stack view. So the image outside of the stack view has exactly the same constraints as the Overlay View.

So long story short: Do you know why my UIImageView has the wrong size and also doesn't apply the corner radius that works perfectly on the Overlay View (UIView). Thanks in advance!

EDIT: The expected result should look like this. Unless the top corners of the image should also be rounded (you see that little difference at the top corners of the image? That's caused by the overlay. It has the correct corner radius but the image doesn't).

EDIT 2: I was asked to add the code of the view controller. However, I don't change anything here.

import UIKit

protocol PostListDisplayLogic: class {
}

class PostListViewController: UIViewController, PostListDisplayLogic, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    var interactor: PostListBusinessLogic?
    var router: (NSObjectProtocol & PostListRoutingLogic & PostListDataPassing)?

    // MARK: Object lifecycle

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    // MARK: Setup

    private func setup() {
       let viewController = self
       let interactor = PostListInteractor()
       let presenter = PostListPresenter()
       let router = PostListRouter()
       viewController.interactor = interactor
       viewController.router = router
       interactor.presenter = presenter
       presenter.viewController = viewController
       router.viewController = viewController
       router.dataStore = interactor
   }

   // MARK: Routing

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let scene = segue.identifier {
            let selector = NSSelectorFromString("routeTo\(scene)WithSegue:")
            if let router = router, router.responds(to: selector) {
                router.perform(selector, with: segue)
            }
        }
   }

   // MARK: View lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.delegate = self
        self.tableView.dataSource = self
        tableView.register(UINib(nibName: "PostCell", bundle: nil), forCellReuseIdentifier: "PostCell")
    }

    // MARK: TableView DataSource & Delegate
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell {
            return cell
            }

        return UITableViewCell()
    }
}

Body:
Try call super in 'draw' function:

 override func draw(_ rect: CGRect) {
      super.draw(rect)
      setUpView()
 }