text:
Q: How to constrain a product to one shipping method? A client of mine sells some products that can not be shipped via regular channels due to extreme size and/or weight.
For these products, I would like to add a setting like "can be shipped regularly".
Then, in the checkout process I would like to check if there are any products in the cart having this flag, and if so: only show the shipment option "delivery on appointment".
I have already developed custom shipment carriers/methods, but do not know what would be a good way to disable any shipment methods for carts that contain a product matching the criteria.
I expected that when I set <sort_order>99999</sort_order> in the carrier's config.xml (so it's rendered last) and then having the following code in the Carrier.php model, I would be able to unset any other possible carriers. However, this does not work.
<?php
class Vendor_ExampleCarrier_Model_Carrier
    extends Mage_Shipping_Model_Carrier_Abstract
    implements Mage_Shipping_Model_Carrier_Interface
{
    /** @var string carrier code */
    protected $_code = 'vendor_examplecarrier';

    /**
     * Collect and get rates
     *
     * @param  Mage_Shipping_Model_Rate_Request $request
     * @return Mage_Shipping_Model_Rate_Result|bool|null
     */
    public function collectRates( Mage_Shipping_Model_Rate_Request $request )
    {
        // ...
        $canShipRegularly = false;
        // ...

        $shippingRateResultModel = Mage::getModel('shipping/rate_result');

        if (true !== $canShipRegularly) {
            // does nothing
            $shippingRatesResultModel->reset();

            // returns empty array
            $shippingRatesResultModel->getAllRates();
        }

        return $shippingRateResultModel;
    }

    // other stuff..
}

I feel this might be a possible solution, if I would be possible to get access to this model in another scope.
Anyone have an idea as to how to accomplish this?

A: You should be able to do this with the Magento table rates shipping method. By limiting the weight for the table rate rules they won't show up if an item is added with sufficient weight to invalidate the rule.
You could also make the weight of the over sized products 9999 for example. This way there is a clear difference between shippable products and over sized products.
Then add the appointment method either as different shipping method or separate rule in table rates and you should be good to go


text:
Q: Не понятно решение
Создайте функцию getRepeats с одним параметром. В этот параметр будет приходить массив данных.
Функция должна возвращать объект, в котором указано сколько раз каждое слово встречается в массиве
Обратите внимание, что счёт начинается не с нуля, а с единицы. Если вы встречаете слово в массиве в первый раз, значит надо записать, что слово встречается один раз, а не ноль.

Не понятна эта часть кода
acc[el]=(acc[el] ||0) + 1

Решение:

const getRepeats = arr=> arr.reduce((acc,el)=>{ acc[el]=(acc[el] ||0) + 1; return acc },{});

console.log(getRepeats(["Василий","Пётр","Иннокентий","Пётр","Иван","Василий"]));

A:

const getRepeats = arr => arr.reduce((acc, el) => {
  //acc[el] = (acc[el] || 0) + 1;
  // or
  /*
  if (!acc[el]) // have not seen this name yet, set count to zero
    acc[el] = 0;
  acc[el] += 1; // increase count by one
  */
  // or
  //acc[el] = (acc[el]? acc[el] : 0) + 1;
  // or
  //acc[el] = acc[el]? (acc[el] + 1) : 1;
  // or
  acc[el] = el in acc? (acc[el] + 1) : 1;
  return acc;
}, {});

console.log(getRepeats(["Василий", "Пётр", "Иннокентий", "Пётр", "Иван", "Василий"]));

redpajama_set_name: RedPajamaStackExchange


text:
Q: If $|a|,|b|<1$, prove that $\frac{|a+b|}{|1+ab|}<1$. So I've gotten as far as $\displaystyle\frac{|a+b|}{|1+ab|}<\frac{2}{|1+ab|}$ which is clearly wrong because it is greater than 1. What am I doing wrong? Is this question even true?

A: We need to prove: /a + b/ < /1 + ab/ <==> (a + b)^2 < (1 + ab)^2 <==> a^2 + 2ab + b^2 < 1 + 2ab + a^2b^2 <==>
(1 - a^2)(1 - b^2) > 0 which is true since /a/ <  1 and /b/ < 1.


text:
Q: Template method pattern with IDisposable in C# I see that the common guideline to implement the disposable pattern in C# is to have an abstract base class that implements the Dispose() method from IDisposable interface and provides a protected virtual Disposable(bool) method. Then sub-classes need to override Disposable(bool) and always do something like:
if (!disposed && disposing)
{
    // dispose resources here

    disposed = true;
}

My question is: wouldn't be possible to reuse this pattern? I don't like to have to manage this "disposed state" in every subclass. We could have some abstract base class like this:
public abstract class AbstractResource : IDisposable
{
    private bool myDisposed = false;

    protected abstract void ReleaseUnmanagedResources();

    protected virtual void ReleaseManagedResources()
    {
        // optionally override this to explicitly call Dispose() of other IDisposable objects
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (!myDisposed)
        {
            if (disposing)
            {
                ReleaseManagedResources();
            }

            ReleaseUnmanagedResources();

            myDisposed = true;
        }
    }

    ~AbstractResource()
    {
        Dispose(false);
    }
}

Then users of this class only need to implement ReleaseUnmanagedResources and (optionally) ReleaseManagedResources. No need to deal with booleans.
I've found that this article proposes a similar technique. But that is it! Nobody else mentions it. Are there flaws with this approach?

A: The biggest flaw with this method is that it takes away a finite resource... the ability to derive from exactly one class means if I use your implementation, I basically can kiss OOP goodbye because I will need to derive many classes from your class and cannot derive them from another class as I could if I implemented the interface.
So in the real world, you'd have a wild mix of some classes using your baseclass, some rolling their own baseclass for business purposes that already incorporates IDisposable and some just implementing the interface. I cannot speak for everybody, but I'd rather have the same construct applied to all classes using a tool (R# for example) than having a wild mixture of things.
If we had the ability to derive from more than one base class, it might be a thing, but we don't in C#.

A: It's worse than you think. If you have a class heirarchy like this, you probably need to check disposed in every  method and property, since the class object can live long past the lifetime of the unmanaged resource, to be sure you never access a disposed resource. This means your abstract class is really not very much help.
It's not as bad as you think. You probably should not be implementing either the finalizer (~AbstractResource()) or the complete Dispose pattern in the first place.
It's common to believe classes need these that in fact should not have them at all. Just because you use an unmanaged resource in a class, it does not necessarily mean that class needs IDisposable, if you use the resource in a way where it is disposed by it's own type. Just because you implement IDisposable does not mean you need a finalizer, if the resource controlled by IDisposable is already finalized by another type.
This article is also worth your time:

IDisposable: What Your Mother Never Told You About Resource Deallocation


text:
Q: Scale down a webpage to 90% When you press Ctrl+- on any browser, the page scales down to 90% of it's original size. I need to replicate that, and open my webpage at 90% of it's original by default, instead of 100% because it looks nicer at 90%.
I tried the most common approach as mentioned here, here, and here, all of which basically tell you to add this block of code in your css.
html
{
    zoom: 0.9; /* Old IE only */
    -moz-transform: scale(0.9);
    -webkit-transform: scale(0.9);
    transform: scale(0.9);
}

The problem with this is that it creates a gap on the left and the right sides, as well as a huge gap on the top, which aren't present when you manually reduce the size by doing a ctrl+-.
This is what happens when I use the above mentioned code - notice the gaps on the left, right, top.

While this is what I want - this is what happens when you do a ctrl+ - manually in your browser.

How do I go about this?
EDIT: As Jonathon said in the comments, if my page looks nicer at 90%, I should have designed it to be that way instead of having to scale down. The problem was that I'm using this default template, and I just prefer it at 90% over the full 100%.

A: You need to use/convert to relative units in your CSS.  Either % or em or rem.
Then at the body level you can set an absolute size that results in the relative measures recalculating to what you want.
If you use em or ex exclusively:
You declare font-size: 90% for body and you'll be able to adjust on the fly.
It all comes down to the units you choose and making them relative will allow you the kind of freedom you are looking for now.

A: Maybe you can compensate this gaps with margin-top:-50px; for specific elements.


text:
Q: How to define conditional compilation symbols in separate file (not .csproj or app.config) We need to define a conditional compilation symbol in a class library project. This should not be checked in the source control (it doesn't apply to all developers), so it should be defined in someplace other than the .csproj or the app.config file. How can this be achieved?

A: This works:
It turns out you can define conditional symbols in the  csproj.user file. I assume the same thing would work for other languages, but I haven't tried.
So just add something like the following to the csproj.user file.
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DefineConstants>MySpecialConstant, TestBlahBlah</DefineConstants>
</PropertyGroup>

I actually like @SimonPStevens solution better because it embraces TFS, instead of hiding. Sometimes, however, this is just easier...

A: I would define your various build types in the configuration manager (menu Build → Configuration Manager) and set up each of the required constants on each of the build types.
You can then have each member of the team simply select the build type they want to do, and it will automatically use the appropriate constants. (I think that the most recently used build type is stored in the .suo file, which is "solution user options" and you wouldn't normally check in to your source control, so this would be maintained specifically for each user).
You can define pre-processor constants on the C# compiler command line using the /define switch, but you will have the problem of how to call this. Any changes you make to the project properties to use this will be saved in the .csproj file. You would have to do all of your building from the command line instead which I'm sure you won't want. You can also define them in MSBuild scripts, but you would have the same problem.


text:
Q: Main menu not appearing in custom post type archive My site's main menu shows everywhere except on the archive of a custom post type "object".
This is caused by this pre_get_posts callback. If I remove it, the menu shows up:

add_action('pre_get_posts', array($this, 'frontend_pre_get_posts_handler'), 99);

// ....

public function frontend_pre_get_posts_handler($query){

      if (is_admin()) {
        return;
      }

      // Tweak which posts to display on frontpage, and order them by "unsold first".
      if ((is_front_page() && $query->is_main_query()) || is_post_type_archive('objet')) {
        $query->set('post_type', array(
          'objet', 'nav_menu_item'
        ));
        $query->set('meta_key', 'wpcf-objet-disponibilite');
        $query->set('orderby', array('meta_value' => 'ASC', 'date' => 'DESC'));
        $query->set( 'posts_per_page', 30);
      }
}

I have added the nav_menu_itempost type, as I suggested in other similar issues, and also changed the priority to 99 to make sure this runs at the end of the hook.
Still, no dice. Any idea?

A: It's because when you use the is_post_type_archive( 'object' ) condition you're checking whether the main query is a post type archive, not whether this query is a post type archive. This means that your code will apply to all queries, including for menus, on the post type archive.
You need to use $query->is_post_type_archive() to check the specific query that is currently being filtered. You already did this correctly for $query->is_main_query().
if ((is_front_page() && $query->is_main_query()) || $query->is_post_type_archive('objet')) {
    // etc.
}


text:
Q: Facebook login not working after first time in Android I have implemented login with facebook in my app and it works perfectly for the first time but after first time it is not working at all. I tried setting breakpoint on onSuccess method but it doesn't stop there. Here is my code for facebook login.
First I initialize it in onCreate method like this
 FacebookSdk.sdkInitialize(this.getApplicationContext());

then I call this method also in onCreate
public void LoginViaFacebook() {
    callbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            //  AppSharedPreference.getInstance(LoginActivity.this).setFbAccessToken(loginResult.getAccessToken().getToken().toString());

            final GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    try {
                        if (object.getString("id") != null) {

                            String fbId = object.getString("id");
                            String name = object.getString("name");
                            String imageUrl = object.getJSONObject("picture").getJSONObject("data").getString("url");
                            int randomPIN = (int) (Math.random() * 9000) + 1000;
                            String password = String.valueOf(randomPIN);
                            String nettype = "2";
                            param.add(new BasicNameValuePair("name", "Vivian"));
                            param.add(new BasicNameValuePair("lastname",fbId));
                            param.add(new BasicNameValuePair("email","valw_umg@yahoo.com"));
                            param.add(new BasicNameValuePair("password",password));
                            param.add(new BasicNameValuePair("nettype",nettype));
                            new FbRegisterAsyncTask().execute();
                            // getLoginTokenViaAPI(fbId);
                            //registerUser(name, name, fbId, password,nettype);

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });

            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender,picture,birthday,link,location");
            request.setParameters(parameters);
            request.executeAsync();
        }

        @Override
        public void onCancel() {
            //AppUtils.showDialog(LoginActivity.this, getResources().getString(R.string.fb_login_cancel));
        }

        @Override
        public void onError(FacebookException exception) {
            //AppUtils.showDialog(LoginActivity.this, getResources().getString(R.string.fb_login_error) + exception.getMessage().toString());
        }
    });

}

onActivityResult method
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case RC_FB_IN:
            callbackManager.onActivityResult(requestCode, resultCode, data);
            break;
    }
}

and on button click I'm doing this
 iv_facebook.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LoginManager.getInstance().logInWithReadPermissions(ActivityLogin.this, Arrays.asList("public_profile", "user_friends", "user_location", "email", "user_birthday"));

            //LoginViaFacebook();
        }
    });

A: After successful login you need to logout from fb before goto next activity, for that use this code to logout from facebook.
LoginManager.getInstance().logOut();


text:
Q: SwiftUI | onDrag - customize (dragItem) preview image appearance I've been wondering if there is any way to customize the preview image of the view that's being dragged when using onDrag?

As you might see, the preview image is by default a slightly bigger opacity image of the view.
From what I have found, a preview image is generated at the very beginning of the dragging process. But I couldn't find a way to change it.
What I mean by customizing is to have some custom image or a preview image of a custom view. (Both without the default opacity)
Does anyone have an idea?
I have tried to use previewImageHandler and in general, read a lot about the NSItemProvider. But for me, it seems like this is something that is not possible for SwiftUI yet?
With UIKit one could have just customized the UIDragItem - something like that using previewProvider: Here
Here is my demo code:
struct ContentView: View {

    var body: some View {
        DraggedView()
            .onDrag({ NSItemProvider() })
    }

    private struct DraggedView: View {

        var body: some View {
            RoundedRectangle(cornerRadius: 20)
                .frame(width: 120, height: 160)
                .foregroundColor(.green)
        }
    }
}

I will use this for drag and drop within a LazyVGrid, so custom gestures are unfortunately no option.
One second idea I had would be to have a gesture simultaneously that first changes the item to be dragged to something else and then onDrag starts and returns the NSItemProvider with the preview image which would be then the one I would want. But I couldn't have those two gestures go at the same time, you would have to dismiss one first in order to start the second.
Thank you!

A: iOS 15 adds an API to do this - you can specify the View to use for the preview. onDrag(_:preview:)
RoundedRectangle(cornerRadius: 20)
    .frame(width: 120, height: 160)
    .foregroundColor(.green)
    .onDrag {
        NSItemProvider()
    } preview: {
        RoundedRectangle(cornerRadius: 18)
            .frame(width: 100, height: 140)
            .foregroundColor(.green)
    }


text:
Q: How can I secure local content by checking a license I have launcher that downloads and launches VR experiences. I also have a server that handles the subscription side of things. Is there a surefire way to protect the content on the local machine until it receives a key or license from the server?
My first thought was to use a session token but that's not going to stop someone from just sniffing the network request and then spoofing it and authorizing their client to play the content. Encryption doesn't seem like it would work as the key would need to be in the client which can then be extracted through various means.
Is there a secure way to decrypt a message sent from a server without having the decryption key exposed in the client?

A: The simplest method would be to have the data encrypted on your download server-side with a random key, and then give that key as the license to decrypt the data once the user acquires the license. Since the key is specific to that download and that user, they don't gain much by intercepting the key. Of course, once the data is decrypted, they can do whatever they want with it. There's no way around that without controlling the hardware.


text:
Q: jQuery hidden div doesn't show again with on change event

    Waive admin fee?

            <select name="waive_admin" required>
                <option value="no">No</option>
                <option value="yes">Yes</option>
            </select>

    Remaining Payments

        <input class="input" type="text" name="pn" value="1" required>

7 or more payments will have $150 extra cost.

    Monthly
    <input type="radio" name="p_option" id="monthly" value="monthly" checked required>
    Customized
    <input type="radio" name="p_option" id="custom" value="custom" required>

I'm trying to hide few divs based on select dropdown value. If the value is Yes, divs have to be hidden, otherwise they have to be shown.
HTML code:

    Total Balance Paid

        <select name="total" id="total">
          <option value="No">No</option>
          <option value="Yes">Yes</option>
        </select>

JS:

$(document).ready(function() {
    $("select[name=total]").on("change", function() {
        if($("select[name=total]").val() == 'Yes') {
          $("#payments,.waive_admin_fee,.remaining_payments").hide();
        } else {
            $("#payments,.waive_admin_fee,.remaining_payments").show();
        }
    });
});

divs are hiding when the value is yes but they are not showing when value is no.

A: Using change event on Select element means the currently selected value has to change. When there are 2 options, this only happens when the other option is selected. Consider the following example.

$(function() {
  $("#total").on("change", function() {
    if ($(this).val() == 'Yes') {
      $(this).parent().next(".pay-info").hide();
    } else {
      $(this).parent().next(".pay-info").show();
    }
  });
});
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

  Total Balance Paid

    <select name="total" id="total">
      <option></option>
      <option value="No">No</option>
      <option value="Yes">Yes</option>
    </select>

      Waive admin fee?

          <select name="waive_admin" required>
            <option value="no">No</option>
            <option value="yes">Yes</option>
          </select>

      Remaining Payments

        <input class="input" type="text" name="pn" value="1" required>

7 or more payments will have $150 extra cost.

      Monthly
      <input type="radio" name="p_option" id="monthly" value="monthly" checked required>
      Customized
      <input type="radio" name="payment_option" id="custom" value="custom" required>

You can see this Select element has 3 options. The User must make a selection.
I would consider changing this to a Checkbox, Radio, or Slider versus a Select element. They are better for binary choices in my opinion.
You may also want to look at your use of Id versus Class. If this page will show multiple customers, then you may want to avoid using id attribute in favor of class. You will also find in jQuery, using - (dash) is going to help more than using _ (underscore) for attribute selectors.
Hope that helps.

A: Probably your problem is that you have malformed selectors. You should not have commas in selectors. I.e. $("#payments,.waive_admin_fee,.remaining_payments").
Here's a working example:
<!DOCTYPE html>

    Total Balance Paid

        <select name="total" id="total">
          <option value="No">No</option>
          <option value="Yes">Yes</option>
        </select>

  hide me

A: You can try this for html. I think at first you must be having multiple selector keeping them without space.

        Total Balance Paid

                <select name="total" id="total">
                    <option value="No">No</option>
                    <option value="Yes">Yes</option>
                </select>

 // define class here
    Remaining Payments

        <input class="input" type="text" name="pn" value="1" required>

7 or more payments will have $150 extra cost.

 // define id here.
    Monthly
    <input type="radio" name="p_option" id="monthly" value="monthly" checked required>
    Customized
    <input type="radio" name="payment_option" id="custom" value="custom" required>

In Jquery
$(document).ready(function () {
    $("select[name=total]").on("change", function () {
        if ($(this).val() === 'Yes') {
            $('#test, .helo').show();
        } else {
            $('#test, .helo').hide();
        }
    });
});

Hope this work for you.


text:
Q: Convert to directed graph to undirected graph in Python igraph I am attempting to draw an undirected graph in iGraph, but the graph I draw seems to have little arrows on it still. Is it possible to convert the directed graph object to an undirected graph object, so that the arrows are gone?
Here's my code:
import igraph
import cairo
import igraph
graph = igraph.Graph.Read_Ncol('network.txt')
igraph.plot(graph)

network.txt =
1 2
2 1
2 3
2 7
3 1
4 2
4 6
5 4
5 6
7 4
7 8
8 9
9 7
10 7
10 8
10 9
11 2
1 2
3 4
5 8
12 3
1 1

A: As documented here: http://igraph.org/python/doc/igraph.GraphBase-class.html
There are functions:
to_directed()
to_undirected()

Depending on which way you want to go (it isn't clear to me from the title).


text:
Q: Looking for any Jetson Nano DockerHub example that uses the GPU I'm getting started with my Jetson Nano and I'm looking for an example that I can launch by running docker run xxx where xxx is some image at DockerHub that uses the GPU.
I assume I'll have to pass in some --device flags, but is there even any kind of "hello world"-style sample ready to go that uses the GPU from docker?
I'm hoping to just demonstrate that you can access the GPU from a docker container on the Jetson Nano.  Mostly to make sure that my configuration is correct.

A: You're not alone in wanting that, but you cannot do it at the moment. The NVIDIA Nano team are aware of the need, and the feature is expected later this year.
See https://devtalk.nvidia.com/default/topic/1050809/jetson-nano/docker-image-to-see-if-cuda-is-working-in-container-on-jetson-nano-/
At present you can run a docker container with TensorFlow or PyTorch installed. but it will only use the CPU, not the GPU.

A: Nvidia Jetpack 4.2.1 enabled easy Docker with GPU on Jetson Nano.
See here for detailed instruction on how to get Docker and Kubernetes running on Jetson Nano with GPU:
https://medium.com/jit-team/building-a-gpu-enabled-kubernets-cluster-for-machine-learning-with-nvidia-jetson-nano-7b67de74172a
It uses a simple Docker Hub hosted image for TensorFlow:


text:
Q: Collapsible footer menu with centered button I am trying to create a collapsible bottom menu in JQuery Mobile 1.3. I simply want an horizontal footer at the bottom with an upward pointing arrow. When the footer is clicked, the menu expands and the arrow points downward. This is almost what I want:
http://jsfiddle.net/6F2XU/
But I can't seem to be able to center the button at all.

Pets

Canary

Cat

Dog

Gerbil

Iguana

Mouse

Javascript
.foot{
margin:0;
padding:0;
}
.ui-btn { width: 100%; height:30px;}
.center-button{
margin: 0 auto;
padding:0 20px 0 20px;
}

Any hints?

A: Solution
Here's a working solution: http://jsfiddle.net/Gajotres/HHnzH/
#custom-collapsible h3 a span span.ui-icon {
    margin: 0 auto !important;
    margin-top: 2px !important;
    float: none !important;
}

HTML change, from this:

to:

I hope this is what you want.
More info
If you want to learn how to do this kind of changes by yourself you should check this article, it will teach you how to do this by yourself.

A: Add this to .center-button:
position:relative;


text:
Q: VSCode LaTeX nicematrix I want to use the package "nicematrix" in VSCode, but it's not working the way I tried.
\documentclass{article}
\usepackage{xcolor}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{mathtools,halloweenmath}
\usepackage{stackengine}
\usepackage{nicematrix}
\begin{document}
\begin{vNiceMatrix}[first-row,last-row,first-col,last-col]
(I)&&x-&y+2z=1 \\
(II)-2x-5y+7z=0 & +2 \cdot (I)\\
(III)&5x+&y-3z=-11 & (-5) \cdot (I)
\end{vNiceMatrix}
\end{document}

The output should look like in this image, but it can't generate an  pdf-file.
enter image description here
I get the following error:
Fatal Package nicematrix: Outside math mode. LaTeX [line 1, column 1]
(nicematrix) The environment {vNiceMatrix} can be used
(nicematrix) only in math mode (and not in \vcenter).
(nicematrix) This error is fatal.

The next big problem is, that a pdf can't be created:
Emergency stop LaTeX [line 256, column 1]
:256: ==> Fatal error occurred, no output PDF file produced!Latexmk: Getting log file 'ombplus.log' Latexmk: Examining 'ombplus.fls
Latexmk: Examining 'ombplus.log
Latexmk: Errors, so I did not complete making targets
Collected error summary (may duplicate other messages):

If I click on the problem with line 256, I get this message:
The Editor couldn't be open due to an unexpected error: The file "..." can't be read (Unknown (FileSystemError): TypeError [ERR_INVALID_ARG_VALUE]: The argument 'path' must be a string or Uint8Array without null bytes. Received 'file(...)/\x00'). Button: Try Again

How I can use the package "nicematrix" in VSCode?
I want to use the package "nicematrix", but VSCode doesn't recognise the package "nicematrix".
I downloaded it with the MikTeX-program: "miktex-pdftex" and this opens automically a "package-installer", if I include a new package in VSCode. Then I tried it with a download of this package in CTAN. It's not working this way.

A: The error is caused by the missing math environment around your nicematrix, add for example \[...\] for an unnumbered equation.
I also think with NiceArray you'll get better alignment:
\documentclass{article}
\usepackage{xcolor}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{mathtools,halloweenmath}
\usepackage{stackengine}
\usepackage{nicematrix}
\begin{document}
\[
\begin{NiceArray}{l|rlll|l}
  \text{(I)}   &x    &-y   &+2z  &=1   & \\
  \text{(II)}  &-2x  &-5y  &+7z  &=0   & +2 \cdot \text{(I)}\\
  \text{(III)} &5x   &+y    &-3z  &=-11 & (-5) \cdot \text{(I)}
\end{NiceArray}
\]
\end{document}


text:
Q: jupyter-notebook for Anaconda for python3 :: kernel is crashing I have Anaconda-2 and Anaconda-3 (meaning for Python2 and Python3, respectively) installed.
Here are the version outputs for each:
Current conda install:
             platform : linux-64
        conda version : 3.18.3
  conda-build version : 1.18.1
       python version : 3.4.3.final.0
     requests version : 2.8.1
     root environment : /home/jdoe/ANACONDA.d/v3.d  (writable)
  default environment : /home/jdoe/ANACONDA.d/v3.d
     envs directories : /home/jdoe/ANACONDA.d/v3.d/envs
        package cache : /home/jdoe/ANACONDA.d/v3.d/pkgs
         channel URLs : https://repo.continuum.io/pkgs/free/linux-64/
                        https://repo.continuum.io/pkgs/free/noarch/
                        https://repo.continuum.io/pkgs/pro/linux-64/
                        https://repo.continuum.io/pkgs/pro/noarch/
          config file : None
    is foreign system : False

Current conda install:
             platform : linux-64
        conda version : 3.18.3
  conda-build version : 1.18.1
       python version : 2.7.10.final.0
     requests version : 2.8.1
     root environment : /home/jdoe/ANACONDA.d/v2.d  (writable)
  default environment : /home/jdoe/ANACONDA.d/v2.d
     envs directories : /home/jdoe/ANACONDA.d/v2.d/envs
        package cache : /home/jdoe/ANACONDA.d/v2.d/pkgs
         channel URLs : https://repo.continuum.io/pkgs/free/linux-64/
                        https://repo.continuum.io/pkgs/free/noarch/
                        https://repo.continuum.io/pkgs/pro/linux-64/
                        https://repo.continuum.io/pkgs/pro/noarch/
          config file : None
    is foreign system : False

When I launch and use jupyter-notebook for Python-2, I have no problems. But, sadly, doing the same for Python-3, results in a repeatedly dying notebook (kernel crashes).
For completeness, I did update conda and anaconda (although they were pretty much the latest already):
jdoe$ conda3 update --prefix /home/jdoe/ANACONDA.d/v3.d conda
jdoe$ conda3 update --prefix /home/jdoe/ANACONDA.d/v3.d anaconda

jdoe$ conda2 update --prefix /home/jdoe/ANACONDA.d/v2.d conda
jdoe$ conda2 update --prefix /home/jdoe/ANACONDA.d/v2.d anaconda

Below is stdout output from the terminal in which I started the kernel (again Anaconda for Python-3).
Anyone know what might possibly be wrong?
Thank you. =:)
[I 15:24:43.388 NotebookApp] Serving notebooks from local directory: /home/jdoe
[I 15:24:43.388 NotebookApp] 0 active kernels
[I 15:24:43.388 NotebookApp] The IPython Notebook is running at: http://0.0.0.0:28888/
[I 15:24:43.388 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[I 15:25:02.182 NotebookApp] 302 GET / (65.209.47.35) 1.40ms
[W 15:25:27.872 NotebookApp] Notebook Google.Drives.d/xxx/CODE.DEV.d/JUPYTER.NOTEBOOKS.d/v3.d/Untitled.ipynb is not trusted
[I 15:25:27.969 NotebookApp] Kernel started: 2c3d6b64-cb0c-49be-bcdf-cc8aefe80afd
[I 15:25:30.969 NotebookApp] KernelRestarter: restarting kernel (1/5)
[W 15:25:38.209 NotebookApp] Timeout waiting for kernel_info reply from 2c3d6b64-cb0c-49be-bcdf-cc8aefe80afd
[I 15:25:39.973 NotebookApp] KernelRestarter: restarting kernel (1/5)
WARNING:root:kernel 2c3d6b64-cb0c-49be-bcdf-cc8aefe80afd restarted
[I 15:25:42.976 NotebookApp] KernelRestarter: restarting kernel (2/5)
WARNING:root:kernel 2c3d6b64-cb0c-49be-bcdf-cc8aefe80afd restarted
[I 15:25:45.979 NotebookApp] KernelRestarter: restarting kernel (3/5)
WARNING:root:kernel 2c3d6b64-cb0c-49be-bcdf-cc8aefe80afd restarted
[I 15:25:48.984 NotebookApp] KernelRestarter: restarting kernel (4/5)
WARNING:root:kernel 2c3d6b64-cb0c-49be-bcdf-cc8aefe80afd restarted
[W 15:25:51.989 NotebookApp] KernelRestarter: restart failed
[W 15:25:51.989 NotebookApp] Kernel 2c3d6b64-cb0c-49be-bcdf-cc8aefe80afd died, removing from map.
ERROR:root:kernel 2c3d6b64-cb0c-49be-bcdf-cc8aefe80afd restarted failed!
[W 15:25:52.033 NotebookApp] Kernel deleted before session


text:
Q: Setting up Octave with gnuplot support in Emacs I added the Octave binary directory containing octave and gnuplot executables to the PATH in Windows 7. This has allowed me to run inferior-octave mode in Emacs.  However, I cannot display graphs like I can with the commandline version.  No errors show up; the graphs just don't appear anywhere.  How can I fix this?
Edit:  GNU Plot wont run in Emacs Calc either, although several GNU Plot related buffers are created.  But there are no errors as far as I can see.

A: Try:
graphics_toolkit gnuplot;

at the Octave console.
I had the same problem and that worked for me.


text:
Q: https protocol based address is not supported - javax.xml.ws.Endpoint I'm trying to create a web service independent or Tomcat of any other Application Server, works well with http, but with https I get the error below. Seems all the documentation relates either to a client example or application server example.
A link to a good tutorial would be great.
Thanks!
Exception in thread "main" java.lang.IllegalArgumentException: https protocol based address is not supported
     at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.publish(EndpointImpl.java:149)
     at com.sun.xml.internal.ws.spi.ProviderImpl.createAndPublishEndpoint(ProviderImpl.java:107)

     at javax.xml.ws.Endpoint.publish(Endpoint.java:181)

A: If you used something like
Endpoint.publish("https://localhost:9999/abc", new YourEndpoint());

to publish your web service endpoint, and got specified exception - looks like internal JDK web server does not support HTTPS.
Please refer here for more information: JAX-WS2 and HTTPS.
And this page has Jetty related information, but it is useful as well: Jetty Webservice - https protocol based address is not supported.
If you don't want to mess with "heavy" Tomcat server, you can use something lightweight.
These pages have good examples of doing it: Java Webservice using HTTPS part 1 and How to develop a standalone SSL web service.
It does not answer question to not use any application server at all, but hope it helps.


text:
Q: Pass context to background task discord.py A server owner  on discord asked me to Add a custom currency system to my bot for him (the bot is only on this server). To encourage activity we did not go with the dailies system and instead my idea was to have a message pop up every 7min with an image and users have to add a "Reaction" to the image. To make it easy and control the inputs i want to add a reaction to my image so users can just click the reaction and it will add the amount.
With all that context out of the way, here is the problem as a background task. I have no clue how to pass context to the reaction!
async def my_background_task():
    await bot.wait_until_ready()
    counter = 0
    channel = discord.Object(id='446782521070321664')
    while not bot.is_closed:
        counter += 1
        with open('vbuck.png', 'rb') as f:
            await bot.send_file(channel, f) #sends a png of a vbuck
            await bot.add_reaction(discord.message,'<:vbuck:441740047897591809>') #This is the Reaction part
    await asyncio.sleep(420) # task runs every 7 min seconds
bot.loop.create_task(my_background_task())

If you could give me advice that would be great and if you are feeling extra generous Code + explanation would be appreciated I am learning python from this project.

A: You need to save the Message object that send_file returns (the message that was sent).  Then you can use that Message object in Client.wait_for_reaction to wait for a reaction.
async def task():
    await bot.wait_until_ready()
    channel = discord.Object(id='446782521070321664')
    vbuck = discord.utils.get(bot.get_all_emojis(), name='vbuck')
    check = lambda reaction, user: user != bot.user
    while not bot.is_closed:
        msg = await bot.send_file(channel, 'vbuck.png') #sends a png of a vbuck
        await bot.add_reaction(msg, vbuck)
        for _ in range(7*60):
            res = await bot.wait_for_reaction(message=msg, emoji=vbuck, check=check, timeout=1)
            if res:
                # res.user reacted to the message

A: If I understood the question correctly, you want to actually wait for users to react to the file you posted and then award them on that reaction. I'm gonna assume you are using discord.py version 1.0 or higher.
The background task itself can not, as far as I know, be handed any context - because it isn't invoked like a comment in a specific context.
However, the API (https://discordpy.readthedocs.io/en/rewrite/api.html#discord.on_reaction_add) states that there is a listener to reactions on messages, which means you can simply use
@bot.event
async def on_reaction_add(reaction, user):
    #here do some checks on reaction.message and to check that it is actually
    #the correct message being reacted too and avoid multiple reactions of one user.

The API will also tell you what kind of checks you can do on the message. You could give the message a certain signature when you let the bot post it (a timestamp like time.time() seems good enough) and then access reaction.message.content and compare it to the current time. To do that, I would modify your background task to something like this:
async def my_background_task():
    await bot.wait_until_ready()
    counter = 0
    channel = bot.get_channel(id='446782521070321664')

    while not bot.is_closed:
        counter += 1
        mess = "maybe a timestamp"
        e = discord.Embed()
        e.set_image(url = "some cool image maybe randomly chosen, please no vbucks")
        await channel.send(mess, embed = e) #sends a message with embed picture
        await asyncio.sleep(420) # task runs every 7 min

the message content will then simply be message.
Hope this helps.


text:
Q: How does the ClojureScript compiler transform cljs to Javascript I am having a little difficulty seeing how this is done. How is it able to convert it to JS without writing any JS (everything is in Clojure or CS).
Can someone give a simple example of how the compiler would convert something simple to javascript. Maybe (def x "foo") or (defn [x] (+ x x))?

A: Emitting JavaScript is handled by the cljs.compiler namespace. (The link is to the source on the master branch.) As you can see, it boils down to printing strings to files.
Which strings exactly depends on the ClojureScript source, of course, but not directly: the original source is first transformed into a different representation more useful during the compilation process. This happens in the cljs.analyzer namespace.
The analyser is rather more involved then the compiler. For your (def x "foo") example, it would produce a fairly simple map which would be handled by the :def method of the emit multimethod of the compiler; search for defmethod emit :def. The things to note are the call to munge (transforming ClojureScript identifiers into valid JavaScript identifiers; e.g. foo-bar -> foo_bar) and the emits call with init as one of the arguments, where the representation of init will be generated recursively. (In this case it'll simply be "foo".)


text:
Q: How to find MongoDB record that has a reference to another document? Say if there're two simple Mongo documents, Person and Class. Person references Class to model a many-to-many this-person-takes-these-classes relationship. How do I find the person that is not registered in ANY classes (that has no references to any Class)?
I tried the following but didn't seem to work:
db.people.find({"class": {$exists: false}});

The above returns all the people, even the ones that are taking classes.
Appreciate any input. Thanks!

A:
Person references Class to model a many-to-many this-person-takes-these-classes relationship.

First you have to define how this is modeled. There are three ways to do this with MongoDB.

*

*Intermediate table, similar to how this is done in SQL.

*Array of references on one collection.

*Array of references in both collections.

Based on your query, it looks like you have #3, but that is not a given.

How do I find the person that is not registered in ANY classes?

This will be very specific to how your data is actually stored in the DB.
Let's say that people contains an array of references to classes, your data will probably look like this:
{ _id: "John", classes: [ 'math', 'science', 'english' ] }
{ _id: "Mary", classes: [ 'computers', 'biology' ] }
{ _id: "Steve", classes: [ ] }

In this case "Steve" clearly has no classes. Your query is looking for people where classes does not exist. But in this case, classes does exist, it's just empty.
If your data looks like this, you probably want to use the [$size][1] operator.


text:
Q: No clan chest after playing the team battle I want to ask that my clan had been finished playing the team battle and I didn't receive the chest ( It was already at 10/10). Is it that we need to wait until the team battle to be finished to get the chest, or it is a glitch

A: According to this wikia page a Clan Chest will be available for opening after collecting all crowns. There isn't any cooldown to open it.
Another condition to get rewards from a Clan Chest is that you must have joined your clan before the Clan Chest Event started. Otherwise you'll have to wait for the next Clan Chest Event.
So, the reasons that you can't collect your rewards from the Clan Chest are:

*

*You joined your clan after a Clan Chest Event started.

*You left your clan and joined back.


text:
Q: How to return to root with popBack using navController Suppose i have 2 fragments: A and B, and my navController switch between them with a link.
The context is a login/signup window, the user can switch between the 2 fragments for login or signup the application, so the backstack looks like this:
A -> B -> A -> B

How can i clear the stack or return to the first A without smashing the back button?
I have tried singleTop, popBackUpTo, inclusive = true but nothing because the fragments repeat eachother.
I heard about another method that replace the fragments instead of navigating, can be a solution to my problem?
EDIT
Is more clear to say: return to the initial A on top of the stack not on the previous one!
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/access_graph"
    app:startDestination="@id/LoginFragment">
    <fragment
        android:id="@+id/LoginFragment"
        android:name="com.example.LoginFragment"
        android:label="fragment_login"
        tools:layout="@layout/fragment_login" >
        <action
            android:id="@+id/action_LoginFragment_to_signupFragment"
            app:destination="@id/SignupFragment" />
    </fragment>
    <fragment
        android:id="@+id/SignupFragment"
        android:name="com.example.SignupFragment"
        android:label="fragment_signup"
        tools:layout="@layout/fragment_signup" >
        <action
            android:id="@+id/action_SignupFragment_to_LoginFragment"
            app:destination="@id/LoginFragment" />
    </fragment>
</navigation>

A: SOLVED
I don't know if i have explained properly the problem, but i have found the solution.
As i sayd in the questions i heard about the replacement of the fragment and that is the main point to solve this type of problem.
I replaced in the code the usage of the navController with the FragmentTransaction, this object allow you to completely block the stack to grow up using the method disallowAddToBackStack(). I don't know why but that function is not mentioned anywhere, i found it by myself looking in the method's object.
Using that function the stack blocks like this:
   stack: [A]         stack: [B]         stack: [A]

(click on link) -> (click on link) -> (click on link) -> ...

so when i push the back button the app is closed as i want.
SUGGESTION
Use the navController when you have more then 2 fragment and you want to create a logical path between those fragments, so when the user push the back button you can let the user go back until a safe point in the path.
Use the FragmentTransaction in conjunction with the method disallowAddToBackStack() when u have some fragments but you don't need some strategical path between them, in other words you are just showing something to the user and you don't care if the user push the back button. The method MUST be used in all the fragment that do not need to be placed in the stack.


text:
Q: read localhost e-mail with thunderbird What would be simplest IMAP server allow Thunderbird to read messages to user@localhost for Ubuntu Linux?
My assumption was that if mailutils could read mail with the "mail" command then IMAP or POP was configured, which was incorrect.

A: If you open the Account Settings menu you should be able to add an new account using Movemail.   It should be located in Account Actions under Add Other Accounts.   This should then move mail from the spool folder into your inbox.
Personally, I use Dovecot with Maildir format directories populated by proccmail.   This allows me to read mail both locally and remotely using the same mailstore.   I also provide webmail access using Squirrelmail.

A: I'd suggest installing alpine/pine (available in most repositories) if you're looking for a lightweight mail reader that can address locally-delivered mail. Short of that, Thunderbird will need to interface with a POP3 or IMAP server on the host.

A: My first suggestion would have been to set up a simple POP or IMAP server, but this email suggests that Thunderbird has native support for local mail accounts via the movemail account type.  I have never tried this out, and in your position I would probably just set up something like Dovecot (which is a POP/IMAP server).
Actually, to be honest, in your position I would simply use mutt, but that's not necessarily the best choice for all people.
EDIT: Additional discussion about Thunderbird and movemail is here.


text:
Q: Sass: module loop when using @use and @forward In my style.scss I am loading a scss file by using:
@use "bootstrap/functions";

Somewhat later in the style.scss I load another scss file called _variables.scss. In this file I also want to use the functions file, for example by doing:
$link-color:                functions.theme-color("primary") !default;
@include functions.assert-ascending($grid-breakpoints, "$grid-breakpoints");

The problem is that I am getting the following error:
SassError: Module loop: this module is already being loaded.
   ┌──> src/assets/scss/bootstrap/_variables.scss
4  │ @forward "functions";
   │ ^^^^^^^^^^^^^^^^^^^^ new load
   ╵
   ┌──> src/assets/scss/style.scss
22 │ @use "bootstrap/functions";
   │ ━━━━━━━━━━━━━━━━━━━━━━━━━━ original load
   ╵

I tried loading it with @use and @forward, I also tried not loading it to see if it can find it in the current context, but nothing works. What am I doing wrong?
I am using Webpack with the sass-loader that uses dart-sass.

A: I think the main reason you're having this issue is that you're trying to load two files that depend on each other; _functions.scss & _variables.scss and this just isn't possible. To load a file, it must be fully executed and this isn't possible when both are depending on each other. There can only be one dependent between two files.
A similar issue was raised on the sass GitHub repo by jacobScripts.

A: I'm currently having the same issue, due to @import being depreciated in October 2022.
This is because you're effectively loading bootstrap/functions into your style.scss twice, once as itself, and once within _variables.scss.
Because @use isn't global, like @import is, it seems to automatically reject any duplications, throwing an error rather than ignoring the duplicate.


text:
Q: Qmake build and gcc includes I am working with Qt and kinda new to it. I want to build a Qt application and created devprog.pro file. However, after executing qmake and make  I get the error

c:\qt473\include\qtcore../../src/corelib/global/qglobal.h(45)
  : fatal error C10 83: Cannot open
  include file: 'stddef.h': No such file
  or directory

So I specified the gcc 4.4.1 include location and the error messages (amongst others) I get is:

c:\codeblocks\MinGW\lib\gcc\mingw32\4.4.1\include\stddef.h(211)
  : error C2371: ' size_t' :
  redefinition; different basic types
          predefined C++ types (compiler internal)(19) : see declaration of
  'size_ t'
  C:\CodeBlocks\MinGW\include\string.h(126)
  : error C2143: syntax error : missing
  ';' before '*'
  C:\CodeBlocks\MinGW\include\string.h(126)
  : error C4430: missing type specifier
  - int assumed. Note: C++ does not support default-int

My question is:
1. How can resolve such error problems as I've scratched my hair off trying to solve this.
2. Is there a way to make automatically let qmake detect your main gcc mingw location without having to set it for each project during qmake execution?


text:
Q: add repeating strings value in json array I have JSON as
var newJSON = [{
    "key": "India",
    "value": "72"
}, {
    "key": "India",
    "value": "27"
}, {
    "key": "Pakistan",
    "value": "90"
}, {
    "key": "Zimbamwe",
    "value": "88"
}, {
    "key": "India",
    "value": "100"
}, {
    "key": "Pakistan",
    "value": "172"
}]

I want desired result as below, where the duplicate key values have their value properties added together:
[{
    "key": "India",
    "value": "199"
}, {
    "key": "Pakistan",
    "value": "262"
}, {
    "key": "Zimbamwe",
    "value": "88"
}]

Please help me with this

A: Here is the solution:
var grouped = [];
var added = [];

for(var i = 0; i < json.length; i++) {
    var indexOfCountry = added.indexOf(json[i].key);
    if (indexOfCountry >= 0)
    {
        grouped[indexOfCountry].value = (Number(grouped[indexOfCountry].value) + Number(json[i].value)).toString();
    }
    else {
        grouped.push(json[i]);
        added.push(json[i].key);
    }
}

grouped array is your desired result.
Fiddle: https://jsfiddle.net/zummw9zp/

A: This is a classic use case for reduce, which is designed to take arrays and somehow, well, "reduce" them to other things, by looping across them and transforming the result at each iteration.
return newJSON.reduce(function(result, entry) {
    key = entry.key;
    result[key] = result[key] || { key: key, value: 0 };
    result[key].value += entry.value;
    return result;
}, {});

Using Underscore
If you're OK with using a library like Underscore, you can write this as
_.mapObject(_.groupBy(newJSON, 'key'), total)

Using a narrative style where we describe
`A(B, C)`

as

Take B and do A to it usingC

and
`A(B(C))`

as

Take C and do B to it. Then take the result and do A to it

we can almost read this as English:

Take newJSON and group it by using key. Then take the result and map the object using total

_.groupBy produces an object keyed by some property and returns groups, which are arrays of all the entries falling into each group:
{
  India: [ {key: "India", value: 72}, {key: "India", value: 100... ],
  ...
}

total calculates the total value for each group:
function total(group) { return sum(group . map(value)); }

So it converts an array of entries
[ {key: "India", value: 72}, {key: "India", value: 100}, ... ],

into 199. We use this to map the arrays of entries to total scores using _.mapObject.
Here sum can be written as
function sum(array)   { return array.reduce(add); }
function add(a, b)    { return a+b; }

and value is a little utility function to retrieve the value property:
function value(entry) { return entry.value; }

So the complete solution is:
function add   (a, b)  { return a+b;                     }
function sum   (array) { return array.reduce(add);       }
function value (entry) { return entry.value;             }
function total (group) { return sum(group . map(value)); }

_.mapObject(_.groupBy(newJSON, 'key'), total)

A: Yet another variant with reduce
var result = newJSON.reduce(function(acc, el){
  var val = acc.map[el.key];
  if(!val){
    acc.map[el.key] = val = { key:el.key, value: parseInt(el.value) };
    acc.result.push(val);
  }else{
    val.value += parseInt(el.value);
  }
  return acc;
},{map:{}, result:[]}).result;

var newJSON = [
    {"key":"India","value":"72"},{"key":"India","value":"27"},
    {"key":"Pakistan","value":"90"},{"key":"Zimbamwe","value":"88"},
    {"key":"India","value":"100"},{"key":"Pakistan","value":"172"}
];

document.getElementById('r').innerHTML = 'newJSON: ' + JSON.stringify(newJSON);

var result = newJSON.reduce(function(acc, el){
  var val = acc.map[el.key];
  if(!val){
    acc.map[el.key] = val = { key:el.key, value: parseInt(el.value) };
    acc.result.push(val);
  }else{
    val.value += parseInt(el.value);
  }
  return acc;
},{map:{}, result:[]}).result;

document.getElementById('r').innerHTML += '

result: ' + JSON.stringify(result);


text:
Q: a strange error i define method in my class and this error occurred.
error C2371: redefinition; different basic types
my Method:
Buffer::SetSourceCode(string str)
    {
        SourceCode=str;
    }

and my class:
class Buffer
{
    string SourceCode;
    int Index;
    int PreIndex;
    int Length;
    public:
        void SetSourceCode(string str);
        void SetSourceFromFile();
        string CopyString();
        string Copy();
        void SetPreIndex(void);
        void IncreaseIndex();
        void ReturnBack();
        bool IsEnd();
        char ReadChar();
        Buffer(void);
        ~Buffer(void);
    };

what is error ?
thanks.

A: As far a i know, Buffer is a "reserved" (existing) name for a class in Visual-C++.  Your class tries to redefine an existing type.
See
http://msdn.microsoft.com/en-us/library/system.buffer.aspx

A: Try to include headers:

#include <string>
using namespace std;


text:
Q: what is wrong in this code...it is not taking input after I enter t #include<stdio.h>

void main()
{

    int t,i=0;
    scanf("%d",&t);

    while(t--)
    {
        char c;
        scanf("%c",&c);
        char s[10]="codeforces";

        while(s[i]!='\0')
        {
            if(s[i]==c)
            printf("YES\n");

            else
            printf("NO\n");

            i++;
        }
    }

}

I tried 10 test cases but the output is 10 times NO

A: For starters according to the C Standard the function main without parameters shall be declared like
int main( void )

After this call of scanf
scanf("%d",&t);

the input buffer stores the new line character '\n' that corresponds to the pressed key Enter.
So the next call of scanf
scanf("%c",&c);

automatically reads this new line character '\n'.
To skip white space characters in the input buffer you need to place a leading space character in the format string like
scanf(" %c",&c);
      ^^^^

Also the inner while loop should be interrupted as soon as the inputted character is found in the string. The messages should be outputted after the while loop. And the variable i is not set to 0 within the outer while loop. So the code has a logical array. You should declare variables in minimum scopes where they are used.
Remove the declaration of i in this line
int t,i=0;

And rewrite the while loop the following way
    size_t i = 0;
    while ( s[i] !='\0' && s[i] != c ) ++i;

    if ( s[i] != '\0' )
    {
        printf("YES\n");
    }
    else
    {
        printf("NO\n");
    }

In whole the program can look for example the following way.
#include <stdio.h>

int main( void )
{
    unsigned int t;

    if ( scanf( "%u", &t ) == 1 )
    {
        while ( t-- )
        {
            const char *s = "codeforces";
            char c;

            scanf( " %c", &c );

            size_t i = 0;

            while ( s[i] != '\0' && s[i] != c ) ++i;

            if ( s[i] != '\0' )
            {
                puts( "YES" );
            }
            else
            {
                puts( "NO" );
            }
        }
    }
}

A: #include<stdio.h>

void main()
{

    int t,i=0;
    scanf("%d",&t);

    while(t--)
    {
        char c;
        scanf(" %c",&c);  // note the addition of a space character before the %c format specifier
        char s[10]="codeforces";

        while(s[i]!='\0')
        {
            if(s[i]==c)
            printf("YES\n");

            else
            printf("NO\n");

            i++;
        }
    }
}

check this one


text:
Q: Can you say which is better, DialogFragment or AlertDialog? I know that both AlertDialog and DialogFragment are customizable. Which of the two is better? If you can say which is better, why?

A: A dialog is a UI that is displayed in a window of its own. The only difference between a Fragment and a dialog is that the Fragment displays its UI in the View hierarchy of the Activity, i.e. in the Activity's window.


text:
Q: Select an id within another id with CSS & php query parameter In Wordpress I have a template that changes certain elements based on a query parameter
e.g. www.mysite.com/member-levels/?level=3
The template creates a div on the page with an id related to this query param.
e.g <div id="mem_level-<?php echo $mem_level->id; ?>">
Within the mem-level div is another div with an id so it looks like this

What I am trying to achieve is to change the mem_message styles differently depending on the mem-level. (It will be different colours etc for membership levels e.g. Bronze, Silver, Gold)
How can I select the different mem_message div's with css so I can style them individually. If it is possible.
Thanks

A: You can select the inner div in CSS like this:
#mem_level-X > #mem_message

Here is a demo:

#mem_level-X > #mem_message {
  color: red;
}

  Outer div

Inner div

  Outer div

However, this is pointless for IDs because they're unique, so it is more efficient to just use the ID of the inner div alone:

#mem_message {
  color: red;
}

  Outer div

Inner div

  Outer div

Edit based on your comment, you will have several boxes and you're changing the ID of the outer box, so that's good. You'll have to do the same for the inner box and change it's ID because IDs must be unique, in which case my comment above is still valid and there is no point in selecting an ID inside another ID, just select the inner ID directly. Alternatively, you can use a class instead of an ID on the inner box and then select them like this:
#mem_level-X > .mem_message

Here is a demo:

#mem_level-1 > .mem_message {
  color: red;
}

#mem_level-2 > .mem_message {
  color: blue;
}

#mem_level-3 > .mem_message {
  color: green;
}

  Outer div

Inner div

  Outer div

  Outer div

Inner div

  Outer div

  Outer div

Inner div

  Outer div

Or you can simply use nothing (neither ID nor class) and select them like this:
#mem_level-X > div

Here is a demo:

#mem_level-1 > div {
  color: red;
}

#mem_level-2 > div {
  color: blue;
}

#mem_level-3 > div {
  color: green;
}

  Outer div

Inner div

  Outer div

  Outer div

Inner div

  Outer div

  Outer div

Inner div

  Outer div

A: I'm not sure if I have misunderstood, but can't you use;
#mem_level-X #mem_message{
  background-color:#ccc;
}

If you have more than one of these on a page, then you may be better to use;
class="mem_message-X" & class="mem_message"

instead with;
.mem_level-X .mem_message{
  ...
}

A: You can a descendant or direct child CSS Combinator.

#mem_message {
  height: 40px;
  width: 80px;
}

#mem_level-1 > #mem_message {
 background-color: #ffbc00;
}

#mem_level-2 > #mem_message {
 background-color: #a7a7a7;
}

#mem_level-3 > #mem_message {
 background-color: #c78027;
}

      Level1

   Level2

   Level3

I recommend that you use classes instead of IDs if there's going to be more than one mem_message / mem_level-x on the same page.

A: its simple : use selector :
#mem_level-X #mem_message{ style  }
as value of x will change according to the url parameter  so you can easily change color scheme according to the level..

#mem_level-1 #mem_message{ border:1px solid #000;background:#555; }
#mem_level-2 #mem_message{ border:1px solid #000;background:red; }
etc....


text:
Q: Google Contacts Fields to fill variables in email template First of all, thank you for your time.
I have been looking for a while for a program, a script or anything that could help me automate a task that otherwise is going to take very long.
See, i'm a french computer technician working for almost exclusively doctors here in France.
The doctors receive results by email, the results are then imported to the patient's folder from the email automatically.
But in order for them to receive that information we have to communicate an email address from a special domain + the doctor's ID that is like your driver's ID.
We use google contact as an address book because it's convenient. Since whenever we make a new maintenance contract with a doctor we input everything to google contact the info is already there. Sometimes we have up to 20 doctors in the same cabinet to set.
Link to a Google Sheet Contact Sample
The fields are the following :
Structure's Name : {{contact company name}} (all the doctors share the same structure)
Strutre's Adress : {{contact full address}} (all the doctors share the same structure)

*

*First doctor

*

*Last Name : {{last_name}}

*First Name : {{first_name}}

*eMail Address : {{email_address}} (this one is tagged MSSANTE in ggC)

*Doc's ID : {{custom_field}} (this is a custom field tagged RPPS in ggC)

*Second doctor

*

*Last Name : {{last_name}}

*First Name : {{first_name}}

*eMail Address : {{email_address}} (this one is tagged MSSANTE in ggC)

*Doc's ID : {{custom_field}} (this is a custom field tagged RPPS in ggC)

So on and so on.
Then this as to be sent to many laboratories all in BCC and the customers/doctors usually in CC
I was thinking of using google sheets or google's people API somehow...
Can someone give me a strategy or some code to start ?
Again thanks to anyone who can help even a bit.

A: Try
function email() {
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const emails = ss.getSheetByName('LABS mails').getRange('C2:C').getValues().flat().filter(r => r != '').join(',')
  MailApp.sendEmail({
    to: emails,
    subject: 'titre du mail',
    htmlBody: body()
  })
}
function body() {
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const template = ss.getSheetByName('Mail Template (Exemple)')
  const docteurs = ss.getSheetByName('Doctors')

  let [headers, ...data] = docteurs.getDataRange().getDisplayValues()
  let debut = template.getRange('A2:A').getValues().flat().filter(r => r != '').join('
')
  let variable = template.getRange('B2:B').getValues().flat().filter(r => r != '').join('
')
  let fin = template.getRange('C2:C').getValues().flat().filter(r => r != '').join('
')
  const liste = ['{CABINET}', '{NOM}', '{PRENOM}', '{EMAIL}', '{RPPS}']
  const colonnes = [1,4,3,8,7]

  let message = debut
  data.forEach((r, row) => {
    var texte = variable
    for (var i = 0; i < liste.length; i++) {
      texte = texte.replace(liste[i], r[+colonnes[i] - 1])
    }
    message += texte + '

'
  })
  message += fin

  return (message)
}

Put the text as follows (you will need a little html tags)

The email will be


text:
Q: HTML5 AutoFocus attribute causes Firefox to scroll to bottom of page We have an HTML5 application (<!DOCTYPE html>) with Twitter Bootstrap and various other JavaScript libraries (including jQuery) - all running on their current versions.
The page contains a text input with the autofocus attribute set.
<input type="text" autofocus="autofocus" />
The page contains more than one 'screen' of content, meaning there will always be a vertical scrollbar on the page. The text input is located within the first 'fold' of the page, approx. 250px from the top of the page.
On Chrome, Safari and Opera the page works as expected. When the page loads, the element is on screen and focused.
On FireFox (current version - 18.0.1) the element has focus, but the page has scrolled to 1533px (determined via window.pageYOffset). The same page with differing lengths of content will always scroll to the same position, and the element will be rendered offscreen.
There is definitely only one element with the autofocus attribute set ($("[autofocus]").length).
Removing the autofocus attribute from the element does not cause the page to scroll at all (i.e. the page remains scrolled to the top - as expected).
Can anyone offer any help or insight?
Things we've tried
The following test works correctly:
<!DOCTYPE html>

Test

    test

    <input autofocus type="text" />

A: We've recently retried this with Firefox and can't replicate the issue.
Closing...

A: You need css code to say this:
.focusedInput {
    border-color: rgba(82,168,236,.8);
    outline: 0;
    outline: thin dotted \9;
    -moz-box-shadow: 0 0 8px rgba(82,168,236,.6);
    box-shadow: 0 0 8px rgba(82,168,236,.6) !important;
}

Then the text input code to be this:
<input class="form-control focusedInput" type="text">


text:
Q: Remove From NSArray if it Contains a Certain Word In my app, I have a UITableView that is currently set to show everything inside the Downloads folder that is a PDF. What I'd like to do is have it show everything UNLESS it contains a specific word. I know I can use NSPredicate to make an NSArray that ONLY has that word, but how can I do the opposite? I've tried making it an NSMutableArray and then looping through it to remove all objects that contain that word, but it isn't working.
NSArray *theNewArray22 = [thefirstNewArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH 'Kids.pdf'"]];
        NSMutableArray *arr = [NSMutableArray arrayWithArray:theNewArray22];

        for (int i = 0 ; i<  arr.count; i++) {
            [arr removeObjectAtIndex:i];
        }
        NSArray *resultArr = [arr mutableCopy];

I was thinking that since the predicate should return ONLY those that end with Kids.pdf, that looping through it to remove each object would work, but for some reason I can't get it.


text:
Q: how to keep a loop going until it reaches a set number I have a data like this
df <- seq(5,10)

I pick the first number
t <- df[1]

I want to do the following (Collatz sequence):

*

*if it is odd then multiple by 3 and +1

*if the answer is even divide by 2 otherwise multiply by 2

*and keep doing this until the answer is 1

Examples:

*

*5 is odd then I multiple by 3 +1 will become 16
and 16 is even then I divide by 2 because 8 and 8 is even I divide by 2 become 4 and I divide by 2 become 2 and I divide by 2 become 1. Finished. Move on to the next number.

*I pick 6, it is even I divide by 2 which become 3 then I multiple by 3 +1 which becomes 10...

I have done this but I don't know how to get it together
if( (df[1]%%2) == 0) {
mydf <- df[1]* 3+1
} else {
mydf <- df[1]/2

I found that this does the job for each number at the time
mydf <-  NULL
n <- 5
while (n != 1) {
  if (n %% 2 == 0) {
    n <- n / 2
  } else {
    n <- (n * 3) + 1
  }
  mydf <- c(mydf, cbind(n))
}

I should always give one number at the time, how can I make it to get numbers one after the other and save the intermediate results as rows?

A: You could use Recursion function:
fun <- function(x){
  if (x == 1) 1     # if 1 RETURN 1
  else if(x %% 2) Recall(x*3 + 1)    # If odd, multiply by 3 add 1 and repeat
  else Recall(x/2)     # otherwise divide by 2 and repeat
}

Your fun can now work on single digits, ie:
fun(5)
[1] 1

We can then vectorize it to make it work on a vector:
collatz <- Vectorize(fun)
collatz(seq(1, 10))
[1] 1 1 1 1 1 1 1 1 1 1

EDIT:
If you need the intermediate steps:
fun <- function(x){
  if (x[1] == 1) rev(x)
  else if(x[1] %% 2) Recall(c(x[1]*3 + 1, x))
  else Recall(c(x[1]/2, x))
}
collatz <- Vectorize(fun)

collatz(seq(5,10))
[[1]]
[1]  5 16  8  4  2  1

[[2]]
[1]  6  3 10  5 16  8  4  2  1

[[3]]
 [1]  7 22 11 34 17 52 26 13 40 20 10  5 16  8  4  2  1

[[4]]
[1] 8 4 2 1

[[5]]
 [1]  9 28 14  7 22 11 34 17 52 26 13 40 20 10  5 16  8  4  2  1

[[6]]
[1] 10  5 16  8  4  2  1

A: Using your code in the for loop for each number.
df <- seq(5,10)
mydf <- numeric(length(df))

for(i in seq_along(df)) {
  n <- df[i]
  while (n != 1) {
    if (n %% 2 == 0) {
      n <- n / 2
    } else {
      n <- (n * 3) + 1
    }
  }
  mydf[i] <- n
}

mydf
#[1] 1 1 1 1 1 1

To get the intermediate steps saved as well use a list.
df <- seq(5,10)
mydf <- vector('list', length(df))

for(i in seq_along(df)) {
  n <- df[i]
  mydf[[i]][1] <- n
  while (n != 1) {
    if (n %% 2 == 0) {
      n <- n / 2
    } else {
      n <- (n * 3) + 1
    }
    mydf[[i]] <- c(mydf[[i]], n)
  }
}

mydf
#[[1]]
#[1]  5 16  8  4  2  1

#[[2]]
#[1]  6  3 10  5 16  8  4  2  1

#[[3]]
# [1]  7 22 11 34 17 52 26 13 40 20 10  5 16  8  4  2  1

#[[4]]
#[1] 8 4 2 1

#[[5]]
# [1]  9 28 14  7 22 11 34 17 52 26 13 40 20 10  5 16  8  4  2  1

#[[6]]
#[1] 10  5 16  8  4  2  1

A: Here is another recursion option
f <- Vectorize(function(x) {
  if (x == 1) {
    return(1)
  }
  c(x, f(if (x %% 2) 3 * x + 1 else x / 2))
})

which gives
> f(c(5:10))
[[1]]
[1]  5 16  8  4  2  1

[[2]]
[1]  6  3 10  5 16  8  4  2  1

[[3]]
 [1]  7 22 11 34 17 52 26 13 40 20 10  5 16  8  4  2  1

[[4]]
[1] 8 4 2 1

[[5]]
 [1]  9 28 14  7 22 11 34 17 52 26 13 40 20 10  5 16  8  4  2  1

[[6]]
[1] 10  5 16  8  4  2  1


text:
Q: Separating array with different objects into specific object arrays in ruby Imagine I have an array with different types of objects such as:
[1,true,'hello',true,2,' ','world']

I'm trying to create a function that outputs an array of arrays with those objects separated.
[ [1,2] , ['hello', ' ', 'world'] , [true,true] ]

So far i've come with this:
def same_object arg
    arg.inject([]){ |acc,value|
            flag = 0
            acc.each do |i|
                if i[0] != nil && value.class == i[0].class
                    i << value
                    flag = 1
                end
            end

            if flag == 0
                acc << [value]
            end
    }
end

The problem is that apparently I get an error when I do:
value.class == i[0].class

Which is kind of weird, because for me it makes sense. I'm new to ruby and I'd appreciate some insight.

A: Your example fails, because you do not return updated acc at the end of the inject block. Just add acc before the closing }:
  #...
  end
  acc
}

Beside that I would do something like this:
[1,true,'hello',true,2,' ','world'].group_by(&:class).values
#=> [[1, 2], [true, true], ["hello", " ", "world"]]


text:
Q: Check if UTF-8 letter is vowel in MATLAB I found a simple way to check whether a letter is a vowel in MATLAB (from here), simply like this :
is_vowel = numel(regexp(letter,'[aeiouAEIOU]'))>0

However, in my language (Turkish), the list of vowels is actually this:
is_vowel = numel(regexp(letter,'[aeiouöüıAEIOUÖÜİ]'))>0

this works correctly for ö and ü (Also for capitals) but it returns 0 for ı and İ. How can I solve this issue so it returns 1 for all the letters in the second list?
P.S. : I will use this code as a base for the latter part of my project which will involve things like getting the number of vowels in a word, so I'm open to alternative solutions too.
Also, if no other way is found, I'm ok with converting the letters to their English counterparts (like Ö to O etc.) but I prefer not changing them.
Thanks for any help!
Edit
I now see that the related part of my .m file is converted to this :
regexp(letter,'[aeiouöü?AEIOUÖÜ?]');

This is probably why regex is not working on those two characters. Any way to save these characters correctly in an *.m file?
Solution
Thanks to @AndrasDeak :
function [b] = is_vowel(letter)
b = ismember(letter,['aeiouöüAEIOUÖÜ' 304 305]);
end

A: As we revealed in comments, the problem is that some Turkish characters are incompatible with matlab, but only as string literals. The solution is to check the problematic letters by their value rather than as characters.
A fast solution is based on using ismember to check if the given letter is among the set of Turkish vowels:
b = ismember(letter,['aeiouöüAEIOUÖÜ' 304 305]);

This makes use of the fact that strings are integer vectors under the hood.
And just to overdo it a bit, you can also define this as an anonymous function:
is_vowel = @(letter) ismember(letter,['aeiouöüAEIOUÖÜ' 304 305]);


text:
Q: EMV development I am new to EMV development.
I would appreciate if someone could give some guide
how to communicate with EMV based card (e.g.,
read card owner, expiry date, etc.) preferably using C++?
Any information (samples, references to links online, etc.)
how to do this welcome.

A: First, you'll have to go through the EMV specification : http://www.emvco.com/specifications.aspx?id=223
If you just want to play a little bit around, on Windows you can use the PC/SC Windows API. If you're ready to switch to C#, this article is a really nice tutorial, with examples.
But if you intend to eventually perform full EMV transactions, it'll be way cheaper and faster to buy an existing EMV level 2 kernel (ex : from http://www.level2kernel.com/emv_kernel.html).


text:
Q: c++ How do you specify one of several overloaded functions as an argument in a template Function I want to use some predefined comparators as an argument for a template function.
A code skeleton:
struct Line
{
    double length() const;
    // some data
};

struct Square
{
    double area() const;
    // some data
};

bool customCompare(const Line& a1, const Line& a2) { return a1.length() < a2.length(); }
bool customCompare(const Square& b1, const Square& b2) { return b1.area() < b2.area(); }

template <typename Comparator>
double calculateSomething(Comparator&& tieBreaker)
{
    Line l1, l2;
    return tiebreaker(l1, l2) ? l1.length() : l2.length();
}

auto result = calculateSomething(customCompare);

However, my compiler (VS12 update 5) gives the following compile errors
error C2914: 'calculateSomething' : cannot deduce template argument as function argument is ambiguous
error C2784: 'double calculateSomething(Comparator &&)' : could not deduce template argument for 'overloaded function type' from 'overloaded function type'

Clearly, what I want to do is to specify the comparator more precisely, like
auto result = calculateSomething(customCompare(const Line&, const Line&));

But this is also not allowed...
how to solve this ? (I know I can resort to a lambda, but is there another way ?)

A: Specify the template parameter type explicitly, like this:
auto result = calculateSomething<bool(const Line&,const Line&)>(customCompare);


text:
Q: Regular expression in java to replace string as mentioned below <#if ${x} == 'abc' > ${add} <#else if ${y} == 'dfg' > bef </#if>

Here I want to remove all ${ and } which are inside < and > . , how can I do it in java?
expected output should be
 <#if x == 'abc' > ${add} <#else if y == 'dfg' > bef </#if>

A: You can try this:
String str = "<#if ${x} == 'abc' > ${add} <#else if ${y} == 'dfg' > bef </#if>";
System.out.println(str.replaceAll("(<#.+?)\\$\\{(.+?)\\}(.+?>)", "$1$2$3"));

Yields:
<#if x == 'abc' > ${add} <#else if y == 'dfg' > bef </#if>

Regex Explanation available here.
EDIT:
I have made some more amendments and also how I assume the else would be implemented. The code should do the trick:
String str = "<#if ${x} || ${z} > ${add} <#else if ${y} == 'dfg' && ${x} == 'abx'> bef <#else if ${y} == 'dfg' > sdadas <#else> ${foo}</#if>";
System.out.println(str.replaceAll("(?<=(?!<#else>)<#|\\|\\||&&)(.+?)\\$\\{(.+?)\\}", "$1$2"));

Given this:
<#if ${x} || ${z} > ${add} <#else if ${y} == 'dfg' && ${x} == 'abx'> bef <#else if ${y} == 'dfg' > sdadas <#else> ${foo}</#if>

Yields:
<#if x || z > ${add} <#else if y == 'dfg' && x == 'abx'> bef <#else if y == 'dfg' > sdadas <#else> ${foo}</#if>


text:
Q: Creating a word document from a template dynamically using values from java objects I want to create a word document from an HTML page.
I am planning to get the values on the HTML page and then pass these values to a document template.
I have used JSOUP to parse the contents of the HTML page and I get the values in my java program. I now want to pass these values to a word document template.
I want to know what are the best techniques I can use to create the document template and pass the values to the template to create the word document.
Thank You.

A: I found something very Interesting and simple. We just need to create a simple .xml template for the document we want to create and then programmatically change the contents of the xml file and save it as a ms word document.
You can find the xml template and the code here.

A: i suggest you use xslt, because your data is already in xml-format and there are well defined xml-formats from microsoft.
You could write a document template with word and save it in xml-format. Then you can convert the word-xml to a xsl-template with your html-xml as input. After the xslt-transformation you have a valid word-xml with your dynamic values from the html-xml.
XSLT example for excel
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="no" />
<xsl:template match="/">
    <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office"
        xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
        xmlns:html="http://www.w3.org/TR/REC-html40">
        ...
        <xsl:for-each
            select="/yourroot/person">
        ...
        <Cell ss:StyleID="uf">
                            <Data ss:Type="String">
                                <xsl:value-of
                                    select="@Name" />
                            </Data>
                        </Cell>
        ..
        </xsl:for-each>

...
</xsl:template>
</xsl:stylesheet>

A: JODReports and Docmosis might also be useful options for you since there is template populate and Doc output.  If DOCX is your real target, then you can write out the document yourself since the XML is published - but that is a lot of work.


text:
Q: how to convert PHP hash into Python I can create random salt using PHP and it works great. Below is my php code
$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));

this generate 128 character like below
647366c3950b5fa89d6c71eaa9933c0e8cdf3e09b903641db41fdfe2591cef92aac46cc7b3b36c664bdbe4544aa24476eecbe19b21317c733e970998563e6a50

How can i achieve that in Python?

A: Here is the solution what you want in python
import uuid
import hashlib

def random_salt():
    s =  uuid.uuid4().hex
    s = hashlib.sha512(str(s).encode('utf-8')).hexdigest()
    return s

print(random_salt())

example output
aa8434ae552feb1421ec4a4a7273b10d3daebf15eaf0620cc61ce1e5d8bd3439f3ab0b23c7048bfa95071fc20c6244269fbfab68af024b6b3d30e393e31209e1

this will generate unique salt in 128 character every time


text: Q: How can I extract my MacBook Pro Notes files so that the data becomes "normal" again after my computer's file system crashed? My MacBook Pro from ca. 2011-2013 or something kind of "crashed" - the computer's file system was ruined - when I did a manual forced shutdown because the Notes app was not responding. When I turned it back on again repeatedly, it was in MacOS Recovery Mode and I sent it in to a computer expert who's having a look at it. He's been able to save/restore many documents - Pages documents, sound files, pictures and videos etc - and also says that the data isn't gone, it's just like scrambled or arranged differently now or something. However: He doesn't know how to extract the files from my Notes app, which are my most important documents. He says that there could be several ways to do this but he's not an expert on this particular Mac file system or computer model/operation system. How does one extract the Notes files and get my data back as readable Notes files?


text:
Q: Prevent app from loading explicit intent every onResume So I have Activity A and Activity B. A is the main screen of the app, and from this activity i can open B. Inside B the user inputs some data that gets sent through an intent back to activity A, then the data is displayed on the screen.
I have noted that while the intent works perfectly, every time I re-open the app on activity A there is an exact copy of the data sent in the last Intent.
onResume of activity A (reciever and displayer of the data)
@Override
    protected void onResume() {
        super.onResume();

        Intent intent = getIntent();
        String name = intent.getStringExtra("name");
        String path = intent.getStringExtra("path");

        setAttrs(name, path);
    }

This is the intent that sends data from B to A, the intent is binded on an OnClick listener
send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                name = mEditText.getText().toString();

                Intent intent = new Intent(SecondActivity.this, MainActivity.class);
                intent.putExtra("name", nameFile);
                intent.putExtra("path", outputFile);
                startActivity(intent);

            }
        });

Thanks in advance.

A: Look into using startActivityForResult() from Activity A.  In Activity B you then call setResult() and provide an Intent which is sent back to Activity A.  In Activity A you'll implement onActivityResult() to process the result.


text:
Q: Dynamic memory re-allocation in custom vector class How I understand, every time when I use word new I must use delete , for avoiding memory leaks. In my example, in push_back() ,I use new for re-allocating dynamic memory to my vector. I think, that every time when I use push_back(), I allocate a new part of memory and dont delete old. If I right, can someone explain me, how I should delete my memory, for saving values in with theirs adresses. If i wrong, please, explain my why?
 class Vector {
        double* ptr;
        size_t size;
        size_t max_size;
        public:
        Vector(): size{0}, max_size{1} {
            ptr = new double(max_size);
        }
        ~Vector(){
            delete pointer;
        }
        void push_back(const double elem) {
            if (size+1 == max_size) {
                double* buf_ptr = ptr;
                max_size*=2;
                ptr = new double(max_size);
            }
            ptr[size] = elem;
            size+=1;
        }
    };

A: Three things:

*

*You want to use new double[maxsize] (allocate array of doubles), not new double(maxsize) (allocate single double value)

*After the new allocation succeed, you want to copy data from the old array (e.g. with std::copy), or you'll drop the old data on the floor

*Once you've succesfully allocated the new array and copied the old data, delete[] buf_ptr to release the old array's memory

All of that can be fixed by replacing this line:
            ptr = new double(max_size);

with these lines:
            ptr = new double[max_size];
            std::copy(buf_ptr, buf_ptr + size, ptr);
            delete[] buf_ptr;

Make sure to #include <algorithm> for std::copy at the top of your source file.
Note: You'd need to adjust your constructor and destructor use matching array based forms of new and delete respectively.


text:
Q: Bootsrap expand on a link, plus link to another page I've got a page that lists out a whole bunch of categories and their associated items.  What I'd like to do is have this page list the categories, and if you click on one, it expands to show the items in that category.  I'm using bootstrap's built in expand/collapse functionality to make this happen.
This is fine, unless the js doesn't load (which might be the case if there's a js error, you're on a slow mobile connection and the js hasn't downloaded yet, etc). To account for these cases, I want my categories to link to a stand alone category page.
The problem is that when you click on the category, it expands the list of items, but then takes you to the category page instead of keeping you where you are at.
Any idea how I can resolve this?  I know I can use return false, but I really don't want to start making modifications to the bootstrap.js file.
Thanks!

  Category 56

  Here is the info to expand and collapse

A: This attribute:
href="link.html"

is your problem.
If you need to test if the related div is fully loaded you may do this:
$($(this).data('target')).length == 1

where this is your toggle_div anchor.
So a possible solution could be:

$('.toggle_div').on('click', function(e) {

  if ($($(this).data('target')).length == 1) {
    //
    // if the related div is loaded you can prevent default action
    //
    e.preventDefault();
  } else {
    // goto next page
  }

});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    Category 56

    Here is the info to expand and collapse


text:
Q: Variation of the determinant of a Jacobian I am following a derivation in a Calculus of Variation problem.
After introducing a one-parameter family of one-to-one mappings from $R^{2}$ to itself, $$z({x},\epsilon)$$, $x = (x_1,x_2)$, such that $$z({x},0) = x$$.
The mapping is used for a change of variable within an integral, hence the issue of computing the variation of the jacobian's determinant arises.
The author says that the obvious identity $$\delta \, det z_{a,b} = \delta z_{a,a}$$
Well as it often happens, it is not entirely obvious to some...Any help would be so appreciated, thanks

A: Hints:

*

*Consider a differentiable function $f: \mathbb{R}^n \times \mathbb{R}\to \mathbb{R}^n$ [let us write $z=f(x,\epsilon)$] with the property that $f(\cdot , 0)={\rm id}_{\mathbb{R}^n}$ is the identity map.

*Define Jacobi matrix $A:=\frac{\partial f}{\partial x}$. Then $\left. A \right|_{\epsilon=0}={\bf 1}_{n\times n}$ is the identity matrix.

*One can argue in several ways that the sought-for identity must hold, e.g.
$$ \left.\frac{\partial}{\partial\epsilon} \det(A)  \right|_{\epsilon=0}
~=~\left. \det(A)^{-1} \frac{\partial}{\partial\epsilon} \det(A)  \right|_{\epsilon=0}
~=~\left.\frac{\partial}{\partial\epsilon}\ln\det(A)  \right|_{\epsilon=0}$$
$$~=~\left.\frac{\partial}{\partial\epsilon}{\rm tr}\ln(A) \right|_{\epsilon=0}
~=~\left.{\rm tr}(A^{-1}\frac{\partial}{\partial\epsilon}A) \right|_{\epsilon=0}
~=~\left.\frac{\partial}{\partial\epsilon}{\rm tr}(A) \right|_{\epsilon=0}. $$


text:
Q: Не срабатывает Input для строки Почему не считывается вводимая строка?
С числами работает, если добавить sval, а со строками никак.

.486
 .model flat, stdcall
 option casemap :none
 __UNICODE__ equ 1
 include C:\masm32\include\windows.inc
 include C:\masm32\include\masm32.inc
  include C:\masm32\include\gdi32.inc
 include C:\masm32\include\user32.inc
 include C:\masm32\include\kernel32.inc
 include C:\masm32\include\winextra.inc
 include C:\masm32\include\msvcrt.inc
 include C:\masm32\macros\macros.asm
 includelib C:\masm32\lib\masm32.lib
 includelib C:\masm32\lib\msvcrt.lib
 includelib C:\masm32\lib\gdi32.lib
 includelib C:\masm32\lib\user32.lib
 includelib C:\masm32\lib\kernel32.lib
 Main   PROTO
 .data
_mov db "test ",0
 .code

 start:

 invoke Main
 invoke ExitProcess,0
 Main proc

    push eax
    mov eax, input() ; <========== Вот тут вся проблема
    mov _mov, eax ; И тут тоже
    pop eax

 Main endp
 end start

Вот то на чём я остановился...
.486
 .model flat, stdcall
 option casemap :none
 __UNICODE__ equ 1
 include C:\masm32\include\windows.inc
 include C:\masm32\include\masm32.inc
  include C:\masm32\include\gdi32.inc
 include C:\masm32\include\user32.inc
 include C:\masm32\include\kernel32.inc
 include C:\masm32\include\winextra.inc
 include C:\masm32\include\msvcrt.inc
 include C:\masm32\macros\macros.asm
 includelib C:\masm32\lib\masm32.lib
 includelib C:\masm32\lib\msvcrt.lib
 includelib C:\masm32\lib\gdi32.lib
 includelib C:\masm32\lib\user32.lib
    ;includelib C:\masm32\lib\winextra.lib
 includelib C:\masm32\lib\kernel32.lib
 Main   PROTO
 .data
 hmyHeap dd 0
 nim dd ?
_mov db "test",0
hMylp1 dd 0
 .code

 start:

 invoke Main
 invoke ExitProcess,0
 Main proc
 invoke GetProcessHeap
 mov hmyHeap,eax

invoke HeapAlloc,hmyHeap,HEAP_ZERO_MEMORY,300h
mov hMylp1,eax

;mov edx, sizeof _mov
;invoke RtlMoveMemory,eax,addr _mov, edx

    push eax

    mov ebx, input()
    mov edx, sizeof (ebx)
    ;mov _mov, eax
    pop eax

mov ebx, [hMylp1]
invoke HeapFree,hmyHeap,NULL,hMylp1

 Main endp
 end start

Ну вот посмотрите вроде-бы всё работает, как вы думаете правильно? Если правильно то в eax у меня адрес на строчку или значение уже?

A:  .486
 .model flat, stdcall
 option casemap :none
 __UNICODE__ equ 1
 include C:\masm32\include\windows.inc
 include C:\masm32\include\masm32.inc
 include C:\masm32\include\gdi32.inc
 include C:\masm32\include\user32.inc
 include C:\masm32\include\kernel32.inc
 include C:\masm32\include\winextra.inc
 include C:\masm32\include\msvcrt.inc
 include C:\masm32\macros\macros.asm
 includelib C:\masm32\lib\masm32.lib
 includelib C:\masm32\lib\msvcrt.lib
 includelib C:\masm32\lib\gdi32.lib
 includelib C:\masm32\lib\user32.lib
 includelib C:\masm32\lib\kernel32.lib
 Main   PROTO
 .data
 addrHeap dd 0
 hMylp1 dd 0
 .code

 start:

 invoke Main
 invoke ExitProcess,0
 Main proc
 invoke GetProcessHeap
 mov addrHeap,eax

 invoke HeapAlloc,addrHeap,HEAP_ZERO_MEMORY,300h
 mov hMylp1,eax
 mov [hMylp1], input()
 mov eax, [hMylp1]
 invoke HeapFree,hmyHeap,NULL,hMylp1

 Main endp
 end start


text:
Q: Draw a circle on top of Renderer2D I created a renderer2D so the user can click and pick the centre of a lesion. I want to show the user where he clicked. Currently my idea is to freeze the renderer (so the slice will be the same and the zoom too) and then use the canvas to draw a circle.
Here is my code:
centerpick2D =  new X.renderer2D();
centerpick2D.container = 'pick_center_segment';
centerpick2D.orientation = 'Z';
centerpick2D.init();
centerpick2D.add(volumeT1DCM);
centerpick2D.render();
centerpick2D.interactor.onMouseDown = function(){
  tumorCenter=centerpick2D.xy2ijk(centerpick2D.interactor.mousePosition[0],centerpick2D.interactor.mousePosition[1]);
  centerpick2D.interactor.config.MOUSEWHEEL_ENABLED = false;
  centerpick2D.interactor.config.MOUSECLICKS_ENABLED = false;
  $('canvas').attr('id', 'xtkCanvas');
  var myCanvas = document.getElementById("xtkCanvas");
  var ctx=myCanvas.getContext("2d");
  ctx.fillStyle="#FF0000";
  ctx.beginPath();
  ctx.arc(centerpick2D.interactor.mousePosition[0],centerpick2D.interactor.mousePosition[1],20,0,Math.PI*2,true);
  ctx.closePath();
  ctx.fill();
};

I have two problems:

*

*The MOUSEWHEEL_ENABLED=false and MOUSECLICKS_ENABLED = false do not work. I tried adding a centerpick2D.init() which works but add a second canvas on top of the previous one.

*My circle does not appear anywhere.
Any help would be greatly appreciated. :-D

A: Sorry took me a while to get this uploaded. Here's a quick overview of how I am copying the XTK canvas' contents into my own canvas and then do my own custom drawing on top of it. The actual code for my project is all over the place, so am just pasting formatted snippets here. Again there's a definite drawback in terms of performance here (due to the copying of pixels), so I think it would be better to introduce all this into the XTK Code in the first place and do all the drawing in one Canvas element.
// initialise animation loop with requestAnimationFrame
startDraw:function(){
        var _this = this;
        var time = new Date().getTime();

        function draw() {
            //update time
            var now = new Date().getTime();

            //only draw the frame if 25 milliseconds have passed!
            if(now > (time + 25)){

                // call drawing function here
                drawFrame();

                time = now;
            }

            requestAnimationFrame(draw);
        }
        requestAnimationFrame(draw);
    };

//...

// actual drawing function, for each frame copy the pixel contents from a XTK canvas
// into custom canvas and do custom drawing on top of it, so drawing is actually at each
// frame

drawFrame:function(){

    //...

    // this.ctx is the context of my own custom canvas element
    // I use drawImage() function to copy the pixels from this.srcCanvasA
    // this.srcCanvasA is a predefined XTKCanvas

    this.ctx.drawImage(this.srcCanvas, 1, 1)

    // custom func to draw on top of this same canvas (ie. this.ctx) with standard
    // HTML Canvas functionality, so this is where you could draw your own circle based
    // on the user mouse coords
    this.drawAnnotation();

    //...
    }

Let me know if you have any more questions. The full code is available here:
https://github.com/davidbasalla/IndividualProject


text:
Q: JMeter Random Variable Element not recognise variable from previous step tl;dr
When I use my variable created in Regular Expression Extractor I cannot use it in Random Variable as Maximum Value
Long description:

*

*My test structure:

*

*

*I have variable my_test what is crated in Regular Expression Extractor

*

*request: GET //echo.getpostman.com/get?test=123

*regex:

*

*Then I want it use as Maximum Value in  Regular Expression Extractor

*

*

*So finally I can make request:

*

*//echo.getpostman.com/get?test=${rand}
Unfortunately I get error from Random Variable
2016/10/07 07:52:41 ERROR - jmeter.config.RandomVariableConfig: maximum(${my_test}) must be > minimum1)
Why my_test is not evaluated?
I have tried ${__javaScript(parseInt('${my_test}'))} but it looks like it is evaluated before my variable initialization
2016/10/07 08:06:01 ERROR - jmeter.config.RandomVariableConfig: maximum(NaN) must be > minimum1)
If I initialize this variable in Test Plan in User Defined Variables value from that setting will be used - not updated by regex.
I know that I can do //echo.getpostman.com/get?test=${__Random(0,${my_test})}
I'm just curious how pass my variable as value for Maximum Value in  Regular Expression Extractor.

A: Random Variable is a Config Element and it will be executed first before any other components get executed first.

4.9 Execution order

*

*Configuration elements

*Pre-Processors

*Timers

*Sampler

*Post-Processors (unless SampleResult is null)

*Assertions (unless SampleResult is null)

*Listeners (unless SampleResult is null)

If two or more Config elements present in the Test Plan, then they will be executed in the order they appear in the Test Plan.
Check the execution order and Scope here:
Refer 4.9 7 4.10 here Execution Order and Scope Rules
So, first Random Variable is evaluated first and then Sampler and then regular expression extractor.
When you used User Defined Variables, which is another Config Element, and probably you put it before Random Variable, so it evaluated the expression as you already defined the value for "my_test". But it won't override the value you captured in Regular Expression Extractor.
To solve your problem (one probable solution):
you can use different thread groups. In first thread group, you capture the value and in second thread group, you use the value.

*

*Run Thread Groups consecutively.

*Use BeanShell Assertion to capture the value by setProperty. (in first thread group)

*Use value using __property() (in thread group)

https://www.blazemeter.com/blog/knit-one-pearl-two-how-use-variables-different-thread-groups

A: It seems that Random Variable element does not evaluate variables, maybe it worth creating an issue in JMeter Issue Tracker
As a workaround you can substitute it with __Random() function directly where required like:

*

*${__Random(1,${my_test},)} - if you need the value right away, directly in you URL:
//echo.getpostman.com/get?test=${__Random(1,${my_test},)}

*${__Random(1,${my_test},rand)} - if if you need to store the value into ${rand} variable as well
See:

*

*Using JMeter Functions article for extended information on this and others JMeter Functions.

*Function Helper Dialog - an utility helping to generate correct function syntax.

A: I think it's valid for me to comment on a problem I had, I set the random variable and it didn't work at all, I did everything I could to try to solve it.
In the end my problem was a space at the beginning of the variable.

A: One possibility is you can use a Beanshell Postprocessor to write the RegEx value to the variable name.
After that you can use it as ${variable_name}
NB: Beanshell function vars.get can be used for getting regex value and vars.put can be used for putting it into your variable.