text:
Q: Map more than 1 property of custom List object in java 8 I have below custom List object List<Person> personList
class Person(){
    String name;
    String age;
    String countryName;
    String stateName;
// getter and setter for all property
}

if i want to map personList based on countryName or StateName then i will do :
List<String> countryName = personList.stream().map(Person :: getCountryName)

or
List<String> stateName = personList.stream().map(Person :: getStateName)

But now i want to mapping personList based on CountryName and StateName in new custom List Object List<Country> countryandStateList
class Country(){
    String countryName;
    String stateName;
// getter and setter for CountryName and StateName
}

How would i do this?

A: First of all, you are using the wrong term. You are not filtering stream elements, you are mapping stream elements to elements of a different type.
Just map to Country instances:
List<Country> countries =
    personList.stream()
              .map(p->new Country(p.getCountry(),p.getState()))
              .collect(Collectors.toList());

This is assuming the relevant constructor exists. If that's no the case, you can also use a parameter-less constructor and then call the setters on the created instance.

A: First filter as you did then create an object inside your map:
List<Country> countryList = personList.stream().map(new Country(person.getCountryName(), person.getStateName()).collect(Collectors.toList());

A: You can use the following :
List<Country> countries = personList.stream()
            .map(person -> new Country(person.getCountryName(),
                    person.getStateName()))
            .collect(Collectors.toList());

or
List<Country> countries = personList.stream()
            .collect(Collectors.mapping(person -> new
                             Country(person.getCountryName(),
                    person.getStateName()), Collectors.toList()));


text:
Q: (Fe)Male Human vs Human (Fe)Male Why is it (fe)male human and not human (fe)male? Is it even correct to use second form?
I sometimes use the second form and was corrected yesterday but could not find anything about this topic.

A: You can say 'human male' or human female'. Who corrected you?
Womanhood is the period in a human female's life after she has passed through childhood, puberty, and adolescence. (Wikipedia)
When a human female is born, it is almost invariably known that the baby is female, by inspection. (Philosophy paper)
THYMIDINE UPTAKE BY A RING X CHROMOSOME IN A HUMAN FEMALE. (Medical research paper)
a human female employed to do housework - crossword clue.

A: Whoever told you this is incorrect, although the confusion is understandable.
The confusion arises because 'male' and 'female' can be used as adjectives or nouns. But 'human' can also be either an adjective or a noun. As I'm sure you know, an adjective goes before the noun it describes. So, the determining factor is which word you ultimately want to use to define your subject. Do you want to say that they are human that happens to be male or a male that happens to be human?
You tend to see sex used as an adjective when speaking about animals, for example, 'a female dog', 'a male baboon' etc. This is mainly because 'dog', 'cat', 'monkey' etc can only be nouns. The equivalent words to 'human' that describe those species would be canine, feline, and simian respectively, and these can be either adjectives or nouns. Of course, you could say 'my dog is a female', but in this example both are nouns, and you would be subcategorising your dog as both a dog and a female.
I would suggest that you hear 'human (fe)male' more than the other way around because we very rarely define ourselves as 'a human', probably because it goes without saying. Of course we are humans - what else could we be? We tend to use it as an adjective to emphasise our limitations (ie 'I'm only human'). The nouns we use to refer to ourselves are usually 'man' and 'woman', and there would be no need to say either 'I'm a male man', or even 'a human man'.

A: The form of phrase you have there is modifier-category. It is a question of which word is the modifier and which word is the category.
In your example, to some extent this is an option, and to some extent it is ambiguous. This is beause each of the words human and female can be either modifier or category. If one word were clearly a category and the other a modifier, it would be much more clear. For example, consider brown dog. It would be unusual to refer to a dog brown when you meant a dog that was brown. But in this case each word can be used as either a category or a modifier.
If the context tended to show one word or the other as a category,  you might put that one last. For example, if you were discussing sexual dimorphism in several different species, then the species might be the modifier and the sex the category. You might have human female, feline female, cetacean female, etc. "The feline female is nearly always secretive about giving birth. The cetacean female gives birth in open water and so is unable to be secretive."
However, it would be acceptable to change this order, particularly if you wanted to switch over to comparing male to female in one species. "The female feline is on average smaller than the male feline. This is in contrast to the female canadensis and male canadensis which are typically quite similar in size and appearance."
(Branta canadensis is the Canadian goose.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scatter Plot Y-axis Number Ranging Problem in Matplotlib I wrote a few lines of code that creates a simple scatter plot. I want the numbers on the y-axis to range from 0 to 1000000. I know it's a big number and sometimes I might experience strange numerical problems but when I run this code the y-axis is ranging from 0 to 1. That's quite strange. I have to manually drag the graph if I want the graph to range in the numbers that I wish using the tools in the python window that pops up when I run the code. Otherwise, the numbers on the y-axis just simply doesn't range in the way I designated. ps: The numbers on the x-axis ranges perfectly fine though.
import matplotlib.pyplot as plt

x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]

plt.scatter(x_values, y_values, s=10)
plt.title('Square Numbers', fontsize=18)
plt.xlabel('Value', fontsize=18)
plt.ylabel('Square of Value', fontsize=12)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.axis([0, 1000, 0, 1100000])
plt.show()

A: The matplotlib will take the values of the any axis as a logarithmic value after reaching 1 million or above that. if u wish to see the values in numerical values:
(i) Slightly pan towards the -y axis. You will be able to see the number.
or
(ii) Set plt.axis([0, 1000, 0, 1100000]) to plt.axis([0, 1000, 0, 110000])
I hope it will work for you.


text:
Q: Open filename with embedded spaces with Roo Ruby 2.0.0, Rails 4.0.3, Windows 8.1 Update, Roo 1.13.2
I am trying to open an Excel spreadsheet with embedded spaces using Roo.  So far, I am unable to do that.  I don't really know if this problem is restricted to Roo.  If I rename it to eliminate the spaces, I have no problem with it.  I tried encoding it, but then it simply said the file doesn't exist.  Can I open the file while it contains spaces?
Code sample:
  exceptions = [URI::InvalidURIError, IOError]
  puts "f is #{f}"
  puts "f exist? #{File.exist?(f)}"
  begin
    xls = Roo::Spreadsheet.open(f)
  rescue *exceptions => e
    puts e.message
  end

  encoded_f = URI.encode(f).to_s
  puts "encoded_f is #{encoded_f}"
  puts "encoded_f exist? #{File.exist?(encoded_f)}"
  begin
    xls = Roo::Spreadsheet.open(encoded_f)
  rescue *exceptions => e
    puts e.message
  end

  gsub_f = f.gsub(" ", "") # Rename file without spaces
  File.rename(f, gsub_f)
  puts "gsub_f is #{gsub_f}"
  puts "gsub_f exist? #{File.exist?(gsub_f)}"
  begin
    xls = Roo::Spreadsheet.open(gsub_f)
  rescue *exceptions => e
    puts e.message
  end

Output sample:
f is Whitt Report 2014-07-28-0803.xls
f exist? true
bad URI(is not URI?): Whitt Report 2014-07-28-0803.xls

encoded_f is Whitt%20Report%202014-07-28-0803.xls
encoded_f exist? false
file Whitt%20Report%202014-07-28-0803.xls does not exist

gsub_f is WhittReport2014-07-28-0803.xls
gsub_f exist? true

No message is given in the end because the file opens successfully.

A: This is caused by the way in which the URI module is called in the Roo::Spreadsheet#open method.
I posted a fix to this problem which has now been merged. If you update your Roo gem you should no longer have this issue.


text:
Q: Passing a range of columns as a constant parameter I am trying to pass a range of columns as a parameter for a function.
For sr = 1 To srCount
    If IsEmpty(Data(sr, 4)) Then

        dr = dr + 1
        Data(dr, 4) = Data(sr, 1) 'instead of just the first column, a range of columns

    End If
Next sr

I thought I could define a range ("A:C") and pass its reference as a parameter, but VBA doesn't seem to accept anything but (references to) long variables/constants as parameters for the Data() function. What is the correct syntax for such a thing?
Edited 01/26 for clarification: Data is an array. The goal is to copy a row of a range of columns based on the condition that another cell in that row is empty (If IsEmpty(Data(sr, 4))). E.g. if cell(7,4) is empty, then row 7 of columns A-C should be copied to another area of the worksheet (K2:M2). If (13,4) is empty, then row 13, columns A-C to K3-M3, and so on.
As per @Cameron's tip I used Collections to store the ranges instead.
Dim users As New Collection
Dim cell As Range

With Worksheets(2)
    users.Add .Range("A:C"), "Users"
    users.Add .Range("K:M"), "FinalList"

End With

For Each cell In users.Item("Users")
   For sr = 1 to srCount
    If IsEmpty(Data(sr, 4)) Then

        dr = dr + 1
        FinalList = Users

    End If
Next sr

Next

Despite the research I can't find how I can manipulate Collections for this objective. Once I have all the necessary values stored in FinalList, how can I copy them to the goal Range ("K:M")?

A: Using a Single Array to Extract Matching Data
Option Explicit

Sub Test()

    Const SRC_CRITERIA_COLUMN As Long = 4
    Const DST_WORKSHEET_ID As Variant = 2 ' using the tab name is preferable!
    Const DST_FIRST_CELL As String = "K2"
    ' The following could be calculated from the source variables.
    Const DST_COLUMNS_COUNT As Long = 3

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    ' whatever...

    Dim Data() ' ?
    Dim srCount As Long ' ?

    ' whatever...

    Dim sr As Long, dr As Long, c As Long

    ' Write the matching values to the top of the array
    ' When using a single array, the result needs to be in the top-left
    ' of the array. The data of interest is already left-most
    ' so there is no column offset.
    For sr = 1 To srCount
        If IsEmpty(Data(sr, SRC_CRITERIA_COLUMN)) Then
            dr = dr + 1
            For c = 1 To DST_COLUMNS_COUNT
                Data(dr, c) = Data(sr, c)
            Next c
        End If
    Next sr

    ' Reference the destination range.
    Dim dws As Worksheet: Set dws = wb.Worksheets(DST_WORKSHEET_ID)
    Dim dfCell As Range: Set dfCell = dws.Range(DST_FIRST_CELL)
    ' Note how you're using just the 'dr' number of rows
    ' and 'DST_COLUMNS_COUNT' number of columns.
    Dim drg As Range: Set drg = dfCell.Resize(dr, DST_COLUMNS_COUNT)

    ' Write the result from the top-left of the array to the destination range.
    drg.Value = Data
    ' Clear below.
    drg.Resize(dws.Rows.Count - drg.Row - dr + 1).Offset(dr).ClearContents

    MsgBox "Data copied.", vbInformation

End Sub


text:
Q: modifying values in pointers is very slow? I'm working with a huge amount of data stored in an array, and am trying to optimize the amount of time it takes to access and modify it. I'm using Window, c++ and VS2015 (Release mode).
I ran some tests and don't really understand the results I'm getting, so I would love some help optimizing my code.
First, let's say I have the following class:
class foo
{
public:
    int x;

    foo()
    {
        x = 0;
    }

    void inc()
    {
        x++;
    }

    int X()
    {
        return x;
    }

    void addX(int &_x)
    {
        _x++;
    }

};

I start by initializing 10 million pointers to instances of that class into a std::vector of the same size.
#include <vector>
int count = 10000000;
std::vector<foo*> fooArr;
fooArr.resize(count);
for (int i = 0; i < count; i++)
{
     fooArr[i] = new foo();
}

When I run the following code, and profile the amount of time it takes to complete, it takes approximately 350ms (which, for my purposes, is far too slow):
for (int i = 0; i < count; i++)
{
    fooArr[i]->inc(); //increment all elements
}

To test how long it takes to increment an integer that many times, I tried:
int x = 0;
for (int i = 0; i < count; i++)
{
    x++;
}

Which returns in <1ms.
I thought maybe the number of integers being changed was the problem, but the following code still takes 250ms, so I don't think it's that:
for (int i = 0; i < count; i++)
{
    fooArr[0]->inc(); //only increment first element
}

I thought maybe the array index access itself was the bottleneck, but the following code takes <1ms to complete:
int x;
for (int i = 0; i < count; i++)
{
    x = fooArr[i]->X(); //set x
}

I thought maybe the compiler was doing some hidden optimizations on the loop itself for the last example (since the value of x will be the same during each iteration of the loop, so maybe the compiler skips unnecessary iterations?). So I tried the following, and it takes 350ms to complete:
int x;
for (int i = 0; i < count; i++)
{
    fooArr[i]->addX(x); //increment x inside foo function
}

So that one was slow again, but maybe only because I'm incrementing an integer with a pointer again.
I tried the following too, and it returns in 350ms as well:
for (int i = 0; i < count; i++)
{
    fooArr[i]->x++;
}

So am I stuck here? Is ~350ms the absolute fastest that I can increment an integer, inside of 10million pointers in a vector? Or am I missing some obvious thing? I experimented with multithreading (giving each thread a different chunk of the array to increment) and that actually took longer once I started using enough threads. Maybe that was due to some other obvious thing I'm missing, so for now I'd like to stay away from multithreading to keep things simple.
I'm open to trying containers other than a vector too, if it speeds things up, but whatever container I end up using, I need to be able to easily resize it, remove elements, etc.
I'm fairly new to c++ so any help would be appreciated!

A: Let's look from the CPU point of view.
Incrementing an integer means I have it in a CPU register and just increments it. This is the fastest option.
I'm given an address (vector->member) and I must copy it to a register, increment, and copy the result back to the address. Worst: My CPU cache is filled with vector pointers, not with vector-member pointers. Too few hits, too much cache "refueling".
If I could manage to have all those members just in a vector, CPU cache hits would be much more frequent.

A: Try the following:
int count = 10000000;
std::vector<foo> fooArr;
fooArr.resize(count, foo());

for (auto it= fooArr.begin(); it != fooArr.end(); ++it) {
   it->inc();
}

The new is killing you and actually you don't need it because resize inserts elements at the end if the size it's greater (check the docs: std::vector::resize)
And the other thing it's about using pointers which IMHO should be avoided until the last moment and it's uneccesary in this case. The performance should be a little bit faster in this case since you get better locality of your references (see cache locality). If they were polymorphic or something more complicated it might be different.


text:
Q: Find MAX with JOIN where Field also shows up in another Table I have 3 tables: Master, Paper and iCodes. For a certain set of Master.Ref's, I need to find Max(Paper.Date), where the Paper.Code is also in the iCodes table (i.e., Paper.Code is a type of iCode). Master is joined to Paper by the File field.
EDIT:
I only need the Max(Paper.Date) its corresponding Code; I do not need all of the Codes.
I wrote the following but it is very slow. I have a few hundred ref #'s to look for. What is a better way to do this?
SELECT Master.Ref,
       Paper.Code,
   mp.MaxDate
FROM ( SELECT p.File ,
              MAX(p.Date) AS MaxDate ,
       FROM Paper       AS p
       LEFT JOIN Master AS m ON p.File = m.File
       WHERE m.Ref IN ('ref1', 'ref2', 'ref3', 'ref4', 'ref5', 'ref6'... )
         AND p.Code IN ( SELECT DISTINCT i.iCode
                         FROM iCodes AS i
                       )
       GROUP BY p.File
     ) AS mp
LEFT JOIN Master ON mp.File     = Master.File
LEFT JOIN Paper  ON Master.File = Paper.File
                AND mp.MaxDate  = Paper.Date
WHERE Paper.Code IN ( SELECT DISTINCT iCodes.iCode
                      FROM iCodes
                    )

A: Does this do what you want?
SELECT m.Ref, p.Code, max(p.date)
FROM Master m LEFT JOIN
     Paper
     ON m.File = p.File
WHERE p.Code IN (SELECT DISTINCT iCodes.iCode FROM iCodes) and
      m.Ref IN ('ref1','ref2','ref3','ref4','ref5','ref6'...)
GROUP BY m.Ref, p.Code;

EDIT:
To get the code on the max date, then use window functions:
select ref, code, date
from (SELECT m.Ref, p.Code, p.date
             row_number() over (partition by m.Ref order by p.date desc) as seqnum
      FROM Master m LEFT JOIN
           Paper
           ON m.File = p.File
      WHERE p.Code IN (SELECT DISTINCT iCodes.iCode FROM iCodes) and
            m.Ref IN ('ref1','ref2','ref3','ref4','ref5','ref6'...)
     ) mp
where seqnum = 1;

The function row_number() assigns a sequential number starting at 1 to a group of rows.  The groups are defined by the partition by clause, so in this case everything with the same m.Ref value would be in a single group.  Within the group, rows are assigned the number based on the order by clause.  So, the one with the biggest date gets the value of 1.  That is the row you want.


text:
Q: Error with Subscript in DialogInput Writing:
DialogInput[DialogNotebook[
  {TextCell["(" <> ToString[Subscript["m", "2"], StandardForm] <> ")"],
   InputField[Dynamic[x], String],
   DefaultButton[DialogReturn[x]]}]]

I get:

and I do not understand how to correct the code.

A: I would avoid linear syntax (strings generated using ToString[.., StandardForm]) and just use normal expressions. For example:
DialogInput[
    DialogNotebook[
        {
        Row[{"(", Subscript[m, 2], ")"}],
        InputField[Dynamic[x],String],
        DefaultButton[DialogReturn[x]]
        }
    ],
    ShowStringCharacters->False
]


text:
Q: How do I get vb.net to add all links within a particular div class from a webpage I want to add in the list box items:
https://www.facebook.com/XXXXXXX

https://www.facebook.com/XXXXXXX

document:

 <a href="https://www.facebook.com/XXXXXXX?fref=pb&hc_location=friends_tab"

 <a href="https://www.facebook.com/XXXXXXX?fref=pb&hc_location=friends_tab"

 <a href="https://www.facebook.com/XXXXXXX?fref=pb&hc_location=friends_tab"

A: This works as expected:
Dim html = File.ReadAllText("Path")
Dim doc = New HtmlAgilityPack.HtmlDocument()
doc.LoadHtml(html)

Dim anchorTexts As New List(Of String)
Dim divNodes = doc.DocumentNode.SelectNodes("//div[@class='fsl fwb fcb']")
If Not divNodes Is Nothing Then
    For Each div In divNodes
        For Each anchorNode In div.SelectNodes("//a")
            Dim href As String = anchorNode.GetAttributeValue("href", "")
            If Not String.IsNullOrEmpty(href) Then
                anchorTexts.Add(href)
            End If
        Next
    Next
End If


text:
Q: Can @media used to trigger different Javascript? I am trying to add ad code (javascript)  into my responsive design blog. But I'm not sure how to handle it. Can I make use of @media? I have two ads 728x90 and 320x50, both javascript code. I want to display 728x90 when width is greater than 730 else always 320x50. Is this possible?
My blog is a tumblr blog.

A: CSS can't trigger JavaScript, but JavaScript can directly test media queries.
if (window.matchMedia("min-width: 730px").matches) {
  // show big ad
}
else {
  // show small add
}

MDN

A: you can find the client window width with js and apply your logic accordingly
if (window.innerWidth > 730) {
  //your code here
} else {
  // code here
}

http://www.w3schools.com/jsref/prop_win_innerheight.asp

A: Try the following and see if it works:
jQuery(window).on('resize change', function () {
if(jQuery(window).width() > 730){
    Do something here...
}else{
    Do something here...
}}


text:
Q: How to I set one root application next to other applications on Oracle Weblogic Server? I got 3 applications running on my Weblogic server. Let's say these are:

*

*www.example.org/a

*www.example.org/b

*www.example.org/c

Now I want application "a" to be directly available via www.example.org without the /a at the end.
I know that I can set context-root for "a" like this:
   <web>
      <web-uri>a.war</web-uri>
      <context-root>/</context-root>
   </web>

But won't this cause any problems with the other installed apps like path collisions and such?

A: You should use Oracle HTTP Server, Apache Web Server (with WebLogic plugin), or Oracle Traffic Director, to correctly map that, instead of deploying an application to root context.
Keep all apps deployed to their / context roots. Map the external context root on the Web Tier.


text:
Q: jQuery to change all the links in the page  $(function(){
            $('a').each(function(){
                        var x=this.href;
                        this.href="www.somesitename.com/filter"+this.href;
                  });
         });

i wrote the above jQuery script to append some site name to all the links in the page but it's not working as expected.

A: You probably need to add http://:
$(function(){
    $('a').each(function() {
        $(this).attr('href', 'http://www.somesitename.com/filter' + this.href);
    });
});

A: Further improvement of Darin's solution:
$(function(){
    $('a').attr('href', (n, old) => 'http://www.somesitename.com/filter' + old);
});

One thing to notice that in case of .each this.href produces an absolute fully qualified URL (e.g.: http://localhost:8888/mylink) so result might look like: www.somesitename.com/filter/http://localhost:8888/mylink. The solution was to get attribute value via jQuery: $(this).attr('href'), which correctly yields /mylink.

A: I wonder why would you use jQuery for such basic behaviour...
that is why the tag BASE is there for

Specify a default URL and a default target for all links on a page:

    <base href="http://www.w3schools.com/images/" />
    <base target="_blank" />

    W3Schools

don't complicate what is simple!

added
from Sitepoint

The base element is only going to be useful to you if all your relative links or form submissions go to the same location.

A: Here is what i have used to do this
I have removed each 'blog/' from href on the page in the same you can change link or update it
$('a').each(function(){
       var updated_link = $(this).attr('href').replace('blog/', '');
       $(this).attr('href', updated_link);
    });
I have used replace function to update part of url.in your case you can update it

A: define a base tag in your head and then update it's href property when needed.
<base href="http://www.some-domain.com/" />
$("base").attr("href","http://www.some-other-domain.com/");

A: You will probably need to use the append() function jQuery has http://api.jquery.com/append/


text:
Q: navegacion a una propiedad epecifica Estoy realizando una API , la cosa es que quiero listar los datos de una tabla "businessobject" que tiene relacion con otras tablas.Estoy usando DTO para no enviar todo los datos de la tabla sino las que se requieras,el detalle es cuando quiero navegar a datos mas "profundos" de una relacion. es como si no le reconociera.
CODIGO.
 public function  all()
{
    $listClassBo = $this->model->with(["promotionproduct.promotion", "categorybusinessobject.category", "businessobjectrole"])->where("state", 1)->get()->map(function ($businessobject) {
        return ClassBo::fromRepositoryToBo(ClassRepositoryDto::fromModelToRepository($businessobject));
    });
           return $listClassBo;
}

Y mi DTO de "ClassRepository" que devuelve un objeto con informacion necesaria, lo tengo asi:
  public static function fromModelToRepository(Businessobject $businessObject): self
{
    $properties = [
        "id" => $businessObject->id,
        "name" => $businessObject->name,
        "type" => $businessObject->type,
        "category" => $businessObject->category_business_object,
        "price" => $businessObject->price,
        "state" => $businessObject->state,
        "promotion" => $businessObject->type == TypeClassEnum::especial() ? $businessObject->promotion_product : null,
        "role" => $businessObject->businessobjectrole
    ];
    return new self($properties);
}

ya hice varias pruebas y en la lista me sale null la promocion y las categoria, es por que no puedo acceder a esos valores,alguna forma de hacerlo?
resultado.


text:
Q: How to use a specific query in Retrofit with Android? I have an API interface which has two overloaded methods:
public interface Api {
    @GET("movie/now_playing")
    Call<ApiResponse> getMovies(@Query("page") int page);

    @GET("search/movie")
    Call<ApiResponse> getMovies(@Query("query") String query,  @Query("page") int page);
}

First one is used to get now playing movies and the second one to search for movies.
In my MainActivity I use this code to display the data in a RecyclerView:
MovieViewModel movieViewModel = ViewModelProviders.of(this).get(MovieViewModel.class);
MovieAdapter adapter = new MovieAdapter(this);
movieViewModel.moviePagedList.observe(this, adapter::submitList);
recyclerView.setAdapter(adapter);

This is my MovieViewModel class:
public class MovieViewModel extends ViewModel {
    LiveData<PagedList<ApiResponse.Movie>> moviePagedList;

    public MovieViewModel() {
        MovieDataSourceFactory movieDataSourceFactory = new MovieDataSourceFactory();
        PagedList.Config config = new PagedList.Config.Builder().setEnablePlaceholders(false).setPageSize(20).build();
        moviePagedList = new LivePagedListBuilder<>(movieDataSourceFactory, config).build();
    }
}

And this my MovieDataSourceFactory class:
public class MovieDataSourceFactory extends DataSource.Factory<Integer, ApiResponse.Movie> {
    private MutableLiveData<PageKeyedDataSource<Integer, ApiResponse.Movie>> movieLiveDataSource = new MutableLiveData<>();

    @Override
    public DataSource<Integer, ApiResponse.Movie> create() {
        MovieDataSource movieDataSource = new MovieDataSource();
        movieLiveDataSource.postValue(movieDataSource);
        return movieDataSource;
    }
}

And this is my MovieDataSource class:
public class MovieDataSource extends PageKeyedDataSource<Integer, ApiResponse.Movie> {
    @Override
    public void loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull LoadInitialCallback<Integer, ApiResponse.Movie> callback) {
        Api api = RetrofitClient.getInstance().getApi();
        Callback<ApiResponse> call = new Callback<ApiResponse>() {
            @Override
            public void onResponse(@NonNull Call<ApiResponse> call, @NonNull Response<ApiResponse> response) {
                if(response.body() != null){
                    callback.onResult(response.body().movieList, null, page + 1);
                }
            }

            @Override
            public void onFailure(@NonNull Call<ApiResponse> call, @NonNull Throwable t) {}
        };
        api.getMovies(page).enqueue(call);
    }

    //loadBefore and loadAfter methods
}

If I run this code, everything works fine, the first query is invoked and I get the result correctly. The question is, how can I dynamically use one or the other?
api.getMovies(query, page).enqueue(call);

A: boolean globalVariableShouldUseGetMoviesCallWithOnlyOneArgument = true

private void doNetworkCallAndCheckBooleanStatus(){
    if (globalVariableShouldUseGetMoviesCallWithOnlyOneArgument) {
        getMovies(thisIsOneArgumentAsYouCanSee);
    } else {
        getMovies(thisIsUsingTwoArguments, asYouCanSee);
    }
}

private void someOtherMethodInTheApp() {
    globalVariableShouldUseGetMoviesCallWithOnlyOneArgument = false
    doNetworkCallAndCheckBooleanStatus()
}


text:
Q: Ignore temporary files or suppress "Invalid Exclude: filename. File not found." message from Swift Package Manager I have a Swift Package which consists only of C files. It builds and works great as part of my iOS app. However, the directory also contains a Makefile and a simple REPL to use for adhoc development and testing. Accordingly, there will often, but not always, be .o files, as well as support files like tags during active development.
I use the SPM Package { targets: [.target( exclude ... setting to make sure those files are never included while building the app which includes this package. However, it means that in a "clean" environment like a CI machine there will be build messages like:
Invalid Exclude '..../Packages/SchemeC/Sources/SchemeC/s7repl.o': File not found.
Invalid Exclude '..../Packages/SchemeC/Sources/SchemeC/s7sqlite.o': File not found.
Invalid Exclude '..../Packages/SchemeC/Sources/SchemeC/s7.o': File not found.
Invalid Exclude '.../Packages/SchemeC/Sources/SchemeC/TAGS.scheme': File not found.

Is there a way to mark a file as "Ignore" for Swift Package Manager? (I.e. similar to including a file in .gitignore?)


text:
Q: System.Net.Sockets.SocketException in Function App 2.0 I have function app 2.0 with set of functions with service bus and http trigger.
After deploying to our Azure production environment, we started to see below exception logged in the app insight from our function app.
Exception Type : System.Net.Sockets.SocketException
Exception Message:
The SSL connection could not be established, see inner exception. Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. An existing connection was forcibly closed by the remote host
We are clueless about this exception and was following the issue - https://github.com/dotnet/core/issues/1696
 and not sure by adding DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER=false will solve this issue.
Below is the stack trace I find it in the exception which is not triggered by my code.
System.Net.Http.HttpRequestException:
   at System.Net.Http.ConnectHelper+<EstablishSslConnectionAsyncCore>d__5.MoveNext (System.Net.Http, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.ValueTask`1.get_Result (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1+ConfiguredValueTaskAwaiter.GetResult (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Net.Http.HttpConnectionPool+<CreateConnectionAsync>d__44.MoveNext (System.Net.Http, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.ValueTask`1.get_Result (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1+ConfiguredValueTaskAwaiter.GetResult (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Net.Http.HttpConnectionPool+<WaitForCreatedConnectionAsync>d__49.MoveNext (System.Net.Http, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.ValueTask`1.get_Result (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1+ConfiguredValueTaskAwaiter.GetResult (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Net.Http.HttpConnectionPool+<SendWithRetryAsync>d__39.MoveNext (System.Net.Http, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter.GetResult (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Net.Http.RedirectHandler+<SendAsync>d__4.MoveNext (System.Net.Http, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter.GetResult (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Net.Http.DiagnosticsHandler+<SendAsync>d__2.MoveNext (System.Net.Http, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
Inner exception System.IO.IOException handled at System.Net.Http.ConnectHelper+<EstablishSslConnectionAsyncCore>d__5.MoveNext:
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1+ConfiguredValueTaskAwaiter.GetResult (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Net.FixedSizeReader+<ReadPacketAsync>d__1.MoveNext (System.Net.Security, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Net.Security.SslState.ThrowIfExceptional (System.Net.Security, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
   at System.Net.Security.SslState.InternalEndProcessAuthentication (System.Net.Security, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
   at System.Net.Security.SslState.EndProcessAuthentication (System.Net.Security, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
   at System.Net.Security.SslStream.EndAuthenticateAsClient (System.Net.Security, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
   at System.Net.Security.SslStream+<>c.<AuthenticateAsClientAsync>b__47_1 (System.Net.Security, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Net.Http.ConnectHelper+<EstablishSslConnectionAsyncCore>d__5.MoveNext (System.Net.Http, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
Inner exception System.Net.Sockets.SocketException handled at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw:

A: Thanks All.
Issue has been resolved by adding this environment varaible - DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER=false as specified in this Issue
https://github.com/dotnet/core/issues/1696 and not sure by adding


text:
Q: How SQLAlchemy's many to many inserts work? I've been trying to understand how to insert "many-to-many" records in database using raw SQL properly, but couldn't find any examples, so I decided to see what SQLAlchemy would generate:
I've created my python objects models:
python objects model (models.py):
import typing

from dataclasses import dataclass

@dataclass(unsafe_hash=True)
class OrderLine:
    """Item amount + SKU in order"""

    order_id: int
    amount: int
    sku: str

class Batch:
    """Batch of items."""

    def __init__(self, batch_name: str, amount: int, sku: str, eta: typing.Optional[datetime.datetime]):
        self.batch_name = batch_name
        self.available_quantity = amount
        self.sku = sku
        self.eta = eta

        self._allocations = set()

    def allocate(self, order_line: OrderLine):
        self._allocations.add(order_line)

*

*tables and sqlalchemy's mappers (tables.py):

from sqlalchemy import Table, MetaData, Column, Integer, String, Date, ForeignKey
from sqlalchemy.orm import mapper, relationship

import models

metadata = MetaData()

order_lines = Table(
    "order_lines",
    metadata,
    Column("id", Integer, primary_key=True, autoincrement=True),
    Column("order_id", Integer),
    Column("amount", Integer, nullable=False),
    Column("sku", String(255)),
)

batches = Table(
    "batches",
    metadata,
    Column("id", Integer, primary_key=True, autoincrement=True),
    Column("batch_name", String(255)),
    Column("available_quantity", Integer),
    Column("sku", String(255)),
    Column("eta", Date, nullable=True)
)

allocations = Table(
    "allocations",
    metadata,
    Column("id", Integer, primary_key=True, autoincrement=True),
    Column("batch_id", ForeignKey("batches.id")),
    Column("orderline_id", ForeignKey("order_lines.id"))
)

def map_objects_to_tables():
    lines_mapper = mapper(models.OrderLine, order_lines)
    mapper(models.Batch, batches, properties={
        "_allocations": relationship(
            lines_mapper, secondary=allocations, collection_class=set
        )
    })

Now if I try to save an object using an ORM:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

import models
import tables

engine = create_engine("sqlite:///:memory:", echo=True)
tables.metadata.create_all(engine)
tables.map_objects_to_tables()

example_batch = models.Batch("test", 1000, "WHITE DOOR", None)
example_line = models.OrderLine(1, 50, "WHITE DOOR")
example_batch.allocate(example_line)

session = sessionmaker(bind=engine)()

session.add(example_batch)
session.commit()

sqlalchemy produces following output:
BEGIN (implicit)
  INSERT INTO batches (batch_name, available_quantity, sku, eta) VALUES ('test', 1000, 'WHITE DOOR', null)
  INSERT INTO order_lines (order_id, amount, sku) VALUES (1, 50, 'WHITE DOOR')
  INSERT INTO allocations (batch_id, orderline_id) VALUES (1, 1)
COMMIT

BEGIN (implicit)
  SELECT order_lines.id AS order_lines_id, order_lines.order_id AS order_lines_order_id, order_lines.amount AS order_lines_amount, order_lines.sku AS order_lines_sku
  FROM order_lines
  WHERE order_lines.id = 1

How SQLAlchemy knows when inserting into allocations, that batch_id and orderline_id should be (1, 1)? Does it somehow manages those values inside if foreign key maps to an autoincrement?
What is the point of last select?


text:
Q: How can I delete latest 2 binlog files from RDS MYSQL Aurora I have created a snapshot of Aurora MYSQL database and then restore it. Let's call it clone
Here is the output of the command SHOW BINARY LOGS on the master database

Here is the output of the command SHOW BINARY LOGS on the clone database

As you can see there are 2 extra binlog files on the clone which I don't want. I want to have binlog identical to the master.
How can I delete the last 2 bing logs from the clone database?
There is nothing special in these bin log files
mysql-bin-changelog.603814

mysql-bin-changelog.603815

A:
"I want to have binlog identical to the master."

Why would you want this? The binlogs are already not identical between these two instances, even besides the last two, because the filenames and sizes are different.
Binlogs start new files if FLUSH LOGS is run, or if MySQL Server restarts, or the file reaches the max binlog size. The number of files and their sizes are bound to be out of sync between the source instance and its replicas. I would guess in this case that restoring the snapshot caused two restarts.
It's not a problem for binlog files to have different sizes. As long as they contain the same changes, they can be stored in few files or many files, and they don't have to be the same.
To apply changes in binlogs, you must have a contiguous set of changes since the last snapshot. If you were to purge the last two files, you could never use the binlogs for replication or point-in-time recovery, at least not past mysql-bin-changelog.603813.
Purging the binlog files older than the latest snapshot is common and recommended, but not the newest binlog files. In fact, PURGE BINARY LOGS will never remove the latest binlog file, because the MySQL Server is still using it.
One solution for you is to set the expire_logs_days in the parameter group to a modest value such as 2 or 3, then wait that number of days for the current set of binlogs to expire. After that, the small binlog files will be gone.


text:
Q: como poner una condicional dentro de echo td php Un saludo cordial estimados amigos, Tengo una dificultad en insertar una condicional segun el numero de evaluacion que tengo de los cuales deseo cambiar las notas de numero a letras dentro de un echo td. espero su pronta ayuda saludos.
Dejo el codigo:

$tb_miperu_notas = $conn->prepare("SELECT id, nota
                                                                    FROM tb_miperu_notas
                                                                    WHERE id_alumno = ".$alumno['id']."
                                                                    AND id_materia = ".$id_materia);
                                $tb_miperu_notas->execute();
                                $tb_miperu_notas = $tb_miperu_notas->fetchAll();
                                $nota_media=0;

                                foreach ($tb_miperu_notas as $eval => $nota) {
                                        $nota_media += $nota['nota']/4;

                                     echo '
                                            <input type="hidden"
                                            name="nota'.$eval.'" value="'. $nota['nota'] . '" >'. $nota['nota'] . '	';

                                        if ($nota['nota'] >= 18) {
                                            echo '
AD
';

                                        } else if ($nota['nota'] >= 14) {
                                            echo '
A
';

                                        } else if ($nota['nota'] >= 11) {
                                            echo '
B
';

                                        } else if ($nota['nota'] >= 1) {
                                            echo '
C
';

                                        } else if ($nota['nota'] >= 0) {
                                            echo '
NSP
';
                                        }

                                }

Por lo tanto aqui les dejo la foto lo que necesito es cambiar esas notas  segun las condionales en letras

Lo que intento es que dentro del echo td deseo insertar la condionales pero me sale error. echo
dejo la tabla.

                        NRO
                        CODIGO
                        APELLIDOS Y NOMBRES
                        TA
                        EP
                        EF
                        AV
                        PROMEDIO
                        LETRAS
                        OBSERVACIONES

                    <?php foreach ($alumnos as $index => $alumno) :?>

                            <?php echo $i++ ?>
                            <?php echo $alumno['dni'] ?>
                            <?php echo $alumno['apellido_paterno']." ".$alumno['apellido_materno'].", ".$alumno['nombres'] ?>

                            <?php
                                //escribiendo las notas en columnas
                                $tb_miperu_notas = $conn->prepare("SELECT id, nota
                                                                    FROM tb_miperu_notas
                                                                    WHERE id_alumno = ".$alumno['id']."
                                                                    AND id_materia = ".$id_materia);
                                $tb_miperu_notas->execute();
                                $tb_miperu_notas = $tb_miperu_notas->fetchAll();
                                $nota_media=0;

                                foreach ($tb_miperu_notas as $eval => $nota) {
                                        $nota_media += $nota['nota']/4;

                                    echo '<input type="hidden"
                                            name="nota'.$eval.'" value="'. $nota['nota'] . '" >'. $nota['nota'] .

                                        if ($nota['nota'] >= 18) {
                                            echo '
AD
';

                                        } else if ($nota['nota'] >= 14) {
                                            echo '
A
';

                                        } else if ($nota['nota'] >= 11) {
                                            echo '
B
';

                                        } else if ($nota['nota'] >= 1) {
                                            echo '
C
';

                                        } else if ($nota['nota'] >= 0) {
                                            echo '
NSP
';
                                        }
                                    } '	';

                                }

                            echo ''.number_format($nota_media).'	';
                            echo ''. $alumno['observaciones']. '	';
                            ?>

                    <?php endforeach;?>

segun las codionales if necesito cambiar los numero por letras en mi tabla.


text:
Q: I don't understand how an option is wrong in a multiple choise question I dont understan why option E from this multiple choice question is accurate (option E is not the answer to the problem but was one of the options which are not false).
I dont understand why its potential cannot be described by the formla. Does it have to do with that it is different coordinate system (cylindrical) and the dipole should be oriented in z direction? But can't that formula be used anyway if we somehow turn the formula or something?

Problem:

The option:

From Collection of formulas:

A: This is a common misconception. A dipole is NOT a set of two opposite charges, so you do not have a dipole in your configuration.
To be precise, you have a "physical dipole", two equal (in absolute value) and opposite ( sign) charges near each other. This is a usual configuration; but, as you have a finite numebr of point charges, you find the potential via superposition principle. The potential at one point is the sum of the one created by 1 and the one created by 2.
On the contrary, a "pure" dipole is an abstract idea. A dipole is an ideal concept, which is what appears as the first order term in the multipolar development of the potential.
In plain words, a pure dipole is a limit case of that you have. A pure dipole is two charges brought together, so near that their distance is exactly 0. If we want the distance to be 0, we better have charges tending to infinity, so that a dipole would have $q\cdot d = 0 \cdot \infty$.
$$dipole=\lim_{d\rightarrow 0\\ q\rightarrow +\infty} (q^+\text{---- }q^-)$$

A: UPDATE:
Since the other answers are providing more of the answer,
let me reveal my interactive visualization.
As I mentioned in the comment to the OP, the "physical dipole" (composed of two equal-magnitude oppositely-signed point charges)
is not the same as the "pure [or point] dipole". For the same dipole moment $\vec p$, they disagree, especially near the dipole.
A plot reveals this disagreement.
At large distances (asymptotically), the two are in better agreement.
https://www.desmos.com/calculator/dis3e4xadc ( robphy - dipole - pure vs physical ) [assumes that the charges on the x-axis, are centered at the origin]
[Play with the sliders to get some intuition. Fix $p$ so that when you change $d$, you must have $Q=p/d$.
When do the potentials agree?]
The green graph is the pure-dipole potential.
The dashed-lines are negative equipotentials.

As I suggested in the original version of this answer,
one can plot these potential-functions for points along the x-axis.

Original answer:
Since this is tagged homework, I won't give the whole answer.
Given two point charges on the x-axis (following your givens): $q$ at $x=-(a/2)$ and $-q$ at $x= (a/2)$,
compute the potential at (say) $x=(a/4)$.
Compare it to the value from the potential for the "point dipole" formula with $\vec p=q\vec a=(-q a) \hat x$ and $\vec R=(a/4)\hat x$.
Can you plot the potential of this two-point-charge example for points on the x-axis (vary x, fix y at 0)?
Can you plot the potential of the point dipole for points on the x-axis (vary x, fix y at 0)?

A: The potential near the two charges would be found by adding two terms.  The formula you show is a good approximation if, R, is much larger than, a.


text:
Q: Calling a function when any function from another class is called I want to use this simple class:
class Debug
{
    function __construct( $caller )
    {
       file_put_contents( "out", print_r( $caller, true ) . PHP_EOL, FILE_APPEND );
    }

}

And have another class:
class SomeObject
{
    public function someFunction()
    {
        // calls the Debug constructor or function automatically
    }
}

Whenever someFunction or any other function from this class is executed, it should automatically execute Debug constructor or call a function from that class and I want to grab debug data from which function the debug class was called. How can I accomplish this?


text:
Q: Como paginar en php Buenas, tengo un listado de una base de datos con el modelo vista controlador y no se como paginarlo
view_listaUsuarios

Registros

            Usuario
            Contraseña
            Nombre
            1º Apellido
            2º Apellido
            DNI
            Dirección
            Población
            Código Postal
            Provincia
            Teléfono
            Email
            Web
            Blog
            Twitter
            Fecha de registro

        <?php foreach ($usuarios as $user)
        {

        ?>

        <?php echo $user['usuario'];?>
        <?php echo $user['contraseña'];?>
        <?php echo $user['nombre'];?>
        <?php echo $user['apellido1'];?>
        <?php echo $user['apellido2'];?>
        <?php echo $user['dni'];?>
        <?php echo $user['direccion'];?>
        <?php echo $user['poblacion'];?>
        <?php echo $user['CPostal'];?>
        <?php echo $user['provincia'];?>
        <?php echo $user['telefono'];?>
        <?php echo $user['email'];?>
        <?php echo $user['web'];?>
        <?php echo $user['blog'];?>
        <?php echo $user['twitter'];?>
        <?php echo $user['fecha'];?>

        <?php }?>

ctrl_listaUsuarios
   include_once (MODEL_PATH.'model_usuario.php');

    $usuarios = listaUsuarios();
    include (VIEW_PATH.'view_listarUsuarios.php');

model_usuario
   include_once (MODEL_PATH.'claseBD.php');

function insertaUsuario($valores){
    try{
        $sentencia = 'INSERT INTO usuarios (usuario, contraseña, nombre, apellido1, apellido2, dni,direccion, '
                . 'poblacion, CPostal, provincia,telefono, email, web, blog, twitter)'
                . ' VALUES ("'.$valores['usuario'].'","'.$valores['pass'].'","'.$valores['nombre'].'","'.$valores['apellido1'].'","'.$valores['apellido2'].'",'
                . '"'.$valores['dni'].'","'.$valores['direccion'].'","'.$valores['poblacion'].'","'.$valores['CPostal'].'","'.$valores['provincia'].'","'.$valores['telefono'].'",'
                . '"'.$valores['email'].'","'.$valores['web'].'","'.$valores['blog'].'","'.$valores['twitter'].'","'.$valores['tipo'].'")';
        $Db=db::getInstance();
        $Db->Ejecutar($sentencia);

    } catch (PDOexception $e){
        die($e->getMessage());
    }
}
function listaUsuarios(){
    try{
        $sentencia='SELECT * FROM usuarios ORDER BY fecha DESC';
        $Db=db::getInstance();
        $listado=$Db->Ejecutar($sentencia);
        return $listado;
    } catch (PDOexception $e){
        die($e->getMessage());
    }
}
function borraUsuario($usuario){
    try{
        $sentencia = 'DELETE  FROM usuarios WHERE usuario =".$usuario."';
        $Db=db::getInstance();
        $listado=$Db->Ejecutar($sentencia);
    } catch (PDOexception $e) {
        die($e->getMessage());
    }
}

A: Para usar dataTable debe agregar los archivos jquery-1.12.4.min.js también jquery.dataTables.min.js y jquery.dataTables.min.css y los referencia.
Luego agregas el script, puede ser como este:

Donde #myTable es el nombre del id de su tabla y le agregas las clases para que funcione correctamente. Por ejemplo al crear la tabla sería algo así:

 ....
 ....
 ....

Y al terminar tendrá una tabla con campo de búsqueda , paginación y un select con la opción de los registros que quiere mostrar por página. Espero haber podido ayudar a lo que necesita.


text:
Q: How to pass parameters to Microsoft SQL Server query? I am new to SQL Server 2012, and I found SQL Server Management Studio is a little bit difficult to use.
Here is one of the problems that I cannot solve: Is it possible to pass values to a query in SQL Server Management Studio ?
SELECT col1, col2
FROM table
WHERE col3 = :variable

If I run this query in the Studio, instead of prompting an input field to let me input value for variable, it will not execute the query because of an error

Incorrect syntax near ':'

I used to use the same method in SQL Developer for Oracle, thus I thought it would work the same.
Thanks for any useful advice.

A: DECLARE @someVariable varchar(n)
SET @someVariable = 'variable'

SELECT col1, col2
FROM table
WHERE col3 = someVariable


text:
Q: Linq .All returning true for empty collection Consider the following code:
static void Main(string[] args)
{
    List<string> items = new List<string>();
    string result = null;

    if(items.All(o => o == "ABC"))
    {
        result = "All";
    }
    else if(items.Any(o => o == "XYZ"))
    {
        result = "Any";
    }

    Console.WriteLine(result);
    Console.Read();
}

This prints "All".
Why does an empty list satisfy an "All" condition where o == "ABC"

A: According to MSDN:-
Enumerable.All

Return true if every element of the source sequence passes the
  test in the specified predicate, or if the sequence is empty;
  otherwise, false.

So in your case since items is an empty collection it is returning true.

A: This is by design and also consistent with how the universal quantifier ∀ works in mathematics on sets.


text:
Q: The meaning of "stood it out, visibly yellowing,"
We booked our berths, and when the time came, he wafted us and ours
aboard the Southampton mail-boat with the pomp of plenipotentiaries
and the precision of the Navy. Then he dismissed his yacht, and became
an inconspicuous passenger in a cabin opposite to mine, on the port
side. We ran at once into early British spring weather, followed by
sou'west gales. Mrs. Godfrey, Milly, and the nurses disappeared.
Attley stood it out, visibly yellowing, till the next meal, and followed suit, and Shend and I had the little table all to
ourselves.

This is from "The Dog Hervey " by Rudyard Kipling.
https://www.kiplingsociety.co.uk/tale/the-dog-hervey.htm
What does "stood it out, visibly yellowing" mean in this context?

A: The passage is describing unpleasant weather at sea. "Early British spring weather, followed by southwest gales" does not make for a pleasant and calm voyage; instead there would be much rocking of the ship. Passengers who were not accustomed to this would become very seasick.
Based on the context of "next meal" and "little table," Kipling is using the dining room to demonstrate the illness of the other passengers. Seasick people are nauseous and do not want to eat anything, so it makes sense that they would "disappear" from the dining table; likely they remained in their rooms and did not come out to eat.
Stood it out means endured it. Yellowing is the present participle of the verb to yellow, that is, to become yellow in color, with "visibly" modifying it. So: Attley endured the seasick-causing conditions, while turning yellow from the seasickness, until the next meal; then he also stopped coming.
The "yellow" describes Attley's face; seasickness and other illness can result in people's faces turning pale and sometimes other colors. Usually seasick people are described as being green, not yellow, but it's a sort of sickly green-yellow that might be described either way.


text:
Q: Why jquery UI sortable don't work on AngularJS templateURL? I'm trying to have sortable panels on each of my tab. If I put panels on index.html it works, but when used inside directive templateUrl: tabs.html it doesn't. Please see the Plunker example here
My html file:

    <app-tabs></app-tabs>

My tabs.html file:

        {{t.Name}}

    Add Tab

Panel 1

Panel 2

Panel 3

Panel 4

Panel 5

Panel 6

My app.js file:
(function() {

  var modelTabs = [{
    Id: 2,
    Name: "Tab 1",
    Layout: 1
  }, {
    Id: 3,
    Name: "Tab 2",
    Layout: 1
  }, {
    Id: 4,
    Name: "Tab 3",
    Layout: 1
  }];

  var app = angular.module('appTest', []);

  app.controller('testCtrl', ["$scope", function($scope) {

    $scope.myListOfTabs = modelTabs;
  }]);

  app.directive("appTabs", function() {
    return {
      restrict: "E",
      templateUrl: "tabs.html",
      controller: function($scope) {
        $scope.tab = 2;

        $scope.isSet = function(checkTab) {
          return $scope.tab === checkTab;
        };

        $scope.setTab = function(activeTab) {
          $scope.tab = activeTab;
        };
      },
      controllerAs: "tab"
    };
  });

})();

A: First of all you'll need to select the .sortable elements and apply the sortable plugin to them.
Next issue is that the items inside that ng-repeat won't exist in the DOM at the time link runs for the parent directive. You can find a clear explanation of this here. For now the only solution is a timeout.
setTimeout(function() {
    $('.sortable', element).sortable();
}, 100);

Also
 so that the .sortable class is not inside another
.
Here is the working plunker.

A: All you need to do is create a sortable directive
app.directive("sortable", function() {
    return {
      restrict: "C",
      link: function(scope, element, attrs) {
        element.sortable();
      }
    }
});

This assures that once the element exists, the plugin will be bound to it
DEMO


text:
Q: Download a file(attachment) on href sending Authorization Header In my web api app(.net webapi) y need to pass the authorization header when a download link is clicked.
Normally, when you use a href link this not pass the authorization header and then, the api authorization denegate the download(api request with axios).
How to achieve this and add this authorization header when href is clicked with a React-redux front?
or another way to aproach this...

A: href link won't be possible.
You will need to make a xhr request. I'm not familiar with react well, but in vue.js projects I use axios library to perform such requests
https://www.npmjs.com/package/axios


text:
Q: XGBoost - predict not exported in namespace I am trying to tune an xgboost model with a multiclass dependent variable in R. I am using MLR to do this, however I run into an error where xgboost doesn't have predict within its namespace - which I assume MLR wants to use. I have had a look online and see that other people have encountered similar issues. However, I can't entirely understand the answers that have been provided (e.g. https://github.com/mlr-org/mlr/issues/935), when I try to implement them the issue persists. My code is as follows:
# Tune parameters
#create tasks
train$result <- as.factor(train$result)  # Needs to be a factor variable for makeClass to work
test$result <- as.factor(test$result)
traintask <- makeClassifTask(data = train,target = "result")
testtask <- makeClassifTask(data = test,target = "result")

lrn <- makeLearner("classif.xgboost",predict.type = "response")

# Set learner value and number of rounds etc.
lrn$par.vals <- list(
 objective = "multi:softprob",  # return class with maximum probability,
 num_class = 3,  # There are three outcome categories
 eval_metric="merror",
 nrounds=100L,
  eta=0.1
)

# Set parameters to be tuned
params <- makeParamSet(
 makeDiscreteParam("booster",values = c("gbtree","gblinear")),
 makeIntegerParam("max_depth",lower = 3L,upper = 10L),
 makeNumericParam("min_child_weight",lower = 1L,upper = 10L),
 makeNumericParam("subsample",lower = 0.5,upper = 1),
 makeNumericParam("colsample_bytree",lower = 0.5,upper = 1)
)

# Set resampling strategy
rdesc <- makeResampleDesc("CV",stratify = T,iters=5L)

# search strategy
ctrl <- makeTuneControlRandom(maxit = 10L)
#parallelStartSocket(cpus = detectCores())  # Enable parallel processing

 mytune <- tuneParams(learner = lrn
                 ,task = traintask
                 ,resampling = rdesc
                 ,measures = acc
                 ,par.set = params
                 ,control = ctrl
                 ,show.info = T)

The specific error I get is:
Error: 'predict' is not an exported object from 'namespace:xgboost'
My package versions are:
packageVersion("xgboost")
[1] '0.6.4'

packageVersion("mlr")
[1] '2.8'

Would anyone know what I should do here?
Thanks in advance.


text:
Q: How to add rows to Vaadin table from a Map>? I have a Collection as:
Map<String,Map<Date,Statistics>> map;

Statistics look something like this:
    private final Date day;
    private int count;
    private long totalTime;
    private Map<Integer, BigDecimal> averagesMap = new HashMap<Integer, BigDecimal>();

So entries and values for map is like:
nameOne, 03.03.2015, statisticsOne
nameOne, 03.04.2015, statisticsTwo
nameTwo, 03.02.2014, statisticsThree

etc..
And lets say statisticsOne look like this:
day = 03.03.2015
count = 5
totalTime = 50
avaragesMap = {3:20;5:70}

Now how can I add a row to a Vaadin Table so I see something like this:
nameOne 03.03.2015 5 50 3 20
nameOne 03.03.2015 5 50 5 70

?

A: I would make a wrapper class arround your Map averagesMap structure, which can return something like List
That way you could use the BeanItemContainer to show your content.


text:
Q: Prove that the function $e(a,b)=\frac{d(a,b)}{1+d(a,b)} \ where \ a,b\in X$, is a metric I am looking to prove that the following function from the non empty group $X$ is a metric with $d$ already being a metric:
$$e(a,b)=\frac{d(a,b)}{1+d(a,b)} \ \text{where} \ a,b\in X$$
But I am not sure how to proceed with such equations.
UPDATE:
From the comments posted so far, I interpreted the following:

*

*$$d(a,b) \geq 0$$
$$e(a,b) \geq 0 \implies \frac{d(a,b)}{1+d(a,b)} \implies d(a,b) \geq 0 \Rightarrow \text{true}$$

*$$d(a,b) = 0 \implies \frac{d(a,b)}{1+d(a,b)} = 0\implies d(a,b) = 0 \implies a=b$$

*$$d(a,b)=d(b,a) \implies e(a,b) = e(b,a) \implies \frac{d(a,b)}{1+d(a,b)} = \frac{d(b,a)}{1+d(b,a)}$$

*$$d(a,c) \leq d(a,b) + d(c,d) \implies e(a,c) \leq e(a,b) + e(b,c) \implies \frac{d(a,c)}{1+d(a,c)} \leq \frac{d(a,b)}{1+d(a,b)} + \frac{d(b,c)}{1+d(b,c)}$$
Am I following the right path?

A: You are almost there, but there are some issues about the order you've written things in.

*

*Since $d$ is a metric, $d(a,b)\geq 0$ for all $a,b\in X$. It follows that $1+d(a,b)\geq 1$ and $e(a,b)=\frac{d(a,b)}{1+d(a,b)}\geq 0$ for all $a,b\in X$.

2.
$$e(a,b)=0 \iff d(a,b)=0 \iff a=b$$
where the last equivalence comes from the fact that $d$ is a metric.

*Since $d$ is a metric $d(a,b)=d(b,a)$ for all $a,b\in X$. It follows that $e(a,b)=e(b,a)$ for all $a,b\in X$.

*Lastly, we need to prove that the triangle inequality holds. Take any $a,b,c\in X$. We must show $e(a,b)+e(a,c)\geq e(a,c)$. This is the hard part of this question. There is a nice solution here: If $d$ is a metric, then $d/(1+d)$ is also a metric


text:
Q: i have to calculate a matrix with biopython by aligning sequences taken from a protein I have to calculate a matrix from the alignement of some sequences,which is the library from which I can import the function : MatrixInfo?
with the previous version of biopython (3.7) I have always being using "Bio.SubsMat" as function, now, with the new version (3.8), this function doesn't work anymore.
I tried to use Bio.Align, but the resulting matrices, with global and local values, are exactly the same and they should not.
how can I overcome the problem?


text:
Q: 2.5mm Audio jack to micro USB First of all, just a caveat: I am a complete newbie with electronics, computer software is more my thing!
I have bought a (used) car this morning and it came with an old TrafficMaster Satnav installed which I have now removed. It seems that a power jack has been installed in the dashboard to power it.
I usually have my phone in a dock and run a long micro usb charging cable to a cigarette lighter USB charger so I can charge my phone while driving.
It would be nice to utilise the power jack that has been installed, to charge the phone as it will be a neater solution than running the long USB cable.
The old Trafficmaster is powered through a 2.5mm audio jack, the other end is moulded to the unit. Therefore the power jack installed in the car is the female end. This all works and the Trafficmaster recieves power.
The TrafficMaster is pictured here
What I want to do if possible is make a cable that has the 2.5mm jack at one end and a micro USB on the other.
Is it possible to take a spare USB charging cable cut the micro USB off, cut the 2.5mm off the trafficmaster and solder the ground USB wire to the ground audio jack wire and the 5V USB wire to the 5V wire in the 2.5mm connector? (Is there one!?)

A: "2.5 mm jack" is a mechanical spec.  You also need the electrical spec.  What voltage does this jack provide?  At what maximum current?  Is it a regulated and de-glitched 5 V?  A direct connection to the car 12 V system?  Something else?
Measure what power comes out.  Only then can you decide what needs to be electrically between this jack and a USB charger output.  If the jack provides 5 V, then maybe you can just connect them directly.  If 12 V, then you have to assume all the nasty spikes on the car 12 V system come along with it.  You could then hack up the same charger you now plug into a cigarette lighter outlet to plug into this jack instead.

A: You'll have to figure out the pinout of that 2.5mm connector, it's impossible to guess for us here. Measure the voltages between the different rings? Does one give something like a stable 12V, 5V or so?
Note that you probably do not want to use some old car nav supply to charge your devices. Modern smart phones can draw multiple Amperes, and there's so far no reason to assume that

*

*there's a DC/DC converter built into your dashboard and that instead of the car-typical 12V, you get 5V on that connector,

*that if there is such a DC/DC converter built into the dashboard, it will give you exactly 5V,

*that if it exists and gives you 5V, it will be powerful enough to charge a modern phone (which will probably draw a lot more current when charging than some old-school car nav).

So, while if you're already measuring, sure, look for 5V between any of the rings on the converter, then connect a 5V/2A = 2.5Ω resistor and see how much that voltage drops if you draw a 2A charging current. But: If you'd start by walking into a store, buying a multimeter, trying to grab a lot of resistors to put in parallel so that you can even have such a dummy load: forget about it.

A: Not likely directly possible. The jack for the traffic master most likely puts out +12V to match the vehicle power system. The micro USB to your phone is 5V.
Note also that cigarette lighter phone chargers have an internal DC-DC converter that converts vehicle +12V to 5V.


text:
Q: How do I make my widget update more frequently or update when an action happens within the app I have a widget that fetches data from my app. The widget works fine but doesn't update frequently enough. Ideally, id like it to update anytime an item is deleted or added in my app so if there is a way to force the widget to update, that works. Otherwise if the widget could just fetch new data more frequently then that works fine too.
The data is stored in a json file in an app group. I load and decode that data into an array and then choose a random item from that array to display.
Here's the widget Provider:
let testBook = Book(id: UUID(), name: "Name", author: "Author", genre: "Error", page: "0", total: "77")

public enum AppGroup: String {
  case Livre = "group.com.identifier"

  public var containerURL: URL {
    switch self {
    case .Livre:
      return FileManager.default.containerURL(
      forSecurityApplicationGroupIdentifier: self.rawValue)!
    }
  }
}

struct Provider: TimelineProvider {
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date(), book: testBook)
    }

    func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date(), book: testBook)
        completion(entry)
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        var entries: [SimpleEntry] = []

        let currentDate = Date()
        for hourOffset in 0 ..< 5 {
            let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
            let books: [Book] = self.load("list")
            let entry = SimpleEntry(date: entryDate, book: books.randomElement() ?? testBook)
            entries.append(entry)
        }

        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)

    }

    func load<T: Decodable>(_ filename: String) -> T {
        let groupDirectory = AppGroup.Livre.containerURL
        let groupURL = groupDirectory
            .appendingPathComponent(filename)
            .appendingPathExtension("json")

        return try! JSONDecoder().decode(T.self, from: Data(contentsOf: groupURL))
    }
}

As I am new to widgetKit, im not sure if I've provided enough context, please tell me if you require anymore information or code.

A: You can always update your widget from your app with the code block below. Please be aware you need to import WidgetKit to your class for calling this function.
WidgetCenter.shared.reloadAllTimelines()


text:
Q: An exercise about superdense coding My question is second part of exercise 2.70 page 98 of the book Quantum Computation and Quantum Information written by Michael A. Nielsen and Isaac L. Chuang.
Assume Bob and Alice share each one qubit of the entangled state $$|\psi\rangle=\dfrac{|00\rangle+|11\rangle}{\sqrt{2}}$$
Alice for sending a 2-bits data operate one of the Pauli single-qubit gets on her qubit then sends her qubit to Bob, then bob with a projective measurement find out what was the message of Alice with their pre-agreement as follow.
$$\begin{array}{l}
00\;:\;\dfrac{|00\rangle+|11\rangle}{\sqrt{2}}\\
01\;:\;\dfrac{|00\rangle-|11\rangle}{\sqrt{2}}\\
10\;:\;\dfrac{|01\rangle+|10\rangle}{\sqrt{2}}\\
11\;:\;\dfrac{|01\rangle-|10\rangle}{\sqrt{2}}
\end{array}$$
The exercise says;

Exercise 2.70: Suppose $E$ is any positive operator acting on Alice's qubit. Show that $\langle \psi|E\otimes I|\psi\rangle$ takes the same value when $|\psi\rangle$ is any of the four Bell states.
Suppose some malevolent third party ('Eve') intercepts Alice's qubit on the way to Bob in the superdense coding protocol. Can Eve infer anything about which of the four possible bit strings $00,\,01,\,10,\,11$ Alice is trying to send? If so, how, or if not, why not?

I did the first part and actually that same value is $\frac{1}{2}tr(E)$. It's obvious or at least I think, I have to use the first part of the question for rejecting that Eve can understand anything but I don't know how.

A: You've yourself said that the expectation value of Eve's operator does not depend on what Alice is trying to send, so you're most of the way there.
What's the reduced density operator for half of a maximally entangled Bell state? Does it depend on which Bell state it is made from?


text:
Q: Compatibilidad con Firefox e IE con el objeto Date() - JavaScript Quería pediros ayuda con un código de Javascript de un reloj cuenta atrás, con el objeto date, que me da problemas retornando NAN con dos navegadores, con IE y con Firefox, (con Safari también me daba, pero pude solucionarlo); Muchas gracias por adelantado!

const second = 1000,
      minute = 1000 * 60,
      hour = 60000 * 60,
      day = hour * 24;

let countDown = new Date('Jan 01, 2020 00:00:00'.replace(/\s/, 'T')).getTime(),

w = setInterval(function() {
    let now = new Date().getTime(),
    distance = countDown - now;

    document.getElementById('days').innerText = Math.floor((distance / (day))),
    document.getElementById('hours').innerText = Math.floor((distance % (day)) / (hour)),
    document.getElementById('seconds').innerText = Math.floor((distance % (minute)) / second);

}, second);

cuenta atras

Days

Hours

Seconds


text:
Q: TableView makes multiple copies of same label, swift For some reason, my cell titles keep duplicating. Here's the code:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! ContactsTableViewCell

    // Configure the cell...
    cell.contactNumberLabel.text = allNumbers[indexPath.row]

    // App downloads confirmedContactList from server
    // Before data is downloaded confirmedContactList is empty and 'for in' loop crashes app.
    if confirmedContactList != new {

        // Title should appear only in cells where arrays allNumbers and confirmedContactList are identical
        for n in 0..<self.allNumbers.count {
            for k in 0..<self.confirmedContactList.count {
                if self.allNumbers[n] == self.confirmedContactList[k]{
                    cell.nameLabel.text = "This Title Keeps Duplicating"
                }
            }
        }
    }
    return cell
}

Basically, there are two arrays containing telephone numbers, if contact number displayed in cell exist in confirmedContactList then cell.nameLabel should say something specific.

A: When the cellForRowAtIndexPath method is called for already displayed indexPaths, the nameLabel text is not set to a default value.
If the previously used value passed the confirmedContactList test, then you will see the title even if the new value doesn't pass the test.
Just add a line and you'll be fine :
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! ContactsTableViewCell

    // Configure the cell...
    cell.contactNumberLabel.text = allNumbers[indexPath.row]

    // reset the label
    cell.nameLabel.text = ""

    // App downloads confirmedContactList from server
    // Before data is downloaded confirmedContactList is empty and 'for in' loop crashes app.
    if confirmedContactList != new {

        // Title should appear only in cells where arrays allNumbers and     confirmedContactList are identical
        for n in 0..<self.allNumbers.count {
            for k in 0..<self.confirmedContactList.count {
                if self.allNumbers[n] == self.confirmedContactList[k]{
                    cell.nameLabel.text = "This Title Keeps Duplicating"
                }
            }
        }
   }
    return cell
}


text:
Q: Publicar una entrada en blogger usando la Api y php Intento enviar un Post a Blogger usando la Api v3 de Blogger Y Php . El código funciona bien pero tengo unas dudas de como actualizar el token  sin dar nuevamente permisos pensé que con esta parte:
$client->setAccessType('offline');

No necesitaba actualizarlo.
Otra duda es por que no puedo enviar una imagen usando esta manera :
$post->setimages(array("url"=>"https://image.freepik.com/vector-gratis/casa-dos-pisos_1308-16176.jpg"));

No aparece la imagen publicada .
Segun este enlace Posts: insert esa es la manera o eso entiendo .
Les dejo el código completo para que puedan entender y ayudarme .
    require_once __DIR__.'/vendor/autoload.php';

    $scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];

    $client = new Google_Client();
    $client->setApplicationName('B'); //name of the application
    $client->setAuthConfig('client_secret.json');
    $client->setRedirectUri($scriptUri); //redirects to same url
    $client->setApprovalPrompt("force");
    $client->setAccessType('offline'); // default: offline
    $client->setApprovalPrompt("consent");
    $client->addScope(Google_Service_Blogger::BLOGGER);
    $client->setIncludeGrantedScopes(true); // incremental auth
    $guzzleClient = new \GuzzleHttp\Client(array('curl' => array(CURLOPT_SSL_VERIFYPEER => false)));
    $client->setHttpClient($guzzleClient);

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
//authenticate using the parameter $_GET['code'] you got from google server
$client->authenticate($_GET['code']);

//get the access token
$tokens = $client->getAccessToken();
file_put_contents(__DIR__."/Data/token.json", $tokens);
}

    $service = new Google_Service_Blogger($client);
    $blog = $service->blogs->getByUrl('http://Miblog.mx/');
    //this is part for sending post into blogger, which is getting
    //error
    $post = new Google_Service_Blogger_Post();
    $post->setTitle('poner imagen 3');
    $post->setImages(array("url"=>"https://image.freepik.com/vector-gratis/casa-dos-pisos_1308-16176.jpg"));
    $post->setLabels(array('Label1', 'Label2'));
    $post->setContent("plantilla.html");
    $service->posts->insert('203422', $post);

Esta parte tampoco funciona como yo espero.
$post->setContent("plantilla.html");

No publica el html de "plantilla.html" y no se por que o como se logra
y e buscado en Internet y no hay mucha información en español

A: Voy a responder cada una de las preguntas en un apartado.
Con setAccessType('offline') no necesito actualizar el token
Estamos tratando con tokens OAuth, por lo que tal y como puede leerse en la documentación, el modo offline permite que la aplicación refresque el token sin interacción con el usuario: sin necesidad de que el usuario esté presente en un navegador o deba validar de nuevo los permisos.
Pero los tokens siempre tienen un tiempo de expiración e incluso un tiempo de renovación máximo. Con esa opción delegas el trabajo el cliente PHP, pero si se superan los plazos de renovación del token se deberá solicitar el acceso al usuario de nuevo.
Un procedimiento de refresco del token puedes verlo en cualquier ejemplo del repositorio php-samples. Muestro el ejemplo del acceso al calendario:
/* Archivo que guardará el token para sucesivas ejecuciones */
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
    /* Cargamos los datos del archivo */
    $accessToken = json_decode(file_get_contents($tokenPath), true);
    /* Lo cargamos en el cliente de Google */
    $client->setAccessToken($accessToken);
}

/* Si no había token o está expirado */
if ($client->isAccessTokenExpired()) {
    /* Refrescamos el token si es posible, o solicitamos uno nuevo */
    if ($client->getRefreshToken()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    } else {
        /* Si no se pudo renovar el token solicitamos una nueva autorización al usuario */
    }
    /* Guardamos el token en el archivo */
    if (!file_exists(dirname($tokenPath))) {
        mkdir(dirname($tokenPath), 0700, true);
    }
    file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}

Otra duda es por que no puedo enviar una imagen usando esta manera
He probado el API de Blogger y no es posible agregar una imagen a un post, ni externo (como el que indicaste) ni previamente cargado con la herramienta de subida de imágenes (las URLs comienzan por https://4.bp.blogspot.com/) ni desde el álbum personal del autor del post (las URLs comienzan por https://lh3.googleusercontent.com/).
Aunque en la documentación pone:

*

*images[] (list): Display image for the Post.

*images[].url (string)

En la práctica, incluso haciendo uso de la función Try this API, no he sido capaz de insertar ninguna imagen como imagen para mostrar (aunque sí he podido poner una imagen para mostrar agregando una imagen dentro del contenido) y no he podido obtener ningún resultado de búsqueda con el índice images exceptuando en el icono del usuario autor de un post o un comentario.
Creo que este campo se usa cuando se consulta un dato de una publicación que sí que tiene imagen para mostrar, no para cambiar la imagen para mostrar a la que deseemos.
$post->setContent("plantilla.html") no funciona como espero
Esta parte es la más sencilla de aclarar. El parámetro de la función es el contenido de la publicación, no un archivo que contenga el contenido de la publicación.
De modo que debes cargar el contenido del archivo haciendo uso de, por ejemplo, file_get_contents():
$post->setContent(file_get_contents("plantilla.html"));


text:
Q: Does intercepting and replaying all system calls suffice to ensure deterministic program behavior? On GNU/Linux it is possible to intercept all system calls of a program and its children using ptrace(2). Typical software will rely exclusively on system calls to interact with other software.
What are the possible sources of non-determinism a program can utilize that do not involve system calls? And are they commonly used?
Typically, if I wanted to develop a universal caching mechanism which keeps track of all system calls of a program and its sub-processes, and I were to simply replay them, checking those calls return the exact same result (if not, I fallback to actually running the program), would that always behave perfectly as the genuine program?
More practically, if I relax some of the calls to allow for different behavior (typically, brk and mmap tend to choose different addresses and getpid return different process id, but they don't really affect program behavior much) are there commonly used programs that would break those expectations? (typically, I assume build tools tend to be rather deterministic)
Is there such an implementation of universal caching mechanism out there?


text:
Q: WPF using a view to change the parents atributes My program has several views that are controlled using a Hamburger menu. Inside one of these views i have made a toggle switch to change between fullscreen and windowed. The only problem is that to do this i need to change the Mainwindow.xaml from within the view. The mainwindow is a "MetroWindow"
I have tried adapting the following:
 Window parent = Window.GetWindow(this);

This works fine but when i want to use a metro specific attribute:
Parent.IgnoreTaskbarOnMaximize = true;

It obviously doesn't contain a reference as its not a window its a metrowindow. I changed the code to a metrowindow but that wont work as it cant convert from windows.window to mahapps.metro.controls.metrowindow.
 MetroWindow metroParent = MetroWindow.GetWindow(this);

Is there anyway i can do this or run code from the mainwindow code within my view ?

A: Cast the result:
MetroWindow parent = Window.GetWindow(this) as MetroWindow;


text:
Q: agm-snazzy-info-window for Angular 4 on Map Load without the marker I want to load a snazzy-info-window on Map load , and dont want it to be associated with any marker or marker click ( more like need the snazzy-info-window to display information for a location at the load of the map itself). Can someone please suggest how to do it. I have used the following code, but it does not display the info window
<agm-map [latitude] = "lat" [longitude]="lng" [zoom] = "zoom">
<!-- <agm-marker [latitude]="lat" [longitude]="lng" label = "MARK"></agm-marker> -->
<agm-snazzy-info-window [maxWidth]="200" [closeWhenOthersOpen]="true">
<ng-template>
My first Snazzy Info Window!
</ng-template>
</agm-snazzy-info-window>
</agm-map>

A: you can do it like it says on their website:
Snazzy Info Window & Angular Google Maps website


text:
Q: Optimal Oracle SQL Query to complete group-by on multiple columns in single table containing ~ 7,000,000 records I am a SQL Novice in need of some advice. What is the most efficient (fastest running query) way to do the following-
Select all columns from a table after-
-Performing a "Group By" based on the unique values contained in two columns: "top_line_id" and "external_reference".
-Selecting a single record from each group based on the max or min value (doesn't matter which one) contained in a different field such as support_id.
Someone on my team provided the below query, but I can't seem to get it working. I receive an error message stating "invalid relational operator" when I attempt to execute it.
Select *
from STAGE.SFS_GH_R3_IB_ENTLMNT_CONTACTS
Where support_id, external_reference, top_line_id in (
         select max(support_id),
                external_reference,
                top_line_id from STAGE.SFS_GH_R3_IB_ENTLMNT_CONTACTS
)

One more thing - the columns on which we are performing the Group By contain null values in some records. We would like those excluded from the query.
Any assistance you can provide is very much appreciated.

A: Although you phrase this as a group by query, there is another approach using row_number().  This enumerates each row in the group, based on the "order by" clause.  In the following query, it enumerates each group based on external_reference and top_line_id, ordered by support_id:
select *
from (Select t.*,
             row_number() over (partition by external_reference, top_line_id
                                order by support_id) as seqnum
      from STAGE.SFS_GH_R3_IB_ENTLMNT_CONTACTS t
     )
where seqnum = 1

A: This should work(can't test it)

SELECT
  *
FROM
  stage.sfs_gh_r3_ib_entlmnt_contacts
WHERE
  (support_id, external_reference, top_line_id) IN
    (
      SELECT
        max(support_id),
        external_reference,
        top_line_id
      FROM
        stage.sfs_gh_r3_ib_entlmnt_contacts
      WHERE
        external_reference IS NOT NULL AND
        top_line_id IS NOT NULL
      GROUP BY
        top_line_id, external_reference
    )


text:
Q: Creating a testing script which 'skips' file uploads I am creating a testing script for my team. So far it works fine - it goes to the login form and attempts to login using the details you entered, if that fails it goes to a job description and attempts to apply for a job, selecting a random answer for each screening question until it gets to the actual application form. Unfortunately the application form includes a file upload control, which I don't appear to be able to skip over. Does anyone have any idea if I could actually skip over it or somehow click it? I am using FF7 and from previous posts I can see that apparently FF4 does it - but FF7 doesn't appear to make file uploads clickable through JS.... any ideas? Thanks in advance.
Regards,
Richard

A: Javascript can't access file upload inputs for security reasons (e.g. prevent malicious upload of user's files). For this kind of testing you should use a browser automation tool like Selenium http://seleniumhq.org/ (or in web service form https://saucelabs.com/).


text:
Q: Wash your hands before you go to sleep. (sleep is a noun or a verb?)
Wash your hands before you go to sleep.

'sleep' is a noun or a verb in the sentence above? (In other words, the 'to' is a preposition or an infinitive?)


text:
Q: Create a shortcut to a folder on the desktop 13.04 I am looking to create a shortcut either in the explorer or on my desktop to the /host/users/Harry/ folder so I can access my windows partition easily, it is a hassle to go through the filesystem each time

A: Open files, right click the folder that you want, and click on Make Link,

once done, move the newly created link to the desktop

A: Open the explorer and browse to the folder you want to bookmark (/host/users/Harry/). Press Ctrl+D to bookmark the folder. It will show up in the left pane of the explorer.
P.S. In Ubuntu, the explorer is called Nautilus.


text:
Q: How can I map an SQL Server geometry column to an EF6 property I have a nullable geography column in a table in a SQL Server database. In an Azure Function project (v4, .NET 6.08, NetTopologySuite included), when using Scaffold-DbContext to create an EF6 data context, the geometry column was mapped to Geometry? which seems right.
But when I run the project, and initialize the DBContext, I get the following error:

The property 'Geometry.UserData' could not be mapped because it is of type 'object', which is not a supported primitive type or a valid entity type.

BTW, I tried to change Geometry? to Point? but this made no difference.
What is going on? How can I map a Geography column to an EF6 property?

A: You must configure the SQL Server provider options by enabling support for spatial type mappings with "UseNetTopologySuite":
options.UseSqlServer(
    @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=WideWorldImporters",
        x => x.UseNetTopologySuite());


text:
Q: MYSQL priority or rank based values exchange inside a group I am trying to figure out how to write a functiom, which would run trough my dataset and fullfill several conditions.
Here is a quick look at the dataset

We have same Items with different quantities on different locations with different priorities.
The trick is to find a location with the lowest priority and add that quantity or just 1 to the location with the highest priority for the same item. Then move on the the second lowest priority and add that to the second largest and so on untill all pairs in the same item_no group are done, and if there is an uneven number of locations leave the last one allone, move on to the next item__no.
Priorities go from 1-26 , 1 being the highest and 26 the lowest.
for starters I just wanted to write something that would at least get me the result for the first group.
I have item_no 100115 and to locations P26 and P30, P30 needs to receive that item from P26 because it has a higher priority
The desired output needs to be in the following format
in_location | from_location | item_no | quantity
I wrote this
SELECT in_loc, from_loc, item_no, quantity FROM
(
SELECT
(SELECT Store_no from sep  WHERE Priority = 15) AS in_loc,
Store_no AS from_loc,
Item_no,
Stock_Quantity AS quantity FROM sep
WHERE Item_no = 100115) AS P
WHERE in_loc <> from_loc

which got me the desired result for the first item

I am trying to figure out how to go about the complete function.
Like:
Creating and joining or self joining a copy of the table
where i could say just a.store_no <> b.store_no
Do I need to state cases where one CASE is even number of locations in a Group and the other is uneven.
How do I go about the actual exchange , Do I do a COUNT of the number of locations for all items in a group and divide in pairs, do I pair GREATEST with the LEAST then move on to the second GREATEST or somehow use TOP nad BOTTOM with offset.
Maybe I need to define some local variables?
Edit
Sample table script
CREATE TABLE sep (
    id INT PRIMARY KEY NOT NULL,
    item_no VARCHAR(12),
    store_no VARCHAR(4),
    quantity INT,
    priority INT);

INSERT INTO sep (id, item_no, store_no, quantity, priority)
VALUES
(1, 100115, 'P026', 1, 15),
(2, 100115, 'P030', 1, 19),
(3, 100116, 'P015', 3, 14),
(4, 100116, 'P017', 1, 2),
(5, 100116, 'P002', 1, 11),
(6, 100117, 'P021', 1, 9),
(7, 100117, 'P033', 3, 20),
(8, 100117, 'P008', 1, 22),
(9, 100117, 'P007', 5, 5);

Also script for output if needed
CREATE TABLE output (
    in_location VARCHAR(4),
    from_location VARCHAR(4),
    item_no VARCHAR(12),
    quantity INT);

Update
Thanks for the response, just a little tweak needed with output now.
This is the output from the answer

and I actually need this

Explanation about the output: we are looking at a large retailer, after doing inventory in some store locations it was found that certain items are unpaired when in fact they should be sold in pairs.
If you look at the first image in the post you can see that an item has  an inventory multiple is x2 and quantity on location is 1 or 3 or whatever when in fact it should always be in pair. That is why I am trying to find storre_locations with lower priority which can give at least 1 item  to a store_location with higher priority if they have the same unpaired item...
That's why in my output I need to see that
Pxx(in_location with higher priority) Pxx(from_location with lower priority)
Item_no(which item) quantity(receives how many/ 1 is enough)

A: Does this query gives the output which you need in?
WITH cte AS ( SELECT id, item_no, store_no, quantity, priority,
                     LEAST(ROW_NUMBER() OVER (PARTITION BY item_no ORDER BY priority),
                           1 + COUNT(*) OVER (PARTITION BY item_no) - ROW_NUMBER() OVER (PARTITION BY item_no ORDER BY priority)) pair
               FROM sep )
SELECT id, item_no, store_no, quantity, priority,
       CASE WHEN priority = MIN(priority) OVER (PARTITION BY item_no, pair)
            THEN quantity + 1
            ELSE quantity - 1
            END new_quantity
FROM cte
ORDER BY item_no, priority

fiddle


text:
Q: Receiving strange values to kafka topic from kura Trying to send data to kafka topic from kura through Mqtt proxy but receiving strange values in kafka topic

we are trying to send json data to kafka topic

A: The MQTT proxy only sends binary data (bytes or strings), and Control Center can only show strings.
You will want to verify the Kafka producer settings to see if it is truly sending JSON, and not other binary format, or compressed/encrypted bytes.
You can further debug with kafka-console-consumer, rather than use any UI tool


text:
Q: cancellation laws in a Ring There's a theorem that states that cancellation laws hold in a ring $R$ if and only if $R$ has no zero divisors. Note that Integral Domains have no zero divisors. However, from my understanding in group theory, cancellation law happens by multiplying the (multiplicative) inverse on both sides, i.e. $$a^{-1}\cdot ab=a^{-1}\cdot ac\implies b=c.$$ Equivalently, $$ba\cdot a^{-1}=ca\cdot a^{-1}\implies b=c.$$ Going back to rings, this feels counterintuitive as this is only possible if all elements have a multiplicative inverse. But take note that Integral Domains are not necessarily division rings. So how does cancellation exactly work in rings?
Our professor said we should not multiply the inverse on both sides since we're not guaranteed that a multiplicative inverse exists for all elements of a ring $R$. So for the rest of the discussion, she only canceled terms without explicitly stating why it happens.

A: Suppose $ab=ac$. This means that
$$a(b-c)=0$$
but if the ring is an integral domain, either $a=0$ or $b-c=0$. If $a\neq0$, this implies that $b=c$.

A: Consider the example of the polynomial ring ${\Bbb R}[x]$. Since it is an integral domain, it holds for a non-zero polynomial $p$ that
$$
pq_1=pq_2\quad\Rightarrow\quad q_1=q_2,
$$
however, an inverse of the polynomial $p$ does not exist.

A: I would like to illustrate that with an example: take for example the integers $modn$ with n composite, then if $n=6$ for example you can see that $2x=0mod6$ does not imply $x=mod6$ but it could also mean $x=3$. This is because you have zero divisors in that ring.

A: For variety....
Every integral domain $D$ has a field of fractions $F$, and $D$ is a subring of $F$. (The general procedure for constructing rings of fractions is called localization)
If $ab = ac$ holds for $a,b,c \in D$, then in $F$ we have $\frac{ab}{1} = \frac{ac}{1}$. If $a \neq 0$, then $\frac{1}{a} \in F$, and multiplying through and applying the fact that $\frac{xy}{x} = \frac{y}{1}$ gives an equation $\frac{b}{1} = \frac{c}{1}$. Since $D$ is a subring of $F$, this implies $b=c$.