text:
Q: Show div after X% of body's height How can I invoke a div, to show it on top (a search bar and some functions), after 300px of page's heigh have been scrolled?
What I'm trying to achieve is that when the user scrolls, at a certain point to show another div containing some tools.

A: Probably that's what you're looking for:
JavaScript
$(document).ready(function () {
  $('#my-div').hide();
});
$(document).scroll(function (e) {
    if (document.body.scrollTop >= 300) {
       $('#my-div').show(200);
    } else {
      $('#my-div').hide(200);
    }
});

CSS
#my-div {
  position: fixed;
  top: 10px;
  left: 10px;
  width: 300px;
}
body {
  height: 11100px;
}

HTML
<div id="my-div">
  Search: <input type="text" />
</div>

Demo: http://jsbin.com/welcome/49824

A: Use .scroll() to fire an event, and use .scrollTop() to calculate the height scrolled from the top of the page.
Then depending on this value, show/hide the tools:
 $(document).scroll(function(){
        if (document.body.scrollTop>300){
            $(".tools").show();
       } else
       {
           $(".tools").hide();
       }
    });

-- View Demo --


text:
Q: JSON parser exception is observed for on fly JSON I created a JSON file on the fly by using some runtime data and stored as string as like below:
JSON:
  {
        "ticketDetails": "kindle tracking ticket: TICKET0900060

        Iimpact statement: impacted due to year 2020 format handling issue,
        depending on the Gateway,
        user can be asked to
        try with another instrument.

        Timeline: 00: 00 SAP Internal Declines spiked to 300 +
            05: 22 AM flintron reported DECLINED errors since 0: 00 PST.

        As per TDO,flitron is not seeing clear metrics impact " }

Note: I just copied the exact json which i'm getting at runtime. It containse \n space and exactly like above.
I can see few JSONObjects like ticketDetails is having huge description and when I tried to parse the above string is leading to parse error.
I tried the below way to eliminate the parse error by using
String removeSpecialCharacterFromJson= jsonString.replaceAll("[^A-Za-z0-9]","")

System.out.println(removeSpecialCharacterFromJson);

Sample Output:
kindletrackingticketTICKET0900060Iimpactstatementimpactedduetoyear2020formathandlingissue....[space between characters are removed and It's hard to read the string]
The above code removed all the special characters from the string and It will be successfully parsed. But the description is not having the space and It very hard to read the content after the above changes done.
I tried to escape the \s in the regular expression which is giving the original String value which is leading to parse exception.
String removeSpecialCharacterFromJson= jsonString.replaceAll("[^A-Za-z0-9\\s]","")

Is there anyohter way to handle this ? I just want to the ticketDetails to be readable format and It should not have any special characters and \n lines.
Can someone help me on this?

A: s in regular expression is not for space but for the whitespace
I guess that you may have some additional non allowed whitespace in your JSON string
Take a look at The JSON spec (RFC 7159):

Insignificant whitespace is allowed before or after any of the six structural characters.
ws = *(
%x20 / ; Space
%x09 / ; Horizontal tab
%x0A / ; Line feed or New line
%x0D ) ; Carriage return

Verify your values and look for improper whitespaces

redpajama_set_name: RedPajamaStackExchange


text:
Q: Replace placeholder of HTML file in JAVA I am using jsoup library to parse HTML file in Java.
I want to replace placeholders of that HTML file.
Presently I am putting the placeholders in  xx  and replacing them.
I have tried to do many other things, but didn't achieve success.
    Document doc = Jsoup.parse(new File("abc.html"), UTF_8);
    doc.getElementById("id_1").text("MUKUL");

Placeholders in my html file are like <%= name %>. I want to replace all placeholders with suitable value. For now I had made change in my html file to put placeholders in  xx  tag. I don't want to change my html template.
Can anyone please suggest some clean and better way to achieve this thing.
Why I am not changing it to String: I don't want to change the html file in String because html file contains some Japanese characters and whenever I transform it to string, some of the Japanese characters distort and produces some junk data.


text:
Q: SQLite database on FireDAC engine not respecting rollback I have a Data Access Object (DAO) in a Delphi (Delphi 10.1 Berlin) application. I create the connection with the SQLite database, select some data (Simple select clause) and then execute an update clause, using the method ExecSQL() of TFDQuery component. The data in database is not changed.
Then, I execute the rollback() method in the connection. The data in database is not changed yet.
So, I execute the close() method in the connection. The data in database is changed.
I don't know if this is the expected behavior of FireDAC and SQLite, but I think it should not be.
Some code:
FFDConnection                  := TFDConnection.Create(nil);
FFDConnection.Params.Database  := 'database.db3';
FFDConnection.Params.UserName  := '';
FFDConnection.Params.Password  := '';
FFDConnection.Params.DriverID  := 'SQLite';
FFDConnection.Open();

FFDQuery            := TFDQuery.Create(nil);
FFDQuery.Connection := FFDConnection;

FFDConnection.StartTransaction();
// ... Some update code ...
FFDConnection.Rollback();
FFDConnection.Close();
FFDConnection.Free();

After the FFDConnection.Rollback(); but before FFDConnection.Close(); the data in database is still not changed. After FFDConnection.Close(); the data in database is changed.
Is this a problem of SQLite?
I really appreciate any help you can provide.
EDIT 1: The problem is that I was not creating the TFDTransaction for my connection beacuse I thought that the creation was implicit. I feel so dumb.


text:
Q: How do I fill an element using keypress event This is the code:

What I'm trying to do is filling an element with keypress events.

i need  to fill here with keyboard events. {ENTER}

I have write a basic function which fills the innerHtml,
function myFunction()
{
    var element = document.getElementsByClassName('sampletext')[0].firstChild;
    element.innerHTML = 'i need  to fill here with keyboard events.\n';
}

Basically this function will do the job, but it won't work in the site which am trying. If am entering it from keyboard it works perfectly. The window is listening for the keyenter event.
I'm using Chrome browser. The project was related with the cefsharp.
private void SampleFucntion()
{
    string script = "var element = document.getElementsByClassName('sampletext')[0].firstChild;element.innerHTML = 'i need  to fill here with keyboardevents.\n';";
    myBrowser.ExecuteScriptAsync(script);
}

I already checked input fill with keypress simulation
So please help me how can I achieve this with pure JavaScript.

A: You can actually send key strokes directly to the browser which is likely easier than executing a block of javascript. Assuming the text box has focus of course.
The SendKeyEvent can be used to send a character at a time.
There is a basic example available in the CefSharp.WPF.Example project.
https://github.com/cefsharp/CefSharp/blob/cefsharp/43/CefSharp.Wpf.Example/Views/BrowserTabView.xaml.cs#L32

A: add style to your span

A: Is this what you mean?
JS-FIDDLE
document.addEventListener("keyup", function(e){
    var target = document.getElementById("here");
    var value = String.fromCharCode(e.keyCode);
    if (value!="undefined") {
        target.innerHTML += value;
    }
});


text:
Q: Are directory dots in scandir always first elements of array? When using scandir in PHP, one always gets directory dots ('.' and '..'). It seems that they are two first elements in array, but will they always be? Is it safe to use something like this to get rid of them?
$files = scanf('/images');
unset($files[0]);
unset($files[1]);

A: No, it isn't.
When called like that scandir will return entries in alphabetical order, which means that if e.g. an entry named - exists it will appear before the dot entries. Tthere are also other characters that are widely accepted inside file names but sort before the dot, see an ASCII table for reference.


text:
Q: Is there a way to iterate over potential WCF server endpoints? In a WCF server/client situation, the WCF configurations on both server and client have to be synchronized. E.g. In a situation where my client has the configuration below, the server has to have the same binding name, contract and configuration, or it won't connect properly.
<bindings>
   <basicHttpBinding>
       <binding name="ServerContract" />
   </basicHttpBinding>
</bindings>
<client>
   <endpoint address="http://localhost/.../ServerContractImpl.svc/Mtom"
            binding="basicHttpBinding" bindingConfiguration="ServerContract"
            contract="ServerReference.ServerContract" name="ServerContract" />
</client>

I'm writing WCF client code for a server whose configuration I don't control, and this requirement makes me very nervous. I've generated my initial client configuration using VS2010's Service Reference, but if at any time the admin of the server changes, say, their binding names, how would my WCF client respond to that?
So my questions:

*

*How does a WCF client, assuming it has the URL to the server's .svc endpoint address, find out which endpoints and bindings are active on the server and connect to whichever one of them it chooses?

*How are situations such as these, where the WCF server and client are controlled by different people, usually managed in terms of WCF configuration?

A: I asked a somewhat related question a few weeks ago: WCF endpoint discovery from a client; Is it possible?
From the answer:

The following MSDN article should address your concern, as it clearly states that a client must have prior knowledge of the service address prior to discovery.

The answer includes a link to this article which is pretty informative and might address what you're looking for: http://msdn.microsoft.com/en-us/magazine/ee335779.aspx
From the article:

It would be great if the service could use any available address. The client, in turn, would need to discover that address at runtime. In fact, there is an industry standard-based solution that stipulates how that discovery takes place. That solution, called simply discovery (and its supporting mechanisms), is the subject of this column.

A: In my opinion this is more like a best practice thing. If you have no prior knowledge about the server you are about to connect to, the best thing is to prevent the worst to happen.
You can develop an exception mechanism to fail over one endpoint to another endpoint. The exception you expect to catch include CommunicationException and FaultException, both are under the Service.ServiceModel namespace.
Secondly as the other user said, get better knowledge of the WCF server side see if they enable WCF discovery. WCF discovery allow you decouple your WCF client and the address it connects to. In case of service failure/migration your client (yourself) can automatically connect to a proper address without failure.


text:
Q: Promise confusion using node (ES6) and Bluebird I had an issue with values being assigned prior to an async call being complete, so I opted to use Promises (in this instance: Bluebird). Which I thought would solve the problem, but seeing as I'm not at all familiar with promises / or node for that matter, it's still doing the same thing.
How would I go about modifying my code below, to use promises correctly? And maintain a flow, so I can validate modules based upon a previous row ?
var Promise         = require('bluebird');
var db              = require('../shared/db');
var queryHelper     = require('../shared/queryHelper');
var schemas         = require('../schemas/schemas');
var _               = require('lodash');
var serverSettings  = require('../shared/coreServerSettings');

// Create new instance of mysql module
var connection      = new db();
var queryhelper     = new queryHelper();

// Promised methods
var queryAndWait = Promise.promisify(connection.query);

..snip..
queryAndWait(query + '; ' + queryFoundRows, params).then(function (result) {
  var payload = [];
  var site_access = [];
  var module_access = [];

  _.each(result[0], function (row) {
    var sites = row.site_access.split(',');
    _.each(sites, function (site_id) {
      site_access.push(site_id);
    });

    row.site_access = site_access;
    site_access = [];

    queryAndWait(queryModules, [row.priv_id]).then(function (result) {
      _.each(result, function (module) {
        var modulePriv = {
          priv_name: module.priv_name,
          priv_num: module.priv_num,
          enabled: module.enabled
        };

        module_access.push(modulePriv);
      });

      //console.log("am assigning " + JSON.stringify(module_access));
      row.module_access = module_access;
      module_access = []
    });

    payload.push(row);
  });
});

To clarify:
Sorry, modules are groups of products that users (row) have access to, which are calculated on the fly (bitwise - hence no join available and a separate query), the module query returns something like the following, which I then loop through and attach to the row prior to returning the payload:
[{"priv_name":"INTERACT","priv_num":1,"enabled":1},{"priv_name":"STAFF_ADMIN","priv_num":32,"enabled":1},{"priv_name":"INT_EDIT","priv_num":64,"enabled":0},{"priv_name":"FAILED_LOGIN","priv_num":128,"enabled":0},{"priv_name":"INT_TAGS","priv_num":256,"enabled":0},{"priv_name":"NC","priv_num":512,"enabled":0},{"priv_name":"CC_TIMETABLE_MGR","priv_num":1024,"enabled":0}]

A: yes, the inner queryAndWait will run independently for each row as you don't chain the promises.
Since you use bluebird you'll need something like this to maintain the flow
queryAndWait(query + '; ' + queryFoundRows, params).then(function (result) {
    return Promise.map(result[0], function (row) {
        var site_access = [];
        var module_access = [];

        var sites = row.site_access.split(',');
        _.each(sites, function (site_id) {
            site_access.push(site_id);
        });

        row.site_access = site_access;

        return queryAndWait(queryModules, [row.priv_id]).then(function (result) {
            _.each(result, function (module) {
                var modulePriv = {
                    priv_name: module.priv_name,
                    priv_num: module.priv_num,
                    enabled: module.enabled
                };

                module_access.push(modulePriv);
            });
            row.module_access = module_access;
            return row;
        });
    });
}).then(function(payload) {
    console.log(payload);
}).catch(function(error) {
    console.log(error);
});

A: Promise help you to control de flow of the application in a simple way. I encourage you to read the basic principles about promise, at least the Promise A+ specification.
Your code could be written in many ways this is the way that I recommend because is modular:
var Promise         = require('bluebird');
var queryAndWait = Promise.promisify(connection.query);

function getRows(params) {
  return queryAndWait(query + '; ' + queryFoundRows, params)
          .then(function (result) {
            var site_access = [];
            _.each(result[0], function (row) {
              var sites = row.site_access.split(',');
              _.each(sites, function (site_id) {
                site_access.push(site_id);
              });
              row.site_access = site_access;
              site_access = [];
              return row;
            });
          });
}

function getModules(row) {
 return queryAndWait(queryModules, [row.priv_id])
         .then(function (result) {
          var payload = [];
          var module_access = [];
          _.each(result, function (module) {
            var modulePriv = {
              priv_name: module.priv_name,
              priv_num: module.priv_num,
              enabled: module.enabled
            };

            module_access.push(modulePriv);
          });
          row.module_access = module_access;

          payload.push(row);
          return payload;
        });
}

getRows(params)
  .then(getModules)
  .then(function(payload) {
    // Do something with your payload
  })

I did the next:

*

*Separate each logic in his own function (Why?, Because you can reuse logic in another promise, export methods in another libraries, etc.)

*I return the promise in each function. The promise can be nested and are executed in order.

*Each intern promise resolve a value. getRows -> resolve rows, getModules -> resolve a payload

You can also manage the erros using the catch method of promises, for example:
getRows(params)
  .catch(function(err) {
    // Something went wrong with getRows
    // If i can't recovery must return a reject.
  })
  .then(getModules)
  .catch(function(err) {
    //Something went wrong with getModules
    // If i can't recovery must return a reject.
  })
  .then(function(payload) {
    // Do something with your payload
  })


text:
Q: Map-summing items in a multidimensional array I have an array that looks roughly like this:
[ (0.5, 0.6, 0.7), (0.1, 0.9, 0.8), (0.9, 1.0, 0.4),
  ...
  (0.3, 0.8, 0.3), (0.2, 0.4, 0.9), (0.5, 0.5, 0.3) ]

What I need is a sum of [0][0], [0][1], [0][2], etc. as well as [1][0], [1][1], [1][2], etc. I need a way to get a sum of the first index of all items in the array, then a sum of the second index of all items in the array, etc.
How can I do this in Python? The ultimate result would be to have a single tuple that contained the average of each index of all of the tuples.

A: This should do for arbitrary sized tuples:
result = reduce(lambda x, y: tuple((xi + yi) for (xi, yi) in zip (x, y)), l)

with l being the list of tuples. Of course, that only sums everything up, doesn't calculate the average.
Any reason why you're not doing this with NumPy. It would simplify (and speed up) things.

A: >>> c=[ (0.5, 0.6, 0.7), (0.1, 0.9, 0.8), (0.9, 1.0, 0.4),(0.5, 0.6, 0.7), (0.1, 0.9, 0.8), (0.9, 1.0, 0.4),(0.5, 0.6, 0.7), (0.1, 0.9, 0.8), (0.9, 1.0, 0.4)]
>>> [ sum([t[i] for t in c]) for i in range(len(c[0]))]
[4.5, 7.5, 5.6999999999999993]

This assumes all tuples have has many elements as your first tuple

A: python 2.6.x
>>> reduce(lambda x, y: (x[0]+y[0], x[1]+y[1], x[2]+y[2]), [(1, 2, 3), (2, 3, 4), (4, 5, 6)])
(7, 10, 13)

A: tuple(a.sum(axis=0))
if a is the array

A: Try the following:
values = [(1,2,3), (4,5,6)]
print map(sum, values)


text:
Q: Handling the cleanup of the gen_server state I have a gen_server running which it must clean up its state whenever it is stopped normally or it crash unexpectedly. The cleanup basically consists in deleting a few files.
At this moment, when the gen_server crash or it is stopped normally, the cleanup is done in terminate/2.
Is there any reason why terminate/2 would not be called if the gen_server crash?
Should be any other process monitoring the gen_server waiting to do the cleanup if the gen_server dies unexpectedly?
So, the code is like this:
terminate(normal, State) ->
    % Invoked when the process stops
    % Clean up the mess
terminate(Error, State) ->
    % Invoked when the process crashes
    % Clean up the mess

EDIT: I found this email in the official mailing list which is talking about the same thing:
http://groups.google.com/group/erlang-programming/browse_thread/thread/9a1ba2d974775ce8
As Adam says below, if we want to avoid to trap the exists in the gen_server, we could use different approaches.
But if we trap the exists, terminate/2 seems to be a safe place to do the cleanup as it always will be called. Furthermore we must handle correctly when 'EXIT' is sent to terminate/2 and to handle_call/3 trying to propagate the errors correctly between workers and supervisors.

A: terminate/2 is called when a crash occur inside the gen_server even if it doesn't trap exits, it will not be called if it receives an 'EXIT' from some other process linked to it, in case you need to clean up then it should trap exits(using process_flag(trap_exit, true)).
This behavior is a bit unfortunate because it makes it difficult to write a reliable shutdown procedure for a gen_server process. Also, it is not a good habit to trap exits just for the sake of being able to run terminate/2, since you might catch a lot of other errors which makes it harder to debug the system.
I would consider three options:

*

*Handle the left over files when the next instance of the process starts (for example, in init/1)

*Trap exits, clean up the files, and then crash again with the same reason

*Have a 3rd process which monitors the gen_server whose only purpose is to clean up the files

Option 1 is probably the best option, since at least the code doesn't trap exits and you get persistent state for free. Option 2 is not so nice for the reasons described above, that it can hide and obscure other errors. 3 is messy because the cleanup process might not be done before the gen_server is started again.
Think carefully about why you want to clean up, and if it really has to be done when the process crashes (it is a bug, after all). Be careful that you don't end up doing too much defensive programming.

A: This is quite fresh and relevant
When does terminate/2 get called in a gen_server?


text:
Q: angularjs update model view after from http json Hi everyone I'm learning angular i wrote a simple app but i don't know how i can update the model or the view ,later of get http json.
angular.module("dataApp",[])

.controller("ctrlData",function($scope,$http){
    $http.get('consulta.php')
    .success(function(data){
        //console.log(data);
        $scope.personas = data;
    }).error(function(error){
        console.log(error);
    }); });//end ctrl

output of consulta.php
[
    {
        "id_persona":"1",
        "nombre":"sebastian",
        "apellido":"rincon ",
        "telefono":"4422404",
        "direccion":"calle 93 # 23 2132"
    },
    {
        "id_persona":"2",
        "nombre":"leiton",
        "apellido":"aricapa",
        "telefono":"4421112313",
        "direccion":"calle 634 supia avenia 93"
    },
    {
        "id_persona":"3",
        "nombre":"daniel",
        "apellido":"desconocido",
        "telefono":"645452423",
        "direccion":"urbanizacion los vientos 123"
    },
    {
        "id_persona":"4",
        "nombre":"angularjs",
        "apellido":"javascript",
        "telefono":"0231391",
        "direccion":"module controller 321"
    },
    {
        "id_persona":"5",
        "nombre":"mark",
        "apellido":"zuckerberg",
        "telefono":"423423423",
        "direccion":"palo alto california"
    }
]

index.html

            {{persona.id_persona}}
            {{persona.nombre}}
            {{persona.apellido}}
            {{persona.telefono}}
            {{persona.direccion}}

Everything works well but if I insert a new row in the database mysql angularjs will dont know it, i need refresh the page for view the new row.
For other hand i tried setTimeout function
setTimeout(function(){

    $http.get('consulta.php')
    .success(function(data){
        console.log(data);
        $scope.personas = data;
    }).error(function(error){
        console.log(error);
    });

},1000);

but i think that is not is the correct!. please help thanks.

A: You'll need to call the service again for the view to update.
When you write the $http.get() call in the controller, it's called only once when the view loads. After that it's not called.
You could use something like setInterval which periodically calls your service.
angular.module("dataApp",[])
.controller("ctrlData",function($scope,$http){
    setInterval(function(){
        $http.get(...)
    }, 60000);
});

That'll call your service every minute to update your view.
Note, though, that you shouldn't be using $http directly in your controller; rather use a service.

A: If you want your web application to react to server-side changes you'll either need something like web sockets or similar, or poll the API regularly. I reckon the first (best) options might be a bit too complex for you at this point, so that leaves the second.
Before you start implementing something like this, you'll have to be certain you actually need your view to react to changes without user interaction. Why isn't it enough to just wait for the user to either refresh (or change route)?
Anyways, here's one way you could create a service to poll your API for data:
angular.module('dataApp').service('personaService', PersonaService);

function PersonaService($http, $q, $interval){
    var pollingInterval;

    this.getConsulta = getConsulta;
    this.startGetConsulta = startGetConsulta;
    this.stopGetConsulta = stopGetConsulta;

    function startGetConsulta(interval){
        if(pollingInterval){
            return $q.resolve();
        }
        var deferred = $q.defer();

        // Get first time
        getConsulta().then(function(data){
            deferred.notify(data);
        }, function(response){
            deferred.reject(response);
        });
        // Start polling
        pollingInterval = $interval(function(){
            getConsulta().then(function(data){
                deferred.notify(data);
            }, function(response){
                deferred.reject(response);
            });
        }, interval);

        return deferred.promise;
    }

    function stopGetConsulta(){
        if(angular.isDefined(pollingInterval)) {
            $interval.cancel(pollingInterval);
        }
        pollingInterval = null;
    }

    function getConsulta(){
        return $http.get('consulta.php')
            .then(function(response){ return response.data; } );
    }
}

To use it, you'll inject in into your controller and start polling like this:
angular.module("dataApp",[])
.controller("ctrlData",function($scope, personaService){

    personaService.startGetConsulta(60000).then(null, null, function(data){
        $scope.personas = data;
    });

});

Note that since we're using notify instead of resolve, for the promise returned by the service, we're using the third notify-callback when consuming the promise in the .then(..) function.
That should do it. But just to cement things - don't just use this blindly. First make sure you actually need your view to be this reactive. Then make sure you actually understand what is going on in the above sample.
Here's a plunker showing this in action


text:
Q: Analysing C# source with Irony This is what my team and I chose to do for our school project. Well, actually we haven't decided on how to parse the C# source files yet.
What we are aiming to achieve is, perform a full analysis on a C# source file, and produce up a report.
In which the report is going to contain stuff that happening in the codes.
The report only has to contain:

*

*string literals

*method names

*variable names

*field names

*etc

I'm in charge of looking into this Irony library. To be honest, I don't know the best way to sort the data out into a clean readable report. I am using the C# grammar class packed with the zip.
Is there any step where I can properly identify each node children? (eg: using directives, namespace declaration, class declaration etc, method body)
Any help or advice would be very much appreciated. Thanks.
EDIT: Sorry I forgot to say we need to analysis the method calls too.

A: I'm not sure this is what you need but you could use the CodeDom and CodeDom.Compiler namespaces to compile the C# code, and than analyze the results using Reflection, something like:
        // Create assamblly in Memory
        CodeSnippetCompileUnit code = new CodeSnippetCompileUnit(classCode);
        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerResults results = provider.CompileAssemblyFromDom(compileParams, code);
        foreach(var type in results.CompiledAssembly)
        {
              // Your analysis go here
        }

Update: In VS2015 you could use the new C# compiler (AKA Roslyn) to do the same, for example:
var root = (CompilationUnitSyntax)tree.GetRoot();
var compilation = CSharpCompilation.Create("HelloTDN")
            .AddReferences(references: new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly) })
            .AddSyntaxTrees(tree);
var model = compilation.GetSemanticModel(tree);
var nameInfo = model.GetSymbolInfo(root.Usings[0].Name);
var systemSymbol = (INamespaceSymbol)nameInfo.Symbol;
foreach (var ns in systemSymbol.GetNamespaceMembers())
{
   Console.WriteLine(ns.Name);
}

A: Your main goal is to master the basics of formal languages. A good start-up might be found here. This article describes the way to use Irony on the sample of a grammar of a simple numeric calculator.
Suppose you want to parse a certain file containing C# code the path to which you know:
private void ParseForLongMethods(string path)
    {
        _parser = new Parser(new CSharpGrammar());
        if (_parser == null || !_parser.Language.CanParse()) return;
        _parseTree = null;
        GC.Collect(); //to avoid disruption of perf times with occasional collections
        _parser.Context.SetOption(ParseOptions.TraceParser, true);
        try
        {
            string contents = File.ReadAllText(path);
            _parser.Parse(contents);//, "<source>");
        }
        catch (Exception ex)
        {
        }
        finally
        {
            _parseTree = _parser.Context.CurrentParseTree;
            TraverseParseTree();
        }
    }

And here is the traversal method itself with counting some info in the nodes. Actually this code counts the number of statements in every method of the class. If you have any question you are always welcome to ask me
 private void TraverseParseTree()
        {
            if (_parseTree == null) return;
            ParseNodeRec(_parseTree.Root);
        }
        private void ParseNodeRec(ParseTreeNode node)
        {
            if (node == null) return;
            string functionName = "";
            if (node.ToString().CompareTo("class_declaration") == 0)
            {
                ParseTreeNode tmpNode = node.ChildNodes[2];
                currentClass = tmpNode.AstNode.ToString();
            }
            if (node.ToString().CompareTo("method_declaration") == 0)
            {
                foreach (var child in node.ChildNodes)
                {
                    if (child.ToString().CompareTo("qual_name_with_targs") == 0)
                    {
                        ParseTreeNode tmpNode = child.ChildNodes[0];
                        while (tmpNode.ChildNodes.Count != 0)
                        { tmpNode = tmpNode.ChildNodes[0]; }
                        functionName = tmpNode.AstNode.ToString();
                    }
                    if (child.ToString().CompareTo("method_body") == 0)  //method_declaration
                    {
                        int statementsCount = FindStatements(child);
                        //Register bad smell
                        if (statementsCount>(((LongMethodsOptions)this.Options).MaxMethodLength))
                        {
                            //function.StartPoint.Line
                            int functionLine = GetLine(functionName);
                            foundSmells.Add(new BadSmellRegistry(name, functionLine,currentFile,currentProject,currentSolution,false));
                        }
                    }
                }
            }
            foreach (var child in node.ChildNodes)
            { ParseNodeRec(child); }
        }


text:
Q: Prove that $f(a)f(b)<0$ Let $f:[a,b]\to\Bbb R$ a continous and differentiable function such that $f''(x)>0$ and $F$ is primitive. Prove that this equation
$$\frac{F(x)-F(a)}{x-a}-\frac{F(x)-F(b)}{x-b}+\frac{1}{2}(b-a)f'(x)=0.$$
has at least one solution
I know from the propriety of Darboux that I can solve the problem by proving $f(a)f(b)<0$ but I do not know how to prove it.


text:
Q: complex query about combining data from two tables Recently I had the following request. There are two tables.
-- lots of items
declare @items table(id varchar(10), pieces integer)
-- boxes
declare @boxes table(num varchar(10), capacity integer)

insert @items(id, pieces)
select 'l1', 5
union all select 'l2', 12
union all select 'l3', 8

insert @boxes(num, capacity)
select 'o1',2
union all select 'o2', 8
union all select 'o3', 2
union all select 'o4', 5
union all select 'o5', 9
union all select 'o6', 5

-- list all pairs of items-boxes. So that item will be put in what order
-- example: o1-l1, o2-l1, o2-l2, o3-l2, ...

Please let me explain it imperative way:
There are two tables. One with items another with boxes. We need to put all items into boxes the following way:
We take first item l1 and first box o1. Item l1 has 5 pieces and box o1  capacity is 2. We can only put maximum 2 pieces into the box o1. So we create first row:
o1-l1

We have filled the box o1. moving to the next box o2. It has the capacity of 8 and we have item l1 which has 3 pieces left. Putting the left pieces of l1 into the box o2 and so we create the second record:
o2-l1

We have put all the pieces of the item l1 into the boxes. Moving to the next item l2. It has the 12 pieces. And we have 5 capacity left in box o2 . So we are putting 5 pieces of l2 into o2 and creating the next record:
o2-l2

Then we are taking the next box in order and creating the following record:
o3-l2

And this way we are generating the rows till we "put" all item pieces into the boxes.
The resulting query should be something like:
o1-l1
o2-l1
o2-l2
o3-l2
...

It could be solved imperative way in T-SQL with the CURSOR and stuff, which is not good performance-wise. Is there any SQL query that could generate the desired output?

A: Ilya Sh, I couldn't quite verify if your own answer to your question was correct. But here is my approach.
Originally I thought this could be solved with a recursive query, but that's where all the boxes are equal in size and guaranteed to be bigger than the items, and the items are indivisible but vary in size (so that the only decision in relation to each item is whether it can be packed in the current box, or has to go in the next box).
In this case, we have groups of items (i.e. a row specifying an item type and a quantity) in which the items are equal in size but the groups are divisible, and each item group may therefore be spread over a number of boxes, and each box may contain parts of a number of itemgroups, in a many-to-many relationship between boxes and itemgroups.
My thinking is that each box, according to its capacity, has a number of individual "slots" (i.e. a volume of space) that can receive individual items.
The way I've approached the solution is to employ a "numbers table" to expand the quantities of each box/item group into individual box-slots and individual items - one row per box-slot and one row per item. On my machine I have a table called zx_numbers - but I've included code below that, for illustrative purposes, eliminates the dependency on this table.
Once we have normalised the data in this way - by expanding boxes into their individual slots, and expanding the item groups and summary quantities into individual items - each box slot and item in the entire batch is numbered sequentially, and then the two are simply joined on that sequence number.
I've used an FULL OUTER JOIN to preserve unmatched slots/items. This gives us a very general and adaptable solution to the problem, which we can then process further in a variety of ways to get the specific data we want (in this case, just a summary of box-itemgroup combinations).
The way I've written the query currently, boxes with unfilled space (or itemgroups that leave a remainder after all boxes have been fully filled) are left in the results, and placed at the end, but these can be filtered if not required.
WITH
item_groups(item_group_id, group_qty) AS
(
    select 'l1', 5
    union all select 'l2', 12
    union all select 'l3', 8
    --union all select 'l4', 8
)

,boxes(box_id, capacity) AS
(
    select 'o1',2
    union all select 'o2', 8
    union all select 'o3', 2
    union all select 'o4', 5
    union all select 'o5', 9
    union all select 'o6', 5
)

,zx_numbers(zx_number) AS
(
    --SELECT * FROM dbo.zx_numbers

    --I have a dedicated numbers table on my machine, but I've substituted a
    --manual sequence generator for the purposes of a self-contained demonstration
    SELECT
        (ones.n) + (10 * tens.n) + (100 * hundreds.n) AS zx_number

    FROM --range 0 to 999
         (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) AS ones(n)
        ,(VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) AS tens(n)
        ,(VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) AS hundreds(n)
)

,items AS
(
    SELECT
        item_groups.*
        ,zx_number AS group_item_number
        ,ROW_NUMBER() OVER (ORDER BY item_group_id, zx_number) AS batch_item_number

    FROM
        item_groups

    INNER JOIN
        zx_numbers
        ON (zx_number BETWEEN 1 AND item_groups.group_qty)
)

,box_slots AS
(
    SELECT
        boxes.*
        ,zx_number AS box_slot_number
        ,ROW_NUMBER() OVER (ORDER BY box_id, zx_number) AS batch_slot_number

    FROM
        boxes

    INNER JOIN
        zx_numbers
        ON (zx_number BETWEEN 1 AND boxes.capacity)
)

,box_item_matches AS
(
    SELECT
        COALESCE(bxsl.batch_slot_number, itms.batch_item_number) AS slot_number

        ,bxsl.box_id
        ,bxsl.capacity
        ,bxsl.box_slot_number

        ,itms.item_group_id
        ,itms.group_qty
        ,itms.group_item_number

    FROM
        box_slots AS bxsl

    FULL OUTER JOIN
        items AS itms
        ON (bxsl.batch_slot_number = itms.batch_item_number)
)

--SELECT * FROM box_item_matches

SELECT
    box_id
    ,item_group_id

FROM
    box_item_matches

GROUP BY
    box_id, item_group_id

ORDER BY
    IIF(box_id IS NULL OR item_group_id IS NULL, 1, 0) --i.e. NULLS LAST
    ,box_id
    ,item_group_id


text:
Q: Correct way to post file to Laravel server using Angular 8 I am trying to post an array of files along with some other data to a laravel server using angular. The file information gets set on the angular side and File object is there when the data is posted. However if I just return the request, the File data has been removed and I get a empty array. The rest of my data is fine though.
My service code:
storeChecklistAnswers(checklistAnswers: ChecklistAnswersModel) {
        return this.http
            .post<any>(
                `${environment.apiUrl}/checklist/answers/store`,
                checklistAnswers,
                {
                    reportProgress: true,
                    headers: new HttpHeaders().append(
                        'enctype',
                        'multipart/form-data'
                    )
                }
            )
            .pipe(
                catchError(error => {
                    console.log(error);
                    let errors;
                    if (error.error.errors) {
                        errors = {
                            message: error.message,
                            errors: Object.values(error.error.errors)
                        };
                    } else if (error.error.message) {
                        errors = {
                            message: error.error.message
                        };
                    } else {
                        errors = {
                            message:
                                'An unknown error has occured. Please refresh the application'
                        };
                    }
                    return throwError(errors);
                }),
                tap(resultData => {
                    return resultData;
                })
            );
    }

In my controller
return response()->json([
            'data' => $request->all()
        ]);

The data before it is posted:
images: Array(1)
0:
file: File
name: "292588.jpg"
lastModified: 1568349822014
lastModifiedDate: Fri Sep 13 2019 06:43:42 GMT+0200 (South Africa Standard Time) {}
webkitRelativePath: ""
size: 282431
type: "image/jpeg"
__proto__: File

The actual response
images: Array(1)
0:
file: []

I have tried to remove the headers as suggested in some SO answers, but I get the same result
I have also checked file_uploads, upload_max_filesize, post_max_size in php.ini.
I am running out of ideas. Please could someone point me in the right direction. I am not sure why I cant post the file?

A: You can try something like this.
Also as @Akram Wahid suggested make sure you have included csrf token.
And regarding file post see below code sample.
Your angular template

Choose File

            <form (ngSubmit)="onSubmit()">

                    <input type="file" name="image"  />

                    <button class="btn btn-primary">Submit</button>

            </form>

Your angular component file
export class AppComponent {

    fileData = null;
    ngOnInit() {
    }

    fileProgress(fileInput: any) {
        this.fileData = <File>fileInput.target.files[0];
    }

    onSubmit() {
        const formData = new FormData();
        formData.append('file', this.fileData);
        this.http.post('url/to/your/api', formData, {
            reportProgress: true,
            observe: 'events'
        })
        .subscribe(events => {
            if(events.type == HttpEventType.UploadProgress) {
                console.log('Upload progress: ', Math.round(events.loaded / events.total * 100) + '%');
            } else if(events.type === HttpEventType.Response) {
                console.log(events);
            }
        })
  }
}


text:
Q: Alterar posição do marker do google maps ao clicar Estou querendo alterar a posição do marcador do maps ao clicar na tela do Smartphone, no meu código em vez de alterar a posição ele cria vários marcadores.

abaixo o codigo da main activity
package com.t2ti.localizacao;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    private double latitude;
    private double longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        latitude = getIntent().getDoubleExtra("latitude", 0);
        longitude = getIntent().getDoubleExtra("longitude", 0);

        setUpMapIfNeeded();

    }

    @Override
    protected void onResume() {
        super.onResume();
        //setUpMapIfNeeded();
        //configura o zoom do mapa
        LatLng local = new LatLng(latitude, longitude);
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(local, 15);
        mMap.animateCamera(update);

        mMap .setOnMapClickListener( new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick (LatLng latLng) {
                MarkerOptions options = new MarkerOptions() ;
                options.position( latLng ) ;
                mMap .addMarker( options ) ;

                //mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker"));
            }
        });

    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     *

     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     *

     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     *

     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker"));
    }

}

A: Consegui colocando a função clear da variável GoogleMap mMap no inicio do método onclick do map.
exemplo abaixo:
  mMap .setOnMapClickListener( new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick (LatLng latLng) {
            //função clear
            mMap.clear();
            MarkerOptions options = new MarkerOptions() ;
            options.position( latLng ) ;
            mMap .addMarker( options ) ;

            //mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker"));
        }
    });

A: Você deve usar a CameraUpdate para fazer esses movimentos programáticos do mapa.
Para fazer isso, primeiro calcule os limites de todos os marcadores da seguinte forma:
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
    builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();

Em seguida, obtenha um objeto de movimento usando a factory CameraUpdateFactory
int padding = 0; // deslocamento das bordas do mapa em pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);

Finalmente mova o mapa:
googleMap.moveCamera(cu);

Ou se você quiser uma animação:
googleMap.animateCamera(cu);


text:
Q: Embedding Image Editor in ADF page My requirement is that I shall be able to render an image in ADF page as well as can scale the rendered image, edit it, rotate in as necessary.
Does ORACLE ADF gives me out of the box support for that.
Note: I want to use something like this for image editing
http://jdevadf.oracle.com/adf-richclient-demo/faces/components/hierarchyViewer.jspx#%2Fcomponents%2FrichTextEditor.jspx

A: There is nothing like that in ADF.
You'll have to write your own component using a lot of Javascript to handle all that functionality.

A: There is nothing like that in ADF.
BUT you can use one of numerous jQuery plugins to address your needs.


text:
Q: Python RegEx - How do I form a regex that contains a hyphen inside a word I need a regular expression to match "/page-2" or "/page-3" as part of a bigger URL such as http://domain.com/articles/page-number
So far, I have tried these combinations:
'/page-\d'
'/page-\d'
'\b/page-\d\b'
Please note, I am using the regex as part of the rules in the start_urls section in a Scrapy project. Any suggestions much appreciated. Here's a code snippet:
class NdtvXoloNewsItem(CrawlSpider):
    name = "ndtvxolonews"
    allowed_domains = ["http://gadgets.ndtv.com/tags/"]
    start_urls = ["http://gadgets.ndtv.com/tags/xolo/articles"]
    rules = [Rule(LinkExtractor(allow=['\b/page\-\d\b']))]

A: rules = [Rule(LinkExtractor(allow=[r'/page-\d+\b']))]

This should do it for you.

A: allowed_domains should be just the domain name. You can filter to a specific path by including the start of the URL in the RegEx
class NdtvXoloNewsItem(CrawlSpider):
    name = "ndtvxolonews"
    allowed_domains = ["gadgets.ndtv.com"]
    start_urls = ["http://gadgets.ndtv.com/tags/xolo/articles"]
    rules = [Rule(LinkExtractor(allow=['http://gadgets.ndtv.com/tags/.*/page\-\d+']))]


text:
Q: how is this survey made? Does anyone know how this survey is made? And how something like it can be created?
I know it's made with Flash but how do they export the results to a shopping cart? Have a client that would like something created similar to this.
Thanks
www.vitaminid com

A: While you fill out the form the selected answers are stored in Flash.  When you click submit at the end of the survey the Flash movie generates XML in the form:
<Survey Status="1" NavPosition="">
  <UserInfo Name="sberry2a"/>
  <Questions>
    <Q QId="1" TypeId="1" Answer="1"/>
    <Q QId="2" TypeId="3" Answer="02/1979"/>
    <Q QId="3" TypeId="3" Answer="67"/>
    <Q QId="4" TypeId="4" Answer="180"/>
    <Q QId="5" TypeId="1" Answer="2"/>
    <Q QId="6" TypeId="1" Answer=""/>
    <Q QId="7" TypeId="1" Answer=""/>
    <Q QId="8" TypeId="3" Answer="3"/>
    <Q QId="9" TypeId="3" Answer="2"/>
    <Q QId="10" TypeId="3" Answer="3"/>
    ...
    etc
    ...
  </Questions>
</Survey>

This XML gets posted to http://www.vitaminid.com/webapp/wcs/stores/servlet/GetSurveyResult?storeId=201&flash=true which is most likely a Java servlet that parses the XML and based on the results makes recomendations.
Does that answer your question?


text:
Q: Adding static files at runtime in Spring I have a Java Spring Application and I need to serve some static content, so I use the well documented approach as described in e.g. https://www.baeldung.com/spring-mvc-static-resources. I create a folder src/main/resources/static, I add a file test.json. I build and run the app, and I can access localhost:8080/test.json
But if I want to add another file, e.g. test2.json I need to restart the server in order for the app to serve it.
Is there a way to "force a new file search" and circumvent the caching so that I can add files at runtime without writing a new Controller?
Performance doesn't matter to me in this case.

A: My recommendation would be to add your dynamic files to the a location on the filesystem, and then add a custom resource handler.
@Configuration
public class WebConfig implements WebMvcConfigurer {

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry resourceHandlerRegistry) {
     resourceHandlerRegistry.addResourceHandler("/fs_resources/**")
       .addResourceLocations("file:///my/path/where/i/keep/stuff")
       .setCachePeriod(0);
   }
}


text:
Q: Are there English letter frequency charts based on the assumed age of the speaker/reader? Has anyone done work to construct letter frequency charts based on the assumed age of the reader/speaker, and also spoken word vs written text?
One would expect that letter usage would be different in books targeted at (for example) a 3rd grader vs a college student.  Also, people often write differently than they speak.
My first grade daughter loves the show "Pokemon".  In that show the Pokemon characters only speak sounds that are made from pieces of their name.  For example a Pikachu pokemon only speaks words made from combinations of the sounds "Pi", "Ka", and "Chu".  She thought it would be cool to make a real Pikachu language.  And I think its a good opportunity to teach her about encoding schemes.
The obvious choice is encoding letters of the alphabet using these three sounds.  Ideally one would want the length of the words to be minimized.  We have three sounds, therefore a ternary Huffman code based on an English letter frequency chart would provide an optimal code.
I have seen many charts (like this one) ...
http://pi.math.cornell.edu/~mec/2003-2004/cryptography/subs/frequencies.html
Based on that chart, here is the code I came up with so far.

... but this chart is based on generic data and therefore wouldn't be optimal in terms of the words a first grader would choose to speak.
This would be a spoken language only, so there is no need to encode special symbols or different letter cases.  I am only interested in the frequency of English letters A-Z.
The ideal table would come from research based on recordings of spoken interactions of elementary school children in the United States (preferably first grade).  But if that's not available then tables based on books targeted at those age ranges would be the next best choice.


text:
Q: Why don't I have permission to use WorldEdit? I'm trying to install WorldEdit, and I've done the following:

*

*Gotten the craftbukkit JAR,

*run it, stopped it,

*replaced world with my save from single,

*run again, stopped again,

*copied WorldEdit.jar into plugins,

*tried //hpos1 and other WorldEdit commands.

I get the following error:

You don't have permission to do this

What causes this? (I'm on a Mac, if that's a factor)

A: Due to the nature of worldedit, worldedit requires you to specify permissions, either the build in, or by using a permissions plugin
Worldedit uses the WEPIF (WorldEdit Permissions Interoperability Framework) to handle permissions.
If you're not using a permissions plugin, the easiest way is using Flat file permissions which allows you to simply give yourself all permissions by editing two files in the root of your server (same location as bukkit itself):
perms_groups.txt
admins:*

perms_users.txt
sk89q:admins:*

(replace sk89q with your username)
There's a list of permissions, on the Worldedit Wiki which can help you if you want to further specify permissions

A: I realize this is a very old thread but for those players who still need help I will offer my limited experience.
Recently the bukkit commands have changed to include minecraft commands that basically have the same permissions but are preceded with minecraft instead of bukkit. For example:
  - bukkit.command.op
becomes

*

*minecraft.command.op

and so on.
I had the same problem described above and solved it by adding all the minecraft.commands to my perms. I use Groupmanager.
I found this information at:
http://wiki.bukkit.org/CraftBukkit_Commands
The new perms are listed under Mojang Permission on the spreadsheet.
I suspect bukkit is being phased out to be replaced by a Microsoft system under the heading of Mojang.
Regardless, I no longer get the dreaded fail message. :)

A: Man this took me so long to figure out. I'm using Paper minecraft server and what I needed to do was add this to my permissions.yml:
server.basics:
       description: Basic permissions for my server.
       default: true
       children:
              worldedit.*: true


text:
Q: Laravel/Ajax DELETE: "Call to a member function delete() on null" As the title says, I am getting an error when I try to delete my data using laravel/ajax and the function inside the controller:

Controller:
public function destroy($category_id) {
    $category_delete = HmsBbrCategory::find($category_id);
    $category_delete->delete();
    return response()->json([
        'status'=>200,
        'message'=>'Category Deleted!',
    ]);

}

Form & Ajax:
`delete_category` is the id that opens the delete modal and `delete_category_btn` is the button that will delete the data.

<button type="submit" class="btn btn-primary btn-block delete_category_btn">Yes</button>
<button type="button" value="${cat.category_id}" class="delete_category btn btn-outline-secondary"> Delete</button>

        $(document).on('click', '.delete_category', function (e) {
            e.preventDefault();
            //click this button(delete_category) to get the value(category_id)
            var cat_id = $(this).val();
            // alert(cat_id);
            $('#delete_cat_id').val(cat_id);
            $('#deleteCategoryModal').modal('show');
        });
        $(document).on('click', '.delete_category_btn', function (e) {
            e.preventDefault();
            var cat_id = $('#delete_cat_id').val();
            // alert(cat_id);
            //token taken from laravel documentation
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $.ajax({
                type: "DELETE",
                url: "/clinical/bbr-category-configuration-delete/"+cat_id,
                dataType: "dataType",
                success: function (response){
                    // console.log(response);
                    $('#category_notif').addClass('alert alert-success');
                    $('#category_notif').text(response.message);
                    $('#deleteCategoryModal').modal('hide');
                }
            });
        });

Route:
Route::delete('/bbr-category-configuration-delete/{category_id}', [BBRCategoryConfigurationController::class,'destroy']);

Things to note:

*

*I went ahead and showed the category_id inside the modal to prove that the table is getting retrieved.

the the second ajax function for the delete button: $(document).on('click', '.delete_category_btn', function (e), I also tried to show the id using alert(cat_id); to also prove that the id is still getting recognized inside the modal:

Even if category_id is present, inspecting the page after attempting to delete still shows:
message: "Call to a member function delete() on null"

What can I do to resolve this? thanks for any help.

A: $category_delete object is null. Maybe you are sending a wrong $category_id. If you check that the category exists before delete you avoid that error.
public function destroy($category_id) {
    $category_delete = HmsBbrCategory::find($category_id);

    if($category_delete) {
        $category_delete->delete();
        return response()->json([
            'status'=>200,
            'message'=>'Category Deleted!',
        ]);
    }

    return response()->json([
        'status'=>404,
        'message'=>'Category Not Found!',
    ]);
}


text:
Q: CakePHP 3 - Cache query keyed by full SQL statement Using this answer I tried added caching to a query that is particularly slow.
This query has fixed selected fields and limits but three components can differ between different users: the where statement on the table itself, on filters on a joined table and on filters on a second joined table.
So I filter data on the main table and two joined ones.
For caching to work I need to incorporate the filtered conditions into the cache-key. How can I extract all the find filters, including on joins, for this purpose?
If I use $q->clause('where'), like in the linked suggestion, I only get the filter on the main table, not the joins. And $q->clause('join') is empty.
$query = $this->Regions->find('veryComplicatedFinder')
    ->cache(function (\Cake\ORM\Query $q)
            {
                debug($q->clause('where'));
                return 'test123';
            }, 'queries');

I figured I might just use the entire SQL statement. However, $q->sql() results in something like:

'SELECT ... FROM regions Regions INNER JOIN chains Chains ON
(Chains.id in (:c0,:c1,:c2) AND Chains.id = (Regions.chain_id)) LEFT
JOIN stores Stores ON (Stores.type in (:c388) AND Stores.type in
(:c389) AND Regions.id = (Stores.region_id)) LEFT JOIN sales Sales ON
Stores.id = (Sales.store_id) WHERE (Regions.shape &&
ST_MakeEnvelope(51.5,5,52,5.5,4326)) GROUP BY Regions.id  LIMIT 2000'

It seems the binding parameters are not included.

A: Joins for containments are built lazily
If the join clause is empty, then you're probably using containments, ie the contain(), *joinWith(), matching(), and/or notMatching() methods.
Joins of containments will only be added to the query object's join clause when the query is being compiled, until then they live in the eager loader, with their query builder callbacks not yet evaluated. So while you can obtain them like this:
// contain()
$contain = $query->getEagerLoader()->getContain();

// *joinWith()/matching()/notMatching()
$matching = $query->getEagerLoader()->getMatching();

the conditions haven't yet been applied anywhere.
Obtaining bindings
That being said, if you'd wanted to evaluate the whole query, then you could access the bound values via the value binder, like this:
$sql = $query->sql();
$bindings = $query->getValueBinder()->bindings();

Building cache keys in finders
One approach you might want to consider is partially shifting the cache key responsibility into the finder, ie building cache keys in your finders where you have all the required information at hand, and setting them on the query object to evaluate/use in other places.
It could look something like this:
public function findVeryComplicatedFinder(\Cake\ORM\Query $query)
{
    $cacheKey = '';

    if ($abc) {
        $cacheKey .= 'abc';
        $query->leftJoinWith('Abc', function () {
            // ...
        });
    }

    if ($xyz) {
        $cacheKey .= 'xyz';
        $query->innerJoinWith('Xyz', function () {
            // ...
        });
    }

    // ...

    $query->applyOptions([
        'veryComplicatedFinderCacheKey' => $cacheKey
    ]);

    return $query;
}

In your main query object's cache() callback you could then read that option and use it to build the final cache key, something along the lines of this:
$query = $this->Regions
    ->find('veryComplicatedFinder')
    ->cache(
        function (\Cake\ORM\Query $query) {
            $options = $query->getOptions();

            $cacheKey =
                'mainQueryCachKeyBasedOnWhateverYouRequire' .
                $options['veryComplicatedFinderCacheKey'];

            return $cacheKey;
        },
        'queries'
    );


text:
Q: When down-sizing my website, one of my a tags starts to get hidden and a horizontal scroll bar appears This is my first website and i'm doing it for a project at school nut i've got a couple of problems. First, when resizing my website one of my buttons starts to disappear for some reason. Secondly, my background color disappears when going below 992px of width. This project is due this week and this is the last part. Anyways, here is my code, the classes, ids and text are in french but the actual code is in english.The image that doesn't appear is supposed to be 2000px by 391px

@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@100;200;300;400;500;600;700;800;900&display=swap');
:root {
  --ming: #16697A;
  --pacific-blue: #489FB5;
  --middle-blue: #82C0CC;
  --isabelline: #EDE7E3;
  --orange-peel: #FFA62B;
  --white: #FFFFFF;
  --black: #000000;
}

* {
  box-sizing: border-box;
}

html {
  font: 400 100%/150% Montserrat, Arial, Helvetica, sans-serif;
  color: var(--white);
}

@media screen and (min-width:768px) {
  html {
    font-size: 100%;
    line-height: 150%;
  }
}

body {
  margin: 0;
}

#entete,
#pied-page {
  background: var(--pacific-blue);
  color: var(--white);
}

#entete {
  padding: 5%;
}

@media screen and (min-width:768px) {
  #entete {
    padding: 5% 5% 0;
  }
}

@media screen and (min-width:992px) {
  #entete {
    position: sticky;
    top: 0;
    left: 0;
    z-index: 2;
    padding: 0;
  }
}

@media screen and (min-width:992px) {
  .wrapper-navigation {
    display: flex;
    align-items: flex-end;
    max-width: 1400px;
    margin: 0 auto;
  }
  #logo,
  #menu {
    flex: 0 0 50%;
  }
  #logo {
    padding: 3% 0% 3% 5%;
  }
}

#pied-page * {
  color: white;
}

nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

#menu {
  margin-top: 1rem;
}

#menu ul li a {
  color: inherit;
  text-decoration: none;
  text-transform: uppercase;
  display: block;
  padding: .5rem 1rem;
  border-bottom: 0.063rem solid #fff;
  font-weight: 600;
  transition: all .3s ease;
}

#menu ul li a:hover,
#menu ul li a:focus {
  color: rgba(255, 255, 255, .5);
}

#menu ul li a span {
  font-weight: 400;
}

#menu ul li:last-child a {
  border-bottom: none;
}

@media screen and (min-width:768px) {
  #menu ul {
    display: flex;
  }
  #menu ul li {
    padding-top: .5rem;
  }
  #menu ul li a {
    border-bottom: none;
    line-height: 1.125rem;
  }
  #menu ul li a span {
    display: block;
  }
  #menu ul li.active {
    background: white;
    border-top-left-radius: 1rem;
    border-top-right-radius: 1rem;
  }
  #menu ul li.active a {
    color: var(--pacific-blue);
  }
}

Introduction au site

Doge Cheems

Spiderman meme

Clash Royale

Informations importantes

A: Your media queries need to have larger values.

@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@100;200;300;400;500;600;700;800;900&display=swap');
:root {
  --ming: #16697A;
  --pacific-blue: #489FB5;
  --middle-blue: #82C0CC;
  --isabelline: #EDE7E3;
  --orange-peel: #FFA62B;
  --white: #FFFFFF;
  --black: #000000;
}

* {
  box-sizing: border-box;
}

html {
  font: 400 100%/150% Montserrat, Arial, Helvetica, sans-serif;
  color: var(--white);
}

@media screen and (min-width:1328px) {
  html {
    font-size: 100%;
    line-height: 150%;
  }
}

body {
  margin: 0;
}

#entete,
#pied-page {
  background: var(--pacific-blue);
  color: var(--white);
}

#entete {
  padding: 5%;
}

@media screen and (min-width:768px) {
  #entete {
    padding: 5% 5% 0;
  }
}

@media screen and (min-width:1328px) {
  #entete {
    position: sticky;
    top: 0;
    left: 0;
    z-index: 2;
    padding: 0;
  }
}

@media screen and (min-width:1328px) {
  .wrapper-navigation {
    display: flex;
    align-items: flex-end;
    max-width: 1400px;
    margin: 0 auto;
  }
  #logo,
  #menu {
    flex: 0 0 50%;
  }
  #logo {
    padding: 3% 0% 3% 5%;
  }
}

#pied-page * {
  color: white;
}

nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

#menu {
  margin-top: 1rem;
}

#menu ul li a {
  color: inherit;
  text-decoration: none;
  text-transform: uppercase;
  display: block;
  padding: .5rem 1rem;
  border-bottom: 0.063rem solid #fff;
  font-weight: 600;
  transition: all .3s ease;
}

#menu ul li a:hover,
#menu ul li a:focus {
  color: rgba(255, 255, 255, .5);
}

#menu ul li a span {
  font-weight: 400;
}

#menu ul li:last-child a {
  border-bottom: none;
}

@media screen and (min-width:768px) {
  #menu ul {
    display: flex;
  }
  #menu ul li {
    padding-top: .5rem;
  }
  #menu ul li a {
    border-bottom: none;
    line-height: 1.125rem;
  }
  #menu ul li a span {
    display: block;
  }
  #menu ul li.active {
    background: white;
    border-top-left-radius: 1rem;
    border-top-right-radius: 1rem;
  }
  #menu ul li.active a {
    color: var(--pacific-blue);
  }
}

Introduction au site

Doge Cheems

Spiderman meme

Clash Royale

Informations importantes


text:
Q: Leaping frog algorithm I need your help with a riddle,
I need to find the best algorithm to catch a frog,
The frog is on the Natural numbers, it begins at point L, each time it goes K Leaps right (means if it was at point X, now it is at point x+k), we don't know what is L and each time that we try to catch it and miss, it goes k steps more... (We also don't know what is k),
How can I find the best algorithm to always catch it?
I though I can just go and jump for eternity but I guess it's not a good answer...
Thanks for helping...

A: The frog is on one of a countable set of possible trajectories, indexed by the pair $(L,k)$, where $L$ denotes its starting point and $k$ its "speed."  For each possibility, you can compute where it will be on the $n$th attempt to catch it (namely $L+(n-1)k$).  So simply list the possible trajectories, and on the $n$th attempt go to where the $n$th trajectory predicts the frog to be.

A: The position at instant $n$ is $\;x(n)=L+nk$.
If there is no known upper bound on $k$ and $L$ you may simply try all the values of $(L,K)$ in $\mathbb{N}\times \mathbb{N}$ starting at the origin and with the constraints $L+k=C$ with $C$ increasing once the diagonal was handled i.e. try the couples (for $n=0,1,2,3,\cdots$) :
$$(0,0),(0,1),(1,0),(0,2),(1,1),(2,0),(0,3),(1,3)\cdots$$
(the path being the same than in the Cantor proof of equivalence between $\mathbb{Q}$ and $\mathbb{N}$)
Of course at instant $n$ you'll have to search at $x(n)=L+nk$.


text:
Q: How do I get the tally of items in a list based on a another list using python? I want to tally the items in a list. I use the following:
from collections import Counter
list1 = ['a', 'b','a', 'c', 'c', 'a', 'b', 'b']
tally_items = Counter(list1)

But in the list it's possible not all the unique items I want appear.
For example, list1 has 'a', 'b', 'c' but I want 'a', 'b', 'c', 'd', 'e'.
I could use something like this:
list0 = ['a', 'b', 'c', 'd', 'e']
tally_items = [list1.count(i) for i in list0]

Are there any other ways ?

A: An instance of Counter will already return 0 for any key that does not explicitly exist. So in the above example:
list1 = ['a', 'b','a', 'c', 'c', 'a', 'b', 'b']
tally_items = Counter(list1)
print tally_items['d'] # prints 0

If you want to explicitly have these keys, you create a counter with all of the keys initialized to 0:
tally_list = Counter()
for key in ['a', 'b', 'c', 'd', 'e']:
    tally_list[key] = 0

Then you can update it with the list of actual items:
tally_list.update(list1)
print tally_list # prints Counter({'a': 3, 'b': 3, 'c': 2, 'e': 0, 'd': 0})


text:
Q: Django select query with limited fields I want to select a object with just one return field. I can do it using values. But the problem is when not using values it returns an object and when using values it returns a dictionary. Any reason for this difference. And is there a way I can get a return of objects with just one or two fields.
     obj=UserProfile.objects.get(pk=1)
     obj=UserProfile.objects.values('my_field').get(pk=1)

A: You can use only() method and  enter fields which you need
obj=UserProfile.objects.only('my_field').get(pk=1)


text:
Q: Opening new applications/windows in currently active screen - macOS Big Sur I have a dual monitor setup with my MacBook, and when I'm using my second screen with active dock (spotlight shows up on it), opening apps bring them up in the MacBook's screen instead of my secondary monitor.
Is there any way to get an app or window to open in the currently active screen? Either by mouse position or dock activation?
Using macOS Big Sur 11.4, M1 Macbook Pro


text:
Q: Is it possible to have multiple levels on a gantt chart in R Shiny? I have created a simple Shiny App where I am graphing the timeline of building a house. I was wondering if it were possible to have a gantt chart where you could plot the level you want and the level right below it.
For example, in this app if the user chose Level One, then the gantt chart would show the timeline of Level One AND the timeline of Level Two.
Then of course if they chose Level Two they would be shown Level Two AND Level Three.
My code pasted below contains the basic app.
As always any and all help is appreciated. Thank you.
library(tidyverse)
library(shiny)
library(shinydashboard)
library(shinyWidgets)

project_data <- tibble(
  Project_Name = c("Dream House", "Main Floor", "Living Room", "Kitchen"),
  Project_Level = c("One", "Two", "Three", "Three"),
  Start = c("01-01-2022", "03-01-2022", "03-01-2022", "06-01-2022"),
  Finish = c("12-01-2022", "08-01-2022", "06-01-2022", "08-01-2022")
)

ui <- fluidPage(
  selectInput(inputId = "project_level",
              label = "Project Level",
              multiple = FALSE,
              choices = unique(project_data$Project_Level),
              selected = "One"
              ),
  plotOutput("timeline", height = 500),

)

server <- function(input, output, session) {

  timeline_data <- reactive({
    project_data %>%
      filter(Project_Level %in% input$project_level)

  })

  output$timeline <- renderPlot({

    timeline_data() %>%
      ggplot(aes(xmin = Start, xmax = Finish,
                 color = Project_Name, y = Project_Name)) +
      geom_linerange(size = 8, position = position_dodge(width = 0.5)) +
      labs(
        x = "Start and Finish Dates",
        y = "Project Name") +
      theme_minimal(base_size = 16)

  })

}

shinyApp(ui, server)


text:
Q: What is Object k? public V put(K key, V value) {
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}

I am trying to understand the HashMap implemintation. I understood everything except this line - Object k;
Please, explain how this Object k appears??

A: In that implementation of a HashMap, the data structure was backed by an array of linked lists of entries. These entries have a key and a value.
That variable k is used to store the key for each entry while iterating over the linked list bucket. If it's found to be equal (reference and then value equality) to the key with which you're trying to insert a value, then that value replaces the old.


text:
Q: Let $ X $ be compact and let $f: X \rightarrow Y$ be a local homeomorphism. Show that for any point $y \in Y$, $f^{-1}(y)$ is a finite set. PROBLEM: Let $ X $ be compact and let $f: X \rightarrow Y$ be a local homeomorphism. Show that for any point $y \in Y$, $f^{-1}(y)$ is a finite set.
I was trying out this problem from Massey, but got stuck.
MY ATTEMPT: My thought was to pick an open neighborhood $U_i$ of arbitrary but fixed $y_i \in Y$, then show that $U_i$ is evenly covered by $f$, so $f^{-1}(U_i)$ is a disjoint union of open sets in $X$,
$f^{-1}(U_i) = \underset{\alpha \in X} \amalg V_{{y_i}_{\alpha}} $ such that for each $\alpha$, $f|_{V_{{y_i}_{\alpha}}}: V_{{y_i}_{\alpha}} \rightarrow U$ is a surjective homeomorphism. This also implies $f$ is a covering map.
Then $X = \underset{\alpha \in X}\amalg V_{{y_1}_{\alpha}} \cup \underset{\alpha \in X}\amalg V_{{y_2}_{\alpha}} ...$, which is an open covering. Since $X$ is compact, that means there is a finite subcover. Specifically, this means only finitely many $f^{−1}(U_i) = \underset{\alpha \in X} \amalg V_{{y_i}_{\alpha}}$ cover $f^{-1}(y_i)$ for each $y_i$.
Does this outline seem correct? I have a problem at the beginning, not knowing how to use the local homeomorphism to show that $f$ evenly covers $U_i$, and I'm not sure about if my conclusion appropriately proves the statement.

A: Without going into evenly covered maps etc., it might be simpler: Suppose for some $y$, $F_y := f^{-1}[\{y\}]$ is infinite. As $X$ is compact (in fact we need only countably compact) there is a limit point $p$ of $F_y$. But if $U$ is a neighbourhood of $p$ such that $f \restriction U: U \to f[U]$ is a homeomorphism, then $U$ contains at least 2 (in fact infinitely many; here I'm assuming $X$ is $T_1$ as well) points of $F_y$, which makes $f$ not even injective on $U$, as both map to $y$ under $f$.
So in fact, for a locally injective map $f$ on a countably compact $T_1$ space, all fibres are finite.
So if some $F_y$ were infinite, by compactness it would have an $\omega$-accumulation point $x \in X$. If $O$ were the witnessing neighbourhood of $x$ wrt local homeomorphism, a contradiction to injectivity ensues; no sep. axioms needed.

A: Let me suggest a strategy.  The problem is to show that every fiber $f^{-1}(y)$ is finite when $f$ is a local homeomorphism; if it's unclear what the role of this hypothesis is, try asking the same question without it: is it necessarily true that the fiber of any map $f$ is finite, when $X$ is compact?  Obviously not: you could have, as a really silly example, the map $f \colon X \to \{\text{pt}\}$, whose fiber is all of $X$, which doesn't need to be finite.  Though if such an $f$ were a local homeomorphism, then $X$ would be a discrete union of points and a discrete, compact space is finite.  So the claim holds for maps from a compact space to a point.
It's crucial to recall the proof of the last claim there.  If $D$ is a discrete compact space, then each point is, in itself, an open set (discreteness), and $D$ is the union of its points, so is a finite union of some of them (compactness).  But since each singleton set contains only one point, this accounts for only finitely many points, so $D$ is finite.
So if we want to execute the same argument on a general map $f \colon X \to Y$, we need to cover the fiber $f^{-1}(y)$ by open sets each of which contains only one point of the fiber, and somehow argue by compactness that there is a finite subcover.  Note that (without some kind of separation axiom) the fiber itself may not be compact, but this is not an impediment as one can always enlarge the covering by adding irrelevant open sets.
All the ingredients for this are in your outlined proof.

A: I think you might be trying to prove too much here. As you say, there's a problem at the beginning. Even if $f$ is a covering map, it's not necessarily true that it evenly covers every neighborhood of $y_i$. So you would have to come up with a way to pick a small enough $U_i$. For what it's worth, I'm not sure how to do that, or even if it's possible.
There's a simpler approach, which is to forget about $y$ for a minute and apply the compactness of $X$ right away. If you can get a finite cover of $X$ on which $f$ is nice enough, it will make everything much easier...

A: I don't have a full answer for you but here are some thoughts.  If f-1(Ui) is a disjoint union of open sets in X, that does not mean that they are a cover for X (and we don't care).  They are a subset of X and by definition none of them are compact (being open).  So I think you should close them, forming a compact set V ⊂ X (V is compact because X is).  Now you can conclude as you say that a finite set of the f-1Ui) cover V.
Since you obviously can form all the f-1(Ui) you want, the problem comes down to whether you can make them disjoint.  For this I think you need to pay attention both to the fact that f is a local homeomorphism, and  that it is (therefore) continuous.  The former rules out cases such as X = [0,1] on the real line and f(x) ≡ 1.  The latter allows you to choose
each Ui so that yi is unique.
You need to do this so that f-1(yi) is unique in f-1(Ui), which I think it will be because f is 1-1; otherwise having a finite cover doesn't necessarily imply a finite number of f-1(yi).
I still don't quite see how to get from there to disjoint, but I think that plus the compactness of X should be the right approach.
I'll keep thinking about it.  If you solve it, please post the solution so I can see it.

Further thought: First just to be sure we are clear, I am using the set {yi} to be all the y's which have the same value.  Following up on the idea of there being a Ui for each yi which contains only one yi, it must be that there is a there is a constant a > 0 such that the "radius" of each Ui can be a while still preserving just one yi for each Ui.   Otherwise there is a convergent sequence of yi which goes to say yc.  I believe that f-1 would not be continuous at yc, so that f would not be a homeomorphism. (I haven't quite shown this, but maybe you can do that).
Having gotten that far, maybe the disjointness of f-1(Ui) will follow.


text:
Q: Why are the navigation links stacked when using inline-block? I want the navigation links: "about", "resume", "projects", and "contact" to line up horizontally in the navigation bar.
Why does this only work with display: inline-block?
It is my understanding that inline-block boxes allows these elements to be side by side. I need it to be inline-block instead of just inline because I want to size it to the nav bar's exact height.
What am I doing wrong?

Here is the HTML and CSS for my nav:

/* ----------------------------NAVIGATION SECTION-------------------------------- */

.headerContainer {
  background-color: #000;
  text-align: center;
  height:60px;
  margin-left: 600px;
  margin-right: 600px;
  font-family: 'Monda', sans-serif;
  text-transform: uppercase;
  position: fixed;
}

nav {
  padding-left: 1000px;
  padding-right: 1000px;
}

nav li {
  list-style: none;
  display: inline-block;
  background-color: #000;
  height: 40px;
  padding-top: 20px;
  width: 120px;
}

nav li:hover {
  background-color: #e1e1e1;
  -webkit-text-stroke: 2px #000;
}

a:link {
  color: #fff;
  text-decoration: none;
  margin-left:25px;
  margin-right:25px;
}

a:visited {
  color: #fff;
}

a:focus {
  color: #fff;
}

a:hover {

}

a:active {
  color: #fff;
}

About

Resume

Projects

Contact

A: You have a massive amount of padding inside the nav element.

nav {
  padding-left: 1000px;
  padding-right: 1000px;
}

This doesn't leave very much space for the content to render in.
The li elements are laid out side by side until they run out of space, at which point they word wrap.
If you zoom out, you'll see the fit in one line.
If you look at the live demo in your question, with the very narrow frame, you will see everything squashed to the side.

Don't set a huge padding on the nav element.


text:
Q: New to Apache: what exacty should my conf file contain for a basic forward proxy? I was hoping to get some help setting up Apache as a forward proxy, primarily just to know how it's done and for learning. I've found countless examples that look a lot like this:
<IfModule mod_proxy>
ProxyRequests On
ProxyVia On
<Proxy *>
  Allow from all
</Proxy>

But I'm not sure what to do with that information. What happens in the rest of the conf file? Do I just append it to the bottom and activate all the proxy modules? And if so, why isn't working when I try it with Firefox?
Thanks

A: This config should work, you'll probably want to drop any sites/virtual hosts that it's actually trying to serve up if it's going to be a dedicated proxy.
Check what settings the Apache config has for Listen directives - the proxy will need to be using one of those ports (this will be either in the main apache conf file, or a separate ports.conf file).
Along those same lines, what url did you place in the firefox proxy configuration?


text:
Q: Running Visual Studio Code from the CLI in Linux I've downloaded and "installed" VSCode for Linux. I have placed the app in /home/Christian/Apps/VSCode/ and symlinked the executable to /usr/bin/code.
When I use this method to start Code it hijacks the terminal (expected I guess) and also dumps a lot of STDERR stuff at the same time.

If I redirect STDERR to a file, for example like
code 2> ~/.logs/VSCode-`date +%Y%m%d%H%M%S.log` &

Then I can get it to give me back my prompt, and it's silent (logging everything to the filename I gave it).
I was thinking of making this an alias, but then I realized I can't inject arguments ($1 $2 $3) in an alias. And I usually want to start code with code filename.js or code ..
What is the correct way to launch an application like this "in the background"?

A: Instead of making a symlink to the executable, create a bash script like this:
#!/bin/bash
/path/to/VSCode/Code "$@" 2>/dev/null &


text:
Q: Producing a 3D Net from a 3d inspired image Producing a 3D Net from a 2D Image
I'm trying to find the volume of the illustration, I've taken reference from the medium size of a strawberry's diameter, I've applied this scale to the remaining sides of the shape. As for the image, it's the only reference I have to work from. Ultimately I'm trying to produce a net, the  image has been created / drawn to resemble a '3d' looking object, I'm trying to convert the image back into a 3d net. And to find the volume of the illustrated components Cake Sponge, Icing, Strawberry, Cake Filling Etc.


text:
Q: How do I send fetched data from chrome extension background script to content script? Once an event is triggered in my content script, it send a message request to the background script and waits for a response.
content.js
chrome.runtime.sendMessage({ userId: userId }, function (response) {
    console.log(response);
});

background.js:
chrome.runtime.onMessage.addListener(function (
  request,
  sender,
  sendResponse
) {
  const userId = request.userId;
  if (userId) {
    fetchData(userId).then((data) => {
      sendResponse({ response: data });
    });
    return true;
  }
});

I've tried async/await, moving the "return true" to outside the if statement, but in my content script the response is either undefined (even though fetchData returns the correct data), no response, or the error "the message port closed before a response was received extension".
The flow I want is:

*

*content.js sends a message request to background.js and waits for a response

*background.js receives the message

*background.js fetches data via http request

*background.js sends resolved promise back to content.js

*content.js receives response and logs the data

A: The issue turned out to be changing tabs in the popup before the response was received. I fixed it by moving the command to change the popup tab (window.open()) to be in the response, after processing the response data.


text:
Q: Poco c++ How to read "text" data type from PostgreSQL DB? I am executing a database (PostgreSQL) query.
Сomment column has "text" data type.
SELECT Comment FROM table WHERE id = 1;
RecordSet result = query->execute("");
bool more = result .moveFirst();

while (more)
{
  std::string comment = result["Comment"].convert<std::string>());
  or
  std::string comment = result["Comment"].extract<std::string>());

  more = result.moveNext();
}

I get an exception

Poco::SQL::UnknownTypeException

How can I read a field without changing the database data type?

A: I figured out
Poco::SQL::MetaColumn::ColumnDataType type = result.columnType("Comment");
type is Poco::SQL::MetaColumn::ColumnDataType::FDT_CLOB
Poco::SQL::CLOB comment = response["Comment"].extract<Poco::SQL::CLOB>();
Look the same https://github.com/pocoproject/poco/issues/2566 if POCO version < 1.9.1


text:
Q: Cloudformation script taskset cannot pull image from ECR In my current setup I use cloudformation to setup an environment. All the steps configured so far seem to work, except for the taskset. I use an image on AWS ECR repo to launch a Fargate instance, which is put into a new cluster with a service.
When I create the stack all the steps succeed but the creation of the service is stuck in "CREATE_IN_PROGRESS" forever. When I look at the created service and more specifically the task, I found that cloudformation was unable to fetch the image. The error is as follows:

STOPPED (CannotPullContainerError: Error response from daem)

Now when I manually try to an instance using the same image on said cluster, it works just fine. After some googling I came upon certain solutions. I have implemented all of them, such as:

*

*Create a network with security groups which allows outgoing traffic to all destinations

*Set the flag AssignPublicIp to 'ENABLED' in the awsvpc configuration

*Set the user execution role to the same one I used in manual creation

Note that the task does get created and it does receive a public and private IP address. Also, I have tried to throw away the ECR instance and create a new one with a new name (and of course tagged and pushed the image).
The following snippet is my service and taskset definition (renamed some sensitive info):
    "MyVPC": {
        "Type": "AWS::EC2::VPC",
        "Properties": {
            "CidrBlock": "10.0.1.0/16",
            "Tags": [
                {"Key":"Name", "Value":"MyVPC"
                }
            ]
        },
    },
    "MyInternetGateway" : {
      "Type" : "AWS::EC2::InternetGateway",
          "Properties" : {
          }
       },
    "MySubPublic": {
        "Type": "AWS::EC2::Subnet",
        "Properties": {
            "AvailabilityZone": "eu-central-1a",
            "CidrBlock": "10.0.1.0/28",
            "MapPublicIpOnLaunch": true,
            "VpcId": {
                "Ref": "MyVPC"
            }
        },
        "DependsOn": "MyInternetGateway"
    },
    "MySecGroup":
            {
      "Type" : "AWS::EC2::SecurityGroup",
      "Properties" : {
          "GroupDescription" : "My security group for all incoming and outgoing.",
          "GroupName" : "MySecGroup",
          "SecurityGroupEgress" : [ {
              "CidrIp" : "0.0.0.0/0",
              "Description" : "Allow machine to reach internet.",
              "FromPort" : -1,
              "IpProtocol" : -1,
              "ToPort" : -1
            } ],
          "SecurityGroupIngress" : [ {
              "CidrIp" : "0.0.0.0/0",
              "Description" : "Allow machine to be reached from the entire internet.",
              "FromPort" : -1,
              "IpProtocol" : -1,
              "ToPort" : -1
            } ],
          "VpcId" : {"Ref": "MyVPC"}
        },
        "DependsOn": "MyVPC"
    },
    "MyCluster": {
        "Type": "AWS::ECS::Cluster",
        "Properties": {
            "ClusterName": "MyCluster"
        },
        "DependsOn": [
            "MyVPC"
        ]
    },
    "MyDockerTask": {
        "Type": "AWS::ECS::TaskDefinition",
        "Properties": {
            "ContainerDefinitions": [
                {
                    "Cpu": 512,
                    "Image": "<NRHERE>.dkr.ecr.eu-central-1.amazonaws.com/mysqs",
                    "Memory": 1024,
                    "MemoryReservation": 1024,
                    "Name": "MyContainer"
                }
            ],
            "Cpu": "512",
            "ExecutionRoleArn": "arn:aws:iam::<NRHERE>:role/ecsTaskExecutionRole",
            "Family": "MyFam",
            "Memory": "1024",
            "NetworkMode": "awsvpc",
            "RequiresCompatibilities": [
                "FARGATE",
                "EC2"
            ],
            "TaskRoleArn": "arn:aws:iam::<NRHERE>:role/ecsTaskExecutionRole"
        },
    },
    "MyService": {
      "Type" : "AWS::ECS::Service",
      "Properties" : {
          "Cluster" : {"Fn::GetAtt": ["MyCluster", "Arn"]},
          "DesiredCount" : 1,
          "LaunchType" : "FARGATE",
          "NetworkConfiguration" : {
             "AwsvpcConfiguration" : {
                  "AssignPublicIp" : "ENABLED",
                  "SecurityGroups" : [ {"Fn::GetAtt": ["MySecGroup", "GroupId"]} ],
                  "Subnets" : [ {"Ref": "MySubPublic"}]
                }
          },
          "SchedulingStrategy" : "REPLICA",
          "ServiceName" : "MyService",
          "TaskDefinition": {"Ref": "MyDockerTask"}
        },
        "DependsOn": "MySubPublic"
    },
    "MyTaskSet": {
        "Type": "AWS::ECS::TaskSet",
        "Properties": {
            "Cluster": {
                "Ref": "MyCluster"
            },
            "LaunchType": "FARGATE",
            "NetworkConfiguration" : {
                 "AwsvpcConfiguration" : {
                      "AssignPublicIp" : "ENABLED",
                      "SecurityGroups" : [ {"Fn::GetAtt": ["MySecGroup", "GroupId"]} ],
                      "Subnets" : [ {"Ref": "MySubPublic"}]
                    }
              },
            "Service": {"Ref": "MyService"},
            "TaskDefinition": {
                "Ref": "MyDockerTask"
            }
        },
        "DependsOn": [
            "MyCluster"
        ]
    },

None of the above provided the solution. I'm open to any suggestion/solution

A: From the CFN template provided I can conclude that MySubPublic has no  internet access.
Specifically, I see that you are creating the following VPC-related resources:

*

*AWS::EC2::VPC

*AWS::EC2::InternetGateway

*AWS::EC2::Subnet

*AWS::EC2::SecurityGroup
However, the problem is the lack of:

*

*AWS::EC2::VPCGatewayAttachment which will connect the InternetGateway to your VPC

*Definitions of AWS::EC2::RouteTable and AWS::EC2::Route which will be used to make your MySubPublic route traffic to the AWS::EC2::InternetGateway.
General steps to enable internet access in a subnet are described here:

Attach an internet gateway to your VPC.
Add a route to your subnet's route table that directs internet-bound traffic to the internet gateway. If a subnet is
  associated with a route table that has a route to an internet gateway,
  it's known as a public subnet. If a subnet is associated with a route
  table that does not have a route to an internet gateway, it's known as
  a private subnet.
Ensure that instances in your subnet have a globally unique IP address (public IPv4 address, Elastic IP address, or IPv6 address).
Ensure that your network access control lists and security group rules allow the relevant traffic to flow to and from your instance.


text:
Q: How to find the LCM of numbers with exponents? I would like to know if there is a mathematical approach to finding the LCM of
$(29^{17} +2 , 29^{17} -1)$?
Even if we would rearrange it to a fraction of the form
$\frac{(29^{17} +2)\cdot (29^{17} -1)}{gcd(29^{17} +2 , 29^{17} -1)}$ ,
we would still need to calculate the GCD. Is there a way using number theory that I am missing? I dont want to resort to using calculator to figure this one out.
If its not possible to find the LCM, is it possible to find just it's unit digit?

A: Let do this:
$$(29^{17}+2,29^{17}-1) = (29^{17}+2 - 29^{17}+1, 29^{17}-1) = (3,29^{17}-1)$$
$$29^{17}-1 \overset{3}{\equiv} (-1)^{17}-1 \overset{3}{\equiv} -1-1 \overset{3}{\equiv} -2$$
$$\Longrightarrow (29^{17}+2,29^{17}-1) = (3,29^{17}-1) = (3,-2) = 1$$
Now you can continue your way.

A: Hint $\, \gcd(a\!+\!3,a) =\!\!\!\!\overbrace{ \gcd(3,a)}^{\large \gcd(\color{#c00}{3,\,29^{17}-1})}\!\!\! $ by subtractive Euclid algorithm (subtract least from largest arg)
Finally note that: $\bmod \color{#c00}{3}\!:\ \underbrace{\color{#c00}{29^{17}\!-\!1}\equiv (-1)^{17}\!-1}_{\textstyle{29\ \equiv\ -1\ \ }}\equiv -2\not\equiv 0\ $ by the Congruence Power Rule.


text:
Q: Can't scroll to dynamic element Hey guys I'm having some issues scrolling to a an element that's dynamically created. You click on a search button, AJAX does its thing and updates the content. I have some code to dynamically find the ID and scroll to it. I am able to get the ID but I can't scroll to it. So far I have the code:
to_Scroll = $(this).closest('tr').attr('id');
$('html, body').animate({
    scrollTop: $(to_Scroll).offset().top
}, 2000);

Which seems to work when I put it in the console with hard coded data. But doing it dynamically yields no results and no errors. Any help would be greatly appreciated
Below is some code which is done before I animate and scroll to an element:
dateChange(blah, blah2, blah3);
to_Scroll = $(this).closest('tr').attr('id');
    $('html, body').animate({
        scrollTop: $(to_Scroll).offset().top
    }, 2000);

function dateChange(dateInput, nGuests, vName){
    var promises = [];
    var promise = $.ajax({
          url: "/blah.asp?blah="+blah+"&blah2="+blah2+"&blah3="+blah3,
          dataType:"html",
          success: function(data){
              table.html(data);
          }
        });
    promises.push(promise);

$.when.apply($, promises).done(function() {
    $( "#boatContent" ).removeClass( "loading" ); //Everything is done, remove loading gif
    //do other stuff
}

A: to use ID again from attr you need to add # to it
$(document).ready(function(){
    var to_Scroll = $(this).closest('tr').attr('id');
    $('html, body').animate({
        scrollTop: $( '#' + to_Scroll).offset().top
    }, 2000);
});


text:
Q: AttributeError: 'bytes' object has no attribute 'encode' I am trying to build a user login system and I have successfully built the user register page, but when I try to login I get the error below. I am using flask, python3.6 and pymongo.
This is the error: AttributeError: 'bytes' object has no attribute 'encode'
please help.

Traceback (most recent call last):
    File "C:\Users\elvis\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2309, in call
      return self.wsgi_app(environ, start_response)
    File "C:\Users\elvis\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2295, in wsgi_app
      response = self.handle_exception(e)
    File "C:\Users\elvis\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1741, in handle_exception
      reraise(exc_type, exc_value, tb)
    File "C:\Users\elvis\AppData\Local\Programs\Python\Python36\lib\site-packages\flask_compat.py", line 35, in reraise
      raise value
    File "C:\Users\elvis\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2292, in wsgi_app
      response = self.full_dispatch_request()
    File "C:\Users\elvis\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
      rv = self.handle_user_exception(e)
    File "C:\Users\elvis\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
      reraise(exc_type, exc_value, tb)
    File "C:\Users\elvis\AppData\Local\Programs\Python\Python36\lib\site-packages\flask_compat.py", line 35, in reraise
      raise value
    File "C:\Users\elvis\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
      rv = self.dispatch_request()
    File "C:\Users\elvis\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1799, in dispatch_request
      return self.view_functionsrule.endpoint
    File "C:\Users\elvis\Desktop\flask apps\testmon\even\app\run.py", line 30, in login
      if bcrypt.hashpw(request.form['pass'].encode('utf-8'), login_user['password']) == login_user['password'].encode('utf-8'):
  AttributeError: 'bytes' object has no attribute 'encode'

(a screenshot of the error page)

A: Only give the Password=" "
Example:
pdf = pdfplumber.open(f,password='')

A: The last line of the traceback
login_user['password']) == login_user['password'].encode('utf-8'): AttributeError: 'bytes' object has no attribute 'encode'

Tells you that you are passing an object that is of type bytes, not a str.
So you are trying to invoke .encode() method on bytes object.
You need to check what is the login_user['password'] value, and either cast it to string by invoking decode() method on the bytes object login_user['password']).decode().encode('utf-8') or store a string value in this dictionary at the beginning.
From this traceback I can see, that what you're doing doesn't make much sense, but unless you can share the code, there is not much more I can tell.
EDIT:
login if bcrypt.hashpw(request.form['pass'].encode('utf-8'), login_user['password']) == login_user['password'].encode('utf-8'): AttributeError: 'bytes' object has no attribute 'encode'

You can also probably remove the .endoce('utf-8') from the login_user['password'] part, and it could work as well.