text:
Q: How to bind text alignment in GridViewColumn I'm using MVVM in a WPF application. I've a UserControl whose DataContext is set to a ViewModel. The UserControl is a table with 3 columns.

This is the following ListView/GridView:
<DockPanel>
        <ListView DockPanel.Dock="Top" ItemsSource="{Binding Items}" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                  ctrl:ListViewLayoutManager.Enabled="True">
            <ListView.View>
                <GridView>

                    <GridViewColumn Header="{Binding ColumnHeader1}"
                                    CellTemplate="{StaticResource cellTemplateColumn1}">
                        <GridViewColumn.HeaderContainerStyle>
                            <Style BasedOn="{StaticResource {x:Type GridViewColumnHeader}}" TargetType="GridViewColumnHeader">
                                <Setter Property="TextBlock.TextAlignment" Value="{Binding Column1HAlignment}" />
                            </Style>
                        </GridViewColumn.HeaderContainerStyle>
                    </GridViewColumn>

                    <GridViewColumn Header="{Binding ColumnHeader2}"
                                    CellTemplate="{StaticResource cellTemplateColumn2}">
                        <GridViewColumn.HeaderContainerStyle>
                            <Style BasedOn="{StaticResource {x:Type GridViewColumnHeader}}" TargetType="GridViewColumnHeader">
                                <Setter Property="TextBlock.TextAlignment" Value="{Binding Column2HAlignment}" />
                            </Style>
                        </GridViewColumn.HeaderContainerStyle>
                    </GridViewColumn>

                    <GridViewColumn Header="{Binding ColumnHeader3}"
                                    CellTemplate="{StaticResource cellTemplateColumn3}"
                                    ctrl:RangeColumn.IsFillColumn="True">
                        <GridViewColumn.HeaderContainerStyle>
                            <Style BasedOn="{StaticResource {x:Type GridViewColumnHeader}}" TargetType="GridViewColumnHeader">
                                <Setter Property="TextBlock.TextAlignment" Value="{Binding Column3HAlignment}" />
                            </Style>
                        </GridViewColumn.HeaderContainerStyle>
                    </GridViewColumn>

                </GridView>
            </ListView.View>
        </ListView>

    </DockPanel>

This is achieved by the following resources:
<Style TargetType="GridViewColumnHeader">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="GridViewColumnHeader">
                            <TextBlock Text="{TemplateBinding Content}" Margin="5" Width="{TemplateBinding Width}">
                        </TextBlock>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="FontWeight" Value="Bold" />
            <Setter Property="FontSize" Value="14" />
        </Style>

        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            <Setter Property="VerticalAlignment" Value="Stretch" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
        </Style>

        <DataTemplate x:Key="cellTemplateColumn1">
            <fa:ImageAwesome Icon="{Binding IconType}" Foreground="{Binding Status}" Width="10" />
        </DataTemplate>

        <DataTemplate x:Key="cellTemplateColumn2">
            <TextBlock Text="{Binding SerialNumber, StringFormat='0'}" />
        </DataTemplate>

        <DataTemplate x:Key="cellTemplateColumn3">
            <TextBlock Text="{Binding Action}" TextWrapping="Wrap" />
        </DataTemplate>

The text alignments of each column is settable through the view model. I can do this easily for the headers:
<GridViewColumn.HeaderContainerStyle>
    <Style BasedOn="{StaticResource {x:Type GridViewColumnHeader}}" TargetType="GridViewColumnHeader">
        <Setter Property="TextBlock.TextAlignment" Value="{Binding Column1HAlignment}" />
    </Style>
</GridViewColumn.HeaderContainerStyle>

But how can I pass the same parameter (Column1HAlignment) to align the cell's TextBlock contents?
Note the alignment of the 2nd column (where header is #) in the image above. The header is right aligned through data binding. I want the same binding for each cell content.

A: You could bind the HorizontalAlignment property of the element in the CellTemplate to the Column1HAlignment source property using a {RelativeSource}:
<DataTemplate x:Key="cellTemplateColumn2">
    <TextBlock Text="{Binding SerialNumber, StringFormat='0'}"
                               HorizontalAlignment="{Binding DataContext.Column1HAlignment,
                                    RelativeSource={RelativeSource AncestorType=ListView}}"/>
</DataTemplate>


text:
Q: How to open Node.js command line in ubuntu? I have completed installed Ruby on Rails on my ubuntu system. I have installed Node.js of version v0.10.33. I have try to search the node.js command prompt but not found. May anybody help me how to open node.js cmd prompt in ubuntu ?

A: The binary for node.js provided by the nodejs package is called nodejs. So, run:
nodejs
#or
/usr/bin/nodejs

A: As muru already mentioned: Since there is a naming conflict with another package "node" is called "nodejs" in Ubuntu. To fix any related errors can add a link to nodejs like this:
sudo ln -s /usr/bin/nodejs /usr/bin/node

redpajama_set_name: RedPajamaStackExchange


text:
Q: uint: Why is -(a*b) different from -a*b I understand all of these apart from the last one:
import numpy as np
a = np.array(5).astype('uint16')

a
Out[24]: array(5, dtype=uint16)

-a
Out[25]: 65531

a*1.
Out[26]: 5.0

-(a*1.)
Out[27]: -5.0

0-a*1.
Out[28]: -5.0

-a*1.
Out[29]: 65531.0

type(a*1.)
Out[30]: numpy.float64

In the last line a uint variable is multiplied with a float resulting in a float, so why is the result of -a*1. not -5.0, and how is this different from -(a*1.) and 0-a*1.?

A: -a*1. is (-a)*1., because unary - has a higher precedence than *. For details, look at the excerpts from the Python grammar in the documentation.

A: I think it is due to the order of operations:
-a*1. is from left to right, but 0-a*1. it is a subtraction (even if it is zero) and the 0- is applied after a*1. (where the type of the object is changed).


text:
Q: MongoDB - Query Multiple Documents which match array values; I am trying to query multiple documents based on an array of document IDs.
Here is an example array: [{_id: '123151djadjw11', quantity: 1}, {_id: 'some4idda123131', quantity: 2}];
I want to be able to send an array like that to the server and retrieve the documents matching the ID property in each of the objects in the array.
Any ideas would be greatly appreciated!
Thanks in advance!

A: let array1 = [{_id: '123151djadjw11', quantity: 1}, {_id: 'some4idda123131', quantity: 2}];
let array2 = array1.map(a => a._id);

//results array2 =['123151djadjw11', 'some4idda123131'];
db contains values as
{
"_id" : "123151djadjw11",
"quantity" : 1.0
}
{
"_id" : "some4idda123131",
"quantity" : 2.0
}
{
"_id" : "3rdId",
"quantity" : 5.0
}
let array3 = db.objects.find({_id:{$in : array2}}).toArray();

//returns array3= [{_id: '123151djadjw11', quantity: 1}, {_id: 'some4idda123131', quantity: 2}]


text:
Q: Python - SSL Client/Server Certificate I want to create a Client/Server architecture following the python documentation.
This works well with my self-signed certificates in one pem file. (ca_root root_key ca_intermediate intermediate_key)
So my next plan is to create client certificates which can be revoked by the server if the client isn't trustworthy anymore.
So the way to go is that i create a certificate, signed with the intermediate key, and hand it out to the client.
But i still get
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)
Do i need to export the whole certificate chain to the client? This seems odd to me.
Thanks!

A: Most likely you're entire chain isn't in your .pem file. Just copy the text from the certificates in the right order into a single .pem file and attempt that. If that doesn't work you may be getting this error because of your server configuration. More information is need thought to provide a better answer.


text:
Q: Getting the face of a cube I want to calculate which face on a cube has been clicked. I've got the mouse to 3D down, and I can draw things, in 3D, at the mouse's position.
All I need to do now is calculate WHAT face of a cube is being touched.
EG. I have a function, when I pass the size, position and mouse position to it, it returns the face. Top, bottom, left, right, front, back.
Sounds simple, but I don't have the foggiest.
Thanks all,
SilentC

A: not sure what API are you using but OpenGL has a selection API, which does this for you

A: You just have to calculate a line plane intersection for every face of the cube with the line defined by the camera location and the mouse position on the view plane. Throw out all intersection that are in the plane but not on the face of the cube and pick the closest one.
You can also use line triangle intersections if you represent the cube as twelve triangles. But in both case you have to provide much more information for a more specific answer.


text:
Q: Filereader image thumbnail lags I'm using Filereader API to show little thumbnails of photo uploads. However I'm having a problem. When you upload really big images, and you upload a few of those, it starts to lag. The thumbnails are really small but the files are too big. Is there a way to fix this? Here's my javascript:
document.querySelector('input').addEventListener('change', function(e){
    var files = e.target.files;

  for(var i = 0; i < files.length; i++){

    var f = files[i];
    var reader = new FileReader();

    reader.onload = (function(tf){
      return function(evt){
        document.querySelector('.thumbs').innerHTML += '

';
      }
    })(f);

    reader.readAsDataURL(f);
  }
});

Here's a fiddle where you can test it: https://jsfiddle.net/snx79yw2/1/.
For example, I tested it with 6000x4000 photos, and when there are more than 4, 5 they start to lag (and my PC is quite decent so it shouldn't lag like that).
BTW with lag I refer to slow down, freeze etc, not actual lag.
I found this post but I don't really know how to implement the solutions from that answer. Thx in advance!

A: This example resizes the images down to a max width of 127px using a Canvas before displaying them in the thumbnail list.

document.querySelector('input').addEventListener('change', function(e){
  var files = e.target.files;
  for(var i = 0; i < files.length; i++){
    var f = files[i];
    var reader = new FileReader();

    reader.onload = (function(tf) {
      return function(evt) {
        // resize the image before using the resolved dataURL to set the thumbnail src
        resize(evt.target.result, 127, function(dataURL) {
          document.querySelector('.thumbs').innerHTML += `<img class="thumb" src="${dataURL}" />`;
        });
      }
    })(f)

    reader.readAsDataURL(f);
  }
});
/**
* usage   resize( dataURL:src, int:maxWidth, function:callback)
*/
function resize(src, maxWidth, callback) {
    var img = document.createElement('img');
    img.src = src;
    img.onload = () => {
      var oc = document.createElement('canvas');
      var ctx = oc.getContext('2d');
      // resize to [maxWidth] px
      var scale = maxWidth / img.width;
      oc.width = img.width * scale;
      oc.height = img.height * scale;
      ctx.drawImage(img, 0, 0, oc.width, oc.height);
      // convert canvas back to dataurl
      callback(oc.toDataURL());
    }
}
.thumbs{background: #222;border-radius: 5px;white-space: nowrap;overflow-x: scroll;padding: .25rem;}
.thumb{height: 3rem;width: 3rem;border-radius: 3px;background-size: cover;background-position: center center;background-repeat: no-repeat;display: inline-block;margin: .25rem .25rem calc(.25rem - 4px);}
<input type="file" multiple />


text:
Q: Malformed JSON in Yahoo response I am trying to get Yahoo user email by decoding ID Token like here in Ruby. I have a token docoding it with Base64.decode64, parsing JSON and here problem come up. String I am trying to parse to JSON is invalid.
Sorry for this copy-paste have problem with formatting it.
START
{"at_hash":"pNgANAsIViDvJ7OCgSk1hw==","sub":"C4SNYQZSHET33BLBTUM3NU2KVP","email_verified":true,"birthdate":"1984","iss":"https://api.login.yahoo.com","profile_images":{"image64":"https://ws.progrss.yahoo.com/progrss/v1/user/C4SNYQZSHET33BLBTUM3NU2KVP/profile/picture
[XYNL΋XZ݌KӖTVU                   [Y^OM
              SLӕLՔ
                    ٚ[KX\O˚[Y^OLNL
                                 N[XY΋XZ݌KӖTVU
                                              SLӕLՔ
                                                    ٚ[KX\Bw6S##"vS3"#&GG3w2&w'726&w'72cW6W"E44UC34$ET$e&f7GW&Pͥȉ艕ULٕ}興Ր艑IYY])DYY9!5)4)9]9!EL4Ռa)]9aE}ѥ͕݅}ذЈ݅兡
END
It looks like the string is cut before its end. Is there any way to get proper JSON?
I am using Ruby 2.4.1


text:
Q: User needs to re-authenticate with Azure AD B2C after the user closes and reopens the browser I have an Angular front end application which is using Azure AD B2C custom policies(Home Realm Discovery) to authenticate the federated AAD user.
After I login to the application with federated Azure AD tenant user, close this tab(without logout) then open a new tab, access application and login, this user can be automatically sign in. This is the expected behavior as SSO feature.
But if I close the browser and reopen the browser, when try to login it asks me to input user name, seems the session is lost and the user need to re-authenticate.
I saw below documentation on Microsoft website:

The Keep me signed-in feature extends the session life time through
the use of a persistent cookie. The session remains active after the
user closes and reopens the browser. The session is revoked only when
a user signs out. The Keep me signed-in feature only applies to
sign-in with local accounts.

I was wondering is there a way to use the persistent cookie for Azure AD B2C(federated Azure AD tenant user)? How can I keep the session active after the user closes and reopens the browser?
Any help would be appreciated. Thanks.

A: According Microsoft doc.

You can enable Keep Me Signed In (KMSI) functionality for users of
your web and native applications that have local accounts in your
Azure Active Directory B2C (Azure AD B2C) directory. This feature
grants access to users returning to your application without prompting
them to reenter their username and password. This access is revoked
when a user signs out.

And Prerequisites.

An Azure AD B2C tenant that is configured to allow local account
sign-in. KMSI is unsupported for external identity provider accounts.

So,at present, there is no way to use the persistent cookie for Azure AD B2C(federated Azure AD tenant user).
For more information,please refer to this.


text:
Q: Unable to change the contents of the last index of a string in C? I am currently facing some issues with changing the contents of a string.
The following program I am writing rearranges words in the string src that start with a consonant such that the consonant ends up at the back (bob --> obb). Words that start with a vowel remain unchanged. The result is inserted into the string dest.
However, the last word of a sentence input always ends up with a missing consonant at the end (bob --> ob). This suggests to me that I am unable to change the contents of the last index of the string dest.
Is there a reason why?
void convert(char src[], char dest[]) {
    int i, isVowel, first_pos;
    int len = strlen(src);
    int count = 0;
    char first = 0;

    for (i = 0; i < len; i++) {
        while (!isspace(src[i])) {

            if (first == 0) {
                first = src[i];
                first_pos = i;
            }

            isVowel = first == 'a' || first == 'e' || first == 'i' || first == 'o' || first == 'u';

            if (isVowel == 1) {
                dest[count++] = src[i];
            }
            else if (i != first_pos) {
                dest[count++] = src[i];
            }

            i++;
        }

        if (isVowel == 0) {
            dest[count++] = first;
        }

        dest[count++] = ' ';
        first = 0;
      }
}

Input: "hi guys"
Expected output: "ih uysg"
Actual output: "ih uys"

A: You should change
while (!isspace(src[i])) {

to
while (src[i] && !isspace(src[i])) {

and the function is finally add
dest[count++] = '\0';

Modified code:
void convert(char src[], char dest[]) {
    int i, isVowel, first_pos;
    int len = strlen(src);
    int count = 0;
    char first = 0;

    for (i = 0; i <= len; i++) {
        while (src[i] && !isspace(src[i])) {

            if (first == 0) {
                first = src[i];
                first_pos = i;
            }

            isVowel = first == 'a' || first == 'e' || first == 'i' || first == 'o' || first == 'u';

            if (isVowel == 1) {
                dest[count++] = src[i];
            }
            else if (i != first_pos) {
                dest[count++] = src[i];
            }

            i++;
        }

        if (isVowel == 0) {
            dest[count++] = first;
        }

        dest[count++] = ' ';
        first = 0;
      }
      dest[count++] = '\0';
}

A: As far as I understand you want to iterate a string of words. If a word starts with a consonant you want to move that consonant to the end of the word (while keeping the rest of the word unchanged). If a word starts with a vowel you want to keep the whole word unchanged.
In your code I see a few things that look strange:

*

*In case the input starts with a space you use isVowel uninitialized which is undefined behavior

*It seems you never zero terminate the destination string
That said I think your algorithm is too complex. To get a more simple implementation consider this algorithm:
While unhandled characters in src:
  if current char is space
      copy space to dest
  else
      if current char is consonant
          save current char and move to next input char
      copy rest of word to dest
      if first char was consonant
          add saved char to destination

The code could look like:
void convert(char src[], char dest[])
{
  int i = 0;
  int count = 0;

  while(src[i])
  {
    if (isspace(src[i]))
    {
      // Copy the space
      dest[count++] = src[i++];
    }
    else
    {
      int isVowel = src[i] == 'a' || src[i] == 'e' || src[i] == 'i' || src[i] == 'o' || src[i] == 'u';

      char first;
      if (!isVowel)
      {
        // Save first char and move to next char
        first = src[i];
        ++i;
      }

      // Copy rest of word
      while (src[i] && !isspace(src[i]))
      {
        dest[count++] = src[i++];
      };

      if (!isVowel)
      {
        // Add the saved char
        dest[count++] = first;
      }
    }
  }

  // Terminate destination string
  dest[count] = '\0';
}


text:
Q: Can we use sigmoid activation function and binary _crossentropy for one hot encoded labels I am working on image dataset, where i have one hot encoded labels. Shape of label vector is (3500,8). When i try categorical cross entropy and softmax function in output layer my accuracy is very low. But when i use binary cross entropy and sigmoid my accuracy improves.
Previosuly I believe for multi class classification, we should use softmax and categorical cross entropy.
But in a kaggle competetion, i see use of sigmoid and binary cross entropy.
I want to know is it a right approach?
Can any one give me an insight to this concept.

A: This question probably duplicated this. Basically, by using binary cross entropy and 'accuracy' argument. You implicitly tell keras to use binary accuracy instead of categorical accuracy. Hence, the the problem changed to multilabel problem and not multiclass problem.


text:
Q: How to catch error from a forked child process? Node.js v8.11.1
There are two files: parent.js and child.js.
Parent
const { fork } = require('child_process');

const forked = fork('./child');

forked.on('message', (msg) => {
  console.log('Message from child', msg);
  forked.kill();
});

forked.on('error', (err) => {
  console.log('Error from child', err);
});

forked.send({ hello: 'world' });

Child
process.on('message', (msg) => {
  console.log('Message from parent:', msg);
});

try {
  let counter = 0;

  seTimeout(() => {
    process.send({ counter: counter++ });
  }, 1000);
} catch (err) {
  throw new Error('not good: ' + err);
}

There is an intentional typo in the child script - seTimeout. When I execute parent node parent.js, I get:
/media/trex/safe/Development/child.js:12
  throw new Error('not good: ' + err);
  ^

Error: not good: ReferenceError: seTimeout is not defined
    at Object.<anonymous> (/media/trex/safe/Development/siren/sentinl-private/server/lib/actions/report/child.js:12:9)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3

The error was not caught by the parent. How to catch the error by the parent?
Update 1
As I see here https://github.com/nodejs/node/issues/15734 this is working as intended. Maybe there is another event to catch errors or something else?
Update 2
Now I can catch an error the following way. But I'm not sure it is the best way to do it.
Parent
const { fork } = require('child_process');

const forked = fork('./child');

forked.on('message', (msg) => {
  if (msg.error) {
    console.error(msg.error);
  } else {
    console.log('Message from child', msg);
  }
  forked.kill();
});

forked.send({ hello: 'world' });

Child
process.on('message', (msg) => {
  console.log('Message from parent:', msg);
});

try {
  let counter = 0;

  seTimeout(() => {
    process.send({ counter: counter++ });
  }, 1000);
} catch (err) {
  process.send({error: err.message});
}

A: Why not to use the array of the option.stdio? This array has three elements [subprocess.stdin, subprocess.stdout, subprocess.stderr], thus you just want to console the errors and not anything else.
Therefore you'd use stdio: ['ignore', 'ignore', 'inherit']
Parent
const { execSync } = require('child_process')

try {
  execSync('node myNodeChildScript.js', { stdio: ['ignore', 'ignore', 'inherit'] })
} catch (err) {
  console.error(Error(err))
  process.exit(1)
}

Child
console.log('Some log') // this will not be output to parent
if (someError()) {
  console.error('There was an error') // this will be output to parent console
  process.exit(1) // exit with error
}


text:
Q: RxJS combine ObjectA emissions into ObjectB Array I have the following code grabbing data from a web service
@Effect()
searchAction$ : Observable<Action> = this._actions$
    .ofType(ActionTypes.SEARCH_CASES)
    .do(val => this._store.dispatch(new SetLoadingAction(true)))
    .map(action => action.payload) //just interested in the payload
    .map(payload => new CaseSearchCriteria(payload)) //form search criteria
    .switchMap(payload => this._httpSearchCases.searchDiseaseCases(payload)
        /*
            1. Return from httpCall is IDiseaseControlCaseManagement[]
            2. Transform this array into SearchDiseaseCaseResults[]
         */
        .do((val) =>{
            console.log('Type of Value: ', typeof val);
            console.log('Is value SearchDiseaseCaseResult? :', val instanceof SearchDiseaseCaseResults);
        })
        .map(res => new LoadSearchResultsAction(res))
    );

I have added comments briefly explaining my desired functionality, I'm certain there is a ReactiveX operator that can achieve this, however I am unable to find exactly what I'm looking for.
I tried pushing to the accumulator of the .scan operator
.scan((acc: SearchDiseaseCaseResults[], val: IDiseaseControlCaseManagement) => {
            acc.push(new SearchDiseaseCaseResults(val));
        })

However TS static analysis tells me this is incorrect,
Error:(32, 31) TS2453:The type argument for type parameter 'R' cannot be inferred from the usage. Consider specifying the type arguments explicitly.

Type argument candidate 'SearchDiseaseCaseResults[]' is not a valid type argument because it is not a supertype of candidate 'void'.

So I need an operator chain (or method) that will allow me to either:

*

*Receive an emission of type ObjectA.

*Transform emission of type ObjectA into object of type ObjectB

*Receive emissions of type ObjectB

*Combine each emission of ObjectB into a single array ObjectB[]

or

*

*Receive an emission of type ObjectA[]

*Transform emission of type ObjectA[] into array of type ObjectB[]

A: Unless i'm misunderstanding you, then the operator you're looking for is just the plain old map.
Taking a step back, let's focus on your switchMap.
.switchMap(payload => this._httpSearchCases.searchDiseaseCases(payload)

         //    1. Return from httpCall is IDiseaseControlCaseManagement[]
        .map(IDiseaseControlCaseManagementArray => this.mapToSearchDiseaseCaseResultsArray(IDiseaseControlCaseManagementArray) )

        .do((val) =>{
            console.log('Type of Value: ', typeof val);
            console.log('Is value SearchDiseaseCaseResult? :', val instanceof SearchDiseaseCaseResults);
        })
        .map(res => new LoadSearchResultsAction(res))
    );

I think that's basically what you're asking - the implementation of that mapToSearchDiseaseCaseResultArray method.
And, if you can map a single IDiseaseControlCaseManagement to a single SearchDiseaseCaseResult, then really, implementing the array version of that is simple.
So, assuming that there is a method convertFrom that can be used like:
searchDiseaseCaseResult = convertFrom(iDeseaseControlCaseManagement)

Then, with the arrays,
mapToSearchDiseaseCaseResultArray(sourceArray) {
  return sourceArray.map(caseManagement => this.convertFrom(caseManagement));
}

You, of course, still need to write your convertFrom method to convert a single item, but once you do, you can plug it in to the method above.
Does the above make sense?


text:
Q: Given the numerical succession 5, 55, 555, 5555, 55555... Are there numbers that are multiples of 495? If so, determine the lowest. I get the solution (555555555555555555) by using prime factorization. But I was wondering if there is a solution using modular arithmetic.

A: $495=5\cdot 9\cdot 11$
Every member of the sequence is divisible by $5$.
Only members of the sequence with some multiple of $9$ digits are divisible by $9$ (from the usual divisibility test of $9$).
Only members of the sequence with an even number of digits are divisible by $11$ (from the divisibility test for $11$, that the two alternating digit sums must differ by some multiple of $11$).
Therefore all members of the sequence with some multiple of $18$ digits are divisible by $495$

A: Here's a general solution with modular arithmetic that happens to solve this problem anyway, though using divisibility tests is faster.
Writing $555\dots5$ as $\frac59 (10^n-1)$, we want to know when $\frac{5}{9}(10^n-1) \equiv 0 \pmod{495}$, or when $10^n-1 \equiv 0 \pmod{891}$.
Since $891 = 81 \cdot 11$, by the Chinese remainder theorem, we have a solution when we satisfy both of:$$\begin{cases}10^n \equiv 1 \pmod{81}, \\ 10^n \equiv 1 \pmod{11}.\end{cases}$$
For the first equation, we can write $10 = 9+1$, and therefore $$10^n = (1+9)^n = 1 + \binom{n}{1}9 + \binom{n}{2}81 + \cdots.$$ Taking $10^n \bmod{81}$ leaves only $1 + 9n$ to worry about. So $10^n \equiv 1 + 9n \pmod{81}$, which is $1$ if and only if $9 \mid n$.
(This is taking a shortcut. The long way around, we know that $10^{72} \equiv 1 \pmod{81}$, because $\phi(81) = 72$. But this might not be the minimal solution, so we'd have to consider $10^d$ where $d$ is a divisor of $72$ to see which of these are $1\pmod{81}$.)
The second equation is easy. $10^n \equiv (-1)^n \pmod{11}$, so this is equal to $1$ if and only if $n$ is even.
For both of these to be true, we want $n$ to be a multiple of $18$, which unsurprisingly gives the same answer as straightforward divisibility tests.

A: We have $\frac{555..5}{495} = \frac{111..11}{99} = \frac{111..11}{9\cdot 11}$(with $n$ digits in the numerator). A number is divisible by 9 if and only if the sum of its digits is divisible by 9, therefore for $111...11$ to be divisible by $99$, $1 + 1 + 1 + ... + 1 + 1 = n\cdot 1 = n$ has to be divisible by 9. For a number to be divisible by 11, the sum of the digits with alternating signs: $1 - 1 + 1 - ... \pm 1 \equiv n \pmod{2}$ has to be divisible by 11, so $n$ has to be even. This leaves us with $111...11$ being divisible by $99$, and therefore $555...55$ being divisible by $495$ if and only if $n$ is divisible by $18$, which makes $n=18$ the lowest amount of digits.

A: As others have said, $495 = 5 \cdot 9 \cdot 11$. We can leverage this fact very nicely.
All multiples of 9 have digits that add up to a multiple of 9, so we can deduce that the number of 5s in the answer has to be a multiple of 9.
$11$ is a multiple of 11, and $1111$, or $11 \cdot 100 + 11$ is also a multiple of 11. You can keep going and conclude that every even number of ones can be a multiple of 11 (e.g. $11, 1111, 111111, ...$). If every even number of ones is a multiple of 11, an odd number of ones is $10 \cdot \text{an even number of ones} + 1$, which is $1 \text{ mod } 11$ and not divisible by 11.
Therefore, our number must have an even number of 5's which is also divisible by 9. The smallest number of 5's which satisfies this is 18, so the answer is $555555555555555555$.
I knew the fact about the even number of ones beforehand, as well as the nine divisibility rule, so this was easy to solve after those. Things like that are good to know in math competitions.


text:
Q: How to get theme from store and switch the app theme on react-admin? react-admin version: 3.8.4
I have a react-admin app and I'm trying to switch between light and dark themes.
Below you can see the Theme.js where I export the two objects with default theme overrides as described on docs. (https://material-ui.com/pt/customization/default-theme/)
export const darkTheme = {
palette: {
    type: 'dark'
},
overrides: {
    MuiAppBar: {
        colorSecondary: {
            backgroundColor: '#424242', //'#1e4c9a',
            color: '#fff'
        },
    },
    MuiButton: {
        textPrimary: {
            color: '#fff',
        }
    },
    MuiTypography: {
        colorPrimary: {
            color: '#fff'
        }
    },
    MuiDrawer: {
        paper: {
            paddingTop: '20px'
        }
    },
    MuiFilledInput: {
        underline: {
            '&:after': {
                borderBottomColor: '#bf9f00'
            }
        }
    },
    MuiFormLabel: {
        root: {
            '&$focused': {
                color: '#bf9f00'
            }
        }
    },
}
}

export const lightTheme = {
    palette: {
        type: 'light'
    },
    overrides: {
        MuiAppBar: {
            colorSecondary: {
                backgroundColor: '#2196f3',
                color: '#fff'
            },
        },
    },
}

I did also a customReducer as you can see below, called ThemeReducer.js
import { createMuiTheme } from '@material-ui/core/styles';

import { darkTheme } from '../../layout/Theme'
const Theme = createMuiTheme(darkTheme)

export default (previousState = Theme, action) => {
  if (action.type === 'SWITCH_THEME') {
    return action.theme;
  }
  return previousState;
}

Also to dispatch the state there is an action (ThemeAction.js):
export const switchTheme = (theme) => {
  return {
    type: 'SWITCH_THEME',
    theme
  }
}

To set the custom Reducer, as explained on the docs, I set on <Admin> the attribute custom Reducer as below:
import Theme from './store/reducers/themeReducer'

const App = () => {

  return (

      <Admin
        customReducers={{ theme: Theme }}
        layout={Layout}
        authProvider={login}
        dataProvider={dataProvider}
        loginPage={LoginPage}
        locale="pt"
        customRoutes={[
          <Route
            key="configuration"
            path="/configuration"
            title="Configurações"
            component={Configuration}
          />
        ]}
      > ...

To switch between the themes and set into the store I'm using this configuration page:
import React from 'react'
import { useSelector, useDispatch } from 'react-redux';
import Button from '@material-ui/core/Button';
import { switchTheme } from '../../store/actions/themeAction';
import { darkTheme, lightTheme } from '../../layout/Theme'
import { createMuiTheme } from '@material-ui/core/styles';

import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import { Title } from 'react-admin';

import './styles.css'

const Configuration = () => {
  const dispatch = useDispatch();
  const theme = useSelector(state => state.theme);

  const mainClass = 'configPage'

  return (
    <Card>
      <Title title="Configurações" />
      <CardContent className={mainClass}>

Selecione seu Tema:

          <Button
            variant="contained"
            className={theme.palette.type === 'light' ? 'active' : ''}
            onClick={() => dispatch(switchTheme(createMuiTheme(lightTheme)))}
          >
            Claro
        </Button>
          <Button
            variant="contained"
            className={theme.palette.type === 'dark' ? 'active' : ''}
            onClick={() => dispatch(switchTheme(createMuiTheme(darkTheme)))}
          >
            Escuro
        </Button>

      </CardContent>
    </Card>

  )
}

export default Configuration;

All this structure is working fine, I mean the global state theme is updating correctly, so the reducer is getting the clicked theme and switching the state.
The issue is that, as described on docs, to change the default theme we have to pass the new theme as an attribute on the tag <Admin> like: <Admin theme={theme}> </admin>
But the tag <Admin> is set into the App.js, and the redux context isn't above the App, so isn't possible to get the global theme state into it.
Then my question is how can I use the global theme state that I've created to pass as an Application theme.
I already tried passing  as Layout's parent as you can see below, but the theme not reflected on the application.
Layout.js
const MyLayout = (props) => {
    const theme = useSelector(state => state.theme)
    return (
        <ThemeProvider theme={theme}>
            <Layout
                {...props}
                appBar={AppBar}
                sidebar={Sidebar}
                menu={Menu}
                notification={Notification}
            />
        </ThemeProvider>
    )
};

App.js
...
    import Layout from './layout'

    const App = () => {

      return (

          <Admin
            customReducers={{ theme: Theme }}
            layout={Layout}
            authProvider={login}
            dataProvider={dataProvider}
            loginPage={LoginPage}
            locale="pt"
            customRoutes={[
              <Route
                key="configuration"
                path="/configuration"
                title="Configurações"
                component={Configuration}
              />
            ]}
          >
...

Appreciate any help.
Regards

A: I don't know your requirements, but maybe it's not necessary to store the theme in redux? You could use a solution using the react context api, like so:
type ThemeState = {
    theme: 'light' | 'dark',
    setTheme(theme: 'light' | 'dark'): void,
};

const StateContext = React.createContext<ThemeState>({
    theme: 'light',
    setTheme: () => {}
});

export const ThemeStateProvider = (props: { children: React.ReactNode }) => {

    const [theme, setTheme] = React.useState('light');

    return (

        <StateContext.Provider value={{
            theme,
            setTheme
        }}>
            {props.children}
        </StateContext.Provider>
    );
};

export const useThemeState = () => useContext(StateContext);

And use it like that:
// new root compontent that wraps App
const Root = () => (
    <ThemeStateProvider>
       <App />
    </ThemeStateProvider>
)

const App = () => {
    const {theme} = useThemeState();

    return <Admin theme={theme === 'light' ? lightTheme : darkTheme} ... />
}

const Configuration = () => {
    const {setTheme} = useThemeState();

    [...]

    return (
        [...]
        <Button onClick={() => setTheme('light')} />
        [...]
    );
}

Hope that works for you!


text:
Q: Whats the purpose of Cloning a Repository in Mercurial? I a xampp setup for php.
I have created a new repository at D:/xampp/htdocs/cart and i am using Mercurial along with Netbeans.
I am working on a locally and a lone developer.
The cart is installed and works at my localhost hXXp://localhost/cart
If I make a change to a clone repository, since it is not the directory which runs on the localhost, what makes it useful ? Everything resides on my local computer.
I am new to DVCS.
What purpose does Cloning a repository achieve ?

A: Cloning serves two basic purposes:

*

*It makes the idea of branching easier: It's simpler to clone the repository to work on a new feature on the side, while leaving the main repository as-is until you're done and able to pull and merge the changes back into the main repo. While Mercurial does allow to have several branches in the repository, the cloning approach is often easier.

*The second purpose is pretty much the same thing that happens when you make a checkout from a centralized VCS like Subversion. In DVCS, however, you don't just checkout whatever revision you want to work with, but the whole repository. This way, you don't depend on the "central" repository anymore. Since you're a lone developer on a single computer, this one isn't too important for you.
Either way, you can always push / pull changes from one repository to another, so the changes made in the clone aren't lost in your main repository. There's a good introduction to Mercurial at http://hgbook.red-bean.com/ .
Hope this helps.


text:
Q: Visual Studio Team Services Build Package Restore failing with project.json netstandard1.0 target I have recently updated my portable class libraries to target .NET Core, using project.json, and the new netstandard1.0 framework moniker.  My understanding is that this is supported now in Nuget 3.4.
I have the following project.json for my project:
{
  "supports": {},
  "dependencies": {
    "Microsoft.NETCore.Portable.Compatibility": "1.0.1",
    "NETStandard.Library": "1.6.0"
  },
  "frameworks": {
    "netstandard1.0": {}
  }
}

This builds great from Visual Studio 2015 Update 3.
However, when using VSTS (was Visual Studio Online) build, it now gives me the following error during the Package Restore step:
The project 'MyProject' does not specify any target frameworks in 'C:\a\1\s\MyProject\project.json'.

The command it shows executing is:
NuGet.exe restore "C:\a\1\s\Build.sln"  -NonInteractive -configfile "C:\a\1\NuGet\newNuGet.config"

Is this due to executing restore against a solution?  Or perhaps VSTS Build task is not yet using Nuget 3.4?

A: You could expand Advanced section, and select latest version of Nuget. As of October 2016 that was Nuget 3.5 rc2

A: I believe it has been resolved already and you use the valid version of NuGet, but you can also add a command line as a new build step, just after the NuGet Installer, and invoke dotnet restore (Tool: dotnet, Arguments: restore).


text:
Q: Sci Fi book about xenoarchaeology and a beetle like culture Circa late 60s, 70s, or early 80s, written in English.
A group of Xenoarchaeologists are exploring ruins on a distant planet. The inhabitants were beetle like. One researcher (mentally unstable?) builds a robot beetle so he can better understand the culture.  His conclusion was that they became 'bankrupt' because of inbreeding.

A: Total Eclipse, by John Brunner.

In 2020, an international space team, exploring Sigma Draconis, 19 light years from earth, discovers the remains of a highly advanced society that has left behind its most spectacular artifact; the largest telescope imaginable, carved & polished from a natural moon crater. Successive space crews determine that the native culture evolved & disappeared mysteriously after a mere 3000 years of existence. It's now 2028. Another mission reaches the planet with just one goal--to discover why the civilization disappeared--& with just one hope--that this knowledge will prevent the same thing from happening on earth.

I no longer have a copy, but I distinctly remember that line about going bankrupt.
If I recall correctly, the government didn't trust scientists and sent along a South American (?) army officer with a Stone Age mentality who continuously got in the way. After a chapter or two, however, he came round to seeing their point of view.


text:
Q: Dynamic memory in a struct So, my struct is like this:
struct player{
 char name[20];
 int time;
}s[50];

I don't know how many players i am going to add to the struct, and i also have to use dynamic memory for this. So how can i allocate and reallocate more space when i add a player to my struct?
I am inexperienced programmer, but i have been googling for this for a long time and i also don't perfectly understand structs.
This site doesn't accept my question so let's put some more text to this post

A: I assume you are programming in C/C++.
Your struct player has static-allocated fields, so, when you use malloc on it, you are asking space for a 20-byte char array a for one integer.
My suggestion is to store in a variable (or #define a symbol) the initial number of structures you can accept. Then, use malloc to allocate a static array that contains these structures.
Also you have to think about a strategy to store new players coming. The simplest one could be have an index variable to store last free position and use it to add over that position.
A short example follows:
#define init_cap 50

struct player {
    char name[20];
    int time;
};

int main() {
    int index;

    struct player* players;
    players = (struct player*) malloc(init_cap * sizeof(struct player));

    for(i = 0; i < init_cap; i++) {
        strcpy(players[i].name, "peppe");
        players[i].time = i;
    }

    free(players);

    return 0;
}

At this point you should also think about reallocating memory if the number of players you get a runtime exceeds your initial capacity. You can use:
players = (struct player*) realloc(2 * init_cap * sizeof(struct player));

in order to double the initial capacity.
At the end, always remember to free the requested memory.


text:
Q: In Vagrant, do I get boot_timeout error because my processor doesn't support Virtualization Technology (VT-d)? I'm trying to setup a development environment with Vagrant, but every time I run the command vagrant up in my terminal I get the following error message:

Timed out while waiting for the machine to boot. This means that
  Vagrant was unable to communicate with the guest machine within
  the configured ("config.vm.boot_timeout" value) time period.
If you look above, you should be able to see the error(s) that
  Vagrant had when attempting to connect to the machine. These errors
  are usually good hints as to what may be wrong.
If you're using a custom box, make sure that networking is properly
  working and you're able to connect to the machine. It is a common
  problem that networking isn't setup properly in these boxes.
  Verify that authentication configurations are also setup properly,
  as well.
If the box appears to be booting properly, you may want to increase
  the timeout ("config.vm.boot_timeout") value.

I've tried almost every solution I found on the internet, but the error still shows up. Some solution indicated that this may occur because my computer's processor doesn't support Virtualization, so I searched to find out if my processor support it or not and I found the next relevant specification (my processor's type and model is: Intel(R) Core(TM) i5-2410M CPU @ 2.30GHZ):

Do I get the above-mentioned error because my computer's processor doesn't support Virtualization Technology for Directed I/O (VT-d)? And is there any solution for that?


text:
Q: SQL Returning False $checkQuery = "SELECT Id FROM Events
                       WHERE Date = '$date'
                       AND VehId = $vehicleId
                       AND ((StartTime BETWEEN $timeOut AND $timeIn)
                       OR (EndTime BETWEEN $timeOut AND $timeIn))";
$checkResults = sqlsrv_query($conn, $checkQuery);
if (sqlsrv_num_rows($checkResults) > 0)
    {
        //do some stuff where the vehicle is already reserved.
    } else { // this always executes.
        var_dump($rowCounts, $date, $vehicleId, $timeOut, $timeIn);
        //insert the new reservation.
    }

//Var_dump - bool(false) string(10) "2016-11-01" int(184) float(9.5) float(11)
My SQL query continually returns false, Though I do not get my expects param to be 1 error? Always executes the else statement. Thus, something is wrong in my query, but below is my fiddle that shows it working as expected? My goal is to query the db, if any results come back, it doesn't insert a new record as the vehicle should already be reserved. Any help is appreciated!
http://sqlfiddle.com/#!3/a86be/6
SELECT Id FROM Events
     WHERE Date = '2016-11-01'
     AND VehId = 184
     AND ((StartTime BETWEEN 9.5 AND 11)
     OR (EndTime BETWEEN 9.5 AND 11))

I'd assume obvious, but I did verify that there is in fact a record in the DB that it should return.

A: From the official docs:

If a forward cursor (the default) or dynamic cursor is used, FALSE is returned.

So you need to specify a different cursor, this is done like this:
$checkResults = sqlsrv_query(
    $conn,
    $checkQuery,
    array(),
    array('Scrollable' => 'buffered'));


text:
Q: ENOENT error when trying to emulate Ionic made iOS app I am trying the Ionic framework.Everything ran smoothly but
when I tried to emulate an iOS app
macbook$ sudo ionic emulate ios

I got the following error:
Password:

....

** BUILD SUCCEEDED **

No target specified for emulator. Deploying to iPhone-6 simulator
ENOENT, no such file or directory '/Users/macbook/Library/Logs/CoreSimulator/9F89ED64-0748-4A65-92DF-611110E9D4C4/system.log'
Error code 1 for command: ios-sim with args: launch,/Users/macbook/Documents/workspaceionic/MyTestApp/platforms/ios/build/emulator/MyTestApp.app,--devicetypeid,com.apple.CoreSimulator.SimDeviceType.iPhone-6,--stderr,/Users/macbook/Documents/workspaceionic/MyTestApp/platforms/ios/cordova/console.log,--stdout,/Users/macbook/Documents/workspaceionic/MyTestApp/platforms/ios/cordova/console.log,--exit
Error: /Users/macbook/Documents/workspaceionic/MyTestApp/platforms/ios/cordova/run: Command failed with exit code 2
    at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:134:23)
    at ChildProcess.EventEmitter.emit (events.js:98:17)
    at maybeClose (child_process.js:735:16)
    at Process.ChildProcess._handle.onexit (child_process.js:802:5)

do you have any ideas about what could be wrong?
I'm using Yosemite and Node version is 0.12.7. iOS apps from XCode emulate fine
EDIT:
if I open the project with XCode and emulate it, it works.

A: no need for sudo
ionic emulate iOS
is the correct statement

A: There are apparently issues with running Node 0.12.x and Ionic. I'm running into this issue, myself, in my c9.io account... the dev environ wants 0.12.x, but Ionic requires 0.10.x. See Anil Singh's response in this thread for more information: With Node 0.12.2 and npm 2.7.4 ionic installation error on windows 7

A: It's a permission issue, it's resolve my problem,
sudo chown -R $(whoami) ~/Code/ionic-app/


text:
Q: Dirichlet problem with separation of variables Use separation of variables to find a nonzero solution for the following Dirichlet problem:
$\Delta u = 0$ in $\Omega$ with $u=0$ on $\partial \Omega$, where $\Omega = \{(x,y) \in \mathbb{R}^{2}: 0 < y < \pi\}$
$\Omega \in \mathbb{R}^{2}$ is open and bounded, u is harmonic on $\Omega$.
If we assume that $u \in C^{2}(\Omega) \cap C(\bar{\Omega})$, then according to the maximum principle for harmonic functions we have:
$0 = \min_{y \in \partial \Omega} u(y) \leq u(x) \leq \max_{y \in \partial \Omega} u(y) = 0$ $\hspace{3mm} \forall x \in \Omega \hspace{3mm}$ (since $u = 0$ on $\partial \Omega$)
Hence u(x) = 0 for all $x \in \Omega$.
I have the feeling that there does not exist a nonzero solution, because of this maximum principle. So how do I know that there does exist a nonzero solution and how can I find this solution. I think I need to assume that there exist a solution $u(x,y) = X(x) \cdot Y(y)$. Then $0 = \Delta u = u_{xx} + u_{yy} = Y(y) \cdot X''(x) + X(x) \cdot Y''(y)$. So $X''(x) + aX(x) = 0$ and $Y''(y) + b \cdot Y(y) = 0$ for some constants $a = a(y)$ and $b = b(x)$. And then solve these ODEs for $X(x)$ and $Y(y)$. So $u(x,y) = X(x) \cdot Y(y) = (c_{1} \cdot \cos(\sqrt{a}x) + c_{2} \cdot \sin(\sqrt{a} x)) \cdot (d_{1} \cdot \cos(\sqrt{b}y) + d_{2} \cdot \sin(\sqrt{b} y))$
And we know that $u = 0$ on $\partial \Omega$. So that means that $u(x,0) = 0$ and $u(x,\pi) = 0$.
And with these boundary values, I only find that $d_{1} = 0$.
So how to continue then?
And what does this Dirichlet problem tell is then about the maximum principle and what is wrong about my conclusion that $u(x) = 0$ for all $x \in \Omega$?

A: The domain $\Omega$ is unbounded, in particular you do not know whether the solution u attains a maximum, which is an essential condition for the maximum principle to be applicable.
As you already observed, with the separation of variables Ansatz $u(x,y) = X(x)\cdot Y(y)$, the following formulas are obtained:
$$
 X(x) = c_1  \cos(\sqrt{a}x) + c_2 \sin( \sqrt{a}x), \quad Y(y)=  d_2 \sin(\sqrt{b}y),
$$
where we used $d_1 = 0$ (due to boundary condition). Now observe that
$
 a := \frac{Y''(y)}{Y(y)} = -b,
$
assuming $b> 0$, we see that
$$
 X(x) = c_1 \cos(i\sqrt{b}x) + c_2 \sin(i\sqrt{b}x).
$$
At this point, we have found a complex solution, in order to find a real solution, set $z = \sqrt{b}x$ and use the identity
$
 \cos(iz) -i \sin(iz)  = e^z
$
(i.e. we have to choose $c_1 = 1, c_2 = -i$). Thus we arrive at
$
X(x) = e^{\sqrt{b}x},
$
and consequently
$$
 u(x,y) = e^{\sqrt{b}x} \cdot d_2 \sin(\sqrt{b}y).
$$
Since $u_{xx} = bu, u_{yy} = -bu$, we see that u is a solution.


text:
Q: Bootstrap & Internet Explorer 11 issues So I'm having a small formatting problem with my Internet Explorer 11.
Here is the picture from Google Chrome (THIS IS PERFECT):

Here is the picture from Internet Explorer 11

Here is the code:

.bottomRightBox {
  height: 170px;
  width: 310px;
  /* background-color: #4B92DB;
  border: 1px black solid; //BOTTOM RIGHT BOX BORDER */
}

#contactsPicture {
  align: left;
  valign: top;
  height: 98px;
  /* padding-top: 10px; //PADDING FOR CONTACT PICTURE */
}

#contactImg {
  width: auto;
  height: 148px;
}

.contactsPictureName {
  color: black!important;
  font-weight: normal!important;
  padding-left: 15px!important;
  padding-top: 2px;
}

#rightBottomHeading {
  float: right;
  clear: right;
  padding-right:176px;
  font-size: 18px!important;
  font-weight: bold!important;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Office 365 Contacts

NAME

PORTALHELP

Any input with CSS formatting and styling would be highly appreciated. Currently using Bootstrap 3.

A: Got it guys!
Thanks to Girdharilal and his attempt I was able to use:

.UserPhoto a {
  display: -ms-inline-flexbox;
}

which ended up working perfectly.

A: I would suggest a different approach to your display method.  Rather than relying on a bunch of custom css and float declarations, why not use the Grid for this situation?  Consider the following implementation:

.contactBox {
  padding-bottom: 1.5rem;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

This area is intentionally left blank.

Office 365 Contacts

          Name

          Name

          Name

          Name

In the above code we're relying more heavily on the Bootstrap 3.x Grid component as well as a few other utility classes.  An added bonus is that by relying more heavily on Bootstrap you have an opportunity to offer better responsive behavior.
It really only requires one custom line of CSS; .contactBox ... which is really only there to ensure that you have proper bottom padding without the need to re-iterate row or add line breaks.
You may need to expand the snippet to see how the layout can adjust depending on screen resolution.  Alternatively, you can view the same code via the following Bootply link: https://www.bootply.com/LK0cVLrCBm


text:
Q: How to start opennms? I installed opennms on RHEL6 operating....i have installed all dependencies and when i am running this command
/sbin/service opennms start

then the opennms is running but i am not able to open the opennms page on my web the adress that I have been using is:
http://192.168.1.15:8980/opennms/

can any one please help me regarding this.
I have already edited iptables and the id that i have given there is 192.168.1.00/24
I have also edited discovery-configuration.xml with the same ip.

A: Firstly, check that the OpenNMS service is bound to either all interfaces, or the interface you expect it to be bound to:
netstat -na | grep 8980

You should see something similar to the following, assuming a wildcard bind:
tcp        0      0 0.0.0.0:8980                0.0.0.0:*                   LISTEN      13504/java

Next, make sure that IPtables really isn't the culprit by checking the relevant logs (if you've configured IPtables to log, that is), or by temporarily disabling IPtables (after you've considered the security ramifications of doing so, i.e. whether or not you can accept the risk of being without a firewall for a minute or two).
I don't believe that OpenNMS Discovery has anything to do with your access problem, so ignore discovery-configuration.xml for the moment.


text:
Q: Представить число в виде суммы последовательных слагаемых Есть переменная a,
а может быть любым числом. Допустим a = rand()%10+1;
И надо найти все возможные варианты сложения.
Представить целое число a в виде суммы как минимум двух последовательных натуральных чисел.
Например:
10 = 1 + 2 + 3 + 4
24 = 7 + 8 + 9

Помогите найти и придумать алгоритм поиска. Спасибо.

A: Смотрите, всё не так сложно. Это простое диофантово уравнение.
Вспомним формулу суммы арифметической прогрессии (у нас разность d = 1, n — неизвестное количество слагаемых, a_1 — неизвестное первое слагаемое):
S = n * (2 * a_1 + (n - 1)) / 2

Отсюда 2S делится на n.
Дальше легко найти кандидатуры на n перебором как делители 2S. Например, для S = 10 это будут 2, 4, 5, 10, 20, n = 1 отбрасываем, у нас должно быть больше одного слагаемого. Для каждого из них находим 2S / n = 2 * a_1 + (n - 1), а потом и a_1 (у нас получится соответственно 4.5, 1, 0, -3.5, -9). Отбрасываем дробные результаты, и получаем ответы:
1 + 2 + 3 + 4
0 + 1 + 2 + 3 + 4
-9 + -8 + -7 + -6 + -5 + -4 + -3 + -2 + -1 + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10

Если нужно только натуральные числа, оставляем только варианты с a_1 > 0, это будет
1 + 2 + 3 + 4

Асимптотическая сложность: простейшее разложение на множители перебором до корня O(sqrt(n)), проверка каждого кандидата O(1).

A: Вот ещё одно решение. Оно, в сущности, основано на таком же принципе, что и у VladD, и даже имеет такую же асимптотическую сложность (хотя объяснение этого не тривиально): O(sqrt(a)).
Поскольку речь о натуральных числах, их легко представить себе по количеству некоторых предметов. Например, квадратиков. Итак, у нас есть N квадратиков и нам надо из них выложить фигуру вот такого вида:

Т. е. на треугольник и прямоугольник. Заметим, что общая сумма элементов в подобной фигуре состоит из треугольного числа и произведения двух натуральных чисел.
Что мы можем наверняка сказать о результате?

*

*a не больше T_t — это даёт условие завершения алгоритма

*r целое — это устраняет возможность более чем одного решения для каждого t
Алгоритм построчно описывать не буду, опишу важные части:

*

*Решение будет удовлетворять выражению a = T_t + (t+1)*r

*Подберите начальные данные: считаете ли вы 0 натуральным числом? Если нет, то вам может быть интереснее рассматривать числа от r + 1 до r + t (убрать верхний ряд зелёных квадратиков). Поскольку вам нужно как минимум два натуральных числа t будет сначала равно 1, как и T_t (вырожденный треугольник).

*Проверяйте, не делится ли a - T_t на t+1. Если делится — найдено решение: это числа от r = (a - T_t)/(t+1) до r + t.

*Каждый шаг алгоритма t увеличивается на 1, а затем T увеличивается на t.

*Алгоритм прекращается, как только a становится меньше T_t.

Анализ фигуры для каждого t это O(1): константное число операций. Проводится t раз. Какое для нашего алгоритма максимальное t? Минимальное из тех, для которых:
a < T_t
a < t^2 / 2 + t/2

T_t растёт квадратично при линейном росте a. Значит, число итераций асимптотически определяется функцией, обратной t^2 / 2 + t/2, и её асимптотика O(sqrt(a)).
Развлечения ради можете её вывести!

A: Код:
bool PrintFragments (unsigned num, unsigned max, unsigned& nTry, unsigned lvl){
   unsigned n = num;
   while (n){
      if (n <= max){
        bool found = false;
        if (n == num && !--nTry)
            found = true;
        else if (PrintFragments (num - n, n, nTry, lvl + 1))
            found = true;
        if (found){
            printf("%d ",n);
        if (!lvl)
            puts("");
        return true;
        }
    }
    --n;
  }
  return false;
}

void PrintNumFragmentsInfo (unsigned num){
  unsigned counter = 0;
  while (1){
    unsigned nTry = counter + 1;
    if (PrintFragments (num, num - 1, nTry,0))
        ++counter;
    else
        break;
  }
  printf("\n количество сумм = %d\n",counter);
}

int main (){
   int n;
   puts("Enter number");
   scanf("%d",&n);
   PrintNumFragmentsInfo (n);
   system("pause");
}


text:
Q: Exception in thread "main" java.lang.IllegalArgumentException: Invalid GraphDef I use java reload the tensorflow pb model. I put the model in the resource package(intellij IDEA). It works ok when I run it on my pc. But When I compile it to .jar and run it on another computer. it goes wrong as follows:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid GraphDef
at org.tensorflow.Graph.importGraphDef(Native Method)
at org.tensorflow.Graph.importGraphDef(Graph.java:130)
at org.tensorflow.Graph.importGraphDef(Graph.java:114)
at com.xunlei.algo.analysis.LstmSeqModel.<init>(LstmSeqModel.java:66)
at com.xunlei.algo.analysis.LstmSeqModel.main(LstmSeqModel.java:90)

My code is shown as follows:
InputStream is = LstmSeqModel.class.getResourceAsStream("/lstmSeq.pb");
int count = is.available();
System.out.println(count);
graphDef = new byte[count];
is.read(graphDef);
g.importGraphDef(graphDef);
sess = new Session(g);


text:
Q: Problema de Tipo array de n numeros pero el programa termina cuando el usuario no quiera escribir más números Desarrollar un programa que solicite leer n números y mostrarlos en el mismo orden introducido. Que el programa termine cuando el usuario no quiera escribir más números.
En el ejercicio creo que quiere decir que el programa termina cuando el usuario digite cualquier cosa menos un numero.
Hay alguna forma de hacerlo? Solo se que se desarrolla con array.
Lo que yo he intentado es hacer lo siguiente:
Pero no se que ponerle al numero de términos del array ni tampoco se como hacer para el programa termine.
package javaapplication66;

import java.util.Scanner;

public class JavaApplication66 {

    public static void main(String[] args) {
Scanner sn=new Scanner(System.in);

         for( int i=0;i>0;i++){
             double t[]=new double[];
       System.out.println("Digite numero");
       t[i]=sn.nextDouble();

       }
  }
 }
}

A: No sé si entendí bien tu pregunta pero intentaré ayudarte.
Si quieres introducir números lo harás con un for hasta n como tienes hecho pero no te acaba nunca por dos razones:
1.- El bucle que implementas es infinito por la razón 2  de tu condición del fori>0 y siempre será mayor a 0 en tu bucle, por eso nunca acaba.
2.-Y de la manera que lo tienes implementado, en cada iteración estas creando una array distinta.
Mira mi código:
public static void main(){
boolean sigue=true;  //para indicar si acabo o no.
double t[]=new double[]; //declaro mi array fuera del bucle.

for(int i=0;i<n && sigue;i++){
System.out.println("Introduce un número:");
int numeroLeido=sc.nextDouble();
if(numeroLeido== -1) sigue = false; //saldremos del bucle.
else t[i]=numeroLeido; //sino, introducimos el valor numeroLeido a nuestraArray.
} //acaba el for

//leemos el contenido de nuestra Array
for(int i=0;i<t.length;i++){
System.out.println(t[i]);
}

En mi código si introduces -1 se parará. Espero que te haya servido y lo hayas entendido.


text:
Q: ISOTOPE: Sort by a category and by date I'm using ISOTOPE and have 6 categories. Each category will have any number of posts.
I have a list of links to each category, when a category name is clicked (for example: Artists) I need all boxes within that artists category to be moved to the top and ordered by date, the most recent box displayed first.
In my JS file I have this:
$container.isotope({
    itemSelector : '.module',
    getSortData : {
      artists : function( $elem ) {
        return $elem.attr('artists');
      }
    }
  });

My HTML looks like this:

01/02/12

Link title

This code doesn't seem to sort it the way I want and haven't a clue how to adapt it, could someone help?

A: This is all I really needed to do:
getSortData : {
  blogs : function( $elem ) {
    var isBlog = $elem.hasClass('blogs');
    return (isBlog?' ':'') + $elem.find('.date').text();
  }
}

For the full answer check out this post: Isotope: Select and display .xx class at the top


text:
Q: Windows couldn't shutdown, then It starts without aero Yesterday I turned off my pc which has Windows 7 Ultimate 64-bit. It didn't turn off so I forced it off as it was getting late. Now I turn it on to find out that stuff like windows aero didn't load. Here's a screenshot:

Oh, and for those who will tell me to just switch themes:

I tried troubleshooting it, but we all know nothing good ever comes out.
Also, when I tried shutting it down today, it wouldn't.. It would just remove the GUI leaving only the desktop background and mouse pointer.
I've tried rebooting in safe mode, still the same (when I reboot from safe mode to normal mode)
I've also tried using a Windows Repair Disk... but the Startup repair utility didn't work, and the closest system restore point is at 13th September 2013, which is a bit far away considering that this problem began last night.
Thanks to anyone who will post helpful answers
Edit: I've changed my theme to Windows Classic, and now it's shutting down OK. I've also just run the Aero Troubleshooter again, to be able to post the results in case it might help, so here it is:

A: You should reboot you system in safe mode. Restart you computer and press F8 key before Windows logo appears
And choose safe mode press Enter Key.
I think You get aero now. If you get aero you should re-install your Graphics driver.


text:
Q: Adding mimetypes in servicesatck How would one add custom MIME types to a servicestack application?
I tried searching servicestack.net and peeking in the source code, but i seems that it is not a common requirement to change MIME types.

A: You can look at http://www.servicestack.net/ServiceStack.Northwind/vcard-format.htm for an example on how to use custom MIME types i.e. custom content-type.


text:
Q: How do I convert string value to a date format string strDateFrom;
string strDateTo;

CrystalDecisions.Shared.ParameterDiscreteValue DateValue = new CrystalDecisions.Shared.ParameterDiscreteValue();

if ((strDateFrom != "") && (strDateTo != ""))
{
    DateValue.Value = "(From: " + strDateFrom + " - " + strDateTo + ")";
}
else
{
    DateValue.Value = "(ALL DATES)";
}

A: You can use DateTime.Parse
string date = "2020-02-02";
    DateTime time = DateTime.Parse(date);
    Console.WriteLine(time);

Or use:
DateTime oDate = DateTime.Parse(string s);

A: In order to avoid formatting issue, I prefer using DateTime.ParseExact or DateTime.TryParseExact.
basically the difference between those methods and  DateTime.Parse is weather you know the date format of the string (and then you use  DateTime.ParseExact) or not (and then use DateTime.Parse).
You can read more about ParseExact and TryParseExact
EDIT:
Example code from the links:
 string dateString, format;
      DateTime result;
      CultureInfo provider = CultureInfo.InvariantCulture;

      // Parse date-only value with invariant culture.
      dateString = "06/15/2008";
      format = "d";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }

      // Parse date-only value without leading zero in month using "d" format.
      // Should throw a FormatException because standard short date pattern of
      // invariant culture requires two-digit month.
      dateString = "6/15/2008";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }

A: If you know the format used, you can try DateTime.ParseExact() or DateTime.TryParseExact():
  String text = "30/12/2013";

  DateTime result = DateTime.ParseExact(text, "d/M/yyyy", CultureInfo.InvariantCulture);


text:
Q: Form with two different nested models which exclude each other I have a form for one model with a couple of input boxes and one dropdown box where type (TypeA and TypeB) of the model can be picked. Let's say models are something like this:
// car has columns name and country
class Car < ActiveRecord::Base
end

// has columns a_property_1 and a_property2
class TypeAProperties < ActiveRecord::Base
    belongs_to :cars
end

// has columns b_property_1 and b_property2
class TypeBProperties < ActiveRecord::Base
    belongs_to :cars
end

After user opens form, by default there should be displayed fields for name, country, dropdown box with TypeA selected, a_property_1 and a_property2.
If user navigates to dropdown box and selects TypeB, a_property_1 and a_property2 should disappear from screen, and b_property_1 and b_property2 should appear on screen. So, TypeAProperties and TypeBProperties are created depending on selected value from drop down box. Car can have only one property, A or B.
Any ideas how to handle this situation? I am a little bit stuck with this. Thank you.

A: I believe you should do vise versa, so:
class Cars < ActiveRecord::Base
   belongs_to :car_type, polymorphic: true
end

and in type classes
class TypeAPropertySet < ActiveRecord::Base
   has_one :car, as: :car_type # or has_many
end

class TypeBPropertySet < ActiveRecord::Base
   has_one :car, as: :car_type # or has_many
end

Please refer to the document on the rails polymorphism. So then you be able to use Cars properties, along with the car_type in the form.


text:
Q: Nhibernate throws error No persister for: Mapping file:
<?xml version="1.0"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"  auto-import="true">
    <class name="PlayHibernate.Employee, PlayHibernate" lazy="false">
        <id name="id" access="field">
            <generator class="native"/>
        </id>
        <property name="name" access="field" column="name"/>
        <many-to-one access="field" name="manager" column="manager" cascade="all"/>
    </class>
</hibernate-mapping>

I tried setting the mapping file as a resource, but that just changes the error message to
"Unhandled Exception: NHibernate.MappingException: PlayHibernate.Employee.hbm.xml
(5,31): XML validation error: The element 'id' in namespace 'urn:nhibernate-mapp
ing-2.2' cannot contain text. ---> System.Xml.Schema.XmlSchemaValidationExceptio
n: The element 'id' in namespace 'urn:nhibernate-mapping-2.2' cannot contain tex
t."

A: The first error "No persister for..." was a consequence of not setting mapping file as an embedded resource.
The current error has something to do with your id definition. It looks like you have some text within your <id> definition. Maybe some unallowed whitespaces? Try to write it as:
<id name="id" access="field" column="uid" generator="native" />

Also if that doesn't help, try to use some other name than id for a field name. Maybe Id.

A: In visual studio remember change the property: "Compilation action" of your .hbm.xml file to : "Embedded resource"


text:
Q: Difference between $\sqrt{x^2}$ and $(\sqrt{x})^2$ According to my logic,
$$\large\sqrt{x^2} = x^{2\times \frac{1}{2}} = x = x^{\frac{1}{2}\times 2}={(\sqrt{x})}^2$$
But when I look at the graphs of these guys, they're totally different.
Edit: Complex answers are okay, if you know what I mean.

A: $f(x)=\sqrt{x^2}=|x|,$ so if $x\ge 0$, then $f(x)=x$. And if $x\lt 0$, then $f(x)=-x.$
On the other hand, $g(x)={\sqrt x}^2=x$ is defined only when $x\ge0.$
Hence, we know that $y=f(x)=\sqrt{x^2}$ is different from $y=g(x)={\sqrt x}^2.$

A: Since noone has (yet) pointed out where your logic went wrong,
the expression $a^b$ is not always well-defined : usually you need $b$ to be an integer or $a$ to be a positive real for it to make sense (also you need $b \ge 0$ if $a=0$) (you can define it in more cases but it is complicated enough like this)
So the identity $(a^b)^c = a^{bc}$ is often nonsense because it talks about things that don't exist or they both exist but are not the same.
However it is true when $a$ is positive or if both $b$ and $c$ are integers (and surely in some other complicated cases)
In your case $(x^\frac 12)^2$ is only well-defined for positive $x$ and for those $x$ we do have $(x^\frac 12)^2 = x^1$, while $x^1 = (x^2)^\frac 12$ for positive $x$ and not for negative $x$.

A: Notice that:
$$\sqrt{x^2} = |x|$$
And
$$\sqrt{x}^2 = x$$
But also notice that the domains are different:
$$\sqrt{x^2}: (-\infty, \infty)$$
And
$$\sqrt{x}^2 = [0, \infty)$$
Make sense now why the graphs would look different?

A: I think your confusion arrises from the idea that the $\sqrt{\cdot}$-fuction is the inverse function of $\cdot^2$. This is not exactly the case; you see $f(x)=x^2 $ does not really allow for an inverse function, because you can always find two distinct values $a_1$ and $a_2$ such that $(a_1)^2=(a_2)^2=x$ (exept maybe for the $0$-case). So there is in fact no "good" reason why we should have $$\sqrt{x^2}=\sqrt{x}^2,$$ because this kind of behaviour is something you would generally expect from functions and their inverse. And since $\sqrt{\cdot}$ is not a proper inverse function for $\cdot^2$ we should not be supprised that in general $\sqrt{x^2}\neq\sqrt x^2$.
For a more elaborate discussion on functions and their inverses, see this.

A: I think you want an answer allowing for the case of imaginary numbers.
Your are under the impression (under your logic) that $f\circ g(x) = g\circ f(x)$.
This is clearly not true in general, and not true in your case, even if, at first sight, case, $g$ is similar to the inverse of $f$.
But $g$ is NOT the inverse of $f$, for $f$ does not have any inverse, since $x^2$ is not injective, be it in real or imaginary fields...

A: Your equation reminds me of the following: Gift $=$ Present. It looks truthful, doesn't it ? But is it always ? Well, if both words are taken to be written in English, even then there's a glitch, since the second one has at least two completely different meanings, so, depending on its interpretation, the equation can be either true or false. But what if the two words are actually an entry in a German-English dictionary, instead of being one from an English thesaurus, as we previously suspected ? Then the equation is false, since the German word Gift means poison$(!)$. Now, a language is for a word what a domain of definition is to a function. So, what is the definition domain of your square root function ? If this domain is $\mathbb R^{^\mathbf+}$ then your equation is indeed true. And if not, then, as it has already been pointed out in the comment section, for $x\in$ R we have $\sqrt{x^2}=|x|$, and $\big(\sqrt x\big)^2=x$. For instance, $\sqrt{(-1)^2}=\sqrt1=1$, but $\Big(\sqrt{-1}\Big)^2=\big(\pm i\big)^2=-1$.

A: If by the radical symbol you mean the set-valued function that associates to each non-zero complex number $w$ the two complex numbers $z$ satisfying $w = z^{2}$, and if "squaring a set $A$" means "the set obtained by squaring each element of $A$", then for each complex $z$,

*

*$\sqrt{z^{2}} = \{\pm z\}$ by the difference of squares identity: For complex numbers $z_{1}$ and $z_{2}$, you have $z_{1}^{2} = z_{2}^{2}$ if and only if $z_{1} = \pm z_{2}$.

*$(\sqrt{z})^{2} = \{z\}$ from the definitions of $\sqrt{\phantom{z}}$ and squaring a set.

A: $\large\sqrt{x^2}$ the domain of it is $(-\infty,+\infty)$ because $x^2\ge0$ always,so $x \in $$ (-\infty,+\infty)$ and the range of the function is $[0,+\infty)$ since square root function always produces non-negative result(i.e., $\ge 0$) whereas,
${(\sqrt{x})}^2$ the domain of it is $[0,+\infty)$ since square root function accept only positive values including zero($\ge0$) and the range of it is $[0,+\infty)$ since square of any number is greater than zero($\ge0$)

A: In real numbers, square roots are defined for non-negative numbers only, and $$\sqrt{x^2}=\left(\sqrt x\right)^2.$$
In complex numbers, the principal square root can be defined to have its argument in $(-\frac\pi2,\frac\pi2]$, and for negative numbers, $\sqrt{x^2}=|x|=-x$, $\sqrt x^2=(i\sqrt{|x|})^2=-|x|=x$, so that
$$\sqrt{x^2}=-(\sqrt x)^2.$$


text:
Q: Practicing Interview Question, Find Largest sum Of Two Consecutive Numbers In An Array Java I found an interview practice question as stated in the title. Everything so far seems correct, however my if and else-if statements for comparing stored values of each sum are letting me down. If the largest sum is obtained from the FIRST TWO elements of the array, then it does not work. If they are anywhere else, then it does.
I thought I logically get why this is the case hence why I have an else-if statement which I thought would fix it. The answer found is 51, but this is incorrect. It should be the FIRST TWO (100+50). I feel like my logic is failing me and any guidance would be great!
import java.util.ArrayList;

public class Main { //Qn is to find the largest sum of two consecutive numbers in an array

    public Main() {}

    private static int sum;

    public static void main(String[] args) {

        int[] intArray = new int[]{100, 50, 0, 50, 1, 0, 0};
        ArrayList<Integer> sumArray = new ArrayList<>();
        int sum;
        int answer = 0;

        for (int i = 0; i < (intArray.length - 1); i++) {
            for (int j = 1; j < intArray.length; j++) {
                sum = intArray[i] + intArray[j];
                sumArray.add(sum);

            }
        }

        for (int temp = 0; temp < (sumArray.size()-1); temp++) {
            for (int temp1 = 1; temp1 < sumArray.size(); temp1++) {
                if(sumArray.get(temp) > sumArray.get(temp1)){
                    answer = sumArray.get(temp);
                }
                else if (sumArray.get(temp) < sumArray.get(temp1)) {
                    answer = sumArray.get(temp1);
                }

            }
        }
        System.out.println(answer);
    }
}

Actual answer = 51. Expected answer = 150.

A: That is a lot of code, and I'm not certain why you are comparing sumArray.get(temp) with sumArray.get(temp1) - you should compare with answer; but honestly, we can simplify this.
Start by initializing answer to the smallest possible value. Then iterate the array once and compare consecutive sums with the current answer. Like,
int[] intArray = { 100, 50, 0, 50, 1, 0, 0 };
int answer = Integer.MIN_VALUE;
for (int i = 0; i < intArray.length - 1; i++) {
    int sum = intArray[i] + intArray[i + 1];
    answer = Math.max(answer, sum);
}
System.out.println(answer);

If using Java 8+, you could simplify it further by using a lambda to map the array values and stream that into max(). Like,
int[] intArray = { 100, 50, 0, 50, 1, 0, 0 };
int answer = IntStream.range(0, intArray.length - 1)
        .map(i -> intArray[i] + intArray[i + 1])
        .max()
        .orElse(Integer.MIN_VALUE);
System.out.println(answer);

A: What you can do is create an IntStream with a range of 0 to the array length - 1 and then map the sum of values[index] and values[index + 1] and then find the max, otherwise return -1.
    private static int max(int[] values) {
        return IntStream.range(0, values.length - 1)
                .map(index -> values[index] + values[index + 1])
                .max()
                .orElse(-1);
    }


text:
Q: Is it possible to toggle display of earned/unearned badges? Every so often I like to take a break from answering question on SO so I'll visit the badges page and start putting in some effort towards the long-term grinds.  Things like Marshal or Proofreader are good examples.
I think it would be nice to have some sort of JavaScript buttons near the header of the page to toggle the display of: All Badges | Earned Badges | Unearned Badges.
If this has been discussed before I was unable to find it on meta.
EDIT: With the recent changes to the badge page which allows for filtering by type, hopefully this will have new interest.


text:
Q: How to update OS X when App Store is giving error: "Unable to verify software update.(700)"? I'm running OS X 10.13.6 on a MacBook Pro (15-inch, 2018).
App Store shows one available update, "The macOS High Sierra 10.13.6 Supplemental Update 2 for MacBook Pro (2018)".
Attempting to install update via the App Store GUI results in an error: "Unable to verify software update.(700)"
I've also tried installing the update via the terminal which gives the following output:
$ sudo softwareupdate --verbose -ia
Software Update Tool

Finding available software

Downloading macOS High Sierra 10.13.6 Supplemental Update 2 for MacBook Pro (2018)
Error downloading macOS High Sierra 10.13.6 Supplemental Update 2 for MacBook Pro (2018): Unable to verify software update.
Done.

Error downloading updates.

Subsequent CLI runs yield:
$ sudo softwareupdate --verbose -ia
Software Update Tool

Finding available software

Downloaded macOS High Sierra 10.13.6 Supplemental Update 2 for MacBook Pro (2018)
Installing macOS High Sierra 10.13.6 Supplemental Update 2 for MacBook Pro (2018)
Done.

Error installing updates.

I've tried deleting the App Store cache folder ~/Library/Caches/com.apple.appstore, but that didn't change anything.
How can I get the update to install?


text:
Q: Float:left e float:right em resoluções menores Eu tenho o componente 1 em float:left e o componente 2 em float:rigth, , porém o problema ocorre quando em resolução menores o componente 2 fica a baixo do componente 1 voltado pro lado direito e o componente um 1 voltado pro lado esquerdo.
Meu objetivo é que em resoluções menores o componente 2 ficar alinhado com o outro ao lado esquerdo.
Esclarecendo melhor o componente fica abaixo do outro, em resoluções menores um voltado pro lado esquerdo o outro pro lado direito.
Também lembrando que não posso dar float:left pros 2, se não vai ficar 1 abaixo do outro em resolução maiores.

A: Essa questão se deve ao fato de que a soma do tamanho dos dois elementos é grande demais para caber na largura da tela, e por isso há essa quebra de espaço. Já que seu problema está na exibição em uma tela de celular, eu sugiro que você use media queries para aperfeiçoar o seu sistema em relação a exibição na tela de celulares.

body {
  margin: 0;
}

.left {
  float: left;
  background-color: green;
}

.right {
  float: right;
  background-color: red;
}

@media only screen and (max-width: 480px) {
  .right,
  .left {
    display: block;
    float: none;
  }
}

    Left is the left choice :D

    Right is the right choice :3


text:
Q: Excel Pivot with "and" operator Not sure I've titled this intelligently, but here is what I've been trying to do. I think I have to rearrange the raw data I've been given to make it work, but...
I've been given a list with these columns: product feature, product family, customer, customer size, state.
(so customer A who has 5 product features in 2 product families is in the list five times)
I need to produce a pivot report of customers with the names of all product features they have regardless of the product families those features belong to-- but only for the customers who have at least one product in Family 1 and Family 2 and Family 3. Then if mgmt wants to look at it by size or state, they can go from there.
There are 50+ features in 20 or so families, so attempts at flattening it across more columns hasn't helped me so far.
Do I need to be doing this in a data model instead of just a plain pivot? Something else? I'll research any suggestions you have.

A: There may be better ways of doing it, but this is what I think. I would create 1 additional column where I would indicate if I want that row to be included in the pivot or not.

1 means that the row is included, 0 - the row is not included.
=IFERROR(IF(MATCH(1,($C$2:$C$11=C2)*($B$2:$B$11="fam1"),0)
           *MATCH(1,($C$2:$C$11=C2)*($B$2:$B$11="fam2"),0)
           *MATCH(1,($C$2:$C$11=C2)*($B$2:$B$11="fam3"),0),1),0)

This is an array formula, which is entered not with regular Enter, but a combination of Ctrl+Shift+Enter. Also, in the formula, "fam1", "fam2" and "fam3" must be changed with the family names that you need.
Then this column can be included in in the filters area of the pivot.


text:
Q: How to use the elements of a slice in bson.A using mongo-go-driver 0.2.0 How do I use a given slice to generate a bson.A? I need this to make dynamic queries.
I am upgrading from mongo-go-driver alpha to beta 0.2.0, and this has become a major change in my project since the API is different now.
https://godoc.org/github.com/mongodb/mongo-go-driver/bson
input := []string{"bar", "world"}
//expected output
bson.A{"bar", "world"}

A: Not sure if you ever found your answer, but I battled with this for an hour+ yesterday.
I'm not positive this will solve what you're asking. I assume you're trying to build a filter from your input. Ultimately I did not use a bson.A when I was trying to pass an array.
Situation: Trying to build a filter and one of the bson.D elements is an array.
I thought I needed to use bson.A.
My initial assumption:
return bson.D{
  {"uuid", request.Uuid},
  {"action", request.Action},
  {"resource", bson.D{{"$in", bson.A{resourceStrings}}}},
}

where resourceStrings is a slice of strings.
However this will ultimately build a filter that looks like
FILTER :  [ {resource [{$in [[Orgs::Organizations::1 Orgs::Organizations::* Orgs::Organizations Orgs::*]]}]}]
*Note that the $in method is looking for an array of arrays here.
What we want is:
FILTER :  [{uuid 80} {action UpdateOrganization} {resource [{$in [Orgs::Organizations::1 Orgs::Organizations::* Orgs::Organizations Orgs::*]}]}]
If we pass in a literal array of strings it will work...
return bson.D{
  {"uuid", request.Uuid},
  {"action", request.Action},
  {"resource", bson.D{{"$in", bson.A{"Orgs::Organizations::1", "Orgs::Organizations::*", "Orgs::Organizations", "Orgs::*"}}}},
}

After some trial and error I found that bson.D will directly accept the array.
ultimately I solved the issue thus
return bson.D{
  {"uuid", request.Uuid},
  {"action", request.Action},
  {"resource", bson.D{{"$in", resourceStrings}}},
}

Taking your example literally - if you're simply trying to marshal an array to a bson.A try:
bson.A{input}

A: So bson.A underlying type is []interface{},
I could just use append to it like a slice

A: Here is my code to delete multiple documents based on ID which are present in another collection.
We first collect all the IDs from one collection and add to a slice. Then we delete documents in another collection using DeleteMany()
I am showing the relevant code to keep the code clean.
Json
[
    {
        "id": "602607bcfdc0548bfebbd0c7",
        "subject": "SUBJECT",
        "system": "SYSTEM",
        "board": "BOARD",
        "series": "SERIES",
        "paper": "PAPER",
        "year": "2021",
        "month": "February",
        "question_hex_ids": [
            "602607bcfdc0548bfebbd0c4",
            "602607bcfdc0548bfebbd0c5",
            "602607bcfdc0548bfebbd0c6"
        ]
    }
]

Code

    var hexIDCollection []primitive.ObjectID
    database := db.Conn.Database("mydatabase")
    question := database.Collection("questions")

    //Iterating to collect IDs from paper
    for k, _ := range mystruct.question_hex_ids {

        // fetching all IDs and appending to slice
        ids := mystruct.question_hex_ids[k]
        hexID, err := primitive.ObjectIDFromHex(ids)
        if err != nil {
            fmt.Println("ObjectIDFromHex ERROR", err)
        }

        //Populating a slice of all the IDs
        hexIDCollection = append(hexIDCollection, hexID)
    }

    filter := bson.D{
        {"_id", bson.D{{"$in", hexIDCollection}}}, }

    deleteResult, err1 := question.DeleteMany(ctx, filter)
    if err != nil {
        fmt.Println("Question Deletion Error", err1)
    }

    fmt.Println("All questions Deleted: ", deleteResult)


text:
Q: csv parsing & search in java I have a CSV file which looks like this
"key,"id.attr.id","id.attr.id1","id.attr.id2","id.attr.id7","id.attr.arry","id.attr.arry1","id.attr.arry2","id.attr.arry5","id.attr.arry4"
// this header goes on for around next 600 field.

"1","0",,,"8",,,"8",,"8"
"2","3",,,"7",,,"7",,"7"
"3","4",,,"8",,,"8",,"8"
"4","5",,,"7",,,"7",,"7"
"5","4",,,"8",,,"8",,"8"
"6","3",,,"7",,,"7",,"7"
"7","4",,,"8",,,"8",,"8"
"8","5",,,"7",,,"7",,"7"
"9","3",,,"8",,,"8",,"8"
"10","6",,,"7",,,"7",,"7"

Now I'm trying to search through the content in such a way so that it will return the values
say for "id.attr.id" it will search for all the corresponding values.
the format of the result will be
"key","id.attr.id","id.attr.id7"
    "1","0","8"
    "2","3","7"
    "3","4","8"
    "4","5","7"
    "5","4","8"
    "6","3","7"
    "7","4","8"
    "8","5","7"
    "9","3","8"
    "10","6","7"

and also for "id.attr.arry"
Here is the code i'm trying.. but of no use.
public void run() {
    String csvFile = "/Users/file.csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {

        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] id = line.split(cvsSplitBy);
            int j=0;
            for ( j:id.size()){
                 if (id[1]=="id.attr.id"+j){
return true;
                     //don't know then how to check                     }
            else     {
                 int i=0;
                 }           }

        }

so my question is how to achieve this result?

A: Use a good quality CSV parser.  I am using Apache Commons CSV, OpenCSV and Univocity.
I can wholeheartedly endorse Univocity as its CSV parser is very fast.  Using it, you can select columns.

A: The core of your requirement is you need to build a lookup map between the columns you are looking for and their position in the row. Here's some code that demonstrates how.
public List<String[]> selectColumns(String[] csvFile, String... columns) {
    List<String[]> rows = new ArrayList<>();
    // Split the first row to get the column names.
    String[] columnNames = csvFile[0].split(",");
    // Build a map to get the column number from the name.
    Map<String, Integer> columnNumbers = new HashMap<>();
    for (int i = 0; i < columnNames.length; i++) {
        columnNumbers.put(columnNames[i], i);
    }
    // Put the title columns in.
    String[] colHeaders = new String[columns.length];
    for (int i = 0; i < columns.length; i++) {
        colHeaders[i] = columns[i];
    }
    rows.add(colHeaders);
    // Walk the rest of the file.
    for (int i = 1; i < csvFile.length; i++) {
        // Get and split the line.
        String[] values = csvFile[i].split(",");
        // Collect the required columns.
        String[] row = new String[columns.length];
        for (int j = 0; j < columns.length; j++) {
            // Look up the column number from the header map.
            row[j] = values[columnNumbers.get(columns[j])];
        }
        // Add the row.
        rows.add(row);
    }
    return rows;
}

public void test() {
    // In-line data for demonstration.
    String[] csvFile = new String[]{
        "key,id.attr.id,id.attr.id1,id.attr.id2,id.attr.id7,id.attr.arry,id.attr.arry1,id.attr.arry2,id.attr.arry5,id.attr.arry4",
        "1,0,,,8,,,8,,8",
        "2,3,,,7,,,7,,7",
        "3,4,,,8,,,8,,8",
        "4,5,,,7,,,7,,7",
        "5,4,,,8,,,8,,8",
        "6,3,,,7,,,7,,7",
        "7,4,,,8,,,8,,8",
        "8,5,,,7,,,7,,7",
        "9,3,,,8,,,8,,8",
        "10,6,,,7,,,7,,7"
    };
    List<String[]> selected = selectColumns(csvFile, "key", "id.attr.id", "id.attr.id7");
    for (String[] row : selected) {
        System.out.println(Arrays.toString(row));
    }

}

prints
[key, id.attr.id, id.attr.id7]
[1, 0, 8]
[2, 3, 7]
[3, 4, 8]
[4, 5, 7]
[5, 4, 8]
[6, 3, 7]
[7, 4, 8]
[8, 5, 7]
[9, 3, 8]
[10, 6, 7]

The suggestions to use a good CSV parser is a very good one - String.split(",") is very unreliable.


text:
Q: web application cart implementation for non-logged users I am working for implementing a spring-boot based shopping application, where a feature exist called 'add to cart' for product which works when users is only logged in. Meaning spring-boot back-end creates session when user logged in to make mapping to cart object.
I am trying to implementing a features like real world shopping application like amazon, where product can be added into 'cart' even user is not logged in. Then after user log-in user session can be managed / merged with previous non-logged user.
Can some please give me any typical design pattern idea in details or book reference or tutorial link where I can get details idea about such kind of implementation.

A: If user is anonymous, I would save cart on server and save cart ID in browser using a persistent cookie. When user logs in, server can retrieve the anonymous cart from its ID. Alternatively, you could store full cart in cookie.


text:
Q: How to set this code to open at specific times of the day? SO basically how do i do to set this to run at a specific time of the day ?
import winsound
from win10toast import ToastNotifier

def timer (reminder,seconds):
    notificator=ToastNotifier()
    notificator=ToastNotifier("Reminder",f"""Alarm will go off in (seconds) Seconds.""",duration=20
    notificator.show_toast(f"Reminder",reminder,duration=20)

    #alarm
    frequency=2500
    duration=1000
    winsound.Beep(frequency,duration)

if __name__=="__main__":
    words=input("What shall i be reminded of: ")
    sec=int(input("Enter seconds: "))
    timer(words,sec)

Could this be ? as i tried to write it but doesn t seem to work
import time
local_time = float(input())
local_time = local_time * 60
time.sleep(local_time)

A: Two possibilities from the top of my head:

*

*[Linux] Use cron job https://help.ubuntu.com/community/CronHowto

*[Any OS] Use scheduler https://schedule.readthedocs.io/en/stable/

*[Windows] Scheduling a .py file on Task Scheduler in Windows 10


text:
Q: OpenGL do stuff when player don't look I'm facing this kind of problem: I would like to do something, when player isn't looking. For instance, like in SCP, move monster towards player. My question is: How can I check if player does see an object?

A: Assuming the player is in control of the camera. The camera has a front vector. Using that front vector and the normal of the object, in this case the monster, you can find out whether he is looking or not.
You can take the dot product of the object normal and the front vector. If it is negative or equal to 0, the angle is perpendicular and the player can't see the object.