text:
Q: Notifications with Facebook Comment Box I've been reading through other related questions here, but I think they are even too advanced for where I am at with Facebook's coding and such...
I want to have a Facebook Comment box on my website. That is no problem and it works fine. I also want to be notified, on Facebook, when someone leaves a comment. I've tried numerous different things with the comment.create but I really don't have a clue what I am doing.
Can someone take me through this step-by-step and help me understand what I need to do? Here is what I've got:

A: WX, I have a Classifieds app on Facebook. I needed to create some notification to the owner of the advertisement also. I solved that with a simple way, after a comment I manipulate the response from FB with Ajax and Jquery:
FB.Event.subscribe('comment.create', function(response) {

    //Send an email with ajax

    $.ajax({
            type: "POST",
            url: "sendcommentemail.php?",
            data: "urlofpage=",
            beforeSend:  function() {
                $('#loading').show();

        },
            success: function(html){
                $('#loading').hide();
        },
            error: function(html){
        }
    });
});

good luck!

A: What you need is just add a friend in the app settings on the page as moderator.
He/she will get notification in their Facebook profile each time someone is commenting on your website.
Also, this tool is very handy and to be Favorited for people with developer accounts:
https://developers.facebook.com/tools/comments


text:
Q: Why is this matching not allowed in scala? I have to find if an element is inside a list using scala, and I am only allowed to use recursion. Why is the following code not working, as the match statement seems to be correct to me. My IDE gives me an error on all three case statements and it says type, mistmatch, boolean required.
def isInN(x: Int, l: List[Int]): Boolean = (l,l.head) match {
  case Nil,_ => false
  case _,x => true
  case _,_ => isInN (x,l.tail)
}

A: You're matching a tuple, so you need to use a proper tuple extractor. i.e. just add parenthesis:
def isInN(x: Int, l: List[Int]): Boolean = (l, l.head) match {
    case (Nil, _) => false
    case (_, x) => true
    case (_, _) => isInN (x, l.tail)
}

This compiles, but won't quite work like you want it to. l.head will throw an exception if the list is empty. And x within the match will eagerly match anything, so the last case can never be reached. To match against an identifier, you need to surround it with backticks, otherwise it will just be a placeholder matcher.
To use a similar pattern match without calling l.head, you can pattern match on the List itself:
def isInN(x: Int, l: List[Int]): Boolean = l match {
    case Nil => false
    case `x` :: _ => true
    case head :: tail => isInN (x, tail)
}

Though this is all trumped by contains in the standard collections library:
scala> List(1, 2, 3, 4).contains(2)
res5: Boolean = true

redpajama_set_name: RedPajamaStackExchange


text:
Q: Janusgraph troubles to understand how to manipulate data from gremlin query I'm trying to reconstruct the data retrieved with a gremlin query from a graph.
Precisely I'm having troubles finding an efficient way to manipulate the data that comes back.
The version of JanusGraph I'm using it's the 0.3.1 and it's running on Cassandra + ES, also it is configured with the ConfiguredGraphFactory. So I can create graphs dynamically.
I'm using gremlin javascript version 3.4.2 (the 3.3.3 doesn't work properly)
I built a little example to better explain what I mean.
The graph in this examples is created without a schema.
First of all, I'll connect to the graph using this functions:
const gremlin = require('gremlin');

const { Graph } = gremlin.structure;
const { DriverRemoteConnection } = gremlin.driver;

const __ = gremlin.process.statics;
const P = gremlin.process.P;

const GREMLIN_URL = "ws://localhost:8182/gremlin";
const GRAPH_NAME = "graphtest";

let connection;

function getTraversal() {
    const graph = new Graph();
    connection = new DriverRemoteConnection(GREMLIN_URL, { traversalSource: GRAPH_NAME });
    return g = graph.traversal().withRemote(connection);
}

function closeConnection() {
    if(connection && connection.close) connection.close();
}

Then I'll create some Vertices and Edges.
We'll have one User, two Institution and two 'trained' edges connecting the user to the institutions:
async function createVerticesAndEdges() {
    const g = getTraversal();
    const userV = await g.addV('user').property('name', 'Emily').property('identityId', '1234').next();
    console.log('user', userV);
    const institutionV = await g.addV('institution').property('name', 'University of California').property('identityId', 'CA83').next();
    console.log('institution', institutionV);
    const institutionV2 = await g.addV('institution').property('name', 'University of Illinois').property('identityId', 'IL847').next();
    console.log('institution2', institutionV2);
    const trainedE = await g.addE('trained').property('title', 'MS in Computer Science').property('grade', 'B')
        .from_(__.V().has('identityId', '1234')).to(__.V().has('identityId', 'CA83')).next();
    console.log('trained', trainedE);
    const trainedE2 = await g.addE('trained').property('title', 'Political Science').property('grade', 'A')
        .from_(__.V().has('identityId', '1234')).to(__.V().has('identityId', 'IL847')).next();
    console.log('trained2', trainedE2);
    closeConnection();
}

Then, let's say I want to retrieve all the trainings that a user took, and I'd also like to have the name of the institution where the training was taken.
So the query I run is this:
async function getUserTrainings() {
    const g = getTraversal();
    const result = await g.V()
        .hasLabel('user')
        .has('identityId', '1234')
        .as('u').outE()
        .hasLabel('trained')
        .inV()
        .path()
        .unfold()
        .where(P.neq('u'))
        .toList();
    closeConnection();
    console.log(result);
}

and I get this output:
[
    Edge {
    id: { relationId: 'odxqw-3b4-27th-38o'
        },                                                                                alber@DESKTOP-8CVHP91 MINGW64 ~/Ref    label: 'trained',
    outV: 4288,
    inV: 4200,
    properties: {}
    },
  Vertex { id: 4200, label: 'institution', properties: undefined
    },
  Edge {
    id: { relationId: 'odxco-3b4-27th-3ao'
        },
    label: 'trained',
    outV: 4288,
    inV: 4272,
    properties: {}
    },
  Vertex { id: 4272, label: 'institution', properties: undefined
    }
]

This is not bat, I could use the vertices ids and the edges inV to reconstruct the relations and return the data as I wanted it, but the problem is, as you can see, that this query doesn't return the properties. So it's kinda useless.
But then, looking through the gremlin docs I found the valueMap() step, so I can slightly edit the previous query like this:
async function getUserTrainings() {
    const g = getTraversal();
    const result = await g.V()
        .hasLabel('user')
        .has('identityId', '1234')
        .as('u').outE()
        .hasLabel('trained')
        .inV()
        .path()
        .unfold()
        .where(P.neq('u'))
        .valueMap(true)
        .toList();
    closeConnection();
    console.log(result);
}

to get this output:
[
    Map {
    EnumValue { typeName: 'T', elementName: 'id'
        } => { relationId: 'odxqw-3b4-27th-38o'
        },
    'title' => 'Political Science',
    EnumValue { typeName: 'T', elementName: 'label'
        } => 'trained',
    'grade' => 'A'
    },
  Map {
    'name' => [ 'University of Illinois'
        ],
    EnumValue { typeName: 'T', elementName: 'id'
        } => 4200,
    'identityId' => [ 'IL847'
        ],
    EnumValue { typeName: 'T', elementName: 'label'
        } => 'institution'
    },
  Map {
    EnumValue { typeName: 'T', elementName: 'id'
        } => { relationId: 'odxco-3b4-27th-3ao'
        },
    'title' => 'MS in Computer Science',
    EnumValue { typeName: 'T', elementName: 'label'
        } => 'trained',
    'grade' => 'B'
    },
  Map {
    'name' => [ 'University of California'
        ],
    EnumValue { typeName: 'T', elementName: 'id'
        } => 4272,
    'identityId' => [ 'CA83'
        ],
    EnumValue { typeName: 'T', elementName: 'label'
        } => 'institution'
    }
]

So, apart from the fact that the data returned it's not at all clear (I mean, what is that "typeName: 'T'" that's the same for every vertex?), now I do get back the properties, but I loose the outV and inV on the edges and I'm unable to reconstruct the data the way I need. (understand which vertex is connected by which edge).
I guess that I could just use the first query without the valueMap() step, and then for each and every vertex and edge I get back, will do another query to retrieve the properties using the ids.
And this could be ok for a simple situation like this, but I don't think it would be really efficient for queries that could concern hundreds of vertices and edges.
So the final question is: what is the most efficient way to reconstruct the data from a path, including vertices and edges properties?

A: I'll just go to what I perceive as the heart of your question as I think the direct answer to that might clarify away the other sub-questions:

let's say I want to retrieve all the trainings that a user took, and I'd also like to have the name of the institution where the training was taken

gremlin> g.V().has('user','identityId', '1234').
......1>   outE('trained').
......2>   project('institution','title','grade').
......3>     by(inV().values('name')).
......4>     by('title').
......5>     by('grade')
==>[institution:University of California,title:MS in Computer Science,grade:B]
==>[institution:University of Illinois,title:Political Science,grade:A]

One side question that I thought could use some clarification:

what is that "typeName: 'T'" that's the same for every vertex?

T is an enum value in Gremlin and represents some core structural properties of graph elements, specifically label and id.


text:
Q: Can reindex time be reduce when boosting is changed in Sunspot I am trying to fine-tune the column boost in Sunspot. However it is said that every time I change the search index block in model I need to reindex for it to take effect. However reindexing takes 20 minutes.
Since boosting/weight of a column should be store separately from fulltext information itself, is it possible to reduce this reindex time (or do I need to reindex that at all?)

A: You would probably be best served to insert your boosting information in the qf parameter at search time.
For Sunspot, if you're talking about the boost in this context:
searchable do
  text :title, :boost => 2
end

Then the advice to reindex doesn't quite apply. That particular boost option is indeed applied at query time via the Solr qf parameter.


text: Q: Can't type after starting chrome extension debugger I'm trying to debug my chrome extension, but once I open the debugger, all keyboard extensions are captured by the debugger or the main chrome window, and I can't type in my extension popup. If I don't open the extension debugger, it works fine. Any ideas how to get around this?


text:
Q: Open/close div toggle and click outside div This post looks like duplicate, but I think is not. Now you can click Show box and show red box, if you want close this box, click outside.
Question: How close this red box on click again Show box text except click outside. And how change css style after click e.g. change font-size Show box after click

var myApplication = angular.module('myApp', []);
myApplication.directive('hideLogin', function($document){
  return {
  restrict: 'A',
  link: function(scope, elem, attr, ctrl) {
   elem.bind('click', function(e) {
      e.stopPropagation();
    });
    $document.bind('click', function() {
        scope.$apply(attr.hideLogin);
     })
    }
  }
});

myApplication.controller('hideContainer',function ($scope){
    $scope.openLogin = function(){
        $scope.userLogin = true;
   };
     $scope.hideLoginContainer = function(){
        $scope.userLogin = false;
   };
 });
body {
    position:relative;
}

.loginBox {
    z-index:10;
    background:red;
    width:100px;
    height:80px;
    padding:10px;
    position:absolute;
}

  Show box

A: instead of using multiple $scope for achieve something like this you can use a single $scope variable, take look at code snippet.

var myApplication = angular.module('myApp', []);
myApplication.directive('hideLogin', function($document){
  return {
  restrict: 'A',
  link: function(scope, elem, attr, ctrl) {
   elem.bind('click', function(e) {
      e.stopPropagation();
    });
    $document.bind('click', function() {
        scope.$apply(attr.hideLogin);
     })
    }
  }
});

myApplication.controller('hideContainer',function ($scope){
     $scope.userLogin = true;
     $scope.hideLoginContainer = function(){
        $scope.userLogin = true;
    };
 });
body
{
position:relative;
}
.loginBox
{
z-index:10;
background:red;
width:100px;
height:80px;
padding:10px;
position:absolute;
}

  Show box

A: To be able to hide the box on click on it, use $scope.userLogin = !$scope.userLogin condition.
To change it's css style, e.g. font-size, use ng-class. If userLogin variable is true, it will add fontSize class into it, changing it's font-size.

var myApplication = angular.module('myApp', []);
myApplication.directive('hideLogin', function($document) {
  return {
    restrict: 'A',
    link: function(scope, elem, attr, ctrl) {
      elem.bind('click', function(e) {
        e.stopPropagation();
      });
      $document.bind('click', function() {
        scope.$apply(attr.hideLogin);
      })
    }
  }
});

myApplication.controller('hideContainer', function($scope) {
  $scope.openLogin = function() {
    $scope.userLogin = !$scope.userLogin;
  };
  $scope.hideLoginContainer = function() {
    $scope.userLogin = false;
  };
});
body {
  position: relative;
}

.loginBox {
  z-index: 10;
  background: red;
  width: 100px;
  height: 80px;
  padding: 10px;
  position: absolute;
}

.fontSize {
  font-size: 30px;
}

  Show box

A: You could rename openLogin() to toggleLogin() and change the function accordingly to
 $scope.toggleLogin = function(){
        $scope.userLogin != $scope.userLogin;
    };

That will toggle the box when you click on the link.
For the CSS part, use ng-class to conditionaly sign a class to the element if userLogin ==true


text:
Q: Open Google Play using alert confirm button Can you explain me how to launch the Google Play app using the alert confirm button?
Here's the code:
let confirm = this.alertCtrl.create({
  title: 'Nouvelle mise a jour disponible',
  message: 'Version ameliorer de eLahiya disponible, voulez vous la telecharger?',
  buttons: [
    {
      text: 'Plus tard',
      handler: () => {
        console.log('Disagree clicked');
      }
    },
    {
      text: 'Mise a jour',
      handler: () => {
        console.log('Agree clicked');
        window.open("play.google.com/store/apps/details?id=<package_name>", '_system', 'location=yes')//
      }
    }
  ]
});
confirm.present();

I want my app to open my app's page on the playstore, how to do it?

A: Ionic native has a plugin to open an app's page in the market place. Here it is cordova-plugin-market
Use this command to install this plugin,
 ionic plugin add cordova-plugin-market
 npm install --save @ionic-native/market

Usage,
import { Market } from '@ionic-native/market';

constructor(private market: Market) { }

...

this.market.open('your.package.name');

A: this works perfectly for me:
window.open('market://details?id=your.package.name', '_system');

This is for Android though. For others:
IOS: itms-apps://itunes.apple.com/app/<appId>
Amazon: amzn://apps/android?p=<appPackageId>

Let me know if it works for you. Look into cordova-plugin-market as an alternative if that does not work.


text:
Q: Can *any* program task be expressed without state? This is a theoretical question, but after many years of programming in what I now realize is "normal" imperative technique, using C++ mainly, I've discovered this other world of functional programming, which I stumbled upon accidentally while casually learning JavaScript.
This has led me to wonder if you could technically replace any complete state-oriented program with a different implementation that is purely functional and without state?
It's an intriguing idea and I must admit that there is a clarity and elegance in functional programming that has really blown my mind.

A: Short answer: yes. According to Wikipedia, the equivalence of lambda calculus to Turing machines as an universal model of computation was shown 1937 by Alan Turing. The computational model of a Turing machine is what you typically have in mind when talking about imperative or stateful programming, and lambda calculus is a mathematically formalization of "pure functional programming".
It is conjected that every effective model of computation is able to carry out the same calculations as a Turing machine, and vice versa. This is called Church-Turing thesis. This conjection, however, cannot be proven, because of the more or less intuitive term "effective model of computation" (perhaps someone will invent a new model in the future?)

A: In whatever dynamic system, the "state" is what make your present to be influenced by your past or future (the arrow of time is not a mathematical issue, just a physical constrain).
Whether you have something to "remember" or that depends on what you did, you have a state.
A system with no state is not "dynamic": it is just a combinatorial function. That may not have a state, but -to produce different results- need a state to be somehow supplied.
Now, depending on the computational model you refer to, a state can be represented explicitly (in the form of variable) or implicitly (in the form of "return addresses").
when you do fna(fnb(x)) you are giving a state to fnb that in turn will produce a state for fna. This is due to the fact that x exist before fnb is called (so, it comes from it's own "past").
It's not a matter of "state exisit" or "state don't exist". It's a mater of "I care" or "I don't".

A: State means the ability to respond to a present stimulus in an manner that depends on past stimuli, not just based on the present stimulus.
Purely functional programs are just functions. Thus for practical applications the purely functional program inputs a pair (old_state * present_stimulus) and outputs a pair (new_state * present_response). An external, stateful "looper" is needed to wait for the next stimulus and propagate the state.
A purely functional program doesn't intrinsically have state, and -can't- be used for practical applications directly.
Thus no state-oriented program can be replaced with a different implementation that is purely functional and without state.

A: You can avoid explicit mutable state as long as you don't have to interact with the outside world.
In JavaScript in order for you program to actually have an effect beyond taking up processor cycles, you have to modify the Dom or the Window object, and these API's are stateful. But I suppose you could create a wrapper which passed the Dom and Window objects as parameters to the JavaScript code, and then received a new Dom/Window as output. This would isolate the JavaScript code from mutable state.
Of course you are still relying on state, since the browser window and DOM is stateful by nature. Any interactive application is inherently stateful, but you can still structure your code in such away as to minimize explicit state.
A different question is if it is a good idea. Even Haskell, which is a pure functional language by design,  includes the 'state' monad, which allows you to simulate mutable state. This shows that explicit mutable state sometimes really is a desirable pattern.

A: Think about how you would implement a "state machine" in a programming language without state.
You could probably actually do it but you would end up using function names as storage.
Ending up with gobblyday gook like:
if (sm.atBegining()) sm.start() else if (sm.done()) sm.stop() ) else sm.progress()


text:
Q: view tags of a docker image from index.docker.io? How does one view what tags are available for a docker image on index.docker.io before pulling? Using sudo docker pull debian will get me all the tags associated with debian which I don't need.

A: As of today the Docker registry exposes this in the index. See, for example, the Ubuntu base image tags which shows each tag and the filesystem contents of each layer. Via the API:
$ curl https://index.docker.io/v1/repositories/ubuntu/tags
[{"layer": "9cd978db300e27386baa9dd791bf6dc818f13e52235b26e95703361ec3c94dc6", "name": "latest"}, {"layer": "9cc9ea5ea540116b89e41898dd30858107c1175260fb7ff50322b34704092232", "name": "10.04"}, ...

A: Found what I wanted with this How to pull a single image from any docker repository?
docker pull <image_name>:<tag>
Example: docker pull debian:stable


text:
Q: Barplots overlapping with blank subplot in Matplotlib I am trying to make two subplots as a row in matplot lib.
Here is my code
fig, (ax1, ax2) = plt.subplots(1,2)

ax1 = plt.bar(x="Topic", height='perc', data=df1)

ax2 = plt.bar(x="Topic", height='perc', data=df2)

What is happening is that the barplots overlap eachother and leave col1 empty.
How can I fix this


text:
Q: How do I make Excel return the most frequent value in one cell? I have a single cell which contains a long list of numbers, delimited by a comma and a space.
Some of the numbers are repeated, and I want to know which number is repeated the most.
The function MODE doesn't work and seems designed to work on a range where every value is in its own cell.
Example of what I need
Cell with numbers
123, 456, 456

Most frequently repeated value
 456

A: If your values are numbers like you show:
=MODE.SNGL(FILTERXML(""&SUBSTITUTE(A1,",","")&"","//b"))

the ""&SUBSTITUTE(A1,",","")&"" creates an xml string.  Then FILTERXML(...,"//b") returns the array of numbers.  Then MODE.SNGL returns the largest repeating item.

If text or a mix:
=INDEX(FILTERXML(""&SUBSTITUTE(A1,",","")&"","//b"),MODE.SNGL(MATCH(FILTERXML(""&SUBSTITUTE(A1,",","")&"","//b"),FILTERXML(""&SUBSTITUTE(A1,",","")&"","//b"),0)))

This time we use Match to return an array of numbers(where it matches the first match, in the below case the would be 1,2,2)  The MODE_SNGL then returns the 2 to the INDEX.

A: Try this short User Defined Function:
Public Function splitt(s As String) As Variant
    Dim mx As Long, i As Long, j As Long, mxkp As Long
    arr = Split(s, ", ")
    mx = 0
    mxkp = 0
    splitt = arr(0)
    For i = 0 To UBound(arr)
        v = arr(i)
        mx = 0
        For j = 1 To UBound(arr)
            If v = arr(j) Then mx = mx + 1
        Next j
        If mx > mxkp Then
            mxkp = mx
            splitt = v
        End If
    Next i
End Function


text:
Q: switch from 64-bit long mode to 32-bit compatibility mode on x64 I want to switch from 64-bit long mode to 32-bit compatibility mode (and back) in a UEFI boot application.
Changing bit L in the code segment descriptor seems not enough.
What are the other steps? Is there an example?

A: You cannot switch in 32bit mode in UEFI. Even if you switch the CPU and reboot the machine the UEFI will blow up! Because the rest of the UEFI firmware (BIOS) expects x64 mode. There is only one way is to create a 32bit virtual machine that will run 32bit applications. That's exactly what 64bit Windows does running 32bit apps.


text:
Q: What does this IE specific code do? I was looking at an article on how to detect focus in a browser window. Here's the demo page.
I'm confused as to what this conditional does.
if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}

I assume that document.onfocusin is an Internet Explorer equivalent of window.onfocus. But I don't understand what the conditional is doing:
if (/*@cc_on!@*/false) { // check for Internet Explorer

Isn't this just a comment, which simplifies the expression to if(false)?

A: As per this link, the @cc_on statement allows IE to render something that other browsers are not. They call this, "conditional compilation".

It is strongly recommended that you use the @cc_on statement in a comment, so that browsers that do not support conditional compilation will accept your script as valid syntax:
An @if or @set statement outside of a comment also activates conditional compilation.

Therefore, IE will read the first condition of your code as !false, but every other browser will read it as false.
A warning, though:

Conditional compilation is not supported in Internet Explorer 11 Standards mode and Windows Store apps.


text:
Q: Derivation of Morris's Algorithm I am following the derivation of Morris's algorithm given here:
https://algorithms.wikischolars.columbia.edu/file/view/scribe1.pdf/604615257/scribe1.pdf
On page 3
They calculate $E[2^{X_n}]$
and in the second line and third line of the derivation they show:
$\Sigma_i 2 Pr[X_{n-1}= i-1] + \Sigma_i 2^i Pr[X_{n-1}= i] - \Sigma_i Pr[X_{n-1}= i]$
$= E[2^{X_n-1}]+1$
The middle term of the second line gives the first term in the third line, but how to the remaining two terms in the second line sum to one?
Thanks
Baz

A: Note that $\sum_{i=0}^{\infty} Pr(X_{n-1}=i-1) = Pr(X_{n-1} \text{ something between -1 and} \infty ) = 1$. So first term evaluates to 2 and similarly last term evaluates to -1. which gives us what we want.


text:
Q: Getting user to login, then checking if someone is logged in already I'm horrible at security so I was curious if you guys had any ideas. I recently wrote an application in Python that I will be selling to select people. The information on the application is private (not incredibly so, I just need a minimal solution). How could I have a user login to the application (from a MySQL database), then have the program check is someone is logged in already under those credentials. Here is a basic flow:

*

*User opens the EXE (cx_freezed python file)

*Program asks user for their login (from a MySQL database)

*Program checks if someone is already logged in using that info

*If someone is logged in, don't let them log in. If someone isn't, log them in.

I have absolutely no idea where to start with this, any suggestions/directions to point me?

A: *

*Don't be a Dave and roll your own security system. Use an existing one if you can

*This shouldn't have anything to do with your database. If you happen to persist session info to the db, that's fine, but your session-management should be in-memory

*Basically you should have a list of authenticated users in memory somewhere in application state. if authenticatedSessions.get($username) != null then deny

*Concurrent Session Control is a PITA for users. Example: You login just before leaving work, then get in your car, try to login from your mobile, and now you can't. Consider allowing 2 concurrent sessions, or keep the timeout short
Spring Security (Java) has this feature. It's open source so you could "gain inspiration" it: http://docs.spring.io/autorepo/docs/spring-security/current/reference/htmlsingle/#ns-concurrent-sessions


text:
Q: PHP simple debugging ways I would like to debug PHP code and see what is going on with the data being processed in on of the integrations.
What is the easiest way to debug this .php file (without using complex features Magento/ZendDesk/Plugins environment setup)??
I imagine something like :

*

*Setting debug points in the code that output .log files

*Setting alerts that can be seen in the Chrome Dev tools

Thanks

A: Outputting values
When you need a simple way to debug programs and you have no other options, you can usually output values. Sometimes this means doing a var_dump or logging a whole series of events.
It's useful to have debug logging in your program. In PHP, you can use various loggers to log debug messages. When the program is run in debug mode or the log level is set to debug, these messages will end up in your stdout, stderr, or log files. The logs will fill up pretty quickly in "debug mode," so you only want to turn it on temporarily. But I'm getting ahead of myself here. Let me backup to some simple ways to output values.
Dumping variables to stdout
The var_dump function is one way to see what's happening in your PHP program. It'll dump a variable value to stdout. There are other functions you can use for debugging through outputs. Here are a few and how they'll help you:

*

*var_dump ($var)) dumps the variable type and value to stdout.

*print_r ($var) prints the variable value in human-readable form to stdout.

*get_defined_vars() gets all the defined variables including built-ins and custom variables (print_r to view them).

*debug_zval_dump ($var) dumps the variable with its reference counts. This is useful when there are multiple paths to update a single reference.

*debug_print_backtrace() prints a backtrace that shows the current function call-chain.

*debug_backtrace() gets the backtrace. You can print_r, log it to a file, or send it to a logging endpoint asynchronously.

Here's sample code that exercises each of these useful debugging functions:
<?php
$myVar = "hello world!";

var_dump($myVar);
print_r($myVar);

$allVars = get_defined_vars();
print_r($allVars);
debug_zval_dump($allVars);

function sayHello($hello) {
    echo $hello;
    debug_print_backtrace();
}

sayHello($myVar);
?>

These functions are a quick way to debug your PHP code. Each function has a purpose and can be useful for debugging.

*

*error_reporting sets the level of logging. E_NOTICE is useful during development since it will tell you about defects such as unassigned variables.

*display_errors tells PHP if and where to display error messages.

*display_startup_errors should only be used when debugging.

*log_errors and error_log work together to send errors to a log file. Do this in production rather than displaying them to end users.

The PHP manual spells out these settings in more detail and provides more information I could ever fit in this section. But even with the best logging settings, you still need to monitor for errors.
Monitoring error logs
It's one thing to log errors—that's almost a given. It's a whole other thing to take action when errors are logged. First, you have to know about the errors. Unless you have all day and night to hover over the logs, you will not know when something bad is happening!
The best thing you can do is send your PHP logs to a service that will handle a few key things for you:

*

*Log aggregation You want to see all your logs in one place. If you can centralize your logs and metrics across instances, that's even better! You'd be able to spot trouble wherever it happens.

*Alerting There's nothing better than automation. If you're a programmer, you know what I mean! You'll want to automate almost anything if you can. Alerting is a way to send alerts automatically to a group email (better than an individual for continuity) when there's a problem. This can be a server issue or errors hitting your logs. It should be configurable and you should have control over the configuration.

*Traces in your logs What's a trace? It's not just a stack dump that lets you see what was going on when an error happened. It's also a way to track performance, which is often a sign or a cause of a bug.

*Deduplication of log entries When a bug causes an error, it can fill up the logs pretty quickly. Just combing through the logs with hundreds or thousands of the same entry is a showstopper. Deduplication takes away the pain!

Stepping through code
Now we will talk about debugging by stepping through code. This is what many of us developers think of when we see "debugging." It's a common way to debug code (remove defects that cause errors). With a web app or website, debugging is often two-pronged.
Once notified about an error that's been logged, we can debug if needed. With enough detail in the logs, this should be easy. We might not even have to use a debugger. Often, the less use one, the better. But if you do, here's how to tackle that!
PHP debugging tools
You can debug PHP using one of many debugging tools to attach a debugger client. PhpStorm works with debug utilities like Xdebug and ZendDebugger.
The debug server setup is the same, but each client (IDE or CLI) will have a slightly different setup. See, the debug server (a Zend extension) opens a port, and the client communicates with the server through that port. It's just a matter of configuration and installing the right components.
Hope this helps.


text:
Q: Use pre-signed url to get objects I'm trying to get the objects in AWS S3 by listObjects but I need to do this with a pre-signed url.
The following code gives me the objects:
$objects = $s3Client->listObjects([
   'Bucket' => $bucket,
   'Prefix' => $prefix
]);

The problem is that I need to do it with a presigned url. I get the url with following:
$cmd = $s3Client->getCommand('ListObjects', [
    'Bucket' => $bucket,
    'Prefix' => $prefix
]);
$request = $s3Client->createPresignedRequest($cmd, '+20 minutes');
$url = (string)$request->getUri();

And I retrieve the objects when accessing the URL through the browser but I need to get objects in PHP instead of a link to them. How do I do that?

A: $s3Client = Aws::createClient('s3');
$result = $s3Client->getObject(array(
   'Bucket' => $bucket,
   'Key'    => $path
));
$metadata = $result->get("@metadata");
$statusCode = $metadata["statusCode"];
if ($statusCode == 200) {
    header("Content-type: text/image");
    header("Content-Disposition: attachment; filename=".$path);
    header("Pragma: no-cache");
    header("Expires: 0");
    return $result['Body'];//echo $result['Body'];
}


text:
Q: jQuery ui modal window causes gray line I wanted to change the color of the window surrounding the modal alert-popup in jQuery UI.
So I changed it; .ui-widget-overlay { background: white
But for some weird reason, a gray line with the previously existing color, shows up in the middle of the screen. I haven't been able to select the element with the Chrome debugger, nor have I been able to find it's class in the jQuery-ui css-file. See image.
Anyone know what could be causing this?

A: Fixed this. For some reason, my jquery-ui.css file had two .ui-widget-overlay classes defined. Added the background-color as in Williams example to the other class and it worked.


text:
Q: Need help in reading an xml file I have created an xml folder under res and placed myxml.xml in xml folder.
res/xml/myxml.xml
I want to read the description according to the id number. How can I achieve that?
Please help.
myxml.xml is like this;
<?xml version="1.0" encoding="utf-8" ?>
<Books>
  <Number id ="1">
    <Description>This is childrens book.
    </Description>
  </Number>
  <Number id = "2">
    <Description>This is about cooking.
   </Description>
</Books>

Here is the code I am working with (but doesn't seems to be doing anything)
try{
        XmlPullParser xpp = getResources().getXml(R.xml.myxml);
                while(xpp.getEventType() != XmlPullParser.END_DOCUMENT){
            if(xpp.getEventType() == XmlPullParser.START_TAG){
              if(xpp.getName().equals("Description")){

                  show1.setText(" " + xpp.getAttributeValue(1));
              }
            }
        xpp.next();
         }
        }
        catch(Throwable t){

        }

A: For what you're trying to achieve here, I'd recommend using javax.xml.xpath. Taken from the example on that page, adapted to your XML file (the XPath here will get the description of Number with id attribute of 2):
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "//Number[@id='2']/Description";

try {
    InputSource inputSource = new InputSource(activity.getResources().openRawResource(R.raw.myxml));
    Node node = (Node) xpath.evaluate(expression, inputSource, XPathConstants.NODE);
    String description = node.getTextContent();
} catch (Exception e) {
    Log.d("ParseException", e.toString());
}

I've updated the example slightly to load the InputSource from a resource input stream. To do this it looks like you'll need to put your xml file in the res/raw folder rather than res/xml (based on this answer: problem loading and parsing xml from resources). I also had to do project > clean to get this to work.
You'll probably also want to handle the parse exception error in a slightly better way!

A: How will it even work when activity has null in it.. u r doin null.getResources();

A: you can use this, I am sure that this help you
XmlResourceParser pars = res.getXml(R.xml.myxml);
while (pars.getEventType() != XmlResourceParser.END_DOCUMENT) {
    if (pars.getEventType() == XmlResourceParser.START_TAG) {
              if(pars.getName().equals("Number")) {
                   int id = pars.getAttributeIntValue(null, "id", 0);
              }
        }
    pars.next();
}
pars.close();

in your Xml you have forgotten to put / in your Number tag
<Number id ="1" />

use this link to understand XmlResourceParser, it is evry easy to use
http://www.anddev.org/using_xmlresourceparser_to_parse_custom_compiled_xml-t9313.html

A: The reason it isn't working is because you are calling xrp.getName() method when your current eventType is XmlPullParser.TEXT.
According to the documentation:

public abstract String getName()
For START_TAG or END_TAG events...If
  the current event is not START_TAG,
  END_TAG, or ENTITY_REF, null is
  returned.

I would create a Stack<String> to hold the names of the element I am currently on.  When I get to a start tag, I would push the name to the top, and when i hit an end tag, I would pop the name off the top.  This way, when I am in a text element, I would know the whole xPath of my current location.

A: I noticed in your example the XML appears to missing the closing </Number> tag where the id attribute is equal to "2".  Its possible a formatting error such as this may be causing your error.

A: I wouldn't use XPath for this, the XMLResourceParser-class was meant to do that (tutorial).

A: The problem is that you can't access APK resources like they're on the path, because they're compiled into your application. If you want to access a resource directly, try this:
InputStream inputStream = context.getResources().openRawResource(R.xml.myxml);
InputSource inputSource = new InputSource(inputStream);

You may need use move the XML file into the res/raw/ folder and use R.raw.myxml to access it instead.

A: You most likely have an unexpected situation and your program throws an exception and dies.
Find the printed stack trace and add it to your question.  This will most likely tell you why.  A very common reason is to have uninitialized variables which you then try to invoke a method on giving a NullPointerException.

A: I don't think any of your "if" condition is getting satisfies. Return a string that is not empty and see if that gets displayed. If it does, then re-look at your logic for getEventsFromAnXML method.


text:
Q: WPF Open file dialog embedded in a window In my WPF application, on a button click, a modal window opens and several functionalities inside the window involve selecting a file. I don't want to open yet another window to select a file. Can I somehow embed a file browser within the existing window?

A: You can definetly create your own dialog. Take Microsoft Expression for example, where dialogs are all custom controls and styled to match expression dark theme.

A: Since you are associating with a file on the fly, you really only have 2 options to my knowledge. The first is to utilize the built in FileDialog from .NET to select the file.  The second is to create a display/dialog/etc that recreates that functionality using System.IO.Directory and some display elements.


text:
Q: Edit part of a div created using .createElement in js rather than duplicating the whole line Im making a rock paper scissors game using js and html. Right now I'm having an issue with displaying the computers random choice. I created the text that appears purley through js with the .createElement method and it partially works. Right now this is what I'm getting:

I don't want to add a new line every time the player clicks a button. I just want to update the part with the orange box around it:

I have looked online for solutions but couldn't make sense of the solutions so any help with this would be greatly appreciated.

const getComputerChoice = () => {
  let optionsArray = ["rock", "paper", "scissors"];
  let randomNumber = Math.floor(Math.random() * optionsArray.length);

  let compChoiceText = document.createElement("div");
  compChoiceText.className = "font-light text-white text-4xl";

  compChoiceText.innerHTML = `

      Computer chose: ${optionsArray[randomNumber]}

`;
  document.getElementById("text-output-container").appendChild(compChoiceText);
};

const choice = document.querySelector(".buttons");
choice.addEventListener("click", (event) => {
  getComputerChoice();
});
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>ROCK PAPER SCISSORS</title>
  <meta name="description" content="" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="stylesheet" href="" />

      <button class="w-80 bg-cyan-500 shadow-lg shadow-cyan-500/50 text-white rounded text-6xl hover:bg-blue-500 hover:shadow-blue-500/50">
          ROCK
        </button>
      <button class="w-80 bg-cyan-500 shadow-lg shadow-cyan-500/50 text-white rounded text-6xl hover:bg-blue-500 hover:shadow-blue-500/50">
          PAPER
        </button>
      <button class="w-80 bg-cyan-500 shadow-lg shadow-cyan-500/50 text-white rounded text-6xl hover:bg-blue-500 hover:shadow-blue-500/50">
          SCISSORS
        </button>

A: instead of creating the element every time, creare it once in the html and edit it evertime the user clicks

const getComputerChoice = () => {
  let optionsArray = ["rock", "paper", "scissors"];
  let randomNumber = Math.floor(Math.random() * optionsArray.length);
  // edit here
  let compChoiceText = document.getElementById("computer-response");

  compChoiceText.innerHTML = `

      Computer chose: ${optionsArray[randomNumber]}

`;
  document.getElementById("text-output-container").appendChild(compChoiceText);
};

const choice = document.querySelector(".buttons");
choice.addEventListener("click", (event) => {
  getComputerChoice();
});
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>ROCK PAPER SCISSORS</title>
  <meta name="description" content="" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="stylesheet" href="" />

      <button class="w-80 bg-cyan-500 shadow-lg shadow-cyan-500/50 text-white rounded text-6xl hover:bg-blue-500 hover:shadow-blue-500/50">
          ROCK
        </button>
      <button class="w-80 bg-cyan-500 shadow-lg shadow-cyan-500/50 text-white rounded text-6xl hover:bg-blue-500 hover:shadow-blue-500/50">
          PAPER
        </button>
      <button class="w-80 bg-cyan-500 shadow-lg shadow-cyan-500/50 text-white rounded text-6xl hover:bg-blue-500 hover:shadow-blue-500/50">
          SCISSORS
        </button>

A: Figured it out. Each time the getCompChoice function was called I was creating a new div so all I needed to do was create the div once then edit the  variable.

let compChoiceText;

const getComputerChoice = () => {
  let optionsArray = ["rock", "paper", "scissors"];
  let randomNumber = Math.floor(Math.random() * optionsArray.length);
  if (!compChoiceText) {
  compChoiceText = document.createElement("div");
  compChoiceText.className = "font-light text-white text-4xl";
  }
  console.log(optionsArray[randomNumber]);

  compChoiceText.innerHTML = `

      Computer chose: ${optionsArray[randomNumber]}

`;
  document.getElementById("text-output-container").appendChild(compChoiceText);
};

const choice = document.querySelector(".buttons");
choice.addEventListener("click", (event) => {
  getComputerChoice();
});
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>ROCK PAPER SCISSORS</title>
  <meta name="description" content="" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="stylesheet" href="" />

      <button class="w-24 h-fit bg-cyan-500 shadow-lg shadow-cyan-500/50 text-white rounded text-md hover:bg-blue-500 hover:shadow-blue-500/50">
          ROCK
        </button>
      <button class="w-24 h-fit bg-cyan-500 shadow-lg shadow-cyan-500/50 text-white rounded text-md hover:bg-blue-500 hover:shadow-blue-500/50">
          PAPER
        </button>
      <button class="w-24 h-fit bg-cyan-500 shadow-lg shadow-cyan-500/50 text-white rounded text-md hover:bg-blue-500 hover:shadow-blue-500/50">
          SCISSORS
        </button>


text:
Q: Solution of a homogenous differential equation with constant coefficients. I was reading this Wikipedia article. I tried to adopt the same method that they used to solve the following diffrential equation:
$$y\frac {d^2(y)}{dx^2}+{(\frac {dy}{dx})}^2+y^2=0$$
Putting $y=e^{rx}$ and then taking out $e^{2rx}$ outside with $2r^2+1$ inside. Solving for $r$ we get $y=e^{\frac{ix}{\sqrt 2}}$ or $y=e^{-\frac{ix}{\sqrt 2}}$ and when we combine both results as one and apply euler form of complex number we get $$y=a\cos {\frac{x}{\sqrt 2}} + b\sin {\frac{x}{\sqrt 2}}$$ but when I used Wolfram Alpha (computational software)  to verify my solution by plugging in the solution into the diffrential equation I don't get $0$ but $1$.
I am not able to identify what I did wrong. It would be very nice if you could help me with identifying my mistake. Thanks a lot.

A: Your equation is not linear...
$$y\frac {d^2(y)}{dx^2}+{(\frac {dy}{dx})}^2+y^2=0$$
$$\color {red} {y''y+(y')^2}+y^2=0$$
$$ \color {red}{(y'y)'}+y^2=0$$
$$ (2y'y)'+2y^2=0$$
$$((y^2))''+2y^2=0$$
Substitute $u=y^2$
$$u''+2u=0$$
This is linear....
$$r^2+2=0 \implies r=\pm i\sqrt 2$$
$$\implies u=c_1\cos(\sqrt 2 x)+c_2 \sin ( \sqrt 2 x)$$
$$\boxed {y^2(x)=c_1\cos(\sqrt 2 x)+c_2 \sin ( \sqrt 2 x)}$$

Another method is
$$y'=\frac {dy}{dx}=p $$
And
$$y''=\frac {dp}{dx}=\frac {dp}{dy}\frac {dy}{dx}=pp'_y$$
The equation becomes
$$pp'y+p^2+y^2=0$$
Note that $(p^2)'=2pp'$
$$\frac 12 (p^2)'y+(p^2)+y^2=0$$
Substitute $u=p^2$
$$  u'+2\frac uy=-2y$$
Its linear of first order...

A: Let $$v(y)=\frac{dy(x)}{dx}$$
then $$2\frac{dv(y)}{dy}v(y)+\frac{2v(y)^2}{y}=-2y$$
Now let
$$u(y)=v(y)^2$$
then
$$\frac{du(y)}{dy}+\frac{u(y)}{y}=-2y$$
Can you proceed?

A: If you look sharp enough, the first two terms have the form of a product derivative. Indeed $(yy')'=yy''+(y')^2$. This in turn is the derivative of the square, so that in the end the ODE is equivalent to
$$
(y^2)''+2(y^2)=0
$$
which is an oscillation equation for $u=y^2$ with solutions $$y^2=u=A\sin(\sqrt2 x+\phi).$$ As these sinoids also take negative values, the solution for $y$ has some sudden stops.
Or in initial conditions:
$$
y(x)^2=y(0)^2\cos(\sqrt2 x)+\sqrt2y(0)y'(0)\sin(\sqrt2 x)
$$
so that the square root with the correct sign is
$$
y(x)=y(0)\sqrt{\cos(\sqrt2 x)+\sqrt2\frac{y'(0)}{y(0)}\sin(\sqrt2 x)}.
$$


text:
Q: Suspend Sub-Process in .NET? I wrote a small daemon application in .NET last year that basically launches a Minecraft server, and provides a web based GUI to manage it. It does other things such as restart the process if it crashes, and other useful functions.
Our company recently heard of a french hosting company that had setup their servers in a way that when the last player disconnected, the server would shutdown until another player joined. Now, I have been thinking about how this might be possible, and wanted to see what the thoughts on it were. My daemon can already tell how many players are connected, so that is not an issue.
My psuedo thought process is...

*

*Last Player disconnects from server

*Daemon takes over listening on the server port for connections

*Upon incoming connection, save the connection packet data and restart the server sub-process

*Pass the save connection on to the Minecraft java process

I can't really figure out how to handle the last step yet, but that is the best solution I have come up with. Any thoughts or suggestions?

A: Perhaps you'll have more players wanting to connect at once, so you might have problems with that approach (cuz i'm guessing your server won't start instantaneously).
You should have a daemon waiting for connections and putting them on a queue or something, until the server starts, and feed it then, the connections (or connection packets or whatever). After the server is started, and all connections have been forwarded to it, get your daemon to "stop" (a.k.a die or stop clogging the port)
Hope this helps.

A: You can not "save" a TCP network connection and then redirect it to a different process. The only way to implement this would be to let your tool act as a proxy server that accepts all connections and sends all data to the server running on a different port.
In such a set-up you could start the server upon the first incoming connection.
The only other solution would require direct read access to the network interface the way e.g. is used by Wireshark/Pcap library. They you would be able to detect TCP SYN packets and start the server when they are coming in.


text:
Q: "I've got a place at college, so do I" Is the sentence "I've got a place at college, so do I" grammatically correct? if yes, what does "so do I" add in the meaning?

A: Grammatically correct, but there's something wrong. "So do I" would be expected from a different person responding to the first part of the sentence, or "so I do" might be said by someone with a particular speech pattern (I associate it with the UK more than the US, for some reason). One person would not say the entire sentence, it wouldn't make sense.


text:
Q: How to retrieve compound fields like address using Bulk API? Attempting to retrieve address fields (such as BillingAddress on Account) via Bulk API gives an error:

Failed to process query: FUNCTIONALITY_NOT_ENABLED: Selecting compound
  data not supported in Bulk Query

Sure enough, the Bulk API docs say:

Bulk API can't access or query compound address or compound geolocation fields.

Is there really no way to access address and geolocation data via the Bulk API?

A: There is a clue in this help page on compound fields:

Compound fields can't be included in Bulk queries. Use the individual field components to access or update field values.

It turns out that you can use the component fields like so:
SELECT BillingStreet, BillingCity,
       BillingState, BillingCountry, BillingPostalCode,
       BillingLatitude, BillingLongitude
FROM Account

A: In fact, you can safely remove compound fields from your export as they're read only and updatable only by its component fields.
Look for "Address" or "Geolocation" type fields, remove them from your select/query and voila.
For Account, in my case I removed ShippingAddress, BillingAddress and a custom geolocation field.


text:
Q: Regex - Match any sequence of characters except a particular word in a URL I want to match a URL that contains any sequence of valid URL characters but not a particular word. The URL in question http://gateway.ovid.com and I want to match anything but the word 'gateway' so:

*

*http://abc123.ovid.com - would match

*http://abc.123.ovid.com - would match

*http://abc-123.ovid.com - would match

*http://fdfsffdfs.ovid.com - would match

but

*

*http://gateway.ovid.com - would NOT match

Something like the following:
^http://([a-z0-9\-\.]+|(?<!gateway))\.ovid\.com$

but it doesn't seem to work.

Update: Sorry forget to mention the language, it's C#.NET

A: Your regex is almost correct except the extra '|' after '+'. Remove the '|'
^http://([a-z0-9\-\.]+(?<!gateway))\.ovid\.com$


text:
Q: Running Node app through Grunt I am trying to run my Node application as a Grunt task. I need to spawn this as a child process, however, to allow me to run the watch task in parallel.
This works:
grunt.registerTask('start', function () {
  grunt.util.spawn(
    { cmd: 'node'
    , args: ['app.js']
    })

  grunt.task.run('watch:app')
})

However, when changes are detected by the watch task, this will trigger the start task again. Before I spawn another child process of my Node app, I need to kill the previous one.
I can't figure out how to kill the process, however. Something like this does not work:
var child

grunt.registerTask('start', function () {
  if (child) child.kill()
  child = grunt.util.spawn(
    { cmd: 'node'
    , args: ['app.js']
    })

  grunt.task.run('watch:app')
})

It appears that:

*

*Even though I store the spawned process in a variable outside of the function context, it does not persist, so the next time the start task is run, child is undefined.

*child has no kill function…

A: Take a look at grunt-nodemon which handles a lot of the headaches related to spawning a child process.

A: This is because grunt-contrib-watch currently spawns all task runs as child processes. So the variable child is not within the same process context. Fairly soon, grunt-contrib-watch@0.3.0 will be released with a nospawn option. This will let you configure the watch to spawn task runs within the same context and would make your above example work.
Take a look at this issue for a little more information:
https://github.com/gruntjs/grunt-contrib-watch/issues/45


text:
Q: Can't ping postgres pod from another pod in kubernetes I created one busy pod to test db connection by following yaml
pod.yaml
kind: Pod
apiVersion: v1
metadata:
  name: marks-dummy-pod
spec:
  containers:
    - name: marks-dummy-pod
      image: djtijare/ubuntuping:v1
      command: ["/bin/bash", "-ec", "while :; do echo '.'; sleep 5 ; done"]
  restartPolicy: Never

Dockerfile used :-
FROM ubuntu
RUN apt-get update && apt-get install -y iputils-ping
CMD bash

I create service as
postgresservice.yaml
kind: Service
apiVersion: v1
metadata:
 name: postgressvc
spec:
 type: ClusterIP
 ports:
 - port: 5432
   targetPort: 5432

Endpoint for created service as
kind: Endpoints
apiVersion: v1
metadata:
 name: postgressvc
subsets:
 - addresses:
     - ip: 172.31.6.149
   ports:
     - port: 5432

Then i ran ping 172.31.6.149 inside pod (kubectl exec -it mark-dummy-pod bash) but not working.(ping localhost is working)
output of  kubectl get pods,svc,ep -o wide
NAME                                       READY   STATUS    RESTARTS   AGE     IP             NODE              NOMINATED NODE   READINESS GATES
pod/marks-dummy-pod                        1/1     Running   0          43m     192.168.1.63   ip-172-31-11-87   <none>           <none>

NAME                       TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE     SELECTOR
service/postgressvc        ClusterIP   10.107.58.81     <none>        5432/TCP         33m     <none>

NAME                         ENDPOINTS           AGE
endpoints/postgressvc        172.31.6.149:5432   32m

Output for answer by P Ekambaram
kubectl get pods,svc,ep -o wide gives
NAME                            READY   STATUS    RESTARTS   AGE    IP             NODE              NOMINATED NODE   READINESS GATES
pod/postgres-855696996d-w6h6c   1/1     Running   0          44s    192.168.1.66   ip-172-31-11-87   <none>           <none>

NAME                    TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE    SELECTOR
service/postgres        NodePort    10.110.203.204   <none>        5432:31076/TCP   44s    app=postgres

 NAME                      ENDPOINTS           AGE
endpoints/postgres        192.168.1.66:5432   44s

A: So problem was in my DNS pod in namespace=kube-system
I just create new kubernetes setup and make sure that DNS is working
For new setup refer to my answer of another question
How to start kubelet service??

A: postgres pod is missing?
did you create endpoint object or was it auto generated?
share the pod definition YAML
you shouldnt be creating endpoint. it is wrong. follow the below deployment for postgres.
apiVersion: v1
kind: ConfigMap
metadata:
  name: postgres-config
  labels:
    app: postgres
data:
  POSTGRES_DB: postgres
  POSTGRES_USER: postgres
  POSTGRES_PASSWORD: example
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: postgres
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
        - name: postgres
          image: postgres:11
          imagePullPolicy: Always
          ports:
            - containerPort: 5432
          envFrom:
            - configMapRef:
                name: postgres-config
          volumeMounts:
            - mountPath: /var/lib/postgresql/data
              name: postgres-data
      volumes:
        - name: postgres-data
          emptyDir:
---
apiVersion: v1
kind: Service
metadata:
  name: postgres
  labels:
    app: postgres
spec:
  type: NodePort
  ports:
   - port: 5432
  selector:
   app: postgres

undeploy postgres service and endpoint and deploy the above YAML.
it should work
why NODE ip is prefixed with ip-

A: you should create deployment for your database and then make a service that target this deployment and then ping using this service why ping with ip ?


text:
Q: Получить индекс элемента относительно конкретного предка Есть div id="high" с вложенными прямыми потомками div attr="low", внутри каждого из которых есть множество параграфов, причем эти параграфы могут быть как прямые потомки для div[attr], так и непрямые (например внутри таблиц).
Все эти параграфы я прогоняю через .each().
$('#high p').each()

Мне нужно получить индекс каждого параграфа относительно именно closest('div'), а не относительно родителя. В каких-то случаях closest('div') и является родителем, но не обязательно. Делать два .each() (сначала прогоняем каждый div[attr], а в нем каждый p) кажется глупостью.
Наверняка же есть какое-то элегантное решение. Если это так, то подскажите, как сделать правильно.

A: Ну получается так... если только на jQuery...

$('div[attr="low"]').each( function(){
  $(this).find('p').each( function(index){
    $(this).text( 'Мой индекс — ' + index );
  });
});
div[attr="low"] {border: 1px solid red; margin: 5px;}

На чистом JS это можно организовать так:

let low = document.querySelectorAll('div[attr="low"]');
for( let i = 0; i < low.length; i++ ){
  /* перебрав все найденные low, на каждом круге находим теги 'p' внутри них */
  let p = low[i].getElementsByTagName('p');
  for( let u = 0; u < p.length; u++ ){
    /* и снова перебираем уже найденные элементы 'p'... причем, на каждом круге
    u является конкретным числом, по совместительству - индексом элемента. */
    p[u].innerText = 'Мой индекс — ' + u;
  }

}
div[attr="low"] {border: 1px solid red; margin: 5px;}

В таком случае не факт, что на jQuery лучше)


text:
Q: microsoft cpprestsdk listen to multiple url with same ip? I want to use cpprestsdk to make a restful API,
I copied some code from here :
int main()
{
    http_listener listener("http://0.0.0.0:9080/demo/work1");
    cout<<"start server!"<<endl;
    listener.support(methods::GET,  handle_get);
    listener.support(methods::POST, handle_post);
    listener.support(methods::PUT,  handle_put);
    listener.support(methods::DEL,  handle_del);

    try
    {
        listener
                .open()
                .then([&listener]() {TRACE(L"\nstarting to listen\n"); })
                .wait();

        while (true);
    }
    catch (exception const & e)
    {
        cout << e.what() << endl;
    }

    return 0;
}

now I have to listen to not only "http://0.0.0.0:9080/demo/work1" , but also "http://0.0.0.0:9080/demo/work2", "http://0.0.0.0:9080/realfunction/work1". All in the same IP and port, but different sub-path
Should I use multiple listener to handle all the url one by one in multi-thread? Or there is any other way to handle this?

A: You can set
http_listener listener("http://0.0.0.0:9080/");

And then in the handler check the request. In the examples linked in cpprestsdk's github I saw things like
void handle_get(http_request message) {
    auto path = uri::split_path(uri::decode(message.relative_uri().path()));

    if (path.size() == 2 && path[0] == "demo" && path[1] == "work1") {
           // ...
    } else if (path.size() == 2 && path[0] == "demo" && path[1] == "work2") {
          // ...
    } else {
          message.reply(status_codes::NotFound);

    }
}


text:
Q: Source-based routing on Cisco 3750 switch? I have this Cisco 3750 switch which handles many VLANs. It has an IP interface on some of them, and it does routing for those computers connected to those VLANs which use the switch's IP addresses as their default gateway.
The switch has a default gateway, too; this is needed because one of those VLANs is connected to an Internet router, so every outgoing connection which is not directed to any specific internal subnet needs to go there.
The switch itself also has another IP address, which we use for management; this address is attached to one of the VLANs. Traffic from/to this address needs to go through another route.
The question: I want any outgoing IP connection which comes from the switch to go through a different route than its default gateway. But this should only apply to packets which originates from the switch itself; those packets which come from any device connected to any VLAN on the switch should go through the default route.
Source-based routing is what I need here; i.e. I want a static route which only applies to packets originating from the switch itself.
Can this be done on a Cisco 3750 switch?
How?

Edit: why I want this
This is a test environment, where the default gateway is a Linux firewall which at any given time might be down; our workstations are on the other side of this firewall, and there's also some other routing in the middle.
The switch has a management IP on a subnet which is linked to our main network, where a gateway could allow it to talk with us without going through its default gateway.
And of course we don't want to lose connectivity to the switch if the test area is not fully working.
But, at the same time, the switch's default gateway has to be that one, because the switch itself also acts as a router for the (many) subnets which form this test area.
So I need to route through an alternate gateway all the traffic that comes from the switch, but only it.

Edit: show version
Cisco IOS Software, C3750 Software (C3750-IPBASEK9-M), Version 12.2(25)SEE1, RELEASE SOFTWARE (fc1)
Copyright (c) 1986-2006 by Cisco Systems, Inc.
Compiled Mon 22-May-06 08:51 by yenanh
Image text-base: 0x00003000, data-base: 0x01026AEC

ROM: Bootstrap program is C3750 boot loader
BOOTLDR: C3750 Boot Loader (C3750-HBOOT-M) Version 12.2(25r)SEC, RELEASE SOFTWARE (fc4)

SW-TEST uptime is 5 weeks, 1 day, 16 hours, 22 minutes
System returned to ROM by power-on
System image file is "flash:c3750-ipbasek9-mz.122-25.SEE1/c3750-ipbasek9-mz.122-25.SEE1.bin"

A: If you want to direct or tag the traffic originating from the switch or router (will work on IPBASE) I'm guessing you already succeeded but if not.
conf t

access-list 1 any

route-map pbr permit 10

 match ip address 1

 set ip next-hop 3.3.3.3

exit

ip local policy route-map pbr

end

wr

Note that ip local policy is specified in global configuration, not under an interface. And you might want to have a more detailed ACL
This is only for traffic that originates from the device, not traffic that passes through it.

A: Cisco 3750s support "Policy-Based Routing" which will allow you to make routing decisions based on a standard ACL. Here is the PDF explaining it:
http://www.cisco.com/en/US/docs/switches/lan/catalyst4500/12.2/25sg/configuration/guide/pbroute.pdf
Out of curiosity, why? It seems to me like what you want to achieve might be possible another way.
From the PDF:
The following example illustrates how to route traffic from different sources to different
places (next hops). Packets arriving from source 1.1.1.1 are sent to the next hop at 3.3.3.3;
packets arriving from source 2.2.2.2 are sent to the next hop at 3.3.3.5.

access-list 1 permit ip 1.1.1.1
access-list 2 permit ip 2.2.2.2

! interface fastethernet 3/1
ip policy route-map Texas
! route-map Texas permit 10
   match ip address 1 set ip next-hop 3.3.3.3
! route-map Texas permit 20
   match ip address 2 set ip next-hop 3.3.3.5

Though in your case instead for fastethernet 3/1 you would put the vlan interface that you want the source routing to occur. If you copy and paste this code into a text editor and change the IPs and the interface to what you need you can paste it right into config mode on the switch

A: As per einstiien's answer, the right thing to do is to use PBR. Unfortunately, you're using an IP Base feature set and the PBR functionality is not available in that feature set, so you'd need to buy PBR instead.
Would it be possible to simply make the management uplink part of the managemenet VLAN and provide routing to the management station? That would allow all other VLANs access to the management station via that route, but that may be fixable by providing traffic-blocking ACLs further down the line (or, possibly, on the switch itself, I can't say I recall exactly what you can and cannot do with ACLs on switch ports right now).


text:
Q: PHP strange echo behavior I have noticed a very strange PHP behavior, where echo function seems to affect the styling of some elements on the page.
when I use:
echo "
";
echo "
Item-1
";
echo "
Item-2
";
echo "
";

I get "item-icon" slightly out of position.
But when I use this I get correct icon positions:
echo "
";
?>

Item-1

Item-2

<?php
echo "
";

I can still fix the css and use the first syntax, but I am very curious to know what is causing this porblem!!
Answer:
Thanks to Brad Kent, adding line break to the echo fixed the problem!!
echo "
";
echo "
Item-1
\r\n";
echo "
Item-2
\r\n";
echo "
";

A: depending on what CSS is being applied...
version A contains no line breaks between the
s
version B does contain line breaks betwen the
s

blah

blah

vs

blah

blah

it can make a difference

A: Missing = in this line?
                  v
echo "
Item-1
";

Single quotes are okay.


text:
Q: Limit video buffer to X seconds in YouTube iframe player I have a YouTube IFrame player in a UIWebView. When the video is paused, the player keeps caching the video until its end. I'd like to limit the buffered part to no more than X seconds after the pausing/playing time point. How can I do that?
I haven't found any caching control in the IFrame API.
In the official iOS YouTube app, the caching seems to be limited to around 30s after the pausing/playing time.

A: There is no control over buffering through iFrame API. Buffering is usually determined with respect to viewer's own platform, device and connection and dynamically adjusted on the fly rather being controlled statically.
If that's the case for YouTube app or for the best of the user, that should be coming to the embed as well. You don't need to worry or try to control it.


text:
Q: How can we check whether coefficeints of a multivariable regression models are zero(null hypothesis) without creating full and restricted model? I want to test whether a variable Y has an influence over other variable Y. For this I have established a null hypothesis that the coefficients of Y in the regression model are zero. Can I test this hypothesis without having a need to create Full or Restricted model, so as to make it computationally less expensive ? If yes please explain me how this can be achieved.

A: In linear regression this is called the t-test, i.e. your test statistic is the coefficient divided by its standard error, and you compare it with a t-distribution with the residual degrees of freedom. Any introductory statistics test covering linear regression will be able to provide you all the details.


text:
Q: Javax Validation with RESTfull webservice(jersey)? I am currently working in a service where i have to use validation with service.We are getting the input from client through request class storing in the database using entity by repository,where we have to give the annotations and where we have to give the bindingresult parameters.While we calling the the service the validation have to take place.Here,I have attached the sample code.
this is the service class where i tried to implement the validation
public long create(@Valid Document document,BindingResult bindingResult,DocumentResourceRequest DocumentResourceRequest,
        long agreementId) throws Exception {
    // TODO Auto-generated method stub
    logger.info("In DocumentServiceImpl createLoanDocument");

    Document documentObject = new Document(new lend(
            agreementId));

    documentObject.setDocumentType(DocumentResourceRequest
            .getDocumentType());
    documentObject.setDocumentDetails(DocumentResourceRequest
            .getDocumentDetails());
    documentObject.setRemarks(DocumentResourceRequest.getRemarks());
    documentObject.setDocumentStatus(DocumentResourceRequest
            .getDocumentStatus());
    documentObject.setCreatedBy(DocumentResourceRequest
            .getCreatedBy());
    documentObject.setCreatedOn(new Date());
    try {
        if(document != null)
        {
        document = loanDocumentRepo.saveAndFlush(documentObject);//DocumentRepository
        }else(bindingResult.getAllErrors())//if getting errors
        {

        }

    } catch (Exception e) {
        throw new Exception("Error in persisting Document-->" + e);
    }

    return document.getId();

}

'


text:
Q: What is the point of talking about linear independence for 1 element Let ${w*(80/27,-76/27,-31/27)} $ be the solution set of a homogeneous system of linear equations.
The statement to be decided if it's true or false, is this:

The solution set of the given system, contains at least one linearly
  independent element

As I got, using wolfram with this query:

linear independence (1,2*w)

(and got this)

(1, 2 w) is linearly independent

What is the point of talking about linear independence for 1 element?
Also, could the statement be false, due to the fact that the linearly independent is only one and not at least one?
Thank you!

A: The definition of linear independence holds for one element as it does for any other number of elements. An element $v$ is linearly independent if $cv=0$ with $c$ a scalar implies $c=0$. Thus the only linearly dependent element is $0$.


text:
Q: Firebase Firestore get data from Document Java Android I have a Collection "Users".  Each user has some member variables.  I am trying to read the data stored in the Co-Email member variable through a document reference.
public String getCoEmail() {
        coUserReference = db.collection("users").document(email);

        coUserReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                if (documentSnapshot.exists()) {
                    String coEmail = documentSnapshot.getString("coEmail");

                }
                else {
                    Toast.makeText(ViewExpenses.this, "Document does not exist", Toast.LENGTH_LONG).show();
                }
            }
        });

    return coEmail;

    }

It never gets into the OnSuccess part of the code.  So I am unable to get the coEmail.  Any help would be greatly appreciated.
enter image description here
I have also used this code but I am having the same issue.  It never gets past the addOnCompleteListener line.  (Doesn't get into onComplete)
public String getCoEmail() {

coUserReference = db.collection("users").document(email);

coUserReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {

            String coEmail = document.getString("coEmail");
            Log.d("TAG", "CoEmail:  " + coEmail);

        }
        else {
            Toast.makeText(ViewExpenses.this, "Document does not exist", Toast.LENGTH_LONG).show();
        }
    }}
});

    return coEmail;

    }


text:
Q: Difference between JavaScript's trimLeft() vs trimStart() What's the difference between JavaScript's trimLeft() and trimStart() methods? How does trimLeft() work with right-to-left scripts?

A: MDN states that trimLeft is an alias of trimStart.

A:
The property trimStart is preferred. The trimLeft property is provided principally for compatibility with old code. It is recommended that the trimStart property be used in new ECMAScript code.

However, trimLeft() or trimStart() do not affect the value of the string itself.

var greeting = "   Hello world!   ";

console.log(greeting);
// expected output: "   Hello world!   ";

console.log("trimStart:" + greeting.trimStart() + ";"); console.log("trimLeft:" + greeting.trimLeft() + ";");
// expected output: "Hello world!   ";

var nTrimVal = greeting.trimStart();
var nTrimNormal = "   Hello world!   ".trim();
console.log("Original String: ", greeting);
console.log("String value and new Trim value is same: ", greeting == nTrimVal);

A: The existing answers are correct that trimStart and trimLeft are aliases and therefore functionally identical.  However, support varies.  ES2019 was the first version to specify trimStart and trimLeft , with the note:

The property trimStart is preferred. The trimLeft property is provided principally for compatibility with old code. It is recommended that the trimStart property be used in new ECMAScript code.

The rationale for preferring the name trimStart over trimLeft is consistency with padStart.  trimLeft is much more widely supported (Edge, Node < 10, Firefox < 61, Chrome < 66) (via MDN and kangax).  The choice of which to use is one of compatibility vs consistency.

A: The trimStart() method removes whitespace from the beginning of a string. trimLeft() is an alias of this method.
So both work same both return the same value. The example of proof is attached.

var greeting = "   Hello world!   ";

console.log(greeting);
// expected output: "   Hello world!   ";

console.log("output:" + greeting.trimStart() + ";", "output:" + greeting.trimLeft() + ";");
// expected output: "Hello world!   ";

console.log(greeting.trimStart() === greeting.trimLeft());
// expected output: true;

A: I got an error when I used trimStart on Edge
Object doesn't support property or method 'trimStart'

trimLeft works  well
Edge version:
Microsoft Edge 44.18362.449.0

A: Technically both trimStart() and trimLeft() are used for the same purpose to remove the left white spaces from a provided string trimEnd() and trimRight() are used to remove left whitespaces from the strings. They can be called as aliases to each other.
For example:
const dedent = (s:string) => s.split('\n').map( l => l.trimLeft() ).join('\n') ;

A: both are exactly same functions but with different names or in short alias
this is the proof:

console.log( String.prototype.trimLeft === String.prototype.trimStart );


text:
Q: Jquery list filtering help required Hello I want to change a little function of list filtering instead of filtering li, i want to scan the multiple ul tags of the div which contains which contains same list items in it
how is it possible with it
here is my js code
$( document ).ready(function() {
  $('#s').keyup(function(){
   var valThis = $(this).val().toLowerCase();
    $('.domain_pricing_list>li').each(function(){
     var text = $(this).text().toLowerCase();
        (text.indexOf(valThis) == 0) ? $(this).show() : $(this).hide();
   });
  });
});

here is my html
<input placeholder="Search..." id="s" type="text" />

TLD.com

Duration1 Year

Registration$10

Renewal$10.45

Transfer$10.33

TLD.net

Duration1 Year

Registration$10

Renewal$10.45

Transfer$10.33

TLD.org

Duration1 Year

Registration$10

Renewal$10.45

Transfer$10.33

A: CSS selector is not correct. It should be:
$('.domain_pricing_list > ul >li')

.domain_pricing_list > li means "direct child of .domain_pricing_list" element. According to your HTML there are no such children. Direct descendants of .domain_pricing_list are ul tags.
Demo: http://jsfiddle.net/06kvcmqq/


text:
Q: Visual Basic MDI application modal sub-dialogs I have a very complex application, written in Visual Basic 6.
The main dialog of this application is an MDI form.
My problem is:
There are a lot of dialogs (e.G. message boxes), these have to be modal. But modal dialogs cannot stay inside the frame of the MDI main form.
My question is:
How could this problem be solved? The (standard VB) message boxes and other (custom) modal dialogs should not be allowed to be moved outside of the MDI dialog's frame.


text:
Q: How can i show date & time in the X Axis (domain axis) of the graph I have a graph in which i want to show Date-Time in the X Axis and some values in the Y Axis.
I am wondering how I can show the date and time on the X Axis.
The Format in which i want to show is: dd/mm/yyyy hh:mm
My X Axis Data is :
Number[] xaxisSeries = {2407141120,2507141220,2607141640,2707141850,2807142027,2907142333};

plot.setDomainValueFormat(new SimpleDateFormat("dd/mm/yy hh:mm"));

But its not showing the correct values.
Please help me how should i show the Date-Time on my X Axis of the Graph

A: Here's what worked for me, based on this example. In my case, I wanted to show time only, and the x values were millis since the epoch.
mGraphView.getGraph().getLineLabelStyle(XYGraphWidget.Edge.BOTTOM)
        .setFormat(new Format() {
            private final DateFormat dateFormat = DateFormat.getTimeInstance();

            @Override
            public StringBuffer format(Object obj,
                                       @NonNull StringBuffer toAppendTo,
                                       @NonNull FieldPosition pos) {
                Number timestamp = (Number) obj;
                return dateFormat.format(timestamp, toAppendTo, pos);
            }

            @Override
            public Object parseObject(String source, @NonNull ParsePosition pos) {
                return null;
            }
        });

A: There's a tutorial on androidplot.com that describes the process.  Additionally, here's a similar question which includes another example of how it's done.


text:
Q: How to retrieve uid according to that PhoneNumber while registration in swift I have registerButton and otpButton for successful registration to the app.
in registerButton tapping i am sending otp to that registered phonenumber. after otp verification in otpButton then the person successfully registered and i will get uid .
now i want to check if user is already registered or not while registration.. for that i have saved uid in otpButton.. and retrieving uid in registerButton to check if uid is not nil then to show alert message... but here all the time including new user also i am getting recently registered person uid WHY?
How to check if user is already registered or not with their phone number.
saving uid in otpButton:
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
print("the json of otppppppppp \(json)")
DispatchQueue.main.async {
    if (self.otpTextField.text == String(self.otpField ?? 12)){
        print("registration successfullllll...")
        let mobileNum = json["mobile_number"] as! [String : Any]
        self.regUid = mobileNum["id"] as? String
        print("otp uid \(String(describing: self.regUid))")

        DispatchQueue.main.async {
            KeychainWrapper.standard.set(self.regUid!, forKey: "regUid")
        }
        print("the otp uid keywrap \(KeychainWrapper.standard.set(self.regUid!, forKey: "regUid"))")

        let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
        self.present(loginVC, animated: true)
    }
}
}

retrieving uid to check if user is already registered or not
do{
let userId: String? = KeychainWrapper.standard.string(forKey: "regUid")
print("reg userid \(userId)")
if userId != nil{
    DispatchQueue.main.async {
        AlertFun.ShowAlert(title: "Title", message: "user exist", in: self)
    }
}
else{
    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
    print("the json regggggggggggis \(json)")
    let phNum = json["mobile_number"] as? Int
    let status = json["status"] as? String
    self.otpField = json["otp"] as? Int
}
}

Please help me to check if user exist or not while registration according to uid.

A: used mobile number instead of regUid as a key chain key
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
print("the json of otppppppppp \(json)")
DispatchQueue.main.async {
    if (self.otpTextField.text == String(self.otpField ?? 12)){
        print("registration successfullllll...")
        let mobileNum = json["mobile_number"] as! [String : Any]
        self.regUid = mobileNum["id"] as? String
        print("otp uid \(String(describing: self.regUid))")

        DispatchQueue.main.async {
            KeychainWrapper.standard.set(self.regUid!, forKey: mobileNum)
        }
        print("the otp uid keywrap \(KeychainWrapper.standard.set(self.regUid!, forKey: mobileNum))")

        let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
        self.present(loginVC, animated: true)
    }
}
}

let mobileNumber = ""  // set mobile number
do{
let userId: String? = KeychainWrapper.standard.string(forKey: mobileNumber)
print("reg userid \(userId)")
if userId != nil{
    DispatchQueue.main.async {
        AlertFun.ShowAlert(title: "Title", message: "user exist", in: self)
    }
}
else{
    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
    print("the json regggggggggggis \(json)")
    let phNum = json["mobile_number"] as? Int
    let status = json["status"] as? String
    self.otpField = json["otp"] as? Int
}
}


text:
Q: Can I stop Visual Studio compilation when it already started? Sometime I mistakenly press build (or Debug/F5) in Visual Studio, which result in a build process. I don't know how to stop this, stop debugging button is disabled, and normally I have to wait until the compilation is finished before I can code again (this might take a while if my solution has quite a number of csproj).
Any idea how to stop the compilation process?

A: You can press the key combination Ctrl + Break.

A: Press Ctrl+Pause|Break to abort the build.

A: That's easy - Press Ctrl+Break (Works only from VS2005 upto 2010)
I suggest to download for your reference this document
Visual Studio 2010 Default Key Bindings

A: Press the Control Button and then Break (pause break)


text:
Q: C++ gcc vs visual c++ Hello everyone as starting programmer in c++ i was looking into some differences in compilers I imported the same source files for both the gcc compiler (code blocks) and the visual c++ (Visual studio express) and i found some strange behavior that i did not expect.
The visual c++ threw a bunch of errors which were in my opinion quite big... like iterating through vector with different iterators , iterator was from another instance of the vector than the operation was done on with this iterator.... gcc compiled successfully and threw no errors in runtime... while the visual c++ threw a bunch of errors in compilation and then threw a runtime error of 'different iterator type', or dynamic char allocation with new char[str.length()+1] and strcpy_s() into them from string - visual c++ debuger threw runtime error of corrupted heap while code blocks debugger ran just fine.
My question is. Is there really this big of a difference in these compilers and debuggers? Should i worry that my programming is on a bad level if the code runs totally perfect with gcc and code blocks debuger but throws errors in visual studio?
I ve learned to programm in c++ in code blocks, visal c++ has shown me mistakes that i was totally not aware of..

A: The problem is with your code, not with your compilers or setup.   The types of problems you are describing are examples of undefined behaviour that result from rather bad programming or coding techniques  (in fact, some of them are fairly hard to achieve, without going out of your way to write very flawed code).
The thing is, compilers are not required to detect such things.   Whether they do or not is a concern of compiler or library quality of implementation.   In your case, it appears that your version of VC++ is detecting concerns that g++ is not, which is a point in favour of VC++.
My experience is actually the reverse of that:   I find g++ detects more problems than VC++.    However, both VC++ and g++ do diagnose problems that the other does not.
Which all just goes to show that your milage will vary.   Personally, I'm an advocate of feeding all my code through multiple compilers when possible - precisely because that widens the net of what problems are diagnosed.
And then I exercise a policy of ensuring my code compiles cleanly with all compilers (no diagnostics at all, which includes no warnings) without having to disable any diagnostics, and avoiding use of any code constructs that are designed to suppress compiler diagnostics.
One thing to realise is that compilers, when installed, are typically configured to NOT produce many diagnostics.  The reasons for this are historical.    It is necessary to turn on the settings to make the compiler give warnings or errors.   With g++, command options like -Wall -pedantic (which can be enabled through Code::Blocks) really increase the number of problems that will be reported.   There are similar options for VC++ (although I don't remember them offhand).

A: MSVC has "checked iterators" for std::vector, which perform a number of useful checks. You can turn on some of these types of checks in GCC by compiling with -D_GLIBCXX_DEBUG. If you want your access to always be bounds-checked, then you need to use std::vector::at(). Often, for performance reasons, it is better to ensure bounds checking outside of your loop and then use unchecked iterators or indexing in your loop.

A: GCC's standard library does exactly what you told it, bugs and all.  Most of the time, it behaves as you expected, and you don't realize that the bugs are there.  Don't be fooled by the fact the program appears to work, it may still have bugs.
Visual Studio has two variants of the standard library.  In Release builds, it acts the same as GCC.  It does exactly what you told it to do, bugs and all.  In Debug builds, it adds a ton of code behind the scenes to detect some of these errors, and will notify you, as you've observed.  Fix these!.  Note that some of these, like "heap corruption" mean that it detected that a bug occured several seconds ago, and does not mean that the bug is at the free/delete.  You should also go to the project properties, and in C++/General, make sure your Warning Level is set to Level3 or even Level4.  This will reveal even more bugs at compile time.
The differences in the compilers in this respect aren't that significant, except that in Debug builds, Visual Studio adds tons of error checking that's finding bugs.  The other implementations, and Visual Studio in Release builds, don't go out of their way to help you find bugs.


text:
Q: code": -32000, "message": "gas required exceeds allowance (20058647) when i want to deploy this contract in REMIX IDE i get this error:
Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
Internal JSON-RPC error.
{
"code": -32000,
"message": "gas required exceeds allowance (20058647)"
}

this is my contract:

//SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract KINGs300 is ERC721Enumerable, Ownable {

    using Strings for uint256;

    string public baseURI;
    string public baseExtension = ".json";
    uint256 public  cost = 0.5 ether;
    uint256 public  maxSupply = 300;

    constructor(
        string memory _name,
        string memory _symbol,
        string memory _initBaseURI
    )
    ERC721(_name, _symbol) {
        setBaseURI(_initBaseURI);
        mint(msg.sender, 300);
    }

    function _baseURI() internal  view override virtual  returns (string memory) {
        return baseURI;
    }

    function mint(address _to, uint256 _mintAmount) public  payable {
        uint256 supply = totalSupply();
        require(_mintAmount > 0);
        require(supply + _mintAmount <= maxSupply);

        for (uint256 i = 1; i <= _mintAmount; i++) {
            _safeMint(_to, supply + i);
        }
    }

function walletOfOwner(address _owner) public  view  returns (uint256[] memory)
    {
        uint256 ownerTokenCount = balanceOf(_owner);
        uint256[] memory tokenIds = new uint256[](ownerTokenCount);
        for (uint256 i; i < ownerTokenCount; i++) {
            tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
        }
        return tokenIds;
    }

    function tokenURI(uint256 tokenId) public  view override virtual returns (string memory)
    {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        string memory currentBaseURI = _baseURI();
        return  bytes(currentBaseURI).length > 0
                ? string(abi.encodePacked(currentBaseURI,tokenId.toString(),baseExtension))
                : "";
    }

    function setCost(uint256 _newCost) public onlyOwner {
        cost = _newCost;
    }

    function setBaseURI(string memory _newBaseURI) public onlyOwner {
        baseURI = _newBaseURI;
    }

    function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
        baseExtension = _newBaseExtension;
    }

}

i want to mint a collection that has 300 NFTs in it

A: You can't mint 300 NFTs at once because of gas Limit of blocks, check this link for the limit of ethereum
https://ethereum.org/en/developers/docs/gas/
Block limit of 30 million gas for ethereum.
Try minting less NFTs like 100 NFTs per transaction and you must send 3 tranasction for minting 300 NFTs.


text:
Q: How to determine a script's location from the script's code? In struggling with a solution to this problem I've run into another, related issue: how can I determine what the location of a running script is? (no, it's not document.location as that will tell you the location of the page including the script)
so, with:
- a.html -
<script type="text/javascript" src="/my/path/myscript.js"></script>

- myscript.js -
var myLoc = document.location; // what to use instead?

A: If you can select the script, you can get its src.
var scripts = document.getElementsByTagName('script');

var loc = scripts[ 0 ].src;

This gives you the src of the first script element found.
You can use jQuery to do it too.
var loc = $('script').eq(0).prop('src');

or for older jQuery versions:
var loc = $('script').eq(0).attr('src');

$(function() {
    $.ajax({
         type: 'get', cache: false, url: '/svc.html',
         success: function(h) {

             var d = document.createElement('div');
             d.innerHTML = h;

             var scripts = d.getElementsByTagName('script');

             alert( scripts[ scripts.length - 1 ].src );

             $('#main').html( d.childNodes );
         }
    });
});

A: so the answer to this is two-fold: 1) if the script was loaded by a  tag directly, one can use RightSaidFred's approach consisting of picking up the last entry in the list of scripts, 2) for scripts that are loaded in a page that was loaded via ajax, the solution is the plugin at: Where are scripts loaded after an ajax call?


text:
Q: Что обозначает эта запись? Что обозначает такая запись? поставило в тупик, применением "::" несколько раз.
typename FGameMenuItem::FOnOptionChanged::TSPMethodDelegate< UserClass >::FMethodPtr InMethod

A: Данный оператор :: называется Оператор разрешения области видимости. В случае наличия вложенных классов class/struct и/или пространств имён namespace с его помощью обеспечивается доступ к нужному имени. Например:
namespace N
{
    struct C
    {
        struct D
        {
            static int i;
        };
    };
}

Для доступа из глобального пространства имён к статической переменной i нужно написать N::C::D::i.
Подробнее об операторе разрешения области видимости есть на MSDN.
Наличие же typename вначале говорит о том, что зависимое от шаблона имя является типом, а не переменной.


text:
Q: I cannot run SDK manager when I try to run the SDK manager Kasper-Sky quarantine it and delete it from SDK tools and I have this message at eclipse

[2013-06-17 10:18:50 - SDK Manager] [SDK Manager] 'D:\Work\MOBILE~1\Andriod\ANDROI~1\tools\lib\find_java.exe -s' is not recognized as an internal or external command,
  [2013-06-17 10:18:50 - SDK Manager] [SDK Manager] operable program or batch file.

A: Disable Kaspersky while running SDK manager.
If eclipse can run it, consider to change your antivirus software or find a way to add the sdk folder to an ignore list of kaspersky.

A: Found this i a forum on the web ... check it out :
Forum answer
it basically tells you to try 2 things :
1) disable your antivirus while working.
2) add the sites of updating the sdk to the trusted sites list in Kasper-Sky.