text:
Q: How to add text to body of e-mail? I searched StackOverflow and others with no good results.
I have to send e-mails through Access VBA. I'm using Selenium Basic library.
I can, access the e-mail web page, click on the "new mail" button, fill fields "To", "subject", "Copy to" and "blind copy to" if such parameters are given, and click the "send e-mail" button.
I cannot, edit the rich text body of the e-mail. I can send e-mails, but they're blank.
Public Sub sendEmail( _
    emailPage As String, _
    sendTo As String, _
    subject As String, _
    emailText As String, _
    Optional copyTo As String, _
    Optional blindCopyTo As String)

'Parameters above: emailPage is the intranet, corporative e-mail site from which the e-mails must be
'sent; sendTo is the e-mail address to which the e-mail will be sent; subject is the subject of the
'e-mail; emailText is the text that I want to go in the body of the e-mail.

'Variables below: preparing variables to be used, like a webDriver. I tried to mingle Selenium and
'Windows HTML objects to no vail, as one can infer from the commented variable

    Dim browser As WebDriver
    Dim webEle As WebElement
    Dim theKeys As selenium.Keys
    Dim por As By
    'Dim CurrentWindow As HTMLWindowProxy

'choosing the web browser driver. I chose firefox since it went farther than chrome*:

    Set browser = New FirefoxDriver

'with the browser driver, I go to the e-mail webpage:

    With browser
        .Get emailPage

'Below I find the elements with the XPath to interact with

        .SwitchToFrame "s_MainFrame"
        .FindElementByXPath("/html/body/div[2]/div/div[4]/div/div/div[1]/div/div[1]/div/div[3]/div[2]/div[10]/table[1]/tbody/tr/td[2]/table/tbody/tr/td[1]/span").Click
        .FindElementByXPath("/html/body/div[2]/div/div[4]/div/div/div[1]/div/div[1]/div/div[3]/div[1]/div/div[5]/div/form/div/div/div[5]/table[1]/tbody/tr[3]/td[3]/div/textarea").SendKeys sendTo
        If IsMissing(copyTo) = False Then
            .FindElementByXPath("/html/body/div[2]/div/div[4]/div/div/div[1]/div/div[1]/div/div[3]/div[1]/div/div[5]/div/form/div/div/div[5]/table[1]/tbody/tr[4]/td[3]/div/textarea").SendKeys copyTo
        End If
        If IsMissing(blindCopyTo) - False Then
            .FindElementByXPath("/html/body/div[2]/div/div[4]/div/div/div[1]/div/div[1]/div/div[3]/div[1]/div/div[5]/div/form/div/div/div[5]/table[1]/tbody/tr[5]/td[3]/div/textarea").SendKeys blindCopyTo
        End If
        .FindElementByXPath("/html/body/div[2]/div/div[4]/div/div/div[1]/div/div[1]/div/div[3]/div[1]/div/div[5]/div/form/div/div/div[5]/table[1]/tbody/tr[6]/td[3]/div/textarea").SendKeys subject

'And here is the problem: I cannot access the e-mail body text to change it. SendKeys won't work. I also
'tried inserting HTML texts like <HTLM>email text goes here and
'<HTLM>
email text goes here, to no vail.

        .FindElementByXPath("/html/body/div/div").SendKeys emailText
        '.SwitchToFrame "s_MainFrame"

'After that, I click the button to send the e-mail, close the browser driver, and set it to nothing.
        .FindElementByXPath("/html/body/div[2]/div/div[4]/div/div/div[1]/div/div[1]/div/div[3]/div[2]/div[14]/table[1]/tbody/tr/td[1]/span").Click
    End With
    browser.Close
    Set browser = Nothing

End Sub

These are the elements that I get when inspecting the body text. In the first line of the e-mail body text, which is clean, the element is

And its XPath is:
/html/body/div/div

But using it as the path to access is of no use in my tests. Below is the rich text body text element main values:

And it's XPath:
/html/body

In Chrome, I get an error, and it doesn't open the email page. I have the Chrome 87 version and the appropriate driver.

A: Sorry to bother everyone!
I did some more testing and discovered I had to reference the XPath for the iframe:
    .FindElementByXPath("/html/body/div[2]/div/div[4]/div/div/div[1]/div/div[1]/div/div[3]/div[1]/div/div[5]/div/form/div/div/div[2]/div/div/div[1]/iframe").SendKeys emailText

I also updated the function with a While DoEvents to close the browser driver only after the e-mail page writes in the referenced HTML element that the e-mail was sent succesfully:
    Do While InStr(1, browser.FindElementByXPath("/html/body/div[2]/div/div[4]/div/div/div[1]/div/div[2]/div[1]/div/div[2]/div/table[1]/tbody/tr/td[2]/span").text, "Email sent successfully") = 0
        DoEvents
    Loop

Also, some declared variables were unused and were removed, like the webEle. Only the browser variable is declared in the final code.


text:
Q: What are the advantages and disadvantages of cryptographically signing commits and tags in Git? So someone peer reviewed my work, and he told me that I should always sign my commits and tags cryptographically. When asked why, he didn't know to explain it to me, and said "It's just a good thing to do".
Trying to avoid an obvious chimpanzee scenario, why should I really? Are there really so many distinct advantages and no disadvantages?
What are the practical reasons which would make me want to sign every commit and tag I make?

A: (This is largely based on A Git Horror Story: Repository Integrity With Signed Commits—a very good read, and more information than I could put into an answer.)
There are a number of ways in which a git repository can be compromised (this isn't a security flaw, just a fact of life—one should not avoid using git because of this). For example, someone may have pushed to your repository claiming to be you. Or for that matter, someone could have pushed to someone else's repository claiming to be you (someone could push to their own repository claiming to be you too). This is just part of life in a DVCS.
Just as an example:
$ git config --global user.name 'Madara Uchiha'
$ git config --global user.email muchiha@example.com

There, I've changed my git configuration to pretend I'm you. And now I can commit away and let those commits somehow make their way into the production build, and it looks like you've done it.
With signing of the commits (and tags), one can prove that certain commits and tags were from you (and things that aren't signed shouldn't have made it into the production build). That's really the key to it all—by signing commits you've said it's your work.
The "your work" aspect is particularly important in the linux kernel (and thus git) that is occasionally hit with copyright lawsuits. By signing commits you say that you have the right to the software—it tracks the origin. It may be that you've got no access to the source that is being claimed as copyright and the claim is groundless. It may be that the company forgot that you were working for them a few years ago and under their direction added material to the kernel, or whatever.
There is some debate as to if every commit should be signed. From GPG signing for git commit? (back in '09), Linus wrote:

Signing each commit is totally stupid. It just means that you automate it, and you make the signature worth less. It also doesn't add any real value, since the way the git DAG-chain of SHA1's work, you only ever need one signature to make all the commits reachable from that one be effectively covered by that one. So signing each commit is simply missing the point.

Much more about the thoughts on signing in git can be read there too.
That said, it made its way into git anyways.
There seems to be a majority consensus that signing commits is unnecessary, but signing tags is very good. That blog post linked at the top suggests that one should sign everything anyways. As I said, there's some debate about if every commit is necessary or not.
The key to the "sign every commit" debate probably has to do with the workflow you use. Most people make a bunch of commits in their local repo, and then push that set. It should be sufficient to tag the final collection (assuming, that is, you make sure that all the changes are correct). If you are working in an environment where lots of single commits are moving around, the distinction between a tag and a commit becomes less… distinct—and signing commits may become more useful.

redpajama_set_name: RedPajamaStackExchange


text:
Q: mysql deleting duplicates from table I can find the duplicates by :
select id,date,count(*) as rep,comment
     from New_opinion group by comment,
     Date,company_id having rep>1;

I believe this gives me one record in the group of duplicates that are matched by the same comment, Date and company_id which is close but only shows one of the matching duplicates.
I'd like to select all but one of the duplicates and delete them.
id is a primary key
I've worked on this for hours, and keep getting errors about operands need 1 columns, or deleting a non key, etc. Please help, the other delete answers don't seem to be working.

A: Try this...
DELETE FROM New_opinion n WHERE n.comment,n.Date,n.company_id
IN(
    SELECT temp.comment,temp.Date,temp.company_id FROM
    (SELECT comment,Date,company_id, id,date,count(*) AS rep,comment
     FROM New_opinion
     GROUP BY comment,Date,company_id
     HAVING rep>1 ) temp);

I hope this will work..

A: Your comment group has multiple ids, which is why you can't use them for a DELETE.
Try a GROUP_CONCAT(id) in the field list to see the list of id numbers.
Not enough for the group contents to be similar - its only a useful group in terms of those fields if every field is identical which given the presence of a primary key it won't be.

A: Try this to keep the row with lowest id
DELETE r1 FROM tableName r1, tableName r2 WHERE r1.id > r2.id AND r1.x = r2.x

To keep the row with highest id just change
WHERE r1.id < r2.id

A: say you have three duplicates for company SMITH & SON, does it matter which of those rows is kept? if it does (say the newest one per company by date) then you might want to select those to a new table, then truncate the old table and then copy the values from the new table back to the old table and then add a unique index across those columns. if it doesn't matter which are kept but just one of each then you can add the index immediately, telling it to ignore the table, and that will immediately drop the duplicates leaving one random row for each company where duplicates happen. The latter like this:
ALTER IGNORE TABLE yourtablename ADD UNIQUE companyid, date, comment

if you need the latest per date in case of duplicates for each company, see the tutorial in the manual under GROUPWISE MAXIMUM


text:
Q: BigQuery: Search for all elements matching in subquery Given data: table1
        column 1 column 2 column 3
Row1    k1       k2       k3
Row2    k1       k4       k3
Row3    k1       k2       k3

I want to select all rows which is matching keys in rows returned in subquery.
select *
from tabl1
where Exists(select *
             from table1
             where column2 = k2)

Should return rows with (k1       k2       k3). Is this correct approach? Why would we use Exists() rather than In() subquery expression?
Note: This question is simple version where in real life, I am matching against many rows (TBs) returned by subquery against many rows (TBs) returned by outer query


text: Q: Number Theory Transform recursive algorithm I was studying the Fast Fourier transform and Number theory Transform, I fully understood the FFT recursive code, I need NTT code to work with, but everywhere I see, its iterative code, but for learning purpose I need the recursive code of it.


text:
Q: Deformations and blow-down I would like to understand how blowing down affects (first order) deformations.
For a concrete example, set $D=k[\epsilon]/(\epsilon^2)$ and consider in $\mathbb{A}^2_D=\operatorname{Spec} D[x,y]$ the following deformation of the two coordinate axis and the line $y=1$:
$$X=\operatorname{Spec} D[x,y]/(xy-a\epsilon)\cap(x(y-1)-b\epsilon)$$ for $a,b\in k$.
Now blow down the $y$-axis. In other words, consider the map to $\text k[u,v]/(uv)$ given by $$(t,0)\mapsto (t,0), (t,1)\mapsto (0,t), (0,t)\mapsto (0,0)$$ which, if I am correct, should be given by $$u\mapsto x(y-1),v\mapsto xy$$ (or maybe the other way around, doesn't matter).
Now it is clear that $uv-\epsilon(au+bv)$ (again, maybe I switched $a$ and $b$) maps to $0$, so the structure at the node is $$D[u,v]/(uv-\epsilon(au+bv))$$ whose completion is $D[[u,v]]/(uv)$ (only constant term matters, and here it is $0$), so it is a trivial deformation.
I would have expected something like $D[[u,v]]/(uv-\epsilon(a+b))$... what did I do wrong? Do really all deformations blow down to the trivial one?
Note: I carried out the same computation in the case of the disjoint union of two nodes mapping to a node collapsing one component from each node. The result seems to still be the same.


text:
Q: how to get default store view label on magento I have this code:
$options = ($_Item->getProductOptions());

How I can have the default view label name of the option and not of the translated store view one?
Thanks.

A: this particular code depends on the class of the $item object.
Theoretically, you would get the default view label by loading the product in admin store:
Mage::getModel('catalog/product')->setStoreId(0)->load(PRODUCT_ID);
In your case, it might be something close to:

$productId = $item->getProductId();
$product = Mage::getModel('catalog/product')->setStoreId(0)->load($productId);
$label = $product->getName();
setStoreId(0) before loading the object is the key component.


text:
Q: Retaining rows that have percent overlapping ranges in Pandas I have a dataframe with the columns:
[id, range_start, range_stop, score]

If two rows have a range overlap by x percentage I retain the row with the higher score. However, I am confused how to pull out rows with no overlap to other ranges. I am using a nested loop and recursion to condense overlapping ranges into a new dataframe. However, this structure causes all rows to be retained when I am looking for the non overlapping rows.
## This is my function to recursively select the highest scoring overlapping regions

def overlap_retention(df_overlap, threshold, df_nonoverlap=None):
     if df_nonoverlap != None:
          df_nonoverlap = pd.DataFrame()

     df_overlap = pd.DataFrame()

     for index, row in x.iterrows():
          rs = row['range_start']
          re = row['range_end']

          ## Silly nested loop to compare ranges between all rows
          for index2, row2 in x.drop(index).iterrows():
               rs2 = row2['range_start']
               re2 = row2['range_end']
               readRegion=[*range(rs,re,1)]
               refRegion=[*range(rs2,re2,1)]
               regionUnion = set(readRegion).intersection(set(refRegion))
               overlap_length = len(regionUnion)

               overlap_min = min(rs, rs2)
               overlap_max = max(re, re2)
               overlap_full_range = overlap_max-overlap_min

               overlap_percentage = (overlap_length/overlap_full_range)*100

               ## Check if they overlap by x_percentage and retain the higher score
               if overlap_percentage>x_percentage:
                    evalue = row['score']
                    evalue_2 = row2['score']

                    if evalue_2 > evalue:
                          df_overlap = df_overlap.append(row2)
                    else:
                         df_overlap = df_overlap.append(row)
#----------------------------------------------------------
                ## How to find non-overlapping rows without pulling everything?
               else:
                    df_nonoverlap = df_nonoverlap.append(row)
# ---------------------------------------------

          ### Recursion here to condense overlapped list further
          if len(df_overlap)>1:
              overlap_retention(df_overlap, threshold, df_nonoverlap)
          else:
              return(df_nonoverlap)

An example input is below:
data = {'id':['id1', 'id2', 'id3', 'id4', 'id5', 'id6'],
       'range_start':[1,12,11,1,20, 10],
       'range_end':[4,15,15,6,23,16],
       'score':[3,1,8,2,5,1]}
input = pd.DataFrame(data, columns=['id', 'range_start', 'range_end', 'score'])

The desired output can change based on the overlap threshold. In the example above id1 and id4 may both be retained or simply id1 depending on the overlap threshold:
data = {'id':['id1', 'id3', 'id5'],
       'range_start':[1,11,20],
       'range_end':[4,15,23],
       'score':[3,8,5]}
output = pd.DataFrame(data, columns=['id', 'range_start', 'range_end', 'score'])

A: You can make a cartesian join between all the ranges, then find length and % of the overlap for each pair, and filter it based on the x_overlap threshold.
After that, for each range we can find the overlapping range with the highest score (which could be the range itself, with the overlap of 100%):
# set min overlap parameter
x_overlap = 0.5

# cartesian join all ranges
z = df.assign(k=1).merge(
    df.assign(k=1), on='k', suffixes=['_1', '_2'])

# find lengths of overlaps
z['len_overlap'] = (
    z[['range_end_1', 'range_end_2']].min(axis=1) -
    z[['range_start_1', 'range_start_2']].max(axis=1)).clip(0)

# we're only interested in cases where ranges overlap, so the total
# range is the range between min(start1, start2) and max(end1, end2)
z['len_total'] = (
    z[['range_end_1', 'range_end_2']].max(axis=1) -
    z[['range_start_1', 'range_start_2']].min(axis=1)).clip(0)

# find % overlap and filter out pairs above threshold
# these include 'pairs' where a range is paired to itself
z['pct_overlap'] = z['len_overlap'] / z['len_total']
z = z[z['pct_overlap'] > x_overlap]

# for each range find an overlapping range with the highest score
# (could be the range itself)
z = z.sort_values('score_2').groupby('id_1')['id_2'].last()

# filter the inputs
df_out = df[df['id'].isin(z)]

df_out

Output:
    id  range_start  range_end  score
0  id1            1          4      3
2  id3           11         15      8
4  id5           20         23      5

P.S. Please note that it is not very clear what should happen with id4 in your example. Since you don't have it in your output, I assumed (hopefully correctly) that you're not interested in zero-length ranges in the output
P.P.S. There is a new syntax for cartesian join in pandas 1.2.0+ with how=cross parameter in the merge method. I've used in my answer a version with a dummy variable k=1, which is more verbose, but compatible with older versions

A: I think you need a very clear definition of overlap. If you have [2;7], [6;10] and [7;8], which one overlaps with which one ?
Avoid using input as a variable name, it shadows the function input() (to get input from the user)
If you want to select clear overlaps (only the start or the end differs), and you only have at most ONE overlap, here you go:
sorted_df = df.sort_values(by=["range_start"])
starts_earlier = sorted_df[sorted_df.range_end.shift(-1) == sorted_df.range_end]

sorted_df = df.sort_values(by=["range_end"])
ends_earlier = sorted_df[sorted_df.range_start.shift(-1) == sorted_df.range_start]

Then you can do a df.drop(starts_earlier.index) and df.drop(ends_earlier.index) to remove the shorter ones/
df.shift() : https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.shift.html
This code won't work for multiple overlapping segments. If you are interested in that, let me know.


text:
Q: Django equivalent to Rails application_controller In Rails, I used the application_controller to control things like user sessions, and create objects to populate parts of the site like the menu.
How should this be done in Django, since there is no kind of "application view"? Do you have to use custom filters and partial templates to be included, for instance in the base template to do this?
I have also been looking at class-based views, but am unsure if that is it.

A: There are several ways to accomplish this:

*

*Template Tags

*Context Processors

*Class Based Views

*Middleware

It just depends on what you're needing to do. request.user is always present in the request object, even if it's an anonymous user, so you don't have to do anything special to access that object from within a template or server-side code.
Inclusion tags are as close as you'll get to render partial in Rails.
Signals and Class-Based views are close to what you'd find in controller filters.
One of the books I found most helpful when learning Django (I went to Django from Rails) was Practical Django Projects. The Definitive Guide to Django is also available for free.


text:
Q: How to filter list with bloc? So, here is bloc (ref https://bloclibrary.dev/#/flutterinfinitelisttutorial)
class ProductBloc extends Bloc<ProductsEvent, ProductsState> {
  String categoryId, userId;
  int limit, offset, type;
  http.Client client;

  ProductBloc(
      {@required this.client,
      @required this.categoryId,
      @required this.userId,
      @required this.limit,
      @required this.offset,
      @required this.type});

  @override
  ProductsState get initialState => InitialProductsState();

  @override
  Stream<ProductsState> mapEventToState(ProductsEvent event) async* {
    final currentState = state;
    print(event);
    print(state);
    if (event is FetchProductsEvent && !_hasReachedMax(currentState)) {
      String categoryId = event.categoryId;
      try {
        if (currentState is InitialProductsState) {
          final posts = await _fetchProducts(categoryId, 0, 3);
          yield ProductsLoaded(product: posts, hasReachedMax: false);
          return;
        }

        if (currentState is ProductsLoaded) {
          final posts =
              await _fetchProducts(categoryId, currentState.product.length, 6);
          yield posts.isEmpty
              ? currentState.copyWith(hasReachedMax: true)
              : ProductsLoaded(
                  product: currentState.product + posts,
                  hasReachedMax: false,
                );
        }
      } catch (e) {
        print(e.toString());
        yield ProductsError();
      }
    }
  }

  bool _hasReachedMax(ProductsState state) =>
      state is ProductsLoaded && state.hasReachedMax;

  Future<List<Products>> _fetchProducts(
      String categoryId, int startIndex, int limit) async {
    final response = await http.Client().post(Configuration.url +
        'api/getProductsTest/$categoryId/$startIndex/$limit');
    if (response.statusCode == 200) {
      List<dynamic> responseData = jsonDecode(response.body);
      final List<Products> products = [];
      responseData.forEach((singleProduct) {
        products.add(Products(
            productId: singleProduct['productId'],
            productName: singleProduct['productName'],
            isNew: singleProduct['isNew'],
            isHot: singleProduct['isHot'],
            productImage: singleProduct['productImage'],
            categoryId: singleProduct['categoryId'],
            productPrice: singleProduct['productPrice'],
            productDescription: singleProduct['productDescription'],
            isLiked: singleProduct['isLiked'],
            productColorId: singleProduct['productColorId'],
            image1: singleProduct['image1'],
            image2: singleProduct['image2'],
            image3: singleProduct['image3'],
            childCategoryId: singleProduct['childCategoryId']));
      });
      return products;
    } else {
      throw Exception('error fetching posts');
    }
  }
}

It is working fine, now i want to adding filter item, so i create new event
class FilterProductEvent extends ProductsEvent {
  String childCategoryId, categoryId;
  FilterProductEvent({this.childCategoryId,@required this.categoryId});

  @override
  List<Object> get props => null;
}

then i create new state
class ProductsFiltered extends ProductsState {
  final List<Products> product;
  final bool hasReachedMax;
  final String filter;

  const ProductsFiltered({
    this.product,
    this.hasReachedMax,
    this.filter
  });

  ProductsFiltered copyWith({
    List<Products> product,
    bool hasReachedMax,
  }) {

    return ProductsFiltered(
      product: product ?? this.product,
      hasReachedMax: hasReachedMax ?? this.hasReachedMax,
    );
  }

  @override
  List<Object> get props => [product, hasReachedMax];

  @override
  String toString() =>
      'PostLoaded { product: ${product.length}, hasReachedMax: $hasReachedMax }';
}

and inside mapEventToState i adding condition
@override
  Stream<ProductsState> mapEventToState(ProductsEvent event) async* {
    final currentState = state;
    print(event);
    print(state);
    if (event is FetchProductsEvent && !_hasReachedMax(currentState)) {
      String categoryId = event.categoryId;
      try {
        if (currentState is InitialProductsState) {
          final posts = await _fetchProducts(categoryId, 0, 3);
          yield ProductsLoaded(product: posts, hasReachedMax: false);
          return;
        }

        if (currentState is ProductsLoaded) {
          final posts =
              await _fetchProducts(categoryId, currentState.product.length, 6);
          yield posts.isEmpty
              ? currentState.copyWith(hasReachedMax: true)
              : ProductsLoaded(
                  product: currentState.product + posts,
                  hasReachedMax: false,
                );
        }
      } catch (e) {
        print(e.toString());
        yield ProductsError();
      }
    }
    else if (event is FilterProductEvent && !_hasReachedMax(currentState)) {
      String categoryId = event.categoryId;
      String childCategoryId = event.childCategoryId;
      try {
        if (currentState is InitialProductsState) {
          var posts = await _fetchProducts(categoryId, 0, 3);
          posts.where((a) => a.childCategoryId == childCategoryId).toList();

          yield ProductsFiltered(
              product: posts, hasReachedMax: false, filter: childCategoryId);
          return;
        }
        if (currentState is ProductsFiltered) {
          var posts =
              await _fetchProducts(categoryId, currentState.product.length, 6);
          var oldPost = currentState.product;
          oldPost.where((a) => a.childCategoryId == childCategoryId).toList();
          yield posts.isEmpty
              ? currentState.copyWith(hasReachedMax: true)
              : ProductsFiltered(
                  product: oldPost + posts,
                  hasReachedMax: false,
                  filter: childCategoryId);
        }
      } catch (e) {
        print(e.toString());
        yield ProductsError();
      }
    }
  }

Then from my UI, i do this
productBloc.add(FilterProductEvent(
                        categoryId: widget.categoryId,
                        childCategoryId:
                            state.childCategory[index].categoryId));

When i run it , the list of my data is not filtered. how can i fix it ? did i miss something ?

A: I think problem here is missing set posts again after you filter it.
Try it:
var posts = await _fetchProducts(categoryId, 0, 3);
posts = posts.where((a) => a.childCategoryId == childCategoryId).toList();

A: You can search with 2 ways

*

*From server side :
  You have to design your API to return result according to your search query.

*From App :
  You can simply do the api call 1st and store it in bloc then for search you can make a method which will return the searched List.
List search(keyword){
    return list.where((item)=>item.contains(keyword)).toList();
}


text:
Q: Spotify authorization code flow (WPF browser control) C# I'm using Spotify account service (authorization code flow) to get an authorization code by passing in the required parameters (client_id, response_type and redirect_uri. Its a WPF application so i am using the browser control and navigating the user to
https://accounts.spotify.com/authorize/?client_id=myclientId&response_type=code&redirect_uri=someUri

When i copy paste the link in the browser, i see the right stuff i.e page with the Login to Spotify button but when i am navigating through the browser control in my WPF application, it gives me a file download dialog with Authorize.json file to download with Open and Save options, however in some cases it presents the right page to browser code.
Below is my code:
    public winOAuthBrowserForm(string navigateTo)
    {
        InitializeComponent();
        webBrowser.Navigated += webBrowser_Navigated;
        webBrowser.Navigate(navigateTo);

    }

    private void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
    {
        if(!String.IsNullOrEmpty(e.Uri.Query))
        {
            //since we are looking for code for authorization that will be exchanged for request token from the server
            if (e.Uri.Query.StartsWith("?code=") || e.Uri.Query.Contains("code="))
            {
                code = HttpUtility.ParseQueryString(e.Uri.Query).Get("code");
                this.Close();
            }

            if (e.Uri.Query.StartsWith("?error=") || e.Uri.Query.Contains("error="))
            {
                error = HttpUtility.ParseQueryString(e.Uri.Query).Get("error");
                this.Close();
            }
        }
    }

And i am calling this control like:
            var uri = string.Format(SpotifyAuthUriFormatter, RequestAuthBaseUrl, clientId);
            winOAuthBrowserForm form = new winOAuthBrowserForm(uri);
            form.ShowDialog();

This is what i see:

UPDATE: When i right click on document and see the properties, i see it changes the URL to something like res://ieframe.dll/navcancl.htm#... I've searched it and found some solutions related to I.E (I'm using latest but you can't be sure that it'll be latest on client machines), some say that its firewall setting. The thing is, it appears sometimes only.
Any ideas? Thanks


text:
Q: How to pass array of string into a FastReport variable? My plan is to pass an array of string into a FastReport
Here's my code (stripped from all irrelevant parts and error handling):
var
  elements: TStringArray; // TStringArray = array of string;
begin
  FR := TfrxReport.Create(Self);
  FR.LoadFromFile(...);
  FR.Variables['dataArray'] := elements; // <-- Error here
  FR.ShowReport;
  FR.Free;
end;

But I get the error, indicating that I can not assign an array to a string that way:

Could not convert variant of type (array OleStr) into type String

However if I assign '['a', 'b', 'c', 'd', 'e', 'f']' to a dataArray variable within FastReport editor it works just fine - I can access dataArray[1] and etc.
So my question is - How to properly assign a variable of type array of string to FastReport variable?

A: I don't have a copy of FastReport to hand, but I know it uses an internal copy of FastScript. If you can gain access to this you should be able to make the Delphi variable available to the script using the script's AddVariable method. e.g.
FR.Script.AddVariable('elements', 'Array', elements);


text:
Q: How should I inject behaviour into an Entity I am exploring the use of Entity Framework Database First and I am trying to understand if I should inject behavior into an entity, and if so, what is the best technique for doing this.  I typically have done this in the past to avoid anemic domain objects.  A couple use cases are where I inject a specification into an entity (specification pattern/define composable business rules) or where I perhaps inject a ninject implemented factory into a root entity where the binding of the implementation is determined by a strategy/factory method at point of use) So for example below, I would use an IOC to inject in ISomethingSpec implementation.
 class Foo
 {
    void DoSomething()
    {
        if(somethingSpec.SatisfiedBy(this)
        {
        }
    }
}

May I ask, Should I consider a different pattern for associating behavior with an entity?  Or if it is reasonable, is using partial classes/property and method injection the best option where I am using EF5 with database first?
This is my first post, so I hope it's format is not too far off the mark. I posted as I have looked at other questions that are similar but I could not determine a consensus on best practice for associating behavior with Domain objects /EF Entities.

A: I use the specification pattern with Entity Framework to filter the data that is retrieved from the database. I think you can use the same approach and adapt it to your needs.
You can use a DI container to inject your specifications and other objects you may need. First step is to define a contract for your specification objects, something like this:
public interface ISpecification<T> where T : class
{
    Expression<Func<T, bool>> GetExpression();
    bool IsSatisfiedBy(T entity);
}

A generic Specification object can be defined like this:
public class Specification<T> : ISpecification<T> where T : class
{
    private Expression<Func<T, bool>> expression;

    public Expression<Func<T, bool>> GetExpression()
    {
        return expression;
    }

    public Specification(Expression<Func<T, bool>> expression)
    {
        this.expression = expression;
    }

    public bool IsSatisfiedBy(T entity)
    {
        var query = (new[] { entity }).AsQueryable();

        return query.Any(this.expression);
    }
}

And then you can change your Foo class like this, so you can inject the dependency using a DI/IoC container:
public class Foo()
{
    public ISpecification<Foo> Specification
    {
        get;
        private set;
    }

    public Foo(ISpecification<Foo> specification)
    {
        this.Specification = specification;
    }

    public void DoSomething()
    {
        if(Specification.SatisfiedBy(this))
        {
            //...
        }
    }
}

Creating and using a specification:
// example - create one specification
Expression<Func<Foo, bool>> expression =  ....;
ISpecification<Foo> fooSpecification = new Specification<Foo>(expression);

// using the specification with linq
var entities = dbContext.Foos.Where(fooSpecification.GetExpression());

// performing validation
var foo = new Foo{
    // ....
};

if(fooSpecification.IsSatisfiedBy(foo))
{
    // do something....
}

More details here:
http://ruijarimba.wordpress.com/2011/06/05/entity-framework-and-t4-generate-specification-objects-for-your-entities/

A: Re this question, after some investigation following Rui's helpful comments I have concluded that my intention to inject services into an entity is flawed.  The answer to my original question therefore is to use Domain Events instead which reduces coupling considerably, or alternatively using 'double dispatch' as per link below.  I am currently looking at nServiceBus as the tech for implementing Domain Events (and as an introduction into nServiceBus itself)
The following article helped clear my mind on types of services and how to use with a Domain model:
Domain Events Salvation


text:
Q: HTTP Status 500 - Servlet.init() for servlet cxf threw exception I'm trying to Create RESTful web service using WSO2 Developer studio, I'm new to this, So i used this tutorial http://codeoncloud.blogspot.com/2015/02/build-simple-java-jax-rs-restful-web.html.
When i did Deploy the web service in WSO2 Application server, then its work fine, but After clicking Find Services i can't see available RESTful services.
I'm getting this error
    HTTP Status 500 - Servlet.init() for servlet cxf threw exception

type Exception report

message Servlet.init() for servlet cxf threw exception

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Servlet.init() for servlet cxf threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.wso2.carbon.statistics.webapp.RequestIntercepterValve.invoke(RequestIntercepterValve.java:43)
    org.wso2.carbon.bam.webapp.stat.publisher.WebAppStatisticPublisherValve.invoke(WebAppStatisticPublisherValve.java:104)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
    org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
    org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
    org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:745)

A: This error can happen when you are using invalid class in cxf-servlet.xml. So make sure that the value for class is correct in the cxf-servlet.xml. You can find this file inside src>>main>>webapp>>WEB-INF directory.

A: This error is telling you that your class name is incorrect somewhere.
Quick Tip! - Scroll down and read the portion right below the error message that says "Caused by:".  It will give you more insight.
Check your cxf-servlet.xml file to make sure the fully qualified class name actually exists in the specified package.
Also, check your classes that are annotated with @WebService to make sure that your endpointInterface parameter is correct.
Hope this helps.


text:
Q: Javascript: How to simulate cursor with arrow key control for positioning DOM edits? I'm building an in-browser IDE using Javascript.  The code/widgets are stored in the document.  I want control over the editing process so I am intercepting keystrokes and displaying a simulated cursor where the edit point is in the DOM. (At first I tried using contenteditable = true but that isn't giving me enough control.)
I've made some progress so that clicking will insert the cursor at the beginning of the div and the right arrow will move to the next node, although now I am realizing that I am going to have to dig into the contents() and keep track of my cursor position in text nodes..
I'm wondering if anyone knows of any code out there that I can refer to or just copy or something rather than re-inventing the wheel.  I am using jQuery but that isn't a requirement.

A: Perhaps Mozilla Bespin can help. But IMHO if you can't use contenteditable you'll need to write a lot of code.


text:
Q: How can I place widget A in the center and the widget B to the edge?
        Row(
          children: [
            Center(
              child: TextButton(
                  onPressed: () {
                    print('hello');
                  },
                  child: Text('hmmm')),
            ),
            Container(
              height: 20,
              width: 20,
              color: Colors.white,
            ),
          ],
        ),

I have this Row widget that has two widgets. I want to place the hmmm button widget in the center, while placing that white container widget in the right side of the edge. How can I do that inside the Row widget?

A: you can use MainAxisAlignment.spaceBetween and add a third element to be at the start
Row(
  mainAxisAlignment: MainAxisAlignment.spaceBetween, // add this
  children: [
    Container(), // add this
    Center(
      child: TextButton(
        onPressed: () {
          print('hello');
        },
        child: Text('hmmm'),
      ),
    ),
    Container(
      height: 20,
      width: 20,
      color: Colors.white,
    ),
  ],
),

output:

Row in DevTools:

A: If you try to get this result:

You can either use a Row with MainAxisAlignment.spaceBetween and add a SizedBox() like so:
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SizedBox(),
                  Center(
                    child: TextButton(
                      onPressed: () {
                        print('hello');
                      },
                      child: Text(
                        'hmmm',
                        style: TextStyle(color: Colors.black),
                      ),
                    ),
                  ),
                  Container(
                    height: 20,
                    width: 20,
                    color: Colors.white,
                  ),
                ],
              ),

Or you could use a Stack widget with two children:

*

*A Row with you hmmm text.

*A Positionned widget with an Align widget as a child, and your white Container as a child of your Align

A: Try this code,
      Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextButton(
                onPressed: () {
                  print('hello');
                },
                child: Text('hmmm')
            ),
            Container(
              height: 20,
              width: 20,
              color: Colors.white,
            ),
          ],
        ),
      ),

Let us know if this is what you wanted.


text: Q: Does SQL Server 2017 Express support Linked Server connections to Oracle DB Is there any restrictions with "Linked Servers" with SQL Server 2017 Express?  Vs using SQL Server 2017 Standard.   Only in regards to "Linked Servers".


text:
Q: What is the homotopy fiber of the map from a space to its James construction? Given a pointed space X, let $J(X)$ denote its James construction. There is a natural inclusion $X\rightarrow J(X)$ which can equivalently be described as the unit map $\eta_X:X\rightarrow \Omega \Sigma X$.
The homotopy fiber of the counit map $\epsilon_X:\Sigma \Omega X\rightarrow X$ is known to be $\Omega X * \Omega X$. Is there an analogous result for the homotopy fiber of $\eta_X$ in terms of $X$?

A: This might not be a satisfactory answer, but let me point out that S.-c. Wong constructed a "little cube" model for the homotopy fiber of $\Omega^{k-1}E^n : \Omega^{k-1}\Sigma^{k}X \to \Omega^{k-1+n}\Sigma^{k+n} X$ in this paper in 1994.
Note that May's little cube model for $\Omega\Sigma X$ is essentially the James construction.


text:
Q: reload Data table with ajax.url().load() not working I have a server-side paging enabled data table that works fine. Following is my table initialized, which pulls json data & renders:
function initTestTable(){
    myTable = $('#testTable').dataTable({
   "processing": true,
   "serverSide": true,
   "ajax": {
       "url": "testTableData.html",
       "type": "GET",
   },
   "columnDefs": [ {
       "targets": 0,
       "data": "code",
       "render": function ( data, type, full ) {
           return ''+data+'';
         }
     },
     {
       "targets": 1,
       "data": "description",
       "render": function ( data, type, row, meta ) {
           return data;
       }
     }]
 });

}
Even ajax following ajax reload working fine:
myTable.api().ajax.reload(); //reloads ajax with very previous ajaxed URL

The problem is when I want to relaod with different URL using following load() function. Actually it is freezing the on "Processing..." message without rendering the data on table. Response seems to alright.
myTable.api().ajax.url('getNextData.html').load(); //reloads ajax with specified URL

I dont know what is going wrong as there are errors are shown in the developer tool console. Please suggest.


text:
Q: Preventing Python from escaping characters in a list of strings I need to create several strings using the format() method and store them in a list. (Ultimately, the strings will be used as regular expressions but that's not important at this stage.)
I've defined a string that presents potential spaces:
space_sep = r"[\s_\-–—]*"   # which defines several characters used as separators

The full string is produced using:
myStr = """category\d{spc}\d{{3}}""".format(spc = space_sep)

...which produces the complete string (as expected):
category\d[\s_\-–—]*\d{3}

However, if I use the same method to create several strings and store them in a list, the backslashes are automatically escaped. As these strings will be used as regexes, that is not what is wanted:
myLst = ["""category\d{spc}\d{{3}}""".format(spc = space_sep),
         """group\d{spc}\d{{3}}""".format(spc = space_sep)]

This produces a list of strings with all the backslashes escaped:
['category\\d[\\s_\\-–—]*\\d{3}', 'group\\d[\\s_\\-–—]*\\d{3}']

This is not what is needed. Instead, I want to produce unescaped strings, such as:
['category\d[\s_\-–—]*\d{3}', 'group\d[\s_\-–—]*\d{3}']

I've tried using r to identify a raw string but it doesn't work (at least, not in any of the ways I've tried). Is there a way to prevent Python from automatically escaping characters in a list of strings? (I'm running Python 3.6.1 on Windows 7 and can't upgrade either.)


text:
Q: I need my bot to ignore messages by users with a specific role My bot needs to ignore posts by people with a specific role.
I have written this code and it should be working but every command under this piece of code doesn't work.
I receive no error message(s) and my bot is fine above this piece of code.
What do I need to change?
client.on('message', message => {
    if (message.guild.roles.cache.find(r => r.name === "ROLE NAME")) {return;}
})

Any help is appreciated.

A: You are checking if the Guild has a Role named ROLE NAME, not the actual GuildMember.
GuildMember has a property called roles, which contains all the roles of GuildMember.
client.on("message", message => {
    if (message.member.roles.cache.find(role => role.name == "ROLE NAME")) return false;

    // Execute your commands here.
});

A: You should be checking if the GuildMember has the Role, not the Guild.
client.on("message", message => {
    if (message.member.roles.cache.some(role => role.name == "ROLE NAME")) return;

    // code...
});

You can use the .some() method, which will check if any item in the Collection (the member's roles) passes a test you give. In this case, the test is if the role name equals ROLE NAME


text:
Q: How can I move data from one table to another in rails migration? I have set up a rails site with these resources:
users(devise)
authors
I have realised that I need to move all authors over to users table because I am setting up roles for these users as an author now.
Currently I have tried the following migration but nothing worked and no data was transferred over to the users table:
class MoveAuthorsColumnDataToUsersTable < ActiveRecord::Migration
  def change
    Author.find_each do |author|
       User.find_or_create_by(
           :username => author.name.downcase.gsub(' ',''),
           :encrypted_password => "",
           :email => "",
           :avatar_file_name => author.avatar_updated_at,
           :avatar_content_type => author.avatar_content_type,
           :avatar_file_size => author.avatar_file_size,
           :avatar_updated_at => author.avatar_updated_at,
           :role_id => "3"
       )
     end
  end
end

I have got an author model setup with attributes in the controller, I am eventually going to transfer all author models relationships to users.
author.rb model:
class Author < ActiveRecord::Base
    has_many :books, dependent: :destroy
    has_many :ideas, dependent: :destroy
    accepts_nested_attributes_for :books
    accepts_nested_attributes_for :ideas
    validates_uniqueness_of :name

    has_attached_file :avatar, :styles => { :large => "980x760", :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
    validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/

end

user.rb model(devise)
class User < ActiveRecord::Base
  belongs_to :role
  def confirmation_required?
    false
  end
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

  has_attached_file :avatar, styles: {
        large: "600x450#",
        medium: "250x250#",
        small: "100x100#"
    }, :default_url => "/images/:style/filler.png"
  #validates_attachment_content_type :avatar, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
  validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
  validates :avatar, :email, :username, :password, presence: true

end

Here is the schema for users and authors:
  create_table "authors", force: true do |t|
    t.string   "name"
    t.text     "biography"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "book_id"
    t.string   "avatar_file_name"
    t.string   "avatar_content_type"
    t.integer  "avatar_file_size"
    t.datetime "avatar_updated_at"
    t.integer  "idea_id"
  end

  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "avatar_file_name"
    t.string   "avatar_content_type"
    t.integer  "avatar_file_size"
    t.datetime "avatar_updated_at"
    t.string   "username"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.integer  "role_id"
  end

The end result I am trying to achieve here is to get all authors safely over to users as entries in the postgres database and then from there I can use this data to carry on finishing off what else needs refactoring in the models for users etc.
This will hopefully help someone try and find the right solution to what i am trying to do. I am pretty sure many people have been here before and had the same headache.
Thanks

A: Assuming:
 1.you have created all required column in User table(as it was in author table).
2. You just need to copy all author records to User.
Create your copy_author_to_user.rb file in below location!
# db/scripts/copy_author_to_user.rb
require 'rubygems'

Author.all.each do |a|
  user = User.new(
    :username => a.name.downcase.strip,
    :encrypted_password => '',
    :email => '',
    :avatar_file_name => a.avatar_updated_at,
    :avatar_content_type => a.avatar_content_type,
    :avatar_file_size => a.avatar_file_size,
    :avatar_updated_at => a.avatar_updated_at,
    :role_id => "3"
  )
  user.save!
end

then from console run :
$rails runner db/scripts/copy_author_to_user.rb

A: On your user model you have these validations:
  validates :avatar, :email, :username, :password, presence: true

However in your migration you're setting encrypted_password to "" which won't pass the presence true validation on password.
As a side note find_or_create_by is going to do 1 of two things, find the first record that matches your hash (username, etc) or if nothing is found create a new use with that info.  If you find the record and don't create it, you'll want to call save after the fact.
I like first_or_initialize so something like:
Author.find_each do |author|
       user = User.first_or_initialize(
           :username => author.name.downcase.gsub(' ',''),
           :encrypted_password => "",
           :email => "",
           :avatar_file_name => author.avatar_updated_at,
           :avatar_content_type => author.avatar_content_type,
           :avatar_file_size => author.avatar_file_size,
           :avatar_updated_at => author.avatar_updated_at,
           :role_id => "3"
       )
       user.save!
     end


text:
Q: pagenation ellipsis (1, 2, 3, 4, 5 ..... 20) in php I was wondering how I could do an ellipsis where it would show the first 5 pages, then echo "...", then echo the very last page, does anyone know how I could do that? Thank you so much!
if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 5;

$GrabRows = $database2->prepare("SELECT * FROM `data` ORDER BY `ranks`.`xp` DESC LIMIT $start_from, 5");
$GrabRows->execute();
$OverallSkills = $GrabRows->fetchAll();
$TotalCount = $GrabRows->rowCount();
$TotalPages = ceil($TotalCount / 1);

$RankNumber = (intval($_GET["page"]) *5) -4;
foreach($OverallSkills as $row){
//dowork
$RankNumber +=1; //rank for the table, irrelevant at the moment.
}

for ($i=1; $i<=$TotalPages; $i++) {
echo "
$i
\n"; //$i is the page  it's adding (each time it loops the page is +1)
echo "\n";
}

A: This code does the job:
<?

$max = max($TotalPages, min($TotalPages, 5));
for ($i=1; $i<=$max; $i++) {
    echo "
$i
\n"; //$i is the page  it's adding (each time it loops the page is +1)
    echo "\n";
}

if($totalPages > 6) {
    echo "
...
\n";
}

if($totalPages > 5) {
    echo "
$totalPages
\n";
    echo "\n\n";
}

?>

There are 2 if statements, because you don't want to display 1, 2, 3, 4, 5, ..., 6.
With 6 pages, this code displays 1, 2, 3, 4, 5, 6, and with 7 pages 1, 2, 3, 4, 5, ..., 7.


text:
Q: Búsquedas de texto en Python Estoy desarrollando un pequeño programa para buscar palabras o secuencias de palabras en una cadena de texto, y la función del programa sería devolver las posiciones donde se encuentran las letras. El código sería así:
def buscar_motivo(x,y):
    indice = []
    for i,j in zip(x,y):
       indice = x.find(y)

Pero el problema es que al detectar la primera secuencia de y que se encuentra en s, para y no busca más, aunque haya más secuencias. ¿Cuál es el problema? Muchas gracias!

A: Si quieres trabajar con texto y procesamiento de lenguaje natural, utiliza nltk, librería especializada para ello que seguro ya tienen las primitvas que deseas desarrollar.


text:
Q: extraneous output from hello world php html javascript page I am a noob with web based languages, and was just trying to figure out the server/client side of things.
I have this index.html file stored in two locations.
1) c:\MAMP\htdocs\Test\index.html
2) c:\Test\index.html
<!DOCTYPE HTML>

Hello from html!

        <?php
            echo "
Hello from php!
";
        ?>

What confuses me, is that the output is
Hello from html!

Hello from javascript!

Hello from php!
"; ?>

I don't understand why I get the trailing "; ?>
I have Apache installed (via MAMP), and I was expecting that if I open the index.html file via the server in my web browser http://localhost/Test/index.html the php would execute, and if I open it in the web broswer directly with file:///C:/Test/index.html the php wouldn't execute.  But I get the same output either way.

A: The server wont parse PHP when it's inside a file with a .html extension. The browser is assuming that this is an HTML tag:
<?php echo "

And is just printing everything after that. If you change your file to index.php you will get the outcome you're looking for.

A: Issue is that the PHP is not being executed on both cases.
When you have a look at the HTML code generated is easy to see that the php was not executed at all (this is me simply opening the file not running any MAMP/XAMP):

To solve this problem try to change the extension to .php and to make sure you have MAMP running.


text:
Q: Can you programmatically detect a change in MPMoviePlayerController currentPlaybackTime I've written custom control which allows the user to change the currentPlaybackTime of a MPMoviePlayerController by clicking or dragging on a custom UIButton that displays an image of some musical notation. The code uses the x position of the touch event to update currentPlaybackTime and it all works fine. I also have a CALayer (a vertical red line) that shows the user where they have touched on the control.
What I'd like to do now is have the red line's (CALayer object) position update if the user changes the currentPlaybackTime property of the movie player using the scrubber (slider) control.
Obviously currentPlaybackTime is always updating as the movie plays, but is there a way to detect if the user interferes with this by skipping forward or backwards?
Many thanks.

A: You could use Key-Value-Observing to track changes of currentPlaybackTime in your MPMoviePlayerController, but that might generate a lot of events and thus negatively affect your performance. Maybe you can also use KVO with the playbackState property of your MPMoviePlayerController, I believe it changes when the user starts seeking.
Another alternative is that you just setup a repeating timer that updates quite frequently, and everytime it fires you check the new value of currentPlaybackTime. But that might look choppy and it could also affect performance.


text:
Q: Viewbag value is rendering in proper case. How do I force it to render in the intended case? In my controller I am setting a Viewbag value to false but when I render it on the view it comes out False. How do I prevent this?
My controller:
 ViewBag.IsEditable = false;

My view:
$.fn.editable.defaults.disabled =@ViewBag.IsEditable;
Because it is rendered with the Capital F in false the boolean doesn't work with my Jquery call.

A: You have a boolean value that you want to evaluate in order to create some Javascript code.  In this case @ViewBag.IsEditable is basically calling ToString() on your boolean value, which produces capitalized True or False.
C# does have the lowercase keywords true and false, but they are literals which represent the Boolean object which always returns a capitalized True or False when ToString() is called on it.
I recommend using the ternary operator to evaluate the boolean.
$.fn.editable.defaults.disabled = @( ViewBag.IsEditable ? "true" : "false");

A clearer way of seeing what's going on here might be to write it like this:
@( ViewBag.IsEditable ?
  "$.fn.editable.defaults.disabled = true;" :
  "$.fn.editable.defaults.disabled = false;")

A: You are confusing your types. true and false the keywords are boolean values. In the .NET world, the .ToString() represetation is "True" and "False", respectively. To keep your original code working, you could try
$.fn.editable.defaults.disabled =@ViewBag.IsEditable.ToString().ToLower()

A: You might want to consider an extension method as a way of simplifying.  Note, you'd need to include the namespace for the extensions class in the view - either directly or via the web.config.  The flag would also need to be part of the model (or cast as bool so it can resolve the extension method)
   public static class BooleanExtensions
   {
        public static string AsJs(this bool source)
        {
            return source ? "true" : "false";
        }
   }

Used as
$.fn.editable.defaults.disabled = @(((bool)ViewBag.IsEditable).AsJs())

or
$.fn.editable.defaults.disabled = @Model.IsEditable.AsJs()


text:
Q: Python multiple arguments issue I'm currently facing an issue with my write line in my script:
out_file.write(",".join(CX, SDX, EDX, NCX, CJX, LX, POIX, DOIX, NAAX, DOGX, NKX) + "\n")

The error I get is
TypeError: str.join() takes exactly one argument (11 given)

I understand I need to only give one argument, however I can't quite seem to work out how to condense them to fit my 11 headings with this approach.
Any insight would be greatly appreciated!
Edit:
Full code:
import re
import csv
import os

from bs4 import BeautifulSoup

path = r'D:/E/F/Test1'

ext = '.htm'

out_file = open('names.csv', 'w')
out_file.write(",".join(['Ref', 'Start date of Validity', 'country', 'End date of validity', 'Nomenclature code', 'Classification justification', 'Language', 'Place of issue', 'Date of issue', 'Name and address', 'Description', 'keywords']) + "\n") # Write your keys

for filename in os.listdir(path):

    if filename.endswith(ext):

        fullpath = os.path.join(path, filename)

        filename = os.path.splitext(os.path.basename(filename))[0]

        soup = BeautifulSoup(open(fullpath, encoding="utf-8"), 'html.parser')

        text = soup.get_text()

        ref = soup.find("td", text="Reference")
        pattern = re.compile(r'GBBTI\S{9}')
        IC = soup.find("b", text="Issuing country")
        CX = IC.findNext("td").contents
        SD = soup.find("b", text="Start date of validity")
        SDX = SD.findNext("td").contents
        ED = soup.find("b", text="End date of validity")
        EDX = ED.findNext("td").content
        NC = soup.find("b", text="Nomenclature code")
        NCX = NC.findNext("td").contents
        CJ = soup.find("b", text="Classification justification")
        CJX = CJ.findNext("td").contents
        L = soup.find("b", text="Language")
        LX = L.findNext("td").contents
        POI = soup.find("b", text="Place of issue")
        POIX = POI.findNext("td").contents
        DOI = soup.find("b", text="Date of issue")
        DOIX = DOI.findNext("td").contents
        NAA = soup.find("b", text="Name and adress")
        NAAX = NAA.findNext("td").contents
        DOG = soup.find("b", text="Description of goods")
        DOGX = DOG.findNext("td").contents
        NK = soup.find("b", text="National keywords")
        NKX = NK.findNext("td").contents

        out_file.write(",".join((CX, SDX, EDX, NCX, CJX, LX, POIX, DOIX, NAAX, DOGX, NKX)) + "\n")
out_file.close()

A: You need to combine the arguments into a list or a tuple by adding a set of [] or () around them:
out_file.write(",".join((CX, SDX, EDX, NCX, CJX, LX, POIX, DOIX, NAAX, DOGX, NKX)) + "\n")

PS: You might also consider using the csv module; you'll still need the double brackets, but it'll automatically handle the , and \n for you as well as various other things

A: The join method takes a sequence of values, it's not *args, it's args.
So you should use join like this:
out_file.write(",".join((CX, SDX, EDX, NCX, CJX, LX, POIX, DOIX, NAAX, DOGX, NKX)) + "\n")

Or without join:
out_file.write(CX + "," + SDX + "," + EDX + "," + NCX + "," + CJX + "," + LX + "," + POIX + "," + DOIX + "," + NAAX + "," + DOGX + "," + NKX + '\n')

A: The .join() method takes an iterable as an input, meaning it just takes one argument that it can iterate over. This could be a list, tuple - any python iterable which you then pass in as a single arugment.
You could easily achieve this in your code by converting the items you're passing in individually into a list that contains all of those items:
out_file.write(",".join([CX, SDX, EDX, NCX, CJX, LX, POIX, DOIX, NAAX, DOGX, NKX])+ "\n")


text:
Q: Why is Entity Framework Core using SqlConnection on Azure? I'm creating an application using PostgreSQL database.
I'm using the AddDbContext.UseNpgsql() methods to work with it :
Startup.cs:
services.AddDbContext<DbModel>(options =>
    options.UseNpgsql(
        Configuration.GetConnectionString("connectionStringName"))

When I'm starting the application on my computer (Windows 11), it works. I'm able to connect to my PostgreSQL database, perform migrations, CRUD actions and else.
But when I'm trying to deploy it on an Azure App Service (running Linux) I get the following error :

Application startup exception
System.ArgumentException: Keyword not supported: 'port'.
at Microsoft.Data.Common.DbConnectionOptions.ParseInternal(Dictionary2 parsetable, String connectionString, Boolean buildChain, Dictionary2 synonyms, Boolean firstKey)
at Microsoft.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
at Microsoft.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at Microsoft.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at Microsoft.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
at Microsoft.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at Microsoft.Data.SqlClient.SqlConnection..ctor(String connectionString)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.CreateDbConnection()
...

Even if I'm using the UseNpgsql() method, it seems like on the App Service only, Entity Framework Core is still trying to use SQL Server instead of PostgreSQL, and it cannot recognize the keyword "port".
But why? How can I tell it to use the correct Npgsql provider?
UPDATE 1
I've changed my local connection string to make it throws an error, here is the stack trace I have in local when a keyword is not supported :

System.ArgumentException: Keyword not supported: azerty (Parameter 'keyword')    at
Npgsql.NpgsqlConnectionStringBuilder.GetProperty(String keyword)    at
Npgsql.NpgsqlConnectionStringBuilder.set_Item(String keyword, Object
value)    at
System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String
value)    at Npgsql.NpgsqlConnectionStringBuilder..ctor(String
connectionString)    at Npgsql.NpgsqlConnection.GetPoolAndSettings()
at Npgsql.NpgsqlConnection.set_ConnectionString(String value)    at
Npgsql.NpgsqlConnection..ctor(String connectionString)    at
Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlRelationalConnection.CreateDbConnection()
at
Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()

In local, it uses the correct provider. Do I have to change a setting on the Azure App Service ?


text:
Q: Unable to scroll a canvas full of buttons I built scrollable canvas before, but now I have to fill one of them with buttons, and I don't know why the scrollbar is inactive... maybe the problem is that the canvas contains buttons?
It's strange that it is inactive since the canvas and the scrollbar seem to be correctly connected by vscrollbar.set and cv.yview...
from Tkinter import *

def main():

  root = Tk()
  root.geometry("%dx%d+0+0" % (1800,1000))

  auxframe=Frame(root)
  auxframe.pack(fill=BOTH, expand=YES)

  cv = Canvas(auxframe, scrollregion=(0,0,8000,8000))
  vscrollbar = Scrollbar(auxframe, orient=VERTICAL)
  vscrollbar.pack(fill=Y, side=RIGHT)
  vscrollbar.config(command=cv.yview)
  cv.config(yscrollcommand=vscrollbar.set)
  cv.pack(side=LEFT, fill=BOTH, expand=TRUE)

  memimages=[]
  for row_index in range(8):
      for col_index in range(8):
          iconimage = PhotoImage(file="test.gif")
          b=Button(cv,image=iconimage)
          memimages.append(iconimage)
          b.grid(row=row_index, column=col_index, sticky=N+S+E+W)

  mainloop()

main()

(edit)
according to Bryan's answer, I made it work by adding this - note that fcv is not packed.
fcv=Frame(root)
cv.create_window(0, 0, anchor = "nw", window=fcv)

and all the buttons are children of fcv: b=Button(fcv,image=iconimage)
I still dont understand why the documentation (e.g.infohost or tutorialspot) doesnt mention this important fact.

A: The canvas will not scroll objects added to it via pack, place, or grid. You must use the canvas method create_window.
A common technique is to use create_window to create a single frame, and then you can use pack, place, or grid on widgets that are placed inside the frame. For an example see Adding a scrollbar to a group of widgets in Tkinter


text:
Q: Making sure a value is equal to one of many in LINQ I have an IEnumerable containing values like "ABC", "DEF", etc.
I'm trying to form a LINQ query where the value of a property in my object may be equal to one of the many values contained in my IEnumerable. How do I form that LINQ query?
var statesFilter = new List<string>();
statesFilter.Add("NY");
statesFilter.Add("CA");

var employees = new List<Employee>();
employees = getDataFromSomewhere();

// Code below is not working. Just wanted to give you an idea about my LINQ query
var myFilteredList = employees.Where(x => x.State.Contains(statesFilter));

Employee class could be something like this:
public class Employee
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string State { get; set; }
}

A: If State property is of type string, you should change your Where to the following:
var myFilteredList = employees.Where(x => statesFilter.Contains(x.State));

Also, you can do this:
var myFilteredList = employees.Where(x => statesFilter.Any(s=>s==x.State));

A: Condition should be
x=>statesFilter.Contains(x.State))


text:
Q: Soft Key board not coming I have an edit text, which based on some condition, i dynamically want to perform click, so i use :0 editText.performClick()
Using this the click event is triggered and also i can see the focus in the edit text, but soft keyboard is not coming up, I also tried :-
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(editText,
                    InputMethodManager.SHOW_IMPLICIT);

and
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(editText,
                    InputMethodManager.SHOW_FORCED);

But the key board is not coming up.... Any ideas..... Thanks :)

A: Try InputMethodManager's toggleSoftInput method.


text:
Q: Validate field for 10 digits javascript I have following code for a field which must be filled out with exact 10 numbers

$('#input-payment-egn').on('input', function() {

 var input=$(this);
 var is_egn=input.val();
 $("div.wrong-egn").hide();
 var re = /^\d{10}$/;
 var is_egn=re.test(input.val());
 if(is_egn<10){
 $("div.wrong-egn").show();
 }
});

<form id="leasingform">

    <?php echo $text_egn; ?>
        <input type="text" maxlength="10" name="egn" value="" placeholder="Въведете вашето ЕГН" id="input-payment-egn"
                   class="form-control"/>

Въведете валидно ЕГН !

</form>

I want to validate the input when the user clicks somewhere else on the page, after he entered the number! I used regex (i think its okay).Can you help me? Thank you!

A: Here you go with an example solution https://jsfiddle.net/3bgpdp7v/1/

$('#input-payment-egn').keyup(function(e){
  if($(this).val().length === 10){
    e.preventDefault();
    $('#wrong-egn').slideUp();
  } else {
    $('#wrong-egn').slideDown();
  }
});
#wrong-egn{
  display: none;
  font-size: 12px;
  color: red;
}

<input type="text" maxlength="10" name="egn" value="" placeholder="Въведете вашето ЕГН" id="input-payment-egn" class="form-control"/>

Please provide 10digit number.

I've used jQuery keyup event & checking for number of characters, instead of regex.
One more way
Here is one more solution https://jsfiddle.net/3bgpdp7v/2/

$('#input-payment-egn').keyup(function(e){
 if($(this).val().length === 10)
   e.preventDefault();
}).focusout(function(){
 if($(this).val().length === 10){
   $('#wrong-egn').slideUp();
  } else {
   $('#wrong-egn').slideDown();
  }
});
#wrong-egn{
  display: none;
  font-size: 12px;
  color: red;
}

<input type="text" maxlength="10" name="egn" value="" placeholder="Въведете вашето ЕГН" id="input-payment-egn" class="form-control"/>

Please provide 10 digit number.

This will display the message on focusout.
Hope this will help you.

A: I would suggest using the focusout event if you want the behavior to only show when the user clicks out. This will also catch if the user uses the tab out function.
Here is an example. fiddle
<input type="text" maxlength="10" name="egn" value="" placeholder="Въведете вашето ЕГН" id="input-payment-egn" class="form-control"/>

Javascript
$('#input-payment-egn').focusout(function(e){
 if($(this).val().length < 10){
  $('#wrong-egn').css('display','block');
 }else{
  $('#wrong-egn').css('display','none');
 }
});


text:
Q: Queue of data when sending Google Firebase commands sorry if my English is messy :(
Recently, I learned about the IoT system and started implementing it in several simple projects.
Well, one of my projects uses Esp32 wifi and 16 channel Relay to control lights via Firebase. However, there is a delay in the process, because the system (Looping) always checks one by one in the database.
For example, I update the Relay 6 command to turn on. Then the order must be queued up until it is your turn to turn on.
If 1 relay = 1 second, it will take 16 seconds for each command, because the system always starts from scratch. Not to mention if the network is slow, sometimes it's almost a minute of waiting
how to avoid queuing when sending commands?
Thank you  enter image description here


text:
Q: How to send integer in POST to Tornado's AsyncHTTPTestCase.fetch()? I'm using python's Tornado framework to test my HTTP POST endpoint. To do this, I'm using the fetch method.
    data = urllib.urlencode({
        'integer_arg': 1,
        'string_arg': 'hello'
    })

    resp = AsyncHTTPTestCase.fetch('/endpoint',
                                   method='POST',
                                   headers={'h1': 'H1',
                                            'h2': 'H2',
                                            'Content-Type': 'application/json'},
                                   body=data)

When I do this, the endpoint receives integer_arg as the string "1" even though I want it to receive it as an integer. This is understandable because urllib.urlencode converts it to a string. So how can I ensure it receives an integer?
Just eliminating the call to urllib.urlencode doesn't work.
By the way, when I hit the same endpoint with a naked curl call as shown below, the endpoint properly receives integer_arg as the integer 1.
curl \
--request POST \
--header "h1: H1" \
--header "h2: H2" \
--header "Content-Type: application/json" \
--data '{
    "integer_arg": 1,
    "string_arg": "hello"
}' \
"http://localhost:8000/endpoint"

A: The body in curl is significantly different than that in AsyncHTTPClient.fetch. With python you urlencode the data in curl there is just json. So simply change urlencode with json.dumps:
import json
from tornado.ioloop import IOLoop
from tornado.httpclient import AsyncHTTPClient
from tornado.gen import coroutine

@coroutine
def main():
    client = AsyncHTTPClient()
    body = json.dumps({
        'integer_arg': 1,
        'string_arg': 'hello'
    })
    yield client.fetch(
        '/endpoint', method='POST', body=body,
         headers={'h1': 'H1',  'h2': 'H2', 'Content-Type': 'application/json'}
    )

ioloop = IOLoop.instance()
ioloop.run_sync(main)


text:
Q: Dynamic open-loop optimization with Pyomo I want to implement a dynamic open-loop optimization. I find that the documentation is not covering these use-case that well, so I found these two examples

*

*https://jckantor.github.io/CBE32338/05.02-Optimization-Control-and-Estimation-using-Pyomo-With-Windows-ipopt.html

*https://ndcbe.github.io/CBE60499/02.06-Pyomo-DAE.html
I can get a solution if I use the discretization method  dae.finite_difference but not with dae.collocations. It says:
pyomo.common.errors.ApplicationError: Solver (ipopt) did not exit normally
I want to use collocation because I want to constrain the input to pice-wise constant which apparently is possible only with model = discretizer.reduce_collocation_points(...)  which does not exist if I do not use the collocation method. Here is my working code ( I use bokeh to visualise the results)
from pyomo.environ import *
from pyomo.dae import *
import numpy as np
from utils.utils import SimSettings
from bokeh.plotting import figure, show
from bokeh.layouts import row, gridplot, grid
from bokeh.io import output_file
from bokeh.palettes import Category20b

results_dir = 'results/ukf_opt'

# Final time
tf = 120

# time vector
t_sim = np.arange(0, tf, 3)

# Define the model
model = ConcreteModel()
model.t = ContinuousSet(bounds=(0, tf)) #time
model.glu = Var(model.t, bounds=(0, None)) # first state
model.bio = Var(model.t, bounds=(0, None))# second state
model.lac = Var(model.t, bounds=(0, None))# Third state
model.v = Var(model.t, bounds=(0, 5)) # forth state
model.fglu = Var(model.t, bounds=(0, 0.5)) # Input

model.dglu = DerivativeVar(model.glu, wrt=model.t)
model.dbio = DerivativeVar(model.bio, wrt=model.t)
model.dlac = DerivativeVar(model.lac, wrt=model.t)
model.dv = DerivativeVar(model.v, wrt=model.t)

model.v_max = Param(initialize=0.08)
model.km = Param(initialize=0.4)
model.v_maxl = Param(initialize=0.04)
model.kml = Param(initialize=0.2)
model.cglu = Param(initialize=5)

# Initial condition
x0 = [1., 2., 0.1, 1.]

# Definition of the odes
def ode_glu(model, t):
    vl = (model.v_maxl * model.glu[t]) / (model.kml + model.glu[t])
    v = (model.v_max * model.glu[t]) / (model.km + model.glu[t])
    return model.dglu[t] == - v * model.bio[t] - vl * model.bio[t] + model.fglu[t] / model.v[t] * (
            model.cglu - model.glu[t])

def ode_bio(model, t):
    v = (model.v_max * model.glu[t]) / (model.km + model.glu[t])
    return model.dbio[t] == v * model.bio[t] - model.fglu[t] / model.v[t] * model.bio[t]

def ode_lac(model, t):
    vl = (model.v_maxl * model.glu[t]) / (model.kml + model.glu[t])
    return model.dlac[t] == vl * model.bio[t] - model.fglu[t] / model.v[t] * model.lac[t]

def ode_v(model, t):
    return model.dv[t] == model.fglu[t]

model.diffeq_glu = Constraint(model.t, rule=ode_glu)
model.diffeq_bio = Constraint(model.t, rule=ode_bio)
model.diffeq_lac = Constraint(model.t, rule=ode_lac)
model.diffeq_v = Constraint(model.t, rule=ode_v)

# Fix initial condition
model.glu[0].fix(x0[0])
model.bio[0].fix(x0[1])
model.lac[0].fix(x0[2])
model.v[0].fix(x0[3])

# I initialize a constant input. This is only to run a simulation to initialize the model. If I don't do it even the finite difference method does not work
model.Usim = Suffix(direction=Suffix.LOCAL)
model.Usim[model.fglu] = {0: 0.01}

# Here is the point where the problem is discretized. If I use dae.collocation instead of dae.finite_difference it does not work
discretizer = TransformationFactory('dae.finite_difference')
discretizer.apply_to(model, nfe=len(t_sim), scheme='FORWARD')

# Simulate the system with a constant input
sim = Simulator(model, package='casadi')
tsim, profiles = sim.simulate(integrator='idas', varying_inputs=model.Usim)
sim.initialize_model()

# Define objective function for the optimiyation
model.ls_control = sum([(model.lac[t]) ** 2 for t in model.t])
model.obj = Objective(expr=model.ls_control, sense=maximize)

# Solve the model. The print_level has basically no effect I do not why
solver = SolverFactory('ipopt')
solver.options['print_level'] = 5
solver.options['output_file'] = f"{ss.results_dir}/my_ipopt_log.txt"

solver.solve(model).write()

# Plot the results
profiles = np.concatenate((np.array([model.glu[t]() for t in t_sim]).reshape(-1, 1),
                           np.array([model.bio[t]() for t in t_sim]).reshape(-1, 1),
                           np.array([model.lac[t]() for t in t_sim]).reshape(-1, 1),
                           np.array([model.v[t]() for t in t_sim]).reshape(-1, 1)),
                          axis=1)
output_file(f"{results_dir}/simulation.html")
p_states = []
color_list = ['blue', 'green', 'magenta', 'red']
for k, state in enumerate(['glu', 'bio', 'lac', 'v']):
    p = figure(background_fill_color='#fafafa', y_range=(0, 3.5))
    p.line(t_sim, profiles[:, k],
           line_color=color_list[k], line_alpha=0.5, line_width=2)
    p_states.append(p)

grid = gridplot([[p_states[0], p_states[1]], [p_states[2], p_states[3]]])
show(grid)


text:
Q: Mapping multiple click events to a single method Currently i am faceing a problem while Mapping multiple click events to a single method. My currently
implimentation goes as follows and its working fine but i need a better way to handle multiple buttons
using one method.can any one help with this please.
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-draggable',
  templateUrl: './draggable.component.html',
  styleUrls: ['./draggable.component.scss']
})
export class AppComponent implements OnInit {

  status1: boolean = false;
  status2: boolean = false;
  status3: boolean = false;
  status4: boolean = false;
  status5: boolean = false;
  status6: boolean = false;

  constructor() { }

  ngOnInit() {
  }

  clickEvent1() {
    this.status1 = !this.status1;
  }
  clickEvent2() {
    this.status2 = !this.status2;
  }
  clickEvent3() {
    this.status3 = !this.status3;
  }
  clickEvent4() {
    this.status4 = !this.status4;
  }
  clickEvent5() {
    this.status5 = !this.status5;
  }
  clickEvent6() {
    this.status6 = !this.status6;
  }
}

Need to reduce amount of method and variable definition inside the ts file and also in the template file. div tags can be also add dynamically up to max 10 divs...
app.component.html

Widget 1
                            <button class="float-right" type="button">

                                </button>

                      Content

                      Footer

Widget 2
                            <button class="float-right" type="button">

                            </button>

                      Content

                      Footer

Widget 3
                            <button class="float-right" type="button">

                                </button>

                      Content

                      Footer

Widget 4
                            <button class="float-right" type="button">

                                </button>

                      Content

                      Footer

Widget 5
                            <button class="float-right" type="button">

                                </button>

                      Content

                      Footer

Widget 6
                          <button class="float-right" type="button">

                          </button>

                          Content

                          Footer

A: There are two possible ways according to me
first: you can directly change the value in html by calling the required variable on click event
ex:-
(click)="this.status1 = !this.status1"

second: if you want to make function in ts then do like this
ex:-
clickEvent(status): boolean {
    return !status;
  }

and you can use this function of yours in ts as in html:-
(click)="status1 = clickEvent(status1)"
(click)="status2 = clickEvent(status2)"

A: Are the buttons toggle switches? I'm asking because the implementation is like that.
You could use eval :
clickEvent(id) {
eval(`this.status${id} = !this.status${id};`)
}

PS: Notice that the expression in eval is quoted inside |``| and not normal |''|.

A: You can create a event handler with buttonId as parameter and use switch case. Trigger the event handler in html (click)="clickEvent(1)"
.component.html
<button `(click)="clickEvent(1)"`>button1</button>
<button `(click)="clickEvent(2)"`>button2</button>

.component.ts
clickEvent(buttonId : Number){
  switch (buttonId){
    case 1 : {
     this.status1 = !this.status1;
     break;
   }
    case 2 : {
     this.status2 = !this.status2;
   }
   ...
}


text:
Q: What is the tolerance level of SMD resistors? As in normal ceramic and carbon film resistors we can calculate by color codes but nothing mention over the smd components so how to get it? As nothing is ideal so I believe there will be some tolerance level in it also.
please help :)

A: Guessing would put you in a very vague realm. Just looking at a single online catalog and pulling up all of the SMD/SMT resistors that they carry, the tolerances range from 0.01% to 30%, some with differing values of + and - tolerances. The data sheet would be the only real way to know.

A: You can't tell without the datasheet, though there are some hints- usually precision resistors are thin film and look a bit different from thick film. Most consumer products use 5% resistors, some use 1% or better. There are similar size resistors that are 0.1% or even 0.01%, with commensurately better stability and stunningly high price tags (at the low end they are almost free, a reel of 10,000 costing less than a decent lunch, about the cost of a single high precision resistor).
You may be able to tell something from the resistance marking (if any, many smaller parts are not marked at all). If it's made to an E96 series value it's 1% or better, but it's also possible a 2.7K resistor could be 1% tolerance. If it is marked with the 3 character alphanumeric code it's 1% or better.
There are a lot of other things you don't know without a part number, manufacturer and datasheet/manual- the rated power dissipation, the maximum voltage, the temperature coefficient, the rated stability and so on. Tolerance is just one more unknown.


text:
Q: react-native-router-flux: How to prevent Tab Scene history stack from being reset when changing between tabs? I have a Router setup with 2 tab scenes:

*

*Tab 1: have 2 navigable scenes (static screens);

*

*Screen A: have a button to navigate to Screen B;

*Screen B: just have a text;

*Tab 2: just have 1 static screen.

*

*Screen C: just have a text;

The code is as follows.
app.js:
import React from 'react';
import { Router, Scene } from 'react-native-router-flux';
import Tab from '../tab';
import ScreenA from './a';
import ScreenB from './b';
import ScreenC from './c';

export default class App extends React.Component {
  render(){
    return (
      <Router>
        <Scene key="root">
          <Scene key="tabbar" tabs={true}>

            <Scene key="tab1" title="Tab 1" icon={Tab}>
              <Scene key="a" title="Screen A" component={ScreenA} />
              <Scene key="b" title="Screen B" component={ScreenB} />
            </Scene>

            <Scene key="tab2" title="Tab 2" icon={Tab}>
              <Scene key="c" title="Screen C" component={ScreenC} />
            </Scene>

          </Scene>
        </Scene>
      </Router>
    );
  }
}

The screens are pretty simple too.
a.js:
export default class ScreenA extends React.Component {
  render(){
    return (
      <View>
        <Text>This is Screen A</Text>
        <TouchableHighlight onPress={() => Actions.b()}>
          <Text>Go to Screen B</Text>
        </TouchableHighlight>
      </View>
    );
  }
}

b.js:
export default class ScreenB extends React.Component {
  render(){
    return (
      <View>
        <Text>This is Screen B</Text>
      </View>
    );
  }
}

c.js:
export default class ScreenC extends React.Component {
  render(){
    return (
      <View>
        <Text>This is Screen C</Text>
      </View>
    );
  }
}

Use case:

*

*The app renders Screen A (in Tab 1);

*Click on button in Screen A: the app navigates to Screen B (still in Tab 1);

*Click on Tab 2: the app navigates to Screen C (in Tab 2).

*Click on Tab 1: the app navigates to Screen A (in Tab 1) and NOT to Screen B, as expected.

react-native-router-flux is not retaining the Tabs' history stack when we get back to them. Or am I doing something wrong here?
Packages versions:

*

*react v15.3.2

*react-native v0.34.1

*react-native-router-flux v3.36.0

A: Turns out this was a bug in react-native-router-flux package, and it was fixed in this pull request.


text:
Q: why is this set NOT open?? (regarding uniform convergence topology) Let $$B([0,1[,R) := \{ f:[0,1[ \rightarrow R:\ f \text{ is a bounded function}\}.$$
Let $$A = \{f: [0,1[ \rightarrow R:\ f\text{ is bounded such that } f(x)<1\text{ for all }x\in [0,1[\}.$$
Considering the topology of uniform convergence, I've proven that $A$ is not closed: The constant function $f(x)=1$ is adherent to $A$ but not in $A$.
But how come is it not open? Can you show me a function in $A$ that's not interior to $A$?
Just to remember, for each $g\in B([0,1[,R)$ and $r > 0$ the neighborhoods are as follows:
$$V(g,r) = \{f\in B([0,1[,R):\ |f(x)-g(x)|< r,\text{ for all }x\in [0,1[\}.$$
thanks!

A: Consider $f(x)=x$. Notice that if you allow for a band of width $r$ then you will allow for functions that go beyond $1$.


text:
Q: How to get missing dates in column of table in SQL Server I have a table with following records
DateIn      TimeIn
----------------------------
2019-02-01  09:31:00.0000000
2019-02-02  09:35:00.0000000
2019-02-04  09:27:00.0000000
2019-02-05  09:34:00.0000000
2019-02-06  09:32:00.0000000
2019-02-09  09:38:00.0000000
2019-02-11  09:35:00.0000000
2019-02-12  15:09:00.0000000
2019-02-13  09:31:00.0000000
2019-02-14  09:35:00.0000000
2019-02-15  09:35:00.0000000
2019-02-16  09:37:00.0000000
2019-02-18  09:33:00.0000000
2019-02-19  09:31:00.0000000

So 2019-02-03,2019-02-07,2019-02-08,2019-02-10,2019-02-17 are missing dates
so I want result in following format
DateIn      TimeIn
----------------------------
2019-02-01  09:31:00.0000000
2019-02-02  09:35:00.0000000
2019-02-03  null
2019-02-04  09:27:00.0000000
2019-02-05  09:34:00.0000000
2019-02-06  09:32:00.0000000
2019-02-07  null
2019-02-08  null
2019-02-09  09:38:00.0000000
2019-02-10  null
2019-02-11  09:35:00.0000000
2019-02-12  15:09:00.0000000
2019-02-13  09:31:00.0000000
2019-02-14  09:35:00.0000000
2019-02-15  09:35:00.0000000
2019-02-16  09:37:00.0000000
2019-02-17  null
2019-02-18  09:33:00.0000000
2019-02-19  09:31:00.0000000

For that I created the function 'GetAllDates' which return all dates between given dates and I used this function in following manner
Select
    TA.DateIn, TA.TimeIn
from
    [ES].[getAllDates]('20190201','20190228') DD
left outer join
    [ES].[tblAttendance] TA on Cast(TA.DateIn as date) = cast(DD.date as date)
where
    TA.PersonId = 21

This query returns the following results:
DateIn      TimeIn
----------------------------
2019-02-01  09:31:00.0000000
2019-02-02  09:35:00.0000000
2019-02-04  09:27:00.0000000
2019-02-05  09:34:00.0000000
2019-02-06  09:32:00.0000000
2019-02-09  09:38:00.0000000
2019-02-11  09:35:00.0000000
2019-02-12  15:09:00.0000000
2019-02-13  09:31:00.0000000
2019-02-14  09:35:00.0000000
2019-02-15  09:35:00.0000000
2019-02-16  09:37:00.0000000
2019-02-18  09:33:00.0000000
2019-02-19  09:31:00.0000000

It is not the correct result.. Please help me to find the solution

A: One easy approach here is to left join a calendar table to your current table on the date, something like this:
WITH dates AS (
    select date from [ES].getAllDates('20190201','20190228')
)

SELECT
    d.date,
    t.TimeIn
FROM dates d
LEFT JOIN [ES].[tblAttendance] t
    ON d.date = t.DateIn and t.PersonId = 21
ORDER BY
    d.date;

The answer by @PSK might work, assuming that your tblAttendance table actually already has data for every date present.  If it doesn't, then just moving the WHERE restriction to the ON clause might still leave some holes in the dates present.

A: Move your WHERE query with the LEFT JOIN if you want to get NULL records.
SELECT TA.datein,
       TA.timein
FROM   [ES].[Getalldates]('20190201', '20190228') DD
       LEFT OUTER JOIN [ES].[tblattendance] TA
                    ON Cast(TA.datein AS DATE) = Cast(DD.date AS DATE)
                       AND TA.personid = 21

A: First create your date records, then make left join with your current record.
    GO

        DECLARE  @arrival_date date = '2019-01-01',
             @leaving_date date = '2019-02-01'

    ;WITH DD AS (
    SELECT @arrival_date as date_
    UNION ALL
    SELECT CAST(DATEADD(day,1,date_) as date)
    FROM DD
    WHERE date_ < @leaving_date
    )
    select DD.date_ as DateIn,  TA.TimeIn as TimeIn from DD LEFT OUTER JOIN [ES].[tblattendance] TA
                ON Cast(TA.datein AS DATE) = Cast(DD.date_ AS DATE)
                   AND TA.personid = 21

    GO


text:
Q: Mikrotik: HowTo pre-define static leases in DCHP-server I would like to replace my current router by a Mikrotik (v6.48.3). In order not to mess up my network, I would like to pre-set the IP addresses the DHCP clients will get from the server. I do not find such an example, does anybody know how to do it? I have a list of IPs and MACs in a file, so I would appreciate CLI commands, I do not like clicking the mouse button so much ;-)
THX for your answers!
Christof

A: You can check out the lease sub-menu of the Mikrotik dhcp-server lease configuration, e.g.:
/ip dhcp-server lease add address=192.168.0.23 mac-address=b6:c2:55:41:bb:14 ...


text:
Q: Does Bootcamp still result in a hybrid MBR/GPT situation? I am running Mojave still (if that matters, but could update to Catalina), and want to dual-boot Windows 10 for the odd occasion when i need to run a program that is windows only.. or debug something.. but crucially don't want to virtualise.
Not being a massively experienced macOS user (only switch this past year), i've read that bootcamp does some funky things with the partition table, resulting in a MBR/GPT hybrid? Is this still the case? Even though Windows 10 has been UEFI for ages now?
I was planning to simply do a UEFI boot from a USB drive with Windows 10 it, and go from there... will i struggle with drivers without Bootcamp, and is that partition still going to be available in something like parallels though?
Thanks in advance!

A: Based on the information in your question, Windows 10 UEFI boots on your model Mac. Most users use the Boot Camp Assistant to install Windows 10. You do not have to use the Boot Camp Assistant, however the easiest way to download the Windows Support Software (the drivers) is to use the Boot Camp Assistant. Once you have the Windows Support Software, you can install using a flash drive if you wish.

You can use the Boot Camp Assistant to download the Windows Support Software without actually creating a partition and installing Windows.

You will not need hybrid partitioning to run Windows 10 on your Mac. This is true whether or not you use the Boot Camp Assistant to install.


text:
Q: Starlette + asyncio.create_task() doesn't log error if task object is stored in instance variable Okay, this is very weird, but here goes -
import asyncio

from starlette.applications import Starlette

class MyTasks:
    def __init__(self):
        self.task = None

    async def main(self):
        self.task = asyncio.create_task(self.hello())

    async def hello(self):
        raise ValueError

async def main():
    await MyTasks().main()

app = Starlette(on_startup=[main])

$ uvicorn test:app
INFO:     Started server process [26622]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

Hmm, no ValueError here...

Now, remove the assignment to self.task in MyTasks.main().
    async def main(self):
        asyncio.create_task(self.hello())
    ...

$ uvicorn test:app
INFO:     Started server process [29083]
INFO:     Waiting for application startup.
ERROR:    Task exception was never retrieved
future: <Task finished name='Task-3' coro=<MyTasks.hello() done, defined at ./test.py:13> exception=ValueError()>
Traceback (most recent call last):
  File "./test.py", line 14, in hello
    raise ValueError
ValueError
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

... And voila.

What's going on here? How does that assignment make or break the exception logging!?

A: A task is a subclass of future, which means that it has the concept of a result. In case of a task, the result is the value returned by the coroutine it drives. If the coroutine raises an exception, then the exception is encapsulated in the task object. Correctly written code is expected to eventually either await the task or access its result, in order for exceptions not to pass silently.
To help debug code that forgets to access the task, task's destructor logs an error if the task raised an exception but was never awaited. This error cannot be logged before running the destructor because as long as your code holds on to the task object, it might conceivable await it at any point. The point when the destructor runs is the first instance when Python can reliably "prove" that the task is unawaited.
But this last-ditch logging is not something you should rely on, it's provided on a best-effort basis. For example, running the destructor can be postponed due to GC. I expect that assigning the task to an instance whose bound method is being driven by the task makes the task part of a reference cycle. This postpones running the destructor until a full GC, and you don't see the log.
To fix the problem, you should either catch the exceptions in your coroutine and log them yourself instead of allowing them to propagate, or actually await the task at some point in your code.

A: Sorry, this was a dupe of this other question.
A drop-in replacement to asyncio.create_task() has been posted there.

Here's the output, after using the replacement create_task()
Case 1: With await self.task
$ uvicorn test:app
INFO:     Started server process [33213]
INFO:     Waiting for application startup.
ERROR:    Traceback (most recent call last):
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/starlette/routing.py", line 517, in lifespan
    await self.startup()
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/starlette/routing.py", line 494, in startup
    await handler()
  File "./test.py", line 35, in main
    await MyTasks().main()
  File "./test.py", line 27, in main
    print(await self.task)
  File "./test.py", line 13, in wrapper
    return await task
  File "./test.py", line 30, in hello
    raise ValueError
ValueError

ERROR:    Application startup failed. Exiting.

Case 2: Without await self.task
$ uvicorn test:app
INFO:     Started server process [32627]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
ERROR:    Exception in callback <function create_task.<locals>.on_done at 0x10c519550>
handle: <Handle create_task.<locals>.on_done created at /Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py:382>
source_traceback: Object created at (most recent call last):
  File "/Users/dev/.virtualenvs/server-99338def/bin/uvicorn", line 8, in <module>
    sys.exit(main())
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 764, in __call__
    return self.main(*args, **kwargs)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 717, in main
    rv = self.invoke(ctx)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py", line 331, in main
    run(**kwargs)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py", line 354, in run
    server.run()
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py", line 382, in run
    loop.run_until_complete(self.serve(sockets=sockets))
Traceback (most recent call last):
  File "uvloop/cbhandles.pyx", line 70, in uvloop.loop.Handle._run
  File "./test.py", line 9, in on_done
    fut.result()
  File "./test.py", line 30, in hello
    raise ValueError
ValueError