text:
Q: What is the set notation for an image with data?? I want to describe all data-points $x_i,...,x_n$ on a 2D digital image, say $X$. Each pixel is either background, or a datapoint. Is it possible to describe all of that as a set? I guess something like this where $k$ is meant to be a non-data pixel, but i'm not sure:
$$X = \{\{(x_i,x_j) \in \mathbb{R}^2 | i,j \neq k, k = 0\} \subset \mathbb{R}^2$$

A: An issue with trying to represent a 2D digital image with a set is that you lose information regarding the position of pixels relative to each other.
Even more, as you have it now, there is no way of determining the state of a pixel: how can we know if $(x_i, y_i)$ is a background pixel or a data pixel?
This is like trying to show someone what a fully-built lego set looks like by showing them a bag of pieces it's comprised of.
I'd say it'd be better if you represented your image with a matrix since, by definition, digital images are matrices with pixel elements.


text:
Q: Django Rest Framework, "lookup_field" value that is defined on models level I faced with an issue in Django Rest Framework when I try to implement hyperlink related stuff.
Let's say there is a model with slug that is defined during save procedure
class Family(models.Model):
    name = models.CharField(unique=True, max_length=150)
    slug = models.SlugField(unique=True)
    description = models.TextField(blank=True)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.slug)
        super().save(*args, **kwargs)

So in my serializers package I have the following:
class FamilySerializer(serializers.ModelSerializer):

    class Meta:
        model = Family
        fields = ["name", "slug", "description", "url"]

        extra_kwargs = {
            "url": {"view_name": "api:family-detail", "lookup_field": "slug"},
            # I have to mark this field as not required one to be able POST wo this field
            "slug": {"required": False}
        }

When I try to create a new Family through POST request, of course, I'm getting
django.urls.exceptions.NoReverseMatch: Reverse for 'family-detail' with keyword arguments '{'slug': ''}' not found. 2 pattern(s) tried: ['api/families/(?P<slug>[^/.]+)\\.(?P<format>[a-z0-9]+)/?$', 'api/families/(?P<slug>[^/.]+)/$'] and django.core.exceptions.ImproperlyConfigured:... exception as well.
And here is my ViewSet:
class FamilyViewSet(ModelViewSet):
    """
    Provides CRUD operations on Family entity.
    """
    serializer_class = FamilySerializer
    queryset = Family.objects.all()
    lookup_field = "slug"
    permission_classes = [permissions.IsAdminUser]

How to elaborate the issue I faced. Should I modify FamilyViewSet to generate slug on ViewSet level or take a look at "custom" reverse?

A: My fault/typo in save method:
def save(self, *args, **kwargs):
    self.slug = self.name(self.slug)  # <-- must be self.name, but not self.slug
    super().save(*args, **kwargs)

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the difference between @Inject and @Autowired i am just wondering what is the difference between @Inject & @Autowired
when to use each one ?, or they are doing the same thing ?
and if i have a spring bean which have a scope:
@Service
@Scope("singleton")

can i make dependency injection for it with both with no problems ?
thanks in advance.

A: From what I know, they do the same. @Inject is an annotation from javax.inject, which is only the API for dependency injection. In Spring you can use both, as I think Spring provides an implementation for @Inject which does the same thing as @Autowired in Spring environments.
Matthias Wessendorf blogged about this here: http://matthiaswessendorf.wordpress.com/2010/04/20/spring-3-0-and-jsr-330-part-2/

A: How about reading the documentation?

JSR 330's @Inject annotation can be used in place of Spring's
  @Autowired in the examples below. @Inject does not have a required
  property unlike Spring's @Autowired annotation which has a required
  property to indicate if the value being injected is optional. This
  behavior is enabled automatically if you have the JSR 330 JAR on the
  classpath.

A: I think it is worth pointing out that, if you use @Autowired, you are creating a dependency on Spring, where using @Inject, you will be able to swap out another dependency injection framework that supports JSR 330.

A: First, @Autowired is defined by Spring Framework but @Inject came from "Dependency Injection for Java" (JSR-330)"
Second, @Inject doesn't take required attribute so if it fails to find any bean, it will fail with an error but @Autowired can come with required=false and will allow a nullable field.
Third, Advantage of @Inject annotation is that rather than inject a reference directly, you could ask @Inject to inject a Provider. The Provider interface enables, among other things, lazy injection of bean references and injection of multiple instances of a bean.


text:
Q: JUnit test method, testing a feature of a add method Suppose that the add method of MyList takes one argument, and is specified to throw a
NullPointerException if null is given as its argument. Complete this JUnit test method to test that feature of
the add method:
    public void testAddNull() {
    MyList<String> ls = new MyList<String>();

    }

this is the answer:
    public void testAddNull() {
    MyList<String> ls = new MyList<String>();
      try {
        ls.add(null);
        fail();
        } catch (NullPointerException e) {
      }
    }

why exactly is fail(); needed here, wouldn't the ls.add(null) cause it to fail, so isn't putting fail(); here redundant?

A: The above test method will fail, if the ls.add(null); does not throw a NullPointerException. Since the desired behavior is to throw an exception, the test will pass when the exception is catched at catch (NullPointerException e).
With Junit 4 You could also do this:
@Test(expected = NullPointerException.class)
public void testAddNull() {
    ls.add(null);
}

which would require the tested code to throw a NullPointerException. Otherwise, the test would fail.


text:
Q: "Expected type parameter" error in the constructor of a generic struct I am trying to store piston textures in a struct.
struct TextureFactory<R> where R: gfx::Resources {
    block_textures: Vec<Rc<Texture<R>>>,
}

impl<R> TextureFactory<R> where R: gfx::Resources  {
    fn new(window: PistonWindow) -> Self {
        let texture = Rc::new(gfx_texture::Texture::from_path(
            &mut *window.factory.borrow_mut(),
            "assets/element_red_square.png",
            Flip::None, &TextureSettings::new()
        ).unwrap());
        let block_textures = Vec::new();
        block_textures.push(texture);

        TextureFactory {
            block_textures: block_textures,
        }
    }
}

This does not compile:
src/main.rs:37:9: 39:10 error: mismatched types:
 expected `TextureFactory<R>`,
    found `TextureFactory<gfx_device_gl::Resources>`
(expected type parameter,
    found enum `gfx_device_gl::Resources`)

gfx_device_gl::Resources implements gfx::Resources though (I think it's just the device specific implementation.) I don't actually care what type this is, but I need to know so that I can store it in the struct.
I made a compilable repo on Github.
(I suspect Rust generics/traits: "expected 'Foo<B>', found 'Foo<Foo2>'" is the same question, but I can't figure out how to apply it to my problem.)

A: Here's a reproduction of your error:
struct Foo<T> {
    val: T,
}

impl<T> Foo<T> {
    fn new() -> Self {
        Foo { val: true }
    }
}

fn main() {}

The problem arises because you tried to lie to the compiler. This code:
impl<T> Foo<T> {
    fn new() -> Self {
        /* ... */
    }
}

Says "For whatever T the caller chooses, I will create a Foo with that type". Then your actual implementation picks a concrete type — in the example, a bool. There's no guarantee that T is a bool. Note that your new function doesn't even accept any parameter of type T, which is highly suspect as that's how the caller picks the concrete type 99% of the time.
The correct way of saying this would be
impl Foo<bool> {
    fn new() -> Self {
        Foo { val: true }
    }
}

Although you probably want to pick a more specific name than new, as it looks as if you are trying to make your struct generic. Presumably there would be other constructors with different types.
For your exact code, you probably want something like
impl TextureFactory<gfx_device_gl::Resources> { /* ... */ }

Another possible solution would be to remove the generic type parameter from your struct. If you only ever construct it with a gfx_device_gl::Resources, then there's no reason to make it generic.
In other cases, you may be trying to return a type that implements a trait. For that, you can use a boxed trait object:
impl Foo<Box<dyn std::fmt::Display>> {
    fn new() -> Self {
        Foo { val: Box::new(true) }
    }
}

In the future, you may also be able to use impl Trait (a.k.a. existential types):
#![feature(type_alias_impl_trait)]

struct Foo<T> {
    val: T,
}

type SomeConcreteButOpaqueType = impl std::fmt::Display;

impl Foo<SomeConcreteButOpaqueType> {
    fn new() -> Self {
        Foo { val: true }
    }
}

See also:

*

*What is the correct way to return an Iterator (or any other trait)?


text: Q: does asp.net core web applications come under uwp? I saw in some blogs that apps for windows pc, windows phone etc come under uwp. But I cound not find anywhere mentioning if asp.net core web application comes under uwp. If yes then can we apply Microsoft's new fluent design to a asp.net core web app?


text:
Q: How to hide a picture box on another Form To elaborate on the title:
I currently have 2 forms.

*

*Form1 = Main form

*Form2 = linked to Form1 using ShowDialog()
Form1 has 3 picture boxes and a button
Form2 is a simple Fillable form and what I want it to do is when I click the OK button on Form2, I have form2 set to close But I need to hide the picture boxes and buttons on Form1, i.e. have it show blank.
I'm not too sure what I am doing wrong.
I added the picture boxes as public declaration in Form2.vba
Public Class CreateNewProject

'declare Form1 objects
Public Img_Documentation As PictureBox
Public Img_OnlineResources As PictureBox
Public Img_Tutorials As PictureBox

And I added the .hide() to each picture box in my button sub
Private Sub ButtonOK_Click(sender As Object, e As EventArgs) Handles ButtonOK.Click

    If TextNewProjectName.Text = "" And TextSaveFileLocation.Text = "" Then
        MessageBox.Show("Please enter a " & LabelProjectFileName.Text & vbCrLf & vbCrLf & "Please choose a " & LabelSaveFileLocation.Text, "Warning")
    Else
        'Close current form
        Me.Close()
        'Close objects on Form1
        Img_Documentation.Hide()
        Img_OnlineResources.Hide()
        Img_Tutorials.Hide()
    End If
End Sub

Alternatively, I tried creating a new blank form (form3) opening that form after closing form2 which worked great but I cannot get Form1 to close using Form1.close().
 Me.Close()
 Form3.Show()
 Form1.close()

A: Simply hide the PictureBox on your Form1 Before you open Form2:
PictureBox1.Visible = False
PictureBox2.Visible = False
PictureBox3.Visible = False
Form2.Show()


text:
Q: Datagridview like control for asp.net I need to use something like DataGridView of winforms on asp.net webform.  If I use GridView control of asp.net, the look and functionality is really poor.
Is there anything else that could give me better look and functionality as Datagridview is not available in asp.net?

A: I use this: http://www.jtable.org/
It uses JQuery and AJAX and provides something way different then gridview.

A: there are a number of 3rd party webforms controls from componentOne, Telerik, and DevExpress that may suit your needs.
if you don't have a budget for purchasing controls then WebGrid and/or plain old Html along with some js and css to spice up the UX is your next option.
remember that webforms (http for that matter) is a different experience for the user a web app shouldn't necessarily be exactly the same as the desktop and vice versa. trying to fit the concepts of on into the other means you are working against the framework, not with it.


text:
Q: AngularJS - accessing directive scope So, I'm looking to use ui.bootstrap.tooltip to appear when an element in a form is invalid.
I'm using a directive to do this - it's a bit ugly, but it works. Except for one thing - the controller isn't seeing the updated model values due to another scope being created in the directive.
I can get the model value through the form and using $viewValue, but this seems a bit "unclean" to me.
Also, is there a better way to get the "tooltip element", that I'm using elem.parent().children()[2]; for? I suppose I could create a <template> in the directive for all this.
The JSFiddle is at: http://jsfiddle.net/n8vNw/2/

A: You have created a parser function but never return a value from it. A parser function is used to parse the input value before it ends up in your model. Since a value never is returned, $scope.email will always be undefined.
Secondly there's no reason for your directive to create an isolated scope since you don't use that anyway, unless you're not showing us all the code--in such case us the $parse service instead.
Regarding how you access the tooltip element, perhaps let your formTooltipError directive create and add the element using the $compile service. (I haven't used Angular Bootstrap so there might be an easier/better answer.)
Updated fiddle.


text:
Q: How to get Wikidata ID for an entity of a property ? Is there an API available for python? The MediaWiki API is able to find ID for an item with the request URL:
/w/api.php?action=query&format=json&prop=pageprops&titles=skype&formatversion=2&ppprop=wikibase_item
The result is:
{
    "batchcomplete": true,
    "query": {
        "normalized": [
            {
                "fromencoded": false,
                "from": "skype",
                "to": "Skype"
            }
        ],
        "pages": [
            {
                "pageid": 424589,
                "ns": 0,
                "title": "Skype",
                "pageprops": {
                    "wikibase_item": "Q40984"
                }
            }
        ]
    }
}

However, it does not work well when querying about a property, e.g., developer P178. The result is Q409857 rather than the desired P178:
{
    "batchcomplete": true,
    "query": {
        "normalized": [
            {
                "fromencoded": false,
                "from": "developer",
                "to": "Developer"
            }
        ],
        "pages": [
            {
                "pageid": 179684,
                "ns": 0,
                "title": "Developer",
                "pageprops": {
                    "wikibase_item": "Q409857"
                }
            }
        ]
    }
}

Is there any way to get the ID for an entity which could be an item, a property or even a lexeme?

A: You could use on Wikidata the search API.
For example, to find properties with the name "developer" inside, use
https://www.wikidata.org/w/api.php?action=query&list=search&srsearch=developer&srnamespace=120
120 is the property namespace. To find a lexeme, use srnamespace=146.
Note, this API guesses your language and adapts the results correspondingly. If you don't live in an English speaking country, the above example may thus fail.


text:
Q: Once inserted, data in Firebase is automatically disappearing for some reason This video shows exactly what I mean. Firebase stores data.
The video is:
https://www.youtube.com/watch?v=DCg00fe-_xs
After the 6th second of the video, trying to enter new data, the data stays about a second in Firebase, but automatically then it disappears.
I try to input the data into Firebase two more times in this video, but the data always automatically disappears afterwards.
You can see that the other data that is stored in Firebase does NOT disappear.
But the data of this code is automatically disappearing for some reason as shown in the video.
Please what can I do to fix it?
Code:
 button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String raça = spinner_raca.getSelectedItem().toString();
                final String regiaoDoEstado = spinner_regiaoDoEstado.getSelectedItem().toString();
                final String estado = spinner_estado.getSelectedItem().toString();

                Intent receiverIntent = getIntent();
                Bundle bundleRecebedor = receiverIntent.getExtras();
                String nomecompleto = bundleRecebedor.getString("nomecompleto");
                String email = bundleRecebedor.getString("email");
                String doencasPreExistentes = bundleRecebedor.getString("doencasPreExistentes");
                String dataDeNascimento = bundleRecebedor.getString("dataDeNascimento");
                String genero = bundleRecebedor.getString("genero");
                String identificadorEmHash = bundleRecebedor.getString("identificadorEmHash");
                String telefone = receiverIntent.getStringExtra("telefone");

                reference = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(identificadorEmHash);
                Toast.makeText(getApplicationContext(), identificadorEmHash, Toast.LENGTH_LONG).show();
                if(identificadorEmHash.equals(null)) {
                    Toast.makeText(getApplicationContext(), "The identifier does not exist", Toast.LENGTH_LONG).show();
                } else {
                    reference.addListenerForSingleValueEvent(new ValueEventListener() {
                //    reference.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {

                        }
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            reference = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(identificadorEmHash);
                            if (!dataSnapshot.exists()) {
                                Toast.makeText(getApplicationContext(), "The identifier does not exist", Toast.LENGTH_LONG).show();
                            } else {

                                HashMap<String, String> sendDataToDataBase = new HashMap<>();
                                    sendDataToDataBase.put("Nome Completo", nomecompleto);
                                    sendDataToDataBase.put("E-mail", email);
                                    sendDataToDataBase.put("Identificador em Hash", identificadorEmHash);
                                    sendDataToDataBase.put("Telefone", telefone);
                                    sendDataToDataBase.put("Doenças Pré Existentes", doencasPreExistentes);
                                    sendDataToDataBase.put("Data de Nascimento", dataDeNascimento);
                                    sendDataToDataBase.put("Gênero", genero);
//                  // When I am going to send the following data to Firebase, the problem of the video happens.
                                    sendDataToDataBase.put("Região do Estado em que mora", regiaoDoEstado);
                                    sendDataToDataBase.put("Raça", raça);
                                    sendDataToDataBase.put("Estado do Brasil em que mora", estado);

                                try {
                                    raiz.child(identificadorEmHash).setValue(sendDataToDataBase);

                                } catch (Exception e) {
                                    e.getMessage();
                                }

                                Intent senderIntent = new Intent(getApplicationContext(), MainActivity0.class);
                                senderIntent.putExtra("nomecompleto", nomecompleto);
                                senderIntent.putExtra("email", email);
                                senderIntent.putExtra("doencasPreExistentes", doencasPreExistentes);
                                senderIntent.putExtra("dataDeNascimento", dataDeNascimento);
                                senderIntent.putExtra("genero", genero);
                                senderIntent.putExtra("raça", raça);
                                senderIntent.putExtra("estado", estado);
                                senderIntent.putExtra("regiaoDoEstado", regiaoDoEstado);
                                senderIntent.putExtra("identificadorEmHash", identificadorEmHash);
                                senderIntent.putExtra("telefone", telefone);
                                startActivity(senderIntent);
                            //    Toast.makeText(getApplication(), "Success!", Toast.LENGTH_LONG).show();
                            }
                            Toast.makeText(getApplicationContext(), identificadorEmHash, Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        });

Please, what to do to fix the problem shown on the video?

A: You are calling MainActivity0 at the end of the code. The problem can be there


text:
Q: Using a for loop in a Mocha Test I'm new to mocha, and I wanted to try using a for loop to create test cases.  I want to test a function that I've made that takes an input of standard 12 hour time, and outputs it into 24 hour military time.  This is what it looks like.
exports.main = function(time) {
var hr = parseInt(time.substr(0,2));
var period = time.substr(8,10);
if (period == 'AM' && hr == 12) {
    hr = '0';
}
if (period == 'PM' && hr < 12) {
           hr += 12;
}
    hr.toString();
    if (hr < 10) {
        hr = '0' + hr;
    }
 return time = time.replace(/^\d{2}/g, hr).substr(0,8);

}

To test my function in mocha, I have two arrays, one array holds the standard times and the other holds the corresponding expected output.  I want to iterate through them and produce a test case for each iteration and test my function.
test_array = ["12:00:00AM", "01:00:00AM", "02:00:00AM", "03:00:00AM", "04:00:00AM",
"05:00:00AM", "06:00:00AM", "07:00:00AM", "08:00:00AM", "09:00:00AM",
"10:00:00AM", "11:00:00AM", "12:00:00PM", "01:00:00PM", "02:00:00PM",
"03:00:00PM", "04:00:00PM", "05:00:00PM", "06:00:00PM", "07:00:00PM",
"08:00:00PM", "09:00:00PM", "10:00:00PM", "11:00:00PM"];

against = ["00:00:00", "01:00:00", "02:00:00", "03:00:00", "04:00:00",
"05:00:00", "06:00:00", "07:00:00", "08:00:00", "09:00:00", "10:00:00",
"11:00:00", "12:00:00", "13:00:00", "14:00:00", "15:00:00", "16:00:00",
"17:00:00", "18:00:00", "19:00:00", "20:00:00", "21:00:00", "22:00:00",
"23:00:00"]

This is what my test script looks like:
var converter = require('../modules/time.js');
describe('Time Converter', function() {
 describe('main()', function() {
  for(i = 0; i < 24; i++) {
   it(test_array[i]  + ' should convert to ' + against[i], function() {
   var test = converter.main(test_array[i]);
   assert.equal(test, against[i]);
   });
  }
 });
});

The following is the results of the tests:
0 passing (23ms)
24 failing

1) Time Converter main() 12:00:00AM should convert to 00:00:00:
 TypeError: Cannot read property 'substr' of undefined
  at Object.exports.main (app/modules/time.js:43:27)
  at Context.<anonymous> (app/test/test.js:35:26)

2) - 24) has the same result:

24) Time Converter main() 11:00:00PM should convert to 23:00:00:
 TypeError: Cannot read property 'substr' of undefined
  at Object.exports.main (app/modules/time.js:43:27)
  at Context.<anonymous> (app/test/test.js:35:26)

However when I change the for loop to
for(i = 0; i < 23; i++)

All the tests pass except, naturally it doesn't test the last test case.
Time Converter
main()
  ✓ 12:00:00AM should convert to 00:00:00
  ✓ 01:00:00AM should convert to 01:00:00
  ✓ 02:00:00AM should convert to 02:00:00
  ✓ 03:00:00AM should convert to 03:00:00
  ✓ 04:00:00AM should convert to 04:00:00
  ✓ 05:00:00AM should convert to 05:00:00
  ✓ 06:00:00AM should convert to 06:00:00
  ✓ 07:00:00AM should convert to 07:00:00
  ✓ 08:00:00AM should convert to 08:00:00
  ✓ 09:00:00AM should convert to 09:00:00
  ✓ 10:00:00AM should convert to 10:00:00
  ✓ 11:00:00AM should convert to 11:00:00
  ✓ 12:00:00PM should convert to 12:00:00
  ✓ 01:00:00PM should convert to 13:00:00
  ✓ 02:00:00PM should convert to 14:00:00
  ✓ 03:00:00PM should convert to 15:00:00
  ✓ 04:00:00PM should convert to 16:00:00
  ✓ 05:00:00PM should convert to 17:00:00
  ✓ 06:00:00PM should convert to 18:00:00
  ✓ 07:00:00PM should convert to 19:00:00
  ✓ 08:00:00PM should convert to 20:00:00
  ✓ 09:00:00PM should convert to 21:00:00
  ✓ 10:00:00PM should convert to 22:00:00
  23 passing (14ms)

However when I test the last test case by itself, it passes.
✓ 11:00:00PMshould convert to 23:00:00

So, I'm confused as to why all the tests don't work if the for loop iterates through the whole array, but works if I iterate up until the last index.  Can someone clear this up for me?

A: Your code may be sync, but mocha calls it it async. Means: your it descriptions are parsed sync, mocha stores this information and runs every test in it's own context. This is async. To make this work, you have to create a closure with a function:
var converter = require('../modules/time.js');
// outside the loop:
function itShouldTestArray(i) {
   // i is now within the function scope and won't change anymore
   it(test_array[i]  + ' should convert to ' + against[i], function() {
   var test = converter.main(test_array[i]);
   assert.equal(test, against[i]);
}
describe('Time Converter', function() {
 describe('main()', function() {
  for(i = 0; i < 24; i++) {
   itShouldTestArray(i);
   });
  }
 });
});

A:
So, I'm confused as to why all the tests don't work if the for loop
  iterates through the whole array, but works if I iterate up until the
  last index. Can someone clear this up for me?

This is probably a very-hard-to-debug-problem caused by the asynchronous testing conducted by Mocha. It seems like that changing i from 23 to 24 somehow results in your arrays being deleted before the tests are conducted, confer the error message:
 TypeError: Cannot read property 'substr' of undefined

You can avoid this deletion of the arrays before testing time by assigning their values inside a closure:
var converter = require('../modules/time.js');

describe('Time Converter', function() {
  describe('main()', function() {

       test_array = // insert array inside closure;
       against = //insert array inside closure;

       callback = function () {

        var test = converter.main (test_array[i]);
        assert.equal(test, against[i]);
       }

       for(i = 0; i < 24; i++) {

          it(test_array[i]  + ' should convert to ' + against[i], callback);
        }
      })
    })

This way each callback passed to it() will have access to the arrays without any possibility of them being deleted or altered before testing time.

A: I don't know mocha at all, so I will defer to Johannes' expert advice on that.
I do have some other suggestions for you though.
First, it will be a real maintenance headache having two arrays running in parallel like test_array and against. It's hard to look at those and be sure the right values are matched up.
Instead, put everything into a single array, where each array element contains both test values:
var tests = [
    '12:00:00AM = 00:00:00',
    '01:00:00AM = 01:00:00',
    '02:00:00AM = 02:00:00',
    '03:00:00AM = 03:00:00',
    '04:00:00AM = 04:00:00',
    '05:00:00AM = 05:00:00',
    '06:00:00AM = 06:00:00',
    '07:00:00AM = 07:00:00',
    '08:00:00AM = 08:00:00',
    '09:00:00AM = 09:00:00',
    '10:00:00AM = 10:00:00',
    '11:00:00AM = 11:00:00',
    '12:00:00PM = 12:00:00',
    '01:00:00PM = 13:00:00',
    '02:00:00PM = 14:00:00',
    '03:00:00PM = 15:00:00',
    '04:00:00PM = 16:00:00',
    '05:00:00PM = 17:00:00',
    '06:00:00PM = 18:00:00',
    '07:00:00PM = 19:00:00',
    '08:00:00PM = 20:00:00',
    '09:00:00PM = 21:00:00',
    '10:00:00PM = 22:00:00',
    '11:00:00PM = 23:00:00',
];

You can use split() in your code to separate the two values in each array element.
Next, never hard code an array length in a for loop. Instead, if the array is named test as in my example above, use i < test.length in the loop. Now if you add or remove entries, the loop will still have the correct length.
However, I wouldn't use a for loop here at all. You can get cleaner code by using the forEach array method.
Taking Johannes' code as a starting point, I would change it to:
function itShouldTestTimes( test ) {
    var times = test.split( ' = ' );
    var time12 = times[0], time24 = times[1];
    it( time12 + ' should convert to ' + time24, function() {
        var result = converter.main( time12 );
        assert.equal( result, time24 );
    });
}

describe( 'Time Converter', function() {
    describe( 'main()', function() {
        tests.forEach( itShouldTestTimes );
    });
});

A: 1) BatchTest.js
const assert = require('chai').assert;
const fileOperations = require('../UDRServer/Utility/FileOperations');
var testResultFileName = "TestResult.json";

var data = fileOperations.readFile(testResultFileName);
//console.log(data);

var jsons = data.split('\n');

function runTest(obj) {
    describe(obj.name + " Test", function () {
        it("Expexted Value " + obj.expectedStatus, function (done) {

            assert.equal(obj.expectedStatus, obj.actualStatus);
            if (obj.expectedCause != 'null') {
                assert.equal(obj.expectedCause, obj.actualCause);
            }
            done();
        })

    })
}

describe("Main", function () {
    for (let i = 0; i < jsons.length - 1; i++) {
        var obj = JSON.parse(jsons[i]);
        runTest(obj);
    }
});

2 ) FileOperations.js
var readFile = function(filename){
    return fs.readFileSync(filename).toString();
}

3) TestResult.json file
{"actualStatus":403,"actualCause":"false","name":"test1","expectedCause":"false","expectedStatus":400}
{"actualStatus":0,"actualCause":"true","name":"test2","expectedCause":"false","expectedStatus":400}
{"actualStatus":400,"actualCause":"false","name":"test3","expectedCause":"false","expectedStatus":400}
{"actualStatus":200,"actualCause":"true","name":"test4","expectedCause":"false","expectedStatus":200}


text:
Q: A way to sort WordPress themes? I want to write a plugin which can sort themes into categories.
For example
I have Categories
3 themes in Business as subfolder from /themes/business
7 themes in Nature /themes/nature
2 themein in private /themes/private
by default WordPress shows me all 12 themes in the backend.
I tried to change the theme root
add_filter("theme_root","tr");
function tr($J){
print_r($J);//if yo udo this you see the main theme folder
$J="/www/wp-content/new-themes"; //folder new-themes exists
return $J;
}

but in general this does not work.
Any ideas are highly appreciated.


text:
Q: Infinitesimal Generator of semigroup for markov chain In Wikipedia the definition of generator of a semigroup is given as follows

For a Feller process $(X_t)_{t\ge0}$ with Feller Semigroup $T=(T_t)_{t\ge0}$ and state space $E$ we define the generator $(A,D(A))$ by:
$$D(A)=\left\{f\in C_\infty :\lim_{t↓0}\frac{T_tf-f}{t}\text{exists as a uniform limit}\right\},$$

I saw another definition of infinitsimal generator in context of markov chains which says that if
$$d\phi(X_t)=A \phi(X_t)dt+dM_t$$
where $M_t$ is a martingale and $\phi \in C_c^{\infty}(\mathcal{X})$ and {$X_t$} is a markov chain on $\mathcal{X}$ then A is the infinitesimal generator.
Are these two definitions equivalent?

A: I think this theorem is useful, it is from Continuous Time Markov
Processes by Liggett:

Theorem: Let $X(t)$ be a Feller process on a state space $S$ and let $A$ be its generator with domain $D(A)$. Let $(P_x)_{x \in S}$ be the collection of path distributions - in case you are not familiar with this general definition, $P_x$ is the measure under which $X$ starts at $x$ almost surely. Then for every $x \in S$ and $f \in D(A)$:
$$M(t) := f(X(t)) - \int_{0}^{t} (Af)(X(s)) ds$$
is a martingale under the measure $P_x$.

Note that the Hille-Yosida-theorem states that every Feller process corresponds to a generator and vice versa. However, not every Markov process is a Feller process - which in addition to the Markov property satisfies the following condition:

Feller Property: $\forall f \in \mathcal{C}(S)$ and $t\ge 0$ the function $\phi: S \rightarrow \mathbb{R}$ given by $$\phi(x) = \mathbb{E}_{P^{x}}[f(X(t))]$$ is also in $\mathcal{C}(S)$, i.e. continuous and vanishing at infinity.


text:
Q: Can't find struct's some field with pragma pack, 64 bits integer package main

/*
#include <inttypes.h>
#pragma pack(1)
typedef struct _sss {
uint64_t some; // ok
uint32_t wow; // ok
uint64_t some2; // not found
uint64_t some3; // not found
uint64_t some4; // not found
uint32_t some5; // ok
} Type;
#pragma pack()
*/
import "C"
import (
    "fmt"
)

func main() {
    s := C.Type{}
    s.some = 10;
    s.wow = 10;
    s.some2 = 10;
    s.some5 = 10;
    fmt.Println("Hello, playground")
}

I declared struct named C.Type.
If pragma pack(1) and 64 bits members are used together.
╭─dire@dire-81w4 ~/workspace
╰─go run test.go                                                                                2 ↵
# command-line-arguments
./test.go:25:6: s.some2 undefined (type _Ctype_struct__sss has no field or method some2)

Compilation is possible by removing pragma pack(1).
Go 1.15 version is being used. Do you know why?

A: I found answer about my question.
If the fields of a C struct are aligned such that they can't be represented by a Go struct, then they cannot be accessed directly from cgo. You will have to write functions in C to read and write those fields.
I nowdays am too busy to comment. It's late, but it's answered.


text:
Q: How can I make a phantom power mic popless mute switch? I want to make a phantom power (PP) mic mute switch with an indicator led powered by PP. I already did it based on the following circuit. It works but, with the led included in the circuit, I get a pop when turn On-Off the switch. Without the led it work fine and silent.

simulate this circuit – Schematic created using CircuitLab
Is it possible to prevent this pop keeping the led being powered by the PP? Or there any contraindications of powering the led with PP?
Please, help me. I'm not electronic engineer.

A: I'm assuming balanced lines with 48V phantom power like is used with Cannon XLR connectors
you need to ensure that the draw for the LED is balanced across the signal lines, you can either do this with a transformer with a centre tap.

Or by making the circuit symmetrical.


text:
Q: Exclude certain columns form range Having trouble coding a macro in vba to exclude certain columns from being included in a chart. I want to exclude Column F from being included. Here is my code from a recoreded macro that I tweaked a bit:
Sub Macro4()

Dim ws As Worksheet
Dim wb As Workbook
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")

    ActiveSheet.Shapes.AddChart2(251, xlBarClustered).Select
    ActiveChart.SetSourceData Source:=ws.Range("E" & ActiveCell.Row & ":F" & ActiveCell.Row & ":G" & ActiveCell.Row & ":H" & ActiveCell.Row)
    ActiveChart.FullSeriesCollection(1).XValues = "=Sheet1!$E$9:$H$9"
    ActiveChart.SetElement (msoElementDataLabelOutSideEnd)
    ActiveChart.SetElement (msoElementPrimaryCategoryGridLinesNone)
    ActiveChart.Axes(xlValue).MajorGridlines.Format.Line.Visible = msoFalse
    ActiveChart.FullSeriesCollection(1).DataLabels.ShowCategoryName = False
    With ActiveChart
    .HasTitle = True
    .ChartTitle.Characters.Text = "Analysis for " & ws.Range("C" & ActiveCell.Row)
    ActiveChart.HasAxis(xlValue) = False
    ActiveChart.HasLegend = False
    End With

End Sub

A: This should exclude F from your chart.
Edit:
To create your chart only using data from the active row, you can try:
Sub Macro4()

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("Sheet1")
ws.Activate

    Dim MyRange1 As Range: Set MyRange1 = Range("E" & ActiveCell.Row)
    Dim MyRange2 As Range: Set MyRange2 = Range(Cells(ActiveCell.Row, "G"), Cells(ActiveCell.Row, "H"))
    Dim MyChartRange As Range: Set MyChartRange = Union(MyRange1, MyRange2)

    ActiveSheet.Shapes.AddChart2(251, xlBarClustered).Select
    ActiveChart.SetSourceData Source:=MyChartRange
    ActiveChart.FullSeriesCollection(1).XValues = "=Sheet1!$E$9:$H$9"
    ActiveChart.SetElement (msoElementDataLabelOutSideEnd)
    ActiveChart.SetElement (msoElementPrimaryCategoryGridLinesNone)
    ActiveChart.Axes(xlValue).MajorGridlines.Format.Line.Visible = msoFalse
    ActiveChart.FullSeriesCollection(1).DataLabels.ShowCategoryName = False

With ActiveChart
    .HasTitle = True
    .ChartTitle.Characters.Text = "Analysis for " & ws.Range("C" & ActiveCell.Row)
    ActiveChart.HasAxis(xlValue) = False
    ActiveChart.HasLegend = False
End With

End Sub

A: Try the following, you use "," to delimit non-consecutive ranges:
ActiveChart.SetSourceData Source:=ws.Range("Sheet1!$E$" & ActiveCell.Row & ",Sheet1!$G$" & ActiveCell.Row & ",Sheet1!$H$" & ActiveCell.Row)
ActiveChart.FullSeriesCollection(1).XValues = "=Sheet1!$E$9,Sheet1!$G$9,Sheet1!$H$9"


text:
Q: Is it possible to detect if you are on the synchronous side of an async method? I am trying to develop a context system for a web application which will propagate data along the logical flow of control. This is similar to AsyncLocal stack described enter link description here.
Originally, I was simply using the LogicalCallContext to do this, but this runs into issues with ASP.NET thread agility. To counter this, I have implemented a hybrid system that uses both the logical call context and HttpContext.Items. With this system, we keep the two contexts in sync (assuming both are available), and trust the logical call context unless it is missing and there is something in HttpContext.Items.
This works in almost all cases, but can run into trouble in the first half of an async method that is called from a synchronous method where we are on the request thread but in a different logical call context. Here's an example:
// in BeginRequest
MyContext.Push("BeginRequest");

public ActionResult SomeAction()
{
    // sometimes Asp.NET does a thread switch between begin request and the action
    // in that case, we have:
    // Logical: null
    // HttpContext:  "BeginRequest"

    var result = this.DoSomethingAsync().Result;

    // Here we have
    // Logical: null
    // THIS IS WRONG: the logical context was correctly restored by async magic, but we
    // corrupted the HttpContext. Since we lost the logical call context, we can't use that
    // HttpContext: "DoSomethingAsync" -> "BeginRequest"
}

private async Task DoSomethingAsync()
{
    // right now we're on the request thread, so we still have HttpContext but
    // because we have a logical call context
    // I would like to detect when the code is in THIS STATE
    MyContext.Push("DoSomethingAsync");

    // Here we have
    // Logical: "DoSomethingAsync" -> "BeginRequest"
    // HttpContext: "DoSomethingAsync" -> "BeginRequest"

    // because this method does ConfigureAwait(false), on the other side of await
    // you won't have the context
    await ComputeSomethingAsync().ConfigureAwait(false);

    // Here we have
    // Logical: "DoSomethingAsync" -> "BeginRequest"
    // HttpContext: null

    MyContext.Pop();

    // Here we have
    // Logical: "BeginRequest"
    // HttpContext: null
}

Is there any way to detect this state? Is there another way to get a consistent logical context flow in ASP.NET/.NET 4.5?


text:
Q: How to use python "include" and "libs" path in a windows makefile to compile all python embedded C++ program in a folder? Makefile specified in this question, compiling all the cpp programs in a folder but not with python embedded cpp programs.
all: myUB

sourcesC := $(wildcard ../src/*.cpp)

objectsC := $(patsubst %.cpp,%.o,$(sourcesC))

INPATH=-I"C:/Python27/include"

LIBPATH=-L"C:/Python27/libs"-lpython27

myUB:

    @echo 'Building target $@'

    g++ -O0 -Wall -c -g3 -fmessage-length=0 \
        $(sourcesC)

    del *.o

clean:

A: Your final makefile could look somthing like:
all: myUB

sourcesC := $(wildcard ../src/*.cpp)

# Not used
#objectsC := $(patsubst %.cpp,%.o,$(sourcesC))

INC = -IC:\Python27\include

LIBS = -LC:\Python27\libs -lpython27

myUB:
    @echo 'Building target $@'
    g++ -O0 -Wall -g3 -fmessage-length=0 -o myprog.out $(sourcesC) $(INC) $(LIBS)

clean:
    rm myprog.out

update
For the undefined ref to WinMain(), it means the linker can't find this function in your code. Either you need to include a library/object that contains it or you can define it yourself in a cpp file like:
#include <windows.h>

int WINAPI (*MyDummyReferenceToWinMain)(HINSTANCE hInstance, ..., int
nShowCmd ) = &WinMain;

I got the function template from here.
But this seems to mean that you are creating a windows application instead of a console app which uses int main(...) entry point.
Update2
I have made a new makefile to do what you have asked for in your latest comment which seems to be to create one executable per source file - I am assuming each source file has its own main.
# Build vars
CXX = g++
CXX_FLAGS = -O0 -Wall -g3
INC = -IC:\Python27\includ
LIBS = -LC:\Python27\libs -lpython27

# Sources
SRC_DIR=src
SOURCES = $(wildcard $(SRC_DIR)/*.cpp)
$(info SOURCES: $(SOURCES))

# Executables
EXE_DIR=bin
EXECUTABLES = $(subst $(SRC_DIR)/,$(EXE_DIR)/,$(subst cpp,out,$(SOURCES)))
$(info EXECUTABLES: $(EXECUTABLES))

$(info ----)

# Directories
DIRS = $(EXE_DIR)

# Rule to create folders and compile executables
all: $(DIRS) $(EXECUTABLES)

# Pattern rule to build each executable
$(EXE_DIR)/%.out : $(SRC_DIR)/%.cpp
    @echo "compiling $< --> $@"
    @$(CXX) $(CXX_FLAGS) -o $@ $< $(INC) $(LIBS)

# Rule to create output dirs
$(DIRS):
    @echo "Creating output folders"
    @mkdir -p $(EXE_DIR)

# Rule to clean up
clean:
    @echo "Cleaning"
    @rm -rf $(EXE_DIR)

This should create one executable in the folder bin/ for each source file (.cpp) in folder src/.


text:
Q: PhpStorm: Missing code completion on custom Vue 3 component library I have built a Vue Component Library for my projects.
After I have integrated the library in my main.js with app.use(ComponentLibrary), and use the individual components in my views, they do not have code-completion or tag & attribute suggestions in my IDE (PhpStorm), so they are not recognised.
They still work, but it would be very helpful if the IDE also recognised them.
Does anyone have an idea how I can solve this?

A: The IDE doesn't understand the way components are exposed in library files, thus the issue.
To improve code completion for different Vue.js component libraries, the IDE is using a special format of metadata, called web-types. web-types describe the library's components and their directives. The library developers have to provide descriptions of library components in the web-types format and include it in package distribution to get all props correctly completed and resolved.


text:
Q: How can I redraw zoomed text on a transformed UIView? I'm currently implementing an expanding timeline.  When I pinch zoom into the timeline, I need my drawn text to stay at the same relative locations on the UIView they're drawn on inside the UIScrollView that handles the zooming. (Essentially like pins on GoogleMaps)  However, I don't want to zoom vertically, so I apply a transform by overriding:
- (void)setTransform:(CGAffineTransform)newValue;
{
    newValue.d = 1.0;
    [super setTransform:newValue];
}

This works great in keeping the timeline fixed vertically and allowing it to expand horizontally.  However, I am drawing my text labels as such in a method called during setNeedsDisplay:
for (int i = 1; i < 11; i++)
{
    CGRect newFrame = CGRectMake(i * (512.0/11.0) - (512.0/11.0/2.0), self.frame.size.height - 16.0, 512.0/11.0, 32.0);
    NSString *label = [NSString stringWithFormat:@"%d", i+1];
    [label drawInRect:newFrame withFont:[UIFont systemFontOfSize:14.0]];
}

This draws my text at the correct position in the scrollview, and nearly works perfectly.  However, because of my transform to keep the zooming view static vertically, the text expands horizontally and not vertically, and so stretches out horribly.  I can't seem to get the text to redraw at the correct aspect ratio.  Using UILabels works, however I am going to be rendering and manipulating upwards of 1,000 such labels, so I'd preferably like to draw static images in drawRect or something similar.
I've tried changing the CGRect I'm drawing the text in (was worth a shot), and applying CGAffineTransformIdentity isn't possible because I'm already transforming the view to keep it from zooming vertically.  I've also tried drawing the text in various Views to no avail, and again, I'd rather not populate an obscene amount of objects if I can avoid it.
Thanks for any help!

A: Instead of applying a transform inside the 'setTransform:' method, I intercepts the scale at which it is being transformed, and resize the frame of the view being transformed. The code (roughly) follows:
- (void)setTransform:(CGAffineTransform)newValue;
{
    // The 'a' value of the transform is the transform's new scale of the view, which is reset after the zooming action completes
    //  newZoomScale should therefore be kept while zooming, and then zoomScale should be updated upon completion
    _newZoomScale = _zoomScale * newValue.a;

    if (_newZoomScale < 1.0)
        _newZoomScale = 1.0;

    // Resize self
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, _originalFrame.size.width * _newZoomScale, self.frame.size.height);
}

As mentioned in the comments, the transform value of the CGAffineTransform is reset each time a new zooming action occurs (however, it is kept for the duration of the zooming action). So, I keep two instance variables in my UIView subclass (not sure if it's incredibly elegant, but it's not insanely terrible): the original frame the the view was instantiated with, and the "current" zoom scale of the view (prior to the current zooming action).
The _originalFrame is what is referenced in order to determine the proper sizing of the now zoomed frame, and the _zoomScale(the scale of the view prior to the current zooming action) is set to the value of _newZoomScale when the didFinishZooming callback is called in the UIScrollView containing this UIView.
All of this allows for the coordinate system of the UIView to not be transformed during zooming, so text, etc. may be drawn on the view without any distortion. Looking back at this solution, I'd wager a guess that you could also account for the transform and draw based on a stretched coordinate system. Not sure which is more effective. I had a slight concern by not calling super in setTransform:, but I haven't noticed any ill effects after about 6 months of use and development.


text:
Q: How do I integrate $\int \frac{x^2}{(x^2+9)^2}\, dx$? How do I integrate $\displaystyle \int \frac{x^2}{(x^2+9)^2}\, dx$
?
I tried doing using algebra and solving the question a bit. But it didn't become something that looks solvable.
How should I do this?

A: Hint:
Integrate by parts
$$\int uv\ dx=u\int v\ dx-\int\left(\dfrac{du}{dx}\int v\ dx\right)dx$$
Here $u=x,v=\dfrac x{(9+x^2)^2} $

A: Hint:
Use $x=3\tan t,\implies dx=?$ and $x^2+9=9\sec^2t$
finally use $\cos2y=1-2\sin^2y$

A: I think the best thing to do in such a question, should be suitable substitution.
So let
$x=3\tan{\theta}$
$dx=3\sec^2(\theta) d\theta$
$\begin{align} \displaystyle \int \frac{x^2}{(x^2+9)^2}\, dx & = \int \frac{9 \tan^2(\theta) }{(9 \tan^2(\theta) + 9)^2} 3\sec^2(\theta)\, d\theta  = \int \frac{27 \tan^2(\theta)\sec^2(\theta)}{81 \sec^4(\theta)} \, d\theta \\ & = \int \frac{1}{3} \frac{ \tan^2(\theta)}{ \sec^2(\theta)}\, d\theta = \frac{1}{3} \int \sin^2(\theta) \, d\theta \\ & = \frac{1}{3} \int \frac{1}{2} - \frac{\cos(2\theta)}{2} \, d\theta = \frac{1}{3} (\frac{1}{2}\theta - \frac{\sin(2\theta)}{4}) + C\\ & = \frac{1}{6} \theta - \frac{2\sin\theta\cos\theta}{12} + C = \frac{1}{6} \theta - \frac{1}{6} \sin{\theta}\cos{\theta} + C \end{align}$
And since $x=3\tan \theta$, we get that:

*

*$\displaystyle \theta = \arctan(\frac{x}{3})$

*$\displaystyle \cos \theta = \frac{3}{\sqrt{x^2+9}}$

*$\displaystyle \sin \theta = \frac{x}{\sqrt{x^2+9}}$
Therefore, turning $\theta$ back into $x$, we get that:
$\displaystyle \begin{align}\int \frac{x^2}{(x^2+9)^2} \, dx & = \frac{1}{6} \theta - \frac{1}{6} \sin{\theta}\cos{\theta} + C \\ & = \frac{1}{6} \arctan(\frac{x}{3}) - \frac{1}{6} \frac{x}{\sqrt{x^2+9}}\frac{3}{\sqrt{x^2+9}} + C \\ & = \frac{1}{6} \arctan(\frac{x}{3}) - \frac{1}{2} \left(\frac{x}{x^2+9}\right)+C\end{align}$
And that should be your final answer.


text:
Q: How to create multiple variables from function output in one line in js? I need to create 4 variables which will all carry a random composite number. The composite numbers are created by a function. Is there an easier way to create 4 variables using the same function instead of the below script?
var a = create_composite();
var b = create_composite();
var c = create_composite();
var d = create_composite();

A: This is a bit shorter, not sure if it's what you are going for though...

// stub function
const create_composite = () => Math.floor(Math.random() * 10)

const [a, b, c, d] = (new Array(4)).fill(0).map(create_composite)

console.log(a, b, c, d);

Another option would be to modify create_composite to accept the quantity of composite numbers you wish to generate:
const create_composites = (qty=1) => {
   return (new Array(qty)).fill(0).map(() => {
      // original composite number function code
   });
}

Then you could use this in a similar manner as I did above:
const [a, b, c, d] = create_composites(4);

While we are on suggestions for altering your create_composite function, the best option I can think of is to turn that function into a generator:

function* create_composite() {
   while(true)
     // yield your return value here
     yield Math.floor(Math.random() * 10);
}

const [a, b, c, d, e, f, g] = create_composite();
console.log(a, b, c, d, e, f, g);

This will allow you to take as many variables as you need

A: I think this is the easies way. You can also do it that way:
var a = create_composite(),
b = create_composite(),
c = create_composite(),
d = create_composite();

This is depend on preferences but in JavaScript there is not easier way :)

A: If you're in a browser that supports ES6, or are using babel or similar, you can do this:
var { a, b, c, d } = create_composite();

If create_composite returns an object with the keys a, b,c, d, then you'll have access to those individual variables.
Otherwise, in older browsers, you can still have the function return an object, you'll just have to call the properties individually as such:
var compositeNumber = create_composite();
console.log(compositeNumber.a);


text:
Q: How to set background image for the frame? I know in this article they set the background color using the steps followed. I was wondering if there was a way of using an image instead of a Color. I tried the following but it didn't work:
ImageBrush brush = new ImageBrush();
brush.ImageSource =
new BitmapImage(new Uri("/MyApp;component/Images/Backgrounds/myimage.jpg"));
Rootframe.Background = brush;

Has anyone seen if this is possible? Or is it restricted to Colors?

A: I decided to have a go and got it working. The only catch is, it's a bit of a workaround since there seems to be some strange behaviour with the ImageOpened event. Basically, the ImageOpened event of the Brush doesn't get called when you assign the background to the frame. Strangely, it does get called when you assign it to an element. So I just created a hidden button and assigned the brush to that (to force the ImageOpened event to fire). I then assigned it to the frame and it works for me. Seems like a bug, but the workaround below works for me.
ImageBrush brush = new ImageBrush();

brush.ImageSource = new BitmapImage(new Uri("/myImage.jpg", UriKind.Relative));
//hide the fake button and set the brush to be its background
button1.Visibility = System.Windows.Visibility.Collapsed;
button1.Background = brush;

//assign it to the frame (or using RootFrame in your case)
var frame = App.Current.RootVisual as PhoneApplicationFrame;
frame.Background = brush;

A: Using
RootFrame.Background = App.Current.Resources["MainBackground"] as ImageBrush;

works for me. You'll need the following in your resources dictionary in App.xaml
<ImageBrush x:Key="MainBackground" ImageSource="/resources/MainBackground.jpg" />

A: Set CreateOption to None or BackgroundCreation and wait while image is loaded:
 BitmapImage image = new BitmapImage(new Uri("/MyApp;component/Images/Backgrounds/myimage.jpg"))
 {
      CreateOptions = System.Windows.Media.Imaging.BitmapCreateOptions.None
 };
 image.ImageOpened += (s, e) =>
 {
      brush.ImageSource = image;
      App.RootFrame.Background = brush;
 };


text: Q: Setting opcache per site Is it possible to set opcache options per site in Apache? I'm trying to disable it via local php.ini in site directory or site config file but it is always enabled. After every config change I restarted Apache and PHP fpm service to apply new config.


text:
Q: Database Schema Normalization Violation To my knowledge the following doesn't violate 1NF or 2NF. Is 3NF violated because LocationID and LocationName isn't separated into a different table?
Department (DNum PK, DName, LocationID, LocationName)

A: You can't be sure whether a relation is normalized or not based only on a list of attribute names. What really matter are the dependencies that apply to those attributes. For example, given the following set of dependencies
F: {DNum}->{LocationID}->{DNum,DName,LocationName}

we can say that Department satisfies 3NF (and therefore 2NF) with respect to F because both DNum and LocationID should be keys for Department and there are no functional dependencies other than the ones implied by those keys. The choice of primary key is irrelevant as far as normalization is concerned because a relation may have more than one key and all the keys are equally significant.
Alternatively, given the following set of dependencies
G: {DNum}->{DName,LocationID,LocationName}, {LocationID}->{LocationName}

the Department relation violates 3NF with respect to G because LocationID is a non-key determinant.

A: Yes, 3NF is violated.
3NF requires 2NF and that no non-key field should depend on another non-key field.
LocationName is dependent on LocationID as (I'm assuming that) LocationID is a PK and that's the violation.

I earlier explained 1NF, 2NF and 3NF in this another answer.


text:
Q: How to have urls with a '$' in a SASS file? I've inherited legacy code, and theres this portion of a class in css:
background: url(//site.com/path/path/$?wid=3&fmt=png/myimg.jpg)

SASS throws an error because it things the '$' is a variable. How can I get around this if I cannot modify the image path on the server?

A: Surround the URL in quotes.  Sass does not look for variables within quoted strings, instead you would have to use the interpolation syntax #{}
background: url('//site.com/path/path/$?wid=3&fmt=png/myimg.jpg')


text:
Q: Python Pandas Dataframe - Groupby and Average based on Condition I have a dataframe that looks like this:
id  start       end         diff mindiff
1   2015-01-02  2015-07-01  180 57
2   2015-02-03  2015-05-12  98  56
3   2015-01-15  2015-01-20  5   5
4   2015-02-04  2015-04-15  70  55
5   2015-03-15  2015-05-01  47  46
6   2015-02-22  2015-03-01  7   7
7   2015-03-21  2015-04-12  22  22
8   2015-04-11  2015-06-15  65  50
9   2015-04-11  2015-05-01  20  20
10  2015-03-30  2015-04-01  2   2
11  2015-04-28  2015-06-15  48  33
12  2015-05-01  2015-06-01  31  31
13  2015-05-10  2015-06-09  30  30
14  2015-05-19  2015-07-01  43  42
15  2015-06-01  2015-06-06  5   5
16  2015-06-02  2015-06-29  27  27
17  2015-04-29  2015-05-21  22  22
18  2015-05-25  2015-07-01  37  36
19  2015-06-04  2015-06-26  22  22
20  2015-06-21  2015-07-01  10  10
21  2015-05-30  2015-06-06  7   7
22  2015-06-30  2015-07-01  1   1

The fields are id, start (date), end (date), diff(the number of days between start and end), mindiff(the min(diff and the last day x months from start).
x in this case is 1 (so one month "later than" the start date)
What I am trying to accomplish is to find the Average(mean) of mindiff, grouped by the year/month of 'end', but ONLY averaging for each group the records which have a 'start' year/month x (defined above) months back through the groupedby month.  Example from the data set above, id 1 would only be averaged in year/month 2015/1 and 2015/1+x (2015/2).
Here is a table flagging each record and which month I would like to average in:
    Months
id  1   2   3   4   5   6   7
1   1   1
2       1   1
3   1
4       1   1
5           1   1
6       1   1
7           1   1
8               1   1
9               1   1
10          1   1
11              1   1
12                  1   1
13                  1   1
14                  1   1
15                      1
16                      1
17              1   1
18                  1   1
19                      1
20                      1   1
21                  1   1
22                      1   1

Here are the mindiffs and resulting AVG/month I am looking for:
    Months
id  1   2   3   4   5   6   7
1   57  57
2       56  56
3   5
4       55  55
5           46  46
6       7   7
7           22  22
8               50  50
9               20  20
10          2   2
11              33  33
12                  31  31
13                  30  30
14                  42  42
15                      5
16                      27
17              22  22
18                  36  36
19                      22
20                      10  10
21                  7   7
22                      1   1
AVG 31  43.8    31.3    27.9    30.1    21.1    5.5

Finally, here is the dataframe I am looking for as a result:
Month   Avg Diff Trailing x months
2015-01 31
2015-02 43.75
2015-03 31.33333333
2015-05 27.85714286
2015-05 30.11111111
2015-06 21.1
2015-07 5.5

I know this is possible with a loop, but my gut says that a GROUPBY is more pythonic and likely more efficient.  But how do I get only the specific rolling mindiff values for months of 'start' to be averaged within the groupby of the 'end' year/month.  Thanks for the help.

A: First I created testing data with different years and start in last row is set to December. Then I convert start and end columns to periods - periodS and periodE cols.
I use function groupby by column month and count mean from column Avg:
g = df1.groupby('months')['Avg'].mean().reset_index()

import pandas as pd
import numpy as np
import io

temp=u"""id;start;end
1;2014-01-02;2014-07-01
2;2014-02-03;2014-05-12
3;2014-01-15;2014-01-20
4;2014-02-04;2014-04-15
5;2014-03-15;2014-05-01
6;2014-02-22;2014-03-01
7;2015-03-21;2015-04-12
8;2015-04-11;2015-06-15
9;2015-04-11;2015-05-01
10;2015-03-30;2015-04-01
11;2015-04-28;2015-06-15
12;2015-05-01;2015-06-01
13;2015-05-10;2015-06-09
14;2016-05-19;2016-07-01
15;2016-06-01;2016-06-06
16;2016-06-02;2016-06-29
17;2016-04-29;2016-05-21
18;2016-05-25;2016-07-01
19;2017-06-04;2017-06-26
20;2017-06-21;2017-07-01
21;2017-05-30;2017-06-06
22;2017-12-30;2018-02-01"""

df = pd.read_csv(io.StringIO(temp), sep=";", index_col=[0])
print df
def last_day_of_next_month(any_day):
    next_month = any_day.replace(day=28) + pd.Timedelta(days=36)  # this will never fail
    return next_month - pd.Timedelta(days=next_month.day)

df['mindiff'] = (pd.to_datetime(df['start']).apply(last_day_of_next_month) - pd.to_datetime(df['start'])).astype('timedelta64[D]')
df['diff'] = (pd.to_datetime(df['end']) - pd.to_datetime(df['start'])).astype('timedelta64[D]')
df['mindiff'] = df[['mindiff', 'diff']].apply(lambda x: min(x), axis=1)
#print df

#set day of start and end to periodindex
df['periodS'] =  pd.to_datetime(df['start']).dt.to_period('M')
df['periodE'] =  pd.to_datetime(df['end']).dt.to_period('M')

#if period end is higher as period start, add one month else NaN
df['period'] = np.where(df['periodE'] > df['periodS'],df['periodS'] + 1, np.nan)
#print df
#df from subset
df1 = df[['mindiff', 'periodS', 'period']]
#pivot data (from rows to columns)
df1 = df1.set_index('mindiff').stack().reset_index()
#rename columns names
df1.columns = ['Avg', 'tmp', 'months']
#groupby by column month and count mean from column Avg
g = df1.groupby('months')['Avg'].mean().reset_index()
print g
#     months        Avg
#0   2014-01  31.000000
#1   2014-02  43.750000
#2   2014-03  41.000000
#3   2014-04  46.000000
#4   2015-03  12.000000
#5   2015-04  25.400000
#6   2015-05  32.800000
#7   2015-06  30.500000
#8   2016-04  22.000000
#9   2016-05  33.333333
#10  2016-06  27.500000
#11  2017-05   7.000000
#12  2017-06  13.000000
#13  2017-07  10.000000
#14  2017-12  32.000000
#15  2018-01  32.000000


text:
Q: Rich Snippets Review Aggregate displaying images in search results I'm trying to get an image to be included within google search results for a review aggregate, and have not had any success.
Based on this page from Google, it should be possible:
https://support.google.com/webmasters/answer/146645?hl=en&ref_topic=1088474
However, I have been unable to get the Google Structured Data tool to display the image i've specified:
http://www.google.com/webmasters/tools/richsnippets?q=http%3A%2F%2Fwww.kidspot.com.au%2Fparenting-directory%2FSkincare%2B247%2FCleanskin-Candle-Company%2B38267%2FNational.htm
There is an image specified for the page, the localbusiness and the review aggregate, but none of these get used.
i'm not sure if the structure of the microdata on the page is wrong, or if it's an issue with using localbusiness object or if google just doesn't want to display images.
Any help would be appreciated
Cheers
Chris

A: The max image dimensions must be: height 120px and width 100px with max aspect-ratio 3.
Specify thumbnails


text:
Q: How can I get the facebook friends_count of a user profile via graph API 2.2? In most of the profiles the count of the actual friends is public, but there seems to be no obvious way to get this figure via graph api.
If you access via /user.id/friends?access_token= will get the whole friends list but only if the friends are using your facebook app too. (see Get facebook friends with Graph API v.2.0 ). But I will not need the friends, I just need the count.
There is a possibilty via FQL:
facebook.com/fql?q=SELECT friend_count FROM user WHERE username="<username>"

but this leads to nowhere because in the future FQL is not supported anymore.
The 3rd possibilty would be to scrape the whole page. But this will make facebook mad and is not very efficient (a fb site has ~400kb).
Does anyone know another possiblity/trick to get the friends_count of any user on facebook  with this attribute public ?
Thanks for any suggestions.

A: You cannot get the friend count of any user, you can only get that value from the user who is authorized right now:
/me/friends

There will be a summary.total_count field in the result.
You need the user_friends permission with the access token as well.
Btw, scraping is not allowed: https://www.facebook.com/apps/site_scraping_tos_terms.php


text:
Q: Create a g-torus I'm looking for an easy, elegant way to create a triangle mesh of a torus with an arbitrary number of holes. Here are some examples.

First, the AI had a problem with the question title, then a human decided "Closed. This question needs to be more focused."
Anyway, here is one direction:
% sphere
%fun = @(x, y, z) x.^2 + y.^2 + z.^2 - 1;

% 3-torus
% http://metamathological.blogspot.com/2013/01/today-i-learned-how-to-plot-doughnut.html
fun = @(x, y, z) (x.^2 + (y - 2).^2 - 1) .* ((x - sqrt(3)).^2 + (y + 1).^2 - 1) .* ((x + sqrt(3)).^2 + (y + 1).^2 - 1) - 0.0015*(x.^2 + y.^2 + 7*z.^2).^5;

% 4-torus
%fun = @(x, y, z) ((x - 2).^2 + (y - 2).^2 - 1) .* ((x - 2).^2 + (y + 2).^2 - 1) .* ((x + 2).^2 + (y - 2).^2 - 1) .* ((x + 2).^2 + (y + 2).^2 - 1) - 0.02*(x.^2 + y.^2 + 7*z.^2).^5;

res = 0.1;
r = 8;
x = -r:res:r;
y = -r:res:r;
z = -r:res:r;
[X, Y, Z] = meshgrid(x, y, z);
V = fun(X,Y,Z); % volumetric function (e.g. distance function)
I = isosurface(x ,y , z, V, 0); % extract level set as a mesh

p = patch(I);
isonormals(X, Y, Z, V, p);
p.FaceColor = 'red';
p.EdgeColor = 'none';
daspect([1 1 1])
view(3);
axis tight;
camlight;
lighting gouraud;


text:
Q: Principle of superposition and QED For finding a net force on a charge when it is in influence of many charges we simply do vectorical addition of all individual interaction of that charge with others. That's what is principle of superposition. It is an observed experimental fact. The principle of superposition and coulomb's law rule the whole electrostatics and same principle we do use in classical electrodynamics. But QED models how these forces actually work (with the virtual particles and more). So in QED do we still add individual interactions of charges to get a net Electric field at a point or force acting on a particle which is in influence of many, or something strange happens at quantum level?
( Adding more : So,is principle of superposition still an observed experimental fact or do any model keep an opinion about it ? )

A: In QED, this superposition principle is still valid at least to first order perturbation theory. The deeper reason behind this superposition principle from the QED point of view, is, that photons do not interact with each other. They do not carry charges. They do not "see" each other. So they can be safely  superposed without having an effect on each other.
Since the electromagnetic field is described by photons in QED, the same applies for the electromagnetic and therefore also for the electrostatic field.
Please be aware that when I just said that "the field is described by photons" this does not mean that you can imagine a field as composed out of photons. The description happens in a highly non-trivial and very abstract manner totally lacking any imaginability.
As ACuriousMind already pointed out, the field is actually an operator-valued distribution in QED which lives in some Hilbertspace (an abstract mathematical space which kind of replaces the imaginability we are used to in classical physics in QM).
The field operator at a single point in spacetime has the capability of adding or canceling field quanta  ("photons" so to speak) at this point in space and time. This capability of adding and canceling quanta at a certain point in spacetime contributes to a transition amplitude if certain condition (like energy momentum conservation) are fulfilled (to formulate it in rather simple language).
One would not talk about "forces" in QED, by the way. The concept of force is nearly totally absent in QED. It is replaced by the concept of interaction (!!!!and not by the concept of exchange of virtual particles!!!!).
You define a suitable interaction term in the Hamiltonian (= energy) or Lagrangian which contains the fields you would like to interact with each other and compute transition amplitudes with it. Regarding the virtual particles, they only appear when you try to compute the transition amplitude via perturbation theory (which is the only suitable way since exact solutions are not available).
So, they are actually kind of artefacts of the approximation scheme we use to evaluate things we can measure at the end.
At the very beginning I said that the superposition principle is valid only to first order perturbation theory. This is true, since when you push the approximation scheme further (to second order), photons indeed can interact with each other. They do not do this directly, but via virtual charged particles. The technical term is "Delbrück scattering". The cross section of this interaction is very, very tiny and does not have an effect in any practical applications.

A: QED is rarely concerned with precise forces or fields, although you may calculate e.g. the Coulomb force in a non-relativistic classical limit, see my answer here.
QED is a quantum field theory. As such, the electromagnetic field does not possess a definite "value" at any point, it is to be thought of as an operator-valued distribution and what you may want to compute is e.g. its expectation value. Furthermore, particles in a quantum field theory may be created and destroyed, and it is only at energy/distance scales where this is relevant that QED delivers substantial corrections to the classical electromagnetism, but it is also at this scale that the classical picture of a bunch of charged particles that sit at definite spatial locations is not a good picture of what the theory describes (and presumably how the world is) anymore.
Thus, your question is not really meaningful at the quantum level - we do not think in terms of single charges and the fields produced by them on the level of the quantum field theory.


text:
Q: i want select city from cites table and create View in stored Procedure my stored procedure :
USE [maskanjo.com_travelenterDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[SPSelectCites]
    -- Add the parameters for the stored procedure here
    @cityName  nvarchar(50)
AS
BEGIN

    SET NOCOUNT ON;
--------------------------Select---------------------

CREATE VIEW CUSTOMERS_VIEW AS
    SELECT *
    FROM [dbo].[City] where [NameFA] LIKE cityName+'%'

-----------------------------------------------------
END

i want select city from cites table and create View
have error
Error :
Incorrect syntax:'CREATE VIEW' Must be only statement in the batch

A: The error tells you what the problem is. Try executing the query using the "Exec" command:
declare @sql varchar(max)
set @sql = 'CREATE VIEW CUSTOMERS_VIEW AS SELECT * FROM [dbo].[City]
where [NameFA] LIKE ''' + cityName + '%'''
exec (@sql)


text:
Q: Converting result set of a column into those many column names in oracle How to divide result set of a Column into multiple columns
Suppose I've a column Quarter and Tenure with values as below for table Sample
Quarter|Tenure
Q1     |3
Q2     |3
Q3     |2
Q4     |1

So tenure is the number of months served quarterly by an employee.
Now I expect the result set to be the four different tenures fetched quarterly should be in four different columns. Meaning it should show for which quarter how much is the tenure but in 4 different columns.
e.g.
Q1_A| Q2_A |Q3_A |Q4_A
3   | 3    |2    |1

A: You could use DECODE:
SELECT SUM(DECODE(quarter,'Q1',tenure,0)) Q1_A,
SUM(DECODE(quarter,'Q2',tenure,0)) Q2_A,
SUM(DECODE(quarter,'Q3',tenure,0)) Q3_A,
SUM(DECODE(quarter,'Q4',tenure,0)) Q4_A
FROM Sample;

A: Use PIVOT:
Oracle Setup:
CREATE TABLE table_name ( Quarter, Tenure ) AS
  SELECT 'Q1', 3 FROM DUAL UNION ALL
  SELECT 'Q2', 3 FROM DUAL UNION ALL
  SELECT 'Q3', 2 FROM DUAL UNION ALL
  SELECT 'Q4', 1 FROM DUAL;

Query:
SELECT *
FROM   table_name
PIVOT  ( MAX( Tenure ) FOR Quarter IN (
    'Q1' AS Q1_A,
    'Q2' AS Q2_A,
    'Q3' AS Q3_A,
    'Q4' AS Q4_A
) )

Output:

Q1_A | Q2_A | Q3_A | Q4_A
---: | ---: | ---: | ---:
   3 |    3 |    2 |    1

db<>fiddle here


text:
Q: Braintree & Taxamo integration, how to do it right? Yes, Braintree and Taxamo have a couple of widgets facilitating their integration, but the way they work they are tied to the process of authorization of a credit card while what the tax services are interested in are SETTLED transactions (i.e. what is actually billed from the client at the end of the day),
settled transactions aren't the same thing as authorized transactions, voids, IO problems in API communication, client-side software bugs, even credit card company policies (chargebacks, presentment rejections etc) result with what is authorized not being equal to what is settled / billed,
special world of pain continues when you consider the complex formulas for mid-cycle subscription updates (proration), discount and addon calculations and the fact that none of my subscription API calls done using the sandbox don't have a transaction object (so I don't know the amounts being billed from the client),
meaning I have to reimplement a bunch of advanced logic done by Braintree to deduce what the client will see on his bank statement and hope to have gotten everything right, or have IRS on our back -_- (in Croatia companies get blocked over 1-3 euro imbalances in the tax reports)
So the question, am I missing something here?

*

*is there a simple way to submit to Taxamo only settled transactions?

*does maybe the sandbox and mock webhooks behave differently than production, is it possible that Subscription API calls and webhooks in production return a transaction object and that I just don't see it?

*does the current Braintree and Taxamo integration at least "kind of work in practice 100% of the time" and I'm worrying too much?

A: Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
Braintree and Taxamo don't have an official integration package (the widgets available are not supported by Braintree, and Braintree had no hand in developing them). However, the two can be, and often are, used alongside each other. Because there's no official integration, the two integrations don't interact with one another, and the logic concerning when any action in Taxamo should take place in relation to an action in Braintree is up to a user to implement.
With that in mind, there's no 'out-of-the-box' solution to submit only settled transactions to Taxamo. Braintree does offer settlement batch summary reports, which contain the transactions that settle every night. Using the information there, you could submit your transactions to Taxamo every night alongside the settlement batches. However, be aware that transactions don't always settle immediately, so there will be a gap between the time that you submit a transaction for settlement and the time you submit the transaction to Taxamo.
Alternatively, you could store the transaction in Taxamo immediately and keep track of the transaction key that Taxamo generates to reference the tranasction. Then, if anything happens that prevents the transaction from settling, you can delete that transaction in Taxamo.
These are just two options to consider for an open-ended problem. As always, you should evaluate your business needs carefully, and do whatever you believe will work best.
As BladeBarringer mentioned in the comments to your question, the subscription response object does contain an array of transactions that you can reference. The most recent transaction is always at index [0] of that array.


text:
Q: why does rand() in this code always produce the same matrix I would like to create a matrix which has all it's elements as either 1 or 0. This is what I've tried, it produces a matrix with 1s and 0s at random locations just as I want. However, it produces the same matrix everytime.
#include <stdio.h>
#include <stdlib.h>

int a[10][10];
int i = 0,j= 0,n=0;

int main(void)
{
 populate(5);
 print(5);

 return 0;
}

int populate(int n)
{
 for(i=0;i<n;i++)
 {
  for(j=0;j<n;j++)
  {
   a[i][j] = rand()%2;
  }
 }
}

int print(int n)
{
 for(i=0;i<n;i++)
 {
  for(j=0;j<n;j++)
  {
   printf("%d ",a[i][j]);
  }
  printf("\n");
 }
}

EDIT : Based on replies, I have edited my function as follows. However I see that my matrix is now all zeros or all ones.
int populate(int n)
{
 for(i=0;i<n;i++)
 {
  for(j=0;j<n;j++)
  {
   srand (time(NULL));
   a[i][j] = rand()%2;
  }
 }
}

A:
However, it produces the same matrix everytime.

That's because you haven't added the code to seed the random number generator. Add
srand(time(NULL));

at the start of main, before any calls to rand() are made.

A: You need to add srand ( time(NULL) );
The pseudo-random number generator is initialized using the argument passed as seed.
For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.
Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.
If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.
Here is an example how you seed srand:
/* srand example */
#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
  printf ("First number: %d\n", rand()%100);
  srand (time(NULL));
  printf ("Random number: %d\n", rand()%100);
  srand (1);
  printf ("Again the first number: %d\n", rand()%100);

  return 0;
}

EDIT: As the OP edited the question, here is the solution:
Use srand(time(NULL)); very beginning of the method.
int populate(int n) {
    srand(time(NULL));
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            a[i][j] = rand() % 2;
        }
    }
    return 0;
}


text:
Q: Are the builder pattern and a DSL equivalent - or is one more expressive? Assumptions

*

*I'll limit this to internal DSLs - but if you can give me a good reason why I should consider external DSLs - I'll listen to that.

*If you want to answer this in Clojure or Scala and explain why I'm wrong - I'm cool with that too.

I heard a friend say the other day:

You know, a DSL and the builder pattern - they're basically the same thing.

To me this sounded strange, as I had always assumed a DSL would always be more expressive than the Builder Pattern.
My question is: Are the builder pattern and a DSL equivalent - or is one more expressive?
So I took a look - here is a User Builder Pattern in Java:
public class User {
    private final String firstName; // required
    private final String lastName; // required
    private final int age; // optional
    private final String phone; // optional
    private final String address; // optional

    private User(UserBuilder builder) {
        this.firstName = builder.firstName;
        this.lastName = builder.lastName;
        this.age = builder.age;
        this.phone = builder.phone;
        this.address = builder.address;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public int getAge() {
        return age;
    }

    public String getPhone() {
        return phone;
    }

    public String getAddress() {
        return address;
    }

    public static class UserBuilder {
        private final String firstName;
        private final String lastName;
        private int age;
        private String phone;
        private String address;

        public UserBuilder(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public UserBuilder age(int age) {
            this.age = age;
            return this;
        }

        public UserBuilder phone(String phone) {
            this.phone = phone;
            return this;
        }

        public UserBuilder address(String address) {
            this.address = address;
            return this;
        }

        public User build() {
            return new User(this);
        }

    }
}

Here is the above builder pattern being used:
public User getUser() {
    return new
        User.UserBuilder("John", "Doe")
        .age(30)
        .phone("1234567")
        .address("Fake address 1234")
        .build();
}

Here is usage of an Internal DSL in Java:
 Person person = constructor().withParameterTypes(String.class)
                              .in(Person.class)
                              .newInstance("Yoda");

 method("setName").withParameterTypes(String.class)
                  .in(person)
                  .invoke("Luke");

 field("name").ofType(String.class)
              .in(person)
              .set("Anakin");

A: I don't think that you can even compare these 2 different concepts.
A DSL is a language for a specific domain i.e it has primitives and composition rules that allows you to talk about a specific domain.
A builder pattern is a pattern i.e a solution template that you apply to a problem to come up with a solution and then you use that solution. In your code example, the UserBuilder class comes out of applying the builder pattern, it itself is not builder pattern.
It seems that you are trying to compare them syntactically as your sample code is trying to show. In both the example code you show that syntactically, both DSL and a builder patter class, have the same feature i.e a chain of method calls and that leads to the thought that you can compare them. I don't think that comparison is fair as that can only allow you to compare them in a same language i.e there is no way to compare them syntactically across different programming languages.
You can implement a DSL using the builder pattern OR you can also implement DSL using other patterns too. A pattern is a solution template for a set of problems, builder pattern is one such template for the problem of implementing a DSL but it is not the only one.

A: Of course DSLs include a lot of things which aren't a builder pattern. So no, they aren't the same thing.
If you consider every builder pattern to be a DSL (for the domain of constructing objects of a particular class), then you obviously get that DSLs in general are more expressive than builder patterns. But a DSL is not more expressive than the builder pattern; any single DSL can't do everything that the builder pattern can do.

A: Had your friend said

You know, for constructing Plain Old Java Objects, the builder pattern is a kind of DSL.

... then I'd agree.
However, in Clojure, you don't need a builder class or a DSL to construct an object concisely.

*

*POJOs translate into records, which imitate (hash) maps. There is a somewhat clunky
syntax for creating a record from a map.

Given
(defrecord User [first-name last-name age phone address])

... then
(map->User {:first-name "John"
            :last-name "Doe"
            :address "Fake address 1234"})

... produces
{:first-name "John",
 :last-name "Doe",
 :age nil,
 :phone nil,
 :address "Fake address 1234"}

... which is a User record, though it prints like a map.
So, for this purpose, Clojure takes the DS out of DSL and you're just left with a language construct.


text:
Q: Minimum separation between two bodies
Let Bodies A and B be kept at two points in the x-y plane. They are allowed to move in the x-y plane.
  Suppose the velocity of B is constant, and the speed of body A is fixed, how must the body A move so that the bodies A and B get as close as possible at any point of time. The two bodies start from rest at the same time.

My approach:
I assumed some general intitial coordinates of bodies A and B and velocity of body B to be $a \wedge{i}+ b \wedge{j}$ and of A to be $v_x \wedge{i} + v_y \wedge{j}$.
The situation seemed a bit complicated in ground frame, I assumed a general time t, calculated the position of bodies A and B, and tried to find the minimum distance between bodies A and B(by differentiation), but it got too messy.
I also tried in frame of reference of B but couldn't make much progress.
Intuitively, I feel that the direction of velocity of A must be given is independent of the initial coordinates of A and B and it much be such that velocity of A is perpendicular to the relative velocity of B wrt A.
Is this true? How to prove this?
(Sorry for the terrible latex. I am not getting how to write I cap, j cap)

A: Hint:
I suggest a different approach.
First, choose the coordinates such that body $B$ is at the origin for $t=0$ and let its velocity be along the $x$ axis, so $\vec{v_B} = v_B \vec{i}$.
Body $A$ would start somewhere in the plane $\vec{r_A}(t=0) = x_0 \vec{i} + y_0 \vec{j}$, with velocity $\vec{v_A} = v_A^x \vec{i} + v_A^y \vec{j}$.
Then we could change the referential to body $B$. In this referential, at time $t=0$, $A$ would be at $\vec{r_A'}(t=0) = x_0 \vec{i} + y_0 \vec{j}$ but it's moving with velocity $\vec{v_A'} = (v_A^x - v_b) \vec{i} + v_A^y \vec{j}$.
Can you solve it from this point onward?


text:
Q: Java - Is it possible to call an interface method on a any object? Lets say I have Object X and Object B. X is an object of a random class, which in turn creates B, and passes itself on to be stored as a variable in object B.
Now object B, wants to run a method in object X, without knowing what class it is.
Is it possible to call a method in any object, and if a method with that name exist, it runs, and if not, it doesn't. I assume some try/catch can work around that part.
But lets say i have something like this:
public class ObjectB {

  public Object parentX;

  public ObjectB(Object x) {
    parentX = x;
  }

  public void anyMethod() {
    x.runMyMethod();
  }
}

In another program I worked with, this was possible with interfaces, and therefore have an idea that it is possible with Java too. However, i cant seem to find the way to set this up. So if the above was the case, how would it be set up, such that ObjectB can call the method on all the classes in my program if that was what i wanted?

A:
Now object B, wants to run a method in object X, without knowing what class it is.

Simply doesn't make sense. In order to invoke a method, you need to know its name and the expected parameters. In that sense, class B needs some knowledge. Thus, you would/could do something like
if (parentX instanceof ClassA) {
 ( (ClassA) parentX ) . someAMethod(bla, blub);
}
if (parentX instanceof InterfaceC) {
 ( (InterfaceC) parentX ) . someCMethod(bla, blub);
}

In that sense: you might use an interface here; but classes work as well. The key thing is: you need a certain piece of information; otherwise you are simply stuck.
The only other alternative is to look into reflection - then you would not need to know the specific type; as you can inspect parentX to find out which methods could be called on that object. But reflection is A) an advanced concept and b) intricate in its usage.

A: Yes its definitely possible.
Define interface MyIntf, and your Class X implements it. now in Class B you can assign the object of Class X (or any class that implements MyIntf) to parent which of type MyIntf the you can invoke method with that parent
    interface MyIntf
    {
       void runMyMethod()
    }

    public class ObjectX implements MyIntf {
           void runMyMethod()
           {
           }
    }

    public class ObjectB {

      public MyIntf parentX;

      public ObjectB(MyIntf x) {
        parentX = x;
      }

      public void anyMethod() {
        parentX.runMyMethod();
      }
    }

A: If you look at the end of this documentation, it tells you about casting. Casting allows the program to assume the object is of a type and attempt to call a method within it.
public void anyMethod() {
     ((MethodParentObject) this.x).runMyMethod();
}


text:
Q: How can I find if a number in a doubly linked list is between max and min? I want to create a method called inBetween that accepts an item as a parameter and returns true if the item is "in between" the smallest and largest list elements. That is, based on the compareTo method defined for list elements, the item is larger than the smallest list element and smaller than the largest list element. Otherwise, the method returns false (even if the item "matches" the smallest or largest element).
public class DoublyLinkedList {

private Link first;               // ref to first item
private Link last;                // ref to last item
// -------------------------------------------------------------

public DoublyLinkedList() // constructor
{
    first = null;                  // no items on list yet
    last = null;
}
// -------------------------------------------------------------

public boolean isEmpty() // true if no links
{
    return first == null;
}
// -------------------------------------------------------------

public void insertFirst(long dd) // insert at front of list
{
    Link newLink = new Link(dd);   // make new link

    if (isEmpty()) // if empty list,
    {
        last = newLink;             // newLink <-- last
    } else {
        first.previous = newLink;   // newLink <-- old first
    }
    newLink.next = first;          // newLink --> old first
    first = newLink;               // first --> newLink
}
// -------------------------------------------------------------

public void insertLast(long dd) // insert at end of list
{
    Link newLink = new Link(dd);   // make new link
    if (isEmpty()) // if empty list,
    {
        first = newLink;            // first --> newLink
    } else {
        last.next = newLink;        // old last --> newLink
        newLink.previous = last;    // old last <-- newLink
    }
    last = newLink;                // newLink <-- last
}
// -------------------------------------------------------------

public Link deleteFirst() // delete first link
{                              // (assumes non-empty list)
    Link temp = first;
    if (first.next == null) // if only one item
    {
        last = null;                // null <-- last
    } else {
        first.next.previous = null; // null <-- old next
    }
    first = first.next;            // first --> old next
    return temp;
}
// -------------------------------------------------------------

public Link deleteLast() // delete last link
{                              // (assumes non-empty list)
    Link temp = last;
    if (first.next == null) // if only one item
    {
        first = null;               // first --> null
    } else {
        last.previous.next = null;  // old previous --> null
    }
    last = last.previous;          // old previous <-- last
    return temp;
}
// -------------------------------------------------------------
// insert dd just after key

public boolean insertAfter(long key, long dd) {
// (assumes non-empty list)
    Link current = first;          // start at beginning
    while (current.dData != key) // until match is found,
    {
        current = current.next;     // move to next link
        if (current == null) {
            return false;            // didn't find it
        }
    }
    Link newLink = new Link(dd);   // make new link

    if (current == last) // if last link,
    {
        newLink.next = null;        // newLink --> null
        last = newLink;             // newLink <-- last
    } else // not last link,
    {
        newLink.next = current.next; // newLink --> old next
        // newLink <-- old next
        current.next.previous = newLink;
    }
    newLink.previous = current;    // old current <-- newLink
    current.next = newLink;        // old current --> newLink
    return true;                   // found it, did insertion
}
// -------------------------------------------------------------

public Link deleteKey(long key) // delete item w/ given key
{                              // (assumes non-empty list)
    Link current = first;          // start at beginning
    while (current.dData != key) // until match is found,
    {
        current = current.next;     // move to next link
        if (current == null) {
            return null;             // didn't find it
        }
    }
    if (current == first) // found it; first item?
    {
        first = current.next;       // first --> old next
    } else // not first
    // old previous --> old next
    {
        current.previous.next = current.next;
    }

    if (current == last) // last item?
    {
        last = current.previous;    // old previous <-- last
    } else // not last
    // old previous <-- old next
    {
        current.next.previous = current.previous;
    }
    return current;                // return value
}
// -------------------------------------------------------------

public void displayForward() {
    System.out.print("List (first-->last): ");
    Link current = first;          // start at beginning
    while (current != null) // until end of list,
    {
        current.displayLink();      // display data
        current = current.next;     // move to next link
    }
    System.out.println("");
}
// -------------------------------------------------------------

public void displayBackward() {
    System.out.print("List (last-->first): ");
    Link current = last;           // start at end
    while (current != null) // until start of list,
    {
        current.displayLink();      // display data
        current = current.previous; // move to previous link
    }
    System.out.println("");
}
// -------------------------------------------------------------

public DoublyLinkedList inBetween(long n) {

}
}  // end class DoublyLinkedList
////////////////////////////////////

public class InBetweenDemo
{
public static void main(String[] args)
  {                             // make a new list
  DoublyLinkedList theList = new DoublyLinkedList();

  theList.insertFirst(22);      // insert at front
  theList.insertFirst(44);
  theList.insertFirst(66);

  theList.insertLast(11);       // insert at rear
  theList.insertLast(33);
  theList.insertLast(55);

  theList.displayForward();
  int n=55;// display list forward
  System.out.println("inBetween("+n+") "+ inBetween(n));
  theList.displayBackward();    // display list backward

  theList.deleteFirst();        // delete first item
  n=55;
  System.out.println("inBetween("+n+") "+ theList.inBetween(n));

  theList.deleteLast();
  n=33;
  System.out.println("inBetween("+n+") "+ theList.inBetween(n));
  theList.deleteKey(22);        // delete item with key 11
  System.out.println("inBetween("+n+") "+ theList.inBetween(n));

  theList.displayForward();     // display list forward

  theList.insertAfter(11, 77);  // insert 77 after 22
  theList.insertAfter(33, 88);  // insert 88 after 33

  theList.displayForward();     // display list forward
  }  // end main()
}  // end class DoublyLinkedApp
////////////////////////////////////////////////////////////////

I was thinking that I could assign a max and min and then check if the parameter is less than and greater than each respective values. If it was then I would return true, if not return false. I'm not sure how I would start the code of looking for the max and min in an unordered list.

A: I think you should create two variables, MAX and MIN firstly. After, run over the List and find the MAX and the MIN values. So, pick the value you want to campare and make the comparison. If the value is bigger than MIN and smaller than MAX, it is a valid number. I sugest you add a variable called listLenght on the class of the List. When you add something, update the variable listLenght. When you remove, do the same.

A: There are two possible ways to solve your problem. (There might be other methods)

*

*You can make another method that will go through your linked list and find min and max. And just call this method in your inBetween method. This method will have the worst case of O(n). (If you are planning to do this then having a variable for min and max is not enough, you have to call the method every time you call inBetween since there is a possibility that the values have been updated)

*Have a variable for min and max then update it after every insert and delete. It must be of type Link. In insert it will just have the runtime of O(1) since you will just compare their values directly. While in delete you will have to compare the key, if it has the same key then you have to find another min or max. Thus you should also create a method to find min and max. And in your inBetween method you will just have to get the variables min and max. There is no possibility that the values for min and max will update while executing inBetween since you are updating min and max every insert and delete.

So there you go, just choose what you will implement from the two.

A: Just iterate the list and make sure your item is less than at least one element and more than another:
public boolean inBetween(long n) {
    boolean less = false, more = false;
    for (Link current = first; current != null; current = current.next)
        if ((less |= n < current.dData) & (more |= n > current.dData))
            return true;
    return false;
}

A: Iterate over the list to find the min and max values, then return true if the input value is greater than min and less than max:
public static boolean isBetween(List<Integer> list, int value){

    int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;

    for (int i : list){

        if (i < min)
            min = i;

        if (i > max)
            max = i;
    }

    return value > min && value < max;
}


text:
Q: memory mapped file access is very slow I am writing to a 930GB file (preallocated) on a Linux machine with 976 GB memory.
The application is written in C++ and I am memory mapping the file using Boost Interprocess. Before starting the code I set the stack size:

ulimit -s unlimited

The writing was very fast a week ago, but today it is running slow. I don't think the code has changed, but I may have accidentally changed something in my environment (it is an AWS instance).
The application ("write_data") doesn't seem to be using all the available memory. "top" shows:
Tasks: 559 total,   1 running, 558 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.0%us,  0.0%sy,  0.0%ni, 98.5%id,  1.5%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:  1007321952k total, 149232000k used, 858089952k free,   286496k buffers
Swap:        0k total,        0k used,        0k free, 142275392k cached

   PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
  4904 root      20   0 2708m  37m  27m S  1.0  0.0   1:47.00 dockerd
 56931 my_user   20   0  930g  29g  29g D  1.0  3.1  12:38.95 write_data
 57179 root      20   0     0    0    0 D  1.0  0.0   0:25.55 kworker/u257:1
 57512 my_user   20   0 15752 2664 1944 R  1.0  0.0   0:00.06 top

I thought the resident size (RES) should include the memory mapped data, so shouldn't it be > 930 GB (size of the file)?
Can someone suggest ways to diagnose the problem?

A: Memory mappings generally aren't eagerly populated. If some other program forced the file into the page cache, you'd see good performance from the start, otherwise you'd see poor performance as the file was paged in.
Given you have enough RAM to hold the whole file in memory, you may want to hint to the OS that it should prefetch the file, reducing the number of small reads triggered by page faults, substituting larger bulk reads. The posix_madvise API can be used to provide this hint, by passing POSIX_MADV_WILLNEED as the advice, indicating it should prefetch the whole file.