text:
Q: Что не так с порядком добавления элементов в GridPane? (JavaFX) Здравствуйте.
Есть метод, генерирующий аналог таблицы с использованием GridPane:
private GridPane createTable(ObservableList<String> headers, int matrix_size){
    GridPane table = new GridPane();
    table.getStyleClass().add("table_design");
    table.setGridLinesVisible(true);
    table.setVgap(0);
    ObservableList<Label> labels = FXCollections.observableArrayList();
    ObservableList<Label> labelsVertical = FXCollections.observableArrayList();
    for(int i = 0; i < matrix_size; i++){
        Label label = new Label(headers.get(i));
        label.setPadding(new Insets(0));
        label.getStyleClass().add("labels_headers");
        labels.add(label);

        Label labelVertical = new Label(headers.get(i));
        labelVertical.setPadding(new Insets(0));
        labelVertical.getStyleClass().add("labels_headers");
        labelsVertical.add(labelVertical);
    }

    TextField[][] textFields = new TextField[matrix_size][matrix_size];
    for(int i = 0; i < matrix_size; i++){
        for (int j = 0; j < matrix_size; j++){
            TextField textField = new TextField();
            if(i == j){
                textField.setText("1");
                textField.setEditable(false);
            }
            textField.setMinWidth(5);
            textField.setAlignment(Pos.CENTER);
            textFields[i][j] = textField;
        }
    }

    for(int i = 0; i < matrix_size; i++){
        for(int j = 0; j < matrix_size; j++){
            if(i == 0 && j == 0){
                continue;
            }
            if(i == 0){
                table.add(labels.get(j - 1), j, i);
                System.out.println("Label added to " + j + ", " + i);
                GridPane.setHalignment(labels.get(j - 1), HPos.CENTER);
                if(j == matrix_size - 1){
                    table.add(labels.get(j), j + 1, i);
                    System.out.println("Label added to " + (j + 1) + ", " + i);
                    GridPane.setHalignment(labels.get(j), HPos.CENTER);
                }
            }
            if(j == 0){
                table.add(labelsVertical.get(i - 1), j, i);
                System.out.println("LabelV added to " + j + ", " + i);
                if(i == matrix_size - 1){
                    table.add(labelsVertical.get(i), j, i + 1);
                    System.out.println("LabelV added to " + j + ", " + (i + 1));
                }
            }
            if(i != 0 && j != 0){
                table.add(textFields[i - 1][j - 1], j, i);
                System.out.println("TextField added to " + j + ", " + i);
                if(i == matrix_size - 1){
                    table.add(textFields[i][j - 1], j, i + 1);
                    System.out.println("TextField added to " + j + ", " + (i + 1));
                }
                if (j == matrix_size - 1) {
                    table.add(textFields[i - 1][j], j + 1, i);
                    System.out.println("TextField added to " + (j + 1) + ", " + i);
                }
                if(i == matrix_size - 1 && j == matrix_size - 1){
                    table.add(textFields[i][j], j + 1, i + 1);
                    System.out.println("TextField added to " + (j + 1) + ", " + (i + 1));
                }
            }
        }
    }
    return table;
}

Нужно, чтобы метки и текстовые поля добавлялись в таком порядке: метка, и до конца строки текстовые поля. Кроме первой строки, естественно.
Работает корректно, за исключением того, что в последних двух строках порядок следующий: метка первой строки, метка второй строки, текстовое поле первой строки, текстовое поле второй строки и т. д., до конца итерации цикла.
Никак не могу понять, почему?


text:
Q: EF Best practices - Shadow Properties I generally create a domain model and use data annotations/explicit foreign key relationships in that domain model to define how the database is created.  To me, this makes certain rules (like max length or required) clear and in one place.
I was going through a code review and one part of the feedback was to not do either of those things.  They recommended I do everything in the configuration for each model using Fluent API/shadow properties instead so that all database generation code is in one place and that the model stays clean and only concerns itself with the domain alone.
As an example, I updated my code to something similar to this:
public class Blog
  {
    private HashSet<Comment> comments;
    public IReadOnlyCollection<Comment> Comments => comments;
    public string Title {get; private set;}
    public string Content {get; private set;}
    public Core.Constants.Blog.Categories Category {get; private set;}

    public Blog(string title, string content, Core.Constants.Blog.Categories category)
    {
      Id = Guid.NewGuid().ToString("D");
      comments = new HashSet<Comment>();
      Title = title;
      Content = content;
      Category = category;
    }
  }

public class Comment{
    private string Id {get; private set;}
    public string Identifier { get; private set; }
    public string Description { get; private set; }

    public Comment(string identifier, string description)
    {
      Id = Guid.NewGuid().ToString("D");
      Identifier = identifier;
      Description = description;
    }
}

and added fluent configuration code with:
internal class BlogConfiguration : IEntityTypeConfiguration<Domain.Blog>
  {
    public void Configure(EntityTypeBuilder<Domain.Blog> builder)
    {
      builder.ToTable("Blog");

      builder.HasKey("Id").HasName("PK_Blog");

      builder.Property(res => res.Title)
            .IsRequired();

      builder.Property(res => res.Content)
            .IsRequired();

      builder.Metadata
          .FindNavigation(nameof(Domain.Blog.Comments))
          .SetPropertyAccessMode(PropertyAccessMode.Field);

      builder.Property(blog => blog.Category)
             .HasConversion(value =>
                                  value.ToString(),
                                  convertedValue => Enum.Parse<Core.Constants.Blog.Categories>(convertedValue));

    }
  }

   internal class CommentConfig : IEntityTypeConfiguration<Domain.Comment>
  {
    public void Configure(EntityTypeBuilder<Domain.Comment> builder) {
      builder.ToTable("Comment");

      builder.HasKey("Id").HasName("PK_Comment");

      builder.Property(asset => asset.Identifier)
            .HasMaxLength(25)
            .IsRequired();

      builder.Property(asset => asset.Description)
           .HasMaxLength(250);

      builder.HasIndex(asset => asset.Identifier).IsUnique();
    }
  }

My questions are:

*

*In my actual project, I need a navigation property filled from "Comment" back to "Blog".  Is it bad to add an explicitly navigation property on Comment that points back to Blog that is ignored in the fluent configuration?

*Is using Data Annotations on the domain model really that bad of a practice?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generate stream delayed from list As indicated in the title, I want to generate stream from list, but the list need a large performance cost, and the stream may not be really used.
Something I need is like this:
Stream<T> stream = Stream.fromList(() -> calculateList(...))
    .filter(...)
    .map(...)
    // TODO
    ;

//#region some case why I want delayed stream instead of other way.

if (condition$1) {
    // that is why I don't want to re-order those code.
    stream.forEach(...);
    return;
}

var something$1 = ...; // that should only execute after the condition$1 not passed.

if (condition$2) {
    // that is why I don't want to use `Supplier<Stream<T>>`.
    stream = stream.concat(Stream.fromList(() -> calculateOthList(...)));
}

var something$2 = ...;

if (condition$3) {
    // that is why I dont want to use `Stream<Supplier<Stream<T>>>` (and what's more, it not easy to read).
    stream = stream.filter(...).peek(...);
}

... // as you see, the most important thing of those code is to deal the stream, it's data-driven.
//#endregion

// TODO may be return if some condition not passed.
// TODO and even worse, some exception may be throw.

stream.forEach(...); // TODO really use the stream.

Is there any built-in methods to do that? or maybe any way to implement elegantly?

A: You can create a Spiliterator from a Supplier and get a Stream back which makes your Stream creation lazy. For example:
 Supplier<Spliterator<Integer>> supplier = () -> calculateList(...).spliterator();
 Stream<Integer> stream = StreamSupport.stream(supplier, Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED, false);

A: Probably the simplest thing is to replace your Stream with a Supplier<Stream> e.g.
Supplier<Stream<T>> stream = () -> Stream.fromList(() -> calculateList(...));

but if you can't do that, you can implement a lazy Stream like this:
Stream<T> lazyStream = Stream.<Supplier<List<T>>>of(() -> calculateList())
            .map(Supplier::get)
            .flatMap(List::stream);

A: In this situation you really need to provide a Supplier. The Supplier will evaluate your list populating method when you want it. There are two ways to achieve this:
   Supplier<T> streamSupplier = () -> calculateList(...).stream();
   // other code
   // then use it
   streamSupplier.get().forEach(...);

Or maybe you really want a stream, so might do something like this:
   Stream<Supplier<Stream<T>> streamOfStreamSuppliers = Stream.of(() -> calculateList().stream());
   // other code
   // then use it by unpacking the supplied stream
   // and then flatmapping that
   streamOfStreamSuppliers.map(Supplier::get)
       .flatMap(Function.identity())
       .forEach(...);

This has the side effect of allowing you to put multiple streams into the mix.
The bigger question, though, is why you don't reorganise your code so that your stream is created when it's first needed?

A: You could do it like this.
        List<Integer> list = List.of(1,2,3,4,5,6);
        Function<List<Integer>,Stream<Integer>> fnc = a->a.stream().filter(b->b%2 == 0).map(b->b*20);

        fnc.apply(list).forEach(System.out::println);

In your case it could be
       fnc.apply(calculateList(...)).forEach(....);


text:
Q: df data does not match fdisk data in LUKS encrypted partition I'm having issues trying to understand a LUKS encrypted setup at work in Ubuntu. It was done by someone before me with Ansible and roughly the process is as follows:
create a sparse file with DD
dd of=/root/encfs bs=1 count=0 seek=40G
format LUKS partition
cryptsetup -y luksFormat /root/encfs
open encrypt file
cryptdisks_start datafs
create filesystem
mkfs.ext4 -j /dev/mapper/datafs
mount partition:
mount /dev/mapper/datafs /data
The sparse file seems to be in a disk 30G but I think that somehow is actually on another disk which is 64G. I'm trying to change the size of that encrypted volume and I successfully made bigger the sparse file but df still shows it is 40G
Does anyone know how can I:
 - first, make sure the partition is on the disk I think it is
 - secondly, make use of the whole disk so the partition is 64G?
 - bonus question: is the sparse file really necessary?
I've tried deleting /root/encfs and recreating it, reformating the image path but none worked.
Any pointers/help would be highly appreciated as I couldn't find any help online.
Many thanks

A: What you are seing is the sparse property of a sparse file: Only those parts of the file, that have been written at least once, will actually be allocated on disk.
The part, that is not (yet) allocated on disk is not yet actually used, so it doesn't show up on du or df
As an example: This is what I just did on my Ubuntu PC:
~$ df -h .
Filesystem                Size  Used Avail Use% Mounted on
/dev/mapper/payload-home  2.8T  540G  2.1T  21% /home

~$ dd if=/dev/zero of=./test.sparse bs=1 count=0 seek=5000G
0+0 records in
0+0 records out
0 bytes copied, 0.00022495 s, 0.0 kB/s

~$ ls -lh test.sparse
-rw-r--r-- 1 me me 4.9T Apr 29 17:23 test.sparse

~$ du -h test.sparse
0   test.sparse

~$ df -h .
Filesystem                Size  Used Avail Use% Mounted on
/dev/mapper/payload-home  2.8T  540G  2.1T  21% /home

So: While the disk has 2.1T free, I can easily create a 5T sparse file, which will show up as using zero bytes and no changes to df
If I were to populate that file, I would receive a "no space left on device" message after writing a touching over 2TB of blocks.
To answer your direct questions: df -h /path/to/file will tell you which partition or volume the file is on and how much space there is on that partition.


text:
Q: Group rows with number ranges in Access 2000 SQL? I have this picture with my two columns:

"povrsina" is area size in square meters. It can be classified in ranges, for example (0 < povrsina <= 10), (10 < povrsina <= 30), (30 < povrsina <= 60) etc...
"tipprod" can have textual values like "01", "05", "09", "04" etc...
I need to group all data I have by "povrsina" but in the given ranges.
I have created helper table in access which looks like this:

You can see the ranges. I tried it with my main table but I am not sure if I get correct results. Is it really checking "povrsina" value against the range in my helper table?
How can I do this in Access 2000?

A: You can add two fields to your guide table with povrsina_min, povrsina_max to define your ranges:
povrsina_tag|povrsina_min|povrsina_max
10          |0           |10
30          |11          |30
....

Then you can do a query with a CROSS JOIN against your guide table adding a where clase with
    povrsina <= povrsina_max and povrsina >= povrsina_min
And then you can GROUP BY povrsina_tag and tipprod.

A: Just guessing... Can you try something like this?
select MainTable.Povishnina as [Povishnina], count(*) as [number of occurences]
from (
  select case
    when score between 0 and 10 then ' do 10 m2'
    when score between 30 and 50 then ' od 11 do 30 m2'
    else 'Nad 3000 m2'
  from scores) MyTable
group by MainTable.Povishnina

In general, take a look at this question:
In SQL, how can you "group by" in ranges?

A: In an Access query you can use:
Select
    *,
    (Select Top 1 T.PovrsinaM2 From T13_Povrshina As T
    Where T.povrsina <= YourTable.povrsina
    Order By T.povrsina Desc)
From
    YourTable

You will have to adjust T13_Povrshina slightly.


text:
Q: Able to select from table, but not count rows I've been running a tiny MySQL db for a throwaway project, and dumped the file for a coworker, who was able to get everything running.
We're using C#, and running two queries, one of which does:
SELECT * FROM someview LIMIT 20 OFFSET 0;

and the other does:
SELECT COUNT(*) FROM someview;

I would be using SELECT SQL_CALC_FOUND_ROWS * and FOUND_ROWS(), but that's apparently not supported outside of stored procs with the MySQLDataReader.
Anyway, the problem is, both queries work fine on my system. On his, the first works just fine, but the SELECT COUNT(*) statement fails with the following error:
Error Code: 1356. View 'db.someview' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them

We checked the results of SHOW GRANTS, and have identical permissions, both running as the same user (root). It's not a C# problem, because the exact same thing happens if he runs it in the MySQL command line or Workbench.
He's also able to issue SELECT COUNT(*) queries successfully against any other table or view in the DB, including a view that the first view depends on. It's just this one particular view, where he can SELECT *, but not SELECT COUNT(*).
Has anyone else experienced anything similar?
Server version: 5.5.29 MySQL Community Server (GPL)
EDIT: Here are the two view creation scripts, stripped down to the relevant parts that still have the problem, based on Evan Miller's How Not To Sort By Average Rating.
CREATE VIEW
    product_rating_counts
AS
SELECT
    p.id AS productId,
    sum(case when (r.rating = 1) then 1 else 0 end) AS 1_star,
    sum(case when (r.rating = 2) then 1 else 0 end) AS 2_star,
    sum(case when (r.rating = 3) then 1 else 0 end) AS 3_star,
    sum(case when (r.rating = 4) then 1 else 0 end) AS 4_star,
    sum(case when (r.rating = 5) then 1 else 0 end) AS 5_star,
    sum(case when (r.rating < 3) then 1 else 0 end) AS negative_ratings,
    sum(case when (r.rating > 3) then 1 else 0 end) AS positive_ratings,
    sum(case when (r.rating = 3) then 1 else 0 end) AS neutral_ratings
FROM
    product p
INNER JOIN
    review r
ON
    p.id = r.productId
GROUP BY
    p.id;

CREATE VIEW
    ranked_products
AS
SELECT
    p.id AS ID,
    p.SKU AS SKU,
    p.Name AS Name,
    prc.1_star,
    prc.2_star,
    prc.3_star,
    prc.4_star,
    prc.5_star,
    prc.positive_ratings AS Positive,
    prc.negative_ratings AS Negative,
    prc.neutral_ratings AS Neutral,
    ((prc.positive_ratings + 1.9208) / (prc.positive_ratings + prc.negative_ratings) -
               1.96 * SQRT((prc.positive_ratings * prc.negative_ratings) / (prc.positive_ratings + prc.negative_ratings) + 0.9604) /
                      (prc.positive_ratings + prc.negative_ratings)) / (1 + 3.8416 / (prc.positive_ratings + prc.negative_ratings))
    AS ci_lower_bound
FROM
    product p
INNER JOIN
    product_rating_counts prc
ON
    p.id = prc.productId
WHERE
    (prc.positive_ratings + prc.negative_ratings) > 0
ORDER BY
    ci_lower_bound DESC;

So what's working for me is:
SELECT * FROM ranked_products LIMIT 20 OFFSET 0;
SELECT COUNT(*) FROM ranked_products;

But for my coworker, the first query returns just fine, while the second gives him the invalid tables/columns/permissions error.
We're probably going to scrap this anyway, but I hate not knowing why something's not working.

A: A quick search yields the following results:
This documented bug#59005 (5.1.36-5.5.9) happens when there is NULL in the result set in the view
While this bug#60295 (5.1.57-5.6.3) happens when tables in the view have the same column name
On the other hand, this link suggests that you could be running into a variation of bug#33000 (5.0-5.6.6) and that a viable solution is to run FLUSH TABLES
Another solution to try can be found here: Views and Privileges

A: SELECT *, COUNT(*) as `totalcount` FROM ranked_products LIMIT 20 OFFSET 0;


text:
Q: Shopify: Global variable data type I'm having an unbelievable amount of difficulty finding out the data type of a global variable in Shopify. My problem could be a matter of scope, but it still shouldn't be difficult for them to tell me a data type. Their tech support says the theme writer should answer it and the theme writer says that Shopify should answer it. IMHO, either of them should be able to answer it. So I would greatly appreciate any wisdom you can provide.
My client is a wholesaler who does not do orders less that $50.00. It should be fairly easy to run a comparison in the variable for the total order (cart.total_price | money_with_currency), but my code is entirely unsuccessful. The code should also allow a retailer to change their order and run the comparison again. I have added every possible combination of parenthesis to the variable and pieces, in case I have a syntax error.

          {% if cart.total_price | money_with_currency < 50 %}

Your order must be at least $50.00

          {% endif %}

          {% if cart.total_price | money_with_currency > 50 %}
              <input class="button nice" type="submit" value="{{settings.checkout_text}}" name="checkout" />
                {% if additional_checkout_buttons %}
                  or
                  {{ content_for_additional_checkout_buttons }}
                {% endif %}
            {% endif %}

A: See the Shopify docs on money filters. The money_with_currency filter may output something like "$1.45 CAD". Maybe try money_without_currency, which formats the price as a decimal.
EDIT:
Looks like money_without_currency doesn't work. The code below causes Liquid error: comparison of String with 50 failed:
{% assign total_price = cart.total_price | money_without_currency %}
{% if total_price < 50 %} ... {% endif %}

So, you have 2 options. First, you could convert the output of money_without_currency to a number like this:
{% assign total_price = cart.total_price | money_without_currency | times: 1 %}

Or, compare against cart.total_price without a filter (add 2 zeros because cart.total_price does not have a decimal place, so $50.00 is 5000 if not formatted with a money filter):
{% if cart.total_price < 5000 %} ... {% endif %}


text:
Q: How to add OAuth connection settings without Azure Bot Service? I'm adding authentication to a bot built with Bot Framework SDK v4 (C#) that will work with Microsoft Teams. I've been following add authentication and add SSO tutorials, trying to get it to work. Both of these hyperlinks jump to a requirement I am stuck on, which is to add OAuth connection settings through the Azure Bot Service. I don't have a subscription with Azure and would prefer to avoid it. I just don't want to deal with a subscription to all these services when I need a tiny portion of it. I'm also going to publish the bot on a local server, not to Azure, and I'm pretty sure I only need a standard channel, which should be free.
The tutorials also explain that I need to use Azure Bot Service to generate a Microsoft app id and an app password. It turns out those values can be obtained through a normal app registration, which I need anyways, in Azure AD. They are just app Id and client secret. This is making me wonder if that OAuth connection setting can be created outside of an Azure subscription as well.
As of now, running the 46.teams-auth sample throws me an error explaining that I need a valid connectionName which is obtained by creating an OAuth connection setting.
All I'm trying to do is to implement authentication to a bot that will be used in Teams. So my questions are the following:

*

*What even is the OAuth connection setting and is it necessary to create?

*Is it not enough to register the bot application in Azure AD? It's just an API.

*Is there any way to create the OAuth connection setting outside of an Azure subscription?

I've already used the Developer Portal, Azure AD, Bot Framework website, and ngrok to successfully test my bot in Teams. Adding authentication is the last step.


text:
Q: How to blackout screen or start screensaver with shortcut keys? I'm often reading a hardcopy paper/book and taking notes on the laptop.  I like to save energy (and battery) when the laptop is just waiting for me to read.  My laptop unfortunately doesn't have a function key that blacks out the screen (which my previous laptop had, such a great idea) --not to mention that my function keys don't work with Ubuntu anyways.
As simple as this is, I haven't found the optimal solution: How do I blackout the screen (or start a screensaver, that's fine, too) with a shortcut key combination?  I would really like to avoid loading an application to RAM (at startup).  This should be a simple function that can be performed on demand.  But, if you are strongly convinced that there is no way, then please be kind enough to state that so I can go figure out how to do this with xscreensaver or whatever.
Note that I'm not trying to lock the screen.  Indeed, I'm trying to avoid locking the screen so that I don't have to keep on typing my password everytime I want to start the screen to take a note.
I'm on Ubuntu 13.04 64-bit with a Toshiba Satellite L830-135.

A: Use the gnome-screensaver-command. Read the man page (man gnome-screensaver-command) to learn about other features.
For example, to simply blackout the screen (without locking) in a terminal run:
 gnome-screensaver-command -a

Now you just need to add this command as a custom shortcut under the Keyboard settings.


text:
Q: setVisibility(View.INVISIBLE) not working on first row of ListView setVisibility(View.INVISIBLE) is not working on first row of ListView when Listview is created. But when I scroll down and scroll up, it's working fine
MY CODE:
public class AudioListAdapter extends ArrayAdapter<GalleryItem>{

    private Context context;
    private int layoutResourceId;
    private ArrayList<GalleryItem> data = new ArrayList<GalleryItem>();
    private ArrayList<Boolean> isPlaying = new ArrayList<Boolean>();
    boolean isPlaying1;
    final MediaPlayer mediaPlayer = new MediaPlayer();

    public AudioListAdapter(Context context, int resource, ArrayList<GalleryItem> data) {
        super(context, resource, data);
        this.layoutResourceId = resource;
        this.context = context;
        this.data = data;
        Iterator<GalleryItem> iterator = data.iterator();
        while (iterator.hasNext()) {
            GalleryItem galleryItem = (GalleryItem) iterator.next();
            isPlaying.add(false);
        }
        //notifyDataSetChanged();
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        //return super.getView(position, convertView, parent);
        final ViewHolder holder;
        //View row = convertView;

        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(layoutResourceId, parent, false);

            holder = new ViewHolder();

            holder.playImage = (ImageView) convertView.findViewById(R.id.audio_play_image);
            holder.stopImage = (ImageView) convertView.findViewById(R.id.audio_stop_image);
            holder.title = (TextView) convertView.findViewById(R.id.audio_title);
            holder.duration = (TextView) convertView.findViewById(R.id.audio_duration);
            isPlaying.set(position, false);
            //convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
            LogUtils.d("TEST", holder.title.getText().toString());
        }

        final GalleryItem item =  data.get(position);
        System.out.println(item.getDateModified());

        holder.title.setText(item.getTitle());
        holder.title.setSelected(true);
        holder.duration.setText("00:00");
        if (isPlaying.get(position)) {
            holder.playImage.setVisibility(View.INVISIBLE);
            holder.stopImage.setVisibility(View.VISIBLE);
        }else{
            holder.playImage.setVisibility(View.VISIBLE);
            holder.stopImage.setVisibility(View.INVISIBLE);
        }

        OnClickListener audioControlsListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (isPlaying.get(position)) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                    }
                    mediaPlayer.reset();
                    isPlaying.set(position, false);
                    holder.playImage.setVisibility(View.VISIBLE);
                    holder.stopImage.setVisibility(View.INVISIBLE);
                }else{
                    holder.playImage.setVisibility(View.INVISIBLE);
                    holder.stopImage.setVisibility(View.VISIBLE);
                    for(int i=0 ; i< isPlaying.size();i++){
                        isPlaying.set(i, false);
                    }
                    try {
                        mediaPlayer.reset();
                        mediaPlayer.setDataSource(item.getPath());
                        mediaPlayer.prepare();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.start();
                    isPlaying.set(position, true);
                    notifyDataSetChanged();
                }
            }
        };
        holder.playImage.setOnClickListener(audioControlsListener);
        holder.stopImage.setOnClickListener(audioControlsListener);
        convertView.setTag(holder);
        return convertView;
    }

    static class ViewHolder{
        TextView title;
        TextView duration;
        ImageView playImage;
        ImageView stopImage;

    }
}

A: Still setVisibility(View.INVISIBLE) not working. But I used only one ImageView and replaced the image when required.This worked for me.


text:
Q: How to get message tracking logs from Office 365? Any APIs? How can I get message tracking logs from Office 365? Will Graph API or PowerShell work? Is there any other solution, like auto forwarding or any other option?

A: There are two ways to track messages in Office 365 – PowerShell and EAC.
You can use PowerShell to search through message tracking logs on on-premises servers as well as to trace messages in Exchange Online.
And although the experience is somehow similar, there are some differences worth mentioning.
On-prem Exchange did not allow message tracking via Exchange Admin Center. In Office 365, EAC enables message tracing and offers quite a comfortable experience.
Please see this link:
Message tracking in Office 365 (Exchange Online)


text:
Q: How to send image in email body Android I am working on an android application which sends email (texts and images) to gmail, yahoo and other mail services. The version i am using is android 2.2 and it is compatible with 2.2 and above. I want to send images in the mail compose body section. I have tried doing so but whenever I sent mail either the images won't come or a small box is displayed in the mail body. I have searched many websites but did not get enough help. Please help me out with this. I don't want to send the images as an attachment. I want to send both text and images in the mail compose body itself. Looking forward to a quick and positive response from you guyz as soon as possible

A: The solution I would use if i don't want to send the images as attachments, is to upload the images to some location on a webserver, then put the images in the email body as image html controls with src pointing to the images urls on the web server.


text:
Q: Finding ordered basis of two vector spaces Let $K$ a field and $E, F$ two $K$-vector spaces with ordered basis $B_1 = (e_1, e_2, e_3, e_4)$ and $B_2=(v_1,v_2,v_3)$ respectively. Given $f:E\rightarrow F$ the only linear map such that:
$\\f(e_1)=v_1-v_3,\\f(e_2)=v_1+v_2+v_3,\\f(e_3)=3v_1+2v_2,\\f(e_4)=2v_1-v_2-2v_3,$
How can I find a basis $D_1,D_2$ of $E$ and $F$ such that $M(f,D_1,D_2)=\left( \begin{array}{cccc} 1 & 1 & 1 & 1 \\ 1 & 2 & 3 & 4 \\1 & 4 & 9 & 16\end{array} \right)$?

A: You have many degree of freedom, so there is not a unique solution. In fact you are looking for two change of basis in dimension $4$ and $3$, so you need a non-singular $4x4$ and a non-singular $3x3$ matrix: $16+9=25$ unknown.
The equation to impose are only $12$ ($4$ vectorial equations in dim $3$).
We can use the freedom to leave the basis of $F$ as is, and only change the basis in $E$. If
$$
e'_i=e_jA_{ji}
$$
is the change of basis relation, the equations
$$
f(e'_i)=f(e_j)A_{ji}=v_k M_{kj}A_{ji}=v_k M'_{ki}
$$
gives
$$
MA=M'
$$
The general solution of this system of equations is
$$
A=\begin{pmatrix}
-5a   & -5b   & -5c+2  & -5d+6 \\
-3a+1 & -3b+4 & -3c+11 & -3d+22 \\
 2a   &  2b-1 &  2c-4  &  2d-9 \\
  a   &   b   &   c    &   d
\end{pmatrix}
$$
where $a, b, c, d$ are free parameters, to be chosen with the condition
$$
|A|=2a-6b+6c-2d\neq0.
$$
For example, letting $a=c=1$ and $b=d=-1$ we have
$$
A=\begin{pmatrix}
-5 &  5 & -3 &  11 \\
-2 &  7 &  8 &  25 \\
 2 & -3 & -2 & -11 \\
 1 & -1 &  1 &  -1
\end{pmatrix}
$$
We can check that with $e'_1=e_1 A_{11}+e_2 A_{21}+e_3 A_{31}+e_4 A_{41}=-5e_1-2e_2+2e_3+e_4$ we have
\begin{align}
f(e'_1)&=-5f(e_1)-2f(e_2)+2f(e_3)+f(e_4)\\
       &=-5(v_1-v_3)-2(v_1+v_2+v_3)+2(3v_1+2v_2)+(2v_1-v_2-2v_3)\\
       &=v_1+v_2+v_3
\end{align}
and similarly for $f(e'_i)$, with $i=2,3,4$.


text:
Q: Can we have multiple validations in a HTML form? I'm new in HTML and I want to have two types of validation for a single constant. For example, for "name" I want it to be required and also start with an Uppercase letter, with a maximum length and minimum length. Can I put two < input > lines in my html or will it give me an error?
Example of my Code:

                <input type="text" id="name" name="name" class="form-control validate">

                Name
                 <input type="text" id="name" name="name" required>
                 <input type="text" name="name" pattern="[A-zA-Z]{3,30}">
                     *

I am also looking for email validation, i only want to allow @gmail and @yahoo format.. I've been googling for hours but I can't find it, could someone help me with that as well?


text:
Q: load() responds correctly, but html not loaded into div I have an AJAX request to post-bid.php that is the result of this call:
$('#alert-container').load("post-bid.php", data);

According to firebug, this AJAX request returns the following code:

I have this line of code above load() line:

Yet no HTML is loaded into this div. Any ideas?
SOLUTION: I simply needed to return data to the callback function of load().

A: If the content you receive is:

Your div is empty because you did not receive any Html but only the script content, which is stripped out before the content is passed to the .html() of the target element.
Did you expect the script content to be rendered in the #alert-container div or did you expect for the script to execute during the .load() request?
Edit

What's a good way to make an alert conditionally pop up, based on some
  php that's run in the AJAX request?

According to the load() http://api.jquery.com/load/, it seems you could use the callback to assert the return value and then pop up the alert if the call was successful.   The success callback is executed after any html which is returned is rendered into the target element.
$('#alert-container').load("post-bid.php", data, function(responseText, textStatus, XMLHttpRequest){
    // textStatus = 'success' if the call was successful.
    if(textStatus == 'success'){
        alert("My alert");
    }
});

In addition if you look at the bottom of the documentation there is an example on how to deal with errors too.
Edit

I don't want the alert to pop up when the AJAX request succeeds. I
  want the alert to pop up after some php code requested by the AJAX has
  run. It is from this php code, and not from the load() function, that
  I want the alert to originate

In that case I would reconsider the design. Your php should only return the message to display and let the calling code worry about how to display it.
You can use an ajax post for that.
$.post('post-bid.php', data, function(message){
    if(message.length > 0)
    {
        alert(message);
    }
});

A: At first I couldn't get it to work either but I put a document.ready around the load code and it worked.
HTML
<button id="click">Click</button>

Contents of test1.html
{"result": "true"}

JavaScript
$(document).ready(function(){
    $('#click').click(function(){
        $.getJSON("test1.html", function(data){
            if (data["result"] == "true") {
                alert("My alert");
            }
        });
    });
});


text:
Q: Meteor Files findOne return undefined i use Meteor Files for uploading files. i managed to save it to database and filesystem but i failed to get those files from its findOne method. here is my product collection :
import { Mongo } from 'meteor/mongo';
import { Meteor } from 'meteor/meteor';
import Images from './imagesCollection';

const ProductCollection = new Mongo.Collection( 'products' );

ProductCollection.helpers({
   photos() {
      return Images.findOne({ meta: { productId: this._id } });
   }
});

and here is my image collection:
const Images = new FilesCollection({
collectionName: 'Images',
allowClientCode: false,
storagePath: () => {
    return `${process.env.PWD}/public/assets/products/`;
},
onBeforeUpload: function(file) {
    if (/png|jpe?g/i.test(file.extension)) {
        return true;
    }

  }

});

export default Images;

i used meteor-collection-helper to get image associated with the product.
class ProductBox extends Component {
constructor(props) {
    super(props);

    this.productRemove = this.productRemove.bind(this);
    this.selectUpdate = this.selectUpdate.bind(this);
}

render() {
    console.log(this.props.produk.photos())
    return (
    );
  }
}

export default ProductBox;

whenever i consol log out the image collection it returned undefined or the cursor failed to get the data. please point me out which part i'm doing it wrong? any help would be appreaciated!


text:
Q: MVC Missing Views We have a legacy Web Forms application which we've recently converted from a website project to a web application project.
The Web Forms project is the "startup" project of the solution.
There is an MVC project which is a reference to the Web Forms project.
In the MVC project, there are several view (cshtml) files that are set as "Embedded Resource". When the application is debugged locally in visual studio, these files are found and compiled and the pages are visible.
When the Web Forms project is published (locally), I get an error that says "The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:" etc
The question is how come this works on IIS Express but not on IIS 10? Is there some config settings I can update to make this work?

A: Do you have a Virtual Path Provider in the WebForms project?
Try installing my project 'EmbeddedResourceVirtualPathProvider'

Install-Package EmbeddedResourceVirtualPathProvider

https://github.com/mcintyre321/EmbeddedResourceVirtualPathProvider/


text:
Q: Render UITableView during background fetch for restoration I have a table which rows gets normally rendered from processes running in a background thread (not to slow down the scrolling). All works well but, when the app is launched from a background fetch, I struggle to render the table before calling the fetch completion handler. In facts it looks like the main thread (which is responsible to render the table after the reload data call) gets only processed after the fetch completion handler is called, leaving not much time for the table to render before its state is saved.
Is there a way to run a table reload data not in the main thread? Any other idea how I could make sure the table is rendered before calling the fetch completion?


text:
Q: pywin32 - restrict, filtering by a list of potential senders I need to iterate through every email within my project. I have more than 20000 mails. Therefore i read I need to use the restrict function. I found examples how to restrict to one specific domain
messages = messages.Restrict("@SQL=(urn:schemas:httpmail:SenderEmailAddress LIKE '%@domain.com')")

What do I need to use if have more than 100 domains or multiple (more than 100) Senders I want to use? Would it be a huge restrict function with logical OR connectors with all of the domains or can I input somehow a list into the restrict statement?
EDIT:
and i realized if i run a restrict function with this code, it just shows me with the len(messages) function that there are 0 emails while i can see a bunch of emails in outlook with used domain in the filter. what am i doing wrong?

A: Typically you would need to use the logical OR operator in the search string. Read more about that in the Filtering Items Using a String Comparison article. Also you may find the following articles helpful:

*

*How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)

*How To: Use Restrict method to retrieve Outlook mail items from a folder
But I would recommend handling each domain separately, so you will get Outlook running without freezes and will be able to process items in a logical bunch, especially when you have a hundred of domain names to search for.

A: If you want to filter out internal senders and only process the senders outside your organization, check the SenderEmailType property - it will be "EX" for the internal senders (assuming you are using Exchange Server) and "SMTP" for the external senders.


text:
Q: cost of switching to MAXDOP=1 in prod Have a client who's Sql Server instance serving SP2010 databases has MAXDOP=0. What are immediate/postponed cost in terms of resource usage (CPU/mem/IO) when MAXDOP is set to 1?
Should then I apply it ASAP or wait for minimum farm usage hours?
UPDATE This is NOT a dublicate Q: I've marked the important part

A: In SharePoint 2013 this option is must have thing, without it you cannot configure the SharePoint. That's mean it is important piece of configuration, we had set since the launch of SharePoint 2010 and had no issue.

this has been tested pretty comprehensively and gives best performance
  and without this setting it is possible to see Table Scans for some
  content databases under various conditions. Yes, many of the Stored
  Procedures now have this set as a hint in many (>150 stored procs) but
  as a general rule for a SharePoint specific SQL environment, set this
  value to 1.

http://blogs.technet.com/b/lukeb/archive/2011/09/08/sharepoint-maxdop-1.aspx
that's mean if your setting is not 1 then if Optimerzer see no index on table or  dont want to use existing index then it perform table scan. which is resource extensive process and delay you query execution time and user has to wait for longer time.
to understand the Table-scan concept, please see this https://technet.microsoft.com/en-us/library/aa224773(v=sql.80).aspx


text:
Q: Firestore security rule with get().id - id prop not available? I am attempting to get the key of a document using the Firestore resource property id derived from using get(), like so:
get(/databases/$(database)/documents/the/$(path)/is/$(request.resource.data.here)).id
I don't think id is available. I have tried a simulation using exists() without the  id property at the end and it worked, so I know the resource is there and the path is correct.
Here is the piece of Firestore security rule doc I referenced: https://firebase.google.com/docs/reference/rules/rules.firestore.Resource
Not sure if the way I try to get the id is incorrect or it's just not available?


text:
Q: Populating MatTables with promises (asynchronous rows) I'm trying to display a collection of objects in a MatTable. I have a list with each object's URL, so I want to populate the rows asynchronously (I'm ok with having all the empty rows upfront, and then fill in the data as I load it)
So, this is my data source
export class TableDataSource extends DataSource<Promise<any>> {

  private _items: Promise<any>[];

  constructor(private loader: LoaderService, private collection: ObjectMember) {
    super();
  }
  connect():  Observable<Promise<any>[]> {
    if (!this._items) {
      //aggregates each Promise<any> into an array.
      this._items = this.collection.value.map(x => this.mm.load(ObjectRepr, x.href));
    }
    return Observable.of(this._items);
  }
  disconnect() {}
}

and this is my table
<mat-table #table [dataSource]="CollectionSource" class="mat-elevation-z8" sort>
    <ng-container matColumnDef="Name">
        <mat-header-cell *matHeaderCellDef> Name</mat-header-cell>
        <td mat-cell *matCellDef="let element"> {{element.name}} </td>
      </ng-container>

      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>

This is showing the right number of rows, but they are not populated. The Promises are not getting resolved.
I've tried the following things but in both cases I got compile errors:
 <td mat-cell *matCellDef="let element | async"> {{element.name}} </td>

and
  <mat-row *matRowDef="let row| async"; columns: displayedColumns;">

Is what I'm trying to do possible in any way?

A: You need to use Observable.forkjoin() to handle the observable in for loop.
connect():  Observable<Promise<any>[]> {
    const observable = [];
    if (!this._items) {
      //aggregates each Promise<any> into an array.
      this.collection.value.forEach(x => {
          const obs = this.mm.load(ObjectRepr, x.href));
          observable.push(obs);
      });
    }
    return Observable.forkjoin(observable);
  }


text:
Q: Darle cobertura de test a archivos que no son componentes en angular Mi pregunta es mas bien sencilla pero me gustaria tener una orientacion.
Tengo un componente con su respectiva clase spec para los test. El archivo .ts supera las mil lineas por lo que el sonarqube me lo arroja como un issue de alto riesgo, por lo que  me vi forzado en desacoplar el codigo.
Para esto tome algunas funciones generales de dicho archivo y las traslade a otro archivo .ts en una carpeta utils consumiendolas desde el archivo principal con un import y exportandolas con export function desde el archivo desacoplado.
El tema es que el sonarqube me arroja baja cobertura ya que no logra cubrir esos archivos extras, y no se como puedo hacerlo ya que eso son simples archivos .ts, no componentes propiamente tal donde pueda tenerle archivos de test spec.
Alguna idea de como darle cobertura a esos archivos que no son componentes sino simplemente archivos de funciones?
Saludos!!


text:
Q: Regular expression to find R code in Sweave expression I have some sweave expressions contained among text in some .Rnw files. The paragraph below contains two sweave expressions. What regular expression can I use to find the R code in each expression. So the regular expression should be able to find mean(mtcars$mpg) and/or summary(lm(mpg ~ hp + drat, mtcars))

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \Sexpr{mean(mtcars$mpg)}. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat \Sexpr{summary(lm(mpg ~ hp + drat, mtcars))} non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

A: The regex would be (?<=\\Sexpr{).+?(?=})

*

*(?<=\\Sexpr{) part is positive lookbehind

*(?=}) is positive lookahead

*.+? will match everything between above two lookarounds lazily.

Readup more here. http://www.regular-expressions.info/lookaround.html
E.g. in R (since you tagged R)
txt <- 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \\Sexpr{mean(mtcars$mpg)}. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat \\Sexpr{summary(lm(mpg ~ hp + drat, mtcars))} non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'

regmatches(txt, gregexpr('(?<=\\Sexpr{).+?(?=})', txt, perl=T))

## [[1]]
## [1] "mean(mtcars$mpg)"                     "summary(lm(mpg ~ hp + drat, mtcars))"


text:
Q: Angularjs Material Design with JQuery I am developing a new webapp and I want to use material design for it.
Currently the backend is developed with laravel (php) and the frontend with JQuery and materializecss.
 The problem is that materializecss is not powerful enough for my needs (I need ajax calls, dynamic content...).
 Since i know angular has a FANTASTIC material design framework but i don't want to use angularjs, i was wondering if i could use just the material design template (even with some necessary angularjs code in order to run things) and then develop my things with JQuery.
 Would i be able to do ajax calls, update content dinamically, add visual elements of angularjs material design with JQuery?
Thank you for your time!

A: yes you can use what ever you want
even you can combine them and set jquery codes in angularJs controller although its not recommended cos you have what ever you want in jquery and angular both are awesome js frameworks .
if you are looking for material design you can use it without angularJs its a separate css and js framework .
get material desing light


text:
Q: Optimise Python Code I have written the following code to preprocess a dataset like this:
StartLocation   StartTime   EndTime
school          Mon Jul 25 19:04:30 GMT+01:00 2016  Mon Jul 25 19:04:33 GMT+01:00 2016
...             ...         ...

It contains a list of locations attended by a user with the start and end time. Each location may occur several times and there is no comprehensive list of locations. From this, I want to aggregate data for each location (frequency, total time, mean time). To do this I have written the following code:
def toEpoch(x):
    try:
        x = datetime.strptime(re.sub(r":(?=[^:]+$)", "", x), '%a %b %d %H:%M:%S %Z%z %Y').strftime('%s')
    except:
        x = datetime.strptime(x, '%a %b %d %H:%M:%S %Z %Y').strftime('%s')
    x = (int(x)/60)
    return x

#Preprocess data
df = pd.read_csv('...')
for index, row in df.iterrows():
    df['StartTime'][index] = toEpoch(df['StartTime'][index])
    df['EndTime'][index] = toEpoch(df['EndTime'][index])
    df['TimeTaken'][index] = int(df['EndTime'][index]) - int(df['StartTime'][index])
total = df.groupby(df['StartLocation'].str.lower()).sum()
av = df.groupby(df['StartLocation'].str.lower()).mean()
count = df.groupby(df['StartLocation'].str.lower()).count()
output = pd.DataFrame({"location": total.index, 'total': total['TimeTaken'], 'mean': av['TimeTaken'], 'count': count['TimeTaken']})
print(output)

This code functions correctly, however is quite inefficient. How can I optimise the code?
EDIT: Based on @Batman's helpful comments I no longer iterate. However, I still hope to further optimise this if possible. The updated code is:
df = pd.read_csv('...')
df['StartTime'] = df['StartTime'].apply(toEpoch)
df['EndTime'] = df['EndTime'].apply(toEpoch)
df['TimeTaken'] = df['EndTime'] - df['StartTime']
total = df.groupby(df['StartLocation'].str.lower()).sum()
av = df.groupby(df['StartLocation'].str.lower()).mean()
count = df.groupby(df['StartLocation'].str.lower()).count()
output = pd.DataFrame({"location": total.index, 'total': total['TimeTaken'], 'mean': av['TimeTaken'], 'count': count['TimeTaken']})
print(output)

A: First thing I'd do is stop iterating over the rows.
df['StartTime'] = df['StartTime'].apply(toEpoch)
df['EndTime'] = df['EndTime'].apply(toEpoch)
df['TimeTaken'] = df['EndTime'] - df['StartTime']

Then, do a single groupby operation.
gb = df.groupby('StartLocation')
total = gb.sum()
av = gb.mean()
count = gb.count()

A: *

*vectorize the date conversion

*take the difference of two series of timestamps gives a series of timedeltas

*use total_seconds to get the seconds from the the timedeltas

*groupby with agg

# convert dates
cols = ['StartTime', 'EndTime']
df[cols] = pd.to_datetime(df[cols].stack()).unstack()

# generate timedelta then total_seconds via the `dt` accessor
df['TimeTaken'] = (df.EndTime - df.StartTime).dt.total_seconds()

# define the lower case version for cleanliness
loc_lower = df.StartLocation.str.lower()

# define `agg` functions for cleanliness
# this tells `groupby` to use 3 functions, sum, mean, and count
# it also tells what column names to use
funcs = dict(Total='sum', Mean='mean', Count='count')
df.groupby(loc_lower).TimeTaken.agg(funcs).reset_index()

explanation of date conversion

*

*I define cols for convenience

*df[cols] = is an assignment to those two columns

*pd.to_datetime() is a vectorized date converter but only takes pd.Series not pd.DataFrame

*df[cols].stack() makes the 2-column dataframe into a series, now ready for pd.to_datetime()

*use pd.to_datetime(df[cols].stack()) as described and unstack() to get back my 2-columns and now ready to be assigned.


text:
Q: How to deploy apps in tomcat server I want to deploy myapp in tomcat server. I know one way is to delete the Root folder from webapps and rename my app.war as ROOT.WAR. But i do not want to do this. I want to deploy like when user access my app as www.xxx.com , it should go to my app like www.xxx.com/login.html.
Please help

A: You have several options to set a root application. (see https://stackoverflow.com/a/5328636/6371459)

*

*Remove ROOT directory and deploy your war as ROOT.war

*Deploy your war in webapps and configure the context root in conf/server.xml to use your war file  (not recommended because requires restarting)

*Create a specific context file $CATALINA_BASE/conf/[enginename]/[hostname]/ROOT.xml  and set docBase=your_war_name  like previous 2) (see @ChristopherShultz answer)
Since you have discarded option 1, and option 2 is not recommended, I suggest use a context file

A: You can deploy any WAR file (or exploded WAR directory) from (almost) anywhere with any context name you want, as long as it doesn't conflict with any auto-deployed application. Here's how:

*

*Remove any conflicting applications from webapps/ (in this case, really, it's just ROOT)

*Move your own application someplace other than in webapps/

*Copy the META-INF/context.xml file from your application and place it into Tomcat's conf/[engine]/[host]/[contextpath].xml – for example conf/Catalina/localhost/ROOT.xml

*Edit conf/[engine]/[host]/[contextpath].xml and add this attribute to the <Context> element:
docBase="/path/to/your/WAR.war"
Now, Tomcat will deploy /path/to/your/WAR.war on context path / (because the deployment descriptor's filename is ROOT), and you didn't have to modify conf/server.xml.
Who cares about modifying conf/server.xml? Well, that file is only read once during container startup, so if you want to make changes, undeploy, redeploy, etc. you must restart the entire container to pick-up those changes. It's much better to use Tomcat's auto-deployment facility, which as you can see is quite flexible.
All of this is laid out in Tomcat's documentation on defining contexts where, incidentally, the very first sentence makes it clear that defining a context in server.xml is a bad practice.

A: Configuration file is server.xml
You can just follow this example : https://examples.javacodegeeks.com/enterprise-java/tomcat/tomcat-server-xml-configuration-example/
referencing tomcat documentation : http://tomcat.apache.org/tomcat-7.0-doc/config/context.html


text:
Q: save variables to session with jquery/ajax - MODX Revolution I have 2 options user can change on page made in modx rev 2.2.0
 * background
 * font-size
To change background and font size i used jquery, so i think the best way would be use ajax. So i would have to create 1/2 pages which add those variables to session, so if user go to a different page, background and font size stay the same. And if user visit page after few days, background and font size would stay the same.
Here is my javascript code:
<script type="text/javascript">
 $(document).ready(function () {
  background5();
    var originalFontSize = $('html').css('font-size');
 });

 function background1() { $('.wrap').css("background","url(assets/templates/default/images/bg1.jpg)"); return false; }
 function background2() { $('.wrap').css("background","url(assets/templates/default/images/bg2.jpg)"); return false; }
 function background3() { $('.wrap').css("background","url(assets/templates/default/images/bg3.png)"); return false; }
 function background4() { $('.wrap').css("background","url(assets/templates/default/images/bg4.jpg)"); return false; }
 function background5() { $('.wrap').css("background","url(assets/templates/default/images/bg5.jpg)"); return false; }
 function background6() { $('.wrap').css("background","url(assets/templates/default/images/bg6.jpg)"); return false; }
 function background7() { $('.wrap').css("background","url(assets/templates/default/images/bg7.jpg)"); return false; }
 function background8() { $('.wrap').css("background","url(assets/templates/default/images/bg8.jpg)"); return false; }
 function background9() { $('.wrap').css("background","url(assets/templates/default/images/bg9.jpg)"); return false; }
 function big_font() {
  var currentFontSize = $('html').css('font-size');
  var currentFontSizeNum = parseFloat(currentFontSize, 10);
  var newFontSize = currentFontSizeNum*1.1;
  $('html').css('font-size', newFontSize);
  return false;
 }
 function small_font() {
  var currentFontSize = $('html').css('font-size');
  var currentFontSizeNum = parseFloat(currentFontSize, 10);
  var newFontSize = currentFontSizeNum*0.9;
  $('html').css('font-size', newFontSize);
  return false;
 }
</script>

My question is how to add variables to session in modx, and what is the best way of doing this?

A: Create a resource to be used as an Ajax stub, and on it place an uncached snippet containing your 'add to session' code. The snippet could be as simple as:
<?php
// example only, be sure to sanitize and add some sensible defaults here
$background = $_POST['background'];
$fontSize   = $_POST['font_size'];

// write to user's session
$_SESSION['background'] = $background;
$_SESSION['fontSize'] = $fontSize;

return '';

Then use jQuery to create an Ajax call to the stub, passing the background and font_size params to it:
var background = 6,
    fontSize = 2;
// let's assume your Ajax stub resource id is 7
$.post("[[~7]]", { background: background, font_size: fontSize } );

Note: you could tidy up all those background() functions by using just one, something like this:
function background(n) {
    var url = "assets/templates/default/images/bg"+parseInt(n)+".jpg";
    $('.wrap').css("background","url("+url+")");
    return false;
}


text:
Q: Linq expression decimal culture I have this piece of code:
fee.SingleOrDefault(f => 100.05M >= f.Rate);

In the database the Fee.Rate is a money field stored using invariant culture. But using this select gives an error because my current culture will convert "100.05" to "100,05" wihich results in;
An expression of non-boolean type specified in a context where a condition is expected, near ','.

What is the best way to do this?

A: This strikes me as less of a LINQ issue and more of a SubSonic issue. Taking a quick peek at their LINQ parser it looks like constant values are handled with ToString() with no regard for culture (see SubSonic.Linq.Structure.TSqlFormatter.VisitConstant). Writing/contributing a patch for this would be ideal (to either allow specification of a culture or at least to use invariant by default), otherwise I think you're stuck switching the thread culture.

A: Thank you for the answer. As a solution I have modified the SqlServer.ttinclude template to switch to invariant culture in the Find method.
Not a perfect but temporary solution, I'll create a patch or at least report the problem to SubSonic.


text:
Q: Regex Expression to remove any html tag with a given class Can anyone help me with a regex expression that I can use to remove any html tag with a given class.
Example -
I have selected all tr in the dom and I have them as a string. But I will like to remove all tr's that has class, "world"..

Note - I have them as a string because I would like to copy them to the clipboard. However, I would like this tag(with a given class) to remain the dom but not in the string I want to copy to the clipboard

A: A regular expression isn't the right tool for this task.
To do what you require, select the table element from the DOM and clone it. You can then select the child tr.world elements from the cloned table, so you don't affect the instance currently in the DOM, before you get the resulting innerHTML. Here's a working example:

let table = document.querySelector('table').cloneNode(true);
table.querySelectorAll('tr.world').forEach(el => el.remove());
let html = table.querySelector('tbody').innerHTML;

console.log(html);

World

Stack

Hello world

Foo


text:
Q: What is a plain English explanation of Jenkins' OneOffExecutor? I am working on a script that uses Jenkins REST API to get all current running builds. I can get a list of nodes and their executors information from computer/api/json in the format of:
{
    "computer": [
        {
            "displayName": "master",
            "executors": [...]
            "oneOffExecutors": [
                {
                    "currentExecutable": {<my_pipeline_job_info>}
                }
            ]
        },
        {
            "displayName": "slave1",
            "executors": [
                {
                    "currentExecutable": null,
                    ...
                },
                {
                    "currentExecutable": null,
                    ...
                }
                ]
        }
    ]
}

In the pipeline definition groovy script, I restrict the job to run only on slave node:
node("slave_label") {...}

I noticed that, although they are actually running on the slave node, in the above JSON response, they are not showing up in the 'executors' section under each slave node. Instead, they are on oneOffExecutors on master node.
I couldn't find any good explanation of oneOffExecutors except one line in the class JavaDoc:

Executor that's temporarily added to carry out tasks that doesn't
  consume regular executors, like a matrix project parent build.

So what is oneOffExecutor exactly? Why my pipeline jobs are not running on regular executors on slave nodes?

A: OneOffExecutor, also called a Flyweight Executor, is a thread on your Jenkins master that tracks and coordinates a pipeline build.  While they are called FlyWeights they actually can cause a significant load on your master, for example, while your build on a slave is shipping logs back, the master has to receive those logs and write them.  When your job archives artifacts, they are shipped back to the master and written on the Master file system.  They are Flyweight in the sense that they may be idle doing nothing except waiting for the slave(s) to complete the task(s), and they take little memory to maintain.
In your example, my_pipeline_job_info may be waiting for a node (slave), may be ending, or may have JUST been dequeued and not yet doing anything, however all the time that job (or any pipeline job) is running, it will have a Flyweight executor on the master.
See also https://serverfault.com/a/981461/236229 for an explanation of how Jenkins shows One Off executors on the master.
By the way, slaves can have OneOffExecutors, too.
You can monitor what is running on the Master as "OneOffExecutors" as you have shown, but here is a more complete URL:
https://YOUR.JENKINS.URL/computer/(master)/api/python?pretty=true&tree=oneOffExecutors[currentExecutable[fullDisplayName,result,id,url]]&depth=1
But you can also substitute (master) with your actual slave1 name to see OneOff Executors on other slaves.

A: Executor of a slave should return something when it is not idle. Instead it shows up in the oneoffexecutor. I am facing the same problem. I want to identify which slaves are running what builds but i can't distinguish because executors of slave is empty
If you got any insight, please do share.


text:
Q: XSLT - Search for last element in a group I am iterating over a group of elements and while I am iterating I need to access information from the last node set.
For example, I have a test that goes back out to the level1 elements, while I am getting the values for the current node set, to check and see if there are multiple elements that contain the same group number, and then if so would need to access information from the last node set that contains the group with number 3.
<root>
    <level1>
        <group>1</group>
        <name>test1</name>
        <email>test@email.com</email>
    </level1>
    <level1>
        <group>3</group>
        <name>test2</name>
        <email>test2@email.com</email>
    </level1>
    <level1>
        <group>3</group>
        <name>test3</name>
        <email>test3@email.com</email>
        <manager>manager@email.com</email>
    </level1>
</root>

I have tried the following to get back out to the root level to check to see if the group exists and to get the last node set that contains the specific group.
../../level1/group = ./group

./group = ../../level1/group

./group = ../../level1/group[1][last()]

A: If you just want to locate the last  tag for group 3, you can do the following:
root/level1[group = 3][position() = last()]


text:
Q: Ajax return no response when calling another function LARAVEL Problem solved it was due to the echo in the called function i just removed echo
My view is calling ajax and i am returning reponse when function ends in my controller.
View

    $(".btn-submit").click(function(e){

        e.preventDefault();

        var name = $("input[name=name]").val();
        var password = $("input[name=password]").val();
        var email = $("input[name=email]").val();

        $.ajax({
           type:'POST',
           url:"{{ route('ajaxRequest.post') }}",
           data:{name:name, password:password, email:email},
           success:function(data){
              alert(data.success);
           }
        });

    });

Controller
public function post()
{

   return response()->json(['success'=>'Got Simple Ajax Request.']);
}

But when calling a function before the return response the response is not returned
public function post()
{
   self::hello();
   return response()->json(['success'=>'Got Simple Ajax Request.']);
}


text:
Q: Expectation and variance of a biased random walk I'm sure this should be straight forward but somehow i can't find a similar example online.
How do i calculate expectation and variance in this case:
A random walker takes 1 step backwards (-1) with p= 0.2, 1 step forward (+1) with p= 0.5, and stays at the same position with p = 0.3.
How do i find expectation and variance after n steps?

A: Here are some of the concepts that you need to understand to solve this problem:
(1) The final location can be viewed as the sum of steps from the initial location:
$$X(n) = X(0)+S(1)+S(2)+\dots+S(n)$$
Here $X(0)$ is the initial location, which also contributes to the mean and variance of $X(n)$. Often $X(0)$ is given as the origin (deterministic initial condition), in which case it has a mean and variance of zero, so can be ignored. I do not see an initial condition given in your problem. You would need that to determine the answer.
(2) The mean of a sum of random variables is equal to the sum of the means of the random variables.  This is ALWAYS true (when each random variable has a mean), since the expected value is a linear operator:
When $a$ and $b$ are nonrandom:
$$\mathbb{E}[aX+bY] = a\mathbb{E}[X]+b\mathbb{E}[Y]$$
(3) When random variables are INDEPENDENT (as in this problem), then the variance of their sum is equal to the sum of their variances.
Without independence, the formula is:
$$\operatorname{Var}[aX+bY] = a^2\operatorname{Var}[X]+b^2\operatorname{Var}[Y] + 2ab \operatorname{Cov}[X,Y]$$
Independence implies that $\operatorname{Cov}[X,Y]=0$ (independence is a stronger condition)
(4) You need to know how to compute the mean and variance of each step. Your computation of the mean in the comments is correct (you should edit your original post to include that, rather than have it in the comments). Your computation of the variance is not correct, your computation is actually for $\mathbb{E}[S_1^2] = 0.2(-1)^2 + 0.5(1)^2 + 0.3(0)^2$. In order to compute the variance, you could use that computation, together with the identity:
$$\operatorname{Var}[X] = \mathbb{E}[X^2] - \left( \mathbb{E}[X]\right)^2$$


text:
Q: How isolated must a system be for it's wave function to be considered not collapsed? As an undergrad I was often confused over people's bafflement with Schodinger's cat thought experiment.  It seemed obvious to me that the term "observation" referred to the Geiger counter, not the person opening the box.  Over time, I have come to realize that the Copenhagen interpretation actually is ambiguous and that "observer" cannot be so easily defined.  Nonetheless, an objective collapse theory (which is what I was unknowingly assuming) still seems to me the simplest explanation of wave collapse phenomena.
I have read some of the objections cited in the Wikipedia article linked above, but it is still unclear to me why most physicists adopt the Copenhagen interpretation and reject objective collapse.  For example, in this question on hidden observers, there was some discussion about the mechanism of wave collapse.  It was suggested that perhaps the gravitational pull of a hidden observer would collapse the wave function.  In response, it was pointed out that the gravitational pull would be negligible at the scales involved.
Okay, then imagine the following:
A hermetically sealed (i.e. isolated) box is balanced on a fulcrum.  Inside the box is a radioactive isotope, a Geiger counter, and a trigger mechanism connected to a spring loaded with a mass on one side of the box.  If the Geiger counter detects a decay, the trigger releases the spring and the mass shifts to the other side of the box.  The shift in mass would, under observable conditions tilt the box on the fulcrum.
According to the interpretation of Schrodinger's cat that I often hear (the cat is in a superposition) it seems that the box should slowly tilt over as the wave function of the system evolves with the half-life of the isotope.  I can't imagine that anyone thinks this is a realistic expectation.
I can see that people might object and say "But the contents of the box are interacting gravitationally with the outside system and observer so it is not really isolated!"  Well, what of it?  The same is true of the cat even if the interaction is less dramatic.
The question, then, is: How isolated must a system be for it's wave function to be considered not collapsed?

A: ''How isolated must a system be for it's wave function to be considered not collapsed?''
Experimentally, a system whose collapse is observable must be so small that one can prepare it in a well-defined pure state. If this is not the case, one can only speculate about what happened, leaving much room to imagination.
This means that even when the carrier of the system is fairly big, the wave function collapsed models only extremely few degrees of freedom, and the real system considered is the one with these few degrees of freedom, not the bigger one.
For example, arXiv:1103.4081 discusses superposition and collapse of macroscopic objects. But prepared in a superposition is only a single degree of freedom, the distance; all other degrees of freedom are either uncontrolled (and hence presumably in a mixed state) or eliminated by extreme cooling.
Thus the system measured is in effect a single quantum oscillator.
Now a typical quantum oscillator decoheres rapidly unless isolated, and a quantum oscillator of some size is hard to isolate. The experimental art consists in maintaining a superposition of two distances by isolating this particular degree of freedom from the environment. This isolation must be almost perfect, as otherwise decoherence effects responsible for the collapse set in extremely rapidly. (No special observer is needed. The environment does the observing by itself.)
''why most physicists [...] reject objective collapse.''
The main reason is that they want to maintain the simplicity of the traditional quantum mechanical foundations that are based on the assumption that the dynamics of quantum states is exactly linear, which seems to suffice for all applications. Objective collapse theories would require a tiny nonlinear modification of the basic laws, and spoil simplicity for (so far) uncheckable philosophy.
Note that ''no objective collapse'' doean't mean that collapse isn't observable (it is observed routinely), but only that the collapse is not due to decoherence (the approximation in which the collapse is derivable in terms of generally believed assumptions from statistical mechanics - needed already in classical physics) but to objective deviations from the Schroedinger equation.
The latter has no observable basis, and hence is rejected by most physicists.

A: The minute you make the box able to change the surroundings, it ceases to be just a box; and becomes a measuring device.
How this happens can be easily visualised. Lets take an ideal geiger counter-atom setup in a similar box. It is wired outside to a display. Now, for obvious reasons, the atom wavefunction will be immediately collapsed. It will not slowly evolve. This is because you can observe the system using the display. We cannot argue that the geiger counter's wavefunction itself will be affected.
A more stark way of formulating your problem is by attaching the counter to a hammer. If, within the first xyz seconds, there is a decay, the hammer wil strike the box lid; opening it. If you are outside, and the box does not open in xyz secs,  you will know that there were no decays, and will have collapsed the wavefunction WITHOUT opening the box. Here, the counter did not become a measuring device by affecting the surrounding; it did so by its ability to affect the surroundings.
Your box is again a measurement device, with the ability to affect the surroundings. Same thing happens, it immediately collapses the wavefunction.
Now to your original question: Anything that can affect the surroundings in a measurable way on the basis of whatever property is being measured counts as a measuring device for that property in the surroundings.
Now heres where everything goes crazy: I've specifically kept the weasel words 'in a measurable way' as QM observations are a fuzzy and conttoverersial topic. May be only conscious beings can make an observation. Maybe only beings who know the implication of their measurement  can collapse the wavefunction (so a random person who sees the lever shift but doesn't know what the shift signifies won't collapse it).  In the latter case, stuff like 'negligible effects' also create an issue, as the experimenter can't conscously register them and segregate them from 'noise', even though they might feel it.. For example, your geiger counter can emit a photon depending on the results. An experimenter can see the photon with his eyes (our sight is a photon phenomenon),but not register it. Im assuming that the experimenter doesn't have photon detectors.
From there onwards, it gets more philosophical. Which is IMHO why physicists have gone 'shut up and calculate' as @JohnRennie mentioned.

A: The Schrodinger's cat is a though experiment modeled in such a way that it's as unrealistic as that common assumptions you see in physical questions, like assuming perfect vacuum. You can't get a perfect vacuum as you can't get a cat going its way through a poison bottle and get dead and alive without happening any decoherence in the middle, the Schrodinger's cat is just an unrealistic Zen Master of Quantum Collapsing Counterfeit's Cat (ZMQC³) as your box is a ZMQC²B.
What about looking at other experiments that shows more clearly the question about the measurement problem? Like the double-slit experiment which shows at which point by means of an observer (which implicitly refer to the thing, anything, that realizes a measurement, that interacts, not only conscious observers), the observed (the thing measured) comes out of its wave function as a quantized particle, and at which point not. The referred link also points out advances on non-perturbative detectors (which I must confess is new stuff to me, but as it's stated, doesn't contradict wave/particle duality and also relates with the objective collapse theories).
What seems clear is that, in the event of measurements/interactions ("observations"), quantum collapses ("spontaneous localization" as in the wikipedia article on objective collapse) will occur, and so, complex systems free from this measurements, that's, "isolated systems", are mostly unrealistic.
There's a good discussion related to this topic at this physics forum about Heisenberg views, which also seems more objective than the Copenhagen interpretation: www.physicsforums.com/showthread.php?t=492354
Quoting Heisenberg on "Physics and Philosophy":
"It applies to the physical, not the psychical act of observation, and we may say that the transition from the 'possible' to the 'actual' takes place as soon as the interaction of the object with the measuring device, and thereby with the rest of the world, has come into play; it is not connected with the act of registration of the result by the mind of the observer. The discontinuous change in the probability function, however, takes place with the act of registration, because it is the discontinuous change of our knowledge in the instant of registration that has its image in the discontinuous change of the probability function."

A: Well, this depends on the system inside the box and how long you want it remain in superposition state.
For example, D-Wave Systems creates the following conditions for their quantum computer:

*

*Electric magnets screening Earth's magnetic field, so to get at 1 nano tesla magnetic field across the processor, which is 50000 times less than the Earth's magnetic field.

*200 sq feet refrigirator comsuming 7.5 kW electricity creates 20 millikelvin temperature for the processor's package and the board.

*30Mhz filtering on any electric lines
source

A: quantum mechanics is inherently linear, this has consequences to superposition states, mainly multiple superpositions of a physical system cannot interact to each other.
Now, observation clearly breaks this, precisely because it is about different physical systems interacting with each other. In the particular case where one of the systems is the environment, it should be obvious that you cannot still have multiple superpositions not interacting to each other at the same time the environment is interact with both of them (or more precisely, a physical system coming from and returning to the heat bath). The reason for this should be clear: if they both stayed in superposition then they could interact to each other through the environment, hence breaking the quantum mechanics linearity.
This is why i think that measurement is inherently a non-linear process, because it breaks the linearity regime of quantum mechanics.
How is this possible? well, mainly because classical physical systems are non-linear, and quantum mechanics by correspondence should be non-linear in the classical limit. For instance, a physical object (like a geiger counter) will behave in extremely non-linear ways after an $\alpha$ or $\beta$ particle hits or doesn't hit. There will be gauge movements and electric currents in the case where it hits that cannot be simply modeled by anything as trivial as a linear superposition.
In more precise terms, a physical observer (again, like the geiger counter) is by design oriented to behave non-linearly across a range of eigenvalues in a very specific eigenbasis, while approximately linearly (i.e: non discriminating) in other non-conmuting eigenbasis. You cannot design an observer to behave non-linear in two nonconmuting eigenbasis at the same time. This is in essence the uncertainty principle


text:
Q: Is a topological vector space that is $T_0$ already $T_2$? If $A$ is a topological vector space, then I know that being $T_1$ is equivalent to beeing $T_2$.
Now I was wondering if $A$ is a $T_0$-space, is it then automatically $T_1$ (and therefore $T_2$).
I can't find an easy counterexample making me think that it might be true.

A: This is true more generally for arbitrary topological groups. Indeed, suppose $A$ is $T_0$. Given two distinct $x,y$ there is a neighbourhood $U$ of one not containing the other, say $x\in U,y\not\in U$. Then $y+x-U$ is a neighbourhood of $y$ not containing $x$ (my comment above has a typo). Therefore $A$ is $T_1$ which, as you already know, implies $T_2$.


text:
Q: maven error "Property ${samedir} has not been set" How to fix the maven checkstyle plugin error
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-checkstyle-plugin:3.1.2:check (validate) on project yourproject:
Failed during checkstyle execution:
Failed during checkstyle configuration: unable to parse configuration stream:
com.puppycrawl.tools.checkstyle.api.CheckstyleException:
Property ${samedir} has not been set -> [Help 1]

${samedir} is a property working well with eclipse plugin and is required to get related files mentioned in the checkstyle configuration working well with eclipse IDE. So either I need a consistent replacement, or I can tell maven to define the property
Any ideas how to fix this issue?

A: You will have to set these values via the plugin configuration in your pom.
Example configuration of pom.xml if you have a directory named checks in your project root:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-checkstyle-plugin</artifactId>
    <version>3.1.2</version>
    <configuration>
        <configLocation>${basedir}/checks/checkstyle.xml</configLocation>
        <propertiesLocation>${basedir}/checks/checkstyle_maven.properties</propertiesLocation>
    </configuration>
</plugin>

And the checkstyle_maven.properties contents:
samedir=checks

As an alternative to the <propertiesLocation> you can also use the following, in which case you don't need the .properties file:
<propertyExpansion>samedir=${basedir}/checks</propertyExpansion>

This will make sure any configuration in checkstyle.xml will work like this:
<module name="Checker">
    <module name="SuppressionFilter">
        <property name="file" value="${samedir}/suppress.xml"/>
    </module>
</module>

See for reference:

*

*Using ${samedir} in Checkstyle-plugins for Gradle and Eclipse

*http://rolf-engelhard.de/2011/04/using-the-same-suppression-filter-for-checkstyle-in-eclipse-and-maven/


text:
Q: Как отобразить сообщение для первой новой записи? У меня имеется условие если появляется новая запись то должно отобразиться сообщение. И у меня возникает проблема в счетчике. Когда происходит добавление новой первой записи счетчик на данном этапе равен еще 0 и из-за этого сообщение не отображается.
Если установить условие:
if (this.counter >= 0) {}

То при каждой перезагрузке страницы будет всплывать мое сообщение.
Как это можно исправить?
ts:
counter = 0;
load() {
  this.ngUnsubscribe = timer(0, 1000).pipe(
    switchMap(() => this._orders.getAllOrders()),
    filter(data => data.length !== (this.orders || []).length)
  ).subscribe(orders => {
    this.orders = orders;
    if (this.counter > 0) {
    this._toast.warning('Новое.', 'Внимание!', {
        closeButton: true,
        disableTimeOut: true
      });
    }
    this.counter++;
  }, error => {
    this._toast.error(error.error.message);
  })
}

A: Можете сохранить состояние одним из способов Cookie SessionStorage LocalStorage
и при следующей загрузке посмотреть имеется ли запись в хранилище, если имеется то взять значение если нет то показать ваше сообщение.

Веб хранилища в браузерах реализованы в виде LocalStorage и Session
Storage. Также для обмена данными между Сервером и браузером
используются куки, которые представляют собой ключ значение.
Управление куками можно тоже в какой-то мере назвать хранилищем, но
очень абстрактно.


text:
Q: how to call a function inside a foreEach? I added an eventListener on small pictures, when a picture is clicked, PhotoSwipe opens the whole gallery but it doesn't remind open...
If I uncomment //openPhotoSwipe() at the end of the js file, the PhotoSwipe gallery appears when the page is loaded, and the eventListener works as expected. But that's not what I want...
I am new to javascript... Help and explanation would be much appreciated
 function openPhotoSwipe() {

    var pswpElement = document.querySelectorAll('.pswp')[0];

    var pics =  Array.from(document.getElementsByTagName('img'));

    var items = []

    pics.forEach(function(e){
                    items.push({src: e.src, w: 0, h: 0});
                    })
    var options = {

        history: false,
        focus: false,
        showAnimationDuration: 0,
        hideAnimationDuration: 0,
        closeOnScroll: false,
        closeOnClick: false,

    };

    var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);

    gallery.listen('gettingData', function(index, item) {
      if (item.w < 1 || item.h < 1) {
        var img = new Image();
        img.onload = function() {
            item.w = this.width;
            item.h = this.height;
            gallery.invalidateCurrItems();
            gallery.updateSize(true);
        }
        img.src = item.src;
      }
    });

    gallery.init();
};

   var open = Array.from(document.getElementsByClassName("open_gallery"));

open.forEach(function(e){
    e.addEventListener('click', openPhotoSwipe);
})
// openPhotoSwipe();

here is a part of my view:

<%= @article.title %>

<%= @article.description %>

        <% @article.attachments.each do | art| %>

        <%= link_to image_tag art.url, class: "open_gallery" %>

        <% end %>

            <% @article.attachments.each do | art| %>

                    <%= image_tag art.url %>

            <% end %>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

A: As you confirmed in the comment that my guess was correct that, your link_to basically doesn't created the desired HTML markup. So here I am putting the comment as answer. Write your link to method as below:
<%= link_to "#", class: "open_gallery" do %>
  <%= image_tag art.url %>
<%end%>


text:
Q: sonar-runner lcov report discrepency SonarQube Community,
When doing an analysis of a Node/JS project the coverage valued reported via istanbul show much different than what gets reported and shows on our SonarQube server.
Our SonarQube server is at 4.5.4
Our sonar-runner version is 2.4
The project generated the following report:
Code coverage report for All files
Statements: 67.65% (1520 / 2247)      Branches: 49.76% (418 / 840)      Functions: 65.13% (269 / 413)      Lines: 68.31% (1481 / 2168)      Ignored: none
File        Statements      Branches        Functions       Lines
classes/        94.4%   (118 / 125) 70% (7 / 10)    100%    (9 / 9) 94.35%  (117 / 124)
helpers/        84% (126 / 150) 75.44%  (43 / 57)   86.67%  (26 / 30)   84.25%  (123 / 146)
services/       82.64%  (976 / 1181)    66.67%  (272 / 408) 81.63%  (160 / 196) 83.26%  (955 / 1147)
view_controllers/       37.93%  (300 / 791) 26.3%   (96 / 365)  41.57%  (74 / 178)  38.08%  (286 / 751)
Generated by istanbul at Tue Sep 15 2015 17:01:21 GMT+0000 (UTC)
The coverage values shown in the SonarQube 4.5.4 drill down differ greatly from what the other report shows: ( I apologize for not being able to post an image but I do not have a high enough reputation yet to do this.)
Technical Debt
64d
Issues
5,707
Blocker    0
 Critical   3
 Major  3,922
 Minor  696
 Info   1,086
Unit Tests Coverage
28.6%
Line Coverage
25.6%
Condition Coverage
49.8%
SQALE Rating
A
Technical Debt Ratio
1.0%
 The project has warnings on the following quality gate conditions:
Coverage
28.6% < 70.0%
Critical issues
3 > 0
 cd-services-test-Indexing web client cd-services-test-RECORDS-IDX-indexing-web-client
Profiles: Sonar way (JavaScript)
Quality Gate: SonarWayWithFindbugsForNFSWithBuildBreaker - java (Default)
Lines Of Code
104,320
JavaScript
Files
426
Directories
109
Lines
120,238
Functions
6,726
Classes
4
Statements
32,377
Accessors
0
Useless Code
18,260
18,260 lines in duplications
Duplications
41.5%
Lines
49,923
Blocks
10,915
Files
89
Complexity
4.9 /function
4.5 /class
29.5  /file
Total: 12,588
If you should need the actual lcov.info file or if you would like pngs of the data above to better analyze this problem I can send them via an e-mail directly to you.
What would you suggest I do to try and track down why there is such a discrepency?
Any thoughts on how I can proceed to get correct data logged would be very much appreciated.
Doug


text:
Q: Connect people from different networks to mdf file database I have for local connection the code
@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users[PCUsername]\source\repos\ZermoCSharp\ZermoCSharp\data.mdf;Integrated Security=True;Connect Timeout=30"
but if I want my friends, from a different network, to connect to the MDF file and get information (for logging in, etc.)
What code do I need to use so they'll be able to connect and log in?
(my database is in Visual studio 2019)


text:
Q: Horizontal scrolling with inline-block working in Firefox but not in Chrome I have implemented horizontal scrolling in Firefox, but it's not working in Chrome. In Firefox I have this situation (where A, B, C, D are divs):

but when accessing the same page with Chrome, this is what I see:

the divs are structured like this:

A

B

C

D

E

F

and the css:
.news-list-container {
    display: inline-block;
    display: -moz-inline-box;
    height: 187px;
    overflow-x: auto;
    overflow-y: hidden;
    width: 700px;
}

.news-list-item {
    border: 1px solid #E5E5E5;
    float: left;
    height: 175px;
    padding: 5px;
    width: 184px;
}

Apparently, Chrome is not recognizing the display: inline-block. Is there something similar/equivalent to -moz-inline-block that does the same for Chrome? If not, how can I obtain the same horizontal scrolling on the two browsers?
Thanks in advance.

A: Solved it after some experimenting. I had to add another div in between and set its width to the total width of the contained elements (considering borders and paddings). This way the display property is no longer needed and everything works in both Firefox and Chrome.

A

B

C

D

E

F

.news-list-container {
    overflow-x: auto;
    overflow-y: hidden;
}

#container {
    height: 187px;
    width: 1176px;
}

.news-list-item {
    border: 1px solid #E5E5E5;
    float: left;
    height: 175px;
    padding: 5px;
    width: 184px;
}

A: USE Below CSS Property .
-webkit-backface-visibility: hidden


text:
Q: Select oldest and newest value from a set of running values I'm trying to get the oldest and newest value of a running (for lack of a better term) value in a specified date window with MSSQL 2008 and I'm struggling.  Here's what the table looks like:
Job      Date         Percent_complete
---      ----         ----------------
1        1/5/2013     5
2        1/10/2013    5
2        1/25/2013    15
2        2/15/2013    25
3        2/15/2013    5
1        2/10/2013    10
1        2/23/2013    20
1        2/24/2013    18
4        1/12/2013    40

For example, in my query, I'd like to ask for the oldest and newest percent_complete for 2/1/2013 - 2/28/2013 and get:
Job   Old    New
---   ---    ---
1     5      18
2     15     25
3     0      5
4     40     40

...so the catch here is that the last percent_complete value before the start date has to carry forward and if there is no record (such as job 3), it needs to assume 0.  Furthermore, the number may step backwards from it's high, as it did with job 1... so min(complete) and max(complete) won't get us there.  Also, I've added a record for Job 4 to illustrate the expected result when there's no record in the reporting window.

A: I can get the result with something like this:
with max_percent as
(
  select Job
    , [Max] = max(Percent_complete)
  from jobs
  where [Date] between '2/1/2013' and '2/28/2013'
  group by Job
),
min_percent as
(
  select Job
    , [Max] = max(Percent_complete)
  from jobs
  where [Date] < '2/1/2013'
  group by Job
)
select Job = coalesce(mn.Job, mx.Job)
  , [Min] = case when mx.Job is not null then mn.[Max] else 0 end
  , [Max] = coalesce(mx.[Max], mn.[Max], 0)
from max_percent mx
  full join min_percent mn on mx.Job = mn.Job
order by Job

SQL Fiddle demo.
But it's a bit difficult to understand your requirements so I'm not sure this will work for your data in all cases. If you add some more data and expected results to the question I can update if required.
Edit after comment:
This new query gives the results you're after:
with jobList as
(
  select distinct Job from jobs
)
select Job
  , [Min] = isnull(case when mx.[Max] is not null then mn.[Max] else 0 end, 0)
  , [Max] = coalesce(mx.[Max], mn.[Max], 0)

from jobList jl
  outer apply
  (
    select top 1 [Max] = j.Percent_complete
    from jobs j
    where [Date] between '2/1/2013' and '2/28/2013'
      and jl.Job = j.Job
    order by j.[Date] desc
  ) mx
  outer apply
  (
    select top 1 [Max] = j.Percent_complete
    from jobs j
    where [Date] < '2/1/2013'
      and jl.Job = j.Job
    order by j.[Date] desc
  ) mn
order by jl.Job

SQL Fiddle with demo.
Again, it's only against a small dataset, but it takes top values by date instead of just the max percentage so hopefully will get you in the right direction.
Second edit:
Just change the query slightly to get your new results:
with jobList as
(
  select distinct Job from jobs
)
select Job
  , [Min] = isnull(mn.[Max], 0)
  , [Max] = coalesce(mx.[Max], mn.[Max], 0)

from jobList jl
  outer apply
  (
    select top 1 [Max] = j.Percent_complete
    from jobs j
    where [Date] between '2/1/2013' and '2/28/2013'
      and jl.Job = j.Job
    order by j.[Date] desc
  ) mx
  outer apply
  (
    select top 1 [Max] = j.Percent_complete
    from jobs j
    where [Date] < '2/1/2013'
      and jl.Job = j.Job
    order by j.[Date] desc
  ) mn
order by jl.Job

SQL Fiddle with demo.

A: Here's another approach:
Step 1. Select rows with Date values no later than the selected month, splitting every job's data into two partitions: the selected month data goes into the New partition, the rest goes into the Old one.
Applied to your example, this would produce the following result set:

Job  Date       Percent_complete  recency
---  ----       ----------------  -------
1    1/5/2013   5                 Old
2    1/10/2013  5                 Old
2    1/25/2013  15                Old
2    2/15/2013  25                New
3    1/15/2013  5                 New
1    2/10/2013  10                New
1    2/23/2013  20                New
1    2/24/2013  18                New
4    1/12/2013  40                Old

Step 2. Rank rows in every partition in the descending order of Date:

Job  Date       Percent_complete  recency  rnk
---  ----       ----------------  -------  ---
1    1/5/2013   5                 Old      1
2    1/10/2013  5                 Old      2
2    1/25/2013  15                Old      1
2    2/15/2013  25                New      1
3    1/15/2013  5                 New      1
1    2/10/2013  10                New      3
1    2/23/2013  20                New      2
1    2/24/2013  18                New      1
4    1/12/2013  40                Old      1

Step 3. Get only rows with the rankings of 1:

Job  Date       Percent_complete  recency  rnk
---  ----       ----------------  -------  ---
1    1/5/2013   5                 Old      1
2    1/25/2013  15                Old      1
2    2/15/2013  25                New      1
3    1/15/2013  5                 New      1
1    2/24/2013  18                New      1

Step 4. Pivot the percentages and default any Old NULLs to 0, and New to Old:

Job  Old  New
---  ---  ---
1    5    18
2    15   25
3    0    5

The following query implements the above logic:
WITH partitioned AS (
  SELECT
    Job,
    Date,
    Percent_complete,
    recency = CASE
      WHEN Date >= '20130201' THEN 'NEW'
      ELSE 'Old'
    END
  FROM atable
  WHERE Date < '20130301'
)
, ranked AS (
  SELECT
    Job,
    Date,
    Percent_complete,
    recency,
    rnk = ROW_NUMBER() OVER (PARTITION BY Job, recency ORDER BY Date DESC)
  FROM partitioned
)
, filtered AS (
  SELECT
    Job,
    Percent_complete,
    recency
  FROM ranked
  WHERE rnk = 1
)
, pivoted AS (
  SELECT
    Job,
    Old = ISNULL(Old, 0),
    New = ISNULL(New, Old)
  FROM filtered
  PIVOT (
    MAX(Percent_complete) FOR recency IN (Old, New)
  ) u
)
SELECT *
FROM pivoted
;

You can test this query at SQL Fiddle.


text:
Q: Variation of Buffon's Needle Problem What is the probability that a square thrown arbitrarily (with random orientation and position) onto an infinite chessboard, the side of which is equal to the side of the board cell, will not cover any corner of any cell?
I got this solution, I would like you to check it out:
Let's say we have $2$ squares with side $2$ and a common center. The first square is rotated relative to the second by an angle: $\displaystyle-\frac{\pi}{4} \leq \phi \leq \frac{\pi}{4}$. Then the first square can be shifted vertically and horizontally by no more than: $\displaystyle \Delta(\phi)=\sqrt{2} \sin \left(\frac{\pi}{4}+|\phi|\right)-1$.
Then the required probability is:
$$ P=\frac{2 \int_{0}^{\pi / 4}(2 \Delta(\phi))^{2} d \phi}{2^{2} \cdot \frac{\pi}{2}}=\frac{2(\pi-3)}{\pi}.$$
Also, if I want to calculate when the square covers $2$ points, then I take $\Delta(\phi)=\tan \phi / 2$?